@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,412 @@
|
|
|
1
|
+
"""완료 주장의 구조와 확인 질문 판정 — 설계 27 T2·T3.
|
|
2
|
+
|
|
3
|
+
stop-claim-check.v3 가 이미 고른 '주장 문장(영역, 문장)'을 받아
|
|
4
|
+
extract(sentence) → 대상(target)·범위(scope)·극성(polarity)
|
|
5
|
+
turn_activity(entries, start, end) → 이번 턴의 실행(명령·성공 여부·시각)과 편집 시각
|
|
6
|
+
judge(domain, claim, activity, ...) → 확인 질문 답: 'yes' | 'no' | 'unknown' + 이유 키
|
|
7
|
+
를 돌려준다. 판정은 실행 기록 대조만 한다 — LLM 호출·자기 점수 없음(C3).
|
|
8
|
+
질문 표는 데이터(hooks/claim-questions.json). 출력 문구에 질문 id·규칙 이름을 넣지 않는다(C6).
|
|
9
|
+
|
|
10
|
+
켜기: ROUTINECODE_CLAIM_CQ=on 일 때만 v3 가 이 모듈을 쓴다(라벨 표본 측정 전 기본값 변경 금지).
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
|
|
17
|
+
from evidence import normalize_mcp_tool_name # 같은 lib 디렉터리(v3 가 sys.path 에 넣는다)
|
|
18
|
+
|
|
19
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
20
|
+
QUESTIONS_PATH = os.path.join(os.path.dirname(_HERE), 'claim-questions.json')
|
|
21
|
+
|
|
22
|
+
# ─── 극성: 결정·비선택 서술은 완료 주장이 아니다 (§0.1 오탐 유형 1) ───
|
|
23
|
+
_DECISION_PATTERNS = [re.compile(p, re.IGNORECASE) for p in [
|
|
24
|
+
r'(하|쓰|넣|올리|배포하|푸시하|커밋하|만들|진행하)지\s*않기로',
|
|
25
|
+
r'안\s*(하|쓰|올리)기로',
|
|
26
|
+
r'않기로\s*(했|결정|정했)',
|
|
27
|
+
r'보류(했|하기로|합니다|중)',
|
|
28
|
+
r'(제외|생략)하기로',
|
|
29
|
+
r'\bdecided\s+(not\s+to|against)\b',
|
|
30
|
+
r'\bchose\s+not\s+to\b',
|
|
31
|
+
r'\b(skipped|deferred|on\s+hold)\b',
|
|
32
|
+
]]
|
|
33
|
+
# 약한 결정 표지 — 완료 신호와 같은 절에 있으면 결정이 아니다('Pushed to main instead of the feature branch').
|
|
34
|
+
# 완료 신호가 없는 절에서만 결정 표지로 센다(재현율 보존).
|
|
35
|
+
_WEAK_DECISION_PATTERNS = [re.compile(p, re.IGNORECASE) for p in [
|
|
36
|
+
r"\b(will\s+not|won't|won’t|did\s+not|didn't|didn’t)\b",
|
|
37
|
+
r'\binstead\s+of\b',
|
|
38
|
+
]]
|
|
39
|
+
|
|
40
|
+
# ─── 범위 표지 (Toulmin 한정어) ───
|
|
41
|
+
_SCOPE_PATTERNS = {
|
|
42
|
+
'local': re.compile(r'로컬|\blocal(ly)?\b', re.IGNORECASE),
|
|
43
|
+
'staging': re.compile(r'스테이징|\bstaging\b|\bdev\s+server\b', re.IGNORECASE),
|
|
44
|
+
'partial': re.compile(r'일부|부분|\bpartial(ly)?\b|\bsome\s+of\b', re.IGNORECASE),
|
|
45
|
+
'only': re.compile(r'[가-힣]만\b|\bonly\b', re.IGNORECASE),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
# ─── 대상: 경로·하이픈 이름(서비스·패키지·브랜치) ───
|
|
49
|
+
# ASCII 문자 클래스만 — \w 는 한글을 포함해 'x.ts를' 처럼 조사를 삼키거나(경로) 'auth-backend를' 을 놓친다(이름).
|
|
50
|
+
# 이름 뒤에 한글 조사(를·에·은·로·의 …)가 바로 붙어도 된다.
|
|
51
|
+
_PATH_RE = re.compile(r'(?<![A-Za-z0-9_@])(?:\.{0,2}/)?(?:[A-Za-z0-9_@.-]+/)+[A-Za-z0-9_.@-]+')
|
|
52
|
+
_HYPHEN_NAME_RE = re.compile(r'(?<![A-Za-z0-9_/.-])[a-z][a-z0-9]*(?:-[a-z0-9]+){1,5}(?![A-Za-z0-9_/-])')
|
|
53
|
+
_NOT_TARGET = re.compile(r'^(\d|v\d)|^(e-mail|follow-up|end-to-end|step-by-step|re-run|built-in|opt-in|opt-out|read-only|real-time|on-call)$', re.IGNORECASE)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# 완료 신호 — 한 절에 이것이 있고 결정 표지가 없으면 그 문장은 완료 주장이다.
|
|
57
|
+
# 정본 = v3 와 같은 hooks/lib/anchors.json 의 locales.*.completion(전 로케일). 영역 동사의 과거형처럼
|
|
58
|
+
# anchors 에 없는 절 단위 보강만 claim-questions.json 의 clause_completion_extra 에 둔다(복제 없음).
|
|
59
|
+
def _build_completion():
|
|
60
|
+
pats = []
|
|
61
|
+
try:
|
|
62
|
+
with open(os.path.join(_HERE, 'anchors.json'), encoding='utf-8') as f:
|
|
63
|
+
locs = (json.load(f).get('locales') or {})
|
|
64
|
+
for loc in locs.values():
|
|
65
|
+
if isinstance(loc, dict):
|
|
66
|
+
pats.extend(p for p in (loc.get('completion') or []) if isinstance(p, str) and p and not p.endswith('$'))
|
|
67
|
+
except Exception:
|
|
68
|
+
pass
|
|
69
|
+
try:
|
|
70
|
+
with open(QUESTIONS_PATH, encoding='utf-8') as f:
|
|
71
|
+
pats.extend(json.load(f).get('clause_completion_extra') or [])
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
ok = []
|
|
75
|
+
for p in pats:
|
|
76
|
+
try:
|
|
77
|
+
re.compile(p)
|
|
78
|
+
ok.append('(?:%s)' % p)
|
|
79
|
+
except re.error:
|
|
80
|
+
continue
|
|
81
|
+
return re.compile('|'.join(ok) if ok else r'(?!x)x', re.IGNORECASE)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
_COMPLETION = _build_completion()
|
|
85
|
+
# 절 경계 — 쉼표·세미콜론·마침표, 영어 접속사, 한국어 연결 어미 '고'
|
|
86
|
+
_CLAUSE_SPLIT = re.compile(r'[,;.。]|\s+(?:and|but|while|so)\s+|(?<=고)\s+', re.IGNORECASE)
|
|
87
|
+
# 파일로 보이는 대상(확장자) — 빌드·테스트는 파일이 아니라 패키지를 돌린다
|
|
88
|
+
_FILE_LIKE = re.compile(r'\.[A-Za-z0-9]{1,6}$')
|
|
89
|
+
_GENERIC_DIRS = {'src', 'lib', 'app', 'apps', 'components', 'hooks', 'test', 'tests', 'pages', 'utils', 'routes', 'api', 'e2e', 'scripts', 'packages', 'dist'}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _polarity(s):
|
|
93
|
+
"""절 단위 극성 — 완료 신호가 있는 절 중 하나라도 결정 표지가 없으면 assert, 결정 표지만 있으면 decision"""
|
|
94
|
+
clauses = [c for c in _CLAUSE_SPLIT.split(s) if c and c.strip()] or [s]
|
|
95
|
+
has_decision = False
|
|
96
|
+
for c in clauses:
|
|
97
|
+
done = bool(_COMPLETION.search(c))
|
|
98
|
+
dec = any(p.search(c) for p in _DECISION_PATTERNS) or (not done and any(p.search(c) for p in _WEAK_DECISION_PATTERNS))
|
|
99
|
+
has_decision = has_decision or dec
|
|
100
|
+
if not dec and done:
|
|
101
|
+
return 'assert'
|
|
102
|
+
return 'decision' if has_decision else 'assert'
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def extract(sentence):
|
|
106
|
+
"""문장 → {'target': str|None, 'scope': [..], 'polarity': 'assert'|'decision'}"""
|
|
107
|
+
s = sentence or ''
|
|
108
|
+
polarity = _polarity(s)
|
|
109
|
+
scope = [k for k, r in _SCOPE_PATTERNS.items() if r.search(s)]
|
|
110
|
+
target = None
|
|
111
|
+
m = _PATH_RE.search(s)
|
|
112
|
+
if m and not re.match(r'^\d+/\d+', m.group(0)):
|
|
113
|
+
target = m.group(0).strip('./')
|
|
114
|
+
else:
|
|
115
|
+
for h in _HYPHEN_NAME_RE.finditer(s):
|
|
116
|
+
if not _NOT_TARGET.search(h.group(0)):
|
|
117
|
+
target = h.group(0)
|
|
118
|
+
break
|
|
119
|
+
return {'target': target, 'scope': scope, 'polarity': polarity}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _ts(entry):
|
|
123
|
+
v = entry.get('timestamp') or ''
|
|
124
|
+
try:
|
|
125
|
+
return datetime.fromisoformat(v.replace('Z', '+00:00')).timestamp() if v else 0.0
|
|
126
|
+
except Exception:
|
|
127
|
+
return 0.0
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _result_text(block):
|
|
131
|
+
bc = block.get('content', '')
|
|
132
|
+
if isinstance(bc, str):
|
|
133
|
+
return bc
|
|
134
|
+
out = ''
|
|
135
|
+
if isinstance(bc, list):
|
|
136
|
+
for x in bc:
|
|
137
|
+
if isinstance(x, dict) and x.get('type') == 'text':
|
|
138
|
+
out += (x.get('text') or '') + '\n'
|
|
139
|
+
return out
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _norm_tool(name):
|
|
143
|
+
# 정본 = evidence.normalize_mcp_tool_name (v3 증거 수집과 같은 정규화 — 복제하지 않는다)
|
|
144
|
+
return normalize_mcp_tool_name(name) or ''
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
_EXIT_FAIL = re.compile(r'Exit code [1-9]\d*')
|
|
148
|
+
# 파이프(| tail 등)로 종료 코드가 가려져도 출력에 남는 실패 표지 — 빌드·테스트 실행기 공통
|
|
149
|
+
_OUTPUT_FAIL = re.compile(
|
|
150
|
+
r'\berror TS\d+|\bFound [1-9]\d* errors?\b|npm ERR!|ERR_PNPM_|^\s*FAIL\s|\bTests?:?\s+[1-9]\d* failed\b|\b[1-9]\d* (?:failed|failing)\b'
|
|
151
|
+
r'|Failed to compile|Build failed|Compilation failed|Traceback \(most recent call last\)|^error(?:\[E\d+\])?:|\bELIFECYCLE\b|# fail [1-9]',
|
|
152
|
+
re.IGNORECASE | re.MULTILINE)
|
|
153
|
+
_PIPED = re.compile(r'\|(?!\|)')
|
|
154
|
+
_MCP_FAIL = re.compile(r'"success"\s*:\s*false|"passed"\s*:\s*false')
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
_CD_RE = re.compile(r'\s*cd\s+("([^"]+)"|\'([^\']+)\'|([^\s;&|]+))')
|
|
158
|
+
_GIT_C_RE = re.compile(r'\bgit\s+-C\s+("([^"]+)"|\'([^\']+)\'|(\S+))')
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _join_dir(base, d):
|
|
162
|
+
if not d or d.startswith('/') or d.startswith('~') or not base:
|
|
163
|
+
return d
|
|
164
|
+
return os.path.normpath(os.path.join(base, d))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _bash_dir(cmd, cwd):
|
|
168
|
+
"""(이 명령의 실행 위치, 다음 명령에 이어질 작업 폴더). 앞머리 cd 는 이어지고, git -C 는 이 명령에만 적용."""
|
|
169
|
+
d = cwd
|
|
170
|
+
m = _CD_RE.match(cmd or '')
|
|
171
|
+
if m:
|
|
172
|
+
# 이 명령의 위치는 cd 인자 그대로(상대 경로는 편집 경로 부분 일치로 덮는다 — 같은 상대 cd 반복을 이중으로 잇지 않음),
|
|
173
|
+
# 다음 명령에 이어질 폴더만 앞 폴더에 잇는다
|
|
174
|
+
d = m.group(2) or m.group(3) or m.group(4) or ''
|
|
175
|
+
cwd = _join_dir(cwd, d)
|
|
176
|
+
g = _GIT_C_RE.search(cmd or '')
|
|
177
|
+
if g:
|
|
178
|
+
d = _join_dir(d, g.group(2) or g.group(3) or g.group(4) or '')
|
|
179
|
+
return d, cwd
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _fail_sig(text):
|
|
183
|
+
"""실패 출력 → 오류 서명(정본: error_line 머리 줄 + normalize_sig). 못 뽑으면 None."""
|
|
184
|
+
try:
|
|
185
|
+
from error_line import error_line
|
|
186
|
+
from normalize_sig import sig_of
|
|
187
|
+
line = error_line(text or '', fallback=True)
|
|
188
|
+
return sig_of(line) if line else None
|
|
189
|
+
except Exception:
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def turn_activity(entries, start_idx, end_idx):
|
|
194
|
+
"""이번 턴(start_idx..end_idx)의 실행·편집.
|
|
195
|
+
|
|
196
|
+
runs = [{'tool','cmd','ok','ts','dir'}] — Bash 명령 / MCP 도구(projectDir 를 dir 로)
|
|
197
|
+
edits = [{'path','ts'}] — Edit·Write·NotebookEdit
|
|
198
|
+
"""
|
|
199
|
+
start = max(0, start_idx if start_idx is not None and start_idx >= 0 else end_idx - 50)
|
|
200
|
+
uses = {}
|
|
201
|
+
edits = []
|
|
202
|
+
# 셸 작업 폴더는 명령 사이에 이어진다 — 이번 턴 이전의 cd 까지 따라가 각 명령의 실행 위치를 정한다
|
|
203
|
+
cwd = ''
|
|
204
|
+
for i, e in enumerate(entries[:end_idx]):
|
|
205
|
+
if e.get('type') != 'assistant':
|
|
206
|
+
continue
|
|
207
|
+
c = (e.get('message') or {}).get('content', [])
|
|
208
|
+
if not isinstance(c, list):
|
|
209
|
+
continue
|
|
210
|
+
in_turn = i >= start
|
|
211
|
+
for b in c:
|
|
212
|
+
if not isinstance(b, dict) or b.get('type') != 'tool_use':
|
|
213
|
+
continue
|
|
214
|
+
name = _norm_tool(b.get('name'))
|
|
215
|
+
inp = b.get('input') if isinstance(b.get('input'), dict) else {}
|
|
216
|
+
if name == 'Bash':
|
|
217
|
+
cmd = inp.get('command', '') or ''
|
|
218
|
+
d, cwd = _bash_dir(cmd, cwd)
|
|
219
|
+
else:
|
|
220
|
+
cmd = ''
|
|
221
|
+
d = inp.get('projectDir') or inp.get('dir') or ''
|
|
222
|
+
if not in_turn:
|
|
223
|
+
continue
|
|
224
|
+
if name in ('Edit', 'Write', 'MultiEdit', 'NotebookEdit'):
|
|
225
|
+
p = inp.get('file_path') or inp.get('notebook_path') or ''
|
|
226
|
+
if p:
|
|
227
|
+
edits.append({'path': p, 'ts': _ts(e)})
|
|
228
|
+
continue
|
|
229
|
+
uses[b.get('id', '')] = {'tool': name, 'cmd': cmd, 'dir': d, 'ts': _ts(e), 'ok': None}
|
|
230
|
+
for e in entries[start:end_idx]:
|
|
231
|
+
if e.get('type') != 'user':
|
|
232
|
+
continue
|
|
233
|
+
c = (e.get('message') or {}).get('content', [])
|
|
234
|
+
if not isinstance(c, list):
|
|
235
|
+
continue
|
|
236
|
+
for b in c:
|
|
237
|
+
if not isinstance(b, dict) or b.get('type') != 'tool_result':
|
|
238
|
+
continue
|
|
239
|
+
u = uses.get(b.get('tool_use_id', ''))
|
|
240
|
+
if not u:
|
|
241
|
+
continue
|
|
242
|
+
rt = _result_text(b)
|
|
243
|
+
bad = bool(b.get('is_error')) or (u['tool'] == 'Bash' and bool(_EXIT_FAIL.search(rt[:400]))) or bool(_MCP_FAIL.search(rt[:2000]))
|
|
244
|
+
# 파이프로 묶은 명령은 마지막 명령의 종료 코드만 남는다 — 출력의 실패 표지로 판정
|
|
245
|
+
if not bad and u['tool'] == 'Bash' and _PIPED.search(u['cmd']) and _OUTPUT_FAIL.search(rt[-8000:]):
|
|
246
|
+
bad = True
|
|
247
|
+
u['ok'] = not bad
|
|
248
|
+
u['ts'] = max(u['ts'], _ts(e))
|
|
249
|
+
if bad:
|
|
250
|
+
u['sig'] = _fail_sig(rt)
|
|
251
|
+
runs = [u for u in uses.values() if u['ok'] is not None]
|
|
252
|
+
return {'runs': runs, 'edits': edits}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
_QCACHE = {}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def load_questions(path=QUESTIONS_PATH):
|
|
259
|
+
if path in _QCACHE:
|
|
260
|
+
return _QCACHE[path]
|
|
261
|
+
try:
|
|
262
|
+
with open(path, 'r', encoding='utf-8') as f:
|
|
263
|
+
q = json.load(f)
|
|
264
|
+
except Exception:
|
|
265
|
+
q = {'domains': {}, 'messages': {}}
|
|
266
|
+
for d in q.get('domains', {}).values():
|
|
267
|
+
for k in ('run', 'remote'):
|
|
268
|
+
d['_' + k] = [re.compile(p, re.IGNORECASE) for p in d.get(k, [])]
|
|
269
|
+
_QCACHE[path] = q
|
|
270
|
+
return q
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _matches(run, spec):
|
|
274
|
+
if run['tool'] == 'Bash':
|
|
275
|
+
return any(r.search(run['cmd']) for r in spec.get('_run', []))
|
|
276
|
+
return run['tool'] in spec.get('mcp', [])
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _mentions(run, target):
|
|
280
|
+
t = target.lower().rstrip('/')
|
|
281
|
+
base = t.split('/')[-1]
|
|
282
|
+
hay = (run.get('cmd', '') + ' ' + run.get('dir', '')).lower()
|
|
283
|
+
return t in hay or (len(base) >= 3 and base in hay)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _package_target(target):
|
|
287
|
+
"""빌드·테스트 주장의 대상이 파일이면 그 파일이 속한 디렉터리 이름(일반 이름 제외)으로. 남는 것이 없으면 None(대상 질문 생략)"""
|
|
288
|
+
if not target or not _FILE_LIKE.search(target.split('/')[-1]):
|
|
289
|
+
return target
|
|
290
|
+
dirs = [d for d in target.split('/')[:-1] if d and len(d) >= 3 and d.lower() not in _GENERIC_DIRS]
|
|
291
|
+
return '/'.join(dirs) if dirs else None
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
_NON_CODE = re.compile(r'\.(md|mdx|txt|rst|adoc)$|/docs?/|/docs2/|CHANGELOG|README', re.IGNORECASE)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _code_edit(path):
|
|
298
|
+
return not _NON_CODE.search(path or '')
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _covers(run_dir, path):
|
|
302
|
+
"""실행 위치가 편집 파일을 덮는가 — 위치를 모르면 덮는다고 본다(보수적: 기존 동작)."""
|
|
303
|
+
d = (run_dir or '').strip().rstrip('/')
|
|
304
|
+
if not d or d in ('.', '~'):
|
|
305
|
+
return True
|
|
306
|
+
p = path or ''
|
|
307
|
+
if d.startswith('/'):
|
|
308
|
+
return p == d or p.startswith(d + '/')
|
|
309
|
+
rel = d.lstrip('./')
|
|
310
|
+
return not rel or ('/' + rel + '/') in ('/' + p.lstrip('/'))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def judge(domain, claim, activity, v3_found=False, questions=None):
|
|
314
|
+
"""확인 질문 판정. 반환 (answer, reason_key, detail)
|
|
315
|
+
|
|
316
|
+
answer: 'yes'(근거 충분 → 경고 안 함) · 'no'(답이 '아니오'인 질문 → 그 이유로 경고) ·
|
|
317
|
+
'unknown'(판단 재료 부족 → v3 의 기존 판정에 맡김)
|
|
318
|
+
"""
|
|
319
|
+
q = questions or load_questions()
|
|
320
|
+
spec = q.get('domains', {}).get(domain)
|
|
321
|
+
if not spec:
|
|
322
|
+
return ('unknown', None, None)
|
|
323
|
+
runs = activity.get('runs', [])
|
|
324
|
+
target = claim.get('target')
|
|
325
|
+
asked = spec.get('cq', [])
|
|
326
|
+
|
|
327
|
+
mine = [r for r in runs if _matches(r, spec)]
|
|
328
|
+
ok_runs = [r for r in mine if r['ok']]
|
|
329
|
+
remote_ok = [r for r in runs if r['tool'] == 'Bash' and r['ok'] and any(p.search(r['cmd']) for p in spec.get('_remote', []))]
|
|
330
|
+
|
|
331
|
+
# 질문 1 — 근거 실행이 있는가
|
|
332
|
+
if not ok_runs:
|
|
333
|
+
if domain == 'deploy' and remote_ok and target:
|
|
334
|
+
if any(_mentions(r, target) for r in remote_ok):
|
|
335
|
+
return ('yes', None, None)
|
|
336
|
+
return ('no', 'target', target)
|
|
337
|
+
if mine and not v3_found:
|
|
338
|
+
return ('no', 'failed', None)
|
|
339
|
+
if v3_found:
|
|
340
|
+
return ('unknown', None, None) # 다른 소스(tracker·ledger)가 봤다 — 기존 판정
|
|
341
|
+
if domain == 'deploy' and remote_ok:
|
|
342
|
+
return ('unknown', None, None) # 원격 실행은 있는데 대상 이름이 없다 — 기존 판정
|
|
343
|
+
return ('no', 'ran', None)
|
|
344
|
+
|
|
345
|
+
# 질문 2 — 마지막 편집 뒤인가 (빌드·테스트). 설계: '해당 패키지'의 마지막 편집 시각과 비교한다 —
|
|
346
|
+
# 실행 위치(cd·projectDir)를 아는 실행은 그 디렉터리 안의 편집만 덮고, 위치를 모르는 실행은 전부를 덮는다.
|
|
347
|
+
# 어느 성공 실행의 위치에도 들지 않는 편집(다른 패키지)은 이 주장의 질문 2에서 뺀다(대상 질문이 따로 본다).
|
|
348
|
+
if 'after_edit' in asked:
|
|
349
|
+
edits = [e for e in activity.get('edits', []) if _code_edit(e.get('path')) and e.get('ts')]
|
|
350
|
+
for e in edits:
|
|
351
|
+
covering = [r for r in ok_runs if _covers(r.get('dir'), e['path'])]
|
|
352
|
+
if covering and max(r['ts'] for r in covering) < e['ts']:
|
|
353
|
+
return ('no', 'after_edit', None)
|
|
354
|
+
|
|
355
|
+
# 질문 3 — 대상이 맞는가 (대상을 말했을 때만)
|
|
356
|
+
if 'after_edit' in asked:
|
|
357
|
+
target = _package_target(target)
|
|
358
|
+
if 'target' in asked and target:
|
|
359
|
+
pool = ok_runs + (remote_ok if domain == 'deploy' else [])
|
|
360
|
+
if not any(_mentions(r, target) for r in pool):
|
|
361
|
+
# 로컬 실행인데 위치를 모르면(세션 시작 폴더 그대로) 대상이 맞는지 알 수 없다 — 기존 판정에 맡긴다
|
|
362
|
+
if any(not (r.get('dir') or '').strip() for r in ok_runs):
|
|
363
|
+
return ('unknown', None, None)
|
|
364
|
+
return ('no', 'target', target)
|
|
365
|
+
|
|
366
|
+
return ('yes', None, None)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def message(reason_key, domain, locale='ko', target=None, questions=None):
|
|
370
|
+
q = questions or load_questions()
|
|
371
|
+
lang = 'ko' if (locale or '').startswith('ko') else 'en'
|
|
372
|
+
spec = q.get('domains', {}).get(domain, {})
|
|
373
|
+
label = (spec.get('label') or {}).get(lang) or domain
|
|
374
|
+
tmpl = ((q.get('messages') or {}).get(reason_key) or {}).get(lang) or ' - {label}'
|
|
375
|
+
return tmpl.format(label=label, target=(target or '')[:60])
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def enabled(env=None):
|
|
379
|
+
return ((env if env is not None else os.environ).get('ROUTINECODE_CLAIM_CQ') or '').lower() in ('on', '1', 'true')
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def apply(confirmed_claims, activity, evidence_found, locale='ko', questions=None):
|
|
383
|
+
"""v3 L5 결과(confirmed_claims=[(domain, sentence)])를 확인 질문으로 다시 판정.
|
|
384
|
+
|
|
385
|
+
반환 dict:
|
|
386
|
+
claims — 결정 서술을 뺀 남은 주장 [(domain, sentence)]
|
|
387
|
+
reasons — 'no' 답의 경고 문구(중복 제거)
|
|
388
|
+
passed — 'yes' 로 판정돼 경고에서 빼는 영역 집합
|
|
389
|
+
deferred — 'unknown' → v3 기존 판정에 맡길 영역 집합
|
|
390
|
+
"""
|
|
391
|
+
q = questions or load_questions()
|
|
392
|
+
claims, reasons, passed, deferred = [], [], set(), set()
|
|
393
|
+
seen = set()
|
|
394
|
+
for dom, sent in confirmed_claims:
|
|
395
|
+
c = extract(sent)
|
|
396
|
+
if c['polarity'] == 'decision':
|
|
397
|
+
continue
|
|
398
|
+
claims.append((dom, sent))
|
|
399
|
+
ans, key, detail = judge(dom, c, activity, v3_found=(dom in evidence_found), questions=q)
|
|
400
|
+
if ans == 'yes':
|
|
401
|
+
passed.add(dom)
|
|
402
|
+
elif ans == 'no':
|
|
403
|
+
m = message(key, dom, locale, detail, q)
|
|
404
|
+
if m not in seen:
|
|
405
|
+
seen.add(m)
|
|
406
|
+
reasons.append(m)
|
|
407
|
+
else:
|
|
408
|
+
deferred.add(dom)
|
|
409
|
+
# 같은 영역이 한 문장에선 yes, 다른 문장에선 no 면 no 가 이긴다
|
|
410
|
+
no_domains = {d for d, s in claims if d not in passed and d not in deferred}
|
|
411
|
+
passed -= no_domains
|
|
412
|
+
return {'claims': claims, 'reasons': reasons, 'passed': passed, 'deferred': deferred - passed}
|
|
@@ -26,7 +26,7 @@ def _kdir():
|
|
|
26
26
|
os.path.expanduser('~'), '.routinecode', 'knowledge')
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
def _last_ts(log_path):
|
|
29
|
+
def _last_ts(log_path, sid=None):
|
|
30
30
|
try:
|
|
31
31
|
with open(log_path, 'rb') as f:
|
|
32
32
|
f.seek(0, 2)
|
|
@@ -35,7 +35,11 @@ def _last_ts(log_path):
|
|
|
35
35
|
tail = f.read().decode('utf-8', 'ignore').strip().split('\n')
|
|
36
36
|
for line in reversed(tail):
|
|
37
37
|
try:
|
|
38
|
-
|
|
38
|
+
row = json.loads(line)
|
|
39
|
+
# 설계 31 §16: 다른 세션의 완료는 이 세션 태스크 창의 시작이 아니다(세션 없는 구형 행은 공용)
|
|
40
|
+
if sid and row.get('session') and row.get('session') != sid:
|
|
41
|
+
continue
|
|
42
|
+
return int(row.get('ts') or 0)
|
|
39
43
|
except Exception:
|
|
40
44
|
continue
|
|
41
45
|
except Exception:
|
|
@@ -56,7 +60,7 @@ def _first_edit_ms(since_ms, files):
|
|
|
56
60
|
return min(ts) if ts else None
|
|
57
61
|
|
|
58
62
|
|
|
59
|
-
def record_completion(task_id, tier, tracker_path):
|
|
63
|
+
def record_completion(task_id, tier, tracker_path, session=None):
|
|
60
64
|
now = int(time.time() * 1000)
|
|
61
65
|
kdir = _kdir()
|
|
62
66
|
vdir = os.path.join(kdir, 'verification')
|
|
@@ -68,7 +72,8 @@ def record_completion(task_id, tier, tracker_path):
|
|
|
68
72
|
except Exception:
|
|
69
73
|
pass
|
|
70
74
|
|
|
71
|
-
|
|
75
|
+
sid = str(session or '')[:12] or None
|
|
76
|
+
prev = max(_last_ts(log_path, sid), now - WINDOW_MS)
|
|
72
77
|
|
|
73
78
|
score = None
|
|
74
79
|
forced = False
|
|
@@ -115,6 +120,8 @@ def record_completion(task_id, tier, tracker_path):
|
|
|
115
120
|
'score': score, 'forcedPass': forced, 'dims': dims, 'files': files[:200],
|
|
116
121
|
'preEditFailure': pre_edit_failure, 'hadFailure': had_failure,
|
|
117
122
|
}
|
|
123
|
+
if sid:
|
|
124
|
+
row['session'] = sid
|
|
118
125
|
try:
|
|
119
126
|
os.makedirs(vdir, exist_ok=True)
|
|
120
127
|
with open(log_path, 'a', encoding='utf-8') as f:
|
|
@@ -125,6 +132,6 @@ def record_completion(task_id, tier, tracker_path):
|
|
|
125
132
|
|
|
126
133
|
if __name__ == '__main__':
|
|
127
134
|
try:
|
|
128
|
-
record_completion(sys.argv[1], sys.argv[2], sys.argv[3])
|
|
135
|
+
record_completion(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] if len(sys.argv) > 4 else None)
|
|
129
136
|
except Exception:
|
|
130
137
|
pass
|
|
@@ -6,12 +6,12 @@ Edit/Write 는 post-edit-track.sh 가 tracker 에 기록하지만 Bash(`cp`·`mv
|
|
|
6
6
|
|
|
7
7
|
pre (PreToolUse Bash, pre-bash-guard.sh 안에서 동기) : 명령이 쓰기일 수 있고 cwd 레포에 형상 지도가 있으면
|
|
8
8
|
`git status`(GIT_SAFE) 로 지도 루트 아래 소스 파일의 (상태, mtime_ns, size) 스냅샷을 tool_use_id 별로 저장.
|
|
9
|
-
post (PostToolUse Bash, post-bash-verify.sh 에서
|
|
9
|
+
post (PostToolUse Bash, post-bash-verify.sh 에서 동기 — 안내를 이번 응답에 싣기 위해) : 같은 tool_use_id 스냅샷과 지금 상태를 비교해
|
|
10
10
|
바뀐·생긴·삭제된 소스 파일을 edit-tracker(files·ts·first·heads) 와 wiring-state/<sid>.dirty 에 기록.
|
|
11
11
|
|
|
12
12
|
지연 예산: pre 는 Bash 실행 전 동기 경로 — 읽기 전용이 분명한 명령(쓰기 리다이렉트·sed -i·find -delete 등이 없는 ls/cat/rg/git log …)과
|
|
13
13
|
지도 없는 레포는 git 을 돌리지 않고 즉시 반환한다(프로세스 추가 없음: pre-bash-guard 의 파이썬 안에서 호출).
|
|
14
|
-
post 는
|
|
14
|
+
post 는 스냅샷이 있는 호출에서만 돈다. 실패는 전부 fail-open(기록 생략).
|
|
15
15
|
지도 위치·키 계산은 mcp-routinecode/src/config-map/index-store.ts(configMapDir·repoKeyOf·mainWorktreeOf)와 같은 규칙.
|
|
16
16
|
|
|
17
17
|
git 아닌 cwd(여러 레포를 담은 워크스페이스 루트): cwd 로 toplevel 을 못 찾으면 명령 안의 경로 토큰(`#_repos_from_cmd`)이
|
|
@@ -22,6 +22,7 @@ import hashlib
|
|
|
22
22
|
import json
|
|
23
23
|
import os
|
|
24
24
|
import re
|
|
25
|
+
import shlex
|
|
25
26
|
import subprocess
|
|
26
27
|
import time
|
|
27
28
|
|
|
@@ -97,6 +98,103 @@ def maybe_writes(cmd):
|
|
|
97
98
|
return False
|
|
98
99
|
|
|
99
100
|
|
|
101
|
+
# 설계 18 T3: 형상 게이트가 다루는 소스(gate.ts SRC_EXT_RE)만. 그 밖의 쓰기에는 Node 를 띄우지 않는다
|
|
102
|
+
_GATE_SRC_RE = re.compile(r'\.(tsx?|jsx?|mjs|cjs|mts|cts)$')
|
|
103
|
+
_GATE_SRC_HINT = re.compile(r'\.(tsx?|jsx?|mjs|cjs|mts|cts)\b')
|
|
104
|
+
_HEREDOC_RE = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1")
|
|
105
|
+
_REDIR_OPS = {'>', '>>', '>|', '&>', '&>>', '>&'}
|
|
106
|
+
_SEG_OPS = {';', ';;', '&', '&&', '|', '||', '|&', '(', ')'}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _strip_heredocs(cmd):
|
|
110
|
+
"""히어독 본문 제거 — 본문의 `>` 나 따옴표를 명령으로 읽지 않게 한다"""
|
|
111
|
+
out, lines, i = [], cmd.split('\n'), 0
|
|
112
|
+
while i < len(lines):
|
|
113
|
+
ln = lines[i]
|
|
114
|
+
out.append(ln)
|
|
115
|
+
i += 1
|
|
116
|
+
for m in _HEREDOC_RE.finditer(ln):
|
|
117
|
+
while i < len(lines) and lines[i].strip() != m.group(2):
|
|
118
|
+
i += 1
|
|
119
|
+
i += 1
|
|
120
|
+
return '\n'.join(out)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _in_place_files(words):
|
|
124
|
+
"""sed -i / perl -i 의 인자 중 소스 경로"""
|
|
125
|
+
return [w for w in words[1:] if not w.startswith('-') and _GATE_SRC_RE.search(w) and not re.search(r'[\s/]$', w)]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def source_write_targets(cmd, cwd=None):
|
|
129
|
+
"""리다이렉트·tee·sed -i·perl -i 가 쓰는 소스 경로(절대 경로, 등장 순, 중복 제거).
|
|
130
|
+
|
|
131
|
+
게이트 전용 경로라 지연이 먼저다: 소스 확장자가 안 보이면 파싱도 하지 않는다. 변수·치환이 든 경로는 해석할 수 없어 뺀다.
|
|
132
|
+
스크립트 내부 쓰기는 잡지 못한다(래칫이 받는다). 파싱 실패 = [].
|
|
133
|
+
"""
|
|
134
|
+
if not cmd or not _GATE_SRC_HINT.search(cmd):
|
|
135
|
+
return []
|
|
136
|
+
try:
|
|
137
|
+
lex = shlex.shlex(_strip_heredocs(cmd).replace('\n', ' ; '), posix=True, punctuation_chars=True)
|
|
138
|
+
lex.whitespace_split = True
|
|
139
|
+
lex.commenters = ''
|
|
140
|
+
toks = list(lex)
|
|
141
|
+
except ValueError:
|
|
142
|
+
return []
|
|
143
|
+
base = cwd or os.getcwd()
|
|
144
|
+
out = []
|
|
145
|
+
|
|
146
|
+
def add(p):
|
|
147
|
+
if not _GATE_SRC_RE.search(p) or re.search(r'[$`*?]', p):
|
|
148
|
+
return
|
|
149
|
+
ab = os.path.normpath(os.path.expanduser(p) if p.startswith('~') else os.path.join(base, p))
|
|
150
|
+
if ab not in out:
|
|
151
|
+
out.append(ab)
|
|
152
|
+
|
|
153
|
+
seg = []
|
|
154
|
+
|
|
155
|
+
def flush():
|
|
156
|
+
nonlocal base
|
|
157
|
+
words = list(seg)
|
|
158
|
+
seg.clear()
|
|
159
|
+
while words and re.match(r'^[A-Za-z_][A-Za-z0-9_]*=', words[0]):
|
|
160
|
+
words = words[1:]
|
|
161
|
+
if not words:
|
|
162
|
+
return
|
|
163
|
+
w0 = os.path.basename(words[0])
|
|
164
|
+
if w0 == 'cd' and len(words) == 2 and not re.search(r'[$`*?]', words[1]):
|
|
165
|
+
base = os.path.normpath(os.path.join(base, os.path.expanduser(words[1])))
|
|
166
|
+
elif w0 == 'tee':
|
|
167
|
+
for w in words[1:]:
|
|
168
|
+
if not w.startswith('-'):
|
|
169
|
+
add(w)
|
|
170
|
+
elif w0 == 'sed' and any(a.startswith('-i') or a == '--in-place' or a.startswith('--in-place=') for a in words[1:]):
|
|
171
|
+
for w in _in_place_files(words):
|
|
172
|
+
add(w)
|
|
173
|
+
elif w0 == 'perl' and any(re.match(r'^-[a-zA-Z]*i', a) for a in words[1:]):
|
|
174
|
+
for w in _in_place_files(words):
|
|
175
|
+
add(w)
|
|
176
|
+
|
|
177
|
+
i, n = 0, len(toks)
|
|
178
|
+
while i < n:
|
|
179
|
+
t = toks[i]
|
|
180
|
+
if t in _REDIR_OPS:
|
|
181
|
+
nxt = toks[i + 1] if i + 1 < n else ''
|
|
182
|
+
fd2 = bool(seg) and seg[-1] == '2' and t in ('>', '>>')
|
|
183
|
+
if fd2:
|
|
184
|
+
seg.pop()
|
|
185
|
+
if nxt and nxt not in _SEG_OPS and not fd2 and not (t == '>&' and nxt.isdigit()):
|
|
186
|
+
add(nxt)
|
|
187
|
+
i += 2
|
|
188
|
+
continue
|
|
189
|
+
if t in _SEG_OPS:
|
|
190
|
+
flush()
|
|
191
|
+
else:
|
|
192
|
+
seg.append(t)
|
|
193
|
+
i += 1
|
|
194
|
+
flush()
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
100
198
|
def _find_toplevel(d):
|
|
101
199
|
cur = os.path.realpath(d)
|
|
102
200
|
for _ in range(64):
|
|
@@ -279,29 +377,19 @@ def pre(inp):
|
|
|
279
377
|
return None
|
|
280
378
|
|
|
281
379
|
|
|
282
|
-
def _record_tracker(paths, lib_dir=None):
|
|
380
|
+
def _record_tracker(paths, lib_dir=None, session_id=None):
|
|
381
|
+
"""Bash 로 바뀐 파일을 edit-tracker 에 — post-edit-track 과 같은 규칙(edit_tracker.record, 세션별 칸 포함)."""
|
|
382
|
+
import sys
|
|
383
|
+
if lib_dir and lib_dir not in sys.path:
|
|
384
|
+
sys.path.insert(0, lib_dir)
|
|
385
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
386
|
+
if here not in sys.path:
|
|
387
|
+
sys.path.insert(0, here)
|
|
388
|
+
import edit_tracker as et
|
|
283
389
|
tp = os.path.join(knowledge_dir(), 'edit-tracker.json')
|
|
284
|
-
|
|
285
|
-
try:
|
|
286
|
-
t = json.load(open(tp, encoding='utf-8'))
|
|
287
|
-
if not isinstance(t, dict) or not isinstance(t.get('files'), list):
|
|
288
|
-
t = {'files': []}
|
|
289
|
-
except Exception:
|
|
290
|
-
t = {'files': []}
|
|
291
|
-
now = int(time.time() * 1000)
|
|
292
|
-
for k in ('ts', 'first', 'heads'):
|
|
293
|
-
if not isinstance(t.get(k), dict):
|
|
294
|
-
t[k] = {}
|
|
295
|
-
for p in paths:
|
|
296
|
-
if p not in t['files']:
|
|
297
|
-
t['files'].append(p)
|
|
298
|
-
t['ts'][p] = now
|
|
299
|
-
t['first'].setdefault(p, now)
|
|
390
|
+
heads = {}
|
|
300
391
|
# 태스크 시작 HEAD — post-edit-track 과 같은 규칙(attest_reader.task_head_for, 기록된 기준 HEAD 만 — fail-closed)
|
|
301
392
|
try:
|
|
302
|
-
import sys
|
|
303
|
-
if lib_dir and lib_dir not in sys.path:
|
|
304
|
-
sys.path.insert(0, lib_dir)
|
|
305
393
|
from attest_reader import task_head_for
|
|
306
394
|
seen = set()
|
|
307
395
|
for p in paths:
|
|
@@ -313,13 +401,11 @@ def _record_tracker(paths, lib_dir=None):
|
|
|
313
401
|
seen.add(d)
|
|
314
402
|
top, sha = task_head_for(d)
|
|
315
403
|
if top and sha:
|
|
316
|
-
|
|
404
|
+
heads.setdefault(top, sha)
|
|
317
405
|
except Exception:
|
|
318
406
|
pass
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
json.dump(t, f)
|
|
322
|
-
os.replace(tmp, tp)
|
|
407
|
+
sid, now = et.sid_of(session_id), int(time.time() * 1000)
|
|
408
|
+
et.update(lambda t: et.record(t, paths, sid, now, heads), tp)
|
|
323
409
|
|
|
324
410
|
|
|
325
411
|
def post(inp, lib_dir=None):
|
|
@@ -352,7 +438,7 @@ def post(inp, lib_dir=None):
|
|
|
352
438
|
changed = sorted(set(changed))
|
|
353
439
|
if not changed:
|
|
354
440
|
return []
|
|
355
|
-
_record_tracker(changed, lib_dir)
|
|
441
|
+
_record_tracker(changed, lib_dir, inp.get('session_id'))
|
|
356
442
|
# 재검사 dirty — 바뀐 파일을 덮는 가장 안쪽 지도 루트(gate.markDirty 와 같은 형식: 루트 한 줄)
|
|
357
443
|
sid = inp.get('session_id') or 'unknown'
|
|
358
444
|
dirty = os.path.join(config_map_dir(), 'wiring-state', safe_seg(sid) + '.dirty')
|