@routinecrew/routinecode 2.31.86 → 2.31.88
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.
- package/bin/cli.sh +10 -0
- package/bin/prompt-vault.dat +1 -1
- package/bin/rc-login.js +5 -4
- package/bin/rc-savings.js +808 -0
- package/bin/rc-skills.js +1 -1
- package/bin/rc-suggestions.js +100 -0
- package/bin/rc-team.js +1 -1
- package/hooks/hooks-config.json +9 -0
- package/hooks/lib/attest_reader.py +16 -1
- package/hooks/lib/calibration.json +89 -0
- package/hooks/lib/card_gate.py +735 -0
- package/hooks/lib/cc-surface.json +1 -1
- package/hooks/lib/command_fix.py +209 -0
- package/hooks/lib/delegate_nudge.py +179 -0
- package/hooks/lib/deploy_suggest.py +312 -0
- package/hooks/lib/design_pick_nudge.py +86 -0
- package/hooks/lib/emit_raw.py +4 -0
- package/hooks/lib/i18n.py +48 -20
- package/hooks/lib/knowledge_items.py +189 -19
- package/hooks/lib/knowledge_stock.py +604 -0
- package/hooks/lib/ops_guard.py +549 -0
- package/hooks/lib/prices.json +8 -0
- package/hooks/lib/route_ledger.py +622 -0
- package/hooks/lib/route_rules.json +88 -0
- package/hooks/lib/savings_emit.py +93 -0
- package/hooks/lib/secret_filter.py +11 -0
- package/hooks/lib/sync_manager.py +4 -1
- package/hooks/post-bash-verify.sh +14 -0
- package/hooks/post-edit-track.sh +9 -0
- package/hooks/pre-agent-spawn.mjs +1 -1
- package/hooks/pre-agent-spawn.sh +34 -2
- package/hooks/pre-bash-guard.sh +22 -0
- package/hooks/pre-bash-knowledge.sh +12 -2
- package/hooks/pre-credit-guard.sh +1 -1
- package/hooks/pre-edit-delegate.sh +15 -0
- package/hooks/pre-edit-guard.sh +10 -0
- package/hooks/pre-mark-complete.sh +54 -12
- package/hooks/pre-read-guard.sh +10 -0
- package/hooks/session-start.sh +15 -10
- package/hooks/stop-usage-metrics.sh +6 -0
- package/hooks/subagent-stop-usage.sh +36 -4
- package/hooks/user-prompt-submit.sh +9 -0
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-routinecode/dist/criteria-card.js +1 -0
- package/mcp-routinecode/dist/design-judge.js +1 -0
- package/mcp-routinecode/dist/edit-tracker.js +1 -1
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
- package/mcp-routinecode/dist/index.js +1 -1
- package/mcp-routinecode/dist/known-solutions.js +1 -1
- package/mcp-routinecode/dist/ledger-miner.js +1 -1
- package/mcp-routinecode/dist/normalize-sig.js +1 -1
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -1
- package/mcp-routinecode/dist/pattern-matcher.js +1 -1
- package/mcp-routinecode/dist/route-match.js +1 -1
- package/mcp-routinecode/dist/routines.js +1 -1
- package/mcp-routinecode/dist/rule-engine.js +1 -1
- package/mcp-routinecode/dist/rule-promoter.js +1 -1
- package/mcp-routinecode/dist/session-registry.js +1 -1
- package/mcp-routinecode/dist/skill-pack/sync.js +40 -14
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/thinking-judge.js +1 -0
- package/mcp-routinecode/dist/verification.js +1 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/agents/analyzer.md.sealed +1 -1
- package/plugin/agents/architect.md.sealed +1 -1
- package/plugin/agents/crawler.md.sealed +1 -1
- package/plugin/agents/explorer.md.sealed +1 -1
- package/plugin/agents/implementor-lite.md.sealed +1 -0
- package/plugin/agents/implementor.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- package/plugin/agents/ops-lite.md.sealed +1 -0
- package/plugin/agents/planner.md.sealed +1 -1
- package/plugin/agents/recorder.md.sealed +1 -1
- package/plugin/agents/reviewer.md.sealed +1 -1
- package/plugin/agents/runner-lite.md.sealed +1 -0
- package/plugin/agents/verifier.md.sealed +1 -1
- package/plugin/commands/analyze.md.sealed +1 -1
- package/plugin/commands/plan.md.sealed +1 -1
- package/plugin/commands/rc.md.sealed +1 -1
- package/plugin/commands/receipt.md.sealed +1 -1
- package/plugin/commands/recharge.md.sealed +1 -1
- package/plugin/commands/routines.md.sealed +1 -1
- package/plugin/commands/share.md.sealed +1 -1
- package/plugin/routinecode-prompt.md.sealed +1 -1
|
@@ -0,0 +1,604 @@
|
|
|
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})
|
|
451
|
+
a['files'].add(p)
|
|
452
|
+
if hit:
|
|
453
|
+
a['reflected'].add(p)
|
|
454
|
+
if ts is not None and (a['first'] is None or ts < a['first']):
|
|
455
|
+
a['first'] = ts
|
|
456
|
+
return {'files': len(files), 'items': items, 'agg': agg}
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _command_eligible(it):
|
|
460
|
+
if any(isinstance(t, dict) and t.get('type') == 'command' for t in (it.get('triggers') or [])):
|
|
461
|
+
return True
|
|
462
|
+
fn = getattr(ki, 'command_heads', None)
|
|
463
|
+
if callable(fn):
|
|
464
|
+
try:
|
|
465
|
+
return bool(fn(it.get('statement') or ''))
|
|
466
|
+
except Exception: # noqa: BLE001
|
|
467
|
+
return False
|
|
468
|
+
return False
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _encounters(acct):
|
|
472
|
+
p = ki.account_path(acct, ENCOUNTERS_FILE)
|
|
473
|
+
out = []
|
|
474
|
+
if not p:
|
|
475
|
+
return out
|
|
476
|
+
for r in ki._read_jsonl(p):
|
|
477
|
+
t = ki._parse_ts(r.get('ts'))
|
|
478
|
+
pk, sid = r.get('problemKey'), r.get('sessionId')
|
|
479
|
+
if t is None or not pk or not sid:
|
|
480
|
+
continue
|
|
481
|
+
out.append((t, str(pk), str(sid)))
|
|
482
|
+
return out
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _read_history(p):
|
|
486
|
+
try:
|
|
487
|
+
with open(p, encoding='utf-8') as f:
|
|
488
|
+
d = json.load(f)
|
|
489
|
+
h = d.get('history') if isinstance(d, dict) else None
|
|
490
|
+
return h if isinstance(h, list) else []
|
|
491
|
+
except Exception:
|
|
492
|
+
return []
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def run_auto(acct, root=None, force=False, now=None):
|
|
496
|
+
"""주 1회 자동 점검. 반환 = 이력 한 줄 dict, 건너뛰면 {'skipped': reason}."""
|
|
497
|
+
now = time.time() if now is None else now
|
|
498
|
+
stamp = ki.account_path(acct, AUTO_STAMP)
|
|
499
|
+
if not stamp:
|
|
500
|
+
return {'skipped': 'no-account'}
|
|
501
|
+
if not force and os.path.exists(stamp) and now - os.path.getmtime(stamp) < AUTO_INTERVAL_S:
|
|
502
|
+
return {'skipped': 'stamp'}
|
|
503
|
+
os.makedirs(os.path.dirname(stamp), exist_ok=True)
|
|
504
|
+
with open(stamp, 'w', encoding='utf-8') as f:
|
|
505
|
+
f.write(_iso(now))
|
|
506
|
+
|
|
507
|
+
m = measure(acct, root=root, now=now)
|
|
508
|
+
agg, items = m['agg'], m['items']
|
|
509
|
+
exposed = [k for k in agg if agg[k]['files']]
|
|
510
|
+
reflected = [k for k in agg if agg[k]['reflected']]
|
|
511
|
+
retired_prior = _retired_kids(acct)
|
|
512
|
+
|
|
513
|
+
# C2(v1.1): 노출 세션 >= 5 이고 반영 0 → 읽기·편집 주입만 끈다(items.quiet.json, source 'auto-quiet').
|
|
514
|
+
# 재우면 맞는 때(명령 직전·같은 오류)에 보일 기회까지 사라진다 — 실데이터 첫 실행에서 유용한 3건이 걸렸다.
|
|
515
|
+
quiet_prior = _kids_of(acct, QUIET_FILE)
|
|
516
|
+
cands = []
|
|
517
|
+
for it in items:
|
|
518
|
+
kid = str(it.get('kid'))
|
|
519
|
+
a = agg.get(kid)
|
|
520
|
+
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:
|
|
521
|
+
cands.append(kid)
|
|
522
|
+
if cands:
|
|
523
|
+
_merge_kids(acct, QUIET_FILE, cands, 'auto-quiet', now)
|
|
524
|
+
retired_after = retired_prior
|
|
525
|
+
|
|
526
|
+
# D1: 명령 지식이 주입 뒤 같은 문제로 2개 이상 세션에서 다시 마주쳤으면 승격
|
|
527
|
+
enc = _encounters(acct)
|
|
528
|
+
promo = []
|
|
529
|
+
for it in items:
|
|
530
|
+
kid = str(it.get('kid'))
|
|
531
|
+
pk = it.get('problemKey')
|
|
532
|
+
a = agg.get(kid)
|
|
533
|
+
if kid in retired_after or not pk or not a or a['first'] is None:
|
|
534
|
+
continue
|
|
535
|
+
if not _command_eligible(it):
|
|
536
|
+
continue
|
|
537
|
+
sids = set(sid for (t, p, sid) in enc if p == str(pk) and t > a['first'])
|
|
538
|
+
if len(sids) >= PROMOTE_SESSIONS:
|
|
539
|
+
promo.append(kid)
|
|
540
|
+
if promo:
|
|
541
|
+
_merge_kids(acct, PROMOTED_FILE, promo, 'auto-promote', now)
|
|
542
|
+
promoted_total = len(_kids_file(acct, PROMOTED_FILE))
|
|
543
|
+
|
|
544
|
+
# D4: 이력 최근 12개
|
|
545
|
+
entry = {
|
|
546
|
+
'ranAt': _iso(now), 'scannedFiles': m['files'], 'exposedItems': len(exposed),
|
|
547
|
+
'reflectedItems': len(reflected),
|
|
548
|
+
'reflectRate': round(len(reflected) / float(len(exposed)), 3) if exposed else 0.0,
|
|
549
|
+
'quietAuto': len(cands), 'promoted': promoted_total,
|
|
550
|
+
}
|
|
551
|
+
hp = ki.account_path(acct, AUTO_FILE)
|
|
552
|
+
hist = (_read_history(hp) + [entry])[-AUTO_HISTORY_KEEP:]
|
|
553
|
+
tmp = hp + '.tmp'
|
|
554
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
555
|
+
json.dump({'history': hist}, f, ensure_ascii=False, indent=2)
|
|
556
|
+
os.replace(tmp, hp)
|
|
557
|
+
return entry
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
def _main(argv):
|
|
561
|
+
if '--auto' in argv:
|
|
562
|
+
tr = None
|
|
563
|
+
if '--transcripts' in argv:
|
|
564
|
+
i = argv.index('--transcripts')
|
|
565
|
+
if i + 1 >= len(argv):
|
|
566
|
+
raise ValueError('--transcripts 뒤에 DIR 이 필요하다')
|
|
567
|
+
tr = argv[i + 1]
|
|
568
|
+
r = run_auto(ks.account(), root=tr, force='--force' in argv)
|
|
569
|
+
if 'skipped' in r:
|
|
570
|
+
print('자동 점검 건너뜀(%s).' % r['skipped'])
|
|
571
|
+
else:
|
|
572
|
+
print('자동 점검: 노출 %d · 반영 %d · 읽기·편집 주입 끔 %d · 승격 누계 %d' % (
|
|
573
|
+
r['exposedItems'], r['reflectedItems'], r['quietAuto'], r['promoted']))
|
|
574
|
+
return 0
|
|
575
|
+
if '--report' in argv:
|
|
576
|
+
out = None
|
|
577
|
+
if '--out' in argv:
|
|
578
|
+
i = argv.index('--out')
|
|
579
|
+
if i + 1 >= len(argv):
|
|
580
|
+
raise ValueError('--out 뒤에 DIR 이 필요하다')
|
|
581
|
+
out = argv[i + 1]
|
|
582
|
+
acct = ks.account()
|
|
583
|
+
d, res = write_report(acct, out_dir=out)
|
|
584
|
+
n = sum(1 for r in res['items'] if r['class'] in RETIRE_CLASSES)
|
|
585
|
+
print('보고서 %s 와 제안 %s 를 썼다(재우기 제안 %d건). 적용 전에 보고서를 확인한다.' % (
|
|
586
|
+
os.path.join(d, REPORT_FILE), os.path.join(d, PROPOSAL_FILE), n))
|
|
587
|
+
return 0
|
|
588
|
+
if '--apply' in argv:
|
|
589
|
+
i = argv.index('--apply')
|
|
590
|
+
if i + 1 >= len(argv):
|
|
591
|
+
raise ValueError('--apply 뒤에 FILE 이 필요하다')
|
|
592
|
+
total = apply_proposal(ks.account(), argv[i + 1])
|
|
593
|
+
print('items.retired.json 에 재움 목록 %d건을 썼다. 되돌리기는 이 파일 삭제.' % total)
|
|
594
|
+
return 0
|
|
595
|
+
print('사용법: knowledge_stock.py --report [--out DIR] | --apply FILE', file=sys.stderr)
|
|
596
|
+
return 1
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
if __name__ == '__main__':
|
|
600
|
+
try:
|
|
601
|
+
sys.exit(_main(sys.argv[1:]))
|
|
602
|
+
except Exception as e: # noqa: BLE001
|
|
603
|
+
print('knowledge_stock 오류: %s' % e, file=sys.stderr)
|
|
604
|
+
sys.exit(1)
|