Skip to content

Commit e83bc00

Browse files
committed
Discover pinned OpenCLI help scopes without executing commands
1 parent c8a5b17 commit e83bc00

6 files changed

Lines changed: 176 additions & 22 deletions

File tree

‎openspec/changes/add-opencli-capability-discovery/tasks.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,9 @@
4343
客户端保存一个最近成功的根帮助快照,每次显式发现均重新探测。刷新失败且配置指纹一致、未观测到不同版本时,返回 `STALE`,保留成功时的采集时间、schema 和帮助摘要。失败的刷新另存于 `failedRefresh`,包括失败原因、尝试时间和可取得的原始帮助。配置或已观测版本改变会清除旧快照;成功刷新以新内容更新摘要。同一客户端并发探测时,较早发起但较晚完成的探测不会覆盖已发布的新结果。
4444

4545
`OpenCliCapabilityDiscoveryTest` 的定向红灯为预期 `STALE`、实际 `UNKNOWN`。实现后验证同配置降级、失败原文、同版本帮助变化、配置与版本失效、并发完成顺序。当前缓存范围为根帮助。
46+
47+
## OC-CAP-001/003/004/005/006 固定范围帮助探测
48+
49+
`discoverCapabilities(OpenCliHelpScope)` 提供根目录、浏览器、浏览器 tab/get/state、auth、list 及 npm 站点和 search 的九个固定查询。细粒度参数只在已验证的 OpenCLI 1.8.8 启用。浏览器查询使用固定的帮助会话占位,不接受调用者提供的命令路径,也不执行帮助描述中的内容。结构化结果需匹配请求范围;纯文本和混合输出维持原有失败原因。
50+
51+
每个范围只保存其最近成功的观察,且配置或已观测版本变化使其他不匹配的范围一并失效。OpenCLI 能力仍按请求观察,并保留来源未知标记。增加 `OpenCliCapabilityDiscoveryTest` 的进程验收后,缺少范围 API 时失败,加入实现后定向测试通过。类型化会话绑定及执行前参数校验仍待验收。

‎src/main/java/io/github/easy4j/opencli/OpenCliClient.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
2121
import io.github.easy4j.opencli.capability.OpenCliCapabilityDiscovery;
2222
import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot;
23+
import io.github.easy4j.opencli.capability.OpenCliHelpScope;
2324
import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
2425
import io.github.easy4j.opencli.meta.OpenCliMetaClient;
2526
import io.github.easy4j.opencli.core.OpenCliExecutor;
@@ -95,6 +96,15 @@ public OpenCliCapabilitySnapshot discoverCapabilities() {
9596
return capabilityDiscovery.refresh();
9697
}
9798

99+
/**
100+
* Probes a fixed help query from the verified OpenCLI protocol fixture set.
101+
* @param scope versioned local help query
102+
* @return scoped observation or explicit failure status
103+
*/
104+
public OpenCliCapabilitySnapshot discoverCapabilities(OpenCliHelpScope scope) {
105+
return capabilityDiscovery.refresh(scope);
106+
}
107+
98108
// ----- 参考强类型门面(Desktop) -----
99109

100110
/** @return Codex 桌面适配器客户端 */

‎src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscovery.java‎

Lines changed: 32 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
import java.security.MessageDigest;
2222
import java.security.NoSuchAlgorithmException;
2323
import java.time.Instant;
24-
import java.util.Arrays;
2524
import java.util.Collections;
25+
import java.util.EnumMap;
2626
import java.util.Map;
2727
import java.util.Objects;
2828
import java.util.TreeMap;
@@ -39,7 +39,8 @@ public final class OpenCliCapabilityDiscovery {
3939
private final OpenCliExecutor executor;
4040
private long nextAttempt;
4141
private long lastPublishedAttempt;
42-
private OpenCliCapabilitySnapshot lastAvailable;
42+
private final Map<OpenCliHelpScope, OpenCliCapabilitySnapshot> lastAvailable =
43+
new EnumMap<>(OpenCliHelpScope.class);
4344

4445
/** @param executor client executor whose local process capacity is shared */
4546
public OpenCliCapabilityDiscovery(OpenCliExecutor executor) {
@@ -62,38 +63,50 @@ public static OpenCliCapabilitySnapshot discover(OpenCliExecutor executor) {
6263
* @return current observation, or a clearly marked stale snapshot or failure
6364
*/
6465
public OpenCliCapabilitySnapshot refresh() {
66+
return refresh(OpenCliHelpScope.ROOT_HELP);
67+
}
68+
69+
/**
70+
* Queries a fixed help scope on the pinned protocol version and tracks its snapshot.
71+
* @param scope help query from the locked protocol fixture set
72+
* @return current scoped observation or the explicit stale or failure status
73+
*/
74+
public OpenCliCapabilitySnapshot refresh(OpenCliHelpScope scope) {
75+
Objects.requireNonNull(scope, "scope");
6576
long attempt;
6677
synchronized (this) {
6778
attempt = ++nextAttempt;
6879
}
69-
return publish(attempt, observe());
80+
return publish(attempt, observe(scope));
7081
}
7182

7283
private synchronized OpenCliCapabilitySnapshot publish(long attempt, OpenCliCapabilitySnapshot current) {
7384
if (attempt < lastPublishedAttempt) {
7485
return current;
7586
}
7687
lastPublishedAttempt = attempt;
88+
lastAvailable.values().removeIf(old ->
89+
!old.getConfigurationSha256().equals(current.getConfigurationSha256())
90+
|| (Objects.nonNull(current.getObservedVersion())
91+
&& !old.getObservedVersion().equals(current.getObservedVersion())));
92+
OpenCliHelpScope scope = current.getHelpScope();
7793
if (current.getStatus() == Status.AVAILABLE) {
78-
lastAvailable = current;
94+
lastAvailable.put(scope, current);
7995
return current;
8096
}
81-
if (current.getStatus() == Status.UNKNOWN
82-
&& Objects.nonNull(lastAvailable)
83-
&& lastAvailable.getConfigurationSha256().equals(current.getConfigurationSha256())
84-
&& (Objects.isNull(current.getObservedVersion())
85-
|| lastAvailable.getObservedVersion().equals(current.getObservedVersion()))) {
86-
return lastAvailable.toBuilder().status(Status.STALE).reason(current.getReason())
97+
OpenCliCapabilitySnapshot previous = lastAvailable.get(scope);
98+
if (current.getStatus() == Status.UNKNOWN && Objects.nonNull(previous)) {
99+
return previous.toBuilder().status(Status.STALE).reason(current.getReason())
87100
.failedRefresh(current).build();
88101
}
89-
lastAvailable = null;
102+
lastAvailable.remove(scope);
90103
return current;
91104
}
92105

93-
private OpenCliCapabilitySnapshot observe() {
106+
private OpenCliCapabilitySnapshot observe(OpenCliHelpScope scope) {
94107
OpenCliProperties configured = executor.getProperties();
95108
OpenCliCapabilitySnapshot.OpenCliCapabilitySnapshotBuilder snapshot =
96-
OpenCliCapabilitySnapshot.builder().observedAt(Instant.now());
109+
OpenCliCapabilitySnapshot.builder().helpScope(scope).observedAt(Instant.now());
97110
if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) {
98111
return snapshot.status(Status.UNSUPPORTED).reason("LOCAL_DISCOVERY_ONLY").build();
99112
}
@@ -132,16 +145,20 @@ private OpenCliCapabilitySnapshot observe() {
132145
return snapshot.status(Status.UNKNOWN).reason("INVALID_VERSION_OUTPUT").build();
133146
}
134147
snapshot.observedVersion(version);
148+
if (scope != OpenCliHelpScope.ROOT_HELP && !"1.8.8".equals(version)) {
149+
return snapshot.status(Status.UNSUPPORTED).reason("UNVERIFIED_HELP_VERSION").build();
150+
}
135151
phase = "HELP";
136-
OpenCliResult helpResult = local.invokeLocalOnly(Arrays.asList("--help", "-f", "json"));
152+
OpenCliResult helpResult = local.invokeLocalOnly(scope.arguments());
137153
if (helpResult.getExecutionDetails().isStdoutTruncated()) {
138154
return snapshot.status(Status.UNKNOWN).reason("HELP_TRUNCATED").build();
139155
}
140156
String stdout = helpResult.getStdout();
141157
OpenCliHelpResult help = OpenCliHelpParser.parse(stdout);
142158
snapshot.help(help).helpSha256(hex(sha256().digest(stdout.getBytes(StandardCharsets.UTF_8))));
143159
if (help.getStatus() == OpenCliHelpResult.Status.AVAILABLE) {
144-
return snapshot.status(Status.AVAILABLE).build();
160+
return scope.matches(help.getSchema()) ? snapshot.status(Status.AVAILABLE).build()
161+
: snapshot.status(Status.UNKNOWN).reason("UNEXPECTED_HELP_SCOPE").build();
145162
}
146163
return snapshot.status(Status.UNKNOWN).reason(help.getReason().name()).build();
147164
} catch (OpenCliTimeoutException ex) {

‎src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilitySnapshot.java‎

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

8-
/** Immutable observation of the configured local CLI's root help. */
8+
/** Immutable observation of the configured local CLI's help for one query. */
99
@Getter
1010
@Builder(toBuilder = true)
1111
public final class OpenCliCapabilitySnapshot {
1212
public enum Status { AVAILABLE, STALE, UNKNOWN, UNSUPPORTED }
1313

14+
@Builder.Default
15+
private final OpenCliHelpScope helpScope = OpenCliHelpScope.ROOT_HELP;
1416
private final Status status;
1517
private final String reason;
1618
private final String executable;
@@ -24,7 +26,7 @@ public enum Status { AVAILABLE, STALE, UNKNOWN, UNSUPPORTED }
2426

2527
/** @return scope of the metadata probe */
2628
public String getScope() {
27-
return "ROOT_HELP";
29+
return helpScope.name();
2830
}
2931

3032
/** @return unresolved origin, since help does not attribute overrides or plugins */
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package io.github.easy4j.opencli.capability;
2+
3+
import io.github.easy4j.opencli.parser.OpenCliHelpSchema;
4+
import java.util.ArrayList;
5+
import java.util.Arrays;
6+
import java.util.Collections;
7+
import java.util.List;
8+
import java.util.Objects;
9+
10+
/** Local help queries verified against OpenCLI 1.8.8. Browser queries use a fixed help-only session token. */
11+
public enum OpenCliHelpScope {
12+
ROOT_HELP(null, "opencli", null, null),
13+
BROWSER("opencli browser", null, null, "browser", "browser"),
14+
BROWSER_TAB("opencli browser <session> tab", null, null, "browser", "browser", "fixture", "tab"),
15+
BROWSER_GET("opencli browser <session> get", null, null, "browser", "browser", "fixture", "get"),
16+
BROWSER_STATE("opencli browser <session> state", "state", null, "browser", "browser", "fixture", "state"),
17+
META_AUTH("opencli auth", null, null, "auth", "auth"),
18+
META_LIST("opencli list", "list", null, null, "list"),
19+
SITE_NPM(null, null, "npm", null, "npm"),
20+
SITE_NPM_SEARCH("opencli npm search", "search", "npm", null, "npm", "search");
21+
22+
private final String command;
23+
private final String name;
24+
private final String site;
25+
private final String namespace;
26+
private final List<String> arguments;
27+
28+
OpenCliHelpScope(String command, String name, String site, String namespace, String... path) {
29+
this.command = command;
30+
this.name = name;
31+
this.site = site;
32+
this.namespace = namespace;
33+
List<String> argv = new ArrayList<>(Arrays.asList(path));
34+
argv.addAll(Arrays.asList("--help", "-f", "json"));
35+
this.arguments = Collections.unmodifiableList(argv);
36+
}
37+
38+
List<String> arguments() {
39+
return arguments;
40+
}
41+
42+
boolean matches(OpenCliHelpSchema schema) {
43+
return Objects.equals(command, schema.getCommand())
44+
&& Objects.equals(name, schema.getName())
45+
&& Objects.equals(site, schema.getSite())
46+
&& Objects.equals(namespace, schema.getNamespace());
47+
}
48+
}

‎src/test/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscoveryTest.java‎

Lines changed: 76 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ void lateRefreshCannotOverwriteNewerSnapshot(@TempDir Path directory) throws Exc
173173
props.setMaxConcurrentExecutions(2);
174174
ExecutorService callers = Executors.newSingleThreadExecutor();
175175
try (OpenCliClient client = new OpenCliClient(props)) {
176-
Future<OpenCliCapabilitySnapshot> older = callers.submit(client::discoverCapabilities);
176+
Future<OpenCliCapabilitySnapshot> older = callers.submit(() -> client.discoverCapabilities());
177177
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
178178
while (!Files.exists(entered) && System.nanoTime() < deadline) {
179179
Thread.sleep(10);
@@ -196,6 +196,50 @@ void lateRefreshCannotOverwriteNewerSnapshot(@TempDir Path directory) throws Exc
196196
}
197197
}
198198

199+
@Test
200+
void fixedQueriesReturnTheirCapturedScopeAndKeepUnsupportedFormats() {
201+
OpenCliHelpScope[] scopes = {OpenCliHelpScope.BROWSER_TAB, OpenCliHelpScope.BROWSER_GET,
202+
OpenCliHelpScope.BROWSER_STATE, OpenCliHelpScope.META_AUTH, OpenCliHelpScope.SITE_NPM,
203+
OpenCliHelpScope.SITE_NPM_SEARCH};
204+
try (OpenCliClient client = new OpenCliClient(properties("structured"))) {
205+
for (OpenCliHelpScope scope : scopes) {
206+
OpenCliCapabilitySnapshot snapshot = client.discoverCapabilities(scope);
207+
assertEquals(OpenCliCapabilitySnapshot.Status.AVAILABLE, snapshot.getStatus(), scope.name());
208+
assertEquals(scope.name(), snapshot.getScope());
209+
assertEquals("UNKNOWN", snapshot.getCommandOrigin());
210+
}
211+
assertEquals("opencli browser <session> state",
212+
client.discoverCapabilities(OpenCliHelpScope.BROWSER_STATE).getHelp().getSchema().getCommand());
213+
assertEquals("UNSUPPORTED_FORMAT", client.discoverCapabilities(OpenCliHelpScope.META_LIST).getReason());
214+
assertEquals("INVALID_JSON", client.discoverCapabilities(OpenCliHelpScope.BROWSER).getReason());
215+
}
216+
}
217+
218+
@Test
219+
void freshnessIsScopedAndVersionChangesClearOldQueries(@TempDir Path directory) throws Exception {
220+
Path control = directory.resolve("mode");
221+
writeMode(control, "structured");
222+
try (OpenCliClient client = new OpenCliClient(controlledProperties(control))) {
223+
OpenCliCapabilitySnapshot root = client.discoverCapabilities();
224+
OpenCliCapabilitySnapshot state = client.discoverCapabilities(OpenCliHelpScope.BROWSER_STATE);
225+
assertEquals(OpenCliCapabilitySnapshot.Status.AVAILABLE, state.getStatus());
226+
227+
writeMode(control, "wrong-help");
228+
OpenCliCapabilitySnapshot stale = client.discoverCapabilities(OpenCliHelpScope.BROWSER_STATE);
229+
assertEquals(OpenCliCapabilitySnapshot.Status.STALE, stale.getStatus());
230+
assertEquals("UNEXPECTED_HELP_SCOPE", stale.getReason());
231+
assertEquals(state.getHelpSha256(), stale.getHelpSha256());
232+
assertNotEquals(root.getHelpSha256(), stale.getHelpSha256());
233+
234+
writeMode(control, "new-version-error");
235+
OpenCliCapabilitySnapshot upgraded = client.discoverCapabilities(OpenCliHelpScope.BROWSER_STATE);
236+
assertEquals(OpenCliCapabilitySnapshot.Status.UNSUPPORTED, upgraded.getStatus());
237+
assertEquals("UNVERIFIED_HELP_VERSION", upgraded.getReason());
238+
writeMode(control, "error");
239+
assertEquals(OpenCliCapabilitySnapshot.Status.UNKNOWN, client.discoverCapabilities().getStatus());
240+
}
241+
}
242+
199243
private static OpenCliProperties controlledProperties(Path control) {
200244
OpenCliProperties props = properties("unused");
201245
props.getEnvironment().put("OPENCLI_TEST_HELP_CONTROL", control.toString());
@@ -232,6 +276,27 @@ public static void main(String[] args) throws Exception {
232276
System.out.print("raw available");
233277
return;
234278
}
279+
if (args.length > 3 && Arrays.asList("--help", "-f", "json")
280+
.equals(Arrays.asList(args).subList(args.length - 3, args.length))) {
281+
if ("new-version-error".equals(mode) || "error".equals(mode)) {
282+
System.exit(3);
283+
}
284+
String path = String.join(" ", Arrays.asList(args).subList(0, args.length - 3));
285+
String fixture;
286+
switch (path) {
287+
case "browser": fixture = "browser.stdout"; break;
288+
case "browser fixture tab": fixture = "browser-tab.json"; break;
289+
case "browser fixture get": fixture = "browser-get.json"; break;
290+
case "browser fixture state": fixture = "browser-state.json"; break;
291+
case "auth": fixture = "meta-auth.json"; break;
292+
case "list": fixture = "meta-list.txt"; break;
293+
case "npm": fixture = "site-npm.json"; break;
294+
case "npm search": fixture = "site-npm-search.json"; break;
295+
default: throw new IllegalArgumentException("Unapproved fixture command");
296+
}
297+
System.out.print(readFixture("wrong-help".equals(mode) ? "root.json" : fixture));
298+
return;
299+
}
235300
if (!Arrays.equals(args, new String[]{"--help", "-f", "json"})) {
236301
System.exit(2);
237302
}
@@ -256,12 +321,18 @@ public static void main(String[] args) throws Exception {
256321
System.out.print("{\"name\":\"opencli\",\"commands\":[],\"site_adapters\":{}}");
257322
return;
258323
}
324+
String root = readFixture("root.json").trim();
325+
System.out.print(root.substring(0, root.length() - 1)
326+
+ ",\"description_fixture\":\"do not run this example " + mode + "\"}");
327+
}
328+
329+
private static String readFixture(String fixture) {
259330
try (InputStream input = DiscoveryFixture.class.getResourceAsStream(
260-
"/opencli-contracts/v1/structured-help-1.8.8/root.json");
331+
"/opencli-contracts/v1/structured-help-1.8.8/" + fixture);
261332
Scanner scan = new Scanner(input, "UTF-8").useDelimiter("\\A")) {
262-
String root = scan.next().trim();
263-
System.out.print(root.substring(0, root.length() - 1)
264-
+ ",\"description_fixture\":\"do not run this example " + mode + "\"}");
333+
return scan.next();
334+
} catch (java.io.IOException ex) {
335+
throw new java.io.UncheckedIOException(ex);
265336
}
266337
}
267338
}

0 commit comments

Comments
 (0)