@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.
- package/README.md +2 -2
- package/bin/cli.sh +23 -0
- package/bin/prompt-vault.dat +1 -0
- package/bin/prompt-vault.js +51 -1
- package/bin/rc-board.js +58 -0
- package/bin/rc-config.js +756 -1
- package/bin/rc-credit-turn.js +2 -1
- package/bin/rc-grant.js +2 -1
- package/bin/rc-login.js +2 -0
- package/bin/rc-map.js +132 -0
- package/bin/rc-privacy.js +200 -0
- package/bin/rc-skills.js +31 -0
- package/bin/rc-team.js +2 -1
- package/bin/setup.js +4 -0
- package/hooks/cc-compat-watch.js +2 -1
- package/hooks/claim-questions.json +40 -0
- package/hooks/hooks-config.json +108 -1
- package/hooks/lib/agent_budget.py +122 -0
- package/hooks/lib/agent_telemetry.py +143 -0
- package/hooks/lib/attest_reader.py +15 -6
- package/hooks/lib/attribution_judge.py +109 -0
- package/hooks/lib/board-golden.json +268 -0
- package/hooks/lib/board.py +503 -0
- package/hooks/lib/board_sync.py +535 -0
- package/hooks/lib/cc-surface.json +1 -1
- package/hooks/lib/claim_structure.py +412 -0
- package/hooks/lib/completion_log.py +12 -5
- package/hooks/lib/config_bash_track.py +114 -28
- package/hooks/lib/config_guard.py +137 -5
- package/hooks/lib/edit_tracker.py +182 -0
- package/hooks/lib/error_line.py +94 -0
- package/hooks/lib/escalation_restore.py +66 -0
- package/hooks/lib/i18n.py +37 -15
- package/hooks/lib/knowledge_items.py +1407 -0
- package/hooks/lib/knowledge_scope.py +123 -0
- package/hooks/lib/known_solution.py +37 -9
- package/hooks/lib/log_compact.py +85 -0
- package/hooks/lib/metacog_signals.py +228 -0
- package/hooks/lib/orch_decision.py +690 -0
- package/hooks/lib/premise-golden.json +96 -0
- package/hooks/lib/presence.py +10 -3
- package/hooks/lib/privacy_log.py +35 -0
- package/hooks/lib/receipt.py +137 -14
- package/hooks/lib/review_gate.py +83 -0
- package/hooks/lib/routine_skill_eval.py +213 -0
- package/hooks/lib/secret_filter.py +2 -1
- package/hooks/lib/skill_drafts.py +188 -0
- package/hooks/lib/sync_manager.py +121 -26
- package/hooks/lib/usage_v2.py +680 -0
- package/hooks/lib/work_kind.py +198 -0
- package/hooks/lib/work_kind_events.py +361 -0
- package/hooks/pending-drainer.sh +28 -0
- package/hooks/post-agent-budget.sh +50 -0
- package/hooks/post-agent-return.sh +89 -3
- package/hooks/post-bash-failure.sh +39 -0
- package/hooks/post-bash-knowledge.sh +15 -34
- package/hooks/post-bash-verify.sh +33 -16
- package/hooks/post-build-check.sh +16 -18
- package/hooks/post-config-context.sh +13 -0
- package/hooks/post-delegation-nudge.sh +12 -1
- package/hooks/post-edit-track.sh +19 -28
- package/hooks/post-orch-decision.sh +35 -0
- package/hooks/post-read-config-context.sh +20 -0
- package/hooks/pre-account-guard.sh +1 -1
- package/hooks/pre-agent-spawn.mjs +2 -1
- package/hooks/pre-agent-spawn.sh +12 -1
- package/hooks/pre-bash-guard.sh +61 -3
- package/hooks/pre-bash-knowledge.sh +46 -0
- package/hooks/pre-credit-guard.sh +1 -1
- package/hooks/pre-edit-board.sh +44 -0
- package/hooks/pre-edit-check.sh +29 -5
- package/hooks/pre-edit-config-gate.sh +1 -1
- package/hooks/pre-edit-domain-gate.sh +23 -22
- package/hooks/pre-mark-complete.sh +32 -4
- package/hooks/pre-read-knowledge-inject.sh +34 -24
- package/hooks/pre-review-gate.sh +17 -0
- package/hooks/recorder-runner.sh +25 -2
- package/hooks/session-start-compact.sh +28 -0
- package/hooks/session-start.sh +167 -19
- package/hooks/skill-knowledge.sh +37 -0
- package/hooks/stop-claim-check.v3.sh +21 -3
- package/hooks/stop-usage-metrics.sh +138 -83
- package/hooks/subagent-stop-usage.sh +25 -0
- package/hooks/user-prompt-submit.sh +10 -4
- package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
- package/mcp-db-manager/dist/core/model-parser.js +1 -1
- package/mcp-db-manager/dist/core/schema-reader.js +1 -1
- package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
- package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
- package/mcp-db-manager/dist/index.js +1 -1
- package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
- package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
- package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
- package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
- package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
- package/mcp-dev-tester/dist/attestation.js +1 -1
- package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
- package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
- package/mcp-dev-tester/dist/config/project-config.js +1 -1
- package/mcp-dev-tester/dist/index.js +1 -1
- package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
- package/mcp-doc-fetcher/dist/index.js +1 -1
- package/mcp-html-renderer/dist/index.js +1 -1
- package/mcp-html-renderer/dist/preview.js +1 -1
- package/mcp-html-renderer/dist/template-engine.js +1 -1
- package/mcp-intelligence/dist/concept-catalog.js +1 -1
- package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
- package/mcp-intelligence/dist/config-auth.js +1 -1
- package/mcp-intelligence/dist/contracts.generated.js +1 -1
- package/mcp-intelligence/dist/domain-templates.js +1 -1
- package/mcp-intelligence/dist/grounding.js +1 -1
- package/mcp-intelligence/dist/handlers.js +1 -1
- package/mcp-intelligence/dist/index.js +1 -1
- package/mcp-intelligence/dist/intelligence-file.js +1 -1
- package/mcp-intelligence/dist/knowledge-critic.js +1 -1
- package/mcp-intelligence/dist/knowledge-guide.js +1 -0
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-migrate.js +1 -0
- package/mcp-intelligence/dist/knowledge-record.js +1 -0
- package/mcp-intelligence/dist/knowledge-scope.js +1 -0
- package/mcp-intelligence/dist/mention-extractor.js +1 -1
- package/mcp-intelligence/dist/provenance.js +1 -1
- package/mcp-intelligence/dist/sanitize.generated.js +242 -0
- package/mcp-intelligence/dist/semantic-embedder.js +1 -1
- package/mcp-log-watcher/dist/config-auth.js +1 -1
- package/mcp-log-watcher/dist/file-watcher.js +1 -1
- package/mcp-log-watcher/dist/index.js +1 -1
- package/mcp-log-watcher/dist/known-solutions.js +1 -1
- package/mcp-log-watcher/dist/log-store.js +1 -1
- package/mcp-log-watcher/dist/sanitize.generated.js +242 -0
- package/mcp-log-watcher/dist/websocket-server.js +1 -1
- package/mcp-log-watcher/package.json +1 -1
- package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
- package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
- package/mcp-plan-manager/dist/file-ops.js +1 -1
- package/mcp-plan-manager/dist/index.js +1 -1
- package/mcp-plan-manager/dist/plan-parser.js +1 -1
- package/mcp-project-context/dist/git-ops.js +1 -1
- package/mcp-project-context/dist/index.js +1 -1
- package/mcp-project-context/dist/project-analysis.js +1 -1
- package/mcp-routinecode/dist/agent-tracker.js +1 -1
- package/mcp-routinecode/dist/analysis-ledger.js +590 -0
- package/mcp-routinecode/dist/attestation.js +1 -1
- package/mcp-routinecode/dist/blast-radius.js +1 -1
- package/mcp-routinecode/dist/board.js +1 -0
- package/mcp-routinecode/dist/build-id.js +1 -0
- package/mcp-routinecode/dist/changeset.js +1 -1
- package/mcp-routinecode/dist/config-auth.js +1 -1
- package/mcp-routinecode/dist/config-map/applied.js +1 -0
- package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
- package/mcp-routinecode/dist/config-map/architect-store.js +1132 -1
- package/mcp-routinecode/dist/config-map/assign.js +1 -1
- package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/audit.js +1 -1
- package/mcp-routinecode/dist/config-map/blocks.js +1 -1
- package/mcp-routinecode/dist/config-map/briefing.js +541 -1
- package/mcp-routinecode/dist/config-map/certify.js +10 -5
- package/mcp-routinecode/dist/config-map/const-use.js +1 -1
- package/mcp-routinecode/dist/config-map/context.js +219 -0
- package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -0
- package/mcp-routinecode/dist/config-map/decisions.js +1 -1
- package/mcp-routinecode/dist/config-map/decls.js +1 -1
- package/mcp-routinecode/dist/config-map/drift.js +1 -1
- package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
- package/mcp-routinecode/dist/config-map/extract.js +1 -1
- package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
- package/mcp-routinecode/dist/config-map/gate.js +796 -1
- package/mcp-routinecode/dist/config-map/hash.js +1 -1
- package/mcp-routinecode/dist/config-map/ident-norm.js +1 -1
- package/mcp-routinecode/dist/config-map/index-store.js +1051 -1
- package/mcp-routinecode/dist/config-map/light-eval.js +253 -1
- package/mcp-routinecode/dist/config-map/link.js +1 -1
- package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
- package/mcp-routinecode/dist/config-map/lookup.js +1 -1
- package/mcp-routinecode/dist/config-map/louvain.js +1 -1
- package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
- package/mcp-routinecode/dist/config-map/names.js +1 -1
- package/mcp-routinecode/dist/config-map/post-bash-eval.js +105 -0
- package/mcp-routinecode/dist/config-map/proposals.js +1 -1
- package/mcp-routinecode/dist/config-map/ratchet.js +148 -0
- package/mcp-routinecode/dist/config-map/recheck.js +148 -1
- package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
- package/mcp-routinecode/dist/config-map/route-security.js +1 -1
- package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
- package/mcp-routinecode/dist/config-map/scc.js +1 -1
- package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
- package/mcp-routinecode/dist/config-map/shape.js +1 -1
- package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
- package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
- package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
- package/mcp-routinecode/dist/config-map/store.js +1 -1
- package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
- package/mcp-routinecode/dist/config-map/task-eval.js +369 -1
- package/mcp-routinecode/dist/config-map/templates.js +1 -1
- package/mcp-routinecode/dist/contracts.generated.js +1 -1
- package/mcp-routinecode/dist/coverage.js +1 -1
- package/mcp-routinecode/dist/edit-tracker.js +1 -0
- package/mcp-routinecode/dist/explorer-advisor.js +1 -1
- package/mcp-routinecode/dist/failure-tracker.js +1 -1
- package/mcp-routinecode/dist/file-lock-registry.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 -0
- package/mcp-routinecode/dist/observed-draft.js +1 -1
- package/mcp-routinecode/dist/observed-escalation.js +1 -0
- 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/sanitize.generated.js +242 -0
- package/mcp-routinecode/dist/session-registry.js +1 -0
- package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
- package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
- package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
- package/mcp-routinecode/dist/test-runner.js +1 -1
- package/mcp-routinecode/dist/verification.js +1 -1
- package/mcp-routinecode/dist/viral-loop.js +1 -1
- package/mcp-routinecode/package.json +1 -1
- package/package.json +3 -3
- 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.md.sealed +1 -1
- package/plugin/agents/looker.md.sealed +1 -1
- 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/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,198 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""work_kind — Bash 명령 한 줄을 '일의 종류' (도구군, 대상, 동작) 라벨로 바꾼다 (docs/지식체계/40 §3.1).
|
|
3
|
+
|
|
4
|
+
- 결정적 규칙 사전. LLM 없음. 명령 원문은 돌려주지 않는다(라벨만) — RDPE A10 원칙.
|
|
5
|
+
- 대상: 원격이면 호스트 별칭(user@ 제거, 변수는 '$var'), 로컬이면 맨 앞 `cd <경로>` 의 마지막 디렉터리.
|
|
6
|
+
- 동작 사전은 원격 안쪽 명령과 로컬 명령에 같은 것을 쓴다.
|
|
7
|
+
|
|
8
|
+
classify(command) -> {"group": str, "target": str, "action": str}
|
|
9
|
+
"""
|
|
10
|
+
import re
|
|
11
|
+
import shlex
|
|
12
|
+
|
|
13
|
+
# 동작 사전 — 위에서부터 먼저 맞는 것. 쓰기·배포를 읽기보다 앞에 둔다(섞이면 위험한 쪽으로 분류).
|
|
14
|
+
ACTIONS = [
|
|
15
|
+
("deploy", r"docker(-compose| compose)?\s+(up|build|pull|restart|stop|rm)\b|docker\s+run\s+(?!--rm\b)(-d|--detach|--name|--restart)|compose\s+up|systemctl\s+(restart|start|stop|reload)|"
|
|
16
|
+
r"\bpm2\s+(restart|reload|start|stop|delete)|\bnginx\s+-s\s+reload|\bkubectl\s+(apply|rollout|delete|scale)"),
|
|
17
|
+
("copy", r"\brclone\s+(copy|sync|move)\b|\bdocker\s+cp\b"),
|
|
18
|
+
("db", r"\b(psql|pg_dump|pg_restore|mysql|redis-cli|mongosh?)\b|require\(\\?[\"']pg\\?[\"']\)|node_modules/pg\b"),
|
|
19
|
+
("logs", r"docker(-compose| compose)?\s+logs|\bkubectl\s+logs|\bjournalctl\b|\bpm2\s+logs|/var/log/|"
|
|
20
|
+
r"\b(cat|tail|less|grep|head)\b[^;|&\n]*\.(log|out)\b"),
|
|
21
|
+
("status", r"docker(-compose| compose)?\s+(ps|inspect|stats|top)|\bcurl\b|\bwget\b|health|systemctl\s+status|\bpm2\s+(ls|list|status)|"
|
|
22
|
+
r"\bnvidia-smi\b|\bfree\b|\bdf\b|\buptime\b|\bps\s+(aux|-ef)|\bpgrep\b|\bss\s+-|\bnetstat\b|\blsof\b|\bkubectl\s+(get|describe)"),
|
|
23
|
+
("test", r"\b(jest|vitest|pytest|mocha)\b|\bnode\s+--test\b|\bnpm\s+(run\s+)?test\b|\bpnpm\s+(run\s+)?test\b|\bgo\s+test\b|\bcargo\s+test\b|unittest"),
|
|
24
|
+
("build", r"\btsc\b|\bnpm\s+run\s+(build|typecheck|lint)|\bpnpm\s+(run\s+)?(build|typecheck|lint)|\bnext\s+build\b|\beslint\b|\bcargo\s+build\b|\bgo\s+build\b"),
|
|
25
|
+
("install", r"\b(npm|pnpm|yarn)\s+(install|i|add|ci|link)\b|\bpip3?\s+install\b|\bbrew\s+install\b|\bapt(-get)?\s+install\b"),
|
|
26
|
+
("git", r"\bgit\s+\w+"),
|
|
27
|
+
("cron", r"\bcrontab\b"),
|
|
28
|
+
("script", r"\bpython3?\b|\bnode\b|\bbash\s+\S+\.sh|\bsh\s+\S+\.sh|(^|\s)\./\S+"),
|
|
29
|
+
# 리다이렉트는 파일로 쓸 때만 쓰기 — 2>&1 · >/dev/null 은 출력 정리일 뿐이다
|
|
30
|
+
("write", r"(?<![-\w])rm\s|(?<![-\w])mv\s|(?<![-\w])cp\s|\bmkdir\b|\bchmod\b|\bchown\b|\btee\b|\bsed\s+-i|(?<![0-9&>])>>?\s*(?!&|/dev/null)[^\s&|;]"),
|
|
31
|
+
("view", r"\b(cat|ls|grep|rg|find|head|tail|sed|wc|du|stat|tree|awk|diff|jq)\b"),
|
|
32
|
+
]
|
|
33
|
+
_ACTIONS = [(name, re.compile(rx)) for name, rx in ACTIONS]
|
|
34
|
+
|
|
35
|
+
_SSH_OPTS_WITH_ARG = set("bcDEeFIiJLlmOopQRSWw")
|
|
36
|
+
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
|
|
37
|
+
_HEREDOC = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?[^\n]*\n(.*?)\n\s*\1\b", re.S)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def action_of(text):
|
|
41
|
+
for name, rx in _ACTIONS:
|
|
42
|
+
if rx.search(text or ""):
|
|
43
|
+
return name
|
|
44
|
+
return "other"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_OPS = {";", "&&", "||", "|", "&", ";;", "|&"}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _unquoted_newlines_to_semicolons(s):
|
|
51
|
+
out, q = [], None
|
|
52
|
+
for ch in s:
|
|
53
|
+
if q:
|
|
54
|
+
if ch == q:
|
|
55
|
+
q = None
|
|
56
|
+
elif ch in ("'", '"'):
|
|
57
|
+
q = ch
|
|
58
|
+
elif ch == "\n":
|
|
59
|
+
ch = ";"
|
|
60
|
+
out.append(ch)
|
|
61
|
+
return "".join(out)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _segment_tokens(command):
|
|
65
|
+
"""따옴표를 지키며 연산자(; && || | &)·줄바꿈으로 자른 토큰 목록들. heredoc 본문은 빼고 읽는다."""
|
|
66
|
+
text = _unquoted_newlines_to_semicolons(_HEREDOC.sub(lambda m: "<<" + m.group(1), command))
|
|
67
|
+
try:
|
|
68
|
+
lex = shlex.shlex(text, posix=True, punctuation_chars=";&|")
|
|
69
|
+
lex.whitespace_split = True
|
|
70
|
+
toks = list(lex)
|
|
71
|
+
except ValueError:
|
|
72
|
+
toks = text.replace(";", " ; ").split()
|
|
73
|
+
segs, cur = [], []
|
|
74
|
+
for t in toks:
|
|
75
|
+
if t in _OPS:
|
|
76
|
+
if cur:
|
|
77
|
+
segs.append(cur)
|
|
78
|
+
cur = []
|
|
79
|
+
else:
|
|
80
|
+
cur.append(t)
|
|
81
|
+
if cur:
|
|
82
|
+
segs.append(cur)
|
|
83
|
+
return segs
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _host_label(tok, env=None):
|
|
87
|
+
tok = tok.strip("'\"")
|
|
88
|
+
if tok.startswith("$"):
|
|
89
|
+
name = tok.strip("${}")
|
|
90
|
+
val = (env or {}).get(name)
|
|
91
|
+
if not val or val.startswith("$"):
|
|
92
|
+
return "$var"
|
|
93
|
+
tok = val
|
|
94
|
+
host = tok.split("@", 1)[-1]
|
|
95
|
+
return host.split(":", 1)[0] or "?"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _remote_segments(command):
|
|
99
|
+
"""원격 구간만 뽑는다: [(도구, 호스트, 안쪽 명령 | 'copy')]. 로컬 구간(cat > f, grep, git …)은 섞지 않는다.
|
|
100
|
+
|
|
101
|
+
heredoc 본문은 그 heredoc 을 연 원격 구간에만 붙인다. `colima ssh` 는 로컬 VM 이라 원격이 아니다.
|
|
102
|
+
"""
|
|
103
|
+
bodies = {m.group(1): m.group(2) for m in _HEREDOC.finditer(command)}
|
|
104
|
+
segs = _segment_tokens(command)
|
|
105
|
+
# 같은 명령 안에서 글자 그대로 대입된 변수만 푼다(SRV=rcw-4g; ssh $SRV ...). $(…) 는 풀지 않는다.
|
|
106
|
+
env = {}
|
|
107
|
+
for toks in segs:
|
|
108
|
+
for t in toks:
|
|
109
|
+
if _ENV_ASSIGN.match(t) and "$(" not in t and "`" not in t:
|
|
110
|
+
k, v = t.split("=", 1)
|
|
111
|
+
env[k] = v
|
|
112
|
+
out = []
|
|
113
|
+
for toks in segs:
|
|
114
|
+
for i, t in enumerate(toks):
|
|
115
|
+
base = t.rsplit("/", 1)[-1]
|
|
116
|
+
if base in ("scp", "rsync"):
|
|
117
|
+
hosts = [x for x in toks[i + 1:] if ":" in x and not x.startswith("-") and "=" not in x]
|
|
118
|
+
out.append((base, _host_label(hosts[0], env) if hosts else "?", "copy"))
|
|
119
|
+
break
|
|
120
|
+
if base != "ssh" or (i > 0 and toks[i - 1] == "colima"):
|
|
121
|
+
continue
|
|
122
|
+
j = i + 1
|
|
123
|
+
while j < len(toks):
|
|
124
|
+
a = toks[j]
|
|
125
|
+
if a.startswith("-") and len(a) >= 2:
|
|
126
|
+
j += 2 if (len(a) == 2 and a[1] in _SSH_OPTS_WITH_ARG) else 1
|
|
127
|
+
continue
|
|
128
|
+
break
|
|
129
|
+
if j >= len(toks):
|
|
130
|
+
out.append(("ssh", "?", ""))
|
|
131
|
+
break
|
|
132
|
+
rest = toks[j + 1:]
|
|
133
|
+
text = " ".join(rest)
|
|
134
|
+
for tag, body in bodies.items():
|
|
135
|
+
if "<<" + tag in text:
|
|
136
|
+
text += "\n" + body
|
|
137
|
+
out.append(("ssh", _host_label(toks[j], env), text))
|
|
138
|
+
break
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# 원격 구간이 여럿이면 위험·무게가 큰 쪽: 배포 > db > 파일 전송 > 나머지 사전 순서
|
|
143
|
+
_REMOTE_RANK = ["deploy", "db", "copy"] + [a for a, _ in ACTIONS if a not in ("deploy", "db", "copy")] + ["other", "connect"]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _local_target(command):
|
|
147
|
+
m = re.match(r"\s*cd\s+(\"[^\"]+\"|'[^']+'|\S+)", command)
|
|
148
|
+
if not m:
|
|
149
|
+
return ""
|
|
150
|
+
p = m.group(1).strip("'\"").rstrip("/")
|
|
151
|
+
return p.rsplit("/", 1)[-1] if p else ""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _strip_prefix_noise(command):
|
|
155
|
+
"""앞의 `cd x &&`, 환경 변수 대입, sleep 을 걷어낸다 — 동작 판정용."""
|
|
156
|
+
out = []
|
|
157
|
+
for toks in _segment_tokens(command):
|
|
158
|
+
while toks and (_ENV_ASSIGN.match(toks[0]) or toks[0] in ("sleep", "time", "nohup", "env")):
|
|
159
|
+
toks = toks[2:] if toks[0] == "sleep" else toks[1:]
|
|
160
|
+
if toks and toks[0] == "cd":
|
|
161
|
+
continue
|
|
162
|
+
if toks:
|
|
163
|
+
out.append(" ".join(toks))
|
|
164
|
+
return "\n".join(out)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
_ROUTINE = re.compile(r"skills/(rc-routine-[A-Za-z0-9_-]+)/")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def classify(command):
|
|
171
|
+
command = command or ""
|
|
172
|
+
rm = _ROUTINE.search(command)
|
|
173
|
+
if rm: # 루틴 스킬 스크립트 실행 — 절감 측정(R6·R7)의 '후' 쪽 호출
|
|
174
|
+
return {"group": "routine", "target": rm.group(1), "action": "run"}
|
|
175
|
+
remote = _remote_segments(command)
|
|
176
|
+
if remote:
|
|
177
|
+
labeled = []
|
|
178
|
+
for _tool, host, inner in remote:
|
|
179
|
+
if inner == "copy":
|
|
180
|
+
act = "copy"
|
|
181
|
+
elif not inner.strip() or re.fullmatch(r"\s*['\"]?\s*(echo\s+\S+|true|exit|hostname|whoami)\s*['\"]?(\s*\d?>&?\s*\S+)*\s*", inner):
|
|
182
|
+
act = "connect" # 접속 확인만
|
|
183
|
+
else:
|
|
184
|
+
act = action_of(inner)
|
|
185
|
+
labeled.append((_REMOTE_RANK.index(act), host, act))
|
|
186
|
+
labeled.sort(key=lambda x: x[0])
|
|
187
|
+
_, host, act = labeled[0]
|
|
188
|
+
return {"group": "remote", "target": host, "action": act}
|
|
189
|
+
body = _strip_prefix_noise(command)
|
|
190
|
+
heredocs = [m.group(2) for m in _HEREDOC.finditer(command)]
|
|
191
|
+
act = action_of(body)
|
|
192
|
+
if act == "script" and heredocs:
|
|
193
|
+
act = "inline-script"
|
|
194
|
+
return {"group": "local", "target": _local_target(command), "action": act}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def kind_key(k):
|
|
198
|
+
return f"{k['group']}:{k['target'] or '-'}:{k['action']}"
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""work_kind_events — 끝난 세션의 '반복하는 일'을 지식 문제 등록부에 싣는다 (docs/지식체계/40 §4.8, 39 시안 v4 '일' 행).
|
|
3
|
+
|
|
4
|
+
- 대상: 메인 대화형 세션(cli) transcript 중 마지막 변경이 IDLE_SEC 이전이고 LOOKBACK_DAYS 안인 것, 아직 보낸 적 없는 것.
|
|
5
|
+
- 세션 안 Bash 호출을 work_kind 로 묶어, 같은 종류가 MIN_CALLS 번 이상이면 그 세션의 '일' 1건으로 본다.
|
|
6
|
+
encounter {kind:'work', problemKey:'w:<fk>', familyKey:<fk>, label:'<대상> · <동작>', area, example, at}
|
|
7
|
+
resolution {problemKey, familyKey, tools=호출 수, seconds=첫~끝 호출 간격, at}
|
|
8
|
+
fk = sha1(종류 키)[:12]. 같은 종류는 세션이 달라도 한 줄로 묶인다(반복 횟수 = 세션 수).
|
|
9
|
+
- example = 그 일 직전 사용자 요청의 첫 줄(가림 처리, ≤80자). 명령 원문은 보내지 않는다(라벨만, RDPE A10).
|
|
10
|
+
- 만든 루틴 스킬(skills/rc-routine-*/routine.json 의 replaces 정규식)이 대신하는 종류를 찾아
|
|
11
|
+
skill_link {skillName, familyKeys, runs, removed} 로 보낸다 → 화면 '스킬 있음' 표시. 바뀔 때만 보낸다.
|
|
12
|
+
종류 키→fk 는 KEYS_NAME 에 쌓는다(키 원문은 보내지 않음). 처음이면 기간 안 세션을 한 번 훑어 채운다.
|
|
13
|
+
- 보내기는 knowledge_items 대기열(queue_events) → flush. 실패해도 훅을 막지 않는다.
|
|
14
|
+
|
|
15
|
+
CLI: python3 work_kind_events.py [--dry-run]
|
|
16
|
+
"""
|
|
17
|
+
import glob
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
from datetime import datetime, timezone
|
|
25
|
+
|
|
26
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
27
|
+
import work_kind as wk # noqa: E402
|
|
28
|
+
|
|
29
|
+
LOOKBACK_DAYS = 28
|
|
30
|
+
IDLE_SEC = 2 * 3600
|
|
31
|
+
MIN_CALLS = 3
|
|
32
|
+
MAX_SESSIONS_PER_RUN = 80
|
|
33
|
+
REFRESH_SEC = 30 * 60
|
|
34
|
+
STATE_NAME = 'work-sessions.json'
|
|
35
|
+
STAMP_NAME = 'work-sessions.stamp'
|
|
36
|
+
KEYS_NAME = 'work-kinds.json'
|
|
37
|
+
LINKS_NAME = 'skill-links.json'
|
|
38
|
+
# 반복하는 '일'로 보는 동작 — 읽기·쓰기·git 처럼 모든 일에 섞이는 동작은 뺀다
|
|
39
|
+
WORK_ACTIONS = frozenset(['deploy', 'db', 'logs', 'status', 'copy', 'cron', 'test', 'build', 'install'])
|
|
40
|
+
EXAMPLE_MAX = 80
|
|
41
|
+
CALL_SEC_CAP = 180 # 호출 1번에 드는 시간 상한(다음 응답까지 간격, 생각·다른 일 포함 방지)
|
|
42
|
+
|
|
43
|
+
_CONFIRM_ONLY = re.compile(r'^(?:그래|응|네|예|좋아|오케이|ok|okay|yes|go)?[\s,.!~]*(?:모두|다|전부|계속|더|이어서|바로)?\s*(?:진행|구현|반영|수정|배포|해|해줘|진행해|구현해|반영해|수정해|배포해|시작|확인)[가-힣]*[\s.!~]*$', re.I)
|
|
44
|
+
|
|
45
|
+
_MASKS = [re.compile(p) for p in [
|
|
46
|
+
r"(?i)\b\w*(?:PW|PASS|PASSWD|PASSWORD|TOKEN|SECRET|KEY)\w*\s*[=:]\s*\S+",
|
|
47
|
+
r"(?i)authorization:\s*\S+\s+\S+",
|
|
48
|
+
r"(://[^:/\s]+:)[^@\s]+@",
|
|
49
|
+
r"\b[A-Za-z0-9+/_-]{32,}\b",
|
|
50
|
+
r"[\w.+-]+@[\w-]+\.[\w.]+",
|
|
51
|
+
]]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def mask_example(text):
|
|
55
|
+
"""요청 첫 줄 → 가림 처리한 ≤80자. 명령·붙여넣기·시스템 문구면 None."""
|
|
56
|
+
try:
|
|
57
|
+
t = str(text or '').strip()
|
|
58
|
+
if not t or t.startswith('<') or t.startswith('/') or t.startswith('[') or t.startswith('{'):
|
|
59
|
+
return None
|
|
60
|
+
t = t.split('\n')[0].strip()
|
|
61
|
+
if t.startswith('❯'):
|
|
62
|
+
t = t[1:].strip()
|
|
63
|
+
if '│' in t or '┃' in t or t[:1] in ('\'', '"', '`'):
|
|
64
|
+
return None # 붙여넣은 표·인용(경로) — 요청이 아니다
|
|
65
|
+
for rx in _MASKS:
|
|
66
|
+
t = rx.sub('<가림>', t)
|
|
67
|
+
try:
|
|
68
|
+
import secret_filter as sf
|
|
69
|
+
t, _ = sf.redact(t)
|
|
70
|
+
except Exception:
|
|
71
|
+
pass
|
|
72
|
+
t = re.sub(r'\s+', ' ', t).strip()
|
|
73
|
+
if len(t.replace(' ', '')) < 6 or _CONFIRM_ONLY.match(t):
|
|
74
|
+
return None
|
|
75
|
+
return t[:EXAMPLE_MAX]
|
|
76
|
+
except Exception:
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def family_key(key):
|
|
81
|
+
return hashlib.sha1(key.encode('utf-8')).hexdigest()[:12]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def label_of(k):
|
|
85
|
+
return '%s · %s' % (k.get('target') or '-', k['action'])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _ts(v):
|
|
89
|
+
try:
|
|
90
|
+
return datetime.strptime(v[:19], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc).timestamp()
|
|
91
|
+
except Exception:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _repo_name(cwd):
|
|
96
|
+
"""cwd 의 git 루트 폴더 이름(없으면 cwd 마지막 폴더)."""
|
|
97
|
+
try:
|
|
98
|
+
d = os.path.abspath(cwd)
|
|
99
|
+
cur = d
|
|
100
|
+
while cur and cur != os.path.dirname(cur):
|
|
101
|
+
if os.path.exists(os.path.join(cur, '.git')):
|
|
102
|
+
return os.path.basename(cur)
|
|
103
|
+
cur = os.path.dirname(cur)
|
|
104
|
+
return os.path.basename(d) or '-'
|
|
105
|
+
except Exception:
|
|
106
|
+
return '-'
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _prompt_text(content):
|
|
110
|
+
if isinstance(content, str):
|
|
111
|
+
return content
|
|
112
|
+
if isinstance(content, list):
|
|
113
|
+
for b in content:
|
|
114
|
+
if isinstance(b, dict) and b.get('type') == 'text':
|
|
115
|
+
return b.get('text')
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def session_work(path):
|
|
120
|
+
"""transcript 하나 → (세션 id, cwd, {종류 키: {kind, count, first, last, example}}) 또는 None(대화형 아님)."""
|
|
121
|
+
sid = os.path.basename(path)[:-6]
|
|
122
|
+
inter, cwd, last_prompt = None, None, None
|
|
123
|
+
kinds = {}
|
|
124
|
+
pending = []
|
|
125
|
+
try:
|
|
126
|
+
fh = open(path, errors='replace')
|
|
127
|
+
except OSError:
|
|
128
|
+
return None
|
|
129
|
+
with fh:
|
|
130
|
+
for line in fh:
|
|
131
|
+
try:
|
|
132
|
+
e = json.loads(line)
|
|
133
|
+
except Exception:
|
|
134
|
+
continue
|
|
135
|
+
if e.get('isSidechain'):
|
|
136
|
+
continue
|
|
137
|
+
if cwd is None and e.get('cwd'):
|
|
138
|
+
cwd = e.get('cwd')
|
|
139
|
+
if e.get('type') == 'user':
|
|
140
|
+
if inter is None and e.get('entrypoint'):
|
|
141
|
+
inter = e.get('entrypoint') == 'cli'
|
|
142
|
+
if e.get('isMeta'):
|
|
143
|
+
continue
|
|
144
|
+
txt = _prompt_text(e.get('message', {}).get('content'))
|
|
145
|
+
if txt and not (isinstance(e.get('message', {}).get('content'), list)
|
|
146
|
+
and any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in e['message']['content'])):
|
|
147
|
+
last_prompt = txt
|
|
148
|
+
continue
|
|
149
|
+
if e.get('type') != 'assistant':
|
|
150
|
+
continue
|
|
151
|
+
ts = _ts(e.get('timestamp', ''))
|
|
152
|
+
if pending and ts:
|
|
153
|
+
# 직전 '일' 호출의 시간 = 다음 응답까지 간격(상한 CALL_SEC_CAP)
|
|
154
|
+
for d0 in pending:
|
|
155
|
+
d0['seconds'] += int(min(max(0, ts - d0['_t']), CALL_SEC_CAP))
|
|
156
|
+
pending = []
|
|
157
|
+
for b in (e.get('message', {}).get('content') or []):
|
|
158
|
+
if not (isinstance(b, dict) and b.get('type') == 'tool_use' and b.get('name') == 'Bash'):
|
|
159
|
+
continue
|
|
160
|
+
k = wk.classify((b.get('input') or {}).get('command', ''))
|
|
161
|
+
if k['action'] not in WORK_ACTIONS or k['group'] not in ('remote', 'local'):
|
|
162
|
+
continue
|
|
163
|
+
if k['group'] == 'local' and (not k.get('target') or k['target'] == '-') and cwd:
|
|
164
|
+
k = dict(k, target=_repo_name(cwd))
|
|
165
|
+
key = wk.kind_key(k)
|
|
166
|
+
d = kinds.get(key)
|
|
167
|
+
if d is None:
|
|
168
|
+
d = kinds[key] = {'kind': k, 'count': 0, 'first': ts, 'seconds': 0, 'example': mask_example(last_prompt)}
|
|
169
|
+
d['count'] += 1
|
|
170
|
+
if ts:
|
|
171
|
+
d['first'] = d['first'] or ts
|
|
172
|
+
d['_t'] = ts
|
|
173
|
+
pending.append(d)
|
|
174
|
+
if not inter:
|
|
175
|
+
return None
|
|
176
|
+
return sid, cwd, {k: v for k, v in kinds.items() if v['count'] >= MIN_CALLS}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def events_of(sid, cwd, kinds, area_of):
|
|
180
|
+
out = []
|
|
181
|
+
for key, d in sorted(kinds.items()):
|
|
182
|
+
fk = family_key(key)
|
|
183
|
+
pk = 'w:' + fk
|
|
184
|
+
at = datetime.fromtimestamp(d['first'], timezone.utc).isoformat() if d['first'] else None
|
|
185
|
+
enc = {'type': 'encounter', 'problemKey': pk, 'familyKey': fk, 'sessionId': sid[:200],
|
|
186
|
+
'label': label_of(d['kind']), 'kind': 'work'}
|
|
187
|
+
area = area_of(cwd)
|
|
188
|
+
if area:
|
|
189
|
+
enc['area'] = area
|
|
190
|
+
if d['example']:
|
|
191
|
+
enc['example'] = d['example']
|
|
192
|
+
if at:
|
|
193
|
+
enc['at'] = at
|
|
194
|
+
res = {'type': 'resolution', 'problemKey': pk, 'familyKey': fk, 'sessionId': sid[:200],
|
|
195
|
+
'tools': d['count'], 'seconds': min(int(d.get('seconds') or 0), 604800)}
|
|
196
|
+
if at:
|
|
197
|
+
res['at'] = at
|
|
198
|
+
out += [enc, res]
|
|
199
|
+
return out
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _save(p, d):
|
|
203
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
204
|
+
tmp = p + '.tmp'
|
|
205
|
+
with open(tmp, 'w') as fh:
|
|
206
|
+
json.dump(d, fh)
|
|
207
|
+
os.replace(tmp, p)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def skill_links(keys, skills, runs_of, sent):
|
|
211
|
+
"""루틴 스킬 → skill_link 이벤트(바뀐 것만)와 새 보낸 상태. keys={종류 키: fk}, sent={스킬: [fk…]}."""
|
|
212
|
+
events, now_sent = [], {}
|
|
213
|
+
for name, c in sorted(skills.items()):
|
|
214
|
+
try:
|
|
215
|
+
rx = re.compile(c['replaces'])
|
|
216
|
+
except Exception:
|
|
217
|
+
continue
|
|
218
|
+
fks = sorted({fk for k, fk in keys.items() if rx.search(k)})[:50]
|
|
219
|
+
if not fks:
|
|
220
|
+
continue
|
|
221
|
+
st = runs_of.get(name) or {}
|
|
222
|
+
if not isinstance(st, dict):
|
|
223
|
+
st = {'runs': st}
|
|
224
|
+
runs = int(st.get('runs') or 0)
|
|
225
|
+
stats = {k: st.get(k) for k in ('since', 'beforeCalls', 'afterCalls', 'afterSessions', 'runErrors', 'lastRunAt') if st.get(k) is not None}
|
|
226
|
+
now_sent[name] = dict({'fks': fks, 'runs': runs}, **stats)
|
|
227
|
+
if sent.get(name) != now_sent[name]:
|
|
228
|
+
events.append(dict({'type': 'skill_link', 'skillName': name, 'familyKeys': fks, 'runs': runs}, **stats))
|
|
229
|
+
for name, prev in sorted(sent.items()):
|
|
230
|
+
if name not in now_sent and isinstance(prev, dict) and prev.get('fks'):
|
|
231
|
+
events.append({'type': 'skill_link', 'skillName': name, 'familyKeys': prev['fks'][:50], 'runs': int(prev.get('runs') or 0), 'removed': True})
|
|
232
|
+
return events, now_sent
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def send_links(events):
|
|
236
|
+
"""skill_link 묶음을 바로 POST. 200 이면 True(400·네트워크 = False, 다음 실행에 다시)."""
|
|
237
|
+
try:
|
|
238
|
+
import knowledge_items as ki
|
|
239
|
+
cfg = ki._config()
|
|
240
|
+
base, key = ki._server(cfg)
|
|
241
|
+
if not key or not ki._send_allowed(cfg):
|
|
242
|
+
return False
|
|
243
|
+
status, _ = ki._http('POST', base + '/api/v1/knowledge/items/events', key, {'events': events[:100]})
|
|
244
|
+
return status == 200
|
|
245
|
+
except Exception:
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _skills_and_runs():
|
|
250
|
+
try:
|
|
251
|
+
import routine_skill_eval as rse
|
|
252
|
+
skills = rse.skill_dirs()
|
|
253
|
+
c = rse.cached() or {}
|
|
254
|
+
stats = {}
|
|
255
|
+
for x in c.get('skills') or []:
|
|
256
|
+
if not isinstance(x, dict):
|
|
257
|
+
continue
|
|
258
|
+
a, b = x.get('after') or {}, x.get('before') or {}
|
|
259
|
+
stats[x.get('name')] = {
|
|
260
|
+
'runs': a.get('runs') or 0, 'since': x.get('since'),
|
|
261
|
+
'beforeCalls': b.get('median_calls'), 'afterCalls': a.get('median_calls'),
|
|
262
|
+
'afterSessions': a.get('sessions') or 0, 'runErrors': a.get('run_errors') or 0, 'lastRunAt': a.get('last_run'),
|
|
263
|
+
}
|
|
264
|
+
return skills, stats
|
|
265
|
+
except Exception:
|
|
266
|
+
return {}, {}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _load(p):
|
|
270
|
+
try:
|
|
271
|
+
d = json.load(open(p))
|
|
272
|
+
return d if isinstance(d, dict) else {}
|
|
273
|
+
except Exception:
|
|
274
|
+
return {}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def run(now=None, projects_glob=None, dry_run=False, acct=None, force=False):
|
|
278
|
+
"""끝난 세션을 처리해 대기열에 싣는다. 반환 {'sessions': 처리 수, 'events': 실은 이벤트 수}."""
|
|
279
|
+
import knowledge_items as ki
|
|
280
|
+
now = now or time.time()
|
|
281
|
+
a = acct if acct is not None else ki._ks().account()
|
|
282
|
+
state_p = ki.account_path(a, STATE_NAME)
|
|
283
|
+
if not state_p:
|
|
284
|
+
return {'sessions': 0, 'events': 0}
|
|
285
|
+
stamp_p = ki.account_path(a, STAMP_NAME)
|
|
286
|
+
if not force and not dry_run:
|
|
287
|
+
try:
|
|
288
|
+
if now - os.path.getmtime(stamp_p) < REFRESH_SEC:
|
|
289
|
+
return {'sessions': 0, 'events': 0}
|
|
290
|
+
except OSError:
|
|
291
|
+
pass
|
|
292
|
+
state = _load(state_p)
|
|
293
|
+
keys_p = ki.account_path(a, KEYS_NAME)
|
|
294
|
+
keys = _load(keys_p) if keys_p else {}
|
|
295
|
+
backfill = keys_p is not None and not os.path.exists(keys_p)
|
|
296
|
+
files = []
|
|
297
|
+
for f in glob.glob(projects_glob or os.path.expanduser('~/.claude/projects/*/*.jsonl')):
|
|
298
|
+
try:
|
|
299
|
+
m = os.path.getmtime(f)
|
|
300
|
+
except OSError:
|
|
301
|
+
continue
|
|
302
|
+
sid = os.path.basename(f)[:-6]
|
|
303
|
+
if m > now - IDLE_SEC or m < now - LOOKBACK_DAYS * 86400:
|
|
304
|
+
continue
|
|
305
|
+
if sid in state:
|
|
306
|
+
if backfill: # 처음 한 번 — 이미 보낸 세션의 종류 키만 모은다(이벤트 없음)
|
|
307
|
+
r = session_work(f)
|
|
308
|
+
if r:
|
|
309
|
+
keys.update({k: family_key(k) for k in r[2]})
|
|
310
|
+
continue
|
|
311
|
+
files.append((m, f, sid))
|
|
312
|
+
files.sort()
|
|
313
|
+
done, events = 0, []
|
|
314
|
+
for _m, f, sid in files[:MAX_SESSIONS_PER_RUN]:
|
|
315
|
+
r = session_work(f)
|
|
316
|
+
state[sid] = int(now)
|
|
317
|
+
done += 1
|
|
318
|
+
if not r:
|
|
319
|
+
continue
|
|
320
|
+
_sid, cwd, kinds = r
|
|
321
|
+
keys.update({k: family_key(k) for k in kinds})
|
|
322
|
+
events += events_of(_sid, cwd, kinds, lambda c: ki.encounter_area(a, c) if c else None)
|
|
323
|
+
links_p = ki.account_path(a, LINKS_NAME)
|
|
324
|
+
skills, runs_of = _skills_and_runs()
|
|
325
|
+
prev_sent = _load(links_p) if links_p else {}
|
|
326
|
+
link_events, now_sent = skill_links(keys, skills, runs_of, prev_sent)
|
|
327
|
+
if dry_run:
|
|
328
|
+
return {'sessions': done, 'events': len(events), 'keys': len(keys), 'links': link_events, 'sample': events[:4]}
|
|
329
|
+
if events:
|
|
330
|
+
ki.queue_events(events, acct=a)
|
|
331
|
+
try:
|
|
332
|
+
os.makedirs(os.path.dirname(state_p), exist_ok=True)
|
|
333
|
+
# 기간 밖 세션은 잊는다(상태 파일이 커지지 않게)
|
|
334
|
+
keep = {k: v for k, v in state.items() if v > now - (LOOKBACK_DAYS + 7) * 86400}
|
|
335
|
+
_save(state_p, keep)
|
|
336
|
+
if keys_p:
|
|
337
|
+
_save(keys_p, keys)
|
|
338
|
+
# skill_link 은 대기열에 섞지 않고 따로 보낸다 — 옛 서버가 400 으로 묶음 전체를 버리지 않게. 보낸 때만 상태 갱신.
|
|
339
|
+
if links_p and link_events and send_links(link_events):
|
|
340
|
+
_save(links_p, now_sent)
|
|
341
|
+
with open(stamp_p, 'w') as fh:
|
|
342
|
+
fh.write(str(int(now)))
|
|
343
|
+
except Exception:
|
|
344
|
+
pass
|
|
345
|
+
if events:
|
|
346
|
+
try:
|
|
347
|
+
ki.flush(acct=a)
|
|
348
|
+
except Exception:
|
|
349
|
+
pass
|
|
350
|
+
# 화면 ① '한 번에 스킬로 만들기' 의 재료 — 내 컴퓨터에만(6시간에 1번, 실패해도 무시)
|
|
351
|
+
try:
|
|
352
|
+
import skill_drafts
|
|
353
|
+
skill_drafts.write(acct=a, now=now)
|
|
354
|
+
except Exception:
|
|
355
|
+
pass
|
|
356
|
+
return {'sessions': done, 'events': len(events)}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
if __name__ == '__main__':
|
|
360
|
+
dry = '--dry-run' in sys.argv
|
|
361
|
+
print(json.dumps(run(dry_run=dry, force='--force' in sys.argv), ensure_ascii=False, indent=2))
|
package/hooks/pending-drainer.sh
CHANGED
|
@@ -48,8 +48,15 @@ ROUTINECODE_DRAIN_PENDING="$PENDING" \
|
|
|
48
48
|
ROUTINECODE_DRAIN_DEADLETTER="$DEADLETTER" \
|
|
49
49
|
ROUTINECODE_DRAIN_MARKER="$MARKER" \
|
|
50
50
|
ROUTINECODE_DRAIN_DRY="${ROUTINECODE_DRAIN_DRY:-}" \
|
|
51
|
+
ROUTINECODE_DRAIN_LIB="$(cd "$(dirname "$0")" && pwd)/lib" \
|
|
51
52
|
python3 - <<'PYEOF'
|
|
52
53
|
import json, os, sys, time, urllib.request, urllib.error
|
|
54
|
+
sys.path.insert(0, os.environ.get('ROUTINECODE_DRAIN_LIB', ''))
|
|
55
|
+
try:
|
|
56
|
+
from privacy_log import log_transmission
|
|
57
|
+
except Exception:
|
|
58
|
+
def log_transmission(url, body):
|
|
59
|
+
pass
|
|
53
60
|
|
|
54
61
|
CONFIG = os.environ['ROUTINECODE_DRAIN_CONFIG']
|
|
55
62
|
CLAIM = os.environ['ROUTINECODE_DRAIN_CLAIM']
|
|
@@ -122,6 +129,20 @@ tenant_id = cfg.get('tenantId')
|
|
|
122
129
|
user_id = cfg.get('userId')
|
|
123
130
|
machine_id = cfg.get('machineId')
|
|
124
131
|
contributor = ('p:' + str(user_id)) if user_id else machine_id
|
|
132
|
+
knowledge_off = cfg.get('knowledgeSyncDisabled') is True
|
|
133
|
+
|
|
134
|
+
def is_config(endpoint):
|
|
135
|
+
return str(endpoint).startswith('config/')
|
|
136
|
+
|
|
137
|
+
def legacy_config(item):
|
|
138
|
+
# 이전 기본값(상세 공유 on)으로 쌓인 본문. 오늘 다시 만들어지므로 보내지 않고 버린다(설계 15 §4.4).
|
|
139
|
+
data = item.get('data') or {}
|
|
140
|
+
return item.get('endpoint') in ('config/snapshots', 'config/proposals') and data.get('consentVersion') is None
|
|
141
|
+
|
|
142
|
+
def needs_flush(item):
|
|
143
|
+
# 드레이너는 정제하지 않는다. 표식(sv)이 없는 지식 항목은 flushPending(MCP)에 넘긴다(설계 15 §4.2).
|
|
144
|
+
endpoint = item.get('endpoint', '')
|
|
145
|
+
return not is_config(endpoint) and endpoint != 'ontology/verify' and not item.get('sv')
|
|
125
146
|
|
|
126
147
|
items = load_claim()
|
|
127
148
|
leftover = [] # 이번 패스에서 전송하지 않고 pending 으로 되돌릴 항목(미도래/백오프/상한초과)
|
|
@@ -158,6 +179,7 @@ def send(endpoint, data):
|
|
|
158
179
|
body['userId'] = user_id if user_id is not None else None
|
|
159
180
|
body['contributorHash'] = contributor
|
|
160
181
|
url = endpoint_url(endpoint)
|
|
182
|
+
log_transmission(url, body)
|
|
161
183
|
payload = json.dumps(body).encode('utf-8')
|
|
162
184
|
req = urllib.request.Request(url, data=payload, method='POST')
|
|
163
185
|
req.add_header('Content-Type', 'application/json')
|
|
@@ -176,6 +198,12 @@ def send(endpoint, data):
|
|
|
176
198
|
|
|
177
199
|
cur = now_ms()
|
|
178
200
|
for idx, item in enumerate(items):
|
|
201
|
+
if legacy_config(item):
|
|
202
|
+
continue
|
|
203
|
+
# privacy knowledge off: 지식 항목은 보내지 않고 큐에 둔다. config/ 는 arch share·team 이 따로 제어한다.
|
|
204
|
+
if (knowledge_off and not is_config(item.get('endpoint', ''))) or needs_flush(item):
|
|
205
|
+
leftover.append(item)
|
|
206
|
+
continue
|
|
179
207
|
# 상한 초과 → 남은 항목 전부 pending 으로 이월
|
|
180
208
|
if processed >= MAX_BATCH:
|
|
181
209
|
leftover.append(item)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# PostToolUse hook: 맥락이 커질 때 알린다.
|
|
3
|
+
# 작업자: 호출이 많을수록 서브 맥락이 커져 호출당 비용이 오른다. 일정 호출에 도달하면 결과를 정리해
|
|
4
|
+
# 반환하라고 알린다. 강제 종료는 하지 않는다. 독립 검증 에이전트에는 적용하지 않는다.
|
|
5
|
+
# 메인: 메인은 자기 맥락 크기를 모른다. 호출 20회마다 transcript 끝을 읽어 큰 맥락을 알린다.
|
|
6
|
+
#
|
|
7
|
+
# 환경변수: ROUTINECODE_AGENT_CALL_LIMIT=60 (0 이면 끔), ROUTINECODE_CONTEXT_NOTICE=300000 (0 이면 끔)
|
|
8
|
+
|
|
9
|
+
INPUT="$(cat)"
|
|
10
|
+
INTERVAL=20
|
|
11
|
+
|
|
12
|
+
RC_RUNDIR="${XDG_RUNTIME_DIR:-$HOME/.routinecode/run}"
|
|
13
|
+
export RC_RUNDIR
|
|
14
|
+
LIB="$(dirname "$0")/lib/agent_budget.py"
|
|
15
|
+
|
|
16
|
+
case "$INPUT" in
|
|
17
|
+
*'"agent_id"'*)
|
|
18
|
+
mkdir -p "$RC_RUNDIR/agent-budget" 2>/dev/null || exit 0
|
|
19
|
+
printf '%s' "$INPUT" | python3 "$LIB" 2>/dev/null
|
|
20
|
+
exit 0
|
|
21
|
+
;;
|
|
22
|
+
esac
|
|
23
|
+
|
|
24
|
+
[ "${ROUTINECODE_CONTEXT_NOTICE:-300000}" = "0" ] && exit 0
|
|
25
|
+
|
|
26
|
+
SID_RE='"session_id"[[:space:]]*:[[:space:]]*"([A-Za-z0-9_-]{1,80})"'
|
|
27
|
+
[[ "$INPUT" =~ $SID_RE ]] || exit 0
|
|
28
|
+
SID="${BASH_REMATCH[1]}"
|
|
29
|
+
|
|
30
|
+
DIR="$RC_RUNDIR/context-notice"
|
|
31
|
+
mkdir -p "$DIR" 2>/dev/null || exit 0
|
|
32
|
+
COUNT_FILE="$DIR/$SID.count"
|
|
33
|
+
|
|
34
|
+
COUNT=0
|
|
35
|
+
NEXT=$INTERVAL
|
|
36
|
+
if [ -f "$COUNT_FILE" ]; then
|
|
37
|
+
read -r COUNT NEXT < "$COUNT_FILE" 2>/dev/null
|
|
38
|
+
fi
|
|
39
|
+
case "$COUNT" in ''|*[!0-9]*) COUNT=0 ;; esac
|
|
40
|
+
case "$NEXT" in ''|*[!0-9]*) NEXT=$INTERVAL ;; esac
|
|
41
|
+
|
|
42
|
+
COUNT=$((COUNT + 1))
|
|
43
|
+
if [ "$COUNT" -ge "$NEXT" ]; then
|
|
44
|
+
NEXT=$((COUNT + INTERVAL))
|
|
45
|
+
printf '%s %s\n' "$COUNT" "$NEXT" > "$COUNT_FILE" 2>/dev/null
|
|
46
|
+
printf '%s' "$INPUT" | python3 "$LIB" --context 2>/dev/null
|
|
47
|
+
else
|
|
48
|
+
printf '%s %s\n' "$COUNT" "$NEXT" > "$COUNT_FILE" 2>/dev/null
|
|
49
|
+
fi
|
|
50
|
+
exit 0
|