Skip to content

Commit 2532c29

Browse files
authored
perf(model): converge late execution success projection (#765)
1 parent 7301186 commit 2532c29

14 files changed

Lines changed: 1167 additions & 35 deletions

File tree

‎crates/webcodex-tool-contracts/src/registry/output_schemas/jobs.rs‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1196,7 +1196,7 @@ pub(super) fn output_schema_for_tool(name: &str) -> Option<Value> {
11961196
let mut properties = vec![
11971197
(
11981198
"duration_ms",
1199-
schema_type("integer", "Command duration in milliseconds."),
1199+
nullable_schema("integer", "Command duration in milliseconds when reported by the Runner; null is retained on rich exceptional/recovered terminal results when timing is unavailable."),
12001200
),
12011201
(
12021202
"exit_code",
@@ -1289,12 +1289,63 @@ pub(super) fn output_schema_for_tool(name: &str) -> Option<Value> {
12891289
"Named Runner-local SSH resource used for this command, when any.",
12901290
),
12911291
),
1292+
("recovery_state", schema_type("string", "Canonical recovery state retained on a recovered terminal snapshot; this result remains rich.")),
1293+
("recovered_after_server_restart", schema_type("boolean", "True when the terminal snapshot was recovered after Server restart.")),
1294+
("reconciled_at", schema_type("integer", "Reconciliation timestamp retained on an exceptional terminal result.")),
1295+
("recovery_reason_code", schema_type("string", "Canonical recovery reason retained on a recovered terminal snapshot.")),
12921296
("execution_state", process_execution_state_schema()),
12931297
];
12941298
properties.extend(structured_continuation_properties());
12951299
let mut schema = wrapped_output_schema(properties);
12961300
schema["properties"]["output"]["allOf"] =
12971301
structured_execution_lifecycle_constraints("run_shell");
1302+
schema["description"] = json!("Ordinary proven synchronous terminal success is sparse: success=true implies completed exit 0 and no active Job. Runtime-selected command_summary, cwd, shell and any ssh_resource remain explicit. Nonempty output, truncation/loss, expectations and sidecars remain. Failure, uncertainty and exceptional/recovery results retain rich lifecycle evidence; normal pending handoff remains execution_state plus continuation.");
1303+
for key in ["duration_ms", "exit_code", "command_started", "command_completed",
1304+
"command_ok", "failure_kind", "tool_failure", "executor", "execution_source",
1305+
"execution_state", "promoted_to_job", "terminal", "job_id", "job_status",
1306+
"observation_token", "effective_timeout_secs", "sync_wait_secs", "async_handoff_available"] {
1307+
if let Some(description) = schema["properties"]["output"]["properties"][key]["description"].as_str() {
1308+
schema["properties"]["output"]["properties"][key]["description"] =
1309+
json!(format!("{description} Omitted on proven ordinary synchronous terminal success."));
1310+
}
1311+
}
1312+
for key in ["stdout_tail", "stderr_tail", "stdout_lines", "stderr_lines", "stdout_truncated", "stderr_truncated"] {
1313+
let description = schema["properties"]["output"]["properties"][key]["description"].as_str().unwrap();
1314+
schema["properties"]["output"]["properties"][key]["description"] =
1315+
json!(format!("{description} Empty/zero/false values are omitted on ordinary synchronous terminal success."));
1316+
}
1317+
schema["allOf"]
1318+
.as_array_mut()
1319+
.expect("wrapped output schema allOf")
1320+
.push(json!({
1321+
"if": {
1322+
"properties": {
1323+
"success": {"const":true},
1324+
"output": {"not":{"required":["execution_state"]}}
1325+
},
1326+
"required":["success", "output"]
1327+
},
1328+
"then": {"properties":{"output":{
1329+
"required":["command_summary", "cwd", "shell"],
1330+
"not":{"anyOf":[
1331+
{"required":["duration_ms"]}, {"required":["exit_code"]},
1332+
{"required":["command_started"]}, {"required":["command_completed"]},
1333+
{"required":["command_ok"]}, {"required":["failure_kind"]},
1334+
{"required":["tool_failure"]}, {"required":["promoted_to_job"]},
1335+
{"required":["terminal"]}, {"required":["job_id"]},
1336+
{"required":["job_status"]}, {"required":["observation_token"]},
1337+
{"required":["effective_timeout_secs"]}, {"required":["sync_wait_secs"]},
1338+
{"required":["async_handoff_available"]}, {"required":["executor"]},
1339+
{"required":["execution_source"]}, {"required":["continuation"]},
1340+
{"required":["suggested_call"]}, {"required":["activity"]},
1341+
{"required":["recovery_state"]},
1342+
{"required":["recovered_after_server_restart"]},
1343+
{"required":["reconciled_at"]}, {"required":["recovery_reason_code"]},
1344+
{"required":["recovery"]}, {"required":["recovery_reason"]},
1345+
{"required":["observation_error"]}, {"required":["reconciliation"]}
1346+
]}
1347+
}}}
1348+
}));
12981349
Some(schema)
12991350
}
13001351
"open_session_shell"

‎crates/webcodex-tool-runtime-contracts/src/tool_audit.rs‎

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,6 +1145,276 @@ fn typed_skill_request_audit(kind: SkillRequestAudit, arguments: &Value) -> Valu
11451145
Value::Object(out)
11461146
}
11471147

1148+
fn bounded_test_count_assertion_audit(value: &Value) -> Option<Value> {
1149+
let assertion = value.as_object()?;
1150+
let minimum_tests = assertion.get("minimum_tests")?.as_u64()?;
1151+
let actual_tests_run = match assertion.get("actual_tests_run")? {
1152+
Value::Null => Value::Null,
1153+
value => serde_json::json!(value.as_u64()?),
1154+
};
1155+
let status = assertion.get("status")?.as_str()?;
1156+
let reason_code = assertion.get("reason_code")?.as_str()?;
1157+
let evidence_reason_code = assertion.get("evidence_reason_code")?.as_str()?;
1158+
if !matches!(status, "passed" | "failed" | "unproven")
1159+
|| !matches!(
1160+
reason_code,
1161+
"minimum_satisfied" | "minimum_not_met" | "test_count_unproven"
1162+
)
1163+
|| !matches!(
1164+
evidence_reason_code,
1165+
"complete_summary"
1166+
| "output_truncated"
1167+
| "partial_harness_summary"
1168+
| "no_complete_summary"
1169+
| "incomplete_stream"
1170+
)
1171+
{
1172+
return None;
1173+
}
1174+
Some(serde_json::json!({
1175+
"minimum_tests": minimum_tests,
1176+
"actual_tests_run": actual_tests_run,
1177+
"status": status,
1178+
"reason_code": reason_code,
1179+
"evidence_reason_code": evidence_reason_code,
1180+
}))
1181+
}
1182+
1183+
/// ActionAudit cannot persist the raw canonical evidence that the Session ledger
1184+
/// consumes. Narrow definition-owned execution evidence to lifecycle scalars plus
1185+
/// bounded validation counts/assertions; Session excerpt/source processing continues
1186+
/// to consume its original result.
1187+
pub fn canonical_execution_audit_result_for_tool(tool_name: &str, output: &Value) -> Value {
1188+
let Some(definition) = webcodex_tool_contracts::lookup_tool_definition(tool_name) else {
1189+
return empty_audit_projection();
1190+
};
1191+
if definition.audit_policy().result
1192+
!= webcodex_tool_contracts::ToolAuditResultPolicy::CanonicalLedgerEvidence
1193+
{
1194+
return session_log_result_for_tool(tool_name, output);
1195+
}
1196+
if definition.audit_policy().execution.detail
1197+
== webcodex_tool_contracts::ToolAuditExecutionDetail::Omit
1198+
{
1199+
return empty_audit_projection();
1200+
}
1201+
// Canonical ledger evidence is borrowed only; never clone that raw body
1202+
// into ActionAudit. The definition still owns execution eligibility.
1203+
let mut result = serde_json::Map::new();
1204+
for key in [
1205+
"command_started",
1206+
"command_completed",
1207+
"command_ok",
1208+
"passed",
1209+
"terminal",
1210+
"promoted_to_job",
1211+
"changed",
1212+
"state_changed",
1213+
"tool_failure",
1214+
] {
1215+
if let Some(value) = output.get(key).filter(|value| value.is_boolean()) {
1216+
result.insert(key.to_string(), value.clone());
1217+
}
1218+
}
1219+
if let Some(value) = output.get("exit_code").filter(|value| value.is_i64()) {
1220+
result.insert("exit_code".to_string(), value.clone());
1221+
}
1222+
if let Some(kind) = output.get("failure_kind").and_then(Value::as_str) {
1223+
if !kind.is_empty()
1224+
&& kind.len() <= 64
1225+
&& kind
1226+
.bytes()
1227+
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
1228+
{
1229+
result.insert("failure_kind".to_string(), Value::String(kind.to_string()));
1230+
}
1231+
}
1232+
if let Some(kind) = output.get("recovery_kind").and_then(Value::as_str) {
1233+
if webcodex_core::runtime_contract::RECOVERY_KIND_VALUES.contains(&kind) {
1234+
result.insert("recovery_kind".to_string(), Value::String(kind.to_string()));
1235+
}
1236+
}
1237+
for key in ["warnings_count", "errors_count"] {
1238+
if let Some(value) = output.get(key).filter(|value| value.is_u64()) {
1239+
result.insert(key.to_string(), value.clone());
1240+
}
1241+
}
1242+
if matches!(
1243+
definition.audit_policy().execution.detail,
1244+
webcodex_tool_contracts::ToolAuditExecutionDetail::TestCounts
1245+
| webcodex_tool_contracts::ToolAuditExecutionDetail::TestAssertions
1246+
) {
1247+
for key in ["tests_run_count", "tests_passed", "tests_failed"] {
1248+
if let Some(value) = output.get(key).filter(|value| value.is_u64()) {
1249+
result.insert(key.to_string(), value.clone());
1250+
}
1251+
}
1252+
for key in ["tests_detected", "zero_tests_run"] {
1253+
if let Some(value) = output.get(key).filter(|value| value.is_boolean()) {
1254+
result.insert(key.to_string(), value.clone());
1255+
}
1256+
}
1257+
}
1258+
if definition.audit_policy().execution.detail
1259+
== webcodex_tool_contracts::ToolAuditExecutionDetail::TestAssertions
1260+
{
1261+
for key in ["require_tests", "no_run"] {
1262+
if let Some(value) = output.get(key).filter(|value| value.is_boolean()) {
1263+
result.insert(key.to_string(), value.clone());
1264+
}
1265+
}
1266+
if let Some(assertion) = output
1267+
.get("test_count_assertion")
1268+
.and_then(bounded_test_count_assertion_audit)
1269+
{
1270+
result.insert("test_count_assertion".to_string(), assertion);
1271+
}
1272+
}
1273+
if let Some(state) = output.get("execution_state").and_then(Value::as_str) {
1274+
if matches!(
1275+
state,
1276+
"completed"
1277+
| "not_started"
1278+
| "outcome_unknown"
1279+
| "timed_out"
1280+
| "pending"
1281+
| "queued"
1282+
| "running"
1283+
| "started"
1284+
) {
1285+
result.insert(
1286+
"execution_state".to_string(),
1287+
Value::String(state.to_string()),
1288+
);
1289+
}
1290+
}
1291+
if let Some(source) = output.get("source_state") {
1292+
// Only closed source classifications, never the fence/epoch identity.
1293+
if let (Some(freshness), Some(fence)) = (
1294+
source.get("freshness").and_then(Value::as_str),
1295+
source
1296+
.get("observed_mutation_fence")
1297+
.and_then(Value::as_str),
1298+
) {
1299+
if matches!(freshness, "unproven" | "stale")
1300+
&& matches!(fence, "uncrossed" | "crossed" | "unknown")
1301+
{
1302+
result.insert(
1303+
"source_state".to_string(),
1304+
serde_json::json!({
1305+
"freshness": freshness, "observed_mutation_fence": fence,
1306+
}),
1307+
);
1308+
}
1309+
}
1310+
}
1311+
Value::Object(result)
1312+
}
1313+
1314+
#[cfg(test)]
1315+
mod canonical_execution_audit_projection_tests {
1316+
use super::*;
1317+
use serde_json::json;
1318+
1319+
#[test]
1320+
fn validation_audit_keeps_bounded_counts_and_assertion_without_payloads() {
1321+
let output = json!({
1322+
"execution_state": "completed",
1323+
"command_started": true,
1324+
"command_completed": true,
1325+
"command_ok": true,
1326+
"passed": true,
1327+
"exit_code": 0,
1328+
"tests_detected": true,
1329+
"tests_run_count": 12,
1330+
"tests_passed": 12,
1331+
"tests_failed": 0,
1332+
"zero_tests_run": false,
1333+
"require_tests": true,
1334+
"no_run": false,
1335+
"test_count_assertion": {
1336+
"minimum_tests": 1,
1337+
"actual_tests_run": 12,
1338+
"status": "passed",
1339+
"reason_code": "minimum_satisfied",
1340+
"evidence_reason_code": "complete_summary"
1341+
},
1342+
"source_state": {
1343+
"freshness": "unproven",
1344+
"observed_mutation_fence": "uncrossed",
1345+
"source_fence": "PRIVATE_FENCE"
1346+
},
1347+
"command_summary": "PRIVATE_COMMAND",
1348+
"stdout_tail": "PRIVATE_STDOUT",
1349+
"stderr_tail": "PRIVATE_STDERR",
1350+
"diagnostics": {"diagnostics":[{"message":"PRIVATE_DIAGNOSTIC"}]}
1351+
});
1352+
let audit = canonical_execution_audit_result_for_tool("cargo_test", &output);
1353+
assert_eq!(audit["execution_state"], "completed");
1354+
assert_eq!(audit["tests_run_count"], 12);
1355+
assert_eq!(audit["tests_passed"], 12);
1356+
assert_eq!(audit["tests_failed"], 0);
1357+
assert_eq!(audit["zero_tests_run"], false);
1358+
assert_eq!(audit["require_tests"], true);
1359+
assert_eq!(audit["test_count_assertion"]["status"], "passed");
1360+
assert_eq!(audit["source_state"]["freshness"], "unproven");
1361+
assert_eq!(
1362+
audit["source_state"]["observed_mutation_fence"],
1363+
"uncrossed"
1364+
);
1365+
let serialized = serde_json::to_string(&audit).unwrap();
1366+
for private in [
1367+
"PRIVATE_COMMAND",
1368+
"PRIVATE_STDOUT",
1369+
"PRIVATE_STDERR",
1370+
"PRIVATE_DIAGNOSTIC",
1371+
"PRIVATE_FENCE",
1372+
] {
1373+
assert!(!serialized.contains(private));
1374+
}
1375+
assert!(audit.get("command_summary").is_none());
1376+
assert!(audit.get("diagnostics").is_none());
1377+
}
1378+
1379+
#[test]
1380+
fn execution_audit_keeps_bounded_failure_and_recovery_classification() {
1381+
let audit = canonical_execution_audit_result_for_tool(
1382+
"run_shell",
1383+
&json!({
1384+
"execution_state":"outcome_unknown",
1385+
"command_started":true,
1386+
"command_completed":false,
1387+
"command_ok":false,
1388+
"failure_kind":"outcome_unknown",
1389+
"recovery_kind":"reconcile",
1390+
"stdout_tail":"PRIVATE_OUTPUT"
1391+
}),
1392+
);
1393+
assert_eq!(audit["failure_kind"], "outcome_unknown");
1394+
assert_eq!(audit["recovery_kind"], "reconcile");
1395+
assert!(!audit.to_string().contains("PRIVATE_OUTPUT"));
1396+
}
1397+
1398+
#[test]
1399+
fn text_validation_audit_keeps_warning_error_counts() {
1400+
let audit = canonical_execution_audit_result_for_tool(
1401+
"cargo_check",
1402+
&json!({
1403+
"execution_state":"completed",
1404+
"command_started":true,
1405+
"command_completed":true,
1406+
"passed":true,
1407+
"warnings_count":3,
1408+
"errors_count":0,
1409+
"stdout_tail":"PRIVATE_OUTPUT"
1410+
}),
1411+
);
1412+
assert_eq!(audit["warnings_count"], 3);
1413+
assert_eq!(audit["errors_count"], 0);
1414+
assert!(!audit.to_string().contains("PRIVATE_OUTPUT"));
1415+
}
1416+
}
1417+
11481418
pub fn session_log_result_for_tool(tool_name: &str, output: &Value) -> Value {
11491419
let Some(definition) = webcodex_tool_contracts::lookup_tool_definition(tool_name) else {
11501420
return empty_audit_projection();

‎docs/agent/session-model.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,12 @@ durable/queryable sink for low-cardinality ergonomics telemetry. No second
771771
telemetry table or recorder is created. The shared ToolRuntime kernel owns the
772772
normal timer for a registered model-visible tool; the transport that already owns
773773
the outer Action Audit row then finalizes one `summary.model_ergonomics` object
774-
from the final model-facing ToolResult projection. A transport may use a bounded
774+
from the final model-facing ToolResult projection, retaining the canonical
775+
closed execution state captured before late model compaction. Execution
776+
ActionAudit receipts retain definition-authorized bounded lifecycle, validation
777+
counts/assertion verdicts, and source classifications, never raw command/script/stdout/stderr,
778+
diagnostic bodies, or source fence identity.
779+
Workflow Session evidence is consumed before projection. A transport may use a bounded
775780
fallback timer only after a runtime tool identity is established when MCP-only
776781
validation rejects the call before kernel entry or the MCP hard dispatch timeout
777782
prevents kernel completion. Batch items do not create generic invocation records,

‎docs/agent/tool-contract-guidelines.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,17 @@ ready Job ids/status/outcomes and pending ids remain, including terminal failure
513513
Passive `job_attention` presence with nonempty `items` represents changed delivery
514514
without a second `changed=true` flag.
515515

516+
Execution/validation success compaction shares this late boundary: Session and
517+
source consumers see canonical results, then definition-owned privacy projections
518+
and generic telemetry capture bounded facts, then the model receipt is compacted.
519+
Existing process/script/Skill and validation success shapes are unchanged.
520+
`run_shell` removes lifecycle/Job/timing bookkeeping only for proven synchronous
521+
exit-zero completion without Job/recovery identity or observation ambiguity. It
522+
retains runtime-selected `command_summary`, `cwd`, `shell`, any `ssh_resource`,
523+
nonempty output, truncation/loss, expectations, normalization and sidecars. Failure,
524+
timeout, uncertainty and exceptional handoff remain rich; normal pending receipts
525+
still contain `execution_state=pending` and the exact continuation.
526+
516527
### Runtime status projections
517528

518529
Canonical `runtime_status` and HTTP/API omission retain full diagnostic output.

0 commit comments

Comments
 (0)