feat: migrate View 0.3.0 to marqdo 3.0.0-rc.4 contracts
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/push/woodpecker Pipeline was successful
Replace the retired rc.2 Analysis v2/Trace v2/Execution Events v1 stack with the
single current contract family:
- Analysis v3 (ADR-0069 public boundary): one check --emit artifact carries the
exact source, Markdown AST, heading scopes (heading_span + complete span),
anchors, state-bearing references, calls, resources and diagnostics; the old
revision-3 shape is rejected with a rebuild hint.
- Observation v1: one run/call --output jsonl stream (+ atomic
--observation-file snapshot) decoded by one decoder and projected into the
reader/SSE/export layers; stale/malformed/truncated/incomplete never render
as success.
- CLI Tool revision 1: requires {api_revision:1, analysis:3, observation:1},
product range >=3.0.0-rc.3,<4.0.0, only MARQDO_BIN and
MARQDO_API_REVISION are consumed.
- Remove compatibility branches, retired flags/env vars and duplicate decoders;
re-record Analysis v3 and Observation v1 fixtures; rewrite contract,
integration and security tests (173 passing locally).
- Add check-no-legacy/check-docs/check-observation gates, rc.4 pins in the
CI pipelines, 0.3.0 Tool bundle and evidence manifest support.
See issues #4, #5 and #6; acceptance baseline is CLI source
452e9a32bd9e40dba427d4180691c58bab74449e, archive
9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8.
This commit is contained in:
1 parent
7b34199c96
commit
340ecb035f
108 files changed
+13928
-6461
No files matched your search
+2
-2
@@ -12,8 +12,8 @@ use std::path::PathBuf;
|
||||
#[command(
|
||||
name = "marqdo-view",
|
||||
version,
|
||||
about = "Read .mq.md documents as documents: static Analysis v2, optional explicit run Trace v2",
|
||||
long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v2 facts. \
|
||||
about = "Read .mq.md documents as documents: static Analysis v3, optional explicit Observation v1",
|
||||
long_about = "Marqdo View renders the original Markdown and attaches verified Analysis v3 facts. \
|
||||
Running is never implicit: it requires an explicit user action. \
|
||||
Export is always a pure read-only operation.",
|
||||
disable_help_subcommand = true,
|
||||
|
||||
+161
-196
@@ -1,9 +1,11 @@
|
||||
//! The only way View talks to the frozen CLI.
|
||||
//!
|
||||
//! Invariants (RFC-VIEW-0001 §4.2, §10.3, §14.1):
|
||||
//! Invariants:
|
||||
//! * absolute `MARQDO_BIN`, argv arrays, never `sh -c`, never shell strings;
|
||||
//! * `check --emit` is the only static channel; `run --trace-file --json` the
|
||||
//! only dynamic one; private Core IR dumps are never used;
|
||||
//! * `check --emit` is the only static channel; `run`/`call --output jsonl`
|
||||
//! (optionally with `--observation-file`) is the only dynamic channel, and
|
||||
//! both dynamic destinations come from the same execution;
|
||||
//! * private Core IR dumps, second parsers and protocol probing are never used;
|
||||
//! * stdout/stderr/exit status are handled separately; a stderr JSON blob is
|
||||
//! never promoted to a successful Analysis;
|
||||
//! * temporary artifacts live in a private 0700 directory and are removed on
|
||||
@@ -24,14 +26,18 @@ pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
/// Default View-level wall clock cap for one Core `check`.
|
||||
pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
|
||||
/// Bounded observation budget sent on every explicit run. The protocol
|
||||
/// expresses exhaustion through `observation.truncated`; View never silently
|
||||
/// drops or amplifies events itself.
|
||||
pub const DEFAULT_OBSERVE_MAX_EVENTS: u64 = 10_000;
|
||||
pub const DEFAULT_OBSERVE_MAX_BYTES: u64 = 4_194_304;
|
||||
pub const DEFAULT_OBSERVE_MAX_VALUE_BYTES: u64 = 256;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SandboxMode {
|
||||
Pure,
|
||||
Project,
|
||||
Strict,
|
||||
}
|
||||
|
||||
impl SandboxMode {
|
||||
@@ -39,7 +45,6 @@ impl SandboxMode {
|
||||
match self {
|
||||
SandboxMode::Pure => "pure",
|
||||
SandboxMode::Project => "project",
|
||||
SandboxMode::Strict => "strict",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,14 +64,13 @@ pub struct Grants {
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CheckOptions {
|
||||
/// `--refs` also validates Markdown link targets; it is a stricter check
|
||||
/// and may fail where plain syntax succeeds.
|
||||
/// and its artifact must never be used as the Observation binding input.
|
||||
pub refs: bool,
|
||||
pub timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunOptions {
|
||||
pub event_stream: bool,
|
||||
pub mode: SandboxMode,
|
||||
pub grants: Grants,
|
||||
pub fuel: Option<u64>,
|
||||
@@ -74,14 +78,19 @@ pub struct RunOptions {
|
||||
pub max_output: Option<u64>,
|
||||
pub timeout_seconds: Option<u64>,
|
||||
pub view_timeout: Option<Duration>,
|
||||
pub trace_max_events: Option<u64>,
|
||||
pub trace_max_bytes: Option<u64>,
|
||||
pub observe_max_events: u64,
|
||||
pub observe_max_bytes: u64,
|
||||
pub observe_max_value_bytes: u64,
|
||||
/// Explicit value selection. Empty by default: View never requests values
|
||||
/// unless the user opts in (and Text additionally needs a second consent).
|
||||
pub observe_variables: Vec<String>,
|
||||
pub observe_parameters: Vec<String>,
|
||||
pub observe_text_values: bool,
|
||||
}
|
||||
|
||||
impl Default for RunOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
event_stream: false,
|
||||
mode: SandboxMode::Pure,
|
||||
grants: Grants::default(),
|
||||
fuel: None,
|
||||
@@ -89,8 +98,12 @@ impl Default for RunOptions {
|
||||
max_output: None,
|
||||
timeout_seconds: None,
|
||||
view_timeout: Some(DEFAULT_RUN_TIMEOUT),
|
||||
trace_max_events: None,
|
||||
trace_max_bytes: None,
|
||||
observe_max_events: DEFAULT_OBSERVE_MAX_EVENTS,
|
||||
observe_max_bytes: DEFAULT_OBSERVE_MAX_BYTES,
|
||||
observe_max_value_bytes: DEFAULT_OBSERVE_MAX_VALUE_BYTES,
|
||||
observe_variables: Vec::new(),
|
||||
observe_parameters: Vec::new(),
|
||||
observe_text_values: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,13 +114,13 @@ pub struct CheckOutput {
|
||||
pub analysis_bytes: Vec<u8>,
|
||||
/// Lowercase hex SHA-256 of `analysis_bytes`.
|
||||
pub analysis_sha256: String,
|
||||
/// Prefixed digest (`sha256:...`) for comparison with Trace v2.
|
||||
/// Prefixed digest (`sha256:...`) used by the Observation binding.
|
||||
pub analysis_digest: String,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
/// One compile diagnostic from `check --json`, normalized so no absolute
|
||||
/// One check diagnostic from `check --json`, normalized so no absolute
|
||||
/// machine path can leak into pages, exports or logs.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RawCheckDiagnostic {
|
||||
@@ -128,7 +141,7 @@ pub struct RawCheckDiagnostic {
|
||||
}
|
||||
|
||||
/// Result of one `check` invocation. A failed check is **not** an I/O error:
|
||||
/// the prose stays readable and diagnostics must be shown (RFC §12.3).
|
||||
/// the prose stays readable and diagnostics must be shown.
|
||||
#[derive(Debug)]
|
||||
pub struct CheckResponse {
|
||||
pub success: bool,
|
||||
@@ -138,65 +151,39 @@ pub struct CheckResponse {
|
||||
pub stderr: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RunOutput {
|
||||
/// Exactly one JSON document emitted on stdout by the Core.
|
||||
pub json: serde_json::Value,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: i32,
|
||||
/// Raw Trace v2 bytes when the Core wrote them (even for a failed run).
|
||||
pub trace_bytes: Option<Vec<u8>>,
|
||||
pub trace_sha256: Option<String>,
|
||||
}
|
||||
|
||||
pub use crate::scratch::ScratchDir;
|
||||
|
||||
/// Negotiated public-client for one frozen core binary.
|
||||
/// The public client for one frozen core binary.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreClient {
|
||||
bin: PathBuf,
|
||||
protocol_env: ProtocolEnv,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct ProtocolEnv {
|
||||
tool: Option<String>,
|
||||
analysis: Option<String>,
|
||||
trace: Option<String>,
|
||||
api_revision: Option<String>,
|
||||
}
|
||||
|
||||
impl CoreClient {
|
||||
/// Build a client from `--marqdo-bin` (development) or `MARQDO_BIN`
|
||||
/// (installed Tool Protocol). Never guesses a `PATH` binary: a wrong
|
||||
/// version must fail loudly, not silently.
|
||||
/// (installed Tool). Never guesses a `PATH` binary: a wrong version must
|
||||
/// fail loudly, not silently.
|
||||
pub fn from_env(explicit: Option<&Path>) -> ViewResult<Self> {
|
||||
let bin = locate_bin(explicit)?;
|
||||
Self::with_bin(bin)
|
||||
}
|
||||
|
||||
/// Construct from an explicit binary path, still reading any negotiated
|
||||
/// protocol environment. Useful for `--marqdo-bin` and integration tests;
|
||||
/// production dispatch should prefer [`CoreClient::from_env`].
|
||||
/// Construct from an explicit binary path, still reading the injected API
|
||||
/// revision expectation. Useful for `--marqdo-bin` and integration tests.
|
||||
pub fn with_bin(bin: impl Into<PathBuf>) -> ViewResult<Self> {
|
||||
let bin = validate_bin(&bin.into(), "core binary")?;
|
||||
Ok(Self {
|
||||
bin,
|
||||
protocol_env: ProtocolEnv {
|
||||
tool: std::env::var(tool_v1::ENV_TOOL_PROTOCOL).ok(),
|
||||
analysis: std::env::var(tool_v1::ENV_PROTOCOL_ANALYSIS).ok(),
|
||||
trace: std::env::var(tool_v1::ENV_PROTOCOL_TRACE).ok(),
|
||||
},
|
||||
})
|
||||
let api_revision = std::env::var(tool_v1::ENV_MARQDO_API_REVISION).ok();
|
||||
tool_v1::validate_api_revision_env(api_revision.as_deref())?;
|
||||
Ok(Self { bin, api_revision })
|
||||
}
|
||||
|
||||
/// Test-only constructor with an explicit binary and no environment
|
||||
/// negotiation input.
|
||||
/// Test-only constructor with no injected environment expectation.
|
||||
#[cfg(test)]
|
||||
pub fn for_test(bin: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
bin: bin.into(),
|
||||
protocol_env: ProtocolEnv::default(),
|
||||
api_revision: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,15 +191,15 @@ impl CoreClient {
|
||||
&self.bin
|
||||
}
|
||||
|
||||
/// Run `--version`, validate the product range and any negotiated protocol
|
||||
/// environment variables. A missing Development-mode env is allowed; an
|
||||
/// unknown major is a hard error.
|
||||
pub fn api_revision(&self) -> Option<&str> {
|
||||
self.api_revision.as_deref()
|
||||
}
|
||||
|
||||
/// Run `--version`, validate the product range and the injected API
|
||||
/// revision. A missing Development-mode environment is allowed; an
|
||||
/// unknown revision is a hard error.
|
||||
pub fn negotiate(&self) -> ViewResult<CoreVersion> {
|
||||
tool_v1::negotiate_protocol_env(
|
||||
self.protocol_env.tool.as_deref(),
|
||||
self.protocol_env.analysis.as_deref(),
|
||||
self.protocol_env.trace.as_deref(),
|
||||
)?;
|
||||
tool_v1::validate_api_revision_env(self.api_revision.as_deref())?;
|
||||
let output = self.execute(
|
||||
&[OsString::from("--version")],
|
||||
&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
@@ -232,7 +219,7 @@ impl CoreClient {
|
||||
if !tool_v1::product_is_compatible(&version.version) {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"core {} is outside the supported range {}",
|
||||
"core {} is outside the supported range {}; install the current rc.3+ core",
|
||||
version.version,
|
||||
tool_v1::PRODUCT_RANGE
|
||||
),
|
||||
@@ -241,9 +228,11 @@ impl CoreClient {
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// `check --json --emit`. On success the exact Analysis v2 bytes are
|
||||
/// returned; on failure the structured diagnostics are returned without
|
||||
/// any absolute path. Only spawn/timeout/IO failures are hard errors.
|
||||
/// `check --json --emit`. `--json` only selects the diagnostic summary on
|
||||
/// stdout; it does not change the emitted Analysis bytes. On success the
|
||||
/// exact Analysis bytes are returned; on failure the structured
|
||||
/// diagnostics are returned without any absolute path. Only
|
||||
/// spawn/timeout/IO failures are hard errors.
|
||||
pub fn check(
|
||||
&self,
|
||||
project: &Project,
|
||||
@@ -320,62 +309,6 @@ impl CoreClient {
|
||||
})
|
||||
}
|
||||
|
||||
/// `run --trace-file --json`, only after an explicit user confirmation in
|
||||
/// the calling layer. Returns the CLI JSON document and raw Trace bytes.
|
||||
pub fn run(
|
||||
&self,
|
||||
project: &Project,
|
||||
relative: &SafeRelativePath,
|
||||
options: &RunOptions,
|
||||
) -> ViewResult<RunOutput> {
|
||||
let entry = project.absolute_for(relative)?;
|
||||
let scratch = ScratchDir::create("run")?;
|
||||
let trace_path = scratch.file("trace.json");
|
||||
let args = build_run_args(&entry, &trace_path, options);
|
||||
let output = self.execute(
|
||||
&args,
|
||||
project.root(),
|
||||
options.view_timeout.unwrap_or(DEFAULT_RUN_TIMEOUT),
|
||||
)?;
|
||||
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_slice(&output.stdout_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!(
|
||||
"`marqdo run --json` did not emit exactly one JSON document: {err}; stderr: {}",
|
||||
summarize_stderr(&output.stderr)
|
||||
),
|
||||
})?;
|
||||
if !json.is_object() {
|
||||
return Err(ViewError::Io {
|
||||
detail: "`marqdo run --json` emitted a non-object JSON document".to_string(),
|
||||
});
|
||||
}
|
||||
let trace_bytes = match std::fs::read(&trace_path) {
|
||||
Ok(bytes) => {
|
||||
if bytes.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(bytes)
|
||||
}
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(err) => {
|
||||
return Err(ViewError::io(
|
||||
&format!("read trace {}", trace_path.display()),
|
||||
err,
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(RunOutput {
|
||||
json,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
exit_code: output.exit_code,
|
||||
trace_sha256: trace_bytes.as_deref().map(sha256_hex),
|
||||
trace_bytes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawn the core through the single process adapter with an explicit
|
||||
/// argv, private cwd, bounded capture and a wall-clock cap.
|
||||
fn execute(&self, args: &[OsString], cwd: &Path, timeout: Duration) -> ViewResult<ExecOutput> {
|
||||
@@ -410,30 +343,48 @@ struct ExecOutput {
|
||||
stderr: String,
|
||||
}
|
||||
|
||||
/// Build the base `check` arguments. The caller appends `--emit <path>` and
|
||||
/// optionally `--refs`; this function exists so the argv shape is unit-testable.
|
||||
/// Build the base `check` arguments. The caller appends `--json`,
|
||||
/// `--emit <path>` and optionally `--refs`; this function exists so the argv
|
||||
/// shape is unit-testable and cannot drift to a retired flag.
|
||||
fn build_check_args(entry: &Path) -> Vec<OsString> {
|
||||
vec![OsString::from("check"), entry.as_os_str().to_os_string()]
|
||||
}
|
||||
|
||||
/// Common explicit flags shared by `run` and `call`. Budgets are always sent
|
||||
/// explicitly by the execution controller (RFC-VIEW-0002 §6.7).
|
||||
fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &RunOptions) {
|
||||
/// Common explicit flags shared by `run` and `call`.
|
||||
fn append_common_args(args: &mut Vec<OsString>, observation_file: &Path, options: &RunOptions) {
|
||||
fn push_pair(args: &mut Vec<OsString>, flag: &str, value: &str) {
|
||||
args.push(OsString::from(flag));
|
||||
args.push(OsString::from(value));
|
||||
}
|
||||
args.push(OsString::from("--mode"));
|
||||
args.push(OsString::from(options.mode.as_str()));
|
||||
if options.event_stream {
|
||||
push_pair(args, "--event-stream", "jsonl");
|
||||
push_pair(args, "--observe-max-events", "10000");
|
||||
push_pair(args, "--observe-max-bytes", "4194304");
|
||||
} else {
|
||||
args.push(OsString::from("--json"));
|
||||
push_pair(args, "--output", "jsonl");
|
||||
args.push(OsString::from("--observation-file"));
|
||||
args.push(observation_file.as_os_str().to_os_string());
|
||||
push_pair(
|
||||
args,
|
||||
"--observe-max-events",
|
||||
&options.observe_max_events.to_string(),
|
||||
);
|
||||
push_pair(
|
||||
args,
|
||||
"--observe-max-bytes",
|
||||
&options.observe_max_bytes.to_string(),
|
||||
);
|
||||
push_pair(
|
||||
args,
|
||||
"--observe-max-value-bytes",
|
||||
&options.observe_max_value_bytes.to_string(),
|
||||
);
|
||||
for name in &options.observe_variables {
|
||||
push_pair(args, "--observe-variable", name);
|
||||
}
|
||||
for name in &options.observe_parameters {
|
||||
push_pair(args, "--observe-parameter", name);
|
||||
}
|
||||
if options.observe_text_values {
|
||||
args.push(OsString::from("--observe-text-values"));
|
||||
}
|
||||
args.push(OsString::from("--trace-file"));
|
||||
args.push(trace_path.as_os_str().to_os_string());
|
||||
for glob in &options.grants.allow_read {
|
||||
push_pair(args, "--allow-read", glob);
|
||||
}
|
||||
@@ -464,18 +415,16 @@ fn append_common_args(args: &mut Vec<OsString>, trace_path: &Path, options: &Run
|
||||
if let Some(timeout) = options.timeout_seconds {
|
||||
push_pair(args, "--timeout", &timeout.to_string());
|
||||
}
|
||||
if let Some(max_events) = options.trace_max_events {
|
||||
push_pair(args, "--trace-max-events", &max_events.to_string());
|
||||
}
|
||||
if let Some(max_bytes) = options.trace_max_bytes {
|
||||
push_pair(args, "--trace-max-bytes", &max_bytes.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Build `run` arguments from an already user-approved request.
|
||||
pub fn build_run_args(entry: &Path, trace_path: &Path, options: &RunOptions) -> Vec<OsString> {
|
||||
pub fn build_run_args(
|
||||
entry: &Path,
|
||||
observation_file: &Path,
|
||||
options: &RunOptions,
|
||||
) -> Vec<OsString> {
|
||||
let mut args = vec![OsString::from("run"), entry.as_os_str().to_os_string()];
|
||||
append_common_args(&mut args, trace_path, options);
|
||||
append_common_args(&mut args, observation_file, options);
|
||||
args
|
||||
}
|
||||
|
||||
@@ -485,7 +434,7 @@ pub fn build_call_args(
|
||||
entry: &Path,
|
||||
function: &str,
|
||||
arguments: &[(String, String)],
|
||||
trace_path: &Path,
|
||||
observation_file: &Path,
|
||||
options: &RunOptions,
|
||||
) -> Vec<OsString> {
|
||||
let mut args = vec![
|
||||
@@ -497,7 +446,7 @@ pub fn build_call_args(
|
||||
args.push(OsString::from("--arg"));
|
||||
args.push(OsString::from(format!("{name}={expression}")));
|
||||
}
|
||||
append_common_args(&mut args, trace_path, options);
|
||||
append_common_args(&mut args, observation_file, options);
|
||||
args
|
||||
}
|
||||
|
||||
@@ -505,18 +454,19 @@ fn locate_bin(explicit: Option<&Path>) -> ViewResult<PathBuf> {
|
||||
if let Some(path) = explicit {
|
||||
return validate_bin(path, "--marqdo-bin");
|
||||
}
|
||||
if let Some(raw) = std::env::var_os(ENV_MARQDO_BIN) {
|
||||
if let Some(raw) = std::env::var_os(tool_v1::ENV_MARQDO_BIN) {
|
||||
if raw.is_empty() {
|
||||
return Err(ViewError::CoreMissing {
|
||||
detail: format!("{ENV_MARQDO_BIN} is set but empty"),
|
||||
detail: format!("{} is set but empty", tool_v1::ENV_MARQDO_BIN),
|
||||
});
|
||||
}
|
||||
return validate_bin(Path::new(&raw), ENV_MARQDO_BIN);
|
||||
return validate_bin(Path::new(&raw), tool_v1::ENV_MARQDO_BIN);
|
||||
}
|
||||
Err(ViewError::CoreMissing {
|
||||
detail: format!(
|
||||
"{ENV_MARQDO_BIN} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \
|
||||
or pass --marqdo-bin <path> when running marqdo-view directly."
|
||||
"{} is not set. Install this tool with `marqdo tool install <bundle>/tool.json`, \
|
||||
or pass --marqdo-bin <path> when running marqdo-view directly.",
|
||||
tool_v1::ENV_MARQDO_BIN
|
||||
),
|
||||
})
|
||||
}
|
||||
@@ -545,25 +495,12 @@ fn validate_bin(path: &Path, origin: &str) -> ViewResult<PathBuf> {
|
||||
Ok(canonical)
|
||||
}
|
||||
|
||||
fn summarize_stderr(stderr: &str) -> String {
|
||||
let trimmed = stderr.trim();
|
||||
if trimmed.is_empty() {
|
||||
"(no stderr)".to_string()
|
||||
} else {
|
||||
let mut text: String = trimmed.chars().take(1200).collect();
|
||||
if trimmed.chars().count() > 1200 {
|
||||
text.push('…');
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// `marqdo view verify`: static Analysis/source binding check. Never executes.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
use crate::cli::{RuntimeOpts, VerifyArgs};
|
||||
use crate::protocol::analysis_v2;
|
||||
use crate::protocol::analysis_v3;
|
||||
|
||||
pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32> {
|
||||
let path = args
|
||||
@@ -577,7 +514,6 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{entry} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||
|
||||
let client = CoreClient::from_env(opts.marqdo_bin.as_deref())?;
|
||||
let core_version = client.negotiate()?;
|
||||
@@ -627,12 +563,8 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
})
|
||||
}
|
||||
};
|
||||
let verified = analysis_v2::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&source,
|
||||
&source_index,
|
||||
entry.as_str(),
|
||||
)?;
|
||||
let verified =
|
||||
analysis_v3::verify_analysis(&check.analysis_bytes, entry.as_str(), Some(&source))?;
|
||||
let projection = &verified.projection;
|
||||
|
||||
if args.json {
|
||||
@@ -643,6 +575,7 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
"core": {
|
||||
"version": core_version.version.to_string(),
|
||||
"supported_range": tool_v1::PRODUCT_RANGE,
|
||||
"api_revision": tool_v1::API_REVISION,
|
||||
},
|
||||
"analysis": {
|
||||
"schema": "marqdo.analysis",
|
||||
@@ -652,13 +585,21 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
"markdown_profile": projection.markdown_profile,
|
||||
"functions": projection.functions.len(),
|
||||
"units": projection.units.len(),
|
||||
"references": projection.references.len(),
|
||||
"diagnostics": projection.diagnostics.len(),
|
||||
"requires": {
|
||||
"analysis": tool_v1::ANALYSIS_REVISION,
|
||||
"observation": tool_v1::OBSERVATION_REVISION,
|
||||
},
|
||||
},
|
||||
"project": {
|
||||
"root_id": projection.project_root_id,
|
||||
"identity_kind": projection.identity_kind,
|
||||
"entry_module_id": projection.entry_module_id,
|
||||
"lock_digest": projection.lock_digest,
|
||||
"manifest_digest": projection.manifest_digest,
|
||||
"stdlib_version": projection.stdlib_version,
|
||||
"extensions": projection.extensions.len(),
|
||||
},
|
||||
"document": {
|
||||
"relative_path": entry.as_str(),
|
||||
@@ -676,9 +617,10 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"core: marqdo {} (supported {})",
|
||||
"core: marqdo {} (supported {}, api revision {})",
|
||||
core_version.version,
|
||||
tool_v1::PRODUCT_RANGE
|
||||
tool_v1::PRODUCT_RANGE,
|
||||
tool_v1::API_REVISION
|
||||
);
|
||||
println!(
|
||||
"project: {} ({})",
|
||||
@@ -686,10 +628,11 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
);
|
||||
println!("document: {entry}");
|
||||
println!(
|
||||
"analysis: schema=marqdo.analysis v{} modules={} functions={} digest={}",
|
||||
"analysis: schema=marqdo.analysis v{} modules={} functions={} references={} digest={}",
|
||||
projection.schema_version,
|
||||
projection.modules.len(),
|
||||
projection.functions.len(),
|
||||
projection.references.len(),
|
||||
projection.analysis_digest
|
||||
);
|
||||
println!("source digest: match");
|
||||
@@ -702,41 +645,70 @@ pub fn verify_command(opts: &RuntimeOpts, args: &VerifyArgs) -> ViewResult<i32>
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn text(args: &[OsString]) -> Vec<String> {
|
||||
args.iter()
|
||||
.map(|arg| arg.to_string_lossy().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_args_are_explicit_argv_never_shell() {
|
||||
fn run_args_use_the_current_observation_flags_only() {
|
||||
let args = build_run_args(
|
||||
Path::new("/p/index.mq.md"),
|
||||
Path::new("/t/trace.json"),
|
||||
Path::new("/t/observation.json"),
|
||||
&RunOptions {
|
||||
event_stream: false,
|
||||
mode: SandboxMode::Pure,
|
||||
mode: SandboxMode::Project,
|
||||
grants: Grants {
|
||||
allow_read: vec!["data/**".into()],
|
||||
allow_net: vec!["example.com".into()],
|
||||
..Default::default()
|
||||
},
|
||||
fuel: Some(1000),
|
||||
trace_max_events: Some(20),
|
||||
observe_max_events: 20,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let text: Vec<String> = args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().to_string())
|
||||
.collect();
|
||||
let text = text(&args);
|
||||
assert_eq!(text[0], "run");
|
||||
assert_eq!(text[1], "/p/index.mq.md");
|
||||
assert!(text.contains(&"pure".to_string()));
|
||||
assert!(text.contains(&"--json".to_string()));
|
||||
assert!(text.contains(&"--trace-file".to_string()));
|
||||
assert!(text.contains(&"project".to_string()));
|
||||
assert!(text.contains(&"--output".to_string()));
|
||||
assert!(text.contains(&"jsonl".to_string()));
|
||||
assert!(text.contains(&"--observation-file".to_string()));
|
||||
assert!(text.contains(&"--observe-max-events".to_string()));
|
||||
assert!(text.contains(&"--observe-max-bytes".to_string()));
|
||||
assert!(text.contains(&"--observe-max-value-bytes".to_string()));
|
||||
assert!(text.contains(&"data/**".to_string()));
|
||||
assert!(text.contains(&"example.com".to_string()));
|
||||
assert!(text.contains(&"1000".to_string()));
|
||||
assert!(text.contains(&"20".to_string()));
|
||||
// No token is a shell fragment: every argument is a separate value.
|
||||
// Retired flags and any shell fragment must never appear.
|
||||
for retired in [
|
||||
"--json",
|
||||
"--trace-file",
|
||||
"--event-stream",
|
||||
"--trace-max-events",
|
||||
"--trace-max-bytes",
|
||||
] {
|
||||
assert!(
|
||||
!text.contains(&retired.to_string()),
|
||||
"retired flag {retired}"
|
||||
);
|
||||
}
|
||||
assert!(!text
|
||||
.iter()
|
||||
.any(|t| t.contains(';') || t.contains('|') || t.contains('&')));
|
||||
.any(|token| token.contains(';') || token.contains('|') || token.contains('&')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_defaults_do_not_request_values() {
|
||||
let args = build_run_args(
|
||||
Path::new("/p/index.mq.md"),
|
||||
Path::new("/t/observation.json"),
|
||||
&RunOptions::default(),
|
||||
);
|
||||
let text = text(&args);
|
||||
assert!(!text.iter().any(|token| token == "--observe-variable"));
|
||||
assert!(!text.iter().any(|token| token == "--observe-parameter"));
|
||||
assert!(!text.iter().any(|token| token == "--observe-text-values"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -768,11 +740,4 @@ mod tests {
|
||||
drop(scratch);
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_summary_is_bounded() {
|
||||
let text = summarize_stderr(&"x".repeat(5000));
|
||||
assert!(text.chars().count() <= 1201);
|
||||
assert_eq!(summarize_stderr(" "), "(no stderr)");
|
||||
}
|
||||
}
|
||||
+26
-7
@@ -37,8 +37,17 @@ pub enum ViewError {
|
||||
SourceSpanInvalid {
|
||||
detail: String,
|
||||
},
|
||||
/// Trace does not bind to the current Analysis bytes.
|
||||
TraceStale {
|
||||
/// Observation v1 is malformed, mixed, out of order or violates the
|
||||
/// selected observation policy.
|
||||
ObservationInvalid {
|
||||
detail: String,
|
||||
},
|
||||
/// Observation does not bind to the current Analysis bytes/source.
|
||||
ObservationStale {
|
||||
detail: String,
|
||||
},
|
||||
/// The CLI rejected an option combination before starting (exit code 2).
|
||||
CoreOptionRejected {
|
||||
detail: String,
|
||||
},
|
||||
/// The user did not confirm, or the requested mode/grants are not allowed.
|
||||
@@ -106,7 +115,7 @@ pub enum ViewError {
|
||||
OutputLimit {
|
||||
detail: String,
|
||||
},
|
||||
/// The CLI exited but its `--json` document was missing or invalid.
|
||||
/// The CLI exited but its Observation v1 stream was missing or invalid.
|
||||
CoreProtocol {
|
||||
detail: String,
|
||||
},
|
||||
@@ -136,7 +145,9 @@ impl ViewError {
|
||||
ViewError::AnalysisFailed { .. } => "view.analysis_failed",
|
||||
ViewError::SourceMismatch { .. } => "view.source_mismatch",
|
||||
ViewError::SourceSpanInvalid { .. } => "view.source_span_invalid",
|
||||
ViewError::TraceStale { .. } => "view.trace_stale",
|
||||
ViewError::ObservationInvalid { .. } => "view.observation_invalid",
|
||||
ViewError::ObservationStale { .. } => "view.observation_stale",
|
||||
ViewError::CoreOptionRejected { .. } => "view.core_option_rejected",
|
||||
ViewError::RunDenied { .. } => "view.run_denied",
|
||||
ViewError::PathForbidden { .. } => "view.path_forbidden",
|
||||
ViewError::BindDenied { .. } => "view.bind_denied",
|
||||
@@ -170,6 +181,8 @@ impl ViewError {
|
||||
| ViewError::PathForbidden { .. }
|
||||
| ViewError::BindDenied { .. }
|
||||
| ViewError::SourceSpanInvalid { .. }
|
||||
| ViewError::ObservationInvalid { .. }
|
||||
| ViewError::CoreOptionRejected { .. }
|
||||
| ViewError::Unsupported { .. }
|
||||
| ViewError::RunInvalid { .. }
|
||||
| ViewError::NoEntryFunction { .. }
|
||||
@@ -208,7 +221,11 @@ impl ViewError {
|
||||
"view.analysis_failed" => "Core 静态检查失败;正文仍可阅读,语义标注已撤销。",
|
||||
"view.source_mismatch" => "当前源码与 Analysis 字节摘要不一致。",
|
||||
"view.source_span_invalid" => "语义位置超出源码或不在 UTF-8 边界。",
|
||||
"view.trace_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。",
|
||||
"view.observation_invalid" => "运行观察事件无效或不符合当前协议,已拒绝展示。",
|
||||
"view.observation_stale" => "运行结果与当前 Analysis 不匹配,已标记为过期。",
|
||||
"view.core_option_rejected" => {
|
||||
"冻结核心在启动前拒绝了该选项组合( exit 2 );View 不会去掉参数重试。"
|
||||
}
|
||||
"view.run_denied" => "运行请求未获授权或被拒绝。",
|
||||
"view.path_forbidden" => "请求的路径超出允许的项目根目录。",
|
||||
"view.bind_denied" => "拒绝绑定该网络地址。",
|
||||
@@ -226,7 +243,7 @@ impl ViewError {
|
||||
"view.run_busy" => "已有一次运行正在进行;本版本每个 View 服务只允许一个任务。",
|
||||
"view.run_conflict" => "同一客户端请求 ID 携带了不同内容,拒绝执行。",
|
||||
"view.run_not_found" => "运行任务不存在、已过期或不属于当前会话。",
|
||||
"view.core_protocol" => "冻结核心退出但未给出合法的 --json 结果。",
|
||||
"view.core_protocol" => "冻结核心退出但未给出合法的 Observation v1 事件流。",
|
||||
"view.sse_busy" => "该运行任务的 SSE 观察连接超过上限,请稍后重试。",
|
||||
"view.output_limit" => "执行输出超过 View 的接收上限,已停止接收。",
|
||||
"view.io" => "本地 I/O 失败。",
|
||||
@@ -264,7 +281,9 @@ impl ViewError {
|
||||
| ViewError::ProtocolIncompatible { detail }
|
||||
| ViewError::AnalysisFailed { detail }
|
||||
| ViewError::SourceSpanInvalid { detail }
|
||||
| ViewError::TraceStale { detail }
|
||||
| ViewError::ObservationInvalid { detail }
|
||||
| ViewError::ObservationStale { detail }
|
||||
| ViewError::CoreOptionRejected { detail }
|
||||
| ViewError::RunDenied { detail }
|
||||
| ViewError::PathForbidden { detail }
|
||||
| ViewError::BindDenied { detail }
|
||||
|
||||
+641
-599
File diff suppressed because it is too large.
Load diff
+32
-13
@@ -1,8 +1,9 @@
|
||||
//! View-owned run event log and SSE frames (`marqdo.view-run-events` v1).
|
||||
//!
|
||||
//! This is View's own protocol, not a CLI protocol (RFC-VIEW-0002 §6.4). It
|
||||
//! only carries four event types and a bounded, sequenced replay buffer; it is
|
||||
//! not an event bus and never carries token streams or per-instruction values.
|
||||
//! only carries View lifecycle frames plus already-normalized Observation v1
|
||||
//! values and a bounded, sequenced replay buffer; it is not an event bus and
|
||||
//! never carries token streams or per-instruction values.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
|
||||
@@ -54,7 +55,7 @@ impl RunState {
|
||||
RunState::Cancelled => "已取消",
|
||||
RunState::TimedOut => "超时",
|
||||
RunState::Unavailable => "不可用",
|
||||
RunState::Incomplete => "事件流不完整",
|
||||
RunState::Incomplete => "观察未完成",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,8 +101,8 @@ pub struct RunEvent {
|
||||
pub at: String,
|
||||
/// Safe parsed CLI result summary (never raw HTML/innerHTML material).
|
||||
pub result: Option<serde_json::Value>,
|
||||
/// Verified Trace v2 summary, only after digest/binding checks.
|
||||
pub trace: Option<serde_json::Value>,
|
||||
/// Verified Observation v1 summary, only after digest/binding checks.
|
||||
pub observation_summary: Option<serde_json::Value>,
|
||||
/// `{code, message}` for terminal failures.
|
||||
pub error: Option<serde_json::Value>,
|
||||
pub observation: Option<serde_json::Value>,
|
||||
@@ -120,8 +121,8 @@ impl RunEvent {
|
||||
if let Some(result) = &self.result {
|
||||
data["result"] = result.clone();
|
||||
}
|
||||
if let Some(trace) = &self.trace {
|
||||
data["trace"] = trace.clone();
|
||||
if let Some(summary) = &self.observation_summary {
|
||||
data["observation_summary"] = summary.clone();
|
||||
}
|
||||
if let Some(error) = &self.error {
|
||||
data["error"] = error.clone();
|
||||
@@ -188,7 +189,7 @@ impl EventLog {
|
||||
state,
|
||||
at: utc_now(),
|
||||
result: None,
|
||||
trace: None,
|
||||
observation_summary: None,
|
||||
error: None,
|
||||
observation: None,
|
||||
};
|
||||
@@ -233,11 +234,11 @@ impl EventLog {
|
||||
pub fn publish_complete(
|
||||
&mut self,
|
||||
result: serde_json::Value,
|
||||
trace: Option<serde_json::Value>,
|
||||
observation_summary: Option<serde_json::Value>,
|
||||
) -> RunEvent {
|
||||
let mut event = self.next_event(EventKind::Complete, RunState::Succeeded);
|
||||
event.result = Some(result);
|
||||
event.trace = trace;
|
||||
event.observation_summary = observation_summary;
|
||||
self.record(event)
|
||||
}
|
||||
|
||||
@@ -247,7 +248,7 @@ impl EventLog {
|
||||
code: &str,
|
||||
message: &str,
|
||||
result: Option<serde_json::Value>,
|
||||
trace: Option<serde_json::Value>,
|
||||
observation_summary: Option<serde_json::Value>,
|
||||
) -> RunEvent {
|
||||
let mut event = self.next_event(EventKind::Error, state);
|
||||
event.error = Some(serde_json::json!({
|
||||
@@ -255,7 +256,7 @@ impl EventLog {
|
||||
"message": message,
|
||||
}));
|
||||
event.result = result;
|
||||
event.trace = trace;
|
||||
event.observation_summary = observation_summary;
|
||||
self.record(event)
|
||||
}
|
||||
|
||||
@@ -291,7 +292,7 @@ impl EventLog {
|
||||
state: self.last_state,
|
||||
at: utc_now(),
|
||||
result: None,
|
||||
trace: None,
|
||||
observation_summary: None,
|
||||
error: None,
|
||||
observation: None,
|
||||
}
|
||||
@@ -430,6 +431,24 @@ mod tests {
|
||||
assert!(subscription.replay[0].result.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_frame_carries_observation_summary_not_trace() {
|
||||
let mut log = EventLog::new();
|
||||
log.publish_observation(serde_json::json!({
|
||||
"kind": "stdout.chunk",
|
||||
"seq": 13,
|
||||
"run_id": "core-run",
|
||||
}));
|
||||
let event = log.publish_complete(
|
||||
serde_json::json!({"success": true}),
|
||||
Some(serde_json::json!({"status": "verified"})),
|
||||
);
|
||||
let data = event.data("run-1");
|
||||
assert!(data.get("trace").is_none());
|
||||
assert_eq!(data["observation_summary"]["status"], "verified");
|
||||
assert_eq!(data["result"]["success"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utc_formatting_is_stable() {
|
||||
assert_eq!(format_utc(0), "1970-01-01T00:00:00Z");
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
//! A bounded projection retained only inside an existing terminal Job.
|
||||
//!
|
||||
//! The overlay is bound to the verified Observation v1 terminal (run id, state,
|
||||
//! capture level, truncation) and to the exact pre-run Analysis bytes; it never
|
||||
//! re-parses the CLI JSON and never widens the value consent the user gave.
|
||||
|
||||
use crate::execution::events::RunState;
|
||||
use crate::execution::request::ExecutionPlan;
|
||||
use crate::protocol::observation_v1::{EventCounts, RunProjection};
|
||||
use crate::reader::assemble::StaticDocument;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -16,11 +21,13 @@ pub struct TerminalExportCandidate {
|
||||
pub project_root_id: String,
|
||||
pub module_id: String,
|
||||
pub analysis_digest: String,
|
||||
/// Analysis revision carried by the exact pre-run artifact (3).
|
||||
pub analysis_version: u32,
|
||||
pub source_sha256: String,
|
||||
pub lock_digest: String,
|
||||
pub media: BTreeMap<String, String>,
|
||||
pub core_run_id: String,
|
||||
/// Observation v1 run id (`run.id`/`run_id`).
|
||||
pub observation_run_id: String,
|
||||
pub core_version: String,
|
||||
pub mode: String,
|
||||
pub terminal_at: String,
|
||||
@@ -30,8 +37,9 @@ pub struct TerminalExportCandidate {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub arguments: Vec<(String, String)>,
|
||||
pub trace_status: String,
|
||||
pub trace_counts: Option<BTreeMap<String, u64>>,
|
||||
pub observation_status: String,
|
||||
pub observation_counts: Option<BTreeMap<String, u64>>,
|
||||
pub capture_level: String,
|
||||
pub output_complete: bool,
|
||||
pub result_complete: bool,
|
||||
pub observation_truncated: bool,
|
||||
@@ -43,14 +51,21 @@ impl TerminalExportCandidate {
|
||||
plan: &ExecutionPlan,
|
||||
document: &StaticDocument,
|
||||
result: &Value,
|
||||
trace: Option<&Value>,
|
||||
observation: Option<&RunProjection>,
|
||||
) -> Option<Self> {
|
||||
if !matches!(state, RunState::Succeeded | RunState::Failed)
|
||||
if !matches!(state, RunState::Succeeded | RunState::Failed) {
|
||||
return None;
|
||||
}
|
||||
let observation = observation?;
|
||||
if !observation.source_verified
|
||||
|| result.get("source_verified").and_then(Value::as_bool) != Some(true)
|
||||
|| result.get("event_protocol").and_then(Value::as_u64) != Some(1)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let observation_status = result.get("observation_status").and_then(Value::as_str)?;
|
||||
if !matches!(observation_status, "verified" | "truncated") {
|
||||
return None;
|
||||
}
|
||||
let projection = &document.verified.projection;
|
||||
let function = projection
|
||||
.functions
|
||||
@@ -58,48 +73,19 @@ impl TerminalExportCandidate {
|
||||
.find(|function| function.id == plan.function_id)?;
|
||||
let (stdout, stdout_complete) = bounded_text(result["stdout"].as_str());
|
||||
let (stderr, stderr_complete) = bounded_text(result["stderr"].as_str());
|
||||
let wire = &result["value"];
|
||||
let value_is_scalar = matches!(
|
||||
wire["type"].as_str(),
|
||||
Some("int" | "float" | "bool" | "unit" | "none" | "text")
|
||||
);
|
||||
let value_text = match state {
|
||||
RunState::Succeeded if value_is_scalar => {
|
||||
result["value_text"].as_str().map(str::to_string)
|
||||
}
|
||||
RunState::Succeeded if crate::protocol::value_wire_v1::transferable(wire) => {
|
||||
Some(wire.to_string())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let (value, value_complete) = match value_text {
|
||||
Some(text) => {
|
||||
let (text, complete) = bounded_text(Some(&text));
|
||||
(Some(text), complete)
|
||||
}
|
||||
None => (None, false),
|
||||
};
|
||||
let trace_status = match &result["trace_status"] {
|
||||
Value::String(status) if status == "verified" => {
|
||||
if trace.is_some_and(|trace| !trace["truncated"].is_null()) {
|
||||
"truncated"
|
||||
} else {
|
||||
"verified"
|
||||
// Only a public scalar result value is exportable without an extra
|
||||
// sensitive-output confirmation; container/text values stay omitted.
|
||||
let (value, value_complete, value_is_public_scalar) =
|
||||
match observation.result_value.as_ref() {
|
||||
Some(run) if public_scalar_type(&run.ty) => {
|
||||
let (text, complete) = bounded_text(Some(run.display.as_str()));
|
||||
(Some(text), complete, true)
|
||||
}
|
||||
}
|
||||
Value::String(status) if status == "invalid" => "invalid",
|
||||
_ => "unavailable",
|
||||
};
|
||||
let trace_counts = trace
|
||||
.filter(|trace| trace["status"] == "verified")
|
||||
.and_then(|trace| trace["counts"].as_object())
|
||||
.map(|counts| {
|
||||
counts
|
||||
.iter()
|
||||
.filter_map(|(kind, count)| Some((kind.clone(), count.as_u64()?)))
|
||||
.collect()
|
||||
});
|
||||
let value_is_public_scalar = value_is_scalar && wire["type"] != "text";
|
||||
Some(_) => (None, false, false),
|
||||
None => (None, true, false),
|
||||
};
|
||||
let observation_truncated = observation.truncated.is_some();
|
||||
let observation_counts = Some(counts_map(&observation.counts));
|
||||
Some(Self {
|
||||
document: plan.document.to_string(),
|
||||
function_id: function.id.clone(),
|
||||
@@ -111,7 +97,7 @@ impl TerminalExportCandidate {
|
||||
source_sha256: document.source_sha256.clone(),
|
||||
lock_digest: projection.lock_digest.clone(),
|
||||
media: document.media_digests.clone(),
|
||||
core_run_id: result["core_run_id"].as_str()?.to_string(),
|
||||
observation_run_id: observation.run_id.clone(),
|
||||
core_version: projection.producer_version.clone(),
|
||||
mode: plan.mode.as_str().to_string(),
|
||||
terminal_at: crate::execution::events::utc_now(),
|
||||
@@ -121,13 +107,16 @@ impl TerminalExportCandidate {
|
||||
stdout,
|
||||
stderr,
|
||||
arguments: plan.arguments.clone(),
|
||||
trace_status: trace_status.to_string(),
|
||||
trace_counts,
|
||||
observation_status: observation_status.to_string(),
|
||||
observation_counts,
|
||||
capture_level: observation.capture_level.clone(),
|
||||
output_complete: result["output_complete"].as_bool() == Some(true)
|
||||
&& stdout_complete
|
||||
&& stderr_complete,
|
||||
result_complete: state == RunState::Succeeded && value_complete,
|
||||
observation_truncated: result["observation_truncated"].as_bool().unwrap_or(false),
|
||||
result_complete: state == RunState::Succeeded
|
||||
&& !observation_truncated
|
||||
&& value_complete,
|
||||
observation_truncated,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -140,8 +129,9 @@ impl TerminalExportCandidate {
|
||||
"stdout_bytes": self.stdout.len(),
|
||||
"stderr_bytes": self.stderr.len(),
|
||||
"arguments_count": self.arguments.len(),
|
||||
"trace_summary": self.trace_counts.is_some(),
|
||||
"trace_status": self.trace_status,
|
||||
"observation_summary": self.observation_counts.is_some(),
|
||||
"observation_status": self.observation_status,
|
||||
"capture_level": self.capture_level,
|
||||
"observation_truncated": self.observation_truncated,
|
||||
"output_complete": self.output_complete,
|
||||
"result_complete": self.result_complete,
|
||||
@@ -149,6 +139,31 @@ impl TerminalExportCandidate {
|
||||
}
|
||||
}
|
||||
|
||||
fn public_scalar_type(ty: &str) -> bool {
|
||||
matches!(
|
||||
ty.to_ascii_lowercase().as_str(),
|
||||
"int" | "float" | "bool" | "unit" | "none"
|
||||
)
|
||||
}
|
||||
|
||||
fn counts_map(counts: &EventCounts) -> BTreeMap<String, u64> {
|
||||
[
|
||||
("total", counts.total()),
|
||||
("call_enter", counts.call_enter),
|
||||
("call_exit", counts.call_exit),
|
||||
("branch_eval", counts.branch_eval),
|
||||
("loop_iteration", counts.loop_iteration),
|
||||
("control_break", counts.control_break),
|
||||
("control_continue", counts.control_continue),
|
||||
("return", counts.return_events),
|
||||
("effect", counts.effect),
|
||||
("other", counts.other),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(kind, count)| (kind.to_string(), count as u64))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bounded_text(value: Option<&str>) -> (String, bool) {
|
||||
let Some(text) = value else {
|
||||
return (String::new(), true);
|
||||
@@ -159,3 +174,26 @@ fn bounded_text(value: Option<&str>) -> (String, bool) {
|
||||
}
|
||||
(text[..end].to_string(), end == text.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn public_scalar_types_exclude_text_and_containers() {
|
||||
for accepted in ["Int", "float", "Bool", "Unit", "none"] {
|
||||
assert!(public_scalar_type(accepted), "{accepted}");
|
||||
}
|
||||
for rejected in ["Text", "List", "Map", "Table", "Memory", "Resource"] {
|
||||
assert!(!public_scalar_type(rejected), "{rejected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_text_never_splits_utf8() {
|
||||
let text = "é".repeat(MAX_TEXT);
|
||||
let (bounded, complete) = bounded_text(Some(&text));
|
||||
assert!(bounded.is_char_boundary(bounded.len()));
|
||||
assert!(!complete);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
//! - `request`: schema/target/parameter/mode/grant validation
|
||||
//! - `process`: the one cancellable Core process adapter with bounded capture
|
||||
//! - `events`: bounded, sequenced View-owned run events and SSE frames
|
||||
//! - `controller`: single-job lifecycle, dedupe, cancel, Trace binding
|
||||
//! - `controller`: single-job lifecycle, dedupe, cancel, Observation v1 binding
|
||||
|
||||
pub mod controller;
|
||||
pub mod events;
|
||||
|
||||
+103
-40
@@ -1,14 +1,14 @@
|
||||
//! Validation of the two-phase explicit run request (RFC-VIEW-0002 §6.3).
|
||||
//!
|
||||
//! The browser never sends a command: it sends a document, a target selected
|
||||
//! from Analysis v2, constant parameter expressions, the exact Analysis digest
|
||||
//! from Analysis v3, constant parameter expressions, the exact Analysis digest
|
||||
//! it rendered, a mode and (for project mode) explicit fs globs. Everything is
|
||||
//! re-validated here and finally by the Core itself; the client cannot inject
|
||||
//! cwd, flags, a binary path or shell text.
|
||||
|
||||
use crate::core_client::Grants;
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::protocol::analysis_v2::SemanticProjection;
|
||||
use crate::protocol::analysis_v3::SemanticProjection;
|
||||
use crate::reader::source::SafeRelativePath;
|
||||
use serde::Deserialize;
|
||||
|
||||
@@ -371,7 +371,7 @@ fn validate_glob(glob: &str) -> ViewResult<()> {
|
||||
/// first, then a unique local name. No fallback to any other function.
|
||||
fn resolve_main(
|
||||
projection: &SemanticProjection,
|
||||
) -> Option<&crate::protocol::analysis_v2::SemanticFunction> {
|
||||
) -> Option<&crate::protocol::analysis_v3::SemanticFunction> {
|
||||
projection
|
||||
.functions
|
||||
.iter()
|
||||
@@ -401,7 +401,7 @@ fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str
|
||||
canonical == local_name
|
||||
}
|
||||
|
||||
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||
/// Analysis v3 function ids are `<module id>::<canonical name>`.
|
||||
pub fn canonical_name(function_id: &str, module_id: &str) -> String {
|
||||
function_id
|
||||
.strip_prefix(&format!("{module_id}::"))
|
||||
@@ -456,44 +456,107 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn projection() -> SemanticProjection {
|
||||
use crate::protocol::analysis_v3::{
|
||||
DocumentNode, FunctionParam, FunctionSignature, ModuleSummary, SemanticFunction,
|
||||
};
|
||||
use crate::reader::source::{sha256_hex, SourceSpan};
|
||||
|
||||
let module_id = "root:t@0.1.0::index.mq.md";
|
||||
let source = "x".repeat(200);
|
||||
let digest = crate::reader::source::sha256_hex(source.as_bytes());
|
||||
let analysis = serde_json::json!({
|
||||
"schema": "marqdo.analysis",
|
||||
"schema_version": 2,
|
||||
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
|
||||
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
|
||||
"modules": [{
|
||||
"id": "root:t@0.1.0::index.mq.md",
|
||||
"package_instance_id": "root:t@0.1.0",
|
||||
"relative_path": "index.mq.md",
|
||||
"source_digest": digest,
|
||||
"units": [],
|
||||
"functions": [
|
||||
{"id": "root:t@0.1.0::index.mq.md::main", "unit_id": "u1", "local_name": "main",
|
||||
"namespace": null, "span": {"start": 0, "end": 10}, "heading_span": {"start": 0, "end": 10},
|
||||
"signature": {"kind": "inferred", "params": []}, "body": [], "effects": ["unknown"]},
|
||||
{"id": "root:t@0.1.0::index.mq.md::N.f", "unit_id": "u2", "local_name": "f",
|
||||
"namespace": "N", "span": {"start": 20, "end": 30}, "heading_span": {"start": 20, "end": 30},
|
||||
"signature": {"kind": "explicit", "params": [
|
||||
{"name": "n", "required": true, "type": "Int", "default": null, "span": null}
|
||||
]}, "body": [], "effects": ["unknown"]}
|
||||
],
|
||||
"imports": [], "references": [], "calls": [], "resources": []
|
||||
let source_digest = sha256_hex(source.as_bytes());
|
||||
SemanticProjection {
|
||||
schema_version: 3,
|
||||
analysis_sha256: "a".repeat(64),
|
||||
analysis_digest: format!("sha256:{}", "a".repeat(64)),
|
||||
producer_version: "3.0.0-rc.4".to_string(),
|
||||
markdown_profile: "marqdo.md.v1".to_string(),
|
||||
project_root_id: "root:t@0.1.0".to_string(),
|
||||
identity_kind: "manifest".to_string(),
|
||||
entry_module_id: module_id.to_string(),
|
||||
lock_digest: String::new(),
|
||||
manifest_digest: String::new(),
|
||||
stdlib_version: None,
|
||||
stdlib_digest: None,
|
||||
stdlib_instance_id: None,
|
||||
extensions: Vec::new(),
|
||||
module_id: module_id.to_string(),
|
||||
package_instance_id: "root:t@0.1.0".to_string(),
|
||||
relative_path: "index.mq.md".to_string(),
|
||||
source_digest: source_digest.clone(),
|
||||
source: source.clone(),
|
||||
document: DocumentNode {
|
||||
kind: "document".to_string(),
|
||||
span: SourceSpan::new(0, source.len() as u64),
|
||||
children: Vec::new(),
|
||||
literal: None,
|
||||
level: None,
|
||||
setext: None,
|
||||
ordered: None,
|
||||
start: None,
|
||||
tight: None,
|
||||
task: None,
|
||||
ticks: None,
|
||||
fenced: None,
|
||||
info: None,
|
||||
display: None,
|
||||
url: None,
|
||||
title: None,
|
||||
alignments: None,
|
||||
header: None,
|
||||
tag: None,
|
||||
},
|
||||
anchors: Vec::new(),
|
||||
units: Vec::new(),
|
||||
functions: vec![
|
||||
SemanticFunction {
|
||||
id: format!("{module_id}::main"),
|
||||
unit_id: "u1".to_string(),
|
||||
local_name: "main".to_string(),
|
||||
namespace: None,
|
||||
span: SourceSpan::new(0, 10),
|
||||
heading_span: SourceSpan::new(0, 10),
|
||||
signature: FunctionSignature {
|
||||
kind: "inferred".to_string(),
|
||||
params: Vec::new(),
|
||||
},
|
||||
effects: vec!["unknown".to_string()],
|
||||
statements: Vec::new(),
|
||||
},
|
||||
SemanticFunction {
|
||||
id: format!("{module_id}::N.f"),
|
||||
unit_id: "u2".to_string(),
|
||||
local_name: "f".to_string(),
|
||||
namespace: Some("N".to_string()),
|
||||
span: SourceSpan::new(20, 30),
|
||||
heading_span: SourceSpan::new(20, 30),
|
||||
signature: FunctionSignature {
|
||||
kind: "explicit".to_string(),
|
||||
params: vec![FunctionParam {
|
||||
name: "n".to_string(),
|
||||
ty: Some("Int".to_string()),
|
||||
required: true,
|
||||
default: None,
|
||||
span: SourceSpan::new(24, 25),
|
||||
}],
|
||||
},
|
||||
effects: vec!["unknown".to_string()],
|
||||
statements: Vec::new(),
|
||||
},
|
||||
],
|
||||
resources: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
references: Vec::new(),
|
||||
calls: Vec::new(),
|
||||
diagnostics: Vec::new(),
|
||||
warnings: Vec::new(),
|
||||
modules: vec![ModuleSummary {
|
||||
id: module_id.to_string(),
|
||||
package_instance_id: "root:t@0.1.0".to_string(),
|
||||
relative_path: "index.mq.md".to_string(),
|
||||
source_digest,
|
||||
source,
|
||||
}],
|
||||
"diagnostics": []
|
||||
})
|
||||
.to_string();
|
||||
let source = "x".repeat(200);
|
||||
let index = crate::reader::source::SourceIndex::new(&source);
|
||||
crate::protocol::analysis_v2::verify_analysis(
|
||||
analysis.to_string().as_bytes(),
|
||||
&source,
|
||||
&index,
|
||||
"index.mq.md",
|
||||
)
|
||||
.map(|verified| verified.projection)
|
||||
.unwrap_or_else(|err| panic!("fixture analysis must verify: {err}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+39
-6
@@ -200,13 +200,30 @@ fn build_site(
|
||||
let mut manifest = serde_json::json!({
|
||||
"schema": MANIFEST_SCHEMA,
|
||||
"schema_version": 1,
|
||||
"view": {"name": "marqdo-view", "version": env!("CARGO_PKG_VERSION")},
|
||||
"compatibility": {
|
||||
"view": {
|
||||
"name": "marqdo-view",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"binary_sha256": current_view_sha256(),
|
||||
},
|
||||
"producers": {
|
||||
"view": {
|
||||
"name": "marqdo-view",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"binary_sha256": current_view_sha256(),
|
||||
},
|
||||
"cli": match context.core() {
|
||||
Some(core) => serde_json::json!({
|
||||
"version": entry_model.core_version,
|
||||
"binary_sha256": sha256_file(core.bin()),
|
||||
}),
|
||||
None => serde_json::Value::Null,
|
||||
},
|
||||
},
|
||||
"requires": {
|
||||
"marqdo": crate::protocol::tool_v1::PRODUCT_RANGE,
|
||||
"tool_protocol": crate::protocol::tool_v1::TOOL_PROTOCOL,
|
||||
"analysis": crate::protocol::tool_v1::ANALYSIS_PROTOCOL,
|
||||
"analysis_supported": crate::protocol::tool_v1::ANALYSIS_PROTOCOLS,
|
||||
"trace": crate::protocol::tool_v1::TRACE_PROTOCOL,
|
||||
"api_revision": crate::protocol::tool_v1::API_REVISION,
|
||||
"analysis": crate::protocol::tool_v1::ANALYSIS_REVISION,
|
||||
"observation": crate::protocol::tool_v1::OBSERVATION_REVISION,
|
||||
"markdown_profile": "marqdo.md.v1",
|
||||
},
|
||||
"core_version": entry_model.core_version,
|
||||
@@ -240,6 +257,22 @@ fn build_site(
|
||||
})
|
||||
}
|
||||
|
||||
/// Lowercase hex SHA-256 of the running View executable, used to bind the
|
||||
/// exported manifest to the exact producer binary. Never a machine path.
|
||||
fn current_view_sha256() -> String {
|
||||
let Ok(exe) = std::env::current_exe() else {
|
||||
return "unavailable".to_string();
|
||||
};
|
||||
sha256_file(&exe)
|
||||
}
|
||||
|
||||
fn sha256_file(path: &std::path::Path) -> String {
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => sha256_hex(&bytes),
|
||||
Err(_) => "unavailable".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SnapshotArchive {
|
||||
pub file: std::fs::File,
|
||||
pub len: usize,
|
||||
|
||||
+13
-11
@@ -3,11 +3,12 @@
|
||||
|
||||
use crate::{
|
||||
execution::{events::RunState, export_candidate::TerminalExportCandidate},
|
||||
protocol::tool_v1,
|
||||
reader::{
|
||||
assemble::DocumentService,
|
||||
media,
|
||||
model::PresentationModel,
|
||||
snapshot::{ExportResultOverlay, SnapshotExecution, SnapshotProtocols, SnapshotSource},
|
||||
snapshot::{ExportResultOverlay, SnapshotContracts, SnapshotExecution, SnapshotSource},
|
||||
source::{sha256_hex, SafeRelativePath},
|
||||
},
|
||||
ViewError, ViewResult,
|
||||
@@ -44,7 +45,7 @@ struct Include {
|
||||
result_value: bool,
|
||||
stdout: bool,
|
||||
stderr: bool,
|
||||
trace_summary: bool,
|
||||
observation_summary: bool,
|
||||
arguments: bool,
|
||||
}
|
||||
|
||||
@@ -113,7 +114,7 @@ impl ExportSelection {
|
||||
|| !candidate.output_complete
|
||||
|| !candidate.result_complete
|
||||
|| candidate.observation_truncated
|
||||
|| candidate.trace_status == "truncated")
|
||||
|| candidate.observation_status == "truncated")
|
||||
&& !self.confirm_partial
|
||||
{
|
||||
return Err(invalid());
|
||||
@@ -147,13 +148,14 @@ impl ExportSelection {
|
||||
},
|
||||
execution: SnapshotExecution {
|
||||
included: true,
|
||||
core_run_id: candidate.core_run_id.clone(),
|
||||
core_run_id: candidate.observation_run_id.clone(),
|
||||
target: candidate.function_id.clone(),
|
||||
core_version: candidate.core_version.clone(),
|
||||
status: candidate.state.data_value(),
|
||||
terminal_at: candidate.terminal_at.clone(),
|
||||
source_verified: true,
|
||||
trace_status: candidate.trace_status.clone(),
|
||||
observation_status: candidate.observation_status.clone(),
|
||||
capture_level: candidate.capture_level.clone(),
|
||||
result_complete: candidate.result_complete,
|
||||
output_complete: candidate.output_complete,
|
||||
observation_truncated: candidate.observation_truncated,
|
||||
@@ -163,10 +165,10 @@ impl ExportSelection {
|
||||
"omitted"
|
||||
},
|
||||
mode: candidate.mode.clone(),
|
||||
core_protocol: SnapshotProtocols {
|
||||
contracts: SnapshotContracts {
|
||||
api_revision: tool_v1::API_REVISION,
|
||||
analysis: candidate.analysis_version,
|
||||
trace: 2,
|
||||
events: 1,
|
||||
observation: tool_v1::OBSERVATION_REVISION,
|
||||
},
|
||||
},
|
||||
label: candidate.label.clone(),
|
||||
@@ -177,10 +179,10 @@ impl ExportSelection {
|
||||
.flatten(),
|
||||
stdout: self.include.stdout.then(|| candidate.stdout.clone()),
|
||||
stderr: self.include.stderr.then(|| candidate.stderr.clone()),
|
||||
trace_counts: self
|
||||
observation_counts: self
|
||||
.include
|
||||
.trace_summary
|
||||
.then(|| candidate.trace_counts.clone())
|
||||
.observation_summary
|
||||
.then(|| candidate.observation_counts.clone())
|
||||
.flatten(),
|
||||
arguments: self.include.arguments.then(|| candidate.arguments.clone()),
|
||||
};
|
||||
|
||||
@@ -1,952 +0,0 @@
|
||||
//! Analysis v2 validation and static semantic projection.
|
||||
//!
|
||||
//! This module is the only consumer of the public Analysis JSON. It verifies
|
||||
//! protocol identity first, then projects functions/units/statements/diagnostics
|
||||
//! into View-owned types with **validated** source spans. A span that is out of
|
||||
//! range or not on a UTF-8 boundary is dropped with an explicit View warning
|
||||
//! instead of being pointed at nearby text (RFC-VIEW-0001 §4.3, §8.2).
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
/// Stable DOM identity for one source-bound annotation, local to this document
|
||||
/// and run. It is not a cross-edit identity.
|
||||
pub fn source_id(module_id: &str, span: SourceSpan, kind: &str) -> String {
|
||||
let material = format!("{module_id}\0{}:{}:{}", span.start, span.end, kind);
|
||||
sha256_hex(material.as_bytes())[..16].to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UnitKind {
|
||||
Root,
|
||||
Namespace,
|
||||
Function,
|
||||
Knowledge,
|
||||
Section,
|
||||
Other,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticUnit {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub level: u8,
|
||||
pub kind: UnitKind,
|
||||
pub function: Option<String>,
|
||||
pub span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionParam {
|
||||
pub name: String,
|
||||
pub ty: String,
|
||||
pub required: bool,
|
||||
pub default: Option<String>,
|
||||
pub span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FunctionSignature {
|
||||
pub kind: String,
|
||||
pub params: Vec<FunctionParam>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticFunction {
|
||||
pub id: String,
|
||||
pub unit_id: String,
|
||||
pub local_name: String,
|
||||
pub namespace: Option<String>,
|
||||
pub span: SourceSpan,
|
||||
pub heading_span: SourceSpan,
|
||||
pub signature: FunctionSignature,
|
||||
pub effects: Vec<String>,
|
||||
pub statements: Vec<SemanticStatement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StatementKind {
|
||||
Assign,
|
||||
Expression,
|
||||
Branch,
|
||||
Loop,
|
||||
Return,
|
||||
Break,
|
||||
Continue,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl StatementKind {
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
StatementKind::Assign => "赋值",
|
||||
StatementKind::Expression => "表达式",
|
||||
StatementKind::Branch => "条件分支",
|
||||
StatementKind::Loop => "循环",
|
||||
StatementKind::Return => "返回",
|
||||
StatementKind::Break => "跳出循环",
|
||||
StatementKind::Continue => "继续循环",
|
||||
StatementKind::Other => "语句",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn data_value(&self) -> &'static str {
|
||||
match self {
|
||||
StatementKind::Assign => "assign",
|
||||
StatementKind::Expression => "expression",
|
||||
StatementKind::Branch => "branch",
|
||||
StatementKind::Loop => "loop",
|
||||
StatementKind::Return => "return",
|
||||
StatementKind::Break => "break",
|
||||
StatementKind::Continue => "continue",
|
||||
StatementKind::Other => "other",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticStatement {
|
||||
pub kind: StatementKind,
|
||||
/// Header span for control flow, payload span for simple statements.
|
||||
pub span: SourceSpan,
|
||||
/// For `if` arms and `while` conditions: the condition text span as the
|
||||
/// compiler recorded it.
|
||||
pub condition_span: Option<SourceSpan>,
|
||||
pub arms: Vec<SemanticArm>,
|
||||
pub body: Vec<SemanticStatement>,
|
||||
/// Target name for assignments (local name or `index` form), for static
|
||||
/// outline display only. Never a runtime value.
|
||||
pub target: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticArm {
|
||||
pub span: Option<SourceSpan>,
|
||||
pub condition_span: Option<SourceSpan>,
|
||||
pub body: Vec<SemanticStatement>,
|
||||
}
|
||||
|
||||
impl SemanticFunction {
|
||||
/// Depth-first statement walk in source order.
|
||||
pub fn flattened_statements(&self) -> Vec<&SemanticStatement> {
|
||||
let mut out = Vec::new();
|
||||
for statement in &self.statements {
|
||||
collect_statements(statement, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_statements<'a>(statement: &'a SemanticStatement, out: &mut Vec<&'a SemanticStatement>) {
|
||||
out.push(statement);
|
||||
for arm in &statement.arms {
|
||||
for child in &arm.body {
|
||||
collect_statements(child, out);
|
||||
}
|
||||
}
|
||||
for child in &statement.body {
|
||||
collect_statements(child, out);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaticResource {
|
||||
pub id: String,
|
||||
pub kind: String,
|
||||
pub span: SourceSpan,
|
||||
pub content_digest: String,
|
||||
pub language: Option<String>,
|
||||
pub display: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaticImport {
|
||||
pub alias: String,
|
||||
pub target: String,
|
||||
pub resolved: Option<String>,
|
||||
pub span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaticReference {
|
||||
pub url: String,
|
||||
pub span: SourceSpan,
|
||||
pub state: String,
|
||||
pub target_module: Option<String>,
|
||||
pub target_unit: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StaticCall {
|
||||
pub state: String,
|
||||
pub target: Option<String>,
|
||||
pub function: Option<String>,
|
||||
pub span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreDiagnostic {
|
||||
pub module: Option<String>,
|
||||
pub relative_path: Option<String>,
|
||||
pub span: Option<SourceSpan>,
|
||||
pub line: Option<u64>,
|
||||
pub column: Option<u64>,
|
||||
pub severity: String,
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub hints: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ViewWarning {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ModuleSummary {
|
||||
pub id: String,
|
||||
pub package_instance_id: String,
|
||||
pub relative_path: String,
|
||||
pub source_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SemanticProjection {
|
||||
pub schema_version: u32,
|
||||
pub analysis_sha256: String,
|
||||
pub analysis_digest: String,
|
||||
pub producer_version: String,
|
||||
pub markdown_profile: String,
|
||||
pub project_root_id: String,
|
||||
pub identity_kind: String,
|
||||
pub lock_digest: String,
|
||||
pub stdlib_version: Option<String>,
|
||||
pub module_id: String,
|
||||
pub package_instance_id: String,
|
||||
pub relative_path: String,
|
||||
pub source_digest: String,
|
||||
pub units: Vec<SemanticUnit>,
|
||||
pub functions: Vec<SemanticFunction>,
|
||||
pub resources: Vec<StaticResource>,
|
||||
pub imports: Vec<StaticImport>,
|
||||
pub references: Vec<StaticReference>,
|
||||
pub calls: Vec<StaticCall>,
|
||||
pub diagnostics: Vec<CoreDiagnostic>,
|
||||
pub warnings: Vec<ViewWarning>,
|
||||
pub modules: Vec<ModuleSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct VerifiedAnalysis {
|
||||
pub projection: SemanticProjection,
|
||||
}
|
||||
|
||||
impl SemanticProjection {
|
||||
pub fn unit_for_heading(&self, span: SourceSpan, level: u8) -> Option<&SemanticUnit> {
|
||||
self.units
|
||||
.iter()
|
||||
.filter(|unit| unit.level == level && unit.span.contains(span))
|
||||
.min_by_key(|unit| unit.span.len())
|
||||
}
|
||||
|
||||
pub fn function_by_heading(&self, span: SourceSpan) -> Option<&SemanticFunction> {
|
||||
self.functions
|
||||
.iter()
|
||||
.find(|function| function.heading_span == span)
|
||||
.or_else(|| {
|
||||
self.functions
|
||||
.iter()
|
||||
.find(|function| function.span.contains(span))
|
||||
})
|
||||
}
|
||||
|
||||
/// All statements of all functions, flattened in deterministic order.
|
||||
pub fn all_statements(&self) -> Vec<(&SemanticFunction, &SemanticStatement)> {
|
||||
let mut out = Vec::new();
|
||||
for function in &self.functions {
|
||||
for statement in function.flattened_statements() {
|
||||
out.push((function, statement));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The innermost statement whose span is contained in `inline_span`.
|
||||
pub fn statement_for_inline(
|
||||
&self,
|
||||
inline_span: SourceSpan,
|
||||
) -> Option<(&SemanticFunction, &SemanticStatement)> {
|
||||
self.all_statements()
|
||||
.into_iter()
|
||||
.filter(|(_, statement)| {
|
||||
statement.span.start >= inline_span.start
|
||||
&& statement.span.end <= inline_span.end
|
||||
&& !statement.span.is_empty()
|
||||
})
|
||||
.max_by_key(|(_, statement)| statement.span.start)
|
||||
}
|
||||
|
||||
pub fn resource_for_span(&self, span: SourceSpan) -> Option<&StaticResource> {
|
||||
self.resources
|
||||
.iter()
|
||||
.find(|resource| resource.span == span || resource.span.contains(span))
|
||||
}
|
||||
|
||||
pub fn reference_for_span(&self, span: SourceSpan) -> Option<&StaticReference> {
|
||||
self.references
|
||||
.iter()
|
||||
.find(|reference| reference.span == span || reference.span.contains(span))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Raw protocol types (additive fields are tolerated and ignored).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawAnalysis {
|
||||
schema: String,
|
||||
schema_version: u32,
|
||||
producer: RawProducer,
|
||||
project: RawProject,
|
||||
modules: Vec<RawModule>,
|
||||
#[serde(default)]
|
||||
diagnostics: Vec<RawDiagnostic>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawProducer {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
#[serde(default)]
|
||||
markdown_profile: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawProject {
|
||||
#[serde(default)]
|
||||
root_id: String,
|
||||
#[serde(default)]
|
||||
identity_kind: String,
|
||||
#[serde(default)]
|
||||
lock_digest: String,
|
||||
#[serde(default)]
|
||||
stdlib: Option<RawStdlib>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawStdlib {
|
||||
#[serde(default)]
|
||||
version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawModule {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
package_instance_id: String,
|
||||
#[serde(default)]
|
||||
relative_path: String,
|
||||
#[serde(default)]
|
||||
source_digest: String,
|
||||
#[serde(default)]
|
||||
units: Vec<RawUnit>,
|
||||
#[serde(default)]
|
||||
functions: Vec<RawFunction>,
|
||||
#[serde(default)]
|
||||
imports: Vec<RawImport>,
|
||||
#[serde(default)]
|
||||
references: Vec<RawReference>,
|
||||
#[serde(default)]
|
||||
calls: Vec<RawCall>,
|
||||
#[serde(default)]
|
||||
resources: Vec<RawResource>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawUnit {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
level: u8,
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
function: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawFunction {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
unit_id: String,
|
||||
#[serde(default)]
|
||||
local_name: String,
|
||||
#[serde(default)]
|
||||
namespace: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
heading_span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
signature: Option<RawSignature>,
|
||||
#[serde(default)]
|
||||
effects: Vec<String>,
|
||||
#[serde(default)]
|
||||
body: Vec<RawStatement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawSignature {
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
params: Vec<RawParam>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawParam {
|
||||
#[serde(default)]
|
||||
name: String,
|
||||
#[serde(default, rename = "type")]
|
||||
ty: Option<String>,
|
||||
#[serde(default)]
|
||||
required: bool,
|
||||
#[serde(default)]
|
||||
default: Option<Value>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawStatement {
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
condition_span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
arms: Vec<RawArm>,
|
||||
#[serde(default)]
|
||||
body: Vec<RawStatement>,
|
||||
#[serde(default)]
|
||||
target: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawArm {
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
condition_span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
body: Vec<RawStatement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawResource {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
content_digest: String,
|
||||
#[serde(default)]
|
||||
language: Option<String>,
|
||||
#[serde(default)]
|
||||
display: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawImport {
|
||||
#[serde(default)]
|
||||
alias: String,
|
||||
#[serde(default)]
|
||||
target: String,
|
||||
#[serde(default)]
|
||||
resolved: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawReference {
|
||||
#[serde(default)]
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
state: String,
|
||||
#[serde(default)]
|
||||
target_module: Option<String>,
|
||||
#[serde(default)]
|
||||
target_unit: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawCall {
|
||||
#[serde(default)]
|
||||
state: String,
|
||||
#[serde(default)]
|
||||
target: Option<String>,
|
||||
#[serde(default)]
|
||||
function: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawDiagnostic {
|
||||
#[serde(default)]
|
||||
module: Option<String>,
|
||||
#[serde(default)]
|
||||
relative_path: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
line: Option<u64>,
|
||||
#[serde(default)]
|
||||
column: Option<u64>,
|
||||
#[serde(default)]
|
||||
severity: String,
|
||||
#[serde(default)]
|
||||
code: String,
|
||||
#[serde(default)]
|
||||
message: String,
|
||||
#[serde(default)]
|
||||
hints: Vec<String>,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Validation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Verify Analysis bytes against the exact source and project the static facts.
|
||||
///
|
||||
/// Rejects protocol incompatibility and source-digest mismatch as errors; drops
|
||||
/// individual invalid spans as warnings so the prose stays readable.
|
||||
pub fn verify_analysis(
|
||||
analysis_bytes: &[u8],
|
||||
source: &str,
|
||||
source_index: &SourceIndex,
|
||||
expected_relative_path: &str,
|
||||
) -> ViewResult<VerifiedAnalysis> {
|
||||
let raw: RawAnalysis =
|
||||
serde_json::from_slice(analysis_bytes).map_err(|err| ViewError::AnalysisFailed {
|
||||
detail: format!("Analysis is not valid JSON: {err}"),
|
||||
})?;
|
||||
if raw.schema != "marqdo.analysis" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!("unexpected Analysis schema {:?}", raw.schema),
|
||||
});
|
||||
}
|
||||
if !crate::protocol::tool_v1::ANALYSIS_PROTOCOLS.contains(&raw.schema_version) {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"Analysis schema_version {} is not supported (View implements v2/v3)",
|
||||
raw.schema_version
|
||||
),
|
||||
});
|
||||
}
|
||||
if raw.producer.name != "marqdo" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"Analysis producer.name {:?} is not `marqdo`",
|
||||
raw.producer.name
|
||||
),
|
||||
});
|
||||
}
|
||||
if raw.producer.markdown_profile != "marqdo.md.v1" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"unexpected Markdown profile {:?}; this View targets marqdo.md.v1",
|
||||
raw.producer.markdown_profile
|
||||
),
|
||||
});
|
||||
}
|
||||
if raw.project.root_id.is_empty() {
|
||||
return Err(ViewError::AnalysisFailed {
|
||||
detail: "Analysis project.root_id is empty".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let actual_digest = sha256_hex(source.as_bytes());
|
||||
let module = raw
|
||||
.modules
|
||||
.iter()
|
||||
.find(|module| module.relative_path == expected_relative_path)
|
||||
.ok_or_else(|| ViewError::AnalysisFailed {
|
||||
detail: format!("Analysis has no module for {expected_relative_path}"),
|
||||
})?;
|
||||
if module.source_digest != actual_digest {
|
||||
return Err(ViewError::SourceMismatch {
|
||||
expected: module.source_digest.clone(),
|
||||
actual: actual_digest,
|
||||
});
|
||||
}
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
let mut valid_span = |span: Option<SourceSpan>, what: &str| -> Option<SourceSpan> {
|
||||
let span = span?;
|
||||
if source_index.validate_span_bytes(source.as_bytes(), span) {
|
||||
Some(span)
|
||||
} else {
|
||||
warnings.push(ViewWarning {
|
||||
code: "view.source_span_invalid".to_string(),
|
||||
message: format!("{what} 的字节区间超出源码或不在 UTF-8 边界,已跳过该标注"),
|
||||
span: Some(span),
|
||||
});
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let units: Vec<SemanticUnit> = module
|
||||
.units
|
||||
.iter()
|
||||
.filter_map(|unit| {
|
||||
let span = valid_span(unit.span, "语义单元")?;
|
||||
Some(SemanticUnit {
|
||||
id: unit.id.clone(),
|
||||
name: unit.name.clone(),
|
||||
level: unit.level,
|
||||
kind: match unit.kind.as_str() {
|
||||
"root" => UnitKind::Root,
|
||||
"namespace" => UnitKind::Namespace,
|
||||
"function" => UnitKind::Function,
|
||||
"knowledge" => UnitKind::Knowledge,
|
||||
"section" => UnitKind::Section,
|
||||
_ => UnitKind::Other,
|
||||
},
|
||||
function: unit.function.clone(),
|
||||
span,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let functions: Vec<SemanticFunction> = module
|
||||
.functions
|
||||
.iter()
|
||||
.filter_map(|function| {
|
||||
let span = valid_span(function.span, "函数范围")?;
|
||||
let heading_span = valid_span(function.heading_span, "函数标题")?;
|
||||
let statements = function
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|statement| {
|
||||
convert_statement(statement, raw.schema_version, &mut valid_span)
|
||||
})
|
||||
.collect();
|
||||
Some(SemanticFunction {
|
||||
id: function.id.clone(),
|
||||
unit_id: function.unit_id.clone(),
|
||||
local_name: function.local_name.clone(),
|
||||
namespace: function.namespace.clone(),
|
||||
span,
|
||||
heading_span,
|
||||
signature: FunctionSignature {
|
||||
kind: function
|
||||
.signature
|
||||
.as_ref()
|
||||
.map(|signature| signature.kind.clone())
|
||||
.unwrap_or_default(),
|
||||
params: function
|
||||
.signature
|
||||
.as_ref()
|
||||
.map(|signature| {
|
||||
signature
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| FunctionParam {
|
||||
name: param.name.clone(),
|
||||
ty: param.ty.clone().unwrap_or_default(),
|
||||
required: param.required,
|
||||
default: param.default.as_ref().map(compact_value),
|
||||
span: param.span.filter(|span| {
|
||||
source_index.validate_span_bytes(source.as_bytes(), *span)
|
||||
}),
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
},
|
||||
effects: function.effects.clone(),
|
||||
statements,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let resources: Vec<StaticResource> = module
|
||||
.resources
|
||||
.iter()
|
||||
.filter(|resource| matches!(resource.kind.as_str(), "formula" | "code"))
|
||||
.filter_map(|resource| {
|
||||
let span = valid_span(resource.span, "资源")?;
|
||||
Some(StaticResource {
|
||||
id: resource.id.clone(),
|
||||
kind: resource.kind.clone(),
|
||||
span,
|
||||
content_digest: resource.content_digest.clone(),
|
||||
language: resource.language.clone(),
|
||||
display: resource.display,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let imports: Vec<StaticImport> = module
|
||||
.imports
|
||||
.iter()
|
||||
.filter_map(|import| {
|
||||
Some(StaticImport {
|
||||
alias: import.alias.clone(),
|
||||
target: import.target.clone(),
|
||||
resolved: import.resolved.clone(),
|
||||
span: valid_span(import.span, "导入声明")?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let references: Vec<StaticReference> = module
|
||||
.references
|
||||
.iter()
|
||||
.filter_map(|reference| {
|
||||
Some(StaticReference {
|
||||
url: reference.url.clone(),
|
||||
state: reference.state.clone(),
|
||||
target_module: reference.target_module.clone(),
|
||||
target_unit: reference.target_unit.clone(),
|
||||
span: valid_span(reference.span, "Markdown 引用")?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let calls: Vec<StaticCall> = module
|
||||
.calls
|
||||
.iter()
|
||||
.filter_map(|call| {
|
||||
Some(StaticCall {
|
||||
state: call.state.clone(),
|
||||
target: call.target.clone(),
|
||||
function: call.function.clone(),
|
||||
span: valid_span(call.span, "调用点")?,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let diagnostics: Vec<CoreDiagnostic> = raw
|
||||
.diagnostics
|
||||
.iter()
|
||||
.map(|diagnostic| {
|
||||
let span = diagnostic
|
||||
.span
|
||||
.filter(|span| source_index.validate_span_bytes(source.as_bytes(), *span));
|
||||
CoreDiagnostic {
|
||||
module: diagnostic.module.clone(),
|
||||
relative_path: diagnostic.relative_path.clone(),
|
||||
span,
|
||||
line: diagnostic.line,
|
||||
column: diagnostic.column,
|
||||
severity: if diagnostic.severity.is_empty() {
|
||||
"error".to_string()
|
||||
} else {
|
||||
diagnostic.severity.clone()
|
||||
},
|
||||
code: diagnostic.code.clone(),
|
||||
message: diagnostic.message.clone(),
|
||||
hints: diagnostic.hints.clone(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let modules = raw
|
||||
.modules
|
||||
.iter()
|
||||
.map(|module| ModuleSummary {
|
||||
id: module.id.clone(),
|
||||
package_instance_id: module.package_instance_id.clone(),
|
||||
relative_path: module.relative_path.clone(),
|
||||
source_digest: module.source_digest.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(VerifiedAnalysis {
|
||||
projection: SemanticProjection {
|
||||
schema_version: raw.schema_version,
|
||||
analysis_sha256: sha256_hex(analysis_bytes),
|
||||
analysis_digest: sha256_prefixed(analysis_bytes),
|
||||
producer_version: raw.producer.version.clone(),
|
||||
markdown_profile: raw.producer.markdown_profile.clone(),
|
||||
project_root_id: raw.project.root_id.clone(),
|
||||
identity_kind: raw.project.identity_kind.clone(),
|
||||
lock_digest: raw.project.lock_digest.clone(),
|
||||
stdlib_version: raw.project.stdlib.as_ref().map(|s| s.version.clone()),
|
||||
module_id: module.id.clone(),
|
||||
package_instance_id: module.package_instance_id.clone(),
|
||||
relative_path: module.relative_path.clone(),
|
||||
source_digest: module.source_digest.clone(),
|
||||
units,
|
||||
functions,
|
||||
resources,
|
||||
imports,
|
||||
references,
|
||||
calls,
|
||||
diagnostics,
|
||||
warnings,
|
||||
modules,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn convert_statement(
|
||||
raw: &RawStatement,
|
||||
schema_version: u32,
|
||||
valid_span: &mut impl FnMut(Option<SourceSpan>, &str) -> Option<SourceSpan>,
|
||||
) -> Option<SemanticStatement> {
|
||||
let span = valid_span(raw.span, "语句")?;
|
||||
let kind = match raw.kind.as_str() {
|
||||
"assign" => StatementKind::Assign,
|
||||
"expression" => StatementKind::Expression,
|
||||
"branch" => StatementKind::Branch,
|
||||
"loop" => StatementKind::Loop,
|
||||
"return" => StatementKind::Return,
|
||||
"break" if schema_version == 3 => StatementKind::Break,
|
||||
"continue" if schema_version == 3 => StatementKind::Continue,
|
||||
_ => StatementKind::Other,
|
||||
};
|
||||
let body = raw
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|child| convert_statement(child, schema_version, valid_span))
|
||||
.collect();
|
||||
let arms = raw
|
||||
.arms
|
||||
.iter()
|
||||
.map(|arm| SemanticArm {
|
||||
span: valid_span(arm.span, "分支臂"),
|
||||
condition_span: valid_span(arm.condition_span, "分支条件"),
|
||||
body: arm
|
||||
.body
|
||||
.iter()
|
||||
.filter_map(|child| convert_statement(child, schema_version, valid_span))
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
Some(SemanticStatement {
|
||||
kind,
|
||||
span,
|
||||
condition_span: valid_span(raw.condition_span, "控制条件"),
|
||||
arms,
|
||||
body,
|
||||
target: raw.target.as_ref().and_then(assignment_target_label),
|
||||
})
|
||||
}
|
||||
|
||||
fn assignment_target_label(target: &Value) -> Option<String> {
|
||||
match target {
|
||||
Value::String(name) => Some(name.clone()),
|
||||
Value::Object(map) => {
|
||||
if map.get("kind").and_then(Value::as_str) == Some("index") {
|
||||
Some("索引赋值".to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_value(value: &Value) -> String {
|
||||
match value {
|
||||
Value::String(text) => text.clone(),
|
||||
other => {
|
||||
let text = other.to_string();
|
||||
if text.chars().count() > 40 {
|
||||
format!("{}…", text.chars().take(40).collect::<String>())
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn analysis(schema_version: u32, digest: &str) -> Vec<u8> {
|
||||
serde_json::json!({
|
||||
"schema": "marqdo.analysis",
|
||||
"schema_version": schema_version,
|
||||
"producer": {"name": "marqdo", "version": "3.0.0-beta.1", "markdown_profile": "marqdo.md.v1"},
|
||||
"project": {"root_id": "root:t@0.1.0", "identity_kind": "manifest", "lock_digest": "", "stdlib": null},
|
||||
"modules": [{
|
||||
"id": "root:t@0.1.0::index.mq.md",
|
||||
"package_instance_id": "root:t@0.1.0",
|
||||
"relative_path": "index.mq.md",
|
||||
"source_digest": digest,
|
||||
"units": [],
|
||||
"functions": [],
|
||||
"imports": [],
|
||||
"references": [],
|
||||
"calls": [],
|
||||
"resources": []
|
||||
}],
|
||||
"diagnostics": []
|
||||
})
|
||||
.to_string()
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_schema_major_and_profile() {
|
||||
let source = "# hi\n";
|
||||
let index = SourceIndex::new(source);
|
||||
let digest = sha256_hex(source.as_bytes());
|
||||
let err =
|
||||
verify_analysis(&analysis(4, &digest), source, &index, "index.mq.md").unwrap_err();
|
||||
assert_eq!(err.code(), "view.protocol_incompatible");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_digest_mismatch() {
|
||||
let source = "# hi\n";
|
||||
let index = SourceIndex::new(source);
|
||||
let err = verify_analysis(&analysis(2, &"0".repeat(64)), source, &index, "index.mq.md")
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code(), "view.source_mismatch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_valid_analysis() {
|
||||
let source = "# hi\n";
|
||||
let index = SourceIndex::new(source);
|
||||
let digest = sha256_hex(source.as_bytes());
|
||||
let verified =
|
||||
verify_analysis(&analysis(2, &digest), source, &index, "index.mq.md").unwrap();
|
||||
assert_eq!(verified.projection.project_root_id, "root:t@0.1.0");
|
||||
assert_eq!(verified.projection.relative_path, "index.mq.md");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_id_is_deterministic_and_bounded() {
|
||||
let span = SourceSpan::new(1, 5);
|
||||
let id = source_id("mod", span, "statement");
|
||||
assert_eq!(id.len(), 16);
|
||||
assert_eq!(id, source_id("mod", span, "statement"));
|
||||
assert_ne!(id, source_id("mod", span, "resource"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,355 +0,0 @@
|
||||
//! Decode the CLI's bounded, source-bound NDJSON stream. The browser only
|
||||
//! receives projections selected by this decoder.
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, BufReader, Read};
|
||||
|
||||
const SCHEMA: &str = "marqdo.execution-events";
|
||||
const MAX_LINE: usize = 4 * 1024 * 1024;
|
||||
const MAX_CHUNK: usize = 64 * 1024;
|
||||
const MAX_TRANSPORT: usize = 16 * 1024 * 1024;
|
||||
|
||||
pub struct Binding {
|
||||
pub digest: String,
|
||||
pub root: String,
|
||||
pub entry: String,
|
||||
pub function: String,
|
||||
pub mode: String,
|
||||
pub producer: String,
|
||||
pub modules: Vec<String>,
|
||||
pub max_output: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Stream {
|
||||
pub id: String,
|
||||
pub verified: bool,
|
||||
pub truncated: bool,
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub terminal: Option<Value>,
|
||||
pub invalid: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Event {
|
||||
schema: String,
|
||||
schema_version: u32,
|
||||
run_id: String,
|
||||
seq: u64,
|
||||
kind: String,
|
||||
payload: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
pub fn read(input: impl Read, binding: &Binding, mut publish: impl FnMut(Value)) -> Stream {
|
||||
let mut input = BufReader::new(input);
|
||||
let mut stream = Stream::default();
|
||||
let mut line = Vec::new();
|
||||
let mut total = 0;
|
||||
let mut seq = 0;
|
||||
let mut entry_frame_seen = false;
|
||||
loop {
|
||||
line.clear();
|
||||
let size = match input
|
||||
.by_ref()
|
||||
.take(MAX_LINE as u64 + 1)
|
||||
.read_until(b'\n', &mut line)
|
||||
{
|
||||
Ok(0) => break,
|
||||
Ok(size) => size,
|
||||
Err(_) => {
|
||||
stream.invalid = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
total += size;
|
||||
if total > MAX_TRANSPORT || size > MAX_LINE {
|
||||
stream.invalid = true;
|
||||
break;
|
||||
}
|
||||
if line.last() != Some(&b'\n') {
|
||||
stream.invalid = true;
|
||||
break;
|
||||
}
|
||||
let Ok(event) = serde_json::from_slice::<Event>(&line) else {
|
||||
stream.invalid = true;
|
||||
break;
|
||||
};
|
||||
match consume(&mut stream, binding, event, seq, &mut entry_frame_seen) {
|
||||
Ok(Some(projection)) => publish(projection),
|
||||
Ok(None) => {}
|
||||
Err(()) => {
|
||||
stream.invalid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
seq += 1;
|
||||
}
|
||||
if stream.invalid {
|
||||
// Drain without keeping bytes so a malformed child cannot block on its pipe.
|
||||
let _ = std::io::copy(&mut input, &mut std::io::sink());
|
||||
stream.terminal = None;
|
||||
}
|
||||
stream
|
||||
}
|
||||
|
||||
fn consume(
|
||||
stream: &mut Stream,
|
||||
binding: &Binding,
|
||||
event: Event,
|
||||
seq: u64,
|
||||
entry_frame_seen: &mut bool,
|
||||
) -> Result<Option<Value>, ()> {
|
||||
if event.schema != SCHEMA
|
||||
|| event.schema_version != 1
|
||||
|| event.seq != seq
|
||||
|| event.run_id.is_empty()
|
||||
|| event.run_id.len() > 128
|
||||
|| stream.terminal.is_some()
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
let payload = &event.payload;
|
||||
let kind = event.kind.as_str();
|
||||
if seq == 0 {
|
||||
if kind != "stream.opened"
|
||||
|| payload.get("protocol") != Some(&json!({"name": SCHEMA, "schema_version": 1}))
|
||||
|| payload
|
||||
.get("producer")
|
||||
.and_then(|value| value["name"].as_str())
|
||||
!= Some("marqdo")
|
||||
|| payload
|
||||
.get("producer")
|
||||
.and_then(|value| value["version"].as_str())
|
||||
!= Some(&binding.producer)
|
||||
|| !payload.get("limits").is_some_and(Value::is_object)
|
||||
|| !payload.get("observation").is_some_and(Value::is_object)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
stream.id = event.run_id;
|
||||
return Ok(Some(json!({"seq": seq, "kind": kind})));
|
||||
}
|
||||
if stream.id != event.run_id {
|
||||
return Err(());
|
||||
}
|
||||
let mut projection = json!({"seq": seq, "kind": kind});
|
||||
if seq == 1 {
|
||||
match kind {
|
||||
"run.rejected" => {
|
||||
if text(payload, "status") != Some("rejected") || text(payload, "phase").is_none() {
|
||||
return Err(());
|
||||
}
|
||||
stream.terminal = Some(failure(payload)?);
|
||||
return Ok(None);
|
||||
}
|
||||
"run.started" => {
|
||||
let source = payload.get("source").ok_or(())?;
|
||||
if source["analysis_digest"].as_str() != Some(&binding.digest)
|
||||
|| source["root_id"].as_str() != Some(&binding.root)
|
||||
|| text(payload, "entry") != Some(&binding.entry)
|
||||
|| text(payload, "mode") != Some(&binding.mode)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
stream.verified = true;
|
||||
return Ok(Some(projection));
|
||||
}
|
||||
_ => return Err(()),
|
||||
}
|
||||
}
|
||||
match kind {
|
||||
"stream.opened" | "run.started" | "run.rejected" => return Err(()),
|
||||
"stdout.chunk" | "stderr.chunk" => {
|
||||
let data = text(payload, "data_base64").ok_or(())?;
|
||||
if text(payload, "encoding") != Some("base64") || data.len() > MAX_CHUNK.div_ceil(3) * 4
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
let bytes = STANDARD.decode(data).map_err(|_| ())?;
|
||||
if bytes.len() > MAX_CHUNK
|
||||
|| payload.get("byte_count").and_then(Value::as_u64) != Some(bytes.len() as u64)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
if stream.stdout.len() + stream.stderr.len() + bytes.len() > binding.max_output {
|
||||
return Err(());
|
||||
}
|
||||
if kind == "stdout.chunk" {
|
||||
stream.stdout.extend_from_slice(&bytes);
|
||||
} else {
|
||||
stream.stderr.extend_from_slice(&bytes);
|
||||
}
|
||||
projection["data_base64"] = json!(data);
|
||||
}
|
||||
"run.completed" => {
|
||||
let value = payload
|
||||
.get("value")
|
||||
.filter(|value| super::value_wire_v1::valid(value))
|
||||
.ok_or(())?;
|
||||
if text(payload, "status") != Some("ok") || (!*entry_frame_seen && !stream.truncated) {
|
||||
return Err(());
|
||||
}
|
||||
stream.terminal = Some(json!({"success": true, "value": value}));
|
||||
return Ok(None);
|
||||
}
|
||||
"run.failed" => {
|
||||
if text(payload, "status") != Some("error") {
|
||||
return Err(());
|
||||
}
|
||||
stream.terminal = Some(failure(payload)?);
|
||||
return Ok(None);
|
||||
}
|
||||
"observation.truncated" => {
|
||||
if stream.truncated
|
||||
|| !matches!(
|
||||
text(payload, "reason"),
|
||||
Some("event_budget" | "byte_budget")
|
||||
)
|
||||
|| payload.get("limit").and_then(Value::as_u64).is_none()
|
||||
|| payload.get("written").and_then(Value::as_u64).is_none()
|
||||
|| !payload
|
||||
.get("dropped")
|
||||
.is_some_and(|value| value.is_null() || value.is_u64())
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
stream.truncated = true;
|
||||
}
|
||||
"call.enter" | "call.exit" | "return" | "branch.eval" | "loop.iteration"
|
||||
| "control.break" | "control.continue" | "effect" => {
|
||||
let module = text(payload, "module_id").ok_or(())?;
|
||||
let span = payload.get("span").ok_or(())?;
|
||||
let span_ok = span["start"]
|
||||
.as_u64()
|
||||
.zip(span["end"].as_u64())
|
||||
.is_some_and(|(start, end)| start < end);
|
||||
if !binding.modules.iter().any(|known| known == module)
|
||||
|| !(span_ok
|
||||
|| span.is_null() && !matches!(kind, "control.break" | "control.continue"))
|
||||
|| kind != "effect" && text(payload, "frame_id").is_none()
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
match kind {
|
||||
"call.enter" => {
|
||||
let function = text(payload, "function_id").ok_or(())?;
|
||||
match payload.get("parent_frame_id") {
|
||||
Some(Value::Null) if !*entry_frame_seen && function == binding.function => {
|
||||
*entry_frame_seen = true
|
||||
}
|
||||
Some(Value::String(_)) if *entry_frame_seen => {}
|
||||
_ => return Err(()),
|
||||
}
|
||||
}
|
||||
"call.exit" if text(payload, "status").is_none() => return Err(()),
|
||||
"return" if text(payload, "value_type").is_none() => return Err(()),
|
||||
"branch.eval" => {
|
||||
projection["decision"] =
|
||||
json!(payload.get("result").and_then(Value::as_bool).ok_or(())?)
|
||||
}
|
||||
"loop.iteration" => {
|
||||
let decision = text(payload, "decision")
|
||||
.filter(|decision| matches!(*decision, "continue" | "exit"))
|
||||
.ok_or(())?;
|
||||
projection["decision"] = json!(decision);
|
||||
}
|
||||
"effect"
|
||||
if text(payload, "operation").is_none()
|
||||
|| text(payload, "result_code").is_none() =>
|
||||
{
|
||||
return Err(())
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Values and additive kinds are never emitted as browser observations.
|
||||
_ => return Ok(None),
|
||||
}
|
||||
Ok(Some(projection))
|
||||
}
|
||||
|
||||
fn text<'a>(payload: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a str> {
|
||||
payload
|
||||
.get(key)?
|
||||
.as_str()
|
||||
.filter(|text| !text.is_empty() && text.len() <= MAX_LINE)
|
||||
}
|
||||
|
||||
fn failure(payload: &serde_json::Map<String, Value>) -> Result<Value, ()> {
|
||||
let error = payload.get("error").ok_or(())?;
|
||||
let code = error["code"].as_str().ok_or(())?;
|
||||
let message = error["message"].as_str().ok_or(())?;
|
||||
Ok(json!({"success": false, "error": {"code": code, "message": message}}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample() -> (Binding, Vec<Value>) {
|
||||
let binding = Binding {
|
||||
digest: "sha256:expected".into(),
|
||||
root: "root:p".into(),
|
||||
entry: "root:p::index.mq.md::main".into(),
|
||||
function: "root:p::index.mq.md::main".into(),
|
||||
mode: "pure".into(),
|
||||
producer: "3.0.0-rc.2".into(),
|
||||
modules: vec!["root:p::index.mq.md".into()],
|
||||
max_output: 100,
|
||||
};
|
||||
let event = |seq, kind, payload| {
|
||||
json!({"schema": SCHEMA, "schema_version": 1, "run_id": "r", "seq": seq,
|
||||
"kind": kind, "payload": payload})
|
||||
};
|
||||
let events = vec![
|
||||
event(
|
||||
0,
|
||||
"stream.opened",
|
||||
json!({"protocol": {"name": SCHEMA, "schema_version": 1},
|
||||
"producer": {"name": "marqdo", "version": binding.producer}, "limits": {}, "observation": {}}),
|
||||
),
|
||||
event(
|
||||
1,
|
||||
"run.started",
|
||||
json!({"entry": binding.entry, "mode": binding.mode,
|
||||
"source": {"analysis_digest": binding.digest, "root_id": binding.root}}),
|
||||
),
|
||||
event(
|
||||
2,
|
||||
"stdout.chunk",
|
||||
json!({"data_base64": "NAo=", "encoding": "base64", "byte_count": 2}),
|
||||
),
|
||||
event(
|
||||
3,
|
||||
"run.failed",
|
||||
json!({"status": "error", "error": {"code": "runtime.test", "message": "test"}}),
|
||||
),
|
||||
];
|
||||
(binding, events)
|
||||
}
|
||||
|
||||
fn decode(binding: &Binding, events: &[Value]) -> Stream {
|
||||
let ndjson = events
|
||||
.iter()
|
||||
.map(|value| format!("{value}\n"))
|
||||
.collect::<String>();
|
||||
read(ndjson.as_bytes(), binding, |_| {})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_stream_identity_bytes_and_terminal_boundary() {
|
||||
let (binding, mut events) = sample();
|
||||
let stream = decode(&binding, &events);
|
||||
assert!(stream.verified && !stream.invalid);
|
||||
assert_eq!(stream.stdout, b"4\n");
|
||||
assert!(stream.terminal.is_some());
|
||||
assert!(decode(&binding, &events[..3]).terminal.is_none());
|
||||
events[2]["payload"]["byte_count"] = json!(1);
|
||||
assert!(decode(&binding, &events).invalid);
|
||||
events[1]["payload"]["source"]["analysis_digest"] = json!("wrong");
|
||||
assert!(!decode(&binding, &events).verified);
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -1,10 +1,12 @@
|
||||
//! Public protocol adapters consumed by View.
|
||||
//!
|
||||
//! These modules are a **consumer** of the published CLI formats, never a
|
||||
//! second publisher or implementation of them (RFC-VIEW-0002 §5.3).
|
||||
//! second publisher or implementation of them. Each public boundary has
|
||||
//! exactly one current decoder and one domain projection:
|
||||
//! Analysis v3 (`marqdo.analysis`) and Observation v1 (`marqdo.observation`).
|
||||
//! Retired formats are rejected, never decoded through a fallback.
|
||||
|
||||
pub mod analysis_v2;
|
||||
pub mod execution_events_v1;
|
||||
pub mod analysis_v3;
|
||||
pub mod observation_v1;
|
||||
pub mod tool_v1;
|
||||
pub mod trace_v2;
|
||||
pub mod value_wire_v1;
|
||||
File diff suppressed because it is too large.
Load diff
+60
-91
@@ -1,28 +1,30 @@
|
||||
//! Product/protocol version negotiation with the frozen CLI.
|
||||
//! Current CLI Tool protocol constants (revision 1) and product identity.
|
||||
//!
|
||||
//! Version axes are independent (RFC-VIEW-0001 §4): product SemVer,
|
||||
//! Analysis major, Trace major and Tool protocol. We never infer one from
|
||||
//! another and never silently fall back to a latest-looking JSON.
|
||||
//! A CLI Tool declares exact contract revisions in `tool.json`
|
||||
//! (`requires.api_revision`, optional `analysis`/`observation`). There is no
|
||||
//! negotiation: the installed registration injects only `MARQDO_BIN` and
|
||||
//! `MARQDO_API_REVISION`, and a mismatch is a hard, actionable error.
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use semver::Version;
|
||||
|
||||
/// Product range this View build targets. Must match `tool.json`.
|
||||
pub const PRODUCT_RANGE: &str = ">=3.0.0-beta.1,<4.0.0";
|
||||
/// Product range this View build consumes. The rc.3 contract family is the
|
||||
/// first public pre-release with Observation v1 and Tool revision 1.
|
||||
pub const PRODUCT_RANGE: &str = ">=3.0.0-rc.3,<4.0.0";
|
||||
|
||||
/// Lowest compatible product version (inclusive).
|
||||
pub const MIN_PRODUCT: &str = "3.0.0-beta.1";
|
||||
pub const MIN_PRODUCT: &str = "3.0.0-rc.3";
|
||||
|
||||
pub const TOOL_PROTOCOL: u32 = 1;
|
||||
pub const ANALYSIS_PROTOCOL: u32 = 2;
|
||||
pub const ANALYSIS_PROTOCOLS: [u32; 2] = [2, 3];
|
||||
pub const TRACE_PROTOCOL: u32 = 2;
|
||||
/// CLI Tool API revision implemented by this View build.
|
||||
pub const API_REVISION: u32 = 1;
|
||||
/// Public Analysis revision consumed by this View build.
|
||||
pub const ANALYSIS_REVISION: u32 = 3;
|
||||
/// Public Observation revision consumed by this View build.
|
||||
pub const OBSERVATION_REVISION: u32 = 1;
|
||||
|
||||
/// Environment variables injected by CLI Tool Protocol v1.
|
||||
/// Environment variables injected by the CLI Tool registration.
|
||||
pub const ENV_MARQDO_BIN: &str = "MARQDO_BIN";
|
||||
pub const ENV_TOOL_PROTOCOL: &str = "MARQDO_TOOL_PROTOCOL";
|
||||
pub const ENV_PROTOCOL_ANALYSIS: &str = "MARQDO_PROTOCOL_ANALYSIS";
|
||||
pub const ENV_PROTOCOL_TRACE: &str = "MARQDO_PROTOCOL_TRACE";
|
||||
pub const ENV_MARQDO_API_REVISION: &str = "MARQDO_API_REVISION";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreVersion {
|
||||
@@ -31,7 +33,7 @@ pub struct CoreVersion {
|
||||
pub raw: String,
|
||||
}
|
||||
|
||||
/// Parse the output of `marqdo --version` (`marqdo 3.0.0-beta.1`).
|
||||
/// Parse the output of `marqdo --version` (`marqdo 3.0.0-rc.4`).
|
||||
pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
|
||||
let line = output
|
||||
.lines()
|
||||
@@ -55,103 +57,70 @@ pub fn parse_version_output(output: &str) -> ViewResult<CoreVersion> {
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `version` is inside the product range without relying on
|
||||
/// prerelease quirks of `semver::VersionReq`: any 3.x at or above the first
|
||||
/// beta is accepted, so a later `3.1.0-beta.1` keeps working.
|
||||
/// True when `version` is inside the supported product range.
|
||||
pub fn product_is_compatible(version: &Version) -> bool {
|
||||
let min = Version::parse(MIN_PRODUCT).expect("MIN_PRODUCT is valid SemVer");
|
||||
version.major == 3 && version >= &min
|
||||
}
|
||||
|
||||
/// RC.2 is the first public Core release with Execution Events v1.
|
||||
pub fn supports_execution_events(version: &str) -> bool {
|
||||
let first = Version::parse("3.0.0-rc.2").expect("valid Core version");
|
||||
Version::parse(version).is_ok_and(|version| version >= first)
|
||||
}
|
||||
|
||||
/// Validate the negotiated environment for Tool Protocol v1.
|
||||
/// Validate the CLI-injected API revision, if present.
|
||||
///
|
||||
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development
|
||||
/// binary (`--marqdo-bin`), but presence of an unknown major is a hard error.
|
||||
pub fn negotiate_protocol_env(
|
||||
tool_protocol: Option<&str>,
|
||||
analysis_protocol: Option<&str>,
|
||||
trace_protocol: Option<&str>,
|
||||
) -> ViewResult<()> {
|
||||
if let Some(raw) = tool_protocol {
|
||||
let value = parse_env_u32(ENV_TOOL_PROTOCOL, raw)?;
|
||||
if value != TOOL_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_TOOL_PROTOCOL}={value} is not supported (this View implements protocol {TOOL_PROTOCOL})"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(raw) = analysis_protocol {
|
||||
let value = parse_env_u32(ENV_PROTOCOL_ANALYSIS, raw)?;
|
||||
if !ANALYSIS_PROTOCOLS.contains(&value) {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_PROTOCOL_ANALYSIS}={value} is not supported (this View implements Analysis v2/v3)"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(raw) = trace_protocol {
|
||||
let value = parse_env_u32(ENV_PROTOCOL_TRACE, raw)?;
|
||||
if value != TRACE_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_PROTOCOL_TRACE}={value} is not supported (this View requires Trace v{TRACE_PROTOCOL})"
|
||||
),
|
||||
});
|
||||
}
|
||||
/// Absence is allowed for a directly-run development binary (`--marqdo-bin`);
|
||||
/// a present-but-different revision is a hard error. The value is only a
|
||||
/// static expectation check, never a negotiation input.
|
||||
pub fn validate_api_revision_env(raw: Option<&str>) -> ViewResult<()> {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(());
|
||||
};
|
||||
let value: u32 = raw
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| ViewError::ProtocolIncompatible {
|
||||
detail: format!("{ENV_MARQDO_API_REVISION}={raw:?} is not a positive integer"),
|
||||
})?;
|
||||
if value != API_REVISION {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"{ENV_MARQDO_API_REVISION}={value} is not supported; this View implements CLI Tool \
|
||||
API revision {API_REVISION}. Reinstall the rebuilt Tool bundle."
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_env_u32(name: &str, raw: &str) -> ViewResult<u32> {
|
||||
raw.trim()
|
||||
.parse::<u32>()
|
||||
.map_err(|_| ViewError::ProtocolIncompatible {
|
||||
detail: format!("{name}={raw:?} is not a positive integer protocol version"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_official_version_line() {
|
||||
let version = parse_version_output("marqdo 3.0.0-beta.1\n").unwrap();
|
||||
assert_eq!(version.version.to_string(), "3.0.0-beta.1");
|
||||
let version = parse_version_output("marqdo 3.0.0-rc.4\n").unwrap();
|
||||
assert_eq!(version.version.to_string(), "3.0.0-rc.4");
|
||||
assert!(product_is_compatible(&version.version));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_stable_only_reinterpretation() {
|
||||
// 2.9.1 is the old product line and must never be accepted.
|
||||
let old = Version::parse("2.9.1").unwrap();
|
||||
assert!(!product_is_compatible(&old));
|
||||
// A future major is rejected too.
|
||||
assert!(!product_is_compatible(&Version::parse("4.0.0").unwrap()));
|
||||
// Later prereleases in the 3.x line remain compatible.
|
||||
assert!(product_is_compatible(
|
||||
&Version::parse("3.1.0-beta.1").unwrap()
|
||||
));
|
||||
assert!(product_is_compatible(&Version::parse("3.0.0").unwrap()));
|
||||
fn rejects_retired_and_future_product_lines() {
|
||||
for accepted in ["3.0.0-rc.3", "3.0.0-rc.4", "3.0.0", "3.1.0-beta.1"] {
|
||||
assert!(
|
||||
product_is_compatible(&Version::parse(accepted).unwrap()),
|
||||
"{accepted} must be accepted"
|
||||
);
|
||||
}
|
||||
for rejected in ["2.9.1", "3.0.0-beta.1", "3.0.0-rc.2", "4.0.0"] {
|
||||
assert!(
|
||||
!product_is_compatible(&Version::parse(rejected).unwrap()),
|
||||
"{rejected} must be rejected"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negotiates_known_protocols_only() {
|
||||
assert!(negotiate_protocol_env(Some("1"), Some("2"), Some("2")).is_ok());
|
||||
assert!(negotiate_protocol_env(None, None, None).is_ok());
|
||||
assert!(negotiate_protocol_env(Some("1"), Some("3"), Some("2")).is_ok());
|
||||
assert!(negotiate_protocol_env(Some("2"), None, None).is_err());
|
||||
assert!(negotiate_protocol_env(None, Some("1"), None).is_err());
|
||||
assert!(negotiate_protocol_env(None, None, Some("3")).is_err());
|
||||
assert!(negotiate_protocol_env(None, Some("two"), None).is_err());
|
||||
fn api_revision_is_an_exact_expectation() {
|
||||
assert!(validate_api_revision_env(None).is_ok());
|
||||
assert!(validate_api_revision_env(Some("1")).is_ok());
|
||||
assert!(validate_api_revision_env(Some("2")).is_err());
|
||||
assert!(validate_api_revision_env(Some("one")).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
//! Trace v2 validation and run projection.
|
||||
//!
|
||||
//! Trace data is observed execution, not execution itself. Validation is hard:
|
||||
//! the trace must bind to the exact Analysis bytes and project identity, and
|
||||
//! every event module id must exist in Analysis. Missing capabilities (per
|
||||
//! assignment values, memory snapshots, proofs) are explicit `UNSUPPORTED`
|
||||
//! states, never invented (RFC-VIEW-0001 §4.4, §12).
|
||||
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::protocol::analysis_v2::{ModuleSummary, SemanticProjection};
|
||||
use crate::reader::source::{sha256_hex, sha256_prefixed, SourceIndex, SourceSpan};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RunDisplayState {
|
||||
NotRun,
|
||||
StaticOnly,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Stale,
|
||||
Truncated,
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
impl RunDisplayState {
|
||||
pub fn data_value(&self) -> &'static str {
|
||||
match self {
|
||||
RunDisplayState::NotRun => "not-run",
|
||||
RunDisplayState::StaticOnly => "static-only",
|
||||
RunDisplayState::Running => "running",
|
||||
RunDisplayState::Succeeded => "succeeded",
|
||||
RunDisplayState::Failed => "failed",
|
||||
RunDisplayState::Stale => "stale",
|
||||
RunDisplayState::Truncated => "truncated",
|
||||
RunDisplayState::Unsupported => "unsupported",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
RunDisplayState::NotRun => "未运行",
|
||||
RunDisplayState::StaticOnly => "仅静态检查",
|
||||
RunDisplayState::Running => "运行中",
|
||||
RunDisplayState::Succeeded => "运行成功",
|
||||
RunDisplayState::Failed => "运行失败",
|
||||
RunDisplayState::Stale => "结果已过期",
|
||||
RunDisplayState::Truncated => "Trace 已截断",
|
||||
RunDisplayState::Unsupported => "当前协议不支持",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum TraceKind {
|
||||
CallEnter,
|
||||
CallExit,
|
||||
BranchEval,
|
||||
LoopIteration,
|
||||
Return,
|
||||
Effect,
|
||||
Truncated,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl TraceKind {
|
||||
pub fn data_value(&self) -> &str {
|
||||
match self {
|
||||
TraceKind::CallEnter => "call.enter",
|
||||
TraceKind::CallExit => "call.exit",
|
||||
TraceKind::BranchEval => "branch.eval",
|
||||
TraceKind::LoopIteration => "loop.iteration",
|
||||
TraceKind::Return => "return",
|
||||
TraceKind::Effect => "effect",
|
||||
TraceKind::Truncated => "trace.truncated",
|
||||
TraceKind::Other(kind) => kind,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(raw: &str) -> TraceKind {
|
||||
match raw {
|
||||
"call.enter" => TraceKind::CallEnter,
|
||||
"call.exit" => TraceKind::CallExit,
|
||||
"branch.eval" => TraceKind::BranchEval,
|
||||
"loop.iteration" => TraceKind::LoopIteration,
|
||||
"return" => TraceKind::Return,
|
||||
"effect" => TraceKind::Effect,
|
||||
"trace.truncated" => TraceKind::Truncated,
|
||||
other => TraceKind::Other(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TraceEvent {
|
||||
pub seq: u64,
|
||||
pub kind: TraceKind,
|
||||
pub function_id: Option<String>,
|
||||
pub module_id: Option<String>,
|
||||
/// Validated span in the entry module; `None` for other modules or invalid
|
||||
/// spans (which are reported as warnings).
|
||||
pub span: Option<SourceSpan>,
|
||||
/// Presentation-only span in an event's own module, kept for the panel.
|
||||
pub raw_span: Option<SourceSpan>,
|
||||
/// Statement span in the entry document this event attaches to, if any.
|
||||
pub anchor_span: Option<SourceSpan>,
|
||||
pub detail: Option<String>,
|
||||
pub operation: Option<String>,
|
||||
pub duration_micros: Option<u64>,
|
||||
}
|
||||
|
||||
impl TraceEvent {
|
||||
pub fn kind_label(&self) -> &str {
|
||||
self.kind.data_value()
|
||||
}
|
||||
|
||||
pub fn is_entry_module(&self, entry_module: &str) -> bool {
|
||||
self.module_id.as_deref() == Some(entry_module)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Truncation {
|
||||
pub reason: String,
|
||||
pub limit: u64,
|
||||
pub written: u64,
|
||||
}
|
||||
|
||||
impl Truncation {
|
||||
pub fn label(&self) -> String {
|
||||
let reason = match self.reason.as_str() {
|
||||
"event_budget" => "事件数量上限",
|
||||
"byte_budget" => "字节上限",
|
||||
other => other,
|
||||
};
|
||||
format!("{reason}(上限 {},已写入 {})", self.limit, self.written)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunValue {
|
||||
pub ty: String,
|
||||
pub display: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EventCounts {
|
||||
pub call_enter: usize,
|
||||
pub call_exit: usize,
|
||||
pub branch_eval: usize,
|
||||
pub loop_iteration: usize,
|
||||
pub return_events: usize,
|
||||
pub effect: usize,
|
||||
pub other: usize,
|
||||
}
|
||||
|
||||
impl EventCounts {
|
||||
pub fn total(&self) -> usize {
|
||||
self.call_enter
|
||||
+ self.call_exit
|
||||
+ self.branch_eval
|
||||
+ self.loop_iteration
|
||||
+ self.return_events
|
||||
+ self.effect
|
||||
+ self.other
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProjection {
|
||||
pub run_id: String,
|
||||
pub entry: Option<String>,
|
||||
/// Raw `run.status` from the Core (`ok` or a stable runtime error code).
|
||||
pub run_status: String,
|
||||
pub state: RunDisplayState,
|
||||
pub error_code: Option<String>,
|
||||
pub analysis_digest: String,
|
||||
pub events: Vec<TraceEvent>,
|
||||
pub truncated: Option<Truncation>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub exit_code: i32,
|
||||
pub result_value: Option<RunValue>,
|
||||
pub counts: EventCounts,
|
||||
/// Counts per event module: entry document vs other modules.
|
||||
pub entry_event_count: usize,
|
||||
pub other_event_count: usize,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl RunProjection {
|
||||
pub fn state_label(&self) -> &'static str {
|
||||
self.state.label()
|
||||
}
|
||||
|
||||
pub fn is_success(&self) -> bool {
|
||||
matches!(
|
||||
self.state,
|
||||
RunDisplayState::Succeeded | RunDisplayState::Truncated
|
||||
)
|
||||
}
|
||||
|
||||
/// Events whose statement anchor is exactly `span`, in sequence order.
|
||||
pub fn events_for_anchor(&self, span: SourceSpan) -> Vec<&TraceEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
.filter(|event| event.anchor_span == Some(span))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Compact inline summary for one statement anchor, or `None` when the
|
||||
/// statement has no sourced run event.
|
||||
pub fn anchor_summary(&self, span: SourceSpan) -> Option<RunAnchorSummary> {
|
||||
let events = self.events_for_anchor(span);
|
||||
if events.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let last = events.last().expect("non-empty");
|
||||
let mut kinds: Vec<&str> = Vec::new();
|
||||
for event in &events {
|
||||
if !kinds.contains(&event.kind_label()) {
|
||||
kinds.push(event.kind_label());
|
||||
}
|
||||
}
|
||||
let detail = match last.kind {
|
||||
TraceKind::BranchEval => format!("if → {}", last.detail.as_deref().unwrap_or("?")),
|
||||
TraceKind::LoopIteration => {
|
||||
let outcome = match last.detail.as_deref() {
|
||||
Some("continue") => "continue",
|
||||
Some("exit") => "exit",
|
||||
other => other.unwrap_or("?"),
|
||||
};
|
||||
format!("loop {outcome}")
|
||||
}
|
||||
TraceKind::Return => format!("return {}", last.detail.as_deref().unwrap_or("Unit")),
|
||||
TraceKind::CallEnter => "call".to_string(),
|
||||
TraceKind::CallExit => "call exit".to_string(),
|
||||
TraceKind::Effect => format!("effect {}", last.operation.as_deref().unwrap_or("ok")),
|
||||
_ => last.kind_label().to_string(),
|
||||
};
|
||||
Some(RunAnchorSummary {
|
||||
count: events.len(),
|
||||
detail,
|
||||
kinds: kinds.into_iter().map(str::to_string).collect(),
|
||||
last_seq: last.seq,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunAnchorSummary {
|
||||
pub count: usize,
|
||||
pub detail: String,
|
||||
pub kinds: Vec<String>,
|
||||
pub last_seq: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VerifiedRun {
|
||||
pub projection: RunProjection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTrace {
|
||||
schema: String,
|
||||
schema_version: u32,
|
||||
run: RawRun,
|
||||
source: RawTraceSource,
|
||||
#[serde(default)]
|
||||
truncated: Option<RawTruncation>,
|
||||
#[serde(default)]
|
||||
events: Vec<RawEvent>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawRun {
|
||||
#[serde(default)]
|
||||
id: String,
|
||||
#[serde(default)]
|
||||
entry: Option<String>,
|
||||
#[serde(default)]
|
||||
status: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTraceSource {
|
||||
#[serde(default)]
|
||||
root_id: String,
|
||||
#[serde(default)]
|
||||
analysis_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawTruncation {
|
||||
#[serde(default)]
|
||||
reason: String,
|
||||
#[serde(default)]
|
||||
limit: u64,
|
||||
#[serde(default)]
|
||||
written: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct RawEvent {
|
||||
#[serde(default)]
|
||||
seq: u64,
|
||||
#[serde(default)]
|
||||
kind: String,
|
||||
#[serde(default)]
|
||||
function_id: Option<String>,
|
||||
#[serde(default)]
|
||||
module_id: Option<String>,
|
||||
#[serde(default)]
|
||||
span: Option<SourceSpan>,
|
||||
#[serde(default)]
|
||||
detail: Option<String>,
|
||||
#[serde(default)]
|
||||
operation: Option<String>,
|
||||
#[serde(default)]
|
||||
duration_micros: Option<u64>,
|
||||
}
|
||||
|
||||
pub struct TraceVerificationInput<'a> {
|
||||
pub trace_bytes: &'a [u8],
|
||||
pub analysis_bytes: &'a [u8],
|
||||
pub semantic: &'a SemanticProjection,
|
||||
pub modules: &'a [ModuleSummary],
|
||||
pub source: &'a str,
|
||||
pub source_index: &'a SourceIndex,
|
||||
pub run_json: &'a Value,
|
||||
pub exit_code: i32,
|
||||
}
|
||||
|
||||
/// Verify Trace v2 against the current Analysis and project it for the reader.
|
||||
pub fn verify_trace(input: TraceVerificationInput<'_>) -> ViewResult<VerifiedRun> {
|
||||
let raw: RawTrace =
|
||||
serde_json::from_slice(input.trace_bytes).map_err(|err| ViewError::TraceStale {
|
||||
detail: format!("Trace v2 is not valid JSON: {err}"),
|
||||
})?;
|
||||
if raw.schema != "marqdo.trace" {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!("unexpected Trace schema {:?}", raw.schema),
|
||||
});
|
||||
}
|
||||
if raw.schema_version != crate::protocol::tool_v1::TRACE_PROTOCOL {
|
||||
return Err(ViewError::ProtocolIncompatible {
|
||||
detail: format!(
|
||||
"Trace schema_version {} is not supported (View implements v{})",
|
||||
raw.schema_version,
|
||||
crate::protocol::tool_v1::TRACE_PROTOCOL
|
||||
),
|
||||
});
|
||||
}
|
||||
let expected_digest = sha256_prefixed(input.analysis_bytes);
|
||||
if raw.source.analysis_digest != expected_digest {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace.source.analysis_digest {} does not match current Analysis {}",
|
||||
raw.source.analysis_digest, expected_digest
|
||||
),
|
||||
});
|
||||
}
|
||||
if raw.source.root_id != input.semantic.project_root_id {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace.source.root_id {} does not match Analysis project {}",
|
||||
raw.source.root_id, input.semantic.project_root_id
|
||||
),
|
||||
});
|
||||
}
|
||||
let known_modules: std::collections::HashSet<&str> = input
|
||||
.modules
|
||||
.iter()
|
||||
.map(|module| module.id.as_str())
|
||||
.collect();
|
||||
for event in &raw.events {
|
||||
if let Some(module) = event.module_id.as_deref() {
|
||||
if !known_modules.contains(module) {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace event seq {} references unknown module {module}",
|
||||
event.seq
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let entry_module = input.semantic.module_id.as_str();
|
||||
let statements = input.semantic.all_statements();
|
||||
let mut warnings = Vec::new();
|
||||
let mut counts = EventCounts::default();
|
||||
let mut entry_event_count = 0usize;
|
||||
let mut other_event_count = 0usize;
|
||||
let mut events = Vec::with_capacity(raw.events.len());
|
||||
for event in raw.events {
|
||||
let kind = TraceKind::parse(&event.kind);
|
||||
match kind {
|
||||
TraceKind::CallEnter => counts.call_enter += 1,
|
||||
TraceKind::CallExit => counts.call_exit += 1,
|
||||
TraceKind::BranchEval => counts.branch_eval += 1,
|
||||
TraceKind::LoopIteration => counts.loop_iteration += 1,
|
||||
TraceKind::Return => counts.return_events += 1,
|
||||
TraceKind::Effect => counts.effect += 1,
|
||||
_ => counts.other += 1,
|
||||
}
|
||||
let is_entry = event.module_id.as_deref() == Some(entry_module);
|
||||
if is_entry {
|
||||
entry_event_count += 1;
|
||||
} else {
|
||||
other_event_count += 1;
|
||||
}
|
||||
// Only entry-module spans can be anchored to the rendered document.
|
||||
let (span, anchor_span) = if is_entry {
|
||||
match event.span {
|
||||
Some(span)
|
||||
if input
|
||||
.source_index
|
||||
.validate_span_bytes(input.source.as_bytes(), span) =>
|
||||
{
|
||||
let anchor = statements
|
||||
.iter()
|
||||
.filter(|(_, statement)| {
|
||||
statement.span == span
|
||||
|| statement.condition_span == Some(span)
|
||||
|| statement
|
||||
.arms
|
||||
.iter()
|
||||
.any(|arm| arm.condition_span == Some(span))
|
||||
})
|
||||
.min_by_key(|(_, statement)| statement.span.len())
|
||||
.map(|(_, statement)| statement.span)
|
||||
.or_else(|| {
|
||||
statements
|
||||
.iter()
|
||||
.filter(|(_, statement)| statement.span.contains(span))
|
||||
.min_by_key(|(_, statement)| statement.span.len())
|
||||
.map(|(_, statement)| statement.span)
|
||||
});
|
||||
(Some(span), anchor)
|
||||
}
|
||||
other => {
|
||||
if other.is_some() {
|
||||
warnings.push(format!(
|
||||
"事件 seq {} 的 span 超出当前源码或不在 UTF-8 边界,已取消位置绑定",
|
||||
event.seq
|
||||
));
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
events.push(TraceEvent {
|
||||
seq: event.seq,
|
||||
kind,
|
||||
function_id: event.function_id,
|
||||
module_id: event.module_id,
|
||||
span,
|
||||
raw_span: event.span,
|
||||
anchor_span,
|
||||
detail: event.detail,
|
||||
operation: event.operation,
|
||||
duration_micros: event.duration_micros,
|
||||
});
|
||||
}
|
||||
// Sequence numbers must be strictly increasing; a broken trace is stale.
|
||||
for pair in events.windows(2) {
|
||||
if pair[1].seq <= pair[0].seq {
|
||||
return Err(ViewError::TraceStale {
|
||||
detail: format!(
|
||||
"trace seq is not strictly increasing ({} then {})",
|
||||
pair[0].seq, pair[1].seq
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let truncated = raw.truncated.map(|truncated| Truncation {
|
||||
reason: truncated.reason,
|
||||
limit: truncated.limit,
|
||||
written: truncated.written,
|
||||
});
|
||||
let run_status = if raw.run.status.is_empty() {
|
||||
"ok".to_string()
|
||||
} else {
|
||||
raw.run.status.clone()
|
||||
};
|
||||
let success = input
|
||||
.run_json
|
||||
.get("success")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false);
|
||||
let error_code = input
|
||||
.run_json
|
||||
.get("error")
|
||||
.and_then(|error| error.get("code"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
if run_status == "ok" {
|
||||
None
|
||||
} else {
|
||||
Some(run_status.clone())
|
||||
}
|
||||
});
|
||||
let state = if truncated.is_some() {
|
||||
RunDisplayState::Truncated
|
||||
} else if success && run_status == "ok" {
|
||||
RunDisplayState::Succeeded
|
||||
} else {
|
||||
RunDisplayState::Failed
|
||||
};
|
||||
let stdout = bounded_text(input.run_json, "stdout", 64 * 1024);
|
||||
let stderr = bounded_text(input.run_json, "stderr", 64 * 1024);
|
||||
let result_value = input.run_json.get("value").and_then(|value| {
|
||||
let ty = value.get("type").and_then(Value::as_str)?;
|
||||
let display = value
|
||||
.get("decimal")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| value.get("text").and_then(Value::as_str))
|
||||
.or_else(|| value.get("value").and_then(Value::as_str))
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| compact_json(value));
|
||||
Some(RunValue {
|
||||
ty: ty.to_string(),
|
||||
display,
|
||||
})
|
||||
});
|
||||
let _ = sha256_hex(input.trace_bytes);
|
||||
Ok(VerifiedRun {
|
||||
projection: RunProjection {
|
||||
run_id: raw.run.id,
|
||||
entry: raw.run.entry,
|
||||
run_status,
|
||||
state,
|
||||
error_code,
|
||||
analysis_digest: expected_digest,
|
||||
events,
|
||||
truncated,
|
||||
stdout,
|
||||
stderr,
|
||||
exit_code: input.exit_code,
|
||||
result_value,
|
||||
counts,
|
||||
entry_event_count,
|
||||
other_event_count,
|
||||
warnings,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn bounded_text(run_json: &Value, key: &str, limit: usize) -> String {
|
||||
let text = run_json
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if text.len() <= limit {
|
||||
text
|
||||
} else {
|
||||
let mut truncated: String = text.chars().take(limit).collect();
|
||||
truncated.push_str("\n…(输出已截断)");
|
||||
truncated
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_json(value: &Value) -> String {
|
||||
let text = value.to_string();
|
||||
if text.chars().count() > 80 {
|
||||
format!("{}…", text.chars().take(80).collect::<String>())
|
||||
} else {
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a stale run projection that keeps the raw result accessible without
|
||||
/// binding any event to the current document.
|
||||
pub fn stale_projection(analysis_digest: &str, source: &SourceIndex) -> RunProjection {
|
||||
let _ = source;
|
||||
RunProjection {
|
||||
run_id: String::new(),
|
||||
entry: None,
|
||||
run_status: "stale".to_string(),
|
||||
state: RunDisplayState::Stale,
|
||||
error_code: Some("view.trace_stale".to_string()),
|
||||
analysis_digest: analysis_digest.to_string(),
|
||||
events: Vec::new(),
|
||||
truncated: None,
|
||||
stdout: String::new(),
|
||||
stderr: String::new(),
|
||||
exit_code: 0,
|
||||
result_value: None,
|
||||
counts: EventCounts::default(),
|
||||
entry_event_count: 0,
|
||||
other_event_count: 0,
|
||||
warnings: vec!["Trace 与当前 Analysis 字节摘要不匹配,未绑定任何事件。".to_string()],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn state_values_are_stable() {
|
||||
assert_eq!(RunDisplayState::Succeeded.data_value(), "succeeded");
|
||||
assert_eq!(RunDisplayState::Truncated.data_value(), "truncated");
|
||||
assert_eq!(RunDisplayState::Failed.data_value(), "failed");
|
||||
assert_eq!(RunDisplayState::Stale.label(), "结果已过期");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trace_kinds_are_additive_safe() {
|
||||
assert_eq!(TraceKind::parse("branch.eval"), TraceKind::BranchEval);
|
||||
assert_eq!(
|
||||
TraceKind::parse("future.event"),
|
||||
TraceKind::Other("future.event".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
TraceKind::parse("future.event").data_value(),
|
||||
"future.event"
|
||||
);
|
||||
}
|
||||
}
|
||||
+83
-68
@@ -1,12 +1,16 @@
|
||||
//! Assembly of the one `PresentationModel`.
|
||||
//!
|
||||
//! Merges the raw document, verified Analysis v2, diagnostics and an optional
|
||||
//! verified Trace v2 run into the model; decides stale/revoked semantics here
|
||||
//! and nowhere else (RFC-VIEW-0002 §5.2/§5.4).
|
||||
//! Merges the exact artifact source and verified Analysis v3 facts, diagnostics
|
||||
//! and an optional verified Observation v1 run into the model; decides
|
||||
//! stale/revoked semantics here and nowhere else.
|
||||
//!
|
||||
//! The artifact source (`modules[].source`) is the only source used to interpret
|
||||
//! spans. View only re-reads the file before the check to detect concurrent
|
||||
//! changes; it never rebuilds spans from `relative_path`.
|
||||
|
||||
use crate::config::ViewConfig;
|
||||
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection};
|
||||
use crate::protocol::trace_v2::VerifiedRun;
|
||||
use crate::protocol::analysis_v3::{CoreDiagnostic, SemanticProjection};
|
||||
use crate::protocol::observation_v1::{self, RunProjection};
|
||||
use crate::reader::markdown::{DocumentIdentity, DocumentModel};
|
||||
use crate::reader::model::{
|
||||
Navigation, OutlineEntry, OutlineKind, PresentationModel, SourceStatus,
|
||||
@@ -15,20 +19,19 @@ use crate::reader::source::{sha256_hex, Project, SafeRelativePath};
|
||||
|
||||
use crate::core_client::{CheckOptions, CheckResponse, CoreClient, RawCheckDiagnostic};
|
||||
use crate::error::{ViewError, ViewResult};
|
||||
use crate::protocol::analysis_v2;
|
||||
use crate::protocol::trace_v2;
|
||||
use crate::protocol::analysis_v3;
|
||||
use crate::reader::model::{anchor_for_span, PRESENTATION_VERSION};
|
||||
|
||||
/// Input to the one builder. `analysis` is already protocol/byte verified.
|
||||
pub struct BuildInput<'a> {
|
||||
pub document: DocumentModel,
|
||||
pub analysis: Option<&'a crate::protocol::analysis_v2::VerifiedAnalysis>,
|
||||
pub analysis: Option<&'a analysis_v3::VerifiedAnalysis>,
|
||||
pub status: SourceStatus,
|
||||
pub status_note: Option<String>,
|
||||
pub diagnostics: Vec<CoreDiagnostic>,
|
||||
pub navigation: Navigation,
|
||||
pub core_version: Option<String>,
|
||||
pub run: Option<&'a crate::protocol::trace_v2::VerifiedRun>,
|
||||
pub run: Option<&'a RunProjection>,
|
||||
}
|
||||
|
||||
pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||
@@ -81,7 +84,7 @@ pub fn build(input: BuildInput<'_>) -> PresentationModel {
|
||||
navigation,
|
||||
outline,
|
||||
core_version,
|
||||
run: run.map(|verified| verified.projection.clone()),
|
||||
run: run.cloned(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,10 +99,10 @@ fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
|
||||
.params
|
||||
.iter()
|
||||
.map(|param| {
|
||||
if param.ty.is_empty() {
|
||||
param.name.clone()
|
||||
if let Some(ty) = ¶m.ty {
|
||||
format!("{}: {}", param.name, ty)
|
||||
} else {
|
||||
format!("{}: {}", param.name, param.ty)
|
||||
param.name.clone()
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
@@ -119,18 +122,19 @@ fn build_outline(projection: &SemanticProjection) -> Vec<OutlineEntry> {
|
||||
}
|
||||
for unit in &projection.units {
|
||||
let kind = match unit.kind {
|
||||
crate::protocol::analysis_v2::UnitKind::Knowledge if unit.level >= 2 => {
|
||||
OutlineKind::Knowledge
|
||||
}
|
||||
crate::protocol::analysis_v2::UnitKind::Section => OutlineKind::Section,
|
||||
analysis_v3::UnitKind::Knowledge if unit.level >= 2 => OutlineKind::Knowledge,
|
||||
analysis_v3::UnitKind::Section => OutlineKind::Section,
|
||||
_ => continue,
|
||||
};
|
||||
if unit.name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(heading_span) = unit.heading_span else {
|
||||
continue;
|
||||
};
|
||||
entries.push(OutlineEntry {
|
||||
label: unit.name.clone(),
|
||||
anchor: anchor_for_span(unit.span.start, unit.span.end),
|
||||
anchor: anchor_for_span(heading_span.start, heading_span.end),
|
||||
detail: if unit.level == 2 {
|
||||
"知识单元".to_string()
|
||||
} else {
|
||||
@@ -204,26 +208,23 @@ impl DocumentService {
|
||||
self.load_with_run(relative, None)
|
||||
}
|
||||
|
||||
/// Same pipeline, optionally attaching an already-verified run projection.
|
||||
/// Same pipeline, optionally attaching an already-verified Observation run.
|
||||
/// The run is re-bound to freshly checked Analysis bytes; if the source or
|
||||
/// analysis changed meanwhile the result becomes `STALE` instead of being
|
||||
/// attached to the wrong text.
|
||||
pub fn load_with_run(
|
||||
&self,
|
||||
relative: &SafeRelativePath,
|
||||
run: Option<&VerifiedRun>,
|
||||
run: Option<&RunProjection>,
|
||||
) -> ViewResult<PresentationModel> {
|
||||
let source_bytes = self.project.read_source(relative)?;
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let document = DocumentModel::parse(source, DocumentIdentity::placeholder(relative));
|
||||
let disk_source = self.read_disk_source(relative)?;
|
||||
let navigation = Navigation::from_project(&self.project, &self.config, relative);
|
||||
|
||||
let mut status = SourceStatus::CoreUnavailable;
|
||||
let mut status_note = self.core_note.clone();
|
||||
let mut diagnostics = Vec::new();
|
||||
let mut verified = None;
|
||||
let mut source = disk_source.clone();
|
||||
|
||||
if let Some(client) = &self.core {
|
||||
match client.check(
|
||||
@@ -253,15 +254,15 @@ impl DocumentService {
|
||||
success: true,
|
||||
analysis: Some(check),
|
||||
..
|
||||
} => match analysis_v2::verify_analysis(
|
||||
} => match analysis_v3::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&document.source,
|
||||
&document.source_index,
|
||||
relative.as_str(),
|
||||
Some(&disk_source),
|
||||
) {
|
||||
Ok(verified_analysis) => {
|
||||
status = SourceStatus::StaticOk;
|
||||
status_note = None;
|
||||
source = verified_analysis.projection.source.clone();
|
||||
verified = Some(verified_analysis);
|
||||
}
|
||||
Err(err) if err.code() == "view.source_mismatch" => {
|
||||
@@ -290,28 +291,17 @@ impl DocumentService {
|
||||
}
|
||||
}
|
||||
|
||||
let attached_run: Option<VerifiedRun> = match (run, verified.as_ref()) {
|
||||
(Some(run), Some(analysis)) => {
|
||||
let expected = format!("sha256:{}", analysis.projection.analysis_sha256);
|
||||
if expected == run.projection.analysis_digest {
|
||||
Some(VerifiedRun {
|
||||
projection: run.projection.clone(),
|
||||
})
|
||||
} else {
|
||||
Some(VerifiedRun {
|
||||
projection: trace_v2::stale_projection(
|
||||
&run.projection.analysis_digest,
|
||||
&document.source_index,
|
||||
),
|
||||
})
|
||||
}
|
||||
let identity = identity_for(verified.as_ref(), relative);
|
||||
let document = DocumentModel::parse(source, identity);
|
||||
|
||||
let attached_run: Option<RunProjection> = match (run, verified.as_ref()) {
|
||||
(Some(run), Some(analysis))
|
||||
if run.analysis_digest == analysis.projection.analysis_digest
|
||||
&& run.source_verified =>
|
||||
{
|
||||
Some(run.clone())
|
||||
}
|
||||
(Some(run), None) => Some(VerifiedRun {
|
||||
projection: trace_v2::stale_projection(
|
||||
&run.projection.analysis_digest,
|
||||
&document.source_index,
|
||||
),
|
||||
}),
|
||||
(Some(run), _) => Some(observation_v1::stale_projection(&run.analysis_digest)),
|
||||
(None, _) => None,
|
||||
};
|
||||
|
||||
@@ -329,6 +319,31 @@ impl DocumentService {
|
||||
model.media = media;
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
fn read_disk_source(&self, relative: &SafeRelativePath) -> ViewResult<String> {
|
||||
let bytes = self.project.read_source(relative)?;
|
||||
String::from_utf8(bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn identity_for(
|
||||
verified: Option<&analysis_v3::VerifiedAnalysis>,
|
||||
relative: &SafeRelativePath,
|
||||
) -> DocumentIdentity {
|
||||
match verified {
|
||||
Some(verified) => {
|
||||
let projection = &verified.projection;
|
||||
DocumentIdentity {
|
||||
project_root_id: projection.project_root_id.clone(),
|
||||
module_id: projection.module_id.clone(),
|
||||
relative_path: projection.relative_path.clone(),
|
||||
source_sha256: projection.source_digest.clone(),
|
||||
}
|
||||
}
|
||||
None => DocumentIdentity::placeholder(relative),
|
||||
}
|
||||
}
|
||||
|
||||
fn generic_core_note(err: &ViewError) -> String {
|
||||
@@ -352,11 +367,11 @@ fn diagnostic_to_view(
|
||||
.map(|module| module.ends_with(relative.as_str()))
|
||||
.unwrap_or(true);
|
||||
CoreDiagnostic {
|
||||
module: diagnostic.module.clone(),
|
||||
module: diagnostic.module.clone().unwrap_or_default(),
|
||||
relative_path: if belongs_to_entry {
|
||||
Some(relative.as_str().to_string())
|
||||
relative.as_str().to_string()
|
||||
} else {
|
||||
None
|
||||
String::new()
|
||||
},
|
||||
span: None,
|
||||
line: diagnostic.line,
|
||||
@@ -373,10 +388,11 @@ fn diagnostic_to_view(
|
||||
}
|
||||
|
||||
/// One read-only, byte-verified static view of a document, used by explicit
|
||||
/// run validation and Trace binding. Nothing here executes the document.
|
||||
/// run validation and Observation binding. Nothing here executes the document.
|
||||
#[derive(Debug)]
|
||||
pub struct StaticDocument {
|
||||
pub relative: SafeRelativePath,
|
||||
/// Exact source carried by the verified Analysis artifact.
|
||||
pub source: String,
|
||||
pub source_index: crate::reader::source::SourceIndex,
|
||||
pub source_sha256: String,
|
||||
@@ -384,23 +400,20 @@ pub struct StaticDocument {
|
||||
pub analysis_bytes: Vec<u8>,
|
||||
pub media_digests: std::collections::BTreeMap<String, String>,
|
||||
pub analysis_digest: String,
|
||||
pub verified: crate::protocol::analysis_v2::VerifiedAnalysis,
|
||||
pub core_version: Option<String>,
|
||||
pub verified: analysis_v3::VerifiedAnalysis,
|
||||
}
|
||||
|
||||
impl DocumentService {
|
||||
/// Re-run the read-only `check --emit` and verify Analysis v2 against the
|
||||
/// current exact source bytes. This is the only static truth used before an
|
||||
/// explicit run is accepted.
|
||||
/// Re-run the read-only `check --emit` and verify Analysis v3 bytes against
|
||||
/// the source View read before the check. This is the only static truth used
|
||||
/// before an explicit run is accepted.
|
||||
pub fn static_document(&self, relative: &SafeRelativePath) -> ViewResult<StaticDocument> {
|
||||
let client = self.core.as_ref().ok_or_else(|| ViewError::RunDenied {
|
||||
detail: "没有可用的冻结核心(MARQDO_BIN);无法验证运行请求".to_string(),
|
||||
})?;
|
||||
let source_bytes = self.project.read_source(relative)?;
|
||||
let source_sha256 = sha256_hex(&source_bytes);
|
||||
let source = String::from_utf8(source_bytes).map_err(|err| ViewError::Io {
|
||||
detail: format!("{relative} is not valid UTF-8: {err}"),
|
||||
})?;
|
||||
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||
let disk_source = self.read_disk_source(relative)?;
|
||||
let disk_sha256 = sha256_hex(disk_source.as_bytes());
|
||||
let response = client.check(
|
||||
&self.project,
|
||||
relative,
|
||||
@@ -438,24 +451,26 @@ impl DocumentService {
|
||||
});
|
||||
}
|
||||
};
|
||||
let verified = crate::protocol::analysis_v2::verify_analysis(
|
||||
let verified = analysis_v3::verify_analysis(
|
||||
&check.analysis_bytes,
|
||||
&source,
|
||||
&source_index,
|
||||
relative.as_str(),
|
||||
Some(&disk_source),
|
||||
)?;
|
||||
let source = verified.projection.source.clone();
|
||||
let source_index = crate::reader::source::SourceIndex::new(&source);
|
||||
let document =
|
||||
DocumentModel::parse(source.clone(), DocumentIdentity::placeholder(relative));
|
||||
DocumentModel::parse(source.clone(), identity_for(Some(&verified), relative));
|
||||
let media = super::media::collect(&self.project, relative, &document.blocks);
|
||||
let media_digests = super::media::digests(&media);
|
||||
Ok(StaticDocument {
|
||||
relative: relative.clone(),
|
||||
source,
|
||||
source_index,
|
||||
source_sha256,
|
||||
source_sha256: disk_sha256,
|
||||
analysis_digest: check.analysis_digest,
|
||||
analysis_bytes: check.analysis_bytes,
|
||||
media_digests,
|
||||
core_version: self.core_version.clone(),
|
||||
verified,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! source for **typography only**; the resulting tree is converted into a
|
||||
//! View-owned `DocBlock`/`Inline` model that keeps exact UTF-8 byte spans.
|
||||
//! No semantic decision (which node is executable) is taken here — that comes
|
||||
//! exclusively from validated Analysis v2 (`semantic.rs`).
|
||||
//! exclusively from validated Analysis v3 (`protocol::analysis_v3`).
|
||||
|
||||
use crate::reader::source::SafeRelativePath;
|
||||
use crate::reader::source::{sha256_hex, SourceIndex, SourceSpan};
|
||||
|
||||
+4
-4
@@ -5,8 +5,8 @@
|
||||
//! Assembly from Analysis/Trace happens in `reader::assemble`.
|
||||
|
||||
use crate::config::ViewConfig;
|
||||
use crate::protocol::analysis_v2::{CoreDiagnostic, SemanticProjection, ViewWarning};
|
||||
use crate::protocol::trace_v2::{RunDisplayState, RunProjection};
|
||||
use crate::protocol::analysis_v3::{CoreDiagnostic, SemanticProjection, ViewWarning};
|
||||
use crate::protocol::observation_v1::{RunDisplayState, RunProjection};
|
||||
use crate::reader::markdown::DocumentModel;
|
||||
use crate::reader::source::{Project, SafeRelativePath};
|
||||
|
||||
@@ -17,7 +17,7 @@ pub const PRESENTATION_VERSION: u32 = 1;
|
||||
pub enum SourceStatus {
|
||||
/// No usable `MARQDO_BIN`; prose only, semantics explicitly unverified.
|
||||
CoreUnavailable,
|
||||
/// `check` succeeded and Analysis v2 was verified.
|
||||
/// `check` succeeded and Analysis v3 was verified.
|
||||
StaticOk,
|
||||
/// `check` failed; diagnostics shown, semantics revoked.
|
||||
CoreError,
|
||||
@@ -180,7 +180,7 @@ pub fn anchor_for_span(start: u64, end: u64) -> String {
|
||||
format!("mq-h-{start:x}-{end:x}")
|
||||
}
|
||||
|
||||
/// Analysis v2 function ids are `<module id>::<canonical name>`.
|
||||
/// Analysis v3 function ids are `<module id>::<canonical name>`.
|
||||
fn canonical_function_name(function_id: &str, module_id: &str) -> String {
|
||||
function_id
|
||||
.strip_prefix(&format!("{module_id}::"))
|
||||
|
||||
+119
-32
@@ -10,7 +10,7 @@
|
||||
//! Markdown is serialized here from the View-owned `DocBlock` tree, with raw
|
||||
//! HTML omitted by default and every URL scheme sanitized.
|
||||
|
||||
use crate::protocol::analysis_v2::{source_id, UnitKind};
|
||||
use crate::protocol::analysis_v3::{source_id, UnitKind};
|
||||
use crate::reader::assets::AssetBundle;
|
||||
use crate::reader::markdown::{DocBlock, Inline, TableAlign};
|
||||
use crate::reader::model::{anchor_for_span, PresentationModel};
|
||||
@@ -195,7 +195,7 @@ impl ReaderRenderer {
|
||||
<link rel="stylesheet" href="{css}"/>
|
||||
{script}
|
||||
</head>
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-execution-events="{execution_events}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||
"##,
|
||||
presentation_version = model.version,
|
||||
@@ -210,10 +210,6 @@ impl ReaderRenderer {
|
||||
run_available = if ctx.run_available { "true" } else { "false" },
|
||||
has_main = if has_main { "true" } else { "false" },
|
||||
core_available = if ctx.core_available { "true" } else { "false" },
|
||||
execution_events = model
|
||||
.core_version
|
||||
.as_deref()
|
||||
.is_some_and(crate::protocol::tool_v1::supports_execution_events),
|
||||
document = escape_attr(&relative_path),
|
||||
analysis_digest = escape_attr(&analysis_digest),
|
||||
run_timeout = ctx.run_timeout_secs,
|
||||
@@ -490,7 +486,7 @@ impl ReaderRenderer {
|
||||
match ¤t {
|
||||
Some(current) => {
|
||||
let mut section = None;
|
||||
let place_result = |html: &mut String, function: &crate::protocol::analysis_v2::SemanticFunction| {
|
||||
let place_result = |html: &mut String, function: &crate::protocol::analysis_v3::SemanticFunction| {
|
||||
if ctx.live {
|
||||
let _ = write!(html, "<div class=\"mq-result-slot\" data-result-for=\"{}\"></div>", escape_attr(&function.id));
|
||||
}
|
||||
@@ -563,7 +559,7 @@ impl ReaderRenderer {
|
||||
html,
|
||||
r##"<footer class="mq-footer">
|
||||
<span>Marqdo · 静态阅读</span>
|
||||
<span>Analysis v2 · Trace v2 · {core}</span>
|
||||
<span>Analysis v3 · Observation v1 · {core}</span>
|
||||
<span>默认不执行 · 无自动运行</span>
|
||||
</footer>
|
||||
"##,
|
||||
@@ -585,8 +581,8 @@ impl ReaderRenderer {
|
||||
<div id="mq-run-summary"></div>
|
||||
<pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre>
|
||||
<pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre>
|
||||
<details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden>
|
||||
<summary id="mq-run-trace-title">实时结构事件</summary>
|
||||
<details id="mq-run-observation-wrap" class="mq-run-events-wrap" hidden>
|
||||
<summary id="mq-run-observation-title">实时结构观察事件</summary>
|
||||
<ol id="mq-run-events" class="mq-run-events"></ol>
|
||||
</details>
|
||||
<button type="button" class="mq-fn-call mq-export-result" data-action="export-result" id="mq-export-result" hidden>导出文档(含本次结果)</button>
|
||||
@@ -673,7 +669,7 @@ impl ReaderRenderer {
|
||||
<ul class="mq-menu-list">
|
||||
<li><button type="button" data-action="mode-document">文档态 <span class="mq-menu-hint">原始 Markdown 阅读</span></button></li>
|
||||
<li><button type="button" data-action="mode-source">源码态 <span class="mq-menu-hint">逐行原文,含标记</span></button></li>
|
||||
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v2/v3</span></button></li>
|
||||
<li><button type="button" data-action="functions">函数大纲 <span class="mq-menu-hint">来自 Analysis v3</span></button></li>
|
||||
<li><button type="button" data-action="unsupported">未提供的能力 <span class="mq-menu-hint">变量 / 内存 / 调试 / 证明</span></button></li>
|
||||
<li><button type="button" data-action="print">打印 <span class="mq-menu-hint">隐藏交互与装饰</span></button></li>
|
||||
<li><button type="button" data-action="about">关于 Marqdo View <span class="mq-menu-hint">版本与协议</span></button></li>
|
||||
@@ -692,7 +688,7 @@ impl ReaderRenderer {
|
||||
{export_dialog}
|
||||
<dialog class="mq-dialog" id="mq-dialog-about" aria-labelledby="mq-about-title">
|
||||
<div class="mq-dialog-head"><h2 id="mq-about-title">关于 Marqdo View</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭关于">×</button></div>
|
||||
<p>版本 {view_version} · Tool Protocol v1 · Analysis v2/v3 · Trace v2。</p>
|
||||
<p>版本 {view_version} · CLI Tool API revision 1 · Analysis v3 · Observation v1。</p>
|
||||
<p>冻结核心:{core}。</p>
|
||||
<p class="mq-colophon">本页面只渲染原始 Markdown 与已校验的静态语义;打开、刷新、搜索、导出都不会执行文档。运行需要用户显式确认。</p>
|
||||
</dialog>
|
||||
@@ -723,7 +719,7 @@ impl ReaderRenderer {
|
||||
html,
|
||||
r##"<section class="mq-run-panel" id="mq-run-panel" data-run-state="{state}" data-run-id="{run_id}" aria-labelledby="mq-run-title">
|
||||
<h2 id="mq-run-title">本次运行 · {label}</h2>
|
||||
<p class="mq-colophon">入口 {entry} · 模式 pure · 退出码 {exit_code} · 事件 {total}(本文 {entry_count} / 其他模块 {other_count})</p>
|
||||
<p class="mq-colophon">入口 {entry} · 观察级别 {capture} · 退出码 {exit_code} · 事件 {total}(本文 {entry_count} / 其他模块 {other_count})</p>
|
||||
"##,
|
||||
state = run.state.data_value(),
|
||||
run_id = escape_attr(&run.run_id),
|
||||
@@ -733,11 +729,16 @@ impl ReaderRenderer {
|
||||
total = counts.total(),
|
||||
entry_count = run.entry_event_count,
|
||||
other_count = run.other_event_count,
|
||||
capture = escape_text(if run.capture_level.is_empty() {
|
||||
"(未知)"
|
||||
} else {
|
||||
&run.capture_level
|
||||
}),
|
||||
);
|
||||
if let Some(truncated) = &run.truncated {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-run-warning\" role=\"note\">Trace 被截断:{}</p>\n",
|
||||
"<p class=\"mq-run-warning\" role=\"note\">Observation 已截断:{}</p>\n",
|
||||
escape_text(&truncated.label())
|
||||
);
|
||||
}
|
||||
@@ -778,7 +779,7 @@ impl ReaderRenderer {
|
||||
);
|
||||
}
|
||||
if !run.events.is_empty() {
|
||||
html.push_str("<details class=\"mq-run-events-wrap\" open><summary>真实 Trace v2 事件</summary>\n<ol class=\"mq-run-events\">\n");
|
||||
html.push_str("<details class=\"mq-run-events-wrap\" open><summary>真实 Observation v1 事件</summary>\n<ol class=\"mq-run-events\">\n");
|
||||
for event in run.events.iter().take(200) {
|
||||
let location = match event.span {
|
||||
Some(span) => {
|
||||
@@ -903,6 +904,15 @@ fn render_block(
|
||||
);
|
||||
}
|
||||
let (badge, cleaned) = display_heading_content(content, unit);
|
||||
let section_span = unit
|
||||
.and_then(|unit| unit.span.start.checked_sub(0).map(|_| unit.span))
|
||||
.map(|span| {
|
||||
format!(
|
||||
" data-section-start=\"{}\" data-section-end=\"{}\"",
|
||||
span.start, span.end
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let data_semantic = if let Some((_, data)) = badge {
|
||||
data
|
||||
} else if let Some(unit) = unit {
|
||||
@@ -916,12 +926,16 @@ fn render_block(
|
||||
};
|
||||
let _ = write!(
|
||||
html,
|
||||
"<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\">",
|
||||
"<h{} id=\"{}\" data-source-id=\"{}\" data-semantic=\"{}\"
|
||||
data-heading-start=\"{}\" data-heading-end=\"{}\">",
|
||||
level,
|
||||
escape_attr(slug),
|
||||
source_id_id(model, *span),
|
||||
data_semantic,
|
||||
span.start,
|
||||
span.end,
|
||||
);
|
||||
let _ = section_span;
|
||||
if let Some(badge) = badge {
|
||||
let _ = write!(
|
||||
html,
|
||||
@@ -1095,7 +1109,7 @@ fn resolve_heading_unit(
|
||||
model: &PresentationModel,
|
||||
heading_span: SourceSpan,
|
||||
level: u8,
|
||||
) -> Option<&crate::protocol::analysis_v2::SemanticUnit> {
|
||||
) -> Option<&crate::protocol::analysis_v3::SemanticUnit> {
|
||||
let projection = model.semantic.as_ref()?;
|
||||
// A function heading maps to its function unit exactly; never borrow the
|
||||
// ancestor function for H3/H4 sections (that would duplicate DOM ids).
|
||||
@@ -1115,14 +1129,14 @@ fn resolve_heading_unit(
|
||||
projection
|
||||
.units
|
||||
.iter()
|
||||
.filter(|unit| unit.level == level && unit.span == heading_span)
|
||||
.filter(|unit| unit.level == level && unit.heading_span == Some(heading_span))
|
||||
.min_by_key(|unit| unit.span.len())
|
||||
.or_else(|| projection.unit_for_heading(heading_span, level))
|
||||
}
|
||||
|
||||
fn display_heading_content(
|
||||
content: &[Inline],
|
||||
unit: Option<&crate::protocol::analysis_v2::SemanticUnit>,
|
||||
unit: Option<&crate::protocol::analysis_v3::SemanticUnit>,
|
||||
) -> (Option<(&'static str, &'static str)>, Vec<Inline>) {
|
||||
let Some(unit) = unit else {
|
||||
return (None, content.to_vec());
|
||||
@@ -1312,8 +1326,63 @@ fn render_inline(
|
||||
children,
|
||||
} => {
|
||||
let reference = projection.and_then(|projection| projection.reference_for_span(*span));
|
||||
let state = reference.map(|reference| reference.state.as_str());
|
||||
let target = resolve_link(url, current, model, &ctx.links);
|
||||
let reference_state = reference.map(|reference| reference.state);
|
||||
let reference_href = reference.and_then(|reference| match reference.state {
|
||||
crate::protocol::analysis_v3::ReferenceState::Resolved => {
|
||||
// A resolved module target is linked through the project
|
||||
// document map; the fragment is preserved as written.
|
||||
reference.candidate_path.as_deref().and_then(|candidate| {
|
||||
crate::reader::source::SafeRelativePath::parse(candidate)
|
||||
.ok()
|
||||
.map(|target| {
|
||||
let mut href = ctx.links.document_href(current, &target);
|
||||
if let Some(fragment) = &reference.fragment {
|
||||
if !fragment.is_empty() {
|
||||
href.push('#');
|
||||
href.push_str(&percent_encode_path(fragment));
|
||||
}
|
||||
}
|
||||
href
|
||||
})
|
||||
})
|
||||
}
|
||||
crate::protocol::analysis_v3::ReferenceState::External => {
|
||||
resolve_link(url, current, model, &ctx.links)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let target = match reference {
|
||||
// A local target the loaded catalog did not cover is shown as
|
||||
// unverified, never as a broken link: keep the navigation href
|
||||
// only when the document is known to the project.
|
||||
Some(_reference)
|
||||
if reference_state
|
||||
== Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) =>
|
||||
{
|
||||
resolve_link(url, current, model, &ctx.links)
|
||||
}
|
||||
Some(_) => reference_href,
|
||||
None => resolve_link(url, current, model, &ctx.links),
|
||||
};
|
||||
let state = reference_state.map(|state| state.data_value());
|
||||
let state_title = match reference_state {
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded) => {
|
||||
"未核验:当前加载目录未覆盖该本地目标"
|
||||
}
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::Missing) => "引用目标缺失",
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::Ambiguous) => {
|
||||
"引用目标不唯一,请检查候选"
|
||||
}
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::OutsideScope) => {
|
||||
"引用目标越出项目范围,已拒绝读取"
|
||||
}
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::Invalid) => "引用地址无效",
|
||||
_ => "",
|
||||
};
|
||||
let unverified = matches!(
|
||||
reference_state,
|
||||
Some(crate::protocol::analysis_v3::ReferenceState::NotLoaded)
|
||||
);
|
||||
match target {
|
||||
Some(href) => {
|
||||
let _ = write!(html, "<a href=\"{href}\"", href = escape_attr(&href));
|
||||
@@ -1323,14 +1392,27 @@ fn render_inline(
|
||||
if let Some(state) = state {
|
||||
let _ = write!(html, " data-reference-state=\"{}\"", escape_attr(state));
|
||||
}
|
||||
if unverified {
|
||||
html.push_str(" class=\"mq-link-unverified\"");
|
||||
}
|
||||
html.push('>');
|
||||
render_inlines(html, children, model, ctx, current, assets_placeholder());
|
||||
html.push_str("</a>");
|
||||
}
|
||||
None => {
|
||||
html.push_str(
|
||||
"<span class=\"mq-link-blocked\" title=\"链接地址已被安全策略移除\">",
|
||||
);
|
||||
let class = if state.is_some() {
|
||||
"mq-link-blocked mq-link-error"
|
||||
} else {
|
||||
"mq-link-blocked"
|
||||
};
|
||||
let _ = write!(html, "<span class=\"{class}\"");
|
||||
if let Some(state) = state {
|
||||
let _ = write!(html, " data-reference-state=\"{}\"", escape_attr(state));
|
||||
}
|
||||
if !state_title.is_empty() {
|
||||
let _ = write!(html, " title=\"{}\"", escape_attr(state_title));
|
||||
}
|
||||
html.push('>');
|
||||
render_inlines(html, children, model, ctx, current, assets_placeholder());
|
||||
html.push_str("</span>");
|
||||
}
|
||||
@@ -1472,14 +1554,19 @@ fn render_snapshot(html: &mut String, overlay: &super::snapshot::ExportResultOve
|
||||
} else {
|
||||
html.push_str("<p class=\"mq-colophon\">参数未包含</p>");
|
||||
}
|
||||
let trace_status = match execution.trace_status.as_str() {
|
||||
let observation_status = match execution.observation_status.as_str() {
|
||||
"verified" => "已验证",
|
||||
"truncated" => "已验证,轨迹截断",
|
||||
"truncated" => "已验证,观察截断",
|
||||
"invalid" => "无效",
|
||||
"stale" => "已过期",
|
||||
_ => "不可用",
|
||||
};
|
||||
let _ = write!(html, "<p class=\"mq-colophon\">Trace v2 {trace_status}</p>");
|
||||
if let Some(counts) = &overlay.trace_counts {
|
||||
let _ = write!(
|
||||
html,
|
||||
"<p class=\"mq-colophon\">Observation v1 {observation_status} · 捕获级别 {capture_level}</p>",
|
||||
capture_level = escape_text(&execution.capture_level),
|
||||
);
|
||||
if let Some(counts) = &overlay.observation_counts {
|
||||
html.push_str("<dl class=\"mq-snapshot-counts\">");
|
||||
for (kind, count) in counts {
|
||||
let _ = write!(html, "<dt>{}</dt><dd>{count}</dd>", escape_text(kind));
|
||||
@@ -1584,7 +1671,7 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span
|
||||
};
|
||||
let _ = write!(
|
||||
html,
|
||||
"<span class=\"mq-run-chip\" data-run-seq=\"{seq}\" data-run-kind=\"{kinds}\" title=\"真实 Trace 事件:{count} 条({kinds})\">{detail}{suffix}</span>",
|
||||
"<span class=\"mq-run-chip\" data-run-seq=\"{seq}\" data-run-kind=\"{kinds}\" title=\"真实 Observation 事件:{count} 条({kinds})\">{detail}{suffix}</span>",
|
||||
seq = summary.last_seq,
|
||||
kinds = escape_attr(&summary.kinds.join(",")),
|
||||
count = summary.count,
|
||||
@@ -1596,7 +1683,7 @@ fn render_run_chips(html: &mut String, model: &PresentationModel, statement_span
|
||||
fn function_at(
|
||||
model: &PresentationModel,
|
||||
span: SourceSpan,
|
||||
) -> Option<&crate::protocol::analysis_v2::SemanticFunction> {
|
||||
) -> Option<&crate::protocol::analysis_v3::SemanticFunction> {
|
||||
model
|
||||
.semantic
|
||||
.as_ref()?
|
||||
@@ -1606,7 +1693,7 @@ fn function_at(
|
||||
}
|
||||
|
||||
fn function_call_button(
|
||||
function: &crate::protocol::analysis_v2::SemanticFunction,
|
||||
function: &crate::protocol::analysis_v3::SemanticFunction,
|
||||
label: &str,
|
||||
) -> String {
|
||||
format!(
|
||||
@@ -1616,7 +1703,7 @@ fn function_call_button(
|
||||
)
|
||||
}
|
||||
|
||||
fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunction) -> String {
|
||||
fn function_params_json(function: &crate::protocol::analysis_v3::SemanticFunction) -> String {
|
||||
serde_json::json!(function
|
||||
.signature
|
||||
.params
|
||||
|
||||
+16
-6
@@ -1,4 +1,8 @@
|
||||
//! Renderer input for one explicitly selected, already verified terminal result.
|
||||
//!
|
||||
//! The overlay is bound to the exact pre-run Analysis bytes and to the
|
||||
//! Observation v1 terminal: View never emits a result whose observation run id,
|
||||
//! capture level or truncation state disagrees with the verified run.
|
||||
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -13,29 +17,35 @@ pub struct SnapshotSource {
|
||||
pub lock_digest: Option<String>,
|
||||
}
|
||||
|
||||
/// Exact contract revisions this overlay was produced against. There is no
|
||||
/// range negotiation: View only consumes Analysis 3 + Observation 1 + CLI Tool
|
||||
/// API revision 1.
|
||||
#[derive(Serialize)]
|
||||
pub struct SnapshotProtocols {
|
||||
pub struct SnapshotContracts {
|
||||
pub api_revision: u32,
|
||||
pub analysis: u32,
|
||||
pub trace: u32,
|
||||
pub events: u32,
|
||||
pub observation: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SnapshotExecution {
|
||||
pub included: bool,
|
||||
/// Observation v1 run id (`run.id`/`run_id`).
|
||||
pub core_run_id: String,
|
||||
pub core_version: String,
|
||||
pub target: String,
|
||||
pub status: &'static str,
|
||||
pub terminal_at: String,
|
||||
pub source_verified: bool,
|
||||
pub trace_status: String,
|
||||
/// `verified` | `truncated` | `invalid` | `stale` | `unavailable`.
|
||||
pub observation_status: String,
|
||||
pub capture_level: String,
|
||||
pub result_complete: bool,
|
||||
pub output_complete: bool,
|
||||
pub observation_truncated: bool,
|
||||
pub parameters: &'static str,
|
||||
pub mode: String,
|
||||
pub core_protocol: SnapshotProtocols,
|
||||
pub contracts: SnapshotContracts,
|
||||
}
|
||||
|
||||
pub struct ExportResultOverlay {
|
||||
@@ -45,6 +55,6 @@ pub struct ExportResultOverlay {
|
||||
pub value: Option<String>,
|
||||
pub stdout: Option<String>,
|
||||
pub stderr: Option<String>,
|
||||
pub trace_counts: Option<BTreeMap<String, u64>>,
|
||||
pub observation_counts: Option<BTreeMap<String, u64>>,
|
||||
pub arguments: Option<Vec<(String, String)>>,
|
||||
}
|
||||
+1
-1
@@ -64,7 +64,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
.unwrap_or(0)
|
||||
);
|
||||
if let Some(version) = state.service.core_version() {
|
||||
eprintln!("core: marqdo {version} (Analysis v2/v3, Trace v2)");
|
||||
eprintln!("core: marqdo {version} (Analysis v3, Observation v1)");
|
||||
} else if let Some(note) = state.service.core_note() {
|
||||
eprintln!("core: unavailable ({note})");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user