For AI agents: the complete documentation index is available at https://canary.gukhanmun.org/llms.txt, the full documentation bundle is available at https://canary.gukhanmun.org/llms-full.txt, and this page is available as Markdown at https://canary.gukhanmun.org/internals/design.md.

Gukhanmun design docs

Gukhanmun is a library for converting Korean text written in mixed script (國漢文混用體) into hangul-only text. It is the successor to Seonbi, narrowed in scope to the hanja conversion pipeline and broadened along several axes: streaming I/O, pluggable dictionaries, lattice-based segmentation, and a wider range of output formats. The project is implemented in Rust and exposed as a Rust library, a command-line tool, WebAssembly bindings, Node-API bindings, and Python bindings.

Goals and non-goals

The library converts hanja words in Korean text into their hangul readings, optionally annotating them with the source hanja for disambiguation, ruby markup, or stylistic reasons. It does so without disturbing structure or content outside the text it is asked to transform; regions marked as non-Korean or as preserved (code blocks and the like) pass through untouched. It streams input and output where possible, with buffering bounded by the size of contiguous conversion spans that contain hanja and by opt-in cross-context disambiguation. It accepts pluggable dictionaries that may be in-memory, mmap-backed, or otherwise opaque to the engine. It ships default dictionaries derived from the National Institute of Korean Language's Loanword spelling examples and Standard Korean Language Dictionary (標準國語大辭典). It is usable from Rust, from Python, from Node.js via Node-API, from browsers and Deno via WebAssembly, and from a command line.

The library provides opt-in output profiles for commas, periods, and explicit citation delimiters. The default preserves punctuation. Broader typographic adjustments such as inferring quotes from ASCII substitutes, dashes, and ellipses remain Seonbi's job. It does not provide a fully HTML5-conformant parser; the HTML scanner is fragment-oriented and recovers from minor malformations but is not a substitute for html5ever. It does not roundtrip Markdown byte-for-byte; semantic preservation is the contract, and original-form preservation is best effort. It does not translate between languages or transliterate beyond the hanja-to-hangul mapping.

Design principles

Three principles run through the design.

The engine is format-neutral. The same engine processes HTML, Markdown, and plain text because each format is read into a single intermediate representation and written back from it. Adapters at the boundary handle format specifics: scanning, serialization, and the format-specific notion of what counts as a preserved region or a block boundary. The engine never inspects HTML tag names, Markdown event variants, or anything else that would couple it to one format. This is what makes a single test fixture meaningful across all three formats, and what makes adding a new format a contained piece of work.

Responsibilities are split into independently selectable pipeline stages. The Reader parses an input format into the IR. The Engine finds hanja-containing lexical spans, segments them, and emits annotations. Middlewares transform the IR stream by adjusting annotation flags. The Renderer turns annotations into concrete text or markup. The Writer serializes the IR back to the target format. A user replacing one stage does not perturb the others; the boundaries are explicit values, not method calls.

Streaming is the default where correctness allows it. Operations that fundamentally require lookahead buffer until the relevant context boundary. In HTML and Markdown, the default per-block homophone window usually reaches that boundary at paragraphs, list items, headings, and similar scopes. Plain text has no block scopes, so the same default window is document-wide: an annotation on a later line can force disambiguating hanja on an earlier line, and a byte stream cannot revise text already written to stdout. Callers that require immediate plain-text output can disable homophone marking, accepting the corresponding loss of disambiguation.

Streaming conversion also preserves fallback annotation spans exactly. A trailing run of fallback hanja is held until a following non-convertible boundary or EOF, even when the dictionary's maximum word length is shorter. This can make fallback-only hanja input less eager than dictionary lookahead alone would require, but it keeps render modes such as hangul-hanja-parens equivalent to one-shot conversion.

Architecture

The pipeline has five stages.

A reader parses bytes into a stream of input tokens. The engine reads input tokens and emits output tokens, with the difference that output tokens may include annotation tokens carrying both an original hanja form and its hangul reading. Middlewares walk the output stream and adjust the flags on those annotations. The optional punctuation middleware then normalizes ordinary text without changing annotation payloads. The renderer expands each annotation into concrete text or markup according to the flags and the chosen rendering mode. The writer serializes the final stream into the output format.

Intermediate representation

The intermediate representation is a flat stream of tokens parameterized by a scope data type that belongs to the adapter rather than the engine. The engine knows the shape of a token, but the contents of the scope payload (raw HTML attributes, the variant of a pulldown-cmark event, and so on) are opaque to it.

The token sent into the engine is one of:

  • Open(Scope<S>): enter a structural scope, such as an HTML element or a Markdown block. The Scope<S> carries the adapter's opaque data plus three pre-computed flags described below.
  • Close: leave the most recent scope. The engine maintains the stack itself; the adapter does not have to repeat which scope is closing.
  • Text(Cow<str>): a chunk of text that the engine may transform.
  • Verbatim(Cow<str>): a chunk of text that must pass through untouched, such as the contents of an HTML <code> element or a Markdown code span. The adapter, not the engine, decides what is verbatim.

The token coming out of the engine is one of:

  • Open(Scope<S>), Close, Text(Cow<str>), Verbatim(Cow<str>): the same forms, passed through.
  • Annotated(Annotation): a position in the stream where the engine converted a hanja word. The annotation carries the original hanja, the canonical dictionary spelling when one matched, the hangul reading, and flags describing why the conversion happened and what subsequent stages might want to do with it.

The Annotation carries policy flags. homophone is set when the effective dictionary entry set or the active context indicates another hanja word shares this hangul reading, so a reader of the rendered output cannot recover the word from hangul alone. require_hanja is set when the source dictionary or a user directive demands the original hanja be shown alongside the hangul. require_hangul is set in the opposite direction: the source preserves the hanja in the output, but a hangul gloss is required (used for the Original rendering mode that keeps mixed script as the default presentation). skip_annotation is set by user directives that want the renderer to emit only the primary plain text form. first_in_context is set when this is the first occurrence of the hanja word within the current context window, where the window is a block, a section, or the document depending on configuration. from_dictionary distinguishes a dictionary match from a character-by-character fallback; renderers may choose to mark these differently for debugging.

dictionary_hanja is Some for dictionary-backed annotations and None for fallback annotations. Variant spellings retain the source in hanja, while middlewares use the canonical spelling as lexical identity and renderers use it as the input to their variant set.

The split between InputToken and OutputToken is the most consequential shape decision in the IR. The alternative we considered was a single Token enum that includes Annotated from the start, with adapters emitting Annotated only as a future possibility. We rejected it for two reasons. First, it would force the input-side Annotated variant to remain a no-op throughout the reader and engine, polluting every match in the codebase with an unreachable arm. Second, it would obscure the contract that the engine produces annotations and renderers consume them. Two distinct types make the dataflow legible at a glance and let the type system enforce that an unrendered annotation cannot reach a writer.

Scope data

The opaque scope payload obeys a small trait:

pub trait ScopeData: Clone + 'static {
    /// Should text inside this scope be left alone?
    fn is_preserve(&self) -> bool;

    /// May the renderer insert inline markup, such as a `<ruby>` element,
    /// inside this scope?
    fn allows_inline_markup(&self) -> bool { true }

    /// Does this scope mark a boundary at which per-block middlewares reset?
    fn is_block_boundary(&self) -> bool { false }

    /// How may punctuation and space lookahead interact with this scope?
    fn punctuation_boundary(&self) -> PunctuationBoundary {
        if self.is_block_boundary() {
            PunctuationBoundary::Block
        } else {
            PunctuationBoundary::Opaque
        }
    }
}

The engine treats the current scope's is_preserve() as the single point of truth for whether to skip a Text token. Adapters that need inheritance encode the effective answer in each opened scope. The HTML adapter's ScopeData implementation aggregates several concerns into that one flag: the inherited lang attribute compared against a Korean predicate, the current tag and preserved ancestors (against the preserved-tag list of pre, code, kbd, script, style, and textarea), and any user-supplied predicate over raw attributes. The engine itself does not know what a lang attribute is.

This is a departure from Seonbi, which threads a parallel LangHtmlEntity annotation through the pipeline. We removed it because the engine never needs both signals separately; it only ever asks the single question, is this text skipped? Pushing lang inheritance into the adapter (where the tag-name preservation list already lives) keeps the engine ignorant of HTML and keeps the IR free of fields the engine does not consume.

Engine

The engine has three duties: identify convertible lexical spans that contain hanja, segment those spans into dictionary and fallback edges, and emit annotations and fallback text accordingly. Most spans are contiguous runs of hanja, but dictionary entries may also include Korean native or hangul fragments around hanja, as in 汽車길 or 色깔論. It also has a fallback phoneticizer that maps single hanja characters to hangul and applies the initial sound law where appropriate, and a numeral converter that translates hanja digits to either hangul or Arabic numerals depending on configuration.

Lattice segmentation

Segmenting a hanja-containing span into dictionary words and fallback fragments is the engine's core decision, and the obvious algorithm is wrong.

The obvious algorithm is eager longest-match: scan left to right, at each position take the longest dictionary entry that starts there, and continue from its end. This is what Seonbi does. Its failure mode is mis-segmentation when a longer prefix consumes characters that belong to a more natural split. Consider a dictionary containing 行事, 行事場, 場所, and 入口. On the input 行事場入口, eager segmentation produces 行事場 + 入口, which is correct. On the input 行事場所, eager segmentation produces 行事場 + 所, which leaves 所 to the character-by-character fallback even though the segmentation 行事 + 場所 would have covered both segments with the dictionary.

The span is not limited to hanja-only text. Some entries in the Standard Korean Language Dictionary mix native Korean and hanja, such as 汽車길 for 기찻길, 祭祀날 for 제삿날, 洗手대야 for 세숫대야, 火김 for 홧김, and 色깔論 for 색깔론. A dictionary edge may therefore consume a mixed-script prefix from the current text cursor. Fallback edges, however, are still created only for hanja characters that no dictionary edge covers; hangul that is not part of a dictionary match passes through as ordinary text.

The correct algorithm is dynamic programming over a lattice. For each character position i in the conversion span, the engine queries the dictionary for every match that starts at i and considers a single-hanja fallback edge as a backup when the current character is hanja. Arabic numeral strategies also add a plain-text numeral edge when a numeral starts at i. A ranking function compares the alternatives; we choose the best segmentation by Viterbi-style backtracking from the end of the span.

The ranking function is deliberately simple. It first minimizes the number of characters left to fallback, so 行事 + 場所 beats 行事場 + 所 because the former leaves no fallback. Among paths with the same fallback coverage, Arabic numeral edges are preferred over dictionary matches when the configured numeral strategy produces them; this is what lets a dictionary calendar entry such as 六月 normalize to 6월. After that, the segmenter maximizes dictionary coverage and then prefers fewer segments, so a whole-word match such as 天地 beats the component split 天 + 地. Remaining ties are kept deterministic by preserving the first candidate that reached the same score.

The cost of lattice segmentation is bounded by the conversion-span length times the maximum dictionary entry length. In normal Korean text, spans that contain hanja are short: most are one to four characters, almost never more than ten, except for rare mixed-script dictionary entries. The dictionary's maximum entry length is on the order of ten characters. The per-span runtime is therefore tens of dictionary lookups, which the FST and CDB backends handle in microseconds.

An eager segmentation strategy remains available as an option for callers who do not need lattice accuracy and want to reduce per-span overhead. The default is lattice.

Source phrase constraints

The bundled Standard Korean Language Dictionary also supplies phrase evidence for choosing among a word's retained readings. The extractor compiles strictly aligned source phrases into PhraseEvidence; it does not insert whole phrases as TSV keys or change the default preference of their component words. For example, 無條件^降服 can constrain the existing 降服 edge to 항복 while leaving bare 降服 on its legacy selection path.

The resolver runs after the lattice or eager path is fixed. It cannot split, join or add edges, and it does not change segmentation scores. Each source chunk matches either its complete hanja spelling, including a recognized glyph variant, or its complete attested hangul reading. A caret boundary permits zero characters or exactly one U+0020 space. Repeated spaces, tabs, newlines and punctuation cannot replace that internal separator. Dictionary chunks must cover whole selected edges. Literal hangul chunks can cover adjacent unchanged text segments, but cannot absorb dictionary, numeral or fallback edges. Outer word boundaries prevent matching a literal substring inside another word; a supported particle with its own boundary witness can follow a dictionary terminal chunk.

A terminal extension applies only through a compiled word-to-subheadword relationship and complete child candidate links. This permits a source phrase ending in 降服 to constrain an existing 降服하다 edge when that exact relationship is attested. It does not infer a productive suffix or split an unrelated longer word.

Every participating dictionary chunk must have an eligible candidate from the leaf source that owns the rule. A higher-priority user reading cannot acquire lower-priority evidence merely by sharing a key. For phrase proof, nested chains preserve complete choice eligibility, including reference-only exclusions and previously authorized forms. Rule links constrain both the original anchor and the complete attested initial/suffix output pair. A promoted form with a different pair cannot satisfy that phrase. The selected choice retains its complete identity and marks. Thus 車間距離 can use 차간거리 while bare 車間 retains the policy's redirect default 찻간.

The resolver validates each rule atomically, then intersects valid restrictions per target edge with witnessed particle compatibility. When the remaining choices agree on form, lexical identity, alias and marks, the resolver selects the first in the existing rank order. If distinct choices remain, if the intersection is empty, or if a matcher limit is reached, the resolver keeps the legacy particle-aware choice and can produce an opt-in ResolutionReport. Conflicts remain local to the affected edge; overlapping rules do not create an unbounded chain of pending decisions. This is source phrase matching, with no frequency prior or general semantic inference.

Rules from different leaf sources can agree when their directly witnessed choices have the same complete form, lexical identity, alias and marks. After intersecting those agreements, the resolver selects only currently eligible choices directly witnessed by at least one applicable rule. An unwitnessed duplicate gains no phrase authority from semantic agreement alone.

For Ordered and cooperating policies alike, the engine preserves legacy parent selection over each child's public canonical projection, including particle evidence. The separate leaf proof pool may be wider or different. A nested fallback may be an opaque projection at the first slot of the child's SourceId range, with an explicit diagnostic. Such a projection establishes no leaf identity or WordId witness and supplies no phrase authority. Only eligible complete choices from the ranked leaf pool contribute proof; on success, the resolver replaces the whole choice atomically. SelectedReading can therefore retain a fallback outside its proof pool.

Streaming retains a finite additional tail and committed left context derived from the maximum admitted phrase span and boundary/particle lookahead. Ordinary text chunk boundaries preserve that context. A scope open/close, a preserved/verbatim transition or an explicit Engine::flush() ends the phrase flow. Inline markup, preserved/verbatim transitions and explicit flushes do not themselves prove a lexical right boundary. A rule needs a textual witness within its flow, an adapter-reported block boundary or actual EOF; finish() proves EOF. This additional allowance does not bound the whole engine: unresolved lattice frontiers, unknown dictionary maxima, numeral spans, fallback annotation grouping and middleware can retain more input. Reporting is disabled by default; enabled callers can drain it during a stream and obtain EOF decisions with finish_with_report().

Fallback phoneticizer

When no dictionary entry covers a hanja character, the fallback phoneticizer converts the character to hangul by looking up its canonical reading in the embedded Unihan-derived character map. The character map is built from the Unicode kHangul property and embedded in gukhanmun-core as a generated sorted table queried by binary search. It covers thousands of hanja and keeps the default build independent of network access.

For the first character of a word produced by the fallback, that is, the first character of a fallback-only run or the first character after a dictionary match, the initial sound law (頭音法則) optionally applies. The law converts a small set of word-initial hangul syllables that originally began with ㄴ or ㄹ into their South Korean orthography forms (녀 becomes 여, 려 becomes 여, 례 becomes 예, and so on). The conversion table is small (sixteen entries) and lives in gukhanmun-core. The toggle for the law applies only to the fallback; dictionary entries are assumed to encode the correct reading already (a South Korean dictionary stores 來日 as 내일, a North Korean dictionary stores it as 래일).

Two small rules from Seonbi survive in the fallback because they are not learnable from per-character mappings alone. First, the ryeol-ryul rule (列, 律) is treated as part of the initial sound law: when the law is enabled and these characters follow a syllable whose final jamo is ㄴ or absent, their pronunciation glides to 열 or 율 rather than 렬 or 률. When the law is disabled, as in North Korean orthography, they remain 렬 or 률. Second, the hanja-numeral rule: a sequence of two or more hanja digits is read as a single word with the initial sound law applied at its head and not at internal positions. Both rules are encoded as small parsers over the character stream.

Numeral conversion

Hanja numerals are a special case because they can be converted to three different surface forms and the right one depends on context. The library exposes a NumeralStrategy option with four variants:

StrategyExample: 二〇一六年Example: 十一月Example: 一千二百三十四
hangul-phonetic이공일륙년십일월일천이백삼십사
positional-arabic2016년(not applicable)(not applicable)
additive-arabic(not applicable)11월1234
smart2016년11월1234

The hangul-phonetic strategy is Seonbi's behavior and the default for both the ko-kr and ko-kp presets. The command-line interface uses smart as its own default when --numerals is omitted, because CLI output is usually a final human-facing rendering. The positional-arabic strategy treats a digit-only sequence (〇一二三四五六七八九, plus their variants) as positional notation and converts it to Arabic. The additive-arabic strategy parses sequences that contain place markers (十百千萬億兆京) using stack-based accumulation and produces Arabic, handling the Korean convention that 一 is elidable before 十 (十一 means 11, not 一十一). The smart strategy looks at the surrounding context: additive numerals that begin with a digit use additive-arabic, and runs that begin with a small place marker such as 十, 百, or 千 use additive-arabic only when the next character is not an ambiguous non-unit hanja word character. Pure digit runs use positional-arabic when they have length four or more (matching the year convention) or a unit hanja follows (年月日時分秒號世紀 and so on). Standalone large place markers such as 萬 or 京, and small-place-marker words such as 百濟 or 十長生, fall back to hangul-phonetic, which prevents unknown words from being split as numbers.

The hangul-phonetic strategy runs inside the fallback path on segments that the lattice has identified as not matching the dictionary. It emits a fallback Annotated token, preserving the original hanja numeral so renderers such as HangulHanjaParens can still show the source text. Arabic numeral strategies participate in segmentation as plain-text numeral edges, so numeric normalization can win over dictionary calendar entries such as 六月 and 十月. When such an override is tied to a dictionary match whose suffix is only recognized unit hanja, the plain-text edge covers that suffix too and renders it with fallback context; 六月 can therefore normalize to 6월 even when 月 is not a separate dictionary entry. A numeral edge only starts at the beginning of a numeral run, so positional-arabic does not split additive forms such as 十一月 by converting only the trailing 一. A longer dictionary match that extends beyond the numeral plus recognized unit hanja still protects the word, so smart does not split ordinary dictionary entries such as 北京 or 一分錢.

Dictionaries

A dictionary is anything that can be asked what matches start at a given text position.

pub trait HanjaDictionary {
    /// Yield every match that starts at the beginning of `s`.
    fn matches_at<'a>(&'a self, s: &'a str)
        -> Box<dyn Iterator<Item = Match<'a>> + 'a>;

    /// Greatest entry length, in characters, that this dictionary contains.
    /// Used as the lattice termination bound.
    fn max_word_chars(&self) -> Option<usize> { None }

    /// Complete entries, when the backend can enumerate them efficiently
    /// enough to build a batch policy index.
    fn entries<'a>(&'a self)
        -> Option<Box<dyn Iterator<Item = DictionaryRecord> + 'a>>
    { None }

    /// Is there another hanja word with the same hangul reading?
    /// Convenience API; the homophone-marker middleware uses entries() to
    /// avoid repeated full-dictionary scans.
    fn has_homophone(&self, hanja: &str, reading: &str) -> bool { false }
}

matches_at is the unusual part. The natural signature for a Korean text application would be longest_match, but eager longest-match is exactly the algorithm we reject in the engine. The trait surfaces every match starting at a position because the lattice segmenter needs the full set in order to score alternatives. The input string is the text suffix at the current cursor, not only a pre-cut hanja run; this lets dictionaries contain mixed-script keys such as 汽車길 as long as the match itself contains at least one hanja character.

A Match carries the matched byte length, the hangul reading, and a MatchMark. byte_len is the UTF-8 length of the matched dictionary key, which may include both hanja and hangul:

pub struct Match<'a> {
    pub byte_len: usize,
    pub reading: Cow<'a, str>,
    pub mark: MatchMark,
}

pub struct MatchMark {
    /// The dictionary asserts this entry should always be shown with hanja.
    pub require_hanja: bool,
    /// The dictionary asserts this entry should always be shown with hangul.
    pub require_hangul: bool,
}

The marks come from the source dictionary's build-time metadata. The bundled Standard Korean Language Dictionary's CDB and FST files are accompanied by a rules file that enumerates hard-to-read characters and ambiguous readings that should be hanja-annotated.

Built-in implementations

UnihanCharDict exposes the per-character Unihan reading table as a HanjaDictionary so callers can compose those readings through the same public dictionary interface as other sources. It returns canonical pre-initial-sound- law readings from a generated sorted table built from the Unicode kHangul property; stateful fallback rules such as initial sound law and numeral grouping remain engine behavior.

MapDictionary is the small in-memory dictionary used for tests, programmatically supplied entries, and custom vocabularies that are already in process memory. It is backed by an ordered map so it stays dependency-light and usable in the no_std core crate. Callers that need compact serialized data, mmap-friendly loading, or large static dictionaries should use the gukhanmun-fst backend instead.

ChainDictionary composes a sequence of dictionaries with a precedence policy. A caller can chain a small user dictionary (highest priority), a domain-specific dictionary, the Standard Korean Language Dictionary, and, when canonical single-character dictionary matches are desired, UnihanCharDict (lowest priority).

Cooperative source resolution

Builder defaults to ReferenceAuthorized. Authored dictionaries replace the whole candidate set for the same matched spelling and consumed length. Reference and loanword sources instead retain separate local candidate sets, preferences, marks and aliases. The source role changes candidate eligibility and ranking; it adds no bonus to the lattice path score. Direct ChainDictionary construction retains the legacy Ordered default.

The offline source graph distinguishes word IDs from sense IDs and retains all contributors to a merged reading. Only direct foreign-name synonyms and typed formal redirects authorize another complete initial/suffix form, and a grant must survive intersection over every contributor. Unknown or conflicting relations retain the original form. Formal redirects can provide a reference form without a matching loanword record; prose descriptions and language labels do not infer grants.

For each reference anchor, ReferenceAuthorized ranks authorized loanword realizations, a unique redirect terminal if present, and the original form. Independent loans follow every reference anchor. One particle filter runs over this ranked pool, falling back to its first member when no candidate fits. ReferenceFirst and LoanwordFirst expose the simpler source-class orders. Ordered preserves dictionary order without enabling role-based promotion. When a dictionary carries phrase evidence, it also retains that winning source's candidate pool so its own phrase rules can apply.

Nested registration preserves the child's effective eligibility contract for phrase proof. Reference is transparent to descendant source roles; Override keeps the complete eligible child pool as an exclusive override. Registering a nested chain explicitly as Loanword instead exposes its opaque effective candidate projection and exports no descendant phrase evidence. This prevents that registration from reviving descendants excluded by the child's policy.

Reference-only eligibility excludes independent loans while retaining reference-authorized realizations. Strict error/preserve-hanja ambiguity modes remain deferred until there is an explicit fallible conversion contract.

A selected form carries its source-local lexical identity, anchor reading, alias, positional form and marks through segmentation and middleware. First occurrence uses lexical canonical spelling plus anchor reading; homophones use actual emitted reading plus selected homophone canonical spelling. Source IDs alone do not distinguish either. A parenthetical reading override revalidates the retained ranked pool or resets to an authorial identity without stale aliases. Cooperative source-policy selections keep their existing annotation grouping. Plain dictionary views and Ordered chains keep legacy grouping, regardless of phrase metadata. In those legacy views, only a successful phrase proof keeps the selected edge's annotation separate; metadata alone does not change grouping. The lattice edges and scores remain unchanged. The engine caches immutable resolution results under bounded key and byte budgets. Lattice streaming commits only prefixes shared by every still-viable frontier path; overlapping paths can require a boundary or EOF even with a known maximum word length.

The evidence JSON is a reproducible extractor output. FST/CDB containers with critical evidence use version 4 and encode the typed data compactly as CBOR tuples. Readers validate schema, tuple structure and exact canonical candidate links before exposing the evidence. Evidence-free versions 1–3 remain readable with unknown evidence; older readers reject version 4. Candidate authorization uses the candidate_evidence metadata member and its unchanged version 1 schema. Source phrase constraints use a separate critical phrase_evidence member in the same container, with independent schema and policy versions. Runtime callers load one dictionary artifact; no evidence sidecar is required.

External backends

Two external dictionary backends ship as separate crates.

gukhanmun-cdb wraps a CDB file as a HanjaDictionary. CDB is djb's constant database: a static on-disk hash table with a compact, documented format. The naive use of CDB as a hanja-to-hangul map fails because CDB is a hash table without prefix iteration; there is no way to ask whether some key starts with a given byte sequence. We work around this by encoding the dictionary as a trie embedded in the CDB key space. At build time, gukhanmun-mkdict enumerates every prefix of every entry and stores a record for each, with a one-byte flag distinguishing complete words from intermediate prefixes:

key   = utf-8 bytes of a prefix
value = { is_complete: u8, mark: u8, reading_len: u16, reading: utf-8 }

Lookup walks one character at a time from the cursor position. On a miss, no longer match is possible from this position and the walk terminates. On a hit with is_complete = 1, the match is yielded; on a hit with is_complete = 0, the walk continues to look for longer matches. The cost is O(\text{max_word_chars}) indexed key queries per position. At load time, the backend validates record framing, table ranges and slot integrity, then builds a range index sorted by hash, key bytes and probe order, using O(N)O(N) storage for NN records. Before allocating the index, the loader counts framed records and checks that the bytes requested for record descriptors and lookup positions together do not exceed 64 MiB. The record limit depends on these types' sizes: 1,048,576 records on 64-bit targets, at 64 bytes per record for the two vectors together. A file with more framed records fails loading. Both vectors use Vec::try_reserve_exact() without geometric capacity growth. This budget excludes the loaded file bytes, decoded metadata and payloads, and allocator overhead. Each query hashes its key and makes O(log⁡N)O(\log N) key comparisons, independent of on-disk collision clusters. Keys and values stay in the backing bytes; embedded static data is borrowed, and candidate payloads are decoded when accessed. The on-disk size cost is real: every prefix of every entry occupies a record, so the bundled stdict CDB is roughly twice the size of the source TSV. The trade-off is that CDB's simplicity (six syscalls of file format, public-domain reference implementations) makes the backend trivially auditable.

gukhanmun-fst wraps an fst::Map as a HanjaDictionary. The FST (finite state transducer) supports prefix iteration natively and compresses better than CDB-as-trie, but its on-disk format is less universally implemented. We provide both because users have different priorities; CDB is the choice for code-auditability and trivial mmap support, while FST is the choice for small WebAssembly bundles.

Before enumerating FST keys, the loader validates the reachable automaton with an iterative graph walk. It counts actual accepted keys independently of the stored length and of max_word_chars metadata. Loading rejects more than 1,048,576 keys, 128 MiB of total accepted key bytes, 134,217,728 expanded traversal node visits (including nonaccepting branches), or a 4,096-byte path. A separate 64 MiB graph admission budget charges 128 bytes per unique node and 32 bytes per transition. The DFS stack is depth-limited. Fallible layout checks run before raw node decoding, without requiring panic unwinding. These charges bound admission work rather than measuring allocator overhead or RSS. The existing UTF-8-aware maximum-length fallback runs only after this check; valid static FST bytes remain borrowed.

Both container loaders (CDB and FST) preflight metadata without allocating decoded values. They apply admission charges before CBOR deserialization: 128 bytes per item and four bytes per byte of text or byte strings. Ordinary metadata, including aliases, has a 64 MiB charge budget; every alias row costs another 1,536 bytes, including duplicates and ignored rows. Candidate and phrase evidence share a separate 1 GiB charge budget to accommodate bundled source evidence. Metadata also has an aggregate limit of 8,388,608 CBOR items and 32 levels of nesting. Declared collection lengths are checked against the remaining item and charge budgets before traversing children. Indefinite collections and tagged values consume the same budgets and depth limit. The derived phrase index has a separate 64 MiB admission charge, checked before construction. Exceeding a limit fails dictionary loading in both formats. These are conservative admission estimates, not a bound on process memory; file bytes, dictionary indexes and allocator overhead have separate costs. Existing semantic and candidate-link validation still applies.

Dictionary tooling

gukhanmun-mkdict is a separate CLI for building CDB and FST dictionary files. It accepts TSV, CSV, and JSON Lines input, supports merging multiple input files with a configurable conflict policy, validates the result with a round-trip pass, and embeds build metadata (source, license, build date) in the dictionary header.

gukhanmun-mkdict [OPTIONS] -o OUTPUT <INPUT>...

INPUT FORMATS:
    tsv     hanja TAB hangul [TAB flags]
    csv     hanja,hangul[,require_hanja,require_hangul]
    jsonl   {"hanja":..., "hangul":..., "requireHanja":..., ...}

OPTIONS:
    -o, --output PATH               output path
    -f, --format FMT                cdb|fst            (default: fst)
        --merge STRATEGY            first-wins|last-wins|error
        --metadata KEY=VAL          embedded metadata
        --validate                  round-trip verification
        --max-key-bytes N           reject pathologically long entries
        --rules PATH                annotation rules TSV (repeatable)
        --allow-unmatched-rules     accept rules that match no entries

A rules file is a TSV with columns kind, pattern, require_hanja, require_hangul, reason. The kind selects one of three matchers: entry (exact hanja key), contains (any entry whose hanja key contains the hanja substring pattern), or reading (any entry whose hangul reading equals pattern). contains patterns must be hanja-only because dictionary keys can be mixed-script (e.g. 布告하다); accepting a hangul substring would silently mark unrelated entries. Multiple rules touching the same entry are OR-merged on the mark bits. A rule must set at least one of require_hanja / require_hangul, must carry a non-empty reason, and must match at least one entry; unmatched rules fail the build by default so that the rules file does not drift away from the dictionary it annotates. --allow-unmatched-rules is a hatch for partial dictionaries that share a rules file with a larger build.

The same binary is invoked by gukhanmun-stdict's build script to produce the bundled Standard Korean Language Dictionary FST file, so end-users and the library itself share the build path. The CDB backend uses the same normalized inputs and validation path for user-built dictionaries. Bugs in the build path get caught by the library's own integration tests before they reach users.

Candidate readings

Dictionary keys can retain several lexical readings. ReadingCandidate keeps its word-initial reading, optional suffix reading, annotation marks and relative default preference together. ReadingCandidates validates and deduplicates these pairs, merging marks only for identical pairs. It normalizes the minimum preference to zero and sorts by descending preference, then reading and suffix. select_default_reading chooses the first candidate without consulting text. Profiles remain future work; the engine applies the conservative particle filter below by default.

HanjaDictionary::candidate_matches_at() and candidate_entries() expose the full sets. Their default implementations wrap each existing Match or DictionaryRecord as a single candidate, so custom dictionaries remain usable. Legacy empty readings and explicit empty suffixes remain intact in memory. Strict new sets and serialized input reject them. The existing lookup and enumeration APIs project defaults. A chain replaces the entire candidate set for a key with the first dictionary's set, so lower-priority alternatives cannot undo an explicit override.

Variant resolution compares canonical spellings and their complete candidate sets before choosing a reading. The legacy particle-aware selection supplies the initial choice. Source-aware edges retain the eligible pool through segmentation so phrase constraints can revise that choice on the fixed path. Positional realization follows reading resolution. Phrase metadata alone leaves annotation grouping unchanged; a successful phrase proof keeps its selected edge separate. Particle selection alone needs four additional source scalars beyond dictionary lookahead. Active phrase rules add their finite surface and boundary allowance so ordinary chunk splits preserve the same evidence.

Dictionary-wide homophone detection indexes context-free default initial and suffix readings, then queries the actual emitted reading. Unused alternatives never create collisions by themselves. Context-local detection compares actual emitted readings. Custom lookup-only chains retain the existing per-child homophone fallback limitation. The Standard Korean Language Dictionary snapshot records source identifiers and curated tie-breaking decisions outside the runtime binary.

Particle evidence

After resolving a complete key and its candidate set, the engine chooses the first candidate compatible with an immediately following Korean particle. 을/를, 은/는, 이/가, and 과/와 distinguish consonant and vowel endings; 으로/로 also handles the rieul exception. The finite grammar additionally accepts 으로는, 으로도, 으로만, 로는, 로도, 로만, 과는, 과도, 과만, 와는, 와도, and 와만. The source particle is never rewritten. The entire suffix needs a witness: whitespace, EOF, a block boundary reported by the reader, or one of .,!?:;)]}。、!?,:;)】」』. Unsupported combinations, copulas such as 이다, and lexical prefixes such as 이름 supply no evidence.

Endings use the final precomposed hangul syllable. Unknown endings stay eligible, and a custom candidate remains eligible if either its initial or suffix form is compatible or unknown. Several survivors retain preference order; when no candidate survives or context is uncertain, the default is kept. The heuristic neither revives candidates removed by overrides nor resolves semantic ambiguity. A longer mixed-script key consumes its complete spelling before context is examined. Variant identity is resolved on full candidate sets, and context starts after the matched source bytes, even when variant byte widths differ.

Incremental chunk ends do not prove EOF. Inline, preserved, or verbatim transitions alone do not supply a witness. finish() supplies EOF; explicit flush() emits conservatively and can forfeit evidence when called inside a word. Textual whitespace remains a witness in either case. Pending multi-candidate edges also hold a preceding fallback run until selection is stable, preserving annotation grouping. The engine allows four extra source scalars for particle lookahead in its tail, never in the dictionary lookup bound.

The following examples assume a controlled dictionary containing 東京 but no longer 東京이 key. The bundled dictionary has 東京이 → 동경이, which takes precedence and makes 東京이다 become 동경이다.

The engine does not connect particle evidence across inline tokens. Markdown soft/hard line breaks and links, HTML br, literal entities such as &nbsp;, and quotation marks outside the witness set can therefore miss evidence. For example, [東京을](u) and 東京을<br> keep the default, while a space after 을, as in [東京을 ](u), supplies evidence. 東京이<b>다</b> and *東京이*다 also keep the default.

A sole non-block root Close is deferred until the next token or EOF. EOF can therefore supply evidence before a root inline close, such as <b>東京을</b>; a later token or explicit flush() resolves that endpoint as unknown. This also preserves the plain reader's Open/Text/Close shape without adding block boundaries to plain-text middleware contexts.

Variant normalization

Variant recognition is always enabled and does not change the HanjaDictionary trait or the FST/CDB formats. At each source position the engine first asks the dictionary for exact prefixes. For each prefix length without an exact match, each source character produces a bounded set of forms through the directional compatibility, Joyo, traditional, simplified, and Asahi projections used by the output variant sets. Reverse relations are used only when an exact target has one source. The engine enumerates the Cartesian product of those per-character forms, and the dictionary remains the oracle: a generated spelling is accepted only when it is itself a complete dictionary key. An exact match blocks expansion only at the same length, so a direct match for 芸 does not hide a longer 藝術 match for source 芸術.

The generated directional tables use Unicode 17.0.0 kZVariant, kSimplifiedVariant, kTraditionalVariant, and kCompatibilityVariant, the Japanese Agency for Cultural Affairs Joyo old/new pairs, and a verified sixteen-pair Asahi character subset. Semantic, specialized-semantic, and spoofing relations are deliberately excluded. Multi-target Unicode relations are not traversed as equivalence classes, so characters that only meet through a shared simplified form do not become interchangeable. Non-self simplified mappings remain directional even when their source is also another mapping's target. Prefixes are limited to 32 characters and 256 Cartesian candidates. The per-character form sets are computed once for each lookup window, and generated reverse/target indexes keep every table lookup logarithmic. Expansion is skipped for a prefix that exceeds either bound. After identical duplicates are removed, a variant-derived match is accepted only when exactly one complete dictionary match remains. Distinct canonical spellings or distinct match metadata are ambiguous even when their readings agree, because choosing either spelling would invent a lexical identity that the source does not establish.

Compatibility folding also applies to character fallback readings, so a compatibility form such as 神 inherits the reading of 神. Parenthetical reading validation remains source-based. Reading lookup deliberately ignores kHangul values attached directly to compatibility code points, including distinctions inherited from KS X 1001/1002. Gukhanmun treats those code points as presentation variants of the unified character rather than independent lexical characters.

Middlewares

The renderer's input is an OutputToken stream where each Annotated token carries flags. The flags describe what the engine knows about the annotation: was it from the dictionary, is there a homophone, is this the first time we have seen this word. What they do not describe is what the renderer should do about it; that is set by middlewares.

Splitting policy (which annotations should be presented with hanja, which with hangul only, when does “first” reset) from form (parentheses, ruby, hangul only) gives us a cleaner pipeline than Seonbi has. In Seonbi, the rendering function decides both what to present and how. As a result, the homophone-disambiguating renderer must internally re-implement a homophone-detecting pass, and there is no way to swap in a different homophone heuristic without rewriting the renderer. In Gukhanmun the middlewares are stateful filters on the OutputToken stream, and the renderer is a usually stateless translator from Annotated tokens to concrete text and markup.

Built-in middlewares

HomophoneMarker scans the stream and sets homophone = true on annotations whose hangul reading is shared by another hanja form in the effective dictionary entry set or within the configured context window. It builds a single reading-to-hanja index from HanjaDictionary::entries() when the backend exposes entries; lookup-only dictionaries fall back to has_homophone() and still get context-local marking. The window is one of per-block (default), per-document, or off. Per-block windows buffer only until the next scope whose is_block_boundary() returns true, which is typically a paragraph or a list item. Per-document windows buffer the whole stream and are appropriate only when the input is small or when full accuracy matters more than latency. Plain text has no block scopes, so per-block is document-wide there. This is intentional: if 漢字 appears on line 1 and 翰字 appears on line 100, both lines must render with disambiguating hanja, and a streaming writer cannot retroactively rewrite line 1 after line 100 is seen.

FirstOccurrenceFilter clears require_hanja and require_hangul on annotations after their first occurrence within a configurable context, leaving the first occurrence as-is so the reader still encounters the gloss once. The context is one of per-block, per-section, or per-document. The section variant resets at any heading boundary, which the HTML and Markdown adapters expose through is_section_boundary() on heading scopes.

UserDirectives applies a user-supplied set of rules. A rule is a predicate over the hanja form plus an action: set require_hanja, set require_hangul, or skip the annotation entirely (which collapses to plain hangul or plain hanja text depending on the active renderer). The rule predicate may be a literal string set, a glob, or an arbitrary closure for Rust callers; JavaScript callers expose only the literal-set form to avoid the cost of per-token cross-boundary calls.

Punctuation normalization

Punctuation profiles describe output, independently of hanja rendering, character variants, and language presets. Every profile recognizes the same fixed input roles: comma, period, and the opening and closing members of single and double citation delimiters. There is no input-style detection or bracket repair. preserve bypasses normalization by default; custom profiles may leave individual roles unchanged. If a custom profile emits a character outside the recognized input alphabet, a later conversion does not recognize that character as the role it came from. Idempotence does not imply reversibility between arbitrary profiles. The punctuation guide in docs/en/guide/punctuation.md provides the profile and API reference.

PunctuationNormalizer runs after annotation policies and before rendering. It rewrites only ordinary OutputToken::Text, leaving Annotated payloads and Verbatim tokens intact. This placement keeps reading selection independent of the output profile and prevents generated ruby, annotation parentheses, and readings from becoming normalization input. HTML entity decoding belongs to this stage too; it does not feed decoded hanja back into the engine.

Space handling needs structural lookahead. Only U+0020 is normalized; other whitespace remains unchanged. ScopeData::punctuation_boundary() distinguishes transparent inline scopes, block boundaries, explicit line breaks, opaque boundaries, and punctuation-preserved subtrees. Space lookahead can cross transparent scopes and places a space at their common enclosing scope. Block and line-break boundaries trim a pending contextual space; opaque boundaries retain existing spaces without adding one. Unknown scopes default to opaque unless they already declare a block boundary. Technical guards for numbers, URLs, and Latin text reset at every structural or annotation boundary, even when space lookahead can cross it. Unicode Latin-script letters share guard context across combining marks. Marks and format controls are ambiguous spacing witnesses, so they do not cause a new space to detach a continuation from a stop.

Preservation has two separate meanings. is_preserve() is the adapter's already-resolved answer for the current scope, so a Korean child can override an inherited foreign language. Middleware must not OR that flag with every ancestor. The punctuation-specific Preserve boundary instead protects an entire subtree, such as a Markdown image label, independently of hanja conversion. Adapters retain responsibility for inherited code and raw-text preservation. Writers must keep this effective preservation information until serialization, even when lowering scopes into another event representation.

A single normalizer instance persists across all input batches for a document. Upstream stages must finish and drain before its finish() runs; an I/O flush is not EOF. Adjacent text chunks share context, so chunk boundaries must not change output. Space lookahead crosses at most 256 structural events and falls back to keeping existing spaces when that limit is reached. This is not a constant-memory promise: unfinished HTML numeric references and runs of differently spelled encoded spaces can still require unbounded buffering.

Custom middlewares

A middleware is an impl Iterator<Item = OutputToken<S>> taking an upstream iterator. The trait surface is small enough to write inline. Users who want, for example, to mark technical-term annotations from a glossary write a middleware that holds the glossary set and updates require_hanja on hits.

Renderers

The renderer expands Annotated tokens into concrete Annotated, Ruby, Open, and Close tokens according to its mode and the annotation's flags. Annotated marks text the renderer generated from annotation data, as opposed to Text, which is source text that is already valid for the output format. Every writer serializes Annotated as literal text, so a dictionary reading can never become markup (GHSA-j87h-8h88-wm6g). Five renderers ship with the library.

The HangulOnly renderer emits the hangul reading alone. If require_hanja or homophone is set, it emits 한글(한자). If require_hangul is set, the result is already hangul, so nothing changes.

The HangulHanjaParens renderer always emits 한글(한자). The require_hangul flag is satisfied by the hangul half, and require_hanja by the hanja half.

The HanjaHangulParens renderer always emits 한자(한글). This is useful for academic and historical-document styles that lead with hanja.

The Ruby renderer emits a <ruby> element with a sub-mode that determines which side is the base: <ruby>한글<rp>(</rp><rt>한자</rt><rp>)</rp></ruby> for on-hangul, and <ruby>한자<rp>(</rp><rt>한글</rt><rp>)</rp></ruby> for on-hanja. The <rp> elements carry parenthesized fallback text so that browsers without <ruby> support render the annotation inline as base(gloss) (한글(한자) for on-hangul, 한자(한글) for on-hanja) rather than running it into the base. If the current scope returns false from allows_inline_markup(), the renderer falls back to parens.

The Original renderer emits the original hanja as plain text. Only annotations with require_hangul, or those marked by a user directive, receive a gloss; the gloss appears in either parens or ruby form depending on a sub-option. This is the mode for “keep mixed script, gloss only the difficult characters”, which is the style this very design document uses on its Korean edition.

Every mode applies a separate HanjaVariantSet whenever it emits hanja. AsDictionary is the default and preserves dictionary_hanja, or source hanja for fallback annotations. Shinjitai applies the Joyo new forms, Kanxi prefers compatibility-folded traditional forms, Simplified uses the Chinese simplified representative, and Asahimoji applies shinjitai plus the verified Asahi subset. These conversions compose directional source/target relations. Within each connected kZVariant component, Kanxi chooses the lowest Unicode scalar value as a deterministic representative, so reciprocal rows produce stable, idempotent output. Compatibility folding is reapplied after traditional projection so that a directional mapping cannot reintroduce a compatibility ideograph. A reverse relation is used only when the exact target has one source, so a connected equivalence class never transfers a form across different senses that merely share a simplified character. A direct mapping for the requested set takes precedence over cross-set projection, and characters already recorded as Joyo or Asahi targets remain in that set. A cross-set reverse projection for simplified output is retained only when it reaches a direct simplified mapping; otherwise the existing character remains unchanged. This is an output policy only; all sets share the same recognition and reading.

Renderers are pure functions over a single Annotated token plus the current scope's allows_inline_markup() value. They produce a small fixed-size sequence of output tokens (one for plain hangul or hanja, three for parens, between five and nine for ruby). They contain no state and no buffering.

The renderer is the right place to make form decisions because the form depends on what other tokens are in the stream at the same scope position; for example, <ruby> inside <pre> is wrong, and the decision needs the scope stack, which is what flows through the IR. Putting form decisions elsewhere would either duplicate the scope tracking or require the renderer to know about other middlewares.

Format adapters

Three adapters ship with the library. A new adapter requires only Reader and Writer implementations that translate between the format's tokens and the IR.

HTML

The HTML adapter implements a hand-written scanner that produces InputToken<HtmlScopeData> events. The scanner is a near-direct port of Seonbi's Text.Seonbi.Html.Scanner module, which has been used on real-world Korean web content for several years. It is fragment-oriented: the input may be a complete document, a body, or a fragment, and the scanner emits the events it sees rather than attempting tree construction.

We considered using html5ever or lol_html. html5ever is the reference HTML5 parser for Rust; it produces a DOM and handles every edge case in the HTML5 specification. lol_html is Cloudflare's streaming HTML rewriter; it is selector-driven and integrates with WebAssembly well. We chose a hand-written scanner because the Seonbi approach has two specific virtues that fit our model. First, it preserves raw attribute strings rather than parsing them, which means the writer can serialize an unchanged scope exactly as it appeared in the input. Second, it is small enough to fit comfortably in a WebAssembly bundle, where bringing along html5ever would dominate the binary size. The cost is that our scanner is not HTML5-conformant; we accept the trade-off.

The scanner recovers from minor errors. Unclosed tags pop the most recently opened scope of the same name, or, if none, are emitted as text. Unrecognized constructs that begin with < but are not valid tag, comment, or CDATA starts are emitted as text characters. Entirely malformed input still produces a token stream, just one with structural anomalies; the engine is robust to anomalies (it does not assume scope matching) and the writer emits whatever scopes it received.

HtmlScopeData::is_preserve() returns true if the current element is one of pre, code, kbd, script, style, or textarea, or if the inherited lang attribute is not Korean. The lang inheritance is computed inside the adapter: each Open event evaluates its raw attributes for a lang value, and the adapter maintains its own lang stack. This is the only place in the codebase that knows what lang means, and the only place that knows the preserved-tag list. The engine receives the consequences as is_preserve() and does not reproduce either rule.

Punctuation processing uses an adapter-owned PunctuationTextCodec: each unit keeps its raw source spelling and a once-decoded value for classification and context. Unchanged units retain their spelling. &amp;period; is not decoded twice, and &lt;script&gt; never becomes markup. Plain text and already-decoded Markdown use the literal codec. The core stays independent of HTML tables; WHATWG character-reference data and Unicode punctuation categories are pinned, vendored inputs with offline regeneration checks. Recognition follows decoded Unicode values rather than entity names: WHATWG &lang;/&rang; denote mathematical delimiters U+27E8/U+27E9, outside the citation delimiter input set, whereas U+2329/U+232A and their canonical equivalents U+3008/U+3009 are recognized.

Safe output depends on adjacent source text as well as the replacement character. Generated HTML ; and # use numeric references so they cannot complete a neighboring character reference. In &notin。, the parser recognizes the legacy &not and renders ¬in。. Replacing 。 with a literal ; would serialize as &notin;, rendering ∉ instead of the intended ¬in;. Generated !, ?, and / also use numeric references to avoid forming markup after a recovered literal <. Unmatched end tags need separate protection: escaping them as ordinary text would change existing HTML semantics. The punctuation-enabled façade therefore asks the reader to preserve them as Verbatim. Low-level pipelines must select both these reader options and the HTML codec, including for rootless fragments.

Markdown

The Markdown adapter is a thin layer over pulldown-cmark. Each pulldown-cmark::Event becomes one or more IR tokens. Start(Tag) and End(Tag) become Open and Close. Text becomes Text. Code becomes Verbatim. Inline HTML, which pulldown-cmark exposes as Event::Html, is passed through a second pass of the HTML scanner so that constructs like <q lang="ja"> inside a paragraph receive proper lang handling.

Output is via pulldown-cmark-to-cmark, which serializes an event stream back to Markdown. Semantic preservation is contractual: the output, when re-parsed, produces the same logical structure. Byte-for-byte preservation is best effort: Setext headings may become ATX, link reference definitions may be inlined, soft breaks may be regularized. Users who require byte-fidelity should process rendered HTML rather than Markdown.

We chose pulldown-cmark rather than writing a Markdown parser because the work of CommonMark conformance is large and well-handled by pulldown-cmark, and because the event-stream API is a near-perfect match for our IR. The alternative was markdown-rs, which is more recent and produces an AST rather than an event stream; we preferred event streams for the streaming property.

With punctuation normalization enabled, MarkdownWriteOptions::protect_text_syntax prevents transformed text from becoming new Markdown syntax. The writer escapes ordinary ASCII punctuation with numeric references and protects text newlines and spaces that could become hard breaks. It lowers emphasis, strong emphasis, and strikethrough to local HTML, because changing adjacent punctuation or spaces can invalidate Markdown delimiter flanking. Changed autolink labels become ordinary links while retaining their original destinations. Code, raw HTML, and effectively preserved text must bypass these escapes; raw-text elements such as script do not decode character references.

The writer preserves the structure represented by pulldown-cmark, while source spelling may change. Hosting-site extensions such as implicit bare-URL, mention, and issue-reference linking are outside that contract; explicit links retain their destinations. Downstream formatters also need integration tests: the Hongdown formatter can strip inline HTML from headings, so the CLI protects those spans while formatting the whole document and restores them afterward. If restoration cannot be verified, it retains the converted Markdown without the formatting pass.

Plain text

The plain-text adapter wraps the entire input in a single scope and emits one Text token. The output is the concatenation of Text and Annotated tokens. Ruby rendering is not meaningful in plain text and falls back to parens. The CLI can stream plain text before EOF only when no document-wide middleware can change already rendered output. In practice, the ko-kp preset streams because homophone marking is off, while the default ko-kr preset keeps the plain-text output until EOF so cross-line homophones are rendered correctly.

Distribution

Rust workspace

The Rust source is organized as a Cargo workspace with the following layout:

  • Cargo.toml: workspace manifest
  • DESIGN.md: symbolic link to DESIGN.en.md
  • DESIGN.en.md, DESIGN.ko-Kore.md: design documentation
  • crates/
    • gukhanmun-core/: IR types, engine, dictionary trait, lattice segmenter, fallback phoneticizer, initial sound law tables, embedded UnihanCharDict. No I/O, no format-specific code, minimal dependencies. Suitable for no_std environments with alloc.
    • gukhanmun-html/: HTML scanner and serializer. HtmlScopeData implementation.
    • gukhanmun-markdown/: Markdown adapter atop pulldown-cmark.
    • gukhanmun-cdb/: CDB-trie dictionary backend.
    • gukhanmun-fst/: FST dictionary backend.
    • gukhanmun-stdict/: bundled Standard Korean Language Dictionary as an embedded FST byte array.
    • gukhanmun-mkdict/: CLI for building CDB and FST dictionaries from TSV, CSV, or JSONL inputs.
    • gukhanmun/: the umbrella library crate. Re-exports from the others under feature flags, exposes the high-level Builder API, defines the umbrella Error enum.
    • gukhanmun-cli/: the gukhanmun command-line binary.
    • gukhanmun-wasm/: WebAssembly bindings via wasm-bindgen.
    • gukhanmun-napi/: Node-API bindings via napi-rs.
    • gukhanmun-python/: private Python extension via PyO3.
  • python/gukhanmun/: Python façade and distribution metadata.
  • python/gukhanmun-cli/: independent Python launcher for the bundled CLI.

The umbrella crate's feature flags compose the others. Default features enable HTML, Markdown, the CDB and FST backends, and the bundled loanwords, stdict, and opendict dictionaries. Each feature is individually selectable. Disabling everything yields a Rust-API-only build with just the engine and UnihanCharDict, suitable for embedded targets.

Conversion ownership

Builder<'a> and Converter<'a> accept borrowed dictionaries and local callbacks. They impose no Send or Sync requirement on dictionaries or preservation predicates, so callers can use thread-local state and captures that borrow from their own scope.

SharedBuilder produces an owned SharedConverter whose fields satisfy Send + Sync + 'static. It accepts owned dictionaries with those bounds, literal directives, and an owned thread-safe HTML preservation predicate. Callers can share one runtime through Arc<SharedConverter> for concurrent one-shot plain-text, HTML and Markdown conversion. HTML and Markdown methods retain their existing feature gates; iterator conversion remains available through Builder and Converter.

Both façades resolve presets and assemble the same dictionary chain at build time, preserving source roles, nested policies and phrase-evidence ownership. They retain the lexical index constructed for the ordered source policy and use the same execution helpers. Each conversion creates its own parser, engine and middleware state. Each call creates temporary directive and HTML reader adapters. Literal directive strings are cloned, while the HTML predicate borrows the immutable runtime. An HTML predicate may run concurrently, so its captured data must meet the shared builder's bounds.

JavaScript packages

The JavaScript side is split into a type-only package and one package per runtime implementation:

  • @gukhanmun/types (npm and JSR): TypeScript interfaces, type aliases, error class declarations, and the GukhanmunFactory interface. Contains no runtime code; npm emits declarations only, while JSR receives the .ts source directly. This is the canonical API contract; both implementations satisfy it structurally.
  • @gukhanmun/wasm (npm and JSR): WebAssembly implementation. Re-exports the types. Resolves its .wasm artifact relative to import.meta.url. On Node.js, local files are read through node:fs/promises; other URLs use fetch(). The package supports Node.js 20+.
  • @gukhanmun/napi (npm only): Node-API implementation. Re-exports the types. Ships per-platform prebuilt binaries through napi-rs's optional-dependency packaging.
  • @gukhanmun/cli (npm only): a dependency-free Node.js launcher for the existing dictionary-bundled CLI. Six exact-version optional packages carry macOS, Windows and static musl Linux executables on x64/arm64. The parent contains the shared completion bundle. These packages are staged and packed outside the pnpm library workspace, without installation scripts or a dependency on the Node-API binding.

The data dictionaries ship as separate packages so that the runtime bundle stays small:

  • @gukhanmun/stdict-fst (npm and JSR): the bundled stdict as an FST file, exported as a Uint8Array.
  • @gukhanmun/stdict-cdb (npm and JSR): the same dictionary as a CDB file.
  • @gukhanmun/opendict-fst and @gukhanmun/opendict-cdb (npm and JSR): the four Open Korean Dictionary categories.
  • @gukhanmun/loanwords-fst and @gukhanmun/loanwords-cdb (npm and JSR): the National Institute of Korean Language’s loanword spelling examples.

The reason for the type-only package is that the canonical API contract should live in exactly one place. If the contract lived in @gukhanmun/wasm and @gukhanmun/napi duplicated the types or imported them from one another, version skew between the implementations would become a maintenance burden. With @gukhanmun/types as a peerDependency of both implementations, users get a single source of truth and a single set of types regardless of which runtime they pick. We considered, and rejected, two alternatives: keeping the types in the WASM package and having NAPI depend on it directly (asymmetric, makes NAPI subordinate to WASM); and duplicating the types in both packages (drift between copies, no obvious home for the canonical TSDoc comments).

Option enums on the JavaScript side are string union types rather than const-asserted objects. This keeps @gukhanmun/types genuinely type-only: it emits zero bytes of runtime code, which matters for bundles and which means the JSR package's source can be a single .ts file with no transpilation step. The trade-off is that the option strings are stringly typed at runtime; both implementations validate them at the boundary and throw a GukhanmunError with code invalid-input on unrecognized values.

The JavaScript stream() method uses the platform TransformStream<string, string> interface. Both bindings currently buffer all input and convert it when the writable side closes. They do not emit partial output, even with homophone marking disabled, and do not provide a bounded-memory conversion interface. Chunks are JavaScript strings; encoding concerns (TextDecoderStream, TextEncoderStream) live outside the Gukhanmun stream.

The Rust engine's incremental API has a different contract. A chunk that ends in the middle of a conversion span, or close enough to a hanja character that a mixed-script dictionary key could still cross the boundary, causes that trailing span to be held until the next chunk arrives. Already settled prefixes can be emitted. Dictionary lookahead uses max_word_chars plus particle lookahead; source phrase rules add a finite tail and committed left context. Unresolved lattice frontiers can retain more input than those allowances. Fallback-only hanja runs are deliberately not split at chunk boundaries, because render modes that show source hanja expose annotation grouping; those runs flush at a later non-convertible boundary or EOF.

Stateful middlewares can add their own lookahead requirement. A homophone marker with a document-wide context, including plain-text per-block where no block scopes exist, must buffer until EOF to preserve exact rendering. Disabling that middleware permits early output through the Rust incremental API but also disables cross-line homophone disambiguation. It does not change the JavaScript bindings' buffering behavior.

We chose strings rather than Uint8Array for the streaming type because the engine fundamentally works on Unicode scalar values: byte-level chunking would force the adapter to do partial-codepoint reassembly at every boundary, which the platform's TextDecoderStream already does correctly. Users who have a byte stream chain it through TextDecoderStream and then through the gukhanmun transform.

Python package

The gukhanmun Python distribution lives under python/gukhanmun/ and exposes an immutable Converter(...) with snake_case keyword options. The Python façade defines standard-library enum.Enum classes and frozen configuration records. Options accept the declared enum members, not implicit strings; configuration read from a string can use an explicit conversion such as Preset("ko-kr"). packages/types/index.ts is the behavior baseline, and executable parity tests compare the constructor fields, resolved view and enum values with that contract. The public package has no required third-party Python runtime dependencies.

The private gukhanmun._native extension is built with PyO3 and maturin from crates/gukhanmun-python/, a publish = false crate. Python values are validated and converted to owned Rust data before the thread detaches from the Python interpreter. On ordinary CPython this releases the global interpreter lock (GIL). The native handle owns a SharedConverter, so the same configured converter can serve concurrent threads while parser, engine and middleware state remains local to each document. The detached boundary catches Rust panics and translates them to INTERNAL errors. Python signals are checked after native work returns; a long conversion can delay KeyboardInterrupt. Python callbacks are not part of this interface: directives are literal lists, and HTML preservation uses class and attribute rules.

Converter(...) snapshots configuration and loads explicit map/FST/CDB sources at construction time. File sources accept owned bytes or filesystem paths; URL sources are a separate UrlDictionarySource with HTTP(S) downloads, same-origin redirects, response-size limits and response-reading deadlines. Conversion calls perform no dictionary I/O. Neither preset loads official dictionary data, and installing an extra does not change converter defaults. converter.options exposes the frozen, resolved settings. Punctuation profiles distinguish an omitted override (UNSET, which inherits), None (which preserves that punctuation role), and an explicit style.

convert() accepts plain text, HTML or Markdown, with MarkdownOptions(gfm=True) enabling GFM. stream() creates a single-consumer ConversionStream that holds a reference to its converter. Each successful push() returns an empty string; finish() converts all buffered input once. After a successful finish, or after any push or finish failure, the stream accepts no further calls. convert_iter() adapts an iterable to the same batch-equivalent behavior, finalizing only after normal input exhaustion. It is a chunked interface, not a bounded-memory or asynchronous streaming implementation.

The public Python source ships with py.typed and a stub for the native boundary. mise selects pinned interpreters and uv manages locked dependencies in a virtual workspace without building the native extension during automatic dependency setup. The optional Python tool profile provides CPython 3.11–3.15 and PyPy 3.11/3.12. tox builds a noneditable wheel for each explicit interpreter/ABI and runs copied tests outside the checkout. mypy, Pyright, basedpyright, ty and Pyrefly check the installed package with positive and negative consumer examples; stubtest compares native signatures with the stub. Fast tooling tests need no native build, while the full local gate includes runtime, typing, data and artifact checks.

Official dictionaries ship as six optional, resource-only distributions under python/: gukhanmun-stdict-fst, gukhanmun-stdict-cdb, gukhanmun-opendict-fst, gukhanmun-opendict-cdb, gukhanmun-loanwords-fst and gukhanmun-loanwords-cdb. They are platform-independent Hatchling wheels with no dependencies and never import the native package. Core extras pin each data distribution to exactly the core distribution's own version. The stdict, opendict and loanwords extras select the FST distributions; explicit FST aliases and CDB extras are also available. Staging reuses the existing JavaScript dictionary generators' outputs and adds licenses, attribution and provenance. gukhanmun.dictionaries reads installed resources through importlib.resources, checks recorded sizes and hashes, decompresses packaged gzip data and returns owned bytes in ordinary file sources. Helpers preserve the reference/loanword roles and expose all four Open Korean Dictionary categories. Missing or damaged optional data produces a coded error with an installation or reinstallation command.

Release artifacts comprise eight CPython abi3 wheels with a Python 3.11 baseline, ten PyPy-specific wheels, six data wheels and seven source distributions (sdists), 31 files at one coordinated Python version. CPython wheels cover glibc 2.28 and musl 1.2 on x86_64/aarch64, macOS 11 on x86_64/arm64, and Windows 10 on AMD64/ARM64, subject to the interpreter's own OS requirements. PyPy 3.11/3.12 wheels cover the glibc and macOS targets above and Windows AMD64. Free-threaded CPython, 32-bit targets, and PyPy on musl or Windows ARM64 are outside this matrix. Each advertised target has native install and execution evidence, and each sdist is rebuilt outside the checkout. The native sdist carries the required Rust/Python sources and Cargo metadata, without the optional dictionaries' source data; data sdists already contain their resources.

CI inventories those artifacts with hashes, source commit, platform audits, execution evidence and sdist rebuild records. A credential-free job validates the complete immutable bundle. A separate job obtains PyPI Trusted Publishing credentials, retrieves the original bundle by artifact ID, verifies its pinned manifest hash, and uploads its files without rebuilding. Data distributions are uploaded first and confirmed visible before the core package is uploaded. Reruns skip only files whose hashes and sizes match the registry; a content conflict stops publication, and attempt-specific receipts record partial progress. Eligible upstream branch pushes publish development versions; matching signed tags publish stable versions and attach the same files, manifest and checksums to GitHub Releases. Publisher bootstrap and recovery procedures live in CONTRIBUTING.md.

Dictionary configuration

The JavaScript dictionary configuration accepts either a file source or an in-memory map:

export type DictionarySource = FileDictionarySource | MapDictionarySource;

export interface FileDictionarySource {
  readonly data: BufferSource | string | URL;
  readonly format: "cdb" | "fst";
}

export interface MapDictionarySource {
  readonly entries: readonly DictionaryEntry[];
}

The two variants are distinguished by the presence of an entries property at runtime ("entries" in source) and by structural typing at compile time. The array form carries one reading per item, so repeating a hanja key supplies competing readings for the same headword; this is what allows particle evidence to choose between them, and a ReadonlyMap could not express it once a key has several readings. Wrapping the array in an object also leaves room for per-source options such as the reading profiles of #17. The file form remains the route for shipped dictionaries, and the reserved "tsv" member is gone: entries that exist only in memory go through MapDictionarySource instead.

Each descriptor can specify a source role: "override", "reference", or "loanword". Entry lists default to overrides; compiled dictionaries use their embedded role, falling back to override when absent. Official loaders declare their roles explicitly. Overrides replace cooperating candidates for the same spelling and consumed length; earlier overrides take priority. Entry lists become MapDictionary values in gukhanmun-core with no text parser in the bindings.

Python uses frozen MapDictionarySource, FileDictionarySource and UrlDictionarySource records instead of structural descriptors. Map entries retain competing readings, preferences and suffix readings. File sources accept bytes or paths; a string path is never guessed to be a URL. All three source types use the same role precedence and evidence-aware dictionary chain as the JavaScript bindings. Each official Python source helper returns one FileDictionarySource, supplied as an item in the converter's dictionary sequence. The corresponding *_bytes() helpers return dictionary bytes.

Both JavaScript backends' loadDictionary() and Python's load_dictionary() return an opaque snapshot of a source's parsed data and resolved role. A converter owns a reference to each loaded dictionary in its source chain, so dropping the caller's handle does not invalidate the converter. Source order, override resolution, the merged ordered alias index, and dictionary-wide homophone detection remain converter- or document-specific. A new explicit load takes a new snapshot; no path- or URL-based cache is involved.

Registry matrix

Packagecrates.ionpmJSRPyPI
gukhanmun-coreyesnonono
gukhanmun-htmlyesnonono
gukhanmun-markdownyesnonono
gukhanmun-cdbyesnonono
gukhanmun-fstyesnonono
gukhanmun-stdictyesnonono
gukhanmun-opendictyesnonono
gukhanmun-loanwordsyesnonono
gukhanmun-mkdictyesnonono
gukhanmunyesnonoyes
gukhanmun-cliyesnonoyes
gukhanmun-wasmyesnonono
gukhanmun-napiyesnonono
gukhanmun-pythonnononono
@gukhanmun/typesnoyes (declarations only)yes (.ts source)no
@gukhanmun/wasmnoyesyesno
@gukhanmun/napinoyesnono
@gukhanmun/clinoyesnono
@gukhanmun/stdict-fstnoyesyesno
@gukhanmun/stdict-cdbnoyesyesno
@gukhanmun/opendict-fstnoyesyesno
@gukhanmun/opendict-cdbnoyesyesno
@gukhanmun/loanwords-fstnoyesyesno
@gukhanmun/loanwords-cdbnoyesyesno
gukhanmun-stdict-fstnononoyes
gukhanmun-stdict-cdbnononoyes
gukhanmun-opendict-fstnononoyes
gukhanmun-opendict-cdbnononoyes
gukhanmun-loanwords-fstnononoyes
gukhanmun-loanwords-cdbnononoyes

CLI binaries ship as platform releases (Linux x86_64 and aarch64, macOS arm64 and x86_64, Windows AMD64 and ARM64) attached to the GitHub Releases for each version. The independent gukhanmun-cli PyPI distribution wraps the same dictionary-bearing converter and gukhanmun-mkdict builder in six py3-none platform wheels, with entry points and native audits for both commands. Its Linux wheels have compressed manylinux/musllinux tags and require static-linkage and execution checks on both libc families. The launcher has no runtime package dependencies, extension module or source distribution. It includes the shared completion resources, software and data notices. Its artifact manifest, native execution evidence and immutable upload bundle remain separate from the Python binding's 31-file release set.

Versioning is lockstep across all public packages. The workspace.package.version in Cargo.toml is the only manually chosen version; it names the next planned release. mise run bump-execute updates the workspace and synchronizes JavaScript manifests, all eight Python manifests, exact extra pins and uv.lock in one signed bump commit. A release tag publishes that version without changing it. Packages with no functional change still advance together to keep cross-language dependencies aligned. Coordinated releases avoid dependency-range drift between independently versioned runtimes, shared types and dictionary packages. The tag workflow publishes crates to crates.io, JavaScript packages to npm/JSR, and Python distributions to PyPI. It builds per-platform NAPI prebuilts and attaches release binaries to GitHub Releases. The private gukhanmun-python crate is packaged in the Python sdist, not published to crates.io.

Python uses PEP 440 spelling, including X.Y.Z.devN for eligible pushes to main or X.Y-maintenance in dahlia/gukhanmun, where N is the workflow run number. Matching signed X.Y.Z tags publish stable versions. Python versions omit the Rust/npm development version's +sha suffix; provenance retains the source SHA separately, and gukhanmun.__version__ reads installed distribution metadata. PRs, forks and feature branches validate X.Y.Z.dev0 artifacts without publishing credentials, or retain the workspace version if it is already a development release. The next development cycle needs a new workspace version after each stable release, since X.Y.Z.devN sorts before X.Y.Z.

Publication to PyPI is not atomic. The upload job uses the original tested bundle, reconciles already-published files by hash and size, and records each attempt's completed, missing and conflicting files. Rerunning the upload job can complete a partial release with identical files; rebuilding after an upload cannot substitute new bytes under the same filenames. Bootstrap creates the seven binding and dictionary PyPI projects with one seed upload, then configures normal Trusted Publishers for the repository workflow. The independent gukhanmun-cli project instead uses a pending Trusted Publisher for its first upload. Normal development and stable publication use Trusted Publishing without a long-lived token fallback.

Engineering policies

Errors

Each crate defines its own error enum via thiserror. The umbrella gukhanmun crate aggregates them with #[from] so that callers can use ? across crate boundaries without manual conversion. The pattern:

// gukhanmun-core/src/error.rs
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error("dictionary load failed: {0}")]
    DictionaryLoad(String),

    #[error("segmentation failed for {hanja:?}: {reason}")]
    Segmentation { hanja: String, reason: String },

    #[error("invalid hangul reading {reading:?} for hanja {hanja:?}")]
    InvalidReading { hanja: String, reading: String },

    #[error("internal invariant violated: {0}")]
    Internal(&'static str),

    #[error(transparent)]
    Other(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
}

The #[non_exhaustive] attribute lets us add new variants in minor releases without breaking callers; downstream match expressions are required to have a wildcard arm. Each variant carries enough structured data to drive both human-readable messages and machine consumers. std::error::Error::source() chains are preserved through #[from] and #[source] so that walking an error gives a complete trace.

Library crates do not use anyhow. The CLI does, because the CLI's job is to print errors to a human, not to be inspected by other code.

The stream-level recovery policy is configurable. The default is Recovery::Strict: the engine propagates any reader error and stops. Recovery::Lenient causes the engine to log the error via tracing and emit a Verbatim token for the unrecognized region so that downstream tokens still flow.

On the JavaScript side, errors are a single class with a discriminant code:

export class GukhanmunError extends Error {
  readonly code: ErrorCode;
  readonly chain: readonly { code: ErrorCode; message: string }[];
}

export type ErrorCode =
  | "dictionary-load"
  | "segmentation"
  | "invalid-reading"
  | "html-scan"
  | "html-malformed-attr"
  | "markdown"
  | "unsupported-content-type"
  | "invalid-input"
  | "io"
  | "internal"
  | "other";

The bindings walk the Rust source() chain at the FFI boundary and materialize a chain property on the error, so JavaScript callers can inspect causes without needing further FFI calls.

Python exposes the same codes as ErrorCode enum members in GukhanmunError.code. Its message is a string and chain is a frozen tuple of ErrorCause records ordered from deepest/root cause to immediate cause. Wrong argument types raise TypeError; invalid configuration values use INVALID_INPUT. File/URL operational failures use DICTIONARY_LOAD and preserve their Python causes. Source text containing lone surrogates raises UnicodeEncodeError. Python interruptions propagate unchanged.

Logging

gukhanmun-core and its siblings depend on the tracing crate unconditionally. Library code uses tracing::trace!, tracing::debug!, tracing::info!, tracing::warn!, and tracing::error! directly. The overhead when no subscriber is registered is one atomic load and a branch per call site, well under any threshold worth optimizing for.

Binaries that want to compile out the calls entirely (the WebAssembly build is the obvious case) enable tracing's release_max_level_off feature in their own Cargo.toml. That feature works at the binary level: it replaces every tracing::*! invocation in every dependency with a no-op at compile time, without requiring library code to be reconfigured.

We considered adding a library-level feature flag to make the tracing dependency itself optional, with stub macros for the off path. The added complexity (a log module per crate that conditionally re-exports tracing's macros or provides stubs) is larger than the binary savings; we will revisit if WebAssembly bundle measurements call for it.

Testing

The test suite has four parts.

Regression fixtures cover specific bug shapes that have appeared in Seonbi or in early Gukhanmun development. The relevant subset of Seonbi's test/data/ directory ports over directly; each fixture is a pair of input and expected-output files in HTML or Markdown, with a configuration sidecar.

Snapshot tests use insta to compare IR serializations against a stored JSON. They are most useful for the engine and middleware crates, where the input and output are token streams rather than text. A failed snapshot prints a colored diff and offers an interactive accept-or-reject prompt.

Property-based tests use proptest to assert invariants over generated inputs. The two invariants that matter most: reader-then-writer roundtrips a token stream losslessly (modulo the documented Markdown best-effort caveats); and engine-then-renderer applied to plain-hangul input is a no-op (the engine should not invent annotations from text without hanja).

Conformance tests run the Markdown adapter against a selected subset of the CommonMark specification examples to verify that the adapter does not break syntax that Gukhanmun is not interested in changing.

CI runs all four under stable, beta, and the MSRV (minimum supported Rust version) of the workspace. The WASM build is also exercised for size regressions: a fixed size budget per artifact is enforced, and a regression that exceeds it fails the build.

Presets

Optionko-krko-kp
renderinghangul-onlyhangul-only
disambiguationper-blockoff
segmentationlatticelattice
initialSoundLawtruefalse
numeralshangul-phonetichangul-phonetic
dictionary.bundledloanwords + stdictopendict North Korean
firstOccurrence(none)(none)

The ko-kr preset matches the orthographic and lexical conventions of South Korea: dictionary-driven readings, lattice segmentation, the initial sound law applied to fallback fragments, and per-block homophone disambiguation that emits hanja in parentheses when the reading is ambiguous within a paragraph. Bundled sources cooperate under ReferenceAuthorized: stdict keeps lexical identity and admits loanword forms only with compiled source evidence. User dictionaries override both for the same spelling and consumed length. The ko-kp preset matches the North Korean convention of writing Sino-Korean words in hangul without the initial sound law applied (래일, 류행, 녀자). It includes the Open Korean Dictionary North Korean category, with loanword examples disabled by default. JavaScript and Python presets configure the linguistic options but require callers to load dictionary packages explicitly. Installing a Python dictionary extra alone never activates that dictionary.

The CLI exposes both as --preset ko-kr and --preset ko-kp. Individual options remain settable to override the preset, for example --preset ko-kr --no-loanwords disables loanword examples while keeping stdict and the other South Korean defaults. --preset ko-kp --loanwords enables loanword examples explicitly.

Initial sound law table

The South Korean orthography (한글 맞춤법, Clause 5, Section 52, Chapter 6) converts a small set of word-initial hangul syllables. The table is reproduced from Seonbi's Text.Seonbi.Hanja module and is the source of truth for gukhanmun-core's initial_sound_law_table constant.

OriginalConverted
녀여
뇨요
뉴유
니이
랴야
려여
례예
료요
류유
리이
라나
래내
로노
뢰뇌
루누
르느

Hanja numeral table

The fallback phoneticizer and the additive-arabic numeral strategy share a single table of digit and place-marker hanja with their canonical values.

HanjaValueNotes
零, 〇0
一, 壹, 壱, 弌, 夁1
二, 貳, 贰, 弐, 弍, 貮2
三, 參, 叁, 参, 弎, 叄3
四, 肆, 䦉4
五, 伍5
六, 陸, 陆6
七, 柒, 漆7
八, 捌8
九, 玖9
十, 拾10
百, 佰, 陌100
千, 仟, 阡1000
萬, 万10000
億10000000010810^8
兆101210^{12}
京101610^{16}
垓102010^{20}
秭102410^{24}
穰102810^{28}
溝103210^{32}
澗103610^{36}

The additive-arabic strategy treats place markers as multipliers and adjacent digit hanja as multiplicands, with the Korean elision rule that bare 十, 百, 千 mean 10, 100, 1000 respectively (not 一十, 一百, 一千).

HTML preserved tags

The default HtmlScopeData::is_preserve() returns true for the following tag names regardless of attribute content: pre, code, kbd, script, style, textarea.

It additionally returns true when the inherited lang attribute's primary tag is anything other than ko, kor, or a subtag-prefixed Korean form (ko-KR, ko-Hang, ko-Kore, kor-KP, and so on). The Korean predicate matches Seonbi's isKorean.

Users who want to extend the list (for example, to add a project-specific class="no-translate" attribute) pass an HtmlReaderOptions value with a preserve_when predicate to read_html_fragment_with_options. The predicate receives an HtmlElementInfo view of each opened element—its canonical tag name, the raw attribute slice from the start tag, and the inherited lang value—and returns true to preserve the scope. A predicate-matched scope inherits its preserve flag to descendants, mirroring how the built-in preserved tags propagate, so callers do not have to re-assert the rule on every child. The CLI exposes the two most common shapes of this hook as --html-preserve-class CLASS and --html-preserve-attr KEY[=VALUE] (both repeatable, OR-composed, valid only with --format text/html). A format-neutral skip closure on EngineOptions is contemplated for a future release; it is not implemented today because every adapter that currently ships can satisfy its preserve needs through its own ScopeData.

CDB-trie key scheme

A CDB-trie database stores one record per prefix of each entry. The key is the UTF-8 bytes of the prefix. The value layout:

OffsetSizeField
01is_complete (1 if the prefix is itself an entry)
11mark (bitfield: bit 0 is require_hanja, bit 1 is require_hangul)
22reading_len (little-endian; 0 if is_complete = 0)
4reading_lenreading (UTF-8)

A separate well-known key, __gukhanmun_meta__, stores a small CBOR document with build metadata: source, license, build date, original entry count, prefix count, maximum entry length in characters and bytes.

FST schema

The FST database stores one entry per dictionary word. The key is the UTF-8 bytes of the hanja form; the value is a 64-bit integer whose layout is:

BitsField
0–15reading length in UTF-8 bytes
16–23mark (require_hanja and require_hangul bits as in CDB)
24–63offset into a side reading-string table

The reading-string table is a contiguous block of UTF-8 bytes following the FST itself. The side table is necessary because the FST value type is fixed-size; we cannot store variable-length readings inline. The mark byte sits in the value rather than the side table because checking it is hot for every lookup.

A metadata header at the file start (eight bytes of magic, version, layout offsets, and a CBOR metadata blob analogous to the CDB form) precedes the FST bytes.

Glossary

HangulHanjaEnglish
한자漢字hanja, a Chinese character used in Korean writing
한자어漢字語Sino-Korean word
국한문혼용國漢文混用mixed-script Korean writing
두음법칙頭音法則initial sound law
표준국어대사전標準國語大辭典Standard Korean Language Dictionary
한글한글hangul, the native Korean alphabet
한글전용한글專用hangul-only writing
동음이의同音異義homophony, distinct words sharing a reading

Candidate payload extension

The CDB/FST layouts above describe scalar v1 records. A dictionary needing multiple candidates or a suffix form uses v2. Mark byte 0x80 then identifies a candidate payload, with the existing length and offset pointing to that payload. Scalar records remain unchanged, and payload-free dictionaries are still written as v1. New readers accept both versions; old readers reject v2. The full byte layout and validation rules are documented in docs/en/internals/dictionary-format.md.