@routinecrew/routinecode 2.31.87 → 2.31.90

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 (65) hide show
  1. package/bin/cli.sh +10 -0
  2. package/bin/prompt-vault.dat +1 -1
  3. package/bin/rc-login.js +5 -4
  4. package/bin/rc-savings.js +808 -0
  5. package/bin/rc-suggestions.js +100 -0
  6. package/bin/rc-team.js +1 -1
  7. package/bin/setup.js +1 -1
  8. package/hooks/hooks-config.json +9 -0
  9. package/hooks/lib/agent_budget.py +2 -0
  10. package/hooks/lib/calibration.json +89 -0
  11. package/hooks/lib/card_gate.py +735 -0
  12. package/hooks/lib/cc-surface.json +1 -1
  13. package/hooks/lib/codemode_guard.py +30 -0
  14. package/hooks/lib/command_fix.py +209 -0
  15. package/hooks/lib/delegate_nudge.py +179 -0
  16. package/hooks/lib/deploy_suggest.py +312 -0
  17. package/hooks/lib/emit_raw.py +4 -0
  18. package/hooks/lib/knowledge_items.py +281 -22
  19. package/hooks/lib/knowledge_stock.py +708 -0
  20. package/hooks/lib/known_solution.py +1 -1
  21. package/hooks/lib/ops_guard.py +549 -0
  22. package/hooks/lib/prices.json +8 -0
  23. package/hooks/lib/route_ledger.py +622 -0
  24. package/hooks/lib/route_rules.json +88 -0
  25. package/hooks/lib/savings_emit.py +93 -0
  26. package/hooks/lib/secret_filter.py +11 -0
  27. package/hooks/lib/sync_manager.py +4 -1
  28. package/hooks/post-bash-verify.sh +14 -0
  29. package/hooks/post-edit-track.sh +9 -0
  30. package/hooks/pre-agent-spawn.mjs +1 -1
  31. package/hooks/pre-agent-spawn.sh +22 -2
  32. package/hooks/pre-bash-guard.sh +31 -0
  33. package/hooks/pre-bash-knowledge.sh +12 -2
  34. package/hooks/pre-edit-delegate.sh +15 -0
  35. package/hooks/pre-edit-guard.sh +10 -0
  36. package/hooks/pre-read-guard.sh +10 -0
  37. package/hooks/session-start.sh +6 -0
  38. package/hooks/stop-usage-metrics.sh +6 -0
  39. package/hooks/subagent-stop-usage.sh +36 -4
  40. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  41. package/mcp-intelligence/dist/knowledge-record.js +1 -1
  42. package/mcp-routinecode/dist/index.js +1 -1
  43. package/package.json +1 -1
  44. package/plugin/.claude-plugin/plugin.json +1 -1
  45. package/plugin/agents/analyzer.md.sealed +1 -1
  46. package/plugin/agents/architect.md.sealed +1 -1
  47. package/plugin/agents/crawler.md.sealed +1 -1
  48. package/plugin/agents/explorer.md.sealed +1 -1
  49. package/plugin/agents/implementor-lite.md.sealed +1 -0
  50. package/plugin/agents/implementor.md.sealed +1 -1
  51. package/plugin/agents/looker.md.sealed +1 -1
  52. package/plugin/agents/ops-lite.md.sealed +1 -0
  53. package/plugin/agents/planner.md.sealed +1 -1
  54. package/plugin/agents/recorder.md.sealed +1 -1
  55. package/plugin/agents/reviewer.md.sealed +1 -1
  56. package/plugin/agents/runner-lite.md.sealed +1 -0
  57. package/plugin/agents/verifier.md.sealed +1 -1
  58. package/plugin/commands/analyze.md.sealed +1 -1
  59. package/plugin/commands/plan.md.sealed +1 -1
  60. package/plugin/commands/rc.md.sealed +1 -1
  61. package/plugin/commands/receipt.md.sealed +1 -1
  62. package/plugin/commands/recharge.md.sealed +1 -1
  63. package/plugin/commands/routines.md.sealed +1 -1
  64. package/plugin/commands/share.md.sealed +1 -1
  65. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -0,0 +1,708 @@
1
+ # -*- coding: utf-8 -*-
2
+ """기존 지식 재고 정리 (routinecode/.routinecode/plans/knowledge-utilization.md W3).
3
+
4
+ 현재 계정의 지식 항목을 노출(attribution ledger)·해결(resolutions.jsonl) 근거로 분류해
5
+ 보고서(stock-report.md)와 재우기 제안(stock-proposal.json)을 만든다. 적용은 사람이 보고서를 본 뒤에만.
6
+
7
+ CLI:
8
+ python3 knowledge_stock.py --report [--out DIR] 읽기만 한다. DIR(기본: 계정 디렉터리)에 두 파일을 쓴다.
9
+ python3 knowledge_stock.py --apply FILE 제안 FILE 의 retire[].kid 를 계정 items.retired.json 에 합쳐 쓴다.
10
+ python3 knowledge_stock.py --auto [--force] [--transcripts DIR] 7일에 한 번 노출·반영 측정, 반영 0 재움, 명령 지식 승격(items.promoted.json), stock-auto.json 이력.
11
+ 되돌리기 = 계정 items.retired.json 삭제.
12
+
13
+ 분류(앞 조건 우선): codified → mistriggered → noisy → stale → keep.
14
+ 오류 시 메시지를 stderr 에 내고 exit 1. 표준 라이브러리만, Python 3.9 호환.
15
+ """
16
+ import bisect
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+ import time
22
+ from datetime import datetime, timezone
23
+
24
+ _HERE = os.path.dirname(os.path.abspath(__file__))
25
+ if _HERE not in sys.path:
26
+ sys.path.insert(0, _HERE)
27
+
28
+ import knowledge_items as ki # noqa: E402
29
+ import knowledge_scope as ks # noqa: E402
30
+
31
+ RETIRED_FILE = 'items.retired.json'
32
+ # 설계 36-2 v1.1: 노출 많고 반영 0 은 내용이 아니라 때가 틀린 경우가 많다 → 재우지 않고 읽기·편집 주입만 끈다
33
+ QUIET_FILE = 'items.quiet.json'
34
+ RESOLUTIONS_FILE = 'resolutions.jsonl'
35
+ REPORT_FILE = 'stock-report.md'
36
+ PROPOSAL_FILE = 'stock-proposal.json'
37
+ TOP_N = 20
38
+ NOISY_SESSIONS = 10
39
+ STALE_DAYS = 90
40
+ STATEMENT_PREVIEW = 80
41
+
42
+ CLASSES = ('codified', 'mistriggered', 'noisy', 'stale', 'keep')
43
+ # mistriggered 는 재우지 않는다 — 유용한 명령 함정이라 command 트리거로 다시 쓸 후보다(설계 36 2단계)
44
+ RETIRE_CLASSES = ('codified', 'noisy', 'stale')
45
+ REASONS = {
46
+ 'codified': 'command_fix 가 코드로 교정',
47
+ 'mistriggered': '명령 함정이 파일 트리거로 저장돼 엉뚱한 편집 때 주입 — command 트리거 재작성 후보',
48
+ 'noisy': '노출 세션 %d 이상인데 해결 0',
49
+ 'stale': '%d일 넘게 노출 없음',
50
+ }
51
+ CMD_WORDS = ('git', 'npm', 'pnpm', 'npx', 'python3', 'pip', 'docker', 'ssh', 'rsync', 'grep', 'find',
52
+ 'psql', 'curl', 'kubectl')
53
+ # 명령 호출 모양(낱말 + 하위 명령·옵션)만 본다. 'python3.14 venv' 같은 서술은 제외(실재고 오탐 8건 중 7건)
54
+ _CMD_RE = re.compile(r'(?<![A-Za-z0-9_\-./])(' + '|'.join(re.escape(w) for w in CMD_WORDS) + r')\s+(-{1,2}[A-Za-z]|[a-z][\w-]*)')
55
+ _FAIL_RE = re.compile(r'fatal:|error|에러|오류|실패|not found|exit \d+|denied|차단|막힌|안 된다|않는다|금지')
56
+
57
+
58
+ def _attribution_dir():
59
+ return os.environ.get('ROUTINECODE_ATTRIBUTION_DIR') or os.path.join(os.path.expanduser('~'), '.routinecode', 'attribution')
60
+
61
+
62
+ def _statement_flat(item):
63
+ return ' '.join(str(item.get('statement') or '').split())
64
+
65
+
66
+ def _kids_of(acct, name):
67
+ """계정 폴더 name({"kids": [...]}) 의 kid 집합. 없거나 깨졌으면 빈 집합."""
68
+ try:
69
+ with open(ki.account_path(acct, name), encoding='utf-8') as f:
70
+ d = json.load(f)
71
+ return set(str(k) for k in (d.get('kids') or [])) if isinstance(d, dict) else set()
72
+ except Exception:
73
+ return set()
74
+
75
+
76
+ def _retired_kids(acct):
77
+ """계정 items.retired.json 의 kid 집합. 없거나 깨졌으면 빈 집합."""
78
+ return _kids_of(acct, RETIRED_FILE)
79
+
80
+
81
+ def all_items(acct):
82
+ """load() 와 같은 규칙(계정 격리·중복 제거)을 쓰되 retired 필터는 적용하지 않는다(재움 항목도 보고서에 보인다)."""
83
+ out, seen = [], set()
84
+ for name, conv in (('items.server.jsonl', ki._from_server), ('items.jsonl', ki._from_local)):
85
+ p = ki.account_path(acct, name)
86
+ if not p:
87
+ continue
88
+ for r in ki._read_jsonl(p):
89
+ it = conv(r)
90
+ if not it or not it['statement'] or not ks.visible(it, acct):
91
+ continue
92
+ k = ki.dedup_key(it)
93
+ if k in seen:
94
+ continue
95
+ seen.add(k)
96
+ out.append(it)
97
+ return out
98
+
99
+
100
+ def exposure_stats(attr_dir):
101
+ """ledger-*.jsonl 를 읽어 kid → {'count', 'sessions'(set), 'last'(ts)}. 세션 id 는 파일 이름의 sid12."""
102
+ stats = {}
103
+ try:
104
+ names = sorted(os.listdir(attr_dir))
105
+ except Exception:
106
+ return stats
107
+ for name in names:
108
+ if not (name.startswith('ledger-') and name.endswith('.jsonl')):
109
+ continue
110
+ sid = name[len('ledger-'):-len('.jsonl')]
111
+ for r in ki._read_jsonl(os.path.join(attr_dir, name)):
112
+ kid = r.get('kid')
113
+ if not kid:
114
+ continue
115
+ st = stats.setdefault(str(kid), {'count': 0, 'sessions': set(), 'last': None})
116
+ st['count'] += 1
117
+ st['sessions'].add(sid)
118
+ ts = ki._parse_ts(r.get('at'))
119
+ if ts is not None and (st['last'] is None or ts > st['last']):
120
+ st['last'] = ts
121
+ return stats
122
+
123
+
124
+ def resolution_stats(acct):
125
+ """problemKey → {'total', 'shown'}. shown 은 bool 또는 'True'/'False' 문자열을 모두 받는다."""
126
+ stats = {}
127
+ p = ki.account_path(acct, RESOLUTIONS_FILE)
128
+ if not p:
129
+ return stats
130
+ for r in ki._read_jsonl(p):
131
+ pk = r.get('problemKey')
132
+ if not pk:
133
+ continue
134
+ s = stats.setdefault(str(pk), {'total': 0, 'shown': 0})
135
+ s['total'] += 1
136
+ sh = r.get('shown')
137
+ if sh is True or (isinstance(sh, str) and sh.strip().lower() == 'true'):
138
+ s['shown'] += 1
139
+ return stats
140
+
141
+
142
+ def classify(item, exp, res, now):
143
+ """반환 (class, reason|None). exp = 노출 통계 dict|None, res = 해결 통계 dict|None."""
144
+ st = _statement_flat(item)
145
+ low = st.lower()
146
+ kind = item.get('kind')
147
+ triggers = item.get('triggers') or []
148
+ types = set(t.get('type') for t in triggers if isinstance(t, dict))
149
+
150
+ # 1 codified: zsh nomatch 글롭 오류 — command_fix 가 명령을 고친다
151
+ if 'no matches found' in low and ('--include' in low or '-name' in low or 'glob' in low or '글롭' in st):
152
+ return 'codified', REASONS['codified']
153
+
154
+ # 2 mistriggered: 명령 함정인데 command 트리거 없이 touch 만 있다
155
+ has_touch = 'touch' in types or any(isinstance(a, str) and a.startswith('code:') for a in (item.get('anchors') or []))
156
+ if kind in ('pitfall', 'resolution') and _CMD_RE.search(st) and _FAIL_RE.search(low) and 'command' not in types and has_touch:
157
+ return 'mistriggered', REASONS['mistriggered']
158
+
159
+ sessions = len(exp['sessions']) if exp else 0
160
+ shown_res = res['shown'] if res else 0
161
+
162
+ # 3 noisy: 많이 노출됐는데 해결에 도움 된 적이 없다
163
+ if sessions >= NOISY_SESSIONS and shown_res == 0:
164
+ return 'noisy', REASONS['noisy'] % NOISY_SESSIONS
165
+
166
+ # 4 stale: 결정·사실인데 오래 노출되지 않았다(마지막 노출, 없으면 updatedAt)
167
+ if kind in ('decision', 'fact'):
168
+ last = exp['last'] if exp and exp.get('last') is not None else ki._parse_ts(item.get('updatedAt'))
169
+ if last is not None and now - last > STALE_DAYS * 86400:
170
+ return 'stale', REASONS['stale'] % STALE_DAYS
171
+
172
+ return 'keep', None
173
+
174
+
175
+ def build(acct, attr_dir=None, now=None):
176
+ """재고 분석. 반환 {'items': [row...], 'retired': set, 'account': dict}. row = 항목 + 분류 정보."""
177
+ now = time.time() if now is None else now
178
+ attr_dir = attr_dir or _attribution_dir()
179
+ exp_all = exposure_stats(attr_dir)
180
+ res_all = resolution_stats(acct)
181
+ retired = _retired_kids(acct)
182
+ rows = []
183
+ for it in all_items(acct):
184
+ kid = it.get('kid')
185
+ exp = exp_all.get(str(kid))
186
+ res = res_all.get(str(it.get('problemKey'))) if it.get('problemKey') else None
187
+ cls, reason = classify(it, exp, res, now)
188
+ rows.append({
189
+ 'kid': kid, 'kind': it.get('kind'), 'statement': _statement_flat(it),
190
+ 'sessions': len(exp['sessions']) if exp else 0, 'exposures': exp['count'] if exp else 0,
191
+ 'resolved': res['total'] if res else 0, 'resolvedShown': res['shown'] if res else 0,
192
+ 'class': cls, 'reason': reason, 'retired': kid in retired,
193
+ })
194
+ return {'items': rows, 'retired': retired, 'account': acct}
195
+
196
+
197
+ def _iso(ts):
198
+ return datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
199
+
200
+
201
+ def _cell(s):
202
+ return ' '.join(str(s if s is not None else '').split()).replace('|', '/')
203
+
204
+
205
+ def render_report(res, generated_at):
206
+ rows = res['items']
207
+ total = len(rows)
208
+ counts = {c: 0 for c in CLASSES}
209
+ for r in rows:
210
+ counts[r['class']] += 1
211
+ retire_n = sum(counts[c] for c in RETIRE_CLASSES)
212
+ already = sum(1 for r in rows if r['retired'])
213
+ lines = ['# 지식 재고 보고서', '', '- 생성: %s' % generated_at, '- 계정: %s' % (ki.account_dir_name(res['account']) or '없음'),
214
+ '- 전체 %d건 · 이미 재움 %d건 · 재우기 제안 %d건' % (total, already, retire_n), '',
215
+ '## 분류별 개수', '', '| 분류 | 개수 | 뜻 |', '|---|---|---|']
216
+ meaning = {'codified': '명령 교정이 코드로 막는 오류 → 재우기', 'mistriggered': '명령 함정이 파일 트리거로 잘못 주입 → 트리거 재작성 후보(재우지 않음)',
217
+ 'noisy': '노출 많고 해결 0 → 재우기', 'stale': '결정·사실이 오래 노출 없음 → 재우기', 'keep': '유지'}
218
+ for c in CLASSES:
219
+ lines.append('| %s | %d | %s |' % (c, counts[c], meaning[c]))
220
+ lines += ['', '## 분류별 상위 %d건' % TOP_N, '']
221
+ for c in CLASSES:
222
+ group = [r for r in rows if r['class'] == c]
223
+ group.sort(key=lambda r: (-r['sessions'], -r['resolved'], str(r['kid'])))
224
+ lines += ['### %s (%d건)' % (c, len(group)), '']
225
+ if not group:
226
+ lines += ['- 없음', '']
227
+ continue
228
+ lines += ['| kid | kind | 노출 세션 | 해결 | 상태 | statement |', '|---|---|---|---|---|---|']
229
+ for r in group[:TOP_N]:
230
+ lines.append('| %s | %s | %d | %d(보임 %d) | %s | %s |' % (
231
+ _cell(r['kid']), _cell(r['kind']), r['sessions'], r['resolved'], r['resolvedShown'],
232
+ '재움' if r['retired'] else '', _cell(r['statement'][:STATEMENT_PREVIEW])))
233
+ lines.append('')
234
+ lines += ['## 적용·되돌리기', '',
235
+ '- 적용: 이 보고서를 확인한 뒤 `python3 hooks/lib/knowledge_stock.py --apply <stock-proposal.json 경로>` 를 실행한다.'
236
+ ' 재우기 제안의 kid 만 계정 `items.retired.json` 에 합쳐진다. 원본 항목은 지우지 않는다.',
237
+ '- 되돌리기: 계정 폴더의 `items.retired.json` 을 삭제한다. 다음 주입부터 항목이 다시 보인다.', '']
238
+ return '\n'.join(lines)
239
+
240
+
241
+ def proposal(res, generated_at):
242
+ retire = []
243
+ for r in res['items']:
244
+ if r['class'] in RETIRE_CLASSES:
245
+ retire.append({'kid': r['kid'], 'class': r['class'], 'reason': r['reason']})
246
+ return {'generatedAt': generated_at, 'account': ki.account_dir_name(res['account']), 'retire': retire}
247
+
248
+
249
+ def write_report(acct, out_dir=None, now=None):
250
+ now = time.time() if now is None else now
251
+ generated = _iso(now)
252
+ res = build(acct, now=now)
253
+ d = out_dir
254
+ if not d:
255
+ base = ki.account_path(acct, REPORT_FILE)
256
+ d = os.path.dirname(base) if base else None
257
+ if not d:
258
+ raise RuntimeError('계정 디렉터리를 정할 수 없다(계정 설정 없음)')
259
+ os.makedirs(d, exist_ok=True)
260
+ with open(os.path.join(d, REPORT_FILE), 'w', encoding='utf-8') as f:
261
+ f.write(render_report(res, generated))
262
+ with open(os.path.join(d, PROPOSAL_FILE), 'w', encoding='utf-8') as f:
263
+ json.dump(proposal(res, generated), f, ensure_ascii=False, indent=2)
264
+ return d, res
265
+
266
+
267
+ def _kids_file(acct, name):
268
+ """계정 폴더 {"kids": [...]} 파일의 kid 집합. 없거나 깨졌으면 빈 집합."""
269
+ try:
270
+ with open(ki.account_path(acct, name), encoding='utf-8') as f:
271
+ d = json.load(f)
272
+ return set(str(k) for k in (d.get('kids') or [])) if isinstance(d, dict) else set()
273
+ except Exception:
274
+ return set()
275
+
276
+
277
+ def _merge_kids(acct, name, kids, source, now=None):
278
+ """계정 폴더 name 파일에 kids 를 합집합으로 쓴다. 반환 = 쓴 kid 수(합계)."""
279
+ rp = ki.account_path(acct, name)
280
+ if not rp:
281
+ raise RuntimeError('계정 디렉터리를 정할 수 없다(계정 설정 없음)')
282
+ merged = sorted(_kids_file(acct, name) | set(str(k) for k in kids))
283
+ now = time.time() if now is None else now
284
+ os.makedirs(os.path.dirname(rp), exist_ok=True)
285
+ tmp = rp + '.tmp'
286
+ with open(tmp, 'w', encoding='utf-8') as f:
287
+ json.dump({'kids': merged, 'updatedAt': _iso(now), 'source': source}, f, ensure_ascii=False, indent=2)
288
+ os.replace(tmp, rp)
289
+ return len(merged)
290
+
291
+
292
+ def apply_proposal(acct, proposal_path, now=None):
293
+ """제안의 retire[].kid 를 items.retired.json 에 합집합으로 쓴다. 반환 = 쓴 kid 수(합계)."""
294
+ with open(proposal_path, encoding='utf-8') as f:
295
+ prop = json.load(f)
296
+ kids = set(str(r['kid']) for r in (prop.get('retire') or []) if isinstance(r, dict) and r.get('kid'))
297
+ return _merge_kids(acct, RETIRED_FILE, kids, 'knowledge_stock', now)
298
+
299
+
300
+ # ── 자동 점검 (설계 36-2 C1~D4) ───────────────────────────────────────────────
301
+ # 노출 = 주입 줄이 든 transcript 파일 수. 반영 = 주입 뒤 assistant 8개의 새 낱말 중 진술 낱말 3개 이상 겹침.
302
+ AUTO_FILE = 'stock-auto.json'
303
+ AUTO_STAMP = 'stock-auto.stamp'
304
+ AUTO_INTERVAL_S = 7 * 86400
305
+ AUTO_WINDOW_S = 30 * 86400
306
+ AUTO_HISTORY_KEEP = 12
307
+ AUTO_RETIRE_SESSIONS = 5
308
+ AUTO_WINDOW_MSGS = 8
309
+ AUTO_MIN_OVERLAP = 3
310
+ AUTO_KEY_CHARS = 40
311
+ PROMOTE_SESSIONS = 2
312
+ PROMOTED_FILE = 'items.promoted.json'
313
+ ENCOUNTERS_FILE = 'recent-encounters.jsonl'
314
+ _WORD_RE = re.compile(r'[A-Za-z][A-Za-z0-9_\-./]{4,}|[가-힣]{3,}')
315
+ _KLINE_RE = re.compile(r'^\[KNOWLEDGE:[^\]]*\]\s*(?:\([^)]*\)\s*)?(.*)$')
316
+ _STOP = frozenset([
317
+ 'about', 'after', 'again', 'against', 'these', 'those', 'there', 'their', 'which', 'while', 'where',
318
+ 'would', 'should', 'could', 'being', 'before', 'other', 'still', 'every', 'using', 'first', 'never',
319
+ 'always', 'check', 'files', 'with', 'from', 'into', 'that', 'this', 'have', 'will', 'does', 'when',
320
+ 'then', 'than', 'them', 'they', 'your', 'just', 'only', 'also', 'make', 'need', 'code', 'file',
321
+ '이것', '그것', '저것', '있다', '없다', '한다', '하는', '하고', '합니다', '있는', '없는', '대한',
322
+ '경우', '때문', '에서', '으로', '해서', '하면', '되는', '된다', '않는다', '안된다',
323
+ ])
324
+
325
+
326
+ def _flat(s):
327
+ return ' '.join(str(s or '').split())
328
+
329
+
330
+ def _words(text):
331
+ return set(w.lower() for w in _WORD_RE.findall(text or '')) - _STOP
332
+
333
+
334
+ def _transcripts_root(arg=None):
335
+ return arg or os.environ.get('ROUTINECODE_TRANSCRIPTS_DIR') or os.path.join(os.path.expanduser('~'), '.claude', 'projects')
336
+
337
+
338
+ def _transcript_files(root, now):
339
+ out = []
340
+ for dp, _dn, fn in os.walk(root):
341
+ for f in fn:
342
+ if not f.endswith('.jsonl'):
343
+ continue
344
+ p = os.path.join(dp, f)
345
+ try:
346
+ if now - os.path.getmtime(p) <= AUTO_WINDOW_S:
347
+ out.append(p)
348
+ except OSError:
349
+ pass
350
+ return sorted(out)
351
+
352
+
353
+ def _record_text(r):
354
+ msg = r.get('message') if isinstance(r.get('message'), dict) else {}
355
+ c = msg.get('content')
356
+ if isinstance(c, str):
357
+ return c
358
+ parts = []
359
+ if isinstance(c, list):
360
+ for b in c:
361
+ if not isinstance(b, dict):
362
+ continue
363
+ if b.get('type') == 'text':
364
+ parts.append(str(b.get('text') or ''))
365
+ elif b.get('type') == 'tool_use':
366
+ parts.append(json.dumps(b.get('input'), ensure_ascii=False))
367
+ return '\n'.join(parts)
368
+
369
+
370
+ def _injected_lines(r):
371
+ """hook_additional_context 첨부 중 '[KNOWLEDGE:' 로 시작하는 줄."""
372
+ if r.get('type') != 'attachment':
373
+ return []
374
+ a = r.get('attachment')
375
+ if not isinstance(a, dict) or a.get('type') != 'hook_additional_context':
376
+ return []
377
+ c = a.get('content')
378
+ if isinstance(c, str):
379
+ texts = [c]
380
+ elif isinstance(c, list):
381
+ texts = [x if isinstance(x, str) else (x.get('text') if isinstance(x, dict) else '') for x in c]
382
+ else:
383
+ texts = []
384
+ out = []
385
+ for t in texts:
386
+ for ln in str(t or '').split('\n'):
387
+ if ln.startswith('[KNOWLEDGE:'):
388
+ out.append(ln)
389
+ return out
390
+
391
+
392
+ def _line_key(ln):
393
+ """주입 줄 → 진술 공백 압축 앞 40자 (load() 항목 매칭 키). 결정 전제 줄(뒤 줄)은 버린다."""
394
+ first = ln.split('\n', 1)[0]
395
+ m = _KLINE_RE.match(first)
396
+ return _flat(m.group(1) if m else first)[:AUTO_KEY_CHARS]
397
+
398
+
399
+ def _scan_file(path, keymap, stmt_words):
400
+ """한 transcript 의 노출 목록 [(kid, ts, reflected)] (주입 줄×kid 마다 한 건)."""
401
+ recs = ki._read_jsonl(path)
402
+ asst_idx = []
403
+ words = {}
404
+ for i, r in enumerate(recs):
405
+ if r.get('type') == 'assistant':
406
+ asst_idx.append(i)
407
+ words[i] = _words(_record_text(r))
408
+ out = []
409
+ for i, r in enumerate(recs):
410
+ lines = _injected_lines(r)
411
+ if not lines:
412
+ continue
413
+ kids = []
414
+ for ln in lines:
415
+ kids += keymap.get(_line_key(ln), [])
416
+ if not kids:
417
+ continue
418
+ ts = ki._parse_ts(r.get('timestamp'))
419
+ p = bisect.bisect_left(asst_idx, i)
420
+ before = set()
421
+ for j in asst_idx[max(0, p - AUTO_WINDOW_MSGS):p]:
422
+ before |= words[j]
423
+ after = set()
424
+ for j in asst_idx[p:p + AUTO_WINDOW_MSGS]:
425
+ after |= words[j]
426
+ new = after - before
427
+ for kid in set(kids):
428
+ hit = len(stmt_words.get(kid, set()) & new) >= AUTO_MIN_OVERLAP
429
+ out.append((kid, ts, hit))
430
+ return out
431
+
432
+
433
+ def measure(acct, root=None, now=None):
434
+ """transcript 를 읽어 항목별 노출·반영을 센다. 반환 {'files': n, 'items': [...], 'agg': {kid: {...}}}."""
435
+ now = time.time() if now is None else now
436
+ items = all_items(acct)
437
+ keymap, stmt_words = {}, {}
438
+ for it in items:
439
+ kid = str(it.get('kid'))
440
+ stmt_words[kid] = _words(it.get('statement'))
441
+ keymap.setdefault(_flat(it.get('statement'))[:AUTO_KEY_CHARS], []).append(kid)
442
+ files = _transcript_files(_transcripts_root(root), now)
443
+ agg = {}
444
+ for p in files:
445
+ try:
446
+ rows = _scan_file(p, keymap, stmt_words)
447
+ except Exception: # noqa: BLE001 — 파일 하나가 깨져도 나머지는 센다
448
+ continue
449
+ for kid, ts, hit in rows:
450
+ a = agg.setdefault(kid, {'files': set(), 'reflected': set(), 'first': None, 'events': []})
451
+ a['events'].append((p, ts, hit))
452
+ a['files'].add(p)
453
+ if hit:
454
+ a['reflected'].add(p)
455
+ if ts is not None and (a['first'] is None or ts < a['first']):
456
+ a['first'] = ts
457
+ return {'files': len(files), 'items': items, 'agg': agg}
458
+
459
+
460
+ RETRIGGER_MAX_ROUNDS = 2
461
+
462
+
463
+ def _parse_iso(s):
464
+ try:
465
+ return datetime.strptime(str(s), '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=timezone.utc).timestamp()
466
+ except Exception:
467
+ return None
468
+
469
+
470
+ def _write_kids(acct, name, kids, source, now):
471
+ rp = ki.account_path(acct, name)
472
+ tmp = rp + '.tmp'
473
+ with open(tmp, 'w', encoding='utf-8') as f:
474
+ json.dump({'kids': sorted(kids), 'updatedAt': _iso(now), 'source': source}, f, ensure_ascii=False, indent=2)
475
+ os.replace(tmp, rp)
476
+
477
+
478
+ def _retrigger_round(acct, items, agg, quiet, retired, now):
479
+ """quiet 지식의 트리거 재작성 회차. items.retrigger.json 만 쓰고(원본 불변) quiet·retired 목록을 갱신한다."""
480
+ res = {'retriggered': 0, 'noTrigger': 0, 'graduated': [], 'retired': []}
481
+ by_kid = {str(it.get('kid')): it for it in items}
482
+ ov = dict(ki.retrigger_overlay(acct))
483
+ changed = False
484
+ for kid in sorted(quiet):
485
+ it = by_kid.get(kid)
486
+ if it is None or kid in retired:
487
+ continue
488
+ e = ov.get(kid)
489
+ if not e:
490
+ have = [json.dumps(x, sort_keys=True) for x in (it.get('triggers') or [])]
491
+ trig = [x for x in ki.derive_triggers(it.get('statement')) if json.dumps(x, sort_keys=True) not in have]
492
+ if trig:
493
+ ov[kid] = {'triggers': trig, 'round': 1, 'at': _iso(now)}
494
+ res['retriggered'] += 1
495
+ changed = True
496
+ else:
497
+ res['noTrigger'] += 1
498
+ continue
499
+ if e.get('ok'):
500
+ continue
501
+ since = _parse_iso(e.get('at'))
502
+ evs = [ev for ev in (agg.get(kid) or {}).get('events', []) if since is None or (ev[1] is not None and ev[1] > since)]
503
+ if any(ev[2] for ev in evs):
504
+ e = dict(e, ok=True)
505
+ res['graduated'].append(kid)
506
+ elif len(set(ev[0] for ev in evs)) >= AUTO_RETIRE_SESSIONS:
507
+ if int(e.get('round') or 1) >= RETRIGGER_MAX_ROUNDS:
508
+ res['retired'].append(kid)
509
+ else:
510
+ e = dict(e, round=int(e.get('round') or 1) + 1, at=_iso(now))
511
+ else:
512
+ continue
513
+ ov[kid] = e
514
+ changed = True
515
+ if changed:
516
+ rp = ki.account_path(acct, ki.RETRIGGER_FILE)
517
+ tmp = rp + '.tmp'
518
+ with open(tmp, 'w', encoding='utf-8') as f:
519
+ json.dump({'items': ov, 'updatedAt': _iso(now)}, f, ensure_ascii=False, indent=2)
520
+ os.replace(tmp, rp)
521
+ if res['graduated']:
522
+ _write_kids(acct, QUIET_FILE, _kids_of(acct, QUIET_FILE) - set(res['graduated']), 'auto-quiet', now)
523
+ if res['retired']:
524
+ _merge_kids(acct, RETIRED_FILE, res['retired'], 'auto-retired-after-retrigger', now)
525
+ return res
526
+
527
+
528
+ def _form_of(it, extra=None):
529
+ trs = list(it.get('triggers') or []) + list(extra or [])
530
+ if any(isinstance(x, dict) and x.get('type') == 'command' for x in trs):
531
+ return 'command'
532
+ if any(isinstance(x, dict) and x.get('type') == 'problem' and isinstance(x.get('match'), dict)
533
+ and x['match'].get('text') for x in trs):
534
+ return 'error'
535
+ if it.get('problemKey'):
536
+ return 'problemKey'
537
+ return 'touch'
538
+
539
+
540
+ def _by_form(items, agg, overlay):
541
+ """F1: 트리거 형태별 [노출 항목 수, 반영 항목 수]."""
542
+ out = {}
543
+ for it in items:
544
+ kid = str(it.get('kid'))
545
+ a = agg.get(kid)
546
+ if not a or not a['files']:
547
+ continue
548
+ f = _form_of(it, (overlay.get(kid) or {}).get('triggers'))
549
+ c = out.setdefault(f, [0, 0])
550
+ c[0] += 1
551
+ if a['reflected']:
552
+ c[1] += 1
553
+ return out
554
+
555
+
556
+ def _command_eligible(it):
557
+ if any(isinstance(t, dict) and t.get('type') == 'command' for t in (it.get('triggers') or [])):
558
+ return True
559
+ fn = getattr(ki, 'command_heads', None)
560
+ if callable(fn):
561
+ try:
562
+ return bool(fn(it.get('statement') or ''))
563
+ except Exception: # noqa: BLE001
564
+ return False
565
+ return False
566
+
567
+
568
+ def _encounters(acct):
569
+ p = ki.account_path(acct, ENCOUNTERS_FILE)
570
+ out = []
571
+ if not p:
572
+ return out
573
+ for r in ki._read_jsonl(p):
574
+ t = ki._parse_ts(r.get('ts'))
575
+ pk, sid = r.get('problemKey'), r.get('sessionId')
576
+ if t is None or not pk or not sid:
577
+ continue
578
+ out.append((t, str(pk), str(sid)))
579
+ return out
580
+
581
+
582
+ def _read_history(p):
583
+ try:
584
+ with open(p, encoding='utf-8') as f:
585
+ d = json.load(f)
586
+ h = d.get('history') if isinstance(d, dict) else None
587
+ return h if isinstance(h, list) else []
588
+ except Exception:
589
+ return []
590
+
591
+
592
+ def run_auto(acct, root=None, force=False, now=None):
593
+ """주 1회 자동 점검. 반환 = 이력 한 줄 dict, 건너뛰면 {'skipped': reason}."""
594
+ now = time.time() if now is None else now
595
+ stamp = ki.account_path(acct, AUTO_STAMP)
596
+ if not stamp:
597
+ return {'skipped': 'no-account'}
598
+ if not force and os.path.exists(stamp) and now - os.path.getmtime(stamp) < AUTO_INTERVAL_S:
599
+ return {'skipped': 'stamp'}
600
+ os.makedirs(os.path.dirname(stamp), exist_ok=True)
601
+ with open(stamp, 'w', encoding='utf-8') as f:
602
+ f.write(_iso(now))
603
+
604
+ m = measure(acct, root=root, now=now)
605
+ agg, items = m['agg'], m['items']
606
+ exposed = [k for k in agg if agg[k]['files']]
607
+ reflected = [k for k in agg if agg[k]['reflected']]
608
+ retired_prior = _retired_kids(acct)
609
+
610
+ # C2(v1.1): 노출 세션 >= 5 이고 반영 0 → 읽기·편집 주입만 끈다(items.quiet.json, source 'auto-quiet').
611
+ # 재우면 맞는 때(명령 직전·같은 오류)에 보일 기회까지 사라진다 — 실데이터 첫 실행에서 유용한 3건이 걸렸다.
612
+ quiet_prior = _kids_of(acct, QUIET_FILE)
613
+ cands = []
614
+ for it in items:
615
+ kid = str(it.get('kid'))
616
+ a = agg.get(kid)
617
+ if a and len(a['files']) >= AUTO_RETIRE_SESSIONS and not a['reflected'] and kid not in retired_prior and kid not in quiet_prior:
618
+ cands.append(kid)
619
+ if cands:
620
+ _merge_kids(acct, QUIET_FILE, cands, 'auto-quiet', now)
621
+ retired_after = retired_prior
622
+
623
+ # R1·R2(설계 36-3): quiet 지식은 트리거를 다시 쓴다 → 재작성 뒤 반영되면 quiet 해제, 5세션 반영 0 이 2회차면 재움
624
+ rt = _retrigger_round(acct, items, agg, quiet_prior | set(cands), retired_prior, now)
625
+ retired_after = retired_prior | set(rt['retired'])
626
+
627
+ # D1: 명령 지식이 주입 뒤 같은 문제로 2개 이상 세션에서 다시 마주쳤으면 승격
628
+ enc = _encounters(acct)
629
+ promo = []
630
+ for it in items:
631
+ kid = str(it.get('kid'))
632
+ pk = it.get('problemKey')
633
+ a = agg.get(kid)
634
+ if kid in retired_after or not pk or not a or a['first'] is None:
635
+ continue
636
+ if not _command_eligible(it):
637
+ continue
638
+ sids = set(sid for (t, p, sid) in enc if p == str(pk) and t > a['first'])
639
+ if len(sids) >= PROMOTE_SESSIONS:
640
+ promo.append(kid)
641
+ if promo:
642
+ _merge_kids(acct, PROMOTED_FILE, promo, 'auto-promote', now)
643
+ promoted_total = len(_kids_file(acct, PROMOTED_FILE))
644
+
645
+ # D4: 이력 최근 12개
646
+ entry = {
647
+ 'ranAt': _iso(now), 'scannedFiles': m['files'], 'exposedItems': len(exposed),
648
+ 'reflectedItems': len(reflected),
649
+ 'reflectRate': round(len(reflected) / float(len(exposed)), 3) if exposed else 0.0,
650
+ 'quietAuto': len(cands), 'promoted': promoted_total,
651
+ 'retriggered': rt['retriggered'], 'noTrigger': rt['noTrigger'], 'graduated': len(rt['graduated']),
652
+ 'retiredAfterRetrigger': len(rt['retired']), 'byForm': _by_form(items, agg, ki.retrigger_overlay(acct)),
653
+ }
654
+ hp = ki.account_path(acct, AUTO_FILE)
655
+ hist = (_read_history(hp) + [entry])[-AUTO_HISTORY_KEEP:]
656
+ tmp = hp + '.tmp'
657
+ with open(tmp, 'w', encoding='utf-8') as f:
658
+ json.dump({'history': hist}, f, ensure_ascii=False, indent=2)
659
+ os.replace(tmp, hp)
660
+ return entry
661
+
662
+
663
+ def _main(argv):
664
+ if '--auto' in argv:
665
+ tr = None
666
+ if '--transcripts' in argv:
667
+ i = argv.index('--transcripts')
668
+ if i + 1 >= len(argv):
669
+ raise ValueError('--transcripts 뒤에 DIR 이 필요하다')
670
+ tr = argv[i + 1]
671
+ r = run_auto(ks.account(), root=tr, force='--force' in argv)
672
+ if 'skipped' in r:
673
+ print('자동 점검 건너뜀(%s).' % r['skipped'])
674
+ else:
675
+ print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 트리거 재작성 %d · 재작성 후 반영 %d · 재작성 후 재움 %d · 승격 누계 %d' % (
676
+ r['exposedItems'], r['reflectedItems'], r['quietAuto'], r.get('retriggered', 0), r.get('graduated', 0),
677
+ r.get('retiredAfterRetrigger', 0), r['promoted']))
678
+ return 0
679
+ if '--report' in argv:
680
+ out = None
681
+ if '--out' in argv:
682
+ i = argv.index('--out')
683
+ if i + 1 >= len(argv):
684
+ raise ValueError('--out 뒤에 DIR 이 필요하다')
685
+ out = argv[i + 1]
686
+ acct = ks.account()
687
+ d, res = write_report(acct, out_dir=out)
688
+ n = sum(1 for r in res['items'] if r['class'] in RETIRE_CLASSES)
689
+ print('보고서 %s 와 제안 %s 를 썼다(재우기 제안 %d건). 적용 전에 보고서를 확인한다.' % (
690
+ os.path.join(d, REPORT_FILE), os.path.join(d, PROPOSAL_FILE), n))
691
+ return 0
692
+ if '--apply' in argv:
693
+ i = argv.index('--apply')
694
+ if i + 1 >= len(argv):
695
+ raise ValueError('--apply 뒤에 FILE 이 필요하다')
696
+ total = apply_proposal(ks.account(), argv[i + 1])
697
+ print('items.retired.json 에 재움 목록 %d건을 썼다. 되돌리기는 이 파일 삭제.' % total)
698
+ return 0
699
+ print('사용법: knowledge_stock.py --report [--out DIR] | --apply FILE', file=sys.stderr)
700
+ return 1
701
+
702
+
703
+ if __name__ == '__main__':
704
+ try:
705
+ sys.exit(_main(sys.argv[1:]))
706
+ except Exception as e: # noqa: BLE001
707
+ print('knowledge_stock 오류: %s' % e, file=sys.stderr)
708
+ sys.exit(1)