<!-- description: Learn how HoldFast tracks computation and type use separately with natural grades, and how broader grading domains are modeled and qualified. -->

# Graded dependent foundation

> Rules for [first-release graded typing](../../language/first-release/#default-graded-checking)
> and extensions to its domains and resource interpretation.

## Scope and research boundary

General domains extend the fixed modes and phases of the
[synchronous core](../../language/core-design/#judgments-and-interpretations).
The [resource interface](#resource-and-computation-interface) serves
[handlers](../handlers-async/) and [cells](../interior-mutability/), including
their [combined cases](../full-language-review/).

The selected CIC and resource interpretation must prove substitution, structural
rules, preservation and erasure over the elaborated image. The frontend checks
correspondence to exact source. [Frontend admission](../full-language-review/#frontend-admission)

Pure source replay checks computation and type demand for graded boxes,
indexed sums and dependent records. Rocq proves structural rules, simultaneous
substitution, symbolic normalization and call-by-value erasure for its modeled
fragments. The frontend also trials domain and inductive declarations, grade
polymorphism, proof-producing inference, derived combinators and bounded synthesis.
[GrTT, GraD and Agda comparison](../../assurance/verification-strategy/#reading-the-graded-type-claims) ·
[Mechanized core limits](#mechanized-core-review) ·
[Source replay](../../tooling/elaboration-prototype/#pure-graded-source-replay) ·
[Source and target qualification](../../plan/#q25be)
[GrTT metatheory](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_metatheory.v) ·
[Unified graded core](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core.v) ·
[Unified core metatheory](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_metatheory.v) ·
[Unified core type substitution](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_type_subst.v) ·
[Unified core CBV erasure](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_erasure.v) ·
[Symbolic semiring polymorphism](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_semiring.v) ·
[CBV erasure and skipping](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_erasure.v) ·
[Grade inference](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_inference.py) ·
[Derived combinators](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_combinators.py) ·
[Grade-directed synthesis](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_synthesis.py)

## Extension selection and qualification

[First-release default graded checking](../../language/first-release/#default-graded-checking) selects natural computation grades and separate type-use accounting. Qualify that selection and any broader grading extension against fixed use modes using a concrete client's independently frozen behavior/resource/representation contract, evidence endpoint, toolchain, positives, and semantic refusals.

| Candidate | Comparison and admission evidence |
| --- | --- |
| Fixed use modes and checked library contracts | Baseline: state-indexed operations and natural exact/bounded trace judgments under existing ownership/phase rules, keeping actual proof/maintenance obligations. |
| `NatExact`/`NatBound` with separate type use | Qualify boxes, dependent data, and arithmetic with checked domain laws, usage-aware CBV interpretation, and exact-source correspondence; link demand to trace properties, compare dependency rows against the simplest sound account, and show dependency/parametricity/authoring benefit. |
| General domains | Show an analysis natural domains cannot express cleanly and prove its interpretation and composition laws. |

Freeze budgets and thresholds for annotations, proof, review, repair,
diagnostics, time and memory. Match behavior, preconditions and endpoints.
Measure reconstruction, constraint search and kernel replay on fresh and changed
inputs, separating setup and maintenance from recurring work. Report open
goals, exhausted budgets, unsupported inputs and semantic refusals separately.
Each extension needs the required laws and measured benefit.

To qualify [GrTT's distinction](../../assurance/verification-strategy/#reading-the-graded-type-claims), replay an index unused computationally that contributes to later declarations and result types, testing both an allowance-violating computation edit and a computation-preserving type-dependency edit across callable and locked module boundaries, naming affected bindings and retained telescope rows.

For qualified graded builds, optional substitution skipping requires
zero-type-use irrelevance, agreement with ordinary substitution and a net
speedup including constraint solving. The pure `NatExact` trial proves type
and demand preservation in modeled cases and checks a multi-binder fixture.
[Research comparison](../../assurance/verification-strategy/#reading-the-graded-type-claims) ·
[Irrelevance theorem](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_type_irrelevance.v) ·
[CBV erasure and skipping](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_erasure.v) ·
[Metatheory audit](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_metatheory.py) ·
[Frontend skip benchmark](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded.py#_q25cb_zero_type_use_skip_and_benchmark)

### Audio routing candidate

`StereoRoute` specializes a pure router (`(period + 1) + (period + 1)` stereo length, plus channel-label count). The ungraded baseline checks a pointwise Rocq result equation; graded replay checks the dependent signature and demands:

| Binder | Computation | Type | Type dependencies |
| --- | --- | --- | --- |
| `period` | 0 | 4 | Twice in the stereo input and twice in the result |
| `labelCount` | 0 | 1 | Once in the channel-label input |
| `stereo` | 1 | 0 | n/a |
| `channelLabels` | 0 | 0 | n/a |

Both checkers reject specializing to the old period; graded checking also rejects a zero computation allowance on returned samples. Since the baseline already checks dependent shape and behavior, selection trials need a client obligation that benefits from exact counts at one shared evidence endpoint. [Source fixture](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-audio-route.hf) · [Paired replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_client.py)

### Branch-specific fallback supply

A sum places `Box<Nat, 1>` in the empty alternative and the available value in
the present alternative. Opening the box checks one use of the fallback. The
present alternative has only the available value. The trial proves that this
selector agrees with an ordinary conditional for all inputs. It exercises
branch-dependent use with a library interface and existing grade syntax.
[Dependent multiplicities](https://arxiv.org/abs/2507.08759v4) ·
[Fallback source](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/fixtures/graded-fallback.hf) ·
[Comparison](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_fallback.py)

The batch comparison traverses two independent sums. Each sum selects a
one-sample or two-sample record, with a callback supplied in a box of grade
one or two respectively. Both dispatches use the same visitor. The graded
and fixed-mode paths use the same Rocq result equation.
[Batch comparison](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_batch_traversal.py)

### Conditional usability producers

`derive-combinator` derives distributive combinators for supported structures.
`synthesize-graded` prunes bounded search by resource requirements and checks
candidates against a behavioral oracle. Both emit terms for ordinary checking
and Rocq replay. [Granule combinators](https://arxiv.org/abs/2112.14966) ·
[Grade-directed synthesis](https://doi.org/10.1007/978-3-031-57262-3_4)

Name a client that needs recurring conversions or bounded synthesis. Freeze
derivation constructors, direction and premises, or synthesis grammar, components,
behavior and budget. Test capture, ownership, phase and effect preservation
with a changed binding, missing `Dup` or domain law, well-typed wrong candidate,
and exhausted search. Compare recurring effort and total checking cost with
existing combinators or proof search. [Generation contract](../metaprogramming/#qualification) ·
[Extension plan](../../plan/#language-extensions)

## Dimensions and lawful domains

Each judgment fixes the definitions, universes, grade identities, primitive
contracts, logic, representation and observation model in `S`. It names the
elaborated term checked in the [minimal CIC profile](../../assurance/verification-strategy/#research-and-semantic-boundaries).
Universe levels retain `Type i : Type (i+1)`. Transports need checked terms and
assumption audits. `SProp` and sort polymorphism are research options outside the
current profile.

| Dimension | Meaning | Evidence it cannot replace |
| --- | --- | --- |
| Computation use `u` | Demand on stable values in the selected graded value semantics | Invocation counts, physical copies, exclusive permission or WCET |
| Type use `v` and dependency rows `M` | Demand in the result type and in every declaration's type | Runtime availability of an erased index |
| Phase and representation `p, rho` | Runtime, specification or proof; represented or erased at the selected ABI | Protocol disposal or secret zeroization |
| Resource context `Delta` | Live ownership, loans, restoration and other kinded authority under the selected logic | A generic numeric, effect or security annotation |
| Effects `E` | Allowed operation footprints, including transitive calls and captures | Permission to perform those operations |
| Trace contract `T` | Named source events, their order and exact counts or upper bounds | Surviving machine calls or instruction timing |
| Target bound `W` | The existing final-CFG cost judgment against pinned Sail timing | A source use or event count without its transport theorem |

In the extensible proposal, domains are sealed CIC records (never runtime plugins or client-swappable dictionaries behind signatures; first release excludes arbitrary domains and general domain inference):

```text
q ::= 0_D | 1_D | named_constant_D | alpha_D | q +_D q | q *_D q
    | certified_domain_operation_D(q, ...)

Domain D:
  carrier Q : Type i; equivalence =D; preorder <=D
  additive commutative monoid (+,0); multiplicative commutative monoid (*,1)
  left/right distributivity; multiplicative zero annihilation
  congruence and monotonicity of both operations
  admissible weakening/contraction/scaling relations with proved meanings
  InterpretUse, InterpretTypeUse, CheckCertificate and soundness obligations
```

`q <=D q'` admits demand `q` under allowance `q'`. `NatExact` and `NatBound`
use natural addition and multiplication, with equality and `<=` respectively.
Boolean presence uses `or` and `and`, so `1 + 1 = 1`. The Rocq domain trial checks
these records alongside `JoinDomain`, symbolic grade normalization, row
certificates and substitution across exact-to-bound and bound-to-presence maps.
[Rocq domain trial](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_domains.v)

Promotion and motive scaling here use commutative multiplication. A
noncommutative domain needs ordered actions. Custom operations need composition
laws, incomparable branches need a proved bound or result-indexed contract, and
product domains need compatible demand and trace interpretations. Erasure needs
an observation theorem, exact cardinality needs faithful counts, uniqueness
needs spatial exclusivity, and security needs relational laws.
[Qualification obligations](#proof-and-qualification-obligations)

## Stable telescope and dependency bookkeeping

`J(M; u; v; Gamma |- t:A)` (implicit `S`) elaborates `t`, `A`, and demand interpretation to checked terms and image theorems. `Gamma` is an ordered telescope of stable values/types, immutable snapshots, and logical identities (runtime handles are descriptors; permissions live in `Delta`; stability grants no copy rights and indices never evaluate unsynchronized mutable reads). `M[i]` records prior declarations' use in `Gamma[i]`'s type; `u` and `v` have one entry per declaration for `t` and `A` (`v` is not a sum of `M` rows; zero-padded to the same telescope):

```text
CTX-EXT: J(M; a; 0; Gamma |- A : Type i)
         implies WF(M appended with a; Gamma, x:A).

VAR:     WF(M; Gamma), Gamma[i] = x:A
         implies J(M; unit_vector(i); padded(M[i]); Gamma |- x:A).

UNIV:    WF(M; Gamma)
         implies J(M; 0; 0; Gamma |- Type i : Type (i+1)).
```

Runtime variables require represented bindings in `rho` (spec variables cannot become runtime operands; tracked resources never enter `Gamma` via embedded record propositions—only their identities may index predicates).

### Functions and application

For `Pi x:(s,r) A. B` (body use `s`, codomain use `r`, domain demand `a`, codomain demand `(b,r)` under `Gamma,x:A`):

```text
PI:  J(M; a; 0; Gamma |- A : Type i)
     J(M,a; (b,r); 0; Gamma,x:A |- B : Type j)
     ---------------------------------------------------------
     J(M; a+b; 0; Gamma |- Pi x:(s,r) A.B : Type max(i,j))

LAM: J(M,a; (w,s); (b,r); Gamma,x:A |- t:B), with PI premises
     ---------------------------------------------------------
     J(M; w; a+b; Gamma |- lambda x.t : Pi x:(s,r) A.B)

APP: J(M; w; a+b; Gamma |- f : Pi x:(s,r) A.B)
     J(M; z; a; Gamma |- v:A), with PI premises
     ---------------------------------------------------------
     J(M; w+s*z; b+r*z; Gamma |- f v : B[v/x])
```

Application type use is `b+r*z` from substituting `v` for `x` in `B` (reconstructed under conversion rules; [substitution/resource obligations](#proof-and-qualification-obligations) cover closure envs and call modes). HoldFast evaluates arguments once from left to right. An effectful argument
elaborates as `bind x <- c; call f x` and retains its trace, effects and exit
even if the function discards `x`. Multiple uses reuse the evaluated value.
Moving an evaluation across handlers, mutation or checkpoints requires proof.

The Rocq call-by-value trial relates exact and bounded natural grades to reads
of evaluated arguments and preserves the event prefix on failure. A scoped span
trial proves descriptor preservation and framing of untouched bytes. For nested
slices, the inner bounds apply to the immediate parent and writes use owner
coordinates. The model restores the inner loan before the outer loan. The
exact and bounded box trials check both restoration events on success and on
failure after the write. Dependent box elimination specializes vector
identities at the retained extent.
[Execution model](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_cbv.v) ·
[Scoped argument model](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_cbv_span.v) ·
[Dependent box interpretation](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_modal_cbv.v)

The research models motivate preserving argument effects and promoting only
evaluated pure values in `Box_q`. HoldFast needs its own dependent, mutable and
handler laws for those rules. [CBPV effects and coeffects](https://doi.org/10.1145/3689750) ·
[Value-only promotion](https://antonlorenzen.de/papers/oxidizing-ocaml-modal-memory-management.pdf) ·
[Proof obligations](#proof-and-qualification-obligations)

### Substitution and structural rules

For `Gamma, x:A, Xi |- t:B` and `Gamma |- v:A` (`v` having subject demand `z`), each demand row `d=(d_G,d_x,d_X)` after `x` updates as:

```text
substDemand(d,x,z) = (d_G + d_x*z, d_X)
Gamma, x:A, Xi   becomes   Gamma, Xi[v/x]
u               becomes   substDemand(u,x,z)
v_type          becomes   substDemand(v_type,x,z)
each later M row becomes   substDemand(that row,x,z)
```

Earlier rows stay unchanged and `x`'s row drops; capture-avoiding substitution also updates types, motives, index-dependent grades, captures, and exit predicates across the whole telescope (`GF-substitution` requires simultaneous typing/WF and image-agreement proofs, never unchecked solver rewrites or computed indices).

A stable closure trial replays capture demand over a graph of direct bindings.
One reverse declaration-order pass multiplies along captures and adds demand
from all paths. The trial compares those totals with checked computation demand
before and after a locked provider edit. Direct type-use rows retain their
telescope interpretation. [Grade graphs](https://arxiv.org/html/2507.13792v5#S7) ·
[Capture replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_demand_graph.py)

| Structural operation | Admissibility condition |
| --- | --- |
| Extend an unused declaration | Construct type row, zero-pad subsequent rows and demand vectors; preserve prior dependencies. |
| Remove a declaration | Zero demand in term, result type, and all retained declaration rows, or substitute a checked stable witness (`u[x]=0` alone is insufficient). |
| Exchange declarations | Dependency-preserving permutation renaming rows/identities/captures (forbidden across an actual dependency). |
| Contract pure descriptors | Add demands and reindex telescope with checked equality (operations still need live spatial permission). |
| Weaken an advertised bound | Supply domain order proof (exact-use allows equality only; no implicit coercion to approximate domains). |
| Drop, duplicate or scale a resource | Supply `Dispose`, `Dup`, or repeated-use protocol (no generic telescope rule transforms `Delta`). |

### Dependent data and elimination

`Sigma x:^r A. B` uses `PI`'s `a,b,r` premises; pair introduction takes component demands `z,w` with second-component type demand `b+r*z`, yielding `(z+w, a+b)`. Tensor dependent elimination requires an explicit motive `C(p)` (opaque pairs cannot split field demands arbitrarily):

```text
p : Sigma x:^r A.B                  subject demand z
C(p) : Type k under Gamma,p         demand (c,kappa)
body : C((x,y)) under Gamma,x:A,y:B  subject (w,s,s)
                                    type (c,kappa,kappa)
----------------------------------------------------------------
match p as (x,y) in body : C(p)      subject w+s*z
                                    type c+kappa*z
```

Requires the full WF telescope (including `y`'s `r`-dependency on `x`) and checked motive substitution; asymmetric field allowances need graded modalities or a proved eliminator; erased weak pairs give no runtime witness/tag/projection (runtime matching requires a represented scrutinee, barred under security-lattice zero). [Dependent pair replay](../../tooling/elaboration-prototype/#graded-dependent-pair-replay) tests length-indexed vectors sharing computation allowance with exact motive rows.

`Box_q A` scales subject vector by `q` at introduction (fixing type vector) and eliminates with body demand `q` (type demand `q*kappa` for motive box-use `kappa`), adding `z` to body subject and `kappa*z` to body type demand without hiding effects or forging `Dup` (representations/erasure explicit in `rho`; [graded box replay](../../tooling/elaboration-prototype/#graded-box-source-replay)). Finite sums check branches under one advertised demand (substituting constructor dependencies; unequal branch counts stay result-indexed or bounded, never summed); bounded iteration uses inductive invariant, grade recurrence, and termination measure; general inductive eliminators need checked constructor/motive resource rules.

The shared-length vector trial compares an index-specialized proxy for the
second vector with an ordinary dependent motive in Rocq. The common
observation model checks ordered evaluation and applies a separately
checked callback on nonempty inputs.
[Proxy-based small inversions](https://www.floc-conference.org/publications/paper/xHSb5) ·
[Trial and measurements](../../assurance/completion-log/#q25fc-complete-checked-graded-frontend-correspondence)

For the strict natural fold trial, the base runs once and the step receives
the evaluated prior result. For stable captures and a depth `n`, the model
checks `base demand + n * step demand`. It checks predecessor and accumulator
reads in separate step rows. The source argument's effects and failure are
sequenced before the fold. The published call-by-name recursion result supplies
the separation of step binders. HoldFast's Rocq proof accounts for reads under
its call-by-value evaluation. For the supported structural fold, the source
projection distinguishes a local binding of the recursive result from a
second recursive call. The counted fold and the erased core evaluator agree
on the result at every depth. In `ReuseAccumulator`, each step reads the
predecessor once and the bound accumulator twice. The seed is read once in
the base and once per step.
[ICFP recursion paper](https://icfp26.sigplan.org/details/icfp-2026-icfp-papers/5/On-Recursion-in-Graded-Modal-Type-Theory) ·
[CBV fold proof](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_cbv_fold.v) ·
[Core evaluator agreement](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_cbv_fold.v) ·
[Authored fold replay](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_fold_source.py)

## Resource and computation interface

```text
S; M; Gamma; Delta_in |- c : Exit(A,Q)
  [use u; type-use v; captures C; effects E; trace T;
   phase p; representation rho; exit duties O]

Q(tag,value) = Delta_out for that represented exit
```

Generated theorems relate entry, elaborated execution and each exit in the
selected interpretation. `Delta` carries owners, loans, restoration duties,
protocols and effect or security rights. `Own(id,shape,snapshot)` describes an
ownership predicate in that interpretation. `Q` retains captures and branch
discriminants until a join or restoration discharges them. `Suspend`, concurrent
`Share` and multi-shot `Dup` require separately qualified extensions.

| Interface obligation | Required evidence |
| --- | --- |
| `Capture(C,Delta)` | Complete transitive retained env (handlers, tasks, stored continuations, cell fields) with kinded resources, lifetimes, effects, and representation (evaluation-only uses tracked separately). |
| `Dup(C,Delta)` | Semantic split supporting both uses under interference, lifetime, and protocol laws (immutable snapshots qualify by representation; exclusive owners/loans/single-use tokens have no default instance). |
| `Dispose(Delta,exit)` | Explicit resource-returning/terminal transition (affine permission drop does not discharge protocols, must-erase data, or mandatory examined verdicts). |
| `Suspend(C,Delta,rho,O)` | Stable represented storage, live loan ancestry, closed invariants, bounded checkpoint restoration/cleanup, and no escaping refs into moved frames. |
| `Transfer(domain,Delta)` | Cross-domain permission/representation transport preserving exclusivity, lifetime, publication order, and manifest join. |
| `Share(protocol,Delta)` | Concurrent ops preserve invariant under interference and pinned memory model (shared handles grant only declared ops). |

`Dispose` accounts for explicit cleanup and writes, including zeroing covered
registers or spills when required. Verdict elimination follows
[R-05-097 through R-05-100](https://github.com/symbiogenesis/VerifiedOS/blob/main/docs/spec.md#r-05-097).
Source ownership retains the exclusive-access requirements of
[R-05-096a](https://github.com/symbiogenesis/VerifiedOS/blob/main/docs/spec.md#r-05-096a).

Sequencing composes transitions, concatenates traces and unions effects.
Repeated callbacks or resumptions need repeatability contracts, separated
`Delta_i` and per-call trace laws. A multi-shot capture needs `Dup` for the
whole context, even for pure arguments. Mutation updates the current owner
snapshot, and a shape change consumes the old owner. A historical copy needs
fresh evidence before it describes the current contents.
[Cell and snapshot rules](../interior-mutability/#snapshots-and-dependent-indices)

## Schematic derivations and invalid neighbors

These hand derivations illustrate the proposed rules. The invalid variants
preserve unrelated representations and resources so each reaches its stated
failing premise.

### Pure dependent identity

In `NatExact`, `Gamma = a:Type i, x:a`, `M=((),(1))`: `VAR` gives `u=(0,1), v=(1,0)` for `x:a`; `LAM` over `x` gives `Pi x:(1,0) a.a` (`a` subject 0, type `1+1=2`); abstracting `a` yields:

```text
id : Pi a:(0,2) Type i. Pi x:(1,0) a.a
id = lambda a. lambda x. x
```

Instantiating `a=Byte, x=7` erases `a` and keeps `7`; changing `a`'s type grade to 1 fails `2=1`, and changing `x`'s subject grade to 0 or 2 fails `1=0` / `1=2` (scalars imply no byte-storage ownership). For `(2,cons 7 (cons 9 nil)) : Sigma k:Nat.Vec Byte k` (with constructors `nil:Vec Byte 0`, `cons:Byte -> Vec Byte k -> Vec Byte (k+1)`), substituting `2` matches `Vec Byte 2`, while packing under `3` fails `2=3` (`GF-elimination` owns recursor/constructor laws).

### Runtime-dependent packet

With `N=4`, immutable `n=2`, buffer `[7,9,0,0]`, entry `Own(r,4,[7,9,0,0])`, and checked descriptor `h:Handle(r,n)` (capacity/narrowing determined by contract): in `Gamma=r:Identity,n:Nat,h:Handle(r,n)`, `h` depends on `r,n`; `(n,h):Sigma k:Nat.Handle(r,k)` uses `(n=1,h=1)` in subject, retains `n` physically, and attaches `n<=N` as erased evidence. Matching `(k,p)` once (`s=1`) repacks `(k,p)` retaining `r` and loan/restoration duties; bounded readers use their own recurrence rather than inheriting `s=1` (`GF-resource` owns read/view/restoration lemmas). Negatives: erasing `n` fails reader's phase premise; packing `Handle(r,2)` under `3` fails without transport; deleting `n` despite zero computation use breaks `h`'s WF telescope; resizing while keeping stale length fails the output predicate.

### Graded callback and shared service join

A pure callback over an immutable 2-byte snapshot runs twice in order (`CallCount=1+1=2`, `NatExact(2)` on callable, `Dup` on env; allowance `1` fails `2=1`; single-call branches must return an indexed count or bound). In [the combined client](../full-language-review/#composed-client-and-inhabited-entry), packet/frame owners and `AddOnce(request,n)` stay in `Delta` outside the handler (`n` represented, overflow bound erased); multi-shot resumptions cannot reuse `AddOnce`, callbacks capturing owners via cells fail `Dup`, Boolean presence `1+1=1` cannot contract `AddOnce`'s spatial split, and dropping verdicts or must-erase data fails `Dispose`.

## Inference, specialization and admission

Compile-time availability is independent of grade, phase and representation.
Materialized constants and generated syntax still undergo resource checks.
[Staging contract](../metaprogramming/#evaluation-and-phase-boundaries)

The first release selects natural domains, bidirectional checking, fixed
ownership modes and bounded refinements. The broader design adds domain
identities, grade variables and constraints. Typing rules propose demand, and
checked CIC terms prove the required equalities and orderings. Each successful
constraint result binds its proposition, domain dictionary, substitutions and
replayable proof. Unresolved or timed-out searches leave open obligations under
the declared grade. Check public polymorphic calls against their explicit
constraints and keep runtime indices represented.

**Derived mode crossing:** following OxCaml's [Data Race Freedom à la Mode](https://doi.org/10.1145/3704859) (POPL 2025) and [Mode Crossing](https://doi.org/10.1145/3828681) (ICFP 2026) (see [the research survey](../../assurance/verification-strategy/#dependent-types-effects-and-ergonomics)), types with checked deeply immutable, authority-free representations (scalars, closed non-dependent pure records, unions, tuples, and immutable snapshots) cross locality, duplication (`Dup`), bulk relocation, and read-sharing modes automatically via structural fixed-point derivation. Authority-bearing handles, exclusive loans, mutable cells, unconstrained generics, and linear tokens never cross modes silently, and every crossing rule remains backed by a checked representation and resource theorem.

Specialization fixes phase, ABI, layout, and erasure pre-emission (mixed represented/erased instantiations need separate ABIs or uniform-erasure theorems; devices carry no runtime grade dictionaries or open-term normalization; source specialization never authorizes composition-time singleton cloning). `SourcePackage` binds source/generated inputs, domain impls/laws, constraints, proofs, implicits/transports, representation, and exact core term (stale core proofs must fail on changed source; erasure preserves results, control, effects, resources, and observations across proof-differing instances). Project applicable source duties into admitted [R-05-132 TAL attributes](https://github.com/symbiogenesis/VerifiedOS/blob/main/docs/spec.md#r-05-132) and carry remaining general-domain/dependent-normalization obligations as CIC terms via [the compiler route](../../assurance/compiler-route-contract/).

## Mechanized core review

The [unified graded core](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core.v) and
[closed graded core](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v) (`GradedCoreClosure`)
replay without admits or axioms. The unified core proves
[checker soundness](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core.v#core_infer_sound),
structural rules, index and type substitution, subgrade admissibility,
[transport along zero-reflecting domain morphisms](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_meta_transport.v#core_grade_substitution),
[zero type-use irrelevance](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_meta_irrelevance.v#core_zero_type_use_irrelevance),
and [erasure simulation](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_erasure.v#core_erasure_simulation)
over any domain that satisfies the erasure laws. `GradedCoreClosure` and
`holdfast-parser check-graded-core` ([closure qualifier](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#qualify_graded_core_closure))
close all five review limits below; cite the core only within the recorded
**indexed graded CBV calculus boundary**.
[Prior work](../../assurance/verification-strategy/#reading-the-graded-type-claims) ·
[Theorem-level comparison](#theorem-level-prior-work-comparison) ·
[Closure item](../../assurance/completion-log/#q25fd-close-the-mechanized-graded-core-review-limits)

| Limit | Closed realization | Qualification evidence |
| --- | --- | --- |
| Dependency and conversion | Explicit **indexed graded CBV calculus boundary**: types (`TVec`, `TBox`, `TFun`) depend on normalized natural index arithmetic (`IVar \| INat \| IAdd \| IMul` over `ic : nat`), while general term-level dependency routes through Rocq kernel replay of elaborated HoldFast terms. `ty_conv` / `ty_convb` decide index arithmetic ([`idx_norm_sound`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#idx_norm_sound), [`idx_convb_sound`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#idx_convb_sound), [`ty_convb_sound`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#ty_convb_sound), [`ty_conv_equiv`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#ty_conv_equiv), [`vec_index_arith_conv`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#vec_index_arith_conv)), with reproved [`subst_preserves_typing`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#subst_preserves_typing), [`zero_type_use_irrelevance`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#zero_type_use_irrelevance), and [`conv_preserves_demands`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#conv_preserves_demands). | `GradedCoreClosure` (`tools/rocq/graded_core_closure.v`) + `holdfast-parser check-graded-core` (`probe_vec_arith_conv`, [`demand_changing_conv_refused`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#demand_changing_conv_refused)) audited with `Print Assumptions` and `rocqchk` (zero axioms). |
| Type safety | 3-way CBV evaluator (`EvalVal \| EvalOutOfFuel \| EvalStuck`) separates stuck faults from fuel exhaustion over `TmFix` and `TVec`. Closed well-typed terms never get stuck at any fuel `k : nat` ([`closed_typed_never_stuck`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#closed_typed_never_stuck)), and returned values inhabit their types ([`eval_val_typed`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#eval_val_typed)). | `GradedCoreClosure` (`tools/rocq/graded_core_closure.v`) + `holdfast-parser check-graded-core` with negative control [`seeded_fault_is_stuck_not_timeout`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#seeded_fault_is_stuck_not_timeout) (`probe_seeded_fault_stuck` confirms `TmVHead (TmVNil TNat)` returns `EvalStuck`) and [`divergent_loop_witness`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#divergent_loop_witness). |
| Fuel and termination | Bidirectional step-exact CBV erasure termination between source `eval` and erased `eval_erased` at arbitrary fuel `k : nat` ([`erasure_preserves_val`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#erasure_preserves_val), [`erasure_reflects_val`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#erasure_reflects_val), [`erasure_preserves_timeout`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#erasure_preserves_timeout), [`erasure_reflects_timeout`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#erasure_reflects_timeout), [`erasure_respects_conv`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#erasure_respects_conv)), with explicit zero-demand pure binder `EUnit` step accounting ([`zero_demand_pure_binder_erased`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#zero_demand_pure_binder_erased), [`zero_demand_pure_binder_accounting`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/rocq/graded_core_closure.v#zero_demand_pure_binder_accounting)). | `GradedCoreClosure` (`tools/rocq/graded_core_closure.v`) + `holdfast-parser check-graded-core` replayed with `Print Assumptions` and `rocqchk` (zero axioms). |
| Self-contained replay | `graded_cbv_span_carrier` is deterministically generated from [`elaborate_types._PRELUDE`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/elaborate_types.py) and bound by SHA-256 digest ([`verify_carrier_digest`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#verify_carrier_digest) vs [`carrier_sha256`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#carrier_sha256)). Every tracked `tools/rocq/*.v` unit passes minimal CIC profile and empty-ledger checks ([`audit_rocq_tree`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#audit_rocq_tree)) and compiles cleanly in topological order alongside `graded_cbv_span_carrier.v` from a fresh directory with `rocqchk` (`allowed_axioms=()`) via [`replay_full_rocq_tree`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#replay_full_rocq_tree). | `holdfast-parser check-graded-core` (`graded_core_closure.py --full-tree`) verifies missing/tampered carrier refusals, `Print Assumptions` on `AUDITED_THEOREMS`, and full-corpus `tools/rocq/*.v` clean-tree `rocqchk` replay (zero axioms). |
| Prior-work positioning | Published [theorem-level prior-work comparison](#theorem-level-prior-work-comparison) matching [`prior_work_comparison`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#prior_work_comparison), separating `holdfast-specific` from `re-mechanized` theorems, modeled fragments, and hypotheses across GrTT/Gerty, GraD, and Abel–Danielsson–Eriksson. | [`prior_work_comparison`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#prior_work_comparison) verified by `holdfast-parser check-graded-core` and [the closure test suite](https://github.com/symbiogenesis/HoldFast/blob/main/tools/tests/test_holdfast_graded_core_closure.py) against the published Markdown table. |

### Theorem-level prior-work comparison

Published positioning of `GradedCoreClosure` (`tools/rocq/graded_core_closure.v`) against GrTT/Gerty, GraD, and Abel–Danielsson–Eriksson (ADE), matching [`prior_work_comparison`](https://github.com/symbiogenesis/HoldFast/blob/main/tools/toolchain/graded_core_closure.py#prior_work_comparison):

| Theorem group | Status | Modeled fragment | Hypotheses | GrTT / Gerty | GraD | Abel–Danielsson–Eriksson (ADE) |
| --- | --- | --- | --- | --- | --- | --- |
| `idx_norm_sound` / `idx_conv_sound` / `vec_index_arith_conv` | `holdfast-specific` | Indexed graded CBV calculus (`IVar \| INat \| IAdd \| IMul` over `ic : nat`) | Decidable normalized index arithmetic without general term-in-type evaluation | GrTT proves normalization on paper for full dependent types; Gerty prototype relies on unverified external SMT | GraD Coq mechanization covers selected non-indexed syntax only | ADE Agda mechanization proves decidable definitional equality for a full dependent type theory without HoldFast index-carrier restriction |
| `conv_preserves_demands` / `demand_changing_conv_refused` | `holdfast-specific` | Dual computation (`u`) and type-use (`v`) demand vectors under `ty_conv` | `ty_wf ic B`, `ty_conv A B`, and `ty_demand ic B = v` | GrTT separates subject and type grades on paper; no mechanized Coq/Rocq demand-preservation conversion theorem | GraD discards type-use demand rows in runtime heap semantics | ADE tracks a single grade vector in Agda rather than HoldFast's split `(u, v)` demand rows |
| `subst_preserves_typing` | `re-mechanized` | Simultaneous depth-`k` term substitution updating demand vectors via `subst_demand` | `HasType ic (G_hi ++ (qs, qts, S) :: G_lo) u v t B` and `HasType ic G_lo u_s v_s s S` | Re-mechanizes GrTT's paper substitution lemma for HoldFast's indexed `HasType` judgment | Parallels GraD's Coq substitution for selected syntax, but within Rocq 9.3.0 minimal CIC (predicative universes) | Parallels ADE's Agda substitution lemma inside a distinct Martin-Lof Agda formulation |
| `zero_type_use_irrelevance` | `re-mechanized` | Type-use demand vector `ty_demand` over `idx` and `Ty` | `k < n` and `nth k (ty_demand n A) 0 = 0` | Extends `graded_type_irrelevance.v` / `graded_core_metatheory.v` to conversion-equipped indexed types | No separate type-use irrelevance theorem in GraD | ADE proves extraction irrelevance for computation erasure rather than HoldFast's separate type-use substitution skipping |
| `closed_typed_never_stuck` / `eval_val_typed` / `seeded_fault_is_stuck_not_timeout` | `holdfast-specific` | 3-way CBV evaluator (`EvalVal \| EvalOutOfFuel \| EvalStuck`) with `TmFix` and `TVec` | Closed well-typed `HasType 0 [] [] [] t A` at arbitrary fuel `k : nat` | Gerty models CBN/normalization on paper; no mechanized 3-way CBV progress/preservation | GraD Coq mechanization uses `Type : Type` and notes ordinary progress/preservation does not cover usage | ADE proves normalization in Agda for terminating restricted modalities without a fuel-vs-stuck CBV evaluator |
| `erasure_preserves_val` / `erasure_reflects_val` / `erasure_preserves_timeout` / `erasure_reflects_timeout` / `zero_demand_pure_binder_accounting` | `holdfast-specific` | Bidirectional step-exact CBV erasure with explicit zero-demand pure binder `EUnit` accounting | `HasType 0 [] [] [] t A` at fuel `k : nat`; pure-value zero-demand binders satisfy `is_pure_val rhs && var_unused 0 body` | GrTT/Gerty do not mechanize bidirectional CBV termination/timeout reflection | GraD heap semantics does not prove bidirectional erased timeout reflection | ADE proves extraction soundness in Agda for `Nat`-typed terminating programs with no erased weak-pair matching; HoldFast proves both value and timeout reflection for CBV at exact fuel `k` |

<a id="q25d-debts-and-acceptance-boundary"></a>

## Proof and qualification obligations

Applies to the selected graded feature over its elaborated image; [the extension plan](../../plan/#language-extensions) owns implementation.

| Obligation | Required artifact and refusal predicate |
| --- | --- |
| `GF-domain` | Domain records, certificate interpreters, cross-domain laws with reconstructable certificates; reject Boolean-to-exact/ownership coercions and unsound order relaxation. |
| `GF-substitution` | Mechanize telescope WF, simultaneous substitution, vector updates, grade substitution, and structural rules over elaborated images; reject stale unsubstituted indices (no independent source reduction premise). |
| `GF-elimination` | Dependent functions, pairs, boxes, sums, and recursors preserve grades and WF motives; include positive asymmetric-field examples with modalities; refuse erased runtime discriminants. |
| `GF-cbv` | Connect demand interpretation to sequenced CBV images, captures, and outcome-indexed exits; prove zero demand preserves effects/failures/verdicts and repeated demand reuses once-evaluated values. |
| `GF-resource` | Instantiate spatial ownership, views, restoration, and kinded authority on the CHERI logic/representation with inhabited packet entry states. |
| `GF-control-mutation` | Compose Capture/Dup/Dispose/Suspend/Transfer/Share with handlers and cells (repeated continuations, hidden cell captures, snapshots, cancellation, fresh `Delta_i`); prove [synchronous conservativity](../full-language-review/#conservative-connection-to-the-synchronous-slice); reject cross-resumption resource reuse. |
| `GF-erasure-source` | Prove phase separation, representation erasure (related behavior across proof-differing instances), and source correspondence under R-05-164/R-05-163; qualify inference diagnostics and stale-source rejection. |
| `GF-target` | Connect source representation, event projections, and obligations through the compiler route to TAL/Sail artifacts (source counts never substitute for final cost or arbitrary-context preservation). |
