Skip to content

Latest commit

 

History

History
949 lines (774 loc) · 52.1 KB

AGENTS.md

File metadata and controls

949 lines (774 loc) · 52.1 KB

AGENTS.md — memory-safety conversion guideline (standing standard)

The standing engineering standard for the openssl-rs unsafe→safe conversion campaign (integrate/safe-c33). Tracked in Git (not an admitted forensic artifact): it is a living working document, so re-read it at the point of use rather than assuming a session already has it.

Load this file at the start of every fresh session.

The goal is not "uses Rust". The goal is sound abstractions with genuinely safe interiors: every unsafe assumption either eliminated (made inexpressible) or confined to a narrow, auditable abstraction with a sound interface.

Compatibility is preserved, but compatibility is never an excuse to reproduce a known-unsafe operation: preserve OpenSSL behaviour where required, and record any deliberate safety improvement that deviates from it.

How to read this file

  • §0–§7 are the always-enforced conversion contract — apply them to every batch.
  • §8–§20 are specialized procedures, invoked when a change touches the relevant concern (a reusable unsafe abstraction, a security-sensitive algorithm, protocol handling, a promotion, research instrumentation). Do not treat every technique below as a requirement for every small edit — that recreates the verification bottleneck this campaign exists to escape.

0. The standard to hold (good ≠ exceptional)

pattern what it guarantees
good (foundation) *mut T → NonNull<T> → Drop consolidates cleanup; provenance/uniqueness still caller obligations
exceptional (target) validated ownership boundary → borrowed/owned Rust state → safe internal algorithms unsafe assumptions live only at auditable boundaries; types, lifetimes and borrow rules enforce the interior

We are moving from the first to the second. Every conversion must state which unsafe assumptions were eliminated (became inexpressible), which were merely relocated (into one documented boundary), and which remain hidden (unreported obligations). Hidden must be zero; if you find a hidden obligation, report it and block graduation — never reclassify it to satisfy the target.

On "the C ABI edge". Unsafe code cannot always be confined to the C ABI edge alone. Allocators, operating-system interfaces, CPU intrinsics, and specialized internal representations each require their own unsafe operations. The real requirement is that every such operation live inside an appropriately narrow, auditable abstraction with a sound interface — not that unsafe appears in exactly one place.


1. Ownership adoption is a proof obligation, not a function call

An ownership-adoption constructor turns a caller-supplied raw pointer into an owning handle whose Drop frees it. Such a constructor MUST be unsafe fn with a # Safety contract.

The contract must establish, at minimum:

  • provenance (which allocator seam produced it);
  • allocation identity and extent (the whole block, not a sub-range);
  • alignment;
  • initialization state valid for every operation the owner performs (including the cleansing length, which must be valid for that allocation);
  • exclusive ownership (no other owner will release it);
  • the exact release mechanism (plain vs cleansed vs secure).

An unsafe fn declaration transfers a proof obligation to its caller; it does not discharge it. Marking a constructor unsafe without making its callers establish the preconditions is not a fix.

  • A safe fn whose body can trigger an invalid free is a soundness bug even if today's call sites are correct.
  • Prefer design over documentation where cheap: when a block comes from a known allocator call in the same function, construct the owner directly from that call (new/new_zeroed) so provenance is not re-asserted by hand. Reserve adopt/take for genuine helper-allocated blocks and justify each.
  • Never add a new unsafe fn with a safe-looking signature that hides raw work.

Audited constructors (fix any regression): OwnedBlock::take, OwnedBuf::take, OwnedStr::take, OwnedRaw::adopt, adopt/adopt_cleansed, from_raw, across runtime/bio/owned.rs, store/store_lib.rs, evp/{pkey_ctx,digest,e_aes}.rs, pem/pvkfmt.rs, ui/ui_lib.rs, hpke/mod.rs, ssl/{ssl_lib.rs,statem/statem_srvr.rs}, x509/v3_utl.rs, ec/smpl.rs, provider/{cipher,kdf}.rs.

2. Valid Rust values are an explicit invariant

Allocated storage and initialized Rust values are separate states. CRYPTO_zalloc returning zeroed bytes does not, by itself, establish that those bytes represent a valid initialized T; validity must be established for the actual type and for every subsequent operation. (Zero initialization may be a valid value for some types — that must be justified per type, not assumed.)

  • An owner may hold NonNull<MaybeUninit<T>> while constructing an object.
  • No &T, &mut T, initialized read, or full destructor is permitted before the required initialization invariants hold. Zeroing does not make a value valid when T contains references, NonNull, valid-range-restricted enums, or other fields with validity requirements.
  • Partially initialized objects must release only the resources actually acquired — never run a complete destructor on a partially constructed value (this is the OwnedRaw<T> vs OwnedCtx<T> distinction; keep it).

Borrowing

  • Prefer owner-derived borrowing: &mut OwnedTree, &mut OwnedNode, split_at_mut/get_mut partitioning — instead of raw from_raw_parts_mut.
  • from_raw_parts_mut requires exclusive access to the whole range for the entire returned borrow; derive that from an owner rather than asserting it.
  • Audit: unsafe fn tree_levels<'a>(tree) -> &'a mut [...] (caller-chosen lifetime; no tie to the tree's owner) and Node::parent_mut(&self) (uniqueness the type system does not establish).

3. Fallible arithmetic and allocation

  • Any count * size_of::<T>(), length/size sum, or offset used for allocation MUST use checked_mul/checked_add and translate overflow to the OpenSSL failure semantics (None/error), not rely on a panic boundary. Audit: the generic alloc helper in src/asn1/owned.rs.
  • Make allocation failure, overflow and partial initialisation explicit through Option/Result (or the module's established outcome type).

4. Panic safety across the C ABI

  • guard_ffi catches unwinding, but uses AssertUnwindSafe; catching a panic does not repair partially mutated state.
  • For stateful contexts require one of: failure-atomic mutation, explicit rollback, or a poisoned state that forbids reuse after an interrupted operation. An error code alone is not sufficient.

5. Secret-bearing memory is a distinct category

Classify memory by security requirement, not only by allocation mechanism and destructor — and distinguish secret contents, public metadata, and sensitive state. (IVs/nonces are often public, yet their uniqueness and lifecycle can be security-critical.)

  1. Lifetime + cleansing. Cleansing must cover the actual secret-bearing storage, including copies, temporary representations, partially initialized states and failure paths. Release and cleansing are separate obligations: a destructor that merely frees memory is not a secret-safe destructor. Keep every OPENSSL_clear_free arm through conversion.
  2. Constant-time. Separate secret-dependent operations from public-data parsing; keep the full-length CRYPTO_memcmp accumulation; never introduce secret-dependent branches or early exits. Source-level intent is not constant-time behaviour after optimization: for secret-dependent operations, preserve the intended timing discipline under optimisation and review generated code or use leakage-testing methods where the change warrants it. Never claim constant-time behaviour from source inspection alone.
  3. Initialised vs uninitialised. MaybeUninit<T> + initialisation state.
  4. Reference/alias ownership. Express shared/exclusive access through types; minimise unconstrained pointer→reference conversions.

No third-party crypto implementations: RustCrypto zeroize/subtle and similar are references for technique only.

6. Per-batch execution contract

  • One bounded task at a time; a subagent does not commit or push; the orchestrator commits, verifies and merges.
  • Everything runs in the court container (docker/openssl-rs-court.sh), never on
    • OOM protection is mandatory: run one heavy command at a time; build with CARGO_BUILD_JOBS=4 and test with cargo test --lib -- --test-threads=4 (the editor and other host work already consume most of RAM and swap is full — a build spike has crashed the session before); check free -g before a build and abort if available is small. Never build into a RAM-backed tmpfs. §6.1 makes this unconditional, and it binds every agent, every command.
  • Local gate per batch: cargo fmt --all -- --check, cargo clippy --all-targets -- -D warnings, all current library tests pass. The observed floor is 1962 library tests (0 failed, 42 ignored; commit a8676158f); it will grow, so the rule is no unexplained removals and no newly ignored tests — not a frozen literal.
  • Preserve the CRYPTO_* allocator seam at the authority's exact size/file/ line; preserve #[repr(C)] layouts and every exported symbol/signature; never weaken unsafe_op_in_unsafe_fn / undocumented_unsafe_blocks / missing_safety_doc.
  • docker/ is out of scope for conversion agents. This is a scope boundary, not an endorsement of the current launcher: the known isolation defect (host checkout bind-mounted read-write at /work) is a standing infrastructure task that must be tracked and fixed deliberately, never silently forgotten.
  • Opaque types may change layout, with a check. A type whose layout is not part of the public contract — opaque in the installed headers, with no exported symbol exposing its size, alignment, member offsets or arity — may change its #[repr(C)] layout, provided the change carries a check proving that opacity. The check is mechanical: no exported symbol takes or returns it by value, no exported macro or inline function sizes it, and no documented ABI statement names its layout. Record the check with the change. This does not license layout changes to types reached through exported signatures, and it does not license a size change in a type a consumer allocates.
  • Report per batch: mechanism eliminated / relocated / hidden (must be 0), unsafe ops removed vs relocated, boundary size, obligations discharged / retained / newly introduced, compatibility tested, and whether every remaining unsafe op has an explicit validity contract.
  • Defer full Phase-25 forensic regeneration to seal points; keep the local gate.

§6.1 OOM protection is unconditional (2026-11-11)

No command may run without a memory cap. There is no exception, no "small" build, and no agent that is exempt. A crash of the editor or the session is not an acceptable cost of any experiment, so protection is applied before the command starts, not after it gets large.

Rules, all mandatory:

  1. Every heavy command runs inside docker/openssl-rs-court.sh, which caps the cgroup. Nothing compiles, links, tests or benchmarks on the host — not one crate, not one rustc invocation, not one script that does either.

  2. The cap and the floor are computed from live availability and a measured peak, never assumed. Before the command: read available from free -g, then set OPENSSL_RS_COURT_MEM and OPENSSL_RS_COURT_MEMSWAP explicitly to min(8g, available - 16g) with a floor of 2g; if that floor is not met, the command does not run. The build floor is available >= cap + headroom, where headroom is 12 GiB for a build profile whose peak has been measured in this repository, and 24 GiB for any profile that has not. Measured peaks on record: a debug test build peaked at 4.0 GiB at a 4 GiB cap — the former absolute 24 GiB floor was six times its requirement and blocked four priorities across several blocks. A release build with debug = 2 peaked at 3.56 GiB at a 4 GiB cap (cgroup memory.peak 3,822,895,104 B; 3.49 GiB sampled; no OOM), measured 2026-11-29 and recorded in evidence/frc4/CANONICAL-BUILD.md; a later rebuild of the same profile from 6834d9e8 peaked at 2.69 GiB at a 4 GiB cap (cgroup memory.peak 2,889,674,752 B; 2.59 GiB sampled; no OOM), recorded in evidence/frc4/CANDIDATE-1d3aac93.md; it therefore takes the 12 GiB measured-profile headroom, not the 24 GiB floor. The debug test profile is the larger user: at the court's 4 GiB RLIMIT_DATA it peaks at ~4.0 GiB, and at 8 GiB RLIMIT_DATA it reaches 4.88 GiB cgroup (memory.peak 5,244,403,712 B; 4.79 GiB sampled; no OOM), recorded in the same receipt. A court started without these variables set is a violation, even if it happens to fit.

    Miscalibration is corrected by measuring, never by proceeding under a floor that is known to be wrong: record the profile's peak, amend this clause with it, and cite the run that established it.

    First measurement of an unmeasured profile. The 24 GiB figure would otherwise make the measurement that replaces it impossible, which is a circular refusal. A profile may therefore be measured by an authorised bounded experiment: a hard cgroup cap of at most the §24.4 cap, host reserve of at least 8 GiB above that cap, one command at a time, and the experiment declared in the brief as the measurement that will amend this clause. The bounded experiment proves only that the workload fits the tested configuration; it does not establish an unconstrained requirement. Escalate the cap only after an observed bounded failure, never pre-emptively, and record every attempt's cap, outcome and peak. When the measured peak is recorded, the profile moves to the 12 GiB row and the 24 GiB figure no longer applies to it. A profile that has never been attempted in this repository stays at 24 GiB.

    Report four distinct quantities, never one: observed peak RSS (what the process used), cgroup memory.peak (aggregate court consumption), the cgroup cap (the enforced ceiling), and host reserve (what was left for everything else). RLIMIT_DATA is a fifth, independent failure mechanism: a workload can abort against it while the cgroup is nowhere near full, and that distinction must be recorded rather than reported as an OOM.

  3. One heavy command at a time. Check docker ps and /proc/pressure/io first. Another session's benchmark is not ours to interrupt and not ours to compete with: wait, or lower the cap and say so in the receipt.

  4. Bound the parallelism: CARGO_BUILD_JOBS<=4, --test-threads<=4, and prefer an exact test name over a whole module when the module is large.

  5. A run that OOMs is evidence, not noise. Record it, stop, lower the cap, and state the change. Do not retry the same command at the same size.

  6. If a cap cannot be established, the command does not run. "I could not measure" is a refusal, never a licence to run unprotected.

This section binds the orchestrator as well as subagents: the ledger, receipt and git commands are exempt because they do not compile; everything else is not.

Execution discipline (mandatory — 2026-10-17)

This is a context-preservation rule, not a preference.

  • The orchestrator must not run project commands directly. Outside a subagent, the only permitted commands are the staging-branch git add/git commit, git push, and a release/publish step. Everything else — reading large files, grep, find, builds, tests, fmt, clippy, benchmarks, forensics generation, Docker/VM management, and any diagnostic that can emit large output — MUST run inside a subagent.
  • Run exactly one subagent at a time. Do not launch concurrent subagents. One subagent owns the court container/VM and its OOM budget; concurrency defeats the context and memory discipline this rule exists to protect.
  • All testing uses the minimal court container/VM, never the host. Subagents must use docker/openssl-rs-court.sh with CARGO_BUILD_JOBS=4 and cargo test --lib -- --test-threads=4, and must check free -g before a build. The orchestrator must never run cargo, rustc, tests, or project scripts on the host. The docker/ directory remains out of scope for conversion agents; if the pinned image is not minimal, record that as a standing infrastructure task rather than silently running on the host.
  • The orchestrator may make small documentation edits directly, but must then commit and push them through the staging branch; it must still use a subagent for any verification that requires running code.
  • Status reporting is mandatory. After every merged subphase, report: current source HEAD and docs tip, the subphase files/mechanisms, gate results (tests and probes), atlas/probe figures, remaining blockers, and the next queued subphase. Do not claim a gate passed unless a subagent ran it and reported the actual output.
  • Subagents do not commit or push. They return a short report; the orchestrator commits the verified change on a stage/p25/sweepN branch, merges it into integrate/safe-c33, pushes, and updates the ledger.

Transport-only orchestrator (mandatory — 2026-11-13)

Outside a subagent, the orchestrator may run nothing but publishing transport: git commit, git push (GitHub) and a crates.io/release publish step. The commit is part of the push path and is permitted only for that purpose.

Everything else is forbidden in the orchestrator, including git status, git log, git diff, grep, ls, cat, find, python3, docker, cargo, rustc, tests, and any script — read-only or not, large output or small. Anything that observes, measures, builds, tests or changes project state MUST run inside exactly one subagent at a time; the subagent returns a short report, and the orchestrator commits and pushes what it reports.

This supersedes every earlier permission for the orchestrator to run project commands directly, to read large files itself, or to run "small" commands: there is no size exemption. Context is the scarce resource this rule protects, so reconnaissance belongs in the subagent that will act on it.

Verification scheduling: FAST / BATCH / BOUNDARY / SEAL (additive, 2026-10-18)

This subsection governs how often evidence is generated. It changes scheduling, not the standard: §7 discharge criteria, §§8–20 evidence axes, and the playbook gates are unchanged. Where the per-batch local gate or the per-subphase reporting rule above conflicts with this subsection, this subsection governs.

Level Trigger Required evidence
FAST every source edit cargo fmt --all -- --check; incremental compile/check of the touched target; focused, name-filtered tests for the changed units; structural guards (allocator seam, #[repr(C)], exported symbols, unsafe lint attributes, and a SAFETY: contract for every new unsafe op).
BATCH each coherent audit/repair group, before an integration checkpoint full cargo test --lib both serially and with --test-threads=4; cargo clippy --all-targets -- -D warnings; the affected adversarial probes; the affected compatibility courts; compact receipt committed.
BOUNDARY before a shared mechanism is independently discharged, or when a critical trust boundary changes independent caller/dependency-closure audit; targeted ASan/Miri/Loom/mutation controls; authority differential for changed semantics; negative-control canary; reviewer must not be the author.
SEAL consumer graduation, major milestone, release candidate full applicable dependency closure; complete probe suite; full forensic regeneration; held-out and broad compatibility/cryptographic assurance against the exact candidate.

Rules:

  1. FAST is development feedback, not a safety certificate. Nothing becomes SAFETY_DISCHARGED or SAFE_COMPATIBLE because it passed FAST or BATCH. A batch may be merged into integrate/safe-c33 with BATCH evidence while its remaining BOUNDARY/SEAL obligations are explicitly PENDING or NOT_RUN.
  2. Deferred is never PASS. Every check not run at the current level is recorded as NOT_RUN together with the gate that will run it. Only observed output counts as evidence.
  3. STOP conditions are level-independent. A confirmed memory-safety defect, an unexplained ABI regression, a weakened detector, a new hidden obligation, or a safe-Rust interface that can cause UB stops the batch immediately and invokes the narrowest BOUNDARY check capable of establishing the failure — regardless of the schedule.
  4. Reuse established evidence; invalidate conservatively. A discharged mechanism's evidence is bound to its exact source identity and declared contract scope. An unrelated edit preserves it. An edit to the shared owner, its contract, or a precondition it relies on invalidates that mechanism and its dependent closure. If non-impact cannot be proven, treat the evidence as invalid: a dependency graph's failure to prove non-impact is not evidence of non-impact.
  5. Batch by mechanism/dependency cluster, not by raw file count. Aim for roughly 10–25 ordinary files per integration checkpoint, adjusting downward or splitting to one file when a genuinely new unsafe boundary, callback/reentrancy edge, or ownership transition appears. Per-file accounting is retained for completeness, but repeated instances of an established contract do not require a new model or a new full gate.
  6. Per-file work is contract checking. For an ordinary file: classify applicable mechanisms → check caller preconditions and unusual transitions → repair genuine defects → run FAST → emit the compact receipt → queue the next file. Reserve deep analysis for novel boundaries and for any counterexample.
  7. Reporting cadence. Emit a compact receipt after every subphase (source identity, files/mechanisms, contracts reused, new unsafe assumptions, defects, tests run, obligations discharged/retained/new, and deferred gates marked NOT_RUN). Update the human-readable campaign summary only at batch checkpoints, not after every file.
  8. Execution economics. Run one heavy command at a time; reuse the court's compiled artifacts; build a probe/test binary once and re-execute it per isolated case rather than invoking the cargo driver once per case; skip Rust rebuilds for documentation-only changes. Before deleting or deferring any existing gate, measure its cold and warm wall time and confirm that its unique defect-detection role is preserved elsewhere.
  9. Impact analysis is itself evidence. The dependency graph used for evidence reuse must be regenerated or validated at each BATCH checkpoint from the exact candidate. Any unresolved dependency is treated as affected.
  10. CI mirrors these levels. Use branch-aware FAST (debug/incremental, affected tests), BATCH (full suite, clippy, affected probes) and SEAL (release build, full courts) profiles. Do not run a release build or the complete probe suite on every integration push. CI and container changes remain infrastructure work requiring their own measured justification; they are not conversion-agent scope.

7. Graduation states

  • OWNERSHIP_RECONSTRUCTED — a safe ownership model exists and its residual boundary is identified.
  • SAFETY_DISCHARGED — materially harder. A mechanism is SAFETY_DISCHARGED only when, within its defined scope:
    1. every remaining unsafe operation has an explicit validity contract;
    2. every required precondition is established by its callers or by an external ABI contract; and
    3. no safe-Rust caller can cause undefined behaviour through the safe interfaces. All retained, introduced and unresolved obligations must be enumerated. Documentation alone does not discharge an obligation.
  • SAFE_COMPATIBLE — the only graduation state for a consumer family. A family graduates only when every applicable mechanism in its conservatively established dependency closure is SAFETY_DISCHARGED, unresolved dependencies are accounted for, and compatibility is confirmed against the exact converted implementation. L4 build/link and L7 functional evidence remain separate (an L4 pass is not an L7 pass). An unresolved or unknown safety-relevant dependency blocks SAFE_COMPATIBLE graduation until its applicability is excluded with evidence or its safety obligations are discharged: recording an unknown is necessary, but recording it does not establish safety. No family inherits safety graduation solely from a shared mechanism's successful conversion: a consumer like curl depends on many mechanisms, and discharging one does not make the whole consumer safe.

An unproven raw-pointer boundary never becomes SAFETY_DISCHARGED merely because a Drop wrapper exists, and hidden = 0 is a target, never a reporting incentive.


8. Three axes of evidence (compatibility ≠ safety ≠ cryptography)

Compatibility is necessary for our objective but not sufficient: a faithful port can reproduce a security defect. Every subsystem must be able to answer, separately:

  • Compatibility — does it preserve OpenSSL's intended public behaviour? (differential courts, downstream replay.)
  • Safety — can its ownership, aliasing, initialisation, concurrency and FFI contracts prevent UB? (contracts, Miri, sanitizers, negative controls.)
  • Cryptography — are results, protocol decisions, secret handling and timing protections correct? (Wycheproof/ACVP vectors, dudect, proofs.)

Never let one axis's evidence stand in for another. A green differential court is not a safety result; a clean grep for unsafe is not a cryptographic result.

9. Safe abstractions (the RustBelt standard)

A safe interface must not let safe clients cause UB. For every reusable unsafe abstraction (owner types, adoption ctors, CtxDestroy, freefunc tables):

  • give it a contract: what a caller must establish, and what an implementer must guarantee;
  • prefer deriving ownership from the known allocation result and restrict raw adoption to genuine transfer boundaries;
  • review the traits — CtxDestroy-style destructor traits impose an obligation on implementers. A wrong destroy_body (releasing the enclosing allocation, or freeing a member twice) invalidates every generic owner. State the destructor contract (frees its owned members exactly once, handles the declared initialisation state, never the enclosing block) and, where feasible, make the trait unsafe.

10. Aliasing and architecture layering

Aliasing correctness is a conversion property, not an afterthought. Prefer, by layer:

Layer Preferred representation
C ABI façade raw pointers with defined C contracts
allocation / ownership NonNull, typed owners, explicit transfer
interior structures borrowing, checked slices, discriminated states
algorithms and parsers safe Rust wherever feasible
CPU-specific cryptography small, documented intrinsic/assembly boundary

The target is not fewer unsafe expressions but fewer ways to construct conflicting references. At focused checkpoints run Miri under both Stacked Borrows and Tree Borrows where supported; do not require full-library Miri. Miri is a research instrument, not the normative aliasing spec — record what it did and did not cover.

11. Cryptographic assurance instruments (distinct, not interchangeable)

Property Instrument Scope
algorithm correctness Wycheproof / NIST ACVP/CAVP vectors malformed + edge inputs
unsafe-code soundness Miri + contract review ownership, aliasing, init
bounded functional props Kani bounds, invariants, arithmetic
mathematical equivalence hax/Lean (or F*) for small pure interiors proofs, not tests
secret-dependent flow ctgrind branching/memory access
statistical timing dudect optimised crypto ops
protocol robustness Rustls/BoringSSL/NSS-style fuzzing handshake/record parsing

Absence of detected leakage is not proof of constant-time behaviour, and ACVP vectors are not a NIST validation certificate. State coverage and limits.

12. Secret classification

Tag security-sensitive operations with an explicit classification (engineering metadata first, safe wrappers over time):

PUBLIC_DATA, SECRET_DATA, SECRET_DEPENDENT_CONTROL, CLEANSING_REQUIRED, DECLASSIFICATION_BOUNDARY.

A constant-time comparison should yield an internal choice-like value until the authorised decision point; secret-dependent branching is forbidden before it. Any constant-time claim must name the target arch, compiler version, feature dispatch and build profile that were measured.

13. Two fuzzing courts (never merge their verdicts)

  • Deep-state exploration — test-only deterministic crypto / controlled verification bypasses to reach otherwise unreachable protocol states. Claim: protocol-state robustness under the modified model.
  • Authentic execution — real crypto, real provider behaviour, full handshakes. Claim: observed behaviour of the real implementation.

Bypasses must never appear in the release configuration.

14. Proof-carrying conversion receipt

Each landed conversion batch writes a compact receipt (template: forensics/memory-safety/campaign/safe-c33/RECEIPT.template.md) with: source identity, authority contract, ownership before/after, unsafe eliminated / retained / introduced, compatibility delta, safety checks, residuals. The point is to let a fresh session resume without reconstructing the reasoning.

15. Agent roles and independence

Run sequentially in the same container; separation is about independent judgment: contract analyst (authority requirements, no code), conversion engineer (smallest coherent safe change), adversarial reviewer (can a safe interface be misused? do aliases escape? can destruction double-release? does failure leave inconsistent state?), evidence adjudicator (reads actual outputs; cannot certify from another agent's description).

The agent that writes a safety claim must not be the sole authority deciding whether its evidence proves that claim.

16. Negative controls

If a court claims to detect an unsafe-ownership violation, introduce an isolated test-only canary of that defect class (aliasing, wrong release path, overflow, secret-dependent flow) and confirm the instrument fires. Keep canaries out of production artefacts and classify unsupported detectors honestly.

17. Divergence classification (vs OpenSSL and the standard)

Divergence Treatment
documented OpenSSL behaviour conserve it
implementation-defined state the compatibility scope; test it
UB in the C authority do not reproduce UB; document the boundary
known vulnerability mechanism eliminate the mechanism; test the correction
standards nonconformance establish normative behaviour; record the compat consequence
harness/environmental difference keep separate from implementation findings

Never imitate a flawed implementation and call it correctness.

18. Verification schedule

Frequency Evidence
every coherent conversion fmt, clippy, compile, focused tests, contract review
every integrated subsystem library tests, relevant differential/lifetime tests, targeted Miri
security-sensitive algorithm change applicable Wycheproof/ACVP vectors, constant-time checks
protocol handling change targeted adversarial fuzzing + authentic workload
reusable unsafe abstraction change misuse analysis, negative controls, cross-caller audit
Safe-33 promotion whole-cohort dependency closure, downstream replay, broader sanitizers, refreshed forensics
release candidate full security + compatibility campaign, reproducibility, independent review

19. Measuring progress (five dimensions, not one %)

  1. Ownership reconstruction — mechanisms converted (not files touched).
  2. Safe-interior coverage — functions/mechanisms whose safe interfaces enforce their invariants.
  3. Discharged safety obligations — verified contracts, with retained and unknown obligations reported alongside.
  4. Cryptographic assurance — vectors, timing evidence, checked properties.
  5. Safe-compatible consumers — families past their dependency closure + compat.

Plus a trust-boundary budget per subsystem: number/complexity of unsafe interfaces, scope of caller obligations, and the amount of code relying on them. A correctly scoped SIMD intrinsic and a safe fn that can build two exclusive references to the same memory are not the same risk.

20. Conversion-aware residual fuzzing (FRF-Fuzz), kept outside the crate

FRF-Fuzz is a standalone external instrument: never an implementation dependency of the single crate, never anything src/ links against. It lives in the court/venue, with pinned authority + exact converted candidate binaries. The distinctive idea is to try to discover where an unsafe→safe conversion changed observable behaviour (allocator, lifetime, protocol state, error paths), not just where a crash exists.

Three initial targets, each with a pinned OpenSSL authority executable, the exact converted-candidate executable, a normalised transcript contract and deterministic replay:

  1. allocator / ownership — differential cleanup, partial initialisation, failed allocation, refcount transitions;
  2. ASN.1 / X.509 — parsing boundaries, object lifetime, policy evaluation, error and rejection differences;
  3. TLS state machines — unexpected transitions, fragmented inputs, renegotiation / post-handshake where applicable.

The experiment that matters runs across a conversion: capture a subsystem's behavioural residuals → apply the ownership reconstruction → replay the same corpus against the new candidate and the authority → FRF-Fuzz's exploration / DSFB machinery prioritises new structural differences and proposes discriminating inputs → promote only replay-confirmed findings to FRF, which independently adjudicates each promotion, carrying its exact source identities and disposition → let Gemel preserve the history of discovered/fixed/reopened/unresolved divergences. Keep hypothesis generation (FRF-Fuzz) separate from verification (FRF); that separation is the framework's principal strength.

Executable adapters. FRF-Fuzz's authority interface expects an executable that speaks its fixture protocol. The pinned OpenSSL executable and the exact converted candidate therefore each need a compatible case-harness adapter that normalises the same observables (allocator events, return values, error codes, transcript bytes), preserves allocator and error semantics, and records the exact candidate build identity (commit + binary hash). Without those adapters §20 would describe the intended experiment but not how the existing FRF-Fuzz implementation executes it.

  • Keep the fast compare-guided exploration and the ASan-confirmation builds separate until the documented ASan/trace-compare instrumentation incompatibility is resolved. Never trade memory-safety detection for guidance.
  • Bypasses/fuzz modes are test-only and must never appear in the release configuration (see §13).

Earning the claim (rigorous, honest evaluation)

The four-arm ablation is coverage → coverage+compare → residual → full. To claim the original mechanisms add value, compare FRF-Fuzz against AFL++, libFuzzer and an appropriate LibAFL configuration under equal CPU, time, corpus and instrumentation, and measure: verified unique defects, time-to-first-confirmed-divergence, reproducible boundary witnesses, and performance on previously-unseen defects. Include at least one external benchmark corpus not designed around FRF's strengths. Report censoring, held-out defects, negative controls, reproducibility and statistics.

The claim FRF must earn: the residual/full arms outperform coverage+compare on held-out conversion defects, and findings survive independent replay. Until then, do not claim frontier-level superiority. A preserved negative result is a valid result.


21. Safe-33 assurance protocol (read at relevant gates)

The existing §§0–20 remain authoritative. Specialized procedures and research-grounded operational checklists live in forensics/memory-safety/campaign/safe-c33/ASSURANCE_PLAYBOOK.md §§21–32. This split keeps first-read agent context bounded. Load only the playbook sections required by the touched trust boundary; do not run its full suite on every mechanical conversion.

Mandatory new decisions for every changed unsafe boundary

  1. State the exact external contract. A C-valid hostile input or legitimate application callback must not cause UB. A C-invalid pointer is not silently assumed safe. State OpenSSL authority, ABI, target, object lifecycle and candidate binary identity.
  2. Prove the whole boundary, not the unsafe expression. Assign a stable boundary ID. Include every constructor, raw alias/escape, mutation, callback, duplicate/up-ref, partial-init failure, release and safe caller. A private field, unsafe trait, owner-token or SAFETY: comment is NOT discharge.
  3. Treat FFI callbacks and hooks as reentrancy edges. No unjustified &mut or non-reentrant lock across an application-controlled callback, even when owned member fields are private. Audit allocator hooks, BIO callbacks, provider/ENGINE dispatch, ex_data and TLS callback families. A failure must leave a valid reusable, rolled-back, or explicitly poisoned state.
  4. Establish validity before references. Prove provenance, alignment, extent, initialization, lifetime alias exclusivity, (ptr,len) consistency and Send/Sync claims. debug_assert! cannot uphold a safety invariant in release. Preserve pointer provenance through transformations where needed.
  5. Keep three independent evidence axes. ABI/functional parity (including loader and callback behavior), Rust soundness, and cryptographic/security properties require different proofs and courts. Use negative controls.

Highest-value Safe-33 prioritization

Retain the historical 33-family cohort. Rank actionable obligations by importance of the consumer × demonstrated reachability × security consequence ÷ engineering effort, never raw file/token/unsafe-block counts. First deepen current-candidate functional courts for curl, nginx, OpenSSH, HAProxy and Redis; recover the missing per-family symbol fingerprints. Preserve any remaining L4-only families as build/link results until each earns meaningful L7 evidence (as of 2026-10-20 the 33-family cohort is 33/33 at L7-functional in runtime-functional-atlas.json). Additional candidates (Git/CPython/Apache HTTP Server) must first earn their own precise compatibility evidence and are not retroactively counted in 33.

New evidence promotion rule

Every obligation has a candidate-bound lifecycle: UNKNOWN -> CONTRACTED -> ESTABLISHED -> INDEPENDENTLY_CHECKED -> DISCHARGED. Record an explicit source witness for each precondition, an independent reviewer, relevant runtime/static checks and negative controls, exact source/build hashes, and retained/unknown obligations. Unknown/unsupported instruments are NOT PASS. A method is not SAFETY_DISCHARGED because a document names it; the existing §7 full dependency-closure rule for SAFE_COMPATIBLE is unchanged.

Verification economics and stop conditions

Continue the existing cheap per-batch court, one heavy command at a time. Add focused alias/callback/adversarial tests whenever a reusable safety boundary changes. Run native sanitizers and model tools where supported, protocol and cryptographic courts on corresponding changes, and the full forensic seal only at the designed subsystem/promotion gates. Never turn absent evidence into a green result. A counterexample, newly hidden assumption, ABI regression, weakened detector or newly unsafe safe-API is STOP even if 1,196+ unit tests pass.

Before untrusted external pilots, fix the court container's documented writable host bind mount and prepare the maintainer-specific source/binary identity, replay/rollback and security-response evidence bundle. The precise court and bundle contracts are in the playbook §§24–32.


22. Candidate freeze and evidence identity (additive, 2026-10-27)

Five consecutive SAFE_COMPATIBLE adjudications were rejected, and the cause was never analysis. It was identity. A subphase edited source after the measurement it then argued about, so the analysed DSO was not the rebuilt one, the executed consumer binary was not the analysed one, and receipts drifted off the operations they described. The fixes survived every rejection; the claim did not. This section makes that failure mode unavailable.

Two identities, never conflated

  • S — the frozen source candidate. The commit containing every build-relevant input: src/, Cargo.toml, Cargo.lock, build.rs, the build scripts, the verification tools, the recipes and the test definitions.
  • E — the evidence commit. A commit containing only receipts, atlases and ledger updates about S.

Adding evidence does not change the candidate. Moving HEAD by committing E must never appear to invalidate S or its binaries. Every receipt in E names the same S, the same artefact hashes and the same downstream executable hashes.

Invalidation rule. Any change to a build-relevant input, or to a tool that derives evidence, invalidates the freeze and requires a new candidate S'. A change confined to receipts, atlases, status documents or ledger entries does not. If it is not obvious which side of that line a change falls on, treat it as build-relevant.

The freeze procedure

  1. Complete every source and tool correction first. Do not freeze a candidate whose known defects are still being repaired.
  2. Commit S and record its commit hash plus the hash of every build-relevant tree.
  3. Rebuild once from S and record the artefact hashes.
  4. In the same freeze, generate everything that depends on those artefacts: the safety inventory, the closure, the receipts, and the downstream measurements — binding the digest of the executable that actually ran into the runtime row, not only the library hashes.
  5. Commit the evidence as E, naming S and the artefact hashes throughout.
  6. Adjudicate read-only against the freeze. No repairs, no regenerated source, no silent substitution during adjudication.

Per-call-site witnesses

A classification is not evidence. When a resolver assigns an indirect call to an external ABI contract, it must carry a per-call-site witness connecting that specific function-pointer slot to that specific contract — where the slot is written, by which reachable code, and which documented interface fills it. Two indirect calls are not the same edge because they are both indirect.

A generic contract class that can absorb an unrelated internal callback is a defect in the verifier, not a convenience. When one is discovered, the fix is to require the witness, not to widen the class.

Evidence finality

The bottleneck is verification finality, not verification volume. One candidate, one coherent evidence set, one independent decision. A rejected claim whose refusal names a property is progress; a claim re-attempted without changing the procedure is not.


23. Earned-trust constitution (additive, 2026-11-23)

docs/EARNED-TRUST.md is the standing constitution of this project's commitments about claims. It is normative and cumulative with this standard: it adds no permission and withdraws none, and where an article and a clause here describe the same commitment, the stricter reading governs. A session re-reads the constitution at the point of use, exactly as it must re-read this file.

article commitment
1 a claim may never exceed its evidence
2 evidence is bound to an exact identity
3 deferred is never pass
4 an omission is not a pass
5 independence is never asserted without a distinct trust domain
6 a specification is never a restatement of the implementation
7 a proof in a model is not a proof about the binary
8 a constant-time result is not a proof of constant time
9 severity is not a probability
10 a correction preserves what was believed
11 no authority may promote a contradicted claim by declaration

The machine record is evidence/etp-t14/ARTICLES.json. The release mapping is docs/RELEASE_GATES.md §10, which names the four articles no gate item covers. The consistency checker is forensics/tools/earned_trust.py, invoked from forensics/tools/docs_consistency.py (release-gate item 6); it refuses an article citation that names no article, an article with no enforcement and no declaration of that, and a gate mention of an article no gate item covers.


24. Memory-incident stop-work rule (additive, 2026-11-24)

A memory incident has occurred in this campaign: a full test discovery ran while host available was near the floor, and the session was killed. This section is normative and cumulative with §6 and §6.1. Where they differ, this section governs.

24.1 What counts as an incident

  • an OOM kill of any process (cgroup memory.events oom or oom_kill increased, or a kernel OOM line);
  • host available below 4 GiB at any point during a heavy command;
  • a session or editor crash attributed to memory;
  • a command whose observed peak plus the court cap exceeds the available figure measured immediately before it.

24.2 Stop-work

On an incident: no build, no full test discovery, no benchmark, no new court and no concurrent heavy command. The only permitted actions are to record the incident, reduce the unit of work, and re-measure. Re-running the same command at the same or a larger size is forbidden.

24.3 Bounded work units (no whole-discovery runs)

  • python3 -m unittest discover -s forensics/tools/tests may run only when available >= 24 GiB measured immediately before it.
  • Otherwise run one named module at a time (python3 -m unittest forensics.tools.tests.<module>), with a bounded timeout, and record which modules ran and which did not.
  • A partial run is PARTIAL, never PASS. The receipt names the modules executed and the number of tests actually run.
  • Never run two heavy commands concurrently, in one agent or across agents.

24.4 Cap derivation, tightened

cap = min(4g, available - 8g), floor 2g. If available - 8g < 2g, no new court and no heavy command. Reusing a running court is permitted only when the command's declared peak is below half of available. The §6.1 formula remains the upper bound; this one is operative while incidents are recent.

24.5 Every brief states its cap

A brief that can compile, link, test or benchmark must name the measured available, the computed cap, and the bounded unit it will run. A brief that does not is defective; the subagent must stop and report rather than proceed.

24.6 Incident receipt

Each incident produces evidence/incidents/<date>-<n>/RECEIPT.md: the command, available before it, the cap, the observed peak, the OOM evidence, what was lost, the reduced unit that replaced it, and the module list subsequently run.

24.7 Claim discipline

A suite result obtained during an incident is NOT_RUN. A green bounded subset is never reported as "the suite passes", and no item is DONE on the strength of a run that was interrupted.

This section adds no permission and withdraws none. The stricter reading of §6, §6.1 and this section governs every agent, every command.


25. Context-incident stop-work rule (additive, 2026-11-30)

Context has the same failure mode as memory and has now caused the same class of loss: an unbounded unit of work exhausted the thread, and subagent dispatch began failing before it started. §6.1 exists so that a build cannot kill the session; until now nothing existed for the record itself. This section is normative and cumulative with §6, §6.1 and §24. Where they differ, the stricter reading governs.

25.1 What counts as a context incident

Measurable, not subjective. An incident is any of:

  • a spawn_agent call that fails with a context-length error, for any brief size, on a new or resumed session;
  • a single tool result above 200 KB of text or 50,000 estimated tokens; such a result must have been written to the repository and cited instead of returned in full — a second read is a symptom, not a threshold;
  • a thread whose accumulated history is above 75% of the model's stated limit, estimated from the sizes of the briefs and results in it. The estimate must be labelled an estimate; it is a guard, not a measurement;
  • cumulative tool output in one thread above 2 MB of text.

25.1.1 Rotation thresholds (initial policy, estimates)

Calibrated against nothing yet; treat as estimates until measured, and label them so.

band utilisation permitted work
normal 0–60% bounded implementation and verification
conservation 60–75% restrict tool output, prepare the handoff
closure 75–85% finish the current bounded task only, no new dispatch
rotate 85%+ persist state, write the checkpoint, start a fresh thread

The principle is rotation before failure, not recovery after it: the handoff written at 7a1cef99 was written at failure, which is one band too late.

25.2 Stop-work

On an incident: no further dispatch from that thread, no retry at the same size, and no attempt to summarise the history as a workaround. The only permitted actions are to record the incident, write the resumable handoff, and continue in a fresh thread. A retry that cannot succeed is not evidence of persistence.

25.3 Bounded work units

  • One subagent task per dispatch, with a brief that names paths, not contents. A brief that pastes a file is a defect in the brief.
  • The orchestrator does not read large files, does not grep the tree, and does not run commands at all beyond git, gh api and cargo publish — §6's transport-only rule is also the context rule.
  • Subagents return a short report, not file dumps. Evidence lives in the repository; the report cites it.
  • Prefer one closed claim with a compact reproduction path over an expanding evidence tree: a reviewer should not need a thousand files to check one result.

25.4 Every batch states its context budget

A brief states what it expects to read and roughly how much it expects to produce, in the same spirit as §24.5's requirement to name the memory cap. A batch that would read more than a handful of large files is split, not attempted.

25.5 Handoff is mandatory, not optional

When a thread approaches its limit, the handoff is written before the last dispatch, not after it fails. Two artifacts, both in the repository:

  • docs/HANDOFF-*.md — prose: what is closed and must not be reopened, what is open with its specific blocker, the verbatim next brief, and the process rules that have already cost time;
  • docs/CHECKPOINT.json — machine-readable state, so a fresh agent resumes without interpreting prose. Required fields: source_commit, candidate_digest, active_obligation, completed_claims, blocked_claims, evidence_applicability (formerly invalidated_evidence; evidence bound to an earlier candidate is historically valid for that candidate, not invalid), and next_task with inputs, acceptance_criteria, context_budget and memory_cap.

The repository is the durable state of the engineering process; agent context is disposable. A checkpoint that cannot be parsed is a defective handoff.

25.6 Claim discipline

A batch that was dispatched from a thread that had already hit the limit is NOT_RUN. A summary written from memory after the failure is not a result, and a retry against a known-failing limit is a violation, not diligence.

This section adds no permission and withdraws none.