@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,123 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""지식 계정 격리 — docs/지식체계/36 §16.2 (S1 CLI).
|
|
3
|
+
|
|
4
|
+
규칙은 하나다: 지식의 주인 = 만든 계정. 내용으로 가리지 않는다.
|
|
5
|
+
- 팀 계정(config.teamTenantId 있음) → 그 팀 공간(teamTenantId)
|
|
6
|
+
- 개인 계정(없음) → 본인 공간(config.tenantId)
|
|
7
|
+
- visible(entry): entry.tenantId == account.tenantId 일 때만 True.
|
|
8
|
+
legacy(없음·0·''·'0'·None·서비스 테넌트 50)는 False. 계정 공간이 없으면 아무것도 보이지 않는다.
|
|
9
|
+
|
|
10
|
+
TS 구현(mcp-intelligence/src/knowledge-scope.ts)과 같은 표를 쓴다. 바꿀 때 둘 다 바꾼다.
|
|
11
|
+
어떤 실패도 예외를 올리지 않는다(훅 fail-closed = 주입 없음, 훅은 계속 exit 0).
|
|
12
|
+
|
|
13
|
+
CLI: python3 knowledge_scope.py --notice → 팀 계정이면 세션 안내 한 줄, 개인이면 출력 없음.
|
|
14
|
+
"""
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
# 서비스 테넌트(routinecode 서비스 자체). 계정 공간으로 인정하지 않는다(36 §16.1).
|
|
19
|
+
SERVICE_TENANT_ID = '50'
|
|
20
|
+
_LEGACY_VALUES = (None, '', '0', SERVICE_TENANT_ID)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def config_path():
|
|
24
|
+
return os.path.expanduser(os.environ.get('ROUTINECODE_CONFIG_PATH', '') or '~/.routinecode/config.json')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load_config(path=None):
|
|
28
|
+
"""config.json → dict. 없으면 TS readConfig 와 같은 환경변수 폴백(API 키가 있을 때만)."""
|
|
29
|
+
try:
|
|
30
|
+
with open(path or config_path()) as f:
|
|
31
|
+
c = json.load(f)
|
|
32
|
+
return c if isinstance(c, dict) else {}
|
|
33
|
+
except Exception:
|
|
34
|
+
pass
|
|
35
|
+
if os.environ.get('ROUTINECODE_API_KEY'):
|
|
36
|
+
return {'tenantId': os.environ.get('ROUTINECODE_TENANT_ID')}
|
|
37
|
+
return {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _norm(v):
|
|
41
|
+
"""tenant id 를 비교용 문자열로. legacy 값이면 None."""
|
|
42
|
+
if v is None or isinstance(v, bool):
|
|
43
|
+
return None
|
|
44
|
+
s = str(v).strip()
|
|
45
|
+
if s.endswith('.0'): # 숫자형(138.0)으로 저장된 경우
|
|
46
|
+
s = s[:-2]
|
|
47
|
+
return None if s in _LEGACY_VALUES else s
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_legacy(v):
|
|
51
|
+
return _norm(v) is None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def account_from_config(cfg):
|
|
55
|
+
"""{'kind': 'team'|'personal', 'tenantId': str|None, 'teamName': str|None}."""
|
|
56
|
+
cfg = cfg if isinstance(cfg, dict) else {}
|
|
57
|
+
team = cfg.get('teamTenantId')
|
|
58
|
+
if team not in (None, '', 0, '0'):
|
|
59
|
+
return {'kind': 'team', 'tenantId': _norm(team), 'teamName': cfg.get('teamName') or None}
|
|
60
|
+
return {'kind': 'personal', 'tenantId': _norm(cfg.get('tenantId')), 'teamName': None}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
_ACCOUNT = None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def account(refresh=False):
|
|
67
|
+
global _ACCOUNT
|
|
68
|
+
if _ACCOUNT is None or refresh:
|
|
69
|
+
try:
|
|
70
|
+
_ACCOUNT = account_from_config(_load_config())
|
|
71
|
+
except Exception:
|
|
72
|
+
_ACCOUNT = {'kind': 'personal', 'tenantId': None, 'teamName': None}
|
|
73
|
+
return _ACCOUNT
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def visible_tenant(entry_tenant_id, acct=None):
|
|
77
|
+
try:
|
|
78
|
+
a = acct if acct is not None else account()
|
|
79
|
+
mine = a.get('tenantId')
|
|
80
|
+
if mine is None:
|
|
81
|
+
return False
|
|
82
|
+
theirs = _norm(entry_tenant_id)
|
|
83
|
+
return theirs is not None and theirs == mine
|
|
84
|
+
except Exception:
|
|
85
|
+
return False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def visible(entry, acct=None):
|
|
89
|
+
"""지식 행 하나가 현재 계정에 보이는가(36 §16.2)."""
|
|
90
|
+
if not isinstance(entry, dict):
|
|
91
|
+
return False
|
|
92
|
+
return visible_tenant(entry.get('tenantId'), acct)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def record_tenant_id(acct=None):
|
|
96
|
+
"""기록 시 entry 에 붙일 tenantId(계정 공간). 없으면 None."""
|
|
97
|
+
a = acct if acct is not None else account()
|
|
98
|
+
return a.get('tenantId')
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def team_notice(acct=None):
|
|
102
|
+
"""팀 계정이면 '이 계정의 작업 지식은 {teamName}팀에 공유됩니다'(5개 언어), 아니면 ''."""
|
|
103
|
+
try:
|
|
104
|
+
a = acct if acct is not None else account()
|
|
105
|
+
if a.get('kind') != 'team' or not a.get('tenantId'):
|
|
106
|
+
return ''
|
|
107
|
+
name = a.get('teamName') or a.get('tenantId')
|
|
108
|
+
try:
|
|
109
|
+
from i18n import t
|
|
110
|
+
return t('knowledge.team_shared_notice', team=name)
|
|
111
|
+
except Exception:
|
|
112
|
+
return '이 계정의 작업 지식은 %s팀에 공유됩니다' % name
|
|
113
|
+
except Exception:
|
|
114
|
+
return ''
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
if __name__ == '__main__':
|
|
118
|
+
import sys
|
|
119
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
120
|
+
if '--notice' in sys.argv[1:]:
|
|
121
|
+
msg = team_notice()
|
|
122
|
+
if msg:
|
|
123
|
+
print(msg)
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
|
|
4
4
|
설계: .routinecode/plans/design-knowledge-consumption-loop.md (design score 96)
|
|
5
5
|
사용처: user-prompt-submit.sh(L1, additionalContext) / post-bash-knowledge.sh(L2, systemMessage)
|
|
6
|
+
새 형식 지식(v31): consume_v31 — Bash 에러 = 마주침 기록 + 문제 키·명령 조건 일치 주입(docs/지식체계/36 §4·§5)
|
|
7
|
+
계정 격리: _tenant_ok → knowledge_scope.visible_tenant (docs/지식체계/36 §16.2, legacy 숨김)
|
|
6
8
|
|
|
7
9
|
원칙: 보수 이중 문턱(12자+ 공통 부분열 OR 토큰 자카드>=0.5), 1건만, 저장된 지식 필드만 인용
|
|
8
10
|
(사용자 프롬프트 원문 비포함), 세션x시그니처 1회(dedup 마커), 실패 시 조용히 None(fail-open).
|
|
@@ -58,18 +60,16 @@ def _common_substr_len(a, b):
|
|
|
58
60
|
|
|
59
61
|
|
|
60
62
|
def _tenant_ok(entry_tid):
|
|
61
|
-
"""
|
|
62
|
-
legacy = entry_tid in (None, 0, '0', '')
|
|
63
|
-
if legacy:
|
|
64
|
-
return True
|
|
63
|
+
"""계정 격리(docs/지식체계/36 §16.2) — 공용 knowledge_scope 와 같은 판정. legacy 는 숨김, 실패 시 숨김."""
|
|
65
64
|
try:
|
|
66
|
-
|
|
67
|
-
|
|
65
|
+
import sys
|
|
66
|
+
_d = os.path.dirname(os.path.abspath(__file__))
|
|
67
|
+
if _d not in sys.path:
|
|
68
|
+
sys.path.insert(0, _d)
|
|
69
|
+
import knowledge_scope
|
|
70
|
+
return knowledge_scope.visible_tenant(entry_tid)
|
|
68
71
|
except Exception:
|
|
69
|
-
my = None
|
|
70
|
-
if my in (None, 0, '0', ''):
|
|
71
72
|
return False
|
|
72
|
-
return str(entry_tid) == str(my)
|
|
73
73
|
|
|
74
74
|
|
|
75
75
|
def find_known_solution(error_text):
|
|
@@ -146,3 +146,31 @@ def consume_once(session_id, error_text):
|
|
|
146
146
|
except Exception:
|
|
147
147
|
pass
|
|
148
148
|
return build_injection(e)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def consume_v31(session_id, error_text, command=None, fallback=False):
|
|
152
|
+
"""실패한 Bash 경로(docs/지식체계/38 E1·E2, PostToolUseFailure).
|
|
153
|
+
1) 마주침: 에러 머리 줄(error_line)만 — 소스 코드 줄·빈 실패는 마주침이 아니다. 문제 키·종류 키·열린 문제(점검=명령 머리)
|
|
154
|
+
2) 주입: 같은 문제 키의 지식 → 순위·예산 → 노출 기록 + 열린 문제에 '지식 보임' 표시
|
|
155
|
+
3) 대기열 백그라운드 flush. 반환 = 주입문 또는 None. 어떤 실패도 None.
|
|
156
|
+
command 조건 지식은 실행 전(pre-bash-knowledge.sh)에서 본다(E6)."""
|
|
157
|
+
try:
|
|
158
|
+
import sys
|
|
159
|
+
_d = os.path.dirname(os.path.abspath(__file__))
|
|
160
|
+
if _d not in sys.path:
|
|
161
|
+
sys.path.insert(0, _d)
|
|
162
|
+
import knowledge_items as ki
|
|
163
|
+
if not error_text:
|
|
164
|
+
return None
|
|
165
|
+
rec = ki.record_error(error_text, session_id, 'bash', ki.check_of_command(command), fallback=fallback)
|
|
166
|
+
if not rec:
|
|
167
|
+
return None
|
|
168
|
+
pk = rec['problemKey']
|
|
169
|
+
sel = ki.select([{'type': 'problem', 'problemKey': pk}], session_id=session_id)
|
|
170
|
+
if sel:
|
|
171
|
+
ki.record_exposure(sel, session_id, 'inject:bash', problem_key=pk)
|
|
172
|
+
ki.mark_problem_shown(session_id, pk)
|
|
173
|
+
ki.flush_background()
|
|
174
|
+
return sel['text'] if sel else None
|
|
175
|
+
except Exception:
|
|
176
|
+
return None
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""테스트·빌드 출력 축약. 맥락에 들어가는 로그를 줄이고 원문은 임시 파일에 남긴다.
|
|
3
|
+
|
|
4
|
+
pre-bash-guard 가 wrap() 으로 명령을 감싸고, 실행 후 이 파일이 CLI 로 출력을 고른다.
|
|
5
|
+
종료 코드는 그대로 보존한다. ROUTINECODE_LOG_COMPACT=off 면 감싸지 않는다.
|
|
6
|
+
"""
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
KEEP_CHARS = 6000 # 이 이하이면 원문 그대로 출력한다.
|
|
13
|
+
TAIL_LINES = 25
|
|
14
|
+
MAX_ERROR_LINES = 200
|
|
15
|
+
CONTEXT = 2
|
|
16
|
+
|
|
17
|
+
# 쉘 메타문자가 없는 단순 실행만 감싼다. 파이프·리다이렉트가 있으면 사용자가 이미 출력을 다루는 것이다.
|
|
18
|
+
_ARGS = r'(?:\s+[^;&|<>`$\n]*)?'
|
|
19
|
+
_RUNNER = re.compile(
|
|
20
|
+
r'^(?:cd\s+[^;&|<>`$\n]+&&\s*)?(?:'
|
|
21
|
+
r'(?:npm|pnpm|yarn)(?:\s+-r|\s+--filter\s+\S+)?\s+(?:run\s+)?(?:test|build|typecheck|lint)(?::\S+)?'
|
|
22
|
+
r'|npx\s+(?:tsc|jest|vitest)|tsc|jest|vitest'
|
|
23
|
+
r'|pytest|python3?\s+-m\s+pytest'
|
|
24
|
+
r'|go\s+(?:test|build)|cargo\s+(?:test|build|check)|make(?:\s+(?:test|build))?'
|
|
25
|
+
r')' + _ARGS + r'$')
|
|
26
|
+
|
|
27
|
+
_ANSI = re.compile(r'\x1b\[[0-9;]*[A-Za-z]')
|
|
28
|
+
_ERROR = re.compile(r'\b(error|errors|failed|failure|fail|exception|traceback|panic|fatal)\b|^\s*(E\s|✕|×|●)', re.I)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def should_wrap(cmd, tool_input=None):
|
|
32
|
+
if os.environ.get('ROUTINECODE_LOG_COMPACT', 'on') == 'off':
|
|
33
|
+
return False
|
|
34
|
+
if isinstance(tool_input, dict) and tool_input.get('run_in_background'):
|
|
35
|
+
return False
|
|
36
|
+
return bool(_RUNNER.match((cmd or '').strip()))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def wrap(cmd, lib_dir):
|
|
40
|
+
"""중괄호로 감싸 cd 가 세션에 유지되게 하고, 마지막에 원래 종료 코드를 돌려준다."""
|
|
41
|
+
script = shlex.quote(os.path.join(lib_dir, 'log_compact.py'))
|
|
42
|
+
return (
|
|
43
|
+
'_rcl=$(mktemp "${TMPDIR:-/tmp}/rc-log.XXXXXX"); '
|
|
44
|
+
'{ %s\n} >"$_rcl" 2>&1; _rcs=$?; '
|
|
45
|
+
'python3 %s "$_rcl" "$_rcs" 2>/dev/null || cat "$_rcl"; '
|
|
46
|
+
'(exit $_rcs)' % (cmd.strip(), script)
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def compact(text, code):
|
|
51
|
+
text = _ANSI.sub('', text)
|
|
52
|
+
if len(text) <= KEEP_CHARS:
|
|
53
|
+
return text, False
|
|
54
|
+
lines = text.splitlines()
|
|
55
|
+
keep = set(range(max(0, len(lines) - TAIL_LINES), len(lines)))
|
|
56
|
+
if code != 0:
|
|
57
|
+
picked = set()
|
|
58
|
+
for i, line in enumerate(lines):
|
|
59
|
+
if _ERROR.search(line):
|
|
60
|
+
picked.update(range(max(0, i - CONTEXT), min(len(lines), i + CONTEXT + 1)))
|
|
61
|
+
if len(picked) >= MAX_ERROR_LINES:
|
|
62
|
+
break
|
|
63
|
+
keep |= picked
|
|
64
|
+
out = []
|
|
65
|
+
last = -1
|
|
66
|
+
for i in sorted(keep):
|
|
67
|
+
if last >= 0 and i != last + 1:
|
|
68
|
+
out.append('...')
|
|
69
|
+
out.append(lines[i])
|
|
70
|
+
last = i
|
|
71
|
+
return '\n'.join(out), True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main():
|
|
75
|
+
path, code = sys.argv[1], int(sys.argv[2])
|
|
76
|
+
with open(path, encoding='utf8', errors='replace') as f:
|
|
77
|
+
text = f.read()
|
|
78
|
+
body, cut = compact(text, code)
|
|
79
|
+
sys.stdout.write(body if body.endswith('\n') or not body else body + '\n')
|
|
80
|
+
if cut:
|
|
81
|
+
print('[RoutineCode] 출력 축약: 원문 %d줄 %d자, 전체 로그 %s' % (len(text.splitlines()), len(text), path))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == '__main__':
|
|
85
|
+
main()
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""메타지능 신호 — 설계 28 T1·T4.
|
|
2
|
+
|
|
3
|
+
대화 기록(transcript) → 사람 메시지 기준 작업 턴 → 편집이 있는 턴마다 관찰 신호와 결과 라벨.
|
|
4
|
+
split_turns(entries) → [{'entries', 'next_user', 'warned', 'idx'}]
|
|
5
|
+
signals(turn, links=None) → 신호 dict (수치만)
|
|
6
|
+
labels(turns, i) → {'correction': 0|1, 'rework': 0|1}
|
|
7
|
+
auc / stratified_auc / ceiling → 측정
|
|
8
|
+
판정·측정은 실행 기록 대조뿐 — LLM·자기 점수 없음(C4). 반환값에 원문 문자열을 넣지 않는다(C5).
|
|
9
|
+
"""
|
|
10
|
+
import hashlib
|
|
11
|
+
import importlib.util
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
|
|
16
|
+
import claim_structure as cs
|
|
17
|
+
|
|
18
|
+
_HERE = os.path.dirname(os.path.abspath(__file__))
|
|
19
|
+
_EDIT = ('Edit', 'Write', 'MultiEdit', 'NotebookEdit')
|
|
20
|
+
|
|
21
|
+
# 다음 사람 메시지가 앞 작업을 정정하는가(거친 라벨 L1 — 정밀도는 사람 표본으로 잰다, T2)
|
|
22
|
+
CORRECTION = re.compile(
|
|
23
|
+
r'안\s?돼|안\s?되|아직도|여전히|틀렸|틀린|잘못|그게 아니|왜\s.*(안|못)|다시 (해|확인)|버그|에러|오류'
|
|
24
|
+
r'|still|doesn.?t work|not working|wrong|broken|failed', re.IGNORECASE)
|
|
25
|
+
HEDGE = re.compile(r'아마|추정|것 같|보입니다|가능성|probably|likely|might|seems', re.IGNORECASE)
|
|
26
|
+
_NON_CODE = re.compile(r'\.(md|mdx|txt|rst|adoc|json|ya?ml)$', re.IGNORECASE)
|
|
27
|
+
|
|
28
|
+
# 정본 = scripts/claim-sample.py 의 is_real_user(파일 이름에 하이픈 — importlib 로 불러 복제하지 않는다)
|
|
29
|
+
_cs_path = os.path.join(os.path.dirname(os.path.dirname(_HERE)), 'scripts', 'claim-sample.py')
|
|
30
|
+
try:
|
|
31
|
+
_spec = importlib.util.spec_from_file_location('claim_sample', _cs_path)
|
|
32
|
+
_claim_sample = importlib.util.module_from_spec(_spec)
|
|
33
|
+
_spec.loader.exec_module(_claim_sample)
|
|
34
|
+
_is_real_user_base = _claim_sample.is_real_user
|
|
35
|
+
except Exception: # 설치본에 scripts 가 없을 때 — 같은 규칙
|
|
36
|
+
def _is_real_user_base(e):
|
|
37
|
+
if e.get('type') != 'user':
|
|
38
|
+
return False
|
|
39
|
+
c = (e.get('message') or {}).get('content')
|
|
40
|
+
return isinstance(c, str) or (isinstance(c, list) and any(isinstance(b, dict) and b.get('type') == 'text' for b in c))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _user_text(e):
|
|
44
|
+
c = (e.get('message') or {}).get('content')
|
|
45
|
+
if isinstance(c, str):
|
|
46
|
+
return c
|
|
47
|
+
if isinstance(c, list):
|
|
48
|
+
return '\n'.join(b.get('text', '') for b in c if isinstance(b, dict) and b.get('type') == 'text')
|
|
49
|
+
return ''
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_real_user(e):
|
|
53
|
+
"""사람이 쓴 메시지 — 도구 결과·명령 출력·시스템 주입(<...>)은 제외"""
|
|
54
|
+
if not _is_real_user_base(e):
|
|
55
|
+
return False
|
|
56
|
+
c = (e.get('message') or {}).get('content')
|
|
57
|
+
if isinstance(c, list) and any(isinstance(b, dict) and b.get('type') == 'tool_result' for b in c):
|
|
58
|
+
return False
|
|
59
|
+
return not _user_text(e).lstrip().startswith('<')
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def split_turns(entries):
|
|
63
|
+
turns, cur = [], None
|
|
64
|
+
for e in entries:
|
|
65
|
+
if e.get('isSidechain'):
|
|
66
|
+
continue
|
|
67
|
+
if e.get('type') == 'attachment':
|
|
68
|
+
a = e.get('attachment') or {}
|
|
69
|
+
if cur is not None and a.get('hookEvent') == 'Stop' and 'stop-claim-check' in (a.get('command') or '') \
|
|
70
|
+
and '[WARN]' in (a.get('stdout') or ''):
|
|
71
|
+
cur['warned'] = 1
|
|
72
|
+
continue
|
|
73
|
+
if e.get('type') not in ('user', 'assistant'):
|
|
74
|
+
continue
|
|
75
|
+
if is_real_user(e):
|
|
76
|
+
if cur is not None:
|
|
77
|
+
cur['next_user'] = _user_text(e)
|
|
78
|
+
cur = {'entries': [e], 'next_user': None, 'warned': 0, 'idx': len(turns)}
|
|
79
|
+
turns.append(cur)
|
|
80
|
+
continue
|
|
81
|
+
if cur is not None:
|
|
82
|
+
cur['entries'].append(e)
|
|
83
|
+
return turns
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _last_text(entries):
|
|
87
|
+
for e in reversed(entries):
|
|
88
|
+
if e.get('type') == 'assistant':
|
|
89
|
+
c = (e.get('message') or {}).get('content')
|
|
90
|
+
if isinstance(c, list):
|
|
91
|
+
t = '\n'.join(b.get('text', '') for b in c if isinstance(b, dict) and b.get('type') == 'text')
|
|
92
|
+
if t:
|
|
93
|
+
return t
|
|
94
|
+
return ''
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _is_check(run):
|
|
98
|
+
q = cs.load_questions().get('domains', {})
|
|
99
|
+
return any(cs._matches(run, q[d]) for d in ('build_ok', 'test_ok') if d in q)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _start_ts(turn):
|
|
103
|
+
return cs._ts(turn['entries'][0]) if turn['entries'] else 0.0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def load_links(path=None):
|
|
107
|
+
"""causal-links.jsonl → [(ts, {파일 경로})] — 파일 위험 점수의 주 입력(그 시각 이전 것만 쓰도록 ts 를 남긴다)"""
|
|
108
|
+
path = path or os.path.expanduser(os.path.join('~', '.routinecode', 'knowledge', 'causal-links.jsonl'))
|
|
109
|
+
out = []
|
|
110
|
+
try:
|
|
111
|
+
import json
|
|
112
|
+
from datetime import datetime
|
|
113
|
+
with open(path, encoding='utf-8') as f:
|
|
114
|
+
for ln in f:
|
|
115
|
+
try:
|
|
116
|
+
d = json.loads(ln)
|
|
117
|
+
t = datetime.fromisoformat(str(d.get('ts')).replace('Z', '+00:00')).timestamp()
|
|
118
|
+
except Exception:
|
|
119
|
+
continue
|
|
120
|
+
files = {(d.get('trigger') or {}).get('file'), (d.get('effect') or {}).get('file')} - {None, ''}
|
|
121
|
+
if files:
|
|
122
|
+
out.append((t, files))
|
|
123
|
+
except Exception:
|
|
124
|
+
pass
|
|
125
|
+
return out
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def signals(turn, links=None):
|
|
129
|
+
"""편집이 있는 턴 → 신호(수치). 편집 없으면 None."""
|
|
130
|
+
act = cs.turn_activity(turn['entries'], 0, len(turn['entries']))
|
|
131
|
+
edits = act['edits']
|
|
132
|
+
if not edits:
|
|
133
|
+
return None
|
|
134
|
+
per_file = defaultdict(int)
|
|
135
|
+
for e in edits:
|
|
136
|
+
per_file[e['path']] += 1
|
|
137
|
+
code = [e for e in edits if not _NON_CODE.search(e['path'] or '')]
|
|
138
|
+
checks = [r for r in act['runs'] if _is_check(r)]
|
|
139
|
+
last_edit = max(e['ts'] for e in edits)
|
|
140
|
+
ok_after = any(r['ok'] and r['ts'] > last_edit and any(cs._covers(r.get('dir'), e['path']) for e in edits) for r in checks)
|
|
141
|
+
edit_ts = sorted(e['ts'] for e in edits)
|
|
142
|
+
fails = [r for r in act['runs'] if not r['ok'] and r.get('sig')]
|
|
143
|
+
refuted = 0
|
|
144
|
+
for i, f1 in enumerate(fails):
|
|
145
|
+
if any(f2['sig'] == f1['sig'] and any(f1['ts'] < t < f2['ts'] for t in edit_ts) for f2 in fails[i + 1:]):
|
|
146
|
+
refuted += 1
|
|
147
|
+
st = _start_ts(turn)
|
|
148
|
+
link_n = 0
|
|
149
|
+
if links:
|
|
150
|
+
files = set(per_file)
|
|
151
|
+
link_n = sum(1 for t, fs in links if t < st and fs & files)
|
|
152
|
+
return {
|
|
153
|
+
'edits': len(edits),
|
|
154
|
+
'files': len(per_file),
|
|
155
|
+
'max_same': max(per_file.values()),
|
|
156
|
+
'code_edit': int(bool(code)),
|
|
157
|
+
'fails': sum(1 for r in act['runs'] if not r['ok']),
|
|
158
|
+
'refuted': refuted,
|
|
159
|
+
'no_check_after_edit': int(bool(code) and not ok_after),
|
|
160
|
+
'hedge': int(bool(HEDGE.search(_last_text(turn['entries'])[-800:]))),
|
|
161
|
+
'warned': int(turn.get('warned', 0)),
|
|
162
|
+
'causal_links': link_n,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def labels(turns, i, horizon=3):
|
|
167
|
+
"""L1 correction = 다음 사람 메시지가 정정 표현. L2 rework = 다음 horizon 턴 안에 같은 파일을 실패한 점검 뒤 다시 편집."""
|
|
168
|
+
t = turns[i]
|
|
169
|
+
corr = int(bool(CORRECTION.search((t.get('next_user') or '')[:400])))
|
|
170
|
+
files = {e['path'] for e in cs.turn_activity(t['entries'], 0, len(t['entries']))['edits']}
|
|
171
|
+
rework = 0
|
|
172
|
+
for nt in turns[i + 1:i + 1 + horizon]:
|
|
173
|
+
act = cs.turn_activity(nt['entries'], 0, len(nt['entries']))
|
|
174
|
+
failed = [r['ts'] for r in act['runs'] if not r['ok'] and _is_check(r)]
|
|
175
|
+
if failed and any(e['path'] in files and e['ts'] > min(failed) for e in act['edits']):
|
|
176
|
+
rework = 1
|
|
177
|
+
break
|
|
178
|
+
return {'correction': corr, 'rework': rework}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def edit_bin(n):
|
|
182
|
+
return 1 if n <= 1 else 3 if n <= 3 else 8 if n <= 8 else 99
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def auc(xs, ys):
|
|
186
|
+
"""순위 AUC(동점 0.5). 양성·음성 한쪽이 없으면 None."""
|
|
187
|
+
pairs = sorted(zip(xs, ys), key=lambda p: p[0])
|
|
188
|
+
pos = sum(1 for _, y in pairs if y)
|
|
189
|
+
neg = len(pairs) - pos
|
|
190
|
+
if not pos or not neg:
|
|
191
|
+
return None
|
|
192
|
+
# 순위 합(동점 평균 순위) — O(n log n)
|
|
193
|
+
rank_sum, i = 0.0, 0
|
|
194
|
+
while i < len(pairs):
|
|
195
|
+
j = i
|
|
196
|
+
while j < len(pairs) and pairs[j][0] == pairs[i][0]:
|
|
197
|
+
j += 1
|
|
198
|
+
avg = (i + 1 + j) / 2.0
|
|
199
|
+
rank_sum += avg * sum(1 for _, y in pairs[i:j] if y)
|
|
200
|
+
i = j
|
|
201
|
+
return (rank_sum - pos * (pos + 1) / 2.0) / (pos * neg)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def stratified_auc(rows, key, label, strata=('edit_bin', 'code_edit')):
|
|
205
|
+
"""층(편집량 구간 × 편집 종류) 안에서 잰 AUC 를 양성×음성 쌍 수로 가중 평균 — 편집량 교란 통제"""
|
|
206
|
+
groups = defaultdict(list)
|
|
207
|
+
for r in rows:
|
|
208
|
+
groups[tuple(r.get(s) for s in strata)].append(r)
|
|
209
|
+
num = den = 0.0
|
|
210
|
+
for g in groups.values():
|
|
211
|
+
a = auc([r[key] for r in g], [r[label] for r in g])
|
|
212
|
+
if a is None:
|
|
213
|
+
continue
|
|
214
|
+
p = sum(1 for r in g if r[label])
|
|
215
|
+
w = p * (len(g) - p)
|
|
216
|
+
num += a * w
|
|
217
|
+
den += w
|
|
218
|
+
return num / den if den else None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def ceiling(true_given_pos, true_given_neg):
|
|
222
|
+
"""거친 라벨에 대해 완벽한 예측기가 낼 수 있는 AUC.
|
|
223
|
+
true_given_pos = P(진짜 | 라벨=1), true_given_neg = P(진짜 | 라벨=0) — 사람 표본에서 추정."""
|
|
224
|
+
return 0.5 * (1.0 + true_given_pos - true_given_neg)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def session_hash(path):
|
|
228
|
+
return hashlib.sha1(os.path.basename(path).encode('utf-8', 'replace')).hexdigest()[:12]
|