string? Code { get; }
Source
Gets the existing stable diagnostic code when the rendered diagnostic starts with one.
Describes the native filesystem guarantees verified for an artifact root.
CoverageArtifactCapability Verify(string root)
Verifies that an existing private root supports the optional artifact operations.
root
The filesystem and physical identity observed while the native probes succeeded.
The probe uses only a uniquely named, manager-owned child directory and removes that exact child through the retained private-root lease. It never invokes another process.
bool IsSupportedFileSystem(string platform, string? fileSystem, bool isLocalVolume)
Pure filesystem/platform classification seam used by the supported-lane tests.
int InvokeUnixFStatFs(string platform, Architecture architecture, int descriptor, nint buffer, Func<int, nint, int> unixFStatFs, Func<int, nint, int> darwinX64FStatFs)
Dispatches fstatfs to the symbol matching the native filesystem-stat structure ABI.
Intel Darwin uses fstatfs$INODE64
; arm64 Darwin and Linux use fstatfs
.
(string FileSystem, bool IsLocal) ReadFileSystem(CoverageRunOutputLease root, string platform, Func<string, CoverageArtifactVolumeObservation> windowsVolumeObservation, Func<int, nint, int> unixFStatFs, Func<string, IEnumerable<string>> linuxMountInfo)
Reads filesystem metadata through narrow platform observations while keeping the retained directory handle and all path validation under the normal capability probe.
root
platform
windows
, macos
, or linux
.windowsVolumeObservation
unixFStatFs
fstatfs
against the retained directory descriptor and supplied buffer.linuxMountInfo
The observed filesystem name and whether the volume is local.
Production supplies DriveInfo
, the native fstatfs
call, and File.ReadLines(string)
. Tests may inject observations to verify result and failure orchestration; injected values do not establish native filesystem guarantees. The platform argument exists to exercise each decision lane on any test host. All callers still need a real retained lease, and the public capability probe continues its no-follow path, identity, locking, and rename checks after this observation succeeds.
string ReadLinuxMountType(string path, IEnumerable<string> mountInfoLines)
Finds the filesystem type of the longest Linux mountpoint containing a path.
path
mountInfoLines
/proc/self/mountinfo
; ordering does not affect the result.The filesystem type from the matching mountinfo record.
Structurally malformed records and records with non-absolute mountpoints are skipped. Mount paths are decoded using mountinfo octal escapes and matched on path-component boundaries; if no valid record contains path
, the parser throws IOException
. Callers should pass the retained absolute Linux path and the complete mountinfo snapshot.
Windows volume metadata returned by a capability filesystem observation.
IsReady
FileSystem
IsReady
is false.DriveType
Native file identity and mutation fingerprint captured from one open handle.
Identity
Length
ModifiedSeconds
ModifiedSubseconds
ChangedSeconds
ChangedSubseconds
Reads bounded, informational Git fingerprints for a coverage artifact run.
Only hashes and the clean/dirty/unknown label leave this reader; Git output is never retained.
Task<CoverageArtifactProvenance> ReadAsync(string repository, CoverageArtifactProvenance policy, CancellationToken token = default)
Combines caller policy metadata with repository HEAD and working-tree state fingerprints.
repository
policy
token
Task<CoverageArtifactProvenanceReadResult> ReadWithOutcomeAsync(string repository, CoverageArtifactProvenance policy, CancellationToken token = default)
Reads provenance and returns a safe outcome for the Git-state probe.
repository
policy
token
Fingerprints and a non-sensitive state describing whether the status probe completed.
Pairs provenance fingerprints with the safe outcome of its Git-state probe.
Provenance
GitStateProbeOutcome
Caller-owned streams used for coverage progress and diagnostics.
The coverage core never disposes, flushes, or retains these writers after an operation returns. Normal progress is written to Output
and watchdog or critical diagnostics are written to Error
.
CoverageTextWriters Create(TextWriter output, TextWriter error)
Validates the supplied writer pair before it enters the core.
Represents a stable execution failure raised by the private coverage core.
Command adapters map this exception to their host-specific error contract. The rendered message deliberately preserves the existing ASCOV diagnostic text, while ExitCode
preserves terminal watchdog exit 124.
string? Code { get; }
Source
Gets the existing stable diagnostic code when the rendered diagnostic starts with one.
int? ExitCode { get; }
Source
Gets the optional host process exit code.
Runs coverage collection and gate evaluation in their required order for first-party Evidence.
Task<CoverageEvidenceExecutionResult> RunAndGateAsync(CoverageRunRequest runRequest, CoverageGateRequest gateRequest, CoverageTextWriters writers, CancellationToken cancellationToken)
Runs collection, then evaluates and writes the supplied gate only after a successful collection.
Captures the two ordered operation results produced for an Evidence coverage declaration.
CoverageRunResult Run { get; }
Source
Gets the nonnull coverage collection result.
CoverageGateResult? Gate { get; }
Source
Gets the optional coverage-gate result produced after successful collection.
This value is null when Run
reports failure because the workflow deliberately skips gate evaluation and report writing. Callers must check CoverageRunResult.Success
and handle a null value before accessing gate details.
Describes a bounded, local storage diagnostic that never changes a primary coverage result.
Code
Operation
Cause
Recovery
SideEffects
RunId
ObservedBytes
AllowedBytes
SourceStillAvailable
SourceReplaced
Trace
CoverageArtifactDiagnostic Failure(string code, string operation, Exception exception, string sideEffects = "none")
Creates a cause-specific optional-storage failure without disclosing exception text.
code
operation
exception
sideEffects
Task WriteAsync(TextWriter writer)
Writes one bounded trusted diagnostic to stderr; writer failures remain secondary.
writer
string? Reason { get; init; }
Source
Gets the stable store-open failure reason, when classification is available; it is never ownership authority.
string Documentation { get; }
Source
Gets the canonical reference anchor for the diagnostic.
int MaxRetries { get; }
Source
Gets the maximum automatic retry count after the named condition has been resolved.
string Version { get; }
Source
Gets the producing engine version for troubleshooting effective defaults.
IReadOnlyList<string> EnvironmentNames { get; }
Source
Gets environment names relevant to local management, without their values.
int PolicySchemaVersion { get; }
Source
Gets the schema defining the fixed storage limits used by this diagnostic.
Bounds strings and renders local paths without exposing user prefixes or control characters.
string PathLabel(string path, string? repositoryRoot = null)
Renders an observed path for local diagnostics, with no credential-bearing URI support.
path
repositoryRoot
string Bound(string value)
Escapes controls and bounds an informational value; it never creates executable shell text.
value
Tracks one cumulative monotonic deadline for optional storage work.
void Check(CancellationToken token)
Checks cancellation and the work deadline before the next bounded chunk.
token
TimeSpan Elapsed { get; }
Source
Gets elapsed wall-clock work time, including waits and filesystem operations.
TimeSpan? Remaining { get; }
Source
Gets the remaining cooperative allowance, or null for explicit cancellable operations.
Classifies failures without parsing exception messages or disclosing persisted identities.
Schema-v1 native identities bind live objects but contain no independent continuity proof. A differing device/volume therefore remains a refusal, including when the file ID matches. The classification is diagnostic only: it never replaces retained-handle validation or authorizes repair.
InvalidDataException Invalid(CoverageArtifactStoreFailureKind kind, Exception? inner = null)
Annotates an ordinary invalid-data error, preserving the existing exception contract.
IOException PrivateAccess()
Annotates a native permission refusal while preserving its IOException contract.
IOException MarkMissing(IOException exception)
Classifies a nonempty unmarked root without changing the existing IOException refusal contract.
T Mark<T>(T exception, CoverageArtifactStoreFailureKind kind)
Attaches only a trusted bounded classification while retaining the original exception type.
CoverageArtifactStoreFailureKind? Kind(Exception exception)
Gets a trusted classification, or null for unclassified errors; messages and payloads are never inspected.
CoverageArtifactStoreFailureKind CompareIdentity(string persisted, string observed)
Distinguishes an observed volume change only when both complete legacy tuples parse.
Matching file IDs across volumes are insufficient. Unknown formats remain a generic identity mismatch.
bool TryReadIdentity(string value, out ulong volume)
Parses nonempty unsigned tuple fields in the complete schema-v1 record format; malformed fields fail closed without slicing outside their bounds.
string Cause(CoverageArtifactStoreFailureKind kind)
Gets actionable trusted text for a known refusal, without raw paths, metadata or native IDs.
string Recovery(CoverageArtifactStoreFailureKind kind)
Gets the conservative schema-v1 recovery path; no operation rebinds uncertain registrations.
A bounded, read-only lower-bound observation of known coverage output.
IReadOnlyList<string> ContinuationDirectories { get; init; }
Source
Gets bounded relative directories to inspect first on the next observation; these grant no ownership.
A relative path and size observed during coverage inspection.
A sanitized inspection failure, scoped to a repository-relative path.
Collector settings state and a precise reason for the result.
Inspects known test output without reading report payloads or modifying files.
CoverageArtifactObservation Inspect(string repositoryRoot, TimeProvider clock, TimeSpan budget, int maximumEntries, CancellationToken token, IReadOnlyList<string>? continuationDirectories = null)
Counts regular files below repository TestResults and coverage-output roots.
Budgets include directory enumerations and entry metadata checks. Incomplete results are lower bounds.
CoverageCollectorRisk ReadCollectorRisk(string settingsPath)
Reads a supplied effective settings file safely; this reports configured risk, not execution.
bool TryOpenRegularFile(string path, out FileStream? stream, out long length, CoverageArtifactCandidateCalls? nativeCalls = null)
Opens a candidate without following links and validates native regular-file facts.
path
stream
length
nativeCalls
Injected observations verify managed decisions; native platform acceptance is separate.
Per-call native candidate-file observations; defaults always inspect the real host.
Fake opens must return caller-owned native handles. Tests do not establish another OS's ABI or containment.
CoverageArtifactCandidateCalls Default { get; }
Source
Gets the real host's immutable observation set.
bool IsWindows { get; init; }
Source
Gets whether Windows handle metadata is selected.
bool IsMacOS { get; init; }
Source
Gets whether Darwin stat decoding is selected.
bool IsLinux { get; init; }
Source
Gets whether Linux stat decoding is supported.
Architecture Architecture { get; init; }
Source
Gets the process architecture used to decode Linux stat mode.
Func<string, SafeFileHandle> WindowsOpen { get; init; }
Source
Gets the Windows no-follow regular-candidate open operation.
Func<SafeFileHandle, uint> WindowsType { get; init; }
Source
Gets the Windows object-type observation.
CoverageArtifactStateCalls.ReadWindowsInformation WindowsInformation { get; init; }
Source
Gets the Windows native size and attribute observation.
Func<string, int, int> UnixOpen { get; init; }
Source
Gets the Unix no-follow candidate open operation.
Func<int, nint, int> UnixStat { get; init; }
Source
Gets the Unix native stat operation.
Collects explicitly writer-owned paths without adopting pre-existing output contents.
Writers register each attempted file publication and only invocation-unique subtrees. Hashing occurs after producers drain, under the caller's output lease. An incomplete inventory cannot publish complete history.
void RecordFile(string path)
Registers a path that this invocation creates or overwrites; absent failed writes are not invented.
path
void RecordFreshTree(string path)
Registers a newly created invocation-unique subtree, never a reused project or output directory.
path
FileObservation? ObserveBeforeWrite(string path)
Captures the pre-write state of a fixed-name artifact so a retained stale file is not adopted.
path
The prior length and write timestamp, or null when the destination did not exist.
void RecordAfterWrite(string path, FileObservation? before)
Records a newly created producer file; ambiguous retained destinations make the inventory incomplete.
path
before
IReadOnlyList<CoverageArtifactInventoryEntry> Capture(CancellationToken token)
Hashes the writer-owned regular files after producers stop, preserving exact original bytes.
token
A bounded complete inventory, or an exception that prevents optional complete publication.
CoverageArtifactProvenance Provenance(string driver, string configuration, IEnumerable<string> projects, string? include, string? exclude)
Creates bounded informational provenance from an invocation's declared policy.
driver
configuration
projects
include
exclude
Fingerprints contain no test arguments, environment values or source contents.
string OutputDirectory { get; }
Source
Gets the absolute output root whose writers own this inventory.
string ProducingVersion { get; }
Source
Gets the exact producing assembly version without reading environment or process arguments.
Length and timestamp used to distinguish a writer's output from a retained fixed-name file.
Coordinates a gate's read roots and report-write destination before evaluation starts.
Task<CoverageArtifactGateContext> AcquireAsync(CoverageGateRequest request, TextWriter errors, CancellationToken token)
Acquires strongest modes in deterministic physical-object order, reusing an explicit nested session.
request
errors
token
A disposable context retained through report publication and caller hashing.
Task RecordReportsAsync(CoverageGateRequest request, CoverageGateResult result, CancellationToken token)
Extends compatible current inventory with gate report bytes after publication.
request
result
token
void Dispose()
Releases all acquired leases in reverse deterministic order.
Coordinates bounded repository observations and persistent, local warning cooldowns.
Each instance shares one second and 10,000 entries across preflight and terminal inspection. Discovered files remain observations: they never become artifact ownership or deletion authority. Warning-state failure cannot replace the primary coverage result.
Task ObserveAsync(bool terminal, IReadOnlyList<CoverageArtifactInventoryEntry>? inventory, CancellationToken token)
Inspects at preflight or terminal publication with the remaining cumulative observation budget.
terminal
inventory
token
Task SettingsAsync(IEnumerable<CoverageArtifactSettingsResult> observations)
Reports configured collector risk or unknown settings, under the same persistent cooldown.
observations
Task EmitAsync(CoverageArtifactDiagnostic diagnostic, string condition, long bytes)
Emits one trusted condition unless an equivalent persisted observation is still in cooldown.
diagnostic
condition
bytes
Extends the existing retained-directory boundary for private artifact storage.
string GetArtifactObjectIdentity(SafeFileHandle handle)
Gets the physical identity of an already-opened regular file or directory.
handle
CoverageArtifactObjectState GetArtifactObjectState(SafeFileHandle handle, CoverageArtifactStateCalls? nativeCalls = null)
Reads native identity, length, last-write time and change time from an open regular file.
handle
nativeCalls
The file state used to detect in-place changes across an archive read.
Injected observations verify managed decoding and rejection decisions, not the native filesystem or ABI.
CoverageRunOutputLease? AcquireArtifactDirectory(string path, bool createMissing, bool requirePrivate, bool allowWindowsRenameSharing = false, Func<int, uint, int>? unixFChmod = null, Action<string>? beforeWindowsCreate = null)
Opens a retained directory without coverage-output ownership semantics.
path
createMissing
requirePrivate
allowWindowsRenameSharing
unixFChmod
beforeWindowsCreate
A retained directory, or null when an existing-only path is missing.
Existing permissions are validated, never repaired. Callers separately validate store/schema authority.
void VerifyArtifactBinding()
Rechecks the entire pathname against the directory objects originally acquired.
SafeFileHandle OpenArtifactOperationLock(string name = ".appsurface-coverage-operation.lock", bool requirePrivate = false, bool readExistingOnly = false)
Opens the Windows cooperative-lock file without following links or allowing replacement.
name
requirePrivate
readExistingOnly
long ReadArtifactCoordinationFileLength(string name)
Validates an existing zero-length private coordination file without creating or changing it.
name
The validated length, always zero.
void VerifyArtifactOperationLockBinding(SafeFileHandle lockHandle, string expectedIdentity, string name = ".appsurface-coverage-operation.lock")
Verifies the named Windows operation lock still identifies the retained lock object.
lockHandle
expectedIdentity
name
CoverageRunOutputLease CreateArtifactDirectory(string name, Action? beforeCreate = null, Action? onCreated = null)
Creates a private immediate child and retains its complete no-follow path.
name
beforeCreate
onCreated
The privately created child directory.
FileStream OpenArtifactFile(string name, bool createNew, bool requirePrivate = true)
Opens an immediate regular, singly-linked file through the retained directory.
name
createNew
requirePrivate
A caller-owned stream bound to the opened object.
IReadOnlyList<CoverageArtifactDirectoryEntry> EnumerateArtifactEntries(int maximumEntries)
Enumerates at most a caller-supplied number of immediate entries without following links.
maximumEntries
Validated regular-file and directory names.
void MoveArtifactEntry(string sourceName, CoverageRunOutputLease destination, string destinationName, bool replaceFile = false, string? expectedSourceIdentity = null)
Atomically renames an immediate child, optionally replacing one regular metadata file.
sourceName
destination
destinationName
replaceFile
expectedSourceIdentity
void DeleteArtifactEntry(string name, int maximumEntries, string? expectedIdentity = null)
Deletes only a previously authorized immediate entry through the retained directory.
name
maximumEntries
expectedIdentity
Unknown trees, links, changed identities and excessive depth fail closed; they are not repaired. Windows deletion completes after retained handles to the entry close. Callers keep their candidate lease through deletion and metadata publication, then dispose it before asserting namespace disappearance.
void ValidateArtifactComponent(string name)
Validates one cross-platform path component before any filesystem call.
name
bool AcquirePrivateWindowsDirectory(bool createMissing, bool allowRenameSharing, Action<string>? beforeCreate)
Retains and validates each Windows path component, reopening a competing creator without repairing its access.
void CreateMissingWindowsDirectory(string path, Action<string> createDirectory)
Accepts only an already-existing-name race during an idempotent Windows component walk.
path
createDirectory
The caller must reopen and verify kind, no-follow identity and required private access. Fresh destinations never use this helper.
void CreatePrivateWindowsDirectory(string path)
Atomically creates one new directory with the current-user owner and protected private ACL.
void CreateArtifactWindowsDirectory(string path, byte[] descriptor, Func<string, nint, bool>? createDirectory = null)
Publishes a fresh Windows directory with its already-built private security descriptor in the native create call.
path
descriptor
createDirectory
void ValidateArtifactWindowsAccess(string? owner, string user, IEnumerable<CoverageArtifactAccessRule> rules)
Rejects Windows ownership or allow rules granting access beyond the current user and system administrators.
owner
user
rules
These are policy decisions over observed facts; caller tests do not establish native ACL retrieval or Windows handle binding.
void ValidateArtifactUnixMetadata(SafeFileHandle handle, bool directory, bool requirePrivate, CoverageArtifactStateCalls? nativeCalls = null, uint? effectiveUserId = null)
Validates ownership, link count and private permissions from one retained Unix object.
handle
directory
requirePrivate
nativeCalls
effectiveUserId
Synthetic observations test rejection policy and stat decoding, not another platform's native ABI.
IReadOnlyList<string> ReadArtifactWindowsNames(SafeFileHandle directory, int maximumEntries, Func<SafeFileHandle, IEnumerable<string>>? enumerate = null)
Collects bounded immediate Windows names from the retained directory.
directory
maximumEntries
enumerate
Injected names verify the count and iterator decisions; they do not prove Windows enumeration.
IReadOnlyList<string> ReadArtifactUnixNames(SafeFileHandle directory, int maximumEntries, CoverageArtifactEnumerationCalls? nativeCalls = null)
Enumerates a bounded Unix directory with explicit descriptor/stream ownership.
directory
maximumEntries
nativeCalls
Omission uses the host APIs; fake results exercise orchestration, not the kernel ABI.
int DuplicateCloseOnExec(int descriptor)
Atomically duplicates a Unix descriptor with close-on-exec set.
descriptor
A close-on-exec duplicate, or a negative value on native failure.
void RenameArtifactWindows(SafeFileHandle source, SafeFileHandle destination, string name, bool replace, Func<SafeFileHandle, nint, uint, int>? publish = null, Func<int, uint>? translateError = null)
Encodes a Windows handle-relative rename and rejects unsuccessful native publication.
source
destination
name
replace
publish
translateError
Tests can inspect the encoded request without executing Windows or attesting to its ABI.
string ArtifactDirectoryPath { get; }
Source
Gets the canonical path whose binding is retained by this lease.
string ArtifactDirectoryIdentity { get; }
Source
Gets an operating-system object identity, independent of path spelling.
SafeFileHandle ArtifactDirectoryHandle { get; }
Source
Gets the retained directory handle for a cooperative native lock; the caller must not dispose it.
Per-call native Unix enumeration results with production descriptor ownership defaults.
Fake results must describe their own descriptors and pointers; they do not establish filesystem support.
CoverageArtifactEnumerationCalls Default { get; }
Source
Gets the immutable default call set.
Func<int, int> Duplicate { get; init; }
Source
Gets a fresh close-on-exec descriptor for the same directory.
Func<int, long, int, long> Seek { get; init; }
Source
Gets the rewind operation on the fresh descriptor.
Func<int, nint> OpenDirectory { get; init; }
Source
Gets the operation transferring descriptor ownership to a directory stream.
Func<nint, nint> ReadDirectory { get; init; }
Source
Gets the next native directory entry or zero at end/failure.
Func<int, int> Close { get; init; }
Source
Gets the close operation before stream ownership transfers.
Func<nint, int> CloseDirectory { get; init; }
Source
Gets the operation closing the directory stream and its descriptor.
Describes a bounded, no-follow directory observation; it does not grant deletion authority.
Name
IsDirectory
Identity
Per-call native observations used to verify file-state decoding without altering global platform state.
Defaults call the host APIs. Tests may supply a platform, native results and retained-object identity; callers must not mix synthetic stat bytes with a real filesystem claim. No ownership check is bypassed in production.
CoverageArtifactStateCalls Default { get; }
Source
Gets the host-bound default operations.
bool IsWindows { get; init; }
Source
Gets whether Windows file-state decoding is selected.
bool IsMacOS { get; init; }
Source
Gets whether Darwin stat decoding is selected.
bool IsLinux { get; init; }
Source
Gets whether Linux stat decoding is available.
Architecture Architecture { get; init; }
Source
Gets the native process architecture used for Linux stat layouts.
ReadWindowsBasic WindowsBasic { get; init; }
Source
Gets the native Windows timestamp call, including its success result.
ReadWindowsInformation WindowsInformation { get; init; }
Source
Gets the native Windows size and identity metadata call.
Func<int, nint, int> UnixStat { get; init; }
Source
Gets the native Unix stat call; failure leaves the P/Invoke error available.
Func<SafeFileHandle, string> Identity { get; init; }
Source
Gets the identity observer for the same retained handle.
One SID-normalized Windows access rule observed through the native ACL API.
Principal
Rights
Allows
Describes the user-editable retention and warning thresholds for coverage artifacts.
Policy values control optional history retention and growth warnings. They do not change coverage collection, test execution, or gate thresholds. Hard resource limits are defined by CoverageArtifactLimits
and cannot be raised by this policy. The JSON object requires schemaVersion
with value 1
; its optional fields are historyMaxBytes
, historyMaxAgeDays
, repositoryWarningBytes
, domainWarningBytes
, and warningCooldownHours
. Omitted optional fields retain the property defaults shown below. Field names are case-sensitive. Unknown fields, duplicate names, missing or unsupported schema versions, and nesting deeper than 16 levels are rejected. Callers should apply only the returned complete policy; an invalid document never produces a partially applied result and does not make coverage collection optional.
CoverageArtifactPolicy Read(Stream policyStream)
Reads and validates a version 1 coverage artifact policy from a bounded UTF-8 JSON stream. Integer fields must use JSON integer syntax and satisfy their documented ranges; fractions, exponents, negative values where prohibited, unknown fields, duplicate fields, and documents deeper than 16 levels are rejected. The parser reads no more than 65,537 bytes to distinguish an allowed 65,536-byte document from an oversized one.
policyStream
The complete policy, with defaults applied to omitted optional fields.
ArgumentNullException
policyStream
is null.ArgumentException
policyStream
cannot be read.InvalidDataException
IOException
The stream remains open and must begin at the document's first byte. Reading is bounded even for a non-seekable or untrusted stream; the complete document is validated before a policy value is returned.
long HistoryMaxBytes { get; init; }
Source
Gets the maximum eligible history size in bytes. Its default is 2 GiB and its allowed range is zero through 1 TiB. Zero disables new history and allows only eligible unpinned history to expire during maintenance.
int HistoryMaxAgeDays { get; init; }
Source
Gets the maximum age in days for eligible history before it may expire. Its default is 7 days and its allowed range is 1 through 365 days.
long RepositoryWarningBytes { get; init; }
Source
Gets the repository-growth warning threshold in bytes. Its default is 1 GiB and its allowed range is 1 byte through 1 TiB.
long DomainWarningBytes { get; init; }
Source
Gets the domain-growth warning threshold in bytes. Its default is 2 GiB and its allowed range is 1 byte through 1 TiB.
int WarningCooldownHours { get; init; }
Source
Gets the minimum number of hours between repeated equivalent growth warnings. Its default is 24 hours and its allowed range is 1 through 168 hours.
Defines fixed resource caps and cooperative work budgets for coverage artifact storage.
These limits protect optional storage management from unbounded work or metadata growth. They are not user-configurable and do not constrain coverage collection or gate behavior.
Reads bounded private metadata, rejecting ambiguous duplicate keys before deserialization.
T Read<T>(Stream stream, long maximumBytes, JsonSerializerOptions options)
Reads at most the metadata limit plus one byte, even if an opened file grows.
T
stream
maximumBytes
options
The unambiguous schema record; callers validate its semantic facts.
Publishes bounded observation state through one fixed, private staging slot.
The caller must hold the directory's exclusive operation lease. A fixed slot bounds crash remnants; only a validated private regular slot with its retained identity may be reconciled. Unknown names and oversized, linked, or nonprivate slots remain untouched. This grants no current-output authority.
void Write(CoverageRunOutputLease directory, string destinationName, byte[] bytes, long maximumBytes, Action? beforePublish = null)
Writes and atomically replaces one bounded state file without accumulating unique remnants.
directory
destinationName
bytes
maximumBytes
beforePublish
The hook verifies cleanup decisions; production omits it. It must not be used as ownership authority.
Holds one compatible output mutation context across collection, gate reports and evidence hashing.
Required output coordination remains authoritative even when optional private history is unavailable.
Task<CoverageArtifactSession> BeginAsync(string output, string repository, bool clean, CoverageTextWriters writers, TimeProvider clock, CancellationToken token, CoverageArtifactOperationLease? operationLease = null)
Acquires output mutation authority, then attempts a prior-run snapshot at the normal clean boundary.
output
repository
clean
writers
clock
token
operationLease
A required run-long lease plus best-effort optional storage.
void VerifyBinding()
Verifies the required output identity before a participating mutation or read.
Task CompleteAsync(string outcome, CoverageArtifactProvenance provenance)
Publishes current-run registration without replacing the primary command outcome.
outcome
provenance
Task RecordPublishedArtifactsAsync(IEnumerable<string> publishedFiles)
Records reports written under this session and republishes the same run metadata.
publishedFiles
Task UpdateRegisteredInventoryAsync(string outputDirectory, IEnumerable<string> publishedFiles, TextWriter errors, CoverageArtifactOperationLease outputLease)
Updates an existing registered run's sidecar and registry after an independent gate writes reports.
outputDirectory
publishedFiles
errors
outputLease
The sidecar and existing non-report files must still match their registered lengths and hashes. Publication remains bound to the caller's leased physical output, including after a directory rename. A nonparticipating writer's changes are never adopted under earlier provenance.
void Dispose()
Releases compatible output authority after every participating caller has finished.
void PublishSidecar(CoverageRunOutputLease output, byte[] json, Action? beforePublish = null)
Publishes the current sidecar and removes only this call's staging file when publication fails.
output
json
beforePublish
Cleanup checks the staged file's retained object identity. A replacement entry is preserved, and cleanup failure never replaces the original publication failure.
string? FindOwnedInputRoot(string coveragePath, IDictionary<string, bool>? observedRoots = null)
Finds a physically bound managed input root without adopting copied metadata.
coveragePath
observedRoots
The nearest root whose bounded sidecar names its actual physical output, or null.
Missing, malformed, inaccessible and foreign sidecars do not grant ownership or require an input lock. A copied report remains eligible for the existing arbitrary-XML numeric gate. First-party Evidence retains its explicit execution session; this observation is neither source attestation nor registration.
CoverageArtifactCurrentRun ReadCurrent(Stream input)
Reads one bounded current sidecar, requiring compatible explicit producer inventory.
input
bool IsOptionalFailure(Exception exception)
Classifies expected optional store, filesystem, and metadata failures without catching programming errors broadly.
CoverageArtifactInventory Inventory { get; }
Source
Gets this invocation's explicit writer-owned inventory.
CoverageArtifactWarnings Warnings { get; }
Source
Gets the shared, bounded warning context for preflight, settings, and terminal observations.
Describes the explicitly owned current-run files eligible for a verified snapshot.
ManifestBase
Inventory
OutputPath
RepositoryPath
A bounded point-in-time view of the private coverage artifact domain.
long PinnedBytes { get; init; }
Source
Gets archived bytes protected by explicit pins, separate from current output bytes.
long StagingReservedBytes { get; init; }
Source
Gets bytes reserved for active or unreconciled staging; not a measurement of reclaimable bytes.
long MetadataBytes { get; init; }
Source
Gets bounded metadata bytes read for this observation.
int ExpiryReceiptCount { get; init; }
Source
Gets bounded expiry receipts retained for the last seven days.
IReadOnlyList<CoverageArtifactOverflowObservation> OverflowObservations { get; init; }
Source
Gets recent overflow observations; repeated observations are never added to exact current totals.
A recent capacity observation, never ownership authority or an exact domain total.
Coordinates private coverage artifact metadata and verified historical snapshots.
The store manages only producer-registered inventories and its own complete archives. Current output remains at its existing path. Metadata is versioned and bounded; unknown or invalid state fails closed and is never treated as permission to adopt or delete files.
string CreateNewDomain(string destination, bool apply, CancellationToken cancellationToken, Action? beforeRegistryPublication = null, Action? onDirectoryCreated = null, Action? beforeDestinationInspection = null, Action? beforeDestinationReopen = null)
Previews or explicitly creates a separate, empty private domain without accessing the configured old domain.
destination
apply
cancellationToken
beforeRegistryPublication
onDirectoryCreated
beforeDestinationInspection
beforeDestinationReopen
The normalized destination path. No history, registrations, pins or deletion authority are transferred.
Existing destinations are always refused, including empty or valid stores. Creation uses the retained parent's no-replace primitive. Cancellation or failure preserves any created private directory and metadata for inspection; retry with a different fresh destination rather than adopting a partial result. This is the safe schema-v1 alternative when independent continuity cannot be established.
CoverageArtifactStore Open(string? overrideHome = null, TimeProvider? clock = null, Func<CoverageRunOutputLease, string>? observeIdentity = null)
Opens or creates the current user's private artifact domain.
overrideHome
clock
observeIdentity
IOException
InvalidDataException
CoverageArtifactStore OpenReadOnly(string? overrideHome = null, TimeProvider? clock = null, Func<CoverageRunOutputLease, string>? observeIdentity = null)
Opens an existing private domain for status reads without creating or repairing any filesystem entry.
overrideHome
clock
observeIdentity
A read-only store; an absent domain is represented by an empty in-memory status view.
Task RegisterAsync(CoverageArtifactCurrentRun run, CancellationToken cancellationToken)
Registers one producer-owned current output and inventory.
run
cancellationToken
Task<CoverageArtifactRunManifest> SnapshotAsync(CoverageArtifactCurrentRun run, bool pin, bool automatic, CancellationToken cancellationToken, bool sourceLeaseHeld = false, CoverageArtifactWorkBudget? routineBudget = null)
Creates a complete, verified archive of the supplied registered current run.
run
pin
automatic
cancellationToken
sourceLeaseHeld
routineBudget
The complete manifest published in the archive.
CoverageArtifactCurrentRun? GetCurrentRun(string outputPath)
Returns the registered current run for the same physical output directory, if present.
outputPath
Task<bool> HasVerifiedArchiveAsync(string outputPath, CancellationToken token)
Checks whether a registered current output already has a complete, integrity-verified archive.
outputPath
token
CoverageArtifactStoreStatus GetStatus()
Reads a bounded status snapshot without changing current outputs or archives.
CoverageArtifactOperationLease AcquireCandidateLease(string candidatePath, bool exclusive)
Acquires candidate authority outside a deletable Windows directory, using the private domain's fixed lock file.
candidatePath
exclusive
A retained candidate lease; disposal never removes the domain lock file.
Task<IReadOnlyList<string>> MaintainAsync(bool apply, CancellationToken cancellationToken, CoverageArtifactWorkBudget? routineBudget = null, Action<string>? onArchiveDeleted = null, CoverageArtifactOperationLease? heldSourceLease = null)
Applies or previews eligible archive expiry under the shared retention policy.
routineBudget
apply
cancellationToken
heldSourceLease
onArchiveDeleted
Apply reconciles absent, unpinned historical archive registrations before selecting candidates. Reconciliation changes metadata only, preserves current/pinned entries and active snapshot reservations, and records an explicit missing-archive receipt without reporting a new physical deletion. Before deleting a candidate, apply verifies every stored and expanded payload length and hash under its exclusive candidate lease and the same cumulative work budget. Corruption preserves the archive.
Task PinAsync(string runId, bool pin, CancellationToken cancellationToken)
Changes pin state for a verified archived run.
runId
pin
cancellationToken
Task RestoreAsync(string runId, string freshOutputPath, CancellationToken cancellationToken)
Restores a verified archive into a fresh private output directory.
runId
freshOutputPath
cancellationToken
The destination is made absolute with Path.GetFullPath(string)
and normalized with Path.TrimEndingDirectorySeparator(string)
before checking existence or deriving its parent and final name. A trailing directory separator is accepted. The parent must already exist and pass safe traversal checks; an existing destination is never overwritten.
void Dispose()
Releases store resources.
StoreMarker? ReadMarker(CoverageRunOutputLease directory)
Reads bounded schema-v1 ownership metadata; missing is distinguished from malformed bytes.
void ValidateMarker(StoreMarker marker, string identity)
Requires the complete native identity; schema-v1 contains no independent remount continuity proof.
long MetadataBytes(CoverageRunOutputLease root)
Counts bounded domain metadata, including the non-authoritative warning and inspection observations.
string RootPath { get; }
Source
Gets the canonical private domain root.
CoverageArtifactPolicy Policy { get; }
Source
Gets the fully validated effective retention policy.
DateTimeOffset? ArchivedAtUtc { get; init; }
Source
Gets the verified archive publication time, independent of later current-output observations.
Describes the versioned metadata and integrity facts for one archived coverage run.
This is bounded local storage metadata. It describes the bytes observed during the original run and is not an attestation that those bytes match any later source tree.
int SchemaVersion { get; init; }
Source
Gets the manifest schema version. Version 1 is the only supported version.
string RunId { get; init; }
Source
Gets the run identifier encoded as 32 hexadecimal GUID N-format characters.
string OutputIdentity { get; init; }
Source
Gets the native identity of the output directory that produced the run.
string RepositoryIdentity { get; init; }
Source
Gets the native identity of the repository or worktree containing the run.
string Version { get; init; }
Source
Gets the producing AppSurface version.
string Outcome { get; init; }
Source
Gets the producing run outcome.
DateTimeOffset CreatedAtUtc { get; init; }
Source
Gets the time the original coverage run was created.
DateTimeOffset ArchivedAtUtc { get; init; }
Source
Gets the time this archive was completed.
CoverageArtifactProvenance? Provenance { get; init; }
Source
Gets optional bounded Git and configuration fingerprints.
IReadOnlyList<CoverageArtifactFileEntry> Files { get; init; }
Source
Gets the ordered file inventory and its verified compressed payload facts.
bool Complete { get; init; }
Source
Gets whether every payload and the manifest passed integrity verification.
Describes one archived file and the opaque payload that stores its gzip representation.
Path
PayloadId
OriginalLength
OriginalSha256
StoredLength
StoredSha256
Complete
Captures the expected path, length, and content hash observed by the archive inventory writer.
Path
Length
Sha256
Contains optional bounded fingerprints that describe original-run provenance.
GitRevisionFingerprint
GitStateFingerprint
ConfigurationFingerprint
Streams, verifies, and restores private gzip payloads for coverage-run archives.
Staging writes only inside a caller-owned private staging directory and never removes source files. The manager remains responsible for atomic directory publication, locking, quotas, and cleanup.
Task<CoverageArtifactRunManifest> StageAsync(string sourceRoot, string stageRoot, CoverageArtifactRunManifest manifestBase, IReadOnlyList<CoverageArtifactInventoryEntry> inventory, long maxOriginalBytes, long maxStoredBytes, TimeProvider clock, TimeSpan? budget, CancellationToken cancellationToken)
Creates and verifies a complete archive in an existing private staging directory.
sourceRoot
stageRoot
manifestBase
inventory
maxOriginalBytes
maxStoredBytes
clock
budget
cancellationToken
The complete manifest after every stored payload has been verified by decompression.
void WriteManifest(Stream destination, CoverageArtifactRunManifest manifest)
Writes one complete version 1 manifest to a caller-owned stream under the JSON size limit.
destination
manifest
CoverageArtifactRunManifest ReadManifest(Stream source)
Reads and validates one bounded version 1 manifest without disposing the input stream.
source
The validated complete archive manifest.
Task RestorePayloadsAsync(string archiveRoot, string freshStageRoot, CoverageArtifactRunManifest manifest, long expandedLimit, TimeProvider clock, TimeSpan? budget, CancellationToken cancellationToken)
Restores all verified payloads into an existing, empty, private staging directory.
archiveRoot
freshStageRoot
manifest
expandedLimit
clock
budget
cancellationToken
A task that completes after all restored bytes pass length and SHA-256 verification.
Task VerifyPayloadsAsync(string archiveRoot, CoverageArtifactRunManifest manifest, CancellationToken token, CoverageArtifactWorkBudget? sharedBudget = null)
Verifies every stored and original payload fact without publishing extracted files.
archiveRoot
manifest
token
sharedBudget
Persists bounded, non-authoritative directory cursors for incremental coverage inspection.
IReadOnlyList<string>? Read(CoverageArtifactStore? store, string scopeId, TimeProvider clock)
Reads the cursor for one scope without creating or modifying any store entry.
store
scopeId
clock
Ordered pending directories, or null when no unexpired observation exists.
Only observation hints are returned. Callers must revalidate every path and must not infer ownership or sum overlapping scans.
void Write(CoverageArtifactStore? store, string scopeId, IReadOnlyList<string> paths, TimeProvider clock)
Writes a bounded cursor for one scope into the existing store's private staging tree.
store
scopeId
paths
clock
State is private and atomically replaced. At most 32 scopes and 64 KiB are retained; older scopes and trailing paths are dropped before publication.
Reports whether one native operation-lock request acquired the lock and its native error code.
Acquired
ErrorCode
Provides per-acquisition observations for coverage artifact operation-lock orchestration.
Unset delegates use the production filesystem and native calls. Setting IsWindows
selects only the operation-lock branch: directory acquisition and physical identity inspection always use the real host OS. To exercise the Windows branch on another OS, callers must supply a real open lock-file handle through OpenWindowsLock
and fake TryWindowsLock
and VerifyWindowsLockBinding
delegates. Disposing that handle is the Windows lock-release operation. These delegates verify orchestration only; they do not emulate or validate LockFileEx
or Windows path binding. Native acceptance must be verified separately on the target OS. Instances are passed to one CoverageArtifactOperationLease.Acquire(string, bool, CoverageArtifactOperationLeaseOptions?, string?)
call and are never stored globally.
bool? IsWindows { get; init; }
Source
Gets the optional lock-platform selector; null
uses the real host OS.
Func<int, int, CoverageArtifactNativeLockResult>? UnixFlock { get; init; }
Source
Gets an optional Unix flock operation receiving the retained directory descriptor and flags.
It receives lock flags 5
for shared and 6
for exclusive acquisition, and 8
for unlock.
Func<CoverageRunOutputLease, SafeFileHandle>? OpenWindowsLock { get; init; }
Source
Gets an optional Windows lock-file opener for the retained directory.
The returned handle is owned by the operation lease and is disposed on failure or lease disposal.
Func<SafeFileHandle, uint, CoverageArtifactNativeLockResult>? TryWindowsLock { get; init; }
Source
Gets an optional Windows lock request receiving the owned file handle and LockFileEx flags.
It receives flags 1
for shared and 3
for exclusive nonblocking acquisition.
Action<CoverageRunOutputLease>? VerifyUnixBinding { get; init; }
Source
Gets an optional verifier for the retained Unix directory binding.
It runs after successful acquisition and on each live lease binding verification.
Action<CoverageRunOutputLease, SafeFileHandle, string>? VerifyWindowsLockBinding { get; init; }
Source
Gets an optional verifier for the retained Windows lock-file binding.
It receives the retained directory, lock handle, and identity captured when the lease was constructed. The default verifier checks the current named lock file against that identity using the host's native APIs.
Holds a fail-fast cooperative shared or exclusive lease on one physical output.
Unix uses nonblocking flock on the retained directory object; Windows uses LockFileEx on a persistent, no-follow regular lock file. Older binaries and external readers do not participate in this protocol. Multiple-output callers must acquire their strongest modes in deterministic physical-identity order.
CoverageArtifactOperationLease Acquire(string existingDirectory, bool exclusive, CoverageArtifactOperationLeaseOptions? options = null, string? windowsLockRoot = null)
Acquires one nonblocking strongest-mode lease without performing output cleanup.
existingDirectory
exclusive
options
windowsLockRoot
A disposable lease; contention fails with ASCOV202 before caller mutation.
The directory is always opened and validated with the actual host's filesystem APIs. Supplying options
can substitute only the lock orchestration observations for this call. A forced Windows branch on a non-Windows host requires an injected lock-file opener, lock result, and binding observer, so it cannot accidentally call Windows native exports on that host.
void VerifyBinding()
Rejects a changed physical output binding before a participating operation publishes.
void Dispose()
Releases native authority once; lock files remain persistent and are never removed to force admission.
ulong CandidateLockOffset(string physicalIdentity)
Maps a physical candidate identity to one nonzero Windows byte-range offset without growing the lock file.
A hash collision only rejects concurrent work; it cannot admit conflicting work. The fixed file is distinct from the root metadata lock.
string PhysicalIdentity { get; }
Source
Gets the physical volume/object identity used to order compatible operations.
bool IsExclusive { get; }
Source
Gets whether this retained lease authorizes mutation and recovery of its physical output.
Describes whether the bounded Git-state probe produced a fingerprint or a safe unknown.
Trusted failure categories for bounded store-open diagnostics; these grant no ownership.