Skip to content

Translation Candidates and Patches

Palamedes Core exposes a provider-neutral boundary for finding local translation work and writing completed translations back to repository-owned catalogs. The API is available from Rust and through @palamedes/core-node.

Page outline

It deliberately does not choose a translation provider, authenticate remote requests, build prompts, or decide whether a translation is linguistically acceptable. A CLI, editor, hosted workflow, or local script can own those choices while sharing the same catalog semantics.

Translation Foundation And Boundaries

translation_candidates is the implemented local foundation: it enumerates work with stable identities and optimistic-concurrency fingerprints, then applies completed values with validation and per-file atomic writes. This page is the reference for that shipped boundary.

Adjacent local foundations may build on it without moving repository-owned catalog semantics into a separate product stack:

  • caller-supplied terminology and protected-term matching (see below);
  • deterministic QA for placeholders, ICU structure, whitespace, and review signals;
  • compact PO metadata and stale-metadata detection;
  • flagged/unresolved report shapes; and
  • bounded batching and retry decision support.

Those concerns belong in Palamedes only while they remain host-neutral, repository-local, and independent of account or provider concerns. Remote translation execution, provider routing, authentication, billing, policy packs, and hosted review or collaboration are product-layer responsibilities.

That split lets an optional managed layer compose discovery, request building, remote calls, retry coordination, incremental writeback, and reporting without reimplementing catalog semantics. Palamedes remains the complete open-source local toolchain and never requires that managed layer.

Caller-supplied terminology

matchTerminology() in @palamedes/core-node, and match_terminology() in Rust, find relevant caller-owned terms in one authored ICU message. They do not load files or dictionaries, call providers, change catalogs, or evaluate a translation's linguistic quality. A caller can pass a candidate's id.message and use the result to prepare guidance or implement its own review policy.

Each TerminologyEntry has a stable id, literal source, and a kind:

  • protected expresses an exact spelling to preserve. The intended spelling is preferredTarget when supplied, otherwise source.
  • advisory expresses translation guidance. Grammar, inflection, compounding, and context can justify a different target spelling.

Both kinds accept optional preferredTarget and note strings. The matcher does not search those fields or enforce either intention on target text. IDs and sources must be nonblank; supplied target spellings must also be nonblank. IDs are unique by exact, case-sensitive equality. Values are preserved without trimming, and duplicate IDs are rejected even when their terms do not match. Malformed ICU rejects the whole call, including with an empty entry list.

import { matchTerminology, type TerminologyEntry } from "@palamedes/core-node";

const entries: TerminologyEntry[] = [
  { id: "java", source: "Java", kind: "protected" },
  {
    id: "javascript",
    source: "JavaScript",
    kind: "advisory",
    preferredTarget: "JavaScript",
    note: "Use the language name in this context.",
  },
];
const matches = matchTerminology({ message: "Try JavaScript, {Java}!", entries });
// Two occurrences in the first literal: JavaScript (preferred), Java (overlap).
// The placeholder named Java is not an occurrence.

Matching is exact and case-sensitive, with no Unicode normalization, case folding, word segmentation, punctuation rewriting, or whitespace rewriting. It deliberately uses substrings: Java matches inside JavaScript; java does not. Composed café does not match decomposed cafe\u0301. CJK phrases and punctuation follow the same rule. Callers that need language-specific word boundaries must apply their own policy; a substring is a relevance signal, not a universal translation QA gate.

Only decoded native ICU literal nodes are searched. Placeholder and formatter names, formatter styles, tag names, and choice selectors are excluded. All plural, selectordinal, select, and rich-text child literals are visited. Terms never span separate literals, placeholders, tags, or branches. The runtime's apostrophe policy applies, so quoted ICU braces are literal searchable text.

Every occurrence is returned, including overlapping occurrences of the same term. preferred marks a greedy nonoverlapping selection within each literal: longest UTF-8 byte length first, then earlier start, then lexicographically smaller entry ID. Protection has no implicit priority over advisory guidance; nonpreferred protected matches remain available to the caller. Results follow native AST traversal, then start, descending length, and ID, independent of the entry list's order.

Each TerminologyMatch includes entryId, kind, decoded literal, and a literalPath. The path contains a root node index, followed by a child node index for a tag, or an option index and child node index for a choice, recursively. Indices follow native parser order. start and end are half-open UTF-8 byte offsets within that decoded literal. They are neither raw ICU source offsets nor JavaScript UTF-16 indices. For Node consumers, Buffer.from(match.literal).subarray(match.start, match.end).toString("utf8") recovers the matched phrase. Quoting can change the decoded text's length; do not use these ranges to edit the original ICU source.

Enumerating candidates

listTranslationCandidates() scans every configured non-source locale by default and returns active entries whose target value is missing. Pass targets to select exact translated, fuzzy, or obsolete entries for a re-run or review instead.

The source locale is never a translation target, including when it is named in an explicit locale request. Default enumeration skips a configured target whose catalog has not been created yet and emits a translation.missing_catalog diagnostic with locale and catalogPath; run pmds extract to create it. An explicitly requested missing target remains a hard read error so a caller cannot mistake an incomplete requested scope for an empty result.

Every candidate includes:

  • a stable identity consisting of catalog scope, locale, source message, and optional context;
  • a resolved target path and storage format;
  • singular content or structured top-level ICU plural branches;
  • extracted comments and a bounded origin list;
  • translated, fuzzy, and obsolete state;
  • native Ferrocat machine provenance when present; and
  • a per-entry fingerprint for optimistic concurrency control.

The fingerprint covers the candidate's source, current target, complete origin state, relevant metadata, and review state. The maxOrigins response limit only affects the displayed origin list, never the fingerprint. An unrelated entry can therefore be written in an earlier incremental batch without invalidating the remaining candidates.

Fingerprint payload changes are versioned. When upgrading across a fingerprint version, discard in-flight candidates and list them again before patching.

Exact reference hints

findTranslationReferences() finds existing translations with exactly the same source message, context, and target locale. The caller supplies the eligible reference facts and target identities; Core performs no catalog discovery, quality inference, fuzzy matching, remote requests, or automatic replacement. A context-free short label such as Open never matches a context-qualified entry. Locale tags and message text match exactly, without normalization.

To obtain translated facts from configured PO/FCL catalogs, pass known explicit reference identities to listTranslationCandidates({ config, targets }). Its default enumeration returns missing translations, so it does not supply a complete translated reference pool. The host must already know which catalog entries it wants to inspect and decide their eligibility. Review flags and machine metadata are available on those candidates; their absence or presence alone establishes no translation quality.

import {
  findTranslationReferences,
  listTranslationCandidates,
  type CatalogArtifactConfig,
  type TranslationCandidateId,
} from "@palamedes/core-node";

declare const config: CatalogArtifactConfig;

// These identities come from the host's selected reference entries.
const referenceIds: TranslationCandidateId[] = [
  { catalog: "shared/{locale}", locale: "de", message: "Open", context: "verb" },
];
const facts = listTranslationCandidates({ config, targets: referenceIds });
if (facts.diagnostics.length > 0) throw new Error("Reference catalogs need attention");
const hints = findTranslationReferences({
  references: facts.candidates.map(({ id, translation, origins }) => ({
    id,
    translation,
    origins,
  })),
  targets: [{ catalog: "app/{locale}", locale: "de", message: "Open", context: "verb" }],
  maxReferences: 5,
  maxOrigins: 3,
});

Each target has one result in request order, including empty results. Each hint contains the reference id (catalog, locale, source message, context), target translation, bounded sorted origins, matchKind: "exact", and a match explanation. References are ordered by catalog identity, excluding the target's own identity. maxReferences defaults to 5 and is capped at 20; maxOrigins defaults to 8. Zero limits return no hints or no origins respectively.

The native index validates each reference once with the existing ICU compatibility rules. Empty values, incompatible arguments or ICU structure, and duplicate reference identities are excluded with deterministic diagnostics; duplicates produce translation.duplicate_reference, empty values produce translation.empty_reference, and ICU findings retain their existing codes. References may add compatible target-language plural categories. Hints do not replace writeback validation or its fingerprint check.

Rust integrations can construct TranslationReferenceIndex::new(&references) and reuse references_for(&target, max_references, max_origins). This is a caller-owned snapshot: rebuild it when the selected catalog facts change. The Node batch API builds one index for all targets, avoiding a full reference scan per candidate. Neither API tracks catalog freshness automatically.

Applying completed translations

applyTranslationPatches() validates the complete request before writing any catalog. Unknown or ambiguous catalogs, unknown messages, duplicate identities, stale fingerprints, empty completed values, invalid ICU, and invalid provenance are returned as structured diagnostics with the rejected patch identity. A rejected validation batch leaves every original catalog unchanged. Source-locale patch identities are likewise rejected as translation.source_locale, before any catalog write.

Patch validation and auditCatalogs() share the same native ICU compatibility rules, including the runtime's apostrophe quoting policy. A missing argument such as Hello {name} → Hallo is rejected as icu.missing_argument before writeback. Plural translations may add target-language categories such as Russian few and many; variable names, argument kinds, plural offsets, required selectors (including exact-number selectors), and rich-text tags remain checked by Ferrocat. Repeated arguments in plain messages must retain their occurrence counts. Compatibility errors use the same icu.* codes and explanations as audit; audit warnings do not reject a patch. The singular/plural value variants describe the payload projection, not a separate compatibility rule. Completed plural branches must all be nonempty.

On success, Palamedes preserves unrelated translations, comments, origins, flags, obsolete entries, and PO headers. Each changed PO or FCL file is replaced atomically through Ferrocat's format-aware writer. A batch spanning several files has per-file atomicity; it is not a filesystem transaction across files. If a later replacement fails, the call still returns a hard error. Rust callers can recover the completed per-file outcomes from PalamedesError::translation_patch_result(); remaining patches are reported as notApplied. Node callers receive an Error with code ERR_PALAMEDES_TRANSLATION_PATCH_WRITE; its report property is the completed TranslationPatchResult, and its cause describes the failed catalog write. This remains an error rather than a successful partial result.

A patch without machine provenance is an authored completion and clears the entry's fuzzy marker, the way gettext tools do when a translator confirms a guessed entry; without it a fuzzy entry could never be finished through the API and stayed incomplete in coverage. A patch carrying machine provenance leaves review flags as they were — it records lock and ai instead. Every other flag is preserved in both cases, and setting review flags remains the caller's responsibility.

Provider-neutral TypeScript example

import {
  applyTranslationPatches,
  isTranslationPatchWriteError,
  listTranslationCandidates,
  type CatalogArtifactConfig,
  type TranslationPatch,
} from "@palamedes/core-node";

declare function completedSingular(source: string): string;
declare function completedPluralBranch(selector: string, source: string): string;

const config: CatalogArtifactConfig = {
  rootDir: process.cwd(),
  sourceLocale: "en",
  locales: ["en", "de"],
  catalogs: [
    {
      path: "src/locales/{locale}/messages",
      include: ["src"],
    },
  ],
};

const { candidates, diagnostics } = listTranslationCandidates({
  config,
  locales: ["de"],
  maxOrigins: 5,
});

if (diagnostics.length > 0) {
  throw new Error(diagnostics.map(({ message }) => message).join("\n"));
}

// A provider, translation memory, editor, or human review step can produce
// these completed values. Core only validates and persists them.
const patches: TranslationPatch[] = candidates.map((candidate) => ({
  id: candidate.id,
  fingerprint: candidate.fingerprint,
  translation:
    candidate.source.kind === "singular"
      ? { kind: "singular", value: completedSingular(candidate.source.value) }
      : {
          ...candidate.source,
          values: Object.fromEntries(
            Object.entries(candidate.source.values).map(([selector, source]) => [
              selector,
              completedPluralBranch(selector, source),
            ]),
          ),
        },
}));

let result;
try {
  result = applyTranslationPatches({ config, patches });
} catch (error) {
  if (isTranslationPatchWriteError(error)) {
    console.error(error.code, error.message, error.cause, error.report);
  }
  throw error;
}

if (result.diagnostics.length > 0) {
  // Re-enumerate stale candidates before retrying them.
  console.error(result.diagnostics);
}

When a machine produced a value, a patch can add native provenance without supplying its integrity lock. Core computes the lock from the completed value:

const patch: TranslationPatch = {
  id: candidate.id,
  fingerprint: candidate.fingerprint,
  translation: { kind: "singular", value: "Zur Kasse" },
  machine: {
    ai: { model: "example/model", confidence: 0.92 },
  },
};
Edit this page on GitHubLast updated: November 28, 2026