@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,96 @@
1
+ {
2
+ "_comment": "설계 27 T6 결정 전제 줄 형식 계약 — mcp-routinecode/src/pattern-matcher.ts premiseLines·PREMISE_RECHECK 와 hooks/lib/knowledge_items.py premise_lines·PREMISE_RECHECK 가 같은 출력을 내야 한다(바꾸면 세 곳 모두).",
3
+ "recheck": "If a rejected approach comes up again, run each premise check first. If a premise no longer holds, record a new decision with supersedes instead of following the old one.",
4
+ "cases": [
5
+ {
6
+ "name": "text+check",
7
+ "premises": [
8
+ {
9
+ "text": "Kling API는 한국어 립싱크 미지원",
10
+ "check": "grep -n lipsync docs/kling.md"
11
+ }
12
+ ],
13
+ "lines": [
14
+ " - premise: Kling API는 한국어 립싱크 미지원 — check: grep -n lipsync docs/kling.md"
15
+ ]
16
+ },
17
+ {
18
+ "name": "text only + blank skipped",
19
+ "premises": [
20
+ {
21
+ "text": " 단가 2배 "
22
+ },
23
+ {
24
+ "text": " "
25
+ },
26
+ {
27
+ "check": "x"
28
+ }
29
+ ],
30
+ "lines": [
31
+ " - premise: 단가 2배"
32
+ ]
33
+ },
34
+ {
35
+ "name": "quotes and secret-like masked",
36
+ "premises": [
37
+ {
38
+ "text": "키 \"A\" 는 QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ 형식",
39
+ "check": "echo \"v\""
40
+ }
41
+ ],
42
+ "lines": [
43
+ " - premise: 키 'A' 는 [REDACTED] 형식 — check: echo 'v'"
44
+ ]
45
+ },
46
+ {
47
+ "name": "long clipped to 200",
48
+ "premises": [
49
+ {
50
+ "text": "가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가"
51
+ }
52
+ ],
53
+ "lines": [
54
+ " - premise: 가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가가"
55
+ ]
56
+ },
57
+ {
58
+ "name": "more than 5",
59
+ "premises": [
60
+ {
61
+ "text": "p0"
62
+ },
63
+ {
64
+ "text": "p1"
65
+ },
66
+ {
67
+ "text": "p2"
68
+ },
69
+ {
70
+ "text": "p3"
71
+ },
72
+ {
73
+ "text": "p4"
74
+ },
75
+ {
76
+ "text": "p5"
77
+ },
78
+ {
79
+ "text": "p6"
80
+ }
81
+ ],
82
+ "lines": [
83
+ " - premise: p0",
84
+ " - premise: p1",
85
+ " - premise: p2",
86
+ " - premise: p3",
87
+ " - premise: p4"
88
+ ]
89
+ },
90
+ {
91
+ "name": "no premises",
92
+ "premises": null,
93
+ "lines": []
94
+ }
95
+ ]
96
+ }
@@ -15,8 +15,9 @@ pending·auth-failure 마커 무접촉.
15
15
  ts (선택) ISO-8601 — 서버는 참고만(판정 시각은 서버 수신시각)
16
16
 
17
17
  opt-out(P2, 절대 우선):
18
- env ROUTINECODE_TELEMETRY=off 또는 config telemetryEnabled=false
19
- (sync_manager.py의 telemetryEnabled 관례와 동일 키·동일 의미론)
18
+ env ROUTINECODE_TELEMETRY=off, config telemetryEnabled=false, config loggedOut=true 중 하나
19
+ (sync_manager.py의 telemetryEnabled 관례와 동일 키·동일 의미론.
20
+ loggedOut: `routinecode logout` 은 서버 전송을 전부 멈춘다고 안내하므로 이 신호도 멈춘다)
20
21
 
21
22
  dedup(§2.2): ~/.routinecode/presence-state.json {"lastSentDate":"YYYY-MM-DD"}
22
23
  발사 시점에 기록(성공 확인 안 함 — 1일 1발사 상한 보장이 우선).
@@ -50,7 +51,7 @@ def opted_out(cfg):
50
51
  """P2: env 또는 config 어느 쪽이든 opt-out이면 미방출."""
51
52
  if os.environ.get("ROUTINECODE_TELEMETRY", "on").strip().lower() == "off":
52
53
  return True
53
- if cfg.get("telemetryEnabled") is False:
54
+ if cfg.get("telemetryEnabled") is False or cfg.get("loggedOut") is True:
54
55
  return True
55
56
  return False
56
57
 
@@ -146,6 +147,12 @@ def server_base(cfg):
146
147
  def send(base_url, envelope, timeout=PRESENCE_TIMEOUT_SEC):
147
148
  import urllib.request
148
149
 
150
+ try:
151
+ from privacy_log import log_transmission
152
+ log_transmission(base_url + "/api/v1/presence", envelope)
153
+ except Exception:
154
+ pass
155
+
149
156
  req = urllib.request.Request(
150
157
  base_url + "/api/v1/presence",
151
158
  data=json.dumps(envelope).encode(),
@@ -0,0 +1,35 @@
1
+ """
2
+ privacy_log: 전송 기록(설계 15 §4.5). shared/sanitize.ts logTransmission 의 Python 판.
3
+ 엔드포인트·키 이름·크기만 남긴다. 값은 절대 기록하지 않는다. 실패는 전송을 막지 않는다.
4
+ """
5
+
6
+ import json, os, re, time
7
+
8
+ MAX_BYTES = 1024 * 1024
9
+
10
+
11
+ def log_path():
12
+ base = os.environ.get("ROUTINECODE_DIR") or os.path.expanduser("~/.routinecode")
13
+ return os.path.join(base, "privacy-log.jsonl")
14
+
15
+
16
+ def log_transmission(url, body):
17
+ try:
18
+ p = log_path()
19
+ os.makedirs(os.path.dirname(p), exist_ok=True)
20
+ if os.path.exists(p) and os.path.getsize(p) > MAX_BYTES:
21
+ os.replace(p, p + ".1")
22
+ endpoint = re.sub(r"^https?://[^/]+", "", str(url)).split("?")[0]
23
+ keys = sorted(body.keys()) if isinstance(body, dict) else []
24
+ size = 0 if body is None else len(json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode())
25
+ line = json.dumps({
26
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
27
+ "endpoint": endpoint,
28
+ "keys": keys,
29
+ "bytes": size,
30
+ })
31
+ fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
32
+ with os.fdopen(fd, "a") as f:
33
+ f.write(line + "\n")
34
+ except Exception:
35
+ pass
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
  """Prevented Cost 영수증 — 집계기 (설계: docs2/지능개선/new/Prevented-Cost-영수증-설계.md).
3
3
 
4
- 순수 읽기(사이드이펙트 0). `/receipt` 커맨드와 stop-hook 세션말 1줄이 공유한다.
4
+ 영수증 집계는 순수 읽기(사이드이펙트 0). `/receipt` 커맨드와 stop-hook 세션말 1줄이 공유한다.
5
+ 세션 요약(설계 15 §2.6)만 rdpe/sessions/ 에 쓴다: record_session 은 Stop, previous_session_line 은 SessionStart.
5
6
  제1원칙 = 과대주장 금지: 모든 숫자에 {실측|추정·하한|잠재|측정중} 라벨, 잠재/실측 불혼합,
6
7
  음수(지식 무익) 정직 표기, "API 환산" 각주. fail-open: 어떤 파손도 "측정 중" 폴백.
7
8
 
@@ -21,6 +22,30 @@ STATS = os.path.join(_RC, 'attribution', 'stats.json')
21
22
  ROUTINES = os.path.join(_RC, 'rdpe', 'routines.json')
22
23
  ADOPTION = os.path.join(_RC, 'rdpe', 'adoption.json')
23
24
  PRICES = os.path.join(_RC, 'rdpe', 'prices.json')
25
+ SESSIONS_DIR = os.path.join(_RC, 'rdpe', 'sessions')
26
+ SESSIONS_KEEP = 30
27
+
28
+ _PREV_LINE = {
29
+ "en": "Last session: {tokens} tokens · {calls} API calls · {turns} turns · {agents} subagents",
30
+ "ko": "이전 세션: 토큰 {tokens} · API 호출 {calls}회 · 턴 {turns}회 · 서브에이전트 {agents}개",
31
+ "ja": "前回のセッション: トークン {tokens} · API 呼び出し {calls} 回 · ターン {turns} 回 · サブエージェント {agents} 個",
32
+ "zh": "上次会话: 令牌 {tokens} · API 调用 {calls} 次 · 回合 {turns} 次 · 子代理 {agents} 个",
33
+ "es": "Sesión anterior: {tokens} tokens · {calls} llamadas a la API · {turns} turnos · {agents} subagentes",
34
+ }
35
+ _PREV_SAVED = {
36
+ "en": " · re-reads avoided ≈ {saved} tokens [estimate]",
37
+ "ko": " · 재읽기 회피 약 {saved} 토큰 [추정]",
38
+ "ja": " · 再読み込み回避 約 {saved} トークン [推定]",
39
+ "zh": " · 避免重读约 {saved} 令牌 [估算]",
40
+ "es": " · relecturas evitadas ≈ {saved} tokens [estimación]",
41
+ }
42
+ _PREV_PARTIAL = {
43
+ "en": " (some calls not measured)",
44
+ "ko": " (일부 호출 미계측)",
45
+ "ja": " (一部の呼び出しは未計測)",
46
+ "zh": " (部分调用未计量)",
47
+ "es": " (algunas llamadas sin medir)",
48
+ }
24
49
 
25
50
  # 내장 기본 단가 ($/1M tokens) — 보수(낮은 쪽) 채택: 과대주장 금지 원칙.
26
51
  # 출처: Anthropic 공시가(Sonnet 급) 기준, 2026-10 확인. prices.json 으로 교체 가능.
@@ -108,8 +133,17 @@ def snapshot(routines=None, stats=None):
108
133
  "r1_state": r1["state"]}
109
134
 
110
135
 
136
+ def savings_display_on():
137
+ """달러 환산 표시 플래그. _sync_features 가 받은 로컬 캐시만 본다. 없거나 못 읽으면 off(설계 15 D2)."""
138
+ try:
139
+ import usage_v2
140
+ return usage_v2.flag(usage_v2.FLAG_SAVINGS_DISPLAY, False)
141
+ except Exception:
142
+ return False
143
+
144
+
111
145
  def oneline(snap_now, snap_old):
112
- """변화 종류별 세션말 1줄. 변화 없으면 None."""
146
+ """변화 종류별 세션말 1줄. 변화 없으면 None. 달러를 넣지 않는다: 플래그와 무관하게 건수만 말한다."""
113
147
  try:
114
148
  if snap_now.get("r1_state") == "active" and snap_old.get("r1_state") != "active":
115
149
  return ("✅ 지식 효과 측정이 통계적 유의 수준에 도달했습니다 — "
@@ -140,6 +174,86 @@ def _fmt_dur(sec):
140
174
  return "%ds" % sec
141
175
 
142
176
 
177
+ def record_session(session, delta, subagents=0, subagent_tokens=0, partial=False):
178
+ """Stop 구간 증분을 세션 요약에 더한다. 토큰 수만 남긴다(프로젝트·경로·본문 없음)."""
179
+ if not session:
180
+ return
181
+ path = os.path.join(SESSIONS_DIR, session + '.json')
182
+ cur = _load(path, {})
183
+ cur = cur if isinstance(cur, dict) else {}
184
+ for k in ('input', 'output', 'cache_read', 'cache_create', 'calls', 'turns', 'avoided'):
185
+ cur[k] = int(cur.get(k, 0) or 0) + int(delta.get(k, 0) or 0)
186
+ cur.update({'session': session, 'subagents': int(subagents or 0),
187
+ 'subagent_tokens': int(subagent_tokens or 0), 'partial': bool(partial),
188
+ 'shown': False})
189
+ os.makedirs(SESSIONS_DIR, exist_ok=True)
190
+ tmp = '%s.%d.tmp' % (path, os.getpid())
191
+ with open(tmp, 'w') as f:
192
+ json.dump(cur, f)
193
+ os.replace(tmp, path)
194
+
195
+
196
+ def session_total(s):
197
+ """메인 + 서브에이전트 토큰 합계."""
198
+ return sum(int(s.get(k, 0) or 0) for k in
199
+ ('input', 'output', 'cache_read', 'cache_create', 'subagent_tokens'))
200
+
201
+
202
+ def previous_session_line(current, locale='en', show_savings=False):
203
+ """현재 세션이 아닌 가장 최근 세션의 사용량 한 줄. 세션당 한 번만 낸다. 없으면 None."""
204
+ try:
205
+ names = [n for n in os.listdir(SESSIONS_DIR) if n.endswith('.json')]
206
+ except Exception:
207
+ return None
208
+ names.sort(key=lambda n: os.path.getmtime(os.path.join(SESSIONS_DIR, n)), reverse=True)
209
+ for old in names[SESSIONS_KEEP:]:
210
+ try:
211
+ os.remove(os.path.join(SESSIONS_DIR, old))
212
+ except OSError:
213
+ pass
214
+ prev = next((n for n in names[:SESSIONS_KEEP] if n[:-len('.json')] != current), None)
215
+ if prev is None:
216
+ return None
217
+ path = os.path.join(SESSIONS_DIR, prev)
218
+ s = _load(path, None)
219
+ if not isinstance(s, dict) or s.get('shown') or session_total(s) <= 0:
220
+ return None
221
+ s['shown'] = True
222
+ with open(path, 'w') as f:
223
+ json.dump(s, f)
224
+ line = _PREV_LINE.get(locale, _PREV_LINE['en']).format(
225
+ tokens=_fmt_tok(session_total(s)), calls=int(s.get('calls', 0) or 0),
226
+ turns=int(s.get('turns', 0) or 0), agents=int(s.get('subagents', 0) or 0))
227
+ if show_savings and int(s.get('avoided', 0) or 0) > 0:
228
+ line += _PREV_SAVED.get(locale, _PREV_SAVED['en']).format(saved=_fmt_tok(int(s['avoided'])))
229
+ if s.get('partial'):
230
+ line += _PREV_PARTIAL.get(locale, _PREV_PARTIAL['en'])
231
+ return line
232
+
233
+
234
+ def _prev_session_cli():
235
+ """session-start 전용. stdin = 훅 입력. 새 세션(startup·clear)에서만 한 줄을 출력한다."""
236
+ try:
237
+ inp = json.load(sys.stdin)
238
+ except Exception:
239
+ return 0
240
+ if not isinstance(inp, dict) or inp.get('source') not in ('startup', 'clear'):
241
+ return 0
242
+ import usage_v2
243
+ if not usage_v2.v2_enabled():
244
+ return 0
245
+ try:
246
+ import i18n
247
+ loc = i18n.get_locale()
248
+ except Exception:
249
+ loc = 'en'
250
+ line = previous_session_line((inp.get('session_id') or '')[:12], loc,
251
+ usage_v2.flag(usage_v2.FLAG_SAVINGS_DISPLAY, False))
252
+ if line:
253
+ print(line)
254
+ return 0
255
+
256
+
143
257
  def _time_totals():
144
258
  """Prevented Time 누계 (lib/time_savings.py 원장) — 실패 시 침묵."""
145
259
  try:
@@ -158,10 +272,13 @@ def build_receipt():
158
272
  # 행3: 분리 표기 (합산 단일 $ 금지 — 설계 §2행3 v1.1)
159
273
  usd_potential = r2["potential_tokens"] * cr / 1_000_000
160
274
  usd_measured = r2["measured_tokens"] * cr / 1_000_000 # R2 실측분(현재 0)
161
- return {"r1": r1, "r2": r2,
162
- "r3": {"usd_potential": round(usd_potential, 2),
163
- "usd_measured": round(usd_measured, 2),
164
- "price_basis": "cache_read $%.2f/M (%s)" % (cr, pr.get('_note', 'prices.json'))},
275
+ # 플래그 off 면 --json 으로도 달러가 나가지 않게 값 자체를 만들지 않는다.
276
+ r3 = None
277
+ if savings_display_on():
278
+ r3 = {"usd_potential": round(usd_potential, 2),
279
+ "usd_measured": round(usd_measured, 2),
280
+ "price_basis": "cache_read $%.2f/M (%s)" % (cr, pr.get('_note', 'prices.json'))}
281
+ return {"r1": r1, "r2": r2, "r3": r3,
165
282
  "time": _time_totals(),
166
283
  "snapshot": snapshot()}
167
284
 
@@ -210,14 +327,15 @@ def render(r):
210
327
  if t.get("potential_gate_blocks"):
211
328
  L.append(" 게이트 선차단 %d건 [잠재 — 실측분포 축적 전 미적립]"
212
329
  % t["potential_gate_blocks"])
213
- c = r["r3"]
214
- if c["usd_measured"] > 0:
215
- L.append(" 환산 가치 실측분 ≈ $%.2f [실측]" % c["usd_measured"])
216
- if c["usd_potential"] > 0:
217
- L.append(" 환산 가치 잠재분 ≈ $%.2f [잠재]" % c["usd_potential"])
218
- L.append(" ※ %s — API 단가 환산 가치. 구독 요금제에서는 실지출이 아니라"
219
- % c["price_basis"])
220
- L.append(" 세션 용량·속도 여유로 환원됩니다.")
330
+ c = r.get("r3")
331
+ if c and savings_display_on():
332
+ if c["usd_measured"] > 0:
333
+ L.append(" 환산 가치 실측분 ≈ $%.2f [실측]" % c["usd_measured"])
334
+ if c["usd_potential"] > 0:
335
+ L.append(" 환산 가치 잠재분 ≈ $%.2f [잠재]" % c["usd_potential"])
336
+ L.append(" ※ %s — API 단가 환산 가치. 구독 요금제에서는 실지출이 아니라"
337
+ % c["price_basis"])
338
+ L.append(" 세션 용량·속도 여유로 환원됩니다.")
221
339
  # per-kid 상세 (음수 정직 표기 — 빈도 통제: 노출수 병기)
222
340
  pk = [k for k in a["per_kid"] if (k["exposed"] + k["holdout"]) >= 5]
223
341
  if pk:
@@ -233,6 +351,11 @@ def render(r):
233
351
 
234
352
  def main():
235
353
  args = sys.argv[1:]
354
+ if "--prev-session" in args:
355
+ try:
356
+ return _prev_session_cli()
357
+ except Exception:
358
+ return 0
236
359
  r = build_receipt()
237
360
  if "--json" in args:
238
361
  print(json.dumps(r, ensure_ascii=False, indent=1))
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env python3
2
+ """reviewer 호출 관문. 같은 대상의 재검토가 변경분만 보도록 ANALYSIS_SCOPE 를 요구한다.
3
+
4
+ - reviewer 가 아니면 아무것도 하지 않는다.
5
+ - ANALYSIS_SCOPE 가 없으면 거절한다. 원장이 없으면 재검토가 매번 전수 분석이 된다.
6
+ - INDEPENDENT: true 는 같은 범위에서 세션당 1회만 허용한다.
7
+ - 어떤 실패도 통과시킨다(fail-open).
8
+ """
9
+ import json
10
+ import os
11
+ import re
12
+ import sys
13
+ import time
14
+
15
+ SCOPE = re.compile(r'^\s*ANALYSIS_SCOPE:\s*(\S.{0,200}?)\s*$', re.M)
16
+ INDEP = re.compile(r'^\s*INDEPENDENT:\s*true\s*$', re.M | re.I)
17
+ ID = re.compile(r'[A-Za-z0-9_-]{1,80}')
18
+ KEEP = 7 * 86400
19
+
20
+ NEED_SCOPE = ('[review-gate] reviewer 호출에 `ANALYSIS_SCOPE: <저장소>:<대상>:<기준>` 줄이 없습니다. '
21
+ '같은 대상은 같은 키를 쓰면 다음 검토가 변경분만 봅니다. 프롬프트에 그 줄과 '
22
+ '`REVIEW_MODE: code|design|audit`, 대상, 주장 목록, 통과한 빌드·시험을 넣어 다시 호출하세요.')
23
+ SECOND_INDEP = ('[review-gate] 이 세션에서 `{scope}` 범위의 독립 검토를 이미 했습니다. '
24
+ '`INDEPENDENT: true`를 빼고 같은 `ANALYSIS_SCOPE`로 호출하면 변경분만 검토합니다. '
25
+ '수정 확인은 이전 결과의 `verify` 명령을 실행하세요.')
26
+
27
+
28
+ def is_reviewer(kind):
29
+ k = str(kind or '').strip().lower()
30
+ return k == 'reviewer' or k.endswith(':reviewer')
31
+
32
+
33
+ def deny(reason):
34
+ print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny',
35
+ 'permissionDecisionReason': reason}}, ensure_ascii=False))
36
+
37
+
38
+ def main():
39
+ inp = json.load(sys.stdin)
40
+ ti = inp.get('tool_input') or {}
41
+ if not is_reviewer(ti.get('subagent_type')):
42
+ return
43
+ prompt = str(ti.get('prompt') or '')
44
+ m = SCOPE.search(prompt)
45
+ if not m:
46
+ deny(NEED_SCOPE)
47
+ return
48
+ if not INDEP.search(prompt):
49
+ return
50
+ sid = str(inp.get('session_id') or '')
51
+ if not ID.fullmatch(sid):
52
+ return
53
+ folder = os.path.join(os.environ['RC_RUNDIR'], 'review-gate')
54
+ os.makedirs(folder, exist_ok=True)
55
+ now = time.time()
56
+ for name in os.listdir(folder):
57
+ p = os.path.join(folder, name)
58
+ try:
59
+ if os.path.getmtime(p) < now - KEEP:
60
+ os.unlink(p)
61
+ except OSError:
62
+ pass
63
+ path = os.path.join(folder, sid + '.json')
64
+ try:
65
+ with open(path) as f:
66
+ seen = json.load(f)
67
+ if not isinstance(seen, list):
68
+ seen = []
69
+ except (OSError, ValueError):
70
+ seen = []
71
+ scope = m.group(1)
72
+ if scope in seen:
73
+ deny(SECOND_INDEP.format(scope=scope))
74
+ return
75
+ seen.append(scope)
76
+ tmp = path + '.tmp'
77
+ with open(tmp, 'w') as f:
78
+ json.dump(seen[-200:], f, ensure_ascii=False)
79
+ os.replace(tmp, path)
80
+
81
+
82
+ if __name__ == '__main__':
83
+ main()
@@ -0,0 +1,213 @@
1
+ #!/usr/bin/env python3
2
+ """routine_skill_eval — 루틴 스킬별 전·후 스냅샷 (docs/지식체계/40 §4.8, 절감 계산기 saving_D 의 입력).
3
+
4
+ - 루틴 스킬 = `skills/rc-routine-<이름>/` 에 `routine.json` {"replaces": "<일의 종류 정규식>", "since": "YYYY-MM-DD"?} 이 있는 것.
5
+ - 로컬 transcript(메인 세션만, 서브에이전트 제외)에서 그 종류 호출 + 루틴 실행을 세션별로 센다.
6
+ 전 = 채택일 이전 BEFORE_DAYS 일, 후 = 채택일부터. 채택일 = since, 없으면 첫 실행일.
7
+ - 금액은 계산하지 않는다. 토큰만 낸다 — 단가는 서버(growth savings.constants.ts)가 정본.
8
+ - 명령 원문은 내보내지 않는다(라벨·숫자만, RDPE A10).
9
+
10
+ CLI: python3 routine_skill_eval.py [--write] (--write 면 캐시 파일에 저장)
11
+ """
12
+ import calendar
13
+ import glob
14
+ import json
15
+ import os
16
+ import re
17
+ import statistics
18
+ import sys
19
+ import time
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22
+ import work_kind as wk # noqa: E402
23
+
24
+ BEFORE_DAYS = 28
25
+ # 호출당 비용을 고를 때만 쓰는 상대 가중(재읽기 = 새 입력의 10%). 금액 아님 — 서버 CACHE_READ/INPUT 비와 같다.
26
+ CACHE_READ_WEIGHT = 0.1
27
+ CACHE_PATH = os.path.expanduser('~/.routinecode/usage/routine-skills.json')
28
+ REFRESH_SEC = 3600 # 화면 ② 내 스킬의 실행 횟수가 같은 날 안에 보이게(24h → 1h)
29
+
30
+
31
+ def skill_dirs(cwd=None):
32
+ roots = [os.path.expanduser('~/.claude/skills')]
33
+ if cwd:
34
+ roots.append(os.path.join(cwd, '.claude', 'skills'))
35
+ out = {}
36
+ for r in roots:
37
+ for d in glob.glob(os.path.join(r, 'rc-routine-*')):
38
+ cfg = os.path.join(d, 'routine.json')
39
+ if not os.path.isfile(cfg):
40
+ continue
41
+ try:
42
+ c = json.load(open(cfg))
43
+ re.compile(c['replaces'])
44
+ except Exception:
45
+ continue
46
+ out.setdefault(os.path.basename(d), c) # 개인 우선(Claude Code 우선순위와 같음)
47
+ return out
48
+
49
+
50
+ def _utc(ts):
51
+ try:
52
+ return calendar.timegm(time.strptime(ts[:19], '%Y-%m-%dT%H:%M:%S'))
53
+ except Exception:
54
+ return None
55
+
56
+
57
+ def _read_sessions(lo, projects_glob):
58
+ """[(세션 시작 epoch, [(kind_key, usage, n_tools, is_error)])] — 메인 대화형 세션만."""
59
+ res = []
60
+ for f in glob.glob(projects_glob):
61
+ try:
62
+ if os.path.getmtime(f) < lo:
63
+ continue
64
+ except OSError:
65
+ continue
66
+ msgs, order, errs, inter, first = {}, [], set(), None, None
67
+ try:
68
+ fh = open(f, errors='replace')
69
+ except OSError:
70
+ continue
71
+ with fh:
72
+ for line in fh:
73
+ if '"tool_use"' not in line and '"tool_result"' not in line and '"entrypoint"' not in line and first is not None:
74
+ continue
75
+ try:
76
+ e = json.loads(line)
77
+ except Exception:
78
+ continue
79
+ if e.get('type') == 'user':
80
+ if inter is None and e.get('entrypoint'):
81
+ inter = e.get('entrypoint') == 'cli'
82
+ ct = e.get('message', {}).get('content')
83
+ if isinstance(ct, list):
84
+ for b in ct:
85
+ if isinstance(b, dict) and b.get('type') == 'tool_result' and b.get('is_error'):
86
+ errs.add(b.get('tool_use_id'))
87
+ continue
88
+ if e.get('type') != 'assistant' or e.get('isSidechain'):
89
+ continue # 서브에이전트 안 호출은 격리 절감(saving_A)에 이미 들어 있다
90
+ m = e.get('message', {})
91
+ mid = m.get('id')
92
+ if not mid:
93
+ continue
94
+ if first is None:
95
+ first = _utc(e.get('timestamp', ''))
96
+ if mid not in msgs:
97
+ msgs[mid] = {'u': {}, 't': []}
98
+ order.append(mid)
99
+ if m.get('usage'):
100
+ msgs[mid]['u'] = m['usage']
101
+ msgs[mid]['t'] += [b for b in (m.get('content') or []) if isinstance(b, dict) and b.get('type') == 'tool_use']
102
+ if not inter or first is None or first < lo:
103
+ continue
104
+ calls = []
105
+ for mid in order:
106
+ tools = msgs[mid]['t']
107
+ for t in tools:
108
+ if t.get('name') != 'Bash':
109
+ continue
110
+ k = wk.classify((t.get('input') or {}).get('command', ''))
111
+ calls.append((wk.kind_key(k), msgs[mid]['u'], len(tools), t.get('id') in errs))
112
+ res.append((first, calls))
113
+ return res
114
+
115
+
116
+ def _call_tokens(u, n):
117
+ n = max(1, n)
118
+ cr = u.get('cache_read_input_tokens', 0) / n
119
+ other = (u.get('input_tokens', 0) + u.get('cache_creation_input_tokens', 0) + u.get('output_tokens', 0)) / n
120
+ return cr, other
121
+
122
+
123
+ def evaluate(now=None, cwd=None, projects_glob=None, skills=None):
124
+ now = now or time.time()
125
+ skills = skills if skills is not None else skill_dirs(cwd)
126
+ if not skills:
127
+ return []
128
+ projects_glob = projects_glob or os.path.expanduser('~/.claude/projects/*/*.jsonl')
129
+ # 채택일이 가장 이른 스킬 기준으로 한 번만 읽는다
130
+ since = {}
131
+ for name, c in skills.items():
132
+ s = c.get('since')
133
+ since[name] = calendar.timegm(time.strptime(s, '%Y-%m-%d')) if s else None
134
+ earliest = min([v for v in since.values() if v] or [now])
135
+ sessions = _read_sessions(earliest - BEFORE_DAYS * 86400, projects_glob)
136
+ out = []
137
+ for name, c in skills.items():
138
+ rx = re.compile(c['replaces'])
139
+ run_key = f'routine:{name}:run'
140
+ t0 = since[name]
141
+ if t0 is None: # 첫 실행 세션의 시작일
142
+ starts = [st for st, calls in sessions if any(k == run_key for k, *_ in calls)]
143
+ t0 = min(starts) if starts else None
144
+ if t0 is None:
145
+ out.append({'name': name, 'replaces': c['replaces'], 'since': None, 'before': None, 'after': None})
146
+ continue
147
+ lo = t0 - BEFORE_DAYS * 86400
148
+ side = {'before': [], 'after': []}
149
+ toks, runs, run_err, adopted, last_run = [], 0, 0, 0, None
150
+ for st, calls in sessions:
151
+ if st < lo:
152
+ continue
153
+ mine = [x for x in calls if x[0] == run_key or rx.search(x[0])]
154
+ if not mine:
155
+ continue
156
+ s = 'after' if st >= t0 else 'before'
157
+ side[s].append(len(mine))
158
+ if s == 'after':
159
+ r = [x for x in mine if x[0] == run_key]
160
+ runs += len(r)
161
+ run_err += sum(1 for x in r if x[3])
162
+ adopted += 1 if r else 0
163
+ if r:
164
+ last_run = max(last_run or st, st)
165
+ toks += [_call_tokens(x[1], x[2]) for x in mine]
166
+ med_tok = None
167
+ if toks:
168
+ toks.sort(key=lambda x: x[0] * CACHE_READ_WEIGHT + x[1])
169
+ mcr, mo = toks[len(toks) // 2]
170
+ med_tok = {'cache_read': int(mcr), 'other': int(mo)}
171
+ out.append({
172
+ 'name': name, 'replaces': c['replaces'], 'since': time.strftime('%Y-%m-%d', time.gmtime(t0)),
173
+ 'window_days': BEFORE_DAYS,
174
+ 'before': {'sessions': len(side['before']),
175
+ 'median_calls': statistics.median(side['before']) if side['before'] else None},
176
+ 'after': {'sessions': len(side['after']),
177
+ 'median_calls': statistics.median(side['after']) if side['after'] else None,
178
+ 'adopted_sessions': adopted, 'runs': runs, 'run_errors': run_err,
179
+ 'last_run': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(last_run)) if last_run else None,
180
+ 'median_call_tokens': med_tok},
181
+ })
182
+ return out
183
+
184
+
185
+ def cached():
186
+ try:
187
+ d = json.load(open(CACHE_PATH))
188
+ return d if isinstance(d, dict) and isinstance(d.get('skills'), list) else None
189
+ except Exception:
190
+ return None
191
+
192
+
193
+ def stale(now=None):
194
+ d = cached()
195
+ return d is None or (now or time.time()) - d.get('computed_at', 0) > REFRESH_SEC
196
+
197
+
198
+ def write(now=None, cwd=None):
199
+ now = now or time.time()
200
+ doc = {'computed_at': int(now), 'skills': evaluate(now, cwd)}
201
+ os.makedirs(os.path.dirname(CACHE_PATH), exist_ok=True)
202
+ tmp = CACHE_PATH + '.tmp'
203
+ with open(tmp, 'w') as fh:
204
+ json.dump(doc, fh, ensure_ascii=False)
205
+ os.replace(tmp, CACHE_PATH)
206
+ return doc
207
+
208
+
209
+ if __name__ == '__main__':
210
+ if '--write' in sys.argv:
211
+ print(json.dumps(write(cwd=os.getcwd()), ensure_ascii=False, indent=2))
212
+ else:
213
+ print(json.dumps(evaluate(cwd=os.getcwd()), ensure_ascii=False, indent=2))