@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
@@ -88,28 +88,19 @@ def _read_jsonl(p):
88
88
  return []
89
89
  return out
90
90
 
91
- # ── 테넌트 격리(docs/18): 현재 config.tenantId 를 읽어 도메인지식 표면화를 필터 ──
92
- # entry.tenantId == config.tenantId 또는 legacy(없음/0/null/''/'0') 이면 노출.
93
- # 그 외(다른 테넌트 태그)는 제외 → A고객 지식이 B고객 업무에 새지 않게. domain_knowledge 전용.
94
- def _config_tenant_id():
95
- cfg_path = os.path.expanduser(os.environ.get('ROUTINECODE_CONFIG_PATH', '') or '~/.routinecode/config.json')
96
- try:
97
- with open(cfg_path) as f:
98
- return json.load(f).get('tenantId')
99
- except Exception:
100
- return None
101
-
102
- def _is_legacy_tenant(v):
103
- return v is None or v == 0 or v == '0' or v == ''
104
-
105
- _CFG_TENANT = _config_tenant_id()
106
-
107
- def _tenant_ok(entry_tenant):
108
- if _is_legacy_tenant(entry_tenant):
109
- return True
110
- if _is_legacy_tenant(_CFG_TENANT):
91
+ # ── 계정 격리(docs/지식체계/36 §16.2): 공용 knowledge_scope.visible 만 쓴다 ──
92
+ # entry.tenantId == 계정 공간(팀=teamTenantId, 개인=tenantId)일 때만 노출. legacy(없음·0·50)는 숨김.
93
+ # 모듈·config 를 못 읽으면 fail-closed(아무것도 주입하지 않음).
94
+ try:
95
+ _ks_lib = os.path.join(os.environ.get('ROUTINECODE_HOOKS_DIR', ''), 'lib')
96
+ if _ks_lib not in sys.path:
97
+ sys.path.insert(0, _ks_lib)
98
+ import knowledge_scope as _ks
99
+ def _visible(e):
100
+ return _ks.visible(e)
101
+ except Exception:
102
+ def _visible(e):
111
103
  return False
112
- return str(entry_tenant) == str(_CFG_TENANT)
113
104
 
114
105
  parts = []
115
106
 
@@ -138,7 +129,7 @@ def _is_holdout(kid, maturity=None):
138
129
  return False
139
130
 
140
131
  # 1) 도메인지식 — flat scope 직접매칭(우선) + 의미 그래프(concept/GOVERNS) 확장(meaning→consumption)
141
- _DK = [e for e in _read_jsonl(os.path.join(KN, 'domain-knowledge.jsonl')) if _tenant_ok(e.get('tenantId'))]
132
+ _DK = [e for e in _read_jsonl(os.path.join(KN, 'domain-knowledge.jsonl')) if _visible(e)]
142
133
 
143
134
  def _dk_sid(e):
144
135
  # contracts: dk:<project>:<title>
@@ -214,7 +205,7 @@ except Exception:
214
205
  pass
215
206
 
216
207
  # 2) 라이브러리 quirk (파일 import에서 라이브러리 추론 → quirks.jsonl library exact-match, 최대 2건)
217
- quirks = _read_jsonl(os.path.join(KN, 'quirks.jsonl'))
208
+ quirks = [e for e in _read_jsonl(os.path.join(KN, 'quirks.jsonl')) if _visible(e)] # 36 §16.2: quirk 도 같은 격리
218
209
  if quirks:
219
210
  libs = set()
220
211
  try:
@@ -247,6 +238,17 @@ if quirks:
247
238
  if q_count >= 2:
248
239
  break
249
240
 
241
+ # 3) 새 형식 지식(v31) — 대상(touch) 조건이 맞는 것만, 순위·예산 안에서 (docs/지식체계/36 §4·§5).
242
+ # legacy 주입 뒤에 블록을 덧붙인다. 노출 → emit_raw exposure + 이벤트 API 대기열 + 주입 원장(씨앗·잘린 id).
243
+ _v31 = None
244
+ try:
245
+ import knowledge_items as _ki # ROUTINECODE_HOOKS_DIR/lib 는 위 격리 로드에서 sys.path 에 들어간다
246
+ _v31 = _ki.select({'type': 'read', 'file': read_file}, session_id=session_id)
247
+ if _v31:
248
+ parts.append(_v31['text'])
249
+ except Exception:
250
+ _v31 = None
251
+
250
252
  if not parts and not _led:
251
253
  allow()
252
254
 
@@ -271,10 +273,12 @@ try:
271
273
  from datetime import datetime as _dtt, timezone as _tzz
272
274
  _now_iso = _dtt.now(_tzz.utc).isoformat()
273
275
  _fh = _h.sha1(os.path.basename(read_file).encode('utf-8', 'replace')).hexdigest()[:8]
276
+ # 설계 28 T3: 전체 경로 해시 — basename 만으로는 index.ts 같은 이름끼리 섞인다(attribution_judge.file_keys 와 같은 규칙)
277
+ _ffh = _h.sha1(os.path.abspath(read_file).encode('utf-8', 'replace')).hexdigest()[:12]
274
278
  with open(os.path.join(_att, 'ledger-' + _sid12 + '.jsonl'), 'a') as _lf:
275
279
  for _kid, _kind, _ho in _led:
276
280
  _lf.write(json.dumps({"at": _now_iso, "kid": _kid, "kind": _kind,
277
- "file": _fh, "holdout": bool(_ho)}) + "\n")
281
+ "file": _fh, "file_full": _ffh, "holdout": bool(_ho)}) + "\n")
278
282
  # exposure 이벤트 — usage 분석 보조 (성숙 분모 아님, v1.1: migration 015 로 분모는 verified_cnt)
279
283
  _elib = os.path.join(os.environ.get('ROUTINECODE_HOOKS_DIR', ''), 'lib')
280
284
  if _elib and _elib not in sys.path:
@@ -290,6 +294,12 @@ try:
290
294
  except Exception:
291
295
  pass
292
296
 
297
+ try:
298
+ if _v31:
299
+ _ki.record_exposure(_v31, session_id, 'inject:read', file_path=read_file)
300
+ except Exception:
301
+ pass
302
+
293
303
  if parts:
294
304
  allow_with_message('\n\n'.join(parts))
295
305
  else:
@@ -0,0 +1,17 @@
1
+ #!/bin/bash
2
+ # PreToolUse hook: Agent — reviewer 호출 관문 (설계 22).
3
+ # 같은 대상의 재검토가 분석 원장으로 변경분만 보도록 ANALYSIS_SCOPE 를 요구하고,
4
+ # 독립 검토(INDEPENDENT: true)는 범위당 세션 1회로 제한한다. 실패하면 통과한다.
5
+ # kill switch: ROUTINECODE_REVIEW_GATE=off
6
+
7
+ [ "${ROUTINECODE_REVIEW_GATE:-on}" = "off" ] && exit 0
8
+ INPUT="$(cat)"
9
+ case "$INPUT" in
10
+ *reviewer*) ;;
11
+ *) exit 0 ;;
12
+ esac
13
+ RC_RUNDIR="${XDG_RUNTIME_DIR:-$HOME/.routinecode/run}"
14
+ mkdir -p "$RC_RUNDIR" 2>/dev/null || exit 0
15
+ export RC_RUNDIR
16
+ printf '%s' "$INPUT" | python3 "$(dirname "$0")/lib/review_gate.py" 2>/dev/null
17
+ exit 0
@@ -17,7 +17,7 @@ CLAIM="$QUEUE.processing.$$"
17
17
  mv "$QUEUE" "$CLAIM" 2>/dev/null || exit 0
18
18
 
19
19
  CLAUDE_BIN="${RECORDER_CLAUDE_BIN:-claude}"
20
- TOOLS="mcp__intelligence__record_error_fix,mcp__intelligence__record_pattern,mcp__intelligence__record_quirk,mcp__intelligence__record_decision,mcp__intelligence__record_domain_knowledge,mcp__intelligence__record_verification,mcp__intelligence__resolve_concept,mcp__intelligence__record_grounding,mcp__intelligence__run_knowledge_critic,mcp__intelligence__mark_session_recorded,Read,Grep,Bash"
20
+ TOOLS="mcp__intelligence__record_error_fix,mcp__intelligence__record_pattern,mcp__intelligence__record_quirk,mcp__intelligence__record_decision,mcp__intelligence__record_knowledge,mcp__intelligence__record_domain_knowledge,mcp__intelligence__record_verification,mcp__intelligence__resolve_concept,mcp__intelligence__record_grounding,mcp__intelligence__run_knowledge_critic,mcp__intelligence__mark_session_recorded,Read,Grep,Bash"
21
21
 
22
22
  # ── intelligence MCP 명시 등록 (검증→성숙 루프 점화의 핵심) ─────────
23
23
  # 과거엔 --allowedTools에 mcp__intelligence__* 를 나열해도 서버가 미등록이라(비-routinecode
@@ -65,7 +65,30 @@ while IFS= read -r task; do
65
65
  # 멱등: 이미 처리됐으면 skip
66
66
  [ -f "$KN/.recorder-done-$sid" ] && continue
67
67
 
68
- prompt="당신은 routinecode:recorder(지식 전담 기록자)다. 세션 transcript(${tp})를 Read/Grep으로 읽어 error-fix/pattern/quirk/decision/domain-knowledge를 추출하라. 감지된 signals: ${sig}. [도메인지식 능동 탐색 — 신호(${sig})에 domain_knowledge가 없어도 반드시 수행] transcript 전체에서 '코드만 읽어서는 알 수 없는' 정보를 능동적으로 찾아라. 판정 기준 단 하나: 이 정보를 코드/설정/git으로 유도할 수 있으면 저장 금지, 없으면 domain-knowledge다. 특히 두 유형을 놓치지 마라 — (1)암시적 발화: 키워드(기억해/절대/금지) 없이 규칙·정책·이유를 설명한 사용자 발화(예: '이건 카드사가 30분으로 정해둔 거라', '금요일 오후엔 배포 안 해'). '왜 이렇게 했나'의 답이 코드에 없으면 category=why/timing. (2)observed: 구현 중 외부 API가 문서와 다르게 동작한 관찰(예: '문서엔 X인데 실제 응답은 Y', 'rate limit 초과하면 24h 차단')→category=external, source=observed. category(why/timing/external/tenant)·source(user_correction/explicit/observed)·scope(관련 파일 절대경로 필수)를 채워 mcp__intelligence__record_domain_knowledge로 기록하라. 각 지식의 표면 표현을 mcp__intelligence__resolve_concept로 개념 후보를 받아 mcp__intelligence__record_grounding으로 의미층(concept)에 연결하라. 근거(에러원문/파일:line/사용자발화) 없는 지식은 절대 기록하지 마라. [Verification 폐루프 — signals에 verification이 있거나 항상 확인] ~/.routinecode/knowledge/community-usage.json 을 Read하라(있으면). 그 entries의 각 surfaced 지식(id, errorSignature)에 대해 transcript로 (a)실제 적용 여부와 (b)에러 최종 해소 여부를 판정해 mcp__intelligence__record_verification(errorFixId=<id>, result, project)를 호출하라 — 적용+해소=prevented, 적용했으나 실패=still_failed, transcript에 적용 근거 없음=not_applicable(기본값). 근거 없는 prevented는 절대 금지. 이것이 지식이 성숙(observation→pattern→rule)하는 유일한 신호다. 기록을 마쳤으면 mcp__intelligence__run_knowledge_critic(force=true)를 호출해 방금 기록한 지식의 품질(앵커 실존/중복/저신뢰)을 검증·격리하라. 그 다음 반드시 mcp__intelligence__mark_session_recorded(sessionId='${sid}', extracted, grounded, reason)를 호출하라(기록 0건이어도)."
68
+ # docs/지식체계/38 E5: 비용이 든 해결 구간(도구 5회 이상)을 먼저 지식으로 만든다 — 문제 키를 그대로 쓴다.
69
+ res=$(RC_SID="$sid" RC_LIB="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)" python3 -c "
70
+ import os, sys, json
71
+ sys.path.insert(0, os.environ.get('RC_LIB', ''))
72
+ try:
73
+ import knowledge_items as ki
74
+ p = ki.account_path(ki._ks().account(), ki.RESOLUTIONS)
75
+ rows = [json.loads(l) for l in open(p) if l.strip()]
76
+ rows = [r for r in rows if r.get('sessionId') == os.environ.get('RC_SID')][-5:]
77
+ def _rej(r):
78
+ # 설계 27 T5: 편집했는데 같은 오류가 다시 난 시도 = 원인이 아니었던 변경(관찰 값)
79
+ rej = [', '.join(os.path.basename(f) for f in a) for a in (r.get('rejectedAttempts') or []) if a]
80
+ fix = ', '.join(os.path.basename(f) for f in (r.get('fixFiles') or []))
81
+ out = ''
82
+ if rej: out += ' 원인이 아니었던 변경(편집 후 같은 오류 재발)=[%s]' % ' | '.join(rej)
83
+ if fix: out += ' 해결 직전 편집=[%s]' % fix
84
+ return out
85
+ print(' / '.join('%s..%s 문제키=%s 이름=%s 도구=%s회%s' % (r.get('from'), r.get('to'), r.get('problemKey'), str(r.get('label') or '')[:80], r.get('tools'), _rej(r)) for r in rows))
86
+ except Exception:
87
+ print('')
88
+ " 2>/dev/null)
89
+ RES_NOTE=""
90
+ [ -n "$res" ] && RES_NOTE=" [해결 구간 우선 — docs/지식체계/38 E5] 이 세션에서 비용이 든 해결 구간: ${res}. 각 구간을 transcript 의 그 시각 범위에서 먼저 읽고, 원인과 해결이 확인되면 mcp__intelligence__record_knowledge(kind=resolution 또는 pitfall, problemKey=위 문제키 그대로, statement=한 문장, anchors·triggers·evidence.sessionId)로 기록하라. 일반 지식(LLM 이 이미 아는 것)이면 스킵 사유를 남겨라. '원인이 아니었던 변경'이 적힌 구간은 해법 기록 statement 에 '이건 원인이 아니었다'(그 파일들을 고쳐도 같은 오류)를 함께 남겨라 — 다음 사람이 같은 시도를 반복하지 않게. 적힌 파일 외의 추측은 쓰지 마라."
91
+ prompt="당신은 routinecode:recorder(지식 전담 기록자)다. 세션 transcript(${tp})를 Read/Grep으로 읽어 error-fix/pattern/quirk/decision/domain-knowledge를 추출하라. 감지된 signals: ${sig}. [도메인지식 능동 탐색 — 신호(${sig})에 domain_knowledge가 없어도 반드시 수행] transcript 전체에서 '코드만 읽어서는 알 수 없는' 정보를 능동적으로 찾아라. 판정 기준 단 하나: 이 정보를 코드/설정/git으로 유도할 수 있으면 저장 금지, 없으면 domain-knowledge다. 특히 두 유형을 놓치지 마라 — (1)암시적 발화: 키워드(기억해/절대/금지) 없이 규칙·정책·이유를 설명한 사용자 발화(예: '이건 카드사가 30분으로 정해둔 거라', '금요일 오후엔 배포 안 해'). '왜 이렇게 했나'의 답이 코드에 없으면 category=why/timing. (2)observed: 구현 중 외부 API가 문서와 다르게 동작한 관찰(예: '문서엔 X인데 실제 응답은 Y', 'rate limit 초과하면 24h 차단')→category=external, source=observed. category(why/timing/external/tenant)·source(user_correction/explicit/observed)·scope(관련 파일 절대경로 필수)를 채워 mcp__intelligence__record_domain_knowledge로 기록하라. 각 지식의 표면 표현을 mcp__intelligence__resolve_concept로 개념 후보를 받아 mcp__intelligence__record_grounding으로 의미층(concept)에 연결하라. 근거(에러원문/파일:line/사용자발화) 없는 지식은 절대 기록하지 마라. [Verification 폐루프 — signals에 verification이 있거나 항상 확인] ~/.routinecode/knowledge/community-usage.json 을 Read하라(있으면). 그 entries의 각 surfaced 지식(id, errorSignature)에 대해 transcript로 (a)실제 적용 여부와 (b)에러 최종 해소 여부를 판정해 mcp__intelligence__record_verification(errorFixId=<id>, result, project)를 호출하라 — 적용+해소=prevented, 적용했으나 실패=still_failed, transcript에 적용 근거 없음=not_applicable(기본값). 근거 없는 prevented는 절대 금지. 이것이 지식이 성숙(observation→pattern→rule)하는 유일한 신호다. [결정 전제 — 설계 27 T6] 기각·방향 결정을 mcp__intelligence__record_decision 으로 남길 때, 그 결정을 정당화한 전제가 transcript 에 관찰로 있으면(에러 원문·API 응답·버전·사용자 발화) premises=[{text:'전제 한 문장', check:'지금도 참인지 확인하는 읽기 전용 명령(grep·버전 확인·테스트)'}] 로 함께 남겨라. 관찰 없는 추측 전제는 쓰지 말고, check 에 쓰기·배포·삭제 명령을 넣지 마라. 같은 결정이 이미 있으면 같은 statement 로 다시 부르면 전제만 보강된다. 기록을 마쳤으면 mcp__intelligence__run_knowledge_critic(force=true)를 호출해 방금 기록한 지식의 품질(앵커 실존/중복/저신뢰)을 검증·격리하라. 그 다음 반드시 mcp__intelligence__mark_session_recorded(sessionId='${sid}', extracted, grounded, reason)를 호출하라(기록 0건이어도).${RES_NOTE}"
69
92
 
70
93
  drained=$((drained + 1))
71
94
  # 이 헤드리스 실행의 세션 id(분석 대상 세션 $sid 와 별개) — 유휴 판정 제외 목록에 남긴다
@@ -0,0 +1,28 @@
1
+ #!/bin/bash
2
+ # 압축 직후 남은 작업 재주입 (SessionStart matcher=compact)
3
+ # 근거: 압축 기준 A/B(11/05) — 20만 압축 군은 결함 목록은 요약에 보존됐지만, 요약이 남은 점검을
4
+ # "Optionally ..." 로 낮춰 적어 압축 뒤 1~4회 호출 만에 마무리했다(40만 군 97~100회 대비 53~76회).
5
+ # 압축 직후 한 번, 요약의 남은 작업이 필수임을 되돌린다. 실패해도 세션을 막지 않는다(무출력 종료).
6
+ # 요청 원문·살펴본 파일 목록까지 재주입하는 안은 A/B(5회)에서 이 버전보다 나아지지 않아 기각했다(11/05).
7
+ # Kill switch: ROUTINECODE_COMPACT_RESUME_DISABLED=1
8
+ [ "${ROUTINECODE_COMPACT_RESUME_DISABLED:-0}" = "1" ] && exit 0
9
+ INPUT=""
10
+ if [ ! -t 0 ]; then INPUT=$(cat); fi
11
+ RC_INPUT="$INPUT" python3 -c '
12
+ import json, os
13
+ try:
14
+ src = json.loads(os.environ.get("RC_INPUT") or "{}").get("source")
15
+ except Exception:
16
+ src = None
17
+ if src != "compact":
18
+ raise SystemExit(0)
19
+ msg = (
20
+ "[RoutineCode] The conversation was just compacted. The pending tasks and remaining checks listed in the "
21
+ "summary are still part of the original task, not optional, even if the summary marks them as "
22
+ "\"optional\" or \"quick\". Unless the user narrowed the scope, finish every remaining check with the same "
23
+ "depth as before compaction, then deliver the final output. Do not re-read what the summary already "
24
+ "records as verified; continue from the remaining items."
25
+ )
26
+ print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": msg}}))
27
+ ' 2>/dev/null || true
28
+ exit 0
@@ -45,6 +45,13 @@ RC_CONFIG="$HOME/.routinecode/config.json"
45
45
  MESSAGES="${ROUTINECODE_CARRY_MESSAGES:-}"
46
46
  HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)"
47
47
 
48
+ # --- 에이전트·명령 정의 추출 (설치 시점 postinstall 은 2.31.85 에서 없앴다) ---
49
+ # `routinecode` 실행기 대신 `claude` 를 바로 띄운 사용자도 정의 파일을 받게 한다. 정의가 이미 있으면 건너뛴다.
50
+ # 로더는 네트워크·프로세스 실행 없이 bin/prompt-vault.dat 를 plugin/ 아래로만 푼다(개발 체크아웃은 건너뜀).
51
+ if [ ! -f "$HOOKS_DIR/../plugin/agents/explorer.md" ] && [ -f "$HOOKS_DIR/../bin/prompt-vault.js" ]; then
52
+ node "$HOOKS_DIR/../bin/prompt-vault.js" >/dev/null 2>&1 || true
53
+ fi
54
+
48
55
  # --- recorder 큐 자율 드레인 (헤드리스, 백그라운드 비블로킹) ---
49
56
  # 이전 세션에서 적재된 지식 recording task를 헤드리스 recorder가 자율 처리한다.
50
57
  # 메인 에이전트와 완전 무관 — 트리거 신뢰성의 핵심. 재귀/중복은 runner가 방지.
@@ -166,6 +173,11 @@ find /tmp -maxdepth 1 -name 'routinecode-agent-state-*.json.lock' -mmin +1 -dele
166
173
  find "$RC_RUNDIR" -maxdepth 1 -name 'mcp-alive' -mmin +1440 -delete 2>/dev/null
167
174
  find /tmp -maxdepth 1 -name 'mcp-alive' -mmin +1440 -delete 2>/dev/null
168
175
  find /tmp -maxdepth 1 -name 'routinecode-agent-state-*.json.tmp.*' -mmin +1 -delete 2>/dev/null
176
+ # 설계 15: 실행별 파일·절감 상태는 재개를 위해 세션 뒤에도 남기고 14일 뒤 지운다.
177
+ find "$RC_RUNDIR" -maxdepth 1 \( -name 'run-*.json' -o -name 'launch-*' \) -mtime +14 -delete 2>/dev/null
178
+ if [ -d "$RC_RUNDIR/savings" ]; then
179
+ find "$RC_RUNDIR/savings" -mindepth 1 -maxdepth 1 -type d -mtime +14 -exec rm -rf {} + 2>/dev/null
180
+ fi
169
181
 
170
182
  # Deploy tracker: 24h 초과 라인만 삭제 (Stop hook v2가 참조하는 JSONL)
171
183
  DEPLOY_TRACKER="$RC_RUNDIR/routinecode-deploy-tracker.jsonl"
@@ -199,7 +211,13 @@ fi
199
211
  # Legacy JSON tracker 제거 (v1 → v2 마이그레이션)
200
212
  rm -f $RC_RUNDIR/routinecode-deploy-tracker.json
201
213
 
202
- if [ -f "$ATTEMPTS_FILE" ]; then
214
+ if [ -f "$ATTEMPTS_FILE" ] && [ -f "$HOOKS_DIR/lib/escalation_restore.py" ]; then
215
+ # 설계 27 T4: 키가 <서명>@<프로젝트> — 이 프로젝트 기록·7일 TTL 만 세고 안내엔 issueId 원문을 보인다
216
+ ESCALATION_CHECK=$(python3 "$HOOKS_DIR/lib/escalation_restore.py" "$ATTEMPTS_FILE" "$STATE_FILE" "${CLAUDE_PROJECT_DIR:-$PWD}" 2>/dev/null)
217
+ if [ -n "$ESCALATION_CHECK" ]; then
218
+ MESSAGES="${ESCALATION_CHECK}"
219
+ fi
220
+ elif [ -f "$ATTEMPTS_FILE" ]; then
203
221
  ESCALATION_CHECK=$(python3 -c "
204
222
  import json
205
223
  try:
@@ -795,9 +813,8 @@ try:
795
813
  import hashlib
796
814
  machine_id = hashlib.md5(os.uname().nodename.encode()).hexdigest()[:16]
797
815
 
798
- # apiKey 재발급 성공 — 이전 무효화 잔재(2.4 가 남긴 사유/시각)를 명시 제거한다.
799
- # 아래 config 를 새 dict 로 통째 교체하므로 잔재는 자연 소멸하지만, 향후 이 블록이
800
- # merge 방식으로 바뀌어도 잔재가 남지 않도록 authUrl 등 기존 유효 키는 보존하며 정리.
816
+ # apiKey 재발급 성공 — 기존 설정 위에 병합한다. 통째 교체하면 사용자 끄기(knowledgeSyncDisabled,
817
+ # shareSnippets, telemetryEnabled)와 locale 등이 사라진다(설계 15 §4.5). 무효화 잔재만 지운다.
801
818
  prior = {}
802
819
  try:
803
820
  if os.path.exists(config_path):
@@ -805,7 +822,13 @@ try:
805
822
  except Exception:
806
823
  prior = {}
807
824
 
808
- config = {
825
+ config = dict(prior)
826
+ # 키가 있는데 syncEnabled=false 면 사용자가 직접 끈 것이다. 재발급이 되돌리지 않게 명시 값으로 옮긴다.
827
+ if prior.get('syncEnabled') is False and prior.get('apiKey'):
828
+ config['knowledgeSyncDisabled'] = True
829
+ for stale in ('teamTenantId', 'teamName', 'loggedOut'):
830
+ config.pop(stale, None)
831
+ config.update({
809
832
  'syncEnabled': True,
810
833
  'serverUrl': result.get('serverUrl', server_url),
811
834
  'apiKey': result.get('apiKey'),
@@ -813,18 +836,17 @@ try:
813
836
  'userId': result.get('userId'),
814
837
  'tenantId': result.get('tenantId'),
815
838
  'provisionedAt': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
816
- 'growthApiUrl': result.get('growthApiUrl', os.environ.get('GROWTH_API_URL', '')),
817
- 'internalApiKey': result.get('internalApiKey', os.environ.get('INTERNAL_API_KEY', '')),
818
- }
819
- # 기존에 사용자가 지정한 authUrl 은 보존(있으면).
820
- if prior.get('authUrl'):
821
- config['authUrl'] = prior['authUrl']
839
+ })
840
+ for k, env_name in (('growthApiUrl', 'GROWTH_API_URL'), ('internalApiKey', 'INTERNAL_API_KEY')):
841
+ v = result.get(k) or os.environ.get(env_name, '')
842
+ if v:
843
+ config[k] = v
822
844
  # 팀 귀속 보존: 팀으로 재발급이 실제 적용됐을 때만(teamApplied!=False) 팀 필드를 유지.
823
845
  if team_tid and result.get('teamApplied') is not False:
824
846
  config['teamTenantId'] = result.get('issuedTenantId') or team_tid
825
847
  if team_name:
826
848
  config['teamName'] = team_name
827
- # 무효화 잔재는 새 config 에 절대 싣지 않는다(명시).
849
+ # 무효화 잔재는 병합 결과에 남기지 않는다.
828
850
  config.pop('apiKeyInvalidReason', None)
829
851
  config.pop('apiKeyInvalidatedAt', None)
830
852
 
@@ -1289,6 +1311,34 @@ except Exception:
1289
1311
  " 2>/dev/null
1290
1312
  fi
1291
1313
 
1314
+ # --- 4.5.2. 디자인 스킬 팩 (설계 23 §5.1, 기본 꺼짐) ---
1315
+ # 백그라운드 세션(recorder·architect·maintenance)은 건너뛴다(F6 관례). ROUTINECODE_SKILL_PACKS=0 이거나 state.json 이 enabled:false 면
1316
+ # node 를 띄우지 않고 셸에서 바로 건너뛴다 — 처음 한 번 안내가 남은 경우(noticeShown 아님)만 예외. 실패는 통과.
1317
+ # 5초 제한은 macOS 에 timeout 이 없으므로 sync 안에서 건다(fetch 4초 + 전체 예산). 첫 줄 changed → reloadSkills, notice → 안내 한 줄.
1318
+ RC_RELOAD_SKILLS=""
1319
+ _RC_SP_STATE="${ROUTINECODE_DIR:-$HOME/.routinecode}/skill-packs/state.json"
1320
+ if [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ "${ROUTINECODE_ARCHITECT:-}" != "1" ] && [ "${ROUTINECODE_MAINTENANCE:-}" != "1" ] \
1321
+ && [ -f "$HOOKS_DIR/../bin/rc-skills.js" ] && command -v node >/dev/null 2>&1; then
1322
+ _RC_SP_SKIP=""
1323
+ if [ -f "$_RC_SP_STATE" ] && grep -q '"noticeShown":true' "$_RC_SP_STATE" 2>/dev/null; then
1324
+ if [ "${ROUTINECODE_SKILL_PACKS:-}" = "0" ] || grep -q '"enabled":false' "$_RC_SP_STATE" 2>/dev/null; then
1325
+ _RC_SP_SKIP=1
1326
+ fi
1327
+ fi
1328
+ if [ -z "$_RC_SP_SKIP" ]; then
1329
+ _RC_SP_OUT=$(node "$HOOKS_DIR/../bin/rc-skills.js" sync 2>/dev/null) || _RC_SP_OUT=""
1330
+ case "$(printf '%s\n' "$_RC_SP_OUT" | head -n 1)" in
1331
+ changed) RC_RELOAD_SKILLS=1 ;;
1332
+ notice)
1333
+ _RC_SP_MSG=$(printf '%s\n' "$_RC_SP_OUT" | sed -n '2p')
1334
+ if [ -n "$_RC_SP_MSG" ]; then
1335
+ MESSAGES="${MESSAGES:+$MESSAGES | }${_RC_SP_MSG}"
1336
+ fi
1337
+ ;;
1338
+ esac
1339
+ fi
1340
+ fi
1341
+
1292
1342
  # --- 4.5.1. Fleet presence (1일 1회, 무인증, fail-open — design 09 §2) ---
1293
1343
  # opt-out: env ROUTINECODE_TELEMETRY=off 또는 config telemetryEnabled=false (sync_manager와 동일 키).
1294
1344
  # apiKey·syncEnabled와 무관하게 동작(키 미보유 설치자 관측 목적 §2.3) — opt-out은 절대 우선(P2).
@@ -1430,15 +1480,29 @@ fi
1430
1480
 
1431
1481
  # --- 5.5. session_start 이벤트 기록 ---
1432
1482
  (
1433
- python3 -c "
1483
+ RC_SS_INPUT="$_RC_SS_INPUT" python3 -c "
1434
1484
  import json, os, time, hashlib, platform
1435
1485
  from datetime import datetime, timezone
1436
1486
 
1437
1487
  log_dir = os.path.expanduser('~/.routinecode/usage')
1438
1488
  os.makedirs(log_dir, exist_ok=True)
1439
1489
 
1440
- # session_id: 랜덤 생성 (session-start hook에는 입력 JSON 없음)
1441
- session_id = hashlib.md5((str(time.time()) + str(os.getpid())).encode()).hexdigest()[:12]
1490
+ # session_id: 훅 입력의 실제 ID. 토큰 이벤트와 같은 값이어야 세션별 집계가 묶인다.
1491
+ # 입력이 없을 때만 랜덤으로 두고 id_source 로 남긴다(조용한 폴백 금지). session_title 은 전송하지 않는다.
1492
+ try:
1493
+ ss_input = json.loads(os.environ.get('RC_SS_INPUT') or '{}')
1494
+ ss_input = ss_input if isinstance(ss_input, dict) else {}
1495
+ except Exception:
1496
+ ss_input = {}
1497
+ _sid = ss_input.get('session_id')
1498
+ if isinstance(_sid, str) and _sid:
1499
+ session_id = _sid[:12]
1500
+ id_source = 'hook'
1501
+ else:
1502
+ session_id = hashlib.md5((str(time.time()) + str(os.getpid())).encode()).hexdigest()[:12]
1503
+ id_source = 'random'
1504
+ _src = ss_input.get('source')
1505
+ start_source = _src[:20] if isinstance(_src, str) and _src else 'unknown'
1442
1506
 
1443
1507
  now = datetime.now(timezone.utc)
1444
1508
 
@@ -1462,22 +1526,51 @@ except Exception:
1462
1526
  if not machine_id:
1463
1527
  machine_id = hashlib.md5(os.uname().nodename.encode()).hexdigest()[:16]
1464
1528
 
1529
+ # run_key: 같은 터미널로 추정되는 세션 묶음. 값이 없으면 null(평면 목록), PID 추정은 쓰지 않는다.
1530
+ run_key = None
1531
+ for _k in ('TMUX_PANE', 'WEZTERM_PANE', 'KITTY_WINDOW_ID', 'WT_SESSION', 'TERM_SESSION_ID'):
1532
+ _v = os.environ.get(_k)
1533
+ if _v:
1534
+ run_key = hashlib.sha1((machine_id + _v).encode('utf-8', 'replace')).hexdigest()[:10]
1535
+ break
1536
+
1465
1537
  event = {
1466
1538
  'at': now.isoformat(),
1467
1539
  'date': now.strftime('%Y-%m-%d'),
1468
1540
  'session': session_id,
1469
1541
  'type': 'session_start',
1470
1542
  'cost': 0,
1543
+ 'usage_version': 2,
1471
1544
  'cwd': os.path.basename(os.getcwd()),
1472
1545
  'metadata': {
1473
1546
  'version': version,
1474
1547
  'platform': platform.system().lower(),
1475
1548
  'machineId': machine_id,
1549
+ 'start_source': start_source,
1550
+ 'id_source': id_source,
1476
1551
  }
1477
1552
  }
1553
+ if run_key:
1554
+ event['metadata']['run_key'] = run_key
1555
+
1556
+ # 실행별 파일(공유 파일 금지). 압축·재개로 다시 불려도 처음 시작 시각을 유지한다.
1557
+ start_ts = time.time()
1558
+ run_path = '$RC_RUNDIR/run-' + session_id + '.json'
1559
+ try:
1560
+ _prev = json.load(open(run_path)).get('start_ts')
1561
+ if isinstance(_prev, (int, float)):
1562
+ start_ts = _prev
1563
+ except Exception:
1564
+ pass
1565
+ try:
1566
+ with open(run_path, 'w') as f:
1567
+ json.dump({'session_id': session_id, 'run_key': run_key, 'start_source': start_source,
1568
+ 'id_source': id_source, 'start_ts': start_ts}, f)
1569
+ except Exception:
1570
+ pass
1478
1571
 
1479
1572
  # timestamp 파일 (session_end에서 duration 계산용)
1480
- ts_data = json.dumps({'session_id': session_id, 'start_ts': time.time()})
1573
+ ts_data = json.dumps({'session_id': session_id, 'start_ts': time.time(), 'id_source': id_source})
1481
1574
  with open('$RC_RUNDIR/routinecode-session-latest.json', 'w') as f:
1482
1575
  f.write(ts_data)
1483
1576
 
@@ -1496,6 +1589,13 @@ disown
1496
1589
  ) &
1497
1590
  disown
1498
1591
 
1592
+ # --- 6b. 새 형식 지식(v31) 끌어오기 + 노출·마주침 대기열 flush (docs/지식체계/36 §4·§5, 10분에 1번, 백그라운드) ---
1593
+ (
1594
+ _KI_LIB="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)"
1595
+ [ -f "$_KI_LIB/knowledge_items.py" ] && python3 "$_KI_LIB/knowledge_items.py" --pull </dev/null >/dev/null 2>&1
1596
+ ) &
1597
+ disown
1598
+
1499
1599
  # --- 7. Continual Learning: promote rules (이전 세션 데이터 → 규칙 승격) ---
1500
1600
  ROUTINECODE_HOME="${ROUTINECODE_HOME:-$(dirname "$HOOKS_DIR")}"
1501
1601
  PROMOTE_RESULT=$(node -e "
@@ -1590,11 +1690,59 @@ if [ -n "$PERM_WARN" ]; then
1590
1690
  MESSAGES="${MESSAGES:+$MESSAGES | }${PERM_WARN}"
1591
1691
  fi
1592
1692
 
1693
+ # --- 팀 계정 지식 공유 안내 (docs/지식체계/36 §16.2): 팀 계정이면 세션 시작 1회, 개인 계정은 침묵 ---
1694
+ if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ -n "$_RC_HOOK_LIB" ]; then
1695
+ TEAM_KNOWLEDGE_LINE=$(python3 "$_RC_HOOK_LIB/knowledge_scope.py" --notice 2>/dev/null)
1696
+ if [ -n "$TEAM_KNOWLEDGE_LINE" ]; then
1697
+ MESSAGES="${MESSAGES:+$MESSAGES | }${TEAM_KNOWLEDGE_LINE}"
1698
+ fi
1699
+ fi
1700
+
1701
+ # --- 세션 영수증: 새 세션 첫 턴에 이전 세션 사용량 한 줄 (설계 15 §2.6) ---
1702
+ if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ -n "$_RC_HOOK_LIB" ]; then
1703
+ PREV_SESSION_LINE=$(printf '%s' "$_RC_SS_INPUT" | python3 "$_RC_HOOK_LIB/receipt.py" --prev-session 2>/dev/null)
1704
+ if [ -n "$PREV_SESSION_LINE" ]; then
1705
+ MESSAGES="${MESSAGES:+$MESSAGES | }${PREV_SESSION_LINE}"
1706
+ fi
1707
+ fi
1708
+
1709
+ # --- 공유 판 (설계 31): 세션 PID → session_id 기록 + 판 요약을 모델 맥락에 (판이 비면 침묵) ---
1710
+ RC_BOARD_CTX=""
1711
+ if [ "$ROUTINECODE_MAINTENANCE" != "1" ] && [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ -n "$_RC_HOOK_LIB" ] && [ -f "$_RC_HOOK_LIB/board.py" ]; then
1712
+ RC_BOARD_CTX=$(printf '%s' "$_RC_SS_INPUT" | _RC_LIB="$_RC_HOOK_LIB" python3 -c '
1713
+ import json, os, sys
1714
+ sys.path.insert(0, os.environ["_RC_LIB"])
1715
+ try:
1716
+ import board
1717
+ d = json.loads(sys.stdin.read() or "{}")
1718
+ sid = str(d.get("session_id") or "")[:12]
1719
+ cwd = d.get("cwd") or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
1720
+ if sid:
1721
+ board.record_session(sid, cwd=cwd)
1722
+ print(board.summary(sid, cwd=cwd))
1723
+ except Exception:
1724
+ pass
1725
+ ' 2>/dev/null)
1726
+ fi
1727
+
1593
1728
  # --- Output ---
1594
1729
  # JSON 은 반드시 직렬화기로 만든다 — 메시지에 줄바꿈·역슬래시가 섞이면 손으로 만든 JSON 이 깨져
1595
1730
  # Claude Code 가 "hook output opens a JSON payload that never completed" 로 거부한다.
1596
- RC_HOOK_MESSAGES="$MESSAGES" python3 -c '
1731
+ # 디자인 스킬 팩을 이번 시작에 설치·교체했으면(RC_RELOAD_SKILLS=1) reloadSkills 를 합쳐 첫 프롬프트에 반영한다(설계 23 §5.1).
1732
+ RC_HOOK_MESSAGES="$MESSAGES" RC_RELOAD_SKILLS="${RC_RELOAD_SKILLS:-}" RC_BOARD_CTX="$RC_BOARD_CTX" python3 -c '
1597
1733
  import json, os
1598
1734
  m = os.environ.get("RC_HOOK_MESSAGES", "").strip()
1599
- print(json.dumps({"continue": True, "systemMessage": "[HOOK] " + m} if m else {"continue": True}, ensure_ascii=False))
1600
- ' 2>/dev/null || echo '{"continue":true}'
1735
+ out = {"continue": True, "systemMessage": "[HOOK] " + m} if m else {"continue": True}
1736
+ if os.environ.get("RC_RELOAD_SKILLS") == "1":
1737
+ out["hookSpecificOutput"] = {"hookEventName": "SessionStart", "reloadSkills": True}
1738
+ board_ctx = os.environ.get("RC_BOARD_CTX", "").strip()
1739
+ if board_ctx:
1740
+ out.setdefault("hookSpecificOutput", {"hookEventName": "SessionStart"})["additionalContext"] = board_ctx
1741
+ print(json.dumps(out, ensure_ascii=False))
1742
+ ' 2>/dev/null || {
1743
+ if [ "${RC_RELOAD_SKILLS:-}" = "1" ]; then
1744
+ echo '{"continue":true,"hookSpecificOutput":{"hookEventName":"SessionStart","reloadSkills":true}}'
1745
+ else
1746
+ echo '{"continue":true}'
1747
+ fi
1748
+ }
@@ -0,0 +1,37 @@
1
+ #!/bin/bash
2
+ # 팀 스킬 사용 측정 (docs/지식체계/38 S4).
3
+ # - PostToolUse(Skill): 우리 스킬(rc-*)을 불렀다 → 사용 구간을 연다.
4
+ # - Stop: 이 턴의 열린 스킬 구간을 닫고 도구·초·토큰·$ 를 skill_use 이벤트로 보낸다.
5
+ # - fail-open: 어떤 실패도 {"continue":true}
6
+
7
+ INPUT=$(cat)
8
+ HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)"
9
+
10
+ ROUTINECODE_HOOK_INPUT="$INPUT" _HOOK_LIB_DIR="$HOOKS_DIR/lib" python3 - <<'PYEOF' 2>/dev/null || echo '{"continue":true}'
11
+ import json, os, sys
12
+
13
+ try:
14
+ inp = json.loads(os.environ.get('ROUTINECODE_HOOK_INPUT', '') or '{}')
15
+ sys.path.insert(0, os.environ.get('_HOOK_LIB_DIR', ''))
16
+ import knowledge_items as ki
17
+ sid = inp.get('session_id') or 'unknown'
18
+ ev = inp.get('hook_event_name') or ''
19
+ if ev == 'PostToolUse':
20
+ ti = inp.get('tool_input') or {}
21
+ name = str(ti.get('skill') or ti.get('name') or '') if isinstance(ti, dict) else ''
22
+ name = name.split(':')[-1] # 'plugin:skill' 형태 대비
23
+ if name.startswith('rc-'):
24
+ ki.skill_started(sid, name)
25
+ elif ev == 'Stop':
26
+ if ki.skills_finished(sid, transcript_path=inp.get('transcript_path')):
27
+ ki.flush_background()
28
+ # 설계 33: 턴 끝 — 공유 판 전송 대기열(MCP board_* 가 쌓은 것 포함)을 백그라운드로 보낸다
29
+ try:
30
+ import board_sync
31
+ board_sync.flush_background()
32
+ except Exception:
33
+ pass
34
+ except Exception:
35
+ pass
36
+ print(json.dumps({"continue": True}))
37
+ PYEOF
@@ -606,6 +606,18 @@ if deferral_hits and confirmed_claims:
606
606
  except Exception:
607
607
  pass
608
608
 
609
+ # ─── L6.5: 확인 질문 판정 (설계 27 T2·T3, ROUTINECODE_CLAIM_CQ=on 일 때만) ──
610
+ # 결정·비선택 서술을 주장에서 빼고, 영역마다 '실행 있나 · 마지막 편집 뒤인가 · 대상 맞나'를
611
+ # 이번 턴 실행 기록과 대조한다. 답이 '아니오'인 것만 그 이유로 경고, '모름'은 아래 기존 판정.
612
+ cq_result = None
613
+ try:
614
+ import claim_structure as _cs
615
+ if _cs.enabled():
616
+ cq_result = _cs.apply(confirmed_claims, _cs.turn_activity(entries, last_user_idx, last_asst_idx), evidence_found, primary_locale)
617
+ confirmed_claims = cq_result['claims']
618
+ except Exception:
619
+ cq_result = None
620
+
609
621
  # ─── L7: Evidence-First 판정 ──────────────────────────────────
610
622
  if not confirmed_claims:
611
623
  if pending_msg_extra:
@@ -618,8 +630,14 @@ claimed = sorted(set(c for c, _ in confirmed_claims))
618
630
  # 증거 gap 계산
619
631
  gap_domains = [d for d in claimed if d not in evidence_found]
620
632
  failed_domains = [d for d in claimed if d in evidence_failed]
621
-
622
- if not gap_domains and not failed_domains:
633
+ cq_reasons = []
634
+ if cq_result is not None:
635
+ # 확인 질문이 판정한 영역은 그 답을 따르고, '모름'인 영역만 기존 판정을 쓴다
636
+ gap_domains = [d for d in gap_domains if d in cq_result['deferred']]
637
+ failed_domains = [d for d in failed_domains if d in cq_result['deferred']]
638
+ cq_reasons = cq_result['reasons']
639
+
640
+ if not gap_domains and not failed_domains and not cq_reasons:
623
641
  # 모든 주장이 증거로 뒷받침됨
624
642
  if pending_msg_extra:
625
643
  emit({"continue": True, "systemMessage": "[STOP HOOK v3]" + pending_msg_extra})
@@ -637,7 +655,7 @@ label_map = {
637
655
  'test_ok': 'test',
638
656
  }
639
657
 
640
- reasons = []
658
+ reasons = list(cq_reasons)
641
659
  for d in failed_domains:
642
660
  reasons.append(_t('stop.v3_failure_evidence', label=label_map.get(d, d)))
643
661
  for d in gap_domains: