c24165b8bc
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게 [공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류. 문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인). - Topic_Programming → Domain_Programming (내부 구조 보존) - Topic_Graphic → Domain_Design - Topic_Business → Domain_Product - Topic_General → Domain_General - _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning), Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing) - 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서) - 빈 폴더 정리 (memory/procedures) - 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
6.7 KiB
6.7 KiB
id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
| id | title | category | status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | verification_status | tags | raw_sources | last_reinforced | github_commit | tech_stack | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| wiki-2026-0508-zod-런타임-유효성-검사-통합 | Zod 런타임 유효성 검사 통합 | 10_Wiki/Topics | verified | self |
|
none | A | 0.9 | applied |
|
2026-05-10 | pending |
|
Zod 런타임 유효성 검사 통합
매 한 줄
"매 type schema = single source of truth". Zod는 매 TypeScript type을 런타임 schema 로 정의하고, parse 시점에 매 validation + type narrowing 을 동시 제공한다. API boundary, env vars, form input 매 unsafe input 의 매 첫 검증선.
매 핵심
매 동기 (Why Zod over alternatives)
- TypeScript types are erased: 매 컴파일 후
interface User는 매 사라짐 → API response 의data as User매 lying. - Zod = schema → type:
z.infer<typeof Schema>로 매 schema 가 source of truth. - Composability: 매
.merge,.partial,.extend,.transform으로 매 schema 합성. - Error-rich: parse failure 시 매 path, code, message tree 반환.
매 경쟁 라이브러리
- Yup: 매 older, schema → type 약함, 매 Zod 가 대체.
- io-ts: 매 더 functional (fp-ts), 매 learning curve 높음.
- Valibot: 매 tree-shakable, 매 bundle size 우선이면 고려 (~10x smaller).
- ArkType: 매 string-based syntax, 매 빠르지만 ecosystem 작음.
- Zod: 매 default choice in 2026 — DX, ecosystem (tRPC, React Hook Form), maturity.
매 응용
- API boundary: fetch response 매 parse 후 typed 으로 사용.
- Form validation: React Hook Form + zodResolver.
- env vars:
process.env의 매 schema parse, missing key 시 즉시 fail. - DB row → domain: ORM 결과 매
Schema.parse(row). - LLM structured output: Claude/GPT JSON response 매 schema 로 검증.
💻 패턴
Pattern 1: 기본 schema + type inference
import { z } from "zod";
export const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
age: z.number().int().min(0).max(150),
role: z.enum(["admin", "user", "guest"]),
createdAt: z.coerce.date(),
});
export type User = z.infer<typeof UserSchema>;
// usage
const raw: unknown = await fetchUser();
const user = UserSchema.parse(raw); // throws ZodError if invalid
// ^? User
Pattern 2: safeParse for non-throw
const result = UserSchema.safeParse(raw);
if (!result.success) {
console.error(result.error.flatten());
return;
}
const user = result.data; // typed
Pattern 3: env validation (fail fast at boot)
const EnvSchema = z.object({
DATABASE_URL: z.string().url(),
PORT: z.coerce.number().int().positive().default(3000),
NODE_ENV: z.enum(["development", "production", "test"]),
ANTHROPIC_API_KEY: z.string().startsWith("sk-ant-"),
});
export const env = EnvSchema.parse(process.env);
// process exits at startup if invalid — better than runtime surprise
Pattern 4: discriminated union
const ResultSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("ok"), data: z.string() }),
z.object({ status: z.literal("error"), code: z.number() }),
]);
type Result = z.infer<typeof ResultSchema>;
// narrowing on .status works correctly
Pattern 5: transform for parse-not-validate
const DateSchema = z.string().transform((s, ctx) => {
const d = new Date(s);
if (isNaN(d.getTime())) {
ctx.addIssue({ code: "custom", message: "Invalid date" });
return z.NEVER;
}
return d;
});
const out = DateSchema.parse("2026-05-10"); // Date instance
Pattern 6: API client with Zod
async function fetchUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
const json = await res.json();
return UserSchema.parse(json); // unknown → User
}
Pattern 7: tRPC integration
import { router, procedure } from "./trpc";
export const userRouter = router({
create: procedure
.input(UserSchema.omit({ id: true, createdAt: true }))
.mutation(async ({ input }) => {
// input is fully typed + validated
return db.user.create({ data: input });
}),
});
Pattern 8: React Hook Form + Zod
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
const FormSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
const { register, handleSubmit, formState } = useForm({
resolver: zodResolver(FormSchema),
});
Pattern 9: schema composition
const Base = z.object({ id: z.string(), createdAt: z.date() });
const Post = Base.extend({ title: z.string(), body: z.string() });
const PostUpdate = Post.partial().required({ id: true });
Pattern 10: refinement (custom rules)
const PasswordSchema = z
.object({ password: z.string(), confirm: z.string() })
.refine((d) => d.password === d.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
매 결정 기준
| 상황 | Approach |
|---|---|
| API boundary, untrusted input | Zod parse |
| Internal pure-TS code | Type only, no Zod |
| Bundle size critical (mobile, edge) | Valibot |
| Functional ergonomics | io-ts |
| LLM structured output (Claude/GPT) | Zod + tool schema |
| Performance hot path (>10k parses/sec) | Compile to TypeBox/AJV |
기본값: Zod 3.x — 매 modern TS app 의 default validation layer.
🔗 Graph
- 부모: TypeScript · Runtime_Validation
- 변형: Valibot · Yup · ArkType
- 응용: React Hook Form
- Adjacent: JSON Schema · 과잉 속성 체크 (Excess Property Checking)
🤖 LLM 활용
언제: untrusted boundary (API, form, env, LLM output) 매 parse. tool/function calling 의 매 input schema. 언제 X: internal pure-TS code 매 over-validation 불필요. hot loop 의 매 매 parse 호출.
❌ 안티패턴
- Anti1: parse everywhere: 매 internal function 매 Zod parse — 매 overhead 누적, 매 type only 충분.
- Anti2: as cast after parse:
Schema.parse(x) as MyType— 매 redundant, parse 가 이미 typed return. - Anti3: schema duplication: type + schema 따로 정의 — 매 z.infer 사용.
- Anti4: nested transforms with side effects: transform 안에서 fetch/IO — 매 pure 하게 유지.
🧪 검증 / 중복
- Verified (Zod docs colinhacks.com/zod, 2026 ecosystem).
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Zod runtime validation patterns + 2026 ecosystem context |