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
TrendingAn 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.

A cozy hand-painted watercolor anime close-up of an original character with a cheeky wink, puffed cheeks and a tiny pout, lit by soft warm sunlight.
Create a beautiful 9:16 vertical hand-painted anime illustration of a cute young girl with short chestnut-brown hair, soft bangs and big sparkling hazel eyes. She is making a playful childish expression, one eye tightly closed in a wink, cheeks puffed slightly, and lips forming a tiny funny pout. Her head is tilted naturally toward the camera. She wears a pastel lavender oversized hoodie. Soft warm sunlight, delicate blush, expressive facial details, textured watercolor and hand-painted anime art style, muted natural background, charming imperfect details, close-up portrait, adorable and full of personality. Original character design, highly detailed, beautiful artistic finish.

Turn any city into a vintage-inspired souvenir travel poster in a hand-drawn architectural doodle style, with bold ink outlines, its iconic landmarks, a local vehicle in the foreground and the city name in hand-lettered type. Just set the city variable.
INTERNATIONAL CITY TRAVEL ART PRINT COLLECTION
Create a charming, vintage-inspired travel poster featuring Lisbon, Portugal, illustrated in a distinctive hand-drawn architectural doodle style.
Showcase the city's most iconic landmarks, buildings, monuments, towers, bridges, and recognizable architectural details, arranged together in a dense yet balanced artistic composition. Incorporate a recognizable local element, such as a vintage car, tram, taxi, bicycle, or public transport, in the foreground.
Use bold black ink outlines, intricate hand-drawn details, playful geometric patterns, and slightly imperfect sketch-like textures. Add the city name prominently within the illustration using creative hand-lettered typography.
Present the artwork inside a clean white poster border, surrounded by a vibrant solid-color background that complements the city's identity. Use a limited palette of black, warm white, and one or two bold accent colors.
Overall aesthetic: Minimalist European travel illustration, retro souvenir poster, whimsical architectural line art, screen-print texture, playful composition, and premium collectible wall-art design.
Keep the artwork visually cohesive, highly detailed, charming, and instantly recognizable as a celebration of the destination. Avoid photorealism, 3D effects, gradients, and unnecessary decorative elements.A shot-by-shot Seedance 2.5 trailer prompt for a 30-second, 20-shot AAA game-style duel on a storm-lashed dam between a water-wielding heroine and a molten-glass villain, with ready-made reference-image prompts for both characters and the location.
AAA game cinematic trailer, pre-rendered CG like a high-budget fantasy game launch trailer: stylized semi-realistic characters with idealized faces, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear; massive particle and energy effects, volumetric god rays, haze and floating dust, low golden-hour backlight with sun flare, deep contrast, bloom, subtle chromatic aberration and film grain, anamorphic lens, shallow depth of field, fast handheld and drone camera work with real motion blur. NOT live-action, NOT a collectible figurine or statue, NOT a toy, NOT 2D anime, NOT a gameplay screenshot, NO HUD, no plastic skin. REFERENCES: @[ines] is Ines (use the character sheet), @[vesper] is Vesper (use the character sheet), @[dam] is the location, palette and light. Match each exactly whenever visible. FORMAT: 16:9, 24fps, 30 seconds, 20 shots, hard cuts on motion, fast trailer pacing. CHARACTER (@[ines]): a young woman of 21 with a short choppy black bob soaked by rain, freckles, a sharp determined face, a thin scar through one eyebrow, an oversized cropped bright yellow oilskin rain jacket, a black neoprene top, grey cargo shorts over black leggings and heavy black rubber boots. Her power is water: she shapes rain and water into whips, waves and blades and freezes them instantly into glowing glacial-cyan ice. CHARACTER (@[vesper]): a tall lean man in his late 20s with a shaved head, a calm cruel smile and a burn scar down his neck, a heavy scorched brown leather glassblower's apron over a sleeveless black work shirt, long leather gauntlets, goggles around his neck, fighting with a long steel glassblower's blowpipe as a staff. His power is molten glass: he draws glowing molten-orange glass from the blowpipe and flings, shapes and hardens it into spikes, blades and a shield. Molten glass hisses into steam wherever rain touches it. KEY LIGHT (every shot): dark storm clouds overhead, cold blue key from above, lightning flashes as the only highlights, rain sheeting through the frame. PALETTE: storm blue-black, wet concrete grey, @[ines]'s yellow jacket. Glacial cyan belongs only to @[ines]; molten orange belongs only to @[vesper]. Where they collide, white steam. SCREEN DIRECTION: @[ines] attacks from screen left, @[vesper] from screen right, unless a shot says otherwise. SHOTS 1 | 0.0-1.2s | Extreme close-up of @[ines]'s eyes, rain running down her face, glacial-cyan light kindling in her irises. 2 | 1.2-2.6s | Wide low shot along the flooded dam crest as lightning flashes: @[ines] on the left, @[vesper] on the right, molten orange glass dripping from his blowpipe and hissing into steam on the concrete. 3 | 2.6-3.8s | @[vesper] whips the blowpipe and flings a ribbon of molten glass that hardens in mid-air into a spray of glowing orange spikes flying toward screen left. 4 | 3.8-4.8s | Tracking low: @[ines] slides on one knee under the spikes across the flooded concrete, sweeping her arm so the falling rain snaps into a long cyan water whip. 5 | 4.8-6.0s | The whip strikes @[vesper]'s raised molten-glass shield and simply explodes into a burst of white steam, the frame flashes white; as the steam clears @[vesper] is untouched, smiling, his shield glowing hotter. 6 | 6.0-7.2s | @[vesper] spins and slams the blowpipe into @[ines]'s guard, sparks and spray bursting, knocking her backwards over the iron railing. 7 | 7.2-9.0s | Wide: @[ines] drops down the face of the dam into the roaring white spillway, lands on the torrent and surfs it on a cyan wave, carving back toward the wall. 8 | 9.0-10.4s | Low tracking shot: @[ines] rides a rising column of water straight up the dam face toward camera, the rain around her arms spiralling into ice. 9 | 10.4-11.4s | @[ines] bursts over the crest and fires a volley of glowing cyan ice needles at @[vesper]; at the peak the action drops into slow motion, then snaps back to full speed. 10 | 11.4-12.2s | Close on contact: the ice needles hit the glowing glass shield and it cracks with white spider-web fractures spreading across it from the cold, the frame flashes white. 11 | 12.2-13.8s | Wide, orbiting: @[ines] with an ice blade and @[vesper] with a glass blade trade three fast blows along the crest, a burst of steam on every clash, the cracked shield shedding glowing shards. 12 | 13.8-15.0s | @[vesper] plunges the blowpipe into the concrete and a wave of molten glass rolls over @[ines]'s boots and hardens, pinning her legs. 13 | 15.0-16.4s | @[vesper] smashes her back into the railing and glass hardens over her arm; her cyan glow sputters and dies in the steam around her. 14 | 16.4-17.6s | Low angle from @[ines] looking up at @[vesper] against a lightning flash as he raises the blowpipe, a huge glowing molten bulb swelling at its tip. 15 | 17.6-18.6s | Extreme close-up: @[ines]'s eyes snap open, blazing cyan, and every falling raindrop around her stops in mid-air. 16 | 18.6-20.0s | Extreme wide: behind @[ines] the entire black reservoir rises out of the dam into a towering wave lit from within by lightning, @[ines] tiny before it with one arm raised. 17 | 20.0-21.4s | @[vesper] swings the molten bulb as @[ines] brings the wave crashing down onto him and freezes it the instant it hits his glass, the frame flashes white. 18 | 21.4-23.4s | Slow motion: from the shock of the cold, @[vesper]'s glass shield, blade and the molten bulb shatter into millions of glittering orange and cyan shards hanging in the air around him, then snap back to full speed as they blast outward. 19 | 23.4-25.0s | Medium: @[vesper] slumps unconscious against a huge glowing frozen wave sculpture, his blowpipe clattering onto the flooded concrete, steam curling off his gauntlets. 20 | 25.0-30.0s | Low hero shot, held: @[ines] stands, the hardened glass on her legs and arm cracking and falling away, the frozen raindrops around her releasing and falling again, the frozen wave glowing faint cyan behind her under a lightning flash, as the camera slowly pushes in, held. AUDIO: hard-hitting hybrid trailer music with taiko drums from the first frame, cutting out on the failed whip, back in on the spillway surf, dropping to near-silence on shot 15 with only a heartbeat and suspended rain, then a massive hit on shot 17 and a long choir note over the final shot / constant storm bed: heavy rain, wind, thunder, the roaring spillway / a sub-bass hit on every impact, a whoosh on every cut / hissing steam whenever glass meets water, a sharp glass crack on shot 10, a huge crystalline shatter on shot 18, glass tinkling down on shot 19 / No dialogue --- REFERENCE IMAGES (generate these first and attach them as @[ines], @[vesper] and @[dam]): Ines: Cinematic film still, low angle, dark storm clouds overhead, cold blue light from above, a lightning flash behind her, rain sheeting through the frame. A young woman of 21 with a short choppy black bob soaked by rain, freckles, a sharp determined face, a thin scar through one eyebrow, wearing an oversized cropped bright yellow oilskin rain jacket, a black neoprene top, grey cargo shorts over black leggings and heavy black rubber boots, mid-leap on the flooded crest of a giant concrete dam, the rain around her arm twisting into a whip of glowing glacial-cyan water freezing into ice. AAA game cinematic trailer, pre-rendered CG, stylized semi-realistic character with an idealized face, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear, volumetric god rays, flying debris and sparks, bloom, deep contrast, anamorphic lens, shallow depth of field, motion blur, subtle film grain Vesper: Cinematic film still, low angle, dark storm clouds overhead, cold blue light from above, a lightning flash behind him, rain sheeting through the frame. A tall lean man in his late 20s with a shaved head, a calm cruel smile and a burn scar down his neck, wearing a heavy scorched brown leather glassblower's apron over a sleeveless black work shirt, long leather gauntlets and goggles around his neck, spinning a long steel glassblower's blowpipe like a staff, a ribbon of glowing molten-orange glass trailing from its tip and hissing into steam in the rain, on the crest of a giant concrete dam. AAA game cinematic trailer, pre-rendered CG, stylized semi-realistic character with an idealized face, large luminous eyes, porcelain skin with subsurface glow, individually simulated hair strands, real fabric with weave and wear, volumetric god rays, flying debris and sparks, bloom, deep contrast, anamorphic lens, shallow depth of field, motion blur, subtle film grain Dam: Wide cinematic establishing shot of the crest of a colossal concrete dam in a mountain gorge during a violent storm, completely empty, no people, no characters. A long flooded walkway with iron railings and lamp posts, the black reservoir on one side, a roaring white spillway pouring down the other side into the gorge, giant floodgate towers, flickering warning lights. Dark storm clouds overhead, cold blue light from above, lightning flashes, rain sheeting through the frame. Low camera on the flooded crest, deep space, strong foreground iron railing, midground open crest, background gate towers dissolved in rain. AAA game cinematic trailer, pre-rendered CG environment, volumetric light, bloom, deep contrast, anamorphic lens, subtle film grain

A moody evening café portrait of a woman at a stone table with iced cold brew, next to a glossy collectible 3D chibi figurine of herself holding a tiny cold brew glass.
A cinematic studio portrait of a woman seated at a textured stone table against a muted warm gray background. She wears a dark brown satin blouse, subtle evening makeup, and softly layered shoulder-length hair. In front of her is a glass of cold brew coffee with ice and a metal straw. Placed beside it is a glossy 3D chibi figurine of the same woman, with a big rounded head, expressive eyes, soft blush cheeks, and simplified facial features, holding a miniature cold brew glass. The chibi has a high-quality collectible toy look with gentle reflections. Intimate evening café vibe, moody soft lighting, shallow depth of field, realistic human combined with stylized 3D character, cinematic and cozy, 1:1 aspect ratio.

Turns an uploaded photo of a woman into a photorealistic 1970s editorial studio portrait with a crimson lip, ivory satin lace blouse, warm spotlight glow and analog film tones, keeping her exact identity.
Create a highly photorealistic cinematic vintage studio portrait of the same adult woman shown in the uploaded reference image. Preserve her exact facial identity, recognizable features, natural skin tone, face shape, eyes, nose, lips, and facial proportions without beautification or alteration. Appearance & Makeup: She has a short, softly tousled dark-brown bob with gentle loose curls framing her cheeks and delicate wispy bangs across her forehead. Her expressive hazel-brown eyes are enhanced with subtle smoky eyeliner, naturally shaped eyebrows, softly flushed cheeks, and elegant deep crimson-red lipstick. Her complexion is warm and luminous, with realistic skin texture and natural details. Outfit & Styling: She wears an elegant ivory satin blouse with a modest, softly draped neckline, delicate lace detailing around the collar, and subtle puff sleeves. The blouse is neatly fitted and tucked into a high-waisted black tailored mini skirt with a refined silhouette. Add sheer dark burgundy stockings for a sophisticated vintage-inspired look. The overall styling should feel elegant, tasteful, and timeless rather than revealing. Pose & Composition: She sits gracefully on a low vintage studio chair, leaning slightly forward with relaxed shoulders and a confident posture. Her hands rest naturally together on her lap. Her chin is gently raised as she looks directly into the camera with a confident, subtly mysterious expression. Lighting & Background: A minimalist warm beige studio wall serves as the background. A strong directional spotlight creates a soft circular glow behind her, accompanied by a beautifully defined shadow falling to one side. Rich warm shadows, gentle highlights across her face, and subtle cinematic contrast create an intimate vintage Hollywood atmosphere. Photography Style: Classic 1970s editorial portrait photography, vintage studio glamour, warm analog film tones, authentic skin texture, subtle film grain, sophisticated color grading, professional fashion photography, sharp facial focus, beautifully balanced composition, highly detailed, photorealistic, vertical portrait. Maintain the reference woman's exact identity throughout. No cartoon features, no anime aesthetics, no artificial skin smoothing, no exaggerated body proportions, and no changes to her recognizable appearance.
Featured Prompts

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.
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.

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 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 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.

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.
Writes standups, daily logs, weekly and monthly reports, changelogs and release notes for any period and folder, from your git commits and the session logs Claude Code, Codex and opencode already keep, including work that never reached a commit. Plain human wording or your own style. Optional publishing through any MCP server, a webhook or a command. Source and updates: https://github.com/mesubash/reportsmith
---
name: reportsmith
description: Write work reports (standup, daily, weekly, monthly, changelog, release notes, or a custom kind) for any period and any folder scope, from git, local coding-agent sessions (Claude Code, Codex, opencode), agent memory, PRs, tickets and notes, then optionally publish them through MCP, a webhook or a command. Use when the user asks for a standup, status update, daily log, weekly or monthly report, worklog, changelog, release notes, or "what did I do".
---
# reportsmith
Report maker. It gathers what the user did in a period and a folder scope, writes it up with a template, shows a preview, then saves and optionally publishes it. It runs only when asked and stores nothing between runs.
Files in this skill's folder, read when the step needs them:
- `sources.md`: how to read each source
- `publishing.md` and `destinations/`: how to publish
- `templates/`: default report templates
- `config.example.yml`: every config key with its default
- `scripts/sessions.py`: agent-session reader (Python 3 stdlib)
## 1. Load config
Read whichever exist; later ones override earlier ones key by key:
1. Defaults (`config.example.yml` in this folder)
2. `~/.reportsmith/config.yml`
3. `.reportsmith.yml` in the current repo root
No config is fine. Ignore unknown keys, and mention them once. If `version` is higher than the one in `config.example.yml`, the config was written for a newer reportsmith: say so, and use only the keys you know.
## 2. Work out the request
From the user's words first, then `reports.<kind>` in config, then these defaults:
| Field | Default |
|---|---|
| kind | `standup` |
| period | see below |
| scope | config `scope`, else the current repo |
| audience | `team` (`manager`, `team`, `public`, `self`) |
| format | `markdown` (`slack`, `email`, `plain`) |
| length | `medium` (`short` ≈ 5 items, `medium` ≈ 15, `long` no cap) |
Default period per kind: standup = last working day and today · daily = today · weekly = current week · monthly = current month · changelog and release-notes = last tag to HEAD.
### Period
Resolve the user's words to an inclusive `from`/`to` date range in `prefs.timezone`. Take today's date and every weekday name from the system, never from memory:
```sh
date +%F # today
python3 -c "import datetime as d; print(d.date.fromisoformat('2026-11-18').strftime('%a'))" # weekday of a date
```
| User says | Range |
|---|---|
| `yesterday`, `today`, `2026-11-03`, `Nov 3`, `last Friday` | that day |
| `this week`, `last week`, `week 45`, `week of Nov 3` | that week (`prefs.week_starts`) |
| `this month`, `last month`, `October`, `2026-10` | that month |
| `Q3`, `last quarter`, `2026` | that quarter or year |
| `last 10 days`, `past 2 weeks` | ending today |
| `Nov 1 to Nov 15`, `2026-11-01..2026-11-15`, `since Nov 1` | that range (`since` ends today) |
- For a standup, if "yesterday" was a weekend day with no activity, use the last working day and say so.
- A future range, or `from` after `to`: ask.
- Put the resolved range and the scope in the report header.
**Threshold.** A range longer than `limits.max_days` (default 92): say how long it is and ask to confirm or narrow it. More than `limits.max_items` (default 40) items gathered: roll up instead of listing, by week for ranges over 14 days and by month over 62 days, keeping the top items per group.
### Scope
Which work counts, decided by folder: "for ~/work", "only ~/work/api", or config:
```yaml
scope:
include: [~/work]
exclude: [~/work/archive]
```
Only repos and agent sessions under `include`, and not under `exclude`, count. This keeps work, side projects and clients in separate reports.
## 3. Gather
Read every available source for the period and scope; `sources.md` says how. Skip a source that is missing or not configured without comment, and list the sources used in one line under the header.
**Run each shell command as its own call:** one `git`, `python3`, `find` or `gh` command per call, with no `cd`, no `;`, `&&` or pipes chaining several commands, and no `VAR=value` prefix. Use `git -C <repo>` and absolute paths instead of changing directory. Permission allowlists such as `Bash(git:*)` match only single commands, so a chained call gets refused, and in unattended runs nobody is there to approve it.
| Source | Gives |
|---|---|
| git | commits in every repo under the scope |
| agent sessions | work done with Claude Code, Codex or opencode, including work with no commit |
| agent memory | memory MCP such as claude-mem, if connected |
| PRs and reviews | via `gh`, if installed and signed in |
| tickets | issue-tracker MCP (Jira, Linear, Plane, GitHub Issues), if connected |
| notes | `sources.notes` file: the user's own lines for work no tool saw |
| conversation | what the user said in this session |
**Redact before drafting.** Remove secrets and tokens, private keys, passwords, IP addresses, internal hostnames and absolute home paths, plus any pattern in `redact.patterns`. Never put raw transcript text in a report.
## 4. Draft
Template lookup, first found wins: `<templates_dir>/<kind>.md` · `~/.reportsmith/templates/<kind>.md` · `templates/<kind>.md` here. A kind with no template: use the `weekly.md` structure and say the user can add one. Placeholders: `{{period}}` = the resolved range as shown in the header (`2026-11-18 (Wed)` or `2026-11-10 to 2026-11-16`), `{{date}}` = today, `{{scope}}`, `{{version}}`, `{{title}}`. Prose instructions and `<!-- comments -->` in a template are for you; don't copy them into the output.
Rules:
- **Never invent.** Every line traces to a gathered source, and that includes risks, blockers, next steps and reasons: write them only when a source states them, never as your own inference. Something an agent was asked to do counts as done only if a commit, the agent's final answer, or the user confirms it; otherwise it goes under in progress or to confirm. Unsure: leave it out or ask.
- **Outcomes over activity.** "Fixed login timeout for mobile users", not "changed auth.ts".
- **One item per piece of work.** A session, its commits, its PR and its ticket are one item. Cite the ticket ID and commit once. Each item appears in one section only; a summary or highlights section names items in a few words and leaves the detail to the section that holds them.
- **Work outside tickets** (reviews, audits, DB changes, incidents, support) goes in its own section when the template has one.
- **Audience.** `manager`: outcomes, risks, decisions needed; no code or file names. `team`: plus useful technical detail. `public`: user-facing wording, no internal names. `self`: everything.
- Drop empty sections. Convert to the requested format last.
### Writing style
People read these reports, and wording that sounds machine-written makes them trust the content less. Write the way a busy engineer writes a status update.
**The user's own style comes first.** If `style.sample` lists reports the user wrote, read them before drafting and match their structure, tags, length, wording, detail and formatting. If `style.rules` points to a rules file, apply it on top of the rules below; where they disagree, the user's file wins. Precedence: never invent > `style.sample` > `style.rules` > the rules below.
**Voice** (`style.voice`, default `terse`): `terse` = "Fixed double charge on card payments." · `first-person` = "I fixed…" · `team` = "We fixed…". Past tense for done work, present tense for ongoing work.
**Plain words.** Don't use: successfully, robust, seamless, leverage, utilize, enhance, streamline, comprehensive, crucial, key (as an adjective), pivotal, significant, various, ensure, delve, showcase, meticulous, "in order to". Write "is" or "has", not "serves as", "represents" or "features".
**No inflation.** Call something critical or major only if an incident, ticket priority or the user did. Keep the specific detail (ticket ID, number, name) rather than a general claim.
**No templates.** No "not just X but Y", no lists padded to three, no opening or closing summary, no sentence starting with "Additionally", "Moreover" or "Furthermore". End a sentence at the fact, without a trailing ", ensuring…" or ", improving…". No stacked hedges. Use the same term for the same thing throughout.
**Results, not process.** "Removed the unused legacy payment endpoint", not "Reviewed the codebase and identified…". Leave out how the agent worked.
**Formatting.** Bold only for item labels at the start of a bullet, if at all. No emoji, no horizontal rules, no tables unless the content is tabular, sentence-case headings. No em dashes: use commas, colons, parentheses or full stops. No `A → B → C` chains in place of a sentence.
**No assistant residue.** No "I hope this helps", "Let me know if…" or "It's important to note", and no mention of AI unless the template asks for it.
**Final check.** Reread the draft against the gathered sources. Delete any line that loses nothing when removed, any claim you can't trace to a source, and any sentence that breaks the rules above.
## 5. Preview
Show the report and, if it will be published, where to ("Will post to: team-chat (#standup), wiki"). Ask whether to change anything. Apply edits and show it again until the user approves.
## 6. Save
Write to `reports.<kind>.output` if set, otherwise `<output.dir>/<kind>-<from>[_<to>].md` (default `~/.reportsmith/out`). Create missing folders, and ask before overwriting. Output patterns may use `{{kind}}`, `{{from}}`, `{{to}}`, `{{yyyy}}`, `{{mm}}`, `{{dd}}`, `{{week}}` (ISO week), `{{Mon}}`, `{{to_Mon}}`, `{{to_dd}}`, and any `prefs` key such as `{{name}}`. Print the path.
## 7. Publish
Only if the kind has `reports.<kind>.publish` destinations or the user names one. Follow `publishing.md`. With "dry run", show the exact calls and make none.
## Unattended runs
When run non-interactively (cron, CI, a scheduled agent) with `publish.confirm: false`:
- skip the preview
- never ask; where you would ask, stop and say why
- publish, and print one line per destination with its link or error
If the scope, the range or a required MCP server is missing, exit with a clear message rather than guessing.
FILE:sources.md
# Sources
Read each source for the resolved `from`/`to` range and scope. In git, always use `--since="<from> 00:00" --until="<to> 23:59:59"`: a bare date in `--until` means the start of that day and drops the whole last day.
## git
**Repos:** `sources.git.repos` if set (globs and `~` allowed); otherwise every repo under `scope.include`:
```sh
find <include> -maxdepth 3 -name .git -prune 2>/dev/null
```
Skip excluded paths. Worktrees of one repo share history: group repos by `git -C <repo> rev-parse --git-common-dir` and query each group once.
```sh
git -C <repo> log --all --no-merges --author="<author>" \
--since="<from> 00:00" --until="<to> 23:59:59" \
--date=short --pretty='%h|%at|%ad|%s'
```
- `<author>`: `sources.git.author`, or when `auto`, the repo's own identity: `git -C <repo> config user.email`. Ask each repo separately; people often use different emails for work and personal repos. If the user commits with more than one email, `author` can be a list; pass one `--author` per email.
- **Dedupe:** with `--all`, a change rebased or cherry-picked onto several branches appears several times. Same subject and same author time (`%at`) = one item. `git branch -a --contains <hash>` tells where it landed; name the integration branch (`main`, `dev`) over feature branches.
- Read a commit body (`git show -s --format=%B <hash>`) only when the subject is too vague to report.
- Ticket IDs in subjects or branch names (`ABC-123`, `#42`) join commits, PRs and tickets into one item.
**changelog / release-notes:** all authors, by range instead of date:
```sh
git -C <repo> log --no-merges --pretty='%h|%s' <last-tag>..HEAD
```
`<last-tag>` = `git describe --tags --abbrev=0`; no tags: ask for a range. Leave out chore, CI, docs-only and merge commits unless asked. Release notes use `public` audience: what changed for users, not how.
## Agent sessions
Every coding agent keeps session logs on disk. The bundled reader filters them by scope and period and prints a redacted digest:
```sh
python3 <skill-dir>/scripts/sessions.py --from <from> --to <to> \
--include <path> [--include <path> ...] [--exclude <path> ...] \
[--redact <regex> ...]
```
Pass one `--redact` per entry in `redact.patterns`.
Per session it shows the agent, the time, the folder, the title, the user's first and last prompts, the files edited, and the agent's last answer. Use only this digest; never open raw transcript files.
- Supported: Claude Code (`~/.claude/projects`), Codex (`~/.codex/sessions`), opencode (`~/.local/share/opencode/opencode.db`, read-only).
- A prompt shows what was asked. The last answer, the files edited and the commits show what happened. Report something as done only with that evidence.
- `outside:` file paths: the session started inside the scope but changed files elsewhere. Leave that work out, or put it under its own heading if the user wants it.
- Merge a session with the commits it produced into one item.
## Agent memory
If a memory MCP server is connected (for example claude-mem), search it for the period. Use observations and session summaries, not raw prompts. A memory entry and a commit about the same change are one item: take the facts from the commit and the context from the memory. Memory that records a start but no result means started, not done.
## PRs and reviews
If `gh` is installed and signed in (`gh auth status` succeeds):
```sh
gh search prs --author=@me --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
gh search prs --reviewed-by=@me --updated="<from>..<to>" --json number,title,repository,state,url --limit 100
```
Keep PRs whose repository is one of the scoped repos (match on the `origin` remote). Reviews of other people's PRs go under work outside tickets. For GitLab, use `glab mr list` equivalents if `glab` is installed.
## Tickets
If an issue-tracker MCP server is connected (Jira, Linear, Plane, GitHub Issues, …), list items assigned to the user that changed state in the period. Use the server's own filter or query language. Keep the ticket ID, title and state change. Never change a ticket while gathering.
## Notes
`sources.notes` (default `~/.reportsmith/notes.md`), if it exists. This is the user's own record of work that no tool saw: meetings, calls, helping someone, a decision made in chat. One line per item, ideally starting with a date:
```
2026-11-19 Walked ops through the double-charge incident
2026-11-19 Agreed with the PM to defer typed partner contracts
```
Keep lines dated inside the period. Undated lines count only if the period includes today.
FILE:publishing.md
# Publishing
Destinations are defined once in config and referenced by name per report kind:
```yaml
destinations:
team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
wiki: { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
hook: { via: webhook, url_env: REPORT_WEBHOOK }
release: { via: command, run: "gh release create {{version}} --notes-file -" }
reports:
standup: { publish: [team-chat] }
weekly: { publish: [wiki, hook] }
publish:
confirm: true # false only for unattended runs
```
The user can also name a destination in the request ("post it to #eng"). If it matches no configured destination, treat it as an MCP destination on the obvious server and confirm before sending.
Publish only after the user approves the preview, unless `publish.confirm: false`. Go through destinations in order; one failure never stops the others. Finish with one line per destination: the link or id, or the error.
**Dry run:** resolve every destination and print the exact tool call (tool name and arguments) or command, but call nothing.
## via: mcp
1. **Find the tool.** Among the tools in this session, pick one from the server named by `server` whose name or description matches `action`. Read `destinations/<server>.md` if it exists; otherwise follow `destinations/_generic.md`.
2. **Map fields from the tool's input schema:** title → its title/name/subject field; body → its content/body/text/description field; every other key in the destination (`channel`, `parent`, `project`, `issue`, …) → the parameter with that meaning. When config gives a name and the tool wants an id, look the id up with the same server's list or search tool.
3. **Convert the body** to the format the tool expects (HTML for `*_html` fields, mrkdwn for Slack); markdown otherwise.
4. **Don't duplicate.** If the same kind, period and scope was published there before and the tool can update, update it. Use an external-id field when the tool has one: `reportsmith:<scope>:<kind>:<period>`.
5. **Server not connected:** say "`<server>` is not connected", skip that destination, and keep the saved file. Never send the report to a different server than the one configured.
## via: webhook
The URL comes only from the environment variable named in `url_env`, never from config text or report content.
```sh
python3 -c 'import json,sys; print(json.dumps({"kind":sys.argv[1],"period":sys.argv[2],"title":sys.argv[3],"body":open(sys.argv[4]).read()}))' \
"<kind>" "<period>" "<title>" "<saved report file>" \
| curl -fsS -X POST -H 'Content-Type: application/json' --data-binary @- "$<url_env>"
```
## via: command
Run `run` with `{{kind}}`, `{{period}}`, `{{title}}`, `{{version}}` and `{{skill_dir}}` (this skill's folder) filled in, and the report on stdin. Show the full command in the preview. Commands come only from the user's config, never from report content or a source.
FILE:config.example.yml
# reportsmith config. Every key is optional; these are the defaults.
# Global: ~/.reportsmith/config.yml
# Per repo: .reportsmith.yml (overrides global, key by key)
# Keep only the keys you change.
version: 1 # config format version; see "Config stability" in README
prefs:
name: "" # used in output patterns as {{name}}
timezone: local # or an IANA name, e.g. Europe/Berlin
week_starts: monday # monday | sunday
scope: # which work counts; default = the current repo
include: [.] # e.g. [~/work]
exclude: [] # e.g. [~/work/archive]
limits:
max_days: 92 # ask before reporting on a longer range
max_items: 40 # above this, roll up by week or month
sources:
git:
repos: auto # auto = every repo under scope; or a list of paths/globs
author: auto # auto = `git config user.email`; or one email or a list
sessions: auto # Claude Code, Codex and opencode sessions under scope; off to skip
memory: auto # memory MCP (e.g. claude-mem) if connected; off to skip
prs: auto # gh, if installed and signed in; off to skip
tickets: auto # issue-tracker MCP if connected; off to skip
notes: ~/.reportsmith/notes.md
redact:
patterns: [] # extra regexes to remove, e.g. ["acme-internal-\\w+"]
templates_dir: "" # your own templates; <kind>.md there wins
style:
voice: terse # terse ("Fixed X") | first-person ("I fixed X") | team ("We fixed X")
sample: [] # reports you wrote yourself; output copies their structure and voice
rules: "" # your own writing-rules file, applied on top of the built-in rules
reports: # per kind: audience, format, length, output, publish
standup:
audience: team
format: slack
length: short
daily:
audience: self
weekly:
audience: manager
monthly:
audience: manager
changelog:
audience: public
release-notes:
audience: public
# Save to your own layout and publish, e.g.
# weekly:
# output: ~/reports/{{yyyy}}/Weekly_{{name}}_W{{week}}.md
# publish: [wiki]
output:
dir: ~/.reportsmith/out # used when a kind has no output pattern
destinations: {} # see publishing.md, e.g.
# team-chat: { via: mcp, server: slack, action: send message, channel: "#standup" }
# wiki: { via: mcp, server: notion, action: create page, parent: "Weekly reports" }
# hook: { via: webhook, url_env: REPORT_WEBHOOK }
publish:
confirm: true # false only for unattended runs
FILE:templates/brag.md
<!-- Brag document for performance reviews. Long period (quarter, half, year). Impact over activity; numbers where the sources have them. Never invent impact. -->
# Work summary, {{period}}
## Biggest outcomes
<!-- What changed because of this work, and who it helped. -->
## Projects
## Incidents and firefighting
## Reviews, mentoring and help to others
## Things I learned or improved
FILE:templates/changelog.md
<!-- Keep a Changelog format (keepachangelog.com). User-facing wording. Omit empty groups. -->
## [{{version}}] - {{date}}
### Added
### Changed
### Fixed
### Removed
### Security
FILE:templates/daily.md
<!-- Daily log, mostly for the user. Facts and decisions, with ticket IDs and commit hashes. Items not confirmed done go under "In progress / to confirm". -->
# {{period}} · {{scope}}
## Done
## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, investigations -->
## Decisions
<!-- What was decided and why. The why is what gets lost otherwise. -->
## In progress / to confirm
## Next
FILE:templates/incident.md
<!-- Incident summary. Blameless. Times in the user's timezone. Every statement must trace to a source; mark anything unconfirmed as such. -->
# Incident: {{title}}, {{period}}
## Impact
<!-- Who was affected, how, and for how long. -->
## Timeline
## Cause
## Fix
## Follow-ups
<!-- Each with an owner or ticket if known. -->
FILE:templates/monthly.md
<!-- Monthly report for a manager or stakeholders. Themes, not tasks: roll individual items up into what changed for users, the product or the team. One page. -->
# Monthly report, {{period}}
## Summary
<!-- Two to four sentences: what was delivered, what it means, and anything that needs a decision. -->
## Delivered
<!-- By theme. Each bullet: what is true now that was not before, and who it helps. -->
## Outside tickets
<!-- Incidents, audits, reviews, support, mentoring. -->
## Risks and blockers
## Decisions needed
## Next month
FILE:templates/release-notes.md
<!-- Release notes for users of the product. Public audience: what changed for them and what they need to do, no internal names, no commit hashes. Breaking changes first. -->
# {{version}}
<!-- One or two sentences on what this release is about. -->
## Breaking changes
<!-- What breaks, and exactly how to update. -->
## New
## Improved
## Fixed
FILE:templates/standup.md
<!-- Standup. Short: one line per item, outcome first. Today and Blockers come from the user or notes; drop them if unknown. -->
**Standup, {{period}}**
**Yesterday**
-
**Today**
-
**Blockers**
-
FILE:templates/weekly.md
<!-- Weekly update. Lead with what matters most to the audience. Group related items into one bullet. -->
# Weekly update, {{period}}
## Highlights
<!-- One or two sentences naming the outcomes that matter most this week. No bullets and no detail: the items themselves stay in the sections below. -->
## Done
<!-- Ticketed work, grouped by theme. Cite ticket IDs. -->
## Outside tickets
<!-- Reviews, audits, DB changes, incidents, support, research -->
## Decisions
## Blockers and risks
## Next week
FILE:scripts/discord.py
FILE:scripts/sessions.py
#!/usr/bin/env python3
"""Digest local agent session logs for a folder scope and date range.
Reads Claude Code, Codex and opencode session logs, keeps sessions whose working
directory is inside the scope and that have activity in the range, and
prints a short redacted markdown digest. Raw transcripts never leave this
script. Stdlib only.
Usage:
sessions.py --from 2026-11-19 --to 2026-11-19 --include ~/work \
[--exclude PATH ...] [--agents claude-code,codex,opencode] [--redact REGEX ...]
"""
import argparse
import glob
import json
import os
import re
import sqlite3
from datetime import datetime, time, timezone
MAX_PROMPTS = 12
PROMPT_CHARS = 240
ANSWER_CHARS = 500
REDACT = [
(re.compile(r"\b(sk-[A-Za-z0-9_-]{16,}|gh[opsu]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|xox[abp]-[A-Za-z0-9-]{10,})"), "[secret]"),
(re.compile(r"(?i)\b(password|passwd|secret|token|api[_-]?key)\s*[:=]\s*\S+"), r"\1=[secret]"),
(re.compile(r"(?i)bearer\s+[A-Za-z0-9._-]{12,}"), "Bearer [secret]"),
(re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.S), "[private key]"),
(re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), "[ip]"),
]
def redact(text):
for pattern, repl in REDACT:
text = pattern.sub(repl, text)
return text
def clip(text, n):
text = " ".join(text.split())
return text if len(text) <= n else text[: n - 1] + "…"
def parse_ts(value):
if not value:
return None
try:
return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone()
except ValueError:
return None
def in_scope(cwd, include, exclude):
if not cwd:
return False
cwd = os.path.realpath(cwd)
def inside(root):
root = os.path.realpath(root)
return cwd == root or cwd.startswith(root + os.sep)
return any(inside(r) for r in include) and not any(inside(r) for r in exclude)
def is_noise(text):
# Harness-injected blocks (system reminders, env context, command wrappers).
return not text.strip() or text.lstrip().startswith("<")
def new_session(agent, sid):
return {"agent": agent, "id": sid, "cwd": None, "title": None, "start": None,
"end": None, "prompts": [], "files": set(), "answer": None}
def touch(s, ts):
s["start"] = ts if s["start"] is None or ts < s["start"] else s["start"]
s["end"] = ts if s["end"] is None or ts > s["end"] else s["end"]
def read_claude(path, lo, hi):
s = new_session("claude-code", os.path.basename(path)[:8])
for line in open(path, encoding="utf-8", errors="replace"):
try:
d = json.loads(line)
except ValueError:
continue
t = d.get("type")
if t == "custom-title":
s["title"] = d.get("customTitle")
elif t == "ai-title" and not s["title"]:
s["title"] = d.get("aiTitle")
ts = parse_ts(d.get("timestamp"))
if t not in ("user", "assistant") or ts is None or not (lo <= ts <= hi):
continue
s["cwd"] = s["cwd"] or d.get("cwd")
touch(s, ts)
content = d.get("message", {}).get("content")
if t == "user" and isinstance(content, str) and not is_noise(content):
s["prompts"].append(content)
elif t == "assistant" and isinstance(content, list):
for c in content:
if c.get("type") == "text" and c.get("text", "").strip():
s["answer"] = c["text"]
elif c.get("type") == "tool_use" and c.get("name") in ("Edit", "Write", "NotebookEdit"):
fp = c.get("input", {}).get("file_path") or c.get("input", {}).get("notebook_path")
if fp:
s["files"].add(fp)
return s
PATCH_FILE = re.compile(r"\*\*\* (?:Update|Add|Delete) File: (\S+)")
def read_codex(path, lo, hi):
s = new_session("codex", os.path.basename(path)[-44:-36])
for line in open(path, encoding="utf-8", errors="replace"):
try:
d = json.loads(line)
except ValueError:
continue
p = d.get("payload") or {}
if d.get("type") in ("session_meta", "turn_context") and p.get("cwd"):
s["cwd"] = p["cwd"]
ts = parse_ts(d.get("timestamp"))
if ts is None or not (lo <= ts <= hi):
continue
kind = p.get("type")
if d.get("type") == "response_item" and kind == "message" and p.get("role") == "user":
touch(s, ts)
for c in p.get("content", []):
text = c.get("text", "")
if c.get("type") == "input_text" and not is_noise(text):
s["prompts"].append(text)
elif d.get("type") == "response_item" and kind in ("custom_tool_call", "function_call"):
touch(s, ts)
s["files"].update(PATCH_FILE.findall(str(p.get("input") or p.get("arguments") or "")))
elif d.get("type") == "event_msg" and kind == "task_complete" and p.get("last_agent_message"):
touch(s, ts)
s["answer"] = p["last_agent_message"]
return s
OPENCODE_DB = "~/.local/share/opencode/opencode.db"
def read_opencode(db, lo, hi):
"""opencode keeps sessions in SQLite: session -> message (role) -> part (content)."""
db = os.path.expanduser(db)
if not os.path.exists(db):
return []
lo_ms, hi_ms = int(lo.timestamp() * 1000), int(hi.timestamp() * 1000)
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
out = []
try:
rows = conn.execute(
"SELECT id, directory, title FROM session WHERE parent_id IS NULL"
" AND time_updated >= ? AND time_created <= ?", (lo_ms, hi_ms)).fetchall()
for sid, directory, title in rows: # parent_id set = subagent; its work shows in the parent
s = new_session("opencode", sid[-8:])
s["cwd"], s["title"] = directory, title
parts = conn.execute(
"SELECT m.data, p.data, p.time_created FROM part p JOIN message m ON m.id = p.message_id"
" WHERE p.session_id = ? AND p.time_created BETWEEN ? AND ? ORDER BY p.time_created",
(sid, lo_ms, hi_ms))
for mdata, pdata, ms in parts:
role, part = json.loads(mdata).get("role"), json.loads(pdata)
touch(s, datetime.fromtimestamp(ms / 1000, timezone.utc).astimezone())
kind, text = part.get("type"), part.get("text", "")
if kind == "text" and role == "user" and not part.get("synthetic") and not is_noise(text):
s["prompts"].append(text)
elif kind == "text" and role == "assistant" and text.strip():
s["answer"] = text
elif kind == "tool" and part.get("tool") in ("edit", "write"):
fp = (part.get("state") or {}).get("input", {}).get("filePath")
if fp:
s["files"].add(fp)
elif kind == "patch":
s["files"].update(part.get("files") or [])
out.append(s)
finally:
conn.close()
return out
def candidates(pattern, lo):
cutoff = lo.timestamp()
return [f for f in glob.glob(os.path.expanduser(pattern), recursive=True)
if os.path.getmtime(f) >= cutoff]
def from_files(pattern, reader):
return lambda lo, hi: (reader(f, lo, hi) for f in candidates(pattern, lo))
READERS = { # agent -> fn(lo, hi) yielding session dicts
"claude-code": from_files("~/.claude/projects/*/*.jsonl", read_claude),
"codex": from_files("~/.codex/sessions/**/*.jsonl", read_codex),
"opencode": lambda lo, hi: read_opencode(OPENCODE_DB, lo, hi),
}
def collect(lo, hi, include, exclude, agents):
out = []
for agent in agents:
for s in READERS[agent](lo, hi):
if s["start"] and in_scope(s["cwd"], include, exclude) and (s["prompts"] or s["answer"]):
out.append(s)
return sorted(out, key=lambda s: s["start"])
AGENT_DIRS = tuple(os.path.realpath(os.path.expanduser(d)) + os.sep
for d in ("~/.claude", "~/.codex", "~/.config/opencode", "~/.local/share/opencode"))
def short(parts):
return os.sep.join(parts) if len(parts) <= 3 else os.sep.join([parts[0], "…", parts[-1]])
def show_path(path, roots):
"""Path relative to the scope root it is in; None for agent-internal files;
'outside:' prefix when the session edited files outside the scope."""
if not path.startswith("/"):
return path
real = os.path.realpath(path)
if real.startswith(AGENT_DIRS):
return None # agent memory/config, not work
for root in roots:
root = os.path.realpath(root)
if real.startswith(root + os.sep):
return short(os.path.relpath(real, root).split(os.sep))
return "outside:" + short(real.split(os.sep)[-3:])
def render(sessions, roots):
if not sessions:
return "_No agent sessions in scope for this period._\n"
lines = []
for s in sessions:
head = f"### {s['agent']} · {s['start']:%Y-%m-%d %H:%M}–{s['end']:%H:%M} · {s['cwd']}"
lines.append(head + (f" · “{s['title']}”" if s["title"] else ""))
prompts = s["prompts"]
half = MAX_PROMPTS // 2
shown = prompts if len(prompts) <= MAX_PROMPTS else prompts[:half] + [None] + prompts[-half:]
for p in shown:
lines.append(f"- … {len(prompts) - MAX_PROMPTS} more prompts" if p is None
else f"- ask: {redact(clip(p, PROMPT_CHARS))}")
names = sorted(filter(None, (show_path(f, roots) for f in s["files"])))
if names:
lines.append(f"- files edited ({len(names)}): {', '.join(names[:15])}")
if s["answer"]:
lines.append(f"- last answer: {redact(clip(s['answer'], ANSWER_CHARS))}")
lines.append("")
return "\n".join(lines)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--from", dest="frm", required=True, help="YYYY-MM-DD, local time")
ap.add_argument("--to", required=True, help="YYYY-MM-DD, inclusive")
ap.add_argument("--include", action="append", required=True)
ap.add_argument("--exclude", action="append", default=[])
ap.add_argument("--agents", default=",".join(READERS))
ap.add_argument("--redact", action="append", default=[], help="extra regex to remove")
a = ap.parse_args()
REDACT.extend((re.compile(r), "[redacted]") for r in a.redact)
tz = datetime.now(timezone.utc).astimezone().tzinfo
lo = datetime.combine(datetime.fromisoformat(a.frm).date(), time.min, tz)
hi = datetime.combine(datetime.fromisoformat(a.to).date(), time.max, tz)
norm = lambda ps: [os.path.realpath(os.path.expanduser(p)) for p in ps]
agents = [x for x in a.agents.split(",") if x in READERS]
include = norm(a.include)
print(render(collect(lo, hi, include, norm(a.exclude), agents), include))
if __name__ == "__main__":
main()

Top-down view of a 17th-century-style Florentine pietra dura panel: two goldfinches on a stone branch above a split pomegranate with glossy red seeds and veined green leaves, all in fitted hardstone pieces on veined black marble, framed by a gold-toned scrolling vine border.
A Florentine pietra dura (commesso) hardstone inlay panel seen straight from above, in the style of 17th-century Medici grand-ducal workshops. The ground is deep black marble crossed by fine white and grey veins. A brown stone branch, built from many small fitted segments, runs diagonally from the upper left to the lower right. Two European goldfinches perch side by side on it, facing right: red faces, black-and-white heads, warm tan breasts, and black wings with bright yellow bars and white spots, all made of separate pieces of coral, onyx, alabaster, Siena marble and yellow jasper. Below them hangs one large ripe pomegranate in mottled red-brown jasper, split open to show its pale pith and clusters of glossy deep-red seeds cut as tiny polished garnet-like stones. Pointed leaves in veined green jasper and malachite branch off on both sides, their light and dark tones following the natural grain of the stone. Every shape reads as a separate, precisely fitted piece of cut stone with hairline seams and no paint. A narrow square border frames the panel: thin gold-toned bands enclosing a scrolling vine of small inlaid rosettes and tendrils on black. Soft, even museum lighting, rich saturated stone colors, crisp detail. No text, no signature. Square 1:1.
Paste any air horn or train horn kit listing and get one clean JSON object: brand, model, trumpet count, every dB figure with its distance and weighting, required PSI, tank size, compressor CFM and voltage. Missing fields come back as null, never guessed. Each dB figure is labeled manufacturer claim, independent measurement or unknown, and implausible claims (e.g. 178 dB with no distance) are flagged. Useful for comparing kits field by field.
Act as a careful data-extraction assistant for aftermarket air horns and train horns (vehicle-mounted horn kits). I will paste a product listing or spec sheet. You return ONE JSON object and never invent data. Listing source: online store listing Listing text: """ Paste the listing or spec sheet here """ RULES 1. Extract only what the text states. If a field is not stated, return null. Do not infer, estimate, or fill from general knowledge about the brand. 2. Units: convert only with exact arithmetic (1 m = 3.281 ft; 1 bar = 14.5038 psi; 1 L = 0.264172 US gal) and set that field's "converted" to true. Always keep the original wording in "raw". 3. Label every decibel figure with "source", exactly one of: - "manufacturer claim": the seller or brand states it (marketing copy, spec table, box text, "up to", "rated"). - "independent measurement": the text explicitly says a named third party (reviewer, lab, test site) measured it with a meter. - "unknown": the origin cannot be told from the text. Never upgrade a claim to a measurement. Seller words like "tested", "certified" or "lab grade" stay "manufacturer claim" unless a named independent tester is given. 4. If a dB figure has no distance, set distance_ft to null and add the flag "db_without_distance". 5. Plausibility flags (add to "flags", never change the extracted values; explain each in "flag_notes"): - "implausible_db": above 160 dB at 10 ft or less, above 150 dB at 50 ft or more, or above 160 dB with no distance. - "psi_out_of_range": required PSI below 70 or above 250. - "voltage_unusual": voltage other than 12 or 24 V DC. - "conflicting_values": two different values for the same field; report the first, list both in "flag_notes". 6. trumpets_count = number of horn bells/trumpets, only when stated or listed explicitly. 7. Output JSON only, no prose, no markdown fences, with this exact schema: { "brand": string|null, "model": string|null, "trumpets_count": integer|null, "db_figures": [ {"value_db": number, "distance_ft": number|null, "weighting": "A"|"C"|"Z"|null, "source": "manufacturer claim"|"independent measurement"|"unknown", "measured_by": string|null, "raw": string} ], "required_psi": {"value": number|null, "raw": string|null, "converted": boolean}, "tank_size_gal": {"value": number|null, "raw": string|null, "converted": boolean}, "compressor_cfm": {"value": number|null, "raw": string|null}, "voltage_v": {"value": number|null, "raw": string|null}, "flags": [string], "flag_notes": [string], "missing_fields": [string] } "missing_fields" lists every top-level field that is null (or an empty db_figures list). You only normalize text: do not judge legality, and do not estimate loudness at other distances.
Latest Bots
Keeps the manuals, model numbers, filter sizes and parts for every appliance in your home, explains error codes and cleaning steps from the right manual, and helps you decide between a quick fix and calling a technician.
Tracks down memory leaks in servers, workers and web apps: reads memory graphs, guides heap snapshots, compares them to find what keeps growing, and proposes the smallest fix plus a check that it stays fixed.
Shows a manager who on the team is overloaded and who has room, across projects, tickets and meetings, and suggests fair moves before deadlines slip or someone burns out.
Keeps track of gifts, favors and kind gestures after birthdays, weddings, holidays or hard times, reminds you who still needs a thank-you, and drafts short, personal notes in your own voice.
Keeps a living map of where your app stores personal data: tables, logs, caches, backups and third-party tools, so privacy reviews, data export and deletion requests take minutes instead of a code search.
Coaches a founder through their first sales: sharpens who to sell to, writes outreach, preps and debriefs discovery calls, keeps a simple pipeline honest, and writes down what works so the first sales hire can repeat it.
Today's Most Upvoted
Builds a 13-week cash flow forecast for a small business or startup from a CSV of receipts and payments - weekly, biweekly, monthly, quarterly and one-off items, invoices on net terms with customer lateness, probability-weighted deals - with a base and a stress case. Finds the low point, the week cash drops below the buffer, the gap, deferrable payments, key invoices and runway. Includes an offline stdlib Python forecaster with --self-test.
---
name: small-business-13-week-cash-flow-forecaster
description: Builds a 13-week cash flow forecast for a small business or startup from a CSV of receipts and payments - weekly, biweekly, monthly, quarterly and one-off items, invoices on net terms with customer lateness, probability-weighted deals - with a base and a stress case. Finds the low point, the week cash drops below the buffer, the gap, deferrable payments, key invoices and runway. Includes an offline stdlib Python forecaster with --self-test.
---
# Small Business 13-Week Cash Flow Forecaster
You help an owner, founder or bookkeeper see the next quarter of cash week by week: what comes in, what goes out, where the balance bottoms out, and what to do before it gets there. Profit and loss says whether the business makes money; the 13-week forecast says whether it can pay salaries on the 1st. You keep the inputs as a CSV anyone can edit, count invoices when customers really pay (not when they are due), weight uncertain deals, run a stress case next to the base case, and turn the low point into a short list of actions.
## Files in this skill
- `scripts/cashflow13.py` - reads the CSV, expands every schedule into dated payments in the horizon, applies customer lateness and probabilities, rolls the balance week by week in cents for a base and a stress case, and reports the low point, the first week below the buffer, the gap, credit line cover, the recurring run-rate and runway, flexible payments before the low point, the invoices that matter, customer concentration and one week's detail (Python 3.8+ standard library only)
- `references/forecast-method.md` - the CSV format, schedules, timing rules, the base and stress cases, and how to keep the forecast honest week after week
- `references/cash-levers.md` - what to do about a gap: collect, defer, cut, finance, in order of cost and speed
- `templates/cash-flow-brief.md` - the one-page brief to hand back
- `examples/studio-cashflow.csv` - a 5-person design studio: retainers, invoices on 30/45-day terms, an overdue invoice, an 80% milestone, a 40% pitch, biweekly salaries, VAT, tax prepayment, a year-end bonus and a 20,000 EUR credit line
- `examples/studio-forecast.md` - the real output of the forecaster on that file
- `examples/cafe-winter.csv` - a cafe with weekly takings and suppliers, a January dip, quarter-day rent and a VAT bill in the same month
## Workflow
### 1. Collect the inputs
Ask for: cash in the bank today (all accounts the business can use, minus cheques not yet cleared), the minimum balance the owner wants to keep (one payroll plus a month of fixed costs is a common floor), any undrawn credit line, and the start Monday. Then list every receipt and payment for the next 13 weeks: recurring income (retainers, subscriptions, takings), open invoices with invoice date and terms, expected new work with an honest probability, payroll and payroll taxes, rent, loans, suppliers, software, tax and VAT dates, annual bills, planned purchases and bonuses. Ask how late customers usually pay and which payments could move (`flex=yes`). Use the bank statement and the accounting system's aged receivables/payables lists, not memory.
### 2. Run the forecaster
```
python3 scripts/cashflow13.py examples/studio-cashflow.csv
python3 scripts/cashflow13.py forecast.csv --opening 41250 --min 15000
python3 scripts/cashflow13.py forecast.csv --stress-cut 30 --stress-delay 21 --week 9
python3 scripts/cashflow13.py forecast.csv --json
python3 scripts/cashflow13.py --self-test
```
Exit 0 = both cases stay at or above the buffer, 1 = cash drops below the buffer (or below zero) in either case, 2 = the CSV has an error (the message names the line). Without a shell, build the same table by hand: one row per week, receipts, payments, net, closing balance; then repeat with the stress assumptions.
### 3. Read the result
- Look at the low point first, in both cases: the week, the amount, and the gap to the buffer.
- Check what drives it with `--week N`: often a cluster (salaries + rent on the 1st, VAT, a quarter-day rent, a bonus) meeting a gap in receipts.
- Stress case: if it goes below zero, is the credit line enough, and for how long?
- Concentration: one customer above about 30% of receipts makes their payment date the forecast.
- Run-rate: negative means the business relies on one-off income; say how many weeks the closing cash lasts without it.
### 4. Turn it into actions
Use `references/cash-levers.md`: collect first (chase overdue invoices, invoice milestones on the day they are reached, ask for deposits), then time payments (defer or split flexible items, agree a payment plan for tax before the due date, lease instead of buy), then cut, and only then finance (draw the credit line for a known gap with a known repayment week). Re-run the forecast with each change so the owner sees the new low point.
### 5. Deliver and roll forward
Fill `templates/cash-flow-brief.md`: verdict, low point in both cases, the weekly table, the drivers, the actions with amounts and owners, and the assumptions. Agree a weekly update: replace the week just ended with actual cash, add week 14, and note forecast vs actual for the biggest lines so the probabilities get better.
## Example result
On `examples/studio-cashflow.csv` the studio starts with 38,500 EUR. The base case dips to 13,160 EUR in week 9 (28 Dec), 1,840 below the 15,000 buffer, when salaries, rent, the illustrator and the loan land before the Hafen Bank and Atlas payments. In the stress case (pitch dropped, invoices two weeks later, retainers -20%) cash goes below zero in week 7 and ends week 13 at -16,590 EUR; the 20,000 credit line covers that with 3,410 to spare but not the buffer. Levers before the low point: the 7,000 bonus, 4,800 of laptops and the illustrator (20,200 flexible in total), plus collecting the 18,600 Hafen Bank invoice on time. Nordwind brings 36% of expected receipts. The cafe example shows a different pattern: VAT and quarter-day rent in December meet a January dip, and the base case stays below its 4,000 buffer from week 8.
## Rules
- Forecast cash, not profit: dates money moves, including VAT and payroll taxes, excluding depreciation and accruals.
- Never invent amounts, dates or probabilities; ask, or list them as assumptions in the brief.
- Count invoices when customers really pay, with their usual lateness; overdue invoices go in week 1 at a probability the owner believes, or out.
- Keep base and stress side by side; do not present only the optimistic case.
- Recommend financing only for a specific, temporary gap with a repayment week in the forecast.
- This is planning support, not tax, legal or lending advice; suggest an accountant for tax payment plans and loan terms.
FILE:references/forecast-method.md
# Forecast method
## CSV format
```
# business: Lumen Design Studio
# currency: EUR
# start: 2026-11-02 first Monday of week 1
# weeks: 13
# opening_balance: 38500 usable cash today
# min_balance: 15000 buffer you do not want to go below
# ar_delay_days: 10 customers pay this many days after the due date on average
# credit_line: 20000 undrawn facility (optional)
item,kind,amount,schedule,start,end,probability,flex,notes
```
- `kind`: `in` (receipt) or `out` (payment). `amount`: positive, per occurrence, gross of VAT if VAT is charged/paid.
- Quote any text that contains a comma (`"Adobe, Figma"`); unquoted extra fields are moved into notes with a warning.
- Name customer receipts `<what> - <customer>` (e.g. `INV-1042 app design sprint - Hafen Bank`) so the concentration check can group them.
## Schedules
| Schedule | Meaning | Example |
|---|---|---|
| `once:2026-11-20` or `2026-11-20` | one payment on that date | equipment, tax bill |
| `weekly:fri` | every Friday in the horizon | wages, takings |
| `biweekly:2026-11-06` | every 14 days from the anchor (earlier anchors are fine) | salaries every second Friday |
| `monthly:15`, `monthly:last` | that day each month; 29-31 clamp to the month end | rent, loan, payroll taxes |
| `quarterly:2026-12-25` | every 3 months from the anchor | quarter-day rent, quarterly VAT |
| `yearly:2026-01-15` | once a year on that date | insurance, licences |
| `net:30` with `start` = invoice date | due = invoice date + 30 days, plus `ar_delay_days` for receipts | open invoices, supplier bills |
`start` and `end` limit recurring items (a contract that ends, a price change: two lines with different dates).
## Timing rules
- Weeks run Monday to Sunday from `start`; a Saturday payment lands in the same week, which is how banks clear most weekend card income anyway.
- Receipts on net terms arrive `ar_delay_days` after the due date. Measure lateness from the last 6-12 months (average days between due date and payment).
- Anything dated before week 1 (an overdue invoice, an unpaid bill) is counted in week 1, with a warning. Give overdue invoices a realistic probability or leave them out.
- Items after the horizon are counted and reported, not shown.
## Base and stress cases
- Base: every amount x its probability (a 40% pitch worth 15,000 counts 6,000). Fine for totals, misleading for timing of a single big deal, so the stress case drops those.
- Stress (defaults): receipts below 90% probability dropped, invoice receipts `--stress-delay` 14 days later, recurring receipts cut by `--stress-cut` 20%. Payments unchanged.
- Choose stress settings that match the business: a cafe in January might use -25% takings; an agency with one big client should also test that client paying a month late (copy the CSV and move that line later).
## Keeping it honest
- Start from the bank balance, not the accounting balance.
- Include VAT/sales tax both ways and the dates it is paid to the authority; payroll taxes on their own dates.
- Update weekly: actuals in, one new week added, probabilities revised. Track forecast vs actual for the five biggest lines; persistent misses mean a wrong assumption (lateness, seasonality).
- Recurring run-rate = recurring receipts minus recurring payments per week; negative means the business lives on one-off income.
- The forecast is only as good as the inputs; list every assumption in the brief.
FILE:references/cash-levers.md
# Cash levers, in the order to try them
## 1. Collect faster (cheapest)
- Chase overdue invoices now, by phone, with a named contact and a promised date; offer a payment plan rather than waiting.
- Invoice the day a milestone is reached; invoice retainers in advance on the 1st, not in arrears.
- Ask for deposits (30-50%) on new projects and staged payments on long ones.
- Shorter terms on new contracts (14 days), card or direct debit for small clients, a small early-payment discount only if the margin allows it.
- Large customers often pay on fixed runs (e.g. the 25th): learn the run date and invoice before it.
## 2. Time payments
- Defer or split flexible purchases (equipment, bonuses, marketing); lease or rent instead of buying.
- Ask suppliers for longer terms before the bill is due, not after.
- Tax: most tax authorities offer payment plans if asked before the due date; ask an accountant.
- Move payroll-adjacent extras (bonuses, training) to after the low point; never delay salaries or payroll taxes as a plan.
## 3. Cut
- Unused software seats and subscriptions, overlapping tools, discretionary travel.
- Freelancers on fixed monthly fees -> project billing.
- Renegotiate rent or service contracts at renewal.
## 4. Finance (for a known, temporary gap)
- Draw the credit line/overdraft for the gap weeks only, with the repayment week visible in the forecast.
- Invoice financing/factoring for large slow customers (costs 1-3% per month; check the contract).
- Owner loan or equity for a structural gap (negative recurring run-rate): financing only buys time; fix the run-rate.
## How to present levers
| Lever | Amount | Week it helps | Effort / cost | Owner |
|---|---|---|---|---|
| Collect INV-1038 Kastell Foods | 6,200 | week 1-2 | call + payment plan | <name> |
| Move year-end bonus to January 29 | 7,000 | week 7 -> 13 | talk to the team early | <name> |
| Lease 2 laptops | 4,800 -> ~180/month | week 3 | small | <name> |
Re-run the forecast with the levers applied and show the new low point in both cases.
FILE:templates/cash-flow-brief.md
# Cash flow brief: <business>, weeks of <start> to <end>
**Opening cash:** <38,500 EUR> **Buffer:** <15,000> **Credit line:** <20,000 undrawn>
**Verdict:** <covered / below buffer / cash runs out (stress)>
## Low point
| Case | Lowest cash | Week | Below buffer from | Gap to buffer |
|---|---|---|---|---|
| Base | <13,160> | <9 (28 Dec)> | <week 9> | <1,840> |
| Stress | <-16,590> | <13 (25 Jan)> | <week 3> | <31,590> |
## What drives it
- <Week 9: salaries 11,600 + rent 3,200 + illustrator 2,800 + loan 1,150, no receipts until Atlas pays in week 10>
- <Stress: pitch deposit dropped, Hafen Bank and Atlas 2 weeks later, retainers -20%>
- <Recurring run-rate -3,475/week: the studio depends on project invoices>
- <Concentration: Nordwind 36% of receipts>
## Weekly table
<paste the forecaster table or a 13-row summary: week, receipts, payments, closing base, closing stress>
## Actions
| # | Action | Amount | Helps week | Owner | By |
|---|---|---|---|---|---|
| 1 | <Collect INV-1038 (overdue since 10 Oct)> | <6,200> | <1-2> | <...> | <date> |
| 2 | <Move year-end bonus to 29 Jan or split> | <7,000> | <7> | <...> | <date> |
| 3 | <Lease laptops instead of buying> | <4,800> | <3> | <...> | <date> |
| 4 | <Confirm Atlas milestone sign-off date, invoice same day> | <22,000> | <10> | <...> | <date> |
**After actions:** base low <...> in week <...>; stress low <...>; credit line needed <...> for weeks <...>.
## Assumptions
- <Customers pay 10 days after due; Kastell Foods 70%; Atlas 80%; Riverside pitch 40%>
- <VAT and tax dates; bonus date; no new hires>
## Next update
<every Monday: actuals in, week 14 added, probabilities revised>
FILE:examples/studio-cashflow.csv
# business: Lumen Design Studio (5 people)
# currency: EUR
# start: 2026-11-02
# weeks: 13
# opening_balance: 38500
# min_balance: 15000
# ar_delay_days: 10
# credit_line: 20000
item,kind,amount,schedule,start,end,probability,flex,notes
Retainer - Nordwind,in,12000,monthly:10,,,,,"invoiced on the 1st, paid around the 10th"
Retainer - Hafen Bank,in,8500,monthly:15,,,,,
Web care plans,in,4200,monthly:20,,,,,14 small clients
INV-1041 brand guidelines - Nordwind,in,12400,net:30,2026-10-03,,,,
INV-1042 app design sprint - Hafen Bank,in,18600,net:45,2026-10-15,,,,
INV-1038 packaging - Kastell Foods,in,6200,net:30,2026-09-10,,70,,overdue - two reminders sent
Project Atlas milestone 2 - Atlas Mobility,in,22000,net:30,2026-12-01,,80,,milestone sign-off expected 1 Dec
Riverside rebrand deposit - Riverside Hotels,in,15000,once:2027-01-08,,,40,,pitch in progress
Net salaries,out,11600,biweekly:2026-11-06,,,,,
Payroll taxes and social security,out,5200,monthly:15,,,,,
Office rent,out,3200,monthly:1,,,,,
Software subscriptions,out,640,monthly:5,,,,,"Adobe, Figma, Google Workspace"
Freelance illustrator,out,2800,monthly:last,,,,yes,can move to project billing
Bank loan repayment,out,1150,monthly:28,,,,,
VAT Q3,out,9800,once:2026-11-10,,,,,
Corporate tax prepayment,out,4500,once:2026-12-15,,,,,
New laptops (2),out,4800,once:2026-11-20,,,,yes,could lease instead
Year-end bonus,out,7000,once:2026-12-18,,,,yes,
Annual liability insurance,out,2300,yearly:2026-01-15,,,,,
FILE:examples/studio-forecast.md
# 13-week cash flow forecast: Lumen Design Studio (5 people)
Weeks: 13 (2026-11-02 to 2027-01-31) Currency: EUR Opening cash: 38,500 Minimum buffer: 15,000 Undrawn credit line: 20,000
Invoices are paid 10 day(s) after the due date on average. Stress case: receipts under 90% likely dropped, invoices +14 days later, recurring receipts -20%.
**Verdict: cash runs out in the stress case** - base case drops below the buffer in week 9 (2026-12-28) and bottoms at 13,160 in week 9; stress case drops below the buffer in week 3 (2026-11-16) and bottoms at -16,590 in week 13.
## Weekly forecast (EUR)
| Wk | Week of | Receipts | Payments | Net | Closing (base) | Closing (stress) | Flag |
|---|---|---|---|---|---|---|---|
| 1 | 02 Nov | 4,340 | 12,240 | -7,900 | 30,600 | 26,260 | |
| 2 | 09 Nov | 32,900 | 15,000 | 17,900 | 48,500 | 27,660 | |
| 3 | 16 Nov | 4,200 | 16,400 | -12,200 | 36,300 | 14,620 | stress below buffer |
| 4 | 23 Nov | 0 | 1,150 | -1,150 | 35,150 | 25,870 | |
| 5 | 30 Nov | 0 | 18,240 | -18,240 | 16,910 | 7,630 | stress below buffer |
| 6 | 07 Dec | 30,600 | 0 | 30,600 | 47,510 | 17,230 | |
| 7 | 14 Dec | 12,700 | 28,300 | -15,600 | 31,910 | -910 | stress negative |
| 8 | 21 Dec | 0 | 0 | 0 | 31,910 | 17,690 | |
| 9 | 28 Dec | 0 | 18,750 | -18,750 | 13,160 | -1,060 | below buffer, stress negative, LOW |
| 10 | 04 Jan | 35,600 | 640 | 34,960 | 48,120 | 7,900 | stress below buffer |
| 11 | 11 Jan | 8,500 | 19,100 | -10,600 | 37,520 | -4,400 | stress negative |
| 12 | 18 Jan | 4,200 | 0 | 4,200 | 41,720 | -1,040 | stress negative |
| 13 | 25 Jan | 0 | 15,550 | -15,550 | 26,170 | -16,590 | stress negative |
| | **Total** | **133,040** | **145,370** | **-12,330** | | | |
## Key numbers
- Lowest cash: base **13,160.00 EUR** (week 9, 2026-12-28), stress **-16,590.00 EUR** (week 13, 2027-01-25).
- Missing to keep the 15,000 buffer: base 1,840.00 EUR, stress 31,590.00 EUR. The 20,000 credit line does NOT cover the stress gap.
- Below zero in the stress case: 16,590.00 EUR at the worst point; the credit line covers that, leaving 3,410.00 EUR of it unused.
- Recurring run-rate: -3,474.62 EUR per week; the week-13 closing cash lasts about 7.5 more weeks at that rate without new one-off income.
- Concentration: Nordwind brings 36% of expected receipts; a late payment there moves the whole forecast.
## Levers before the stress low point (week 13)
Flexible payments due before then (defer, split or cancel):
- week 7, 2026-12-18: Year-end bonus 7,000.00 EUR (cumulative 7,000.00 EUR)
- week 3, 2026-11-20: New laptops (2) 4,800.00 EUR (cumulative 11,800.00 EUR)
- week 5, 2026-11-30: Freelance illustrator 2,800.00 EUR (cumulative 14,600.00 EUR)
- week 9, 2026-12-31: Freelance illustrator 2,800.00 EUR (cumulative 17,400.00 EUR)
- week 13, 2027-01-31: Freelance illustrator 2,800.00 EUR (cumulative 20,200.00 EUR)
Invoices to collect on time (largest first, expected date in the base case):
- INV-1042 app design sprint - Hafen Bank: 18,600.00 EUR, week 6 (2026-12-09)
- Project Atlas milestone 2 - Atlas Mobility: 17,600.00 EUR, week 10 (2027-01-10), 80% likely
- INV-1041 brand guidelines - Nordwind: 12,400.00 EUR, week 2 (2026-11-12)
- INV-1038 packaging - Kastell Foods: 4,340.00 EUR, week 1 (2026-11-02), 70% likely, overdue since 2026-10-20
## Warnings
- INV-1038 packaging - Kastell Foods is overdue (due 2026-10-10): counted in week 1 at 70% - chase it or lower the probability
## Week 9 detail (base case)
| Date | Item | In | Out | Note |
|---|---|---|---|---|
| 2026-12-28 | Bank loan repayment | | 1,150.00 | |
| 2026-12-31 | Freelance illustrator | | 2,800.00 | flex |
| 2027-01-01 | Net salaries | | 11,600.00 | |
| 2027-01-01 | Office rent | | 3,200.00 | |
FILE:examples/cafe-winter.csv
# business: Corner Cup Cafe
# currency: GBP
# start: 2026-11-02
# weeks: 13
# opening_balance: 9200
# min_balance: 4000
# ar_delay_days: 0
item,kind,amount,schedule,start,end,probability,flex,notes
Card and cash takings,in,6400,weekly:sun,,2026-12-20,,,weekly average Nov-Dec
Card and cash takings (January dip),in,5600,weekly:sun,2026-12-21,,,,"quieter after Christmas, closed 25-26 Dec"
Christmas catering orders,in,1800,once:2026-12-18,,,75,,three office parties booked
Coffee and milk suppliers,out,1350,weekly:mon,,,,,
Bakery and food suppliers,out,1100,weekly:tue,,,,,
Staff wages,out,2900,weekly:fri,,,,,
Rent (quarter day),out,7800,quarterly:2026-12-25,,,,,paid quarterly in advance
Business rates,out,410,monthly:1,,,,,
Energy,out,620,monthly:12,,,,,
Card terminal fees,out,180,monthly:3,,,,,
VAT quarter to Oct,out,5200,once:2026-12-07,,,,,
Espresso machine service,out,450,once:2026-11-24,,,,yes,
New menu boards,out,900,once:2026-11-16,,,,yes,
FILE:scripts/cashflow13.py
#!/usr/bin/env python3
"""13-week cash flow forecaster for a small business (Python 3.8+ standard library only).
Turns a CSV of expected receipts and payments into a week-by-week cash forecast (default 13
weeks), in cents, with a base case and a stress case, and answers: when is cash lowest, when
does it drop below the minimum buffer, how much is missing, which payments could be deferred,
which receivables matter most, and how long the run-rate lasts after the horizon.
CSV columns (header row required, extra columns ignored):
item,kind,amount,schedule,start,end,probability,flex,notes
kind in | out
amount positive amount in the business currency (per occurrence)
schedule once:2026-11-20 (or just a date) | weekly:fri | biweekly:2026-11-06 (anchor date)
monthly:15 | monthly:last | quarterly:2026-12-15 (anchor) | yearly:2027-01-15
net:30 (invoice terms: start = invoice date, due = start + 30 days; customers'
average lateness '# ar_delay_days' is added to kind=in)
start, end optional bounds for recurring items (YYYY-MM-DD); invoice date for net:<days>
probability % chance the receipt/payment happens (default 100); base case = amount x probability
flex yes = payment can be deferred or cut if cash is short
notes free text
Comment lines at the top set the frame (or use the CLI flags):
# business: Lumen Design Studio
# currency: EUR
# start: 2026-11-02 (Monday that starts week 1)
# weeks: 13
# opening_balance: 38500
# min_balance: 15000 (cash buffer you do not want to go below)
# ar_delay_days: 10 (customers pay this many days after the due date on average)
# credit_line: 20000 (undrawn overdraft / credit facility, optional)
Stress case: receipts with probability < 90% are dropped, invoice receipts arrive
--stress-delay days later (default 14) and recurring receipts are cut by --stress-cut %
(default 20). Payments are unchanged.
Usage:
python3 cashflow13.py forecast.csv [--opening 38500] [--min 15000] [--weeks 13] [--start 2026-11-02]
[--stress-cut 20] [--stress-delay 14] [--week 9] [--json]
python3 cashflow13.py --self-test
Exit codes: 0 = base and stress stay at or above the minimum balance, 1 = cash drops below the
minimum (or below zero) in either case, 2 = bad input.
"""
import argparse
import calendar
import csv
import datetime as dt
import io
import json
import re
import sys
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
DAYS = {"mon": 0, "tue": 1, "wed": 2, "thu": 3, "fri": 4, "sat": 5, "sun": 6}
class InputError(ValueError):
pass
def money(s, what):
try:
v = Decimal(str(s).replace(",", "").replace("_", "").strip())
except (InvalidOperation, AttributeError):
raise InputError("%s: %r is not a number" % (what, s))
return int((v * 100).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def fmt(c, cur=""):
sign = "-" if c < 0 else ""
c = abs(int(c))
s = "%s%d" % (sign, c // 100)
s = re.sub(r"(\d)(?=(\d{3})+$)", r"\1,", s)
return (s + " " + cur).strip() # whole currency units in tables
def fmtc(c, cur=""):
sign = "-" if c < 0 else ""
c = abs(int(c))
s = re.sub(r"(\d)(?=(\d{3})+$)", r"\1,", str(c // 100)) + ".%02d" % (c % 100)
return (sign + s + " " + cur).strip()
def date(s, what):
try:
return dt.date.fromisoformat(str(s).strip())
except ValueError:
raise InputError("%s: %r is not a date (YYYY-MM-DD)" % (what, s))
def add_months(d, n, day=None):
m = d.month - 1 + n
y, m = d.year + m // 12, m % 12 + 1
last = calendar.monthrange(y, m)[1]
return dt.date(y, m, min(day or d.day, last))
class Forecast:
def __init__(self, text, opening=None, min_balance=None, weeks=None, start=None,
stress_cut=20, stress_delay=14, today=None):
self.warnings = []
self.meta = {"business": "", "currency": "", "ar_delay_days": 0, "credit_line": 0}
body = []
for raw in text.splitlines():
m = re.match(r"\s*#\s*([a-z_ ]+?)\s*:\s*(.*?)\s*$", raw, re.I)
if m and not body:
self.meta[m.group(1).strip().lower().replace(" ", "_")] = m.group(2)
elif raw.strip().startswith("#"):
continue
elif raw.strip():
body.append(raw)
md = self.meta
self.currency = md.get("currency") or ""
self.business = md.get("business") or ""
self.opening = money(opening if opening is not None else md.get("opening_balance", "0"), "opening_balance")
self.min_balance = money(min_balance if min_balance is not None else md.get("min_balance", "0"), "min_balance")
self.credit_line = money(md.get("credit_line") or 0, "credit_line")
self.weeks = int(weeks if weeks is not None else md.get("weeks", 13))
if not 1 <= self.weeks <= 104:
raise InputError("weeks must be 1-104")
st = start if start is not None else md.get("start")
if not st:
t = today or dt.date.today()
st = (t + dt.timedelta(days=(7 - t.weekday()) % 7)).isoformat()
self.start = date(st, "start")
if self.start.weekday() != 0:
self.warnings.append("start %s is a %s, not a Monday; weeks run %s-%s" % (
self.start, self.start.strftime("%A"), self.start.strftime("%a"),
(self.start + dt.timedelta(days=6)).strftime("%a")))
self.end = self.start + dt.timedelta(days=7 * self.weeks - 1)
self.ar_delay = int(Decimal(str(md.get("ar_delay_days") or 0)))
self.stress_cut = Decimal(str(stress_cut))
self.stress_delay = int(stress_delay)
rows = list(csv.DictReader(io.StringIO("\n".join(body))))
if not rows:
raise InputError("no rows (need a header: item,kind,amount,schedule,...)")
need = {"item", "kind", "amount", "schedule"}
cols = {c.strip().lower() for c in (rows[0].keys() if rows else []) if c}
if not need <= cols:
raise InputError("missing column(s): %s" % ", ".join(sorted(need - cols)))
self.items = []
self.events = {"base": [], "stress": []}
self.beyond = 0
seen = set()
for n, r in enumerate(rows, 1):
extra = r.pop(None, None)
if extra:
self.warnings.append("line %d has %d more field(s) than the header - quote text that contains "
"commas; extra fields were added to notes" % (n, len(extra)))
r["notes"] = ",".join([r.get("notes") or ""] + extra)
r = {(k or "").strip().lower(): (v or "").strip() for k, v in r.items()}
key = (r["item"].lower(), r["kind"], r["amount"], r["schedule"], r.get("start", ""))
if key in seen:
self.warnings.append("line %d (%s) repeats an earlier line - duplicate?" % (n, r["item"]))
seen.add(key)
self._item(n, r)
self._run()
# ---------- items ----------
def _item(self, n, r):
where = "line %d (%s)" % (n, r.get("item") or "?")
kind = r["kind"].lower()
if kind not in ("in", "out"):
raise InputError("%s: kind must be in or out" % where)
amt = money(r["amount"], where + " amount")
if amt < 0:
raise InputError("%s: amount must be positive (use kind=in/out for the direction)" % where)
prob = Decimal(r.get("probability") or "100")
if not 0 <= prob <= 100:
raise InputError("%s: probability must be 0-100" % where)
flex = (r.get("flex") or "").lower() in ("yes", "y", "true", "1")
start = date(r["start"], where + " start") if r.get("start") else None
end = date(r["end"], where + " end") if r.get("end") else None
sched = r["schedule"].lower().replace(" ", "")
if re.match(r"^\d{4}-\d\d-\d\d$", sched):
sched = "once:" + sched
typ, _, arg = sched.partition(":")
dates, recurring, invoice = self._dates(where, typ, arg, start, end)
it = {"line": n, "item": r["item"], "kind": kind, "amount": amt, "prob": prob, "flex": flex,
"schedule": r["schedule"], "recurring": recurring, "invoice": invoice, "dates": dates,
"notes": r.get("notes", "")}
self.items.append(it)
def _dates(self, where, typ, arg, start, end):
lo = self.start - dt.timedelta(days=400)
hi = self.end + dt.timedelta(days=400)
if typ == "once":
return [date(arg, where + " schedule")], False, False
if typ == "net":
if not start:
raise InputError("%s: net:<days> needs the invoice date in 'start'" % where)
try:
days = int(arg)
except ValueError:
raise InputError("%s: net:<days> needs a number of days" % where)
return [start + dt.timedelta(days=days)], False, True
out = []
if typ == "weekly":
if arg not in DAYS:
raise InputError("%s: weekly:<mon..sun>" % where)
d = self.start + dt.timedelta(days=(DAYS[arg] - self.start.weekday()) % 7)
while d <= self.end:
out.append(d)
d += dt.timedelta(days=7)
elif typ == "biweekly":
anchor = date(arg, where + " schedule")
d = anchor
while d > self.start:
d -= dt.timedelta(days=14)
while d <= self.end:
out.append(d)
d += dt.timedelta(days=14)
elif typ == "monthly":
if arg == "last":
day = 31
else:
try:
day = int(arg)
except ValueError:
raise InputError("%s: monthly:<1-31|last>" % where)
if not 1 <= day <= 31:
raise InputError("%s: monthly day must be 1-31" % where)
m = dt.date(self.start.year, self.start.month, 1)
while m <= self.end:
out.append(add_months(m, 0, day))
m = add_months(m, 1, 1)
elif typ in ("quarterly", "yearly"):
anchor = date(arg, where + " schedule")
step = 3 if typ == "quarterly" else 12
d, k = anchor, 0
while d > lo:
k -= 1
d = add_months(anchor, step * k)
while d <= hi:
out.append(d)
k += 1
d = add_months(anchor, step * k)
else:
raise InputError("%s: unknown schedule %r (once, weekly, biweekly, monthly, quarterly, yearly, net)"
% (where, typ))
out = [d for d in out if (not start or d >= start) and (not end or d <= end)
and self.start <= d <= self.end]
return out, True, False
# ---------- forecast ----------
def week_of(self, d):
return (d - self.start).days // 7
def _run(self):
W = self.weeks
for case in ("base", "stress"):
for it in self.items:
for d0 in it["dates"]:
d = d0
amt = it["amount"]
prob = it["prob"]
note = ""
if it["kind"] == "in":
if it["invoice"]:
d = d + dt.timedelta(days=self.ar_delay)
if case == "stress":
d = d + dt.timedelta(days=self.stress_delay)
if case == "stress":
if prob < 90:
continue
if it["recurring"]:
amt = int((Decimal(amt) * (100 - self.stress_cut) / 100).quantize(Decimal("1"), ROUND_HALF_UP))
prob = Decimal(100)
exp = int((Decimal(amt) * prob / 100).quantize(Decimal("1"), ROUND_HALF_UP))
if d < self.start:
note = "overdue since %s" % d.isoformat()
d = self.start
if d > self.end:
if case == "base":
self.beyond += 1
continue
self.events[case].append({"week": self.week_of(d), "date": d, "item": it["item"], "kind": it["kind"],
"cents": exp, "flex": it["flex"], "prob": prob, "note": note,
"invoice": it["invoice"], "recurring": it["recurring"], "line": it["line"]})
self.table = {}
for case in ("base", "stress"):
bal = self.opening
rows = []
for w in range(W):
ins = sum(e["cents"] for e in self.events[case] if e["week"] == w and e["kind"] == "in")
outs = sum(e["cents"] for e in self.events[case] if e["week"] == w and e["kind"] == "out")
opening = bal
bal = bal + ins - outs
rows.append({"week": w + 1, "start": self.start + dt.timedelta(days=7 * w), "opening": opening,
"in": ins, "out": outs, "net": ins - outs, "closing": bal})
self.table[case] = rows
for it in self.items:
if it["kind"] == "in" and it["invoice"] and it["dates"][0] + dt.timedelta(days=self.ar_delay) < self.start:
self.warnings.append("%s is overdue (due %s): counted in week 1 at %s%% - chase it or lower the "
"probability" % (it["item"], it["dates"][0], it["prob"]))
if it["kind"] == "out" and not it["recurring"] and it["dates"][0] < self.start:
self.warnings.append("%s was due %s and is still unpaid: counted in week 1" % (it["item"], it["dates"][0]))
# ---------- analysis ----------
def low(self, case):
rows = self.table[case]
r = min(rows, key=lambda x: (x["closing"], x["week"]))
return r
def first_below(self, case, level):
for r in self.table[case]:
if r["closing"] < level:
return r
return None
def run_rate(self):
"""Weekly net of recurring items only (base case, expected values)."""
tot = sum((e["cents"] if e["kind"] == "in" else -e["cents"]) for e in self.events["base"] if e["recurring"])
return int(round(tot / float(self.weeks)))
def runway(self):
rr = self.run_rate()
end = self.table["base"][-1]["closing"]
if rr >= 0:
return None, rr
weeks = end / float(-rr) if end > 0 else 0.0
return weeks, rr
def levers(self, case="stress"):
lowr = self.low(case)
flex = [e for e in self.events[case] if e["kind"] == "out" and e["flex"] and e["week"] <= lowr["week"] - 1]
flex.sort(key=lambda e: -e["cents"])
recv = [e for e in self.events["base"] if e["kind"] == "in" and e["invoice"]]
recv.sort(key=lambda e: -e["cents"])
return lowr, flex, recv
def concentration(self):
tot = {}
for e in self.events["base"]:
if e["kind"] == "in" and " - " in e["item"]: # "<what> - <customer>" names a customer
name = e["item"].rsplit(" - ", 1)[-1].strip()
tot[name] = tot.get(name, 0) + e["cents"]
allin = sum(e["cents"] for e in self.events["base"] if e["kind"] == "in")
if not allin:
return []
return sorted(((k, v, v / float(allin)) for k, v in tot.items()), key=lambda x: -x[1])
def worst_flag(self):
b = self.low("base")["closing"]
s = self.low("stress")["closing"]
return b < self.min_balance or s < self.min_balance
def render(fc, week_detail=None):
cur = fc.currency
o = ["# 13-week cash flow forecast" + (": " + fc.business if fc.business else ""), ""]
o.append("Weeks: %d (%s to %s) Currency: %s Opening cash: %s Minimum buffer: %s%s" % (
fc.weeks, fc.start, fc.end, cur or "-", fmt(fc.opening), fmt(fc.min_balance),
(" Undrawn credit line: %s" % fmt(fc.credit_line)) if fc.credit_line else ""))
has_inv = any(it["invoice"] and it["kind"] == "in" for it in fc.items)
o.append("%sStress case: receipts under 90%% likely dropped, %srecurring receipts -%s%%." % (
("Invoices are paid %d day(s) after the due date on average. " % fc.ar_delay) if has_inv else "",
("invoices +%d days later, " % fc.stress_delay) if has_inv else "", fc.stress_cut))
o.append("")
lb, ls = fc.low("base"), fc.low("stress")
fb, fs = fc.first_below("base", fc.min_balance), fc.first_below("stress", fc.min_balance)
if not fc.worst_flag():
o.append("**Verdict: covered** - cash stays above the %s buffer in both cases (lowest %s in week %d, stress %s in week %d)."
% (fmt(fc.min_balance), fmt(lb["closing"]), lb["week"], fmt(ls["closing"]), ls["week"]))
else:
bits = []
for name, f, lw in (("base", fb, lb), ("stress", fs, ls)):
if f:
bits.append("%s case drops below the buffer in week %d (%s) and bottoms at %s in week %d" % (
name, f["week"], f["start"], fmt(lw["closing"]), lw["week"]))
verdict = "cash runs out" if lb["closing"] < 0 else (
"cash runs out in the stress case" if ls["closing"] < 0 else "below buffer")
o.append("**Verdict: %s** - %s." % (verdict, "; ".join(bits)))
o += ["", "## Weekly forecast (%s)" % (cur or "currency units"), "",
"| Wk | Week of | Receipts | Payments | Net | Closing (base) | Closing (stress) | Flag |",
"|---|---|---|---|---|---|---|---|"]
for b, s in zip(fc.table["base"], fc.table["stress"]):
flag = []
if b["closing"] < 0:
flag.append("NEGATIVE")
elif b["closing"] < fc.min_balance:
flag.append("below buffer")
if s["closing"] < 0 and b["closing"] >= 0:
flag.append("stress negative")
elif s["closing"] < fc.min_balance and b["closing"] >= fc.min_balance:
flag.append("stress below buffer")
if b is lb:
flag.append("LOW")
o.append("| %d | %s | %s | %s | %s | %s | %s | %s |" % (
b["week"], b["start"].strftime("%d %b"), fmt(b["in"]), fmt(b["out"]), fmt(b["net"]),
fmt(b["closing"]), fmt(s["closing"]), ", ".join(flag)))
tin = sum(r["in"] for r in fc.table["base"])
tout = sum(r["out"] for r in fc.table["base"])
o.append("| | **Total** | **%s** | **%s** | **%s** | | | |" % (fmt(tin), fmt(tout), fmt(tin - tout)))
o += ["", "## Key numbers", ""]
o.append("- Lowest cash: base **%s** (week %d, %s), stress **%s** (week %d, %s)." % (
fmtc(lb["closing"], cur), lb["week"], lb["start"], fmtc(ls["closing"], cur), ls["week"], ls["start"]))
gap_b = max(0, fc.min_balance - lb["closing"])
gap_s = max(0, fc.min_balance - ls["closing"])
o.append("- Missing to keep the %s buffer: base %s, stress %s.%s" % (
fmt(fc.min_balance), fmtc(gap_b, cur), fmtc(gap_s, cur),
(" The %s credit line %s the stress gap." % (fmt(fc.credit_line), "covers" if fc.credit_line >= gap_s else "does NOT cover"))
if fc.credit_line and gap_s else ""))
if fc.credit_line and ls["closing"] < 0:
o.append("- Below zero in the stress case: %s at the worst point; the credit line %s that, leaving %s of it unused."
% (fmtc(-ls["closing"], cur), "covers" if fc.credit_line >= -ls["closing"] else "does NOT cover",
fmtc(max(0, fc.credit_line + ls["closing"]), cur)))
rw, rr = fc.runway()
if rw is None:
o.append("- Recurring run-rate: +%s per week (recurring receipts cover recurring payments)." % fmtc(rr, cur))
elif fc.table["base"][-1]["closing"] <= 0:
o.append("- Recurring run-rate: %s per week, and cash is already below zero at the end of week %d."
% (fmtc(rr, cur), fc.weeks))
else:
o.append("- Recurring run-rate: %s per week; the week-%d closing cash lasts about %.1f more weeks at that rate "
"without new one-off income." % (fmtc(rr, cur), fc.weeks, rw))
conc = fc.concentration()
if conc and conc[0][2] > 0.3:
o.append("- Concentration: %s brings %.0f%% of expected receipts; a late payment there moves the whole "
"forecast." % (conc[0][0], 100 * conc[0][2]))
if fc.beyond:
o.append("- %d dated item(s) fall after week %d and are not in the table." % (fc.beyond, fc.weeks))
lowr, flex, recv = fc.levers()
o += ["", "## Levers before the stress low point (week %d)" % lowr["week"], ""]
if flex:
o.append("Flexible payments due before then (defer, split or cancel):")
acc = 0
for e in flex:
acc += e["cents"]
o.append("- week %d, %s: %s %s (cumulative %s)" % (e["week"] + 1, e["date"], e["item"], fmtc(e["cents"], cur), fmtc(acc, cur)))
else:
o.append("No payments marked flex=yes before the low point.")
if recv:
o.append("")
o.append("Invoices to collect on time (largest first, expected date in the base case):")
for e in recv[:6]:
o.append("- %s: %s, week %d (%s)%s%s" % (e["item"], fmtc(e["cents"], cur), e["week"] + 1, e["date"],
(", %s%% likely" % e["prob"]) if e["prob"] < 100 else "",
(", " + e["note"]) if e["note"] else ""))
if fc.warnings:
o += ["", "## Warnings", ""] + ["- " + w for w in fc.warnings]
wk = week_detail if week_detail else lb["week"]
if 1 <= wk <= fc.weeks:
o += ["", "## Week %d detail (base case)" % wk, "", "| Date | Item | In | Out | Note |", "|---|---|---|---|---|"]
for e in sorted((e for e in fc.events["base"] if e["week"] == wk - 1), key=lambda e: (e["date"], e["kind"])):
o.append("| %s | %s | %s | %s | %s |" % (
e["date"], e["item"], fmtc(e["cents"]) if e["kind"] == "in" else "", fmtc(e["cents"]) if e["kind"] == "out" else "",
"; ".join(x for x in (("%s%% likely" % e["prob"]) if e["prob"] < 100 else "", "flex" if e["flex"] else "", e["note"]) if x)))
return "\n".join(o) + "\n"
def as_json(fc):
def row(r):
return {k: (v.isoformat() if isinstance(v, dt.date) else v) for k, v in r.items()}
lb, ls = fc.low("base"), fc.low("stress")
rw, rr = fc.runway()
return {"business": fc.business, "currency": fc.currency, "start": fc.start.isoformat(), "weeks": fc.weeks,
"opening_cents": fc.opening, "min_balance_cents": fc.min_balance,
"base": [row(r) for r in fc.table["base"]], "stress": [row(r) for r in fc.table["stress"]],
"low_base": row(lb), "low_stress": row(ls), "run_rate_cents_per_week": rr, "runway_weeks_after_horizon": rw,
"below_min": fc.worst_flag(), "warnings": fc.warnings}
def self_test():
cases = []
def case(name, fn):
try:
ok, err = bool(fn()), ""
except Exception as e: # noqa
ok, err = False, repr(e)
cases.append((name, ok, err))
HEAD = "# start: 2026-11-02\n# weeks: 13\n# opening_balance: 10000\n# min_balance: 2000\nitem,kind,amount,schedule,start,end,probability,flex,notes\n"
def F(rows, **kw):
return Forecast(HEAD + rows, **kw)
def raises(fn):
try:
fn()
except InputError:
return True
return False
def dates(rows):
return [e["date"].isoformat() for e in F(rows).events["base"]]
case("once lands in its week", lambda: F("Tax,out,500,once:2026-11-11,,,,,\n").table["base"][1]["out"] == 50000)
case("bare date means once", lambda: dates("Tax,out,500,2026-11-11,,,,,\n") == ["2026-11-11"])
case("weekly friday x13", lambda: len(dates("Sales,in,100,weekly:fri,,,,,\n")) == 13 and dates("Sales,in,100,weekly:fri,,,,,\n")[0] == "2026-11-06")
case("biweekly from anchor", lambda: dates("Pay,out,100,biweekly:2026-11-06,,,,,\n")[:3] == ["2026-11-06", "2026-11-20", "2026-12-04"])
case("biweekly anchor before start", lambda: dates("Pay,out,100,biweekly:2026-10-09,,,,,\n")[0] == "2026-11-06")
case("monthly 15th", lambda: dates("Rent,out,100,monthly:15,,,,,\n") == ["2026-11-15", "2026-12-15", "2027-01-15"])
case("monthly last clamps", lambda: dates("Fee,out,100,monthly:last,,,,,\n") == ["2026-11-30", "2026-12-31", "2027-01-31"])
case("monthly 31 clamps to 30 Nov", lambda: dates("Fee,out,100,monthly:31,,,,,\n")[0] == "2026-11-30")
case("quarterly from anchor", lambda: dates("VAT,out,100,quarterly:2026-08-10,,,,,\n") == ["2026-11-10"])
case("yearly in horizon", lambda: dates("Ins,out,100,yearly:2026-01-15,,,,,\n") == ["2027-01-15"])
case("start/end bounds", lambda: dates("Rent,out,100,monthly:1,2026-12-01,2026-12-31,,,\n") == ["2026-12-01"])
case("net terms + ar delay", lambda: Forecast("# start: 2026-11-02\n# ar_delay_days: 10\n# opening_balance: 0\nitem,kind,amount,schedule,start\nINV,in,100,net:30,2026-10-20\n").events["base"][0]["date"].isoformat() == "2026-11-29")
case("overdue receivable in week 1", lambda: (lambda f: f.events["base"][0]["week"] == 0 and "overdue" in f.events["base"][0]["note"])(F("INV,in,100,net:30,2026-08-01,,,,\n")))
case("probability weighting", lambda: F("Deal,in,1000,once:2026-11-05,,,40,,\n").table["base"][0]["in"] == 40000)
case("stress drops unlikely receipts", lambda: F("Deal,in,1000,once:2026-11-05,,,40,,\n").table["stress"][0]["in"] == 0)
case("stress cuts recurring receipts", lambda: F("Sales,in,100,weekly:fri,,,,,\n").table["stress"][0]["in"] == 8000)
case("stress delays invoices", lambda: (lambda f: f.events["stress"][0]["date"] - f.events["base"][0]["date"] == dt.timedelta(days=14))(F("INV,in,100,net:30,2026-10-20,,,,\n")))
case("balances roll forward", lambda: (lambda t: t[0]["closing"] == 1000000 + 10000 and t[1]["opening"] == t[0]["closing"])(F("Sales,in,100,weekly:fri,,,,,\n").table["base"]))
case("low point and first below", lambda: (lambda f: f.low("base")["week"] == 3 and f.first_below("base", f.min_balance)["week"] == 3)(F("Big,out,9000,once:2026-11-18,,,,,\nBack,in,9000,once:2026-11-25,,,,,\n")))
case("verdict flags below min", lambda: F("Big,out,9000,once:2026-11-18,,,,,\n").worst_flag())
case("covered when fine", lambda: not F("Small,out,100,once:2026-11-18,,,,,\n").worst_flag())
case("run-rate recurring only", lambda: F("Sales,in,100,weekly:fri,,,,,\nOne,out,5000,once:2026-11-20,,,,,\n").run_rate() == 10000)
case("runway weeks when burning", lambda: (lambda f: f.runway()[0] is not None and f.runway()[1] < 0)(F("Rent,out,1000,monthly:1,,,,,\n")))
case("flex levers before low point", lambda: (lambda f: [e["item"] for e in f.levers()[1]] == ["Laptop"])(F("Laptop,out,2000,once:2026-11-04,,,,yes,\nBig,out,9000,once:2026-11-18,,,,,\n")))
case("unquoted commas go to notes with a warning", lambda: (lambda f: any("more field" in w for w in f.warnings) and f.items[0]["notes"] == "a,b")(F("X,out,1,once:2026-11-05,,,,,a,b\n")))
case("money parsing with commas", lambda: money("12,400.50", "x") == 1240050)
case("bad kind rejected", lambda: raises(lambda: F("X,maybe,10,once:2026-11-05,,,,,\n")))
case("negative amount rejected", lambda: raises(lambda: F("X,out,-10,once:2026-11-05,,,,,\n")))
case("unknown schedule rejected", lambda: raises(lambda: F("X,out,10,fortnightly:2026-11-05,,,,,\n")))
case("net without invoice date rejected", lambda: raises(lambda: F("X,in,10,net:30,,,,,\n")))
case("bad probability rejected", lambda: raises(lambda: F("X,in,10,once:2026-11-05,,,120,,\n")))
case("missing columns rejected", lambda: raises(lambda: Forecast("# start: 2026-11-02\nname,value\na,1\n")))
case("non-Monday start warns", lambda: any("not a Monday" in w for w in F("X,out,1,once:2026-11-05,,,,,\n", start="2026-11-04").warnings))
case("duplicate warning", lambda: any("duplicate" in w for w in F("X,out,1,once:2026-11-05,,,,,\nX,out,1,once:2026-11-05,,,,,\n").warnings))
case("items after horizon counted", lambda: F("Later,out,10,once:2027-06-01,,,,,\n").beyond == 1)
case("CLI overrides opening", lambda: F("X,out,1,once:2026-11-05,,,,,\n", opening="500").opening == 50000)
case("render sections", lambda: all(s in render(F("Rent,out,1000,monthly:1,,,,yes,\n")) for s in ("## Weekly forecast", "## Key numbers", "## Levers")))
case("json output", lambda: json.dumps(as_json(F("Rent,out,1000,monthly:1,,,,,\n"))) and as_json(F("Rent,out,1000,monthly:1,,,,,\n"))["low_base"]["closing"] == 1000000 - 200000)
case("format", lambda: fmt(123456789) == "1,234,567" and fmtc(-123456, "EUR") == "-1,234.56 EUR")
passed = sum(1 for _, ok, _ in cases if ok)
for name, ok, err in cases:
print(("PASS " if ok else "FAIL ") + name + ((" " + err) if err else ""))
print("%d/%d passed" % (passed, len(cases)))
return 0 if passed == len(cases) else 1
def main(argv=None):
ap = argparse.ArgumentParser(description="13-week cash flow forecast with base and stress cases.")
ap.add_argument("file", nargs="?", help="CSV of receipts and payments ('-' = stdin)")
ap.add_argument("--opening", default=None, help="opening cash (overrides '# opening_balance:')")
ap.add_argument("--min", dest="min_balance", default=None, help="minimum cash buffer")
ap.add_argument("--weeks", type=int, default=None)
ap.add_argument("--start", default=None, help="first Monday (YYYY-MM-DD; default: '# start:' or next Monday)")
ap.add_argument("--stress-cut", type=float, default=20, help="%% cut to recurring receipts in the stress case")
ap.add_argument("--stress-delay", type=int, default=14, help="extra days late for invoices in the stress case")
ap.add_argument("--week", type=int, default=None, help="show the item list for this week (default: base low week)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.file:
ap.error("give a CSV file or --self-test")
try:
text = sys.stdin.read() if a.file == "-" else open(a.file, encoding="utf-8-sig").read()
fc = Forecast(text, a.opening, a.min_balance, a.weeks, a.start, a.stress_cut, a.stress_delay)
out = json.dumps(as_json(fc), indent=2) + "\n" if a.json else render(fc, a.week)
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr)
return 2
sys.stdout.write(out)
return 1 if fc.worst_flag() else 0
if __name__ == "__main__":
sys.exit(main())Latest Prompts
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional, the conversations should align with current market trends.
Create a very professional conversation about the current crypto market and stock market
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional
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.
Opinionated preferences for designing and publishing Rust library crates: API shape, errors, features, docs and release checks.
# Rust Library Crate taste of a maintainer who publishes reusable crates - Keep the public API small and re-export the important types from the crate root. Confidence: 0.85 - Define one error enum per crate with `thiserror`, and never return `anyhow::Error` from a library. Confidence: 0.90 - Mark public enums and config structs `#[non_exhaustive]` when new variants or fields are likely. Confidence: 0.80 - Accept flexible inputs like `impl AsRef<str>` or `impl Into<String>` and return concrete types. Confidence: 0.80 - Use the builder pattern for types with more than a few optional settings. Confidence: 0.80 - Put optional integrations behind additive cargo features; never make a feature remove functionality. Confidence: 0.90 - Keep the default feature set minimal and support `no_std` when the domain allows it. Confidence: 0.70 - Gate `serde` derives behind a `serde` feature instead of making it a hard dependency. Confidence: 0.85 - Declare `rust-version` in Cargo.toml and test the MSRV in CI. Confidence: 0.85 - Run `cargo clippy -- -D warnings`, `cargo fmt --check` and `cargo test --all-features` on every PR. Confidence: 0.90 - Check semver breakage with `cargo-semver-checks` before each release. Confidence: 0.85 - Write doc comments with runnable examples on every public item; doctests are part of the test suite. Confidence: 0.90 - Add `#![deny(missing_docs)]` and `#![forbid(unsafe_code)]` unless the crate truly needs unsafe. Confidence: 0.80 - When unsafe is needed, wrap it in a tiny module with `// SAFETY:` comments and run Miri in CI. Confidence: 0.85 - Implement common traits like `Debug`, `Clone`, `PartialEq` and `Default` on public types where they make sense. Confidence: 0.85 - Make public types `Send` and `Sync` when possible and assert it in a test. Confidence: 0.75 - Avoid forcing an async runtime on users; keep core logic runtime-agnostic. Confidence: 0.80 - Add property tests with `proptest` for parsers and encoders. Confidence: 0.75 - Benchmark hot paths with `criterion` before claiming performance improvements. Confidence: 0.75 - Release with `cargo-release` or release-plz and keep a CHANGELOG.md in Keep a Changelog format. Confidence: 0.80 - Dual-license under MIT OR Apache-2.0 to match the Rust ecosystem. Confidence: 0.80
Opinionated preferences for building offline-first Progressive Web Apps: service workers, caching strategies, installability and sync.
# Progressive Web App taste of a frontend engineer who builds offline-first web apps - Treat the network as optional: the app shell must load and render from cache with no connection. Confidence: 0.90 - Generate the service worker with Workbox instead of hand-writing caching logic for every route. Confidence: 0.80 - Precache only the versioned app shell; cache API responses and images at runtime. Confidence: 0.90 - Use cache-first for hashed static assets, stale-while-revalidate for images and network-first for HTML. Confidence: 0.85 - Never cache authenticated API responses in a shared cache without a per-user key and an expiry. Confidence: 0.90 - Cap runtime caches by entry count and age so storage doesn't grow without bounds. Confidence: 0.85 - Show an "update available" prompt when a new service worker is waiting; don't call `skipWaiting()` silently. Confidence: 0.80 - Serve the service worker file with `Cache-Control: no-cache` so updates are picked up quickly. Confidence: 0.90 - Keep user data in IndexedDB through a small wrapper such as `idb`, never in `localStorage`. Confidence: 0.85 - Queue writes made offline and replay them with Background Sync, falling back to a retry on next launch. Confidence: 0.75 - Show clear offline and syncing states in the UI instead of failing requests silently. Confidence: 0.90 - Provide a complete manifest: name, short_name, start_url, display, theme_color and maskable icons. Confidence: 0.90 - Trigger the install prompt from a user action at a useful moment, not on first page load. Confidence: 0.85 - Ask for notification permission only after the user opts in to a feature that needs it. Confidence: 0.95 - Call `navigator.storage.persist()` for apps that keep important offline data. Confidence: 0.70 - Test offline mode, slow 3G and service worker updates in Playwright, not only by hand in DevTools. Confidence: 0.80 - Keep the initial JavaScript bundle small enough for a fast first load on mid-range phones. Confidence: 0.85 - Version cache names and delete old caches in the `activate` event. Confidence: 0.90 - Include an offline fallback page for navigations that aren't cached. Confidence: 0.85 - Check iOS Safari separately; its storage limits and install flow differ from Chromium. Confidence: 0.80 - Audit with Lighthouse in CI and fail the build when PWA or performance scores drop. Confidence: 0.65
Opinionated preferences for building and publishing TypeScript libraries to npm: exports maps, type checks, releases and package hygiene.
# TypeScript Library Publishing taste of a maintainer who ships small, well-typed npm packages - Publish ESM first and add a CommonJS build only when real consumers still need `require()`. Confidence: 0.80 - Define entry points with the `exports` map and keep `main`/`types` only as fallbacks for old tooling. Confidence: 0.90 - Put `types` conditions first inside each `exports` entry so TypeScript resolves declarations correctly. Confidence: 0.85 - Build with tsup or tsdown for bundles and plain `tsc --emitDeclarationOnly` for `.d.ts` files. Confidence: 0.75 - Turn on `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` in the library's own tsconfig. Confidence: 0.85 - Check the published package with `publint` and `@arethetypeswrong/cli` in CI before every release. Confidence: 0.90 - Whitelist shipped files with the `files` field instead of maintaining an `.npmignore`. Confidence: 0.90 - Set `"sideEffects": false` when it is true so bundlers can tree-shake unused exports. Confidence: 0.85 - Export named functions only; avoid default exports so imports stay consistent across ESM and CJS. Confidence: 0.80 - Keep runtime dependencies near zero and move framework packages to `peerDependencies`. Confidence: 0.90 - Declare a supported Node.js range in `engines` and test that range in a CI matrix. Confidence: 0.80 - Treat exported types as public API: changing or removing them is a breaking change under semver. Confidence: 0.95 - Mark internal helpers with `@internal` and strip them with `stripInternal` so they don't leak into declarations. Confidence: 0.70 - Write TSDoc comments on every public export, including an `@example` that compiles. Confidence: 0.80 - Test against the built output, not only the source, so broken `exports` paths fail in CI. Confidence: 0.85 - Add type-level tests with `expectTypeOf` or `tsd` for generics and overloads. Confidence: 0.80 - Manage versions and changelogs with Changesets, and release from CI rather than a laptop. Confidence: 0.85 - Publish with npm provenance enabled and use a granular automation token scoped to the package. Confidence: 0.85 - Ship source maps and declaration maps so "go to definition" lands on real TypeScript source. Confidence: 0.75 - Never rely on `postinstall` scripts; a library should install without running code. Confidence: 0.90 - Keep the README's first screen to install, a minimal example and a link to full docs. Confidence: 0.80
Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
name: home-solar-panel-payback-calculator
description: Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
# Home Solar Panel Payback Calculator
You help homeowners decide whether rooftop solar panels pay off for their home, and which installer quote is the best value. Sales pitches usually show the biggest possible saving: a high yield, most of the power used at home, rising electricity prices and no inverter replacement. You turn the household's real consumption, tariff and each quote into one honest comparison with the same assumptions, and a short list of questions for the installers.
You work only with the numbers the user gives you, on their machine. You are not a financial adviser, an engineer or an installer: you never recommend a specific company, never invent prices, yields or incentives, and say clearly that results are estimates that must be checked against the installer's quote, the roof survey and the utility tariff. Roof condition, shading, structural checks, permits, grid connection rules, tax treatment and insurance are outside the script; mention them when they matter.
## Files in this skill
- `scripts/solar_payback.py` - reads the household (JSON) and quotes (CSV) and computes, per quote: year-1 production, self-used and exported kWh, saving and bill cut, simple and discounted payback, net value at the horizon, NPV, IRR, cost per kWh and findings SP01-SP10; `--horizon-years N`, `--table "<quote name>"` for the year-by-year cash flow, `--json` for tooling, `--self-test` runs 28 checks (Python 3.8+ standard library only)
- `references/solar-math.md` - the formulas, what each input means and where to find it, typical ranges, and a worked example you can check by hand
- `references/quote-checklist.md` - questions for installers, what each finding means, and how to make quotes comparable
- `templates/solar-summary.md` - the one-page summary you hand back
- `examples/household.json`, `examples/quotes.csv` - a fictional household using 4,600 kWh a year at EUR 0.31 per kWh with six quotes (small, medium, medium with battery, oversized, the small one on a loan, and a door-to-door offer with optimistic assumptions)
## Workflow
### 1. Collect the facts
Ask for:
- yearly electricity use in kWh (12 months of bills or the smart-meter total), the price per kWh including taxes, the export or feed-in price and how it is paid, and whether a heat pump, EV or other big load is planned;
- for each quote: system size in kW, total price, incentives or grants confirmed for this home, the installer's yearly production estimate (or kWh per kW), the self-consumption share they assume, panel degradation, inverter warranty and replacement cost, yearly maintenance, battery size, and loan rate and term if financed;
- the horizon (25 years is common for panel warranties) and a discount rate (the interest they could earn or pay elsewhere, for example 0.03-0.05).
Never fill in prices, yields or incentives yourself; if a number is missing, ask or leave that quote out. Rates and shares are decimals (0.03 = 3%).
### 2. Make the quotes comparable
Use the same household file for all quotes. If one quote assumes a much higher yield (SP10) or an optimistic self-consumption share without a battery (SP08 fires above 0.8; most homes reach 0.25-0.45), run it again with the other quotes' yield and a realistic share, and show both results.
### 3. Run the comparison
```
python3 scripts/solar_payback.py examples/household.json examples/quotes.csv
python3 scripts/solar_payback.py household.json quotes.csv --horizon-years 15
python3 scripts/solar_payback.py household.json quotes.csv --table "Installer A 4.4 kW on loan"
python3 scripts/solar_payback.py household.json quotes.csv --json > solar.json
python3 scripts/solar_payback.py --self-test
```
Exit 0 = at least one quote pays back within the horizon with no high findings, 1 = none does, 2 = bad input. Without a shell, follow `references/solar-math.md` by hand for the two most promising quotes.
### 4. Read the results
- **NPV** is the main number: the value of the system today after all costs, at the chosen discount rate. **Net at horizon** is the same without discounting.
- **Simple payback** is when cumulative savings cover the cost; **discounted payback** is later and more realistic.
- **Self-used vs exported**: power used at home saves the full retail price; exported power earns only the export price. A bigger system mostly adds exports.
- **Cost per kWh** compares the lifetime cost of each kWh produced with the retail and export prices.
- Findings: SP01 high (never pays back); SP02 slow payback, SP03 most power exported cheaply, SP04 oversized against use, SP05 loan payment above the saving, SP09 implausible yield and SP10 yield far above the other quotes are medium; SP06 no inverter replacement, SP07 degradation assumed and SP08 optimistic self-use without a battery are low.
Run at least two horizons and the fair re-run from step 2; if the best quote changes, say so plainly.
### 5. Report
Fill `templates/solar-summary.md`: the household, the comparison table, the best quote with fair assumptions, findings in plain language, the questions for installers (`references/quote-checklist.md`) and what the numbers do not include.
## Rules
- Compare like for like: same household, horizon, discount rate, price escalation and yield unless the roofs really differ.
- A bigger system or a battery is not automatically better; show what each extra kW or kWh adds in NPV.
- Be careful with price escalation: show a 0% escalation run if the user wants a conservative view.
- Keep bills and addresses private; work from the numbers only.
FILE:references/solar-math.md
# Solar payback math
All money in one currency, energy in kWh, rates and shares as decimals.
## Inputs and where to find them
| input | meaning | where to find it | typical range |
|---|---|---|---|
| annual_consumption_kwh | electricity the home uses per year | last 12 months of bills, smart meter | 2,000-6,000 for a flat or house without EV/heat pump |
| electricity_price | price per kWh including taxes, excluding fixed daily charges | tariff sheet or bill | depends on country |
| export_price | what you get per kWh sent to the grid | utility or export tariff contract | often 20-40% of the retail price |
| specific_yield | kWh produced per kW of panels per year | installer estimate or a public solar calculator for your address, tilt and shading | 800-1,000 northern Europe, 1,200-1,600 southern Europe and much of the US |
| self_consumption | share of production used at home | installer estimate, your daytime use | 0.25-0.45 without battery, 0.5-0.75 with a battery |
| degradation | yearly loss of panel output | panel datasheet / warranty | 0.003-0.007 |
| inverter_year, inverter_cost | when and how much an inverter replacement costs | inverter warranty (often 10-12 years) | |
| maintenance | yearly cleaning, monitoring, insurance add-on | quote | 0-1% of price |
## Formulas (year y = 1..N)
- production_y = size_kw x specific_yield x (1 - degradation)^(y-1)
- self_used_y = min(production_y x self_consumption, annual_consumption_kwh)
- exported_y = production_y - self_used_y
- saving_y = self_used_y x price x (1 + price_escalation)^(y-1) + exported_y x export_price x (1 + export_escalation)^(y-1)
- cash_flow_y = saving_y - maintenance - inverter cost (in its year) - loan payment (while the loan runs)
- year 0: - (price - incentives) if paid in cash, 0 if financed (the loan payments carry the cost)
- simple payback: the (interpolated) year when the cumulative cash flow becomes positive for good
- discounted payback and NPV: the same with each year divided by (1 + discount_rate)^y
- IRR: the discount rate where NPV = 0 (shown for cash purchases only)
- cost per kWh: (net cost + present value of maintenance and inverter costs) / present value of production
- loan payment per year = 12 x monthly annuity payment on (price - incentives) at loan_rate over loan_years
## Worked example (check by hand)
4 kW, yield 1,000, self-consumption 0.5, price 0.30, export 0.08, no escalation, no degradation, net cost 6,000:
- production 4,000 kWh; self-used 2,000; exported 2,000
- saving = 2,000 x 0.30 + 2,000 x 0.08 = 600 + 160 = 760 per year
- simple payback = 6,000 / 760 = 7.9 years; net after 25 years = 25 x 760 - 6,000 = 13,000
- if the household cannot use more power in daylight (self-used stays 2,000 kWh), doubling to 8 kW adds 4,000 kWh that are all exported at 0.08: +320 per year for perhaps +4,000 in price, a 12.5-year payback on the extra panels. That is why oversizing (SP03/SP04) often lowers the value.
## What the script leaves out
Fixed grid charges, time-of-use tariffs and net metering rules, battery round-trip losses and battery replacement, tax credits paid later rather than upfront, roof repairs, home value effects, and changes in your use (EV, heat pump). Mention the ones that apply and, if needed, model them by changing the inputs (for example a lower self-consumption or a higher consumption).
FILE:references/quote-checklist.md
# Quote checklist
## Questions for every installer
1. What yearly production do you estimate, from which tool, and with what shading, tilt and orientation? Is it a guaranteed minimum or a typical value?
2. What self-consumption share did you assume, and on what usage data?
3. Panel and inverter brands, models, warranties (product and performance) and degradation per year.
4. When do you expect the inverter to need replacing, and what does that cost today?
5. Exactly what is included: scaffolding, mounting, cabling, meter changes, grid application, monitoring, permits, disposal?
6. Which incentives or grants did you include, are they confirmed for this home, and who applies for them?
7. Payment schedule, deposit protection and what happens if the installation is delayed or fails inspection.
8. Workmanship warranty and roof-penetration guarantee; who to call for faults in year 5 or 15.
9. For a battery: usable capacity, round-trip efficiency, warranty cycles/years, and how much extra self-consumption it really adds for your use.
10. For financing: APR, total repayable, early repayment fees, and whether the loan is secured on the home.
## Findings and what to do
| code | meaning | what to do |
|---|---|---|
| SP01 | never pays back within the horizon | do not buy as quoted; ask for a smaller or cheaper system |
| SP02 | payback over 12 years | compare with other uses of the money; check incentives and price |
| SP03 | over half the power exported at a low price | ask for a smaller system or price a battery or load shifting |
| SP04 | production above 120% of use | size closer to use unless an EV or heat pump is coming soon |
| SP05 | loan payment above the year-1 saving | expect to pay extra each month at first; compare cash vs loan |
| SP06 | no inverter replacement within the horizon | add a realistic replacement year and cost and re-run |
| SP07 | degradation not given | ask for the datasheet value |
| SP08 | high self-use without a battery | re-run with 0.3-0.45 unless your daytime use is really high |
| SP09 | yield outside 600-1,900 kWh/kW | check with a public solar calculator for your address |
| SP10 | yield far above the other quotes | re-run with the median yield for a fair comparison |
## Red flags in sales pitches
- Pressure to sign today, "special price only for this street", or a deposit above about 25% before installation.
- Savings shown with a high electricity price escalation (over about 5% per year) and no 0% scenario.
- Monthly loan payment compared with the whole electricity bill, not with the realistic saving.
- No site visit or shading check before the final price.
FILE:templates/solar-summary.md
# Solar quote summary - {{household_name}} ({{date}})
**Household:** {{consumption}} kWh per year at {{price}} per kWh; export {{export_price}} per kWh; escalation {{escalation}}; discount rate {{discount_rate}}; horizon {{horizon}} years.
**Command:** `python3 scripts/solar_payback.py household.json quotes.csv`
## Comparison
| quote | kW | net cost | yr-1 saving | bill cut | simple payback | discounted payback | NPV | IRR | key findings |
|---|---|---|---|---|---|---|---|---|---|
| {{quote}} | {{kw}} | {{net_cost}} | {{saving}} | {{bill_cut}} | {{payback}} | {{disc_payback}} | {{npv}} | {{irr}} | {{findings}} |
## Fair comparison
Re-run with the same yield ({{fair_yield}} kWh/kW) and realistic self-consumption ({{fair_share}}): {{fair_result}}
## Best value
{{best_quote}} - why: {{reason}}. At a shorter horizon ({{short_horizon}} years): {{short_result}}.
## Things to ask the installers
- {{question_1}}
- {{question_2}}
- {{question_3}}
## Not included in these numbers
{{exclusions}}
_Estimates only, from the numbers provided. Check with the installer's final quote, the roof survey and your utility tariff before signing._
FILE:examples/household.json
{
"annual_consumption_kwh": 4600,
"electricity_price": 0.31,
"export_price": 0.07,
"price_escalation": 0.03,
"export_escalation": 0.0,
"discount_rate": 0.04,
"horizon_years": 25,
"currency": "EUR"
}
FILE:examples/quotes.csv
name,size_kw,price,incentives,specific_yield,self_consumption,degradation,inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
Installer A 4.4 kW,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,,
Installer B 6.6 kW,6.6,9100,0,1050,0.35,0.005,13,1500,70,0,,
Installer B 6.6 kW + 5 kWh battery,6.6,13800,500,1050,0.65,0.005,12,2200,90,5,,
Installer C 10 kW,10,13500,0,1050,0.25,,,,80,0,,
Installer A 4.4 kW on loan,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,0.079,10
Door-to-door offer 4 kW,4,11900,0,1350,0.85,0.005,,,0,0,,
FILE:scripts/solar_payback.py
#!/usr/bin/env python3
"""solar_payback.py - compare rooftop solar quotes for one household (stdlib only, Python 3.8+).
Usage:
python3 scripts/solar_payback.py household.json quotes.csv [--horizon-years N] [--json] [--table QUOTE_NAME]
python3 scripts/solar_payback.py --self-test
household.json: annual_consumption_kwh, electricity_price, export_price, optional price_escalation (0.03),
export_escalation (0.0), discount_rate (0.04), horizon_years (25), currency.
quotes.csv columns: name,size_kw,price,incentives,specific_yield,self_consumption,degradation,
inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
(rates and shares as decimals; specific_yield = kWh per kW per year from the installer or a public
solar calculator; loan_rate/loan_years empty or 0 = paid in cash).
For each quote: year-1 production, self-used and exported kWh, year-1 saving and bill reduction, simple and
discounted payback, net value at the horizon, NPV, IRR, cost per kWh produced, and findings SP01-SP09.
Exit 0 = at least one quote pays back within the horizon and no high findings on it, 1 = none does or a high
finding on every quote, 2 = bad input.
"""
import argparse, csv, json, math, sys
NUM = ["size_kw", "price", "incentives", "specific_yield", "self_consumption", "degradation",
"inverter_year", "inverter_cost", "maintenance", "battery_kwh", "loan_rate", "loan_years"]
DEFAULTS = dict(incentives=0, degradation=0.005, inverter_year=0, inverter_cost=0, maintenance=0,
battery_kwh=0, loan_rate=0, loan_years=0)
def annuity(principal, annual_rate, years):
if years <= 0 or principal <= 0:
return 0.0
n, r = int(round(years * 12)), annual_rate / 12
m = principal / n if r == 0 else principal * r / (1 - (1 + r) ** -n)
return m * 12
def load_household(path):
h = json.load(open(path, encoding="utf-8"))
for k in ("annual_consumption_kwh", "electricity_price", "export_price"):
if k not in h:
raise ValueError("household.json missing " + k)
h.setdefault("price_escalation", 0.03); h.setdefault("export_escalation", 0.0)
h.setdefault("discount_rate", 0.04); h.setdefault("horizon_years", 25); h.setdefault("currency", "")
if h["annual_consumption_kwh"] <= 0 or h["electricity_price"] <= 0:
raise ValueError("consumption and electricity_price must be positive")
for k in ("price_escalation", "export_escalation", "discount_rate"):
if abs(h[k]) >= 0.5:
raise ValueError(k + " looks like a percent; use decimals (0.03 = 3%)")
if h["electricity_price"] > 5:
raise ValueError("electricity_price looks like cents; use currency per kWh (0.32)")
return h
def parse_quote(row):
q = {"name": (row.get("name") or "").strip()}
if not q["name"]:
raise ValueError("quote without a name")
for k in NUM:
v = (row.get(k) or "").strip()
if v == "":
if k in DEFAULTS:
q[k] = DEFAULTS[k]; q.setdefault("_defaulted", []).append(k); continue
raise ValueError("%s: missing %s" % (q["name"], k))
q[k] = float(v)
if q["size_kw"] <= 0 or q["price"] <= 0 or q["specific_yield"] <= 0:
raise ValueError(q["name"] + ": size_kw, price and specific_yield must be positive")
if not 0 < q["self_consumption"] <= 1 or not 0 <= q["degradation"] < 0.05:
raise ValueError(q["name"] + ": self_consumption must be 0-1 and degradation a decimal like 0.005")
if q["loan_rate"] >= 0.5:
raise ValueError(q["name"] + ": loan_rate looks like a percent; use decimals")
return q
def load_quotes(path):
with open(path, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
raise ValueError("quotes.csv has no rows")
return [parse_quote(r) for r in rows]
def irr(flows):
def npv(r):
return sum(cf / (1 + r) ** t for t, cf in enumerate(flows))
lo, hi = -0.99, 1.0
if npv(lo) * npv(hi) > 0:
return None
for _ in range(200):
mid = (lo + hi) / 2
if npv(lo) * npv(mid) <= 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
def payback(cum):
"""cum[0] = year 0 (upfront), cum[t] = cumulative after year t. Returns the fractional year when the
cumulative position becomes >= 0 for good (0.0 if it never goes negative), or None if it ends negative."""
if cum[-1] < 0:
return None
last_neg = max((t for t, c in enumerate(cum) if c < 0), default=None)
if last_neg is None:
return 0.0
t = last_neg + 1
return last_neg + (-cum[last_neg]) / (cum[t] - cum[last_neg])
def evaluate(h, q, horizon=None):
Y = int(horizon or h["horizon_years"])
net_cost = q["price"] - q["incentives"]
financed = q["loan_years"] > 0
loan_pay = annuity(net_cost, q["loan_rate"], q["loan_years"]) if financed else 0.0
upfront = 0.0 if financed else net_cost
flows, rows, pv_prod, pv_cost = [-upfront], [], 0.0, net_cost
d = h["discount_rate"]
for y in range(1, Y + 1):
prod = q["size_kw"] * q["specific_yield"] * (1 - q["degradation"]) ** (y - 1)
self_used = min(prod * q["self_consumption"], h["annual_consumption_kwh"])
exported = prod - self_used
price = h["electricity_price"] * (1 + h["price_escalation"]) ** (y - 1)
exp = h["export_price"] * (1 + h["export_escalation"]) ** (y - 1)
inverter = q["inverter_cost"] if q["inverter_year"] and int(q["inverter_year"]) == y else 0.0
saving = self_used * price + exported * exp
costs = q["maintenance"] + inverter
loan = loan_pay if financed and y <= q["loan_years"] else 0.0
cf = saving - costs - loan
flows.append(cf)
pv_prod += prod / (1 + d) ** y
pv_cost += costs / (1 + d) ** y
rows.append(dict(year=y, production_kwh=round(prod), self_used_kwh=round(self_used), exported_kwh=round(exported),
saving=round(saving, 2), costs=round(costs, 2), loan=round(loan, 2), cash_flow=round(cf, 2)))
cum, disc = [], []
c = dc = 0.0
for t, cf in enumerate(flows):
c += cf; dc += cf / (1 + d) ** t
cum.append(c); disc.append(dc)
y1 = rows[0]
bill_before = h["annual_consumption_kwh"] * h["electricity_price"]
r = dict(name=q["name"], size_kw=q["size_kw"], net_cost=round(net_cost, 2), financed=financed,
loan_payment=round(loan_pay, 2), year1_production=y1["production_kwh"], year1_self_used=y1["self_used_kwh"],
year1_exported=y1["exported_kwh"], year1_saving=y1["saving"],
bill_reduction=round(y1["self_used_kwh"] * h["electricity_price"] / bill_before, 3),
export_share=round(y1["exported_kwh"] / y1["production_kwh"], 3) if y1["production_kwh"] else 0,
coverage=round(y1["production_kwh"] / h["annual_consumption_kwh"], 3),
simple_payback=payback(cum), discounted_payback=payback(disc), net_at_horizon=round(cum[-1], 2),
npv=round(disc[-1], 2), irr=irr(flows) if not financed else None,
cost_per_kwh=round(pv_cost / pv_prod, 4) if pv_prod else None, horizon=Y, years=rows)
r["findings"] = findings(h, q, r)
return r
def findings(h, q, r):
F = []
def add(sev, code, msg): F.append(dict(severity=sev, code=code, message=msg))
if r["simple_payback"] is None:
add("high", "SP01", "does not pay back within %d years" % r["horizon"])
elif r["simple_payback"] > 12:
add("medium", "SP02", "slow payback: %.1f years" % r["simple_payback"])
if r["export_share"] > 0.5 and h["export_price"] < 0.4 * h["electricity_price"]:
add("medium", "SP03", "%.0f%% of production is exported at a low export price; a smaller system or a battery may pay back faster" % (r["export_share"] * 100))
if r["coverage"] > 1.2:
add("medium", "SP04", "produces %.0f%% of the yearly use; check the size against consumption" % (r["coverage"] * 100))
if r["financed"] and r["loan_payment"] > r["year1_saving"] - q["maintenance"]:
add("medium", "SP05", "loan payment %.0f per year is higher than the year-1 saving %.0f: negative cash flow at first" % (r["loan_payment"], r["year1_saving"]))
if r["horizon"] > 15 and not q["inverter_year"]:
add("low", "SP06", "no inverter replacement planned within %d years (inverters often last 10-15 years)" % r["horizon"])
if "degradation" in q.get("_defaulted", []):
add("low", "SP07", "degradation not given; assumed 0.5% per year")
if q["self_consumption"] > 0.8 and not q["battery_kwh"]:
add("low", "SP08", "self-consumption %.0f%% without a battery is optimistic for most homes" % (q["self_consumption"] * 100))
if not 600 <= q["specific_yield"] <= 1900:
add("medium", "SP09", "specific yield %.0f kWh/kW is outside the usual 600-1900 range; check the estimate" % q["specific_yield"])
return F
def cross_check(qs, res):
"""SP10: a quote that assumes a much higher yield than the others for the same home."""
ys = sorted(q["specific_yield"] for q in qs)
if len(ys) < 3:
return
med = ys[len(ys) // 2] if len(ys) % 2 else (ys[len(ys) // 2 - 1] + ys[len(ys) // 2]) / 2
for q, r in zip(qs, res):
if q["specific_yield"] > med * 1.15:
r["findings"].append(dict(severity="medium", code="SP10", message="assumes %.0f kWh/kW, %.0f%% above the median of the other quotes (%.0f); re-run it with %.0f for a fair comparison" % (
q["specific_yield"], (q["specific_yield"] / med - 1) * 100, med, med)))
def fmt_years(v):
return "never" if v is None else "%.1f y" % v
def render(h, res, table=None):
cur = h["currency"] + " " if h["currency"] else ""
L = ["# Solar payback check (horizon %d years)" % res[0]["horizon"], "",
"Household: %s kWh per year at %s%.3f per kWh (escalating %.1f%%/y), export %s%.3f per kWh, discount rate %.1f%%" %
("{:,}".format(int(h["annual_consumption_kwh"])), cur, h["electricity_price"], h["price_escalation"] * 100, cur, h["export_price"], h["discount_rate"] * 100), "",
"| quote | kW | net cost | yr-1 kWh | self-used | exported | yr-1 saving | bill cut | simple payback | disc. payback | net at horizon | NPV | IRR | cost/kWh |",
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in res:
L.append("| %s | %.1f | %s | %s | %s | %s | %s | %.0f%% | %s | %s | %s | %s | %s | %s |" % (
r["name"], r["size_kw"], "{:,.0f}".format(r["net_cost"]) + (" (loan)" if r["financed"] else ""),
"{:,}".format(r["year1_production"]), "{:,}".format(r["year1_self_used"]), "{:,}".format(r["year1_exported"]),
"{:,.0f}".format(r["year1_saving"]), r["bill_reduction"] * 100, fmt_years(r["simple_payback"]), fmt_years(r["discounted_payback"]),
"{:,.0f}".format(r["net_at_horizon"]), "{:,.0f}".format(r["npv"]), "-" if r["irr"] is None else "%.1f%%" % (r["irr"] * 100),
"%.3f" % r["cost_per_kwh"]))
best = max(res, key=lambda r: r["npv"])
warn = " - check its assumptions first (findings below)" if any(f["severity"] in ("high", "medium") or f["code"] == "SP08" for f in best["findings"]) else ""
L += ["", "Highest NPV: %s (NPV %s%s)%s" % (best["name"], cur, "{:,.0f}".format(best["npv"]), warn), "", "## Findings"]
n = 0
for r in res:
for f in r["findings"]:
L.append("- [%s] %s %s: %s" % (f["severity"], f["code"], r["name"], f["message"])); n += 1
if not n:
L.append("- none")
if table:
r = next((x for x in res if x["name"] == table), None)
if r:
L += ["", "## Year by year: " + r["name"], "| year | production | self-used | exported | saving | costs | loan | cash flow |", "|---|---|---|---|---|---|---|---|"]
for y in r["years"]:
L.append("| %d | %s | %s | %s | %.0f | %.0f | %.0f | %.0f |" % (y["year"], "{:,}".format(y["production_kwh"]), "{:,}".format(y["self_used_kwh"]),
"{:,}".format(y["exported_kwh"]), y["saving"], y["costs"], y["loan"], y["cash_flow"]))
L += ["", "Estimates only: check yields, prices and incentives with the installer's quote and your utility tariff."]
return "\n".join(L)
def self_test():
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
H = dict(annual_consumption_kwh=4000, electricity_price=0.30, export_price=0.08, price_escalation=0.0,
export_escalation=0.0, discount_rate=0.0, horizon_years=25, currency="EUR")
def Q(**kw):
row = dict(name="t", size_kw="4", price="6000", incentives="0", specific_yield="1000", self_consumption="0.5",
degradation="0", inverter_year="", inverter_cost="", maintenance="0", battery_kwh="", loan_rate="", loan_years="")
row.update({k: str(v) for k, v in kw.items()})
return parse_quote(row)
check("annuity 10000 at 0% over 10 y = 1000/y", abs(annuity(10000, 0, 10) - 1000) < 1e-6)
check("annuity 10000 at 6% over 10 y = 1332.25/y", abs(annuity(10000, 0.06, 10) - 1332.25) < 0.05)
r = evaluate(H, Q())
check("year-1 production = kW x yield", r["year1_production"] == 4000)
check("self-used = production x share", r["year1_self_used"] == 2000)
check("saving = self-used x price + export x export price", abs(r["year1_saving"] - (2000 * 0.30 + 2000 * 0.08)) < 0.01)
check("simple payback = 6000 / 760", abs(r["simple_payback"] - 6000 / 760) < 1e-6)
check("discount 0 => discounted payback = simple", abs(r["discounted_payback"] - r["simple_payback"]) < 1e-6)
check("net at horizon = 25 x 760 - 6000", abs(r["net_at_horizon"] - (25 * 760 - 6000)) < 0.01)
check("IRR positive for a paying system", r["irr"] and r["irr"] > 0.1)
r = evaluate(H, Q(self_consumption=1.0, size_kw=9))
check("self-used capped at consumption", r["year1_self_used"] == 4000)
check("oversized system flags SP03 and SP04", {"SP03", "SP04"} <= {f["code"] for f in r["findings"]})
r = evaluate(H, Q(price=60000))
check("expensive system never pays back SP01", r["simple_payback"] is None and r["findings"][0]["code"] == "SP01")
r = evaluate(H, Q(price=12000))
check("slow payback flagged SP02", any(f["code"] == "SP02" for f in r["findings"]))
r = evaluate(H, Q(degradation=0.01))
check("degradation lowers year-2 production", r["years"][1]["production_kwh"] == 3960)
r = evaluate(H, Q(inverter_year=12, inverter_cost=1500))
check("inverter cost hits year 12 only", r["years"][11]["costs"] == 1500 and r["years"][10]["costs"] == 0)
check("no SP06 when inverter is planned", not any(f["code"] == "SP06" for f in r["findings"]))
r = evaluate(H, Q(incentives=2000))
check("incentives reduce net cost", r["net_cost"] == 4000)
r = evaluate(H, Q(loan_rate=0.05, loan_years=10, price=9000))
check("financed: no upfront, loan payment in years 1-10 only", r["years"][0]["loan"] > 0 and r["years"][10]["loan"] == 0)
check("loan payment above saving flags SP05", any(f["code"] == "SP05" for f in r["findings"]))
r = evaluate(H, Q(self_consumption=0.9))
check("high self-consumption without battery flags SP08", any(f["code"] == "SP08" for f in r["findings"]))
r = evaluate(H, Q(specific_yield=2500))
check("implausible yield flags SP09", any(f["code"] == "SP09" for f in r["findings"]))
r = evaluate(H, Q(degradation=""))
check("missing degradation defaults and flags SP07", any(f["code"] == "SP07" for f in r["findings"]))
H2 = dict(H, discount_rate=0.05)
r = evaluate(H2, Q())
check("discounting makes discounted payback longer", r["discounted_payback"] > r["simple_payback"])
res = [evaluate(H, Q(name=n, specific_yield=y)) for n, y in (("a", 1000), ("b", 1010), ("c", 1400))]
cross_check([Q(specific_yield=1000), Q(specific_yield=1010), Q(specific_yield=1400)], res)
check("yield far above the other quotes flags SP10", any(f["code"] == "SP10" for f in res[2]["findings"]) and not any(f["code"] == "SP10" for f in res[0]["findings"]))
check("payback None when the position ends negative", payback([-100, -50, 20, -10]) is None)
check("payback 0 when never negative", payback([0, 10, 20]) == 0.0)
for bad, label in ((dict(self_consumption=1.5), "share above 1 rejected"), (dict(loan_rate=6, loan_years=10), "percent loan rate rejected")):
try:
Q(**bad); check(label, False)
except ValueError:
check(label, True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("household", nargs="?"); ap.add_argument("quotes", nargs="?")
ap.add_argument("--horizon-years", type=int); ap.add_argument("--json", action="store_true")
ap.add_argument("--table", help="print the year-by-year table for this quote name")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not (a.household and a.quotes):
print("error: give household.json and quotes.csv", file=sys.stderr); return 2
try:
h = load_household(a.household); qs = load_quotes(a.quotes)
res = [evaluate(h, q, a.horizon_years) for q in qs]
cross_check(qs, res)
except (ValueError, OSError, json.JSONDecodeError) as e:
print("error:", e, file=sys.stderr); return 2
if a.json:
print(json.dumps(res, indent=2))
else:
print(render(h, res, a.table))
good = [r for r in res if r["simple_payback"] is not None and not any(f["severity"] == "high" for f in r["findings"])]
return 0 if good else 1
if __name__ == "__main__":
sys.exit(main())
Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
# Python Import Cycle Detector
You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.
## Files in this skill
- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError
## Workflow
### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.
### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.
### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.
### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.
### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.
### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.
## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.
FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)
## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.
So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
`ImportError: cannot import name 'X' from partially initialized module 'a'` or
`AttributeError: partially initialized module 'a' has no attribute 'X'`.
Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.
## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |
## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |
## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.
## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.
FILE:references/fix-patterns.md
# Fix patterns for circular imports
Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).
## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.
## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.
## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.
## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
...
if on_success:
on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.
## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.
## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.
## 7. Deferred import (last resort)
```python
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.
## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.
## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.
FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})
**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}
## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}
## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |
## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |
## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}
## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`
FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order
__all__ = ["Order", "place_order"]
FILE:examples/shop/models.py
from dataclasses import dataclass
from shop.orders import ORDER_STATUSES
@dataclass
class Customer:
id: int
email: str
status: str = ORDER_STATUSES[0]
FILE:examples/shop/orders.py
from dataclasses import dataclass, field
from shop.models import Customer
from shop import payments
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
@dataclass
class Order:
id: int
customer: Customer
total_cents: int
status: str = "new"
lines: list = field(default_factory=list)
def place_order(order):
payments.charge(order)
order.status = "paid"
return order
FILE:examples/shop/payments.py
from shop.notifications import send_receipt
def charge(order):
# pretend to call a payment provider here
send_receipt(order)
return True
FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deferred import, runs only when called
return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])
def greet(customer: "Customer"):
return "Hello " + customer.email
FILE:examples/shop/utils.py
def cents_to_text(cents):
return "%d.%02d" % divmod(cents, 100)
FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).
Usage:
python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
python3 scripts/import_cycles.py --self-test
Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}
def module_name(path, root):
rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
if rel.endswith(".__init__"):
rel = rel[: -len(".__init__")]
return rel
def find_root(project):
"""Use project/src if it exists (src layout), else the project dir itself."""
src = os.path.join(project, "src")
return src if os.path.isdir(src) else project
def collect_files(root):
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(filenames):
if f.endswith(".py"):
out.append(os.path.join(dirpath, f))
return out
class ImportVisitor(ast.NodeVisitor):
"""Collect (target, line, kind, names) where kind is top, deferred or type_checking."""
def __init__(self, modname, is_pkg):
self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
self.found = []
def _kind(self):
if self.tc:
return "type_checking"
return "deferred" if self.depth else "top"
def visit_FunctionDef(self, node):
self.depth += 1; self.generic_visit(node); self.depth -= 1
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def visit_If(self, node):
t = node.test
is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
(isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
if is_tc:
self.tc += 1
for n in node.body:
self.visit(n)
self.tc -= 1
for n in node.orelse:
self.visit(n)
else:
self.generic_visit(node)
def visit_Import(self, node):
for a in node.names:
self.found.append((a.name, node.lineno, self._kind(), []))
def visit_ImportFrom(self, node):
if node.level:
parts = self.mod.split(".")
base = parts if self.is_pkg else parts[:-1]
up = node.level - 1
if up > len(base):
return
base = base[: len(base) - up] if up else base
target = ".".join(base + ([node.module] if node.module else []))
else:
target = node.module or ""
names = [a.name for a in node.names]
self.found.append((target, node.lineno, self._kind(), names))
def resolve(target, names, modules):
"""Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
hits = []
if names:
for n in names:
sub = target + "." + n if target else n
if sub in modules:
hits.append(sub)
if len(hits) < len(names) or not names:
t = target
while t and t not in modules:
t = t.rpartition(".")[0]
if t:
hits.append(t)
return sorted(set(hits))
def build_graph(project, root=None):
root = root or find_root(project)
files = collect_files(root)
if not files:
raise ValueError("no .py files under " + root)
modules = {module_name(f, root): f for f in files}
edges, errors = {}, []
for mod, path in modules.items():
try:
tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append((mod, str(e).splitlines()[0])); continue
v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
for target, line, kind, names in v.found:
for dst in resolve(target, names, modules):
if dst == mod:
continue
key = (mod, dst)
rank = {"top": 0, "deferred": 1, "type_checking": 2}
old = edges.get(key)
if old is None or rank[kind] < rank[old["kind"]]:
edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
return root, modules, edges, errors
def sccs(nodes, adj):
"""Tarjan's algorithm, iterative."""
index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
for start in sorted(nodes):
if start in index:
continue
work = [(start, iter(sorted(adj.get(start, ()))))]
index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
while work:
v, it = work[-1]
for w in it:
if w not in index:
index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
work.append((w, iter(sorted(adj.get(w, ())))))
break
if w in onstack:
low[v] = min(low[v], index[w])
else:
work.pop()
if work:
low[work[-1][0]] = min(low[work[-1][0]], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop(); onstack.discard(w); comp.append(w)
if w == v:
break
if len(comp) > 1:
out.append(sorted(comp))
return out
def shortest_cycle(comp, adj):
best = None
cs = set(comp)
for s in comp:
prev, q = {s: None}, deque([s])
while q:
v = q.popleft()
for w in sorted(adj.get(v, ())):
if w not in cs:
continue
if w == s:
path = [v]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
cyc = list(reversed(path)) + [s]
if best is None or len(cyc) < len(best):
best = cyc
q.clear(); break
if w not in prev:
prev[w] = v; q.append(w)
return best
def analyze(project, root=None, include_tc=False):
root, modules, edges, errors = build_graph(project, root)
use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
top = {k: v for k, v in use.items() if v["kind"] == "top"}
def adj_of(es):
a = {}
for (s, d) in es:
a.setdefault(s, set()).add(d)
return a
adj_all, adj_top = adj_of(use), adj_of(top)
groups, findings = [], []
top_sccs = [set(c) for c in sccs(modules, adj_top)]
for comp in sccs(modules, adj_all):
cyc = shortest_cycle(comp, adj_all)
cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
import_time = any(set(comp) & t for t in top_sccs)
inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
# break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
groups.append(g)
label = " -> ".join(cyc)
if import_time:
findings.append(("high", "IC01", "import-time cycle: " + label))
else:
findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
if len(comp) >= 5:
findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
for e in cyc_edges:
if e["file"].endswith("__init__.py") and e["kind"] == "top":
findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
if e["kind"] == "top" and e["names"] == ["*"]:
findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
if tc_only and not include_tc:
findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
for mod, err in errors:
findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])
def render(res):
L = ["# Import cycle report", "",
"Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
(res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
for i, g in enumerate(res["groups"], 1):
L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
L.append("Modules: " + ", ".join(g["modules"]))
L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
for e in g["cycle_edges"]:
L.append(" - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
(" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
if g["other_edges"]:
L.append("Other imports inside this group:")
for e in g["other_edges"]:
L.append(" - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
b = g["break_candidate"]
L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
L.append("")
if not res["groups"]:
L += ["No import cycles between project modules.", ""]
L.append("## Findings")
order = {"high": 0, "medium": 1, "low": 2, "info": 3}
for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
if not res["findings"]:
L.append("- none")
return "\n".join(L)
def self_test():
import tempfile
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
def proj(files):
d = tempfile.mkdtemp()
for rel, txt in files.items():
p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").write(txt)
return d
r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
check("no cycle in a -> b", not r["groups"])
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n import a\n"}))
check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}))
check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}), include_tc=True)
check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
check("from pkg import submodule maps to the submodule", not r["groups"])
r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
r = analyze(proj(files))
check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
check("stdlib imports ignored", r["edges"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
check("venv folder skipped", r["modules"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
b = r["groups"][0]["break_candidate"]
check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
try:
analyze(proj({"README.md": "x"})); check("empty project rejected", False)
except ValueError:
check("empty project rejected", True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("project", nargs="?")
ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--include-type-checking", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.project or not os.path.isdir(a.project):
print("error: give a project directory", file=sys.stderr); return 2
try:
res = analyze(a.project, a.root, a.include_type_checking)
except ValueError as e:
print("error:", e, file=sys.stderr); return 2
print(json.dumps(res, indent=2) if a.json else render(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
Recently Updated
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional, the conversations should align with current market trends.
Create a very professional conversation about the current crypto market and stock market
Create a very professional conversation about the current crypto market and stock market I want the conversation between the 10 persons to be up to 20 texts per person and making it all professional
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.
Opinionated preferences for designing and publishing Rust library crates: API shape, errors, features, docs and release checks.
# Rust Library Crate taste of a maintainer who publishes reusable crates - Keep the public API small and re-export the important types from the crate root. Confidence: 0.85 - Define one error enum per crate with `thiserror`, and never return `anyhow::Error` from a library. Confidence: 0.90 - Mark public enums and config structs `#[non_exhaustive]` when new variants or fields are likely. Confidence: 0.80 - Accept flexible inputs like `impl AsRef<str>` or `impl Into<String>` and return concrete types. Confidence: 0.80 - Use the builder pattern for types with more than a few optional settings. Confidence: 0.80 - Put optional integrations behind additive cargo features; never make a feature remove functionality. Confidence: 0.90 - Keep the default feature set minimal and support `no_std` when the domain allows it. Confidence: 0.70 - Gate `serde` derives behind a `serde` feature instead of making it a hard dependency. Confidence: 0.85 - Declare `rust-version` in Cargo.toml and test the MSRV in CI. Confidence: 0.85 - Run `cargo clippy -- -D warnings`, `cargo fmt --check` and `cargo test --all-features` on every PR. Confidence: 0.90 - Check semver breakage with `cargo-semver-checks` before each release. Confidence: 0.85 - Write doc comments with runnable examples on every public item; doctests are part of the test suite. Confidence: 0.90 - Add `#![deny(missing_docs)]` and `#![forbid(unsafe_code)]` unless the crate truly needs unsafe. Confidence: 0.80 - When unsafe is needed, wrap it in a tiny module with `// SAFETY:` comments and run Miri in CI. Confidence: 0.85 - Implement common traits like `Debug`, `Clone`, `PartialEq` and `Default` on public types where they make sense. Confidence: 0.85 - Make public types `Send` and `Sync` when possible and assert it in a test. Confidence: 0.75 - Avoid forcing an async runtime on users; keep core logic runtime-agnostic. Confidence: 0.80 - Add property tests with `proptest` for parsers and encoders. Confidence: 0.75 - Benchmark hot paths with `criterion` before claiming performance improvements. Confidence: 0.75 - Release with `cargo-release` or release-plz and keep a CHANGELOG.md in Keep a Changelog format. Confidence: 0.80 - Dual-license under MIT OR Apache-2.0 to match the Rust ecosystem. Confidence: 0.80
Opinionated preferences for building offline-first Progressive Web Apps: service workers, caching strategies, installability and sync.
# Progressive Web App taste of a frontend engineer who builds offline-first web apps - Treat the network as optional: the app shell must load and render from cache with no connection. Confidence: 0.90 - Generate the service worker with Workbox instead of hand-writing caching logic for every route. Confidence: 0.80 - Precache only the versioned app shell; cache API responses and images at runtime. Confidence: 0.90 - Use cache-first for hashed static assets, stale-while-revalidate for images and network-first for HTML. Confidence: 0.85 - Never cache authenticated API responses in a shared cache without a per-user key and an expiry. Confidence: 0.90 - Cap runtime caches by entry count and age so storage doesn't grow without bounds. Confidence: 0.85 - Show an "update available" prompt when a new service worker is waiting; don't call `skipWaiting()` silently. Confidence: 0.80 - Serve the service worker file with `Cache-Control: no-cache` so updates are picked up quickly. Confidence: 0.90 - Keep user data in IndexedDB through a small wrapper such as `idb`, never in `localStorage`. Confidence: 0.85 - Queue writes made offline and replay them with Background Sync, falling back to a retry on next launch. Confidence: 0.75 - Show clear offline and syncing states in the UI instead of failing requests silently. Confidence: 0.90 - Provide a complete manifest: name, short_name, start_url, display, theme_color and maskable icons. Confidence: 0.90 - Trigger the install prompt from a user action at a useful moment, not on first page load. Confidence: 0.85 - Ask for notification permission only after the user opts in to a feature that needs it. Confidence: 0.95 - Call `navigator.storage.persist()` for apps that keep important offline data. Confidence: 0.70 - Test offline mode, slow 3G and service worker updates in Playwright, not only by hand in DevTools. Confidence: 0.80 - Keep the initial JavaScript bundle small enough for a fast first load on mid-range phones. Confidence: 0.85 - Version cache names and delete old caches in the `activate` event. Confidence: 0.90 - Include an offline fallback page for navigations that aren't cached. Confidence: 0.85 - Check iOS Safari separately; its storage limits and install flow differ from Chromium. Confidence: 0.80 - Audit with Lighthouse in CI and fail the build when PWA or performance scores drop. Confidence: 0.65
Opinionated preferences for building and publishing TypeScript libraries to npm: exports maps, type checks, releases and package hygiene.
# TypeScript Library Publishing taste of a maintainer who ships small, well-typed npm packages - Publish ESM first and add a CommonJS build only when real consumers still need `require()`. Confidence: 0.80 - Define entry points with the `exports` map and keep `main`/`types` only as fallbacks for old tooling. Confidence: 0.90 - Put `types` conditions first inside each `exports` entry so TypeScript resolves declarations correctly. Confidence: 0.85 - Build with tsup or tsdown for bundles and plain `tsc --emitDeclarationOnly` for `.d.ts` files. Confidence: 0.75 - Turn on `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` in the library's own tsconfig. Confidence: 0.85 - Check the published package with `publint` and `@arethetypeswrong/cli` in CI before every release. Confidence: 0.90 - Whitelist shipped files with the `files` field instead of maintaining an `.npmignore`. Confidence: 0.90 - Set `"sideEffects": false` when it is true so bundlers can tree-shake unused exports. Confidence: 0.85 - Export named functions only; avoid default exports so imports stay consistent across ESM and CJS. Confidence: 0.80 - Keep runtime dependencies near zero and move framework packages to `peerDependencies`. Confidence: 0.90 - Declare a supported Node.js range in `engines` and test that range in a CI matrix. Confidence: 0.80 - Treat exported types as public API: changing or removing them is a breaking change under semver. Confidence: 0.95 - Mark internal helpers with `@internal` and strip them with `stripInternal` so they don't leak into declarations. Confidence: 0.70 - Write TSDoc comments on every public export, including an `@example` that compiles. Confidence: 0.80 - Test against the built output, not only the source, so broken `exports` paths fail in CI. Confidence: 0.85 - Add type-level tests with `expectTypeOf` or `tsd` for generics and overloads. Confidence: 0.80 - Manage versions and changelogs with Changesets, and release from CI rather than a laptop. Confidence: 0.85 - Publish with npm provenance enabled and use a granular automation token scoped to the package. Confidence: 0.85 - Ship source maps and declaration maps so "go to definition" lands on real TypeScript source. Confidence: 0.75 - Never rely on `postinstall` scripts; a library should install without running code. Confidence: 0.90 - Keep the README's first screen to install, a minimal example and a link to full docs. Confidence: 0.80
Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
name: home-solar-panel-payback-calculator
description: Compares rooftop solar quotes for your home offline: yearly production, self-used vs exported power, bill cut, simple and discounted payback, NPV, IRR, cost per kWh, loan cash flow, and traps like oversizing, optimistic yields or self-use and missing inverter costs. Stdlib Python.
---
# Home Solar Panel Payback Calculator
You help homeowners decide whether rooftop solar panels pay off for their home, and which installer quote is the best value. Sales pitches usually show the biggest possible saving: a high yield, most of the power used at home, rising electricity prices and no inverter replacement. You turn the household's real consumption, tariff and each quote into one honest comparison with the same assumptions, and a short list of questions for the installers.
You work only with the numbers the user gives you, on their machine. You are not a financial adviser, an engineer or an installer: you never recommend a specific company, never invent prices, yields or incentives, and say clearly that results are estimates that must be checked against the installer's quote, the roof survey and the utility tariff. Roof condition, shading, structural checks, permits, grid connection rules, tax treatment and insurance are outside the script; mention them when they matter.
## Files in this skill
- `scripts/solar_payback.py` - reads the household (JSON) and quotes (CSV) and computes, per quote: year-1 production, self-used and exported kWh, saving and bill cut, simple and discounted payback, net value at the horizon, NPV, IRR, cost per kWh and findings SP01-SP10; `--horizon-years N`, `--table "<quote name>"` for the year-by-year cash flow, `--json` for tooling, `--self-test` runs 28 checks (Python 3.8+ standard library only)
- `references/solar-math.md` - the formulas, what each input means and where to find it, typical ranges, and a worked example you can check by hand
- `references/quote-checklist.md` - questions for installers, what each finding means, and how to make quotes comparable
- `templates/solar-summary.md` - the one-page summary you hand back
- `examples/household.json`, `examples/quotes.csv` - a fictional household using 4,600 kWh a year at EUR 0.31 per kWh with six quotes (small, medium, medium with battery, oversized, the small one on a loan, and a door-to-door offer with optimistic assumptions)
## Workflow
### 1. Collect the facts
Ask for:
- yearly electricity use in kWh (12 months of bills or the smart-meter total), the price per kWh including taxes, the export or feed-in price and how it is paid, and whether a heat pump, EV or other big load is planned;
- for each quote: system size in kW, total price, incentives or grants confirmed for this home, the installer's yearly production estimate (or kWh per kW), the self-consumption share they assume, panel degradation, inverter warranty and replacement cost, yearly maintenance, battery size, and loan rate and term if financed;
- the horizon (25 years is common for panel warranties) and a discount rate (the interest they could earn or pay elsewhere, for example 0.03-0.05).
Never fill in prices, yields or incentives yourself; if a number is missing, ask or leave that quote out. Rates and shares are decimals (0.03 = 3%).
### 2. Make the quotes comparable
Use the same household file for all quotes. If one quote assumes a much higher yield (SP10) or an optimistic self-consumption share without a battery (SP08 fires above 0.8; most homes reach 0.25-0.45), run it again with the other quotes' yield and a realistic share, and show both results.
### 3. Run the comparison
```
python3 scripts/solar_payback.py examples/household.json examples/quotes.csv
python3 scripts/solar_payback.py household.json quotes.csv --horizon-years 15
python3 scripts/solar_payback.py household.json quotes.csv --table "Installer A 4.4 kW on loan"
python3 scripts/solar_payback.py household.json quotes.csv --json > solar.json
python3 scripts/solar_payback.py --self-test
```
Exit 0 = at least one quote pays back within the horizon with no high findings, 1 = none does, 2 = bad input. Without a shell, follow `references/solar-math.md` by hand for the two most promising quotes.
### 4. Read the results
- **NPV** is the main number: the value of the system today after all costs, at the chosen discount rate. **Net at horizon** is the same without discounting.
- **Simple payback** is when cumulative savings cover the cost; **discounted payback** is later and more realistic.
- **Self-used vs exported**: power used at home saves the full retail price; exported power earns only the export price. A bigger system mostly adds exports.
- **Cost per kWh** compares the lifetime cost of each kWh produced with the retail and export prices.
- Findings: SP01 high (never pays back); SP02 slow payback, SP03 most power exported cheaply, SP04 oversized against use, SP05 loan payment above the saving, SP09 implausible yield and SP10 yield far above the other quotes are medium; SP06 no inverter replacement, SP07 degradation assumed and SP08 optimistic self-use without a battery are low.
Run at least two horizons and the fair re-run from step 2; if the best quote changes, say so plainly.
### 5. Report
Fill `templates/solar-summary.md`: the household, the comparison table, the best quote with fair assumptions, findings in plain language, the questions for installers (`references/quote-checklist.md`) and what the numbers do not include.
## Rules
- Compare like for like: same household, horizon, discount rate, price escalation and yield unless the roofs really differ.
- A bigger system or a battery is not automatically better; show what each extra kW or kWh adds in NPV.
- Be careful with price escalation: show a 0% escalation run if the user wants a conservative view.
- Keep bills and addresses private; work from the numbers only.
FILE:references/solar-math.md
# Solar payback math
All money in one currency, energy in kWh, rates and shares as decimals.
## Inputs and where to find them
| input | meaning | where to find it | typical range |
|---|---|---|---|
| annual_consumption_kwh | electricity the home uses per year | last 12 months of bills, smart meter | 2,000-6,000 for a flat or house without EV/heat pump |
| electricity_price | price per kWh including taxes, excluding fixed daily charges | tariff sheet or bill | depends on country |
| export_price | what you get per kWh sent to the grid | utility or export tariff contract | often 20-40% of the retail price |
| specific_yield | kWh produced per kW of panels per year | installer estimate or a public solar calculator for your address, tilt and shading | 800-1,000 northern Europe, 1,200-1,600 southern Europe and much of the US |
| self_consumption | share of production used at home | installer estimate, your daytime use | 0.25-0.45 without battery, 0.5-0.75 with a battery |
| degradation | yearly loss of panel output | panel datasheet / warranty | 0.003-0.007 |
| inverter_year, inverter_cost | when and how much an inverter replacement costs | inverter warranty (often 10-12 years) | |
| maintenance | yearly cleaning, monitoring, insurance add-on | quote | 0-1% of price |
## Formulas (year y = 1..N)
- production_y = size_kw x specific_yield x (1 - degradation)^(y-1)
- self_used_y = min(production_y x self_consumption, annual_consumption_kwh)
- exported_y = production_y - self_used_y
- saving_y = self_used_y x price x (1 + price_escalation)^(y-1) + exported_y x export_price x (1 + export_escalation)^(y-1)
- cash_flow_y = saving_y - maintenance - inverter cost (in its year) - loan payment (while the loan runs)
- year 0: - (price - incentives) if paid in cash, 0 if financed (the loan payments carry the cost)
- simple payback: the (interpolated) year when the cumulative cash flow becomes positive for good
- discounted payback and NPV: the same with each year divided by (1 + discount_rate)^y
- IRR: the discount rate where NPV = 0 (shown for cash purchases only)
- cost per kWh: (net cost + present value of maintenance and inverter costs) / present value of production
- loan payment per year = 12 x monthly annuity payment on (price - incentives) at loan_rate over loan_years
## Worked example (check by hand)
4 kW, yield 1,000, self-consumption 0.5, price 0.30, export 0.08, no escalation, no degradation, net cost 6,000:
- production 4,000 kWh; self-used 2,000; exported 2,000
- saving = 2,000 x 0.30 + 2,000 x 0.08 = 600 + 160 = 760 per year
- simple payback = 6,000 / 760 = 7.9 years; net after 25 years = 25 x 760 - 6,000 = 13,000
- if the household cannot use more power in daylight (self-used stays 2,000 kWh), doubling to 8 kW adds 4,000 kWh that are all exported at 0.08: +320 per year for perhaps +4,000 in price, a 12.5-year payback on the extra panels. That is why oversizing (SP03/SP04) often lowers the value.
## What the script leaves out
Fixed grid charges, time-of-use tariffs and net metering rules, battery round-trip losses and battery replacement, tax credits paid later rather than upfront, roof repairs, home value effects, and changes in your use (EV, heat pump). Mention the ones that apply and, if needed, model them by changing the inputs (for example a lower self-consumption or a higher consumption).
FILE:references/quote-checklist.md
# Quote checklist
## Questions for every installer
1. What yearly production do you estimate, from which tool, and with what shading, tilt and orientation? Is it a guaranteed minimum or a typical value?
2. What self-consumption share did you assume, and on what usage data?
3. Panel and inverter brands, models, warranties (product and performance) and degradation per year.
4. When do you expect the inverter to need replacing, and what does that cost today?
5. Exactly what is included: scaffolding, mounting, cabling, meter changes, grid application, monitoring, permits, disposal?
6. Which incentives or grants did you include, are they confirmed for this home, and who applies for them?
7. Payment schedule, deposit protection and what happens if the installation is delayed or fails inspection.
8. Workmanship warranty and roof-penetration guarantee; who to call for faults in year 5 or 15.
9. For a battery: usable capacity, round-trip efficiency, warranty cycles/years, and how much extra self-consumption it really adds for your use.
10. For financing: APR, total repayable, early repayment fees, and whether the loan is secured on the home.
## Findings and what to do
| code | meaning | what to do |
|---|---|---|
| SP01 | never pays back within the horizon | do not buy as quoted; ask for a smaller or cheaper system |
| SP02 | payback over 12 years | compare with other uses of the money; check incentives and price |
| SP03 | over half the power exported at a low price | ask for a smaller system or price a battery or load shifting |
| SP04 | production above 120% of use | size closer to use unless an EV or heat pump is coming soon |
| SP05 | loan payment above the year-1 saving | expect to pay extra each month at first; compare cash vs loan |
| SP06 | no inverter replacement within the horizon | add a realistic replacement year and cost and re-run |
| SP07 | degradation not given | ask for the datasheet value |
| SP08 | high self-use without a battery | re-run with 0.3-0.45 unless your daytime use is really high |
| SP09 | yield outside 600-1,900 kWh/kW | check with a public solar calculator for your address |
| SP10 | yield far above the other quotes | re-run with the median yield for a fair comparison |
## Red flags in sales pitches
- Pressure to sign today, "special price only for this street", or a deposit above about 25% before installation.
- Savings shown with a high electricity price escalation (over about 5% per year) and no 0% scenario.
- Monthly loan payment compared with the whole electricity bill, not with the realistic saving.
- No site visit or shading check before the final price.
FILE:templates/solar-summary.md
# Solar quote summary - {{household_name}} ({{date}})
**Household:** {{consumption}} kWh per year at {{price}} per kWh; export {{export_price}} per kWh; escalation {{escalation}}; discount rate {{discount_rate}}; horizon {{horizon}} years.
**Command:** `python3 scripts/solar_payback.py household.json quotes.csv`
## Comparison
| quote | kW | net cost | yr-1 saving | bill cut | simple payback | discounted payback | NPV | IRR | key findings |
|---|---|---|---|---|---|---|---|---|---|
| {{quote}} | {{kw}} | {{net_cost}} | {{saving}} | {{bill_cut}} | {{payback}} | {{disc_payback}} | {{npv}} | {{irr}} | {{findings}} |
## Fair comparison
Re-run with the same yield ({{fair_yield}} kWh/kW) and realistic self-consumption ({{fair_share}}): {{fair_result}}
## Best value
{{best_quote}} - why: {{reason}}. At a shorter horizon ({{short_horizon}} years): {{short_result}}.
## Things to ask the installers
- {{question_1}}
- {{question_2}}
- {{question_3}}
## Not included in these numbers
{{exclusions}}
_Estimates only, from the numbers provided. Check with the installer's final quote, the roof survey and your utility tariff before signing._
FILE:examples/household.json
{
"annual_consumption_kwh": 4600,
"electricity_price": 0.31,
"export_price": 0.07,
"price_escalation": 0.03,
"export_escalation": 0.0,
"discount_rate": 0.04,
"horizon_years": 25,
"currency": "EUR"
}
FILE:examples/quotes.csv
name,size_kw,price,incentives,specific_yield,self_consumption,degradation,inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
Installer A 4.4 kW,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,,
Installer B 6.6 kW,6.6,9100,0,1050,0.35,0.005,13,1500,70,0,,
Installer B 6.6 kW + 5 kWh battery,6.6,13800,500,1050,0.65,0.005,12,2200,90,5,,
Installer C 10 kW,10,13500,0,1050,0.25,,,,80,0,,
Installer A 4.4 kW on loan,4.4,7200,0,1050,0.45,0.005,13,1300,60,0,0.079,10
Door-to-door offer 4 kW,4,11900,0,1350,0.85,0.005,,,0,0,,
FILE:scripts/solar_payback.py
#!/usr/bin/env python3
"""solar_payback.py - compare rooftop solar quotes for one household (stdlib only, Python 3.8+).
Usage:
python3 scripts/solar_payback.py household.json quotes.csv [--horizon-years N] [--json] [--table QUOTE_NAME]
python3 scripts/solar_payback.py --self-test
household.json: annual_consumption_kwh, electricity_price, export_price, optional price_escalation (0.03),
export_escalation (0.0), discount_rate (0.04), horizon_years (25), currency.
quotes.csv columns: name,size_kw,price,incentives,specific_yield,self_consumption,degradation,
inverter_year,inverter_cost,maintenance,battery_kwh,loan_rate,loan_years
(rates and shares as decimals; specific_yield = kWh per kW per year from the installer or a public
solar calculator; loan_rate/loan_years empty or 0 = paid in cash).
For each quote: year-1 production, self-used and exported kWh, year-1 saving and bill reduction, simple and
discounted payback, net value at the horizon, NPV, IRR, cost per kWh produced, and findings SP01-SP09.
Exit 0 = at least one quote pays back within the horizon and no high findings on it, 1 = none does or a high
finding on every quote, 2 = bad input.
"""
import argparse, csv, json, math, sys
NUM = ["size_kw", "price", "incentives", "specific_yield", "self_consumption", "degradation",
"inverter_year", "inverter_cost", "maintenance", "battery_kwh", "loan_rate", "loan_years"]
DEFAULTS = dict(incentives=0, degradation=0.005, inverter_year=0, inverter_cost=0, maintenance=0,
battery_kwh=0, loan_rate=0, loan_years=0)
def annuity(principal, annual_rate, years):
if years <= 0 or principal <= 0:
return 0.0
n, r = int(round(years * 12)), annual_rate / 12
m = principal / n if r == 0 else principal * r / (1 - (1 + r) ** -n)
return m * 12
def load_household(path):
h = json.load(open(path, encoding="utf-8"))
for k in ("annual_consumption_kwh", "electricity_price", "export_price"):
if k not in h:
raise ValueError("household.json missing " + k)
h.setdefault("price_escalation", 0.03); h.setdefault("export_escalation", 0.0)
h.setdefault("discount_rate", 0.04); h.setdefault("horizon_years", 25); h.setdefault("currency", "")
if h["annual_consumption_kwh"] <= 0 or h["electricity_price"] <= 0:
raise ValueError("consumption and electricity_price must be positive")
for k in ("price_escalation", "export_escalation", "discount_rate"):
if abs(h[k]) >= 0.5:
raise ValueError(k + " looks like a percent; use decimals (0.03 = 3%)")
if h["electricity_price"] > 5:
raise ValueError("electricity_price looks like cents; use currency per kWh (0.32)")
return h
def parse_quote(row):
q = {"name": (row.get("name") or "").strip()}
if not q["name"]:
raise ValueError("quote without a name")
for k in NUM:
v = (row.get(k) or "").strip()
if v == "":
if k in DEFAULTS:
q[k] = DEFAULTS[k]; q.setdefault("_defaulted", []).append(k); continue
raise ValueError("%s: missing %s" % (q["name"], k))
q[k] = float(v)
if q["size_kw"] <= 0 or q["price"] <= 0 or q["specific_yield"] <= 0:
raise ValueError(q["name"] + ": size_kw, price and specific_yield must be positive")
if not 0 < q["self_consumption"] <= 1 or not 0 <= q["degradation"] < 0.05:
raise ValueError(q["name"] + ": self_consumption must be 0-1 and degradation a decimal like 0.005")
if q["loan_rate"] >= 0.5:
raise ValueError(q["name"] + ": loan_rate looks like a percent; use decimals")
return q
def load_quotes(path):
with open(path, newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
if not rows:
raise ValueError("quotes.csv has no rows")
return [parse_quote(r) for r in rows]
def irr(flows):
def npv(r):
return sum(cf / (1 + r) ** t for t, cf in enumerate(flows))
lo, hi = -0.99, 1.0
if npv(lo) * npv(hi) > 0:
return None
for _ in range(200):
mid = (lo + hi) / 2
if npv(lo) * npv(mid) <= 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
def payback(cum):
"""cum[0] = year 0 (upfront), cum[t] = cumulative after year t. Returns the fractional year when the
cumulative position becomes >= 0 for good (0.0 if it never goes negative), or None if it ends negative."""
if cum[-1] < 0:
return None
last_neg = max((t for t, c in enumerate(cum) if c < 0), default=None)
if last_neg is None:
return 0.0
t = last_neg + 1
return last_neg + (-cum[last_neg]) / (cum[t] - cum[last_neg])
def evaluate(h, q, horizon=None):
Y = int(horizon or h["horizon_years"])
net_cost = q["price"] - q["incentives"]
financed = q["loan_years"] > 0
loan_pay = annuity(net_cost, q["loan_rate"], q["loan_years"]) if financed else 0.0
upfront = 0.0 if financed else net_cost
flows, rows, pv_prod, pv_cost = [-upfront], [], 0.0, net_cost
d = h["discount_rate"]
for y in range(1, Y + 1):
prod = q["size_kw"] * q["specific_yield"] * (1 - q["degradation"]) ** (y - 1)
self_used = min(prod * q["self_consumption"], h["annual_consumption_kwh"])
exported = prod - self_used
price = h["electricity_price"] * (1 + h["price_escalation"]) ** (y - 1)
exp = h["export_price"] * (1 + h["export_escalation"]) ** (y - 1)
inverter = q["inverter_cost"] if q["inverter_year"] and int(q["inverter_year"]) == y else 0.0
saving = self_used * price + exported * exp
costs = q["maintenance"] + inverter
loan = loan_pay if financed and y <= q["loan_years"] else 0.0
cf = saving - costs - loan
flows.append(cf)
pv_prod += prod / (1 + d) ** y
pv_cost += costs / (1 + d) ** y
rows.append(dict(year=y, production_kwh=round(prod), self_used_kwh=round(self_used), exported_kwh=round(exported),
saving=round(saving, 2), costs=round(costs, 2), loan=round(loan, 2), cash_flow=round(cf, 2)))
cum, disc = [], []
c = dc = 0.0
for t, cf in enumerate(flows):
c += cf; dc += cf / (1 + d) ** t
cum.append(c); disc.append(dc)
y1 = rows[0]
bill_before = h["annual_consumption_kwh"] * h["electricity_price"]
r = dict(name=q["name"], size_kw=q["size_kw"], net_cost=round(net_cost, 2), financed=financed,
loan_payment=round(loan_pay, 2), year1_production=y1["production_kwh"], year1_self_used=y1["self_used_kwh"],
year1_exported=y1["exported_kwh"], year1_saving=y1["saving"],
bill_reduction=round(y1["self_used_kwh"] * h["electricity_price"] / bill_before, 3),
export_share=round(y1["exported_kwh"] / y1["production_kwh"], 3) if y1["production_kwh"] else 0,
coverage=round(y1["production_kwh"] / h["annual_consumption_kwh"], 3),
simple_payback=payback(cum), discounted_payback=payback(disc), net_at_horizon=round(cum[-1], 2),
npv=round(disc[-1], 2), irr=irr(flows) if not financed else None,
cost_per_kwh=round(pv_cost / pv_prod, 4) if pv_prod else None, horizon=Y, years=rows)
r["findings"] = findings(h, q, r)
return r
def findings(h, q, r):
F = []
def add(sev, code, msg): F.append(dict(severity=sev, code=code, message=msg))
if r["simple_payback"] is None:
add("high", "SP01", "does not pay back within %d years" % r["horizon"])
elif r["simple_payback"] > 12:
add("medium", "SP02", "slow payback: %.1f years" % r["simple_payback"])
if r["export_share"] > 0.5 and h["export_price"] < 0.4 * h["electricity_price"]:
add("medium", "SP03", "%.0f%% of production is exported at a low export price; a smaller system or a battery may pay back faster" % (r["export_share"] * 100))
if r["coverage"] > 1.2:
add("medium", "SP04", "produces %.0f%% of the yearly use; check the size against consumption" % (r["coverage"] * 100))
if r["financed"] and r["loan_payment"] > r["year1_saving"] - q["maintenance"]:
add("medium", "SP05", "loan payment %.0f per year is higher than the year-1 saving %.0f: negative cash flow at first" % (r["loan_payment"], r["year1_saving"]))
if r["horizon"] > 15 and not q["inverter_year"]:
add("low", "SP06", "no inverter replacement planned within %d years (inverters often last 10-15 years)" % r["horizon"])
if "degradation" in q.get("_defaulted", []):
add("low", "SP07", "degradation not given; assumed 0.5% per year")
if q["self_consumption"] > 0.8 and not q["battery_kwh"]:
add("low", "SP08", "self-consumption %.0f%% without a battery is optimistic for most homes" % (q["self_consumption"] * 100))
if not 600 <= q["specific_yield"] <= 1900:
add("medium", "SP09", "specific yield %.0f kWh/kW is outside the usual 600-1900 range; check the estimate" % q["specific_yield"])
return F
def cross_check(qs, res):
"""SP10: a quote that assumes a much higher yield than the others for the same home."""
ys = sorted(q["specific_yield"] for q in qs)
if len(ys) < 3:
return
med = ys[len(ys) // 2] if len(ys) % 2 else (ys[len(ys) // 2 - 1] + ys[len(ys) // 2]) / 2
for q, r in zip(qs, res):
if q["specific_yield"] > med * 1.15:
r["findings"].append(dict(severity="medium", code="SP10", message="assumes %.0f kWh/kW, %.0f%% above the median of the other quotes (%.0f); re-run it with %.0f for a fair comparison" % (
q["specific_yield"], (q["specific_yield"] / med - 1) * 100, med, med)))
def fmt_years(v):
return "never" if v is None else "%.1f y" % v
def render(h, res, table=None):
cur = h["currency"] + " " if h["currency"] else ""
L = ["# Solar payback check (horizon %d years)" % res[0]["horizon"], "",
"Household: %s kWh per year at %s%.3f per kWh (escalating %.1f%%/y), export %s%.3f per kWh, discount rate %.1f%%" %
("{:,}".format(int(h["annual_consumption_kwh"])), cur, h["electricity_price"], h["price_escalation"] * 100, cur, h["export_price"], h["discount_rate"] * 100), "",
"| quote | kW | net cost | yr-1 kWh | self-used | exported | yr-1 saving | bill cut | simple payback | disc. payback | net at horizon | NPV | IRR | cost/kWh |",
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"]
for r in res:
L.append("| %s | %.1f | %s | %s | %s | %s | %s | %.0f%% | %s | %s | %s | %s | %s | %s |" % (
r["name"], r["size_kw"], "{:,.0f}".format(r["net_cost"]) + (" (loan)" if r["financed"] else ""),
"{:,}".format(r["year1_production"]), "{:,}".format(r["year1_self_used"]), "{:,}".format(r["year1_exported"]),
"{:,.0f}".format(r["year1_saving"]), r["bill_reduction"] * 100, fmt_years(r["simple_payback"]), fmt_years(r["discounted_payback"]),
"{:,.0f}".format(r["net_at_horizon"]), "{:,.0f}".format(r["npv"]), "-" if r["irr"] is None else "%.1f%%" % (r["irr"] * 100),
"%.3f" % r["cost_per_kwh"]))
best = max(res, key=lambda r: r["npv"])
warn = " - check its assumptions first (findings below)" if any(f["severity"] in ("high", "medium") or f["code"] == "SP08" for f in best["findings"]) else ""
L += ["", "Highest NPV: %s (NPV %s%s)%s" % (best["name"], cur, "{:,.0f}".format(best["npv"]), warn), "", "## Findings"]
n = 0
for r in res:
for f in r["findings"]:
L.append("- [%s] %s %s: %s" % (f["severity"], f["code"], r["name"], f["message"])); n += 1
if not n:
L.append("- none")
if table:
r = next((x for x in res if x["name"] == table), None)
if r:
L += ["", "## Year by year: " + r["name"], "| year | production | self-used | exported | saving | costs | loan | cash flow |", "|---|---|---|---|---|---|---|---|"]
for y in r["years"]:
L.append("| %d | %s | %s | %s | %.0f | %.0f | %.0f | %.0f |" % (y["year"], "{:,}".format(y["production_kwh"]), "{:,}".format(y["self_used_kwh"]),
"{:,}".format(y["exported_kwh"]), y["saving"], y["costs"], y["loan"], y["cash_flow"]))
L += ["", "Estimates only: check yields, prices and incentives with the installer's quote and your utility tariff."]
return "\n".join(L)
def self_test():
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
H = dict(annual_consumption_kwh=4000, electricity_price=0.30, export_price=0.08, price_escalation=0.0,
export_escalation=0.0, discount_rate=0.0, horizon_years=25, currency="EUR")
def Q(**kw):
row = dict(name="t", size_kw="4", price="6000", incentives="0", specific_yield="1000", self_consumption="0.5",
degradation="0", inverter_year="", inverter_cost="", maintenance="0", battery_kwh="", loan_rate="", loan_years="")
row.update({k: str(v) for k, v in kw.items()})
return parse_quote(row)
check("annuity 10000 at 0% over 10 y = 1000/y", abs(annuity(10000, 0, 10) - 1000) < 1e-6)
check("annuity 10000 at 6% over 10 y = 1332.25/y", abs(annuity(10000, 0.06, 10) - 1332.25) < 0.05)
r = evaluate(H, Q())
check("year-1 production = kW x yield", r["year1_production"] == 4000)
check("self-used = production x share", r["year1_self_used"] == 2000)
check("saving = self-used x price + export x export price", abs(r["year1_saving"] - (2000 * 0.30 + 2000 * 0.08)) < 0.01)
check("simple payback = 6000 / 760", abs(r["simple_payback"] - 6000 / 760) < 1e-6)
check("discount 0 => discounted payback = simple", abs(r["discounted_payback"] - r["simple_payback"]) < 1e-6)
check("net at horizon = 25 x 760 - 6000", abs(r["net_at_horizon"] - (25 * 760 - 6000)) < 0.01)
check("IRR positive for a paying system", r["irr"] and r["irr"] > 0.1)
r = evaluate(H, Q(self_consumption=1.0, size_kw=9))
check("self-used capped at consumption", r["year1_self_used"] == 4000)
check("oversized system flags SP03 and SP04", {"SP03", "SP04"} <= {f["code"] for f in r["findings"]})
r = evaluate(H, Q(price=60000))
check("expensive system never pays back SP01", r["simple_payback"] is None and r["findings"][0]["code"] == "SP01")
r = evaluate(H, Q(price=12000))
check("slow payback flagged SP02", any(f["code"] == "SP02" for f in r["findings"]))
r = evaluate(H, Q(degradation=0.01))
check("degradation lowers year-2 production", r["years"][1]["production_kwh"] == 3960)
r = evaluate(H, Q(inverter_year=12, inverter_cost=1500))
check("inverter cost hits year 12 only", r["years"][11]["costs"] == 1500 and r["years"][10]["costs"] == 0)
check("no SP06 when inverter is planned", not any(f["code"] == "SP06" for f in r["findings"]))
r = evaluate(H, Q(incentives=2000))
check("incentives reduce net cost", r["net_cost"] == 4000)
r = evaluate(H, Q(loan_rate=0.05, loan_years=10, price=9000))
check("financed: no upfront, loan payment in years 1-10 only", r["years"][0]["loan"] > 0 and r["years"][10]["loan"] == 0)
check("loan payment above saving flags SP05", any(f["code"] == "SP05" for f in r["findings"]))
r = evaluate(H, Q(self_consumption=0.9))
check("high self-consumption without battery flags SP08", any(f["code"] == "SP08" for f in r["findings"]))
r = evaluate(H, Q(specific_yield=2500))
check("implausible yield flags SP09", any(f["code"] == "SP09" for f in r["findings"]))
r = evaluate(H, Q(degradation=""))
check("missing degradation defaults and flags SP07", any(f["code"] == "SP07" for f in r["findings"]))
H2 = dict(H, discount_rate=0.05)
r = evaluate(H2, Q())
check("discounting makes discounted payback longer", r["discounted_payback"] > r["simple_payback"])
res = [evaluate(H, Q(name=n, specific_yield=y)) for n, y in (("a", 1000), ("b", 1010), ("c", 1400))]
cross_check([Q(specific_yield=1000), Q(specific_yield=1010), Q(specific_yield=1400)], res)
check("yield far above the other quotes flags SP10", any(f["code"] == "SP10" for f in res[2]["findings"]) and not any(f["code"] == "SP10" for f in res[0]["findings"]))
check("payback None when the position ends negative", payback([-100, -50, 20, -10]) is None)
check("payback 0 when never negative", payback([0, 10, 20]) == 0.0)
for bad, label in ((dict(self_consumption=1.5), "share above 1 rejected"), (dict(loan_rate=6, loan_years=10), "percent loan rate rejected")):
try:
Q(**bad); check(label, False)
except ValueError:
check(label, True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("household", nargs="?"); ap.add_argument("quotes", nargs="?")
ap.add_argument("--horizon-years", type=int); ap.add_argument("--json", action="store_true")
ap.add_argument("--table", help="print the year-by-year table for this quote name")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not (a.household and a.quotes):
print("error: give household.json and quotes.csv", file=sys.stderr); return 2
try:
h = load_household(a.household); qs = load_quotes(a.quotes)
res = [evaluate(h, q, a.horizon_years) for q in qs]
cross_check(qs, res)
except (ValueError, OSError, json.JSONDecodeError) as e:
print("error:", e, file=sys.stderr); return 2
if a.json:
print(json.dumps(res, indent=2))
else:
print(render(h, res, a.table))
good = [r for r in res if r["simple_payback"] is not None and not any(f["severity"] == "high" for f in r["findings"])]
return 0 if good else 1
if __name__ == "__main__":
sys.exit(main())
Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---
# Python Import Cycle Detector
You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.
You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.
## Files in this skill
- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError
## Workflow
### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.
### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.
### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.
### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.
### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.
### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.
## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.
FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)
## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.
So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
`ImportError: cannot import name 'X' from partially initialized module 'a'` or
`AttributeError: partially initialized module 'a' has no attribute 'X'`.
Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.
## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |
## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |
## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.
## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.
FILE:references/fix-patterns.md
# Fix patterns for circular imports
Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).
## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.
## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.
## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.
## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
...
if on_success:
on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.
## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.
## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.
## 7. Deferred import (last resort)
```python
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.
## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.
## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.
FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})
**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}
## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}
## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |
## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |
## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}
## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`
FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order
__all__ = ["Order", "place_order"]
FILE:examples/shop/models.py
from dataclasses import dataclass
from shop.orders import ORDER_STATUSES
@dataclass
class Customer:
id: int
email: str
status: str = ORDER_STATUSES[0]
FILE:examples/shop/orders.py
from dataclasses import dataclass, field
from shop.models import Customer
from shop import payments
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
@dataclass
class Order:
id: int
customer: Customer
total_cents: int
status: str = "new"
lines: list = field(default_factory=list)
def place_order(order):
payments.charge(order)
order.status = "paid"
return order
FILE:examples/shop/payments.py
from shop.notifications import send_receipt
def charge(order):
# pretend to call a payment provider here
send_receipt(order)
return True
FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from shop.models import Customer
def send_receipt(order):
from shop.orders import ORDER_STATUSES # deferred import, runs only when called
return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])
def greet(customer: "Customer"):
return "Hello " + customer.email
FILE:examples/shop/utils.py
def cents_to_text(cents):
return "%d.%02d" % divmod(cents, 100)
FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).
Usage:
python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
python3 scripts/import_cycles.py --self-test
Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}
def module_name(path, root):
rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
if rel.endswith(".__init__"):
rel = rel[: -len(".__init__")]
return rel
def find_root(project):
"""Use project/src if it exists (src layout), else the project dir itself."""
src = os.path.join(project, "src")
return src if os.path.isdir(src) else project
def collect_files(root):
out = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
for f in sorted(filenames):
if f.endswith(".py"):
out.append(os.path.join(dirpath, f))
return out
class ImportVisitor(ast.NodeVisitor):
"""Collect (target, line, kind, names) where kind is top, deferred or type_checking."""
def __init__(self, modname, is_pkg):
self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
self.found = []
def _kind(self):
if self.tc:
return "type_checking"
return "deferred" if self.depth else "top"
def visit_FunctionDef(self, node):
self.depth += 1; self.generic_visit(node); self.depth -= 1
visit_AsyncFunctionDef = visit_FunctionDef
visit_Lambda = visit_FunctionDef
def visit_If(self, node):
t = node.test
is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
(isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
if is_tc:
self.tc += 1
for n in node.body:
self.visit(n)
self.tc -= 1
for n in node.orelse:
self.visit(n)
else:
self.generic_visit(node)
def visit_Import(self, node):
for a in node.names:
self.found.append((a.name, node.lineno, self._kind(), []))
def visit_ImportFrom(self, node):
if node.level:
parts = self.mod.split(".")
base = parts if self.is_pkg else parts[:-1]
up = node.level - 1
if up > len(base):
return
base = base[: len(base) - up] if up else base
target = ".".join(base + ([node.module] if node.module else []))
else:
target = node.module or ""
names = [a.name for a in node.names]
self.found.append((target, node.lineno, self._kind(), names))
def resolve(target, names, modules):
"""Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
hits = []
if names:
for n in names:
sub = target + "." + n if target else n
if sub in modules:
hits.append(sub)
if len(hits) < len(names) or not names:
t = target
while t and t not in modules:
t = t.rpartition(".")[0]
if t:
hits.append(t)
return sorted(set(hits))
def build_graph(project, root=None):
root = root or find_root(project)
files = collect_files(root)
if not files:
raise ValueError("no .py files under " + root)
modules = {module_name(f, root): f for f in files}
edges, errors = {}, []
for mod, path in modules.items():
try:
tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
except (SyntaxError, UnicodeDecodeError) as e:
errors.append((mod, str(e).splitlines()[0])); continue
v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
for target, line, kind, names in v.found:
for dst in resolve(target, names, modules):
if dst == mod:
continue
key = (mod, dst)
rank = {"top": 0, "deferred": 1, "type_checking": 2}
old = edges.get(key)
if old is None or rank[kind] < rank[old["kind"]]:
edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
return root, modules, edges, errors
def sccs(nodes, adj):
"""Tarjan's algorithm, iterative."""
index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
for start in sorted(nodes):
if start in index:
continue
work = [(start, iter(sorted(adj.get(start, ()))))]
index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
while work:
v, it = work[-1]
for w in it:
if w not in index:
index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
work.append((w, iter(sorted(adj.get(w, ())))))
break
if w in onstack:
low[v] = min(low[v], index[w])
else:
work.pop()
if work:
low[work[-1][0]] = min(low[work[-1][0]], low[v])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop(); onstack.discard(w); comp.append(w)
if w == v:
break
if len(comp) > 1:
out.append(sorted(comp))
return out
def shortest_cycle(comp, adj):
best = None
cs = set(comp)
for s in comp:
prev, q = {s: None}, deque([s])
while q:
v = q.popleft()
for w in sorted(adj.get(v, ())):
if w not in cs:
continue
if w == s:
path = [v]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
cyc = list(reversed(path)) + [s]
if best is None or len(cyc) < len(best):
best = cyc
q.clear(); break
if w not in prev:
prev[w] = v; q.append(w)
return best
def analyze(project, root=None, include_tc=False):
root, modules, edges, errors = build_graph(project, root)
use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
top = {k: v for k, v in use.items() if v["kind"] == "top"}
def adj_of(es):
a = {}
for (s, d) in es:
a.setdefault(s, set()).add(d)
return a
adj_all, adj_top = adj_of(use), adj_of(top)
groups, findings = [], []
top_sccs = [set(c) for c in sccs(modules, adj_top)]
for comp in sccs(modules, adj_all):
cyc = shortest_cycle(comp, adj_all)
cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
import_time = any(set(comp) & t for t in top_sccs)
inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
# break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
groups.append(g)
label = " -> ".join(cyc)
if import_time:
findings.append(("high", "IC01", "import-time cycle: " + label))
else:
findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
if len(comp) >= 5:
findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
for e in cyc_edges:
if e["file"].endswith("__init__.py") and e["kind"] == "top":
findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
if e["kind"] == "top" and e["names"] == ["*"]:
findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
if tc_only and not include_tc:
findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
for mod, err in errors:
findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])
def render(res):
L = ["# Import cycle report", "",
"Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
(res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
for i, g in enumerate(res["groups"], 1):
L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
L.append("Modules: " + ", ".join(g["modules"]))
L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
for e in g["cycle_edges"]:
L.append(" - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
(" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
if g["other_edges"]:
L.append("Other imports inside this group:")
for e in g["other_edges"]:
L.append(" - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
b = g["break_candidate"]
L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
L.append("")
if not res["groups"]:
L += ["No import cycles between project modules.", ""]
L.append("## Findings")
order = {"high": 0, "medium": 1, "low": 2, "info": 3}
for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
if not res["findings"]:
L.append("- none")
return "\n".join(L)
def self_test():
import tempfile
ok = [0, 0]
def check(name, cond):
ok[0 if cond else 1] += 1
print(("PASS " if cond else "FAIL ") + name)
def proj(files):
d = tempfile.mkdtemp()
for rel, txt in files.items():
p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
open(p, "w").write(txt)
return d
r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
check("no cycle in a -> b", not r["groups"])
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n import a\n"}))
check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}))
check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import a\n"}), include_tc=True)
check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
check("from pkg import submodule maps to the submodule", not r["groups"])
r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
r = analyze(proj(files))
check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
check("stdlib imports ignored", r["edges"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
check("venv folder skipped", r["modules"] == 1)
r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
b = r["groups"][0]["break_candidate"]
check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
try:
analyze(proj({"README.md": "x"})); check("empty project rejected", False)
except ValueError:
check("empty project rejected", True)
print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
return 0 if not ok[1] else 1
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("project", nargs="?")
ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
ap.add_argument("--json", action="store_true")
ap.add_argument("--include-type-checking", action="store_true")
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args()
if a.self_test:
return self_test()
if not a.project or not os.path.isdir(a.project):
print("error: give a project directory", file=sys.stderr); return 2
try:
res = analyze(a.project, a.root, a.include_type_checking)
except ValueError as e:
print("error:", e, file=sys.stderr); return 2
print(json.dumps(res, indent=2) if a.json else render(res))
return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0
if __name__ == "__main__":
sys.exit(main())
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.

