Pixel

Pixel Updates & Events

Server Updates & Events

Announcements

Shopify 5% Prepay Discount: What the Data Revealed

DEV Community

I offered 5% off to move shoppers off cash on delivery. The numbers surprised me

In Pakistan, cash on delivery isn't one payment option among many. On the store I run tech for, a bookstore, it's 655 of the last 855 orders. That's 77%. COD is expensive. Couriers collect the cash and pay it out later, refused parcels come back at your cost, and you hold stock for orders that may never be paid for. So I built the obvious fix: pay online and save 5%. The data was not what I expected. What I built The shopper ticks a toggle on the product page or in the cart drawer. Two Shopify Functions read that choice: An order discount (purchase.order-discount.run) that takes 5% off the order A payment customization (purchase.payment-customization.run) that hides COD, so nobody takes the discount and then pays cash anyway Both read one shared signal, a cart attribute: await fetch('/cart/update.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ attributes: { prepay_discount: 'true' } }),
keepalive: true,
});
The toggle on the product page and the one in the cart drawer stay in sync through a single document event, so they never disagree. The bug that only shoppers found Tick the toggle, hit Buy Now straight away, and the page left before the /cart/update.js request finished. The box looked ticked, but checkout had no discount and still showed COD. keepalive alone didn't fix it. What did: keep the in-flight request as a promise, and hold the form's submit until it settles. form.addEventListener('submit', async (e) => {
if (!pending) return;
e.preventDefault();
await pending;
form.requestSubmit(e.submitter);
});
One more lesson: /cart/clear.js empties the items but keeps cart attributes. My first clean test passed only because an old attribute was still sitting in the cart. I retested in a brand-new browser profile. The numbers (last 30 days) Checkouts Started Completed Conversion Opted in to pay online 126 61 48% Everyone else 973 794 82% The shoppers I gave money to finished checkout far less often than the ones who paid cash. A second detail surprised me more. 98 orders were paid by card or wallet, but only 61 used the discount. So 37 people paid online and never took the 5%. The people happy to prepay weren't the ones the discount was moving. What I think is happening To be clear, this isn't an A/B test. It compares two groups that chose themselves. My guesses: Removing COD removes the safety net. At checkout, a shopper who opted in sees one option: the gateway. If a bank OTP fails or a wallet times out, there's no fallback, so they leave. 5% doesn't buy trust. For someone who has never ordered from you, paying first is a risk. A small discount doesn't cancel it. Abandoned checkouts include retries. Some of those 65 may have come back and paid COD in a fresh checkout. What I couldn't build The cleaner design is a discount that applies only when the shopper actually pays online, with COD still visible. That needs to know the chosen payment method, which needs checkout extensibility, which on a custom app needs Shopify Plus. This store isn't on Plus. So the opt-in toggle is the best version available. The store owner looked at the numbers and kept it, because 61 prepaid orders are 61 orders that can't be refused at the door. What I'm changing next This part is planned. It isn't live yet. The obvious fix is to stop hiding cash on delivery. Bank OTPs fail in Pakistan more often than anyone likes, and a shopper whose payment just failed should still have a way to finish the order. There's a catch, and it's the Plus limit from above: the discount can't see which payment method gets picked. With COD visible, someone can tick the toggle, take the 5%, and still pay cash. I don't know how many will. Nobody does until it runs. So the test looks like this: COD stays visible next to the toggle, with one line under it: "Payment didn't go through? Cash on delivery is still available." For a fixed window, I compare by payment choice: checkouts started, checkouts completed, ...

Powered by Readybot.io

Shopify 5% Prepay Discount: What the Data Revealed

How to Get an Accurate Claude Code Token Count

DEV Community

Why your Claude Code token count is wrong (and how to get the real number)

Originally published at neverpaytwice.pages.dev. Short answer: Claude Code writes each AI response to its log several times, and every copy carries the full token count. If you add up every line, you count most responses two or more times. On the made-up sample log in our free scripts repo (30 responses, each logged 2 to 4 times, as Claude Code does), a plain sum says 5.3M tokens. The real figure is 1.8M. To get the right number, count each response once. Our free counter does that in your browser, or use the short script below. Where Claude Code keeps its usage logs Claude Code keeps a local log of every session. They live in a hidden folder in your home directory: System Folder Mac and Linux ~/.claude/projects Windows %USERPROFILE%.claude\projects Inside there is one folder per project, holding .jsonl files (mostly one per session). Each line is one JSON event. Lines for AI responses carry a usage block with four token counts: input_tokens: new input sent to the model output_tokens: what the model wrote back cache_creation_input_tokens: input written to the prompt cache cache_read_input_tokens: input read back from the cache (much cheaper than new input) Why adding up the logs gives the wrong answer It looks simple: add the usage numbers on every line. But three things in how the logs are written make that total too high. One response, several lines. A single response is written once per content block: thinking, text, and each tool call. Every one of those lines repeats the usage of the whole response. A response with a thinking block, some text and two tool calls can appear four times. Resumed sessions copy their history. When you resume a session, earlier lines can be copied into a new log file, so the same response shows up in more than one file. Early lines are incomplete. While a response streams, the first lines can carry a partial output count. Only the last one is final, so even picking "any one line" can under-count output. None of this means you were billed twice. Each response is one request to the API. The over-count only appears when you total the log lines yourself, for example to estimate spending or build a dashboard. How to count correctly Every response line carries a message.id and a requestId. Together they identify one response. So: Keep one record per (message.id, requestId) pair, across all files. For its output tokens, use the largest value seen for that pair (the final streaming count). Skip lines that are not real responses: "model": "" and API error messages. A short script to do it yourself This Python 3 script follows the rules above. It only reads your logs and prints three numbers. (Download it, or get it with the other scripts on GitHub.) import json, pathlib, sys

root = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else pathlib.Path.home() / ".claude" / "projects"
best, plain = {}, 0

for f in sorted(root.rglob("*.jsonl")):
n = 0
for line in f.open(encoding="utf-8", errors="replace"):
try:
o = json.loads(line)
except ValueError:
continue
if not isinstance(o, dict):
continue
n += 1
m = o.get("message")
if o.get("type") != "assistant" or not isinstance(m, dict) or not m.get("usage"):
continue
if m.get("model") == "" or o.get("isApiErrorMessage"):
continue
u = m["usage"]
t = [u.get("input_tokens") or 0, u.get("output_tokens") or 0,
u.get("cache_creation_input_tokens") or 0, u.get("cache_read_input_tokens") or 0]
plain += sum(t)
if m.get("id") or o.get("requestId"):
key = (m.get("id") or "", o.get("requestId") or "")
else:
key = (str(f), n)
if key not in best:
best[key] = t
else:
best[key][1] = max(best[key][1], t[1]) # keep the final (largest) output count

real = sum(sum(t) for t in best.values())
print(f"{len(best):,} responses...

Powered by Readybot.io

How to Get an Accurate Claude Code Token Count

How Selfie Search Finds Event Photos—and Protects Face Data

DEV Community

How selfie search for event photos works, and what happens to the face data

After any big event (a wedding, a conference, a 10K race) someone ends up holding a folder of a few thousand photos. Everyone in those photos wants the handful they're in. The usual ways of handing them out are a shared Drive or Google Photos link, where everyone scrolls through everything and anyone with the link sees all of it, or a group-chat dump, where photos get buried and recompressed. Selfie search is the pattern a lot of event-photo tools have settled on: a guest takes one selfie, and the system returns only the photos that guest appears in. We build one of these tools, FotoNest. This post walks through how the flow works and, because it's what people actually ask about, what happens to the face data at each step. The guest flow From the guest's side there are five steps: Open the event. The host gets one QR code and one shareable link per event. A guest scans the code or taps the link, in the Android app or in any browser. Sign in with Google. One tap: no password, no OTP, no phone number. Tap "Find my photos" and take one selfie. See the matches. Only the photos you appear in, ranked by how strongly they match. Download. One at a time or in bulk, as the original full-resolution files. The photos arrive from the other direction. The host, the photographers and, depending on the event's privacy mode, the guests add them from a phone camera, a phone gallery, a public Google Drive link or desktop drag-and-drop. Several photographers can upload to the same event at once, and uploads resume if the connection drops. What happens between the selfie and the results Face search systems generally work in two halves. Cataloguing the gallery. When photos are added, each face in each photo is detected and turned into an embedding: a list of numbers that describes the face in a way that stays stable across lighting, angle and expression. Two photos of the same person produce embeddings that sit close together; photos of different people sit further apart. This happens once per photo, not once per search. Searching. The guest's selfie goes through the same process. The system compares that one embedding against the event's catalogue and returns the photos whose faces are closest, best match first. In FotoNest, the selfie becomes an encrypted face embedding, it's matched only against the photos of the event the guest joined, and the results come back ranked by match. A few behaviours follow from that: Group selfies work. If several faces are in one selfie, the search returns photos of any of them, combined. One selfie with your friends returns everyone's photos. Angles and small obstructions are fine. Side and profile shots match, and so do faces behind small sunglasses, a hat or light makeup. A face that's mostly covered won't. Low light, children and twins were all tested, and all work. No tagging, ever. Nobody labels faces by hand. Late photos aren't pushed. If more photos are added after you've searched, you re-run your selfie to pick them up. It's a retrieval flow for after the event, not a live feed during it. No match is an answer too. You get a "photos not found" state and can search again later. Matching quality is the number everyone asks for first. FotoNest's figure, from internal testing, is 99.8% match accuracy. Why sign-in is required Plenty of photo-sharing tools let anyone with the link browse. FotoNest requires Google sign-in for every guest on every event, with no exceptions. The reasoning: a gallery of people's faces shouldn't have anonymous visitors, so everyone inside one is a verified identity. Keeping it to one tap is what makes the requirement bearable at a wedding. Two other controls do similar work: Searching is selfie-only. You search with your own live selfie. You can't upload someone else's photo to find them. Event URLs are auto-generated, with no custom slugs, so nobody can guess a URL from an event's name. The three privacy modes The host picks a mode when creating the event, and it locks once the...

Powered by Readybot.io

How Selfie Search Finds Event Photos—and Protects Face Data

SEO para Saúde: E-E-A-T e Dados Estruturados

DEV Community

Planos de saúde Sorocaba: dados estruturados e E-E-A-T num site na 1ª página do Google

No meu artigo anterior contei como levei um site HTML estático de 64 para 97 no PageSpeed. Desta vez o assunto é outro: como o Google sabe quem escreveu o seu conteúdo. Relembrando: não sou programador. Sou corretor de planos de saúde, sócio de uma corretora com seis consultores, e cuido dos nossos sites. Um deles, sobre planos de saúde em Sorocaba (SP), já aparece na 1ª página do Google para o termo principal. Eu achava que os dados estruturados dele estavam em ordem. Afinal, a home tinha um JSON-LD caprichado, com InsuranceAgency, FAQPage e até um Dataset com números do IBGE e da ANS. Resolvi conferir página por página. Descobri que 83 das 96 páginas não tinham nenhum dado estruturado. Transparência: fiz a auditoria e as correções com ajuda de IA (Claude). Os números são do meu site, e eu revisei cada decisão. Por que isso pesa mais num site de saúde O Google trata saúde e dinheiro como YMYL ("Your Money or Your Life"): assuntos em que uma informação ruim pode prejudicar a vida de alguém. Nesses temas, ele procura com mais rigor os sinais de E-E-A-T: experiência, especialidade, autoridade e confiabilidade. Na prática, o Google quer responder a perguntas simples sobre cada página: Quem escreveu isto? Essa pessoa tem habilitação para falar do assunto? Qual empresa responde pelo conteúdo? Quando foi atualizado? O leitor responde olhando a página. Os robôs (do Google e das IAs) respondem melhor quando você diz isso em JSON-LD, de forma explícita e igual em todas as páginas. Foi exatamente aí que o meu site falhou. A auditoria: 20 linhas de Python Baixei o site inteiro e rodei um script simples, que só conta o que existe em cada HTML: import glob, re

paginas = [f for f in glob.glob('*/.html', recursive=True)
if len(open(f, 'rb').read()) > 400] # ignora redirecionamentos

faltando = {'json-ld': 0, 'og:title': 0, 'canonical': 0, 'h1': 0}
ids_autor = set()

for f in paginas:
s = open(f, encoding='utf-8').read()
if 'application/ld+json' not in s: faltando['json-ld'] += 1
if 'og:title' not in s: faltando['og:title'] += 1
if not re.search(r'rel=\s"canonical"', s): faltando['canonical'] += 1
if '<h1' not in s: faltando['h1'] += 1
ids_autor |= set(re.findall(r'"@id":\s
"([^"]emerson[^"])"', s))

print(len(paginas), faltando)
print(ids_autor)
O resultado, em 96 páginas: Item Páginas sem ele JSON-LD (dados estruturados) 83 Open Graph (prévia ao compartilhar) 83 Tag canonical 63 H1 10 E a última linha do script mostrou outro problema: dois IDs diferentes para a mesma pessoa. Erro 1: o mesmo autor com dois IDs Nas poucas páginas que tinham dados estruturados, o autor era declarado assim: {
"@type": "Person",
"@id": "https://.../#emerson-lavieri",
"name": "Emerson Lavieri",
"url": "https://.../"
}
Já a página "Sobre a corretora" declarava assim: {
"@type": "Person",
"@id": "https://.../sobre-a-corretora/#emerson",
"name": "Emerson Lavieri",
"sameAs": ["https://www.linkedin.com/in/...", "https://....jusbrasil.com.br/"]
}
O @id funciona como a "chave" de uma entidade no grafo. Com dois IDs, o Google pode entender que são duas pessoas diferentes com o mesmo nome: uma sem nenhuma prova de quem é, e outra com LinkedIn e Jusbrasil. A autoridade fica dividida ao meio. A correção: escolhi um único ID, o da página Sobre (que é onde a pessoa é apresentada de verdade), e coloquei o mesmo nó completo em todas as páginas: {
"@type": "Person",
"@id": "https://.../sobre-a-corretora/#emerson",
"name": "Emerson Lavieri",
"url": "https://.../sobre-a-corretora/",
"jobTitle": "Corretor de seguros – SUSEP nº 201096017",
"identifier": {
"@type": "PropertyValue",
"propertyID": "SUSEP",
"value": "201096017"
},
"sameAs": [
"https://www.linkedin.com/in/...",
"https://....jusbrasil.com.br/"
],
"worksFor": { "@id": "https://.../#consult-vida" }
}
O identifier com o registro na SUSEP (o órgão que fiscaliza corretores de seguros no Brasil) é...

Powered by Readybot.io

SEO para Saúde: E-E-A-T e Dados Estruturados

Safe HTTP Telemetry for Rust Services

DEV Community

Building a Safe-by-Design HTTP Telemetry Crate in Rust

Incidents are easier to investigate when you can see what happened inside your HTTP service: which route failed, how long it took, and what the request looked like. But logging request data can create new problems. Passwords and tokens may end up in logs. Large payloads can consume memory. And if telemetry export waits on a slow or unavailable backend, it can affect the request path. To address these tradeoffs, I built safe-http-telemetry, an open-source Rust crate for Axum and Tower applications. Its design goal is to make HTTP telemetry useful while keeping capture, resource use, and export behavior under the application’s control. Three design priorities Redact sensitive data before queueing When an application captures request data, it needs to consider credentials such as passwords, bearer tokens, and API keys. safe-http-telemetry applies capture limits and redaction before events enter the export queue. It supports configured sensitive-field matching in query parameters, headers, and supported structured body formats. JSON objects are traversed recursively, with limits on depth, visited nodes, and string size. Body capture is optional. It requires the body-capture feature and a route configured for the Detailed profile. Applications can also add field names specific to their own domain. Redaction is a safeguard, not a guarantee that every secret will be identified. I recommend starting with the Minimal profile, enabling richer capture only on reviewed routes, and limiting access to the telemetry backend. Keep the request path independent from Loki The middleware submits events to a bounded queue without waiting for a network export. Background workers can consume and batch events for asynchronous delivery to Grafana Loki. If the queue fills up, the default DropNewest policy rejects the incoming event and updates operational counters. This keeps queue memory bounded and avoids waiting for Loki to become available. The application can monitor these counters and configure limits to suit its workload. The event flow looks like this: HTTP request
│
▼
Axum / Tower middleware
│
▼
Route policy → bounded capture → redaction
│
▼
Bounded event queue ── full? ──► drop newest + update counters
│
▼
Background exporter workers
│
▼
Grafana Loki
The queue and exporter have separate responsibilities: the middleware prepares events, while the consumer handles delivery and shutdown. Make geolocation an explicit local option For applications that need it, the optional geolocation feature can look up country information using a local MMDB database. The database is supplied separately, loaded during setup, and is not downloaded by the crate. Lookups do not call an external geolocation API. The cache has configurable capacity and time-to-live limits. By default, the event includes country code and country name; the application can choose other supported fields. Geolocation depends on resolving the client IP correctly, so forwarded headers should only be trusted from configured proxy networks. A small Axum integration surface After creating a bounded queue and route policies, attach the layer to your router: let telemetry_layer =
axum_telemetry_layer(queue.clone(), policies, MiddlewareConfig::default())?;

let app = Router::new()
.route("/hello/{name}", get(handler))
.layer(telemetry_layer);
With Axum, register routes before applying the layer so the middleware can record normalized route templates. The crate leaves server setup, queue consumption, and shutdown sequencing to the application. What the benchmarks show I used Criterion to measure middleware overhead with tower::ServiceExt::oneshot. The recorded run compared a service without telemetry to three capture profiles: Baseline: 2.38 µs Minimal: 27.31 µs Standard: 60.16 µs Detailed: 71.58 µs These are estimates from a documented run on one machine, not universal performance guarantees. The benchmark does not measure networ...

Powered by Readybot.io

Safe HTTP Telemetry for Rust Services

Claude Code Skills: Personal Folders to Team Plugins

DEV Community

Claude Code Skills Deep Dive (9): From Personal Folders to Team Plugins

TL;DR: Personal, project, plugin, and managed Skills are not four tiers of one inheritance stack. They are different distribution contracts. Personal Skills favor local iteration; project Skills travel with reviewed repository changes; plugins add a namespace, versioned packaging, and other components; managed Skills support organization-wide deployment. The Agent Skills format is portable, but each runtime still has its own dependencies and sharing rules. Update for current Claude Code: Skills enabled in a claude.ai account can now sync down into signed-in terminal and cloud sessions; locally authored Skills are not automatically uploaded back to claude.ai. Part 8: From Loading to Compaction followed a Skill through a session. This article takes the longer view: how does a workflow written in ~/.claude/skills/ today become something a team can maintain and install tomorrow? Copying a folder is easy: cp -r ~/.claude/skills/release-check teammate-machine/
But the copy raises new questions: Which copy is authoritative, and who updates it? How do same-named Skills avoid collisions? Which runtime does each script require? How do hooks, agents, and MCP configuration install together? How does a team review changes to the permission surface? Can the Claude Code version be used unchanged in the API or claude.ai? What you distribute is not merely a folder. You distribute a maintenance and trust relationship. Four distribution contracts Form Source of truth Update path Best fit Personal A user's local directory Individual edits Experiments, personal habits, private workflows across projects Project A repository's .claude/skills/ Commits and PRs Repository-specific capabilities shared by contributors Plugin A plugin package and version Install, upgrade, marketplace Multi-project or multi-team capabilities with multiple components Managed Organization-managed configuration Administrator deployment Organization-wide workflows and governance This is not a mandatory promotion ladder. A migration Skill tied to one repository may always belong in that project; a public tool may merit a plugin from day one. The useful questions are: Who authors it?
Who uses it?
Who approves updates?
How do users receive a new version?
What other components does it depend on?
Personal: the fastest place to experiment A personal directory is a good place to turn repeated work into a first Skill: ~/.claude/skills/release-check/
├── SKILL.md
└── scripts/
You can edit quickly, test a description across local projects, and observe when the Skill triggers without affecting teammates. But other contributors do not automatically have it. A new machine may not have it either. Local CLI tools, paths, credentials, and even the history of changes can remain invisible. A personal Skill should be treated as personal configuration, not a hidden project dependency. If team work fails without it, the distribution scope is wrong. Project: put the workflow under review Put the Skill in: repo/.claude/skills/release-check/
Commit it, and the workflow becomes part of the repository. A contributor can get it with the code, while changes become reviewable: Why did the release checklist change?
→ Read the commit or PR.

Who broadened allowed-tools?
→ Inspect the diff.

When did a new CLI become required?
→ Check repository history.
The important gain is not automatic copying; it is an auditable history. Project Skills fit capabilities coupled to repository facts. When the same Skill is copied into ten repositories and evolves independently, however, Git gives you ten forks—not one upgrade path. That is a reason to consider a plugin. Iterate standalone; productize as a plugin Standalone configuration is well suited to a single project, a personal workflow, or an unstable Skill or hook. A plugin becomes useful when the capability needs reuse across projects, independent versioning, team or community distribution, or installation alongside agents, hooks, and MCP servers. Re...

Powered by Readybot.io

Claude Code Skills: Personal Folders to Team Plugins

SaaS API Cost Attribution with Leaked-Key Drills

DEV Community

Leaked Keys: SaaS API Cost Attribution Explained Through Refusal Drills

A B2B SaaS leaked-key drill should end with an owner, an attributed usage record, and a decision about which traffic to refuse. Start with one key per cost centre and the platform's per-key usage figures. The bill contains accepted API work and retained accounting evidence; asking teams to reconstruct consumption afterward adds a dispute to the response process. TL;DR: Attribute API costs across teams using keys as cost centres, rather than self-reported usage. Keep the spend-ceiling decision separate: attribution explains accepted work, while admission policy determines refused traffic. A shared service still needs an allocation rule. Quantify the exposure before choosing a control. Accepted calls multiplied by their applicable costs make up the consumption term; retained bytes and their retention policy determine the evidence term. In an illustrative drill, 8 budget units already accepted against a 10-unit ceiling leave 2 units. Admitting a further 3-unit attempt crosses that ceiling. These are exercise inputs, not vendor prices or measured results. Refusing that attempt moves the consumption term; deleting evidence afterward does not undo accepted work. How should teams use keys for API cost attribution across shared services? The least complex useful change is to put ownership into the credential boundary before traffic starts. A shared credential makes attribution depend on a later join against application records; separate credentials give the platform's own numbers a cost-centre dimension. Self-reporting leaves the reporting process behind the consumption it is supposed to explain. Count refused traffic. When a suspected credential is refused, legitimate requests using it may be refused too. If the service keeps admitting work during investigation, the spend ceiling needs to account for that interval. Reporting only lower accepted usage can make an interrupted workflow appear to be successful containment, so the drill should retain both attributed consumption and refusal reasons. Per-key reporting isn't proof of atomic budget enforcement. Two workers may read the same remaining allowance and both admit work; a strict ceiling needs a consistency boundary around reservation and admission. Require that contract explicitly. Neither credential separation nor an accounting dashboard establishes how quickly new usage becomes visible. Choose the ceiling and refusal rule before the exercise, identify a test credential as suspected compromised, then rehearse its replacement while preserving the owning cost centre. Rotation must not turn the same team's later usage into an unowned bucket. Those are design acceptance criteria, not promises about a vendor's propagation time. Compare the control boundary, not the invoice headline Evaluate alternatives against the part of the drill they need to own. The following table is a selection framework: it does not assert identical budget-enforcement behavior across products. Option Useful evaluation focus Fit Boundary to resolve Stripe Billing Customer-facing billing A team whose accounting question ends in customer invoices An invoice alone cannot establish that a leaked backend credential was refused Unkey API credential management A team evaluating the credential boundary independently of its backend providers Reconcile credential identity with the source of billable usage Kong Gateway Gateway admission policy A team that wants to evaluate policy at its application ingress Determine which backend calls can bypass that ingress Infrai One API key across DNS and account capabilities A team that wants a stable capability contract when the underlying vendor changes, with per-call cost and vendor metadata for reconciliation Shared-service allocation remains a team policy; a combined provider concentrates operational dependency The first three are real alternatives for different portions of the control system. Stripe Billing is relevant when the output is an invoice; Unkey and Kong Gateway ar...

Powered by Readybot.io

SaaS API Cost Attribution with Leaked-Key Drills

SuppressIldasm: Why It Won’t Protect .NET Assemblies

DEV Community

SuppressIldasmAttribute is not protection: what anti-ILDASM actually buys you

Search "protect .NET assembly" and someone will tell you to add one line: [assembly: System.Runtime.CompilerServices.SuppressIldasm]
The promise is that your DLL can no longer be disassembled. The reality is narrower than almost anyone who pastes that line realises, and on modern .NET it does nothing at all. This is a deep explainer on what SuppressIldasmAttribute actually does, why it stops exactly one program, and what it takes to make an assembly genuinely expensive to read. What the attribute really is SuppressIldasmAttribute is not encryption, not a permission, not a lock. It is a marker — a zero-field custom attribute that the compiler writes into your assembly's metadata. At the IL level it is just another .custom entry in the CustomAttribute table: .custom instance void [System.Runtime]
System.Runtime.CompilerServices.SuppressIldasmAttribute::.ctor() = ( 01 00 00 00 )
That ( 01 00 00 00 ) is the attribute blob: a two-byte prolog and a two-byte count, with no arguments. Nothing about your code changes. Every type, every method body, every string literal is written to the file exactly as before. The only new thing in the assembly is a flag that says, in effect, "please don't disassemble me." Whether anyone honours that request is entirely up to the tool reading the file. Exactly one tool ever listened — and it stopped Historically, Microsoft's own ildasm.exe — the IL Disassembler shipped with the .NET Framework SDK — checked for this attribute. If it found one, it printed // This assembly is protected... and refused to dump the IL. That is the entire mechanism. It was a gentleman's agreement between Microsoft's authoring tool and Microsoft's disassembling tool. Two facts collapse the protection: No other reader ever checked it. ILSpy, dnSpy, dotPeek, JustDecompile, the Mono monodis utility, and modern decompilers including Glass.NET read the metadata tables directly. None of them consult the SuppressIldasm flag, because nothing in the ECMA-335 format obliges them to. They open the file, walk the TypeDef and MethodDef tables, resolve each method's IL from its RVA, and reconstruct C#. The attribute is invisible to them. On .NET 6 and later, even ildasm ignores it. The honour was removed. The attribute still compiles — it is marked obsolete — but the modern disassembler dumps the assembly regardless. So on any current .NET target, [assembly: SuppressIldasm] is a literal no-op: it changes four bytes of metadata and protects nothing, not even against the one tool it was written for. The net effect, today: you have added an attribute that does nothing, and possibly convinced yourself you are protected when you are not. That second part is the real hazard. Why it was always weak: the file is still readable Step back from the attribute and look at what a .NET assembly actually exposes. The managed metadata is not an opaque blob — it is a set of well-defined streams inside the PE file, and decompilers feed on them directly. What a decompiler reads from the metadata streams — the SuppressIldasm flag guards none of it Assembly metadata a decompiler walks directly #~ (tables) TypeDef, MethodDef, Field, Param rows #Strings every type, method and field name #US every string literal in your code method bodies (IL) resolved from each RVA #Blob signatures, constants SuppressIldasm flag — one row in CustomAttribute The flag sits beside the data; it does not encrypt, remove or guard any of it. A reader that skips the flag still reads every box above. The #Strings heap holds the plaintext name of every type, method, field and parameter. The #US (user-string) heap holds every string literal your code contains. The #~ stream holds the tables that stitch them together, and each method's IL is resolved from its relative virtual address. A decompiler opens the file and reads these structures. That is the whole job. The SuppressIldasm flag sits next to all of this, in one row of the CustomAttribute table. It does not remove a single nam...

Powered by Readybot.io

SuppressIldasm: Why It Won’t Protect .NET Assemblies

Enforce AI Coding Boundaries with Pre-Commit Gates

DEV Community

Shift Left AI Coding Agent Boundaries with Pre-Commit Gates

Autonomous AI coding agents operating inside large monorepos frequently struggle with strict boundary enforcement, often importing unauthorized modules deep into their coding loops only to fail late during CI merge checks. When an agent spends thousands of tokens writing code that gets rejected at merge time, teams face expensive rollback and untangling cycles. Quick solution: Prevent cross-module import leaks instantly by pairing a deterministic static AST linter in a pre-commit hook with your CI checks, enforcing boundaries before code ever reaches remote storage. npx dependency-cruiser --config .dependency-cruiser.js apps/billing/
Prerequisite: Ensure your repository uses isolated worktrees as outlined in guides like Git Sparse Checkout Cone Mode Root Files before implementing pre-commit hook enforcement. Be mindful that local hooks can occasionally be bypassed if the agent environment retains raw shell execution permissions. The Late Failure Trap in Autonomous Pipelines Platform engineers typically rely on a CI Merge-Time Diff Allowlist to stop unauthorized files from entering trunk branches: # CI merge check verifying modified paths
git diff --name-only origin/main...HEAD | grep -v -E "^apps/billing/"
While a CI allowlist provides a strong unforgeable barrier, it introduces a significant latency and financial penalty known as the late failure trap. An agent might spend dozens of tool-call iterations refactoring code, only to pull in a forbidden utility from another service. By the time CI runs minutes later, the agent has finished its turn, requiring a human or an expensive retry loop to fix the stray import. When an agent burns thousands of tokens producing code only to be rejected at merge time by CI, teams face expensive rollback and untangling cycles. In large-scale enterprise environments with hundreds of active agents running in parallel, these wasted cycles accumulate into massive cloud compute bills and stagnant pull request queues that stall feature delivery. Furthermore, relying solely on post-push validation creates an adversarial dynamic between automated agents and platform stability guards. Because the agent receives no immediate tactile feedback during its generation loop, it often repeats the same architectural mistake across multiple subsequent tasks. This systemic oversight highlights why shifting validation upstream into the local worktree is an operational necessity rather than a premature optimization. Without early boundary enforcement, engineering organizations find themselves continuously tuning LLM system prompts with strict negative constraints, which agents inevitably bypass when complex refactoring tasks require reaching across internal service boundaries. To maintain robust control over expanding codebases, platform maintainers must implement proactive filters that intercept violations inside the developer sandbox before remote propagation occurs. Architectural Trade-Offs: The 3-Tier Shift-Left Model To balance agent autonomy with strict repository hygiene, engineering teams can adopt a 3-tier governance model that moves validation upstream from remote CI runners into the local developer or agent loop. Option When to Use It Trade-off or Failure Mode Recommendation Tier 1: Static AST Linter For instant, zero-token import checks on every local commit. Catches explicit imports only; misses dynamic runtime or reflection-based leaks. Use as the mandatory first line of defense in pre-commit hooks. Tier 2: Semantic Subagent To evaluate architectural intent and subtle boundary breaches. Incurs a small token cost and adds milliseconds of latency before pushing. Run as an automated pre-push review gate in the orchestrator pipeline. Tier 3: CI Merge Fence As an immutable backstop and unbypassable security boundary. Fails late after branch push, wasting tokens if used alone. Keep as the final source of truth for trunk promotion safety. According to community discussions highlighted by Manoj Kagitha ...

Powered by Readybot.io

Enforce AI Coding Boundaries with Pre-Commit Gates

A PM’s Guide to Vibe-Coding with AI

DEV Community

A PM's Guide to Vibe-Coding: Requirements First, Code Second

For about a year, my team kept a shared resource — meeting rooms — in a spreadsheet and a group chat. Someone would write "Room B, Thursday 2–4pm?" in the chat. Someone else would check the spreadsheet. Someone would forget to update it. And then two teams would show up at the same door at the same time, each holding a laptop and a reasonable claim to the room. It worked badly, and everyone knew it worked badly. Nobody had time to build a real system for it. And I am a project manager, not a programmer — I hadn't written production code in years. So I did the thing every PM seems to be doing now: I asked an AI coding assistant to build it for me. I want to be honest about what happened next. The AI did not magically turn my idea into software. It turned my requirements into software — and the difference between those two sentences is the whole story. The requirements came first Before I opened the editor, I spent a day writing the rules. Not a PRD, not a forty-page spec — just a list, in plain language, of how the thing had to behave. Four questions did most of the work: Who can use it? Anyone on the team, no approval needed. If a tool needs a gatekeeper, people go back to the group chat. When can they book? Within a fixed window ahead of time — far enough to plan, short enough that nobody hoards rooms weeks out. What happens when two people want the same slot? The second booking fails, clearly, in words a human understands. No silent overwrites, ever. What happens when someone cancels? The slot frees up immediately, and the system shows it as free. No ghost bookings. Those four answers became the spine of everything I asked the AI to build. Everything else — the layout, the colours, the buttons — was decoration. Here is the part nobody warns you about: the AI will also invent rules. Mine did, on the first day. It added an auto-expiry rule I never asked for — unconfirmed bookings would vanish after two hours. It sounded sensible. It was also completely made up, and it would have deleted real bookings made by real people who simply hadn't clicked a confirmation nobody told them about. So I learned the first real lesson of vibe-coding, and it is a PM lesson, not a coding lesson: every rule in the system must come from your written spec. If a behaviour isn't in the list, it doesn't exist. I added one line to the top of my spec, and it stayed there for the whole build: "Build only the rules written here. Do not add rules of your own." The rules I insisted on, the ones the AI would never have written by itself, were the boring human ones: One active booking per person per day. Not because the system needs it, but because without it, one organised person books every room and everyone else goes back to the spreadsheet. Every booking shows a name. Not an ID, not an email — a name. When two people collide, they need to know who to talk to. Software can't resolve that conversation; it can only make it possible. The system never moves or deletes a booking silently. If something changes, the person affected gets told. This rule cost me an afternoon of argument with the AI, which kept trying to "helpfully" resolve conflicts on its own. I kept deleting that help. Those three rules are the whole difference between a tool people trust and a tool people route around. The AI was very good at the first kind of rule — the logic. It was blind to the second kind — the trust. That part was my job, and no prompt would have done it for me. The workflow: small prompts, real acceptance tests The tools were deliberately boring: an AI coding assistant in my editor, plain HTML, CSS and JavaScript with no framework, a private repo for version control, and Cloudflare Pages for hosting. Nothing exotic. The point of the exercise was the method, not the stack. I wrote prompts the way I write tickets: context first, then the rule, then what "done" looks like — one feature at a time. I never asked for the whole app at once. Every prompt ended with the same ac...

Powered by Readybot.io

A PM’s Guide to Vibe-Coding with AI

Signal2Speech: Final Testing and Hackathon Submission

DEV Community

Signal2Speech: one app, a final round of testing, and our submission (Update 6)

This is our sixth update on Signal2Speech, our Hack the Nest 2026 project that lets someone answer questions with an EEG headset. The app suggests replies, the wearer picks one with a P300 response (a brain signal that shows up about 300 milliseconds after the card you're watching flashes), and they confirm by closing their eyes. Nothing is spoken until they confirm. In our last post, we covered testing a PiEEG board on two people and finding no usable brain signal, so the app now runs on real human EEG that g.tec recorded on their own amplifier. Since then, we have submitted our project on Devpost. This post covers the last few hours before the deadline. One app instead of two Up to now, the AI replies and the NASA air-quality demo were two separate windows. Signal2Speech is now one app. The main screen is a question box and two reply cards, and the top of the window says what the app is and the three steps to use it. The NASA question is now an example inside the app. Clicking "Example: NASA air quality" brings up the map in the side panel, and the conversation shows the rest of the time. Nothing about choosing, previewing, confirming, or speaking changed, only the layout and the way in. We made this change because the conversation is the actual product. A person who can't speak needs to answer any question, not just one about air quality. The NASA example shows that the app can also do something on screen, but it shouldn't be the first thing someone sees. The reply screen can also run on g.tec's recorded brain data now, so recorded EEG picks between Claude's replies the same way it picks between the NASA options. Testing the parts we couldn't see Soak test: We wanted to know the app would hold up for a full judging hour, so we built a soak test that runs the demo by itself for 60 minutes. It runs through the same crash-safe launcher we use at the table and kills the app once on purpose. The first full run passed with 169 confirms and 169 spoken lines, zero doubles, zero crashes, and the app back within 1.1 seconds after the kill. The selection time was 3.1 seconds at the start and 3.2 seconds at the end, so the app didn't slow down over time. This ran on simulated input, not live EEG. OSCAR on real EEG: OSCAR is g.tec's artifact removal (cleaning out noise from blinks and muscle movement). We measured it on all five of g.tec's recorded people. The biggest blink and movement swings got 14 to 65% smaller while the rest of the signal barely changed, and classification stayed the same or improved, with one person going from 0.72 to 0.81. We also found something we didn't expect. OSCAR delays the signal by about a third of a second, but g.Pype doesn't shift the flash markers to match. Because of this, the classifier ends up looking at the wrong part of the response after each flash, which can cost up to 0.14 accuracy. We documented how to handle it, and it is something the live headset path will have to check. A last-minute voice bug About half an hour before the deadline, we found that some fresh spoken lines were silent on the judging laptop. Qt's audio player reported the clips as playing, so the app thought everything had been said, but nothing came out of the speakers. In an app that speaks for someone, that is a serious problem. The wearer would confirm a reply, the screen would say it was spoken, and the person they're talking to would never hear it. We switched clip playback to the Windows WAV player and added tests that cover both players. Smaller things Restart key: Between judges, pressing R brings back a fresh first question from wherever the app is, without saying anything. It uses the same rules as a normal cancel, so a brain decision still in progress from before the restart is thrown away instead of picking something on the new question. Team briefing: We wrote one page every teammate read before judging. It covers what is real and what is scripted, the numbers to know, and straight answers to the questions j...

Powered by Readybot.io

Signal2Speech: Final Testing and Hackathon Submission

How C# Decompilers Recover File-Local Types

DEV Community

Decompiling file-local types: recovering the file modifier from a mangled metadata name

C# 11 added the file access modifier: a type declared file class Parser is visible only inside the single source file that declares it. Two files in the same project — or two source-generated files that each emit a helper — can both declare a file class Parser without colliding, and neither can be touched from anywhere else. It exists mostly for the benefit of source generators, which emit support types into a user's compilation and must not leak names that clash with the user's own code or with another generator's. From a decompiler's point of view file is an interesting problem because, like several recent C# features, it leaves no attribute behind. There is no [FileLocal] marker, no custom modifier, no flag in the TypeDef row that says "this type was declared file." The compiler encodes the modifier in the one place that survives into metadata and is guaranteed unique: the type's name. It mangles the declared name into a form that is deliberately not a legal C# identifier, and it drops the visibility down to assembly-internal. A decompiler that reads the TypeDef table and prints what it finds will emit a type called F0__Parser with internal accessibility — which is neither what the author wrote nor anything the C# compiler will accept. Reconstructing the original means recognising the mangling, reversing it, and putting the recovered type back in a file bucket. This post walks the full round trip: the source, the metadata the compiler emits, and the C# Glass.NET reconstructs. What the author wrote A file type usually keeps a small helper private to one file. Here Validators.cs has a file-local rule plus a public façade that uses it: // Validators.cs
file sealed class PhoneRule
{
public static bool IsValid(string s) => s.Length == 10;
}

public static class Contact
{
public static bool Check(string phone) => PhoneRule.IsValid(phone);
}
PhoneRule is file-scoped, so nothing outside Validators.cs can name it — not another file in the same assembly, not a consumer referencing the DLL. Contact, declared normally, calls it freely because it lives in the same file. What the compiler emits Two things happen to PhoneRule on the way to metadata. First, its name is mangled. The compiler builds a metadata name from a file identifier (derived from the source file's name), an ordinal that disambiguates files that happen to share a name, and the declared type name, wrapped so the result cannot be written in source: .class private sealed auto ansi beforefieldinit
'F0__PhoneRule'
extends [System.Runtime]System.Object
{
.method public hidebysig static
bool IsValid (string s) cil managed
{
ldarg.0
callvirt instance int32 [System.Runtime]System.String::get_Length()
ldc.i4.s 10
ceq
ret
}
}
Note what is not there: no CompilerGeneratedAttribute, no custom attribute of any kind announcing the modifier. The F0__PhoneRule name is the entire record of the file keyword. The < and > are the tell — they are reserved exactly so that user code can never produce an identifier that collides with a compiler-synthesized one. Second, the type's accessibility drops to assembly-internal. A top-level type can only be public or internal in the CLI type system — there is no finer-grained visibility at the metadata level — so the compiler emits PhoneRule as internal and relies on the unspeakable name to enforce the stronger "one file only" rule at compile time. In ILDasm a top-level internal type reads as .class private, which is why the row above says private even though you never wrote private. The call site inside Contact.Check references the mangled name directly, because by the time IL is emitted the only name PhoneRule has is the mangled one: .method public hidebysig static bool Check (string phone) cil managed
{
ldarg.0
call bool 'F0__PhoneRule'::IsValid(string)
ret
}
Every reference to a file-local type inside its own file — base types, field...

Powered by Readybot.io

How C# Decompilers Recover File-Local Types

Let's Encrypt for Internal Domains: CT Log Risks

DEV Community

Let's Encrypt for Internal Domains: What CT Logs Make Public

Let's Encrypt for internal domains works: the DNS-01 challenge proves you control a domain without any server answering from the internet, and wildcard certificates come the same way. What it does not do is keep the name private. Every certificate a browser trusts is written to public Certificate Transparency (CT) logs. A service on a private address behind a VPN therefore still has a public hostname, and its issue dates and renewals are on record for anyone to read. A public certificate means a public name. Choose a certificate per host, a wildcard or a private CA by how much of the name you can afford to publish, and protect every service as if its name is already known. What a certificate publishes the moment it is issued Before issuing, a CA submits a precertificate to the logs. It is the certificate-to-be plus a critical extension, called the poison, that makes standard clients refuse it. The logs answer with signed timestamps (SCTs), and the CA embeds them in the real certificate. Nearly every CA works this way, so the hostname is public before the certificate exists. Chrome and Apple platforms both require signed proof from logs run by at least two separate organizations, so a publicly trusted CA cannot skip the step and a site owner cannot opt out. The log entry holds the whole certificate. For a domain-validated certificate, the kind Let's Encrypt issues, that means the names it covers, the issuer and the validity dates. Neither the server's address nor what it runs is in the entry. The leak is the name, which usually tells you what the host is for. Internet-wide scans already aggregated certificates, but the logs make the collection complete and early, and let anyone search it by name without connecting to your server. The entries for a domain, read as a list, give a stranger: the services you run, from labels such as vault, grafana, jenkins or vpn; products and customer names before any announcement; the date each host appeared and whether its certificate keeps renewing; a ready target list, if the same names also resolve in public DNS. Newer logs publish their contents as plain files that any client can download, and some add a compact list of just the names. For logs that Chrome accepts, the time a log may take to include an entry is capped at one minute for these static logs and four hours for the older kind. Soon after a Let's Encrypt certificate is logged, automated crawlers can find the new hostname and request it, and a public web server sees that traffic in its access log. Logs are append-only, so a name stays listed after its certificate expires or is revoked. The full Certificate Transparency background covers logs, SCTs and browser enforcement in more detail. Let's Encrypt for internal domains: what DNS-01 solves and what it publishes Let's Encrypt checks control of a name with a challenge. HTTP-01 needs a web server answering on port 80. DNS-01 needs only a TXT record in the domain's public DNS, so it works for hosts that are not exposed to the internet, and only DNS-01 can issue a wildcard. The renewing machine then holds a DNS API credential, and one that can edit your whole zone is a risk on a web server, so scope it narrowly or run the validation elsewhere. The name must sit under a domain you own in public DNS: public CAs may not issue for names that do not end in a registered top-level domain, so names ending in lan or local are out. On the publishing side, Let's Encrypt submits every certificate it issues to CT logs. Its default lifetime is 90 days, with renewal advised every 60, and six-day certificates are opt-in. Industry rules cap lifetimes at 200 days now, 100 from March 2027 and 47 from March 2029, so a per-host certificate puts the same name into the logs more often each year. Wildcard certificate subdomains: what stays hidden A wildcard certificate for .lab.example.com covers exactly one label below lab.example.com. It matches vault.lab.example.com and rejects a.vault.lab.example.com ...

Powered by Readybot.io*

Let's Encrypt for Internal Domains: CT Log Risks

Bus Parking Out : un jeu de réflexion en CoddyRun

DEV Community

Bus Parking Out, codé en CoddyRun

Nouveau jeu de réflexion écrit entièrement en CoddyRun, le langage de programmation en français. Le principe est simple, mais il faut réfléchir avant de cliquer : Le parking est encombré de voitures, de minibus et de bus. Clique sur un véhicule : il avance dans le sens de sa flèche. Si la voie est libre, il sort et se gare au quai. Sinon, il cogne et revient. Les passagers montent dans le véhicule de leur couleur, dans l'ordre de la file. Une voiture prend 4 passagers, un minibus 6 et un bus 8. Le quai n'a que 4 places. S'il est plein et que personne ne peut monter, c'est perdu. Ce qu'il y a dedans : des niveaux générés automatiquement et toujours faisables la route du véhicule qui s'affiche quand on passe la souris dessus, en rouge si quelque chose le bloque des véhicules vus de dessus, avec phares, vitres et sièges qui se remplissent un joker pour ouvrir une 5e place au quai, une fois par niveau une note de 1 à 3 étoiles à la fin du niveau, et le niveau atteint gardé en mémoire Le tout fait environ 900 lignes de code en français : si … alors, tant que, procédure, et un processus qui dessine l'écran en continu pendant que le jeu attend les clics. Jusqu'à quel niveau irez-vous ? Démo : Démo

Powered by Readybot.io

Bus Parking Out : un jeu de réflexion en CoddyRun

Use ETags to Cut License Refresh Downloads

DEV Community

Conditional license refresh with ETag: stop re-downloading a license that has not changed

A Keyright client does not call home on every license check. It activates once, caches the signed lease, and from then on every Validate() is a local, offline operation against the embedded public key. What does talk to the issuing service is the background refresh: on a timer — typically every few minutes to a few hours — the SDK re-fetches the lease so that a renewal, an entitlement change, or a revocation is picked up without waiting for a restart. Here is the thing about that refresh loop: almost every iteration of it is a no-op. A license is a slow-moving resource. It changes when someone renews, upgrades, transfers a seat, or gets revoked — events that happen days or weeks apart. Between those events, a client that refreshes every five minutes asks the service "what is the current state of this license?" hundreds of times and gets back byte-for-byte the same signed lease every single time. Each of those answers is a full response body the service serialized and signed, pushed over the network, that the client then base64-decoded and ran an RSA verify over — all to confirm what it already knew. HTTP has had the right primitive for this since 1999. It is the conditional GET, built on the ETag response header and the If-None-Match request header, and wiring it into the refresh path turns the common case — nothing changed — into a headers-only round trip that returns 304 Not Modified with an empty body. Key takeaway: Have your issuing service stamp every license response with a strong ETag derived from the license's version and signature. Have the SDK remember that tag and send it back as If-None-Match on the next refresh. When nothing has changed the service answers 304 Not Modified with no body, the client keeps its cached lease untouched, and you have replaced a full signed-payload download plus a signature verify with a few hundred bytes of headers — without ever letting a stale cache hide a revocation. What a license fetch looks like today Strip the SDK away and a refresh is an ordinary HTTP GET. The client asks for the current lease for a key; the service returns the signed document. GET /v1/licenses/current HTTP/1.1
Host: keyright.example.com
X-Keyright-Product: acme-suite
Authorization: Bearer AK-9f3c… ← the activation token from the initial handshake

HTTP/1.1 200 OK
Content-Type: application/vnd.keyright.lease+json
Content-Length: 1184

{ "lease": "eyJhbGciOi…", "signature": "MEUCIQ…", "edition": "pro", "expiresAt": "2027-01-01T00:00:00Z" }
That lease blob is the canonical, signed payload the client verifies offline. At a kilobyte-plus a shot, times a fleet of clients, times a refresh every few minutes, times the fact that the content is identical between license events, it is pure waste. The service did real work to produce a body nobody needed. The ETag: a fingerprint the client can quote back An ETag ("entity tag") is an opaque validator the server attaches to a response. Its only contract is this: if two responses for the same URL carry the same ETag, their representations are identical; if the resource changes, the ETag must change. The client treats it as a black box — it never parses it — and simply quotes it back on the next request to ask "do you still have exactly this?". For a license, you do not want to hash the whole response body to produce the tag (that works, but it costs a hash over the payload on every request). You already have two fields that change if and only if the license changes: a monotonic version the issuing service bumps on every mutation, and the signature itself. Combine them into a strong validator: ETag: "v47-3b9a1f" ← license version 47, first bytes of the signature, strong tag
This is a strong ETag (no W/ prefix), which is the correct choice here: a conditional request should match only when the bytes are genuinely identical, because the client is going to skip verifying a new signature on a match. A weak tag (W/"…"), which only promises semantic equivalence,...

Powered by Readybot.io

Use ETags to Cut License Refresh Downloads

Build a Readable TypeScript Agent Loop

DEV Community

Build a readable TypeScript agent loop with tools and traces

An agent that calls tools needs a few concrete pieces: conversation history, a model interface, an allowlist of tools, and a decision about when to stop. Writing those pieces yourself makes the behavior visible. You can follow a failed tool call from its arguments to the error message sent back to the model. I put that approach into Agent Loop Starter, a small MIT-licensed TypeScript repository. It uses strict TypeScript, ESM, Zod v4, and the official OpenAI SDK. There is no agent framework between the loop and the tools. Start with the conversation The model receives messages and tool definitions. Its reply contains text, tool calls, or both. Each tool call has an ID, a name, and arguments encoded as JSON text. Keeping the arguments raw lets malformed JSON follow the same recovery path as other tool errors. The loop begins with one user message. Every model reply is appended as an assistant message. Tool results follow it, carrying the matching call IDs. On the next request, the model sees what it asked for and what actually happened. Here is the model-call section from src/agent.ts, inside while (steps < maxSteps): if (signal?.aborted) return stopped("aborted");
const step = ++steps;
const started = performance.now();
let response;
try {
try {
response = await withAbort(() => model.complete({ messages, tools: definitions, ...(signal ? { signal } : {}) }), signal);
} finally {
emit({ type: "model_call", step, durationMs: performance.now() - started });
}
} catch (error) {
if (signal?.aborted) return stopped("aborted");
throw error; // Transport/auth errors are different from recoverable tool errors.
}
withAbort stops waiting if the signal fires. It also passes the signal through to the model adapter. Authentication and transport failures reject the run, giving the caller a chance to decide whether to retry. The next decision is short: if (signal?.aborted) return stopped("aborted");
messages.push({ role: "assistant", ...response });
if (!response.toolCalls?.length) {
emit({ type: "final", step, durationMs: 0, output: response.content });
return { output: response.content, stopReason: "final", steps, trace };
}
A reply with tool calls enters a sequential execution loop. After appending all results, execution returns to the next model call. A reply without tool calls ends the run. Define tools once, with Zod A tool needs a description the model can read and validation the program can enforce. defineTool takes a Zod object schema, converts its input shape with z.toJSONSchema, and validates arguments before calling execute. The argument type is inferred from that schema. This is the calculator definition from src/tools/calculator.ts: export const calculator = defineTool({
name: "calculator",
description: "Calculate arithmetic with +, -, , /, %, parentheses, decimals and unary signs. No exponents. Uses JavaScript floating-point numbers.",
schema: z.object({ expression: z.string().min(1).max(512) }).strict(),
execute: ({ expression }) => ({ value: evaluateExpression(expression) }),
});
expression is a string inside execute. The schema also rejects extra fields. The arithmetic implementation is a recursive descent parser with precedence, parentheses, and unary signs. It never evaluates JavaScript. It rejects division by zero, excessive nesting, and non-finite results. The other examples return the current time for an IANA timezone through Intl, and search three built-in notes by keyword. All three run without external services. Tools return JSON values so results can go into conversation history and traces. Make failures part of the conversation A model can request an unknown tool, send broken JSON, or use the wrong argument types. A valid call can also fail during execution. These cases become tool error messages rather than crashing the loop. The execution boundary includes these lines: const tool = registry.get(call.name);
if (!tool) throw new Error(Unknown tool: ${call.name});
const args: u...

Powered by Readybot.io*

Build a Readable TypeScript Agent Loop

Build an osu! Skin Contact Sheet with Python

DEV Community

Generating a contact sheet for an osu! skin with Python and Pillow

An osu! skin is a folder with anywhere from 50 to 500 PNG files. Opening them one by one to check consistency is slow, and file browsers show transparent images on white, which hides half of a typical skin. A contact sheet, one image with every sprite tiled on a checkerboard and labelled, makes it much easier to review a skin, spot missing @2x files and share a preview. Here is a small, dependency-light script that does exactly that. The script #!/usr/bin/env python3
"""contact_sheet.py SKIN_DIR OUT.png - tile every PNG in an osu! skin folder."""
import sys
from pathlib import Path
from PIL import Image, ImageDraw

CELL, LABEL, COLS = 160, 18, 8

def checker(w, h, s=10):
img = Image.new("RGB", (w, h), (200, 200, 200))
d = ImageDraw.Draw(img)
for y in range(0, h, s):
for x in range(0, w, s):
if (x // s + y // s) % 2:
d.rectangle([x, y, x + s - 1, y + s - 1], fill=(160, 160, 160))
return img

def main(skin, out):
files = sorted(p for p in Path(skin).glob("*.png") if "@2x" not in p.stem)
rows = (len(files) + COLS - 1) // COLS
sheet = Image.new("RGB", (COLS * CELL, rows * (CELL + LABEL)), (30, 30, 30))
draw = ImageDraw.Draw(sheet)
problems = []
for i, p in enumerate(files):
hd = p.with_name(p.stem + "@2x.png")
src = hd if hd.exists() else p
im = Image.open(src).convert("RGBA")
if hd.exists():
sd = Image.open(p)
if (sd.width * 2, sd.height * 2) != im.size:
problems.append(f"{p.name}: @2x is {im.size}, SD is {sd.size}")
else:
problems.append(f"{p.name}: no @2x version")
im.thumbnail((CELL - 8, CELL - 8))
x, y = (i % COLS) * CELL, (i // COLS) * (CELL + LABEL)
cell = checker(CELL, CELL)
cell.paste(im, ((CELL - im.width) // 2, (CELL - im.height) // 2), im)
sheet.paste(cell, (x, y))
draw.text((x + 4, y + CELL + 2), p.stem[:22], fill=(240, 240, 240))
sheet.save(out)
print("\n".join(problems) or "no size problems found")

if name == "main":
main(sys.argv[1], sys.argv[2])
Install Pillow with pip install pillow, then run: python3 contact_sheet.py "$HOME/osu!/Skins/My Skin" sheet.png
What it gives you A checkerboard background. Transparent and semi-transparent pixels are visible, so faint glows and accidental halos stand out. One cell per element. The @2x image is preferred when it exists, so you review the version most players with 1080p or higher screens actually see. A size report. Each @2x file should be exactly twice the size of its SD file. The script lists every mismatch and every element with no @2x version. Ideas for extending it Group cells by prefix (hit, slider, spinner, score-, mania) so related elements sit together. Read skin.ini and draw the combo colours as swatches at the top of the sheet. Skip animation frames after -0 to keep the sheet short, or put each animation on its own row. Flag files above a size threshold (say 1 MB) as candidates for compression. Why bother A contact sheet is the fastest way to answer "does this skin look like one consistent design?" It also makes a good first image for a skin release post, because it shows everything at once rather than one gameplay screenshot. If you want to see how finished skins hold together, the osuskins.org skin library has gameplay screenshots for a large collection of skins, and the osuskins.org skin making notes list the element names this script will be tiling.

Powered by Readybot.io

Build an osu! Skin Contact Sheet with Python

Discord Ban Appeal: A 10-Year Account Deleted

DEV Community

discord banned my account of ten years over a cat gif, then it got deleted. i took the username back anyway.

this is the year i spent trying to get an answer out of discord, and how it ended. the account i've had my discord account since october 2015. it was my main, and it owned Akiko, my bot. i also had a separate personal account, kept apart on purpose. what happened in november 2025 my personal account was suspended under the graphic content policy. the reason was that i was a member of a server discord later removed. as far as i can tell, i joined that server for the custom emojis. the channel had been quiet for months. the only message i ever sent there was a cat gif, and other members had already posted the same ones. about a week later my main account was disabled for ban evasion. i got logged out instantly and never saw the DM, so i never had a chance to respond. the evasion charge only exists because the first ban exists. i didn't dodge anything, i just kept using the account i'd always used. the appeals i filed seven support tickets between november and march. every one got closed with the same canned reply: go to Settings, My Account, Standing, and let us know. one of them even got a human reply, and it was the same macro. the one real review request, the in-app one from the standing page, has been sitting at "you requested a review of this violation" for a year. no decision, no rejection, nothing. on november 6 i sent a data request to their privacy address, because that's the one channel that can't be bounced back to the standing page. it was acknowledged, and that's all i have so far. how it ended the personal account is gone. and as of today my main one shows up as deleted_user with a string of hex after it. a ten year old account, reduced to a placeholder. so there is nothing left to appeal. the thing i'd need reviewed no longer exists in their system. the funny part the username was free. i renamed the account i'm using now to motzumoto. it's not the account i lost, and none of the history came with it. but the name is mine again, and discord didn't get to keep that one. what it cost the bot mostly dodged it. i had moved Akiko to a dev team account long before the ban, so she's still here. the one thing that did get hit is her botlist listings, which sat under the banned account, so i can't edit any of them anymore. i've spent a year working around an account i can't open. if you run something on a discord account, make a team on everything that matters while you still can. I wasn't ever told this, but i did it anyway and im grateful for younger me :3

Powered by Readybot.io

Discord Ban Appeal: A 10-Year Account Deleted

Flutter and NVIDIA Edge AI: Runtime Versioning

DEV Community

Flutter + NVIDIA Edge AI: Model Versioning and Runtime Capability Negotiation

This advanced tutorial treats Flutter as the operator-facing presentation layer while wearable SDKs, Jetson services, ROS 2 nodes, and NVIDIA-accelerated inference handle device-specific or compute-heavy work. The goal is predictable latency, bounded memory, useful observability, and graceful degradation—not simply maximizing message throughput. Architecture note: Keep safety-critical control loops on the robot. A Flutter app is not a hard real-time controller and must not be the sole safety mechanism. 1. Define measurable service objectives Track freshness, event-to-display latency, throughput, frame pacing, CPU, memory, network use, battery, thermal state, dropped messages, reconnect time, and command acknowledgements. Do not use a single FPS number to represent the entire system: a smooth screen can still display stale data. 2. Instrument the complete path sensor capture
- > native/ROS processing
- > gateway publish
- > Flutter receive
- > state accepted
- > widget build
- > frame rendered
Record source and receive timestamps separately. Use monotonic clocks for elapsed durations within a process. When comparing devices, account for clock offset and uncertainty. Profile on a physical target in profile mode and inspect Flutter DevTools' Performance view. Debug-mode timing is not a reliable production baseline. See https://docs.flutter.dev/tools/devtools/performance 3. Establish a repeatable baseline Start from a clean launch. Connect to the robot or replay a fixed trace. Run a representative scenario for several minutes. Record frame times, memory, CPU, message rates, stale-data counts, and reconnects. Change one variable at a time. Compare p50, p95, and p99 latency, not just averages. class PipelineMetrics {
int received = 0;
int accepted = 0;
int dropped = 0;
int stale = 0;
int uiPublishes = 0;
}
Use bounded metric windows or histograms; do not store every sample forever. 4. Separate acquisition from presentation High-rate sources should not directly trigger widget rebuilds. Use a latest-value cache for state-like data, bounded queues for events that must be preserved, and a controlled presentation cadence. class LatestValue {
T? _value;
int _version = 0;

void put(T value) {
_value = value;
_version++;
}

T? get value => _value;
int get version => _version;
}
Replacing an older pending value may be acceptable for battery, pose, or temperature. Commands, alarms, and audit events need a separate reliable path and explicit acknowledgement semantics. 5. Make buffering bounded Every queue needs a maximum capacity, an overflow policy, a drop/replacement counter, and an owner responsible for recovery. Latest wins: pose, preview frames, current detections. Drop old items: display-oriented streams where freshness matters. Persist: events that must survive disconnection. Reject with feedback: commands that cannot safely be queued. An unbounded telemetry or log list turns overload into memory growth rather than a visible, measurable condition. 6. Protect the Flutter frame budget Keep parsing, filtering, and transformations out of build(). Split screens into independently updating sections and avoid rebuilding camera or map widgets for unrelated state changes. For CPU-heavy pure Dart work, benchmark compute or a dedicated isolate with realistic payload sizes. Isolates have startup and message-transfer costs. For hardware acceleration or platform APIs, prefer a native service designed for that workload. 7. Keep robotics compute near the robot Sensors -> ROS 2 / accelerated nodes -> Jetson gateway
|
compact UI-facing state
|
WebSocket / MQTT / gRPC
|
Flutter client
NVIDIA Isaac ROS provides accelerated, low-latency ROS 2 packages for Jetson and other NVIDIA platforms. Keep image processing, infe...

Powered by Readybot.io

Flutter and NVIDIA Edge AI: Runtime Versioning

Advanced RGB + Depth Reference Editing in One Pass

DEV Community

Reference Edit Advanced: RGB + Depth Composite Reference in a Single Video Pass

Most reference-edit workflows use one reference. This one uses two simultaneously: an RGB reference for appearance and a depth reference for geometry. The combination unlocks doing four things in a single pass that normally need four passes. What the two references each carry RGB reference — who the character is. Face structure, hair, costume, colour. Depth reference — where everything is. Camera position, subject distance from lens, scene layout. Using both means the new character inherits appearance from one and spatial position from the other. Using only RGB, the character lands wherever the model feels like putting it. The four jobs in one pass Character replacement — the subject becomes the reference character. Action inheritance — the motion of the source performance transfers. Scene and camera preservation — because depth is conditioned, the camera does not wander and the set does not rebuild itself between frames. Audio-driven lip sync — when audio is supplied, mouth movement is driven by it. Doing these separately is how most pipelines end up with a character that has the right face but the wrong head angle, because each pass re-decides. Three variants File Use Standard Default settings Silent (无声版) No audio conditioning Face Refine Extra pass on the face after the main render The Face Refine variant is worth the extra time whenever the character is in frame larger than about a third of the image height. At smaller sizes the refine pass adds nothing. Where it breaks Depth conditioning is precise but rigid. If the source performance moves the subject closer to camera in a way the depth map does not describe (because the depth was extracted from a single frame), the composite drifts at that moment. The fix is a per-frame depth extraction, which is much more expensive — and the episode shows the difference. Files HF: https://huggingface.co/AI-KSK/minimax-h3-role-swap-reference-edit ModelScope: https://modelscope.cn/models/Sunjian520/minimax-h3-role-swap-reference-edit Video walkthrough (Chinese): https://youtu.be/UespHFT9cjc Bilibili: https://www.bilibili.com/video/BV1VjaD6jEU3/ Notes Three ComfyUI workflow exports; H3 weights and the depth extractor must exist locally. Tutorial material, not a product. Independent AI-KSK release; not affiliated with the model authors.

Powered by Readybot.io

Advanced RGB + Depth Reference Editing in One Pass

Amazon Cognito Adds Per-Device Session Management

DEV Community

Cognito session management: sign out devices with Lambda

Cognito session management answers a question that every app with a login hears sooner or later: “Where am I actually signed in, and how do I kick out that old tablet?” Until now, Amazon Cognito gave you two options: sign the user out everywhere at once, or build your own table of refresh tokens. Since November 11, 2026, Cognito can list the sessions of an account by itself and end them one at a time. I care about this because a “My devices” page is no longer a luxury. People who share an account, lose a phone or suspect misuse simply expect it. In this article you build that page with the Serverless Framework, TypeScript and two small Lambda functions for a fictional bike rental called “Speichenwerk”. On top, there is a support function your team can use to end suspicious sessions. In short With the new session management, Cognito lists every active sign-in of an account across devices and app clients and ends them individually, optionally together with linked sessions. You have to turn the feature on per user pool, and it requires the Essentials or Plus feature plan. The biggest pitfall: an access token that was already issued stays valid until it expires if your API only checks it locally. What you will learn in this article how SSO sessions and token sessions differ in Cognito how to build a “My devices” API with HTTP API, JWT authorizer and Lambda how support can end sessions, including linked sessions how to pick session limits and SSO validity per app client why short-lived access tokens matter after a sign-out What is Cognito session management? Cognito session management is an extension of user pools, the user directory in Amazon Cognito. Once it is on, Cognito keeps a server-side record for every sign-in: when it started, when it was last active, which device type it came from, which IP address and which city. New API calls let you read that list and end individual entries. Before, Cognito offered essentially two tools. RevokeToken revokes a refresh token the app still holds. GlobalSignOut signs the user out everywhere. The middle ground was missing: signing out one specific device whose tokens you never see. That is exactly the gap the feature fills. SSO sessions and token sessions Cognito knows two kinds of sessions. An SSO session is created when someone signs in through managed login, the sign-in page that Cognito hosts. It lives in a browser cookie and lets the user open other app clients of the same user pool without typing the password again. A token session is created on every sign-in to an app client and follows the lifecycle of the refresh token that client received. One detail helps a lot: a token refresh does not create a new session, it extends the existing one. Only a real new sign-in creates a new token session. If that sign-in came through an SSO session, the token session remembers its “parent” in the field OriginSessionId. One SSO session can carry several token sessions, a direct sign-in through the SDK has no SSO session. The sid claim in the token With session management turned on, Cognito adds a sid claim to ID and access tokens. A claim is a field inside the JSON Web Token (JWT). Its value stays the same across all refreshes of a session, so you can use it in logs or for your own checks. Watch out if you have a pre token generation trigger that sets its own sid: Cognito leaves your claim alone, and session management has no effect for the whole pool. Cognito session management compared to RevokeToken Before you build anything, it helps to put the tools side by side. The new calls do not replace the old ones, they cover different situations. Call Who calls it? What for? RevokeToken App with refresh token normal sign-out on the current device ListUserSessions User with access token show “My devices” RevokeUserSession User with access token sign out another device of your own AdminListUserSessions Backend with IAM permissions support view, suspected misuse AdminRevokeUserSession Backend with I...

Powered by Readybot.io

Amazon Cognito Adds Per-Device Session Management

Claim $300 in Google Gemini Credits Before Nov 16

DEV Community

Last hours for $300 GCP Gemini credits, grab it if you haven't

Sorry guys, copying this quick breakdown from AI because there isn't much time left, grab it if you still haven't! Google is pulling Gemini platform (Vertex AI) out of the $300 Free Trial tomorrow (Nov 16) .) To keep it for the next 90 days, you have to sign up and click Upgrade to Paid today (Nov 15), then set a Spend Cap right after. I've got a regular VPS sitting around too and want to wire Gemini 4 into some cool open-source GitHub tools for small web utilities on techlift.solutions, instead of wasting the credits on basic chat prompts. Let me know if you already grabbed it, or tell me why it's not worth it?

Powered by Readybot.io

Claim $300 in Google Gemini Credits Before Nov 16

Post-Quantum Signatures: Why the Internet Is Catching Up

DEV Community

Your browser went quantum-safe two years ago. Your signatures are only now catching up

Your browser went quantum-safe two years ago. Your signatures are only now catching up Open any major website in a current browser and look at the handshake. There is a good chance the session key was agreed with X25519MLKEM768: a classical elliptic-curve exchange running next to ML-KEM-768, the lattice-based key encapsulation mechanism NIST standardized in FIPS 203. Nobody announced it with a banner. Chrome, Firefox, OpenSSL and OpenSSH just turned it on, and the internet kept working. That was the first half of the post-quantum migration, and it moved first for a simple reason. Key exchange is the part an attacker can exploit retroactively. Record encrypted traffic today, store it, and decrypt it years from now when a large enough quantum computer exists. That is the harvest now, decrypt later threat, and it is the reason NIST's final transition report, IR 8547, published on October 27, 2026, treats key exchange as the urgent half. The second half is signatures, and it is only now starting to ship in real software. Why signatures lagged behind A signature does a different job from a key exchange. It proves that a certificate, a token, a login, a passkey assertion or a software update really came from who it claims to come from. A forgery is only useful while the verifier still trusts the key, so there is no harvest now, decrypt later pressure on signatures. Nobody rushes to replace something that only breaks in the future. The real blocker was size. An Ed25519 signature is 64 bytes. An ML-DSA-65 signature is about 3.3 kilobytes, and its public key is close to 2 kilobytes. Put that in every certificate in a TLS chain, every JSON Web Token, every passkey assertion, and everything gets fat. Handshakes grow, tokens grow, and the protocols that carry them were never designed for signatures that big. That is why, two years after NIST finalized ML-DSA in FIPS 204, no browser-trusted certificate authority issues ML-DSA certificates yet, and no browser accepts one. The standards exist: RFC 9881, published in October 2025, defines ML-DSA in X.509 certificates, and RFC 9935, from March 2026, does the same for ML-KEM keys. The plumbing is there. The public trust part is not. What actually shipped this month On November 3, authentik, the open source identity provider, shipped version 2026.11, and it is the clearest example I have seen of the signature half moving from roadmap to release. It adds ML-DSA in three places: First, certificates. It can generate and store ML-DSA-44, ML-DSA-65 and ML-DSA-87 certificates next to the RSA, ECDSA and Ed25519 ones it already supports. These are for the parts you control: TLS between your own components, mutual TLS against a private certificate authority, and RADIUS with EAP-TLS 1.3. They are explicitly not for your public login page, because public CAs and browsers do not accept them yet. Second, OIDC tokens. OAuth2 providers can now sign ID tokens, access tokens and client assertions with an ML-DSA certificate, and the proxy outposts verify ML-DSA signed tokens from upstream identity providers. This is the part that puts actual logins onto post-quantum signatures. The honest catch, which authentik states plainly: applications that validate tokens themselves need a JWT library that understands ML-DSA before you switch a provider over. Check that first. Third, passkeys. WebAuthn registration and login accept ML-DSA credentials. No shipping authenticator supports ML-DSA yet, and some browsers error if you suggest an algorithm they do not know, so authentik puts ML-DSA at the bottom of the accepted list. Only an authenticator that offers nothing else will use it. That sounds useless until you think about it the other way: the support is in place and tested before the hardware shows up, instead of after. The same release raises the default symmetric encryption for SAML to AES-256-GCM. AES-128 is not broken by a quantum computer, but Grover's algorithm eats into its safety margin, and the NSA's CNSA 2...

Powered by Readybot.io

Post-Quantum Signatures: Why the Internet Is Catching Up

How to Build a Tsunami Simulator with Real Terrain

DEV Community

How I Built a Tsunami Simulator on Real Terrain with Mapbox and OpenStreetMap

Most disaster maps tell you where something did happen. I wanted one that answers a different question: what would happen on my street? So I built HazardSim: you click a coastline, pick a wave height, and watch the water move inland over real terrain. It also does sea level rise and meteor impacts, and there are pages for earthquakes, hurricanes and volcanoes too. This post is about how it works under the hood, and just as importantly, where it is wrong on purpose. The data Three public sources do most of the work: Elevation: Mapbox Terrain-RGB tiles, at roughly 10 to 30 m resolution. Each pixel encodes a height in its RGB channels. The documented decoding is: // Mapbox Terrain-RGB: height in metres
const height = -10000 + (R * 256 * 256 + G * 256 + B) * 0.1;
City boundaries: OpenStreetMap. When you click the map, the site finds the city under the cursor and outlines its real boundary. That polygon becomes the calculation area. Population: OSM tags, with a manual density slider as a fallback when a place has no data. The nice side effect of using real boundaries is that the output is not "a circle on a map". The flooded area respects the actual city limits. The physics (intentionally simple) I did not try to build a hydrodynamic solver. The rule is: Water enters from the sea. It floods every cell whose ground elevation is below the current water level. Every 250 m of travel, the wave loses 1 m of height. This one number stands in for friction against terrain and buildings. In pseudocode, the idea looks like this (a simplified illustration, not the production code): // BFS flood from the coastline
queue = coastCells.map(c => ({ cell: c, level: waveHeight }));
while (queue.length) {
const { cell, level } = queue.shift();
if (ground(cell) >= level) continue; // terrain blocks the water
flooded.add(cell);
const next = level - metresPerStep / 250; // lose 1 m per 250 m
for (const n of neighbours(cell)) {
if (!flooded.has(n) && next > 0) queue.push({ cell: n, level: next });
}
}
Hills, embankments and levees stop the wave, just as in reality. Water flows around obstacles and fills low ground, which is exactly what you want from a first-order tool. Sea level rise uses the same engine but without the decay: the water simply sits at the chosen mark everywhere it can reach. Meteors The meteor is a body of stone, iron, ice or loose rubble at a chosen entry speed (17 km/s by default). Damage radii come from standard overpressure scaling, and the crater is roughly twenty times wider than the body itself. Unlike tsunamis, meteors have no coastline restriction: you can drop one anywhere on Earth. One check I liked adding Tsunamis and sea level rise need a coast, so before calculating, the site checks for open sea within about 30 km of your click, using the same elevation data. If there is none, it tells you instead of producing nonsense. What it gets wrong (on purpose) This is the part I care about most. The output is an order of magnitude, not a forecast: A real tsunami depends on seafloor shape, the fault that moved, the tide and the time of day. The tool ignores all of that. It answers: if water of this height arrived here, how far inland would the terrain let it go? Casualty numbers assume nobody evacuated, which never happens in real life. The decay rule is a single constant, not a fluid simulation. I would rather ship a simple model with honest labels than a flashy one that looks authoritative. What I learned The same wave height gives wildly different results depending on only a few metres of elevation. A 10 m wave barely troubles a city on high ground, while flat deltas are devastated. Seeing that on a map is more convincing than any table. What is next Earthquake, hurricane and volcano pages exist, and I recently added an ice age map showing the ocean 130 m lower than today. There is also an Android app on Google Play. If you try it, I would love feedback, especially on the model and on places wher...

Powered by Readybot.io

How to Build a Tsunami Simulator with Real Terrain

Product Compositing: From Scene to Hero Shot

DEV Community

Product Compositing: Dissolving a Product Into a Scene, Then Finishing It as a Hero Shot

Pasting a product into a scene is easy. Making it look like it belongs there — correct contact shadow, colour bounce from the environment, and a plausible edge where the product meets the surface — is the part that takes an afternoon. This episode splits that into two jobs and gives each its own model. The two workflows # Workflow Job 01 Qwen Image 2.1 product-scene dissolve, 40-step quality + Viggle accelerated Compose the product into the scene 02 H3 VDN 12NFE high-quality second pass Finish it as a hero shot The split matters: composition and finish are different problems and a single model doing both ends up mediocre at each. What "dissolve" means here Not alpha compositing. The model re-renders the product in the scene context — which means it reconstructs the lighting on the product from the scene, adds contact shadow at the base, and lets environment colour spill onto adjacent surfaces. That is why the result reads as cohesive. It is also why the product's exact label text and logo placement drift — the model is reconstructing, not copying. The 40-step vs Viggle trade 40-step quality — label text stays legible, material reads correctly (glass reads as glass, fabric as fabric). Slow, used for the final frame. Viggle accelerated — fast enough to iterate on composition. Label text degrades first, then fine surface detail. Use the accelerated path to decide the composition, then re-run the same seed at 40 steps for the frame you actually keep. The Hero Shot pass The H3 VDN 12NFE pass takes the composited frame and re-renders it at higher fidelity. Its job is not composition — it is making the product read as a photograph rather than a composite: micro-edges, specular highlights, depth-of-field fall-off. 12 NFE is the operating point where that finish is convincing without costing a full render. Where this fits commercially E-commerce hero images without a product shoot. Seasonal variants: one product, many scenes, consistent finish. A/B testing backgrounds before committing to photography. The honest limitation: if the product has text you need exact, composite the text in after the model pass. The model will not preserve it faithfully. Files HF: https://huggingface.co/AI-KSK/h3-hero-shot-qwen21-composite ModelScope: https://modelscope.cn/models/Sunjian520/h3-hero-shot-qwen21-composite Video walkthrough (Chinese): https://youtu.be/K6HI-iuMXeg Bilibili: https://www.bilibili.com/video/BV1AsHy6nEPR/ Notes Two ComfyUI workflow exports; Qwen Image 2.1 and H3 weights must exist locally. Tutorial material, not a product. Independent AI-KSK release; not affiliated with the model authors.

Powered by Readybot.io

Product Compositing: From Scene to Hero Shot