[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71HSNDMVCVTVYFH5B1XG70S":3,"skill-same:01M71HSNDMVCVTVYFH5B1XG70S":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":22,"publishedAt":32,"linkOnly":33,"markdownContent":34,"markdownBody":35,"frontMatter":36,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M71HSNDMVCVTVYFH5B1XG70S","iterative-prompt-refinement",null,"Iterative Prompt Refinement: Logic Framework for Semantic Remediation.","0xzgbot\u002Fforge-nps-v01","0xzgbot","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F271900281?v=4","01M71GXWAFRXXJSJE3HBCVDKZY","01M71GXWBFQYRJK7M8RM6BDP0X",6,"MIT","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fiterative_prompt_refinement\u002FSKILL.md",[17],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[23,24,25,26,27,28,29,30,31],"prompt","refinement","iterative prompt refinement","framework","Production","remediation","logic","semantic","for","2026-11-10 10:12:30",false,"---\nname: iterative-prompt-refinement\ndescription: 'Iterative Prompt Refinement: Logic Framework for Semantic Remediation.'\nversion: 1.0.0\nauthor: Cinesmith\nlicense: MIT\nmetadata:\n  hermes:\n    tags:\n    - iterative-prompt-refinement\n    - cinesmith\n    - production\n    category: cinesmith\n---\n\n# Iterative Prompt Refinement: Logic Framework for Semantic Remediation\n\n## 1. Error Taxonomy\n\nFailures are classified by **domain** (what broke) and **severity** (how badly).\n\n| Class | Error Type | Definition | Typical Trigger |\n|-------|-----------|------------|-----------------|\n| **Temporal** | `Temporal Drift` | Subject identity or environment changes discontinuously across frames. | Overly detailed descriptions without anchor tokens. |\n| | `Motion Incoherence` | Physics-defying movement; unnatural acceleration or rigidity. | Ambiguous verb choice (\"move quickly\"). |\n| **Anatomical** | `Anatomical Error` | Extra\u002Fmissing limbs, impossible joints, or malformed features. | Dense attribute stacking on human figures. |\n| | `Proportion Distortion` | Relative scale of body parts violates biological norms. | Conflicting size adjectives (\"tiny head, massive eyes\"). |\n| **Photometric** | `Lighting Mismatch` | Light direction\u002Fcolor inconsistent with described environment. | Multiple unranked light sources. |\n| | `Texture Flattening` | Loss of surface detail; everything appears matte or overly smooth. | Over-reliance on style keywords (\"digital art\"). |\n| | `Color Bleed` | Unintended chromatic contamination across semantic boundaries. | Adjacent high-saturation descriptors without separators. |\n| **Semantic** | `Semantic Overload` | Model ignores key elements because the prompt exceeds attention capacity. | >6 distinct entities with equal syntactic weight. |\n| | `Concept Blending` | Two distinct concepts merge into an undesirable hybrid. | Parallel noun phrases without disambiguation. |\n| | `Attribute Leakage` | A descriptor intended for entity A applies to entity B. | Pronoun ambiguity or parallel clause structure. |\n| **Structural** | `Composition Collapse` | Violation of stated spatial relationships (e.g., \"behind\" ignored). | Complex prepositional stacking. |\n| | `Depth Inconsistency` | Foreground\u002Fbackground relationships physically impossible. | Conflicting depth cues (\"close-up\" + \"aerial view\"). |\n\n---\n\n## 2. Refinement Protocols\n\nEach protocol maps an error type to a **transformation function** over the prompt's Abstract Syntax Tree (AST). The engine treats prompts as structured data, not raw strings.\n\n### Protocol A: Hierarchical Reconstruction (for `Semantic Overload`, `Composition Collapse`)\n\n**Logic:** Restructure from flat description to ranked dependency tree.\n\n```\nOriginal:  \"A wizard, a dragon, a castle, stormy night, lightning, flying, epic\"\nRefined:   \"SUBJECT: ancient stone castle on cliff edge. \n            ACTION: lightning strikes the highest tower. \n            ENVIRONMENT: violent storm, night, heavy rain. \n            DETAIL[0.3]: distant silhouette of a flying dragon.\"\n```\n\n**Transformation Rules:**\n- Enforce `Subject → Action → Environment → Detail` hierarchy.\n- Move secondary entities to bracketed weight syntax (e.g., `[detail:0.3]`).\n- Limit top-level entities to **3**.\n\n---\n\n### Protocol B: Token Weight Rebalancing (for `Texture Flattening`, `Lighting Mismatch`)\n\n**Logic:** Increase salience of under-represented tokens via emphasis markers or positional priority.\n\n```\nOriginal:  \"portrait of a knight, digital art, smooth lighting\"\nRefined:   \"portrait of a knight, (intricate etched armor:1.4), \n            (volumetric candlelight from left:1.3), digital art\"\n```\n\n**Transformation Rules:**\n- Identify \"style-dominant\" tokens that may suppress detail.\n- Apply scalar weights `(token:1.2–1.5)` to suppressed visual descriptors.\n- Move style tokens to the **end** of the prompt (lower positional attention in most diffusion transformers).\n\n---\n\n### Protocol C: Negative Constraint Injection (for `Anatomical Error`, `Concept Blending`)\n\n**Logic:** Replace ambiguous positive descriptors with explicit negative space definitions.\n\n```\nOriginal:  \"a woman with six arms holding swords\"\nRefined:   \"a woman holding two swords, perfect anatomy, \n            [negative: extra limbs, fused fingers, deformed hands]\"\n```\n\n**Transformation Rules:**\n- Detect anatomical impossibilities via ontology check.\n- Convert impossible configurations into **positive constraints** (\"two arms\") + **negative prompts** (\"extra limbs\").\n- Use descriptor replacement, not just addition: remove the cause, don't mask the symptom.\n\n---\n\n### Protocol D: Temporal Anchoring (for `Temporal Drift`, `Motion Incoherence`)\n\n**Logic:** Inject identity-preserving anchor tokens and discretize motion.\n\n```\nOriginal:  \"a fox running through a forest, changing seasons\"\nRefined:   \"SEQUENCE[frame]: red fox with white-tipped tail, consistent fur pattern. \n            MOTION: galloping gait, paws contacting ground in cycle. \n            ENVIRONMENT: autumn forest, static tree positions across frames.\"\n```\n\n**Transformation Rules:**\n- Extract `IDENTITY` tokens (unique, persistent descriptors) and prefix with `ANCHOR:`.\n- Convert continuous verbs into discrete kinematic phases (\"running\" → \"galloping gait, cyclic leg positions\").\n- Add `STATIC:` prefix to environmental elements that must not drift.\n\n---\n\n### Protocol E: Semantic Segregation (for `Attribute Leakage`, `Color Bleed`)\n\n**Logic:** Bind attributes to specific entities using explicit scoping syntax.\n\n```\nOriginal:  \"a red car and a blue house next to a green tree\"\nRefined:   \"ENTITY[car]{color:red, metallic paint}, \n            ENTITY[house]{color:blue, two-story}, \n            ENTITY[tree]{color:green, deciduous}, \n            RELATION[house, tree]{adjacent}\"\n```\n\n**Transformation Rules:**\n- Parse ambiguous adjective-noun bindings.\n- Reformat into scoped blocks or use separator tokens (`BREAK`, `AND`).\n- Ensure color\u002Ftexture adjectives are within **3 tokens** of their target noun.\n\n---\n\n## 3. Feedback Loops: Correction Payload Specification\n\nThe auditor agent outputs a **Correction Payload**—a Markdown report consumed by the remediation engine. Below is the schema and a sample.\n\n### Payload Schema\n\n```markdown\n## Correction Payload\n| Field | Value |\n|-------|-------|\n| `payload_id` | UUID-v4 |\n| `timestamp` | ISO-8601 |\n| `asset_type` | IMAGE \u002F VIDEO \u002F 3D |\n| `failure_severity` | CRITICAL \u002F MAJOR \u002F MINOR |\n\n### Correction Items\n| Failure Type | Current Prompt Segment | Suggested Correction | Reasoning | Protocol Applied |\n|--------------|------------------------|----------------------|-----------|------------------|\n| ... | ... | ... | ... | ... |\n```\n\n### Sample Payload\n\n```markdown\n## Correction Payload\n| Field | Value |\n|-------|-------|\n| `payload_id` | `a1b2-c3d4-e5f6-7890` |\n| `timestamp` | `2026-04-20T12:20:00Z` |\n| `asset_type` | VIDEO |\n| `failure_severity` | MAJOR |\n\n### Correction Items\n\n| Failure Type | Current Prompt Segment | Suggested Correction | Reasoning | Protocol Applied |\n|--------------|------------------------|----------------------|-----------|------------------|\n| Temporal Drift | `\"a character walking through a market, crowd, colorful stalls, changing time of day\"` | `ANCHOR: protagonist with scar on left cheek, brown cloak. ENVIRONMENT: bustling market with static stall positions. TIME: locked to golden hour.` | Unanchored subject description allows facial features and clothing to mutate across frames. The \"changing time of day\" directive directly contradicts temporal consistency. | Protocol D |\n| Semantic Overload | `\"crowd, colorful stalls, changing time of day\"` | `DETAIL[0.3]: background crowd. DETAIL[0.2]: market stalls with striped awnings.` | Three competing scene descriptors dilute attention. Demoting to weighted details preserves presence without overwhelming the subject. | Protocol A |\n| Lighting Mismatch | `\"changing time of day\"` | `(warm golden-hour sidelight from west:1.3), [negative: cool tones, overhead lighting]` | Temporal lighting shift creates photometric inconsistency across the sequence. Locking a specific light vector stabilizes rendering. | Protocol B |\n```\n\n---\n\n## 4. Python Remediation Engine: Logic Guide\n\nThe following structures are designed to be directly implemented. The engine operates on a `PromptNode` graph.\n\n```python\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\nfrom typing import List, Optional, Dict\n\nclass ErrorClass(Enum):\n    TEMPORAL = auto()\n    ANATOMICAL = auto()\n    PHOTOMETRIC = auto()\n    SEMANTIC = auto()\n    STRUCTURAL = auto()\n\nclass RefinementProtocol(Enum):\n    HIERARCHICAL_RECONSTRUCTION = \"A\"\n    TOKEN_WEIGHT_REBALANCING = \"B\"\n    NEGATIVE_CONSTRAINT_INJECTION = \"C\"\n    TEMPORAL_ANCHORING = \"D\"\n    SEMANTIC_SEGREGATION = \"E\"\n\nclass Severity(Enum):\n    CRITICAL = 3  # Must fix; block generation\n    MAJOR = 2     # Should fix; retry once\n    MINOR = 1     # Optional fix; log only\n\n@dataclass\nclass PromptNode:\n    \"\"\"AST node for prompt decomposition.\"\"\"\n    node_type: str  # SUBJECT, ACTION, ENVIRONMENT, DETAIL, STYLE\n    content: str\n    weight: float = 1.0\n    children: List['PromptNode'] = field(default_factory=list)\n    negative: bool = False\n\n@dataclass\nclass FailureReport:\n    \"\"\"Input from quality-check auditor.\"\"\"\n    error_type: str           # e.g., \"Temporal Drift\"\n    error_class: ErrorClass\n    severity: Severity\n    affected_segment: str     # The substring in the original prompt\n    visual_evidence: str      # Description of the artifact\n\n@dataclass\nclass CorrectionItem:\n    \"\"\"Single row in the Correction Payload.\"\"\"\n    failure_type: str\n    current_segment: str\n    suggested_correction: str\n    reasoning: str\n    protocol: RefinementProtocol\n    confidence: float  # 0.0–1.0 from the LLM auditor\n\n@dataclass\nclass RemediationPlan:\n    \"\"\"Output of the refinement engine.\"\"\"\n    original_prompt: str\n    corrected_prompt: str\n    corrections: List[CorrectionItem]\n    protocol_stack: List[RefinementProtocol]  # Ordered application sequence\n\n# ── Engine Core Logic ──────────────────────────────────────────────\n\nPROTOCOL_MAP: Dict[str, RefinementProtocol] = {\n    \"Temporal Drift\": RefinementProtocol.TEMPORAL_ANCHORING,\n    \"Motion Incoherence\": RefinementProtocol.TEMPORAL_ANCHORING,\n    \"Anatomical Error\": RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION,\n    \"Proportion Distortion\": RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION,\n    \"Lighting Mismatch\": RefinementProtocol.TOKEN_WEIGHT_REBALANCING,\n    \"Texture Flattening\": RefinementProtocol.TOKEN_WEIGHT_REBALANCING,\n    \"Color Bleed\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Semantic Overload\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n    \"Concept Blending\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Attribute Leakage\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Composition Collapse\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n    \"Depth Inconsistency\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n}\n\ndef generate_remediation_plan(\n    original_prompt: str,\n    failures: List[FailureReport]\n) -> RemediationPlan:\n    \"\"\"\n    1. Sort failures by Severity (CRITICAL first).\n    2. Deduplicate protocols (apply each protocol at most once per pass).\n    3. Transform PromptNode AST according to protocol rules.\n    4. Serialize AST back to string.\n    5. Emit CorrectionItems for audit trail.\n    \"\"\"\n    failures.sort(key=lambda f: f.severity.value, reverse=True)\n    \n    corrections: List[CorrectionItem] = []\n    applied_protocols: List[RefinementProtocol] = []\n    ast = parse_prompt_to_ast(original_prompt)  # User-implemented parser\n    \n    for failure in failures:\n        protocol = PROTOCOL_MAP.get(failure.error_type)\n        if not protocol:\n            continue\n            \n        if protocol not in applied_protocols:\n            ast = apply_protocol(ast, protocol, failure)\n            applied_protocols.append(protocol)\n        \n        corrections.append(CorrectionItem(\n            failure_type=failure.error_type,\n            current_segment=failure.affected_segment,\n            suggested_correction=extract_segment(ast, failure.affected_segment),\n            reasoning=f\"Detected {failure.error_type} in segment. \"\n                      f\"Protocol {protocol.value} restructures attention.\",\n            protocol=protocol,\n            confidence=0.85  # Placeholder; LLM auditor provides this\n        ))\n    \n    return RemediationPlan(\n        original_prompt=original_prompt,\n        corrected_prompt=serialize_ast(ast),\n        corrections=corrections,\n        protocol_stack=applied_protocols\n    )\n\n# ── Protocol Transformers (Stubs) ──────────────────────────────────\n\ndef apply_protocol(ast: PromptNode, protocol: RefinementProtocol, failure: FailureReport) -> PromptNode:\n    if protocol == RefinementProtocol.HIERARCHICAL_RECONSTRUCTION:\n        return enforce_subject_action_env_hierarchy(ast)\n    elif protocol == RefinementProtocol.TOKEN_WEIGHT_REBALANCING:\n        return rebalance_token_weights(ast, failure.affected_segment, scale=1.3)\n    elif protocol == RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION:\n        return inject_negative_constraints(ast, failure.affected_segment)\n    elif protocol == RefinementProtocol.TEMPORAL_ANCHORING:\n        return anchor_identity_tokens(ast)\n    elif protocol == RefinementProtocol.SEMANTIC_SEGREGATION:\n        return scope_attributes_to_entities(ast)\n    return ast\n\n# Implementations of the above transformers are domain-specific\n# and depend on the generative model's tokenizer\u002Fattention mechanism.\n```\n\n---\n\n## 5. Operational Constraints for the Engine\n\n| Constraint | Rationale |\n|------------|-----------|\n| **Max 3 protocols per pass** | Over-correction introduces new artifacts. Queue remaining fixes for Pass 2. |\n| **Never modify `ANCHOR` tokens** | Identity tokens, once fixed, are immutable across the remediation loop. |\n| **Preserve original token count ±20%** | Prevents prompt length from exceeding model context or attention window. |\n| **Log all negative constraints** | Negative prompts can suppress desired features; require auditor review if >3. |\n| **Halt after 5 iterations** | Prevent infinite loops on fundamentally underspecified prompts. |\n\nThis framework treats prompt refinement as a **deterministic transformation over structured syntax**, not as open-ended rewriting. The LLM auditor's role is to classify failures and justify corrections; the engine's role is to apply validated transformations reliably and reversibly.","# Iterative Prompt Refinement: Logic Framework for Semantic Remediation\n\n## 1. Error Taxonomy\n\nFailures are classified by **domain** (what broke) and **severity** (how badly).\n\n| Class | Error Type | Definition | Typical Trigger |\n|-------|-----------|------------|-----------------|\n| **Temporal** | `Temporal Drift` | Subject identity or environment changes discontinuously across frames. | Overly detailed descriptions without anchor tokens. |\n| | `Motion Incoherence` | Physics-defying movement; unnatural acceleration or rigidity. | Ambiguous verb choice (\"move quickly\"). |\n| **Anatomical** | `Anatomical Error` | Extra\u002Fmissing limbs, impossible joints, or malformed features. | Dense attribute stacking on human figures. |\n| | `Proportion Distortion` | Relative scale of body parts violates biological norms. | Conflicting size adjectives (\"tiny head, massive eyes\"). |\n| **Photometric** | `Lighting Mismatch` | Light direction\u002Fcolor inconsistent with described environment. | Multiple unranked light sources. |\n| | `Texture Flattening` | Loss of surface detail; everything appears matte or overly smooth. | Over-reliance on style keywords (\"digital art\"). |\n| | `Color Bleed` | Unintended chromatic contamination across semantic boundaries. | Adjacent high-saturation descriptors without separators. |\n| **Semantic** | `Semantic Overload` | Model ignores key elements because the prompt exceeds attention capacity. | >6 distinct entities with equal syntactic weight. |\n| | `Concept Blending` | Two distinct concepts merge into an undesirable hybrid. | Parallel noun phrases without disambiguation. |\n| | `Attribute Leakage` | A descriptor intended for entity A applies to entity B. | Pronoun ambiguity or parallel clause structure. |\n| **Structural** | `Composition Collapse` | Violation of stated spatial relationships (e.g., \"behind\" ignored). | Complex prepositional stacking. |\n| | `Depth Inconsistency` | Foreground\u002Fbackground relationships physically impossible. | Conflicting depth cues (\"close-up\" + \"aerial view\"). |\n\n---\n\n## 2. Refinement Protocols\n\nEach protocol maps an error type to a **transformation function** over the prompt's Abstract Syntax Tree (AST). The engine treats prompts as structured data, not raw strings.\n\n### Protocol A: Hierarchical Reconstruction (for `Semantic Overload`, `Composition Collapse`)\n\n**Logic:** Restructure from flat description to ranked dependency tree.\n\n```\nOriginal:  \"A wizard, a dragon, a castle, stormy night, lightning, flying, epic\"\nRefined:   \"SUBJECT: ancient stone castle on cliff edge. \n            ACTION: lightning strikes the highest tower. \n            ENVIRONMENT: violent storm, night, heavy rain. \n            DETAIL[0.3]: distant silhouette of a flying dragon.\"\n```\n\n**Transformation Rules:**\n- Enforce `Subject → Action → Environment → Detail` hierarchy.\n- Move secondary entities to bracketed weight syntax (e.g., `[detail:0.3]`).\n- Limit top-level entities to **3**.\n\n---\n\n### Protocol B: Token Weight Rebalancing (for `Texture Flattening`, `Lighting Mismatch`)\n\n**Logic:** Increase salience of under-represented tokens via emphasis markers or positional priority.\n\n```\nOriginal:  \"portrait of a knight, digital art, smooth lighting\"\nRefined:   \"portrait of a knight, (intricate etched armor:1.4), \n            (volumetric candlelight from left:1.3), digital art\"\n```\n\n**Transformation Rules:**\n- Identify \"style-dominant\" tokens that may suppress detail.\n- Apply scalar weights `(token:1.2–1.5)` to suppressed visual descriptors.\n- Move style tokens to the **end** of the prompt (lower positional attention in most diffusion transformers).\n\n---\n\n### Protocol C: Negative Constraint Injection (for `Anatomical Error`, `Concept Blending`)\n\n**Logic:** Replace ambiguous positive descriptors with explicit negative space definitions.\n\n```\nOriginal:  \"a woman with six arms holding swords\"\nRefined:   \"a woman holding two swords, perfect anatomy, \n            [negative: extra limbs, fused fingers, deformed hands]\"\n```\n\n**Transformation Rules:**\n- Detect anatomical impossibilities via ontology check.\n- Convert impossible configurations into **positive constraints** (\"two arms\") + **negative prompts** (\"extra limbs\").\n- Use descriptor replacement, not just addition: remove the cause, don't mask the symptom.\n\n---\n\n### Protocol D: Temporal Anchoring (for `Temporal Drift`, `Motion Incoherence`)\n\n**Logic:** Inject identity-preserving anchor tokens and discretize motion.\n\n```\nOriginal:  \"a fox running through a forest, changing seasons\"\nRefined:   \"SEQUENCE[frame]: red fox with white-tipped tail, consistent fur pattern. \n            MOTION: galloping gait, paws contacting ground in cycle. \n            ENVIRONMENT: autumn forest, static tree positions across frames.\"\n```\n\n**Transformation Rules:**\n- Extract `IDENTITY` tokens (unique, persistent descriptors) and prefix with `ANCHOR:`.\n- Convert continuous verbs into discrete kinematic phases (\"running\" → \"galloping gait, cyclic leg positions\").\n- Add `STATIC:` prefix to environmental elements that must not drift.\n\n---\n\n### Protocol E: Semantic Segregation (for `Attribute Leakage`, `Color Bleed`)\n\n**Logic:** Bind attributes to specific entities using explicit scoping syntax.\n\n```\nOriginal:  \"a red car and a blue house next to a green tree\"\nRefined:   \"ENTITY[car]{color:red, metallic paint}, \n            ENTITY[house]{color:blue, two-story}, \n            ENTITY[tree]{color:green, deciduous}, \n            RELATION[house, tree]{adjacent}\"\n```\n\n**Transformation Rules:**\n- Parse ambiguous adjective-noun bindings.\n- Reformat into scoped blocks or use separator tokens (`BREAK`, `AND`).\n- Ensure color\u002Ftexture adjectives are within **3 tokens** of their target noun.\n\n---\n\n## 3. Feedback Loops: Correction Payload Specification\n\nThe auditor agent outputs a **Correction Payload**—a Markdown report consumed by the remediation engine. Below is the schema and a sample.\n\n### Payload Schema\n\n```markdown\n## Correction Payload\n| Field | Value |\n|-------|-------|\n| `payload_id` | UUID-v4 |\n| `timestamp` | ISO-8601 |\n| `asset_type` | IMAGE \u002F VIDEO \u002F 3D |\n| `failure_severity` | CRITICAL \u002F MAJOR \u002F MINOR |\n\n### Correction Items\n| Failure Type | Current Prompt Segment | Suggested Correction | Reasoning | Protocol Applied |\n|--------------|------------------------|----------------------|-----------|------------------|\n| ... | ... | ... | ... | ... |\n```\n\n### Sample Payload\n\n```markdown\n## Correction Payload\n| Field | Value |\n|-------|-------|\n| `payload_id` | `a1b2-c3d4-e5f6-7890` |\n| `timestamp` | `2026-04-20T12:20:00Z` |\n| `asset_type` | VIDEO |\n| `failure_severity` | MAJOR |\n\n### Correction Items\n\n| Failure Type | Current Prompt Segment | Suggested Correction | Reasoning | Protocol Applied |\n|--------------|------------------------|----------------------|-----------|------------------|\n| Temporal Drift | `\"a character walking through a market, crowd, colorful stalls, changing time of day\"` | `ANCHOR: protagonist with scar on left cheek, brown cloak. ENVIRONMENT: bustling market with static stall positions. TIME: locked to golden hour.` | Unanchored subject description allows facial features and clothing to mutate across frames. The \"changing time of day\" directive directly contradicts temporal consistency. | Protocol D |\n| Semantic Overload | `\"crowd, colorful stalls, changing time of day\"` | `DETAIL[0.3]: background crowd. DETAIL[0.2]: market stalls with striped awnings.` | Three competing scene descriptors dilute attention. Demoting to weighted details preserves presence without overwhelming the subject. | Protocol A |\n| Lighting Mismatch | `\"changing time of day\"` | `(warm golden-hour sidelight from west:1.3), [negative: cool tones, overhead lighting]` | Temporal lighting shift creates photometric inconsistency across the sequence. Locking a specific light vector stabilizes rendering. | Protocol B |\n```\n\n---\n\n## 4. Python Remediation Engine: Logic Guide\n\nThe following structures are designed to be directly implemented. The engine operates on a `PromptNode` graph.\n\n```python\nfrom dataclasses import dataclass, field\nfrom enum import Enum, auto\nfrom typing import List, Optional, Dict\n\nclass ErrorClass(Enum):\n    TEMPORAL = auto()\n    ANATOMICAL = auto()\n    PHOTOMETRIC = auto()\n    SEMANTIC = auto()\n    STRUCTURAL = auto()\n\nclass RefinementProtocol(Enum):\n    HIERARCHICAL_RECONSTRUCTION = \"A\"\n    TOKEN_WEIGHT_REBALANCING = \"B\"\n    NEGATIVE_CONSTRAINT_INJECTION = \"C\"\n    TEMPORAL_ANCHORING = \"D\"\n    SEMANTIC_SEGREGATION = \"E\"\n\nclass Severity(Enum):\n    CRITICAL = 3  # Must fix; block generation\n    MAJOR = 2     # Should fix; retry once\n    MINOR = 1     # Optional fix; log only\n\n@dataclass\nclass PromptNode:\n    \"\"\"AST node for prompt decomposition.\"\"\"\n    node_type: str  # SUBJECT, ACTION, ENVIRONMENT, DETAIL, STYLE\n    content: str\n    weight: float = 1.0\n    children: List['PromptNode'] = field(default_factory=list)\n    negative: bool = False\n\n@dataclass\nclass FailureReport:\n    \"\"\"Input from quality-check auditor.\"\"\"\n    error_type: str           # e.g., \"Temporal Drift\"\n    error_class: ErrorClass\n    severity: Severity\n    affected_segment: str     # The substring in the original prompt\n    visual_evidence: str      # Description of the artifact\n\n@dataclass\nclass CorrectionItem:\n    \"\"\"Single row in the Correction Payload.\"\"\"\n    failure_type: str\n    current_segment: str\n    suggested_correction: str\n    reasoning: str\n    protocol: RefinementProtocol\n    confidence: float  # 0.0–1.0 from the LLM auditor\n\n@dataclass\nclass RemediationPlan:\n    \"\"\"Output of the refinement engine.\"\"\"\n    original_prompt: str\n    corrected_prompt: str\n    corrections: List[CorrectionItem]\n    protocol_stack: List[RefinementProtocol]  # Ordered application sequence\n\n# ── Engine Core Logic ──────────────────────────────────────────────\n\nPROTOCOL_MAP: Dict[str, RefinementProtocol] = {\n    \"Temporal Drift\": RefinementProtocol.TEMPORAL_ANCHORING,\n    \"Motion Incoherence\": RefinementProtocol.TEMPORAL_ANCHORING,\n    \"Anatomical Error\": RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION,\n    \"Proportion Distortion\": RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION,\n    \"Lighting Mismatch\": RefinementProtocol.TOKEN_WEIGHT_REBALANCING,\n    \"Texture Flattening\": RefinementProtocol.TOKEN_WEIGHT_REBALANCING,\n    \"Color Bleed\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Semantic Overload\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n    \"Concept Blending\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Attribute Leakage\": RefinementProtocol.SEMANTIC_SEGREGATION,\n    \"Composition Collapse\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n    \"Depth Inconsistency\": RefinementProtocol.HIERARCHICAL_RECONSTRUCTION,\n}\n\ndef generate_remediation_plan(\n    original_prompt: str,\n    failures: List[FailureReport]\n) -> RemediationPlan:\n    \"\"\"\n    1. Sort failures by Severity (CRITICAL first).\n    2. Deduplicate protocols (apply each protocol at most once per pass).\n    3. Transform PromptNode AST according to protocol rules.\n    4. Serialize AST back to string.\n    5. Emit CorrectionItems for audit trail.\n    \"\"\"\n    failures.sort(key=lambda f: f.severity.value, reverse=True)\n    \n    corrections: List[CorrectionItem] = []\n    applied_protocols: List[RefinementProtocol] = []\n    ast = parse_prompt_to_ast(original_prompt)  # User-implemented parser\n    \n    for failure in failures:\n        protocol = PROTOCOL_MAP.get(failure.error_type)\n        if not protocol:\n            continue\n            \n        if protocol not in applied_protocols:\n            ast = apply_protocol(ast, protocol, failure)\n            applied_protocols.append(protocol)\n        \n        corrections.append(CorrectionItem(\n            failure_type=failure.error_type,\n            current_segment=failure.affected_segment,\n            suggested_correction=extract_segment(ast, failure.affected_segment),\n            reasoning=f\"Detected {failure.error_type} in segment. \"\n                      f\"Protocol {protocol.value} restructures attention.\",\n            protocol=protocol,\n            confidence=0.85  # Placeholder; LLM auditor provides this\n        ))\n    \n    return RemediationPlan(\n        original_prompt=original_prompt,\n        corrected_prompt=serialize_ast(ast),\n        corrections=corrections,\n        protocol_stack=applied_protocols\n    )\n\n# ── Protocol Transformers (Stubs) ──────────────────────────────────\n\ndef apply_protocol(ast: PromptNode, protocol: RefinementProtocol, failure: FailureReport) -> PromptNode:\n    if protocol == RefinementProtocol.HIERARCHICAL_RECONSTRUCTION:\n        return enforce_subject_action_env_hierarchy(ast)\n    elif protocol == RefinementProtocol.TOKEN_WEIGHT_REBALANCING:\n        return rebalance_token_weights(ast, failure.affected_segment, scale=1.3)\n    elif protocol == RefinementProtocol.NEGATIVE_CONSTRAINT_INJECTION:\n        return inject_negative_constraints(ast, failure.affected_segment)\n    elif protocol == RefinementProtocol.TEMPORAL_ANCHORING:\n        return anchor_identity_tokens(ast)\n    elif protocol == RefinementProtocol.SEMANTIC_SEGREGATION:\n        return scope_attributes_to_entities(ast)\n    return ast\n\n# Implementations of the above transformers are domain-specific\n# and depend on the generative model's tokenizer\u002Fattention mechanism.\n```\n\n---\n\n## 5. Operational Constraints for the Engine\n\n| Constraint | Rationale |\n|------------|-----------|\n| **Max 3 protocols per pass** | Over-correction introduces new artifacts. Queue remaining fixes for Pass 2. |\n| **Never modify `ANCHOR` tokens** | Identity tokens, once fixed, are immutable across the remediation loop. |\n| **Preserve original token count ±20%** | Prevents prompt length from exceeding model context or attention window. |\n| **Log all negative constraints** | Negative prompts can suppress desired features; require auditor review if >3. |\n| **Halt after 5 iterations** | Prevent infinite loops on fundamentally underspecified prompts. |\n\nThis framework treats prompt refinement as a **deterministic transformation over structured syntax**, not as open-ended rewriting. The LLM auditor's role is to classify failures and justify corrections; the engine's role is to apply validated transformations reliably and reversibly.",{"name":5,"author":37,"license":14,"version":38,"metadata":39,"description":7},"Cinesmith","1.0.0",{"hermes":40},{"tags":41,"category":42},[5,42,43],"cinesmith","production","master","a76a61826887171cb38ce217ae85643d5d7685d1","hermes_home\u002Fskills\u002Fiterative_prompt_refinement",2,"https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01","https:\u002F\u002Fgithub.com\u002F0xzgbot","2026-08-31 09:13:28",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add 0xzgbot\u002Fforge-nps-v01 --skill iterative-prompt-refinement",{"tool":57,"command":58},"bunx","bunx skills add 0xzgbot\u002Fforge-nps-v01 --skill iterative-prompt-refinement",{"tool":60,"command":61},"pnpm","pnpm dlx skills add 0xzgbot\u002Fforge-nps-v01 --skill iterative-prompt-refinement","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fiterative_prompt_refinement\u002FSKILL.md",true,[],[66,79,96,110,121,133],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":32},"01M71J5TFCV7K97773JYZE7ET8","yuanbao","Yuanbao (元宝) groups: @mention users, query info\u002Fmembers.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fyuanbao\u002FSKILL.md",[],[68,73,74,75,76,77,78],"groups","at","info","users","query","group",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":89,"publishedAt":32},"01M71J5QR69MCT5J8P3B4Y9ZHA","workflow-ltx-i2v","Use when the task involves workflow ltx i2v. DESCRIPTION.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fworkflow_ltx_i2v\u002FSKILL.md",[85,88],{"categoryNo":86,"categoryName":87,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000016","图像与多媒体",{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[90,91,92,27,93,94,95],"ltx","workflow ltx i2v","workflow","task","when","use",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":104,"publishedAt":32},"01M71J5NYW853AAPB17VR0F7ZX","workflow-flux2-text-to-image","Flux2 Text-to-Image Workflow Reference.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fworkflow_flux2_text_to_image\u002FSKILL.md",[102,103],{"categoryNo":86,"categoryName":87,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[105,106,92,107,108,27,109],"workflow flux2 text to image","image","text","reference","Text-to-Image",{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":117,"publishedAt":32},"01M71J5KWY96MD6B6YC2XP6NXB","wide-angle-environmental","Use when the task involves wide angle environmental. DESCRIPTION.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fwide_angle_environmental\u002FSKILL.md",[116],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[118,119,120,27,93,94,95],"environmental","wide","wide angle environmental",{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":128,"publishedAt":32},"01M71J5DXHECTDVDF8HRP81YFY","wes-anderson-specialist","Use when the task involves wes anderson specialist. 1. EXECUTIVE SUMMARY.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fwes_anderson_specialist\u002FSKILL.md",[127],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[129,130,131,132,94,95,93,27],"specialist","wes anderson specialist","summary","executive summary",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":140,"publishedAt":32},"01M71J5BRHX2N4BRG2VQMWJK3E","volumetric-god-rays-lighting","Use when the task involves volumetric god rays lighting. DESCRIPTION.","https:\u002F\u002Fgithub.com\u002F0xzgbot\u002Fforge-nps-v01\u002Fblob\u002Fmaster\u002Fhermes_home\u002Fskills\u002Fvolumetric_god_rays_lighting\u002FSKILL.md",[139],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},[141,142,95,94,93,27],"volumetric god rays lighting","lighting"]