DMC-RELKEY-C0-S3A -- Relation-Key Identity Slice 3a: Lookup enrichment, duplicate, and mismatch delegation
=============================================================================================================

AUTHORITY
---------
Implement ONLY the accepted Slice 3a of the Relation-Key Identity Cycle-0
design. The architecture authority is the `relation_key_cycle0_assessment`
component (the corrected, independently accepted assessment), specifically
its "Slice 3a -- Lookup enrichment, duplicate, and mismatch delegation"
section and its "Lookup and pandas boundary" section, together with
`relation_key_cycle0_delta_rereview` (the closing delta re-review; read its
F1/F2 dispositions and W2 -- the Number/DateTime implementation traps apply
here exactly as they did to Slice 1/2, because Slice 3a calls the same owner,
it does not reimplement any part of it). The already-accepted Slice-1 owner
is authority for what you consume, not something you may change:
`relation_key_slice1_acceptance` records verdict A ("SLICE 1 ACCEPTED",
commit `efe3187b1095e97d3840670d258535ff67948ab1`) for
`src/spreadsheet_handling/domain/relation_keys.py` and
`tests/unit/domain/test_relation_keys.py`. `relation_key_slice2_acceptance`
records verdict A ("SLICE 2 ACCEPTED", commit `6ade55a66138881024b7684ba9f2769a28c834ef`)
for the sibling FK delegation slice; read it as a *pattern precedent* only
(the FK/Lookup layer split, the `_helper_payload_comparison_value`-style
naming discipline for a payload contract kept separate from relation-key
identity) -- it does not authorize touching any FK file, and Slice 3a's own
pandas boundary differs from Slice 2's `HelperValueProvider` seam because
Lookup has no analogous Core module to delegate through (see PANDAS-BOUNDARY
DESIGN AUTHORITY below). The `dmc_contract` component is the governing
procedure. Do not treat this task.txt as a substitute for reading those
components in full before editing.

CONCERN
-------
Make the maintained Lookup path (`add_lookup_helpers` / `enrich_lookup`)
consume the Slice-1 relation-key semantic owner
(`spreadsheet_handling.domain.relation_keys`) instead of independently
interpreting relation-key identity through raw pandas mechanics:

* Lookup value-mode enrichment (`enrich_lookup` in
  `enrich_lookup/operation.py`) currently joins the source and lookup frames
  with a raw `source_df.merge(helper_cols, on=source_keys, how="left")`
  (`operation.py:188`). This must instead match rows by owner-defined
  relation-key identity: Missing source/target key components must never
  resolve a match (currently `""`/`""` and `None`/`None` both resolve --
  this must stop), mixed-category pairs (`1`/`"1"`, `True`/`1`) must never
  resolve, integral Number carrier differences (`1`, `1.0`,
  `numpy.int64(1)`) must resolve, and exact-String whitespace must matter
  (`" 1 "` must not resolve against `"1"`). A raw pandas dtype error must
  never leak as the outcome for a mixed-dtype join; the existing
  `missing="fail"`/`"empty"` policy in `_check_unmatched_rows` must keep
  working exactly as today against whichever eligible keys the owner
  actually resolves.
* Duplicate lookup-key detection (`_lookup_frame_has_duplicate_keys` in
  `enrich_lookup/policy.py:61`) currently uses raw
  `lookup_df.duplicated(subset=join_keys, keep=False).any()`. This single
  shared predicate is consumed by both `operation.py`'s raising
  `_check_duplicate_lookup_keys` (enrichment time) and `mismatch.py`'s
  non-raising unverifiable-duplicate-keys check (mismatch-evaluation time);
  delegating it once delegates both call sites. It must count only eligible
  owner-defined relation keys: repeated Missing target rows must stop being
  reported as duplicate, mixed Number/String must never collapse into a
  duplicate, and eligible Number/String/Boolean duplicates must still be
  found exactly as today for same-category pairs.
* Lookup mismatch verification (`enrich_lookup/mismatch.py`) currently uses
  one private `_norm(value) -> str | None` (`mismatch.py:247`) for two
  unrelated purposes: (a) building the payload/lookup key tuples used to look
  rows up in the canonical value map (`mismatch.py:211,242` -- this is
  relation-key *identity* and must delegate to the owner), and (b) comparing
  a materialized helper cell's displayed value against the target row's
  stored field value (`mismatch.py:229` -- this is the Lookup-owned
  *helper-payload* contract described in the module's own docstring, and is
  explicitly NOT relation-key identity per the assessment's disposition
  table). These two uses must be split under distinct names; the payload
  comparison may keep its current `str(value).strip()` shape but must not
  keep the name `_norm` or otherwise imply it is the same operation as the
  relation-key delegation, per the Local Human Readability requirement below.
* Add the truthful Lookup behavior-change release-note bullet under the
  active unreleased section (`== unknown -- planned`) of
  `docs/release_notes/release_notes.adoc`.

PANDAS-BOUNDARY DESIGN AUTHORITY
---------------------------------
Unlike FK (Slice 2), Lookup has no Core module and no existing
provider-injection seam to delegate through -- `enrich_lookup` performs its
own `DataFrame.merge` and `DataFrame.duplicated` directly in Domain. The
assessment's "Lookup and pandas boundary" section is therefore the operative
design authority for Slice 3a specifically, and states:

    `DataFrame.merge` is acceptable only after the Domain rule has determined
    the join representation and eligibility. ... It may create temporary
    internal join values and use `merge`, or use an owner-keyed mapping. This
    assessment does not create a generic DataFrame normalization framework
    and does not make any temporary token part of the public Domain contract.

This authorizes, but does not mandate, an implementation shape where Domain
computes an owner-derived `RelationKeyIdentity` per row for the configured
join key column(s) on both frames, holds it in a temporary internal join
column (or an owner-keyed mapping used the same way), performs the join or
lookup against that temporary representation, and then drops it before the
result is returned. Any such temporary column/representation is pure
mechanics: it must never appear in `out[output]`, in `_meta` provenance, or
in any other caller-visible surface, and it must not survive into the
existing `enriched.where(pd.notnull(enriched), "")` Missing-rewrite step
(`operation.py:209`) in a way that widens B-2 (see EXPLICIT NON-SCOPE). Do
not build a general DataFrame/Domain-key normalization helper reusable
outside `enrich_lookup`; the smallest local mechanism that satisfies the
required semantics is what the assessment authorizes here.

REQUIRED SEMANTICS (see the assessment component for the full contract)
-------------------------------------------------------------------------
Lookup enrichment, Lookup duplicate checking, and Lookup mismatch
verification must agree on the same owner-defined relation-key identity for
the deterministic five-pair matrix:

    " 1 " / "1"   -> unequal (no trim; exact String)
    1 / "1"       -> unequal (distinct categories; no text-token coercion)
    1.0 / 1       -> equal (one Number category, exact represented value)
    "" / ""       -> ineligible (Missing; never a key)
    None / None   -> ineligible (Missing; never a key)

Required consequences:

* exact String whitespace matters -- no `.strip()` anywhere in relation-key
  identity (enrichment matching, duplicate checking, mismatch key lookup);
* Number and String remain distinct; Boolean and Number remain distinct
  (`True` is not `1`) -- this is an explicit Lookup compatibility break per
  the assessment's compatibility table (current pandas Lookup resolution and
  duplicate mechanics can collapse `True`/`1` today);
* integral Number carrier differences resolve/duplicate as one key (`1`,
  `1.0`, `numpy.int64(1)` agree);
* Missing (`None`, `""`, NaN, `pandas.NA`, `NaT`) never participates as a
  relation key on either the source or the target side -- this is
  *participation*, not row validity: source-side unmatched behavior remains
  governed entirely by Lookup's existing `missing="empty"`/`"fail"` policy
  (this slice adds no new Lookup-side "invalid key" finding), and Missing
  target values are simply excluded from the join/duplicate representation;
* mixed pandas dtypes must not produce a pandas dtype error where the owner
  rule provides a deterministic result -- Lookup routes the outcome through
  its existing `missing` policy instead;
* helper-payload comparison (does the materialized helper cell's displayed
  value match the target row's stored field value) remains Lookup-owned,
  local, explicit mechanics, split from and not named like the relation-key
  delegation above;
* original source/target key carrier columns are unchanged by this slice --
  any temporary internal join representation is dropped before output.

Local Human Readability (per the DMC and the Slice-1/Slice-2 precedent):
every call site that now delegates to the owner must import or call a name
containing `relation_key`, with a comment stating why local pandas/string
equality is insufficient. Names such as `_norm`, `_norm_key`, `_plain`,
`_token`, or `_coerce` alone do not satisfy this and must not survive as the
identity interpreter (they may survive only for the distinct, locally-owned
helper-payload-comparison contract described above, under a name that does
not imply relation-key identity).

EXPLICIT NON-SCOPE
------------------
Do not, under this WorkItem:

* modify `src/spreadsheet_handling/domain/relation_keys.py` or
  `tests/unit/domain/test_relation_keys.py` -- Slice 1 is independently
  accepted and closed; this WorkItem is a pure consumer;
* modify any Slice-2 FK file
  (`domain/transformations/fk_helpers/enrich.py`,
  `domain/transformations/fk_helpers/value_provider.py`,
  `domain/validations/fk_helpers.py`, or their tests) -- Slice 2 is
  independently accepted and closed;
* modify `src/spreadsheet_handling/core/fk.py` or any other `core/` module;
* modify `enrich_lookup/provenance.py` -- it interprets stored provenance
  shape only and performs no key-identity comparison; preparation-time
  inspection found no relation-key logic there;
* modify `src/spreadsheet_handling/domain/transformations/derived_column_policy.py`
  (DCP) production code -- DCP delegates entirely to
  `evaluate_lookup_mismatches`/`interpret_written_enrich_lookup_provenance`
  from the `enrich_lookup` package and owns no key-identity interpretation of
  its own; only `tests/unit/domain/transformations/test_derived_column_policy.py`
  is in scope, because its fixtures exercise `evaluate_lookup_mismatches`
  indirectly and may need updated expectations for the new mismatch-key
  identity. If implementation genuinely finds a DCP production change
  necessary, STOP and escalate rather than silently widening scope;
* change formula-mode authoring (`_build_formula_enrichment` in
  `operation.py`) or its `LookupFormulaSpec` structural-mismatch comparison
  in `mismatch.py` -- formula mode authors backend-neutral formula Intent
  rather than performing Domain resolution and is explicitly unchanged by
  this cycle; the *duplicate-key* check that gates formula-mode authoring
  (`_check_duplicate_lookup_keys`, shared with value mode) is in scope, but
  the formula-authoring/structural-comparison logic itself is not;
* migrate or modify reference or graph validation
  (`domain/validations/reference_validations.py`,
  `domain/validations/graph_validations.py`) -- Slice 3b;
* touch canonical Semantic Model, Technical Model, or any other canonical
  documentation surface -- Slice 4;
* widen or rename any public/helper surface, change the `_meta.helper_
  policies.lookup` contract or Lookup provenance shape, or register a new
  pipeline step;
* implement a general scalar normalizer, general tuple-uniqueness identity,
  or any Number/DateTime normalization API beyond what the accepted Slice-1
  owner already exposes;
* fix the known B-2 whole-frame Missing rewrite
  (`enriched.where(pd.notnull(enriched), "")`, `operation.py:209`) -- it
  remains FOLLOW-UP. Ensure any temporary internal join column this slice
  introduces is dropped before that rewrite runs (or is otherwise excluded
  from it), so the rewrite's existing scope is not made more invasive, but
  do not attempt to fix the rewrite itself;
* redesign Lookup output/carrier policy generally, beyond what exact
  relation-key delegation requires;
* decide the public FK/Lookup helper-surface consolidation FTR
  (`FTR-FK-REFERENCE-HELPER-SURFACE-CONSOLIDATION-P5`);
* touch Project Memory;
* touch the Workflow Coordinator, the Runtime, or any other WorkItem's
  artifacts; and
* touch Slices 3b or 4 in any form.

If correct Slice-3a implementation mechanics genuinely require touching a
file not named in `authorized_scope`, do not silently add it: stop and
escalate (report the need and rationale) rather than expanding scope.

Also inspect the known unmatched-row / Missing-payload distinction recorded
by the accepted review (an unresolved payload row -- its join-key value has
no match in the current lookup frame -- is left unchecked by mismatch
verification, matching current, deliberately preserved behavior). Do not
accidentally entrench or broaden that separate issue while changing key
identity; it is orthogonal to this slice.

REVIEW / FINDING CHOREOGRAPHY
-----------------------------
An implementation that meets the accepted contract may be accepted without a
Finding:

    implement -> review -> accept

The fresh gate reviewer writes the required review artifact and may open a
new blocking Finding only for a real remaining defect against the accepted
Cycle-0 contract and this task's bounded scope; do not manufacture one. In
that case return `outcome: changes_required` and request `correct`:

    implement -> review -> correct -> rereview -> accept

The corrector may cite or add evidence to an existing Finding but must not
resolve, residualize, supersede, reopen, or otherwise dispose of it. After a
completed correction, request `rereview`.

The fresh gate rereviewer may resolve an open blocking Finding only when the
correction establishes closure, then request `accept`. If a blocker remains,
return `changes_required` and request `correct`; the four-Hop budget, not an
invented retry, controls whether another correction can run.

CORRECTION AUTHORITY
---------------------
If and only if the fresh review finds a REAL remaining Slice-3a semantic or
scope defect, `correct` may mutate only:

    src/spreadsheet_handling/domain/transformations/enrich_lookup/operation.py
    src/spreadsheet_handling/domain/transformations/enrich_lookup/policy.py
    src/spreadsheet_handling/domain/transformations/enrich_lookup/mismatch.py
    tests/unit/domain/transformations/test_enrich_lookup.py
    tests/unit/domain/transformations/test_derived_column_policy.py
    docs/release_notes/release_notes.adoc

No other production path. No amend/rewrite of any existing commit. No later
Relation-Key slices.

VALIDATION
----------
Before claiming implementation or correction success, run at least:

    python -m pytest -q tests/unit/domain/transformations/test_enrich_lookup.py
    python -m pytest -q tests/unit/domain/transformations/test_derived_column_policy.py
    git diff --check

Report results truthfully. The only trusted evidence providers selected by
this profile are `diff_hygiene`, `git_version`, `pytest_enrich_lookup`, and
`pytest_derived_column_policy`. Both named test files pass on the unmodified
baseline (186 tests total: 62 in `test_enrich_lookup.py`, 124 in
`test_derived_column_policy.py`); implementation and correction must not
reduce that count without an explicit, justified rationale in the commit or
review artifact.

AGENT GIT RULE
--------------
Core's general commit-identity guidance
(`docs/ai_info/git_and_workflow.adoc`, "DMC-family commit identity") is a
traceability *recommendation*, not a binding rule.

For any commit the Coordinator creates under this WorkItem, the only
requirement is a valid, single-line, Conventional-Commit-compatible subject
that contains both this WorkItem's ID and the current Hop ID as identity
tokens, e.g.:

    feat(DMC-RELKEY-C0-S3A): delegate Lookup relation identity H001
    docs(DMC-RELKEY-C0-S3A): record Slice 3a review H002

This is exactly what Runtime `ec397b6`'s `commit_subject_error` mechanically
enforces (Conventional-Commit subject shape plus WorkItem/Hop token
presence); it requires no body and no trailers. Do not invent a new
commit-identity mechanism or validator, and do not require a multiline commit
body.
