Fix replay policy wire commands and register the agent smoke tool

Send complete op/steps/value records to the Lean decoder for every operation. Preserve companion exit status and a bounded stderr tail on transport failure. Register the smoke fixture read tool explicitly without weakening the allowlist or changing its output assertion.

Validation: 462 library tests and 312 gold tests passed. The repository regression run passed 946 tests with two existing ignored experiments; the previously passed 1000-document scale test was not repeated.
This commit is contained in:
cflmy committed 2026-11-08 21:50:01 +08:00
1 parent 5080136d65
commit 16c44588d5
5 files changed
+216 -50

No files matched your search

+1 -1
View File
@@ -68,4 +68,4 @@ node tests/web/layout.browser.cjs /absolute/path/to/preview.html
既有 Anlian 渲染测试已从硬编码个人数据库改为临时目录建表并注入已知数据,使完整 Go 套件无需个人站点状态。
全库 Rust 库级回归为 436 通过、25 失败,失败集中于外联内核与验证策略/回放;在隔离源码副本还原本轮三个核心文件后,失败集合完全一致,没有新增失败。Web 专项、全部 Web Go 测试、浏览器几何与 Quantum 手册回归通过。本轮没有把这些既有策略/回放失败混入布局修复。
Web 提交时,全库 Rust 为 436 通过、25 项既有策略/回放失败,基线失败集合相同。后续已单独修复 Rust→Lean 命令缺字段的问题:所有操作发送完整的 op、steps、value,进程错误保留退出码与 stderr。原 25 项失败全部消除,新增诊断回归后库级测试为 462 通过、0 失败。策略判定仍由 Lean 执行。
+6 -6
View File
@@ -1,7 +1,7 @@
//! Production adapter to the executable Lean replay policy.
//! All replay decisions come from ReplayPolicy.Cursor, with no Rust fallback.
use super::ProtocolStep;
use serde_json::{json, Value};
use serde_json::Value;
use std::collections::VecDeque;
mod policy;
@@ -62,10 +62,10 @@ impl ReplayCursor {
self.stopped = Some(error.clone());
error
}
fn command(&mut self, command: Value) -> Result<(), Divergence> {
fn command(&mut self, op: &str, value: &str) -> Result<(), Divergence> {
if let Some(error) = &self.stopped { return Err(error.clone()) }
let result = self.client.as_mut().ok_or_else(|| "no policy process".to_string())
.and_then(|client| client.exchange(command));
.and_then(|client| client.exchange(op, value));
let reply = result.map_err(|e| self.unavailable(e))?;
self.progress = (reply.matched, reply.remaining);
if reply.allow { return Ok(()) }
@@ -82,15 +82,15 @@ impl ReplayCursor {
Err(error)
}
fn prepare(&mut self, session: &str, request: &Value) -> Result<DispatchPermit, Divergence> {
self.command(json!({"op":"prepare", "value":policy::request_key(session,request)}))?;
self.command("prepare", &policy::request_key(session,request))?;
Ok(DispatchPermit { session: session.into(), request: request.clone() })
}
pub(super) fn accept_response(&mut self, response: &Result<Value,String>) -> Result<(), Divergence> {
self.command(json!({"op":"receive", "value":policy::response_key(response)}))
self.command("receive", &policy::response_key(response))
}
pub fn progress(&self) -> (usize,usize) { self.progress }
/// Called only at the outer action boundary; consumes the cursor.
pub fn finish(mut self) -> Result<(),Divergence> { self.command(json!({"op":"finish"})) }
pub fn finish(mut self) -> Result<(),Divergence> { self.command("finish", "") }
}
pub(super) fn prepare(cursor: Option<&mut ReplayCursor>, session: &str, request: &Value)
-> Result<DispatchPermit,Divergence> {
+180 -43
View File
@@ -1,10 +1,10 @@
//! Transport for the executable Lean policy. This module makes no replay
//! acceptance decisions; malformed/unavailable policy responses fail closed.
use super::super::ProtocolStep;
use serde::Deserialize;
use serde_json::{json, Value};
use std::io::{BufRead, BufReader, Write};
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;
@@ -19,26 +19,46 @@ pub(super) struct Reply {
pub reason: Option<String>,
}
#[derive(Serialize)]
struct StepWire {
q: String,
r: String,
}
// Lean's derived FromJson requires every field, including fields with a Lean
// default. Always send the complete record for init, prepare, receive and finish.
#[derive(Serialize)]
struct CommandWire<'a> {
op: &'a str,
steps: &'a [StepWire],
value: &'a str,
}
#[derive(Debug)]
pub(super) struct Client {
child: Child,
input: ChildStdin,
replies: Receiver<Result<Reply,String>>,
replies: Receiver<Result<Reply, String>>,
stderr: Receiver<String>,
}
pub(super) fn request_key(session: &str, request: &Value) -> String {
serde_json::to_string(&(session,request.to_string())).expect("strings serialize")
serde_json::to_string(&(session, request.to_string())).expect("strings serialize")
}
pub(super) fn response_key(response: &Result<Value,String>) -> String {
pub(super) fn response_key(response: &Result<Value, String>) -> String {
serde_json::to_string(response).expect("protocol responses serialize")
}
fn executable() -> PathBuf {
if let Some(path) = std::env::var_os("MARQDO_REPLAY_POLICY") { return path.into() }
if let Some(path) = std::env::var_os("MARQDO_REPLAY_POLICY") {
return path.into();
}
if let Ok(exe) = std::env::current_exe() {
if let Some(parent) = exe.parent() {
let adjacent = parent.join("marqdo-replay-policy");
if adjacent.is_file() { return adjacent }
if adjacent.is_file() {
return adjacent;
}
}
}
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -46,47 +66,164 @@ fn executable() -> PathBuf {
}
impl Client {
pub(super) fn start(steps: impl IntoIterator<Item=ProtocolStep>) -> Result<(Self,Reply),String> {
let path=executable();
let mut child=Command::new(&path).stdin(Stdio::piped()).stdout(Stdio::piped())
.stderr(Stdio::null()).spawn().map_err(|e|format!("{}: {e}",path.display()))?;
let input=child.stdin.take().ok_or("policy stdin unavailable")?;
let output=child.stdout.take().ok_or("policy stdout unavailable")?;
let (sender,replies)=mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(output).lines() {
let reply=line.map_err(|e|e.to_string())
.and_then(|line|serde_json::from_str(&line).map_err(|e|e.to_string()));
let failed=reply.is_err();
if sender.send(reply).is_err() || failed { break }
}
});
let steps: Vec<_>=steps.into_iter().map(|step|json!({
"q":request_key(&step.session,&step.request),"r":response_key(&step.response)
})).collect();
let mut client=Self {child,input,replies};
let reply=client.exchange(json!({"op":"init","steps":steps}))?;
Ok((client,reply))
pub(super) fn start(
steps: impl IntoIterator<Item = ProtocolStep>,
) -> Result<(Self, Reply), String> {
Self::start_at(&executable(), steps)
}
pub(super) fn exchange(&mut self, command: Value) -> Result<Reply,String> {
serde_json::to_writer(&mut self.input,&command).map_err(|e|e.to_string())?;
self.input.write_all(b"\n").map_err(|e|e.to_string())?;
self.input.flush().map_err(|e|e.to_string())?;
let reply=self.replies.recv_timeout(Duration::from_secs(30))
.map_err(|e|format!("policy response: {e}"))??;
if reply.policy != include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/verification/replay-policy/POLICY-SHA256")).trim() {
return Err("policy executable does not match the compiled source identity".into())
fn start_at(
path: &Path,
steps: impl IntoIterator<Item = ProtocolStep>,
) -> Result<(Self, Reply), String> {
let mut child = Command::new(path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("{}: {e}", path.display()))?;
let input = child.stdin.take().ok_or("policy stdin unavailable")?;
let output = child.stdout.take().ok_or("policy stdout unavailable")?;
let mut errors = child.stderr.take().ok_or("policy stderr unavailable")?;
let (sender, replies) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(output).lines() {
let reply = line
.map_err(|e| e.to_string())
.and_then(|line| serde_json::from_str(&line).map_err(|e| e.to_string()));
let failed = reply.is_err();
if sender.send(reply).is_err() || failed {
break;
}
}
});
// Drain stderr concurrently so a verbose failure cannot block the child.
// Retain a bounded diagnostic tail rather than buffering an entire stream.
let (error_sender, stderr) = mpsc::channel();
std::thread::spawn(move || {
const LIMIT: usize = 4096;
let mut tail = Vec::new();
let mut buffer = [0; LIMIT];
while let Ok(count) = errors.read(&mut buffer) {
if count == 0 {
break;
}
tail.extend_from_slice(&buffer[..count]);
if tail.len() > LIMIT {
tail.drain(..tail.len() - LIMIT);
}
}
let _ = error_sender.send(String::from_utf8_lossy(&tail).trim().to_string());
});
let steps: Vec<_> = steps
.into_iter()
.map(|step| StepWire {
q: request_key(&step.session, &step.request),
r: response_key(&step.response),
})
.collect();
let mut client = Self {
child,
input,
replies,
stderr,
};
let reply = client.send(CommandWire {
op: "init",
steps: &steps,
value: "",
})?;
Ok((client, reply))
}
pub(super) fn exchange(&mut self, op: &str, value: &str) -> Result<Reply, String> {
self.send(CommandWire {
op,
steps: &[],
value,
})
}
fn send(&mut self, command: CommandWire<'_>) -> Result<Reply, String> {
let result = (|| {
serde_json::to_writer(&mut self.input, &command).map_err(|e| e.to_string())?;
self.input.write_all(b"\n").map_err(|e| e.to_string())?;
self.input.flush().map_err(|e| e.to_string())?;
let reply = self
.replies
.recv_timeout(Duration::from_secs(30))
.map_err(|e| format!("policy response: {e}"))??;
if reply.policy
!= include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/verification/replay-policy/POLICY-SHA256"
))
.trim()
{
return Err("policy executable does not match the compiled source identity".into());
}
if reply.allow == reply.reason.is_some() {
return Err("policy response has inconsistent verdict and reason".into());
}
Ok(reply)
})();
result.map_err(|error| self.process_error(error))
}
fn process_error(&mut self, mut error: String) -> String {
// Prefer the actual exit status when the process has already failed.
let status = match self.child.try_wait() {
Ok(Some(status)) => Some(status),
_ => {
let _ = self.child.kill();
self.child.wait().ok()
}
};
if let Some(status) = status {
error.push_str(&format!("; policy process {status}"));
}
if reply.allow == reply.reason.is_some() {
return Err("policy response has inconsistent verdict and reason".into())
if let Ok(stderr) = self.stderr.recv_timeout(Duration::from_millis(100)) {
if !stderr.is_empty() {
error.push_str(&format!("; stderr: {stderr}"));
}
}
Ok(reply)
error
}
}
impl Drop for Client {
fn drop(&mut self) {
let _=self.child.kill();
let _=self.child.wait();
let _ = self.child.kill();
let _ = self.child.wait();
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn failed_companion_reports_its_exit_status_and_decoder_error() {
let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join(format!(
"policy-transport-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let executable = dir.join("failed-policy");
std::fs::write(&executable, "#!/bin/sh\nIFS= read -r command\nprintf '%s\\n' 'PolicyCommand.value: String expected' >&2\nexit 17\n").unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();
let error = Client::start_at(&executable, Vec::<ProtocolStep>::new()).unwrap_err();
std::fs::remove_dir_all(dir).unwrap();
assert!(error.contains("exit status: 17"), "{error}");
assert!(
error.contains("PolicyCommand.value: String expected"),
"{error}"
);
}
}
+13
View File
@@ -25,6 +25,19 @@ import:
**模型 = > llm.llm**
**助手 = > agent.agent model=`模型` tools=`工具表` standing="you are a readable Marqdo agent"**
The allowlist names what the agent may call; ToolSpec registration declares the
actual capability. This deterministic read tool takes no arguments and keeps
this smoke test independent of a real clock or mutating effect ledger.
`spec` =
| id | version | description | effect |
|----|---------|-------------|--------|
| 获取时间 | "1" | deterministic smoke value | read |
> agent.tools_clear
> agent.tools_register spec=`spec`
**id = > json.get value=`助手` key="id"**
**ctx = > agent.build_step_context agent=`助手` task="probe"**
+16
View File
@@ -5,6 +5,22 @@ reply acceptance and final-history exhaustion. The Rust transport adapter does
not contain a second implementation of these decisions. Ordinary recording
does not start a policy process.
The JSON-lines transport sends a complete `PolicyCommand` record on every
operation: `op`, `steps`, and `value` are always present. Lean structure defaults
are not missing-field defaults for the derived JSON decoder. In particular,
initialization and finish still need an empty `value`, while prepare/receive
still need an empty `steps` array:
```jsonl
{"op":"init","steps":[],"value":""}
{"op":"finish","steps":[],"value":""}
```
The Rust adapter uses one typed wire record for all four operations. Transport
failures stop the companion and include its exit status and a bounded stderr
tail, so a decoder error is not reduced to a closed-channel message. Neither
this transport nor its diagnostics replace Lean's replay verdict.
Build the companion before building or testing strict replay:
```sh