Skip to content

Commit 25e1c58

Browse files
committed
Preserve bounded OpenCLI stderr envelopes and observed exit evidence
1 parent 3a930a8 commit 25e1c58

8 files changed

Lines changed: 415 additions & 1 deletion

File tree

‎openspec/changes/preserve-opencli-error-envelope/tasks.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,11 @@
2424
## 证据交付模板(实施时填写)
2525

2626
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
27+
28+
## OC-ERR-001–006 本地解码与退出来源
29+
30+
`OpenCliResult.errorEnvelope` 在本地失败上提供解码状态、错误码、错误消息、help、trace、扩展字段与独立的 observed/reported 退出码。原始 stderr 保留在结果中。超时、非零退出、输出限额和不完整流继续由执行器决定主异常,由此避免解码覆盖执行证据。成功结果和原有远端 collect 保持各自路径。
31+
32+
JSON 复用各版本线 Jackson,严格检查重复键、尾随内容及嵌套深度。YAML 使用 SnakeYAML 2.7 的事件预检和安全构造器,保留 JSON 标量语义,拒绝锚点、别名、显式标签、重复键及多文档。解码预算为 256 KiB UTF-8、32 层。解析失败仅以状态呈现,原始诊断片段留在 stderr。AutoFix 和 trace 路径作为数据保存。
33+
34+
`OpenCliErrorEnvelopeTest` 首先因缺少 API 无法编译。实现后使用已归档 YAML、合成 JSON 和真实 JVM 子进程验证解码、退出值不一致、输入拒绝、超时优先、诊断脱敏与单次执行。现有远端失败分类继续由 C04 测试覆盖。

‎pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@
131131
<groupId>tools.jackson.core</groupId>
132132
<artifactId>jackson-databind</artifactId>
133133
</dependency>
134+
<dependency>
135+
<groupId>org.yaml</groupId>
136+
<artifactId>snakeyaml</artifactId>
137+
<version>2.7</version>
138+
</dependency>
134139

135140
<dependency>
136141
<groupId>org.apache.commons</groupId>

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io.github.easy4j.opencli.OpenCliExecutionTarget;
44
import io.github.easy4j.opencli.OpenCliProperties;
55
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
6+
import io.github.easy4j.opencli.parser.OpenCliErrorDecoder;
67
import io.github.easy4j.opencli.core.support.SubprocessExecutionSupport;
78
import io.github.easy4j.opencli.exception.OpenCliException;
89
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
@@ -206,7 +207,10 @@ private OpenCliResult complete(SubprocessExecutionSupport.RunSession session) {
206207
&& details.isStreamsDrained();
207208
OpenCliResult result = OpenCliResult.builder().stdout(stdout).stderr(stderr).exitCode(exit)
208209
.success(success).parsed(OpenCliOutputParser.parseBestEffort(stdout, stderr))
209-
.executionDetails(details).build();
210+
.executionDetails(details)
211+
.errorEnvelope(success ? null : OpenCliErrorDecoder.decode(stderr, exit,
212+
reason != TerminationReason.PROCESS_EXIT || !details.isStreamsDrained() || details.isStderrTruncated()))
213+
.build();
210214
if (success) { return result; }
211215
if (reason == TerminationReason.QUEUE_TIMEOUT || reason == TerminationReason.EXECUTION_TIMEOUT) {
212216
throw new OpenCliTimeoutException("OpenCLI deadline exceeded: " + reason, result);

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.github.easy4j.opencli.core;
22

3+
import io.github.easy4j.opencli.parser.OpenCliErrorEnvelope;
34
import io.github.easy4j.opencli.parser.OpenCliParsedFields;
45
import lombok.Builder;
56
import lombok.Getter;
@@ -49,6 +50,8 @@ public class OpenCliResult {
4950

5051
/** Bounded local execution evidence, when available. */
5152
private final OpenCliExecutionDetails executionDetails;
53+
/** Structured stderr interpretation for local failures. */
54+
private final OpenCliErrorEnvelope errorEnvelope;
5255
/** Evidence from a legacy HTTP collect response, if available. */
5356
private final OpenCliRemoteExecutionDetails remoteExecutionDetails;
5457
}
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import tools.jackson.core.json.JsonFactory;
4+
import tools.jackson.core.StreamReadConstraints;
5+
import tools.jackson.core.StreamReadFeature;
6+
import tools.jackson.databind.DeserializationFeature;
7+
import tools.jackson.databind.ObjectReader;
8+
import tools.jackson.databind.json.JsonMapper;
9+
import io.github.easy4j.opencli.parser.OpenCliErrorEnvelope.Format;
10+
import io.github.easy4j.opencli.parser.OpenCliErrorEnvelope.Status;
11+
import io.github.easy4j.opencli.util.OpenCliStrings;
12+
import java.nio.charset.StandardCharsets;
13+
import java.util.ArrayList;
14+
import java.util.Collections;
15+
import java.util.LinkedHashMap;
16+
import java.util.List;
17+
import java.util.Map;
18+
import java.util.Objects;
19+
20+
/** Decodes local CLI failure metadata without changing process status or interpreting advice. */
21+
public final class OpenCliErrorDecoder {
22+
private static final int MAX_BYTES = 256 * 1024;
23+
private static final int MAX_DEPTH = 32;
24+
private static final ObjectReader JSON = new JsonMapper(JsonFactory.builder()
25+
.enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
26+
.streamReadConstraints(StreamReadConstraints.builder().maxNestingDepth(MAX_DEPTH).build()).build())
27+
.readerFor(Object.class)
28+
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
29+
30+
private OpenCliErrorDecoder() {
31+
}
32+
33+
/**
34+
* @param stderr captured error text
35+
* @param observedExit observed local process exit code, or null
36+
* @param incomplete true if transport or lifecycle prevented a complete local observation
37+
* @return decoded metadata or a status describing why it is unavailable
38+
*/
39+
public static OpenCliErrorEnvelope decode(String stderr, Integer observedExit, boolean incomplete) {
40+
OpenCliErrorEnvelope.OpenCliErrorEnvelopeBuilder result =
41+
OpenCliErrorEnvelope.builder().observedProcessExit(observedExit);
42+
if (incomplete) {
43+
return result.status(Status.INCOMPLETE).build();
44+
}
45+
if (Objects.isNull(stderr) || stderr.isEmpty()) {
46+
return result.status(Status.EMPTY).build();
47+
}
48+
if (stderr.length() > MAX_BYTES || stderr.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) {
49+
return result.status(Status.OVER_BUDGET).build();
50+
}
51+
int first = 0;
52+
while (first < stderr.length() && " \t\r\n".indexOf(stderr.charAt(first)) >= 0) {
53+
first++;
54+
}
55+
if (first == stderr.length()) {
56+
return result.status(Status.EMPTY).build();
57+
}
58+
boolean json = stderr.charAt(first) == '{' || stderr.charAt(first) == '[';
59+
result.format(json ? Format.JSON : Format.YAML);
60+
try {
61+
Object decoded = json ? JSON.readValue(stderr) : OpenCliErrorYaml.read(stderr, MAX_DEPTH, MAX_BYTES);
62+
if (!(decoded instanceof Map)) {
63+
return result.status(Status.NO_ENVELOPE).build();
64+
}
65+
Map<String, Object> root = immutableMap((Map<?, ?>) decoded);
66+
if (!Boolean.FALSE.equals(root.get("ok")) || !(root.get("error") instanceof Map)) {
67+
return result.status(Status.NO_ENVELOPE).build();
68+
}
69+
Map<String, Object> error = asMap(root.get("error"));
70+
Object code = error.get("code");
71+
Object message = error.get("message");
72+
Object help = error.get("help");
73+
Object exit = error.get("exitCode");
74+
Object trace = root.get("trace");
75+
if (!(code instanceof String) || OpenCliStrings.isBlank((String) code)
76+
|| !(message instanceof String) || !(exit instanceof Integer)
77+
|| (Objects.nonNull(help) && !(help instanceof String))
78+
|| (Objects.nonNull(trace) && !(trace instanceof Map))) {
79+
return result.status(Status.INVALID).build();
80+
}
81+
return result.status(Status.DECODED).code((String) code).message((String) message)
82+
.help((String) help).reportedExit((Integer) exit).envelopeFields(root).errorFields(error)
83+
.trace(Objects.isNull(trace) ? Collections.emptyMap() : asMap(trace)).build();
84+
} catch (RuntimeException ex) {
85+
return result.status(Status.INVALID).build();
86+
}
87+
}
88+
89+
@SuppressWarnings("unchecked")
90+
private static Map<String, Object> asMap(Object value) {
91+
return (Map<String, Object>) value;
92+
}
93+
94+
private static Map<String, Object> immutableMap(Map<?, ?> source) {
95+
Map<String, Object> result = new LinkedHashMap<>();
96+
source.forEach((key, value) -> {
97+
if (!(key instanceof String)) {
98+
throw new IllegalArgumentException("Envelope keys must be strings");
99+
}
100+
result.put((String) key, immutableValue(value));
101+
});
102+
return Collections.unmodifiableMap(result);
103+
}
104+
105+
private static Object immutableValue(Object value) {
106+
if (value instanceof Map) {
107+
return immutableMap((Map<?, ?>) value);
108+
}
109+
if (value instanceof List) {
110+
List<Object> result = new ArrayList<>();
111+
((List<?>) value).forEach(item -> result.add(immutableValue(item)));
112+
return Collections.unmodifiableList(result);
113+
}
114+
return value;
115+
}
116+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import java.util.Collections;
4+
import java.util.Map;
5+
import java.util.Objects;
6+
import lombok.AccessLevel;
7+
import lombok.Builder;
8+
import lombok.Getter;
9+
10+
/** Immutable interpretation of a local failure's bounded stderr. Raw stderr remains on the execution result. */
11+
@Getter
12+
@Builder(access = AccessLevel.PACKAGE)
13+
public final class OpenCliErrorEnvelope {
14+
public enum Status { DECODED, EMPTY, NO_ENVELOPE, INCOMPLETE, OVER_BUDGET, INVALID }
15+
public enum Format { JSON, YAML }
16+
17+
private final Status status;
18+
private final Format format;
19+
private final Integer observedProcessExit;
20+
private final Integer reportedExit;
21+
private final String code;
22+
private final String message;
23+
private final String help;
24+
25+
/** Original error object, including cause, stack and unknown fields. */
26+
@Builder.Default
27+
private final Map<String, Object> errorFields = Collections.emptyMap();
28+
29+
/** Original envelope, including trace and unknown fields. */
30+
@Builder.Default
31+
private final Map<String, Object> envelopeFields = Collections.emptyMap();
32+
33+
/** Trace metadata. Paths are returned as data. */
34+
@Builder.Default
35+
private final Map<String, Object> trace = Collections.emptyMap();
36+
37+
/** @return whether both exit values are available and disagree */
38+
public boolean isExitMismatch() {
39+
return Objects.nonNull(observedProcessExit) && Objects.nonNull(reportedExit)
40+
&& !observedProcessExit.equals(reportedExit);
41+
}
42+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import java.io.StringReader;
4+
import java.math.BigDecimal;
5+
import java.util.Objects;
6+
import java.util.regex.Pattern;
7+
import org.yaml.snakeyaml.DumperOptions;
8+
import org.yaml.snakeyaml.LoaderOptions;
9+
import org.yaml.snakeyaml.Yaml;
10+
import org.yaml.snakeyaml.constructor.AbstractConstruct;
11+
import org.yaml.snakeyaml.constructor.SafeConstructor;
12+
import org.yaml.snakeyaml.events.CollectionStartEvent;
13+
import org.yaml.snakeyaml.events.DocumentStartEvent;
14+
import org.yaml.snakeyaml.events.Event;
15+
import org.yaml.snakeyaml.events.NodeEvent;
16+
import org.yaml.snakeyaml.events.ScalarEvent;
17+
import org.yaml.snakeyaml.nodes.Node;
18+
import org.yaml.snakeyaml.nodes.ScalarNode;
19+
import org.yaml.snakeyaml.nodes.Tag;
20+
import org.yaml.snakeyaml.representer.Representer;
21+
import org.yaml.snakeyaml.resolver.Resolver;
22+
23+
/** Reads the upstream YAML subset with bounded structure and JSON-style scalar types. */
24+
final class OpenCliErrorYaml {
25+
private static final Resolver WIRE_SCALARS = new WireResolver();
26+
27+
private OpenCliErrorYaml() {
28+
}
29+
30+
static Object read(String input, int maxDepth, int maxLength) {
31+
LoaderOptions settings = new LoaderOptions();
32+
settings.setAllowDuplicateKeys(false);
33+
settings.setAllowRecursiveKeys(false);
34+
settings.setMaxAliasesForCollections(0);
35+
settings.setCodePointLimit(maxLength);
36+
settings.setNestingDepthLimit(maxDepth);
37+
DumperOptions output = new DumperOptions();
38+
Yaml yaml = new Yaml(new WireConstructor(settings), new Representer(output), output, settings, WIRE_SCALARS);
39+
int documents = 0;
40+
int depth = 0;
41+
for (Event event : yaml.parse(new StringReader(input))) {
42+
if (event instanceof DocumentStartEvent && ++documents != 1) {
43+
throw new IllegalArgumentException("Unexpected YAML document count");
44+
}
45+
if (event instanceof NodeEvent && Objects.nonNull(((NodeEvent) event).getAnchor())) {
46+
throw new IllegalArgumentException("YAML anchors and aliases are unsupported");
47+
}
48+
if ((event instanceof ScalarEvent && Objects.nonNull(((ScalarEvent) event).getTag()))
49+
|| (event instanceof CollectionStartEvent && Objects.nonNull(((CollectionStartEvent) event).getTag()))) {
50+
throw new IllegalArgumentException("Explicit YAML tags are unsupported");
51+
}
52+
if (event instanceof CollectionStartEvent && ++depth > maxDepth) {
53+
throw new IllegalArgumentException("YAML nesting depth exceeded");
54+
}
55+
if (event.is(Event.ID.MappingEnd) || event.is(Event.ID.SequenceEnd)) {
56+
depth--;
57+
}
58+
}
59+
return yaml.load(input);
60+
}
61+
62+
private static final class WireResolver extends Resolver {
63+
@Override
64+
protected void addImplicitResolvers() {
65+
addImplicitResolver(Tag.BOOL, Pattern.compile("true|false"), "tf");
66+
addImplicitResolver(Tag.NULL, Pattern.compile("null"), "n");
67+
addImplicitResolver(Tag.INT, Pattern.compile("-?(?:0|[1-9][0-9]*)"), "-0123456789");
68+
addImplicitResolver(Tag.FLOAT,
69+
Pattern.compile("-?(?:0|[1-9][0-9]*)(?:[.][0-9]+)?(?:[eE][+-]?[0-9]+)?"), "-0123456789");
70+
}
71+
}
72+
73+
private static final class WireConstructor extends SafeConstructor {
74+
WireConstructor(LoaderOptions settings) {
75+
super(settings);
76+
yamlConstructors.put(Tag.FLOAT, new AbstractConstruct() {
77+
@Override
78+
public Object construct(Node node) {
79+
return new BigDecimal(((ScalarNode) node).getValue());
80+
}
81+
});
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)