Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/patches/d67f7a5e8bbd4610 # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## B3: every new revision carries a full intent record and stays inside its declared footprint closed `d67f7a5e8bbd4610` #112 · opened 2026-10-18 17:29 UTC · closed 2026-10-29 18:59 UTC Imported from GitHub aien-dev/synapse#112, by drakestapleton Base `2f06c455a5af8a5db7e0230c3692f08db21f61f2` · Head `55e1e42ee13ab6397b521ceeb0fa8ab5bedfeed5` drakestapleton wrote on 2026-10-18 17:29 UTC Closes #31. ## What Core `intent.rs` IntentRecord. A revision's intent is now either the old v2 summary or a v3 record; the store refuses new revisions that carry only a summary (`IntentRecordRequired`) and refuses changes outside the declared footprint (`MutationOutsideFootprint`). The context blob is stored and retained. API v3 `scope.paths` is the footprint. Derived revisions (B5) keep the v2 summary. ## Evidence (worker run, verified by the desk before merge) - `cargo test --workspace --locked --no-fail-fast`: 408 passed, 0 failed; clippy -D warnings and fmt clean. - Red evidence in `evidence/b3-intent-record` (mutations turn tests red). ## Not covered - Expect a small textual conflict with B2 (#30 branch `synapse/30-operation-views`): both edit store `revision.rs` test helpers and core `lib.rs` refusal codes. Whichever merges second gets rebased by the desk. 🤖 Generated with Claude Code drakestapleton wrote on 2026-10-29 18:59 UTC Closing in org cleanup (Drake, 2026-10-29): abandoned: no activity in 11 days (>= 7 days), merge conflicts with base, failing checks with no follow-up. Reopen if still needed. ### Apply it ``` git checkout -b patch-d67f7a5e8bbd4610 2f06c455a5af8a5db7e0230c3692f08db21f61f2 curl -fsSL https://interplane.io/drakestapleton/synapse/patches/d67f7a5e8bbd4610.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/synapse 112 55e1e42ee13ab6397b521ceeb0fa8ab5bedfeed5 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"synapse","number":112,"url":"https://github.com/aien-dev/synapse/pull/112","export_sha256":"1c576073d3642d6130bfff61541dda3d27f03618b9224cb72ff5d1ad6d163116","imported_utc":"2026-11-18T16:39:09Z"} ``` ### Changes ``` diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs index f41f7de..e708e91 100644 --- a/crates/synapse-api/src/lib.rs +++ b/crates/synapse-api/src/lib.rs @@ -633,11 +633,20 @@ impl SynapseService { let envelope = ChangesetEnvelopeV2::decode(&req.payload)?; let content = &envelope.content; check_join_scope(req, content.change_id)?; - let paths: Vec = content.mutations.iter().map(|m| m.path.clone()).collect(); - if req.scope.paths != paths { + let Some(intent) = content.intent.record() else { + return Err(SynapseError::new( + RefusalCode::IntentRecordRequired, + "an agent revision needs an IntentRecord, not only a free-text summary (B3)", + )); + }; + // The request scope is the declared footprint, so F1 checks the whole footprint + // against the chain's `Propose` path scope; the content rules already put every + // mutation inside the footprint (`MutationOutsideFootprint`). + content.validate()?; + if req.scope.paths != intent.footprint { return Err(SynapseError::new( RefusalCode::AuthPathOutOfScope, - "request scope paths must be exactly the revision's mutation paths", + "request scope paths must be exactly the revision's declared footprint", )); } self.auth.authorize_chain( diff --git a/crates/synapse-api/tests/b1_chained_revisions.rs b/crates/synapse-api/tests/b1_chained_revisions.rs index 1240c45..21ab2d3 100644 --- a/crates/synapse-api/tests/b1_chained_revisions.rs +++ b/crates/synapse-api/tests/b1_chained_revisions.rs @@ -11,8 +11,8 @@ use synapse_auth::{ }; use synapse_core::{ encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, - GitOid, IdempotencyKey, MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RepoId, - RevisionContent, RevisionState, TreeDigest, WalSeq, + GitOid, IdempotencyKey, IntentKind, IntentRecord, MutationOp, ObsolescenceMarker, PathMutation, + RefusalCode, RepoId, RevisionContent, RevisionIntent, RevisionState, TreeDigest, WalSeq, }; use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits}; @@ -160,7 +160,10 @@ impl Fx { size_bytes: body.len() as u64, }, }], - intent_summary: "implement the task".into(), + intent: RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + vec!["src/lib.rs".into()], + )), }; ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey([idem; 32]), NOW) } @@ -297,6 +300,10 @@ fn b1_api_refuses_paths_outside_scope_foreign_authors_and_unknown_bases() { // W's path scope is `src`: a revision touching `docs` is refused by F1. let mut env = fx.envelope(&w.0, b"doc", 2); env.content.mutations[0].path = "docs/x.md".into(); + env.content.intent = RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + vec!["docs/x.md".into()], + )); let env = ChangesetEnvelopeV2::sign_new(&w.0, repo(), env.content, IdempotencyKey([2; 32]), NOW); let req = fx.request(&w, vec!["docs/x.md".into()], env.encode()); @@ -330,3 +337,120 @@ fn b1_api_refuses_paths_outside_scope_foreign_authors_and_unknown_bases() { RefusalCode::BaseTreeNotFound ); } + +// --------------------------------------------------------------------------------------- +// ADR 0003 step B3: IntentRecord and claims through the API +// --------------------------------------------------------------------------------------- + +/// An envelope of `author` whose intent is `intent`, upserting `src/lib.rs` with `body`. +fn b3_envelope( + fx: &Fx, + author: &SigningKey, + intent: RevisionIntent, + body: &[u8], + idem: u8, +) -> ChangesetEnvelopeV2 { + let mut env = fx.envelope(author, body, idem); + env.content.intent = intent; + ChangesetEnvelopeV2::sign_new(author, repo(), env.content, IdempotencyKey([idem; 32]), NOW) +} + +fn footprint(paths: &[&str]) -> RevisionIntent { + RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + paths.iter().map(|p| p.to_string()).collect(), + )) +} + +/// Acceptance: envelopes with only free text are refused. A worker inside its scope sends a +/// content version 2 envelope (free-text summary only): refused with `IntentRecordRequired` +/// and nothing is written; the same work with an `IntentRecord` is admitted. +#[test] +fn b3_api_free_text_only_envelope_is_refused() { + let mut fx = Fx::new("b3-free-text"); + let w = fx.w.clone(); + let body = b"free text"; + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + let env = b3_envelope( + &fx, + &w.0, + RevisionIntent::Summary("implement the task".into()), + body, + 1, + ); + let before = fx.svc.store().committed_seq(); + let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, + RefusalCode::IntentRecordRequired + ); + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + let env = b3_envelope(&fx, &w.0, footprint(&["src/lib.rs"]), body, 2); + let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); + assert!(matches!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap(), + RevisionOutcome::Admitted { .. } + )); +} + +/// Acceptance: a mutation outside the declared footprint is refused (`MutationOutsideFootprint`) +/// before any write, even when the chain's path scope covers it. +#[test] +fn b3_api_mutation_outside_declared_footprint_is_refused() { + let mut fx = Fx::new("b3-footprint"); + let w = fx.w.clone(); + let body = b"outside"; + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + let before = fx.svc.store().committed_seq(); + for declared in [&["src/main.rs"][..], &["src/lib"], &["docs"]] { + let env = b3_envelope(&fx, &w.0, footprint(declared), body, 1); + let paths = declared.iter().map(|p| p.to_string()).collect(); + let req = fx.request(&w, paths, env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, + RefusalCode::MutationOutsideFootprint, + "{declared:?}" + ); + } + assert_eq!(fx.svc.store().committed_seq(), before, "nothing written"); + // A directory footprint holds the mutation. + let env = b3_envelope(&fx, &w.0, footprint(&["src"]), body, 2); + let req = fx.request(&w, vec!["src".into()], env.encode()); + assert!(matches!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap(), + RevisionOutcome::Admitted { .. } + )); +} + +/// ADR 0003 section 5.2: the footprint must lie inside the submitter's `Propose` scope. The +/// request scope of a revision is exactly its footprint, so F1 checks every footprint entry; +/// worker `W` (path scope `src`) declaring `docs` beside `src/lib.rs` is refused, and a request +/// scope that is not exactly the footprint is refused. +#[test] +fn b3_api_footprint_must_lie_inside_the_propose_scope() { + let mut fx = Fx::new("b3-scope"); + let w = fx.w.clone(); + let body = b"scoped"; + let blobs = vec![(BlobDigest::compute(body), body.to_vec())]; + let wide = footprint(&["docs", "src/lib.rs"]); + let env = b3_envelope(&fx, &w.0, wide, body, 1); + let req = fx.request(&w, vec!["docs".into(), "src/lib.rs".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, + RefusalCode::AuthPathOutOfScope + ); + // Hiding the wide footprint behind a request scope of only the mutation paths. + let req = fx.request(&w, vec!["src/lib.rs".into()], env.encode()); + assert_eq!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap_err().code, + RefusalCode::AuthPathOutOfScope + ); + // `O` holds the whole repository: the same footprint is admitted. + let o = fx.o.clone(); + let env = b3_envelope(&fx, &o.0, footprint(&["docs", "src/lib.rs"]), body, 3); + let req = fx.request(&o, vec!["docs".into(), "src/lib.rs".into()], env.encode()); + assert!(matches!( + fx.svc.submit_revision(&req, &blobs, NOW).unwrap(), + RevisionOutcome::Admitted { .. } + )); +} diff --git a/crates/synapse-api/tests/b4_revision_states.rs b/crates/synapse-api/tests/b4_revision_states.rs index 7ea75a5..b70060c 100644 --- a/crates/synapse-api/tests/b4_revision_states.rs +++ b/crates/synapse-api/tests/b4_revision_states.rs @@ -14,8 +14,8 @@ use synapse_auth::{ }; use synapse_core::{ encode_did_key_ed25519, BlobDigest, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, - GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, - RevisionState, TreeDigest, WalSeq, + GitOid, IdempotencyKey, IntentKind, IntentRecord, MutationOp, PathMutation, RefusalCode, + RepoId, RevisionContent, RevisionIntent, RevisionState, TreeDigest, WalSeq, }; use synapse_store::{FsyncPolicy, RecoveryPolicy, RevisionOutcome, StoreLimits, StoredRevision}; @@ -209,7 +209,10 @@ impl Fx { size_bytes: body.len() as u64, }, }], - intent_summary: "implement the task".into(), + intent: RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + vec!["src/lib.rs".into()], + )), }; let env = ChangesetEnvelopeV2::sign_new(&who.0, repo(), content, IdempotencyKey([idem; 32]), NOW); diff --git a/crates/synapse-api/tests/b5_derivation_attestation.rs b/crates/synapse-api/tests/b5_derivation_attestation.rs index a03f518..78e5e2a 100644 --- a/crates/synapse-api/tests/b5_derivation_attestation.rs +++ b/crates/synapse-api/tests/b5_derivation_attestation.rs @@ -28,9 +28,9 @@ use synapse_auth::{ }; use synapse_core::{ BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, DerivationAttestation, - DerivationInput, DerivationRule, DerivedRevision, FileMode, GitOid, IdempotencyKey, MergeTier, - MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, RevisionState, TreeDigest, - WalSeq, WitnessSigner, + DerivationInput, DerivationRule, DerivedRevision, FileMode, GitOid, IdempotencyKey, IntentKind, + IntentRecord, MergeTier, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, + RevisionIntent, RevisionState, TreeDigest, WalSeq, WitnessSigner, }; use synapse_radicle::{ IdentityDocumentDigest, IdentityEdit, IdentityLog, RepositoryIdentityDocument, @@ -173,7 +173,7 @@ fn agent_revision(s: &str, base: TreeDigest, path: &str, body: &[u8]) -> Changes base_tree: base, parents: vec![], mutations: vec![upsert(path, body)], - intent_summary: format!("agent revision {s}"), + intent: RevisionIntent::Record(IntentRecord::new(IntentKind::Feature, vec![path.into()])), }; ChangesetEnvelopeV2::sign_new( &key(&format!("agent {s}")), @@ -394,7 +394,7 @@ fn b5_replica_recomputes_every_derived_revision_and_gets_the_same_digests() { assert_eq!(rebase.content.change_id, fx.ra.content.change_id); assert_eq!(rebase.content.base_tree, fx.b1); assert_eq!(rebase.content.mutations, fx.ra.content.mutations); - assert_eq!(rebase.content.intent_summary, fx.ra.content.intent_summary); + assert_eq!(rebase.content.intent, fx.ra.content.intent); // A merge's parents are the merged revisions in the canonical order. let mut parents = vec![fx.ra.changeset_id(), fx.rb.changeset_id()]; parents.sort(); @@ -662,7 +662,7 @@ fn b5_attestation_signed_by_another_key_is_refused_at_admission_and_replay() { fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationSignatureInvalid); // The registered key's attestation presented with content it does not name. let mut swapped = honest.clone(); - swapped.content.intent_summary = "a different intent".into(); + swapped.content.intent = RevisionIntent::Summary("a different intent".into()); fx.refused_at_admission_and_replay(at, swapped, RefusalCode::DerivationSignatureInvalid); // A field changed after signing. let mut tampered = honest.clone(); @@ -768,6 +768,12 @@ fn b5_recomputation_that_disagrees_is_refused_at_admission_and_replay() { // The right inputs and rule with other content (an extra mutation the rule never makes). let mut content = honest.content.clone(); content.mutations.push(upsert("src/z.rs", b"a1")); + // Declared in the footprint too, so the content rules (B3) pass and the rule is what + // refuses it. + if let RevisionIntent::Record(r) = &mut content.intent { + r.footprint.push("src/z.rs".into()); + r.footprint.sort(); + } let forged = forge(&fx.server, content, a.rule, a.inputs.clone(), a.output_tree); fx.refused_at_admission_and_replay(at, forged, RefusalCode::DerivationRecomputeMismatch); // `rc` changed docs/x.md, which `B1` also changed: the rebase conflicts and cannot be diff --git a/crates/synapse-core/src/derivation.rs b/crates/synapse-core/src/derivation.rs index 7f334d3..8d4da11 100644 --- a/crates/synapse-core/src/derivation.rs +++ b/crates/synapse-core/src/derivation.rs @@ -18,8 +18,8 @@ use crate::revision::{malformed, put_str, Reader}; use crate::{ encode_did_key_ed25519, AdmissionWitness, ChainPath, ChangeId, ChangesetId, IdempotencyKey, - PathMutation, RefusalCode, RepoId, RevisionContent, SynapseError, SynapseResult, TreeDigest, - WalSeq, WitnessSigner, + PathMutation, RefusalCode, RepoId, RevisionContent, RevisionIntent, SynapseError, + SynapseResult, TreeDigest, WalSeq, WitnessSigner, }; use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use sha2::{Digest, Sha256}; @@ -608,7 +608,10 @@ pub fn derive_revision_output( base_tree: *base, parents: ids.clone(), mutations, - intent_summary: format!("merge tier T0 of {} revisions", ids.len()), + intent: RevisionIntent::Summary(format!( + "merge tier T0 of {} revisions", + ids.len() + )), }; content.validate()?; let tree = trees.apply_mutations(*base, &content.mutations)?; @@ -729,7 +732,7 @@ mod tests { size_bytes: 1, }, }], - intent_summary: "derived".into(), + intent: RevisionIntent::Summary("derived".into()), }; let attestation = DerivationAttestation::sign( &server(), diff --git a/crates/synapse-core/src/intent.rs b/crates/synapse-core/src/intent.rs new file mode 100644 index 0000000..4844381 --- /dev/null +++ b/crates/synapse-core/src/intent.rs @@ -0,0 +1,742 @@ +//! `IntentRecord` and claims (ADR 0003 section 5.2, section 9 step B3). +//! +//! The free-text `intent_summary` of envelope v2 content is replaced by an [`IntentRecord`]: +//! +//! * `kind`: a closed [`IntentKind`]. +//! * `task`: an optional typed [`TaskRef`] (a tracker issue or a ledger lane), never free text. +//! * `claims`: machine-checkable [`Claim`]s; every [`ClaimKind`] names exactly one +//! [`PredicateType`], the type of receipt predicate that discharges it (step E1). +//! * `footprint`: the paths the change intends to touch, as path prefixes with the F1 +//! segment-boundary rule. Every actual mutation must lie inside it +//! (`MutationOutsideFootprint`). +//! * `supersedes`: revisions this one replaces (also expressed as obsolescence markers). +//! * `context`: the optional `BlobDigest` of a machine-readable rationale blob, stored and +//! retained with the revision, never part of any decision rule. +//! +//! The binary form is canonical (ADR 0003 principle P5): one encoding per value, every length +//! checked against the bytes that remain before anything is allocated, and any other byte +//! sequence refused with `EnvelopeMalformed` (`docs/B3_INTENT_RECORD.md` section 2). + +use crate::revision::{malformed, put_str, Reader}; +use crate::{ + validate_repo_relative_path, BlobDigest, ChangesetId, PathMutation, RefusalCode, RepoId, + SynapseError, SynapseResult, +}; + +/// Most claims in one intent record. +pub const MAX_INTENT_CLAIMS: usize = 64; +/// Most footprint entries in one intent record. +pub const MAX_FOOTPRINT_ENTRIES: usize = 256; +/// Most superseded revisions in one intent record. +pub const MAX_SUPERSEDES: usize = 256; +/// Longest ledger lane name. +pub const MAX_LANE_BYTES: usize = 64; + +const MAX_PATH_BYTES: usize = 2048; +const TASK_TAG_NONE: u8 = 0; +const TASK_TAG_TRACKER_ISSUE: u8 = 1; +const TASK_TAG_LEDGER_LANE: u8 = 2; +const CONTEXT_TAG_NONE: u8 = 0; +const CONTEXT_TAG_BLOB: u8 = 1; +/// Encoded size of the smallest claim (`BehaviourUnchanged`: its tag only). +const MIN_CLAIM_BYTES: usize = 1; +/// Encoded size of the smallest footprint entry (`u32` length and one byte). +const MIN_FOOTPRINT_ENTRY_BYTES: usize = 4 + 1; + +/// The closed set of intent kinds (ADR 0003 section 5.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum IntentKind { + Fix, + Feature, + Refactor, + Revert, + Merge, + ResolveConflict, + Format, + DependencyUpdate, + Generated, +} + +impl IntentKind { + /// Every kind, in tag order. + pub const ALL: [IntentKind; 9] = [ + IntentKind::Fix, + IntentKind::Feature, + IntentKind::Refactor, + IntentKind::Revert, + IntentKind::Merge, + IntentKind::ResolveConflict, + IntentKind::Format, + IntentKind::DependencyUpdate, + IntentKind::Generated, + ]; + + pub fn tag(self) -> u8 { + match self { + IntentKind::Fix => 1, + IntentKind::Feature => 2, + IntentKind::Refactor => 3, + IntentKind::Revert => 4, + IntentKind::Merge => 5, + IntentKind::ResolveConflict => 6, + IntentKind::Format => 7, + IntentKind::DependencyUpdate => 8, + IntentKind::Generated => 9, + } + } + + pub fn from_tag(tag: u8) -> Option { + Self::ALL.into_iter().find(|k| k.tag() == tag) + } +} + +/// A typed reference to the work item a change serves: never free text. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TaskRef { + /// Issue `number` (at least 1) of tracker repository `repo`. + TrackerIssue { repo: RepoId, number: u64 }, + /// A ledger lane: 1..=64 bytes of `[a-z0-9._-]`, starting with `[a-z0-9]`. + LedgerLane { lane: String }, +} + +impl TaskRef { + fn validate(&self) -> SynapseResult<()> { + match self { + TaskRef::TrackerIssue { number, .. } => { + if *number == 0 { + return Err(malformed("task tracker issue number must be at least 1")); + } + } + TaskRef::LedgerLane { lane } => { + let b = lane.as_bytes(); + let ok = !b.is_empty() + && b.len() <= MAX_LANE_BYTES + && (b[0].is_ascii_lowercase() || b[0].is_ascii_digit()) + && b.iter().all(|c| { + c.is_ascii_lowercase() + || c.is_ascii_digit() + || matches!(c, b'.' | b'_' | b'-') + }); + if !ok { + return Err(malformed( + "task ledger lane must be 1..=64 bytes of [a-z0-9._-] starting with [a-z0-9]", + )); + } + } + } + Ok(()) + } +} + +/// The type of receipt predicate that discharges a claim (the in-toto predicate type of the +/// receipt that E1 accepts for it). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum PredicateType { + /// The named action passed on the revision's resulting tree. + ActionResult, + /// The public interface of a module is identical before and after. + InterfaceEquivalence, + /// Behaviour is unchanged (an equivalence or test receipt), as a `Refactor` claims. + BehaviourEquivalence, + /// The resulting tree equals the tree before the named revision. + ExactRevert, +} + +impl PredicateType { + /// Every predicate type. + pub const ALL: [PredicateType; 4] = [ + PredicateType::ActionResult, + PredicateType::InterfaceEquivalence, + PredicateType::BehaviourEquivalence, + PredicateType::ExactRevert, + ]; + + /// Stable name of the predicate type, as a receipt names it. + pub fn name(self) -> &'static str { + match self { + PredicateType::ActionResult => "synapse.predicate.action-result.v1", + PredicateType::InterfaceEquivalence => "synapse.predicate.interface-equivalence.v1", + PredicateType::BehaviourEquivalence => "synapse.predicate.behaviour-equivalence.v1", + PredicateType::ExactRevert => "synapse.predicate.exact-revert.v1", + } + } +} + +/// The kind of a claim, without its arguments. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ClaimKind { + ActionPasses, + InterfaceUnchanged, + BehaviourUnchanged, + RevertsRevision, +} + +impl ClaimKind { + /// Every claim kind, in tag order. + pub const ALL: [ClaimKind; 4] = [ + ClaimKind::ActionPasses, + ClaimKind::InterfaceUnchanged, + ClaimKind::BehaviourUnchanged, + ClaimKind::RevertsRevision, + ]; + + pub fn tag(self) -> u8 { + match self { + ClaimKind::ActionPasses => 1, + ClaimKind::InterfaceUnchanged => 2, + ClaimKind::BehaviourUnchanged => 3, + ClaimKind::RevertsRevision => 4, + } + } + + /// The one predicate type that discharges claims of this kind. + pub fn predicate_type(self) -> PredicateType { + match self { + ClaimKind::ActionPasses => PredicateType::ActionResult, + ClaimKind::InterfaceUnchanged => PredicateType::InterfaceEquivalence, + ClaimKind::BehaviourUnchanged => PredicateType::BehaviourEquivalence, + ClaimKind::RevertsRevision => PredicateType::ExactRevert, + } + } +} + +/// A machine-checkable assertion a change makes. Promotion needs each one discharged by a +/// passing receipt of its [`PredicateType`] on the revision's exact tree (steps E1 and E2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Claim { + /// Action `action` (the 32-byte action digest, `synapse_evidence::EvidenceActionDigest` + /// until E1) passes on the resulting tree. + ActionPasses { action: [u8; 32] }, + /// The public interface of the module at repository path `module` is unchanged. + InterfaceUnchanged { module: String }, + /// Behaviour is unchanged. + BehaviourUnchanged, + /// The change reverts revision `revision` exactly. + RevertsRevision { revision: ChangesetId }, +} + +impl Claim { + pub fn kind(&self) -> ClaimKind { + match self { + Claim::ActionPasses { .. } => ClaimKind::ActionPasses, + Claim::InterfaceUnchanged { .. } => ClaimKind::InterfaceUnchanged, + Claim::BehaviourUnchanged => ClaimKind::BehaviourUnchanged, + Claim::RevertsRevision { .. } => ClaimKind::RevertsRevision, + } + } + + /// The predicate type of the receipt that discharges this claim. + pub fn predicate_type(&self) -> PredicateType { + self.kind().predicate_type() + } + + fn encode_into(&self, buf: &mut Vec) { + buf.push(self.kind().tag()); + match self { + Claim::ActionPasses { action } => buf.extend_from_slice(action), + Claim::InterfaceUnchanged { module } => put_str(buf, module), + Claim::BehaviourUnchanged => {} + Claim::RevertsRevision { revision } => buf.extend_from_slice(&revision.0), + } + } + + fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(40); + self.encode_into(&mut buf); + buf + } + + fn decode_from(r: &mut Reader) -> SynapseResult { + match r.u8()? { + 1 => Ok(Claim::ActionPasses { action: r.array()? }), + 2 => Ok(Claim::InterfaceUnchanged { + module: r.string(MAX_PATH_BYTES)?, + }), + 3 => Ok(Claim::BehaviourUnchanged), + 4 => Ok(Claim::RevertsRevision { + revision: ChangesetId(r.array()?), + }), + tag => Err(malformed(format!("unknown claim tag {tag}"))), + } + } + + fn validate(&self) -> SynapseResult<()> { + if let Claim::InterfaceUnchanged { module } = self { + validate_repo_relative_path(module)?; + } + Ok(()) + } +} + +/// True when footprint entry `prefix` covers `path`: equal, or `path` continues it after a `/` +/// (the F1 `PathScope` segment-boundary rule). +pub fn footprint_entry_covers(prefix: &str, path: &str) -> bool { + path == prefix + || (path.len() > prefix.len() + && path.starts_with(prefix) + && path.as_bytes()[prefix.len()] == b'/') +} + +/// The machine-structured purpose of a revision (ADR 0003 section 5.2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IntentRecord { + pub kind: IntentKind, + pub task: Option, + /// Strictly ascending by canonical claim encoding, at most 64. + pub claims: Vec, + /// Path prefixes, strictly ascending, none covering another, 1..=256. + pub footprint: Vec, + /// Strictly ascending, at most 256. + pub supersedes: Vec, + /// Digest of a machine-readable rationale blob, stored and retained with the revision. + pub context: Option, +} + +impl IntentRecord { + /// A record of `kind` whose footprint is `footprint`, with no task, claims, supersedes, + /// or context. The footprint is put in canonical form (sorted, covered entries dropped). + pub fn new(kind: IntentKind, footprint: Vec) -> Self { + let mut sorted = footprint; + sorted.sort(); + sorted.dedup(); + let mut kept: Vec = Vec::with_capacity(sorted.len()); + for p in sorted { + if !kept.iter().any(|k| footprint_entry_covers(k, &p)) { + kept.push(p); + } + } + Self { + kind, + task: None, + claims: Vec::new(), + footprint: kept, + supersedes: Vec::new(), + context: None, + } + } + + /// True when some footprint entry covers `path`. + pub fn footprint_covers(&self, path: &str) -> bool { + self.footprint + .iter() + .any(|p| footprint_entry_covers(p, path)) + } + + /// The record's own rules: a valid task, valid claims in strictly ascending encoded order, + /// a canonical non-empty footprint of valid paths, strictly ascending supersedes. Refused + /// with `EnvelopeMalformed`, or `PathInvalid` for a bad path. + pub fn validate(&self) -> SynapseResult<()> { + if let Some(task) = &self.task { + task.validate()?; + } + if self.claims.len() > MAX_INTENT_CLAIMS { + return Err(malformed(format!( + "intent has {} claims, above {MAX_INTENT_CLAIMS}", + self.claims.len() + ))); + } + for c in &self.claims { + c.validate()?; + } + let encoded: Vec> = self.claims.iter().map(Claim::encode).collect(); + if !encoded.windows(2).all(|w| w[0] < w[1]) { + return Err(malformed( + "intent claims must be strictly ascending by canonical encoding", + )); + } + if self.footprint.is_empty() || self.footprint.len() > MAX_FOOTPRINT_ENTRIES { + return Err(malformed(format!( + "intent footprint must hold 1..={MAX_FOOTPRINT_ENTRIES} entries" + ))); + } + for p in &self.footprint { + validate_repo_relative_path(p)?; + } + let canonical = self.footprint.windows(2).all(|w| w[0] < w[1]) + && self.footprint.iter().enumerate().all(|(i, p)| { + self.footprint + .iter() + .enumerate() + .all(|(j, q)| i == j || !footprint_entry_covers(q, p)) + }); + if !canonical { + return Err(malformed( + "intent footprint must be strictly ascending with no entry covering another", + )); + } + if self.supersedes.len() > MAX_SUPERSEDES + || !self.supersedes.windows(2).all(|w| w[0] < w[1]) + { + return Err(malformed(format!( + "intent supersedes must be strictly ascending, at most {MAX_SUPERSEDES}" + ))); + } + Ok(()) + } + + /// [`Self::validate`], then every mutation path lies inside the footprint + /// (`MutationOutsideFootprint`). + pub fn validate_for(&self, mutations: &[PathMutation]) -> SynapseResult<()> { + self.validate()?; + if let Some(m) = mutations.iter().find(|m| !self.footprint_covers(&m.path)) { + return Err(SynapseError::new( + RefusalCode::MutationOutsideFootprint, + format!( + "mutation path {} lies outside the declared footprint", + m.path + ), + )); + } + Ok(()) + } + + /// `kind u8 | task | u32 n | claim* | u32 n | path str* | u32 n | id [32]* | context`, + /// where `task` is `0`, `1 | repo str | number u64`, or `2 | lane str`; a claim is + /// `1 | action [32]`, `2 | module str`, `3`, or `4 | revision [32]`; `context` is `0` or + /// `1 | blob [32]`. + pub fn encode_into(&self, buf: &mut Vec) { + buf.push(self.kind.tag()); + match &self.task { + None => buf.push(TASK_TAG_NONE), + Some(TaskRef::TrackerIssue { repo, number }) => { + buf.push(TASK_TAG_TRACKER_ISSUE); + put_str(buf, repo.as_str()); + buf.extend_from_slice(&number.to_le_bytes()); + } + Some(TaskRef::LedgerLane { lane }) => { + buf.push(TASK_TAG_LEDGER_LANE); + put_str(buf, lane); + } + } + buf.extend_from_slice(&(self.claims.len() as u32).to_le_bytes()); + for c in &self.claims { + c.encode_into(buf); + } + buf.extend_from_slice(&(self.footprint.len() as u32).to_le_bytes()); + for p in &self.footprint { + put_str(buf, p); + } + buf.extend_from_slice(&(self.supersedes.len() as u32).to_le_bytes()); + for s in &self.supersedes { + buf.extend_from_slice(&s.0); + } + match &self.context { + None => buf.push(CONTEXT_TAG_NONE), + Some(d) => { + buf.push(CONTEXT_TAG_BLOB); + buf.extend_from_slice(&d.0); + } + } + } + + /// Decode one record and refuse any encoding that is not canonical ([`Self::validate`]). + pub(crate) fn decode_from(r: &mut Reader) -> SynapseResult { + let tag = r.u8()?; + let kind = IntentKind::from_tag(tag) + .ok_or_else(|| malformed(format!("unknown intent kind {tag}")))?; + let task = match r.u8()? { + TASK_TAG_NONE => None, + TASK_TAG_TRACKER_ISSUE => Some(TaskRef::TrackerIssue { + repo: r.repo()?, + number: r.u64()?, + }), + TASK_TAG_LEDGER_LANE => Some(TaskRef::LedgerLane { + lane: r.string(MAX_LANE_BYTES)?, + }), + tag => return Err(malformed(format!("unknown task tag {tag}"))), + }; + let n = r.count(MAX_INTENT_CLAIMS, MIN_CLAIM_BYTES)?; + let mut claims = Vec::with_capacity(n); + for _ in 0..n { + claims.push(Claim::decode_from(r)?); + } + let n = r.count(MAX_FOOTPRINT_ENTRIES, MIN_FOOTPRINT_ENTRY_BYTES)?; + let mut footprint = Vec::with_capacity(n); + for _ in 0..n { + footprint.push(r.string(MAX_PATH_BYTES)?); + } + let n = r.count(MAX_SUPERSEDES, 32)?; + let mut supersedes = Vec::with_capacity(n); + for _ in 0..n { + supersedes.push(ChangesetId(r.array()?)); + } + let context = match r.u8()? { + CONTEXT_TAG_NONE => None, + CONTEXT_TAG_BLOB => Some(BlobDigest(r.array()?)), + tag => return Err(malformed(format!("unknown context tag {tag}"))), + }; + let record = Self { + kind, + task, + claims, + footprint, + supersedes, + context, + }; + record + .validate() + .map_err(|e| malformed(format!("intent record not canonical: {}", e.message)))?; + Ok(record) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + ChangeId, ChangesetEnvelopeV2, FileMode, IdempotencyKey, MutationOp, RevisionContent, + RevisionIntent, TreeDigest, ENVELOPE_V2_VERSION, INTENT_RECORD_CONTENT_VERSION, + }; + use ed25519_dalek::SigningKey; + use std::collections::BTreeSet; + + fn upsert(path: &str) -> PathMutation { + PathMutation { + path: path.into(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(b"x"), + size_bytes: 1, + }, + } + } + + fn full_record() -> IntentRecord { + let mut r = IntentRecord::new( + IntentKind::Refactor, + vec!["src".into(), "docs/B3.md".into()], + ); + r.task = Some(TaskRef::TrackerIssue { + repo: RepoId::new("aien-dev/synapse").unwrap(), + number: 31, + }); + r.claims = vec![ + Claim::ActionPasses { action: [3; 32] }, + Claim::InterfaceUnchanged { + module: "src/lib.rs".into(), + }, + Claim::BehaviourUnchanged, + Claim::RevertsRevision { + revision: ChangesetId([9; 32]), + }, + ]; + r.supersedes = vec![ChangesetId([1; 32]), ChangesetId([2; 32])]; + r.context = Some(BlobDigest::compute(b"plan")); + r + } + + fn content(intent: RevisionIntent, paths: &[&str]) -> RevisionContent { + RevisionContent { + change_id: ChangeId([7; 16]), + base_tree: TreeDigest([0x5A; 32]), + parents: vec![ChangesetId([1; 32])], + mutations: paths.iter().map(|p| upsert(p)).collect(), + intent, + } + } + + fn encoded(r: &IntentRecord) -> Vec { + let mut buf = Vec::new(); + r.encode_into(&mut buf); + buf + } + + fn decode(bytes: &[u8]) -> SynapseResult { + let mut r = Reader::new(bytes); + let rec = IntentRecord::decode_from(&mut r)?; + r.finish()?; + Ok(rec) + } + + /// Acceptance: every claim kind maps to a predicate type. The mapping is a bijection onto + /// `PredicateType::ALL`, every claim value reports the kind its encoding tags, and every + /// predicate type has its own stable name. + #[test] + fn b3_every_claim_kind_maps_to_a_predicate_type() { + let mapped: BTreeSet = + ClaimKind::ALL.iter().map(|k| k.predicate_type()).collect(); + assert_eq!( + mapped.len(), + ClaimKind::ALL.len(), + "one predicate type per kind" + ); + assert_eq!(mapped, PredicateType::ALL.into_iter().collect()); + let names: BTreeSet<&str> = PredicateType::ALL.iter().map(|p| p.name()).collect(); + assert_eq!(names.len(), PredicateType::ALL.len()); + let tags: BTreeSet = ClaimKind::ALL.iter().map(|k| k.tag()).collect(); + assert_eq!(tags.len(), ClaimKind::ALL.len()); + let claims = full_record().claims; + let kinds: BTreeSet = claims.iter().map(Claim::kind).collect(); + assert_eq!( + kinds, + ClaimKind::ALL.into_iter().collect(), + "fixture covers every kind" + ); + for c in &claims { + assert_eq!(c.encode()[0], c.kind().tag()); + assert_eq!(c.predicate_type(), c.kind().predicate_type()); + } + for k in IntentKind::ALL { + assert_eq!(IntentKind::from_tag(k.tag()), Some(k)); + } + assert_eq!(IntentKind::from_tag(0), None); + assert_eq!(IntentKind::from_tag(10), None); + } + + /// Acceptance: a mutation outside the declared footprint is refused, by the content rules + /// and so by every signed envelope; the F1 segment-boundary rule decides "inside". + #[test] + fn b3_mutation_outside_declared_footprint_is_refused() { + let rec = IntentRecord::new(IntentKind::Fix, vec!["src".into()]); + let inside = content(RevisionIntent::Record(rec.clone()), &["src", "src/a/b.rs"]); + assert_eq!(inside.validate(), Ok(())); + for outside in ["srcx/lib.rs", "README.md", "sr"] { + let c = content(RevisionIntent::Record(rec.clone()), &[outside]); + assert_eq!( + c.validate().unwrap_err().code, + RefusalCode::MutationOutsideFootprint, + "{outside}" + ); + let env = ChangesetEnvelopeV2::sign_new( + &SigningKey::from_bytes(&[1; 32]), + RepoId::new("aien-dev/synapse").unwrap(), + c, + IdempotencyKey([1; 32]), + 10, + ); + assert_eq!( + env.validate().unwrap_err().code, + RefusalCode::MutationOutsideFootprint + ); + let bytes = env.encode(); + assert_eq!( + ChangesetEnvelopeV2::decode(&bytes) + .unwrap() + .validate() + .unwrap_err() + .code, + RefusalCode::MutationOutsideFootprint + ); + } + // One mutation outside among several inside is enough. + let c = content(RevisionIntent::Record(rec), &["src/a.rs", "tests/a.rs"]); + assert_eq!( + c.validate().unwrap_err().code, + RefusalCode::MutationOutsideFootprint + ); + } + + #[test] + fn b3_intent_record_round_trips_and_non_canonical_bytes_are_refused() { + let rec = full_record(); + assert_eq!(rec.validate(), Ok(())); + let bytes = encoded(&rec); + assert_eq!(decode(&bytes).unwrap(), rec); + let c = content( + RevisionIntent::Record(rec.clone()), + &["docs/B3.md", "src/lib.rs"], + ); + let cb = c.encode(); + assert_eq!( + u16::from_le_bytes([cb[0], cb[1]]), + INTENT_RECORD_CONTENT_VERSION + ); + assert_eq!(RevisionContent::decode(&cb).unwrap(), c); + let lane = RevisionIntent::Record(IntentRecord { + task: Some(TaskRef::LedgerLane { + lane: "synapse-adr0003".into(), + }), + ..IntentRecord::new(IntentKind::Generated, vec!["a".into()]) + }); + let c = content(lane, &["a"]); + assert_eq!(RevisionContent::decode(&c.encode()).unwrap(), c); + + let refused = |r: IntentRecord| { + let e = decode(&encoded(&r)).unwrap_err(); + assert_eq!(e.code, RefusalCode::EnvelopeMalformed, "{e:?}"); + }; + let mut r = rec.clone(); + r.claims.swap(0, 1); + refused(r); + let mut r = rec.clone(); + r.claims.push(Claim::BehaviourUnchanged); + r.claims.sort_by_key(Claim::encode); + refused(r); + let mut r = rec.clone(); + r.footprint = vec!["src".into(), "docs/B3.md".into()]; + refused(r); + let mut r = rec.clone(); + r.footprint = vec!["src".into(), "src/lib.rs".into()]; + refused(r); + let mut r = rec.clone(); + r.footprint = vec![]; + refused(r); + let mut r = rec.clone(); + r.footprint = vec!["src/../x".into()]; + refused(r); + let mut r = rec.clone(); + r.supersedes.reverse(); + refused(r); + let mut r = rec.clone(); + r.task = Some(TaskRef::TrackerIssue { + repo: RepoId::new("aien-dev/synapse").unwrap(), + number: 0, + }); + refused(r); + for lane in ["", "Upper", "-x", "has space", &"a".repeat(65)] { + let mut r = rec.clone(); + r.task = Some(TaskRef::LedgerLane { lane: lane.into() }); + refused(r); + } + let mut r = rec.clone(); + r.claims = vec![Claim::InterfaceUnchanged { + module: "/abs".into(), + }]; + refused(r); + + // Unknown tags and trailing bytes. + let mut b = bytes.clone(); + b[0] = 0; + assert_eq!(decode(&b).unwrap_err().code, RefusalCode::EnvelopeMalformed); + let mut b = bytes.clone(); + b[1] = 9; + assert_eq!(decode(&b).unwrap_err().code, RefusalCode::EnvelopeMalformed); + let mut b = bytes.clone(); + let context_tag = b.len() - 33; + b[context_tag] = 2; + assert_eq!(decode(&b).unwrap_err().code, RefusalCode::EnvelopeMalformed); + let mut b = bytes.clone(); + b.push(0); + assert_eq!(decode(&b).unwrap_err().code, RefusalCode::EnvelopeMalformed); + // A claim count above the cap is refused before anything is reserved. + let mut r = IntentRecord::new(IntentKind::Fix, vec!["a".into()]); + r.claims = (0..=MAX_INTENT_CLAIMS as u8) + .map(|i| Claim::ActionPasses { action: [i; 32] }) + .collect(); + refused(r); + // Every truncation is refused, never a panic. + for n in 0..bytes.len() { + assert!(decode(&bytes[..n]).is_err(), "prefix {n}"); + } + } + + /// B3 leaves content version 2 exactly as B1 wrote it: the same bytes and the same + /// `ChangesetId` (golden value computed on main 2f06c45, before B3), so every existing + /// v2 record, attestation, and derived revision keeps its identity. + #[test] + fn b3_content_version_2_keeps_its_bytes_and_changeset_id() { + let v2 = content(RevisionIntent::Summary("add lib".into()), &["src/lib.rs"]); + let b = v2.encode(); + assert_eq!(u16::from_le_bytes([b[0], b[1]]), ENVELOPE_V2_VERSION); + assert_eq!( + v2.changeset_id().to_string(), + "9e6878fe29d91b27135e21ee94f6a21e4a0c6551de4a0cf6d911280c32c668e2" + ); + assert_eq!(RevisionContent::decode(&b).unwrap(), v2); + let v3 = content( + RevisionIntent::Record(IntentRecord::new(IntentKind::Feature, vec!["src".into()])), + &["src/lib.rs"], + ); + assert_ne!(v3.changeset_id(), v2.changeset_id()); + } +} diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 9966ad3..785275d 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -9,6 +9,7 @@ use sha2::{Digest, Sha256}; use std::fmt; mod derivation; +mod intent; mod revision; mod revision_state; mod tree; @@ -18,11 +19,16 @@ pub use derivation::{ DOMAIN_DERIVATION_ATTESTATION_V1, DOMAIN_DERIVATION_SIGN_V1, DOMAIN_DERIVED_MERGE_CHANGE_V1, MAX_DERIVATION_INPUTS, }; +pub use intent::{ + footprint_entry_covers, Claim, ClaimKind, IntentKind, IntentRecord, PredicateType, TaskRef, + MAX_FOOTPRINT_ENTRIES, MAX_INTENT_CLAIMS, MAX_LANE_BYTES, MAX_SUPERSEDES, +}; pub use revision::{ AdmissionWitness, AuthorshipAttestation, ChainPath, ChangesetEnvelopeV2, ObsolescenceKind, - ObsolescenceMarker, RevisionContent, WitnessSigner, DOMAIN_ADMISSION_WITNESS_V1, - DOMAIN_AUTHORSHIP_SIGN_V2, DOMAIN_CHANGESET_ID_V2, DOMAIN_OBSOLESCENCE_SIGN_V1, - ENVELOPE_V2_VERSION, MAX_CHAIN_PATH_DEPTH, MAX_OBSOLESCENCE_SUCCESSORS, + ObsolescenceMarker, RevisionContent, RevisionIntent, WitnessSigner, + DOMAIN_ADMISSION_WITNESS_V1, DOMAIN_AUTHORSHIP_SIGN_V2, DOMAIN_CHANGESET_ID_V2, + DOMAIN_OBSOLESCENCE_SIGN_V1, ENVELOPE_V2_VERSION, INTENT_RECORD_CONTENT_VERSION, + MAX_CHAIN_PATH_DEPTH, MAX_OBSOLESCENCE_SUCCESSORS, }; pub use revision_state::RevisionState; pub use tree::{ @@ -137,6 +143,12 @@ pub enum RefusalCode { /// it needs: the change's creating chain for a prune, or for a rewrite or split either the /// creating chain or the chain that first admitted the replaced revision (step B1). AuthChainNotDominant, + /// An agent envelope v2 whose content carries only a free-text intent summary (content + /// version 2) instead of an `IntentRecord` (ADR 0003 section 5.2, step B3). + IntentRecordRequired, + /// A revision mutates a path outside the footprint its `IntentRecord` declares (ADR 0003 + /// section 5.2, step B3). + MutationOutsideFootprint, /// An obsolescence marker names an unknown revision, a revision of another change, itself /// as its own successor, or would close a cycle of markers (step B1). ObsolescenceMarkerInvalid, diff --git a/crates/synapse-core/src/revision.rs b/crates/synapse-core/src/revision.rs index 0e257a6..b56e573 100644 --- a/crates/synapse-core/src/revision.rs +++ b/crates/synapse-core/src/revision.rs @@ -3,7 +3,8 @@ //! //! * A **revision** is one immutable version of a change. Its [`RevisionContent`] is what its //! v2 `ChangesetId` covers: the `ChangeId`, the native base `TreeDigest`, parent revisions, -//! path mutations, and the intent summary. Who submitted it and when are excluded, so a +//! path mutations, and the intent (an `IntentRecord` since B3, content version 3; the free-text +//! summary of content version 2 before it). Who submitted it and when are excluded, so a //! rewrite (new content, same `ChangeId`) gets a new `ChangesetId` while identical content //! from two agents is one revision. //! * An [`AuthorshipAttestation`] is an agent's signed statement that it produced a revision @@ -26,17 +27,21 @@ //! is allocated, and any other byte sequence refused with `EnvelopeMalformed` (or //! `EnvelopeVersionUnsupported` for an unknown content version). There is no serde form. +use crate::intent::IntentRecord; use crate::{ encode_did_key_ed25519, validate_intent_summary, validate_mutations, - validate_parent_changesets, ChangeId, ChangesetId, FileMode, IdempotencyKey, MutationOp, - PathMutation, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq, + validate_parent_changesets, BlobDigest, ChangeId, ChangesetId, FileMode, IdempotencyKey, + MutationOp, PathMutation, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq, MAX_INTENT_SUMMARY_BYTES, }; use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; use sha2::{Digest, Sha256}; -/// Content format version of envelope v2 (the first field of [`RevisionContent::encode`]). +/// Content format version of envelope v2 with a free-text intent (the first field of +/// [`RevisionContent::encode`]). pub const ENVELOPE_V2_VERSION: u16 = 2; +/// Content format version of envelope v2 whose intent is an [`IntentRecord`] (step B3). +pub const INTENT_RECORD_CONTENT_VERSION: u16 = 3; /// Domain tag of a v2 `ChangesetId` (v1 uses `SYNAPSE_CHANGESET_V1\0`). pub const DOMAIN_CHANGESET_ID_V2: &[u8] = b"SYNAPSE_CHANGESET_V2\0"; /// Domain tag of the Ed25519 signature of an [`AuthorshipAttestation`]. @@ -96,7 +101,7 @@ pub(crate) fn verify_ed25519( // --------------------------------------------------------------------------------------- /// What a v2 `ChangesetId` covers: the content of one revision, never who submitted it or -/// when. `IntentRecord` (step B3) and conflict terms (step D2) extend it under a later content +/// when. Conflict terms (step D2) extend it under a later content /// version. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RevisionContent { @@ -108,25 +113,61 @@ pub struct RevisionContent { pub parents: Vec, /// Path mutations, strictly ascending by path, at least one. pub mutations: Vec, - /// Free-text intent, 1..=4096 bytes (replaced by `IntentRecord` in step B3). - pub intent_summary: String, + /// The revision's intent: an `IntentRecord` (content version 3, step B3), or the free-text + /// summary of content version 2 (B1 records; refused at agent admission since B3). + pub intent: RevisionIntent, +} + +/// The intent a revision's content carries, which also fixes its content version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RevisionIntent { + /// Content version 2: free text, 1..=4096 bytes. Still decoded, replayed, and produced by + /// the B5 derivation rules, so every existing v2 `ChangesetId` keeps its value; an agent + /// envelope that carries only this is refused at admission (`IntentRecordRequired`). + Summary(String), + /// Content version 3: the machine-structured [`IntentRecord`] (ADR 0003 section 5.2). + Record(IntentRecord), +} + +impl RevisionIntent { + /// The content version this intent is encoded under. + pub fn content_version(&self) -> u16 { + match self { + RevisionIntent::Summary(_) => ENVELOPE_V2_VERSION, + RevisionIntent::Record(_) => INTENT_RECORD_CONTENT_VERSION, + } + } + + /// The intent record, if this is content version 3. + pub fn record(&self) -> Option<&IntentRecord> { + match self { + RevisionIntent::Record(r) => Some(r), + RevisionIntent::Summary(_) => None, + } + } } impl RevisionContent { - /// Parents strictly ascending, mutations non-empty on valid sorted unique paths, intent - /// summary 1..=4096 bytes (the same rules and refusal codes as envelope v1). + /// Parents strictly ascending, mutations non-empty on valid sorted unique paths (the same + /// rules and refusal codes as envelope v1); a free-text intent of 1..=4096 bytes, or an + /// intent record that is canonical and whose footprint holds every mutation path + /// (`MutationOutsideFootprint`). pub fn validate(&self) -> SynapseResult<()> { - validate_intent_summary(&self.intent_summary)?; validate_parent_changesets(&self.parents)?; - validate_mutations(&self.mutations) + validate_mutations(&self.mutations)?; + match &self.intent { + RevisionIntent::Summary(s) => validate_intent_summary(s.as_str()), + RevisionIntent::Record(r) => r.validate_for(&self.mutations), + } } - /// `version u16 (2) | change_id [16] | base_tree [32] | u32 count | parent [32]* | - /// u32 count | (path str | op)* | intent_summary str`, where `op` is `1 | mode u8 | - /// blob_digest [32] | size u64` (upsert) or `2` (delete) and `str` is `u32 len | UTF-8`. + /// `version u16 (2 or 3) | change_id [16] | base_tree [32] | u32 count | parent [32]* | + /// u32 count | (path str | op)* | intent`, where `op` is `1 | mode u8 | blob_digest [32] | + /// size u64` (upsert) or `2` (delete), `str` is `u32 len | UTF-8`, and `intent` is the + /// summary `str` under version 2 or the [`IntentRecord`] encoding under version 3. pub fn encode(&self) -> Vec { let mut buf = Vec::with_capacity(128 + 96 * self.mutations.len()); - buf.extend_from_slice(&ENVELOPE_V2_VERSION.to_le_bytes()); + buf.extend_from_slice(&self.intent.content_version().to_le_bytes()); buf.extend_from_slice(&self.change_id.0); buf.extend_from_slice(&self.base_tree.0); buf.extend_from_slice(&(self.parents.len() as u32).to_le_bytes()); @@ -150,7 +191,10 @@ impl RevisionContent { MutationOp::Delete => buf.push(OP_TAG_DELETE), } } - put_str(&mut buf, &self.intent_summary); + match &self.intent { + RevisionIntent::Summary(s) => put_str(&mut buf, s.as_str()), + RevisionIntent::Record(r) => r.encode_into(&mut buf), + } buf } @@ -164,7 +208,7 @@ impl RevisionContent { pub(crate) fn decode_from(r: &mut Reader) -> SynapseResult { let version = r.u16()?; - if version != ENVELOPE_V2_VERSION { + if version != ENVELOPE_V2_VERSION && version != INTENT_RECORD_CONTENT_VERSION { return Err(SynapseError::new( RefusalCode::EnvelopeVersionUnsupported, format!("unsupported revision content version {version}"), @@ -197,16 +241,32 @@ impl RevisionContent { }; mutations.push(PathMutation { path, op }); } - let intent_summary = r.string(MAX_INTENT_SUMMARY_BYTES)?; + let intent = if version == ENVELOPE_V2_VERSION { + RevisionIntent::Summary(r.string(MAX_INTENT_SUMMARY_BYTES)?) + } else { + RevisionIntent::Record(IntentRecord::decode_from(r)?) + }; Ok(Self { change_id, base_tree, parents, mutations, - intent_summary, + intent, }) } + /// Every blob this content references: each upserted blob, then the intent's context blob. + /// Retention keeps all of them while the revision is kept. + pub fn referenced_blobs(&self) -> impl Iterator + '_ { + self.mutations + .iter() + .filter_map(|m| match &m.op { + MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest), + MutationOp::Delete => None, + }) + .chain(self.intent.record().and_then(|r| r.context)) + } + /// `SHA-256(DOMAIN_CHANGESET_ID_V2 || u64 len || encode())`: content only. pub fn changeset_id(&self) -> ChangesetId { let bytes = self.encode(); @@ -871,7 +931,7 @@ mod tests { size_bytes: body.len() as u64, }, }], - intent_summary: "add lib".into(), + intent: RevisionIntent::Summary("add lib".into()), } } @@ -885,7 +945,7 @@ mod tests { assert_eq!(ea.validate().unwrap(), eb.validate().unwrap()); assert_ne!(ea.attestation, eb.attestation); let mut rewritten = c.clone(); - rewritten.intent_summary = "add lib, rewritten".into(); + rewritten.intent = RevisionIntent::Summary("add lib, rewritten".into()); assert_ne!(rewritten.changeset_id(), c.changeset_id()); assert_eq!(rewritten.change_id, c.change_id); } @@ -922,7 +982,7 @@ mod tests { RefusalCode::EnvelopeMalformed ); let mut version = bytes.clone(); - version[4] = 3; + version[4] = 4; // 2 and 3 are defined (B1, B3) assert_eq!( ChangesetEnvelopeV2::decode(&version).unwrap_err().code, RefusalCode::EnvelopeVersionUnsupported @@ -952,7 +1012,7 @@ mod tests { RefusalCode::AuthSignatureInvalid ); let mut t = env.clone(); - t.content.intent_summary = "changed".into(); + t.content.intent = RevisionIntent::Summary("changed".into()); assert_eq!( t.validate().unwrap_err().code, RefusalCode::AuthSignatureInvalid diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs index 08411db..949dc0a 100644 --- a/crates/synapse-store/src/lib.rs +++ b/crates/synapse-store/src/lib.rs @@ -360,21 +360,26 @@ impl WalRecord { } } - /// Blob digests the upserts of this record reference (ingest and revision records). + /// Blob digests this record references and replay requires present: the upserts of an + /// ingest or revision record, and a revision intent's context blob (step B3). pub fn upsert_blobs(&self) -> Vec { - let mutations = match self { - Self::ChangesetIngest { envelope, .. } => &envelope.mutations, - Self::RevisionAdmitted { envelope, .. } => &envelope.content.mutations, - Self::DerivedRevisionAdmitted { derived, .. } => &derived.content.mutations, - _ => return Vec::new(), - }; - mutations - .iter() - .filter_map(|m| match &m.op { - MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest), - MutationOp::Delete => None, - }) - .collect() + match self { + Self::ChangesetIngest { envelope, .. } => envelope + .mutations + .iter() + .filter_map(|m| match &m.op { + MutationOp::Upsert { blob_digest, .. } => Some(*blob_digest), + MutationOp::Delete => None, + }) + .collect(), + Self::RevisionAdmitted { envelope, .. } => { + envelope.content.referenced_blobs().collect() + } + Self::DerivedRevisionAdmitted { derived, .. } => { + derived.content.referenced_blobs().collect() + } + _ => Vec::new(), + } } } @@ -1662,11 +1667,7 @@ impl SynapseStore { // 2. Compute retained blob closure from retained changesets let mut retained_blobs: BTreeSet = BTreeSet::new(); for rev in self.revisions.revisions() { - for m in &rev.content.mutations { - if let MutationOp::Upsert { blob_digest, .. } = &m.op { - retained_blobs.insert(*blob_digest); - } - } + retained_blobs.extend(rev.content.referenced_blobs()); } for stored in self.changesets.values() { for m in &stored.envelope.mutations { diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index ad5305b..1f00551 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -827,6 +827,14 @@ impl crate::SynapseStore { let id = envelope.validate()?; let content = &envelope.content; let att = &envelope.attestation; + let Some(intent) = content.intent.record() else { + return Err(SynapseError::new( + RefusalCode::IntentRecordRequired, + format!( + "revision {id} carries only a free-text intent summary; an agent envelope needs an IntentRecord (content version 3)" + ), + )); + }; let repo = att.repo_id.clone(); if let Some((wal_seq, existing)) = self.revisions @@ -913,6 +921,20 @@ impl crate::SynapseStore { } } } + // The intent's rationale blob is stored and retained like a mutation blob, so it can + // be read, scanned (M1), and kept by compaction. + if let Some(ctx) = intent.context { + if let Some(raw) = provided.get(&ctx) { + if !inline.iter().any(|(d, _)| *d == ctx) { + inline.push((ctx, raw)); + } + } else if !self.blob_first_visible_seq.contains_key(&ctx) { + return Err(SynapseError::new( + RefusalCode::BlobNotFound, + format!("intent context references missing blob {ctx}"), + )); + } + } let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); let record = WalRecord::RevisionAdmitted { envelope, @@ -1008,6 +1030,14 @@ impl crate::SynapseStore { } } } + if let Some(ctx) = content.intent.record().and_then(|r| r.context) { + if !self.blob_first_visible_seq.contains_key(&ctx) { + return Err(SynapseError::new( + RefusalCode::BlobNotFound, + format!("derived intent context references blob {ctx}, which is not visible"), + )); + } + } let joined_existing_revision = self.revisions.get_revision(&repo, id).is_some(); let record = WalRecord::DerivedRevisionAdmitted { derived, @@ -1243,7 +1273,7 @@ mod b4_tests { Capability, CapabilityChain, CapabilityLink, ChainQuotas, ChangeScope, LinkCaveats, OperationSet, PathScope, ReferenceScope, ROOT_PARENT, }; - use synapse_core::{FileMode, PathMutation, TreeDigest}; + use synapse_core::{FileMode, PathMutation, RevisionIntent, TreeDigest}; struct SplitMix64(u64); @@ -1379,6 +1409,20 @@ mod b4_tests { } fn admission(chain: ChainPath, author: &[u8], n: u32) -> WalRecord { + let intent = RevisionIntent::Record(synapse_core::IntentRecord::new( + synapse_core::IntentKind::Feature, + vec!["src/lib.rs".into()], + )); + admission_with(chain, author, n, intent) + } + + /// [`admission`] with the given intent (a content version 2 summary writes a B1-era record). + fn admission_with( + chain: ChainPath, + author: &[u8], + n: u32, + intent: RevisionIntent, + ) -> WalRecord { let body = body(n); let content = RevisionContent { change_id: ChangeId([(n % 7) as u8; 16]), @@ -1392,7 +1436,7 @@ mod b4_tests { size_bytes: body.len() as u64, }, }], - intent_summary: "implement the task".into(), + intent, }; let mut idem = derived("idempotency", &n.to_le_bytes()); idem[0] ^= author.len() as u8; @@ -1836,4 +1880,121 @@ mod b4_tests { }; assert_ne!(record_digest(&later), base); } + + fn owner_authority(owner: &[u8]) -> AdmissionAuthority { + AdmissionAuthority { + chain: path(owner), + change_scope: Vec::new(), + } + } + + /// B3 acceptance "envelopes with only free text are refused": an agent envelope whose + /// content is version 2 (free-text summary) is refused at admission with + /// `IntentRecordRequired` and nothing is written; a B1-era version 2 record already in the + /// log keeps replaying, through a checkpoint and compaction, with its `ChangesetId`. + #[test] + fn b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay() { + const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; + let owner: &[u8] = &[1, 2]; + let dir = temp_dir("b3-free-text"); + let mut s = open(&dir, STRICT).unwrap(); + let summary = RevisionIntent::Summary("implement the task".into()); + let v2 = admission_with(path(owner), owner, 1, summary.clone()); + let WalRecord::RevisionAdmitted { envelope, .. } = v2.clone() else { + unreachable!() + }; + let id = envelope.changeset_id(); + let b = body(1); + let before = s.committed_seq(); + let err = s + .admit_revision( + envelope, + &[(BlobDigest::compute(&b), b.to_vec())], + owner_authority(owner), + 5_000, + ) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::IntentRecordRequired, "{err:?}"); + assert_eq!(s.committed_seq(), before, "a refusal writes nothing"); + assert!(s.get_revision(&repo(), id).is_err()); + + s.append_revision_record(v2, &[(BlobDigest::compute(&b), &b[..])], None) + .unwrap(); + drop(s); + let mut s = open(&dir, STRICT).unwrap(); + assert_eq!(s.get_revision(&repo(), id).unwrap().content.intent, summary); + s.checkpoint_and_compact(7_000).unwrap(); + drop(s); + let s = open(&dir, STRICT).unwrap(); + let rev = s.get_revision(&repo(), id).unwrap(); + assert_eq!(rev.content.intent, summary); + assert_eq!(rev.content.changeset_id(), id); + assert_eq!( + s.get_blob_visible(BlobDigest::compute(&b), None, None) + .unwrap(), + b + ); + } + + /// B3: the intent's rationale blob is admitted with the revision, readable, required at + /// replay, and retained through a checkpoint and compaction; a context naming a blob that + /// is neither provided nor stored is refused with `BlobNotFound` and writes nothing. + #[test] + fn b3_context_blob_is_stored_retained_and_required() { + const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; + let owner: &[u8] = &[1, 2]; + let dir = temp_dir("b3-context"); + let mut s = open(&dir, STRICT).unwrap(); + let rationale = b"plan: split the parser, then the codec".to_vec(); + let ctx = BlobDigest::compute(&rationale); + let mut record = + synapse_core::IntentRecord::new(synapse_core::IntentKind::Refactor, vec!["src".into()]); + record.context = Some(ctx); + let b = body(1); + let file = (BlobDigest::compute(&b), b.to_vec()); + + let missing = admission_with( + path(owner), + owner, + 1, + RevisionIntent::Record(record.clone()), + ); + let WalRecord::RevisionAdmitted { envelope, .. } = missing else { + unreachable!() + }; + let before = s.committed_seq(); + let err = s + .admit_revision( + envelope.clone(), + std::slice::from_ref(&file), + owner_authority(owner), + 5_000, + ) + .unwrap_err(); + assert_eq!(err.code, RefusalCode::BlobNotFound, "{err:?}"); + assert_eq!(s.committed_seq(), before); + + let id = envelope.changeset_id(); + let outcome = s + .admit_revision( + envelope, + &[file, (ctx, rationale.clone())], + owner_authority(owner), + 5_000, + ) + .unwrap(); + assert!( + matches!(outcome, RevisionOutcome::Admitted { .. }), + "{outcome:?}" + ); + assert_eq!(s.get_blob_visible(ctx, None, None).unwrap(), rationale); + s.checkpoint_and_compact(7_000).unwrap(); + drop(s); + let s = open(&dir, STRICT).unwrap(); + assert_eq!( + s.get_revision(&repo(), id).unwrap().content.intent, + RevisionIntent::Record(record) + ); + assert_eq!(s.get_blob_visible(ctx, None, None).unwrap(), rationale); + } } diff --git a/crates/synapse-store/tests/b1_change_identity.rs b/crates/synapse-store/tests/b1_change_identity.rs index c216e7d..9d0c3b9 100644 --- a/crates/synapse-store/tests/b1_change_identity.rs +++ b/crates/synapse-store/tests/b1_change_identity.rs @@ -7,9 +7,9 @@ use ed25519_dalek::SigningKey; use std::path::{Path, PathBuf}; use synapse_core::{ encode_did_key_ed25519, BlobDigest, ChainPath, ChangeId, ChangesetEnvelope, - ChangesetEnvelopeV2, ChangesetId, FileMode, GitOid, IdempotencyKey, MutationOp, - ObsolescenceMarker, PathMutation, RefusalCode, RepoId, RevisionContent, RevisionState, - TreeDigest, WalSeq, + ChangesetEnvelopeV2, ChangesetId, FileMode, GitOid, IdempotencyKey, IntentKind, IntentRecord, + MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RepoId, RevisionContent, + RevisionIntent, RevisionState, TreeDigest, WalSeq, }; mod common; use synapse_store::codec::{decode_record, encode_record}; @@ -99,7 +99,10 @@ fn revision( size_bytes: body.len() as u64, }, }], - intent_summary: "implement the task".into(), + intent: RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + vec!["src/lib.rs".into()], + )), }; let env = ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey([idem; 32]), 1_000); diff --git a/crates/synapse-store/tests/b4_revision_states.rs b/crates/synapse-store/tests/b4_revision_states.rs index 90bf3be..68aea9e 100644 --- a/crates/synapse-store/tests/b4_revision_states.rs +++ b/crates/synapse-store/tests/b4_revision_states.rs @@ -13,8 +13,8 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use synapse_core::{ BlobDigest, ChainPath, ChangeId, ChangesetEnvelopeV2, ChangesetId, FileMode, IdempotencyKey, - MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, RevisionContent, RevisionState, - TreeDigest, + IntentKind, IntentRecord, MutationOp, ObsolescenceMarker, PathMutation, RefusalCode, + RevisionContent, RevisionIntent, RevisionState, TreeDigest, }; mod common; use common::{key_of, mv, path, repo, signed}; @@ -102,7 +102,10 @@ fn revision( size_bytes: body.len() as u64, }, }], - intent_summary: "implement the task".into(), + intent: RevisionIntent::Record(IntentRecord::new( + IntentKind::Feature, + vec!["src/lib.rs".into()], + )), }; let env = ChangesetEnvelopeV2::sign_new(author, repo(), content, IdempotencyKey(idem), 1_000); (env, vec![(digest, body.to_vec())]) diff --git a/crates/synapse-store/tests/b5_derived_record.rs b/crates/synapse-store/tests/b5_derived_record.rs index fb8bc24..2be7d4b 100644 --- a/crates/synapse-store/tests/b5_derived_record.rs +++ b/crates/synapse-store/tests/b5_derived_record.rs @@ -8,7 +8,7 @@ use sha2::{Digest, Sha256}; use synapse_core::{ BlobDigest, ChainPath, ChangeId, ChangesetId, DerivationAttestation, DerivationInput, DerivationRule, DerivedRevision, FileMode, MergeTier, MutationOp, PathMutation, RepoId, - RevisionContent, TreeDigest, + RevisionContent, RevisionIntent, TreeDigest, }; use synapse_store::codec::{decode_record, encode_record}; use synapse_store::WalRecord; @@ -33,7 +33,7 @@ fn derived(rule: DerivationRule, inputs: Vec) -> DerivedRevisio size_bytes: 1, }, }], - intent_summary: "derived".into(), + intent: RevisionIntent::Summary("derived".into()), }; let attestation = DerivationAttestation::sign( &SigningKey::from_bytes(&label("server")), diff --git a/docs/B3_INTENT_RECORD.md b/docs/B3_INTENT_RECORD.md new file mode 100644 index 0000000..d022e0f --- /dev/null +++ b/docs/B3_INTENT_RECORD.md @@ -0,0 +1,55 @@ +# B3: IntentRecord and Claims + +ADR 0003 section 9 step B3 (issue aien-dev/synapse#31), section 5.2 "Intent as data, not prose": the free-text `intent_summary` of envelope v2 content is replaced by a machine-structured `IntentRecord`. + +Code: `crates/synapse-core/src/intent.rs` (types, canonical codec, rules), `crates/synapse-core/src/revision.rs` (`RevisionIntent`, content version 3), `crates/synapse-store/src/revision.rs` (admission), `crates/synapse-store/src/lib.rs` (replay presence check and retention of the context blob), `crates/synapse-api/src/lib.rs` (`submit_revision` scope). Tests: `intent::tests` in `synapse-core`, `b3_*` in `synapse-store` `revision::b4_tests`, `b3_api_*` in `crates/synapse-api/tests/b1_chained_revisions.rs`. Evidence: `evidence/b3-intent-record/`. + +## 1. Model and rules + +* **`IntentRecord`** = `kind` (closed `IntentKind`: `Fix`, `Feature`, `Refactor`, `Revert`, `Merge`, `ResolveConflict`, `Format`, `DependencyUpdate`, `Generated`), optional `task` (`TaskRef`: a tracker issue `repo` + `number >= 1`, or a ledger lane of 1..=64 bytes of `[a-z0-9._-]` starting with `[a-z0-9]`; never free text), `claims`, `footprint`, `supersedes`, optional `context`. +* **Claims.** `Claim` is one of `ActionPasses { action }` (32-byte action digest; `synapse_evidence::EvidenceActionDigest` until E1 defines `ActionDigest`), `InterfaceUnchanged { module }` (a repository path), `BehaviourUnchanged`, `RevertsRevision { revision }`. Every `ClaimKind` maps to exactly one `PredicateType` (`ActionResult`, `InterfaceEquivalence`, `BehaviourEquivalence`, `ExactRevert`), each with a stable name (`synapse.predicate..v1`); the mapping is a bijection. Discharging claims with receipts is E1 and E2; B4 already refuses an owner move to `Verified`. +* **Footprint.** Path prefixes with the F1 `PathScope` segment rule: an entry covers itself and every path below it after a `/`. Canonical form: 1..=256 valid repository paths, strictly ascending, none covering another. Every mutation path must be covered (`MutationOutsideFootprint`). A content-rule check, so it holds for every signed envelope wherever it is validated. +* **Footprint inside `Propose` scope.** Through the API the request scope of a revision is exactly its footprint, so F1 checks every footprint entry against the chain's path scope (`AuthPathOutOfScope`). Since an F1 prefix covering a footprint entry covers every path below it, this also covers every mutation. +* **Supersedes**: strictly ascending `ChangesetId`s, at most 256. Obsolescence markers (B1) stay the authority on replacement; `supersedes` is the declared intent. +* **Context**: the `BlobDigest` of a machine-readable rationale blob. Admission needs it provided (digest checked) or already stored (`BlobNotFound`); it is written with the revision's new blobs, required present at replay, and kept by compaction like a mutation blob. It is never part of a decision rule. + +## 2. Content versions and canonical layout + +`RevisionContent.intent` is a `RevisionIntent`: `Summary(String)` encodes as content version 2 (B1, unchanged byte for byte), `Record(IntentRecord)` as content version 3. Both use the `SYNAPSE_CHANGESET_V2\0` domain; the version is the first content field, so the two never share a `ChangesetId`. Any other version is `EnvelopeVersionUnsupported`. + +Version 3 content: `version u16 = 3 | change_id [16] | base_tree [32] | u32 n | parent [32]*n | u32 m | (path str | op)*m | intent record`, with the record: + +`kind u8 (1..=9) | task | u32 n (<= 64) | claim* | u32 n (<= 256) | path str* | u32 n (<= 256) | id [32]* | context` + +* `task` = `0` | `1 | repo str | number u64` | `2 | lane str` +* `claim` = `1 | action [32]` | `2 | module str` | `3` | `4 | revision [32]`; claims strictly ascending by these bytes +* `context` = `0` | `1 | blob [32]` + +All integers little-endian, `str` = `u32 len | UTF-8`, every count checked against the bytes that remain before anything is reserved, and any encoding that is not canonical (unknown tag, order, covering footprint entries, bad path or lane, issue 0) refused with `EnvelopeMalformed`. + +## 3. Where free text is refused + +* `SynapseStore::admit_revision` (agent envelopes, every path that admits one) refuses content version 2 with `IntentRecordRequired` before any idempotency, join, parent, or blob check, and writes nothing. `SynapseService::submit_revision` refuses it the same way before authorization. +* Replay, checkpoints, and compaction keep applying B1-era version 2 records unchanged, so every existing v2 `ChangesetId` still resolves (`b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay`; golden v2 ID computed on main 2f06c45 in `b3_content_version_2_keeps_its_bytes_and_changeset_id`). +* Server-derived revisions (B5) are not agent envelopes. The B5 rules are unchanged: a rebase keeps its input's intent (so a version 3 input stays version 3), and a T0 merge still writes its fixed version 2 summary, so recomputation at replay of existing derivations gives the same digests. + +## 4. Acceptance + +| Acceptance (issue #31) | Test | +|---|---| +| Envelopes with only free text are refused | `b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay` (store), `b3_api_free_text_only_envelope_is_refused` (API, real F1 chain) | +| Every claim kind maps to a predicate type | `b3_every_claim_kind_maps_to_a_predicate_type` | +| A mutation outside the declared footprint is refused | `b3_mutation_outside_declared_footprint_is_refused` (core, signed envelope and decoded bytes), `b3_api_mutation_outside_declared_footprint_is_refused` (API) | + +Also: `b3_api_footprint_must_lie_inside_the_propose_scope`, `b3_intent_record_round_trips_and_non_canonical_bytes_are_refused`, `b3_context_blob_is_stored_retained_and_required`, `b3_content_version_2_keeps_its_bytes_and_changeset_id`. + +Red before green: `evidence/b3-intent-record/red-green/red.txt` holds one mutation per behaviour (free-text refusal, footprint containment, request scope = footprint, context blob stored, context blob retained, predicate mapping, content version), each turning its test red; `green.txt` holds the passing runs. With the API's own free-text check removed, the API test stays green because the store refuses the same envelope: the store is the authority, the API check is an early exit. + +## 5. Limits and deviations + +* **Envelope v1 is not touched.** The legacy `submit` path (`ChangesetEnvelope`, free-text `intent_summary`) is the human-era adapter kept until Phase 8 and removed by I1 (ADR 0002). Its free-text envelopes are still admitted; B3's refusal covers the native envelope v2. +* The footprint quota charged by breadth, footprint subscriptions, and predictive conflicts are F2. Symbol footprints ("later, symbols") are not in B3. +* Kind-specific rules (for example a `Revert` that must carry `RevertsRevision`) are not enforced; any kind may carry any claims. A change that claims nothing beyond the required actions is valid (ADR 0003 section 5.2). +* `task` is optional so that work with no tracker item can still be described; when present it is typed. +* The M1 secret scan (PR #108 at the time of writing) runs on mutation blobs; the context blob now exists and needs the same scan once both land. +* No performance figures: B3 has no hot-path acceptance and none were measured. diff --git a/evidence/b3-intent-record/SHA256SUMS b/evidence/b3-intent-record/SHA256SUMS new file mode 100644 index 0000000..3c02332 --- /dev/null +++ b/evidence/b3-intent-record/SHA256SUMS @@ -0,0 +1,2 @@ +659757902747c952a90da6ba10400ff1607f03fbb9b180ea5d5754ba6009db23 red-green/green.txt +45f4b33fda0520cdaff250c870901e61fbfc82f6b9e76525dcbf42f4f6d0e77e red-green/red.txt diff --git a/evidence/b3-intent-record/red-green/green.txt b/evidence/b3-intent-record/red-green/green.txt new file mode 100644 index 0000000..7518ad5 --- /dev/null +++ b/evidence/b3-intent-record/red-green/green.txt @@ -0,0 +1,16 @@ +# Green (2026-10-18) at commit 6970910 +## cargo test --locked -p synapse-core b3_ +test intent::tests::b3_every_claim_kind_maps_to_a_predicate_type ... ok +test intent::tests::b3_content_version_2_keeps_its_bytes_and_changeset_id ... ok +test intent::tests::b3_mutation_outside_declared_footprint_is_refused ... ok +test intent::tests::b3_intent_record_round_trips_and_non_canonical_bytes_are_refused ... ok +test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 21 filtered out; finished in 0.00s +## cargo test --locked -p synapse-store --lib b3_ +test revision::b4_tests::b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay ... ok +test revision::b4_tests::b3_context_blob_is_stored_retained_and_required ... ok +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 60 filtered out; finished in 0.07s +## cargo test --locked -p synapse-api --test b1_chained_revisions b3_api +test b3_api_mutation_outside_declared_footprint_is_refused ... ok +test b3_api_free_text_only_envelope_is_refused ... ok +test b3_api_footprint_must_lie_inside_the_propose_scope ... ok +test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.04s diff --git a/evidence/b3-intent-record/red-green/red.txt b/evidence/b3-intent-record/red-green/red.txt new file mode 100644 index 0000000..9d0beeb --- /dev/null +++ b/evidence/b3-intent-record/red-green/red.txt @@ -0,0 +1,46 @@ +# Red (2026-10-18): each B3 behaviour removed by one mutation applied to the working tree of +# commit 6970910 (parent main 2f06c45), its tests run, the mutation reverted. Script kept +# outside the repo; each case lists the mutated file and the test lines it produced. + +=== M1 no free-text refusal (store and API) (crates/synapse-store/src/revision.rs) +test revision::b4_tests::b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay ... FAILED +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 61 filtered out; finished in 0.02s +=== M1b no free-text refusal (API) (crates/synapse-api/src/lib.rs) +# (stays green: the store refuses the same envelope, see docs/B3_INTENT_RECORD.md section 4) +test b3_api_free_text_only_envelope_is_refused ... ok +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 4 filtered out; finished in 0.03s +=== M2 no footprint containment (crates/synapse-core/src/intent.rs) +# (workspace run without --no-fail-fast: cargo stopped at the first red binary; M2b below runs core and store) +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 31 filtered out; finished in 0.00s +test b3_api_free_text_only_envelope_is_refused ... ok +test b3_api_footprint_must_lie_inside_the_propose_scope ... ok +test b3_api_mutation_outside_declared_footprint_is_refused ... FAILED +test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.04s +=== M3 request scope = mutation paths, not footprint (crates/synapse-api/src/lib.rs) +test b3_api_footprint_must_lie_inside_the_propose_scope ... FAILED +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 4 filtered out; finished in 0.03s +=== M4 context blob not stored at admission (crates/synapse-store/src/revision.rs) +test revision::b4_tests::b3_context_blob_is_stored_retained_and_required ... FAILED +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 61 filtered out; finished in 0.03s +=== M5 two claim kinds share a predicate type (crates/synapse-core/src/intent.rs) +test intent::tests::b3_every_claim_kind_maps_to_a_predicate_type ... FAILED +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 24 filtered out; finished in 0.00s +=== M6 content version 3 written as 2 (crates/synapse-core/src/revision.rs) +test intent::tests::b3_every_claim_kind_maps_to_a_predicate_type ... ok +test intent::tests::b3_content_version_2_keeps_its_bytes_and_changeset_id ... ok +test intent::tests::b3_intent_record_round_trips_and_non_canonical_bytes_are_refused ... FAILED +test intent::tests::b3_mutation_outside_declared_footprint_is_refused ... FAILED +test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 21 filtered out; finished in 0.00s +=== M2b no footprint containment, core and store (crates/synapse-core/src/intent.rs) +test intent::tests::b3_mutation_outside_declared_footprint_is_refused ... FAILED +test intent::tests::b3_every_claim_kind_maps_to_a_predicate_type ... ok +test intent::tests::b3_content_version_2_keeps_its_bytes_and_changeset_id ... ok +test intent::tests::b3_intent_record_round_trips_and_non_canonical_bytes_are_refused ... ok +test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 21 filtered out; finished in 0.00s +test revision::b4_tests::b3_free_text_envelope_is_refused_at_admission_and_b1_records_still_replay ... ok +test revision::b4_tests::b3_context_blob_is_stored_retained_and_required ... ok +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 60 filtered out; finished in 0.07s +=== M7 context blob dropped from referenced_blobs (retention and replay presence check) (crates/synapse-core/src/revision.rs) +test revision::b4_tests::b3_context_blob_is_stored_retained_and_required ... FAILED +thread 'revision::b4_tests::b3_context_blob_is_stored_retained_and_required' (2892352) panicked at crates/synapse-store/src/revision.rs:1978:56: +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 61 filtered out; finished in 0.08s ```