universal-dev-standards 5.1.1 → 5.3.0

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 (65) hide show
  1. package/bundled/ai/options/push/single-owner-mode.ai.yaml +60 -0
  2. package/bundled/ai/options/push/team-mode.ai.yaml +64 -0
  3. package/bundled/ai/options/release/publish-mode-github-actions.ai.yaml +65 -0
  4. package/bundled/ai/standards/agent-behavior-discipline.ai.yaml +142 -0
  5. package/bundled/ai/standards/cd-deployment-strategies.ai.yaml +73 -0
  6. package/bundled/ai/standards/no-cicd-deployment.ai.yaml +134 -0
  7. package/bundled/ai/standards/pipeline-security-gates.ai.yaml +71 -0
  8. package/bundled/ai/standards/push-standards.ai.yaml +105 -0
  9. package/bundled/ai/standards/rollback-standards.ai.yaml +68 -0
  10. package/bundled/core/agent-behavior-discipline.md +178 -0
  11. package/bundled/core/cd-deployment-strategies.md +121 -0
  12. package/bundled/core/no-cicd-deployment.md +205 -0
  13. package/bundled/core/pipeline-security-gates.md +109 -0
  14. package/bundled/core/rollback-standards.md +104 -0
  15. package/bundled/core/versioning.md +1 -1
  16. package/bundled/locales/zh-CN/CHANGELOG.md +34 -3
  17. package/bundled/locales/zh-CN/README.md +54 -7
  18. package/bundled/locales/zh-CN/SECURITY.md +8 -0
  19. package/bundled/locales/zh-CN/core/ai-friendly-architecture.md +8 -0
  20. package/bundled/locales/zh-CN/core/workflow-enforcement.md +8 -0
  21. package/bundled/locales/zh-CN/docs/CHEATSHEET.md +8 -0
  22. package/bundled/locales/zh-CN/docs/CLI-FLOW.md +8 -0
  23. package/bundled/locales/zh-CN/docs/FEATURE-REFERENCE.md +8 -0
  24. package/bundled/locales/zh-CN/docs/STANDARDS-REFERENCE.md +8 -0
  25. package/bundled/locales/zh-CN/skills/commands/requirement.md +8 -0
  26. package/bundled/locales/zh-CN/skills/commands/reverse-bdd.md +8 -0
  27. package/bundled/locales/zh-CN/skills/commands/reverse-sdd.md +8 -0
  28. package/bundled/locales/zh-CN/skills/commands/reverse-tdd.md +8 -0
  29. package/bundled/locales/zh-CN/skills/commands/reverse.md +8 -0
  30. package/bundled/locales/zh-CN/skills/commands/review.md +8 -0
  31. package/bundled/locales/zh-CN/skills/commands/sdd-retro.md +8 -0
  32. package/bundled/locales/zh-CN/skills/commands/sdd.md +8 -0
  33. package/bundled/locales/zh-CN/skills/commands/tdd.md +8 -0
  34. package/bundled/locales/zh-CN/skills/commands/update.md +8 -0
  35. package/bundled/locales/zh-TW/CHANGELOG.md +34 -3
  36. package/bundled/locales/zh-TW/MAINTENANCE.md +17 -6
  37. package/bundled/locales/zh-TW/README.md +53 -6
  38. package/bundled/locales/zh-TW/SECURITY.md +8 -0
  39. package/bundled/locales/zh-TW/adoption/STATIC-DYNAMIC-GUIDE.md +1 -1
  40. package/bundled/locales/zh-TW/core/ai-friendly-architecture.md +8 -0
  41. package/bundled/locales/zh-TW/core/anti-hallucination.md +8 -0
  42. package/bundled/locales/zh-TW/core/git-workflow.md +8 -0
  43. package/bundled/locales/zh-TW/core/refactoring-standards.md +8 -0
  44. package/bundled/locales/zh-TW/core/spec-driven-development.md +8 -0
  45. package/bundled/locales/zh-TW/core/structured-task-definition.md +8 -0
  46. package/bundled/locales/zh-TW/core/test-driven-development.md +8 -0
  47. package/bundled/locales/zh-TW/core/versioning.md +1 -1
  48. package/bundled/locales/zh-TW/core/workflow-enforcement.md +8 -0
  49. package/bundled/locales/zh-TW/core/workflow-state-protocol.md +8 -0
  50. package/bundled/locales/zh-TW/docs/CHEATSHEET.md +8 -0
  51. package/bundled/locales/zh-TW/docs/CLI-FLOW.md +8 -0
  52. package/bundled/locales/zh-TW/docs/FEATURE-REFERENCE.md +8 -0
  53. package/bundled/locales/zh-TW/docs/MIGRATION-V5.md +8 -0
  54. package/bundled/locales/zh-TW/docs/STANDARDS-REFERENCE.md +8 -0
  55. package/bundled/locales/zh-TW/integrations/claude-code/README.md +8 -0
  56. package/bundled/locales/zh-TW/skills/deploy-assistant/SKILL.md +178 -0
  57. package/bundled/skills/deploy-assistant/SKILL.md +183 -0
  58. package/bundled/skills/push/SKILL.md +203 -0
  59. package/package.json +1 -1
  60. package/src/config/ai-agent-paths.js +0 -1
  61. package/standards-registry.json +71 -4
  62. package/bundled/locales/zh-CN/docs/AI-AGENT-ROADMAP.md +0 -410
  63. package/bundled/locales/zh-CN/docs/OPERATION-WORKFLOW.md +0 -1074
  64. package/bundled/locales/zh-TW/docs/AI-AGENT-ROADMAP.md +0 -410
  65. package/bundled/locales/zh-TW/docs/OPERATION-WORKFLOW.md +0 -1074
@@ -0,0 +1,105 @@
1
+ id: push-standards
2
+ meta:
3
+ version: "1.0.0"
4
+ updated: "2026-04-23"
5
+ source: skills/push/SKILL.md
6
+ description: "Git push safety gates, protected branch detection, force-push guardrails, and push receipt audit trail"
7
+
8
+ config:
9
+ protected_branches:
10
+ default: ["main", "master", "release/*", "hotfix/*"]
11
+ description: "Branches requiring explicit confirmation before push"
12
+
13
+ push_gates:
14
+ default: ["lint", "test"]
15
+ optional: ["ac-coverage", "type-check", "security-scan"]
16
+ description: "Quality gates to run before pushing"
17
+
18
+ receipt:
19
+ output:
20
+ default: "console"
21
+ choices: ["console", "file", "both"]
22
+ file_path: "~/.uds/push-history.jsonl"
23
+
24
+ auto_pr:
25
+ default: true
26
+ description: "Prompt to create PR after pushing to non-protected branch"
27
+
28
+ repo_mode:
29
+ default: "team"
30
+ choices: ["team", "single-owner"]
31
+ description: "single-owner skips PR prompts and reduces collaboration guardrails"
32
+
33
+ rules:
34
+ - id: detect-protected-branch
35
+ trigger: "executing /push"
36
+ priority: required
37
+ instruction: |
38
+ Before pushing, detect the target branch name.
39
+ If the target matches any protected_branches pattern:
40
+ 1. Display a warning with the branch name
41
+ 2. Show what commits will be pushed
42
+ 3. Require explicit user confirmation before proceeding
43
+ 4. If user does not confirm, abort without pushing
44
+
45
+ - id: force-push-guardrail
46
+ trigger: "push with --force flag detected"
47
+ priority: required
48
+ instruction: |
49
+ When force push is detected:
50
+ 1. Calculate commits that will be overwritten on remote
51
+ 2. Show the count and authors of overwritten commits
52
+ 3. Require the user to type a confirmation string (e.g., "yes, force push")
53
+ 4. Record force_push: true in the push receipt
54
+
55
+ - id: pre-push-gates
56
+ trigger: "before executing git push"
57
+ priority: required
58
+ instruction: |
59
+ Run all configured push_gates in sequence:
60
+ - lint: run project lint command (from uds.project.yaml or detected)
61
+ - test: run project test command
62
+ If any gate fails: abort push, display which gate failed, suggest fix.
63
+ If --skip-gates flag: run push without gates, mark gates_skipped: true in receipt.
64
+
65
+ - id: push-receipt
66
+ trigger: "after successful push"
67
+ priority: required
68
+ instruction: |
69
+ Output a structured push receipt containing:
70
+ - branch: target branch name
71
+ - commit_sha: HEAD commit SHA (short)
72
+ - gates_passed: list of gates that ran and passed
73
+ - gates_skipped: boolean
74
+ - force_push: boolean
75
+ - timestamp: ISO 8601 format
76
+ If receipt.output includes "file": append to ~/.uds/push-history.jsonl as JSON line.
77
+
78
+ - id: pr-integration
79
+ trigger: "after successful push to non-protected branch"
80
+ priority: suggested
81
+ instruction: |
82
+ If auto_pr is true AND repo_mode is "team":
83
+ Check if an open PR exists for this branch on the remote.
84
+ If no open PR: prompt user whether to run pr-automation-assistant.
85
+ If user confirms: invoke pr-automation-assistant.
86
+ If auto_pr is false OR repo_mode is "single-owner": skip this step.
87
+
88
+ - id: single-owner-mode
89
+ trigger: "repo_mode: single-owner is configured"
90
+ priority: recommended
91
+ instruction: |
92
+ In single-owner mode, skip all collaboration-specific steps:
93
+ - No PR prompts
94
+ - Reduced force-push warnings (still warn, but no confirmation text required)
95
+ Protected branch detection remains active.
96
+
97
+ schema:
98
+ push_receipt:
99
+ branch: string
100
+ commit_sha: string
101
+ gates_passed: "string[]"
102
+ gates_skipped: boolean
103
+ force_push: boolean
104
+ timestamp: "ISO 8601 string"
105
+ target_remote: string
@@ -0,0 +1,68 @@
1
+ # Rollback Standards (AI-Optimized v1)
2
+ # Source: core/rollback-standards.md
3
+
4
+ standard:
5
+ id: rollback-standards
6
+ name: Rollback Standards
7
+ description: Rollback trigger conditions, auto vs manual decisions, and error budget integration
8
+ guidelines:
9
+ - "Define rollback triggers with measurable thresholds — never subjective 'it looks bad'"
10
+ - "Auto-rollback on error rate > 2× baseline sustained 5 minutes"
11
+ - "Assisted rollback when SLO violated but non-critical"
12
+ - "Manual rollback for latency degradation within SLO bounds"
13
+ - "Error budget < 10% automatically escalates assisted to auto-rollback"
14
+ - "Every rollback event must be logged and trigger incident response flow"
15
+
16
+ meta:
17
+ version: "1.0.0"
18
+ updated: "2026-04-26"
19
+ source: core/rollback-standards.md
20
+ parent: deployment-standards.ai.yaml
21
+
22
+ trigger_conditions:
23
+ auto_rollback:
24
+ error_rate: ">2× baseline sustained 5min"
25
+ health_check_failures: "3 consecutive"
26
+ p99_latency: ">5× baseline sustained 3min"
27
+ assisted_rollback:
28
+ slo_violated: "non-critical path"
29
+ error_budget_remaining: "<10%"
30
+ manual_rollback:
31
+ latency_degraded: "within SLO bounds"
32
+ cosmetic_issues: "user-visible but non-functional"
33
+
34
+ severity_matrix:
35
+ P0: {trigger: auto, timeline: "<2min", notify: "all-hands"}
36
+ P1: {trigger: auto, timeline: "<5min", notify: "on-call"}
37
+ P2: {trigger: assisted, timeline: "<15min", notify: "team-lead"}
38
+ P3: {trigger: manual, timeline: "<1hr", notify: "developer"}
39
+
40
+ error_budget_integration:
41
+ threshold: "10% remaining"
42
+ escalation: "assisted → auto"
43
+ incident_event: true
44
+ pause_deploys: "when budget exhausted"
45
+
46
+ rollback_methods:
47
+ blue_green: {time: "<30s", risk: low, prerequisite: "dual-slot infrastructure"}
48
+ feature_flag: {time: "<5s", risk: minimal, prerequisite: "flag system in place"}
49
+ dns_switch: {time: "60-120s", risk: medium, prerequisite: "multi-region setup"}
50
+ code_revert: {time: "minutes", risk: medium, prerequisite: "clean git history"}
51
+ database_restore: {time: "hours", risk: high, prerequisite: "backup verified"}
52
+
53
+ checklist:
54
+ pre_rollback:
55
+ - "Confirm rollback target version is healthy"
56
+ - "Verify database migration is backward compatible"
57
+ - "Notify stakeholders of rollback"
58
+ post_rollback:
59
+ - "Confirm health checks pass at target version"
60
+ - "Write rollback event to deployment log"
61
+ - "Open incident ticket for root cause analysis"
62
+ - "Update error budget tracking"
63
+
64
+ physical_spec:
65
+ type: custom_script
66
+ validator:
67
+ command: "test -f rollback.sh && grep -q 'set -euo pipefail' rollback.sh"
68
+ rule: "rollback_script_configured"
@@ -0,0 +1,178 @@
1
+ # Agent Behavior Discipline
2
+
3
+ > **Language**: English | [繁體中文](../locales/zh-TW/core/agent-behavior-discipline.md)
4
+
5
+ **Version**: 1.0.0
6
+ **Last Updated**: 2026-04-24
7
+ **Applicability**: All AI agent implementations using UDS-compliant harnesses
8
+ **Scope**: universal
9
+ **Industry Standards**: Informed by Karpathy 2026-01 observations + andrej-karpathy-skills (MIT)
10
+
11
+ ---
12
+
13
+ ## Purpose
14
+
15
+ This standard defines four behavioral disciplines for AI agents that elevate performance from "functional" to "excellent". These disciplines address the most common failure modes observed in production LLM coding agents:
16
+
17
+ 1. **Executing on wrong assumptions** — agent proceeds without confirming direction
18
+ 2. **Over-engineering** — agent writes 200 lines when 50 would suffice
19
+ 3. **Scope creep** — agent "helpfully" modifies unrelated code
20
+ 4. **Goalless loops** — agent iterates without a defined stopping condition
21
+
22
+ The disciplines are designed to be stackable with existing UDS standards (`anti-hallucination`, `anti-sycophancy-prompting`, `test-driven-development`) and enforceable at the harness level (DevAP `DisciplineConfig`).
23
+
24
+ ---
25
+
26
+ ## Principle 1: Ask — Surface Assumptions Before Executing
27
+
28
+ ### Rule
29
+
30
+ Before any non-trivial task, explicitly state all assumptions and wait for confirmation.
31
+
32
+ ### When to Apply
33
+
34
+ | Condition | Action |
35
+ |-----------|--------|
36
+ | Ambiguous requirements or multiple valid interpretations | Use Disclosure Format (below) |
37
+ | Confidence score < 0.7 | Pause and ask |
38
+ | Architecture changes or multi-file modifications | Always disclose |
39
+ | Single-file trivial change (confidence ≥ 0.9, < 5 lines) | May skip confirmation |
40
+
41
+ ### Disclosure Format
42
+
43
+ ```
44
+ My assumptions: [explicit list]
45
+ Approach considered: [A] vs [B] — choosing A because [reason]
46
+ If my understanding is incorrect, please redirect before I proceed.
47
+ ```
48
+
49
+ ### Why This Matters
50
+
51
+ Karpathy observed: *"Models make wrong assumptions, don't seek clarification, and are a little too sycophantic."* A wrong direction costs more tokens to undo than the upfront 3-second check would have taken.
52
+
53
+ ---
54
+
55
+ ## Principle 2: Simple — Minimum Code, Nothing Speculative
56
+
57
+ ### Rule
58
+
59
+ Solve with the least code required. Never add unrequested functionality.
60
+
61
+ ### Three Strikes Rule (DRY Threshold)
62
+
63
+ Abstract only when identical logic appears **3 or more times**. A single-use helper is always a premature abstraction.
64
+
65
+ ### DO / DO NOT
66
+
67
+ | DO | DO NOT |
68
+ |----|--------|
69
+ | ✅ Write only what the task requires | ❌ Add features "that might be needed later" |
70
+ | ✅ Rewrite when a significantly shorter solution exists | ❌ Create single-use abstractions |
71
+ | ✅ Inline logic used only once | ❌ Add speculative configuration hooks |
72
+ | ✅ Skip error handling for impossible scenarios | ❌ Add defensive code for internal invariants |
73
+
74
+ ### Why This Matters
75
+
76
+ Karpathy observed: *"It will implement 1000 lines of bloated code, and when challenged, immediately cuts it to 100."* If it can be 50 lines, it should be 50 lines from the start.
77
+
78
+ ---
79
+
80
+ ## Principle 3: Precision — Touch Only What the Task Requires
81
+
82
+ ### Rule
83
+
84
+ Scope modifications to the declared minimum set of files and lines. Clean up only your own mess.
85
+
86
+ ### Scope Declaration Format
87
+
88
+ Before any edit, output:
89
+ ```
90
+ Modifying: [file list]
91
+ Not touching: [related but out-of-scope areas]
92
+ Out-of-scope observation (action deferred): [optional — verbal only, no edit]
93
+ ```
94
+
95
+ ### DO / DO NOT
96
+
97
+ | DO | DO NOT |
98
+ |----|--------|
99
+ | ✅ Match existing local code style | ❌ Improve unrelated code "while I'm here" |
100
+ | ✅ Flag pre-existing issues verbally | ❌ Remove dead code you didn't create |
101
+ | ✅ Remove only imports orphaned by YOUR change | ❌ Rename symbols not in your task scope |
102
+ | ✅ Declare scope before starting | ❌ Format unrelated code to match your preferences |
103
+
104
+ ### Why This Matters
105
+
106
+ Karpathy observed agents that *"alter code it doesn't understand, and then things break"*. Precision prevents untraceable side effects and keeps diffs reviewable.
107
+
108
+ ---
109
+
110
+ ## Principle 4: Test — Define Success Criteria, Loop Until Verified
111
+
112
+ ### Rule
113
+
114
+ Transform every task into a measurable, verifiable success criterion before implementation.
115
+
116
+ ### TDD Flow
117
+
118
+ ```
119
+ Define success criterion → Write failing test (Red) → Implement (Green) → Refactor → Verify
120
+ ```
121
+
122
+ ### Vague Criteria Escalation
123
+
124
+ If the task uses subjective language ("make it better", "improve search quality"):
125
+ > "What specific metric or observable outcome defines success here?"
126
+
127
+ Never proceed with a subjective stopping condition.
128
+
129
+ ### Autonomous Loop Protocol
130
+
131
+ | Parameter | Value |
132
+ |-----------|-------|
133
+ | max_retries | 5 (default; configurable via DisciplineConfig) |
134
+ | Per-iteration logging | Record `failureSource` (see failure-source-taxonomy) |
135
+ | On stuck (same error fingerprint) | Escalate to human with failureSource summary |
136
+
137
+ ### Why This Matters
138
+
139
+ Karpathy's strongest principle: *"LLMs excel at looping toward specific goals — provide success criteria rather than directives."* Without a verifiable goal, an autonomous agent loop has no natural stopping point.
140
+
141
+ ---
142
+
143
+ ## Integration with Other UDS Standards
144
+
145
+ | Standard | Relationship |
146
+ |----------|-------------|
147
+ | `anti-hallucination` | Ask principle: disclose when uncertain rather than guessing |
148
+ | `anti-sycophancy-prompting` | Ask principle: don't assume, push back when warranted |
149
+ | `test-driven-development` | Test principle: TDD is the operational implementation |
150
+ | `change-batching-standards` | Precision principle: scope limits reinforce batching logic |
151
+ | `failure-source-taxonomy` | Test principle: loop protocol uses failureSource taxonomy |
152
+ | `recovery-recipe-registry` | Test principle: max_retries maps to recovery recipe escalation |
153
+
154
+ ---
155
+
156
+ ## Enforcement at Harness Level (DevAP)
157
+
158
+ `DisciplineConfig` in DevAP `src/types.ts`:
159
+
160
+ ```typescript
161
+ interface DisciplineConfig {
162
+ ask_threshold: number; // Confidence below this triggers Ask disclosure (default: 0.6)
163
+ max_loop_retries: number; // Autonomous loop ceiling (default: 5)
164
+ precision_scope: 'strict' | 'relaxed'; // strict = always declare scope
165
+ }
166
+ ```
167
+
168
+ The `assumptionCheckGate()` in `src/orchestrator.ts` evaluates task complexity against `ask_threshold` before dispatching to the agent.
169
+
170
+ ---
171
+
172
+ ## Checklist
173
+
174
+ - [ ] Assumptions stated before execution starts
175
+ - [ ] Code solves the problem with minimum required lines
176
+ - [ ] Only declared-scope files were modified
177
+ - [ ] Success criterion is quantifiable and verified
178
+ - [ ] Autonomous loops have `max_retries` and escalation path defined
@@ -0,0 +1,121 @@
1
+ # CD Deployment Strategies(CD 部署策略)
2
+
3
+ ## 概述
4
+
5
+ 本標準定義四種主要部署策略的選用矩陣:Blue-Green、Canary、Rolling、Recreate。幫助團隊根據流量規模、風險容忍度和基礎設施成本,做出一致且有據可查的策略選擇。
6
+
7
+ ---
8
+
9
+ ## 核心原則
10
+
11
+ - **三維決策**:根據流量規模 × 風險容忍度 × 基礎設施成本選擇策略
12
+ - **禁止直接推產**:任何變更都必須先通過 staging 環境驗證
13
+ - **零停機目標**:除非為內部工具或開發環境,否則應追求零停機部署
14
+
15
+ ---
16
+
17
+ ## 策略選用矩陣
18
+
19
+ | 策略 | 流量規模 | 風險容忍度 | 基礎設施成本 | 停機時間 | 回滾時間 |
20
+ |------|---------|----------|------------|---------|---------|
21
+ | Blue-Green | 高 | 低 | 高 | 零 | < 30 秒 |
22
+ | Canary | 中至高 | 中 | 中 | 零 | < 2 分鐘 |
23
+ | Rolling | 任意 | 中 | 低 | 極少 | 數分鐘 |
24
+ | Recreate | 低 | 高 | 極低 | 數秒至數分鐘 | 數分鐘 |
25
+
26
+ ---
27
+
28
+ ## 各策略詳細說明
29
+
30
+ ### Blue-Green
31
+
32
+ **適用場景**:有狀態服務、資料庫相容性變更、高 SLA API
33
+
34
+ **運作方式**:
35
+ - 維護兩個完全相同的環境(Blue = 現有線上版,Green = 新版本)
36
+ - 完整部署並驗證 Green 環境後,切換 Load Balancer 流量
37
+ - 問題發生時立即切回 Blue
38
+
39
+ **前置條件**:雙環境基礎設施、Load Balancer、健康檢查
40
+
41
+ ---
42
+
43
+ ### Canary
44
+
45
+ **適用場景**:功能驗證、A/B 測試、高風險變更
46
+
47
+ **流量漸進比例**:1% → 5% → 25% → 50% → 100%
48
+
49
+ **運作方式**:
50
+ - 先將少量流量導向新版本
51
+ - 監控指標,符合自動晉升規則則繼續擴大
52
+ - 發現問題立即縮回 0%
53
+
54
+ **前置條件**:流量切分機制、可觀測性、自動晉升規則
55
+
56
+ ---
57
+
58
+ ### Rolling
59
+
60
+ **適用場景**:無狀態服務、標準更新、批次工作者
61
+
62
+ **運作方式**:
63
+ - 依序更新每個實例,更新前進行健康檢查
64
+ - 允許新舊版本短暫共存
65
+ - 資源效率最佳,但回滾需時較長
66
+
67
+ **前置條件**:多個服務實例、健康檢查
68
+
69
+ ---
70
+
71
+ ### Recreate
72
+
73
+ **適用場景**:開發/測試環境、內部工具、單一實例服務
74
+
75
+ **運作方式**:
76
+ - 停止所有現有實例,部署新版本,重新啟動
77
+ - 最簡單,但有停機時間
78
+
79
+ **前置條件**:無(最低門檻)
80
+
81
+ ---
82
+
83
+ ## 決策樹
84
+
85
+ ```
86
+ Q1: 需要零停機時間?
87
+ → 否 → Recreate
88
+ → 是 → Q2
89
+
90
+ Q2: 流量 > 10k req/min?
91
+ → 是 → Q3(Blue-Green 或 Canary)
92
+ → 否 → Rolling
93
+
94
+ Q3: 變更屬於高風險?
95
+ → 是 → Canary
96
+ → 否 → Q4
97
+
98
+ Q4: 基礎設施預算有限?
99
+ → 是 → Rolling
100
+ → 否 → Blue-Green
101
+ ```
102
+
103
+ ---
104
+
105
+ ## 無 CI/CD 環境的替代做法
106
+
107
+ | 策略 | 替代方案 |
108
+ |------|---------|
109
+ | Blue-Green | 參見 no-cicd-deployment.ai.yaml 的 Shell Script 實作 |
110
+ | Canary | 使用 Nginx `split_clients` 或 HAProxy 做流量切分 |
111
+ | Rolling | 使用順序式 rsync + 健康檢查迴圈 |
112
+ | Recreate | 最簡單 — 停止、部署、啟動 |
113
+
114
+ ---
115
+
116
+ ## 相關標準
117
+
118
+ - [deployment-standards.md](deployment-standards.md) — 部署基礎原則
119
+ - [rollback-standards.md](rollback-standards.md) — 回滾觸發條件矩陣
120
+ - [no-cicd-deployment.md](no-cicd-deployment.md) — 無 CI/CD 部署策略
121
+ - AI 格式:[../ai/standards/cd-deployment-strategies.ai.yaml](../ai/standards/cd-deployment-strategies.ai.yaml)
@@ -0,0 +1,205 @@
1
+ # No-CI/CD Deployment Strategy
2
+
3
+ > **補充**: 本文件補充 `deployment-standards.md`,專注於無 CI/CD 平台(GitHub Actions / GitLab CI)環境下的可靠部署設計。
4
+
5
+ ## 核心三層架構
6
+
7
+ ```
8
+ Layer 1: 防止錯誤部署
9
+ └─ set -euo pipefail、版本 tag 強制、deploy.lock
10
+
11
+ Layer 2: 驗證部署正確
12
+ └─ Smoke Test、健康檢查、版本號比對、自動 rollback
13
+
14
+ Layer 3: 快速回復能力
15
+ └─ Blue-Green 切換、< 30 秒 rollback
16
+ ```
17
+
18
+ ## Layer 1:防止錯誤部署
19
+
20
+ ### Shell 腳本強制執行
21
+
22
+ 所有部署腳本必須以下列標頭開始:
23
+
24
+ ```bash
25
+ #!/usr/bin/env bash
26
+ set -euo pipefail
27
+ ```
28
+
29
+ - `set -e`:任何命令失敗立即退出
30
+ - `set -u`:引用未定義變數視為錯誤
31
+ - `set -o pipefail`:管線中任何命令失敗都會傳播錯誤
32
+
33
+ ### 強制部署順序
34
+
35
+ ```bash
36
+ echo "[1/4] 執行測試..."
37
+ npm test
38
+
39
+ echo "[2/4] 建置產物..."
40
+ npm run build
41
+
42
+ echo "[3/4] 推送到伺服器..."
43
+ rsync -avz --delete ./dist/ user@server:/app/
44
+
45
+ echo "[4/4] 驗證部署..."
46
+ ./verify.sh || { echo "驗證失敗,執行 rollback..."; ./rollback.sh; exit 1; }
47
+ ```
48
+
49
+ ### deploy.lock 防並發
50
+
51
+ ```bash
52
+ LOCK_FILE="/tmp/deploy.lock"
53
+ trap "rm -f $LOCK_FILE" EXIT
54
+
55
+ if [ -f "$LOCK_FILE" ]; then
56
+ echo "❌ 部署進行中(PID: $(cat $LOCK_FILE)),請等待完成"
57
+ exit 1
58
+ fi
59
+
60
+ echo $$ > "$LOCK_FILE"
61
+ ```
62
+
63
+ ### 版本 Tag 強制
64
+
65
+ ```bash
66
+ CURRENT_TAG=$(git describe --exact-match --tags HEAD 2>/dev/null || echo "")
67
+ if [ -z "$CURRENT_TAG" ]; then
68
+ echo "❌ 當前 commit 沒有版本 tag,請先執行:"
69
+ echo " git tag v$(cat VERSION) && git push --tags"
70
+ exit 1
71
+ fi
72
+ ```
73
+
74
+ ## Layer 2:驗證部署正確
75
+
76
+ ### Smoke Test 腳本 (verify.sh)
77
+
78
+ ```bash
79
+ #!/usr/bin/env bash
80
+ set -euo pipefail
81
+
82
+ HEALTH_URL="${HEALTH_URL:-https://example.com/health}"
83
+ EXPECTED_VERSION=$(cat VERSION)
84
+ MAX_RETRIES=3
85
+ RETRY_INTERVAL=5
86
+
87
+ for i in $(seq 1 $MAX_RETRIES); do
88
+ RESPONSE=$(curl -sf --max-time 10 "$HEALTH_URL" 2>/dev/null) && break
89
+ echo "健康檢查失敗 ($i/$MAX_RETRIES),等待 ${RETRY_INTERVAL}s..."
90
+ sleep $RETRY_INTERVAL
91
+ done
92
+
93
+ ACTUAL_VERSION=$(echo "$RESPONSE" | python3 -c "import json,sys; print(json.load(sys.stdin)['version'])")
94
+
95
+ if [ "$ACTUAL_VERSION" != "$EXPECTED_VERSION" ]; then
96
+ echo "❌ 版本不符!預期 $EXPECTED_VERSION,實際 $ACTUAL_VERSION"
97
+ exit 1
98
+ fi
99
+
100
+ echo "✅ 版本驗證通過:$ACTUAL_VERSION"
101
+ ```
102
+
103
+ ### 健康檢查端點規格
104
+
105
+ 應用程式必須提供 `/health` 端點,回應格式:
106
+
107
+ ```json
108
+ {
109
+ "status": "ok",
110
+ "version": "1.2.3",
111
+ "timestamp": "2026-04-26T10:00:00Z"
112
+ }
113
+ ```
114
+
115
+ ## Layer 3:快速回復能力
116
+
117
+ ### Blue-Green 架構
118
+
119
+ ```
120
+ [Nginx]
121
+
122
+ ├─── Blue (port 3001) ← 穩定版(當前 active)
123
+ └─── Green (port 3002) ← 新版(部署目標)
124
+ ```
125
+
126
+ **Nginx 配置**:
127
+
128
+ ```nginx
129
+ upstream app {
130
+ server 127.0.0.1:3001; # blue
131
+ # server 127.0.0.1:3002; # green(切換時啟用此行並停用上一行)
132
+ }
133
+
134
+ server {
135
+ listen 80;
136
+ location / {
137
+ proxy_pass http://app;
138
+ }
139
+ }
140
+ ```
141
+
142
+ ### Rollback 腳本 (rollback.sh)
143
+
144
+ ```bash
145
+ #!/usr/bin/env bash
146
+ set -euo pipefail
147
+
148
+ CURRENT=$(readlink /app/current)
149
+ if [[ "$CURRENT" == *"green"* ]]; then
150
+ TARGET="/app/blue"
151
+ else
152
+ TARGET="/app/green"
153
+ fi
154
+
155
+ ln -sfn "$TARGET" /app/current
156
+ nginx -s reload
157
+
158
+ echo "✅ 已切回 $TARGET($(date -u +%Y-%m-%dT%H:%M:%SZ))"
159
+
160
+ # 記錄 rollback 事件
161
+ echo "{\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"event\":\"rollback\",\"from\":\"$CURRENT\",\"to\":\"$TARGET\",\"operator\":\"$(whoami)\"}" >> /var/log/deployments.jsonl
162
+ ```
163
+
164
+ ### 完整 Makefile
165
+
166
+ ```makefile
167
+ .PHONY: deploy rollback verify
168
+
169
+ deploy:
170
+ @./deploy.sh
171
+
172
+ rollback:
173
+ @./rollback.sh
174
+
175
+ verify:
176
+ @./verify.sh
177
+
178
+ status:
179
+ @echo "Current: $$(readlink /app/current)"
180
+ @curl -s $${HEALTH_URL:-http://localhost/health} | python3 -m json.tool
181
+ ```
182
+
183
+ ## Deployment Log 格式
184
+
185
+ 每次部署(成功或失敗)都必須寫入 JSON Lines 格式的日誌:
186
+
187
+ ```json
188
+ {"timestamp":"2026-04-26T10:00:00Z","version":"1.2.3","git_commit":"abc1234","operator":"albert","result":"success","duration_seconds":45,"slot":"green"}
189
+ {"timestamp":"2026-04-26T11:30:00Z","version":"1.2.4","git_commit":"def5678","operator":"albert","result":"failure","duration_seconds":12,"slot":"green","error":"version_mismatch"}
190
+ ```
191
+
192
+ ## 適用場景
193
+
194
+ | 場景 | 建議 |
195
+ |------|------|
196
+ | 個人 VPS / 小型專案 | Layer 1 + Layer 2(無需 Blue-Green) |
197
+ | 自架伺服器(多人團隊) | 三層全套 + deploy.lock |
198
+ | Air-gapped 環境 | 三層全套 + 本地 artifact registry |
199
+ | 容器化部署 | 搭配 `docker compose` 執行 |
200
+
201
+ ## 相關標準
202
+
203
+ - `deployment-standards.ai.yaml` — 有 CI/CD 平台的部署策略(本文件的補充前提)
204
+ - `health-check-standards.ai.yaml` — /health 端點設計規範
205
+ - `circuit-breaker.ai.yaml` — 斷路器整合(進階場景)