⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
xxg-portrait-rebuild-light
Edit an existing JPG, JPEG, PNG, or WebP portrait to rebuild physically coherent light, exposure, color, capture style, clean optical skin, and frame quality without changing the person. Use for plastic-skin or AI-look removal, dirty synthetic texture, banding, edit seams, color drift, multi-round quality loss, tone or white-balance correction, camera/film/device emulation, backlight, prism, blind shadows, candlelight, neon, golden hour, rim light, rain-wet low key, studio light, or silhouettes.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
xxg-portrait-rebuild-light is an image-edit skill for existing portraits. V2.3 separately controls physical light, exposure placement, color/style grade, capture-device response, broad skin tone, bounded reflection, scale/focus-aware microdetail, and AI-generation quality repair.
The skill changes the lighting without redrawing the person. It preserves identity, facial structure and proportions, natural slight asymmetry, expression, pose, camera view, and composition. It avoids plastic skin, grainy skin, dirty color variation, and fake depth made by exaggerating wrinkles.

Key features
- Provides
texture-onlyfidelity recovery without changing source lighting, color, focus, depth of field, or scene content. - Repairs plastic smoothness by separating clean broad tone, source-shaped highlights, and scale/focus-aware regional microdetail.
- Adds seven skin-finish profiles (
P0–P6) for source-matched, satin-matte, soft-daylight, editorial, direct-flash, beauty, and available-light response. - Adds
E0–E7exposure recipes that explicitly place highlight headroom, facial midtones, directional shadows, and black point. - Adds
G0–G8color/style grades andD0–D8capture profiles for full-frame digital, medium format, 35mm negative, CCD compact, point-and-shoot flash, smartphone, instant film, and disposable-camera response. - Separates device response from optics: camera-style edits preserve viewpoint, perspective, crop, focal plane, and depth of field unless optical restyle is explicitly requested.
- Repairs weak backlighting, disconnected indoor window light, flat lighting, unintended crushed shadows, and highlights with no physical source.
- Supports soft window light, commercial soft light, Rembrandt lighting, cinematic low-key lighting, golden hour, dual-color neon, and diagonal hard light.
- Adds at most one physically coherent atmosphere effect, including prism refraction, blind/lattice shadow lines, rain-wet reflections, window/tree shadow, bokeh, sunset flare, volumetric light, or a full-black silhouette.
- Adds dedicated candle/flame and rim-led portrait keys with realistic falloff, edge placement, and restrained fill.
- Adds
Q0–Q6quality recipes for synthetic dirt/grid patterns, banding, edit seams, color drift, and cumulative multi-round degradation. - Uses the first root base—not the previous edit round—as the stable color/identity reference, while retaining intentional new colors and authorized lighting or grading.
- Repairs only observed artifacts and preserves pores, hair, directional fibers, fabric weave, edges, shadow boundaries, and source focus falloff.
- Controls subject and background in layers: key light and exposure intent first, then fill, shadows, ambient light, and color temperature.
- Preserves identity, facial feature size and position, expression, pose, wardrobe, background structure, and source framing.
- Reduces the skin-detail target automatically when the face is small, without canceling the requested lighting change.
- Uses the current agent's own image-generation or image-editing capability by default; no separate API is required.
- If the current agent has no image-edit capability, or the edit misses the target, returns one complete compact image-edit prompt.
- Never uses Pillow, NumPy, OpenCV, ImageMagick, or temporary filter scripts to produce the delivered image.

Core method
The skill first makes a director-style lighting decision internally:
Scope → Key L → Exposure E → Fill/Shadow → Skin S/P → Light color T → Look G → Capture D → Atmosphere A → Quality Q
The prompt sent to the image model uses four compact core lines, adding RENDER only for a requested grade/device response and QUALITY only for an observed repair target. Target length is 55–110 English words:
EDIT: Choose the smallest authorized scope; retain source identity, geometry, pose, camera view, optics, framing, and every unauthorized axis.
LIGHT: One L and E with explicit highlight, midtone, shadow, black-point, background, T, and optional A behavior.
RENDER: One G palette/curve plus one D capture response. Omit for G0 + D0.
SKIN: One scale-aware S plus one light-consistent P finish.
QUALITY: One observed Q repair; omit for Q0.
AVOID: Only two or three source-specific failures.
The skill does not pile identity audits, object inventories, repeated negatives, and several photographic styles into one prompt. That often causes constraints to cancel each other or produces an unchanged copy.
For skin-only requests, V2.3 forces L0 + E0 + T0 + G0 + D0 + A0 + Q0. Tone correction changes only E/T/G; capture-style changes only G/D and a logically required E; relighting changes L/E/T/A; quality repair changes only Q. Viewpoint, perspective, crop, focal plane, and depth of field stay source-matched unless the user explicitly requests optical-restyle.
A6 forces E6 silhouette exposure, moves the effective light behind the person, removes all fill and catchlights, and renders the subject interior black. L/T and any G/D treatment affect only the rear source and background; S/P are suppressed.
Recipes
Choose only:
one L light + one E exposure + one S skin scale + one P skin finish + one T light color + one G color/style grade + one D capture response + zero or one A atmosphere + one Q quality repair
Lighting L
| Code | Purpose |
|---|---|
L0 | Match the source; repair only flat light, unexplained crushed shadows, abnormal highlights, and harsh transitions |
L1 | Natural backlight, highlight-priority by default; add fill only when explicitly requested |
L2 | Soft natural window light |
L3 | Large commercial soft light |
L4 | Outdoor skylight |
L5 | Indoor practical and mixed lighting |
L6 | Hard single-point light or direct sunlight |
L7 | Low-key diagonal narrow light beam |
L8 | Classic editorial Rembrandt lighting |
L9 | Cinematic low-key warm key / cool ambient light |
L10 | Golden-hour sunset side backlight |
L11 | Cyberpunk cyan/magenta dual-tone neon |
L12 | Clean, even commercial soft light |
L13 | Candle or flame near-field key with rapid falloff |
L14 | Rim-led dramatic portrait light with restrained frontal fill |
Exposure E
| Code | Purpose |
|---|---|
E0 | Preserve source highlights, midtones, shadows, and black point |
E1 | Balanced natural exposure with clear midtones and directional shadows |
E2 | Protect a bright source/rim and let unlit planes follow available bounce |
E3 | Recover only blocked shadow information while controlling bright sources |
E4 | High-key exposure with textured whites and gentle facial modeling |
E5 | Low-key exposure with selected lit planes and a clean black point |
E6 | Full |
// HOW IT'S BUILT
// FILES
35 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md16 KB4d675127f9c6upstream ↗
--- name: xxg-portrait-rebuild-light description: "Edit an existing JPG, JPEG, PNG, or WebP portrait to rebuild physically coherent light, exposure, color, capture style, clean optical skin, and frame quality without changing the person. Use for plastic-skin or AI-look removal, dirty synthetic texture, banding, edit seams, color drift, multi-round quality loss, tone or white-balance correction, camera/film/device emulation, backlight, prism, blind shadows, candlelight, neon, golden hour, rim light, rain-wet low key, studio light, or silhouettes." --- # XXG Portrait Rebuild Light V2.3 ## Objective Treat the input as the same photograph, never as a reference for a replacement portrait. Improve illumination, exposure, color rendering, capture character, skin response, and generation quality while retaining identity, facial geometry and natural asymmetry, expression, pose, camera view, framing, and subject scale. Preserve source optics unless the user explicitly requests an optical restyle. Build realism from three separable signals: 1. clean low-frequency skin tone and broad transitions; 2. source-driven diffuse/specular response with highlights confined to plausible light-facing areas; 3. fine, region-specific microdetail limited by face scale, focus, and illumination. Do not manufacture realism with dirt, darkness, coarse pores, uniform grain, random color patches, or exaggerated facial lines. The result must first read as a clean photograph at normal size. ## Choose the Edit Scope - **`texture-only`**: when the user asks only to remove plastic/AI skin or recover detail, force `L0 + E0 + T0 + G0 + D0 + A0 + Q0`. Preserve the source lighting, highlight placement, exposure, white balance, focal plane, depth of field, and background. - **`tone-and-exposure`**: when the user asks for brightness, highlight/shadow recovery, white balance, palette, or grading without new lighting, preserve the source light direction and edit only E/T/G. - **`relight-and-skin`**: when the user requests a lighting change or selects L/T/A, authorize the requested light response while preserving source focal plane and depth of field unless explicitly changed. - **`capture-style`**: when the user requests a camera, film, phone, CCD, or era look, edit G/D and only the exposure behavior logically required by that capture; preserve viewpoint, crop, focal plane, and depth of field. - **`optical-restyle`**: only when the user explicitly requests a different focal-length perspective, camera angle, aperture behavior, or depth of field. State that axis once and permit only the minimum framing/background reconstruction it requires. - **`quality-repair`**: when the user asks to remove dirty synthetic patterns, banding, posterization, seams, halos, or other generation residue, edit only Q and preserve light, color, structure, optics, and natural texture. - **`base-color-repair`**: when an edited result has an unintended cast, use the original root base to restore only unchanged or unauthorized color relationships; preserve deliberate recolors and requested E/T/G/A changes. - **`multi-round-repair`**: when repeated edits accumulate tint, noise, sharpening, compression, banding, or seams, use the latest accepted edit as the target and the first root base as the stable identity/geometry/color reference. Never let texture repair become relighting, tone correction become a new light source, device emulation become a new pose/viewpoint, or quality cleanup become global smoothing or an unauthorized regrade. ## Use the Host Image Editor 1. Inspect the source and read the host's native image-generation or image-editing skill. 2. Discover the actual callable in the tool registry. In Codex, inspect `ALL_TOOLS` and prefer the exact discovered name `image_gen__imagegen`. 3. For a local source in Codex, use the discovered tool and its real arguments: ```js const result = await tools.image_gen__imagegen({ referenced_image_paths: ["/absolute/path/source.png"], prompt: "compact English image-edit prompt" }); generatedImage(result); ``` Never guess `tools.image_gen` or `input_image`. Correct wrong members, arguments, or `TypeError` from the registered signature and retry. In Claude, OpenClaw, or another host, use the equivalent native image-edit action explicitly exposed by that host. For base-anchored or multi-round repair, pass exactly `[CURRENT_EDIT, ROOT_BASE]` and state: Image 1 is the edit target; Image 2 is the original root reference for declared locked axes only. Do not attach every intermediate round. ## Route the Outcome | Observed state | Required action | | --- | --- | | Compatible image tool discovered | Invoke it. A small face, dense text, complex props, or edge contact lowers detail ambition but never blocks generation. | | Correct image tool returns a real error | Report the actual error, enter `prompt-only`, and return a complete compact prompt. | | Discovery completes with no compatible callable | Enter `invocation-handoff` and return a complete compact prompt. | | Result is nearly unchanged, changes identity, creates artificial skin, or misses the light | State that the result did not achieve the requested improvement, enter `prompt-handoff`, and recompile from the source. | Reading a skill, inspecting an image, creating a task, or announcing generation is not an image-tool invocation. ## Never Produce the Final Image Locally Do not use Pillow, NumPy, OpenCV, ImageMagick, FFmpeg, `sips`, or custom raster scripts to relight, grade, retouch, sharpen, add texture, resize, crop, extend, composite, repair, or produce the delivered image. Use them only for read-only aspect-ratio, mask, and result audits. See `requirements.txt`. ## Compile the Image Prompt Read [the V2.3 prompt compiler](references/prompt-recipes.md), [the lighting and skin recipes](references/lighting-skin-color-temperature-recipes.md), [the tone/exposure/style/device recipes](references/tone-exposure-style-device-recipes.md), and [the quality/iteration recipes](references/quality-repair-and-iteration.md). Decide internally as: ```text Scope → Key L → Exposure E → Fill/Shadow → Skin scale S → Skin finish P → Light color T → Look G → Capture D → Background/Atmosphere A → Quality Q ``` Select exactly: ```text one L + one E + one S + one P + one T + one G + one D + zero or one A + one Q ``` Use one key-light system. Atmosphere and skin reflections must inherit its direction, size, falloff, and color. E controls exposure, G controls palette/curve, and D controls capture response; none may invent another light. `A6` is the sole override: force E6 silhouette exposure, remove all subject fill/catchlights/internal illumination, use L/T only for the rear source and background, and suppress S/P. Q may clean the background but must never restore detail inside the silhouette. Send four core lines, adding RENDER for a requested grade/device response and QUALITY for an observed repair target: ```text EDIT: scope, identity/structure lock, and source-optics lock. LIGHT: one L, one E, physical shadow/background response, T, and optional A. RENDER: one G plus one D, only when either differs from source. SKIN: one scale-aware S behavior plus one source-consistent P finish. QUALITY: one Q repair, only when Q differs from source. AVOID: only the two or three failures most likely for this source. ``` - Use four lines when `G0 + D0 + Q0`; add RENDER only for a requested grade/device and QUALITY only for an observed repair target. Target `55–110` English words, with an absolute ceiling of `135` for combined edits. - State identity once. Treat the source itself as the identity card; do not invent a new age, personality, beauty description, lens, or aperture. - Use positive, observable photographic behavior before negative constraints. Omit recipe codes, audits, confidence, backend notes, and reasoning. - Compile bare words such as `cinematic`, `editorial`, `HDR`, `film`, `DSLR`, `medium format`, or `smartphone` into visible exposure, palette, tonal, microcontrast, sharpening, and dynamic-range behavior. - Default to `E0 + G0 + D0 + Q0`. Never mix multiple device profiles, color looks, or quality recipes. Never claim exact manufacturer color science or pixel identity from prompt wording. - Keep default prompts free of realism-by-dirt terms: freckles, blemishes, blackheads, rough skin, color irregularity, film grain, gritty texture, under-eye lines, and high contrast. Preserve source-specific marks without naming or amplifying them. - Use `deep`, `near-black`, or `hard contrast` only when the user explicitly selects backlight, hard light, low-key, neon, or silhouette behavior. - On retry, replace the failed line instead of appending more instructions. Every handoff must use this structure with no placeholders. ## Preserve the Identity Signature Keep six source-defined groups stable: face outline/proportions; feature spacing, shape, and size; hairline, parting, and hair mass; source-identifying skin anchors; makeup/accessories; and apparent age/expression. Do not describe these groups in detail to the image model unless a real failure requires a shorter identity retry. Detailed identity checks belong in validation, not the generation prompt. Under A6, internal features are intentionally hidden. Judge identity from hair/head/body outline, head-to-body ratio, pose, position, and framing. ## Apply Optical Skin Realism - Keep overall skin color clean and continuous across face, ear, neck, and visible upper chest. Local transitions should be gentle and source-consistent, never patch-like. - Use a diffuse base with small bounded specular highlights only on planes facing the selected key. Avoid a whole-face gloss layer and avoid removing all highlights. - Vary surface detail by region: cheek pores softer, nose pores slightly clearer, lip texture separate, eye-area structure undisturbed. Do not tile one pore pattern across the face. - Match detail to the source focus plane, depth of field, face size, and illumination. Never sharpen the whole face, every hair, clothing, and background equally. - Preserve source-existing marks as identity anchors, but do not list or generate new imperfections by default. - Preserve source skin tone; do not use `fair`, `whiter`, or beauty-grade language unless the user explicitly requests a complexion change. ## Apply Physical Light Without Unwanted Darkness - Default preservation to E0 and natural relighting to E1, with clean midtones and readable but directional shadow separation. - Add fill only when the selected exposure requires information to remain readable. Do not flatten intended backlight, hard light, low-key, or silhouette. - Derive shadow edge from apparent source size and distance. Carry direction, falloff, cast shadows, and reflected color across subject, clothing, nearby surfaces, and background. - Keep window/tree shadows continuous across curvature and adjacent surfaces; keep bokeh only in optically defocused regions; require a visible or strongly inferred source for rays; give neon a clear primary and secondary source. - Treat prism color as refraction of one existing source, not painted rainbow patches. Give blind/lattice shadows one projection geometry, candlelight rapid near-field falloff, rim light a continuous rear-quarter outline, and rain-wet highlights the same direction as the key. - Under A6, render the complete subject interior as one clean black mass. Permit only a narrow source-consistent rim that does not enter the silhouette. ## Apply Tone and Capture Style Precisely - Separate scene light from image rendering. L/T define the physical source; E places highlights, midtones, shadows, and black point; G defines palette and curve; D defines capture response. - For exposure changes, name all four tonal zones. Do not request simultaneous global highlight recovery and shadow lifting; preserve directional contrast. - For color/style changes, state skin-neutral placement, neutral-object behavior, saturation relationship, contrast curve, and highlight roll-off. A tint alone is not a style. - Translate device names into visible behavior. Full-frame, medium-format, 35mm negative, CCD compact, point-and-shoot flash, smartphone computational, instant film, and disposable-camera profiles live in the device reference. - Device emulation preserves camera position, perspective, crop, focal plane, and depth-of-field strength unless `optical-restyle` is explicit. If optics change, state the visible consequence rather than lens numbers alone. - Grain, vignetting, borders, color casts, exposure defects, and date stamps are opt-in analog artifacts. They are frame-level effects and never create skin realism. ## Repair AI Generation Quality Without Flattening Detail - Read [the V2.3 quality reference](references/quality-repair-and-iteration.md) for dirty synthetic patterns, gradient banding, edit seams, color drift, or cumulative multi-round degradation. - Distinguish synthetic repeating residue from real pores, hair, fibers, weave, film grain, edges, and focus falloff. Remove only the observed defect; never apply generic denoising or whole-frame smoothing. - Treat banding as broken luminance/chroma continuity, not as a shadow to lift. Preserve real object edges, cast-shadow boundaries, local contrast, and black point. - For local seams, separate the target, its legitimate interaction pixels, and protected surroundings. Match boundary light, color, sharpness, depth, noise, haze, and reflections without blurring the whole region. - For color drift, use the first root base—not the previous round—as the color reference. Lock only unchanged or unauthorized regions; never undo an intentional relight, grade, monochrome conversion, or recolor. - For repeated edits, use the current accepted edit as Image 1 and the root base as Image 2. Repair after every round before continuing, and do not attach the full history. - Prompt constraints reduce regeneration but cannot hard-lock pixels. Never use local Pillow/NumPy/OpenCV filters to produce the final image or claim deterministic preservation. ## Preserve the Frame Retain orientation, aspect ratio, composition, focal plane, depth of field, and subject-to-frame scale. A backend may downscale uniformly; exact pixel dimensions are not required. If a local result exists, run the read-only check: ```bash python3 "$XXG_SKILL_DIR/scripts/check_aspect_ratio.py" SOURCE_IMAGE EDITED_IMAGE ``` Accept relative aspect-ratio drift of `≤5%`. Never resize, crop, pad, or extend locally to force a pass. ## Validate the Result After generation, read [the V2.3 identity and detail audit](references/identity-and-detail-audit.md). At normal size first, verify: 1. the requested lighting/tone/capture change—or exact preservation of every unauthorized axis—is immediately clear; 2. identity signature, pose, source optics, framing, and subject scale remain stable; 3. skin reads clean before microdetail becomes visible, with bounded highlights and no uniform gloss or texture overlay; 4. detail density follows facial region, focus, scale, and illumination rather than appearing equally sharp everywhere; 5. subject and environment share one physical light system; exposure, grade, and capture response are coherent; A6 remains a complete black interior. 6. the selected Q repair is visible without erased natural detail, unintended color rollback, new seams, or later-round quality loss. If a result is nearly unchanged, strengthen one observable target. If skin becomes artificial, replace SKIN with `clean continuous source skin tone; bounded source-shaped highlights; faint region-specific microdetail only where focus and light resolve it`. Never present a failed image as final. ## Load References Only When Needed - For every prompt: `references/prompt-recipes.md` and `references/lighting-skin-color-temperature-recipes.md` - For tone, exposure, grading, style, device, film, camera, phone, CCD, or optics requests: `references/tone-exposure-style-device-recipes.md` - For dirty texture, banding, posterization, seams, color drift, or repeated-edit degradation: `references/quality-repair-and-iteration.md` - For tool routing, backend classification, or failure handling: `references/backend-and-clean-realism.md` - After generation: `references/identity-and-detail-audit.md` - Only for a verified strict local-edit backend: `references/edit-plan-and-protection.md`README.md23 KB3da2cc0370a8upstream ↗
<div align="center"> <img src="assets/skill-icon.png" width="120" alt="xxg-portrait-rebuild-light skill-logo"> </div> <h1 align="center">XXG Portrait Rebuild Light</h1> <p align="center"> <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-red?style=flat-square" alt="MIT License"></a> <a href=""><img src="https://img.shields.io/badge/Python-3.10+-blue.svg?style=flat-square" alt="Python"></a> <a href=""><img src="https://img.shields.io/badge/CodeX-Skill-green.svg?style=flat-square" alt="codex"></a> <a href=""><img src="https://img.shields.io/badge/Claude-Skill-yellow.svg?style=flat-square" alt="Claude"></a> <a href=""><img src="https://img.shields.io/badge/Open-Claw-8A2BE2.svg?style=flat-square" alt="OpenClaw"></a> <a href="CHANGELOG.md"><img src="https://img.shields.io/badge/Version-2.3.0-black?style=flat-square" alt="Version 2.3.0"></a> </p> English | [简体中文](README.zh-CN.md) | [日本語](README.ja.md) | [한국어](README.ko.md) `xxg-portrait-rebuild-light` is an image-edit skill for existing portraits. V2.3 separately controls physical light, exposure placement, color/style grade, capture-device response, broad skin tone, bounded reflection, scale/focus-aware microdetail, and AI-generation quality repair. The skill changes the lighting without redrawing the person. It preserves identity, facial structure and proportions, natural slight asymmetry, expression, pose, camera view, and composition. It avoids plastic skin, grainy skin, dirty color variation, and fake depth made by exaggerating wrinkles.  ## Key features - Provides `texture-only` fidelity recovery without changing source lighting, color, focus, depth of field, or scene content. - Repairs plastic smoothness by separating clean broad tone, source-shaped highlights, and scale/focus-aware regional microdetail. - Adds seven skin-finish profiles (`P0–P6`) for source-matched, satin-matte, soft-daylight, editorial, direct-flash, beauty, and available-light response. - Adds `E0–E7` exposure recipes that explicitly place highlight headroom, facial midtones, directional shadows, and black point. - Adds `G0–G8` color/style grades and `D0–D8` capture profiles for full-frame digital, medium format, 35mm negative, CCD compact, point-and-shoot flash, smartphone, instant film, and disposable-camera response. - Separates device response from optics: camera-style edits preserve viewpoint, perspective, crop, focal plane, and depth of field unless optical restyle is explicitly requested. - Repairs weak backlighting, disconnected indoor window light, flat lighting, unintended crushed shadows, and highlights with no physical source. - Supports soft window light, commercial soft light, Rembrandt lighting, cinematic low-key lighting, golden hour, dual-color neon, and diagonal hard light. - Adds at most one physically coherent atmosphere effect, including prism refraction, blind/lattice shadow lines, rain-wet reflections, window/tree shadow, bokeh, sunset flare, volumetric light, or a full-black silhouette. - Adds dedicated candle/flame and rim-led portrait keys with realistic falloff, edge placement, and restrained fill. - Adds `Q0–Q6` quality recipes for synthetic dirt/grid patterns, banding, edit seams, color drift, and cumulative multi-round degradation. - Uses the first root base—not the previous edit round—as the stable color/identity reference, while retaining intentional new colors and authorized lighting or grading. - Repairs only observed artifacts and preserves pores, hair, directional fibers, fabric weave, edges, shadow boundaries, and source focus falloff. - Controls subject and background in layers: key light and exposure intent first, then fill, shadows, ambient light, and color temperature. - Preserves identity, facial feature size and position, expression, pose, wardrobe, background structure, and source framing. - Reduces the skin-detail target automatically when the face is small, without canceling the requested lighting change. - Uses the current agent's own image-generation or image-editing capability by default; no separate API is required. - If the current agent has no image-edit capability, or the edit misses the target, returns one complete compact image-edit prompt. - Never uses Pillow, NumPy, OpenCV, ImageMagick, or temporary filter scripts to produce the delivered image.     ## Core method The skill first makes a director-style lighting decision internally: ```text Scope → Key L → Exposure E → Fill/Shadow → Skin S/P → Light color T → Look G → Capture D → Atmosphere A → Quality Q ``` The prompt sent to the image model uses four compact core lines, adding `RENDER` only for a requested grade/device response and `QUALITY` only for an observed repair target. Target length is 55–110 English words: ```text EDIT: Choose the smallest authorized scope; retain source identity, geometry, pose, camera view, optics, framing, and every unauthorized axis. LIGHT: One L and E with explicit highlight, midtone, shadow, black-point, background, T, and optional A behavior. RENDER: One G palette/curve plus one D capture response. Omit for G0 + D0. SKIN: One scale-aware S plus one light-consistent P finish. QUALITY: One observed Q repair; omit for Q0. AVOID: Only two or three source-specific failures. ``` The skill does not pile identity audits, object inventories, repeated negatives, and several photographic styles into one prompt. That often causes constraints to cancel each other or produces an unchanged copy. For skin-only requests, V2.3 forces `L0 + E0 + T0 + G0 + D0 + A0 + Q0`. Tone correction changes only E/T/G; capture-style changes only G/D and a logically required E; relighting changes L/E/T/A; quality repair changes only Q. Viewpoint, perspective, crop, focal plane, and depth of field stay source-matched unless the user explicitly requests `optical-restyle`. `A6` forces E6 silhouette exposure, moves the effective light behind the person, removes all fill and catchlights, and renders the subject interior black. L/T and any G/D treatment affect only the rear source and background; S/P are suppressed. ## Recipes Choose only: ```text one L light + one E exposure + one S skin scale + one P skin finish + one T light color + one G color/style grade + one D capture response + zero or one A atmosphere + one Q quality repair ``` ### Lighting L | Code | Purpose | | --- | --- | | `L0` | Match the source; repair only flat light, unexplained crushed shadows, abnormal highlights, and harsh transitions | | `L1` | Natural backlight, highlight-priority by default; add fill only when explicitly requested | | `L2` | Soft natural window light | | `L3` | Large commercial soft light | | `L4` | Outdoor skylight | | `L5` | Indoor practical and mixed lighting | | `L6` | Hard single-point light or direct sunlight | | `L7` | Low-key diagonal narrow light beam | | `L8` | Classic editorial Rembrandt lighting | | `L9` | Cinematic low-key warm key / cool ambient light | | `L10` | Golden-hour sunset side backlight | | `L11` | Cyberpunk cyan/magenta dual-tone neon | | `L12` | Clean, even commercial soft light | | `L13` | Candle or flame near-field key with rapid falloff | | `L14` | Rim-led dramatic portrait light with restrained frontal fill | ### Exposure E | Code | Purpose | | --- | --- | | `E0` | Preserve source highlights, midtones, shadows, and black point | | `E1` | Balanced natural exposure with clear midtones and directional shadows | | `E2` | Protect a bright source/rim and let unlit planes follow available bounce | | `E3` | Recover only blocked shadow information while controlling bright sources | | `E4` | High-key exposure with textured whites and gentle facial modeling | | `E5` | Low-key exposure with selected lit planes and a clean black point | | `E6` | Full silhouette exposure; use only with `A6` | | `E7` | Direct-flash subject exposure with rapid ambient falloff | ### Skin scale S | Code | Purpose | | --- | --- | | `S0` | Small face or wide shot; restore only clean skin tone and natural reflection | | `S1` | Default for medium shots; low-contrast microtexture with original lip and eye-area detail | | `S2` | High-resolution close-up; region-aware pores, fine vellus hair, and existing details | ### Skin finish P | Code | Purpose | | --- | --- | | `P0` | Preserve the exact source diffuse/specular response; default for texture-only edits | | `P1` | Natural satin-matte balance with bounded key-facing highlights | | `P2` | Soft-daylight luminous midtones and broad highlight roll-off | | `P3` | Editorial satin response with controlled T-zone highlights | | `P4` | Direct-flash response with compact separated highlights | | `P5` | Clean beauty response without porcelain uniformity | | `P6` | Available-light response with source focus falloff and no added grain or marks | ### Color temperature T | Code | Purpose | | --- | --- | | `T0` | Preserve the source white balance | | `T1` | Neutral natural daylight | | `T2` | Golden warm light with healthy neutral zones retained in the skin | | `T3` | Warm key light with cool background ambience | | `T4` | Cyan/magenta neon relationship | | `T5` | Cool-neutral overcast or blue-hour light without a full-frame blue wash | | `T6` | Warm tungsten practicals with distance-based color falloff | | `T7` | Mixed daylight/practical balance with believable skin and neutral objects | | `T8` | Candle/flame amber with distance-based warmth and neutral-deep shadows | ### Color and style grade G | Code | Purpose | | --- | --- | | `G0` | Preserve the source palette and curve | | `G1` | Neutral editorial color with a restrained S-curve | | `G2` | Clean commercial color, accurate whites, bright midtones | | `G3` | Muted documentary environment with protected skin chroma | | `G4` | Warm lit skin with controlled cool background/shadow ambience | | `G5` | Pastel editorial midtones and compressed highlights | | `G6` | Tonal monochrome with separated skin, hair, clothing, and background | | `G7` | Restrained 1970s print response; grain remains opt-in | | `G8` | Clean 1990s/Y2K flash color and contrast | ### Capture response D | Code | Purpose | | --- | --- | | `D0` | Preserve source capture response | | `D1` | Modern full-frame digital: clean detail and smooth highlight roll-off | | `D2` | Medium-format digital: smooth tonal steps and restrained sharpening | | `D3` | 35mm color negative: gentle highlight compression and softer microcontrast | | `D4` | Compact CCD/digicam: direct crisp tone with modest highlight headroom | | `D5` | Point-and-shoot direct flash; pair with `L6 + E7` | | `D6` | Smartphone computational: broad range without HDR halos or crunchy edges | | `D7` | Instant-film tone; border and grain remain opt-in | | `D8` | Disposable-camera response; exposure defects and grain remain opt-in | ### Atmosphere A | Code | Purpose | | --- | --- | | `A0` | Add no atmosphere effect | | `A1` | Soft window shadow | | `A2` | Sparse natural tree shadow | | `A3` | Soft bokeh restricted to the defocused background | | `A4` | Gentle lens flare aligned with the sunset direction | | `A5` | Very subtle volumetric light with sparse dust motes | | `A6` | Force the entire backlit subject to a clean black silhouette; no face, skin, hair, or clothing detail remains visible inside | | `A7` | Prism refraction with a few source-aligned spectral bands or caustic patches | | `A8` | Physically projected blind/lattice light-and-shadow lines | | `A9` | Rain-wet atmosphere with gravity-consistent droplets and key-shaped reflections | ### Quality repair Q | Code | Purpose | | --- | --- | | `Q0` | Preserve current quality behavior; perform no quality repair | | `Q1` | Remove only repeating synthetic cellular/maze/grid/chroma residue while preserving natural directional detail | | `Q2` | Repair posterization, contour banding, and broken luminance/chroma gradients without blurring real edges | | `Q3` | Repair local edit seams, halos, cutout edges, and boundary rendering mismatch | | `Q4` | Lock unchanged/unauthorized color relationships to the original root base without undoing intended changes | | `Q5` | Consolidate a multi-round edit against the root base and remove accumulated drift, noise, sharpening, compression, banding, and seams | | `Q6` | Repair at most three explicitly observed Q1–Q4 defects in one pass | ### Extracted lighting presets | Effect | Recipe | | --- | --- | | Prism glow | `L1/L4 + E2 + Sx + P2 + T1 + G1 + D1 + A7` | | Blind shadow lines | `L6 + E5 + Sx + P3 + T1/T2 + G1/G4 + D1 + A8` | | Candlelit low key | `L13 + E5 + Sx + P6 + T8 + G3/G4 + D1 + A0/A3` | | Neon city | `L11 + E5 + Sx + P6 + T4 + G4 + D1 + A3/A9` | | Golden twilight | `L10 + E2 + Sx + P2 + T2 + G0/G1 + D0/D1 + A4` | | Soft morning window | `L2 + E1 + Sx + P2 + T1/T2 + G0/G1 + D0/D2 + A0/A1` | | Rim-led drama | `L14 + E2/E5 + Sx + P3 + T2/T3 + G1/G4 + D1 + A0/A5` | | Cool rain-wet low key | `L4/L11 + E5 + Sx + P6 + T5/T4 + G3/G4 + D1 + A9` | See [Lighting, skin, color-temperature, and atmosphere recipes](references/lighting-skin-color-temperature-recipes.md) for detailed prompt clauses. ## Image capabilities by agent | Agent | Default route | | --- | --- | | Codex | Read the `$imagegen` rules, discover the actual tool in `ALL_TOOLS`, prefer `tools.image_gen__imagegen`, and pass source images through `referenced_image_paths` | | Claude Code | Use the image-generation or image-editing capability installed or built into the current environment | | OpenClaw | Use the imagegen skill or native image action enabled for the current agent | | Other agents | Use an equivalent image-edit capability explicitly exposed by the tool registry | In Codex, the skill never guesses `tools.image_gen` or `input_image`. It returns a prompt handoff only after tool discovery confirms that no compatible image capability exists. If the real image tool fails, produces an almost unchanged image, changes identity, or dirties the skin, the skill also returns a short copy-ready prompt. ## Requirements - An agent that supports directory-based `SKILL.md` skills. - An image-generation or image-editing capability in the current agent. - Python 3.9 or newer, used only for read-only aspect-ratio, mask, and region checks. - Pillow 9.1 or newer, used only for read-only analysis and never to create the final image. Install the read-only script dependencies: ```bash python3 -m pip install -r ./xxg-portrait-rebuild-light/requirements.txt ``` ## Install in Codex Personal skill: ```bash mkdir -p ~/.codex/skills cp -R ./xxg-portrait-rebuild-light ~/.codex/skills/ ``` Shared Agent Skills directory: ```bash mkdir -p ~/.agents/skills cp -R ./xxg-portrait-rebuild-light ~/.agents/skills/ ``` For a project-level install, place it in `.agents/skills/` at the project root. Invoke it explicitly with `$xxg-portrait-rebuild-light`. ## Install in Claude Code Personal install: ```bash mkdir -p ~/.claude/skills cp -R ./xxg-portrait-rebuild-light ~/.claude/skills/ ``` Project install: ```bash mkdir -p .claude/skills cp -R ./xxg-portrait-rebuild-light .claude/skills/ ``` Invoke it with `/xxg-portrait-rebuild-light`. ## Install in OpenClaw Local install: ```bash openclaw skills install ./xxg-portrait-rebuild-light \ --as xxg-portrait-rebuild-light ``` Shared install: ```bash openclaw skills install ./xxg-portrait-rebuild-light \ --as xxg-portrait-rebuild-light \ --global ``` You can also copy the complete directory into the current agent workspace's `skills/` directory or the shared `~/.openclaw/skills/` directory. ## Install in other agents Copy the complete `xxg-portrait-rebuild-light/` directory into the agent's personal or project skill root. Preserve the relative structure of `SKILL.md`, `requirements.txt`, `references/`, `scripts/`, and `agents/`, then reload the skill list. ## Usage examples ### Tone and exposure correction ```text Use $xxg-portrait-rebuild-light to edit this portrait with L0 + E1 + S1 + P0 + T7 + G1 + D0 + A0. Keep the existing light direction. Protect bright-area shape, place facial midtones clearly, open only blocked shadows, and retain a stable black point. Neutralize the unwanted cast while preserving skin hue, white objects, wardrobe color, viewpoint, focal plane, depth of field, and scene content. ``` ### Smartphone capture response ```text Use $xxg-portrait-rebuild-light to edit this portrait with L0 + E1 + S1 + P1 + T0 + G0 + D6 + A0. Preserve the physical light and optics. Use broad usable dynamic range, neutral skin color, restrained local tone mapping, and controlled edge sharpening; keep bright sources shaped and shadows directional, without changing crop, focal plane, or depth of field. ``` ### Classic fashion editorial ```text Use $xxg-portrait-rebuild-light to edit this portrait with L8 + E1 + S2 + P3 + T1 + G1 + D2 + A0. A large soft key from the upper front-side creates restrained Rembrandt lighting; subtle fill preserves the eye socket, one cheek falls into a deep soft shadow, and the eyes receive one source-consistent catchlight. Keep the skin clean and healthy with low-contrast photographic microtexture. ``` ### Cinematic low-key warm/cool ```text Use $xxg-portrait-rebuild-light to edit this portrait with L9 + E5 + S1 + P3 + T3 + G4 + D1 + A5. A warm side key shapes selected illuminated planes under explicit low-key exposure with no frontal fill. Keep cool color only in the background and rim, with extremely subtle source-aligned haze; illuminated skin remains chromatically clean and facial lines are not used for sculpting. ``` ### Golden-hour backlight ```text Use $xxg-portrait-rebuild-light to edit this portrait with L10 + E2 + S1 + P2 + T2 + G1 + D1 + A4. Warm sunset light from the side-rear outlines the hair and shoulders. Expose for the sunset highlights with no frontal fill; let the unlit side of the face fall naturally into a partial silhouette, allow slight bloom on lit edges, and give the background matching oblique warm light and long shadows. ``` ### Cyberpunk neon ```text Use $xxg-portrait-rebuild-light to edit this night portrait with L11 + E5 + S1 + P6 + T4 + G4 + D1 + A3. Separate the cyan rim light clearly from the magenta key while preserving a natural skin-tone zone in the center of the face. Keep bokeh only in the defocused background, never over the eyes or skin. ``` ### Full-black backlit silhouette ```text Use $xxg-portrait-rebuild-light to edit this portrait with L10 + E6 + S1 + P0 + T2 + G0 + D0 + A6. Place the effective light behind the person and expose for the bright background. Remove all frontal and side fill, catchlights, and internal subject illumination. Render the face, skin, hair, clothing, and body as one clean continuous black silhouette while preserving the original outer contour, proportions, pose, camera view, and composition. ``` ### Soft window light with window shadow ```text Use $xxg-portrait-rebuild-light to edit this indoor portrait with L2 + E1 + S1 + P2 + T1 + G0 + D0 + A1. Soft window light from the upper-left front creates a broad, gradual left-to-right falloff; faint room fill preserves the shadow side. One low-contrast window shadow continues across the person and adjacent wall and must not look pasted on. ``` ### Portrait with tree shadows ```text Use $xxg-portrait-rebuild-light to edit this outdoor portrait with L4 + E1 + S1 + P2 + T1 + G0 + D0 + A2. Broad skylight illuminates the person. Sparse tree shadows break softly across facial and clothing curvature, may cross parts of the eyes and cheeks where physically plausible, and continue into the background in the same direction with source-consistent color and smooth transitions. ``` ### Clean dirty AI texture and banding ```text Use $xxg-portrait-rebuild-light with L0 + E0 + S1 + P0 + T0 + G0 + D0 + A0 + Q6. Repair generation quality only. Remove the visible repeating synthetic texture and tonal banding while preserving natural pores, hair, directional fabric fibers, true edges, cast-shadow boundaries, color, framing, focal plane, and depth of field. Do not globally denoise, smooth, sharpen, recolor, or relight the image. ``` ### Restore color after an AI edit ```text Use $xxg-portrait-rebuild-light with Q4. Image 1 is the current edit target; Image 2 is the original root base. Retain Image 1's intended content and lighting changes. In unchanged or unauthorized regions only, restore Image 2's skin hue, neutral objects, whites, darks, saturation relationships, and lightness curve. Preserve intentional new colors and do not add a compensating green, cyan, or magenta cast. ``` ### Consolidate a degraded multi-round edit ```text Use $xxg-portrait-rebuild-light with Q5. Image 1 is the latest accepted edit; Image 2 is the first root base. Preserve every intended change in Image 1 once. Use Image 2 only for identity, geometry, framing, original color truth, and clean texture hierarchy. Remove accumulated color drift, repeating noise, sharpening halos, compression residue, banding, and seam buildup without smoothing natural detail or undoing the accepted edit. ``` ## Output standard - The target key light, light-to-shadow relationship, or atmosphere effect is immediately visible at normal viewing size. - The subject remains the same person; facial features are neither beautified nor made artificially symmetrical. - Subject, clothing, and background obey the same light sources. - Shadow depth, highlight roll-off, and silhouette strength follow the selected exposure intent instead of flattening the scene to keep everything visible. - E clearly controls highlight headroom, subject midtones, directional shadows, and black point; G/D produce one coherent palette and capture response without unauthorized optical change. - Source complexion remains clean and continuous, with bounded source-shaped highlights and regional detail limited by scale, focus, and illumination. - Grain, added marks, random color variation, global sharpening, and darker facial lines are never used to imitate realism. - Q removes only observed generation defects; it does not flatten real texture, blur boundaries, introduce a new grade, or undo requested lighting/color changes. - Multi-round work always compares the current accepted edit with the first root base; intermediate raw rounds are not generation references. - Window shadows, tree shadows, bokeh, sunset flare, and light beams have a plausible source and landing area. - With `A6`, the complete subject interior is clean black with no facial, skin, hair, clothing, or catchlight detail; identity continuity is judged from the preserved outer contour, proportions, pose, and framing. - Preserve composition, orientation, aspect ratio, and the subject's share of the frame. Proportional downscaling to an image model's maximum resolution is allowed; exact source pixel dimensions are not required. ## Related files - [Main skill rules](SKILL.md) - [Compact prompt compiler](references/prompt-recipes.md) - [Lighting, skin, color-temperature, and atmosphere recipes](references/lighting-skin-color-temperature-recipes.md) - [Tone, exposure, color/style, device, and optics recipes](references/tone-exposure-style-device-recipes.md) - [Clean-frame quality, color-lock, and iterative-repair recipes](references/quality-repair-and-iteration.md) - [Backend capability notes](references/backend-and-clean-realism.md) - [Python dependencies](requirements.txt) - [Contributing guide](CONTRIBUTING.md) - [Changelog](CHANGELOG.md) ## License Licensed under the [MIT License](LICENSE).scripts/audit_pixel_regions.py15 KB791dddfe1412upstream ↗
#!/usr/bin/env python3 """Measure exact pixel changes for the full frame and named rectangular regions.""" from __future__ import annotations import argparse import json from collections import Counter from pathlib import Path from PIL import Image, ImageChops, ImageDraw EXPECTED_TILES = {f"r{row}c{column}" for row in range(1, 4) for column in range(1, 4)} REQUIRED_CAPABILITIES = { "preexisting_exposed_tool", "semantic_image_edit", "edit_mask", "frozen_pixel_passthrough", "exact_canvas", "local_result_file", } def parse_region(value: str) -> tuple[str, str, tuple[int, int, int, int]]: try: name, role, coords = value.split(":", 2) box = tuple(int(item) for item in coords.split(",")) except ValueError as exc: raise argparse.ArgumentTypeError("Use NAME:ROLE:X1,Y1,X2,Y2") from exc if role not in {"frozen", "editable", "observe"}: raise argparse.ArgumentTypeError("ROLE must be frozen, editable, or observe") if len(box) != 4 or box[0] < 0 or box[1] < 0 or box[2] <= box[0] or box[3] <= box[1]: raise argparse.ArgumentTypeError("Region coordinates must be a valid X1,Y1,X2,Y2 box") return name, role, box def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path) parser.add_argument("edited", type=Path) parser.add_argument( "--region", action="append", default=[], type=parse_region, help="Repeatable NAME:ROLE:X1,Y1,X2,Y2; frozen regions require exact pixel identity", ) parser.add_argument( "--manifest", type=Path, help="Validated strict-final edit plan; all required protected items are audited automatically", ) parser.add_argument("--output", type=Path, help="Optional JSON output path") return parser.parse_args() def resolve(base: Path, value: str) -> Path: path = Path(value) return path if path.is_absolute() else (base / path).resolve() def binary_mask(path: Path, size: tuple[int, int]) -> Image.Image: with Image.open(path) as image: mask = image.convert("L") if mask.size != size: raise ValueError(f"Mask {path} has size {mask.size}, expected {size}") return mask.point(lambda value: 255 if value > 0 else 0) def count_nonzero(mask: Image.Image) -> int: return mask.width * mask.height - mask.histogram()[0] def item_mask(item: dict[str, object], base: Path, size: tuple[int, int]) -> Image.Image: if item.get("mask_path"): return binary_mask(resolve(base, str(item["mask_path"])), size) box = item.get("bbox") if not isinstance(box, list) or len(box) != 4: raise ValueError(f"Manifest item {item.get('id')} needs bbox or mask_path") x1, y1, x2, y2 = (int(value) for value in box) if x1 < 0 or y1 < 0 or x2 <= x1 or y2 <= y1 or x2 > size[0] or y2 > size[1]: raise ValueError(f"Manifest item {item.get('id')} has invalid bbox {box}") mask = Image.new("L", size, 0) ImageDraw.Draw(mask).rectangle((x1, y1, x2 - 1, y2 - 1), fill=255) return mask def metrics(source: Image.Image, edited: Image.Image) -> dict[str, object]: diff = ImageChops.difference(source, edited) histogram = diff.histogram() pixels = source.width * source.height total_abs = sum((index % 256) * count for index, count in enumerate(histogram)) red, green, blue = diff.split() any_channel = ImageChops.lighter(ImageChops.lighter(red, green), blue) unchanged = any_channel.histogram()[0] changed = pixels - unchanged return { "pixels": pixels, "changed_pixels": changed, "changed_percent": round(changed * 100.0 / pixels, 6), "mean_absolute_rgb_difference": round(total_abs / (pixels * 3), 6), "max_channel_difference": max(maximum for _, maximum in diff.getextrema()), "exact_match": changed == 0, } def metrics_mask(source: Image.Image, edited: Image.Image, selection: Image.Image) -> dict[str, object]: selection = selection.point(lambda value: 255 if value > 0 else 0) selected_pixels = selection.width * selection.height - selection.histogram()[0] if selected_pixels == 0: raise ValueError("Protected mask contains zero pixels") diff = ImageChops.difference(source, edited) red, green, blue = diff.split() any_channel = ImageChops.lighter(ImageChops.lighter(red, green), blue) any_changed = any_channel.point(lambda value: 255 if value > 0 else 0) changed = ImageChops.multiply(any_changed, selection) changed_pixels = changed.width * changed.height - changed.histogram()[0] selection_rgb = Image.merge("RGB", (selection, selection, selection)) masked_diff = ImageChops.multiply(diff, selection_rgb) histogram = masked_diff.histogram() total_abs = sum((index % 256) * count for index, count in enumerate(histogram)) return { "pixels": selected_pixels, "changed_pixels": changed_pixels, "changed_percent": round(changed_pixels * 100.0 / selected_pixels, 6), "mean_absolute_rgb_difference": round(total_abs / (selected_pixels * 3), 6), "max_channel_difference": max(maximum for _, maximum in masked_diff.getextrema()), "exact_match": changed_pixels == 0, } def main() -> int: args = parse_args() with Image.open(args.source) as source_image, Image.open(args.edited) as edited_image: source = source_image.convert("RGB") edited = edited_image.convert("RGB") same_dimensions = source.size == edited.size manifest = None manifest_base = None required_ids: list[str] = [] manifest_errors: list[str] = [] if args.manifest: manifest_path = args.manifest.resolve() manifest_base = manifest_path.parent manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest.get("delivery_mode") != "strict-final": manifest_errors.append("manifest delivery_mode must be strict-final") backend_raw = manifest.get("backend", {}) backend = backend_raw if isinstance(backend_raw, dict) else {} if not isinstance(backend_raw, dict): manifest_errors.append("manifest backend must be an object") capabilities_raw = backend.get("capabilities", {}) capabilities = capabilities_raw if isinstance(capabilities_raw, dict) else {} missing_capabilities = sorted( name for name in REQUIRED_CAPABILITIES if not capabilities.get(name, False) ) if backend.get("classification") != "strict-local" or missing_capabilities: manifest_errors.append( f"manifest backend is not verified strict-local; missing {missing_capabilities}" ) if manifest.get("inventory_complete") is not True: manifest_errors.append("manifest inventory_complete must be true") if manifest.get("inventory_method") != "full-frame-3x3-tile-sweep": manifest_errors.append("manifest inventory_method must be full-frame-3x3-tile-sweep") if set(manifest.get("reviewed_tiles", [])) != EXPECTED_TILES: manifest_errors.append("manifest reviewed_tiles must contain the complete 3x3 sweep") if manifest.get("source_size") != list(source.size): manifest_errors.append( f"manifest source_size {manifest.get('source_size')} does not match source {list(source.size)}" ) items = manifest.get("protected_items", []) if not isinstance(items, list) or not items: manifest_errors.append("manifest protected_items must be non-empty") else: all_ids = [str(item.get("id", "")) for item in items if isinstance(item, dict)] if len(all_ids) != len(items) or not all(all_ids) or len(all_ids) != len(set(all_ids)): manifest_errors.append("all manifest items need unique non-empty ids") if manifest.get("protected_item_count") != len(items): manifest_errors.append("manifest protected_item_count must match protected_items") computed_counts = Counter( str(item.get("category", "")) for item in items if isinstance(item, dict) ) inventory_counts = manifest.get("inventory_counts", {}) if not isinstance(inventory_counts, dict): manifest_errors.append("manifest inventory_counts must be an object") inventory_counts = {} if dict(sorted(computed_counts.items())) != dict(sorted(inventory_counts.items())): manifest_errors.append("manifest inventory_counts must match protected_items") for item in items: if not isinstance(item, dict): manifest_errors.append("manifest protected_items entries must be objects") continue if item.get("protection") == "frozen" and item.get("required_audit") is not True: manifest_errors.append( f"frozen manifest item {item.get('id')} must set required_audit=true" ) editable = None protected = None for key in ("editable_mask", "protected_mask"): value = manifest.get(key) if not value: manifest_errors.append(f"manifest {key} is required") continue try: loaded = binary_mask(resolve(manifest_base, str(value)), source.size) except (OSError, ValueError) as exc: manifest_errors.append(str(exc)) continue if key == "editable_mask": editable = loaded else: protected = loaded if editable is not None and protected is not None: overlap_pixels = count_nonzero(ImageChops.multiply(editable, protected)) if overlap_pixels: manifest_errors.append( f"manifest editable_mask overlaps protected_mask by {overlap_pixels} pixels" ) for item in items: if not isinstance(item, dict) or item.get("protection") != "frozen": continue item_id = str(item.get("id", "")) try: selection = item_mask(item, manifest_base, source.size) except (OSError, ValueError) as exc: manifest_errors.append(f"{item_id}: {exc}") continue if protected is not None: missing_pixels = count_nonzero( ImageChops.subtract( selection, ImageChops.multiply(selection, protected), ) ) if missing_pixels: manifest_errors.append( f"frozen manifest item {item_id} is missing {missing_pixels} protected pixels" ) if editable is not None: conflict_pixels = count_nonzero(ImageChops.multiply(selection, editable)) if conflict_pixels: manifest_errors.append( f"manifest editable_mask overlaps frozen item {item_id} by " f"{conflict_pixels} pixels" ) required_ids = [ str(item.get("id", "")) for item in items if isinstance(item, dict) and item.get("required_audit") is True ] if not all(required_ids) or len(required_ids) != len(set(required_ids)): manifest_errors.append("required manifest items need unique non-empty ids") report: dict[str, object] = { "source": str(args.source.resolve()), "edited": str(args.edited.resolve()), "source_size": list(source.size), "edited_size": list(edited.size), "same_dimensions": same_dimensions, "full_frame": None, "regions": [], "manifest": str(args.manifest.resolve()) if args.manifest else None, "manifest_required_ids": required_ids, "manifest_audited_ids": [], "manifest_complete": False, "manifest_errors": manifest_errors, "frozen_regions_exact": False, "pass": False, } if not same_dimensions: report["error"] = "Pixel-difference audit requires identical dimensions; run the size gate first." else: report["full_frame"] = metrics(source, edited) frozen_results: list[bool] = [] audited_ids: list[str] = [] if manifest is not None and manifest_base is not None: for item in manifest.get("protected_items", []): if item.get("required_audit") is not True: continue item_id = str(item.get("id", "")) protection = item.get("protection") role = "frozen" if protection == "frozen" else "observe" try: selection = item_mask(item, manifest_base, source.size) region_metrics = metrics_mask(source, edited, selection) except (OSError, ValueError) as exc: manifest_errors.append(f"{item_id}: {exc}") continue region_metrics.update( { "name": item_id, "role": role, "category": item.get("category"), "box": item.get("bbox"), "mask_path": item.get("mask_path"), "source": "manifest", } ) if role == "frozen": region_metrics["pass"] = region_metrics["exact_match"] frozen_results.append(bool(region_metrics["exact_match"])) else: region_metrics["pass"] = None report["regions"].append(region_metrics) audited_ids.append(item_id) for name, role, box in args.region: if box[2] > source.width or box[3] > source.height: raise SystemExit(f"Region {name} exceeds image bounds {source.size}: {box}") region_metrics = metrics(source.crop(box), edited.crop(box)) region_metrics.update({"name": name, "role": role, "box": list(box), "source": "cli"}) if role == "frozen": region_metrics["pass"] = region_metrics["exact_match"] frozen_results.append(bool(region_metrics["exact_match"])) else: region_metrics["pass"] = None report["regions"].append(region_metrics) manifest_complete = ( manifest is not None and not manifest_errors and set(audited_ids) == set(required_ids) and bool(required_ids) ) report["manifest_audited_ids"] = audited_ids report["manifest_complete"] = manifest_complete report["manifest_errors"] = manifest_errors report["frozen_regions_exact"] = bool(frozen_results) and all(frozen_results) report["pass"] = manifest_complete and bool(frozen_results) and all(frozen_results) serialized = json.dumps(report, ensure_ascii=False, indent=2) if args.output: args.output.write_text(serialized + "\n", encoding="utf-8") print(serialized) return 0 if report["pass"] else 2 if __name__ == "__main__": raise SystemExit(main())scripts/check_aspect_ratio.py2.6 KBab878988d328upstream ↗
#!/usr/bin/env python3 """Check only aspect-ratio similarity; proportional resolution changes are accepted.""" from __future__ import annotations import argparse import json import sys from pathlib import Path from PIL import Image def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("source", type=Path, help="original portrait") parser.add_argument("edited", type=Path, help="edited portrait") parser.add_argument( "--tolerance", type=float, default=0.05, help="maximum relative aspect-ratio delta; default: 0.05 (5%%)", ) parser.add_argument("--json", action="store_true", help="emit machine-readable output") return parser.parse_args() def read_ratio(path: Path) -> float: if not path.is_file(): raise FileNotFoundError(path) with Image.open(path) as image: width, height = image.size if width <= 0 or height <= 0: raise ValueError(f"invalid image dimensions: {path}") return width / height def main() -> int: args = parse_args() if not 0 <= args.tolerance <= 1: print("error: --tolerance must be between 0 and 1", file=sys.stderr) return 1 try: source_ratio = read_ratio(args.source) edited_ratio = read_ratio(args.edited) except (FileNotFoundError, OSError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 relative_delta = abs(source_ratio - edited_ratio) / source_ratio within_tolerance = relative_delta <= args.tolerance payload = { "source": str(args.source), "edited": str(args.edited), "source_aspect_ratio": round(source_ratio, 8), "edited_aspect_ratio": round(edited_ratio, 8), "relative_aspect_ratio_delta": round(relative_delta, 8), "tolerance": args.tolerance, "within_tolerance": within_tolerance, "proportional_resolution_change_allowed": True, "operation": "read-only-aspect-ratio-check", "delivery_action": "accept_ratio_gate" if within_tolerance else "reject_ratio_gate", } if args.json: print(json.dumps(payload, ensure_ascii=False, indent=2)) else: print(f"source_aspect_ratio: {source_ratio:.6f}") print(f"edited_aspect_ratio: {edited_ratio:.6f}") print(f"relative_delta: {relative_delta:.2%}") print(f"tolerance: {args.tolerance:.2%}") print(f"within_tolerance: {str(within_tolerance).lower()}") print(f"delivery_action: {payload['delivery_action']}") return 0 if within_tolerance else 2 if __name__ == "__main__": raise SystemExit(main())scripts/evaluate_backend_gate.py4.5 KB3650a90733bcupstream ↗
#!/usr/bin/env python3 """Choose strict-local or non-blocking best-effort portrait editing.""" from __future__ import annotations import argparse import json from pathlib import Path DEFAULT_REGISTRY = Path(__file__).resolve().parent.parent / "references" / "backend-capabilities.json" def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--backend", required=True, help="Profile id in backend-capabilities.json") parser.add_argument("--registry", type=Path, default=DEFAULT_REGISTRY) parser.add_argument("--face-height", type=int, required=True) parser.add_argument( "--delivery-mode", choices=("strict-final", "best-effort", "diagnostic-preview"), default="strict-final", ) parser.add_argument("--complex-scene", action="store_true") parser.add_argument("--protected-text-or-product", action="store_true") parser.add_argument("--multiple-people", action="store_true") parser.add_argument("--subject-touches-edge", action="store_true") parser.add_argument( "--relight-requested", action="store_true", help="keep a visible medium lighting change even when skin detail or background redraw must stay low", ) parser.add_argument( "--strong-light-requested", action="store_true", help="user explicitly requested a hard light, narrow beam, or similarly pronounced lighting effect", ) parser.add_argument( "--explicit-preview-authorization", action="store_true", help="deprecated compatibility flag; best-effort fallback no longer requires a second authorization", ) return parser.parse_args() def main() -> int: args = parse_args() registry = json.loads(args.registry.read_text(encoding="utf-8")) profiles = registry.get("profiles", {}) registered = args.backend in profiles profile = profiles.get( args.backend, { "classification": "unverified-full-frame-generative", "capabilities": {}, "best_effort_allowed": True, }, ) required = registry["strict_local_required_capabilities"] capabilities = profile.get("capabilities", {}) missing = [name for name in required if not capabilities.get(name, False)] strict_local = not missing flags = { "face_height_lt_256": args.face_height < 256, "complex_scene": args.complex_scene, "protected_text_or_product": args.protected_text_or_product, "multiple_people": args.multiple_people, "subject_touches_edge": args.subject_touches_edge, } risk_flags = [name for name in registry["full_frame_risk_flags"] if flags.get(name)] if strict_local: decision = "allow_strict_edit" effective_delivery_mode = "strict-final" reason = "All strict-local capabilities are present." else: decision = "allow_best_effort_edit" effective_delivery_mode = "best-effort" reason = ( "Strict-local guarantees are unavailable, so continue with an identity-constrained full-frame edit " "and label the result as best-effort instead of refusing generation or collapsing to a no-op." ) if args.strong_light_requested: lighting_strength = "strong-on-request" elif args.relight_requested: lighting_strength = "medium" else: lighting_strength = "source-matched" if args.face_height < 256: skin_detail_strength = "none" elif risk_flags: skin_detail_strength = "low" else: skin_detail_strength = "medium" result = { "schema_version": registry["schema_version"], "backend": args.backend, "backend_registered": registered, "classification": "strict-local" if strict_local else profile.get("classification"), "requested_delivery_mode": args.delivery_mode, "effective_delivery_mode": effective_delivery_mode, "missing_strict_capabilities": missing, "scene_flags": flags, "risk_flags_triggered": risk_flags, "recommended_lighting_strength": lighting_strength, "recommended_skin_detail_strength": skin_detail_strength, "minimum_visible_improvement_required": True, "decision": decision, "must_generate": True, "strict_guarantees_available": strict_local, "reason": reason, } print(json.dumps(result, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())scripts/validate_edit_plan.py9.3 KB48662ea2ba8dupstream ↗
#!/usr/bin/env python3 """Validate a strict-local portrait edit plan and reject protected-mask overlap.""" from __future__ import annotations import argparse import json from collections import Counter from pathlib import Path from PIL import Image, ImageChops, ImageDraw REQUIRED_CAPABILITIES = { "preexisting_exposed_tool", "semantic_image_edit", "edit_mask", "frozen_pixel_passthrough", "exact_canvas", "local_result_file", } EXPECTED_TILES = {f"r{row}c{column}" for row in range(1, 4) for column in range(1, 4)} def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("plan", type=Path) parser.add_argument("--output", type=Path) return parser.parse_args() def resolve(base: Path, value: str) -> Path: path = Path(value) return path if path.is_absolute() else (base / path).resolve() def binary_mask(path: Path, size: tuple[int, int]) -> Image.Image: with Image.open(path) as image: mask = image.convert("L") if mask.size != size: raise ValueError(f"Mask {path} has size {mask.size}, expected {size}") return mask.point(lambda value: 255 if value > 0 else 0) def count_nonzero(mask: Image.Image) -> int: histogram = mask.histogram() return mask.width * mask.height - histogram[0] def item_mask(item: dict[str, object], base: Path, size: tuple[int, int]) -> Image.Image: if item.get("mask_path"): return binary_mask(resolve(base, str(item["mask_path"])), size) box = item.get("bbox") if not isinstance(box, list) or len(box) != 4: raise ValueError(f"Item {item.get('id')} needs bbox or mask_path") x1, y1, x2, y2 = (int(value) for value in box) if x1 < 0 or y1 < 0 or x2 <= x1 or y2 <= y1 or x2 > size[0] or y2 > size[1]: raise ValueError(f"Item {item.get('id')} has invalid bbox {box} for {size}") mask = Image.new("L", size, 0) ImageDraw.Draw(mask).rectangle((x1, y1, x2 - 1, y2 - 1), fill=255) return mask def main() -> int: args = parse_args() plan_path = args.plan.resolve() base = plan_path.parent plan = json.loads(plan_path.read_text(encoding="utf-8")) errors: list[str] = [] overlaps: list[dict[str, object]] = [] if plan.get("schema_version") != 1: errors.append("schema_version must be 1") if plan.get("delivery_mode") != "strict-final": errors.append("validate_edit_plan.py is for delivery_mode=strict-final") source_size_raw = plan.get("source_size") if not isinstance(source_size_raw, list) or len(source_size_raw) != 2: errors.append("source_size must be [W,H]") source_size = (0, 0) else: source_size = (int(source_size_raw[0]), int(source_size_raw[1])) source_value = plan.get("source_image") if not source_value: errors.append("source_image is required") else: source_path = resolve(base, str(source_value)) if not source_path.exists(): errors.append(f"source_image does not exist: {source_path}") elif source_size != (0, 0): with Image.open(source_path) as source: if source.size != source_size: errors.append(f"source_size {source_size} does not match file size {source.size}") backend_raw = plan.get("backend", {}) backend = backend_raw if isinstance(backend_raw, dict) else {} if not isinstance(backend_raw, dict): errors.append("backend must be an object") capabilities_raw = backend.get("capabilities", {}) capabilities = capabilities_raw if isinstance(capabilities_raw, dict) else {} missing = sorted(name for name in REQUIRED_CAPABILITIES if not capabilities.get(name, False)) if backend.get("classification") != "strict-local" or missing: errors.append(f"backend is not verified strict-local; missing capabilities: {missing}") if plan.get("inventory_complete") is not True: errors.append("inventory_complete must be true") if plan.get("inventory_method") != "full-frame-3x3-tile-sweep": errors.append("inventory_method must be full-frame-3x3-tile-sweep") reviewed_tiles = set(plan.get("reviewed_tiles", [])) if reviewed_tiles != EXPECTED_TILES: errors.append(f"reviewed_tiles must contain exactly {sorted(EXPECTED_TILES)}") items = plan.get("protected_items", []) if not isinstance(items, list) or not items: errors.append("protected_items must be a non-empty list") items = [] identifiers = [str(item.get("id", "")) for item in items if isinstance(item, dict)] if not all(identifiers) or len(identifiers) != len(set(identifiers)): errors.append("every protected item needs a unique non-empty id") if plan.get("protected_item_count") != len(items): errors.append("protected_item_count must equal len(protected_items)") computed_counts = Counter(str(item.get("category", "")) for item in items if isinstance(item, dict)) inventory_counts = plan.get("inventory_counts", {}) if not isinstance(inventory_counts, dict): errors.append("inventory_counts must be an object") inventory_counts = {} if dict(sorted(computed_counts.items())) != dict(sorted(inventory_counts.items())): errors.append("inventory_counts must exactly match protected_items categories") targets = plan.get("perceptual_targets", []) if not isinstance(targets, list): errors.append("perceptual_targets must be a list") targets = [] target_ids = [str(target.get("id", "")) for target in targets if isinstance(target, dict)] if not targets or not all(target_ids) or len(target_ids) != len(set(target_ids)): errors.append("perceptual_targets must contain unique non-empty ids") for target in targets: if target.get("required") is True and ( not target.get("acceptance_view") or not target.get("acceptance_criterion") ): errors.append(f"required target {target.get('id')} needs acceptance_view and acceptance_criterion") editable = None protected = None if source_size != (0, 0): for key in ("editable_mask", "protected_mask"): value = plan.get(key) if not value: errors.append(f"{key} is required") continue try: loaded = binary_mask(resolve(base, str(value)), source_size) if key == "editable_mask": editable = loaded else: protected = loaded except (OSError, ValueError) as exc: errors.append(str(exc)) if editable is not None and protected is not None: overlap_pixels = count_nonzero(ImageChops.multiply(editable, protected)) if overlap_pixels: errors.append(f"editable_mask overlaps protected_mask by {overlap_pixels} pixels") for item in items: if not isinstance(item, dict): errors.append("protected_items entries must be objects") continue item_id = str(item.get("id", "")) if not item.get("category") or not item.get("description"): errors.append(f"item {item_id} needs category and description") tile_ids = set(item.get("tile_ids", [])) if not tile_ids or not tile_ids.issubset(EXPECTED_TILES): errors.append(f"item {item_id} needs valid tile_ids") protection = item.get("protection") if protection not in {"frozen", "authorized-edit"}: errors.append(f"item {item_id} protection must be frozen or authorized-edit") if protection == "frozen" and item.get("required_audit") is not True: errors.append(f"frozen item {item_id} must set required_audit=true") if protection == "authorized-edit" and not item.get("authorization"): errors.append(f"authorized-edit item {item_id} needs explicit authorization text") if source_size == (0, 0): continue try: current_item_mask = item_mask(item, base, source_size) except (OSError, ValueError) as exc: errors.append(str(exc)) continue if protection == "frozen" and protected is not None: missing_from_union = count_nonzero( ImageChops.subtract(current_item_mask, ImageChops.multiply(current_item_mask, protected)) ) if missing_from_union: errors.append(f"frozen item {item_id} is missing {missing_from_union} pixels from protected_mask") if protection == "frozen" and editable is not None: conflict = count_nonzero(ImageChops.multiply(current_item_mask, editable)) overlaps.append({"id": item_id, "editable_overlap_pixels": conflict}) if conflict: errors.append(f"editable_mask overlaps frozen item {item_id} by {conflict} pixels") report = { "plan": str(plan_path), "delivery_mode": plan.get("delivery_mode"), "inventory_items": len(items), "reviewed_tiles_complete": reviewed_tiles == EXPECTED_TILES, "editable_protected_overlap": overlaps, "errors": errors, "pass": not errors, } serialized = json.dumps(report, ensure_ascii=False, indent=2) if args.output: args.output.write_text(serialized + "\n", encoding="utf-8") print(serialized) return 0 if report["pass"] else 2 if __name__ == "__main__": raise SystemExit(main())scripts/validate_result_assessment.py4.0 KBd810f4a08355upstream ↗
#!/usr/bin/env python3 """Validate reported target evidence and select accept-image or prompt-handoff delivery.""" from __future__ import annotations import argparse import json from pathlib import Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("plan", type=Path) parser.add_argument("assessment", type=Path) parser.add_argument("--output", type=Path) return parser.parse_args() def resolve(base: Path, value: str) -> Path: path = Path(value) return path if path.is_absolute() else (base / path).resolve() def main() -> int: args = parse_args() plan_raw = json.loads(args.plan.read_text(encoding="utf-8")) plan = plan_raw if isinstance(plan_raw, dict) else {} assessment_path = args.assessment.resolve() assessment_raw = json.loads(assessment_path.read_text(encoding="utf-8")) assessment = assessment_raw if isinstance(assessment_raw, dict) else {} targets = plan.get("perceptual_targets", []) if not isinstance(targets, list): targets = [] required = { str(target["id"]) for target in targets if isinstance(target, dict) and target.get("required") is True and target.get("id") } results = assessment.get("target_results", []) errors: list[str] = [] if not isinstance(plan_raw, dict): errors.append("edit plan must be a JSON object") if not isinstance(assessment_raw, dict): errors.append("assessment must be a JSON object") if not required: errors.append("edit plan has no required perceptual targets") if not isinstance(results, list): errors.append("target_results must be a list") results = [] result_ids = [str(result.get("id", "")) for result in results if isinstance(result, dict)] if len(result_ids) != len(results) or len(result_ids) != len(set(result_ids)): errors.append("target_results must contain exactly one object per unique id") by_id = { str(result.get("id", "")): result for result in results if isinstance(result, dict) } if set(result_ids) != required: errors.append(f"target_results ids must exactly match required targets: {sorted(required)}") for target_id in sorted(required): result = by_id.get(target_id, {}) if result.get("status") != "pass": errors.append(f"target {target_id} status is not pass") if not result.get("finding"): errors.append(f"target {target_id} needs a concrete finding") evidence = result.get("evidence", []) if not isinstance(evidence, list) or not evidence: errors.append(f"target {target_id} needs at least one evidence file") else: for value in evidence: path = resolve(assessment_path.parent, str(value)) if not path.exists(): errors.append(f"target {target_id} evidence does not exist: {path}") report = { "plan": str(args.plan.resolve()), "assessment": str(assessment_path), "required_targets": sorted(required), "errors": errors, "pass": not errors, "failed_targets": sorted( target_id for target_id in required if by_id.get(target_id, {}).get("status") != "pass" ), "delivery_action": ( "accept_image" if not errors else "notify_and_output_complete_prompt" ), "validation_scope": ( "This script validates the assessment record and evidence paths; the agent must " "perform an honest normal-view visual comparison and must not infer visual success " "from this script alone." ), } serialized = json.dumps(report, ensure_ascii=False, indent=2) if args.output: args.output.write_text(serialized + "\n", encoding="utf-8") print(serialized) return 0 if report["pass"] else 2 if __name__ == "__main__": raise SystemExit(main())references/backend-and-clean-realism.md12 KB30a1facb0d96upstream ↗
# V2.3 Backend Capability and Clean Realism ## Delivery Modes | Mode | Entry condition and delivery | | --- | --- | | `strict-final` | Verified `strict-local` backend, valid edit plan, and every applicable gate passes. | | `best-effort` | Native full-frame semantic edit without verified mask/pixel passthrough; label non-strict and never claim frozen pixels. | | `invocation-handoff` | Discovery completed and no compatible callable exists; return a complete compact prompt without claiming invocation failed. | | `prompt-only` | The correct image tool returned a real error; summarize it and return a complete compact prompt. | | `prompt-handoff` | A generated image misses the target, changes identity/protected content, or breaks framing; report failure and recompile from source. | A small face, complex scene, visible text, edge contact, or limited backend can only trigger `best-effort`; none permits refusal. Uniform downscaling is acceptable. ## Native Tool Routing 1. Read the host's native image skill, inspect the source, and search registered tools. In Codex, inspect `ALL_TOOLS` and prefer `image_gen__imagegen` when actually present. 2. For a local source in Codex, call `tools.image_gen__imagegen({referenced_image_paths: [absolute_path], prompt})`. 3. Treat a wrong member, function name, argument, or `TypeError` as a dispatch error. Correct it from the registered signature and retry. 4. Classify a real backend as `strict-local` or `full-frame-generative`. Do not bypass the host with a CLI or separate API by default. Never guess `tools.image_gen` or `input_image`. Reading a skill, inspecting an image, creating a task, or announcing generation is not a tool invocation. ## Invocation Evidence | State | Required evidence | Mode | | --- | --- | --- | | Image generated | Image-tool call plus image/result ID or accessible output file | `strict-final` or `best-effort` after validation | | Invocation failed | Correct tool call plus explicit error from the same attempt | `prompt-only` | | No image tool | `tool_discovery_completed: true`, recorded candidates, `selected_image_tool_name: null` | `invocation-handoff` | | Dispatch error | Wrong function or argument caused a local error | Correct and retry; no handoff | | Result failed | Image exists and visual/file validation fails | `prompt-handoff` | ## Backend Classification Match [backend-capabilities.json](backend-capabilities.json); classify an unknown path as `full-frame-generative`. When a registered profile exists, run `scripts/evaluate_backend_gate.py`. `strict-local` requires all of these capabilities before execution: semantic image editing, editable/protected masks, exact passthrough of unedited pixels, verifiable fixed canvas, and a local result file. Prompt language cannot create backend capability. If any item is missing, continue with best-effort generation. Pillow, NumPy, OpenCV, ImageMagick, FFmpeg, `sips`, and temporary filters are not semantic backends. Use them only for read-only measurement and validation. ## Operation Scope and Generation Policy | Condition | Policy | | --- | --- | | `texture-only` | Preserve source light, highlight map, color, optics, and environment; authorize only skin reflectance/microdetail. | | `tone-and-exposure` | Preserve physical light direction and source optics; authorize only selected E/T/G behavior. | | `relight-and-skin` | Authorize selected L/E/T/A and scene-wide response; preserve source identity, focal plane, DOF, framing, and object structure. | | `capture-style` | Authorize selected G/D and logically required E; preserve viewpoint, crop, focal plane, DOF, identity, and scene structure. | | `optical-restyle` | Authorize only explicitly requested perspective/focal/DOF change; preserve facial feature geometry and all unrelated content. | | `quality-repair` | Authorize one Q repair only; preserve L/E/T/G/D/A, optics, identity, scene structure, and natural texture. | | `base-color-repair` | Authorize Q4 only in unchanged/unauthorized regions; preserve intended recolors and requested E/T/G/A. | | `multi-round-repair` | Use current edit plus root base; authorize Q5 while preserving each accepted current change once. | | Verified `strict-local` | Execute the validated local edit plan; deliver a strict final only after every gate passes. | | `full-frame-generative` | Generate the full frame as best effort; keep one clear visible target and reduce redraw/detail ambition. | | Face `<256 px` | Disable added microdetail; retain tone/reflection and the full scene-level lighting target. | | Text, products, complex props, multiple people, or edge contact | Name only the highest-risk protected objects; still allow source-consistent illumination/reflection. | | A6 | Authorize the full subject interior to become black while locking outline, proportion, pose, placement, composition, and background. | For full-frame edits, separate `structural_invariants`, `authorized_appearance_changes`, and one `minimum_visible_improvement` observable at normal size. An almost unchanged result cannot pass as restrained processing. ## V2.3 Clean Optical Realism | Signal | Pass | Fail | | --- | --- | --- | | Broad tone | Source complexion remains continuous across face, ear, neck, and visible chest; transitions are gentle and light-driven. | Patch-like hue/luminance changes, localized whitening, or face-neck separation. | | Reflectance/form | Diffuse base and bounded highlights follow key direction and facial curvature; volume comes from illumination and occlusion. | Whole-face gloss, dead-matte flattening, duplicate highlights, or local line darkening used as sculpting. | | Microdetail | Region-specific detail is faint, nonrepeating, and limited by face scale, focus, distance, and illumination. | Uniform pore fields, texture overlays, global sharpening, or equally crisp skin/hair/clothing/background. | | Optics | Source focal plane and depth of field remain; edges and background transition optically. | Artificial blur, focus relocation, oversharpened edges, or cutout separation. | Treat source marks as identity anchors without naming or amplifying them in the generation prompt. Do not create realism by adding imperfections, color variation, grain, or darker facial lines. Under A6, replace skin checks with one continuous black interior. ## Prompt-Priming Safety - Default to positive photographic behavior: tone continuity, bounded reflection, regional detail, and source focus. - Keep imperfection bundles, film grain, roughness, gritty texture, and high-contrast language out of default prompts. - Preserve the source complexion; do not inject `fair`, `whiter`, or beauty-grade terminology. - Use dramatic darkness only for an explicitly selected backlight, hard-light, low-key, neon, or silhouette recipe. - If a model becomes artificial, rewrite the SKIN line from scratch; never append more defect terms. ## Tone and Capture Boundaries - Keep physical light (L/T), exposure placement (E), color/look (G), and capture response (D) separate. A grade or camera name never creates another light source. - Default to E0/G0/D0. Compile a nonzero recipe only from an explicit tone, style, era, device, film, camera, or phone request. - Exposure prompts must place highlight headroom, subject midtones, directional shadows, and black point. Avoid whole-frame highlight-plus-shadow recovery. - Compile device labels into tonal steps, highlight roll-off, color separation, microcontrast, sharpening, and dynamic range; never promise exact manufacturer color science. - A capture-style edit preserves source viewpoint, perspective, crop, focal plane, and DOF. Change optics only under explicit `optical-restyle`. - Grain, vignette, borders, date stamps, color casts, and exposure defects are opt-in frame-level artifacts, never skin-detail mechanisms. ## Lighting Boundaries - Select E before fill, shadow, and highlight policy. Use E0 for preservation and E1 for unspecified natural relighting. - Derive highlight/shadow edge from apparent source size. Never add a second nose shadow/catchlight or create volume by darkening facial lines. - Preserve bright sources and rims under backlight. Use dramatic shadow loss only when the selected exposure requires it. - Indoor window light must explain subject, clothing, wall/furniture, reflective objects, and room falloff together. With insufficient evidence, use `match-source`. - A6 forces `silhouette + fill none`; the interior is black and any narrow rim stays outside it. Off-camera window confidence: `high` requires a visible window or at least three consistent evidence classes and permits explicit relighting; `medium` requires two and permits low-amplitude correction; `low` uses `match-source`. ## Quality and Iteration Boundaries - Q is independent of L/E/T/G/D/A. Quality cleanup may not invent a new light, grade, capture profile, or skin finish. - For synthetic dirt, distinguish repeating cellular/grid/chroma residue from real directional fibers, pores, hair, fabric weave, edges, and focus falloff. Never denoise the full frame by default. - For banding, repair broken luminance/chroma continuity while retaining object edges, cast-shadow boundaries, local contrast, and black point. - For local seams, match boundary exposure, white balance, saturation, sharpness, noise, depth, haze, shadow, and reflection. Do not hide a seam with global blur. - For color drift, compare unchanged or unauthorized regions with the first root base. Preserve deliberate new colors and authorized E/T/G/A behavior. - For repeated edits, attach only current target plus root base. Use the repaired current output before the next round; never treat an intermediate raw round as color truth. - Full-frame prompt constraints are probabilistic. Do not claim frozen pixels and do not use local raster filters to produce the delivered repair. ## Failure Mapping | Failure | Action | | --- | --- | | Backend lacks strict capability | Continue as `best-effort` and disclose the missing capability. | | No compatible tool / real tool error | Use `invocation-handoff` / `prompt-only`, respectively. | | Nearly unchanged, target missed, identity/protection/framing failed | Use `prompt-handoff`; never repair locally. | | Plastic smoothness remains | Use scale-aware S plus P0/P1; specify bounded highlights and focus-aware regional detail. | | Skin becomes artificial or the image dims unintentionally | Remove realism-by-defect/darkness terms; reset to clean source tone, bounded reflection, and E0/E1 exposure. | | Tone becomes flat or globally tinted | Replace E/G with explicit tonal-zone placement, neutral references, skin-hue protection, saturation relationship, and one curve. | | Device style is absent or changes optics | Replace the name with D capture behavior and restore source viewpoint/crop/focus/DOF. | | A6 retains interior detail or gray fill | Remove S/P, fill, catchlights, and subject lighting; require one continuous black interior. | | Prism effect looks painted | Reduce to a few ordered spectral bands; align them with one refracted source and surface curvature. | | Blind shadows look like an overlay | Restore one projection direction, repeated spacing, edge hardness, perspective, and continuation onto a nearby surface. | | Candlelight becomes orange fill | Keep one low near-field flame, rapid falloff, weak bounce, and a neutral-deep black point. | | Rain/wet effect dirties skin | Restrict droplets and wet highlights to gravity and key-facing planes; restore clean continuous complexion elsewhere. | | Repeating dirt/grid remains | Use Q1 only on the affected material; restore clean continuity while preserving natural directional detail. | | Repair creates waxy or flat surfaces | Remove global denoise/smoothing; restore pores, fibers, hair, edges, bounded reflection, and source focus falloff. | | Tonal/chroma banding remains | Use Q2 on the named gradient; preserve true edges, shadow boundaries, local contrast, and black point. | | Local edit boundary remains visible | Use Q3 to match boundary light/color/sharpness/noise/depth/haze/reflection without blurring the region. | | Color lock undoes an intentional look | Restrict Q4 to unchanged/unauthorized regions and exempt selected E/T/G/A behavior. | | Multi-round result keeps degrading | Use Q5 with current edit plus root base only; remove accumulated residue while preserving accepted changes once. |references/backend-capabilities.json2.7 KB30d60b0a820aupstream ↗
{ "schema_version": 8, "invocation_evidence_contract": { "initial_state": { "tool_discovery_completed": false, "discovered_image_tool_names": [], "selected_image_tool_name": null, "native_invocation_attempted": false, "delivery_decision_allowed": false }, "tool_discovery_required": true, "codex_preferred_callable": "image_gen__imagegen", "codex_preferred_tool_member": "tools.image_gen__imagegen", "edit_source_argument": "referenced_image_paths", "forbidden_guessed_tool_members": [ "tools.image_gen" ], "forbidden_guessed_arguments": [ "input_image" ], "native_invocation_attempted_definition": "A callable discovered in the current tool registry was actually invoked; invalid local member access does not count.", "success_requires": [ "image_tool_call_record", "returned_image_artifact_or_result" ], "failure_requires": [ "image_tool_call_record", "explicit_error_payload_from_same_call" ], "not_invoked_requires": [ "tool_discovery_completed", "no_compatible_image_generation_or_edit_tool_found", "selected_image_tool_name_is_null" ], "dispatch_error_requires_retry": [ "undiscovered_or_missing_tool_member", "guessed_argument_name", "local_type_error_before_real_image_tool_call" ], "execution_context_is_not_capability_evidence": [ "direct_user_turn", "background_thread", "delegation_message" ], "not_invoked_delivery_mode": "invocation-handoff", "explicit_failure_delivery_mode": "prompt-only", "result_failure_delivery_mode": "prompt-handoff" }, "strict_local_required_capabilities": [ "preexisting_exposed_tool", "semantic_image_edit", "edit_mask", "frozen_pixel_passthrough", "exact_canvas", "local_result_file" ], "profiles": { "host-native-imagegen": { "match_when": { "route": "host-native-imagegen-skill", "skill_or_capability": "imagegen", "codex_callable": "image_gen__imagegen", "edit_source_argument": "referenced_image_paths", "built_in_mode": true, "accepts_whole_image_reference": true, "accepts_edit_mask": false }, "classification": "full-frame-generative", "capabilities": { "preexisting_exposed_tool": true, "semantic_image_edit": true, "edit_mask": false, "frozen_pixel_passthrough": false, "exact_canvas": false, "local_result_file": true }, "strict_final_allowed": false, "best_effort_allowed": true } }, "full_frame_risk_flags": [ "face_height_lt_256", "complex_scene", "protected_text_or_product", "multiple_people", "subject_touches_edge" ] }references/edit-plan-and-protection.md5.2 KB2db494c88bb1upstream ↗
# V2.3 Strict Local Edit Plan and Protection Gate Use this file only with a verified `strict-local` backend. Follow [the backend contract](backend-and-clean-realism.md) for delivery mode and invocation evidence. If strict capability is missing, continue as `best-effort`; do not create a fictional freeze plan. ## Full-Frame Inventory Divide the frame into `r1c1`–`r3c3` and inspect all nine tiles before setting `inventory_complete: true`. Record each: - eye/lid, brow, ala/nostril, lip boundary/corner, jaw, ear, and hairline; - hair mass, braid, loose strand, garment, strap, accessory, hand, and pose boundary; - book and visible text, computer/phone, cup, lamp, and product; - door, table, chair, shelf, plant, wall, floor, window, and object touching a frame edge. Record same-class objects separately with a unique `id`, description, tile, `bbox`, and optional `mask_path`. Build from [edit-plan-template.json](edit-plan-template.json). `protected_item_count` and `inventory_counts` must match the actual entries. ## Edit Plan A strict plan contains: source dimensions for coordinate/same-size audit only; `operation_scope`; selected L/E/S/P/T/G/D/A/Q recipes; current/root reference roles when applicable; source perspective/crop/focal-plane/DOF policy; verified backend profile; nine-tile inventory; `editable_mask`; union `protected_mask`; actual exposure, fill, shadow, and highlight policy; and an acceptance view/criterion for every required perceptual target. Only user-authorized objects may be marked `authorized-edit`; every other item is `frozen + required_audit`. For a full-frame `best-effort` edit, use instead: - `structural_invariants`: identity geometry, composition, and object content; - `authorized_appearance_changes`: selected L/E/T/G/D/A/Q response, scale/focus-aware skin detail, P-profile reflection, and continuous source complexion; - `minimum_visible_improvement`: one result visible at normal full-frame viewing size. For `texture-only`, freeze source light, highlight map, exposure, white balance, color look, capture response, focal plane, depth of field, environment, and all non-skin content. For `tone-and-exposure`, authorize only E/T/G. For `relight-and-skin`, authorize selected L/E/T/A plus matching S/P. For `capture-style`, authorize only G/D and a logically required E while freezing viewpoint, crop, focal plane, and DOF. For `quality-repair`, authorize only Q. For `base-color-repair`, authorize Q4 only in unchanged/unauthorized regions. For `multi-round-repair`, authorize Q5 using current edit plus root base. `optical-restyle` must explicitly name any authorized perspective, crop, or DOF change. A6 authorizes luminance, skin color, feature visibility, and hair/clothing/accessory surface detail inside the original subject outline to become black. Freeze the outline, proportions, pose, composition, and background. Suppress S/P. A strict A6 editable mask must cover the complete subject interior and stop at the original outline; do not darken only the face. ## Mask Gate ```bash python3 "$XXG_SKILL_DIR/scripts/validate_edit_plan.py" EDIT_PLAN.json \ --output edit-plan-validation.json ``` If any tile, count, backend capability, source dimension, frozen coverage, or editable/protected mask intersection fails, do not execute the strict plan. Correct it or continue as `best-effort`. A `bbox` protects its entire rectangle by default; provide an item mask when a tighter shape is required rather than shrinking the box around content. ## Frozen-Region Audit Only for a same-size strict result, run: ```bash python3 "$XXG_SKILL_DIR/scripts/audit_pixel_regions.py" SOURCE EDITED \ --manifest EDIT_PLAN.json --output pixel-audit.json ``` The script revalidates the plan and automatically covers every `required_audit` item. A missing manifest, omitted item/audit, count mismatch, mask overlap, or changed frozen pixel cannot return strict PASS. For a uniformly downscaled result, skip pixel differencing and perform `best-effort` visual validation. ## Target Improvement For every `perceptual_targets` item, record `status`, a concrete `finding`, and evidence from the full frame or specified zoom. Then run: ```bash python3 "$XXG_SKILL_DIR/scripts/validate_result_assessment.py" \ EDIT_PLAN.json RESULT_ASSESSMENT.json --output target-validation.json ``` Mark an almost unchanged result `fail`; a difference map or `restrained processing` does not establish improvement. For `texture-only`, require preserved source light/color/capture/optics plus visibly improved bounded reflection and regional focus-aware detail. For tone/capture work, require the selected E/T/G/D response without unauthorized optical change. For relight, require selected L/E/T/A and matching P. For Q work, require the named artifact to be reduced without natural-detail loss, unauthorized recolor/relight, or rollback of accepted changes. For A6, require the complete subject interior to be continuous black with no facial feature, skin color, catchlight, lit hair strand, or garment texture, while outline, proportions, pose, position, and background remain stable. Mark S/P targets not applicable. If any required target fails, enter `prompt-handoff`: report the failure and return a complete compact prompt recompiled from the source. Do not repair locally or present the failed image as final.references/edit-plan-template.json3.9 KB6bddb8591556upstream ↗
{ "schema_version": 1, "source_image": "/absolute/path/source.png", "source_size": [1672, 941], "delivery_mode": "strict-final", "operation_scope": "relight-and-skin", "recipe_selection": { "lighting": "L2", "exposure": "E1", "skin_scale": "S1", "skin_finish": "P2", "color_temperature": "T1", "color_grade": "G0", "capture_profile": "D0", "atmosphere": "A0", "quality": "Q0" }, "reference_roles": { "current_edit": "/absolute/path/source.png", "root_base": null, "root_base_role": "none" }, "optics_policy": { "optical_restyle_requested": false, "perspective": "preserve-source", "crop": "preserve-source", "focal_plane": "preserve-source", "depth_of_field": "preserve-source" }, "backend": { "id": "verified-local-editor", "classification": "strict-local", "capabilities": { "preexisting_exposed_tool": true, "semantic_image_edit": true, "edit_mask": true, "frozen_pixel_passthrough": true, "exact_canvas": true, "local_result_file": true } }, "inventory_complete": true, "inventory_method": "full-frame-3x3-tile-sweep", "reviewed_tiles": [ "r1c1", "r1c2", "r1c3", "r2c1", "r2c2", "r2c3", "r3c1", "r3c2", "r3c3" ], "protected_item_count": 2, "inventory_counts": { "identity-boundary": 1, "text": 1 }, "protected_items": [ { "id": "eyes-and-eyelids", "category": "identity-boundary", "description": "Both eyes, irises, and eyelid boundaries", "tile_ids": ["r1c2", "r2c2"], "bbox": [500, 300, 820, 440], "mask_path": "/absolute/path/eyes-mask.png", "protection": "frozen", "required_audit": true }, { "id": "handheld-book", "category": "text", "description": "Handheld book with printed text", "tile_ids": ["r2c2"], "bbox": [650, 405, 750, 535], "protection": "frozen", "required_audit": true } ], "editable_mask": "/absolute/path/editable-mask.png", "protected_mask": "/absolute/path/protected-mask.png", "perceptual_targets": [ { "id": "lighting-direction", "required": true, "acceptance_view": "Full frame and 100% face comparison", "atmosphere_recipe": "A0", "exposure_intent": "source-matched", "fill_policy": "ambient-reflection", "shadow_policy": "retained-detail", "highlight_policy": "retained", "acceptance_criterion": "The selected L/E/T/A direction, highlight and midtone placement, shadow transition, black point, and background response are visible and physically coherent without duplicate sources or artificial sculpting." }, { "id": "clean-skin-realism", "required": true, "acceptance_view": "Normal viewing size and the face-scale-defined close view", "acceptance_criterion": "Skin first reads clean and continuous, with bounded source-shaped highlights and faint regional detail limited by scale, focus, and illumination; no uniform gloss or texture overlay." }, { "id": "tone-and-capture-response", "required": false, "acceptance_view": "Full frame at normal viewing size", "acceptance_criterion": "When G or D differs from source, the requested palette, curve, highlight behavior, microcontrast, sharpening, and dynamic-range response are visible while source viewpoint, crop, focal plane, and depth of field remain stable." }, { "id": "clean-frame-quality", "required": false, "acceptance_view": "Full frame at normal size plus affected gradients, materials, and edit boundaries at 200%–400%", "acceptance_criterion": "When Q differs from source, the named synthetic residue, banding, seam, color drift, or cumulative edit degradation is visibly reduced without smoothing natural detail, changing unauthorized light/color/structure, or undoing accepted edits." } ] }references/identity-and-detail-audit.md14 KB36a8eafc718eupstream ↗
# V2.3 Identity, Skin, Light, Tone, Capture, Quality, and Optics Validation ## Contents [Evidence](#evidence-record) · [Strict protection](#strict-protection-gate) · [Face scale](#face-scale-gate) · [Identity](#identity-signature-gate) · [Skin](#skin-realism-gate) · [Focus](#focus-and-detail-distribution-gate) · [Lighting](#lighting-gate) · [Tone/capture](#tone-grade-and-capture-gate) · [Quality](#quality-and-iteration-gate) · [Framing](#aspect-ratio-and-composition-gate) · [Improvement](#target-improvement-gate) ## Evidence Record Follow [the backend contract](backend-and-clean-realism.md). When a result exists, inspect source/result at normal full-frame size, same normalized face regions, side-by-side `200%–400%` views, and original result files for aspect ratio. Do not locally resize either image for comparison; uniform backend downscaling is acceptable. ```yaml source_size: [W, H] operation_scope: texture-only | tone-and-exposure | relight-and-skin | capture-style | optical-restyle | quality-repair | base-color-repair | multi-round-repair face_box: [x1, y1, x2, y2] face_top_y: y_top chin_y: y_chin face_height_px: y_chin - y_top face_height_ratio: face_height_px / H recipes: lighting: L0 exposure: E0 skin_scale: S1 skin_finish: P0 color_temperature: T0 color_grade: G0 capture_profile: D0 atmosphere: A0 quality: Q0 references: current_edit: path-or-id root_base: path-or-id-or-null root_base_role: none | identity-geometry-color | identity-geometry-only light: mode: match-source | relight exposure_intent: source-matched | balanced | highlight-priority | shadow-priority | low-key | silhouette | high-key fill_policy: none | ambient-reflection | explicit-fill shadow_policy: retained-detail | dramatic-clean | silhouette highlight_policy: retained | soft-rolloff | controlled-clipping confidence: low | medium | high evidence: [{type, object, observation}] contradictions: [] optics: optical_restyle_requested: false perspective_preserved: true crop_preserved: true focal_plane_preserved: true depth_of_field_preserved: true ``` Compute `face_height_px` by coordinate subtraction and reuse normalized audit regions. Derive light confidence from evidence: `low` uses `match-source`, `medium` permits low-amplitude correction, and `high` permits explicit relighting. ## Strict Protection Gate Use [the edit plan](edit-plan-and-protection.md) only for verified `strict-local`. Require all nine inventory tiles, item-level protection, matching counts, every frozen item in the union mask, and zero editable/protected overlap. Run `scripts/validate_edit_plan.py`. On failure, continue as `best-effort` rather than refusing. ## Face-Scale Gate | Visible face height | Evaluated detail | | --- | --- | | `≥512 px` | Fine regional pores, natural lip texture, sparse focus-resolved vellus detail, and bounded reflections. | | `256–511 px` | Faint regional microdetail, clean lip/eye boundaries, and local reflective variation. | | `<256 px` | Continuous tone, broad illumination, and natural reflection; surface microdetail is not a target. | Never demand detail the source scale cannot resolve. ## Identity Signature Gate Compare six source-defined groups: | Group | Compare | | --- | --- | | Face outline | Jawline, face width, forehead/head ratio, cheek/chin contour. | | Feature geometry | Eye spacing/aperture/lids, brow shape, nose bridge/alae/tip, lip boundary/opening and feature size/placement. | | Hair signature | Hairline, parting, fringe, hair mass, braid/loose-strand layout. | | Skin anchors | Source-existing identifying marks and lip/eye-area structure, without requiring newly visible imperfections. | | Fixed styling | Makeup boundaries, glasses, earrings, accessories, and wardrobe identity. | | Age/expression | Apparent age, gaze, lid/mouth tension, expression, and overall demeanor. | Fail any idealization, symmetry correction, boundary/size/placement change, or reconstructed identity. Under A6, internal features are intentionally hidden; compare hair/head/body outline, head-to-body ratio, pose, placement, and framing instead. ## Skin Realism Gate Judge broad tone before zoomed texture: | Signal/region | Pass | Fail | | --- | --- | --- | | Face-neck color | Clean source complexion with gentle continuous transitions across ear, neck, and visible chest. | Patch-like hue/luminance changes, local whitening, or face-neck separation. | | Forehead/nose | Small bounded highlights that match key direction and P profile; detail appropriate to scale. | One continuous shine layer, fixed plastic highlight, or overdefined pore pattern. | | Cheeks/jaw | Softer diffuse response, visible tonal shape, and lower surface contrast than the nose. | Flat smoothing, equally shiny cheeks, texture overlay, or locally burned contour. | | Eye area | Original lids and tonal transition remain clean; no newly emphasized surface detail. | Darkened lines, invented bags/wrinkles, or changed lid geometry. | | Lips | Original shape/color with separate natural lip texture when resolved. | Reshaping, enlargement, or skin texture copied onto lips. | | Makeup | Original boundaries, color, and intensity remain. | Heavier/redesigned makeup or changed complexion. | At normal size, skin must read clean, continuous, and dimensional before any microdetail is noticed. At closer view, detail must be faint, regional, nonrepeating, and optical—not a surface layer. Under A6, mark skin targets `not-applicable-by-design` and require one clean black interior. ## Focus and Detail Distribution Gate - Preserve the source focal plane and depth of field unless the user explicitly requests an optical change. - Highest detail belongs only on in-focus, adequately illuminated regions. Let detail reduce naturally with distance, shadow, curvature, and defocus. - Fail equally crisp pores across the entire face, every hair strand sharply separated, oversharpened clothing/background, artificial blur, or cutout edges. - In `texture-only`, any focus relocation, background change, global sharpening, or altered bokeh fails. ## Lighting Gate - In `texture-only`, preserve source highlight placement, E0 exposure, T0 white balance, G0 look, D0 capture response, shadow transition, subject/environment response, and atmosphere. - In `tone-and-exposure`, preserve light direction and geometry; only the requested E/T/G axes may change. - In `relight-and-skin`, catchlight; nose/eye-socket/cheek/jaw/neck shadows; hair; clothing; and background must agree with one L/E/T/A system. - Lighting may change luminance/reflection but may not move feature boundaries or sculpt the face through localized line darkening. - Default/ambiguous relight should use E1 with luminous midtones. E5 shadow loss passes only when explicitly selected; E6 requires A6; E7 requires direct-flash intent. - A6 requires E6, `fill_policy: none`, and one black interior; any internal feature, skin color, catchlight, lit hair, garment texture, or accessory shading fails. - A7 passes only when a few ordered spectral bands remain tied to one source and bend across real surfaces; floating rainbow patches or a global tint fail. - A8 passes only when repeated bands share direction, spacing, perspective, edge hardness, and continuity across subject and adjacent surfaces. - L13/T8 requires rapid near-field falloff, weak warm bounce, and clean deep surroundings; a uniform orange face or room fails. - L14 requires a narrow continuous rear-quarter rim with restrained fill; a halo entering the face or unrelated edge glow fails. - A9 requires gravity-consistent rain and key-facing wet reflections; random droplets, whole-face oiliness, or reflections with a second direction fail. ## Tone, Grade, and Capture Gate Compare the result with the selected E/G/D definitions in [the V2.3 tone and capture recipes](tone-exposure-style-device-recipes.md). | Layer | Pass | Fail | | --- | --- | --- | | Exposure E | Highlight shape/headroom, subject midtones, directional shadows, and black point all match one declared intent. | Flat whole-frame recovery, clipped skin, unintended dimming, lifted gray blacks, or contradiction between subject and environment. | | Light color T | Source color appears only where that source illuminates or bounces; skin and neutral references remain plausible. | Full-frame orange/blue/neon wash or inconsistent face/neck color. | | Grade G | Palette, saturation relationship, curve, and highlight roll-off match one look while identity and skin hue remain stable. | A simple tint, multiple competing eras, crushed tonal separation, or recolored skin. | | Capture D | Tonal steps, highlight behavior, microcontrast, sharpening, dynamic range, and optional noise match one capture class. | Device name with no visible response, multiple capture classes, crunchy HDR, artificial grain, or device emulation used as skin texture. | | Optics | Viewpoint, perspective, crop, focal plane, and DOF remain source-matched unless `optical-restyle` is explicit. | A capture-style request changes camera position, facial perspective, crop, or background blur without authorization. | For a brand-named request, validate the compiled capture behavior, not unverifiable claims about exact manufacturer color science. ## Quality and Iteration Gate Compare the result with the selected Q definition in [the V2.3 quality reference](quality-repair-and-iteration.md). | Signal | Pass | Fail | | --- | --- | --- | | Synthetic residue | Named repeating cellular/grid/chroma artifact is removed only where present; clean material continuity returns. | Dirty veil remains, natural texture is flattened, or a new artificial texture is added. | | Natural detail | Pores, hair, directional fibers, fabric weave, true edges, and focal falloff remain scale-appropriate and nonrepeating. | Waxy surfaces, whole-frame smoothing, global sharpening, repeated texture, or lost edge hierarchy. | | Gradient continuity | Skin shadows, walls, sky, haze, and bokeh have continuous luminance/chroma roll-off. | Posterization, contour steps, hue bands, blotches, or blurred real shadow/object edges. | | Edit boundary | Exposure, white balance, saturation, sharpness, noise, depth, haze, shadow, and reflection transition naturally. | Rectangle seam, halo, doubled contour, cutout edge, or abrupt texture/sharpness change. | | Base color lock | Only unchanged/unauthorized regions return toward root skin hue, neutrals, whites, darks, saturation, and lightness. | Intended colors or selected E/T/G/A are rolled back, or a compensating green/cyan/magenta cast appears. | | Multi-round quality | Current accepted changes remain once; frame is no noisier, dirtier, sharper, more compressed, tinted, banded, or seamed merely because it is a later round. | Intermediate states blend together, accepted edits disappear, or cumulative defects remain/amplify. | If no root base exists, do not claim exact color restoration. Judge only visible cast normalization against skin and neutral objects. Prompt wording alone cannot establish protected-pixel identity. ## Aspect-Ratio and Composition Gate Run `scripts/check_aspect_ratio.py`. Relative aspect-ratio drift of `≤5%` passes. Accept edge rounding and uniform downscaling; do not compare absolute dimensions. Fail stretching, orientation change, crop/extension, ratio drift above tolerance, altered camera view, or changed subject position/scale. Never repair framing locally. ## Strict Pixel Audit Only for a same-size `strict-local` result, run: ```bash python3 "$XXG_SKILL_DIR/scripts/audit_pixel_regions.py" SOURCE EDITED \ --manifest EDIT_PLAN.json --output pixel-audit.json ``` Fail a missing plan, incomplete inventory/count, mask overlap, omitted `required_audit`, or changed frozen pixel. For uniform downscaling, skip pixel differencing and use `best-effort` visual validation. ## Target-Improvement Gate Define `acceptance_view` and `acceptance_criterion` before generation. Afterward, record `pass`, an observation, and evidence. Improvement must be visible at the specified normal view; a difference map or extreme zoom is insufficient. - `texture-only`: source light/optics remain stable; plastic smoothness is replaced by bounded reflection and scale/focus-aware regional detail. - `tone-and-exposure`: requested E/T/G change is immediately visible while source light direction, optics, identity, and scene structure remain stable. - `relight-and-skin`: requested L/E/T/A direction, tonal consequence, background response, and skin reflectance are immediately legible and coherent. - `capture-style`: requested G/D response is visible without changing viewpoint, crop, focal plane, or DOF. - `optical-restyle`: the requested optical consequence is visible and facial geometry remains stable; assess authorized framing changes separately. - `quality-repair`: the selected Q defect is visibly reduced at normal size without changing light/color/structure or flattening natural detail. - `base-color-repair`: unchanged/unauthorized regions agree with the root base while intentional recolors and authorized E/T/G/A remain intact. - `multi-round-repair`: accepted current edits remain once and accumulated color/noise/sharpening/compression/banding/seam residue is reduced against the root base. - Fail whole-face gloss, fully dead-matte flattening, texture overlay, uniform sharpness, unintended dimming, complexion change, or identity drift. - A6: require a black interior plus original outline, proportions, pose, and placement. For strict results, run `scripts/validate_result_assessment.py`. Any required target marked `fail` or `not_verifiable`, missing evidence, or omitted assessment enters `prompt-handoff`. ## Final Decision Any applicable failure in identity signature, light/scope, exposure, grade, capture response, quality, skin realism, focus distribution, framing, frozen regions, or target improvement disqualifies the image. State `This image did not achieve the requested improvement` and return a compact prompt recompiled from source. Never present or locally repair a failed image.references/lighting-skin-color-temperature-recipes.md14 KBc88da4af5f34upstream ↗
# V2.3 Lighting, Skin, Finish, Color, and Atmosphere Recipes ## Contents [Protocol](#selection-protocol) · [Scope](#operation-scope) · [Exposure](#exposure-handoff) · [Combinations](#quick-combinations) · [Key lights](#key-light-recipes-l) · [Skin scale](#skin-scale-recipes-s) · [Skin finish](#skin-finish-recipes-p) · [Atmosphere](#atmosphere-recipes-a) · [Color](#color-temperature-recipes-t) ## Selection Protocol Choose exactly `one L + one E + one S + one P + one T + one G + one D + zero or one A`. Decide internally as `Scope → Key L → Exposure E → Fill/Shadow → Skin S/P → Light color T → Look G → Capture D → Atmosphere A`, then send only model-facing behavior without codes. - Set operation scope first. A texture-only request must not change lighting or optics. - Define one key by direction, apparent size, landing area, and falloff. Select E from [the tone/exposure/device reference](tone-exposure-style-device-recipes.md) before fill. - Make skin finish inherit the key; never add an independent gloss or texture layer. - Preserve source focal plane and depth of field. Detail visibility must follow scale, focus, distance, and illumination. - Use at most one atmosphere. A1–A5 and A7–A9 inherit the key; A6 overrides exposure and suppresses S/P. ## Operation Scope | Scope | Required behavior | | --- | --- | | `texture-only` | Force `L0 + E0 + T0 + G0 + D0 + A0 + Q0`; preserve source highlight placement, exposure, white balance, shadow transitions, focal plane, depth of field, environment, and quality behavior. Use S + P0/P1 only. | | `tone-and-exposure` | Keep L0 and source optics; authorize only the requested E/T/G corrections. | | `relight-and-skin` | Apply selected L/E/T/A consistently to subject and environment; preserve source optics and identity while adapting S/P. | | `capture-style` | Keep physical light unless requested; apply G/D and only a logically required E while preserving viewpoint, crop, focus, and DOF. | ## Exposure Handoff Select exactly one E from [Tone, Exposure, Look, and Capture Recipes](tone-exposure-style-device-recipes.md). E—not L—places highlights, midtones, shadows, and black point. L defines only the physical source and its geometry. Default to E0 for preservation and E1 for natural relighting. E5/E6/E7 require an explicit low-key, silhouette, or direct-flash intent. ## Quick Combinations | Requested result | Combination | | --- | --- | | Skin fidelity only | `L0 + E0 + Sx + P0/P1 + T0 + G0 + D0 + A0 + Q0` | | Tone/exposure correction | `L0 + E1/E2/E3 + Sx + P0 + T0/T7 + G0/G1 + D0 + A0` | | Natural backlight | `L1 + E2 + Sx + P2 + T1 + G0 + D0 + A0` | | Soft window light | `L2 + E1 + Sx + P2 + T1 + G0/G1 + D0/D2 + A0/A1` | | Commercial studio softness | `L3 + E1/E4 + Sx + P5 + T1 + G2 + D1/D2 + A0` | | Point-and-shoot flash | `L6 + E7 + Sx + P4 + T0/T1 + G8 + D5 + A0` | | Low-key diagonal beam | `L7 + E5 + Sx + P3 + T0/T2 + G0/G4 + D0 + A0/A5` | | Fashion editorial | `L8 + E1 + Sx + P3 + T1 + G1 + D1/D2 + A0` | | Cinematic warm/cool low-key | `L9 + E5 + Sx + P3 + T3 + G4 + D1 + A0/A5` | | Golden hour | `L10 + E2 + Sx + P2 + T2 + G0/G1 + D0/D1 + A4` | | Full-black silhouette | `Lx + E6 + Sx + Px + Tx + Gx + Dx + A6` | | Neon city | `L11 + E5 + Sx + P6 + T4 + G4 + D1 + A3/A9` | | Clean commercial high-key | `L12 + E4 + Sx + P5 + T1 + G2 + D1/D2 + A0` | | Prism glow | `L1/L4 + E2 + Sx + P2 + T1 + G1 + D1 + A7` | | Blind or lattice shadow lines | `L6 + E5 + Sx + P3 + T1/T2 + G1/G4 + D1 + A8` | | Candlelit low key | `L13 + E5 + Sx + P6 + T8 + G3/G4 + D1 + A0/A3` | | Sculpted rim drama | `L14 + E2/E5 + Sx + P3 + T2/T3 + G1/G4 + D1 + A0/A5` | | Cool rain-wet low key | `L4/L11 + E5 + Sx + P6 + T5/T4 + G3/G4 + D1 + A9` | ## Key-Light Recipes L | Code | Model-facing behavior | | --- | --- | | L0 Source lock | Preserve source direction, apparent source size, highlight/shadow landing geometry, falloff, and environmental response. E0 separately preserves tonal placement. | | L1 Natural backlight | Keep one rear source, source-shaped hair/shoulder rim, and plausible environmental reflection on camera-facing planes. Pair with E2 unless the user requests face fill. | | L2 Soft window key | Place one large soft window source above and to one side for a broad directional gradient. Carry the same direction, roll-off, and room bounce across skin, clothing, wall, and furniture. | | L3 Commercial soft key | Place one large soft source above and camera-side with low-level frontal fill. Produce a short soft nose shadow, readable eye socket, gentle cheek/jaw separation, and restrained background response. | | L4 Open-sky light | Use broad skylight plus location bounce for soft curvature, wide transitions, and source-consistent ambient direction. Avoid artificial studio hotspots or added hair rims. | | L5 Practical mixed light | Let each visible practical affect only plausible nearby planes and decay with distance. Retain ambient fill only when supported by the room; make subject and environment agree. | | L6 Direct flash or hard point | Use one small source from the requested direction. Create compact bounded highlights and clean cast-shadow edges; align nose, neck, clothing, and background shadow geometry. Let E set their tonal depth. | | L7 Diagonal light beam | For an explicit low-key request, place one slightly softened narrow beam across eye, nose, and cheek following facial curvature. Keep the beam edge continuous and let out-of-beam areas recede according to the chosen exposure. | | L8 Rembrandt editorial | Place one large soft key above and to one side, with minimal fill preserving the eye socket. Create a short nose shadow, gentle far-cheek separation, and exactly one source-consistent catchlight. | | L9 Cinematic low-key | For an explicit low-key request, use one warm side key for selective facial illumination and no frontal fill. Confine any cool component to background/rim; pair with E5. | | L10 Golden-hour side backlight | Place one warm sunset source behind and to one side, outlining hair and shoulders. Derive camera-facing illumination from natural reflected fill and align background direction and long shadows; pair with E2. | | L11 Dual-tone neon | Use one colored side key and one weaker opposite-rear rim with distinct directions. Keep saturation controlled and restrict each color to illuminated planes rather than washing the full face. | | L12 Minimal high-key soft light | Use one large top-front diffused source with slight frontal fill, broad source-shaped highlights, soft directional shadows, and nonflat separation; pair with E4 for high key. | | L13 Candle or flame key | Use one visible or strongly implied flame below and to one side as the dominant near-field source. Let amber light fall off rapidly across face, hands, clothing, and room; retain only weak warm bounce and one flame-consistent catchlight. Pair with E5 and T8. | | L14 Rim-led dramatic portrait | Place one strong rear-quarter source to draw a narrow continuous rim along source-facing hair, shoulder, and garment edges. Use only weak broad camera-side fill when facial readability is requested; keep the rim outside facial interiors and align background spill with the source. | ## Skin Scale Recipes S | Code | Scale and model-facing behavior | | --- | --- | | S0 `<256 px` | Maintain continuous source skin tone and natural light response; the visible scale does not resolve added surface detail. | | S1 `256–511 px` | Render faint regional microdetail only on illuminated in-focus skin; preserve clean eye-area and lip boundaries. | | S2 `≥512 px` | Render fine camera-resolved detail: softer cheek pores, slightly clearer nose pores, natural lip texture, and sparse vellus detail only where source focus resolves it. | Apply S only where scale, focus, and light support it. Never lift shadows, sharpen the whole face, or tile a uniform pore field to reveal texture. Preserve source identity anchors without naming, adding, or amplifying marks. A6 suppresses S. ## Skin Finish Recipes P P controls diffuse/specular balance, not complexion or makeup. | Code | Model-facing behavior | | --- | --- | | P0 Source finish | Preserve the exact source diffuse/specular balance and existing highlight location, area, and intensity. Use by default for texture-only work. | | P1 Natural satin-matte | Use a soft diffuse base with small bounded highlights on key-facing convexities; keep cheeks, jaw, and eye area less reflective without making skin flat. | | P2 Soft-daylight finish | Use luminous clean midtones, broad roll-off, and restrained window/sky-shaped highlights with continuous face-neck color. | | P3 Editorial satin | Use controlled T-zone highlights, smooth cheek separation, and low-amplitude optical detail; keep the face dimensional without local line darkening. | | P4 Direct-flash finish | Keep compact flash-facing highlights with clear boundaries, distinct cheek/jaw tones, and one flash-consistent catchlight; never connect highlights into a facial film. | | P5 Clean beauty finish | Keep even broad tone, natural three-dimensional reflection, and fine focus-aware detail; retain skin character without porcelain uniformity. | | P6 Available-light finish | Preserve source-driven highlight placement and optical falloff with restrained detail; do not add marks, grain, stronger color variation, or global sharpening. | A whole-face gloss layer fails every P. A fully dead-matte result also fails unless the source or user explicitly requires it. ## Atmosphere Recipes A | Code | Model-facing behavior | | --- | --- | | A0 None | Add no atmosphere effect. | | A1 Window shadow | Add one low-amplitude soft window shadow across subject and an adjacent surface; perspective, direction, penumbra, and falloff must follow the key. | | A2 Tree shadow | Add sparse foliage shadows that break naturally across facial/clothing curvature and continue onto nearby background surfaces in the same direction. | | A3 Bokeh | Add only a few light circles in optically defocused background regions. Derive color from scene lighting and never place them over the subject. | | A4 Sunset flare | Add one restrained flare aligned with the sunset source. Permit slight bloom only near that source, never across the full frame or face. | | A5 Volumetric light | Add faint source-aligned haze only where a visible or strongly inferred beam crosses air/background; do not veil the subject or add decorative dust. | | A6 Full-black silhouette | Place the subject against one bright rear source or luminous background with no fill, catchlight, or internal illumination. Render the entire subject interior black while retaining outline, proportions, pose, and placement. | | A7 Prism refraction | Refract one existing key through a prism, faceted glass, or crystal into a few soft spectral bands or caustic patches. Preserve ordered color dispersion, source direction, curvature, and falloff across skin and nearby surfaces; never create floating rainbow stickers or a full-frame color wash. | | A8 Blind/lattice shadow lines | Project one hard directional source through blinds, slats, or lattice as repeated parallel light-and-shadow bands. Keep spacing, perspective, edge hardness, and direction coherent; bend bands across facial/clothing curvature and continue them onto an adjacent surface. | | A9 Rain-wet atmosphere | Add source-lit rain, gravity-consistent droplets, and narrow wet reflections on hair, skin, clothing, and ground only where the selected key reaches them. Keep dark regions clean, avoid whole-face oiliness, and let background reflections inherit the scene colors and depth of field. | ### A6 Override - Force `E6`, `exposure_intent: silhouette`, `fill_policy: none`, and `shadow_policy: silhouette`. - Retain from L only the rear source and background treatment; remove all subject-facing illumination. - Omit both S and P. Apply T, G, and D only to the source/background; none may restore subject detail. - Q may repair the background only; it must not reveal, reconstruct, or texture the silhouette interior. - Fail if any facial feature, skin color, catchlight, lit hair strand, garment texture, accessory shading, or gray fill remains inside. ## Color-Temperature Recipes T | Code | Model-facing behavior | | --- | --- | | T0 Source white balance | Preserve source white balance and the skin neutral point; correct only a localized discontinuous cast when requested. | | T1 Neutral daylight | Use neutral natural daylight; keep skin and nominally white objects from drifting blue or yellow. | | T2 Golden warm light | Concentrate warmth on directly illuminated planes and nearby bounce; retain neutral transitions and avoid a global orange cast. | | T3 Warm key, cool background | Put warm color in the subject key and cool color only in background/rim; keep face-neck transitions continuous. | | T4 Cyan/magenta relationship | Give cyan and magenta distinct directions, roles, and intensities; preserve plausible skin reflection and controlled saturation. | | T5 Cool overcast or blue hour | Use cool-neutral ambient light with preserved skin neutrality, smooth sky-to-subject color continuity, and no full-frame blue wash. | | T6 Tungsten practical | Keep visible tungsten sources warm and let their color decay with distance; retain believable skin hue and neutral reference separation. | | T7 Mixed-light balance | Preserve distinct daylight and practical-light regions while neutralizing only conflicting casts on skin and nominally neutral objects. | | T8 Candle/flame amber | Keep directly flame-lit planes amber-gold, let warmth decay rapidly with distance, retain neutral-to-deep shadows, and avoid a global orange or sepia wash. | ## Optional Control Clauses | Need | Add only this clause | | --- | --- | | One catchlight | `one source-consistent catchlight` | | Balanced fill | `low-level environmental fill retaining directional shadow separation` | | Soft source | `large diffused key with broad highlight and shadow transitions` | | Hard source | `small directional key with bounded highlights and a clean cast-shadow edge` | | Focus realism | `detail follows the source focal plane, depth of field, distance, and illumination` | | Highlight placement | `small bounded specular highlights only on key-facing convexities` | | Clean midtones | `luminous clean midtones with directional shadow separation` | | Highlight priority | `expose for the source and rim; derive subject brightness from available reflected fill` | | Low-key | `low-key exposure with selected illuminated planes` — explicit dramatic requests only | | Silhouette | `no subject-facing fill; preserve the outer silhouette while the entire interior falls to black` |references/prompt-recipes.md24 KB30fc8107e67fupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
references/quality-repair-and-iteration.md9.5 KBa5218c1edafbupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
references/tone-exposure-style-device-recipes.md12 KBc31a0b0f33dbupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/demo1_v2_0_0.jpg205 KB8b8f517a8938upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/demo2_v2_0_0.jpg189 KB7fe74760d642upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/demo3_v2_0_0.jpg969 KB25d80a9c9041upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/demo4_v2_0_0.jpg470 KB357a114d5576upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/lightv2.jpg614 KBc539a52b1810upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/skill-demo1.jpg427 KBbe9c821a00d4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/skill-demo2.jpg509 KBeeb1187ee9a0upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/skill-demo3.jpg351 KB1db59398033dupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/skill-demo4.jpg395 KB2764493ae348upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/skill-icon.png76 KBd452b6f77f39upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
.gitignore33 Bdff2f412104dupstream ↗
.DS_Store __pycache__/ *.py[cod]agents/openai.yaml417 B964ff31c3e81upstream ↗
interface: display_name: "XXG Portrait Rebuild Light" short_description: "Relight and repair portraits with optical realism" default_prompt: "Use $xxg-portrait-rebuild-light V2.3 to choose the smallest edit scope, then compile one physical light, explicit tonal placement, optional color/device response, clean scale-aware skin, and one observed quality repair while preserving every unauthorized source axis."CHANGELOG.md5.5 KB542cec737bf4upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
CONTRIBUTING.md2.3 KBda6ba79f7fa6upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
LICENSE1.0 KB27e4365059f1upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.ja.md24 KB1fda2a9f28adupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.ko.md24 KB424e0920ec90upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
README.zh-CN.md19 KB7e42ebefb8f7upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
requirements.txt88 B13d50ff750e2upstream ↗
# Read-only image loading, mask validation, and pixel-region audits only. Pillow>=9.1.0
Plain-text copy, no login: /skill-bundles/moskoo-xxg-portrait-rebuild-light.md