yorishiro-proxy
CLAUDE.md19 starsChanged 22 days agoApache-2.0View on GitHub
A network proxy tool for AI agents — a MITM proxy for AI. Operates as an MCP (Model Context Protocol) server, providing traffic interception, recording, and replay capabilities for vulnerability assessment. Status: OSS (Apache License 2.0) · Under active development Design: RFC-001 Envelope + Layered Connection Model. Implementation strategy: docs/rfc/envelope-implementation.md. Each connection is an explicit stack of Layers (RFC-001 §3.3); each Layer yields one or more Channels; the Pipeline runs on Envelopes drawn from those Channels. The data model is:
- Deletes or force-pushes
- Installs packages
- Commits and pushes
In this repository13 other files it gives its agents.
- autopilotSkill
- buildSkill
- code-reviewSkill
- implement-pluginSkill
- implementSkill
- license-checkSkill
- orchestrateSkill
- pentest-proxySkill
- projectSkill
- prSkill
- review-gateSkill
- security-reviewSkill
- testSkill
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
16 rules. About 0 are common, 7 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 57
No external proxy libraries — built on the standard library
- Very specific: line 239
When adding new e2e tests (*_integration_test.go), verify not just communication success but also subsystem integration.
- Very specific: line 266
Do not expose internal/ packages externally
- Very specific: line 270
When implementation involves goroutines, channels, or io.Pipe, verify the following before opening a PR.
- Distinctive: line 292
Debug vs Info: If an operator can confirm normal operation without the log, use Debug.
- Distinctive: line 293
Info vs Warn: Use Info if it is part of the normal flow.
- Distinctive: line 294
Warn vs Error: Use Warn if processing can continue.
- Distinctive: line 321
All GPL variants (GPL-2.0, GPL-3.0, LGPL-2.1, LGPL-3.0, AGPL-3.0)
- Very specific: line 325
Every module in the require block of go.mod, with the licence taken from the module's own LICENSE file rather than from a package index.
- Very specific: line 350
When adding a new module to go.mod or to web/package.json's dependencies, verify the license with the /license-check skill, and add a row …
- Very specific: line 401
When splitting Issues for a new feature milestone with /project plan, treat the following as mandatory checks.
- Very specific: line 412
When splitting Issues for a new protocol with /project plan, treat the following as mandatory checks.
- Very specific: line 457
Document the isolation setting in the calling skill (.claude/skills/*/SKILL.md)
- Distinctive: line 474
Do not bulk-delete to avoid destroying active worktrees of other sessions.
- Very specific: line 510
If stale worktrees accumulate, check with git worktree list and remove individually with git worktree remove <path> --force --force.
- Distinctive: line 561
All PRs require CI to pass before merge
≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
yorishiro-proxy
A network proxy tool for AI agents — a MITM proxy for AI. Operates as an MCP (Model Context Protocol) server, providing traffic interception, recording, and replay capabilities for vulnerability assessment.
Status: OSS (Apache License 2.0) · Under active development
Architecture
Design: RFC-001 Envelope + Layered Connection Model. Implementation strategy: docs/rfc/envelope-implementation.md.
Principle: L7-first, L4-capable
- The default operation interface is a structured L7 view — Prioritize AI agent token efficiency by representing communication as structured data: method, URL, headers, body, etc.
- Raw bytes recording, viewing, and modification must be possible for all protocols — As a diagnostic tool, protocol-level anomaly detection and reproduction must be supported (pure transport-layer protocols like SOCKS5 apply to the tunneled protocol)
- L7 parsing is an overlay on top of raw bytes; the wire-observed raw bytes snapshot itself must not be destroyed or modified — Recorded raw bytes always reflect the original wire data; modifications must always be treated as separate derived data (e.g., modified variant)
Pipeline
TCP Listener (Layer 4)
→ Protocol Detection (peek bytes / ALPN)
→ Connection Stack (TCP → TLS → HTTP/1 | HTTP/2 → WS | gRPC | gRPC-Web | SSE | Raw)
→ Pipeline Steps
(HostScope → HTTPScope → Safety → PluginPre → Intercept → Transform → PluginPost → Record [→ UpgradeStep])
→ Flow Recording (L7 Message + L4 Envelope.Raw)
→ MCP Tool (Intercept / Replay / Search / Plugin Introspect)Each connection is an explicit stack of Layers (RFC-001 §3.3); each Layer yields one or more Channels; the Pipeline runs on Envelopes drawn from those Channels. The data model is:
Envelope— protocol-agnostic outer container with identity (StreamID/FlowID/Sequence/Direction), provenance (Protocol), wire fidelity (Raw bytes), and a typedMessage.Message— protocol-specific payload (HTTPMessage,WSMessage,GRPCStartMessage/GRPCDataMessage/GRPCEndMessage,SSEMessage,RawMessage,TLSHandshakeMessage).
L7/L4 Support Status by Protocol
| Protocol | L7 Structured View | L4 raw bytes | Notes |
| HTTP/1.x | YES | YES | Custom parser; net/http not used in data path. Forward: supported (USK-911~917). Plain-HTTP forward proxy: upstream gets origin-form without Proxy-Connection / Proxy-Authorization, recording stays as received; opt-out forward_as_received (USK-1117). Response bodies are streamed — head emitted first, body wire bytes forwarded verbatim as read, flow recorded at body end — unless an intercept / replace_body rule or a plugin hook needs them whole (layer.BodyModeFunc from proxybuild.NewHTTPBodyModeFunc; USK-1409, RFC-001 §3.2.1 "HTTP body streaming"). Request bodies stream the same way (USK-1414) unless an intercept / replace_body rule, any Safety input rule targeting the body, or a plugin on_request hook needs them whole; the next request is parsed only after the current body ended cleanly. |
| HTTP/2 | YES | YES | Custom frame engine; event-granular Channel + per-stream BodyBuffer. Forward: supported (USK-911~917). Request and response bodies are streamed by httpaggregator (head emitted after HEADERS, each DATA frame forwarded as one DATA frame, trailers after, the peer's RST_STREAM code relayed after the DATA received; flow recorded at body end) unless the same layer.BodyModeFunc as HTTP/1.x says a rule or plugin needs them whole (WrapOptions.BodyMode; USK-1401, RFC-001 §3.2.1 "HTTP body streaming"). Buffered bodies keep their raw DATA in a spillable Envelope.RawBuffer capped at max_record_body_size. gRPC-Web stays buffered. |
| gRPC | YES | YES (via HTTP/2) | Native LPM reassembly; GRPCStart/Data/End envelope events. Forward: supported (USK-911~917). |
| gRPC-Web | YES | YES (via HTTP/1.x or HTTP/2) | Binary + base64 wire formats |
| WebSocket | YES | YES (per frame) | Per-message-deflate (RFC 7692) supported. Forward: supported (USK-911~917). |
| SSE | YES | YES | Per-event envelopes; streaming-aware Pipeline; per-event Transform / Intercept (rules/sse) — USK-892. Engines mutate SSEMessage fields directly; session-side sseMessageMutated field-diff is the authoritative re-encode signal (env.Raw is NOT cleared). Forward: supported (USK-911~917). |
| Raw TCP | N/A | YES (byte stream) | Smuggling-safe pass-through (bytechunk Layer). Forward: supported (USK-911~917). |
| SOCKS5 | N/A | N/A (excluded as transport layer itself) | Apply raw bytes/L7 to the protocol delegated after handshake/tunnel |
| TLS handshake | YES (observation) | N/A | TLSHandshakeMessage envelope; SNI / ALPN / JA3 / JA4 visible to plugins |
| HTTP/3 / QUIC | NO | NO | Out of scope (USK-1016). No UDP listener; ALPN advertises only h2 / http/1.1. Proxied Firefox does not use h3 (h3 cannot traverse a CONNECT proxy), so absence is a weak bot signal. See RFC-001 §11. |
Transparent mode (USK-1316 / USK-1317):
transparent_mode: "redirect"(Linux, nftables REDIRECT) routes every accepted TCP connection to itsSO_ORIGINAL_DSTby its first bytes: plain HTTP/1.x → the L7 path pinned to the original destination; TLS → routed by the ClientHello ALPN offer:h2/http/1.1offered → MITM under the SNI (dial target = original dst, client ALPN forwarded verbatim), no ALPN extension → MITM with no ALPN on either leg (an HTTP/1 upstream redial keeps that no-ALPN standard-TLS shape), then HTTP/1 orbytechunkby the decrypted first bytes, only non-HTTP ALPN / unparseable hello /tls_passthroughSNI → metadata-only passthrough; server-first / anything else → metadata-only passthrough (no payload bytes recorded — a documented deviation from L4-capable). CONNECT / SOCKS5 keep no-ALPN → HTTP/1. Seeinternal/connector/transparent_handler.goandtransparent_tls.go.
TCP forward L7 dispatch (USK-911~917): All L7-supported protocols above are also usable through TCP forward mode (
tcp_forwards) with independent client-side (tls) and upstream-side (upstream_tls) TLS axes. Seeinternal/proxybuild/tcp_forward.gofor the dispatch matrix and RFC-001 §3.4.2.
Design Principles
- Accept connections at Layer 4 (TCP) and route to a per-connection
ConnectionStackofLayers - No external proxy libraries — built on the standard library
- MCP-first: all operations are exposed as MCP tools
MITM Implementation Principles
As a MITM proxy, yorishiro-proxy must faithfully represent wire-level reality. The following principles apply to all data path code (internal/envelope/, internal/layer/, internal/connector/, internal/pipeline/, internal/pluginv2/, internal/flow/).
- Do not normalize what the wire did not normalize — Header name casing, header order, duplicate headers with different casing, and whitespace must be preserved exactly as observed on the wire. If the wire sends
Set-Cookie: a=1andset-cookie: b=2, they are two distinct headers with different names. Do not merge, canonicalize, or reorder. Example beyond headers: the client's TLS ALPN offer list is forwarded to upstream in the client's wire order, byte-identical — the sniff-first MITM path (USK-997) peekspeekClientHelloSNIAndALPN, threadsClientHelloPeek.ALPNthroughBuildConnectionStack, and dials upstream with that exact slice (no sort, no dedup, no case fold). Upstream's selected protocol is then advertised back to the client as a single-element list (mitmAdvertiseFromUpstreamPick) so end-to-end ALPN is whatever the upstream actually chose, including RFC 7301 §3.2 violations (e.g. demo1.nextcloud.com returninghttp/1.1for a soloh2offer). - Each protocol has its own canonical form; do not unify across protocols — HTTP/1.x headers are case-insensitive but preserve wire casing. HTTP/2 headers are lowercase by spec (RFC 9113). These are different realities and must be handled by protocol-specific code paths, not forced into a shared normalized representation.
- Prefer lossless representations over convenient ones — Use ordered arrays (
[]KeyValue) over maps (map[string][]string) for headers. Use protocol-native types (parser.RawHeadersfor HTTP/1.x,hpack.HeaderFieldfor HTTP/2) over bridge types. Convenience helpers may be provided on top but must not be the storage format. net/httpusage policy — Data path code must not usenet/httptypes for transport or data representation. Use internal types (internal/layer/http1/parserRawRequest/RawResponse, hpack types).net/httpis permitted only in the control plane: MCP server (internal/mcp/), CLI (cmd/), and self-update (internal/selfupdate/).- Attacker-controlled input must be handled gracefully — Parsers must not panic on malformed input. Surface anomalies via
parser.Anomaly(HTTP/1.x) or equivalent typed anomaly fields (grpcweb.Anomaly*, etc.) so they are recorded with the flow rather than crashing the proxy. Buffer limits (MaxBodySize,MaxLineLength, etc.) must be enforced at parse time — not assumed by the caller. - Pre-implementation reality check on hypothetical bugs — Before implementing a code/security review finding (especially CWE-prefixed ones), construct the concrete scenario that triggers the bug and confirm the preconditions exist in the current architecture. If the failure mode requires architecture not yet present (hot-reload, multi-tenant pool, runtime override injection), defer with a documented re-open trigger rather than designing for hypothetical future requirements.
- SafetyFilter Input vs Output: different purposes, different layers — Input Filter (Send-direction, live wire,
internal/pipeline/safety_step.go+internal/rules/{http,ws,grpc}/safety.go) blocks destructive payloads bound for the upstream server. Output Filter (MCP control plane,internal/safety.Engineinvoked frominternal/mcp/safety_helper.go) masks sensitive bytes when an MCP tool returns recorded data to the AI agent. The wire copy delivered to the DB / browser / next hop is never modified by Output Filter; masking happens only at the MCP transport boundary. Do not propose "Output Safety on the wire", "Receive-direction SafetyStep", or "unify the two engines" — these have been considered and rejected. See RFC-001 §3.7 for the full rationale and acceptance record (USK-702 / USK-894).
Package Layout
cmd/yorishiro-proxy/ # Entry point
main.go # CLI root: server/client/docs/version/install/upgrade subcommands
client.go # CLI client subcommand (MCP client via Streamable HTTP)
client_params.go # Flag → JSON parameter conversion engine
client_format.go # Result formatting (JSON / table output)
docs.go # Offline `docs` subcommand (embedded help; no server needed)
install.go, upgrade.go, # Subcommand handlers
version.go
internal/
envelope/ # Protocol-agnostic Envelope + typed Message
# envelope.go (Envelope, EnvelopeContext, TLSSnapshot, Direction, Protocol, KeyValue)
# message.go (Message interface) + per-protocol files
# http.go (HTTPMessage), ws.go (WSMessage),
# grpc.go (GRPCStartMessage/GRPCDataMessage/GRPCEndMessage),
# grpcweb.go, sse.go, raw.go
# bodybuf/ (memory-then-spill BodyBuffer for HTTP/2 streams)
layer/ # Layer + Channel interfaces; per-protocol implementations
# layer.go (Layer interface), channel.go (Channel interface),
# errors.go (StreamError)
# bytechunk/ (raw TCP), tlslayer/ (TLS handshake),
# http1/ (with parser/), http2/ (event-granular),
# httpaggregator/ (folds H2 events into HTTPMessage),
# grpc/, grpcweb/, ws/, sse/
pipeline/ # Pipeline Step chain (HostScope → HTTPScope → Safety → PluginPre →
# Intercept → Transform → PluginPost → Record). UpgradeStep is
# appended after Record by proxybuild for the WS/SSE layer-swap.
# Steps dispatch via type-switch on env.Message.
# WireEncoderRegistry (per-protocol on-Send re-encode).
connector/ # TCP listener, ConnectionStack builder, per-connection plumbing
# full_listener.go (the sole listener API),
# connection_stack.go, detect.go, alpn_routing.go,
# connect_handler.go (CONNECT tunnel), socks5_handler.go,
# h2_dispatch.go, h2_pool.go, h2c_handler.go,
# transport/ (TLS / uTLS / mTLS dial; per-host TLS config)
hostcanon/ # Stdlib-only host comparison forms shared by host-matching seams:
# Fold (deny-like: TargetScope, RateLimiter; folds legacy IPv4),
# FoldDialEquivalent (allow-like: TLS / raw passthrough lists,
# per-host TLS via DialEquivalentPatternKey / DialEquivalentLookupKeys)
proxybuild/ # Live data-path stack assembly + multi-listener Manager
# builder.go (BuildLiveStack), manager.go,
# listener.go (lifecycle wrapper)
pluginv2/ # RFC-001 §9.3 Starlark plugin engine
# register_hook builtin, (protocol, event, phase) 3-axis identity,
# 17-entry hook surface, mutable Starlark dict messages,
# ctx.transaction_state / ctx.stream_state, plugin_introspect
rules/ # Per-protocol rule engines (Intercept, Transform, Safety)
# common/ (HoldQueue, pattern compiler, presets)
# http/, ws/, grpc/, sse/ (USK-892: Intercept + Transform); no raw/ engine
safety/ # SafetyFilter Engine (envelope-native; Input Filter + Output Filter)
# engine.go, rule.go, preset.go (destructive-sql,
# destructive-os-command), preset_pii.go (credit-card,
# japan-my-number, email, japan-phone)
job/ # EnvelopeSource impls (per-protocol resend sources)
# RawResendSource + BytePatch consumed by internal/mcp/{resend_raw,fuzz_raw}_helpers.go.
# source.go (EnvelopeSource interface),
# http_source.go, ws_source.go, grpc_source.go, raw_source.go,
# byte_patch.go (raw-payload patching)
macro/ # Macro engine: template / guard / extract / encoder
flow/ # Stream/Flow Store (sqlite); HAR / JSONL export, import
cert/ # Root CA + dynamic server cert issuance
config/ # Configuration loading + validation (incl. Plugins, body-spill, limits)
encoding/ # String codec registry (base64 / url / hex / html / unicode / hash / case)
# used by macro encoders and MCP body patches;
# protobuf/ (schema-less wire <-> JSON), protoschema/ (schema-aware
# codec, server reflection, protoc), grpclpm/ (gRPC LPM helpers)
mcp/ # MCP server, tools, handlers
# typed resend: resend_http / resend_ws / resend_grpc / resend_raw
# typed fuzz: fuzz_http / fuzz_ws / fuzz_grpc / fuzz_raw
# plugin_introspect, query (with Protocol filter), intercept,
# macro, manage, configure, security, proxy_start / proxy_stop,
# docs (embedded help corpus; shared with the CLI docs subcommand)
session/ # RunSession (universal session loop, OnComplete hook)
logging/ # Structured logging (log/slog)
payload/, setup/, testutil/, selfupdate/Build & Test
make build # build-ui → vet → go build (always rebuilds UI)
make build-ui # Build the React/Vite app in web/ and generate dist/
make ensure-ui # Run build-ui only if dist/ does not exist (lightweight)
make test # fast tier: ensure-ui → go test -race -v ./... (unit tests only)
make test-fast # alias for `make test`; explicit naming for the fast tier (USK-728)
make test-pkg PKG=./internal/<pkg>/... [RUN=<regexp>] [TAGS=e2e]
# one package/pattern only — the TDD red/green loop
make test-ui # web/ only: pnpm install --frozen-lockfile → vitest run
make test-depsec # tools/depsec module only: gofmt check + go vet + go test -race (no UI needed)
make test-e2e-smoke # smoke tier (merge gate): ensure-ui → tools/smokeselect → go test -race -v -tags 'e2e e2e_smoke'
# -run <smoke tests only> <smoke packages> (untagged tests are NOT re-run; USK-1209)
make test-e2e # full tier (nightly): ensure-ui → go test -race -v -tags e2e ./...
make test-cover # ensure-ui → test with coverage report
make vet # ensure-ui → go vet ./...
make fmt # Format all files with gofmt -w .
make lint # gofmt check + golangci-lint (govet/staticcheck/unused/ineffassign/gocyclo)
make lint-ui # web/ only: eslint with --max-warnings 0 (`make lint` stays Go-only)
make lint-workflows # .github/ checks: status-check needs + job permissions guards (yq), pinact, ghalint, actionlint+shellcheck
# (needs network; tools pinned + sha256-verified in .workflow-lint-tools)
make bench # ensure-ui → run benchmarks
make clean # Delete build artifactsLinting (USK-1043):
make lintruns two things. First the Go toolchain's owngofmt -l .over the whole working tree, thengolangci-lint run. The golangci-lint version is pinned in.golangci-lint-version(a single source of truth shared by the Makefile and the CI job, which passes it togolangci-lint-actionviaversion-file:), andmake linthard-fails if the binary on your PATH is a different version — local and CI results cannot drift. Install the pinned version with golangci-lint's officialinstall.sh; do notgo installit, because its source declares a newer Go than this module's floor.
.golangci.ymlenables exactly five linters —govet,staticcheck,unused,ineffassign,gocyclo— withlinters.default: none. golangci-lint's own default set stays off deliberately; enabling more is a separate, incremental change.unusedis in that list to restore a check, not to add one: the standalonestaticcheckbinary reported U1000 by default, and golangci-lint splitsunusedout into its own linter, so omitting it would silently drop U1000 coverage.gofmtis deliberately not delegated to golangci-lint:golangci-lint runonly loads the default build configuration, so it cannot see the//go:build e2efiles ortools/depsec, and it vendors a gofmt fork that disagrees with the toolchain on composite-literal indentation. Keepinggofmt -l .costs nothing (it ships with Go) and keepsmake fmta guarantee thatmake lintpasses.
Workflow linting:
make lint-workflowsis separate frommake lint(it needs the network, not Go or the UI) and is run byci.yml'slint-workflowsjob. Every tool — pinact, ghalint, actionlint, shellcheck, yq — is pinned by version and sha256 in.workflow-lint-toolsand downloaded bytools/lint-workflows/install.shintobin/tools/<tool>-<version>/, re-verified on every run, so local and CI run the same binaries. Rule ownership: pinact owns action pinning (--check --verify-comment --min-age 7: full SHA, the# vX.Y.Zcomment must resolve to that SHA, no action younger than 7 days); ghalint owns permissions / timeouts /persist-credentials/ secret and App-token scoping (its own SHA-pin policy is excluded in.github/ghalint.yaml), except "every job declares its ownpermissions:" — ghalint skips that under a top-levelpermissions: {}, sotools/lint-workflows/check-job-permissions.sh(yq) owns it; actionlint owns expressions, contexts andrun:scripts via the pinned shellcheck. These are build-time tools run as separate executables, never shipped, so they are outside the Dependency License Policy (shellcheck is GPL-3.0).
Merge gate (
status-check): the branch ruleset requiresci.yml'sstatus-checkjob (plus CodeQL), not each job by name. It fails when any job in itsneeds:failed or was cancelled and is otherwise skipped, which counts as passing — so a job skipped by its ownif:does not block. Every newci.ymljob must be added tostatus-check'sneeds:;make lint-workflowsfails, naming the job, if one is missing. Keep the namestatus-checkunique across workflows that run onpull_request.
e2e test tiers (USK-728): e2e tests are split into three tiers.
- fast (
make test/make test-fast): untagged unit tests only.- smoke (
make test-e2e-smoke): merge-gate subset — only the tests declared in//go:build e2efiles. Run by CI on every PR. Building under-tags 'e2e e2e_smoke'also compiles every untagged test, so the recipe narrowsgo testwithtools/smokeselect(derived fromgo list+go/parser, nothing hard-coded) instead of re-running the fast tier; it fails loudly on a selection error or an empty selection (USK-1209). For the old "untagged + smoke" coverage, runmake test test-e2e-smoke. Both PR test jobs inci.ymlcall thesemaketargets rather than hand-copiedgo testlines (USK-1058).- full (
make test-e2e): every e2e file — smoke ∪ exhaustive. Run nightly via.github/workflows/nightly-e2e.yml; also on dependency-update PRs (head branchautomated/security-updates) asci.yml'stest-e2e-fulljob (gated throughstatus-check, which a failure turns red; skipped on other PRs), and on any push tomaintouchinggo.mod/go.sum(USK-1055).The
e2e_smokebuild tag is an exclusion filter: smoke files keep plain//go:build e2e; exhaustive files use//go:build e2e && !e2e_smokeso they drop out of the smoke tier but remain in the full tier under-tags e2ealone. This guaranteessmoke ⊂ full.When adding a new integration test, default to
//go:build e2e && !e2e_smoke(exhaustive). Promote to plain//go:build e2eonly when the test is part of the per-PR merge gate.
Important: Do not run
go test/go vet/go builddirectly.internal/mcp/webui/embed.goembeds the Web UI with//go:embed dist/*, so a missingdist/will cause a compilation error. Always run viamaketargets.
e2e Test Subsystem Verification Checklist
When adding new e2e tests (*_integration_test.go), verify not just communication success
but also subsystem integration. Confirm that the following checklist is satisfied.
- Communication success: Data is correctly transmitted/transformed (send request → receive response → validate content)
- Stream recording: Stream saved to Store with correct protocol name (
Protocol), State, and Scheme - Flow recording: Individual Flows (Send/Receive) correctly recorded with direction, sequence, headers, and body
- State transitions: Progressive recording works correctly (
Statetransitions fromactive→complete) - Plugin hook firing: The relevant
(protocol, event, phase)hook is dispatched viapluginv2.Enginefor the protocol - Error paths: Flow is recorded with
State="error"on connection failure or timeout - Raw bytes recording: Wire-observed raw bytes (
Envelope.Raw) are correctly recorded — L4-capable principle - Variant recording: On intercept/transform modification, both original and modified variants are recorded
- MCP tool integration: Flows are correctly retrievable via the
querytool (withresource: "flows"/resource: "flow"parameters; Protocol family filter acceptshttp/ws/grpc/grpc-web/sse/raw/tls-handshake;filter.wire_levelacceptssemantic/h2-frame/h1-chunk/grpc-lpm-frame/grpcweb-base64/allwith defaultsemantic— overlay rows are excluded frommessage_count/message_previewunless explicitly opted in)
Applicability: Not all items are required for every test. Verify relevant items based on protocol characteristics and test purpose. Example: Raw TCP has no L7 structured view, so header validation under "message content" is not required. SOCKS5 is excluded from flow recording as a transport layer; validate at the tunneled protocol instead.
Reference patterns: see
internal/connector/full_listener_integration_test.go(the canonical end-to-end harness) and per-Layer harnesses such asinternal/layer/http1/mitm_integration_test.go,internal/layer/http2/http2_integration_test.go,internal/layer/grpc/grpc_integration_test.go,internal/layer/ws/ws_integration_test.go,internal/layer/sse/sse_integration_test.go,internal/layer/grpcweb/grpcweb_integration_test.go,internal/layer/bytechunk/smuggling_integration_test.go.
Coding Conventions
- Go standard style (
gofmt/goimports) - Wrap errors with
fmt.Errorf("context: %w", err) - Propagate
context.Contextas the first argument - Package comments go in doc.go or the leading file
- Tests in
_test.gofiles; table-driven tests recommended - The pattern of using
t.Logfto record unverified behavior is prohibited. Uset.Skip("not yet implemented: <issue-id>")for unimplemented features - Do not expose
internal/packages externally
Concurrency Checklist
When implementation involves goroutines, channels, or io.Pipe, verify the following before opening a PR. Iterating on these in review (rather than designing them upfront) historically causes multi-round review cycles.
- Termination condition is explicit for every goroutine — context cancel, channel close, EOF, or a named
Closed()/Err()interface. No "this should usually finish" assumptions. - Channel close ownership is single-writer — wrap with
sync.Onceif multiple paths can request teardown. Never close the same channel from two code paths. - Teardown is centralized — concentrate close logic in one
abort()/Close()method. Callers signal; they do not close primitives directly. - Read loops do not block on external backpressure — decouple slow consumers (e.g.,
io.Pipewrites that wait on a reader) with buffered channels or explicit drop policies. - Body / channel
Close()stops every associated goroutine — sender, writer, drainer. A leaked goroutine here often holds a reference to wire data. - Cascade-close is conditional on error — for proxy session goroutines (
clientToUpstreametc.), defer the upstreamClose()only on non-nil error. Closing onio.EOFaborts in-flight responses on HTTP/1.x.
Log Level Guidelines
Level selection for log/slog follows these criteria:
| Level | Purpose | Examples |
slog.Debug | Detailed information for developers/diagnostics. Output only at -log-level debug | Protocol detection results, TLS SNI, rule match decisions, frame send/receive, handshake progress |
slog.Info | Major events of normal operation. Output by default | Server start/stop, proxy start/stop, config load complete, plugin load |
slog.Warn | Abnormal but recoverable state. Events that need operator attention | TLS certificate validation failure (insecure mode), deprecated feature usage, retry occurrence, signs of resource exhaustion |
slog.Error | Processing failure. Unrecoverable or request-level fatal errors | DB write failure, listener start failure, CA certificate load failure |
Decision Criteria
- Debug vs Info: If an operator can confirm normal operation without the log, use Debug. Use Info for events that show "what happened" — start, stop, config change
- Info vs Warn: Use Info if it is part of the normal flow. Use Warn if unexpected but processing continues. Warn means "operator should check", and if it occurs frequently, demote to Info or Debug
- Warn vs Error: Use Warn if processing can continue. Use Error if returning an error to the caller or if a request fails
Decision Examples for Ambiguous Cases
| Case | Level | Reason |
| Client sends invalid request (4xx) | Debug | Client-side issue; not a proxy anomaly |
| Upstream server returns 5xx | Debug | Proxy relayed correctly; upstream issue. Traceable via flow recording |
| Request matches intercept rule | Debug | Normal operation detail. Useful for diagnostics but not needed by default |
| Safety Filter blocks a request | Info | Security event that should notify the operator |
| Starlark script in plugin throws runtime error | Warn | Plugin issue, but the proxy itself can continue |
| WebSocket connection closes normally | Debug | Normal operation detail |
| WebSocket connection disconnects abnormally | Warn | Unexpected but processing can continue |
| Flow DB save fails | Error | Data loss occurred. Unrecoverable |
| Config file not found; using default values | Info | Part of normal flow (designed to work with default values) |
| Connection timeout to CONNECT tunnel target | Debug | Network-dependent. Returns error response to client, but not a proxy anomaly |
Dependency License Policy
Scope: this policy governs distributed dependencies — anything linked into the shipped binary or the published npm artifacts, i.e. what /license-check's go list -m -json all can see. Build-time-only tools that run as separate executables (linters, formatters) are out of scope: golangci-lint, for instance, is GPL-3.0 but appears in no go.mod/go.sum, and its diagnostic output is not a derivative work — the same reason GCC's licence does not infect the programs it compiles. Two caveats: this holds only while such a tool is never vendored or redistributed in a release artifact, and golangci-lint custom would build a combined GPL-3.0 binary, which must not be shipped.
Allowed
MIT, BSD (2-clause, 3-clause), Apache-2.0, ISC, MPL-2.0
Prohibited
All GPL variants (GPL-2.0, GPL-3.0, LGPL-2.1, LGPL-3.0, AGPL-3.0)
Approved Dependencies
Every module in the require block of go.mod, with the licence taken from the module's own
LICENSE file rather than from a package index. Indirect dependencies are governed by the same
policy but are deliberately not enumerated — /license-check walks the whole graph on every run.
| Module | License | Why it is here |
github.com/modelcontextprotocol/go-sdk | Apache-2.0 | Official MCP Go SDK. Its LICENSE opens with the MCP project's MIT → Apache-2.0 transition notice, so contributions whose authors have not consented to relicensing are still MIT. Both are Allowed. |
modernc.org/sqlite | BSD-3-Clause | Pure Go SQLite driver behind the Stream / Flow Store |
github.com/google/uuid | BSD-3-Clause | StreamID / FlowID generation |
golang.org/x/sync | BSD-3-Clause | errgroup / singleflight |
go.starlark.net | BSD-3-Clause | Starlark engine for internal/pluginv2 |
golang.org/x/net | BSD-3-Clause | http2 / hpack / h2c / proxy primitives used by the HTTP/2 data path |
github.com/refraction-networking/utls | BSD-3-Clause | uTLS ClientHello fingerprinting (internal/layer/tlslayer, internal/connector/transport) |
github.com/andybalholm/brotli | MIT | Brotli body decode (internal/bodydecode) |
github.com/klauspost/compress | Apache-2.0 | zstd body decode (internal/bodydecode) |
golang.org/x/time | BSD-3-Clause | Rate limiting in internal/connector/ratelimit.go |
google.golang.org/grpc | Apache-2.0 | Server-reflection client and the MCP-side gRPC resend / fuzz helpers. Not in the proxy data path — gRPC on the wire is parsed natively (see "No external proxy libraries"). |
google.golang.org/protobuf | BSD-3-Clause | Descriptor / reflection handling in internal/encoding/protoschema |
go.uber.org/goleak | MIT | Goroutine-leak assertions. Test-only — absent from go list -deps ./cmd/yorishiro-proxy, so it is never shipped. |
The Web UI's production npm dependencies are in scope as well, because make build-ui bundles them
into internal/mcp/webui/dist/; they are declared in web/package.json and audited by the same
skill. web/'s devDependencies are build-time-only tooling and fall under the Scope exemption
above — confirm a package really does not reach dist/ before relying on that.
When adding a new module to go.mod or to web/package.json's dependencies, verify the license
with the /license-check skill, and add a row here for a direct Go dependency.
Supply Chain Risk Policy
Dependency updates are gated on release age so a freshly compromised version is never pulled in on publish day. The weekly .github/workflows/dependabot-security.yml run is the only automated path that edits dependency manifests; tools/depsec decides what to apply and the workflow applies it.
npm
- The age window, registry, and exclusions live in
web/.npmrc(minimum-release-age, the Takumi Guard proxy registry,minimum-release-age-exclude[]). pnpm >= 10.16 enforces them natively at install time — do not reimplement any of it in the workflow or intools/depsec. pnpm.overridesis forbidden. Forcing a transitive package to a version its parent never declared decouples the lockfile from what upstream actually tested, and the pin silently outlives the parent's own fix.- Refreshing a transitive package within the range its parent already declares is allowed, and the workflow does it automatically with
pnpm update --no-save(no--latest, and the manifest is left untouched so the reviewer sees only lockfile movement). This is an ordinary update, not an override: the parent's semver contract is the ceiling. Do not conflate the two — treating every transitive package as untouchable is what let 48 in-range fixes sit unapplied for 10 weeks (USK-1040). - A transitive fix that falls outside the parent's declared range is the one case that needs manual review: bump the parent, or wait for the parent's release. Never reach for an override to shortcut it.
Go
Go has no native minimum-release-age mechanism, so tools/depsec gates each fix explicitly on the module's publish time from the Go module proxy and applies only fixes at least 7 days old. Newer fixes are deferred to a later run. Note that the Dependabot API reports Go patched versions without the leading v; canonicalize with goVersionTag before touching the proxy or go get (USK-1039).
Judging severity
Dependabot alerts are module-level and carry no reachability analysis. Before treating a Go alert as urgent, check whether the vulnerable package is actually linked: go list -deps ./cmd/yorishiro-proxy. For npm, check whether the package reaches the shipped bundle at all — most of web/'s alerts are build-time or dev-only tooling and never appear in internal/mcp/webui/dist/.
Development Workflow
/project status— Check milestone progress and decide what to work on next/project plan <milestone>— Create and organize Linear Issues from the roadmap/orchestrate— Delegate multiple Issues to sub-agents for parallel implementation per milestone/implement <Issue ID>— Implement, test, commit, and create PR for a single Issue/review-gate— Run Code Review + Security Review in parallel for a PR. If issues found, auto-fix → re-review (up to 2 rounds)/project sync— Update roadmap documents after implementation is complete/autopilot— Unattended variant of/orchestratefor scheduled runs (Desktop local scheduled task). One Issue per run through to a review-gated PR; never merges. See.claude/skills/autopilot/SETUP.md
Test-Driven Development
Implementation is test-first across /implement, /orchestrate and /autopilot; the rules live
in one place, "TDD Workflow" in .claude/agents/implementer.md. In short:
milestone-plannerwrites acceptance criteria as behaviors a test can observe;design-reviewerturns them into a Test Plan (behavior / real seam / fixture source / tier / expected red).- The implementer commits the failing tests alone first (
test(<scope>): add failing tests for <ID>), having seen each fail on its assertion viamake test-pkg, then implements without weakening them. The PR body carries a "TDD evidence" section. Squash merge keeps the red commit offmain. code-reviewerre-runs the red commit, diffs*_test.gofrom red to HEAD for weakening, and falls back to a mutation check when red evidence is missing.- Exempt: docs/CI-only, renames, behavior-preserving refactors (existing or characterization tests must pass first), and test-only Issues (prove each test can fail by local mutation instead).
Note:
/implementassumes single-session, solo execution. Use/orchestratefor parallel implementation of multiple Issues, and/autopilotonly from a scheduled (unattended) session.
Config Checklist for New Feature Milestones
When splitting Issues for a new feature milestone with /project plan, treat the following as mandatory checks.
This prevents config support from being omitted as an implicit assumption.
- Does the config struct in
internal/config/need a new field? - Does config validation (
Validate()) need to be added or updated? - Does an init function (
cmd/yorishiro-proxy/main.go) need to change? - Is a config → runtime path integration test needed?
- If any of the above apply, explicitly create a config support Issue
e2e Test Checklist for New Protocol Addition
When splitting Issues for a new protocol with /project plan, treat the following as mandatory checks.
This prevents gaps in e2e test coverage. Refer to the "e2e Test Subsystem Verification Checklist" for individual test verification details.
- e2e test for successful proxy communication (
internal/connector/*_integration_test.goand/orinternal/layer/*/*_integration_test.go) - Stream/Flow recording completeness verification (protocol name, State transitions, Flow count per Stream)
- Raw bytes recording completeness verification (frame boundaries, binary data round-trip) — L4-capable principle
- Variant recording test (original/modified save on intercept modification)
- Progressive recording test (intermediate state verification for streaming protocols)
- Plugin hook firing verification (relevant
(protocol, event, phase)hooks dispatched viapluginv2.Engine) - Safety Filter / Output Filter application verification
- Error path e2e tests (connection failure, timeout, malformed data)
- Independent tests for derived protocols (e.g., HTTP/2 → gRPC) if they exist
- MCP tool integration tests (flow details returned correctly via query tool)
- WebUI display tests (including null guards for new protocol components)
- If any of the above apply, explicitly create a test Issue
Relationship to Subsystem Verification Checklist: This checklist is a planning-level list for splitting Issues when adding new protocols. The Subsystem Verification Checklist is an implementation-level list for writing individual e2e test files. Refer to both.
Agent Isolation Strategy (Worktree)
To prevent git conflicts during parallel work by sub-agents, apply the following rules.
Principles
- Lock the main worktree (the repository clone origin) to the main branch and prohibit direct work — All branch switching and commits happen inside worktrees. The main branch cannot be pushed to directly due to branch protection
- Sub-agents that touch the working tree are launched with
isolation: "worktree"— During parallel execution, checking out the main worktree's HEAD conflicts with the code state read by other agents, so even read-only review agents that check out a branch are isolated in worktrees - An agent whose only job is to orchestrate other agents is NOT isolated — A sub-agent's worktree is created under its own cwd, so isolating a parent makes every child nest at
agent-<parent>/.claude/worktrees/agent-<child>. Since.claude/worktrees/is gitignored,git worktree remove <parent>leaves that subtree behind as an unregistered directory holding still-registered children — reclaimable only withrm, which is in theasklist and therefore stalls an unattended run. A delegated review-gate agent reads the PR throughghand delegates all code access to its own isolated sub-agents, so it needs no worktree of its own; leaving it un-isolated keeps every leaf worktree flat - Never
git checkoutthe main worktree to a different branch when the user has parallel work in progress — Rungit statusfirst; if the working tree has user-owned modifications, treat the main worktree as locked. Usegit worktree add -b <new-branch> .claude/worktrees/<short-name> <base>to materialise side tasks in an isolated checkout instead. Do not reuse.claude/worktrees/agent-*paths (those are reserved for sub-agents) — pick a descriptive sibling. - Verify main-worktree branch after parallel-agent return — Sub-agents launched with
isolation: "worktree"occasionally write edits into the main clone instead of the worktree (Edit-tool race), leaving the main clone on a feature branch. After every parallel-agent return, rungit branch --show-currentandgit worktree list; if the main clone is off-base, switch back withgit checkout <base> && git pull --rebase origin <base>before launching downstream agents.
Classification in Task Tool
| Agent Type | Operation | isolation |
| implementer | Code implementation, commit, push | "worktree" |
| fixer | Fix review findings, commit, push | "worktree" |
| code-reviewer | Checkout target branch, read diff, post review | "worktree" |
| security-reviewer | Checkout target branch, read diff, post review | "worktree" |
| review-gate (delegated) | Launch reviewers/fixers, aggregate verdict; touches no files itself | none — isolating it nests its children |
When Adding New Agents
- Sub-agents that read or write the working tree use
isolation: "worktree"by default - Sub-agents that only launch and aggregate other sub-agents take no isolation
- Document the isolation setting in the calling skill (
.claude/skills/*/SKILL.md)
Worktree Cleanup
The Claude Code Task tool does not auto-delete worktrees when they have changes after completion. The calling skill is responsible for cleanup.
Cleanup Timing
| Skill | Cleanup Timing |
/orchestrate | Phase 3-3 (after all batches and reviews complete) |
/review-gate | Phase 6 (after review cycle completes) |
/autopilot | Phase 6-1 (end of every run, success or failure) |
/code-review | Step 7 (after reporting results) |
Each skill tracks the agent IDs of the sub-agents it launched and deletes only those worktrees. Do not bulk-delete to avoid destroying active worktrees of other sessions.
This is the canonical snippet. $IDS is a file holding one recorded agent ID per line — never a
glob of agent-*:
git worktree list --porcelain | awk '/^worktree /{print $2}' > "$IDS.wt"
: > "$IDS.targets"
while read -r id _rest; do
[ -n "$id" ] || continue
while read -r wt; do
case "$wt" in *"agent-$id"*) printf '%s\n' "$wt" >> "$IDS.targets" ;; esac
done < "$IDS.wt"
done < "$IDS"
sort -u "$IDS.targets" | awk '{print length, $0}' | sort -rn | cut -d' ' -f2- |
while read -r wt; do
git worktree remove "$wt" --force --force 2>/dev/null || true
done
git worktree pruneThree things in it are load-bearing; all three were verified on 2026-09-17 after a nested
/orchestrate run left a 110 MB unregistered husk on disk:
- Never construct
.claude/worktrees/agent-<id>from an ID. A sub-agent launched by another sub-agent nests under its parent, so the top-level path does not exist and the remove silently no-ops behind2>/dev/null || true. Resolve real paths fromgit worktree listand remove deepest first, so a child is unregistered before its parent's directory disappears. --force --force, not--force. A single--forcefails with exit 128 on a locked worktree (cannot remove a locked working tree), which an agent that is still registered leaves behind.git worktree unlockfirst is the equivalent alternative.- Never select the paths with
grep -F -f <id-file>. Thegrepon this machine is ugrep, and with an empty pattern file it matches every line — an empty ID list would then delete other sessions' worktrees. Thecaseloop above selects nothing when the list is empty.
If stale worktrees accumulate, check with git worktree list and remove individually with
git worktree remove <path> --force --force. An unregistered leftover directory (present on
disk, absent from git worktree list) can only be removed with rm — ask the user rather than
running it from an unattended session.
Permission Policy (.claude/settings.json)
The three permission lists were rewritten for auto mode, where a classifier judges each un-listed tool call instead of every unknown command reaching the user as a prompt. That inverts what each list is for, so keep new entries in the right one.
| List | Meaning under auto mode | Admission test |
deny | Hard boundary. The classifier cannot override it, so this is the only backstop left. | The action is never legitimate in this repo, and the rule matches the whole class rather than one literal string. |
ask | Forces a prompt even when the classifier would allow. Reserved for irreversible loss. | Losing this cannot be undone from reflog, the remote, or a rebuild. |
allow | Skips the classifier entirely. | Deterministic and hard to misuse — not merely "usually fine". |
Consequences worth remembering:
- Anything context-dependent belongs in no list.
find,curl,gh api, andgit rebaseare safe or destructive depending on their arguments, which is exactly the judgement the classifier makes per call. Listing them inasktaxes the safe 99% to catch the 1%; listing them inallowwaves the 1% through. denyrules must match a class. The oldBash(dd if=/dev/zero of=/dev/sda)was an exact-match rule thatof=/dev/sdbwalked straight past. PreferBash(dd:*). For the same reason, a--long-flagdeny needs its short form too (git push --forceandgit push -f).- Prefix rules cannot see past the first token run.
Bash(git worktree remove --force:*)never fires ongit worktree remove <path> --force, andgit push origin +main:mainforce-pushes without matching any--forcerule. Where a rule cannot be expressed, rely on the classifier and branch protection rather than writing one that looks like it works. Read(...)deny rules also feedsandbox.filesystem.denyRead, so a broad glob can block the test process from reading a file it just generated. This is why the CA private key is denied asRead(**/.yorishiro-proxy/ca/**)— the real path — and not asRead(**/*.key), which would collide with certs thatinternal/certtests generate in temp dirs.- The
maketargets are listed one by one, mirroring.PHONYin the Makefile, so that adding a target does not silently inherit an allow rule. Add the new target here when you add it to the Makefile. - Supply-chain commands stay in
ask.go get/go installare gated because Go has no native minimum-release-age mechanism (see "Supply Chain Risk Policy"). pnpm is not gated here —web/.npmrcenforces the age window natively at install time. gh pr merge/gh pr closeare deliberately absent fromallow: merging is outward-facing and should get a look.
Branch Strategy
main— Always maintains a passing build and test state- Feature branches:
feat/<issue-id>-<short-desc>(e.g.,feat/USK-12-http-handler) - Bug fixes:
fix/<issue-id>-<short-desc> - All PRs require CI to pass before merge
Commit Conventions
Conventional Commits format:
<type>(<scope>): <description>
[optional body]
[optional footer]type: feat, fix, refactor, test, docs, ci, chore
Linear
- Team: Usk6666
- Project: yorishiro-proxy
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

