feat(IMP-12): Step 16/17 retry refinement — multi-donor + 3-stage salvage cascade

Extend Step 17 deterministic action surface so donor_slack_insufficient no longer
abort-terminates at zone_ratio_retry. AI is NOT invoked on the normal salvage path.

Source changes (4 files, scope-locked):
- src/phase_z2_retry.py — plan_zone_ratio_retry: single-primary-donor → multi-donor
  greedy aggregation (donors_used / aggregate_slack_used / aggregate_slack_available);
  new plan/apply pairs: cross_zone_redistribute (wraps fit_verifier.redistribute,
  data-role scoped CSS), glue_compression (wraps space_allocator.compute_glue_css_overrides,
  data-zone-position scoped), font_step_compression (wraps find_fitting_font_size,
  zone-scoped, defensive feasible=False on missing text_metrics).
- src/phase_z2_failure_router.py — classifier inspects salvage_steps[-1] via
  SALVAGE_FAILURE_TYPE_BY_ACTION; NEXT_ACTION_BY_FAILURE rewired into
  donor_slack_insufficient/no_donor_candidates → cross_zone_redistribute → glue
  → font_step → layout_adjust; 3 IMPLEMENTED salvage status rows added.
- src/phase_z2_router.py — ACTION_IMPLEMENTATION_STATUS registers 3 new salvage
  actions as IMPLEMENTED; ACTION_BY_CATEGORY untouched (cascade-only labels).
- src/phase_z2_pipeline.py — new _attempt_salvage_chain() iterates router
  next_proposed_action with retry_budget=1 per action; honors IMP-09 dynamic_cols
  / fr_default gate; preserves (b)-revert on all-fail; wires Step 17 telemetry
  (salvage_steps / salvage_passed).

Tests (6 new pytest modules):
- test_phase_z2_retry_multi_donor.py — single sufficient (regression), 1st
  insufficient + 2nd sufficient (multi-donor PASS), aggregate insufficient FAIL.
- test_phase_z2_cross_zone_redistribute.py — multi-role zone feasible,
  single-role zone short-circuits infeasible.
- test_phase_z2_glue_compression.py — feasible asserts emitted CSS contains
  [data-zone-position=...] selector and NO global :root/body/.slide rule.
- test_phase_z2_font_step_compression.py — 15.2 → 13 closes excess; 8px floor;
  missing text_metrics → defensive infeasible reason.
- test_phase_z2_failure_router_cascade.py — donor_slack_insufficient → cross_zone
  (impl=IMPLEMENTED); 3 new failure types → expected next actions; rerender_still_fails
  preserves frame_reselect terminus.
- test_phase_z2_step17_salvage_chain.py — end-to-end (a) cross_zone PASS promotes
  final.html, (b) cross_zone FAIL + glue PASS promotes 2nd candidate, (c) all-3
  FAIL preserves original final.html (revert).

Guardrails preserved:
- AI calls: 0 on normal path (feedback_ai_isolation_contract)
- Spacing direction: no shrink-common-margin; resolve via donor/glue/font-step
  within frame envelope (feedback_phase_z_spacing_direction)
- All CSS overrides scoped to [data-role=...] or [data-zone-position=...]
- IMP-09 dynamic_cols / fr_default gate honored in cascade
- (b)-revert preserved if all 3 salvage actions fail

Refs: gitea#12 IMP-12

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-18 02:07:22 +09:00
co-authored by Claude Opus 4.7
parent a79bd8bc43
commit 56619a0239
10 changed files with 1246 additions and 39 deletions
+207 -13
View File
@@ -162,35 +162,55 @@ def plan_zone_ratio_retry(
),
}
# A3 minimal : single primary donor (multi-donor 는 future)
primary_donor = donor_candidates[0]
if primary_donor["slack"] < target_added_px:
# IMP-12 u1 : multi-donor greedy aggregation (slack-desc 순서대로 합산)
aggregate_slack_available = sum(d["slack"] for d in donor_candidates)
if aggregate_slack_available < target_added_px:
return {
**base_plan,
"feasible": False,
"donor_zone_position": primary_donor["position"],
"donor_max_slack": primary_donor["slack"],
"donor_zone_position": donor_candidates[0]["position"],
"donor_max_slack": donor_candidates[0]["slack"],
"donor_reduced_px": 0,
"donors_used": [],
"aggregate_slack_used": 0,
"aggregate_slack_available": aggregate_slack_available,
"zones_after": dict(zones_before),
"failure_reason": (
f"primary donor '{primary_donor['position']}' slack {primary_donor['slack']}px "
f"< target_added_px {target_added_px}px (excess_y {target_excess_y} + "
f"safety_margin {safety_margin_px}). multi-donor aggregation is future axis."
f"primary donor '{donor_candidates[0]['position']}' slack "
f"{donor_candidates[0]['slack']}px (aggregate "
f"{aggregate_slack_available}px across {len(donor_candidates)} "
f"candidate(s)) < target_added_px {target_added_px}px "
f"(excess_y {target_excess_y} + safety_margin {safety_margin_px})."
),
}
# feasible
# feasible — greedy aggregation: 각 donor 에서 필요한 만큼만 차감
zones_after = dict(zones_before)
zones_after[target_zone_position] = zones_before[target_zone_position] + target_added_px
zones_after[primary_donor["position"]] = (
zones_before[primary_donor["position"]] - target_added_px
)
donors_used: list[dict] = []
remaining = target_added_px
for donor in donor_candidates:
if remaining <= 0:
break
take = min(donor["slack"], remaining)
zones_after[donor["position"]] = zones_before[donor["position"]] - take
donors_used.append({
"position": donor["position"],
"reduced_px": take,
"slack_before": donor["slack"],
"slack_after": donor["slack"] - take,
})
remaining -= take
primary_donor = donors_used[0]
return {
**base_plan,
"feasible": True,
"donor_zone_position": primary_donor["position"],
"donor_reduced_px": target_added_px,
"donor_reduced_px": primary_donor["reduced_px"],
"donors_used": donors_used,
"aggregate_slack_used": target_added_px,
"aggregate_slack_available": aggregate_slack_available,
"zones_after": zones_after,
}
@@ -213,3 +233,177 @@ def apply_retry_to_layout_css(layout_css: dict, plan: dict, zones_data: list[dic
new_layout_css["raw_zone_layout"] = (layout_css.get("raw_zone_layout") or {}).copy()
new_layout_css["raw_zone_layout"]["retry_applied"] = True
return new_layout_css
# ──────────────────────────────────────
# IMP-12 u4 : cross_zone_redistribute (Step 17 salvage cascade — stage 1)
# Wraps src.fit_verifier.redistribute in the Step-17 plan signature so the
# failure-router cascade (donor_slack_insufficient → cross_zone_redistribute)
# can drive it deterministically. Plan-only — no rerender / no final.html
# mutation. Side-effect-free (operates on deepcopy of fit_analysis).
# ──────────────────────────────────────
def plan_cross_zone_redistribute(
*,
fit_analysis,
containers: dict,
min_margin_px: float | None = None,
) -> dict:
"""Cross-zone (intra-zone role-to-role) redistribute plan.
Plan-only — no rerender / no final.html mutation. Side-effect-free
(operates on deepcopy of fit_analysis).
"""
from copy import deepcopy
from src.fit_verifier import redistribute as _fv_redistribute
role_heights_before = {
role: float(rf.allocated_px) for role, rf in (fit_analysis.roles or {}).items()
}
base_plan = {
"action": "cross_zone_redistribute",
"role_heights_before": role_heights_before,
}
if not role_heights_before:
return {**base_plan, "feasible": False, "role_heights_after": {},
"can_redistribute": False,
"failure_reason": "no roles in fit_analysis — cannot redistribute."}
result = _fv_redistribute(deepcopy(fit_analysis), containers, min_margin_px=min_margin_px)
redistribution = dict(result.redistribution or {})
can_redistribute = bool(result.can_redistribute)
if not can_redistribute or not redistribution:
return {
**base_plan,
"feasible": False,
"role_heights_after": redistribution or dict(role_heights_before),
"can_redistribute": can_redistribute,
"failure_reason": (
"fit_verifier.redistribute can_redistribute=False — single-role zone(s) "
"or surplus insufficient to cover deficit within envelope."
),
}
return {**base_plan, "feasible": True, "role_heights_after": redistribution,
"can_redistribute": True}
def apply_cross_zone_redistribute_css(plan: dict) -> str:
"""Emit scoped role-height CSS overrides — [data-role="<role>"] only.
Honors feedback_phase_z_spacing_direction: no :root / body / .slide / .zone selectors.
"""
if not plan.get("feasible"):
return ""
role_heights_after = plan.get("role_heights_after") or {}
role_heights_before = plan.get("role_heights_before") or {}
rules: list[str] = []
for role, new_height in role_heights_after.items():
before = role_heights_before.get(role)
if before is None or abs(float(before) - float(new_height)) < 0.5:
continue
new_h_int = int(round(float(new_height)))
rules.append(
f'[data-role="{role}"] {{ height: {new_h_int}px; min-height: {new_h_int}px; }}'
)
return "\n".join(rules)
# IMP-12 u5 : glue_compression — Step 17 salvage cascade (stage 2).
# Wraps space_allocator.compute_glue_css_overrides in the Step-17 plan signature.
# Frame-scoped: overrides emitted only under [data-zone-position="<pos>"]
# (feedback_phase_z_spacing_direction — no :root/body/.slide/.zone mutation).
def plan_glue_compression(
*, excess_px: float, block_count: int, zone_position: str,
) -> dict:
"""Glue compression plan (frame-scoped). feasible only when envelope absorbs excess."""
from src.space_allocator import (
calculate_glue_absorption, compute_glue_css_overrides,
)
base = {"action": "glue_compression", "zone_position": zone_position,
"excess_px": float(excess_px), "block_count": int(block_count)}
if excess_px <= 0:
return {**base, "feasible": False, "overrides": {}, "absorption_max_px": 0.0,
"failure_reason": "excess_px <= 0 — no compression needed."}
absorption_max = float(calculate_glue_absorption(block_count))
overrides = compute_glue_css_overrides(excess_px, block_count) or {}
if excess_px > absorption_max:
return {**base, "feasible": False, "overrides": overrides,
"absorption_max_px": absorption_max,
"failure_reason": (
f"glue envelope insufficient — excess_px {excess_px:.1f} > "
f"max absorption {absorption_max:.1f}px "
f"(block_count={block_count}, SPACING_GLUE shrink budget)."
)}
return {**base, "feasible": True, "overrides": overrides,
"absorption_max_px": absorption_max}
def apply_glue_compression_css(plan: dict) -> str:
"""Emit zone-scoped glue CSS — wrapped in [data-zone-position="<pos>"] only."""
if not plan.get("feasible"):
return ""
zone_position = plan.get("zone_position")
overrides = plan.get("overrides") or {}
if not zone_position or not overrides:
return ""
var_lines = "\n".join(f" {k}: {v};" for k, v in overrides.items())
return f'[data-zone-position="{zone_position}"] {{\n{var_lines}\n}}'
# IMP-12 u6 : font_step_compression — Step 17 salvage cascade (stage 3).
# Wraps space_allocator.find_fitting_font_size in the Step-17 plan signature.
# Zone-scoped: only [data-zone-position="<pos>"] (no :root/body/.slide/.zone).
def plan_font_step_compression(
*, current_font_px: float, excess_after_glue_px: float,
available_lines: int, chars_per_line: int, zone_position: str,
) -> dict:
"""Font-step compression plan (zone-scoped). feasible only when FONT_SIZE_STEPS
contains a size whose line-height savings cover excess_after_glue_px. Missing
text_metrics yields feasible=False (cascade routes onward to layout_adjust)."""
from src.space_allocator import FONT_SIZE_STEPS, find_fitting_font_size
floor = float(FONT_SIZE_STEPS[-1])
base = {"action": "font_step_compression", "zone_position": zone_position,
"current_font_px": float(current_font_px),
"excess_after_glue_px": float(excess_after_glue_px),
"available_lines": int(available_lines or 0),
"chars_per_line": int(chars_per_line or 0),
"font_floor_px": floor}
if excess_after_glue_px <= 0:
return {**base, "feasible": False, "target_font_px": None,
"failure_reason": "excess_after_glue_px <= 0 — no font compression needed."}
if not available_lines or available_lines <= 0 or not chars_per_line or chars_per_line <= 0:
return {**base, "feasible": False, "target_font_px": None,
"failure_reason": "text_metrics missing — available_lines/chars_per_line required."}
if current_font_px <= floor:
return {**base, "feasible": False, "target_font_px": None,
"failure_reason": (
f"current_font_px {current_font_px:.1f} already at FONT_SIZE_STEPS floor {floor:.1f}px.")}
target = find_fitting_font_size(
current_font_px=float(current_font_px),
excess_after_glue_px=float(excess_after_glue_px),
available_lines=int(available_lines), chars_per_line=int(chars_per_line))
if target is None:
return {**base, "feasible": False, "target_font_px": None,
"failure_reason": (
f"font_step floor — {floor:.1f}px cannot absorb "
f"excess_after_glue_px={excess_after_glue_px:.1f}px "
f"(available_lines={available_lines}, FONT_SIZE_STEPS exhausted).")}
return {**base, "feasible": True, "target_font_px": float(target)}
def apply_font_step_compression_css(plan: dict) -> str:
"""Emit zone-scoped font-size CSS — [data-zone-position="<pos>"] only."""
if not plan.get("feasible"):
return ""
zone_position = plan.get("zone_position")
target_font_px = plan.get("target_font_px")
if not zone_position or target_font_px is None:
return ""
return (f'[data-zone-position="{zone_position}"] {{\n'
f" font-size: {float(target_font_px):.1f}px;\n}}")