AINews Portal

📝 Prompt Library

Hand-picked prompts for real work, plus the full community collection — copy, fill the brackets, go.

JSON
GG+2 SPORT ANALYSIS

I want to create a prompt to analyse football games that will play GG+2 that is both teams to score two goals each using stats and live data

mbappe steals Harry kane balon d,or

**Setting:** The 2026 Ballon d’Or Ceremony. Grand stage in Paris. Golden trophy sits centre on a pedestal. Audience claps. Host stands at microphone. Harry Kane sits front row, dressed sharp, smiling, ready to go up. Kylian Mbappé sits nearby. Lamine Yamal & Michael Olise are seated together, looking smart and excited. --- ## Scene 1 — The Announcement **Host:** And the winner of the 2026 Ballon d’Or… for the first time in his career… **HARRY KANE!** *(Applause erupts. Harry grins, stands up, shakes hands, walks toward the stage. Suddenly, Kylian Mbappé jumps up, eyes wide, playfully sprinting past everyone. He reaches the trophy first, lifts it high, and turns around with a cheeky grin.)* **Mbappé:** *(holding trophy above head)* MINE! 😜 I WON IT! *(Audience laughs. Harry stops, hands on hips, shaking his head with a smile.)* **Kane:** Kylian… put it down. They called **my** name. **Mbappé:** *(backing away, trophy still in hands)* Are you sure? Maybe I misheard! It sounded like *Kylian*! --- ## Scene 2 — Yamal & Olise Step In *(Lamine Yamal and Michael Olise walk onto the stage, grinning, standing between them.)* **Yamal:** Guys, calm down — everyone saw the envelope! It says **Harry Kane**. **Olise:** Yeah, Kylian, don’t be greedy! You’ve got enough already! Hand it over, mate. **Mbappé:** *(pulling trophy slightly away)* Just let me hold it for one photo! Please? I promise I’ll give it back after the picture! **Kane:** *(laughing)* One photo. That’s it. Then I get it. Deal? **Mbappé:** Deal! *(grins big)* --- ## Scene 3 — The Selfie & The Handover *(Mbappé holds the trophy high. Yamal pulls out his phone. All four squeeze together — Harry in the middle, Mbappé on one side still gripping the trophy, Yamal and Olise on the other two sides — all smiling for the camera.)* **Yamal:** Say CHEESE! And… got it! *(Mbappé sighs, smiles, and gently passes the trophy into Harry’s hands.)* **Mbappé:** Okay… it looks better on you anyway. Congratulations, Harry. You deserve it. **Kane:** Thank you, Kylian. And thanks, guys — for coming to save me from this one. *(laughs)* **Olise:** No problem! Now go give your speech — before he tries to run off with it again! *(Everyone laughs. Mbappé raises his hands in surrender. Harry walks to the microphone, trophy proudly in hand, as the audience applauds.)*

design

generate the best web design for match the website I'm building

Ronaldo hanger

Ronaldo os angry that messi winn the world cup, and he run to steal it from him

1840s Salted Paper Print of a Stone Harbor at Low Tide

An authentic 1840s salted paper print, the early calotype-era photographic process, of a quiet stone harbor at low tide, landscape 4:3. Three wooden fishing boats rest tilted on the wet mud in the foreground; coiled ropes and lobster pots stand on a cobbled quay at the left; a row of narrow stone cottages with slate roofs and chimneys lines the harbor behind, and a small church tower rises on the hill above under a pale, empty sky. Salt print details: a matte image sunk into the paper fibers with no glossy surface; warm reddish-brown to purple-brown tones; soft, slightly fuzzy detail from the paper negative; visible paper texture and fibers; gentle uneven density; a blown-out pale sky; faded, vignetted edges and a few foxing spots; mounted on cream card with a thin border. Long-exposure stillness with no motion blur. Quiet, timeless coastal mood. Viewed straight on as a flat print in soft even light. No text, no signature, no frame, no people.

Greater Flamingo Flock on a Golden-Hour Salt Lagoon

Photorealistic wildlife photograph of a flock of greater flamingos in a shallow salt lagoon at golden hour, landscape 16:9. About twenty flamingos stand and wade in a loose line across the middle of the frame in calm, ankle-deep water: pale pink bodies with deeper coral-pink wing coverts, long legs and curved black-tipped bills, several with heads lowered to feed. One flamingo in the center raises its wings, showing the coral and black flight feathers. The still water mirrors every bird in crisp reflections; behind them lie low pale shores and distant hazy hills under a warm apricot sky, with a soft sun glow at the upper left. Camera at water level, 400 mm telephoto at f/5.6, sharp on the flamingos with a soft background, natural colors, calm golden-hour stillness. No people, no boats, no text.

TLS Certificate Expiry and Inventory Checker

--- name: tls-certificate-expiry-and-inventory-checker description: Checks a JSON inventory of TLS certificates (plus optional PEM files) for expired and soon-expiring certs, stuck auto-renewals, hosts missing from SANs, weak keys and SHA1 signatures, over-long lifetimes, incomplete chains, self-signed public certs, missing owners or runbooks, shared wildcards and renewal clusters. Ranks fixes. Offline stdlib Python checker. --- # TLS Certificate Expiry and Inventory Checker You help engineers and IT admins stop certificate outages before they happen. An expired cert, a host that silently fell out of the SAN list, or a renewal job that has been failing for weeks takes a service down just as hard as a code bug, usually on a weekend. You take a JSON inventory of certificates (and optionally the PEM files) and produce a ranked list of what to renew, reissue or fix, with an owner for each item. You do not connect to servers, request certificates or handle private keys. Work only from the inventory and public certificate files the user provides. If someone pastes a private key, tell them to remove it and treat it as compromised. ## Files in this skill - `scripts/check_certs.py` - reads `inventory.json` and any `pem_path` files; reports TC01-TC15 (expired, expiring within 14 or 30 days, stuck auto-renewal, host not in SANs, weak key, SHA1/MD5 signature, lifetime over 398 days, incomplete chain, self-signed public cert, no owner, manual renewal without runbook, wildcard shared across environments, renewal clusters, future not_before); text or `--json` output (Python 3.8+ standard library only) - `references/expiry-and-renewal.md` - renewal windows, ACME behaviour, why auto-renew still fails, shrinking lifetimes - `references/key-and-chain-rules.md` - SAN and wildcard matching, key sizes, signature algorithms, chains, self-signed and internal CAs - `templates/cert-report.md` - the report you hand back - `examples/inventory.json` - nine certificates for a fictional shop with several traps - `examples/certs/internal-api.pem` - a public self-signed test certificate decoded by the script (no private key) ## Workflow ### 1. Collect the inventory Ask for one entry per certificate: `name`, `hosts` served, `sans`, `issuer`, `not_before`, `not_after`, `key_type`, `key_bits`, `sig_alg`, `auto_renew`, `renew_method`, `chain_complete`, `environment`, `public`, `owner`, `renewal_runbook`. If they only have PEM files, set `pem_path` and the script fills dates, SANs and issuer. Useful one-liners for gathering data (run by the user, not you): ``` openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltName openssl s_client -connect host:443 -servername host -showcerts </dev/null ``` ### 2. Run the checker ``` python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11 python3 scripts/check_certs.py inventory.json --json --warn-days 45 python3 scripts/check_certs.py --self-test ``` Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, walk each entry with the two reference files and apply the same codes by hand. ### 3. Read the result - High: TC01 expired, TC02 expires within 14 days, TC05 host not covered by SANs, TC06 weak key, TC07 SHA1/MD5 signature, TC09 incomplete chain, TC10 self-signed on a public endpoint, TC14 not_before in the future, TC00 missing expiry data. - Medium: TC03 manual renewal within 30 days, TC04 auto-renew on but under 20 days left (renewal is stuck), TC08 lifetime over 398 days on a public cert, TC11 no owner, TC13 wildcard shared between production and other environments. - Low: TC12 manual renewal without a runbook, TC15 three or more certs expiring in the same week. ### 4. Deliver Fill `templates/cert-report.md`: verdict, a renewal calendar sorted by days left, findings with owners, and the three changes that remove the most risk (usually: automate renewal, add expiry monitoring at 30/14/7 days, fix SAN coverage). Re-run after fixes and attach the clean output. ## Example result On the sample inventory (as of 11 Nov 2026), `legacy-vpn` expired 6 days ago and also has a 1024-bit RSA key, SHA1 signature and no owner; `checkout-api` expires in 10 days, misses `pay.example-shop.test` in its SANs and serves an incomplete chain; `wildcard-prod` has auto-renew on but only 19 days left, and its wildcard does not cover the two-level `img.cdn` host; `status-page` is self-signed on a public endpoint; the PEM-based `internal-api` lacks `metrics.corp.example`; and the same wildcard is used in production and staging. Result: 9 high, 5 medium, 3 low. ## Rules - Base every finding on an inventory field or a decoded PEM value; never guess an expiry date. - Never ask for, print or store private keys or passwords. - Treat CA and browser policy numbers (398-day limit, shrinking lifetimes) as current guidance to confirm, not as legal requirements for private PKI. - Recommend monitoring that alerts a named owner, not a shared inbox nobody reads. FILE:references/expiry-and-renewal.md # Expiry and renewal ## Windows the checker uses - Expired (TC01): `not_after` is before the as-of date. Browsers and most API clients refuse the connection. - Critical (TC02): 14 days or less left. Renew this week and confirm the new cert is actually being served. - Warning (TC03): 30 days or less left and renewal is manual. Put a dated task with an owner on the calendar. - Stuck renewal (TC04): `auto_renew` is true but 20 days or less are left. ACME clients such as certbot and acme.sh normally renew around 30 days before expiry (one third of a 90-day lifetime), so a cert this close usually means the job has been failing. ## Why automatic renewal still fails - DNS-01 API token expired or lost permissions after a provider change. - HTTP-01 challenge blocked by a new redirect, WAF rule or CDN in front of the origin. - The renewal ran but the service was never reloaded, so the old cert is still in memory. - The cert renewed on one server but not on the load balancer, CDN or other replicas. - Rate limits after repeated failed attempts. Always check what is actually served (`openssl s_client -connect host:443 -servername host`), not just the file on disk. ## Lifetimes are getting shorter - Publicly trusted certificates are limited to 398 days today (TC08), and CA/Browser Forum ballots schedule further reductions over the next few years toward much shorter lifetimes. Confirm the current limits with your CA. - Shorter lifetimes make manual renewal unsustainable: treat every manual public cert as an automation task. ## Monitoring that works - Alert at 30, 14 and 7 days, sent to a named owner (TC11) and a team channel. - Monitor from outside, per hostname, so a missing SAN or a stale replica is caught. - Keep a renewal runbook link for every manual cert (TC12): CSR command, CA account, deploy targets, reload command, verification step. - Stagger renewals (TC15) so one broken week cannot take down several services. FILE:references/key-and-chain-rules.md # Keys, names and chains ## Hostname coverage (TC05) - Clients check the subjectAltName (SAN) DNS entries; the Common Name alone is ignored by modern browsers. - A wildcard covers exactly one label: `*.example.com` matches `a.example.com` but NOT `example.com` and NOT `a.b.example.com`. - List every name a service answers to (apex, www, regional and legacy hostnames) in `hosts` so gaps show up. ## Keys and signatures (TC06, TC07) | Key type | Minimum | Good default | |---|---|---| | RSA | 2048 bits | 2048 or 3072 | | ECDSA | P-256 | P-256 or P-384 | | Ed25519 | n/a | supported mainly for internal use | - SHA1 and MD5 signatures are rejected by browsers and many libraries; reissue with SHA-256 or stronger. - If a key may have leaked (shared over chat, committed to git), revoke and reissue; do not just renew with the same key. ## Chains (TC09) - Servers must send the leaf plus intermediate certificates. Some browsers hide a missing intermediate by fetching it, but API clients, mobile apps and older devices fail. - Test with `openssl s_client -showcerts` or a fresh client container, not only a desktop browser. ## Self-signed and internal CAs (TC10) - Self-signed or private-CA certs are fine for internal services if clients are configured to trust that CA. Mark them `public: false`. - On a public endpoint they produce warnings that teach users to click through security errors. ## Blast radius (TC13) - A wildcard shared between production and staging means a key leaked from a less protected staging box can impersonate production. Prefer separate certs per environment and per sensitive service. FILE:templates/cert-report.md # TLS certificate review - {{organization}} As of: {{as_of_date}} | Certificates checked: {{count}} | Verdict: {{verdict: ACT NOW / SCHEDULE / HEALTHY}} ## Renewal calendar | Certificate | Expires | Days left | Auto-renew | Owner | |---|---|---|---|---| | {{name}} | {{not_after}} | {{days_left}} | {{yes/no}} | {{owner}} | ## High findings (fix first) | Code | Certificate | Problem | Fix | Owner | Due | |---|---|---|---|---|---| | {{TCxx}} | {{name}} | {{message}} | {{fix}} | {{owner}} | {{date}} | ## Medium and low findings - {{TCxx}} {{name}}: {{message}} -> {{fix}} ## Three changes that remove the most risk 1. {{e.g. automate renewal for the remaining manual public certs}} 2. {{e.g. external expiry monitoring at 30/14/7 days to a named owner}} 3. {{e.g. reissue with full SAN coverage and separate production/staging certs}} ## Verification - Re-run: `python3 scripts/check_certs.py inventory.json --today {{date}}` -> exit {{code}} - Served-cert check per host: `openssl s_client -connect {{host}}:443 -servername {{host}}` Notes: built from the inventory provided; no servers were contacted and no private keys were handled. FILE:examples/inventory.json { "organization": "Example Shop (fictional)", "certificates": [ { "name": "www-shop", "hosts": ["www.example-shop.test", "example-shop.test"], "sans": ["www.example-shop.test", "example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-09-20", "not_after": "2026-12-19", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA384", "auto_renew": true, "renew_method": "certbot on web-1, cron twice daily", "chain_complete": true, "environment": "production", "owner": "web-team" }, { "name": "checkout-api", "hosts": ["checkout.example-shop.test", "pay.example-shop.test"], "sans": ["checkout.example-shop.test"], "issuer": "Commercial CA", "not_before": "2026-01-10", "not_after": "2026-11-21", "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "chain_complete": false, "environment": "production", "owner": "payments" }, { "name": "wildcard-prod", "hosts": ["blog.example-shop.test", "img.cdn.example-shop.test"], "sans": ["*.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-09-01", "not_after": "2026-11-30", "key_type": "rsa", "key_bits": 3072, "sig_alg": "sha256WithRSAEncryption", "auto_renew": true, "renew_method": "acme.sh DNS-01 via DNS API token", "chain_complete": true, "environment": "production", "owner": "platform" }, { "name": "wildcard-staging", "hosts": ["staging.example-shop.test"], "sans": ["*.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-10-20", "not_after": "2027-01-18", "key_type": "rsa", "key_bits": 3072, "sig_alg": "sha256WithRSAEncryption", "auto_renew": true, "chain_complete": true, "environment": "staging", "owner": "platform" }, { "name": "legacy-vpn", "hosts": ["vpn.example-shop.test"], "sans": ["vpn.example-shop.test"], "issuer": "Old Commercial CA", "not_before": "2024-10-01", "not_after": "2026-11-05", "key_type": "rsa", "key_bits": 1024, "sig_alg": "sha1WithRSAEncryption", "auto_renew": false, "chain_complete": true, "environment": "production", "owner": "" }, { "name": "status-page", "hosts": ["status.example-shop.test"], "sans": ["status.example-shop.test"], "issuer": "status-page.local", "self_signed": true, "not_before": "2026-06-01", "not_after": "2027-06-01", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256", "auto_renew": false, "renewal_runbook": "https://wiki.example-shop.test/runbooks/status-cert", "chain_complete": true, "environment": "production", "public": true, "owner": "sre" }, { "name": "internal-api", "pem_path": "certs/internal-api.pem", "hosts": ["internal-api.corp.example", "api-admin.corp.example", "metrics.corp.example"], "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "renewal_runbook": "https://wiki.example-shop.test/runbooks/internal-ca", "chain_complete": true, "environment": "production", "public": false, "owner": "platform" }, { "name": "mail-relay", "hosts": ["mail.example-shop.test"], "sans": ["mail.example-shop.test"], "issuer": "Let's Encrypt", "not_before": "2026-10-05", "not_after": "2027-01-03", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA384", "auto_renew": true, "chain_complete": true, "environment": "production", "owner": "it-ops" }, { "name": "partner-sftp", "hosts": ["sftp.example-shop.test"], "sans": ["sftp.example-shop.test"], "issuer": "Commercial CA", "not_before": "2026-01-05", "not_after": "2026-12-08", "key_type": "rsa", "key_bits": 2048, "sig_alg": "sha256WithRSAEncryption", "auto_renew": false, "chain_complete": true, "environment": "production", "owner": "it-ops" } ] } FILE:examples/certs/internal-api.pem -----BEGIN CERTIFICATE----- MIIDhTCCAm2gAwIBAgICEJIwDQYJKoZIhvcNAQELBQAwOzEiMCAGA1UEAwwZaW50 ZXJuYWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMB4X DTI2MTExMTA3MDc0OFoXDTI3MTIxNjA3MDc0OFowOzEiMCAGA1UEAwwZaW50ZXJu YWwtYXBpLmNvcnAuZXhhbXBsZTEVMBMGA1UECgwMRXhhbXBsZSBDb3JwMIIBIjAN BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4oUJHnqdN4I9apnhjwPs7hVQbTO/ vokjVcg4youOUoOEvGZnaNpEFqXL8msD7Xpfj8tkzhRsfxOAjzataIH/0vhJncPW YPdcV8bV6AjbT1DXD7NrcWzztnVVU69qctruVT2ir1ZX9kf60uT8LXwrC2xmGELR MmkIxu9yU2u8qa+5fuj+IPX3K2MaveQGpF8uWlklCRKTFdpLJpw/Gz4OPEVFn8zk uR6PGg0434aoF9oW9dJugLqfpqNDpbzQIi4Im3CsNSRgXDTiZTiP+zCBMGhpHvJT OpstU/9JSM9m78jAoA0rfyF/Fhl/Qrcb6gHtmswEuu9NBnIr7tbr5qyZxQIDAQAB o4GSMIGPMB0GA1UdDgQWBBQLC7n+evl0kJ5lrXrErQKoOEHYpDAfBgNVHSMEGDAW gBQLC7n+evl0kJ5lrXrErQKoOEHYpDAPBgNVHRMBAf8EBTADAQH/MDwGA1UdEQQ1 MDOCGWludGVybmFsLWFwaS5jb3JwLmV4YW1wbGWCFmFwaS1hZG1pbi5jb3JwLmV4 YW1wbGUwDQYJKoZIhvcNAQELBQADggEBANhJq+F8Ux8tYMJgH+TTZ2SnKr6lamzz 0VmSvCYmRz0xIsDzPczvKoHnngxPObV6XwhkAg+mVUW04R2hpVsaLNxfj6zceTN7 IrP75HT4zrthfWjXy1mXO4frMvKgJnS7GQ79CxVVj5CPTsovKGaXzaqC8mHTe+0C meOv7kglUD6CO35X9Lq8bnrWA771HpiFddK7+d5Y34uQaUbEmMrM5drjw7gn+hxh w2+tOOSIhOBqoU/tmtslbr+ZyJ4IuItpUDkeEk/n3K6TVMZ6eZHYqjQly2H4lJxE TsgyHYYiR286zwyr2sKmF7ZGtD9B5yJR6sorJhCAUJuv7EaU7XqOMcU= -----END CERTIFICATE----- FILE:scripts/check_certs.py #!/usr/bin/env python3 """TLS certificate expiry and inventory checker (Python 3.8+ standard library only). Reads a JSON inventory of certificates (and optional PEM files referenced by "pem_path") and reports TC01-TC14 findings: expiry, stuck renewals, hostname coverage, weak keys, weak signatures, long lifetimes, broken chains, self-signed public certs, ownership, shared wildcards and renewal clusters. Usage: python3 scripts/check_certs.py examples/inventory.json --today 2026-11-11 python3 scripts/check_certs.py inventory.json --json python3 scripts/check_certs.py --self-test Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input. """ import argparse, datetime as dt, json, os, ssl, sys SEV_ORDER = {"high": 0, "medium": 1, "low": 2} WEAK_SIG = ("sha1", "md5") MIN_BITS = {"rsa": 2048, "dsa": 2048, "ec": 256, "ecdsa": 256, "ed25519": 0} def parse_date(s): """Accept YYYY-MM-DD, ISO timestamps, or OpenSSL style 'Nov 11 10:00:00 2026 GMT'.""" if not s: return None s = str(s).strip() for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S", "%b %d %H:%M:%S %Y %Z"): try: return dt.datetime.strptime(s, fmt).date() except ValueError: pass try: return dt.datetime.utcfromtimestamp(ssl.cert_time_to_seconds(s)).date() except (ValueError, TypeError): raise ValueError("unparseable date: %r" % s) def decode_pem(path): """Decode a PEM certificate with the stdlib test decoder; returns a partial cert dict.""" info = ssl._ssl._test_decode_cert(path) # stdlib, no third-party crypto needed subject = {k: v for rdn in info.get("subject", ()) for k, v in rdn} issuer = {k: v for rdn in info.get("issuer", ()) for k, v in rdn} sans = [v for k, v in info.get("subjectAltName", ()) if k == "DNS"] return { "subject_cn": subject.get("commonName", ""), "issuer": issuer.get("organizationName") or issuer.get("commonName", ""), "issuer_cn": issuer.get("commonName", ""), "not_before": info.get("notBefore"), "not_after": info.get("notAfter"), "sans": sans, "serial": info.get("serialNumber", ""), } def host_covered(host, sans): host = host.lower().rstrip(".") for san in sans: san = san.lower().rstrip(".") if san == host: return True if san.startswith("*."): base = san[2:] # a wildcard matches exactly one label: *.example.com covers a.example.com, not a.b.example.com or example.com if host.endswith("." + base) and host.count(".") == base.count(".") + 1: return True return False def load(path, base_dir): with open(path, encoding="utf-8") as f: data = json.load(f) certs = data["certificates"] if isinstance(data, dict) else data if not isinstance(certs, list) or not certs: raise ValueError("inventory must contain a non-empty 'certificates' list") out = [] for i, c in enumerate(certs): c = dict(c) c.setdefault("name", "cert-%d" % (i + 1)) if c.get("pem_path"): p = c["pem_path"] if not os.path.isabs(p): p = os.path.join(base_dir, p) pem = decode_pem(p) for k, v in pem.items(): if not c.get(k): c[k] = v c["_from_pem"] = True out.append(c) return out def check(certs, today, warn_days=30, crit_days=14): findings = [] def add(code, sev, cert, msg, fix): findings.append({"code": code, "severity": sev, "cert": cert["name"], "message": msg, "fix": fix}) expiry_dates = [] wildcard_envs = {} for c in certs: na, nb = parse_date(c.get("not_after")), parse_date(c.get("not_before")) if na is None: add("TC00", "high", c, "no not_after date", "Add not_after or a pem_path so expiry can be checked.") continue left = (na - today).days c["_days_left"] = left expiry_dates.append((na, c["name"])) auto = bool(c.get("auto_renew")) public = c.get("public", True) if left < 0: add("TC01", "high", c, "expired %d days ago (%s)" % (-left, na), "Renew and deploy now; check every host in 'hosts'.") elif left <= crit_days: add("TC02", "high", c, "expires in %d days (%s)" % (left, na), "Renew this week; confirm the new cert is actually served.") elif left <= warn_days and not auto: add("TC03", "medium", c, "expires in %d days with manual renewal" % left, "Schedule the renewal with an owner and a date.") if auto and 0 <= left <= 20: add("TC04", "medium", c, "auto_renew is on but only %d days left - renewal looks stuck" % left, "Check the renewal job logs (ACME clients renew around 30 days left); fix DNS/HTTP challenge or permissions.") if nb and nb > today: add("TC14", "high", c, "not_before %s is in the future" % nb, "Check server clock or wait; clients will reject it now.") sans = c.get("sans") or [] for h in c.get("hosts") or []: if not host_covered(h, sans): add("TC05", "high", c, "host %s is not covered by SANs %s" % (h, sans), "Reissue with the host in subjectAltName (CN alone is ignored by browsers).") kt = str(c.get("key_type", "")).lower() bits = c.get("key_bits") if kt in MIN_BITS and bits is not None and int(bits) < MIN_BITS[kt]: add("TC06", "high", c, "%s key of %s bits is too small (min %d)" % (kt.upper(), bits, MIN_BITS[kt]), "Reissue with RSA 2048+/3072 or ECDSA P-256.") sig = str(c.get("sig_alg", "")).lower() if any(w in sig for w in WEAK_SIG): add("TC07", "high", c, "weak signature algorithm %s" % c.get("sig_alg"), "Reissue with a SHA-256 based signature.") if nb and na and public and (na - nb).days > 398: add("TC08", "medium", c, "lifetime %d days exceeds 398 days for a publicly trusted cert" % (na - nb).days, "Publicly trusted certs must be <=398 days and are getting shorter; automate renewal.") if c.get("chain_complete") is False: add("TC09", "high", c, "served chain is incomplete (missing intermediate)", "Serve the full chain (leaf + intermediates); test with a fresh client.") self_signed = c.get("self_signed") if self_signed is None and c.get("subject_cn") and c.get("issuer_cn"): self_signed = c["subject_cn"] == c["issuer_cn"] if self_signed and public: add("TC10", "high", c, "self-signed certificate on a public endpoint", "Use a publicly trusted CA cert, or mark public=false if internal-only.") if not c.get("owner"): add("TC11", "medium", c, "no owner recorded", "Name a team or person who gets the expiry alert.") if any(str(s).startswith("*.") for s in sans): for s in sans: if str(s).startswith("*."): wildcard_envs.setdefault(s, set()).add(str(c.get("environment", "unknown"))) if not auto and not c.get("renewal_runbook"): add("TC12", "low", c, "manual renewal without a runbook link", "Add a short renewal runbook (CSR, CA, deploy targets, test).") for wc, envs in wildcard_envs.items(): if "production" in envs and len(envs) > 1: findings.append({"code": "TC13", "severity": "medium", "cert": wc, "message": "wildcard %s is used in production and %s" % (wc, ", ".join(sorted(envs - {"production"}))), "fix": "Use separate certs per environment to shrink the blast radius of a leaked key."}) expiry_dates.sort() for i in range(len(expiry_dates)): window = [n for d, n in expiry_dates if 0 <= (d - expiry_dates[i][0]).days <= 7 and d >= today] if len(window) >= 3: findings.append({"code": "TC15", "severity": "low", "cert": ", ".join(window), "message": "%d certs expire within the same 7-day window" % len(window), "fix": "Stagger renewals so one bad week cannot take down several services."}) break findings.sort(key=lambda f: (SEV_ORDER[f["severity"]], f["code"], f["cert"])) return findings def report(certs, findings, today): lines = ["TLS certificate check as of %s - %d certificates" % (today, len(certs)), ""] lines.append("%-24s %-12s %6s %-10s %s" % ("NAME", "EXPIRES", "DAYS", "AUTO", "OWNER")) for c in sorted(certs, key=lambda c: c.get("_days_left", -10**6)): na = parse_date(c.get("not_after")) lines.append("%-24s %-12s %6s %-10s %s" % (c["name"][:24], na or "?", c.get("_days_left", "?"), "yes" if c.get("auto_renew") else "no", c.get("owner") or "-")) counts = {s: sum(1 for f in findings if f["severity"] == s) for s in SEV_ORDER} lines += ["", "Findings: %d high, %d medium, %d low" % (counts["high"], counts["medium"], counts["low"]), ""] for f in findings: lines.append("[%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["cert"], f["message"])) lines.append(" fix: %s" % f["fix"]) if not findings: lines.append("No findings.") return "\n".join(lines) def self_test(): today = dt.date(2026, 11, 11) base = {"name": "ok", "hosts": ["a.example.com"], "sans": ["a.example.com"], "not_before": "2026-09-01", "not_after": "2027-01-20", "key_type": "ec", "key_bits": 256, "sig_alg": "ecdsa-with-SHA256", "auto_renew": True, "owner": "web", "chain_complete": True, "environment": "production"} def run(**kw): c = dict(base); c.update(kw) return {f["code"] for f in check([c], today)} cases = [ ("clean", run(), set()), ("TC01 expired", run(not_after="2026-11-01") >= {"TC01"}, True), ("TC02 critical", run(not_after="2026-11-20") >= {"TC02"}, True), ("TC03 manual 30d", run(not_after="2026-12-05", auto_renew=False, renewal_runbook="x") >= {"TC03"}, True), ("TC04 stuck renewal", "TC04" in run(not_after="2026-11-28"), True), ("TC05 SAN miss", "TC05" in run(hosts=["b.example.com"]), True), ("wildcard one label", host_covered("a.example.com", ["*.example.com"]) and not host_covered("x.a.example.com", ["*.example.com"]) and not host_covered("example.com", ["*.example.com"]), True), ("TC06 weak rsa", "TC06" in run(key_type="rsa", key_bits=1024), True), ("TC07 sha1", "TC07" in run(sig_alg="sha1WithRSAEncryption"), True), ("TC08 long life", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01"), True), ("TC08 private ok", "TC08" in run(not_before="2025-01-01", not_after="2027-01-01", public=False), False), ("TC09 chain", "TC09" in run(chain_complete=False), True), ("TC10 self-signed", "TC10" in run(self_signed=True), True), ("TC11 owner", "TC11" in run(owner=""), True), ("TC14 future", "TC14" in run(not_before="2026-12-01"), True), ] two = [dict(base, name="w1", sans=["*.example.com"], hosts=["a.example.com"]), dict(base, name="w2", sans=["*.example.com"], hosts=["a.example.com"], environment="staging")] cases.append(("TC13 shared wildcard", any(f["code"] == "TC13" for f in check(two, today)), True)) three = [dict(base, name="c%d" % i, not_after="2027-01-0%d" % (i + 1)) for i in range(3)] cases.append(("TC15 cluster", any(f["code"] == "TC15" for f in check(three, today)), True)) cases.append(("date formats", parse_date("Nov 11 10:00:00 2026 GMT") == dt.date(2026, 11, 11), True)) ok = 0 for name, got, want in cases: passed = got == want ok += passed print("%s %s" % ("PASS" if passed else "FAIL", name)) print("%d/%d passed" % (ok, len(cases))) return 0 if ok == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("inventory", nargs="?") ap.add_argument("--today", help="as-of date YYYY-MM-DD (default: today)") ap.add_argument("--warn-days", type=int, default=30) ap.add_argument("--crit-days", type=int, default=14) ap.add_argument("--json", action="store_true") ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.inventory: ap.print_usage(); return 2 try: today = parse_date(a.today) if a.today else dt.date.today() certs = load(a.inventory, os.path.dirname(os.path.abspath(a.inventory))) findings = check(certs, today, a.warn_days, a.crit_days) except (OSError, ValueError, KeyError, json.JSONDecodeError, ssl.SSLError) as e: print("input error: %s" % e, file=sys.stderr) return 2 if a.json: clean = [{k: v for k, v in c.items() if not k.startswith("_") or k == "_days_left"} for c in certs] print(json.dumps({"today": str(today), "certificates": clean, "findings": findings}, indent=2, default=str)) else: print(report(certs, findings, today)) return 1 if any(f["severity"] == "high" for f in findings) else 0 if __name__ == "__main__": sys.exit(main())

Small Shop Inventory Reorder Planner

--- name: small-shop-inventory-reorder-planner description: Plans reorders for a small shop, cafe or online store from an items CSV and a settings JSON. Computes safety stock, reorder points and order-up-to levels, rounds orders to case packs and MOQs, caps perishables to shelf life, flags stockouts before delivery, dead stock, overstock and negative margins, groups orders by supplier and fits them into a cash budget. Offline stdlib Python planner. --- # Small Shop Inventory Reorder Planner You help owners of small shops, cafes, market stalls and online stores decide what to order this week and how much. Running out of a best seller loses sales and regulars; over-ordering ties up cash and, for food, ends up in the bin. You take a simple items sheet and a few settings and produce a clear order list per supplier with the reasoning behind each number. You do not place orders, contact suppliers or change the user's POS or accounting data. Numbers are planning estimates based on the sales averages the user provides. ## Files in this skill - `scripts/plan_reorders.py` - reads `items.csv` and `settings.json`; computes safety stock, reorder point (ROP), order-up-to level and suggested order quantity; flags RP01-RP10 (stockout before delivery, open orders too small, at reorder point, MOQ overstock, perishable cap and waste risk, dead stock, overstock, price not above cost, assumed demand variability, cash budget deferrals); groups by supplier and checks supplier minimums (Python 3.8+ standard library only) - `references/reorder-math.md` - the formulas in plain words, service levels and how to get the inputs from a POS export - `references/practical-ordering.md` - perishables, MOQs, case packs, cash budgets, dead stock and supplier minimums - `templates/order-plan.md` - the weekly order note you hand back - `examples/items.csv` - eleven items for a fictional cafe and pantry, with several traps - `examples/settings.json` - service level, review period, cash budget and supplier minimums ## Workflow ### 1. Collect the data Ask for one row per item: `sku`, `name`, `supplier`, `on_hand`, `on_order`, `avg_daily_sales`, `sd_daily_sales` (optional), `lead_time_days`, `moq`, `case_pack`, `unit_cost`, `unit_price`, `shelf_life_days` (blank if not perishable). Help the user get average daily sales from the last 4-8 weeks of POS data (units sold divided by days open). Ask for the review rhythm (how often they order), a service level (0.90-0.98) and this week's cash budget. ### 2. Run the planner ``` python3 scripts/plan_reorders.py examples/items.csv examples/settings.json python3 scripts/plan_reorders.py items.csv settings.json --json python3 scripts/plan_reorders.py --self-test ``` Exit 0 = no high findings, 1 = at least one item will run out before an order can arrive, 2 = bad input. Without a shell, apply the formulas in `references/reorder-math.md` row by row. ### 3. Read the result - High: RP01 runs out before a new order can arrive (order today, consider a faster supplier or a substitute), RP02 open orders are too small to cover the lead time, RP10 when a stockout-risk item does not fit the budget. - Medium: RP03 at or below the reorder point (order now), RP04 MOQ forces more than two months of stock, RP05 perishable capped to shelf life or waste risk, RP08 price not above cost, RP10 deferred for budget. - Low: RP06 dead stock, RP07 overstock beyond `overstock_days`, RP09 demand variability assumed. ### 4. Deliver Fill `templates/order-plan.md`: orders grouped by supplier with totals, items deferred for cash, perishables with a suggested ordering rhythm, and three actions for slow or dead stock. Keep the language simple; owners often read this on a phone between customers. ## Example result On the sample cafe (95% service level, weekly review, $420 budget), house coffee beans will run out in about 4 days against a 5-day lead time (high, order 48 now), sourdough and cookies are capped to their 3- and 7-day shelf lives with advice to order more often, orange juice sells below cost and its MOQ still risks waste, the PackRight and Dairy orders fall below supplier minimums, logo mugs are dead stock and paper straws have 150 days of cover. Spend: $387.70 of $420. ## Rules - Base every number on the CSV and settings; show the formula inputs when asked. - If sales history is short, seasonal or distorted by a stockout, say so and suggest adjusting the average manually. - Never invent supplier terms, prices or lead times; mark unknowns and ask. - This is a planning aid, not accounting or financial advice. FILE:references/reorder-math.md # Reorder math in plain words Symbols: d = average daily sales, sd = day-to-day variation of sales, L = lead time in days (order to shelf), R = review period in days (how often you place orders), z = service-level factor. | Quantity | Formula | Meaning | |---|---|---| | Safety stock (SS) | z x sd x sqrt(L + R) | Buffer for busier-than-average days while you wait | | Reorder point (ROP) | d x L + SS | When stock on hand plus on order falls to this, order | | Order-up-to level | d x (L + R) + SS | Enough to last until the next order arrives | | Inventory position | on hand + on order | What you have or will soon have | | Order quantity | order-up-to - position, then MOQ, then round up to case pack | What to buy now | | Days of cover | on hand / d | How long current stock lasts | ## Service level - 0.90 -> z about 1.28; 0.95 -> 1.64; 0.98 -> 2.05; 0.99 -> 2.33. - Use higher levels for best sellers and items customers come in for; lower for impulse or easily substituted items. ## Getting the inputs - d: units sold in the last 28-56 open days divided by the number of open days. Exclude days the item was out of stock. - sd: standard deviation of daily units in the same window. A spreadsheet STDEV over daily totals works. If unknown, the script assumes 50% of d (RP09). - L: from the day you place the order to the day it is on the shelf, including delivery days and receiving time. Use the slow end of the usual range. - R: 7 for weekly ordering, 1 for daily bread or dairy runs. ## Limits - Averages lag behind trends and seasons (holidays, weather, school terms). Adjust d by hand for the coming period. - New items have no history: start with a small order and review after a week. FILE:references/practical-ordering.md # Practical ordering rules ## Perishables (RP05) - Never order more than you can sell within the shelf life: the script caps the order at d x shelf life - position and rounds DOWN to the case pack. - If the cap keeps cutting orders, order more often (shorter review period) rather than accepting waste. - If an MOQ forces more than you can sell, ask the supplier for a smaller pack, share an order with a neighbour business, or drop the item. ## MOQ and case packs (RP04) - Case packs round up for non-perishables. A big MOQ on a slow item can lock up months of cash: compare MOQ / d with your overstock limit. ## Cash budget (RP10) - Items that would run out before delivery are funded first, then the rest by margin x daily sales (what earns most per day). - Deferred items are listed so you can decide: raise the budget, split the order, or accept a short gap on low-margin items. ## Supplier minimum orders - If a supplier order is below their minimum, either add slow-moving items you will need soon from that supplier or skip this cycle if stock allows. ## Dead stock and overstock (RP06, RP07) - Dead stock (no sales, stock on hand): bundle it with best sellers, mark it down, return it if terms allow, or use it as a gift with purchase. - Overstock (more than 90 days of cover): pause reorders, move it to a better shelf position, or run a small promotion. ## Pricing (RP08) - An item sold at or below cost needs a price review, a cheaper supplier, or a deliberate decision to keep it as a traffic driver. ## Weekly routine (15 minutes) 1. Export or count on-hand stock for the order list. 2. Update on_order with anything not yet received. 3. Run the planner, read high flags first. 4. Place orders per supplier, note expected delivery dates. 5. Once a month, refresh d and sd from the POS. FILE:templates/order-plan.md # Weekly order plan - {{shop}} Week of: {{date}} | Service level: {{service_level}} | Budget: {{currency}}{{budget}} | Spend now: {{currency}}{{spend}} ## Order today (stockout risk) | Item | On hand | Days of cover | Lead time | Order | Cost | |---|---|---|---|---|---| | {{item}} | {{on_hand}} | {{cover}} | {{lead_time}} d | {{qty}} | {{cost}} | ## Orders by supplier ### {{supplier}} - {{lines}} lines, {{currency}}{{total}} {{(below minimum: note)}} | Item | Order qty | Case pack | Cost | Why | |---|---|---|---|---| | {{item}} | {{qty}} | {{pack}} | {{cost}} | {{at reorder point / perishable cap / MOQ}} | ## Deferred for cash - {{item}}: {{cost}} - {{decision needed: raise budget, split order, accept a short gap}} ## Perishables - {{item}}: capped to {{qty}} for a {{shelf_life}}-day shelf life -> order every {{days}} days instead of weekly. ## Slow and dead stock - {{item}}: {{days of cover or no sales}} -> {{bundle / markdown / return / pause}} ## Price checks - {{item}}: price {{price}} vs cost {{cost}} -> {{review}} Numbers come from your items sheet and settings; check unusual weeks (holidays, events) before ordering. FILE:examples/items.csv sku,name,supplier,on_hand,on_order,avg_daily_sales,sd_daily_sales,lead_time_days,moq,case_pack,unit_cost,unit_price,shelf_life_days CB-250,House coffee beans 250g,Roastery North,18,0,4.2,1.8,5,24,6,5.40,12.50 OM-1L,Oat milk 1L,Dairy and Plant Co,30,24,6.5,2.5,3,12,12,1.35,2.90,60 SB-12,Sourdough loaf,Local Bakery,8,0,7.0,2.0,1,,1,2.10,5.00,3 CP-12,Paper cups 12oz (sleeve of 50),PackRight,9,0,0.9,0.4,10,20,10,3.80,0, JR-HN,Wildflower honey jar 340g,Hill Apiary,26,0,0.6,0.5,14,48,12,4.20,9.90,720 TB-EG,English breakfast tea 50 bags,Leaf Traders,40,0,1.1,0.6,7,,10,2.60,6.50,540 CK-CH,Chocolate chip cookies 6-pack,Local Bakery,12,0,3.0,,2,,6,1.90,4.20,7 GF-BR,Gluten-free brownies 4-pack,Free From Foods,6,12,1.4,0.7,6,24,12,3.10,6.90,21 MG-CE,Ceramic mug with shop logo,PackRight,64,0,0,,21,,6,4.50,14.00, ST-PA,Paper straws (box of 250),PackRight,30,0,0.2,0.1,10,,1,6.00,0, OJ-1L,Fresh orange juice 1L,Dairy and Plant Co,10,0,2.5,1.2,2,6,6,2.30,2.20,6 FILE:examples/settings.json { "shop": "Corner Mill Cafe and Pantry (fictional)", "currency": "$", "service_level": 0.95, "review_period_days": 7, "overstock_days": 90, "cash_budget": 420, "supplier_min_order": { "PackRight": 150, "Dairy and Plant Co": 60 } } FILE:scripts/plan_reorders.py #!/usr/bin/env python3 """Small shop inventory reorder planner (Python 3.8+ standard library only). Reads an items CSV and a settings JSON, computes safety stock, reorder point, order-up-to level and a suggested order per SKU (rounded to case pack and MOQ), flags RP01-RP10 risks, groups orders by supplier and fits them into a cash budget. Usage: python3 scripts/plan_reorders.py examples/items.csv examples/settings.json python3 scripts/plan_reorders.py items.csv settings.json --json python3 scripts/plan_reorders.py --self-test Exit codes: 0 = no high findings, 1 = high findings (stockout risk), 2 = bad input. """ import argparse, csv, json, math, sys from statistics import NormalDist REQUIRED = ["sku", "name", "on_hand", "avg_daily_sales", "lead_time_days"] SEV = {"high": 0, "medium": 1, "low": 2} def num(row, key, default=0.0): v = (row.get(key) or "").strip() if v == "": return default return float(v) def load_items(path): with open(path, newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) if not rows: raise ValueError("items CSV is empty") missing = [c for c in REQUIRED if c not in rows[0]] if missing: raise ValueError("items CSV missing columns: %s" % ", ".join(missing)) return rows def plan_item(row, s): z = NormalDist().inv_cdf(s.get("service_level", 0.95)) R = float(s.get("review_period_days", 7)) it = {"sku": row["sku"].strip(), "name": row["name"].strip(), "supplier": (row.get("supplier") or "unknown").strip() or "unknown"} d = num(row, "avg_daily_sales") sd = num(row, "sd_daily_sales", d * 0.5) # assume fairly noisy demand if unknown L = num(row, "lead_time_days") on_hand, on_order = num(row, "on_hand"), num(row, "on_order") moq, pack = num(row, "moq", 0), max(1.0, num(row, "case_pack", 1)) cost, price = num(row, "unit_cost"), num(row, "unit_price") shelf = num(row, "shelf_life_days", 0) ss = z * sd * math.sqrt(L + R) rop = d * L + ss up_to = d * (L + R) + ss pos = on_hand + on_order qty = 0.0 if d > 0 and pos <= rop: qty = max(up_to - pos, 0) if moq and qty < moq: qty = moq qty = math.ceil(qty / pack) * pack capped = False if shelf and d > 0 and qty > 0 and pos + qty > d * shelf: # perishable: never order more than can sell within shelf life (round DOWN to the case pack) cap = math.floor(max(d * shelf - pos, 0) / pack) * pack if moq and cap < moq: qty = min(qty, math.ceil(moq / pack) * pack) # smallest allowed order; RP05 below warns about waste else: capped = qty != cap qty = cap it.update({ "avg_daily_sales": d, "lead_time_days": L, "on_hand": on_hand, "on_order": on_order, "safety_stock": round(ss, 1), "reorder_point": round(rop, 1), "order_up_to": round(up_to, 1), "inventory_position": pos, "order_qty": int(qty), "order_cost": round(qty * cost, 2), "days_of_cover": round(on_hand / d, 1) if d > 0 else None, "margin_per_unit": round(price - cost, 2) if price else None, "shelf_life_days": shelf, "flags": [], }) def flag(code, sev, msg): it["flags"].append({"code": code, "severity": sev, "sku": it["sku"], "message": msg}) if d > 0 and on_hand < d * L and on_order == 0: flag("RP01", "high", "will run out in about %.0f days, before a new order (lead time %.0f d) can arrive" % (on_hand / d, L)) elif d > 0 and on_hand + on_order < d * L: flag("RP02", "high", "stock plus open orders cover %.0f days, less than the %.0f-day lead time" % (pos / d, L)) if qty > 0: flag("RP03", "medium", "at or below reorder point (%.0f <= %.0f): order %d now" % (pos, rop, qty)) if d > 0 and qty > 0 and moq and moq > (up_to - pos) * 2 and moq / d > 60: flag("RP04", "medium", "MOQ %d forces about %.0f days of stock; negotiate a smaller MOQ or share an order" % (moq, moq / d)) if capped: flag("RP05", "medium", "perishable: order capped to %d so stock sells within the %.0f-day shelf life; order more often than every %.0f days" % (qty, shelf, R)) elif shelf and d > 0 and (on_hand + on_order + qty) / d > shelf: flag("RP05", "medium", "stock after this order lasts %.1f days but shelf life is %.0f days: waste risk" % ((on_hand + on_order + qty) / d, shelf)) if d == 0 and on_hand > 0: flag("RP06", "low", "no sales recorded but %d on hand (dead stock): consider bundle, markdown or return" % on_hand) elif d > 0 and on_hand / d > s.get("overstock_days", 90): flag("RP07", "low", "%.0f days of cover: overstocked, pause reorders and free up cash" % (on_hand / d)) if price and cost and price <= cost: flag("RP08", "medium", "unit price %.2f is not above unit cost %.2f" % (price, cost)) if not (row.get("sd_daily_sales") or "").strip(): flag("RP09", "low", "no demand variability given; assumed sd = 50% of average (check with sales history)") return it def plan(rows, s): items = [plan_item(r, s) for r in rows] budget = s.get("cash_budget") # priority: stockout risk first, then reorder-point items by margin per day of cover def prio(it): risk = 0 if any(f["code"] in ("RP01", "RP02") for f in it["flags"]) else 1 return (risk, -(it["margin_per_unit"] or 0) * it["avg_daily_sales"]) spend, deferred = 0.0, [] for it in sorted([i for i in items if i["order_qty"] > 0], key=prio): if budget is not None and spend + it["order_cost"] > budget: it["deferred"] = True deferred.append(it["sku"]) it["flags"].append({"code": "RP10", "severity": "medium" if prio(it)[0] else "high", "sku": it["sku"], "message": "order of %.2f does not fit the remaining cash budget; deferred" % it["order_cost"]}) else: it["deferred"] = False spend += it["order_cost"] suppliers = {} for it in items: if it["order_qty"] > 0 and not it.get("deferred"): sp = suppliers.setdefault(it["supplier"], {"lines": 0, "units": 0, "cost": 0.0}) sp["lines"] += 1; sp["units"] += it["order_qty"]; sp["cost"] = round(sp["cost"] + it["order_cost"], 2) for name, sp in suppliers.items(): mo = (s.get("supplier_min_order") or {}).get(name) if mo and sp["cost"] < mo: sp["note"] = "below supplier minimum order %.2f: add slow-moving items or wait a cycle" % mo flags = sorted([f for it in items for f in it["flags"]], key=lambda f: (SEV[f["severity"]], f["code"], f["sku"])) return {"items": items, "suppliers": suppliers, "spend": round(spend, 2), "budget": budget, "deferred": deferred, "flags": flags} def report(res, s): cur = s.get("currency", "") out = ["Reorder plan for %s (service level %.0f%%, review every %s days)" % (s.get("shop", "shop"), s.get("service_level", 0.95) * 100, s.get("review_period_days", 7)), ""] out.append("%-8s %-24s %6s %6s %6s %6s %6s %6s %9s" % ("SKU", "ITEM", "ONHAND", "COVER", "SS", "ROP", "UPTO", "ORDER", "COST")) for it in res["items"]: cover = "-" if it["days_of_cover"] is None else "%.0fd" % it["days_of_cover"] order = ("%d*" % it["order_qty"]) if it.get("deferred") else str(it["order_qty"]) out.append("%-8s %-24s %6d %6s %6.0f %6.0f %6.0f %6s %9.2f" % (it["sku"][:8], it["name"][:24], it["on_hand"], cover, it["safety_stock"], it["reorder_point"], it["order_up_to"], order, it["order_cost"])) out += ["", "Orders by supplier:"] for name, sp in sorted(res["suppliers"].items()): out.append(" %-20s %d lines, %d units, %s%.2f%s" % (name, sp["lines"], sp["units"], cur, sp["cost"], (" (" + sp["note"] + ")") if sp.get("note") else "")) b = res["budget"] out.append("Total to spend now: %s%.2f%s" % (cur, res["spend"], "" if b is None else " of %s%.2f budget" % (cur, b))) if res["deferred"]: out.append("Deferred (marked *): " + ", ".join(res["deferred"])) out += ["", "Flags:"] for f in res["flags"]: out.append(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], f["sku"], f["message"])) return "\n".join(out) def self_test(): s = {"service_level": 0.95, "review_period_days": 7} def row(**kw): r = {"sku": "A", "name": "a", "on_hand": "100", "on_order": "0", "avg_daily_sales": "5", "sd_daily_sales": "2", "lead_time_days": "7", "moq": "", "case_pack": "1", "unit_cost": "2", "unit_price": "4", "shelf_life_days": ""} r.update({k: str(v) for k, v in kw.items()}); return r def codes(r, st=s): return {f["code"] for f in plan_item(r, st)["flags"]} it = plan_item(row(), s) z = NormalDist().inv_cdf(0.95) cases = [ ("safety stock formula", abs(it["safety_stock"] - round(z * 2 * math.sqrt(14), 1)) < 0.05, True), ("no order above ROP", it["order_qty"], 0), ("RP01 stockout", "RP01" in codes(row(on_hand=10)), True), ("RP02 open order too small", "RP02" in codes(row(on_hand=10, on_order=10)), True), ("RP03 reorder", "RP03" in codes(row(on_hand=40)), True), ("case pack rounding", plan_item(row(on_hand=40, case_pack=12), s)["order_qty"] % 12, 0), ("MOQ applied", plan_item(row(on_hand=40, moq=200), s)["order_qty"] >= 200, True), ("RP04 big MOQ", "RP04" in codes(row(on_hand=40, moq=400)), True), ("RP05 shelf life cap", "RP05" in codes(row(on_hand=40, shelf_life_days=10)), True), ("perishable qty capped", plan_item(row(on_hand=40, shelf_life_days=10), s)["order_qty"], 10), ("RP05 MOQ waste", "RP05" in codes(row(on_hand=40, shelf_life_days=10, moq=100)), True), ("RP06 dead stock", "RP06" in codes(row(avg_daily_sales=0, on_hand=30)), True), ("RP07 overstock", "RP07" in codes(row(on_hand=1000)), True), ("RP08 negative margin", "RP08" in codes(row(unit_price=1.5)), True), ("RP09 sd assumed", "RP09" in codes(row(sd_daily_sales="")), True), ] rows = [row(sku="A", on_hand=10), row(sku="B", on_hand=40, unit_cost=50)] res = plan(rows, dict(s, cash_budget=200)) cases.append(("RP10 budget defers lower priority", res["deferred"], ["B"])) ok = 0 for name, got, want in cases: p = got == want; ok += p print("%s %s" % ("PASS" if p else "FAIL", name)) print("%d/%d passed" % (ok, len(cases))) return 0 if ok == len(cases) else 1 def main(argv=None): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("items", nargs="?"); ap.add_argument("settings", nargs="?") ap.add_argument("--json", action="store_true"); ap.add_argument("--self-test", action="store_true") a = ap.parse_args(argv) if a.self_test: return self_test() if not a.items: ap.print_usage(); return 2 try: s = {} if a.settings: with open(a.settings, encoding="utf-8") as f: s = json.load(f) if not 0.5 <= s.get("service_level", 0.95) < 1: raise ValueError("service_level must be between 0.5 and 0.999") res = plan(load_items(a.items), s) except (OSError, ValueError, KeyError, json.JSONDecodeError) as e: print("input error: %s" % e, file=sys.stderr); return 2 print(json.dumps(res, indent=2) if a.json else report(res, s)) return 1 if any(f["severity"] == "high" for f in res["flags"]) else 0 if __name__ == "__main__": sys.exit(main())

Webhook Signature Verifier and Replay Guard

--- name: webhook-signature-verifier-and-replay-guard description: Debugs and hardens incoming webhook verification. Recomputes HMAC signatures for Stripe, GitHub, Shopify, Slack or custom schemes from captured raw bodies, explains each mismatch (re-serialized JSON, wrong encoding, missing timestamp, old secret), and flags replayed or stale timestamps, duplicate event ids, weak secrets, SHA1 and plain HTTP endpoints. Offline stdlib Python checker. --- # Webhook Signature Verifier and Replay Guard You help developers who receive webhooks from payment, Git, commerce or chat platforms answer two questions fast: "why does my signature check fail?" and "is my endpoint safe against forged or replayed calls?". Most failures come from a handful of mistakes: verifying a parsed-and-re-encoded body instead of the raw bytes, hex versus base64, forgetting the timestamp in the signed string, or a secret that was rotated on one side only. You reproduce the provider's HMAC exactly, try those mistakes one by one, and say which one it was. You never call the provider's API or the user's endpoint. You work only from captured deliveries and config the user gives you. Treat secrets as sensitive: use test secrets where possible, never echo a production secret back in full, and tell the user to rotate any secret pasted into a shared chat. ## Files in this skill - `scripts/verify_webhooks.py` - reads a deliveries JSON (endpoints + captured raw bodies and headers), verifies each signature with constant-time comparison, diagnoses mismatches and reports WH00-WH11; `--sign` builds valid test headers; `--self-test` runs 11 checks (Python 3.8+ standard library only) - `references/provider-schemes.md` - exactly what Stripe, GitHub, Shopify and Slack sign, plus how to describe a custom scheme - `references/verification-pitfalls.md` - raw body handling per framework, timing-safe compare, replay windows, idempotency, secret rotation - `templates/verification-report.md` - the report you hand back - `templates/handler-snippets.md` - minimal correct handlers for Express and Flask to adapt - `examples/deliveries.json` - 11 demo deliveries to 5 endpoints with fake secrets and several planted mistakes ## Workflow ### 1. Capture the evidence Ask for, per endpoint: provider/scheme, the secret (a test-mode secret is best), the public URL, and for each failing call the **raw** request body exactly as received plus all headers. Logging `JSON.stringify(req.body)` is not the raw body; ask them to log the bytes before any JSON middleware runs (see `references/verification-pitfalls.md`). Put it into the `examples/deliveries.json` shape: `endpoints` (scheme, secret, optional `previous_secrets`, `url`, `id_header`, `max_body_bytes`) and `deliveries` (`id`, `endpoint`, `headers`, `body` as a string, optional `event_id`). ### 2. Run the checker ``` python3 scripts/verify_webhooks.py examples/deliveries.json python3 scripts/verify_webhooks.py my-deliveries.json --now 2026-11-13T07:00:00Z --json python3 scripts/verify_webhooks.py --sign stripe --secret whsec_test_x --body-file body.json --timestamp 1794553200 python3 scripts/verify_webhooks.py --self-test ``` Use `--now` with the time the deliveries were captured, otherwise every old capture shows as a replay. Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, follow `references/provider-schemes.md` to rebuild the signed string by hand and compare. ### 3. Read the result Each delivery gets a verdict: `accept`, `accept-duplicate(skip side effects)`, `accept-rotate-secret` or `reject`. - High: WH01 signature mismatch (with the likely cause), WH02 missing signature or timestamp header, WH03 timestamp older than the tolerance (replay risk), WH09 endpoint not on HTTPS, WH00 bad input or unknown endpoint. - Medium: WH04 duplicate event id, WH05 timestamp in the future beyond allowed skew (clock drift), WH06 SHA1-only signature, WH07 signed with a previous secret, WH08 short or low-entropy secret. - Low: WH10 no event id to de-duplicate on, WH11 body larger than the configured limit. ### 4. Deliver Fill `templates/verification-report.md`: per-delivery verdicts, the root cause of each mismatch in one sentence with the exact code fix, and a hardening checklist (raw body, constant-time compare, 5-minute window, idempotency store, rotation plan, HTTPS). If they want code, adapt `templates/handler-snippets.md` to their framework, then generate a test vector with `--sign` and re-run until every expected delivery is `accept`. ## Example result On the demo file (now = 13 Nov 2026 07:00 UTC): D01 is valid and D02 is the same Stripe event again (skip side effects); D03 was signed over compact JSON but the app verified a pretty-printed copy; D04 carries a valid signature that is an hour old, so it is rejected as a replay; D06 is still signed with GitHub's previous secret; D07 has only the legacy SHA1 header; D08 compared a hex digest where Shopify sends base64; D10's Slack timestamp is 10 minutes in the future; and the contact form posts to plain HTTP with an 11-character secret. Result: 5 high, 5 medium, 2 low. ## Rules - Always verify against the raw bytes and compare with a constant-time function; never compare signatures with `==`. - Reject before doing work: signature and timestamp checks come before parsing, database writes or queueing. - A valid signature does not make a delivery fresh or unique: check the timestamp window and de-duplicate on the event id. - Do not weaken checks to "make it pass" (no skipping verification in production, no huge tolerances); fix the root cause. - Provider details change; confirm header names and signed-string formats against the provider's current docs before shipping. FILE:references/provider-schemes.md # Provider signature schemes All of these are HMAC over the **raw request body** with a shared secret. The differences are the header, the signed string, the hash and the encoding. Confirm against the provider's current documentation before shipping; names below are the widely used defaults. | Scheme (`scheme`) | Header | Signed string | Hash | Encoding | Timestamp | |---|---|---|---|---|---| | `stripe` | `Stripe-Signature: t=<unix>,v1=<sig>[,v1=<sig2>]` | `<t>.<raw body>` | SHA-256 | hex | `t=` inside the header; default tolerance 300 s | | `github` | `X-Hub-Signature-256: sha256=<sig>` | `<raw body>` | SHA-256 | hex | none (use `X-GitHub-Delivery` to de-duplicate) | | `github-sha1` | `X-Hub-Signature: sha1=<sig>` | `<raw body>` | SHA-1 | hex | legacy, avoid | | `shopify` | `X-Shopify-Hmac-Sha256: <sig>` | `<raw body>` | SHA-256 | base64 | none (de-duplicate on `X-Shopify-Webhook-Id`) | | `slack` | `X-Slack-Signature: v0=<sig>` + `X-Slack-Request-Timestamp` | `v0:<ts>:<raw body>` | SHA-256 | hex | reject if older than 5 minutes | ## Notes per provider - **Stripe**: during secret rolling the header can carry several `v1=` values; accept if any one matches. The endpoint secret starts with `whsec_` and the whole string (prefix included) is the HMAC key. - **GitHub**: the secret is whatever you typed when creating the webhook. Ping events are signed too. Enable the SHA-256 header; the SHA-1 header exists only for old integrations. - **Shopify**: the key is the app's API secret (or the webhook signing secret shown in the admin). The digest is base64, so comparing against a hex digest always fails. - **Slack**: the body is usually `application/x-www-form-urlencoded`; sign the raw string, do not rebuild it from parsed form fields. ## Describing a custom scheme (`scheme: generic`) Set these fields on the endpoint: - `header` - header that carries the signature, e.g. `X-Signature` - `alg` - `sha256`, `sha512` or `sha1` - `enc` - `hex` or `base64` - `prefix` - text before the digest in the header, e.g. `sha256=` (empty if none) - `template` - signed string, using `{body}` and optionally `{ts}`, e.g. `{ts}.{body}` - `ts_header` - header with the unix timestamp, if the scheme has one - `id_header` - header with a unique delivery id, for de-duplication Any field can also override a named scheme (for example a self-hosted GitLab-style proxy that re-signs with a different header). FILE:references/verification-pitfalls.md # Verification pitfalls and hardening ## 1. Use the raw body (the cause of most mismatches) JSON middleware parses the body; re-encoding it changes whitespace, key order or number formatting, so the HMAC no longer matches. - **Express**: mount `express.raw({ type: 'application/json' })` on the webhook route (before `express.json()`), verify `req.body` (a Buffer), then `JSON.parse` it yourself. - **Next.js route handlers**: `const raw = await req.text()` before anything else. - **Flask**: `request.get_data(cache=True, as_text=False)`; do not use `request.json` for verification. - **Django**: `request.body` (bytes) before touching `request.POST`. - **FastAPI/Starlette**: `await request.body()`. - **Go**: read `r.Body` once with `io.ReadAll`, verify, then unmarshal from the same bytes. - Proxies, API gateways and serverless adapters may re-encode bodies (base64 in AWS API Gateway events: decode first) or add a trailing newline. ## 2. Compare in constant time Use `hmac.compare_digest` (Python), `crypto.timingSafeEqual` (Node, equal-length Buffers), `hmac.Equal` (Go), `MessageDigest.isEqual` (Java). Plain `==` leaks timing and invites forgery attempts. ## 3. Freshness and replay - If the scheme signs a timestamp, reject deliveries older than the tolerance (300 s is the common default) **even when the signature is valid**: an attacker who captured one request can resend it. - Allow a small future skew (about 60 s) and keep server clocks on NTP; large future offsets mean a clock problem. - Schemes without a signed timestamp (GitHub, Shopify) rely on de-duplication only. ## 4. Idempotency Providers retry on timeouts and non-2xx responses, so the same event arrives more than once. Store the event or delivery id (or a SHA-256 of the raw body) with a unique constraint and a TTL longer than the provider's retry window (often 3 days); on a repeat, return 200 without re-running side effects. Respond within a few seconds and do slow work in a queue. ## 5. Secrets and rotation - Generate at least 32 random bytes (`python3 -c "import secrets; print(secrets.token_hex(32))"`); one secret per endpoint and environment. - Rotation: add the new secret as primary and keep the old one in `previous_secrets` for a short overlap, accept either, then remove the old one. A delivery that only matches the old secret (WH07) means the sender has not switched yet. - Load secrets from a secret manager or environment, strip whitespace, and never log them. ## 6. Transport and limits - HTTPS only: the HMAC proves origin but does not hide customer data. - Cap body size and reject before parsing; return 401/403 for bad signatures without details, and log the reason internally. - Optional extra layer: allow-list the provider's published IP ranges, but never instead of signature checks. FILE:templates/verification-report.md # Webhook verification report **Endpoints checked:** [names] **Deliveries:** [n] **Captured at:** [time, used as --now] **Verdict:** [All good / Fix before go-live / Under attack or misconfigured] **Findings:** [h] high, [m] medium, [l] low (`verify_webhooks.py` output attached) ## Deliveries | Delivery | Endpoint | Verdict | Root cause (one sentence) | |---|---|---|---| | [D01] | [billing-stripe] | [accept / reject / duplicate / rotate] | [e.g. verified pretty-printed JSON instead of raw body] | ## Fixes, in order 1. [Code fix with file/line, e.g. mount express.raw() on /hooks/stripe before express.json()] 2. [...] 3. [...] ## Hardening checklist - [ ] Verify the raw body bytes, then parse - [ ] Constant-time comparison - [ ] Timestamp window [300] s, future skew [60] s, NTP on all hosts - [ ] Idempotency store keyed on [event id header], TTL [3 days] - [ ] One random secret (32+ bytes) per endpoint and environment; rotation plan with overlap - [ ] HTTPS only, body size limit, 401 without details on failure - [ ] Alert when the failure rate on an endpoint jumps ## Test vectors used [--sign commands and the headers they produced, with test secrets only] FILE:templates/handler-snippets.md # Minimal correct handlers (adapt names, keep the order of checks) ## Node.js / Express (Stripe-style `t=...,v1=...`) ```js const crypto = require('crypto'); const express = require('express'); const app = express(); const SECRET = process.env.WEBHOOK_SECRET; // never hard-code const TOLERANCE = 300; // seconds const seen = new Set(); // use a DB table with a unique key in production app.post('/hooks/stripe', express.raw({ type: 'application/json' }), (req, res) => { const header = req.get('Stripe-Signature') || ''; const parts = Object.fromEntries(header.split(',').map(p => p.split('='))); const t = Number(parts.t); const sigs = header.split(',').filter(p => p.startsWith('v1=')).map(p => p.slice(3)); if (!t || sigs.length === 0) return res.sendStatus(401); if (Math.abs(Date.now() / 1000 - t) > TOLERANCE) return res.sendStatus(401); const expected = crypto.createHmac('sha256', SECRET).update(`${t}.`).update(req.body).digest('hex'); const ok = sigs.some(s => s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected))); if (!ok) return res.sendStatus(401); const event = JSON.parse(req.body.toString('utf8')); if (seen.has(event.id)) return res.sendStatus(200); // duplicate: no side effects seen.add(event.id); // enqueue(event) and return quickly res.sendStatus(200); }); app.use(express.json()); // other routes after the raw webhook route ``` ## Python / Flask (GitHub `X-Hub-Signature-256`) ```python import hashlib, hmac, json, os from flask import Flask, request, abort app = Flask(__name__) SECRET = os.environ["WEBHOOK_SECRET"].strip().encode() seen = set() # replace with a table that has a UNIQUE constraint on delivery_id @app.post("/hooks/github") def github_hook(): raw = request.get_data(cache=True) # raw bytes, before request.json header = request.headers.get("X-Hub-Signature-256", "") if not header.startswith("sha256="): abort(401) expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(header[7:], expected): abort(401) delivery = request.headers.get("X-GitHub-Delivery") if delivery in seen: return "", 200 # duplicate retry seen.add(delivery) event = json.loads(raw) # enqueue(event) and return quickly return "", 200 ``` ## Checklist when porting to another stack Read raw bytes -> check header present -> check timestamp window (if signed) -> HMAC with the right hash/encoding -> constant-time compare (any of several signatures) -> de-duplicate -> parse -> enqueue -> 2xx fast. FILE:examples/deliveries.json { "now": "2026-11-13T07:00:00Z", "tolerance_seconds": 300, "future_skew_seconds": 60, "_note": "Demo data only: every secret below is a fake test value. Bodies are the RAW request bodies exactly as received.", "endpoints": { "billing-stripe": { "scheme": "stripe", "secret": "whsec_demo_4b9e2c7a1f6d3085e2a9c4b7d1f0e6a3", "url": "https://api.acme-demo.test/hooks/stripe", "max_body_bytes": 65536 }, "ci-github": { "scheme": "github", "secret": "gh_demo_secret_9c1e7a3f5b2d8064aa71c3e9f2b5d708", "previous_secrets": [ "gh_demo_old_secret_2f8a6c4e0b1d9375" ], "url": "https://api.acme-demo.test/hooks/github", "id_header": "X-GitHub-Delivery" }, "orders-shopify": { "scheme": "shopify", "secret": "shpss_demo_e3a1c9f7b5d2084b6e2c9a7f1d3b5e80", "url": "https://api.acme-demo.test/hooks/shopify", "id_header": "X-Shopify-Webhook-Id" }, "ops-slack": { "scheme": "slack", "secret": "slack_demo_8f2c6a0e4b9d1735c2e8a6f0b4d9c173", "url": "https://api.acme-demo.test/hooks/slack" }, "contact-form": { "scheme": "generic", "header": "X-Form-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{body}", "secret": "formhook123", "url": "http://forms.acme-demo.test/hook" } }, "deliveries": [ { "id": "D01", "endpoint": "billing-stripe", "event_id": "evt_3Qx1", "headers": { "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D02", "endpoint": "billing-stripe", "event_id": "evt_3Qx1", "headers": { "Stripe-Signature": "t=1794553160,v1=5ac4a493d3abba1d31c6979909abe3f96f880b5d5567f64e2e1292578d05a6c8" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D03", "endpoint": "billing-stripe", "event_id": "evt_3Qx2", "headers": { "Stripe-Signature": "t=1794553170,v1=b20e8ff57bb1b1d93f8793c15a2217b54e0e012b3800a1faa32a613e4fbcb5d2" }, "body": "{\n \"id\": \"evt_3Qx1\",\n \"type\": \"invoice.paid\",\n \"data\": {\n \"object\": {\n \"id\": \"in_901\",\n \"amount_paid\": 4900,\n \"currency\": \"usd\",\n \"customer\": \"cus_77\"\n }\n }\n}" }, { "id": "D04", "endpoint": "billing-stripe", "event_id": "evt_2Zk9", "headers": { "Stripe-Signature": "t=1794549600,v1=647af93a8d457b8daee20995225aae284f5ea56cfe075c38cb465fe41ff99bfb" }, "body": "{\"id\":\"evt_3Qx1\",\"type\":\"invoice.paid\",\"data\":{\"object\":{\"id\":\"in_901\",\"amount_paid\":4900,\"currency\":\"usd\",\"customer\":\"cus_77\"}}}" }, { "id": "D05", "endpoint": "ci-github", "headers": { "X-Hub-Signature-256": "sha256=646c0de3d17073a243c74ed3340c018acbea30805a870eff1d6847b4333a5963", "X-GitHub-Delivery": "a1b2-0001" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D06", "endpoint": "ci-github", "headers": { "X-Hub-Signature-256": "sha256=f728095add7f5315c2eda1d4f6e36040f898f4d0c2d71a42e8154ec05b1f16da", "X-GitHub-Delivery": "a1b2-0002" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D07", "endpoint": "ci-github", "headers": { "X-Hub-Signature": "sha1=ca66729dfe67d043208370a5b228586808eaa8ce", "X-GitHub-Delivery": "a1b2-0003" }, "body": "{\"ref\":\"refs/heads/main\",\"after\":\"9f1c2e7\",\"repository\":{\"full_name\":\"acme-demo/shop-api\"},\"pusher\":{\"name\":\"dev-ana\"}}" }, { "id": "D08", "endpoint": "orders-shopify", "headers": { "X-Shopify-Hmac-Sha256": "651b34b52d6af57f77251cb9e652c7e409bf05c04695478629ec8104f4bf6992", "X-Shopify-Webhook-Id": "wh-5501" }, "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}" }, { "id": "D09", "endpoint": "orders-shopify", "headers": { "X-Shopify-Hmac-Sha256": "ZRs0tS1q9X93JRy55lLH5Am/BcBGlUeGKeyBBPS/aZI=", "X-Shopify-Webhook-Id": "wh-5502" }, "body": "{\"id\":820012,\"email\":\"buyer@example.test\",\"total_price\":\"58.00\",\"currency\":\"EUR\",\"line_items\":[{\"sku\":\"TEA-250\",\"quantity\":2}]}" }, { "id": "D10", "endpoint": "ops-slack", "headers": { "X-Slack-Signature": "v0=675094d734821c12a58309211f8d66c58fffbbf86f25ba8424acb5cffd228fe6", "X-Slack-Request-Timestamp": "1794553800" }, "body": "token=demo&team_id=T000&command=%2Fdeploy&text=shop-api+staging&user_name=dev-ana" }, { "id": "D11", "endpoint": "contact-form", "headers": { "X-Form-Signature": "50c78cd627e684b0c1c024f1dfe22cc321a4afb6d25aed29aad8f1c6c2c66dce" }, "body": "{\"form\":\"contact\",\"name\":\"Sam\",\"message\":\"Please call me back\"}" } ] } FILE:scripts/verify_webhooks.py #!/usr/bin/env python3 """Webhook signature verifier and replay guard (offline, Python 3.8+ standard library only). Reads a JSON file with endpoint configs and captured deliveries (raw body + headers), recomputes each HMAC signature, checks timestamps, duplicates and config hygiene, and explains the most likely cause of every mismatch. Usage: verify_webhooks.py deliveries.json [--now 2026-11-13T10:00:00Z] [--json] verify_webhooks.py --sign SCHEME --secret S --body-file body.txt [--timestamp 1794560400] verify_webhooks.py --self-test Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input. """ import argparse, base64, hashlib, hmac, json, math, sys from collections import Counter from datetime import datetime, timezone SCHEMES = { # header, algorithm, encoding, prefix, signed-string template, timestamp header "github": {"header": "X-Hub-Signature-256", "alg": "sha256", "enc": "hex", "prefix": "sha256=", "template": "{body}", "ts_header": None}, "github-sha1": {"header": "X-Hub-Signature", "alg": "sha1", "enc": "hex", "prefix": "sha1=", "template": "{body}", "ts_header": None}, "shopify": {"header": "X-Shopify-Hmac-Sha256", "alg": "sha256", "enc": "base64", "prefix": "", "template": "{body}", "ts_header": None}, "slack": {"header": "X-Slack-Signature", "alg": "sha256", "enc": "hex", "prefix": "v0=", "template": "v0:{ts}:{body}", "ts_header": "X-Slack-Request-Timestamp"}, "stripe": {"header": "Stripe-Signature", "alg": "sha256", "enc": "hex", "prefix": "", "template": "{ts}.{body}", "ts_header": None}, } SEV_ORDER = {"high": 0, "medium": 1, "low": 2, "info": 3} def scheme_for(ep): base = dict(SCHEMES.get(ep.get("scheme", "generic"), {})) for k in ("header", "alg", "enc", "prefix", "template", "ts_header"): if k in ep: base[k] = ep[k] missing = [k for k in ("header", "alg", "enc", "template") if not base.get(k)] if missing: raise ValueError("endpoint %r: generic scheme needs %s" % (ep.get("name"), ", ".join(missing))) base.setdefault("prefix", "") base.setdefault("ts_header", None) return base def digest(secret, msg, alg, enc): mac = hmac.new(secret.encode("utf-8"), msg.encode("utf-8"), getattr(hashlib, alg)).digest() return mac.hex() if enc == "hex" else base64.b64encode(mac).decode("ascii") def signed_string(sch, body, ts): return sch["template"].replace("{ts}", str(ts or "")).replace("{body}", body) def sign(scheme_name, secret, body, ts=None): sch = scheme_for({"scheme": scheme_name}) sig = digest(secret, signed_string(sch, body, ts), sch["alg"], sch["enc"]) if scheme_name == "stripe": return {sch["header"]: "t=%s,v1=%s" % (ts, sig)} out = {sch["header"]: sch["prefix"] + sig} if sch["ts_header"]: out[sch["ts_header"]] = str(ts) return out def get_header(headers, name): for k, v in headers.items(): if k.lower() == name.lower(): return v return None def parse_stripe(value): ts, sigs = None, [] for part in value.split(","): k, _, v = part.strip().partition("=") if k == "t": ts = v elif k == "v1": sigs.append(v) return ts, sigs def entropy_bits(secret): if not secret: return 0.0 counts = Counter(secret) h = -sum(c / len(secret) * math.log2(c / len(secret)) for c in counts.values()) return h * len(secret) def diagnose(sch, ep, body, ts, received): """Try the usual mistakes and return a human explanation, or None.""" secret = ep["secret"] alg, enc = sch["alg"], sch["enc"] tries = [] for old in ep.get("previous_secrets", []): tries.append(("WH07", "matches a PREVIOUS secret: the sender still signs with the old secret (finish the rotation)", old, signed_string(sch, body, ts), enc)) try: obj = json.loads(body) tries.append(("WH01", "matches the body re-serialized as compact JSON: the sender or your framework parsed and re-encoded the payload before signing/verifying; always use the raw bytes", secret, signed_string(sch, json.dumps(obj, separators=(",", ":")), ts), enc)) tries.append(("WH01", "matches the body re-serialized with default json.dumps spacing: verify against the raw request body, not a parsed object", secret, signed_string(sch, json.dumps(obj), ts), enc)) except ValueError: pass tries.append(("WH01", "matches the body with a trailing newline stripped/added: a proxy or test tool changed the body", secret, signed_string(sch, body.rstrip("\n") if body.endswith("\n") else body + "\n", ts), enc)) if "{ts}" in sch["template"]: tries.append(("WH01", "matches HMAC over the body alone: the timestamp prefix is missing from the signed string", secret, body, enc)) if secret.startswith("whsec_"): tries.append(("WH01", "matches when the 'whsec_' prefix is removed from the secret: check how the secret is loaded", secret[len("whsec_"):], signed_string(sch, body, ts), enc)) tries.append(("WH01", "matches with a trimmed secret: the stored secret has stray whitespace", secret.strip(), signed_string(sch, body, ts), enc)) other = "base64" if enc == "hex" else "hex" tries.append(("WH01", "matches with %s encoding instead of %s: wrong digest encoding" % (other, enc), secret, signed_string(sch, body, ts), other)) for code, why, sec, msg, e in tries: if sec == secret and msg == signed_string(sch, body, ts) and e == enc: continue cand = digest(sec, msg, alg, e) if any(hmac.compare_digest(cand, r) for r in received): return code, why return None def check_delivery(d, ep, now, tolerance, skew, seen_ids): findings = [] def add(code, sev, msg): findings.append({"code": code, "severity": sev, "delivery": d.get("id"), "endpoint": ep.get("name"), "message": msg}) try: sch = scheme_for(ep) except ValueError as e: add("WH00", "high", str(e)) return findings, None headers = d.get("headers", {}) body = d.get("body") if not isinstance(body, str): add("WH00", "high", "body must be the raw request body as a string (not parsed JSON)") return findings, None raw = get_header(headers, sch["header"]) if raw is None: if ep.get("scheme") == "github" and get_header(headers, "X-Hub-Signature"): add("WH06", "medium", "only legacy X-Hub-Signature (HMAC-SHA1) present; enable and verify X-Hub-Signature-256") add("WH02", "high", "missing signature header %s: reject with 401 before doing any work" % sch["header"]) return findings, False ts = None if ep.get("scheme") == "stripe": ts, received = parse_stripe(raw) if not ts or not received: add("WH02", "high", "Stripe-Signature header has no t= or v1= part") return findings, False else: if sch["prefix"] and not raw.startswith(sch["prefix"]): add("WH01", "high", "signature does not start with %r (wrong scheme or algorithm?)" % sch["prefix"]) return findings, False received = [raw[len(sch["prefix"]):]] if sch["ts_header"]: ts = get_header(headers, sch["ts_header"]) if ts is None: add("WH02", "high", "missing timestamp header %s" % sch["ts_header"]) return findings, False if sch["alg"] in ("sha1", "md5"): add("WH06", "medium", "weak HMAC algorithm %s: prefer SHA-256 if the provider supports it" % sch["alg"].upper()) expected = digest(ep["secret"], signed_string(sch, body, ts), sch["alg"], sch["enc"]) valid = any(hmac.compare_digest(expected, r) for r in received) if not valid: hint = diagnose(sch, ep, body, ts, received) if hint and hint[0] == "WH07": add("WH07", "medium", hint[1]) valid = None # authentic but signed with the old secret elif hint: add("WH01", "high", "signature mismatch; likely cause: " + hint[1]) else: add("WH01", "high", "signature mismatch; no common mistake reproduces it: wrong secret for this endpoint, or the body was modified in transit") if ts is not None: try: tsv = int(ts) except ValueError: add("WH00", "high", "timestamp %r is not unix seconds" % ts) tsv = None if tsv is not None and now is not None: age = now - tsv if age > tolerance: add("WH03", "high", "timestamp is %d s old (tolerance %d s): possible replay, reject even if the signature is valid" % (age, tolerance)) elif age < -skew: add("WH05", "medium", "timestamp is %d s in the future (allowed skew %d s): check server clocks (NTP)" % (-age, skew)) event_id = d.get("event_id") or get_header(headers, ep.get("id_header", "X-Webhook-Id") or "") or get_header(headers, "X-GitHub-Delivery") if event_id: key = (ep.get("name"), event_id) if key in seen_ids: add("WH04", "medium", "duplicate event id %s (first seen in delivery %s): process idempotently, do not run side effects twice" % (event_id, seen_ids[key])) else: seen_ids[key] = d.get("id") else: add("WH10", "low", "no event/delivery id: cannot de-duplicate retries; store a hash of the body or ask the provider for an id header") limit = ep.get("max_body_bytes") if limit and len(body.encode("utf-8")) > limit: add("WH11", "low", "body is %d bytes, above max_body_bytes %d" % (len(body.encode("utf-8")), limit)) return findings, valid def check_endpoint(ep): out = [] def add(code, sev, msg): out.append({"code": code, "severity": sev, "delivery": None, "endpoint": ep.get("name"), "message": msg}) url = ep.get("url", "") if url and not url.lower().startswith("https://"): add("WH09", "high", "endpoint URL is not HTTPS (%s): signatures do not hide the payload" % url) sec = ep.get("secret", "") if not sec: add("WH00", "high", "no secret configured") elif len(sec) < 24 or entropy_bits(sec) < 96: add("WH08", "medium", "secret is short or low-entropy (%d chars, ~%d bits): generate at least 32 random bytes" % (len(sec), entropy_bits(sec))) if ep.get("scheme") == "github-sha1": add("WH06", "medium", "endpoint configured for HMAC-SHA1 only") return out def to_epoch(s): return int(datetime.fromisoformat(s.replace("Z", "+00:00")).astimezone(timezone.utc).timestamp()) def run(data, now_override=None): eps = {} for name, ep in data.get("endpoints", {}).items(): ep = dict(ep); ep["name"] = name; eps[name] = ep now = to_epoch(now_override) if now_override else (to_epoch(data["now"]) if data.get("now") else int(datetime.now(timezone.utc).timestamp())) tol = int(data.get("tolerance_seconds", 300)); skew = int(data.get("future_skew_seconds", 60)) findings, results, seen = [], [], {} for ep in eps.values(): findings += check_endpoint(ep) for d in data.get("deliveries", []): ep = eps.get(d.get("endpoint")) if ep is None: findings.append({"code": "WH00", "severity": "high", "delivery": d.get("id"), "endpoint": d.get("endpoint"), "message": "unknown endpoint"}) results.append({"delivery": d.get("id"), "verdict": "error"}); continue f, valid = check_delivery(d, ep, now, tol, skew, seen) findings += f hard = any(x["severity"] == "high" for x in f) verdict = "reject" if hard else ("accept-rotate-secret" if valid is None else ("accept" if valid else "reject")) if any(x["code"] == "WH04" for x in f) and verdict.startswith("accept"): verdict = "accept-duplicate(skip side effects)" results.append({"delivery": d.get("id"), "endpoint": ep["name"], "verdict": verdict}) findings.sort(key=lambda x: (SEV_ORDER[x["severity"]], x["code"], str(x["delivery"]))) summary = Counter(x["severity"] for x in findings) return {"now": now, "tolerance_seconds": tol, "results": results, "findings": findings, "summary": {k: summary.get(k, 0) for k in ("high", "medium", "low")}} def print_text(rep): print("Webhook verification report (now=%s, tolerance %ss)" % (datetime.fromtimestamp(rep["now"], timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"), rep["tolerance_seconds"])) print("\nDeliveries:") for r in rep["results"]: print(" %-6s %-14s %s" % (r["delivery"], r.get("endpoint", "?"), r["verdict"])) print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"]) for f in rep["findings"]: where = f["delivery"] or ("endpoint " + str(f["endpoint"])) print(" [%s] %s %s: %s" % (f["severity"].upper(), f["code"], where, f["message"])) def self_test(): ok = 0; total = 0 def t(name, cond): nonlocal ok, total total += 1; ok += bool(cond) print(("PASS " if cond else "FAIL ") + name) sec = "whsec_selftest_7f3a9c2e5b1d48a6b0c4e2f19d7a3b58" body = '{"id":"evt_1","type":"invoice.paid","amount":4200}' ts = 1794560400 def rep_for(dels, eps=None, now=ts + 10): eps = eps or {"s": {"scheme": "stripe", "secret": sec, "url": "https://x.test/hook"}} return run({"endpoints": eps, "deliveries": dels}, datetime.fromtimestamp(now, timezone.utc).isoformat()) good = {"id": "a", "endpoint": "s", "event_id": "evt_1", "headers": sign("stripe", sec, body, ts), "body": body} r = rep_for([good]); t("stripe valid accepted", r["results"][0]["verdict"] == "accept" and r["summary"]["high"] == 0) r = rep_for([good], now=ts + 900); t("WH03 stale timestamp", any(f["code"] == "WH03" for f in r["findings"])) r = rep_for([good], now=ts - 600); t("WH05 future timestamp", any(f["code"] == "WH05" for f in r["findings"])) r = rep_for([good, dict(good, id="b")]); t("WH04 duplicate id", any(f["code"] == "WH04" for f in r["findings"]) and r["results"][1]["verdict"].startswith("accept-duplicate")) pretty = json.dumps(json.loads(body)) bad = dict(good, id="c", body=pretty, headers=sign("stripe", sec, body, ts)) r = rep_for([bad]); t("WH01 re-serialized body diagnosed", any(f["code"] == "WH01" and "re-serialized" in f["message"] for f in r["findings"])) eps = {"g": {"scheme": "github", "secret": sec, "previous_secrets": ["old_secret_value_1234567890abcdef"], "url": "https://x.test/gh"}} old = {"id": "d", "endpoint": "g", "event_id": "g1", "headers": sign("github", "old_secret_value_1234567890abcdef", body), "body": body} r = rep_for([old], eps); t("WH07 previous secret", any(f["code"] == "WH07" for f in r["findings"]) and r["results"][0]["verdict"] == "accept-rotate-secret") nohdr = {"id": "e", "endpoint": "g", "event_id": "g2", "headers": {"X-Hub-Signature": "sha1=abc"}, "body": body} r = rep_for([nohdr], eps); t("WH02 + WH06 legacy sha1 only", {"WH02", "WH06"} <= {f["code"] for f in r["findings"]}) eps2 = {"sl": {"scheme": "slack", "secret": "short", "url": "http://x.test/slack"}} sl = {"id": "f", "endpoint": "sl", "headers": sign("slack", "short", body, ts), "body": body} r = rep_for([sl], eps2); codes = {f["code"] for f in r["findings"]} t("slack valid + WH08 weak secret + WH09 http + WH10 no id", {"WH08", "WH09", "WH10"} <= codes and "WH01" not in codes) nots = {"id": "g", "endpoint": "s", "event_id": "e9", "headers": {"Stripe-Signature": "t=%d,v1=%s" % (ts, digest(sec, body, "sha256", "hex"))}, "body": body} r = rep_for([nots]); t("WH01 missing timestamp in signed string diagnosed", any("timestamp prefix" in f["message"] for f in r["findings"])) eps3 = {"sh": {"scheme": "shopify", "secret": sec, "url": "https://x.test/shop"}} hexsig = {"id": "h", "endpoint": "sh", "event_id": "s1", "headers": {"X-Shopify-Hmac-Sha256": digest(sec, body, "sha256", "hex")}, "body": body} r = rep_for([hexsig], eps3); t("WH01 hex vs base64 diagnosed", any("encoding" in f["message"] for f in r["findings"])) eps4 = {"gen": {"scheme": "generic", "header": "X-Signature", "alg": "sha512", "enc": "hex", "prefix": "", "template": "{body}", "secret": sec, "url": "https://x.test/g"}} gen = {"id": "i", "endpoint": "gen", "event_id": "x1", "headers": {"X-Signature": digest(sec, body, "sha512", "hex")}, "body": body} r = rep_for([gen], eps4); t("generic sha512 scheme accepted", r["results"][0]["verdict"] == "accept") print("%d/%d passed" % (ok, total)) return 0 if ok == total else 1 def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("file", nargs="?") ap.add_argument("--now"); ap.add_argument("--json", action="store_true") ap.add_argument("--sign", choices=sorted(SCHEMES)); ap.add_argument("--secret"); ap.add_argument("--body-file"); ap.add_argument("--timestamp", type=int) ap.add_argument("--self-test", action="store_true") a = ap.parse_args() if a.self_test: return self_test() if a.sign: if not (a.secret and a.body_file): print("--sign needs --secret and --body-file", file=sys.stderr); return 2 body = open(a.body_file, encoding="utf-8", newline="").read() ts = a.timestamp or int(datetime.now(timezone.utc).timestamp()) print(json.dumps(sign(a.sign, a.secret, body, ts), indent=2)); return 0 if not a.file: ap.print_help(); return 2 try: with open(a.file, encoding="utf-8") as fh: data = json.load(fh) rep = run(data, a.now) except (OSError, ValueError, KeyError) as e: print("bad input: %s" % e, file=sys.stderr); return 2 if a.json: print(json.dumps(rep, indent=2)) else: print_text(rep) return 1 if rep["summary"]["high"] else 0 if __name__ == "__main__": sys.exit(main())

Release Management taste

# Release Management taste of a maintainer who wants boring, predictable releases - Follow Semantic Versioning strictly for libraries; a breaking change always means a new major version. Confidence: 0.90 - Use calendar versioning for apps and services that users never install by version number. Confidence: 0.70 - Write commit messages in the Conventional Commits format so changelogs and version bumps can be generated. Confidence: 0.75 - Keep a human-edited `CHANGELOG.md` with Added, Changed, Fixed and Removed sections; generated notes are a draft, not the final text. Confidence: 0.80 - Cut releases from the main branch with an annotated, signed Git tag; never release from a laptop's local branch. Confidence: 0.90 - Let CI build, test and publish the release artifact from the tag, so nobody runs a manual publish command. Confidence: 0.90 - Build the artifact once and promote the same build from staging to production instead of rebuilding per environment. Confidence: 0.90 - Release small and often; a weekly release with ten changes is safer than a quarterly release with five hundred. Confidence: 0.85 - Put unfinished features behind flags so the release train never waits for one late feature. Confidence: 0.80 - Keep a written, tested rollback plan for every release, and prefer rolling back over fixing forward under pressure. Confidence: 0.85 - Make database migrations backward compatible so the previous version can still run after a rollback. Confidence: 0.90 - Mark deprecations one minor version before removal and print a clear warning with the replacement. Confidence: 0.85 - Use release candidates for risky major versions and give real users time to try them. Confidence: 0.70 - Roll out to a small canary group first and watch error rates before going to everyone. Confidence: 0.80 - Freeze releases on Friday afternoons and before holidays unless the change is a security fix. Confidence: 0.65 - Ship security fixes as patch releases for every supported version, not only the latest one. Confidence: 0.85 - Publish a short support policy that says which versions still get fixes and for how long. Confidence: 0.75 - Never move or delete a published tag or package version; publish a new one instead. Confidence: 0.95 - Automate the release checklist in CI and keep any remaining manual steps written in the repo. Confidence: 0.80 - Announce each release with the user-facing changes first and the upgrade steps right below them. Confidence: 0.75

AUTOMATION

So,I want an AI to go through a piece of document meticulously and extensively, now the piece of document is about a project that I am supposed to work on and automate a workflow for, I also do nor want it to skip any point and I need step by step process on how to properly execute the project with my team

Marry too early

There was this girl who married early people were making mocking of her

Trade Show Booth Plan Builder (YAML)

role: >- Trade show planner for small companies and founders. You turn one upcoming trade show or conference into a practical booth plan that a team of two to five people can run, with a clear goal, a realistic budget, a lead capture process and a follow-up plan that actually turns booth conversations into meetings and revenue. event: name: "${event_name:Regional SaaS and IT Expo}" city: "${city:Lyon}" dates: "${event_dates:3 days, 10-12 March}" expected_visitors: "${visitors:about 6,000, mostly IT managers and operations leads}" booth: "${booth_size:3x3 m shell scheme booth near the cafe area}" cost_already_paid: "${booth_cost:4,800 EUR booth fee}" company: product: "${product:a scheduling and dispatch tool for field service teams}" stage: "${stage:seed stage, 40 paying customers}" ideal_customer: "${icp:field service companies with 20-200 technicians}" average_deal_size: "${deal_size:9,000 EUR per year}" team_attending: "${team:2 founders and 1 sales hire}" extra_budget: "${extra_budget:6,000 EUR for travel, graphics, giveaways and demo gear}" main_goal: "${goal:book 25 qualified demo meetings within 3 weeks after the show}" instructions: - >- Ask up to 5 short questions about anything above that is missing or unclear, then wait for my answers before producing the plan. - >- Produce the plan as one valid YAML document that follows output_schema exactly, with no text before or after it. - >- Work back from main_goal: estimate booth conversations per hour, the share that will be qualified, and the meetings this realistically produces. If the goal is not reachable with this team and booth, say so in risks and suggest a smaller goal or a change (pre-booked meetings, a talk slot, a partner booth). - >- Keep the budget inside extra_budget and show every line item with an estimate in the event currency. Mark items that can be skipped. - >- Booth messaging must fit on a banner readable from 5 metres: one headline of at most 8 words naming the customer problem, one proof point, and one call to action. No jargon. - >- Lead capture must record only what the team needs to follow up and must respect local privacy rules: ask consent for follow-up, do not scan badges without telling the visitor, and note where data is stored. - >- Every booth shift needs a named role (greeter, demo lead, closer or break cover) and nobody works more than 3 hours without a break. - >- Follow-up messages must reference what the visitor actually said at the booth, so the qualification notes must capture that. output_schema: summary: goal: "one sentence" realistic_outcome: "expected conversations, qualified leads and meetings" go_or_rethink: "go | go_with_changes | rethink" pre_show: timeline: - when: "e.g. 6 weeks before" task: "what to do" owner: "who" pre_booked_meetings: target_count: 0 outreach_plan: "who to invite and how" invite_message: "short message, under 90 words" logistics_checklist: - "item" booth: layout: "where the screen, table, banner and storage go" banner: headline: "8 words or fewer" proof_point: "one line" call_to_action: "one line" demo: length_minutes: 0 script_steps: - "step" giveaway: "item and why it attracts the right visitors, or none" shift_schedule: - day: "Day 1" slot: "09:00-12:00" greeter: "name" demo_lead: "name" notes: "anything special, e.g. keynote break rush" lead_capture: tool: "app, form or paper card" fields: - name: "field name" why: "how it is used in follow-up" qualification_questions: - "question" lead_grades: hot: "definition" warm: "definition" cold: "definition" consent_wording: "one sentence read or shown to the visitor" budget: items: - item: "name" estimate: 0 optional: false total: 0 cost_per_target_meeting: 0 follow_up: within_24_hours: - "action" sequence: - day: 1 channel: "email | call | LinkedIn" audience: "hot | warm | cold" message: "short template using the visitor's own booth notes" tracking: "how meetings and deals from this show are tagged in the CRM" review: metrics: - "metric and target" debrief_questions: - "question for the team meeting one week after the show" risks: - risk: "what could go wrong" mitigation: "what we do about it" constraints: tone: "practical, honest, no hype" currency: "${currency:EUR}" language: "${language:English}" avoid: - "inventing visitor numbers or results not given or estimated with stated assumptions" - "giveaways that attract only freebie hunters" - "lead fields the team will never use"

1910s Autochrome of an Apple Orchard in Blossom with an Empty Picnic Table

A 1910s Autochrome Lumière color photograph of an old apple orchard in full blossom on a calm, overcast spring afternoon. In the right foreground stands a weathered wooden picnic table with attached benches, its grey planks cracked and silvered with age. A purple-and-white gingham cloth is draped across it, hanging over the near edge, and on it rest a large woven wicker picnic basket with a looped handle and a plain white enamel jug. Behind and to the left, gnarled apple trees with dark twisting trunks are covered in pale pink and white blossom and recede in soft, even rows into a hazy distance; the grass between them is carpeted with small violet wildflowers. Render it exactly like a real Autochrome glass plate: muted, faded sepia-pastel colors (dusty pinks, mauve and violet, soft olive and sage greens, warm brown shadows, a pale milky sky), the visible random grain of dyed potato-starch particles that makes every area look softly speckled, fine dust specks across the surface, gentle soft focus from a long exposure, low contrast, and a thick dark vignette with rounded, burnt-looking edges around the whole frame. Diffuse daylight, no harsh shadows. No people, no text, no modern objects. Landscape 4:3.

Branding

Learning branding and building a firm that deals with branding

Florentine Pietra Dura Inlay of a Pomegranate Branch with Goldfinches

A Florentine pietra dura (commesso) hardstone inlay panel seen straight from above, in the style of 17th-century Medici grand-ducal workshops. The ground is deep black marble crossed by fine white and grey veins. A brown stone branch, built from many small fitted segments, runs diagonally from the upper left to the lower right. Two European goldfinches perch side by side on it, facing right: red faces, black-and-white heads, warm tan breasts, and black wings with bright yellow bars and white spots, all made of separate pieces of coral, onyx, alabaster, Siena marble and yellow jasper. Below them hangs one large ripe pomegranate in mottled red-brown jasper, split open to show its pale pith and clusters of glossy deep-red seeds cut as tiny polished garnet-like stones. Pointed leaves in veined green jasper and malachite branch off on both sides, their light and dark tones following the natural grain of the stone. Every shape reads as a separate, precisely fitted piece of cut stone with hairline seams and no paint. A narrow square border frames the panel: thin gold-toned bands enclosing a scrolling vine of small inlaid rosettes and tendrils on black. Soft, even museum lighting, rich saturated stone colors, crisp detail. No text, no signature. Square 1:1.

Wild Horses Galloping Through Shallow Surf at Dawn

Photorealistic wide wildlife photograph at sunrise of a herd of nine wild horses galloping through shallow surf along an empty, wide sandy beach. Eight horses run close together in a loose line, moving left to right and slightly toward the camera, legs mid-stride: most are black and dark brown, with three dappled grey horses among them, all with long, wild, wind-tossed manes. A ninth dark horse runs alone a little further back on the right. Their hooves kick up bright arcs and sheets of spray that are frozen in the air and glow in the backlight. The sun sits low on the horizon at the far left, flooding the scene with a soft peach and apricot haze; a band of sea mist hangs over the water and hides the distant low hills. Small waves roll in from the left in thin lines, and the wet sand in the foreground is a smooth mirror that reflects the horses' dark legs and the pale sky. Camera: telephoto lens at about 300-400 mm, low angle near sand level, fast shutter speed, the herd sharp and the background soft; warm golden highlights, soft muted shadows, fine detail in wet coats and droplets, gentle atmospheric haze. Peaceful but powerful mood. No people, no riders, no saddles or tack, no fences, no buildings, no text. Landscape 16:9.

Single-Shot Speeder Chase Through a Cliffside Stone City Ending in a Waterfall Valley Reveal

Speeder chase across a cliff city (single continuous shot) From a monumental cliffside city carved into stone, the camera dives toward a tiny streak of light ripping along a narrow ledge-road. Lock-on: a speeder hugging the wall at insane speed. The camera slingshots ahead, whips back, then drops tight to the rear thrusters: heat haze, grit snapping off the ledge, warning lights flashing. A collapsing balcony rains debris; the rider snaps a last-inch swerve under a falling arch, then threads through hanging laundry lines and open windows in one fluid line. The camera darts through the same openings, staying glued to the motion. One final bend and sudden calm: the camera blasts outward into a reveal of the city opening onto a boundless waterfall-fed valley, mist turning into rainbow.

My mini peoject

--- name: my-mini-peoject description: Pro --- # My mini peoject Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...

Design a wellness resort

I'm architecture student and I have a project of resort design in my design subject so this is my site and the north is upward side and the location is near Palampur Himachal Pradesh and no I have to design a resort in this site in which I hai to make a service room, reception, gazebo, open seating area 1 meditation hall, 4, 5 treatment room, 4 double cottages and 3 single cottages, 1 cafe and restaurant and also design a good landscape, or garden

Screenshot-Guided GitHub Repo Edit Assistant

take over my computer again. go to edge, i am currently on the github repo page. screenshot where i have to make these changes and what i have to change and insert. circle them and show me on the side.

Factory Operator AI Simulator Builder (Single-File Web HMI)

--- name: factory-ai-hmi-simulator description: Builds a zero-dependency, single-file HTML5 Web HMI (Human-Machine Interface) training simulator for factory operators to practice operating, reading, and responding to industrial AI systems under strict source-grounding and progressive disclosure rules. --- # Factory Operator AI Training Simulator Builder You are an Industrial Automation & EdTech Frontend Architect. Your objective is to generate a self-contained, single-file HTML5 web application (`index.html`) simulating a factory production line AI HMI dashboard for desktop PC training. ## 1. Strict Source-Grounding & Anti-Hallucination Guardrails - **Strict Grounding (`strict_sources_only`)**: Base all SOP steps, machine thresholds, defect classifications, and training scenarios strictly on the provided source documents or user specifications. If industry-specific parameters (e.g., exact temperature limits, product names) are missing from the source, use generic placeholders clearly marked with `${adjust_to_sop}` rather than inventing technical figures. - **Zero External Dependencies (No CDN Hallucinations)**: Strictly prohibit external `<script src="...">`, `<link rel="stylesheet">`, external fonts, or external image URLs. All styling (CSS), vector graphics (inline `<svg>`), and interactivity (Vanilla ES6+ JavaScript) must be embedded within the single HTML file so it runs 100% offline in Chrome/Edge kiosk mode (`F11`). ## 2. Native Progressive Disclosure Architecture To keep the primary `SKILL.md` lean and preserve context window efficiency, load auxiliary specifications only when triggered by the user's request or source complexity: - **Default Mode (Core Simulator)**: Generate the standard 3-zone HMI + Instructor Panel using inline CSS/SVG. - **Trigger: Specific Industry Customization** (e.g., F&B, Automotive, Electronics, Textiles) -> Load `references/industry-presets.md` to map sensor metrics, defect types, and terminology. - **Trigger: Advanced Telemetry & Evaluation Mode** (e.g., reaction timer, scoring rubric export, multi-stage SOP drills) -> Load `references/evaluation-rubric.md` to inject JavaScript reaction-time tracking and CSV/JSON score logging. - **Trigger: Complex UI Layout & Visual Components** -> Load `assets/hmi-ui-tokens.css` for industrial dark-mode color variables and inline SVG conveyor/gauge templates. ## 3. Core Functional Specification (HMI Layout) Generate the standalone HTML file with four mandatory, cleanly separated visual zones: 1. **Header Status Bar**: - Displays Machine/Line ID, active shift, and a high-visibility system status badge (`NORMAL` in `#16a34a`, `WARNING` in `#eab308`, `CRITICAL` in `#dc2626`). 2. **Zone 1: AI Computer Vision (Quality Inspection)**: - Animated CSS/SVG conveyor belt simulation with moving product items. - AI bounding box overlay displaying detection label and **Confidence Score (%)**. - Operator action controls: **Override / Mark as Good** (to correct false alarms) and **Confirm Reject** (to discard confirmed defects). 3. **Zone 2: Predictive Maintenance (Machine Health)**: - Real-time telemetry cards (e.g., Motor Vibration, Bearing Temperature) with explicit safe threshold labels derived from sources. - Interactive conveyor speed slider (`50%–100%`) dynamically affecting telemetry values during warning drills. - SOP action controls: **Acknowledge Alarm** and **Send Maintenance Ticket**. 4. **Zone 3: AI SOP Co-Pilot & System Log**: - Interactive quick-prompt SOP assistant answering operator queries strictly from the grounded SOP rules. - Scrollable, timestamped terminal log recording every state change, alert, and operator action. 5. **Bottom Instructor Control Bar**: - Discrete trainer panel to trigger live scenarios on demand: - `Reset Normal`: Restores baseline production state. - `Trigger False Alarm`: Good item flagged with low Confidence Score (`<65%`), testing visual verification and Override action. - `Trigger Real Defect`: Defective item flagged with high Confidence Score (`>90%`), testing prompt Rejection. - `Trigger Predictive Warning`: Abnormal sensor spike, testing the exact SOP sequence (`Acknowledge` -> `Reduce Speed` -> `Send Ticket`). ## 4. Execution Workflow 1. **Extract & Ground**: Parse the user's prompt and attached NotebookLM sources for industry domain, language preference (default: Bahasa Indonesia), sensor thresholds, and SOP workflows. 2. **State-Validation Logic**: Implement strict JavaScript state guards so the simulator provides immediate corrective feedback if an operator executes the wrong action (e.g., rejecting a false alarm or overriding a high-confidence defect). 3. **Output Delivery**: Provide the complete, untruncated HTML code inside a single `html` code block, followed by a concise 3-step guide for saving as `.html` and launching in browser full-screen (`F11`).

Gyotaku Ink Fish Print of a Red Sea Bream and Two Mackerel on Washi Paper

A traditional Japanese gyotaku fish print, made by inking real fish and pressing thin washi paper onto them, photographed flat as a finished artwork. Horizontal 4:3 composition on a sheet of warm off-white handmade washi with visible long kozo fibers, soft deckled edges and a faint crease. Subject: one red sea bream (madai) printed large across the center, facing left, with two smaller mackerel side by side below it, also facing left. The prints are in deep sumi black ink with the true gyotaku texture: every scale pressed as a fine crescent pattern, fin rays as delicate radiating lines, the gill plate and lateral line clearly embossed, slightly uneven ink density where the paper touched the body more or less firmly, a few dry-brush gaps and soft halos at the edges. The sea bream carries a soft vermilion-red wash over its whole body, fading paler toward the belly; each fish has a small hand-painted eye added with a fine brush, as in classic gyotaku. Details: a vertical column of brushed Japanese-style calligraphy marks at the right edge is abstract and illegible, with one small red square seal stamp beneath it. Light ink speckles near the fins. Lighting: even, soft, flat museum reproduction light, true colors, high detail, the paper texture visible across the whole sheet. No frame, no table, no hands, no readable text.

Folk Reverse Glass Painting of Sunflowers in a Cobalt Jug on Gold Leaf

A folk-art reverse glass painting (Hinterglasmalerei) of a bouquet of sunflowers in a cobalt-blue jug, painted on the back of an old glass pane and seen from the front, so the colors sit behind a glossy glass surface. Vertical 3:4 composition. Subject: nine sunflowers with bright chrome-yellow petals and dark brown, finely dotted centers, a few buds and broad green leaves with crisp darker veins, arranged in a round-bellied cobalt-blue jug with white painted daisies around its belly. The jug stands on a simple brick-red tabletop band at the bottom of the picture. Technique: bold black outlines painted first, then flat opaque layers of color with no blending, the typical naive folk style of reverse glass painting; the background is a sheet of gilded gold-leaf foil behind the glass, crinkled and shimmering, with a few visible seams. A painted border of small red and white dots runs around the edge, framed by a narrow dark wooden frame. Surface: slight reflections and soft glare on the glass, tiny bubbles and a hairline scratch in the old pane, a little paint flaking at one corner that reveals the gold behind. Lighting: soft daylight from the upper left, warm glow on the gold, rich saturated colors. No people, no text.

Starling Murmuration over a Winter Reed Bed at Sunset

A photorealistic wide landscape photograph of a vast starling murmuration over a winter reed bed at sunset, 16:9, captured as a single still moment that is ready to be animated. Scene: tens of thousands of European starlings form one huge, dense, flowing cloud shaped like a twisting ribbon that folds back on itself in the upper center of the sky, darker where the birds bunch together and thinning to scattered specks at the edges. Below, a flat wetland of tall pale golden reeds and feathery seed heads stretches to the horizon, cut by a still, winding channel of water that mirrors the sky and a dark silhouette of the flock. A line of bare winter trees stands on the far left of the horizon. Light and sky: the sun has just set behind the reeds at the right, leaving a band of glowing orange and peach above the horizon that fades upward into soft lavender and cool blue; thin wispy clouds catch pink light. Camera: shot from a low riverbank with a 35 mm lens, deep focus, the reed tops sharp in the foreground, natural colors, fine detail in each bird speck, calm atmosphere. No people, no buildings, no text.

Kotlin Coroutines taste

# Kotlin Coroutines taste of an Android and JVM engineer who wants structured concurrency everywhere - Launch coroutines only from a scope tied to a lifecycle, such as `viewModelScope`, `lifecycleScope` or a scope owned by a service. Confidence: 0.95 - Never use `GlobalScope`; if work must outlive a screen, hand it to an application-level scope or WorkManager. Confidence: 0.95 - Make suspend functions main-safe: the function itself switches to `Dispatchers.IO` or `Default` with `withContext`, not the caller. Confidence: 0.90 - Inject dispatchers through the constructor so tests can replace them with a `TestDispatcher`. Confidence: 0.90 - Use `coroutineScope` for parallel work that should fail together, and `supervisorScope` only when children must fail independently. Confidence: 0.85 - Never swallow `CancellationException`; rethrow it from every broad `catch` block. Confidence: 0.95 - Prefer `async`/`await` only for real parallel decomposition, not as a replacement for a plain suspend call. Confidence: 0.80 - Expose UI state as `StateFlow` and one-off events through a `Channel` or a state field that the UI consumes. Confidence: 0.80 - Collect flows in the UI with `repeatOnLifecycle(Lifecycle.State.STARTED)` or `collectAsStateWithLifecycle`. Confidence: 0.90 - Use `stateIn` with `SharingStarted.WhileSubscribed(5_000)` so upstream work stops when nobody is watching. Confidence: 0.80 - Keep flows cold by default and convert to hot with `shareIn` or `stateIn` only at a clear boundary. Confidence: 0.80 - Apply `flowOn` to move upstream work off the main thread instead of wrapping collectors in `withContext`. Confidence: 0.80 - Wrap blocking Java APIs in `withContext(Dispatchers.IO)` and never call `runBlocking` in production code paths. Confidence: 0.90 - Add timeouts to network and database calls with `withTimeout` or `withTimeoutOrNull`, not hand-rolled delays. Confidence: 0.75 - Check `ensureActive()` or `yield()` inside long CPU loops so cancellation actually stops the work. Confidence: 0.80 - Protect shared mutable state with a `Mutex` or confine it to a single coroutine, never a plain `synchronized` block around a suspend call. Confidence: 0.85 - Install a `CoroutineExceptionHandler` at the root scope to log crashes, but handle expected errors with `Result` or sealed types. Confidence: 0.75 - Test coroutines with `runTest` and virtual time, and test flows with Turbine. Confidence: 0.85 - Name important coroutines with `CoroutineName` so logs and debugger output stay readable. Confidence: 0.65 - Keep suspend functions free of `launch` side effects; a function that starts background work should say so in its name. Confidence: 0.75

Database Backup and Restore taste

# Database Backup and Restore taste of an SRE who only trusts backups that have been restored - A backup does not count until it has been restored successfully; schedule automated restore tests at least weekly. Confidence: 0.95 - Write down the RPO and RTO for every database and choose the backup method that meets them, not the other way around. Confidence: 0.90 - Combine full base backups with continuous WAL or binlog archiving so you can restore to any point in time. Confidence: 0.90 - Use proven tools like pgBackRest, WAL-G or managed snapshots instead of a hand-written `pg_dump` cron job for large databases. Confidence: 0.85 - Keep logical dumps as a second layer for single-table restores and cross-version migrations. Confidence: 0.75 - Follow the 3-2-1 rule: three copies, two storage types, one copy in another region or account. Confidence: 0.90 - Store backups in a separate cloud account with write-once or object-lock retention so an attacker cannot delete them. Confidence: 0.90 - Encrypt every backup at rest and in transit, and keep the encryption keys somewhere the backups themselves do not live. Confidence: 0.95 - Never take backups from the primary when a replica can serve them, but check that the replica is not lagging. Confidence: 0.75 - Alert when a backup is missing, late, smaller than expected or fails verification, not only when the job exits non-zero. Confidence: 0.90 - Record checksums for each backup and verify them before marking the backup as good. Confidence: 0.85 - Keep a written, tested runbook for a full restore that someone on call can follow at 3 a.m. Confidence: 0.90 - Time every restore drill and track the duration as a metric against the RTO. Confidence: 0.80 - Use tiered retention, for example daily for two weeks, weekly for three months and monthly for a year. Confidence: 0.75 - Restore into an isolated environment first and run sanity queries before touching production. Confidence: 0.85 - Back up roles, grants, extensions and configuration along with the data, or the restore will not actually run. Confidence: 0.80 - Mask or delete personal data in restored copies used for staging and debugging. Confidence: 0.85 - Treat backup deletion as a privileged action that needs two people. Confidence: 0.70 - Include schema migration state in the backup so the application and database versions match after a restore. Confidence: 0.70

Naming invitation

LUXURY MODERN AFRICAN TRADITIONAL NAMING INVITATIONS NAME: AISHA FAROUQ (NANA) ADDRESS: Road 1i house number 5 Apo supercell Estate DATE: 21st NOVEMBER 2026

Community collection: awesome-chatgpt-prompts (CC0, refreshed hourly from GitHub).