@routinecrew/routinecode 2.31.86 → 2.31.88

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 (90) hide show
  1. package/bin/cli.sh +10 -0
  2. package/bin/prompt-vault.dat +1 -1
  3. package/bin/rc-login.js +5 -4
  4. package/bin/rc-savings.js +808 -0
  5. package/bin/rc-skills.js +1 -1
  6. package/bin/rc-suggestions.js +100 -0
  7. package/bin/rc-team.js +1 -1
  8. package/hooks/hooks-config.json +9 -0
  9. package/hooks/lib/attest_reader.py +16 -1
  10. package/hooks/lib/calibration.json +89 -0
  11. package/hooks/lib/card_gate.py +735 -0
  12. package/hooks/lib/cc-surface.json +1 -1
  13. package/hooks/lib/command_fix.py +209 -0
  14. package/hooks/lib/delegate_nudge.py +179 -0
  15. package/hooks/lib/deploy_suggest.py +312 -0
  16. package/hooks/lib/design_pick_nudge.py +86 -0
  17. package/hooks/lib/emit_raw.py +4 -0
  18. package/hooks/lib/i18n.py +48 -20
  19. package/hooks/lib/knowledge_items.py +189 -19
  20. package/hooks/lib/knowledge_stock.py +604 -0
  21. package/hooks/lib/ops_guard.py +549 -0
  22. package/hooks/lib/prices.json +8 -0
  23. package/hooks/lib/route_ledger.py +622 -0
  24. package/hooks/lib/route_rules.json +88 -0
  25. package/hooks/lib/savings_emit.py +93 -0
  26. package/hooks/lib/secret_filter.py +11 -0
  27. package/hooks/lib/sync_manager.py +4 -1
  28. package/hooks/post-bash-verify.sh +14 -0
  29. package/hooks/post-edit-track.sh +9 -0
  30. package/hooks/pre-agent-spawn.mjs +1 -1
  31. package/hooks/pre-agent-spawn.sh +34 -2
  32. package/hooks/pre-bash-guard.sh +22 -0
  33. package/hooks/pre-bash-knowledge.sh +12 -2
  34. package/hooks/pre-credit-guard.sh +1 -1
  35. package/hooks/pre-edit-delegate.sh +15 -0
  36. package/hooks/pre-edit-guard.sh +10 -0
  37. package/hooks/pre-mark-complete.sh +54 -12
  38. package/hooks/pre-read-guard.sh +10 -0
  39. package/hooks/session-start.sh +15 -10
  40. package/hooks/stop-usage-metrics.sh +6 -0
  41. package/hooks/subagent-stop-usage.sh +36 -4
  42. package/hooks/user-prompt-submit.sh +9 -0
  43. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  44. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  45. package/mcp-plan-manager/dist/file-ops.js +1 -1
  46. package/mcp-routinecode/dist/criteria-card.js +1 -0
  47. package/mcp-routinecode/dist/design-judge.js +1 -0
  48. package/mcp-routinecode/dist/edit-tracker.js +1 -1
  49. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  50. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  51. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  52. package/mcp-routinecode/dist/index.js +1 -1
  53. package/mcp-routinecode/dist/known-solutions.js +1 -1
  54. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  55. package/mcp-routinecode/dist/normalize-sig.js +1 -1
  56. package/mcp-routinecode/dist/observed-draft.js +1 -1
  57. package/mcp-routinecode/dist/observed-escalation.js +1 -1
  58. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  59. package/mcp-routinecode/dist/route-match.js +1 -1
  60. package/mcp-routinecode/dist/routines.js +1 -1
  61. package/mcp-routinecode/dist/rule-engine.js +1 -1
  62. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  63. package/mcp-routinecode/dist/session-registry.js +1 -1
  64. package/mcp-routinecode/dist/skill-pack/sync.js +40 -14
  65. package/mcp-routinecode/dist/test-runner.js +1 -1
  66. package/mcp-routinecode/dist/thinking-judge.js +1 -0
  67. package/mcp-routinecode/dist/verification.js +1 -1
  68. package/package.json +1 -1
  69. package/plugin/.claude-plugin/plugin.json +1 -1
  70. package/plugin/agents/analyzer.md.sealed +1 -1
  71. package/plugin/agents/architect.md.sealed +1 -1
  72. package/plugin/agents/crawler.md.sealed +1 -1
  73. package/plugin/agents/explorer.md.sealed +1 -1
  74. package/plugin/agents/implementor-lite.md.sealed +1 -0
  75. package/plugin/agents/implementor.md.sealed +1 -1
  76. package/plugin/agents/looker.md.sealed +1 -1
  77. package/plugin/agents/ops-lite.md.sealed +1 -0
  78. package/plugin/agents/planner.md.sealed +1 -1
  79. package/plugin/agents/recorder.md.sealed +1 -1
  80. package/plugin/agents/reviewer.md.sealed +1 -1
  81. package/plugin/agents/runner-lite.md.sealed +1 -0
  82. package/plugin/agents/verifier.md.sealed +1 -1
  83. package/plugin/commands/analyze.md.sealed +1 -1
  84. package/plugin/commands/plan.md.sealed +1 -1
  85. package/plugin/commands/rc.md.sealed +1 -1
  86. package/plugin/commands/receipt.md.sealed +1 -1
  87. package/plugin/commands/recharge.md.sealed +1 -1
  88. package/plugin/commands/routines.md.sealed +1 -1
  89. package/plugin/commands/share.md.sealed +1 -1
  90. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -0,0 +1,312 @@
1
+ """배포 성공 직후 geo 무료 AI 노출 진단 안내 1줄 (설계 35c W5 · 플로우 13).
2
+
3
+ post-bash-verify.sh 가 Bash 결과를 볼 때 호출한다. 배포 명령이 성공했고 처음 보는 공개 도메인이면
4
+ 사용자에게만 보이는 systemMessage 1줄을 돌려준다(additionalContext 에는 넣지 않는다 — AI 맥락에 들어가면 안 됨).
5
+
6
+ 판정 순서(어느 하나라도 걸리면 None):
7
+ 1. 명령이 배포 명령인가: vercel --prod / vercel deploy --prod, netlify deploy --prod, fly deploy,
8
+ railway up, firebase deploy, wrangler deploy · wrangler pages deploy.
9
+ (--prod 없는 vercel 은 미리보기이므로 제외)
10
+ 2. 환경변수 CI 가 설정됐는가 → 제외
11
+ 3. 대화형 세션인가: CLAUDE_CODE_SESSION_ATTENDED=1 일 때만 (훅은 stdin·stdout 이 파이프라 TTY 판별 불가)
12
+ 4. 실패 신호가 있는가(exit_code != 0 또는 출력에 error/failed/fatal 등) → 제외
13
+ 5. 출력에서 https:// 주소의 호스트를 골랐을 때 공개 호스트인가
14
+ (localhost·사설 IP·*.local·대시보드 호스트·배포 해시 주소 제외)
15
+ 6. ~/.routinecode/config.json 의 suggestions 가 false 가 아닌가
16
+ 7. 이 도메인이 ~/.routinecode/suggested-domains.json 에 아직 없는가
17
+ 8. auth 관문(POST /api/v1/me/suggestions/gate, 1.5초): allow 가 false 면 침묵.
18
+ 토큰 없음·실패·시간 초과는 표시(fail-open).
19
+
20
+ 통과하면 도메인을 기록하고, auth 에 event 'shown' 을 보내고, 줄을 돌려준다.
21
+ 기록은 줄을 돌려주기 직전에만 한다(suggestions off 면 기록도 안 함).
22
+ 모든 실패는 fail-open: 예외가 나면 None.
23
+
24
+ 상태 경로: ROUTINECODE_DIR 또는 ~/.routinecode (rc-privacy 와 같은 규칙). 설정 경로: ROUTINECODE_CONFIG_PATH 또는 <dir>/config.json.
25
+ 사용자 토큰: <dir>/credentials.json 의 accessToken (rc-login 이 저장). auth 주소: AUTH_API_URL → ROUTINECODE_AUTH_URL → 기본값.
26
+ """
27
+
28
+ import html
29
+ import ipaddress
30
+ import json
31
+ import os
32
+ import re
33
+ import urllib.parse
34
+ import urllib.request
35
+
36
+ GEO_START = 'https://geo.routinecrew.net/start?url={domain}&ref=routinecode'
37
+ HINT = ' 이 안내 끄기: routinecode suggestions off'
38
+ GATE_CARD_KEY = 'routinecode.deploy_check'
39
+ GATE_TIMEOUT_S = 1.5
40
+ TITLE_MAX = 80
41
+ DEFAULT_AUTH_URL = 'https://auth.routinecrew.net'
42
+
43
+ DEPLOY_RES = [
44
+ # vercel --prod / vercel deploy --prod (사이 인자는 플래그만 허용 — `vercel env ls --prod` 같은 다른 하위명령 제외)
45
+ re.compile(r'\bvercel(?:\s+deploy)?(?:\s+-{1,2}[^\s;&|]+)*\s+--prod\b'),
46
+ re.compile(r'\bnetlify\s+deploy\b[^\n;&|]*--prod\b'),
47
+ re.compile(r'\bfly\s+deploy\b'),
48
+ re.compile(r'\bflyctl\s+deploy\b'),
49
+ re.compile(r'\brailway\s+up\b'),
50
+ re.compile(r'\bfirebase\s+deploy\b'),
51
+ re.compile(r'\bwrangler\s+(?:pages\s+)?deploy\b'),
52
+ ]
53
+
54
+ URL_RE = re.compile(r'https://([A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?)(?::\d+)?(?=[/?#\s"\'<>)\]\],]|$)')
55
+ HOST_RE = re.compile(r'^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$')
56
+ # 주소 줄 선택 우선순위: 별칭 줄 → 운영 주소 줄 → 그 밖 (vercel 은 해시 미리보기 주소와 별칭 주소를 같이 찍는다)
57
+ ALIAS_LINE_RE = re.compile(r'\baliased\b', re.IGNORECASE)
58
+ PREFER_LINE_RE = re.compile(r'production|deployed|live at|hosting url|project url', re.IGNORECASE)
59
+ ERROR_RE = re.compile(r'\berror\b|\bfailed\b|\bfatal\b|\bERR!|\bexception\b', re.IGNORECASE)
60
+ # 주소가 나와도 배포 대상이 아닌 대시보드·문서 호스트
61
+ DASHBOARD_SUFFIXES = (
62
+ 'vercel.com', 'netlify.com', 'fly.io', 'railway.app', 'cloudflare.com',
63
+ 'firebase.google.com', 'console.cloud.google.com', 'github.com', 'npmjs.com',
64
+ )
65
+ HASH_SEG_RE = re.compile(r'^(?=.*[a-z])(?=.*[0-9])[a-z0-9]{6,12}$')
66
+ PAGES_HASH_RE = re.compile(r'^[a-f0-9]{8}$')
67
+ TITLE_RE = re.compile(r'<title[^>]*>(.*?)</title>', re.IGNORECASE | re.DOTALL)
68
+
69
+
70
+ def rc_dir(env=None):
71
+ env = os.environ if env is None else env
72
+ return env.get('ROUTINECODE_DIR') or os.path.join(os.path.expanduser('~'), '.routinecode')
73
+
74
+
75
+ def config_path(env=None):
76
+ env = os.environ if env is None else env
77
+ return env.get('ROUTINECODE_CONFIG_PATH') or os.path.join(rc_dir(env), 'config.json')
78
+
79
+
80
+ def record_path(env=None):
81
+ return os.path.join(rc_dir(env), 'suggested-domains.json')
82
+
83
+
84
+ def is_deploy_command(command):
85
+ if not isinstance(command, str) or not command:
86
+ return False
87
+ return any(p.search(command) for p in DEPLOY_RES)
88
+
89
+
90
+ def _exit_code(tool_response):
91
+ if not isinstance(tool_response, dict):
92
+ return None
93
+ for key in ('exit_code', 'exitCode'):
94
+ v = tool_response.get(key)
95
+ if isinstance(v, int) and not isinstance(v, bool):
96
+ return v
97
+ return None
98
+
99
+
100
+ def has_error_signal(response_text, tool_response=None):
101
+ ec = _exit_code(tool_response)
102
+ if ec is not None and ec != 0:
103
+ return True
104
+ return bool(ERROR_RE.search(response_text or ''))
105
+
106
+
107
+ def is_local_host(host):
108
+ h = host.lower()
109
+ if h == 'localhost' or h.endswith('.localhost') or h.endswith('.local') or '.' not in h:
110
+ return True
111
+ try:
112
+ ip = ipaddress.ip_address(h)
113
+ except ValueError:
114
+ return False
115
+ return ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_unspecified or ip.is_reserved
116
+
117
+
118
+ def is_dashboard_host(host):
119
+ h = host.lower()
120
+ return any(h == s or h.endswith('.' + s) for s in DASHBOARD_SUFFIXES)
121
+
122
+
123
+ def is_hash_host(host):
124
+ """배포마다 바뀌는 해시 주소인가. 해시 주소는 안내 링크로 쓰지 않는다(매번 다른 도메인이 되어 재안내가 난다).
125
+ - vercel: <project>-<hash>-<scope>.vercel.app
126
+ - cloudflare pages: <hash8>.<project>.pages.dev
127
+ - netlify deploy preview: deploy-preview-N--<site>.netlify.app
128
+ """
129
+ h = host.lower()
130
+ labels = h.split('.')
131
+ if h.endswith('.vercel.app') and len(labels) == 3:
132
+ parts = labels[0].split('-')
133
+ return len(parts) >= 3 and any(HASH_SEG_RE.match(p) for p in parts[1:-1])
134
+ if h.endswith('.pages.dev') and len(labels) >= 4:
135
+ return bool(PAGES_HASH_RE.match(labels[0]))
136
+ if h.endswith('.netlify.app'):
137
+ return '--' in labels[0]
138
+ return False
139
+
140
+
141
+ def extract_public_host(response_text):
142
+ """출력에서 배포된 공개 호스트 하나를 고른다. 없으면 None."""
143
+ text = response_text or ''
144
+ candidates = [] # (tier, host): 0=별칭 줄, 1=운영 주소 줄, 2=그 밖. 같은 tier 는 출현 순
145
+ for line in text.splitlines():
146
+ if ALIAS_LINE_RE.search(line):
147
+ tier = 0
148
+ elif PREFER_LINE_RE.search(line):
149
+ tier = 1
150
+ else:
151
+ tier = 2
152
+ for m in URL_RE.finditer(line):
153
+ candidates.append((tier, m.group(1).lower()))
154
+ for _tier, host in sorted(candidates, key=lambda c: c[0]): # sorted 는 안정 정렬
155
+ if not HOST_RE.match(host):
156
+ continue
157
+ if is_local_host(host) or is_dashboard_host(host) or is_hash_host(host):
158
+ continue
159
+ return host
160
+ return None
161
+
162
+
163
+ def suggestions_enabled(env=None):
164
+ """config.json 의 suggestions 가 false 가 아니면 켜짐(기본 켜짐). 읽기 실패는 켜짐으로 본다."""
165
+ try:
166
+ with open(config_path(env), encoding='utf-8') as f:
167
+ cfg = json.load(f)
168
+ except Exception:
169
+ return True
170
+ if not isinstance(cfg, dict):
171
+ return True
172
+ return cfg.get('suggestions') is not False
173
+
174
+
175
+ def load_recorded(env=None):
176
+ try:
177
+ with open(record_path(env), encoding='utf-8') as f:
178
+ data = json.load(f)
179
+ except Exception:
180
+ return set()
181
+ domains = data.get('domains', []) if isinstance(data, dict) else []
182
+ return {d for d in domains if isinstance(d, str)}
183
+
184
+
185
+ def mark_recorded(host, env=None):
186
+ domains = load_recorded(env)
187
+ domains.add(host)
188
+ path = record_path(env)
189
+ os.makedirs(os.path.dirname(path), exist_ok=True)
190
+ tmp = f'{path}.tmp.{os.getpid()}'
191
+ with open(tmp, 'w', encoding='utf-8') as f:
192
+ json.dump({'domains': sorted(domains)}, f, ensure_ascii=False, indent=2)
193
+ os.replace(tmp, path)
194
+
195
+
196
+ def ci_active(env=None):
197
+ env = os.environ if env is None else env
198
+ return str(env.get('CI', '')).strip().lower() not in ('', '0', 'false')
199
+
200
+
201
+ def is_attended(env=None):
202
+ """대화형(사람이 보는) 세션인가. Claude Code 가 세션마다 CLAUDE_CODE_SESSION_ATTENDED=1 을 넣는다.
203
+ 훅 프로세스는 stdin·stdout 이 파이프라 isatty 로는 판별할 수 없어 이 값만 쓴다. 값이 없으면 침묵."""
204
+ env = os.environ if env is None else env
205
+ return str(env.get('CLAUDE_CODE_SESSION_ATTENDED', '')).strip() == '1'
206
+
207
+
208
+ def site_title(cwd):
209
+ """배포한 프로젝트 폴더의 index.html(또는 public/index.html) <title>. 없으면 None. 네트워크를 쓰지 않는다."""
210
+ if not isinstance(cwd, str) or not cwd:
211
+ return None
212
+ for rel in (('index.html',), ('public', 'index.html')):
213
+ try:
214
+ with open(os.path.join(cwd, *rel), encoding='utf-8', errors='replace') as f:
215
+ head = f.read(200000)
216
+ except OSError:
217
+ continue
218
+ m = TITLE_RE.search(head)
219
+ if not m:
220
+ continue
221
+ t = html.unescape(re.sub(r'\s+', ' ', m.group(1))).strip()
222
+ if t:
223
+ return t[:TITLE_MAX]
224
+ return None
225
+
226
+
227
+ def access_token(env=None):
228
+ """rc-login 이 저장한 사용자 토큰(credentials.json accessToken). 없거나 깨졌으면 None."""
229
+ try:
230
+ with open(os.path.join(rc_dir(env), 'credentials.json'), encoding='utf-8') as f:
231
+ tok = json.load(f).get('accessToken')
232
+ return tok if isinstance(tok, str) and tok else None
233
+ except Exception:
234
+ return None
235
+
236
+
237
+ def auth_base(env=None):
238
+ env = os.environ if env is None else env
239
+ base = env.get('AUTH_API_URL') or env.get('ROUTINECODE_AUTH_URL') or DEFAULT_AUTH_URL
240
+ return base.rstrip('/')
241
+
242
+
243
+ def _auth_post(env, path, body, token):
244
+ req = urllib.request.Request(
245
+ auth_base(env) + path,
246
+ data=json.dumps(body).encode('utf-8'),
247
+ method='POST',
248
+ headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {token}', 'User-Agent': 'routinecode-cli'},
249
+ )
250
+ with urllib.request.urlopen(req, timeout=GATE_TIMEOUT_S) as r:
251
+ return json.loads(r.read().decode('utf-8') or '{}')
252
+
253
+
254
+ def gate_allows(env=None):
255
+ """auth 관문. allow 가 false 일 때만 침묵. 토큰 없음·오류·시간 초과·알 수 없는 응답은 표시(fail-open)."""
256
+ token = access_token(env)
257
+ if not token:
258
+ return True
259
+ try:
260
+ d = _auth_post(env, '/api/v1/me/suggestions/gate',
261
+ {'cardKey': GATE_CARD_KEY, 'service': 'routinecode', 'kind': 'term', 'peek': True}, token)
262
+ data = d.get('data', d) if isinstance(d, dict) else None
263
+ allow = data.get('allow') if isinstance(data, dict) else None
264
+ return allow is not False
265
+ except Exception:
266
+ return True
267
+
268
+
269
+ def record_shown(env=None):
270
+ """화면에 실제로 띄운 뒤 event 'shown' 을 보낸다. 실패해도 무시한다(fail-open)."""
271
+ token = access_token(env)
272
+ if not token:
273
+ return
274
+ try:
275
+ _auth_post(env, '/api/v1/me/suggestions/event',
276
+ {'cardKey': GATE_CARD_KEY, 'service': 'routinecode', 'kind': 'term', 'event': 'shown'}, token)
277
+ except Exception:
278
+ pass
279
+
280
+
281
+ def build_line(host, title=None):
282
+ url = GEO_START.format(domain=host)
283
+ if title:
284
+ url += '&title=' + urllib.parse.quote(title, safe='')
285
+ return f'› {host} 이 AI 답변(ChatGPT·Perplexity)에 나오는지 무료로 볼 수 있어요: {url}\n{HINT}'
286
+
287
+
288
+ def suggest_line(command, response_text, tool_response=None, env=None, cwd=None):
289
+ """배포 성공 안내 1줄을 돌려준다. 안내하지 않을 때는 None. 예외는 전부 None (fail-open)."""
290
+ try:
291
+ if not is_deploy_command(command):
292
+ return None
293
+ if ci_active(env):
294
+ return None
295
+ if not is_attended(env):
296
+ return None
297
+ if has_error_signal(response_text, tool_response):
298
+ return None
299
+ host = extract_public_host(response_text)
300
+ if not host:
301
+ return None
302
+ if not suggestions_enabled(env):
303
+ return None
304
+ if host in load_recorded(env):
305
+ return None
306
+ if not gate_allows(env):
307
+ return None
308
+ mark_recorded(host, env)
309
+ record_shown(env)
310
+ return build_line(host, site_title(cwd))
311
+ except Exception:
312
+ return None
@@ -0,0 +1,86 @@
1
+ """design_pick_nudge — 새 화면 디자인 요청이면 rc-routine-design-pick 을 먼저 쓰라고 한 줄 붙인다 (설계 23 v11).
2
+
3
+ 스킬 설명만으로는 Claude 가 루틴을 고르지 않고 바로 화면 코드를 쓰는 경우가 있어, UserPromptSubmit 에서
4
+ "화면 종류 + 만들기·디자인 동사" 가 같이 있는 요청에만 안내를 붙인다. 다음이면 붙이지 않는다:
5
+ - 루틴 스킬이 설치돼 있지 않음(팩 꺼짐·미설치)
6
+ - 프로젝트에 이미 DESIGN.md 가 있음(방향이 정해진 작은 수정)
7
+ - 버그·오류 수정 요청인데 디자인 단어가 없음, 아주 긴 붙여넣기(로그 등)
8
+ - 같은 세션에서 이미 붙였음, 백그라운드 세션
9
+ """
10
+ import os
11
+ import re
12
+
13
+ SKILL = 'rc-routine-design-pick'
14
+
15
+ _SURFACE = re.compile(
16
+ r'홈\s*페이지|랜딩|웹\s*사이트|사이트|대시보드|화면|페이지|\bui\b|'
17
+ r'landing|home\s*page|homepage|web\s*site|website|dashboard|screen|\bpage\b',
18
+ re.I)
19
+ _ACTION = re.compile(
20
+ r'만들|디자인|리디자인|꾸며|꾸미|예쁘게|이쁘게|세련|멋지게|개편|새로\s*짜|구현해|짜\s*줘|'
21
+ r'\bbuild\b|\bcreate\b|\bdesign\b|\bredesign\b|\bmake\b|\bmock\s*up\b|revamp|prettier',
22
+ re.I)
23
+ _DESIGN_WORD = re.compile(r'디자인|design|스타일|style|예쁘게|이쁘게|세련|리디자인|redesign', re.I)
24
+ _FIX = re.compile(r'버그|오류|에러|안\s*돼|깨져|고쳐|\bfix\b|\bbug\b|\berror\b|crash|exception', re.I)
25
+ _MAX_LEN = 600
26
+
27
+ NUDGE = ('[DESIGN-PICK] 새 화면 디자인 요청으로 보인다. 화면 코드를 쓰기 전에 rc-routine-design-pick 스킬을 실행해 '
28
+ '고객 브랜드 이름으로 스타일 카탈로그(design/picker.html)를 열어 보여 주고, 고객이 고른 뒤에 만든다. '
29
+ '고객이 이미 스타일을 정했거나 화면 디자인과 무관한 작업이면 건너뛴다.')
30
+
31
+
32
+ def is_design_request(prompt):
33
+ p = (prompt or '').strip()
34
+ if not p or len(p) > _MAX_LEN:
35
+ return False
36
+ if not (_SURFACE.search(p) and _ACTION.search(p)):
37
+ return False
38
+ if _FIX.search(p) and not _DESIGN_WORD.search(p):
39
+ return False
40
+ return True
41
+
42
+
43
+ def _skill_installed(cwd, env):
44
+ roots = [env.get('CLAUDE_CONFIG_DIR') or os.path.join(env.get('HOME') or os.path.expanduser('~'), '.claude')]
45
+ d = os.path.abspath(cwd or '.')
46
+ for _ in range(6):
47
+ roots.append(os.path.join(d, '.claude'))
48
+ up = os.path.dirname(d)
49
+ if up == d:
50
+ break
51
+ d = up
52
+ return any(os.path.isfile(os.path.join(r, 'skills', SKILL, 'SKILL.md')) for r in roots)
53
+
54
+
55
+ def _has_design_md(cwd):
56
+ d = os.path.abspath(cwd or '.')
57
+ return any(os.path.isfile(os.path.join(d, *p)) for p in (('DESIGN.md',), ('design', 'DESIGN.md'), ('docs', 'DESIGN.md')))
58
+
59
+
60
+ def nudge(inp, env=None):
61
+ """UserPromptSubmit 입력(dict) → 안내 문자열 또는 ''. 절대 throw 하지 않는다."""
62
+ env = env if env is not None else os.environ
63
+ try:
64
+ if any(env.get(k) == '1' for k in ('ROUTINECODE_RECORDER', 'ROUTINECODE_ARCHITECT', 'ROUTINECODE_MAINTENANCE',
65
+ 'ROUTINECODE_DESIGN_NUDGE_DISABLED')):
66
+ return ''
67
+ if not is_design_request(inp.get('prompt') or ''):
68
+ return ''
69
+ cwd = inp.get('cwd') or os.getcwd()
70
+ if _has_design_md(cwd) or not _skill_installed(cwd, env):
71
+ return ''
72
+ sid = re.sub(r'[^A-Za-z0-9_-]', '', str(inp.get('session_id') or ''))[:64]
73
+ if sid:
74
+ mdir = os.path.join(env.get('HOME') or os.path.expanduser('~'), '.routinecode', 'state')
75
+ marker = os.path.join(mdir, 'design-nudge-' + sid)
76
+ if os.path.exists(marker):
77
+ return ''
78
+ try:
79
+ os.makedirs(mdir, exist_ok=True)
80
+ with open(marker, 'w') as f:
81
+ f.write('1')
82
+ except Exception:
83
+ pass
84
+ return NUDGE
85
+ except Exception:
86
+ return ''
@@ -35,6 +35,10 @@ METADATA_ALLOWED_KEYS = {
35
35
  "task": {"task_sig", "area_hint", "cwd_hash"},
36
36
  # Prevented Time 적립(초) — raw 스트림, growth 집계 게이트 자동 우회
37
37
  "time_saved": {"measured_s", "paired_s", "anchored_s", "c1", "c2"},
38
+ # 설계 35 A13 — 사용자 PC 절감 계산기 주간 숫자(퍼센트·주 시작일·배수표 라벨만)
39
+ "savings_calc": {"calc_week", "actual_pct", "opus_pct", "saving_pct", "multiple", "calc_parts", "calc_origin",
40
+ "calc_length", "calc_version", "cum_actual_pct", "cum_opus_pct", "cum_saving_pct",
41
+ "cum_weeks", "rec_actual_pct", "rec_opus_pct", "rec_saving_pct", "rec_weeks", "calc_history"},
38
42
  }
39
43
 
40
44
  EVENT_TYPES = frozenset(METADATA_ALLOWED_KEYS.keys())
package/hooks/lib/i18n.py CHANGED
@@ -566,18 +566,32 @@ STRINGS = {
566
566
  "es": "[HOOK] Puntuación de verificación {score}/100 < 90 (tier={tier}). Analiza dimensiones fallidas -> corrige -> save_evidence -> auto_score -> repite hasta 90+.",
567
567
  },
568
568
  "mark.no_design_score": {
569
- "en": "[HOOK] No design verification found for task {task_id} (tier={tier}). Complete design phase scoring (>= 90) before marking complete.",
570
- "ko": "[HOOK] 태스크 {task_id}에 대한 설계 검증 없음 (tier={tier}). 설계 단계 채점(>= 90)을 완료해야 합니다.",
571
- "ja": "[HOOK] タスク {task_id} の設計検証なし(tier={tier})。完了マーク前に設計フェーズのスコアリング(>= 90)を完了してください。",
572
- "zh": "[HOOK] 未找到任务 {task_id} 的设计验证(tier={tier})。标记完成前需完成设计阶段评分(>= 90)。",
573
- "es": "[HOOK] No se encontró verificación de diseño para tarea {task_id} (tier={tier}). Completa la puntuación de fase de diseño (>= 90) antes de marcar como completa.",
569
+ "en": "[HOOK] No design verification found for task {task_id} (tier={tier}). Run judge_design (score >= 90) before marking complete.",
570
+ "ko": "[HOOK] 태스크 {task_id}에 대한 설계 검증 없음 (tier={tier}). judge_design을 실행해 90점 이상을 받아야 합니다.",
571
+ "ja": "[HOOK] タスク {task_id} の設計検証なし(tier={tier})。完了マーク前に judge_design を実行して 90 点以上を得てください。",
572
+ "zh": "[HOOK] 未找到任务 {task_id} 的设计验证(tier={tier})。标记完成前请运行 judge_design 并达到 90 分以上。",
573
+ "es": "[HOOK] No se encontró verificación de diseño para tarea {task_id} (tier={tier}). Ejecuta judge_design (>= 90) antes de marcar como completa.",
574
574
  },
575
575
  "mark.low_design_score": {
576
- "en": "[HOOK] Design phase score {score}/100 < 90 (retroactive deductions applied). Fix design flaws and re-score design phase before marking complete.",
577
- "ko": "[HOOK] 설계 단계 점수 {score}/100 < 90 (소급 감점 적용됨). 설계 결함을 수정하고 설계 단계를 재채점해야 합니다.",
578
- "ja": "[HOOK] 設計フェーズスコア {score}/100 < 90(遡及減点適用済)。設計の欠陥を修正し、設計フェーズを再スコアリングしてください。",
579
- "zh": "[HOOK] 设计阶段分数 {score}/100 < 90(已应用追溯扣分)。修复设计缺陷并重新评分后再标记完成。",
580
- "es": "[HOOK] Puntuación de fase de diseño {score}/100 < 90 (deducciones retroactivas aplicadas). Corrige los defectos de diseño y vuelve a puntuar.",
576
+ "en": "[HOOK] Design phase score {score}/100 < 90 (retroactive deductions applied). Reproduce each judge deduction, fix the design, then run judge_design again.",
577
+ "ko": "[HOOK] 설계 단계 점수 {score}/100 < 90 (소급 감점 적용됨). 심판 감점을 재현해 설계를 고친 뒤 judge_design을 다시 실행하세요.",
578
+ "ja": "[HOOK] 設計フェーズスコア {score}/100 < 90(遡及減点適用済)。審査員の減点を再現して設計を修正し、judge_design を再実行してください。",
579
+ "zh": "[HOOK] 设计阶段分数 {score}/100 < 90(已应用追溯扣分)。复现评审扣分并修复设计后,重新运行 judge_design。",
580
+ "es": "[HOOK] Puntuación de fase de diseño {score}/100 < 90 (deducciones retroactivas aplicadas). Reproduce las deducciones del juez, corrige el diseño y vuelve a ejecutar judge_design.",
581
+ },
582
+ "mark.design_not_judged": {
583
+ "en": "[HOOK] Design for task {task_id} has no judge score. Run judge_design.",
584
+ "ko": "[HOOK] 태스크 {task_id}의 설계에 심판 채점이 없습니다. judge_design을 실행하세요.",
585
+ "ja": "[HOOK] タスク {task_id} の設計に審査員の採点がありません。judge_design を実行してください。",
586
+ "zh": "[HOOK] 任务 {task_id} 的设计没有评审评分。请运行 judge_design。",
587
+ "es": "[HOOK] El diseño de la tarea {task_id} no tiene puntuación del juez. Ejecuta judge_design.",
588
+ },
589
+ "mark.design_stale": {
590
+ "en": "[HOOK] Design for task {task_id} changed after judging. Run judge_design again.",
591
+ "ko": "[HOOK] 태스크 {task_id}의 설계가 심사 뒤에 바뀌었습니다. judge_design을 다시 실행하세요.",
592
+ "ja": "[HOOK] タスク {task_id} の設計が審査後に変更されました。judge_design を再実行してください。",
593
+ "zh": "[HOOK] 任务 {task_id} 的设计在评审后已更改。请重新运行 judge_design。",
594
+ "es": "[HOOK] El diseño de la tarea {task_id} cambió después de la revisión. Ejecuta judge_design de nuevo.",
581
595
  },
582
596
  # ── gate.* : design/mark 게이트 메시지 (pre-agent-spawn.mjs.src의 GATE_STRINGS와 동기 유지) ──
583
597
  "gate.mcp_degraded_design": {
@@ -602,18 +616,32 @@ STRINGS = {
602
616
  "es": "[HOOK:design-gate] No se puede extraer taskId del prompt del implementor. Incluye \"taskId: <id>\" en la sección CONTEXT.",
603
617
  },
604
618
  "gate.design_score_low": {
605
- "en": "[HOOK:design-gate] Design phase score {score}/100 < 90 for task {task_id}. Verify the design assumptions by running them and re-score the design phase before spawning implementor.",
606
- "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계 점수 {score}/100 < 90. 설계 전제를 실행으로 확인하고 재채점한 뒤 implementor를 위임하세요.",
607
- "ja": "[HOOK:design-gate] タスク {task_id} の設計スコア {score}/100 < 90。設計の前提を実行で確認し、再採点してからimplementorを起動してください。",
608
- "zh": "[HOOK:design-gate] 任务 {task_id} 的设计评分 {score}/100 < 90。请先通过实际运行验证设计前提并重新评分,再派发 implementor。",
609
- "es": "[HOOK:design-gate] Puntuación de diseño {score}/100 < 90 para la tarea {task_id}. Verifica las premisas del diseño ejecutándolas y vuelve a puntuar antes de lanzar el implementor.",
619
+ "en": "[HOOK:design-gate] Design phase score {score}/100 < 90 for task {task_id}. Reproduce each judge deduction, fix the design and run judge_design again before spawning implementor.",
620
+ "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계 점수 {score}/100 < 90. 심판 감점을 재현해 설계를 고치고 judge_design을 다시 실행한 뒤 implementor를 위임하세요.",
621
+ "ja": "[HOOK:design-gate] タスク {task_id} の設計スコア {score}/100 < 90。審査員の減点を再現して設計を修正し、judge_design を再実行してからimplementorを起動してください。",
622
+ "zh": "[HOOK:design-gate] 任务 {task_id} 的设计评分 {score}/100 < 90。请复现评审扣分并修复设计,重新运行 judge_design 后再派发 implementor。",
623
+ "es": "[HOOK:design-gate] Puntuación de diseño {score}/100 < 90 para la tarea {task_id}. Reproduce las deducciones del juez, corrige el diseño y ejecuta judge_design de nuevo antes de lanzar el implementor.",
610
624
  },
611
625
  "gate.no_design_verify": {
612
- "en": "[HOOK:design-gate] No design verification found for task {task_id} (tier={tier}). Complete design phase scoring (>= 90) before spawning implementor.",
613
- "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계 검증이 없습니다 (tier={tier}). 설계 채점(>= 90)을 완료한 뒤 implementor를 위임하세요.",
614
- "ja": "[HOOK:design-gate] タスク {task_id} の設計検証が見つかりません(tier={tier})。設計採点(>= 90)を完了してからimplementorを起動してください。",
615
- "zh": "[HOOK:design-gate] 未找到任务 {task_id} 的设计验证(tier={tier})。请完成设计评分(>= 90)后再派发 implementor。",
616
- "es": "[HOOK:design-gate] No se encontró verificación de diseño para la tarea {task_id} (tier={tier}). Completa la puntuación de diseño (>= 90) antes de lanzar el implementor.",
626
+ "en": "[HOOK:design-gate] No design verification found for task {task_id} (tier={tier}). Run judge_design (score >= 90) before spawning implementor.",
627
+ "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계 검증이 없습니다 (tier={tier}). judge_design으로 90점 이상을 받은 뒤 implementor를 위임하세요.",
628
+ "ja": "[HOOK:design-gate] タスク {task_id} の設計検証が見つかりません(tier={tier})。judge_design で 90 点以上を得てからimplementorを起動してください。",
629
+ "zh": "[HOOK:design-gate] 未找到任务 {task_id} 的设计验证(tier={tier})。请通过 judge_design 达到 90 分以上后再派发 implementor。",
630
+ "es": "[HOOK:design-gate] No se encontró verificación de diseño para la tarea {task_id} (tier={tier}). Ejecuta judge_design (>= 90) antes de lanzar el implementor.",
631
+ },
632
+ "gate.design_not_judged": {
633
+ "en": "[HOOK:design-gate] Design for task {task_id} has no judge score. Run judge_design.",
634
+ "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계에 심판 채점이 없습니다. judge_design을 실행하세요.",
635
+ "ja": "[HOOK:design-gate] タスク {task_id} の設計に審査員の採点がありません。judge_design を実行してください。",
636
+ "zh": "[HOOK:design-gate] 任务 {task_id} 的设计没有评审评分。请运行 judge_design。",
637
+ "es": "[HOOK:design-gate] El diseño de la tarea {task_id} no tiene puntuación del juez. Ejecuta judge_design.",
638
+ },
639
+ "gate.design_stale": {
640
+ "en": "[HOOK:design-gate] Design for task {task_id} changed after judging. Run judge_design again.",
641
+ "ko": "[HOOK:design-gate] 태스크 {task_id}의 설계가 심사 뒤에 바뀌었습니다. judge_design을 다시 실행하세요.",
642
+ "ja": "[HOOK:design-gate] タスク {task_id} の設計が審査後に変更されました。judge_design を再実行してください。",
643
+ "zh": "[HOOK:design-gate] 任务 {task_id} 的设计在评审后已更改。请重新运行 judge_design。",
644
+ "es": "[HOOK:design-gate] El diseño de la tarea {task_id} cambió después de la revisión. Ejecuta judge_design de nuevo.",
617
645
  },
618
646
  "gate.w5_high_risk": {
619
647
  "en": "[risk-gate] {count} HIGH-risk file(s) involved (e.g. {file}) — run the code-review skill after the change.",