feat(epic3): уведомления об изменении Resource/Prompt каталога MCP (Story 3.19)
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Failing after 4m10s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Failing after 4m10s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
Story 3.19 / FR-19 на принятой базе Story 3.18 (`47a6e54`, PR #99): после commit опубликованного каталога Agent клиент получает `notifications/resources/list_changed` и/или `notifications/prompts/list_changed`, обе pinned revisions, а обычное чтение каталога остаётся авторитетным при потере сигнала. Scope ограничен list-change: `resources/subscribe`/`unsubscribe` остаются `-32601`, значение `resources.subscribe` остаётся `false` (одобренный владельцем вариант A). Публикация переносит только semantic delta Story 3.19 из `/home/codex/code/crank-worktrees/story31-worktree` (`1b6db09` + cumulative overlay) на принятый head 3.18, а не копирует worktree: - новый `protocol/signals.rs` (watcher, отпечаток каталога, bounded filter, revision-correct encoders, bounded legacy stream registry) и `protocol/signals_tests.rs` (17 unit oracles); - `subscriptions/listen` (modern-only dispatch registration) + честные `listChanged: true` объявления; `app/endpoint.rs` получает legacy GET producer/DELETE retire, `app/dispatch.rs` — modern listen stream; - ATDD `mcp_signals` 5 сценариев на реальном endpoint/PostgreSQL/artifact store; capability inventory и frozen/provenance проекции обновлены (`b90b59f3…`, inventory `10ca3538…`); - `scripts/ci-story-checks.sh`: добавлены 3.19-проверки, записи Story 3.18 сохранены (гейт не ослаблен). Принятая правка code-health `206ca78` сохранена: `app/endpoint.rs` 402 строки (было 381), `app/legacy_dispatch.rs` 731 без изменений, т.е. split не переписан. Новый ATDD-файл `mcp_signals.rs` до 1138 строк превышал лимит `scripts/check-rust-code-health.sh`, поэтому его сценарии механически вынесены в `mcp_signals/scenarios.rs` без изменения проверок. Наследованный дефект tooling-гейта: `tests/unit/test_validate_capability_inventory.py` требует, чтобы `Run tooling unit tests` шёл раньше `scripts/validate-capability-inventory.py`; в принятом `ci.yml` (3.18) шаг оказался в условном feature-job. Шаг перенесён в обязательный `rust` job перед проверкой inventory — исполняемый tooling-гейт теперь проверяется там же, где применяется; ни одна проверка не отключена и не ослаблена. Проверки на этом коммите: `ci-story-checks.sh` exit 0 — 4/9/1/12/10/3/5(+1 manual ignored)/17 passed; `crank-community-mcp --lib` 102/0; transport 20/0, mcp_prompts 15/0, revision_matrix::negotiation 23/0, era_isolation 5/0; `cargo fmt --check` и `cargo clippy -p crank-community-mcp -p mcp-server --all-targets -D warnings` — 0; `check-rust-code-health.sh` — pass; capability inventory `status=valid protocol_items=50 revisions=2`; `python3 -m unittest discover -s tests/unit` — 305 OK. NOT_RUN (честно, не PASS): полный `just verify`, межкомпонентная интеграция, нагрузка и квалификация ≥3 реальных клиентов — остаются на собранной фиче 3.20 по validation-policy.md.
This commit is contained in:
1 parent
47a6e54660
commit
a965bc4137
22 files changed
+2247
-55
No files matched your search
@@ -0,0 +1,411 @@
|
||||
//! Unit oracles of the Story 3.19 signal seam: the catalog projection, the bounded filter, the exact
|
||||
//! wire frames of both approved revisions and the bounded legacy stream ownership.
|
||||
|
||||
use std::{
|
||||
io,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use crank_core::ToolSelectionPolicy;
|
||||
use crank_core::ids::{PromptId, ResourceId};
|
||||
use crank_registry::PublishedAgentCatalog;
|
||||
use crank_registry::model::{AgentPromptBinding, AgentResourceBinding};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::{
|
||||
CatalogFingerprint, FilterOutcome, INVALID_LISTEN_FILTER, ListenFilter, MAX_FILTER_URIS,
|
||||
MAX_SUBSCRIPTION_ID_BYTES, PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, ReadError, Reader,
|
||||
SIGNAL_QUEUE_CAPACITY, SUBSCRIPTION_ID_KEY, SUBSCRIPTIONS_ACKNOWLEDGED, Signals,
|
||||
StreamRegistry, Watch, Wire, acknowledged_frame, run, subscription_id,
|
||||
};
|
||||
|
||||
fn catalog(
|
||||
resources: &[(&str, u32)],
|
||||
prompts: &[(&str, u32)],
|
||||
catalog_revision: &str,
|
||||
) -> PublishedAgentCatalog {
|
||||
PublishedAgentCatalog {
|
||||
agent_version: 1,
|
||||
catalog_revision: catalog_revision.to_owned(),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
tools: Vec::new(),
|
||||
resources: resources
|
||||
.iter()
|
||||
.map(|(id, version)| AgentResourceBinding {
|
||||
resource_id: ResourceId::new(*id),
|
||||
resource_version: *version,
|
||||
})
|
||||
.collect(),
|
||||
prompts: prompts
|
||||
.iter()
|
||||
.map(|(id, version)| AgentPromptBinding {
|
||||
prompt_id: PromptId::new(*id),
|
||||
prompt_version: *version,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_committed_resource_binding_is_a_resource_change_only() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(
|
||||
&[("res_a", 1), ("res_b", 1)],
|
||||
&[("prm_a", 1)],
|
||||
"rev-2",
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
assert!(!before.changes_since(&after).prompts);
|
||||
assert_eq!(
|
||||
before.changes_since(&after),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_committed_prompt_binding_is_a_prompt_change_only() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 2)], "rev-2"));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: false,
|
||||
prompts: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_version_bump_is_a_change_even_when_the_binding_names_are_stable() {
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[("res_a", 2)], &[("prm_a", 1)], "rev-1"));
|
||||
|
||||
assert_eq!(
|
||||
after.changes_since(&before),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tool_only_catalog_commit_is_silent() {
|
||||
// `catalog_revision` moved, but the visible Resource/Prompt projection did not: a Tool-only
|
||||
// commit must not produce a Resource or Prompt list-change signal.
|
||||
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
||||
let after = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-2"));
|
||||
|
||||
assert!(!after.changes_since(&before).any());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_projection_is_order_independent_and_has_no_duplicate_growth() {
|
||||
let forward = CatalogFingerprint::of(&catalog(
|
||||
&[("res_a", 1), ("res_b", 2)],
|
||||
&[("prm_a", 1), ("prm_b", 2)],
|
||||
"rev-1",
|
||||
));
|
||||
let reversed = CatalogFingerprint::of(&catalog(
|
||||
&[("res_b", 2), ("res_a", 1)],
|
||||
&[("prm_b", 2), ("prm_a", 1)],
|
||||
"rev-1",
|
||||
));
|
||||
|
||||
assert!(!reversed.changes_since(&forward).any());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_legacy_frames_carry_a_closed_method_name_and_no_parameters() {
|
||||
let frames = Wire::Legacy.signal_frames(Signals::BOTH);
|
||||
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![
|
||||
json!({"jsonrpc": "2.0", "method": RESOURCE_LIST_CHANGED}).to_string(),
|
||||
json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string(),
|
||||
]
|
||||
);
|
||||
// No URI, name or payload of a changed object is part of a list-change notification.
|
||||
assert!(frames.iter().all(|frame| !frame.contains("uri")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_modern_frames_carry_the_subscription_id_of_their_listen_request() {
|
||||
let id = json!(41);
|
||||
let frames = Wire::Modern(id.clone()).signal_frames(Signals::BOTH);
|
||||
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": RESOURCE_LIST_CHANGED,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||
})
|
||||
.to_string(),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": PROMPT_LIST_CHANGED,
|
||||
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
||||
})
|
||||
.to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Value>(&frames[0]).unwrap()["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
||||
id
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_requested_and_honoured_types_are_encoded() {
|
||||
let frames = Wire::Modern(json!(1)).signal_frames(Signals {
|
||||
resources: false,
|
||||
prompts: true,
|
||||
});
|
||||
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert!(frames[0].contains(PROMPT_LIST_CHANGED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_acknowledgment_reports_exactly_the_honoured_subset() {
|
||||
let frame: Value = serde_json::from_str(&acknowledged_frame(
|
||||
&json!(7),
|
||||
Signals {
|
||||
resources: true,
|
||||
prompts: false,
|
||||
},
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(frame["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
||||
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(7));
|
||||
assert_eq!(
|
||||
frame["params"]["notifications"],
|
||||
json!({ "resourcesListChanged": true })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_honoured_subset_is_an_empty_filter_object() {
|
||||
let frame: Value =
|
||||
serde_json::from_str(&acknowledged_frame(&json!("sub-1"), Signals::default())).unwrap();
|
||||
|
||||
assert_eq!(frame["params"]["notifications"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filter_keeps_only_the_implemented_list_change_types() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({
|
||||
"toolsListChanged": true,
|
||||
"promptsListChanged": true,
|
||||
"resourcesListChanged": false,
|
||||
"resourceSubscriptions": ["file:///project/config.json"]
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Accepted(signals) => assert_eq!(
|
||||
signals,
|
||||
Signals {
|
||||
resources: false,
|
||||
prompts: true
|
||||
}
|
||||
),
|
||||
FilterOutcome::Invalid(detail) => panic!("a bounded filter must be accepted: {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absent_filter_field_means_not_subscribed() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({})).unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Accepted(signals) => assert!(!signals.any()),
|
||||
FilterOutcome::Invalid(detail) => panic!("an empty filter must be accepted: {detail}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_uri_filter_is_refused_without_echoing_it() {
|
||||
let filter: ListenFilter = serde_json::from_value(json!({
|
||||
"resourceSubscriptions": (0..=MAX_FILTER_URIS)
|
||||
.map(|index| format!("file:///resource-{index}"))
|
||||
.collect::<Vec<_>>()
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
match filter.accepted() {
|
||||
FilterOutcome::Invalid(detail) => assert_eq!(detail, INVALID_LISTEN_FILTER),
|
||||
FilterOutcome::Accepted(_) => panic!("an oversized filter must be refused"),
|
||||
}
|
||||
|
||||
let oversized: ListenFilter = serde_json::from_value(json!({
|
||||
"resourceSubscriptions": ["u".repeat(super::MAX_FILTER_URI_BYTES + 1)]
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
oversized.accepted(),
|
||||
FilterOutcome::Invalid(INVALID_LISTEN_FILTER)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_object_filter_is_a_deserialization_error() {
|
||||
assert!(serde_json::from_value::<ListenFilter>(json!(["toolsListChanged"])).is_err());
|
||||
assert!(serde_json::from_value::<ListenFilter>(json!({"promptsListChanged": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_subscription_id_is_bound_by_its_encoded_size() {
|
||||
assert_eq!(subscription_id(&json!(1)), Some(json!(1)));
|
||||
assert_eq!(subscription_id(&json!("sub-1")), Some(json!("sub-1")));
|
||||
assert_eq!(
|
||||
subscription_id(&json!("x".repeat(MAX_SUBSCRIPTION_ID_BYTES))),
|
||||
None,
|
||||
"an id longer than the frame bound must not be used as a subscription id"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_legacy_stream_supersedes_the_previous_one() {
|
||||
let streams = StreamRegistry::new();
|
||||
let first = streams.admit("session-1").unwrap();
|
||||
let second = streams.admit("session-1").unwrap();
|
||||
|
||||
assert!(!streams.is_current("session-1", first));
|
||||
assert!(streams.is_current("session-1", second));
|
||||
// Another session is unaffected.
|
||||
let other = streams.admit("session-2").unwrap();
|
||||
assert!(streams.is_current("session-2", other));
|
||||
|
||||
streams.retire("session-1");
|
||||
assert!(!streams.is_current("session-1", second));
|
||||
assert!(streams.is_current("session-2", other));
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct SharedLogWriter {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl SharedLogWriter {
|
||||
fn output(&self) -> String {
|
||||
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedLogWriter {
|
||||
type Writer = SharedLogGuard;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
SharedLogGuard {
|
||||
buffer: Arc::clone(&self.buffer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SharedLogGuard {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl io::Write for SharedLogGuard {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
self.buffer.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// AC-2: a failed committed-catalog read is observable and loses nothing — the tick is skipped (no
|
||||
/// fabricated signal, no write path that could roll the catalog back) while the baseline survives, so
|
||||
/// the next successful read still reports the change of the committed catalog.
|
||||
#[tokio::test]
|
||||
async fn a_failed_catalog_read_is_observable_and_loses_no_committed_change() {
|
||||
let writer = SharedLogWriter::default();
|
||||
let subscriber = crank_observability::build_subscriber(
|
||||
crank_observability::ObservabilityConfig::new(
|
||||
crank_observability::ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
|
||||
"info",
|
||||
crank_observability::RedactionLimits::default(),
|
||||
),
|
||||
writer.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let dispatch = tracing::Dispatch::new(subscriber);
|
||||
let _guard = tracing::dispatcher::set_default(&dispatch);
|
||||
|
||||
let baseline = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
||||
let committed = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 1)], "rev-2"));
|
||||
let script = Arc::new(Mutex::new(
|
||||
vec![Ok(baseline), Err(ReadError::Retry), Ok(committed)].into_iter(),
|
||||
));
|
||||
let reader: Reader = Box::new(move || {
|
||||
let next = script
|
||||
.lock()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap_or(Err(ReadError::Retry));
|
||||
Box::pin(async move { next })
|
||||
});
|
||||
|
||||
let (sender, mut receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
||||
tokio::spawn(run(
|
||||
Watch {
|
||||
workspace_slug: "workspace-canary".to_owned(),
|
||||
agent_slug: "agent-canary".to_owned(),
|
||||
signals: Signals::BOTH,
|
||||
wire: Wire::Legacy,
|
||||
legacy_stream: None,
|
||||
deadline: Some(Instant::now() + Duration::from_millis(2_100)),
|
||||
},
|
||||
sender,
|
||||
reader,
|
||||
));
|
||||
|
||||
let mut frames = Vec::new();
|
||||
while let Some(frame) = receiver.recv().await {
|
||||
frames.push(frame);
|
||||
}
|
||||
|
||||
// The failed tick produced no frame; the committed change of the next successful read did.
|
||||
assert_eq!(
|
||||
frames,
|
||||
vec![json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string()]
|
||||
);
|
||||
|
||||
let output = writer.output();
|
||||
let failures: Vec<Value> = output
|
||||
.lines()
|
||||
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
|
||||
.filter(|event| event["event"] == "mcp.signals.read_failed")
|
||||
.collect();
|
||||
assert!(
|
||||
!failures.is_empty(),
|
||||
"a skipped tick must be observable: {output}"
|
||||
);
|
||||
for event in &failures {
|
||||
assert_eq!(event["fields"]["error_category"], "catalog");
|
||||
}
|
||||
// Closed vocabulary: no workspace, Agent, URI or raw database text is read into the event.
|
||||
assert!(!output.contains("workspace-canary"));
|
||||
assert!(!output.contains("agent-canary"));
|
||||
}
|
||||
Reference in new issue
Block a user