@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
@@ -0,0 +1,680 @@
1
+ #!/usr/bin/env python3
2
+ """CLI 계측 v2 공용 라이브러리 (설계: docs2/지능개선/new/15 §2.1~2.5).
3
+
4
+ Stop·SubagentStop·PostToolUse(Agent) 훅이 같은 집계 규칙을 쓰도록 한곳에 둔다.
5
+
6
+ 규칙 요약
7
+ - 토큰은 message.id 단위 1회. 같은 id 는 필드별 최대값. Stop 구간을 넘는 id 는 커서의
8
+ seen 으로 이어서 차이만 더한다.
9
+ - 절감은 "복귀 신호 이후 메인이 다시 읽지 않아도 된 서브에이전트 맥락"의 하한 재료만 낸다.
10
+ 달러 계산은 서버 몫이다.
11
+ - 상태 파일은 쓰기 주체를 나눈다: pending/ 은 SubagentStop 만, state.json 은 Stop 만.
12
+ - 훅은 실패해도 세션을 막지 않는다(fail-open). 모든 진입점은 예외를 밖으로 올리지 않거나
13
+ 호출부가 try 로 감싼다.
14
+
15
+ transcript 내용(프롬프트·응답 본문)은 이 모듈 밖으로 나가지 않는다. 파일에 남는 것은 message.id·
16
+ 토큰 수·모델 이름·agent id 뿐이다.
17
+ """
18
+ import json
19
+ import os
20
+ import re
21
+ import sys
22
+ import time
23
+
24
+ USAGE_VERSION = 2
25
+ SAVINGS_FORMULA = 2
26
+ ISO_CAP = 200000 # 설계 §2.5 초기값. G2 결과로 조정한다.
27
+ SEEN_KEEP = 400 # 커서에 남길 최근 message.id 수. 같은 id 는 인접해서 반복된다.
28
+ SYNTHETIC_MODEL = '<synthetic>'
29
+ # 원격 롤백 플래그: true 면 새 계산을 멈추고 v1 경로로 돌아간다(_sync_features 가 내려받음).
30
+ FLAG_V2_OFF = 'usage_metrics_v2_off'
31
+ FLAG_SAVINGS_DISPLAY = 'savings_display_v2'
32
+
33
+ _FIELDS = ('in', 'out', 'cr', 'cc5m', 'cc1h')
34
+ # 실측: 에이전트 파일명은 a + 16 hex. 알림의 task-id 는 같은 값이고, 비에이전트 task 는 9자라 걸러진다.
35
+ _AGENT_ID_RE = re.compile(r'^a[a-z0-9_-]*[0-9a-f]{16}$')
36
+ _TAG_RE = {k: re.compile('<%s>(.*?)</%s>' % (k, k), re.S)
37
+ for k in ('task-id', 'output-file', 'tool-use-id')}
38
+
39
+
40
+ # ── 경로 ──
41
+
42
+ def rundir():
43
+ return os.environ.get('RC_RUNDIR') or os.environ.get('XDG_RUNTIME_DIR') \
44
+ or os.path.join(os.path.expanduser('~'), '.' + 'routinecode', 'run')
45
+
46
+
47
+ def _flags_path():
48
+ return os.path.join(os.path.expanduser('~'), '.' + 'routinecode', 'remote-flags.json')
49
+
50
+
51
+ def _events_path():
52
+ return os.path.join(os.path.expanduser('~'), '.' + 'routinecode', 'usage', 'events.jsonl')
53
+
54
+
55
+ def session_dir(sid):
56
+ return os.path.join(rundir(), 'savings', sid)
57
+
58
+
59
+ def state_path(sid):
60
+ return os.path.join(session_dir(sid), 'state.json')
61
+
62
+
63
+ def pending_dir(sid):
64
+ return os.path.join(session_dir(sid), 'pending')
65
+
66
+
67
+ def agent_cursor_path(sid, agent_id):
68
+ return os.path.join(session_dir(sid), 'agents', agent_id + '.json')
69
+
70
+
71
+ def run_file_path(sid):
72
+ return os.path.join(rundir(), 'run-%s.json' % sid)
73
+
74
+
75
+ def launch_file_path(sid):
76
+ return os.path.join(rundir(), 'launch-%s' % sid)
77
+
78
+
79
+ # ── 플래그·입출력 ──
80
+
81
+ def flag(name, default=False):
82
+ try:
83
+ with open(_flags_path()) as f:
84
+ data = json.load(f)
85
+ flags = data.get('flags', {}) if isinstance(data, dict) else {}
86
+ return bool(flags.get(name, default))
87
+ except Exception:
88
+ return default
89
+
90
+
91
+ def v2_enabled():
92
+ return not flag(FLAG_V2_OFF, False)
93
+
94
+
95
+ def _read_json(path, default=None):
96
+ try:
97
+ with open(path) as f:
98
+ return json.load(f)
99
+ except Exception:
100
+ return default
101
+
102
+
103
+ def _write_json(path, obj):
104
+ """임시 파일 + rename. 다른 훅이 절반 쓰인 파일을 읽지 않게 한다."""
105
+ os.makedirs(os.path.dirname(path), exist_ok=True)
106
+ tmp = '%s.%d.tmp' % (path, os.getpid())
107
+ with open(tmp, 'w') as f:
108
+ json.dump(obj, f, ensure_ascii=False)
109
+ os.replace(tmp, path)
110
+
111
+
112
+ def load_jsonl(path):
113
+ out = []
114
+ try:
115
+ with open(path, errors='replace') as f:
116
+ for ln in f:
117
+ ln = ln.strip()
118
+ if not ln:
119
+ continue
120
+ try:
121
+ o = json.loads(ln)
122
+ except Exception:
123
+ continue
124
+ if isinstance(o, dict):
125
+ out.append(o)
126
+ except Exception:
127
+ return []
128
+ return out
129
+
130
+
131
+ def append_event(event):
132
+ """events.jsonl append. 실패해도 조용히 넘어간다."""
133
+ try:
134
+ p = _events_path()
135
+ os.makedirs(os.path.dirname(p), exist_ok=True)
136
+ with open(p, 'a') as f:
137
+ f.write(json.dumps(event, ensure_ascii=False) + '\n')
138
+ return True
139
+ except Exception:
140
+ return False
141
+
142
+
143
+ # ── 메시지 집계 ──
144
+
145
+ def _int(v):
146
+ return v if isinstance(v, int) and not isinstance(v, bool) and v > 0 else 0
147
+
148
+
149
+ def usage_fields(u):
150
+ """Anthropic usage → [in, out, cr, cc5m, cc1h]. 캐시 쓰기는 cache_creation 하위 필드로 나눈다."""
151
+ if not isinstance(u, dict):
152
+ return [0, 0, 0, 0, 0]
153
+ total_cc = _int(u.get('cache_creation_input_tokens'))
154
+ cc = u.get('cache_creation')
155
+ cc5, cc1 = 0, 0
156
+ if isinstance(cc, dict):
157
+ cc5 = _int(cc.get('ephemeral_5m_input_tokens'))
158
+ cc1 = _int(cc.get('ephemeral_1h_input_tokens'))
159
+ # 하위 필드가 없거나 합이 모자라면 나머지는 5분으로 둔다(서버가 더 낮은 단가를 쓰는 쪽).
160
+ if cc5 + cc1 < total_cc:
161
+ cc5 += total_cc - (cc5 + cc1)
162
+ return [_int(u.get('input_tokens')), _int(u.get('output_tokens')),
163
+ _int(u.get('cache_read_input_tokens')), cc5, cc1]
164
+
165
+
166
+ def message_key(e):
167
+ msg = e.get('message')
168
+ mid = msg.get('id') if isinstance(msg, dict) else None
169
+ return mid if isinstance(mid, str) and mid else e.get('uuid')
170
+
171
+
172
+ def collapse(entries):
173
+ """assistant entry 들을 message.id 로 묶는다. 같은 id 는 필드별 최대값, 첫 등장 순서 유지."""
174
+ out = {}
175
+ for e in entries:
176
+ if e.get('type') != 'assistant':
177
+ continue
178
+ msg = e.get('message')
179
+ if not isinstance(msg, dict) or not isinstance(msg.get('usage'), dict):
180
+ continue
181
+ key = message_key(e)
182
+ if not key:
183
+ continue
184
+ vals = usage_fields(msg.get('usage'))
185
+ model = msg.get('model') if isinstance(msg.get('model'), str) else ''
186
+ cur = out.get(key)
187
+ if cur is None:
188
+ out[key] = {'f': vals, 'model': model}
189
+ else:
190
+ cur['f'] = [max(a, b) for a, b in zip(cur['f'], vals)]
191
+ if model and (not cur['model'] or cur['model'] == SYNTHETIC_MODEL):
192
+ cur['model'] = model
193
+ return out
194
+
195
+
196
+ def _model_counted(m):
197
+ return bool(m['model']) and m['model'] != SYNTHETIC_MODEL and any(m['f'])
198
+
199
+
200
+ def apply_increment(msgs, seen):
201
+ """seen 대비 증분을 계산하고 seen 을 갱신한다.
202
+ 반환 {totals:[5], calls:int, by_model:{model:{in,out,cr,cc5m,cc1h}}}. calls 는 고유 메시지 수."""
203
+ totals = [0, 0, 0, 0, 0]
204
+ calls = 0
205
+ by_model = {}
206
+ for key, m in msgs.items():
207
+ old = seen.get(key)
208
+ if not (isinstance(old, list) and len(old) == 5):
209
+ old = None
210
+ base = old or [0, 0, 0, 0, 0]
211
+ delta = [max(0, a - b) for a, b in zip(m['f'], base)]
212
+ # 첫 줄 usage 가 0 이면 seen 에 0 으로 남는다. 다음 구간에서 값이 생길 때 한 번 센다.
213
+ if not any(base) and any(m['f']):
214
+ calls += 1
215
+ if any(delta):
216
+ for i, d in enumerate(delta):
217
+ totals[i] += d
218
+ if _model_counted(m):
219
+ row = by_model.setdefault(m['model'][:64], {k: 0 for k in _FIELDS})
220
+ for i, k in enumerate(_FIELDS):
221
+ row[k] += delta[i]
222
+ seen[key] = [max(a, b) for a, b in zip(m['f'], base)]
223
+ return {'totals': totals, 'calls': calls, 'by_model': by_model}
224
+
225
+
226
+ def trim_seen(seen):
227
+ if len(seen) <= SEEN_KEEP:
228
+ return seen
229
+ return dict(list(seen.items())[-SEEN_KEEP:])
230
+
231
+
232
+ def token_totals(totals):
233
+ """[in,out,cr,cc5m,cc1h] → 이벤트 키"""
234
+ i, o, cr, c5, c1 = totals
235
+ return {'input_tokens': i, 'output_tokens': o, 'cache_read_tokens': cr,
236
+ 'cache_create_tokens': c5 + c1, 'total_tokens': i + o + cr + c5 + c1}
237
+
238
+
239
+ # ── 격리 토큰 ──
240
+
241
+ def _last_assistant_text(entries):
242
+ for e in reversed(entries):
243
+ if e.get('type') != 'assistant':
244
+ continue
245
+ ct = e.get('message', {}).get('content') if isinstance(e.get('message'), dict) else None
246
+ if isinstance(ct, str) and ct.strip():
247
+ return ct
248
+ if isinstance(ct, list):
249
+ parts = [b.get('text') or '' for b in ct if isinstance(b, dict) and b.get('type') == 'text']
250
+ txt = ''.join(parts)
251
+ if txt.strip():
252
+ return txt
253
+ return ''
254
+
255
+
256
+ def isolated_tokens(msgs, summary_text):
257
+ """isolated = max(0, max(context) + 마지막 output - 첫 호출 context - 복귀 요약 토큰).
258
+ 서브에이전트 시작 맥락과 메인으로 돌아간 요약을 빼서 이중 계상을 막는다."""
259
+ ctx = []
260
+ last_out = 0
261
+ for m in msgs.values():
262
+ if not any(m['f']) or m['model'] == SYNTHETIC_MODEL:
263
+ continue
264
+ f = m['f']
265
+ ctx.append(f[0] + f[2] + f[3] + f[4])
266
+ last_out = f[1]
267
+ if not ctx:
268
+ return 0
269
+ return max(0, max(ctx) + last_out - ctx[0] - (len(summary_text or '') // 4))
270
+
271
+
272
+ # ── 서브에이전트 ──
273
+
274
+ def _norm_agent_id(v):
275
+ if not isinstance(v, str):
276
+ return ''
277
+ v = v.strip()
278
+ return v[len('agent-'):] if v.startswith('agent-') else v
279
+
280
+
281
+ def subagents_dir(transcript_path):
282
+ if isinstance(transcript_path, str) and transcript_path.endswith('.jsonl'):
283
+ return transcript_path[:-len('.jsonl')] + '/subagents'
284
+ return ''
285
+
286
+
287
+ def resolve_agent_path(inp):
288
+ """agent_transcript_path 는 일부 모드에서 빈 문자열이다 → 메인 transcript 옆 subagents/ 로 유도."""
289
+ p = inp.get('agent_transcript_path')
290
+ if isinstance(p, str) and p:
291
+ return p
292
+ sub = subagents_dir(inp.get('transcript_path'))
293
+ aid = _norm_agent_id(inp.get('agent_id'))
294
+ return os.path.join(sub, 'agent-%s.jsonl' % aid) if sub and aid else ''
295
+
296
+
297
+ def agent_meta(agent_path):
298
+ meta = _read_json(agent_path[:-len('.jsonl')] + '.meta.json', {}) if agent_path.endswith('.jsonl') else {}
299
+ return meta if isinstance(meta, dict) else {}
300
+
301
+
302
+ def handle_subagent_stop(inp, now=None):
303
+ """SubagentStop 처리: 구간 증분 agent_spawn 이벤트 + pending 마커. 반환 이벤트(없으면 None)."""
304
+ if not v2_enabled():
305
+ return None
306
+ sid_full = inp.get('session_id') or ''
307
+ sid = sid_full[:12]
308
+ path = resolve_agent_path(inp)
309
+ aid = _norm_agent_id(inp.get('agent_id')) or _norm_agent_id(os.path.basename(path)[:-len('.jsonl')])
310
+ if not sid or not aid or not path or not os.path.exists(path):
311
+ return None
312
+
313
+ entries = load_jsonl(path)
314
+ msgs = collapse(entries)
315
+
316
+ cur_path = agent_cursor_path(sid, aid)
317
+ cur = _read_json(cur_path, {})
318
+ cur = cur if isinstance(cur, dict) else {}
319
+ n = cur.get('n') if isinstance(cur.get('n'), int) else 0
320
+ seen = cur.get('seen') if isinstance(cur.get('seen'), dict) else {}
321
+ inc = apply_increment(msgs, seen)
322
+
323
+ meta = agent_meta(path)
324
+ agent_type = inp.get('agent_type') or meta.get('agentType') or 'unknown'
325
+ is_fork = agent_type == 'fork' or meta.get('agentType') == 'fork'
326
+ parent = meta.get('parentAgentId') if isinstance(meta.get('parentAgentId'), str) else None
327
+ depth = meta.get('spawnDepth')
328
+ nested = bool(parent) or (isinstance(depth, int) and depth >= 2)
329
+
330
+ summary = inp.get('last_assistant_message')
331
+ if not isinstance(summary, str) or not summary:
332
+ summary = _last_assistant_text(entries)
333
+ iso = isolated_tokens(msgs, summary)
334
+
335
+ # 재개 시 메인 세션 id 는 훅 입력을 믿되, transcript 상위 폴더와 다르면 진단용으로 남긴다.
336
+ parent_dir = os.path.basename(os.path.dirname(os.path.dirname(path)))
337
+ mismatch = bool(parent_dir) and parent_dir != sid_full
338
+
339
+ event = None
340
+ if n == 0 or any(inc['totals']):
341
+ n += 1
342
+ from datetime import datetime, timezone
343
+ ts = now or datetime.now(timezone.utc)
344
+ md = {'agent_type': agent_type, 'action': 'complete', 'agent_id': aid,
345
+ 'isolated_tokens': iso, 'is_fork': is_fork, 'by_model': inc['by_model'],
346
+ 'assistant_calls': inc['calls']}
347
+ md.update(token_totals(inc['totals']))
348
+ if parent:
349
+ md['parent_agent_id'] = parent
350
+ if mismatch:
351
+ md['id_source'] = 'path_mismatch'
352
+ event = {'at': ts.isoformat(), 'date': ts.strftime('%Y-%m-%d'), 'session': sid,
353
+ 'type': 'agent_spawn', 'cost': 0, 'usage_version': USAGE_VERSION, 'stop_n': n,
354
+ 'cwd': os.path.basename(inp.get('cwd') or os.getcwd()), 'metadata': md}
355
+ append_event(event)
356
+
357
+ prev_total = cur.get('total') if isinstance(cur.get('total'), int) else 0
358
+ total = prev_total + sum(inc['totals'])
359
+ _write_json(cur_path, {'n': n, 'seen': seen, 'total': total})
360
+ # pending 은 마지막에 쓴다 — post-agent-return 이 이 파일을 "계측 끝" 표지로 본다.
361
+ _write_json(os.path.join(pending_dir(sid), aid + '.json'),
362
+ {'tokens': iso, 'tool_use_id': meta.get('toolUseId') or '', 'total_tokens': total,
363
+ 'is_fork': is_fork, 'nested': nested})
364
+ return event
365
+
366
+
367
+ def load_pending(sid):
368
+ out = {}
369
+ try:
370
+ names = os.listdir(pending_dir(sid))
371
+ except Exception:
372
+ return out
373
+ for name in names:
374
+ if name.endswith('.json'):
375
+ p = _read_json(os.path.join(pending_dir(sid), name))
376
+ if isinstance(p, dict):
377
+ out[name[:-len('.json')]] = p
378
+ return out
379
+
380
+
381
+ def is_async_launch(tool_response, tool_input=None):
382
+ """Agent 도구 결과가 백그라운드 시작인가. 근거: CC 2.1.316 tool_response = 도구 결과 객체
383
+ {isAsync:true, status:'async_launched', agentId,...}. 형식이 달라져도 이중 행을 만들지 않게
384
+ status 가 없으면 입력의 run_in_background 와 텍스트까지 본다."""
385
+ if isinstance(tool_response, dict):
386
+ st = tool_response.get('status')
387
+ if st == 'async_launched' or tool_response.get('isAsync') is True:
388
+ return True
389
+ if isinstance(st, str) and st:
390
+ return False
391
+ elif isinstance(tool_response, str) and 'async_launched' in tool_response:
392
+ return True
393
+ return isinstance(tool_input, dict) and tool_input.get('run_in_background') is True
394
+
395
+
396
+ def response_agent_id(tool_response):
397
+ if isinstance(tool_response, dict):
398
+ return _norm_agent_id(tool_response.get('agentId'))
399
+ return ''
400
+
401
+
402
+ def record_launch(sid, agent_id, agent_type):
403
+ """백그라운드 시작 표지. events.jsonl 에 쓰지 않는다: 미등록 타입이라 서버가 400 을 주고,
404
+ 동기화 후 파일이 잘려 위임 넛지가 볼 수 없다."""
405
+ try:
406
+ os.makedirs(rundir(), exist_ok=True)
407
+ with open(launch_file_path(sid), 'a') as f:
408
+ f.write(json.dumps({'at': time.time(), 'agent_id': agent_id, 'agent_type': agent_type}) + '\n')
409
+ except Exception:
410
+ pass
411
+
412
+
413
+ def stop_marker_exists(sid, agent_id, tool_use_id):
414
+ """SubagentStop 이 이미 계측했는가(동기 호출의 agent_spawn 이중 행 방지)."""
415
+ if agent_id and os.path.exists(os.path.join(pending_dir(sid), agent_id + '.json')):
416
+ return True
417
+ if tool_use_id:
418
+ return any(p.get('tool_use_id') == tool_use_id for p in load_pending(sid).values())
419
+ return False
420
+
421
+
422
+ def measure_agent(agent_path):
423
+ """마커가 없는 동기 호출의 기존 경로용: 에이전트 전체를 message.id 기준으로 측정한다."""
424
+ entries = load_jsonl(agent_path)
425
+ msgs = collapse(entries)
426
+ inc = apply_increment(msgs, {})
427
+ return {'tokens': token_totals(inc['totals']), 'by_model': inc['by_model'], 'calls': inc['calls'],
428
+ 'isolated_tokens': isolated_tokens(msgs, _last_assistant_text(entries))}
429
+
430
+
431
+ # ── 복귀 신호 ──
432
+
433
+ def _notification_head(e):
434
+ """시스템 task-notification 의 머리(<result> 앞). 사용자가 붙여넣은 같은 태그는 origin 으로 거른다.
435
+ 실측상 알림은 메시지당 1건이라 첫 알림만 본다. <result> 본문은 절대 파싱하지 않는다.
436
+ 전달 경로가 둘이다: 턴 사이는 user 항목, 턴 도중은 attachment(queued_command)."""
437
+ if e.get('type') == 'attachment':
438
+ a = e.get('attachment')
439
+ if not isinstance(a, dict) or a.get('type') != 'queued_command' \
440
+ or a.get('commandMode') != 'task-notification' or not isinstance(a.get('prompt'), str):
441
+ return ''
442
+ s = a['prompt'].lstrip()
443
+ return s.split('<result>', 1)[0] if s.startswith('<task-notification>') else ''
444
+ origin = e.get('origin')
445
+ if isinstance(origin, dict) and origin.get('kind') != 'task-notification':
446
+ return ''
447
+ msg = e.get('message')
448
+ ct = msg.get('content') if isinstance(msg, dict) else None
449
+ texts = [ct] if isinstance(ct, str) else \
450
+ [b.get('text') or '' for b in ct if isinstance(b, dict) and b.get('type') == 'text'] if isinstance(ct, list) else []
451
+ for t in texts:
452
+ s = t.lstrip()
453
+ if s.startswith('<task-notification>'):
454
+ return s.split('<result>', 1)[0]
455
+ return ''
456
+
457
+
458
+ def return_signals(e):
459
+ """user entry 에서 복귀 후보를 뽑는다. 반환 [(kind, value)] — kind: agent | tool_use."""
460
+ head = _notification_head(e)
461
+ if head:
462
+ out = []
463
+ m = _TAG_RE['task-id'].search(head)
464
+ if m:
465
+ out.append(('agent', _norm_agent_id(m.group(1))))
466
+ m = _TAG_RE['output-file'].search(head)
467
+ if m:
468
+ base = os.path.basename(m.group(1).strip())
469
+ out.append(('agent', _norm_agent_id(base[:-len('.output')] if base.endswith('.output') else base)))
470
+ m = _TAG_RE['tool-use-id'].search(head)
471
+ if m:
472
+ out.append(('tool_use', m.group(1).strip()))
473
+ return out
474
+ if e.get('type') == 'attachment':
475
+ return []
476
+ tur = e.get('toolUseResult')
477
+ if isinstance(tur, dict) and tur.get('agentId'):
478
+ return [] if is_async_launch(tur) else [('agent', _norm_agent_id(tur.get('agentId')))]
479
+ if tur is None:
480
+ msg = e.get('message')
481
+ ct = msg.get('content') if isinstance(msg, dict) else None
482
+ if isinstance(ct, list):
483
+ return [('tool_use', b.get('tool_use_id')) for b in ct
484
+ if isinstance(b, dict) and b.get('type') == 'tool_result' and b.get('tool_use_id')]
485
+ return []
486
+
487
+
488
+ def tool_use_map(entries, pending, sub_dir):
489
+ """tool_use_id → agent id. async_launched 결과·pending·meta.json 순으로 모은다."""
490
+ out = {}
491
+ for e in entries:
492
+ tur = e.get('toolUseResult')
493
+ if isinstance(tur, dict) and tur.get('agentId'):
494
+ msg = e.get('message')
495
+ ct = msg.get('content') if isinstance(msg, dict) else None
496
+ if isinstance(ct, list):
497
+ for b in ct:
498
+ if isinstance(b, dict) and b.get('tool_use_id'):
499
+ out[b['tool_use_id']] = _norm_agent_id(tur.get('agentId'))
500
+ for aid, p in pending.items():
501
+ if p.get('tool_use_id'):
502
+ out.setdefault(p['tool_use_id'], aid)
503
+ try:
504
+ for name in os.listdir(sub_dir) if sub_dir else []:
505
+ if name.endswith('.meta.json'):
506
+ tu = (_read_json(os.path.join(sub_dir, name), {}) or {}).get('toolUseId')
507
+ if tu:
508
+ out.setdefault(tu, _norm_agent_id(name[:-len('.meta.json')]))
509
+ except Exception:
510
+ pass
511
+ return out
512
+
513
+
514
+ def _resolve_return(signals, pending, sub_dir, tool_map):
515
+ """복귀 후보 → (agent id, 에이전트 복귀인가). 비에이전트 task(Bash 등)는 (None, False)."""
516
+ candidates = []
517
+ for kind, val in signals:
518
+ aid = val if kind == 'agent' else (tool_map() or {}).get(val)
519
+ if aid and aid not in candidates:
520
+ candidates.append(aid)
521
+ for aid in candidates:
522
+ if aid in pending or (sub_dir and os.path.exists(os.path.join(sub_dir, 'agent-%s.jsonl' % aid))):
523
+ return aid, True
524
+ for aid in candidates:
525
+ if _AGENT_ID_RE.match(aid):
526
+ return aid, True
527
+ return None, False
528
+
529
+
530
+ def walk_savings(entries, state, pending, prior_ids, sub_dir):
531
+ """Stop 구간 절감 계산. state 를 갱신하고 {model: 토큰} 구간 증분을 돌려준다."""
532
+ open_ = state['open']
533
+ moved = state['moved']
534
+ avoided = {}
535
+ counted = set(prior_ids)
536
+ cache = {}
537
+
538
+ def _map():
539
+ if 'm' not in cache:
540
+ cache['m'] = tool_use_map(entries, pending, sub_dir)
541
+ return cache['m']
542
+
543
+ collapsed = collapse(entries)
544
+ for e in entries:
545
+ if e.get('isCompactSummary'):
546
+ open_ = 0
547
+ continue
548
+ t = e.get('type')
549
+ if t in ('user', 'attachment'):
550
+ signals = return_signals(e)
551
+ if not signals:
552
+ continue
553
+ aid, is_agent = _resolve_return(signals, pending, sub_dir, _map)
554
+ if not is_agent:
555
+ continue
556
+ p = pending.get(aid)
557
+ if p is None or p.get('is_fork') or p.get('nested'):
558
+ state['partial'] = True
559
+ continue
560
+ tok = p.get('tokens') if isinstance(p.get('tokens'), int) else 0
561
+ done = moved.get(aid, 0)
562
+ open_ += max(0, tok - done)
563
+ moved[aid] = max(done, tok)
564
+ elif t == 'assistant':
565
+ key = message_key(e)
566
+ m = collapsed.get(key)
567
+ if m is None or key in counted or not _model_counted(m):
568
+ continue
569
+ counted.add(key)
570
+ if open_ > 0:
571
+ model = m['model'][:64]
572
+ avoided[model] = avoided.get(model, 0) + min(open_, ISO_CAP)
573
+ state['open'] = open_
574
+ return avoided
575
+
576
+
577
+ def load_state(sid):
578
+ st = _read_json(state_path(sid))
579
+ if isinstance(st, dict) and st.get('v') == 2 and isinstance(st.get('moved'), dict) \
580
+ and isinstance(st.get('open'), int):
581
+ st['partial'] = bool(st.get('partial'))
582
+ return st
583
+ # 파일이 없으면 재개·fork 세션도 현재 위치부터 센다. 깨진 파일이면 과거를 잃었으니 partial.
584
+ broken = os.path.exists(state_path(sid))
585
+ return {'v': 2, 'open': 0, 'moved': {}, 'partial': broken}
586
+
587
+
588
+ def _savings_partial(state, pending):
589
+ """지금 시점의 partial. 끝난 판정(state.partial)에 아직 복귀가 안 보인 에이전트를 더한다.
590
+ 후자는 다음 Stop 에서 풀릴 수 있어 서버는 세션의 마지막 이벤트 값을 쓴다."""
591
+ if state.get('partial'):
592
+ return True
593
+ for aid, p in pending.items():
594
+ if p.get('is_fork') or p.get('nested'):
595
+ return True
596
+ tok = p.get('tokens') if isinstance(p.get('tokens'), int) else 0
597
+ if aid not in state['moved'] or tok > state['moved'][aid]:
598
+ return True
599
+ return False
600
+
601
+
602
+ def process_main(new_entries, seen, sid, transcript_path):
603
+ """메인 transcript 신규 구간 집계. seen 은 호출 성공 시에만 호출부가 저장한다."""
604
+ prior_ids = set(seen)
605
+ msgs = collapse(new_entries)
606
+ inc = apply_increment(msgs, seen)
607
+ out = {'tokens': token_totals(inc['totals']), 'calls': inc['calls'],
608
+ 'by_model': inc['by_model'], 'savings': None, 'state': None,
609
+ 'subagents': 0, 'subagent_tokens': 0}
610
+ # 절감 실패는 토큰 집계를 막지 않는다.
611
+ try:
612
+ pending = load_pending(sid)
613
+ state = load_state(sid)
614
+ avoided = walk_savings(new_entries, state, pending, prior_ids, subagents_dir(transcript_path))
615
+ out['savings'] = {'avoided_by_model': avoided, 'avoided_reread_tokens': sum(avoided.values()),
616
+ 'savings_formula': SAVINGS_FORMULA, 'savings_partial': _savings_partial(state, pending)}
617
+ out['state'] = state
618
+ out['subagents'] = len(pending)
619
+ out['subagent_tokens'] = sum(p.get('total_tokens') or 0 for p in pending.values()
620
+ if isinstance(p.get('total_tokens'), int))
621
+ except Exception:
622
+ pass
623
+ return out
624
+
625
+
626
+ def save_state(sid, state):
627
+ _write_json(state_path(sid), state)
628
+
629
+
630
+ def resume_start(entries, sid):
631
+ """커서 파일 없이 시작된 재개·fork 세션: 세션 시작 전 항목을 건너뛴 위치를 돌려준다.
632
+ 일반 새 세션(startup·clear)은 0 이다."""
633
+ run = _read_json(run_file_path(sid))
634
+ if not isinstance(run, dict) or run.get('start_source') in (None, 'startup', 'clear', 'unknown'):
635
+ return 0
636
+ start_ts = run.get('start_ts')
637
+ if not isinstance(start_ts, (int, float)):
638
+ return 0
639
+ from datetime import datetime
640
+ pos = 0
641
+ for i, e in enumerate(entries):
642
+ ts = e.get('timestamp')
643
+ if not isinstance(ts, str):
644
+ continue
645
+ try:
646
+ if datetime.fromisoformat(ts.replace('Z', '+00:00')).timestamp() < start_ts:
647
+ pos = i + 1
648
+ else:
649
+ break
650
+ except Exception:
651
+ continue
652
+ return pos
653
+
654
+
655
+ def _main():
656
+ if len(sys.argv) > 1 and sys.argv[1] == 'subagent-stop':
657
+ # 입력을 stdin 으로 바로 읽는다: last_assistant_message 가 크면 환경변수로 넘길 때 실행이 실패할 수 있다.
658
+ try:
659
+ inp = json.load(sys.stdin)
660
+ if isinstance(inp, dict):
661
+ handle_subagent_stop(inp)
662
+ _telemetry(inp)
663
+ except Exception:
664
+ pass
665
+ return 0
666
+
667
+
668
+ def _telemetry(inp):
669
+ """agent-telemetry.jsonl 완료 행(설계 31 §18). usage v2 플래그와 무관하게 쓴다 — 위임 분석용 로컬 기록."""
670
+ try:
671
+ import agent_telemetry
672
+ p = resolve_agent_path(inp)
673
+ if p and os.path.exists(p):
674
+ agent_telemetry.from_stop(inp, p, load_jsonl(p), agent_meta(p))
675
+ except Exception:
676
+ pass
677
+
678
+
679
+ if __name__ == '__main__':
680
+ sys.exit(_main())