Skip to content

Commit a2b2268

Browse files
committed
fix: retain evidence when legacy OpenCLI collect loses its response
1 parent 807801e commit a2b2268

8 files changed

Lines changed: 89 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ Notes:
200200
- Legacy HTTP argv dispatch accepts SDK-listed adapters and one subcommand. Root metadata, Browser sessions, external passthrough, repeated options, `--`, and tokens whose spacing or leading dash cannot be preserved are rejected before HTTP. Place positionals before options. Use local execution for commands that need the original argv. A deployment with its own adapter contract can use the explicit `OpenCliCollectRequest` API.
201201
- A collect timeout raises `OpenCliRemoteTimeoutException`. After dispatch to the HTTP transport, `isRemoteOutcomeUnknown()` is true. Collect does not automatically retry or follow redirects.
202202
- Inspect `getRemoteExecutionDetails()` on the result or on an exception’s `getPartialResult()` to distinguish HTTP status, Agent business status and the source of `items`. The legacy 0/1 returned by `getExitCode()` is synthetic. HTTP and protocol failure snapshots have no exit code. Accepted response text is available in those snapshots only when raw capture is enabled.
203+
- If a collect connection breaks before a complete response, the failure snapshot reports `TRANSPORT_FAILURE` and `isRemoteOutcomeUnknown()`. `getObservedHttpStatus()` is empty when no headers arrived. The snapshot has no CLI exit code or incomplete response body. Server-specific extensions require a verified Agent contract.
203204
- If your Agent accepts a credential header, configure `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`. Supply the complete header value. The Agent base URL must use HTTPS for credentials and contain no user info, query or fragment. The SDK sends the configured header on `/collect`. OAuth discovery and request signing are unsupported.
204205
- Parse previously captured CLI help with `OpenCliHelpParser.parse(stdout)`. The result retains the original text and reports whether the schema is available. Structured commands preserve placeholders and separate command, namespace, global and common options.
205206
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ cli.gemini().deepResearch("topic",
200200
- 旧版 HTTP argv 调用仅接收 SDK 清单中的适配器及其子命令。根命令、Browser 会话、外部程序透传、重复选项、`--` 以及无法保留边界空格或前导短横的参数会在发请求前被拒绝。位置参数应在选项前。需要原样传递 argv 时使用本地执行,已有自定义 Agent 契约时可用显式 `OpenCliCollectRequest` API。
201201
- 远程调用超时抛出 `OpenCliRemoteTimeoutException`。请求提交给 HTTP 传输后,`isRemoteOutcomeUnknown()` 为 true。客户端不会自动重试或跟随重定向。
202202
- 通过结果或异常的 `getPartialResult()` 调用 `getRemoteExecutionDetails()`,查看 HTTP 状态、Agent 业务状态和 `items` 的来源。`getExitCode()` 的 0/1 是兼容映射。HTTP 或协议失败快照没有退出码。仅在开启原文捕获时,失败快照才携带已通过字节上限检查的响应正文。
203+
- collect 连接在完整响应到达前中断时,失败快照标记 `TRANSPORT_FAILURE`,`isRemoteOutcomeUnknown()` 为 true。未收到响应头时,`getObservedHttpStatus()` 为空。快照不包含 CLI 退出码或不完整响应正文。服务端扩展须经过对应 Agent 契约验证。
203204
- Agent 支持认证请求头时,可调用 `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`,传入完整请求头值。认证须使用 HTTPS,Agent 基础地址须省略用户信息、查询参数和片段。SDK 只在 `/collect` 请求上发送已配置的认证头。OAuth 发现和请求签名尚不支持。
204205
- 对已采集的 CLI 帮助调用 `OpenCliHelpParser.parse(stdout)`,可读取结构化命令、占位符、不同作用域的选项和原文。纯文本、混合输出或无效结构会返回未知状态及原因。
205206
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。

‎openspec/changes/harden-opencli-remote-collect/specs/opencli-remote-collect/spec.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Legacy HTTP collect 边界与保真
22

3-
> Proposal specification. Status: DRAFT / NOT_IMPLEMENTED.
3+
> The declared legacy collect scope is verified on the feature branches. PR review and merge are pending.
44
55
## ADDED Requirements
66

‎openspec/changes/harden-opencli-remote-collect/tasks.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@
1212

1313
## 2. 最小适配修复
1414

15-
- [ ] 2.1 引入显式 legacy capability guard 和保真转换子集,避免无条件解析任意 argv。
15+
- [x] 2.1 引入显式 legacy capability guard 和保真转换子集,避免无条件解析任意 argv。
1616
- [x] 2.2 区分 HTTP、协议与命令失败,保留兼容退出码及其来源。见 OC-REMOTE-003/004 验证。
1717
- [x] 2.3 使 body/timeout 有界并实现可测试的显式 header 配置,保持 TLS。见 OC-REMOTE-005/006 验证。
1818

1919
## 3. 三线与安全
2020

2121
- [x] 3.1 验证凭据、URL query、正文和异常 cause 的默认诊断边界。见 OC-REMOTE-006 验证。
2222
- [x] 3.2 在三分支分别跑本地 HTTP fixture;记录旧 API 的行为收紧与迁移例子。见三线验证。
23-
- [ ] 3.3 未取得服务端契约的扩展仍标记 unsupported,不借此宣称远程全量兼容。
23+
- [x] 3.3 未取得服务端契约的扩展仍标记 unsupported,不借此宣称远程全量兼容。
2424

2525
## 证据交付模板(实施时填写)
2626

@@ -83,3 +83,12 @@ JDK 17 基线中,chunked 响应每 125 ms 持续发送数据,900 ms 的原
8383
| 21 | `85de78f4e847ac1c1ff73d855573954a5898e9ee` | 2178 | 92.52% |
8484

8585
这组测试覆盖可控 HTTP 和 HTTPS 服务端。真实 opencli-admin 部署的认证协议及扩展契约仍待验收。
86+
87+
88+
## C04 实施核对与中断结果
89+
90+
JDK 17 基线的两项新测试均失败。Agent 接收请求后断开以及发出 HTTP 200 后提前中断正文,都只得到无 partial result 的异常。修复后,异常类型保持兼容,partial result 标记 `TRANSPORT_FAILURE` 和远端结果未知。已观察的 HTTP 状态得以保留,未收到响应头时状态为空。没有 CLI 退出码或不完整正文,诊断导出也不显示未观察的 HTTP 状态。每种场景桩均只收到一次请求。
91+
92+
argv 入口继续限制为 SDK 已登记适配器和可保真转换的参数。测试同时检查正常映射和被拒绝的零请求路径。已验证范围为回环 legacy Agent DTO、显式请求头与 HTTP/TLS 传输。生产部署特有扩展与未经证实的认证协议保持 unsupported。
93+
94+
本分支以 `807801e785d5fa5ffd9607165f44ae0e1faa6e07` 为基线,使用 JDK 17 执行 `./mvnw -B -ntp -o -Dtest=OpenCliRemoteAgentHttpClientTest,OpenCliArgvToCollectParserTest,OpenCliArgvToCollectParserFullTest,OpenCliDiagnosticExportTest test`,退出码为 0。81 项实际执行,其中 56 项为 HTTP 客户端测试,零失败、零错误、零跳过。报告位于 `target/surefire-reports`。

‎src/main/java/io/github/easy4j/opencli/core/OpenCliDiagnosticExport.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ public static String export(OpenCliResult result, int maxBytes) {
3939
"success=" + result.isSuccess() + "\n",
4040
Objects.isNull(remote) ? "" : "exitCodeSource=" + remote.getExitCodeSource() + "\n",
4141
Objects.isNull(exitCode) ? "" : "exitCode=" + exitCode + "\n",
42-
Objects.isNull(remote) ? "" : "httpStatus=" + remote.getHttpStatus() + "\n",
42+
Objects.isNull(remote) || !remote.getObservedHttpStatus().isPresent()
43+
? "" : "httpStatus=" + remote.getHttpStatus() + "\n",
4344
characterCount("stdoutChars", result.getStdout()),
4445
characterCount("stderrChars", result.getStderr()),
4546
characterCount("rawHttpChars", result.getRemoteRawHttpBody())

‎src/main/java/io/github/easy4j/opencli/core/OpenCliRemoteExecutionDetails.java‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,37 @@
55
import lombok.Builder;
66
import lombok.Getter;
77

8-
/** Observable evidence from an HTTP response to a legacy collect request. */
8+
/** Observable evidence from a legacy HTTP collect attempt. */
99
@Getter
1010
@Builder
1111
public final class OpenCliRemoteExecutionDetails {
1212

1313
/** The layer that supplied the failed or successful result. */
14-
public enum Outcome { SUCCESS, COMMAND_FAILURE, HTTP_FAILURE, PROTOCOL_FAILURE }
14+
public enum Outcome { SUCCESS, COMMAND_FAILURE, HTTP_FAILURE, PROTOCOL_FAILURE, TRANSPORT_FAILURE }
1515

1616
/** Origin of the compatibility exit code on the associated result. */
1717
public enum ExitCodeSource { SYNTHETIC_COMPATIBILITY, UNAVAILABLE }
1818

1919
/** Origin of the items projected to stdout. */
2020
public enum ItemsSource { RESPONSE, ABSENT_DEFAULT, NULL_DEFAULT, UNAVAILABLE }
2121

22+
/** HTTP status observed in the response headers, or zero if unavailable. */
2223
private final int httpStatus;
2324
private final Outcome outcome;
2425
/** Null when a business status was unavailable or its envelope failed validation. */
2526
private final Boolean legacySuccess;
2627
private final ItemsSource itemsSource;
2728

29+
/** @return the observed HTTP status, or empty when no response headers arrived */
30+
public OptionalInt getObservedHttpStatus() {
31+
return httpStatus > 0 ? OptionalInt.of(httpStatus) : OptionalInt.empty();
32+
}
33+
34+
/** @return true if the HTTP exchange failed before a complete response was available */
35+
public boolean isRemoteOutcomeUnknown() {
36+
return outcome == Outcome.TRANSPORT_FAILURE;
37+
}
38+
2839
/** @return whether the associated 0/1 exit code is a mapping of the business status */
2940
public ExitCodeSource getExitCodeSource() {
3041
return Objects.isNull(legacySuccess) ? ExitCodeSource.UNAVAILABLE : ExitCodeSource.SYNTHETIC_COMPATIBILITY;

‎src/main/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClient.java‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,10 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
136136
.build());
137137

138138
ScheduledFuture<?> abort = DEADLINES.schedule(post::abort, deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
139+
int observedStatus = 0;
139140
try (CloseableHttpResponse response = client.execute(post)) {
140141
int status = response.getStatusLine().getStatusCode();
142+
observedStatus = status;
141143
Optional<String> body = readBoundedBody(response.getEntity(), maxResponseBytes);
142144
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
143145
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
@@ -156,12 +158,15 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
156158
throw failure("Failed to parse agent response", correlationId);
157159
} catch (SocketTimeoutException | ConnectTimeoutException e) {
158160
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
159-
} catch (IOException | IllegalArgumentException e) {
161+
} catch (IOException e) {
160162
if (post.isAborted() || deadline - System.nanoTime() <= 0) {
161163
throw new OpenCliRemoteTimeoutException(timeout, true, correlationId);
162164
}
163165
log.warn("Agent HTTP I/O failed correlationId={}", correlationId);
164-
throw failure("Agent HTTP I/O error", correlationId);
166+
throw new OpenCliExecutableFailureException("Agent HTTP I/O error correlationId=" + correlationId,
167+
null, failureSnapshot(observedStatus, Outcome.TRANSPORT_FAILURE, null));
168+
} catch (IllegalArgumentException e) {
169+
throw failure("Failed to interpret agent HTTP response", correlationId);
165170
} finally {
166171
abort.cancel(false);
167172
}

‎src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,6 +551,59 @@ void nullEnvelopeUsesSafeCorrelatedParseFailure() throws IOException {
551551
}
552552
}
553553

554+
@Test
555+
void disconnectAfterAcceptingCollectDoesNotReplayOrInventAnExit() throws IOException {
556+
try (JsonCollectStub stub = JsonCollectStub.start(HttpExchange::close);
557+
OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(baseProps(stub.port()))) {
558+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
559+
OpenCliExecutableFailureException failure = Assertions.assertThrows(
560+
OpenCliExecutableFailureException.class, () -> client.collect(request));
561+
Assertions.assertEquals(1, stub.requests());
562+
OpenCliResult partial = failure.getPartialResult();
563+
Assertions.assertNotNull(partial);
564+
Assertions.assertFalse(partial.isSuccess());
565+
Assertions.assertNull(partial.getExitCode());
566+
Assertions.assertNull(partial.getRemoteRawHttpBody());
567+
OpenCliRemoteExecutionDetails details = partial.getRemoteExecutionDetails();
568+
Assertions.assertEquals(Outcome.TRANSPORT_FAILURE, details.getOutcome());
569+
Assertions.assertTrue(details.isRemoteOutcomeUnknown());
570+
Assertions.assertFalse(details.getObservedHttpStatus().isPresent());
571+
Assertions.assertFalse(details.getObservedRemoteExitCode().isPresent());
572+
Assertions.assertFalse(OpenCliDiagnosticExport.export(partial, 512).contains("httpStatus="));
573+
Assertions.assertNull(failure.getCause());
574+
}
575+
}
576+
577+
@Test
578+
void truncatedResponseBodyRetainsOnlyObservedHttpStatus() throws IOException {
579+
try (JsonCollectStub stub = JsonCollectStub.start(exchange -> {
580+
exchange.sendResponseHeaders(200, 64);
581+
try (OutputStream body = exchange.getResponseBody()) {
582+
body.write('{');
583+
} finally {
584+
exchange.close();
585+
}
586+
})) {
587+
OpenCliProperties props = baseProps(stub.port());
588+
props.setRemoteCaptureRawHttpResponse(true);
589+
try (OpenCliRemoteAgentHttpClient client = new OpenCliRemoteAgentHttpClient(props)) {
590+
OpenCliCollectRequest request = OpenCliCollectRequest.builder().site("npm").command("search").build();
591+
OpenCliExecutableFailureException failure = Assertions.assertThrows(
592+
OpenCliExecutableFailureException.class, () -> client.collect(request));
593+
Assertions.assertEquals(1, stub.requests());
594+
OpenCliResult partial = failure.getPartialResult();
595+
Assertions.assertNotNull(partial);
596+
OpenCliRemoteExecutionDetails details = partial.getRemoteExecutionDetails();
597+
Assertions.assertEquals(Outcome.TRANSPORT_FAILURE, details.getOutcome());
598+
Assertions.assertTrue(details.isRemoteOutcomeUnknown());
599+
Assertions.assertEquals(200, details.getObservedHttpStatus().getAsInt());
600+
Assertions.assertFalse(details.getObservedRemoteExitCode().isPresent());
601+
Assertions.assertNull(partial.getExitCode());
602+
Assertions.assertNull(partial.getRemoteRawHttpBody());
603+
}
604+
}
605+
}
606+
554607
@Test
555608
void losslessAdapterRequestReachesLegacyEndpoint() throws IOException {
556609
try (JsonCollectStub stub = JsonCollectStub.start("{\"success\":true}");

0 commit comments

Comments
 (0)