@routinecrew/routinecode 2.31.87 → 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-suggestions.js +100 -0
- package/bin/rc-team.js +1 -1
- package/hooks/hooks-config.json +9 -0
- 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/emit_raw.py +4 -0
- 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 +22 -2
- package/hooks/pre-bash-guard.sh +22 -0
- package/hooks/pre-bash-knowledge.sh +12 -2
- package/hooks/pre-edit-delegate.sh +15 -0
- package/hooks/pre-edit-guard.sh +10 -0
- package/hooks/pre-read-guard.sh +10 -0
- package/hooks/session-start.sh +6 -0
- package/hooks/stop-usage-metrics.sh +6 -0
- package/hooks/subagent-stop-usage.sh +36 -4
- package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
- package/mcp-intelligence/dist/knowledge-record.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,88 @@
|
|
|
1
|
+
{
|
|
2
|
+
"rules_version": 2,
|
|
3
|
+
"models": {
|
|
4
|
+
"implementor": "sonnet", "implementor-lite": "haiku", "ops-lite": "haiku", "runner-lite": "haiku", "reviewer": "opus", "main": "opus",
|
|
5
|
+
"note": "rules_version 2 (2026-11-16): implementor Opus → Sonnet 5.5 (Terminal-Bench 4.0 70.6 대 66.4, 토큰 단가 1/2). 승격 사슬 Haiku → Sonnet → 메인 Opus. 기준선 비교는 rules_version 으로 나눈다"
|
|
6
|
+
},
|
|
7
|
+
"doc_re": "\\.(md|txt|json|ya?ml|csv)$",
|
|
8
|
+
"risk_re": "(auth|payment|billing|secret|security|credential|token|oauth|migrat|crypto|grant|seal|permission|rls|webhook)",
|
|
9
|
+
"control_ratio": 0.1,
|
|
10
|
+
"projection": {
|
|
11
|
+
"note": "route-metrics S3 예상 절감 가정(초기값). ratio = 같은 일을 Opus 대비 비용비(haiku 1/21 = 벤치 v1 체크리스트 조건 실측, sonnet = 공시 단가 1/2). keep = 메인에 남는 몫(카드 작성·요약 읽기·승인), review = 새로 붙는 리뷰 비용비. 측정값(M5 승격률, card_open 위험·대조군 비중)이 min_n 이상이면 자동 대체",
|
|
12
|
+
"ratio": {"haiku": 0.048, "sonnet": 0.5, "opus": 1.0},
|
|
13
|
+
"control": 0.1, "risk_share": 0.15, "escalation": 0.25
|
|
14
|
+
},
|
|
15
|
+
"kinds": ["main_code", "impl_large", "risk", "ops_read", "ops_proc", "run", "doc", "other"],
|
|
16
|
+
"thresholds": {
|
|
17
|
+
"refix_gap_pp": 2,
|
|
18
|
+
"escalation_max": 0.30,
|
|
19
|
+
"review_low": 0.05,
|
|
20
|
+
"review_high": 0.20,
|
|
21
|
+
"review_hit_min": 0.5,
|
|
22
|
+
"min_n": 20,
|
|
23
|
+
"min_n_widen": 40
|
|
24
|
+
},
|
|
25
|
+
"refix": {
|
|
26
|
+
"same_session_window_s": 7200,
|
|
27
|
+
"note": "refix_same_session = 같은 세션 AND 카드 종료 뒤 2시간 안 재편집(작업 안의 이어진 수정). refix_later = 다른 세션 OR 2시간 뒤. refix_7d = refix_later (M8)"
|
|
28
|
+
},
|
|
29
|
+
"nudge": {
|
|
30
|
+
"note": "설계 34 §5.4 P4 1단계 — 메인 직접 실행 경고(hooks/lib/delegate_nudge.py, 차단 없음). verify_re = mine.py VERIFY",
|
|
31
|
+
"verify_re": "(npm (run )?(test|build)|pnpm (test|build)|tsc|pytest|jest|vitest|go test|cargo (test|build)|node --test|python3? -m pytest|test_|build_check|run_tests)",
|
|
32
|
+
"remote_re": "(?:^|[\\s;&|(`])(ssh|scp|rsync|docker)(?=\\s|$)"
|
|
33
|
+
},
|
|
34
|
+
"gate": {
|
|
35
|
+
"version": 1,
|
|
36
|
+
"note": "설계 34 §5.5 P2 — implementor-lite 완료 관문(hooks/lib/card_gate.py). 차단은 카드당 max_blocks 회, 그 뒤 gate_fail 기록",
|
|
37
|
+
"agent_types": ["implementor-lite"],
|
|
38
|
+
"max_blocks": 2,
|
|
39
|
+
"test_re": "(^|/)(tests?|__tests__|spec)/|[._-](test|spec)\\.[A-Za-z0-9]+$|(^|/)test_[^/]*\\.py$",
|
|
40
|
+
"assert_re": "(\\bassert\\w*\\b|\\bexpect\\s*\\(|\\.should\\b|\\bcheck\\s*\\(|\\bt\\.(ok|equal|is|deepEqual|strictEqual|true|false|throws)\\b|\\.to(Be|Equal|Throw|Match|Contain|Have)\\w*\\s*\\(|\\bself\\.fail\\b|\\bpytest\\.raises\\b)",
|
|
41
|
+
"attest_kinds": ["tests", "typecheck", "build"],
|
|
42
|
+
"path_fix_skip": ["node_modules", ".git", "dist", "build", ".venv", "venv", "__pycache__", ".next", "coverage"],
|
|
43
|
+
"path_fix_max_entries": 60000,
|
|
44
|
+
"path_fix_max_depth": 12,
|
|
45
|
+
"test_scan_max_files": 3000
|
|
46
|
+
},
|
|
47
|
+
"ops": {
|
|
48
|
+
"version": 1,
|
|
49
|
+
"agent_types": ["ops-lite"],
|
|
50
|
+
"approval_dir": "ops-approvals",
|
|
51
|
+
"commands": [
|
|
52
|
+
["docker", "ps"], ["docker", "logs"], ["docker", "inspect"], ["docker", "stats"],
|
|
53
|
+
["docker", "compose", "ps"], ["docker", "compose", "logs"], ["docker", "exec"],
|
|
54
|
+
["systemctl", "status"], ["systemctl", "is-active"], ["journalctl"],
|
|
55
|
+
["curl"], ["psql"], ["ssh"], ["cd"],
|
|
56
|
+
["tail"], ["head"], ["cat"], ["ls"], ["df"], ["free"], ["uptime"],
|
|
57
|
+
["grep"], ["wc"], ["sort"], ["uniq"], ["cut"], ["jq"]
|
|
58
|
+
],
|
|
59
|
+
"deny_flags": {
|
|
60
|
+
"docker logs": ["-f", "--follow"],
|
|
61
|
+
"docker compose logs": ["-f", "--follow"],
|
|
62
|
+
"tail": ["-f", "-F", "--follow", "--retry"],
|
|
63
|
+
"journalctl": ["-f", "--follow", "--vacuum", "--rotate", "--flush", "--sync", "--relinquish-var",
|
|
64
|
+
"--smart-relinquish-var", "--setup-keys", "--update-catalog"],
|
|
65
|
+
"sort": ["-o", "--output"],
|
|
66
|
+
"grep": ["-r", "-R", "--recursive", "--dereference-recursive", "-d", "--directories", "-f", "--file"],
|
|
67
|
+
"curl": ["-X", "--request", "-d", "--data", "--json", "-F", "--form", "-T", "--upload-file",
|
|
68
|
+
"-o", "--output", "-O", "--remote-name", "-K", "--config", "-u", "--user", "-H", "--header",
|
|
69
|
+
"-b", "--cookie", "-c", "--cookie-jar"],
|
|
70
|
+
"psql": ["-f", "--file", "-o", "--output", "-L", "--log-file"]
|
|
71
|
+
},
|
|
72
|
+
"curl_short_deny": "XdFTOoKuHbc",
|
|
73
|
+
"require_flags": {
|
|
74
|
+
"docker stats": ["--no-stream"],
|
|
75
|
+
"curl": ["-s", "--silent"]
|
|
76
|
+
},
|
|
77
|
+
"cat_path_re": "(\\.log(\\.\\d+)?$|/logs?/)",
|
|
78
|
+
"secret_path_re": "(\\.env\\b|secret|credential|\\.pem$|\\.key$|id_rsa|id_ed25519|\\.npmrc|\\.netrc|\\.pgpass|/attest/|\\.ssh/)",
|
|
79
|
+
"inspect_format_deny_re": "(env|\\.Config\\s*[})]|\\{\\{\\s*(json\\s+)?\\.\\s*\\}\\})",
|
|
80
|
+
"stdin_only": ["uniq"],
|
|
81
|
+
"jq_deny_re": "\\b(env|input_filename|\\$__loc__)\\b",
|
|
82
|
+
"psql_select_re": "^\\s*(select|with|show|explain)\\b",
|
|
83
|
+
"psql_write_re": "\\b(insert|update|delete|drop|alter|create|truncate|grant|revoke|copy|vacuum|reindex|cluster|call|do|lock|comment|refresh|set|reset|pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_read_file|pg_read_binary_file|pg_ls_dir|lo_import|lo_export|dblink|nextval|setval)\\b",
|
|
84
|
+
"ssh_alias_re": "^[A-Za-z][A-Za-z0-9_-]*$",
|
|
85
|
+
"script_re": "^(?:\\./)?(?:.*/)?scripts/ops/([a-z0-9][a-z0-9-]*\\.sh)$",
|
|
86
|
+
"read_only_scripts": ["status.sh", "wait-*.sh"]
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""
|
|
2
|
+
savings_emit — 설계 35 A13. 사용자별 절감 계산기(bin/rc-savings.js)가 쓴 ~/.routinecode/savings.json 의
|
|
3
|
+
숫자만 골라 기존 usage 경로(emit_raw → events.jsonl → sync_manager)로 savings_calc 이벤트 1건을 내보낸다.
|
|
4
|
+
|
|
5
|
+
- 숫자만: 퍼센트·배수·주 시작일·배수표 라벨. 경로·세션 id·대화 원문 없음.
|
|
6
|
+
- 세션 id = 주 시작일(YYYY-MM-DD). 서버가 (사용자, 주) 당 1행으로 덮어쓴다.
|
|
7
|
+
- 같은 값이면 다시 보내지 않고, 값이 바뀌어도 최소 30분 간격(세션 끝마다 갱신돼도 이벤트 폭주 방지).
|
|
8
|
+
- fail-open: 어떤 오류에도 조용히 False.
|
|
9
|
+
"""
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
17
|
+
sys.path.insert(0, HERE)
|
|
18
|
+
|
|
19
|
+
MIN_INTERVAL_SEC = 1800
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _num(v):
|
|
23
|
+
return v if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def build_metadata(rep):
|
|
27
|
+
"""savings.json dict -> savings_calc metadata. 핵심 숫자가 없으면 None."""
|
|
28
|
+
cur = rep.get("current") if isinstance(rep, dict) else None
|
|
29
|
+
if not isinstance(cur, dict):
|
|
30
|
+
return None
|
|
31
|
+
actual, opus, saving = _num(cur.get("actualPct")), _num(cur.get("opusPct")), _num(cur.get("savingPct"))
|
|
32
|
+
if actual is None or opus is None or saving is None or not isinstance(cur.get("week"), str):
|
|
33
|
+
return None
|
|
34
|
+
rp = cur.get("replay") or {}
|
|
35
|
+
parts = {k: _num(rp.get(src)) for k, src in (("main", "mainOwnPct"), ("sub", "subTokensPct"), ("reread", "rereadPct"), ("compact", "compactionPct")) if _num(rp.get(src)) is not None}
|
|
36
|
+
origin = {k: _num(v.get("actualPct")) for k, v in (cur.get("byOrigin") or {}).items() if isinstance(v, dict) and _num(v.get("actualPct")) is not None}
|
|
37
|
+
length = {k: _num(v.get("savingPct")) for k, v in (cur.get("byLength") or {}).items() if isinstance(v, dict) and _num(v.get("savingPct")) is not None}
|
|
38
|
+
meta = {
|
|
39
|
+
"calc_week": cur["week"],
|
|
40
|
+
"actual_pct": actual,
|
|
41
|
+
"opus_pct": opus,
|
|
42
|
+
"saving_pct": saving,
|
|
43
|
+
"multiple": _num(cur.get("multiple")),
|
|
44
|
+
"calc_parts": parts,
|
|
45
|
+
"calc_origin": origin,
|
|
46
|
+
"calc_length": length,
|
|
47
|
+
"calc_version": (rep.get("calibration") or {}).get("version"),
|
|
48
|
+
}
|
|
49
|
+
cum = rep.get("cumulative")
|
|
50
|
+
if isinstance(cum, dict) and _num(cum.get("savingPct")) is not None:
|
|
51
|
+
meta.update(cum_actual_pct=_num(cum.get("actualPct")), cum_opus_pct=_num(cum.get("opusPct")),
|
|
52
|
+
cum_saving_pct=_num(cum.get("savingPct")), cum_weeks=_num(cum.get("weeks")))
|
|
53
|
+
rec = rep.get("recent4")
|
|
54
|
+
if isinstance(rec, dict) and _num(rec.get("savingPct")) is not None:
|
|
55
|
+
meta.update(rec_actual_pct=_num(rec.get("actualPct")), rec_opus_pct=_num(rec.get("opusPct")),
|
|
56
|
+
rec_saving_pct=_num(rec.get("savingPct")), rec_weeks=_num(rec.get("weeks")))
|
|
57
|
+
hist = []
|
|
58
|
+
for h in (rep.get("history") or [])[-8:]:
|
|
59
|
+
if isinstance(h, dict) and isinstance(h.get("week"), str) and None not in (_num(h.get("savingPct")), _num(h.get("actualPct")), _num(h.get("opusPct"))):
|
|
60
|
+
hist.append({"w": h["week"], "s": h["savingPct"], "a": h["actualPct"], "o": h["opusPct"]})
|
|
61
|
+
meta["calc_history"] = hist
|
|
62
|
+
return meta
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def maybe_emit(savings_path=None, state_path=None, now=None):
|
|
66
|
+
try:
|
|
67
|
+
base = os.path.expanduser("~/.routinecode")
|
|
68
|
+
savings_path = savings_path or os.path.join(base, "savings.json")
|
|
69
|
+
state_path = state_path or os.path.join(base, "usage", "savings-emit.json")
|
|
70
|
+
now = time.time() if now is None else now
|
|
71
|
+
rep = json.load(open(savings_path, encoding="utf-8"))
|
|
72
|
+
meta = build_metadata(rep)
|
|
73
|
+
if meta is None:
|
|
74
|
+
return False
|
|
75
|
+
digest = hashlib.sha1(json.dumps(meta, sort_keys=True).encode()).hexdigest()[:16]
|
|
76
|
+
try:
|
|
77
|
+
st = json.load(open(state_path, encoding="utf-8"))
|
|
78
|
+
except Exception:
|
|
79
|
+
st = {}
|
|
80
|
+
if st.get("digest") == digest or now - float(st.get("at", 0)) < MIN_INTERVAL_SEC:
|
|
81
|
+
return False
|
|
82
|
+
import emit_raw
|
|
83
|
+
if not emit_raw.emit_raw("savings_calc", meta, session=meta["calc_week"]):
|
|
84
|
+
return False
|
|
85
|
+
os.makedirs(os.path.dirname(state_path), exist_ok=True)
|
|
86
|
+
json.dump({"digest": digest, "at": now}, open(state_path, "w", encoding="utf-8"))
|
|
87
|
+
return True
|
|
88
|
+
except Exception:
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
maybe_emit()
|
|
@@ -1566,6 +1566,15 @@ _OPAQUE_CMD_RE = re.compile(
|
|
|
1566
1566
|
_ASSIGN_RE = re.compile(r'^(?:export\s+|local\s+|readonly\s+|declare\s+(?:-\w+\s+)*)?([A-Za-z_]\w*)=(.*)$', re.S)
|
|
1567
1567
|
_VAR_REF_RE = re.compile(r'\$\{([A-Za-z_]\w*)(?:[:?\-+=][^}]*)?\}|\$([A-Za-z_]\w*)')
|
|
1568
1568
|
_BG_JOB_RE = re.compile(r'(?<![&>|])&(?![&>])\s*(?:$|[;\n)])') # 단독 & (백그라운드 작업)
|
|
1569
|
+
# 폴더 단위 내용 검색(rg·ag·ack·ugrep, grep -r/-R/--recursive). CC 2.1.325 부터 Grep 도구가 기본 노출되지 않아
|
|
1570
|
+
# 검색이 Bash 로 옮겨 왔다. 대상 경로가 명령에 없어도(cwd 검색) 그 아래 비밀 파일 값이 출력에 섞일 수 있으므로 필터를 강제한다.
|
|
1571
|
+
_RECURSIVE_SEARCH_RE = re.compile(
|
|
1572
|
+
r'(?:^|[\s;|&(`])(?:'
|
|
1573
|
+
r'(?:rg|ag|ack|ugrep)(?=[\s;|&)]|$)'
|
|
1574
|
+
r'|[efg]?grep\s+(?:[^|;&]*\s)?(?:-[A-Za-z]*[rR][A-Za-z]*|--recursive|--dereference-recursive'
|
|
1575
|
+
r'|--directories=recurse|-d\s*recurse)(?=[\s;|&)=]|$)'
|
|
1576
|
+
r')'
|
|
1577
|
+
)
|
|
1569
1578
|
|
|
1570
1579
|
|
|
1571
1580
|
def _shell_words(cmd: str) -> List[str]:
|
|
@@ -1671,6 +1680,8 @@ def bash_secret_targets(cmd: str, policy: Optional[Policy] = None) -> Tuple[List
|
|
|
1671
1680
|
force = bool(_ENV_DUMP_RE.search(cmd))
|
|
1672
1681
|
if not force and _OPAQUE_CMD_RE.search(cmd) and not _BG_JOB_RE.search(cmd):
|
|
1673
1682
|
force = True
|
|
1683
|
+
if not force and not files and _RECURSIVE_SEARCH_RE.search(cmd) and not _BG_JOB_RE.search(cmd):
|
|
1684
|
+
force = True
|
|
1674
1685
|
return files, force
|
|
1675
1686
|
|
|
1676
1687
|
|
|
@@ -56,7 +56,7 @@ USAGE_VERSION_AT_SOURCE = frozenset({"tokens", "agent_spawn", "session_start", "
|
|
|
56
56
|
# (remote-flags raw_type_<type>, 기본 off — index-store.emitTypedEvent 가 방출 시점 판정) 뒤에 있고, 전송은 같은 raw 게이트.
|
|
57
57
|
RAW_EVENT_TYPES = frozenset({
|
|
58
58
|
"encounter", "search", "exposure", "resolution",
|
|
59
|
-
"rule_applied", "krecord", "kverify", "task", "time_saved",
|
|
59
|
+
"rule_applied", "krecord", "kverify", "task", "time_saved", "savings_calc",
|
|
60
60
|
"config_task_summary", "config_wired", "config_activity",
|
|
61
61
|
})
|
|
62
62
|
|
|
@@ -71,6 +71,9 @@ RAW_METADATA_KEYS = {
|
|
|
71
71
|
"kverify": ("kid", "result", "verifier_user_id"),
|
|
72
72
|
"task": ("task_sig", "area_hint", "cwd_hash"),
|
|
73
73
|
"time_saved": ("measured_s", "paired_s", "anchored_s", "c1", "c2"),
|
|
74
|
+
"savings_calc": ("calc_week", "actual_pct", "opus_pct", "saving_pct", "multiple", "calc_parts", "calc_origin",
|
|
75
|
+
"calc_length", "calc_version", "cum_actual_pct", "cum_opus_pct", "cum_saving_pct",
|
|
76
|
+
"cum_weeks", "rec_actual_pct", "rec_opus_pct", "rec_saving_pct", "rec_weeks", "calc_history"),
|
|
74
77
|
# 설계 10 §13 북극성·A7 — 경로·코드 없음(카운트·종류·기능 id 만)
|
|
75
78
|
"config_task_summary": ("new_ci", "dup", "unwired", "struct_violation", "phase"),
|
|
76
79
|
"config_wired": ("kind",),
|
|
@@ -71,6 +71,20 @@ elif re.search(r'\bgh\s+pr\s+create\b', command, re.IGNORECASE):
|
|
|
71
71
|
op_type = 'pr_create'
|
|
72
72
|
|
|
73
73
|
if not op_type:
|
|
74
|
+
# 배포 성공 안내(설계 35c W5·플로우 13): 사용자에게만 보이는 systemMessage 1줄. 배포 명령은 op_type 대상이 아니므로
|
|
75
|
+
# 여기서만 판정한다(git push 와 한 명령에 섞인 배포는 안내 생략). 예외는 전부 fail-open.
|
|
76
|
+
_deploy_line = None
|
|
77
|
+
try:
|
|
78
|
+
_DS_LIB = os.environ.get('_HOOK_LIB_DIR', '') # 셸 변수는 env 로 받는다(heredoc 파이썬은 셸 변수를 못 본다)
|
|
79
|
+
if _DS_LIB and _DS_LIB not in sys.path:
|
|
80
|
+
sys.path.insert(0, _DS_LIB)
|
|
81
|
+
from deploy_suggest import suggest_line as _suggest_line
|
|
82
|
+
_deploy_line = _suggest_line(command, response_text, tool_response, os.environ, cwd=inp.get('cwd'))
|
|
83
|
+
except Exception:
|
|
84
|
+
_deploy_line = None
|
|
85
|
+
if _deploy_line:
|
|
86
|
+
print(json.dumps({"continue": True, "systemMessage": _deploy_line, "hookSpecificOutput": {"hookEventName": "PostToolUse"}}, ensure_ascii=False)) # additionalContext 없음: 사용자 표시 전용
|
|
87
|
+
sys.exit(0)
|
|
74
88
|
# Bash 에러 감지 → pre-query knowledge gate 트리거
|
|
75
89
|
ERROR_PATTERNS = re.compile(
|
|
76
90
|
r'(?:TypeError|ReferenceError|SyntaxError|Cannot find module'
|
package/hooks/post-edit-track.sh
CHANGED
|
@@ -11,6 +11,15 @@ _HOOK_LIB_DIR="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)"
|
|
|
11
11
|
_RC_IN=$(mktemp "${TMPDIR:-/tmp}/rc-edit-XXXXXX") || exit 0
|
|
12
12
|
cat > "$_RC_IN"
|
|
13
13
|
|
|
14
|
+
# 작업 카드 원장 main_edit (설계 34 §6.2, P0 기록만 — 서브에이전트 편집은 route_ledger 가 건너뛴다).
|
|
15
|
+
# 백그라운드·fail-open, 출력 없음. 부모가 연 fd 를 넘기므로 아래 rm 과 경합하지 않는다.
|
|
16
|
+
if [ "${ROUTINECODE_ROUTE_LEDGER_DISABLED:-}" != "1" ] && [ -f "$_HOOK_LIB_DIR/route_ledger.py" ]; then
|
|
17
|
+
if exec 3< "$_RC_IN" 2>/dev/null; then
|
|
18
|
+
( python3 "$_HOOK_LIB_DIR/route_ledger.py" main-edit <&3 ) >/dev/null 2>&1 &
|
|
19
|
+
exec 3<&-
|
|
20
|
+
fi
|
|
21
|
+
fi
|
|
22
|
+
|
|
14
23
|
_RC_OUT=$(ROUTINECODE_HOOK_INPUT_FILE="$_RC_IN" _HOOK_LIB_DIR="$_HOOK_LIB_DIR" python3 - <<'PYEOF' 2>/dev/null
|
|
15
24
|
import sys, os, json, hashlib, time
|
|
16
25
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/* rc-min */
|
|
3
|
-
import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{existsSync,statSync,readFileSync as a0a}from'node:fs';import{homedir}from'node:os';const GATE_LOCALES=['en','ko','ja','zh','es'];function gateLocale(){const a=process.env.ROUTINECODE_LOCALE;if(GATE_LOCALES['includes'](a))return a;try{const c=JSON['parse'](a0a(join(homedir(),'.routinecode','config.json'),'utf-8'));if(GATE_LOCALES['includes'](c['locale']))return c['locale'];}catch{}const b=(process.env.LANG||'')['split']('_')[0x0]['toLowerCase']();if(GATE_LOCALES['includes'](b))return b;return'en';}const GATE_STRINGS={'gate.mcp_degraded_design':{'en':'[design-gate]\x20MCP\x20disconnected\x20—\x20design\x20gate\x20skipped\x20(enforced\x20normally\x20in\x20connected\x20sessions).\x20Verify\x20the\x20design\x20manually.','ko':'[design-gate]\x20MCP\x20미연결\x20감지\x20—\x20설계게이트\x20생략(연결\x20세션에서는\x20정상\x20작동).\x20설계\x20검증을\x20수동으로\x20수행하세요.','ja':'[design-gate]\x20MCP未接続を検出\x20—\x20設計ゲートをスキップします(接続セッションでは通常どおり適用)。設計検証を手動で行ってください。','zh':'[design-gate]\x20检测到\x20MCP\x20未连接\x20—\x20跳过设计门禁(已连接会话中正常生效)。请手动完成设计验证。','es':'[design-gate]\x20MCP\x20desconectado\x20—\x20se\x20omite\x20la\x20puerta\x20de\x20diseño\x20(se\x20aplica\x20normalmente\x20en\x20sesiones\x20conectadas).\x20Verifica\x20el\x20diseño\x20manualmente.'},'gate.no_taskid':{'en':'[HOOK:design-gate]\x20Cannot\x20extract\x20taskId\x20from\x20implementor\x20prompt.\x20Include\x20\x22taskId:\x20<id>\x22\x20in\x20CONTEXT\x20section.','ko':'[HOOK:design-gate]\x20implementor\x20프롬프트에서\x20taskId를\x20찾을\x20수\x20없습니다.\x20CONTEXT에\x20\x22taskId:\x20<id>\x22를\x20포함하세요.','ja':'[HOOK:design-gate]\x20implementorプロンプトからtaskIdを抽出できません。CONTEXTに\x20\x22taskId:\x20<id>\x22\x20を含めてください。','zh':'[HOOK:design-gate]\x20无法从\x20implementor\x20提示中提取\x20taskId。请在\x20CONTEXT\x20中包含\x20\x22taskId:\x20<id>\x22。','es':'[HOOK:design-gate]\x20No\x20se\x20puede\x20extraer\x20taskId\x20del\x20prompt\x20del\x20implementor.\x20Incluye\x20\x22taskId:\x20<id>\x22\x20en\x20la\x20sección\x20CONTEXT.'},'gate.design_score_low':{'en':'[HOOK:design-gate]\x20Design\x20phase\x20score\x20{score}/100\x20<\x2090\x20for\x20task\x20{task_id}.\x20Reproduce\x20each\x20judge\x20deduction,\x20fix\x20the\x20design\x20and\x20run\x20judge_design\x20again\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20점수\x20{score}/100\x20<\x2090.\x20심판\x20감점을\x20재현해\x20설계를\x20고치고\x20judge_design을\x20다시\x20실행한\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計スコア\x20{score}/100\x20<\x2090。審査員の減点を再現して設計を修正し、judge_design\x20を再実行してからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计评分\x20{score}/100\x20<\x2090。请复现评审扣分并修复设计,重新运行\x20judge_design\x20后再派发\x20implementor。','es':'[HOOK:design-gate]\x20Puntuación\x20de\x20diseño\x20{score}/100\x20<\x2090\x20para\x20la\x20tarea\x20{task_id}.\x20Reproduce\x20las\x20deducciones\x20del\x20juez,\x20corrige\x20el\x20diseño\x20y\x20ejecuta\x20judge_design\x20de\x20nuevo\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.no_design_verify':{'en':'[HOOK:design-gate]\x20No\x20design\x20verification\x20found\x20for\x20task\x20{task_id}\x20(tier={tier}).\x20Run\x20judge_design\x20(score\x20>=\x2090)\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20검증이\x20없습니다\x20(tier={tier}).\x20judge_design으로\x2090점\x20이상을\x20받은\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計検証が見つかりません(tier={tier})。judge_design\x20で\x2090\x20点以上を得てからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20未找到任务\x20{task_id}\x20的设计验证(tier={tier})。请通过\x20judge_design\x20达到\x2090\x20分以上后再派发\x20implementor。','es':'[HOOK:design-gate]\x20No\x20se\x20encontró\x20verificación\x20de\x20diseño\x20para\x20la\x20tarea\x20{task_id}\x20(tier={tier}).\x20Ejecuta\x20judge_design\x20(>=\x2090)\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.design_not_judged':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20has\x20no\x20judge\x20score.\x20Run\x20judge_design.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계에\x20심판\x20채점이\x20없습니다.\x20judge_design을\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計に審査員の採点がありません。judge_design\x20を実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计没有评审评分。请运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20no\x20tiene\x20puntuación\x20del\x20juez.\x20Ejecuta\x20judge_design.'},'gate.design_stale':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20changed\x20after\x20judging.\x20Run\x20judge_design\x20again.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계가\x20심사\x20뒤에\x20바뀌었습니다.\x20judge_design을\x20다시\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計が審査後に変更されました。judge_design\x20を再実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计在评审后已更改。请重新运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20cambió\x20después\x20de\x20la\x20revisión.\x20Ejecuta\x20judge_design\x20de\x20nuevo.'},'gate.w5_high_risk':{'en':'[risk-gate]\x20{count}\x20HIGH-risk\x20file(s)\x20involved\x20(e.g.\x20{file})\x20—\x20consulting\x20reviewer\x20first\x20is\x20recommended.','ko':'[risk-gate]\x20HIGH\x20risk\x20파일\x20{count}개\x20포함(예:\x20{file})\x20—\x20reviewer\x20선행을\x20권장합니다.','ja':'[risk-gate]\x20HIGHリスクのファイルが{count}件含まれます(例:\x20{file})—\x20reviewerの事前相談を推奨します。','zh':'[risk-gate]\x20包含\x20{count}\x20个高风险文件(如\x20{file})—\x20建议先咨询\x20reviewer。','es':'[risk-gate]\x20{count}\x20archivo(s)\x20de\x20alto\x20riesgo\x20(p.\x20ej.\x20{file})\x20—\x20se\x20recomienda\x20consultar\x20primero\x20al\x20reviewer.'},'gate.w6_full_tier':{'en':'[tier-gate]\x20full-tier\x20task\x20with\x20planName=none\x20—\x20planner-first\x20is\x20recommended\x20(6+\x20file\x20scope\x20is\x20safer\x20with\x20wave\x20decomposition).','ko':'[tier-gate]\x20full\x20tier\x20태스크에\x20planName=none\x20—\x20planner\x20선행을\x20권장합니다\x20(6+\x20파일\x20범위는\x20wave\x20분해가\x20안전).','ja':'[tier-gate]\x20full\x20tierタスクでplanName=none\x20—\x20plannerの先行を推奨します(6ファイル以上はwave分解が安全)。','zh':'[tier-gate]\x20full\x20tier\x20任务且\x20planName=none\x20—\x20建议先用\x20planner(6+\x20文件范围用\x20wave\x20分解更安全)。','es':'[tier-gate]\x20Tarea\x20full-tier\x20con\x20planName=none\x20—\x20se\x20recomienda\x20usar\x20planner\x20primero\x20(ámbitos\x20de\x206+\x20archivos\x20son\x20más\x20seguros\x20con\x20descomposición\x20en\x20waves).'}};function gt(a,b={}){const c=GATE_STRINGS[a]||{};let d=c[gateLocale()]||c['en']||a;for(const [e,f]of Object['entries'](b))d=d['split']('{'+e+'}')['join'](String(f));return d;}async function readStdin(){let a='';for await(const b of process['stdin'])a+=b;return a;}function emit(a){process['stdout']['write'](JSON['stringify'](a)),process['exit'](0x0);}async function main(){let a;try{const x=await readStdin();a=JSON['parse'](x||'{}');}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const b=a['tool_input']??{},d=b['subagent_type']??'',e=typeof b['prompt']==='string'?b['prompt']:'',f=[],g=0x18*0x3c*0x3c*0x3e8;let h=![];try{const y=process.env.XDG_RUNTIME_DIR||join(homedir(),'.routinecode','run'),z=a['session_id']||'';if(z)try{const A=statSync(join(y,'sess-'+z+'.mcp'));if(Date['now']()-A['mtimeMs']<g)h=!![];}catch{}else for(const B of[join(y,'mcp-alive'),'/tmp/mcp-alive']){try{const C=statSync(B);if(Date['now']()-C['mtimeMs']<g){h=!![];break;}}catch{}}}catch{h=![];}const i=new Set(['implementor','routinecode:implementor']);if(i['has'](d)){!h&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},'systemMessage':gt('gate.mcp_degraded_design')});const D=[/taskId[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/task_id[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/TASK_ID[:\s]+['"]?([a-zA-Z0-9_-]+)/,/task[:\s]+['"]?(\d+[a-zA-Z0-9_-]*)/i];let E=null;for(const F of D){const G=F['exec'](e);if(G?.[0x1]){E=G[0x1];break;}}!E&&emit({'decision':'block','reason':gt('gate.no_taskid')});if(E){const {existsSync:H,readFileSync:I}=await import('node:fs'),{join:J}=await import('node:path'),{homedir:K}=await import('node:os'),{createHmac:L,createHash:M,timingSafeEqual:N}=await import('node:crypto'),O=process.env.ROUTINECODE_KNOWLEDGE_DIR||J(K(),'.routinecode','knowledge'),P=J(O,'verification'),Q=J(O,'classifications'),R=J(P,'design-'+E+'.json'),S=J(Q,E+'.json');let T=null;try{T=I(J(O,'attest','.key'));}catch{}const U=(W,X)=>{if(!T||typeof W!=='string'||!/^[0-9a-f]{64}$/['test'](W))return![];const Y=L('sha256',T)['update'](JSON['stringify'](X))['digest']();return N(Buffer['from'](W,'hex'),Y);};let V='standard';if(H(S))try{const W=JSON['parse'](I(S,'utf-8'));if(U(W['mac'],['classification',W['taskId'],W['tier'],W['inputsHash']]))V=W['tier']||'standard';}catch{}V==='full'&&/planName[:\s'"]*none/i['test'](e)&&f['push'](gt('gate.w6_full_tier'));if(V!=='light'){let X='none',Y=0x0;try{if(H(R)){const Z=JSON['parse'](I(R,'utf-8')),a0=[Z['phase'],Z['targetId'],Z['currentScore'],Z['passed'],!!Z['forcedPass'],Z['adjustedScore']??null,Z['scoredAt']??null,Z['changeFingerprint']??null,Z['newL1Growth']??0x0,Z['signedViolations']??0x0],a1=Z['judge']&&typeof Z['judge']==='object'?Z['judge']:null,a2=a1?U(Z['mac'],[...a0,a1['model'],a1['planPath'],a1['planSha256']]):U(Z['mac'],a0)||U(Z['mac'],a0['slice'](0x0,0x8));Y=Z['adjustedScore']??Z['currentScore']??0x0;if(!a2)X='none';else{if(process.env.ROUTINECODE_DESIGN_JUDGE==='off')X=a1?'scored':'selfscored';else{if(!a1)X='not_judged';else{let a3=null;try{a3=M('sha256')['update'](I(a1['planPath']))['digest']('hex');}catch{}X=a3===a1['planSha256']?'scored':'stale';}}}}}catch{X='none';}if(X==='none')emit({'decision':'block','reason':gt('gate.no_design_verify',{'task_id':E,'tier':V})});if(X==='not_judged')emit({'decision':'block','reason':gt('gate.design_not_judged',{'task_id':E})});if(X==='stale')emit({'decision':'block','reason':gt('gate.design_stale',{'task_id':E})});if(Y<0x5a)emit({'decision':'block','reason':gt('gate.design_score_low',{'score':Y,'task_id':E})});if(X==='selfscored')f['push']('[design-gate]\x20task\x20'+E+':\x20설계\x20심판\x20꺼짐(ROUTINECODE_DESIGN_JUDGE=off)\x20—\x20자기\x20채점\x20설계('+Y+'/100)로\x20진행(부채).');}try{const a4=J(K(),'.routinecode','knowledge','file-risk-cache.json');if(H(a4)&&!/reviewer/i['test'](e)){const a5=JSON['parse'](I(a4,'utf-8'))['scores']||{},a6=e['match'](/\/(?:[\w.@-]+\/)+[\w.@-]+\.[A-Za-z0-9]+/g)||[],a7=[];for(const a8 of a6){for(const [a9,aa]of Object['entries'](a5)){if((a9===a8||a8['endsWith'](a9)||a9['endsWith'](a8))&&aa&&typeof aa['score']==='number'&&aa['score']>=0x46){a7['push'](a8);break;}}}a7['length']>0x0&&f['push'](gt('gate.w5_high_risk',{'count':a7['length'],'file':a7[0x0]}));}}catch{}}}const l=new Set(['explorer','Explore']);!l['has'](d)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},...f['length']>0x0?{'systemMessage':f['join']('\x0a')}:{}});const n=dirname(fileURLToPath(import.meta.url)),o=resolve(n,'..','mcp-routinecode','dist','agent-tracker.js');!existsSync(o)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});let q;try{({trackSpawn:q}=await import(o));}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const r=/JUSTIFICATION:\s*([\s\S]+?)(?=\n[A-Z_]+:|$)/i['exec'](e),s=r?.[0x1]?.['trim'](),t=/INVOCATION_MODE:\s*(sequential|parallel)/i['exec'](e),u=t?.[0x1]?.['toLowerCase']()??'sequential';let w;try{w=q({'agentType':d,'parentAgent':'unknown','prompt':e,'invocationMode':u,'justification':s});}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}if(!w['accepted']){const ab=['[HOOK:pre-agent-spawn]\x20'+w['reason'],w['suggestion']?'\x0a'+w['suggestion']:'']['join']('');emit({'decision':'block','reason':ab});}emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}main()['catch'](()=>emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}}));
|
|
3
|
+
import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{existsSync,statSync,readFileSync as a0a,openSync,readSync,closeSync}from'node:fs';import{createHash as a0b}from'node:crypto';import{homedir}from'node:os';const GATE_LOCALES=['en','ko','ja','zh','es'];function gateLocale(){const a=process.env.ROUTINECODE_LOCALE;if(GATE_LOCALES['includes'](a))return a;try{const c=JSON['parse'](a0a(join(homedir(),'.routinecode','config.json'),'utf-8'));if(GATE_LOCALES['includes'](c['locale']))return c['locale'];}catch{}const b=(process.env.LANG||'')['split']('_')[0x0]['toLowerCase']();if(GATE_LOCALES['includes'](b))return b;return'en';}const GATE_STRINGS={'gate.mcp_degraded_design':{'en':'[design-gate]\x20MCP\x20disconnected\x20—\x20design\x20gate\x20skipped\x20(enforced\x20normally\x20in\x20connected\x20sessions).\x20Verify\x20the\x20design\x20manually.','ko':'[design-gate]\x20MCP\x20미연결\x20감지\x20—\x20설계게이트\x20생략(연결\x20세션에서는\x20정상\x20작동).\x20설계\x20검증을\x20수동으로\x20수행하세요.','ja':'[design-gate]\x20MCP未接続を検出\x20—\x20設計ゲートをスキップします(接続セッションでは通常どおり適用)。設計検証を手動で行ってください。','zh':'[design-gate]\x20检测到\x20MCP\x20未连接\x20—\x20跳过设计门禁(已连接会话中正常生效)。请手动完成设计验证。','es':'[design-gate]\x20MCP\x20desconectado\x20—\x20se\x20omite\x20la\x20puerta\x20de\x20diseño\x20(se\x20aplica\x20normalmente\x20en\x20sesiones\x20conectadas).\x20Verifica\x20el\x20diseño\x20manualmente.'},'gate.no_taskid':{'en':'[HOOK:design-gate]\x20Cannot\x20extract\x20taskId\x20from\x20implementor\x20prompt.\x20Include\x20\x22taskId:\x20<id>\x22\x20in\x20CONTEXT\x20section.','ko':'[HOOK:design-gate]\x20implementor\x20프롬프트에서\x20taskId를\x20찾을\x20수\x20없습니다.\x20CONTEXT에\x20\x22taskId:\x20<id>\x22를\x20포함하세요.','ja':'[HOOK:design-gate]\x20implementorプロンプトからtaskIdを抽出できません。CONTEXTに\x20\x22taskId:\x20<id>\x22\x20を含めてください。','zh':'[HOOK:design-gate]\x20无法从\x20implementor\x20提示中提取\x20taskId。请在\x20CONTEXT\x20中包含\x20\x22taskId:\x20<id>\x22。','es':'[HOOK:design-gate]\x20No\x20se\x20puede\x20extraer\x20taskId\x20del\x20prompt\x20del\x20implementor.\x20Incluye\x20\x22taskId:\x20<id>\x22\x20en\x20la\x20sección\x20CONTEXT.'},'gate.design_score_low':{'en':'[HOOK:design-gate]\x20Design\x20phase\x20score\x20{score}/100\x20<\x2090\x20for\x20task\x20{task_id}.\x20Reproduce\x20each\x20judge\x20deduction,\x20fix\x20the\x20design\x20and\x20run\x20judge_design\x20again\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20점수\x20{score}/100\x20<\x2090.\x20심판\x20감점을\x20재현해\x20설계를\x20고치고\x20judge_design을\x20다시\x20실행한\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計スコア\x20{score}/100\x20<\x2090。審査員の減点を再現して設計を修正し、judge_design\x20を再実行してからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计评分\x20{score}/100\x20<\x2090。请复现评审扣分并修复设计,重新运行\x20judge_design\x20后再派发\x20implementor。','es':'[HOOK:design-gate]\x20Puntuación\x20de\x20diseño\x20{score}/100\x20<\x2090\x20para\x20la\x20tarea\x20{task_id}.\x20Reproduce\x20las\x20deducciones\x20del\x20juez,\x20corrige\x20el\x20diseño\x20y\x20ejecuta\x20judge_design\x20de\x20nuevo\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.no_design_verify':{'en':'[HOOK:design-gate]\x20No\x20design\x20verification\x20found\x20for\x20task\x20{task_id}\x20(tier={tier}).\x20Run\x20judge_design\x20(score\x20>=\x2090)\x20before\x20spawning\x20implementor.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계\x20검증이\x20없습니다\x20(tier={tier}).\x20judge_design으로\x2090점\x20이상을\x20받은\x20뒤\x20implementor를\x20위임하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計検証が見つかりません(tier={tier})。judge_design\x20で\x2090\x20点以上を得てからimplementorを起動してください。','zh':'[HOOK:design-gate]\x20未找到任务\x20{task_id}\x20的设计验证(tier={tier})。请通过\x20judge_design\x20达到\x2090\x20分以上后再派发\x20implementor。','es':'[HOOK:design-gate]\x20No\x20se\x20encontró\x20verificación\x20de\x20diseño\x20para\x20la\x20tarea\x20{task_id}\x20(tier={tier}).\x20Ejecuta\x20judge_design\x20(>=\x2090)\x20antes\x20de\x20lanzar\x20el\x20implementor.'},'gate.design_not_judged':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20has\x20no\x20judge\x20score.\x20Run\x20judge_design.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계에\x20심판\x20채점이\x20없습니다.\x20judge_design을\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計に審査員の採点がありません。judge_design\x20を実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计没有评审评分。请运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20no\x20tiene\x20puntuación\x20del\x20juez.\x20Ejecuta\x20judge_design.'},'gate.design_stale':{'en':'[HOOK:design-gate]\x20Design\x20for\x20task\x20{task_id}\x20changed\x20after\x20judging.\x20Run\x20judge_design\x20again.','ko':'[HOOK:design-gate]\x20태스크\x20{task_id}의\x20설계가\x20심사\x20뒤에\x20바뀌었습니다.\x20judge_design을\x20다시\x20실행하세요.','ja':'[HOOK:design-gate]\x20タスク\x20{task_id}\x20の設計が審査後に変更されました。judge_design\x20を再実行してください。','zh':'[HOOK:design-gate]\x20任务\x20{task_id}\x20的设计在评审后已更改。请重新运行\x20judge_design。','es':'[HOOK:design-gate]\x20El\x20diseño\x20de\x20la\x20tarea\x20{task_id}\x20cambió\x20después\x20de\x20la\x20revisión.\x20Ejecuta\x20judge_design\x20de\x20nuevo.'},'gate.w5_high_risk':{'en':'[risk-gate]\x20{count}\x20HIGH-risk\x20file(s)\x20involved\x20(e.g.\x20{file})\x20—\x20consulting\x20reviewer\x20first\x20is\x20recommended.','ko':'[risk-gate]\x20HIGH\x20risk\x20파일\x20{count}개\x20포함(예:\x20{file})\x20—\x20reviewer\x20선행을\x20권장합니다.','ja':'[risk-gate]\x20HIGHリスクのファイルが{count}件含まれます(例:\x20{file})—\x20reviewerの事前相談を推奨します。','zh':'[risk-gate]\x20包含\x20{count}\x20个高风险文件(如\x20{file})—\x20建议先咨询\x20reviewer。','es':'[risk-gate]\x20{count}\x20archivo(s)\x20de\x20alto\x20riesgo\x20(p.\x20ej.\x20{file})\x20—\x20se\x20recomienda\x20consultar\x20primero\x20al\x20reviewer.'},'gate.w6_full_tier':{'en':'[tier-gate]\x20full-tier\x20task\x20with\x20planName=none\x20—\x20planner-first\x20is\x20recommended\x20(6+\x20file\x20scope\x20is\x20safer\x20with\x20wave\x20decomposition).','ko':'[tier-gate]\x20full\x20tier\x20태스크에\x20planName=none\x20—\x20planner\x20선행을\x20권장합니다\x20(6+\x20파일\x20범위는\x20wave\x20분해가\x20안전).','ja':'[tier-gate]\x20full\x20tierタスクでplanName=none\x20—\x20plannerの先行を推奨します(6ファイル以上はwave分解が安全)。','zh':'[tier-gate]\x20full\x20tier\x20任务且\x20planName=none\x20—\x20建议先用\x20planner(6+\x20文件范围用\x20wave\x20分解更安全)。','es':'[tier-gate]\x20Tarea\x20full-tier\x20con\x20planName=none\x20—\x20se\x20recomienda\x20usar\x20planner\x20primero\x20(ámbitos\x20de\x206+\x20archivos\x20son\x20más\x20seguros\x20con\x20descomposición\x20en\x20waves).'}};function gt(a,b={}){const c=GATE_STRINGS[a]||{};let d=c[gateLocale()]||c['en']||a;for(const [e,f]of Object['entries'](b))d=d['split']('{'+e+'}')['join'](String(f));return d;}async function readStdin(){let a='';for await(const b of process['stdin'])a+=b;return a;}const CARD_ID_LINE=/^\s*CARD_ID:[ \t]*([a-z0-9]{6,12})[ \t]*$/m;function cardGateExempt(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b)return![];const c=dirname(fileURLToPath(import.meta.url));if(/^\s*ARM:[ \t]*control[ \t]*$/m['test'](a)){let l=0.1;for(const o of[join(c,'lib','route_rules.json'),join(c,'..','hooks','lib','route_rules.json')]){try{const p=JSON['parse'](a0a(o,'utf-8'));if(p['control_ratio']!==undefined)l=Number(p['control_ratio'])||0x0;break;}catch{}}if(!(l>0x0))return![];const m=BigInt(Math['max'](0x1,Math['round'](0x1/l))),n=BigInt('0x'+a0b('sha256')['update'](b,'utf8')['digest']('hex'));return n%m===0x0n;}const d=/^\s*ESCALATED_FROM:[ \t]*([a-z0-9]{6,12})[ \t]*$/m['exec'](a)?.[0x1];if(!d||d===b||process.env.ROUTINECODE_ROUTE_LEDGER_DISABLED==='1')return![];const e=process.env.ROUTINECODE_KNOWLEDGE_DIR||join(homedir(),'.routinecode','knowledge'),f=join(e,'route-ledger.jsonl'),g=statSync(f)['size'],i=0x200*0x400,j=openSync(f,'r');let k='';try{const q=Math['max'](0x0,g-i),s=Buffer['alloc'](g-q);readSync(j,s,0x0,s['length'],q),k=s['toString']('utf-8');}finally{closeSync(j);}for(const t of k['split']('\x0a')){if(!t['includes'](d))continue;try{const u=JSON['parse'](t);if(u['ev']==='card_open'&&u['card_ref']===d)return!![];}catch{}}return![];}catch{return![];}}function riskCardInfo(a){try{const b=CARD_ID_LINE['exec'](a)?.[0x1];if(!b||!/^\s*CARD_KIND:[ \t]*risk[ \t]*$/m['test'](a))return null;const c=/^\s*(CARD_ID|CARD_KIND|GOAL|FILES|DONE|CHECK|KEEP|PLAN_REF|ARM|ESCALATED_FROM):[ \t]*(.*?)\s*$/,d=/^\s*[-*]\s+(.*?)\s*$/,e=new Set(),g=i=>{const j=/^(edit|read)\s*:\s*(.+)$/i['exec'](i);if(!j)e['add'](i);else{if(j[0x1]['toLowerCase']()==='edit')e['add'](j[0x2]['trim']());}};let h=![];for(const i of a['split']('\x0a')){const j=c['exec'](i);if(j){h=j[0x1]==='FILES';if(h&&j[0x2])g(j[0x2]);continue;}if(!h)continue;const k=d['exec'](i);if(k&&k[0x1])g(k[0x1]);else{if(i['trim']()&&!/^[ \t]/['test'](i))h=![];}}return{'id':b,'editCount':e['size']};}catch{return null;}}function emit(a){process['stdout']['write'](JSON['stringify'](a)),process['exit'](0x0);}async function main(){let a;try{const x=await readStdin();a=JSON['parse'](x||'{}');}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const b=a['tool_input']??{},d=b['subagent_type']??'',e=typeof b['prompt']==='string'?b['prompt']:'',f=[],g=0x18*0x3c*0x3c*0x3e8;let h=![];try{const y=process.env.XDG_RUNTIME_DIR||join(homedir(),'.routinecode','run'),z=a['session_id']||'';if(z)try{const A=statSync(join(y,'sess-'+z+'.mcp'));if(Date['now']()-A['mtimeMs']<g)h=!![];}catch{}else for(const B of[join(y,'mcp-alive'),'/tmp/mcp-alive']){try{const C=statSync(B);if(Date['now']()-C['mtimeMs']<g){h=!![];break;}}catch{}}}catch{h=![];}const i=new Set(['implementor','routinecode:implementor']);if(i['has'](d)){!h&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},'systemMessage':gt('gate.mcp_degraded_design')});const D=[/taskId[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/task_id[:\s]+['"]?([a-zA-Z0-9_-]+)/i,/TASK_ID[:\s]+['"]?([a-zA-Z0-9_-]+)/,/task[:\s]+['"]?(\d+[a-zA-Z0-9_-]*)/i];let E=null;for(const I of D){const J=I['exec'](e);if(J?.[0x1]){E=J[0x1];break;}}const F=cardGateExempt(e);F&&(f['push']('[design-gate]\x20작업\x20카드(대조군·승격)\x20—\x20설계\x20관문\x20면제(설계\x2034\x20P3).'),E=null);const G=F?null:riskCardInfo(e);let H=![];if(G){if(!E)E=G['id'];G['editCount']>=0x1&&G['editCount']<=0x2&&(H=!![],f['push']('[design-gate]\x20위험\x20카드\x20'+G['id']+':\x20수정\x20파일\x20'+G['editCount']+'개\x20—\x20설계\x20관문\x20면제(2파일\x20이하).\x20카드\x20리뷰는\x20그대로.'));}!E&&!F&&emit({'decision':'block','reason':gt('gate.no_taskid')});if(E){const {existsSync:K,readFileSync:L}=await import('node:fs'),{join:M}=await import('node:path'),{homedir:N}=await import('node:os'),{createHmac:O,createHash:P,timingSafeEqual:Q}=await import('node:crypto'),R=process.env.ROUTINECODE_KNOWLEDGE_DIR||M(N(),'.routinecode','knowledge'),S=M(R,'verification'),T=M(R,'classifications'),U=M(S,'design-'+E+'.json'),V=M(T,E+'.json');let W=null;try{W=L(M(R,'attest','.key'));}catch{}const X=(Z,a0)=>{if(!W||typeof Z!=='string'||!/^[0-9a-f]{64}$/['test'](Z))return![];const a1=O('sha256',W)['update'](JSON['stringify'](a0))['digest']();return Q(Buffer['from'](Z,'hex'),a1);};let Y='standard';if(K(V))try{const Z=JSON['parse'](L(V,'utf-8'));if(X(Z['mac'],['classification',Z['taskId'],Z['tier'],Z['inputsHash']]))Y=Z['tier']||'standard';}catch{}Y==='full'&&/planName[:\s'"]*none/i['test'](e)&&f['push'](gt('gate.w6_full_tier'));if(Y!=='light'&&!H){let a0='none',a1=0x0;try{if(K(U)){const a2=JSON['parse'](L(U,'utf-8')),a3=[a2['phase'],a2['targetId'],a2['currentScore'],a2['passed'],!!a2['forcedPass'],a2['adjustedScore']??null,a2['scoredAt']??null,a2['changeFingerprint']??null,a2['newL1Growth']??0x0,a2['signedViolations']??0x0],a4=a2['judge']&&typeof a2['judge']==='object'?a2['judge']:null,a5=a4?X(a2['mac'],[...a3,a4['model'],a4['planPath'],a4['planSha256']]):X(a2['mac'],a3)||X(a2['mac'],a3['slice'](0x0,0x8));a1=a2['adjustedScore']??a2['currentScore']??0x0;if(!a5)a0='none';else{if(process.env.ROUTINECODE_DESIGN_JUDGE==='off')a0=a4?'scored':'selfscored';else{if(!a4)a0='not_judged';else{let a6=null;try{a6=P('sha256')['update'](L(a4['planPath']))['digest']('hex');}catch{}a0=a6===a4['planSha256']?'scored':'stale';}}}}}catch{a0='none';}if(a0==='none')emit({'decision':'block','reason':gt('gate.no_design_verify',{'task_id':E,'tier':Y})});if(a0==='not_judged')emit({'decision':'block','reason':gt('gate.design_not_judged',{'task_id':E})});if(a0==='stale')emit({'decision':'block','reason':gt('gate.design_stale',{'task_id':E})});if(a1<0x5a)emit({'decision':'block','reason':gt('gate.design_score_low',{'score':a1,'task_id':E})});if(a0==='selfscored')f['push']('[design-gate]\x20task\x20'+E+':\x20설계\x20심판\x20꺼짐(ROUTINECODE_DESIGN_JUDGE=off)\x20—\x20자기\x20채점\x20설계('+a1+'/100)로\x20진행(부채).');}try{const a7=M(N(),'.routinecode','knowledge','file-risk-cache.json');if(K(a7)&&!/reviewer/i['test'](e)){const a8=JSON['parse'](L(a7,'utf-8'))['scores']||{},a9=e['match'](/\/(?:[\w.@-]+\/)+[\w.@-]+\.[A-Za-z0-9]+/g)||[],aa=[];for(const ab of a9){for(const [ac,ad]of Object['entries'](a8)){if((ac===ab||ab['endsWith'](ac)||ac['endsWith'](ab))&&ad&&typeof ad['score']==='number'&&ad['score']>=0x46){aa['push'](ab);break;}}}aa['length']>0x0&&f['push'](gt('gate.w5_high_risk',{'count':aa['length'],'file':aa[0x0]}));}}catch{}}}const l=new Set(['explorer','Explore']);!l['has'](d)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'},...f['length']>0x0?{'systemMessage':f['join']('\x0a')}:{}});const n=dirname(fileURLToPath(import.meta.url)),o=resolve(n,'..','mcp-routinecode','dist','agent-tracker.js');!existsSync(o)&&emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});let q;try{({trackSpawn:q}=await import(o));}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}const r=/JUSTIFICATION:\s*([\s\S]+?)(?=\n[A-Z_]+:|$)/i['exec'](e),s=r?.[0x1]?.['trim'](),t=/INVOCATION_MODE:\s*(sequential|parallel)/i['exec'](e),u=t?.[0x1]?.['toLowerCase']()??'sequential';let w;try{w=q({'agentType':d,'parentAgent':'unknown','prompt':e,'invocationMode':u,'justification':s});}catch{emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}if(!w['accepted']){const ae=['[HOOK:pre-agent-spawn]\x20'+w['reason'],w['suggestion']?'\x0a'+w['suggestion']:'']['join']('');emit({'decision':'block','reason':ae});}emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}});}main()['catch'](()=>emit({'hookSpecificOutput':{'hookEventName':'PreToolUse','permissionDecision':'allow'}}));
|
package/hooks/pre-agent-spawn.sh
CHANGED
|
@@ -30,8 +30,22 @@ if [ ! -f "$NODE_SCRIPT" ]; then
|
|
|
30
30
|
fi
|
|
31
31
|
|
|
32
32
|
INPUT=$(cat)
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
# 설계 34 P2 — implementor-lite 카드 관문(lib/card_gate.py): CARD_ID 필수·risk 는 Opus·대조군(§6.3) 재배정.
|
|
34
|
+
# implementor-lite 가 아니면 출력이 없어 아래 판정 그대로. 오류 = 출력 없음(fail-open). 끄기 ROUTINECODE_CARD_GATE=off.
|
|
35
|
+
CARD_OUT=""
|
|
36
|
+
case "$INPUT" in
|
|
37
|
+
*implementor-lite*)
|
|
38
|
+
if command -v python3 >/dev/null 2>&1 && [ -f "$HERE/lib/card_gate.py" ]; then
|
|
39
|
+
CARD_OUT=$(printf '%s' "$INPUT" | python3 "$HERE/lib/card_gate.py" agent-pre 2>/dev/null)
|
|
40
|
+
fi ;;
|
|
41
|
+
esac
|
|
42
|
+
if [ -n "$CARD_OUT" ]; then
|
|
43
|
+
OUT="$CARD_OUT"
|
|
44
|
+
RC=0
|
|
45
|
+
else
|
|
46
|
+
OUT=$(printf '%s' "$INPUT" | node "$NODE_SCRIPT")
|
|
47
|
+
RC=$?
|
|
48
|
+
fi
|
|
35
49
|
printf '%s' "$OUT"
|
|
36
50
|
|
|
37
51
|
# 오케스트레이션 판단 기록 (docs/지식체계/35 §1·36 §8): 통과 → decided delegate, 차단 → decided block + outcome blocked.
|
|
@@ -40,4 +54,10 @@ ORCH_LIB="$HERE/lib/orch_decision.py"
|
|
|
40
54
|
if [ -f "$ORCH_LIB" ] && command -v python3 >/dev/null 2>&1; then
|
|
41
55
|
( printf '%s' "$INPUT" | ORCH_HOOK_OUTPUT="$OUT" python3 "$ORCH_LIB" agent-pre ) >/dev/null 2>&1 &
|
|
42
56
|
fi
|
|
57
|
+
# 작업 카드 원장 card_open (설계 34 §6.2, P0 기록만). 백그라운드·fail-open, 결정·출력에 영향 없음.
|
|
58
|
+
ROUTE_LIB="$HERE/lib/route_ledger.py"
|
|
59
|
+
# 카드 관문이 거절한 호출(실행되지 않는다)은 card_open 을 쓰지 않는다 — card_gate 가 card_reject·control_redirect 로 남겼다.
|
|
60
|
+
if [ -z "$CARD_OUT" ] && [ "${ROUTINECODE_ROUTE_LEDGER_DISABLED:-}" != "1" ] && [ -f "$ROUTE_LIB" ] && command -v python3 >/dev/null 2>&1; then
|
|
61
|
+
( printf '%s' "$INPUT" | python3 "$ROUTE_LIB" agent-pre ) >/dev/null 2>&1 &
|
|
62
|
+
fi
|
|
43
63
|
exit $RC
|
package/hooks/pre-bash-guard.sh
CHANGED
|
@@ -69,6 +69,28 @@ if core_banned:
|
|
|
69
69
|
reason = t('secret.bash_pattern_block', rule=display_rule)
|
|
70
70
|
emit({'decision': 'block', 'reason': reason})
|
|
71
71
|
|
|
72
|
+
# 설계 34 P1 — ops-lite 운영 작업자 전용 허용목록(lib/ops_guard.py, 규칙 = lib/route_rules.json "ops").
|
|
73
|
+
# ops-lite 가 아니면(메인·다른 에이전트) None → 아래 판정 그대로. 모듈을 못 읽으면 ops-lite 만 차단(fail-closed).
|
|
74
|
+
try:
|
|
75
|
+
import ops_guard as _og
|
|
76
|
+
_ov = _og.check_hook(inp, cmd)
|
|
77
|
+
except Exception:
|
|
78
|
+
_ov = ('internal_error', '[RoutineCode ops-lite] 허용목록 가드를 불러오지 못해 차단했다.') \
|
|
79
|
+
if 'ops-lite' in str(inp.get('agent_type') or '') else None
|
|
80
|
+
if _ov:
|
|
81
|
+
emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny',
|
|
82
|
+
'permissionDecisionReason': _ov[1]}})
|
|
83
|
+
|
|
84
|
+
# 설계 34 P2 F5 — implementor-lite 경로 정정(lib/card_gate.py): 없는 경로인데 저장소 안 같은 이름이 1개면 정정 경로로 deny.
|
|
85
|
+
# implementor-lite 가 아니면 None → 아래 판정 그대로. 오류 = 관여 안 함(fail-open). 끄기 ROUTINECODE_CARD_GATE=off.
|
|
86
|
+
try:
|
|
87
|
+
import card_gate as _cgt
|
|
88
|
+
_pf = _cgt.path_fix(inp) if _cgt.enabled() else None
|
|
89
|
+
except Exception:
|
|
90
|
+
_pf = None
|
|
91
|
+
if _pf:
|
|
92
|
+
emit(_pf)
|
|
93
|
+
|
|
72
94
|
# 형상 결정 보조 가드(설계 11 §3.4) — config-map 데이터 쓰기·결정 명령(approve/reject/defer/baseline)·TTY 위조 deny.
|
|
73
95
|
# 훅은 AI 도구 호출에만 걸린다(사용자 터미널 직접 실행 무영향). 모듈 오류는 통과(fail-open).
|
|
74
96
|
try:
|
|
@@ -22,9 +22,16 @@ try:
|
|
|
22
22
|
if not isinstance(cmd, str) or not cmd.strip():
|
|
23
23
|
emit({"continue": True})
|
|
24
24
|
sys.path.insert(0, os.environ.get('_HOOK_LIB_DIR', ''))
|
|
25
|
+
# zsh 글롭 교정 — 기존 지식 가드보다 먼저 본다. deny + 교정 명령만 쓴다(allow/ask/updatedInput 금지).
|
|
26
|
+
import command_fix
|
|
27
|
+
fx = command_fix.fix_command(cmd)
|
|
28
|
+
if fx:
|
|
29
|
+
fixed = fx[0]
|
|
30
|
+
emit({"continue": True, "hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
31
|
+
"permissionDecisionReason": "[RoutineCode] zsh 글롭 교정: 따옴표 없는 글롭은 zsh 에서 일치 파일이 없으면 명령 전체가 실행되지 않습니다. 다음 명령으로 다시 실행하세요:\n" + fixed}})
|
|
25
32
|
import knowledge_items as ki
|
|
26
33
|
sid = inp.get('session_id') or 'unknown'
|
|
27
|
-
g = ki.command_guard(cmd, session_id=sid)
|
|
34
|
+
g = ki.command_guard(cmd, session_id=sid, cwd=inp.get('cwd'))
|
|
28
35
|
if not g:
|
|
29
36
|
emit({"continue": True})
|
|
30
37
|
if g['deny']:
|
|
@@ -32,7 +39,10 @@ try:
|
|
|
32
39
|
ki.record_exposure({'items': items, 'seed': None}, sid, 'guard:bash')
|
|
33
40
|
ki.flush_background()
|
|
34
41
|
lines = [ki.render_line(it) for it in items]
|
|
35
|
-
|
|
42
|
+
head = '[RoutineCode] 팀이 승인한 규칙에 걸린 명령입니다.'
|
|
43
|
+
if g.get('promoted') and all(it.get('kid') in g['promoted'] for it in items):
|
|
44
|
+
head = '[RoutineCode] 이 명령은 과거에 반복해서 실패했습니다. 아래를 확인하고 맞게 고쳐 다시 실행하세요:'
|
|
45
|
+
reason = head + '\n' + '\n'.join(lines)
|
|
36
46
|
emit({"continue": True, "hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
37
47
|
"permissionDecisionReason": reason}})
|
|
38
48
|
sel = g['warn']
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# PreToolUse hook: Edit | Write | MultiEdit | Bash — 설계 34 §5.4 P4 1단계(경고만, 차단 없음)
|
|
3
|
+
# 메인 세션이 코드 파일을 직접 편집하거나 빌드·테스트·ssh/docker/rsync 를 직접 돌리면
|
|
4
|
+
# "작업 카드로 위임하라" 경고를 파일(편집)·종류(Bash)마다 세션당 1회 내고 원장에 ev=main_nudge 를 남긴다.
|
|
5
|
+
# 판정은 hooks/lib/delegate_nudge.py. 서브에이전트·문서·.routinecode/·스크래치패드는 조용히 통과.
|
|
6
|
+
# 출력은 경고할 때만(permissionDecision 없음 — 다른 PreToolUse 훅 판정에 영향 없음). 오류 = 출력 없음(fail-open).
|
|
7
|
+
# 끄기: ROUTINECODE_DELEGATE_NUDGE=off
|
|
8
|
+
|
|
9
|
+
[ "${ROUTINECODE_DELEGATE_NUDGE:-}" = "off" ] && exit 0
|
|
10
|
+
LIB="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)/delegate_nudge.py"
|
|
11
|
+
[ -f "$LIB" ] || exit 0
|
|
12
|
+
command -v python3 >/dev/null 2>&1 || exit 0
|
|
13
|
+
|
|
14
|
+
python3 "$LIB" pre-tool 2>/dev/null
|
|
15
|
+
exit 0
|
package/hooks/pre-edit-guard.sh
CHANGED
|
@@ -67,6 +67,16 @@ except Exception:
|
|
|
67
67
|
if _cg_reason:
|
|
68
68
|
emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': _cg_reason}})
|
|
69
69
|
|
|
70
|
+
# 설계 34 P2 F5 — implementor-lite 경로 정정(lib/card_gate.py): 없는 경로인데 저장소 안 같은 이름이 1개면 정정 경로로 deny.
|
|
71
|
+
# implementor-lite 가 아니면 None → 아래 판정 그대로. 오류 = 관여 안 함(fail-open). 끄기 ROUTINECODE_CARD_GATE=off.
|
|
72
|
+
try:
|
|
73
|
+
import card_gate as _cgt
|
|
74
|
+
_pf = _cgt.path_fix(inp) if _cgt.enabled() else None
|
|
75
|
+
except Exception:
|
|
76
|
+
_pf = None
|
|
77
|
+
if _pf:
|
|
78
|
+
emit(_pf)
|
|
79
|
+
|
|
70
80
|
# secret 스캔 비활성(kill-switch)은 CORE 통과 후에만.
|
|
71
81
|
if sf.is_disabled():
|
|
72
82
|
emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow'}})
|
package/hooks/pre-read-guard.sh
CHANGED
|
@@ -69,6 +69,16 @@ if core_banned:
|
|
|
69
69
|
reason = t('secret.read_block', path=file_path, rule=display_rule)
|
|
70
70
|
emit({'decision': 'block', 'reason': reason})
|
|
71
71
|
|
|
72
|
+
# 설계 34 P2 F5 — implementor-lite 경로 정정(lib/card_gate.py): 없는 경로인데 저장소 안 같은 이름이 1개면 정정 경로로 deny.
|
|
73
|
+
# implementor-lite 가 아니면 None → 아래 판정 그대로. 오류 = 관여 안 함(fail-open). 끄기 ROUTINECODE_CARD_GATE=off.
|
|
74
|
+
try:
|
|
75
|
+
import card_gate as _cgt
|
|
76
|
+
_pf = _cgt.path_fix(inp) if _cgt.enabled() else None
|
|
77
|
+
except Exception:
|
|
78
|
+
_pf = None
|
|
79
|
+
if _pf:
|
|
80
|
+
emit(_pf)
|
|
81
|
+
|
|
72
82
|
# secret 스캔 비활성(디버그 kill-switch)은 CORE 통과 후에만 적용.
|
|
73
83
|
if sf.is_disabled():
|
|
74
84
|
emit({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'permissionDecision': 'allow'}})
|
package/hooks/session-start.sh
CHANGED
|
@@ -107,6 +107,12 @@ if [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ -f "$HOOKS_DIR/pending-drainer.sh
|
|
|
107
107
|
nohup bash "$HOOKS_DIR/pending-drainer.sh" >/dev/null 2>&1 &
|
|
108
108
|
fi
|
|
109
109
|
|
|
110
|
+
# --- 지식 재고 주간 자동 점검 (설계 36-2 C3, 백그라운드 비블로킹) ---
|
|
111
|
+
# 7일 도장(계정 stock-auto.stamp) 안이면 즉시 끝난다. 실패해도 세션 무영향. 헤드리스 러너 세션에서는 띄우지 않는다.
|
|
112
|
+
if [ "${ROUTINECODE_RECORDER:-}" != "1" ] && [ "${ROUTINECODE_ARCHITECT:-}" != "1" ] && [ "${ROUTINECODE_MAINTENANCE:-}" != "1" ]; then
|
|
113
|
+
nohup python3 "$HOOKS_DIR/lib/knowledge_stock.py" --auto </dev/null >/dev/null 2>&1 &
|
|
114
|
+
fi
|
|
115
|
+
|
|
110
116
|
# --- 0. Hook 자체 건강성 검증 + 자동 복구 (순수 bash, 외부 의존 없음) ---
|
|
111
117
|
PRISTINE_DIR="$HOME/.routinecode/pristine/hooks"
|
|
112
118
|
CRITICAL_HOOKS="pre-credit-guard.sh pre-edit-check.sh pre-agent-spawn.sh pre-webfetch-guard.sh pre-secret-guard.sh"
|
|
@@ -21,6 +21,12 @@ fi
|
|
|
21
21
|
|
|
22
22
|
HOOKS_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
23
23
|
|
|
24
|
+
# 순정 Opus 대비 절감 증분 계산(설계 35 A10): 무음·백그라운드·15초 제한, 실패해도 세션에 영향 없음. LLM·네트워크 0.
|
|
25
|
+
if command -v node >/dev/null 2>&1 && [ -f "$HOOKS_DIR/../bin/rc-savings.js" ]; then
|
|
26
|
+
# 계산이 끝나면 숫자만 기존 usage 경로로 내보낸다(savings_calc, 30분 간격·같은 값 생략 — 설계 35 A13).
|
|
27
|
+
( { node "$HOOKS_DIR/../bin/rc-savings.js" --quiet --budget-ms 15000; python3 "$HOOKS_DIR/lib/savings_emit.py"; } >/dev/null 2>&1 & ) 2>/dev/null
|
|
28
|
+
fi
|
|
29
|
+
|
|
24
30
|
ROUTINECODE_HOOK_INPUT="$INPUT" ROUTINECODE_HOOKS_DIR="$HOOKS_DIR" python3 - <<'PYEOF'
|
|
25
31
|
import sys, json, os, time
|
|
26
32
|
from datetime import datetime, timezone
|
|
@@ -7,8 +7,37 @@
|
|
|
7
7
|
#
|
|
8
8
|
# 환경변수: ROUTINECODE_USAGE_METRICS_DISABLED=1 → skip
|
|
9
9
|
|
|
10
|
+
_HOOK_LIB_DIR="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)"
|
|
11
|
+
_RC_IN=""
|
|
12
|
+
|
|
13
|
+
# 작업 카드 원장 card_close (설계 34 §6.2, P0 기록만). 입력을 임시 파일로 받아 백그라운드로 처리하고 지운다.
|
|
14
|
+
# 계측 끔(ROUTINECODE_USAGE_METRICS_DISABLED)과 별개 — 끄기는 ROUTINECODE_ROUTE_LEDGER_DISABLED=1.
|
|
15
|
+
if [ "${ROUTINECODE_ROUTE_LEDGER_DISABLED:-}" != "1" ] && [ -n "$_HOOK_LIB_DIR" ] && [ -f "$_HOOK_LIB_DIR/route_ledger.py" ]; then
|
|
16
|
+
_RC_IN=$(mktemp "${TMPDIR:-/tmp}/rc-route-XXXXXX" 2>/dev/null) || _RC_IN=""
|
|
17
|
+
if [ -n "$_RC_IN" ]; then
|
|
18
|
+
cat > "$_RC_IN" 2>/dev/null
|
|
19
|
+
# 부모가 연 fd 를 넘긴다 — 아래에서 임시 파일을 지워도 백그라운드는 끝까지 읽는다.
|
|
20
|
+
if exec 3< "$_RC_IN" 2>/dev/null; then
|
|
21
|
+
( python3 "$_HOOK_LIB_DIR/route_ledger.py" subagent-stop <&3 ) >/dev/null 2>&1 &
|
|
22
|
+
exec 3<&-
|
|
23
|
+
fi
|
|
24
|
+
fi
|
|
25
|
+
fi
|
|
26
|
+
trap '[ -n "$_RC_IN" ] && rm -f "$_RC_IN"' EXIT
|
|
27
|
+
|
|
28
|
+
# 설계 34 P2 — implementor-lite 완료 관문 G1~G4·보고 블록, reviewer 카드 판정 기록(lib/card_gate.py).
|
|
29
|
+
# implementor-lite 가 아니면 출력 없음 → 응답은 그대로 {"continue":true}. 관문 실패면 {"decision":"block"} 으로 작업자를 계속시킨다
|
|
30
|
+
# (카드당 2회까지). 원장 입력 파일이 있을 때만(원장 끔 = 관문 끔). 오류 = 출력 없음(fail-open). 끄기 ROUTINECODE_CARD_GATE=off.
|
|
31
|
+
_RC_GATE=""
|
|
32
|
+
if [ -n "$_RC_IN" ] && [ -f "$_HOOK_LIB_DIR/card_gate.py" ] && [ "${ROUTINECODE_CARD_GATE:-on}" != "off" ]; then
|
|
33
|
+
_RC_GATE=$(python3 "$_HOOK_LIB_DIR/card_gate.py" subagent-stop < "$_RC_IN" 2>/dev/null)
|
|
34
|
+
fi
|
|
35
|
+
_rc_reply() {
|
|
36
|
+
if [ -n "$_RC_GATE" ]; then printf '%s\n' "$_RC_GATE"; else echo '{"continue":true}'; fi
|
|
37
|
+
}
|
|
38
|
+
|
|
10
39
|
if [ "${ROUTINECODE_USAGE_METRICS_DISABLED}" = "1" ]; then
|
|
11
|
-
|
|
40
|
+
_rc_reply
|
|
12
41
|
exit 0
|
|
13
42
|
fi
|
|
14
43
|
|
|
@@ -16,10 +45,13 @@ RC_RUNDIR="${XDG_RUNTIME_DIR:-$HOME/.routinecode/run}"
|
|
|
16
45
|
if ! mkdir -p "$RC_RUNDIR" 2>/dev/null; then RC_RUNDIR="/tmp"; else chmod 700 "$RC_RUNDIR" 2>/dev/null; fi
|
|
17
46
|
export RC_RUNDIR
|
|
18
47
|
|
|
19
|
-
_HOOK_LIB_DIR="$(cd "$(dirname "$0")/lib" 2>/dev/null && pwd)"
|
|
20
48
|
if [ -n "$_HOOK_LIB_DIR" ]; then
|
|
21
|
-
|
|
49
|
+
if [ -n "$_RC_IN" ]; then
|
|
50
|
+
python3 "$_HOOK_LIB_DIR/usage_v2.py" subagent-stop < "$_RC_IN" >/dev/null 2>&1 || true
|
|
51
|
+
else
|
|
52
|
+
python3 "$_HOOK_LIB_DIR/usage_v2.py" subagent-stop >/dev/null 2>&1 || true
|
|
53
|
+
fi
|
|
22
54
|
fi
|
|
23
55
|
|
|
24
|
-
|
|
56
|
+
_rc_reply
|
|
25
57
|
exit 0
|