fix: 收敛受控 CLI 调用与诊断

This commit is contained in:
Codex
2026-07-12 17:08:00 +02:00
parent 00c60a17cd
commit 2a80e08a40
13 changed files with 168 additions and 35 deletions
+15 -4
View File
@@ -190,8 +190,12 @@ const SSH_OPERATION_HELP: Record<SshHelpScope, SshOperationHelp> = {
},
exec: {
group: "process",
description: "在 k3s workload route 中运行进程,并可显式透传 stdin 或指定容器内 cwd。",
usage: ["trans <provider>:k3s:<namespace>:<workload>[:<container>] exec [--cwd /path] [--stdin] -- <command> [args...]"],
description: "运行单个远端进程;host/workspace 的 cwd 写入 routek3s workload 用 --cwd 指定容器内目录。",
usage: [
"trans <provider>:/absolute/workspace exec <command> [args...]",
"trans <provider>:k3s:<namespace>:<workload>[:<container>] exec [--cwd /path] [--stdin] -- <command> [args...]",
],
notes: ["host/workspace 不接受 exec --cwd;改写 route,例如 trans D601:/workspace exec git status。"],
},
git: {
group: "process",
@@ -221,8 +225,9 @@ const SSH_OPERATION_HELP: Record<SshHelpScope, SshOperationHelp> = {
},
bash: {
group: "shell",
description: "仅在需要 pipefail、数组、[[ ]] 等 Bash 语法时执行远端 Bash。",
usage: ["trans <route> bash <<'BASH'", "trans <route> bash -- '<bash command>'"],
description: "仅在需要 pipefail、数组、[[ ]] 等 Bash 语法时执行远端 Bashcwd 由 route 选择。",
usage: ["trans <provider>:/absolute/workspace bash <<'BASH'", "trans <provider>:k3s:<namespace>:<workload>[/cwd] bash <<'BASH'", "trans <route> bash -- '<bash command>'"],
notes: ["host/workspace 不接受 bash --cwd;将绝对目录写入 route。"],
},
py: {
group: "shell",
@@ -327,6 +332,11 @@ export function sshHelp(scope: SshHelpScope | undefined = undefined): unknown {
"远端文本读取优先 cat/rg,修改优先 apply-patchupload/download 仅用于必要的二进制或生成物。",
"普通 trans 短连接上限保持 60s;长流程使用受控 submit-and-poll 入口。",
],
cwdSemantics: {
hostWorkspace: `${entrypoint} <provider>:/absolute/workspace exec|sh|bash ...`,
k3sWorkload: `${entrypoint} <provider>:k3s:<namespace>:<workload>[:<container>] exec --cwd /absolute/container/path -- <command>`,
rule: "host/workspace cwd 属于 routek3s 容器 cwd 可由 route 后缀或 exec --cwd 指定。",
},
};
}
@@ -343,6 +353,7 @@ export function renderSshHelpText(scope: SshHelpScope | undefined = undefined):
`patch: ${SSH_OPERATION_GROUPS.patch.join(" | ")}`,
`transfer: ${SSH_OPERATION_GROUPS.transfer.join(" | ")}`,
`scoped help: ${entrypoint} --help <operation>`,
`cwd: host/workspace uses <provider>:/absolute/workspace; k3s exec uses --cwd /absolute/container/path`,
"boundary: route only selects the target; use sh/bash/ps/cmd explicitly for shell syntax.",
].join("\n");
}
@@ -97,6 +97,7 @@ export function compactDiagnoseCodeAgentResult(value: unknown): Record<string, u
hwlabReadModel: source.hwlabReadModel ?? null,
http: compactDiagnoseHttp(source.http),
projectionLag: source.projectionLag ?? null,
outcome: source.outcome ?? null,
summary: source.summary ?? null,
rootCauseCandidates: asArray(source.rootCauseCandidates).slice(0, 3).map(compactRootCauseCandidate),
spanNameCounts: compactNameCounts(source.spanNameCounts, 6),
@@ -123,16 +123,33 @@ describe("diagnose-code-agent warm-session terminal classification", () => {
expect(first.payload.diagnosticTrace.traceId).not.toBe(second.payload.diagnosticTrace.traceId);
expect(first.payload.diagnosticTrace.traceparent).not.toBe(second.payload.diagnosticTrace.traceparent);
});
test("keeps durable completion authoritative while projection lag stays a nonblocking warning", () => {
const diagnosis = runFixture({ authorityAvailable: true, terminalSpan: false, projectionStale: true });
expect(diagnosis.status).toBe(0);
expect(diagnosis.payload.outcome).toEqual({
typed: "completed-with-projection-warning",
effectiveStatus: "completed",
authority: { kind: "agentrun-durable-command", status: "completed", source: "agentrun-authority" },
projection: { kind: "hwlab-read-model", status: "running", lag: "confirmed", warning: true, blocking: false },
mutation: false,
});
const compact = compactDiagnoseCodeAgentResult(diagnosis.payload);
const rendered = renderDiagnoseCodeAgentTable({ ok: true, target, options, query: {}, result: compact });
expect(rendered.renderedText).toContain("outcome=completed-with-projection-warning effectiveStatus=completed mutation=false");
expect(rendered.renderedText).toContain("durableAuthority kind=agentrun-durable-command status=completed");
expect(rendered.renderedText).toContain("projection kind=hwlab-read-model status=running lag=confirmed warning=true blocking=false");
});
});
function runFixture(input: { authorityAvailable: boolean; terminalSpan: boolean }): {
function runFixture(input: { authorityAvailable: boolean; terminalSpan: boolean; projectionStale?: boolean }): {
status: number | null;
payload: Record<string, any>;
calls: string;
} {
const directory = mkdtempSync(join(tmpdir(), "unidesk-otel-diagnose-"));
temporaryDirectories.push(directory);
writeFileSync(join(directory, "trace.json"), JSON.stringify(traceFixture(input.terminalSpan)));
writeFileSync(join(directory, "trace.json"), JSON.stringify(traceFixture(input.terminalSpan, input.projectionStale === true)));
writeFileSync(join(directory, "command.json"), JSON.stringify({ id: "cmd_second", state: "completed" }));
writeFileSync(join(directory, "result.json"), JSON.stringify({ ok: true, commandId: "cmd_second", status: "completed", commandState: "completed", terminalStatus: "completed" }));
writeFileSync(join(directory, "run-result.json"), JSON.stringify({ ok: true, commandId: "cmd_second", commandState: "completed", terminalStatus: "completed" }));
@@ -235,7 +252,7 @@ function callLines(calls: string): string[] {
return calls.split("\n").map((line) => line.trim()).filter(Boolean);
}
function traceFixture(terminalSpan: boolean): Record<string, unknown> {
function traceFixture(terminalSpan: boolean, projectionStale = false): Record<string, unknown> {
const common = [
attribute("traceId", "trc_warm_second"),
attribute("runId", "run_warm"),
@@ -244,11 +261,17 @@ function traceFixture(terminalSpan: boolean): Record<string, unknown> {
];
return {
batches: [
batch("hwlab-cloud-api", [span("provider_decision", [
...common,
attribute("agent.chat.provider_profile", "gpt.pika"),
attribute("agentRunRunnerNamespace", "agentrun-v02"),
])]),
batch("hwlab-cloud-api", [
span("provider_decision", [
...common,
attribute("agent.chat.provider_profile", "gpt.pika"),
attribute("agentRunRunnerNamespace", "agentrun-v02"),
]),
...(projectionStale ? [
span("trace_events_read", [...common, attribute("sourceEventCount", "6"), attribute("sinceSeq", "7")]),
span("turn_status_read", [...common, attribute("turnStatus", "running")]),
] : []),
]),
batch("agentrun-manager", [
span("command_created", common),
...(terminalSpan ? [span("runner_terminal.completed", [...common, attribute("terminalStatus", "completed"), attribute("eventType", "terminal_status")])] : []),
@@ -2023,10 +2023,10 @@ def root_cause_candidates(http_summary, agentrun, read_model, lag_summary, error
status_conflict = terminal_status_conflicts(agentrun.get("terminalStatus"), read_model_turn_status)
if status_conflict:
candidates.append({
"code": "otel_business_trace_terminal_conflict",
"label": "OTel terminal conflict",
"code": "projection_authority_terminal_conflict",
"label": "projection/authority terminal conflict",
"confidence": 0.86,
"summary": "Scoped AgentRun terminal status conflicts with HWLAB read-model turn status for the requested business trace; prefer the HWLAB read-model status for Workbench RCA and inspect OTel correlation leakage.",
"summary": "HWLAB projection conflicts with the scoped AgentRun durable authority; preserve the AgentRun terminal outcome and inspect projection correlation or lag.",
"evidence": {
"agentrunTerminalStatus": agentrun.get("terminalStatus"),
"hwlabReadModelTurnStatus": read_model_turn_status,
@@ -2502,16 +2502,16 @@ if http_summary.get("actorForbidden"):
read_model_turn_status = read_model.get("turnStatus")
agentrun_read_model_status_conflict = terminal_status_conflicts(terminal_status, read_model_turn_status)
if agentrun_read_model_status_conflict:
facts.append("OTel AgentRun terminal status conflicts with HWLAB read model")
if terminal_status in ("failed", "error", "timeout", "blocked", "cancelled") and not agentrun_read_model_status_conflict:
facts.append("HWLAB projection conflicts with AgentRun durable authority")
if terminal_status in ("failed", "error", "timeout", "blocked", "cancelled"):
failure_kind = agentrun.get("failureKind")
if failure_kind:
facts.append(f"AgentRun terminal failed ({failure_kind})")
else:
facts.append("AgentRun terminal failed")
if terminal_status == "completed" and not agentrun_read_model_status_conflict:
if terminal_status == "completed":
facts.append("AgentRun completed")
if (terminal_status in (None, "") or agentrun_read_model_status_conflict) and read_model_turn_status in ("completed", "failed", "error", "timeout", "blocked", "cancelled", "canceled"):
if terminal_status in (None, "") and read_model_turn_status in ("completed", "failed", "error", "timeout", "blocked", "cancelled", "canceled"):
facts.append("HWLAB read model terminal " + str(read_model_turn_status))
if lag.get("status") in ("confirmed", "suspected"):
facts.append("projection/read-model stale")
@@ -2552,6 +2552,30 @@ evidence = {
"idleWarningSpanCount": len(idle_warning_spans),
"idleWarningSpanTail": [tiny_span(item) for item in idle_warning_spans[-3:]],
}
projection_warning = lag.get("status") in ("confirmed", "suspected") or agentrun_read_model_status_conflict
effective_status = terminal_status if terminal_status not in (None, "") else read_model_turn_status
typed_outcome = "unknown"
if effective_status not in (None, ""):
typed_outcome = str(effective_status)
if projection_warning:
typed_outcome = typed_outcome + "-with-projection-warning"
outcome = {
"typed": typed_outcome,
"effectiveStatus": effective_status,
"authority": {
"kind": "agentrun-durable-command",
"status": terminal_status,
"source": agentrun.get("terminalSource"),
},
"projection": {
"kind": "hwlab-read-model",
"status": read_model_turn_status,
"lag": lag.get("status"),
"warning": projection_warning,
"blocking": False,
},
"mutation": False,
}
payload = {
"ok": trace_rc == 0 and len(spans) > 0,
"mapping": mapping,
@@ -2594,6 +2618,7 @@ payload = {
"actorForbidden": http_summary.get("actorForbidden"),
},
"projectionLag": lag,
"outcome": outcome,
"summary": summary,
"rootCauseCandidates": candidates,
"spanNameCounts": flat["spanNameCounts"][:12],
@@ -761,6 +761,9 @@ export function renderDiagnoseCodeAgentTable(input: {
const observedCommandId = textValue(identity?.commandId);
const observedSessionId = textValue(identity?.sessionId);
const observedRunnerJobId = textValue(identity?.runnerJobId);
const outcome = asPlainRecord(input.result.outcome);
const outcomeAuthority = asPlainRecord(outcome?.authority);
const outcomeProjection = asPlainRecord(outcome?.projection);
const lines = [
`platform-infra observability diagnose-code-agent (${input.ok ? "ok" : "not-ok"})`,
"",
@@ -792,6 +795,9 @@ export function renderDiagnoseCodeAgentTable(input: {
formatTable(["METHOD", "ROUTE", "STATUS", "COUNT"], httpRows.length > 0 ? httpRows : [["-", "-", "-", "-"]]),
"",
"Summary:",
` outcome=${textValue(outcome?.typed)} effectiveStatus=${textValue(outcome?.effectiveStatus)} mutation=${textValue(outcome?.mutation)}`,
` durableAuthority kind=${textValue(outcomeAuthority?.kind)} status=${textValue(outcomeAuthority?.status)} source=${textValue(outcomeAuthority?.source)}`,
` projection kind=${textValue(outcomeProjection?.kind)} status=${textValue(outcomeProjection?.status)} lag=${textValue(outcomeProjection?.lag)} warning=${textValue(outcomeProjection?.warning)} blocking=${textValue(outcomeProjection?.blocking)}`,
` target=${input.target.id} spanCount=${textValue(input.result.spanCount)} servicePath=${joinValues(input.result.servicePath, 60)}`,
` agentrun=${textValue(agentrun?.terminalStatus)} failureKind=${textValue(agentrun?.failureKind)} source=${textValue(agentrun?.terminalSource)} authority=${shortenEnd(JSON.stringify((asPlainRecord(agentrun?.authority) ?? {})), 120)}`,
` authorityQuery namespace=${textValue(agentrunAuthority?.namespace)} source=${textValue(agentrunAuthority?.namespaceSource)} ok=${textValue(agentrunAuthority?.ok)} commandState=${textValue(agentrunAuthority?.commandState)} terminal=${textValue(agentrunAuthority?.terminalStatus)}`,
+19 -1
View File
@@ -86,10 +86,11 @@ describe("ssh bounded progressive help", () => {
test("renders compact top-level and scoped help without dump fallback", () => {
const top = runTransHelp("--help");
expect(Buffer.byteLength(top, "utf8")).toBeLessThan(2_048);
expect(top.trim().split("\n")).toHaveLength(10);
expect(top.trim().split("\n")).toHaveLength(11);
expect(top).toContain("usage: trans <route> <operation>");
expect(top).toContain("transfer: upload | download");
expect(top).toContain("scoped help: trans --help <operation>");
expect(top).toContain("cwd: host/workspace uses <provider>:/absolute/workspace; k3s exec uses --cwd");
expect(top).not.toContain("outputTruncated");
expect(top).not.toContain("dump");
@@ -102,6 +103,10 @@ describe("ssh bounded progressive help", () => {
expect(applyPatch).toContain("usage: trans <route> apply-patch");
expect(applyPatch).not.toContain("outputTruncated");
const exec = runTransHelp("--help", "exec");
expect(exec).toContain("trans <provider>:/absolute/workspace exec <command>");
expect(exec).toContain("k3s:<namespace>:<workload>");
const download = runTransHelp("--help", "download");
expect(download.trim().split("\n").length).toBeLessThanOrEqual(8);
expect(download).toContain("TRANS HELP download");
@@ -159,4 +164,17 @@ describe("ssh bounded progressive help", () => {
expect(result.stdout).not.toContain("stack");
expect(result.stdout).not.toContain(" at ");
});
test("rejects the moved root entrypoint locally with one exact replacement", () => {
const result = spawnSync("bun", ["scripts/cli.ts", "trans", "NC01:/root/unidesk", "git", "status", "--short"], {
cwd: repoRoot,
env: { ...process.env, UNIDESK_TRANS_REPO_ROOT: repoRoot },
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toBe("");
expect(result.stdout).toContain("ERROR cli-input/trans-root-cli-entrypoint-moved");
expect(result.stdout).toContain("usage: trans NC01:/root/unidesk git status --short");
expect(result.stdout).not.toContain("stack");
});
});
+2 -1
View File
@@ -1372,11 +1372,12 @@ function writeChunkedStdin(stdin: NodeJS.WritableStream, input: string): void {
export async function runSsh(config: UniDeskConfig, providerId: string, args: string[]): Promise<number> {
const normalizedArgs = normalizeSshOperationArgs(args);
process.stderr.write(sshRouteSeparatorCompatibilityHint(args, normalizedArgs));
// 在选择或连接 transport 前完成解析,保证可预测的 route/operation 错误始终在本地失败。
const invocation = parseSshInvocation(providerId, normalizedArgs);
const plan = sshCaptureBackendPlan(config, process.env);
if (plan.backend === "remote-frontend-websocket" && plan.remoteHost !== null) {
return await runRemoteSsh(config, plan.remoteHost, providerId, normalizedArgs);
}
const invocation = parseSshInvocation(providerId, normalizedArgs);
const parsed = invocation.parsed;
const operationName = normalizedArgs[0] ?? "";
if (isSshFileTransferOperation(normalizedArgs)) {
+14
View File
@@ -214,6 +214,20 @@ describe("ssh windows fs read-only operations", () => {
});
describe("ssh direct argv boundaries and plane diagnostics", () => {
test("rejects host/workspace cwd options locally with an exact route replacement", () => {
try {
parseSshInvocation("NC01:/root/unidesk", ["exec", "--cwd", "/root/hwlab-v03", "--", "git", "status", "--short"]);
throw new Error("expected host cwd input error");
} catch (error) {
expect(error).toMatchObject({
code: "trans-host-cwd-belongs-in-route",
usage: "trans NC01:/root/hwlab-v03 'exec' '--' 'git' 'status' '--short'",
});
}
expect(() => parseSshInvocation("NC01:/root/unidesk", ["bash", "--cwd=/root/hwlab-v03"])).toThrow("cwd belongs in the route");
expect(() => parseSshInvocation("NC01:k3s:hwlab-v03:hwlab-cloud-api", ["exec", "--cwd", "/workspace", "--", "pwd"])).not.toThrow();
});
test("preserves a shell-formed argv token containing spaces and Chinese", () => {
const invocation = parseSshInvocation("G14-WSL:/mnt/d/Work/CONSTAR_workspace", [
"python3",
+22
View File
@@ -3,6 +3,7 @@ import { isSshFileTransferOperation } from "./ssh-file-transfer";
import { isWindowsFsReadOnlyOperation, windowsFsReadOnlyScript } from "./ssh-windows-fs";
import { remoteApplyPatchSource, remoteGlobSource, remoteSkillDiscoverSource } from "./ssh-remote-tools";
import { readTransHostProxyEnvRule, type TransHostProxyEnvRule } from "./trans-host-proxy";
import { CliInputError } from "./output";
export interface ParsedSshArgs {
remoteCommand: string | null;
@@ -406,10 +407,31 @@ export function parseSshInvocation(target: string, args: string[]): ParsedSshInv
if ((operationArgs[0] ?? "") === "k3s") {
throw new Error(`ssh k3s shorthand is unsupported; use route syntax instead: trans ${route.providerId}:k3s ${operationArgs.slice(1).join(" ")}`.trim());
}
rejectHostWorkspaceCwdOption(route, operationArgs);
const parsed = parseSshArgs(operationArgs, route.raw);
return { providerId: route.providerId, route, parsed: withTransHostEnvironment(route, parsed) };
}
function rejectHostWorkspaceCwdOption(route: ParsedSshRoute, args: string[]): void {
const operation = args[0] ?? "";
if (!new Set(["exec", "argv", "sh", "bash"]).has(operation)) return;
const cwdIndex = args.findIndex((arg) => arg === "--cwd" || arg === "--workdir" || arg.startsWith("--cwd=") || arg.startsWith("--workdir="));
if (cwdIndex < 0) return;
const option = args[cwdIndex] ?? "--cwd";
const inlineValue = option.includes("=") ? option.slice(option.indexOf("=") + 1) : null;
const cwd = inlineValue ?? args[cwdIndex + 1] ?? "<absolute-workspace>";
const consumed = inlineValue === null ? 2 : 1;
const remaining = [...args.slice(0, cwdIndex), ...args.slice(cwdIndex + consumed)];
const replacementRoute = cwd.startsWith("/") ? `${route.providerId}:${cwd}` : `${route.providerId}:/absolute/workspace`;
const replacement = `trans ${replacementRoute} ${remaining.map(shellQuote).join(" ")}`;
throw new CliInputError(`host/workspace ${operation} does not accept ${option.split("=", 1)[0]}; cwd belongs in the route`, {
code: "trans-host-cwd-belongs-in-route",
argument: option,
usage: replacement,
hint: "Use <provider>:/absolute/workspace for host cwd. Use exec --cwd only with a k3s workload route.",
});
}
export function parseSshRoute(target: string): ParsedSshRoute {
if (!target) throw new Error("ssh requires provider id, for example: trans D601");
const firstColon = target.indexOf(":");