@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,690 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""오케스트레이션 판단 2단계 기록 — docs/지식체계/35 §1·36 §8 (S7, CLI 쪽).
|
|
3
|
+
|
|
4
|
+
decided(상황·고른 것·근거·확신도) → outcome(결과) 를 계정 디렉터리의 로컬 버퍼
|
|
5
|
+
knowledge/<계정>/decisions.pending.jsonl 에 쌓고, flush() 가 지식 서버
|
|
6
|
+
POST {serverUrl}/api/v1/knowledge/decisions 로 ≤100 건씩 보낸다. 서버가 정본이다(35 §1 규칙 5).
|
|
7
|
+
|
|
8
|
+
지키는 것:
|
|
9
|
+
- 표준 라이브러리만, Python 3.9. 어떤 실패도 예외를 올리지 않는다(훅은 계속 exit 0, fail-open).
|
|
10
|
+
- 핫 경로(decided·outcome)는 로컬 파일 추가만. 네트워크는 flush_background()가 띄운 별도 프로세스에서만.
|
|
11
|
+
- context·choice·result 는 범주형 사실만(에이전트 종류·등급·개수·크기 구간·레포 이름).
|
|
12
|
+
짧은 원시값만 남기고 경로·줄바꿈이 든 문자열은 버린다 — 프롬프트·파일 내용·레포 밖 경로는 절대 담지 않는다.
|
|
13
|
+
- 계정 공간이 없으면(knowledge_scope.account() 의 tenantId 없음) 기록하지 않는다.
|
|
14
|
+
디렉터리 이름은 mcp-intelligence/src/knowledge-record.ts accountDirName 과 같다(팀 't-<id>', 개인 'p-<id>').
|
|
15
|
+
- 버퍼 파일은 2 MB 상한, 넘으면 오래된 줄부터 버린다. 전송 실패는 다음 flush 에서 다시 보낸다.
|
|
16
|
+
- API 키는 출력·로그에 남기지 않는다.
|
|
17
|
+
|
|
18
|
+
CLI: python3 orch_decision.py --flush → 쌓인 기록 전송(백그라운드 프로세스용)
|
|
19
|
+
"""
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
import time
|
|
25
|
+
import uuid
|
|
26
|
+
|
|
27
|
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
28
|
+
if HERE not in sys.path:
|
|
29
|
+
sys.path.insert(0, HERE)
|
|
30
|
+
|
|
31
|
+
PENDING_NAME = 'decisions.pending.jsonl'
|
|
32
|
+
MAP_NAME = 'decisions.map.json'
|
|
33
|
+
LOCK_NAME = 'decisions.lock'
|
|
34
|
+
FLUSH_LOCK_NAME = 'decisions.flush.lock'
|
|
35
|
+
FLUSH_STAMP = 'decisions.flush-at'
|
|
36
|
+
MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
37
|
+
BATCH_MAX = 100
|
|
38
|
+
MAX_BATCHES_PER_FLUSH = 10
|
|
39
|
+
FLUSH_MIN_INTERVAL_S = 30
|
|
40
|
+
MAP_MAX_ENTRIES = 500
|
|
41
|
+
MAP_TTL_S = 8 * 24 * 3600
|
|
42
|
+
TIMEOUT_S = 5
|
|
43
|
+
ENDPOINT = '/api/v1/knowledge/decisions'
|
|
44
|
+
|
|
45
|
+
DECISION_KINDS = ('delegate', 'verify_depth', 'ask', 'stop', 'block', 'explore')
|
|
46
|
+
|
|
47
|
+
_KEY_RE = re.compile(r'^[A-Za-z][A-Za-z0-9_]{0,39}$')
|
|
48
|
+
_MAX_KEYS = 20
|
|
49
|
+
_MAX_STR = 64
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ── 경로·계정 ────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
def knowledge_base():
|
|
55
|
+
return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(
|
|
56
|
+
os.path.expanduser('~'), '.routinecode', 'knowledge')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def account_dir_name(acct):
|
|
60
|
+
"""accountDirName(knowledge-record.ts) 와 같은 규칙. 계정 공간이 없으면 None."""
|
|
61
|
+
try:
|
|
62
|
+
if not acct or not acct.get('tenantId'):
|
|
63
|
+
return None
|
|
64
|
+
return '%s-%s' % ('t' if acct.get('kind') == 'team' else 'p', acct.get('tenantId'))
|
|
65
|
+
except Exception:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def account_dir(acct=None):
|
|
70
|
+
"""knowledge/<계정>/ 경로(필요하면 만든다). 계정 공간이 없으면 None."""
|
|
71
|
+
try:
|
|
72
|
+
if acct is None:
|
|
73
|
+
import knowledge_scope
|
|
74
|
+
acct = knowledge_scope.account()
|
|
75
|
+
name = account_dir_name(acct)
|
|
76
|
+
if not name:
|
|
77
|
+
return None
|
|
78
|
+
d = os.path.join(knowledge_base(), name)
|
|
79
|
+
os.makedirs(d, exist_ok=True)
|
|
80
|
+
return d
|
|
81
|
+
except Exception:
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ── 내용 거르기(범주형 사실만) ──────────────────────────────────
|
|
86
|
+
|
|
87
|
+
def _small_value(v):
|
|
88
|
+
if v is None or isinstance(v, bool):
|
|
89
|
+
return True, v
|
|
90
|
+
if isinstance(v, (int, float)):
|
|
91
|
+
return True, v
|
|
92
|
+
if isinstance(v, str):
|
|
93
|
+
s = v.strip()
|
|
94
|
+
if not s or len(s) > _MAX_STR or '/' in s or '\\' in s or '\n' in s or '\r' in s:
|
|
95
|
+
return False, None
|
|
96
|
+
return True, s
|
|
97
|
+
return False, None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def categorical(obj):
|
|
101
|
+
"""dict → 키 규칙·짧은 원시값만 남긴 dict(최대 20키). 그 밖은 버린다."""
|
|
102
|
+
out = {}
|
|
103
|
+
if not isinstance(obj, dict):
|
|
104
|
+
return out
|
|
105
|
+
for k, v in obj.items():
|
|
106
|
+
if len(out) >= _MAX_KEYS:
|
|
107
|
+
break
|
|
108
|
+
if not isinstance(k, str) or not _KEY_RE.match(k):
|
|
109
|
+
continue
|
|
110
|
+
ok, val = _small_value(v)
|
|
111
|
+
if ok:
|
|
112
|
+
out[k] = val
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def size_bucket(n):
|
|
117
|
+
"""길이·개수를 구간으로(원값 대신)."""
|
|
118
|
+
try:
|
|
119
|
+
n = int(n)
|
|
120
|
+
except Exception:
|
|
121
|
+
return 'unknown'
|
|
122
|
+
if n <= 0:
|
|
123
|
+
return '0'
|
|
124
|
+
if n < 500:
|
|
125
|
+
return 'xs'
|
|
126
|
+
if n < 2000:
|
|
127
|
+
return 's'
|
|
128
|
+
if n < 8000:
|
|
129
|
+
return 'm'
|
|
130
|
+
if n < 20000:
|
|
131
|
+
return 'l'
|
|
132
|
+
return 'xl'
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def repo_name(cwd=None):
|
|
136
|
+
"""레포 이름만(경로 아님)."""
|
|
137
|
+
try:
|
|
138
|
+
p = cwd or os.environ.get('CLAUDE_PROJECT_DIR') or os.getcwd()
|
|
139
|
+
name = os.path.basename(os.path.normpath(p))
|
|
140
|
+
ok, val = _small_value(name)
|
|
141
|
+
return val if ok else None
|
|
142
|
+
except Exception:
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ── 잠금·파일 ────────────────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
class _Lock(object):
|
|
149
|
+
def __init__(self, d, blocking=True, name=LOCK_NAME):
|
|
150
|
+
self.path = os.path.join(d, name)
|
|
151
|
+
self.blocking = blocking
|
|
152
|
+
self.fh = None
|
|
153
|
+
self.ok = False
|
|
154
|
+
|
|
155
|
+
def __enter__(self):
|
|
156
|
+
try:
|
|
157
|
+
import fcntl
|
|
158
|
+
self.fh = open(self.path, 'a')
|
|
159
|
+
flags = fcntl.LOCK_EX | (0 if self.blocking else fcntl.LOCK_NB)
|
|
160
|
+
fcntl.flock(self.fh.fileno(), flags)
|
|
161
|
+
self.ok = True
|
|
162
|
+
except Exception:
|
|
163
|
+
# 잠금 실패: 비차단(flush)은 건너뛰고, 차단(추가)은 잠금 없이 진행한다(fail-open).
|
|
164
|
+
self.ok = False
|
|
165
|
+
return self
|
|
166
|
+
|
|
167
|
+
def __exit__(self, *a):
|
|
168
|
+
try:
|
|
169
|
+
if self.fh:
|
|
170
|
+
import fcntl
|
|
171
|
+
fcntl.flock(self.fh.fileno(), fcntl.LOCK_UN)
|
|
172
|
+
self.fh.close()
|
|
173
|
+
except Exception:
|
|
174
|
+
pass
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _read_lines(path):
|
|
179
|
+
try:
|
|
180
|
+
with open(path, 'r', encoding='utf-8') as f:
|
|
181
|
+
return [ln for ln in f.read().split('\n') if ln.strip()]
|
|
182
|
+
except Exception:
|
|
183
|
+
return []
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _write_lines(path, lines):
|
|
187
|
+
tmp = path + '.tmp'
|
|
188
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
189
|
+
for ln in lines:
|
|
190
|
+
f.write(ln + '\n')
|
|
191
|
+
os.replace(tmp, path)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _cap_file(path, max_bytes=MAX_FILE_BYTES):
|
|
195
|
+
"""상한을 넘으면 오래된 줄부터 버린다(최근 것 보존)."""
|
|
196
|
+
try:
|
|
197
|
+
if os.path.getsize(path) <= max_bytes:
|
|
198
|
+
return
|
|
199
|
+
lines = _read_lines(path)
|
|
200
|
+
kept = []
|
|
201
|
+
total = 0
|
|
202
|
+
for ln in reversed(lines):
|
|
203
|
+
b = len(ln.encode('utf-8')) + 1
|
|
204
|
+
if total + b > max_bytes:
|
|
205
|
+
break
|
|
206
|
+
kept.append(ln)
|
|
207
|
+
total += b
|
|
208
|
+
kept.reverse()
|
|
209
|
+
_write_lines(path, kept)
|
|
210
|
+
except Exception:
|
|
211
|
+
pass
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _append(d, record):
|
|
215
|
+
path = os.path.join(d, PENDING_NAME)
|
|
216
|
+
line = json.dumps(record, ensure_ascii=False, separators=(',', ':'))
|
|
217
|
+
with _Lock(d):
|
|
218
|
+
with open(path, 'a', encoding='utf-8') as f:
|
|
219
|
+
f.write(line + '\n')
|
|
220
|
+
_cap_file(path)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ── 기록 ─────────────────────────────────────────────────────
|
|
224
|
+
|
|
225
|
+
def decided(kind, context=None, choice=None, evidence_ids=None, confidence=None, seed=None, acct=None):
|
|
226
|
+
"""decided 1건을 버퍼에 추가하고 decisionId(uuid4)를 돌려준다. 기록하지 못하면 None."""
|
|
227
|
+
try:
|
|
228
|
+
if kind not in DECISION_KINDS:
|
|
229
|
+
return None
|
|
230
|
+
d = account_dir(acct)
|
|
231
|
+
if not d:
|
|
232
|
+
return None
|
|
233
|
+
did = str(uuid.uuid4())
|
|
234
|
+
rec = {
|
|
235
|
+
'phase': 'decided', 'decisionId': did, 'decisionKind': kind,
|
|
236
|
+
'context': categorical(context or {}), 'choice': categorical(choice or {}),
|
|
237
|
+
'at': int(time.time()),
|
|
238
|
+
}
|
|
239
|
+
ev = [e for e in (evidence_ids or []) if isinstance(e, (int, str)) and not isinstance(e, bool)
|
|
240
|
+
and (not isinstance(e, str) or (len(e) <= 200 and '/' not in e))][:50]
|
|
241
|
+
if ev:
|
|
242
|
+
rec['evidenceIds'] = ev
|
|
243
|
+
if isinstance(confidence, (int, float)) and not isinstance(confidence, bool) and 0 <= confidence <= 1:
|
|
244
|
+
rec['confidence'] = float(confidence)
|
|
245
|
+
if isinstance(seed, (str, int)) and not isinstance(seed, bool):
|
|
246
|
+
rec['seed'] = str(seed)[:100]
|
|
247
|
+
_append(d, rec)
|
|
248
|
+
return did
|
|
249
|
+
except Exception:
|
|
250
|
+
return None
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def outcome(decision_id, result, kind=None, acct=None):
|
|
254
|
+
"""decided 에 짝지은 outcome 1건을 버퍼에 추가. 성공하면 True."""
|
|
255
|
+
try:
|
|
256
|
+
if not decision_id or not isinstance(decision_id, str) or len(decision_id) > 100:
|
|
257
|
+
return False
|
|
258
|
+
d = account_dir(acct)
|
|
259
|
+
if not d:
|
|
260
|
+
return False
|
|
261
|
+
if kind is None:
|
|
262
|
+
kind = _kind_from_pending(d, decision_id)
|
|
263
|
+
if kind not in DECISION_KINDS:
|
|
264
|
+
return False
|
|
265
|
+
res = categorical(result or {})
|
|
266
|
+
if not res:
|
|
267
|
+
res = {'status': 'unknown'}
|
|
268
|
+
_append(d, {'phase': 'outcome', 'decisionId': decision_id, 'decisionKind': kind,
|
|
269
|
+
'result': res, 'at': int(time.time())})
|
|
270
|
+
return True
|
|
271
|
+
except Exception:
|
|
272
|
+
return False
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _kind_from_pending(d, decision_id):
|
|
276
|
+
for ln in reversed(_read_lines(os.path.join(d, PENDING_NAME))):
|
|
277
|
+
try:
|
|
278
|
+
r = json.loads(ln)
|
|
279
|
+
if r.get('decisionId') == decision_id and r.get('phase') == 'decided':
|
|
280
|
+
return r.get('decisionKind')
|
|
281
|
+
except Exception:
|
|
282
|
+
continue
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# ── 상관 표(세션 id + tool_use id 등 → decisionId) ─────────────────
|
|
287
|
+
|
|
288
|
+
def _map_path(d):
|
|
289
|
+
return os.path.join(d, MAP_NAME)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _load_map(d):
|
|
293
|
+
try:
|
|
294
|
+
with open(_map_path(d), 'r', encoding='utf-8') as f:
|
|
295
|
+
m = json.load(f)
|
|
296
|
+
return m if isinstance(m, dict) else {}
|
|
297
|
+
except Exception:
|
|
298
|
+
return {}
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _save_map(d, m):
|
|
302
|
+
now = time.time()
|
|
303
|
+
items = [(k, v) for k, v in m.items() if isinstance(v, dict) and now - float(v.get('at', 0)) < MAP_TTL_S]
|
|
304
|
+
items.sort(key=lambda kv: kv[1].get('at', 0))
|
|
305
|
+
items = items[-MAP_MAX_ENTRIES:]
|
|
306
|
+
tmp = _map_path(d) + '.tmp'
|
|
307
|
+
with open(tmp, 'w', encoding='utf-8') as f:
|
|
308
|
+
json.dump(dict(items), f)
|
|
309
|
+
os.replace(tmp, _map_path(d))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def map_key(*parts):
|
|
313
|
+
"""상관 키. 자유 문장(issueId 등)이 섞일 수 있어 해시로만 남긴다."""
|
|
314
|
+
import hashlib
|
|
315
|
+
raw = '\x1f'.join(str(p) for p in parts)
|
|
316
|
+
return hashlib.sha1(raw.encode('utf-8', 'replace')).hexdigest()[:24]
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def remember(key, decision_id, kind, acct=None):
|
|
320
|
+
try:
|
|
321
|
+
d = account_dir(acct)
|
|
322
|
+
if not d or not decision_id:
|
|
323
|
+
return False
|
|
324
|
+
with _Lock(d):
|
|
325
|
+
m = _load_map(d)
|
|
326
|
+
m[key] = {'id': decision_id, 'kind': kind, 'at': time.time()}
|
|
327
|
+
_save_map(d, m)
|
|
328
|
+
return True
|
|
329
|
+
except Exception:
|
|
330
|
+
return False
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def take(key, acct=None):
|
|
334
|
+
"""상관 표에서 꺼내고 지운다. {'id','kind'} 또는 None."""
|
|
335
|
+
try:
|
|
336
|
+
d = account_dir(acct)
|
|
337
|
+
if not d:
|
|
338
|
+
return None
|
|
339
|
+
with _Lock(d):
|
|
340
|
+
m = _load_map(d)
|
|
341
|
+
v = m.pop(key, None)
|
|
342
|
+
if v is not None:
|
|
343
|
+
_save_map(d, m)
|
|
344
|
+
return v if isinstance(v, dict) else None
|
|
345
|
+
except Exception:
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
# ── 전송 ─────────────────────────────────────────────────────
|
|
350
|
+
|
|
351
|
+
def _sync_config():
|
|
352
|
+
"""기존 동기화와 같은 출처: ~/.routinecode/config.json 의 serverUrl·apiKey(환경변수 폴백).
|
|
353
|
+
mcp-intelligence 의 knowledge 동기화 허용 조건(syncEnabled·knowledgeSyncDisabled·loggedOut)을 따른다."""
|
|
354
|
+
try:
|
|
355
|
+
import knowledge_scope
|
|
356
|
+
path = knowledge_scope.config_path()
|
|
357
|
+
with open(path) as f:
|
|
358
|
+
c = json.load(f)
|
|
359
|
+
if not isinstance(c, dict):
|
|
360
|
+
c = {}
|
|
361
|
+
except Exception:
|
|
362
|
+
c = {}
|
|
363
|
+
base = c.get('serverUrl') or os.environ.get('ROUTINECODE_SERVER_URL', '')
|
|
364
|
+
key = c.get('apiKey') or os.environ.get('ROUTINECODE_API_KEY', '')
|
|
365
|
+
enabled = (c.get('syncEnabled') is True or (not c and bool(key))) \
|
|
366
|
+
and c.get('knowledgeSyncDisabled') is not True and c.get('loggedOut') is not True
|
|
367
|
+
return (base.rstrip('/') if base else ''), key, enabled
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _wire(rec):
|
|
371
|
+
out = {k: v for k, v in rec.items() if k != 'at'}
|
|
372
|
+
return out
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _post(base, key, records):
|
|
376
|
+
"""(status, body dict). 네트워크 실패는 (0, {})."""
|
|
377
|
+
import urllib.request
|
|
378
|
+
import urllib.error
|
|
379
|
+
data = json.dumps({'records': records}).encode('utf-8')
|
|
380
|
+
req = urllib.request.Request(base + ENDPOINT, data=data, method='POST', headers={
|
|
381
|
+
'Content-Type': 'application/json',
|
|
382
|
+
'Authorization': 'Bearer ' + key,
|
|
383
|
+
})
|
|
384
|
+
try:
|
|
385
|
+
resp = urllib.request.urlopen(req, timeout=TIMEOUT_S)
|
|
386
|
+
body = resp.read().decode('utf-8', 'replace')
|
|
387
|
+
try:
|
|
388
|
+
return resp.status, json.loads(body or '{}')
|
|
389
|
+
except Exception:
|
|
390
|
+
return resp.status, {}
|
|
391
|
+
except urllib.error.HTTPError as e:
|
|
392
|
+
try:
|
|
393
|
+
return e.code, json.loads(e.read().decode('utf-8', 'replace') or '{}')
|
|
394
|
+
except Exception:
|
|
395
|
+
return e.code, {}
|
|
396
|
+
except Exception:
|
|
397
|
+
return 0, {}
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _remove_sent(path, sent_lines):
|
|
401
|
+
"""앞에서 보낸 줄을 지운다(그 사이 추가된 줄은 보존)."""
|
|
402
|
+
want = {}
|
|
403
|
+
for ln in sent_lines:
|
|
404
|
+
want[ln] = want.get(ln, 0) + 1
|
|
405
|
+
rest = []
|
|
406
|
+
for ln in _read_lines(path):
|
|
407
|
+
if want.get(ln, 0) > 0:
|
|
408
|
+
want[ln] -= 1
|
|
409
|
+
continue
|
|
410
|
+
rest.append(ln)
|
|
411
|
+
_write_lines(path, rest)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def flush(acct=None, post=None):
|
|
415
|
+
"""버퍼를 ≤100 건씩 보낸다. 결과 {'sent','dropped','status'}. 실패한 묶음은 남겨 다음에 다시 보낸다.
|
|
416
|
+
400(INVALID_DECISION)은 다시 보내도 받지 않으므로 버린다. post 는 테스트 주입용."""
|
|
417
|
+
out = {'sent': 0, 'dropped': 0, 'status': 'idle'}
|
|
418
|
+
try:
|
|
419
|
+
d = account_dir(acct)
|
|
420
|
+
if not d:
|
|
421
|
+
out['status'] = 'skip:no-account'
|
|
422
|
+
return out
|
|
423
|
+
base, key, enabled = _sync_config()
|
|
424
|
+
if post is None:
|
|
425
|
+
if not enabled or not base or not key:
|
|
426
|
+
out['status'] = 'skip:no-sync'
|
|
427
|
+
return out
|
|
428
|
+
post = lambda recs: _post(base, key, recs) # noqa: E731
|
|
429
|
+
path = os.path.join(d, PENDING_NAME)
|
|
430
|
+
# 전송자는 하나만(비차단 flush 잠금). 데이터 잠금은 읽기·다시 쓰기 동안만 잡는다 —
|
|
431
|
+
# 네트워크 대기 중에 훅의 추가(_append)가 막히지 않게 한다.
|
|
432
|
+
with _Lock(d, blocking=False, name=FLUSH_LOCK_NAME) as lk:
|
|
433
|
+
if not lk.ok:
|
|
434
|
+
out['status'] = 'skip:busy'
|
|
435
|
+
return out
|
|
436
|
+
for _ in range(MAX_BATCHES_PER_FLUSH):
|
|
437
|
+
with _Lock(d):
|
|
438
|
+
lines = _read_lines(path)[:BATCH_MAX]
|
|
439
|
+
if not lines:
|
|
440
|
+
break
|
|
441
|
+
recs = []
|
|
442
|
+
bad = []
|
|
443
|
+
for ln in lines:
|
|
444
|
+
try:
|
|
445
|
+
recs.append(_wire(json.loads(ln)))
|
|
446
|
+
except Exception:
|
|
447
|
+
bad.append(ln)
|
|
448
|
+
status, _body = post(recs) if recs else (200, {})
|
|
449
|
+
if status == 200:
|
|
450
|
+
with _Lock(d):
|
|
451
|
+
_remove_sent(path, lines)
|
|
452
|
+
out['sent'] += len(recs)
|
|
453
|
+
out['dropped'] += len(bad)
|
|
454
|
+
out['status'] = 'ok'
|
|
455
|
+
elif status == 400:
|
|
456
|
+
with _Lock(d):
|
|
457
|
+
_remove_sent(path, lines)
|
|
458
|
+
out['dropped'] += len(lines)
|
|
459
|
+
out['status'] = 'dropped:invalid'
|
|
460
|
+
else:
|
|
461
|
+
if bad:
|
|
462
|
+
with _Lock(d):
|
|
463
|
+
_remove_sent(path, bad)
|
|
464
|
+
out['status'] = 'retry:%s' % status
|
|
465
|
+
break
|
|
466
|
+
return out
|
|
467
|
+
except Exception as e:
|
|
468
|
+
out['status'] = 'error:%s' % type(e).__name__
|
|
469
|
+
return out
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def flush_background(acct=None):
|
|
473
|
+
"""쌓인 것이 있으면 별도 프로세스로 flush(훅을 막지 않는다). 30초에 한 번까지."""
|
|
474
|
+
try:
|
|
475
|
+
d = account_dir(acct)
|
|
476
|
+
if not d:
|
|
477
|
+
return False
|
|
478
|
+
path = os.path.join(d, PENDING_NAME)
|
|
479
|
+
if not os.path.exists(path) or os.path.getsize(path) == 0:
|
|
480
|
+
return False
|
|
481
|
+
stamp = os.path.join(d, FLUSH_STAMP)
|
|
482
|
+
try:
|
|
483
|
+
if time.time() - os.path.getmtime(stamp) < FLUSH_MIN_INTERVAL_S:
|
|
484
|
+
return False
|
|
485
|
+
except Exception:
|
|
486
|
+
pass
|
|
487
|
+
with open(stamp, 'w') as f:
|
|
488
|
+
f.write(str(int(time.time())))
|
|
489
|
+
import subprocess
|
|
490
|
+
devnull = open(os.devnull, 'wb')
|
|
491
|
+
subprocess.Popen([sys.executable or 'python3', os.path.abspath(__file__), '--flush'],
|
|
492
|
+
stdin=subprocess.DEVNULL, stdout=devnull, stderr=devnull,
|
|
493
|
+
start_new_session=True, close_fds=True)
|
|
494
|
+
return True
|
|
495
|
+
except Exception:
|
|
496
|
+
return False
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
# ── 훅 입구 ───────────────────────────────────────────────────
|
|
500
|
+
|
|
501
|
+
IMPLEMENTOR_LIKE = ('implementor', 'routinecode:implementor')
|
|
502
|
+
EXPLORER_LIKE = ('explorer', 'Explore', 'routinecode:explorer')
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _agent_key(inp):
|
|
506
|
+
return map_key('agent', inp.get('session_id') or '', inp.get('tool_use_id') or '')
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _is_denied(hook_output):
|
|
510
|
+
try:
|
|
511
|
+
o = json.loads(hook_output or '{}')
|
|
512
|
+
except Exception:
|
|
513
|
+
return False
|
|
514
|
+
if not isinstance(o, dict):
|
|
515
|
+
return False
|
|
516
|
+
if o.get('decision') == 'block':
|
|
517
|
+
return True
|
|
518
|
+
hso = o.get('hookSpecificOutput')
|
|
519
|
+
return isinstance(hso, dict) and hso.get('permissionDecision') == 'deny'
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def on_agent_pre(inp, hook_output, acct=None):
|
|
523
|
+
"""pre-agent-spawn: 통과 → decided delegate(상관 표에 기억), 차단 → decided block + 즉시 outcome blocked."""
|
|
524
|
+
try:
|
|
525
|
+
ti = inp.get('tool_input') or {}
|
|
526
|
+
if not isinstance(ti, dict):
|
|
527
|
+
ti = {}
|
|
528
|
+
agent_type = ti.get('subagent_type') or 'general-purpose'
|
|
529
|
+
prompt = ti.get('prompt') if isinstance(ti.get('prompt'), str) else ''
|
|
530
|
+
m = re.search(r'INVOCATION_MODE:\s*(sequential|parallel)', prompt, re.I)
|
|
531
|
+
mode = m.group(1).lower() if m else ('background' if ti.get('run_in_background') else 'sequential')
|
|
532
|
+
ctx = {'promptLen': size_bucket(len(prompt)), 'repo': repo_name()}
|
|
533
|
+
choice = {'agentType': agent_type, 'mode': mode}
|
|
534
|
+
if _is_denied(hook_output):
|
|
535
|
+
gate = 'design_gate' if agent_type in IMPLEMENTOR_LIKE else (
|
|
536
|
+
'explorer_rate' if agent_type in EXPLORER_LIKE else 'other')
|
|
537
|
+
ctx['gate'] = gate
|
|
538
|
+
did = decided('block', ctx, choice, acct=acct)
|
|
539
|
+
if did:
|
|
540
|
+
outcome(did, {'status': 'blocked'}, 'block', acct=acct)
|
|
541
|
+
return did
|
|
542
|
+
did = decided('delegate', ctx, choice, acct=acct)
|
|
543
|
+
if did:
|
|
544
|
+
remember(_agent_key(inp), did, 'delegate', acct=acct)
|
|
545
|
+
return did
|
|
546
|
+
except Exception:
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def on_agent_post(inp, status, tool_calls=None, tokens=None, acct=None):
|
|
551
|
+
"""post-agent-return: 짝지은 delegate 의 outcome. 짝이 없으면 아무것도 하지 않는다."""
|
|
552
|
+
try:
|
|
553
|
+
v = take(_agent_key(inp), acct=acct)
|
|
554
|
+
if not v:
|
|
555
|
+
return False
|
|
556
|
+
res = {'status': status if status in ('success', 'error') else 'unknown'}
|
|
557
|
+
if isinstance(tool_calls, int) and not isinstance(tool_calls, bool):
|
|
558
|
+
res['toolCalls'] = tool_calls
|
|
559
|
+
if isinstance(tokens, int) and not isinstance(tokens, bool):
|
|
560
|
+
res['tokens'] = tokens
|
|
561
|
+
return outcome(v.get('id'), res, v.get('kind') or 'delegate', acct=acct)
|
|
562
|
+
except Exception:
|
|
563
|
+
return False
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _mcp_json(resp):
|
|
567
|
+
"""MCP 도구 응답(content[{type:'text', text:'<json>'}] 등)에서 JSON dict 를 꺼낸다."""
|
|
568
|
+
try:
|
|
569
|
+
if isinstance(resp, str):
|
|
570
|
+
try:
|
|
571
|
+
o = json.loads(resp)
|
|
572
|
+
except Exception:
|
|
573
|
+
return {}
|
|
574
|
+
return _mcp_json(o) if not isinstance(o, dict) or 'content' in o else o
|
|
575
|
+
if isinstance(resp, list):
|
|
576
|
+
for it in resp:
|
|
577
|
+
if isinstance(it, dict) and isinstance(it.get('text'), str):
|
|
578
|
+
try:
|
|
579
|
+
o = json.loads(it['text'])
|
|
580
|
+
if isinstance(o, dict):
|
|
581
|
+
return o
|
|
582
|
+
except Exception:
|
|
583
|
+
continue
|
|
584
|
+
return {}
|
|
585
|
+
if isinstance(resp, dict):
|
|
586
|
+
if 'content' in resp:
|
|
587
|
+
return _mcp_json(resp.get('content'))
|
|
588
|
+
return resp
|
|
589
|
+
except Exception:
|
|
590
|
+
pass
|
|
591
|
+
return {}
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
_CATEGORY_RE = re.compile(r'^[a-z][a-z_-]{0,19}$')
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def on_orch_tool(inp, acct=None):
|
|
598
|
+
"""post-orch-decision: classify_task → verify_depth decided, auto_score → 그 outcome,
|
|
599
|
+
record_attempt(shouldEscalate) → stop decided, record_attempt success·clear_attempts → stop outcome."""
|
|
600
|
+
try:
|
|
601
|
+
name = str(inp.get('tool_name') or '')
|
|
602
|
+
tool = name.rsplit('__', 1)[-1]
|
|
603
|
+
ti = inp.get('tool_input') or {}
|
|
604
|
+
if not isinstance(ti, dict):
|
|
605
|
+
ti = {}
|
|
606
|
+
resp = _mcp_json(inp.get('tool_response'))
|
|
607
|
+
if tool == 'classify_task':
|
|
608
|
+
task_id = ti.get('taskId')
|
|
609
|
+
tier = resp.get('tier')
|
|
610
|
+
if not task_id or tier not in ('light', 'standard', 'full'):
|
|
611
|
+
return None
|
|
612
|
+
ctx = {'fileCount': ti.get('fileCount') if isinstance(ti.get('fileCount'), int) else None,
|
|
613
|
+
'hasApiQa': bool(ti.get('hasApiQa')), 'hasUiQa': bool(ti.get('hasUiQa')),
|
|
614
|
+
'repo': repo_name()}
|
|
615
|
+
cat = ti.get('category')
|
|
616
|
+
if isinstance(cat, str) and _CATEGORY_RE.match(cat):
|
|
617
|
+
ctx['category'] = cat
|
|
618
|
+
did = decided('verify_depth', ctx, {'tier': tier}, acct=acct)
|
|
619
|
+
if did:
|
|
620
|
+
remember(map_key('task', task_id), did, 'verify_depth', acct=acct)
|
|
621
|
+
return did
|
|
622
|
+
if tool == 'auto_score':
|
|
623
|
+
task_id = ti.get('taskId')
|
|
624
|
+
if not task_id:
|
|
625
|
+
return None
|
|
626
|
+
v = take(map_key('task', task_id), acct=acct)
|
|
627
|
+
if not v:
|
|
628
|
+
return None
|
|
629
|
+
score = resp.get('currentScore', resp.get('score'))
|
|
630
|
+
res = {'status': 'scored', 'passed': bool(resp.get('passed'))}
|
|
631
|
+
if isinstance(score, (int, float)) and not isinstance(score, bool):
|
|
632
|
+
res['score'] = score
|
|
633
|
+
return outcome(v.get('id'), res, 'verify_depth', acct=acct)
|
|
634
|
+
if tool == 'record_attempt':
|
|
635
|
+
issue = ti.get('issueId')
|
|
636
|
+
if not issue:
|
|
637
|
+
return None
|
|
638
|
+
key = map_key('stop', issue)
|
|
639
|
+
if resp.get('shouldEscalate') is True:
|
|
640
|
+
attempt_n = resp.get('attemptNumber')
|
|
641
|
+
did = decided('stop', {'attempts': attempt_n if isinstance(attempt_n, int) else None,
|
|
642
|
+
'repo': repo_name()}, {'action': 'escalate'}, acct=acct)
|
|
643
|
+
if did:
|
|
644
|
+
remember(key, did, 'stop', acct=acct)
|
|
645
|
+
return did
|
|
646
|
+
if ti.get('result') == 'success':
|
|
647
|
+
v = take(key, acct=acct)
|
|
648
|
+
if v:
|
|
649
|
+
return outcome(v.get('id'), {'status': 'resolved', 'by': 'attempt_success'}, 'stop', acct=acct)
|
|
650
|
+
return None
|
|
651
|
+
if tool == 'clear_attempts':
|
|
652
|
+
issue = ti.get('issueId')
|
|
653
|
+
if not issue:
|
|
654
|
+
return None
|
|
655
|
+
v = take(map_key('stop', issue), acct=acct)
|
|
656
|
+
if v:
|
|
657
|
+
return outcome(v.get('id'), {'status': 'cleared', 'by': 'clear_attempts'}, 'stop', acct=acct)
|
|
658
|
+
return None
|
|
659
|
+
return None
|
|
660
|
+
except Exception:
|
|
661
|
+
return None
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _read_stdin_json():
|
|
665
|
+
try:
|
|
666
|
+
o = json.loads(sys.stdin.read() or '{}')
|
|
667
|
+
return o if isinstance(o, dict) else {}
|
|
668
|
+
except Exception:
|
|
669
|
+
return {}
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def main(argv):
|
|
673
|
+
try:
|
|
674
|
+
if '--flush' in argv:
|
|
675
|
+
flush()
|
|
676
|
+
return 0
|
|
677
|
+
if 'agent-pre' in argv:
|
|
678
|
+
on_agent_pre(_read_stdin_json(), os.environ.get('ORCH_HOOK_OUTPUT', ''))
|
|
679
|
+
return 0
|
|
680
|
+
if 'orch-tool' in argv:
|
|
681
|
+
on_orch_tool(_read_stdin_json())
|
|
682
|
+
flush_background()
|
|
683
|
+
return 0
|
|
684
|
+
except Exception:
|
|
685
|
+
pass
|
|
686
|
+
return 0
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
if __name__ == '__main__':
|
|
690
|
+
sys.exit(main(sys.argv[1:]))
|