Context Window Engineerのロゴ

Context Window Engineer

コミュニティ
roedyrustam
context-window-engineer

200万トークン超のコンテキストウィンドウの最適化、プロンプトキャッシュの固定、予算の分割

Add to TypingMind

概要

公開者roedyrustam
リポジトリvibes-plug
スキル名context-window-engineer
スター
117
フォーク
27
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    roedyrustamがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Context Window Engineer」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/roedyrustam/vibes-plug/tree/main/skills/context-window-engineer
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/roedyrustam/vibes-plug.git /tmp/vibes-plug
mkdir -p .claude/skills
cp -r /tmp/vibes-plug/skills/context-window-engineer .claude/skills/context-window-engineer
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでContext Window Engineerを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にContext Window Engineerを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Context Window Engineerは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

context-window-engineer — vibes-plug Skill

English | Bahasa Indonesia


English

Orchestration & Integration

  • Upstream & Orchestration: zero-to-prod-orchestrator (Phase 4 AI integration), brainstorming, session-memory-manager (context zone snapshots & handoff).
  • Prefix Locking & Model Cascading: kv-cache-prefix-optimizer (Zone 1-2 cache boundary alignment), adaptive-model-cascade (overflow routing across model sizes), llm-finops-router (per-zone token cost accounting).
  • Frontier LLMs & Model Boosters: frontier-ai-models-expert (2M+ token recall curves), gemini-agent-booster (Google 2M+ native context caching), vercel-ai-sdk-expert (context streaming & tools).
  • Research & Deep Ingestion: deep-research-analyst (retrieval-augmented injection), vector-db-rag-expert (retrieval vs context stuffing decisions).

Description

Production guide for engineering, partitioning, and optimizing ultra-large context windows (128k → 2M+ tokens) across frontier models. Prevents the most common failure mode in 2026 AI applications: dumping raw data into context without structure, causing degraded recall, wasted tokens, and hallucination amplification in the "lost in the middle" zone.

Trigger Conditions

Activate this skill when:

  • Building AI agents or applications that consume >50k tokens of context per request.
  • Experiencing degraded model recall, "lost in the middle" failures, or hallucinations in long-context scenarios.
  • Architecting Retrieval-Augmented Generation (RAG) systems that need to decide between retrieval vs. long-context stuffing.
  • Optimizing token costs for applications with large system prompts, tool registries, or codebase context maps.
  • Designing multi-turn agentic loops where context accumulates across dozens of turns.

Core Concepts & Patterns

1. Context Window Capacity Map (Late-2026 Frontier Models)
ModelTierMax ContextEffective Recall ZoneCost per 1M Input TokensCache Discount
Gemini 4 ArgonMedium2,097,152~1.9M (monolithic)$0.8075% (native context caching)
Gemini 4 ProHigh2,097,152–10M~1.8M (reliable)$1.2575% (explicit cache)
Gemini 3.8 Flash (Fallback)Fast/Medium1,048,576~900k$0.1075% (native context caching)
Claude Opus 5.5Medium500,000~480k$10.0090% (prompt cache)
Claude Opus 4.6 (Fallback)Medium200,000~180k$8.0090% (prompt cache)
Claude Sonnet 5.5High500,000~480k$3.0090% (prompt cache)
Claude Fable 5.1High500,000~480k$2.5090% (prompt cache)
GPT-5.6 SolMedium500,000~450k$1.5050% (prefix cache)
Grok 4.7 High FastHigh Fast256,000~240k$0.5080% (prompt cache)
Composer 2.5 FastFast200,000~180k$0.3080% (AST diff cache)
2. The Context Partitioning Architecture

Never treat the context window as a flat buffer. Partition it into semantically meaningful zones with explicit priority ordering:

┌──────────────────────────────────────────────────────┐
│ ZONE 1: IMMUTABLE SYSTEM DIRECTIVES (1-3%)           │
│   System prompt, behavioral guardrails, output format │
│   ► NEVER changes mid-session                        │
├──────────────────────────────────────────────────────┤
│ ZONE 2: STATIC REFERENCE CONTEXT (10-40%)            │
│   Codebase schemas, API specs, tool definitions,     │
│   architectural docs, PRD excerpts                   │
│   ► Changes only between sessions                    │
├──────────────────────────────────────────────────────┤
│ ZONE 3: RETRIEVED CONTEXT (20-50%)                   │
│   RAG chunks, relevant code files, search results,   │
│   documentation snippets                             │
│   ► Dynamically injected per query via retrieval      │
├──────────────────────────────────────────────────────┤
│ ZONE 4: CONVERSATION HISTORY (10-30%)                │
│   Prior turns, summarized older context,             │
│   tool call results                                  │
│   ► Sliding window with intelligent summarization     │
├──────────────────────────────────────────────────────┤
│ ZONE 5: ACTIVE QUERY + SCRATCHPAD (1-5%)             │
│   Current user message, chain-of-thought workspace   │
│   ► Most volatile, always at the tail                │
└──────────────────────────────────────────────────────┘
3. Token Budget Allocation (TypeScript Implementation)
typescript
export interface ContextBudget {
  totalCapacity: number;
  zones: {
    systemDirectives: { maxTokens: number; priority: 1 };
    staticReference: { maxTokens: number; priority: 2 };
    retrievedContext: { maxTokens: number; priority: 3 };
    conversationHistory: { maxTokens: number; priority: 4 };
    activeQuery: { maxTokens: number; priority: 5 };
  };
}

export function createBudget(modelCapacity: number): ContextBudget {
  return {
    totalCapacity: modelCapacity,
    zones: {
      systemDirectives: { maxTokens: Math.floor(modelCapacity * 0.02), priority: 1 },
      staticReference: { maxTokens: Math.floor(modelCapacity * 0.30), priority: 2 },
      retrievedContext: { maxTokens: Math.floor(modelCapacity * 0.40), priority: 3 },
      conversationHistory: { maxTokens: Math.floor(modelCapacity * 0.25), priority: 4 },
      activeQuery: { maxTokens: Math.floor(modelCapacity * 0.03), priority: 5 },
    },
  };
}

export function enforceTokenBudget(
  zoneContents: Map<string, string>,
  budget: ContextBudget,
  tokenCounter: (text: string) => number
): Map<string, string> {
  const result = new Map<string, string>();
  const zones = Object.entries(budget.zones).sort(([, a], [, b]) => a.priority - b.priority);

  for (const [zoneName, { maxTokens }] of zones) {
    const content = zoneContents.get(zoneName) ?? '';
    const tokenCount = tokenCounter(content);

    if (tokenCount <= maxTokens) {
      result.set(zoneName, content);
    } else {
      result.set(zoneName, truncateToTokenLimit(content, maxTokens, tokenCounter));
    }
  }

  return result;
}

function truncateToTokenLimit(
  content: string,
  maxTokens: number,
  tokenCounter: (text: string) => number
): string {
  const lines = content.split('\n');
  let accumulated = '';
  for (const line of lines) {
    const candidate = accumulated ? `${accumulated}\n${line}` : line;
    if (tokenCounter(candidate) > maxTokens) break;
    accumulated = candidate;
  }
  return accumulated;
}
4. "Lost in the Middle" Mitigation

Frontier models exhibit degraded recall for information positioned in the middle 40-60% of the context. Mitigate with:

  1. Needle Placement: Place the most critical context at the very beginning (Zone 1-2) and very end (Zone 5) of the prompt.
  2. Structural Anchors: Use explicit section headers (=== CRITICAL: Database Schema ===) to create attention anchors.
  3. Redundant Summarization: For critical facts, include both the raw data AND a summary at the top.
  4. Chunked Retrieval: Break large documents into semantically coherent chunks (512-1024 tokens each) rather than inserting monolithic blocks.
5. RAG vs. Long-Context Decision Matrix
CriterionUse RAG (Retrieve & Inject)Use Long-Context Stuffing
Corpus size>10M tokens total corpus<2M tokens total corpus
Query specificityNarrow, focused queriesBroad, synthesis-oriented queries
FreshnessCorpus updates frequentlyCorpus is static per session
Cost sensitivityHigh (pay only for retrieved chunks)Lower priority (amortized via cache)
Recall requirementPrecision-critical (top-k retrieval)Recall-critical (need full picture)
6. Sliding Window Strategy for Multi-Turn Agents
typescript
export interface TurnSummary {
  turnIndex: number;
  role: 'user' | 'assistant';
  summary: string;
  tokenCount: number;
  fullContent?: string;
}

export function buildSlidingWindow(
  allTurns: TurnSummary[],
  maxHistoryTokens: number,
  recentTurnsToKeepFull: number = 4
): string[] {
  const recentFull = allTurns.slice(-recentTurnsToKeepFull);
  const older = allTurns.slice(0, -recentTurnsToKeepFull);

  let budget = maxHistoryTokens;
  const output: string[] = [];

  for (const turn of recentFull) {
    const content = turn.fullContent ?? turn.summary;
    budget -= turn.tokenCount;
    output.push(content);
  }

  if (budget > 0 && older.length > 0) {
    const olderSummaries = older.map((t) => `[Turn ${t.turnIndex}] ${t.summary}`);
    output.unshift(`=== SUMMARIZED EARLIER CONTEXT ===\n${olderSummaries.join('\n')}`);
  }

  return output;
}

Best Practices

  1. Always Count Tokens Before Injection: Use tiktoken (OpenAI), @anthropic-ai/tokenizer, or Gemini's countTokens() API to measure actual token counts.
  2. Cache-Align Zone Boundaries: Coordinate with kv-cache-prefix-optimizer so static zones (1-2) align with KV-cache prefix boundaries.
  3. Measure Recall Quality: Instrument needle-in-haystack tests at various context depths to validate your model's effective recall zone.
  4. Degrade Gracefully: When context exceeds budget, drop Zone 4 (older history) first, then Zone 3 (retrieved context), never Zone 1-2.
  5. Monitor Token Spend Per Zone: Log per-zone token consumption to data-telemetry-expert dashboards to identify context bloat early.

Common Pitfalls to Avoid

Anti-PatternConsequenceRemedy
Dumping entire codebase into contextExceeds effective recall zone, hallucination spikesUse targeted retrieval + file relevance scoring
No zone partitioningCritical instructions get "lost in the middle"Implement explicit zone headers and priority ordering
Ignoring token countingSilent context truncation by model APIPre-count and enforce budgets client-side
Keeping full conversation history foreverContext fills up after 10-15 turnsImplement sliding window with summarization

Sovereign Execution, Token Efficiency & Invariants

DimensionSovereign Mandate & Deterministic Contract
Frontier Model CascadeMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Availability FallbackGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Zero unhandled missing-model errors)
KV-Cache & Token ProtocolPin static instructions & schemas at prompt prefix (kv-cache-prefix-optimizer); pass surgical CONTEXT_MAP.md slices (<250 tokens/call) during Swarm Fan-Out
SaaT CLI & MCP DispatchCLI: vibes skill exec context-window-engineer <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
NFR & Anti-Slop InvariantsP99 API Gateway Latency < 85ms, OpenAPI 3.1 / TypeSpec strict schema parity, RFC 9457 Problem Details error contracts, Idempotency-Key enforcement; 100% complete zero-placeholder output verified via node scripts/check-anti-slop.js --strict


Bahasa Indonesia

Integrasi Orkestrasi

  • Hulu & Orkestrasi: zero-to-prod-orchestrator (Integrasi AI Fase 4), brainstorming, session-memory-manager (snapshot zona konteks & handoff).
  • Penguncian Prefix & Kaskade Model: kv-cache-prefix-optimizer (penyelarasan batas cache Zona 1-2), adaptive-model-cascade (routing luapan kapasitas model), llm-finops-router (akuntansi biaya token per zona).
  • LLM Frontier & Booster Model: frontier-ai-models-expert (kurva recall 2M+ token), gemini-agent-booster (caching konteks native Google 2M+), vercel-ai-sdk-expert (streaming konteks & tools).
  • Riset & Penyerapan Mendalam: deep-research-analyst (injeksi berbasis retrieval), vector-db-rag-expert (keputusan retrieval vs penumpukan konteks).

Deskripsi

Panduan produksi untuk merekayasa, mempartisi, dan mengoptimalkan context window ultra-besar (128k → 2M+ token) pada model frontier. Mencegah kegagalan paling umum di aplikasi AI 2026: memasukkan data mentah ke konteks tanpa struktur, yang menyebabkan recall menurun, token terbuang, dan amplifikasi halusinasi di zona "lost in the middle".

Kondisi Pemicu

Aktifkan skill ini ketika:

  • Membangun agen atau aplikasi AI yang mengonsumsi >50k token konteks per permintaan.
  • Mengalami penurunan recall model, kegagalan "lost in the middle", atau halusinasi pada skenario konteks panjang.
  • Merancang sistem RAG yang perlu memutuskan antara retrieval vs. long-context stuffing.
  • Mengoptimalkan biaya token untuk aplikasi dengan system prompt besar, registri tool, atau peta konteks codebase.

Konsep Inti & Pola Praktik

1. Peta Kapasitas Context Window (Model Frontier Akhir-2026)
ModelTierKonteks MaksZona Recall EfektifBiaya per 1M Token InputDiskon Cache
Gemini 4 ArgonMedium2.097.152~1,9M (monolitik)$0.8075% (native context caching)
Gemini 4 ProHigh2.097.152–10M~1,8M (andal)$1.2575% (explicit cache)
Gemini 3.8 Flash (Fallback)Fast/Medium1.048.576~900k$0.1075% (native context caching)
Claude Opus 5.5Medium500.000~480k$10.0090% (prompt cache)
Claude Opus 4.6 (Fallback)Medium200.000~180k$8.0090% (prompt cache)
Claude Sonnet 5.5High500.000~480k$3.0090% (prompt cache)
Claude Fable 5.1High500.000~480k$2.5090% (prompt cache)
GPT-5.6 SolMedium500.000~450k$1.5050% (prefix cache)
Grok 4.7 High FastHigh Fast256.000~240k$0.5080% (prompt cache)
Composer 2.5 FastFast200.000~180k$0.3080% (AST diff cache)
2. Arsitektur Partisi Konteks

Jangan perlakukan context window sebagai buffer datar. Partisi menjadi zona bermakna secara semantik:

  • Zona 1 (1-3%): Direktif sistem yang tidak berubah — prompt perilaku, format output.
  • Zona 2 (10-40%): Referensi statis — skema codebase, spesifikasi API, definisi tool.
  • Zona 3 (20-50%): Konteks yang di-retrieve — chunk RAG, file kode relevan, cuplikan dokumentasi.
  • Zona 4 (10-30%): Riwayat percakapan — giliran sebelumnya, ringkasan konteks lama.
  • Zona 5 (1-5%): Query aktif — pesan pengguna saat ini, ruang kerja chain-of-thought.
3. Mitigasi "Lost in the Middle"

Model frontier menunjukkan recall yang menurun untuk informasi di tengah-tengah konteks. Mitigasi dengan penempatan informasi kritis di awal dan akhir, jangkar struktural, ringkasan redundan, dan retrieval berbasis chunk.

4. Keputusan RAG vs. Long-Context

Gunakan RAG untuk korpus >10M token dengan query spesifik dan sensitivitas biaya tinggi. Gunakan long-context stuffing untuk korpus <2M token dengan kebutuhan sintesis luas dan corpus statis per sesi.


Praktik Terbaik

  1. Selalu Hitung Token Sebelum Injeksi: Gunakan API countTokens() untuk mengukur jumlah token aktual.
  2. Selaraskan Batas Zona dengan Cache: Koordinasikan dengan kv-cache-prefix-optimizer agar zona statis selaras dengan batas prefix KV-cache.
  3. Ukur Kualitas Recall: Instrumenkan tes needle-in-haystack pada berbagai kedalaman konteks.
  4. Degradasi Anggun: Saat konteks melebihi anggaran, buang Zona 4 (riwayat lama) lebih dulu, bukan Zona 1-2.

Jebakan Umum yang Harus Dihindari

Praktik BurukDampakSolusi
Memasukkan seluruh codebase ke konteksMelebihi zona recall efektif, halusinasi melonjakGunakan retrieval terarah + skor relevansi file
Tanpa partisi zonaInstruksi kritis "hilang di tengah"Implementasikan header zona eksplisit
Mengabaikan penghitungan tokenPemotongan konteks diam-diam oleh API modelHitung dan terapkan anggaran dari sisi klien
Menyimpan seluruh riwayat percakapanKonteks penuh setelah 10-15 giliranTerapkan sliding window dengan ringkasan

Matriks Eksekusi Berdaulat, Efisiensi Token & Invarian

DimensiMandat Berdaulat & Kontrak Deterministik
Kaskade Model FrontierMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Invarian Fallback KetersediaanGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Bebas gagal saat model belum tersedia/kuota penuh)
Protokol Hemat Token & KV-CacheKunci instruksi & skema statis di prefix awal (kv-cache-prefix-optimizer); kirim potongan CONTEXT_MAP.md (<250 token/panggilan) saat Fan-Out
Eksekusi SaaT CLI & MCPCLI: vibes skill exec context-window-engineer <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
Invarian NFR & Anti-SlopLatensi P99 API < 85ms, paritas skema ketat OpenAPI 3.1 / TypeSpec, kontrak error RFC 9457 Problem Details, penegakan Idempotency-Key; kode 100% tuntas tanpa placeholder diverifikasi melalui node scripts/check-anti-slop.js --strict

よくある質問

AIスキル「Context Window Engineer」では何ができますか?

200万トークン超のコンテキストウィンドウの最適化、プロンプトキャッシュの固定、予算の分割

TypingMindでContext Window Engineerを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Context Window Engineerはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにContext Window Engineerをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/roedyrustam/vibes-plug/tree/main/skills/context-window-engineerを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Context Window Engineerを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Context Window Engineerで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもContext Window Engineerを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Context Window Engineer」は無料ですか?

はい。roedyrustamがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇