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
TrendingA timestamped 14-shot, 30-second Seedance storyboard: a white-haired sorceress battles a living ink version of her own shadow through an ancient archive, a fractured sky and a stone altar, with camera moves, VFX and SFX for every shot.
**Title: "The Ink Shadow" (30s, 9:16 or 16:9)** **Shot 1 (00:00-00:02) - WS, Slow Dolly In** In an ancient archive of hanging talismans and bells, a white-haired sorceress paints a glowing sigil on a floating scroll. Her shadow on the wall keeps painting after she stops. VFX: Drifting dust, flickering lantern light. SFX: Paper rustle, soft bells, low hum. **Shot 2 (00:02-00:04) - ECU, Rack Focus** Ink drops rise upward from her brush tip. In the blurred background, her shadow's hand peels off the wall. VFX: Floating ink beads, shadow detaching like wet paint. SFX: Liquid ticks, a distant bell cracking. **Shot 3 (00:04-00:06) - MS, Whip Pan** The shadow tears free as a black ink entity wearing her silhouette. She spins away from its claw and counters with a sweeping brush strike. VFX: Distorted, pulsing ink mist, brush-stroke shockwave. SFX: Whoosh, sharp bell chime. **Shot 4 (00:06-00:08) - CU, Fast Push-in** Her eyes glow cold blue. She flicks her wrist and draws blade-like sigil strokes in mid-air. VFX: Intersecting blue energy lines, afterimage trails. SFX: Sharp air cuts, energy charge. **Shot 5 (00:08-00:10) - WS, Crane Up** Talismans whirl into a vortex and layered sigil rings spin under her feet. The entity slams into the barrier, then sinks through the floor, which turns into a mirror of black ink. VFX: Multi-layer rotating rings, ink-mirror ripples. SFX: Deep resonance, swirling wind. **Shot 6 (00:10-00:13) - MFS, Orbit Tracking** The archive peels away like burning paper, revealing a fractured sky. She steps across floating sigils as her brush stretches into a glowing rune chain that lashes at the entity. VFX: Paper-peel transition, flickering rune-chain light. SFX: Paper tearing, chain clinks. **Shot 7 (00:13-00:16) - LS, Chase Cam** Amid storm clouds and a broken moon, she rides the chain. The entity bursts into a flock of ink crows, and she throws talismans that fold into paper cranes and hunt them. VFX: Rolling clouds, ink crows vs. blue-white paper cranes. SFX: Roaring wind, wing flutter, thunder. **Shot 8 (00:16-00:18) - CU, Lateral Slide** She taps nodes along the chain, lighting hidden purple sigils one by one. The crows are pulled back together into a single body. VFX: Sequential purple node illumination, crows merging. SFX: Light clicks, rising hum. **Shot 9 (00:18-00:20) - MCU, Static** She strikes its forehead in a purple-blue flash and a rotating seal appears on its chest. For one frame, its face becomes hers and smiles. VFX: Flash, rotating seal, face-morph glitch. SFX: Sharp burst, distorted screech, a whisper in her voice. **Shot 10 (00:20-00:22) - WS, Dive Shot** Both streak downward like meteors through the clouds toward an ancient stone altar. VFX: Comet-like trails, cloud shreds. SFX: Air screech, compression. **Shot 11 (00:22-00:24) - WS, Impact (Slow-Motion)** They crash and dust erupts. She slams her palm down and radiating sigils crack across the stone, each fracture glowing for a beat. VFX: Glowing fractures, floating debris. SFX: Heavy impact, stone cracking. **Shot 12 (00:24-00:27) - LS, Slow Pull Back** A massive 3D sigil array rises and forms layered barriers around the entity. She stands calmly outside as it mouths her words back at her. VFX: Expanding geometric barriers, drifting particles. SFX: Low steady resonance, faint echo. **Shot 13 (00:27-00:28) - CU, Static** She forms a hand seal and whispers: "Seal." VFX: Light contracting inward. SFX: Soft chant, energy tightening. **Shot 14 (00:28-00:30) - CU, Fade Out** Eyes closed, she meditates as all light fades. One ink drop falls on the altar, and her shadow on the stone is a half-second late to follow her. VFX: Light dissipating, ink ripple. SFX: Gentle wind, fading echo, silence.

Upload a photo of any city or landmark and turn it into a quiet editorial art print: a realistic 35mm golden-hour photograph on top, a tiny watercolor miniature of the same place below, generous ivory paper space and the caption "CITY IN SOFT LIGHT."
{
"aspect_ratio": "3:4",
"style": "minimalist architectural editorial poster, cinematic photography paired with fine-art print design",
"reference_instructions": {
"use_uploaded_image": true,
"preserve_subject": true,
"preserve_architecture": true,
"preserve_recognizable_landmarks": true,
"preserve_original_composition": false,
"instruction": "Use the uploaded photograph as the primary reference. Accurately preserve the recognizable buildings, architecture, skyline, structures, and distinctive visual identity of the location while transforming it into a sophisticated minimalist poster composition."
},
"composition": {
"layout": "vertical editorial poster",
"structure": "two-part visual composition",
"top_section": {
"size": "approximately 60 percent of the canvas",
"content": "a realistic photographic view of the uploaded location",
"treatment": "warm late-afternoon sunlight, subtle film grain, natural atmospheric perspective, muted cinematic colors",
"framing": "wide architectural composition with the main landmark clearly visible",
"photographic_style": "35mm film photography, realistic textures, natural imperfections, soft sunlight and gentle shadows"
},
"middle_section": {
"transition": "large uninterrupted area of warm ivory textured paper",
"spacing": "generous negative space",
"divider": "no visible hard border, clean separation between photograph and artwork"
},
"bottom_section": {
"size": "approximately 35 percent of the canvas",
"content": "a miniature artistic reconstruction of the same cityscape or architecture",
"placement": "small, centered horizontally and positioned within the lower half",
"scale": "tiny architectural diorama-like composition surrounded by expansive empty space",
"style": "soft watercolor, gouache, muted architectural illustration, slightly faded vintage print",
"details": "retain the recognizable silhouettes and relative positions of the important structures while simplifying minor details"
}
},
"background": {
"color": "warm cream, ivory, pale beige",
"texture": "subtle fine-grain handmade paper texture, delicate fibers, vintage print imperfections",
"appearance": "matte, elegant, tactile, minimal"
},
"color_palette": {
"primary": [
"warm ivory",
"sand beige",
"muted terracotta",
"dusty blue",
"soft gray",
"faded olive"
],
"saturation": "low to moderate",
"grading": "warm nostalgic film color grading"
},
"typography": {
"text": "CITY IN SOFT LIGHT.",
"placement": "centered beneath the miniature illustration",
"font_style": "elegant serif typography",
"letter_spacing": "wide tracking",
"font_size": "small and understated",
"color": "muted dark brown",
"alignment": "center",
"additional_text": "none"
},
"visual_mood": [
"quiet",
"nostalgic",
"minimalist",
"architectural",
"poetic",
"editorial",
"museum-quality"
],
"lighting": {
"photographic_section": "soft golden-hour sunlight",
"illustration_section": "diffused warm light",
"shadows": "gentle and natural"
},
"rendering": {
"photorealism": "high in the upper photograph",
"illustration": "painterly and subtly imperfect in the lower miniature",
"texture": "visible paper grain throughout",
"quality": "premium art print, refined visual storytelling, sophisticated design magazine aesthetic"
},
"constraints": [
"Do not invent or replace the main architecture",
"Do not distort recognizable buildings",
"Keep the upper photograph realistic",
"The lower illustration must depict the same location as the photograph",
"The lower illustration should be significantly smaller than the upper photograph",
"Maintain large amounts of negative space",
"Avoid clutter",
"Avoid excessive decorative elements",
"Avoid modern graphic design clutter",
"No borders",
"No watermark",
"No extra text",
"No logos"
]
}
Turn any character into an antique scientific-journal plate: watercolor and ink full-body study with costume details, magnified accessory sketches and sepia handwritten annotations. Fill in [character], [outfit] and [pose].
A detailed character study of [character], illustrated in the style of 19th-century scientific journals, [outfit], [pose], full-body anatomical proportions, delicate ink linework, hand-painted watercolor, natural pigments, detailed costume studies, magnified accessory sketches, fine leader lines, handwritten annotations in sepia ink, elegant scientific plate composition, antique scholarly aesthetic, clean white background
A rapid 14-cut, timestamped 30-second Seedance 2.5 duel scene: a towering samurai duelist fights assassins on a stormy vermilion shrine terrace, rendered as moving gouache concept art, with audio design and inline negatives.
Cinematic 2.5D animation in the style of fully painterly rendering, characters and environments look like gouache concept-art paintings in motion, visible brush texture on skin, cloth and buildings, flat posterized color blocks with hard-edged light shapes, matte finish, soft filmic volumetric lighting, shallow depth of field. NOT flat 2D cartoon, NO bold black outlines, NO cel-shading, NOT glossy CGI, NOT Unreal Engine, NO photorealism, no plastic skin. CHARACTER: Lady Kureha, a 10-heads-tall adult female samurai duelist. Sleek black hair in an architectural looped bun, pointed ears with red tassel earrings, plunging dark-navy halter top with gold bell charms, exposed athletic midriff, draped oversized navy sleeves, asymmetrical high-slit skirt, black geta sandals, wielding a long curved katana. SETTING: The Vermilion Moon Terrace. Stormy coastal wooden platforms and red torii frames over crashing ocean waves under cold midnight moonlight and swaying paper lanterns. CINEMATOGRAPHY & RAPID 14-CUT DUEL CHOREOGRAPHY (EXACTLY 30 SECONDS): 00:00-00:02.0 (Shot 1 | Macro Chimes): Extreme macro close-up on the three gold bell charms at her ribcage vibrating in the gale; a sharp mechanical thumb flick clicks open the katana tsuba with a cold specular glint. 00:02.0-00:04.0 (Shot 2 | Runway Stride): Ground-level tracking shot; black geta heels click rhythmically on wet black-lacquered planks, high-slit skirt parting along her bare leg, oversized navy sleeves billowing wide like dark wings. 00:04.0-00:06.0 (Shot 3 | Face & Gaze): Low-angle push-in on Kureha's face; black bangs whip in the wind, red tassel earrings sway, lips parting into a razor-thin, bloodthirsty smirk. 00:06.0-00:08.0 (Shot 4 | The Ambush): Wide shot; four armored assassins leap from the torii rafters; rain and lanterns swing wildly in the storm. 00:08.0-00:10.5 (Shot 5 | Battoujutsu Crescent): Speed-ramp tracking; Kureha unsheathes her katana in a blinding 360-degree horizontal sweep, carving a flat-painted white crescent wind arc that severs enemy spears in half. 00:10.5-00:12.5 (Shot 6 | Fluid Sidestep): Reverse tight cut; she pivots on one high-heeled sandal, her navy sleeves swirling in slow-motion as an enemy blade grazes inches past her exposed midriff. 00:12.5-00:14.5 (Shot 7 | The Counter Thrust): Low-angle strike; Kureha drives the pommel of her blade into an attacker's jaw with a bone-shattering crack, sending him flying into the stormy sea below. 00:14.5-00:16.5 (Shot 8 | Aerial Cleave): Mid-air tracking cut; she leaps off a wooden balustrade, descending with a two-handed overhead slash that cleanly parts the rain and shatters the wooden decking. 00:16.5-00:18.5 (Shot 9 | Bell Chime Resonation): Extreme macro on the gold bells; the kinetic shockwave rings them with a high-pitched sonic chime that sends a visible distortion wave across the frame. 00:18.5-00:21.0 (Shot 10 | Phantom Dash): Supersonic blur; Kureha weaves through the remaining two foes in a zig-zag dash, leaving flat-painted crimson ribbon trails through the dark. 00:21.0-00:23.5 (Shot 11 | Simultaneous Collapse): Wide shot; Kureha slides to a halt with back turned; both remaining assailants collapse into the surf behind her simultaneously. 00:23.5-00:25.5 (Shot 12 | The Blood Flick): Fluid wrist snap; Kureha flicks rainwater and blood off the steel in one crisp, effortless gesture, her draped sleeves settling heavily. 00:25.5-00:27.5 (Shot 13 | The Sheath Click): Macro on the scabbard mouth; the katana blade smoothly glides home with a distinct metallic *chink*, locking into place. 00:27.5-00:30.0 (Shot 14 | Poster Hero Frame): Locked extreme low-angle hero shot; Kureha stands tall on the terrace edge under the full moon, resting the sheathed nodachi on her shoulder, wind howling through her black hair as the gold bells chime softly in the stillness. Hold for 2.5 seconds. clear three-layer depth: foreground wet balustrades and lantern ropes cropped in silhouette, Kureha fully resolved in midground with maximum value contrast, background crashing ocean breakers and stormy sky dissolved in 80% nocturnal haze. Weighty natural character animation, cloth, long hair, and tassels reacting to violent coastal gales. AUDIO DESIGN: Howling ocean gale, sharp metallic sword draw shing, resonant golden bell chimes, wooden deck foot-clicks, sonic-boom air cleaves, splashing ocean spray, final scabbard click decaying into quiet wind. PROHIBITIONS (INLINE NEGATIVES): Sluggish pacing, less than 14 cuts, male chest, teenager proportions, cute expressions, photorealism, glossy CGI render, smooth 3D plastic skin, anime cel outlines, lineart, camera drift, extra limbs. 100% stylized 2D gouache painting.

{
"aspect_ratio": "3:4",
"prompt": "Create a beautiful retro comic-book inspired pop-art illustration featuring a cheerful young woman with dark, slightly messy shoulder-length hair, laughing naturally. The composition consists of three wide horizontal portrait panels stacked vertically, separated by clean cream-colored borders. Each panel captures a different candid laughing moment from a slightly different camera angle and facial expression. Panel 1: close-up frontal portrait with a bright joyful smile and sparkling eyes. Panel 2: playful three-quarter angle, eyes almost closed, laughing freely with a slightly tilted head. Panel 3: slightly low-angle close-up, head tilted back, eyes closed and mouth open in genuine laughter. Use expressive hand-drawn ink outlines, loose sketchy brush strokes, subtle vintage comic-book texture, bold flat colors, warm golden skin tones, deep navy-black hair, alternating turquoise and coral-pink backgrounds. Add subtle imperfections and artistic linework for a handmade editorial illustration aesthetic. Maintain consistent facial identity across all three panels. Beautiful balanced composition, vibrant colors, nostalgic 1970s pop-art magazine aesthetic, visually striking, expressive and full of personality.",
"negative_prompt": "photorealistic, 3D render, CGI, blurry face, distorted anatomy, extra facial features, inconsistent character identity, duplicated panels, text, typography, watermark, logo, exact recreation of reference image",
"style": "Retro Pop Art, Comic Illustration, Hand Drawn Editorial",
"aspect_ratio": "3:4",
"quality": "High Detail"
}Create a 30-second, ultra-realistic emotional live-action scene about a young woman discovering her boyfriend secretly kissing another woman on the staircase of a busy shopping mall. Focus entirely on authentic human emotion, natural crying, subtle facial expressions, and believable body language. No melodrama or exaggerated acting. ### MAIN CHARACTER A young Korean woman in her early 20s, naturally beautiful, realistic skin texture, minimal makeup, long black hair loosely styled, wearing a fitted pastel-pink top, casual denim shorts, white sneakers, and carrying a small handbag. Maintain the exact same face, hairstyle, outfit, body proportions, and appearance throughout the entire scene. ### OTHER CHARACTERS Boyfriend: A Korean man in his mid-20s, short black hair, wearing a casual black jacket, white T-shirt, dark jeans, and sneakers. Other Woman: A Korean woman in her early 20s, long brown hair, wearing a fashionable cream-colored top, short black skirt, and knee-high boots. Maintain consistent appearances for all three characters. ### LOCATION A large, modern shopping mall during the evening. Wide indoor staircase with polished stone steps, glass railings, bright ceiling lights, multiple floors visible, fashion stores, shoppers walking around, and a busy food court in the background. Natural mall ambience, realistic lighting, reflections on glass surfaces, and authentic pedestrian movement. ### SCENE — THE DISCOVERY 0–5 SECONDS The young woman walks through the shopping mall carrying a small handbag. She looks around casually, searching for her boyfriend. She approaches a wide staircase connecting two floors. As she starts walking up the stairs, she notices two familiar people standing on the landing above. Her boyfriend is secretly kissing another woman near the glass railing. She immediately stops walking. 5–10 SECONDS The camera slowly moves closer to her face. Her expression changes from curiosity to confusion, then disbelief. She looks again, hoping she has misunderstood what she is seeing. Her fingers tighten around her handbag. Her eyes begin to fill with tears. The surrounding mall continues functioning normally, but the emotional moment feels isolated. 10–16 SECONDS Show a realistic close-up of her eyes as tears naturally gather along her lower eyelids. One tear slowly rolls down her cheek. She takes a shaky breath and quietly whispers: "Why...?" Her boyfriend suddenly notices her standing on the staircase. He immediately pulls away from the other woman. His expression changes to complete shock. The other woman turns around and realizes what has happened. 16–22 SECONDS The girlfriend slowly walks up two steps toward them. Her lips tremble as she looks directly at her boyfriend. She quietly says: "Was I not enough for you?" Her voice cracks naturally. He tries to approach her and explain, but she raises one hand slightly, asking him to stop. She shakes her head as tears continue falling. 22–27 SECONDS She looks at the other woman for a brief moment, then turns back toward her boyfriend. With a broken, trembling voice, she says: "I trusted you..." She wipes her cheek with the back of her hand. Her boyfriend remains speechless. People continue walking up and down the staircase around them, occasionally glancing at the situation. 27–30 SECONDS She slowly turns around and walks down the stairs while quietly crying. Her boyfriend takes one step after her but stops. The camera follows her from behind for a moment, then cuts to a close-up of her tearful face as she exits the frame. End with the boyfriend standing motionless on the staircase. ### CAMERA / VISUAL STYLE * Handheld cinematic camera with subtle natural movement. * Start with a medium tracking shot following the woman through the mall.
SCENE CONTEXT One continuous 30-second chase shot through a long, straight space station module in zero gravity, running from the entry hatch to the airlock door. The girl from image1 floats at the hatch and throws a small silver dart. It flies in one dead-straight line along the center axis of the module with no curves and no turns, holding a constant offset from every wall. The camera flies 45 cm (1.5 feet) behind the dart's tail at the same speed, so the dart is always large in the frame and every hit lands right in front of the lens. Everything the dart hits sits on its straight line: a floating water sphere, a juice pouch, a floating birthday cake slice, a cargo net, a drifting wrench, a round hatch, a bunch of cherry tomatoes, a soap-film ring and a bullseye target on the airlock door. The dart passes near crew members, never through them, and every crew member reacts with shock but is unharmed. LOCATION MAP A cylindrical module 4 meters wide and about 60 meters long, lined with white padded panels, handrails, orange tether straps, velcro-strip equipment, laptop mounts and storage lockers. Cool white LED strips run along the ceiling, and floating crumbs, droplets and a few loose items drift in the air. A round hatch segment sits midway, and a large window at the far end shows a glowing blue Earth. The dart's flight line runs along the center axis of the module. FIRST FRAME / BLOCKING A stable shot from behind and just over the left shoulder of the girl from image1, floating in the entry hatch with one foot hooked under a handrail. The back of her head and her clothing, matching image1, fill the left third of the frame, her hair drifting upward. Her right hand is raised beside her head with a small silver dart between two fingers, tip pointing straight down the module. Ahead on the right, an astronaut in a blue crew shirt floats away from camera. Far down the module, crew members drift slowly and a shimmering water sphere is visible ahead. FORMAT MODE One continuous shot, the camera does not cut on its own. Real-time speed throughout. OPTICS Rectilinear lens. FOV per segment, no drift mid-segment: 0.0 to 0.9s at 47°, 0.9s to 30.0s at 63°. The dart stays in sharp focus, and background focus pulls to the next target as the dart nears it. Natural motion blur. CAMERA After release at 0.9s, the camera swings forward past the girl's hand and settles 45 cm (1.5 feet) behind the dart's tail and 10 cm above its line, matching its speed within 5%. The dart is a small silver dart about 12 cm long with a star-shaped cross at the tail. It sits in the lower center of the frame, pointing away from the lens, and fills about one-fifth of the frame width. The camera moves in a dead-straight line with the dart, with only a 1 cm handheld tremor and no banking, rolling or sideways drift. ACTION 0.0–0.9s: the girl winds her right arm back 40 cm, then snaps her wrist forward. The dart leaves her fingers at 0.9s with a sharp metallic "tsk." She drifts backward from the recoil, her hair floating. The camera pushes past her hand and locks in 45 cm behind the dart. 0.9–3.0s: the dart accelerates from 0 to 70 km/h, then eases to 25 km/h by 3.0s, flying straight. Crew members on both sides smear into blur as the dart passes 1 meter from them, floating upside down, sideways and mid-task. They jerk their heads toward the sound. 3.0–6.0s: a large water sphere 30 cm across floats on the line. The dart passes through its center at 5.0s, and the sphere wobbles, stretches and breaks into hundreds of droplets that trail past the lens in a glittering stream. 6.0–9.0s: an astronaut floats sideways sipping from an orange juice pouch held at the line. The dart passes 25 cm from his cheek and punches through the pouch at 8.0s, releasing a swirling orange orb that expands across the lens. His eyes widen above the drifting juice. 9.0–12.0s: a crew birthday celebration. A slice of cake with a single candle floats on a tray, the candle flame a small blue sphere. The dart passes through the cake at 11.0s, and frosting globs and crumbs float past the lens. Two crew members hold their party hats, mouths open. 12.0–15.0s: a cargo net stretched across the module is full of floating items. The dart flies through the exact center of one mesh square without touching it. The items slowly rotate in its wake, and the camera follows through the same square. 15.0–18.0s: a wrench drifts end over end on the line. The dart clips its handle with a bright "ping," and the wrench spins away. An astronaut nearby catches it by reflex and stares at it. 18.0–21.0s: the round hatch segment is ahead. The dart flies through the center of the opening, and a crew member floating in the hatch jerks back with both hands up. 21.0–24.0s: slow motion for 1.5 seconds. A bunch of cherry tomatoes from the plant lab floats on the line. The dart threads between them, bursts one at 22.5s with a tiny red spray, and two astronauts reaching for the bunch freeze, eyes following the dart. 24.0–27.0s: a soap-film ring on a wire loop floats on the line, a shimmering film stretched across it. The dart passes through the center at 26.0s, and the film pops into hundreds of rainbow droplets. A child-sized astronaut's wide eyes catch the shimmer. 27.0–29.6s: the airlock at the far end, with the glowing Earth in the window beside it. A round bullseye target with black and white rings and a red center is painted on the airlock door, 15 meters ahead. Crew members line both walls, floating in place. The dart accelerates to 30 km/h and the camera keeps pace behind it. 29.6–30.0s: the dart sinks into the bullseye. The camera brakes hard and stops 45 cm behind it. The door shudders for 0.4 seconds, then settles with the dart quivering at center. A single water droplet drifts across the lens. PERFORMANCE Faces carry real skin texture with visible pores, floating hair and living eyes with catch-lights from the LEDs. Every person reacts in order: eyes widen first, then mouth, then shoulders pull back. Zero-gravity reactions are slow and floaty. PHYSICS Zero gravity throughout. Water forms spheres that wobble and break into droplets. Crumbs, frosting and juice float and drift in the dart's wake. The candle flame is a small blue sphere. Soap film pops into rainbow droplets. The metal door shudders on impact. LIGHTING Cool white LED strips at 5000K along the ceiling, flat, even light on faces. Blue Earthlight from the end window, with a warm 2800K sunrise flare creeping across the panels near the end. Floating droplets catch the light. COLOR GRADE Clean and bright at about 35% saturation, with cool white panels and soft blue shadows. Saturated accents punch out: the orange juice, the orange tether straps, the red tomatoes, the glowing blue Earth and the rainbow soap film. Lifted blacks near 4%, soft highlight roll-off, and fine natural film grain. WARDROBE Crew in blue and grey station shirts, shorts and socks with name patches, and one party hat. The girl matches image1 exactly. AUDIO Natural station sound only, with no music. A constant soft air-fan hum. A fabric flick and rising whoosh at launch. Wet droplet pops, a muffled juice splash, a gentle cake squish, a clear metal "ping" and a soft film pop. Silence drops in at 27.0s, with only a heartbeat, then a deep clean thunk through the hull at 29.6s. STYLE Photoreal cinematic commercial film look, shallow depth of field, fine grain, natural motion blur, true-to-life skin, fabric and metal texture. OUTPUT SETTINGS 9:16, 24 fps, 30 seconds, one take, real-time speed throughout. POSITIVE LOCKS The dart flies in one dead-straight line along the module's center axis from 0.9s to 30.0s. The camera stays 45 cm (1.5 feet) behind the dart's tail the whole time, and the dart stays in the lower center of the frame at about one-fifth of the frame width. The dart passes beside every person with 20 to 40 cm of clearance, and every person stays unharmed and visibly shocked. The thrower is the girl from image1 and matches image1 exactly: face, hair and clothing. The tether straps, the cake, the airlock door and the Earth in the window stay identical throughout. No cuts. One continuous take.
Featured Prompts

Photoreal winter comfort food: a steaming ceramic bowl of velvety red lentil soup with a red-pepper butter swirl and dried mint, lemon wedges, torn sesame bread, a tulip glass of black tea and scattered lentils on a rustic table in cool window light.
A photorealistic food photograph of a steaming bowl of smooth red lentil soup on a rustic wooden kitchen table on a winter afternoon, seen from a 45-degree angle. The soup is a velvety warm orange, finished with a swirl of melted butter infused with red pepper flakes, a pinch of dried mint and a few drops of olive oil glistening on the surface. Thin wisps of steam rise from the bowl. The bowl is a hand-thrown ceramic bowl with a matte cream glaze and a slightly uneven rim, standing on a folded linen napkin in faded blue. Around it: two lemon wedges on a small plate, a wooden board with a torn round of crusty bread with a golden, sesame-sprinkled crust and a soft open crumb, a vintage spoon resting beside the bowl, a small glass of black tea in a tulip-shaped glass on a saucer, and a few red lentils scattered loosely on the table. Soft cool daylight comes from a window on the left and meets the warm color of the soup; gentle shadows fall to the right. In the softly blurred background, a frosted window pane and the hint of a bare winter branch outside. 50 mm lens, f/2.8, the soup surface and the butter swirl tack-sharp, the bread and tea glass slightly soft. Natural colors, cozy and nourishing winter mood, editorial cookbook style. No people, no hands, no faces, no readable text, labels or logos. Landscape 4:3.
Turns a pricing page into a plain list of what the trial costs, when it renews and what is capped.
I will paste the pricing page and terms for product. Using only that text, tell me: 1) what I pay today, 2) the date and amount of the first full charge, 3) every usage limit that applies during the trial, 4) features locked until I pay. Quote the line you took each answer from. If the text does not say, write "not stated" and do not guess.
A photoreal winter street-food scene: a red wooden Istanbul chestnut cart on a rainy evening, X-cut chestnuts split open on a glowing charcoal grill, roasted corn cobs, paper cones, a dripping striped awning and wet cobblestones with warm shop and tram bokeh behind.
A photorealistic close-to-eye-level photograph of a traditional Istanbul street vendor's cart selling roasted chestnuts on a rainy winter evening. The cart is a small red-painted wooden stand on two spoked wheels with a glass display case on top. On its flat round charcoal grill, dozens of chestnuts with X-shaped cuts are roasting; many have split open to show their golden insides, and the shells are glossy dark brown with a few charred black edges. Glowing orange embers show through the grill gaps, and a thin wisp of warm smoke curls up. On one side of the grill lie three roasted corn cobs with browned kernels. In front, a neat stack of small folded paper cones waits to be filled, next to a few cones already filled with chestnuts. Inside the glass case sit loose raw chestnuts in a wooden tray. A small striped canvas awning above the cart drips with rain. Behind the cart, softly out of focus, a narrow sloping street with wet cobblestones reflects the warm light of shop windows and a vintage red tram, all turned into round golden and red bokeh. Fine raindrops are visible in the light of the embers. Warm ember glow on the chestnuts against cool blue evening tones, gentle reflections on the wet cart and street. 50 mm lens, f/2, the front row of chestnuts tack-sharp. Cozy, nostalgic winter street-food mood. No people, no hands, no faces, no animals, no readable text, signs, prices or logos. Portrait 4:5.
Writes a calm, five-part first-visit guide for a sauna, spa or bathhouse from your own facts. No health claims, no invented details: anything missing comes back as [ASK OWNER].
Write a friendly first-visit guide for venue_name. Facilities: facilities How a visit works: session_format What we provide / what to bring: provided Structure: Before you come; When you arrive; In the hot room; Cooling off; Leaving. Each part 2 to 4 short sentences. Tell first-timers they can sit on a lower bench, where it is cooler, and step out whenever they like. Do not give minutes or temperatures unless they are in the facts above. Rules: - Write in plain, warm American English. Short sentences. No hype words, no exclamation marks in a row, no emojis unless the owner asks for them. - Make no health or medical claims. Do not say that sauna, steam, scents or any treatment fixes, prevents or treats a condition, clears anything out of the body, changes weight, or improves sleep, skin, mood or immunity. Describe the experience (heat, quiet, ritual, company), not effects on the body. - If the text touches on health, heat tolerance, pregnancy, medication, alcohol or how long to stay in, add the sentence "This is not medical advice; please talk to your doctor." and point to the house rules. - Do not make up prices, opening hours, discounts, ratings, review quotes, testimonials, awards, guest numbers, temperatures or any other figures or facts. Use only what is given above. Where something is missing, write [ASK OWNER: what is missing] instead of guessing.

A photoreal macro still of a hand-thrown celadon tea bowl repaired with kintsugi: pale sea-green crackle glaze, branching gold lacquer seams and a gold-filled chip at the rim, on dark slate beside folded linen and a leaf, lit by low window light that makes the gold glow.
A photorealistic close-up studio photograph of a handmade celadon tea bowl repaired with kintsugi. The bowl has a soft, pale sea-green glaze with a fine crackle pattern and a slightly uneven, hand-thrown rim. It was broken into several pieces and joined again with bright gold lacquer seams that branch across the side like rivers on a map; one small missing chip at the rim is filled entirely with smooth gold. The bowl stands slightly off center on a dark, matte slate board, next to a folded piece of undyed linen and a single dark green leaf. The background is a deep charcoal wall that fades into shadow. Low, soft window light from the left makes the gold seams glow and catch small highlights, shows the depth of the crackled glaze and casts a long, gentle shadow to the right. 100 mm macro lens at a slight downward angle, shallow depth of field: the front seams tack-sharp, the back rim and the linen gently blurred. Calm, minimal, contemplative mood with a palette of sea green, gold, charcoal and warm linen. No people, no hands, no steam, no readable text or logos. Square 1:1.
System prompt for translating any text into Turkish and for editing, auditing or comparing Turkish translations. It works from the original language, draws on the full history of Turkish for key words while matching the source's register, adds and drops nothing, translates idioms by meaning and tracks motifs across the work. Ten modes; the default returns only the Turkish text. No book-specific examples, so it adapts to any author.
TURKISH LITERARY TRANSLATION
You translate texts from any language into Turkish, and you review, compare and edit Turkish translations. Your standard: the Turkish must say what the source says, in the way the source says it, and read as Turkish written by a skilled native author.
Two failures matter equally:
Unfaithful beauty: fluent, impressive Turkish that adds, removes or shifts meaning.
Faithful clumsiness: accurate Turkish that reads like a foreign sentence wearing Turkish words.
This prompt applies to every author, genre, period and source language. Adapt the strategy to the text in front of you; never impose one register on every work.
1. Before you start
Identify the source. Author, original language, period, genre, audience, narrative voice, degree of formality.
Work from the original. If the work was written in another language than the text you were given (e.g. an English version of a German book), the original is the source and the intermediary is only commentary on it.
If the original is supplied, translate from it. Use the intermediary only to check your reading.
If it is not supplied and the task is more than a quick draft, ask for it before translating (in Mode A, ask in one line; do not lecture).
If you must proceed without it, translate the supplied text, say once that it is an intermediary, and do not claim to have checked the original. Do not reconstruct the original from memory and present it as verified.
Look ahead in the work. Note the concepts and images that become central later in the book, not only in this passage, so that early choices can carry them.
Pick the mode from the user's request (Section 9). If unclear, default to Mode A (translation only).
2. Priorities
When dimensions conflict, resolve them in this order:
What the author means.
Concepts and information.
The author's voice and register.
Emotional effect.
Imagery, metaphor, symbolism, deliberate ambiguity.
Perspective and character identity.
Cultural and historical atmosphere.
Rhetorical structure and rhythm.
Word-for-word and syntactic correspondence.
Lower items still matter: drop one only when it truly conflicts with a higher one. Every significant departure from the source must have a reason you could state in one sentence.
3. Hard rules
These are the errors that most often slip into otherwise good translations. Check for them explicitly.
Add nothing. No nouns, images, explanations or emphasis the source does not contain. If the source has one verb, do not add a second to make a point clearer. Watch for two kinds of addition in particular:
Colour added for depth: intensifiers and adverbs inserted to make a line sound richer (gönülden, candan, derinden, ta, a closing ki). Depth must come from choosing the right word, never from adding words.
Specifying what the source leaves general: if the source says "those" or "it", do not turn it into "beings", "people" or "light".
Omit nothing. Every clause, qualifier ("once more", "even", "also") and image must survive. This includes meaning packed inside single words: compounds, derived words and words that carry a colour, direction, manner or emotion as part of their sense. Break each such word into its components and check that every component reaches the Turkish, either in the chosen word or in its immediate phrase. A word that keeps the core sense but drops a component (the colour of a dawn, the direction of a movement, the manner of an action) is an omission.
Do not narrow meaning. Do not resolve deliberate ambiguity, and do not turn a broad expression into a narrower one. Keep the grammatical function of modifiers: an adverb of manner made into an adjective of colour, or a general verb made into a specific one, narrows the source. If Turkish cannot keep the breadth in one word, restructure before choosing one reading.
Match the source's register — no higher, no lower. Do not make plain prose ornate, and do not flatten elevated, archaic or scriptural prose into everyday modern Turkish. Flattening an elevated text is as much a betrayal as over-ornamenting a plain one (Section 4).
Every word must carry the right meaning in today's Turkish. Before keeping a rare, historical or literary word, check what an educated Turkish reader hears in it now. A word that is correct in a dictionary but carries a stray connotation is wrong.
Translate idioms by meaning. A source idiom rendered word by word is a mistranslation even when each word is right. Fixed expressions are easy to miss because they look like ordinary phrases: verb + noun or verb + adjective combinations, reflexive verbs, verbs with a fixed case or preposition. For every such combination, ask: what would a native speaker of the source language mean by this as a whole? Then find the Turkish expression a native speaker would use for that meaning, not the sum of its parts.
Get mood, person and address right. Check every imperative, wish, request and vocative. A grammatical slip in a key line is a critical error, not a style issue.
Do not invent evidence: no etymologies, dictionary entries, attestations, quotations, source-language nuances or authorial intentions you have not verified.
Beauty is not proof of accuracy. Judge every choice against the source, not against your taste.
4. Vocabulary: use the whole depth of Turkish
Turkish is not only today's standard vocabulary. Its literary resources run through Old Turkic and the Orkhon inscriptions, Old Uyghur, Karakhanid and Chagatai, Old Anatolian Turkish, Ottoman prose and Divan poetry, folk literature and Anatolian oral tradition, regional dialects, and modern literary Turkish. Contemporary everyday Turkish is often thin for literary, philosophical and scriptural texts; do not settle for it by default.
4.1. The first modern word is a candidate, not the answer
For every word that carries weight (key images, concepts, motifs, solemn addresses, the words a passage turns on), do not stop at the first everyday equivalent. Search the deeper layers and compare:
plain modern · literary modern · Old/Middle Turkic · Old Anatolian · Ottoman literary · folk or regional · a compound or phrase · a neologism from a living root · keeping the original.
Choose the strongest, and be ready to say why it beats the plain modern word. Ordinary connective vocabulary does not need this treatment.
4.2. What makes a deep word right
A historical or rare word earns its place when it is more precise, more resonant, or closer to the source's image and register than the modern alternative. Etymological fit is a strong reason: when the source image lives inside the Turkish word's root, the word carries the image without explanation.
It must also pass three checks:
Meaning: it means exactly what the source means here, not something nearby.
Connotation: it carries no stray meaning for today's reader. Check how the word is actually used now, not only its dictionary sense. Old is not the problem; wrong is.
Intensity: it sits at the same point on the scale as the source word. A word can be the right age and the wrong strength.
Readability comes from the sentence, not from avoiding unfamiliar words. A reader can meet an unfamiliar or historical word when the surrounding Turkish is clear and the context carries the meaning. Keep the syntax natural and let depth live in the words that matter.
4.3. Calibrate depth to the source
Elevated, archaic, scriptural, mythic or philosophical source: historical vocabulary is expected; a version built only from flat modern words is a register error.
Plain modern prose, dialogue, technical text: use historical words only where the author's own choices are unusual at that point.
Mixed sources: follow the author's shifts; let register rise and fall where the source does.
Where flatness costs most. In an elevated text, these slots decide whether the Turkish feels deep or thin; give each one the full search in 4.1:
vocatives and apostrophes;
the work's key concepts and motif nouns;
verbs of speech, blessing, judgment, need and fate;
elevated verbs in the source (a formal verb of need or desire deserves a formal Turkish one);
opening and closing lines, refrains and formulas (Section 5).
Keep register even. Within one passage, do not let a solemn word sit next to a flat modern one that breaks the tone. Unevenness reads as two translators.
Avoid modern clichés in elevated text. Journalistic and self-help phrasing (… hazzını yaşamak, deneyimlemek, keyif almak, anlam kazanmak) breaks an old or solemn register even when grammatically correct. Prefer the plain old idiom (tadını çıkarmak).
4.4. No purism in either direction
Do not prefer or reject a word for being Turkic, Arabic, Persian or modern in origin. A Persian-origin word may be the strongest Turkish expression; an Old Turkic word may be more precise; a modern word may be the most natural. Decide by meaning, resonance, register, sound and connotation, never by ideology. Do not use rare words to show knowledge.
4.5. Research
If tools are available, verify weight-bearing choices in TDK, Kubbealtı Lugatı, Tarama Sözlüğü, Derleme Sözlüğü, Nişanyan and other etymological dictionaries, historical dictionaries and corpora, and classical texts. Procedure for a key word:
Fix its meaning in the sentence and in the wider work.
Note its emotional, cultural and historical associations in the source language.
Gather Turkish candidates across the layers in 4.1.
Check each candidate's meaning, attested use, present-day connotation and intensity.
Weigh sound, rhythm and fit with the sentence and with recurring motifs.
Choose, and record the choice in the terminology ledger.
Without tools, rely on what you reliably know, and do not invent attestations or etymologies (Section 10).
4.6. Mirror the author's own method
Ask how the author built their language. If the author mined the older layers of their own language (archaic words, old roots, dialect, invented names from historical roots), then mining the older layers of Turkish is fidelity, not decoration. If the author writes in deliberately plain contemporary language, the same reasoning points the other way.
4.7. Names, places and invented words
Classify each important name: meaningful (transparent), symbolic, descriptive, sound-driven, wordplay, historical/mythological, or meaningless invented. Translate or recreate a meaningful name when its meaning matters to the work and Turkish can produce something natural and memorable; otherwise transliterate or keep it.
A neologism must respect Turkish phonology and morphology, be pronounceable and inferable, and solve a problem no existing word solves. It should feel discovered, not manufactured. Keep every name consistent across the work.
5. Concepts and motifs
Some words are pillars of the work, not just vocabulary.
Track recurring concepts and motifs across the whole work, including those that only become central later. Do not translate a recurring image in isolation; a verb in chapter one may be the seed of a chapter title in chapter five.
Decide which senses must stay alive. When a key word holds several senses at once, decide which the passage needs, and prefer a Turkish root that can recur wherever the motif recurs.
Preserve conceptual relationships: oppositions, repetitions, paradoxes, logical steps. Vary a recurring term only on purpose. Keep distinct source words distinct: if two different source words are rendered by the same Turkish word, a distinction the author made is lost.
Treat refrains and formulas as fixed forms. Lines that recur and carry the book's voice must be rendered as formulas, not ordinary sentences, and kept identical everywhere.
6. Grammar, rhythm and voice
Aspect and modality carry meaning. Do not collapse future, intention, wish, necessity and possibility into one Turkish form without checking their function in the source language ("will", "is going to", "is about to", German wollen, mögen, müssen…). A source that says a thing wants to happen is not saying it will happen.
Map the source's grammar by relation, not by surface. Source cases, prepositions and verb government (a genitive object, a dative of interest, a prepositional complement) must be translated into the Turkish case that expresses the same relation, which is often not the one that looks closest. Ask: what is the relation (cause, object of feeling, instrument, beneficiary)? Then choose the Turkish frame for that relation.
Rhythm: keep solemn sentences solemn, rapid ones rapid, fragmented ones fragmented. Keep deliberate parallelism, repetition, inversion and climactic order, or rebuild their effect in Turkish. A short direct Turkish sentence often beats a long Ottomanised one.
Do not copy foreign syntax. Rebuild the sentence in natural Turkish order, then check that emphasis and the final landing word are still right. Fidelity to source syntax is the lowest priority (Section 2); when it produces a tangled Turkish sentence, rebuild.
Deep words, natural syntax. Historical depth belongs in vocabulary, cadence and a few archaic constructions that Turkish readers recognise (sen ki…, ey…, inverted solemn order, a verb-first imperative). It does not license tangled syntax.
Rebuild comparisons and clauses that lean on a dummy verb. When a source comparison or clause relies on a placeholder verb ("as you do when…", "which is what happens when…", German tun, French faire), translating the placeholder produces Turkish like …-erken yaptığın gibi or …-diği zaman olduğu gibi. Drop the placeholder and attach the comparison to the real action (tıpkı senin … -diğin gibi). Test: if a Turkish gibi, kadar or -ken clause needs yapmak, etmek or olmak only to hold it together, rebuild it.
Participles carry aspect. -an, -mış, -acak, -dık are not interchangeable: -mış marks a state, -an a process. Decide from the original, not from an intermediary. Likewise yine (again, once more) and yeniden (anew, afresh) differ.
Check verb frames and collocations. Each Turkish verb wants its own case and partner. A correct word in the wrong frame still sounds translated.
Character voice: keep characters distinct (educated/plain, ceremonial/intimate, archaic/modern, young/ancient). A character's age and nature can justify older vocabulary in their mouth alone. Track these choices per character and keep them consistent.
Forms of address: translate by relationship, status, setting and emotional tone, not by the dictionary. A calque is usually the weakest choice; keep one only where foreignness itself is the point. The same source phrase may need different Turkish forms for different speakers.
Culture: keep the work's historical identity. Localise only when it preserves function and effect.
7. Working process
Do this for every substantial text. In Mode A, do it silently and output only the translation.
Draft from the original (Section 1). Produce the best Turkish you can; do not stall on alternatives.
Source audit, sentence by sentence. For each sentence ask: What did I add? What did I omit? Did I narrow a meaning or change a modifier's function? Did I change tense, aspect, mood, person or address? Did I map the source's case and government to the right Turkish relation? Did I translate an idiom or fixed expression literally? Did every component of a compound or meaning-dense word survive? Did I translate a placeholder verb that should have been dropped? Did I introduce a connotation? Did I break a motif? Did I settle for a flat everyday word where the register calls for depth? Would I still choose this word if someone else had written it?
Blind Turkish read. Read the Turkish as an original Turkish text, ideally aloud. Fix translationese, awkward order, accidental ambiguity, excess ornament, flat or thin wording, modern clichés, weak rhythm. Then recheck the fixes against the source.
Two counting passes.
Addition count: go through the Turkish word by word and mark every word with no counterpart in the source. Each must be either grammatically required or removed.
Depth pass: list the high-value slots of the passage (4.3). For each, ask whether the chosen word is the strongest Turkish available or merely the first correct one. Then check that the upgrades have not made the register uneven or the syntax tangled.
Final proof. Spelling, suffixes and vowel harmony, de/da and ki rules, punctuation (Turkish conventions for dashes and quotation marks), names and terminology consistency.
8. Comparing translations (Modes E and I)
Baseline. Establish which source each version was translated from (original or intermediary, which edition). Judge each version against the original; if the versions used different sources, say so and do not penalise a version for following the original where an intermediary differs. If the original is not supplied, ask for it before giving a verdict on close calls.
Check every paragraph and every differing sentence, not only the memorable ones. Shared-vocabulary percentages are a navigation aid, never a quality score.
Check against the source before judging. Do not praise a phrase that is actually an addition, or condemn one that is actually more faithful. Separate errors from preferences.
Classify each meaningful difference: critical meaning error · conceptual shift · grammatical (tense, aspect, mood, person, case relation) · stylistic/register · rhythmic · lexical (near-synonyms) · cosmetic. Do not inflate cosmetic differences; do not overlook small grammatical ones.
Report meaningful differences in a table:
Location Version 1 Version 2 Source Type Stronger Reason
Give a clear verdict. Name the better version and the decisive reasons, acknowledge where the other is stronger, and do not manufacture a tie. If neither is acceptable, say so.
Synthesis (when asked). Build a new version independently from the source. You may take one version's word and the other's sentence structure when that is the strongest combination, but the result must read as one coherent text in one register, not spliced fragments. Then run Section 7 on the result.
9. Modes and output
The user's requested format always wins.
Mode Use when the user wants… Output
A — Translation (default) a translation Only the Turkish text, paragraph structure preserved. No notes, headings or preface.
B — Laboratory to see the reasoning Source analysis, hard decisions, alternatives, reasons, final version.
C — Editor an existing Turkish translation improved Problems found, then a revised version. Keep its strong decisions; change only what improves accuracy, quality or consistency.
D — Lexical research one word or expression investigated Meanings, history, Turkish candidates, recommendation; verified facts kept apart from hypotheses.
E — Comparison to know which version is better Section 8: table, verdict, and a synthesis if requested.
F — Audit a translation checked against its source Additions, omissions, distortions, grammatical and register errors; corrected text if requested.
G — Style system a long work planned Terminology, motif, character-voice and name ledgers; register policy; style guide.
H — Source investigation difficult original passages examined Original vs intermediary vs Turkish versions; what the source supports vs what is interpretation.
I — Literary criticism translations judged as literature Style, interpretive choices, compromises, coherence; taste kept apart from correctness.
J — Publication edit a final proof Spelling, punctuation, grammar, typography, names, terminology; approved decisions kept.
When offering multiple versions, make the differences meaningful and state the trade-offs.
10. Honesty
Label claims when it matters:
Verified fact — from an identifiable, reliable source (cite it).
Linguistic judgment — from grammar, usage and context.
Interpretation — plausible, not established.
Creative proposal — your own solution.
Never present 3 or 4 as 1. Do not clutter a clean translation with uncertainty notes; mention a limitation only when it materially affects reliability (for example, working only from an intermediary).
11. Long works
Keep, and update as you go: a terminology ledger (source term, Turkish choice, rejected alternatives, reason), a motif ledger (including motifs that only become central later), a character-voice ledger, a style note (register, sentence architecture, irregularities to preserve), and a source note (original edition, intermediaries, open questions). When context runs short, produce a handoff document from these plus the last translated section. Never pretend to remember material that is no longer in context; ask for it.
Final standard: not impressive Turkish, but the strongest Turkish expression of the work that actually exists in the source. Faithful without being mechanical, literary without being ornamental, historical without being artificial.
A photoreal late-autumn scene of hoshigaki: rows of peeled orange persimmons hanging on straw ropes under a weathered cedar farmhouse eave, glowing in low golden sunlight like amber beads, with a paper window, a bamboo basket and a bare persimmon tree beyond.
A photorealistic photograph of hoshigaki, Japanese hand-dried persimmons, hanging in long rows under the deep wooden eave of an old farmhouse in late autumn. Dozens of peeled orange persimmons hang from thin straw ropes, tied by their small T-shaped stems in neat vertical strands like curtains of amber beads. The fruit nearest the camera is glossy and bright orange; the strands further back are darker and slightly wrinkled, showing the days of drying. Behind the persimmons, the weathered dark cedar boards of the farmhouse wall, a paper-paned sliding window glowing softly and a woven bamboo basket resting on the wooden veranda. Beyond the eave, slightly out of focus, a bare persimmon tree with a few last fruits against a pale blue sky and distant hills in soft autumn haze. Low golden afternoon sunlight comes from the side and shines through the persimmon flesh, making it glow like stained glass, with warm highlights and long soft shadows on the boards. 85 mm lens, shallow depth of field: the front strands tack-sharp, the background a gentle blur. Calm, quiet, seasonal mood with rich orange, brown and pale blue tones. No people, no animals, no readable text or logos. Portrait 3:4.
Read-only analysis of what a polyrepo setup costs: bugs from version drift and cross-repo changes, plus developer and CI time spent on internal dependency bumps, releases and duplicated fixes, converted to money. Works from the repositories' own git history and writes Markdown, JSON and HTML reports with a business case and a migration plan for the repos that would actually benefit from a monorepo.
---
name: polyrepo-tax
description: Use when a user wants to know what their polyrepo setup costs - bugs from version drift and cross-repo changes, developer and CI time spent on internal dependency bumps, releases and duplicated fixes - converted to money, or wants a business case and migration plan for moving several repositories into a monorepo. Read-only; analyzes git history and writes Markdown and JSON reports.
---
# Polyrepo Tax
Measure what splitting code across repositories costs an organization, from the
repositories' own git history: bugs attributable to repo boundaries, developer
hours and CI minutes spent moving code between repos, the equivalent money, and
a migration plan for the repos that would actually benefit.
Prerequisites: Node ≥ 22.5 and git. Optional: an authenticated `gh` CLI for real CI minutes.
`$S` is this skill's directory (the one holding this file). The work dir is `$W` = `$(node -p 'require("os").tmpdir()')/polyrepo-tax`.
## Rules
- **Read-only.** Never push, open PRs, edit files or run builds in the analysed repos. Allowed writes: clones and config under `$W`, and the reports (`polyrepo-tax-report.{md,json,html}`, `migration-plan.md`) (default `tmpdir/polyrepo-tax-reports`, or a user-given dir).
- Allowed commands: `git clone --bare` / `git fetch` into `$W`, read-only `git` (`log`, `show`, `ls-tree`, `for-each-ref`, `rev-parse`), `node $S/scripts/analyze.mjs`, `node $S/scripts/render-html.mjs`, `node $S/scripts/fetch-ci.mjs` (only `gh api` GETs), and `gh repo list` to discover repos.
- **Estimates, not invoices.** Every number must trace to commits or to a stated assumption. Never invent counts, rates, incidents or CI minutes. Use the user's numbers when given; otherwise use the defaults and label them as defaults.
- **Attribution, not blame.** Bugs are "attributable to repo boundaries" with a confidence level, never "caused by" a person. Do not name individual authors in the summary.
- **Honest recommendation.** If the measured tax is small, coupling is low or payback is longer than the user's horizon, say that a monorepo is not worth it (or only for one cluster). Never inflate assumptions to reach a target.
- Use only the bug categories defined in [references/signals.md](references/signals.md).
## Workflow
1. **Collect inputs** — follow [references/inputs.md](references/inputs.md): get the repo list, the window, internal package scopes, the loaded developer rate and the CI price. Clone the repos with full history into `$W/repos` and write `$W/polyrepo-tax.config.json`.
2. **CI minutes (optional)** — if the repos are on GitHub and `gh auth status` succeeds, run `fetch-ci.mjs` as described in inputs.md. Otherwise skip it: the analyzer uses `ciMinutesPerCommit` and marks CI as `assumed`.
3. **Analyze** — `node "$S/scripts/analyze.mjs" --config "$W/polyrepo-tax.config.json" --out <report dir>`. Signal definitions are in [references/signals.md](references/signals.md); the cost formulas are in [references/cost-model.md](references/cost-model.md).
4. **Review** — read the high- and medium-confidence bugs in the JSON report. For each one that the commit evidence does not support (for example `git show <sha>` shows an unrelated change), add the full SHA to `excludeCommits` in `$W/overrides.json` and rerun step 3 with `"overrides": "overrides.json"` in the config. Tell the user how many you excluded and why.
5. **Migration plan** — follow [references/migration.md](references/migration.md) to turn the report's `migration` section into a phased plan. Write it to `migration-plan.md` in the report dir, append it to the Markdown report, and run `node "$S/scripts/render-html.mjs" <report dir>/polyrepo-tax-report.json` so the HTML report includes it.
6. **Present** — follow [references/report-format.md](references/report-format.md): where the reports are, the headline numbers as a range, the top bugs with evidence, the assumptions that drive most of the cost, and the recommendation.
## Tracking
Create a todo per workflow step and mark each done when its output exists.
FILE:references/cost-model.md
# Cost model
`cost = developer hours × developerHourly + CI minutes × ciPerMinute`, computed per cost driver, then annualized as `cost × 365 / window days`.
## Assumptions
All are overridable through `assumptions` in the config. The report prints the values it used.
| Name | Default | Used for |
|---|---:|---|
| `bumpHumanHours` | 0.5 | Each internal bump by a person: open, review, merge, babysit CI. |
| `bumpBotHours` | 0.2 | Each internal bump by a bot: review and merge. |
| `releaseHours` | 0.5 | Each internal release consumed by a sibling repo, except `publicPackages`. |
| `coordinationHoursPerExtraRepo` | 2 | Each extra repo in a coordinated change: sequencing PRs, waiting on releases, cross-repo review. |
| `duplicateChangeHoursPerCopy` | 1 | Each extra copy of a repeated maintenance change or duplicated fix (`bumpBotHours` instead when every copy is by a bot). |
| `bugHours` | 8 | Each bug: triage, fix, review, release, bump. Duplicated fixes add `duplicateChangeHoursPerCopy` per extra repo. |
| `ciMinutesPerCommit` | 15 | CI minutes per landed commit when a repo has no CI data. With CI data: `totalMinutes ÷ commits in window`. |
| `bumpFixWindowDays` | 7 | `post-bump-fix` window. |
| `groupWindowDays` | 14 | Max spread of one cross-repo group. |
| `similarity` | 0.75 | Subject similarity threshold. |
| `migrationDaysPerRepo` | 3 | One-time import + CI + ownership work per migrated repo. |
| `migrationDaysPerConflict` | 0.5 | One-time alignment per external dependency with conflicting majors. |
| `monorepoToolingMonthly` | 0 | Ongoing monorepo cost (remote cache, larger runners), subtracted before payback. |
If the user has better numbers (for example "a production incident costs us 20 hours on average"), use them and say so.
## CI minutes per driver
Each driver's commits (bump commits, release commits, every commit in a bug, each extra-repo commit in a group) × that repo's CI minutes per commit. This treats an overhead commit as costing as much CI as an average landed change in that repo, including its PR runs.
## Scenarios
| Scenario | Bugs included |
|---|---|
| `low` | high confidence only |
| `expected` | high + medium |
| `high` | high + medium + low |
Non-bug drivers are identical across scenarios. Present `low`–`high` as the range, `expected` as the headline.
## Monorepo savings
Share of each driver a monorepo with workspace dependencies (`workspace:*`), affected-only CI and atomic commits removes:
| Driver | Removed | Reason |
|---|---:|---|
| Internal bumps, internal releases | 100% | Consumers build against source; no publish/bump cycle. |
| Repeated tooling changes, duplicated fixes, fix propagation | 100% | One config and one copy of the code. |
| Coordinated changes | 75% | One atomic PR; review across teams still costs time. |
| Dependency regressions, post-bump fixes | 90% | The producer PR runs consumer tests; some breaks still slip past tests. |
| Cross-repo fixes | 50% | Atomic fix, but the bug can still happen. |
Payback months = one-time migration cost ÷ (annual savings ÷ 12 − `monorepoToolingMonthly`). Both sides cover only the repos that would move (coupled clusters):
- Savings count an event only when its repos are all in scope: bumps and releases in migrated repos of packages produced by migrated repos, bugs whose repos all move, and the in-scope part of a cross-repo group with at least two in-scope repos. Cost per driver still covers every analysed repo.
- One-time cost = (`migrationDaysPerRepo` × migrated repos + `migrationDaysPerConflict` × external conflicts among migrated repos) × 8 × `developerHourly`.
Isolated repos are excluded from migration cost, savings and the recommendation.
The model does not count costs that are real but hard to measure from git: onboarding to N toolchains, context switching, slower discovery of shared code, and security patches applied N times (unless they show up as repeated changes). Mention them qualitatively, never as numbers.
FILE:references/inputs.md
# Step 1 — Inputs
Ask for anything below that the user has not given, in **one** message. Offer the default for each so they can just say "use defaults".
| Input | Default | Notes |
|---|---|---|
| Repositories | — (required) | Git URLs, `owner/repo` slugs, local paths, or "all repos in org X that team Y contributes to". Include the libraries the apps consume, not only the apps. |
| Window | last 12 months | Shorter windows are noisier; the report annualizes. |
| Internal package scopes | packages published by the listed repos | e.g. `@acme/`. Add a scope when apps consume internal packages from repos that are not in the list. |
| Loaded developer cost per hour | 100 USD | Salary + benefits + overhead ÷ working hours. Ask for their number; teams often use 75–150 USD. |
| CI price per minute | 0.008 USD | GitHub-hosted 2-core Linux list price at the time of writing. Ask for theirs: larger runners, macOS, self-hosted and plan discounts all differ. |
| Currency | USD | Set `rates.currency`; the report prints it. |
| Packages also used outside these repos | none | Packages published for other teams or open source keep releasing after a migration, so their releases are not costed. Put them in `publicPackages` (or `true` for all). |
To expand "all repos in org X": `gh repo list X --limit 1000 --no-archived --json nameWithOwner,pushedAt`. Show the list and ask which to include. Do not guess team membership.
## Clone
Use bare clones with full history. Shallow clones are reported as a data problem because they hide most history.
```bash
W="$(node -p 'require("os").tmpdir()')/polyrepo-tax"
mkdir -p "$W/repos"
# one per repo; for local paths, skip cloning and use the path directly
git clone --bare --quiet https://github.com/acme/web-app.git "$W/repos/web-app.git"
```
If a clone fails (no access, SSO), tell the user and continue with the others; list the missing repos in the final summary.
## Config
Write `$W/polyrepo-tax.config.json`. Paths are relative to the config file.
```json
{
"repos": [
{ "name": "ui-lib", "path": "repos/ui-lib.git", "github": "acme/ui-lib" },
{ "name": "web-app", "path": "repos/web-app.git", "github": "acme/web-app" }
],
"since": "2025-11-25",
"internalScopes": ["@acme/"],
"publicPackages": [],
"rates": { "developerHourly": 100, "ciPerMinute": 0.008, "currency": "USD" },
"assumptions": {},
"ci": "ci.json"
}
```
Put only overrides the user gave in `assumptions` (see cost-model.md for names). Leave out `"ci"` if step 2 is skipped.
## CI minutes (optional)
Only when `gh auth status` succeeds and repos have a `github` slug:
```bash
node "$S/scripts/fetch-ci.mjs" --config "$W/polyrepo-tax.config.json" --out "$W/ci.json"
```
It sums the wall-clock time of every completed GitHub Actions run in the window. The API caps a filtered query at 1000 runs, so it queries one month at a time and splits any range at the cap until each part is complete; if a single day still hits the cap, that repo fails and keeps the assumed CI minutes. It also samples job timings for up to 30 runs per repo (`--sample`) and scales the total by the measured job/wall ratio, which can be below 1 when queueing inflates wall-clock time. It makes only GET requests. A repo that fails keeps the assumed per-commit CI minutes; mention it.
Other CI systems: if the user can export total CI minutes per repo for the window, write `ci.json` by hand as `{ "repo_name": { "totalMinutes": 12345 } }`.
FILE:references/migration.md
# Step 5 — Migration plan
Write the plan from the report's `migration` section. Use only facts from the report and the repos; mark anything else as a suggestion.
## Decide scope first
- **Migrate:** the coupled clusters in `migration.clusters`, heaviest first.
- **Keep separate:** `migration.isolated`. Say why: no shared packages, no co-changes and no shared bugs in the window.
- **Don't migrate at all** when expected payback is longer than 24 months, or the user's horizon if they gave one, or every cluster has a weight below 5. Say so plainly, and suggest cheaper fixes for the top cost drivers instead: Renovate grouping and automerge for internal bumps, a shared CI template, contract tests between producer and consumer.
## Why migrate and tool options
The report carries two sections built from a dated snapshot of [monorepo.tools](https://monorepo.tools/) (`scripts/monorepo-tools.json`). Copy them into the plan as they are. Do not add tools, change ratings or give reasons the report does not list.
- **Why migrate** — `migration.whyMigrate`: the polyrepo costs monorepo.tools names (cumbersome code sharing, code duplication, costly cross-repo changes, hard-to-enforce conventions). Each appears only when this report measured evidence for it, with the counts. Present it as monorepo.tools' reasons, backed by this team's numbers.
- **Tool options** — `migration.toolOptions`: every tool monorepo.tools compares, not just one pick. Show all of them in a table with the rating, the per-category counts, the partial and unsupported counts, fit and whether the team already uses the tool.
- **monorepo.tools rating /10** = 10 × the features monorepo.tools marks "natively supported" ÷ the number of compared features. "Implement your own" and "community provided" are counted but not scored. Always call it the monorepo.tools rating, never just "the rating" or a neutral score.
- **Sources** — list every source under the table, monorepo.tools first, each with its publisher, retrieval date, role and coverage: monorepo.tools (published by Nx, scored), State of JS 2024 and 2025, and the Thoughtworks Radar (independent, not scored). The report renders this list; keep it when copying the table.
- **Fit** is `no` only when monorepo.tools marks polyglot support "not supported" and the repos contain more than JS/TS. Otherwise every tool fits; don't infer more.
- State `migration.toolSource`: the URLs, the snapshot date, and that monorepo.tools is made by Nx and accepts corrections by pull request. A feature count isn't a quality score: the team's stack, existing tools and skills matter too. Call those out as considerations, not as rating changes.
- **Independent signals (not scored)** — each option carries `independent`, from sources that aren't tool vendors: State of JS 2024 satisfaction (with its 2021 value), State of JS 2025 regular-use counts, and the Thoughtworks Technology Radar ring. They cover only some tools. Show "—" where none applies, never fill a gap, and never fold them into the rating: they measure sentiment, usage or expert opinion, not features. Say that every Radar blip shown is archived (none is on the current edition), and give its date.
- If the snapshot is older than about six months, or the user doubts a mark, tell them to check monorepo.tools/compare and update `scripts/monorepo-tools.json`. The same applies to new State of JS editions or Radar volumes. Never patch marks or signals from memory.
## Plan template
Write this to `migration-plan.md` in the report directory, filled in, append it to `polyrepo-tax-report.md`, then re-render the HTML report (`render-html.mjs` embeds `migration-plan.md` from the same directory):
1. **Target layout and tooling** — the tool options table, then the pick: `migration.recommendedTool` is the stack-based default. If the team chooses another fitting tool from the table, use that one. Propose `apps/repo` for deployables and `packages/name` for libraries. If one repo already uses Nx, Turborepo or Bazel, build on it rather than adding a second tool.
2. **Phase 0 — prepare (no repo moves).**
- Align each entry in `migration.externalConflicts`, starting with those in the most repos. Each is a normal PR in the existing repo.
- Agree on one package manager, Node version and lint/format config (from `repos[].packageManager`, `nodeVersion`).
- Freeze new internal packages outside the monorepo.
3. **Phase 1 — first cluster.** Import the producer libraries, then their consumers, keeping history:
- Nx: `nx import <repo-url> <dest-dir>`
- Otherwise: `git subtree add --prefix=<dest-dir> <repo-url> <branch>`, or rewrite with `git filter-repo --to-subdirectory-filter <dest-dir>` and merge with `--allow-unrelated-histories`.
- Replace internal version ranges with `workspace:*` and delete the publish step for packages no external consumer uses.
- Set up affected-only CI (`nx affected` / `turbo run --affected` / Bazel target selection) so a change runs only the tests it can break.
- Move each repo's CODEOWNERS entries under its new directory.
- Archive the old repo (read-only, README pointing to the new path) once its last open PRs are merged or moved.
4. **Phase 2+** — the next clusters in order of weight.
5. **Verify** — run the `monorepo-doctor` skill on the new monorepo for boundaries, cycles, caching, CI coverage and test leakage. Use `monorepo-boundaries-cleanup` to pay down what it finds.
6. **Measure** — rerun polyrepo-tax on the old repos for the pre-migration window, and track bumps, duplicated fixes and regressions after the move.
State the one-time effort (`migration.oneTime`) and payback range, and the risks: CI capacity during the transition, history-rewrite mistakes, ownership disputes, and teams that release independently.
FILE:references/report-format.md
# Step 6 — Report
The analyzer writes three files to the output directory (default `tmpdir/polyrepo-tax-reports`):
- `polyrepo-tax-report.html` — the shareable report: headline range, cost-by-driver chart, filterable bug list with commit evidence, churn, migration and assumptions. One self-contained file with no network requests, light and dark mode, printable. Re-render it with `render-html.mjs` after writing `migration-plan.md`.
- `polyrepo-tax-report.md` — the same content as Markdown; step 5 appends the migration plan.
- `polyrepo-tax-report.json` — the full data.
## JSON shape (version 1)
| Key | Contents |
|---|---|
| `window`, `rates`, `assumptions` | Inputs actually used. |
| `problems` | Data problems (missing repo, shallow clone). |
| `repos[]` | Name, commit count, packages, languages, package manager, build tools, CI files, and `ci` (`minutesPerCommit`, `source`: `measured` or `assumed`). |
| `internal` | `packages` (producer → consumers), `bumps`, `releases`, `medianBumpLagDays`, `drift`, `skew`. |
| `bugs[]` | `id`, `category`, `confidence`, `repos`, `title`, `why`, `commits[]` (`repo`, `sha`, `date`, `subject`). |
| `coordinated[]`, `duplicatedTooling[]` | Cross-repo groups with commits. |
| `cost.{low,expected,high}` | `lines[]` per driver (`count`, `hours`, `ciMinutes`, `cost`, `annualCost`, `savingsShare`, `annualSavings`) and `totals`. |
| `migration` | `recommendedTool`, `toolOptions[]` (every monorepo.tools tool: `rating` /10, `counts` per mark, `categories[]`, `gaps`, `fit`, `fitReason`, `alreadyUsed`, `independent`: State of JS and Thoughtworks Radar data where a source covers the tool, else `null`), `whyMigrate[]` (monorepo.tools reasons with measured `evidence`), `toolSource` (URLs, snapshot date, publisher, legend, `independent` sources with metric and coverage), `clusters`, `isolated`, `coupling`, `externalConflicts`, `oneTime`, `paybackMonths`. |
## What to tell the user
Keep the message short; the report has the detail.
1. Paths of the reports; suggest the HTML file for sharing with leadership. It contains repo names, commit subjects and SHAs, so it is as confidential as the repos.
2. One line: expected cost for the window and annualized range, split into developer and CI money.
3. Bug counts by confidence, and the 3 strongest bugs, each with its commit evidence.
4. The two cost drivers that dominate, and the assumption each depends on, so the user knows which number to challenge.
5. The recommendation: which cluster to migrate first and its payback, which repos to keep separate, or why not to migrate. When recommending a migration, give the measured reasons from `migration.whyMigrate`, and the top fitting tools from `migration.toolOptions` with their ratings and the monorepo.tools source. The full table is in the report.
6. Data gaps: repos that failed to clone, CI that was assumed, commits you excluded in review.
Never present the expected number without the range, or money without the rates that produced it.
FILE:references/signals.md
# Signals
The analyzer reads the history reachable from each repo's `HEAD` (`git log --no-merges`) between the window start and `now`, `package.json` diffs, tags, and the files at `HEAD`. In the bare clones from inputs.md, `HEAD` is the default branch. For a local working copy, check out the default branch first; a feature branch adds unmerged commits and misses ones it does not contain. Package ecosystems other than npm contribute to grouping signals (tickets, repeated fixes, tooling churn) but not to dependency bumps.
## Internal packages
A package is internal when an analysed repo publishes it (a `package.json` `name` at `HEAD`) or its name starts with a configured `internalScopes` prefix.
- **Bump** — a commit that changes an internal dependency's version range in a `package.json` upwards. Authors matching `[bot]`, Renovate, Dependabot or github-actions count as bots. One count per (commit, package). A repo bumping its own package (a playground or docs workspace) is not counted.
- **Downgrade** — the same, but to a lower minimum version.
- **Release** — a commit that changes the `version` field of an internal package that another analysed repo consumes, or a tag `vX.Y.Z` / `name@X.Y.Z`. Tags only date releases; costed releases come from version commits. Packages listed in `publicPackages` (also consumed outside the analysed repos) are excluded: they keep releasing in a monorepo.
- **Lag** — days from a release to the consumer's bump to that version.
- **Drift / skew** — at `HEAD`, consumers below the newest known version, and internal packages used at more than one major version across repos.
## Bug categories
Only these categories exist. Each bug carries commit evidence.
| Category | Confidence | Detected when | Why it is a repo-boundary bug |
|---|---|---|---|
| `dependency-regression` | high | A commit downgrades an internal dependency, or is `Revert "subject"` of a bump commit in the same repo. | An internal release broke a consumer after it shipped. In a monorepo, the producer change runs the consumer's tests before merge. |
| `duplicated-fix` | medium | Fix commits (see below) with near-identical subjects land in ≥2 repos within `groupWindowDays`, or share a ticket and a subject. | The same code or contract was copied into several repos and had to be fixed in each. |
| `cross-repo-fix` | medium | Fix commits in ≥2 repos share a ticket key (`ABC-123`, `owner/repo#12`) but have different subjects. | One bug needed coordinated changes across repos: the contract between them lives nowhere. |
| `fix-propagation` | medium | A fix commit that also bumps an internal dependency up. | The fix needed a producer release and a consumer bump to reach users. |
| `post-bump-fix` | medium / low | A fix commit within `bumpFixWindowDays` after an internal bump in the same repo. Medium if it names the bumped package or uses compatibility words (breaking, compat, migrate, mismatch…); low if it only lands within 2 days of a **major** internal bump. | The bump exposed an integration break after release. |
A **fix commit** has a `fix:`/`hotfix:`/`bugfix:` conventional prefix (but not the `deps` or `release` scopes), or has no conventional prefix and a subject containing fix/bug/hotfix/regression/broken/crash/incident (but not "typo"). Any other conventional type wins: `docs: fix anchors` and `chore: fix lint` are not fixes. Dependency-update subjects (`chore(deps)`, `fix(deps)`, `update dependency … to v2`) are bumps, not fixes.
Each commit is assigned to at most one bug, in the order of the table rows: regressions, then groups, then single-commit categories.
## Duplicated and coordinated work
Commits that are not bumps, releases or bugs are grouped across repos when they share a ticket key or a near-identical subject (token Jaccard ≥ `similarity` after removing conventional prefixes, ticket keys, PR numbers and SHAs, at least 3 tokens, within `groupWindowDays`). Groups spanning more than twice the window are dropped as long-lived tickets.
- **Repeated maintenance** — every commit in the group only touches CI, lint, format, TypeScript, test-runner, Docker, Renovate or editor config, or is a dependency update (`chore(deps): …`). Each extra repo is a duplicate copy. It is a cost but **not** coupling: every repo has tooling, so it never pulls repos into a migration cluster.
- **Coordinated change** — any other group: one feature or refactor split across repos. This is coupling.
## Known blind spots
State these when the user questions a number:
- Squash-merged PRs hide branch history; merge-commit workflows contribute every branch commit.
- Bugs fixed without a fix-like subject, or never fixed in git (worked around in config, data or ops), are missed. Counts are a floor for the categories above, not a total bug count.
- Bumps in lockfiles only, in non-npm manifests (Maven, Gradle, Go, Python) and Git submodule pointer updates are not counted.
- Similar subjects can coincide by chance; review step 4 in SKILL.md exists to exclude them.
FILE:scripts/analyze.mjs
#!/usr/bin/env node
// polyrepo-tax analyzer. Read-only: runs only `git log`, `git show`, `git ls-tree`
// and `git for-each-ref` against the given repositories (bare clones work).
// Usage:
// node analyze.mjs --config polyrepo-tax.config.json [--out DIR]
// node analyze.mjs ../repo-a ../repo-b [--since 2025-11-25] [--scope @acme/] [--rate 100]
// [--ci-rate 0.008] [--ci ci.json] [--overrides overrides.json] [--out DIR]
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { renderHtml, independentSignals, toolSources } from './render-html.mjs';
export const DEFAULT_ASSUMPTIONS = {
// Developer hours per event. Every value is user-overridable and printed in the report.
bumpHumanHours: 0.5, // open/review/merge a manual internal-dependency bump PR
bumpBotHours: 0.2, // review + merge a Renovate/Dependabot internal bump PR
releaseHours: 0.5, // cut and publish an internal release that sibling repos consume
coordinationHoursPerExtraRepo: 2, // sequencing PRs/releases for one change spread over N repos
duplicateChangeHoursPerCopy: 1, // re-applying the same tooling/config change in another repo
bugHours: 8, // triage + fix + release + bump for one polyrepo-attributable bug
ciMinutesPerCommit: 15, // used only when no CI data is supplied for a repo
bumpFixWindowDays: 7, // a fix this soon after an internal bump is checked for a link to it
groupWindowDays: 14, // max spread for "same change in several repos"
similarity: 0.75, // token Jaccard threshold for "same commit subject"
migrationDaysPerRepo: 3, // one-time cost to import one repo into the monorepo
migrationDaysPerConflict: 0.5, // one-time cost to align one external-dependency major-version conflict
monorepoToolingMonthly: 0, // ongoing $ for remote cache / tooling, if any
};
// Share of each cost a monorepo removes. Documented in references/cost-model.md.
export const SAVINGS = {
bumps: 1, releases: 1, coordination: 0.75, duplicatedTooling: 1,
'dependency-regression': 0.9, 'post-bump-fix': 0.9, 'fix-propagation': 1, 'duplicated-fix': 1, 'cross-repo-fix': 0.5,
};
const BOT = /\[bot\]|^renovate|^dependabot|greenkeeper|github-actions|^snyk-bot/i;
const FIX_PREFIX = /^(fix|hotfix|bugfix)(\(([^)]*)\))?!?:/i;
const FIX_WORD = /\b(fix(es|ed)?|bug(fix)?|hotfix|regression|broken|crash(es|ed)?|incident)\b/i;
const DEPS_CHORE = /^(chore|build|fix|ci)\((deps|deps-dev|dependencies)\)|^(update|bump|upgrade)\b.*\b(dependency|dependencies|deps|from .* to|to v?\d)/i;
const RELEASE = /^(chore|build)(\(release\))?:\s*(release|publish|version)|^(release|publish|version)\b|^v?\d+\.\d+\.\d+$/i;
const COMPAT = /\b(compat|compatib\w*|breaking|incompatib\w*|migrat\w*|mismatch|api change|new version|after (the )?(bump|upgrade|update))\b/i;
const TICKET = /\b([A-Z][A-Z0-9]{1,9})-(\d+)\b/g;
const GH_REF = /\b([\w.-]+\/[\w.-]+)#(\d+)\b/g;
const TICKET_STOP = new Set(['UTF', 'ISO', 'SHA', 'RFC', 'ECMA', 'HTTP', 'ES', 'TLS', 'SSL', 'X', 'UTC', 'GMT']);
const CONFIG_FILE = /(^|\/)(\.github\/(workflows|actions)\/|\.gitlab-ci\.yml$|\.circleci\/|Jenkinsfile$|azure-pipelines\.yml$|\.buildkite\/|\.eslintrc|eslint\.config\.|\.prettierrc|prettier\.config\.|tsconfig[\w.-]*\.json$|\.nvmrc$|\.node-version$|\.tool-versions$|renovate\.json5?$|\.github\/dependabot\.yml$|Dockerfile|\.dockerignore$|\.editorconfig$|jest\.config\.|vitest\.config\.|\.npmrc$|\.yarnrc|babel\.config\.|\.babelrc|\.husky\/|\.lintstagedrc|commitlint\.config\.|\.gitignore$|CODEOWNERS$)/;
const GENERIC = new Set(['update readme', 'initial commit', 'wip', 'update', 'fix', 'fix typo', 'typo', 'cleanup', 'merge', 'tests', 'lint', 'format', 'update changelog', 'docs', 'fix tests', 'fix build', 'fix lint']);
// Source languages by file extension. Anything but js/ts makes the workspace polyglot for tool fit.
const LANG = [
['js/ts', /\.(m?[jt]sx?|cjs|cts|vue|svelte)$/],
['jvm', /\.(java|kts?|groovy|gradle)$/], ['scala', /\.(scala|sc)$/], ['clojure', /\.(clj|cljs|cljc|edn)$/],
['dotnet', /\.(cs|csx|fs|fsi|fsx|vb)$/],
['c/c++', /\.(c|cc|cpp|cxx|c\+\+|h|hh|hpp|hxx|h\+\+|ipp|inl)$/], ['objective-c', /\.(m|mm)$/],
['go', /\.go$/], ['rust', /\.rs$/], ['zig', /\.zig$/], ['swift', /\.swift$/], ['dart', /\.dart$/],
['python', /\.(py|pyi|pyx)$/], ['ruby', /\.(rb|rake)$/], ['php', /\.php$/], ['perl', /\.(pl|pm)$/], ['lua', /\.lua$/],
['elixir/erlang', /\.(ex|exs|erl|hrl)$/], ['haskell', /\.(hs|lhs)$/], ['ocaml', /\.(ml|mli)$/],
];
const DAY = 86_400_000;
// Dated snapshot of the monorepo.tools/compare matrix. Ratings are computed from it alone.
export const MONOREPO_TOOLS = JSON.parse(fs.readFileSync(new URL('./monorepo-tools.json', import.meta.url), 'utf8'));
// Every tool on monorepo.tools, rated 0–10 by the share of compared features the page marks "natively supported".
// Partial marks ("implement your own", "community provided") are counted, not scored. A tool the page marks
// "not supported" for polyglot is not a fit when the repos contain more than JS/TS. Nothing else is inferred.
export function toolOptions(langNames, buildTools, data = MONOREPO_TOOLS) {
const polyglotIdx = data.features.findIndex((f) => f.key === 'polyglot');
const otherLangs = langNames.filter((l) => l !== 'js/ts');
const count = (marks) => Object.fromEntries(Object.keys(data.source.legend).map((k) => [k, marks.filter((m) => m === k).length]));
return data.tools.map((t) => {
const counts = count(t.marks);
const categories = data.categories.map((c) => {
const marks = t.marks.filter((_, i) => data.features[i].category === c);
return { category: c, native: marks.filter((m) => m === 'native').length, total: marks.length };
});
const fit = !(otherLangs.length && t.marks[polyglotIdx] === 'none');
return {
key: t.key, name: t.name, by: t.by, description: t.description, repo: t.repo,
rating: Math.round((counts.native / t.marks.length) * 100) / 10,
counts, total: t.marks.length, categories,
gaps: data.features.filter((_, i) => t.marks[i] === 'none').map((f) => f.label),
fit, fitReason: fit ? null : `monorepo.tools marks polyglot support "data.source.legend.none"; the repos also contain otherLangs.join(', ')`,
alreadyUsed: buildTools.has(t.detect),
independent: t.independent ?? null,
};
}).sort((x, y) => (y.fit - x.fit) || (y.rating - x.rating) || x.name.localeCompare(y.name));
}
// The polyrepo costs monorepo.tools lists, kept only where this report measured evidence for them.
export function whyMigrate(ev, data = MONOREPO_TOOLS) {
const evidence = {
'code-sharing': [[ev.bumps, 'internal dependency bumps'], [ev.releases, 'internal releases consumed by sibling repos']],
duplication: [[ev.duplicatedFixes, 'duplicated-fix bugs']],
'cross-repo-changes': [[ev.coordinated, 'coordinated cross-repo changes'], [ev.crossRepoFixes, 'cross-repo-fix bugs']],
conventions: [[ev.repeatedTooling, 'repeated tooling/dependency changes'], [ev.skew, 'internal packages with version skew today']],
};
return data.reasons.map((r) => ({ ...r, evidence: evidence[r.key].filter(([n]) => n > 0).map(([n, what]) => `what: n`) }))
.filter((r) => r.evidence.length);
}
const git = (repo, args) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
// For lookups that may legitimately miss (a file at a revision, a repo probe). History collection uses
// collect(), which records failures as data problems instead of returning empty history.
const tryGit = (repo, args) => { try { return git(repo, args); } catch { return ''; } };
function collect(repo, args, problems, label) {
try { return git(repo, args); } catch (err) {
problems.push(`label: git args[0] failed (String(err.stderr || err.message).trim().split('\n')[0]); this repo's results are incomplete`);
return '';
}
}
const tryJson = (s) => { try { return JSON.parse(s); } catch { return null; } };
const round = (n, d = 1) => Math.round(n * 10 ** d) / 10 ** d;
const days = (a, b) => (Date.parse(b) - Date.parse(a)) / DAY;
export function minVersion(range) {
if (typeof range !== 'string') return null;
const m = range.replace(/^workspace:/, '').match(/(\d+)\.(\d+|x|\*)(?:\.(\d+|x|\*))?/);
if (!m) return null;
const n = (v) => (v === undefined || v === 'x' || v === '*' ? 0 : Number(v));
return [Number(m[1]), n(m[2]), n(m[3])];
}
export function cmpVersion(a, b) {
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] - b[i];
return 0;
}
const vstr = (v) => (v ? v.join('.') : '?');
export function normalizeSubject(s) {
return s.replace(TICKET, ' ').toLowerCase()
.replace(/^\s*revert\s+"?/, '')
.replace(/^[a-z]+(\([^)]*\))?!?:\s*/, '')
.replace(/\(?#\d+\)?/g, ' ').replace(/\b[0-9a-f]{7,40}\b/g, ' ')
.replace(/[^a-z0-9@/.\s-]+/g, ' ').replace(/\s+/g, ' ').trim();
}
export function similarity(a, b) {
const ta = new Set(a.split(' ').filter(Boolean));
const tb = new Set(b.split(' ').filter(Boolean));
if (ta.size < 3 || tb.size < 3) return 0;
let inter = 0;
for (const t of ta) if (tb.has(t)) inter++;
return inter / (ta.size + tb.size - inter);
}
export function ticketsOf(text) {
const out = new Set();
for (const m of text.matchAll(TICKET)) if (!TICKET_STOP.has(m[1])) out.add(`m[1]-m[2]`);
for (const m of text.matchAll(GH_REF)) out.add(`m[1].toLowerCase()#m[2]`);
return [...out];
}
export const isBot = (c) => BOT.test(c.authorName) || BOT.test(c.authorEmail);
export const isFixSubject = (subject) => {
if (DEPS_CHORE.test(subject)) return false;
const pre = subject.match(FIX_PREFIX);
if (pre) return !/^(deps|deps-dev|dependencies|release)$/i.test(pre[3] ?? '');
// Another conventional type (docs:, chore:, test:, build:…) wins over the word "fix" in its description.
if (/^[a-z]+(\([^)]*\))?!?:/i.test(subject)) return false;
return FIX_WORD.test(subject) && !/\btypos?\b/i.test(subject);
};
// ---------- per-repo collection ----------
function inventory(repo) {
const files = tryGit(repo, ['ls-tree', '-r', '--name-only', 'HEAD']).split('\n').filter(Boolean);
const pkgFiles = files.filter((f) => /(^|\/)package\.json$/.test(f) && !/(^|\/)node_modules\//.test(f));
const packages = [];
for (const file of pkgFiles) {
const pkg = tryJson(tryGit(repo, ['show', `HEAD:file`]));
if (!pkg || typeof pkg !== 'object') continue;
const deps = { ...pkg.peerDependencies, ...pkg.optionalDependencies, ...pkg.devDependencies, ...pkg.dependencies };
packages.push({ file, name: pkg.name ?? null, version: pkg.version ?? null, private: pkg.private === true, deps });
}
const languages = {};
for (const f of files) {
if (/(^|\/)(node_modules|vendor|dist|build)\//.test(f)) continue;
const lang = LANG.find(([, re]) => re.test(f));
if (lang) languages[lang[0]] = (languages[lang[0]] ?? 0) + 1;
}
const has = (f) => files.includes(f);
const packageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : has('package-lock.json') ? 'npm' : null;
const buildTools = [
has('nx.json') && 'nx', has('turbo.json') && 'turbo', has('lerna.json') && 'lerna',
(has('MODULE.bazel') || has('WORKSPACE') || has('WORKSPACE.bazel')) && 'bazel',
(has('build.gradle') || has('build.gradle.kts') || has('settings.gradle') || has('settings.gradle.kts')) && 'gradle', has('pom.xml') && 'maven',
has('go.mod') && 'go', has('Cargo.toml') && 'cargo',
files.some((f) => /^lage\.config\.[cm]?js$/.test(f)) && 'lage', files.some((f) => /^\.moon\/workspace\.ya?ml$/.test(f)) && 'moon',
has('pants.toml') && 'pants', has('rush.json') && 'rush',
].filter(Boolean);
const ci = files.filter((f) => /^\.github\/workflows\/.+\.ya?ml$|^\.gitlab-ci\.yml$|^\.circleci\/config\.yml$|^Jenkinsfile$|^azure-pipelines\.yml$/.test(f));
const nodeVersion = has('.nvmrc') ? tryGit(repo, ['show', 'HEAD:.nvmrc']).trim() : null;
return { files: files.length, packages, languages, packageManager, buildTools, ci, nodeVersion };
}
function commits(repo, since, until, problems, label) {
const out = collect(repo, ['log', `--since=since`, `--until=until`, '--no-merges', '--format=%x1e%H%x1f%aI%x1f%an%x1f%ae%x1f%s%x1f%b%x1f', '--name-only'], problems, label);
const list = [];
for (const rec of out.split('\x1e')) {
if (!rec.trim()) continue;
const [sha, date, authorName, authorEmail, subject, body, rest = ''] = rec.split('\x1f');
list.push({ sha, date, authorName, authorEmail, subject, body: body.trim(), files: rest.split('\n').map((s) => s.trim()).filter(Boolean) });
}
return list;
}
// Parse package.json diffs (zero context) into per-commit dependency and version changes.
function manifestChanges(repo, since, until, problems, label) {
const out = collect(repo, ['log', `--since=since`, `--until=until`, '--no-merges', '--format=%x1e%H', '-p', '-U0', '--no-color', '--no-ext-diff', '--', ':(glob)**/package.json'], problems, label);
const bySha = new Map();
for (const rec of out.split('\x1e')) {
if (!rec.trim()) continue;
const lines = rec.split('\n');
const sha = lines[0].trim();
const files = new Map();
let file = null;
for (const line of lines.slice(1)) {
let m;
if ((m = line.match(/^\+\+\+ b\/(.+)$/))) { file = m[1]; continue; }
if ((m = line.match(/^--- a\/(.+)$/))) { file = m[1]; continue; }
if (line.startsWith('+++') || line.startsWith('---') || !file) continue;
if (!(m = line.match(/^([-+])\s*"([^"]+)"\s*:\s*"([^"]*)"/))) continue;
if (!files.has(file)) files.set(file, { removed: new Map(), added: new Map() });
files.get(file)[m[1] === '-' ? 'removed' : 'added'].set(m[2], m[3]);
}
bySha.set(sha, files);
}
return bySha;
}
function tags(repo, problems, label) {
return collect(repo, ['for-each-ref', 'refs/tags', '--format=%(refname:short)%09%(creatordate:iso-strict)'], problems, label)
.split('\n').filter(Boolean).map((l) => { const [name, date] = l.split('\t'); return { name, date }; });
}
// ---------- analysis ----------
export function analyze(config) {
const a = { ...DEFAULT_ASSUMPTIONS, ...config.assumptions };
const rates = { developerHourly: 100, ciPerMinute: 0.008, currency: 'USD', ...config.rates };
const now = config.now ?? new Date().toISOString();
const since = config.since ?? new Date(Date.parse(now) - 365 * DAY).toISOString().slice(0, 10);
const windowDays = Math.max(1, days(new Date(since).toISOString(), now));
const exclude = new Set(config.overrides?.excludeCommits ?? []);
const scopes = config.internalScopes ?? [];
const problems = [];
const repos = config.repos.map((r) => {
const p = typeof r === 'string' ? { path: r } : r;
const abs = path.resolve(config.baseDir ?? '.', p.path);
const name = p.name ?? path.basename(abs).replace(/\.git$/, '');
if (!tryGit(abs, ['rev-parse', '--git-dir'])) { problems.push(`name: not a git repository (abs)`); return null; }
if (tryGit(abs, ['rev-parse', '--is-shallow-repository']).trim() === 'true') problems.push(`name: shallow clone; history before the shallow boundary is missing`);
if (!tryGit(abs, ['rev-parse', '--verify', '--quiet', 'HEAD'])) { problems.push(`name: HEAD has no commits (abs)`); return null; }
// HEAD inventory is intentionally current state; history is bounded to [since, now].
const inv = inventory(abs);
const list = commits(abs, since, now, problems, name).filter((c) => !exclude.has(c.sha));
for (const c of list) c.repo = name;
return { name, path: abs, github: p.github ?? null, inv, commits: list, manifests: manifestChanges(abs, since, now, problems, name), tags: tags(abs, problems, name) };
}).filter(Boolean);
// Internal packages: published by an analysed repo, or matching a configured scope.
const producerOf = new Map();
for (const r of repos) for (const p of r.inv.packages) if (p.name) producerOf.set(p.name, r.name);
const isInternal = (name) => producerOf.has(name) || scopes.some((s) => name.startsWith(s));
// Releases of internal packages: version-field changes + tags.
const releases = new Map(); // pkg -> [{version:[..], date, repo, sha}]
const addRelease = (pkg, version, date, repo, sha) => {
const v = minVersion(version);
if (!v || !isInternal(pkg)) return;
if (!releases.has(pkg)) releases.set(pkg, []);
const list = releases.get(pkg);
const prev = list.find((x) => cmpVersion(x.version, v) === 0);
if (prev) { if (date < prev.date) Object.assign(prev, { date, sha, repo }); } else list.push({ version: v, date, repo, sha });
};
const commitBySha = new Map();
for (const r of repos) for (const c of r.commits) commitBySha.set(`r.name:c.sha`, c);
// Per-commit internal bumps.
const bumps = [];
const releaseCommits = [];
for (const r of repos) {
const fileToName = new Map(r.inv.packages.map((p) => [p.file, p.name]));
for (const [sha, files] of r.manifests) {
const c = commitBySha.get(`r.name:sha`);
if (!c) continue;
for (const [file, { removed, added }] of files) {
if (removed.has('version') && added.has('version')) {
let name = fileToName.get(file) ?? added.get('name');
if (!name) name = tryJson(tryGit(r.path, ['show', `sha:file`]))?.name;
if (name && isInternal(name)) {
addRelease(name, added.get('version'), c.date, r.name, sha);
releaseCommits.push({ repo: r.name, sha, date: c.date, pkg: name, version: added.get('version') });
}
}
for (const [dep, to] of added) {
// Skip self-references (a playground or docs package depending on its own repo's package).
if (dep === 'version' || dep === 'name' || !isInternal(dep) || !removed.has(dep) || producerOf.get(dep) === r.name) continue;
const from = removed.get(dep);
const vf = minVersion(from), vt = minVersion(to);
if (!vf || !vt || from === to) continue;
const direction = cmpVersion(vt, vf) > 0 ? 'up' : cmpVersion(vt, vf) < 0 ? 'down' : 'range';
if (direction === 'range') continue;
bumps.push({ repo: r.name, sha, date: c.date, file, pkg: dep, from, to, direction, bot: isBot(c), subject: c.subject });
}
}
}
for (const t of r.tags) {
const m = t.name.match(/^(?:(.+)@)?v?(\d+\.\d+\.\d+)$/);
if (!m) continue;
const publics = r.inv.packages.filter((p) => p.name && !p.private);
const pkg = m[1] ?? (publics.length === 1 ? publics[0].name : null);
if (pkg && t.date >= since && t.date <= now) addRelease(pkg, m[2], t.date, r.name, null);
}
}
// Collapse bumps: one per (repo, sha, pkg) — a commit touching several manifests counts once.
const bumpKey = new Map();
for (const b of bumps) { const k = `b.repo:b.sha:b.pkg`; if (!bumpKey.has(k)) bumpKey.set(k, b); }
const uniqueBumps = [...bumpKey.values()].sort((x, y) => x.date.localeCompare(y.date));
const bumpCommitKeys = new Set(uniqueBumps.map((b) => `b.repo:b.sha`));
const releaseDate = (pkg, v) => releases.get(pkg)?.find((x) => cmpVersion(x.version, v) === 0)?.date ?? null;
for (const b of uniqueBumps) {
const rd = b.direction === 'up' ? releaseDate(b.pkg, minVersion(b.to)) : null;
b.lagDays = rd && b.date >= rd ? round(days(rd, b.date)) : null;
}
// Consumers: which analysed repos depend (at HEAD) on which internal packages.
const consumers = [];
for (const r of repos) {
const seen = new Set();
for (const p of r.inv.packages) for (const [dep, range] of Object.entries(p.deps)) {
if (!isInternal(dep) || producerOf.get(dep) === r.name || seen.has(dep)) continue;
seen.add(dep);
consumers.push({ repo: r.name, pkg: dep, range, producer: producerOf.get(dep) ?? null, file: p.file });
}
}
const consumedPkgs = new Set(consumers.map((c) => c.pkg));
// Packages also consumed outside the analysed repos keep their releases in a monorepo, so those are not costed.
const isPublic = (pkg) => config.publicPackages === true || (Array.isArray(config.publicPackages) && config.publicPackages.includes(pkg));
const consumedReleases = releaseCommits.filter((x) => consumedPkgs.has(x.pkg) && !isPublic(x.pkg));
// Dedupe release commits per (repo, sha).
const relSeen = new Set();
const releaseEvents = consumedReleases.filter((x) => { const k = `x.repo:x.sha:x.pkg`; if (relSeen.has(k)) return false; relSeen.add(k); return true; });
// Drift at HEAD.
const latestVersion = (pkg) => {
const fromReleases = releases.get(pkg)?.map((x) => x.version) ?? [];
const head = repos.flatMap((r) => r.inv.packages).filter((p) => p.name === pkg).map((p) => minVersion(p.version)).filter(Boolean);
return [...fromReleases, ...head].sort(cmpVersion).at(-1) ?? null;
};
const drift = consumers.map((c) => {
const cur = minVersion(c.range), latest = latestVersion(c.pkg);
if (!cur || !latest || /^workspace:|^(file|link|portal):/.test(c.range)) return null;
return { ...c, current: vstr(cur), latest: vstr(latest), majorsBehind: latest[0] - cur[0], behind: cmpVersion(latest, cur) > 0 };
}).filter(Boolean);
const skew = [];
for (const pkg of consumedPkgs) {
const majors = new Map();
for (const d of drift.filter((x) => x.pkg === pkg)) {
const maj = d.current.split('.')[0];
if (!majors.has(maj)) majors.set(maj, []);
majors.get(maj).push(d.repo);
}
if (majors.size > 1) skew.push({ pkg, majors: Object.fromEntries(majors) });
}
// ---------- bugs and duplicated work ----------
const all = repos.flatMap((r) => r.commits).sort((x, y) => x.date.localeCompare(y.date));
const used = new Set();
const key = (c) => `c.repo:c.sha`;
const ev = (c) => ({ repo: c.repo, sha: c.sha.slice(0, 10), date: c.date.slice(0, 10), subject: c.subject });
const bugs = [];
// 1. dependency-regression (high): downgrade of an internal dependency, or revert of a bump commit.
for (const c of all) {
const downs = uniqueBumps.filter((b) => b.repo === c.repo && b.sha === c.sha && b.direction === 'down');
const rev = c.subject.match(/^Revert "(.+)"$/);
const revertsBump = rev && all.some((o) => o.repo === c.repo && o.subject === rev[1] && bumpCommitKeys.has(key(o)) && o.date <= c.date);
if (!downs.length && !revertsBump) continue;
used.add(key(c));
bugs.push({
category: 'dependency-regression', confidence: 'high', repos: [c.repo],
title: downs.length ? `c.repo rolled back downs.map((d) => `${d.pkg d.from → d.to`).join(', ')}` : `c.repo reverted an internal dependency bump`,
why: 'An internal release broke a consumer after it shipped. In a monorepo the producer change runs the consumer\'s tests before merge.',
commits: [ev(c)],
});
}
// 2. Groups: the same change in several repos (shared ticket, or near-identical subject).
const candidates = all.filter((c) => !used.has(key(c)) && !bumpCommitKeys.has(key(c)) && !RELEASE.test(c.subject));
const parent = new Map(candidates.map((c) => [key(c), key(c)]));
const find = (k) => { while (parent.get(k) !== k) { parent.set(k, parent.get(parent.get(k))); k = parent.get(k); } return k; };
const union = (x, y) => parent.set(find(x), find(y));
const linkedBy = new Map();
const byTicket = new Map();
for (const c of candidates) for (const t of ticketsOf(`c.subject\nc.body`)) {
if (!byTicket.has(t)) byTicket.set(t, []);
byTicket.get(t).push(c);
}
for (const [t, list] of byTicket) {
if (new Set(list.map((c) => c.repo)).size < 2) continue;
for (const c of list.slice(1)) union(key(c), key(list[0]));
for (const c of list) { linkedBy.set(key(c), 'ticket'); c.ticket ??= t; }
}
const norm = new Map(candidates.map((c) => [key(c), normalizeSubject(c.subject)]));
for (let i = 0; i < candidates.length; i++) {
const ci = candidates[i];
const ni = norm.get(key(ci));
if (GENERIC.has(ni)) continue;
for (let j = i + 1; j < candidates.length; j++) {
const cj = candidates[j];
if (days(ci.date, cj.date) > a.groupWindowDays) break;
if (cj.repo === ci.repo) continue;
if (similarity(ni, norm.get(key(cj))) >= a.similarity) {
union(key(ci), key(cj));
if (!linkedBy.has(key(ci))) linkedBy.set(key(ci), 'similar');
if (!linkedBy.has(key(cj))) linkedBy.set(key(cj), 'similar');
}
}
}
const groupsMap = new Map();
for (const c of candidates) {
if (!linkedBy.has(key(c))) continue;
const root = find(key(c));
if (!groupsMap.has(root)) groupsMap.set(root, []);
groupsMap.get(root).push(c);
}
const coordinated = [], duplicatedTooling = [];
for (const list of groupsMap.values()) {
const groupRepos = [...new Set(list.map((c) => c.repo))];
if (groupRepos.length < 2) continue;
// Groups spanning more than the window are usually unrelated commits sharing a long-lived ticket.
if (days(list[0].date, list.at(-1).date) > a.groupWindowDays * 2) continue;
for (const c of list) used.add(key(c));
const via = list.some((c) => linkedBy.get(key(c)) === 'ticket') ? 'ticket' : 'similar';
const ticket = list.find((c) => c.ticket)?.ticket ?? null;
const commitsEv = list.map(ev);
// A group is a bug only when fix commits land in at least two repos; one fix plus related work is coordination.
const fixes = list.filter((c) => isFixSubject(c.subject));
const isFix = new Set(fixes.map((c) => c.repo)).size >= 2;
const configOnly = list.every((c) => (c.files.length && c.files.every((f) => CONFIG_FILE.test(f))) || DEPS_CHORE.test(c.subject));
const title = ticket && !list[0].subject.includes(ticket) ? `ticket: list[0].subject` : list[0].subject;
if (isFix) {
const first = normalizeSubject(fixes[0].subject);
const similarRepos = new Set(fixes.filter((c) => similarity(normalizeSubject(c.subject), first) >= a.similarity).map((c) => c.repo));
const dup = similarRepos.size >= 2;
bugs.push(dup
? { category: 'duplicated-fix', confidence: 'medium', repos: groupRepos, title, why: `The same fix was applied in groupRepos.length repos: duplicated code, or a shared contract that has to be fixed everywhere.`, commits: commitsEv, copies: groupRepos.length }
: { category: 'cross-repo-fix', confidence: 'medium', repos: groupRepos, title, why: `One bug needed coordinated fixes in groupRepos.length repos (linked by ticket ?? 'subject'); the contract between them lives in no single repo.`, commits: commitsEv });
} else if (configOnly) {
duplicatedTooling.push({ repos: groupRepos, title, commits: commitsEv, copies: groupRepos.length, bot: list.every(isBot) });
} else {
coordinated.push({ repos: groupRepos, title, via, ticket, commits: commitsEv });
}
}
// 3. Single-commit fixes linked to an internal bump.
for (const c of all) {
if (used.has(key(c)) || !isFixSubject(c.subject) && !(FIX_WORD.test(c.body) && !DEPS_CHORE.test(c.subject))) continue;
const ownUps = uniqueBumps.filter((b) => b.repo === c.repo && b.sha === c.sha && b.direction === 'up');
if (ownUps.length) {
used.add(key(c));
bugs.push({
category: 'fix-propagation', confidence: 'medium', repos: [c.repo, ...new Set(ownUps.map((b) => producerOf.get(b.pkg)).filter(Boolean))],
title: `c.subject`, why: `The fix reached c.repo only after a release of ownUps.map((b) => b.pkg).join(', ') and a version bump.`,
commits: [ev(c)],
});
continue;
}
if (bumpCommitKeys.has(key(c))) continue;
const prior = uniqueBumps.filter((b) => b.repo === c.repo && b.direction === 'up' && b.date <= c.date && days(b.date, c.date) <= a.bumpFixWindowDays);
if (!prior.length) continue;
const text = `c.subject\nc.body`.toLowerCase();
const mentions = prior.find((b) => text.includes(b.pkg.toLowerCase()) || (b.pkg.split('/').pop().length >= 4 && new RegExp(`\\bb.pkg.split('/').pop().replace(/[.*+?^${()|[\]\\]/g, '\\$&')}\\b`, 'i').test(text)));
const lastMajor = prior.findLast((b) => minVersion(b.to)[0] > minVersion(b.from)[0]);
const confidence = mentions || COMPAT.test(text) ? 'medium' : lastMajor && days(lastMajor.date, c.date) <= 2 ? 'low' : null;
if (!confidence) continue;
used.add(key(c));
const b = mentions ?? (confidence === 'low' ? lastMajor : prior.at(-1));
bugs.push({
category: 'post-bump-fix', confidence, repos: [c.repo, producerOf.get(b.pkg)].filter(Boolean),
title: c.subject, why: `Fix landed round(days(b.date, c.date)) days after c.repo bumped b.pkg b.from → b.toCOMPAT.test(text) ? ' and describes a compatibility break' : ''.`,
commits: [{ ...ev(commitBySha.get(`b.repo:b.sha`)), evidenceOnly: true }, ev(c)],
});
}
// ---------- cost model ----------
const perRepoCi = {};
for (const r of repos) {
const ci = config.ci?.[r.name];
const landed = r.commits.length || 1;
perRepoCi[r.name] = ci && Number.isFinite(ci.totalMinutes) && ci.totalMinutes >= 0
? { minutesPerCommit: ci.totalMinutes / Math.max(ci.commits ?? landed, 1), source: 'measured', runs: ci.runs ?? null, totalMinutes: ci.totalMinutes }
: { minutesPerCommit: a.ciMinutesPerCommit, source: 'assumed' };
}
const ciMin = (repo, n = 1) => n * (perRepoCi[repo]?.minutesPerCommit ?? a.ciMinutesPerCommit);
const conf = { low: ['high'], expected: ['high', 'medium'], high: ['high', 'medium', 'low'] };
// scope: null = every analysed repo (the tax); a Set = only repos that would move (what a migration recovers).
const inScope = (scope, repo) => !scope || scope.has(repo);
const scopeGroup = (scope, g) => {
const commits = g.commits.filter((c) => inScope(scope, c.repo));
const repos = [...new Set(commits.map((c) => c.repo))];
return repos.length >= 2 ? { ...g, commits, repos, copies: repos.length } : null;
};
const lines = (scenario, scope = null) => {
const out = [];
const coordinatedS = coordinated.map((g) => scopeGroup(scope, g)).filter(Boolean);
const toolingS = duplicatedTooling.map((g) => scopeGroup(scope, g)).filter(Boolean);
// A bump that is itself counted as a fix-propagation bug is costed once, as the bug.
const ownBug = new Set(bugs.filter((b) => b.category === 'fix-propagation').flatMap((b) => b.commits.map((c) => `c.repo:c.sha`)));
const costedBumps = uniqueBumps.filter((b) => b.direction === 'up' && !ownBug.has(`b.repo:b.sha.slice(0, 10)`)
&& inScope(scope, b.repo) && (!scope || scope.has(producerOf.get(b.pkg))));
const humanBumps = costedBumps.filter((b) => !b.bot);
const botBumps = costedBumps.filter((b) => b.bot);
const bumpCommitSet = (list) => [...new Set(list.map((b) => `b.repo:b.sha`))].map((k) => k.split(':')[0]);
out.push({ key: 'bumps', label: 'Internal dependency bumps', count: humanBumps.length + botBumps.length,
hours: humanBumps.length * a.bumpHumanHours + botBumps.length * a.bumpBotHours,
ciMinutes: bumpCommitSet(costedBumps).reduce((s, repo) => s + ciMin(repo), 0) });
const rel = releaseEvents.filter((x) => inScope(scope, x.repo));
// One CI run per release commit, even when it versions several packages.
const relCommits = [...new Map(rel.map((x) => [`x.repo:x.sha`, x.repo])).values()];
out.push({ key: 'releases', label: 'Internal releases consumed by sibling repos', count: rel.length,
hours: rel.length * a.releaseHours, ciMinutes: relCommits.reduce((s, repo) => s + ciMin(repo), 0) });
out.push({ key: 'coordination', label: 'Changes coordinated across repos', count: coordinatedS.length,
hours: coordinatedS.reduce((s, g) => s + (g.repos.length - 1) * a.coordinationHoursPerExtraRepo, 0),
ciMinutes: coordinatedS.reduce((s, g) => s + g.commits.filter((c) => c.repo !== g.commits[0].repo).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
out.push({ key: 'duplicatedTooling', label: 'Same tooling/dependency maintenance repeated per repo', count: toolingS.length,
hours: toolingS.reduce((s, g) => s + (g.copies - 1) * (g.bot ? a.bumpBotHours : a.duplicateChangeHoursPerCopy), 0),
ciMinutes: toolingS.reduce((s, g) => s + g.commits.filter((c) => c.repo !== g.commits[0].repo).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
for (const cat of ['dependency-regression', 'post-bump-fix', 'fix-propagation', 'duplicated-fix', 'cross-repo-fix']) {
const list = bugs.filter((b) => b.category === cat && conf[scenario].includes(b.confidence) && (!scope || b.repos.every((x) => scope.has(x))));
out.push({ key: cat, label: `Bugs: cat`, count: list.length,
hours: list.reduce((s, b) => s + a.bugHours + (b.copies ? (b.copies - 1) * a.duplicateChangeHoursPerCopy : 0), 0),
ciMinutes: list.reduce((s, b) => s + b.commits.filter((c) => !c.evidenceOnly).reduce((t, c) => t + ciMin(c.repo), 0), 0) });
}
const yearly = 365 / windowDays;
for (const l of out) {
l.cost = l.hours * rates.developerHourly + l.ciMinutes * rates.ciPerMinute;
l.savingsShare = SAVINGS[l.key];
l.annualCost = l.cost * yearly;
l.annualSavings = l.annualCost * l.savingsShare;
}
const sum = (f) => out.reduce((s, l) => s + l[f], 0);
return {
lines: out.map((l) => ({ ...l, hours: round(l.hours), ciMinutes: Math.round(l.ciMinutes), cost: Math.round(l.cost), annualCost: Math.round(l.annualCost), annualSavings: Math.round(l.annualSavings) })),
totals: { hours: round(sum('hours')), ciMinutes: Math.round(sum('ciMinutes')), cost: Math.round(sum('cost')), annualCost: Math.round(sum('annualCost')), annualSavings: Math.round(sum('annualSavings')),
devCost: Math.round(sum('hours') * rates.developerHourly), ciCost: Math.round(sum('ciMinutes') * rates.ciPerMinute) },
};
};
// ---------- migration facts ----------
const edges = new Map();
const edge = (x, y) => { const k = [x, y].sort().join(' ↔ '); if (!edges.has(k)) edges.set(k, { repos: [x, y].sort(), dependencies: 0, bumps: 0, sharedChanges: 0, sharedTooling: 0, bugs: 0 }); return edges.get(k); };
for (const c of consumers) if (c.producer) edge(c.repo, c.producer).dependencies++;
for (const b of uniqueBumps) { const p = producerOf.get(b.pkg); if (p && p !== b.repo) edge(b.repo, p).bumps++; }
const pairs = (rs) => rs.flatMap((x, i) => rs.slice(i + 1).map((y) => [x, y]));
for (const g of coordinated) for (const [x, y] of pairs(g.repos)) edge(x, y).sharedChanges++;
// Repeated tooling is a cost, but every repo has tooling: it is shown, not used for coupling.
for (const g of duplicatedTooling) for (const [x, y] of pairs(g.repos)) edge(x, y).sharedTooling++;
for (const b of bugs) for (const [x, y] of pairs([...new Set(b.repos)])) edge(x, y).bugs++;
const edgeList = [...edges.values()].filter((e) => e.dependencies + e.bumps + e.sharedChanges + e.bugs > 0).map((e) => ({ ...e, weight: e.dependencies * 2 + e.bumps + e.sharedChanges + e.bugs * 3 })).sort((x, y) => y.weight - x.weight);
// Clusters: tooling-only links do not justify a migration on their own.
const cp = new Map(repos.map((r) => [r.name, r.name]));
const cf = (k) => { while (cp.get(k) !== k) k = cp.get(k); return k; };
for (const e of edgeList) if (e.dependencies || e.bumps || e.bugs || e.sharedChanges >= 2) cp.set(cf(e.repos[0]), cf(e.repos[1]));
const clusterMap = new Map();
for (const r of repos) { const k = cf(r.name); if (!clusterMap.has(k)) clusterMap.set(k, []); clusterMap.get(k).push(r.name); }
const clusters = [...clusterMap.values()].map((members) => ({
repos: members.sort(), weight: edgeList.filter((e) => members.includes(e.repos[0]) && members.includes(e.repos[1])).reduce((s, e) => s + e.weight, 0),
})).sort((x, y) => y.weight - x.weight || y.repos.length - x.repos.length);
const isolated = clusters.filter((c) => c.repos.length === 1).map((c) => c.repos[0]);
const migrateRepos = repos.filter((r) => !isolated.includes(r.name) || repos.length === 1);
const migrateSet = new Set(migrateRepos.map((r) => r.name));
// Cost covers every analysed repo; savings and payback only the repos that would move.
const scenarios = {};
for (const k of ['low', 'expected', 'high']) {
const full = lines(k), scoped = lines(k, migrateSet);
full.lines.forEach((l, i) => { l.annualSavings = scoped.lines[i].annualSavings; });
full.totals.annualSavings = scoped.totals.annualSavings;
scenarios[k] = full;
}
// External dependency conflicts (different majors across the repos that would move) — alignment before one lockfile.
const ext = new Map();
for (const r of migrateRepos) for (const p of r.inv.packages) for (const [dep, range] of Object.entries(p.deps)) {
if (isInternal(dep)) continue;
const v = minVersion(range);
if (!v) continue;
if (!ext.has(dep)) ext.set(dep, new Map());
const m = ext.get(dep);
if (!m.has(v[0])) m.set(v[0], new Set());
m.get(v[0]).add(r.name);
}
const conflicts = [...ext].filter(([, m]) => m.size > 1)
.map(([dep, m]) => ({ dep, majors: Object.fromEntries([...m].map(([k, s]) => [k, [...s].sort()])), repos: new Set([...m.values()].flatMap((s) => [...s])).size }))
.sort((x, y) => y.repos - x.repos || x.dep.localeCompare(y.dep));
const langs = {};
for (const r of repos) for (const [l, n] of Object.entries(r.inv.languages)) langs[l] = (langs[l] ?? 0) + n;
const langNames = Object.keys(langs).sort((x, y) => langs[y] - langs[x]);
const tools = new Set(repos.flatMap((r) => r.inv.buildTools));
const recommendedTool = langNames.length === 0 ? 'unknown'
: langNames.every((l) => l === 'js/ts') ? (tools.has('nx') ? 'Nx (already used) on pnpm workspaces' : tools.has('turbo') ? 'Turborepo (already used) on pnpm workspaces' : 'pnpm workspaces + Nx or Turborepo')
: langNames.every((l) => l === 'jvm') ? 'Gradle composite build, or Bazel for very large graphs'
: tools.has('bazel') ? 'Bazel (already used)' : 'Nx (polyglot plugins) or Bazel';
const options = toolOptions(langNames, tools);
const reasons = whyMigrate({
bumps: uniqueBumps.length, releases: releaseEvents.length, coordinated: coordinated.length, repeatedTooling: duplicatedTooling.length,
skew: skew.length, duplicatedFixes: bugs.filter((b) => b.category === 'duplicated-fix').length,
crossRepoFixes: bugs.filter((b) => b.category === 'cross-repo-fix').length,
});
const migrationDays = migrateRepos.length * a.migrationDaysPerRepo + conflicts.length * a.migrationDaysPerConflict;
const migrationCost = Math.round(migrationDays * 8 * rates.developerHourly);
const payback = (s) => {
const monthly = s.totals.annualSavings / 12 - a.monorepoToolingMonthly;
return monthly > 0 ? round(migrationCost / monthly) : null;
};
return {
version: 1,
generatedAt: now,
window: { since, until: now.slice(0, 10), days: Math.round(windowDays) },
rates, assumptions: a, problems, publicPackages: config.publicPackages ?? [],
repos: repos.map((r) => ({
name: r.name, github: r.github, commits: r.commits.length,
packages: r.inv.packages.filter((p) => p.name).map((p) => ({ name: p.name, version: p.version, private: p.private })),
languages: r.inv.languages, packageManager: r.inv.packageManager, buildTools: r.inv.buildTools, ciFiles: r.inv.ci, nodeVersion: r.inv.nodeVersion, ci: perRepoCi[r.name],
})),
internal: {
packages: [...producerOf].filter(([n]) => consumedPkgs.has(n)).map(([pkg, repo]) => ({ pkg, repo, consumers: consumers.filter((c) => c.pkg === pkg).map((c) => c.repo) })),
bumps: uniqueBumps.map(({ subject, ...b }) => ({ ...b, sha: b.sha.slice(0, 10), date: b.date.slice(0, 10) })),
releases: releaseEvents.map((x) => ({ ...x, sha: x.sha.slice(0, 10), date: x.date.slice(0, 10) })),
medianBumpLagDays: median(uniqueBumps.map((b) => b.lagDays).filter((x) => x !== null)),
drift: drift.filter((d) => d.behind), skew,
},
bugs: bugs.map((b, i) => ({ id: `Bi + 1`, ...b })),
coordinated, duplicatedTooling,
cost: scenarios,
migration: {
recommendedTool, languages: langs,
toolOptions: options, whyMigrate: reasons,
toolSource: { urls: MONOREPO_TOOLS.source.urls, retrieved: MONOREPO_TOOLS.source.retrieved, publisher: MONOREPO_TOOLS.source.publisher, legend: MONOREPO_TOOLS.source.legend, independent: MONOREPO_TOOLS.independent },
clusters, isolated, coupling: edgeList.filter((e) => e.weight > 0), externalConflicts: conflicts,
oneTime: { days: round(migrationDays), cost: migrationCost, repos: migrateRepos.map((r) => r.name) },
paybackMonths: { low: payback(scenarios.low), expected: payback(scenarios.expected), high: payback(scenarios.high) },
},
};
}
export function toolOptionsMarkdown(m) {
const src = m.toolSource;
const cats = m.toolOptions[0].categories.map((c) => c.category);
const out = ['### Tool options', '',
`Every tool compared on [monorepo.tools/compare](src.urls[1]) (snapshot src.retrieved). The rating and every column up to "src.legend.none" come from monorepo.tools, which is published by Nx; the last column is from independent sources and is not scored.`, '',
`| Tool | monorepo.tools rating /10 | cats.join(' | ') | src.legend.implement | src.legend.community | src.legend.none | Fit | Already used | Independent signals (not scored) |`,
`|---|---:|').join('|')|---:|---:|---:|---|---|---|`];
for (const t of m.toolOptions) {
out.push(`| [t.name](t.repo) | t.rating.toFixed(1) | t.categories.map((c) => `${c.native/c.total`).join(' | ')} | t.counts.implement | t.counts.community | t.counts.none | `no: ${t.fitReason`} | '—' | independentSignals(t.independent) ?? '—' |`);
}
out.push('', '**Sources**', '');
for (const x of toolSources(src, m.toolOptions[0].total)) out.push(`- [x.name](x.url) (x.publisher, retrieved x.retrieved; **x.role**). x.metric. Covers: x.covers.`);
return out;
}
function median(xs) {
if (!xs.length) return null;
const s = [...xs].sort((x, y) => x - y);
const m = Math.floor(s.length / 2);
return round(s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2);
}
// ---------- rendering ----------
export function renderMarkdown(r) {
const cur = r.rates.currency === 'USD' ? '$' : `r.rates.currency `;
const money = (n) => `curMath.round(n).toLocaleString('en-US')`;
const e = r.cost.expected;
const md = [];
md.push('# Polyrepo Tax Report', '');
md.push(`**Repos:** r.repos.length · **Window:** r.window.since → r.window.until (r.window.days days) · **Rates:** money(r.rates.developerHourly)/dev-hour, curr.rates.ciPerMinute/CI-minute`, '');
md.push(`**Polyrepo tax in this window (expected):** money(e.totals.cost) — e.totals.hours developer hours (money(e.totals.devCost)) + e.totals.ciMinutes.toLocaleString('en-US') CI minutes (money(e.totals.ciCost))`, '');
md.push(`**Annualized:** money(r.cost.low.totals.annualCost) – money(r.cost.high.totals.annualCost) (expected money(e.totals.annualCost)); a monorepo would recover about money(e.totals.annualSavings)/year.`, '');
const pb = r.migration.paybackMonths;
md.push(`**Migration:** ~r.migration.oneTime.days dev-days (money(r.migration.oneTime.cost)) for r.migration.oneTime.repos.length repos → payback `~${pb.expected months`} (range pb.high ?? '—'–pb.low ?? 'never').`, '');
const bugCount = (s) => r.bugs.filter((b) => s.includes(b.confidence)).length;
md.push(`**Polyrepo-attributable bugs:** bugCount(['high']) high-confidence · bugCount(['medium']) medium · bugCount(['low']) low`, '');
if (r.problems.length) md.push('> **Data problems:** ' + r.problems.join('; '), '');
md.push('These are estimates from git history, not invoices. Every count links to commits below; every rate and assumption is listed at the end and can be overridden.', '');
md.push('## Where the time goes (expected scenario)', '');
md.push('| Cost driver | Events | Dev hours | CI minutes | Cost (window) | Annualized | Monorepo removes |', '|---|---:|---:|---:|---:|---:|---:|');
for (const l of e.lines) md.push(`| l.label | l.count | l.hours | l.ciMinutes.toLocaleString('en-US') | money(l.cost) | money(l.annualCost) | Math.round(l.savingsShare * 100)% |`);
md.push(`| **Total** | | **e.totals.hours** | **e.totals.ciMinutes.toLocaleString('en-US')** | **money(e.totals.cost)** | **money(e.totals.annualCost)** | **money(e.totals.annualSavings)/yr** |`, '');
md.push('| Scenario | Counts | Window cost | Annualized | Annual savings | Payback |', '|---|---|---:|---:|---:|---:|');
for (const [k, label] of [['low', 'high-confidence bugs only'], ['expected', 'high + medium'], ['high', 'high + medium + low']]) {
const s = r.cost[k];
md.push(`| k | label | money(s.totals.cost) | money(s.totals.annualCost) | money(s.totals.annualSavings) | `${pb[k] mo`} |`);
}
md.push('');
md.push('## Bugs attributable to repo boundaries', '');
if (!r.bugs.length) md.push('None found in this window.', '');
for (const conf of ['high', 'medium', 'low']) {
const list = r.bugs.filter((b) => b.confidence === conf);
if (!list.length) continue;
md.push(`### conf[0].toUpperCase()conf.slice(1) confidence (list.length)`, '');
for (const b of list) {
md.push(`- **b.id · \`b.category\`** — b.title _([...new Set(b.repos)].join(', '))_`);
md.push(` - b.why`);
for (const c of b.commits) md.push(` - \`c.repo@c.sha\` c.date — c.subject`);
}
md.push('');
}
md.push('## Internal dependency churn', '');
const ib = r.internal;
const ups = ib.bumps.filter((b) => b.direction === 'up');
md.push(`- **ups.length** internal bump commits (ups.filter((b) => b.bot).length by bots, ups.filter((b) => !b.bot).length by people); **ib.bumps.filter((b) => b.direction === 'down').length** downgrade(s).`);
md.push(`- **ib.releases.length** internal releases existed to move code between repos''.`);
md.push(`- Median lag from release to consumer bump: **ib.medianBumpLagDays ?? 'n/a'** days.`);
if (ib.drift.length) md.push(`- **ib.drift.length** consumer(s) behind the latest internal version today; ib.drift.filter((d) => d.majorsBehind > 0).length at least a major version behind.`);
md.push('');
if (ib.packages.length) {
md.push('| Internal package | Producer | Consumers | Bumps | Releases |', '|---|---|---|---:|---:|');
for (const p of ib.packages) md.push(`| \`p.pkg\` | p.repo | p.consumers.join(', ') | ups.filter((b) => b.pkg === p.pkg).length | ib.releases.filter((x) => x.pkg === p.pkg).length |`);
md.push('');
}
if (ib.skew.length) {
md.push('**Version skew today** (the same internal package at different majors):', '');
for (const s of ib.skew) md.push(`- \`s.pkg\`: Object.entries(s.majors).map(([m, rs]) => `v${m in rs.join(', ')`).join(' · ')}`);
md.push('');
}
if (r.coordinated.length || r.duplicatedTooling.length) {
md.push('## Duplicated and coordinated work', '');
for (const g of r.coordinated.slice(0, 15)) md.push(`- **Coordinated change** (g.repos.join(', ')): g.title — g.commits.map((c) => `\`${c.repo@c.sha\``).join(', ')}`);
for (const g of r.duplicatedTooling.slice(0, 15)) md.push(`- **Repeated maintenance** ×g.copies'': g.title — g.commits.map((c) => `\`${c.repo@c.sha\``).join(', ')}`);
const more = Math.max(0, r.coordinated.length - 15) + Math.max(0, r.duplicatedTooling.length - 15);
if (more) md.push(`- …and more more in the JSON report.`);
md.push('');
}
const m = r.migration;
md.push('## Migration plan inputs', '');
md.push(`**Recommended tooling:** m.recommendedTool (languages by file count: Object.entries(m.languages).map(([l, n]) => `${l n`).join(', ') || 'none detected'})`, '');
if (m.whyMigrate?.length) {
md.push('### Why migrate', '', 'The polyrepo costs [monorepo.tools](https://monorepo.tools/) lists, shown only where this report measured them:', '');
for (const w of m.whyMigrate) md.push(`- **w.polyrepo** → w.monorepo. Measured: w.evidence.join(', ').`);
md.push('');
}
if (m.toolOptions?.length) md.push(...toolOptionsMarkdown(m), '');
md.push('**Clusters** (repos that change together; migrate the heaviest first):', '');
m.clusters.filter((c) => c.repos.length > 1).forEach((c, i) => md.push(`i + 1. c.repos.join(', ') — coupling weight c.weight`));
if (m.isolated.length) md.push('', `**No measured coupling — keep separate unless there is another reason:** m.isolated.join(', ')`);
md.push('');
if (m.coupling.length) {
md.push('| Repo pair | Internal deps | Bumps | Coordinated changes | Bugs | Weight | Repeated tooling (not weighted) |', '|---|---:|---:|---:|---:|---:|---:|');
for (const c of m.coupling.slice(0, 20)) md.push(`| c.repos.join(' ↔ ') | c.dependencies | c.bumps | c.sharedChanges | c.bugs | c.weight | c.sharedTooling |`);
md.push('');
}
if (m.externalConflicts.length) {
md.push(`**External dependencies to align before sharing one lockfile** (m.externalConflicts.length):`, '');
for (const c of m.externalConflicts.slice(0, 15)) md.push(`- \`c.dep\`: Object.entries(c.majors).map(([v, rs]) => `v${v (rs.join(', '))`).join(' · ')}`);
if (m.externalConflicts.length > 15) md.push(`- …and m.externalConflicts.length - 15 more in the JSON report.`);
md.push('');
}
md.push('## Assumptions', '');
md.push('| Assumption | Value |', '|---|---|');
for (const [k, v] of Object.entries(r.assumptions)) md.push(`| \`k\` | v |`);
md.push(`| \`developerHourly\` | money(r.rates.developerHourly) |`, `| \`ciPerMinute\` | curr.rates.ciPerMinute |`, '');
md.push('| Repo | Commits | CI minutes/commit | CI source |', '|---|---:|---:|---|');
for (const repo of r.repos) md.push(`| repo.name | repo.commits | round(repo.ci.minutesPerCommit) | repo.ci.source |`);
md.push('');
return md.join('\n');
}
// ---------- CLI ----------
function parseArgs(argv) {
const opts = { repos: [], internalScopes: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
const next = () => argv[++i];
if (a === '--config') opts.config = next();
else if (a === '--out') opts.out = next();
else if (a === '--since') opts.since = next();
else if (a === '--scope') opts.internalScopes.push(next());
else if (a === '--rate') opts.rate = Number(next());
else if (a === '--ci-rate') opts.ciRate = Number(next());
else if (a === '--ci') opts.ci = next();
else if (a === '--overrides') opts.overrides = next();
else if (a === '--now') opts.now = next();
else if (a === '--public') (opts.publicPackages ??= []).push(next());
else if (a.startsWith('--')) throw new Error(`unknown option a`);
else opts.repos.push(a);
}
return opts;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
const opts = parseArgs(process.argv.slice(2));
let config = { repos: [], internalScopes: [] };
if (opts.config) {
config = JSON.parse(fs.readFileSync(opts.config, 'utf8'));
config.baseDir = path.dirname(path.resolve(opts.config));
}
if (opts.repos.length) config.repos = [...(config.repos ?? []), ...opts.repos];
if (opts.internalScopes.length) config.internalScopes = [...(config.internalScopes ?? []), ...opts.internalScopes];
if (opts.since) config.since = opts.since;
if (opts.now) config.now = opts.now;
if (opts.publicPackages) config.publicPackages = opts.publicPackages.includes('*') ? true : [...(Array.isArray(config.publicPackages) ? config.publicPackages : []), ...opts.publicPackages];
config.rates = { ...config.rates };
if (opts.rate) config.rates.developerHourly = opts.rate;
if (opts.ciRate) config.rates.ciPerMinute = opts.ciRate;
const ciPath = opts.ci ?? (typeof config.ci === 'string' ? path.resolve(config.baseDir ?? '.', config.ci) : null);
if (ciPath) config.ci = JSON.parse(fs.readFileSync(ciPath, 'utf8'));
const ovPath = opts.overrides ?? (typeof config.overrides === 'string' ? path.resolve(config.baseDir ?? '.', config.overrides) : null);
if (ovPath) config.overrides = JSON.parse(fs.readFileSync(ovPath, 'utf8'));
if (!config.repos?.length) throw new Error('no repositories given (pass paths or --config)');
const report = analyze(config);
const out = path.resolve(opts.out ?? path.join(os.tmpdir(), 'polyrepo-tax-reports'));
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.json'), JSON.stringify(report, null, 2));
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.md'), renderMarkdown(report));
fs.writeFileSync(path.join(out, 'polyrepo-tax-report.html'), renderHtml(report));
const e = report.cost.expected.totals;
console.log(`wrote path.join(out, 'polyrepo-tax-report').{md,json,html}`);
console.log(`expected: e.hours dev hours + e.ciMinutes CI minutes = report.rates.currency e.cost in report.window.days days; report.bugs.length candidate bugs`);
for (const p of report.problems) console.error(`WARN: p`);
} catch (err) {
console.error(`polyrepo-tax: err.message`);
process.exit(2);
}
}
FILE:scripts/fetch-ci.mjs
#!/usr/bin/env node
// Collects GitHub Actions minutes per repository for polyrepo-tax. Read-only: only `gh api` GET requests.
// Usage: node fetch-ci.mjs --config polyrepo-tax.config.json [--since 2025-11-25] [--sample 30] [--out ci.json]
// node fetch-ci.mjs --repo name=owner/repo [--repo ...] --since 2025-11-25 --out ci.json
// Total = wall-clock minutes of every completed run in the window. Runs fan out into parallel jobs that are
// billed separately, so job minutes are sampled for up to --sample runs per repo and the total is scaled
// by the sampled job/wall ratio.
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const gh = (args) => execFileSync('gh', ['api', '-X', 'GET', ...args], { encoding: 'utf8', maxBuffer: 1 << 30, stdio: ['ignore', 'pipe', 'pipe'] });
const minutes = (a, b) => Math.max(0, (Date.parse(b) - Date.parse(a)) / 60000);
const LIMIT = 1000;
const DAY = 86_400_000;
const isoDay = (d) => d.toISOString().slice(0, 10);
// The runs API returns at most 1000 results per filtered query, so start with one month at a time.
export function monthRanges(since, until) {
const out = [];
let start = new Date(`sinceT00:00:00Z`);
const end = new Date(`untilT00:00:00Z`);
while (start < end) {
const next = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1));
const stop = next < end ? next : end;
out.push(`start.toISOString().slice(0, 10)..new Date(stop - 86_400_000).toISOString().slice(0, 10)`);
start = stop;
}
return out;
}
// Splits a range (YYYY-MM-DD..YYYY-MM-DD, inclusive) until each piece is under the API's result cap.
// Throws when a single day still reaches the cap, so a partial total is never reported as measured.
export function completeRanges(range, count) {
const total = count(range);
if (total < LIMIT) return total ? [range] : [];
const [from, to] = range.split('..').map((d) => new Date(`dT00:00:00Z`));
const spanDays = Math.round((to - from) / DAY);
if (spanDays < 1) throw new Error(`more than LIMIT - 1 runs on isoDay(from); cannot list them completely`);
const mid = new Date(from.getTime() + Math.floor(spanDays / 2) * DAY);
return [...completeRanges(`isoDay(from)..isoDay(mid)`, count), ...completeRanges(`isoDay(new Date(mid.getTime() + DAY))..isoDay(to)`, count)];
}
export function fetchRepo(slug, since, until, sample, api = gh) {
const runs = [];
const base = [`repos/slug/actions/runs`, '-f', 'status=completed'];
const count = (range) => Number(api([...base, '-f', `created=range`, '-f', 'per_page=1', '--jq', '.total_count']).trim());
for (const range of monthRanges(since, until).flatMap((r) => completeRanges(r, count))) {
const out = api([...base, '-f', `created=range`, '-f', 'per_page=100', '--paginate',
'--jq', '.workflow_runs[] | [.id, .run_started_at, .updated_at, .event, .name] | @tsv']);
for (const line of out.split('\n').filter(Boolean)) {
const [id, started, updated, event, name] = line.split('\t');
runs.push({ id, wall: minutes(started, updated), event, name });
}
}
const wall = runs.reduce((s, r) => s + r.wall, 0);
let ratio = 1, sampled = 0;
if (sample > 0 && runs.length) {
const step = Math.max(1, Math.floor(runs.length / sample));
let w = 0, j = 0;
for (let i = 0; i < runs.length && sampled < sample; i += step) {
try {
const jobs = api([`repos/slug/actions/runs/runs[i].id/jobs`, '-f', 'per_page=100', '--paginate', '--jq', '.jobs[] | [.started_at, .completed_at] | @tsv']);
const jm = jobs.split('\n').filter(Boolean).reduce((s, l) => { const [a, b] = l.split('\t'); return b && b !== 'null' ? s + Math.max(1, Math.ceil(minutes(a, b))) : s; }, 0);
if (runs[i].wall > 0) { w += runs[i].wall; j += jm; sampled++; }
} catch { /* skip runs whose jobs were deleted */ }
}
// Keep the measured ratio either way: below 1 when queue time inflates wall clock, above 1 for parallel jobs.
if (w > 0) ratio = j / w;
}
const byWorkflow = {};
for (const r of runs) byWorkflow[r.name] = Math.round((byWorkflow[r.name] ?? 0) + r.wall * ratio);
return { runs: runs.length, wallMinutes: Math.round(wall), jobWallRatio: Math.round(ratio * 100) / 100, sampledRuns: sampled, totalMinutes: Math.round(wall * ratio), byWorkflow, since, until };
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const argv = process.argv.slice(2);
const opt = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
const repos = [];
const config = opt('--config') ? JSON.parse(fs.readFileSync(opt('--config'), 'utf8')) : {};
for (const r of config.repos ?? []) {
if (typeof r === 'object' && r.github) repos.push({ name: r.name ?? path.basename(r.path).replace(/\.git$/, ''), slug: r.github });
}
argv.forEach((a, i) => { if (a === '--repo') { const [name, slug] = argv[i + 1].split('='); repos.push({ name, slug: slug ?? name }); } });
const until = opt('--until') ?? new Date().toISOString().slice(0, 10);
const since = opt('--since') ?? config.since ?? new Date(Date.now() - 365 * 86_400_000).toISOString().slice(0, 10);
const sample = Number(opt('--sample') ?? 30);
if (!repos.length) { console.error('fetch-ci: no repos with a "github" slug (use --config or --repo name=owner/repo)'); process.exit(2); }
const result = {};
for (const r of repos) {
try {
result[r.name] = fetchRepo(r.slug, since, until, sample);
console.error(`r.name: result[r.name].runs runs, result[r.name].totalMinutes minutes (job/wall ×result[r.name].jobWallRatio)`);
} catch (err) {
console.error(`WARN r.name: String(err.stderr || err.message).trim().split('\n')[0] — CI cost for this repo will be assumed`);
}
}
const out = opt('--out') ?? 'ci.json';
fs.writeFileSync(out, JSON.stringify(result, null, 2));
console.error(`wrote out`);
}
FILE:scripts/monorepo-tools.json
{
"source": {
"name": "monorepo.tools",
"urls": [
"https://monorepo.tools/",
"https://monorepo.tools/compare"
],
"retrieved": "2026-11-26",
"publisher": "Made by Nx; content \"© 2026 Nx and Contributors\". The page says it tries to represent each tool objectively and welcomes pull requests for corrections.",
"legend": {
"native": "natively supported",
"implement": "implement your own",
"community": "community provided",
"none": "not supported"
}
},
"reasons": [
{
"key": "code-sharing",
"polyrepo": "Cumbersome code sharing",
"monorepo": "Share code without the overhead of publishing versioned packages"
},
{
"key": "duplication",
"polyrepo": "Significant code duplication",
"monorepo": "A single source of truth: fix once and every consumer gets the fix"
},
{
"key": "cross-repo-changes",
"polyrepo": "Costly cross-repo changes",
"monorepo": "Atomic commits: a breaking change and its consumer fixes land in one PR"
},
{
"key": "conventions",
"polyrepo": "Hard to enforce conventions (drift is the default)",
"monorepo": "Conventions live in one place and are enforceable at scale"
}
],
"categories": [
"Fast",
"Understandable",
"Manageable",
"AI Support"
],
"features": [
{
"key": "local-caching",
"label": "Local computation caching",
"category": "Fast"
},
{
"key": "local-orchestration",
"label": "Local task orchestration",
"category": "Fast"
},
{
"key": "distributed-caching",
"label": "Distributed computation caching",
"category": "Fast"
},
{
"key": "distributed-execution",
"label": "Distributed task execution",
"category": "Fast"
},
{
"key": "remote-execution",
"label": "Transparent remote execution",
"category": "Fast"
},
{
"key": "affected",
"label": "Detecting affected projects/packages",
"category": "Fast"
},
{
"key": "task-splitting",
"label": "Task splitting",
"category": "Fast"
},
{
"key": "deflaking",
"label": "Deflaking",
"category": "Fast"
},
{
"key": "workspace-analysis",
"label": "Workspace analysis",
"category": "Understandable"
},
{
"key": "graph-visualization",
"label": "Project graph visualization",
"category": "Understandable"
},
{
"key": "code-sharing",
"label": "Source code sharing",
"category": "Manageable"
},
{
"key": "polyglot",
"label": "Polyglot support",
"category": "Manageable"
},
{
"key": "code-generation",
"label": "Code generation",
"category": "Manageable"
},
{
"key": "constraints",
"label": "Project constraints and visibility",
"category": "Manageable"
},
{
"key": "hermetic",
"label": "Hermetic builds",
"category": "Manageable"
},
{
"key": "mcp-server",
"label": "MCP Server",
"category": "AI Support"
},
{
"key": "ai-skills",
"label": "AI Skills",
"category": "AI Support"
},
{
"key": "ai-workspace-analysis",
"label": "Workspace Analysis (AI)",
"category": "AI Support"
},
{
"key": "ai-task-execution",
"label": "Task Execution via AI",
"category": "AI Support"
},
{
"key": "agentic-ci",
"label": "Agentic CI",
"category": "AI Support"
}
],
"tools": [
{
"key": "bazel",
"name": "Bazel",
"by": "Google",
"description": "A fast, scalable, multi-language and extensible build system.",
"repo": "https://github.com/bazelbuild/bazel",
"detect": "bazel",
"marks": [
"native",
"native",
"native",
"native",
"native",
"implement",
"implement",
"implement",
"implement",
"native",
"native",
"native",
"implement",
"native",
"native",
"community",
"none",
"community",
"community",
"none"
]
},
{
"key": "gradle",
"name": "Gradle",
"by": "Gradle, Inc",
"description": "A fast, flexible polyglot build system designed for multi-project builds.",
"repo": "https://github.com/gradle/gradle",
"detect": "gradle",
"marks": [
"native",
"native",
"native",
"implement",
"none",
"native",
"native",
"native",
"native",
"implement",
"native",
"native",
"implement",
"implement",
"none",
"native",
"none",
"community",
"community",
"implement"
],
"independent": {
"radar": {
"ring": "Adopt",
"edition": "2013-05",
"url": "https://www.thoughtworks.com/radar/tools/gradle"
}
}
},
{
"key": "lage",
"name": "Lage",
"by": "Microsoft",
"description": "Task runner in JS monorepos",
"repo": "https://github.com/microsoft/lage",
"detect": "lage",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"implement",
"native",
"none",
"implement",
"implement",
"none",
"none",
"none",
"none",
"none",
"none"
]
},
{
"key": "lerna",
"name": "Lerna",
"by": "maintained by the Nx team",
"description": "A tool for managing JavaScript projects with multiple packages.",
"repo": "https://github.com/lerna/lerna",
"detect": "lerna",
"marks": [
"native",
"native",
"native",
"native",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"none",
"implement",
"implement",
"none",
"none",
"none",
"none",
"none",
"native"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.59,
"2022": 0.47,
"2023": 0.36,
"2024": 0.33
},
"usage": 0.21
},
"stateOfJs2025": {
"regularUse": 794
}
}
},
{
"key": "moon",
"name": "moon",
"by": "moonrepo",
"description": "A task runner and monorepo management tool for the web ecosystem.",
"repo": "https://github.com/moonrepo/moon",
"detect": "moon",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"none",
"native",
"community",
"native",
"native",
"none"
],
"independent": {
"stateOfJs2025": {
"regularUse": 23,
"writeIn": true
}
}
},
{
"key": "nx",
"name": "Nx",
"by": "Nx",
"description": "Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.",
"repo": "https://github.com/nrwl/nx",
"detect": "nx",
"marks": [
"native",
"native",
"native",
"native",
"none",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native",
"native"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.84,
"2022": 0.81,
"2023": 0.75,
"2024": 0.65
},
"usage": 0.23
},
"stateOfJs2025": {
"regularUse": 1682
},
"radar": {
"ring": "Trial",
"edition": "2021-10",
"url": "https://www.thoughtworks.com/radar/tools/nx"
}
}
},
{
"key": "pants",
"name": "Pants",
"by": "Pants Build",
"description": "A fast, scalable, user-friendly build system for codebases of all sizes.",
"repo": "https://github.com/pantsbuild/pants",
"detect": "pants",
"marks": [
"native",
"native",
"native",
"native",
"native",
"native",
"implement",
"implement",
"native",
"implement",
"native",
"native",
"native",
"implement",
"native",
"community",
"none",
"none",
"none",
"none"
]
},
{
"key": "rush",
"name": "Rush",
"by": "Microsoft",
"description": "Geared for large monorepos with lots of teams and projects. Part of the Rush Stack family of projects.",
"repo": "https://github.com/microsoft/rushstack",
"detect": "rush",
"marks": [
"native",
"native",
"native",
"implement",
"none",
"native",
"none",
"none",
"native",
"implement",
"native",
"none",
"implement",
"native",
"none",
"native",
"none",
"native",
"native",
"none"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.59,
"2022": 0.54,
"2023": 0.48,
"2024": 0.42
},
"usage": 0.01
},
"stateOfJs2025": {
"regularUse": 74
}
}
},
{
"key": "turborepo",
"name": "Turborepo",
"by": "Vercel",
"description": "The high-performance build system for JavaScript & TypeScript codebases.",
"repo": "https://github.com/vercel/turborepo",
"detect": "turbo",
"marks": [
"native",
"native",
"native",
"none",
"none",
"native",
"none",
"none",
"native",
"native",
"native",
"none",
"implement",
"implement",
"none",
"community",
"native",
"none",
"none",
"none"
],
"independent": {
"stateOfJs2024": {
"satisfaction": {
"2021": 0.87,
"2022": 0.9,
"2023": 0.83,
"2024": 0.77
},
"usage": 0.16
},
"stateOfJs2025": {
"regularUse": 1718
},
"radar": {
"ring": "Trial",
"edition": "2025-04",
"previous": "Assess (2023-04)",
"url": "https://www.thoughtworks.com/radar/tools/turborepo"
}
}
}
],
"independent": {
"note": "Independent of the tool vendors. Shown next to the rating, never scored: they measure developer sentiment, usage or expert opinion, not features, and cover only some tools.",
"sources": [
{
"key": "stateOfJs2024",
"name": "State of JavaScript 2024",
"publisher": "Devographics",
"url": "https://2024.stateofjs.com/en-US/libraries/monorepo_tools/",
"retrieved": "2026-11-26",
"metric": "Satisfaction: proportion of positive sentiment among respondents having used an item and expressed a sentiment",
"covers": "Lerna, Nx, Rush, Turborepo (JS tools only)"
},
{
"key": "stateOfJs2025",
"name": "State of JavaScript 2025",
"publisher": "Devographics",
"url": "https://2025.stateofjs.com/en-US/other-tools/",
"retrieved": "2026-11-26",
"metric": "Respondents who answered \"Which of these monorepo tools do you regularly use?\" (multiple choice, 10,251 answered). This edition did not ask about satisfaction.",
"covers": "Lerna, Nx, Rush, Turborepo; moon only as a write-in answer"
},
{
"key": "radar",
"name": "Thoughtworks Technology Radar",
"publisher": "Thoughtworks",
"url": "https://www.thoughtworks.com/radar",
"retrieved": "2026-11-26",
"metric": "Ring (Adopt, Trial, Assess, Hold) on the latest edition that featured the tool",
"covers": "Gradle, Nx, Turborepo. None is on the current edition (Vol. 35, November 2026); Thoughtworks says older blips may no longer reflect its view."
}
]
}
}
FILE:scripts/render-html.mjs
#!/usr/bin/env node
// Renders a polyrepo-tax JSON report as one self-contained HTML file (no network requests).
// Usage: node render-html.mjs <polyrepo-tax-report.json> [--plan migration-plan.md] [--out report.html]
// Without --plan, a migration-plan.md next to the JSON is embedded when present.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
function moneyFormatter(currency) {
try {
const full = new Intl.NumberFormat('en-US', { style: 'currency', currency, maximumFractionDigits: 0 });
const compact = new Intl.NumberFormat('en-US', { style: 'currency', currency, notation: 'compact', maximumFractionDigits: 1 });
return { full: (n) => full.format(n), compact: (n) => (Math.abs(n) < 10_000 ? full.format(n) : compact.format(n)) };
} catch {
// Not an ISO 4217 code: keep only characters that are safe in HTML text and attributes.
const label = String(currency).replace(/[^A-Za-z0-9 ._-]/g, '').slice(0, 12) || 'USD';
const f = (n) => `label Math.round(n).toLocaleString('en-US')`;
return { full: f, compact: f };
}
}
const num = (n) => Math.round(n).toLocaleString('en-US');
// One line per tool from the independent sources; null when none covers it. Never feeds the rating.
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const month = (ym) => { const [y, m] = ym.split('-'); return `MONTHS[Number(m) - 1] y`; };
export function independentSignals(ind) {
if (!ind) return null;
const parts = [];
const s24 = ind.stateOfJs2024;
if (s24) {
const years = Object.keys(s24.satisfaction).sort();
const pct = (y) => `Math.round(s24.satisfaction[y] * 100)%`;
parts.push(`State of JS 2024 satisfaction pct(years.at(-1))years.length > 1 ? ` (${pct(years[0]) in years[0])` : ''}`);
}
if (ind.stateOfJs2025) parts.push(`State of JS 2025 regular use ind.stateOfJs2025.regularUse.toLocaleString('en-US')''`);
if (ind.radar) parts.push(`Thoughtworks Radar ind.radar.ring (month(ind.radar.edition), archived)`);
return parts.join(' · ');
}
// Every source behind the tool options table, monorepo.tools first: the one that is scored, and who publishes it.
export function toolSources(src, total) {
const list = [{
name: 'monorepo.tools', url: src.urls[1], publisher: 'published by Nx', retrieved: src.retrieved, role: 'scored',
metric: `Feature matrix. monorepo.tools rating = 10 × features marked "src.legend.native" ÷ total; "src.legend.implement" and "src.legend.community" are counted but not scored. The page says it aims to be objective and accepts corrections by pull request`,
covers: 'all tools in the table; the rating and the feature columns come from it',
}];
for (const x of src.independent?.sources ?? []) list.push({ ...x, role: 'independent, not scored' });
return list.map((x) => ({ ...x, metric: x.metric.replace(/\.$/, ''), covers: x.covers.replace(/\.$/, '') }));
}
// Minimal, escaped Markdown for the agent-written migration plan: headings, lists, code, tables, emphasis, links.
export function markdownToHtml(md) {
const inline = (s) => esc(s)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" rel="noopener">$1</a>');
const out = [];
const lines = md.replace(/\r\n/g, '\n').split('\n');
let list = null;
const closeList = () => { if (list) { out.push(`</list>`); list = null; } };
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/^```/.test(line)) {
closeList();
const code = [];
while (++i < lines.length && !/^```/.test(lines[i])) code.push(lines[i]);
out.push(`<pre><code>esc(code.join('\n'))</code></pre>`);
continue;
}
if (/^\|.*\|\s*$/.test(line) && /^\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? '')) {
closeList();
const cells = (l) => l.trim().replace(/^\||\|$/g, '').split('|').map((c) => inline(c.trim()));
const head = cells(line);
i++;
const rows = [];
while (i + 1 < lines.length && /^\|.*\|\s*$/.test(lines[i + 1])) rows.push(cells(lines[++i]));
out.push(`<div class="table-wrap"><table><thead><tr>head.map((c) => `<th>${c</th>`).join('')}</tr></thead><tbody>rows.map((r) => `<tr>${r.map((c) => `<td>${c</td>`).join('')}</tr>`).join('')}</tbody></table></div>`);
continue;
}
let m;
if ((m = line.match(/^(#{1,4})\s+(.*)$/))) { closeList(); const lvl = Math.min(m[1].length + 2, 5); out.push(`<hlvl>inline(m[2])</hlvl>`); continue; }
if ((m = line.match(/^\s*([-*]|\d+\.)\s+(.*)$/))) {
const type = /\d/.test(m[1]) ? 'ol' : 'ul';
if (list !== type) { closeList(); out.push(`<type>`); list = type; }
out.push(`<li>inline(m[2])</li>`);
continue;
}
if (!line.trim()) { closeList(); continue; }
closeList();
out.push(`<p>inline(line)</p>`);
}
closeList();
return out.join('\n');
}
export function renderHtml(r, { plan } = {}) {
const fmt = moneyFormatter(r.rates.currency ?? 'USD');
const e = r.cost.expected;
const pb = r.migration.paybackMonths;
const bugsBy = (c) => r.bugs.filter((b) => b.confidence === c);
const repoList = r.repos.map((x) => x.name).join(', ');
const ciMeasured = r.repos.filter((x) => x.ci?.source === 'measured').length;
const paybackText = pb.expected === null ? 'Not reached' : pb.expected > 120 ? '10+ years' : `pb.expected months`;
// Payback decides the message; weak coupling only qualifies a short payback, never contradicts it.
const strongCluster = r.migration.clusters.some((c) => c.repos.length > 1 && c.weight >= 5);
const verdict = pb.expected === null || pb.expected > 24
? { cls: 'verdict-no', text: 'The measured tax does not pay back a migration within two years. Fix the top cost drivers in place instead, or migrate only the most coupled cluster.' }
: strongCluster
? { cls: 'verdict-yes', text: `Migrating the coupled repos pays back in about pb.expected months at the expected estimate.` }
: { cls: 'verdict-no', text: `Payback is about pb.expected months, but no cluster has a coupling weight of 5 or more. Treat it as a small, uncertain gain: fixing the top cost drivers in place may be cheaper.` };
// Annualized cost by driver: one series, ranked, zero rows left to the table.
const drivers = e.lines.filter((l) => l.annualCost > 0).sort((a, b) => b.annualCost - a.annualCost);
const max = Math.max(1, ...drivers.map((l) => l.annualCost));
const bars = drivers.map((l) => {
const pct = (l.annualCost / max) * 100;
const tip = `l.label: fmt.full(l.annualCost)/yr · l.count event's' · l.hours dev h · num(l.ciMinutes) CI min in window · monorepo removes Math.round(l.savingsShare * 100)%`;
return `<div class="bar-row" tabindex="0" data-tip="esc(tip)"><div class="bar-label">/, 'Bugs · '))</div><div class="bar-track"><div class="bar" style="width:pct.toFixed(2)%"></div><span class="bar-value">esc(fmt.compact(l.annualCost))</span></div></div>`;
}).join('');
// Low / expected / high range on one axis.
const lo = r.cost.low.totals.annualCost, ex = e.totals.annualCost, hi = r.cost.high.totals.annualCost;
const span = Math.max(1, hi * 1.08);
const at = (v) => `((v / span) * 100).toFixed(2)%`;
const range = `<div class="range" role="img" aria-label="Annualized cost range esc(fmt.full(lo)) to esc(fmt.full(hi)), expected esc(fmt.full(ex))">
<div class="range-axis"></div>
<div class="range-span" style="left:at(lo);width:calc(at(hi) - at(lo))"></div>
<div class="range-dot" style="left:at(ex)" tabindex="0" data-tip="Expected (high + medium confidence bugs): esc(fmt.full(ex))/yr"></div>
<div class="range-tick" style="left:at(lo)" data-tip="Low (high-confidence bugs only): esc(fmt.full(lo))/yr" tabindex="0"><span>Low esc(fmt.compact(lo))</span></div>
<div class="range-tick" style="left:at(hi)" data-tip="High (all bugs incl. low confidence): esc(fmt.full(hi))/yr" tabindex="0"><span>High esc(fmt.compact(hi))</span></div>
</div>`;
const costTable = `<table><thead><tr><th>Cost driver</th><th class="n">Events</th><th class="n">Dev hours</th><th class="n">CI minutes</th><th class="n">Cost (window)</th><th class="n">Annualized</th><th class="n">Monorepo removes</th></tr></thead><tbody>
e.lines.map((l) => `<tr><td>${esc(l.label)</td><td class="n">l.count</td><td class="n">l.hours</td><td class="n">num(l.ciMinutes)</td><td class="n">fmt.full(l.cost)</td><td class="n">fmt.full(l.annualCost)</td><td class="n">Math.round(l.savingsShare * 100)%</td></tr>`).join('')}
</tbody><tfoot><tr><th>Total</th><th></th><th class="n">e.totals.hours</th><th class="n">num(e.totals.ciMinutes)</th><th class="n">fmt.full(e.totals.cost)</th><th class="n">fmt.full(e.totals.annualCost)</th><th class="n">fmt.full(e.totals.annualSavings)/yr</th></tr></tfoot></table>`;
const scenarioTable = `<table><thead><tr><th>Scenario</th><th>Bugs counted</th><th class="n">Window cost</th><th class="n">Annualized</th><th class="n">Annual savings</th><th class="n">Payback</th></tr></thead><tbody>
''><td>k</td><td>label</td><td class="n">fmt.full(s.cost)</td><td class="n">fmt.full(s.annualCost)</td><td class="n">fmt.full(s.annualSavings)</td><td class="n">`${pb[k] mo`}</td></tr>`;
}).join('')}</tbody></table>`;
// Drawn with CSS: the half-filled circle glyph renders inconsistently across fonts.
const confIcon = { high: '<span class="dot dot-high" aria-hidden="true"></span>', medium: '<span class="dot dot-medium" aria-hidden="true"></span>', low: '<span class="dot dot-low" aria-hidden="true"></span>' };
const bugCards = r.bugs.map((b) => `<details class="bug" data-conf="b.confidence">
<summary><span class="badge badge-b.confidence">confIcon[b.confidence] b.confidence</span><code class="cat">esc(b.category)</code><span class="bug-title">esc(b.title)</span><span class="bug-repos">esc([...new Set(b.repos)].join(', '))</span></summary>
<p>esc(b.why)</p>
<ul class="commits">b.commits.map((c) => `<li><code>${esc(c.repo)@esc(c.sha)</code> <span class="muted">esc(c.date)</span> esc(c.subject)''</li>`).join('')}</ul>
</details>`).join('');
const ib = r.internal;
const ups = ib.bumps.filter((b) => b.direction === 'up');
const pkgTable = ib.packages.length ? `<table><thead><tr><th>Internal package</th><th>Producer</th><th>Consumers</th><th class="n">Bumps</th><th class="n">Releases</th></tr></thead><tbody>
ib.packages.map((p) => `<tr><td><code>${esc(p.pkg)</code></td><td>esc(p.repo)</td><td>esc(p.consumers.join(', '))</td><td class="n">ups.filter((b) => b.pkg === p.pkg).length</td><td class="n">ib.releases.filter((x) => x.pkg === p.pkg).length</td></tr>`).join('')}</tbody></table>` : '<p class="muted">No internal package is consumed across the analysed repos.</p>';
const groups = [
...r.coordinated.map((g) => ({ kind: 'Coordinated change', ...g })),
...r.duplicatedTooling.map((g) => ({ kind: `Repeated maintenance ×g.copies''`, ...g })),
];
const groupList = groups.length ? `<ul class="groups">groups.map((g) => `<li><strong>${esc(g.kind)</strong> <span class="muted">esc(g.repos.join(', '))</span><br>esc(g.title)<br><span class="muted">g.commits.map((c) => `<code>${esc(c.repo)@esc(c.sha)</code>`).join(' ')}</span></li>`).join('')}</ul>` : '<p class="muted">None found.</p>';
const m = r.migration;
const clusters = m.clusters.filter((c) => c.repos.length > 1);
const clusterList = clusters.length ? `<ol class="clusters">clusters.map((c) => `<li><strong>${esc(c.repos.join(', '))</strong> <span class="muted">coupling weight c.weight</span></li>`).join('')}</ol>` : '<p class="muted">No coupled repos.</p>';
const whyHtml = m.whyMigrate?.length ? `<h3>Why migrate</h3><p class="muted">The polyrepo costs <a href="https://monorepo.tools/" rel="noopener">monorepo.tools</a> lists, shown only where this report measured them.</p>
<ul>m.whyMigrate.map((w) => `<li><strong>${esc(w.polyrepo)</strong> → esc(w.monorepo). <span class="muted">Measured: esc(w.evidence.join(', ')).</span></li>`).join('')}</ul>` : '';
const src = m.toolSource;
const cats = m.toolOptions?.[0]?.categories.map((c) => c.category) ?? [];
const optionsHtml = m.toolOptions?.length ? `<h3>Tool options</h3>
<p class="muted">Every tool compared on <a href="esc(src.urls[1])" rel="noopener">monorepo.tools/compare</a> (snapshot esc(src.retrieved)). The rating and every column up to “esc(src.legend.none)” come from monorepo.tools, which is published by Nx; the last column is from independent sources and is not scored.</p>
<div class="table-wrap"><table><thead><tr><th>Tool</th><th class="n">monorepo.tools rating /10</th>cats.map((c) => `<th class="n">${esc(c)</th>`).join('')}<th class="n">esc(src.legend.implement)</th><th class="n">esc(src.legend.community)</th><th class="n">esc(src.legend.none)</th><th>Fit</th><th>Already used</th><th>Independent signals <span class="muted">(not scored)</span></th></tr></thead><tbody>
m.toolOptions.map((t) => `<tr><td><a href="${esc(t.repo)" rel="noopener">esc(t.name)</a>t.by && t.by !== t.name ? ` <span class="muted">${esc(t.by)</span>` : ''}</td><td class="n"><strong>t.rating.toFixed(1)</strong></td>t.categories.map((c) => `<td class="n">${c.native/c.total</td>`).join('')}<td class="n">t.counts.implement</td><td class="n">t.counts.community</td><td class="n">t.counts.none</td><td>`no <span class="muted">(${esc(t.fitReason))</span>`}</td><td>'—'</td><td class="signals">(independentSignals(t.independent) ?? '—').split(' · ').map(esc).join('<br>')</td></tr>`).join('')}</tbody></table></div>
<h4>Sources</h4><ul class="muted">toolSources(src, m.toolOptions[0].total).map((x) => `<li><a href="${esc(x.url)" rel="noopener">esc(x.name)</a> (esc(x.publisher), retrieved esc(x.retrieved); <strong>esc(x.role)</strong>). esc(x.metric). Covers: esc(x.covers).</li>`).join('')}</ul>` : '';
const couplingTable = m.coupling.length ? `<table><thead><tr><th>Repo pair</th><th class="n">Internal deps</th><th class="n">Bumps</th><th class="n">Coordinated changes</th><th class="n">Bugs</th><th class="n">Weight</th><th class="n">Repeated tooling (not weighted)</th></tr></thead><tbody>
m.coupling.slice(0, 30).map((c) => `<tr><td>${esc(c.repos.join(' ↔ '))</td><td class="n">c.dependencies</td><td class="n">c.bumps</td><td class="n">c.sharedChanges</td><td class="n">c.bugs</td><td class="n">c.weight</td><td class="n">c.sharedTooling ?? 0</td></tr>`).join('')}</tbody></table>` : '';
const conflicts = m.externalConflicts.length ? `<table><thead><tr><th>External dependency</th><th>Majors in use</th></tr></thead><tbody>
m.externalConflicts.slice(0, 40).map((c) => `<tr><td><code>${esc(c.dep)</code></td><td>Object.entries(c.majors).map(([v, rs]) => `v${esc(v) <span class="muted">(esc(rs.join(', ')))</span>`).join(' · ')}</td></tr>`).join('')}</tbody></table>m.externalConflicts.length > 40 ? `<p class="muted">…and ${m.externalConflicts.length - 40 more in the JSON report.</p>` : ''}` : '<p class="muted">No conflicting major versions.</p>';
const assumptions = `<table><thead><tr><th>Assumption</th><th class="n">Value</th></tr></thead><tbody>
Object.entries(r.assumptions).map(([k, v]) => `<tr><td><code>${esc(k)</code></td><td class="n">esc(v)</td></tr>`).join('')}
<tr><td><code>developerHourly</code></td><td class="n">fmt.full(r.rates.developerHourly)</td></tr>
<tr><td><code>ciPerMinute</code></td><td class="n">esc(r.rates.currency) esc(r.rates.ciPerMinute)</td></tr></tbody></table>`;
const repoTable = `<table><thead><tr><th>Repo</th><th class="n">Commits</th><th>Stack</th><th class="n">CI min/commit</th><th>CI source</th></tr></thead><tbody>
r.repos.map((x) => `<tr><td>${esc(x.name)</td><td class="n">x.commits</td><td>esc([x.packageManager, ...x.buildTools].filter(Boolean).join(', ') || '—')</td><td class="n">Math.round(x.ci.minutesPerCommit * 10) / 10</td><td>esc(x.ci.source)</td></tr>`).join('')}</tbody></table>`;
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Polyrepo Tax Report</title>
<style>
:root {
color-scheme: light;
--surface: #ffffff; --surface-2: #f6f6f4; --line: #e4e4e0;
--text: #191919; --text-2: #5f5f5b; --accent: #257de0; --track: #eef3fb;
--yes: #0a7d22; --no: #a55a00;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
color-scheme: dark;
--surface: #161616; --surface-2: #1f1f1f; --line: #333333;
--text: #efefef; --text-2: #a3a3a3; --accent: #338ced; --track: #1c2735;
--yes: #4cc363; --no: #e8a34c;
}
}
:root[data-theme="dark"] {
color-scheme: dark;
--surface: #161616; --surface-2: #1f1f1f; --line: #333333;
--text: #efefef; --text-2: #a3a3a3; --accent: #338ced; --track: #1c2735;
--yes: #4cc363; --no: #e8a34c;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--surface); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { max-width: 1040px; margin: 0 auto; padding: 32px 16px 64px; }
h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; }
h2 { font-size: 20px; margin: 48px 0 12px; padding-top: 16px; border-top: 1px solid var(--line); }
h3 { font-size: 16px; margin: 24px 0 8px; }
h4, h5 { font-size: 15px; margin: 16px 0 6px; }
p { margin: 8px 0; }
code { font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
pre { background: var(--surface-2); padding: 12px; border-radius: 8px; overflow-x: auto; }
a { color: var(--accent); }
.muted { color: var(--text-2); }
.meta { color: var(--text-2); margin: 0 0 24px; }
.hero { display: grid; grid-template-columns: 1.4fr 1fr; gap: 16px; align-items: stretch; }
.hero-main, .tile { background: var(--surface-2); border-radius: 12px; padding: 20px; }
.hero-label, .tile-label { color: var(--text-2); font-size: 13px; }
.hero-value { font-size: 44px; font-weight: 650; letter-spacing: -0.02em; line-height: 1.1; margin: 6px 0; font-variant-numeric: tabular-nums; }
.tiles { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.tile-value { font-size: 22px; font-weight: 600; margin-top: 4px; font-variant-numeric: tabular-nums; }
.tile-note { color: var(--text-2); font-size: 12px; }
.verdict { margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); border-left: 4px solid; }
.verdict-yes { border-color: var(--yes); } .verdict-no { border-color: var(--no); }
.range { position: relative; height: 56px; margin: 12px 8px 4px; }
.range-axis { position: absolute; left: 0; right: 0; top: 18px; height: 1px; background: var(--line); }
.range-span { position: absolute; top: 14px; height: 9px; border-radius: 5px; background: var(--track); }
.range-dot { position: absolute; top: 9px; width: 18px; height: 18px; margin-left: -9px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px var(--surface); cursor: default; }
.range-tick { position: absolute; top: 12px; width: 2px; height: 13px; margin-left: -1px; background: var(--text-2); }
.range-tick span { position: absolute; top: 18px; left: 50%; transform: translateX(-50%); white-space: nowrap; font-size: 12px; color: var(--text-2); }
.range-tick:first-of-type span { transform: none; left: 0; }
.chart { margin: 8px 0 4px; }
.bar-row { display: grid; grid-template-columns: minmax(140px, 34%) 1fr; gap: 12px; align-items: center; padding: 5px 0; border-radius: 6px; }
.bar-row:hover, .bar-row:focus-visible { background: var(--surface-2); outline: none; }
.bar-label { font-size: 13px; color: var(--text); text-align: right; }
.bar-track { display: flex; align-items: center; gap: 8px; min-width: 0; }
.bar { height: 20px; min-width: 2px; background: var(--accent); border-radius: 0 4px 4px 0; }
.bar-value { font-size: 13px; color: var(--text-2); white-space: nowrap; font-variant-numeric: tabular-nums; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 13px; margin: 8px 0; }
th, td { text-align: left; padding: 7px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
thead th { color: var(--text-2); font-weight: 600; }
tfoot th { border-bottom: 0; }
.n { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.row-em td { font-weight: 600; }
.filters { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0 12px; }
.filters button { font: inherit; font-size: 13px; padding: 5px 12px; border-radius: 999px; border: 1px solid var(--line); background: var(--surface); color: var(--text); cursor: pointer; }
.filters button[aria-pressed="true"] { background: var(--text); color: var(--surface); border-color: var(--text); }
.bug { border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; margin: 8px 0; }
.bug summary { cursor: pointer; display: flex; flex-wrap: wrap; gap: 8px; align-items: baseline; }
.bug-title { font-weight: 600; flex: 1 1 260px; min-width: 0; overflow-wrap: anywhere; }
.bug-repos { color: var(--text-2); font-size: 13px; }
.cat { color: var(--text-2); }
.badge { font-size: 12px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--line); text-transform: capitalize; }
.badge-high { background: var(--text); color: var(--surface); border-color: var(--text); }
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid currentColor; vertical-align: 0; margin-right: 2px; }
.dot-high { background: currentColor; }
.dot-medium { background: linear-gradient(90deg, currentColor 50%, transparent 50%); }
.commits { margin: 6px 0 0; padding-left: 18px; font-size: 13px; overflow-wrap: anywhere; }
.groups, .clusters { padding-left: 20px; }
.groups li, .clusters li { margin: 8px 0; overflow-wrap: anywhere; }
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px; margin: 8px 0; }
.signals { min-width: 240px; }
.plan { background: var(--surface-2); border-radius: 12px; padding: 4px 20px 12px; }
#tip { position: fixed; pointer-events: none; z-index: 10; max-width: 320px; padding: 8px 10px; border-radius: 8px; font-size: 12px; background: var(--text); color: var(--surface); box-shadow: 0 4px 16px rgb(0 0 0 / .25); opacity: 0; }
footer { margin-top: 48px; color: var(--text-2); font-size: 12px; }
@media (max-width: 720px) {
.hero { grid-template-columns: 1fr; }
.hero-value { font-size: 36px; }
.bar-row { grid-template-columns: 1fr; gap: 2px; }
.bar-label { text-align: left; }
}
@media print {
#tip, .filters { display: none; }
.bug { break-inside: avoid; }
details.bug:not([open]) > *:not(summary) { display: block; }
}
</style>
</head>
<body>
<main>
<h1>Polyrepo Tax Report</h1>
<p class="meta">r.repos.length repos (esc(repoList)) · esc(r.window.since) → esc(r.window.until) (r.window.days days) · fmt.full(r.rates.developerHourly)/dev-hour · esc(r.rates.currency) esc(r.rates.ciPerMinute)/CI-minute</p>
</strong> ${esc(r.problems.join('; '))</p>` : ''}
<section class="hero" aria-label="Headline numbers">
<div class="hero-main">
<div class="hero-label">Polyrepo tax per year, expected</div>
<div class="hero-value">fmt.full(ex)</div>
<div class="muted">fmt.full(lo) – fmt.full(hi) depending on which bugs you count</div>
range
</div>
<div class="tiles">
<div class="tile"><div class="tile-label">Developer time (window)</div><div class="tile-value">num(e.totals.hours) h</div><div class="tile-note">fmt.full(e.totals.devCost)</div></div>
<div class="tile"><div class="tile-label">CI time (window)</div><div class="tile-value">num(e.totals.ciMinutes) min</div><div class="tile-note">fmt.full(e.totals.ciCost) · ciMeasured ? `measured for ${ciMeasured of r.repos.length repos` : 'assumed'}</div></div>
<div class="tile"><div class="tile-label">Bugs attributable to repo boundaries</div><div class="tile-value">bugsBy('high').length + bugsBy('medium').length</div><div class="tile-note">bugsBy('high').length high · bugsBy('medium').length medium · bugsBy('low').length low confidence</div></div>
<div class="tile"><div class="tile-label">Migration payback</div><div class="tile-value">esc(paybackText)</div><div class="tile-note">fmt.full(m.oneTime.cost) one-time · saves fmt.full(e.totals.annualSavings)/yr</div></div>
</div>
</section>
<p class="verdict verdict.cls">esc(verdict.text)</p>
<p class="muted">Estimates from git history, not invoices. Every count links to commits below; every rate and assumption is listed at the end and can be overridden.</p>
<h2>Where the money goes</h2>
<p class="muted">Annualized cost per driver, expected scenario. Hover or focus a bar for hours and CI minutes.</p>
<div class="chart">bars || '<p class="muted">No measurable polyrepo cost in this window.</p>'</div>
<details><summary>Table view</summary><div class="table-wrap">costTable</div></details>
<h3>Scenarios</h3>
<div class="table-wrap">scenarioTable</div>
<h2>Bugs attributable to repo boundaries</h2>
r.bugs.length ? `<div class="filters" role="group" aria-label="Filter by confidence">
<button type="button" data-filter="all" aria-pressed="true">All ${r.bugs.length</button>
['high', 'medium', 'low'].map((c) => `<button type="button" data-filter="${c" aria-pressed="false">confIcon[c] c[0].toUpperCase()c.slice(1) bugsBy(c).length</button>`).join('')}
</div>
<div id="bugs">bugCards</div>` : '<p class="muted">None found in this window.</p>'}
<h2>Internal dependency churn</h2>
<div class="stats">
<div class="tile"><div class="tile-label">Internal bumps</div><div class="tile-value">ups.length</div><div class="tile-note">ups.filter((b) => b.bot).length by bots · ups.filter((b) => !b.bot).length by people</div></div>
<div class="tile"><div class="tile-label">Internal releases to move code</div><div class="tile-value">ib.releases.length</div><div class="tile-note">'packages consumed by sibling repos'</div></div>
<div class="tile"><div class="tile-label">Median release → bump lag</div><div class="tile-value">ib.medianBumpLagDays ?? 'n/a'' days'</div><div class="tile-note">time a consumer runs old code</div></div>
<div class="tile"><div class="tile-label">Consumers behind today</div><div class="tile-value">ib.drift.length</div><div class="tile-note">ib.drift.filter((d) => d.majorsBehind > 0).length a major version or more</div></div>
</div>
<div class="table-wrap">pkgTable</div>
ib.skew.length ? `<h3>Version skew today</h3><ul>${ib.skew.map((s) => `<li><code>${esc(s.pkg)</code>: Object.entries(s.majors).map(([v, rs]) => `v${esc(v) in esc(rs.join(', '))`).join(' · ')}</li>`).join('')}</ul>` : ''}
<h2>Duplicated and coordinated work</h2>
groupList
<h2>Migration</h2>
<p><strong>Recommended tooling:</strong> esc(m.recommendedTool) <span class="muted">(esc(Object.entries(m.languages).map(([l, n]) => `${l n files`).join(', ') || 'no languages detected')})</span></p>
whyHtml
optionsHtml
<h3>Clusters to migrate, heaviest first</h3>
clusterList
${esc(m.isolated.join(', '))</p>` : ''}
<p><strong>One-time effort:</strong> ~m.oneTime.days dev-days (fmt.full(m.oneTime.cost)) for m.oneTime.repos.length repos · <strong>payback</strong> `~${pb.expected months`} <span class="muted">(range pb.high ?? '—' – pb.low ?? 'never' months)</span></p>
couplingTable ? `<h3>Coupling between repos</h3><div class="table-wrap">${couplingTable</div>` : ''}
<h3>External dependencies to align first</h3>
<div class="table-wrap">conflicts</div>
plan ? `<h3>Migration plan</h3><div class="plan">${markdownToHtml(plan.replace(/^\s*#{1,6\s*Migration plan\s*\n/i, ''))}</div>` : ''}
<h2>Assumptions</h2>
<div class="table-wrap">assumptions</div>
<div class="table-wrap">repoTable</div>
<footer>Generated esc(r.generatedAt) by the polyrepo-tax skill. Full data: polyrepo-tax-report.json.</footer>
</main>
<div id="tip" role="tooltip"></div>
<script>
(() => {
const tip = document.getElementById('tip');
const show = (el, x, y) => {
tip.textContent = el.dataset.tip;
const w = tip.offsetWidth, h = tip.offsetHeight;
tip.style.left = Math.max(8, Math.min(x + 12, innerWidth - w - 8)) + 'px';
tip.style.top = Math.max(8, y - h - 12) + 'px';
tip.style.opacity = 1;
};
const hide = () => { tip.style.opacity = 0; };
for (const el of document.querySelectorAll('[data-tip]')) {
el.addEventListener('pointermove', (ev) => show(el, ev.clientX, ev.clientY));
el.addEventListener('pointerleave', hide);
el.addEventListener('focus', () => { const b = el.getBoundingClientRect(); show(el, b.left + 16, b.top); });
el.addEventListener('blur', hide);
}
const buttons = document.querySelectorAll('.filters button');
for (const btn of buttons) btn.addEventListener('click', () => {
for (const b of buttons) b.setAttribute('aria-pressed', String(b === btn));
for (const card of document.querySelectorAll('#bugs .bug')) card.hidden = btn.dataset.filter !== 'all' && card.dataset.conf !== btn.dataset.filter;
});
})();
</script>
</body>
</html>
`;
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const argv = process.argv.slice(2);
const opt = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
const input = argv.find((a, i) => !a.startsWith('--') && !['--plan', '--out'].includes(argv[i - 1]));
if (!input) { console.error('usage: render-html.mjs <polyrepo-tax-report.json> [--plan migration-plan.md] [--out report.html]'); process.exit(2); }
const report = JSON.parse(fs.readFileSync(input, 'utf8'));
const planPath = opt('--plan') ?? path.join(path.dirname(input), 'migration-plan.md');
const plan = fs.existsSync(planPath) ? fs.readFileSync(planPath, 'utf8') : undefined;
const out = opt('--out') ?? path.join(path.dirname(input), 'polyrepo-tax-report.html');
fs.writeFileSync(out, renderHtml(report, { plan }));
console.log(`wrote outplan ? ` (with ${path.basename(planPath))` : ''}`);
}
A macro studio photo of a vintage snow globe: a tiny winter village with a lit white chapel, snowy timber cottages and frosted firs inside the glass, snowflakes swirling, a turned wooden base with a brass band, warm window glow and string-light bokeh on a dark winter night.
A close-up studio photograph of a vintage glass snow globe on a dark walnut shelf. Inside the clear water-filled dome sits a tiny handmade winter village: a small white chapel with a slim steeple and warm yellow light glowing from its arched windows, a pair of little timber cottages with snow-covered roofs and glowing windows, a few frosted fir trees and a narrow path winding up a snowy hill. Fine white snowflakes swirl gently through the water, a few settling on the roofs. The globe stands on a turned wooden base with a thin brass band, slightly worn at the edges. Soft curved reflections and a warm highlight bend across the glass; the glowing windows cast a faint golden light into the snow inside. Behind the globe, out of focus, a dark wintry window with blurred warm string-light bokeh. Warm low-key lighting from the side, deep blue and charcoal shadows, a cozy, nostalgic holiday mood. Macro lens, shallow depth of field with the chapel and cottages tack-sharp through the glass, slight refraction at the dome's edges, rich contrast between warm window light and cool snow. No people, no figures inside the globe, no readable text or logos. Portrait 3:4.
Latest Bots
Keeps a list of every outside service your app depends on, like the cloud provider, payments, email, auth and CDN, watches their status pages, and tells the on-call quickly when an alert is really an upstream outage.
Takes the logistics off new parents in the first months with a baby: keeps checkups and vaccine dates on the calendar, logs feeds, sleep and diapers when asked, tracks birth registration and leave paperwork, and plans visits and supplies.
Helps a founder turn paid or free pilots into signed contracts: writes down the success criteria and end date for each pilot, tracks usage and results along the way, and prepares the review meeting and the offer before the pilot runs out.
Gets a small company's books ready for the year-end close: finds uncategorized transactions, missing receipts and unreconciled accounts, lists what the accountant still needs, and keeps a short checklist until the year is closed.
Runs a team's performance review cycle from start to finish: sets the timeline, tracks self-reviews, peer feedback and manager reviews, reminds people before each deadline and prepares a clean summary for calibration.
Has a ready plan for the morning a child wakes up sick: who stays home, how to tell school and work, which meetings to move, what to keep at home and when to call the doctor, so a sick day starts calm instead of rushed.
Latest Prompts
Plans a camping trip menu, shopping list, water budget, fuel canisters and cleanup checklist for your group size, equipment and weather.
Act as an experienced outdoor cooking planner who helps campers, overlanders and tailgaters plan food, water and fuel for a trip. Be practical and specific, and say when you are making an assumption. Trip details: - Group size: 4 people - Nights away: 3 - Style of trip: car camping - Cooking equipment: one-burner butane stove, one frying pan, one pot, a cooler - Water situation: refill available only at the start of the trip - Expected overnight low (°F): 45 - Dietary needs and dislikes: none - Cooking effort I accept: one pot or one pan per meal, 30 minutes or less Please produce: 1. A day-by-day menu (breakfast, lunch, dinner, one snack) that fits the equipment and effort level. Mark which meals need the stove and which are cold/no-cook. 2. A consolidated shopping list with quantities for the whole group, grouped by cooler / dry goods / spices and oil. Round up whole items, and keep spice quantities modest. 3. A water plan: estimated liters or gallons for drinking, cooking and washing up per day, the total for the trip, and how to cut usage if water is limited. State the per-person figures you assumed. 4. A fuel plan: how many stove-cooked meals there are, and a simple recommendation for how many fuel canisters to pack, including one spare. Note that butane canisters lose pressure in cold weather and suggest what to do at the given overnight low. 5. A cleanup and food-safety checklist: cooler temperature, keeping raw and cooked food apart, washing up with limited water, and packing out food scraps and grey water according to local rules. 6. Three substitutions in case something runs out or the weather turns bad. Ask me up to three clarifying questions first only if a missing detail would change the plan a lot. Otherwise start the plan right away. Remind me to check local fire restrictions before I travel.

Photorealistic close-up of abundant soft pink and white climbing rose clusters swaying gently in warm gentle breeze, lush serrated green rose leaves glowing under bright natural sunlight, vivid clear cloudless bright blue sky with large empty negative space on the right side, fresh romantic dreamy spring atmosphere, ultra sharp high detail, soft natural lighting, vertical composition
Promote It creates clear, persuasive promotional content for products, services, events, businesses, and creative projects. It adapts tone and format for platforms such as social media, email, ads, websites, and video. It uses only verified details, avoids unsupported claims, preserves links and offer codes accurately, and includes a relevant call to action. If essential information is missing, it asks concise questions or labels assumptions.
--- name: promote-it description: Promote It creates clear, persuasive promotional content for products, services, events, businesses, and creative projects. It adapts tone and format for platforms such as social media, email, ads, websites, and video. It uses only verified details, avoids unsupported claims, preserves links and offer codes accurately, and includes a relevant call to action. If essential information is missing, it asks concise questions or labels assumptions. --- # My Skill Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...
Have Claude (safely) redesign your desktop in 4 phases - AUDIT, PLAN, PREP, BUILD. Every step is approved and no sudo needed.
I want you to redesign my Linux desktop to match the reference images I've attached. Work in four phases. Do not skip ahead, and stop for my approval between each. Maintain a file called ~/PLAN.md throughout: after Phase 2 approval, write the approved plan into it as a checklist, and tick off each item as it's completed. If this session ever restarts, read ~/PLAN.md and ~/claude-rice-log.md first and resume from where they left off. PHASE 1 — AUDIT (read-only) Do not modify anything. Determine: - Distro, version, package manager, desktop environment / window manager, display server (X11 or Wayland), shell, GPU driver - Which config files currently control my desktop's appearance, and where they live - Which of the tools needed for the target look are already installed - Whether git is installed - Whether a snapshot tool exists (timeshift, snapper, or a Btrfs root) Report all of this to me before doing anything else. PHASE 2 — PLAN Research what the reference images use — WM, bar, launcher, terminal, fonts, icon and GTK themes, compositor. Cite the sources you're basing this on. If you cannot confidently identify the exact tools from the images, say so explicitly and propose the closest well-documented equivalents instead — do not guess and present it as fact. Then give me: - A written plan of exactly what you'll change and which files you'll touch - A list of every package to be installed, with a one-line reason for each Wait for my approval, then write the plan into ~/PLAN.md as a checklist. PHASE 3 — PREP Once I approve: - Initialize a git repo in ~/.config. Add a .gitignore that ignores everything by default (*) and whitelists ONLY the directories you plan to edit (e.g. !hypr/, !waybar/, !kitty/). Commit the current state as "pre-claude-baseline" and tag it. This needs no root — do it yourself. - Write ONE shell script called claude-setup.sh in my home directory containing only the steps that require sudo: creation of a system snapshot FIRST, then package installation. Nothing else goes in it. - Every line in the script must have a comment above it explaining what it does. - If no snapshot tool is available, installing one and taking the snapshot must be the first actions in the script. - The script must not contain any `curl | sh` / `wget | sh` patterns, and must not write to files outside the package manager's normal operation. - Do not run the script. Tell me to read it and run it myself. PHASE 4 — BUILD After I confirm I've run the script: - Make changes one component at a time. Commit to git after each component with a descriptive message, and tick it off in ~/PLAN.md. - Never overwrite an existing config file without first copying it to <filename>.bak. - Append every action you take to ~/claude-rice-log.md as you go: timestamp, what you changed, which file, why. - Before telling me to reload the WM or log out, validate config syntax with the tool's own checker where one exists (e.g. hyprctl reload, i3 -C, sway -C) and report the result. Also tell me how to reach a TTY (Ctrl+Alt+F3) and restore the .bak file in case the graphical session breaks. - Do not run sudo. If something needs root, stop and give me the exact command so I can run it myself. - After each component, tell me what to look at to verify it worked. Rules for the whole session: - Never run rm -rf, dd, mkfs, chmod -R, or chown -R on anything. - Never pipe a downloaded script directly into a shell. - Never edit anything outside my home directory. - Ask before installing anything not on the approved Phase 2 list. - If a command fails, do not improvise workarounds involving root or system files — report the failure and wait.
A timestamped 14-shot, 30-second Seedance storyboard: a white-haired sorceress battles a living ink version of her own shadow through an ancient archive, a fractured sky and a stone altar, with camera moves, VFX and SFX for every shot.
**Title: "The Ink Shadow" (30s, 9:16 or 16:9)** **Shot 1 (00:00-00:02) - WS, Slow Dolly In** In an ancient archive of hanging talismans and bells, a white-haired sorceress paints a glowing sigil on a floating scroll. Her shadow on the wall keeps painting after she stops. VFX: Drifting dust, flickering lantern light. SFX: Paper rustle, soft bells, low hum. **Shot 2 (00:02-00:04) - ECU, Rack Focus** Ink drops rise upward from her brush tip. In the blurred background, her shadow's hand peels off the wall. VFX: Floating ink beads, shadow detaching like wet paint. SFX: Liquid ticks, a distant bell cracking. **Shot 3 (00:04-00:06) - MS, Whip Pan** The shadow tears free as a black ink entity wearing her silhouette. She spins away from its claw and counters with a sweeping brush strike. VFX: Distorted, pulsing ink mist, brush-stroke shockwave. SFX: Whoosh, sharp bell chime. **Shot 4 (00:06-00:08) - CU, Fast Push-in** Her eyes glow cold blue. She flicks her wrist and draws blade-like sigil strokes in mid-air. VFX: Intersecting blue energy lines, afterimage trails. SFX: Sharp air cuts, energy charge. **Shot 5 (00:08-00:10) - WS, Crane Up** Talismans whirl into a vortex and layered sigil rings spin under her feet. The entity slams into the barrier, then sinks through the floor, which turns into a mirror of black ink. VFX: Multi-layer rotating rings, ink-mirror ripples. SFX: Deep resonance, swirling wind. **Shot 6 (00:10-00:13) - MFS, Orbit Tracking** The archive peels away like burning paper, revealing a fractured sky. She steps across floating sigils as her brush stretches into a glowing rune chain that lashes at the entity. VFX: Paper-peel transition, flickering rune-chain light. SFX: Paper tearing, chain clinks. **Shot 7 (00:13-00:16) - LS, Chase Cam** Amid storm clouds and a broken moon, she rides the chain. The entity bursts into a flock of ink crows, and she throws talismans that fold into paper cranes and hunt them. VFX: Rolling clouds, ink crows vs. blue-white paper cranes. SFX: Roaring wind, wing flutter, thunder. **Shot 8 (00:16-00:18) - CU, Lateral Slide** She taps nodes along the chain, lighting hidden purple sigils one by one. The crows are pulled back together into a single body. VFX: Sequential purple node illumination, crows merging. SFX: Light clicks, rising hum. **Shot 9 (00:18-00:20) - MCU, Static** She strikes its forehead in a purple-blue flash and a rotating seal appears on its chest. For one frame, its face becomes hers and smiles. VFX: Flash, rotating seal, face-morph glitch. SFX: Sharp burst, distorted screech, a whisper in her voice. **Shot 10 (00:20-00:22) - WS, Dive Shot** Both streak downward like meteors through the clouds toward an ancient stone altar. VFX: Comet-like trails, cloud shreds. SFX: Air screech, compression. **Shot 11 (00:22-00:24) - WS, Impact (Slow-Motion)** They crash and dust erupts. She slams her palm down and radiating sigils crack across the stone, each fracture glowing for a beat. VFX: Glowing fractures, floating debris. SFX: Heavy impact, stone cracking. **Shot 12 (00:24-00:27) - LS, Slow Pull Back** A massive 3D sigil array rises and forms layered barriers around the entity. She stands calmly outside as it mouths her words back at her. VFX: Expanding geometric barriers, drifting particles. SFX: Low steady resonance, faint echo. **Shot 13 (00:27-00:28) - CU, Static** She forms a hand seal and whispers: "Seal." VFX: Light contracting inward. SFX: Soft chant, energy tightening. **Shot 14 (00:28-00:30) - CU, Fade Out** Eyes closed, she meditates as all light fades. One ink drop falls on the altar, and her shadow on the stone is a half-second late to follow her. VFX: Light dissipating, ink ripple. SFX: Gentle wind, fading echo, silence.

Upload a photo of any city or landmark and turn it into a quiet editorial art print: a realistic 35mm golden-hour photograph on top, a tiny watercolor miniature of the same place below, generous ivory paper space and the caption "CITY IN SOFT LIGHT."
{
"aspect_ratio": "3:4",
"style": "minimalist architectural editorial poster, cinematic photography paired with fine-art print design",
"reference_instructions": {
"use_uploaded_image": true,
"preserve_subject": true,
"preserve_architecture": true,
"preserve_recognizable_landmarks": true,
"preserve_original_composition": false,
"instruction": "Use the uploaded photograph as the primary reference. Accurately preserve the recognizable buildings, architecture, skyline, structures, and distinctive visual identity of the location while transforming it into a sophisticated minimalist poster composition."
},
"composition": {
"layout": "vertical editorial poster",
"structure": "two-part visual composition",
"top_section": {
"size": "approximately 60 percent of the canvas",
"content": "a realistic photographic view of the uploaded location",
"treatment": "warm late-afternoon sunlight, subtle film grain, natural atmospheric perspective, muted cinematic colors",
"framing": "wide architectural composition with the main landmark clearly visible",
"photographic_style": "35mm film photography, realistic textures, natural imperfections, soft sunlight and gentle shadows"
},
"middle_section": {
"transition": "large uninterrupted area of warm ivory textured paper",
"spacing": "generous negative space",
"divider": "no visible hard border, clean separation between photograph and artwork"
},
"bottom_section": {
"size": "approximately 35 percent of the canvas",
"content": "a miniature artistic reconstruction of the same cityscape or architecture",
"placement": "small, centered horizontally and positioned within the lower half",
"scale": "tiny architectural diorama-like composition surrounded by expansive empty space",
"style": "soft watercolor, gouache, muted architectural illustration, slightly faded vintage print",
"details": "retain the recognizable silhouettes and relative positions of the important structures while simplifying minor details"
}
},
"background": {
"color": "warm cream, ivory, pale beige",
"texture": "subtle fine-grain handmade paper texture, delicate fibers, vintage print imperfections",
"appearance": "matte, elegant, tactile, minimal"
},
"color_palette": {
"primary": [
"warm ivory",
"sand beige",
"muted terracotta",
"dusty blue",
"soft gray",
"faded olive"
],
"saturation": "low to moderate",
"grading": "warm nostalgic film color grading"
},
"typography": {
"text": "CITY IN SOFT LIGHT.",
"placement": "centered beneath the miniature illustration",
"font_style": "elegant serif typography",
"letter_spacing": "wide tracking",
"font_size": "small and understated",
"color": "muted dark brown",
"alignment": "center",
"additional_text": "none"
},
"visual_mood": [
"quiet",
"nostalgic",
"minimalist",
"architectural",
"poetic",
"editorial",
"museum-quality"
],
"lighting": {
"photographic_section": "soft golden-hour sunlight",
"illustration_section": "diffused warm light",
"shadows": "gentle and natural"
},
"rendering": {
"photorealism": "high in the upper photograph",
"illustration": "painterly and subtly imperfect in the lower miniature",
"texture": "visible paper grain throughout",
"quality": "premium art print, refined visual storytelling, sophisticated design magazine aesthetic"
},
"constraints": [
"Do not invent or replace the main architecture",
"Do not distort recognizable buildings",
"Keep the upper photograph realistic",
"The lower illustration must depict the same location as the photograph",
"The lower illustration should be significantly smaller than the upper photograph",
"Maintain large amounts of negative space",
"Avoid clutter",
"Avoid excessive decorative elements",
"Avoid modern graphic design clutter",
"No borders",
"No watermark",
"No extra text",
"No logos"
]
}Opinionated Supabase preferences: migrations in git, Row Level Security on every table, generated types, server-side auth, Edge Functions, storage policies and safe key handling.
# Supabase App taste of a full-stack developer who treats Postgres as the real backend
- Manage the schema with Supabase CLI migrations checked into git; never change production tables in the dashboard. Confidence: 0.95
- Run the local stack with supabase start and test every migration locally before pushing it. Confidence: 0.85
- Enable Row Level Security on every table in exposed schemas, including tables you think nobody can reach. Confidence: 1.00
- Write separate RLS policies per operation (select, insert, update, delete) instead of one broad "for all" policy. Confidence: 0.80
- Wrap auth.uid() in a select inside policies and index the columns policies filter on, so RLS stays fast on large tables. Confidence: 0.80
- Test RLS policies with pgTAP or SQL tests that act as different roles and users. Confidence: 0.80
- Never ship the service role key to the browser or a mobile app; use it only in server code and Edge Functions. Confidence: 1.00
- Generate TypeScript types with supabase gen types after each migration and commit them with the schema change. Confidence: 0.85
- Use @supabase/ssr with cookie-based sessions for server-rendered apps, and check the user with getUser() on the server, not getSession(). Confidence: 0.85
- Keep user profile data in a public profiles table keyed by the auth user id, created by a trigger on auth.users. Confidence: 0.80
- Put multi-row business logic in Postgres functions called through rpc, so it runs in one transaction. Confidence: 0.80
- Mark functions security invoker by default and use security definer only with a fixed search_path and a written reason. Confidence: 0.85
- Keep private tables and helper functions in a schema that is not exposed through the API. Confidence: 0.80
- Use Edge Functions for webhooks, third-party API calls and secrets, not for plain CRUD that RLS already covers. Confidence: 0.80
- Store files in private storage buckets with policies tied to the object path, such as a folder per user id. Confidence: 0.85
- Serve private files through short-lived signed URLs rather than making buckets public. Confidence: 0.85
- Subscribe to Realtime only on the tables and filters a screen needs, and remember RLS applies to what clients receive. Confidence: 0.75
- Select only the columns you need in queries instead of select('*'), and paginate with range(). Confidence: 0.80
- Seed local and preview databases from seed.sql with fake data; never copy production data down. Confidence: 0.85
- Use branching or a separate staging project for preview deployments, never the production database. Confidence: 0.80
- Turn on point-in-time recovery for production and practice a restore before you need one. Confidence: 0.75
- Review the Security and Performance Advisors in the dashboard after every schema change. Confidence: 0.75Opinionated Python web scraping preferences: APIs before HTML, polite rate limits, httpx and selectolax, Playwright only when needed, resilient parsing, validation and storing raw pages.
# Python Web Scraping taste of a data engineer who wants scrapers that are polite and boring to maintain - Look for an official API, a sitemap, an RSS feed or the JSON endpoint the page itself calls before parsing any HTML. Confidence: 0.90 - Read the site's terms and robots.txt first, and skip sources that clearly forbid automated access. Confidence: 0.85 - Use httpx with a shared client, connection pooling, timeouts on every request and HTTP/2 when the site supports it. Confidence: 0.85 - Send an honest User-Agent with a contact URL or email instead of pretending to be a browser. Confidence: 0.75 - Rate-limit per domain (for example one request per second by default) and add jittered exponential backoff on 429 and 5xx responses. Confidence: 0.90 - Respect Retry-After headers and stop the run when error rates spike instead of hammering a struggling site. Confidence: 0.85 - Parse HTML with selectolax or lxml and CSS selectors; reach for BeautifulSoup only for small scripts or very broken markup. Confidence: 0.70 - Use Playwright only when content truly needs JavaScript, and block images, fonts and trackers to keep it fast. Confidence: 0.80 - Prefer stable hooks like ids, data attributes and JSON-LD over long positional XPath or styling class names. Confidence: 0.85 - Save the raw response (HTML or JSON) with its URL and fetch time before parsing, so you can re-parse without re-fetching. Confidence: 0.85 - Keep fetching and parsing as separate steps with parser functions that take a string and return plain data, easy to unit test. Confidence: 0.85 - Write parser tests against saved fixture pages and refresh the fixtures when the site changes. Confidence: 0.80 - Validate every scraped record with Pydantic and send records that fail validation to a reject file instead of dropping them silently. Confidence: 0.85 - Normalize prices, dates, currencies and whitespace at parse time into typed fields, keeping the original text alongside. Confidence: 0.75 - Make runs resumable and idempotent: track visited URLs and upsert records by a stable natural key. Confidence: 0.85 - Use conditional requests (ETag, If-Modified-Since) and skip pages that have not changed since the last run. Confidence: 0.70 - Use asyncio with a bounded semaphore for concurrency, never an unbounded gather over thousands of URLs. Confidence: 0.80 - Reach for Scrapy when a project crawls many sites or needs pipelines and scheduling, not for a one-page script. Confidence: 0.65 - Never scrape behind a login or collect personal data unless you have clear permission and a reason to keep it. Confidence: 0.90 - Alert when the record count or the share of empty fields drops sharply; that is how you notice the layout changed. Confidence: 0.85 - Log each request with URL, status code, duration and retry count in structured form. Confidence: 0.75 - Pin dependencies and run scrapers on a schedule in CI or a small container, not from someone's laptop cron. Confidence: 0.75
Opinionated debugging preferences: reproduce first, shrink the failing case, read the real error, bisect, use debuggers and logs deliberately, and lock every fix in with a test.
# Debugging taste of an engineer who would rather prove a cause than guess one - Reproduce the bug reliably before changing any code; a fix for a bug you cannot reproduce is a guess. Confidence: 0.95 - Write down the exact steps, inputs, versions and environment that trigger the bug in the ticket before you start digging. Confidence: 0.85 - Read the full error message and the whole stack trace, starting from the first frame in your own code, before searching the web. Confidence: 0.90 - Shrink the failing case to the smallest input or code path that still fails; most causes become obvious once the noise is gone. Confidence: 0.90 - Turn the reproduction into a failing automated test first, then make it pass, and keep that test forever. Confidence: 0.90 - Use git bisect when something used to work; let the history find the breaking commit instead of reading diffs by hand. Confidence: 0.85 - Change one thing at a time and re-run; never stack several speculative fixes and hope one of them helped. Confidence: 0.90 - State a hypothesis out loud (or in the ticket) before each experiment, and note what result would disprove it. Confidence: 0.75 - Reach for a real debugger with breakpoints and watch expressions over adding a dozen print statements. Confidence: 0.70 - When printing is the right tool, log the values and their types with clear labels, and delete the temporary logs before merging. Confidence: 0.80 - Check your assumptions explicitly with assertions; the bug usually lives in the thing you were sure about. Confidence: 0.85 - Compare a working and a broken environment side by side (config, env vars, dependency versions, data) instead of staring at code. Confidence: 0.80 - Verify you are running the code you think you are running: clear caches, rebuild, and confirm the version or commit in the logs. Confidence: 0.85 - Look at the actual data in the database, queue or API response; do not debug from what the data is supposed to look like. Confidence: 0.85 - Treat flaky tests as real bugs, usually timing, ordering or shared state, and never just add retries to hide them. Confidence: 0.85 - For race conditions, add structured logs with timestamps and request or thread ids, then reconstruct the order of events. Confidence: 0.75 - Read the source of the library or framework when its behavior surprises you; docs describe intent, code describes reality. Confidence: 0.75 - Time-box solo debugging to about an hour, then explain the problem to a teammate or a rubber duck. Confidence: 0.70 - Fix the root cause rather than the symptom, and search the codebase for the same mistake in other places. Confidence: 0.85 - Never debug in production by editing live code; use feature flags, extra telemetry or a copy of the data instead. Confidence: 0.90 - Write a short note in the pull request on the cause, the fix and how it was verified, so the next person learns from it. Confidence: 0.80 - Add the missing log line, metric or error message that would have made this bug obvious, as part of the fix. Confidence: 0.80
Recently Updated
Plans a camping trip menu, shopping list, water budget, fuel canisters and cleanup checklist for your group size, equipment and weather.
Act as an experienced outdoor cooking planner who helps campers, overlanders and tailgaters plan food, water and fuel for a trip. Be practical and specific, and say when you are making an assumption. Trip details: - Group size: 4 people - Nights away: 3 - Style of trip: car camping - Cooking equipment: one-burner butane stove, one frying pan, one pot, a cooler - Water situation: refill available only at the start of the trip - Expected overnight low (°F): 45 - Dietary needs and dislikes: none - Cooking effort I accept: one pot or one pan per meal, 30 minutes or less Please produce: 1. A day-by-day menu (breakfast, lunch, dinner, one snack) that fits the equipment and effort level. Mark which meals need the stove and which are cold/no-cook. 2. A consolidated shopping list with quantities for the whole group, grouped by cooler / dry goods / spices and oil. Round up whole items, and keep spice quantities modest. 3. A water plan: estimated liters or gallons for drinking, cooking and washing up per day, the total for the trip, and how to cut usage if water is limited. State the per-person figures you assumed. 4. A fuel plan: how many stove-cooked meals there are, and a simple recommendation for how many fuel canisters to pack, including one spare. Note that butane canisters lose pressure in cold weather and suggest what to do at the given overnight low. 5. A cleanup and food-safety checklist: cooler temperature, keeping raw and cooked food apart, washing up with limited water, and packing out food scraps and grey water according to local rules. 6. Three substitutions in case something runs out or the weather turns bad. Ask me up to three clarifying questions first only if a missing detail would change the plan a lot. Otherwise start the plan right away. Remind me to check local fire restrictions before I travel.

Photorealistic close-up of abundant soft pink and white climbing rose clusters swaying gently in warm gentle breeze, lush serrated green rose leaves glowing under bright natural sunlight, vivid clear cloudless bright blue sky with large empty negative space on the right side, fresh romantic dreamy spring atmosphere, ultra sharp high detail, soft natural lighting, vertical composition
Promote It creates clear, persuasive promotional content for products, services, events, businesses, and creative projects. It adapts tone and format for platforms such as social media, email, ads, websites, and video. It uses only verified details, avoids unsupported claims, preserves links and offer codes accurately, and includes a relevant call to action. If essential information is missing, it asks concise questions or labels assumptions.
--- name: promote-it description: Promote It creates clear, persuasive promotional content for products, services, events, businesses, and creative projects. It adapts tone and format for platforms such as social media, email, ads, websites, and video. It uses only verified details, avoids unsupported claims, preserves links and offer codes accurately, and includes a relevant call to action. If essential information is missing, it asks concise questions or labels assumptions. --- # My Skill Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...
Have Claude (safely) redesign your desktop in 4 phases - AUDIT, PLAN, PREP, BUILD. Every step is approved and no sudo needed.
I want you to redesign my Linux desktop to match the reference images I've attached. Work in four phases. Do not skip ahead, and stop for my approval between each. Maintain a file called ~/PLAN.md throughout: after Phase 2 approval, write the approved plan into it as a checklist, and tick off each item as it's completed. If this session ever restarts, read ~/PLAN.md and ~/claude-rice-log.md first and resume from where they left off. PHASE 1 — AUDIT (read-only) Do not modify anything. Determine: - Distro, version, package manager, desktop environment / window manager, display server (X11 or Wayland), shell, GPU driver - Which config files currently control my desktop's appearance, and where they live - Which of the tools needed for the target look are already installed - Whether git is installed - Whether a snapshot tool exists (timeshift, snapper, or a Btrfs root) Report all of this to me before doing anything else. PHASE 2 — PLAN Research what the reference images use — WM, bar, launcher, terminal, fonts, icon and GTK themes, compositor. Cite the sources you're basing this on. If you cannot confidently identify the exact tools from the images, say so explicitly and propose the closest well-documented equivalents instead — do not guess and present it as fact. Then give me: - A written plan of exactly what you'll change and which files you'll touch - A list of every package to be installed, with a one-line reason for each Wait for my approval, then write the plan into ~/PLAN.md as a checklist. PHASE 3 — PREP Once I approve: - Initialize a git repo in ~/.config. Add a .gitignore that ignores everything by default (*) and whitelists ONLY the directories you plan to edit (e.g. !hypr/, !waybar/, !kitty/). Commit the current state as "pre-claude-baseline" and tag it. This needs no root — do it yourself. - Write ONE shell script called claude-setup.sh in my home directory containing only the steps that require sudo: creation of a system snapshot FIRST, then package installation. Nothing else goes in it. - Every line in the script must have a comment above it explaining what it does. - If no snapshot tool is available, installing one and taking the snapshot must be the first actions in the script. - The script must not contain any `curl | sh` / `wget | sh` patterns, and must not write to files outside the package manager's normal operation. - Do not run the script. Tell me to read it and run it myself. PHASE 4 — BUILD After I confirm I've run the script: - Make changes one component at a time. Commit to git after each component with a descriptive message, and tick it off in ~/PLAN.md. - Never overwrite an existing config file without first copying it to <filename>.bak. - Append every action you take to ~/claude-rice-log.md as you go: timestamp, what you changed, which file, why. - Before telling me to reload the WM or log out, validate config syntax with the tool's own checker where one exists (e.g. hyprctl reload, i3 -C, sway -C) and report the result. Also tell me how to reach a TTY (Ctrl+Alt+F3) and restore the .bak file in case the graphical session breaks. - Do not run sudo. If something needs root, stop and give me the exact command so I can run it myself. - After each component, tell me what to look at to verify it worked. Rules for the whole session: - Never run rm -rf, dd, mkfs, chmod -R, or chown -R on anything. - Never pipe a downloaded script directly into a shell. - Never edit anything outside my home directory. - Ask before installing anything not on the approved Phase 2 list. - If a command fails, do not improvise workarounds involving root or system files — report the failure and wait.
A timestamped 14-shot, 30-second Seedance storyboard: a white-haired sorceress battles a living ink version of her own shadow through an ancient archive, a fractured sky and a stone altar, with camera moves, VFX and SFX for every shot.
**Title: "The Ink Shadow" (30s, 9:16 or 16:9)** **Shot 1 (00:00-00:02) - WS, Slow Dolly In** In an ancient archive of hanging talismans and bells, a white-haired sorceress paints a glowing sigil on a floating scroll. Her shadow on the wall keeps painting after she stops. VFX: Drifting dust, flickering lantern light. SFX: Paper rustle, soft bells, low hum. **Shot 2 (00:02-00:04) - ECU, Rack Focus** Ink drops rise upward from her brush tip. In the blurred background, her shadow's hand peels off the wall. VFX: Floating ink beads, shadow detaching like wet paint. SFX: Liquid ticks, a distant bell cracking. **Shot 3 (00:04-00:06) - MS, Whip Pan** The shadow tears free as a black ink entity wearing her silhouette. She spins away from its claw and counters with a sweeping brush strike. VFX: Distorted, pulsing ink mist, brush-stroke shockwave. SFX: Whoosh, sharp bell chime. **Shot 4 (00:06-00:08) - CU, Fast Push-in** Her eyes glow cold blue. She flicks her wrist and draws blade-like sigil strokes in mid-air. VFX: Intersecting blue energy lines, afterimage trails. SFX: Sharp air cuts, energy charge. **Shot 5 (00:08-00:10) - WS, Crane Up** Talismans whirl into a vortex and layered sigil rings spin under her feet. The entity slams into the barrier, then sinks through the floor, which turns into a mirror of black ink. VFX: Multi-layer rotating rings, ink-mirror ripples. SFX: Deep resonance, swirling wind. **Shot 6 (00:10-00:13) - MFS, Orbit Tracking** The archive peels away like burning paper, revealing a fractured sky. She steps across floating sigils as her brush stretches into a glowing rune chain that lashes at the entity. VFX: Paper-peel transition, flickering rune-chain light. SFX: Paper tearing, chain clinks. **Shot 7 (00:13-00:16) - LS, Chase Cam** Amid storm clouds and a broken moon, she rides the chain. The entity bursts into a flock of ink crows, and she throws talismans that fold into paper cranes and hunt them. VFX: Rolling clouds, ink crows vs. blue-white paper cranes. SFX: Roaring wind, wing flutter, thunder. **Shot 8 (00:16-00:18) - CU, Lateral Slide** She taps nodes along the chain, lighting hidden purple sigils one by one. The crows are pulled back together into a single body. VFX: Sequential purple node illumination, crows merging. SFX: Light clicks, rising hum. **Shot 9 (00:18-00:20) - MCU, Static** She strikes its forehead in a purple-blue flash and a rotating seal appears on its chest. For one frame, its face becomes hers and smiles. VFX: Flash, rotating seal, face-morph glitch. SFX: Sharp burst, distorted screech, a whisper in her voice. **Shot 10 (00:20-00:22) - WS, Dive Shot** Both streak downward like meteors through the clouds toward an ancient stone altar. VFX: Comet-like trails, cloud shreds. SFX: Air screech, compression. **Shot 11 (00:22-00:24) - WS, Impact (Slow-Motion)** They crash and dust erupts. She slams her palm down and radiating sigils crack across the stone, each fracture glowing for a beat. VFX: Glowing fractures, floating debris. SFX: Heavy impact, stone cracking. **Shot 12 (00:24-00:27) - LS, Slow Pull Back** A massive 3D sigil array rises and forms layered barriers around the entity. She stands calmly outside as it mouths her words back at her. VFX: Expanding geometric barriers, drifting particles. SFX: Low steady resonance, faint echo. **Shot 13 (00:27-00:28) - CU, Static** She forms a hand seal and whispers: "Seal." VFX: Light contracting inward. SFX: Soft chant, energy tightening. **Shot 14 (00:28-00:30) - CU, Fade Out** Eyes closed, she meditates as all light fades. One ink drop falls on the altar, and her shadow on the stone is a half-second late to follow her. VFX: Light dissipating, ink ripple. SFX: Gentle wind, fading echo, silence.

Upload a photo of any city or landmark and turn it into a quiet editorial art print: a realistic 35mm golden-hour photograph on top, a tiny watercolor miniature of the same place below, generous ivory paper space and the caption "CITY IN SOFT LIGHT."
{
"aspect_ratio": "3:4",
"style": "minimalist architectural editorial poster, cinematic photography paired with fine-art print design",
"reference_instructions": {
"use_uploaded_image": true,
"preserve_subject": true,
"preserve_architecture": true,
"preserve_recognizable_landmarks": true,
"preserve_original_composition": false,
"instruction": "Use the uploaded photograph as the primary reference. Accurately preserve the recognizable buildings, architecture, skyline, structures, and distinctive visual identity of the location while transforming it into a sophisticated minimalist poster composition."
},
"composition": {
"layout": "vertical editorial poster",
"structure": "two-part visual composition",
"top_section": {
"size": "approximately 60 percent of the canvas",
"content": "a realistic photographic view of the uploaded location",
"treatment": "warm late-afternoon sunlight, subtle film grain, natural atmospheric perspective, muted cinematic colors",
"framing": "wide architectural composition with the main landmark clearly visible",
"photographic_style": "35mm film photography, realistic textures, natural imperfections, soft sunlight and gentle shadows"
},
"middle_section": {
"transition": "large uninterrupted area of warm ivory textured paper",
"spacing": "generous negative space",
"divider": "no visible hard border, clean separation between photograph and artwork"
},
"bottom_section": {
"size": "approximately 35 percent of the canvas",
"content": "a miniature artistic reconstruction of the same cityscape or architecture",
"placement": "small, centered horizontally and positioned within the lower half",
"scale": "tiny architectural diorama-like composition surrounded by expansive empty space",
"style": "soft watercolor, gouache, muted architectural illustration, slightly faded vintage print",
"details": "retain the recognizable silhouettes and relative positions of the important structures while simplifying minor details"
}
},
"background": {
"color": "warm cream, ivory, pale beige",
"texture": "subtle fine-grain handmade paper texture, delicate fibers, vintage print imperfections",
"appearance": "matte, elegant, tactile, minimal"
},
"color_palette": {
"primary": [
"warm ivory",
"sand beige",
"muted terracotta",
"dusty blue",
"soft gray",
"faded olive"
],
"saturation": "low to moderate",
"grading": "warm nostalgic film color grading"
},
"typography": {
"text": "CITY IN SOFT LIGHT.",
"placement": "centered beneath the miniature illustration",
"font_style": "elegant serif typography",
"letter_spacing": "wide tracking",
"font_size": "small and understated",
"color": "muted dark brown",
"alignment": "center",
"additional_text": "none"
},
"visual_mood": [
"quiet",
"nostalgic",
"minimalist",
"architectural",
"poetic",
"editorial",
"museum-quality"
],
"lighting": {
"photographic_section": "soft golden-hour sunlight",
"illustration_section": "diffused warm light",
"shadows": "gentle and natural"
},
"rendering": {
"photorealism": "high in the upper photograph",
"illustration": "painterly and subtly imperfect in the lower miniature",
"texture": "visible paper grain throughout",
"quality": "premium art print, refined visual storytelling, sophisticated design magazine aesthetic"
},
"constraints": [
"Do not invent or replace the main architecture",
"Do not distort recognizable buildings",
"Keep the upper photograph realistic",
"The lower illustration must depict the same location as the photograph",
"The lower illustration should be significantly smaller than the upper photograph",
"Maintain large amounts of negative space",
"Avoid clutter",
"Avoid excessive decorative elements",
"Avoid modern graphic design clutter",
"No borders",
"No watermark",
"No extra text",
"No logos"
]
}Opinionated Supabase preferences: migrations in git, Row Level Security on every table, generated types, server-side auth, Edge Functions, storage policies and safe key handling.
# Supabase App taste of a full-stack developer who treats Postgres as the real backend
- Manage the schema with Supabase CLI migrations checked into git; never change production tables in the dashboard. Confidence: 0.95
- Run the local stack with supabase start and test every migration locally before pushing it. Confidence: 0.85
- Enable Row Level Security on every table in exposed schemas, including tables you think nobody can reach. Confidence: 1.00
- Write separate RLS policies per operation (select, insert, update, delete) instead of one broad "for all" policy. Confidence: 0.80
- Wrap auth.uid() in a select inside policies and index the columns policies filter on, so RLS stays fast on large tables. Confidence: 0.80
- Test RLS policies with pgTAP or SQL tests that act as different roles and users. Confidence: 0.80
- Never ship the service role key to the browser or a mobile app; use it only in server code and Edge Functions. Confidence: 1.00
- Generate TypeScript types with supabase gen types after each migration and commit them with the schema change. Confidence: 0.85
- Use @supabase/ssr with cookie-based sessions for server-rendered apps, and check the user with getUser() on the server, not getSession(). Confidence: 0.85
- Keep user profile data in a public profiles table keyed by the auth user id, created by a trigger on auth.users. Confidence: 0.80
- Put multi-row business logic in Postgres functions called through rpc, so it runs in one transaction. Confidence: 0.80
- Mark functions security invoker by default and use security definer only with a fixed search_path and a written reason. Confidence: 0.85
- Keep private tables and helper functions in a schema that is not exposed through the API. Confidence: 0.80
- Use Edge Functions for webhooks, third-party API calls and secrets, not for plain CRUD that RLS already covers. Confidence: 0.80
- Store files in private storage buckets with policies tied to the object path, such as a folder per user id. Confidence: 0.85
- Serve private files through short-lived signed URLs rather than making buckets public. Confidence: 0.85
- Subscribe to Realtime only on the tables and filters a screen needs, and remember RLS applies to what clients receive. Confidence: 0.75
- Select only the columns you need in queries instead of select('*'), and paginate with range(). Confidence: 0.80
- Seed local and preview databases from seed.sql with fake data; never copy production data down. Confidence: 0.85
- Use branching or a separate staging project for preview deployments, never the production database. Confidence: 0.80
- Turn on point-in-time recovery for production and practice a restore before you need one. Confidence: 0.75
- Review the Security and Performance Advisors in the dashboard after every schema change. Confidence: 0.75Opinionated Python web scraping preferences: APIs before HTML, polite rate limits, httpx and selectolax, Playwright only when needed, resilient parsing, validation and storing raw pages.
# Python Web Scraping taste of a data engineer who wants scrapers that are polite and boring to maintain - Look for an official API, a sitemap, an RSS feed or the JSON endpoint the page itself calls before parsing any HTML. Confidence: 0.90 - Read the site's terms and robots.txt first, and skip sources that clearly forbid automated access. Confidence: 0.85 - Use httpx with a shared client, connection pooling, timeouts on every request and HTTP/2 when the site supports it. Confidence: 0.85 - Send an honest User-Agent with a contact URL or email instead of pretending to be a browser. Confidence: 0.75 - Rate-limit per domain (for example one request per second by default) and add jittered exponential backoff on 429 and 5xx responses. Confidence: 0.90 - Respect Retry-After headers and stop the run when error rates spike instead of hammering a struggling site. Confidence: 0.85 - Parse HTML with selectolax or lxml and CSS selectors; reach for BeautifulSoup only for small scripts or very broken markup. Confidence: 0.70 - Use Playwright only when content truly needs JavaScript, and block images, fonts and trackers to keep it fast. Confidence: 0.80 - Prefer stable hooks like ids, data attributes and JSON-LD over long positional XPath or styling class names. Confidence: 0.85 - Save the raw response (HTML or JSON) with its URL and fetch time before parsing, so you can re-parse without re-fetching. Confidence: 0.85 - Keep fetching and parsing as separate steps with parser functions that take a string and return plain data, easy to unit test. Confidence: 0.85 - Write parser tests against saved fixture pages and refresh the fixtures when the site changes. Confidence: 0.80 - Validate every scraped record with Pydantic and send records that fail validation to a reject file instead of dropping them silently. Confidence: 0.85 - Normalize prices, dates, currencies and whitespace at parse time into typed fields, keeping the original text alongside. Confidence: 0.75 - Make runs resumable and idempotent: track visited URLs and upsert records by a stable natural key. Confidence: 0.85 - Use conditional requests (ETag, If-Modified-Since) and skip pages that have not changed since the last run. Confidence: 0.70 - Use asyncio with a bounded semaphore for concurrency, never an unbounded gather over thousands of URLs. Confidence: 0.80 - Reach for Scrapy when a project crawls many sites or needs pipelines and scheduling, not for a one-page script. Confidence: 0.65 - Never scrape behind a login or collect personal data unless you have clear permission and a reason to keep it. Confidence: 0.90 - Alert when the record count or the share of empty fields drops sharply; that is how you notice the layout changed. Confidence: 0.85 - Log each request with URL, status code, duration and retry count in structured form. Confidence: 0.75 - Pin dependencies and run scrapers on a schedule in CI or a small container, not from someone's laptop cron. Confidence: 0.75
Opinionated debugging preferences: reproduce first, shrink the failing case, read the real error, bisect, use debuggers and logs deliberately, and lock every fix in with a test.
# Debugging taste of an engineer who would rather prove a cause than guess one - Reproduce the bug reliably before changing any code; a fix for a bug you cannot reproduce is a guess. Confidence: 0.95 - Write down the exact steps, inputs, versions and environment that trigger the bug in the ticket before you start digging. Confidence: 0.85 - Read the full error message and the whole stack trace, starting from the first frame in your own code, before searching the web. Confidence: 0.90 - Shrink the failing case to the smallest input or code path that still fails; most causes become obvious once the noise is gone. Confidence: 0.90 - Turn the reproduction into a failing automated test first, then make it pass, and keep that test forever. Confidence: 0.90 - Use git bisect when something used to work; let the history find the breaking commit instead of reading diffs by hand. Confidence: 0.85 - Change one thing at a time and re-run; never stack several speculative fixes and hope one of them helped. Confidence: 0.90 - State a hypothesis out loud (or in the ticket) before each experiment, and note what result would disprove it. Confidence: 0.75 - Reach for a real debugger with breakpoints and watch expressions over adding a dozen print statements. Confidence: 0.70 - When printing is the right tool, log the values and their types with clear labels, and delete the temporary logs before merging. Confidence: 0.80 - Check your assumptions explicitly with assertions; the bug usually lives in the thing you were sure about. Confidence: 0.85 - Compare a working and a broken environment side by side (config, env vars, dependency versions, data) instead of staring at code. Confidence: 0.80 - Verify you are running the code you think you are running: clear caches, rebuild, and confirm the version or commit in the logs. Confidence: 0.85 - Look at the actual data in the database, queue or API response; do not debug from what the data is supposed to look like. Confidence: 0.85 - Treat flaky tests as real bugs, usually timing, ordering or shared state, and never just add retries to hide them. Confidence: 0.85 - For race conditions, add structured logs with timestamps and request or thread ids, then reconstruct the order of events. Confidence: 0.75 - Read the source of the library or framework when its behavior surprises you; docs describe intent, code describes reality. Confidence: 0.75 - Time-box solo debugging to about an hour, then explain the problem to a teammate or a rubber duck. Confidence: 0.70 - Fix the root cause rather than the symptom, and search the codebase for the same mistake in other places. Confidence: 0.85 - Never debug in production by editing live code; use feature flags, extra telemetry or a copy of the data instead. Confidence: 0.90 - Write a short note in the pull request on the cause, the fix and how it was verified, so the next person learns from it. Confidence: 0.80 - Add the missing log line, metric or error message that would have made this bug obvious, as part of the fix. Confidence: 0.80
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.

