{"id":"fa68cd1c-8fd6-489e-8864-8520a10442c2","shortId":"99AR4C","kind":"skill","title":"test-driven-development","tagline":"Use when implementing any feature or bugfix, before writing implementation code","description":"# Execute\n\n→ Implementing a feature or bugfix? → **No production code without a failing test first.**\n  Gate: medium/high complexity? → route to brainstorming or writing-plans first.\n  Cycle: RED (write test → watch it fail) → GREEN (minimal code → watch it pass) → REFACTOR (clean up → keep green)\n  Regression: shared module → related tests. contract change → producer + consumer. core logic → old + new tests.\n  Ripple signal hit → cover producer+consumer or real user path before claiming green.\n→ Done when: all tests pass, every new function has a test that failed first, TDD preflight gate passed.\n\n# Test-Driven Development (TDD)\n\n## Overview\n\nWrite the test first. Watch it fail. Write minimal code to pass.\n\nIf you didn't watch the test fail, you don't know if it tests the right thing.\n\n## When to Use\n\nNew features, bug fixes, refactoring, behavior/logic changes, interface/data contract changes, cross-module or shared module changes, core logic refactors.\n\nExceptions (ask your human partner): throwaway prototypes, generated code, config files, pure docs cleanup, read-only diagnosis, comment-only changes.\n\n## Preflight Gate\n\nTDD is the implementation discipline for an approved behavior or atomic task.\nIt is not a substitute for task routing, product clarification, or planning.\n\nBefore writing tests or production code, stop and route to brainstorming or\nwriting-plans if the current request has any medium- or high-complexity signal:\n\n- multiple files, modules, pages, screens, services, or owners\n- user-visible flows such as navigation, onboarding, checkout, lifecycle, or\n  recovery paths\n- state transitions, routing rules, API or data contracts, compatibility\n  boundaries, migrations, permissions, or persistence\n- more than one acceptance path or manual/visual verification requirement\n- unclear product behavior, competing constraints, or long-running execution\n\nFor these tasks, require a baseline read-set, plan, and atomic tasks before TDD.\nHigh-complexity or ambiguous tasks also need a spec/design review before\nplanning. Only proceed directly with TDD for low-complexity work whose intent,\nowner, compatibility boundary, and verification path are already clear.\n\nWhen a medium- or high-complexity task needs project records, use configured Aegis workspace support\nlazily. Prefer the installed Aegis workspace helper\n(`python <aegis-workspace-helper> init --root <target-project-root>`) when it\nis available. If the task needs a process trail under `work/`, prefer\n`python <aegis-workspace-helper> new-work --root <target-project-root> ...`\nso the intent, checkpoint, drift, and evidence paths are indexed and\nstructurally checkable:\n\n```text\ndocs/aegis/\n  README.md\n  INDEX.md\n  BASELINE-GOVERNANCE.md\n  adr/\n  baseline/\n  specs/\n  plans/\n  work/YYYY-MM-DD-<task-slug>/\n    10-intent.md\n    20-checkpoint.md\n    90-evidence.md\n    99-reflection.md\n```\n\nDo not promote reusable project facts, decisions, specs, or plans into those\ndirectories unless the workflow needs them and no existing project authority\nalready owns them.\n\n## Red-Green-Refactor\n\n### RED - Write Failing Test\n\nState: input | output | boundary | acceptance criteria. Check existing test coverage first. Write one minimal test showing what should happen.\n\n<Good>\n```typescript\ntest('retries failed operations 3 times', async () => {\n  let attempts = 0;\n  const operation = () => {\n    attempts++;\n    if (attempts < 3) throw new Error('fail');\n    return 'success';\n  };\n\n  const result = await retryOperation(operation);\n\n  expect(result).toBe('success');\n  expect(attempts).toBe(3);\n});\n```\nClear name, tests real behavior, one thing\n</Good>\n\n<Bad>\n```typescript\ntest('retry works', async () => {\n  const mock = jest.fn()\n    .mockRejectedValueOnce(new Error())\n    .mockRejectedValueOnce(new Error())\n    .mockResolvedValueOnce('success');\n  await retryOperation(mock);\n  expect(mock).toHaveBeenCalledTimes(3);\n});\n```\nVague name, tests mock not code\n</Bad>\n\n**Requirements:**\n- One behavior\n- Clear name\n- Real code (no mocks unless unavoidable)\n- If a new feature changes user-observable behavior, prefer one minimal\n  end-to-end or integration test for the main path before narrower unit tests\n- For user-visible work, cover the main journey and the highest-risk experience\n  or operational floor before treating unit tests as sufficient\n- Add unit tests for core rules, boundary conditions, and error branches\n\n### Verify RED - Watch It Fail\n\n**MANDATORY. Never skip.**\n\n```bash\nnpm test path/to/test.test.ts\n```\n\nConfirm:\n- Test fails (not errors)\n- Failure message is expected\n- Fails because feature missing (not typos)\n\n**Test passes?** You're testing existing behavior. Fix test.\n\n**Test errors?** Fix error, re-run until it fails correctly.\n\n### GREEN - Minimal Code\n\nWrite simplest code to pass the test.\n\n<Good>\n```typescript\nasync function retryOperation<T>(fn: () => Promise<T>): Promise<T> {\n  for (let i = 0; i < 3; i++) {\n    try {\n      return await fn();\n    } catch (e) {\n      if (i === 2) throw e;\n    }\n  }\n  throw new Error('unreachable');\n}\n```\nJust enough to pass\n</Good>\n\n<Bad>\n```typescript\nasync function retryOperation<T>(\n  fn: () => Promise<T>,\n  options?: {\n    maxRetries?: number;\n    backoff?: 'linear' | 'exponential';\n    onRetry?: (attempt: number) => void;\n  }\n): Promise<T> {\n  // YAGNI\n}\n```\nOver-engineered\n</Bad>\n\nDon't add features, refactor other code, or \"improve\" beyond the test.\n\nFix the real owner of the behavior. Do not add a new fallback, adapter, or\nbranch unless the debugging or design workflow identifies why it is necessary\nand what old path retires.\n\n### Verify GREEN - Watch It Pass\n\n**MANDATORY.**\n\n```bash\nnpm test path/to/test.test.ts\n```\n\nConfirm:\n- Test passes\n- Other tests still pass\n- Output pristine (no errors, warnings)\n\n**Test fails?** Fix code, not test.\n\n**Other tests fail?** Fix now.\n\n### REFACTOR - Clean Up\n\nAfter green only:\n- Remove duplication\n- Improve names\n- Extract helpers\n\nKeep tests green. Don't add behavior.\n\n### Repeat\n\nNext failing test for next feature.\n\n## Regression Scope\n\nAt minimum, run the target test you just changed or added. Broaden regression\nbased on impact:\n\n- Shared module change -> related module tests\n- Interface or data contract change -> producer and consumer tests\n- Cross-module behavior change -> integration or end-to-end path\n- Core logic refactor -> old behavior regression tests plus new behavior tests\n- Ripple Signal Triage fired -> producer+consumer or real user path that proves\n  the downstream effect remains bounded\n\nIf the current environment cannot run automated tests, state the blocker and provide reproducible manual verification steps.\n\n## Good Tests\n\n| Quality | Good | Bad |\n|---------|------|-----|\n| **Minimal** | One thing. \"and\" in name? Split it. | `test('validates email and domain and whitespace')` |\n| **Clear** | Name describes behavior | `test('test1')` |\n| **Shows intent** | Demonstrates desired API | Obscures what code should do |\n\n## Red Flags - STOP and Start Over\n\n- Code before test\n- Test after implementation\n- Test passes immediately\n- Can't explain why test failed\n- Tests added \"later\"\n- Rationalizing \"just this once\"\n- \"I already manually tested it\"\n- \"Tests after achieve the same purpose\"\n- \"It's about spirit not ritual\"\n- \"Keep as reference\" or \"adapt existing code\"\n- \"Already spent X hours, deleting is wasteful\"\n- \"TDD is dogmatic, I'm being pragmatic\"\n- \"This is different because...\"\n\n**All of these mean: Delete code. Start over with TDD.**\n\n## Example: Bug Fix\n\n**Bug:** Empty email accepted\n\n**RED**\n```typescript\ntest('rejects empty email', async () => {\n  const result = await submitForm({ email: '' });\n  expect(result.error).toBe('Email required');\n});\n```\n\n**Verify RED**\n```bash\n$ npm test\nFAIL: expected 'Email required', got undefined\n```\n\n**GREEN**\n```typescript\nfunction submitForm(data: FormData) {\n  if (!data.email?.trim()) {\n    return { error: 'Email required' };\n  }\n  // ...\n}\n```\n\n**Verify GREEN**\n```bash\n$ npm test\nPASS\n```\n\n**REFACTOR**\nExtract validation for multiple fields if needed.\n\n## Verification Checklist\n\n- [ ] Defined input, output, boundaries, compatibility, acceptance criteria\n- [ ] Every new function/method has a test that failed first\n- [ ] All tests pass, output pristine\n- [ ] Regression: shared/contract/core changes ran related tests\n- [ ] Ripple signal hit: downstream or real user path covered\n- [ ] If automation blocked → blocker + manual steps documented\n\nCan't check all boxes? Start over.\n\n## Exploration and Emergency Exceptions\n\nExploratory spikes are allowed only as throwaway learning. When the spike ends,\nconvert confirmed behavior into tests before formal implementation.\n\nEmergency hotfixes may prioritize the smallest safe repair when delay is more\ndangerous than incomplete TDD. Record the reason, keep the change narrow, and\nadd the missing regression test in the same slice or the next nearest slice.\n\n## When Stuck\n\nDon't know how to test → write wished-for API first. Test too complicated → simplify design. Must mock everything → reduce coupling.\n\n## Debugging Integration\n\nBug found? Write failing test reproducing it. Follow TDD cycle. Never fix bugs without a test.","tags":["test","driven","development","aegis","ganyuanran","add","agent-skills","ai-agents","ai-coding","baseline-first","claude-code","codex"],"capabilities":["skill","source-ganyuanran","skill-test-driven-development","topic-add","topic-agent-skills","topic-ai-agents","topic-ai-coding","topic-baseline-first","topic-claude-code","topic-codex","topic-coding-agents","topic-evidence-driven","topic-first-principles","topic-opencode","topic-software-architecture"],"categories":["Aegis"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/GanyuanRan/Aegis/test-driven-development","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add GanyuanRan/Aegis","source_repo":"https://github.com/GanyuanRan/Aegis","install_from":"skills.sh"}},"qualityScore":"0.581","qualityRationale":"deterministic score 0.58 from registry signals: · indexed on github topic:agent-skills · 262 github stars · SKILL.md body (9,210 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-18T18:54:50.317Z","embedding":null,"createdAt":"2026-05-04T19:05:09.040Z","updatedAt":"2026-05-18T18:54:50.317Z","lastSeenAt":"2026-05-18T18:54:50.317Z","tsv":"'0':476,678 '10-intent.md':409 '2':690 '20-checkpoint.md':410 '3':471,482,501,531,680 '90-evidence.md':411 '99-reflection.md':412 'accept':276,451,1037,1100 'achiev':986 'ad':837,973 'adapt':747,1000 'add':600,724,743,816,1193 'adr':404 'aegi':354,361 'allow':1152 'alreadi':339,436,980,1003 'also':313 'ambigu':311 'api':263,945,1219 'approv':194 'ask':164 'async':473,513,669,702,1044 'atom':197,303 'attempt':475,479,481,499,714 'author':435 'autom':904,1132 'avail':370 'await':491,525,684,1047 'backoff':710 'bad':919 'base':840 'baselin':297,405 'baseline-governance.md':403 'bash':619,772,1057,1081 'behavior':195,284,506,540,557,644,740,817,861,874,879,938,1163 'behavior/logic':148 'beyond':731 'block':1133 'blocker':908,1134 'bound':897 'boundari':268,334,450,606,1098 'box':1142 'brainstorm':35,221 'branch':610,749 'broaden':838 'bug':145,1032,1034,1233,1245 'bugfix':11,21 'cannot':902 'catch':686 'chang':65,149,152,159,184,553,835,845,853,862,1118,1190 'check':453,1140 'checkabl':398 'checklist':1094 'checkout':254 'checkpoint':389 'claim':84 'clarif':208 'clean':55,800 'cleanup':176 'clear':340,502,541,935 'code':15,24,50,119,171,216,537,544,660,663,728,791,948,957,1002,1026 'comment':182 'comment-on':181 'compat':267,333,1099 'compet':285 'complex':32,236,309,328,347 'complic':1223 'condit':607 'config':172 'configur':353 'confirm':623,776,1162 'const':477,489,514,1045 'constraint':286 'consum':67,78,856,886 'contract':64,151,266,852 'convert':1161 'core':68,160,604,870 'correct':657 'coupl':1230 'cover':76,581,1130 'coverag':456 'criteria':452,1101 'cross':154,859 'cross-modul':153,858 'current':228,900 'cycl':41,1242 'danger':1181 'data':265,851,1070 'data.email':1073 'debug':752,1231 'decis':419 'defin':1095 'delay':1178 'delet':1007,1025 'demonstr':943 'describ':937 'design':754,1225 'desir':944 'develop':4,107 'diagnosi':180 'didn':124 'differ':1019 'direct':322 'directori':425 'disciplin':191 'doc':175 'docs/aegis':400 'document':1137 'dogmat':1012 'domain':932 'done':86 'downstream':894,1125 'drift':390 'driven':3,106 'duplic':806 'e':687,692 'effect':895 'email':930,1036,1043,1049,1053,1062,1077 'emerg':1147,1169 'empti':1035,1042 'end':562,564,866,868,1160 'end-to-end':561,865 'engin':721 'enough':698 'environ':901 'error':485,519,522,609,627,648,650,695,786,1076 'everi':91,1102 'everyth':1228 'evid':392 'exampl':1031 'except':163,1148 'execut':16,291 'exist':433,454,643,1001 'expect':494,498,528,631,1050,1061 'experi':590 'explain':968 'explor':1145 'exploratori':1149 'exponenti':712 'extract':809,1086 'fact':418 'fail':27,47,98,116,129,445,469,486,615,625,632,656,789,796,820,971,1060,1109,1236 'failur':628 'fallback':746 'featur':9,19,144,552,634,725,824 'field':1090 'file':173,239 'fire':884 'first':29,40,99,113,457,1110,1220 'fix':146,645,649,734,790,797,1033,1244 'flag':952 'floor':593 'flow':249 'fn':672,685,705 'follow':1240 'formal':1167 'formdata':1071 'found':1234 'function':93,670,703,1068 'function/method':1104 'gate':30,102,186 'generat':170 'good':915,918 'got':1064 'green':48,58,85,441,658,767,803,813,1066,1080 'happen':465 'helper':363,810 'high':235,308,346 'high-complex':234,307,345 'highest':588 'highest-risk':587 'hit':75,1124 'hotfix':1170 'hour':1006 'human':166 'identifi':756 'immedi':965 'impact':842 'implement':7,14,17,190,962,1168 'improv':730,807 'incomplet':1183 'index':395 'index.md':402 'init':365 'input':448,1096 'instal':360 'integr':566,863,1232 'intent':331,388,942 'interfac':849 'interface/data':150 'jest.fn':516 'journey':584 'keep':57,811,996,1188 'know':133,1211 'later':974 'lazili':357 'learn':1156 'let':474,676 'lifecycl':255 'linear':711 'logic':69,161,871 'long':289 'long-run':288 'low':327 'low-complex':326 'm':1014 'main':570,583 'mandatori':616,771 'manual':912,981,1135 'manual/visual':279 'maxretri':708 'may':1171 'mean':1024 'medium':232,343 'medium/high':31 'messag':629 'migrat':269 'minim':49,118,460,560,659,920 'minimum':828 'miss':635,1195 'mock':515,527,529,535,546,1227 'mockrejectedvalueonc':517,520 'mockresolvedvalueonc':523 'modul':61,155,158,240,844,847,860 'multipl':238,1089 'must':1226 'name':503,533,542,808,925,936 'narrow':573,1191 'navig':252 'nearest':1205 'necessari':760 'need':314,349,374,429,1092 'never':617,1243 'new':71,92,143,383,484,518,521,551,694,745,878,1103 'new-work':382 'next':819,823,1204 'npm':620,773,1058,1082 'number':709,715 'obscur':946 'observ':556 'old':70,763,873 'onboard':253 'one':275,459,507,539,559,921 'onretri':713 'oper':470,478,493,592 'option':707 'output':449,783,1097,1114 'over-engin':719 'overview':109 'own':437 'owner':245,332,737 'page':241 'partner':167 'pass':53,90,103,121,639,665,700,770,778,782,964,1084,1113 'path':82,258,277,337,393,571,764,869,890,1129 'path/to/test.test.ts':622,775 'permiss':270 'persist':272 'plan':39,210,225,301,319,407,422 'plus':877 'pragmat':1016 'prefer':358,380,558 'preflight':101,185 'priorit':1172 'pristin':784,1115 'proceed':321 'process':376 'produc':66,77,854,885 'product':23,207,215,283 'project':350,417,434 'promis':673,674,706,717 'promot':415 'prototyp':169 'prove':892 'provid':910 'pure':174 'purpos':989 'python':364,381 'qualiti':917 'ran':1119 'ration':975 're':641,652 're-run':651 'read':178,299 'read-on':177 'read-set':298 'readme.md':401 'real':80,505,543,736,888,1127 'reason':1187 'record':351,1185 'recoveri':257 'red':42,440,443,612,951,1038,1056 'red-green-refactor':439 'reduc':1229 'refactor':54,147,162,442,726,799,872,1085 'refer':998 'regress':59,825,839,875,1116,1196 'reject':1041 'relat':62,846,1120 'remain':896 'remov':805 'repair':1176 'repeat':818 'reproduc':911,1238 'request':229 'requir':281,295,538,1054,1063,1078 'result':490,495,1046 'result.error':1051 'retir':765 'retri':468,511 'retryoper':492,526,671,704 'return':487,683,1075 'reusabl':416 'review':317 'right':138 'rippl':73,881,1122 'risk':589 'ritual':995 'root':366,385 'rout':33,206,219,261 'rule':262,605 'run':290,653,829,903 'safe':1175 'scope':826 'screen':242 'servic':243 'set':300 'share':60,157,843 'shared/contract/core':1117 'show':462,941 'signal':74,237,882,1123 'simplest':662 'simplifi':1224 'skill' 'skill-test-driven-development' 'skip':618 'slice':1201,1206 'smallest':1174 'source-ganyuanran' 'spec':406,420 'spec/design':316 'spent':1004 'spike':1150,1159 'spirit':993 'split':926 'start':955,1027,1143 'state':259,447,906 'step':914,1136 'still':781 'stop':217,953 'structur':397 'stuck':1208 'submitform':1048,1069 'substitut':203 'success':488,497,524 'suffici':599 'support':356 'target':831 'task':198,205,294,304,312,348,373 'tdd':100,108,187,306,324,1010,1030,1184,1241 'test':2,28,44,63,72,89,96,105,112,128,136,213,446,455,461,467,504,510,534,567,575,597,602,621,624,638,642,646,647,667,733,774,777,780,788,793,795,812,821,832,848,857,876,880,905,916,928,939,959,960,963,970,972,982,984,1040,1059,1083,1107,1112,1121,1165,1197,1214,1221,1237,1248 'test-driven':104 'test-driven-develop':1 'test1':940 'text':399 'thing':139,508,922 'throw':483,691,693 'throwaway':168,1155 'time':472 'tobe':496,500,1052 'tohavebeencalledtim':530 'topic-add' 'topic-agent-skills' 'topic-ai-agents' 'topic-ai-coding' 'topic-baseline-first' 'topic-claude-code' 'topic-codex' 'topic-coding-agents' 'topic-evidence-driven' 'topic-first-principles' 'topic-opencode' 'topic-software-architecture' 'trail':377 'transit':260 'treat':595 'tri':682 'triag':883 'trim':1074 'typescript':466,509,668,701,1039,1067 'typo':637 'unavoid':548 'unclear':282 'undefin':1065 'unit':574,596,601 'unless':426,547,750 'unreach':696 'use':5,142,352 'user':81,247,555,578,889,1128 'user-observ':554 'user-vis':246,577 'vagu':532 'valid':929,1087 'verif':280,336,913,1093 'verifi':611,766,1055,1079 'visibl':248,579 'void':716 'warn':787 'wast':1009 'watch':45,51,114,126,613,768 'whitespac':934 'whose':330 'wish':1217 'wished-for':1216 'without':25,1246 'work':329,379,384,512,580 'work/yyyy-mm-dd-':408 'workflow':428,755 'workspac':355,362 'write':13,38,43,110,117,212,224,444,458,661,1215,1235 'writing-plan':37,223 'x':1005 'yagni':718","prices":[{"id":"c902fecf-96d3-42ac-a550-4c19f44b5a82","listingId":"fa68cd1c-8fd6-489e-8864-8520a10442c2","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"GanyuanRan","category":"Aegis","install_from":"skills.sh"},"createdAt":"2026-05-04T19:05:09.040Z"}],"sources":[{"listingId":"fa68cd1c-8fd6-489e-8864-8520a10442c2","source":"github","sourceId":"GanyuanRan/Aegis/test-driven-development","sourceUrl":"https://github.com/GanyuanRan/Aegis/tree/main/skills/test-driven-development","isPrimary":false,"firstSeenAt":"2026-05-04T19:05:09.040Z","lastSeenAt":"2026-05-18T18:54:50.317Z"}],"details":{"listingId":"fa68cd1c-8fd6-489e-8864-8520a10442c2","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"GanyuanRan","slug":"test-driven-development","github":{"repo":"GanyuanRan/Aegis","stars":262,"topics":["add","agent-skills","ai-agents","ai-coding","architecture-driven-development","baseline-first","claude-code","codex","coding-agents","evidence-driven","first-principles","opencode","software-architecture","tdd","tlref"],"license":"mit","html_url":"https://github.com/GanyuanRan/Aegis","pushed_at":"2026-05-18T11:05:01Z","description":"Make AI coding agents architecture-aware: baseline-first, evidence-verified, drift-checked, and safe across long tasks.","skill_md_sha":"36aeabd6596231e630a386ca0df8c4aaab12effc","skill_md_path":"skills/test-driven-development/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/GanyuanRan/Aegis/tree/main/skills/test-driven-development"},"layout":"multi","source":"github","category":"Aegis","frontmatter":{"name":"test-driven-development","description":"Use when implementing any feature or bugfix, before writing implementation code"},"skills_sh_url":"https://skills.sh/GanyuanRan/Aegis/test-driven-development"},"updatedAt":"2026-05-18T18:54:50.317Z"}}