Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 215 additions & 0 deletions src/review/adapters/authoring_clause.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
//! Minimized per-clause Authoring re-review facts from the genuine sealed plan closure.
//!
//! Each captured human clause becomes one reviewable subject bound to its exact
//! original raw identity. The sole authority-bearing input is the receiver-issued
//! `CurrentAuthoringPlanClosure`; hashes, selected keys and asserted policy quorum
//! create no native approval, currentness or publication capability.

use std::collections::BTreeMap;

use crate::hashing::sha256_hex;
use crate::review::authoring_capture::CurrentAuthoringPlanClosure;
use crate::review::decode::{ContractError, ContractLedger};
use crate::review::hash_v3;
use crate::workspace::preparation::WorkControl;

/// Complete captured human-clause count ceiling, not a partial prefix.
const MAX_CLAUSES: usize = 10_000;
/// Exact existing path-free review subject token ceiling in UTF-8 bytes.
const MAX_SUBJECT_ID: usize = 256;

/// One selected actual clause subject, constructible only by this captured adapter.
pub(crate) struct ClauseFact<'a> {
/// Exact native clause key, never inferred from a locator or path.
subject_id: &'a str,
/// Full domain-separated per-clause subject fingerprint; prose is hashed, not exported.
subject_sha256: String,
/// Exact complete original raw identity borrowed from the sealed member.
raw_sha256: &'a str,
/// Full original extent.
byte_length: u64,
}

impl ClauseFact<'_> {
/// Borrow the actual selected native clause key.
pub(crate) fn subject_id(&self) -> &str {
self.subject_id
}
/// Borrow the complete domain-separated per-clause subject binding.
pub(crate) fn subject_sha256(&self) -> &str {
&self.subject_sha256
}
/// Borrow the exact original raw digest this subject is bound to.
pub(crate) fn raw_sha256(&self) -> &str {
self.raw_sha256
}
/// Borrow the full original byte extent.
pub(crate) fn byte_length(&self) -> u64 {
self.byte_length
}
}

/// Per-clause facts borrowing one genuine complete current authoring-plan capture owner.
pub(crate) struct PreparedAuthoringClauseReview<'a> {
/// Sole authority-bearing input is the opaque receiver-issued captured closure.
closure: &'a CurrentAuthoringPlanClosure,
/// All selected facts, in exact selected native clause-key order.
facts: Vec<ClauseFact<'a>>,
/// Complete captured clause denominator before selection.
complete_clauses: usize,
}

impl<'a> PreparedAuthoringClauseReview<'a> {
/// Borrow the genuine complete native owner, never a detached proof.
pub(crate) fn closure(&self) -> &'a CurrentAuthoringPlanClosure {
self.closure
}
/// Borrow the complete captured clause denominator.
pub(crate) fn complete_clauses(&self) -> usize {
self.complete_clauses
}
/// Borrow the selected per-clause facts in exact native key order.
pub(crate) fn facts(&self) -> &[ClauseFact<'a>] {
&self.facts
}
/// Consume the selected clause facts' complete queue binding under the same ledger.
/// Each clause subject is bound to its own sealed ordinal source pin by exact original
/// raw identity; a missing or altered clause pin refuses, never re-binds. The genuine
/// closure owner is re-verified so no detached fact vector can issue this binding.
pub(crate) fn bind_queue(
&self,
queue: &crate::review::wire_v3::QueueDocumentV3,
ledger: &mut ContractLedger,
control: &mut dyn WorkControl,
) -> Result<(), ContractError> {
use crate::review::wire_v3::SourceKindV3;
ledger.checkpoint(control)?;
self.closure().verify_inputs(ledger, control)?;
let pins: Vec<_> =
queue.source_pins.iter().filter(|pin| pin.kind == SourceKindV3::HumanClause).collect();
ledger.visits(pins.len())?;
if pins.len() != self.complete_clauses() || pins.len() != self.facts().len() {
return Err(ContractError::Binding);
}
// Clause pins carry gap-free declaration ordinals from the native project's
// human_clauses order; bind each subject to its own exact original pin.
let mut declared: BTreeMap<&str, usize> = BTreeMap::new();
for (ordinal, clause) in
self.closure().facts().loaded.project.human_clauses.iter().enumerate()
{
declared.entry(clause.key.as_str()).or_insert(ordinal);
}
ledger.derived(
declared
.len()
.checked_mul(std::mem::size_of::<(&str, usize)>())
.ok_or(ContractError::Capacity)?,
)?;
for fact in self.facts() {
ledger.visits(1)?;
let ordinal = declared.get(fact.subject_id()).ok_or(ContractError::Binding)?;
let expected = format!("authoring:clause:{ordinal}");
ledger.derived(expected.len())?;
let pin = pins
.iter()
.find(|pin| pin.artifact_key == expected)
.ok_or(ContractError::Binding)?;
if pin.raw_sha256 != fact.raw_sha256() || pin.byte_length != fact.byte_length() {
return Err(ContractError::Binding);
}
// Charge inspection of both complete digest extents for this binding.
ledger.bytes(
pin.raw_sha256
.len()
.checked_add(fact.subject_sha256().len())
.ok_or(ContractError::Capacity)?,
)?;
}
Ok(())
}
}

/// Admit explicit selection and derive per-clause facts only from the sealed closure.
///
/// The sealed input has consumed the complete maintained native comparison and every
/// human-clause original. This adapter re-verifies each selected clause's exact original
/// digest against its sealed member before issuing the subject binding; a tampered
/// original is refused, never silently re-bound. No file is opened and no approval is
/// promoted here.
pub(crate) fn prepare<'a>(
closure: &'a CurrentAuthoringPlanClosure,
selected: &[&'a str],
ledger: &mut ContractLedger,
control: &mut dyn WorkControl,
) -> Result<PreparedAuthoringClauseReview<'a>, ContractError> {
ledger.bound(|ledger| {
ledger.checkpoint(control)?;
let result = prepare_inner(closure, selected, ledger, control);
ledger.checkpoint(control)?;
result
})
}

/// Preserve one outer post-phase fence after all ordinary binding outcomes.
fn prepare_inner<'a>(
closure: &'a CurrentAuthoringPlanClosure,
selected: &[&'a str],
ledger: &mut ContractLedger,
control: &mut dyn WorkControl,
) -> Result<PreparedAuthoringClauseReview<'a>, ContractError> {
if selected.is_empty() || selected.len() > MAX_CLAUSES {
return Err(ContractError::Invalid);
}
ledger.visits(selected.len())?;
ledger.bytes(selected.len().checked_mul(MAX_SUBJECT_ID).ok_or(ContractError::Capacity)?)?;
for key in selected {
crate::review::validate::token(key, MAX_SUBJECT_ID)?;
}
if selected.windows(2).any(|pair| pair[0] >= pair[1]) {
return Err(ContractError::Invalid);
}

// Recheck all actual physical inputs under the same original invocation work owner.
closure.verify_inputs(ledger, control)?;

let clauses = &closure.facts().loaded.clauses;
if clauses.len() > MAX_CLAUSES {
return Err(ContractError::Capacity);
}
let complete_clauses = clauses.len();

// Correlate every sealed clause member to its exact native key. Key-based matching
// is unambiguous even when two clauses share identical original bytes.
let mut sealed: BTreeMap<&str, &str> = BTreeMap::new();
for (key, raw_sha256) in closure.clause_members() {
ledger.visits(1)?;
ledger.derived(std::mem::size_of::<(&str, &str)>() + key.len() + raw_sha256.len())?;
if sealed.insert(key, raw_sha256).is_some() {
return Err(ContractError::Binding);
}
}

let mut facts = Vec::new();
ledger.derived(
selected
.len()
.checked_mul(std::mem::size_of::<ClauseFact<'a>>())
.ok_or(ContractError::Capacity)?,
)?;
for key in selected {
ledger.visits(1)?;
let clause = clauses.get(*key).ok_or(ContractError::Binding)?;
let raw_sha256 = sealed.get(key).copied().ok_or(ContractError::Binding)?;
// Re-derive the bound original digest from the actual parsed clause allocation;
// a tampered clause original refuses rather than issuing a stale binding.
if sha256_hex(&clause.bytes) != raw_sha256 {
return Err(ContractError::Binding);
}
let byte_length = u64::try_from(clause.bytes.len()).map_err(|_| ContractError::Capacity)?;
let subject_sha256 =
hash_v3::clause_subject(key, raw_sha256, byte_length, ledger, control)?;
facts.push(ClauseFact { subject_id: key, subject_sha256, raw_sha256, byte_length });
}

Ok(PreparedAuthoringClauseReview { closure, facts, complete_clauses })
}
86 changes: 86 additions & 0 deletions src/review/adapters/authoring_clause_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Genuine per-clause 061 adapter controls: each sealed human clause is one reviewable
// subject bound to its exact original; a tampered clause original is refused.
use super::*;
use crate::review::adapters::authoring_clause as adapter;
use crate::review::hash_v3;

/// Each captured clause binds its own exact original digest and a distinct per-clause subject.
#[test]
fn per_clause_subject_binds_each_sealed_original() {
let mut f = Fixture::new(false, false);
f.answer();
originals(&f);
let mut ledger = ContractLedger::default();
let mut caller = NoopControl;
let mut control = ReviewControl::accept(&mut caller);
let owner = init(&f, &mut ledger, &mut control).unwrap();

let prepared =
adapter::prepare(&owner, &["access-clause", "operations-clause"], &mut ledger, &mut control)
.unwrap();
assert_eq!(prepared.complete_clauses(), 2);
let facts = prepared.facts();
assert_eq!(facts.len(), 2);
assert_eq!(facts[0].subject_id(), "access-clause");
assert_eq!(facts[1].subject_id(), "operations-clause");
// Each subject is bound to its own sealed original raw identity, not the whole-plan digest.
assert_eq!(facts[0].raw_sha256(), sha256_hex(&f.clauses[0]));
assert_eq!(facts[1].raw_sha256(), sha256_hex(&f.clauses[1]));
assert_eq!(facts[0].byte_length(), f.clauses[0].len() as u64);
assert_ne!(facts[0].subject_sha256(), facts[1].subject_sha256());
// The per-clause subject profile reproduces the bound fingerprint independently.
assert_eq!(
facts[0].subject_sha256(),
hash_v3::clause_subject(
"access-clause",
facts[0].raw_sha256(),
facts[0].byte_length(),
&mut ledger,
&mut control
)
.unwrap()
);
// The genuine owner stays borrowed; no detached proof is issued.
assert_eq!(prepared.closure().source_pins().len(), owner.source_pins().len());
}

/// A tampered clause original refuses the whole preparation, never issuing a stale binding.
#[test]
fn tampered_clause_original_is_refused() {
let mut f = Fixture::new(false, false);
f.answer();
originals(&f);
let mut ledger = ContractLedger::default();
let mut caller = NoopControl;
let mut control = ReviewControl::accept(&mut caller);
let owner = init(&f, &mut ledger, &mut control).unwrap();
std::fs::write(f.root.join("clause.md"), b"tampered complete human clause original").unwrap();
binding(adapter::prepare(
&owner,
&["access-clause", "operations-clause"],
&mut ledger,
&mut control,
));
}

/// Selection must be a nonempty strictly-increasing list of captured clause keys.
#[test]
fn selection_order_and_membership_are_enforced() {
let f = Fixture::new(false, false);
originals(&f);
let mut ledger = ContractLedger::default();
let mut caller = NoopControl;
let mut control = ReviewControl::accept(&mut caller);
let owner = init(&f, &mut ledger, &mut control).unwrap();
// Empty selection and unsorted selection are structural refusals.
assert!(matches!(
adapter::prepare(&owner, &[], &mut ledger, &mut control),
Err(ContractError::Invalid)
));
assert!(matches!(
adapter::prepare(&owner, &["operations-clause", "access-clause"], &mut ledger, &mut control),
Err(ContractError::Invalid)
));
// Unknown clause key.
binding(adapter::prepare(&owner, &["missing-clause"], &mut ledger, &mut control));
}
3 changes: 3 additions & 0 deletions src/review/adapters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ pub(crate) mod mapping;

/// Re-review explicit applicability decisions only through their genuine report-source closure.
pub(crate) mod applicability;

/// Re-review individual authoring clauses only through their genuine sealed plan closure.
pub(crate) mod authoring_clause;
27 changes: 26 additions & 1 deletion src/review/authoring_binding.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! A-authored genuine Authoring Queue/3 binding over one complete native owner.
//! Every actual Queue/Response allocation stays borrowed; loaded labels confer no proof.
use super::adapters::authoring_clause;
use super::authoring_capture::CurrentAuthoringPlanClosure;
use super::authoring_response_binding::compared_pins;
use super::capture::authoring::RegisteredAuthoringOriginals;
Expand All @@ -23,6 +24,8 @@ pub(crate) struct PendingAuthoringBinding<'native> {
queue: DecodedV3<'native, QueueDocumentV3>,
/// Every actual Response holder in original order, including duplicate occurrences.
responses: Vec<DecodedV3<'native, ResponseDocumentV3>>,
/// Per-clause reviewable subjects bound to their exact sealed originals.
clauses: authoring_clause::PreparedAuthoringClauseReview<'native>,
}
impl<'native> PendingAuthoringBinding<'native> {
/// Borrow the genuine native owner without detaching physical lifetime.
Expand All @@ -41,6 +44,10 @@ impl<'native> PendingAuthoringBinding<'native> {
pub(crate) fn responses(&self) -> &[DecodedV3<'native, ResponseDocumentV3>] {
&self.responses
}
/// Borrow the per-clause reviewable subjects bound to their exact sealed originals.
pub(crate) fn clauses(&self) -> &authoring_clause::PreparedAuthoringClauseReview<'native> {
&self.clauses
}
/// Repeat exact original registrations and complete physical U with ordinary postfences.
pub(crate) fn verify_inputs(
&self,
Expand Down Expand Up @@ -157,6 +164,10 @@ pub(crate) fn prepare<'native>(
let raw = originals.queue_raw().ok_or(ContractError::Binding)?;
let queue = decode_v3::decode_queue(raw, ledger, control)?;
native_queue(closure, &queue, ledger, control)?;
// Re-verify every captured human clause as its own reviewable subject bound to its
// exact original; a tampered clause original refuses before any response is admitted.
let clauses = clause_subjects(closure, ledger)?;
let clause_review = authoring_clause::prepare(closure, &clauses, ledger, control)?;
let actual = originals.responses();
let mut responses = reserved(actual.len(), ledger)?;
for raw in actual {
Expand All @@ -168,6 +179,20 @@ pub(crate) fn prepare<'native>(
originals.verify_review_originals(ledger, control)?;
closure.verify_inputs(ledger, control)?;
ledger.derived(std::mem::size_of::<PendingAuthoringBinding<'_>>())?;
Ok(PendingAuthoringBinding { closure, originals, queue, responses })
Ok(PendingAuthoringBinding { closure, originals, queue, responses, clauses: clause_review })
})
}

/// Borrow every captured human-clause key in lexicographic `BTreeMap` key order for per-clause re-review.
fn clause_subjects<'native>(
closure: &'native CurrentAuthoringPlanClosure,
ledger: &mut ContractLedger,
) -> Result<Vec<&'native str>, ContractError> {
let keys = &closure.facts().loaded.clauses;
let mut selected = reserved(keys.len(), ledger)?;
for key in keys.keys() {
ledger.bytes(std::mem::size_of::<&str>())?;
selected.push(key.as_str());
}
Ok(selected)
}
12 changes: 12 additions & 0 deletions src/review/authoring_capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,18 @@ impl CurrentAuthoringPlanClosure {
pub(crate) fn locator_raw(&self) -> &[u8] {
self.locator_lease.bytes()
}
/// Borrow each sealed human-clause member's exact native key and complete original
/// raw digest, in maintained member order. The key is derived from the actual
/// `human-clause-<key>` role; this projection issues no currentness or approval proof.
pub(crate) fn clause_members(&self) -> impl Iterator<Item = (&str, &str)> {
self.members.iter().filter_map(|member| {
member
.native_role
.as_deref()?
.strip_prefix("human-clause-")
.map(|key| (key, member.raw_sha256.as_str()))
})
}
/// Borrow only internally issued complete operation registrations, preserving duplicates.
pub(crate) fn originals(&self) -> Result<RegisteredAuthoringOriginals<'_>, ContractError> {
self.held.authoring_originals()
Expand Down
5 changes: 5 additions & 0 deletions src/review/authoring_capture_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,8 @@ mod command_tests {
mod edit_merge_tests {
include!("edit_merge_tests.rs");
}

/// Genuine per-clause 061 adapter controls over the sealed plan closure.
mod clause_adapter_tests {
include!("adapters/authoring_clause_tests.rs");
}
Loading
Loading