Quantitative Content Methodology: 5-Layer Content Framework

Quantitative Content Methodology (QCM) treats content not as mere text, but as a mathematical dataset optimized for search engines and LLMs. In this guide, we explain the 5-layer content framework applicable to any topic, step-by-step.

Key Takeaways
• QCM builds pages based on semantic vectors, information density, and probabilistic word distribution.
• An entity pool is extracted prior to production; content is fed from this pool rather than through random word selection.
• An information density budget is defined for each section—targeting at least 2.5 verifiable data points per 100 words.
• The first sentence under every H2 heading serves as an “atomic answer”; it remains meaningful even when extracted from context by an LLM.
• JSON-LD schemas (FAQPage, HowTo, Dataset) present content to search engines as variable-value pairs.

Ranking on the first page is no longer enough. Generative search engines like Google’s AI Overviews, ChatGPT, and Gemini exclusively cite structured, high-information-density pages as sources when generating direct answers to user queries. QCM is an content production framework designed for this new reality.

The 5 layers below represent the methodological steps to be applied at every stage of the production process. We will use “Core Web Vitals Optimization for E-commerce Sites” as our example topic, though the skeleton is adaptable to any industry.

**The 5 Layers of QCM
**Each layer builds upon the previous one. Skipping steps diminishes the effectiveness of subsequent stages.

1. Semantic Vector Map

Before writing, the main entity (core concept) and sub-entities with vectorial proximity are identified. Embedding models (BERT, Sentence-BERT) measure word proximity using cosine similarity. If the content is written while maintaining this cluster distribution, the page signals that it “covers the entire topic.”
Layer Entity Proximity Target Frequency
Core Core Web Vitals 1.00 8–12
Primary LCP, INP, CLS 0.85–0.92 4–6
Secondary TBT, TTFB, FCP 0.70–0.80 2–3
Contextual e-commerce, conversion, cart 0.55–0.65 1–2
Authority PageSpeed, Lighthouse, web.dev 0.50–0.60 1–2
Recommendation: Define at least 15 entities for a topic. Fewer leads to superficial content; more leads to topic dilution.

2. Information Density Budget

The minimum concrete information unit—a figure, threshold, procedure, or definition—required per 100 words is pre-calculated per section. This approach prevents the “empty paragraph” syndrome and increases the Information Gain ratio.
• Target Information Gain: At least 1.3x higher than the average of the top 10 competing pages. That is, 30% more verifiable data per 100 words than the competition.

3. Probabilistic Word Distribution

The frequency and placement of key terms are pre-determined. A mathematical balance is established between over-repetition (keyword stuffing) and under-repetition (semantic weakness) based on TF-IDF and BM25 targets.
Important Positioning Rules:
• The core term must appear in the H1, H2, and both the first and last 100 words.
• Primary terms must be positioned in at least one H2 heading.
• Contextual terms should appear 1–2 times within the natural flow without feeling forced.
• Natural readability always takes precedence over frequency targets. These targets are ceilings, not mandates.

4. Structural Skeleton (LLM-friendly layout)

To enable LLMs and AI Overviews to cite content directly, each section is structured as a question-answer atom. The answer is completed in the first sentence; justifications follow in subsequent sentences.
• Atomic Answer Rule: The first sentence under each H2 contains the independently readable answer to the query. Even if an LLM extracts that sentence alone, the information remains accurate and complete.

5. JSON-LD Schema Layer

This structure explicitly notifies Google and LLMs of the page’s mathematical clarity. JSON-LD schemas present information as variable-value pairs. Google bots no longer ask “what is this about?”; they reach the clarity of “The answer to Question A is B.”
Key Schemas used in QCM:
• Article: Author, date, publisher info (Mandatory for E-E-A-T signals).
• FAQPage: Each question-answer atom in the FAQ section (Direct candidate for AI Overviews).
• HowTo: For sequential procedures (e.g., LCP reduction steps).
• Dataset: Structured markup for numerical thresholds and tables.
• BreadcrumbList: Page position in site architecture (Critical for topic clusters).
Pre- and Post-Production Audit
Before writing, the following must be answered numerically:
• Has the entity pool been extracted? (Min. 15 entities)
• Is the information density goal set for each section?
• Has the average data point count of the top 10 competitors been measured?
• Is the target Information Gain ratio defined? (1.3x recommended)
Post-publication verification metrics:
• Semantic Coverage: ≥ 85% (via InLinks / Surfer SEO)
• Information Density: ≥ 2.5 (verifiable data / 100w)
• Schema Accuracy: 0 errors (via Rich Results Test)
• LLM Source Test: Top 3 source verification (via ChatGPT / Gemini)
To apply this methodology to your own site and produce content that is shaped by data and speaks to AI, feel free to get in touch.

Comment Réduire les Coûts des Tokens d’Agent en Ligne de Commande (Guide 2026)

Un agent de codage CLI paraît économique jusqu’au moment où la facture arrive. Vous lancez Claude Code ou Codex sur un dépôt, demandez une refactorisation, puis l’agent lit quarante fichiers, relance les tests plusieurs fois et consomme des centaines de milliers de jetons pour un contexte inutile. À l’échelle d’une équipe, ce n’est plus un détail. La bonne nouvelle : une grande partie de cette dépense se réduit depuis la ligne de commande, sans changer de modèle principal ni dégrader la qualité.

Essayez Apidog aujourd’hui

TL;DR

Pour réduire le coût des agents CLI :

  1. Limitez le contexte avant qu’il n’atteigne le modèle.
  2. Nommez explicitement les fichiers à modifier.
  3. Gardez les fichiers mémoire comme CLAUDE.md courts.
  4. Utilisez /compact ou /clear entre deux tâches.
  5. Activez la mise en cache des prompts pour les préfixes stables.
  6. Routez les sous-tâches simples vers un modèle moins cher.
  7. Réduisez la sortie des outils (npm test, pytest, git diff, etc.).
  8. Mesurez le coût par exécution au lieu d’attendre la facture mensuelle.

Introduction

Le problème se voit de deux façons : soit vous atteignez une limite de session ou de quota en plein travail, soit la facture API mensuelle déclenche une discussion budgétaire. Dans les deux cas, la cause est souvent la même : les agents CLI sont verbeux et curieux par défaut.

Ils lisent des fichiers complets alors que quelques lignes suffisent, rejouent toute la conversation à chaque tour, injectent des logs bruts dans le contexte et renvoient sans cesse le même prompt système. Une refactorisation qui demande réellement 2 000 jetons de code peut facilement embarquer 180 000 jetons de contexte.

Ce guide montre comment réduire ce gaspillage avec des pratiques directement applicables à Claude Code, Codex ou tout agent CLI facturé au jeton.

Un cas fréquent concerne les API internes. Quand un agent interagit avec une API instable ou mal documentée, il boucle : requêtes échouées, lecture des erreurs, inspection de la documentation, nouvelle tentative. Chaque itération coûte des jetons.

💡 Si vos agents manipulent des API, concevoir, simuler et tester ces API dans Apidog avant de les exposer à un agent réduit fortement les cycles d’essais-erreurs. L’agent travaille contre un contrat prévisible plutôt que contre un endpoint live surprenant.

Où partent réellement les jetons d’un agent CLI

Un tour d’agent envoie une entrée au modèle et reçoit une sortie. Vous payez les deux. En général, les jetons de sortie coûtent plus cher que les jetons d’entrée, mais c’est souvent l’entrée qui explose.

Les principaux postes de coût sont :

  • Prompt système et définitions d’outils : instructions de l’agent, schémas JSON des outils, règles globales.
  • Fichiers mémoire : CLAUDE.md, conventions du projet, consignes persistantes.
  • Historique de conversation : messages, réponses, appels d’outils et résultats précédents.
  • Fichiers lus par l’agent : un fichier de 1 200 lignes peut représenter 12 000 à 18 000 jetons.
  • Sortie d’outils : logs de tests, npm install, stack traces, diffs volumineux.

Le point critique : l’historique est renvoyé à chaque tour. Une session de 30 tours ne coûte pas 30 fois un tour fixe. Elle ressemble plutôt à une somme de contextes de plus en plus longs.

C’est pourquoi les sessions longues et non structurées coûtent cher. Une explication complémentaire est disponible ici : comment la fenêtre de jetons Claude Code se réinitialise.

1. Délimitez le contexte avant de lancer l’agent

Le jeton le moins cher est celui que vous n’envoyez pas.

Évitez les prompts vagues comme :

claude "refactor the billing logic"

Préférez une instruction bornée :

claude "refactor the retry logic so it uses exponential backoff,
only in src/payments/retry.ts and src/payments/retry.test.ts"

Cette différence est simple, mais importante : l’agent ne part pas explorer tout le dépôt pour trouver les fichiers pertinents.

Si vous devez lui laisser de la marge, limitez au moins le répertoire :

claude "inspect src/payments only and propose the smallest change needed
to make retries use exponential backoff"

2. Gardez CLAUDE.md court

Un fichier mémoire comme CLAUDE.md est souvent injecté à chaque tour. Beaucoup d’équipes y mettent progressivement :

  • documentation d’onboarding ;
  • conventions générales ;
  • détails historiques ;
  • exemples obsolètes ;
  • consignes rarement utilisées.

Résultat : plusieurs milliers de jetons renvoyés en permanence.

Mesurez rapidement sa taille :

wc -c CLAUDE.md | awk '{print "≈", int($1/4), "tokens per turn"}'

Un bon CLAUDE.md doit contenir uniquement :

  • commandes de build ;
  • commandes de test ;
  • conventions strictes ;
  • chemins vers la documentation détaillée ;
  • règles que l’agent doit toujours respecter.

Exemple plus efficace :

# Instructions agent

## Tests

- Unit tests: `npm test -- --runInBand`
- Lint: `npm run lint`
- Typecheck: `npm run typecheck`

## Conventions

- Ne pas modifier `generated/`.
- Ne pas éditer les fichiers de lock sauf demande explicite.
- Préférer des changements minimaux et ciblés.

## Documentation

- API payments: `docs/payments-api.md`
- Architecture billing: `docs/billing.md`

Évitez de coller toute la documentation dans le fichier mémoire. Donnez plutôt les chemins que l’agent pourra lire à la demande.

3. Compactez ou réinitialisez les longues sessions

Si vous terminez une tâche puis en commencez une autre dans la même session, vous traînez tout l’ancien contexte.

Dans Claude Code :

/compact

Utilisez /compact quand la session contient encore des informations utiles, mais que l’historique brut devient trop lourd.

Pour une nouvelle tâche indépendante :

/clear

Règle pratique :

  • une tâche logique = une session ;
  • changement de sujet = /compact ou /clear ;
  • refactorisation terminée = nouvelle session pour la suite.

Les modèles de workflow présentés dans les flux de travail de Claude Code reposent largement sur cette discipline.

4. Ignorez les fichiers inutiles

Empêchez l’agent de lire ce qui n’a aucune valeur pour la tâche :

  • node_modules/
  • dist/
  • build/
  • fichiers générés ;
  • fichiers de lock volumineux ;
  • rapports de couverture ;
  • exports temporaires.

Exemple de fichier d’ignorance selon l’outil utilisé :

node_modules/
dist/
build/
coverage/
generated/
*.lock
package-lock.json
pnpm-lock.yaml
yarn.lock

Si un fichier de lock doit être modifié, faites-le explicitement. Sinon, il peut polluer les diffs et le contexte.

5. Activez la mise en cache des prompts

La mise en cache des prompts permet au fournisseur de réutiliser un préfixe stable : prompt système, définitions d’outils, règles de projet, conventions.

Le principe :

contenu stable → cache
contenu variable → pas dans le cache

L’ordre compte. Placez les éléments stables en premier :

outils → système → conventions projet → tâche utilisateur → fichiers récupérés

Si vous appelez directement l’API depuis votre wrapper CLI, vous pouvez définir un point de cache :

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    system=[
        {
            "type": "text",
            "text": SYSTEM_PROMPT + REPO_CONVENTIONS,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[
        {
            "role": "user",
            "content": user_task,
        }
    ],
)

u = response.usage

print("cache write:", u.cache_creation_input_tokens)
print("cache read :", u.cache_read_input_tokens)
print("fresh input:", u.input_tokens)

Points d’attention :

  • ne mettez pas d’horodatage dans le préfixe caché ;
  • ne changez pas dynamiquement les conventions projet ;
  • regroupez les exécutions proches pour garder un cache chaud ;
  • vérifiez les métriques cache_read_input_tokens.

Un bloc stable de 8 000 jetons utilisé 60 fois par jour devient beaucoup moins coûteux s’il est lu depuis le cache plutôt que retraité à chaque invocation.

Pour compléter cette approche, voir aussi l’exécution gratuite de GPT-5.5 via Codex, qui couvre d’autres stratégies de routage et de limites.

6. Routez les tâches simples vers un modèle moins cher

Toutes les actions ne nécessitent pas le modèle le plus puissant.

Exemples de tâches adaptées à un modèle économique :

  • générer un message de commit ;
  • résumer un diff ;
  • écrire une entrée de changelog ;
  • expliquer une erreur de lint ;
  • renommer une variable ;
  • produire un test standard.

Exemple CLI :

claude --model haiku "write a conventional-commit message for the staged diff"

Réservez le modèle plus coûteux aux tâches qui demandent vraiment du raisonnement :

claude --model sonnet "redesign the caching layer for the payments service"

Une bonne stratégie consiste à inverser le défaut habituel :

  • modèle économique par défaut ;
  • montée en gamme explicite quand la tâche est complexe.

Si votre framework supporte des sous-agents, donnez-leur :

  • un modèle moins cher ;
  • un contexte réduit ;
  • une mission précise.

Le parent coûteux ne reçoit ensuite qu’un résumé ou un résultat filtré. Les modèles décrits dans la commande “goal” entre Codex et Claude Code montrent comment structurer cette délégation.

Même avec une hausse de quota comme l’augmentation de la limite hebdomadaire de Claude Code, le routage reste nécessaire pour éviter de consommer le budget premium sur des tâches mécaniques.

7. Réduisez la sortie des outils

Les logs sont souvent réinjectés tels quels dans le contexte. Chaque ligne affichée par une commande peut devenir un coût répété aux tours suivants.

Tests

Au lieu de :

npm test

Utilisez une sortie plus concise :

npm test --silent -- --reporter=dot

Pour Python :

pytest -q

Ou, si vous voulez uniquement la fin du log :

pytest -q 2>&1 | tail -n 30

Installation de dépendances

Au lieu de :

npm install

Préférez :

npm install --silent --no-audit --no-fund

Diffs

Au lieu de renvoyer un diff complet :

git diff

Commencez par :

git diff --stat

Puis ciblez un fichier si nécessaire :

git diff src/payments/retry.ts

Logs d’erreur

Filtrez avant que l’agent ne voie la sortie :

npm test 2>&1 | grep -E "(FAIL|✗|Error)" | head -n 20

L’objectif n’est pas de cacher l’information utile. C’est d’éviter d’envoyer 5 000 lignes quand 30 suffisent.

8. Préférez les lectures ciblées

Lire un fichier entier pour modifier une fonction est rarement nécessaire.

Prompt utile :

Trouve la fonction qui gère les retries.
Lis uniquement cette fonction et 40 lignes autour.
Ne lis pas le fichier entier sauf si nécessaire.

Commande utile côté shell :

grep -n "function retry" src/payments/retry.ts

Puis :

sed -n '120,190p' src/payments/retry.ts

Sur un gros fichier, cette stratégie peut transformer une lecture de 18 000 jetons en quelques centaines de jetons.

9. Contraignez la récupération documentaire

Si votre agent utilise une recherche de codebase ou du RAG, limitez :

  • le nombre de fragments ;
  • la taille des fragments ;
  • les répertoires explorés ;
  • les types de fichiers.

Mauvais comportement :

Récupère toute la documentation billing et payments.

Meilleur comportement :

Récupère au maximum 5 extraits de 200 jetons sur le retry policy payments.
Ignore les guides d’onboarding et les changelogs.

Vous payez tous les jetons récupérés, même si le modèle n’en utilise qu’une petite partie.

10. Mesurez le coût par exécution

Sans mesure, vous ne savez pas si vos optimisations fonctionnent.

Si vous appelez directement une API, capturez l’objet usage :

u = response.usage

INPUT_RATE  = 3.00 / 1_000_000
OUTPUT_RATE = 15.00 / 1_000_000
CACHE_READ  = 0.30 / 1_000_000
CACHE_WRITE = 3.75 / 1_000_000

cost = (
    u.input_tokens * INPUT_RATE +
    u.output_tokens * OUTPUT_RATE +
    u.cache_read_input_tokens * CACHE_READ +
    u.cache_creation_input_tokens * CACHE_WRITE
)

print(
    f"coût ≈ ${cost:.4f} "
    f"(in={u.input_tokens}, out={u.output_tokens}, "
    f"cache_read={u.cache_read_input_tokens})"
)

Les tarifs ci-dessus sont illustratifs. Remplacez-les par les tarifs réels de votre fournisseur.

Si vous utilisez uniquement une CLI :

claude /cost

Autres pratiques utiles :

# Utiliser une clé API dédiée par projet ou agent.
# Cela évite de mélanger tous les coûts dans un seul total.

# Envelopper l’appel agent dans un script.
# Journaliser : timestamp, tâche, modèle, coût, jetons entrée/sortie.

# Comparer le coût par type de tâche :
# - refactorisation quotidienne
# - revue de PR
# - génération de tests
# - résumé de diff

Exemple de CSV minimal :

timestamp,task,model,input_tokens,output_tokens,cache_read_tokens,cost_usd
2026-05-20T09:15:00Z,commit-message,haiku,1800,120,0,0.0031
2026-05-20T09:30:00Z,payments-refactor,sonnet,42000,2100,16000,0.1840

Après une semaine, vous verrez rapidement quelles tâches consomment le plus.

Comparaison des tactiques

Tactique Économies typiques Effort
Nommer les fichiers à modifier 30–60% sur l’entrée par exécution Faible
Réduire CLAUDE.md 5–15% par tour Faible
Utiliser /compact ou /clear 40–80% sur longues sessions Faible
Mettre en cache le prompt stable ~90% sur le préfixe caché Moyen
Router les tâches simples 50–80% sur les sous-tâches Moyen
Filtrer la sortie des outils 20–50% sur les tâches intensives en outils Faible
Lire des fenêtres ciblées 70–95% sur gros fichiers Faible
Limiter la récupération RAG 30–60% sur agents documentaires Moyen
Mesurer le coût par exécution 0% direct, mais active toutes les optimisations Faible

Ces chiffres sont indicatifs. Les gains réels dépendent de votre niveau de gaspillage initial.

Checklist d’implémentation

À appliquer dans cet ordre :

[ ] Réduire CLAUDE.md aux instructions strictement nécessaires
[ ] Ajouter un fichier d’ignorance pour dist/, build/, node_modules/, coverage/
[ ] Modifier les prompts pour nommer les fichiers ciblés
[ ] Utiliser /compact ou /clear entre deux tâches
[ ] Rendre les commandes de test silencieuses
[ ] Remplacer git diff par git diff --stat par défaut
[ ] Router commit messages, résumés et changelogs vers un petit modèle
[ ] Activer la mise en cache des prompts si vous utilisez un wrapper API
[ ] Journaliser le coût par tâche pendant une semaine

Conclusion

Les coûts des agents CLI viennent rarement d’une seule mauvaise décision. Ils viennent surtout d’un contexte trop large, de logs trop verbeux, d’un historique jamais nettoyé et de modèles trop puissants pour des tâches simples.

Commencez par les changements à faible effort : prompts ciblés, fichiers mémoire courts, sorties silencieuses et sessions compactées. Ajoutez ensuite la mise en cache et le routage des modèles. Vous réduirez la facture sans réduire la qualité du travail produit.

Agent Token Kosten reduzieren per CLI (2026 Anleitung)

Ein CLI-Codierungsagent fühlt sich frei an, bis die Rechnung kommt. Sie richten Claude Code oder Codex auf ein Repository, lassen ein Modul refaktorisieren, und zehn Minuten später hat der Agent vierzig Dateien gelesen, die Testsuite dreimal ausgeführt und sechsstellige Token-Mengen für Kontext verbraucht, den er nie gebraucht hätte. In einem Team mit mehreren Entwicklern wird daraus schnell ein echter Kostenfaktor. Die gute Nachricht: Ein großer Teil dieser Token-Kosten lässt sich direkt über CLI-Workflows, Konfiguration und bessere Prompts reduzieren.

Teste Apidog noch heute

TL;DR

Reduzieren Sie Token-Kosten von CLI-Agenten, indem Sie den Kontext begrenzen, bevor er das Modell erreicht:

  • Arbeitssatz explizit eingrenzen
  • Speicherdateien wie CLAUDE.md kurz halten
  • lange Sitzungen mit /compact oder /clear kürzen
  • Prompt-Caching für stabile Präfixe aktivieren
  • einfache Unteraufgaben an günstigere Modelle routen
  • Tool-Ausgaben filtern
  • Kosten pro Lauf messen

Das Ziel ist nicht, schlechtere Modelle oder weniger Automatisierung zu nutzen. Das Ziel ist, keine Tokens für irrelevanten Kontext zu bezahlen.

Einführung

Token-Kosten zeigen sich meist auf zwei Arten:

  1. Sie erreichen mitten in einer Aufgabe ein Wochen- oder Sitzungslimit.
  2. Die monatliche API-Rechnung ist deutlich höher als erwartet.

Beides hat dieselbe Ursache: CLI-Agenten sind standardmäßig kontexthungrig. Sie lesen ganze Dateien, wenn zehn Zeilen reichen würden. Sie senden die gesamte Unterhaltung bei jeder Runde erneut. Sie leiten rohe Test- und Build-Logs zurück in den Kontext. Und sie übertragen dieselben System-Prompts, Tool-Definitionen und Repo-Konventionen hunderte oder tausende Male pro Tag.

Eine Refaktorisierung, die wirklich über 2.000 Tokens Code nachdenken muss, braucht keine 180.000 Tokens Kontext. Die Differenz ist Ihr Einsparpotenzial.

Dieser Leitfaden zeigt konkrete Maßnahmen für:

  • Kontexthygiene und Speicherdateien
  • Prompt-Caching
  • Modell-Routing
  • kürzere Tool-Ausgaben
  • gezielte Dateiabrufe
  • Kostenmessung pro Agentenlauf

Die Beispiele beziehen sich auf Claude Code und Codex, gelten aber für jeden CLI-Agenten, der über eine tokenbasierte API abgerechnet wird.

Ein zusätzlicher Kostenfaktor ist Debugging. Wenn ein Agent eine fehlerhafte interne API aufruft, wiederholt er Requests, liest Fehlertexte, lädt Dokumentation erneut und kann in teuren Schleifen hängen bleiben.

💡 Wenn Ihre Agenten APIs nutzen, lohnt es sich, diese APIs vorher in Apidog zu designen, zu mocken und zu testen. Der Agent arbeitet dann gegen einen stabilen Vertrag statt gegen einen Live-Endpunkt, der unerwartet reagiert. Das reduziert teure Trial-and-Error-Schleifen.

Wohin Tokens bei einem CLI-Agentenlauf gehen

Eine Agentenrunde besteht aus:

  • Eingabe-Payload an das Modell
  • Ausgabe-Payload vom Modell

Sie zahlen für beides. Bei vielen Anbietern sind Output-Tokens deutlich teurer als Input-Tokens. Die konkreten Preise ändern sich, aber die Struktur bleibt gleich: Output ist teuer, und Input explodiert durch wiederholten Kontext.

Typische Token-Quellen:

  • System-Prompt und Tool-Definitionen

    Agentenanweisungen plus JSON-Schemas aller Tools. Oft 5.000 bis 15.000 Tokens pro Runde.

  • Speicher- und Projektdateien

    Dateien wie CLAUDE.md, Repo-Konventionen oder persistente Regeln. Sie werden häufig bei jeder Runde geladen.

  • Gesprächsverlauf

    Frühere Benutzernachrichten, Modellantworten, Tool-Aufrufe und Tool-Ergebnisse. Dieser Verlauf wächst mit jeder Runde.

  • Gelesene Dateien

    Ein Read einer Datei mit 1.200 Zeilen kann schnell 12.000 bis 18.000 Tokens kosten.

  • Tool-Ausgabe

    Testlogs, npm install-Ausgaben, Stacktraces, Lockfile-Diffs und Build-Rauschen.

Der wichtigste Punkt: Der Gesprächsverlauf wird bei jeder Runde erneut gesendet. Eine 30-Runden-Sitzung kostet nicht einfach 30 einzelne Runden. Spätere Runden tragen den gesamten bisherigen Kontext mit.

Wenn Sie tiefer verstehen möchten, wie Sitzungen und Limits in der Praxis abgerechnet werden, lesen Sie ergänzend wie das Token-Fenster von Claude Code zurückgesetzt wird.

Kontexthygiene und Speicherdateien

Das billigste Token ist das, das Sie nie senden. Kontexthygiene ist deshalb der wichtigste Hebel.

1. Arbeitssatz vor dem Start eingrenzen

Starten Sie den Agenten nicht im Repo-Root mit einem vagen Auftrag wie:

claude "refactor the billing logic"

Das lädt den Agenten dazu ein, das Repository breit zu durchsuchen.

Besser:

claude "refactor the retry logic so it uses exponential backoff,
only in src/payments/retry.ts and its test file"

Noch besser, wenn Sie das Zielverhalten explizit machen:

claude "In src/payments/retry.ts, replace the fixed retry delay with exponential backoff.
Update only the related tests in src/payments/retry.test.ts.
Do not inspect unrelated payment modules unless a test failure requires it."

Das spart Tokens, weil der Agent nicht erst zwanzig Dateien lesen muss, um die zwei relevanten zu finden.

2. Speicherdateien kurz halten

Eine Datei wie CLAUDE.md wird oft bei jeder Runde in den Kontext geladen. Wenn sie wie ein Wiki behandelt wird, zahlen Sie dauerhaft für irrelevanten Text.

Prüfen Sie grob die Größe:

wc -c CLAUDE.md | awk '{print "≈", int($1/4), "tokens per turn"}'

Eine gute CLAUDE.md enthält:

# Project instructions

## Build
- npm run build

## Test
- npm test
- npm run test:unit -- --runInBand for focused unit runs

## Conventions
- Use TypeScript strict mode.
- Keep public API changes backward-compatible.
- Prefer small focused diffs.

## Docs
- API contract docs live in docs/api.md.
- Payment retry behavior is documented in docs/payments/retry.md.

Vermeiden Sie:

  • lange Architekturhistorien
  • vollständige API-Dokumentation
  • Onboarding-Texte
  • selten relevante Spezialfälle

Verlinken Sie stattdessen auf tiefere Dokumente, die der Agent nur bei Bedarf lesen soll.

3. Lange Sitzungen kompaktieren oder zurücksetzen

Wenn eine Aufgabe abgeschlossen ist, starten Sie nicht direkt die nächste Aufgabe im selben Verlauf. Sonst trägt jede neue Runde das alte Transkript mit.

In Claude Code:

/compact

Das fasst den Verlauf zusammen und verwirft das rohe Transkript.

Für einen echten Neustart:

/clear

Praktische Regel:

  • eine logische Aufgabe pro Sitzung
  • nach Abschluss /compact oder /clear
  • keine unabhängigen Aufgaben im selben Kontext stapeln

Die Muster in den Claude Code Workflows bauen stark auf diesem Scoping auf.

4. Ignorierdateien nutzen

Halten Sie generierte oder große Dateien außerhalb der Reichweite des Agenten:

node_modules/
dist/
build/
coverage/
*.lock
*.log

Wenn Ihr Agent eine eigene Ignore-Datei unterstützt, ergänzen Sie dort zusätzlich:

docs/generated/
openapi.generated.json
large-fixtures/

Alles, was der Agent nicht sieht, kann er nicht lesen, diffen oder erneut in den Kontext laden.

Prompt-Caching: Nicht mehrfach für dasselbe Präfix zahlen

Prompt-Caching speichert stabile Teile Ihrer Anfrage, etwa:

  • Tool-Definitionen
  • System-Prompt
  • Repo-Konventionen
  • statische Projektregeln

Nachfolgende Anfragen mit demselben Präfix können diesen Teil günstiger wiederverwenden.

Die Grundregel:

stabiler Kontext zuerst
flüchtiger Kontext zuletzt

Typische Reihenfolge:

tools → system → messages

Alles, was sich häufig ändert, gehört hinter den Cache-Breakpoint:

  • aktuelle Benutzernachricht
  • Zeitstempel
  • frisch gelesene Dateien
  • aktuelle Tool-Ergebnisse

Wenn Sie einen eigenen Wrapper verwenden, können Sie Caching explizit setzen:

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    system=[
        {
            "type": "text",
            "text": SYSTEM_PROMPT + REPO_CONVENTIONS,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[
        {
            "role": "user",
            "content": user_task,
        }
    ],
)

u = response.usage

print("cache write:", u.cache_creation_input_tokens)
print("cache read :", u.cache_read_input_tokens)
print("fresh input:", u.input_tokens)

Wichtig für stabile Cache-Treffer:

  • keine Zeitstempel im gecachten Bereich
  • keine zufälligen IDs im System-Prompt
  • gleiche Tool-Reihenfolge
  • gleiche Formatierung
  • stabile Repo-Konventionen

Ein täglicher Refactor-Agent mit einem 8.000-Token-Konventionsblock und 60 Aufrufen pro Tag ist ein klassischer Anwendungsfall. Ohne Caching zahlen Sie den Block 60-mal vollständig. Mit Caching zahlen Sie einmal den Schreibvorgang und danach deutlich günstigere Cache-Reads.

Die OpenAI-API bietet bei unterstützten Modellen ein ähnliches Prinzip für gecachte Eingaben. Details unterscheiden sich, aber das Muster bleibt gleich: stabile Präfixe lohnen sich.

Wenn Caching allein nicht reicht, sind die Free-Tier- und Routing-Muster im Artikel zum kostenlosen Betrieb von GPT-5.5 über Codex eine sinnvolle Ergänzung.

Modell-Routing: Günstiges Modell für einfache Arbeit

Nicht jede Agentenaktion braucht ein Frontier-Modell.

Diese Aufgaben eignen sich oft für ein günstigeres Modell:

  • Commit-Nachrichten schreiben
  • Changelog-Einträge formulieren
  • Diffs zusammenfassen
  • einfache Tests generieren
  • Lint-Fehler erklären
  • Boilerplate erstellen
  • Symbolnamen konsistent umbenennen

Beispiel:

claude --model haiku "write a conventional-commit message for the staged diff"

claude --model sonnet "redesign the caching layer for the payments service"

Die bessere Standardstrategie:

günstiges Modell als Default
teures Modell nur bei Bedarf

Viele Teams machen es umgekehrt und lassen alles „zur Sicherheit“ über das teuerste Modell laufen. Das ist besonders teuer bei hochfrequenten Aufgaben wie Commit-Messages oder kleinen Testanpassungen.

Unteragenten gezielt routen

Wenn Ihr Framework Unteragenten unterstützt, geben Sie ihnen:

  • kleines Modell
  • kleinen Kontext
  • eng definierte Aufgabe

Beispielstruktur:

Parent agent:
- nutzt starkes Modell
- entscheidet Architektur und finale Änderungen

Subagent:
- nutzt günstiges Modell
- sucht relevante Dateien
- fasst Testfehler zusammen
- liefert kurze Ergebnisliste zurück

Dadurch sieht das teure Modell nur destillierte Ergebnisse statt roher Logs und kompletter Suchläufe.

Die autonomen Schleifenmuster im Zielbefehl über Codex und Claude Code zeigen, wie solche Delegation strukturiert werden kann.

Auch bei Plänen mit Nutzungslimits hilft Routing. Sie verbrauchen Ihr Premium-Kontingent nicht für triviale Aufgaben. Die Erhöhung des wöchentlichen Limits von Claude Code hilft zwar, ersetzt aber kein sinnvolles Routing.

Tool-Ausgabe und Abruf kürzen

Tool-Ausgabe ist ein versteckter Kostentreiber. Jeder Befehl, den der Agent ausführt, erzeugt Text. Dieser Text landet im Kontext und wird später erneut gesendet.

Typische Probleme:

  • npm install mit tausenden Zeilen
  • ausführliche Testlogs
  • vollständige Stacktraces
  • große git diff-Ausgaben
  • generierte Lockfile-Diffs
  • komplette Dateien statt relevanter Ausschnitte

1. Befehle leise machen

Statt:

npm test

besser:

npm test --silent -- --reporter=dot

Statt:

npm install

besser:

npm install --silent --no-audit --no-fund

Für Python:

pytest -q

Für gezielte Tests:

pytest tests/payments/test_retry.py -q

2. Ausgabe filtern, bevor der Agent sie sieht

Nur die letzten relevanten Zeilen:

pytest -q 2>&1 | tail -n 30

Nur Fehlerzeilen:

npm test 2>&1 | grep -E "(FAIL|✗|Error)" | head -n 20

Nur Diff-Statistik:

git diff --stat

Nur Diff für relevante Dateien:

git diff -- src/payments/retry.ts src/payments/retry.test.ts

Das ist oft ausreichend, damit der Agent den nächsten Schritt ableitet.

3. Gezielte Dateiabschnitte lesen

Eine komplette Datei mit 1.500 Zeilen zu lesen, nur um eine Funktion zu ändern, ist teuer.

Besserer Prompt:

Find the retry function in src/payments/retry.ts.
Read only the function and its surrounding tests.
Do not read the entire file unless necessary.

Oder manuell vorbereiten:

grep -n "function retry" src/payments/retry.ts
sed -n '80,160p' src/payments/retry.ts

Das reduziert einen möglichen 18.000-Token-Lesevorgang auf wenige hundert Tokens.

4. RAG- und Suchabrufe begrenzen

Wenn Ihr Agent Dokumente oder Code-Chunks abruft, begrenzen Sie:

  • Anzahl der Chunks
  • Chunk-Größe
  • Suchbereich
  • Dateitypen
  • Verzeichnisse

Besser:

Return the top 8 chunks, max 250 tokens each, only from docs/api and src/payments.

Schlechter:

Search the whole repo and include all relevant context.

Sie zahlen für jeden abgerufenen Token, auch wenn das Modell ihn nicht nutzt.

Kosten pro Lauf messen

Ohne Messung optimieren Sie blind. Ziel ist nicht nur eine niedrigere Monatsrechnung, sondern Kosten pro repräsentativer Aufgabe.

Wenn Sie die API direkt verwenden, speichern Sie das usage-Objekt:

u = response.usage

INPUT_RATE  = 3.00 / 1_000_000
OUTPUT_RATE = 15.00 / 1_000_000
CACHE_READ  = 0.30 / 1_000_000
CACHE_WRITE = 3.75 / 1_000_000

cost = (
    u.input_tokens * INPUT_RATE +
    u.output_tokens * OUTPUT_RATE +
    u.cache_read_input_tokens * CACHE_READ +
    u.cache_creation_input_tokens * CACHE_WRITE
)

print(
    f"run cost ≈ ${cost:.4f} "
    f"(in={u.input_tokens} "
    f"out={u.output_tokens} "
    f"cache_read={u.cache_read_input_tokens})"
)

Die Preise sind nur Platzhalter. Ersetzen Sie sie durch die aktuellen Preise Ihres Modells.

Wenn Sie eine Agenten-CLI nutzen:

claude /cost

Zusätzlich sinnvoll:

# separater API-Key pro Projekt oder Agent
# dadurch sehen Sie Kosten in der Anbieter-Konsole sauber getrennt

Oder ein Wrapper-Skript:

#!/usr/bin/env bash

TASK="$1"
START="$(date -Iseconds)"

claude "$TASK"

END="$(date -Iseconds)"

echo "$START,$END,$TASK" >> agent-runs.csv

Noch besser ist ein Log mit:

  • Aufgabe
  • Modell
  • Input-Tokens
  • Output-Tokens
  • Cache-Reads
  • Cache-Writes
  • geschätzten Kosten
  • Git-Branch oder PR-ID

Messen Sie dann wiederkehrende Aufgaben:

Kosten pro täglichem Refactoring-Lauf
Kosten pro PR-Review
Kosten pro Testfix
Kosten pro API-Dokumentationsupdate

Wenn Sie Caching aktivieren oder Unteraufgaben routen, sollte sich diese Zahl sichtbar ändern. Falls nicht, optimieren Sie an der falschen Stelle.

Taktikvergleich

Taktik Typische Token-Einsparung Aufwand
Arbeitssatz eingrenzen 30–60% Input pro Lauf Gering
Kurze, stabile Speicherdatei 5–15% pro Runde Gering
/compact oder /clear zwischen Aufgaben 40–80% bei langen Sitzungen Gering
Prompt-Caching für stabile Präfixe ~90% für gecachten Kontext Mittel
Modell-Routing 50–80% bei gerouteten Unteraufgaben Mittel
Leise oder gefilterte Tool-Ausgabe 20–50% bei tool-intensiven Läufen Gering
Gezieltes Lesen statt ganzer Dateien 70–95% bei großen Dateien Gering
Begrenzter Abrufbereich 30–60% bei RAG-intensiven Agenten Mittel
Kostenmessung pro Lauf 0% direkt, ermöglicht Optimierung Gering

Die Werte sind illustrativ. Einsparungen addieren sich nicht linear, sondern wirken häufig multiplikativ.

Praktische Checkliste

Wenden Sie diese Reihenfolge an:

  1. Repo-Ignorierregeln setzen

    • node_modules/
    • dist/
    • coverage/
    • generierte Dateien
    • große Fixtures
  2. CLAUDE.md kürzen

    • nur Build-, Test- und Stilregeln
    • keine langen Dokumentationen
    • auf Detaildocs verlinken
  3. Prompts enger schreiben

    • konkrete Dateien nennen
    • Zielverhalten beschreiben
    • unnötige Exploration verbieten
  4. Tool-Ausgaben filtern

    • --silent
    • -q
    • tail
    • grep
    • git diff --stat
  5. Sitzungen trennen

    • eine Aufgabe pro Session
    • danach /compact oder /clear
  6. Günstige Modelle als Default

    • einfache Aufgaben günstig routen
    • teures Modell bewusst eskalieren
  7. Prompt-Caching aktivieren

    • stabile Präfixe byte-stabil halten
    • volatile Inhalte nach hinten schieben
  8. Kosten messen

    • pro Lauf
    • pro Aufgabe
    • pro Projekt oder Agent

Fazit

Token-Kosten von CLI-Agenten sind oft selbst verursacht: zu viel Kontext, zu laute Tools, zu lange Sitzungen und zu teure Modelle für einfache Aufgaben.

Die wirksamsten Maßnahmen sind einfach:

  • Dateien und Aufgaben eng eingrenzen
  • Speicherdateien schlank halten
  • Tool-Ausgaben kürzen
  • lange Konversationen kompaktieren
  • einfache Arbeit an günstigere Modelle geben
  • stabile Präfixe cachen
  • Kosten pro Lauf messen

Starten Sie mit den Maßnahmen mit geringem Aufwand. Sie kosten fast nichts, wirken aber bei jedem Agentenlauf. Danach bringen Prompt-Caching und Modell-Routing die Einsparungen auf ein Niveau, das sich im Team-Budget sichtbar bemerkbar macht.

We Stopped Using Microservices. Here Is What We Learned.

We Stopped Using Microservices. Here Is What We Learned.

Two years ago we split our monolith into 12 microservices. Eighteen months ago we merged five of them back. Here is what that taught us.

Why We Split

Deploy times were 45 minutes. Teams were stepping on each other. We thought microservices would fix it.

What Microservices Actually Gave Us

Distributed tracing complexity. Network partition headaches. Data consistency nightmares. Deployment coordination across teams. More infrastructure cost.

Why We Merged Back

The problem was not the architecture. It was the team structure. Microservices require clear domain ownership. We had overlapping boundaries and constant coordination overhead.

What Stayed Split

Services that genuinely have different scaling profiles. Payment processing stays separate from the main app. Public API stays separate.

The Lesson

Microservices are an organizational pattern, not a technical one. If your team structure is not ready, the architecture will fight you.

What is your architecture?

The Monitoring Stack We Actually Use in Production

The Monitoring Stack We Actually Use in Production

Prometheus, Grafana, and three things nobody talks about until they break.

Our Stack

Prometheus for metrics. Grafana for dashboards. PagerDuty for alerts. Sentry for errors. Standard setup.

What Nobody Talks About

Alert fatigue. We had 200 alerts. 180 were noise. Engineers started ignoring everything. When real problems came, nobody noticed for 4 hours.

Dashboard rot. Grafana dashboards that nobody updates. Engineers trust the numbers but nobody checks if the queries are still correct.

Correlation is hard. An alert fires. You spend 40 minutes correlating logs, metrics, and traces to find the real cause.

What We Changed

Cut alerts from 200 to 30. Only alert on symptoms, not causes. CPU at 90% is a cause. Error rate spike is a symptom. Alert on symptoms.

Added runbook links to every alert. When it fires, you know exactly what to do.

Set up a weekly dashboard review. Dead dashboards get archived.

The ROI

Oncall rotation went from miserable to manageable. Mean time to detect dropped from 45 minutes to 8 minutes. Mean time to resolve dropped from 3 hours to 45 minutes.

What is your monitoring setup?

I thought we needed another agent framework — turns out we needed a job_id and a boring config folder

A lot of agent engineering advice still sounds like framework shopping.

Should you use OpenClaw or n8n?
Is LiteLLM enough?
Do you need LangGraph, an MCP server, or a custom Rust runtime with a dashboard that looks like Mission Control?

After reading a bunch of real production threads, I think most teams are solving the wrong problem.

They think they need a better framework.

What they actually need is:

  • a shared config layer for prompts, tools, and policies
  • explicit model routing
  • run-level tracing with a stable job_id
  • one place to see what happened across retries, tool calls, fallbacks, and provider swaps

That’s the boring part of agent systems.

It’s also the part that keeps long-running automations from turning into folklore.

The pattern I kept seeing

I kept running into Reddit posts from people who said they wanted an agent framework comparison.

But when you read closely, they were describing operations problems.

One thread on r/openclaw was from someone running OpenClaw in production on a Mac Mini M4 with 16GB RAM, using GPT-5.5 via OAuth, Telegram as the interface, memory, workflow routing, and a side-by-side sandbox for testing a second framework.

The key line was this:

Building a portable ‘brain’ layer (prompts, memory, workflows, routing rules) that can eventually work across multiple frameworks

That is not a framework problem.

That is the adult version of agent engineering.

Another thread described an API gateway with a Rust correlator where every run gets a job_id and that ID follows the run across LLM calls and tool invocations.

That’s the layer most teams are missing.

Not another runtime.

A durable operational spine.

What actually breaks first in long-running agents?

Not intelligence.

Operations.

The first failures are usually boring:

  • runaway loops
  • fallback confusion
  • stale memory
  • duplicated retry logic
  • expensive models handling cheap tasks
  • no way to explain one bad run end-to-end

One OpenClaw user said they burned through tokens their first week because the agent looped on heartbeat checks and cron pings.

That should sound familiar to anyone who has let an automation run overnight.

The fix was not a better prompt.

The fix was routing policy.

They moved routine work to cheaper models and kept stronger reasoning models for the hard parts.

That’s the move.

Not “make the agent smarter.”

Make the default path cheaper and easier to debug.

Cheap defaults beat clever prompts

If your agent is doing background work like this:

  • heartbeat checks
  • cron pings
  • email triage
  • status polling
  • repetitive browser steps
  • simple classification

…then sending every step to Claude Opus or GPT-5 is just expensive laziness.

Use the expensive model when the run has earned it.

A simple routing policy gets you further than another week of prompt tuning:

TASK_TO_MODEL = {
    "heartbeat_check": "fast-cheap",
    "cron_ping": "fast-cheap",
    "email_triage": "fast-cheap",
    "status_poll": "fast-cheap",
    "classification": "mid-tier",
    "browser_exception": "strong-reasoning",
    "complex_reasoning": "strong-reasoning",
}


def pick_model(task_name: str) -> str:
    return TASK_TO_MODEL.get(task_name, "mid-tier")

If you’re running agents in n8n, Make, Zapier, OpenClaw, or custom workers, this matters a lot more than people admit.

Most runaway cost comes from boring background work nobody classified.

The one thing I’d add before adopting another framework

Before you migrate anything, add a job_id.

Not request IDs.

Run IDs.

A single long-running automation can touch:

  • GPT-5.4
  • Claude Opus 4.6
  • Grok 4.20
  • browser tools
  • webhooks
  • approval steps
  • retries
  • queues

If your observability stops at request logs, you don’t really have observability.

You have receipts.

What you need is a story for one run.

Here’s the minimum useful pattern:

import uuid


def start_job() -> str:
    return f"job_{uuid.uuid4().hex}"


job_id = start_job()

headers = {
    "x-job-id": job_id,
    "x-agent-name": "support-triage",
}

# pass these headers into every LLM request, tool call, and webhook

Then aggregate by job_id:

  • model used at each step
  • latency
  • retries
  • tool calls
  • fallbacks
  • token usage
  • cost
  • human interventions

Once you do that, incident review gets much easier.

Instead of asking:

Why is the dashboard weird?

You can ask:

What happened in job_123?

That’s a much better question.

The repo shape tells you whether a team gets agent ops

The healthiest setups I’ve seen all converge on the same basic shape.

Keep the durable stuff separate from the replaceable stuff.

agents/
  openclaw-prod/
    .env
    workflows/
    runtime/
  sandbox-framework/
    .env
    workflows/
    runtime/
shared-brain/
  prompts/
  tools/
  policies/
  memory-schema.json
  routing.yaml

That layout says:

  • prompts are portable
  • tool contracts are portable
  • policies are portable
  • memory schema is portable
  • runtimes are disposable

That’s what you want.

Because OpenClaw might change.
Your n8n flow might become a Python worker.
Your memory layer might move to a Cloudflare Worker exposed over MCP.
Your provider mix might change next month.

If your prompts, policies, and memory schema are trapped inside one framework’s opinionated format, every migration becomes painful for no good reason.

A practical routing config beats framework magic

I’d rather have a plain YAML file I can inspect than hidden routing logic buried in a framework abstraction.

For example:

default_model: gpt-5.4-mini
routes:
  heartbeat_check: gpt-5.4-mini
  cron_ping: gpt-5.4-mini
  email_triage: gpt-5.4-mini
  browser_automation: claude-opus-4.6
  research_synthesis: gpt-5.4
  fallback_reasoning: grok-4.20
budgets:
  max_cost_per_job_usd: 0.75
  max_llm_calls_per_job: 40
fallbacks:
  - from: claude-opus-4.6
    to: gpt-5.4
  - from: gpt-5.4
    to: grok-4.20

Now your routing policy is visible.

You can diff it.
You can review it in PRs.
You can compare behavior across frameworks.

That is a lot more useful than another demo of an autonomous agent planning vacation itineraries.

Framework choice still matters, just less than people think

To be fair: framework choice is not fake.

It matters if you care about:

  • built-in memory models
  • local model support for Qwen or Llama
  • UI ergonomics
  • tool ecosystem
  • workflow authoring style
  • MCP support

But once agents become operationally important, framework choice stops being the center of gravity.

The real questions become:

  • Can I move prompts and policies without rewriting everything?
  • Can I compare Claude, GPT-5, and Grok on the same job type?
  • Can I see cost, latency, retries, and tool calls in one run view?
  • Can I stop silent fallback behavior before it burns budget?
  • Can I swap runtimes without losing my memory schema?

That’s agent ops.

It’s less glamorous than framework demos.

It’s also what survives six months of production use.

The tradeoff, plainly

Approach What happens over time
Framework-centric setup Fast to start, but prompts, memory, and workflow logic get tightly coupled to one runtime
API gateway plus portable config Better visibility, easier provider swaps, cleaner routing control, but requires discipline around schemas and metadata
Direct provider integrations in each workflow Fine for small projects, but routing, observability, and fallback logic get duplicated everywhere

If you are a solo builder with one short-lived agent, don’t build a giant control plane.

That’s overkill.

But if you have multiple workflows, long-running jobs, or agents running 24/7, the framework-first setup starts rotting from the edges.

Every workflow invents its own retry logic.
Every prompt drifts.
Every dashboard tells a different partial truth.

That’s usually when teams start looking for an OpenAI API alternative.

And honestly, what they often want is not just lower pricing.

They want one consistent execution layer where routing, budgets, and visibility are not reinvented inside every single agent.

Why this connects directly to cost

This is the part people miss.

Agent ops is cost control.

If you can’t see a run end-to-end, you can’t answer:

  • why one workflow got expensive
  • which model handled each step
  • whether fallback increased cost
  • whether retries multiplied spend
  • whether background tasks should be routed to cheaper models

That’s why flat, predictable AI compute is interesting for automation teams.

Not because pricing is a nice spreadsheet feature.

Because per-token billing punishes exactly the kind of experimentation and long-running execution that agent systems need.

If you’re building automations that run all day in n8n, Make, Zapier, OpenClaw, or custom workers, token anxiety becomes an architecture problem.

You start avoiding useful checks.
You under-instrument jobs.
You hesitate to add retries.
You route too much logic through one provider because cost modeling is annoying.

That’s backwards.

The infrastructure should make long-running jobs easier to operate, not harder to justify.

This is a big part of why services like Standard Compute are interesting to teams building agents and automations.

You keep the OpenAI-compatible API surface, but you get predictable monthly pricing, dynamic routing across models like GPT-5.4, Claude Opus 4.6, and Grok 4.20, and you stop treating every extra automation step like a billing event you need to babysit.

That changes how people build.

Especially once jobs run 24/7.

My practical recommendation

If your first instinct is to adopt another framework, stop for a minute.

Do these four things first:

1. Add a shared config layer

Put prompts, policies, tool definitions, and memory schema outside the runtime.

2. Add explicit routing rules

Don’t let model selection happen implicitly.

3. Add a job_id

Trace one run across every LLM call, tool call, retry, and fallback.

4. Add budget controls outside the framework

Make spend limits and fallback policy visible and editable without rewriting workflow code.

If you want a tiny starting point, even this is enough:

mkdir -p shared-brain/{prompts,tools,policies}
touch shared-brain/memory-schema.json
touch shared-brain/routing.yaml

Then wire your runtime to read from it.

That one decision will age better than most framework migrations.

The boring layer is the real product

The cleanest mental model I’ve found is to separate three things:

1. The brain

Prompts, policies, workflow definitions, tool contracts, memory references.

2. The runtime

OpenClaw, n8n, a Python worker, a Rust gateway, a Cloudflare Worker, whatever runs the job today.

3. The ops layer

Routing, budgets, tracing, correlation, failover rules, reporting.

If those are fused together, every change becomes political.

Switching providers feels risky.
Testing a second framework feels expensive.
Debugging a bad run feels like archaeology.

If those layers are separate, your system gets boring in the best possible way.

And boring is exactly what you want when an agent has been running for eight hours, touched email, Telegram, browser automation, and background jobs, and now somebody wants to know why it made one weird decision at 3:14 AM.

My takeaway is simple.

Most teams do not need another agent framework.

They need a shared config folder, explicit routing rules, and a job_id that can explain what their agent did all night.

New Here 👋 eCommerce Developer & Digital Marketing Enthusiast

MagentoBrain

Hi everyone,
I’m excited to join the DEV Community!

I work mainly in the eCommerce industry with strong experience in:

Shopify store development
Magento eCommerce solutions
Custom online store setup
SEO & digital marketing
Google Ads and performance marketing
Helping businesses grow their online presence

Over the years, I’ve worked on creating and optimizing eCommerce stores for different industries, focusing on both design and business growth.

I’m here to:

Connect with developers and marketers
Share insights from real client projects
Learn new technologies and trends
Exchange ideas around eCommerce, SEO, and marketing

Looking forward to interacting with all of you and contributing to the community 🚀

Would love to know:

What technologies are you currently working with?
Are you more into development, design, or marketing?

shopify #magento #ecommerce #seo #webdev #marketing

MagentoBrain

Google Wants AI to Run the Scientific Method

Google launched Gemini for Science yesterday at I/O 2026, and it is the most interesting thing to come out of the keynote. Not the smart glasses, not the new subscription tier, not Gemini Spark promising to coordinate your Gmail and close your laptop. The science suite. Because it is the clearest statement yet of what Google actually thinks AI agents are for.

The pitch is direct: science is drowning in its own output. Millions of papers per year, petabytes of biological data, a growing gap between what the literature contains and what any individual researcher can hold in their head. Google’s framing is that general agents, not narrow specialist models, are the right tool to close that gap. Gemini for Science is the first concrete product that argument.

There are three experimental tools. Hypothesis Generation is built on top of something Google calls Co-Scientist. You feed it a research challenge, and it runs what the announcement describes as a “multi-agent idea tournament”: multiple sub-agents generate hypotheses, debate them, and evaluate them against each other. The winning ideas come with clickable citations and, Google claims, deep verification. Computational Discovery is an agentic engine built on AlphaEvolve that generates and scores thousands of code variations in parallel, designed to dramatically expand the number of hypotheses a lab can actually test. Then there is Science Skills, a bundle that integrates data from more than 30 major life science databases including UniProt, AlphaFold, AlphaGenome, and InterPro. Google says teams using it have compressed complex structural bioinformatics analyses from hours to minutes, and that in early testing it produced novel insights about mechanisms behind a rare genetic disease involving the AK2 gene.

These are still prototypes on Google Labs. I want to be clear about that. No peer-reviewed paper yet confirms the hypothesis quality. The “idea tournament” framing is evocative but we don’t know how it compares to a grad student with a lit review and a week of focused reading. The AK2 claim is intriguing and completely unverified by anyone outside Google.

But here is the thing that keeps pulling at me. The structure of the scientific method, generate a hypothesis, design a test, interpret results, iterate, is actually a good fit for agentic systems in a way that most knowledge-work tasks are not. Code review, document drafting, customer support: these are all things where a human can spot a bad output quickly. Bad science, on the other hand, can look convincing for years. The speed advantage is real; the verification problem is equally real, and Gemini for Science doesn’t fully solve it.

Demis Hassabis closed his section of the keynote by telling the audience that looking back on this moment, we’d realize we were “standing in the foothills of the singularity.” The Engadget live blog response was “Lol, Lmao even.” That reaction is fair. It is also slightly too easy.

I think Hassabis is wrong about the timeline and the framing, but he is pointing at something true. The part of science that is bottlenecked by synthesis, by the human inability to hold the full literature in working memory, is exactly the part that language models are good at. If the hypothesis tournament produces even one genuinely novel connection per hundred tries that a human researcher would not have found, the economics change. Not because AI is smarter than a scientist, but because it is faster, tireless, and can hold more context simultaneously.

The “foothills of the singularity” language is designed to generate attention. The quiet part of the announcement, the 30-database integration inside Google’s Antigravity platform, is where the actual science will get tested or not. That rollout is worth watching more carefully than the keynote rhetoric.

Cách giảm chi phí token của agent từ CLI (Hướng dẫn 2026)

Một tác nhân mã hóa CLI (Claude Code, Codex hoặc công cụ tương tự) có thể đốt token rất nhanh: đọc hàng chục tệp, chạy test nhiều lần, đưa log dài vào ngữ cảnh và phát lại toàn bộ lịch sử ở mỗi lượt. Với một nhóm kỹ sư dùng tác nhân cả ngày, chi phí này không còn là phần nhỏ của hóa đơn. Tin tốt: phần lớn token bị lãng phí có thể giảm ngay từ dòng lệnh mà không cần đổi mô hình hoặc chấp nhận đầu ra kém hơn.

Dùng thử Apidog hôm nay

TL;DR

Để giảm chi phí token của tác nhân CLI:

  • Khoanh vùng tập hợp tệp trước khi giao việc.
  • Giữ CLAUDE.md hoặc tệp bộ nhớ dự án thật ngắn.
  • Dùng /compact hoặc /clear giữa các tác vụ.
  • Bật prompt caching cho phần prompt ổn định.
  • Định tuyến tác vụ đơn giản sang mô hình rẻ hơn.
  • Cắt bớt output của test, install, diff và log.
  • Đo chi phí theo từng lần chạy, không chỉ nhìn hóa đơn cuối tháng.

Token bị tiêu ở đâu trong một lần chạy tác nhân CLI?

Mỗi lượt của tác nhân gửi một payload đầu vào đến mô hình và nhận lại payload đầu ra. Bạn trả tiền cho cả hai. Trên nhiều nhà cung cấp, token đầu ra thường đắt hơn token đầu vào, nhưng token đầu vào mới là phần dễ phình to nhất vì nó bao gồm rất nhiều ngữ cảnh lặp lại.

Một payload đầu vào thường có:

  • System prompt và định nghĩa tool: hướng dẫn tác nhân, schema JSON của tool, quy tắc hành vi.
  • Tệp bộ nhớ dự án: ví dụ CLAUDE.md, quy ước repo, lệnh build/test.
  • Lịch sử hội thoại: tin nhắn người dùng, phản hồi mô hình, tool call, tool result.
  • Nội dung tệp đã đọc: một lần đọc toàn bộ tệp 1.200 dòng có thể thành hàng chục nghìn token.
  • Output của tool: log test, npm install, stack trace, git diff, lockfile.

Điểm quan trọng: lịch sử hội thoại được gửi lại ở mỗi lượt. Một phiên 30 lượt không chỉ tốn gấp 30 lần một lượt; các lượt sau còn kéo theo toàn bộ nội dung trước đó. Vì vậy, phiên dài, lan man là một trong những nguồn lãng phí lớn nhất.

Nếu bạn muốn hiểu thêm về phiên và giới hạn token trong thực tế, xem thêm bài viết về cách cửa sổ token Claude Code được đặt lại.

Một chi phí liên quan khác là debugging API. Khi tác nhân gọi một API nội bộ chưa ổn định, nó có thể thử lại, đọc lỗi, đọc tài liệu, sửa code rồi lặp tiếp. Mỗi vòng như vậy đều tiêu token.

💡 Nếu tác nhân của bạn làm việc với API, hãy thiết kế, mock và kiểm thử API trong Apidog trước khi đưa tác nhân vào luồng xử lý. Khi API có hợp đồng rõ ràng, tác nhân sẽ ít phải đoán, ít phải thử sai và ít đốt token hơn.

1. Khoanh vùng tập hợp làm việc trước khi chạy tác nhân

Token rẻ nhất là token không bao giờ được gửi.

Đừng mở tác nhân ở root repo rồi prompt kiểu:

claude "tái cấu trúc logic thanh toán"

Prompt này buộc tác nhân phải tự khám phá codebase. Nó có thể đọc nhiều file không liên quan trước khi tìm đúng chỗ.

Thay vào đó, hãy chỉ rõ phạm vi:

claude "tái cấu trúc logic retry để dùng exponential backoff.
Chỉ chỉnh src/payments/retry.ts và test tương ứng."

Hoặc nếu chưa biết chính xác tệp:

claude "tìm logic retry trong thư mục src/payments.
Chỉ đọc các file liên quan trực tiếp, không quét toàn repo."

Nguyên tắc thực tế:

  • Giao một tác vụ rõ ràng cho mỗi phiên.
  • Nêu thư mục hoặc file cụ thể.
  • Nói rõ phần nào không được động vào.
  • Nếu cần khám phá, giới hạn ở một thư mục nhỏ.

Các mẫu làm việc trong quy trình làm việc của Claude Code cũng nhấn mạnh thói quen khoanh vùng này.

2. Giữ tệp bộ nhớ dự án thật ngắn

Các tệp như CLAUDE.md thường được nạp vào ngữ cảnh ở nhiều lượt. Nếu tệp này biến thành wiki dài 4.000 token, bạn đang trả tiền cho nó liên tục.

Kiểm tra nhanh kích thước tương đối:

wc -c CLAUDE.md | awk '{print "≈", int($1/4), "tokens per turn"}'

Một CLAUDE.md tốt nên chứa:

# Project conventions

## Commands

- Build: npm run build
- Test: npm test -- --runInBand
- Lint: npm run lint

## Coding rules

- TypeScript strict mode.
- Do not edit generated files.
- Prefer small functions.
- Add tests for changed behavior.

## Important paths

- API clients: src/api/
- Payment logic: src/payments/
- Generated files: src/generated/ (do not edit)

Không nên nhét vào:

  • Tài liệu onboarding dài.
  • Lịch sử kiến trúc.
  • Toàn bộ API docs.
  • Nội dung chỉ dùng cho một tác vụ hiếm gặp.

Nếu tài liệu dài vẫn cần thiết, để đường dẫn cho tác nhân đọc khi cần:

For payment provider details, read docs/payments/provider-contract.md only when required.

3. Dùng /compact hoặc /clear giữa các tác vụ

Khi bạn hoàn thành một việc và chuyển sang việc khác, đừng tiếp tục dùng cùng phiên chỉ vì tiện. Mỗi lượt mới sẽ kéo theo lịch sử cũ.

Trong Claude Code:

/compact

Dùng khi bạn vẫn cần giữ tóm tắt ngắn của phiên trước nhưng muốn loại bỏ transcript thô.

/clear

Dùng khi bắt đầu tác vụ mới không liên quan.

Quy trình đơn giản:

  1. Bắt đầu phiên cho một tác vụ cụ thể.
  2. Chạy tác nhân, review diff, test.
  3. Khi xong, dùng /compact nếu cần tiếp tục cùng chủ đề.
  4. Dùng /clear trước khi chuyển sang tác vụ khác.

Việc này thường giảm mạnh lượng context được gửi lại trong các phiên dài.

4. Cấu hình ignore để tác nhân không đọc rác

Tác nhân không nên đọc:

  • node_modules/
  • dist/
  • build/
  • coverage output
  • generated files
  • lockfile lớn nếu không cần
  • log hoặc artifact CI

Ví dụ .gitignore hoặc tệp ignore tương ứng của agent:

node_modules/
dist/
build/
coverage/
*.log
src/generated/

Nếu repo có lockfile lớn, bạn có thể nhắc tác nhân:

Không đọc package-lock.json trừ khi tác vụ liên quan trực tiếp đến dependency resolution.

Lợi ích của bước này là lâu dài: cấu hình một lần, tiết kiệm ở mọi lần chạy.

5. Bật prompt caching cho phần ổn định

Prompt caching cho phép nhà cung cấp lưu một tiền tố ổn định của request, ví dụ:

  • system prompt
  • tool definitions
  • quy ước repo
  • hướng dẫn cố định

Các request sau dùng lại tiền tố đó với chi phí thấp hơn đáng kể.

Theo tài liệu prompt caching của Anthropic, cache write có chi phí cao hơn input token thông thường, nhưng cache read chỉ khoảng 10% input cơ bản. Nghĩa là phần prefix ổn định có thể được giảm giá khoảng 90% khi cache hit. Con số cụ thể có thể thay đổi theo nhà cung cấp và thời điểm, nên luôn kiểm tra trang giá chính thức.

Nguyên tắc cấu trúc:

tools → system → messages

Đặt phần ổn định lên trước, phần thay đổi xuống sau.

Ví dụ nếu bạn gọi model trực tiếp:

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=2048,
    system=[
        {
            "type": "text",
            "text": SYSTEM_PROMPT + REPO_CONVENTIONS,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[
        {
            "role": "user",
            "content": user_task,
        }
    ],
)

u = response.usage

print("cache write:", u.cache_creation_input_tokens)
print("cache read :", u.cache_read_input_tokens)
print("fresh input:", u.input_tokens)

Lưu ý vận hành:

  • Không chèn timestamp vào prefix được cache.
  • Không thay đổi byte trước cache breakpoint nếu không cần.
  • Gom các lần chạy liên quan gần nhau để tăng khả năng cache hit.
  • Đo cache_read_input_tokens để xác nhận cache thật sự hoạt động.

Nếu caching chưa đủ, bạn có thể kết hợp với các mẹo định tuyến trong bài chạy GPT-5.5 miễn phí qua Codex.

6. Định tuyến tác vụ đơn giản sang mô hình rẻ hơn

Không phải mọi việc đều cần mô hình mạnh nhất.

Các tác vụ thường có thể chạy bằng mô hình rẻ hơn:

  • viết commit message
  • tóm tắt diff
  • tạo changelog
  • giải thích lỗi lint đơn giản
  • đổi tên biến
  • viết test boilerplate
  • format lại tài liệu

Ví dụ:

claude --model haiku "viết commit message theo Conventional Commits cho diff đã stage"

claude --model sonnet "thiết kế lại lớp caching cho payment service"

Cách đặt mặc định hợp lý:

  • Mặc định dùng mô hình rẻ cho tác vụ cơ học.
  • Chỉ nâng lên mô hình mạnh khi cần reasoning, thiết kế hoặc refactor phức tạp.
  • Tách tác vụ phụ ra khỏi phiên chính nếu có thể.

Nếu framework agent hỗ trợ sub-agent, hãy cho sub-agent dùng mô hình rẻ và context nhỏ. Sub-agent có thể tìm kiếm, tóm tắt, lọc kết quả rồi trả lại thông tin cô đọng cho agent chính.

Các mẫu tự động hóa trong lệnh mục tiêu trên Codex và Claude Code là ví dụ hữu ích cho kiểu ủy quyền này.

Nếu bạn dùng gói có giới hạn thay vì trả theo token thuần túy, định tuyến còn giúp kéo dài quota. Việc tăng giới hạn hàng tuần của Claude Code có ích, nhưng không thay thế được việc dùng đúng mô hình cho đúng việc.

7. Cắt bớt output của tool

Tool output là nguồn lãng phí dễ bị bỏ qua. Mỗi dòng log được trả về cho tác nhân có thể đi vào context và tiếp tục được phát lại ở lượt sau.

Làm command im lặng hơn

Thay vì:

npm test

Dùng:

npm test --silent -- --reporter=dot

Thay vì:

npm install

Dùng:

npm install --silent --no-audit --no-fund

Chỉ trả về phần log quan trọng

pytest -q 2>&1 | tail -n 30
npm test 2>&1 | grep -E "(FAIL|✗|Error)" | head -n 20
git diff --stat

Chỉ dùng full diff khi thật sự cần:

git diff src/payments/retry.ts

Tránh đọc toàn bộ file lớn

Thay vì để tác nhân đọc file 1.500 dòng, yêu cầu nó tìm symbol trước:

Tìm hàm xử lý retry trong src/payments/retry.ts.
Chỉ đọc vùng code quanh hàm đó, không đọc toàn bộ file nếu không cần.

Hoặc dùng CLI:

grep -n "function retry" src/payments/retry.ts
sed -n '120,220p' src/payments/retry.ts

Khác biệt có thể là vài trăm token thay vì hàng chục nghìn token.

8. Giới hạn truy xuất trong RAG hoặc code search

Nếu tác nhân dùng tìm kiếm codebase hoặc RAG trên tài liệu, hãy giới hạn:

  • số lượng đoạn trả về
  • kích thước mỗi đoạn
  • thư mục được tìm kiếm
  • loại file được phép đọc

Ví dụ prompt:

Tìm tối đa 5 đoạn liên quan nhất.
Mỗi đoạn không quá 200 token.
Ưu tiên src/payments và docs/payments.
Không đọc generated files.

Mười đoạn ngắn, đúng trọng tâm thường tốt hơn năm mươi đoạn dài làm nhiễu context. Bạn trả tiền cho mọi token được truy xuất, dù mô hình có dùng hay không.

9. Đo chi phí theo từng lần chạy

Bạn không thể tối ưu thứ mình không đo.

Nếu gọi API trực tiếp, lưu usage metadata:

u = response.usage

INPUT_RATE  = 3.00 / 1_000_000
OUTPUT_RATE = 15.00 / 1_000_000
CACHE_READ  = 0.30 / 1_000_000
CACHE_WRITE = 3.75 / 1_000_000

cost = (
    u.input_tokens * INPUT_RATE +
    u.output_tokens * OUTPUT_RATE +
    u.cache_read_input_tokens * CACHE_READ +
    u.cache_creation_input_tokens * CACHE_WRITE
)

print(
    f"run cost ≈ ${cost:.4f} "
    f"(in={u.input_tokens} out={u.output_tokens} "
    f"cache_read={u.cache_read_input_tokens})"
)

Các mức giá trên chỉ để minh họa. Hãy thay bằng giá thực tế của model bạn dùng.

Nếu dùng CLI agent, có thể đo bằng cách:

# Kiểm tra chi phí phiên nếu CLI hỗ trợ
claude /cost

Hoặc tách API key theo dự án/tác nhân để dashboard nhà cung cấp phân bổ chi phí rõ hơn.

Một wrapper script đơn giản cũng đủ hữu ích:

#!/usr/bin/env bash

TASK_LABEL="$1"
shift

START=$(date -Iseconds)

claude "$@"

END=$(date -Iseconds)

echo "$START,$END,$TASK_LABEL" >> agent-runs.csv

Sau đó ghi thêm chi phí/token từ CLI hoặc dashboard vào CSV. Sau một tuần, bạn sẽ biết tác vụ nào đang tốn tiền nhất.

Bảng so sánh chiến thuật

Chiến thuật Mức tiết kiệm token điển hình Nỗ lực
Khoanh vùng tập hợp làm việc 30–60% input mỗi lần chạy Thấp
Rút gọn tệp bộ nhớ dự án 5–15% mỗi lượt Thấp
/compact hoặc /clear giữa các tác vụ 40–80% trong phiên dài Thấp
Prompt caching cho prefix ổn định ~90% trên phần được cache Trung bình
Định tuyến mô hình 50–80% trên tác vụ phụ phù hợp Trung bình
Tool output im lặng hoặc đã lọc 20–50% với workflow nhiều tool Thấp
Đọc có mục tiêu thay vì đọc toàn file 70–95% trên file lớn Thấp
Giới hạn RAG/code search 30–60% với agent dùng truy xuất nhiều Trung bình
Đo chi phí từng lần chạy Không giảm trực tiếp, nhưng giúp tối ưu đúng chỗ Thấp

Các con số trên chỉ mang tính minh họa. Mức tiết kiệm thực tế phụ thuộc vào mức lãng phí ban đầu trong workflow của bạn.

Checklist triển khai nhanh

Áp dụng theo thứ tự này để có hiệu quả nhanh:

  1. Rút gọn CLAUDE.md.
  2. Thêm ignore cho dist/, build/, coverage/, generated files.
  3. Luôn prompt với file/thư mục cụ thể.
  4. Dùng /clear khi đổi tác vụ.
  5. Dùng /compact khi phiên dài nhưng vẫn cùng chủ đề.
  6. Chuyển command test/install sang chế độ ít log.
  7. Dùng git diff --stat trước khi full diff.
  8. Đặt model rẻ cho commit message, changelog, tóm tắt.
  9. Bật prompt caching nếu bạn gọi model trực tiếp.
  10. Ghi lại token/chi phí theo từng tác vụ đại diện.

Kết luận

Chi phí token của tác nhân CLI thường không đến từ phần reasoning thật sự, mà từ context thừa, log thừa, lịch sử phiên quá dài và việc dùng mô hình đắt cho tác vụ đơn giản.

Bắt đầu bằng các thay đổi rẻ nhất: khoanh vùng tác vụ, làm sạch tệp bộ nhớ, cắt output tool và reset phiên đúng lúc. Sau đó thêm prompt caching, model routing và đo chi phí theo từng lần chạy. Khi các thói quen này trở thành mặc định, hóa đơn giảm mà chất lượng công việc vẫn giữ nguyên.

node-ipc Had a 69 Trust Score Before It Got Hacked. TanStack Had 91.

Two npm supply chain attacks hit the same week. One was predictable. One wasn’t. That’s the point.

May 2026 gave us two back-to-back supply chain attacks on npm. Same week. Completely different mechanics. And that tells you more about the state of supply chain security than any whitepaper.

May 11: TanStack — 42 packages, 84 malicious versions in 6 minutes. @tanstack/react-router alone gets 16.9 million weekly downloads.

May 14: node-ipc — 3 malicious versions. 730K weekly downloads. Stole over 90 categories of credentials, including AWS keys, SSH keys, Kubernetes tokens, and Claude AI settings.

I ran both through getcommit.dev — a behavioral scoring tool I built that measures structural risk signals in npm, PyPI, Cargo, and Go packages.

TanStack scored 91. node-ipc scored 69 with a WARN flag.

The 69 was there before the attack.

What happened at node-ipc

node-ipc is a 12-year-old inter-process communication library. One npm publisher. 35 GitHub contributors who can’t publish to npm. Last legitimate release: August 2024 — 21 months of silence.

On May 14, someone published three malicious versions simultaneously across two major version lines (9.x and 12.x). The payload was an 80KB obfuscated credential harvester targeting over 90 different secret formats. The compromised npm account had been dormant long enough to steal without anyone noticing.

The behavioral data before the attack:

Signal Score What it means
Longevity 25/25 12.2 years. Established.
Maintainer depth 4/15 1 npm publisher. Single point of failure.
Release consistency 12/20 646 days since last publish. Dormant.
Trusted Publishing 0/2 No OIDC provenance. No cryptographic link between source and release.
Total 69 WARN

A sole publisher. A dormant release cycle. No provenance. Every signal was pointing at the risk. This is the pattern behind the LiteLLM attack (March 2026) and the axios incident (March 30, 2026): steal the credentials of a single person who hasn’t published in months, and 730,000 weekly consumers get the payload.

What happened at TanStack

TanStack was different. Five npm publishers. Active development — the last publish was 3 days before the attack. Score: 91. HEALTHY by every behavioral metric.

The attacker didn’t steal anyone’s npm credentials. They exploited a chain of three vulnerabilities in TanStack’s GitHub Actions setup:

  1. pull_request_target in a workflow, which lets fork code run with base repo permissions
  2. GitHub Actions cache poisoning across the fork → base trust boundary
  3. Memory extraction of the OIDC token from the GitHub Actions runner process (reading /proc at runtime)

The malware published 84 versions across 42 packages in six minutes. It passed SLSA provenance checks. It carried valid signed certificates. Every automated security tool looking at cryptographic proof of origin said “this is legitimate.”

OpenAI published a response because TanStack was in their dependency tree. Detection took 20 minutes. Cleanup took hours. But the attack bypassed the exact mechanism — provenance attestation — that was supposed to make CI/CD-origin attacks impossible.

What the scores actually tell you

Two attacks. Two completely different risk profiles:

node-ipc TanStack
Score 69 (WARN) 91 (HEALTHY)
Publishers 1 5
Last publish 21 months ago 3 days ago
Provenance No Yes
Attack vector Stolen npm credentials CI/CD pipeline compromise
Predictable? Yes No

Behavioral signals caught the node-ipc pattern. They didn’t catch TanStack’s. SLSA provenance was supposed to catch TanStack’s. It didn’t.

No single tool catches both. That’s not a failure — it’s the reality. Different attacks exploit different trust boundaries.

Which pattern is more common

The node-ipc pattern is far more common than the TanStack pattern. The GitHub Actions cache-poisoning chain is sophisticated — it required chaining three separate vulnerabilities. Stealing a dormant npm account’s credentials requires buying them on a dark web marketplace.

There are 26 npm packages with over 10 million weekly downloads and a single npm publisher. Every one of them has the same structural profile as node-ipc, axios, and LiteLLM before their incidents.

minimatch    — 610M/wk, 1 publisher  ⚑ CRITICAL
chalk        — 436M/wk, 1 publisher  ⚑ CRITICAL
glob         — 355M/wk, 1 publisher  ⚑ CRITICAL
cross-spawn  — 168M/wk, 1 publisher  ⚑ CRITICAL
zod          — 145M/wk, 1 publisher  ⚑ CRITICAL

These won’t appear in your package.json. They’re in your lock file — transitive dependencies you’ve never audited, installed on every npm install.

Check your own project

npx proof-of-commitment --file package-lock.json

This scans your full dependency tree — direct and transitive — and flags the structural risks that npm audit doesn’t look at.

It won’t predict the next TanStack. But it’ll surface every node-ipc-shaped package in your tree. And right now, that’s the pattern that keeps repeating.

Try it on any package: getcommit.dev/npm/node-ipc

getcommit.dev — behavioral supply chain scoring for npm, PyPI, Cargo, and Go. Open source on GitHub.