For a file-by-file map, the prompts and the runtime flows, see DEVELOPER-GUIDE.md.
Modules and dependencies
┌──────────────┐ ┌──────────────┐
│ DzLegal.App │ Avalonia desktop shell │ DzLegal.Web │ Blazor Server web demo
│ (offline) │ + ModelProviders.Ollama │ (public demo)│ + ModelProviders.Hosted
└──────┬───────┘ └──────┬───────┘
└──────────────┬─────────────────────────┘
▼
DzLegal.Presentation view models, .resx strings (CommunityToolkit.Mvvm, no UI framework)
┌─────────────┬────┴─────────┬───────────────┬──────────────┐
▼ ▼ ▼ ▼ ▼
FormEngine Drafting ModelProviders.Stub Storage Documents, Law, (data/ folder)
│ │◄─────────────┘ │
└──────┬──────┘ │
▼ │
DzLegal.Domain ◄───────────────────────────┘
The desktop app and the web demo share everything below them; only the shell and the model provider differ. The desktop never references the hosted providers (OFFLINE.md, WEB-DEMO.md).
-
Domain holds the records (
DocumentTypeDefinition,RequiredElement,RuleCheck,DraftDocument,ComplianceReport) andDefinitionLoader, which parses and validatesdefinition.json. It checks for unknown fields or sections, duplicate ids, bad regexes and missing template files, so a broken data edit fails at load time and in CI. -
FormEngine is a single pure function,
ComplianceChecker.Check(definition, draft) → report. It has no I/O, no AI and no clock, which makes it deterministic and fast enough to run on every keystroke. -
Drafting:
DraftingService.DraftAsyncrenders the generated sections from Scriban templates and asks anIModelProviderto write the narrative sections.DraftOptions.KeepNarrativekeeps sections the lawyer edited;DraftSectionAsyncredrafts one section;OnPartialstreams text as the model writes it (IModelProvider.StreamAsync, which Ollama implements withstream: true).SectionReviser.ReviseAsyncasks the model to edit one section following the lawyer’s instruction (prompts/revise.ar.txt). The proposal goes through the same cleaning, corrections andNarrativeChecksas a draft (numbers in the instruction count as known), is retried once on a hard failure, and is flagged as a refusal when the model returns the fixed «خارج نطاق التعديل» line.TextDiffproduces the word-level diff shown for review. Nothing is applied until the lawyer accepts.- Selected articles:
DraftOptions.LegalTexts,DraftSectionAsync(..., legalTexts)andSectionReviser.ReviseAsync(..., legalTexts)carry the official texts of the articles the lawyer ticked. Prompts receive them aslegal_texts.NarrativeChecksreportsUncitedArticle(an article neither in the notes nor ticked) andMisquotedArticle(a «…» quote that isn’t in the ticked article’s text). Both count as invented law, which earns one retry. Refreshre-applies form changes without calling the model and keeps the lawyer’s narrative edits.BuildRequestexposes the exact prompt for inspection and tests.
-
NarrativeChecks (in Drafting) checks model text against the lawyer’s material:
- foreign-script characters, a hard failure;
- numbers not found in any input, such as an invented amount, date or article;
- numbers from the notes that the text dropped;
- Latin-script words found in no input (for example «caso»);
- text that is mostly not Arabic (for example English reasoning), a hard failure.
Month names (جانفي، يناير، janvier…) count as their numbers, so «15 جانفي 2025» matches
15/01/2025. Wording that appears in the prompt’s instructions (for example «في الشكل: قبول الدعوى شكلا») never counts as copying the example.Paragraphs that copy the prompt’s worked example are removed first. Detection uses the example’s placeholder tokens such as «(س)», or near-verbatim overlap.
DraftAsyncthen retries an empty or hard-failing answer once, falls back to the notes verbatim, and records each step inDraftSection.DraftingNotes. The app re-runs the checks on every edit and shows them as review hints under the section. They cannot detect meaning-level errors such as swapped roles, which remain the lawyer’s review. -
ModelProviders:
StubModelProvider(template mode) andOllamaModelProvider(loopback-only HTTP to a local Ollama, streaming NDJSON, andGetInstalledModelsAsyncover/api/tagsfor the status dot). Adding llama.cpp or another runtime means one new class implementingIModelProvider. -
Documents:
DocumentLayoutBuilderturns a draft into print blocks, using the per-sectionlayoutdata.PdfRenderer(QuestPDF) produces an A4 right-to-left PDF with the embedded Naskh font, and the page images used by the in-app preview, so the preview is exactly the PDF.DocxRenderer(Open XML SDK) produces an editable, schema-valid right-to-left.docx.- Fonts live in
assets/fonts/and are shared by the app and the PDF engine.
-
Law (
DzLegal.Law): the offline law library.LawLibraryLoadervalidatesdata/law/codes/*.json.LawTextParsersplits an official text into articles (headings, «مكرر» numbers, reversed PDF text, repealed markers) and reports gaps for review.LawDiffcompares two imports.ArabicScript.NormalizeandArabicScript.Tokensin Domain give the shared Arabic normalisation used for matching. The importer itself (law importin the Harness) is the only code that downloads anything, and only at development time. See LAW-LIBRARY.md. -
Grounds analysis:
LegalKnowledgeLoader(Law) loads the source manifest, the imported codes, the claim catalog and the analysis prompts, and checks them against each other.ArticleIndex(Law) is a BM25 full-text index over the in-force articles, with chapter headings weighted ×2.GroundsAnalyzer(Drafting) runs three stages: the model reads the facts (prompts/read-facts.ar.txt), the index and the catalog supply candidates, and the model chooses among them by key (prompts/select-articles.ar.txt). Its parsers keep catalog ids and candidate keys only.- The result,
GroundsAnalysis, is saved in the draft together with a hash of the facts, so the app can tell when it is stale. LegalKnowledge.ProvenanceOfsupplies the official reference, location and source link. Links are restricted toOfficialLinkshosts and opened only on click, throughIExternalLinks.- In the app,
MainWindowViewModel.Grounds.cskeeps the ticked articles (DraftDocument.SelectedArticles).DraftingInputs()adds their citations to the grounds notes sent to the model, andSelectedLegalTexts()gives the model their official texts.
-
Storage: drafts (
*.dzdraft.json) and evaluation records as local JSON under the user’s local app-data folder. -
Harness has two modes:
- Its default mode loads the corpus, runs the Form Engine, and prints per-element accuracy, precision and recall. The same logic runs as a test.
- The
draftmode is a model-comparison bench overtests/drafting-cases/.
Data flow
- Since rules v0.3.0, facts are a generated section. Each line of the lawyer’s facts notes becomes «حيث إن …» or «وحيث إن(ه) …» through the
whereastemplate helper. Benchmarks showed 3–4B models reversing who lent and who borrowed. - The case form is generated from
fieldsindefinition.json. Values are strings keyed by field id (for exampleplaintiff.domicile). Visibility follows each field’svisibleWhenconditions. - On every form change,
Refreshre-renders the generated sections (court, parties, subject, publication, opening, documents, date, signature). Sections with anincludeWhencondition, such as land-registry publication, appear or disappear. - Draft narrative sections sends one request per narrative section. Each request is the system prompt (rules: no invented facts, amounts or citations; formal Arabic; text only) plus the section prompt with the lawyer’s notes embedded. Output is cleaned (
<think>blocks, Markdown, a repeated heading). Empty notes mean no model call, so the section stays empty and gets flagged. - Narrative sections are freely editable, and the section assistant proposes edits as a diff to accept or reject; each section keeps an undo history. Re-drafting skips sections the lawyer edited. Generated sections are read-only in the editor and change through the form. This keeps what the lawyer sees identical to what the Form Engine checks.
- After every change the Form Engine produces a report. Missing mandatory elements are listed first, then warnings, then present and not-applicable elements.
The rule model
Each RequiredElement has:
- an
idand anarticle(the legal reference); - a
severity:inadmissibleorwarning; appliesWhenconditions;- bilingual
labelandmissingMessage; verifiedandsourceNote;- a
checkbuilt from a closed set of kinds:
| kind | passes when |
|---|---|
fieldsPresent |
every listed input has a non-blank value |
sectionNotEmpty |
the section exists and has text |
sectionMatches |
the section text matches a regex (for example a date) |
sectionOrder |
the listed sections that are present appear in this order |
predominantlyArabic |
at least minRatio of the letters are Arabic script (CPCA art. 8), so inline French terms and Latin names are tolerated |
allOf / anyOf |
composition (for example domicile or last known domicile) |
The check set is deliberately small. Anything new should be a new kind with unit tests, never logic hidden in the UI.
Key decisions
| Decision | Why |
|---|---|
| .NET 10 LTS + Avalonia 12 | Matches the product owner’s C# skills. Cross-platform, and builds and tests headlessly on Linux CI. .NET 8 support ends Nov 2026. |
| Generated vs narrative sections | Legally critical identification data comes straight from the form, deterministically. The model only rephrases notes, which limits hallucination. |
| JSON files, not SQLite | Drafts and evaluations are small documents; JSON is human-readable, diff-able and easy to back up. SQLite can come later if querying is needed. |
| Scriban templates | Readable by non-developers, with conditionals for legal-person or real-property variants, and offline. |
| Bundled Noto Naskh Arabic | Consistent Arabic shaping on every machine with no font download. |
| Document and inputs always RTL | Even with the English UI, Arabic content with embedded names and numbers must lay out correctly. This is covered by a bidi hit-test test. |
| Official texts typed, then proved against the PDF | The official PDFs extract badly (ك encoded as آ, split words, ligature fonts). Typing the articles and proving their letters and digits against the PDF gives clean text with a mechanical guarantee that no word was changed. A lawyer still checks each article. |
| Deterministic before AI | The articles a claim type requires are proposed by the catalog, not by the model. Quotes and statements of what an article provides are checked against its text. Substance checks are rules tied to articles. The model writes; it does not decide the law. |
| Web demo on Blazor Server, one instance | The demo reuses the desktop’s view models unchanged, so the judges use the real product logic. One instance keeps the queue and limits exact; the visitor’s case is kept in their browser, so a restart loses nothing. The cost is a socket per visitor, which suits a demo. |
Testing
DzLegal.FormEngine.Tests: every check kind; definition validation; one test per corpus case; whole-corpus 100%; every element exercised as missing at least once; the harness detects a wrong expectation.DzLegal.Drafting.Tests: template model; grounding (prompt contents, no call without notes); refresh semantics; output cleaning; keep-edits and single-section redraft; the reviser (checks, retry, refusal) and word diff; Ollama streaming and model listing;LoopbackGuard; the Ollama client against a fake HTTP handler.DzLegal.App.Tests: the whole loop through the view model; headless Skia rendering for the RTL layout, language switch and bidi ordering. SetDZLEGAL_SCREENSHOTS=<folder>to save screenshots.