Skip to content

About

Payroll Engine Lex library: provenance of compliance values in data regulations — lex.json manifests, hashed snapshots, verification and checks against regulation lookups.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

Payroll Engine Lex

Part of the Payroll Engine open-source payroll automation framework. Full documentation at payrollengine.org.

Library for the provenance of compliance values in data regulations. A lex.json manifest documents where each value comes from (source URLs, location, legal reference, evidence files); a snapshot.json freezes the manifest and its evidence with hashes.

The library provides:

  • Manifest and snapshot model (Manifest, Entry, Source, EvidenceFile, Exclusion, Verification, Snapshot)
  • JSON schema of lex.json (Schema) and structural validation (Validator)
  • Editing of lex.json that keeps unknown properties and the property order (ManifestEditor): add entries and files, set source locations, automatic and manual verification records and reviews; change the reason of an exclusion; remove exclusions, entries and source declarations (ManifestReferences lists what refers to them)
  • Download of source documents into the .lex folder (Fetcher)
  • Snapshot creation (SnapshotWriter) and verification against the manifest and the evidence files (Verifier)
  • Check of a manifest against the lookup values of its regulation: coverage, value differences, traceability fields, evidence files, validFrom, verification records and open entries (Checker, EvidenceCheck, CheckReport)
  • Availability check of the source URLs and detection of changed sources (UrlChecker, LiveSource)
  • Lookup of the entry numbers in the source document, with rating of weak matches, source quotes and sampling of large tables (SourceVerifier, ManifestVerifier, SourceDocument)
  • Release gate: entry-specific locations, official main sources, no weak automatic matches, no zero values without justification (Checker)
  • Conversion of official text tables (fixed columns or tab-delimited, also inside a ZIP archive) into lookup values (TextTable, TextTableMap, ContentSource)
  • Transfer of the lex values into the lookup values of the regulation, large tables as deterministic ZIP archive (Applier)
  • Rollover of a satellite to the next cycle (Rollover)

Besides the .NET base class library, the library uses PdfPig (Apache-2.0) to read PDF sources and ExcelDataReader (MIT) to read Excel workbooks (see Third-Party Notices). It is used by the Lex commands of the Payroll Console (LexFetch, LexAdd, LexVerifySource, LexAttest, LexSnapshot, LexVerify, LexCheck, LexApply, LexRollover) and by its LookupTextImport command.


Sources

An entry lists its sources in sourceUrls; the first URL is the main source. A value whose numbers are spread over several documents (e.g. a rate table and a separate ceiling notice) lists all of them. SourceVerifier reads every source and counts a number as found when any readable source holds it; an unreadable source is reported, but does not hide the numbers found in the others. A file in files[] also lists its sourceUrls: SnapshotWriter downloads it from the first URL that answers. A source with "official": false is a secondary source; as main source it is reported by the checker (a finding in the release mode).

Evidence Quality

SourceVerifier.Verify returns a SourceMatch. A single number is rated Ambiguous instead of Found when the source writes it with at most two digits (22%, 1.5), writes it with at most three digits in more than three sections, or holds it in words only ($1 million, one and one-half, 2.5 lakh). A value below 1 is also looked up as percentage when the source writes %, percent, per cent or per centum after the number, except for units that are no rate (factor, hours, days, currency codes). The unit percent points (also percentage points) declares a source that writes the rate as percentage without percent sign, a rate table under a heading (Tipos de cotización … 2,70 for 0.027): the value is then also looked up as the plain number. A sourceQuote anchors the numbers it holds; the other numbers of the entry are looked up in all sources like without quote, so a bundle over several sources can anchor single values. A quote without a number of the entry locates the section that must hold the numbers. A quote missing in the source gives QuoteNotFound.

Sources often hold tables over several years, so a number of another year may be "found". With the year of the entry — its referenceYear, otherwise the year of the manifest validFrom — each hit of a number is rated by the closest year in the text: the nearest four-digit year (1990–2100, not part of a longer number, an amount or a percentage) within 120 characters before or after the hit, considering only the years from the entry year minus 3 to plus 1. An enumeration or range of years counts as one year group: 2024, 2025, or 2026, 2024 and 2025, 2024-2026, 2024 through 2026. A hit is

  • positive when the closest year (group) holds the entry year (at the same distance this group wins),
  • weak when the closest year is another year ($52,400 in 2024 for validFrom 2025),
  • neutral without a year in the window; other years elsewhere on the page (forms filed for 2019 or earlier) do not matter. A validity start up to the entry year is neutral too, it neither weakens nor confirms: effective January 1, 2025, beginning on or after January 1, 2025, 2025 and after; as is the year a value is unchanged from: unchanged from 2024, same as 2024.

A year of the section heading (2024 Rates) counts as a year at the start of the section text.

A number with a weak and without a positive hit rates the entry Ambiguous with multi-year section: add sourceQuote with the year — a neutral hit does not confirm it, a value of a wrong year is the greater risk. For a bundle the reason lists the affected numbers, e.g. (0.0031, 148200). A Partial entry gives the same reason in SourceResult.Ambiguity for its found numbers, so a fixed missing number does not reveal a year finding only on the next run. With a sourceQuote only the quote is rated for the numbers it holds: a quote with the entry year or a year group holding it (2025: employee rate 0.19%) or without any year (statute text) anchors them, a quote whose number stands next to another year is year-weak; the other numbers of the entry are rated in the sources. A four-digit number within a number row is no year: another number within 12 characters on both sides without a word, colon or parenthesis in between (wage bracket table 1965 1995 32.50), as is a number after a currency sign ($ 2025). A value that legally belongs to another year than the cycle (a surcharge for 2025 in the 2026 satellite) sets referenceYear (e.g. 2025): it replaces the validFrom year in the year rating and for the quote, and LexCheck lists such entries as information. referenceYear is part of the snapshot hash and is kept by LexRollover. Years of a legal source reference are ignored: directly after Notice, Pub. or Rev. (also Rev. Guide 2024, Rev. 12-2025), in a document number with hyphen or slash (2024-40, 2025/1234, also ISO dates), in parentheses after a statute reference (Bill 951 (2022)) and in the citations listed in Languages, Scripts and Periods. Print and typesetting marks are ignored too, a date with a time (15:14 - 3-Dec-2025, 16:58 Oct 31, 2025): a document is printed before the year it is valid for. A numeric date with dots (17.09.2026, ab 01.01.2026) counts with its year, also in a table row; after an enactment word it is a citation (Verordnung vom 20.12.2024).

Languages, Scripts and Periods

The year rating and the number lookup read the words of a language from a language file {language}.json (LanguageSet). The package ships English, German, French, Spanish, Italian, Dutch and Portuguese in the folder LexVocabulary next to the library. A folder of additional language files, given by the caller (ManifestVerifier.VerifyManifest(…, languageDirectory), LanguageSet.Get(languages, additionalDirectory); in pecmd LexVerifySource Vocabulary:<folder> or the environment variable PAYROLL_ENGINE_LEX_VOCABULARY), adds a language or replaces a package file with the same language code, so a new language needs no new library version. The library reads no environment variable or configuration of its own. A manifest selects the languages of its sources with languages (["de", "fr"]); without it all available languages apply as one union, so a source mixing languages (an English summary of a Dutch decree) is read the same way. Words of a language apply only in their position (a connector between two years, a validity phrase before a year), so a short word of one language does not change a text of another language.

A language file lists word arrays; every array is optional, an unknown property is an error:

{
  "language": "da",
  "name": "Danish",
  "percentWords": ["procent"],
  "scaleWords": [{ "word": "mio.", "factor": 1000000 }],
  "scaleAbbreviations": [], "minorUnits": [{ "word": "øre", "factor": 0.01 }],
  "halfWords": [], "oneAndHalfWords": [], "doubleWords": [],
  "enumerationWords": ["og", "eller"],
  "rangeWords": ["til"],
  "validityBefore": ["med virkning fra"], "datedValidityBefore": [], "validityAfter": [],
  "unchanged": ["uændret"],
  "enactmentWords": ["lov", "bekendtgørelse"], "enactmentEndings": ["loven"],
  "titleWords": [], "gazettes": [], "dateLinks": ["af"], "dayLinks": [],
  "months": [["januar", "jan"], ["februar", "feb"], ["marts", "mar"], ["april", "apr"], ["maj"], ["juni", "jun"],
    ["juli", "jul"], ["august", "aug"], ["september", "sep"], ["oktober", "okt"], ["november", "nov"],
    ["december", "dec"]]
}

months lists the twelve months January to December, each with its names and abbreviations; a name belongs to one month only. dayLinks are the words between a day and its month (the 1st day of April). scaleAbbreviations are letters directly after an amount with currency sign ($10m), minorUnits are units below 1 after a number (88 cents). titleWords, gazettes and minorUnits are case-sensitive, all other words are not. Each result names the languages and the hash of their words (SourceResult.Languages, e.g. de,en 3f2a9c1b); the automatic verification record writes them into its method (LexVerifySource 1.2.0; languages de,en 3f2a9c1b), so a changed word list renews the record on the next run and every result can be reproduced with the same language files. The manifest validation (LexCheck, LexSnapshot, LexApply) reports an invalid or duplicate language code; a language without language file stops LexVerifySource for the manifest.

Topic Examples
Percent words percent, Prozent, pour cent, por ciento, per cento, procent, por cento
Scale words million, Mio., Mrd., millions, millones, milioni, miljoen, milhões, lakh, crore
Scale abbreviations k, m, bn
Minor units cents, Cent, centimes, céntimos, centavos, centesimi, eurocent, cêntimos
Year groups 2024 und 2025, 2024 et 2025, 2024 bis 2026, de 2024 a 2026, 2024 t/m 2026, 2024 até 2026
Validity starts ab 2025, gültig ab 1. Januar 2025, à compter du 1er janvier 2025, a partir de 2025, a decorrere dal 2025, met ingang van 2025, with effect from 1 April 2025, w.e.f., from 1 April 2025
Unchanged values unverändert seit 2024, inchangé depuis 2024, sin cambios desde 2024, invariato dal 2024, ongewijzigd sinds 2024, inalterado desde 2024

Citations whose year is the year of the enactment, not of the value, are ignored:

  • numbers with a slash after a number mark or enactment word: Gesetz Nr. 12/2025, Loi n° 2024-1234, Real Decreto 1/2025
  • No. 30 of 2025, Act 43 of 1991, (30 of 2025) and margin notes 30 of 2025.
  • enactment titles with their year: Finance Act, 2025, Income-tax Rules, 1962, INCOME-TAX ACT, 2025
  • gazettes: BGBl. I 2025, BOE 2025, Stb. 2025, G.U. 2025
  • enactments with their date: Gesetz vom 23. Dezember 2024, Lei nº 15.191, de 11 de agosto de 2025, décret du 30 décembre 2024

A date after a validity phrase stays a validity start, not a citation.

Tax years. A manifest whose validFrom is not 1 January covers a tax year with the start year of validFrom (2025-04-01 → tax year 2025; a July start works the same way); referenceYear is the start year too. In such a manifest periods are rated: 2025-26, 2025/26, 2025-2026, 2025 to 2026, FY 2025-26, FY26, financial year 2025-26, income year 2025–26, and the assessment year as the following year (AY 2026-27, YA 2026, assessment year 2026-27 = tax year 2025). A period starting in the entry year is positive, a period of another start year is weak. A single year or a year group with the start year or the year after it is neutral (a tax year 2025-26 ends in 2026), any other year is weak. A year with a month belongs to the tax year holding the date: for a tax year from April January 2026 and 31 March 2026 are tax year 2025, April 2026 and 01.04.2026 tax year 2026; a year with a month of the entry tax year is positive, of another tax year weak. In the start month of a tax year starting after the 1st (2026-04-06) only a date with day decides (5 April 2027 is tax year 2026), April 2027 stays neutral. A tax year given by its start date is a period: previous year commencing on 1 April 2025, financial year beginning 1 July 2025 (tax year 2025) and assessment year commencing on the 1st day of April, 2026 (tax year 2025). A validity start up to the start year is neutral as for calendar years. In a manifest from 1 January periods are no years, except two full consecutive years without prefix (2024-2025) which count as a year group.

Scripts. Digits of other scripts (Devanagari, Arabic-Indic, Bengali, fullwidth) and the Arabic decimal and thousands separators and percent signs are mapped to ASCII before the lookup. The mapping keeps the length of the text, so the hit positions and the section names refer to the original text; the normalized text of a source keeps the original script. A four-digit amount with a currency sign is no year: before ($, €, £, ¥, ₹, Rs., R$, CHF, Fr., kr) or after it (2025 €, 2025 EUR, 2025 CHF, 2025 ₹). A middle dot, dot operator or bullet operator between two digits is a decimal point (4⋅85% is 0.0485).

Number formats. Besides plain numbers the lookup reads:

  • magnitudes: a scale word after a number ($150 million, 10 billion) and a scale abbreviation directly after an amount with currency sign ($10m, $1.5m, $2bn, $50k); without currency sign or with a space (10m, $10 m, 10km, 5k run) it is no amount.
  • minor units: a number with a minor unit (91 cents, 88 cents per kilometre, 30 Cent) is the amount times its factor (0.91); the unit may start the next line (a wrapped line). The single letter c is not read, it also labels subsections (2c); per cent is a percentage.
  • written dates: a day, month name and year (1 January 2026, January 1, 2026, 31 March 2027) is the number yyyymmdd (20260101); a date without year or with an invalid day is none. The year of the date is the value, so the date is rated positive. A content written as ISO date (2026-01-01) is not looked up as date.
  • percent columns: in a table with tab-separated cells (HTML, docx, odt) a column whose header is a percent sign or percent word only (Rate (%), Rate [%], in %, Rate in percent) holds percentages, so a row value 12.00 matches 0.12 for the units that read percent signs (empty, rate, mixed). The row must have as many cells as the header and the cell must hold the number only; another header line ends the column. PDF and spreadsheet text has no cell structure: a percent column of such a source needs a sourceQuote or LexAttest.

A newly readable number can stand next to another year (a transitional amount $10m for an earlier year): the year rating then applies to it as to any hit.

Limits: words of a language without language file (Arabic, Hindi, Chinese) are not recognized: add a language file, use the official English version of the source if there is one, otherwise a sourceQuote or LexAttest. Amendment histories ("Amendments 2025 — substituted $6,400") and bare years of a legislative session stay year context.

Tables with more than 40 numbers are sampled evenly. Entries with an autoVerification exclusion are never written (SourceResult.CanWrite). A derived exclusion (Lookup.Key.Property, formula and legal reference as reason) removes the numbers of a computed property from the lookup; the other numbers are verified and the auto record lists the property (Verification.Derived, SourceResult.Derived). A property of a bundle with the value 0 (the rule does not apply, e.g. "DisabilityRate": 0) holds no number to look up: SourceResult.Zero lists these properties. A notApplicable exclusion (Lookup.Key.Property, the reason says why the rule does not apply) documents such a property (SourceResult.NotApplicable); a zero property without it is listed in SourceResult.UnjustifiedZero, so a rate set to 0 by mistake does not stay unnoticed (the checker reports it, a finding in the release mode). ManifestVerifier.VerifyManifest checks all entries of a manifest, inline content and JSON contentFile tables, against the local evidence or a live loader. The local evidence of an entry is its documentRef, otherwise the declared file with the same source URL. EvidenceCheck.UnusedEvidence lists the evidence files that back no entry: a declared file without documentRef, source URL, contentFile or verification evidence pointing to it, and a file in .lex that is not declared in files[]. Such a file is never read, its entries count as without local evidence (the checker reports it, a finding in the release mode). In the release mode an entry without manual verification needs readable local evidence or a source that is readable live: an entry without readable local evidence and without a source URL with text hash in the snapshot (liveSources) can be verified neither locally nor live (CheckResult.NotVerifiable, a finding). A source behind bot protection, a script-only page or a scanned PDF therefore needs a local evidence file (a readable copy, e.g. the official text saved from the browser) or a manual verification.

SourceResult.Location names at most three sections per source. Each source is named by its evidence file, or by the host when the document has no file name (live source): XX-2026-guide.pdf: Sections "Page 24", "Page 25"; XX-2026-limits.pdf: Section "Page 1". A location longer than 500 characters is not proposed. SourceLocation.IsToolLocation recognizes these locations, so /refreshlocations may replace them.

Verification and Open Entries

Each entry can carry a verification record: auto when a tool found the value in the source (SourceVerifier, method and date), manual when a person confirmed it against an evidence document (person, date, evidence). A source with review rule FourEyes requires a second person (reviewedBy, reviewedOn) for manual records.

An entry taken from the previous cycle by Rollover is open ("open": true): it has no verification record until it is verified again, and a new record removes the flag. The checker reports open entries, the applier skips them. The flag is part of the snapshot hash.

Text Tables

Some authorities publish a complete tariff as text file (fixed columns or tab-delimited), often inside a ZIP archive with one file per region. Such a table is the authority file itself: it is not retyped into the manifest, an entry references it with contentFile and converts it with a map in contentMap. The entry key is the lookup name, optionally with an edition tag (TariffA or TariffA.2026):

{
  "files": [
    { "fileName": "tariffs-2026.zip", "sourceUrls": ["https://example.org/tariffs-2026.zip"] }
  ],
  "values": [
    {
      "key": "TariffA",
      "contentFile": "tariffs-2026.zip!tariff-a.txt",
      "contentMap": "tariff.map.json",
      "sourceUrls": ["https://example.org/tariffs-2026.zip"],
      "legalReference": "Tariff ordinance, annex 1"
    }
  ]
}

contentFile addresses a file of the .lex folder or an entry of a ZIP archive there (archive.zip!entry.txt, ContentSource); an archive entry is read in place, never extracted. The archive must be declared in files[]. The map is a JSON file next to lex.json (or a path relative to it) with the columns of the lookup value:

{
  "filters": [ { "start": 0, "length": 2, "values": ["06", "11"] } ],
  "key":        { "valueType": "text",    "start": 6,  "length": 10 },
  "rangeValue": { "valueType": "decimal", "start": 24, "length": 9, "decimalPlaces": 2 },
  "values": [
    { "name": "Code",    "valueType": "text",    "start": 6,  "length": 10 },
    { "name": "TaxRate", "valueType": "decimal", "start": 54, "length": 5, "decimalPlaces": 4 }
  ]
}
Property Content
key or keys Lookup key, or the composite key written to the key values
rangeValue Range value of a range lookup (optional)
value or values Scalar value, or the named properties of the value object
filters Line filters (optional): the trimmed column text must be one of values (case-sensitive); all filters must match

A field has valueType (text, decimal, integer, boolean), start (character index, column index for a tab-delimited line) and length (required for fixed columns). decimalPlaces divides the raw number of a decimal column by 10^n (implied decimals: 00125 with 4 places is 0.0125). The line format is taken from the first lines: a line with a tab is tab-delimited. A line rejected by a filter (header, trailer, other record types) is skipped without warning; a line without key or value is ignored and reported. TextTableMap.Validate lists the structural errors of a map, TextTable.Read converts a stream (UTF-8, a byte order mark selects the encoding). The same classes convert the text file in the LookupTextImport command of the Payroll Console.

Snapshot and verification. The snapshot hashes the text file (for an archive entry the entry content) and the map; the map is copied into the .lex folder when it lies outside. Verifier reports a changed table, a changed map and a missing map copy. LexVerifySource verifies a text table by file identity: the file (or the archive of an archive entry) is declared in files[] with source URLs and present in the .lex folder. No numbers are looked up and nothing is downloaded, also not with a live loader; the auto record has the method LexVerifySource x.y.z; file identity (ManifestVerifier.FileIdentityVerification) and the file as evidence.

Check and apply. LexCheck compares the converted table with the lookup: rows are identified by key, key values and range value; numbers are compared numerically, text case-insensitive. A difference is reported as table <lookup> +added, -removed, ~changed, a duplicate row as problem. LexApply replaces all values of the lookup when the table differs, one value per line. A lookup file that holds lookups only (no wage types, collectors or cases) is written as ZIP archive: Regulation/Lookups.Name.json becomes Regulation/Lookups.Name.zip with the entry Lookups.Name.json (ApplyResult.ReplacedFiles); the references of the regulation package (install files, project file, setup script) are updated by hand. A file with other objects stays JSON. The archive is deterministic (entries in ordinal order, fixed timestamp), so the same table gives the same bytes and a second run changes nothing. RegulationReader reads Regulation/*.json and the JSON entries of Regulation/*.zip; LexApply writes nothing when a JSON file and an archive with the same name both exist.

Range lookups. A new row that LexApply adds to a lookup with a rangeMode other than None gets a rangeValue (ApplyChange.RangeValue, also in the dry-run detail): the key in the format yyyy-MM-dd as the number yyyyMMdd, or the optional rangeValue of the lex entry for another key. A new row with another key and no rangeValue is not guessed: the result carries the error rangeValueMissing (ApplyResult.RangeValueMissing) and nothing is written. The rangeValue of an existing row is never recomputed, so a second run changes nothing. LexCheck reports a value of a range lookup without rangeValue (CheckResult.RangeValueMissing), a finding in the release mode.

Rollover

Rollover.Run copies the satellite of the previous cycle into a new folder for the cycle start: the year tag of folder and file names is replaced (a mid-year edition such as Data.Tax.2026b rolls to Data.Tax.2027), references in the text files are updated, validFrom of manifest and regulation and a year-based version are set, and all entries become open. Build output and snapshot.json are not copied, an existing target is never overwritten. Values are not changed: lines still mentioning the previous year are returned for review (RolloverResult.YearMentions). The cycle start is passed by the caller, e.g. from the payroll calendar of a tenant.

A text table archive keeps its name in the new folder; the contentFile reference is renamed to the new year (tariffs-2026.zip!tariff-a26.txt becomes tariffs-2027.zip!tariff-a27.txt), and a note asks to declare the new archive in files[] and to fetch it. validFrom is also set in the JSON entries of Regulation/*.zip.


Workflow

The Lex commands of the Payroll Console follow the life cycle of a data regulation satellite:

Step Command Library Result
1. Collect sources LexFetch Fetcher Source document in the .lex folder, declared in files[]
2. Document values LexAdd ManifestEditor Entries with source URLs, location and legal reference
3. Verify automatically LexVerifySource ManifestVerifier, SourceVerifier auto verification records for the values found in the sources
4. Verify manually LexAttest ManifestEditor manual verification records for the remaining values
5. Freeze LexSnapshot SnapshotWriter snapshot.json with the hashes of manifest and evidence
6. Verify the snapshot LexVerify Verifier Differences between manifest, snapshot and evidence files
7. Transfer LexApply Applier Lex values written into the lookup values of the regulation
8. Check LexCheck Checker, CheckReport Coverage, value differences and traceability report; release gate
9. Next cycle LexRollover Rollover New satellite folder with open entries, continue with step 2 or 3

A changed value runs through steps 3 to 8 again: a changed manifest no longer matches its snapshot, and LexCheck reports the difference until a new snapshot is written.

Operations

The operations hold the rules of the workflow steps on manifest files and return result models; hosts such as the console or a tool server only present the results:

Operation Rules Result
VerifySourceOperation Verify a manifest file; write the source locations and automatic records of found entries (ambiguous and excluded entries are never written, a manual record is never replaced, refresh replaces tool-written locations only); folder of additional language files from the host variable PAYROLL_ENGINE_LEX_VOCABULARY VerifySourceFileResult, SourceWriteResult
AddEntryOperation Key and content format, existing key, source URL not declared in sources[], document not declared in files[]; empty required fields AddEntryResult
AttestOperation Parameter rules of manual records and reviews (AttestRequest.Test), evidence declared and present; overwrite of a manual record or review AttestationResult
SnapshotOperation Skip an existing snapshot unless overwrite, validation before writing, dry run SnapshotFileResult
ApplyOperation Read and validate the manifest before applying; totals over several manifests; hints for lookup files replaced by a ZIP archive ApplyResult, ApplySummary
RolloverCycle Cycle of the tenant calendar that contains the rollover date (calendar access passed by the host) RolloverCycleResult
// verify and write the locations and automatic records
var vocabulary = VerifySourceOperation.ResolveVocabulary(null, Environment.GetEnvironmentVariable);
var verified = await VerifySourceOperation.VerifyFileAsync(lexPath, vocabulary);
var written = await VerifySourceOperation.WriteAsync(verified, SourceWriteMode.WriteLocations);

// add an entry and attest it
var added = await AddEntryOperation.AddAsync(lexDirectory, entry);
var attested = await AttestOperation.AttestAsync(lexDirectory, new AttestRequest
{
    Key = "Rates.Standard", VerifiedBy = "Jane Doe", Evidence = "tax-rates-2026.pdf"
});

// snapshot (existing snapshot kept unless overwrite) and apply
var snapshot = await SnapshotOperation.RunAsync(lexPath, overwrite: true);
var applied = await ApplyOperation.ApplyFileAsync(lexPath, dryRun: true);

// cycle of the next satellite
var cycle = await RolloverCycle.GetAsync("XX.Test", new DateTime(2027, 1, 1), getTenantId, getCycle);

Lex Packages

A lex package (.lexpkg) delivers the snapshots of the data regulation satellites of one regulation version without lex.json. Namespace PayrollEngine.Lex.Packaging.

Declaration and Pack

The declaration lex-package.json lies next to regulation-package.json of the base regulation. It is read strictly (unknown properties are errors); paths are relative to the declaration and may use \ or /. Schema: https://payrollengine.org/schemas/lex-package/v1.json (embedded, LexPackageDeclaration.SchemaJson; published at build as PayrollEngine.LexPackage.schema.json).

{
  "$schema": "https://payrollengine.org/schemas/lex-package/v1.json",
  "schema": 1,
  "packageId": "Example.Regulation.XX.Lex",
  "version": "2026.1",
  "satellites": [ "Data.Tax.2025", "Data.Tax.2026" ],
  "evidence": "snapshot",
  "license": "LICENSE.txt"
}
Evidence level Content
snapshot (default) snapshot.json, the lookup index regulation-index.json and the content files of each satellite
evidence additionally the evidence documents; a missing document must be listed in omittedFiles with a reason

LexPackageBuilder.PackAsync checks the satellites and writes <packageId>.<version>.lexpkg (default folder nupkgs next to the declaration). The package is deterministic: the same state gives the same bytes (sorted entries, fixed entry time, created is the latest snapshot time). Rules (LexPackRule): the snapshot must match lex.json and the .lex folder, no open entries, no credentials in the snapshot (findings never show the value), no links as source (the .lex folder, its files and the license file), path rule and limits, and a published version is never overwritten. The path rule rejects control and format characters (such as direction marks and zero-width characters) besides separators, reserved characters and device names. The content hash of the manifest covers the satellites, snapshots, indexes and content files, not the evidence level: two packages of the same state have the same content hash.

using PayrollEngine.Lex.Packaging;

var packed = await LexPackageBuilder.PackAsync(new LexPackOptions { DeclarationPath = declarationPath });
if (!packed.Succeeded)
{
    foreach (var finding in packed.Findings)
    {
        Console.WriteLine($"{finding.Rule} {finding.Satellite} {finding.Subject}: {finding.Message}");
    }
}

// read a package without installation: every file against the manifest and the snapshots
using var archive = LexPackageArchive.Open(packed.PackagePath);
var problems = archive.Verify();
var snapshot = archive.ReadSnapshot("Data.Tax.2026");
var index = archive.ReadIndex("Data.Tax.2026");

Package Store

Installed packages live in a package store, by default per user below <LocalApplicationData>/PayrollEngine/packages (PackageStore.DefaultRoot). The store path must be fully qualified and local: UNC and device paths are rejected (PackageStore.ProblemOfRoot). The library reads no environment variable.

<store>/
├── .lock                         # Lock of the installing commands
├── .staging/, .trash/            # Work folders of installations and removals
└── lex/<packageId>/<version>/
    ├── lex-package.json          # Manifest
    ├── installed.json            # Installation record, written last
    ├── LICENSE.txt
    └── satellites/<name>/snapshot.json, regulation-index.json, files/

An installation takes the store lock, extracts into a staging folder with path, size and hash checks and becomes visible by one rename; an aborted installation leaves the store unchanged. The same version with the same content hash and evidence level is checked file by file: unchanged it is AlreadyInstalled and nothing is written; a changed, missing or additional file makes it Repaired — the version is replaced like a level change, and the first difference is the first entry of LexInstallResult.Warnings. Another evidence level is Replaced; the same version with a different content hash, or with an unreadable installed.json, is rejected (uninstall it first). A dry run reports the expected outcome in ExpectedOutcome and writes nothing. A replacement moves the old version to the trash first and moves it back when the new version cannot take its place (for example an open file on Windows), so the previous state stays. Without version, the default version is the highest version without pre-release suffix, otherwise the highest pre-release.

var store = new LexPackageStore(PackageStore.Open(PackageStore.DefaultRoot()));
var installed = await store.InstallAsync("Example.Regulation.XX.Lex.2026.1.lexpkg", "MyTool 1.0", "file");
foreach (var package in store.List())
{
    Console.WriteLine($"{package.PackageId} {package.Version}{(package.IsDefault ? " *" : "")} {package.State} {package.Reason}");
}
var problems = store.Verify(store.Resolve("Example.Regulation.XX.Lex"), includeEvidence: true);
var removed = store.Uninstall("Example.Regulation.XX.Lex", "2026.1");

// read the installed snapshots with the ILexSource answer model
var source = new StoreLexSource(store);
var entries = await source.GetEntriesAsync("Example.Regulation.XX.Lex@2026.1/XX/Data.Tax/2026-01-01");

Comparing Versions

LexPackageDiff.Compare compares two package versions, given as opened package files (LexPackageArchive) or as installed versions (InstalledLexPackage), optionally for one satellite. It reads the snapshots and lookup indexes only, never the evidence documents, so a package at the snapshot level and the same package at the evidence level show no difference. Every list of the result is sorted (ordinal); the same input gives the same result.

  • Satellites by name: Added, Removed, Changed (other source hash, entries, sources or index) or Unchanged. For an added or removed satellite the lists hold everything it contains.
  • Entries by key: Added, Removed or Changed; Fields names the changed fields among content, contentFile, contentMap (the file hash, not the file name), unit, sourceUrls, sourceLocation, sourceQuote, referenceYear, legalReference, documentRef, verification and open.
  • Sources by URL: Added, Removed or Changed (description, legal basis, review rule, official flag).
  • Lookup index: added and removed lookups (Key is null) and value keys.
using var a = LexPackageArchive.Open("Example.Regulation.XX.Lex.2026.1.lexpkg");
using var b = LexPackageArchive.Open("Example.Regulation.XX.Lex.2026.2.lexpkg");
var diff = LexPackageDiff.Compare(a, b, satellite: "Data.Tax.2026");
foreach (var entry in diff.Satellites.SelectMany(x => x.Entries))
{
    Console.WriteLine($"{entry.Kind} {entry.Key} {string.Join(", ", entry.Fields)}");
}

// installed versions
var changes = LexPackageDiff.Compare(store.Resolve("Example.Regulation.XX.Lex", "2026.1"),
    store.Resolve("Example.Regulation.XX.Lex", "2026.2"));

An unknown satellite name throws ArgumentException; a version that is not in state Ok, or a file that differs from the manifest, throws PackageFormatException.

Server Packages

A server package (.mcppkg) holds a self-contained server program for one platform with its profiles (ServerPackageManifest, ServerProfile). Its content hash covers the platform, the entry point, the profiles (name and file) and every file. ServerPackageStore installs it below <store>/mcp/ with the same mechanics and rules (Installed, AlreadyInstalled, Repaired); the store must not be on a network drive. InstallAsync returns a ServerInstallResult with the outcome, the manifest, the version folder, the expected outcome of a dry run and the warnings. ServerPackageManifest.VerifyInstallation is the self-test of an installed server; a server that fails it is repaired by installing the same package again.

var servers = new ServerPackageStore(PackageStore.Open(PackageStore.DefaultRoot(), rejectNetworkDrive: true));
var result = await servers.InstallAsync("Example.Mcp.Server.1.3.1.linux-x64.mcppkg", "MyTool 1.0", "file");
if (result.Outcome == PackageInstallOutcome.Repaired)
{
    Console.WriteLine($"Repaired {result.Directory}: {result.Warnings[0]}");
}

Project Structure

PayrollEngine.Lex/
├── Lex/                          # Library source
│   ├── Manifest.cs, Entry.cs, ...    # Manifest and snapshot model
│   ├── Validator.cs, Schema.cs       # Validation, lex.schema.json (embedded resource)
│   ├── ManifestEditor.cs, Fetcher.cs # Editing of lex.json, download of sources
│   ├── SnapshotWriter.cs, Verifier.cs # Snapshot creation and verification
│   ├── Checker.cs                    # LexCheck: CoverageCheck, ValueComparer, TraceabilityCheck, EvidenceCheck
│   ├── CheckReport.cs                # Markdown and CSV report
│   ├── ManifestVerifier.cs           # LexVerifySource: SourceVerifier, YearAnalyzer, EntryNumbers, SourceLocation
│   ├── SourceDocument.cs             # Source readers: HtmlReader, PdfReader, SpreadsheetReader, OfficeXmlReader
│   ├── LanguageSet.cs                # Language profiles of the source verification
│   ├── TextTable.cs, TextTableMap.cs # Text tables: conversion and map, ContentSource (archive entries)
│   ├── Applier.cs, RegulationReader.cs # LexApply and reading of the regulation lookups (JSON and ZIP)
│   ├── TableComparer.cs, ArchiveWriter.cs # Table differences, deterministic ZIP archives
│   ├── Rollover.cs, RolloverCycle.cs # LexRollover
│   ├── *Operation.cs                 # Workflow operations with result models
│   ├── SnapshotLexInfo.cs            # Snapshot mapped to the ILexSource answer model
│   ├── Packaging/                    # Lex and server packages, package store, StoreLexSource
│   ├── lex-package.schema.json       # Schema of the package declaration (embedded resource)
│   └── LexVocabulary/                # Language files
├── Lex.Tests/                    # Unit tests
├── Directory.Build.props         # Shared build properties
├── PayrollEngine.Lex.sln         # Solution file
└── README.md

Data Regulation Layout

The checks expect the manifest in a .lex folder next to the Regulation folder of the data regulation:

Data.Tax/
├── .lex/
│   ├── lex.json                  # Manifest
│   ├── snapshot.json             # Snapshot (created by SnapshotWriter)
│   ├── *.map.json                # Text table maps
│   └── *.pdf, *.xlsx, *.zip, ... # Evidence files, text table archives
└── Regulation/
    ├── *.json                    # Regulation with lookups
    └── *.zip                     # Large lookups as ZIP archive (written by LexApply)

Usage

using PayrollEngine.Lex;

// structural validation
var errors = Validator.Validate(manifest, lexDirectory);

// snapshot: create and verify
var snapshot = await new SnapshotWriter().WriteAsync(manifest, lexDirectory, lexDirectory, dryRun: false);
var differences = Verifier.Verify(manifest, snapshot, lexDirectory);

// check against the regulation lookups
var result = Checker.Check(manifest, lexPath, requireLocation: false, requireVerification: false);
CheckReport.Write([result], "LexCheck.md");

// release gate: verify the entries against the local evidence
var release = Checker.Check(manifest, lexPath, requireLocation: true, requireVerification: true, release: true);
await Checker.CheckSources(manifest, release);

// look up the numbers of all entries in the local evidence
var results = await ManifestVerifier.VerifyManifest(manifest, lexDirectory);

// write the lex values into the regulation lookups (dry run: differences only)
var applied = Applier.Apply(manifest, lexPath, dryRun: true);

// convert a text table with its map
var map = TextTableMap.Load("tariff.map.json");
await using var stream = File.OpenRead("tariff-a.txt");
var table = TextTable.Read(stream, map);

// download a source document into the .lex folder; lex.json and snapshot.json are refused
// (ReservedFileNameException), as is a target that is a link out of the .lex folder (FetchTargetLinkException)
using var client = SourceDocument.CreateHttpClient();
var fetched = await Fetcher.FetchAsync(client, "https://example.org/tax-rates-2026.pdf", lexDirectory);

// next cycle: new satellite folder with open entries
var rollover = Rollover.Run(satelliteDirectory, new DateTime(2027, 1, 1), dryRun: false);

Editing lex.json

ManifestEditor changes the manifest document in place and keeps everything it does not touch:

var editor = ManifestEditor.Parse(await File.ReadAllTextAsync(lexPath));
editor.AddValue(new Entry
{
    Key = "Rates.Standard", Content = "0.081",
    SourceUrls = ["https://example.org/rates", "https://example.org/rates-notice-2026.pdf"]
});
editor.SetManualVerification("Rates.Standard", new Verification
{
    Mode = "manual", VerifiedOn = "2026-11-03", VerifiedBy = "Jane Doe", Evidence = "tax-rates-2026.pdf"
}, overwrite: false);
await editor.SaveAsync(lexPath);

Removing is mechanical in the editor; the caller plans it from the references first. ManifestReferences answers which entries an exclusion concerns, which exclusions concern an entry, which entries list a source URL, whether other entries use the same evidence document and whether an entry backs a regulation value:

var manifest = JsonSerializer.Deserialize<Manifest>(json, options);
var (all, exclusive) = ManifestReferences.ExclusionsOfEntry(manifest, "Rates.Old");
var link = ManifestReferences.RegulationLinkOf(manifest, lexPath, "Rates.Old");
if (!link.Linked)
{
    editor.RemoveEntry("Rates.Old");
    foreach (var exclusion in exclusive)
    {
        editor.RemoveExclusion(exclusion.Kind, exclusion.Pattern);
    }
}
editor.UpdateExclusion("orphan", "Legacy.*", new ExclusionUpdate { Reason = "Corrected reason" });
editor.RemoveSource("https://example.org/old");   // throws while an entry still lists the URL

An entry that backs a regulation value is not removed by a tool: the value is changed in the regulation, never silently dropped. An evidence file that no entry uses any more stays in files[] and in the .lex folder (the check reports it as unused evidence).

Source Documents

SourceDocument detects the format from the content, not from the file extension or the media type, and splits the text into sections:

Format Sections
HTML One per document heading; a table row is one line with tab-separated cells (paragraphs, line breaks and lists inside a cell are spaces, a table inside a cell is read as its own table)
Text (.txt, .csv) One section
Spreadsheets (.xls, .xlsx, .xlsb, .ods) One per sheet, numbers in invariant format
PDF One per page (text layer), plus the values of the form fields
Text documents (.docx, .odt) One per heading; a table row is one line

A PDF without text layer (scan) or with a user password is unreadable — there is no OCR. Other binary content is unsupported. Readers for further formats are passed by file extension; a passed reader replaces the built-in reader of the same format. A reader returns the text sections of the document:

var readers = new Dictionary<string, Func<Stream, List<(string Heading, string Text)>>>
{
    [".rtf"] = MyRtfReader.Read
};
var sources = new List<(string Url, SourceDocument Document)>();
foreach (var url in entry.Urls)
{
    sources.Add((url, await SourceDocument.LoadLive(url, httpClient, readers)));
}
var match = SourceVerifier.Verify(entry, sources);

NuGet Package

dotnet add package PayrollEngine.Lex

Build

Environment variable used during build:

Variable Description
PayrollEnginePackageDir Output directory for the NuGet package (optional)

License

This project is licensed under the MIT License. Third-party components and their licenses are listed in THIRD-PARTY-NOTICES.md.


See Also

  • Payroll Console — Lex commands built on top of this library
  • Core — Payroll Engine core library

About

Payroll Engine Lex library: provenance of compliance values in data regulations — lex.json manifests, hashed snapshots, verification and checks against regulation lookups.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages