diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 45203ce6..48200792 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -36,6 +36,18 @@ jobs:
java-version: '21'
cache: maven
+ - name: Verify shared contract fixtures and source lock
+ working-directory: src/test/resources/opencli-contracts/v1
+ run: sha256sum --strict -c SHA256SUMS
+
+ - name: Verify pinned structured help samples
+ working-directory: src/test/resources/opencli-contracts/v1/structured-help-1.8.8
+ run: sha256sum --strict -c SHA256SUMS
+
+ - name: Verify pinned browser output samples
+ working-directory: src/test/resources/opencli-contracts/v1/browser-output-1.8.8
+ run: sha256sum --strict -c SHA256SUMS
+
- name: Build and verify with JaCoCo coverage
run: ./mvnw -B --no-transfer-progress clean verify
diff --git a/.github/workflows/platform-contracts.yml b/.github/workflows/platform-contracts.yml
new file mode 100644
index 00000000..8a385564
--- /dev/null
+++ b/.github/workflows/platform-contracts.yml
@@ -0,0 +1,135 @@
+name: Platform subprocess contracts
+
+on:
+ push:
+ branches: [feature/REQ-20261118-wandl-opencli-privacy-30]
+
+permissions:
+ contents: read
+
+jobs:
+ process-platform:
+ name: Subprocess contracts (${{ matrix.os }})
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, macos-15-intel, windows-latest]
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-java@v5
+ with:
+ distribution: temurin
+ java-version: '21'
+ cache: maven
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.13'
+ - uses: actions/setup-node@v4
+ if: runner.os == 'Windows'
+ with:
+ node-version: '22'
+ - name: Exercise real subprocess contracts
+ run: |
+ mkdir -p platform-evidence
+ if [[ "$RUNNER_OS" == Windows ]]; then
+ OPENCLI_CONTRACT_NODE_EXECUTABLE="$(node -p 'process.execPath')"
+ export OPENCLI_CONTRACT_NODE_EXECUTABLE
+ fi
+ java -version > platform-evidence/java.txt 2>&1
+ bash ./mvnw -version > platform-evidence/maven.txt 2>&1
+ result=0
+ bash ./mvnw -B --no-transfer-progress \
+ -Dtest=OpenCliCapabilityDiscoveryTest,OpenCliCapabilityCommandTest,OpenCliErrorEnvelopeTest,OpenCliBrowserResultTest,OpenCliBrowserEvidenceResultTest,OpenCliDiagnosticsTest,OpenCliInvocationContextTest,OpenCliArgvContractTest,OpenCliStructuredArgvContractTest,OpenCliProcessContractTest,OpenCliProcessBoundaryTest,SubprocessCleanupFaultTest,SubprocessCompletionRaceTest,SubprocessStreamFailureTest,OpenCliWsReverseAgentSessionTest,OpenCliWsCollectRequestsTest,OpenCliRemoteAgentHttpClientTest,OpenCliProcessPrivacyTest,OpenCliArgSupportTest#shouldKeepConversionExceptionAndNestedCausePrivate,SubprocessExecutionSupportTest#shouldKeepNativePathOutOfDefaultHandlerException+legacyOutputStreamsAllowBoundedWritesWithoutChangingExecutionDetails,OpenCliStructuredHelpFixtureTest,OpenCliHelpParserTest,OpenCliArgvToCollectParserFullTest,OpenCliDiagnosticExportTest \
+ test > platform-evidence/maven.log 2>&1 || result=$?
+ tail -100 platform-evidence/maven.log
+ python scripts/contract_report.py \
+ --reports target/surefire-reports \
+ --trace openspec/changes/enforce-opencli-branch-contract-parity/evidence/final-requirement-trace.md \
+ --head "$(git rev-parse HEAD)" \
+ --branch "$GITHUB_REF_NAME" \
+ --java-version-file platform-evidence/java.txt \
+ --maven-version-file platform-evidence/maven.txt \
+ --exit-code "$result" \
+ --suite enumeration=io.github.easy4j.opencli.contract.OpenCliHelpParserTest \
+ --suite enumeration=io.github.easy4j.opencli.contract.OpenCliStructuredHelpFixtureTest \
+ --suite enumeration=io.github.easy4j.opencli.capability.OpenCliCapabilityDiscoveryTest \
+ --suite argv=io.github.easy4j.opencli.capability.OpenCliCapabilityCommandTest \
+ --suite argv=io.github.easy4j.opencli.contract.OpenCliArgvContractTest \
+ --suite argv=io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest \
+ --suite process=io.github.easy4j.opencli.contract.OpenCliProcessContractTest \
+ --suite process=io.github.easy4j.opencli.contract.OpenCliProcessBoundaryTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessCleanupFaultTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessCompletionRaceTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessStreamFailureTest \
+ --suite protocol=io.github.easy4j.opencli.remote.OpenCliArgvToCollectParserFullTest \
+ --suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsReverseAgentSessionTest \
+ --suite protocol=io.github.easy4j.opencli.center.ws.OpenCliWsCollectRequestsTest \
+ --suite protocol=io.github.easy4j.opencli.remote.OpenCliRemoteAgentHttpClientTest \
+ --suite process=io.github.easy4j.opencli.core.OpenCliProcessPrivacyTest \
+ --suite argv=io.github.easy4j.opencli.core.OpenCliArgSupportTest \
+ --suite process=io.github.easy4j.opencli.core.support.SubprocessExecutionSupportTest \
+ --suite protocol=io.github.easy4j.opencli.contract.OpenCliErrorEnvelopeTest \
+ --suite typed-result=io.github.easy4j.opencli.core.OpenCliDiagnosticExportTest \
+ --suite typed-result=io.github.easy4j.opencli.contract.OpenCliBrowserResultTest \
+ --suite typed-result=io.github.easy4j.opencli.contract.OpenCliBrowserEvidenceResultTest \
+ --suite typed-result=io.github.easy4j.opencli.capability.OpenCliDiagnosticsTest \
+ --suite argv=io.github.easy4j.opencli.capability.OpenCliInvocationContextTest \
+ --output platform-evidence/report.json
+ exit "$result"
+ - name: Verify npm-installed OpenCLI on Windows
+ if: runner.os == 'Windows'
+ run: bash scripts/run_installed_contracts.sh bash ./mvnw
+ - name: Upload platform subprocess evidence
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: subprocess-${{ matrix.os }}-${{ github.sha }}
+ path: |
+ platform-evidence
+ target/surefire-reports
+ if-no-files-found: error
+
+
+ browser-bridge:
+ name: Real Browser Bridge (${{ matrix.os }})
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-java@v5
+ with:
+ distribution: temurin
+ java-version: '21'
+ cache: maven
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.13'
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '24.18.0'
+ - name: Install the published OpenCLI in the runner's temporary directory
+ run: npm install --prefix "$RUNNER_TEMP/opencli-browser-cli" --ignore-scripts --no-audit --no-fund @jackwener/opencli@1.8.8
+ - name: Exercise the real Chrome extension against the loopback daemon
+ run: |
+ python scripts/run_browser_bridge_contracts.py \
+ --cli-entry "$RUNNER_TEMP/opencli-browser-cli/node_modules/@jackwener/opencli/dist/src/main.js" \
+ --evidence browser-bridge-evidence -- "$(command -v bash)" ./mvnw
+ - name: Upload real Bridge evidence
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: browser-bridge-${{ matrix.os }}-${{ github.sha }}
+ path: browser-bridge-evidence
+ if-no-files-found: error
diff --git a/README.md b/README.md
index ee351268..b1e9183f 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@ Multi-adapter CLI integration SDK for OpenCLI: browser / desktop / public-API ad
### 1.1 What it is
-**opencli-java-sdk** integrates Java applications with the [OpenCLI](https://github.com/partme-ai/opencli) multi-adapter CLI ecosystem. It executes `opencli ...` subprocesses via Commons Exec, exposes typed results (`OpenCliResult` / `OpenCliTypedResult`), unified exception semantics, remote HTTP agent support (Unirest) and a center WebSocket reverse-agent client (Java-WebSocket). It compiles and runs on JDK 8.
+**opencli-java-sdk** integrates Java applications with the [OpenCLI](https://github.com/partme-ai/opencli) multi-adapter CLI ecosystem. It executes `opencli ...` subprocesses via Commons Exec, exposes typed results (`OpenCliResult` / `OpenCliTypedResult`), unified exception semantics, remote HTTP agent support (Apache HttpClient) and a center WebSocket reverse-agent client (Java-WebSocket). It compiles and runs on JDK 8.
### 1.2 What it is not
@@ -73,7 +73,7 @@ Multi-adapter CLI integration SDK for OpenCLI: browser / desktop / public-API ad
| JDK | 21+ | 3.0.x line baseline |
| Maven | 4.0.0-rc-5 | Repository Maven Wrapper version |
| commons-exec | 1.6.0 | Local subprocess execution |
-| Unirest Java | 3.14.5 | Remote agent HTTP |
+| Apache HttpClient | Provided by Unirest Java 3.14.5 | Remote agent HTTP |
| Java-WebSocket | 1.6.0 | Center WebSocket |
| `tools.jackson.core:jackson-databind` | 3.2.1 | JSON parsing |
| SLF4J | 2.0.18 | Logging facade |
@@ -102,7 +102,7 @@ Version-line matrix:
| typed wrappers (codex, npm...) |
| meta list / validate / plugin / ... |
| browser session API (wait, extract...) |
-| remote POST {base}/collect (Unirest) |
+| remote POST {base}/collect (Apache HttpClient) |
| center WebSocket reverse agent |
+------------------------------------------+
|
@@ -177,24 +177,39 @@ Configuration is object-based via `OpenCliProperties`:
| `executionTarget` | `LOCAL_PROCESS` | `LOCAL_PROCESS` or `REMOTE_AGENT_HTTP` |
| `executable` | `opencli` | Executable name or absolute path |
| `workingDirectory` | — | Subprocess working directory |
-| `commandTimeoutMillis` | `300000` | Command timeout (ms; reused as HTTP timeout in remote mode) |
+| `commandTimeoutMillis` | `300000` | Command timeout in milliseconds. Remote pool acquisition, connection and response reading share the invocation budget. |
| `maxConcurrentExecutions` | `0` | Max concurrent subprocesses (0 = unlimited) |
| `startupProbeTimeoutMillis` | `30000` | Availability-probe timeout |
| `environment` | `{}` | Extra environment variables (e.g. `OPENCLI_CDP_ENDPOINT`) |
-| `remoteAgentBaseUrl` | — | Remote agent base URL |
+| `remoteAgentBaseUrl` | — | Remote Agent HTTP(S) base URL. Keep any deployment path prefix and omit user info, queries and fragments. |
| `remoteCollectMode` | `cdp` | `bridge` or `cdp` (must match the agent side) |
| `remoteOutputFormat` | `json` | Output format requested from the agent |
| `remoteCdpEndpoint` | — | Optional CDP endpoint overriding the agent default |
| `remoteCaptureRawHttpResponse` | `false` | Keep the raw HTTP body in `OpenCliResult#getRemoteRawHttpBody()` (large responses — use with care) |
+| `maxRemoteResponseBytes` | `10485760` | Positive byte limit after HTTP decompression. An oversized response raises `OpenCliRemoteResponseLimitException` with its HTTP status and limit. Raw capture only applies to accepted bodies. |
Notes:
- In remote mode the `stdout` is the JSON `items` the agent returned (parsed into line items per `format`), which may differ from local raw subprocess text; `leadingArguments` are local-only and are not injected on the remote path.
+- A legacy HTTP `/collect` reply must contain a JSON boolean `success`. Invalid envelopes raise `OpenCliRemoteProtocolException`, which extends `OpenCliExecutableFailureException`. A valid reply with `success: true` and omitted or null `items` still returns `[]`.
+- 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 and supply an explicit value for each option. The legacy server appends a value to every option, so bare flags require local execution. Use local execution for commands that need the original argv. A deployment with its own adapter contract can use the explicit `OpenCliCollectRequest` API.
+- A collect timeout raises `OpenCliRemoteTimeoutException`. After dispatch to the HTTP transport, `isRemoteOutcomeUnknown()` is true. Collect does not automatically retry or follow redirects.
+- 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.
+- 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.
+- 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.
+- 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.
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
## 8. Core Usage
+### Local argv migration
+
+- Local invocation preserves empty strings, padding, Unicode, line breaks, and literal option terminators. If your application relied on trimming or dropping values, normalize its inputs explicitly before calling the SDK.
+- Use the adapter's no-argument invocation or an empty list for a root command. A null varargs array or null token is invalid. An empty string token remains a valid value.
+- In the legacy options map, Boolean `false` still omits the option. Use `OpenCliOption.value` for a schema-supported literal `false`, or `OpenCliOption.negated` for a schema-supported negative flag. A negatable option reserves both its positive and negative names, so duplicate definitions across ordered and legacy options are rejected.
+- On Windows, use the full path to a native executable such as `node.exe`, with the installed OpenCLI JavaScript entry point in `leadingArguments`. The SDK rejects batch launchers. If the JVM is running in strict process mode, a literal double quote in an argument to a native EXE or an extensionless launcher (the shell `cmd.exe` follows its own command contract) is rejected before spawn with its index and an explanation.
+
### 8.1 meta() and browser()
```java
@@ -225,6 +240,24 @@ agent.close();
Protocol: edge sends `register`; center replies `registered`; center sends `collect` (request_id, site, command, args, positional_args, format, mode); the SDK executes `opencli` locally (via `copyForLocalCliExecution()` to avoid loops) and replies `result`; plus `ping` / `pong`.
+The reverse agent accepts up to four concurrent collect tasks and 32 queued tasks by default. Set `maxConcurrentCollects` and `maxPendingCollects` on the connection properties before constructing the agent to change the limits. A queue capacity of zero disables waiting. When full, the agent replies with a failed `result` and the error `worker is busy`.
+
+The reverse agent accepts collect only after the current connection acknowledges registration. Incoming WebSocket messages are capped at 1 MiB by default, including the assembled size of fragments. Set `maxInboundMessageBytes` before constructing the agent to configure the finite byte limit. Oversized messages close the affected connection before any command is queued.
+
+Collect request IDs must be nonblank strings of at most 128 UTF-8 bytes. The agent suppresses identical in-flight requests and rejects a reused ID with a different payload. An explicit retry may return a result marked `cached: true`. The in-memory cache keeps up to 1,024 completed results for at most ten minutes. Replay across reconnects requires the same TLS-verified endpoint. Plain WebSocket connections keep session-local deduplication. A new agent instance starts with an empty cache.
+
+`stop()` stops admission, discards queued tasks and allows in-flight work up to five seconds to finish before requesting cancellation. After the runner has stopped, `start()` can reconnect the same instance. `close()` immediately requests cancellation and closes the instance permanently.
+
+### Diagnostic export
+
+Call `OpenCliDiagnosticExport.export(result, 512)` explicitly with an `OpenCliResult` or an exception's partial result. The byte budget applies to UTF-8 text. Output contains only status and field lengths, with a `truncated=true` marker when fields do not fit. Field lengths can disclose how much data was present.
+
+The SDK returns the text in memory. Your application controls the destination and retention. SDK diagnostics omit argv values, raw content, URLs and filesystem paths. Applications that use or log raw results should protect that data. `remoteCaptureRawHttpResponse` is still opt-in.
+
+`OpenCliAvailabilityReport.toDiagnosticMessage()` is suitable for startup logs and reports readiness and status. Read the executable paths or probe message through their dedicated getters when needed.
+
+At the low-level process boundary, `RunSession.getHandler().getException()` returns a safe I/O summary. `RunSession.getIoFailure()` is the explicit raw diagnostic accessor. Handle that exception as sensitive data because it can include local paths.
+
## 9. Testing & Build
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 306804b3..752caef0 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -29,7 +29,7 @@
### 1.1 是什么
-**opencli-java-sdk** 将 Java 应用与 [OpenCLI](https://github.com/partme-ai/opencli) 多适配器 CLI 生态对接。它通过 Commons Exec 执行 `opencli ...` 子进程,提供类型化结果(`OpenCliResult` / `OpenCliTypedResult`)与统一异常语义,并支持远程 HTTP Agent(Unirest)与中心 WebSocket 反向 Agent 客户端(Java-WebSocket)。可在 JDK 8 线编译运行。
+**opencli-java-sdk** 将 Java 应用与 [OpenCLI](https://github.com/partme-ai/opencli) 多适配器 CLI 生态对接。它通过 Commons Exec 执行 `opencli ...` 子进程,提供类型化结果(`OpenCliResult` / `OpenCliTypedResult`)与统一异常语义,并支持远程 HTTP Agent(Apache HttpClient)与中心 WebSocket 反向 Agent 客户端(Java-WebSocket)。可在 JDK 8 线编译运行。
### 1.2 不是什么
@@ -72,7 +72,7 @@
| JDK | 21+ | 3.0.x 线基线 |
| Maven | 4.0.0-rc-5 | 仓库 Maven Wrapper 版本 |
| commons-exec | 1.6.0 | 本地子进程执行 |
-| Unirest Java | 3.14.5 | 远程 Agent HTTP |
+| Apache HttpClient | 由 Unirest Java 3.14.5 提供 | 远程 Agent HTTP |
| Java-WebSocket | 1.6.0 | 中心 WebSocket |
| `tools.jackson.core:jackson-databind` | 3.2.1 | JSON 解析 |
| SLF4J | 2.0.18 | 日志门面 |
@@ -101,7 +101,7 @@
| 强类型封装(codex、npm...) |
| meta list / validate / plugin / ... |
| browser 会话 API(wait、extract...) |
-| remote POST {base}/collect(Unirest) |
+| remote POST {base}/collect(Apache HttpClient) |
| center WebSocket 反向 Agent |
+------------------------------------------+
|
@@ -176,24 +176,39 @@ cli.gemini().deepResearch("topic",
| `executionTarget` | `LOCAL_PROCESS` | `LOCAL_PROCESS` 或 `REMOTE_AGENT_HTTP` |
| `executable` | `opencli` | 可执行文件名或绝对路径 |
| `workingDirectory` | — | 子进程工作目录 |
-| `commandTimeoutMillis` | `300000` | 命令超时(毫秒;远程模式复用为 HTTP 超时) |
+| `commandTimeoutMillis` | `300000` | 命令超时(毫秒)。远程连接池等待、建连和读取响应共享调用预算。 |
| `maxConcurrentExecutions` | `0` | 最大并发子进程数(0 = 不限) |
| `startupProbeTimeoutMillis` | `30000` | 可用性探测超时 |
| `environment` | `{}` | 额外环境变量(如 `OPENCLI_CDP_ENDPOINT`) |
-| `remoteAgentBaseUrl` | — | 远程 Agent 根地址 |
+| `remoteAgentBaseUrl` | — | 远程 Agent 的 HTTP(S) 基址,可以保留部署路径前缀。省略用户信息、查询参数和片段。 |
| `remoteCollectMode` | `cdp` | `bridge` 或 `cdp`(须与 Agent 侧一致) |
| `remoteOutputFormat` | `json` | 向 Agent 请求的输出格式 |
| `remoteCdpEndpoint` | — | 可选,覆盖 Agent 默认 CDP 端点 |
| `remoteCaptureRawHttpResponse` | `false` | 在 `OpenCliResult#getRemoteRawHttpBody()` 中保留原始 HTTP 报文(大响应请谨慎开启) |
+| `maxRemoteResponseBytes` | `10485760` | HTTP 解压后的响应体字节上限,须为正数。超限抛出 `OpenCliRemoteResponseLimitException`,含 HTTP 状态和上限。原文捕获受同一上限约束。 |
注意事项:
- 远程模式下 `stdout` 为 Agent 返回的 `items` 的 JSON(已按 `format` 解析为行列表),与本地原始子进程文本可能不同;`leadingArguments` 等仅影响本地进程拼装,**远程路径不注入**。
+- 旧版 HTTP `/collect` 响应须包含 JSON 布尔字段 `success`。无效响应抛出 `OpenCliRemoteProtocolException`,它继承 `OpenCliExecutableFailureException`。当 `success: true` 且 `items` 缺失或为 null 时,仍返回 `[]`。
+- 旧版 HTTP argv 调用仅接收 SDK 清单中的适配器及其子命令。根命令、Browser 会话、外部程序透传、重复选项、`--` 以及无法保留边界空格或前导短横的参数会在发请求前被拒绝。位置参数应在选项前,每个选项必须显式带值。旧版服务会给每个选项补一个值,裸开关应使用本地执行。需要原样传递 argv 时使用本地执行,已有自定义 Agent 契约时可用显式 `OpenCliCollectRequest` API。
+- 远程调用超时抛出 `OpenCliRemoteTimeoutException`。请求提交给 HTTP 传输后,`isRemoteOutcomeUnknown()` 为 true。客户端不会自动重试或跟随重定向。
+- 通过结果或异常的 `getPartialResult()` 调用 `getRemoteExecutionDetails()`,查看 HTTP 状态、Agent 业务状态和 `items` 的来源。`getExitCode()` 的 0/1 是兼容映射。HTTP 或协议失败快照没有退出码。仅在开启原文捕获时,失败快照才携带已通过字节上限检查的响应正文。
+- collect 连接在完整响应到达前中断时,失败快照标记 `TRANSPORT_FAILURE`,`isRemoteOutcomeUnknown()` 为 true。未收到响应头时,`getObservedHttpStatus()` 为空。快照不包含 CLI 退出码或不完整响应正文。服务端扩展须经过对应 Agent 契约验证。
+- Agent 支持认证请求头时,可调用 `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`,传入完整请求头值。认证须使用 HTTPS,Agent 基础地址须省略用户信息、查询参数和片段。SDK 只在 `/collect` 请求上发送已配置的认证头。OAuth 发现和请求签名尚不支持。
+- 对已采集的 CLI 帮助调用 `OpenCliHelpParser.parse(stdout)`,可读取结构化命令、占位符、不同作用域的选项和原文。纯文本、混合输出或无效结构会返回未知状态及原因。
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
## 8. 核心用法
+### 本地 argv 迁移
+
+- 本地调用原样保留空字符串、边界空白、Unicode、换行和字面参数终止符。此前依赖 SDK 裁剪或丢弃参数的调用方,应在调用前显式处理自己的输入。
+- 调用适配器根命令时使用无参调用或空列表。varargs 数组与 token 不能为 null,空字符串仍是有效参数值。
+- 旧选项 Map 的布尔 `false` 继续表示省略。显式布尔值使用有对应 schema 的 `OpenCliOption.value`,否定选项使用 `OpenCliOption.negated`。可否定的结构化选项同时占用正向名和否定别名,避免与旧 Map 或其他结构化选项冲突。
+- Windows 使用 `node.exe` 等原生可执行文件的完整路径,并在 `leadingArguments` 中指定已安装的 OpenCLI JavaScript 入口。SDK 拒绝批处理入口。在 JVM 严格进程模式下,原生 EXE 或无扩展名的启动名参数中的字面双引号(`cmd.exe` 遵循自身的命令契约)在启动前被明确拒绝,错误包含参数索引。
+
### 8.1 meta() 与 browser()
```java
@@ -224,6 +239,24 @@ agent.close();
协议摘要:边缘发送 `register`;中心回执 `registered`;中心下发 `collect`(request_id、site、command、args、positional_args、format、mode);SDK 在本机执行 `opencli`(通过 `copyForLocalCliExecution()` 强制本地子进程,避免回路)并回执 `result`;另有 `ping` / `pong`。
+反向 Agent 默认最多同时执行 4 个 collect 任务,另有 32 个等待名额。构建 Agent 前,可在连接配置中设置 `maxConcurrentCollects` 和 `maxPendingCollects`。等待容量为零时直接拒绝超额请求。容量用尽时返回失败的 `result`,错误为 `worker is busy`。
+
+当前连接收到合法注册确认后,反向 Agent 才开始收单。入站 WebSocket 消息默认上限为 1 MiB,分片按聚合后的字节数计量。需要调整上限时,在创建 Agent 前设置有限的 `maxInboundMessageBytes`。超限消息会关闭对应连接,不会提交命令。
+
+collect 请求 ID 必须为非空白字符串,长度上限 128 个 UTF-8 字节。相同的在途请求只执行一次,同一个 ID 对应不同载荷时会明确拒绝。显式重试已完成的请求有可能收到标记为 `cached: true` 的结果。内存缓存最多保留 1,024 条完成结果,每条最长 10 分钟。跨连接重放要求使用同一个经过 TLS 校验的端点,明文 WebSocket 的去重范围为当前连接。创建新 Agent 实例时从空缓存开始。
+
+`stop()` 停止接单并丢弃等待任务,为已在途任务保留最多 5 秒的收尾时间,随后请求取消。连接线程退出后,同一实例可再次调用 `start()` 重连。`close()` 立即请求取消,并永久关闭该实例。
+
+### 诊断导出
+
+如需导出诊断,请调用 `OpenCliDiagnosticExport.export(result, 512)`,传入 `OpenCliResult` 或异常中的部分结果。上限按 UTF-8 字节计算。输出只包含状态和字段长度,字段放不下时会标明 `truncated=true`。字段长度仍可能反映数据规模。
+
+SDK 在内存中返回文本,由应用决定目的地和保留时间。SDK 诊断会排除命令参数、原始内容、URL 和文件路径。应用读取或记录原始结果时应自行保护这些数据。`remoteCaptureRawHttpResponse` 仍需显式开启。
+
+`OpenCliAvailabilityReport.toDiagnosticMessage()` 可用于启动日志,只输出就绪状态和状态码。需要查看可执行文件路径或原始探测消息时,调用对应的 getter。
+
+低层进程接口的 `RunSession.getHandler().getException()` 返回安全的 I/O 摘要。`RunSession.getIoFailure()` 是显式读取原始诊断的入口,异常可能包含本地路径,应按敏感数据处理。
+
## 9. 测试与构建
diff --git a/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-find-console-network-analyze.md b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-find-console-network-analyze.md
new file mode 100644
index 00000000..551f4e4b
--- /dev/null
+++ b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-find-console-network-analyze.md
@@ -0,0 +1,19 @@
+# OpenCLI 1.8.8 的查找、采集与分析结果
+
+使用 npm 发布包 `@jackwener/opencli@1.8.8`、Node 24.18.0 和 macOS arm64。调用 [锁定版 CLI action](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/cli.ts)。页面调用由隔离的 Browser Bridge 桩提供,命令层的 JSON 包装、采集归一化、分析计算和缓存逻辑使用发布包原实现。固定时间为 2025-01-01T00:00:00Z,测试数据来自本地桩。
+
+| 叶子 | typed 入口 | 1.8.8 输出 | 验收范围 |
+|---|---|---|---|
+| tab list | `tabListTyped()` | 标签数组 | 普通、空列表 |
+| open | `openTyped(url, tab)` | 导航对象 | 页 ID 与可选上下文 |
+| state | `snapshotTyped(tab, source)` | URL 头和正文 | DOM、AX |
+| state --compare-sources | `compareStateSourcesTyped(tab)` | 两侧指标对象 | 成功、AX 单侧失败 |
+| find | `findTyped(locator, tab, options)` | 总匹配数和条目 | CSS、限量及精确 ref |
+| console | `consoleTyped(tab, options)` | 单次采集对象 | 记录与合法空数组 |
+| network | `networkTyped(options, tab)` | 单次采集对象 | 请求条目、形状和扩展元数据 |
+| analyze | `analyzeTyped(url, tab)` | 报告对象 | URL、标题、分类与扩展报告 |
+| console/network --follow、network --detail、其余叶子 | raw 会话 API | 流或其它形状 | 保持 raw |
+
+原始输出、SHA-256 与采集 preload 保存在 [样本目录](../../../../src/test/resources/opencli-contracts/v1/browser-output-1.8.8/)。沿用 [启动方式](2026-11-19-open-and-tab-list.md) 并设置 `OPENCLI_FIXTURE_FIXED_CLOCK=1`。调用 `browser fixture find --css '#fixture' --limit 1`、`browser fixture console`、`browser fixture network` 和 `browser fixture analyze http://127.0.0.1:18765/basic.html`。实际浏览器、网络请求和账户状态未参与本次验收。
+
+typed 捕获返回原始执行结果。对现有异常中的 partial result,可按 leaf 显式调用 `OpenCliBrowserDecoder`。分析提示、网络详情提示与 sitemap 路径保留为数据,由调用者明确决定后续动作。流式和详情参数可继续交给现有 raw 方法。
diff --git a/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-open-and-tab-list.md b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-open-and-tab-list.md
new file mode 100644
index 00000000..c1756856
--- /dev/null
+++ b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-open-and-tab-list.md
@@ -0,0 +1,23 @@
+# OpenCLI 1.8.8 浏览器叶子输出
+
+使用 npm 发布的 `@jackwener/opencli@1.8.8`、Node 24.18.0 和 macOS arm64。对版本锁定的 [CLI action](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/cli.ts) 使用真实命令入口和参数预处理。仅在 Browser Bridge 连接边界接入隔离页面桩,页面字段依据 [扩展输出](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/extension/src/background.ts) 提供。未连接浏览器账户、真实标签页或站点。
+
+| 叶子 | 归档样本 | 验证内容 |
+|---|---|---|
+| `browser fixture tab list` | `tab-list.json`、`tab-list-empty.json` | 数组,保留前导零的 page 字符串及合法空列表 |
+| `browser fixture open ` | `open.json` | 对象,包含实际 URL 和可选 page,允许缺少 sitemap |
+| state、find、console、network、analyze | 待采集 | 原有 raw API |
+
+在 [样本目录](../../../../src/test/resources/opencli-contracts/v1/browser-output-1.8.8/) 保存 stdout 原文、SHA-256 和可复跑的 preload。设置 `OPENCLI_ENTRY` 为锁定包的 `dist/src/main.js` 绝对路径后,可从该目录运行以下命令。
+
+```bash
+fixture_home=$(mktemp -d)
+env OPENCLI_FIXTURE_HOME="$fixture_home" CI=1 NO_COLOR=1 node --import "$PWD/capture.mjs" "$OPENCLI_ENTRY" browser fixture tab list > "$fixture_home/tab-list.json"
+env OPENCLI_FIXTURE_HOME="$fixture_home" CI=1 NO_COLOR=1 OPENCLI_FIXTURE_EMPTY=1 node --import "$PWD/capture.mjs" "$OPENCLI_ENTRY" browser fixture tab list > "$fixture_home/tab-list-empty.json"
+env OPENCLI_FIXTURE_HOME="$fixture_home" CI=1 NO_COLOR=1 node --import "$PWD/capture.mjs" "$OPENCLI_ENTRY" browser fixture open http://127.0.0.1:18765/basic.html > "$fixture_home/open.json"
+for specimen in tab-list.json tab-list-empty.json open.json; do
+ cmp "$specimen" "$fixture_home/$specimen"
+done
+```
+
+`session.tabListTyped()` 和 `session.openTyped(url, tab)` 返回带原始结果的严格视图。原有执行异常仍携带 partial result,可显式传给 `OpenCliBrowserDecoder` 查看截断或执行失败状态。扩展字段保留在 JSON 视图,路径和提示只作为数据。
diff --git a/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-state-dom-and-ax.md b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-state-dom-and-ax.md
new file mode 100644
index 00000000..1811ad33
--- /dev/null
+++ b/openspec/changes/add-opencli-browser-result-models/evidence/2026-11-19-state-dom-and-ax.md
@@ -0,0 +1,14 @@
+# OpenCLI 1.8.8 的 DOM 和 AX 状态输出
+
+使用 npm 发布包 `@jackwener/opencli@1.8.8`、Node 24.18.0 和 macOS arm64。调用 [锁定版 state 命令入口](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/cli.ts)。在 Browser Bridge 页面边界返回受控 DOM 文本,并用 [上游 AX 渲染器](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/browser/ax-snapshot.ts) 渲染合成 CDP 树。对比样本用固定时钟消除 elapsed_ms 波动,并另采集 AX 单侧失败场景。浏览器扩展和实际 CDP 链路仍待验证。
+
+| 叶子调用 | stdout 样本 | 结果 |
+|---|---|---|
+| `state --source dom` | `state-dom.stdout` | URL 头、空行和 DOM 正文 |
+| `state --source ax` | `state-ax.stdout` | URL 头、空行和 AX 正文 |
+| `state --source ax --compare-sources` | `state-compare.json` | JSON,DOM 和 AX 各自报告指标 |
+| `state --compare-sources`,注入 AX 不可用 | `state-compare-ax-failure.json` | 进程成功,DOM 指标和 AX 错误并存 |
+
+[样本目录](../../../../src/test/resources/opencli-contracts/v1/browser-output-1.8.8/) 保存原始 stdout 和 SHA-256。沿用 [前一批样本](2026-11-19-open-and-tab-list.md) 的启动方式,将命令替换为上表的 state 调用并设置 `OPENCLI_FIXTURE_FIXED_CLOCK=1`。最后一项额外设置 `OPENCLI_FIXTURE_AX_FAILURE=1`。
+
+`session.snapshotTyped(tab, OpenCliBrowserSnapshotSource.AX)` 返回 URL 和原样的快照正文。DOM 和 AX 对比使用 `session.compareStateSourcesTyped(tab)`,每侧分别检查 `isOk()`,失败侧可读取错误信息。调用者仍可通过原有 `state(tab, options)` 传递未来的字符串 source 或组合已有参数。
diff --git a/openspec/changes/add-opencli-browser-result-models/specs/opencli-browser-result-models/spec.md b/openspec/changes/add-opencli-browser-result-models/specs/opencli-browser-result-models/spec.md
index 71a736a1..404eaa94 100644
--- a/openspec/changes/add-opencli-browser-result-models/specs/opencli-browser-result-models/spec.md
+++ b/openspec/changes/add-opencli-browser-result-models/specs/opencli-browser-result-models/spec.md
@@ -1,6 +1,6 @@
# Browser 领域结果与严格解析
-> Proposal specification. Status: DRAFT / NOT_IMPLEMENTED.
+> The declared typed scope is verified on the feature branches. PR review and merge are pending.
## ADDED Requirements
diff --git a/openspec/changes/add-opencli-browser-result-models/tasks.md b/openspec/changes/add-opencli-browser-result-models/tasks.md
index eef7abe6..f8222677 100644
--- a/openspec/changes/add-opencli-browser-result-models/tasks.md
+++ b/openspec/changes/add-opencli-browser-result-models/tasks.md
@@ -1,26 +1,50 @@
# C07 Tasks · Browser 领域结果与严格解析
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已核对声明支持的叶子及各自的实现和证据。PR 评审与合并仍待完成。
关联规范:[spec](specs/opencli-browser-result-models/spec.md)。
## 1. 输出证据
-- [ ] 1.1 固定第一批leaf的真实输出fixtures、版本/平台/hash;无样本者在支持表标pending。
-- [ ] 1.2 先补 malformed/truncated/empty/unknownfields/largeID/AX 的失败测试。
+- [x] 1.1 固定第一批leaf的真实输出fixtures、版本/平台/hash;无样本者在支持表标pending。
+- [x] 1.2 先补 malformed/truncated/empty/unknownfields/largeID/AX 的失败测试。
## 2. 模型与decoder
-- [ ] 2.1 实现Java8公共模型与各Jackson分支兼容decoder,避免以double中转ID。
-- [ ] 2.2 保留raw/JsonNode与旧close返回签名,新增strict访问而非破坏旧API。
-- [ ] 2.3 建立每leaf字段约束和parse-state,未验证shape不自动转成空成功。
+- [x] 2.1 实现Java8公共模型与各Jackson分支兼容decoder,避免以double中转ID。
+- [x] 2.2 保留raw/JsonNode与旧close返回签名,新增strict访问而非破坏旧API。
+- [x] 2.3 建立每leaf字段约束和parse-state,未验证shape不自动转成空成功。
## 3. 集成验收
-- [ ] 3.1 与C03错误/trace、C02截断、C08上下文保持一致,禁止自动读取sitemap路径。
-- [ ] 3.2 在三线共享fixtures上验证字段与失败语义等价。
-- [ ] 3.3 生成实际typed支持表,区分已验证和仅raw支持,补迁移示例。
+- [x] 3.1 与C03错误/trace、C02截断、C08上下文保持一致,禁止自动读取sitemap路径。
+- [x] 3.2 在三线共享fixtures上验证字段与失败语义等价。
+- [x] 3.3 生成实际typed支持表,区分已验证和仅raw支持,补迁移示例。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## OC-BROWSER-001/002/003/005/006 首批叶子
+
+`OpenCliBrowserResultTest` 首先因缺少结果类型无法编译。加入 tab list 和 open 的叶子模型后,验收真实 CLI action 的归档输出、合法空数组、畸形输出、截断、命令失败、精确 ID 和扩展元数据。两种命令通过现有会话入口运行,原始结果和既有 close 签名保留。见 [样本与复跑方式](evidence/2026-11-19-open-and-tab-list.md)。AX/state、其余叶子与真实浏览器接入继续验收。
+
+## OC-BROWSER-001/002/004 state 与 AX
+
+`OpenCliBrowserResultTest` 在缺少 state 类型模型和门面入口时无法编译。实现后验收 DOM 与 AX 文本、对比 JSON、单侧失败、无法识别的输出及 typed null source 拒绝。原有 String source 和 compareSources 继续由既有 Options 传递。见 [四份上游入口样本](evidence/2026-11-19-state-dom-and-ax.md)。
+
+## OC-BROWSER-001/002/003/005 find、console、network 与 analyze
+
+`OpenCliBrowserEvidenceResultTest` 首先因缺少模型和门面而无法编译。实现后验收有限的 find 条目、整数 ref 保真、采集 count 与数组一致性、分析扩展信息和原有执行失败。流式采集及网络详情在 typed 入口启动前拒绝,保留 raw 方法。见 [输出证据、支持表和迁移方式](evidence/2026-11-19-find-console-network-analyze.md)。
+
+## C07 实施核对与绑定标签页
+
+- OC-BROWSER-001 / OC-BROWSER-002。版本锁定的值、状态与证据表覆盖已声明的 typed 入口。合法空数组、畸形结果、截断和进程失败各有独立状态。
+- OC-BROWSER-003。测试保留大于 IEEE 754 安全整数范围的 ID、前导零及未知字段。
+- OC-BROWSER-004。真实 Browser Bridge 运行 DOM、AX 和双源对比。参数回归检查原有 source 和 compare-sources,未知 raw source 原样传入。
+- OC-BROWSER-005。分析提示、sitemap 和 trace 保留为数据。相关 decoder 不读取文件或执行提示。
+- OC-BROWSER-006。已有 close 调用继续返回原始结果。新增真实扩展测试绑定隔离浏览器的活动标签页,验证 typed 成功、请求不存在的目标页失败,以及客户端关闭后,原标签页仍能通过同一 ID 列出。最后显式解绑。
+
+以回环 HTTP 服务的 `/bound-fixture.html` 启动临时 Chrome profile,让它成为活动标签页。该 URL 可以返回与普通 fixture 相同的 HTML。
+
+本分支以 `97aee9a451facfdc998ef039a59f7fa4f4e27476` 为基线,使用 JDK 21 执行 `./mvnw -B -ntp -o -Dtest=OpenCliBrowserBridgeIT,OpenCliBrowserResultTest,OpenCliBrowserEvidenceResultTest,OpenCliErrorEnvelopeTest test`。退出码为 0。运行 24 项,包含 3 项真实 Browser Bridge 用例,零失败、零错误、零跳过。报告位于 `target/surefire-reports`。外部认证网站验收仍保持独立。
diff --git a/openspec/changes/add-opencli-capability-discovery/evidence/2026-11-19-structured-help.md b/openspec/changes/add-opencli-capability-discovery/evidence/2026-11-19-structured-help.md
new file mode 100644
index 00000000..0570ffc7
--- /dev/null
+++ b/openspec/changes/add-opencli-capability-discovery/evidence/2026-11-19-structured-help.md
@@ -0,0 +1,21 @@
+# OpenCLI 1.8.8 帮助协议采集
+
+使用 Node 24.18.0 和 npm 发布包 `@jackwener/opencli@1.8.8`,运行包声明的入口 `dist/src/main.js`。上游 `v1.8.8` tag 指向 `8271afc67e8504bda94c147f446ee29775d08274`,与本项目 U02/U03 锁定一致。[上游帮助实现](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/help.ts)
+
+[原始样本及 SHA-256](../../../../src/test/resources/opencli-contracts/v1/structured-help-1.8.8/) 按 stdout 字节保存。两轮分别使用独立临时用户目录,禁止自动更新检查,不加载用户已有的配置或插件。只运行 `--version` 和下表的帮助参数。两轮版本均为 1.8.8,9 个样本均退出 0、stderr 为空,对应 stdout 逐字节一致。样本来自 Apache-2.0 发布包。
+
+| 样本 | 入口参数 | 实际输出 |
+|---|---|---|
+| `root.json` | `--help -f json` | 单一 JSON。根命令为简要列表,`site_adapters` 为含 `count`、`sites` 的对象。 |
+| `browser.stdout` | `browser --help -f json` | JSON 后附加示例说明,共 472 个非首尾空白后缀字符,严格 JSON 读取失败。 |
+| `browser-tab.json` | `browser fixture tab --help -f json` | `tab` 分组 JSON。命令路径保留 ``,包括 `tab list`、`tab select`。 |
+| `browser-get.json` | `browser fixture get --help -f json` | `get` 分组 JSON。包含 `get text`、`get attributes` 等叶子。该版本把 `tab` 和 `get` 分为两组。 |
+| `browser-state.json` | `browser fixture state --help -f json` | 单个叶子,带 session 占位符和独立的三类 options。 |
+| `meta-auth.json` | `auth --help -f json` | meta 命名空间 JSON,保留 namespace 与 global options。 |
+| `meta-list.txt` | `list --help -f json` | 纯文本 Commander 帮助,严格 JSON 读取失败。 |
+| `site-npm.json` | `npm --help -f json` | 站点目录 JSON,公共参数字段为 `common_options`。 |
+| `site-npm-search.json` | `npm search --help -f json` | 叶子 JSON,含必填位置参数 `query` 和命令参数 `limit`。 |
+
+采集时通过 `node --import` 预加载脚本,将进程的 `os.homedir()` 指向临时目录,并同步 Node 内置模块导出。为两轮分别配置 `OPENCLI_CACHE_DIR`、`OPENCLI_CONFIG_DIR`,设置 `CI=1`、`NO_COLOR=1`。浏览器参数 `fixture` 是帮助查询的字面会话名,未创建会话或执行叶子命令。
+
+`OpenCliStructuredHelpFixtureTest` 验证真实的作用域、占位符、根命令目录与两种负例,报告位于 `target/surefire-reports`。这些输出约束后续 C06 模型设计。两种负例仍需发现服务给出明确状态。远端 Agent、运行时插件、本地 override 及其他站点尚无本轮采集证据。
diff --git a/openspec/changes/add-opencli-capability-discovery/tasks.md b/openspec/changes/add-opencli-capability-discovery/tasks.md
index c0e8f0a4..ebb60904 100644
--- a/openspec/changes/add-opencli-capability-discovery/tasks.md
+++ b/openspec/changes/add-opencli-capability-discovery/tasks.md
@@ -1,26 +1,63 @@
# C06 Tasks · 结构化能力发现与可追溯快照
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 勾选项有对应的执行证据。
关联规范:[spec](specs/opencli-capability-discovery/spec.md)。
## 1. schema基线
-- [ ] 1.1 从锁定OpenCLI采集root/browser/meta/site结构化help,记录真实来源与hash,清楚标注不能采集的部分。
-- [ ] 1.2 为scope、optionalvalue、negate、false、aliases、session占位和旧格式编写失败测试。
+- [x] 1.1 从锁定 OpenCLI 采集 root、browser、meta 和 site 帮助,保存原文与 SHA-256。不能读取为单一 JSON 文档的输出单列为负例。见 [1.8.8 采集证据](evidence/2026-11-19-structured-help.md)。
+- [x] 1.2 为scope、optionalvalue、negate、false、aliases、session占位和旧格式编写失败测试。
## 2. 服务实现
-- [ ] 2.1 新增Java8可表达schema与快照模型,保留unknown字段和raw;复用已有adapter入口。
-- [ ] 2.2 实现有限version/help探测与可信executable校验,禁止自动业务操作。
-- [ ] 2.3 实现cache key、内容hash、失效与UNKNOWN/STALE/UNSUPPORTED原因。
+- [x] 2.1 新增Java8可表达schema与快照模型,保留unknown字段和raw;复用已有adapter入口。
+- [x] 2.2 实现有限version/help探测与可信executable校验,禁止自动业务操作。
+- [x] 2.3 实现cache key、内容hash、失效与UNKNOWN/STALE/UNSUPPORTED原因。
## 3. 边界验证
-- [ ] 3.1 测试本地override/插件来源未知时不伪造来源和全量覆盖率。
+- [x] 3.1 测试本地override/插件来源未知时不伪造来源和全量覆盖率。
- [ ] 3.2 测试原有raw入口不会因为发现故障被无声禁用,remote拒绝范围仍受C04控制。
- [ ] 3.3 三线同一schema fixture结果一致;报告未运行的真实上游采集项。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+
+## OC-CAP-001/002/005 结构化帮助解析
+
+`OpenCliHelpParser` 在 Java 8 API 范围内提供帮助解析结果。根目录、站点、命名空间和叶子按真实 1.8.8 结构识别。Schema 保留命令显示路径、会话占位符、命令层级、位置参数、别名和分作用域选项。缺失字段、显式 false、可选取值、否定和默认值分别保留。原文和各节点的来源 JSON 可以追溯未解释字段。纯文本、JSON 后缀、重复字段或无效结构返回 `UNKNOWN` 及对应原因。
+
+基线的 API 验收先因缺少解析入口而无法编译。加入实现后,以 1.8.8 的七个 JSON 样本、两个原始负例和合成扩展验证,详见 `OpenCliHelpParserTest`。当前验证范围为原文解码,运行时探测、快照来源与失效、类型化会话绑定仍由其余任务验收。
+
+## OC-CAP-004/005/006 本地根发现
+
+`OpenCliClient.discoverCapabilities()` 接受调用者信任的绝对本地可执行文件配置,记录规范路径、观测版本、采集时刻、配置指纹及完整帮助文本的 SHA-256。探测固定为 `--version` 和 `--help -f json`,复用客户端执行器的本地并发容量、队列和进程清理。每次探测的队列与运行合计最多 10 秒,清理最多 1 秒,每路最多保留 1 MiB,调用者设置的更小预算优先。命令来源为 `UNKNOWN`,观察范围为 `ROOT_HELP`。采用按需重新观测,同版本改动可形成不同帮助摘要;缓存和 STALE 仍待实现。远端和 PATH 查找的发现请求返回 `UNSUPPORTED`,原有显式本地调用仍可使用。
+
+`OpenCliCapabilityDiscoveryTest` 先因缺少公开发现 API 无法编译。真实 JVM 子进程验收固定参数、同版本变更、无来源推断、文本降级、输出超限、非零退出、超时及 local raw。Maven 定向测试同时验证原有帮助解析。范围仍为根级目录,细粒度帮助探测及类型化执行仍未验收。
+
+## OC-CAP-004/005 根帮助快照失效
+
+客户端保存一个最近成功的根帮助快照,每次显式发现均重新探测。刷新失败且配置指纹一致、未观测到不同版本时,返回 `STALE`,保留成功时的采集时间、schema 和帮助摘要。失败的刷新另存于 `failedRefresh`,包括失败原因、尝试时间和可取得的原始帮助。配置或已观测版本改变会清除旧快照;成功刷新以新内容更新摘要。同一客户端并发探测时,较早发起但较晚完成的探测不会覆盖已发布的新结果。
+
+`OpenCliCapabilityDiscoveryTest` 的定向红灯为预期 `STALE`、实际 `UNKNOWN`。实现后验证同配置降级、失败原文、同版本帮助变化、配置与版本失效、并发完成顺序。当前缓存范围为根帮助。
+
+## OC-CAP-001/003/004/005/006 固定范围帮助探测
+
+`discoverCapabilities(OpenCliHelpScope)` 提供根目录、浏览器、浏览器 tab/get/state、auth、list 及 npm 站点和 search 的九个固定查询。细粒度参数只在已验证的 OpenCLI 1.8.8 启用。浏览器查询使用固定的帮助会话占位,不接受调用者提供的命令路径,也不执行帮助描述中的内容。结构化结果需匹配请求范围;纯文本和混合输出维持原有失败原因。
+
+每个范围只保存其最近成功的观察,且配置或已观测版本变化使其他不匹配的范围一并失效。OpenCLI 能力仍按请求观察,并保留来源未知标记。增加 `OpenCliCapabilityDiscoveryTest` 的进程验收后,缺少范围 API 时失败,加入实现后定向测试通过。类型化会话绑定及执行前参数校验仍待验收。
+
+## OC-CAP-002/003 类型化本地调用
+
+`OpenCliClient.invokeDiscovered` 对本地配置取快照,刷新指定范围,选择显式给定的叶子路径,校验后通过同一执行器运行时提交字面参数。需要提供浏览器会话时,必须填入合法会话标识。校验覆盖必选项和值、声明 choices、可选值 flag、显式 false、否定拼写和可变位置参数;用字面分隔符隔离可能像选项的位置参数。不可用或过期的帮助无法进入类型化执行。原有本地 raw 入口独立可用。
+
+`OpenCliCapabilityCommandTest` 和 `OpenCliCapabilityDiscoveryTest` 以失败→通过验证新 API、字段级错误和真实 JVM 子进程收到的 argv。当前仅对已验证的 OpenCLI 1.8.8 执行发现绑定;测试不依赖浏览器账户。
+
+## OC-CAP-004/006 运行时覆盖验收
+
+`OpenCliCapabilityOverrideIT` 使用 Node 24.18.0 和 npm 发布的 OpenCLI 1.8.8。测试以独立临时用户目录运行,每次刷新均查询 npm search 的同一叶子。依次观察内置定义、本地 adapter 覆盖、插件覆盖、移除插件后恢复本地定义。每次均返回 `AVAILABLE`,保留观测版本 1.8.8、原文、`SITE_NPM_SEARCH` 范围和 `UNKNOWN` 来源。配置指纹相同,内容摘要随有效覆盖变化。覆盖 handler 仅在业务执行时写入标记,帮助探测后标记始终不存在。
+
+在配置 `OPENCLI_INSTALLED_NODE` 和 `OPENCLI_INSTALLED_ENTRY` 后执行 `./mvnw -B -ntp -Dtest=OpenCliCapabilityOverrideIT test`。报告为 `target/surefire-reports/TEST-io.github.easy4j.opencli.contract.OpenCliCapabilityOverrideIT.xml`。本测试仅覆盖受控目录下的两个覆盖定义。真实 Browser Bridge 会话与外部插件生态仍未验收。
diff --git a/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-invocation-context.md b/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-invocation-context.md
new file mode 100644
index 00000000..23682aba
--- /dev/null
+++ b/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-invocation-context.md
@@ -0,0 +1,22 @@
+# OpenCLI 1.8.8 的单次调用上下文
+
+使用 npm 发布包 `@jackwener/opencli@1.8.8`、Node 24.18.0 和隔离的 macOS arm64 用户目录。仅采集 `profile --help -f json` 和 `zhihu hot --help -f json`。原始 stdout 与 SHA-256 保存在 [结构化帮助样本目录](../../../../src/test/resources/opencli-contracts/v1/structured-help-1.8.8/)。
+
+| 选项 | 证据 | SDK 绑定位置 |
+|---|---|---|
+| `--profile` | profile 与 Browser state 帮助中的 global_options | 根命令之前 |
+| `--window` | Browser state namespace_options 或站点 browser_common_options | 浏览器会话名之后,站点参数位 |
+| `--site-session`、`--keep-tab` | 已声明 browser=true 的 zhihu hot browser_common_options | 站点参数位 |
+| `--trace` | 站点 common_options | 站点参数位 |
+
+[argv 预处理](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/cli-argv-preprocess.ts) 要求 Browser 之后先读到会话名。[站点适配器注册器](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/commanderAdapter.ts) 从根选项读取 profile 并单独读取 Browser 通用选项。SDK 在已验证的 `zhihu hot` 范围需要 profile 时,只取当前 profile 帮助的根参数定义。旧的 Browser 会话入口同步调整 `--window` 位置。
+
+```java
+OpenCliInvocationContext defaults = OpenCliInvocationContext.builder().keepTab(true).build();
+properties.setInvocationDefaults(defaults);
+OpenCliInvocationContext request = OpenCliInvocationContext.builder().keepTab(false).build();
+client.invokeDiscovered(OpenCliHelpScope.SITE_ZHIHU_HOT, "opencli zhihu hot",
+ null, null, null, request);
+```
+
+显式上下文和调用选项覆盖默认值。两种显式输入冲突时拒绝提交。默认值只应用于发现后严格校验的本地调用。业务调用按调用者选中的叶子正常执行。SDK 不修改环境或全局 profile。只读诊断留待 C08 后续验收。
diff --git a/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-read-only-diagnostics.md b/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-read-only-diagnostics.md
new file mode 100644
index 00000000..a6cee4ad
--- /dev/null
+++ b/openspec/changes/add-opencli-context-and-diagnostics/evidence/2026-11-19-read-only-diagnostics.md
@@ -0,0 +1,24 @@
+# OpenCLI 1.8.8 只读诊断
+
+已核对 npm 包 `@jackwener/opencli@1.8.8` 的 [启动入口](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/main.ts)。顶层 `--version` 在插件加载、后台更新检查和 `onStartup` 前退出。完整启动路径会创建用户适配器目录并执行启动钩子,因此即便只查询帮助,诊断也不进入完整启动路径。调用者配置的绝对 launcher、前置参数及运行环境属于信任边界。此处的只读证据对应锁定版实际 CLI。
+
+| 检查 | 来源及适用性 |
+|---|---|
+| EXECUTABLE | 本机绝对路径及可执行权限检查 |
+| VERSION | 有界版本 fast path |
+| STRUCTURED_HELP | 历史显式发现,配置与版本匹配才引用。已成功样本标为 STALE,失败样本标为 UNKNOWN |
+| BROWSER_BRIDGE、AUTHENTICATION、DAEMON | UNKNOWN,未确认只读探测 |
+| REMOTE_TRANSPORT | legacy HTTP 模式为 UNKNOWN,诊断不发送 collect |
+| 远端模式的本机检查 | NOT_APPLICABLE |
+
+```java
+OpenCliDiagnostics diagnostics = client.diagnose();
+OpenCliDiagnostics.Observation version =
+ diagnostics.observation(OpenCliDiagnostics.Check.VERSION);
+OpenCliDiagnostics.Observation help =
+ diagnostics.observation(OpenCliDiagnostics.Check.STRUCTURED_HELP);
+```
+
+`OpenCliDiagnosticsTest` 记录子进程的每条命令,验证仅版本探测、历史帮助失败与成功、配置改变以及远端跳过。`OpenCliReadOnlyDiagnosticsIT` 在临时用户目录注册一个只写入测试标记的启动钩子。诊断取得真实版本而未写标记。显式帮助启动会写入标记。移除标记后再次诊断,历史帮助仍可追溯,标记仍未出现。没有真实登录、认证续期、daemon 重启或外部请求。
+
+`open` 与 `analyze` 的可选 sitemap 与 trace 按各自结果元数据保留,缺失仍是缺失。没有 overlay 文件访问。Pipeline 保持 [能力矩阵](../../../../docs/architecture/opencli-java-sdk-capability-matrix.md) 中的 JS 模块/DEFERRED 状态,Java 批处理模型由独立 ADR 评审。
diff --git a/openspec/changes/add-opencli-context-and-diagnostics/specs/opencli-context-diagnostics/spec.md b/openspec/changes/add-opencli-context-and-diagnostics/specs/opencli-context-diagnostics/spec.md
index 76185cda..0b2cf0ad 100644
--- a/openspec/changes/add-opencli-context-and-diagnostics/specs/opencli-context-diagnostics/spec.md
+++ b/openspec/changes/add-opencli-context-and-diagnostics/specs/opencli-context-diagnostics/spec.md
@@ -1,6 +1,6 @@
# 隔离执行上下文与只读诊断
-> Proposal specification. Status: DRAFT / NOT_IMPLEMENTED.
+> Implementation verified on the feature branches. PR review and merge are pending.
## ADDED Requirements
diff --git a/openspec/changes/add-opencli-context-and-diagnostics/tasks.md b/openspec/changes/add-opencli-context-and-diagnostics/tasks.md
index 68488f7c..a0a38133 100644
--- a/openspec/changes/add-opencli-context-and-diagnostics/tasks.md
+++ b/openspec/changes/add-opencli-context-and-diagnostics/tasks.md
@@ -1,26 +1,49 @@
# C08 Tasks · 隔离执行上下文与只读诊断
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 上下文与只读诊断验收已在三条功能分支核对,待 PR 评审与合并。
关联规范:[spec](specs/opencli-context-diagnostics/spec.md)。
## 1. 上下文契约
- [ ] 1.1 核实锁定版本profile与Browser公共options的scope和真实输出fixture。
-- [ ] 1.2 编写并发context隔离、false覆盖、scope冲突与诊断UNKNOWN的失败测试。
+- [x] 1.2 编写并发context隔离、false覆盖、scope冲突与诊断UNKNOWN的失败测试。
## 2. 增量API
-- [ ] 2.1 实现不可变context与优先级合并,复用原meta/auth/skills入口。
-- [ ] 2.2 实现per-check只读诊断,审计每个probe副作用;不能确认时保留unknown。
-- [ ] 2.3 保留sitemap raw/optional metadata,不自动访问overlay或trace文件。
+- [x] 2.1 实现不可变context与优先级合并,复用原meta/auth/skills入口。
+- [x] 2.2 实现per-check只读诊断,审计每个probe副作用;不能确认时保留unknown。
+- [x] 2.3 保留sitemap raw/optional metadata,不自动访问overlay或trace文件。
## 3. 边界评审
-- [ ] 3.1 证明诊断不会执行login/refresh/restart/install/profile use等变更操作。
-- [ ] 3.2 更新DEFERRED清单,移除未经证实的pipelineCLI/单进程承诺。
+- [x] 3.1 证明诊断不会执行login/refresh/restart/install/profile use等变更操作。
+- [x] 3.2 更新DEFERRED清单,移除未经证实的pipelineCLI/单进程承诺。
- [ ] 3.3 三线验证上下文与诊断状态一致,并在指南中给出明确的只读使用示例。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## OC-CTX-001/002 不可变上下文与作用域
+
+提供不可变 `OpenCliInvocationContext` 与 `OpenCliProperties.invocationDefaults`。调用的显式值覆盖默认值,false 会生成有值的 `--keep-tab false`。冲突的显式选项或当前范围不支持的参数在业务进程启动前拒绝。Browser 全局、命名空间和叶子选项分别绑定。见 [锁定版证据与使用示例](evidence/2026-11-19-invocation-context.md)。
+
+`OpenCliInvocationContextTest` 首先因缺少 API 无法编译。实现后用 JVM 子进程验证并发 profile/window、false 与默认继承、非 Browser scope 拒绝及显式冲突。仍需验收诊断与其只读边界。
+
+## OC-CTX-003/004/005/006 只读诊断
+
+`diagnose()` 独立报告可执行文件、版本、历史帮助、Browser Bridge、认证、daemon 和远端传输。历史帮助有来源和观察时刻,配置或版本不匹配时保持 UNKNOWN。远端只读诊断跳过本机命令并保持传输未验证。三个本地运行时状态无法确认只读探测,保持 UNKNOWN。见 [只读边界与集成验证](evidence/2026-11-19-read-only-diagnostics.md)。
+
+`OpenCliDiagnosticsTest` 初始缺少公开 API,编译失败。实现后回归记录只运行 `--version`,并验证显式发现的历史证据不提升为当前健康。已发布 CLI 的 opt-in `OpenCliReadOnlyDiagnosticsIT` 区分版本探测与执行启动钩子的显式帮助。报告位于 `target/surefire-reports`。
+
+
+## C08 失败隔离与只读复验
+
+一个 Java 客户端通过独立 JVM 子进程并发执行两个不同 profile/window 的调用。故意失败的调用及其 partial result 保留自己的 argv,另一调用保留自己的 argv。随后没有覆盖值的调用继续使用客户端的原默认值。现有回归同时验证显式 `false`、scope 冲突和未经验证诊断的 UNKNOWN。
+
+并发夹具使用临时目录中的两个同步信号。成功调用的子进程先发出就绪信号,失败调用才以 7 退出;父测试确认失败结果后释放成功调用。由此验证失败发生时成功调用确实尚未完成。以 `2986a86`、`a4687d1`、`72c9dd8` 为基线加入同步验证后,Java 8、17、21 的 `./mvnw -B -ntp -o clean verify` 分别通过 2235、2236、2235 项,零失败、零错误、零跳过。
+
+使用发布版 OpenCLI 1.8.8 的独立配置目录验证默认诊断只取版本,不执行安装版 CLI 的 startup hook。显式发起帮助探测会触发 fixture hook,后续默认诊断不会再次执行它。sitemap 和 trace 路径保持数据,pipeline CLI 仍为 DEFERRED。
+
+本分支以 `e5811f1bd0c389f6951cb3b356dd3acf1e292b89` 为基线,使用 JDK 21,提供安装版 CLI 对应的 `OPENCLI_INSTALLED_NODE` 与 `OPENCLI_INSTALLED_ENTRY` 后执行 `./mvnw -B -ntp -o -Dtest=OpenCliInvocationContextTest,OpenCliDiagnosticsTest,OpenCliReadOnlyDiagnosticsIT test`。8 项实际执行,零失败、零错误、零跳过,退出码为 0。报告位于 `target/surefire-reports`。
diff --git a/openspec/changes/enforce-opencli-branch-contract-parity/evidence/final-requirement-trace.md b/openspec/changes/enforce-opencli-branch-contract-parity/evidence/final-requirement-trace.md
new file mode 100644
index 00000000..b5709c0e
--- /dev/null
+++ b/openspec/changes/enforce-opencli-branch-contract-parity/evidence/final-requirement-trace.md
@@ -0,0 +1,156 @@
+# OpenCLI 三条 Java 线的需求追溯
+
+此表把 59 项现行 Requirement 指向实际测试方法和 Java 17 线的关键提交;同名方法已在 Java 8、17、21 源码逐项核对。测试名称链接固定在 Java 17 源码 `360cbc5`。各线提交和覆盖率以本页对应矩阵为准。
+
+## 三条测试分支的托管证据
+
+| JDK | 测试分支 | 已验证源码和工作流提交 | GitHub Actions |
+| --- | --- | --- | --- |
+| 8 | `test/20261119-1.0.x` | `427d828c0d55dddc8df2b172c318bdc801d58b35` | [44425698386](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425698386) |
+| 17 | `test/20261119-2.0.x` | `b1169d234d92c7dd1060a8a48c9273f2e4b581af` | [44425698286](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425698286) · [常规全量 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425706221) |
+| 21 | `test/20261119-3.0.x` | `c1f30c48dcfcd8882a4c1f4a0d3148eb846daded` | [44425698650](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425698650) |
+
+三条测试分支的远端 SHA 与表中通过的托管构建一致。逐项核对 59 项需求关联的 102 个具名方法,每条线的 Surefire 报告均包含全部方法的成功执行记录。10 份平台报告各执行枚举 25 项、argv 53 项、进程 48 项、协议 112 项、类型结果 21 项。六份 Browser Bridge 报告和三份 npm 安装版报告各执行 4 项。加上 Java 17 的全量 JVM 报告,共核对 20 份 JSON,命令均退出 0。
+
+Java 17 全量 JVM 报告旧配置漏列四个必选套件。用该次构建的 XML 重放并分别移除 `OpenCliArgSupportTest`、`SubprocessExecutionSupportTest`、`OpenCliArgvToCollectParserFullTest`、`OpenCliDiagnosticExportTest`,旧配置四次均返回 0。全量 JVM 报告与平台报告登记相同套件后,完整证据返回 0,四个缺失用例均返回 1。前述平台和真实执行报告已经覆盖这四个套件关联的追溯方法。
+
+## 具名方法门禁
+
+平台报告和 Java 17 全量 JVM 报告读取本页固定源码中的测试方法链接。对已归属当前报告的套件,XML 必须包含同名测试类下成功执行的每个具名方法。报告记录每层的 `requiredMethodCount` 和 `missingMethods`。参数与参数化索引保留在原始 XML。真实 Browser Bridge 和安装版执行继续使用各自的证据。
+
+使用 [Java 17 的原始全量 XML](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44432735772) 重放,完整报告通过。分别去掉枚举、argv、进程、协议和类型结果层的一个具名方法,并保持原套件仍有通过用例及一致的计数。旧报告五次均通过,新报告五次均失败并指出具体套件和方法。再使用 [Java 8](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425698386)、[Java 17](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44432735772) 和 [Java 21](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44425698650) 的 Windows 安装前 Surefire 工件重放,三条线均通过 96 个具名方法校验。真实执行的另外六个追溯方法由单独报告核对。
+
+## 历史 C04 候选证据
+
+| JDK | 已验证平台基线 | 当前 C04 候选 | 本地全量 | JaCoCo 行覆盖率 | 当前候选托管矩阵 |
+| --- | --- | --- | ---: | ---: | --- |
+| 8 | [`ebeb4de`](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44414786839) | [`b480d6f`](https://github.com/easy-4-java/opencli-java-sdk/commit/b480d6f19863633c34c705d0399ef4abb75ec063) | 2,263 | 3956/4262(92.82%) | [CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44415816379) |
+| 17 | [`6874340`](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44414786916) | [`360cbc5`](https://github.com/easy-4-java/opencli-java-sdk/commit/360cbc5afe25eb72f352bff1166834850bc20acd) | 2,264 | 3951/4253(92.90%) | [CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44415815965) |
+| 21 | [`8a6b45c`](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44414786481) | [`cbf3e88`](https://github.com/easy-4-java/opencli-java-sdk/commit/cbf3e886678b79e1f7c7d6e9eb2d760cc2c5675f) | 2,263 | 3950/4252(92.90%) | [CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44415817737) |
+
+旧平台基线的 Windows 和 Ubuntu 各执行四个具名 Bridge 用例。当前 C04 候选用各线 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,全部退出 0,零失败、错误或跳过。新增三项旧版 HTTP 否定用例均断言服务端请求数为零。专项证据与真实平台执行清单由各次 CI 报告提供。
+
+以未改写的已安装 OpenCLI 1.8.8 重跑三条 C04 候选,使用锁定 opencli-admin Agent、回环 HTTP 和该包接受的默认 Bridge 端口参数 19825。三个 Java 探针均通过实际 CLI 帮助、缺少必需位置参数时的业务失败、显式原文捕获三项。旧版端口参数 61735 在这份已安装包中被 CLI 明确拒绝,退出 78。回环复验未调用 npm 注册表或浏览器。
+
+独立复审核对 59 项 ID 与 Java 17 固定源码链接,复核缺值选项的零派发证据并技术认可 Java 17 先实现、再移植到另外两线。D1 的正式确认及归档按既有流程处理。
+
+### C04 候选托管报告
+
+上表三个候选的 GitHub workflow 都已完成且结论为 success。逐份核对 10 份平台报告、6 份真实 Bridge 报告和 Java 17 全量 JVM 报告。每份均记录对应候选的精确 SHA 和退出 0,必选套件零失败、零错误、零跳过。
+
+| 报告 | 份数 | 枚举 | argv | 进程 | 协议 | 类型结果 | 真实执行 |
+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
+| Windows、Ubuntu、macOS 平台契约 | 10 | 15 | 53 | 48 | 103 | 16 | 未执行 |
+| Windows、Ubuntu 的 Browser Bridge | 6 | 未执行 | 未执行 | 未执行 | 未执行 | 未执行 | 4 |
+| Java 17 Ubuntu 全量 JVM 契约 | 1 | 25 | 52 | 46 | 103 | 16 | 未执行 |
+
+计数是每份报告的实际执行数量。Browser Bridge 的 `missingCases` 均为空。Java 17 的 [常规全量 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44415827590) 也通过。上表的三项候选已分别快进到现有 `test/20261119-1.0.x`、`test/20261119-2.0.x`、`test/20261119-3.0.x`,GitHub refs 已核对。
+
+## C01 ARGV
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-ARGV-001 | [`c93a25c`](https://github.com/easy-4-java/opencli-java-sdk/commit/c93a25c182f0b0acd15cdfa01089599b52601854) | [`OpenCliArgvContractTest#rawMergePreservesEmptyAndPaddedValues`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L142) · [`OpenCliArgvContractTest#nullRawTokenIsRejectedWithoutLeakingOtherTokens`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L160) |
+| OC-ARGV-002 | [`48b1438`](https://github.com/easy-4-java/opencli-java-sdk/commit/48b14388bc1c86fcf1dff2705f0140a541a3fa75), [`0151322`](https://github.com/easy-4-java/opencli-java-sdk/commit/01513226e14c4e73e0ed602332285d407a1489a9) | [`OpenCliArgvContractTest#structuredPositionalsAndValuesReachChildUnchanged`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L125) · [`OpenCliProcessContractTest#queuedInvocationUsesItsArgvSnapshotAfterCallerMutation`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L331) |
+| OC-ARGV-003 | [`48b1438`](https://github.com/easy-4-java/opencli-java-sdk/commit/48b14388bc1c86fcf1dff2705f0140a541a3fa75), [`4fa19df`](https://github.com/easy-4-java/opencli-java-sdk/commit/4fa19df2e0617f142a94fda5a0ca03a5c0d51aeb) | [`OpenCliStructuredArgvContractTest#orderedRepeatedValuesAndExplicitFalseReachChild`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java#L87) · [`OpenCliStructuredArgvContractTest#flagSchemaCannotSilentlyConsumeAValue`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java#L110) · [`OpenCliStructuredArgvContractTest#aNegatableOptionReservesBothSpellingsAcrossAllOccurrences`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredArgvContractTest.java#L135) |
+| OC-ARGV-004 | [`6f830b4`](https://github.com/easy-4-java/opencli-java-sdk/commit/6f830b4f2e5b87bb57eb6b3b669fd299ee48ee39), [`4fa19df`](https://github.com/easy-4-java/opencli-java-sdk/commit/4fa19df2e0617f142a94fda5a0ca03a5c0d51aeb) | [`OpenCliArgvContractTest#literalQuotesAndAdjacentBackslashesReachChildUnchanged`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L117) · [`OpenCliArgvContractTest#strictWindowsLauncherRejectsQuotesAndStillAcceptsUnambiguousArguments`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L177) |
+| OC-ARGV-005 | [`cdc8b66`](https://github.com/easy-4-java/opencli-java-sdk/commit/cdc8b66e74730ab1ed99a9f24a077f9077d2dbf5), [`1369aa1`](https://github.com/easy-4-java/opencli-java-sdk/commit/1369aa1cfca1dc2a6b093895c67ee6e1e6698446) | [`OpenCliArgvContractTest#structuredPositionalsAndValuesReachChildUnchanged`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L125) · [`OpenCliArgvContractTest#typedBrowserFillCanClearAField`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L135) |
+
+## C02 PROC
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-PROC-001 | [`98e3db1`](https://github.com/easy-4-java/opencli-java-sdk/commit/98e3db1f8883b8485ec8a428238173dc1148dfb4), [`dd4f395`](https://github.com/easy-4-java/opencli-java-sdk/commit/dd4f395296821bb036730b09c8bfbc2d380d064e) | [`OpenCliProcessContractTest#anotherClientCannotReplaceAnActiveClientsLimiter`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L182) · [`OpenCliProcessContractTest#sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L372) |
+| OC-PROC-002 | [`98e3db1`](https://github.com/easy-4-java/opencli-java-sdk/commit/98e3db1f8883b8485ec8a428238173dc1148dfb4) | [`OpenCliProcessContractTest#queuedDeadlineExpiresWithoutSpawning`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L205)
队列到期有真实子进程证据。时间源核对 `SubprocessExecutionSupport#remaining` 使用 `System.nanoTime`。实机墙上时钟跳变未单独执行。 |
+| OC-PROC-003 | [`98e3db1`](https://github.com/easy-4-java/opencli-java-sdk/commit/98e3db1f8883b8485ec8a428238173dc1148dfb4), [`9d2b43b`](https://github.com/easy-4-java/opencli-java-sdk/commit/9d2b43bc115e89a728c53fb066fa023c99cc56a5) | [`OpenCliProcessContractTest#stdoutDefaultBudgetFailsInsteadOfReturningUnboundedSuccess`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L240) · [`OpenCliProcessContractTest#stderrHasItsOwnSmallerBudget`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L253) · [`OpenCliProcessBoundaryTest#utf8TruncationReportsBytesNotReencodedCharacters`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessBoundaryTest.java#L51) |
+| OC-PROC-004 | [`98e3db1`](https://github.com/easy-4-java/opencli-java-sdk/commit/98e3db1f8883b8485ec8a428238173dc1148dfb4), [`a164812`](https://github.com/easy-4-java/opencli-java-sdk/commit/a164812beb68a8fe9306f9659d50760cd59257f5) | [`OpenCliProcessContractTest#interruptionStopsTheOwnedHeartbeatAndRestoresFlag`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L263) · [`OpenCliBrowserBridgeIT#boundedNetworkFollowLeavesTheRealBridgeAndPageAvailable`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserBridgeIT.java#L129) |
+| OC-PROC-005 | [`a41f548`](https://github.com/easy-4-java/opencli-java-sdk/commit/a41f548555d02fe3e31e42dee831bc6687f40ded), [`75160c6`](https://github.com/easy-4-java/opencli-java-sdk/commit/75160c63484a179805333b0a368d7cc69fc54723), [`6874340`](https://github.com/easy-4-java/opencli-java-sdk/commit/687434062f48d723ee6d2e7b331a9b7512e34eb9) | [`OpenCliProcessContractTest#cancelledParentPreservesUntrackedDescendantWithinCleanupBudget`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L438) · [`SubprocessCleanupFaultTest#unconfirmedForcedStopQuarantinesRuntimeWithoutFabricatingExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java#L126) · [`SubprocessCompletionRaceTest#simultaneousSignalsKeepOneResultAndReuseThePermit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCompletionRaceTest.java#L31) |
+| OC-PROC-006 | [`bf4f078`](https://github.com/easy-4-java/opencli-java-sdk/commit/bf4f0787f4106eecb94e24369dcfd13bcde7f873) | [`OpenCliProcessContractTest#networkFollowRejectsDisabledDeadlineBeforeSpawning`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L119) · [`OpenCliProcessContractTest#networkFollowReturnsCapturedEventsAfterNormalExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L88) · [`OpenCliProcessContractTest#networkFollowReportsTheCliExitCode`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliProcessContractTest.java#L109) · [`OpenCliBrowserBridgeIT#boundedNetworkFollowLeavesTheRealBridgeAndPageAvailable`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserBridgeIT.java#L129) |
+
+## C03 ERR
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-ERR-001 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60) | [`OpenCliErrorEnvelopeTest#decodesCapturedYamlAndKeepsAutoFixOnlyInRawStderr`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L35) · [`OpenCliErrorEnvelopeTest#rejectsUnsafeDocumentsAndDistinguishesOrdinaryDiagnostics`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L89) |
+| OC-ERR-002 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60), [`ff75cd7`](https://github.com/easy-4-java/opencli-java-sdk/commit/ff75cd73b20c4440bea66dc17646164c0bf36034) | [`OpenCliErrorEnvelopeTest#strictJsonPreservesUnknownFieldsAndTraceWithoutReadingIt`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L50) |
+| OC-ERR-003 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60), [`106585e`](https://github.com/easy-4-java/opencli-java-sdk/commit/106585e16ea67c6bfde5fc827b1913e4bc73cec9) | [`OpenCliErrorEnvelopeTest#equivalentYamlAndJsonPreserveWireTypesAndExitProvenance`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L65) · [`SubprocessCleanupFaultTest#unconfirmedForcedStopQuarantinesRuntimeWithoutFabricatingExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/support/SubprocessCleanupFaultTest.java#L126) |
+| OC-ERR-004 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60), [`3c0c179`](https://github.com/easy-4-java/opencli-java-sdk/commit/3c0c1793733c8091a47bf538be68ee699ea2a89a) | [`OpenCliErrorEnvelopeTest#rejectsUnsafeDocumentsAndDistinguishesOrdinaryDiagnostics`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L89) · [`OpenCliErrorEnvelopeTest#malformedYamlRetainsRawStderrWithoutExposingParserDetails`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L125) |
+| OC-ERR-005 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60), [`a2b2268`](https://github.com/easy-4-java/opencli-java-sdk/commit/a2b226875bf584289cde63d7b18bd8e3cc5dae23) | [`OpenCliErrorEnvelopeTest#incompleteTimeoutKeepsPrimaryFailure`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L171) · [`OpenCliRemoteAgentHttpClientTest#disconnectAfterAcceptingCollectDoesNotReplayOrInventAnExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L749) |
+| OC-ERR-006 | [`f52262e`](https://github.com/easy-4-java/opencli-java-sdk/commit/f52262ec6565db6ce84b907be4df20b4c182de60), [`ff75cd7`](https://github.com/easy-4-java/opencli-java-sdk/commit/ff75cd73b20c4440bea66dc17646164c0bf36034) | [`OpenCliErrorEnvelopeTest#realSubprocessPreservesFailureAndDoesNotFollowRetrySuggestion`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L104) · [`OpenCliErrorEnvelopeTest#equivalentYamlAndJsonPreserveWireTypesAndExitProvenance`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L65)
JSON 为本地协议样本,真实上游失败由 YAML 工件证明。 |
+
+## C04 REMOTE
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-REMOTE-001 | [`a5448e1`](https://github.com/easy-4-java/opencli-java-sdk/commit/a5448e1fdc40f26d3931e98bee7919dc7eef1c67), [`88d4eab`](https://github.com/easy-4-java/opencli-java-sdk/commit/88d4eabfc88a02e20623c50fd7d9b2d61e7c707d) | [`OpenCliRemoteAgentHttpClientTest#losslessAdapterRequestReachesLegacyEndpoint`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L802) · [`OpenCliRemoteAgentHttpClientTest#externalPassthroughCannotBeRoutedAsAnAdapter`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L834)
独立 Agent 和 TLS 代理见 C04 专项记录。 |
+| OC-REMOTE-002 | [`a5448e1`](https://github.com/easy-4-java/opencli-java-sdk/commit/a5448e1fdc40f26d3931e98bee7919dc7eef1c67), [`360cbc5`](https://github.com/easy-4-java/opencli-java-sdk/commit/360cbc5afe25eb72f352bff1166834850bc20acd) | [`OpenCliRemoteAgentHttpClientTest#unrepresentableArgvIsRejectedBeforeHttp`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L825) · [`OpenCliArgvToCollectParserFullTest#shouldRejectAnOptionWithoutAValueBeforeAnotherOption`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliArgvToCollectParserFullTest.java#L10) |
+| OC-REMOTE-003 | [`106585e`](https://github.com/easy-4-java/opencli-java-sdk/commit/106585e16ea67c6bfde5fc827b1913e4bc73cec9), [`a2b2268`](https://github.com/easy-4-java/opencli-java-sdk/commit/a2b226875bf584289cde63d7b18bd8e3cc5dae23) | [`OpenCliRemoteAgentHttpClientTest#collectFailureIncludesRawBodyWhenEnabled`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L116) · [`OpenCliRemoteAgentHttpClientTest#httpFailureRetainsItsStatusWithoutCreatingAProcessExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L386) · [`OpenCliRemoteAgentHttpClientTest#disconnectAfterAcceptingCollectDoesNotReplayOrInventAnExit`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L749) |
+| OC-REMOTE-004 | [`cf9360e`](https://github.com/easy-4-java/opencli-java-sdk/commit/cf9360e99647c935d7ee10c87a391ed602647682), [`106585e`](https://github.com/easy-4-java/opencli-java-sdk/commit/106585e16ea67c6bfde5fc827b1913e4bc73cec9) | [`OpenCliRemoteAgentHttpClientTest#invalidLegacyEnvelopeIsAProtocolFailure`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L875) · [`OpenCliRemoteAgentHttpClientTest#explicitSuccessfulReplyCanOmitItems`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L845) |
+| OC-REMOTE-005 | [`8d826a1`](https://github.com/easy-4-java/opencli-java-sdk/commit/8d826a11a5f56c926c1df4946e07390caa65dc0c), [`bf05ba6`](https://github.com/easy-4-java/opencli-java-sdk/commit/bf05ba69dbaaa27002c874ce72b4bee2707c3f64) | [`OpenCliRemoteAgentHttpClientTest#totalDeadlineStopsAnActiveChunkedResponseAndDoesNotRetry`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L148) · [`OpenCliRemoteAgentHttpClientTest#stopsReadingOversizedChunkedBodiesWithoutWaitingForEof`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L251) · [`OpenCliRemoteAgentHttpClientTest#capsDecodedGzipBodyRatherThanCompressedContentLength`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L290) |
+| OC-REMOTE-006 | [`b40ed5a`](https://github.com/easy-4-java/opencli-java-sdk/commit/b40ed5a91ed357478fe0f05b4936e4ac3508ec31), [`88d4eab`](https://github.com/easy-4-java/opencli-java-sdk/commit/88d4eabfc88a02e20623c50fd7d9b2d61e7c707d) | [`OpenCliRemoteAgentHttpClientTest#authenticationHeaderIsSentOnlyOverVerifiedTls`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L416) · [`OpenCliRemoteAgentHttpClientTest#rejectsConfiguredAuthenticationOnPlainHttpBeforeDispatch`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L489) · [`OpenCliRemoteAgentHttpClientTest#rejectsSecretsInAnAgentBaseUrlBeforeDispatch`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L506)
生产环境的真实认证配置需在部署时验收。 |
+
+## C05 WS
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-WS-001 | [`55b31d4`](https://github.com/easy-4-java/opencli-java-sdk/commit/55b31d452ae1919725e987d05add4cc466793bc0), [`e2b956c`](https://github.com/easy-4-java/opencli-java-sdk/commit/e2b956c5dcdea91c5c7c5bb3b3afeded57c0da87) | [`OpenCliWsReverseAgentSessionTest#collectBeforeRegistrationAcknowledgementDoesNotStartChild`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L266) · [`OpenCliWsReverseAgentSessionTest#trailingJsonCannotAcknowledgeRegistration`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L285) |
+| OC-WS-002 | [`ec49fff`](https://github.com/easy-4-java/opencli-java-sdk/commit/ec49fffb39915d04fe93bd3efed134ab79eab36b) | [`OpenCliWsReverseAgentSessionTest#defaultsToFourActiveCollects`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L425) · [`OpenCliWsReverseAgentSessionTest#rejectsOverflowWithoutLaunchingAnotherChild`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L462) |
+| OC-WS-003 | [`599ce1d`](https://github.com/easy-4-java/opencli-java-sdk/commit/599ce1dcb69c6910c6d4d31231b420421830e735) | [`OpenCliWsReverseAgentSessionTest#rejectsInvalidRequestIdsBeforeExecution`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L631) · [`OpenCliWsReverseAgentSessionTest#duplicateRequestRunsOnceAndReplaysCompletedResult`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L595) |
+| OC-WS-004 | [`599ce1d`](https://github.com/easy-4-java/opencli-java-sdk/commit/599ce1dcb69c6910c6d4d31231b420421830e735) | [`OpenCliWsCollectRequestsTest#evictsAndExpiresCompletedResultsWithoutDroppingActiveReservations`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsCollectRequestsTest.java#L19) · [`OpenCliWsReverseAgentSessionTest#duplicateRequestRunsOnceAndReplaysCompletedResult`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L595)
缓存属于当前实例,未执行跨进程重启复跑。 |
+| OC-WS-005 | [`599ce1d`](https://github.com/easy-4-java/opencli-java-sdk/commit/599ce1dcb69c6910c6d4d31231b420421830e735), [`76e92d4`](https://github.com/easy-4-java/opencli-java-sdk/commit/76e92d47469355effe49560e6e929ac231d9a941), [`8c3e96c`](https://github.com/easy-4-java/opencli-java-sdk/commit/8c3e96c3c443e94e728f91e3df545dd146b815f3) | [`OpenCliWsReverseAgentSessionTest#plainWebSocketReconnectDoesNotExposePreviousSessionCache`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L660) · [`OpenCliWsReverseAgentSessionTest#verifiedTlsReconnectReplaysOnlyAfterAnExplicitRetry`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L666) |
+| OC-WS-006 | [`e933045`](https://github.com/easy-4-java/opencli-java-sdk/commit/e9330452418cbbc47351100b249735b9c3a52bb9), [`0b88820`](https://github.com/easy-4-java/opencli-java-sdk/commit/0b888208173bb1d6e4f4f9729ac750d27ae81f85) | [`OpenCliWsReverseAgentSessionTest#closeDropsQueuedCollectsAndRejectsRestart`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L564) · [`OpenCliWsReverseAgentSessionTest#restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L517) · [`OpenCliWsReverseAgentSessionTest#disconnectAndCloseReleaseBoundedWorkerResources`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L347) |
+
+## C06 CAP
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-CAP-001 | [`1ff6377`](https://github.com/easy-4-java/opencli-java-sdk/commit/1ff63779142004331660da11226aaa3e53b5dd44) | [`OpenCliStructuredHelpFixtureTest#preservesBrowserSessionPlaceholdersAndOptionScopes`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliStructuredHelpFixtureTest.java#L49) · [`OpenCliHelpParserTest#decodesRealSnapshotsWithoutMergingScopes`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliHelpParserTest.java#L20) |
+| OC-CAP-002 | [`441122f`](https://github.com/easy-4-java/opencli-java-sdk/commit/441122f129822c70126390331853d28d64faa66c) | [`OpenCliCapabilityCommandTest#bindsSessionAndPreservesOptionalPresenceNegationAndExplicitFalse`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommandTest.java#L17) · [`OpenCliCapabilityCommandTest#rejectsInvalidChoiceMissingSessionAndRequiredValue`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommandTest.java#L31) |
+| OC-CAP-003 | [`441122f`](https://github.com/easy-4-java/opencli-java-sdk/commit/441122f129822c70126390331853d28d64faa66c) | [`OpenCliCapabilityDiscoveryTest#invokesBoundBrowserLeafThroughLocalExecutor`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L310) · [`OpenCliCapabilityCommandTest#rejectsInvalidChoiceMissingSessionAndRequiredValue`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommandTest.java#L31) |
+| OC-CAP-004 | [`b22796f`](https://github.com/easy-4-java/opencli-java-sdk/commit/b22796f3c4c0b7688fafb42ad26dbaa5a1078f25), [`532cf67`](https://github.com/easy-4-java/opencli-java-sdk/commit/532cf673b7ecf7b337e09c3b50c36a0b4ded9f1c), [`b77a6c7`](https://github.com/easy-4-java/opencli-java-sdk/commit/b77a6c771da624ec80145cb8ae49a6d3c58dc0be) | [`OpenCliCapabilityDiscoveryTest#configAndVersionChangesInvalidateCachedHelp`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L180) · [`OpenCliCapabilityOverrideIT#localAndPluginOverridesRefreshWithoutClaimingOriginOrExecutingHandler`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliCapabilityOverrideIT.java#L26) |
+| OC-CAP-005 | [`b22796f`](https://github.com/easy-4-java/opencli-java-sdk/commit/b22796f3c4c0b7688fafb42ad26dbaa5a1078f25), [`532cf67`](https://github.com/easy-4-java/opencli-java-sdk/commit/532cf673b7ecf7b337e09c3b50c36a0b4ded9f1c), [`a6b59b5`](https://github.com/easy-4-java/opencli-java-sdk/commit/a6b59b54c3a099bd72d79256d307e3b409d014a7) | [`OpenCliCapabilityDiscoveryTest#plainHelpLeavesLocalInvocationAvailable`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L72) · [`OpenCliCapabilityDiscoveryTest#staleFallbackRetainsObservationAndRefreshEvidence`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L147) |
+| OC-CAP-006 | [`b22796f`](https://github.com/easy-4-java/opencli-java-sdk/commit/b22796f3c4c0b7688fafb42ad26dbaa5a1078f25), [`a6b59b5`](https://github.com/easy-4-java/opencli-java-sdk/commit/a6b59b54c3a099bd72d79256d307e3b409d014a7) | [`OpenCliCapabilityDiscoveryTest#rootProbePreservesUnknownSourceAndUsesOnlyDescriptiveCommands`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L29) · [`OpenCliCapabilityDiscoveryTest#slowHelpReturnsTimeoutWithinTheConfiguredProbeBudget`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java#L135) · [`OpenCliReadOnlyDiagnosticsIT#diagnosticsBypassTheOpenCliStartupHook`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliReadOnlyDiagnosticsIT.java#L26)
用户显式调用 help 探测时,上游 CLI 可执行本地已安装插件的启动钩子。 |
+
+## C07 BROWSER
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-BROWSER-001 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`115b095`](https://github.com/easy-4-java/opencli-java-sdk/commit/115b0955b846290b4c91f6ae5aee91c10e262ae3), [`c12df8d`](https://github.com/easy-4-java/opencli-java-sdk/commit/c12df8d95ce04fa367d1db24a16ccff1c9923d21) | [`OpenCliBrowserResultTest#parsesPinnedArrayAndObjectAsTheirOwnContracts`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L30) · [`OpenCliBrowserBridgeIT#typedResultsFromAnIsolatedChromePage`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserBridgeIT.java#L41) · [`OpenCliBrowserBridgeIT#queryAndCaptureUseTheRealBridgeResponses`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserBridgeIT.java#L72) |
+| OC-BROWSER-002 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`3138332`](https://github.com/easy-4-java/opencli-java-sdk/commit/313833273bd3324bf67999899247f43a9b004269) | [`OpenCliBrowserResultTest#malformedTruncatedAndWrongLeafCannotBecomeEmptySuccess`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L69) · [`OpenCliErrorEnvelopeTest#typedBrowserListPreservesProcessFailureEvenWithAnEmptyArray`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L150) |
+| OC-BROWSER-003 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`115b095`](https://github.com/easy-4-java/opencli-java-sdk/commit/115b0955b846290b4c91f6ae5aee91c10e262ae3) | [`OpenCliBrowserResultTest#retainsLosslessIdentifiersAndUnknownMetadata`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L52) · [`OpenCliBrowserEvidenceResultTest#findsLimitedAndLosslessMatches`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserEvidenceResultTest.java#L23) |
+| OC-BROWSER-004 | [`b1d8386`](https://github.com/easy-4-java/opencli-java-sdk/commit/b1d83867be42854994d6443ce7be8fad4cb827c5) | [`OpenCliBrowserResultTest#typedSnapshotRejectsMissingSourceAndRawPreservesFutureSource`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L166) · [`OpenCliBrowserResultTest#decodesDomAndAxTextAndPreservesSnapshotBody`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L108) |
+| OC-BROWSER-005 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`115b095`](https://github.com/easy-4-java/opencli-java-sdk/commit/115b0955b846290b4c91f6ae5aee91c10e262ae3) | [`OpenCliBrowserResultTest#retainsLosslessIdentifiersAndUnknownMetadata`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L52) · [`OpenCliBrowserEvidenceResultTest#retainsAnalysisMetadataWithoutFollowingAdvice`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserEvidenceResultTest.java#L68)
保留提示和文件位置作为数据,仍无已验证的 sitemap 公共字段契约。 |
+| OC-BROWSER-006 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`807801e`](https://github.com/easy-4-java/opencli-java-sdk/commit/807801e785d5fa5ffd9607165f44ae0e1faa6e07) | [`OpenCliBrowserResultTest#typedSessionMethodsUseExistingBrowserCommandsAndKeepCloseResult`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L84) · [`OpenCliBrowserBridgeIT#boundTabSurvivesTypedSuccessFailureAndClientShutdown`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserBridgeIT.java#L100) |
+
+## C08 CTX
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-CTX-001 | [`2eb97e4`](https://github.com/easy-4-java/opencli-java-sdk/commit/2eb97e4998f9c97d8467aedad664df6cf6bf8508), [`a4687d1`](https://github.com/easy-4-java/opencli-java-sdk/commit/a4687d1bb9bb9018b54b1e5809099a55561c2eab), [`84ffb50`](https://github.com/easy-4-java/opencli-java-sdk/commit/84ffb507cb119447426f69496ec73b5e83e638bc) | [`OpenCliInvocationContextTest#concurrentInvocationsKeepTheirProfileAndWindow`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliInvocationContextTest.java#L29) · [`OpenCliInvocationContextTest#failedInvocationKeepsItsContextWithoutChangingConcurrentOrDefaultCalls`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliInvocationContextTest.java#L42) |
+| OC-CTX-002 | [`2eb97e4`](https://github.com/easy-4-java/opencli-java-sdk/commit/2eb97e4998f9c97d8467aedad664df6cf6bf8508) | [`OpenCliInvocationContextTest#rejectsUnsupportedScopesAndConflictingExplicitOptions`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliInvocationContextTest.java#L86) · [`OpenCliInvocationContextTest#explicitFalseOverridesClientDefaultWithinVerifiedBrowserAdapter`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliInvocationContextTest.java#L70) |
+| OC-CTX-003 | [`3c9979e`](https://github.com/easy-4-java/opencli-java-sdk/commit/3c9979ecbd48b0f6ea4fcbb79c920095fefdd1e6) | [`OpenCliDiagnosticsTest#remoteModeSkipsLocalProbesAndRelativeExecutablesAreUnverified`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliDiagnosticsTest.java#L76) · [`OpenCliDiagnosticsTest#failedHelpRemainsUnknownAndSuccessfulPriorHelpIsHistorical`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliDiagnosticsTest.java#L45) |
+| OC-CTX-004 | [`3c9979e`](https://github.com/easy-4-java/opencli-java-sdk/commit/3c9979ecbd48b0f6ea4fcbb79c920095fefdd1e6) | [`OpenCliDiagnosticsTest#versionProbeDoesNotRunHelpDoctorAuthOrDaemonCommands`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/capability/OpenCliDiagnosticsTest.java#L26) · [`OpenCliReadOnlyDiagnosticsIT#diagnosticsBypassTheOpenCliStartupHook`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliReadOnlyDiagnosticsIT.java#L26)
未使用真实过期凭据。默认诊断报告认证状态未知。 |
+| OC-CTX-005 | [`f2feb18`](https://github.com/easy-4-java/opencli-java-sdk/commit/f2feb1868b90964848830526c227ddfecbd56332), [`115b095`](https://github.com/easy-4-java/opencli-java-sdk/commit/115b0955b846290b4c91f6ae5aee91c10e262ae3), [`3c9979e`](https://github.com/easy-4-java/opencli-java-sdk/commit/3c9979ecbd48b0f6ea4fcbb79c920095fefdd1e6) | [`OpenCliBrowserResultTest#retainsLosslessIdentifiersAndUnknownMetadata`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserResultTest.java#L52) · [`OpenCliBrowserEvidenceResultTest#retainsAnalysisMetadataWithoutFollowingAdvice`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliBrowserEvidenceResultTest.java#L68) |
+| OC-CTX-006 | [`3c9979e`](https://github.com/easy-4-java/opencli-java-sdk/commit/3c9979ecbd48b0f6ea4fcbb79c920095fefdd1e6) | 能力矩阵把 JS pipeline 标为 DEFERRED。当前 Java 门面没有公开 pipeline 调用。 |
+
+## C09 PRIV
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-PRIV-001 | [`09a8f60`](https://github.com/easy-4-java/opencli-java-sdk/commit/09a8f60fbae91eee66342c7bfdf6a2d108c6e370), [`c6dc643`](https://github.com/easy-4-java/opencli-java-sdk/commit/c6dc6437f4673182eec1cd99209a8246b392b65d) | [`OpenCliProcessPrivacyTest#preservesStderrOnNonzeroExitWithoutLeakingArgsOrStderr`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java#L41) · [`OpenCliProcessPrivacyTest#adapterDebugLogsOnlyArgumentCount`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java#L82) |
+| OC-PRIV-002 | [`f3022d4`](https://github.com/easy-4-java/opencli-java-sdk/commit/f3022d42b8db38a9c1804cf98332a9370704c26a), [`6894071`](https://github.com/easy-4-java/opencli-java-sdk/commit/6894071f0c698114aa507f79c2533352f48ae436) | [`OpenCliRemoteAgentHttpClientTest#nonSuccessHttpResponseDoesNotExposeBodyCanaryInException`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L539) · [`OpenCliRemoteAgentHttpClientTest#responseCloseFailureProtectsProviderDetailsAndPrimaryOutcome`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L605) · [`OpenCliErrorEnvelopeTest#malformedYamlRetainsRawStderrWithoutExposingParserDetails`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L125) |
+| OC-PRIV-003 | [`6894071`](https://github.com/easy-4-java/opencli-java-sdk/commit/6894071f0c698114aa507f79c2533352f48ae436), [`1946d9f`](https://github.com/easy-4-java/opencli-java-sdk/commit/1946d9f5cc346283e1320e58d945286b69916f69) | [`OpenCliRemoteAgentHttpClientTest#collectSuccessOmitsRawBodyWhenDisabled`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L98) · [`OpenCliRemoteAgentHttpClientTest#collectSuccessCapturesRawBodyWhenEnabled`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L77) · [`OpenCliProcessPrivacyTest#preservesStderrOnNonzeroExitWithoutLeakingArgsOrStderr`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java#L41) |
+| OC-PRIV-004 | [`0b7091c`](https://github.com/easy-4-java/opencli-java-sdk/commit/0b7091c0aa9d79e666c219984d31fd66324e34d6), [`09a8f60`](https://github.com/easy-4-java/opencli-java-sdk/commit/09a8f60fbae91eee66342c7bfdf6a2d108c6e370) | [`OpenCliRemoteAgentHttpClientTest#malformedHttpEndpointDoesNotExposeCredentialsInPublicStackTrace`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L720) · [`OpenCliProcessPrivacyTest#keepsMissingExecutablePathOutOfLogsAndStackTrace`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java#L30) · [`OpenCliErrorEnvelopeTest#strictJsonPreservesUnknownFieldsAndTraceWithoutReadingIt`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L50) |
+| OC-PRIV-005 | [`72abff8`](https://github.com/easy-4-java/opencli-java-sdk/commit/72abff8d0d09918922886aef364a3b85c14f4d09) | [`OpenCliDiagnosticExportTest#explicitProjectionExcludesPayloadsAndLeavesResultIntact`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliDiagnosticExportTest.java#L16) · [`OpenCliDiagnosticExportTest#exactFitAndOneByteShortUseConsistentTruncationMarkers`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliDiagnosticExportTest.java#L52)
显式安全投影交给调用者,SDK 无持久化或上传入口。 |
+| OC-PRIV-006 | [`c327bc5`](https://github.com/easy-4-java/opencli-java-sdk/commit/c327bc5e97e6fa691463621cf246e0246763247f), [`ddfa6c8`](https://github.com/easy-4-java/opencli-java-sdk/commit/ddfa6c8989464c0df1f23b98ea95b28165bbf3a9), [`1946d9f`](https://github.com/easy-4-java/opencli-java-sdk/commit/1946d9f5cc346283e1320e58d945286b69916f69) | [`OpenCliProcessPrivacyTest#keepsArgumentsAndPartialStderrOutOfTimeoutDiagnostics`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/core/OpenCliProcessPrivacyTest.java#L105) · [`OpenCliWsReverseAgentSessionTest#providerErrorRetiresConnectionWithoutLoggingItsCause`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/center/ws/OpenCliWsReverseAgentSessionTest.java#L70) · [`OpenCliRemoteAgentHttpClientTest#responseItemsMappingFailureKeepsStatusAndProtectsDiagnostic`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClientTest.java#L624) |
+
+## C10 PARITY
+
+| Requirement | 实现或验证提交 | 测试与验收范围 |
+| --- | --- | --- |
+| OC-PARITY-001 | [`c4a6646`](https://github.com/easy-4-java/opencli-java-sdk/commit/c4a6646b9c8592bfae17cc641c74e031f4bcb7f4) | [`OpenCliArgvContractTest#structuredPositionalsAndValuesReachChildUnchanged`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliArgvContractTest.java#L125) · [`OpenCliErrorEnvelopeTest#equivalentYamlAndJsonPreserveWireTypesAndExitProvenance`](https://github.com/easy-4-java/opencli-java-sdk/blob/360cbc5afe25eb72f352bff1166834850bc20acd/src/test/java/io/github/easy4j/opencli/contract/OpenCliErrorEnvelopeTest.java#L65)
Java、Jackson、Maven 差异见验收账本。使用同一套测试输入比较三条线。 |
+| OC-PARITY-002 | [`d6e2da5`](https://github.com/easy-4-java/opencli-java-sdk/commit/d6e2da54d205b35c56787df17ebf7a7ef2497bad), [`ff9d999`](https://github.com/easy-4-java/opencli-java-sdk/commit/ff9d99934f655883a575d342e852d06bce03db08) | 锁定上游版本、归档 SHA-256、获取命令及逐项差异。各分支 CI 执行三个校验清单。 |
+| OC-PARITY-003 | [`6da93d0`](https://github.com/easy-4-java/opencli-java-sdk/commit/6da93d05102cd9ed334be8d67278fd67c2f9cbc9), [`20af24e`](https://github.com/easy-4-java/opencli-java-sdk/commit/20af24ed7b1e5733506ca8822ca0e04378a7e047), [`9610a0b`](https://github.com/easy-4-java/opencli-java-sdk/commit/9610a0bd782a18cfe543fc68961899c002c18e23) | 报告脚本回归要求分层和唯一归因。缺失、零用例或跳过会使必选测试证据失败。 |
+| OC-PARITY-004 | [`ed24945`](https://github.com/easy-4-java/opencli-java-sdk/commit/ed24945730f39e613813cc26116b195788ad2749), [`9610a0b`](https://github.com/easy-4-java/opencli-java-sdk/commit/9610a0bd782a18cfe543fc68961899c002c18e23) | 报告检查精确 SHA、实际工具版本、计数和退出码。复用旧报告、缺文件及缺任一 Bridge 用例均有反例。 |
+| OC-PARITY-005 | [`e5c745d`](https://github.com/easy-4-java/opencli-java-sdk/commit/e5c745d459707477061e298d48e5f47604253f9f), [`c4a6646`](https://github.com/easy-4-java/opencli-java-sdk/commit/c4a6646b9c8592bfae17cc641c74e031f4bcb7f4) | 按三条线的 POM、README、Maven/Gradle 示例、Wrapper 以及实际运行记录核对。 |
+| OC-PARITY-006 | [`c4a6646`](https://github.com/easy-4-java/opencli-java-sdk/commit/c4a6646b9c8592bfae17cc641c74e031f4bcb7f4) | 官方 OpenSpec strict 验证与实现门禁独立。最终评审和归档仍待完成。 |
diff --git a/openspec/changes/enforce-opencli-branch-contract-parity/tasks.md b/openspec/changes/enforce-opencli-branch-contract-parity/tasks.md
index f3ad8bac..94b2e26c 100644
--- a/openspec/changes/enforce-opencli-branch-contract-parity/tasks.md
+++ b/openspec/changes/enforce-opencli-branch-contract-parity/tasks.md
@@ -12,7 +12,7 @@
## 2. 上游与文档
-- [ ] 2.1 采集锁定上游的实际help/manifest/output,保存hash与范围,移除对作者绝对路径的依赖。
+- [x] 2.1 采集锁定上游的实际help/manifest/output,保存hash与范围,移除对作者绝对路径的依赖。
- [ ] 2.2 修正各分支README/POMdescription/Gradle示例,检查Java/Jackson/Maven实际声明。
- [ ] 2.3 配置三线正确wrapper/JDK的独立构建与报告,不通过修改coverage阈值绕开行为问题。
@@ -26,3 +26,32 @@
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+### 每个必选套件的执行证据
+
+OC-PARITY-003/004:当同一层含一个已执行套件及一个零用例套件时,旧报告返回 PASS。把同一套件注册到 argv 与 real-execution 也会重复记账。新增两个失败回归后,报告逐套件检查非零执行、零跳过、零失败及零错误,并拒绝同一套件跨层归因。问题套件列在 `unprovenSuites`。
+
+JVM 和平台报告显式登记错误报文、浏览器 typed 结果、上下文和诊断测试。Windows npm 安装版检查用独立 `installed-report.json`,保留实际 Node、OpenCLI、Java 和 Maven 版本、源码 SHA 与执行退出码。真实 CLI 层的范围为安装版 launcher 与隔离的 help、插件和诊断测试。普通 JVM 或平台报告缺少此层时保持 NOT_RUN。用于 Browser 结果解析的全部归档样本继续按 SHA-256 验证。
+
+### 2026-11-19 上游 manifest 采集
+
+OC-PARITY-002:从 npm 发布包提取 `package/cli-manifest.json`。源为 https://registry.npmjs.org/@jackwener/opencli/-/opencli-1.8.8.tgz,包的 SHA-512 完整性与 npm registry 元数据一致。原始 manifest 的 SHA-256 为 `b6f44ab5973dfd46b001f42562ad520b184bf1dd27ec4ae807f849df70b98e6a`。范围为发布包自带的 adapter 命令枚举,共 1,366 条、179 个 site。按 `(site, name)` 逐项对比仓库历史快照,新增 89 条,移除 0 条。89 条新增命令的逐项差异保存在本节链接的来源锁定中。
+
+在临时目录采集并运行生成器后,报告只记录公开来源、原始字节的 SHA-256、观察日期、获取命令和枚举范围。历史报告仍用于原有 Java 测试。生成器通过 `--manifest` 或 `OPENCLI_MANIFEST` 读取本地输入,移植验证覆盖含空格的临时路径。
+
+```bash
+curl -fsSLo opencli-1.8.8.tgz https://registry.npmjs.org/@jackwener/opencli/-/opencli-1.8.8.tgz
+tar -xOf opencli-1.8.8.tgz package/cli-manifest.json > cli-manifest.json
+```
+
+
+### OpenCLI 1.8.8 全量样本复跑
+
+[上游来源锁定](../../../src/test/resources/opencli-contracts/v1/upstream-1.8.8.lock.json) 记录 manifest 采集命令及逐项差异,以及帮助和浏览器输出的校验清单与复跑入口。使用 Node 24.18.0 和已安装的 1.8.8 包,在独立临时配置、缓存及用户目录中执行。11 份帮助、12 份浏览器叶子输出均与已归档的 stdout 逐字节相同,全部退出 0,stderr 为空。帮助包含非 JSON 输出。浏览器叶子使用真实 CLI 与隔离页面桩,真实浏览器联调证据单独见 [Browser Bridge 验收](../add-opencli-browser-result-models/evidence/2026-11-19-real-browser-bridge.md)。历史覆盖基线的升级仍须评审。
+
+
+### OC-PARITY-003 能力发现的必选报告
+
+独立评审确认 GitHub 的 JVM 报告漏列 `OpenCliCapabilityDiscoveryTest` 和 `OpenCliCapabilityCommandTest`。用原工作流的四组报告参数逐一重放,任一个能力套件的 XML 缺失、零用例或全跳过时,24 个反例仍返回成功。
+
+三线平台作业现在显式运行两个套件,在枚举层登记 DiscoveryTest,在 argv 层登记 CommandTest。Java 17 的完整 JVM 报告也登记这两个套件。使用现有 Surefire 结果重放更新后的四组参数,完整报告均退出 0,24 个反例均退出 1,准确标识缺失或未执行的套件。各线的报告脚本回归均通过 17 项。
diff --git a/openspec/changes/harden-opencli-argv-contract/tasks.md b/openspec/changes/harden-opencli-argv-contract/tasks.md
index fc170fd2..e9ff98ad 100644
--- a/openspec/changes/harden-opencli-argv-contract/tasks.md
+++ b/openspec/changes/harden-opencli-argv-contract/tasks.md
@@ -1,26 +1,51 @@
# C01 Tasks · 参数保真与统一调用契约
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已勾选项对应真实子进程契约及历史失败证据。保留 3.4 的评审和归档门禁。
关联规范:[spec](specs/opencli-argv-contract/spec.md)。
## 1. 失败测试
-- [ ] 1.1 在现有 core/support 测试区新增 Java argv echo fixture,覆盖空值、空白、Unicode、换行、-- 和重复 flag。
-- [ ] 1.2 先在实现前运行新增用例,保存真实失败输出;禁止只断言命令前缀。
+- [x] 1.1 在现有 core/support 测试区新增 Java argv echo fixture,覆盖空值、空白、Unicode、换行、-- 和重复 flag。
+- [x] 1.2 先在实现前运行新增用例,保存真实失败输出;禁止只断言命令前缀。
## 2. 最小实现
-- [ ] 2.1 统一 Executor/AdapterChannel/参数 helpers 的值保真路径,并对输入列表做快照。
-- [ ] 2.2 为 null/标识符错误建立不包含业务值的校验;增量支持有序 option occurrences 和 false 语义。
+- [x] 2.1 统一 Executor/AdapterChannel/参数 helpers 的值保真路径,并对输入列表做快照。
+- [x] 2.2 为 null/标识符错误建立不包含业务值的校验;增量支持有序 option occurrences 和 false 语义。
## 3. 迁移与验证
-- [ ] 3.1 补 List/varargs/typed/request 等价与用户列表不被修改的测试。
-- [ ] 3.2 检查 Windows launcher 与引号边界,未测试的平台明确保留未验证状态。
-- [ ] 3.3 分别在三条 feature 线运行共享 vectors 和现有测试,记录允许差异。
-- [ ] 3.4 评审迁移说明与完整 diff;需求通过后再申请 archive,不在文档阶段勾选。
+- [x] 3.1 补 List/varargs/typed/request 等价与用户列表不被修改的测试。
+- [x] 3.2 检查 Windows launcher 与引号边界,未测试的平台明确保留未验证状态。
+- [x] 3.3 分别在三条 feature 线运行共享 vectors 和现有测试,记录允许差异。
+- [x] 3.4 评审迁移说明与完整 diff;归档随最终集成验收申请。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## C01 实现与参数保真证据(2026-11-18)
+
+- OC-ARGV-001、002、004、005。提交 `cdc8b66e74730ab1ed99a9f24a077f9077d2dbf5` 只引入契约夹具。在独立源码目录用 JDK 17 运行 `mvn -B -ntp -o -Dtest=OpenCliArgvContractTest test`,33 项中 21 项失败,0 错误、0 跳过,退出 1。真实子进程收到的完整向量显示空值被丢弃、两端空白被裁剪,typed browser fill 也丢失用于清空字段的空字符串。
+- OC-ARGV-003。提交 `d02b16ddc5e0fe7c1d98c6847f4b2999cf2f2566` 用同一环境运行 `OpenCliStructuredArgvContractTest`,10 项中 10 项失败,0 错误、0 跳过,退出 1。可变 Map 与 StringBuilder 改写了实际 argv。当前实现支持显式 schema、有序重复选项、值型 false、否定 flag,拒绝歧义,旧 Map 继续使用历史语义。[历史 RED/GREEN 执行记录](https://github.com/easy-4-java/opencli-java-sdk/blob/01513226e14c4e73e0ed602332285d407a1489a9/docs/implementation/c10-c01-execution.md)
+- 当前本地回归覆盖完整向量、argv 第三项为 null、空白标识符、等号、引号、反斜杠、`--`、Unicode 和换行。新增排队变更回归。一个真实 JVM 占住共享许可,下一次调用完成列表快照后,调用方修改原列表并释放许可。回显子进程收到提交时的完整向量,调用方原列表只包含它自己所作修改。JDK 17 定向 45 项通过。
+- Windows 使用原生 `node.exe` 运行回显夹具,含空白、引号和末尾反斜杠的 token 保留。SDK 会在启动前拒绝 `.cmd`、`.bat` 批处理入口。JDK 17 曾运行真实安装包的启动器测试,仅执行只读元命令。对应 [JDK 8 平台 CI](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054705)、[JDK 17 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339055208/job/134923652889)、[JDK 21 Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44339054801) 与 [已安装启动器证据](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44313779366/job/134834399117)。
+- 三条维护线使用同一套已校验 SHA-256 的 `argv.tsv`、`ContractProbe` 和 `OpenCliStructuredArgvContractTest`。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,120 项通过,0 失败、0 错误、0 跳过,退出 0。本地报告为 `target/surefire-reports`。三个版本的 JDK/Jackson/Maven 允许差异见 fixture 的 `sources.lock.json`。远端分支最新 CI 单独记录于 PR。
+
+- 排队回归与原始参数回归共用回显启动配置。首次 JDK 17 Windows CI 使用旧 Java 回显启动器时,子进程把原始中文 token 收成 `???`。改用同套 Windows 原生 Node 回显夹具,继续断言完整 Unicode token,并保留 Java 生命周期进程作为许可占用方。[首次 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44340768729/job/134929785664)
+
+## 三线 JVM 兼容和迁移复核
+
+以 GitHub 现有目标分支 `feature/1.0.x` 的 `7726b51`、`feature/2.0.x` 的 `196206d`、`feature/3.0.x` 的 `e66f958` 为基线。各线用自己的 Wrapper 和 JDK 编译目标与候选代码,使用 JDK 21 的 `javap -protected -s` 比对已编译的 SDK 类。三个基线各有 151 个可见类型和 1,687 个公开或受保护的已声明成员。候选均保留这些类型声明和成员 JVM 描述符,未出现缩减访问级别的成员。此处核对的是 JVM 声明,参数行为由子进程用例和迁移说明验证。中英文 README 已补齐本地字面值、空参调用、旧 Map 布尔值和结构化否定选项的迁移差异。
+
+独立评审复现了 Windows 严格进程模式下潜在的字面引号降级,以及可否定选项混用否定别名的冲突。Java 17 基线 `75160c6` 的两项定向测试均失败。原生 EXE 的严格模式会在取得子进程前报告无法保真的参数索引,消息不含值,普通参数仍可执行。可否定 schema 同时保留正向名和否定别名,两种排列顺序和旧 Map 均不会发出冲突组合。
+
+修复后 Java 8、17、21 各用自己的 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,257、2,258、2,257 项,零失败、零错误、零跳过。仍待以新提交的 Windows 托管报告和独立复审作为 3.4 的最终依据。
+
+
+在上一轮候选 `a965392`、`4fa19df`、`4411a4b` 的三份 Windows 工件中,分别确认严格模式用例与否定别名用例真实执行并通过。随后独立复审发现严格模式还需覆盖名称以 `cmd.exe` 结尾的普通 EXE,以及无扩展名的原生启动名。启动检查现在按 basename 精确识别实际的 `cmd.exe`,以相同规则处理正反斜杠路径。两个路径变体和无扩展名用例均在模拟严格 Windows 启动器中断言未调用进程启动器。双语迁移说明已同步此边界。
+
+独立复审确认两类问题已解决。最终三线本地 Wrapper 全量分别执行 2,260、2,261、2,260 项,失败、错误、跳过均为 0。再次比对目标分支 JVM 声明,原有的 151 个类型和 1,687 个成员仍保留。C01 技术评审完成,当前 PR 仍按 C02 与 C10 的独立门禁推进。
+
+[Java 8 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44409386904) · [Java 17 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44409386886) · [Java 21 Windows 结果](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44409386943)
diff --git a/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md b/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
index 2f95b95c..efdefc6a 100644
--- a/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
+++ b/openspec/changes/harden-opencli-diagnostics-privacy/tasks.md
@@ -6,21 +6,85 @@
## 1. 泄露负例
-- [ ] 1.1 对Executor、AdapterChannel、HTTP、WS、JSON/YAML parser所有日志/异常点建立canary矩阵。
-- [ ] 1.2 新增完整日志捕获与nested cause测试,先证明当前泄露可被测试检测。
+- [x] 1.1 对Executor、AdapterChannel、HTTP、WS、JSON/YAML parser所有日志/异常点建立canary矩阵。见本页失败场景与 24 个日志调用点的证据。
+- [x] 1.2 新增完整日志捕获与nested cause测试,先证明当前泄露可被测试检测。
## 2. 安全投影
-- [ ] 2.1 将commandLine/args/bodyPreview/remote error输出改成允许表元数据与correlationId。
-- [ ] 2.2 实现安全异常摘要和cause处理,避免logger输出provider原始对象。
+- [x] 2.1 将commandLine/args/bodyPreview/remote error输出改成允许表元数据与correlationId。见本文日志调用点核对。
+- [x] 2.2 实现安全异常摘要和cause处理,避免logger输出provider原始对象。见本页的异常链、HTTP 清理及响应映射、WebSocket 故障注入回归。
- [ ] 2.3 保留raw业务结果与默认关闭的HTTPdebugcapture,新增显式有限export策略。
## 3. 验证
-- [ ] 3.1 覆盖DEBUG、timeout、malformedresponse、断线和超限路径,任何canary出现均失败。
+- [x] 3.1 覆盖DEBUG、timeout、malformedresponse、断线和超限路径,任何canary出现均失败。
- [ ] 3.2 验证raw结果内容未被脱敏逻辑无声修改。
-- [ ] 3.3 三线执行相同隐私矩阵并记录证据;文档标明SDK与应用日志责任边界。
+- [x] 3.3 三线执行相同隐私矩阵并记录证据;文档标明SDK与应用日志责任边界。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## 2026-11-19 C09 默认异常链与三线隐私矩阵
+
+JDK 17 两项定向红灯实际退出 1。选项对象的 `toString()` 抛出带嵌套 cause 和 suppressed 项的异常,栈文本泄露测试密钥。真实缺失可执行文件的低层 result handler 异常链泄露路径。修复后,值转换报告固定字段诊断,result handler 保留安全摘要。显式 `RunSession.getIoFailure()` 仍返回原始低层诊断。两项回归都扫描完整栈文本,保留原始数据的测试同时验证权限边界。
+
+| 场景 | 现有三线回归 |
+| --- | --- |
+| Adapter DEBUG、本地非零退出、超时、超限、原始 stdout/stderr | `OpenCliProcessPrivacyTest` |
+| 参数对象的嵌套 cause/suppressed、底层原生路径 | `OpenCliArgSupportTest`、`SubprocessExecutionSupportTest` |
+| HTTP 503、凭据 URL、畸形 JSON、原文捕获开关 | `OpenCliRemoteAgentHttpClientTest` |
+| WebSocket 断线和投递异常、配置 URL、日志测试密钥 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest` |
+| JSON 解析 DEBUG、默认不写入的有界导出 | `OpenCliStdoutJsonTest`、`OpenCliDiagnosticExportTest` |
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,133 项通过,0 失败、0 错误、0 跳过。中英文 README 记录应用显式访问原始低层诊断的责任。畸形 YAML 的验证见 C03 的隐私回归及下文。
+
+
+## 本地失败诊断关联
+
+OC-PRIV-001/004。OpenCliProcessPrivacyTest 的新用例在 Java 17 基线复现缺少 correlationId,退出 1。现在本地进程失败时由 SDK 生成随机 UUID,在 DEBUG 日志及返回的异常消息中使用同一值。日志只记录终止原因、退出码和捕获字节数。测试扫描捕获的日志和完整异常栈,同时通过 partialResult 校验 stderr 原值。C03 的 OpenCliErrorEnvelopeTest 覆盖含敏感标记的畸形 YAML,并确认解析器原文不进入默认诊断。
+
+Java 8、17、21 分别用各自 Wrapper 运行 OpenCliProcessPrivacyTest、OpenCliErrorEnvelopeTest 和 OpenCliProcessContractTest,每条线执行 31 项,零失败、零错误、零跳过。报告位于 target/surefire-reports。Java 21 的先前运行曾出现继承管道用例的 JUnit 临时目录清理竞态,本次重跑通过。该竞态需要独立处理。
+
+## SDK 配置对象的默认诊断
+
+OC-PRIV-001/004。Java 17 基线 `58f675a` 的两项回归均失败。输出 `OpenCliProperties` 或 `OpenCliWsAgentConnectionProperties` 时,Lombok 的默认字符串表示包含测试标记。改为显式允许表后,默认字符串只包含受控枚举、开关、字节预算和超时、并发等数值。CDP 地址、本地路径、启动参数、环境变量、WebSocket 地址和节点标签仍可通过各自的配置 API 读取和使用。
+
+实现分别基于 Java 8 `afc6b33`、Java 17 `58f675a`、Java 21 `5cfa937`。三线使用各自 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,242、2,243、2,242 项。失败、错误、跳过均为 0。两项新增测试记录在 `OpenCliPropertiesTest` 和 `OpenCliWsReverseAgentClientTest` 的 Surefire 报告中。随后同步的 Agent TLS 证据提交只触及 OpenSpec 材料。
+
+## 请求和请求构建器的默认诊断
+
+OC-PRIV-001/003/004。Java 17 基线 `c6dc643` 的两项回归均失败。HTTP 收集 DTO 和生成的构建器会将命令、选项、位置参数和 CDP 地址拼进字符串,结构化本地请求构建器也会拼入命令及参数。三个默认字符串只保留类型名称。请求值仍由原访问器和协议序列化读取,结构化命令生成相同的字面 argv。
+
+Java 8 `15ef02a`、Java 17 `c6dc643`、Java 21 `d0f0205` 为回归前基线。三线各自用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,244、2,245、2,244 项,零失败、零错误、零跳过。新增用例见 `OpenCliCollectRequestTest` 和 `OpenCliAdapterCommandRequestTest` 的 Surefire XML。全量回归同时覆盖 HTTP 线上字段和本地子进程调用。
+
+
+## WebSocket 连接关联与日志调用点核对
+
+OC-PRIV-001/004。Java 17 基线 `0b7091c` 的 TLS 重连用例中缺少连接关联 ID。实现为每次反向连接尝试生成独立 UUID,同一连接的建立、校验失败、回调、收集失败、投递失败和关闭失败日志复用该值。连接协议、业务结果和去重键各自沿用原值。TLS 回归注入包含测试标记的投递失败,验证原连接与失败日志共享 ID,重连使用新 ID,并保留显式重试和结果去重断言。
+
+Java 8 `cd1ceac`、Java 17 `0b7091c`、Java 21 `5bee58b` 是本轮修改前基线。三线各使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,244、2,245、2,244 项,零失败、零错误、零跳过。Java 17 修改前实际执行两个 TLS 参数用例,其中一个因缺少关联 ID 失败,修改后三线全量均通过。
+
+| SDK 发出日志的位置 | 调用点数 | 允许的动态值 | 运行证据 |
+| --- | ---: | --- | --- |
+| 本地执行器、适配器、浏览器命令入口 | 3 | 随机关联 ID、终止原因、退出码、字节数或参数个数 | `OpenCliProcessPrivacyTest` 与全量浏览器调用 |
+| JSON 输出检测、远端 argv 转换 | 2 | 长度或参数个数 | `OpenCliStdoutJsonTest`、`OpenCliArgvToCollectParserTest` |
+| HTTP 客户端 | 10 | 随机关联 ID、HTTP 状态、长度 | `OpenCliRemoteAgentHttpClientTest`,七个调用点实际执行 |
+| 反向 WebSocket 客户端 | 9 | 连接 UUID 或重连次数 | `OpenCliWsReverseAgentSessionTest`、`OpenCliWsReverseAgentClientTest`,七个调用点实际执行 |
+
+每线当前 JaCoCo 报告均覆盖 24 个 SDK 日志调用点中的 19 个。仍缺独立驱动 HTTP 请求序列化失败、外层 JSON 映射失败、HTTP transport 关闭失败、WebSocket onError 及 WebSocket 关闭抛异常的动态证据。源码核对确认这些日志也使用固定消息或 SDK 生成的 ID,JaCoCo 缺口由 1.1 和 2.2 继续跟踪。该核对限于 SDK 自身的日志调用与实测异常。
+
+## HTTP 资源关闭异常的隐私回归
+
+OC-PRIV-002/006。Java 17 基线 `ddfa6c8` 的四个定向用例有两个失败。无效响应的协议异常附带了原始 HTTP 响应关闭异常,公开异常栈包含测试标记。连接池关闭的运行时异常也直接暴露了标记。响应清理现在仅传播固定消息,协议失败保留主要类别和 HTTP 200。单独发生的响应关闭 I/O 故障保留传输失败及已观察到的状态,关闭超时沿用超时分类。连接池关闭失败使用固定日志。请求序列化的独立回归确认测试标记未出现在日志或异常栈,回环服务接收请求数为 0。
+
+三线分别以 Java 8 `d5799ac`、Java 17 `ddfa6c8`、Java 21 `0b4b0c8` 为基线修改,用各自 Wrapper 执行 `./mvnw -B -ntp -o clean verify`。分别通过 2,248、2,249、2,248 项,零失败、零错误、零跳过。响应和连接池的关闭异常使用注入的 Apache HTTP provider 测试,协议解析和序列化回归分别使用 JSON 夹具及回环服务。三份 JaCoCo 均命中 24 个日志调用点中的 21 个。HTTP 外层响应映射失败、WebSocket onError 和 WebSocket 关闭抛异常仍待动态证据。
+
+
+## HTTP 响应映射与 WebSocket provider 异常
+
+OC-PRIV-001/002/003/006。HTTP 夹具返回合法响应并使用 Jackson 的实际写入深度约束触发 items 映射失败。Java 17 在原分类逻辑下抛出没有状态证据的通用异常。修复后保留 HTTP 200、`PROTOCOL_FAILURE`、显式捕获的原响应及空退出码。公开异常栈和 SDK 日志只使用固定诊断和关联 ID。数组和其他有效 `items` 使用同一 Jackson writer,普通协议回归仍通过。
+
+真实回环 WebSocket 连接收到注入的 provider error 回调后,旧连接退出,新连接完成注册与 ping/pong。错误日志保留旧连接关联 ID,隐藏 provider 测试标记。另一用例在无网络连接的 Java-WebSocket 1.6.0 夹具上注入底层 close 异常。SDK 清空接单连接,只调用一次关闭,关闭后拒绝重启,DEBUG 日志保留关联 ID。该用例验证 SDK 的错误处理,实际套接字关闭由其他回环测试验证。
+
+Java 8 `f4c6677`、Java 17 `6894071`、Java 21 `a0ba264` 是修改前基线。三线各使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,251、2,252、2,251 项,零失败、零错误、零跳过。三份报告均执行了新增的三项回归,JaCoCo 显示每线 24 个 SDK 日志调用点均被执行。此前各节保留供应商原文、异常链、日志与应用显式读取原始结果的证据边界。
diff --git a/openspec/changes/harden-opencli-process-lifecycle/tasks.md b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
index 253d98a8..6f004455 100644
--- a/openspec/changes/harden-opencli-process-lifecycle/tasks.md
+++ b/openspec/changes/harden-opencli-process-lifecycle/tasks.md
@@ -6,21 +6,138 @@
## 1. 资源回归
-- [ ] 1.1 用可控子进程分别编写排队超时、并发 Client、取消、超限与 cleanup 竞态失败测试。
-- [ ] 1.2 测量在途进程与 capture 峰值;保留失败证据而不运行真实用户网站。
+- [x] 1.1 用可控子进程分别编写排队超时、并发 Client、取消、超限与 cleanup 竞态失败测试。见本文 OC-PROC-004/005 回归矩阵。
+- [x] 1.2 测量在途进程与 capture 峰值;保留失败证据而不运行真实用户网站。见本文 OC-PROC-001/002/003 饱和验证。
## 2. 执行核修复
- [ ] 2.1 引入稳定 limiter 和单调 deadline,将许可等待纳入总预算。
- [ ] 2.2 实现有限 capture、OUTPUT_LIMIT 和安全 UTF-8 截断策略。
-- [ ] 2.3 实现统一终结路径与有限 cleanup,保护共享 daemon/用户进程。
+- [x] 2.3 实现统一终结路径与有限 cleanup,保护共享 daemon/用户进程。
## 3. 兼容和证据
- [ ] 3.1 明确 0/负数配置语义、总预算与 cleanup grace、同步 follow 限制。
-- [ ] 3.2 在三线和声明支持的 OS 上验证真实进程资源回收;能力缺口不得标绿。
+- [x] 3.2 在三线和声明支持的 OS 上验证真实进程资源回收;能力缺口不得标绿。
- [ ] 3.3 回归现有超时/UTF-8/异常测试,记录 HEAD、数量、跳过项和退出码。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## OC-PROC-006 本地同步采集验证
+
+`OpenCliProcessContractTest` 经 typed `browser network --follow` 入口运行真实 JVM fixture,校验 CLI argv,并覆盖正常退出、CLI 非零退出、输出超限、调用线程中断、执行超时,以及禁用时限时启动前拒绝。超时测试同时启动独立进程,确认该进程仍运行并可自行正常退出。JDK 21 执行 `bash ./mvnw -B -ntp -o clean verify` 退出 0,全量 2,095 项(其中该类 14 项),0 失败、0 错误、0 跳过。
+
+## 2026-11-18 OC-PROC-006 真实 OpenCLI 验证
+
+使用 macOS 27.0.1 ARM64、Node 24.18.0、OpenCLI 1.8.6、Chrome for Testing 158.0.8127.18 和 [Browser Bridge 1.0.22](https://github.com/jackwener/OpenCLI/releases/tag/v1.8.6)。扩展归档的 SHA-256 为 `9d2e3d053948beab5d97124aa79b1532d2122e33e461eca56cac113afd33207a`。每条维护线使用新的临时浏览器配置和显式 profile 路由。页面和数据接口仅绑定回环地址,每 120 ms 发起一次带序号的请求。
+
+SDK 通过 `OpenCliBrowserSession.network` 设置 `follow(true)` 和 `all(true)`,实际运行 `opencli --profile browser network --follow --all`。探针分别使用 4,500 ms 时限和 64 KiB 上限,以及 12,000 ms 时限和 2,048 字节上限。每次解析部分 stdout 中完整的 JSON 行,确认来自测试接口、HTTP 状态为 200,且至少有两个不同请求。每条维护线用对应 JDK 执行 `test-compile`,JDK 21 使用仓库 Maven Wrapper。
+
+| JDK | 参与验证的功能分支提交 | 执行超时,完整事件 / 捕获字节 / 耗时 | 输出超限,完整事件 / 捕获字节 / 观测字节 / 耗时 |
+| --- | --- | --- | --- |
+| 8 | `293c281a93c22a077d0f6a9b5ba2663bd6a6ea38` | 34 / 6,044 / 4,519 ms | 11 / 2,048 / 2,844 / 2,220 ms |
+| 17 | `d22a1937ca43f03cb17a707710fb8899fa963b6d` | 34 / 6,044 / 4,524 ms | 11 / 2,048 / 2,132 / 2,204 ms |
+| 21 | `1ed41f928b4c906cb0499955687d33270c70c2ca` | 33 / 5,866 / 4,518 ms | 11 / 2,048 / 2,844 / 2,208 ms |
+
+6 个场景通过,0 失败、0 跳过。SDK 分别返回 `EXECUTION_TIMEOUT` 和 `OUTPUT_LIMIT`,均附带部分输出和 `ROOT_EXIT_CONFIRMED`。每组验证确认共享 daemon 的 PID 和隔离浏览器进程在两次调用后仍存活,后续标签页查询仍成功。当前结果验证 macOS 上的同步有界采集。受控 sink、后代进程所有权和其他操作系统上的真实浏览器验收仍待验证。
+
+## 2026-11-18 OC-PROC-003 捕获数组扩容
+
+JDK 17 红灯测试以 8,193 字节作为捕获上限,分两次写满,观察到旧实现把 backing array 扩到 16,384 字节。修复对单次分配容量应用捕获上限。回归验证 8,193 字节数组、原样保留的前缀、准确的观测字节数及截断标记。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,114 项通过,0 失败、0 错误、0 跳过。真实 OpenCLI 1.8.6 两项复验通过。4,500 ms 时限返回 `EXECUTION_TIMEOUT` 并保留 34 条完整事件。2 KiB 上限返回 `OUTPUT_LIMIT` 并保留 2,048 字节和 11 条完整事件。两次均确认 SDK 启动的 CLI 子进程已退出,后续 daemon 查询可用。
+
+本次测量单个捕获数组的容量。整体堆内存还包含扩容时的数组复制、输出快照和并发调用,按独立指标记录。
+
+## 2026-11-18 OC-PROC-001/002/003 饱和验证
+
+`OpenCliProcessContractTest#sharedRuntimeBoundsConcurrentChildrenAndCombinedCapture` 使用三个客户端共享两个执行许可。两个真实 JVM 子进程分别写入 131,073 字节 stdout 和 65,539 字节 stderr,然后发出就绪标记并等待同一释放信号。两个子进程仍在途时提交四次调用,四次均返回 `QUEUE_TIMEOUT`,执行详情和子进程标记均确认没有启动进程。该场景在途峰值为 2。
+
+释放后,两次调用均确认根进程退出,四条输出流保留 393,224 字节,恰好达到两个执行槽的合计捕获预算,零截断。这个数值由执行详情测得,对应离线 fixture 的捕获量。JVM 整体堆内存还包含其他分配,本场景不对其计量。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,115 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-18 OC-PROC-004/005 回归矩阵
+
+`OpenCliProcessContractTest` 使用真实子进程覆盖排队超时、独立和共享 Client 限流、取消及独立流超限。`SubprocessCompletionRaceTest` 用同步屏障覆盖输出超限、取消、watchdog 与进程结束竞争,确认唯一结果和许可复用。`SubprocessCleanupFaultTest` 注入 watchdog 初始化、流初始化、终止和清理异常,覆盖最初失败保留及无法确认退出的运行时隔离。
+
+新增真实继承管道回归。根进程启动继承 stdout、stderr 的独立 JVM,后者通过文件汇报心跳。观察到后代进程启动后取消调用。清理宽限配置为 250 ms,测试允许 1,500 ms 等待窗口,包含线程调度。SDK 仍返回 `CANCELLED`,流未排空时必须报告 `UNCONFIRMED`,并且不声称后代已退出。断言取消后后代心跳仍更新,最后由测试自己的释放文件终止它。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,116 项通过,0 失败、0 错误、0 跳过。该场景验证未追踪后代的安全边界,后代所有权和回收能力仍由 2.3、3.2 跟踪。
+
+## 2026-11-18 OC-PROC-003 输出缓冲区按需分配
+
+修复前,构造捕获对象即分配每个输出流的初始数组,默认两个共 16 KiB,包括仍排队或在启动前取消的调用。JDK 17 的两项回归分别观测到预取消路径的 16 字节测试配置和普通空写路径的 8,192 字节数组容量,预期均为零。
+
+修复后,第一次非空写入才分配对应捕获数组,仍受流的配置上限约束。预取消路径的 stdout、stderr 容量均为零,读取线程的工作缓冲和 JVM 总堆内存属独立指标。红灯 2 项失败,修复后 JDK 17 定向 33 项通过。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,117 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-18 OC-PROC-005 终止操作阻塞
+
+故障注入让调用独占根进程的普通和强制终止分别等待释放信号。验证显式取消以及 Commons Exec watchdog 到期两条路径。设置清理宽限 250 ms,以 1,250 ms 为回归断言窗口。修复前两项均等待超时。
+
+修复将 native 终止调用交给每次执行最多两个守护工作线程,普通和强制终止各发出一次。watchdog 回调只提交终止请求,既有锁不覆盖 native 终止操作。原始 `CANCELLED` 或 `EXECUTION_TIMEOUT` 保留。终止操作未结束时保留 `UNCONFIRMED`,不伪造退出码,并隔离当前运行时。测试最后释放注入的阻塞线程。该修复范围为 SDK 已持有的根进程,后代所有权仍待验收。
+
+JDK 17 定向 29 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,119 项通过,0 失败、0 错误、0 跳过。平台契约证据增加 `SubprocessCleanupFaultTest`。
+
+
+## C02 锁定版本与托管进程验证
+
+本分支以 `72c9dd89c04d1fa82457fa906744dd3491e3704e` 为基线,用 JDK 21 执行 `OpenCliBrowserBridgeIT#boundedNetworkFollowLeavesTheRealBridgeAndPageAvailable` 与 `OpenCliProcessContractTest`、`OpenCliProcessBoundaryTest`、`SubprocessCleanupFaultTest`、`SubprocessCompletionRaceTest`,共 35 项实际执行,零失败、零错误、零跳过。报告位于 `target/surefire-reports`。
+
+真实 Browser Bridge 1.0.24、OpenCLI 1.8.8 和临时 Chrome 在回环页面上执行两次同步 `network --follow --all`。配置 4,500 ms 与 64 KiB 上限时,结果为 `EXECUTION_TIMEOUT`。配置 12,000 ms 与 2 KiB 上限时,结果为 `OUTPUT_LIMIT`。两次均保留页面请求证据并确认直属进程退出,页面 ID 保持不变。测试进程还验证同一 daemon PID 和 Chrome 进程仍存活。每次使用新的页面 URL 与会话,避免复用已停止产生测试流量的旧页面。
+
+已核对 JDK 8、17、21 的托管基线报告,共八个平台作业。它们分别实际执行独立进程存活、调用取消、线程中断后的直属进程回收、以及继承管道且身份未确认的后代不被停止这四个用例,均无跳过和失败。JDK 8 托管范围为 Intel macOS 和 Windows。JDK 17、21 加测 Apple Silicon macOS。新工作流要求在报告中出具 `SubprocessCompletionRaceTest` 的执行证据,已从 Java 8、17、21 的八份托管工件读取该套件的 Surefire XML,每份报告均实际执行同时信号完成和中断清理两项用例,零失败、零跳过。见 [Java 8](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44393705999)、[Java 17](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44394674731)、[Java 21](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44393703895)。后代身份未知继续通过清理状态和 `descendantsExitConfirmed` 表达。
+
+
+## 继承管道测试的清理同步
+
+Java 21 的一次运行中,未知后代仍在更新心跳,JUnit 已开始清理临时目录,产生 DirectoryNotEmptyException。Java 17 回归加入尾部确认后,旧 fixture 实际执行 1 项、失败 1 项,缺少最后一次心跳确认。现在测试发出自己的 release 信号,等待后代在完成所有心跳写入后创建确认文件,再交还临时目录。测试仍在发出 release 之前确认后代存活及取消预算,SDK 的执行和清理逻辑未改动。
+
+各分支使用 Wrapper 分别在 Java 8、17、21 运行 OpenCliProcessContractTest、OpenCliProcessBoundaryTest、SubprocessCompletionRaceTest、OpenCliProcessPrivacyTest,每条线 31 项通过,零失败、零错误、零跳过。报告位于 target/surefire-reports。
+
+## Linux 维度与旧输出流回归
+
+Java 8、21 功能线的平台矩阵加入 Ubuntu,Java 17 保留现有 Ubuntu JVM 作业。三线平台作业均显式选择旧版输出流的有界写入用例。该用例通过本线 JVM 启动现有 LifecycleProbe,检查退出后从旧 API 写入时的字节上限,并验证此前记录的进程截断事实保持准确。
+
+本地 macOS 上用三个分支的 Wrapper 复跑进程契约、结束竞态、读取失败及两个低层用例,每线 24 项通过,零失败、零错误、零跳过。Linux、macOS 和 Windows 的托管证据按精确功能提交核对。
+
+## 输出读取异常和后代独立管道
+
+OC-PROC-004/005。Java 17 基线 `1946d9f` 的两个故障注入场景均将运行时读取或关闭异常误报为 `PROCESS_EXIT`。Reader 现在报告 `IO_FAILURE`,保留已读取字节、实际直属退出码和显式低层原因。SDK 的默认异常摘要保留固定消息。故障注入用例确认原始 provider 标记不会进入默认诊断。
+
+真实 JVM 进程夹具分别使用继承管道和独立输出管道。两种情况下,取消父进程后,未追踪的后代都继续更新心跳。独立输出用例确认 SDK 可报告 `ROOT_EXIT_CONFIRMED` 和已排空自己的读取线程,同时 `descendantsExitConfirmed` 为 false。继承管道未排空时继续标记 `UNCONFIRMED`。用例通过释放文件停止自己的后代,并等待其最后一次写入的确认。
+
+Java 8 `1310c54`、Java 17 `1946d9f`、Java 21 `89da70e` 为修改前基线。各线使用 Wrapper 执行 `./mvnw -B -ntp -o clean verify`,分别通过 2,254、2,255、2,254 项,零失败、零错误、零跳过。报告为 `SubprocessStreamFailureTest` 与 `OpenCliProcessContractTest` 的 Surefire XML。此处给出直属进程和管道边界的运行证据。多平台的已声明能力与未追踪后代的限制继续由 3.2 验收。
+
+独立复审发现 Windows 下重定向输出文件的句柄可能在心跳确认后仍被后代持有。夹具改用 ProcessBuilder 的独立默认管道,避免临时输出文件的删除竞态。新增断言区分已观察到的根退出码 0 与 SDK 的 IO_FAILURE。三条线分别重跑两个受影响的测试套件,各通过 7 项,零失败、零错误、零跳过。
+
+
+## OC-PROC-004/005 真实直属进程的平台证据
+
+从以下精确提交的 10 份托管平台工件读取 Surefire XML。每份均执行继承及独立管道两个用例、独立进程存活、调用线程中断、两种运行时读取故障,共 6 项,零失败、零错误、零跳过。
+
+| JDK | 验证提交 | 平台 |
+| --- | --- | --- |
+| 8 | `358afd209f98a9b3146383f3ff7ad2e037490f3e` | [Ubuntu、Intel macOS、Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44410065713) |
+| 17 | `1369aa1cfca1dc2a6b093895c67ee6e1e6698446` | [Intel 与 Apple Silicon macOS、Windows,另有 Ubuntu 全量 JVM 作业](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44410066000) |
+| 21 | `e4022f1c7a3cf9789e347270143ec5f013f58f99` | [Ubuntu、Intel 与 Apple Silicon macOS、Windows](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44410064678) |
+
+清理结果区分直属进程与未知后代。若直属进程退出、读取线程排空,可报告 `ROOT_EXIT_CONFIRMED`,同时将 `descendantsExitConfirmed` 保持为 false。无法确认读取线程排空时返回 `UNCONFIRMED`。真实 Browser Bridge 的共享 daemon 与 Chrome 存活证据来自 macOS 回环联调,Windows/Linux 平台工件使用真实 JVM 子进程夹具。3.2 继续记录跨平台真实 Bridge 验收和未追踪后代的能力边界。
+
+### Windows 与 Linux 的真实 Browser Bridge 验收
+
+在独立 runner 使用锁定版本的 OpenCLI、扩展归档及 Chrome for Testing。真实 Node daemon 和临时 Chrome profile 只访问回环页面。沿用 `OpenCliBrowserBridgeIT` 验证类型结果、查询、绑定标签页及有界采集。验证完成后检查同一个 daemon 和 Chrome 进程仍在运行,上传本次 Surefire XML。缺报告、跳过或任一进程异常退出均判失败。
+
+六份托管工件各通过 4 项,零失败、零错误、零跳过。Windows 的第一轮绑定在页面加载前取到空标签页。修复后通过 Chrome DevTools 在测试开始前准备并激活独立标签页,绑定、客户端关闭及重新创建均保持同一 page ID。三线同时验证类型结果、本地 HTTP 采集、有界 follow 的超时与输出超限,以及共享 daemon 和 Chrome 继续运行。
+
+| JDK | 验证提交 | Windows 和 Ubuntu |
+| --- | --- | --- |
+| 8 | `8c713df1216ec3442d41d0b82df84a00bd55a799` | [GitHub Actions](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44413589035) |
+| 17 | `a164812beb68a8fe9306f9659d50760cd59257f5` | [GitHub Actions](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44413590326) |
+| 21 | `75263b16edbd713e44c930a0d367b8e34f2a9ec0` | [GitHub Actions](https://github.com/easy-4-java/opencli-java-sdk/actions/runs/44413590206) |
+
+每份工件包含当前 SHA 的实际 Maven、JDK 版本、Surefire XML、报告和进程身份。macOS 使用上文记录的独立实测。直属进程和 SDK 读取线程按已证明的所有权清理,未追踪后代继续明示为未确认。此验收完成 C02 3.2 的平台证据;C10 最终集成仍待关闭。
diff --git a/openspec/changes/harden-opencli-remote-collect/evidence/2026-11-19-live-agent.md b/openspec/changes/harden-opencli-remote-collect/evidence/2026-11-19-live-agent.md
new file mode 100644
index 00000000..285d758e
--- /dev/null
+++ b/openspec/changes/harden-opencli-remote-collect/evidence/2026-11-19-live-agent.md
@@ -0,0 +1,71 @@
+# OpenCLI 1.8.8 与 opencli-admin Agent 回环联调
+
+使用 [partme-ai/opencli-admin 的锁定源码](https://github.com/partme-ai/opencli-admin/blob/f3879eb2e30f5dedb4df249f0b15a7d007bbfe9e/backend/agent_server.py)。`backend/agent_server.py` 的 SHA-256 为 `a9a53e003234b3615d2097e96bbdceea6642febf89b29f32ae321d8b7fff3530`。使用 OpenCLI 1.8.8、Node 24.18.0、Python 3.14.8、FastAPI 0.165.0、Pydantic 2.14.3、Uvicorn 0.54.0 和 PyYAML 6.0.3。Agent 仅监听回环地址,禁用中心注册。OpenCLI 使用隔离用户、配置和缓存目录。
+
+| 请求 | 观察结果 |
+| --- | --- |
+| 默认 Agent 桥接端口 19825,查询 npm search 帮助 | OpenCLI 1.8.8 拒绝该端口并退出 78,Agent 返回 HTTP 200 和业务失败。三个 Java 客户端均观察到业务失败。 |
+| Agent 桥接端口 61735,查询 npm search 帮助 | HTTP 200,Agent 返回实际 OpenCLI 的结构化帮助,SDK 标记业务成功。 |
+| 同一端口,调用 npm search 时省略必填位置参数 | OpenCLI 退出 1,Agent 返回 HTTP 200 和业务失败。SDK 保留 HTTP 200,将兼容退出值标明为合成值,并保留业务错误。 |
+| 同一端口,再次查询帮助并显式启用原文捕获 | SDK 保留原始 Agent 响应。关闭捕获的成功及失败请求均验证原文为空。 |
+
+带 61735 配置的一轮在 Java 8 `8da04d3`、Java 17 `4fb8c73` 和 Java 21 `df3b58c` 各通过三项。Agent 日志共记录六次成功及三次缺参失败。验证范围为明文回环 legacy 收集协议、CLI 帮助及参数校验。生产 TLS 和认证由独立部署环境验收。此次联调没有调用 npm 注册表、浏览器或用户账户。
+
+## 复跑
+
+从上述提交提取 `backend/agent_server.py` 到临时目录。从已安装的 OpenCLI 1.8.8 包取得 `dist/src/main.js` 的绝对路径,作为 `OPENCLI_ENTRY`。在临时目录保存 `isolate.mjs`,将 `os.homedir()` 指向 `OPENCLI_FIXTURE_HOME`。
+
+```javascript
+import os from 'node:os';
+import { syncBuiltinESMExports } from 'node:module';
+os.homedir = () => process.env.OPENCLI_FIXTURE_HOME;
+syncBuiltinESMExports();
+```
+
+在同一目录保存可执行文件 `opencli-isolated`。使用临时目录及回环端口启动 Agent。
+
+```sh
+#!/bin/sh
+exec node --import "$OPENCLI_FIXTURE_HOME/isolate.mjs" "$OPENCLI_ENTRY" "$@"
+```
+
+```sh
+chmod 700 opencli-isolated
+export OPENCLI_FIXTURE_HOME="$PWD" OPENCLI_CONFIG_DIR="$PWD/config" OPENCLI_CACHE_DIR="$PWD/cache"
+export OPENCLI_BIN="$PWD/opencli-isolated" CI=1 NO_COLOR=1
+export AGENT_REGISTER=off CENTRAL_API_URL='' AGENT_DEPLOY_TYPE=shell OPENCLI_DAEMON_PORT=61735
+uv run --no-project --with fastapi==0.165.0 --with pydantic==2.14.3 \
+ --with uvicorn==0.54.0 --with pyyaml==6.0.3 \
+ python -m uvicorn agent_server:app --host 127.0.0.1 --port 19823
+```
+
+在 SDK 功能分支以对应 JDK 执行 `OpenCliRemoteAgentHttpClientTest`,从生成的 Surefire XML 读取 `java.class.path`。用该 classpath 编译 [OpenCliAdminLoopbackProbe](fixtures/OpenCliAdminLoopbackProbe.java),再用同一 classpath 加上探针输出目录运行,唯一参数为 `http://127.0.0.1:19823`。复现旧端口问题时,在无其他请求的临时 Agent 上改用 19825 并执行同一探针,首个成功断言会得到业务失败,Agent 日志会显示子进程退出 78。
+
+## HTTPS 和显式 Authorization
+
+在同一版本真实 Agent 前加入 [回环 TLS 代理](fixtures/opencli_agent_tls_proxy.py)。代理使用独立监听套接字,校验 Authorization 后只转发 JSON 请求体。证书只包含 IP SAN 127.0.0.1。Java 使用临时 JKS 信任库和 SDK 默认主机名校验。
+
+| 每条 Java 功能线的场景 | 观察结果 |
+| --- | --- |
+| 有效模拟令牌 | 收到 HTTP 200 与实际 CLI 帮助。Agent 每线收到一次请求。 |
+| 缺少令牌或错误令牌 | 两次均收到 HTTP 401,SDK 保留 HTTP 状态并标为 HTTP_FAILURE,CLI 退出码为空。 |
+| 请求主机名改为 localhost | 证书名称不匹配,SDK 标为 TRANSPORT_FAILURE,HTTP 状态为空。 |
+
+Java 8 `afc6b33`、Java 17 `58f675a` 和 Java 21 `5cfa937` 各通过四项。代理日志显示三次转发和六次拒绝。主机名不匹配的请求未进入代理路由。三份 Java 输出与完整异常栈均未出现金丝雀令牌。认证由回环代理执行,生产 Agent 的网关、凭据和部署策略仍需现场验收。
+
+复用前一节的 Agent 源码、OpenCLI 环境和隔离启动脚本,把代理脚本复制到临时目录。生成专用于该目录的证书、信任库和随机测试令牌。
+
+```sh
+openssl req -x509 -newkey rsa:2048 -sha256 -nodes -days 1 \
+ -subj '/CN=OpenCLI Loopback Fixture' -addext 'subjectAltName=IP:127.0.0.1' \
+ -keyout key.pem -out cert.pem
+keytool -importcert -noprompt -storetype JKS -keystore trust.jks \
+ -storepass changeit -alias opencli-loopback -file cert.pem
+openssl rand -hex 24 > token
+chmod 600 token
+uv run --no-project --with fastapi==0.165.0 --with pydantic==2.14.3 \
+ --with uvicorn==0.54.0 --with pyyaml==6.0.3 --with httpx==0.28.1 \
+ python opencli_agent_tls_proxy.py
+```
+
+在对应 JDK 下运行同一个 Java 探针,启动参数增加 `-Djavax.net.ssl.trustStore` 和 `-Djavax.net.ssl.trustStorePassword`。探针依次读取 HTTPS 端点和令牌文件绝对路径。代理端口记录在临时目录的 `tls-port` 中。复跑结束后,在临时目录创建 `stop` 让两个监听器正常退出。
diff --git a/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/OpenCliAdminLoopbackProbe.java b/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/OpenCliAdminLoopbackProbe.java
new file mode 100644
index 00000000..6890480f
--- /dev/null
+++ b/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/OpenCliAdminLoopbackProbe.java
@@ -0,0 +1,117 @@
+import io.github.easy4j.opencli.OpenCliExecutionTarget;
+import io.github.easy4j.opencli.OpenCliProperties;
+import io.github.easy4j.opencli.OpenCliRemoteAuthentication;
+import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
+import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Objects;
+
+public final class OpenCliAdminLoopbackProbe {
+
+ public static void main(String[] args) throws IOException {
+ URI endpoint = URI.create(args[0]);
+ require("127.0.0.1".equals(endpoint.getHost()), "test Agent must be on IPv4 loopback");
+ if (args.length == 2) {
+ require("https".equals(endpoint.getScheme()), "TLS proxy requires HTTPS");
+ String token = new String(Files.readAllBytes(Paths.get(args[1])), StandardCharsets.US_ASCII).trim();
+ verifyTlsProxy(endpoint, token);
+ return;
+ }
+ try (OpenCliExecutor executor = executor(endpoint, false, null)) {
+ OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
+ verify(help, true);
+ require(help.getStdout().contains("opencli npm search"), "structured CLI help is missing");
+ require(Objects.isNull(help.getRemoteRawHttpBody()), "raw capture must be off by default");
+
+ try {
+ executor.invoke("npm", "search", "-f", "json");
+ throw new AssertionError("missing CLI query unexpectedly succeeded");
+ } catch (OpenCliNonZeroExitException failure) {
+ OpenCliResult result = failure.getPartialResult();
+ verify(result, false);
+ require(Objects.isNull(result.getRemoteRawHttpBody()), "failed response was captured by default");
+ require(result.getStderr().contains("opencli exit"), "the Agent's business error is missing");
+ }
+ }
+ try (OpenCliExecutor executor = executor(endpoint, true, null)) {
+ OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
+ verify(help, true);
+ require(Objects.nonNull(help.getRemoteRawHttpBody()) && help.getRemoteRawHttpBody().contains("opencli npm search"),
+ "explicit capture did not retain the original Agent body");
+ }
+ System.out.println("PASS: real Agent help, missing-argument failure, and opt-in raw HTTP capture");
+ }
+
+ private static void verifyTlsProxy(URI endpoint, String token) {
+ try (OpenCliExecutor executor = executor(endpoint, false, "Bearer " + token)) {
+ OpenCliResult help = executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
+ verify(help, true);
+ require(help.getStdout().contains("opencli npm search"), "structured CLI help is missing");
+ require(Objects.isNull(help.getRemoteRawHttpBody()), "raw capture must be off by default");
+ }
+ verifyRejected(endpoint, null, 401);
+ verifyRejected(endpoint, "Bearer invalid-" + token, 401);
+ verifyRejected(URI.create("https://localhost:" + endpoint.getPort()), "Bearer " + token, 0);
+ System.out.println("PASS: real Agent through TLS, missing and invalid credentials, and certificate hostname rejection");
+ }
+
+ private static void verifyRejected(URI endpoint, String credential, int status) {
+ try (OpenCliExecutor executor = executor(endpoint, false, credential)) {
+ executor.invoke("npm", "search", "fixture", "--help=true", "-f", "json");
+ throw new AssertionError("proxy unexpectedly accepted the request");
+ } catch (OpenCliExecutableFailureException failure) {
+ OpenCliResult result = failure.getPartialResult();
+ OpenCliRemoteExecutionDetails details = result.getRemoteExecutionDetails();
+ require(details.getObservedHttpStatus().orElse(0) == status, "wrong observed HTTP status");
+ require(details.getOutcome() == (status == 0 ? OpenCliRemoteExecutionDetails.Outcome.TRANSPORT_FAILURE
+ : OpenCliRemoteExecutionDetails.Outcome.HTTP_FAILURE), "wrong rejection classification");
+ require(Objects.isNull(result.getExitCode()), "rejection must not invent an exit code");
+ require(Objects.isNull(result.getRemoteRawHttpBody()), "raw capture must be off by default");
+ if (Objects.nonNull(credential)) {
+ StringWriter diagnostics = new StringWriter();
+ failure.printStackTrace(new PrintWriter(diagnostics));
+ require(!diagnostics.toString().contains(credential), "exception included the authorization value");
+ }
+ }
+ }
+
+ private static OpenCliExecutor executor(URI endpoint, boolean capture, String credential) {
+ OpenCliProperties properties = new OpenCliProperties();
+ properties.setExecutionTarget(OpenCliExecutionTarget.REMOTE_AGENT_HTTP);
+ properties.setRemoteAgentBaseUrl(endpoint.toString());
+ properties.setRemoteCollectMode("bridge");
+ properties.setRemoteCaptureRawHttpResponse(capture);
+ if (Objects.nonNull(credential)) {
+ properties.setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", credential));
+ }
+ return new OpenCliExecutor(properties);
+ }
+
+ private static void verify(OpenCliResult result, boolean success) {
+ require(result.isSuccess() == success, "wrong business status");
+ require(Integer.valueOf(success ? 0 : 1).equals(result.getExitCode()), "wrong mapped exit value");
+ OpenCliRemoteExecutionDetails details = result.getRemoteExecutionDetails();
+ require(details.getObservedHttpStatus().orElse(-1) == 200, "HTTP status was lost");
+ require(details.getOutcome() == (success ? OpenCliRemoteExecutionDetails.Outcome.SUCCESS
+ : OpenCliRemoteExecutionDetails.Outcome.COMMAND_FAILURE), "wrong outcome classification");
+ require(details.getExitCodeSource() == OpenCliRemoteExecutionDetails.ExitCodeSource.SYNTHETIC_COMPATIBILITY,
+ "legacy mapping must be marked synthetic");
+ require(!details.getObservedRemoteExitCode().isPresent(), "legacy response contains no CLI exit field");
+ require(Objects.isNull(result.getExecutionDetails()), "legacy response contains no local process evidence");
+ }
+
+ private static void require(boolean condition, String message) {
+ if (!condition) {
+ throw new AssertionError(message);
+ }
+ }
+}
diff --git a/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/opencli_agent_tls_proxy.py b/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/opencli_agent_tls_proxy.py
new file mode 100644
index 00000000..9342a052
--- /dev/null
+++ b/openspec/changes/harden-opencli-remote-collect/evidence/fixtures/opencli_agent_tls_proxy.py
@@ -0,0 +1,54 @@
+"""Run a TLS proxy and locked OpenCLI Agent on two IPv4 loopback sockets."""
+import asyncio
+import hmac
+import socket
+from pathlib import Path
+
+import httpx
+import uvicorn
+from fastapi import FastAPI, Request, Response
+
+from agent_server import app as agent
+
+
+def listener():
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ return sock
+
+
+async def main():
+ backend, frontend = listener(), listener()
+ agent_url = f"http://127.0.0.1:{backend.getsockname()[1]}/collect"
+ Path("tls-port").write_text(str(frontend.getsockname()[1]))
+ credential = "Bearer " + Path("token").read_text().strip()
+ proxy = FastAPI()
+
+ @proxy.post("/collect")
+ async def collect(request: Request):
+ supplied = request.headers.get("authorization", "")
+ data = await request.body()
+ if not hmac.compare_digest(supplied, credential):
+ print("proxy rejected missing or invalid credential", flush=True)
+ return Response(status_code=401, headers={"WWW-Authenticate": "Bearer"})
+ assert credential.encode() not in data
+ async with httpx.AsyncClient(timeout=10, trust_env=False) as client:
+ response = await client.post(agent_url, content=data, headers={"Content-Type": "application/json"})
+ print(f"proxy forwarded one accepted request, Agent HTTP {response.status_code}", flush=True)
+ return Response(response.content, status_code=response.status_code, media_type="application/json")
+
+ server = uvicorn.Server(uvicorn.Config(agent, access_log=False))
+ tls = uvicorn.Server(uvicorn.Config(proxy, access_log=False, ssl_keyfile="key.pem", ssl_certfile="cert.pem"))
+ local = asyncio.create_task(server.serve(sockets=[backend]))
+ edge = asyncio.create_task(tls.serve(sockets=[frontend]))
+ try:
+ for _ in range(600):
+ if Path("stop").exists() or local.done() or edge.done():
+ break
+ await asyncio.sleep(0.5)
+ finally:
+ server.should_exit = tls.should_exit = True
+ await asyncio.gather(local, edge)
+
+
+asyncio.run(main())
diff --git a/openspec/changes/harden-opencli-remote-collect/specs/opencli-remote-collect/spec.md b/openspec/changes/harden-opencli-remote-collect/specs/opencli-remote-collect/spec.md
index 6b7179e8..50550a59 100644
--- a/openspec/changes/harden-opencli-remote-collect/specs/opencli-remote-collect/spec.md
+++ b/openspec/changes/harden-opencli-remote-collect/specs/opencli-remote-collect/spec.md
@@ -1,6 +1,6 @@
# Legacy HTTP collect 边界与保真
-> Proposal specification. Status: DRAFT / NOT_IMPLEMENTED.
+> The declared legacy collect scope is verified on the feature branches. PR review and merge are pending.
## ADDED Requirements
diff --git a/openspec/changes/harden-opencli-remote-collect/tasks.md b/openspec/changes/harden-opencli-remote-collect/tasks.md
index 8407a8e1..befd26ff 100644
--- a/openspec/changes/harden-opencli-remote-collect/tasks.md
+++ b/openspec/changes/harden-opencli-remote-collect/tasks.md
@@ -1,27 +1,94 @@
# C04 Tasks · Legacy HTTP collect 边界与保真
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 勾选项具备对应的实现或执行证据。待验收项继续保留。
关联规范:[spec](specs/opencli-remote-collect/spec.md)。
## 1. 服务端契约与失败测试
-- [ ] 1.1 固定 opencli-admin server 协议版本或可控 fixture,标明它不是 jackwener/OpenCLI 的官方 RPC。
-- [ ] 1.2 对 Browser/root/external/重复flag/负数/--/空值编写“拒绝且零请求”的测试。
-- [ ] 1.3 编写 success=false、503、malformed、null、超大body与超时结果未知用例。
+- [x] 1.1 固定可控的 legacy `POST /collect` fixture,记录本地桩与上游 CLI 的范围差异。见下方 OC-REMOTE-004 证据。
+- [x] 1.2 验证 Browser、根命令、外部透传和旧 DTO 无法保真的输入均在发送前拒绝。见下方 OC-REMOTE-001/002 证据。
+- [x] 1.3 验证业务失败、HTTP 503、畸形或 null 响应、响应超限及超时后远端结果未知。见下方 OC-REMOTE-004/005 证据。
## 2. 最小适配修复
-- [ ] 2.1 引入显式 legacy capability guard 和保真转换子集,避免无条件解析任意 argv。
-- [ ] 2.2 区分 HTTP/协议/命令失败、synthetic exit 与未观察的退出码。
+- [x] 2.1 引入显式 legacy capability guard 和保真转换子集,避免无条件解析任意 argv。
+- [x] 2.2 区分 HTTP、协议与命令失败,保留兼容退出码及其来源。见 OC-REMOTE-003/004 验证。
- [ ] 2.3 使 body/timeout 有界并实现可测试的显式 header 配置,保持 TLS。
## 3. 三线与安全
-- [ ] 3.1 对照 C09 测试凭据、URL query、body preview 和异常 cause 的默认脱敏边界。
+- [x] 3.1 验证凭据、URL query、正文和异常 cause 的默认诊断边界。见 OC-REMOTE-006 验证。
- [ ] 3.2 在三分支分别跑本地 HTTP fixture;记录旧 API 的行为收紧与迁移例子。
-- [ ] 3.3 未取得服务端契约的扩展仍标记 unsupported,不借此宣称远程全量兼容。
+- [x] 3.3 未取得服务端契约的扩展仍标记 unsupported,不借此宣称远程全量兼容。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+
+## OC-REMOTE-004 响应校验
+
+`OpenCliRemoteAgentHttpClientTest.JsonCollectStub` 通过本机 HTTP 服务器提供可控的 legacy `POST /collect` 响应。证据只覆盖 SDK 到此测试桩的 HTTP 交互。jackwener/OpenCLI 提供本地 CLI 接口,真实 opencli-admin 部署仍需验收。
+
+JDK 17 基线 `5ac4bb1` 的 20 项用例实际执行,7 项失败。缺少或显式设为 null 的 `success` 被当成业务失败。字符串和数字布尔值、数字 `error`、重复状态字段及拼接文档曾被当成成功。修正后,具备布尔状态字段的单个 JSON 对象才会继续映射结果,无效响应通过 `OpenCliRemoteProtocolException` 保留类别和相关 ID。现有异常父类保持兼容。合法的成功响应允许省略或置空 `items`,空结果仍为 `[]`。
+
+定向测试命令为 `-Dtest=OpenCliRemoteAgentHttpClientTest test`。使用各维护线的 Maven 和 JDK,报告位于 `target/surefire-reports`。Body 大小限制、总超时和退出码来源仍由其他任务验收。
+
+
+## OC-REMOTE-001/002 发请求前校验
+
+基线 `cf9360e` 的集成测试中,16 组输入有 15 组未按要求在 HTTP 前拒绝。既有 SDK 适配器名可能和外部透传调用重名,额外测试复现了该路径;改为仅本地执行后,HTTP 桩记录为零请求。正常 npm search 调用仍发送一次,并检查实际 JSON 的 site、command、positional_args 和 args。公开的低层 `collect(OpenCliCollectRequest)` 继续接收应用已经验证过的服务端 DTO。
+
+本轮证据来自本地桩和各维护线全量验证,当前 SDK 适配器清单用于限制 argv 路由。各 Agent 部署的实际命令与选项契约仍需验证。
+
+
+## OC-REMOTE-005 响应体预算
+
+JDK 17 基线在 42 项 HTTP 用例中有 4 项失败,覆盖多字节响应超出一字节、HTTP 200 和 503 的分块响应,以及 gzip 解压超限。修改复用现有 Unirest 的原始响应流,从解压后的流读取至上限。读取超限检测只需额外一个字节,超限后由 Unirest 释放响应连接。既有整包读取 API 无法在流尚未结束时执行这一限制。分块桩在收到结果前保持响应开启,验证客户端不等待 EOF。
+
+默认上限为 10 MiB,可通过 `maxRemoteResponseBytes` 配置正数。异常保留 HTTP 状态、上限和相关 ID。启用原文捕获的客户端也无法取得超限内容。补充验证恰好满足预算、声明字符集、无效配置零请求以及超限后同一客户端继续执行。总超时、结果不确定性和认证 header 仍待相应场景验收。
+
+
+## OC-REMOTE-005 持续分块与总预算
+
+JDK 17 基线中,chunked 响应每 125 ms 持续发送数据,900 ms 的原套接字超时未能终止调用,测试在 3 秒断言窗口失败。使用现有 Apache HttpClient 的可取消请求后,连接池等待、建连、HTTP 头及有界读取共享一个单调时钟预算。超时只中止当前请求,已提交传输的调用返回远端结果未知,无自动重试。原始预算耗尽且尚未提交时返回未发送。当前响应池可继续处理后续调用,并保留 JVM 信任配置。另有 307 回归验证不会转发采集请求。
+
+本轮验证的是 SDK 侧 HTTP 传输与回环 HTTP 桩。真实部署、系统 DNS 解析器或本地解析处理的执行时延,以及认证 header 仍需独立验收。
+
+
+## OC-REMOTE-003/004 状态与退出码来源
+
+对基线加入结果证据断言后,HTTP 200 业务失败、HTTP 503、缺省 `items` 和十种畸形响应共 13 项未能提供所需证据。修改后,`getRemoteExecutionDetails()` 保留 HTTP 状态、Agent 业务状态、失败层级和 `items` 来源。兼容退出值标记为 `SYNTHETIC_COMPATIBILITY`,观测到的远端退出码为空。HTTP 或协议失败快照保留真实状态且退出值为空,按原文捕获开关提供通过字节上限检查的完整响应。超限和超时沿用原有异常及保留策略。
+
+验证覆盖 503 的 HTML 响应、可选原文与安全诊断、合法业务失败和协议失败。显式诊断导出先输出退出码来源,再输出兼容退出值,避免截断产生缺少来源的数字。
+
+
+## OC-REMOTE-006 显式认证与 TLS
+
+基线先增加配置和夹具,尚未接入传输。HTTPS 认证成功、明文认证拒绝及三类 URL 凭据输入共 5 项验收失败。接入后,回环 HTTPS 服务使用独立测试证书和显式信任。未信任的证书在请求转交应用处理器前被拒绝。信任证书后,桩仅在明确收到正确的指定请求头时返回成功。去除配置后按 401 处理,不自动生成认证数据。错误凭据的 401 回显未出现在默认日志、异常栈或原文捕获关闭时的失败快照中。
+
+显式认证采用 SDK 已有 Apache HttpClient 的 HTTPS 校验。明文认证、URL 用户信息、查询参数和片段均在发送前拒绝。测试复用了 WebSocket 的回环证书生成方式。真实 Agent 可接受的请求头和生产认证流程仍待部署契约验证。
+
+
+## C04 实施核对与中断结果
+
+JDK 17 基线的两项新测试均失败。Agent 接收请求后断开以及发出 HTTP 200 后提前中断正文,都只得到无 partial result 的异常。修复后,异常类型保持兼容,partial result 标记 `TRANSPORT_FAILURE` 和远端结果未知。已观察的 HTTP 状态得以保留,未收到响应头时状态为空。没有 CLI 退出码或不完整正文,诊断导出也不显示未观察的 HTTP 状态。每种场景桩均只收到一次请求。
+
+argv 入口继续限制为 SDK 已登记适配器和可保真转换的参数。测试同时检查正常映射和被拒绝的零请求路径。已验证范围为回环 legacy Agent DTO、显式请求头与 HTTP/TLS 传输。生产部署特有扩展与未经证实的认证协议保持 unsupported。
+
+本分支以 `0bcb405e7a46418c12bc59464d6be477107df480` 为基线,使用 JDK 21 执行 `./mvnw -B -ntp -o -Dtest=OpenCliRemoteAgentHttpClientTest,OpenCliArgvToCollectParserTest,OpenCliArgvToCollectParserFullTest,OpenCliDiagnosticExportTest test`,退出码为 0。81 项实际执行,其中 56 项为 HTTP 客户端测试,零失败、零错误、零跳过。报告位于 `target/surefire-reports`。
+
+## 平台 HTTP 回归门禁
+
+三线 macOS、Windows 平台工作流同时在 Maven 选择器和协议层报告中登记 OpenCliRemoteAgentHttpClientTest。将该套件从现有报告副本移除后,协议层和整体结果均为 FAIL,即使 Maven 退出码为 0。
+
+本地 macOS 按平台步骤分别运行 Java 8、17、21,三线各执行 202 项,协议层各记录 93 项,其中 HTTP 套件 58 项。两个非法响应字符集用例均实际执行,覆盖收到 HTTP 200 和 503 时保留状态。三线零失败、零错误、零跳过。GitHub 平台结果按对应功能提交核验。
+
+实际 Agent 与 OpenCLI 1.8.8 的三线回环验收及默认端口兼容性差异见 [联调记录](evidence/2026-11-19-live-agent.md)。
+
+同一实际 Agent 的三线 HTTPS、Authorization 及证书名称负例,也已写入 [联调记录](evidence/2026-11-19-live-agent.md#https-和显式-authorization)。
+
+### OC-REMOTE-002 旧版 Agent 的无值选项
+
+锁定的旧版 Agent 为每个 DTO 选项生成两个 argv 元素。原转换把尾部的 `--limit`、后接其他选项的 `--limit` 以及裸开关 `--verbose` 猜为布尔 true。JDK 17 回归中,该三项均错误进入 HTTP。转换现在要求明确的字符串值,拒绝向旧版协议派发裸选项。值明确的 `--limit 5`、`--limit=5` 和已联调的 `--help=true` 路径仍能转换。
diff --git a/openspec/changes/harden-opencli-reverse-agent/tasks.md b/openspec/changes/harden-opencli-reverse-agent/tasks.md
index f7ff684d..a9d43092 100644
--- a/openspec/changes/harden-opencli-reverse-agent/tasks.md
+++ b/openspec/changes/harden-opencli-reverse-agent/tasks.md
@@ -1,27 +1,67 @@
# C05 Tasks · 反向 Worker 状态机、背压与去重
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 已勾选项有对应的实现和回归证据。
关联规范:[spec](specs/opencli-reverse-agent/spec.md)。
## 1. Worker fixture
-- [ ] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
-- [ ] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
+- [x] 1.1 新增可控本地 WS server,覆盖未注册 collect、超大/空 ID、队列满与重复消息。
+- [x] 1.2 加入断线写任务、代际结果路由、close竞态和重启边界的失败测试。
## 2. 治理实现
-- [ ] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。
+- [x] 2.1 建立显式状态机及 READY gate,接收线程仅做有界解析与准入。见本文入站验证。
- [ ] 2.2 用有限执行器替换 cached pool,加入容量校验和兼容 BUSY result。
- [ ] 2.3 实现 payload digest、在途记录与有界完成缓存;同 ID 不同载荷拒绝。
-- [ ] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。
+- [x] 2.4 实现连接代际与有界 drain/cancel,CLOSED 终态。见 OC-WS-006 验证。
## 3. 兼容与验收
-- [ ] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
-- [ ] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
-- [ ] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
+- [x] 3.1 证明重连不自动重复写入,完成发送失败不被误标为执行失败。
+- [x] 3.2 验证现有消息结构在 legacy fixture 中不变,安全日志符合 C09。
+- [x] 3.3 分别在三线运行 WS压力/断线fixture,记录执行次数、线程数与终结资源结果。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## JDK 21 回移验证
+
+回移 JDK 17 版本的注册前拒绝、执行与等待上限、关闭保护、请求去重、缓存过期和连接隔离。通过本地回环服务器、真实子进程和测试证书验证普通连接和 TLS 重连。运行 `bash ./mvnw -B -ntp -o clean verify`,2,112 项测试通过,零失败、零跳过,JaCoCo 行覆盖率为 2,890 / 3,148(91.80%)。
+
+## 2026-11-19 OC-WS-005/006 代际发布与停止竞态
+
+`stopDuringConnectionSetupDoesNotPublishAnotherGeneration` 在连接线程读取端点时阻塞配置读取,随后调用 `stop()`,再解除阻塞。修复前本地中心收到已停止 worker 的注册消息,1 项失败,退出 1。修复后停止和连接发布共用同步边界,晚到连接无法发布。异常、关闭及退出均只退役对应 socket,当前代际检查用于注册、收单和异步结果投递。同一个已验证 TLS 中心显式重发仍可读取对应缓存。异常的默认日志保持固定文本。
+
+`OpenCliWsReverseAgentSessionTest` 的回环服务同时覆盖提前收单、空白和超大 ID、队列溢出、重复请求、断线时在途工作、TLS 显式重发、明文会话隔离、关闭丢弃队列及关闭后拒绝重启。JDK 17 定向验证 27 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,121 项通过,0 失败、0 错误、0 跳过。显式状态机、可重启 stop 的任务收尾合同和平台资源验收仍由相应任务跟踪。
+
+## 2026-11-19 OC-WS-006 可重启停止
+
+`restartableStopDropsQueuedCollectsAndCancelsPastDrainDeadline` 在回环中心提交持续心跳的真实 CLI 子进程,并填满等待队列。CLI 时限配置为 20 秒,确保 SDK 命令时限不会代替 Worker 的停止预算。旧实现返回后在途心跳仍递增,定向 1 项失败,退出 1。修复后 `stop()` 先停止准入、退役原连接、撤销未启动的排队任务,给已运行任务最多 5 秒收尾,再取消剩余任务。回归验证停止调用在 7 秒测试窗口内返回、心跳停止、排队任务没有启动、同一实例重连可接收任务。
+
+已启动任务保留去重占位到实际执行收尾。等待任务撤销时释放占位。重连使用原有固定线程池及其容量。终态 `close()` 仍立即取消在途工作,丢弃队列并在共用预算内等待资源回收,关闭后拒绝重启。
+
+JDK 17 定向 28 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,122 项通过,0 失败、0 错误、0 跳过。显式连接状态机和独立平台资源验收仍由 2.1 和 3.3 跟踪。
+
+## 2026-11-19 OC-WS-001 入站状态与消息上限
+
+每条连接的状态从 `CONNECTING` 经 `REGISTERING` 到 `READY`,退役为 `RETIRED`。只有当前连接收到单个 JSON 对象的合法注册确认后才接单。WebSocket 解码使用默认 1 MiB 的有限上限,覆盖单帧和分片聚合,可在创建 Agent 前配置。超限在 JSON 解析和任务入队前关闭该连接,后续重连需要重新注册。
+
+JDK 17 定向红灯复现三项失败,退出 1。拼接 JSON 错误推进注册,超长单帧和分片均未关闭连接。修复后验证合法确认仍可接单,两个超限场景均关闭连接、没有 CLI 标记且重新注册。发送单个超长帧时,接收方可能在对端写完前关闭连接,对端可观察到 1006 或 1009。分片超限场景验证 1009。补充拒绝零、负数及库定义的无限哨兵设置。JDK 17 定向 34 项通过。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,128 项通过,0 失败、0 错误、0 跳过。
+
+## 2026-11-19 OC-WS-005 投递失败和旧协议兼容
+
+在 TLS 回环环境向第一次结果发送注入异常,CLI 子进程实际写入执行标记。修复前中心等待第二次注册超时,定向 2 项中 1 项失败,退出 1。修复后失败连接退役。第二条连接完成注册和心跳时,中心仍未收到自动投递。中心显式重发相同请求后,收到原成功结果和 `cached: true`,`error` 为空,实际子进程标记始终为一条。日志捕获包含固定的投递失败消息,异常内测试密钥未出现在日志中。
+
+旧协议夹具继续核对 register 的五个字段、pong 的单字段、成功与失败 result 的五个字段,以及实际进程收到的完整 argv。三个版本的直接字段断言通过。JDK 17 定向 35 项通过。JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,129 项通过,0 失败、0 错误、0 跳过。全量通过后单独复跑加严的旧协议字段断言,1 项通过。此处的诊断结论覆盖反向 Worker,跨传输隐私仍由 C09 跟踪。
+
+## 2026-11-19 C05 压力、断线与资源收尾
+
+`disconnectAndCloseReleaseBoundedWorkerResources` 通过回环 WS 中心启动两个持续心跳的真实 CLI 子进程,排队一项并拒绝一项超额请求,随后断开旧连接并重新注册。重连后,每项有效命令仍只执行一次,排队和超额请求均没有启动标记。观测到 2 个收单线程、1 个连接发起线程、2 个 stdout 与 2 个 stderr 读取线程。计数以场景前 JVM 线程集合为基线。
+
+终态关闭后,上述线程和 SDK 的终止工作线程新增数回到零,两个真实子进程的心跳停止,执行标记仍为两条。Surefire 报告保留 `C05 resources: started=2 workerThreads=2 runnerThreads=1 readers=4 threadsAfterClose=0`。该计数覆盖 SDK 自有线程,回环中心和 Java-WebSocket 内部线程由各自生命周期管理。
+
+JDK 21 使用仓库 Maven Wrapper 执行 `-B -ntp -o clean verify`,2,130 项通过,0 失败、0 错误、0 跳过。三条线在本地 macOS 得到相同观测。最新托管平台结果单独记录于 PR。
diff --git a/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md
new file mode 100644
index 00000000..3c9dbb00
--- /dev/null
+++ b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-upstream-stderr.md
@@ -0,0 +1,39 @@
+# OpenCLI 1.8.8 错误输出采样
+
+采样日期为 2026-11-18。运行环境使用 Node 24.18.0,npm 依赖安装在临时目录,三个样本各用隔离的 HOME。来源为 npm 包 `@jackwener/opencli@1.8.8`,包的发布校验值为 `sha512-T0rp89sVWMKdnQHoYwkRDuACy7k/lCvVScOZmpqnBhd1AnXG6XLYSYO6U0D/Zdj8qq9kQqgop3qmElNcbMr+sw==`。相关源码见已锁定的 [Adapter 渲染器](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/commanderAdapter.ts#L159) 和 [错误模型](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/errors.ts)。
+
+| 样本 | 执行方式 | 进程退出码 | YAML `error.exitCode` | stdout |
+|---|---|---:|---:|---:|
+| `error-argument.yaml` | 原生只读命令 `opencli 12306 stations '' -f json`,空参数在请求站点前被拒绝 | 2 | 2 | 0 字节 |
+| `error-auth-required.yaml` | 官方 Adapter 渲染受控 `AuthRequiredError` | 77 | 77 | 0 字节 |
+| `error-empty-result-autofix.yaml` | 官方 Adapter 渲染受控 `EmptyResultError` | 66 | 66 | 0 字节 |
+
+样本保存在 `src/test/resources/opencli-contracts/v1`,stderr 按字节保存,摘要见同目录的 `SHA256SUMS`。即使指定 `-f json`,三例的 stderr 均为 YAML。官方渲染器为 `EMPTY_RESULT` 附加 `# AutoFix` 注释,`AUTH_REQUIRED` 的样本没有该注释。如果后续 decoder 测试组合这两个字段,应标注为合成回归样本。
+
+## 复核受控样本
+
+在临时目录安装锁定包后,将下列内容保存为 `capture.mjs`,分别设置 `OPENCLI_FIXTURE=auth` 或 `OPENCLI_FIXTURE=empty`,用 Node 运行并独立收集 stdout、stderr 与退出码。
+
+```javascript
+import { Command } from 'commander';
+import { registerCommandToProgram } from './node_modules/@jackwener/opencli/dist/src/commanderAdapter.js';
+import { AuthRequiredError, EmptyResultError } from './node_modules/@jackwener/opencli/dist/src/errors.js';
+
+const program = new Command().name('opencli');
+registerCommandToProgram(program.command('fixture'), {
+ site: 'fixture',
+ name: 'check',
+ description: 'Offline fixture',
+ args: [],
+ browser: false,
+ func() {
+ if (process.env.OPENCLI_FIXTURE === 'auth') {
+ throw new AuthRequiredError('example.invalid');
+ }
+ throw new EmptyResultError('fixture/check', 'No rows in the offline fixture');
+ },
+});
+await program.parseAsync(['fixture', 'check', '-f', 'json'], { from: 'user' });
+```
+
+两个受控 Adapter 均在本地抛出错误。未执行登录、真实站点请求、写操作或注释中的修复命令。本次证据只完成 C03 任务 1.1,decoder 的实现和验收仍待评审。
diff --git a/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md
new file mode 100644
index 00000000..3bab2d6f
--- /dev/null
+++ b/openspec/changes/preserve-opencli-error-envelope/evidence/2026-11-18-yaml-parser-review.md
@@ -0,0 +1,16 @@
+# C03 YAML 解析器候选验证(2026-11-18)
+
+C03 评审候选为 `org.yaml:snakeyaml:2.7`,三条 Java 维护线可共用。SnakeYAML Engine 的当前维护线要求 Java 11 或更新版本。[SnakeYAML](https://github.com/snakeyaml/snakeyaml) · [SnakeYAML Engine](https://github.com/snakeyaml/snakeyaml-engine) · [Maven Central 发布包](https://repo.maven.apache.org/maven2/org/yaml/snakeyaml/2.7/)
+
+## 探针结果
+
+独立探针使用 SHA-256 为 `2e194eba45a67dee19a4e272f4a04b18de8054e9f598b094382f6dae0b0e4b5e` 的 2.7 JAR。以 JDK 8 编译一次,在 8u504、17.0.21、21.0.13.0.2 各执行 30 个断言。三轮退出码均为 0。使用三个 [OpenCLI 1.8.8 真实 stderr 样本](2026-11-18-upstream-stderr.md) 及合成输入。探针未接入 SDK,SDK 当前行为仍由既有执行器决定。
+
+- 三个真实样本均读出 `ok: false`、原始错误码及整数退出码。带 `# AutoFix` 的样本正常解析。合成 JSON 子集保留未识别的错误码和 trace 路径。普通单行文本得到字符串,后续 envelope 校验应按原执行状态处理。
+- 普通 `SafeConstructor` 的 YAML 1.1 规则会将 `no`、`off` 和日期转成布尔值与日期类型。自定义隐式解析范围只接受 JSON 形式的布尔、空值、整数和小数。日期样式、`no`、`off` 和前导零字符串在探针中均保留原值。
+- 默认浮点映射会将 `1e400` 转为无穷大,并对长小数取近似值。探针改用 `BigDecimal` 保留两者,后续模型应避免以浮点近似值覆盖扩展字段。
+- 用库的事件流预检,拒绝锚点和别名、显式标记、多个文档及超过 32 层的集合。用加载选项拒绝重复键。UTF-8 字节检查在入口执行,加载器另外限制码点数。探针验证了 32 层和 256 KiB 边界、多字节超限、截断的 JSON 形态以及被禁止的 YAML 特性。普通运行日志仅记录断言数量。
+
+## 实现评审范围
+
+建议在 JSON 路径复用各分支已有 Jackson,并以严格 JSON 判定处理疑似 JSON 的失败输入。YAML 路径建议采用事件预检和受限构造,再检查 envelope 形状及字符串键。需用 SDK 测试验证退出码来源、解析状态、超时优先级、日志脱敏和无重试副作用。评审前保留 C03 任务 2.1 未勾选,三个 POM 均未引入该候选依赖。
diff --git a/openspec/changes/preserve-opencli-error-envelope/specs/opencli-error-envelope/spec.md b/openspec/changes/preserve-opencli-error-envelope/specs/opencli-error-envelope/spec.md
index fea99c49..4ba193cc 100644
--- a/openspec/changes/preserve-opencli-error-envelope/specs/opencli-error-envelope/spec.md
+++ b/openspec/changes/preserve-opencli-error-envelope/specs/opencli-error-envelope/spec.md
@@ -1,6 +1,6 @@
# 上游错误协议解析与证据保真
-> Proposal specification. Status: DRAFT / NOT_IMPLEMENTED.
+> Implementation verified on the feature branches. PR review and merge are pending.
## ADDED Requirements
diff --git a/openspec/changes/preserve-opencli-error-envelope/tasks.md b/openspec/changes/preserve-opencli-error-envelope/tasks.md
index fee0afa2..c5d75177 100644
--- a/openspec/changes/preserve-opencli-error-envelope/tasks.md
+++ b/openspec/changes/preserve-opencli-error-envelope/tasks.md
@@ -1,26 +1,45 @@
# C03 Tasks · 上游错误协议解析与证据保真
-> 全部为待执行实现任务。文档/格式检查通过不允许提前勾选。
+> 错误信封实现和回归已在三条功能分支核对,待 PR 评审与合并。验收证据见下文。
关联规范:[spec](specs/opencli-error-envelope/spec.md)。
## 1. 错误 fixture
-- [ ] 1.1 从锁定上游 renderError/真实只读负例建立 YAML fixture,保存版本与 hash。
-- [ ] 1.2 补 JSON、纯文本、AutoFix 注释、exit mismatch、unknown code、malformed 和恶意 YAML 失败测试。
+- [x] 1.1 从锁定上游 renderError/真实只读负例建立 YAML fixture,保存版本与 hash。见 [上游 stderr 采样](evidence/2026-11-18-upstream-stderr.md)。
+- [x] 1.2 补 JSON、纯文本、AutoFix 注释、exit mismatch、unknown code、malformed 和恶意 YAML 失败测试。
## 2. decoder 与结果
-- [ ] 2.1 选定三线可用的安全 YAML 实现并验证安全配置,不复制不兼容 Jackson imports。
-- [ ] 2.2 实现有界 shape 校验和 provenance 模型,保留 help/trace/unknown fields。
-- [ ] 2.3 接入本地异常与 partial result,避免 parser 抢占 primary failure。
+- [x] 2.1 选定三线可用的安全 YAML 实现并验证安全配置,不复制不兼容 Jackson imports。见 [三线候选探针](evidence/2026-11-18-yaml-parser-review.md)。
+- [x] 2.2 实现有界 shape 校验和 provenance 模型,保留 help/trace/unknown fields。
+- [x] 2.3 接入本地异常与 partial result,避免 parser 抢占 primary failure。
## 3. 回归与迁移
-- [ ] 3.1 验证诊断日志不会输出 parser exception 中的原始敏感片段,配合 C09。
-- [ ] 3.2 验证写操作不会因解析器或 help 自动重试。
+- [x] 3.1 验证诊断日志不会输出 parser exception 中的原始敏感片段,配合 C09。
+- [x] 3.2 验证写操作不会因解析器或 help 自动重试。
- [ ] 3.3 在三个分支运行共享失败 fixtures,记录真实结果并更新迁移说明。
## 证据交付模板(实施时填写)
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
+
+## OC-ERR-001–006 本地解码与退出来源
+
+`OpenCliResult.errorEnvelope` 在本地失败上提供解码状态、错误码、错误消息、help、trace、扩展字段与独立的 observed/reported 退出码。原始 stderr 保留在结果中。超时、非零退出、输出限额和不完整流继续由执行器决定主异常,由此避免解码覆盖执行证据。成功结果和原有远端 collect 保持各自路径。
+
+JSON 复用各版本线 Jackson,严格检查重复键、尾随内容及嵌套深度。YAML 使用 SnakeYAML 2.7 的事件预检和安全构造器,保留 JSON 标量语义,拒绝锚点、别名、显式标签、重复键及多文档。解码预算为 256 KiB UTF-8、32 层。解析失败仅以状态呈现,原始诊断片段留在 stderr。AutoFix 和 trace 路径作为数据保存。
+
+`OpenCliErrorEnvelopeTest` 首先因缺少 API 无法编译。实现后使用已归档 YAML、合成 JSON 和真实 JVM 子进程验证解码、退出值不一致、输入拒绝、超时优先、诊断脱敏与单次执行。现有远端失败分类继续由 C04 测试覆盖。
+
+
+## C03 实施核对
+
+- OC-ERR-001 / OC-ERR-002。归档 YAML 和等价 JSON 验证错误码、help、AutoFix 原文、trace 及扩展字段类型,纯文本随退出状态处理。
+- OC-ERR-003。真实子进程和等价解码用例核对实际退出 1、报告退出 77 和 mismatch 各自保留。
+- OC-ERR-004。回归覆盖输入上限、嵌套深度、重复键、多文档、显式标签、锚点、别名及畸形 JSON/YAML。
+- OC-ERR-005。真实进程的非零退出和超时用例验证主异常、部分信封和原始 stderr。新增畸形 YAML 用例同时捕获 SDK 默认诊断和完整异常栈,确认原始 canary 只出现在显式读取的 stderr。
+- OC-ERR-006。真实子进程用 marker 计数,验证解析 AutoFix 建议时只执行一次。
+
+本分支以 `5955fc1fdc96a238bfc67f67e453036832a23b09` 为基线,使用 JDK 21 执行 `./mvnw -B -ntp -o -Dtest=OpenCliErrorEnvelopeTest,OpenCliProcessPrivacyTest,OpenCliStdoutJsonTest test`。退出码为 0。21 项实际执行,其中 8 项为错误信封回归,零失败、零错误、零跳过。报告位于 `target/surefire-reports`。
diff --git a/pom.xml b/pom.xml
index ec8441f5..5a1fd22d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -131,6 +131,11 @@
tools.jackson.core
jackson-databind
+
+ org.yaml
+ snakeyaml
+ 2.7
+
org.apache.commons
@@ -163,6 +168,11 @@
junit-jupiter
test
+
+ org.slf4j
+ slf4j-simple
+ test
+
diff --git a/scripts/contract_report.py b/scripts/contract_report.py
new file mode 100644
index 00000000..23e780e1
--- /dev/null
+++ b/scripts/contract_report.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""Build fail-closed, layer-specific evidence from real Surefire XML reports.
+
+This is not a code coverage percentage or a claim that OpenCLI websites work.
+Only explicitly selected suites contribute to a layer. No network is used.
+"""
+import argparse
+import json
+import pathlib
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+LAYERS = ('enumeration', 'argv', 'process', 'protocol', 'typed-result', 'real-execution')
+TRACE_TEST_LINK = re.compile(
+ r'\[`(?P[\w$]+)#(?P[\w$]+)`\]'
+ r'\(https://github\.com/easy-4-java/opencli-java-sdk/blob/[0-9a-f]{40}/'
+ r'src/test/java/(?P[\w$/]+)\.java#L\d+\)'
+)
+
+
+def read_trace_methods(path):
+ """Read the pinned Java method links from the requirement trace."""
+ methods = {}
+ for link in TRACE_TEST_LINK.finditer(path.read_text(encoding='utf-8')):
+ suite = link['path'].replace('/', '.')
+ if suite.rsplit('.', 1)[-1] != link['class_name']:
+ raise ValueError('requirement trace links a method to another class')
+ methods.setdefault(suite, set()).add(link['method'])
+ if not methods:
+ raise ValueError('requirement trace contains no pinned Java test methods')
+ return methods
+
+
+def _suite_summary(suite):
+ declared = {key: int(suite.attrib.get(key, '0')) for key in ('tests', 'failures', 'errors', 'skipped')}
+ cases = suite.findall('testcase')
+ actual = {'tests': len(cases), 'failures': sum(c.find('failure') is not None for c in cases),
+ 'errors': sum(c.find('error') is not None for c in cases),
+ 'skipped': sum(c.find('skipped') is not None for c in cases)}
+ if declared != actual or any(v < 0 for v in declared.values()):
+ raise ValueError('declared testcase counts disagree with XML evidence')
+ actual['executed'] = actual['tests'] - actual['skipped']
+ return actual
+
+
+def build_report(reports_dir, *, head, branch, java_version, maven_version, exit_code, required_suites,
+ trace_methods=None):
+ """Return a JSON-serializable report; malformed/missing evidence fails closed."""
+ problems = []
+ if not re.fullmatch(r'[0-9a-fA-F]{40}', head or ''):
+ problems.append('exact 40-character source HEAD is required')
+ if not branch or not java_version.strip() or not maven_version.strip():
+ problems.append('branch and actual tool versions are required')
+ if exit_code != 0:
+ problems.append('verification command exited nonzero')
+ if not required_suites or any(layer not in LAYERS or not names for layer, names in required_suites.items()):
+ problems.append('non-empty required suites must use recognized layers')
+ attributed = [name for names in required_suites.values() for name in names]
+ if len(attributed) != len(set(attributed)):
+ problems.append('suite attribution must be unique across layers')
+ trace_methods = {} if trace_methods is None else trace_methods
+ expected_methods = {name: trace_methods[name] for name in attributed if name in trace_methods}
+ if trace_methods and not expected_methods:
+ problems.append('no selected suites match the requirement trace')
+ suites = {}
+ passed_methods = {}
+ for path in sorted(pathlib.Path(reports_dir).glob('TEST-*.xml')):
+ try:
+ root = ET.parse(path).getroot()
+ nodes = [root] if root.tag == 'testsuite' else list(root.findall('testsuite'))
+ if not nodes:
+ raise ValueError('no testsuite')
+ for suite in nodes:
+ name = suite.attrib['name']
+ if name in suites:
+ raise ValueError('duplicate testsuite')
+ suites[name] = _suite_summary(suite)
+ if name in expected_methods:
+ passed_methods[name] = {
+ re.split(r'[\[(]', case.attrib.get('name', ''), maxsplit=1)[0]
+ for case in suite.findall('testcase')
+ if case.attrib.get('classname') == name
+ and not any(case.find(tag) is not None for tag in ('skipped', 'failure', 'error'))
+ }
+ except (ET.ParseError, OSError, KeyError, ValueError):
+ problems.append('invalid or duplicate Surefire report: ' + path.name)
+ layers = {}
+ for layer in LAYERS:
+ names = list(required_suites.get(layer, []))
+ counts = dict.fromkeys(('tests', 'executed', 'skipped', 'failures', 'errors'), 0)
+ missing = [name for name in names if name not in suites]
+ for name in names:
+ for key in counts:
+ counts[key] += suites.get(name, {}).get(key, 0)
+ unproven = [
+ name for name in names
+ if name not in suites or suites[name]['executed'] == 0
+ or any(suites[name][key] for key in ('skipped', 'failures', 'errors'))
+ ]
+ absent_methods = {name: sorted(expected_methods[name] - passed_methods.get(name, set()))
+ for name in names if name in expected_methods}
+ absent_methods = {name: methods for name, methods in absent_methods.items() if methods}
+ state = 'NOT_RUN' if not names else ('FAIL' if unproven or absent_methods else 'PASS')
+ method_count = sum(len(expected_methods.get(name, ())) for name in names)
+ layers[layer] = dict(counts, status=state, requiredSuites=names, missingSuites=missing,
+ unprovenSuites=unproven, requiredMethodCount=method_count,
+ missingMethods=absent_methods)
+ if unproven:
+ problems.append('required layer lacks passing, non-skipped execution: ' + layer)
+ if absent_methods:
+ problems.append('required layer lacks traced test methods: ' + layer)
+ return {'schemaVersion': 1, 'status': 'FAIL' if problems else 'PASS',
+ 'head': head, 'branch': branch, 'javaVersion': java_version,
+ 'mavenVersion': maven_version, 'commandExitCode': exit_code,
+ 'layers': layers, 'problems': problems,
+ 'scope': 'Explicit Surefire suites only; synthetic argv/process probes are not live OpenCLI verification.'}
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--reports', type=pathlib.Path, required=True)
+ parser.add_argument('--head', required=True)
+ parser.add_argument('--branch', required=True)
+ parser.add_argument('--java-version-file', type=pathlib.Path, required=True)
+ parser.add_argument('--maven-version-file', type=pathlib.Path, required=True)
+ parser.add_argument('--exit-code', type=int, required=True)
+ parser.add_argument('--suite', action='append', required=True, help='layer=fully.qualified.TestClass; repeatable')
+ parser.add_argument('--trace', type=pathlib.Path, help='require linked Java methods for selected suites')
+ parser.add_argument('--output', type=pathlib.Path, required=True)
+ args = parser.parse_args(argv)
+ required = {}
+ attributed = set()
+ for item in args.suite:
+ layer, separator, name = item.partition('=')
+ if not separator or layer not in LAYERS or not name:
+ parser.error('--suite must be recognized-layer=fully.qualified.TestClass')
+ if name in attributed:
+ parser.error('--suite must be unique across layers')
+ attributed.add(name)
+ required.setdefault(layer, []).append(name)
+ try:
+ trace_methods = read_trace_methods(args.trace) if args.trace else None
+ report = build_report(args.reports, head=args.head, branch=args.branch,
+ java_version=args.java_version_file.read_text(encoding='utf-8'),
+ maven_version=args.maven_version_file.read_text(encoding='utf-8'),
+ exit_code=args.exit_code, required_suites=required, trace_methods=trace_methods)
+ except OSError as exc:
+ print('Missing contract evidence input: ' + exc.__class__.__name__, file=sys.stderr)
+ return 1
+ except ValueError as exc:
+ print(str(exc), file=sys.stderr)
+ return 1
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
+ print(json.dumps({'status': report['status'], 'head': report['head'], 'layers': report['layers']}))
+ return 0 if report['status'] == 'PASS' else 1
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/generate_opencli_command_tests.py b/scripts/generate_opencli_command_tests.py
index 329a7ae6..14e43efa 100644
--- a/scripts/generate_opencli_command_tests.py
+++ b/scripts/generate_opencli_command_tests.py
@@ -9,28 +9,16 @@
"""
from __future__ import annotations
+import argparse
+import hashlib
import json
import os
import textwrap
+from datetime import date
from pathlib import Path
_SCRIPT_DIR = Path(__file__).resolve().parent
_SDK_ROOT = _SCRIPT_DIR.parent
-_DEFAULT_MANIFEST = (
- _SCRIPT_DIR.parents[4]
- / "workspace-partme-ai"
- / "opencli"
- / "opencli"
- / "cli-manifest.json"
-)
-if not _DEFAULT_MANIFEST.is_file():
- _DEFAULT_MANIFEST = (
- Path("/Users/wandl/workspaces/workspace-partme-ai/opencli/opencli/cli-manifest.json")
- )
-
-MANIFEST_PATH = Path(
- os.environ.get("OPENCLI_MANIFEST", _DEFAULT_MANIFEST)
-).resolve()
COVERAGE_PKG = "io.github.easy4j.opencli.coverage"
COVERAGE_DIR = _SDK_ROOT / "src/test/java/io/github/easy4j/opencli/coverage"
@@ -77,14 +65,7 @@ def build_command_request(entry: dict) -> dict:
}
-def load_manifest() -> list[dict]:
- data = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
- if not isinstance(data, list):
- raise SystemExit("manifest must be a JSON array")
- return data
-
-
-def write_manifest_resource(entries: list[dict]) -> None:
+def write_manifest_resource(entries: list[dict], provenance: dict) -> None:
RESOURCES_DIR.mkdir(parents=True, exist_ok=True)
payload = [build_command_request(e) for e in entries]
out = RESOURCES_DIR / "manifest-coverage-commands.json"
@@ -93,7 +74,7 @@ def write_manifest_resource(entries: list[dict]) -> None:
meta.write_text(
json.dumps(
{
- "manifestPath": str(MANIFEST_PATH),
+ **provenance,
"manifestCommandCount": len(entries),
"siteCount": len({e["site"] for e in entries}),
},
@@ -682,10 +663,29 @@ class OpenCliCommandCoverageSummaryTest {{
def main() -> None:
- if not MANIFEST_PATH.is_file():
- raise SystemExit(f"missing manifest: {MANIFEST_PATH}")
- entries = load_manifest()
- write_manifest_resource(entries)
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, default=os.environ.get("OPENCLI_MANIFEST"),
+ help="Local copy of upstream cli-manifest.json; defaults to OPENCLI_MANIFEST")
+ parser.add_argument("--manifest-source", required=True,
+ help="Upstream URL identifying the package version or source revision")
+ parser.add_argument("--observed-at", type=date.fromisoformat, required=True, help="Observation date (YYYY-MM-DD)")
+ parser.add_argument("--acquisition-command", required=True, help="Portable command to obtain the upstream input")
+ args = parser.parse_args()
+ if args.manifest is None:
+ parser.error("specify --manifest or OPENCLI_MANIFEST")
+ if not args.manifest.is_file():
+ parser.error(f"missing manifest: {args.manifest}")
+ manifest_bytes = args.manifest.read_bytes()
+ entries = json.loads(manifest_bytes)
+ if not isinstance(entries, list):
+ parser.error("manifest must be a JSON array")
+ write_manifest_resource(entries, {
+ "manifestPath": args.manifest_source,
+ "manifestSha256": hashlib.sha256(manifest_bytes).hexdigest(),
+ "observedAt": args.observed_at.isoformat(),
+ "acquisitionCommand": args.acquisition_command,
+ "scope": "Bundled adapter command enumeration from cli-manifest.json",
+ })
write_adapter_coverage_test(len(entries))
# meta_count 涵盖 list/validate/verify/doctor/completion/convention-audit +
# plugin (install/uninstall/update/updateAll/list/create) +
diff --git a/scripts/run_browser_bridge_contracts.py b/scripts/run_browser_bridge_contracts.py
new file mode 100644
index 00000000..5cbb1214
--- /dev/null
+++ b/scripts/run_browser_bridge_contracts.py
@@ -0,0 +1,251 @@
+"""Run the Java Browser Bridge contract against an isolated real browser."""
+import argparse
+from hashlib import sha256
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from urllib.error import URLError
+from urllib.parse import quote
+from urllib.request import Request, urlopen
+from xml.etree import ElementTree
+from zipfile import ZipFile
+
+import contract_report
+
+
+OPENCLI_VERSION = '1.8.8'
+EXTENSION_VERSION = '1.0.24'
+EXTENSION_SHA = 'bad9163f32a66224404e302f52f35391672341d2bd0bf30c8bbaae3c6e6e246c'
+CHROME_VERSION = '158.0.8127.18'
+DAEMON_STATUS = 'http://127.0.0.1:19825/status'
+SUITE = 'io.github.easy4j.opencli.contract.OpenCliBrowserBridgeIT'
+REQUIRED_CASES = {
+ 'boundTabSurvivesTypedSuccessFailureAndClientShutdown',
+ 'boundedNetworkFollowLeavesTheRealBridgeAndPageAvailable',
+ 'queryAndCaptureUseTheRealBridgeResponses',
+ 'typedResultsFromAnIsolatedChromePage',
+}
+PAGE = b"""Bridge fixture
+"""
+
+
+class FixtureHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == '/api/items':
+ body, content_type = b'{"items":[{"id":17}]}', 'application/json'
+ else:
+ body, content_type = PAGE, 'text/html; charset=utf-8'
+ self.send_response(200)
+ self.send_header('Content-Type', content_type)
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_):
+ pass
+
+
+def download_zip(url, directory, expected_sha=None):
+ archive = directory.with_suffix('.zip')
+ with urlopen(url, timeout=60) as response, archive.open('wb') as output:
+ shutil.copyfileobj(response, output)
+ if expected_sha and sha256(archive.read_bytes()).hexdigest() != expected_sha:
+ raise RuntimeError(f'Artifact digest mismatch for {url}')
+ with ZipFile(archive) as zipped:
+ zipped.extractall(directory)
+ if os.name != 'nt':
+ for entry in zipped.infolist():
+ if entry.external_attr >> 16 & 0o111:
+ (directory / entry.filename).chmod(0o755)
+
+
+def chrome_executable(root):
+ platform = {'linux': 'linux64', 'win32': 'win64'}[sys.platform]
+ download_zip(
+ f'https://storage.googleapis.com/chrome-for-testing-public/{CHROME_VERSION}/{platform}/chrome-{platform}.zip',
+ root / 'chrome',
+ )
+ return root / 'chrome' / f'chrome-{platform}' / ('chrome.exe' if os.name == 'nt' else 'chrome')
+
+
+def daemon_status():
+ with urlopen(Request(DAEMON_STATUS, headers={'X-OpenCLI': '1'}), timeout=1) as response:
+ return json.load(response)
+
+
+def wait_for_bridge(daemon, browser):
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if daemon.poll() is not None or browser.poll() is not None:
+ raise RuntimeError('The isolated daemon or Chrome exited before the extension connected')
+ try:
+ status = daemon_status()
+ except URLError:
+ time.sleep(0.25)
+ continue
+ if status.get('pid') != daemon.pid:
+ raise RuntimeError('The Bridge endpoint belongs to a different daemon')
+ if status.get('extensionConnected'):
+ if (status.get('daemonVersion'), status.get('extensionVersion')) != (OPENCLI_VERSION, EXTENSION_VERSION):
+ raise RuntimeError('The connected Bridge versions differ from the pinned versions')
+ return status
+ time.sleep(0.25)
+ raise RuntimeError('The extension did not connect to the isolated daemon')
+
+
+def prepare_bound_tab(profile, url):
+ # Windows Chrome can open a startup tab before its URL is set. Provision the
+ # user tab via the independent DevTools endpoint and wait for navigation.
+ deadline = time.monotonic() + 15
+ port_file = profile / 'DevToolsActivePort'
+ while not port_file.exists() and time.monotonic() < deadline:
+ time.sleep(0.1)
+ port = int(port_file.read_text(encoding='utf-8').splitlines()[0])
+ endpoint = f'http://127.0.0.1:{port}/json'
+ with urlopen(Request(endpoint + '/new?' + quote(url, safe=':/'), method='PUT'), timeout=5) as response:
+ target = json.load(response)['id']
+ while time.monotonic() < deadline:
+ with urlopen(endpoint + '/list', timeout=2) as response:
+ if any(page['id'] == target and page.get('url') == url for page in json.load(response)):
+ with urlopen(endpoint + '/activate/' + target, timeout=2):
+ return
+ time.sleep(0.1)
+ raise RuntimeError('The original Chrome fixture tab did not finish navigation')
+
+
+def stop(process):
+ if process is None or process.poll() is not None:
+ return
+ process.terminate()
+ try:
+ process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+
+
+def require_bridge_cases(report, xml):
+ layer = report['layers']['real-execution']
+ if layer['status'] != 'PASS':
+ return
+ cases = ElementTree.parse(xml).getroot().findall('testcase')
+ missing = sorted(REQUIRED_CASES - {case.get('name') for case in cases})
+ layer['missingCases'] = missing
+ if missing:
+ layer['status'] = report['status'] = 'FAIL'
+ report['problems'].append('Required Browser Bridge cases are missing: ' + ', '.join(missing))
+
+
+def execute(args, root, evidence):
+ extension = root / 'extension'
+ download_zip(f'https://github.com/jackwener/OpenCLI/releases/download/v{OPENCLI_VERSION}/'
+ f'opencli-extension-v{EXTENSION_VERSION}.zip', extension, EXTENSION_SHA)
+ chrome = args.chrome or chrome_executable(root)
+ node = shutil.which('node')
+ if not node:
+ raise RuntimeError('Node executable is unavailable')
+ home = root / 'home'
+ home.mkdir()
+ env = dict(os.environ, HOME=str(home), USERPROFILE=str(home),
+ OPENCLI_CONFIG_DIR=str(root / 'config'), OPENCLI_CACHE_DIR=str(root / 'cache'),
+ OPENCLI_INSTALLED_NODE=node, OPENCLI_INSTALLED_ENTRY=str(args.cli_entry))
+ for name in ('OPENCLI_DAEMON_PORT', 'OPENCLI_CDP_ENDPOINT', 'OPENCLI_CDP_TARGET'):
+ env.pop(name, None)
+
+ # Use the upstream loopback port without changing the published binaries.
+ try:
+ daemon_status()
+ except URLError:
+ pass
+ else:
+ raise RuntimeError('An existing OpenCLI daemon already uses the fixture port')
+
+ reports = Path('target/surefire-reports')
+ xml = reports / f'TEST-{SUITE}.xml'
+ xml.unlink(missing_ok=True)
+ java = subprocess.run(['java', '-version'], check=True, capture_output=True, text=True)
+ maven_launcher = shutil.which(args.maven[0])
+ if not maven_launcher:
+ raise RuntimeError(f'Maven launcher is unavailable: {args.maven[0]}')
+ maven_command = [maven_launcher, *args.maven[1:]]
+ maven = subprocess.run([*maven_command, '-version'], check=True, capture_output=True, text=True)
+ daemon = browser = None
+ with ThreadingHTTPServer(('127.0.0.1', 0), FixtureHandler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{server.server_port}/fixture.html'
+ env['OPENCLI_BRIDGE_FIXTURE_URL'] = url
+ try:
+ with (evidence / 'daemon.log').open('w') as log:
+ daemon = subprocess.Popen([node, str(args.cli_entry.with_name('daemon.js'))],
+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT)
+ profile = root / 'profile'
+ chrome_args = [
+ '--headless=new', '--no-first-run', '--no-default-browser-check',
+ '--disable-background-networking', '--disable-component-update',
+ '--disable-sync', '--remote-debugging-port=0', '--no-proxy-server',
+ '--host-resolver-rules=MAP localhost 127.0.0.1',
+ '--user-data-dir=' + str(profile),
+ '--disable-extensions-except=' + str(extension), '--load-extension=' + str(extension),
+ ]
+ if sys.platform == 'linux' and os.environ.get('GITHUB_ACTIONS') == 'true':
+ # Hosted Ubuntu blocks unprivileged user namespaces for this pinned Chrome.
+ chrome_args.append('--no-sandbox')
+ if sys.platform == 'darwin':
+ chrome_args.append('--use-mock-keychain')
+ with (evidence / 'chrome.log').open('w') as log:
+ browser = subprocess.Popen([str(chrome), *chrome_args, 'about:blank'],
+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT)
+ wait_for_bridge(daemon, browser)
+ prepare_bound_tab(profile, url.replace('/fixture', '/bound-fixture'))
+ with (evidence / 'maven.log').open('w') as log:
+ result = subprocess.run([*maven_command, '-B', '--no-transfer-progress', '-Dtest=OpenCliBrowserBridgeIT', 'test'],
+ env=env, stdout=log, stderr=subprocess.STDOUT, timeout=180)
+ status = wait_for_bridge(daemon, browser)
+ (evidence / 'bridge.json').write_text(json.dumps({
+ 'daemonPid': daemon.pid, 'chromePid': browser.pid, 'chromeVersion': CHROME_VERSION,
+ 'opencliVersion': status['daemonVersion'], 'extensionVersion': status['extensionVersion'],
+ }) + '\n', encoding='utf-8')
+ finally:
+ stop(browser)
+ stop(daemon)
+ server.shutdown()
+
+ if xml.exists():
+ shutil.copyfile(xml, evidence / xml.name)
+ report = contract_report.build_report(
+ evidence, head=subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(),
+ branch=os.environ.get('GITHUB_REF_NAME') or subprocess.check_output(
+ ['git', 'branch', '--show-current'], text=True).strip(),
+ java_version=(java.stdout + java.stderr).strip(), maven_version=(maven.stdout + maven.stderr).strip(),
+ exit_code=result.returncode, required_suites={'real-execution': [SUITE]},
+ )
+ require_bridge_cases(report, evidence / xml.name)
+ (evidence / 'report.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8')
+ print(json.dumps(report['layers']['real-execution']))
+ return 0 if report['status'] == 'PASS' else 1
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--cli-entry', required=True, type=lambda path: Path(path).resolve())
+ parser.add_argument('--chrome', type=lambda path: Path(path).resolve())
+ parser.add_argument('--evidence', required=True, type=lambda path: Path(path).resolve())
+ parser.add_argument('maven', nargs='+')
+ args = parser.parse_args()
+ args.evidence.mkdir(parents=True, exist_ok=False)
+ with tempfile.TemporaryDirectory(prefix='opencli-bridge-', ignore_cleanup_errors=True) as root:
+ return execute(args, Path(root), args.evidence)
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/run_installed_contracts.sh b/scripts/run_installed_contracts.sh
new file mode 100644
index 00000000..31f4cd89
--- /dev/null
+++ b/scripts/run_installed_contracts.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+# Verify the pinned published CLI in an isolated installation and record live-only evidence.
+set -euo pipefail
+
+report_dir=platform-evidence
+mkdir -p "$report_dir"
+temp_root=${RUNNER_TEMP:?}
+if [[ "${RUNNER_OS:-}" == Windows ]]; then
+ temp_root=$(cygpath -u "$temp_root")
+fi
+install_dir=$(mktemp -d "$temp_root/opencli-installed.XXXXXX")
+npm install --prefix "$install_dir" --ignore-scripts --no-audit --no-fund @jackwener/opencli@1.8.8
+
+cli_entry="$install_dir/node_modules/@jackwener/opencli/dist/src/main.js"
+export CI=1 NO_COLOR=1
+node --version > "$report_dir/installed-node.txt"
+node "$cli_entry" --version > "$report_dir/installed-opencli-version.txt"
+grep -Fx '1.8.8' "$report_dir/installed-opencli-version.txt"
+
+export OPENCLI_INSTALLED_NODE
+OPENCLI_INSTALLED_NODE=$(node -p 'process.execPath')
+export OPENCLI_INSTALLED_ENTRY="$cli_entry"
+tests=OpenCliCapabilityOverrideIT,OpenCliReadOnlyDiagnosticsIT
+suites=(
+ --suite real-execution=io.github.easy4j.opencli.contract.OpenCliCapabilityOverrideIT
+ --suite real-execution=io.github.easy4j.opencli.contract.OpenCliReadOnlyDiagnosticsIT
+)
+if [[ "${RUNNER_OS:-}" == Windows ]]; then
+ registry="$install_dir/registry.json"
+ node "$cli_entry" list -f json > "$registry"
+ OPENCLI_INSTALLED_ENTRY=$(cygpath -w "$cli_entry")
+ export OPENCLI_INSTALLED_REGISTRY
+ OPENCLI_INSTALLED_REGISTRY=$(cygpath -w "$registry")
+ export OPENCLI_INSTALLED_BATCH_SHIM
+ OPENCLI_INSTALLED_BATCH_SHIM=$(cygpath -w "$install_dir/node_modules/.bin/opencli.cmd")
+ tests+=,OpenCliInstalledLauncherIT
+ suites+=(--suite real-execution=io.github.easy4j.opencli.contract.OpenCliInstalledLauncherIT)
+fi
+
+java -version > "$report_dir/installed-java.txt" 2>&1
+"$@" -version > "$report_dir/installed-maven.txt" 2>&1
+reports=target/surefire-reports
+if [[ -d "$reports" ]]; then
+ prior_reports=$(mktemp -d "$report_dir/pre-install-surefire.XXXXXX")
+ mv "$reports" "$prior_reports/"
+fi
+result=0
+"$@" -B --no-transfer-progress "-Dtest=$tests" test > "$report_dir/installed-maven.log" 2>&1 || result=$?
+tail -80 "$report_dir/installed-maven.log"
+python scripts/contract_report.py \
+ --reports "$reports" \
+ --head "$(git rev-parse HEAD)" \
+ --branch "${GITHUB_REF_NAME:-$(git branch --show-current)}" \
+ --java-version-file "$report_dir/installed-java.txt" \
+ --maven-version-file "$report_dir/installed-maven.txt" \
+ --exit-code "$result" \
+ "${suites[@]}" \
+ --output "$report_dir/installed-report.json"
diff --git a/scripts/tests/test_contract_report.py b/scripts/tests/test_contract_report.py
new file mode 100644
index 00000000..54e9c7af
--- /dev/null
+++ b/scripts/tests/test_contract_report.py
@@ -0,0 +1,210 @@
+import importlib.util
+import json
+import os
+import pathlib
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+
+SCRIPT = pathlib.Path(__file__).resolve().parents[1] / 'contract_report.py'
+HEAD = 'd0c8056990f7a47fcc202acffa387ba066bcfc67'
+SUITE = 'io.github.easy4j.opencli.contract.OpenCliArgvContractTest'
+SECOND_SUITE = 'io.github.easy4j.opencli.contract.OpenCliStructuredArgvContractTest'
+
+
+class ContractReportTest(unittest.TestCase):
+ def setUp(self):
+ self.assertTrue(SCRIPT.is_file(), 'C10 contract report runner is not implemented')
+ spec = importlib.util.spec_from_file_location('contract_report', SCRIPT)
+ self.module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(self.module)
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = pathlib.Path(self.temp.name)
+
+ def xml(self, tests=2, skipped=0, failures=0, errors=0, suite=SUITE):
+ executed = tests - skipped
+ cases = []
+ for i in range(tests):
+ child = '' if i >= executed else ('' if i < failures else ('' if i < failures + errors else ''))
+ cases.append('' + child + '')
+ (self.root / ('TEST-' + suite + '.xml')).write_text(
+ '' + ''.join(cases) + '', encoding='utf-8')
+
+ def report(self, **kwargs):
+ return self.module.build_report(self.root, head=kwargs.get('head', HEAD),
+ branch='feature/2.0.x', java_version='openjdk 17 (test fixture)',
+ maven_version='Apache Maven (test fixture)', exit_code=kwargs.get('exit_code', 0),
+ required_suites=kwargs.get('required_suites', {'argv': [SUITE]}),
+ trace_methods=kwargs.get('trace_methods'))
+
+ def test_complete_argv_evidence_passes_but_live_is_not_run(self):
+ self.xml()
+ report = self.report()
+ self.assertEqual('PASS', report['status'])
+ self.assertEqual(2, report['layers']['argv']['executed'])
+ self.assertEqual('NOT_RUN', report['layers']['real-execution']['status'])
+ self.assertEqual(HEAD, report['head'])
+ json.dumps(report)
+
+ def test_process_layer_is_separate_from_real_execution(self):
+ self.xml()
+ report = self.module.build_report(self.root, head=HEAD, branch='feature/2.0.x',
+ java_version='fixture-jdk', maven_version='fixture-maven', exit_code=0,
+ required_suites={'process': [SUITE]})
+ self.assertEqual('PASS', report['status'])
+ self.assertEqual(2, report['layers']['process']['executed'])
+ self.assertEqual('NOT_RUN', report['layers']['real-execution']['status'])
+
+ def test_missing_report_fails(self):
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_missing_traced_method_fails_despite_successful_suite(self):
+ self.xml()
+ result = self.report(trace_methods={SUITE: {'case0', 'missing'}})
+ self.assertEqual('FAIL', result['status'])
+ self.assertEqual(2, result['layers']['argv']['executed'])
+ self.assertEqual({SUITE: ['missing']}, result['layers']['argv']['missingMethods'])
+
+ def test_parameters_are_removed_from_observed_method_name(self):
+ self.xml()
+ path = self.root / ('TEST-' + SUITE + '.xml')
+ text = path.read_text(encoding='utf-8').replace('name="case0"', 'name="case0(Path)[1]"')
+ path.write_text(text, encoding='utf-8')
+ result = self.report(trace_methods={SUITE: {'case0'}, SECOND_SUITE: {'unselected'}})
+ self.assertEqual('PASS', result['status'])
+ self.assertEqual({}, result['layers']['argv']['missingMethods'])
+
+ def test_case_from_another_class_cannot_satisfy_traced_method(self):
+ self.xml()
+ path = self.root / ('TEST-' + SUITE + '.xml')
+ text = path.read_text(encoding='utf-8').replace(
+ 'classname="' + SUITE + '"', 'classname="' + SECOND_SUITE + '"', 1)
+ path.write_text(text, encoding='utf-8')
+ result = self.report(trace_methods={SUITE: {'case0'}})
+ self.assertEqual({SUITE: ['case0']}, result['layers']['argv']['missingMethods'])
+
+ def test_trace_collects_pinned_test_method_links(self):
+ path = self.root / 'trace.md'
+ link = ('[`OpenCliArgvContractTest#case0`](https://github.com/easy-4-java/opencli-java-sdk/blob/'
+ + HEAD + '/src/test/java/' + SUITE.replace('.', '/') + '.java#L17)')
+ path.write_text(link + '\n' + link, encoding='utf-8')
+ self.assertEqual({SUITE: {'case0'}}, self.module.read_trace_methods(path))
+ path.write_text(link.replace('OpenCliArgvContractTest#', 'WrongTest#'), encoding='utf-8')
+ with self.assertRaisesRegex(ValueError, 'another class'):
+ self.module.read_trace_methods(path)
+
+ def test_trace_requires_pinned_method_links(self):
+ path = self.root / 'trace.md'
+ path.write_text('missing method links', encoding='utf-8')
+ with self.assertRaisesRegex(ValueError, 'no pinned'):
+ self.module.read_trace_methods(path)
+
+ def test_zero_tests_fails(self):
+ self.xml(tests=0)
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_zero_tests_in_one_required_suite_cannot_hide_behind_a_passing_suite(self):
+ self.xml()
+ self.xml(tests=0, suite=SECOND_SUITE)
+ result = self.report(required_suites={'argv': [SUITE, SECOND_SUITE]})
+ self.assertEqual('FAIL', result['status'])
+ self.assertEqual([SECOND_SUITE], result['layers']['argv']['unprovenSuites'])
+
+ def test_suite_cannot_supply_multiple_evidence_layers(self):
+ self.xml()
+ result = self.report(required_suites={'argv': [SUITE], 'real-execution': [SUITE]})
+ self.assertEqual('FAIL', result['status'])
+ self.assertIn('suite attribution must be unique across layers', result['problems'])
+
+ def test_all_skipped_fails(self):
+ self.xml(tests=2, skipped=2)
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_partly_skipped_fails(self):
+ self.xml(tests=2, skipped=1)
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_failure_fails(self):
+ self.xml(failures=1)
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_error_fails(self):
+ self.xml(errors=1)
+ self.assertEqual('FAIL', self.report()['status'])
+
+ def test_nonzero_command_exit_fails_despite_green_xml(self):
+ self.xml()
+ self.assertEqual('FAIL', self.report(exit_code=1)['status'])
+
+ def test_malformed_xml_fails_closed(self):
+ (self.root / 'TEST-broken.xml').write_text('', '', 1), encoding='utf-8')
+ self.assertEqual('FAIL', self.report()['status'])
+
+
+class InstalledContractsTest(unittest.TestCase):
+ def test_existing_reports_do_not_prove_an_invocation_that_executed_no_tests(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = pathlib.Path(directory)
+ bin_dir = root / 'bin'
+ bin_dir.mkdir()
+ scripts = root / 'scripts'
+ scripts.mkdir()
+ runner = SCRIPT.with_name('run_installed_contracts.sh')
+ for script in (SCRIPT, runner):
+ shutil.copy(script, scripts)
+ reports = root / 'target' / 'surefire-reports'
+ reports.mkdir(parents=True)
+ names = ['OpenCliCapabilityOverrideIT', 'OpenCliReadOnlyDiagnosticsIT']
+ for name in names:
+ (reports / ('TEST-' + name + '.xml')).write_text(
+ ''
+ '', encoding='utf-8')
+
+ commands = {
+ 'npm': 'exit 0',
+ 'node': 'case "$1" in --version) echo v24.18.0;; -p) echo /fixture/node;; *) echo 1.8.8;; esac',
+ 'java': 'echo fixture-jdk',
+ 'mvn': 'if [[ "$1" == -version ]]; then echo fixture-maven; fi',
+ 'git': 'echo ' + HEAD,
+ 'python': 'exec "$OPENCLI_TEST_PYTHON" "$@"',
+ }
+ for name, body in commands.items():
+ command = bin_dir / name
+ command.write_text('#!/usr/bin/env bash\n' + body + '\n', encoding='utf-8')
+ command.chmod(0o755)
+
+ env = dict(os.environ, PATH=str(bin_dir) + os.pathsep + os.environ['PATH'],
+ RUNNER_OS='Linux', RUNNER_TEMP=directory, GITHUB_REF_NAME='feature/2.0.x',
+ OPENCLI_TEST_PYTHON=sys.executable)
+ result = subprocess.run(['bash', 'scripts/run_installed_contracts.sh', 'mvn'],
+ cwd=root, env=env, capture_output=True, text=True, timeout=15)
+ report = json.loads((root / 'platform-evidence' / 'installed-report.json').read_text(encoding='utf-8'))
+ self.assertEqual(1, result.returncode, result.stdout + result.stderr)
+ self.assertEqual('FAIL', report['layers']['real-execution']['status'])
+ self.assertEqual(0, report['layers']['real-execution']['executed'])
+ archived = list((root / 'platform-evidence').glob('pre-install-surefire.*/surefire-reports/TEST-*.xml'))
+ self.assertCountEqual(['TEST-' + name + '.xml' for name in names], [p.name for p in archived])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/tests/test_generate_opencli_command_tests.py b/scripts/tests/test_generate_opencli_command_tests.py
new file mode 100644
index 00000000..7005fae7
--- /dev/null
+++ b/scripts/tests/test_generate_opencli_command_tests.py
@@ -0,0 +1,47 @@
+import hashlib
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+class ManifestCoverageProvenanceTest(unittest.TestCase):
+ def test_explicit_manifest_records_source_and_bytes_without_local_paths(self):
+ generator = Path(__file__).resolve().parents[1] / "generate_opencli_command_tests.py"
+ source = "https://registry.npmjs.org/@jackwener/opencli/-/opencli-1.8.8.tgz"
+ acquisition = "npm pack @jackwener/opencli@1.8.8"
+ payload = b'[{"site": "example", "name": "list"}]\n'
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ script = root / "scripts" / generator.name
+ script.parent.mkdir()
+ script.write_bytes(generator.read_bytes())
+ manifest = root / "source checkout" / "cli-manifest.json"
+ manifest.parent.mkdir()
+ manifest.write_bytes(payload)
+
+ result = subprocess.run(
+ [sys.executable, str(script), "--manifest-source", source,
+ "--observed-at", "2026-11-19", "--acquisition-command", acquisition],
+ env={**os.environ, "OPENCLI_MANIFEST": str(manifest)},
+ capture_output=True, text=True,
+ )
+
+ self.assertEqual(0, result.returncode, result.stderr)
+ metadata = (root / "src/test/resources/opencli/manifest-coverage-meta.json").read_text()
+ self.assertNotIn(temporary, metadata)
+ self.assertEqual(
+ {
+ "manifestPath": source,
+ "manifestSha256": hashlib.sha256(payload).hexdigest(),
+ "observedAt": "2026-11-19",
+ "acquisitionCommand": acquisition,
+ "scope": "Bundled adapter command enumeration from cli-manifest.json",
+ "manifestCommandCount": 1,
+ "siteCount": 1,
+ },
+ json.loads(metadata),
+ )
diff --git a/scripts/verify_opencli_upstream_snapshot.py b/scripts/verify_opencli_upstream_snapshot.py
new file mode 100644
index 00000000..e52e95e6
--- /dev/null
+++ b/scripts/verify_opencli_upstream_snapshot.py
@@ -0,0 +1,117 @@
+"""Replay the locked OpenCLI 1.8.8 manifest, help and browser output fixtures."""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+FIXTURES = ROOT / "src/test/resources/opencli-contracts/v1"
+HELP_CASES = {
+ "root.json": (),
+ "browser.stdout": ("browser",),
+ "browser-tab.json": ("browser", "fixture", "tab"),
+ "browser-get.json": ("browser", "fixture", "get"),
+ "browser-state.json": ("browser", "fixture", "state"),
+ "meta-auth.json": ("auth",),
+ "meta-list.txt": ("list",),
+ "meta-profile.json": ("profile",),
+ "site-zhihu-hot.json": ("zhihu", "hot"),
+ "site-npm.json": ("npm",),
+ "site-npm-search.json": ("npm", "search"),
+}
+PAGE_URL = "http://127.0.0.1:18765/basic.html"
+BROWSER_CASES = {
+ "tab-list.json": (("tab", "list"), {}),
+ "tab-list-empty.json": (("tab", "list"), {"OPENCLI_FIXTURE_EMPTY": "1"}),
+ "open.json": (("open", PAGE_URL), {}),
+ "state-dom.stdout": (("state", "--source", "dom"), {}),
+ "state-ax.stdout": (("state", "--source", "ax"), {}),
+ "state-compare.json": (("state", "--source", "ax", "--compare-sources"), {}),
+ "state-compare-ax-failure.json": (
+ ("state", "--compare-sources"), {"OPENCLI_FIXTURE_AX_FAILURE": "1"},
+ ),
+ "find.json": (("find", "--css", "#fixture", "--limit", "1"), {}),
+ "console.json": (("console",), {}),
+ "console-level.json": (("console", "--level", "warning"), {"OPENCLI_FIXTURE_CONSOLE_LEVEL": "1"}),
+ "network.json": (("network",), {}),
+ "analyze.json": (("analyze", PAGE_URL), {}),
+}
+
+
+def verify_manifest(package: Path, lock: dict) -> None:
+ metadata = json.loads((package / "package.json").read_bytes())
+ if metadata.get("name") != "@jackwener/opencli" or metadata.get("version") != lock["version"]:
+ raise SystemExit(f"expected @jackwener/opencli@{lock['version']}")
+ baseline = lock["manifest"]
+ content = (package / "cli-manifest.json").read_bytes()
+ if hashlib.sha256(content).hexdigest() != baseline["sha256"]:
+ raise SystemExit("installed cli-manifest.json SHA-256 differs from the lock")
+ actual = {f"{entry['site']} {entry['name']}" for entry in json.loads(content)}
+ historical = {
+ f"{entry['site']} {entry['subcommand']}"
+ for entry in json.loads((ROOT / baseline["historicalComparison"]).read_bytes())
+ }
+ if sorted(actual - historical) != baseline["addedAdapterCommands"]:
+ raise SystemExit("added adapter commands differ from the locked comparison")
+ if sorted(historical - actual) != baseline["removedAdapterCommands"]:
+ raise SystemExit("removed adapter commands differ from the locked comparison")
+ print(f"Manifest verified against the lock and historical snapshot ({len(actual)} commands)")
+
+
+def replay(entry: Path, preload: Path, fixture: Path, argv: tuple[str, ...], settings: dict) -> None:
+ with tempfile.TemporaryDirectory(prefix="opencli-fixture-") as isolated:
+ state = Path(isolated)
+ env = {
+ name: value for name, value in os.environ.items()
+ if not name.startswith("OPENCLI_") and name != "NODE_OPTIONS"
+ }
+ env.update({
+ "CI": "1",
+ "NO_COLOR": "1",
+ "OPENCLI_FIXTURE_HOME": isolated,
+ "OPENCLI_CONFIG_DIR": str(state / "config"),
+ "OPENCLI_CACHE_DIR": str(state / "cache"),
+ })
+ env.update(settings)
+ result = subprocess.run(
+ ["node", "--import", str(preload), str(entry), *argv],
+ cwd=state, env=env, capture_output=True, timeout=20,
+ )
+ if result.returncode or result.stderr or result.stdout != fixture.read_bytes():
+ raise SystemExit(f"{fixture.name}: replay differs (exit {result.returncode}, "
+ f"stderr {len(result.stderr)} bytes, stdout {len(result.stdout)} bytes)")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("package", type=Path, help="Installed @jackwener/opencli package directory")
+ package = parser.parse_args().package.resolve()
+ lock = json.loads((FIXTURES / "upstream-1.8.8.lock.json").read_bytes())
+ verify_manifest(package, lock)
+ entry = package / "dist/src/main.js"
+ help_dir = (FIXTURES / lock["structuredHelp"]["checksums"]).parent
+ browser_dir = (FIXTURES / lock["browserOutput"]["checksums"]).parent
+ with tempfile.TemporaryDirectory(prefix="opencli-help-preload-") as tmp:
+ preload = Path(tmp) / "isolate.mjs"
+ preload.write_text(
+ "import os from 'node:os';\n"
+ "import { syncBuiltinESMExports } from 'node:module';\n"
+ "os.homedir = () => process.env.OPENCLI_FIXTURE_HOME;\n"
+ "syncBuiltinESMExports();\n",
+ encoding="utf-8",
+ )
+ for name, argv in HELP_CASES.items():
+ replay(entry, preload, help_dir / name, (*argv, "--help", "-f", "json"), {})
+ for name, (argv, settings) in BROWSER_CASES.items():
+ replay(entry, browser_dir / "capture.mjs", browser_dir / name, ("browser", "fixture", *argv),
+ {"OPENCLI_FIXTURE_FIXED_CLOCK": "1", **settings})
+ print(f"Replay matched {len(HELP_CASES)} help and {len(BROWSER_CASES)} browser samples byte for byte")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/main/java/io/github/easy4j/opencli/OpenCliClient.java b/src/main/java/io/github/easy4j/opencli/OpenCliClient.java
index 4e238e30..7abed8e2 100644
--- a/src/main/java/io/github/easy4j/opencli/OpenCliClient.java
+++ b/src/main/java/io/github/easy4j/opencli/OpenCliClient.java
@@ -18,12 +18,19 @@
import io.github.easy4j.opencli.adapter.publicapi.pypi.PypiOpenCliClient;
import io.github.easy4j.opencli.adapter.publicapi.wikipedia.WikipediaOpenCliClient;
import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
+import io.github.easy4j.opencli.capability.OpenCliCapabilityDiscovery;
+import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot;
+import io.github.easy4j.opencli.capability.OpenCliDiagnostics;
+import io.github.easy4j.opencli.capability.OpenCliHelpScope;
import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
import io.github.easy4j.opencli.meta.OpenCliMetaClient;
import io.github.easy4j.opencli.core.OpenCliExecutor;
+import io.github.easy4j.opencli.core.OpenCliResult;
import io.github.easy4j.opencli.facade.BrowserClient;
import io.github.easy4j.opencli.facade.DesktopClient;
import io.github.easy4j.opencli.facade.PublicApiClient;
+import java.util.List;
+import java.util.Map;
import java.util.Objects;
import lombok.Getter;
@@ -47,6 +54,8 @@
@Getter
private final OpenCliExecutor executor;
+ private final OpenCliCapabilityDiscovery capabilityDiscovery;
+
/**
* Constructs with default configuration (executable assumed to be {@code opencli} on PATH).
*/
@@ -58,8 +67,7 @@ public OpenCliClient() {
* @param properties 运行配置,不得为 null
*/
public OpenCliClient(OpenCliProperties properties) {
- this.properties = Objects.requireNonNull(properties, "properties");
- this.executor = new OpenCliExecutor(properties);
+ this(properties, new OpenCliExecutor(properties));
}
/**
@@ -71,6 +79,7 @@ public OpenCliClient(OpenCliProperties properties) {
public OpenCliClient(OpenCliProperties properties, OpenCliExecutor executor) {
this.properties = Objects.requireNonNull(properties, "properties");
this.executor = Objects.requireNonNull(executor, "executor");
+ this.capabilityDiscovery = new OpenCliCapabilityDiscovery(executor);
}
/**
@@ -83,6 +92,60 @@ public OpenCliAdapterChannel adapter(String adapterId) {
return new OpenCliAdapterChannel(executor, adapterId);
}
+ /**
+ * Checks the configured local executable and version without starting runtime discovery.
+ * @return independent observations and the evidence used for each check
+ */
+ public OpenCliDiagnostics diagnose() {
+ return capabilityDiscovery.diagnose();
+ }
+
+ /**
+ * Probes version and root structured help on the configured absolute local executable.
+ * @return a current observation or a stale matching snapshot with the refresh failure
+ */
+ public OpenCliCapabilitySnapshot discoverCapabilities() {
+ return capabilityDiscovery.refresh();
+ }
+
+ /**
+ * Probes a fixed help query from the verified OpenCLI protocol fixture set.
+ * @param scope versioned local help query
+ * @return scoped observation or explicit failure status
+ */
+ public OpenCliCapabilitySnapshot discoverCapabilities(OpenCliHelpScope scope) {
+ return capabilityDiscovery.refresh(scope);
+ }
+
+ /**
+ * Refreshes structured help and invokes an explicitly selected, validated local command.
+ * @param scope verified help query containing the leaf
+ * @param command exact leaf display path from help
+ * @param session browser session identifier, or null when the command has no session
+ * @param positionals user-supplied positionals in schema order, or null
+ * @param options option spellings and values, with null for bare flags
+ * @return local execution result
+ */
+ public OpenCliResult invokeDiscovered(OpenCliHelpScope scope, String command, String session,
+ List positionals, Map options) {
+ return capabilityDiscovery.invoke(scope, command, session, positionals, options);
+ }
+
+ /**
+ * Dispatches a schema-validated command with explicit invocation context.
+ * @param scope verified help query containing the leaf
+ * @param command exact leaf display path
+ * @param session browser session identifier, or null
+ * @param positionals literal arguments in schema order, or null
+ * @param options explicit command flags, or null
+ * @param context immutable overrides of client context defaults
+ * @return local execution result
+ */
+ public OpenCliResult invokeDiscovered(OpenCliHelpScope scope, String command, String session,
+ List positionals, Map options, OpenCliInvocationContext context) {
+ return capabilityDiscovery.invoke(scope, command, session, positionals, options, context);
+ }
+
// ----- 参考强类型门面(Desktop) -----
/** @return Codex 桌面适配器客户端 */
@@ -120,7 +183,7 @@ public JimengOpenCliClient jimeng() {
/** @return DeepSeek 浏览器适配器客户端 */
/**
* 释放底层资源:本地模式为空操作;REMOTE_AGENT_HTTP 模式下关闭
- * 远程传输(实例级 shutdown,不影响 JVM 其它 Unirest 使用方)。
+ * 远程 HTTP 连接池(仅释放该实例持有的资源)。
* close 之后远程调用抛 IllegalStateException,本地调用不受影响。
*/
@Override
diff --git a/src/main/java/io/github/easy4j/opencli/OpenCliInvocationContext.java b/src/main/java/io/github/easy4j/opencli/OpenCliInvocationContext.java
new file mode 100644
index 00000000..e3263edf
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/OpenCliInvocationContext.java
@@ -0,0 +1,76 @@
+package io.github.easy4j.opencli;
+
+import io.github.easy4j.opencli.util.OpenCliStrings;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import lombok.Builder;
+import lombok.Getter;
+
+/** Immutable overrides for one schema-validated local invocation. */
+@Getter
+@Builder
+public final class OpenCliInvocationContext {
+ public enum WindowMode { FOREGROUND, BACKGROUND }
+ public enum SiteSession { EPHEMERAL, PERSISTENT }
+ public enum TraceMode { OFF, ON, RETAIN_ON_FAILURE }
+
+ private final String profile;
+ private final WindowMode window;
+ private final SiteSession siteSession;
+ private final Boolean keepTab;
+ private final TraceMode trace;
+
+ /**
+ * @param defaults client defaults
+ * @param invocation explicit invocation context
+ * @param options explicit command flags
+ * @return effective options, preserving the distinction between missing and false
+ */
+ public static Map mergeOptions(OpenCliInvocationContext defaults, OpenCliInvocationContext invocation,
+ Map options) {
+ Map result = new LinkedHashMap<>();
+ Map explicit = new LinkedHashMap<>();
+ if (Objects.nonNull(defaults)) {
+ result.putAll(defaults.flags());
+ }
+ if (Objects.nonNull(options)) {
+ explicit.putAll(options);
+ }
+ if (Objects.nonNull(invocation)) {
+ invocation.flags().forEach((flag, value) -> {
+ if (explicit.containsKey(flag) && !Objects.equals(explicit.get(flag), value)) {
+ throw new IllegalArgumentException("Conflicting explicit invocation option " + flag);
+ }
+ explicit.put(flag, value);
+ });
+ }
+ result.putAll(explicit);
+ return Collections.unmodifiableMap(result);
+ }
+
+ private Map flags() {
+ Map flags = new LinkedHashMap<>();
+ if (Objects.nonNull(profile)) {
+ if (OpenCliStrings.isBlank(profile) || profile.indexOf(0) >= 0) {
+ throw new IllegalArgumentException("profile must be a nonblank literal identifier");
+ }
+ flags.put("--profile", profile);
+ }
+ putEnum(flags, "--window", window);
+ putEnum(flags, "--site-session", siteSession);
+ if (Objects.nonNull(keepTab)) {
+ flags.put("--keep-tab", keepTab.toString());
+ }
+ putEnum(flags, "--trace", trace);
+ return flags;
+ }
+
+ private static void putEnum(Map flags, String name, Enum> value) {
+ if (Objects.nonNull(value)) {
+ flags.put(name, value.name().toLowerCase(Locale.ROOT).replace('_', '-'));
+ }
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/OpenCliProperties.java b/src/main/java/io/github/easy4j/opencli/OpenCliProperties.java
index fc368677..8fc0a60f 100644
--- a/src/main/java/io/github/easy4j/opencli/OpenCliProperties.java
+++ b/src/main/java/io/github/easy4j/opencli/OpenCliProperties.java
@@ -5,6 +5,7 @@
import java.util.List;
import java.util.Map;
import lombok.Data;
+import lombok.ToString;
/**
* OpenCLI runtime configuration POJO with no Spring dependency.
@@ -15,9 +16,10 @@
*
*
* {@link #commandTimeoutMillis} 在本地模式下用于子进程 Watchdog;在
- * {@link OpenCliExecutionTarget#REMOTE_AGENT_HTTP} 模式下用作 HTTP 客户端超时上限。
+ * {@link OpenCliExecutionTarget#REMOTE_AGENT_HTTP} 模式下为连接池等待、建连和读取响应共享的总预算。
*
*/
+@ToString(onlyExplicitlyIncluded = true)
@Data/**
* OpenCLI runtime configuration POJO with no Spring dependency.
@@ -43,6 +45,7 @@ public class OpenCliProperties {
/**
* 执行目标:本机进程或与 opencli-admin 兼容的远端 Agent。
*/
+ @ToString.Include
private OpenCliExecutionTarget executionTarget = OpenCliExecutionTarget.LOCAL_PROCESS;
/**
@@ -51,6 +54,9 @@ public class OpenCliProperties {
*/
private String remoteAgentBaseUrl;
+ /** Explicit credential header for the configured HTTPS Agent. */
+ private OpenCliRemoteAuthentication remoteAuthentication;
+
/**
* 传给 Agent collect 的 {@code mode}:{@code bridge} 或 {@code cdp}(与 Agent 环境一致)。
*/
@@ -71,12 +77,18 @@ public class OpenCliProperties {
* {@code remoteRawHttpBody} 字段;
* 本地模式无效果。大响应时请谨慎开启。
*/
+ @ToString.Include
private boolean remoteCaptureRawHttpResponse = false;
+ /** Maximum decoded HTTP response body bytes accepted from a remote Agent. */
+ @ToString.Include
+ private int maxRemoteResponseBytes = 10 * 1024 * 1024;
/**
* OpenCLI 可执行文件名或绝对路径;默认假定已在 {@code PATH} 中。
*/
private String executable = "opencli";
+ /** Defaults applied when dispatching a schema-validated local command. */
+ private OpenCliInvocationContext invocationDefaults;
/**
* 子进程工作目录;为空时使用 JVM 当前目录。
@@ -84,24 +96,28 @@ public class OpenCliProperties {
private String workingDirectory;
/**
- * 单次调用超时(毫秒):本地模式用于子进程 Watchdog;远程模式用于 Agent HTTP 请求。
+ * 单次调用超时(毫秒):本地模式用于子进程 Watchdog;远程模式下覆盖 Agent HTTP 传输全过程。
*/
+ @ToString.Include
private long commandTimeoutMillis = 300_000L;
/**
* 子进程单流(stdout/stderr 各自计)输出捕获上限(字节)。超过部分丢弃,
* 并在结果字符串尾部追加截断标记;{@code <= 0} 表示不限制。默认 10 MiB。
*/
+ @ToString.Include
private long maxOutputBytes = 10L * 1024 * 1024;
/**
* 本机 CLI 子进程最大并发数;小于等于 0 时使用 CPU 核心数与 2 的较大值。
*/
+ @ToString.Include
private int maxConcurrentExecutions = 0;
/**
* 启动探测({@code opencli list})专用超时(毫秒);小于等于 0 时探测使用 30 秒。
*/
+ @ToString.Include
private long startupProbeTimeoutMillis = 30_000L;
/**
@@ -123,13 +139,27 @@ public class OpenCliProperties {
public OpenCliProperties copyForLocalCliExecution() {
OpenCliProperties c = new OpenCliProperties();
c.setExecutable(this.executable);
+ c.setInvocationDefaults(this.invocationDefaults);
c.setWorkingDirectory(this.workingDirectory);
c.setCommandTimeoutMillis(this.commandTimeoutMillis);
c.setMaxConcurrentExecutions(this.maxConcurrentExecutions);
+ c.setMaxStdoutBytes(this.maxStdoutBytes);
+ c.setMaxStderrBytes(this.maxStderrBytes);
+ c.setCleanupGraceMillis(this.cleanupGraceMillis);
c.setStartupProbeTimeoutMillis(this.startupProbeTimeoutMillis);
c.setLeadingArguments(new ArrayList<>(this.leadingArguments));
c.setEnvironment(new LinkedHashMap<>(this.environment));
c.setExecutionTarget(OpenCliExecutionTarget.LOCAL_PROCESS);
return c;
}
+
+ /** Maximum stdout bytes captured per invocation. */
+ @ToString.Include
+ private int maxStdoutBytes = 8 * 1024 * 1024;
+ /** Maximum stderr bytes captured per invocation. */
+ @ToString.Include
+ private int maxStderrBytes = 2 * 1024 * 1024;
+ /** Maximum time to wait for owned resources after execution ends. */
+ @ToString.Include
+ private long cleanupGraceMillis = 5_000L;
}
diff --git a/src/main/java/io/github/easy4j/opencli/OpenCliRemoteAuthentication.java b/src/main/java/io/github/easy4j/opencli/OpenCliRemoteAuthentication.java
new file mode 100644
index 00000000..37d54f91
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/OpenCliRemoteAuthentication.java
@@ -0,0 +1,38 @@
+package io.github.easy4j.opencli;
+
+import java.util.Objects;
+import java.util.regex.Pattern;
+import lombok.AccessLevel;
+import lombok.Getter;
+
+/** A caller-supplied credential for an Agent's explicitly supported HTTP header. */
+@Getter
+public final class OpenCliRemoteAuthentication {
+
+ private static final Pattern HEADER_NAME =
+ Pattern.compile("(?:Authorization|Api-Key|X-[A-Za-z0-9][A-Za-z0-9-]*)", Pattern.CASE_INSENSITIVE);
+ private static final Pattern HEADER_VALUE = Pattern.compile("[!-~](?:[ -~]*[!-~])?");
+
+ private final String headerName;
+ @Getter(AccessLevel.NONE)
+ private final String headerValue;
+
+ /**
+ * @param headerName Authorization, Api-Key or a custom X- header
+ * @param headerValue complete printable ASCII credential value, including any scheme
+ */
+ public OpenCliRemoteAuthentication(String headerName, String headerValue) {
+ if (Objects.isNull(headerName) || !HEADER_NAME.matcher(headerName).matches()) {
+ throw new IllegalArgumentException("Unsupported remote authentication header name");
+ }
+ if (Objects.isNull(headerValue) || !HEADER_VALUE.matcher(headerValue).matches()) {
+ throw new IllegalArgumentException("Invalid remote authentication header value");
+ }
+ this.headerName = headerName;
+ this.headerValue = headerValue;
+ }
+ /** @return the raw credential for the explicitly configured HTTP request */
+ public String headerValue() {
+ return headerValue;
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/OpenCliBrowserSession.java b/src/main/java/io/github/easy4j/opencli/browser/OpenCliBrowserSession.java
index 74ed30e5..1cef1d57 100644
--- a/src/main/java/io/github/easy4j/opencli/browser/OpenCliBrowserSession.java
+++ b/src/main/java/io/github/easy4j/opencli/browser/OpenCliBrowserSession.java
@@ -1,5 +1,15 @@
package io.github.easy4j.opencli.browser;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserAnalysisResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserConsoleResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserDecoder;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserFindResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserNetworkResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserOpenResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserResult;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserSnapshot;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserSourceComparison;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserTab;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserConsoleOptions;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserDragLocator;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserExtractOptions;
@@ -7,6 +17,7 @@
import io.github.easy4j.opencli.browser.support.OpenCliBrowserGetHtmlOptions;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserScreenshotOptions;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserSemanticLocator;
+import io.github.easy4j.opencli.browser.support.OpenCliBrowserSnapshotSource;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserStateOptions;
import io.github.easy4j.opencli.browser.support.OpenCliBrowserTabOptions;
import io.github.easy4j.opencli.core.OpenCliArgSupport;
@@ -47,40 +58,20 @@ public final class OpenCliBrowserSession {
private List sessionPrefix() {
List tokens = new ArrayList<>();
tokens.add("browser");
+ tokens.add(sessionName);
if (Objects.nonNull(windowMode)) {
OpenCliArgSupport.addOptionPair(tokens, "--window", windowMode);
}
- tokens.add(sessionName);
return tokens;
}
private OpenCliResult invokeSub(List subcommandAndOptions) {
List tokens = sessionPrefix();
tokens.addAll(subcommandAndOptions);
- log.debug("OpenCLI browser session={} subcommandSummary={}", sessionName, summarizeSubcommand(tokens));
+ log.debug("OpenCLI browser invoke argvSize={}", tokens.size());
return executor.invoke(tokens);
}
- private static String summarizeSubcommand(List tokens) {
- int start = tokens.indexOf("browser");
- int from = start >= 0 && start + 2 < tokens.size() ? start + 2 : 0;
- int limit = Math.min(tokens.size(), from + 3);
- if (from >= tokens.size()) {
- return "(root)";
- }
- StringBuilder sb = new StringBuilder();
- for (int i = from; i < limit; i++) {
- if (i > from) {
- sb.append(' ');
- }
- sb.append(tokens.get(i));
- }
- if (tokens.size() > limit) {
- sb.append(" ...");
- }
- return sb.toString();
- }
-
private static void appendTabAndLocator(
List args, OpenCliBrowserTabOptions tab, OpenCliBrowserSemanticLocator locator) {
if (Objects.nonNull(tab)) {
@@ -106,6 +97,11 @@ public OpenCliResult tabList() {
return invokeSub(OpenCliLists.of("tab", "list"));
}
+ /** @return strict interpretation of the tab list; execution exceptions retain their partial results */
+ public OpenCliBrowserResult> tabListTyped() {
+ return OpenCliBrowserDecoder.tabList(tabList());
+ }
+
/**
* {@code browser tab new [url]}。
*
@@ -169,6 +165,15 @@ public OpenCliResult open(String url, OpenCliBrowserTabOptions tab) {
return invokeSub(args);
}
+ /**
+ * @param url requested navigation URL
+ * @param tab optional target tab
+ * @return strict interpretation of the navigation result
+ */
+ public OpenCliBrowserResult openTyped(String url, OpenCliBrowserTabOptions tab) {
+ return OpenCliBrowserDecoder.open(open(url, tab));
+ }
+
/** {@code browser back} */
public OpenCliResult back(OpenCliBrowserTabOptions tab) {
List args = new ArrayList<>();
@@ -223,6 +228,27 @@ public OpenCliResult state(OpenCliBrowserTabOptions tab, Boolean json) {
return state(tab, options);
}
+ /**
+ * @param tab optional target tab
+ * @param source explicit DOM or AX source
+ * @return strict URL and snapshot text from the selected source
+ */
+ public OpenCliBrowserResult snapshotTyped(OpenCliBrowserTabOptions tab,
+ OpenCliBrowserSnapshotSource source) {
+ OpenCliBrowserStateOptions options = OpenCliBrowserStateOptions.builder()
+ .source(Objects.requireNonNull(source, "source").getOptionValue()).build();
+ return OpenCliBrowserDecoder.snapshot(state(tab, options));
+ }
+
+ /**
+ * @param tab optional target tab
+ * @return strict comparison with each source's independent outcome
+ */
+ public OpenCliBrowserResult compareStateSourcesTyped(OpenCliBrowserTabOptions tab) {
+ return OpenCliBrowserDecoder.compareSources(
+ state(tab, OpenCliBrowserStateOptions.builder().compareSources(true).build()));
+ }
+
/** {@code browser frames} */
public OpenCliResult frames(OpenCliBrowserTabOptions tab) {
List args = new ArrayList<>();
@@ -279,6 +305,19 @@ public OpenCliResult console(OpenCliBrowserTabOptions tab, OpenCliBrowserConsole
return invokeSub(args);
}
+ /**
+ * @param tab optional target tab
+ * @param options one-shot console collection options
+ * @return strict console capture
+ */
+ public OpenCliBrowserResult consoleTyped(OpenCliBrowserTabOptions tab,
+ OpenCliBrowserConsoleOptions options) {
+ if (Objects.nonNull(options) && Boolean.TRUE.equals(options.getFollow())) {
+ throw new IllegalArgumentException("Use the raw console API for --follow");
+ }
+ return OpenCliBrowserDecoder.console(console(tab, options));
+ }
+
/**
* @deprecated 使用 {@link #console(OpenCliBrowserTabOptions, OpenCliBrowserConsoleOptions)};
* CLI 无 {@code --limit}
@@ -300,6 +339,15 @@ public OpenCliResult analyze(String url, OpenCliBrowserTabOptions tab) {
return invokeSub(args);
}
+ /**
+ * @param url requested analysis URL
+ * @param tab optional target tab
+ * @return strict analysis observation
+ */
+ public OpenCliBrowserResult analyzeTyped(String url, OpenCliBrowserTabOptions tab) {
+ return OpenCliBrowserDecoder.analyze(analyze(url, tab));
+ }
+
/**
* {@code browser find},对齐 {@code --css}、{@code --limit}、{@code --text-max}。
*/
@@ -316,6 +364,17 @@ public OpenCliResult find(
return invokeSub(args);
}
+ /**
+ * @param locator optional semantic locator
+ * @param tab optional target tab
+ * @param options selector and entry limits
+ * @return strict selector matches
+ */
+ public OpenCliBrowserResult findTyped(OpenCliBrowserSemanticLocator locator,
+ OpenCliBrowserTabOptions tab, OpenCliBrowserFindOptions options) {
+ return OpenCliBrowserDecoder.find(find(locator, tab, options));
+ }
+
/**
* @deprecated 使用 {@link #find(OpenCliBrowserSemanticLocator, OpenCliBrowserTabOptions, OpenCliBrowserFindOptions)};
* CLI 无 {@code --source}/{@code --nth}
@@ -729,6 +788,20 @@ public OpenCliResult network(OpenCliBrowserNetworkOptions options, OpenCliBrowse
return invokeSub(args);
}
+ /**
+ * @param options one-shot network listing options
+ * @param tab optional target tab
+ * @return strict network capture
+ */
+ public OpenCliBrowserResult networkTyped(OpenCliBrowserNetworkOptions options,
+ OpenCliBrowserTabOptions tab) {
+ if (Objects.nonNull(options) && (Boolean.TRUE.equals(options.getFollow())
+ || Objects.nonNull(options.getDetailKey()))) {
+ throw new IllegalArgumentException("Use the raw network API for --follow or --detail");
+ }
+ return OpenCliBrowserDecoder.network(network(options, tab));
+ }
+
/** {@code browser init } */
public OpenCliResult init(String siteCommandName) {
List args = new ArrayList<>();
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserAnalysisResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserAnalysisResult.java
new file mode 100644
index 00000000..1a650c9b
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserAnalysisResult.java
@@ -0,0 +1,22 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** Reported browser analysis metadata. Advice and paths are returned as data. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserAnalysisResult {
+ private final String requestedUrl;
+ private final String finalUrl;
+ private final String title;
+ private final String pattern;
+ private final JsonNode metadata;
+
+ /** @return a copy of the complete report, including optional sitemap metadata */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserConsoleResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserConsoleResult.java
new file mode 100644
index 00000000..daa3c271
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserConsoleResult.java
@@ -0,0 +1,37 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** One bounded browser console capture. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserConsoleResult {
+ private final String session;
+ private final String capturedAt;
+ private final List messages;
+ private final JsonNode metadata;
+
+ /** @return a copy of the capture envelope */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+
+ /** A console message with its original browser-supplied fields. */
+ @Getter
+ @AllArgsConstructor(access = AccessLevel.PACKAGE)
+ public static final class Message {
+ private final String type;
+ private final String text;
+ private final String timestamp;
+ private final JsonNode metadata;
+
+ /** @return a copy of the original console record */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserDecoder.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserDecoder.java
new file mode 100644
index 00000000..0310b4f7
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserDecoder.java
@@ -0,0 +1,309 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.core.JacksonException;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.ObjectReader;
+import tools.jackson.databind.json.JsonMapper;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserResult.Status;
+import io.github.easy4j.opencli.browser.result.OpenCliBrowserSourceComparison.Metrics;
+import io.github.easy4j.opencli.core.OpenCliExecutionDetails;
+import io.github.easy4j.opencli.core.OpenCliResult;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+
+/** Decodes known OpenCLI 1.8.8 browser leaf shapes without interpreting metadata as instructions. */
+public final class OpenCliBrowserDecoder {
+ private static final ObjectReader JSON = new JsonMapper().reader().with(
+ DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
+ DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY,
+ DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
+
+ private OpenCliBrowserDecoder() {
+ }
+
+ /** @param raw browser tab list execution result @return strict tab-list observation */
+ public static OpenCliBrowserResult> tabList(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readTabs);
+ }
+
+ /** @param raw browser open execution result @return strict navigation observation */
+ public static OpenCliBrowserResult open(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readNavigation);
+ }
+
+ /** @param raw browser state result @return strict text snapshot without interpreting its contents */
+ public static OpenCliBrowserResult snapshot(OpenCliResult raw) {
+ Status failure = unavailableStatus(raw);
+ if (Objects.nonNull(failure)) {
+ return new OpenCliBrowserResult<>(raw, failure, null);
+ }
+ String output = raw.getStdout();
+ String prefix = "URL: ";
+ int headerEnd = output.indexOf('\n');
+ if (!output.startsWith(prefix) || headerEnd < prefix.length()) {
+ return new OpenCliBrowserResult<>(raw, Status.INVALID_SHAPE, null);
+ }
+ int blankStart = headerEnd + 1;
+ int bodyStart;
+ if (output.startsWith("\r\n", blankStart)) {
+ bodyStart = blankStart + 2;
+ } else if (output.startsWith("\n", blankStart)) {
+ bodyStart = blankStart + 1;
+ } else {
+ return new OpenCliBrowserResult<>(raw, Status.INVALID_SHAPE, null);
+ }
+ String url = output.substring(prefix.length(), headerEnd);
+ if (url.endsWith("\r")) {
+ url = url.substring(0, url.length() - 1);
+ }
+ String body = output.substring(bodyStart);
+ if (url.chars().anyMatch(Character::isISOControl) || isBlankOutput(body)) {
+ return new OpenCliBrowserResult<>(raw, Status.INVALID_SHAPE, null);
+ }
+ return new OpenCliBrowserResult<>(raw, Status.PARSED, new OpenCliBrowserSnapshot(url, body));
+ }
+
+ /** @param raw browser state --compare-sources result @return strict DOM and AX comparison */
+ public static OpenCliBrowserResult compareSources(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readComparison);
+ }
+
+ /** @param raw browser find result @return strict selector matches */
+ public static OpenCliBrowserResult find(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readFind);
+ }
+
+ /** @param raw one-shot browser console result @return strict console capture */
+ public static OpenCliBrowserResult console(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readConsole);
+ }
+
+ /** @param raw one-shot browser network listing @return strict network capture */
+ public static OpenCliBrowserResult network(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readNetwork);
+ }
+
+ /** @param raw browser analyze result @return strict analysis observation */
+ public static OpenCliBrowserResult analyze(OpenCliResult raw) {
+ return decode(raw, OpenCliBrowserDecoder::readAnalysis);
+ }
+
+ private static Status unavailableStatus(OpenCliResult raw) {
+ Objects.requireNonNull(raw, "raw");
+ OpenCliExecutionDetails execution = raw.getExecutionDetails();
+ if (Objects.nonNull(execution) && execution.isStdoutTruncated()) {
+ return Status.TRUNCATED;
+ }
+ if (!raw.isSuccess()) {
+ return Status.EXECUTION_FAILED;
+ }
+ return isBlankOutput(raw.getStdout()) ? Status.EMPTY : null;
+ }
+
+ private static boolean isBlankOutput(String output) {
+ return Objects.isNull(output) || output.chars().allMatch(value -> " \t\r\n".indexOf(value) >= 0);
+ }
+
+ private static OpenCliBrowserResult decode(OpenCliResult raw, Function model) {
+ Status failure = unavailableStatus(raw);
+ if (Objects.nonNull(failure)) {
+ return new OpenCliBrowserResult<>(raw, failure, null);
+ }
+ JsonNode json;
+ try {
+ json = JSON.readTree(raw.getStdout());
+ } catch (JacksonException ex) {
+ return new OpenCliBrowserResult<>(raw, Status.INVALID_JSON, null);
+ }
+ try {
+ return new OpenCliBrowserResult<>(raw, Status.PARSED, model.apply(json));
+ } catch (IllegalArgumentException ex) {
+ return new OpenCliBrowserResult<>(raw, Status.INVALID_SHAPE, null);
+ }
+ }
+
+ private static List readTabs(JsonNode json) {
+ if (!json.isArray()) {
+ throw invalidShape();
+ }
+ List tabs = new ArrayList<>(json.size());
+ for (JsonNode item : json) {
+ JsonNode index = item.path("index");
+ JsonNode active = item.path("active");
+ if (!item.isObject() || !index.isIntegralNumber() || !index.canConvertToInt()
+ || index.intValue() < 0 || !active.isBoolean()) {
+ throw invalidShape();
+ }
+ tabs.add(new OpenCliBrowserTab(index.intValue(), pageId(item.path("page")), active.booleanValue(),
+ optionalText(item.path("url")), optionalText(item.path("title")), item));
+ }
+ return Collections.unmodifiableList(tabs);
+ }
+
+ private static OpenCliBrowserOpenResult readNavigation(JsonNode json) {
+ if (!json.isObject() || !json.path("url").isTextual()) {
+ throw invalidShape();
+ }
+ JsonNode page = json.path("page");
+ return new OpenCliBrowserOpenResult(json.path("url").textValue(),
+ page.isMissingNode() ? null : pageId(page), json);
+ }
+
+ private static OpenCliBrowserSourceComparison readComparison(JsonNode json) {
+ JsonNode url = json.path("url");
+ JsonNode sources = json.path("sources");
+ if (!url.isTextual() || !sources.isObject()) {
+ throw invalidShape();
+ }
+ return new OpenCliBrowserSourceComparison(url.textValue(), readMetrics(sources.path("dom")),
+ readMetrics(sources.path("ax")), json);
+ }
+
+ private static Metrics readMetrics(JsonNode json) {
+ JsonNode ok = json.path("ok");
+ if (!ok.isBoolean()) {
+ throw invalidShape();
+ }
+ long elapsed = counter(json.path("elapsed_ms"));
+ if (!ok.booleanValue()) {
+ JsonNode error = json.path("error");
+ JsonNode message = error.path("message");
+ if (!message.isTextual()) {
+ throw invalidShape();
+ }
+ return new Metrics(false, elapsed, null, null, null, null, null, null, null,
+ optionalText(error.path("code")), message.textValue());
+ }
+ JsonNode interactive = json.path("interactive");
+ return new Metrics(true, elapsed, counter(json.path("chars")), counter(json.path("bytes")),
+ counter(json.path("lines")), counter(json.path("approx_tokens")), counter(json.path("refs")),
+ counter(json.path("frame_sections")), interactive.isMissingNode() ? null : counter(interactive), null, null);
+ }
+
+ private static OpenCliBrowserFindResult readFind(JsonNode json) {
+ long total = counter(json.path("matches_n"));
+ JsonNode reported = json.path("entries");
+ if (total < reported.size()) {
+ throw invalidShape();
+ }
+ List entries = entries(reported, item -> {
+ JsonNode ref = item.path("ref");
+ JsonNode visible = item.path("visible");
+ BigInteger numericRef = ref.isNull() ? null : unsignedInteger(ref);
+ if (!visible.isBoolean() || !item.path("attrs").isObject()) {
+ throw invalidShape();
+ }
+ return new OpenCliBrowserFindResult.Entry(counter(item.path("nth")), numericRef, text(item.path("tag")),
+ text(item.path("role")), text(item.path("text")), visible.booleanValue(), item);
+ });
+ return new OpenCliBrowserFindResult(total, entries, json);
+ }
+
+ private static OpenCliBrowserConsoleResult readConsole(JsonNode json) {
+ JsonNode reported = json.path("messages");
+ validateCount(json, reported);
+ List messages = entries(reported, item -> {
+ String type = optionalText(item.path("type"));
+ String level = Objects.nonNull(type) ? type : optionalText(item.path("level"));
+ return new OpenCliBrowserConsoleResult.Message(level, optionalText(item.path("text")),
+ text(item.path("timestamp")), item);
+ });
+ return new OpenCliBrowserConsoleResult(text(json.path("session")), text(json.path("captured_at")), messages, json);
+ }
+
+ private static OpenCliBrowserNetworkResult readNetwork(JsonNode json) {
+ JsonNode reported = json.path("entries");
+ validateCount(json, reported);
+ List entries = entries(reported, item -> {
+ JsonNode status = item.path("status");
+ if (!status.isIntegralNumber() || !status.canConvertToInt() || status.intValue() < 0) {
+ throw invalidShape();
+ }
+ return new OpenCliBrowserNetworkResult.Entry(text(item.path("key")), text(item.path("method")),
+ status.intValue(), text(item.path("url")), text(item.path("ct")), counter(item.path("size")),
+ optionalText(item.path("timestamp")), item);
+ });
+ return new OpenCliBrowserNetworkResult(text(json.path("session")), text(json.path("captured_at")),
+ counter(json.path("filtered_out")), entries, json);
+ }
+
+ private static OpenCliBrowserAnalysisResult readAnalysis(JsonNode json) {
+ JsonNode pattern = json.path("pattern");
+ if (!json.path("anti_bot").isObject() || !json.path("initial_state").isObject()
+ || !json.path("api_candidates").isArray() || !json.path("recommended_next_step").isTextual()) {
+ throw invalidShape();
+ }
+ return new OpenCliBrowserAnalysisResult(text(json.path("requested_url")), text(json.path("final_url")),
+ text(json.path("title")), text(pattern.path("pattern")), json);
+ }
+
+ private static List entries(JsonNode array, Function entry) {
+ if (!array.isArray()) {
+ throw invalidShape();
+ }
+ List result = new ArrayList<>(array.size());
+ for (JsonNode item : array) {
+ if (!item.isObject()) {
+ throw invalidShape();
+ }
+ result.add(entry.apply(item));
+ }
+ return Collections.unmodifiableList(result);
+ }
+
+ private static void validateCount(JsonNode json, JsonNode entries) {
+ if (counter(json.path("count")) != entries.size()) {
+ throw invalidShape();
+ }
+ }
+
+ private static BigInteger unsignedInteger(JsonNode node) {
+ if (!node.isIntegralNumber() || node.bigIntegerValue().signum() < 0) {
+ throw invalidShape();
+ }
+ return node.bigIntegerValue();
+ }
+
+ private static String text(JsonNode node) {
+ if (!node.isTextual()) {
+ throw invalidShape();
+ }
+ return node.textValue();
+ }
+
+ private static long counter(JsonNode node) {
+ if (!node.isIntegralNumber() || !node.canConvertToLong() || node.longValue() < 0) {
+ throw invalidShape();
+ }
+ return node.longValue();
+ }
+
+ private static String pageId(JsonNode node) {
+ if (node.isTextual() && !node.textValue().isEmpty()) {
+ return node.textValue();
+ }
+ if (node.isIntegralNumber()) {
+ return node.bigIntegerValue().toString();
+ }
+ throw invalidShape();
+ }
+
+ private static String optionalText(JsonNode node) {
+ if (node.isMissingNode() || node.isNull()) {
+ return null;
+ }
+ if (!node.isTextual()) {
+ throw invalidShape();
+ }
+ return node.textValue();
+ }
+
+ private static IllegalArgumentException invalidShape() {
+ return new IllegalArgumentException("Unrecognized browser result shape");
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserFindResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserFindResult.java
new file mode 100644
index 00000000..f8b71ba4
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserFindResult.java
@@ -0,0 +1,40 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import java.math.BigInteger;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** Browser selector matches, including the total before the entry limit. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserFindResult {
+ private final long matchesN;
+ private final List entries;
+ private final JsonNode metadata;
+
+ /** @return a copy of the original result with all reported fields */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+
+ /** A matched element. The optional numeric reference retains its exact value. */
+ @Getter
+ @AllArgsConstructor(access = AccessLevel.PACKAGE)
+ public static final class Entry {
+ private final long nth;
+ private final BigInteger ref;
+ private final String tag;
+ private final String role;
+ private final String text;
+ private final boolean visible;
+ private final JsonNode metadata;
+
+ /** @return a copy including attributes, compound data and extensions */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserNetworkResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserNetworkResult.java
new file mode 100644
index 00000000..ed882789
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserNetworkResult.java
@@ -0,0 +1,42 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** One network capture, with any upstream filtering, cache and truncation metadata. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserNetworkResult {
+ private final String session;
+ private final String capturedAt;
+ private final long filteredOut;
+ private final List entries;
+ private final JsonNode metadata;
+
+ /** @return a copy of the capture envelope */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+
+ /** An observed request. Metadata includes the preview or body supplied by OpenCLI. */
+ @Getter
+ @AllArgsConstructor(access = AccessLevel.PACKAGE)
+ public static final class Entry {
+ private final String key;
+ private final String method;
+ private final int status;
+ private final String url;
+ private final String contentType;
+ private final long size;
+ private final String timestamp;
+ private final JsonNode metadata;
+
+ /** @return a copy including any body, shape, truncation and request metadata */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserOpenResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserOpenResult.java
new file mode 100644
index 00000000..fcab0de9
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserOpenResult.java
@@ -0,0 +1,21 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** Navigation metadata from the pinned OpenCLI browser open contract. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserOpenResult {
+ private final String url;
+ /** Present when OpenCLI reports the active page identifier. */
+ private final String pageId;
+ private final JsonNode metadata;
+
+ /** @return all reported fields, including optional sitemap or trace data */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserResult.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserResult.java
new file mode 100644
index 00000000..bd10141c
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserResult.java
@@ -0,0 +1,18 @@
+package io.github.easy4j.opencli.browser.result;
+
+import io.github.easy4j.opencli.core.OpenCliResult;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** A strict browser result paired with the original process evidence. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserResult {
+ public enum Status { PARSED, TRUNCATED, EXECUTION_FAILED, EMPTY, INVALID_JSON, INVALID_SHAPE }
+
+ private final OpenCliResult raw;
+ private final Status status;
+ /** Typed data, present only when status is PARSED. */
+ private final T value;
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSnapshot.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSnapshot.java
new file mode 100644
index 00000000..b95a38a3
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSnapshot.java
@@ -0,0 +1,13 @@
+package io.github.easy4j.opencli.browser.result;
+
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** The URL header and exact snapshot body from browser state. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserSnapshot {
+ private final String url;
+ private final String text;
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSourceComparison.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSourceComparison.java
new file mode 100644
index 00000000..6096b130
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserSourceComparison.java
@@ -0,0 +1,38 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** DOM and AX observations from the same browser state comparison. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserSourceComparison {
+ private final String url;
+ private final Metrics dom;
+ private final Metrics ax;
+ private final JsonNode metadata;
+
+ /** @return an independent copy of the entire comparison object */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+
+ /** A single source observation. Counts are absent when the source failed. */
+ @Getter
+ @AllArgsConstructor(access = AccessLevel.PACKAGE)
+ public static final class Metrics {
+ private final boolean ok;
+ private final long elapsedMillis;
+ private final Long chars;
+ private final Long bytes;
+ private final Long lines;
+ private final Long approximateTokens;
+ private final Long refs;
+ private final Long frameSections;
+ private final Long interactive;
+ private final String errorCode;
+ private final String errorMessage;
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserTab.java b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserTab.java
new file mode 100644
index 00000000..e056fdae
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/result/OpenCliBrowserTab.java
@@ -0,0 +1,23 @@
+package io.github.easy4j.opencli.browser.result;
+
+import tools.jackson.databind.JsonNode;
+import lombok.AccessLevel;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/** Tab metadata from the pinned OpenCLI browser tab list contract. */
+@Getter
+@AllArgsConstructor(access = AccessLevel.PACKAGE)
+public final class OpenCliBrowserTab {
+ private final int index;
+ private final String pageId;
+ private final boolean active;
+ private final String url;
+ private final String title;
+ private final JsonNode metadata;
+
+ /** @return an independent JSON view containing all fields and the original identifier type */
+ public JsonNode getMetadata() {
+ return metadata.deepCopy();
+ }
+}
diff --git a/src/main/java/io/github/easy4j/opencli/browser/support/OpenCliBrowserSnapshotSource.java b/src/main/java/io/github/easy4j/opencli/browser/support/OpenCliBrowserSnapshotSource.java
new file mode 100644
index 00000000..7f36c096
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/browser/support/OpenCliBrowserSnapshotSource.java
@@ -0,0 +1,14 @@
+package io.github.easy4j.opencli.browser.support;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+
+/** Sources accepted by the typed browser snapshot entry point. */
+@Getter
+@RequiredArgsConstructor
+public enum OpenCliBrowserSnapshotSource {
+ DOM("dom"),
+ AX("ax");
+
+ private final String optionValue;
+}
diff --git a/src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommand.java b/src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommand.java
new file mode 100644
index 00000000..4ea5a2be
--- /dev/null
+++ b/src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilityCommand.java
@@ -0,0 +1,239 @@
+package io.github.easy4j.opencli.capability;
+
+import io.github.easy4j.opencli.core.OpenCliArgSupport;
+import io.github.easy4j.opencli.parser.OpenCliHelpSchema;
+import io.github.easy4j.opencli.parser.OpenCliHelpSchema.Argument;
+import io.github.easy4j.opencli.util.OpenCliStrings;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Pattern;
+import lombok.RequiredArgsConstructor;
+
+/** Converts one explicitly selected help leaf into validated literal CLI arguments. */
+public final class OpenCliCapabilityCommand {
+ private static final Pattern COMMAND_TOKEN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_-]*");
+ private static final Pattern OPTION_TOKEN = Pattern.compile("--[A-Za-z0-9][A-Za-z0-9-]*|-[A-Za-z0-9]");
+
+ private OpenCliCapabilityCommand() {
+ }
+
+ /**
+ * @param snapshot currently available structured help
+ * @param command exact leaf display path from help, including any placeholders
+ * @param session explicit browser session, or null for a non-browser leaf
+ * @param positionals literal values in declared order, or null
+ * @param options declared option spellings and values, with null values for bare flags
+ * @return immutable literal arguments excluding the executable
+ */
+ public static List bind(OpenCliCapabilitySnapshot snapshot, String command, String session,
+ List positionals, Map options) {
+ return bind(snapshot, command, session, positionals, options, Collections.emptyList());
+ }
+
+ static List bind(OpenCliCapabilitySnapshot snapshot, String command, String session,
+ List positionals, Map options, List supplementaryGlobals) {
+ Objects.requireNonNull(snapshot, "snapshot");
+ Objects.requireNonNull(command, "command");
+ if (snapshot.getStatus() != OpenCliCapabilitySnapshot.Status.AVAILABLE
+ || Objects.isNull(snapshot.getHelp()) || Objects.isNull(snapshot.getHelp().getSchema())) {
+ throw new IllegalStateException("Current structured help is unavailable");
+ }
+ OpenCliHelpSchema scope = snapshot.getHelp().getSchema();
+ OpenCliHelpSchema leaf = locateLeaf(scope, command);
+ String[] path = command.split(" ", -1);
+ if (path.length < 3 || !"opencli".equals(path[0])) {
+ throw new IllegalArgumentException("The help command path cannot be bound");
+ }
+
+ List rootOptions = new ArrayList<>();
+ List namespaceOptions = new ArrayList<>();
+ List leafOptions = new ArrayList<>();
+ appendOptions(scope, leaf, options, supplementaryGlobals, rootOptions, namespaceOptions, leafOptions);
+
+ List argv = new ArrayList<>(rootOptions);
+ argv.add(path[1]);
+ boolean browserSessionPath = "browser".equals(path[1]) && "".equals(path[2]);
+ if (!browserSessionPath) {
+ argv.addAll(namespaceOptions);
+ }
+ boolean sessionUsed = false;
+ for (int index = 2; index < path.length; index++) {
+ String token = path[index];
+ if ("".equals(token) && index == 2 && "browser".equals(path[1])) {
+ if (OpenCliStrings.isBlank(session) || !COMMAND_TOKEN.matcher(session).matches()) {
+ throw new IllegalArgumentException("A literal browser session identifier is required");
+ }
+ argv.add(session);
+ argv.addAll(namespaceOptions);
+ sessionUsed = true;
+ } else {
+ if (!COMMAND_TOKEN.matcher(token).matches()) {
+ throw new IllegalArgumentException("The help command path contains an unsupported token");
+ }
+ argv.add(token);
+ }
+ }
+ if (!sessionUsed && Objects.nonNull(session)) {
+ throw new IllegalArgumentException("This command has no browser session binding");
+ }
+ argv.addAll(leafOptions);
+ List values = OpenCliArgSupport.merge(null, positionals);
+ validatePositionals(leaf.getPositionals(), values);
+ if (!values.isEmpty()) {
+ argv.add("--");
+ argv.addAll(values);
+ }
+ return Collections.unmodifiableList(argv);
+ }
+
+ private static OpenCliHelpSchema locateLeaf(OpenCliHelpSchema scope, String command) {
+ if (command.equals(scope.getCommand()) && scope.getCommands().isEmpty()) {
+ return scope;
+ }
+ return scope.getCommands().stream()
+ .filter(child -> command.equals(child.getCommand()) && child.getCommands().isEmpty())
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException("The requested command is not a leaf in this help scope"));
+ }
+
+ private static void validatePositionals(List definitions, List values) {
+ int consumed = 0;
+ for (Argument definition : definitions) {
+ int count = Boolean.TRUE.equals(definition.getVariadic()) ? values.size() - consumed
+ : Math.min(1, values.size() - consumed);
+ if (count == 0 && Boolean.TRUE.equals(definition.getRequired())) {
+ throw invalid(definition, "is required");
+ }
+ for (int index = 0; index < count; index++) {
+ validateValue(definition, values.get(consumed++));
+ }
+ }
+ if (consumed != values.size()) {
+ throw new IllegalArgumentException("Too many positional arguments");
+ }
+ }
+
+ private static void appendOptions(OpenCliHelpSchema scope, OpenCliHelpSchema leaf, Map options,
+ List supplementaryGlobals, List root, List namespace, List local) {
+ Map definitions = new LinkedHashMap<>();
+ index(definitions, inherited(leaf.getGlobalOptions(), scope.getGlobalOptions()), root);
+ index(definitions, supplementaryGlobals, root);
+ index(definitions, inherited(leaf.getNamespaceOptions(), scope.getNamespaceOptions()), namespace);
+ index(definitions, inherited(leaf.getCommonOptions(), scope.getCommonOptions()), local);
+ if (Boolean.TRUE.equals(leaf.getBrowser())) {
+ index(definitions, inherited(leaf.getBrowserCommonOptions(), scope.getBrowserCommonOptions()), local);
+ }
+ index(definitions, leaf.getCommandOptions(), local);
+ Set