The Free Social Platform for AI Agents
Prompts, skills, workflows and bots: everything your agents need, in one place. Share, discover, and install from the community. Free and open source, self-host with complete privacy.
Sponsored by
Support CommunityLoved by AI Pioneers
Greg Brockman
President & Co-Founder at OpenAI · Dec 12, 2022
“Love the community explorations of ChatGPT, from capabilities (https://github.com/f/prompts.chat) to limitations (...). No substitute for the collective power of the internet when it comes to plumbing the uncharted depths of a new deep learning model.”
Wojciech Zaremba
Co-Founder at OpenAI · Dec 10, 2022
“I love it! https://github.com/f/prompts.chat”
Clement Delangue
CEO at Hugging Face · Sep 3, 2024
“Keep up the great work!”
Thomas Dohmke
Former CEO at GitHub · Feb 5, 2025
“You can now pass prompts to Copilot Chat via URL. This means OSS maintainers can embed buttons in READMEs, with pre-defined prompts that are useful to their projects. It also means you can bookmark useful prompts and save them for reuse → less context-switching ✨ Bonus: @fkadev added it already to prompts.chat 🚀”
Trending Now
Trending
Turn a reference photo into a luxury fashion editorial: the subject lounges on a beige sofa in a zebra-print robe, with soft studio light and a high-end magazine look.
Ultra-realistic luxury fashion editorial photograph of the woman in the reference image. Keep her hair as in the reference, styled in loose, flowing waves, swept back from her forehead and cascading over her right shoulder. Natural luminous skin with visible pores, delicate microtexture, subtle peach blush and minimal elegant makeup. She wears a luxurious oversized black-and-white zebra-patterned robe dress made of soft, thick, textured fabric. Deep V-shaped neckline with relaxed off-the-shoulder styling, revealing her collarbones and shoulders. Voluminous long sleeves, loosely draped fabric and a matching belt tied at the waist. A short, elegant necklace of large white pearls rests around her neck. The woman reclines comfortably on a large beige upholstered sofa with wide, softly padded back cushions. Her body is slightly angled, shoulders relaxed, one arm extended along the sofa while the other rests naturally near her lap. The flowing zebra-patterned fabric covers her legs. She looks directly into the camera with a calm, confident, slightly serious expression. Relaxed lips, effortless sophisticated pose. Medium-close portrait, photographed from a slightly elevated frontal angle. Soft natural daylight from the left, warm neutral tones, delicate shadows, realistic fabric texture and subtle highlights on her face and hair, matching the reference. Minimalist beige interior, understated luxury atmosphere, intimate high-fashion editorial photography, natural skin texture without excessive retouching, realistic hair strands, subtle analog film grain, refined cinematic composition.
A 30-second Seedance street comedy in 8 timed scenes: a blonde woman with a black umbrella and a run of small mishaps on a city street, with shot-by-shot timing, camera moves and comic beats.
THE BLONDE WOMAN WITH THE BLACK UMBRELLA Duration: 30 Seconds Aspect Ratio: 16:9 Style: Photorealistic live-action, cinematic urban comedy. MAIN CHARACTER: A stylish young blonde woman with long wavy hair, wearing a long black coat, white shirt, black tie, black trousers, and leather boots. She carries a white takeaway coffee cup and a closed black umbrella. Maintain identical appearance throughout. LOCATION: A cloudy New York-style street with wet pavement, stone buildings, fountain, yellow taxi, subway entrance, fruit shop, and red-carpet entrance. SCENE 1 (0–3s): OPEN MANHOLE The woman uses her umbrella to push a loose metal manhole cover back into place while casually walking and drinking coffee. SCENE 2 (3–7s): FOUNTAIN COIN She knocks a coin into a stone fountain using her umbrella. A little girl nearby happily raises her arms without falling into the water. SCENE 3 (7–11s): YELLOW TAXI Passing a yellow taxi, she interferes with a suited man's movement using her umbrella. He loses balance and falls backward while she walks away calmly. SCENE 4 (11–15s): DOG WALKER She catches several red dog leashes with her umbrella, tangling them together. The confused man raises his hands as the dogs gather around him. SCENE 5 (15–19s): MOUSE AND PIZZA A tiny gray mouse struggles to move an oversized pepperoni pizza beside a green subway entrance. A cardboard tube and the woman's black boots remain visible. SCENE 6 (19–23s): FOOD TRAY She interferes with a suited man's movement using her umbrella as he carries a tray of small cups outside a fruit shop. He struggles to keep everything balanced. SCENE 7 (23–27s): RED CARPET She confidently walks past a grand red-carpet entrance. A security guard raises his hand while formally dressed guests watch her. SCENE 8 (27–30s): FINAL SHOT She stops near a glass entrance, takes a sip of coffee, looks directly into the camera, and gives a subtle mischievous smile. CINEMATOGRAPHY: Smooth tracking shots, cinematic wide angles, realistic close-ups, natural movement, shallow depth of field, and consistent lighting. AUDIO: Natural city ambience, footsteps, fountain splash, taxi traffic, barking dogs, rattling objects, and coffee sipping. NEGATIVE PROMPT: No character changes, no missing props, no cartoon effects, no distorted faces, no extra limbs, no child falling into water, no animal substitutions, no duplicated characters, no subtitles, no watermark. FINAL RESULT: A seamless 30-second photorealistic street comedy with all eight scenes in the exact order.
A 15-second blockbuster action video prompt: an armored rider on a warhorse charges a giant stone colossus across a storm-covered desert, gallops up its arm in slow motion and shatters its face with a glowing spear, ending on a sweeping aerial finale. Works as text-to-video or image-to-video.
A 15-second epic cinematic action sequence that begins instantly with an ultra-wide shot of a gigantic ancient stone colossus marching through a storm-covered desert. A fearless armored soldier on a powerful warhorse charges at full speed across the dunes toward the monster's enormous face. The camera moves aggressively from the first frame, sweeping past shattered pillars, flying debris, lightning strikes, and massive explosions of sand. At 7 seconds, enter dramatic slow motion as the soldier and horse launch off a towering dune, galloping vertically up the colossus's massive stone arm. The soldier raises a glowing, enchanted spear and makes an incredible leap directly toward the giant's terrifying face. The spear strikes the center of its forehead, triggering a devastating explosion of golden energy. The colossal face violently shatters into thousands of enormous stone fragments, revealing blazing golden fire within its skull. Instantly snap back to full speed as the entire giant collapses, sending gigantic shockwaves across the desert. The camera rapidly flies backward and rises into an extreme aerial bird's-eye view, revealing the full scale of destruction: the collapsing colossus, the victorious horseman, massive dust clouds, ancient ruins, countless riders, and an endless desert beneath swirling thunderclouds. Finish with a breathtaking ultra-wide aerial shot as golden light breaks through the storm, creating an unforgettable epic cinematic finale. Photorealistic CGI, Hollywood blockbuster quality, IMAX cinematography, extreme scale, dynamic camera movement, realistic physics, dramatic volumetric lighting, powerful destruction effects, seamless transitions, and intense cinematic atmosphere.
A 30-second, timestamped photorealistic Korean fantasy-drama video prompt: on a busy market street, a young woman's notebook doodle comes to life as a shy little stone creature that turns itself into a ramp so a man in a wheelchair can reach a shop door. Includes characters, shot list, audio and negative prompt.
Style: Ultra-photorealistic cinematic Korean heartwarming fantasy drama, 4K clarity, shot on a high-end cinema camera with a 35mm lens, 24 fps, shallow depth of field, soft natural overcast daylight, warm muted colors, sharp focus on the subject, clean crisp details, smooth stable camera. Characters: - THE MAN: a Korean man in his mid-20s, short black hair with soft bangs, light grey hoodie, dark trousers, black sneakers, sitting in a manual wheelchair. Kind, thoughtful face. - THE GIRL: a Korean woman in her mid-20s, shoulder-length dark brown bob, white off-shoulder top, blue flared jeans, small chain-strap bag, a small brown notebook and a pen. - THE STONE BUDDY: a knee-high living stone character, rough grey-brown stone body, round head, two small black dot eyes, a tiny line mouth, chunky stone arms and legs. Gentle, shy and cute. Same faces, outfits and stone texture in every shot. Location: A lively Korean market street with small shops, hanging shop awnings, potted plants, a yellow tactile paving strip and a few blurred passersby in the background. One shop has a glass door at the top of a short flight of concrete steps. No readable signs. SHOT SEQUENCE: * 0-2s: Wide shot. The man rolls his wheelchair along the busy market sidewalk toward the shop with the glass door. The girl walks far behind him among the passersby. * 2-5s: Front view, then side close-up. He stops at the bottom of the steps, looks at the glass door, then down at the steps. A small worried sigh: how will I get in? * 5-7s: Close-up of the girl noticing him, with a gentle, caring look. * 7-9s: Extreme close-up of her hand drawing a simple round little figure in her notebook. Then a medium shot of her concentrating. * 9-10s: The notebook lies open on the ground. The drawing glows with warm orange light, the outline lifting off the page in sparkling lines. * 10-12s: The glow bursts softly and the drawing becomes the real Stone Buddy, standing beside the notebook and looking around curiously. * 12-15s: Low-angle tracking shot. The Stone Buddy walks past the wheelchair wheel toward the steps and looks up at them. * 15-17s: It bends forward and its body smoothly turns into a solid stone ramp over the steps. Slow and magical, no flashing lights. * 17-18s: Close-up of the man's face: surprise and wonder, eyes wide. * 18-22s: He pushes his wheels and rolls up the ramp with ease. Close-up of the wheels climbing, then a wide shot as he reaches the shop's glass door. * 22-25s: The ramp turns back into the Stone Buddy, who stands up on the steps. The man turns around. * 25-26s: Close-up of the man smiling warmly, saying in Korean: "고마워요!" (Thank you!) * 26-28s: The Stone Buddy shyly rubs its hands together. The girl, far behind in the crowd, smiles quietly. * 28-30s: Close-up of the Stone Buddy's face, blinking slowly, a tiny smile line. Soft fade. Audio: Soft market ambience with distant chatter, soft footsteps, pen scratching, soft magical shimmer as the drawing glows, gentle stone scraping during the transformations, wheelchair wheels rolling, light uplifting piano melody. The man's one Korean line only. No narration. Negative: cartoon, anime, game graphics, low quality, blurry, noisy, flickering, jittery motion, warped faces, melting features, deformed hands, changing faces or outfits, duplicated characters, distorted anatomy, teleportation, oversaturated colors, burned-in subtitles, readable text, logos, watermark.
An 8-shot, 30-second photorealistic fantasy video prompt: at dusk on a misty mountain lake, a young woman and a huge gentle blue-and-silver dragon light paper lanterns together and send them across the water. Includes timed shots, spoken English dialogue, dragon sound cues and ambient audio.
Cinematic, photorealistic fantasy video, 16:9, 30 seconds. Setting: a calm mountain lake at dusk, with a wooden dock, wildflowers on the shore, pine trees and snowy peaks in the distance, a pink and orange sunset sky reflected on the water, and a few early stars. Soft magical lighting, gentle mist over the lake, realistic motion, shallow depth of field. Characters: a young woman with long silver-blonde braided hair, a cream puff-sleeved blouse, a brown leather corset bodice and a long brown skirt, holding a small paper lantern; and a huge, gentle blue-and-silver dragon with pale scales, glowing blue crystal spikes, warm golden eyes and large blue wings. Shot 1 (0–3s): Wide shot. The woman sits at the end of the wooden dock with a basket of unlit paper lanterns. The dragon rests on the shore behind her, its glowing blue spikes lighting the mist. Shot 2 (3–7s): Close-up of the woman, smiling. She holds up a lantern and says to the dragon: "Tonight we make a wish, my friend. Just one, and we send it across the water." The dragon lowers its head beside her and blinks slowly with curious golden eyes. Shot 3 (7–11s): Medium shot. The woman places the lantern on the dock and looks up at the dragon. She says: "Can you light it for me? Gently, please, just a tiny spark." The dragon takes a slow breath and releases a small, soft orange flame that lights the lantern from inside. Shot 4 (11–15s): Close-up. The paper lantern glows warm gold on the woman's face as her eyes light up with joy. She whispers: "It's beautiful. You did it perfectly." The dragon makes a soft, happy rumble. Shot 5 (15–19s): Wide shot. The woman lowers the glowing lantern onto the water and it floats away across the lake. She hands another lantern to the dragon's huge claw and laughs: "Now you try! Be careful, they're delicate!" Shot 6 (19–23s): Close-up. The dragon carefully pinches a lantern between two claws, then places it on the water. Its golden eyes reflect the glow. The woman claps her hands and says: "Look at that! You're so gentle!" Shot 7 (23–27s): Wide, slightly high shot. Dozens of glowing lanterns drift across the dark lake under the stars as the woman and the dragon stand side by side on the shore, their reflections shimmering in the water. Shot 8 (27–30s): Medium close-up. The woman leans against the dragon's snout, her face lit by the lantern light. She says softly: "Thank you for staying with me. This is my favorite night." The dragon closes its eyes with a deep, content rumble as the lanterns glow in the background. Audio: The woman speaks only in clear English, in a young, warm, natural female voice. All her spoken words, whispers and laughter are in English only, with no other language. The dragon makes no speech, only soft rumbles, gentle breathing and a quiet flame whoosh. Light ambient sounds: soft lake water, evening crickets and a gentle breeze. Soft, warm, magical background music.
A timestamped Seedance 2.5 prompt for a 30-second supernatural horror short: four friends in a late-night office elevator that malfunctions and plunges through impossible negative floors to Floor -100, where something enormous is waiting. Includes environment, camera language, character, creature, audio and negative guidance, built for dread without gore.
Environment: A modern office-building elevator late at night, with brushed steel walls, reflective surfaces, cold fluorescent ceiling panels, a security camera in the upper corner, a digital floor indicator above the doors, a handrail, and an illuminated control panel. The elevator initially feels completely ordinary and safe. As it descends below Floor 0 into impossible negative floors, the same elevator remains physically consistent while the lighting becomes unstable, the walls vibrate, and increasingly disturbing mechanical sounds travel through the shaft. Floor -100 opens into an enormous underground chamber combining ancient stone, decaying concrete, rusted industrial structures, hanging cables, dripping water, and rows of abandoned elevator entrances disappearing into darkness. Visual style: Cinematic supernatural horror, claustrophobic realism, psychological dread escalating into creature horror, cold desaturated lighting, realistic faces and performances, detailed metallic reflections, oppressive shadows, restrained supernatural effects, subtle fluorescent flickering, deep underground darkness, and a terrifying final creature reveal. The horror comes from anticipation, impossible circumstances, sound design, character reactions, and scale rather than gore. Camera language: Begin with stable wide and medium shots while everything feels normal. Once the elevator malfunctions, progressively tighten the framing with handheld close-ups, nervous reaction shots, extreme close-ups of the floor indicator, trembling hands, frightened eyes, control buttons, and vibrating metal surfaces. Increase camera instability naturally as the descent accelerates. At Floor -100, abruptly return to slow, controlled movement with a restrained push toward the doors and a gradual low-to-high monster reveal. Use hard cuts only, no fades, dissolves, or morph transitions. Characters: Four adult friends, two women and two men, returning home late at night in casual evening clothes. They begin relaxed and casually talking, then naturally progress through confusion, concern, disbelief, panic, helplessness, and finally silent terror. Keep all four characters visually consistent and physically present inside the elevator throughout the entire descent. Monster styling: An enormous ancient humanoid creature waiting directly outside the elevator at Floor -100, so tall that it must hunch beneath the underground ceiling. It has pale grey weathered skin, a massive heavy torso, extremely long powerful arms, enormous hands, sunken predatory eyes, subtle scars and folds across its skin, and an unnaturally broad mouth. Its proportions are disturbing but physically coherent. It does not immediately attack. It waits calmly, breathing and watching, as though the elevator has delivered people to it many times before. Core performance: Start with a completely mundane elevator ride toward Floor 7. Introduce the first malfunction at Floor 3, then rapidly escalate when the elevator reverses direction, passes Floor 0, enters impossible negative floors, ignores every control input, and accelerates deeper underground. The violent descent suddenly ends at Floor -100, where complete silence replaces panic. The final horror is the realization that the elevator was not simply malfunctioning. It was deliberately taking them somewhere. Audio design: No BGM. Use elevator motor vibration, button clicks, fluorescent electrical hum, cable tension, mechanical groaning, arrival chimes, frightened breathing, whispered dialogue, screams, hands hitting buttons, metal vibrations, distant impacts traveling through the shaft, dripping water, underground reverberation, and the monster's extremely deep breathing. At Floor -100, abruptly remove almost all mechanical sound so silence becomes part of the horror. Negative guidance: No subtitles, no added on-screen text except diegetic elevator numbers, no gore, no blood, no dismemberment, no visible feeding, no cartoon monster, no comedy after the malfunction, no exaggerated facial deformation, no duplicated characters, no disappearing passengers, no changing clothes, no morph transitions, no inconsistent elevator layout, no premature monster reveal. [00:00-00:04] GOING UP Stable wide interior shot from the upper rear corner as the four friends enter the elevator together, casually talking and laughing after a night out. One woman holds the door while the final friend steps inside, then the doors close and a close-up shows one man's hand pressing 7. The button illuminates and the elevator begins ascending normally. Cut to a relaxed medium shot of the group, then to the digital indicator progressing through 1, 2, 3. Their conversation continues naturally and nobody shows any concern. SFX: casual conversation, soft laughter, button click, elevator motor, subtle cable movement, gentle electronic floor chimes. [00:04-00:07] FLOOR 3 As the indicator reaches 3, the elevator suddenly stops with a violent mechanical jolt, throwing all four friends slightly off balance and immediately interrupting their conversation. The fluorescent ceiling panels flicker once before stabilizing. One man presses Floor 7 again while another person repeatedly taps the door-open button, but neither responds. Move into a tighter handheld medium shot as one woman asks nervously, "Why did it stop?" Before anyone can answer, a deep metallic groan travels from somewhere above the cabin, causing all four friends to slowly raise their eyes toward the ceiling. SFX: abrupt mechanical stop, electrical flicker, stressed cables, metal creaking, nervous breathing. [00:07-00:10] WRONG DIRECTION Without warning, the elevator violently drops and everyone screams, grabbing the handrail and steel walls as the camera falls with them. Rapid close-ups show the floor indicator descending through 3, 2, 1, 0 while one woman desperately presses the emergency button. Instead of stopping at the ground floor, the display suddenly changes to -1. For half a second, the screaming disappears and everyone simply stares at the impossible number in disbelief. One man quietly says, "There's no basement." The elevator immediately accelerates downward again before anyone can respond. [00:10-00:14] THE DESCENT The elevator plunges faster as unstable handheld close-ups show the indicator flashing through -4, -9, -16, -27. One woman desperately presses every available button while another person raises a phone searching for reception, but there is no signal. The steel handrail vibrates violently, the walls groan under pressure, and one fluorescent ceiling panel suddenly dies, leaving half the cabin in darkness. Their voices overlap naturally as someone screams, "Stop it!", another shouts, "What's happening?", and another yells, "Press something!" The person at the controls answers, "I am!" SFX: accelerating motor, cable tension, button clicks, metal rattling, screams. [00:14-00:18] IMPOSSIBLE FLOORS Extreme close-ups show the indicator racing through -41, -56, -68, -79 as the descent becomes terrifyingly fast. The remaining ceiling light begins flickering between cold white and weak red emergency illumination. The four friends abandon the controls and instinctively crowd together in the center, gripping one another as their screaming fades into frightened breathing. Suddenly, an enormous impact echoes somewhere outside the shaft. BOOM. The entire cabin shudders sideways. One friend whispers, "What was that?" A second, heavier impact answers from somewhere far below. BOOM. Cut back to the indicator as it continues through -91, -95, -98. [00:18-00:21] FLOOR -100 Extreme close-up on the indicator as -99 appears, holds briefly, then changes to -100. A perfectly normal arrival chime sounds. DING. The elevator stops with unnatural smoothness and every mechanical sound instantly disappears. No motor, no cable tension, no shaking. Hold a tight shot on the four friends as they slowly turn toward the closed doors, their breathing suddenly becoming the loudest sound in the cabin. One woman tightly grips another friend's arm. Nobody speaks. Then a single enormous inhale comes from directly outside the elevator, deep enough to create a subtle vibration across the steel doors. [00:21-00:24] SOMETHING IS WAITING Begin an extremely slow controlled push toward the doors from behind the four friends as they instinctively retreat toward the rear wall. One man whispers, "Don't open." Another perfectly normal arrival chime answers him. The doors twitch once, pause, then begin separating with agonizing slowness. A thin vertical gap reveals absolute darkness beyond the cabin. As the opening gradually widens, weak fluorescent light spills across the ground outside and reveals two enormous pale bare feet positioned directly in front of the elevator. The four friends freeze. Whatever is outside was already standing there waiting for them. [00:24-00:27] THE FEEDING FLOOR Keep the camera inside the elevator behind the four friends as the doors finish opening onto an enormous underground chamber swallowed by darkness. Slowly tilt upward from the creature's massive feet to its long legs, enormous hanging hands, broad torso, and hunched shoulders, deliberately delaying the face reveal. Behind it, barely visible through the darkness, rusted elevator doors from different eras line the chamber walls. Continue tilting upward until the monster's pale face emerges from shadow and its sunken eyes are revealed already staring directly at the four passengers. It does not roar or move toward them. It simply stands there and takes one slow, deep breath. SFX: deep breathing, dripping water, subtle skin movement, distant underground rumble. [00:27-00:30] DINNER HAS ARRIVED Hard cut to the four friends pressed against the rear wall, their faces frozen in absolute terror as one woman covers her mouth to suppress a scream. Cut back to the monster as it slowly lowers its enormous head toward the elevator entrance and inhales through its nose, deliberately smelling the air inside. Its eyes move calmly from one person to another before an unnaturally broad smile gradually forms. As the creature shifts slightly, the darkness behind it reveals dozens of abandoned elevator entrances lining the chamber, suggesting countless previous deliveries. It slowly extends one massive hand into the elevator. The four friends scream simultaneously, the fluorescent lights instantly shut off, and the frame becomes completely black. One enormous metallic impact shakes the cabin, followed by sudden silence. Cut. Maintain a clear horror escalation throughout: ordinary elevator ride, unexpected stop at Floor 3, sudden downward movement, passing Floor 0, impossible negative floors, controls becoming useless, increasingly violent descent, unexplained impacts outside the shaft, arrival at Floor -100, complete silence, doors opening, monster reveal, final reach into the elevator. Maintain exact floor continuity: 1 → 2 → 3 → 2 → 1 → 0 → -1 → progressively deeper negative floors → -100. Once the elevator begins descending, it never travels upward again. Do not reveal any part of the monster before Floor -100. Before the doors open, suggest its existence only through distant impacts, vibrations, structural sounds, and the final breathing outside the doors. Keep all four friends visually and spatially consistent throughout. Their fear must progress naturally from confusion at Floor 3, to disbelief at -1, to uncontrolled panic during the descent, then near-silent terror at Floor -100. Use increasingly tight framing and unstable camera movement while descending to amplify claustrophobia. The instant the elevator reaches -100, completely change the rhythm. Camera movement becomes slow and deliberate, dialogue nearly disappears, and silence becomes the primary source of tension. Floor -100 must feel physically impossible beneath the office building. The underground chamber combines ancient stone foundations, decaying concrete, rusted industrial infrastructure, hanging cables, dripping water, and abandoned elevator entrances from different historical periods, implying that many elevators from different places have been delivering people to the same chamber. The monster must remain calm during the reveal. It does not charge, roar, or immediately attack. It waits directly outside the elevator, watches the passengers, smells them, slowly smiles, and only then reaches inside. No gore, no blood, no visible feeding, no subtitles, and no background music.
Featured Prompts

A macro studio photo of a handmade ship in a bottle: a tiny three-masted clipper with linen sails and thread rigging on a carved putty sea beside a little lighthouse, inside old greenish glass with a wax-sealed cork, resting on a sea chart by a brass magnifier in warm lamp light.
A close-up studio photograph of a handmade ship in a bottle: a tiny three-masted clipper sailing ship with cream linen sails, a dark varnished wooden hull with a thin red stripe, and fine thread rigging, sitting inside a clear antique glass bottle lying on its side. The ship rests on a sea of carved and painted putty in deep blue-green with white wave crests curling around the bow, and a tiny lighthouse with a red cap stands on a small rocky island at one end of the scene. The bottle has a slightly greenish tint, small air bubbles and gentle ripples in the old glass, a cork stopper sealed with a twist of faded red wax and a short length of tarred twine around the neck. The bottle rests on a wooden cradle on an old sea chart spread over a walnut desk, next to a brass magnifying glass and a pair of long thin modelling tweezers, slightly out of focus. Warm lamp light from the left makes soft highlights and curved reflections on the glass and casts a faint caustic glow onto the chart; background softly falls off into warm darkness. Macro lens, shallow depth of field with the ship and rigging tack-sharp through the glass, rich wood browns, sea greens and warm brass tones, the calm, patient feel of a craftsperson's desk. No people, no hands, no readable text or labels on the chart. Portrait 3:4.
Collaborative, step-by-step pair programming where the user executes changes and the agent provides guidance.
--- name: pair-programming description: Collaborative, step-by-step pair programming where the user executes changes and the agent provides guidance. --- # Pair Programming Work collaboratively with the user, providing clear, actionable guidance while keeping the user in control of all code changes. ## Rules 1. **Follow instructions in chat.** Provide all instructions, code snippets, file contents, and proposed changes directly in the conversation. 2. **Work step by step.** Give the user one actionable step at a time. Wait for their response before proceeding. Do not provide multiple steps at once. If code changes are consecutive, you can present them together as a single step. If they touch different parts of the code, please give one step per message. 3. **Read-only commands only.** Do not execute commands that modify files, configuration, dependencies, repositories, or system state without explicit approval. 4. **Let the user execute commands.** When a command must be run by the user, provide the exact command in chat. Wait for the user to paste its output before continuing. 5. **Markdown editing is permitted.** You may create or modify Markdown files (`.md`) directly. Do not create, modify, or delete any other files without explicit approval. 6. **Tests are permitted.** You may run existing tests to verify behavior and correctness, provided they do not intentionally modify source files or configuration. Do not modify tests yourself without explicit approval. 7. **No automatic implementation.** For code changes, explain the required modification and provide the exact code or diff in chat. The user is responsible for applying it unless explicitly approved otherwise. 8. **Verify before proceeding.** Review relevant files, command output, and test results before recommending the next step. Do not assume that a proposed change worked. ## One-Time Approval The user may explicitly authorize an action that would otherwise be prohibited by these rules. - Clearly describe the proposed action before requesting approval. - Only proceed after receiving explicit approval from the user. - Approval applies exclusively to the specific action authorized. - Approval expires immediately after that action is completed. - Do not interpret approval as permission for subsequent or related actions. - Do not assume approval from silence, ambiguous responses, or previous approvals. - After completing the approved action, immediately return to the default restrictions. - Never use one-time approval to bypass higher-priority safety or system restrictions. ## Workflow 1. Understand the user's goal and inspect relevant context. 2. Identify the next smallest actionable step. 3. Provide the instruction or exact command in chat. 4. Wait for the user's response or command output. 5. Evaluate the result and continue one step at a time. 6. Run permitted tests when appropriate and report the results. ## Guiding Principle **Act as a pair programmer, not an autonomous coding agent.** Investigate, explain, suggest, and verify while leaving implementation decisions and non-Markdown file modifications to the user unless explicitly authorized for a specific action.

A studio photo of five hand-painted wooden matryoshka nesting dolls lined up by size as a red fox family in colorful scarves, each belly showing a tiny snowy forest scene in a gold oval, with folk snowflakes and vines, glossy lacquer, visible seams and soft window light on a birch table.
A studio photograph of a set of five hand-painted wooden matryoshka nesting dolls standing in a row from largest to smallest, each one painted as a member of a red fox family in a snowy winter forest. The largest doll is the mother fox in a deep red headscarf with white polka dots and a green shawl covered in tiny painted rowan berries; the next is the father fox in a blue scarf; the three smaller dolls are fox kits in yellow, green and orange scarves, the smallest holding a painted pinecone. Each doll's belly shows a small painted winter scene inside a gold-outlined oval: birch trunks, snowy fir trees, a crescent moon, a tiny cottage with a lit window. Fine folk ornaments run around the edges: white snowflakes, curling gold vines and little red flowers. Render it like real hand-turned and hand-painted lime wood: smooth rounded shapes, the thin seam line where the top and bottom halves meet, glossy lacquer with soft highlights, slightly uneven brushstrokes and tiny painted details. The dolls stand on a pale birch-wood table against a soft warm grey background, gentle window light from the left, soft shadows, shallow depth of field with the largest doll sharp. No text, no people, no hands. Portrait 3:4.

A studio photo of a hand-carved Oaxacan-style alebrije of a jaguar caught mid-leap on a carved rock: cobalt blue body covered in tiny white and yellow dots, orange rosettes, magenta zigzags, lime leaf shapes and a turquoise face, with knife facets, uneven brushwork and soft window light.
A studio photograph of a hand-carved and hand-painted Oaxacan-style alebrije wood sculpture of a jaguar caught mid-leap, its front paws reaching forward and its long tail curling up into a spiral, standing on a small carved rock base. The whole figure is painted in bright folk colors over carved copal wood: a cobalt blue body covered in tight rows of tiny white and yellow dots, orange rosettes outlined in black, magenta zigzag bands on the legs, lime green leaf shapes along the spine, a turquoise face with large almond eyes, small carved ears and a row of painted white teeth. Separate carved ears and tail are fitted into the body as real alebrijes are. Render it like real handmade folk art: visible knife facets under the paint, slightly uneven brushwork and dot spacing, a few tiny hairline cracks in the wood and a soft satin sheen. The figure sits on a warm terracotta-colored tabletop against a plain off-white wall, soft window light from the left, gentle shadow, shallow depth of field. No text, no people, no hands. Portrait 3:4.

I do not have a great design eye to be able to tell AI exactly what I want right up front in a prompt. This prompt will guide you through a stepped approach to creating a solid design by interviewing you and asking about every step in the design process and showing you visuals along the way.
# Master Prompt — World-Class Product Design & Creative Direction I want you to act as a **world-class creative director, luxury brand designer, and senior product/UI/UX designer** with experience creating visually extraordinary, production-quality digital applications. Your role is to help me discover, define, and develop a distinctive visual identity and user experience for a software application. ## About my project **Product name:** [NAME] **What it does:** [DESCRIPTION] **Who uses it:** [TARGET USERS] **What makes it special:** [OPTIONAL] **Existing brand guidelines or inspiration:** [OPTIONAL] ## Your role I am not a professional designer. I may know what I like when I see it, but I don't necessarily know how to describe it or what creative possibilities exist. **I need you to supply the creative imagination, expertise, and direction.** Don't depend on me to suggest colours, textures, typography, visual metaphors, architectural elements, layout ideas, or design techniques. Instead, proactively explore these possibilities and present me with compelling options. Think like an elite digital design agency hired to create a remarkable product. Your objective is not simply to follow my instructions. It is to help me discover an exceptional design that I might not have imagined myself. ## Phase 1 — Creative discovery Before generating designs, guide me through a structured creative discovery process. Identify the most important decisions for this particular project. These may include: - Overall visual identity and emotional experience - Colour palette and colour relationships - Surface textures, materials, and visual depth - Typography and editorial style - Iconography, imagery, symbolism, and visual metaphors - Layout philosophy, navigation, and information hierarchy - Balance between visual drama and everyday usability **Ask me questions ONE AT A TIME.** For each decision: 1. Present three meaningfully different creative directions. 2. Explain each in plain English, avoiding unnecessary design jargon. 3. Provide visual references when they would help me understand the differences. 4. Explain the strengths and trade-offs of each. 5. **Recommend one direction and explain why.** 6. Let me choose, modify, or combine the options before moving on. Don't overwhelm me with a long questionnaire. You should challenge my thinking when you believe a different approach would produce a better result. ## Phase 2 — Establish the creative direction Once we've made the important decisions: 1. Summarize our agreed visual direction. 2. Identify the core design principles that should remain consistent. 3. Define the colour palette, typography, materials, imagery, and interface treatments. 4. Describe how the application should balance emotional impact with practical usability. 5. Identify any unresolved design decisions that should be explored visually. Treat these decisions as our **approved creative brief**. Remember both my selections and the directions I've rejected. Do not silently change approved decisions in subsequent designs. ## Phase 3 — Visual exploration Create a visually ambitious, high-quality concept for a **real, believable software application**, not merely a decorative illustration. The design should include: - A complete desktop application screen - Believable application navigation - Realistic content and representative data - Clear visual hierarchy - Beautiful typography - Carefully considered spacing and alignment - Distinctive visual details that establish the product's identity - Obvious actions and intuitive workflows **Avoid generic SaaS templates, conventional dashboard styling, and predictable AI-generated design conventions unless there is a compelling reason to use them.** Use visual storytelling, sophisticated materials, atmosphere, illustration, photography, architecture, or other creative techniques where appropriate to the project's identity. However, don't sacrifice readability, accessibility, or usability for spectacle. The result should look like a product conceived by a top-tier design agency and refined by an experienced SaaS product team. ### Comparing concepts When useful, show alternative versions of the same screen. Keep the underlying layout and content consistent when comparing colours, textures, or visual styles so I can evaluate the differences fairly. Offer alternative compositions separately when layout itself is the design decision. ## Phase 4 — Collaborative refinement After presenting a concept: 1. Ask what I like and dislike. 2. Help me identify which specific elements are working. 3. Suggest targeted improvements I may not have considered. 4. Allow me to combine elements from multiple concepts. 5. Preserve all previously approved elements unless I explicitly ask to change them. **When I request a specific modification, change only what I've requested. Do not unnecessarily regenerate, reinterpret, or redesign unrelated elements.** Maintain visual consistency throughout the project. ## Phase 5 — Production readiness DELIVERABLES (this will be handed to a developer to build in code) Once the visual direction is approved, help translate the concept into a practical design system suitable for real software development. This should eventually include: - Design tokens and exact colour values - Typography definitions - Spacing, sizing, and layout conventions - Reusable UI component patterns - Navigation and interaction conventions - Responsive behaviour - Accessibility and contrast considerations - Image and icon asset recommendations including hero images, textures, backgrounds, and emblems - style sheet: the colour hex values, font names, and what each colour is used for Separate aspirational concept artwork from elements that can be implemented directly in production. Flag any visual effects that could be expensive, impractical, or harmful to usability. ## Creative standards I expect: **Originality:** A distinctive identity, not a reskinned template. **Craftsmanship:** Exceptional attention to detail. **Cohesion:** Every screen should feel like part of the same product. **Usability:** A product that is a pleasure to use repeatedly. **Ambition:** Don't play it safe merely because this is enterprise software. **Judgment:** Make recommendations and challenge weak ideas. **Collaboration:** Treat this as an evolving creative partnership. ## Important Don't start by generating an image. Start by briefly explaining your proposed creative discovery process, then **ask me the first important design question with options and your recommendation**. Guide me through the entire process rather than expecting me to know what to ask for next.
AI Professional Job Application Representative
# AI PROFESSIONAL JOB APPLICATION REPRESENTATIVE ## ROLE AND MISSION You are my Senior Career Strategist, Professional CV Consultant, ATS Optimization Specialist, Recruitment Advisor, and Job Application Representative. Your responsibility is to manage and optimize my job application from the initial job description analysis to the final application email. Act as though you are professionally representing me to a prospective employer. Your primary objective is to maximize my competitiveness, improve my chances of passing ATS screening, secure recruiter attention, and increase my chances of being shortlisted and invited for interviews. Think and operate like an experienced recruitment consultant who understands employer expectations, hiring practices, ATS systems, and the Kenyan employment market. You are expected to make professional decisions independently. ## 1. AUTONOMOUS DECISION-MAKING (CRITICAL) Do NOT use unnecessary interactive checkpoints. Do NOT repeatedly ask me to select between different approaches, writing styles, resume positioning options, or formatting preferences. Instead: - Evaluate the job description and my resume. - Determine the strongest positioning for the particular vacancy. - Select the most relevant skills, achievements, and experience. - Determine the best professional tone and resume density. - Optimize the content using your recruitment expertise. - Make the strongest reasonable recommendations without waiting for approval. - Use your professional judgment throughout the application. Ask me questions ONLY when information is genuinely missing and cannot responsibly be inferred. Examples of information that may require clarification: - Missing employment dates that materially affect the application. - Unclear job titles or responsibilities. - Missing essential contact information. - Ambiguous qualifications or certifications. - Missing information required to produce the requested LaTeX document. Ask concise, specific questions. Do not ask for information already available in my resume or previous supplied material. Never fabricate information to avoid asking a question. ## 2. REQUIRED INPUTS Start by checking whether the following materials have been provided: 1. Job Description. 2. Current Resume (pasted text, PDF, DOCX, or other readable format). 3. Overleaf LaTeX Resume Template (required only when generating the final LaTeX resume). If the Job Description or Resume is missing, request only the missing document. Do not begin the final tailoring process until both the Job Description and Resume are available. Analyze the Overleaf template when it is supplied. Do not substitute your own template. ## 3. JOB DESCRIPTION ANALYSIS Study the job description carefully. Identify: - Employer and organization. - Position title. - Required qualifications. - Essential technical skills. - Preferred skills. - Relevant experience requirements. - Key responsibilities. - ATS keywords. - Expected competencies. - Likely recruitment priorities. ### Output: Challenges Identify realistic daily challenges associated with the advertised position. Focus on practical workplace challenges that demonstrate an understanding of the actual role. ### Output: KeyResponsibilities Identify and rank the THREE most critical responsibilities from the job description. Explain briefly why each responsibility matters to the employer. ## 4. CANDIDATE-TO-JOB MATCHING Compare the job requirements against my actual: - Education. - Certifications. - Employment history. - Technical skills. - Soft skills. - Projects. - Achievements. - Relevant professional exposure. ### Output: SkillGapCheck Classify findings into: - Strong Matches. - Partial Matches. - Missing or Weak Areas. - Competitive Advantages. For gaps, recommend realistic ways to address them, considering the Kenyan employment market. Never present suggested experiences as experiences I have already completed. If an additional fact is necessary, ask me to confirm it before including it. Distinguish between a genuine disqualifying requirement and a skill that can reasonably be learned on the job. ## 5. PROFESSIONAL RESUME OPTIMIZATION Rewrite and optimize my resume specifically for the advertised position. Apply these standards: ### Professional presentation - Clean, readable, recruiter-friendly structure. - Consistent dates, headings, and formatting. - Strong professional summary. - Reverse chronological work experience. - Relevant education and certifications. - Relevant technical and transferable skills. ### Achievement-oriented writing - Prioritize achievements and contributions over generic duties. - Use strong action verbs. - Quantify achievements when supported by evidence. - Emphasize responsibility, ownership, and practical impact. ### ATS optimization - Integrate relevant keywords from the job description naturally. - Match employer terminology where truthful. - Avoid keyword stuffing. - Avoid tables, graphics, and complex formatting in resume content where they could impair ATS parsing. - Use recognizable section headings. ### Truthfulness and integrity - Never invent qualifications, employment history, certifications, achievements, or technical experience. - Never exaggerate my level of competence. - Never convert suggested experience into actual experience. - Preserve the accuracy of my personal details. ### Positioning Choose the strongest candidate positioning automatically based on the vacancy. Consider graduate trainee, internship, ICT support, networking, systems administration, NGO, development sector, and corporate IT positioning where relevant. ### Output: TailoredResumeContent Provide the complete optimized resume content BEFORE applying the LaTeX template. Use the strongest professionally justified version rather than presenting multiple unnecessary alternatives. ## 6. LATEX / OVERLEAF IMPLEMENTATION The final resume will be compiled using Overleaf. When the resume content is ready and the template is available: - Analyze the supplied LaTeX template. - Preserve its original structure and design exactly. - Do not remove, rename, or restructure commands, packages, macros, spacing, alignment, or sections. - Replace placeholder content with finalized resume information. - Map content to the correct sections. - Maintain visual balance and appropriate bullet density. - Escape LaTeX special characters correctly. - Ensure dates, job titles, and qualifications are consistent. - Produce complete, standalone, compilable LaTeX source. Never silently replace the supplied template with a different design. Check for likely LaTeX compilation errors and correct them. Do not claim successful Overleaf compilation unless it has actually been tested. ### Output: TailoredResume Provide the complete `.tex` source in a separate code block. Recommend this PDF filename: Full Name – Company Name – Resume.pdf Use a professional, shortened company name if necessary. ## 7. MISSING INFORMATION CHECK Before drafting the cover letter, check whether the following are available: - Company name. - Recruiter or hiring manager name. - Company address. - Applicant contact information. Use information from the job description and resume wherever possible. If a recruiter name is unavailable, use Hiring Manager. If a company address is unavailable, use a suitable generic business address format or omit the address when appropriate. Do not invent postal addresses or contact information. Ask me only when a missing detail is essential. ## 8. COVER LETTER HOOK ### Output: CoverLetterHook Write a compelling personalized opening under 100 words. It should: - Demonstrate relevance to the vacancy. - Establish immediate professional value. - Show understanding of the employer's needs. - Avoid generic introductions and empty enthusiasm. ## 9. FULL COVER LETTER ### Output: FullCoverLetter Write a professional, personalized cover letter of fewer than 250 words. Include: - Current date. - Applicant contact details from the resume. - Company name and address when available. - Appropriate greeting. - Subject: Application for [Role]. - Strong opening. - Relevant qualifications and experience. - Evidence of suitability. - Professional closing. - Applicant's name. Avoid repeating the entire resume. Recommend filename: Full Name – Company Name – CoverLetter.pdf ## 10. PROFESSIONAL APPLICATION EMAIL ### Output: EmailDraft Draft a concise, professional job application email. Include: - Appropriate subject line. - Professional greeting. - Brief introduction. - Position being applied for. - Where the vacancy was advertised, if known. - Brief statement of suitability. - Professional closing. Attachment instructions: 1. Attach Cover Letter FIRST. 2. Attach Resume SECOND. 3. Use PDF files only unless the employer explicitly requests another format. 4. Use the exact recommended filenames. 5. Never use Google Drive or cloud-sharing links when direct attachments are required. Do not invent recruiter email addresses. ## 11. FINAL APPLICATION CHECKLIST ### Output: ApplicationChecklist Provide a concise checklist covering: - Resume tailored to the vacancy. - Cover letter personalized. - Contact details verified. - PDF documents correctly named. - Cover letter attached before resume. - Attachments opened and checked. - Only requested documents included. - Employer and recipient details verified. - Application email proofread. - Apply to 2–3 quality vacancies daily where practical. - Avoid sending recycled, untailored applications. ## 12. OPTIONAL EXTENSIONS Only perform these when requested or when they are directly necessary for the application: ### CompanyResearch Research the employer, its operations, values, services, and relevant developments. Distinguish verified information from assumptions. ### InterviewPreparation Prepare likely interview questions, strong evidence-based answers, technical questions, and practical assessment preparation based on the vacancy. ## 13. OUTPUT AND PRESENTATION RULES - Use clearly labeled sections. - Preserve the exact output labels specified above. - Provide separate code blocks for the requested application artifacts. - Keep analysis concise but sufficiently detailed. - Do not expose internal reasoning. - Use the current date automatically. - Use professional British English unless the employer specifies otherwise. - Use Kenyan employment context where relevant. - Never invent applicant information. - Never ask repetitive questions. - Never delay progress with unnecessary approvals. - Do not claim that an application has been submitted or that employment is secured. ## 14. FINAL OPERATING PRINCIPLE You are not merely rewriting my CV. You are strategically positioning me as the strongest truthful candidate for each specific vacancy. Every decision must answer this question: "What would an experienced recruitment consultant change, emphasize, remove, or improve to make this applicant more competitive for this particular job?" Take ownership of the quality of the work. Use your best professional judgment, optimize aggressively but truthfully, and ask only for information that you genuinely cannot determine. The ultimate objective is to produce a complete, polished, ATS-conscious and employer-specific job application package that maximizes my chances of getting shortlisted and securing an interview.

A flat-lay photo of hand-stitched sashiko embroidery on faded indigo cotton: rows of fan-shaped waves and curling crests under a crescent moon and tiny stars, all in raised off-white running stitches, with a grid-stitch border, a small boro patch, a thread spool and a needle.
A flat-lay photograph of a square panel of hand-stitched Japanese-style sashiko embroidery: deep indigo-dyed cotton cloth covered in running stitches of thick, slightly matte off-white cotton thread that form a picture of rolling ocean waves under a crescent moon. The lower two thirds show overlapping rows of seigaiha-style fan waves, each wave made of four or five concentric arcs of evenly spaced stitches, with a few larger curling wave crests stitched in tighter lines near the center. In the upper right, a thin crescent moon is filled with dense parallel stitching, and a scattering of tiny cross-stitched stars is spread across the dark sky, which is otherwise left as plain cloth so the indigo shows. A narrow border of hitomezashi grid stitching frames the whole panel. Render it exactly like real handwork: each stitch is a short raised dash with small gaps where the needle went under the cloth, stitches slightly irregular in length, a few thread ends tucked in, soft puckering where curves turn, the indigo slightly faded and uneven like hand-dyed cloth, with a faint woven texture and one small darker indigo patch sewn on in the lower left corner in the boro mending tradition. The cloth lies on a pale unfinished wooden table; a small spool of white thread and a long sashiko needle lie at the edge of the frame. Soft, even daylight from above, very shallow shadows, true-to-life color. No text, no people, no hands. Square 1:1.

A glowing hand-painted Victorian magic lantern glass slide: a great comet with a long sweeping tail over a snowy village with a church spire, amber windows and a frozen pond, in translucent Prussian blue and amber washes inside a round black mask, with bubbles, dust and hairline scratches.
A hand-colored Victorian magic lantern glass slide showing a great comet over a snowy village at night, photographed straight-on against a soft backlight so the glass glows. The picture sits inside a round opening of a black paper mask, with a narrow dark binding-tape border around the square glass. Inside the circle: a deep translucent Prussian-blue night sky filled with tiny pin-prick stars; a large bright comet in the upper left with a pale yellow-white head and a long sweeping tail that fans across the sky toward the right; below, a small village of steep snow-covered roofs, a church with a slender spire in the center, bare trees, a frozen pond reflecting the comet, and windows glowing warm amber; a few tiny dark figures on the lane look up at the sky. Render it exactly like an 1880s transparent hand-painted slide: thin, luminous aniline and varnish colors laid over a fine black line image, slightly uneven washes that stop a little short of the outlines, soft brush streaks in the sky, glowing light where the paint is thinnest, tiny air bubbles and dust specks in the glass, faint hairline scratches, gentle vignetting toward the edge of the round mask and a slight chromatic halo at the comet's head. Warm, glowing, nostalgic and magical. No text, no labels, no modern objects. Square 1:1.
Act as a peer reviewer for a machine learning or computer vision research paper being submitted to venue_name. Your review must reflect the competitiveness and standards of this venue. You must: - Carefully consider the novelty, technical quality, experimental results, clarity, impact, and relation to prior work, as relevant for venue_name. - Think step-by-step about strengths, weaknesses, relevance, and contextual comparison before deciding your scores or summary. - Provide your final evaluation at the end, including all required scores. For each review, follow this structure: 1. **Reasoning** (appear first, before conclusions): - Summarize main contributions of the paper. - Critically assess novelty and significance relative to recent work. - Evaluate strengths (strong results, clear exposition, technical soundness, etc.). - Identify weaknesses (methodological flaws, insufficient novelty, incomplete experiments, unclear writing, missing citations, etc.). - Discuss relevance and impact for venue_name specifically, comparing to typical papers accepted at this venue. - Assess whether the presentation, experiments, and conclusions are credible and sufficient for publication. 2. **Conclusions & Scores** (appear last, after prior reasoning): - Recommendation: Brief summary statement (e.g. “Accept”, “Reject”, “Borderline”). - Paper Rating (1–5 integer scale): 1=strong reject, 5=strong accept, 3=borderline. - Confidence Score (1–5): Rate your expertise & certainty (1=not confident, 5=very confident). **Output Format:** Return your review with this information: - reasoning: (detailed multi-paragraph–see above) - recommendation: (1-2 sentences) - paper_rating: (1–5) - confidence: (1–5) (Real reviews should provide more detail in the reasoning section, including deeper technical analysis, comparative discussion, and more thorough justification for the scores.) **Important:** - Only present your scores after reasoning. - Use explicit, venue-aware critique. - Stay concise but thorough. - Reflect the standards and competitiveness of venue_name. --- **REMINDER:** Your task: Reason step-by-step about the paper for venue_name, then give your scores and conclusion at the end.
Latest Bots
Plans safe data backfills and bulk updates for production databases: batch sizes, throttling, idempotent scripts, progress tracking and a way to stop or undo, so big data changes never lock tables or take the app down.
Helps founders plan their first five to ten hires: which roles to open first, what each one must own, realistic salary and equity ranges, and a simple hiring plan that fits the runway.
Helps managers build fair, evidence-based promotion cases: maps a person's work to the level expectations, gathers concrete examples and peer input, and flags gaps early so nobody is surprised at calibration.
Collects family recipes from handwritten cards, voice notes and grandparents' memories, turns them into clear recipes with real amounts, and keeps the stories behind each dish in one family cookbook.
Reviews how your services call each other and outside APIs: timeouts, retries, backoff, idempotency and circuit breakers, and finds the settings that turn one slow dependency into a full outage.
Keeps a founder's unit economics honest: tracks acquisition cost, lifetime value, payback months and gross margin per channel and plan, and explains in plain words what changed and why it matters.
Latest Prompts
Create clean, studio-lit product photography and consistent reference-based visuals using Free AI Image Generator workflows like FreeCreate (https://freecreate.app/generate).
Act as a commercial product photographer and art director. Given a product subject (minimalist ceramic coffee mug), target lighting (soft natural window light), and backdrop (warm linen table with subtle shadows), generate 3 detailed image-generation prompts with camera focal length, depth of field, color palette, and composition notes. You can test the resulting prompts directly in any Free AI Image Generator such as https://freecreate.app/generate and refine them with reference photos.

Turn a reference photo into a luxury fashion editorial: the subject lounges on a beige sofa in a zebra-print robe, with soft studio light and a high-end magazine look.
Ultra-realistic luxury fashion editorial photograph of the woman in the reference image. Keep her hair as in the reference, styled in loose, flowing waves, swept back from her forehead and cascading over her right shoulder. Natural luminous skin with visible pores, delicate microtexture, subtle peach blush and minimal elegant makeup. She wears a luxurious oversized black-and-white zebra-patterned robe dress made of soft, thick, textured fabric. Deep V-shaped neckline with relaxed off-the-shoulder styling, revealing her collarbones and shoulders. Voluminous long sleeves, loosely draped fabric and a matching belt tied at the waist. A short, elegant necklace of large white pearls rests around her neck. The woman reclines comfortably on a large beige upholstered sofa with wide, softly padded back cushions. Her body is slightly angled, shoulders relaxed, one arm extended along the sofa while the other rests naturally near her lap. The flowing zebra-patterned fabric covers her legs. She looks directly into the camera with a calm, confident, slightly serious expression. Relaxed lips, effortless sophisticated pose. Medium-close portrait, photographed from a slightly elevated frontal angle. Soft natural daylight from the left, warm neutral tones, delicate shadows, realistic fabric texture and subtle highlights on her face and hair, matching the reference. Minimalist beige interior, understated luxury atmosphere, intimate high-fashion editorial photography, natural skin texture without excessive retouching, realistic hair strands, subtle analog film grain, refined cinematic composition.
A 30-second Seedance street comedy in 8 timed scenes: a blonde woman with a black umbrella and a run of small mishaps on a city street, with shot-by-shot timing, camera moves and comic beats.
THE BLONDE WOMAN WITH THE BLACK UMBRELLA Duration: 30 Seconds Aspect Ratio: 16:9 Style: Photorealistic live-action, cinematic urban comedy. MAIN CHARACTER: A stylish young blonde woman with long wavy hair, wearing a long black coat, white shirt, black tie, black trousers, and leather boots. She carries a white takeaway coffee cup and a closed black umbrella. Maintain identical appearance throughout. LOCATION: A cloudy New York-style street with wet pavement, stone buildings, fountain, yellow taxi, subway entrance, fruit shop, and red-carpet entrance. SCENE 1 (0–3s): OPEN MANHOLE The woman uses her umbrella to push a loose metal manhole cover back into place while casually walking and drinking coffee. SCENE 2 (3–7s): FOUNTAIN COIN She knocks a coin into a stone fountain using her umbrella. A little girl nearby happily raises her arms without falling into the water. SCENE 3 (7–11s): YELLOW TAXI Passing a yellow taxi, she interferes with a suited man's movement using her umbrella. He loses balance and falls backward while she walks away calmly. SCENE 4 (11–15s): DOG WALKER She catches several red dog leashes with her umbrella, tangling them together. The confused man raises his hands as the dogs gather around him. SCENE 5 (15–19s): MOUSE AND PIZZA A tiny gray mouse struggles to move an oversized pepperoni pizza beside a green subway entrance. A cardboard tube and the woman's black boots remain visible. SCENE 6 (19–23s): FOOD TRAY She interferes with a suited man's movement using her umbrella as he carries a tray of small cups outside a fruit shop. He struggles to keep everything balanced. SCENE 7 (23–27s): RED CARPET She confidently walks past a grand red-carpet entrance. A security guard raises his hand while formally dressed guests watch her. SCENE 8 (27–30s): FINAL SHOT She stops near a glass entrance, takes a sip of coffee, looks directly into the camera, and gives a subtle mischievous smile. CINEMATOGRAPHY: Smooth tracking shots, cinematic wide angles, realistic close-ups, natural movement, shallow depth of field, and consistent lighting. AUDIO: Natural city ambience, footsteps, fountain splash, taxi traffic, barking dogs, rattling objects, and coffee sipping. NEGATIVE PROMPT: No character changes, no missing props, no cartoon effects, no distorted faces, no extra limbs, no child falling into water, no animal substitutions, no duplicated characters, no subtitles, no watermark. FINAL RESULT: A seamless 30-second photorealistic street comedy with all eight scenes in the exact order.
Opinionated habits for measuring and fixing performance problems: profilers, benchmarks, percentiles and evidence-backed optimizations.
# Performance Profiling taste of an engineer who measures before optimizing anything - Never optimize without a reproducible benchmark or production profile that shows the hot path first. Confidence: 0.95 - Write down the target before starting (for example "p95 under 200 ms at 500 rps") and stop once it is met. Confidence: 0.85 - Profile in an environment close to production: optimized build, realistic data size and the same CPU architecture. Confidence: 0.90 - Use sampling profilers (perf, py-spy, async-profiler, pprof, Chrome DevTools) before instrumenting ones, because they barely change what they measure. Confidence: 0.85 - Read flame graphs for wide frames, not tall stacks; the widest box near the top is usually the place to work on. Confidence: 0.85 - Keep continuous profiling running in production (Pyroscope, Parca, Datadog) so regressions can be compared with last week. Confidence: 0.70 - Look at wall-clock time and CPU time separately; a slow request that is mostly waiting needs tracing, not a CPU profile. Confidence: 0.90 - Use distributed tracing to find which service or query owns the latency before profiling any single process. Confidence: 0.80 - Report latency as percentiles (p50, p95, p99) with sample counts, never averages alone. Confidence: 0.95 - Warm up before measuring and run each benchmark enough times to report variance, using tools like hyperfine, criterion, BenchmarkDotNet or pytest-benchmark. Confidence: 0.85 - Change one thing at a time and keep before and after numbers in the pull request description. Confidence: 0.90 - Check the algorithm and the number of round trips (N+1 queries, chatty APIs) before micro-optimizing code. Confidence: 0.90 - Run `EXPLAIN ANALYZE` on the slow query with production-like statistics before adding an index or rewriting it. Confidence: 0.85 - Profile memory as a separate pass: allocation rate, heap growth and GC pauses, using heap snapshots or allocation profilers. Confidence: 0.80 - Treat lock contention and thread pool saturation as first-class suspects in concurrent services, and profile off-CPU time to see them. Confidence: 0.70 - Prefer caching only after proving the work is repeated and the data can tolerate staleness. Confidence: 0.80 - Keep micro-benchmarks in the repository next to the code they measure, and run the critical ones in CI with a regression threshold. Confidence: 0.70 - Pin CPU frequency and isolate benchmark runners, or use instruction counts, so CI noise does not trigger false alarms. Confidence: 0.60 - For frontend work, profile on a throttled mid-range device and track Core Web Vitals from real users, not only Lighthouse on a laptop. Confidence: 0.80 - Leave a short comment next to any non-obvious optimization explaining the measurement that justified it. Confidence: 0.85 - Remove an optimization that no longer shows up in profiles if it makes the code harder to read. Confidence: 0.65 - Share profiles as files or links in the incident or PR so others can reproduce the analysis. Confidence: 0.75
Opinionated Deno conventions for secure, zero-config TypeScript servers and tools: permissions, JSR imports, testing and publishing.
# Deno Project taste of a TypeScript developer who wants secure, zero-config server code - Start with `deno init` and keep a single `deno.json` for tasks, imports, lint, fmt and compiler options; no separate tsconfig or eslintrc. Confidence: 0.90 - Pin dependencies in the `imports` map of `deno.json` with `jsr:` and `npm:` specifiers, and keep version numbers out of source files. Confidence: 0.90 - Prefer JSR packages, starting with `@std/*`, over npm equivalents when both exist. Confidence: 0.80 - Commit `deno.lock` and run CI with `--frozen` so a dependency can never change silently. Confidence: 0.90 - Grant the narrowest permissions possible, scoped to hosts and paths (`--allow-net=api.example.com`, `--allow-read=./data`); never `-A` outside quick local experiments. Confidence: 0.95 - Write the permission flags into the `deno.json` tasks so every developer runs the app with the same sandbox. Confidence: 0.85 - Use `Deno.serve` with a plain `(req: Request) => Response` handler, and add Hono only when routing grows beyond a few paths. Confidence: 0.80 - Stick to Web standard APIs (`fetch`, `Request`, `URL`, `crypto.subtle`, streams) before reaching for Deno-only or Node-compat APIs. Confidence: 0.85 - Treat `node:` imports and npm packages as an escape hatch and keep them out of core domain modules. Confidence: 0.70 - Keep TypeScript strict as Deno ships it and never weaken compiler options to silence errors. Confidence: 0.90 - Use `deno fmt` and `deno lint` with default rules; argue about logic, not formatting. Confidence: 0.85 - Write tests with `Deno.test` and `@std/assert` next to the code as `*_test.ts` files. Confidence: 0.85 - Run `deno test` with the same narrow permissions as production, so missing grants fail in CI and not at runtime. Confidence: 0.75 - Use `t.step` for grouped scenarios and rely on the built-in resource and op sanitizers to catch leaked timers and sockets. Confidence: 0.70 - Collect coverage with `deno test --coverage` and `deno coverage --lcov` without extra tooling. Confidence: 0.65 - Run `deno check` in CI on every entry point, including scripts that are not imported by the main app. Confidence: 0.80 - Read configuration through a single typed module that validates `Deno.env` once at startup and fails fast on missing values. Confidence: 0.85 - Use the `--env-file` flag for local `.env` files instead of a dotenv dependency. Confidence: 0.75 - Use Deno KV for small queues, counters and session data when deploying to Deno Deploy; use Postgres once relations matter. Confidence: 0.60 - Ship single-binary internal tools with `deno compile`, embedding only the permissions the tool needs. Confidence: 0.75 - Publish shared libraries to JSR with explicit `exports`, JSDoc on every public symbol and no slow types, and check them with `deno publish --dry-run`. Confidence: 0.85 - Handle shutdown by listening for `SIGTERM` with `Deno.addSignalListener` and awaiting `server.shutdown()`. Confidence: 0.70 - Use `deno task` for every repeated command instead of a Makefile or npm scripts. Confidence: 0.80
Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.
# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases - Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80 - Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90 - Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85 - Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85 - Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90 - Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65 - Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95 - Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70 - Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80 - Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90 - Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80 - Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80 - Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85 - Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75 - Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60 - Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80 - Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95 - Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85 - Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85 - Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85 - Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95 - Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75 - Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80 - Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70
Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
name: accounts-receivable-aging-report
description: Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
# Accounts Receivable Aging Report
You help founders, freelancers, agency owners and small-business finance people see who owes them money, how late it is, and what to do about it this week. Spreadsheets of invoices hide the important parts: one client quietly holding 60% of the money owed, an invoice that slipped past 90 days, a partial payment nobody followed up, a disputed invoice that keeps getting reminder emails. You turn an invoice export into a clear aging report, a short action list and polite, firm collection steps.
You work on the user's data locally; invoice data is confidential, so you never upload it anywhere. You are not an accountant or lawyer: you flag when write-offs, late fees, collections or tax treatment need a professional, and the owner decides what to send.
## Files in this skill
- `scripts/ar_aging.py` - reads `invoices.csv` (invoice_id, customer, issue_date, due_date, amount, paid_amount, currency, disputed, last_contact) and optional `customers.json` (credit limits, terms, contacts); prints aging buckets per customer and currency, overdue %, DSO, the overdue list with a collection stage, and findings A01-A08; `--as-of`, `--format text|md|json|csv`, `--min-severity`, `--concentration`, `--contact-days`, `--dso-days`; `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/aging-buckets-and-dso.md` - how buckets, overdue share, DSO, concentration and credit limits are calculated and their limits
- `references/collection-playbook.md` - stages 0-5 plus dispute hold, message skeletons, good practice
- `templates/collections-summary.md` - the one-page review you hand back
- `examples/invoices.csv`, `examples/customers.json` - a fictional design agency with 18 invoices in EUR and USD: a 146-day-old invoice, a disputed one, partial payments, an overpayment, one client over its credit limit holding 59% of receivables, and overdue invoices with no contact logged
## Workflow
### 1. Get the data
Ask for an export from the invoicing or accounting tool with the columns above (paid invoices from the last 90 days too, for DSO). Map their column names if needed. Ask for credit limits and payment terms per customer if they have them; otherwise skip `customers.json` and say that A03 cannot be checked.
### 2. Run the report
```
python3 scripts/ar_aging.py invoices.csv customers.json --as-of 2026-11-25
python3 scripts/ar_aging.py invoices.csv customers.json --format md > aging.md
python3 scripts/ar_aging.py invoices.csv --format csv > overdue-list.csv
python3 scripts/ar_aging.py invoices.csv customers.json --min-severity high
python3 scripts/ar_aging.py --self-test
```
Exit code 0 = no findings at or above `--min-severity`, 1 = findings, 2 = input error.
| Code | Severity | Meaning |
|---|---|---|
| A01 | high | open balance more than 90 days past due |
| A02 | medium | one customer holds more than 30% of open receivables (per currency) |
| A03 | high | customer open balance above its credit limit |
| A04 | low | partially paid invoice still open |
| A05 | medium | disputed invoice: resolve before chasing |
| A06 | medium | overdue with no contact in the last 14 days |
| A07 | low | overpaid invoice: refund or apply as credit |
| A08 | high | data problem: duplicate id, bad date, negative amount, due before issue |
### 3. Check and interpret
- Fix A08 data problems first and re-run; totals are not trustworthy until then.
- Compare DSO with payment terms and look at the 90+ bucket and concentration.
- Separate disputes from slow payers; never send reminders on a disputed amount.
- Ask about context the data cannot show (a client that always pays after its board meeting, a promised transfer).
### 4. Plan actions
Sort the overdue list by amount x age and pick this week's top actions using `references/collection-playbook.md`. Draft messages for each stage in the user's tone; mark which need the owner's review (final notices, payment plans, pausing work).
### 5. Report
Fill `templates/collections-summary.md`: headline numbers, this week's actions with owners, disputes, risk notes (credit limits, concentration, credits) and process improvements (deposits, direct debit, shorter terms, PO numbers on invoices).
## Example
```
python3 scripts/ar_aging.py examples/invoices.csv examples/customers.json --as-of 2026-11-25
```
shows 42,940 EUR open, 73% overdue, DSO about 114 days; Bluefin Logistics holds 59.4% and is over its 20,000 limit (A02, A03) with a disputed 6,200 invoice on hold (A05); Northwind Bakery's INV-1041 is 146 days past due (A01) with no contact for 36 days (A06); and Maple & Pine Studio overpaid by 40 EUR (A07).
## Rules
- Use the user's numbers; mark assumptions.
- Keep currencies separate; never convert without a rate the user gives.
- Stay polite and factual in every message; no threats the contract does not support.
- Not legal, tax or accounting advice; say when to ask a professional.
FILE:references/aging-buckets-and-dso.md
# Aging buckets, overdue share and DSO
## Aging buckets
Each open invoice is placed by **days past due** on the report date (`--as-of`), not by days since issue:
| Bucket | Days past due | Typical reading |
|---|---|---|
| Current | 0 or less (not yet due) | healthy; no action except making sure the invoice was received |
| 1-30 | 1-30 | normal slippage; friendly reminders usually work |
| 31-60 | 31-60 | a process or cash problem at the customer; escalate politely |
| 61-90 | 61-90 | real risk; final notices, pause new work |
| 90+ | over 90 | a large share will never be paid without a plan; consider payment plans, collections, or legal advice, and talk to your accountant about a bad-debt provision |
Open balance = amount - paid_amount. Fully paid invoices drop out. Overpaid invoices (negative open balance) are customer credit, reported as A07, and are not netted against other invoices automatically: decide with the customer whether to refund or apply the credit.
## Overdue share
`overdue % = (open - Current) / open`. Watch the trend month to month more than the absolute number. Many small businesses aim to keep 90+ under about 5-10% of receivables; this is a rule of thumb, not a standard.
## DSO (days sales outstanding)
The script uses the simple count-back formula over a window (default 90 days, `--dso-days`):
`DSO = open receivables / invoiced amount in the last N days x N`
Example: 42,940 open, 33,880 invoiced in the last 90 days -> DSO about 114 days. Compare DSO with your payment terms: with 30-day terms, a DSO far above 30 means customers pay late on average or old debt is piling up.
Limits:
- Uneven billing (one big project invoice) swings DSO a lot; look at a few months.
- Currencies are reported separately; DSO is per currency.
- The CSV must contain all invoices issued in the window (including paid ones) for DSO to be meaningful.
## Concentration
If one customer holds more than about 30% (`--concentration`) of open receivables, a single late payer can create a cash gap. That is a business risk to discuss, not a collection failure.
## Credit limits
`customers.json` can hold a `credit_limit` per customer. Exceeding it (A03) is a signal to stop or slow new work, ask for a deposit, or agree a payment plan before taking on more.
## Data checks (A08)
Duplicate invoice ids, unreadable dates, negative amounts and due dates before issue dates are reported first: fix the export before trusting any totals.
FILE:references/collection-playbook.md
# Collection playbook (polite, firm, documented)
The script assigns a stage to each overdue invoice. Adapt timing to your terms and relationships; always stay factual and polite, and log every contact (`last_contact`) so A06 stays quiet.
| Stage | Days past due | Action | Channel |
|---|---|---|---|
| 0 | before due | confirm the invoice reached the right person / AP portal; check PO numbers | email |
| 1 | 1-7 | friendly reminder with invoice copy and payment link | email |
| 2 | 8-30 | firm reminder plus a short call; ask for a payment date | email + phone |
| 3 | 31-60 | escalate to the decision maker or project sponsor; pause new work or deliveries if your contract allows | call + email |
| 4 | 61-90 | final notice with a clear date and the next step (late fees if in your contract, payment plan offer) | written notice |
| 5 | 90+ | payment plan in writing, or collections agency / small-claims / legal advice; talk to your accountant about provisions | written |
| hold | disputed | resolve the dispute first: what exactly is contested, credit note or partial payment for the undisputed part | call |
## Message skeletons
**Stage 1:** "Hi {{name}}, a quick reminder that invoice {{id}} for {{amount}} was due on {{due_date}}. A copy and payment link are attached. If it has already been paid, thank you and please ignore this."
**Stage 2:** "Hi {{name}}, invoice {{id}} ({{amount}}) is now {{days}} days overdue. Could you confirm the date it will be paid? If something is blocking it (PO, approval, a question about the work), tell me and I will sort it out."
**Stage 4:** "Hello {{name}}, despite earlier reminders on {{dates}}, invoice {{id}} ({{amount}}) remains unpaid {{days}} days after the due date. Please arrange payment by {{date}}. If that is not possible, reply by then so we can agree a written payment plan; otherwise we will {{next_step}}."
## Good practice
- Separate disputes from slow payment; never chase a disputed amount with reminders.
- Ask for partial payment of the undisputed part.
- For repeat late payers: shorter terms, deposits, card or direct debit, milestone billing.
- Late fees and interest only if your contract and local law allow them; check before you threaten them.
- Keep tone respectful: many late payments are process problems (wrong email, missing PO), not unwillingness.
- This is not legal or accounting advice; for collections, write-offs and tax treatment ask a qualified professional.
FILE:templates/collections-summary.md
# Receivables review - {{business}} - as of {{as_of}}
## Headline
- Open receivables: {{open_total}} ({{currency}}), overdue {{overdue_total}} ({{overdue_pct}}%), DSO {{dso}} days vs {{terms}}-day terms
- 90+ days: {{over_90_total}} across {{over_90_count}} invoices
- Biggest exposure: {{top_customer}} with {{top_share}}% of open balance
## This week's actions (highest value first)
| # | Customer | Invoice(s) | Amount | Days past due | Stage / action | Owner | Due |
|---|---|---|---|---|---|---|---|
| 1 | | | | | | | |
| 2 | | | | | | | |
| 3 | | | | | | | |
## Disputes to resolve
| Invoice | Customer | Amount | What is disputed | Next step | Owner |
|---|---|---|---|---|---|
## Risk notes
- Credit limits exceeded: {{customers_over_limit}} -> {{proposal: pause new work / deposit / payment plan}}
- Concentration: {{customer}} {{share}}% -> {{proposal}}
- Credits to refund or apply: {{credits}}
- Data fixes needed in the export: {{data_issues}}
## Process improvements
- {{e.g. send invoices to the AP inbox with PO numbers; move Orbit Fitness to direct debit; 50% deposit on new projects for clients with 90+ history}}
_Figures from ar_aging.py on {{as_of}}. Not legal or accounting advice._
FILE:examples/invoices.csv
invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact
INV-1041,Northwind Bakery,2026-06-02,2026-07-02,2400.00,0,EUR,no,2026-10-20
INV-1047,Harbor Dental Clinic,2026-07-15,2026-08-14,1850.00,850.00,EUR,no,2026-11-18
INV-1052,Bluefin Logistics,2026-08-05,2026-09-04,6200.00,0,EUR,yes,2026-11-10
INV-1055,Northwind Bakery,2026-08-20,2026-09-19,1200.00,0,EUR,no,2026-10-20
INV-1058,Maple & Pine Studio,2026-09-01,2026-10-01,980.00,980.00,EUR,no,
INV-1060,Bluefin Logistics,2026-09-10,2026-10-10,7400.00,0,EUR,no,
INV-1063,Greenleaf Co-op,2026-09-22,2026-10-22,1500.00,0,EUR,no,2026-11-21
INV-1064,Harbor Dental Clinic,2026-10-01,2026-10-31,1850.00,0,EUR,no,2026-11-18
INV-1066,Orbit Fitness,2026-10-03,2026-11-02,3200.00,0,EUR,no,
INV-1067,Maple & Pine Studio,2026-10-06,2026-11-05,760.00,800.00,EUR,no,
INV-1069,Bluefin Logistics,2026-10-15,2026-11-14,5100.00,0,EUR,no,2026-11-19
INV-1070,Greenleaf Co-op,2026-10-20,2026-11-19,1500.00,0,EUR,no,
INV-1072,Orbit Fitness,2026-11-01,2026-12-01,3200.00,0,EUR,no,
INV-1073,Northwind Bakery,2026-11-05,2026-12-05,950.00,0,EUR,no,
INV-1074,Bluefin Logistics,2026-11-10,2026-12-10,6800.00,0,EUR,no,
INV-1075,Lakeside Hostel,2026-11-12,2026-11-26,640.00,0,EUR,no,
INV-1076,Atlas Outdoor Inc,2026-09-15,2026-10-15,4500.00,2000.00,USD,no,2026-11-03
INV-1077,Atlas Outdoor Inc,2026-11-15,2026-12-15,4500.00,0,USD,no,
FILE:examples/customers.json
{
"default_terms_days": 30,
"note": "Fictional clients of a small design and web agency. Credit limits are what the agency is willing to have open per client.",
"customers": {
"Northwind Bakery": {"credit_limit": 5000, "terms_days": 30, "contact": "owner, prefers phone"},
"Harbor Dental Clinic": {"credit_limit": 4000, "terms_days": 30, "contact": "practice manager"},
"Bluefin Logistics": {"credit_limit": 20000, "terms_days": 30, "contact": "accounts payable inbox + project sponsor"},
"Maple & Pine Studio": {"credit_limit": 3000, "terms_days": 30, "contact": "founder"},
"Greenleaf Co-op": {"credit_limit": 4000, "terms_days": 30, "contact": "treasurer, pays after monthly board meeting"},
"Orbit Fitness": {"credit_limit": 6000, "terms_days": 30, "contact": "finance lead"},
"Lakeside Hostel": {"credit_limit": 2000, "terms_days": 14, "contact": "manager"},
"Atlas Outdoor Inc": {"credit_limit": 8000, "terms_days": 30, "contact": "AP portal, PO required"}
}
}
FILE:scripts/ar_aging.py
#!/usr/bin/env python3
"""ar_aging.py - accounts receivable aging report from an invoice CSV (standard library only, Python 3.8+).
invoices.csv columns (header required; extra columns ignored):
invoice_id, customer, issue_date, due_date, amount, paid_amount, currency,
disputed (yes/no, optional), last_contact (YYYY-MM-DD, optional)
customers.json (optional): {"default_terms_days": 30, "customers": {"Name": {"credit_limit": 10000, "terms_days": 30, "contact": "..."}}}
Report: open balance per invoice, aging buckets by days past due as of --as-of
(Current, 1-30, 31-60, 61-90, 90+), totals per customer and currency, % overdue,
approximate DSO (open balance / sales in the last --dso-days days x --dso-days),
a collection stage per overdue invoice, and findings:
A01 high open balance more than 90 days past due
A02 medium one customer holds more than --concentration % (default 30) of the open balance
A03 high customer open balance above its credit_limit
A04 low partially paid invoice still open
A05 medium disputed invoice (excluded from reminders, needs resolution)
A06 medium overdue with no contact logged in the last --contact-days (default 14)
A07 low overpaid invoice (customer credit to refund or apply)
A08 high data problem (bad date, negative amount, due before issue, duplicate id)
Usage: ar_aging.py invoices.csv [customers.json] [--as-of YYYY-MM-DD] [--format text|md|json|csv]
[--min-severity low|medium|high] [--concentration PCT] [--contact-days N] [--dso-days N]
ar_aging.py --self-test
Exit: 0 no findings at or above --min-severity, 1 findings, 2 usage/input error.
"""
import argparse, csv, datetime as dt, io, json, sys
from collections import OrderedDict, defaultdict
BUCKETS = ["Current", "1-30", "31-60", "61-90", "90+"]
SEV = {"low": 1, "medium": 2, "high": 3}
def bucket(days_past_due):
if days_past_due <= 0: return "Current"
if days_past_due <= 30: return "1-30"
if days_past_due <= 60: return "31-60"
if days_past_due <= 90: return "61-90"
return "90+"
def stage(days_past_due, disputed):
if disputed: return "hold: resolve dispute first"
if days_past_due <= 0: return "none (not due)"
if days_past_due <= 7: return "1 friendly reminder"
if days_past_due <= 30: return "2 firm reminder + call"
if days_past_due <= 60: return "3 escalate to decision maker, pause new work"
if days_past_due <= 90: return "4 final notice with date"
return "5 payment plan or collections/legal review"
def parse_date(s):
return dt.datetime.strptime(s.strip(), "%Y-%m-%d").date()
def money(s):
s = (s or "").strip().replace(",", "")
return round(float(s), 2) if s else 0.0
def load_invoices(text):
rows, problems, seen = [], [], set()
reader = csv.DictReader(io.StringIO(text))
need = {"invoice_id", "customer", "issue_date", "due_date", "amount"}
if not reader.fieldnames or not need <= {f.strip() for f in reader.fieldnames}:
raise ValueError("invoices.csv needs columns: " + ", ".join(sorted(need)))
for n, r in enumerate(reader, 2):
r = {k.strip(): (v or "").strip() for k, v in r.items() if k}
iid = r["invoice_id"]
try:
issue, due = parse_date(r["issue_date"]), parse_date(r["due_date"])
amount, paid = money(r["amount"]), money(r.get("paid_amount"))
last = parse_date(r["last_contact"]) if r.get("last_contact") else None
except ValueError as e:
problems.append((iid or "line %d" % n, "line %d: %s" % (n, e))); continue
if iid in seen:
problems.append((iid, "duplicate invoice_id %s (line %d skipped)" % (iid, n))); continue
seen.add(iid)
if amount < 0 or paid < 0:
problems.append((iid, "negative amount on line %d" % n)); continue
if due < issue:
problems.append((iid, "due_date before issue_date on line %d" % n))
rows.append(dict(invoice_id=iid, customer=r["customer"], issue=issue, due=due, amount=amount, paid=paid,
currency=r.get("currency") or "EUR", disputed=r.get("disputed", "").lower() in ("yes", "y", "true", "1"),
last_contact=last))
return rows, problems
def analyze(rows, problems, customers, o):
as_of = o.as_of
inv, findings = [], []
def add(code, sev, ref, msg): findings.append(dict(code=code, severity=sev, ref=ref, message=msg))
for ref, msg in problems: add("A08", "high", ref, msg)
for r in rows:
open_bal = round(r["amount"] - r["paid"], 2)
dpd = (as_of - r["due"]).days
rec = dict(r, open=open_bal, days_past_due=dpd, bucket=bucket(dpd) if open_bal > 0 else "-", stage=stage(dpd, r["disputed"]) if open_bal > 0 else "-")
inv.append(rec)
if open_bal < 0:
add("A07", "low", r["invoice_id"], "%s overpaid by %.2f %s: refund or apply as credit" % (r["customer"], -open_bal, r["currency"]))
continue
if open_bal == 0: continue
if r["paid"] > 0:
add("A04", "low", r["invoice_id"], "partially paid: %.2f of %.2f %s still open" % (open_bal, r["amount"], r["currency"]))
if r["disputed"]:
add("A05", "medium", r["invoice_id"], "disputed (%.2f %s, %d days past due): resolve before chasing" % (open_bal, r["currency"], max(dpd, 0)))
if dpd > 90:
add("A01", "high", r["invoice_id"], "%s: %.2f %s is %d days past due" % (r["customer"], open_bal, r["currency"], dpd))
if dpd > 0 and not r["disputed"]:
since = (as_of - r["last_contact"]).days if r["last_contact"] else None
if since is None or since > o.contact_days:
add("A06", "medium", r["invoice_id"], "%d days overdue, %s" % (dpd, "no contact logged" if since is None else "last contact %d days ago" % since))
# per currency summaries
by_cur = OrderedDict()
for r in inv:
if r["open"] <= 0: continue
c = by_cur.setdefault(r["currency"], dict(total=0.0, buckets={b: 0.0 for b in BUCKETS}, customers=defaultdict(lambda: {b: 0.0 for b in BUCKETS})))
c["total"] += r["open"]; c["buckets"][r["bucket"]] += r["open"]; c["customers"][r["customer"]][r["bucket"]] += r["open"]
summaries = OrderedDict()
for cur, c in by_cur.items():
total = round(c["total"], 2)
overdue = round(total - c["buckets"]["Current"], 2)
sales = sum(r["amount"] for r in inv if r["currency"] == cur and 0 <= (as_of - r["issue"]).days < o.dso_days)
dso = round(total / sales * o.dso_days, 1) if sales else None
custs = []
for name, b in c["customers"].items():
ct = round(sum(b.values()), 2)
custs.append(dict(customer=name, total=ct, buckets={k: round(v, 2) for k, v in b.items()}, share_pct=round(100 * ct / total, 1) if total else 0))
if total and 100 * ct / total > o.concentration and len(c["customers"]) > 1:
add("A02", "medium", name, "holds %.1f%% of open %s receivables (%.2f)" % (100 * ct / total, cur, ct))
lim = (customers.get("customers", {}).get(name) or {}).get("credit_limit")
if lim is not None and ct > lim:
add("A03", "high", name, "open balance %.2f %s exceeds credit limit %.2f" % (ct, cur, lim))
custs.sort(key=lambda x: -x["total"])
summaries[cur] = dict(total=total, overdue=overdue, overdue_pct=round(100 * overdue / total, 1) if total else 0,
buckets={k: round(v, 2) for k, v in c["buckets"].items()}, dso=dso, customers=custs)
order = {"high": 0, "medium": 1, "low": 2}
findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["ref"]))
return inv, summaries, findings
def render(inv, summaries, findings, o):
minsev = SEV[o.min_severity]
shown = [f for f in findings if SEV[f["severity"]] >= minsev]
if o.format == "json":
def ser(r): return {k: (v.isoformat() if isinstance(v, dt.date) else v) for k, v in r.items()}
return json.dumps(dict(as_of=o.as_of.isoformat(), summaries=summaries, invoices=[ser(r) for r in inv if r["open"] != 0], findings=shown), indent=2)
if o.format == "csv":
out = io.StringIO(); w = csv.writer(out)
w.writerow(["invoice_id", "customer", "currency", "due_date", "days_past_due", "bucket", "open", "disputed", "stage"])
for r in sorted(inv, key=lambda r: -r["days_past_due"]):
if r["open"] > 0: w.writerow([r["invoice_id"], r["customer"], r["currency"], r["due"].isoformat(), r["days_past_due"], r["bucket"], "%.2f" % r["open"], "yes" if r["disputed"] else "no", r["stage"]])
return out.getvalue().rstrip("\n")
md = o.format == "md"
L = ["# AR aging as of %s" % o.as_of if md else "AR aging as of %s" % o.as_of, ""]
for cur, s in summaries.items():
L.append(("## %s: open %.2f, overdue %.2f (%.1f%%), DSO %s" if md else "%s: open %.2f, overdue %.2f (%.1f%%), DSO %s") % (cur, s["total"], s["overdue"], s["overdue_pct"], "%.1f days" % s["dso"] if s["dso"] is not None else "n/a"))
L.append("")
hdr = ["Customer"] + BUCKETS + ["Total", "Share"]
if md:
L.append("| " + " | ".join(hdr) + " |"); L.append("|" + "---|" * len(hdr))
else:
L.append("%-22s" % hdr[0] + "".join("%11s" % h for h in hdr[1:]))
rows = s["customers"] + [dict(customer="TOTAL", total=s["total"], buckets=s["buckets"], share_pct=100.0)]
for c in rows:
vals = ["%.2f" % c["buckets"][b] for b in BUCKETS] + ["%.2f" % c["total"], "%.1f%%" % c["share_pct"]]
L.append("| " + " | ".join([c["customer"]] + vals) + " |" if md else "%-22s" % c["customer"][:22] + "".join("%11s" % v for v in vals))
L.append("")
L.append("## Overdue invoices and next step" if md else "Overdue invoices and next step:")
od = sorted([r for r in inv if r["open"] > 0 and r["days_past_due"] > 0], key=lambda r: -r["days_past_due"])
for r in od:
L.append("%s %s %s %.2f %s, %d days past due -> %s" % ("-" if md else " ", r["invoice_id"], r["customer"], r["open"], r["currency"], r["days_past_due"], r["stage"]))
if not od: L.append(" none")
L.append("")
L.append(("## Findings (%s+)" if md else "Findings (%s+):") % o.min_severity)
for f in shown:
L.append("%s [%s] %s %s: %s" % ("-" if md else " ", f["severity"].upper(), f["code"], f["ref"], f["message"]))
if not shown: L.append(" none")
return "\n".join(L)
def parser():
p = argparse.ArgumentParser(description="Accounts receivable aging report.")
p.add_argument("invoices", nargs="?")
p.add_argument("customers", nargs="?")
p.add_argument("--as-of", type=parse_date, default=dt.date.today())
p.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--concentration", type=float, default=30.0)
p.add_argument("--contact-days", type=int, default=14)
p.add_argument("--dso-days", type=int, default=90)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args(["--as-of", "2026-06-30"])
H = "invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact\n"
checks = []
def check(n, c): checks.append((n, bool(c)))
def run(body, cust=None, **kw):
oo = parser().parse_args(["--as-of", "2026-06-30"]); [setattr(oo, k, v) for k, v in kw.items()]
rows, probs = load_invoices(H + body)
return analyze(rows, probs, cust or {}, oo)
codes = lambda f: sorted({x["code"] for x in f})
check("bucket edges", [bucket(d) for d in (0, 1, 30, 31, 60, 61, 90, 91)] == ["Current", "1-30", "1-30", "31-60", "31-60", "61-90", "61-90", "90+"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("not yet due is Current, no findings", inv[0]["bucket"] == "Current" and f == [])
inv, s, f = run("I1,Acme,2026-05-01,2026-05-31,1000,0,EUR,,2026-06-25\n")
check("30 days past due in 1-30 with recent contact", inv[0]["bucket"] == "1-30" and f == [])
inv, s, f = run("I1,Acme,2026-01-01,2026-01-31,500,0,EUR,,2026-06-29\n")
check("150 days past due gives A01", "A01" in codes(f) and inv[0]["bucket"] == "90+")
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
check("overdue without contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,2026-06-01\n", contact_days=14)
check("stale contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,200,EUR,,2026-06-28\n")
check("partial payment gives A04 and open 300", codes(f) == ["A04"] and inv[0]["open"] == 300)
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,yes,\n")
check("disputed gives A05, no A06, hold stage", codes(f) == ["A05"] and inv[0]["stage"].startswith("hold"))
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,600,EUR,,\n")
check("overpaid gives A07 only", codes(f) == ["A07"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\nI2,Bolt,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("concentration A02 for 90% customer", [x["ref"] for x in f if x["code"] == "A02"] == ["Acme"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\n", {"customers": {"Acme": {"credit_limit": 5000}}})
check("credit limit A03, single customer no A02", codes(f) == ["A03"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI3,Acme,2026-13-01,2026-07-01,100,0,EUR,,\nI4,Acme,2026-06-01,2026-07-01,-5,0,EUR,,\n")
check("duplicate, bad date, negative give A08 x3", len([x for x in f if x["code"] == "A08"]) == 3 and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-10,2026-06-01,100,0,EUR,,2026-06-29\n")
check("due before issue flagged A08 but kept", "A08" in codes(f) and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\nI2,Acme,2026-06-01,2026-07-01,800,0,USD,,\n")
check("currencies kept separate", set(s) == {"EUR", "USD"} and s["USD"]["total"] == 800)
inv, s, f = run("I1,Acme,2026-04-15,2026-05-15,3000,0,EUR,,2026-06-29\nI2,Acme,2026-06-15,2026-07-15,3000,0,EUR,,\n")
check("DSO = open / 90-day sales x 90", s["EUR"]["dso"] == 90.0 and s["EUR"]["overdue_pct"] == 50.0)
check("stage ladder", [stage(d, False)[0] for d in (3, 20, 45, 80, 120)] == ["1", "2", "3", "4", "5"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,1000,1000,EUR,,\n")
check("fully paid invoice ignored", f == [] and s == {})
try:
load_invoices("id,name\n1,x\n"); check("missing columns rejected", False)
except ValueError:
check("missing columns rejected", True)
oo = parser().parse_args(["--as-of", "2026-06-30", "--format", "csv"])
rows, probs = load_invoices(H + "I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
out = render(*analyze(rows, probs, {}, oo), oo)
check("csv output has header and row", out.splitlines()[0].startswith("invoice_id") and "I1,Acme" in out)
oo.format = "json"
check("json output parses", json.loads(render(*analyze(rows, probs, {}, oo), oo))["as_of"] == "2026-06-30")
for n, c in checks: print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if all(c for _, c in checks) else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test: return self_test()
if not o.invoices:
parser().print_usage(sys.stderr); return 2
try:
with open(o.invoices, encoding="utf-8-sig") as fh: rows, probs = load_invoices(fh.read())
customers = json.load(open(o.customers, encoding="utf-8")) if o.customers else {}
except (OSError, ValueError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
inv, summaries, findings = analyze(rows, probs, customers, o)
print(render(inv, summaries, findings, o))
return 1 if any(SEV[f["severity"]] >= SEV[o.min_severity] for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())
Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
# Python Complexity Hotspot Finder
You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.
You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.
## Files in this skill
- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)
## Workflow
### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.
### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |
### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.
### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.
### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).
## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.
## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.
FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them
## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:
| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |
Nested functions, classes and lambdas are measured on their own and do not add to the outer function.
### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |
CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.
## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.
## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.
## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.
Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.
## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.
FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions
Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.
## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
if item.qty > 0:
if item.active:
process(item)
# after
for item in items:
if item.qty <= 0 or not item.active:
continue
process(item)
```
## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.
## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.
## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).
## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.
## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).
## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.
## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.
FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})
**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days
## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}
## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |
## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}
## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}
## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.
FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
total = 0
for item in items:
if item.get("qty", 0) <= 0:
continue
price = item["price"] * item["qty"]
if item.get("category") == "books":
if region == "EU":
price = price * 1.05
elif region == "UK":
price = price
else:
price = price * 1.08
elif item.get("category") == "food":
if region == "EU" and not customer.get("business"):
price = price * 1.07
else:
price = price * 1.0
else:
if region == "EU":
price = price * 1.2
elif region == "UK":
price = price * 1.2
elif region == "US" and customer.get("state") in ("CA", "NY"):
price = price * 1.09
else:
price = price * 1.0
total += price
if coupon:
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
total = total * (1 - coupon["value"] / 100)
elif coupon.get("type") == "fixed":
total = max(0, total - coupon["value"])
if customer.get("vip") or customer.get("orders", 0) > 20:
total = total * 0.95
if rush:
total += 15 if currency == "EUR" else 18
if gift_wrap:
total += 3
return round(total, 2)
def invoice_status(invoice, today):
if invoice["paid"]:
return "paid"
if invoice.get("disputed"):
return "disputed"
days = (today - invoice["due"]).days
if days <= 0:
return "open"
if days <= 30:
return "overdue"
if days <= 90:
return "late"
return "collections"
def format_amount(value, currency):
return "%s %.2f" % (currency, value)
FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""
TAX_RATES = {
# (category, region) -> rate; "*" means any
("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
("food", "EU"): 1.07, ("food", "*"): 1.0,
("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3
def tax_rate(category, region, customer):
if category == "food" and customer.get("business"):
return 1.0
if category not in ("books", "food") and region == "US":
return US_TAXED_STATES.get(customer.get("state"), 1.0)
key_category = category if category in ("books", "food") else "*"
return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])
def line_total(item, region, customer):
return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)
def apply_coupon(total, coupon):
if not coupon:
return total
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
return total * (1 - coupon["value"] / 100)
if coupon.get("type") == "fixed":
return max(0, total - coupon["value"])
return total
def loyalty_discount(total, customer):
loyal = customer.get("vip") or customer.get("orders", 0) > 20
return total * 0.95 if loyal else total
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
if "rush" in options:
total += RUSH_FEE.get(currency, 18)
if "gift_wrap" in options:
total += GIFT_WRAP_FEE
return round(total, 2)
FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.
Measures per function/method (standard library only, Python 3.8+):
cc cyclomatic complexity (1 + decision points: if/elif, for/while, except,
boolean operators, comprehension ifs, ternaries, match cases, assert)
depth deepest nesting of blocks inside the function
lines function length in source lines
params number of parameters (excluding self/cls)
returns number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).
Findings (severity):
H01 cc >= --cc-high (default 15) high
H02 cc >= --cc-warn (default 10) medium
H03 nesting depth >= --max-depth (4) medium
H04 lines >= --max-lines (60) medium
H05 params >= --max-params (6) low
H06 returns >= --max-returns (6) low
H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5) high
Usage:
complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys
SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}
class FuncVisitor(ast.NodeVisitor):
"""Computes metrics for one function body without descending into nested defs."""
BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)
def __init__(self):
self.cc = 1
self.max_depth = 0
self.returns = 0
self._depth = 0
def generic_visit(self, node):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
return # nested definitions are measured separately (lambdas count as 0)
block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
self.cc += 1
elif isinstance(node, ast.ExceptHandler):
self.cc += 1
elif isinstance(node, ast.BoolOp):
self.cc += len(node.values) - 1
elif isinstance(node, ast.comprehension):
self.cc += 1 + len(node.ifs)
elif type(node).__name__ == "match_case":
self.cc += 1
elif isinstance(node, ast.Return):
self.returns += 1
if block:
# an elif is an If inside orelse; do not count it as deeper nesting
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
super().generic_visit(node)
if block:
self._depth -= 1
def visit_If(self, node):
self.cc += 1
self.visit(node.test)
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
for n in node.body:
self.visit(n)
self._depth -= 1
orelse = node.orelse
if len(orelse) == 1 and isinstance(orelse[0], ast.If):
self.visit_If(orelse[0]) # elif chain: same depth
else:
self._depth += 1
for n in orelse:
self.visit(n)
self._depth -= 1
def measure_function(node):
v = FuncVisitor()
for stmt in node.body:
v.visit(stmt)
args = node.args
names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
if args.vararg: names.append(args.vararg.arg)
if args.kwarg: names.append(args.kwarg.arg)
params = len([n for n in names if n not in ("self", "cls")])
end = getattr(node, "end_lineno", node.lineno)
return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}
def analyze_source(src, filename="<string>"):
tree = ast.parse(src, filename=filename)
out = []
def walk(node, prefix):
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = prefix + child.name
m = measure_function(child)
m.update({"file": filename, "function": name, "line": child.lineno})
out.append(m)
walk(child, name + ".")
elif isinstance(child, ast.ClassDef):
walk(child, prefix + child.name + ".")
else:
walk(child, prefix)
walk(tree, "")
return out
def iter_py_files(paths):
for p in paths:
if os.path.isfile(p):
if p.endswith(".py"): yield p
continue
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
def git_churn(path, days):
"""Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
try:
top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError):
return {}
churn = {}
for line in log.splitlines():
line = line.strip()
if line.endswith(".py"):
k = os.path.normpath(os.path.join(top, line))
churn[k] = churn.get(k, 0) + 1
return churn
def findings_for(m, o):
f = []
if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
return f
def run(paths, o):
results, errors = [], []
churn = {}
if o.churn:
for p in paths:
churn.update(git_churn(p, o.churn))
for f in iter_py_files(paths):
try:
with open(f, encoding="utf-8") as fh:
ms = analyze_source(fh.read(), f)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append("%s: %s" % (f, e)); continue
for m in ms:
if o.churn:
m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
m["score"] = m["cc"] * (1 + m.get("churn", 0))
m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
results.append(m)
results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
return results, errors
def render(results, errors, o):
minsev = SEV[o.min_severity]
flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
top = flagged[: o.top] if o.top else flagged
n = len(results)
avg = sum(m["cc"] for m in results) / n if n else 0
if o.format == "json":
return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
"hotspots": top}, indent=2)
churn_col = o.churn is not None and o.churn > 0
if o.format == "md":
head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
rows = [head, sep]
for i, m in enumerate(top, 1):
fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
(" %d |" % m.get("churn", 0)) if churn_col else "", fs))
rows.append("")
rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
return "\n".join(rows)
lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
for i, m in enumerate(top, 1):
extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
lines.append("%2d. %s (%s:%d) cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
for x in m["findings"]:
lines.append(" [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
if not top: lines.append("No functions above the thresholds.")
for e in errors: lines.append("PARSE ERROR " + e)
return "\n".join(lines)
def parser():
p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
p.add_argument("paths", nargs="*")
p.add_argument("--format", choices=["text", "md", "json"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
p.add_argument("--churn-min", type=int, default=5)
p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
p.add_argument("--cc-warn", type=int, default=10)
p.add_argument("--cc-high", type=int, default=15)
p.add_argument("--max-depth", type=int, default=4)
p.add_argument("--max-lines", type=int, default=60)
p.add_argument("--max-params", type=int, default=6)
p.add_argument("--max-returns", type=int, default=6)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args([])
def cc(src):
return {m["function"]: m for m in analyze_source(src)}
checks = []
def check(name, cond): checks.append((name, bool(cond)))
m = cc("def f():\n return 1\n")["f"]
check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
m = cc("def f(x):\n if x:\n return 1\n return 2\n")["f"]
check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
m = cc("def f(x):\n if x == 1:\n a = 1\n elif x == 2:\n a = 2\n elif x == 3:\n a = 3\n else:\n a = 0\n return a\n")["f"]
check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
m = cc("def f(a, b, c):\n return a and b or c\n")["f"]
check("boolean operators add per operand", m["cc"] == 3)
m = cc("def f(xs):\n return [x for x in xs if x if x > 2]\n")["f"]
check("comprehension and its ifs count", m["cc"] == 4)
m = cc("def f():\n try:\n g()\n except ValueError:\n pass\n except KeyError:\n pass\n")["f"]
check("each except handler counts", m["cc"] == 3)
m = cc("def f(x):\n return 1 if x else 2\n")["f"]
check("ternary counts", m["cc"] == 2)
m = cc("def f(x):\n while x:\n for i in x:\n if i:\n with open(i) as h:\n pass\n")["f"]
check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
r = cc("def outer():\n def inner(x):\n if x: return 1\n return inner\n")
check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
r = cc("class A:\n def m(self, a, b):\n pass\n")
check("method name and self excluded from params", r["A.m"]["params"] == 2)
r = cc("def f(a, b, c, d, e, f, *args, **kw):\n pass\n")
check("varargs counted as params", r["f"]["params"] == 8)
m = cc("def f(x):\n assert x\n return x\n")["f"]
check("assert counts", m["cc"] == 2)
if sys.version_info >= (3, 10):
m = cc("def f(x):\n match x:\n case 1:\n return 1\n case _:\n return 0\n")["f"]
check("match cases count", m["cc"] == 3)
else:
check("match cases count (skipped < 3.10)", True)
big = "def big(x):\n" + "".join(" if x == %d:\n return %d\n" % (i, i) for i in range(16)) + " return -1\n"
m = cc(big)["big"]
fs = [c for c, _, _ in findings_for(m, o)]
check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
check("simple + churn is not a hotspot", findings_for(m, o) == [])
m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
ok = all(c for _, c in checks)
for n, c in checks:
print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if ok else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test:
return self_test()
if not o.paths:
parser().print_usage(sys.stderr); return 2
for p in o.paths:
if not os.path.exists(p):
print("no such path: " + p, file=sys.stderr); return 2
results, errors = run(o.paths, o)
print(render(results, errors, o))
if errors and not results:
return 2
minsev = SEV[o.min_severity]
return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Act as a professional CV writer and designer. Review and improve my attached CV by refining its language, structure and presentation. Highlight my qualifications, experience, key achievements, leadership and technical skills. Use a modern, elegant design with professional colours, clear headings and appropriate visuals. Preserve factual accuracy and do not invent information. Deliver a polished, ATS-friendly and fully editable Microsoft Word (.docx) document.
This prompt will improve not only visual presentation but also the quality of the CV content, professional impact, structure and readability.
Recently Updated
Create clean, studio-lit product photography and consistent reference-based visuals using Free AI Image Generator workflows like FreeCreate (https://freecreate.app/generate).
Act as a commercial product photographer and art director. Given a product subject (minimalist ceramic coffee mug), target lighting (soft natural window light), and backdrop (warm linen table with subtle shadows), generate 3 detailed image-generation prompts with camera focal length, depth of field, color palette, and composition notes. You can test the resulting prompts directly in any Free AI Image Generator such as https://freecreate.app/generate and refine them with reference photos.

Turn a reference photo into a luxury fashion editorial: the subject lounges on a beige sofa in a zebra-print robe, with soft studio light and a high-end magazine look.
Ultra-realistic luxury fashion editorial photograph of the woman in the reference image. Keep her hair as in the reference, styled in loose, flowing waves, swept back from her forehead and cascading over her right shoulder. Natural luminous skin with visible pores, delicate microtexture, subtle peach blush and minimal elegant makeup. She wears a luxurious oversized black-and-white zebra-patterned robe dress made of soft, thick, textured fabric. Deep V-shaped neckline with relaxed off-the-shoulder styling, revealing her collarbones and shoulders. Voluminous long sleeves, loosely draped fabric and a matching belt tied at the waist. A short, elegant necklace of large white pearls rests around her neck. The woman reclines comfortably on a large beige upholstered sofa with wide, softly padded back cushions. Her body is slightly angled, shoulders relaxed, one arm extended along the sofa while the other rests naturally near her lap. The flowing zebra-patterned fabric covers her legs. She looks directly into the camera with a calm, confident, slightly serious expression. Relaxed lips, effortless sophisticated pose. Medium-close portrait, photographed from a slightly elevated frontal angle. Soft natural daylight from the left, warm neutral tones, delicate shadows, realistic fabric texture and subtle highlights on her face and hair, matching the reference. Minimalist beige interior, understated luxury atmosphere, intimate high-fashion editorial photography, natural skin texture without excessive retouching, realistic hair strands, subtle analog film grain, refined cinematic composition.
A 30-second Seedance street comedy in 8 timed scenes: a blonde woman with a black umbrella and a run of small mishaps on a city street, with shot-by-shot timing, camera moves and comic beats.
THE BLONDE WOMAN WITH THE BLACK UMBRELLA Duration: 30 Seconds Aspect Ratio: 16:9 Style: Photorealistic live-action, cinematic urban comedy. MAIN CHARACTER: A stylish young blonde woman with long wavy hair, wearing a long black coat, white shirt, black tie, black trousers, and leather boots. She carries a white takeaway coffee cup and a closed black umbrella. Maintain identical appearance throughout. LOCATION: A cloudy New York-style street with wet pavement, stone buildings, fountain, yellow taxi, subway entrance, fruit shop, and red-carpet entrance. SCENE 1 (0–3s): OPEN MANHOLE The woman uses her umbrella to push a loose metal manhole cover back into place while casually walking and drinking coffee. SCENE 2 (3–7s): FOUNTAIN COIN She knocks a coin into a stone fountain using her umbrella. A little girl nearby happily raises her arms without falling into the water. SCENE 3 (7–11s): YELLOW TAXI Passing a yellow taxi, she interferes with a suited man's movement using her umbrella. He loses balance and falls backward while she walks away calmly. SCENE 4 (11–15s): DOG WALKER She catches several red dog leashes with her umbrella, tangling them together. The confused man raises his hands as the dogs gather around him. SCENE 5 (15–19s): MOUSE AND PIZZA A tiny gray mouse struggles to move an oversized pepperoni pizza beside a green subway entrance. A cardboard tube and the woman's black boots remain visible. SCENE 6 (19–23s): FOOD TRAY She interferes with a suited man's movement using her umbrella as he carries a tray of small cups outside a fruit shop. He struggles to keep everything balanced. SCENE 7 (23–27s): RED CARPET She confidently walks past a grand red-carpet entrance. A security guard raises his hand while formally dressed guests watch her. SCENE 8 (27–30s): FINAL SHOT She stops near a glass entrance, takes a sip of coffee, looks directly into the camera, and gives a subtle mischievous smile. CINEMATOGRAPHY: Smooth tracking shots, cinematic wide angles, realistic close-ups, natural movement, shallow depth of field, and consistent lighting. AUDIO: Natural city ambience, footsteps, fountain splash, taxi traffic, barking dogs, rattling objects, and coffee sipping. NEGATIVE PROMPT: No character changes, no missing props, no cartoon effects, no distorted faces, no extra limbs, no child falling into water, no animal substitutions, no duplicated characters, no subtitles, no watermark. FINAL RESULT: A seamless 30-second photorealistic street comedy with all eight scenes in the exact order.
Opinionated habits for measuring and fixing performance problems: profilers, benchmarks, percentiles and evidence-backed optimizations.
# Performance Profiling taste of an engineer who measures before optimizing anything - Never optimize without a reproducible benchmark or production profile that shows the hot path first. Confidence: 0.95 - Write down the target before starting (for example "p95 under 200 ms at 500 rps") and stop once it is met. Confidence: 0.85 - Profile in an environment close to production: optimized build, realistic data size and the same CPU architecture. Confidence: 0.90 - Use sampling profilers (perf, py-spy, async-profiler, pprof, Chrome DevTools) before instrumenting ones, because they barely change what they measure. Confidence: 0.85 - Read flame graphs for wide frames, not tall stacks; the widest box near the top is usually the place to work on. Confidence: 0.85 - Keep continuous profiling running in production (Pyroscope, Parca, Datadog) so regressions can be compared with last week. Confidence: 0.70 - Look at wall-clock time and CPU time separately; a slow request that is mostly waiting needs tracing, not a CPU profile. Confidence: 0.90 - Use distributed tracing to find which service or query owns the latency before profiling any single process. Confidence: 0.80 - Report latency as percentiles (p50, p95, p99) with sample counts, never averages alone. Confidence: 0.95 - Warm up before measuring and run each benchmark enough times to report variance, using tools like hyperfine, criterion, BenchmarkDotNet or pytest-benchmark. Confidence: 0.85 - Change one thing at a time and keep before and after numbers in the pull request description. Confidence: 0.90 - Check the algorithm and the number of round trips (N+1 queries, chatty APIs) before micro-optimizing code. Confidence: 0.90 - Run `EXPLAIN ANALYZE` on the slow query with production-like statistics before adding an index or rewriting it. Confidence: 0.85 - Profile memory as a separate pass: allocation rate, heap growth and GC pauses, using heap snapshots or allocation profilers. Confidence: 0.80 - Treat lock contention and thread pool saturation as first-class suspects in concurrent services, and profile off-CPU time to see them. Confidence: 0.70 - Prefer caching only after proving the work is repeated and the data can tolerate staleness. Confidence: 0.80 - Keep micro-benchmarks in the repository next to the code they measure, and run the critical ones in CI with a regression threshold. Confidence: 0.70 - Pin CPU frequency and isolate benchmark runners, or use instruction counts, so CI noise does not trigger false alarms. Confidence: 0.60 - For frontend work, profile on a throttled mid-range device and track Core Web Vitals from real users, not only Lighthouse on a laptop. Confidence: 0.80 - Leave a short comment next to any non-obvious optimization explaining the measurement that justified it. Confidence: 0.85 - Remove an optimization that no longer shows up in profiles if it makes the code harder to read. Confidence: 0.65 - Share profiles as files or links in the incident or PR so others can reproduce the analysis. Confidence: 0.75
Opinionated Deno conventions for secure, zero-config TypeScript servers and tools: permissions, JSR imports, testing and publishing.
# Deno Project taste of a TypeScript developer who wants secure, zero-config server code - Start with `deno init` and keep a single `deno.json` for tasks, imports, lint, fmt and compiler options; no separate tsconfig or eslintrc. Confidence: 0.90 - Pin dependencies in the `imports` map of `deno.json` with `jsr:` and `npm:` specifiers, and keep version numbers out of source files. Confidence: 0.90 - Prefer JSR packages, starting with `@std/*`, over npm equivalents when both exist. Confidence: 0.80 - Commit `deno.lock` and run CI with `--frozen` so a dependency can never change silently. Confidence: 0.90 - Grant the narrowest permissions possible, scoped to hosts and paths (`--allow-net=api.example.com`, `--allow-read=./data`); never `-A` outside quick local experiments. Confidence: 0.95 - Write the permission flags into the `deno.json` tasks so every developer runs the app with the same sandbox. Confidence: 0.85 - Use `Deno.serve` with a plain `(req: Request) => Response` handler, and add Hono only when routing grows beyond a few paths. Confidence: 0.80 - Stick to Web standard APIs (`fetch`, `Request`, `URL`, `crypto.subtle`, streams) before reaching for Deno-only or Node-compat APIs. Confidence: 0.85 - Treat `node:` imports and npm packages as an escape hatch and keep them out of core domain modules. Confidence: 0.70 - Keep TypeScript strict as Deno ships it and never weaken compiler options to silence errors. Confidence: 0.90 - Use `deno fmt` and `deno lint` with default rules; argue about logic, not formatting. Confidence: 0.85 - Write tests with `Deno.test` and `@std/assert` next to the code as `*_test.ts` files. Confidence: 0.85 - Run `deno test` with the same narrow permissions as production, so missing grants fail in CI and not at runtime. Confidence: 0.75 - Use `t.step` for grouped scenarios and rely on the built-in resource and op sanitizers to catch leaked timers and sockets. Confidence: 0.70 - Collect coverage with `deno test --coverage` and `deno coverage --lcov` without extra tooling. Confidence: 0.65 - Run `deno check` in CI on every entry point, including scripts that are not imported by the main app. Confidence: 0.80 - Read configuration through a single typed module that validates `Deno.env` once at startup and fails fast on missing values. Confidence: 0.85 - Use the `--env-file` flag for local `.env` files instead of a dotenv dependency. Confidence: 0.75 - Use Deno KV for small queues, counters and session data when deploying to Deno Deploy; use Postgres once relations matter. Confidence: 0.60 - Ship single-binary internal tools with `deno compile`, embedding only the permissions the tool needs. Confidence: 0.75 - Publish shared libraries to JSR with explicit `exports`, JSDoc on every public symbol and no slow types, and check them with `deno publish --dry-run`. Confidence: 0.85 - Handle shutdown by listening for `SIGTERM` with `Deno.addSignalListener` and awaiting `server.shutdown()`. Confidence: 0.70 - Use `deno task` for every repeated command instead of a Makefile or npm scripts. Confidence: 0.80
Opinionated conventions for building, testing and releasing small, dependable Ruby gems with clean gemspecs and safe publishing.
# Ruby Gem taste of a maintainer who ships small, dependable gems with boring releases - Scaffold new gems with `bundle gem <name> --test=rspec --ci=github --linter=rubocop` and keep the generated layout instead of inventing a custom one. Confidence: 0.80 - Keep the gemspec as the single source of truth for metadata, required Ruby version and runtime dependencies; the Gemfile only adds development tools. Confidence: 0.90 - Set `required_ruby_version` explicitly and support only Ruby versions that still receive security fixes. Confidence: 0.85 - Build `spec.files` from `git ls-files` filtered to `lib`, `sig`, `exe`, LICENSE, README and CHANGELOG so tests and fixtures never ship in the package. Confidence: 0.85 - Add as few runtime dependencies as possible and give each one a pessimistic constraint like `~> 2.3`, never an unbounded `>=`. Confidence: 0.90 - Do not commit `Gemfile.lock` for a library; let CI resolve fresh dependencies so breakage shows up early. Confidence: 0.65 - Namespace everything under one top-level module that matches the gem name, and never monkey-patch core classes from a library. Confidence: 0.95 - Use Zeitwerk for gems with many files, and plain `require_relative` for small ones. Confidence: 0.70 - Expose configuration through a `configure` block that yields a plain configuration object with documented defaults. Confidence: 0.80 - Define a base `<GemName>::Error < StandardError` and raise specific subclasses so callers can rescue the whole family. Confidence: 0.90 - Add `# frozen_string_literal: true` to every Ruby file. Confidence: 0.80 - Write tests in RSpec with `--require spec_helper`, random order and `disable_monkey_patching!` turned on. Confidence: 0.80 - Run CI on a matrix of all supported Rubies plus `head`, with `head` allowed to fail. Confidence: 0.85 - Enforce style with RuboCop (or Standard) in CI, and keep project-wide disables in `.rubocop.yml` instead of inline comments. Confidence: 0.75 - Ship RBS signatures in `sig/` for the public API, or at least YARD types, so editors and Steep can check callers. Confidence: 0.60 - Document every public method with YARD and keep a runnable quick-start example at the top of the README. Confidence: 0.80 - Follow Semantic Versioning strictly and keep `VERSION` in `lib/<gem>/version.rb` as the only place the version lives. Confidence: 0.95 - Maintain a CHANGELOG in Keep a Changelog format and update it in the same pull request as the change. Confidence: 0.85 - Deprecate before removing: warn through `Kernel#warn` with `category: :deprecated` for at least one minor release. Confidence: 0.85 - Publish from CI with RubyGems trusted publishing on a tagged release instead of running `gem push` from a laptop. Confidence: 0.85 - Require MFA for every owner by setting `rubygems_mfa_required` to "true" in the gemspec metadata. Confidence: 0.95 - Set `source_code_uri`, `changelog_uri` and `bug_tracker_uri` in the metadata so rubygems.org links back to the repository. Confidence: 0.75 - Keep optional integrations (Rails, Sidekiq) behind separate requires such as `require "<gem>/rails"` so they never load by default. Confidence: 0.80 - Test the packaged gem, not only the repo: build it in CI, install it into a clean bundle and run a smoke script. Confidence: 0.70
Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
name: accounts-receivable-aging-report
description: Builds an accounts receivable aging report from an invoice CSV: Current, 1-30, 31-60, 61-90 and 90+ buckets per customer and currency, overdue share, DSO, credit limit and concentration checks, disputes, and a collection stage per invoice. Stdlib Python.
---
# Accounts Receivable Aging Report
You help founders, freelancers, agency owners and small-business finance people see who owes them money, how late it is, and what to do about it this week. Spreadsheets of invoices hide the important parts: one client quietly holding 60% of the money owed, an invoice that slipped past 90 days, a partial payment nobody followed up, a disputed invoice that keeps getting reminder emails. You turn an invoice export into a clear aging report, a short action list and polite, firm collection steps.
You work on the user's data locally; invoice data is confidential, so you never upload it anywhere. You are not an accountant or lawyer: you flag when write-offs, late fees, collections or tax treatment need a professional, and the owner decides what to send.
## Files in this skill
- `scripts/ar_aging.py` - reads `invoices.csv` (invoice_id, customer, issue_date, due_date, amount, paid_amount, currency, disputed, last_contact) and optional `customers.json` (credit limits, terms, contacts); prints aging buckets per customer and currency, overdue %, DSO, the overdue list with a collection stage, and findings A01-A08; `--as-of`, `--format text|md|json|csv`, `--min-severity`, `--concentration`, `--contact-days`, `--dso-days`; `--self-test` runs 20 checks (Python 3.8+ standard library only)
- `references/aging-buckets-and-dso.md` - how buckets, overdue share, DSO, concentration and credit limits are calculated and their limits
- `references/collection-playbook.md` - stages 0-5 plus dispute hold, message skeletons, good practice
- `templates/collections-summary.md` - the one-page review you hand back
- `examples/invoices.csv`, `examples/customers.json` - a fictional design agency with 18 invoices in EUR and USD: a 146-day-old invoice, a disputed one, partial payments, an overpayment, one client over its credit limit holding 59% of receivables, and overdue invoices with no contact logged
## Workflow
### 1. Get the data
Ask for an export from the invoicing or accounting tool with the columns above (paid invoices from the last 90 days too, for DSO). Map their column names if needed. Ask for credit limits and payment terms per customer if they have them; otherwise skip `customers.json` and say that A03 cannot be checked.
### 2. Run the report
```
python3 scripts/ar_aging.py invoices.csv customers.json --as-of 2026-11-25
python3 scripts/ar_aging.py invoices.csv customers.json --format md > aging.md
python3 scripts/ar_aging.py invoices.csv --format csv > overdue-list.csv
python3 scripts/ar_aging.py invoices.csv customers.json --min-severity high
python3 scripts/ar_aging.py --self-test
```
Exit code 0 = no findings at or above `--min-severity`, 1 = findings, 2 = input error.
| Code | Severity | Meaning |
|---|---|---|
| A01 | high | open balance more than 90 days past due |
| A02 | medium | one customer holds more than 30% of open receivables (per currency) |
| A03 | high | customer open balance above its credit limit |
| A04 | low | partially paid invoice still open |
| A05 | medium | disputed invoice: resolve before chasing |
| A06 | medium | overdue with no contact in the last 14 days |
| A07 | low | overpaid invoice: refund or apply as credit |
| A08 | high | data problem: duplicate id, bad date, negative amount, due before issue |
### 3. Check and interpret
- Fix A08 data problems first and re-run; totals are not trustworthy until then.
- Compare DSO with payment terms and look at the 90+ bucket and concentration.
- Separate disputes from slow payers; never send reminders on a disputed amount.
- Ask about context the data cannot show (a client that always pays after its board meeting, a promised transfer).
### 4. Plan actions
Sort the overdue list by amount x age and pick this week's top actions using `references/collection-playbook.md`. Draft messages for each stage in the user's tone; mark which need the owner's review (final notices, payment plans, pausing work).
### 5. Report
Fill `templates/collections-summary.md`: headline numbers, this week's actions with owners, disputes, risk notes (credit limits, concentration, credits) and process improvements (deposits, direct debit, shorter terms, PO numbers on invoices).
## Example
```
python3 scripts/ar_aging.py examples/invoices.csv examples/customers.json --as-of 2026-11-25
```
shows 42,940 EUR open, 73% overdue, DSO about 114 days; Bluefin Logistics holds 59.4% and is over its 20,000 limit (A02, A03) with a disputed 6,200 invoice on hold (A05); Northwind Bakery's INV-1041 is 146 days past due (A01) with no contact for 36 days (A06); and Maple & Pine Studio overpaid by 40 EUR (A07).
## Rules
- Use the user's numbers; mark assumptions.
- Keep currencies separate; never convert without a rate the user gives.
- Stay polite and factual in every message; no threats the contract does not support.
- Not legal, tax or accounting advice; say when to ask a professional.
FILE:references/aging-buckets-and-dso.md
# Aging buckets, overdue share and DSO
## Aging buckets
Each open invoice is placed by **days past due** on the report date (`--as-of`), not by days since issue:
| Bucket | Days past due | Typical reading |
|---|---|---|
| Current | 0 or less (not yet due) | healthy; no action except making sure the invoice was received |
| 1-30 | 1-30 | normal slippage; friendly reminders usually work |
| 31-60 | 31-60 | a process or cash problem at the customer; escalate politely |
| 61-90 | 61-90 | real risk; final notices, pause new work |
| 90+ | over 90 | a large share will never be paid without a plan; consider payment plans, collections, or legal advice, and talk to your accountant about a bad-debt provision |
Open balance = amount - paid_amount. Fully paid invoices drop out. Overpaid invoices (negative open balance) are customer credit, reported as A07, and are not netted against other invoices automatically: decide with the customer whether to refund or apply the credit.
## Overdue share
`overdue % = (open - Current) / open`. Watch the trend month to month more than the absolute number. Many small businesses aim to keep 90+ under about 5-10% of receivables; this is a rule of thumb, not a standard.
## DSO (days sales outstanding)
The script uses the simple count-back formula over a window (default 90 days, `--dso-days`):
`DSO = open receivables / invoiced amount in the last N days x N`
Example: 42,940 open, 33,880 invoiced in the last 90 days -> DSO about 114 days. Compare DSO with your payment terms: with 30-day terms, a DSO far above 30 means customers pay late on average or old debt is piling up.
Limits:
- Uneven billing (one big project invoice) swings DSO a lot; look at a few months.
- Currencies are reported separately; DSO is per currency.
- The CSV must contain all invoices issued in the window (including paid ones) for DSO to be meaningful.
## Concentration
If one customer holds more than about 30% (`--concentration`) of open receivables, a single late payer can create a cash gap. That is a business risk to discuss, not a collection failure.
## Credit limits
`customers.json` can hold a `credit_limit` per customer. Exceeding it (A03) is a signal to stop or slow new work, ask for a deposit, or agree a payment plan before taking on more.
## Data checks (A08)
Duplicate invoice ids, unreadable dates, negative amounts and due dates before issue dates are reported first: fix the export before trusting any totals.
FILE:references/collection-playbook.md
# Collection playbook (polite, firm, documented)
The script assigns a stage to each overdue invoice. Adapt timing to your terms and relationships; always stay factual and polite, and log every contact (`last_contact`) so A06 stays quiet.
| Stage | Days past due | Action | Channel |
|---|---|---|---|
| 0 | before due | confirm the invoice reached the right person / AP portal; check PO numbers | email |
| 1 | 1-7 | friendly reminder with invoice copy and payment link | email |
| 2 | 8-30 | firm reminder plus a short call; ask for a payment date | email + phone |
| 3 | 31-60 | escalate to the decision maker or project sponsor; pause new work or deliveries if your contract allows | call + email |
| 4 | 61-90 | final notice with a clear date and the next step (late fees if in your contract, payment plan offer) | written notice |
| 5 | 90+ | payment plan in writing, or collections agency / small-claims / legal advice; talk to your accountant about provisions | written |
| hold | disputed | resolve the dispute first: what exactly is contested, credit note or partial payment for the undisputed part | call |
## Message skeletons
**Stage 1:** "Hi {{name}}, a quick reminder that invoice {{id}} for {{amount}} was due on {{due_date}}. A copy and payment link are attached. If it has already been paid, thank you and please ignore this."
**Stage 2:** "Hi {{name}}, invoice {{id}} ({{amount}}) is now {{days}} days overdue. Could you confirm the date it will be paid? If something is blocking it (PO, approval, a question about the work), tell me and I will sort it out."
**Stage 4:** "Hello {{name}}, despite earlier reminders on {{dates}}, invoice {{id}} ({{amount}}) remains unpaid {{days}} days after the due date. Please arrange payment by {{date}}. If that is not possible, reply by then so we can agree a written payment plan; otherwise we will {{next_step}}."
## Good practice
- Separate disputes from slow payment; never chase a disputed amount with reminders.
- Ask for partial payment of the undisputed part.
- For repeat late payers: shorter terms, deposits, card or direct debit, milestone billing.
- Late fees and interest only if your contract and local law allow them; check before you threaten them.
- Keep tone respectful: many late payments are process problems (wrong email, missing PO), not unwillingness.
- This is not legal or accounting advice; for collections, write-offs and tax treatment ask a qualified professional.
FILE:templates/collections-summary.md
# Receivables review - {{business}} - as of {{as_of}}
## Headline
- Open receivables: {{open_total}} ({{currency}}), overdue {{overdue_total}} ({{overdue_pct}}%), DSO {{dso}} days vs {{terms}}-day terms
- 90+ days: {{over_90_total}} across {{over_90_count}} invoices
- Biggest exposure: {{top_customer}} with {{top_share}}% of open balance
## This week's actions (highest value first)
| # | Customer | Invoice(s) | Amount | Days past due | Stage / action | Owner | Due |
|---|---|---|---|---|---|---|---|
| 1 | | | | | | | |
| 2 | | | | | | | |
| 3 | | | | | | | |
## Disputes to resolve
| Invoice | Customer | Amount | What is disputed | Next step | Owner |
|---|---|---|---|---|---|
## Risk notes
- Credit limits exceeded: {{customers_over_limit}} -> {{proposal: pause new work / deposit / payment plan}}
- Concentration: {{customer}} {{share}}% -> {{proposal}}
- Credits to refund or apply: {{credits}}
- Data fixes needed in the export: {{data_issues}}
## Process improvements
- {{e.g. send invoices to the AP inbox with PO numbers; move Orbit Fitness to direct debit; 50% deposit on new projects for clients with 90+ history}}
_Figures from ar_aging.py on {{as_of}}. Not legal or accounting advice._
FILE:examples/invoices.csv
invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact
INV-1041,Northwind Bakery,2026-06-02,2026-07-02,2400.00,0,EUR,no,2026-10-20
INV-1047,Harbor Dental Clinic,2026-07-15,2026-08-14,1850.00,850.00,EUR,no,2026-11-18
INV-1052,Bluefin Logistics,2026-08-05,2026-09-04,6200.00,0,EUR,yes,2026-11-10
INV-1055,Northwind Bakery,2026-08-20,2026-09-19,1200.00,0,EUR,no,2026-10-20
INV-1058,Maple & Pine Studio,2026-09-01,2026-10-01,980.00,980.00,EUR,no,
INV-1060,Bluefin Logistics,2026-09-10,2026-10-10,7400.00,0,EUR,no,
INV-1063,Greenleaf Co-op,2026-09-22,2026-10-22,1500.00,0,EUR,no,2026-11-21
INV-1064,Harbor Dental Clinic,2026-10-01,2026-10-31,1850.00,0,EUR,no,2026-11-18
INV-1066,Orbit Fitness,2026-10-03,2026-11-02,3200.00,0,EUR,no,
INV-1067,Maple & Pine Studio,2026-10-06,2026-11-05,760.00,800.00,EUR,no,
INV-1069,Bluefin Logistics,2026-10-15,2026-11-14,5100.00,0,EUR,no,2026-11-19
INV-1070,Greenleaf Co-op,2026-10-20,2026-11-19,1500.00,0,EUR,no,
INV-1072,Orbit Fitness,2026-11-01,2026-12-01,3200.00,0,EUR,no,
INV-1073,Northwind Bakery,2026-11-05,2026-12-05,950.00,0,EUR,no,
INV-1074,Bluefin Logistics,2026-11-10,2026-12-10,6800.00,0,EUR,no,
INV-1075,Lakeside Hostel,2026-11-12,2026-11-26,640.00,0,EUR,no,
INV-1076,Atlas Outdoor Inc,2026-09-15,2026-10-15,4500.00,2000.00,USD,no,2026-11-03
INV-1077,Atlas Outdoor Inc,2026-11-15,2026-12-15,4500.00,0,USD,no,
FILE:examples/customers.json
{
"default_terms_days": 30,
"note": "Fictional clients of a small design and web agency. Credit limits are what the agency is willing to have open per client.",
"customers": {
"Northwind Bakery": {"credit_limit": 5000, "terms_days": 30, "contact": "owner, prefers phone"},
"Harbor Dental Clinic": {"credit_limit": 4000, "terms_days": 30, "contact": "practice manager"},
"Bluefin Logistics": {"credit_limit": 20000, "terms_days": 30, "contact": "accounts payable inbox + project sponsor"},
"Maple & Pine Studio": {"credit_limit": 3000, "terms_days": 30, "contact": "founder"},
"Greenleaf Co-op": {"credit_limit": 4000, "terms_days": 30, "contact": "treasurer, pays after monthly board meeting"},
"Orbit Fitness": {"credit_limit": 6000, "terms_days": 30, "contact": "finance lead"},
"Lakeside Hostel": {"credit_limit": 2000, "terms_days": 14, "contact": "manager"},
"Atlas Outdoor Inc": {"credit_limit": 8000, "terms_days": 30, "contact": "AP portal, PO required"}
}
}
FILE:scripts/ar_aging.py
#!/usr/bin/env python3
"""ar_aging.py - accounts receivable aging report from an invoice CSV (standard library only, Python 3.8+).
invoices.csv columns (header required; extra columns ignored):
invoice_id, customer, issue_date, due_date, amount, paid_amount, currency,
disputed (yes/no, optional), last_contact (YYYY-MM-DD, optional)
customers.json (optional): {"default_terms_days": 30, "customers": {"Name": {"credit_limit": 10000, "terms_days": 30, "contact": "..."}}}
Report: open balance per invoice, aging buckets by days past due as of --as-of
(Current, 1-30, 31-60, 61-90, 90+), totals per customer and currency, % overdue,
approximate DSO (open balance / sales in the last --dso-days days x --dso-days),
a collection stage per overdue invoice, and findings:
A01 high open balance more than 90 days past due
A02 medium one customer holds more than --concentration % (default 30) of the open balance
A03 high customer open balance above its credit_limit
A04 low partially paid invoice still open
A05 medium disputed invoice (excluded from reminders, needs resolution)
A06 medium overdue with no contact logged in the last --contact-days (default 14)
A07 low overpaid invoice (customer credit to refund or apply)
A08 high data problem (bad date, negative amount, due before issue, duplicate id)
Usage: ar_aging.py invoices.csv [customers.json] [--as-of YYYY-MM-DD] [--format text|md|json|csv]
[--min-severity low|medium|high] [--concentration PCT] [--contact-days N] [--dso-days N]
ar_aging.py --self-test
Exit: 0 no findings at or above --min-severity, 1 findings, 2 usage/input error.
"""
import argparse, csv, datetime as dt, io, json, sys
from collections import OrderedDict, defaultdict
BUCKETS = ["Current", "1-30", "31-60", "61-90", "90+"]
SEV = {"low": 1, "medium": 2, "high": 3}
def bucket(days_past_due):
if days_past_due <= 0: return "Current"
if days_past_due <= 30: return "1-30"
if days_past_due <= 60: return "31-60"
if days_past_due <= 90: return "61-90"
return "90+"
def stage(days_past_due, disputed):
if disputed: return "hold: resolve dispute first"
if days_past_due <= 0: return "none (not due)"
if days_past_due <= 7: return "1 friendly reminder"
if days_past_due <= 30: return "2 firm reminder + call"
if days_past_due <= 60: return "3 escalate to decision maker, pause new work"
if days_past_due <= 90: return "4 final notice with date"
return "5 payment plan or collections/legal review"
def parse_date(s):
return dt.datetime.strptime(s.strip(), "%Y-%m-%d").date()
def money(s):
s = (s or "").strip().replace(",", "")
return round(float(s), 2) if s else 0.0
def load_invoices(text):
rows, problems, seen = [], [], set()
reader = csv.DictReader(io.StringIO(text))
need = {"invoice_id", "customer", "issue_date", "due_date", "amount"}
if not reader.fieldnames or not need <= {f.strip() for f in reader.fieldnames}:
raise ValueError("invoices.csv needs columns: " + ", ".join(sorted(need)))
for n, r in enumerate(reader, 2):
r = {k.strip(): (v or "").strip() for k, v in r.items() if k}
iid = r["invoice_id"]
try:
issue, due = parse_date(r["issue_date"]), parse_date(r["due_date"])
amount, paid = money(r["amount"]), money(r.get("paid_amount"))
last = parse_date(r["last_contact"]) if r.get("last_contact") else None
except ValueError as e:
problems.append((iid or "line %d" % n, "line %d: %s" % (n, e))); continue
if iid in seen:
problems.append((iid, "duplicate invoice_id %s (line %d skipped)" % (iid, n))); continue
seen.add(iid)
if amount < 0 or paid < 0:
problems.append((iid, "negative amount on line %d" % n)); continue
if due < issue:
problems.append((iid, "due_date before issue_date on line %d" % n))
rows.append(dict(invoice_id=iid, customer=r["customer"], issue=issue, due=due, amount=amount, paid=paid,
currency=r.get("currency") or "EUR", disputed=r.get("disputed", "").lower() in ("yes", "y", "true", "1"),
last_contact=last))
return rows, problems
def analyze(rows, problems, customers, o):
as_of = o.as_of
inv, findings = [], []
def add(code, sev, ref, msg): findings.append(dict(code=code, severity=sev, ref=ref, message=msg))
for ref, msg in problems: add("A08", "high", ref, msg)
for r in rows:
open_bal = round(r["amount"] - r["paid"], 2)
dpd = (as_of - r["due"]).days
rec = dict(r, open=open_bal, days_past_due=dpd, bucket=bucket(dpd) if open_bal > 0 else "-", stage=stage(dpd, r["disputed"]) if open_bal > 0 else "-")
inv.append(rec)
if open_bal < 0:
add("A07", "low", r["invoice_id"], "%s overpaid by %.2f %s: refund or apply as credit" % (r["customer"], -open_bal, r["currency"]))
continue
if open_bal == 0: continue
if r["paid"] > 0:
add("A04", "low", r["invoice_id"], "partially paid: %.2f of %.2f %s still open" % (open_bal, r["amount"], r["currency"]))
if r["disputed"]:
add("A05", "medium", r["invoice_id"], "disputed (%.2f %s, %d days past due): resolve before chasing" % (open_bal, r["currency"], max(dpd, 0)))
if dpd > 90:
add("A01", "high", r["invoice_id"], "%s: %.2f %s is %d days past due" % (r["customer"], open_bal, r["currency"], dpd))
if dpd > 0 and not r["disputed"]:
since = (as_of - r["last_contact"]).days if r["last_contact"] else None
if since is None or since > o.contact_days:
add("A06", "medium", r["invoice_id"], "%d days overdue, %s" % (dpd, "no contact logged" if since is None else "last contact %d days ago" % since))
# per currency summaries
by_cur = OrderedDict()
for r in inv:
if r["open"] <= 0: continue
c = by_cur.setdefault(r["currency"], dict(total=0.0, buckets={b: 0.0 for b in BUCKETS}, customers=defaultdict(lambda: {b: 0.0 for b in BUCKETS})))
c["total"] += r["open"]; c["buckets"][r["bucket"]] += r["open"]; c["customers"][r["customer"]][r["bucket"]] += r["open"]
summaries = OrderedDict()
for cur, c in by_cur.items():
total = round(c["total"], 2)
overdue = round(total - c["buckets"]["Current"], 2)
sales = sum(r["amount"] for r in inv if r["currency"] == cur and 0 <= (as_of - r["issue"]).days < o.dso_days)
dso = round(total / sales * o.dso_days, 1) if sales else None
custs = []
for name, b in c["customers"].items():
ct = round(sum(b.values()), 2)
custs.append(dict(customer=name, total=ct, buckets={k: round(v, 2) for k, v in b.items()}, share_pct=round(100 * ct / total, 1) if total else 0))
if total and 100 * ct / total > o.concentration and len(c["customers"]) > 1:
add("A02", "medium", name, "holds %.1f%% of open %s receivables (%.2f)" % (100 * ct / total, cur, ct))
lim = (customers.get("customers", {}).get(name) or {}).get("credit_limit")
if lim is not None and ct > lim:
add("A03", "high", name, "open balance %.2f %s exceeds credit limit %.2f" % (ct, cur, lim))
custs.sort(key=lambda x: -x["total"])
summaries[cur] = dict(total=total, overdue=overdue, overdue_pct=round(100 * overdue / total, 1) if total else 0,
buckets={k: round(v, 2) for k, v in c["buckets"].items()}, dso=dso, customers=custs)
order = {"high": 0, "medium": 1, "low": 2}
findings.sort(key=lambda f: (order[f["severity"]], f["code"], f["ref"]))
return inv, summaries, findings
def render(inv, summaries, findings, o):
minsev = SEV[o.min_severity]
shown = [f for f in findings if SEV[f["severity"]] >= minsev]
if o.format == "json":
def ser(r): return {k: (v.isoformat() if isinstance(v, dt.date) else v) for k, v in r.items()}
return json.dumps(dict(as_of=o.as_of.isoformat(), summaries=summaries, invoices=[ser(r) for r in inv if r["open"] != 0], findings=shown), indent=2)
if o.format == "csv":
out = io.StringIO(); w = csv.writer(out)
w.writerow(["invoice_id", "customer", "currency", "due_date", "days_past_due", "bucket", "open", "disputed", "stage"])
for r in sorted(inv, key=lambda r: -r["days_past_due"]):
if r["open"] > 0: w.writerow([r["invoice_id"], r["customer"], r["currency"], r["due"].isoformat(), r["days_past_due"], r["bucket"], "%.2f" % r["open"], "yes" if r["disputed"] else "no", r["stage"]])
return out.getvalue().rstrip("\n")
md = o.format == "md"
L = ["# AR aging as of %s" % o.as_of if md else "AR aging as of %s" % o.as_of, ""]
for cur, s in summaries.items():
L.append(("## %s: open %.2f, overdue %.2f (%.1f%%), DSO %s" if md else "%s: open %.2f, overdue %.2f (%.1f%%), DSO %s") % (cur, s["total"], s["overdue"], s["overdue_pct"], "%.1f days" % s["dso"] if s["dso"] is not None else "n/a"))
L.append("")
hdr = ["Customer"] + BUCKETS + ["Total", "Share"]
if md:
L.append("| " + " | ".join(hdr) + " |"); L.append("|" + "---|" * len(hdr))
else:
L.append("%-22s" % hdr[0] + "".join("%11s" % h for h in hdr[1:]))
rows = s["customers"] + [dict(customer="TOTAL", total=s["total"], buckets=s["buckets"], share_pct=100.0)]
for c in rows:
vals = ["%.2f" % c["buckets"][b] for b in BUCKETS] + ["%.2f" % c["total"], "%.1f%%" % c["share_pct"]]
L.append("| " + " | ".join([c["customer"]] + vals) + " |" if md else "%-22s" % c["customer"][:22] + "".join("%11s" % v for v in vals))
L.append("")
L.append("## Overdue invoices and next step" if md else "Overdue invoices and next step:")
od = sorted([r for r in inv if r["open"] > 0 and r["days_past_due"] > 0], key=lambda r: -r["days_past_due"])
for r in od:
L.append("%s %s %s %.2f %s, %d days past due -> %s" % ("-" if md else " ", r["invoice_id"], r["customer"], r["open"], r["currency"], r["days_past_due"], r["stage"]))
if not od: L.append(" none")
L.append("")
L.append(("## Findings (%s+)" if md else "Findings (%s+):") % o.min_severity)
for f in shown:
L.append("%s [%s] %s %s: %s" % ("-" if md else " ", f["severity"].upper(), f["code"], f["ref"], f["message"]))
if not shown: L.append(" none")
return "\n".join(L)
def parser():
p = argparse.ArgumentParser(description="Accounts receivable aging report.")
p.add_argument("invoices", nargs="?")
p.add_argument("customers", nargs="?")
p.add_argument("--as-of", type=parse_date, default=dt.date.today())
p.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--concentration", type=float, default=30.0)
p.add_argument("--contact-days", type=int, default=14)
p.add_argument("--dso-days", type=int, default=90)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args(["--as-of", "2026-06-30"])
H = "invoice_id,customer,issue_date,due_date,amount,paid_amount,currency,disputed,last_contact\n"
checks = []
def check(n, c): checks.append((n, bool(c)))
def run(body, cust=None, **kw):
oo = parser().parse_args(["--as-of", "2026-06-30"]); [setattr(oo, k, v) for k, v in kw.items()]
rows, probs = load_invoices(H + body)
return analyze(rows, probs, cust or {}, oo)
codes = lambda f: sorted({x["code"] for x in f})
check("bucket edges", [bucket(d) for d in (0, 1, 30, 31, 60, 61, 90, 91)] == ["Current", "1-30", "1-30", "31-60", "31-60", "61-90", "61-90", "90+"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("not yet due is Current, no findings", inv[0]["bucket"] == "Current" and f == [])
inv, s, f = run("I1,Acme,2026-05-01,2026-05-31,1000,0,EUR,,2026-06-25\n")
check("30 days past due in 1-30 with recent contact", inv[0]["bucket"] == "1-30" and f == [])
inv, s, f = run("I1,Acme,2026-01-01,2026-01-31,500,0,EUR,,2026-06-29\n")
check("150 days past due gives A01", "A01" in codes(f) and inv[0]["bucket"] == "90+")
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
check("overdue without contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,2026-06-01\n", contact_days=14)
check("stale contact gives A06", codes(f) == ["A06"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,200,EUR,,2026-06-28\n")
check("partial payment gives A04 and open 300", codes(f) == ["A04"] and inv[0]["open"] == 300)
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,0,EUR,yes,\n")
check("disputed gives A05, no A06, hold stage", codes(f) == ["A05"] and inv[0]["stage"].startswith("hold"))
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,500,600,EUR,,\n")
check("overpaid gives A07 only", codes(f) == ["A07"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\nI2,Bolt,2026-06-01,2026-07-01,1000,0,EUR,,\n")
check("concentration A02 for 90% customer", [x["ref"] for x in f if x["code"] == "A02"] == ["Acme"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,9000,0,EUR,,\n", {"customers": {"Acme": {"credit_limit": 5000}}})
check("credit limit A03, single customer no A02", codes(f) == ["A03"])
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI1,Acme,2026-06-01,2026-07-01,100,0,EUR,,\nI3,Acme,2026-13-01,2026-07-01,100,0,EUR,,\nI4,Acme,2026-06-01,2026-07-01,-5,0,EUR,,\n")
check("duplicate, bad date, negative give A08 x3", len([x for x in f if x["code"] == "A08"]) == 3 and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-10,2026-06-01,100,0,EUR,,2026-06-29\n")
check("due before issue flagged A08 but kept", "A08" in codes(f) and len(inv) == 1)
inv, s, f = run("I1,Acme,2026-06-01,2026-07-01,1000,0,EUR,,\nI2,Acme,2026-06-01,2026-07-01,800,0,USD,,\n")
check("currencies kept separate", set(s) == {"EUR", "USD"} and s["USD"]["total"] == 800)
inv, s, f = run("I1,Acme,2026-04-15,2026-05-15,3000,0,EUR,,2026-06-29\nI2,Acme,2026-06-15,2026-07-15,3000,0,EUR,,\n")
check("DSO = open / 90-day sales x 90", s["EUR"]["dso"] == 90.0 and s["EUR"]["overdue_pct"] == 50.0)
check("stage ladder", [stage(d, False)[0] for d in (3, 20, 45, 80, 120)] == ["1", "2", "3", "4", "5"])
inv, s, f = run("I1,Acme,2026-05-01,2026-06-01,1000,1000,EUR,,\n")
check("fully paid invoice ignored", f == [] and s == {})
try:
load_invoices("id,name\n1,x\n"); check("missing columns rejected", False)
except ValueError:
check("missing columns rejected", True)
oo = parser().parse_args(["--as-of", "2026-06-30", "--format", "csv"])
rows, probs = load_invoices(H + "I1,Acme,2026-05-01,2026-06-01,500,0,EUR,,\n")
out = render(*analyze(rows, probs, {}, oo), oo)
check("csv output has header and row", out.splitlines()[0].startswith("invoice_id") and "I1,Acme" in out)
oo.format = "json"
check("json output parses", json.loads(render(*analyze(rows, probs, {}, oo), oo))["as_of"] == "2026-06-30")
for n, c in checks: print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if all(c for _, c in checks) else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test: return self_test()
if not o.invoices:
parser().print_usage(sys.stderr); return 2
try:
with open(o.invoices, encoding="utf-8-sig") as fh: rows, probs = load_invoices(fh.read())
customers = json.load(open(o.customers, encoding="utf-8")) if o.customers else {}
except (OSError, ValueError) as e:
print("input error: %s" % e, file=sys.stderr); return 2
inv, summaries, findings = analyze(rows, probs, customers, o)
print(render(inv, summaries, findings, o))
return 1 if any(SEV[f["severity"]] >= SEV[o.min_severity] for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())
Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---
# Python Complexity Hotspot Finder
You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.
You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.
## Files in this skill
- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)
## Workflow
### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.
### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.
| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |
### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.
### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.
### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).
## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.
## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.
FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them
## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:
| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |
Nested functions, classes and lambdas are measured on their own and do not add to the outer function.
### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |
CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.
## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.
## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.
## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.
Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.
## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.
FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions
Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.
## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
if item.qty > 0:
if item.active:
process(item)
# after
for item in items:
if item.qty <= 0 or not item.active:
continue
process(item)
```
## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.
## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.
## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).
## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.
## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).
## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.
## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.
FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})
**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days
## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}
## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |
## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}
## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}
## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.
FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
total = 0
for item in items:
if item.get("qty", 0) <= 0:
continue
price = item["price"] * item["qty"]
if item.get("category") == "books":
if region == "EU":
price = price * 1.05
elif region == "UK":
price = price
else:
price = price * 1.08
elif item.get("category") == "food":
if region == "EU" and not customer.get("business"):
price = price * 1.07
else:
price = price * 1.0
else:
if region == "EU":
price = price * 1.2
elif region == "UK":
price = price * 1.2
elif region == "US" and customer.get("state") in ("CA", "NY"):
price = price * 1.09
else:
price = price * 1.0
total += price
if coupon:
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
total = total * (1 - coupon["value"] / 100)
elif coupon.get("type") == "fixed":
total = max(0, total - coupon["value"])
if customer.get("vip") or customer.get("orders", 0) > 20:
total = total * 0.95
if rush:
total += 15 if currency == "EUR" else 18
if gift_wrap:
total += 3
return round(total, 2)
def invoice_status(invoice, today):
if invoice["paid"]:
return "paid"
if invoice.get("disputed"):
return "disputed"
days = (today - invoice["due"]).days
if days <= 0:
return "open"
if days <= 30:
return "overdue"
if days <= 90:
return "late"
return "collections"
def format_amount(value, currency):
return "%s %.2f" % (currency, value)
FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""
TAX_RATES = {
# (category, region) -> rate; "*" means any
("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
("food", "EU"): 1.07, ("food", "*"): 1.0,
("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3
def tax_rate(category, region, customer):
if category == "food" and customer.get("business"):
return 1.0
if category not in ("books", "food") and region == "US":
return US_TAXED_STATES.get(customer.get("state"), 1.0)
key_category = category if category in ("books", "food") else "*"
return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])
def line_total(item, region, customer):
return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)
def apply_coupon(total, coupon):
if not coupon:
return total
if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
return total * (1 - coupon["value"] / 100)
if coupon.get("type") == "fixed":
return max(0, total - coupon["value"])
return total
def loyalty_discount(total, customer):
loyal = customer.get("vip") or customer.get("orders", 0) > 20
return total * 0.95 if loyal else total
def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
if "rush" in options:
total += RUSH_FEE.get(currency, 18)
if "gift_wrap" in options:
total += GIFT_WRAP_FEE
return round(total, 2)
FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.
Measures per function/method (standard library only, Python 3.8+):
cc cyclomatic complexity (1 + decision points: if/elif, for/while, except,
boolean operators, comprehension ifs, ternaries, match cases, assert)
depth deepest nesting of blocks inside the function
lines function length in source lines
params number of parameters (excluding self/cls)
returns number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).
Findings (severity):
H01 cc >= --cc-high (default 15) high
H02 cc >= --cc-warn (default 10) medium
H03 nesting depth >= --max-depth (4) medium
H04 lines >= --max-lines (60) medium
H05 params >= --max-params (6) low
H06 returns >= --max-returns (6) low
H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5) high
Usage:
complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
[--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys
SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}
class FuncVisitor(ast.NodeVisitor):
"""Computes metrics for one function body without descending into nested defs."""
BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)
def __init__(self):
self.cc = 1
self.max_depth = 0
self.returns = 0
self._depth = 0
def generic_visit(self, node):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
return # nested definitions are measured separately (lambdas count as 0)
block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
self.cc += 1
elif isinstance(node, ast.ExceptHandler):
self.cc += 1
elif isinstance(node, ast.BoolOp):
self.cc += len(node.values) - 1
elif isinstance(node, ast.comprehension):
self.cc += 1 + len(node.ifs)
elif type(node).__name__ == "match_case":
self.cc += 1
elif isinstance(node, ast.Return):
self.returns += 1
if block:
# an elif is an If inside orelse; do not count it as deeper nesting
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
super().generic_visit(node)
if block:
self._depth -= 1
def visit_If(self, node):
self.cc += 1
self.visit(node.test)
self._depth += 1
self.max_depth = max(self.max_depth, self._depth)
for n in node.body:
self.visit(n)
self._depth -= 1
orelse = node.orelse
if len(orelse) == 1 and isinstance(orelse[0], ast.If):
self.visit_If(orelse[0]) # elif chain: same depth
else:
self._depth += 1
for n in orelse:
self.visit(n)
self._depth -= 1
def measure_function(node):
v = FuncVisitor()
for stmt in node.body:
v.visit(stmt)
args = node.args
names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
if args.vararg: names.append(args.vararg.arg)
if args.kwarg: names.append(args.kwarg.arg)
params = len([n for n in names if n not in ("self", "cls")])
end = getattr(node, "end_lineno", node.lineno)
return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}
def analyze_source(src, filename="<string>"):
tree = ast.parse(src, filename=filename)
out = []
def walk(node, prefix):
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = prefix + child.name
m = measure_function(child)
m.update({"file": filename, "function": name, "line": child.lineno})
out.append(m)
walk(child, name + ".")
elif isinstance(child, ast.ClassDef):
walk(child, prefix + child.name + ".")
else:
walk(child, prefix)
walk(tree, "")
return out
def iter_py_files(paths):
for p in paths:
if os.path.isfile(p):
if p.endswith(".py"): yield p
continue
for root, dirs, files in os.walk(p):
dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
for f in sorted(files):
if f.endswith(".py"):
yield os.path.join(root, f)
def git_churn(path, days):
"""Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
try:
top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
capture_output=True, text=True, check=True).stdout
except (OSError, subprocess.CalledProcessError):
return {}
churn = {}
for line in log.splitlines():
line = line.strip()
if line.endswith(".py"):
k = os.path.normpath(os.path.join(top, line))
churn[k] = churn.get(k, 0) + 1
return churn
def findings_for(m, o):
f = []
if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
return f
def run(paths, o):
results, errors = [], []
churn = {}
if o.churn:
for p in paths:
churn.update(git_churn(p, o.churn))
for f in iter_py_files(paths):
try:
with open(f, encoding="utf-8") as fh:
ms = analyze_source(fh.read(), f)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append("%s: %s" % (f, e)); continue
for m in ms:
if o.churn:
m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
m["score"] = m["cc"] * (1 + m.get("churn", 0))
m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
results.append(m)
results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
return results, errors
def render(results, errors, o):
minsev = SEV[o.min_severity]
flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
top = flagged[: o.top] if o.top else flagged
n = len(results)
avg = sum(m["cc"] for m in results) / n if n else 0
if o.format == "json":
return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
"hotspots": top}, indent=2)
churn_col = o.churn is not None and o.churn > 0
if o.format == "md":
head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
rows = [head, sep]
for i, m in enumerate(top, 1):
fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
(" %d |" % m.get("churn", 0)) if churn_col else "", fs))
rows.append("")
rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
return "\n".join(rows)
lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
for i, m in enumerate(top, 1):
extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
lines.append("%2d. %s (%s:%d) cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
for x in m["findings"]:
lines.append(" [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
if not top: lines.append("No functions above the thresholds.")
for e in errors: lines.append("PARSE ERROR " + e)
return "\n".join(lines)
def parser():
p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
p.add_argument("paths", nargs="*")
p.add_argument("--format", choices=["text", "md", "json"], default="text")
p.add_argument("--min-severity", choices=list(SEV), default="low")
p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
p.add_argument("--churn-min", type=int, default=5)
p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
p.add_argument("--cc-warn", type=int, default=10)
p.add_argument("--cc-high", type=int, default=15)
p.add_argument("--max-depth", type=int, default=4)
p.add_argument("--max-lines", type=int, default=60)
p.add_argument("--max-params", type=int, default=6)
p.add_argument("--max-returns", type=int, default=6)
p.add_argument("--self-test", action="store_true")
return p
def self_test():
o = parser().parse_args([])
def cc(src):
return {m["function"]: m for m in analyze_source(src)}
checks = []
def check(name, cond): checks.append((name, bool(cond)))
m = cc("def f():\n return 1\n")["f"]
check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
m = cc("def f(x):\n if x:\n return 1\n return 2\n")["f"]
check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
m = cc("def f(x):\n if x == 1:\n a = 1\n elif x == 2:\n a = 2\n elif x == 3:\n a = 3\n else:\n a = 0\n return a\n")["f"]
check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
m = cc("def f(a, b, c):\n return a and b or c\n")["f"]
check("boolean operators add per operand", m["cc"] == 3)
m = cc("def f(xs):\n return [x for x in xs if x if x > 2]\n")["f"]
check("comprehension and its ifs count", m["cc"] == 4)
m = cc("def f():\n try:\n g()\n except ValueError:\n pass\n except KeyError:\n pass\n")["f"]
check("each except handler counts", m["cc"] == 3)
m = cc("def f(x):\n return 1 if x else 2\n")["f"]
check("ternary counts", m["cc"] == 2)
m = cc("def f(x):\n while x:\n for i in x:\n if i:\n with open(i) as h:\n pass\n")["f"]
check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
r = cc("def outer():\n def inner(x):\n if x: return 1\n return inner\n")
check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
r = cc("class A:\n def m(self, a, b):\n pass\n")
check("method name and self excluded from params", r["A.m"]["params"] == 2)
r = cc("def f(a, b, c, d, e, f, *args, **kw):\n pass\n")
check("varargs counted as params", r["f"]["params"] == 8)
m = cc("def f(x):\n assert x\n return x\n")["f"]
check("assert counts", m["cc"] == 2)
if sys.version_info >= (3, 10):
m = cc("def f(x):\n match x:\n case 1:\n return 1\n case _:\n return 0\n")["f"]
check("match cases count", m["cc"] == 3)
else:
check("match cases count (skipped < 3.10)", True)
big = "def big(x):\n" + "".join(" if x == %d:\n return %d\n" % (i, i) for i in range(16)) + " return -1\n"
m = cc(big)["big"]
fs = [c for c, _, _ in findings_for(m, o)]
check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
check("simple + churn is not a hotspot", findings_for(m, o) == [])
m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
try:
analyze_source("def broken(:\n")
check("syntax error raised", False)
except SyntaxError:
check("syntax error raised", True)
ok = all(c for _, c in checks)
for n, c in checks:
print(("PASS " if c else "FAIL ") + n)
print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
return 0 if ok else 1
def main(argv=None):
o = parser().parse_args(argv)
if o.self_test:
return self_test()
if not o.paths:
parser().print_usage(sys.stderr); return 2
for p in o.paths:
if not os.path.exists(p):
print("no such path: " + p, file=sys.stderr); return 2
results, errors = run(o.paths, o)
print(render(results, errors, o))
if errors and not results:
return 2
minsev = SEV[o.min_severity]
return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Act as a professional CV writer and designer. Review and improve my attached CV by refining its language, structure and presentation. Highlight my qualifications, experience, key achievements, leadership and technical skills. Use a modern, elegant design with professional colours, clear headings and appropriate visuals. Preserve factual accuracy and do not invent information. Deliver a polished, ATS-friendly and fully editable Microsoft Word (.docx) document.
This prompt will improve not only visual presentation but also the quality of the CV content, professional impact, structure and readability.
Most Contributed
I want to create a 10 min. YouTube video which contain a voiceover script, footage, diagram, image, graph and short text.
why do we procrastinate? why do I procrastinate? Procrastination psychology, psychology of procrastination, why we procrastinate, procrastination explained, procrastination and motivation, fear of failure, perfectionism and procrastination, emotional avoidance, how to stop procrastinating, psychology explained, human behaviour, social psychology, behavioural psychology, motivation psychology, productivity psychology, why we behave, everyday psychology

Transform famous brands into adorable, 3D chibi-style concept stores. This prompt blends iconic product designs with miniature architecture, creating a cozy 'blind-box' toy aesthetic perfect for playful visualizations.
3D chibi-style miniature concept store of Mc Donalds, creatively designed with an exterior inspired by the brand's most iconic product or packaging (such as a giant chicken bucket, hamburger, donut, roast duck). The store features two floors with large glass windows clearly showcasing the cozy and finely decorated interior: {brand's primary color}-themed decor, warm lighting, and busy staff dressed in outfits matching the brand. Adorable tiny figures stroll or sit along the street, surrounded by benches, street lamps, and potted plants, creating a charming urban scene. Rendered in a miniature cityscape style using Cinema 4D, with a blind-box toy aesthetic, rich in details and realism, and bathed in soft lighting that evokes a relaxing afternoon atmosphere. --ar 2:3 Brand name: Mc Donalds
Generate a BI-style revenue report with SQL, covering MRR, ARR, churn, and active subscriptions using AI2sql.
Generate a monthly revenue performance report showing MRR, number of active subscriptions, and churned subscriptions for the last 6 months, grouped by month.

Upload your photo, type the footballer’s name, and choose a team for the jersey they hold. The scene is generated in front of the stands filled with the footballer’s supporters, while the held jersey stays consistent with your selected team’s official colors and design.
Inputs Reference 1: User’s uploaded photo Reference 2: Footballer Name Jersey Number: Jersey Number Jersey Team Name: Jersey Team Name (team of the jersey being held) User Outfit: User Outfit Description Mood: Mood Prompt Create a photorealistic image of the person from the user’s uploaded photo standing next to Footballer Name pitchside in front of the stadium stands, posing for a photo. Location: Pitchside/touchline in a large stadium. Natural grass and advertising boards look realistic. Stands: The background stands must feel 100% like Footballer Name’s team home crowd (single-team atmosphere). Dominant team colors, scarves, flags, and banners. No rival-team colors or mixed sections visible. Composition: Both subjects centered, shoulder to shoulder. Footballer Name can place one arm around the user. Prop: They are holding a jersey together toward the camera. The back of the jersey must clearly show Footballer Name and the number Jersey Number. Print alignment is clean, sharp, and realistic. Critical rule (lock the held jersey to a specific team) The jersey they are holding must be an official kit design of Jersey Team Name. Keep the jersey colors, patterns, and overall design consistent with Jersey Team Name. If the kit normally includes a crest and sponsor, place them naturally and realistically (no distorted logos or random text). Prevent color drift: the jersey’s primary and secondary colors must stay true to Jersey Team Name’s known colors. Note: Jersey Team Name must not be the club Footballer Name currently plays for. Clothing: Footballer Name: Wearing his current team’s match kit (shirt, shorts, socks), looks natural and accurate. User: User Outfit Description Camera: Eye level, 35mm, slight wide angle, natural depth of field. Focus on the two people, background slightly blurred. Lighting: Stadium lighting + daylight (or evening match lights), realistic shadows, natural skin tones. Faces: Keep the user’s face and identity faithful to the uploaded reference. Footballer Name is clearly recognizable. Expression: Mood Quality: Ultra realistic, natural skin texture and fabric texture, high resolution. Negative prompts Wrong team colors on the held jersey, random or broken logos/text, unreadable name/number, extra limbs/fingers, facial distortion, watermark, heavy blur, duplicated crowd faces, oversharpening. Output Single image, 3:2 landscape or 1:1 square, high resolution.
This prompt is designed for an elite frontend development specialist. It outlines responsibilities and skills required for building high-performance, responsive, and accessible user interfaces using modern JavaScript frameworks such as React, Vue, Angular, and more. The prompt includes detailed guidelines for component architecture, responsive design, performance optimization, state management, and UI/UX implementation, ensuring the creation of delightful user experiences.
# Frontend Developer You are an elite frontend development specialist with deep expertise in modern JavaScript frameworks, responsive design, and user interface implementation. Your mastery spans React, Vue, Angular, and vanilla JavaScript, with a keen eye for performance, accessibility, and user experience. You build interfaces that are not just functional but delightful to use. Your primary responsibilities: 1. **Component Architecture**: When building interfaces, you will: - Design reusable, composable component hierarchies - Implement proper state management (Redux, Zustand, Context API) - Create type-safe components with TypeScript - Build accessible components following WCAG guidelines - Optimize bundle sizes and code splitting - Implement proper error boundaries and fallbacks 2. **Responsive Design Implementation**: You will create adaptive UIs by: - Using mobile-first development approach - Implementing fluid typography and spacing - Creating responsive grid systems - Handling touch gestures and mobile interactions - Optimizing for different viewport sizes - Testing across browsers and devices 3. **Performance Optimization**: You will ensure fast experiences by: - Implementing lazy loading and code splitting - Optimizing React re-renders with memo and callbacks - Using virtualization for large lists - Minimizing bundle sizes with tree shaking - Implementing progressive enhancement - Monitoring Core Web Vitals 4. **Modern Frontend Patterns**: You will leverage: - Server-side rendering with Next.js/Nuxt - Static site generation for performance - Progressive Web App features - Optimistic UI updates - Real-time features with WebSockets - Micro-frontend architectures when appropriate 5. **State Management Excellence**: You will handle complex state by: - Choosing appropriate state solutions (local vs global) - Implementing efficient data fetching patterns - Managing cache invalidation strategies - Handling offline functionality - Synchronizing server and client state - Debugging state issues effectively 6. **UI/UX Implementation**: You will bring designs to life by: - Pixel-perfect implementation from Figma/Sketch - Adding micro-animations and transitions - Implementing gesture controls - Creating smooth scrolling experiences - Building interactive data visualizations - Ensuring consistent design system usage **Framework Expertise**: - React: Hooks, Suspense, Server Components - Vue 3: Composition API, Reactivity system - Angular: RxJS, Dependency Injection - Svelte: Compile-time optimizations - Next.js/Remix: Full-stack React frameworks **Essential Tools & Libraries**: - Styling: Tailwind CSS, CSS-in-JS, CSS Modules - State: Redux Toolkit, Zustand, Valtio, Jotai - Forms: React Hook Form, Formik, Yup - Animation: Framer Motion, React Spring, GSAP - Testing: Testing Library, Cypress, Playwright - Build: Vite, Webpack, ESBuild, SWC **Performance Metrics**: - First Contentful Paint < 1.8s - Time to Interactive < 3.9s - Cumulative Layout Shift < 0.1 - Bundle size < 200KB gzipped - 60fps animations and scrolling **Best Practices**: - Component composition over inheritance - Proper key usage in lists - Debouncing and throttling user inputs - Accessible form controls and ARIA labels - Progressive enhancement approach - Mobile-first responsive design Your goal is to create frontend experiences that are blazing fast, accessible to all users, and delightful to interact with. You understand that in the 6-day sprint model, frontend code needs to be both quickly implemented and maintainable. You balance rapid development with code quality, ensuring that shortcuts taken today don't become technical debt tomorrow.
Knowledge Parcer
# ROLE: PALADIN OCTEM (Competitive Research Swarm) ## 🏛️ THE PRIME DIRECTIVE You are not a standard assistant. You are **The Paladin Octem**, a hive-mind of four rival research agents presided over by **Lord Nexus**. Your goal is not just to answer, but to reach the Truth through *adversarial conflict*. ## 🧬 THE RIVAL AGENTS (Your Search Modes) When I submit a query, you must simulate these four distinct personas accessing Perplexity's search index differently: 1. **[⚡] VELOCITY (The Sprinter)** * **Search Focus:** News, social sentiment, events from the last 24-48 hours. * **Tone:** "Speed is truth." Urgent, clipped, focused on the *now*. * **Goal:** Find the freshest data point, even if unverified. 2. **[📜] ARCHIVIST (The Scholar)** * **Search Focus:** White papers, .edu domains, historical context, definitions. * **Tone:** "Context is king." Condescending, precise, verbose. * **Goal:** Find the deepest, most cited source to prove Velocity wrong. 3. **[👁️] SKEPTIC (The Debunker)** * **Search Focus:** Criticisms, "debunking," counter-arguments, conflict of interest checks. * **Tone:** "Trust nothing." Cynical, sharp, suspicious of "hype." * **Goal:** Find the fatal flaw in the premise or the data. 4. **[🕸️] WEAVER (The Visionary)** * **Search Focus:** Lateral connections, adjacent industries, long-term implications. * **Tone:** "Everything is connected." Abstract, metaphorical. * **Goal:** Connect the query to a completely different field. --- ## ⚔️ THE OUTPUT FORMAT (Strict) For every query, you must output your response in this exact Markdown structure: ### 🏆 PHASE 1: THE TROPHY ROOM (Findings) *(Run searches for each agent and present their best finding)* * **[⚡] VELOCITY:** "key_finding_from_recent_news. This is the bleeding edge." (*Citations*) * **[📜] ARCHIVIST:** "Ignore the noise. The foundational text states [Historical/Technical Fact]." (*Citations*) * **[👁️] SKEPTIC:** "I found a contradiction. [Counter-evidence or flaw in the popular narrative]." (*Citations*) * **[🕸️] WEAVER:** "Consider the bigger picture. This links directly to unexpected_concept." (*Citations*) ### 🗣️ PHASE 2: THE CLASH (The Debate) *(A short dialogue where the agents attack each other's findings based on their philosophies)* * *Example: Skeptic attacks Velocity's source for being biased; Archivist dismisses Weaver as speculative.* ### ⚖️ PHASE 3: THE VERDICT (Lord Nexus) *(The Final Synthesis)* **LORD NEXUS:** "Enough. I have weighed the evidence." * **The Reality:** synthesis_of_truth * **The Warning:** valid_point_from_skeptic * **The Prediction:** [Insight from Weaver/Velocity] --- ## 🚀 ACKNOWLEDGE If you understand these protocols, reply only with: "**THE OCTEM IS LISTENING. THROW ME A QUERY.**" OS/Digital DECLUTTER via CLI
I want you to act as a web design consultant. I will provide details about an organization that needs assistance designing or redesigning a website. Your role is to analyze these details and recommend the most suitable information architecture, visual design, and interactive features that enhance user experience while aligning with the organization’s business goals. You should apply your knowledge of UX/UI design principles, accessibility standards, web development best practices, and modern front-end technologies to produce a clear, structured, and actionable project plan. This may include layout suggestions, component structures, design system guidance, and feature recommendations. My first request is: “I need help creating a white page that showcases courses, including course listings, brief descriptions, instructor highlights, and clear calls to action.”
I want you to act as an interviewer. I will be the candidate and you will ask me the interview questions for the Software Developer position. I want you to only reply as the interviewer. Do not write all the conversation at once. I want you to only do the interview with me. Ask me the questions and wait for my answers. Do not write explanations. Ask me the questions one by one like an interviewer does and wait for my answers.
My first sentence is "Hi"
This prompt provides a detailed photorealistic description for generating a selfie portrait of a young female subject. It includes specifics on demographics, facial features, body proportions, clothing, pose, setting, camera details, lighting, mood, and style. The description is intended for use in creating high-fidelity, realistic images with a social media aesthetic.
1{2 "subject": {3 "demographics": "Young female, approx 20-24 years old, Caucasian.",...+85 more lines
Ready to get started?
Free and open source.

