@routinecrew/routinecode 2.31.77 → 2.31.86

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 (244) hide show
  1. package/README.md +2 -2
  2. package/bin/cli.sh +23 -0
  3. package/bin/prompt-vault.dat +1 -0
  4. package/bin/prompt-vault.js +51 -1
  5. package/bin/rc-board.js +58 -0
  6. package/bin/rc-config.js +756 -1
  7. package/bin/rc-credit-turn.js +2 -1
  8. package/bin/rc-grant.js +2 -1
  9. package/bin/rc-login.js +2 -0
  10. package/bin/rc-map.js +132 -0
  11. package/bin/rc-privacy.js +200 -0
  12. package/bin/rc-skills.js +31 -0
  13. package/bin/rc-team.js +2 -1
  14. package/bin/setup.js +4 -0
  15. package/hooks/cc-compat-watch.js +2 -1
  16. package/hooks/claim-questions.json +40 -0
  17. package/hooks/hooks-config.json +108 -1
  18. package/hooks/lib/agent_budget.py +122 -0
  19. package/hooks/lib/agent_telemetry.py +143 -0
  20. package/hooks/lib/attest_reader.py +15 -6
  21. package/hooks/lib/attribution_judge.py +109 -0
  22. package/hooks/lib/board-golden.json +268 -0
  23. package/hooks/lib/board.py +503 -0
  24. package/hooks/lib/board_sync.py +535 -0
  25. package/hooks/lib/cc-surface.json +1 -1
  26. package/hooks/lib/claim_structure.py +412 -0
  27. package/hooks/lib/completion_log.py +12 -5
  28. package/hooks/lib/config_bash_track.py +114 -28
  29. package/hooks/lib/config_guard.py +137 -5
  30. package/hooks/lib/edit_tracker.py +182 -0
  31. package/hooks/lib/error_line.py +94 -0
  32. package/hooks/lib/escalation_restore.py +66 -0
  33. package/hooks/lib/i18n.py +37 -15
  34. package/hooks/lib/knowledge_items.py +1407 -0
  35. package/hooks/lib/knowledge_scope.py +123 -0
  36. package/hooks/lib/known_solution.py +37 -9
  37. package/hooks/lib/log_compact.py +85 -0
  38. package/hooks/lib/metacog_signals.py +228 -0
  39. package/hooks/lib/orch_decision.py +690 -0
  40. package/hooks/lib/premise-golden.json +96 -0
  41. package/hooks/lib/presence.py +10 -3
  42. package/hooks/lib/privacy_log.py +35 -0
  43. package/hooks/lib/receipt.py +137 -14
  44. package/hooks/lib/review_gate.py +83 -0
  45. package/hooks/lib/routine_skill_eval.py +213 -0
  46. package/hooks/lib/secret_filter.py +2 -1
  47. package/hooks/lib/skill_drafts.py +188 -0
  48. package/hooks/lib/sync_manager.py +121 -26
  49. package/hooks/lib/usage_v2.py +680 -0
  50. package/hooks/lib/work_kind.py +198 -0
  51. package/hooks/lib/work_kind_events.py +361 -0
  52. package/hooks/pending-drainer.sh +28 -0
  53. package/hooks/post-agent-budget.sh +50 -0
  54. package/hooks/post-agent-return.sh +89 -3
  55. package/hooks/post-bash-failure.sh +39 -0
  56. package/hooks/post-bash-knowledge.sh +15 -34
  57. package/hooks/post-bash-verify.sh +33 -16
  58. package/hooks/post-build-check.sh +16 -18
  59. package/hooks/post-config-context.sh +13 -0
  60. package/hooks/post-delegation-nudge.sh +12 -1
  61. package/hooks/post-edit-track.sh +19 -28
  62. package/hooks/post-orch-decision.sh +35 -0
  63. package/hooks/post-read-config-context.sh +20 -0
  64. package/hooks/pre-account-guard.sh +1 -1
  65. package/hooks/pre-agent-spawn.mjs +2 -1
  66. package/hooks/pre-agent-spawn.sh +12 -1
  67. package/hooks/pre-bash-guard.sh +61 -3
  68. package/hooks/pre-bash-knowledge.sh +46 -0
  69. package/hooks/pre-credit-guard.sh +1 -1
  70. package/hooks/pre-edit-board.sh +44 -0
  71. package/hooks/pre-edit-check.sh +29 -5
  72. package/hooks/pre-edit-config-gate.sh +1 -1
  73. package/hooks/pre-edit-domain-gate.sh +23 -22
  74. package/hooks/pre-mark-complete.sh +32 -4
  75. package/hooks/pre-read-knowledge-inject.sh +34 -24
  76. package/hooks/pre-review-gate.sh +17 -0
  77. package/hooks/recorder-runner.sh +25 -2
  78. package/hooks/session-start-compact.sh +28 -0
  79. package/hooks/session-start.sh +167 -19
  80. package/hooks/skill-knowledge.sh +37 -0
  81. package/hooks/stop-claim-check.v3.sh +21 -3
  82. package/hooks/stop-usage-metrics.sh +138 -83
  83. package/hooks/subagent-stop-usage.sh +25 -0
  84. package/hooks/user-prompt-submit.sh +10 -4
  85. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  86. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  87. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  88. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  89. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  90. package/mcp-db-manager/dist/index.js +1 -1
  91. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  92. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  93. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  94. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  95. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  96. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  97. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  98. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  99. package/mcp-dev-tester/dist/attestation.js +1 -1
  100. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  101. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  102. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  103. package/mcp-dev-tester/dist/index.js +1 -1
  104. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  105. package/mcp-doc-fetcher/dist/index.js +1 -1
  106. package/mcp-html-renderer/dist/index.js +1 -1
  107. package/mcp-html-renderer/dist/preview.js +1 -1
  108. package/mcp-html-renderer/dist/template-engine.js +1 -1
  109. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  110. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  111. package/mcp-intelligence/dist/config-auth.js +1 -1
  112. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  113. package/mcp-intelligence/dist/domain-templates.js +1 -1
  114. package/mcp-intelligence/dist/grounding.js +1 -1
  115. package/mcp-intelligence/dist/handlers.js +1 -1
  116. package/mcp-intelligence/dist/index.js +1 -1
  117. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  118. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  119. package/mcp-intelligence/dist/knowledge-guide.js +1 -0
  120. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  121. package/mcp-intelligence/dist/knowledge-migrate.js +1 -0
  122. package/mcp-intelligence/dist/knowledge-record.js +1 -0
  123. package/mcp-intelligence/dist/knowledge-scope.js +1 -0
  124. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  125. package/mcp-intelligence/dist/provenance.js +1 -1
  126. package/mcp-intelligence/dist/sanitize.generated.js +242 -0
  127. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  128. package/mcp-log-watcher/dist/config-auth.js +1 -1
  129. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  130. package/mcp-log-watcher/dist/index.js +1 -1
  131. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  132. package/mcp-log-watcher/dist/log-store.js +1 -1
  133. package/mcp-log-watcher/dist/sanitize.generated.js +242 -0
  134. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  135. package/mcp-log-watcher/package.json +1 -1
  136. package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
  137. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  138. package/mcp-plan-manager/dist/file-ops.js +1 -1
  139. package/mcp-plan-manager/dist/index.js +1 -1
  140. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  141. package/mcp-project-context/dist/git-ops.js +1 -1
  142. package/mcp-project-context/dist/index.js +1 -1
  143. package/mcp-project-context/dist/project-analysis.js +1 -1
  144. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  145. package/mcp-routinecode/dist/analysis-ledger.js +590 -0
  146. package/mcp-routinecode/dist/attestation.js +1 -1
  147. package/mcp-routinecode/dist/blast-radius.js +1 -1
  148. package/mcp-routinecode/dist/board.js +1 -0
  149. package/mcp-routinecode/dist/build-id.js +1 -0
  150. package/mcp-routinecode/dist/changeset.js +1 -1
  151. package/mcp-routinecode/dist/config-auth.js +1 -1
  152. package/mcp-routinecode/dist/config-map/applied.js +1 -0
  153. package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
  154. package/mcp-routinecode/dist/config-map/architect-store.js +1132 -1
  155. package/mcp-routinecode/dist/config-map/assign.js +1 -1
  156. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  157. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  158. package/mcp-routinecode/dist/config-map/blocks.js +1 -1
  159. package/mcp-routinecode/dist/config-map/briefing.js +541 -1
  160. package/mcp-routinecode/dist/config-map/certify.js +10 -5
  161. package/mcp-routinecode/dist/config-map/const-use.js +1 -1
  162. package/mcp-routinecode/dist/config-map/context.js +219 -0
  163. package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -0
  164. package/mcp-routinecode/dist/config-map/decisions.js +1 -1
  165. package/mcp-routinecode/dist/config-map/decls.js +1 -1
  166. package/mcp-routinecode/dist/config-map/drift.js +1 -1
  167. package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
  168. package/mcp-routinecode/dist/config-map/extract.js +1 -1
  169. package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
  170. package/mcp-routinecode/dist/config-map/gate.js +796 -1
  171. package/mcp-routinecode/dist/config-map/hash.js +1 -1
  172. package/mcp-routinecode/dist/config-map/ident-norm.js +1 -1
  173. package/mcp-routinecode/dist/config-map/index-store.js +1051 -1
  174. package/mcp-routinecode/dist/config-map/light-eval.js +253 -1
  175. package/mcp-routinecode/dist/config-map/link.js +1 -1
  176. package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
  177. package/mcp-routinecode/dist/config-map/lookup.js +1 -1
  178. package/mcp-routinecode/dist/config-map/louvain.js +1 -1
  179. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  180. package/mcp-routinecode/dist/config-map/names.js +1 -1
  181. package/mcp-routinecode/dist/config-map/post-bash-eval.js +105 -0
  182. package/mcp-routinecode/dist/config-map/proposals.js +1 -1
  183. package/mcp-routinecode/dist/config-map/ratchet.js +148 -0
  184. package/mcp-routinecode/dist/config-map/recheck.js +148 -1
  185. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  186. package/mcp-routinecode/dist/config-map/route-security.js +1 -1
  187. package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
  188. package/mcp-routinecode/dist/config-map/scc.js +1 -1
  189. package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
  190. package/mcp-routinecode/dist/config-map/shape.js +1 -1
  191. package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
  192. package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
  193. package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
  194. package/mcp-routinecode/dist/config-map/store.js +1 -1
  195. package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
  196. package/mcp-routinecode/dist/config-map/task-eval.js +369 -1
  197. package/mcp-routinecode/dist/config-map/templates.js +1 -1
  198. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  199. package/mcp-routinecode/dist/coverage.js +1 -1
  200. package/mcp-routinecode/dist/edit-tracker.js +1 -0
  201. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  202. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  203. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  204. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  205. package/mcp-routinecode/dist/index.js +1 -1
  206. package/mcp-routinecode/dist/known-solutions.js +1 -1
  207. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  208. package/mcp-routinecode/dist/normalize-sig.js +1 -0
  209. package/mcp-routinecode/dist/observed-draft.js +1 -1
  210. package/mcp-routinecode/dist/observed-escalation.js +1 -0
  211. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  212. package/mcp-routinecode/dist/route-match.js +1 -1
  213. package/mcp-routinecode/dist/routines.js +1 -1
  214. package/mcp-routinecode/dist/rule-engine.js +1 -1
  215. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  216. package/mcp-routinecode/dist/sanitize.generated.js +242 -0
  217. package/mcp-routinecode/dist/session-registry.js +1 -0
  218. package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
  219. package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
  220. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  221. package/mcp-routinecode/dist/test-runner.js +1 -1
  222. package/mcp-routinecode/dist/verification.js +1 -1
  223. package/mcp-routinecode/dist/viral-loop.js +1 -1
  224. package/mcp-routinecode/package.json +1 -1
  225. package/package.json +3 -3
  226. package/plugin/.claude-plugin/plugin.json +1 -1
  227. package/plugin/agents/analyzer.md.sealed +1 -1
  228. package/plugin/agents/architect.md.sealed +1 -1
  229. package/plugin/agents/crawler.md.sealed +1 -1
  230. package/plugin/agents/explorer.md.sealed +1 -1
  231. package/plugin/agents/implementor.md.sealed +1 -1
  232. package/plugin/agents/looker.md.sealed +1 -1
  233. package/plugin/agents/planner.md.sealed +1 -1
  234. package/plugin/agents/recorder.md.sealed +1 -1
  235. package/plugin/agents/reviewer.md.sealed +1 -1
  236. package/plugin/agents/verifier.md.sealed +1 -1
  237. package/plugin/commands/analyze.md.sealed +1 -1
  238. package/plugin/commands/plan.md.sealed +1 -1
  239. package/plugin/commands/rc.md.sealed +1 -1
  240. package/plugin/commands/receipt.md.sealed +1 -1
  241. package/plugin/commands/recharge.md.sealed +1 -1
  242. package/plugin/commands/routines.md.sealed +1 -1
  243. package/plugin/commands/share.md.sealed +1 -1
  244. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -209,6 +209,7 @@ CORE_PROTECTED_PATH_GLOBS = [
209
209
  '**/routinecode/plugin/commands/*.md',
210
210
  '**/plugin/routinecode-prompt.md',
211
211
  '**/routinecode/bin/prompt-vault.js',
212
+ '**/routinecode/bin/prompt-vault.dat',
212
213
  # RoutineCode MCP 서버 로직(9개) — dist 로 배포되는 복제 표적. src 는 dist 미배포라
213
214
  # dev 체크아웃 전용(core_only dev 완화로 면제). 설치본에선 dist 만 존재 → 차단.
214
215
  '**/routinecode/mcp-*/dist/**',
@@ -288,7 +289,7 @@ CORE_PROTECTED_COMMAND_PATTERNS = [
288
289
  # 명령은 영향받지 않는다.
289
290
  r'(?:cat|head|tail|less|more|sed|awk|grep|strings|xxd|hexdump|base64|nl|od|python3?\s+-c|node\s+-e)\s+[^|&;]*routinecode[/\\]hooks[/\\]',
290
291
  r'(?:cat|head|tail|less|more|sed|awk|grep|strings|xxd|hexdump|base64|nl|od)\s+[^|&;]*routinecode[/\\]plugin[/\\]',
291
- r'(?:cat|head|tail|less|more|strings|xxd|base64)\s+[^|&;]*routinecode[/\\][^|&;]*prompt-vault\.js',
292
+ r'(?:cat|head|tail|less|more|strings|xxd|base64)\s+[^|&;]*routinecode[/\\][^|&;]*prompt-vault\.(?:js|dat)',
292
293
  r'(?:cat|head|tail|less|more)\s+[^|&;]*\.routinecode[/\\]config\.json',
293
294
  r'\b(?:ls|find)\s+[^|&;]*routinecode[/\\](?:hooks|plugin|mcp-[\w.-]+|engine)\b',
294
295
  # MCP 서버 dist·engine 로직 읽기 차단(프롬프트/훅 외 복제 표적).
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ """skill_drafts — 반복하는 일마다 '스킬 재료'를 모은다 (docs/지식체계/40 §4.8, 화면 ① '한 번에 스킬로 만들기').
3
+
4
+ - 재료 = 그 일 종류(work_kind 키)가 나온 최근 세션들의 명령 순서 + 실패한 명령과 오류 첫 줄 + 요청 예.
5
+ AI 가 스킬을 만들 때 대화 기록을 처음부터 다시 뒤지지 않게 한다. 규칙으로만 모은다(LLM 0).
6
+ - 내 컴퓨터에만 둔다: ~/.routinecode/knowledge/<계정>/skill-drafts/<fk>.json + index.json. 서버로 보내지 않는다.
7
+ - 명령·오류는 비밀값 가림(work_kind_events.mask_example 규칙 + secret_filter) 후 400자/200자로 자른다.
8
+
9
+ CLI: python3 skill_drafts.py [--write]
10
+ """
11
+ import glob
12
+ import json
13
+ import os
14
+ import re
15
+ import sys
16
+ import time
17
+ from datetime import datetime, timezone
18
+
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+ import work_kind as wk # noqa: E402
21
+ import work_kind_events as wke # noqa: E402
22
+
23
+ LOOKBACK_DAYS = 28
24
+ RUNS_KEEP = 4 # 종류마다 최근 세션 몇 개를 남길지
25
+ STEPS_MAX = 40 # 세션 하나에서 남길 명령 수
26
+ CMD_MAX = 400
27
+ ERR_MAX = 200
28
+ REFRESH_SEC = 6 * 3600
29
+ DIR_NAME = 'skill-drafts'
30
+
31
+
32
+ def _mask(t, n):
33
+ t = str(t or '')
34
+ for rx in wke._MASKS:
35
+ t = rx.sub('<가림>', t)
36
+ try:
37
+ import secret_filter as sf
38
+ t, _ = sf.redact(t)
39
+ except Exception:
40
+ pass
41
+ return t[:n]
42
+
43
+
44
+ def _result_text(b):
45
+ c = b.get('content')
46
+ if isinstance(c, list):
47
+ c = ' '.join(x.get('text', '') for x in c if isinstance(x, dict))
48
+ return str(c or '')
49
+
50
+
51
+ def session_steps(path):
52
+ """transcript → (cwd, {종류 키: {'steps': [...], 'example': str|None, 'at': iso}}). 대화형(cli) 아니면 None."""
53
+ inter, cwd, last_prompt = None, None, None
54
+ calls, errs = {}, {}
55
+ try:
56
+ fh = open(path, errors='replace')
57
+ except OSError:
58
+ return None
59
+ with fh:
60
+ for line in fh:
61
+ try:
62
+ e = json.loads(line)
63
+ except Exception:
64
+ continue
65
+ if e.get('isSidechain'):
66
+ continue
67
+ if cwd is None and e.get('cwd'):
68
+ cwd = e.get('cwd')
69
+ if e.get('type') == 'user':
70
+ if inter is None and e.get('entrypoint'):
71
+ inter = e.get('entrypoint') == 'cli'
72
+ ct = e.get('message', {}).get('content')
73
+ if isinstance(ct, list):
74
+ for b in ct:
75
+ if isinstance(b, dict) and b.get('type') == 'tool_result' and b.get('tool_use_id') in calls and b.get('is_error'):
76
+ errs[b['tool_use_id']] = _result_text(b).strip().split('\n')[0]
77
+ if not e.get('isMeta'):
78
+ txt = wke._prompt_text(ct)
79
+ if txt and not (isinstance(ct, list) and any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in ct)):
80
+ last_prompt = txt
81
+ continue
82
+ if e.get('type') != 'assistant':
83
+ continue
84
+ for b in (e.get('message', {}).get('content') or []):
85
+ if not (isinstance(b, dict) and b.get('type') == 'tool_use' and b.get('name') == 'Bash'):
86
+ continue
87
+ cmd = (b.get('input') or {}).get('command', '')
88
+ k = wk.classify(cmd)
89
+ if k['action'] not in wke.WORK_ACTIONS or k['group'] not in ('remote', 'local'):
90
+ continue
91
+ if k['group'] == 'local' and (not k.get('target') or k['target'] == '-') and cwd:
92
+ k = dict(k, target=wke._repo_name(cwd))
93
+ calls[b.get('id')] = (wk.kind_key(k), cmd, wke.mask_example(last_prompt), e.get('timestamp'))
94
+ if not inter:
95
+ return None
96
+ out = {}
97
+ for tid, (key, cmd, ex, ts) in calls.items():
98
+ d = out.setdefault(key, {'steps': [], 'example': ex, 'at': ts})
99
+ if len(d['steps']) < STEPS_MAX:
100
+ st = {'cmd': _mask(cmd, CMD_MAX)}
101
+ if tid in errs:
102
+ st['error'] = _mask(errs[tid], ERR_MAX)
103
+ d['steps'].append(st)
104
+ return cwd, {k: v for k, v in out.items() if len(v['steps']) >= wke.MIN_CALLS}
105
+
106
+
107
+ def collect(now=None, projects_glob=None):
108
+ """{종류 키: 재료} — 최근 세션부터 RUNS_KEEP 개."""
109
+ now = now or time.time()
110
+ files = []
111
+ for f in glob.glob(projects_glob or os.path.expanduser('~/.claude/projects/*/*.jsonl')):
112
+ try:
113
+ m = os.path.getmtime(f)
114
+ except OSError:
115
+ continue
116
+ if m >= now - LOOKBACK_DAYS * 86400:
117
+ files.append((m, f))
118
+ files.sort(reverse=True)
119
+ drafts = {}
120
+ for _m, f in files:
121
+ r = session_steps(f)
122
+ if not r:
123
+ continue
124
+ cwd, kinds = r
125
+ for key, d in kinds.items():
126
+ dr = drafts.setdefault(key, {'key': key, 'familyKey': wke.family_key(key), 'sessions': 0, 'examples': [], 'runs': []})
127
+ dr['sessions'] += 1
128
+ if d['example'] and d['example'] not in dr['examples'] and len(dr['examples']) < 3:
129
+ dr['examples'].append(d['example'])
130
+ if len(dr['runs']) < RUNS_KEEP:
131
+ dr['runs'].append({'at': d['at'], 'repo': wke._repo_name(cwd) if cwd else None,
132
+ 'errors': sum(1 for s in d['steps'] if 'error' in s), 'steps': d['steps']})
133
+ for dr in drafts.values():
134
+ k = dr['key'].split(':')
135
+ dr['label'] = '%s · %s' % (k[1] if len(k) > 2 else '-', k[-1])
136
+ return drafts
137
+
138
+
139
+ def write(acct=None, now=None, force=False, projects_glob=None):
140
+ import knowledge_items as ki
141
+ now = now or time.time()
142
+ a = acct if acct is not None else ki._ks().account()
143
+ d = ki.account_path(a, DIR_NAME)
144
+ if not d:
145
+ return None
146
+ idx_p = os.path.join(d, 'index.json')
147
+ if not force:
148
+ try:
149
+ if now - os.path.getmtime(idx_p) < REFRESH_SEC:
150
+ return None
151
+ except OSError:
152
+ pass
153
+ drafts = collect(now, projects_glob)
154
+ try:
155
+ import routine_skill_eval as rse
156
+ skills = rse.skill_dirs()
157
+ except Exception:
158
+ skills = {}
159
+ os.makedirs(d, exist_ok=True)
160
+ index = []
161
+ for key, dr in sorted(drafts.items(), key=lambda kv: -kv[1]['sessions']):
162
+ covered = sorted(n for n, c in skills.items() if _matches(c.get('replaces'), key))
163
+ dr['skills'] = covered
164
+ p = os.path.join(d, dr['familyKey'] + '.json')
165
+ with open(p + '.tmp', 'w') as fh:
166
+ json.dump(dr, fh, ensure_ascii=False, indent=1)
167
+ os.replace(p + '.tmp', p)
168
+ index.append({'familyKey': dr['familyKey'], 'key': key, 'label': dr['label'], 'sessions': dr['sessions'], 'skills': covered,
169
+ 'file': os.path.basename(p)})
170
+ with open(idx_p + '.tmp', 'w') as fh:
171
+ json.dump({'updated': datetime.fromtimestamp(now, timezone.utc).isoformat(), 'kinds': index}, fh, ensure_ascii=False, indent=1)
172
+ os.replace(idx_p + '.tmp', idx_p)
173
+ return {'dir': d, 'kinds': len(index)}
174
+
175
+
176
+ def _matches(rx, key):
177
+ try:
178
+ return bool(rx) and re.search(rx, key) is not None
179
+ except re.error:
180
+ return False
181
+
182
+
183
+ if __name__ == '__main__':
184
+ if '--write' in sys.argv:
185
+ print(json.dumps(write(force=True), ensure_ascii=False))
186
+ else:
187
+ dr = collect()
188
+ print(json.dumps({'kinds': len(dr), 'top': [(v['label'], v['sessions'], len(v['runs'])) for v in sorted(dr.values(), key=lambda x: -x['sessions'])[:8]]}, ensure_ascii=False))
@@ -13,17 +13,25 @@ Usage sync manager: 로컬 이벤트를 growth-backend로 동기화.
13
13
  - 400 = pending-quarantine.jsonl 격리(드롭 금지). 429/503 = 잔여 배치 즉시
14
14
  중단. 적응형 배치 축소.
15
15
  - remote-flags `raw_events_enabled` 게이트 = sync 억제(emit 억제 아님):
16
- 로컬 적재 무조건, off/부재면 신규 8종 전송 제외 + 해당 커서 비전진.
16
+ 로컬 적재 무조건, off/부재면 신규 8종을 withheld-raw.jsonl 로 옮기고 커서는 전진
17
+ (커서를 묶어두면 같은 일반 이벤트가 매번 재전송된다, 설계 15 §2.2). on 이면 보류분 전송.
17
18
  """
18
19
 
19
20
  import json, os, time, urllib.request, urllib.error
20
21
  from datetime import datetime, timezone
21
22
 
23
+ try:
24
+ from privacy_log import log_transmission
25
+ except Exception:
26
+ def log_transmission(url, body):
27
+ pass
28
+
22
29
  CONFIG_PATH = os.path.expanduser("~/.routinecode/config.json")
23
30
  EVENTS_PATH = os.path.expanduser("~/.routinecode/usage/events.jsonl")
24
31
  COHORT_PATH = os.path.expanduser("~/.routinecode/usage/cohort.json")
25
32
  PENDING_PATH = os.path.expanduser("~/.routinecode/usage/pending-sync.jsonl")
26
33
  QUARANTINE_PATH = os.path.expanduser("~/.routinecode/usage/pending-quarantine.jsonl")
34
+ WITHHELD_PATH = os.path.expanduser("~/.routinecode/usage/withheld-raw.jsonl")
27
35
  SYNC_STATE_PATH = os.path.expanduser("~/.routinecode/usage/sync-state.json")
28
36
  SYNC_LOG_PATH = os.path.expanduser("~/.routinecode/usage/sync.log")
29
37
  SYNC_LOCK_PATH = os.path.expanduser("~/.routinecode/usage/sync.lock")
@@ -38,6 +46,10 @@ CURSOR_VERSION = 2
38
46
  LOCK_TTL = 600 # 10 min stale lock cleanup
39
47
  BATCH_MAX = 500
40
48
  BATCH_MIN = 50 # 적응형 축소 하한
49
+ WITHHELD_MAX_LINES = 20000 # 보류 파일 상한(오래된 줄부터 버림)
50
+ USAGE_VERSION = 2
51
+ # 이중 합산 영향이 있는 타입은 만든 쪽에서 표시한 이벤트만 v2 다. 큐에 남은 구버전 이벤트를 v2 로 올리면 안 된다.
52
+ USAGE_VERSION_AT_SOURCE = frozenset({"tokens", "agent_spawn", "session_start", "session_end"})
41
53
 
42
54
  # 05 §2 신규 8종 — remote-flags raw_events_enabled 게이트 대상.
43
55
  # + 설계 10 형상관리 3종(config_task_summary·config_wired·config_activity) — 방출 자체가 타입 플래그
@@ -136,6 +148,7 @@ def _release_lock():
136
148
 
137
149
  def _post(base_url, api_key, path, body):
138
150
  url = f"{base_url}/api/v1/growth-proxy{path}"
151
+ log_transmission(url, body)
139
152
  data = json.dumps(body).encode()
140
153
  req = urllib.request.Request(url, data=data, headers={
141
154
  "Content-Type": "application/json",
@@ -335,6 +348,56 @@ def _write_pending(events):
335
348
  _append_jsonl(PENDING_PATH, events)
336
349
 
337
350
 
351
+ def _withhold(events):
352
+ """raw off 기간의 이벤트를 보류 파일로 옮긴다. 커서는 호출부가 전진시킨다."""
353
+ if not events:
354
+ return
355
+ _append_jsonl(WITHHELD_PATH, events)
356
+ try:
357
+ with open(WITHHELD_PATH) as f:
358
+ lines = f.readlines()
359
+ if len(lines) > WITHHELD_MAX_LINES:
360
+ tmp = WITHHELD_PATH + ".tmp"
361
+ with open(tmp, "w") as f:
362
+ f.writelines(lines[-WITHHELD_MAX_LINES:])
363
+ os.replace(tmp, WITHHELD_PATH)
364
+ except Exception:
365
+ pass
366
+
367
+
368
+ def _read_withheld():
369
+ """보류 파일을 꺼낸다. 파일은 남긴다: 전송 결과가 저장된 뒤 _clear_withheld 가 지운다.
370
+ 그 사이 죽으면 다음 sync 가 .processing 을 다시 읽고, 서버는 멱등 키로 중복을 흡수한다."""
371
+ processing = WITHHELD_PATH + ".processing"
372
+ events = []
373
+ try:
374
+ if not os.path.exists(processing):
375
+ os.rename(WITHHELD_PATH, processing)
376
+ except FileNotFoundError:
377
+ return []
378
+ except Exception:
379
+ return []
380
+ try:
381
+ with open(processing) as f:
382
+ for ln in f:
383
+ ln = ln.strip()
384
+ if ln:
385
+ try:
386
+ events.append(json.loads(ln))
387
+ except Exception:
388
+ continue
389
+ except Exception:
390
+ pass
391
+ return events
392
+
393
+
394
+ def _clear_withheld():
395
+ try:
396
+ os.remove(WITHHELD_PATH + ".processing")
397
+ except OSError:
398
+ pass
399
+
400
+
338
401
  def _quarantine(events):
339
402
  """400 배치 격리 — 드롭 금지(사후 진단·재처리 여지). 용량 상한 유지."""
340
403
  if not events:
@@ -526,8 +589,15 @@ def _transform(e, user_id, tenant_id=None):
526
589
  # Attribution Contract: usage = tenantId + personId 태깅
527
590
  if tenant_id is not None:
528
591
  metadata["tenant_id"] = tenant_id
592
+ if event_type in USAGE_VERSION_AT_SOURCE:
593
+ if e.get("usage_version"):
594
+ metadata["usage_version"] = e["usage_version"]
595
+ else:
596
+ metadata["usage_version"] = USAGE_VERSION
529
597
  if event_type == "tokens":
530
- for k in ("input_tokens", "output_tokens", "cache_read_tokens", "cache_create_tokens", "total_tokens", "assistant_calls", "mcp_calls", "mcp_calls_by_server"):
598
+ for k in ("input_tokens", "output_tokens", "cache_read_tokens", "cache_create_tokens", "total_tokens", "assistant_calls", "mcp_calls", "mcp_calls_by_server",
599
+ "by_model", "avoided_reread_tokens", "avoided_by_model", "savings_formula", "savings_partial",
600
+ "routine_skills"): # 설계 40 §4.8 — 라벨·숫자만(명령 원문 없음)
531
601
  if k in e:
532
602
  metadata[k] = e[k]
533
603
  elif event_type == "turn":
@@ -535,7 +605,8 @@ def _transform(e, user_id, tenant_id=None):
535
605
  if k in e:
536
606
  metadata[k] = e[k]
537
607
  elif event_type in ("session_start", "session_end"):
538
- for k in ("version", "platform", "machineId", "duration_sec", "total_turns"):
608
+ for k in ("version", "platform", "machineId", "duration_sec", "total_turns",
609
+ "start_source", "run_key", "id_source"):
539
610
  if k in e.get("metadata", {}):
540
611
  metadata[k] = e["metadata"][k]
541
612
  elif event_type == "tool_call":
@@ -547,7 +618,10 @@ def _transform(e, user_id, tenant_id=None):
547
618
  # 토큰 5키는 growth usage.dto METADATA_ALLOWED_KEYS에 이미 수용됨(서버 변경 불요).
548
619
  for k in ("agent_type", "action", "duration_sec",
549
620
  "input_tokens", "output_tokens", "cache_read_tokens",
550
- "cache_create_tokens", "total_tokens"):
621
+ "cache_create_tokens", "total_tokens",
622
+ # 설계 15 §2.4 구간 증분 집계
623
+ "agent_id", "isolated_tokens", "by_model", "is_fork",
624
+ "parent_agent_id", "assistant_calls", "id_source"):
551
625
  if k in e.get("metadata", {}):
552
626
  metadata[k] = e["metadata"][k]
553
627
  elif event_type == "build_result":
@@ -566,13 +640,29 @@ def _transform(e, user_id, tenant_id=None):
566
640
  if k in src_meta:
567
641
  metadata[k] = src_meta[k]
568
642
 
643
+ idempotency_key = f"{user_id}:{session}:{at}:{event_type}"
644
+ # 토큰·턴은 Stop 구간 증분이다. at 은 재실행마다 달라지므로 구간 시작 커서를 키로 쓴다(growth DTO 100자 이내).
645
+ if event_type in ("tokens", "session_end") and e.get("cursor") is not None:
646
+ idempotency_key = f"{user_id}:{session}:{event_type}:{e['cursor']}"
647
+ if event_type == "tokens":
648
+ value = e.get("total_tokens", 1)
649
+ elif event_type == "agent_spawn":
650
+ # cost 0 이 value 로 넘어가면 일별 agent_spawns 가 0 으로 남는다.
651
+ value = 1
652
+ agent_id = metadata.get("agent_id")
653
+ if agent_id and e.get("stop_n") is not None:
654
+ # 재개된 에이전트는 Stop 마다 한 건: 순번이 멱등 키다.
655
+ idempotency_key = f"{user_id}:{session}:agent:{agent_id}:{e['stop_n']}"
656
+ else:
657
+ value = e.get("value", e.get("cost", 1))
658
+
569
659
  return {
570
660
  "eventType": event_type,
571
661
  "eventDate": e.get("date", time.strftime("%Y-%m-%d")),
572
662
  "sessionId": session,
573
- "value": e.get("total_tokens", 1) if event_type == "tokens" else e.get("value", e.get("cost", 1)),
663
+ "value": value,
574
664
  "metadata": metadata,
575
- "idempotencyKey": f"{user_id}:{session}:{at}:{event_type}",
665
+ "idempotencyKey": idempotency_key,
576
666
  "at": at,
577
667
  }
578
668
 
@@ -604,7 +694,8 @@ def sync():
604
694
  cfg = _load_config()
605
695
 
606
696
  # opt-out: telemetryEnabled defaults to True when key is absent
607
- if cfg.get("telemetryEnabled") is False:
697
+ # 환경변수도 presence.py 와 같은 의미로 존중한다. 어느 쪽이든 끄면 사용량을 보내지 않는다.
698
+ if cfg.get("telemetryEnabled") is False or os.environ.get("ROUTINECODE_TELEMETRY", "on").strip().lower() == "off":
608
699
  _log_sync("skip:opt-out")
609
700
  return {"status": "skip", "reason": "opt-out"}
610
701
 
@@ -652,17 +743,19 @@ def _sync_locked(cfg, user_id, base_url, api_key):
652
743
  excluded_runner += excluded_pending
653
744
 
654
745
  # ── 게이트: raw_events off면 신규 8종은 전송 제외(로컬 적재는 이미 됨) ──
655
- # off 기간엔 신규 8종을 sync 대상에서 빼고, 커서를 그 이벤트 뒤로 전진시키지
656
- # 않는다 → off 기간 데이터 보존. 여기선 "전송 유보 잔여 존재" 여부만 판정해
657
- # rotation 보류에 쓴다(커서는 전 라인 전진하되 rotation만 보류).
658
- withheld_new = 0
746
+ # off 기간 이벤트는 withheld-raw.jsonl 로 옮기고 커서는 전진시킨다. 커서를 묶어두면 같은
747
+ # 일반 이벤트가 매 sync 마다 재전송된다. on 이면 보류분을 이번 전송에 합친다.
748
+ withheld_events = []
659
749
  to_send_new = []
660
750
  for e in new_events:
661
751
  et = e.get("type", "turn")
662
752
  if (not raw_enabled) and et in RAW_EVENT_TYPES:
663
- withheld_new += 1
753
+ withheld_events.append(e)
664
754
  continue
665
755
  to_send_new.append(e)
756
+ withheld_new = len(withheld_events)
757
+ if raw_enabled:
758
+ to_send_new = _read_withheld() + to_send_new
666
759
 
667
760
  all_events = []
668
761
  for e in pending:
@@ -676,16 +769,20 @@ def _sync_locked(cfg, user_id, base_url, api_key):
676
769
  all_events.append(_transform(e, user_id, tenant_id))
677
770
 
678
771
  if not all_events:
772
+ if raw_enabled:
773
+ _clear_withheld()
679
774
  try:
680
775
  _sync_cohort(base_url, api_key, user_id)
681
776
  except _AuthFailed:
682
777
  _note_auth_failure("sync")
683
778
  _log_sync("skip:auth-failed-401-cohort")
684
779
  return {"status": "auth_failed"}
685
- # 신규 이벤트 전량이 게이트로 유보됐어도, 기존 이벤트가 없으면 커서만 판단.
686
- # 커서 전진: raw off면 withheld는 커서 비전진(off 기간 보존).
687
- if raw_enabled and new_offset > 0 and inode is not None:
780
+ # 신규 이벤트 전량이 게이트로 유보돼도 보류 파일로 옮겼으니 커서는 전진한다.
781
+ if new_offset > 0 and inode is not None:
782
+ _withhold(withheld_events)
688
783
  _save_cursor(new_offset, inode)
784
+ # 전송할 것이 없어도 플래그는 받는다: 원격 롤백이 조용한 세션에도 닿아야 한다.
785
+ _sync_features(base_url, api_key)
689
786
  _log_sync("skip:no-events")
690
787
  return {"status": "skip", "reason": "no events", "withheld": withheld_new, "excludedRunner": excluded_runner}
691
788
 
@@ -736,6 +833,9 @@ def _sync_locked(cfg, user_id, base_url, api_key):
736
833
  _write_pending(failed)
737
834
  if quarantined:
738
835
  _quarantine(quarantined)
836
+ # 이 시점에 보류분은 서버에 갔거나 pending·quarantine 에 저장됐다.
837
+ if raw_enabled:
838
+ _clear_withheld()
739
839
 
740
840
  if auth_failed:
741
841
  _note_auth_failure("sync")
@@ -746,20 +846,15 @@ def _sync_locked(cfg, user_id, base_url, api_key):
746
846
  return {"status": "backoff", "accepted": total_accepted, "failed": len(failed)}
747
847
 
748
848
  # 커서 전진 + rotation.
749
- # - raw off로 유보된 신규 8종이 있으면(withheld>0): 커서를 new_offset으로
750
- # 전진시키지 않는다(off 기간 보존). rotation도 보류.
849
+ # - raw off: 유보분을 보류 파일로 옮긴 뒤 커서만 전진. events.jsonl 은 로컬 소비자
850
+ # (resolution 귀속 등)가 읽으므로 자르지 않는다.
851
+ # - raw on: 전 라인 sync 완료 → 커서 전진 후 rotation(절단).
751
852
  # - 전송 실패(failed)가 있으면 커서 미전진(다음 세션 재시도, 단 pending에 이미 보존).
752
853
  if new_offset > 0 and inode is not None and not failed:
753
- if raw_enabled and withheld_new == 0:
754
- # 전 라인 sync 완료 → 커서 전진 후 rotation(절단).
755
- _save_cursor(new_offset, inode)
854
+ _withhold(withheld_events)
855
+ _save_cursor(new_offset, inode)
856
+ if raw_enabled:
756
857
  _rotate_synced(new_offset, inode, unsynced_remaining=False)
757
- elif withheld_new == 0:
758
- # raw off인데 신규 8종이 아예 없던 케이스 → 안전하게 전진.
759
- _save_cursor(new_offset, inode)
760
- else:
761
- # 유보 잔여 존재 → 커서 비전진(off 기간 데이터 보존).
762
- pass
763
858
 
764
859
  try:
765
860
  _sync_cohort(base_url, api_key, user_id)