# Executable library usage

Numeric project policy compares decimal values while retaining original tokens
and the exact-value semantics of other audit APIs.

```mbt check
///|
test "typed numeric policy checks inherited intervals and selects a cohort" {
  let p = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([p], [
    @trace.SidecarInput::new("bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let rules = @trace.NumericRules::from_json(
    "{\"fields\":{\"RepetitionTime\":{\"type\":\"number\",\"gte\":2,\"lte\":2e0}},\"relations\":[]}",
  )
  let expected = @trace.MetadataExpectations::from_json(
    "{\"required\":[],\"allowed\":{}}",
  ).with_numeric(rules)
  assert_eq(index.audit_all().check_expectations(expected).violation_count(), 0)
  let query = @trace.MetadataQuery::from_json(
    "{\"present\":[],\"absent\":[],\"equals\":{}}",
  ).with_numeric(rules)
  assert_eq(index.select_metadata(query).paths(), [p])
  assert_eq(index.resolve(p).to_json(), "{\"RepetitionTime\":2.0}")
}
```

Concurrent edits can be merged and passed through the existing release workflow.

```mbt check
///|
test "three-way merge composes fields and retains a reusable candidate" {
  let p = "sub-01/func/sub-01_task-rest_bold.nii"
  let base = @trace.DatasetIndex::from_manifest([p], [
    @trace.SidecarInput::new("bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let left = base
    .plan_edit(
      "bold.json",
      @trace.MetadataPatch::from_json(
        "{\"set\":{\"RepetitionTime\":3.0},\"remove\":[]}",
      ),
    )
    .after()
  let right = base
    .plan_edit(
      "bold.json",
      @trace.MetadataPatch::from_json(
        "{\"set\":{\"ReviewNote\":null},\"remove\":[]}",
      ),
    )
    .after()
  let report = base.merge(left, right)
  assert_eq(report.conflict_count(), 0)
  assert_eq(
    report.candidate().unwrap().resolve(p).to_json(),
    "{\"RepetitionTime\":3.0,\"ReviewNote\":null}",
  )
  assert_eq(report.impact().unwrap().changed_count(), 1)
}
```

```mbt check
///|
test "source coverage accounts for a completely shadowed parent" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"x\":1}"),
    @trace.SidecarInput::new(
      "sub-01/func/sub-01_task-rest_bold.json", "{\"x\":2}",
    ),
  ])
  let coverage = index.source_coverage()
  assert_eq(coverage.entries()[1].fully_shadowed_paths(), [path])
  assert_eq(coverage.entries()[1].winning_paths(), [])
  assert_eq(coverage.error_count(), 0)
}
```

Build a coordinated plan directly from typed MoonBit patches.

```mbt check
///|
test "typed coordinated edits expose the edited root without rewriting the baseline" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let source = "sub-01/func/sub-01_task-rest_bold.json"
  let before = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
    @trace.SidecarInput::new(source, "{\"RepetitionTime\":4.0,\"Custom\":null}"),
  ])
  let root_patch = @trace.MetadataPatch::from_json(
    "{\"set\":{\"RepetitionTime\":3.0},\"remove\":[]}",
  )
  let local_patch = @trace.MetadataPatch::from_json(
    "{\"set\":{},\"remove\":[\"RepetitionTime\"]}",
  )
  let batch = @trace.EditBatch::from_patches([
    ("task-rest_bold.json", root_patch),
    (source, local_patch),
  ])
  let plan = before.plan_edits(batch)
  assert_eq(
    plan.after().resolve(path).to_json(),
    "{\"Custom\":null,\"RepetitionTime\":3.0}",
  )
  assert_eq(
    before.resolve(path).to_json(),
    "{\"Custom\":null,\"RepetitionTime\":4.0}",
  )
  assert_eq(plan.updated_sidecar_json(source), Some("{\"Custom\":null}"))
  assert_eq(plan.impact().changed_count(), 1)
  assert_eq(
    @trace.EditBatch::from_json(batch.to_json()).to_json(),
    batch.to_json(),
  )
}
```

Review bundles carry every input needed to reproduce a release decision.

```mbt check
///|
test "an offline review round trip retains exact changes and full evidence" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let before = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let after = before
    .plan_edit(
      "task-rest_bold.json",
      @trace.MetadataPatch::from_json(
        "{\"set\":{\"RepetitionTime\":3.0},\"remove\":[]}",
      ),
    )
    .after()
  let captured = @trace.ReviewBundle::create(
    before,
    after,
    @trace.ReleasePolicy::AllChanges,
  )
  let replayed = @trace.ReviewBundle::from_json(captured.to_json())
  assert_eq(replayed.to_json(), captured.to_json())
  assert_true(
    replayed.report().decision() == @trace.ReleaseDecision::ChangesDetected,
  )
  assert_eq(replayed.report().affected_paths(), [path])
  assert_eq(replayed.before().to_manifest_json(), before.to_manifest_json())
  assert_eq(
    replayed.report().to_json(),
    before
    .compare(after)
    .release_check(@trace.ReleasePolicy::AllChanges)
    .to_json(),
  )
}
```

Plan a local removal and inspect its inherited result without changing the baseline.

```mbt check
///|
test "removing an override exposes its parent without mutating the baseline" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let local_path = "sub-01/func/sub-01_task-rest_bold.json"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
    @trace.SidecarInput::new(
      local_path, "{\"RepetitionTime\":3.0,\"Custom\":null}",
    ),
  ])
  let patch = @trace.MetadataPatch::from_json(
    "{\"set\":{},\"remove\":[\"RepetitionTime\"]}",
  )
  let plan = index.plan_edit(local_path, patch)
  assert_eq(plan.updated_sidecar_json(), "{\"Custom\":null}")
  assert_eq(
    plan.after().resolve(path).to_json(),
    "{\"Custom\":null,\"RepetitionTime\":2.0}",
  )
  assert_eq(
    index.resolve(path).to_json(),
    "{\"Custom\":null,\"RepetitionTime\":3.0}",
  )
  assert_eq(plan.impact().changed_count(), 1)
}
```

```mbt check
///|
test "a lower sidecar overrides one field without deleting another" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii.gz"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new(
      "task-rest_bold.json", "{\"RepetitionTime\":2.0,\"EchoTime\":0.04}",
    ),
    @trace.SidecarInput::new(
      "sub-01/func/sub-01_task-rest_bold.json", "{\"RepetitionTime\":3.0}",
    ),
  ])
  let result = index.resolve(path)
  assert_eq(result.to_json(), "{\"EchoTime\":0.04,\"RepetitionTime\":3.0}")
  assert_eq(result.trace("RepetitionTime").length(), 2)
  assert_eq(
    result.trace("RepetitionTime")[1].path(),
    "sub-01/func/sub-01_task-rest_bold.json",
  )
  let reload = @trace.DatasetIndex::from_json(index.to_manifest_json())
  assert_eq(reload.resolve(path).to_report_json(), result.to_report_json())
}
```

Release checks consume existing comparison evidence without dropping it.

```mbt check
///|
test "release policy distinguishes shadowed provenance from effective changes" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let before = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"x\":1}"),
    @trace.SidecarInput::new(
      "sub-01/func/sub-01_task-rest_bold.json", "{\"x\":3}",
    ),
  ])
  let after = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"x\":2}"),
    @trace.SidecarInput::new(
      "sub-01/func/sub-01_task-rest_bold.json", "{\"x\":3}",
    ),
  ])
  let impact = before.compare(after)
  let effective = impact.release_check(@trace.ReleasePolicy::EffectiveValues)
  assert_true(effective.decision() == @trace.ReleaseDecision::Pass)
  assert_true(
    impact.release_check(@trace.ReleasePolicy::AllChanges).decision() ==
    @trace.ReleaseDecision::ChangesDetected,
  )
  assert_eq(effective.impact().to_json(), impact.to_json())
}
```
Source inventory changes compose with the existing release policy.

```mbt check
///|
test "plan an added source without changing the baseline" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let before = @trace.DatasetIndex::from_manifest([path], [])
  let changes = @trace.SourceChanges::new(
    [
      @trace.SidecarInput::new(
        "task-rest_bold.json", "{\"RepetitionTime\":2.0}",
      ),
    ],
    [],
  )
  let plan = before.plan_sources(changes)
  assert_eq(before.resolve(path).to_json(), "{}")
  assert_eq(plan.after().resolve(path).to_json(), "{\"RepetitionTime\":2.0}")
  assert_eq(plan.impact().changed_count(), 1)
}
```
Project-specific expectations check inherited values with complete evidence.

```mbt check
///|
test "required acquisition metadata is checked after inheritance" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let expected = @trace.MetadataExpectations::from_json(
    "{\"required\":[\"RepetitionTime\"],\"allowed\":{\"RepetitionTime\":[2.0]}}",
  )
  let report = index.audit_all().check_expectations(expected)
  assert_true(report.decision() == @trace.ExpectationDecision::Pass)
  assert_eq(report.violation_count(), 0)
}
```
Select a cohort without losing inherited source evidence, then run project checks.

```mbt check
///|
test "entity selection composes with acquisition checks" {
  let first = "sub-01/func/sub-01_task-rest_run-01_bold.nii"
  let second = "sub-01/func/sub-01_task-rest_run-02_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([first, second], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let query = @trace.ScanQuery::new(["bold"], { "sub": ["01"], "run": ["02"] })
  let selection = index.select_scans(query)
  assert_eq(selection.paths(), [second])
  let expected = @trace.MetadataExpectations::from_json(
    "{\"required\":[\"RepetitionTime\"],\"allowed\":{\"RepetitionTime\":[2.0]}}",
  )
  assert_true(
    selection.audit().check_expectations(expected).decision() ==
    @trace.ExpectationDecision::Pass,
  )
}
```

# Filter inherited metadata without hiding unresolved scans

```mbt check
///|
test "metadata filtering feeds an error-aware audit" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii.gz"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("task-rest_bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let query = @trace.MetadataQuery::from_json(
    "{\"present\":[],\"absent\":[],\"equals\":{\"RepetitionTime\":[2.0]}}",
  )
  let selection = index.audit(["unknown", path]).filter_metadata(query)
  assert_eq(selection.paths(), [path])
  assert_eq(selection.audit().error_count(), 1)
  assert_eq(selection.audit().entries().length(), 2)
}
```

## Check scoped acquisition requirements

```mbt check
///|
test "a filename scope carries exact acquisition expectations" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let rules = @trace.AcquisitionRules::from_json(
    "{\"rules\":[{\"id\":\"bold\",\"select\":{\"suffixes\":[\"bold\"],\"entities\":{}},\"expect\":{\"required\":[\"RepetitionTime\"],\"allowed\":{\"RepetitionTime\":[2.0]}}}]}",
  )
  assert_true(
    index.check_acquisition(rules).decision() ==
    @trace.ExpectationDecision::Pass,
  )
  let empty = @trace.DatasetIndex::from_manifest([], [])
  assert_true(
    empty.check_acquisition(rules).decision() ==
    @trace.ExpectationDecision::Indeterminate,
  )
}
```
# Plan one final dataset snapshot

```mbt check
///|
test "combined transaction is exportable and leaves its baseline intact" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([path], [])
  let changes = @trace.DatasetChanges::from_json(
    "{\"scans\":{\"add\":[],\"remove\":[]},\"sources\":{\"add\":[{\"path\":\"bold.json\",\"metadata\":{\"RepetitionTime\":2.0}}],\"remove\":[]},\"edits\":{\"edits\":[]}}",
  )
  let plan = index.plan_changes(changes)
  assert_eq(
    plan.after().resolve(path).get("RepetitionTime").unwrap().stringify(),
    "2.0",
  )
  assert_true(index.resolve(path).get("RepetitionTime") is None)
}
```

## Check acquisition consistency within a subject

```mbt check
///|
test "uniform inherited acquisition values pass a grouped check" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("bold.json", "{\"RepetitionTime\":2.0}"),
  ])
  let rules = @trace.ConsistencyRules::from_json(
    "{\"group_by\":[\"sub\"],\"fields\":[\"RepetitionTime\"],\"require_present\":true}",
  )
  assert_true(
    index.audit_all().check_consistency(rules).decision() ==
    @trace.ExpectationDecision::Pass,
  )
}
```

## Remove a redundant override with a complete proof

```mbt check
///|
test "pruning preserves effective values and exposes its replayable patch" {
  let path = "sub-01/func/sub-01_task-rest_bold.nii"
  let local_source = "sub-01/func/sub-01_task-rest_bold.json"
  let index = @trace.DatasetIndex::from_manifest([path], [
    @trace.SidecarInput::new("bold.json", "{\"RepetitionTime\":2.0}"),
    @trace.SidecarInput::new(local_source, "{\"RepetitionTime\":2.0}"),
  ])
  let plan = index.plan_prune(local_source, ["RepetitionTime"])
  assert_eq(
    plan.after().resolve(path).get("RepetitionTime").unwrap().stringify(),
    "2.0",
  )
  assert_eq(
    index.plan_edit(local_source, plan.patch()).after().to_manifest_json(),
    plan.after().to_manifest_json(),
  )
}
```
