@umacloud/knowledge 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (418) hide show
  1. package/00-governance/governance-capabilities.md +557 -0
  2. package/00-governance/knowledge-map.md +39 -0
  3. package/00-governance/maintenance-policy.md +76 -0
  4. package/00-governance/review-checklist.md +81 -0
  5. package/README.md +13 -0
  6. package/ai/01-standards/agent-development-complete.md +691 -0
  7. package/ai/01-standards/llm-application-complete.md +488 -0
  8. package/ai/01-standards/mlops-complete.md +798 -0
  9. package/ai/01-standards/prompt-engineering-complete.md +646 -0
  10. package/ai/01-standards/rag-architecture-complete.md +649 -0
  11. package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
  12. package/ai/03-checklists/ai-project-checklist.md +215 -0
  13. package/ai/04-antipatterns/ai-antipatterns.md +661 -0
  14. package/ai/05-cases/case-rag-production.md +147 -0
  15. package/ai/06-glossary/ai-glossary.md +162 -0
  16. package/ai/agent-evaluation-benchmark.md +53 -0
  17. package/ai/ai-agent-memory-context-management.md +41 -0
  18. package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
  19. package/ai/ai-data-security-and-compliance-playbook.md +37 -0
  20. package/ai/ai-domain-index-and-checklist.md +40 -0
  21. package/ai/ai-governance-maturity-model.md +50 -0
  22. package/ai/ai-model-selection-and-routing-strategy.md +47 -0
  23. package/ai/ai-observability-and-oncall-runbook.md +52 -0
  24. package/ai/ai-rag-engineering-playbook.md +42 -0
  25. package/ai/ai-red-team-and-safety-evaluation.md +42 -0
  26. package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
  27. package/ai/llm-agent-engineering-deep-dive.md +57 -0
  28. package/ai/prompt-and-tool-guardrails.md +52 -0
  29. package/api/01-standards/enterprise-api-standards.md +198 -0
  30. package/api/01-standards/rest-api-design-guide.md +63 -0
  31. package/api/02-playbooks/api-pagination-playbook.md +93 -0
  32. package/api/02-playbooks/graphql-production-playbook.md +176 -0
  33. package/api/03-checklists/api-review-checklist.md +55 -0
  34. package/api/04-antipatterns/api-antipatterns.md +112 -0
  35. package/architecture/01-standards/api-gateway-patterns.md +496 -0
  36. package/architecture/01-standards/cloud-native-patterns.md +644 -0
  37. package/architecture/01-standards/distributed-systems-patterns.md +591 -0
  38. package/architecture/01-standards/event-driven-architecture.md +595 -0
  39. package/architecture/01-standards/microservices-patterns-complete.md +968 -0
  40. package/architecture/01-standards/microservices-patterns.md +495 -0
  41. package/architecture/01-standards/system-design-interview.md +664 -0
  42. package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
  43. package/architecture/02-playbooks/migration-playbook.md +780 -0
  44. package/architecture/02-playbooks/system-design-playbook.md +779 -0
  45. package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
  46. package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
  47. package/architecture/05-cases/case-netflix-microservices.md +413 -0
  48. package/architecture/06-glossary/architecture-glossary.md +164 -0
  49. package/architecture/adr-template-and-examples.md +38 -0
  50. package/architecture/api-gateway-deep-dive.md +1291 -0
  51. package/architecture/configuration-management.md +1162 -0
  52. package/architecture/distributed-transactions.md +1220 -0
  53. package/architecture/microservices-complete.md +735 -0
  54. package/architecture/resilience-and-disaster-patterns.md +37 -0
  55. package/architecture/service-governance.md +1198 -0
  56. package/architecture/system-architecture-deep-dive.md +37 -0
  57. package/backend/01-standards/analytics-and-growth.md +65 -0
  58. package/backend/01-standards/api-and-error-conventions.md +120 -0
  59. package/backend/01-standards/application-layering-and-packaging.md +160 -0
  60. package/backend/01-standards/auth-implementation.md +104 -0
  61. package/backend/01-standards/backend-framework-idioms.md +74 -0
  62. package/backend/01-standards/background-jobs-and-async.md +66 -0
  63. package/backend/01-standards/caching-strategies-complete.md +390 -0
  64. package/backend/01-standards/config-and-observability.md +77 -0
  65. package/backend/01-standards/data-modeling-and-persistence.md +94 -0
  66. package/backend/01-standards/django-complete.md +1765 -0
  67. package/backend/01-standards/email-and-notifications.md +64 -0
  68. package/backend/01-standards/fastapi-complete.md +925 -0
  69. package/backend/01-standards/file-upload-and-storage.md +66 -0
  70. package/backend/01-standards/graphql-api-complete.md +416 -0
  71. package/backend/01-standards/llm-application-standard.md +78 -0
  72. package/backend/01-standards/message-queue-patterns.md +379 -0
  73. package/backend/01-standards/microservices-and-distributed.md +78 -0
  74. package/backend/01-standards/nestjs-complete.md +2167 -0
  75. package/backend/01-standards/payment-integration.md +80 -0
  76. package/backend/01-standards/rate-limiting-complete.md +451 -0
  77. package/backend/01-standards/realtime-and-websocket.md +65 -0
  78. package/backend/01-standards/search-and-filtering.md +64 -0
  79. package/backend/01-standards/spring-boot-complete.md +445 -0
  80. package/backend/02-playbooks/api-design-playbook.md +718 -0
  81. package/backend/02-playbooks/email-send-playbook.md +130 -0
  82. package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
  83. package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
  84. package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
  85. package/backend/03-checklists/api-launch-checklist.md +189 -0
  86. package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
  87. package/blockchain/01-standards/blockchain-basics.md +557 -0
  88. package/blockchain/01-standards/smart-contract-development.md +1315 -0
  89. package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
  90. package/cicd/01-standards/github-actions-complete.md +473 -0
  91. package/cicd/01-standards/release-and-store-submission.md +75 -0
  92. package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
  93. package/cicd/02-playbooks/release-management-playbook.md +605 -0
  94. package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
  95. package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
  96. package/cicd/05-cases/case-deployment-automation.md +221 -0
  97. package/cicd/05-cases/case-gitops-transformation.md +212 -0
  98. package/cicd/06-glossary/cicd-glossary.md +114 -0
  99. package/cicd/cicd-blueprint-deep-dive.md +38 -0
  100. package/cicd/release-readiness-gate.md +37 -0
  101. package/cloud-native/01-standards/container-security.md +741 -0
  102. package/cloud-native/01-standards/kubernetes-complete.md +812 -0
  103. package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
  104. package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
  105. package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
  106. package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
  107. package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
  108. package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
  109. package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
  110. package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
  111. package/cloud-native/03-checklists/container-security-checklist.md +431 -0
  112. package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
  113. package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
  114. package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
  115. package/cloud-native/05-cases/case-k8s-migration.md +478 -0
  116. package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
  117. package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
  118. package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
  119. package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
  120. package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
  121. package/data/01-standards/elasticsearch-complete.md +2098 -0
  122. package/data/01-standards/postgresql-complete.md +1613 -0
  123. package/data/01-standards/redis-complete.md +1527 -0
  124. package/data/02-playbooks/database-optimization-playbook.md +403 -0
  125. package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
  126. package/data/03-checklists/database-launch-checklist.md +187 -0
  127. package/data/04-antipatterns/database-antipatterns.md +873 -0
  128. package/data/05-cases/case-database-migration.md +310 -0
  129. package/data/06-glossary/database-glossary.md +440 -0
  130. package/data/data-governance-and-modeling-deep-dive.md +39 -0
  131. package/data-engineering/01-standards/airflow-complete.md +523 -0
  132. package/data-engineering/01-standards/kafka-complete.md +1521 -0
  133. package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
  134. package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
  135. package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
  136. package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
  137. package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
  138. package/database/01-standards/database-schema-standards.md +147 -0
  139. package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
  140. package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
  141. package/database/02-playbooks/postgresql-production-playbook.md +146 -0
  142. package/database/02-playbooks/redis-caching-playbook.md +117 -0
  143. package/database/03-checklists/database-review-checklist.md +50 -0
  144. package/database/04-antipatterns/database-antipatterns.md +112 -0
  145. package/design/01-standards/ui-design-system-complete.md +423 -0
  146. package/design/02-playbooks/design-handoff-playbook.md +254 -0
  147. package/design/02-playbooks/design-review-playbook.md +388 -0
  148. package/design/03-checklists/design-review-checklist.md +246 -0
  149. package/design/04-antipatterns/design-antipatterns.md +378 -0
  150. package/design/05-cases/case-design-system-adoption.md +328 -0
  151. package/design/06-glossary/design-glossary.md +329 -0
  152. package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
  153. package/design/ux-system-deep-dive.md +38 -0
  154. package/design-systems/00-craft-rules.md +71 -0
  155. package/design-systems/aesthetic-families.md +43 -0
  156. package/design-systems/anti-ai-slop.md +162 -0
  157. package/design-systems/bold-geometric.md +120 -0
  158. package/design-systems/brutalist-bold.md +103 -0
  159. package/design-systems/editorial-clean.md +109 -0
  160. package/design-systems/glass-aurora.md +108 -0
  161. package/design-systems/modern-minimal.md +145 -0
  162. package/design-systems/premium-luxury.md +106 -0
  163. package/design-systems/product-type-design-map.md +48 -0
  164. package/design-systems/soft-warm.md +123 -0
  165. package/design-systems/tech-utility.md +113 -0
  166. package/desktop/01-standards/desktop-app-standard.md +72 -0
  167. package/desktop/01-standards/desktop-design.md +71 -0
  168. package/development/00-governance/document-template.md +41 -0
  169. package/development/01-standards/api-versioning-strategies.md +432 -0
  170. package/development/01-standards/authentication-patterns-complete.md +479 -0
  171. package/development/01-standards/css-architecture-complete.md +550 -0
  172. package/development/01-standards/database-migration-strategies.md +484 -0
  173. package/development/01-standards/elasticsearch-complete.md +347 -0
  174. package/development/01-standards/git-complete.md +371 -0
  175. package/development/01-standards/golang-complete.md +1565 -0
  176. package/development/01-standards/graphql-complete.md +298 -0
  177. package/development/01-standards/javascript-bundlers-complete.md +469 -0
  178. package/development/01-standards/javascript-typescript-complete.md +528 -0
  179. package/development/01-standards/jest-complete.md +275 -0
  180. package/development/01-standards/linux-complete.md +234 -0
  181. package/development/01-standards/logging-observability-complete.md +526 -0
  182. package/development/01-standards/microservices-communication.md +502 -0
  183. package/development/01-standards/mongodb-complete.md +406 -0
  184. package/development/01-standards/oauth2-complete.md +285 -0
  185. package/development/01-standards/performance-optimization-complete.md +289 -0
  186. package/development/01-standards/playwright-complete.md +247 -0
  187. package/development/01-standards/postgresql-complete.md +456 -0
  188. package/development/01-standards/pytest-complete.md +340 -0
  189. package/development/01-standards/python-async-programming.md +902 -0
  190. package/development/01-standards/python-complete.md +956 -0
  191. package/development/01-standards/python-decorators-complete.md +799 -0
  192. package/development/01-standards/python-design-patterns.md +2854 -0
  193. package/development/01-standards/python-packaging-distribution.md +420 -0
  194. package/development/01-standards/python-testing-strategies.md +607 -0
  195. package/development/01-standards/python-web-frameworks-comparison.md +471 -0
  196. package/development/01-standards/redis-complete.md +317 -0
  197. package/development/01-standards/rest-api-complete.md +316 -0
  198. package/development/01-standards/rust-complete.md +578 -0
  199. package/development/01-standards/typescript-advanced-types.md +1513 -0
  200. package/development/01-standards/web-security-complete.md +292 -0
  201. package/development/02-playbooks/api-design-playbook.md +810 -0
  202. package/development/02-playbooks/database-migration-playbook.md +580 -0
  203. package/development/02-playbooks/debugging-playbook.md +692 -0
  204. package/development/02-playbooks/feature-delivery-playbook.md +430 -0
  205. package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
  206. package/development/02-playbooks/performance-optimization-playbook.md +531 -0
  207. package/development/02-playbooks/performance-tuning-playbook.md +652 -0
  208. package/development/02-playbooks/refactor-playbook.md +403 -0
  209. package/development/02-playbooks/release-playbook.md +469 -0
  210. package/development/03-checklists/architecture-review-checklist.md +168 -0
  211. package/development/03-checklists/data-migration-checklist.md +157 -0
  212. package/development/03-checklists/oncall-handover-checklist.md +173 -0
  213. package/development/03-checklists/pr-checklist.md +158 -0
  214. package/development/03-checklists/production-readiness-checklist.md +190 -0
  215. package/development/03-checklists/release-readiness-checklist.md +154 -0
  216. package/development/03-checklists/security-review-checklist.md +182 -0
  217. package/development/04-antipatterns/api-antipatterns.md +657 -0
  218. package/development/04-antipatterns/architecture-antipatterns.md +686 -0
  219. package/development/04-antipatterns/backend-antipatterns.md +648 -0
  220. package/development/04-antipatterns/cicd-antipatterns.md +540 -0
  221. package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
  222. package/development/04-antipatterns/data-antipatterns.md +658 -0
  223. package/development/04-antipatterns/database-antipatterns.md +578 -0
  224. package/development/04-antipatterns/frontend-antipatterns.md +635 -0
  225. package/development/04-antipatterns/reliability-antipatterns.md +700 -0
  226. package/development/04-antipatterns/security-antipatterns.md +747 -0
  227. package/development/05-cases/case-api-version-migration.md +428 -0
  228. package/development/05-cases/case-authorization-hardening.md +383 -0
  229. package/development/05-cases/case-bluegreen-rollback.md +466 -0
  230. package/development/05-cases/case-cache-snowball-protection.md +485 -0
  231. package/development/05-cases/case-ci-cd-pipeline.md +544 -0
  232. package/development/05-cases/case-database-scaling.md +500 -0
  233. package/development/05-cases/case-db-hotspot-optimization.md +487 -0
  234. package/development/05-cases/case-incident-mttr-reduction.md +563 -0
  235. package/development/05-cases/case-microservice-migration.md +375 -0
  236. package/development/05-cases/case-performance-optimization.md +406 -0
  237. package/development/05-cases/case-security-incident-response.md +345 -0
  238. package/development/06-glossary/full-stack-glossary.md +166 -0
  239. package/development/09-maturity/quarterly-audit-template.md +35 -0
  240. package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
  241. package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
  242. package/development/12-scenarios/development-scenarios-guide.md +565 -0
  243. package/development/13-implementation-assets/implementation-toolkit.md +282 -0
  244. package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
  245. package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
  246. package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
  247. package/development/api-contract-and-versioning-guide.md +36 -0
  248. package/development/api-governance-complete.md +43 -0
  249. package/development/backend-engineering-complete.md +43 -0
  250. package/development/code-review-quality-complete.md +43 -0
  251. package/development/concurrency-reliability-complete.md +43 -0
  252. package/development/database-engineering-complete.md +43 -0
  253. package/development/engineering-effectiveness-complete.md +43 -0
  254. package/development/engineering-standards-deep-dive.md +38 -0
  255. package/development/frontend-engineering-complete.md +43 -0
  256. package/development/performance-capacity-complete.md +43 -0
  257. package/development/refactor-migration-complete.md +42 -0
  258. package/development/refactoring-and-techdebt-playbook.md +37 -0
  259. package/development/security-in-development-complete.md +43 -0
  260. package/devops/01-standards/cicd-pipeline-complete.md +262 -0
  261. package/devops/01-standards/docker-complete.md +1490 -0
  262. package/devops/01-standards/github-actions-complete.md +337 -0
  263. package/devops/01-standards/kubernetes-complete.md +638 -0
  264. package/devops/01-standards/terraform-complete.md +2117 -0
  265. package/devops/02-playbooks/docker-compose-playbook.md +233 -0
  266. package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
  267. package/devops/02-playbooks/docker-production-playbook.md +952 -0
  268. package/edge-iot/01-standards/edge-iot-complete.md +473 -0
  269. package/experts/architect/api-design.md +178 -0
  270. package/experts/architect/methodology.md +124 -0
  271. package/experts/architect/security.md +75 -0
  272. package/experts/backend-lead/methodology.md +216 -0
  273. package/experts/devops/methodology.md +160 -0
  274. package/experts/frontend-lead/methodology.md +178 -0
  275. package/experts/product-manager/industry/ecommerce.md +43 -0
  276. package/experts/product-manager/industry/saas.md +40 -0
  277. package/experts/product-manager/methodology.md +97 -0
  278. package/experts/qa-lead/methodology.md +123 -0
  279. package/experts/qa-lead/test-strategy.md +128 -0
  280. package/experts/uiux-designer/methodology.md +125 -0
  281. package/frontend/01-standards/accessibility-complete.md +532 -0
  282. package/frontend/01-standards/accessibility-standard.md +74 -0
  283. package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
  284. package/frontend/01-standards/design-tokens-complete.md +444 -0
  285. package/frontend/01-standards/forms-and-validation.md +77 -0
  286. package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
  287. package/frontend/01-standards/i18n-and-localization.md +65 -0
  288. package/frontend/01-standards/nextjs-complete.md +451 -0
  289. package/frontend/01-standards/react-complete.md +713 -0
  290. package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
  291. package/frontend/01-standards/react-hooks-complete.md +1171 -0
  292. package/frontend/01-standards/seo-and-web-vitals.md +77 -0
  293. package/frontend/01-standards/state-management-complete.md +444 -0
  294. package/frontend/01-standards/vue-complete.md +499 -0
  295. package/frontend/01-standards/vue3-complete.md +2002 -0
  296. package/frontend/01-standards/web-framework-best-practices.md +64 -0
  297. package/frontend/01-standards/web-performance-complete.md +495 -0
  298. package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
  299. package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
  300. package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
  301. package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
  302. package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
  303. package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
  304. package/frontend/03-checklists/component-quality-checklist.md +166 -0
  305. package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
  306. package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
  307. package/frontend/05-cases/case-performance-optimization.md +274 -0
  308. package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
  309. package/harmony/01-standards/harmonyos-design.md +65 -0
  310. package/high-quality-engineering-playbook.md +54 -0
  311. package/incident/01-standards/incident-response-complete.md +303 -0
  312. package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
  313. package/incident/02-playbooks/postmortem-playbook.md +398 -0
  314. package/incident/03-checklists/incident-readiness-checklist.md +181 -0
  315. package/incident/04-antipatterns/incident-antipatterns.md +490 -0
  316. package/incident/05-cases/case-cascade-failure.md +176 -0
  317. package/incident/06-glossary/incident-glossary.md +114 -0
  318. package/incident/postmortem-and-response-deep-dive.md +39 -0
  319. package/industries/ecommerce/ecommerce-complete.md +631 -0
  320. package/industries/education/education-complete.md +555 -0
  321. package/industries/fintech/fintech-complete.md +501 -0
  322. package/industries/gaming/gaming-complete.md +587 -0
  323. package/industries/healthcare/healthcare-complete.md +452 -0
  324. package/low-code/01-standards/low-code-complete.md +944 -0
  325. package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
  326. package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
  327. package/miniprogram/01-standards/miniprogram-design.md +61 -0
  328. package/miniprogram/01-standards/miniprogram-standard.md +81 -0
  329. package/mobile/01-standards/android-material-design.md +70 -0
  330. package/mobile/01-standards/flutter-complete.md +384 -0
  331. package/mobile/01-standards/ios-design-hig.md +78 -0
  332. package/mobile/01-standards/mobile-app-standard.md +85 -0
  333. package/mobile/01-standards/react-native-complete.md +352 -0
  334. package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
  335. package/mobile/02-playbooks/mobile-performance.md +473 -0
  336. package/mobile/03-checklists/mobile-release-checklist.md +234 -0
  337. package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
  338. package/mobile/05-cases/case-app-performance.md +500 -0
  339. package/mobile/05-cases/case-app-startup-optimization.md +218 -0
  340. package/mobile/06-glossary/mobile-glossary.md +484 -0
  341. package/observability/01-standards/observability-standards.md +103 -0
  342. package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
  343. package/observability/02-playbooks/structured-logging-playbook.md +73 -0
  344. package/observability/03-checklists/observability-checklist.md +54 -0
  345. package/observability/04-antipatterns/observability-antipatterns.md +106 -0
  346. package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
  347. package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
  348. package/operations/03-checklists/production-launch-checklist.md +365 -0
  349. package/operations/04-antipatterns/operations-antipatterns.md +664 -0
  350. package/operations/05-cases/case-sre-practices.md +581 -0
  351. package/operations/06-glossary/operations-glossary.md +120 -0
  352. package/operations/aiops-anomaly-detection.md +758 -0
  353. package/operations/capacity-planning.md +1061 -0
  354. package/operations/chaos-engineering.md +659 -0
  355. package/operations/incident-command-system.md +38 -0
  356. package/operations/observability-complete.md +442 -0
  357. package/operations/slo-sli-playbook.md +517 -0
  358. package/operations/sre-operations-deep-dive.md +39 -0
  359. package/package.json +8 -0
  360. package/performance/01-standards/performance-and-scalability.md +80 -0
  361. package/performance/01-standards/performance-standards.md +156 -0
  362. package/performance/02-playbooks/query-optimization-playbook.md +103 -0
  363. package/performance/03-checklists/performance-checklist.md +56 -0
  364. package/performance/04-antipatterns/performance-antipatterns.md +146 -0
  365. package/product/01-standards/product-management-complete.md +285 -0
  366. package/product/02-playbooks/feature-launch-playbook.md +207 -0
  367. package/product/02-playbooks/user-research-playbook.md +532 -0
  368. package/product/03-checklists/feature-launch-checklist.md +275 -0
  369. package/product/04-antipatterns/product-antipatterns.md +355 -0
  370. package/product/05-cases/case-mvp-to-scale.md +384 -0
  371. package/product/06-glossary/product-glossary.md +462 -0
  372. package/product/feature-prioritization-framework.md +40 -0
  373. package/product/kpi-and-metric-tree.md +37 -0
  374. package/product/product-discovery-and-prd-deep-dive.md +41 -0
  375. package/quantum/01-standards/quantum-complete.md +1186 -0
  376. package/security/01-standards/api-security-complete.md +511 -0
  377. package/security/01-standards/container-runtime-security.md +574 -0
  378. package/security/01-standards/data-protection-gdpr.md +543 -0
  379. package/security/01-standards/owasp-top10-complete.md +1890 -0
  380. package/security/01-standards/secure-coding-baseline.md +90 -0
  381. package/security/01-standards/supply-chain-security.md +441 -0
  382. package/security/01-standards/web-security-checklist.md +108 -0
  383. package/security/01-standards/zero-trust-architecture.md +521 -0
  384. package/security/02-playbooks/auth-sso-playbook.md +166 -0
  385. package/security/02-playbooks/incident-response-security-playbook.md +588 -0
  386. package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
  387. package/security/02-playbooks/payment-integration-playbook.md +119 -0
  388. package/security/02-playbooks/penetration-testing-playbook.md +517 -0
  389. package/security/03-checklists/security-audit-checklist.md +356 -0
  390. package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
  391. package/security/05-cases/case-log4shell-incident.md +537 -0
  392. package/security/05-cases/case-major-breaches.md +468 -0
  393. package/security/06-glossary/security-glossary.md +212 -0
  394. package/security/compliance-automation.md +993 -0
  395. package/security/container-security.md +680 -0
  396. package/security/devsecops-complete.md +426 -0
  397. package/security/sast-dast-sca.md +775 -0
  398. package/security/secrets-management.md +594 -0
  399. package/security/security-architecture-deep-dive.md +37 -0
  400. package/security/threat-modeling-stride-playbook.md +40 -0
  401. package/seed-templates/auth-system.md +59 -0
  402. package/seed-templates/blog-content.md +94 -0
  403. package/seed-templates/dashboard.md +89 -0
  404. package/seed-templates/docs-site.md +73 -0
  405. package/seed-templates/e-commerce.md +50 -0
  406. package/seed-templates/saas-landing.md +92 -0
  407. package/seed-templates/settings-page.md +51 -0
  408. package/testing/01-standards/test-strategy-and-layering.md +83 -0
  409. package/testing/01-standards/testing-strategy-complete.md +422 -0
  410. package/testing/01-standards/unit-testing-best-practices.md +118 -0
  411. package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
  412. package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
  413. package/testing/03-checklists/test-strategy-checklist.md +208 -0
  414. package/testing/04-antipatterns/testing-antipatterns.md +718 -0
  415. package/testing/05-cases/case-testing-transformation.md +300 -0
  416. package/testing/06-glossary/testing-glossary.md +110 -0
  417. package/testing/risk-based-test-matrix.md +36 -0
  418. package/testing/testing-strategy-deep-dive.md +37 -0
@@ -0,0 +1,691 @@
1
+ ---
2
+ id: agent-development-complete
3
+ title: Agent 开发完整指南
4
+ domain: ai
5
+ category: 01-standards
6
+ difficulty: intermediate
7
+ tags: [agent, ai, complete, development, memory, multi-agent, react, tool]
8
+ quality_score: 70
9
+ last_updated: 2026-06-15
10
+ ---
11
+ # Agent 开发完整指南
12
+
13
+ ## 概述
14
+
15
+ AI Agent 是能自主规划、使用工具并完成复杂任务的 LLM 应用。本指南覆盖 ReAct 框架、Tool Use、Multi-Agent 协作、Memory 管理、Planning 策略及安全防护,适用于构建生产级 Agent 系统。
16
+
17
+ ### Agent 系统架构
18
+
19
+ ```
20
+ Agent 核心架构:
21
+ ├── 感知层 (Perception)
22
+ │ ├── 用户输入解析
23
+ │ ├── 环境状态读取
24
+ │ └── 工具输出解析
25
+ ├── 推理层 (Reasoning)
26
+ │ ├── 任务规划 (Planning)
27
+ │ ├── 决策 (Decision Making)
28
+ │ └── 反思 (Reflection)
29
+ ├── 行动层 (Action)
30
+ │ ├── 工具调用 (Tool Use)
31
+ │ ├── 代码执行
32
+ │ └── API 调用
33
+ ├── 记忆层 (Memory)
34
+ │ ├── 短期记忆 (对话上下文)
35
+ │ ├── 工作记忆 (当前任务状态)
36
+ │ └── 长期记忆 (知识库/向量存储)
37
+ └── 安全层 (Safety)
38
+ ├── 权限管控
39
+ ├── 操作审计
40
+ └── 熔断降级
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 1. ReAct 框架
46
+
47
+ ### 1.1 ReAct 核心循环
48
+
49
+ ```
50
+ ReAct 循环: Thought -> Action -> Observation -> Thought -> ...
51
+
52
+ Thought: 分析当前状态,决定下一步行动
53
+ Action: 选择并执行工具调用
54
+ Observation: 获取工具输出结果
55
+ Repeat: 直到任务完成或达到最大步数
56
+ ```
57
+
58
+ ### 1.2 ReAct 实现
59
+
60
+ ```python
61
+ from anthropic import Anthropic
62
+ import json
63
+
64
+ class ReActAgent:
65
+ """基于 ReAct 框架的 Agent 实现。"""
66
+
67
+ def __init__(self, tools: dict, max_steps: int = 10):
68
+ self.client = Anthropic()
69
+ self.tools = tools
70
+ self.max_steps = max_steps
71
+ self.trajectory: list[dict] = []
72
+
73
+ def run(self, task: str) -> str:
74
+ """执行 ReAct 循环直到任务完成。"""
75
+ messages = [{"role": "user", "content": task}]
76
+
77
+ tool_definitions = [
78
+ {
79
+ "name": name,
80
+ "description": tool["description"],
81
+ "input_schema": tool["schema"],
82
+ }
83
+ for name, tool in self.tools.items()
84
+ ]
85
+
86
+ for step in range(self.max_steps):
87
+ response = self.client.messages.create(
88
+ model="claude-sonnet-4-5-20250929",
89
+ max_tokens=4096,
90
+ system=self._system_prompt(),
91
+ tools=tool_definitions,
92
+ messages=messages,
93
+ )
94
+
95
+ # 记录轨迹
96
+ self.trajectory.append({
97
+ "step": step,
98
+ "stop_reason": response.stop_reason,
99
+ "content": [b.model_dump() for b in response.content],
100
+ })
101
+
102
+ # 任务完成
103
+ if response.stop_reason == "end_turn":
104
+ return self._extract_final_answer(response)
105
+
106
+ # 处理工具调用
107
+ if response.stop_reason == "tool_use":
108
+ messages.append({"role": "assistant", "content": response.content})
109
+ tool_results = self._execute_tools(response.content)
110
+ messages.append({"role": "user", "content": tool_results})
111
+
112
+ return "达到最大步数限制,任务未完成"
113
+
114
+ def _execute_tools(self, content) -> list[dict]:
115
+ """执行所有工具调用并返回结果。"""
116
+ results = []
117
+ for block in content:
118
+ if block.type == "tool_use":
119
+ tool_name = block.name
120
+ tool_input = block.input
121
+ try:
122
+ output = self.tools[tool_name]["function"](**tool_input)
123
+ results.append({
124
+ "type": "tool_result",
125
+ "tool_use_id": block.id,
126
+ "content": str(output),
127
+ })
128
+ except Exception as e:
129
+ results.append({
130
+ "type": "tool_result",
131
+ "tool_use_id": block.id,
132
+ "content": f"错误: {e}",
133
+ "is_error": True,
134
+ })
135
+ return results
136
+
137
+ def _system_prompt(self) -> str:
138
+ return """你是一个能使用工具完成任务的 Agent。
139
+
140
+ 规则:
141
+ 1. 每次行动前先思考 (Thought) 再决定行动 (Action)
142
+ 2. 仔细观察工具输出 (Observation) 再决定下一步
143
+ 3. 不确定时优先请求更多信息
144
+ 4. 任务完成时给出明确的最终答案
145
+ 5. 遇到错误时分析原因并尝试替代方案"""
146
+
147
+ def _extract_final_answer(self, response) -> str:
148
+ for block in response.content:
149
+ if hasattr(block, "text"):
150
+ return block.text
151
+ return ""
152
+ ```
153
+
154
+ ---
155
+
156
+ ## 2. Tool Use
157
+
158
+ ### 2.1 工具定义规范
159
+
160
+ ```python
161
+ TOOL_REGISTRY = {
162
+ "search_codebase": {
163
+ "description": "在代码库中搜索文件或代码片段",
164
+ "schema": {
165
+ "type": "object",
166
+ "properties": {
167
+ "query": {
168
+ "type": "string",
169
+ "description": "搜索关键词或正则表达式",
170
+ },
171
+ "file_pattern": {
172
+ "type": "string",
173
+ "description": "文件名 glob 模式,如 '*.py'",
174
+ },
175
+ "max_results": {
176
+ "type": "integer",
177
+ "description": "最大返回结果数",
178
+ "default": 10,
179
+ },
180
+ },
181
+ "required": ["query"],
182
+ },
183
+ "function": search_codebase_impl,
184
+ "permissions": ["read"],
185
+ "risk_level": "low",
186
+ },
187
+ "execute_command": {
188
+ "description": "执行 Shell 命令",
189
+ "schema": {
190
+ "type": "object",
191
+ "properties": {
192
+ "command": {"type": "string", "description": "要执行的命令"},
193
+ "timeout": {"type": "integer", "default": 30},
194
+ },
195
+ "required": ["command"],
196
+ },
197
+ "function": execute_command_impl,
198
+ "permissions": ["read", "execute"],
199
+ "risk_level": "high",
200
+ "requires_confirmation": True,
201
+ },
202
+ }
203
+ ```
204
+
205
+ ### 2.2 工具安全封装
206
+
207
+ ```python
208
+ class SafeToolExecutor:
209
+ """带权限控制和审计日志的工具执行器。"""
210
+
211
+ BLOCKED_COMMANDS = [
212
+ "rm -rf /", "mkfs", "dd if=", "> /dev/",
213
+ "chmod 777", "curl | bash", "wget | sh",
214
+ ]
215
+
216
+ def __init__(self, allowed_permissions: set[str],
217
+ audit_logger=None):
218
+ self.permissions = allowed_permissions
219
+ self.audit = audit_logger
220
+
221
+ def execute(self, tool_name: str, tool_def: dict,
222
+ inputs: dict, context: dict) -> dict:
223
+ """安全执行工具调用。"""
224
+ # 权限检查
225
+ required = set(tool_def.get("permissions", []))
226
+ if not required.issubset(self.permissions):
227
+ return {
228
+ "error": f"权限不足: 需要 {required - self.permissions}",
229
+ "blocked": True,
230
+ }
231
+
232
+ # 危险命令检查
233
+ if tool_name == "execute_command":
234
+ cmd = inputs.get("command", "")
235
+ for pattern in self.BLOCKED_COMMANDS:
236
+ if pattern in cmd:
237
+ return {"error": f"命令被拦截: 匹配危险模式 '{pattern}'"}
238
+
239
+ # 高风险操作需要确认
240
+ if tool_def.get("requires_confirmation"):
241
+ if not context.get("user_confirmed"):
242
+ return {
243
+ "needs_confirmation": True,
244
+ "message": f"高风险操作: {tool_name}({inputs}),请确认执行",
245
+ }
246
+
247
+ # 执行并记录审计日志
248
+ try:
249
+ result = tool_def["function"](**inputs)
250
+ if self.audit:
251
+ self.audit.log(
252
+ tool=tool_name, inputs=inputs,
253
+ result="success", context=context,
254
+ )
255
+ return {"result": result}
256
+ except Exception as e:
257
+ if self.audit:
258
+ self.audit.log(
259
+ tool=tool_name, inputs=inputs,
260
+ result=f"error: {e}", context=context,
261
+ )
262
+ return {"error": str(e)}
263
+ ```
264
+
265
+ ---
266
+
267
+ ## 3. Multi-Agent 协作
268
+
269
+ ### 3.1 协作模式
270
+
271
+ ```
272
+ Multi-Agent 模式:
273
+ ├── 顺序流水线 — Agent A 输出交给 Agent B 处理
274
+ ├── 并行扇出 — 多个 Agent 同时处理不同子任务
275
+ ├── 辩论对抗 — Agent 互相评审产出共识
276
+ ├── 层级委派 — 主 Agent 分配子任务给专家 Agent
277
+ └── 黑板模型 — 所有 Agent 共享状态黑板协作
278
+ ```
279
+
280
+ ### 3.2 层级委派实现
281
+
282
+ ```python
283
+ class OrchestratorAgent:
284
+ """主控 Agent: 分析任务、分配给专家 Agent、综合结果。"""
285
+
286
+ def __init__(self):
287
+ self.experts: dict[str, ReActAgent] = {}
288
+
289
+ def register_expert(self, role: str, agent: ReActAgent):
290
+ self.experts[role] = agent
291
+
292
+ def execute(self, task: str) -> dict:
293
+ # 步骤 1: 任务分解
294
+ subtasks = self._decompose(task)
295
+
296
+ # 步骤 2: 分配并执行
297
+ results = {}
298
+ for subtask in subtasks:
299
+ role = subtask["assigned_to"]
300
+ if role in self.experts:
301
+ results[role] = self.experts[role].run(subtask["description"])
302
+
303
+ # 步骤 3: 综合结果
304
+ synthesis = self._synthesize(task, results)
305
+ return {"subtasks": subtasks, "results": results, "synthesis": synthesis}
306
+
307
+ def _decompose(self, task: str) -> list[dict]:
308
+ """使用 LLM 将任务分解为子任务并分配角色。"""
309
+ prompt = f"""将以下任务分解为子任务,并分配给合适的专家:
310
+
311
+ 可用专家: {list(self.experts.keys())}
312
+
313
+ 任务: {task}
314
+
315
+ 输出 JSON:
316
+ ```json
317
+ [
318
+ {{"description": "子任务描述", "assigned_to": "专家角色", "priority": 1}}
319
+ ]
320
+ ```"""
321
+ response = client.messages.create(
322
+ model="claude-sonnet-4-5-20250929",
323
+ messages=[{"role": "user", "content": prompt}],
324
+ max_tokens=2048,
325
+ )
326
+ return json.loads(extract_json(response.content[0].text))
327
+
328
+ def _synthesize(self, task: str, results: dict) -> str:
329
+ prompt = f"""综合以下专家的分析结果,给出最终结论。
330
+
331
+ 原始任务: {task}
332
+
333
+ 专家结果:
334
+ {json.dumps(results, ensure_ascii=False, indent=2)}
335
+
336
+ 请给出:
337
+ 1. 综合结论
338
+ 2. 各专家结论的共识点
339
+ 3. 存在分歧的点及推荐意见"""
340
+ response = client.messages.create(
341
+ model="claude-sonnet-4-5-20250929",
342
+ messages=[{"role": "user", "content": prompt}],
343
+ max_tokens=4096,
344
+ )
345
+ return response.content[0].text
346
+ ```
347
+
348
+ ### 3.3 Agent 间通信协议
349
+
350
+ ```python
351
+ from dataclasses import dataclass, field
352
+ from enum import Enum
353
+ from datetime import datetime
354
+
355
+ class MessageType(Enum):
356
+ TASK = "task"
357
+ RESULT = "result"
358
+ QUERY = "query"
359
+ FEEDBACK = "feedback"
360
+ STATUS = "status"
361
+
362
+ @dataclass
363
+ class AgentMessage:
364
+ """Agent 间标准消息格式。"""
365
+ sender: str
366
+ receiver: str
367
+ msg_type: MessageType
368
+ content: dict
369
+ correlation_id: str
370
+ timestamp: datetime = field(default_factory=datetime.utcnow)
371
+ priority: int = 0
372
+
373
+ class MessageBus:
374
+ """Agent 消息总线。"""
375
+
376
+ def __init__(self):
377
+ self._queues: dict[str, list[AgentMessage]] = {}
378
+ self._handlers: dict[str, callable] = {}
379
+
380
+ def register(self, agent_id: str, handler: callable):
381
+ self._queues[agent_id] = []
382
+ self._handlers[agent_id] = handler
383
+
384
+ def send(self, message: AgentMessage):
385
+ receiver = message.receiver
386
+ if receiver in self._queues:
387
+ self._queues[receiver].append(message)
388
+ self._handlers[receiver](message)
389
+
390
+ def broadcast(self, sender: str, msg_type: MessageType, content: dict):
391
+ for agent_id in self._queues:
392
+ if agent_id != sender:
393
+ self.send(AgentMessage(
394
+ sender=sender, receiver=agent_id,
395
+ msg_type=msg_type, content=content,
396
+ correlation_id=str(uuid.uuid4()),
397
+ ))
398
+ ```
399
+
400
+ ---
401
+
402
+ ## 4. Memory 管理
403
+
404
+ ### 4.1 三级记忆架构
405
+
406
+ ```python
407
+ class AgentMemory:
408
+ """三级记忆系统: 短期 + 工作 + 长期。"""
409
+
410
+ def __init__(self, vector_store, max_short_term: int = 20):
411
+ self.short_term: list[dict] = [] # 最近对话轮次
412
+ self.working: dict = {} # 当前任务状态
413
+ self.vector_store = vector_store # 长期向量记忆
414
+ self.max_short_term = max_short_term
415
+
416
+ def add_interaction(self, role: str, content: str):
417
+ """添加到短期记忆,超出限制时压缩转存长期记忆。"""
418
+ self.short_term.append({"role": role, "content": content})
419
+ if len(self.short_term) > self.max_short_term:
420
+ self._compress_and_archive()
421
+
422
+ def update_working(self, key: str, value):
423
+ """更新工作记忆 (当前任务状态)。"""
424
+ self.working[key] = value
425
+
426
+ def recall(self, query: str, top_k: int = 5) -> list[dict]:
427
+ """从长期记忆中检索相关信息。"""
428
+ return self.vector_store.search(
429
+ collection="agent_memory",
430
+ query_vector=get_embedding(query),
431
+ top_k=top_k,
432
+ )
433
+
434
+ def _compress_and_archive(self):
435
+ """压缩早期对话并存入长期记忆。"""
436
+ to_archive = self.short_term[:10]
437
+ self.short_term = self.short_term[10:]
438
+
439
+ summary = self._summarize(to_archive)
440
+ self.vector_store.upsert("agent_memory", [{
441
+ "text": summary,
442
+ "embedding": get_embedding(summary),
443
+ "metadata": {"type": "conversation_summary",
444
+ "timestamp": datetime.utcnow().isoformat()},
445
+ }])
446
+
447
+ def _summarize(self, messages: list[dict]) -> str:
448
+ text = "\n".join(f"{m['role']}: {m['content']}" for m in messages)
449
+ response = client.messages.create(
450
+ model="claude-sonnet-4-5-20250929",
451
+ messages=[{"role": "user",
452
+ "content": f"简洁总结以下对话的关键信息:\n{text}"}],
453
+ max_tokens=512,
454
+ )
455
+ return response.content[0].text
456
+
457
+ def get_context(self, query: str) -> str:
458
+ """构建完整上下文: 工作记忆 + 短期记忆 + 长期检索。"""
459
+ parts = []
460
+
461
+ if self.working:
462
+ parts.append(f"当前任务状态:\n{json.dumps(self.working, ensure_ascii=False)}")
463
+
464
+ if self.short_term:
465
+ recent = self.short_term[-5:]
466
+ parts.append("最近对话:\n" + "\n".join(
467
+ f"{m['role']}: {m['content'][:200]}" for m in recent
468
+ ))
469
+
470
+ long_term = self.recall(query, top_k=3)
471
+ if long_term:
472
+ parts.append("相关历史:\n" + "\n".join(
473
+ d["text"][:200] for d in long_term
474
+ ))
475
+
476
+ return "\n\n---\n\n".join(parts)
477
+ ```
478
+
479
+ ---
480
+
481
+ ## 5. Planning 策略
482
+
483
+ ### 5.1 Plan-and-Execute
484
+
485
+ ```python
486
+ class PlanAndExecuteAgent:
487
+ """先规划再执行的 Agent 模式。"""
488
+
489
+ def __init__(self, executor: ReActAgent):
490
+ self.executor = executor
491
+
492
+ def run(self, task: str) -> dict:
493
+ # 阶段 1: 生成计划
494
+ plan = self._create_plan(task)
495
+
496
+ # 阶段 2: 逐步执行
497
+ results = []
498
+ for i, step in enumerate(plan["steps"]):
499
+ result = self.executor.run(step["action"])
500
+ results.append({"step": step, "result": result})
501
+
502
+ # 阶段 3: 执行后反思并调整计划
503
+ if self._needs_replan(step, result, plan["steps"][i+1:]):
504
+ remaining = self._replan(task, results, plan["steps"][i+1:])
505
+ plan["steps"] = plan["steps"][:i+1] + remaining
506
+
507
+ return {"plan": plan, "results": results}
508
+
509
+ def _create_plan(self, task: str) -> dict:
510
+ prompt = f"""为以下任务创建详细的执行计划。
511
+
512
+ 任务: {task}
513
+
514
+ 输出 JSON:
515
+ ```json
516
+ {{
517
+ "goal": "任务目标",
518
+ "steps": [
519
+ {{"id": 1, "action": "具体步骤", "expected_output": "预期结果", "dependencies": []}}
520
+ ],
521
+ "success_criteria": ["完成标准"]
522
+ }}
523
+ ```"""
524
+ response = client.messages.create(
525
+ model="claude-sonnet-4-5-20250929",
526
+ messages=[{"role": "user", "content": prompt}],
527
+ max_tokens=2048,
528
+ )
529
+ return json.loads(extract_json(response.content[0].text))
530
+
531
+ def _needs_replan(self, step: dict, result: str,
532
+ remaining: list) -> bool:
533
+ """判断是否需要调整后续计划。"""
534
+ prompt = f"""评估执行结果是否需要调整后续计划。
535
+
536
+ 已执行步骤: {step['action']}
537
+ 实际结果: {result}
538
+ 预期结果: {step['expected_output']}
539
+ 剩余步骤: {json.dumps(remaining, ensure_ascii=False)}
540
+
541
+ 只回答 YES 或 NO。"""
542
+ response = client.messages.create(
543
+ model="claude-sonnet-4-5-20250929",
544
+ messages=[{"role": "user", "content": prompt}],
545
+ max_tokens=10,
546
+ )
547
+ return "YES" in response.content[0].text.upper()
548
+
549
+ def _replan(self, task: str, completed: list, remaining: list) -> list:
550
+ """根据已完成结果重新规划剩余步骤。"""
551
+ prompt = f"""根据已完成的步骤和结果,调整剩余计划。
552
+
553
+ 任务: {task}
554
+ 已完成: {json.dumps(completed, ensure_ascii=False)}
555
+ 原剩余计划: {json.dumps(remaining, ensure_ascii=False)}
556
+
557
+ 输出调整后的剩余步骤 (JSON 数组)。"""
558
+ response = client.messages.create(
559
+ model="claude-sonnet-4-5-20250929",
560
+ messages=[{"role": "user", "content": prompt}],
561
+ max_tokens=2048,
562
+ )
563
+ return json.loads(extract_json(response.content[0].text))
564
+ ```
565
+
566
+ ---
567
+
568
+ ## 6. 安全防护
569
+
570
+ ### 6.1 权限与沙箱
571
+
572
+ ```python
573
+ class AgentSandbox:
574
+ """Agent 执行沙箱: 限制文件访问、网络和资源。"""
575
+
576
+ def __init__(self, config: dict):
577
+ self.allowed_paths: list[str] = config.get("allowed_paths", [])
578
+ self.allowed_domains: list[str] = config.get("allowed_domains", [])
579
+ self.max_execution_time: int = config.get("max_execution_time", 300)
580
+ self.max_memory_mb: int = config.get("max_memory_mb", 512)
581
+ self.max_tool_calls: int = config.get("max_tool_calls", 50)
582
+ self._tool_call_count = 0
583
+
584
+ def check_file_access(self, path: str) -> bool:
585
+ """检查文件路径是否在白名单内。"""
586
+ from pathlib import Path
587
+ resolved = str(Path(path).resolve())
588
+ return any(resolved.startswith(p) for p in self.allowed_paths)
589
+
590
+ def check_network_access(self, url: str) -> bool:
591
+ """检查 URL 域名是否在白名单内。"""
592
+ from urllib.parse import urlparse
593
+ domain = urlparse(url).hostname or ""
594
+ return any(domain.endswith(d) for d in self.allowed_domains)
595
+
596
+ def check_tool_limit(self) -> bool:
597
+ """检查工具调用次数是否超限。"""
598
+ self._tool_call_count += 1
599
+ return self._tool_call_count <= self.max_tool_calls
600
+ ```
601
+
602
+ ### 6.2 操作审计
603
+
604
+ ```python
605
+ class AgentAuditLog:
606
+ """Agent 操作审计日志。"""
607
+
608
+ def __init__(self, storage):
609
+ self.storage = storage
610
+
611
+ def log(self, **kwargs):
612
+ entry = {
613
+ "timestamp": datetime.utcnow().isoformat(),
614
+ "agent_id": kwargs.get("agent_id"),
615
+ "action": kwargs.get("tool"),
616
+ "inputs_summary": self._redact(kwargs.get("inputs", {})),
617
+ "result_status": kwargs.get("result", "unknown"),
618
+ "session_id": kwargs.get("context", {}).get("session_id"),
619
+ }
620
+ self.storage.insert(entry)
621
+
622
+ def _redact(self, inputs: dict) -> dict:
623
+ """脱敏: 移除密码、密钥等敏感字段。"""
624
+ sensitive_keys = {"password", "token", "secret", "api_key", "credential"}
625
+ return {
626
+ k: "***REDACTED***" if k.lower() in sensitive_keys else v
627
+ for k, v in inputs.items()
628
+ }
629
+ ```
630
+
631
+ ### 6.3 熔断降级
632
+
633
+ ```python
634
+ class AgentCircuitBreaker:
635
+ """Agent 熔断器: 连续失败时自动降级。"""
636
+
637
+ def __init__(self, failure_threshold: int = 3,
638
+ recovery_timeout: int = 60):
639
+ self.failure_threshold = failure_threshold
640
+ self.recovery_timeout = recovery_timeout
641
+ self.failure_count = 0
642
+ self.state = "closed" # closed / open / half-open
643
+ self.last_failure_time = None
644
+
645
+ def call(self, func, *args, **kwargs):
646
+ if self.state == "open":
647
+ if self._should_attempt_recovery():
648
+ self.state = "half-open"
649
+ else:
650
+ raise RuntimeError("Agent 熔断中,请稍后重试")
651
+
652
+ try:
653
+ result = func(*args, **kwargs)
654
+ self._on_success()
655
+ return result
656
+ except Exception as e:
657
+ self._on_failure()
658
+ raise
659
+
660
+ def _on_success(self):
661
+ self.failure_count = 0
662
+ self.state = "closed"
663
+
664
+ def _on_failure(self):
665
+ self.failure_count += 1
666
+ self.last_failure_time = time.monotonic()
667
+ if self.failure_count >= self.failure_threshold:
668
+ self.state = "open"
669
+
670
+ def _should_attempt_recovery(self) -> bool:
671
+ if self.last_failure_time is None:
672
+ return True
673
+ return (time.monotonic() - self.last_failure_time) > self.recovery_timeout
674
+ ```
675
+
676
+ ---
677
+
678
+ ## Agent Checklist
679
+
680
+ - [ ] Agent 使用 ReAct 框架,每步有显式 Thought-Action-Observation 记录
681
+ - [ ] 工具定义包含 description、schema、permissions 和 risk_level
682
+ - [ ] 高风险工具 (写入/删除/执行) 有二次确认和审计日志
683
+ - [ ] 危险命令有黑名单拦截,文件操作有路径白名单
684
+ - [ ] Multi-Agent 有明确的通信协议和角色分工
685
+ - [ ] Memory 系统实现短期/工作/长期三级架构
686
+ - [ ] 长期记忆有压缩归档策略,避免 Token 溢出
687
+ - [ ] Planning 支持执行后反思和动态重新规划
688
+ - [ ] 沙箱限制文件访问、网络访问和资源使用
689
+ - [ ] 工具调用次数有上限,连续失败有熔断降级
690
+ - [ ] 所有操作有审计日志,敏感信息自动脱敏
691
+ - [ ] Agent 轨迹 (trajectory) 完整保存,可回溯调试