Skip to content
~/posts

All Posts

All blog posts by Brandon Wie

// 155 · all
aws

WAF Allowlist Patterns

Block-by-default WAF approach using route allowlisting. Stronger security than

backend

updatedAt Staleness Guard

When receiving asynchronous updates (webhooks, message queues), compare the

devops

AI PR Review Validation Patterns

Fourteen patterns where AI code reviewers (Claude, Copilot, Codex) produce false positives, plus the classification framework and reinforcing-comment templates that keep triage fast.

devops

A Harness That Fixes Itself - And Prunes Its Own Fixes

The most expensive agent mistakes are not the dramatic ones.

devops

Forward Links Only: A Zettelkasten Where Backlinks Are Computed

3B stores the link an author can maintain, derives the reverse edge later, and makes the struggle behind a note part of the knowledge itself.

devops

Folder Is Destiny: A Six-Layer Information Lifecycle

3B lets folder placement decide retrieval, privacy, and staleness most of the time, then uses frontmatter overrides for the cases where physical location and...

devops

Parallel Agents Without Collisions: Tasks, Worktrees, and Locks

Parallel agent work usually looks like a Git problem. Two sessions edit the same repository, one lands first, the other gets a conflict, and everyone learns...

devops

Rules That Route Themselves: Frontmatter as the Loader

In 3B, YAML frontmatter is not decorative metadata. It is the routing language that decides which agent sees which rule, when, and in what shape.

devops

Same Skill, Three Transport Physics

A skill can be authored once and still travel differently to each agent: Claude resolves canonical bytes, Codex reads a pinned adapter, and AGY splits native...

devops

The Token Stack: Four Layers of Code Intelligence Without Re-Scanning

The easy answer to agent context burn is "add memory."

devops

Three Gates and an Audit Log: HITL for an Agent Harness

The first version of an agent workflow usually has one safety rule: ask before doing something risky.

devops

The Session Engine: /wrap, Clean-Slate Rollups, and a Cross-Session Buffer

Agent work does not fail only because the agent made a bad edit. It also fails because the next session cannot tell what happened.

ai-ml

AI Code Review Confusion Patterns

Thirteen distinct ways Claude, Copilot, and Codex behave on PRs — ten failure modes plus two productive behaviors to amplify, plus an analyst-side error class. With detection signals and the empirical tiebreaker that resolves factual disagreements.

devops

Claude Code: Shared + Personal AI Config Pattern

Split AI instructions into committed (shared) and gitignored (personal) layers

devops

Why your updater keeps re-enabling the Claude plugins you disabled

I kept a couple of plugins deliberately off, ran my updater, and they came back on. The script provably never re-enabled anything — because the re-enable was not the script's to begin with. Here is the snapshot-and-reassert guard that stopped the toil.

devops

Codex Skill Mirror Pattern

When a repository already treats `.agents/skills/` as the canonical skill source, the clean Codex integration is not "replace it with `.codex/skills/`" or "symlink the whole folder wholesale." A mirror layer with selective adapters preserves the canonical source while giving Codex what it needs.

devops

`gh pr view` Head-Branch Ambiguity (False-Negative)

Running `gh pr view --json number,state` on a branch with an open PR can return "no pull requests found" even when the PR exists and the branch is correctly tracked. The empty result means "gh's branch resolution didn't find one," not "no PR exists."

devops

Serena MCP — Multi-Profile Setup for Claude Code (cpers/cwork)

Installing the Serena MCP server across a Claude Code dual-profile setup (cpers/cwork) plus Codex, including the four recommended hooks, the system-prompt override, and the non-obvious "installer writes to default ~/.claude.json, misses profile-specific stores" trap.

devops

`test -L` vs `realpath` for symlink detection

A POSIX gotcha. `test -L child/leaf` returns false when a parent is the symlink, even when the resolution chain is healthy. Use `realpath` for source-of-truth chain validation.

devops

The pre-commit hook race that put my files in someone else's commit

Two sessions committing to one repo, a slow pre-commit hook, and `fatal: cannot lock ref HEAD`. The loud failure is the easy one — the quiet failure hands your staged files to the other session's commit under its message.

general

Claude Code Multi-Profile HUD Setup

Running Claude Code with multiple accounts requires careful HUD configuration to show correct per-account usage stats. Here's how to fix cross-profile data leaks.

backend

Rust async channels with tokio

Choosing between tokio's mpsc, unbounded mpsc, and oneshot channels is a stream-vs-handoff decision, not a performance one.

devops

When CLAUDE.md keeps overflowing, move the budget into your generator

The "Large CLAUDE.md will impact performance" warning kept coming back weeks after every trim. It stopped for good once the byte budget moved out of author discipline and into the generator that assembles the file — as a per-rule warning, a total hard-fail, and a rendered-file ceiling.

devops

State-invariant flag drift — recovery via reconciliation pass

A boolean lifecycle flag kept getting stuck on entries that could never reach the code path that clears it. Symptom-only fixes recurred. The durable fix was a third workflow that enforces the invariant the flag implies, independent of how the flag got set.

general

Session-State Dashboards: Merge, Don't Overwrite

Regenerating a cross-session dashboard two ways — overwrite, or merge-with-carry-forward — fails in opposite directions. Here is the rule I settled on, and why I eventually stopped tracking the dashboard in git at all.

devops

tmux Smart Session Auto-Start

Auto-start tmux via an iTerm2 Profile Command (`tmux-smart-attach`) with numeric

frontend

Svelte: an async `onMount` return is NOT cleanup

Svelte runs the value returned from `onMount` as cleanup on unmount — but only when it is a function. An `async` callback returns a Promise, so the cleanup is silently ignored.

frontend

SvelteKit: hydrate a shared store site-wide from `+layout.ts`

A shared `writable` store populated by a single page's `onMount` is empty on every other route. Hydrate it once in the root `+layout` so every navigation carries it.

devops

Anthropic Prompt Cache TTL + Cost Mechanics

Anthropic silently dropped Claude Code's prompt-cache TTL from 1 hour to 5 minutes around early March 2026. Without explicit awareness, idle gaps ≥5 min between messages evaporate the cache and force a full cold cache-write on the next message — pricing it at 1.25× base input on the entire conversation prefix.

devops

One Folder, Three Agents: The `.agents/` Source of Truth

How one folder and a generator make three AI agents obey the same rules.

frontend

Paraglide-JS i18n for SvelteKit

Adding Korean/English internationalization to a SvelteKit static blog without

ai-ml

Don't Retry Retrieval — Diagnose It

When retrieval comes back weak, the reflex is to retry. Wei et al. (2026) shows retry compounds errors on out-of-distribution queries — diagnose the failure instead.

ai-ml

Claude Code Agent Teams

Experimental feature for orchestrating multiple Claude Code instances as a coordinated team with shared task lists and inter-agent messaging

backend

FastAPI Non-blocking Startup Dependencies

FastAPI lifespan code runs before the application accepts requests. If startup awaits an optional dependency such as Kafka, Cloud Run cold starts can fail health checks and E2E probes even when the API would happily serve routes without it.

devops

Two-Phase Invocation as a Manual Merge Gate

When a CI/CD automation skill supports an "all-in-one" mode (`/skill +flag`), the all-in-one mode should be opt-in, not the default. Splitting invocations preserves a meaningful pause point between CI green and the irreversible merge.

devops

`git rev-parse HEAD` vs `git log -1` Divergence Under Watcher Hooks

After a `gh pr merge` and a local pull, `git rev-parse HEAD` returned the correct merge commit while `git log -1` rendered the just-merged-away feature branch tip for several seconds. A graphify watcher rebuild fired during the checkout. The low-level read is authoritative; the log render can lag.

devops

Markdownlint Pre-Commit: MD041 + MD001 Heading Gotchas

Two markdownlint rules that repeatedly block husky pre-commit on newly-created markdown files with YAML frontmatter. Both fire silently, neither is auto-fixed by --fix, and they tend to appear together — fixing one exposes the other.

devops

Wrap Skill Follow-Up Persistence Architecture

When a session-state dashboard regenerates from a single source (today's journal), unresolved follow-ups from prior sessions vanish silently on every rebuild. Compounded with single-source discovery and conversation-only mentions, follow-ups disappear three ways at once. The fix is a 4-layer architecture.

general

Empirical Close: Defer Skill-Side Tests to Natural Exercise

Some verification tests need a real trigger that no fixture replicates faithfully — interactive prompts, conversation parsing, AskUserQuestion flows. Marking the test [~] empirical-close-pending and trusting the next natural trigger to verify is hygienic when paired with a friction-log reopen.

general

Markdownlint Conventions

7,500 markdownlint errors across 200 markdown files. The rules that mattered, the configuration that stuck, two pre-commit traps that surface only in nested scopes, and the strict-preset migration that collapsed a 14-rule custom config into one extends + five carve-outs.

general

Plan-vs-Shipped Divergence Detection on Task Resume

When resuming a multi-session task, the plan.md written at task start may not reflect what is actually shipped now. Implementations evolve mid-flight, scope shifts, branches merge. A 3-minute pre-flight check prevents hours of executing obsolete work.

general

Checklist beats prose for LLM-robust skill preconditions

Compound preconditions written in prose form get silently misapplied under context pressure. Restructuring them as explicit checkbox checklists with one box per clause makes the precondition LLM-robust — and surfaces implicit clauses that turn out to be the actual bugs.

ai-ml

Codex `apply_patch` is a Shell-Mediated Tool, Not a Direct Tool

Codex CLI doesn't have a discrete edit tool. File edits flow through `local_shell` carrying `apply_patch` patch text. Cross-agent hooks need a payload-parsing wrapper, not a tool-name matcher.

ai-ml

Cross-Agent Skill Alias Generalization

Skills shared across Claude Code, Codex, and Gemini fail when they hardcode one agent's MCP tool alias. Two-tier pattern — declare both alias families in frontmatter; use generic names in prose.

devops

Stdlib-Only Helper Portability

Helpers shipped to multiple agents fail in CI when they assume non-stdlib deps. Bind to standard library only — PyYAML, npm packages, and BSD/GNU sed flags are the three usual traps.

general

Schema-Versioned Helper Output Envelope

A JSON output envelope for cross-agent helper scripts — schema_version, status, error, agent, ts. Stable shape, semver-bumpable, error-distinguishing.

backend

emitAsync Stamp Gating for Idempotent Bootstrap Retries

A bootstrap that emits sync to a queue then stamps "done" silently strands downstream when Redis blips. emitAsync gates the stamp on enqueue admission.

backend

Fallback-Branch Test Coverage Gap

Tests pass. Coverage hits 100%. Removing the `|| randomUUID()` would still pass everything. How builder-driven fixtures hide the falsy branch.

backend

Stateless Auth DB-Column Drift

Auth migrated from stateful to stateless JWT validation. Tests pass. Mobile users have access_token populated; web users have NULL. The drift is invisible until ops queries the column.

backend

Symmetric Redis ↔ Kafka Bridge Pair for Cross-Cloud Event Flow

Cloud Run can't reach an internal Kafka broker — `advertised.listeners` always wins. A pair of unidirectional bridges through Redis keeps every invariant intact.

backend

Byte-aware vs Count-based Chunking for Typesense documents/import

Two chunking strategies for Typesense bulk import. Picking the wrong one silently fails the day a single power user creates a multi-MB document.

devops

Ruff Three-Gate Pre-Flight

A push that turned into three CI cycles taught me Ruff in CI is three independent gates. A four-line shell function prevents the loop.

ai-ml

Phase A→B Classifier Deployment: Zero-Shot to Fine-Tuned

How to ship a working intent classifier on day one with zero labeled data, then graduate to a domain-specific model as you collect examples.

ai-ml

Six Papers, Zero Applied: A Week of Disciplined Reading

Six papers from DAIR.AI's April 6-12 batch. Three unifying themes surfaced, and zero were implemented — a practical walk-through of Pattern A, theme saturation before action.

devops

Measuring Claude Code Turn Latency from JSONL Transcripts

Ground-truth, retroactive per-turn latency for Claude Code sessions — parsed from the JSONL transcripts already on disk, with four measurement traps I had to self-correct.

backend

NestJS @Headers Decorator Returns string | undefined

NestJS `@Headers('key')` returns `string | undefined`, not `string[]` — Express normalizes duplicate custom headers by joining them with comma-space.

backend

NestJS Swagger: type is Silently Ignored When content is Provided

When `@ApiResponse` sees both `type` and `content`, NestJS Swagger silently drops `type` — so your DTO stops appearing in the Swagger UI Models tab.

devops

macOS VSCode Terminal Locale Fallback

VSCode's integrated terminal can silently switch to a non-English locale on macOS — here is why your `git status` suddenly speaks Korean and how to pin `LANG` in `settings.json`.

devops

Stow Symlink Health Checking

GNU Stow creates symlinks from system config paths back to a dotfiles repo,

ai-ml

I Built What Karpathy Described — Before He Described It

Andrej Karpathy published a pattern for LLM-maintained knowledge bases. I have been running one for months. Here is what the comparison revealed.

ai-ml

LLM Fine-Tuning Strategies

A practical decision framework for choosing between prompt engineering, RAG, and LoRA fine-tuning when building LLM-powered applications.

ai-ml

Population Stability Index (PSI) for Model Drift Detection

How to detect when your deployed classifier's input distribution shifts away from training data — before accuracy degrades — using a lightweight statistical metric.

devops

Anthropic MCP Context Budget Optimization

Anthropic-hosted MCP integrations consume ~71K tokens of your context window at session start — even when you never call them. Here is how to reclaim that budget.

devops

Docker Subnet Collision with Static-IP Services

When multiple Docker Compose projects define custom bridge networks, their subnets can collide silently. Here is how to diagnose and fix it.

devops

Hybrid CI: Self-Hosted Jenkins + GitHub Actions

Why use one CI system when you can use both? A split architecture that plays to each tool's strengths for polyglot portfolio projects.

general

PortAudio Stale USB Audio Device Handle

Long-running audio daemons using PortAudio silently produce zero-filled buffers when the USB device handle goes stale. Here is how to diagnose and fix it.

google

Google Meet Link Creation

Lesson learned from implementing programmatic Google Meet link creation.

ai-ml

The Next Intelligence Explosion Is Social, Not Computational

A Google paper argues every major intelligence explosion emerged from social organization, not individual cognition — and AI will follow the same pattern.

backend

Redis and BullMQ Queue Patterns

Comprehensive guide to Redis-backed job queues with BullMQ in Node.js/NestJS

ai-ml

Gemini Asymmetric Embeddings

Gemini's text-embedding-004 uses asymmetric embedding with task_type to encode queries and documents differently, producing better retrieval results than symmetric models.

ai-ml

RAG Hybrid Search Architecture

Why single-method retrieval fails and how fusing dense, sparse, fuzzy, and managed search with Reciprocal Rank Fusion builds a retrieval pipeline that handles both semantic understanding and keyword precision.

backend

pgvector HNSW Index in PostgreSQL

You don't need a dedicated vector database for semantic search — pgvector with HNSW indexes handles under 100K vectors at over 95% recall, right inside PostgreSQL.

aws

EBS vs EFS: AWS Storage Comparison

Understanding when to use EBS (block storage) vs EFS (network filesystem).

aws

ECS Autoscaling Patterns

Best practices for implementing ECS service autoscaling with migration task

aws

NAT Gateway Architecture

Understanding NAT Gateway placement and VPC network flow.

aws

AWS Security Groups Fundamentals

Security Groups are virtual firewalls for AWS resources, controlling inbound

aws

Terraform Fundamentals

Core Terraform concepts for AWS infrastructure management.

aws

Terraform RDS Credentials Management

Managing RDS credentials securely using variables instead of hardcoding.

aws

AWS WAF Implementation

Web Application Firewall setup with allowlist approach.

backend

Amplitude ETL Partitioning

How Amplitude event data is partitioned when moving from raw to refined storage.

backend

Amplitude Export API Response Format

The Amplitude Export API returns data in a **nested compression format** that is

backend

Backfill Stats Manifest on Early Exit

When a job has an early exit path (e.g., "no work to do"), always save a

backend

Calendar EXDATE Behavior: Apple vs Google

Understanding how Apple Calendar and Google Calendar handle recurring event

backend

Celery API-Side Dispatch Pattern

Creating a send-only Celery client in an API service that dispatches tasks to a

backend

class-transformer Undefined Own-Property Bug

When `plainToInstance()` creates class instances under ES2022+ TypeScript

backend

CPU Cache Locality in Batch Field Extraction

Multiple `.map()` calls over the same array force the CPU to reload each object

backend

DataSource vs Repository Pattern

Architectural decision guide for choosing between direct DataSource usage and

backend

ETL Data Separation Strategy

Mixing regular ETL data with manually recovered backfill data in the same S3

backend

NestJS WebSockets Reference

Complete reference for implementing WebSocket functionality in NestJS.

backend

pandas itertuples() vs iterrows()

`iterrows()` is the most common way to iterate over DataFrame rows, but it

backend

PostgreSQL Advisory Locks with TypeORM

Application-level locks managed by PostgreSQL for coordination.

backend

PostgreSQL IN Clause Parameter Limits

When querying by a large set of IDs using TypeORM's `In([...])` operator, the

backend

Deduplicating Functions with Keyword-Only Parameters

Two modules contain near-identical functions with slight behavioral differences.

backend

Sentry N+1 Query Detection

How Sentry detects N+1 queries at runtime, common false positives from parallel

backend

Stale vs Orphan Blocks in Calendar Sync

When syncing calendar data from Google Calendar API, two distinct cleanup

backend

Sync Token Invalidation Recovery (410 GONE)

When Google Calendar API returns 410 GONE, the sync token is invalidated and a

backend

TypeORM CLI와 NestJS DataSource 충돌

TypeORM CLI를 NestJS 프로젝트에서 사용할 때 발생하는 연결 충돌 문제와 해결 방법.

backend

TypeScript Type Narrowing Over Assertions

Prefer type narrowing over non-null assertions (`!`) and forced casting

backend

Webhook vs User Activity

Webhooks from external services indicate **their** activity, not **your user's**

data

Amplitude Export API Timezone Behavior

How Amplitude Export API handles timezones and hour boundaries for event data

devops

Airflow Celery Worker Log Server Configuration

When using CeleryExecutor with workers on separate machines, the webserver needs

devops

Airflow CI/CD Concepts

Understanding Airflow deployment and CI/CD concepts through a kitchen analogy.

devops

Airflow DAG-Level Callbacks

Airflow 2.x silently ignores `on_success_callback` at the DAG level. Only

devops

Airflow DAG start_date and Manual Triggers

When manually triggering a DAG, Airflow may skip task execution if the trigger

devops

Airflow Manual DAG Config Pattern

Pattern for allowing manual DAG triggers with custom parameters while keeping

devops

Airflow Task Dependency Syntax

The `>>` operator in Airflow sets task dependencies and returns the downstream

devops

Bash set -e and Command Substitution

When using `set -e` (exit on error), command substitution behaves unexpectedly

devops

boto3 S3 put_object() Body Parameter Encoding

An ETL pipeline that uploaded JSON manifest files to S3 was failing with a

devops

Claude Code PostToolUse Hooks

PostToolUse hooks fire after a tool completes. They receive JSON via stdin with

devops

DAG Deployment Strategies

Different approaches to deploying Airflow DAGs, with trade-offs analysis.

devops

Docker Compose CI/CD Patterns

Patterns for using Docker Compose in CI/CD pipelines: separating dev and prod configurations, ECR integration, and deployment strategies.

devops

ECR Credential Helper

AWS's official solution for automatic ECR authentication. Instead of storing

devops

ECR Token Refresh Cron

AWS ECR authentication tokens expire after 12 hours. For long-running Docker

devops

ETL Schedule Timing

How to choose the correct ETL schedule based on data arrival patterns.

devops

Linux Fundamentals

1. [Cgroups (Control Groups)](#cgroups-control-groups)

devops

Local S3 with MinIO

MinIO is an S3-compatible object storage that runs locally via Docker.

devops

Python Tooling Stack

Standard Python development tooling for all MOBA projects.

devops

S3 Path Normalization Pattern

S3 key prefixes need consistent trailing slashes when building hierarchical

devops

Terraform State Recovery

Procedures for recovering from Terraform state drift when state file doesn't

devops

uv.lock Best Practice

Whether to commit `uv.lock` to version control.

frontend

Giscus SvelteKit Integration

Adding a comment system to a statically generated SvelteKit blog without

frontend

Mobile Input UX

Techniques for making custom-styled inputs work properly on mobile browsers.

frontend

Svelte 5 $effect Rune

In Svelte 5, the reactive statement syntax (`$: { }`) from Svelte 4 is replaced

general

Claude Code Expert Workflows

Synthesized patterns from three complementary expert sources: Boris Cherny (tool

general

CSS Inline-Replaced Element Gap

Elements like `<textarea>`, `<img>`, `<input>`, and `<video>` are

general

Documentation Patterns

The **Buffer Pattern** preserves important discoveries during AI-assisted

general

macOS Keychain Multi-Account Behavior

macOS Keychain allows multiple entries with the same service name but different

general

React Demo Pipeline Pattern

Pattern for building a fully functional demo mode in a React dashboard when the

general

shadcn/ui Setup with Vite + Tailwind

Manual setup of shadcn/ui component primitives in a Vite + React + TypeScript +

general

zsh Backtick Evaluation in Claude Code Skills

Claude Code SKILL.md files can trigger zsh command substitution errors when

google

Google Calendar API: Recurring Event Updates

Handling "this", "thisAndFollowing", and "all" updates for recurring events.

google

Google Calendar Recurring Event Operations

Implementation patterns for `all`, `this`, and `thisAndFollowing` recurring

icalendar

External Calendar Data Normalization

External calendar data (Apple Calendar, GNOME Evolution, travel apps) often

icalendar

Partial Access Recurring Events

When users are invited to recurring events from the middle of a series, Google

icalendar

rrule BYDAY Timezone Correction

The rrule JavaScript library interprets `BYDAY` weekday names in UTC, not the

icalendar

RRULE EXDATE Parsing with Timezone

The `rrule` JavaScript library's `rrulestr()` function fails when:

payments

Lemon Squeezy Subscription Management

Subscription lifecycle, cancellation, expiration, and reactivation.

security

Binary Checksum Verification

Verify downloaded binaries haven't been tampered with using SHA256 checksums.

security

IDOR Prevention via Required Parameters (Type-Level Enforcement)

Insecure Direct Object Reference (IDOR) occurs when an API allows users to

backend

Alembic with Async SQLAlchemy

Configuring Alembic migrations to work with SQLAlchemy's async engine

aws

ECR/ECS Deployment Workflow

Complete guide to container deployment using Amazon ECR and ECS.

aws

AWS VPC Networking Fundamentals

Comprehensive guide to AWS VPC networking: CIDR notation, subnet design, NAT Gateway placement, route tables, and complete Terraform examples.

backend

FastAPI Dependency Injection Patterns

How to use Annotated types with FastAPI Depends() for reusable, type-safe dependency injection across routers.

backend

Pessimistic Locking for Race Conditions

Use SELECT FOR UPDATE to prevent race conditions in check-then-insert patterns, with TypeORM implementation and duplicate key safety nets.

backend

WebSocket Architecture in AWS ECS/ALB

How WebSocket connections work with ALB, ECS, and Redis Pub/Sub for real-time notifications in containerized environments.

security

OAuth 2.0 Implementation Patterns

Practical patterns for implementing OAuth 2.0 flows in backend services.

security

Understanding Traefik, Keycloak, and ForwardAuth

How to add centralized authentication to Kubernetes services using Traefik ForwardAuth, Keycloak, and OAuth2-Proxy.

general

Recharts Dark Theme Customization

Techniques for styling Recharts charts to match a dark terminal theme with CSS

ai-ml

AI Code Review Patterns

Patterns observed when AI reviewers (Claude, Copilot, Codex) generate invalid or misleading feedback, and how to handle each one.

backend

Batch Processing Trade-offs

When processing multiple entities that share database operations, there's a

aws

ECS Auto-Scaling Deep Dive

Comprehensive guide to ECS auto-scaling concepts, algorithms, and container

devops

GitHub PR Review API - Inline Comments

How to create PR reviews with inline comments using the GitHub API via `gh` CLI.

backend

Two-Phase Deletion Pattern

A safe deletion pattern for systems without rollback capability where external

security

Infrastructure Hardening Checklist

Comprehensive security hardening checklist for AWS infrastructure. Covers

google

Google Calendar Sync Strategies

Full sync vs incremental sync patterns and calendar segregation logic.

enko