@routinecrew/routinecode 2.31.57 → 2.31.60

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 (132) hide show
  1. package/bin/cli.sh +71 -41
  2. package/bin/prompt-vault.js +1 -1
  3. package/bin/rc-credit-turn.js +30 -4
  4. package/bin/rc-grant.js +79 -0
  5. package/bin/rc-login.js +23 -32
  6. package/bin/rc-team.js +592 -0
  7. package/bin/seal-open.js +5 -2
  8. package/hooks/lib/block_message.py +21 -19
  9. package/hooks/lib/i18n.py +17 -10
  10. package/hooks/lib/rt_cleanup.py +61 -0
  11. package/hooks/lib/scrub_stream.py +43 -0
  12. package/hooks/lib/secret_filter.py +443 -1
  13. package/hooks/lib/supplements_sig.py +70 -0
  14. package/hooks/post-knowledge-query.sh +14 -0
  15. package/hooks/post-secret-detect.sh +12 -27
  16. package/hooks/pre-account-guard.sh +6 -2
  17. package/hooks/pre-agent-spawn.mjs +1 -1
  18. package/hooks/pre-bash-guard.sh +11 -0
  19. package/hooks/pre-credit-guard.sh +36 -30
  20. package/hooks/pre-edit-domain-gate.sh +3 -1
  21. package/hooks/pre-edit-knowledge-gate.sh +3 -1
  22. package/hooks/pre-grep-guard.sh +18 -0
  23. package/hooks/pre-read-guard.sh +17 -0
  24. package/hooks/pre-read-knowledge-inject.sh +3 -1
  25. package/hooks/session-start.sh +47 -7
  26. package/hooks/stop-knowledge-remind.sh +45 -10
  27. package/hooks/tests/design09-client.test.py +10 -0
  28. package/hooks/tests/in-project-relax.test.py +2 -1
  29. package/hooks/tests/knowledge-loop.test.sh +89 -0
  30. package/hooks/tests/secret-guard-bypass.test.sh +107 -0
  31. package/hooks/tests/secret-guard.test.sh +2 -1
  32. package/hooks/tests/secret-premask.test.py +179 -0
  33. package/hooks/user-prompt-submit.sh +25 -19
  34. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  35. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  36. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  37. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  38. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  39. package/mcp-db-manager/dist/index.js +1 -1
  40. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  41. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  42. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  43. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  44. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  45. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  46. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  47. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  48. package/mcp-dev-tester/dist/attestation.js +1 -1
  49. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  50. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  51. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  52. package/mcp-dev-tester/dist/index.js +1 -1
  53. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  54. package/mcp-doc-fetcher/dist/index.js +1 -1
  55. package/mcp-html-renderer/dist/index.js +1 -1
  56. package/mcp-html-renderer/dist/preview.js +1 -1
  57. package/mcp-html-renderer/dist/template-engine.js +1 -1
  58. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  59. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  60. package/mcp-intelligence/dist/config-auth.js +1 -1
  61. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  62. package/mcp-intelligence/dist/domain-templates.js +1 -1
  63. package/mcp-intelligence/dist/grounding.d.ts +1 -0
  64. package/mcp-intelligence/dist/grounding.d.ts.map +1 -1
  65. package/mcp-intelligence/dist/grounding.js +1 -1
  66. package/mcp-intelligence/dist/handlers.js +1 -1
  67. package/mcp-intelligence/dist/index.js +1 -1
  68. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  69. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  70. package/mcp-intelligence/dist/knowledge-handlers.d.ts +20 -0
  71. package/mcp-intelligence/dist/knowledge-handlers.d.ts.map +1 -1
  72. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  73. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  74. package/mcp-intelligence/dist/provenance.js +1 -1
  75. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  76. package/mcp-log-watcher/dist/config-auth.js +1 -1
  77. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  78. package/mcp-log-watcher/dist/index.js +1 -1
  79. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  80. package/mcp-log-watcher/dist/log-store.js +1 -1
  81. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  82. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  83. package/mcp-plan-manager/dist/file-ops.js +1 -1
  84. package/mcp-plan-manager/dist/index.js +1 -1
  85. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  86. package/mcp-project-context/dist/git-ops.js +1 -1
  87. package/mcp-project-context/dist/index.js +1 -1
  88. package/mcp-project-context/dist/project-analysis.js +1 -1
  89. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  90. package/mcp-routinecode/dist/attestation.js +1 -1
  91. package/mcp-routinecode/dist/blast-radius.js +1 -1
  92. package/mcp-routinecode/dist/changeset.js +1 -1
  93. package/mcp-routinecode/dist/config-auth.js +1 -1
  94. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  95. package/mcp-routinecode/dist/coverage.js +1 -1
  96. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  97. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  98. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  99. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  100. package/mcp-routinecode/dist/index.js +1 -1
  101. package/mcp-routinecode/dist/known-solutions.js +1 -1
  102. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  103. package/mcp-routinecode/dist/observed-draft.js +1 -1
  104. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  105. package/mcp-routinecode/dist/route-match.js +1 -1
  106. package/mcp-routinecode/dist/routines.js +1 -1
  107. package/mcp-routinecode/dist/rule-engine.js +1 -1
  108. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  109. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  110. package/mcp-routinecode/dist/test-runner.js +1 -1
  111. package/mcp-routinecode/dist/verification.js +0 -0
  112. package/mcp-routinecode/dist/viral-loop.d.ts +68 -0
  113. package/mcp-routinecode/dist/viral-loop.js +1 -1
  114. package/package.json +1 -1
  115. package/plugin/agents/analyzer.md.sealed +1 -0
  116. package/plugin/agents/crawler.md.sealed +1 -0
  117. package/plugin/agents/explorer.md.sealed +1 -0
  118. package/plugin/agents/implementor.md.sealed +1 -0
  119. package/plugin/agents/looker.md.sealed +1 -0
  120. package/plugin/agents/planner.md.sealed +1 -0
  121. package/plugin/agents/recorder.md.sealed +1 -0
  122. package/plugin/agents/reviewer.md.sealed +1 -0
  123. package/plugin/agents/verifier.md.sealed +1 -0
  124. package/plugin/commands/analyze.md.sealed +1 -0
  125. package/plugin/commands/plan.md.sealed +1 -0
  126. package/plugin/commands/rc.md.sealed +1 -0
  127. package/plugin/commands/receipt.md.sealed +1 -0
  128. package/plugin/commands/recharge.md.sealed +1 -0
  129. package/plugin/commands/routines.md.sealed +1 -0
  130. package/plugin/commands/share.md.sealed +1 -0
  131. package/plugin/routinecode-prompt.md.sealed +1 -0
  132. package/bin/setup.js +0 -3
package/bin/rc-team.js ADDED
@@ -0,0 +1,592 @@
1
+ #!/usr/bin/env node
2
+ // RoutineCode 팀 귀속 러너 (zero-dep, ESM) — docs/30 §3.5 / §7.1.
3
+ //
4
+ // routinecode team → 현재 팀 표시(status 와 동일)
5
+ // routinecode team status → 현재 귀속(팀 이름·tenantId 또는 개인) + 소속 조직 목록
6
+ // routinecode team switch [tenantId|이름|personal]
7
+ // → 선택한 조직 tenant 로 API 키를 재발급(issuedTenantId)하고
8
+ // config.json(apiKey·tenantId·teamTenantId·teamName)을 갱신
9
+ //
10
+ // 로그인 마지막 단계(bin/rc-login.js)도 이 모듈의 decideTeam/provisionKnowledgeKey 를 쓴다.
11
+ // 규칙(decideTeam):
12
+ // - 소속 organization(공유 테넌트 1 제외)이 0개 → 개인(기존 동작 그대로, tenantId 미전송)
13
+ // - 1개 → 자동 선택
14
+ // - 2개 이상 → 대화형이면 번호 선택, 비대화형(CI·TTY 아님)이면 현재 팀 유지 또는 개인
15
+ // - env ROUTINECODE_TEAM_TENANT_ID 로 지정 가능(숫자=그 조직, 'personal'/'0'=개인)
16
+ //
17
+ // rc-login.js 와 같은 평문 유지 분류(scripts/obfuscate.js 정책): 공개 API 만 호출하고 숨길
18
+ // 시크릿이 없다. 판정(멤버 여부)은 auth quick-signup 이 서버권위로 한다(멤버 아니면 403).
19
+
20
+ import { createHash } from 'node:crypto';
21
+ import { writeFileSync, mkdirSync, existsSync, readFileSync, realpathSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+ import { homedir, hostname } from 'node:os';
24
+ import { createInterface } from 'node:readline';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ export const SHARED_TENANT_ID = 1;
28
+
29
+ export function authBaseUrl() {
30
+ return (
31
+ process.env.AUTH_API_URL ||
32
+ process.env.ROUTINECODE_AUTH_URL ||
33
+ 'https://auth.routinecrew.net'
34
+ ).replace(/\/+$/, '');
35
+ }
36
+
37
+ export function knowledgeServerUrl() {
38
+ return (process.env.ROUTINECODE_SERVER_URL || 'https://knowledge.routinecrew.net').replace(/\/+$/, '');
39
+ }
40
+
41
+ export function configDir() {
42
+ return join(homedir(), '.routinecode');
43
+ }
44
+ export function configPath() {
45
+ return join(configDir(), 'config.json');
46
+ }
47
+ export function credentialsPath() {
48
+ return join(configDir(), 'credentials.json');
49
+ }
50
+
51
+ export function readJson(p) {
52
+ try {
53
+ if (!existsSync(p)) return null;
54
+ const raw = readFileSync(p, 'utf-8');
55
+ return raw.trim() ? JSON.parse(raw) : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function writeJson600(p, obj) {
62
+ if (!existsSync(configDir())) mkdirSync(configDir(), { recursive: true });
63
+ writeFileSync(p, JSON.stringify(obj, null, 2), { mode: 0o600 });
64
+ }
65
+
66
+ // ── locale (bin/rc-locale.js detect 미러: ROUTINECODE_LOCALE > config.locale > LANG > en) ──
67
+ const SUPPORTED = ['en', 'ko', 'ja', 'zh', 'es'];
68
+ export function detectLocale() {
69
+ const env = process.env.ROUTINECODE_LOCALE;
70
+ if (env && SUPPORTED.includes(env)) return env;
71
+ const l = readJson(configPath())?.locale;
72
+ if (SUPPORTED.includes(l)) return l;
73
+ const lang = (process.env.LANG || '').split('_')[0].toLowerCase();
74
+ return SUPPORTED.includes(lang) ? lang : 'en';
75
+ }
76
+
77
+ const MESSAGES = {
78
+ choose_title: {
79
+ en: 'Which team should RoutineCode use?',
80
+ ko: '어느 팀으로 RoutineCode 를 쓸까요?',
81
+ ja: 'どのチームで RoutineCode を使いますか?',
82
+ zh: '要以哪个团队使用 RoutineCode?',
83
+ es: '¿Con qué equipo quieres usar RoutineCode?',
84
+ },
85
+ personal_option: {
86
+ en: 'Personal (no team)',
87
+ ko: '개인 (팀 없음)',
88
+ ja: '個人 (チームなし)',
89
+ zh: '个人 (无团队)',
90
+ es: 'Personal (sin equipo)',
91
+ },
92
+ choose_prompt: {
93
+ en: 'Enter a number [{def}]: ',
94
+ ko: '번호를 입력하세요 [{def}]: ',
95
+ ja: '番号を入力してください [{def}]: ',
96
+ zh: '请输入编号 [{def}]: ',
97
+ es: 'Introduce un número [{def}]: ',
98
+ },
99
+ invalid_choice: {
100
+ en: 'Invalid choice — keeping {current}.',
101
+ ko: '잘못된 선택입니다 — {current} 로 유지합니다.',
102
+ ja: '無効な選択です — {current} のままにします。',
103
+ zh: '选择无效 — 保持 {current}。',
104
+ es: 'Opción no válida — se mantiene {current}.',
105
+ },
106
+ team_selected: {
107
+ en: 'Team: {name} (tenant {id}) — knowledge will be attributed to this team.',
108
+ ko: '팀: {name} (tenant {id}) — 지식이 이 팀으로 귀속됩니다.',
109
+ ja: 'チーム: {name} (tenant {id}) — ナレッジはこのチームに帰属します。',
110
+ zh: '团队: {name} (tenant {id}) — 知识将归属于该团队。',
111
+ es: 'Equipo: {name} (tenant {id}) — el conocimiento se atribuirá a este equipo.',
112
+ },
113
+ personal_selected: {
114
+ en: 'Using RoutineCode personally (no team).',
115
+ ko: '개인으로 RoutineCode 를 사용합니다 (팀 없음).',
116
+ ja: '個人として RoutineCode を使用します (チームなし)。',
117
+ zh: '以个人身份使用 RoutineCode (无团队)。',
118
+ es: 'Usando RoutineCode de forma personal (sin equipo).',
119
+ },
120
+ non_interactive_personal: {
121
+ en: 'Multiple teams found but no terminal to ask — staying personal. Set ROUTINECODE_TEAM_TENANT_ID or run `routinecode team switch`.',
122
+ ko: '소속 팀이 여러 개지만 선택할 터미널이 없어 개인으로 유지합니다. ROUTINECODE_TEAM_TENANT_ID 를 지정하거나 `routinecode team switch` 를 실행하세요.',
123
+ ja: '複数のチームがありますが選択できる端末がないため個人のままにします。ROUTINECODE_TEAM_TENANT_ID を指定するか `routinecode team switch` を実行してください。',
124
+ zh: '检测到多个团队但没有可交互的终端 — 保持个人。请设置 ROUTINECODE_TEAM_TENANT_ID 或运行 `routinecode team switch`。',
125
+ es: 'Hay varios equipos pero no hay terminal para preguntar — se mantiene personal. Define ROUTINECODE_TEAM_TENANT_ID o ejecuta `routinecode team switch`.',
126
+ },
127
+ env_not_member: {
128
+ en: 'ROUTINECODE_TEAM_TENANT_ID={id} is not one of your teams — staying personal.',
129
+ ko: 'ROUTINECODE_TEAM_TENANT_ID={id} 는 소속 팀이 아닙니다 — 개인으로 유지합니다.',
130
+ ja: 'ROUTINECODE_TEAM_TENANT_ID={id} は所属チームではありません — 個人のままにします。',
131
+ zh: 'ROUTINECODE_TEAM_TENANT_ID={id} 不是你的团队 — 保持个人。',
132
+ es: 'ROUTINECODE_TEAM_TENANT_ID={id} no es uno de tus equipos — se mantiene personal.',
133
+ },
134
+ team_forbidden: {
135
+ en: 'You are not a member of that team (403) — issued a personal key instead.',
136
+ ko: '해당 팀의 멤버가 아닙니다(403) — 개인 키로 발급했습니다.',
137
+ ja: 'そのチームのメンバーではありません(403) — 個人キーを発行しました。',
138
+ zh: '你不是该团队成员(403) — 已改为签发个人密钥。',
139
+ es: 'No eres miembro de ese equipo (403) — se emitió una clave personal.',
140
+ },
141
+ team_unsupported: {
142
+ en: 'The auth server does not support team keys yet — issued a personal key. Run `routinecode team switch` later.',
143
+ ko: '인증 서버가 아직 팀 키를 지원하지 않아 개인 키로 발급했습니다. 나중에 `routinecode team switch` 를 실행하세요.',
144
+ ja: '認証サーバーがまだチームキーに対応していないため個人キーを発行しました。後で `routinecode team switch` を実行してください。',
145
+ zh: '认证服务器尚不支持团队密钥 — 已签发个人密钥。稍后请运行 `routinecode team switch`。',
146
+ es: 'El servidor de autenticación aún no admite claves de equipo — se emitió una clave personal. Ejecuta `routinecode team switch` más tarde.',
147
+ },
148
+ status_team: {
149
+ en: 'Current team: {name} (tenant {id})',
150
+ ko: '현재 팀: {name} (tenant {id})',
151
+ ja: '現在のチーム: {name} (tenant {id})',
152
+ zh: '当前团队: {name} (tenant {id})',
153
+ es: 'Equipo actual: {name} (tenant {id})',
154
+ },
155
+ status_personal: {
156
+ en: 'Current team: none (personal)',
157
+ ko: '현재 팀: 없음 (개인)',
158
+ ja: '現在のチーム: なし (個人)',
159
+ zh: '当前团队: 无 (个人)',
160
+ es: 'Equipo actual: ninguno (personal)',
161
+ },
162
+ status_not_logged_in: {
163
+ en: 'Not logged in. Run `routinecode login`.',
164
+ ko: '로그인되어 있지 않습니다. `routinecode login` 을 실행하세요.',
165
+ ja: 'ログインしていません。`routinecode login` を実行してください。',
166
+ zh: '尚未登录。请运行 `routinecode login`。',
167
+ es: 'No has iniciado sesión. Ejecuta `routinecode login`.',
168
+ },
169
+ available_teams: {
170
+ en: 'Your teams:',
171
+ ko: '소속 팀:',
172
+ ja: '所属チーム:',
173
+ zh: '你的团队:',
174
+ es: 'Tus equipos:',
175
+ },
176
+ no_teams: {
177
+ en: 'You do not belong to any team.',
178
+ ko: '소속된 팀이 없습니다.',
179
+ ja: '所属しているチームはありません。',
180
+ zh: '你不属于任何团队。',
181
+ es: 'No perteneces a ningún equipo.',
182
+ },
183
+ team_not_found: {
184
+ en: 'No team matches "{q}". Run `routinecode team status` to see your teams.',
185
+ ko: '"{q}" 에 해당하는 팀이 없습니다. `routinecode team status` 로 소속 팀을 확인하세요.',
186
+ ja: '"{q}" に一致するチームがありません。`routinecode team status` で所属チームを確認してください。',
187
+ zh: '没有与 "{q}" 匹配的团队。运行 `routinecode team status` 查看你的团队。',
188
+ es: 'Ningún equipo coincide con "{q}". Ejecuta `routinecode team status` para ver tus equipos.',
189
+ },
190
+ team_ambiguous: {
191
+ en: '"{q}" matches several teams — use the tenant id.',
192
+ ko: '"{q}" 에 해당하는 팀이 여러 개입니다 — tenant id 로 지정하세요.',
193
+ ja: '"{q}" に一致するチームが複数あります — tenant id で指定してください。',
194
+ zh: '"{q}" 匹配多个团队 — 请使用 tenant id。',
195
+ es: '"{q}" coincide con varios equipos — usa el tenant id.',
196
+ },
197
+ already_current: {
198
+ en: 'Already using {current}.',
199
+ ko: '이미 {current} 로 사용 중입니다.',
200
+ ja: 'すでに {current} を使用中です。',
201
+ zh: '已在使用 {current}。',
202
+ es: 'Ya estás usando {current}.',
203
+ },
204
+ session_expired: {
205
+ en: 'Your login has expired. Run `routinecode login` and choose the team there.',
206
+ ko: '로그인이 만료되었습니다. `routinecode login` 을 실행해 팀을 선택하세요.',
207
+ ja: 'ログインの有効期限が切れました。`routinecode login` を実行してチームを選択してください。',
208
+ zh: '登录已过期。请运行 `routinecode login` 并在其中选择团队。',
209
+ es: 'Tu sesión ha caducado. Ejecuta `routinecode login` y elige el equipo allí.',
210
+ },
211
+ fetch_failed: {
212
+ en: 'Could not load your teams from the auth server. Check your network and try again.',
213
+ ko: '인증 서버에서 소속 팀을 불러오지 못했습니다. 네트워크를 확인하고 다시 시도하세요.',
214
+ ja: '認証サーバーから所属チームを取得できませんでした。ネットワークを確認して再試行してください。',
215
+ zh: '无法从认证服务器加载团队。请检查网络后重试。',
216
+ es: 'No se pudieron cargar tus equipos desde el servidor de autenticación. Revisa la red e inténtalo de nuevo.',
217
+ },
218
+ provision_failed: {
219
+ en: 'Could not issue a new API key — your previous settings were kept.',
220
+ ko: '새 API 키를 발급하지 못했습니다 — 이전 설정을 유지합니다.',
221
+ ja: '新しい API キーを発行できませんでした — 以前の設定を維持します。',
222
+ zh: '无法签发新的 API 密钥 — 已保留之前的设置。',
223
+ es: 'No se pudo emitir una nueva clave API — se conservó la configuración anterior.',
224
+ },
225
+ switched: {
226
+ en: 'Switched. New sessions will use this attribution.',
227
+ ko: '전환했습니다. 새 세션부터 이 귀속이 적용됩니다.',
228
+ ja: '切り替えました。新しいセッションからこの帰属が適用されます。',
229
+ zh: '已切换。新会话将使用此归属。',
230
+ es: 'Cambiado. Las nuevas sesiones usarán esta atribución.',
231
+ },
232
+ usage: {
233
+ en: 'Usage: routinecode team [status | switch [tenantId|name|personal]]',
234
+ ko: '사용법: routinecode team [status | switch [tenantId|이름|personal]]',
235
+ ja: '使い方: routinecode team [status | switch [tenantId|名前|personal]]',
236
+ zh: '用法: routinecode team [status | switch [tenantId|名称|personal]]',
237
+ es: 'Uso: routinecode team [status | switch [tenantId|nombre|personal]]',
238
+ },
239
+ };
240
+
241
+ export function t(key, vars = {}, locale = detectLocale()) {
242
+ const entry = MESSAGES[key];
243
+ if (!entry) return key;
244
+ let s = entry[locale] || entry.en;
245
+ for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
246
+ return s;
247
+ }
248
+
249
+ // ── 팀 후보/선택 (pure) ──
250
+
251
+ /** /me/context tenants[] → 팀 후보(organization, 공유 테넌트 제외, 중복 제거). */
252
+ export function teamCandidates(tenants) {
253
+ if (!Array.isArray(tenants)) return [];
254
+ const seen = new Set();
255
+ const out = [];
256
+ for (const tn of tenants) {
257
+ const id = Number(tn?.tenantId);
258
+ if (!Number.isInteger(id) || id <= 0 || id === SHARED_TENANT_ID) continue;
259
+ if ((tn?.tenantType || 'organization') !== 'organization') continue;
260
+ if (seen.has(id)) continue;
261
+ seen.add(id);
262
+ out.push({ tenantId: id, name: String(tn?.name || `tenant ${id}`), role: tn?.role ?? null });
263
+ }
264
+ return out;
265
+ }
266
+
267
+ /** env ROUTINECODE_TEAM_TENANT_ID 해석: undefined=미지정, null=개인 강제, number=지정. */
268
+ export function parseEnvTenant(raw) {
269
+ if (raw === undefined || raw === null) return undefined;
270
+ const s = String(raw).trim().toLowerCase();
271
+ if (s === '') return undefined;
272
+ if (s === 'personal' || s === '0' || s === 'none') return null;
273
+ const n = Number(s);
274
+ return Number.isInteger(n) && n > 0 ? n : undefined;
275
+ }
276
+
277
+ export function isInteractive() {
278
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI;
279
+ }
280
+
281
+ /**
282
+ * 팀 결정. 반환: { team: {tenantId,name}|null, reason }.
283
+ * reason: 'env' | 'env_personal' | 'env_not_member' | 'none' | 'single' | 'prompt' |
284
+ * 'non_interactive_keep' | 'non_interactive_personal'
285
+ * prompt(candidates, current) → Promise<{tenantId,name}|null> (null=개인).
286
+ */
287
+ export async function decideTeam({ tenants, envTenantId, interactive, currentTeamTenantId = null, prompt }) {
288
+ const cands = teamCandidates(tenants);
289
+ const env = parseEnvTenant(envTenantId);
290
+ if (env === null) return { team: null, reason: 'env_personal' };
291
+ if (typeof env === 'number') {
292
+ const hit = cands.find((c) => c.tenantId === env);
293
+ return hit ? { team: hit, reason: 'env' } : { team: null, reason: 'env_not_member' };
294
+ }
295
+ if (cands.length === 0) return { team: null, reason: 'none' };
296
+ if (cands.length === 1) return { team: cands[0], reason: 'single' };
297
+ if (!interactive || typeof prompt !== 'function') {
298
+ const keep = cands.find((c) => c.tenantId === Number(currentTeamTenantId));
299
+ return keep ? { team: keep, reason: 'non_interactive_keep' } : { team: null, reason: 'non_interactive_personal' };
300
+ }
301
+ const picked = await prompt(cands, currentTeamTenantId);
302
+ return { team: picked ?? null, reason: 'prompt' };
303
+ }
304
+
305
+ /** 번호 입력 해석(pure). '0'=개인, ''=기본값, 범위 밖/비숫자=undefined(무효). */
306
+ export function parseChoice(input, candidates, defaultIndex) {
307
+ const s = String(input ?? '').trim();
308
+ const idx = s === '' ? defaultIndex : Number(s);
309
+ if (!Number.isInteger(idx) || idx < 0 || idx > candidates.length) return undefined;
310
+ return idx === 0 ? null : candidates[idx - 1];
311
+ }
312
+
313
+ /** 대화형 번호 선택 프롬프트(readline). 무효 입력이면 현재값(없으면 개인) 유지. */
314
+ export function promptTeam(candidates, currentTeamTenantId = null, io = { input: process.stdin, output: process.stdout }) {
315
+ const curIdx = candidates.findIndex((c) => c.tenantId === Number(currentTeamTenantId));
316
+ const def = curIdx >= 0 ? curIdx + 1 : 0;
317
+ const out = io.output;
318
+ out.write(`\n ${t('choose_title')}\n`);
319
+ out.write(` 0) ${t('personal_option')}\n`);
320
+ candidates.forEach((c, i) => out.write(` ${i + 1}) ${c.name} (tenant ${c.tenantId})${c.role ? ` — ${c.role}` : ''}\n`));
321
+ return new Promise((resolve) => {
322
+ const rl = createInterface({ input: io.input, output: out, terminal: false });
323
+ let done = false;
324
+ const finish = (v) => {
325
+ if (done) return;
326
+ done = true;
327
+ rl.close();
328
+ resolve(v);
329
+ };
330
+ out.write(` ${t('choose_prompt', { def })}`);
331
+ rl.once('line', (line) => {
332
+ const picked = parseChoice(line, candidates, def);
333
+ if (picked === undefined) {
334
+ const fallback = def === 0 ? null : candidates[def - 1];
335
+ out.write(` ${t('invalid_choice', { current: fallback ? fallback.name : t('personal_option') })}\n`);
336
+ finish(fallback);
337
+ return;
338
+ }
339
+ finish(picked);
340
+ });
341
+ rl.once('close', () => finish(def === 0 ? null : candidates[def - 1]));
342
+ });
343
+ }
344
+
345
+ /** `team switch <arg>` 대상 해석(pure). 반환 {team}|{personal:true}|{error:'not_found'|'ambiguous'}. */
346
+ export function resolveSwitchTarget(arg, candidates) {
347
+ const q = String(arg ?? '').trim();
348
+ const low = q.toLowerCase();
349
+ if (low === 'personal' || low === 'none' || q === '0') return { personal: true };
350
+ if (/^\d+$/.test(q)) {
351
+ const hit = candidates.find((c) => c.tenantId === Number(q));
352
+ return hit ? { team: hit } : { error: 'not_found' };
353
+ }
354
+ const exact = candidates.filter((c) => c.name.toLowerCase() === low);
355
+ if (exact.length === 1) return { team: exact[0] };
356
+ if (exact.length > 1) return { error: 'ambiguous' };
357
+ const prefix = candidates.filter((c) => c.name.toLowerCase().startsWith(low));
358
+ if (prefix.length === 1) return { team: prefix[0] };
359
+ return { error: prefix.length > 1 ? 'ambiguous' : 'not_found' };
360
+ }
361
+
362
+ // ── 네트워크 ──
363
+
364
+ /** auth GET /me/context → { ok, status, data } (data=BasicResponse.data). */
365
+ export async function fetchMeContext(accessToken, fetchImpl = fetch) {
366
+ try {
367
+ const r = await fetchImpl(`${authBaseUrl()}/api/v1/me/context`, {
368
+ headers: { Authorization: `Bearer ${accessToken}`, 'User-Agent': 'routinecode-cli' },
369
+ signal: AbortSignal.timeout(5000),
370
+ });
371
+ if (!r.ok) return { ok: false, status: r.status, data: null };
372
+ const body = await r.json().catch(() => ({}));
373
+ return { ok: true, status: r.status, data: body?.data ?? null };
374
+ } catch {
375
+ return { ok: false, status: 0, data: null };
376
+ }
377
+ }
378
+
379
+ /** auth POST /refresh (session-start.sh _refresh 와 동일 경로·스키마). 성공 시 새 토큰 dict. */
380
+ export async function refreshTokens(refreshToken, fetchImpl = fetch) {
381
+ try {
382
+ const r = await fetchImpl(`${authBaseUrl()}/api/v1/refresh`, {
383
+ method: 'POST',
384
+ headers: { 'Content-Type': 'application/json' },
385
+ body: JSON.stringify({ refreshToken }),
386
+ signal: AbortSignal.timeout(8000),
387
+ });
388
+ if (!r.ok) return null;
389
+ const body = await r.json().catch(() => ({}));
390
+ const d = body?.data || {};
391
+ return d.accessToken ? d : null;
392
+ } catch {
393
+ return null;
394
+ }
395
+ }
396
+
397
+ /** provision 요청 본문(pure). 팀이면 tenantId 를 싣고, 개인이면 기존과 동일하게 빈 객체. */
398
+ export function provisionBody(teamTenantId) {
399
+ const n = Number(teamTenantId);
400
+ return Number.isInteger(n) && n > 0 ? { tenantId: n } : {};
401
+ }
402
+
403
+ /**
404
+ * knowledge POST /provision. 반환 { ok, status, code?, result? }.
405
+ * 팀으로 요청했는데 403(멤버 아님)이면 호출자가 개인 재시도를 결정한다.
406
+ */
407
+ export async function requestProvision(accessToken, teamTenantId, fetchImpl = fetch) {
408
+ try {
409
+ const res = await fetchImpl(`${knowledgeServerUrl()}/api/v1/provision`, {
410
+ method: 'POST',
411
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },
412
+ body: JSON.stringify(provisionBody(teamTenantId)),
413
+ signal: AbortSignal.timeout(8000),
414
+ });
415
+ const body = await res.json().catch(() => ({}));
416
+ if (!res.ok) return { ok: false, status: res.status, code: body?.code };
417
+ return { ok: true, status: res.status, result: body };
418
+ } catch {
419
+ return { ok: false, status: 0 };
420
+ }
421
+ }
422
+
423
+ /** provision 결과 → config.json 객체(pure). rc-login 의 기존 필드 + 팀 필드. */
424
+ export function buildConfig(result, { userId, team }) {
425
+ const teamApplied = Boolean(team) && result?.teamApplied !== false;
426
+ const config = {
427
+ syncEnabled: true,
428
+ serverUrl: result.serverUrl || knowledgeServerUrl(),
429
+ apiKey: result.apiKey,
430
+ machineId: createHash('md5').update(hostname()).digest('hex').slice(0, 16),
431
+ userId: result.userId ?? userId,
432
+ tenantId: result.tenantId ?? null,
433
+ provisionedAt: new Date().toISOString(),
434
+ };
435
+ if (teamApplied) {
436
+ config.teamTenantId = Number(result.issuedTenantId ?? result.tenantId ?? team.tenantId);
437
+ config.teamName = team.name;
438
+ }
439
+ return config;
440
+ }
441
+
442
+ /**
443
+ * 팀(또는 개인)으로 키를 발급하고 config 를 저장한다.
444
+ * 반환 { ok, config?, fallback?: 'forbidden'|'unsupported' }. 실패 시 config 는 건드리지 않는다.
445
+ */
446
+ export async function provisionKnowledgeKey({ accessToken, userId, team, log = console.log, fetchImpl = fetch }) {
447
+ let res = await requestProvision(accessToken, team?.tenantId, fetchImpl);
448
+ let fallback;
449
+ let effectiveTeam = team || null;
450
+ if (!res.ok && team && res.status === 403) {
451
+ fallback = 'forbidden';
452
+ effectiveTeam = null;
453
+ res = await requestProvision(accessToken, null, fetchImpl);
454
+ }
455
+ if (!res.ok) return { ok: false, status: res.status };
456
+ const result = res.result;
457
+ if (!result?.syncEnabled || !result.apiKey) return { ok: false, status: res.status };
458
+ if (effectiveTeam && result.teamApplied === false) {
459
+ fallback = 'unsupported';
460
+ effectiveTeam = null;
461
+ }
462
+ const config = buildConfig(result, { userId, team: effectiveTeam });
463
+ writeJson600(configPath(), config);
464
+ if (fallback === 'forbidden') log(` ${t('team_forbidden')}`);
465
+ if (fallback === 'unsupported') log(` ${t('team_unsupported')}`);
466
+ log(` ${effectiveTeam ? t('team_selected', { name: effectiveTeam.name, id: config.teamTenantId }) : t('personal_selected')}`);
467
+ return { ok: true, config, fallback };
468
+ }
469
+
470
+ // ── 로그인 마지막 단계 (rc-login.js 가 호출) ──
471
+
472
+ /** /me/context 로 팀을 결정한다. 조회 실패는 개인(기존 동작)으로 진행 — 로그인을 막지 않는다. */
473
+ export async function selectTeamForLogin(accessToken, { log = console.log, fetchImpl = fetch } = {}) {
474
+ const ctx = await fetchMeContext(accessToken, fetchImpl);
475
+ const tenants = ctx.ok ? ctx.data?.tenants : [];
476
+ const current = readJson(configPath())?.teamTenantId ?? null;
477
+ const decision = await decideTeam({
478
+ tenants,
479
+ envTenantId: process.env.ROUTINECODE_TEAM_TENANT_ID,
480
+ interactive: isInteractive(),
481
+ currentTeamTenantId: current,
482
+ prompt: promptTeam,
483
+ });
484
+ if (decision.reason === 'env_not_member') {
485
+ log(` ${t('env_not_member', { id: process.env.ROUTINECODE_TEAM_TENANT_ID })}`);
486
+ } else if (decision.reason === 'non_interactive_personal') {
487
+ log(` ${t('non_interactive_personal')}`);
488
+ }
489
+ return decision.team;
490
+ }
491
+
492
+ // ── team status / switch ──
493
+
494
+ async function contextWithRefresh(fetchImpl = fetch) {
495
+ const creds = readJson(credentialsPath());
496
+ if (!creds?.accessToken) return { error: 'not_logged_in' };
497
+ let ctx = await fetchMeContext(creds.accessToken, fetchImpl);
498
+ if (!ctx.ok && (ctx.status === 401 || ctx.status === 403)) {
499
+ const nt = creds.refreshToken ? await refreshTokens(creds.refreshToken, fetchImpl) : null;
500
+ if (!nt) return { error: 'expired' };
501
+ creds.accessToken = nt.accessToken;
502
+ if (nt.refreshToken) creds.refreshToken = nt.refreshToken;
503
+ writeJson600(credentialsPath(), creds);
504
+ ctx = await fetchMeContext(creds.accessToken, fetchImpl);
505
+ }
506
+ if (!ctx.ok) return { error: 'fetch_failed', creds };
507
+ return { creds, data: ctx.data };
508
+ }
509
+
510
+ function currentLabel(cfg) {
511
+ return cfg?.teamTenantId ? `${cfg.teamName || 'tenant'} (tenant ${cfg.teamTenantId})` : t('personal_option');
512
+ }
513
+
514
+ export async function teamStatus({ log = console.log, fetchImpl = fetch } = {}) {
515
+ const cfg = readJson(configPath());
516
+ if (!cfg?.apiKey) {
517
+ log(` ${t('status_not_logged_in')}`);
518
+ return 1;
519
+ }
520
+ log(` ${cfg.teamTenantId ? t('status_team', { name: cfg.teamName || '-', id: cfg.teamTenantId }) : t('status_personal')}`);
521
+ const ctx = await contextWithRefresh(fetchImpl);
522
+ if (ctx.error) return 0; // 표시는 로컬 config 로 충분 — 목록 조회 실패는 무해
523
+ const cands = teamCandidates(ctx.data?.tenants);
524
+ if (cands.length === 0) {
525
+ log(` ${t('no_teams')}`);
526
+ return 0;
527
+ }
528
+ log(` ${t('available_teams')}`);
529
+ for (const c of cands) {
530
+ const mark = c.tenantId === Number(cfg.teamTenantId) ? '*' : ' ';
531
+ log(` ${mark} ${c.tenantId} ${c.name}${c.role ? ` — ${c.role}` : ''}`);
532
+ }
533
+ return 0;
534
+ }
535
+
536
+ export async function teamSwitch(arg, { log = console.log, err = console.error, fetchImpl = fetch, prompt = promptTeam, interactive = isInteractive() } = {}) {
537
+ const ctx = await contextWithRefresh(fetchImpl);
538
+ if (ctx.error === 'not_logged_in') { err(` ${t('status_not_logged_in')}`); return 1; }
539
+ if (ctx.error === 'expired') { err(` ${t('session_expired')}`); return 1; }
540
+ if (ctx.error) { err(` ${t('fetch_failed')}`); return 1; }
541
+
542
+ const cands = teamCandidates(ctx.data?.tenants);
543
+ const cfg = readJson(configPath()) || {};
544
+ let target; // {tenantId,name} | null(개인)
545
+ if (arg === undefined || arg === '') {
546
+ if (cands.length === 0) { log(` ${t('no_teams')}`); return 0; }
547
+ if (!interactive) { err(` ${t('usage')}`); return 1; }
548
+ target = await prompt(cands, cfg.teamTenantId ?? null);
549
+ } else {
550
+ const r = resolveSwitchTarget(arg, cands);
551
+ if (r.error) { err(` ${t(r.error === 'ambiguous' ? 'team_ambiguous' : 'team_not_found', { q: arg })}`); return 1; }
552
+ target = r.personal ? null : r.team;
553
+ }
554
+
555
+ const curId = cfg.teamTenantId ? Number(cfg.teamTenantId) : null;
556
+ const nextId = target ? target.tenantId : null;
557
+ if (cfg.apiKey && curId === nextId) {
558
+ log(` ${t('already_current', { current: currentLabel(cfg) })}`);
559
+ return 0;
560
+ }
561
+ const userId = ctx.data?.userId ?? ctx.creds?.userId ?? cfg.userId ?? null;
562
+ const out = await provisionKnowledgeKey({ accessToken: ctx.creds.accessToken, userId, team: target, log, fetchImpl });
563
+ if (!out.ok) { err(` ${t('provision_failed')}`); return 1; }
564
+ log(` ${t('switched')}`);
565
+ return 0;
566
+ }
567
+
568
+ async function main(argv) {
569
+ const [sub, arg] = argv;
570
+ if (!sub || sub === 'status') return teamStatus();
571
+ if (sub === 'switch') return teamSwitch(arg);
572
+ console.error(` ${t('usage')}`);
573
+ return 1;
574
+ }
575
+
576
+ function isEntry() {
577
+ try {
578
+ return realpathSync(process.argv[1] || '') === realpathSync(fileURLToPath(import.meta.url));
579
+ } catch {
580
+ return false;
581
+ }
582
+ }
583
+
584
+ if (isEntry()) {
585
+ main(process.argv.slice(2)).then(
586
+ (code) => process.exit(code ?? 0),
587
+ (e) => {
588
+ console.error(` ${e?.message || e}`);
589
+ process.exit(1);
590
+ },
591
+ );
592
+ }
package/bin/seal-open.js CHANGED
@@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url";
20
20
  // 임베드 공개키(spki DER base64). 배포 시 embed-pubkey.js 가 아래 `?? ""` 의 빈 문자열을
21
21
  // env GRANT_ED25519_PUBLIC_KEY_B64 실값으로 치환한다(session-grant.ts 와 동일 패턴/정규식).
22
22
  // 비어 있으면(미배포/미치환) 검증 비활성 → 평문 fallback(무붕괴, 점진 롤아웃 안전).
23
- const GRANT_PUBKEY_B64 = process.env.ROUTINECODE_GRANT_PUBKEY ?? "";
23
+ const GRANT_PUBKEY_B64 = process.env.ROUTINECODE_GRANT_PUBKEY ?? "MCowBQYDK2VwAyEAjuZ6jXHaucTciaaPD/dUQvFOYlhm1gX8wajEAumLqFg=";
24
24
 
25
25
  const GRANT_CACHE = join(homedir(), ".routinecode", "session-grant.json");
26
26
 
@@ -139,7 +139,10 @@ function main() {
139
139
  // 5. 복호 → temp(평문 비영속).
140
140
  try {
141
141
  const plaintext = unseal(readFileSync(sealed, "utf8"), key, pluginRelpath(target));
142
- const rtDir = join(homedir(), ".routinecode", ".rt", randomBytes(8).toString("hex"));
142
+ // 폴더명 '<세션 PID>-<rand>' — cli.sh 가 넘긴 RC_LAUNCH_PID(exec 후 Claude Code 의 PID)로 세션 생존을 판정해
143
+ // 정리한다(hooks/lib/rt_cleanup.py). PID 를 못 받으면 이전 형식(시간 기준 정리).
144
+ const lp = /^\d+$/.test(process.env.RC_LAUNCH_PID || "") ? process.env.RC_LAUNCH_PID + "-" : "";
145
+ const rtDir = join(homedir(), ".routinecode", ".rt", lp + randomBytes(8).toString("hex"));
143
146
  mkdirSync(rtDir, { recursive: true, mode: 0o700 });
144
147
  const outPath = join(rtDir, basename(target));
145
148
  writeFileSync(outPath, plaintext, { encoding: "utf8", mode: 0o600 });
@@ -1,9 +1,11 @@
1
1
  """공유 블록 메시지 생성 (user-prompt-submit.sh, pre-credit-guard.sh에서 공용)
2
2
 
3
- 재충전 모델(2026-09):
4
- 1회차 → 루틴크루 사이트에 자기 경험/인사이트 글쓰기 → 즉시 +50 (우리가 직접 기록, 악용 불가)
5
- 2회차부터 → 개인 추적링크 공유 → 누군가 클릭하면 +50 (플랫폼 무관, 소셜 API 불필요)
6
- 차단 시 1순위 CTA = 온사이트 글쓰기 페이지. 리퍼럴은 재충전 허브에서 2회차부터 노출.
3
+ 충전 사다리(2026-10, 서버 권위 — growth recharge-ladder):
4
+ 1단계 → 홈페이지에 인사이트 글쓰기 → +50 (평생 3회)
5
+ 2단계 → 공유 링크 보내기 → 받는 즉시 +50 (10회), 그 이후 새 방문자당 +50 (무제한)
6
+ (언제든) 크레딧 팩 / Pro
7
+ 훅은 사용자의 현재 단계를 모르므로 1순위 CTA = /recharge (서버 단계를 읽어 지금 할 일 하나를 안내).
8
+ 웹 허브(/recharge)도 같은 단계를 보여준다.
7
9
  """
8
10
 
9
11
  WRITE_URL = "https://routinecode.routinecrew.net/recharge"
@@ -11,29 +13,29 @@ SUBSCRIBE_URL = "https://routinecode.routinecrew.net/subscribe"
11
13
 
12
14
  _MESSAGES = {
13
15
  "en": (
14
- "You're out of today's free Credits. Write one line to recharge +50 instantly:\n"
15
- "{write_url}\n"
16
- "Post it, then type anything here to continue. (/share or /subscribe also work)"
16
+ "You're out of today's free Credits. Type /recharge — it shows the easiest way to refill right now\n"
17
+ "(start with a quick insight on our site, +50).\n"
18
+ "On the web: {write_url} · Unlimited: /subscribe"
17
19
  ),
18
20
  "ko": (
19
- "오늘의 무료 크레딧을 다 썼어요. 글 한 줄 남기면 바로 +50 충전됩니다:\n"
20
- "{write_url}\n"
21
- "작성 후 이 창에 아무거나 입력하면 이어집니다. (/share · /subscribe 도 가능)"
21
+ "오늘의 무료 크레딧을 다 썼어요. /recharge 를 입력하면 지금 가장 쉬운 충전 방법을 바로 안내해 드려요\n"
22
+ "(홈페이지에 인사이트 한 편 쓰기 +50부터).\n"
23
+ "웹에서: {write_url} · 무제한: /subscribe"
22
24
  ),
23
25
  "ja": (
24
- "本日の無料クレジットを使い切りました。一言書けば即 +50 補充:\n"
25
- "{write_url}\n"
26
- "投稿後、ここに何か入力すれば続行します。(/share · /subscribe も可)"
26
+ "本日の無料クレジットを使い切りました。/recharge と入力すると、今いちばん簡単なチャージ方法を案内します\n"
27
+ "(まずはサイトにインサイトを1件 +50)。\n"
28
+ "Webで: {write_url} · 無制限: /subscribe"
27
29
  ),
28
30
  "zh": (
29
- "今天的免费积分已用完。写一句即可立即 +50 充值:\n"
30
- "{write_url}\n"
31
- "发布后在此输入任意内容即可继续。(/share · /subscribe 也可用)"
31
+ "今天的免费积分已用完。输入 /recharge,立即告诉你现在最简单的充值方式\n"
32
+ "(先在网站写一条洞察 +50)。\n"
33
+ "网页: {write_url} · 无限: /subscribe"
32
34
  ),
33
35
  "es": (
34
- "Se acabaron tus Créditos gratis de hoy. Escribe una línea y recarga +50 al instante:\n"
35
- "{write_url}\n"
36
- "Publica, luego escribe algo aquí para continuar. (/share o /subscribe también)"
36
+ "Se acabaron tus Créditos gratis de hoy. Escribe /recharge y te mostramos la forma más fácil de recargar ahora\n"
37
+ "(empieza con un insight en nuestro sitio, +50).\n"
38
+ "En la web: {write_url} · Ilimitado: /subscribe"
37
39
  ),
38
40
  }
39
41