About Files History Releases Proposed changes Issues For developers
desk block: 2 PRs (#104, #108)
closed f1189d76741bf288 #121 · opened 2026-10-21 21:58 UTC · closed 2026-10-21 22:29 UTC
Imported from GitHub aien-dev/synapse#121, by drakestapleton
Base 5b732e5d353bbcc3f6d0cd1eac60f2e543601521 · Head 2c56213287ce31cb9cec3e8980fd6aea545ab4ff
drakestapleton wrote on 2026-10-21 21:58 UTC
Desk block built by renda-harness: one judge run for 2 pull requests instead of 2 (Drake 2026-10-20: do the shared work once, in blocks).
When this merges, each carried PR is closed with a link here. If the judge fails, the block is split and retried in halves; nothing is waived.
Carries #104 (feat/53-omega-codec@c2a41c9a ): J1 (#53): sealed cross-check corpus for the Omega port of codec v2
Carries #108 (feat/32-secret-scan@2293d48e ): Agents can no longer commit API keys or private keys into Synapse (M1, #32)
drakestapleton wrote on 2026-10-21 22:29 UTC
Judge failure on the block head (BLOCKED FAIL SYNAPSE-WORKSPACE:rc_nonzero: bundle /home/drakestapleton/.local/state/aien-local-ci/bundles/synapse/2c56213287ce31cb9cec3e8980 ). Splitting the block in halves; each half is judged on its own.
Fetch it
A git bundle of the pull request's head, 208173 bytes.
curl -fsSL https://interplane.io/drakestapleton/synapse/patches/f1189d76741bf288 .bundle -o f1189d76741bf288 .bundle
git fetch f1189d76741bf288 .bundle refs/pull/121/head
Raw bundle · 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
121
2c56213287ce31cb9cec3e8980fd6aea545ab4ff
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":121,"url":"https://github.com/aien-dev/synapse/pull/121","export_sha256":"1c576073d3642d6130bfff61541dda3d27f03618b9224cb72ff5d1ad6d163116 ","imported_utc":"2026-11-18T16:39:03Z"}
Changes
diff --git a/crates/synapse-api/src/lib.rs b/crates/synapse-api/src/lib.rs
index 71fa247 ..6ba8330 100644
--- a/crates/synapse-api/src/lib.rs
+++ b/crates/synapse-api/src/lib.rs
@@ -29,6 +29,7 @@ mod crumb;
mod derivation;
pub use derivation::ServiceDerivationTrees;
mod evidence;
+pub mod secret_scan;
pub mod tree;
pub use advisory::{
ChangesetAdvisory, ChangesetAdvisoryPayload, CoordinationStatus, GuidanceNote,
@@ -632,6 +633,9 @@ impl SynapseService {
req,
now_ms,
)?;
+ // Secret scanning (ADR 0003 section 5.13, step M1) runs here, before the store and the
+ // single writer, so a refused secret never reaches the WAL.
+ secret_scan::check_blobs(&req.payload.blobs)?;
if req.payload.envelope.repo_id != self.repo_id {
return Err(SynapseError::new(
@@ -714,6 +718,7 @@ impl SynapseService {
));
}
let authority = admission_authority(req)?;
+ secret_scan::check_blobs(blobs)?;
self.store
.admit_revision(envelope, blobs, authority, now_ms)
}
diff --git a/crates/synapse-api/src/secret_scan.rs b/crates/synapse-api/src/secret_scan.rs
new file mode 100644
index 0000000 ..f7e8f51
--- /dev/null
+++ b/crates/synapse-api/src/secret_scan.rs
@@ -0,0 +1,518 @@
+//! Secret scanning at admission (ADR 0003 section 5.13, step M1).
+//!
+//! Every blob an agent submits is scanned before the store sees it, so a refused secret never
+//! reaches the WAL, the content store, an index, or a cache. A hit refuses the whole admission
+//! with [`RefusalCode::SecretDetected`]. The refusal names the blob digest, the rule, the rule
+//! set version, and the byte offset; it never contains the matched bytes, and this module keeps
+//! no copy of them.
+//!
+//! The scanner is a hand-written single pass over raw bytes (binary safe, no UTF-8
+//! assumption, no regular expressions). Each position does a bounded amount of work, and the
+//! windows that longer checks walk cannot overlap without bound, so time is linear in the input
+//! length and memory is constant. The rule set is versioned data ([`SECRET_RULESET_VERSION`]).
+//!
+//! Policy (refuse by default): there is no allowlist and no override. Clearly fake
+//! documentation values (`EXAMPLE`, `fake`, `your`, `xxxxxxxx`, very low character variety) are not
+//! secrets and are admitted.
+
+use synapse_core::{BlobDigest, RefusalCode, SynapseError, SynapseResult};
+
+/// Version of the rule set below. Bump it whenever a rule is added, removed, or changed.
+pub const SECRET_RULESET_VERSION: u16 = 1;
+
+/// One rule of the secret-scanning rule set.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum SecretRule {
+ /// A PEM or OpenSSH private key block (`BEGIN ... PRIVATE KEY`) with a key body.
+ PrivateKeyBlock,
+ /// An AWS access key id (`AKIA` or `ASIA` plus 16 characters).
+ AwsAccessKeyId,
+ /// A GitHub classic token (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`).
+ GithubToken,
+ /// A GitHub fine-grained personal access token (`github_pat_`).
+ GithubFineGrainedToken,
+ /// A Slack token (`xoxb-`, `xoxp-`, ...).
+ SlackToken,
+ /// A Slack incoming webhook URL.
+ SlackWebhook,
+ /// A Stripe live secret or restricted key.
+ StripeLiveKey,
+ /// An Anthropic API key (`sk-ant-`).
+ AnthropicKey,
+ /// An OpenAI API key (project, service account, admin, or legacy format).
+ OpenAiKey,
+ /// A high-entropy value assigned to a secret-like name (`token = "..."`).
+ SecretAssignment,
+}
+
+impl SecretRule {
+ /// Stable identifier of the rule, used in refusal text.
+ pub fn id(self) -> &'static str {
+ match self {
+ SecretRule::PrivateKeyBlock => "private-key-block",
+ SecretRule::AwsAccessKeyId => "aws-access-key-id",
+ SecretRule::GithubToken => "github-token",
+ SecretRule::GithubFineGrainedToken => "github-fine-grained-token",
+ SecretRule::SlackToken => "slack-token",
+ SecretRule::SlackWebhook => "slack-webhook",
+ SecretRule::StripeLiveKey => "stripe-live-key",
+ SecretRule::AnthropicKey => "anthropic-key",
+ SecretRule::OpenAiKey => "openai-key",
+ SecretRule::SecretAssignment => "secret-assignment",
+ }
+ }
+}
+
+/// Where a rule matched. Carries no matched bytes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SecretFinding {
+ pub rule: SecretRule,
+ /// Byte offset of the start of the match inside the scanned input.
+ pub offset: usize,
+}
+
+/// Scan `bytes` and return the first finding, if any.
+pub fn scan(bytes: &[u8]) -> Option<SecretFinding> {
+ Scanner::new(bytes).scan_all()
+}
+
+/// Scan and also return the number of byte inspections made, for the linear-time bound tests.
+#[doc(hidden)]
+pub fn scan_with_steps(bytes: &[u8]) -> (Option<SecretFinding>, u64) {
+ let mut s = Scanner::new(bytes);
+ let found = s.scan_all();
+ (found, s.steps)
+}
+
+/// Refuse the admission if any blob matches a rule. The error never contains blob bytes.
+pub fn check_blobs(blobs: &[(BlobDigest, Vec<u8>)]) -> SynapseResult<()> {
+ for (digest, bytes) in blobs {
+ if let Some(f) = scan(bytes) {
+ return Err(refusal(*digest, f));
+ }
+ }
+ Ok(())
+}
+
+fn refusal(digest: BlobDigest, f: SecretFinding) -> SynapseError {
+ SynapseError::new(
+ RefusalCode::SecretDetected,
+ format!(
+ "blob {digest} refused: matched secret rule {} (rule set v{}) at byte offset {}",
+ f.rule.id(),
+ SECRET_RULESET_VERSION,
+ f.offset
+ ),
+ )
+}
+
+// Bounds on every window a rule walks. Each is a constant, so the work per position is bounded.
+const PEM_LABEL_MAX: usize = 48;
+const PEM_BODY_WINDOW: usize = 512;
+const PEM_BODY_MIN: usize = 64;
+const TOKEN_MAX: usize = 255;
+const IDENT_MAX: usize = 64;
+const SPACE_MAX: usize = 4;
+const VALUE_MIN: usize = 20;
+const VALUE_MAX: usize = 128;
+
+const SECRET_NAMES: &[&[u8]] = &[
+ b"secret",
+ b"token",
+ b"password",
+ b"passwd",
+ b"passphrase",
+ b"pwd",
+ b"apikey",
+ b"api_key",
+ b"api-key",
+ b"accesskey",
+ b"access_key",
+ b"access-key",
+ b"privatekey",
+ b"private_key",
+ b"private-key",
+ b"credential",
+ b"authkey",
+ b"auth_key",
+];
+
+const FAKE_MARKERS: &[&[u8]] = &[
+ b"example",
+ b"fake",
+ b"dummy",
+ b"placeholder",
+ b"redacted",
+ b"changeme",
+ b"your",
+ b"xxxxxxxx",
+];
+
+fn is_tok(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
+}
+fn is_upper_digit(b: u8) -> bool {
+ b.is_ascii_uppercase() || b.is_ascii_digit()
+}
+fn is_alnum_us(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'_'
+}
+fn is_alnum_dash(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'-'
+}
+fn is_b64(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'='
+}
+fn is_ident(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.'
+}
+fn is_value(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'_' | b'-' | b'.')
+}
+fn is_space(b: u8) -> bool {
+ b == b' ' || b == b'\t'
+}
+fn is_quote(b: u8) -> bool {
+ b == b'"' || b == b'\'' || b == b'`'
+}
+
+fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {
+ hay.len() >= needle.len()
+ && hay
+ .windows(needle.len())
+ .any(|w| w.eq_ignore_ascii_case(needle))
+}
+
+fn distinct_bytes(s: &[u8]) -> usize {
+ let mut seen = [false; 256];
+ let mut n = 0;
+ for &b in s {
+ if !seen[b as usize] {
+ seen[b as usize] = true;
+ n += 1;
+ }
+ }
+ n
+}
+
+/// A clearly fake documentation value: a fake marker or too little character variety.
+fn looks_fake(body: &[u8]) -> bool {
+ distinct_bytes(body) < 8 || FAKE_MARKERS.iter().any(|m| contains_ci(body, m))
+}
+
+/// Shannon entropy in bits per byte.
+fn entropy(s: &[u8]) -> f64 {
+ let mut counts = [0u32; 256];
+ for &b in s {
+ counts[b as usize] += 1;
+ }
+ let n = s.len() as f64;
+ counts
+ .iter()
+ .filter(|&&c| c > 0)
+ .map(|&c| {
+ let p = f64::from(c) / n;
+ -p * p.log2()
+ })
+ .sum()
+}
+
+struct Scanner<'a> {
+ b: &'a [u8],
+ steps: u64,
+}
+
+impl<'a> Scanner<'a> {
+ fn new(b: &'a [u8]) -> Self {
+ Self { b, steps: 0 }
+ }
+
+ fn at(&self, i: usize) -> Option<u8> {
+ self.b.get(i).copied()
+ }
+
+ fn lit(&mut self, i: usize, lit: &[u8]) -> bool {
+ self.steps += lit.len() as u64;
+ self.b.get(i..i + lit.len()) == Some(lit)
+ }
+
+ /// Length of the run of `pred` bytes from `i`, counting at most `cap + 1` bytes so callers
+ /// can tell a run longer than `cap`.
+ fn run(&mut self, i: usize, pred: fn(u8) -> bool, cap: usize) -> usize {
+ let end = self.b.len().min(i.saturating_add(cap + 1));
+ let n = self
+ .b
+ .get(i..end)
+ .map_or(0, |w| w.iter().position(|&c| !pred(c)).unwrap_or(w.len()));
+ self.steps += n as u64 + 1;
+ n
+ }
+
+ fn left_boundary(&self, i: usize) -> bool {
+ i == 0 || !is_tok(self.b[i - 1])
+ }
+
+ fn scan_all(&mut self) -> Option<SecretFinding> {
+ for i in 0..self.b.len() {
+ self.steps += 1;
+ let rule = match self.b[i] {
+ b'-' => self.pem(i),
+ b'A' => self.aws(i),
+ b'g' => self.github(i),
+ b'x' => self.slack(i),
+ b'h' => self.slack_webhook(i),
+ b's' | b'r' => self.sk(i),
+ b'=' | b':' => self.assignment(i),
+ _ => None,
+ };
+ if let Some(rule) = rule {
+ return Some(SecretFinding { rule, offset: i });
+ }
+ }
+ None
+ }
+
+ fn pem(&mut self, i: usize) -> Option<SecretRule> {
+ if !self.lit(i, b"-----BEGIN ") {
+ return None;
+ }
+ let label_start = i + 11;
+ let label_len = self.run(
+ label_start,
+ |c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b' ',
+ PEM_LABEL_MAX,
+ );
+ if label_len > PEM_LABEL_MAX {
+ return None;
+ }
+ let label = &self.b[label_start..label_start + label_len];
+ if !(label.ends_with(b"PRIVATE KEY") || label == b"PGP PRIVATE KEY BLOCK") {
+ return None;
+ }
+ let body_start = label_start + label_len;
+ if !self.lit(body_start, b"-----") {
+ return None;
+ }
+ let start = body_start + 5;
+ let end = self.b.len().min(start + PEM_BODY_WINDOW);
+ let window = &self.b[start..end];
+ self.steps += window.len() as u64;
+ let mut b64 = 0usize;
+ let mut other = 0usize;
+ for &c in window {
+ match c {
+ b'-' => break,
+ b'\r' | b'\n' | b' ' | b'\t' => {}
+ c if is_b64(c) => b64 += 1,
+ _ => other += 1,
+ }
+ }
+ let body_ok = b64 >= PEM_BODY_MIN && other * 4 <= b64;
+ body_ok.then_some(SecretRule::PrivateKeyBlock)
+ }
+
+ fn aws(&mut self, i: usize) -> Option<SecretRule> {
+ if !self.left_boundary(i) || !(self.lit(i, b"AKIA") || self.lit(i, b"ASIA")) {
+ return None;
+ }
+ let n = self.run(i + 4, is_upper_digit, 16);
+ if n != 16 || self.at(i + 20).is_some_and(|c| c.is_ascii_alphanumeric()) {
+ return None;
+ }
+ let body = &self.b[i + 4..i + 20];
+ (!looks_fake(body)).then_some(SecretRule::AwsAccessKeyId)
+ }
+
+ fn github(&mut self, i: usize) -> Option<SecretRule> {
+ if !self.left_boundary(i) {
+ return None;
+ }
+ if self.lit(i, b"github_pat_") {
+ let n = self.run(i + 11, is_alnum_us, TOKEN_MAX);
+ let body = &self.b[i + 11..i + 11 + n.min(TOKEN_MAX)];
+ return ((80..=TOKEN_MAX).contains(&n) && !looks_fake(body))
+ .then_some(SecretRule::GithubFineGrainedToken);
+ }
+ let prefix_ok = self.lit(i, b"gh")
+ && matches!(self.at(i + 2), Some(b'p' | b'o' | b'u' | b's' | b'r'))
+ && self.at(i + 3) == Some(b'_');
+ if !prefix_ok {
+ return None;
+ }
+ let n = self.run(i + 4, |c| c.is_ascii_alphanumeric(), 36);
+ if n != 36 || self.at(i + 40).is_some_and(is_tok) {
+ return None;
+ }
+ (!looks_fake(&self.b[i + 4..i + 40])).then_some(SecretRule::GithubToken)
+ }
+
+ fn slack(&mut self, i: usize) -> Option<SecretRule> {
+ let prefix_ok = self.left_boundary(i)
+ && self.lit(i, b"xox")
+ && matches!(
+ self.at(i + 3),
+ Some(b'b' | b'p' | b'a' | b'r' | b's' | b'o')
+ )
+ && self.at(i + 4) == Some(b'-');
+ if !prefix_ok {
+ return None;
+ }
+ let n = self.run(i + 5, is_alnum_dash, TOKEN_MAX);
+ if !(20..=TOKEN_MAX).contains(&n) {
+ return None;
+ }
+ let body = &self.b[i + 5..i + 5 + n];
+ let dashes = body.iter().filter(|&&c| c == b'-').count();
+ let digits = body.iter().filter(|c| c.is_ascii_digit()).count();
+ (dashes >= 2 && digits >= 10 && !looks_fake(body)).then_some(SecretRule::SlackToken)
+ }
+
+ fn slack_webhook(&mut self, i: usize) -> Option<SecretRule> {
+ const PREFIX: &[u8] = b"hooks.slack.com/services/";
+ if !self.lit(i, PREFIX) {
+ return None;
+ }
+ let start = i + PREFIX.len();
+ let n = self.run(start, |c| c.is_ascii_alphanumeric() || c == b'/', TOKEN_MAX);
+ if !(40..=TOKEN_MAX).contains(&n) {
+ return None;
+ }
+ let body = &self.b[start..start + n];
+ let slashes = body.iter().filter(|&&c| c == b'/').count();
+ (slashes >= 2 && !looks_fake(body)).then_some(SecretRule::SlackWebhook)
+ }
+
+ fn sk(&mut self, i: usize) -> Option<SecretRule> {
+ if !self.left_boundary(i) {
+ return None;
+ }
+ if self.lit(i, b"sk_live_") || self.lit(i, b"rk_live_") {
+ let n = self.run(i + 8, |c| c.is_ascii_alphanumeric(), TOKEN_MAX);
+ let body = &self.b[i + 8..i + 8 + n.min(TOKEN_MAX)];
+ return ((24..=TOKEN_MAX).contains(&n) && !looks_fake(body))
+ .then_some(SecretRule::StripeLiveKey);
+ }
+ if !self.lit(i, b"sk-") {
+ return None;
+ }
+ let (rule, start, min) = if self.lit(i, b"sk-ant-") {
+ (SecretRule::AnthropicKey, i + 7, 32)
+ } else if self.lit(i, b"sk-proj-") || self.lit(i, b"sk-admin-") {
+ let len = if self.at(i + 3) == Some(b'p') { 8 } else { 9 };
+ (SecretRule::OpenAiKey, i + len, 40)
+ } else if self.lit(i, b"sk-svcacct-") {
+ (SecretRule::OpenAiKey, i + 11, 40)
+ } else {
+ // Legacy OpenAI key: 48 alphanumerics with the base64 "OpenAI" marker inside.
+ let n = self.run(i + 3, |c| c.is_ascii_alphanumeric(), 48);
+ if n != 48 || self.at(i + 51).is_some_and(is_tok) {
+ return None;
+ }
+ let body = &self.b[i + 3..i + 51];
+ return body
+ .windows(8)
+ .any(|w| w == b"T3BlbkFJ")
+ .then_some(SecretRule::OpenAiKey);
+ };
+ let n = self.run(start, is_tok, TOKEN_MAX);
+ let body = &self.b[start..start + n.min(TOKEN_MAX)];
+ ((min..=TOKEN_MAX).contains(&n) && !looks_fake(body)).then_some(rule)
+ }
+
+ /// `name = value`, `name: value`, `name := value`, `name => value`, with the name holding
+ /// a secret-like word and the value a high-entropy literal.
+ fn assignment(&mut self, i: usize) -> Option<SecretRule> {
+ let op = self.b[i];
+ let prev = if i > 0 { Some(self.b[i - 1]) } else { None };
+ let next = self.at(i + 1);
+ self.steps += 2;
+ let mut name_end = i;
+ let mut value_from = i + 1;
+ if op == b':' {
+ // `:=` is handled at the `=`; `::` is a path separator.
+ if matches!(next, Some(b'=' | b':')) || prev == Some(b':') {
+ return None;
+ }
+ } else {
+ if next == Some(b'=')
+ || matches!(
+ prev,
+ Some(
+ b'=' | b'!'
+ | b'<'
+ | b'>'
+ | b'+'
+ | b'-'
+ | b'*'
+ | b'/'
+ | b'|'
+ | b'&'
+ | b'^'
+ | b'%'
+ )
+ )
+ {
+ return None;
+ }
+ if prev == Some(b':') {
+ name_end = i - 1;
+ }
+ if next == Some(b'>') {
+ value_from = i + 2;
+ }
+ }
+
+ // Name, walking back over a few spaces and one closing quote.
+ let mut j = name_end;
+ let mut k = 0;
+ while k < SPACE_MAX && j > 0 && is_space(self.b[j - 1]) {
+ j -= 1;
+ k += 1;
+ }
+ if j > 0 && is_quote(self.b[j - 1]) {
+ j -= 1;
+ }
+ let mut name_len = 0;
+ while name_len < IDENT_MAX && j > name_len && is_ident(self.b[j - 1 - name_len]) {
+ name_len += 1;
+ }
+ self.steps += (k + name_len + 1) as u64;
+ if name_len == 0 {
+ return None;
+ }
+ let name = &self.b[j - name_len..j];
+ if !SECRET_NAMES.iter().any(|w| contains_ci(name, w)) {
+ return None;
+ }
+
+ // Value, after a few spaces and an optional opening quote.
+ let mut v = value_from + self.run(value_from, is_space, SPACE_MAX).min(SPACE_MAX);
+ let quote = self.at(v).filter(|&c| is_quote(c));
+ if quote.is_some() {
+ v += 1;
+ }
+ let n = self.run(v, is_value, VALUE_MAX);
+ if !(VALUE_MIN..=VALUE_MAX).contains(&n) {
+ return None;
+ }
+ let value = &self.b[v..v + n];
+ let mut after = v + n;
+ let pad = self.run(after, |c| c == b'=', 2).min(2);
+ after += pad;
+ match quote {
+ Some(q) if self.at(after) != Some(q) => return None,
+ None if matches!(self.at(after), Some(b'(' | b'[' | b'{' | b'<')) => return None,
+ _ => {}
+ }
+ self.steps += n as u64;
+ let has_digit = value.iter().any(|c| c.is_ascii_digit());
+ let has_alpha = value.iter().any(|c| c.is_ascii_alphabetic());
+ if !has_digit || !has_alpha || looks_fake(value) {
+ return None;
+ }
+ let h = entropy(value);
+ let hex = value.iter().all(|c| c.is_ascii_hexdigit());
+ let strong = if hex { n >= 32 && h >= 3.0 } else { h >= 3.5 };
+ strong.then_some(SecretRule::SecretAssignment)
+ }
+}
diff --git a/crates/synapse-api/tests/m1_secret_scan.rs b/crates/synapse-api/tests/m1_secret_scan.rs
new file mode 100644
index 0000000 ..e6c58d1
--- /dev/null
+++ b/crates/synapse-api/tests/m1_secret_scan.rs
@@ -0,0 +1,596 @@
+//! ADR 0003 step M1: secret scanning at admission (section 5.13).
+//!
+//! Every planted secret below is assembled at run time from split pieces and a deterministic
+//! generator, so this file itself holds no complete token and no real key. Values used as
+//! negatives are clearly fake documentation examples.
+
+use ed25519 _dalek::SigningKey;
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+use synapse_api::secret_scan::{
+ check_blobs, scan, scan_with_steps, SecretRule, SECRET_RULESET_VERSION,
+};
+use synapse_api::{SubmitChangesetPayload, SynapseService, TreeTarget};
+use synapse_auth::{
+ AgentCapabilityGrant, AuthenticatedRequest, Capability, CapabilityChain, CapabilityLink,
+ ChainQuotas, ChainedRequest, ChangeScope, LinkCaveats, OperationSet, PathScope, ReferenceKind,
+ ReferenceScope, RequestScope, ROOT_PARENT,
+};
+use synapse_core::{
+ encode_did_key_ed25519 , BlobDigest, ChangeId, ChangesetEnvelope, ChangesetEnvelopeV2, FileMode,
+ GitOid, IdempotencyKey, MutationOp, PathMutation, RefusalCode, RepoId, RevisionContent, WalSeq,
+ SYNAPSE_ENVELOPE_VERSION,
+};
+use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, StoreLimits};
+
+/// Deterministic xorshift generator for token bodies.
+struct Gen(u64);
+
+impl Gen {
+ fn next(&mut self) -> u64 {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 7;
+ self.0 ^= self.0 << 17;
+ self.0
+ }
+ fn from(&mut self, alphabet: &[u8], n: usize) -> String {
+ (0..n)
+ .map(|_| alphabet[(self.next() % alphabet.len() as u64) as usize] as char)
+ .collect()
+ }
+}
+
+const ALNUM: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+const UPPER_DIGIT: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
+const DIGITS: &[u8] = b"0123456789 ";
+const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+/// `(rule, secret)` pairs; each secret is the exact sensitive span.
+fn planted() -> Vec<(SecretRule, String)> {
+ let mut g = Gen(0x9E37_79B9_7F4A_7C15);
+ let dash5 = "-".repeat(5);
+ let pem = |label: &str, g: &mut Gen| {
+ let body: Vec<String> = (0..6).map(|_| g.from(B64, 64)).collect();
+ format!(
+ "{dash5}{} {label}{dash5}\n{}\n{dash5}END {label}{dash5}\n",
+ "BEGIN",
+ body.join("\n")
+ )
+ };
+ let rsa = pem(&["RSA", "PRIVATE", "KEY"].join(" "), &mut g);
+ let openssh = pem(&["OPENSSH", "PRIVATE", "KEY"].join(" "), &mut g);
+ let pkcs8 = pem(&["PRIVATE", "KEY"].join(" "), &mut g);
+ vec![
+ (SecretRule::PrivateKeyBlock, rsa),
+ (SecretRule::PrivateKeyBlock, openssh),
+ (SecretRule::PrivateKeyBlock, pkcs8),
+ (
+ SecretRule::AwsAccessKeyId,
+ format!("{}{}", ["AK", "IA"].concat(), g.from(UPPER_DIGIT, 16)),
+ ),
+ (
+ SecretRule::AwsAccessKeyId,
+ format!("{}{}", ["AS", "IA"].concat(), g.from(UPPER_DIGIT, 16)),
+ ),
+ (
+ SecretRule::GithubToken,
+ format!("{}{}", ["gh", "p_"].concat(), g.from(ALNUM, 36)),
+ ),
+ (
+ SecretRule::GithubToken,
+ format!("{}{}", ["gh", "s_"].concat(), g.from(ALNUM, 36)),
+ ),
+ (
+ SecretRule::GithubFineGrainedToken,
+ format!(
+ "{}{}_{}",
+ ["github", "_pat_"].concat(),
+ g.from(ALNUM, 22),
+ g.from(ALNUM, 59)
+ ),
+ ),
+ (
+ SecretRule::SlackToken,
+ format!(
+ "{}{}-{}-{}",
+ ["xo", "xb-"].concat(),
+ g.from(DIGITS, 12),
+ g.from(DIGITS, 13),
+ g.from(ALNUM, 24)
+ ),
+ ),
+ (
+ SecretRule::SlackWebhook,
+ format!(
+ "https://{}T{}/B{}/{}",
+ ["hooks.", "slack.com/services/"].concat(),
+ g.from(UPPER_DIGIT, 10),
+ g.from(UPPER_DIGIT, 10),
+ g.from(ALNUM, 24)
+ ),
+ ),
+ (
+ SecretRule::StripeLiveKey,
+ format!("{}{}", ["sk_", "live_"].concat(), g.from(ALNUM, 32)),
+ ),
+ (
+ SecretRule::AnthropicKey,
+ format!("{}api03-{}", ["sk-", "ant-"].concat(), g.from(ALNUM, 93)),
+ ),
+ (
+ SecretRule::OpenAiKey,
+ format!("{}{}", ["sk-", "proj-"].concat(), g.from(ALNUM, 64)),
+ ),
+ (
+ SecretRule::OpenAiKey,
+ format!(
+ "sk-{}{}{}",
+ g.from(ALNUM, 20),
+ ["T3Blbk", "FJ"].concat(),
+ g.from(ALNUM, 20)
+ ),
+ ),
+ (SecretRule::SecretAssignment, g.from(ALNUM, 40)),
+ ]
+}
+
+/// The planted secret placed in a realistic source context.
+fn in_context(rule: SecretRule, secret: &str) -> Vec<u8> {
+ match rule {
+ SecretRule::SecretAssignment => {
+ format!("fn main() {{\n let db_password = \"{secret}\";\n}}\n").into_bytes()
+ }
+ SecretRule::PrivateKeyBlock => format!("# deploy key\n{secret}").into_bytes(),
+ _ => {
+ format!("config:\n endpoint: https://api.local\n upstream: '{secret}'\n").into_bytes()
+ }
+ }
+}
+
+#[test]
+fn m1_every_planted_secret_is_found_by_its_rule() {
+ for (rule, secret) in planted() {
+ let blob = in_context(rule, &secret);
+ let f = scan(&blob).unwrap_or_else(|| panic!("{} not found", rule.id()));
+ if rule != SecretRule::SecretAssignment {
+ assert_eq!(f.rule, rule, "rule for {}", rule.id());
+ }
+ // Binary context: the secret between non-text bytes is still found.
+ let mut bin = vec![0u8, 0xFF, 0x80, b'\n'];
+ bin.extend_from_slice(secret.as_bytes());
+ bin.extend_from_slice(&[0u8, 0xFE]);
+ if rule != SecretRule::SecretAssignment {
+ assert_eq!(
+ scan(&bin).map(|f| f.rule),
+ Some(rule),
+ "binary {}",
+ rule.id()
+ );
+ }
+ }
+}
+
+#[test]
+fn m1_assignment_forms_are_found() {
+ let mut g = Gen(7);
+ let v = g.from(ALNUM, 32);
+ let hex = g.from(b"0123456789abcdef ", 64);
+ for text in [
+ format!("API_KEY={v}\n"),
+ format!("export GITHUB_TOKEN={v}\n"),
+ format!("{{\"client_secret\": \"{v}\"}}"),
+ format!("password := \"{v}\""),
+ format!("auth_token => '{v}',"),
+ format!("secret: {hex}\n"),
+ ] {
+ assert_eq!(
+ scan(text.as_bytes()).map(|f| f.rule),
+ Some(SecretRule::SecretAssignment),
+ "{text}"
+ );
+ }
+}
+
+#[test]
+fn m1_lookalikes_and_marked_fake_examples_are_admitted() {
+ let dash5 = "-".repeat(5);
+ let negatives: Vec<String> = vec![
+ // AWS documentation example key id (clearly fake: ends in EXAMPLE).
+ format!("{}IOSFODNN7EXAMPLE", ["AK", "IA"].concat()),
+ // Placeholder GitHub token from docs.
+ format!("{}{}", ["gh", "p_"].concat(), "x".repeat(36)),
+ // Wrong length and prefix glued to a word.
+ format!("{}abc123", ["gh", "p_"].concat()),
+ format!(
+ "my{}{}",
+ ["gh", "p_"].concat(),
+ "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8"
+ ),
+ // Stripe test keys are not live keys.
+ format!(
+ "{}{}",
+ ["sk_", "test_"].concat(),
+ "4eC39HqLyjWDarjtT1zdp7dc"
+ ),
+ // A PEM header in prose with no key body, and a public key block.
+ format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n...\n{dash5}END RSA PRIVATE KEY{dash5}"),
+ format!(
+ "{dash5}BEGIN PUBLIC KEY{dash5}\n{}\n",
+ "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA".repeat(3)
+ ),
+ // Assignments that are not literal secrets.
+ "let token = generate_token_v2(seed_1234567890abcdef );".into(),
+ "password = \"${DB_PASSWORD_FROM_ENVIRONMENT_1}\"".into(),
+ "pub token: String,\n secret: [u8; 32],".into(),
+ "api_key = \"your-api-key-goes-here-123\"".into(),
+ "client_secret = \"EXAMPLE0123456789abcdefEXAMPLE\"".into(),
+ "if token == expected_token_value_1234 {}".into(),
+ "let tokens = Vec::<Token>::with_capacity(1024);".into(),
+ // High-entropy values under names that are not secret-like.
+ "digest = \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 \"".into(),
+ "commit: 2f06c45a1b2c3d4e5f60718293a4b5c6d7e8f901 ".into(),
+ // Rust paths with `::`.
+ "synapse_api::secret_scan::check_blobs(&blobs)?;".into(),
+ // A short hex value named token.
+ "token = \"deadbeef12345678 \"".into(),
+ ];
+ for n in &negatives {
+ assert_eq!(scan(n.as_bytes()), None, "false refusal: {n}");
+ }
+}
+
+#[test]
+fn m1_refusal_names_rule_and_never_echoes_secret_bytes() {
+ for (rule, secret) in planted() {
+ let blob = in_context(rule, &secret);
+ let digest = BlobDigest::compute(&blob);
+ let ok = BlobDigest::compute(b"clean");
+ let err = check_blobs(&[(ok, b"clean".to_vec()), (digest, blob)]).unwrap_err();
+ assert_eq!(err.code, RefusalCode::SecretDetected);
+ let rendered = format!("{err} {err:?}");
+ assert!(rendered.contains(&digest.to_string()));
+ assert!(rendered.contains(&format!("v{SECRET_RULESET_VERSION}")));
+ // No 8-byte window of the secret appears in any rendering of the refusal.
+ let s = secret.as_bytes();
+ for w in s.windows(8) {
+ let w = String::from_utf8_lossy(w);
+ if w.contains('-') || w.contains('\n') {
+ continue; // PEM framing is not secret material.
+ }
+ assert!(!rendered.contains(&*w), "{} leaked into refusal", rule.id());
+ }
+ }
+}
+
+/// Inputs built to make naive or backtracking matchers blow up: every trigger byte repeated,
+/// near-miss prefixes, and long runs that stop one byte short of a match.
+fn adversarial(len: usize) -> Vec<Vec<u8>> {
+ let dash5 = "-".repeat(5);
+ let units: Vec<String> = vec![
+ format!("{dash5}BEGIN RSA PRIVATE KEY{dash5}\n"),
+ format!("{dash5}BEGIN "),
+ "-".into(),
+ ["AK", "IA"].concat(),
+ ["gh", "p_"].concat(),
+ ["github", "_pat_"].concat(),
+ format!("{}1-", ["xo", "xb-"].concat()),
+ ["sk-", "ant-"].concat(),
+ "sk-".into(),
+ "token=".into(),
+ "password:".into(),
+ "a=".into(),
+ "=".into(),
+ ":".into(),
+ format!("secret_token = \"{}\"\n", "Ab1".repeat(50)),
+ format!("api_key={}", "Z9".repeat(64)),
+ "hooks.slack.com/services/".into(),
+ ];
+ let mut out: Vec<Vec<u8>> = units
+ .iter()
+ .map(|u| u.as_bytes().iter().copied().cycle().take(len).collect())
+ .collect();
+ out.push(vec![b'a'; len]);
+ out.push(vec![0u8; len]);
+ let mut g = Gen(42);
+ out.push((0..len).map(|_| g.next() as u8).collect());
+ out
+}
+
+#[test]
+fn m1_adversarial_input_is_linear_in_time_and_steps() {
+ const LEN: usize = 1 << 22; // 4 MiB per input
+ const STEPS_PER_BYTE: u64 = 64;
+ for input in adversarial(LEN) {
+ let t = Instant::now();
+ let (_, steps) = scan_with_steps(&input);
+ let took = t.elapsed();
+ assert!(
+ steps <= STEPS_PER_BYTE * input.len() as u64,
+ "{steps} steps for {} bytes",
+ input.len()
+ );
+ // Generous wall-clock ceiling for an unoptimized test build.
+ assert!(took < Duration::from_secs(10), "took {took:?}");
+ // Doubling the input at most doubles the work (plus a constant).
+ let half = &input[..LEN / 2];
+ let (_, half_steps) = scan_with_steps(half);
+ assert!(steps <= 2 * half_steps + 65_536, "{steps} vs {half_steps}");
+ }
+}
+
+fn source_files(dir: &Path, out: &mut Vec<PathBuf>) {
+ let Ok(rd) = std::fs::read_dir(dir) else {
+ return;
+ };
+ for e in rd.flatten() {
+ let p = e.path();
+ let name = e.file_name();
+ if name == "target" || name.to_string_lossy().starts_with('.') {
+ continue;
+ }
+ if p.is_dir() {
+ source_files(&p, out);
+ } else if matches!(
+ p.extension().and_then(|x| x.to_str()),
+ Some("rs" | "md" | "toml" | "sh" | "json")
+ ) {
+ out.push(p);
+ }
+ }
+}
+
+/// Real AIEN source without secrets: this repository's own crates, docs, and scripts. The
+/// false-refusal count is printed and must be zero.
+#[test]
+fn m1_real_aien_source_is_admitted_with_zero_false_refusals() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+ let mut files = Vec::new();
+ for d in ["crates", "docs", "scripts"] {
+ source_files(&root.join(d), &mut files);
+ }
+ files.sort();
+ assert!(files.len() > 50, "corpus too small: {}", files.len());
+ let mut bytes = 0usize;
+ let mut refused = Vec::new();
+ let t = Instant::now();
+ for f in &files {
+ let data = std::fs::read(f).unwrap();
+ bytes += data.len();
+ if let Some(found) = scan(&data) {
+ refused.push(format!(
+ "{} ({} @ {})",
+ f.display(),
+ found.rule.id(),
+ found.offset
+ ));
+ }
+ }
+ let secs = t.elapsed().as_secs_f64();
+ println!(
+ "m1 corpus: {} files, {} bytes, {} false refusals, {:.6} s scan (debug build)",
+ files.len(),
+ bytes,
+ refused.len(),
+ secs
+ );
+ assert!(refused.is_empty(), "false refusals: {refused:#?}");
+}
+
+fn temp_dir(label: &str) -> PathBuf {
+ std::env::temp_dir().join(format!(
+ "synapse-m1-{label}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ))
+}
+
+fn repo() -> RepoId {
+ RepoId::new("aien-spark/synapse").unwrap()
+}
+
+/// Link nonces for one fixture: SHA-256 of the fixture label and a counter, so every link
+/// gets a fresh nonce and none is a fixed value (same shape as b4_revision_states).
+fn link_nonces(label: &str) -> impl FnMut() -> [u8; 32] {
+ let seed = label.to_owned();
+ let mut issued = 0u32;
+ move || {
+ issued += 1;
+ let mut h = Sha256::new();
+ h.update(seed.as_bytes());
+ h.update(issued.to_le_bytes());
+ h.finalize().into()
+ }
+}
+
+fn open(label: &str) -> SynapseService {
+ SynapseService::open(
+ temp_dir(label),
+ repo(),
+ FsyncPolicy::EveryCommit,
+ RecoveryPolicy::StrictFailClosed,
+ StoreLimits {
+ wal_prealloc_bytes: 64 * 1024,
+ ..Default::default()
+ },
+ )
+ .unwrap()
+}
+
+/// Envelope v1 `submit`: a blob with a secret is refused before any WAL write; a clean blob
+/// in the same service is then admitted.
+#[test]
+fn m1_submit_refuses_secret_blob_before_any_wal_write() {
+ let mut svc = open("submit");
+ let auth = SigningKey::from_bytes(&[10; 32]);
+ svc.register_authority(encode_did_key_ed25519 (&auth.verifying_key().to_bytes()));
+ let agent = SigningKey::from_bytes(&[20; 32]);
+ let agent_did = encode_did_key_ed25519 (&agent.verifying_key().to_bytes());
+ let base = GitOid::compute_blob(b"base");
+ svc.register_base_tree(
+ base,
+ vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())],
+ )
+ .unwrap();
+ let grant = AgentCapabilityGrant::issue(
+ &auth,
+ [1; 32],
+ repo(),
+ agent_did,
+ vec![Capability::Read, Capability::Propose],
+ 1 << 20,
+ 100,
+ 60_000,
+ 10,
+ 100_000,
+ );
+ let request = |body: &[u8], n: u8| {
+ let digest = BlobDigest::compute(body);
+ let mut env = ChangesetEnvelope {
+ version: SYNAPSE_ENVELOPE_VERSION,
+ repo_id: repo(),
+ base_git_oid: base,
+ parent_changesets: vec![],
+ author_did: String::new(),
+ idempotency_key: IdempotencyKey([n; 32]),
+ created_at_ms: 100,
+ intent_summary: "edit config".into(),
+ mutations: vec![PathMutation {
+ path: "src/config.rs".into(),
+ op: MutationOp::Upsert {
+ mode: FileMode::Regular644,
+ blob_digest: digest,
+ size_bytes: body.len() as u64,
+ },
+ }],
+ evidence_receipts: vec![],
+ signature: vec![],
+ };
+ env.sign(&agent);
+ AuthenticatedRequest::sign_new(
+ &agent,
+ grant.clone(),
+ repo(),
+ Capability::Propose,
+ [n; 32],
+ 100,
+ 0,
+ SubmitChangesetPayload {
+ envelope: env,
+ blobs: vec![(digest, body.to_vec())],
+ },
+ )
+ .unwrap()
+ };
+ let before = svc.store().committed_seq();
+ for (i, (rule, secret)) in planted().into_iter().enumerate() {
+ let body = in_context(rule, &secret);
+ let err = svc.submit(&request(&body, 100 + i as u8), 100).unwrap_err();
+ assert_eq!(err.code, RefusalCode::SecretDetected, "{}", rule.id());
+ assert!(!err.message.contains(&secret));
+ assert_eq!(svc.store().committed_seq(), before, "WAL advanced");
+ assert!(svc
+ .read_blob_bytes(BlobDigest::compute(&body), None)
+ .is_err());
+ }
+ let clean = b"pub fn port() -> u16 { 8080 }\n";
+ let out = svc.submit(&request(clean, 1), 100).unwrap();
+ assert!(matches!(out, IngestOutcome::Committed { .. }));
+ assert!(svc.store().committed_seq() > before);
+}
+
+/// Envelope v2 `submit_revision` under an F1 chain: the same refusal, no WAL write.
+#[test]
+fn m1_submit_revision_refuses_secret_blob_before_any_wal_write() {
+ const NOW: u64 = 2_000;
+ const C: ChangeId = ChangeId([0xC1; 16]);
+ let mut svc = open("revision");
+ let a = SigningKey::from_bytes(&[1; 32]);
+ let o = SigningKey::from_bytes(&[2; 32]);
+ svc.auth_mut().register_repo_authority(
+ repo(),
+ encode_did_key_ed25519 (&a.verifying_key().to_bytes()),
+ );
+ let caveats = LinkCaveats {
+ operations: OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]),
+ paths: PathScope::whole_repository(),
+ references: ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]),
+ changes: ChangeScope::any(),
+ quotas: ChainQuotas {
+ max_ops_per_window: 1_000,
+ window_duration_ms: 60_000,
+ storage_bytes: 1 << 30,
+ footprint_paths: 1 << 20,
+ max_bytes_per_op: 1 << 20,
+ },
+ issued_at_ms: 1_000,
+ expires_at_ms: 100_000,
+ };
+ let link = CapabilityLink::issue(
+ &a,
+ ROOT_PARENT,
+ link_nonces("revision")(),
+ repo(),
+ o.verifying_key().to_bytes(),
+ caveats,
+ );
+ let chain = CapabilityChain::new(vec![link]);
+ svc.auth_mut().grant_link(&chain, WalSeq(0), NOW).unwrap();
+ let base_oid = GitOid([0x0B; 20]);
+ svc.register_base_tree(
+ base_oid,
+ vec![("README.md".into(), FileMode::Regular644, b"base".to_vec())],
+ )
+ .unwrap();
+ let base = svc
+ .tree_digest(TreeTarget::BaseGitCommit(base_oid), None)
+ .unwrap();
+ let mut submit = |body: &[u8], n: u8| {
+ let content = RevisionContent {
+ change_id: C,
+ base_tree: base,
+ parents: vec![],
+ mutations: vec![PathMutation {
+ path: "src/lib.rs".into(),
+ op: MutationOp::Upsert {
+ mode: FileMode::Regular644,
+ blob_digest: BlobDigest::compute(body),
+ size_bytes: body.len() as u64,
+ },
+ }],
+ intent_summary: "implement the task".into(),
+ };
+ let env = ChangesetEnvelopeV2::sign_new(&o, repo(), content, IdempotencyKey([n; 32]), NOW);
+ let req = ChainedRequest::sign_new(
+ &o,
+ chain.clone(),
+ repo(),
+ Capability::Propose,
+ RequestScope {
+ paths: vec!["src/lib.rs".into()],
+ reference: None,
+ join_change: Some(C),
+ },
+ [n; 32],
+ NOW,
+ env.encode(),
+ );
+ let blobs = vec![(BlobDigest::compute(body), body.to_vec())];
+ let before = svc.store().committed_seq();
+ let r = svc.submit_revision(&req, &blobs, NOW);
+ (r.map(|_| ()), before, svc.store().committed_seq())
+ };
+ let (rule, secret) = planted().swap_remove(5);
+ let body = in_context(rule, &secret);
+ let (r, before, after) = submit(&body, 7);
+ let err = r.unwrap_err();
+ assert_eq!(err.code, RefusalCode::SecretDetected);
+ assert!(!err.message.contains(&secret));
+ assert_eq!(before, after, "WAL advanced on a refused secret");
+ let (r, before, after) = submit(b"pub fn ok() {}\n", 8);
+ r.unwrap();
+ assert!(after > before);
+}
diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs
index 4bceed1 ..61eb612 100644
--- a/crates/synapse-core/src/lib.rs
+++ b/crates/synapse-core/src/lib.rs
@@ -188,6 +188,13 @@ pub enum RefusalCode {
RadicleQuorumInsufficient,
StaleBaseHead,
SplitBrainDivergence,
+
+ // Content admission refusals
+ /// An admitted blob matches a rule of the versioned secret-scanning rule set (a private key
+ /// block, a provider token format, or a high-entropy value assigned to a secret-like name).
+ /// The refusal names the rule and byte offset only, never the matched bytes (ADR 0003
+ /// section 5.13, step M1).
+ SecretDetected,
}
/// Structured error pairing a deterministic `RefusalCode` with diagnostic context.
diff --git a/crates/synapse-store/src/a1_tests.rs b/crates/synapse-store/src/a1_tests.rs
index 2c2d28e ..735a56d 100644
--- a/crates/synapse-store/src/a1_tests.rs
+++ b/crates/synapse-store/src/a1_tests.rs
@@ -135,7 +135,7 @@ fn v2_flags(dir: &Path) -> Vec<u8> {
}
/// Every v1 JSON record payload in both fixtures.
-fn fixture_json_records() -> Vec<Vec<u8>> {
+pub(super) fn fixture_json_records() -> Vec<Vec<u8>> {
let mut out = Vec::new();
for (kind, flags, json) in
v1_log_frames(&fs::read(fixture_dir("v1-wal-log").join("wal.log")).unwrap())
@@ -189,7 +189,7 @@ fn a1_every_record_kind_matches_its_v1_json_form_in_both_directions() {
);
}
-fn edge_records() -> Vec<WalRecord> {
+pub(super) fn edge_records() -> Vec<WalRecord> {
let key = SigningKey::from_bytes(&[0xE1; 32]);
let a = BlobDigest::compute(b"a");
let mut env = ChangesetEnvelope {
diff --git a/crates/synapse-store/src/codec.rs b/crates/synapse-store/src/codec.rs
index 46a5def ..d38ad08 100644
--- a/crates/synapse-store/src/codec.rs
+++ b/crates/synapse-store/src/codec.rs
@@ -1057,7 +1057,7 @@ impl CheckpointState {
}
}
- fn encode_content(&self) -> SynapseResult<Vec<u8>> {
+ pub(crate) fn encode_content(&self) -> SynapseResult<Vec<u8>> {
self.check_keys()?;
let mut w = Writer(Vec::with_capacity(4096));
w.u8(CODEC_V2);
@@ -1096,7 +1096,7 @@ impl CheckpointState {
Ok(w.0)
}
- fn decode_content(
+ pub(crate) fn decode_content(
bytes: &[u8],
checkpoint_seq: WalSeq,
anchor_frame_sha256: [u8; 32],
diff --git a/crates/synapse-store/src/j1_corpus.rs b/crates/synapse-store/src/j1_corpus.rs
new file mode 100644
index 0000000 ..1df32ad
--- /dev/null
+++ b/crates/synapse-store/src/j1_corpus.rs
@@ -0,0 +1,1046 @@
+//! J1 cross-check corpus for the Omega port of the binary codec (ADR 0003 section 9 step 33).
+//!
+//! The Rust codec (`codec.rs`) is the specification by test (ADR 0003 section 5.12). This
+//! module writes what "decodes and re-encodes every record byte for byte, refuses the
+//! malformed corpus identically" means for a port into one language-neutral file, sealed in
+//! `evidence/j1-codec-corpus/corpus.bin`: every base record and checkpoint content with its
+//! logical form, and every A1 malformed case (the mutation set of `a1_malformed_corpus.rs`)
+//! with the outcome the Rust decoder gives. The format and the logical form are specified in
+//! `docs/J1_OMEGA_CODEC.md`.
+//!
+//! `J1_CORPUS_WRITE=1 cargo test -p synapse-store --lib j1_corpus` rewrites the file; without
+//! it the test only checks that the sealed file is what the codec gives today.
+
+use super::a1_tests::{edge_records, fixture_dir, fixture_json_records};
+use super::*;
+use crate::codec::*;
+use ed25519 _dalek::SigningKey;
+use synapse_core::{ChangeId, FileMode, PathMutation, RevisionContent, TreeDigest};
+
+/// The sealed corpus, relative to the repository root.
+const CORPUS_PATH: &str = "evidence/j1-codec-corpus/corpus.bin";
+/// SHA-256 of the sealed corpus, so the seal is checked by a test, not by hand.
+const CORPUS_SHA256: &str = "469a25239b6d683d137497b8cab1bebb186e11b180fb5061723af2fe8f6bb8b7 ";
+const MAGIC: [u8; 8] = *b"SYNJ1COD";
+const VERSION: u16 = 1;
+/// Record cap of the A1 malformed corpus (`a1_malformed_corpus.rs`).
+const CAP: u64 = 2048;
+
+// Logical-form token types (docs/J1_OMEGA_CODEC.md section 3).
+const T_U16: u64 = 2;
+const T_U64: u64 = 4;
+const T_BOOL: u64 = 5;
+const T_TAG: u64 = 6;
+const T_FIX: u64 = 7;
+const T_STR: u64 = 8;
+const T_BYTES: u64 = 9;
+const T_REPO: u64 = 10;
+const T_COUNT: u64 = 11;
+
+/// Field names a refusal can carry, in id order (id = index + 1; 0 means none).
+const FIELDS: [&str; 15] = [
+ "bool",
+ "option",
+ "mutation op",
+ "file mode",
+ "record kind",
+ "envelope v2",
+ "chain path",
+ "obsolescence marker",
+ "changesets",
+ "idempotency index",
+ "blob visibility",
+ "projections",
+ "canonical heads",
+ "revision records",
+ "revision record kind",
+];
+/// Refusal codes an embedded `synapse-core` decoder gives, in id order (id = index + 1).
+const CODES: [RefusalCode; 2] = [
+ RefusalCode::EnvelopeMalformed,
+ RefusalCode::EnvelopeVersionUnsupported,
+];
+/// `CodecRefusal` kinds in id order (id = index + 1).
+const KINDS: [&str; 9] = [
+ "Truncated",
+ "LengthOverCap",
+ "TrailingBytes",
+ "UnknownTag",
+ "InvalidUtf8",
+ "VersionUnsupported",
+ "NotCanonical",
+ "InvalidRepoId",
+ "EmbeddedMalformed",
+];
+
+const ENTRY_RECORD: u8 = 1;
+const ENTRY_CHECKPOINT: u8 = 2;
+/// A refused base is itself the case input (op 0).
+const OP_AS_IS: u8 = 0;
+const OP_TRUNCATE: u8 = 1;
+const OP_FLIP: u8 = 2;
+const OP_FALSE_LENGTH: u8 = 3;
+
+// ---------------------------------------------------------------------------------------
+// Logical form: the typed fields of a record, in encoding order, without derived lengths
+// or constant bytes.
+// ---------------------------------------------------------------------------------------
+
+#[derive(Default)]
+struct Lf(Vec<u64>);
+
+impl Lf {
+ fn scalar(&mut self, t: u64, v: u64) {
+ self.0.push(t | 1 << 8);
+ self.0.push(v);
+ }
+ fn run(&mut self, t: u64, b: &[u8]) {
+ self.0.push(t | (b.len() as u64) << 8);
+ self.0.extend(b.iter().map(|&x| u64::from(x)));
+ }
+ fn u64(&mut self, v: u64) {
+ self.scalar(T_U64, v);
+ }
+ fn bool(&mut self, v: bool) {
+ self.scalar(T_BOOL, u64::from(v));
+ }
+ fn tag(&mut self, v: u8) {
+ self.scalar(T_TAG, u64::from(v));
+ }
+ fn count(&mut self, n: usize) {
+ self.scalar(T_COUNT, n as u64);
+ }
+ fn fix(&mut self, b: &[u8]) {
+ self.run(T_FIX, b);
+ }
+ fn str(&mut self, s: &str) {
+ self.run(T_STR, s.as_bytes());
+ }
+ fn repo(&mut self, r: &RepoId) {
+ self.run(T_REPO, r.as_str().as_bytes());
+ }
+
+ fn attachment(&mut self, a: &EvidenceAttachment) {
+ self.str(&a.gate_name);
+ self.bool(a.passed);
+ self.fix(&a.artifact_digest);
+ self.str(&a.summary);
+ }
+ fn attachments(&mut self, v: &[EvidenceAttachment]) {
+ self.count(v.len());
+ v.iter().for_each(|a| self.attachment(a));
+ }
+ fn mutations(&mut self, v: &[PathMutation]) {
+ self.count(v.len());
+ for m in v {
+ self.str(&m.path);
+ match &m.op {
+ MutationOp::Upsert {
+ mode,
+ blob_digest,
+ size_bytes,
+ } => {
+ self.tag(1);
+ self.tag(mode.tag_byte());
+ self.fix(&blob_digest.0);
+ self.u64(*size_bytes);
+ }
+ MutationOp::Delete => self.tag(2),
+ }
+ }
+ }
+ fn ids(&mut self, v: impl ExactSizeIterator<Item = [u8; 32]>) {
+ self.count(v.len());
+ v.for_each(|id| self.fix(&id));
+ }
+ fn envelope(&mut self, e: &ChangesetEnvelope) {
+ self.scalar(T_U16, u64::from(e.version));
+ self.repo(&e.repo_id);
+ self.fix(&e.base_git_oid.0);
+ self.ids(e.parent_changesets.iter().map(|p| p.0));
+ self.str(&e.author_did);
+ self.fix(&e.idempotency_key.0);
+ self.u64(e.created_at_ms);
+ self.str(&e.intent_summary);
+ self.mutations(&e.mutations);
+ self.attachments(&e.evidence_receipts);
+ self.run(T_BYTES, &e.signature);
+ }
+ fn review(&mut self, r: &ReviewRecord) {
+ self.str(&r.reviewer_did);
+ self.bool(r.approved);
+ self.str(&r.comment);
+ self.u64(r.recorded_at_ms);
+ }
+ fn projection(&mut self, p: &GitHubPullRequestProjection) {
+ self.repo(&p.repo_id);
+ self.u64(p.pr_number);
+ self.fix(&p.changeset_id.0);
+ self.fix(&p.head_git_oid.0);
+ self.fix(&p.base_git_oid.0);
+ self.str(&p.pr_branch_ref);
+ self.str(&p.title);
+ self.str(&p.body_markdown);
+ self.fix(&p.evidence_summary_digest);
+ self.bool(p.github_merged);
+ }
+ fn canonical(&mut self, c: &RadicleCanonicalHead) {
+ self.repo(&c.repo_id);
+ self.str(&c.default_branch);
+ self.fix(&c.canonical_git_oid.0);
+ match &c.promoted_changeset_id {
+ Some(id) => {
+ self.tag(1);
+ self.fix(&id.0);
+ }
+ None => self.tag(0),
+ }
+ self.fix(&c.rad_id_commit_oid.0);
+ self.u64(c.threshold as u64);
+ self.count(c.verified_delegates.len());
+ c.verified_delegates.iter().for_each(|d| self.str(d));
+ self.u64(c.verified_at_ms);
+ }
+ fn stored(&mut self, s: &StoredChangeset) {
+ self.fix(&s.changeset_id.0);
+ self.u64(s.committed_seq.0);
+ self.envelope(&s.envelope);
+ self.attachments(&s.evaluations);
+ self.count(s.reviews.len());
+ s.reviews.iter().for_each(|r| self.review(r));
+ self.u64(s.lease_expires_at_ms);
+ }
+ fn chain(&mut self, c: &ChainPath) {
+ self.ids(c.links().iter().copied());
+ }
+ fn record(&mut self, r: &WalRecord) {
+ self.tag(r.kind_byte());
+ match r {
+ WalRecord::ChangesetIngest {
+ envelope,
+ changeset_id,
+ new_blobs,
+ } => {
+ self.envelope(envelope);
+ self.fix(&changeset_id.0);
+ self.ids(new_blobs.iter().map(|b| b.0));
+ }
+ WalRecord::EvaluationAttached {
+ changeset_id,
+ attachment,
+ } => {
+ self.fix(&changeset_id.0);
+ self.attachment(attachment);
+ }
+ WalRecord::ReviewRecorded {
+ changeset_id,
+ review,
+ } => {
+ self.fix(&changeset_id.0);
+ self.review(review);
+ }
+ WalRecord::GitProjected { projection } => self.projection(projection),
+ WalRecord::CanonicalPromoted { canonical } => self.canonical(canonical),
+ WalRecord::LeaseUpdated {
+ changeset_id,
+ lease_expires_at_ms,
+ } => {
+ self.fix(&changeset_id.0);
+ self.u64(*lease_expires_at_ms);
+ }
+ WalRecord::RevisionAdmitted {
+ envelope,
+ chain,
+ admitted_at_ms,
+ new_blobs,
+ } => {
+ let c = &envelope.content;
+ self.fix(&c.change_id.0);
+ self.fix(&c.base_tree.0);
+ self.ids(c.parents.iter().map(|p| p.0));
+ self.mutations(&c.mutations);
+ self.str(&c.intent_summary);
+ let a = &envelope.attestation;
+ self.repo(&a.repo_id);
+ self.fix(&a.changeset_id.0);
+ self.fix(&a.author_key);
+ self.fix(&a.idempotency_key.0);
+ self.u64(a.attested_at_ms);
+ self.fix(&a.signature);
+ self.chain(chain);
+ self.u64(*admitted_at_ms);
+ self.ids(new_blobs.iter().map(|b| b.0));
+ }
+ WalRecord::ObsolescenceRecorded {
+ marker,
+ chain,
+ recorded_at_ms,
+ } => {
+ self.repo(&marker.repo_id);
+ self.fix(&marker.change_id.0);
+ self.fix(&marker.predecessor.0);
+ self.ids(marker.successors.iter().map(|s| s.0));
+ self.fix(&marker.signer_key);
+ self.u64(marker.signed_at_ms);
+ self.fix(&marker.signature);
+ self.chain(chain);
+ self.u64(*recorded_at_ms);
+ }
+ // Kinds 9 and 11 landed on main after this corpus was sealed; the corpus covers
+ // kinds 1 to 8 only (see the coverage test), so no corpus record reaches here.
+ WalRecord::RevisionStateMoved { .. } | WalRecord::DerivedRevisionAdmitted { .. } => {
+ unreachable!("J1 corpus does not yet cover record kinds 9 and 11")
+ }
+ }
+ }
+ fn checkpoint(&mut self, s: &CheckpointState) {
+ self.count(s.changesets.len());
+ s.changesets.values().for_each(|c| self.stored(c));
+ self.count(s.idempotency_index.len());
+ for ((repo, key), (seq, id)) in &s.idempotency_index {
+ self.repo(repo);
+ self.fix(&key.0);
+ self.u64(seq.0);
+ self.fix(&id.0);
+ }
+ self.count(s.blob_first_visible_seq.len());
+ for (d, seq) in &s.blob_first_visible_seq {
+ self.fix(&d.0);
+ self.u64(seq.0);
+ }
+ self.count(s.github_projections.len());
+ s.github_projections
+ .values()
+ .for_each(|p| self.projection(p));
+ self.count(s.canonical_heads.len());
+ s.canonical_heads.values().for_each(|c| self.canonical(c));
+ // Always present in the logical form; the bytes hold the section only when n > 0.
+ self.count(s.revision_log.len());
+ for (seq, r) in &s.revision_log {
+ self.u64(seq.0);
+ self.record(r);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------
+// Bases and outcomes
+// ---------------------------------------------------------------------------------------
+
+/// A test signing key derived from a label (no literal key material in the source).
+fn derived_key(label: &str) -> SigningKey {
+ SigningKey::from_bytes(&Sha256::digest(label.as_bytes()).into())
+}
+
+fn derived32(label: &str) -> [u8; 32] {
+ Sha256::digest(label.as_bytes()).into()
+}
+
+fn repo() -> RepoId {
+ RepoId::new("aien-dev/synapse").unwrap()
+}
+
+fn chain(depth: usize) -> ChainPath {
+ ChainPath::new(
+ (0..depth)
+ .map(|i| derived32(&format!("j1 link {i}")))
+ .collect(),
+ )
+ .unwrap()
+}
+
+/// Kind 7 and kind 8 records (on `main`; kinds 9 to 11 are reserved by open PRs).
+fn revision_records() -> Vec<WalRecord> {
+ let author = derived_key("j1 corpus author");
+ let blob = |s: &str| BlobDigest::compute(s.as_bytes());
+ let mut parents = vec![
+ ChangesetId(derived32("j1 parent a")),
+ ChangesetId(derived32("j1 parent b")),
+ ];
+ parents.sort();
+ let content = RevisionContent {
+ change_id: ChangeId(derived32("j1 change")[..16].try_into().unwrap()),
+ base_tree: TreeDigest(derived32("j1 base tree")),
+ parents,
+ mutations: vec![
+ PathMutation {
+ path: "bin/run".into(),
+ op: MutationOp::Upsert {
+ mode: FileMode::Executable755,
+ blob_digest: blob("run"),
+ size_bytes: 3,
+ },
+ },
+ PathMutation {
+ path: "old.txt".into(),
+ op: MutationOp::Delete,
+ },
+ PathMutation {
+ path: "src/lib.rs".into(),
+ op: MutationOp::Upsert {
+ mode: FileMode::Regular644,
+ blob_digest: blob("lib"),
+ size_bytes: u64::MAX,
+ },
+ },
+ ],
+ intent_summary: "j1: été 🦀".into(),
+ };
+ let change_id = content.change_id;
+ let env = ChangesetEnvelopeV2::sign_new(
+ &author,
+ repo(),
+ content,
+ IdempotencyKey(derived32("j1 idempotency")),
+ 1_000,
+ );
+ let id = env.changeset_id();
+ let mut successors = vec![
+ ChangesetId(derived32("j1 successor a")),
+ ChangesetId(derived32("j1 successor b")),
+ ];
+ successors.sort();
+ vec![
+ WalRecord::RevisionAdmitted {
+ envelope: env,
+ chain: chain(3),
+ admitted_at_ms: 5_000,
+ new_blobs: vec![blob("run"), blob("lib")],
+ },
+ WalRecord::ObsolescenceRecorded {
+ marker: ObsolescenceMarker::sign_new(&author, repo(), change_id, id, successors, 6_000),
+ chain: chain(1),
+ recorded_at_ms: 7_000,
+ },
+ WalRecord::ObsolescenceRecorded {
+ marker: ObsolescenceMarker::sign_new(
+ &author,
+ RepoId::new("x").unwrap(),
+ change_id,
+ id,
+ vec![],
+ 0,
+ ),
+ chain: chain(16),
+ recorded_at_ms: u64::MAX,
+ },
+ ]
+}
+
+fn fixture_state() -> CheckpointState {
+ let manifest: CheckpointManifest =
+ serde_json::from_slice(&fs::read(fixture_dir("v1-wal-log").join("checkpoint.v1")).unwrap())
+ .unwrap();
+ CheckpointState::from_v1_manifest(manifest).unwrap()
+}
+
+/// A checkpoint with a revision section (kinds 7 and 8).
+fn revision_state() -> CheckpointState {
+ let r = revision_records();
+ let mut s = CheckpointState {
+ checkpoint_seq: WalSeq(9),
+ anchor_frame_sha256: derived32("j1 anchor"),
+ ..Default::default()
+ };
+ for (i, label) in ["run", "lib"].iter().enumerate() {
+ s.blob_first_visible_seq
+ .insert(BlobDigest::compute(label.as_bytes()), WalSeq(4 + i as u64));
+ }
+ s.revision_log = vec![(WalSeq(4), r[0].clone()), (WalSeq(9), r[1].clone())];
+ s
+}
+
+/// One base: a record or a checkpoint content, its bytes, and its logical form.
+struct Base {
+ entry: u8,
+ cap: u64,
+ checkpoint_seq: u64,
+ anchor: [u8; 32],
+ label: String,
+ bytes: Vec<u8>,
+ /// `None`: a hand-made input the decoder refuses (no logical form, one op-0 case).
+ lf: Option<Vec<u64>>,
+ mutate: bool,
+}
+
+fn record_base(label: String, r: &WalRecord, mutate: bool) -> Base {
+ let mut lf = Lf::default();
+ lf.record(r);
+ Base {
+ entry: ENTRY_RECORD,
+ cap: CAP,
+ checkpoint_seq: 0,
+ anchor: [0u8; 32],
+ label,
+ bytes: encode_record(r).unwrap(),
+ lf: Some(lf.0),
+ mutate,
+ }
+}
+
+fn checkpoint_base(label: &str, s: &CheckpointState) -> Base {
+ let mut lf = Lf::default();
+ lf.checkpoint(s);
+ Base {
+ entry: ENTRY_CHECKPOINT,
+ cap: 0,
+ checkpoint_seq: s.checkpoint_seq.0,
+ anchor: s.anchor_frame_sha256,
+ label: label.into(),
+ bytes: s.encode_content().unwrap(),
+ lf: Some(lf.0),
+ mutate: true,
+ }
+}
+
+fn bases() -> Vec<Base> {
+ let mut out = Vec::new();
+ let mut first_of_kind = BTreeSet::new();
+ for (i, json) in fixture_json_records().iter().enumerate() {
+ let r: WalRecord = serde_json::from_slice(json).unwrap();
+ // The A1 malformed corpus mutates the first record of each kind of the v1 log.
+ let mutate = first_of_kind.insert(r.kind_byte());
+ out.push(record_base(format!("fixture record {i}"), &r, mutate));
+ }
+ for (i, r) in edge_records().iter().enumerate() {
+ out.push(record_base(format!("edge record {i}"), r, false));
+ }
+ for (i, r) in revision_records().iter().enumerate() {
+ out.push(record_base(format!("revision record {i}"), r, i < 2));
+ }
+ let fixture = checkpoint_base("fixture checkpoint", &fixture_state());
+ let revision = checkpoint_base("revision checkpoint", &revision_state());
+ // Hand-made inputs no mutation reaches: record kinds 9 to 11 (reserved by open PRs, refused
+ // on `main`), a revision section that is empty, and one that holds a kind 6 record.
+ for kind in 9u8..=11 {
+ out.push(refused_base(
+ format!("reserved record kind {kind}"),
+ ENTRY_RECORD,
+ CAP,
+ 0,
+ [0u8; 32],
+ vec![CODEC_V2, kind, 0, 0],
+ ));
+ }
+ let mut empty_section = fixture.bytes.clone();
+ empty_section.extend_from_slice(&0u32.to_le_bytes());
+ out.push(refused_base(
+ "empty revision section".into(),
+ ENTRY_CHECKPOINT,
+ 0,
+ fixture.checkpoint_seq,
+ fixture.anchor,
+ empty_section,
+ ));
+ // Two projections, the second renumbered below the first: keys out of order.
+ let mut two = fixture_state();
+ let mut p = two.github_projections.values().next().unwrap().clone();
+ let first = p.pr_number;
+ p.pr_number = first + 1;
+ let p_bytes = encode_record(&WalRecord::GitProjected {
+ projection: p.clone(),
+ })
+ .unwrap()[2..]
+ .to_vec();
+ two.github_projections.insert(p.pr_number, p.clone());
+ let mut misordered = two.encode_content().unwrap();
+ let at = misordered
+ .windows(p_bytes.len())
+ .position(|w| w == p_bytes.as_slice())
+ .unwrap();
+ let num_at = at + 4 + p.repo_id.as_str().len();
+ misordered[num_at..num_at + 8].copy_from_slice(&(first - 1).to_le_bytes());
+ out.push(refused_base(
+ "projections out of order".into(),
+ ENTRY_CHECKPOINT,
+ 0,
+ two.checkpoint_seq.0,
+ two.anchor_frame_sha256,
+ misordered,
+ ));
+ out.extend(equal_key_bases(&fixture_state()));
+ out.extend(repo_id_bases());
+ let mut same_seq = revision_state();
+ same_seq.revision_log[1].0 = same_seq.revision_log[0].0;
+ out.push(refused_base(
+ "revision records with equal seqs".into(),
+ ENTRY_CHECKPOINT,
+ 0,
+ same_seq.checkpoint_seq.0,
+ same_seq.anchor_frame_sha256,
+ same_seq.encode_content().unwrap(),
+ ));
+ let mut wrong_kind = revision_state();
+ let lease = WalRecord::LeaseUpdated {
+ changeset_id: ChangesetId(derived32("j1 lease")),
+ lease_expires_at_ms: 1,
+ };
+ wrong_kind.revision_log = vec![(WalSeq(2), lease)];
+ out.push(refused_base(
+ "revision section holding kind 6".into(),
+ ENTRY_CHECKPOINT,
+ 0,
+ wrong_kind.checkpoint_seq.0,
+ wrong_kind.anchor_frame_sha256,
+ wrong_kind.encode_content().unwrap(),
+ ));
+ out.push(fixture);
+ out.push(revision);
+ out
+}
+
+/// Hand-made checkpoints whose map holds two entries with equal keys (each map's keys must be
+/// strictly increasing): the map's first entry is cloned under a fresh key above it, the state
+/// is encoded, and the clone's key bytes are set back to the first key.
+fn equal_key_bases(s: &CheckpointState) -> Vec<Base> {
+ fn above(mut k: [u8; 32]) -> [u8; 32] {
+ assert!(k[31] < 255, "test key ends in 0xff");
+ k[31] += 1;
+ k
+ }
+ /// `content` with its only occurrence of `from` replaced by `to` (lengths may differ: the
+ /// patched run is a length-prefixed string or fixed bytes).
+ fn patched(content: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
+ let hits: Vec<usize> = content
+ .windows(from.len())
+ .enumerate()
+ .filter(|(_, w)| *w == from)
+ .map(|(i, _)| i)
+ .collect();
+ assert_eq!(hits.len(), 1, "the clone's key must occur exactly once");
+ let mut v = content.to_vec();
+ v.splice(hits[0]..hits[0] + from.len(), to.iter().copied());
+ v
+ }
+ let le = |v: u64| v.to_le_bytes();
+ let mut out = Vec::new();
+ let mut push = |label: &str, t: &CheckpointState, from: Vec<u8>, to: Vec<u8>| {
+ out.push(refused_base(
+ format!("equal keys: {label}"),
+ ENTRY_CHECKPOINT,
+ 0,
+ t.checkpoint_seq.0,
+ t.anchor_frame_sha256,
+ patched(&t.encode_content().unwrap(), &from, &to),
+ ));
+ };
+
+ let (id, first) = s.changesets.iter().next().expect("fixture changeset");
+ let mut t = s.clone();
+ let mut c = first.clone();
+ c.changeset_id = ChangesetId(above(id.0));
+ t.changesets.insert(c.changeset_id, c.clone());
+ let seq = le(c.committed_seq.0);
+ push(
+ "changesets",
+ &t,
+ [&c.changeset_id.0[..], &seq].concat(),
+ [&id.0[..], &seq].concat(),
+ );
+
+ let ((repo, key), v) = s
+ .idempotency_index
+ .iter()
+ .next()
+ .expect("fixture idempotency entry");
+ let mut t = s.clone();
+ let key2 = IdempotencyKey(above(key.0));
+ t.idempotency_index.insert((repo.clone(), key2), *v);
+ let seq = le(v.0 .0);
+ push(
+ "idempotency index",
+ &t,
+ [&key2.0[..], &seq].concat(),
+ [&key.0[..], &seq].concat(),
+ );
+
+ let mut t = s.clone();
+ let d = BlobDigest::compute(b"j1 equal key blob");
+ t.blob_first_visible_seq.insert(d, WalSeq(1));
+ let d2 = BlobDigest(above(d.0));
+ t.blob_first_visible_seq.insert(d2, WalSeq(1));
+ push(
+ "blob visibility",
+ &t,
+ [&d2.0[..], &le(1)].concat(),
+ [&d.0[..], &le(1)].concat(),
+ );
+
+ let first = s
+ .github_projections
+ .values()
+ .next()
+ .expect("fixture projection");
+ let mut t = s.clone();
+ let mut p = first.clone();
+ p.pr_number = first.pr_number + 1;
+ t.github_projections.insert(p.pr_number, p.clone());
+ let head = |n: u64| {
+ let r = p.repo_id.as_str().as_bytes();
+ [
+ &(r.len() as u32).to_le_bytes()[..],
+ r,
+ &le(n),
+ &p.changeset_id.0,
+ ]
+ .concat()
+ };
+ push("projections", &t, head(p.pr_number), head(first.pr_number));
+
+ let (repo, h) = s
+ .canonical_heads
+ .iter()
+ .next()
+ .expect("fixture canonical head");
+ let mut t = s.clone();
+ let repo2 = RepoId::new(format!("{}-j1", repo.as_str())).unwrap();
+ let mut h2 = h.clone();
+ h2.repo_id = repo2.clone();
+ t.canonical_heads.insert(repo2.clone(), h2);
+ let run = |r: &RepoId| {
+ let b = r.as_str().as_bytes();
+ [&(b.len() as u32).to_le_bytes()[..], b].concat()
+ };
+ push("canonical heads", &t, run(&repo2), run(repo));
+ out
+}
+
+/// Hand-made records whose repository id breaks one `RepoId::new` rule each (bit flips reach
+/// only some of them): a projection record with its repository id bytes replaced.
+fn repo_id_bases() -> Vec<Base> {
+ let p = fixture_json_records()
+ .iter()
+ .map(|j| serde_json::from_slice::<WalRecord>(j).unwrap())
+ .find(|r| r.kind_byte() == 4)
+ .expect("fixture projection record");
+ let bytes = encode_record(&p).unwrap();
+ let n = u32::from_le_bytes(bytes[2..6].try_into().unwrap()) as usize;
+ assert!(n >= 4, "fixture repository id too short");
+ let good = bytes[6..6 + n].to_vec();
+ let with = |label: &str, repo: Vec<u8>| {
+ let mut b = bytes[..2].to_vec();
+ b.extend_from_slice(&(repo.len() as u32).to_le_bytes());
+ b.extend_from_slice(&repo);
+ b.extend_from_slice(&bytes[6 + n..]);
+ refused_base(
+ format!("repository id: {label}"),
+ ENTRY_RECORD,
+ CAP,
+ 0,
+ [0u8; 32],
+ b,
+ )
+ };
+ let at = |i: usize, s: &[u8]| {
+ let mut r = good.clone();
+ r[i..i + s.len()].copy_from_slice(s);
+ r
+ };
+ vec![
+ with("empty", Vec::new()),
+ with("129 bytes", vec![b'a'; 129]),
+ with("leading slash", at(0, b"/")),
+ with("trailing slash", at(n - 1, b"/")),
+ with("double slash", at(1, b"//")),
+ with("double dot", at(1, b"..")),
+ with("space", at(1, b" ")),
+ with("two-byte UTF-8 letter", at(1, "\u{e9}".as_bytes())),
+ ]
+}
+
+fn refused_base(
+ label: String,
+ entry: u8,
+ cap: u64,
+ checkpoint_seq: u64,
+ anchor: [u8; 32],
+ bytes: Vec<u8>,
+) -> Base {
+ Base {
+ entry,
+ cap,
+ checkpoint_seq,
+ anchor,
+ label,
+ bytes,
+ lf: None,
+ mutate: false,
+ }
+}
+
+/// The A1 mutation set (`a1_malformed_corpus.rs` `mutations`): every truncation, every bit
+/// flip, and a false `u32` length at every offset.
+fn mutations(bytes: &[u8]) -> Vec<(u8, u32, u32, Vec<u8>)> {
+ let mut out = Vec::new();
+ for n in 0..bytes.len() {
+ out.push((OP_TRUNCATE, n as u32, 0, bytes[..n].to_vec()));
+ }
+ for bit in 0..bytes.len() * 8 {
+ let mut b = bytes.to_vec();
+ b[bit / 8] ^= 1 << (bit % 8);
+ out.push((OP_FLIP, bit as u32, 0, b));
+ }
+ for off in 0..bytes.len().saturating_sub(3) {
+ let remaining = (bytes.len() - off - 4) as u64;
+ for declared in [remaining + 1, CAP + 1, u64::from(u32::MAX)] {
+ let mut b = bytes.to_vec();
+ b[off..off + 4].copy_from_slice(&(declared as u32).to_le_bytes());
+ out.push((OP_FALSE_LENGTH, off as u32, declared as u32, b));
+ }
+ }
+ out
+}
+
+/// The cases of one base: its A1 mutations, or itself when it is a hand-made refusal.
+fn cases_of(b: &Base) -> Vec<(u8, u32, u32, Vec<u8>)> {
+ match (&b.lf, b.mutate) {
+ (None, _) => vec![(OP_AS_IS, 0, 0, b.bytes.clone())],
+ (Some(_), true) => mutations(&b.bytes),
+ (Some(_), false) => Vec::new(),
+ }
+}
+
+/// `(kind, at, x, y, field)`; kind 0 is an accept.
+type Outcome = (u8, u32, u32, u32, u8);
+
+fn field_id(f: &str) -> u8 {
+ let i = FIELDS.iter().position(|&n| n == f);
+ i.map(|i| i as u8 + 1)
+ .unwrap_or_else(|| panic!("field {f:?} missing from the J1 field table"))
+}
+
+fn n32<T: TryInto<u32>>(v: T) -> u32 {
+ v.try_into()
+ .unwrap_or_else(|_| panic!("refusal value above u32"))
+}
+
+fn outcome_of(r: &CodecRefusal) -> Outcome {
+ let k = KINDS.iter().position(|&n| n == r.kind()).unwrap() as u8 + 1;
+ match r {
+ CodecRefusal::Truncated { at, need } => (k, n32(*at), n32(*need), 0, 0),
+ CodecRefusal::LengthOverCap { at, declared, cap } => {
+ (k, n32(*at), n32(*declared), n32(*cap), 0)
+ }
+ CodecRefusal::TrailingBytes { at, count } => (k, n32(*at), n32(*count), 0, 0),
+ CodecRefusal::UnknownTag { at, field, tag } => {
+ (k, n32(*at), u32::from(*tag), 0, field_id(field))
+ }
+ CodecRefusal::InvalidUtf8 { at } => (k, n32(*at), 0, 0, 0),
+ CodecRefusal::VersionUnsupported { found } => (k, 0, u32::from(*found), 0, 0),
+ CodecRefusal::NotCanonical { at, field } => (k, n32(*at), 0, 0, field_id(field)),
+ CodecRefusal::InvalidRepoId { at } => (k, n32(*at), 0, 0, 0),
+ CodecRefusal::EmbeddedMalformed { at, field, code } => {
+ let c = CODES.iter().position(|x| x == code).unwrap_or_else(|| {
+ panic!("embedded refusal code {code:?} missing from the J1 code table")
+ });
+ (k, n32(*at), c as u32 + 1, 0, field_id(field))
+ }
+ }
+}
+
+/// What the Rust decoder does with `m` under base `b`. An accept must be canonical.
+fn decide(b: &Base, m: &[u8]) -> Outcome {
+ match b.entry {
+ ENTRY_RECORD => match decode_record(m, b.cap) {
+ Ok(r) => {
+ assert_eq!(
+ encode_record(&r).unwrap(),
+ m,
+ "{}: non-canonical accept",
+ b.label
+ );
+ (0, 0, 0, 0, 0)
+ }
+ Err(e) => outcome_of(&e),
+ },
+ _ => match CheckpointState::decode_content(m, WalSeq(b.checkpoint_seq), b.anchor) {
+ Ok(s) => {
+ assert_eq!(
+ s.encode_content().unwrap(),
+ m,
+ "{}: non-canonical accept",
+ b.label
+ );
+ (0, 0, 0, 0, 0)
+ }
+ Err(e) => outcome_of(&e),
+ },
+ }
+}
+
+// ---------------------------------------------------------------------------------------
+// File
+// ---------------------------------------------------------------------------------------
+
+fn put_name(out: &mut Vec<u8>, s: &str) {
+ out.extend_from_slice(&(s.len() as u16).to_le_bytes());
+ out.extend_from_slice(s.as_bytes());
+}
+
+/// Corpus bytes and a per-class tally `(class, cases, refused)`.
+fn build() -> (Vec<u8>, BTreeMap<String, (usize, usize)>) {
+ let bases = bases();
+ let mut out = Vec::new();
+ out.extend_from_slice(&MAGIC);
+ out.extend_from_slice(&VERSION.to_le_bytes());
+ out.extend_from_slice(&0u16.to_le_bytes());
+ out.extend_from_slice(&(CAP as u32).to_le_bytes());
+ // Rust layout sizes the record decoder's reservation check depends on (LengthOverCap).
+ let layout = [
+ std::mem::size_of::<EvidenceAttachment>(),
+ std::mem::size_of::<PathMutation>(),
+ std::mem::size_of::<ReviewRecord>(),
+ std::mem::size_of::<String>(),
+ ];
+ out.extend_from_slice(&(layout.len() as u32).to_le_bytes());
+ for s in layout {
+ out.extend_from_slice(&(s as u32).to_le_bytes());
+ }
+ let codes: Vec<String> = CODES.iter().map(|c| format!("{c:?}")).collect();
+ for table in [
+ FIELDS.to_vec(),
+ codes.iter().map(String::as_str).collect(),
+ KINDS.to_vec(),
+ ] {
+ out.extend_from_slice(&(table.len() as u32).to_le_bytes());
+ table.iter().for_each(|n| put_name(&mut out, n));
+ }
+ out.extend_from_slice(&(bases.len() as u32).to_le_bytes());
+ for b in &bases {
+ // A base with a logical form is accepted as is; a hand-made one is refused.
+ let refused = decide(b, &b.bytes).0 != 0;
+ assert_eq!(refused, b.lf.is_none(), "{}: unexpected outcome", b.label);
+ out.push(b.entry);
+ out.extend_from_slice(&b.cap.to_le_bytes());
+ out.extend_from_slice(&b.checkpoint_seq.to_le_bytes());
+ put_name(&mut out, &b.label);
+ out.extend_from_slice(&(b.bytes.len() as u32).to_le_bytes());
+ out.extend_from_slice(&b.bytes);
+ match &b.lf {
+ Some(lf) => {
+ out.extend_from_slice(&(lf.len() as u32).to_le_bytes());
+ lf.iter()
+ .for_each(|c| out.extend_from_slice(&c.to_le_bytes()));
+ }
+ None => out.extend_from_slice(&u32::MAX.to_le_bytes()),
+ }
+ }
+ let mut cases = Vec::new();
+ let mut n_cases: u32 = 0;
+ let mut tally: BTreeMap<String, (usize, usize)> = BTreeMap::new();
+ for (i, b) in bases.iter().enumerate() {
+ let entry = if b.entry == ENTRY_RECORD {
+ "record"
+ } else {
+ "checkpoint"
+ };
+ for (op, pos, declared, m) in cases_of(b) {
+ let o = decide(b, &m);
+ cases.extend_from_slice(&(i as u16).to_le_bytes());
+ cases.push(op);
+ cases.extend_from_slice(&pos.to_le_bytes());
+ if op == OP_FALSE_LENGTH {
+ cases.extend_from_slice(&declared.to_le_bytes());
+ }
+ cases.push(o.0);
+ if o.0 != 0 {
+ cases.extend_from_slice(&o.1.to_le_bytes());
+ cases.extend_from_slice(&o.2.to_le_bytes());
+ cases.extend_from_slice(&o.3.to_le_bytes());
+ cases.push(o.4);
+ }
+ n_cases += 1;
+ let class = ["hand_made", "truncated", "bit_flipped", "false_length"][op as usize];
+ let t = tally.entry(format!("{entry}_{class}")).or_default();
+ t.0 += 1;
+ t.1 += usize::from(o.0 != 0);
+ }
+ }
+ out.extend_from_slice(&n_cases.to_le_bytes());
+ out.extend_from_slice(&cases);
+ let seal: [u8; 32] = Sha256::digest(&out).into();
+ out.extend_from_slice(&seal);
+ (out, tally)
+}
+
+fn repo_root() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
+}
+
+#[test]
+fn j1_sealed_corpus_is_what_the_rust_codec_gives() {
+ let (bytes, tally) = build();
+ let digest = hex::encode(Sha256::digest(&bytes));
+ let path = repo_root().join(CORPUS_PATH);
+ if std::env::var_os("J1_CORPUS_WRITE").is_some() {
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(&path, &bytes).unwrap();
+ println!(
+ "wrote {} ({} bytes, sha256 {digest})",
+ path.display(),
+ bytes.len()
+ );
+ }
+ let mut total = 0;
+ for (class, (cases, refused)) in &tally {
+ total += cases;
+ println!(
+ " {class}: {cases} cases, {refused} refused, {} accepted (canonical)",
+ cases - refused
+ );
+ }
+ println!(
+ " total malformed cases: {total}; corpus {} bytes, sha256 {digest}",
+ bytes.len()
+ );
+ let sealed = fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
+ assert!(
+ sealed == bytes,
+ "the sealed corpus differs from what the codec gives today"
+ );
+ assert_eq!(
+ digest, CORPUS_SHA256,
+ "the corpus seal moved; update CORPUS_SHA256 with the file"
+ );
+}
+
+#[test]
+fn j1_corpus_covers_every_record_kind_on_main_and_every_refusal_kind() {
+ let bases = bases();
+ let kinds: BTreeSet<u8> = bases
+ .iter()
+ .filter(|b| b.entry == ENTRY_RECORD && b.lf.is_some())
+ .map(|b| b.bytes[1])
+ .collect();
+ assert_eq!(kinds, (1u8..=8).collect(), "record kinds 1 to 8");
+ let mutated: BTreeSet<u8> = bases
+ .iter()
+ .filter(|b| b.entry == ENTRY_RECORD && b.mutate)
+ .map(|b| b.bytes[1])
+ .collect();
+ assert_eq!(mutated, (1u8..=8).collect(), "every kind is mutated");
+ let mut seen = BTreeSet::new();
+ let mut fields = BTreeSet::new();
+ for b in &bases {
+ for (_, _, _, m) in cases_of(b) {
+ let o = decide(b, &m);
+ seen.insert(o.0);
+ fields.insert(o.4);
+ }
+ }
+ assert_eq!(
+ seen,
+ (0u8..=9).collect(),
+ "every refusal kind and an accept are present"
+ );
+ assert_eq!(fields, (0u8..=15).collect(), "every field id is reached");
+ // One encoding per logical form: equal forms have equal bytes, and the other way round.
+ let pairs: BTreeSet<(&Vec<u64>, &Vec<u8>)> = bases
+ .iter()
+ .filter_map(|b| b.lf.as_ref().map(|lf| (lf, &b.bytes)))
+ .collect();
+ let forms: BTreeSet<&Vec<u64>> = pairs.iter().map(|p| p.0).collect();
+ let encodings: BTreeSet<&Vec<u8>> = pairs.iter().map(|p| p.1).collect();
+ assert_eq!(forms.len(), pairs.len());
+ assert_eq!(encodings.len(), pairs.len());
+}
diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs
index 8aeb003 ..ea3db2b 100644
--- a/crates/synapse-store/src/lib.rs
+++ b/crates/synapse-store/src/lib.rs
@@ -37,6 +37,8 @@ mod blockdev_tests;
pub mod codec;
#[cfg(test)]
mod group_tests;
+#[cfg(test)]
+mod j1_corpus;
mod revision;
pub mod seal;
pub mod segment;
diff --git a/docs/J1_OMEGA_CODEC.md b/docs/J1_OMEGA_CODEC.md
new file mode 100644
index 0000000 ..1c43644
--- /dev/null
+++ b/docs/J1_OMEGA_CODEC.md
@@ -0,0 +1,123 @@
+# ADR 0003 step J1: Omega port of the binary codec (cross-check corpus)
+
+Issue #53. ADR 0003 section 9, row 33 (J1), needs A1. The Rust codec
+(`crates/synapse-store/src/codec.rs`, step A1) stays the specification by test (section 5.12).
+This step adds one language-neutral file that says what "decodes and re-encodes every record byte
+for byte, refuses the malformed corpus identically" means, so a port in any language is checked
+against the Rust outcomes and never against a second reading of the spec.
+
+* Exporter and seal: `crates/synapse-store/src/j1_corpus.rs` (test only).
+* Sealed corpus: `evidence/j1-codec-corpus/corpus.bin`, SHA-256 in `CORPUS_SHA256`.
+* The Omega port lives in `aien-dev/omega` (`src/synapse/syn_codec.osc`, driver
+ `tests/synapse/test_syn_codec.c`, `make test-synapse-codec`); it vendors the file byte for byte.
+
+## 1. What is covered
+
+Codec v2 record payloads (`CODEC_V2 | kind | body`) for every record kind on `main` (1 to 8,
+including the embedded `synapse-core` revision envelope v2 and obsolescence marker) and checkpoint
+content (`CheckpointState::encode_content` / `decode_content`, including the revision-log
+section). The frame layer around them (WAL frame header, CRC, SHA-256 chain, checkpoint frame and
+`state_root`) is out of scope: it is hashing, which belongs to J3 and J4.
+
+Kinds 9, 10 and 11 are reserved by open PRs (#88, #96, #95). A kind that merges adds its bases to
+`bases()`, its flattener arm to `Lf::record`, its expected set in the coverage test, and a reseal;
+the Omega side adds one `if k == N` arm in `record`.
+
+## 2. Cases
+
+* **Bases** (48). 28 accepted, each with its LF: the fixture JSON records, the A1 edge records,
+ kind 7 and 8 records, and two checkpoints (fixture, and one with a revision log). 20 hand-made
+ refusals that the mutation set cannot reach: reserved kinds 9 to 11, an empty revision section,
+ a revision section holding kind 6, projections out of order, equal keys in each of the five
+ checkpoint maps, equal revision seqs, and the repository id rules (empty, 129 bytes, leading or
+ trailing slash, `//`, `..`, space, non-ASCII).
+* **Mutations** of every accepted base marked for mutation, exactly the A1 malformed set
+ (`a1_malformed_corpus.rs`): every truncation, every bit flip, and a false `u32` length at every
+ offset with declared values `remaining + 1`, `cap + 1` and `u32::MAX`.
+* Each case carries the Rust outcome. An accept is asserted canonical (re-encodes to the input)
+ before it is written. Today: 55,670 cases, 41,750 accepts, 13,920 refusals.
+
+## 3. Logical form (LF)
+
+A record or checkpoint as a flat list of `u64` cells, the typed fields in encoding order, without
+derived lengths or constant bytes. Each field starts with a header cell `type | n << 8`:
+
+| type | id | n | cells after the header |
+| --- | --- | --- | --- |
+| u16 | 2 | 1 | value |
+| u64 | 4 | 1 | value (`usize` fields too) |
+| bool | 5 | 1 | 0 or 1 |
+| tag | 6 | 1 | tag byte (record kind, Option, mutation op, file mode) |
+| fixed bytes | 7 | len | one cell per byte |
+| string | 8 | len | one cell per UTF-8 byte |
+| byte string | 9 | len | one cell per byte |
+| repository id | 10 | len | one cell per byte |
+| count | 11 | 1 | element count of the sequence that follows |
+
+The field order per record kind is `Lf::record` and per checkpoint `Lf::checkpoint`. The
+checkpoint revision-log count is always present in the LF; the bytes hold that section only when
+the count is above zero.
+
+## 4. File format (version 1, little-endian)
+
+```
+magic "SYNJ1COD" | version u16 = 1 | reserved u16 = 0 | cap u32 (2048, A1 record cap)
+layout: n u32 | n x u32 size_of EvidenceAttachment, PathMutation, ReviewRecord, String
+fields: n u32 | n x name refusal field names, id = index + 1, 0 = none
+codes: n u32 | n x name embedded synapse-core refusal codes, id = index + 1
+kinds: n u32 | n x name CodecRefusal kinds, id = index + 1, 0 = accept
+bases: n u32 | n x base
+cases: n u32 | n x case
+seal: SHA-256 of every byte before it
+name = len u16 | UTF-8 bytes
+base = entry u8 (1 record, 2 checkpoint content) | cap u64 | checkpoint_seq u64 | label name
+ | len u32 | bytes | lf_cells u32 (u32::MAX = refused base, no LF) | lf_cells x u64
+case = base u16 | op u8 (0 as is, 1 truncate, 2 bit flip, 3 false length) | pos u32
+ | [declared u32 when op = 3] | kind u8 | [at u32 | x u32 | y u32 | field u8 when kind > 0]
+```
+
+The case input is rebuilt from its base and op: truncate keeps `bytes[..pos]`, bit flip XORs bit
+`pos % 8` of byte `pos / 8`, false length writes `declared` at `pos`, op 0 is the base as is.
+The `layout` sizes are part of the format because the Rust record decoder checks a sequence's
+reservation `n * size_of::<T>()` against the cap (`LengthOverCap`) before reading it.
+
+Outcome fields per refusal kind (`x`, `y` are 0 when unused):
+
+| kind | at | x | y | field |
+| --- | --- | --- | --- | --- |
+| Truncated | offset | need | | |
+| LengthOverCap | offset | declared | cap | |
+| TrailingBytes | offset | count | | |
+| UnknownTag | tag offset | tag | | field id |
+| InvalidUtf8 | offset | | | |
+| VersionUnsupported | 0 | found | | |
+| NotCanonical | offset | | | field id |
+| InvalidRepoId | offset | | | |
+| EmbeddedMalformed | length-prefix offset | code id | | field id |
+
+## 5. Reproduce
+
+```
+cargo test -p synapse-store --lib j1_corpus # checks the seal
+J1_CORPUS_WRITE=1 cargo test -p synapse-store --lib j1_corpus # rewrites the file
+```
+
+After a rewrite, update `CORPUS_SHA256` and re-vendor the file into the Omega repository.
+Red and green runs: `evidence/j1-codec-corpus/red-green/`.
+
+## 6. Speed against the section 6.2 bound
+
+Omega native AArch64, one core, on the 28 accepted bases (omega `evidence/SYNAPSE-J1/perf.txt`,
+`make bench-synapse-codec`): decode 0.0434 GB/s (23.0 ns per record byte, calc:1c31099c ), encode
+0.0269 GB/s. The bound for moving the bytes once is the 273 GB/s memory bandwidth
+(`docs/A0_HOST_BOUNDS.md`), so the fraction reached is 1.59e-4 for decode (calc:2ef7b34c ) and
+9.85e-5 for encode (calc:a0366c9f ). The unit reads one byte per bounds-checked index and writes one
+`u64` LF cell per payload byte. The Rust codec's speed on the same bases is not measured here.
+
+## 7. Limits
+
+* The Omega unit refuses inputs above 1,000,000 bytes with a limit refusal (its loop bound);
+ the corpus inputs are all below that.
+* Encode mirrors the Rust encoder: it does not apply decoder caps, so an LF the decoder would
+ refuse for size can still encode.
+* Hashing (frame CRC and SHA-256, checkpoint roots) is J3/J4 scope.
diff --git a/evidence/j1-codec-corpus/corpus.bin b/evidence/j1-codec-corpus/corpus.bin
new file mode 100644
index 0000000 ..52993d0
Binary files /dev/null and b/evidence/j1-codec-corpus/corpus.bin differ
diff --git a/evidence/j1-codec-corpus/red-green/green.txt b/evidence/j1-codec-corpus/red-green/green.txt
new file mode 100644
index 0000000 ..17e04f7
--- /dev/null
+++ b/evidence/j1-codec-corpus/red-green/green.txt
@@ -0,0 +1,20 @@
+# J1 green: the sealed corpus is what the Rust codec gives (3d78efe + this branch); 2026-10-17T05:40:40Z
+# workspace: cargo test --workspace: 329 passed, 0 failed, 1 ignored; cargo clippy --workspace --all-targets -D warnings clean; cargo fmt --check clean
+$ cargo test -p synapse-store --lib j1_corpus -- --nocapture
+
+running 2 tests
+. checkpoint_bit_flipped: 21952 cases, 3570 refused, 18382 accepted (canonical)
+ checkpoint_false_length: 8214 cases, 2390 refused, 5824 accepted (canonical)
+ checkpoint_hand_made: 9 cases, 9 refused, 0 accepted (canonical)
+ checkpoint_truncated: 2744 cases, 2743 refused, 1 accepted (canonical)
+ record_bit_flipped: 15208 cases, 1948 refused, 13260 accepted (canonical)
+ record_false_length: 5631 cases, 1348 refused, 4283 accepted (canonical)
+ record_hand_made: 11 cases, 11 refused, 0 accepted (canonical)
+ record_truncated: 1901 cases, 1901 refused, 0 accepted (canonical)
+ total malformed cases: 55670; corpus 775681 bytes, sha256 469a25239b6d683d137497b8cab1bebb186e11b180fb5061723af2fe8f6bb8b7
+.
+test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 53 filtered out; finished in 0.67s
+
+exit=0
+# corpus.bin sha256 469a25239b6d683d137497b8cab1bebb186e11b180fb5061723af2fe8f6bb8b7
+# Omega side (aien-dev/omega, branch feat/synapse-j1-codec): the Omega codec reproduces every base and every case outcome of this file; see its evidence/SYNAPSE-J1/.
diff --git a/evidence/j1-codec-corpus/red-green/red.txt b/evidence/j1-codec-corpus/red-green/red.txt
new file mode 100644
index 0000000 ..e3e2829
--- /dev/null
+++ b/evidence/j1-codec-corpus/red-green/red.txt
@@ -0,0 +1,32 @@
+# J1 red: the sealed-corpus test with the exporter in place but no sealed corpus (3d78efe + this branch's exporter; corpus.bin removed for this run, then restored and cmp-checked); 2026-10-17T05:32:20Z
+# Note: this run was taken while the Spark quiet flag was held by another job (SPEED-1B); it is a 0.68 s host test of already-built code, recorded as is.
+$ cargo test -p synapse-store --lib j1_corpus
+
+running 2 tests
+j1_corpus::j1_sealed_corpus_is_what_the_rust_codec_gives --- FAILED
+.
+failures:
+
+---- j1_corpus::j1_sealed_corpus_is_what_the_rust_codec_gives stdout ----
+ checkpoint_bit_flipped: 21952 cases, 3570 refused, 18382 accepted (canonical)
+ checkpoint_false_length: 8214 cases, 2390 refused, 5824 accepted (canonical)
+ checkpoint_hand_made: 9 cases, 9 refused, 0 accepted (canonical)
+ checkpoint_truncated: 2744 cases, 2743 refused, 1 accepted (canonical)
+ record_bit_flipped: 15208 cases, 1948 refused, 13260 accepted (canonical)
+ record_false_length: 5631 cases, 1348 refused, 4283 accepted (canonical)
+ record_hand_made: 11 cases, 11 refused, 0 accepted (canonical)
+ record_truncated: 1901 cases, 1901 refused, 0 accepted (canonical)
+ total malformed cases: 55670; corpus 775681 bytes, sha256 469a25239b6d683d137497b8cab1bebb186e11b180fb5061723af2fe8f6bb8b7
+
+thread 'j1_corpus::j1_sealed_corpus_is_what_the_rust_codec_gives' (2346559 ) panicked at crates/synapse-store/src/j1_corpus.rs:950:53:
+/home/drakestapleton/workspace/synapse-53/crates/synapse-store/../../evidence/j1-codec-corpus/corpus.bin: No such file or directory (os error 2)
+note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
+
+
+failures:
+ j1_corpus::j1_sealed_corpus_is_what_the_rust_codec_gives
+
+test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 53 filtered out; finished in 0.68s
+
+error: test failed, to rerun pass `-p synapse-store --lib`
+exit=101