@routinecrew/routinecode 2.31.56 → 2.31.58

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.
Files changed (149) hide show
  1. package/bin/cli.sh +65 -41
  2. package/bin/prompt-vault.js +1 -1
  3. package/bin/rc-credit-turn.js +30 -4
  4. package/bin/rc-grant.js +79 -0
  5. package/bin/rc-login.js +19 -1
  6. package/bin/seal-open.js +5 -2
  7. package/bin/setup.js +1 -1
  8. package/hooks/hooks-config.json +31 -4
  9. package/hooks/lib/anchors.json +523 -126
  10. package/hooks/lib/attest_reader.py +695 -0
  11. package/hooks/lib/completion_log.py +130 -0
  12. package/hooks/lib/evidence.py +12 -0
  13. package/hooks/lib/i18n.py +7 -0
  14. package/hooks/lib/rt_cleanup.py +61 -0
  15. package/hooks/lib/scrub_stream.py +43 -0
  16. package/hooks/lib/secret_filter.py +300 -1
  17. package/hooks/lib/supplements_sig.py +70 -0
  18. package/hooks/post-edit-track.sh +35 -5
  19. package/hooks/post-knowledge-query.sh +14 -0
  20. package/hooks/post-secret-detect.sh +12 -27
  21. package/hooks/post-tool-universal.sh +6 -0
  22. package/hooks/pre-account-guard.sh +13 -1
  23. package/hooks/pre-agent-spawn.mjs +1 -1
  24. package/hooks/pre-bash-guard.sh +11 -0
  25. package/hooks/pre-credit-guard.sh +45 -28
  26. package/hooks/pre-edit-domain-gate.sh +3 -1
  27. package/hooks/pre-edit-knowledge-gate.sh +3 -1
  28. package/hooks/pre-edit-snapshot.sh +29 -0
  29. package/hooks/pre-grep-guard.sh +11 -0
  30. package/hooks/pre-mark-complete.sh +170 -72
  31. package/hooks/pre-read-guard.sh +9 -0
  32. package/hooks/pre-read-knowledge-inject.sh +3 -1
  33. package/hooks/session-start.sh +66 -10
  34. package/hooks/stop-claim-check.v3.sh +81 -0
  35. package/hooks/stop-knowledge-remind.sh +45 -10
  36. package/hooks/tests/gate-integration.test.sh +183 -2
  37. package/hooks/tests/in-project-relax.test.py +2 -1
  38. package/hooks/tests/knowledge-loop.test.sh +89 -0
  39. package/hooks/tests/mcp-name-wiring.test.sh +64 -0
  40. package/hooks/tests/secret-guard.test.sh +2 -1
  41. package/hooks/tests/secret-premask.test.py +166 -0
  42. package/hooks/tests/stop-autoproceed.test.sh +60 -0
  43. package/hooks/user-prompt-submit.sh +18 -12
  44. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  45. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  46. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  47. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  48. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  49. package/mcp-db-manager/dist/index.js +1 -1
  50. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  51. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  52. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  53. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  54. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  55. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  56. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  57. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  58. package/mcp-dev-tester/dist/attestation.d.ts +36 -0
  59. package/mcp-dev-tester/dist/attestation.d.ts.map +1 -0
  60. package/mcp-dev-tester/dist/attestation.js +1 -0
  61. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  62. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  63. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  64. package/mcp-dev-tester/dist/index.js +1 -1
  65. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  66. package/mcp-doc-fetcher/dist/index.js +1 -1
  67. package/mcp-html-renderer/dist/index.js +1 -1
  68. package/mcp-html-renderer/dist/preview.js +1 -1
  69. package/mcp-html-renderer/dist/template-engine.js +1 -1
  70. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  71. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  72. package/mcp-intelligence/dist/config-auth.js +1 -1
  73. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  74. package/mcp-intelligence/dist/domain-templates.js +1 -1
  75. package/mcp-intelligence/dist/grounding.d.ts +1 -0
  76. package/mcp-intelligence/dist/grounding.d.ts.map +1 -1
  77. package/mcp-intelligence/dist/grounding.js +1 -1
  78. package/mcp-intelligence/dist/handlers.js +1 -1
  79. package/mcp-intelligence/dist/index.js +1 -1
  80. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  81. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  82. package/mcp-intelligence/dist/knowledge-handlers.d.ts +20 -0
  83. package/mcp-intelligence/dist/knowledge-handlers.d.ts.map +1 -1
  84. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  85. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  86. package/mcp-intelligence/dist/provenance.js +1 -1
  87. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  88. package/mcp-log-watcher/dist/config-auth.js +1 -1
  89. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  90. package/mcp-log-watcher/dist/index.js +1 -1
  91. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  92. package/mcp-log-watcher/dist/log-store.js +1 -1
  93. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  94. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  95. package/mcp-plan-manager/dist/file-ops.js +1 -1
  96. package/mcp-plan-manager/dist/index.js +1 -1
  97. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  98. package/mcp-project-context/dist/git-ops.js +1 -1
  99. package/mcp-project-context/dist/index.js +1 -1
  100. package/mcp-project-context/dist/project-analysis.js +1 -1
  101. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  102. package/mcp-routinecode/dist/attestation.d.ts +37 -0
  103. package/mcp-routinecode/dist/attestation.js +1 -0
  104. package/mcp-routinecode/dist/blast-radius.js +1 -1
  105. package/mcp-routinecode/dist/changeset.d.ts +86 -0
  106. package/mcp-routinecode/dist/changeset.js +1 -0
  107. package/mcp-routinecode/dist/config-auth.js +1 -1
  108. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  109. package/mcp-routinecode/dist/coverage.d.ts +49 -0
  110. package/mcp-routinecode/dist/coverage.js +1 -0
  111. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  112. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  113. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  114. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  115. package/mcp-routinecode/dist/index.js +1 -1
  116. package/mcp-routinecode/dist/known-solutions.js +1 -1
  117. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  118. package/mcp-routinecode/dist/observed-draft.js +1 -1
  119. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  120. package/mcp-routinecode/dist/route-match.d.ts +24 -0
  121. package/mcp-routinecode/dist/route-match.js +1 -0
  122. package/mcp-routinecode/dist/routines.d.ts +1 -0
  123. package/mcp-routinecode/dist/routines.js +1 -1
  124. package/mcp-routinecode/dist/rule-engine.js +1 -1
  125. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  126. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  127. package/mcp-routinecode/dist/test-runner.d.ts +66 -0
  128. package/mcp-routinecode/dist/test-runner.js +1 -0
  129. package/mcp-routinecode/dist/verification.d.ts +65 -0
  130. package/mcp-routinecode/dist/verification.js +0 -0
  131. package/mcp-routinecode/dist/viral-loop.js +1 -1
  132. package/package.json +1 -1
  133. package/plugin/.claude-plugin/plugin.json +1 -1
  134. package/plugin/agents/analyzer.md.sealed +1 -0
  135. package/plugin/agents/crawler.md.sealed +1 -0
  136. package/plugin/agents/explorer.md.sealed +1 -0
  137. package/plugin/agents/implementor.md.sealed +1 -0
  138. package/plugin/agents/looker.md.sealed +1 -0
  139. package/plugin/agents/planner.md.sealed +1 -0
  140. package/plugin/agents/recorder.md.sealed +1 -0
  141. package/plugin/agents/reviewer.md.sealed +1 -0
  142. package/plugin/agents/verifier.md.sealed +1 -0
  143. package/plugin/commands/analyze.md.sealed +1 -0
  144. package/plugin/commands/plan.md.sealed +1 -0
  145. package/plugin/commands/rc.md.sealed +1 -0
  146. package/plugin/commands/receipt.md.sealed +1 -0
  147. package/plugin/commands/routines.md.sealed +1 -0
  148. package/plugin/commands/share.md.sealed +1 -0
  149. package/plugin/routinecode-prompt.md.sealed +1 -0
@@ -0,0 +1,695 @@
1
+ """Attestation reader — mcp-routinecode/src/attestation.ts 의 Python 검증기.
2
+
3
+ 서명 대상 직렬화는 JS `JSON.stringify([v, kind, ts, projectDir, success, detail])` 와
4
+ 바이트 단위로 같아야 한다 → separators=(',', ':'), ensure_ascii=False.
5
+ """
6
+
7
+ import hashlib
8
+ import hmac
9
+ import json
10
+ import os
11
+
12
+
13
+ def _attest_dir():
14
+ base = os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(
15
+ os.path.expanduser('~'), '.routinecode', 'knowledge')
16
+ return os.path.join(base, 'attest')
17
+
18
+
19
+ def _canonical(e):
20
+ return json.dumps(
21
+ [e.get('v'), e.get('kind'), e.get('ts'), e.get('projectDir'), e.get('success'), e.get('detail')],
22
+ separators=(',', ':'), ensure_ascii=False,
23
+ )
24
+
25
+
26
+ def read_attestations(since_ms=0, kinds=None):
27
+ """서명 검증된 행만 반환. 키/파일 없음 → []"""
28
+ d = _attest_dir()
29
+ try:
30
+ key = open(os.path.join(d, '.key'), 'rb').read()
31
+ except Exception:
32
+ return []
33
+ out = []
34
+ try:
35
+ with open(os.path.join(d, 'attestations.jsonl'), encoding='utf-8') as f:
36
+ for line in f:
37
+ line = line.strip()
38
+ if not line:
39
+ continue
40
+ try:
41
+ e = json.loads(line)
42
+ except Exception:
43
+ continue
44
+ mac = e.get('mac')
45
+ if e.get('v') != 1 or not isinstance(mac, str):
46
+ continue
47
+ expected = hmac.new(key, _canonical(e).encode('utf-8'), hashlib.sha256).hexdigest()
48
+ if not hmac.compare_digest(mac, expected):
49
+ continue
50
+ if (e.get('ts') or 0) < since_ms:
51
+ continue
52
+ if kinds and e.get('kind') not in kinds:
53
+ continue
54
+ out.append(e)
55
+ except Exception:
56
+ return out
57
+ return out
58
+
59
+
60
+ def verify_state(v):
61
+ """verification.ts saveState 의 mac 검증 — stateMacPayload 와 바이트 동일 직렬화."""
62
+ if not isinstance(v, dict) or not isinstance(v.get('mac'), str):
63
+ return False
64
+ payload = json.dumps(
65
+ [v.get('phase'), v.get('targetId'), v.get('currentScore'), v.get('passed'),
66
+ bool(v.get('forcedPass')), v.get('adjustedScore'), v.get('scoredAt'), v.get('changeFingerprint')],
67
+ separators=(',', ':'), ensure_ascii=False,
68
+ )
69
+ return _mac_ok(v['mac'], payload)
70
+
71
+
72
+ def _mac_ok(mac, payload):
73
+ try:
74
+ key = open(os.path.join(_attest_dir(), '.key'), 'rb').read()
75
+ except Exception:
76
+ return False
77
+ expected = hmac.new(key, payload.encode('utf-8'), hashlib.sha256).hexdigest()
78
+ return isinstance(mac, str) and hmac.compare_digest(mac, expected)
79
+
80
+
81
+ def _heads_path():
82
+ base = os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(os.path.expanduser('~'), '.routinecode', 'knowledge')
83
+ return os.path.join(base, 'task-heads.json')
84
+
85
+
86
+ def _git_top_head(d):
87
+ import subprocess
88
+ try:
89
+ top = subprocess.run(['git', '-C', d, 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=5)
90
+ if top.returncode != 0 or not top.stdout.strip():
91
+ return None, None
92
+ t = os.path.realpath(top.stdout.strip())
93
+ sha = subprocess.run(['git', '-C', t, 'rev-parse', 'HEAD'], capture_output=True, text=True, timeout=5).stdout.strip()
94
+ return t, (sha or None)
95
+ except Exception:
96
+ return None, None
97
+
98
+
99
+ def _repo_has_work(top):
100
+ """비무시 변경(추적 수정·미추적 비무시 파일)이 있으면 True — 진행 중인(커밋 안 된) 작업의 흔적.
101
+ status 실패·타임아웃은 True(fail-closed) — 판정 불가 시 기존 기록을 유지하는 쪽이 안전하다."""
102
+ out = _git_raw(['status', '--porcelain', '--untracked-files=normal'], top, timeout=10)
103
+ if out is None:
104
+ return True
105
+ return bool(out.strip())
106
+
107
+
108
+ _KEEP_COMMIT_WINDOW_MS = 24 * 3600 * 1000
109
+
110
+
111
+ def _advanced_by_commits_only(top, rec, at_ms):
112
+ """기록 HEAD(rec) 이후 HEAD 이동이 전부 'commit'(amend 포함)이고 rec 가 현재 HEAD 의 조상이며
113
+ 기록 시각(at_ms) 이후 24h 이내면 True — 진행 중 태스크가 커밋만 한 것(커밋 후 재시작 세탁 차단).
114
+ pull·merge·checkout·reset·rebase 가 하나라도 끼면 False(새 맥락 → 재기록)."""
115
+ import time as _t
116
+ if not rec or not isinstance(at_ms, (int, float)) or _t.time() * 1000 - at_ms > _KEEP_COMMIT_WINDOW_MS:
117
+ return False
118
+ if _git_raw(['merge-base', '--is-ancestor', rec, 'HEAD'], top, timeout=10) is None:
119
+ return False
120
+ out = _git_raw(['log', '-g', '--date=unix', '--format=%H%x09%gd%x09%gs', 'HEAD'], top, timeout=10)
121
+ if not out:
122
+ return False
123
+ for line in out.splitlines():
124
+ parts = line.split('\t', 2)
125
+ if len(parts) < 3:
126
+ return False
127
+ h, gd, gs = parts
128
+ if h == rec:
129
+ return True # 기록 HEAD 에 도달 — 그 이후 이동은 모두 commit 이었음
130
+ try:
131
+ ts = int(gd[gd.index('{') + 1:gd.index('}')])
132
+ except Exception:
133
+ return False
134
+ if ts * 1000 < at_ms - 1000 or not gs.startswith('commit'):
135
+ return False
136
+ return False
137
+
138
+
139
+ def record_task_heads(dirs, overwrite=False, keep_if_dirty=False):
140
+ """레포별 '다음 태스크 기준 HEAD' 기록 — 새 세션 startup(진행 중 태스크 없을 때)·태스크 완료 시점에 overwrite=True."""
141
+ p = _heads_path()
142
+ try:
143
+ heads = json.load(open(p))
144
+ if not isinstance(heads, dict):
145
+ heads = {}
146
+ except Exception:
147
+ heads = {}
148
+ import time as _t
149
+ at = heads.get('__at__') if isinstance(heads.get('__at__'), dict) else {}
150
+ for d in dirs:
151
+ top, sha = _git_top_head(d)
152
+ if top and sha and (overwrite or top not in heads):
153
+ # 세션 재시작(startup)인데 이미 기록이 있고 레포에 미커밋 작업이 있으면 진행 중 태스크 —
154
+ # 덮어쓰면 Bash 전용 작업의 산출물이 '태스크 시작 이전' 이 되어 기준선에 섞인다
155
+ # (HEAD 가 바뀌었으면 — 커밋·pull — 이전 태스크 맥락이 끝난 것이므로 새로 기록)
156
+ if keep_if_dirty and heads.get(top) == sha and _repo_has_work(top):
157
+ continue
158
+ # HEAD 가 바뀌었어도 기록 이후 이동이 커밋뿐이면 같은 태스크가 커밋한 것 — 유지
159
+ if keep_if_dirty and heads.get(top) and heads.get(top) != sha and \
160
+ _advanced_by_commits_only(top, heads.get(top), at.get(top)):
161
+ continue
162
+ heads[top] = sha
163
+ at[top] = int(_t.time() * 1000) # 기록 시각 = 태스크 시작 기준 (지연 스냅샷이 이후 생긴 파일을 제외)
164
+ heads['__at__'] = at
165
+ try:
166
+ os.makedirs(os.path.dirname(p), exist_ok=True)
167
+ json.dump(heads, open(p, 'w'))
168
+ except Exception:
169
+ pass
170
+
171
+
172
+ def task_head_for(d):
173
+ """기록된(직전 완료·세션 시작) 기준 HEAD. 기록 없으면 None — 현재 HEAD 로 폴백하면
174
+ 첫 Edit 전 Bash 커밋이 기준선으로 세탁되므로 fail-closed (기준선 불가, 실패는 전부 계상)."""
175
+ top, _ = _git_top_head(d)
176
+ if not top:
177
+ return None, None
178
+ try:
179
+ rec = json.load(open(_heads_path())).get(top)
180
+ except Exception:
181
+ rec = None
182
+ return top, rec
183
+
184
+
185
+ def git_repos_under(d, depth=2):
186
+ """d 자신(레포 안이면 그 레포) + 하위 depth 단계의 git 레포 루트들."""
187
+ out = []
188
+ top, _ = _git_top_head(d)
189
+ if top:
190
+ out.append(d)
191
+ try:
192
+ lvl = [d]
193
+ for _ in range(depth):
194
+ nxt = []
195
+ for base in lvl:
196
+ for name in os.listdir(base):
197
+ if name.startswith('.') or name in ('node_modules', 'dist', 'build', 'venv', '__pycache__', 'target'):
198
+ continue
199
+ p = os.path.join(base, name)
200
+ if os.path.isdir(p):
201
+ if os.path.isdir(os.path.join(p, '.git')) or os.path.isfile(os.path.join(p, '.git')):
202
+ out.append(p)
203
+ else:
204
+ nxt.append(p)
205
+ lvl = nxt
206
+ except Exception:
207
+ pass
208
+ return out
209
+
210
+
211
+ # ── 태스크 시작 시점 로컬 환경 스냅샷 (HEAD 기준선 환경 재현용) ──────────────
212
+ # mcp-routinecode test-runner.ts restoreSnapshot 과 경로·manifest 규약 공유.
213
+ SNAP_FILE_MAX = 1024 * 1024
214
+ SNAP_MAX_FILES = 5000
215
+ SNAP_MAX_TOTAL = 100 * 1024 * 1024
216
+ _ENV_DIR_NAMES = ('venv', '.venv', '__pycache__', '.cache', '.turbo', '.tox', '.mypy_cache', '.pytest_cache')
217
+
218
+
219
+ def _kdir():
220
+ return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(os.path.expanduser('~'), '.routinecode', 'knowledge')
221
+
222
+
223
+ def snap_dir(top):
224
+ import hashlib as _h
225
+ import sys as _sys
226
+ key = top.lower() if (_sys.platform == 'darwin' or _sys.platform.startswith('win')) else top
227
+ return os.path.join(_kdir(), 'baseline-snap', _h.sha256(key.encode('utf-8')).hexdigest()[:16])
228
+
229
+
230
+ def task_window_start_ms():
231
+ """changeset.ts taskWindowStartMs 와 동일: max(마지막 완료, now - 창 상한)."""
232
+ import time
233
+ hours = float(os.environ.get('ROUTINECODE_TASK_WINDOW_HOURS') or 0) or 72.0
234
+ last = 0
235
+ try:
236
+ with open(os.path.join(_kdir(), 'verification', 'completions.jsonl'), 'rb') as fh:
237
+ fh.seek(0, 2)
238
+ size = fh.tell()
239
+ fh.seek(max(0, size - 8192))
240
+ for line in reversed(fh.read().decode('utf-8', 'ignore').strip().split('\n')):
241
+ try:
242
+ last = int(json.loads(line).get('ts') or 0)
243
+ break
244
+ except Exception:
245
+ continue
246
+ except Exception:
247
+ pass
248
+ return max(last, int(time.time() * 1000 - hours * 3600 * 1000))
249
+
250
+
251
+ def _is_skipped_local(rel):
252
+ parts = rel.rstrip('/').split('/')
253
+ return 'node_modules' in parts or '.git' in parts or any(p in _ENV_DIR_NAMES for p in parts)
254
+
255
+
256
+ def snapshot_local_files(top, force=False, created_before_ms=None):
257
+ """첫 편집 직전(PreToolUse) 레포의 무시·미추적 로컬 파일을 보존. 현재 태스크 창의 스냅샷이 있으면 생략.
258
+ created_before_ms: 지연 스냅샷(기준선 실행 시점)용 — 이 시각 이후 생기거나 바뀐 **비무시 미추적** 파일
259
+ (작업이 만든 코드·테스트)은 제외. 무시 파일은 그대로 (Bash 로만 바꾼 무시 파일은 §7.4 잔여위험)."""
260
+ import shutil
261
+ import time
262
+ d = snap_dir(top)
263
+ mf = os.path.join(d, 'manifest.json')
264
+ if not force:
265
+ try:
266
+ if int(json.load(open(mf)).get('createdAt') or 0) >= task_window_start_ms():
267
+ return False
268
+ except Exception:
269
+ pass
270
+ listed = set()
271
+ out = _git_raw(['ls-files', '-oi', '--exclude-standard', '--directory', '-z'], top) or ''
272
+ for rel in out.split('\0'):
273
+ if not rel or _is_skipped_local(rel):
274
+ continue
275
+ if rel.endswith('/'):
276
+ sub = _git_raw(['ls-files', '-oi', '--exclude-standard', '-z', '--', rel], top) or ''
277
+ listed.update(r for r in sub.split('\0') if r)
278
+ else:
279
+ listed.add(rel)
280
+ plain_untracked = set(r for r in (_git_raw(['ls-files', '-o', '--exclude-standard', '-z'], top) or '').split('\0') if r)
281
+ listed.update(plain_untracked)
282
+ tmp = d + '.tmp-%d' % os.getpid()
283
+ shutil.rmtree(tmp, ignore_errors=True)
284
+ os.makedirs(os.path.join(tmp, 'files'), exist_ok=True)
285
+ files, big, total, truncated = [], [], 0, False
286
+ for rel in sorted(listed):
287
+ if _is_skipped_local(rel):
288
+ continue
289
+ src = os.path.join(top, rel)
290
+ try:
291
+ st = os.stat(src)
292
+ except Exception:
293
+ continue
294
+ import stat as _st
295
+ if not _st.S_ISREG(st.st_mode):
296
+ continue
297
+ # ctime 포함: cp -p·tar·touch 로 mtime 을 과거로 보존해도 ctime 은 복사 시각으로 남는다
298
+ if created_before_ms is not None and rel in plain_untracked and max(st.st_mtime, st.st_ctime) * 1000 >= created_before_ms:
299
+ continue # 태스크 시작 이후 생긴 미추적 파일 = 작업 산출물 (기준선에 넣으면 그 실패가 '기존 실패'로 세탁됨)
300
+ if st.st_size <= SNAP_FILE_MAX and len(files) < SNAP_MAX_FILES and total + st.st_size <= SNAP_MAX_TOTAL:
301
+ dst = os.path.join(tmp, 'files', rel)
302
+ try:
303
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
304
+ shutil.copyfile(src, dst)
305
+ files.append(rel)
306
+ total += st.st_size
307
+ except Exception:
308
+ truncated = True
309
+ else:
310
+ # 큰 파일·상한 초과: 크기·mtime 만 기록 → 기준선 시점에 변하지 않았으면 링크, 바뀌었으면 환경 불완전
311
+ big.append({'rel': rel, 'size': st.st_size, 'mtimeMs': int(st.st_mtime * 1000)})
312
+ with open(os.path.join(tmp, 'manifest.json'), 'w') as fh:
313
+ json.dump({'v': 1, 'top': top, 'createdAt': int(time.time() * 1000), 'files': files, 'big': big,
314
+ 'truncated': truncated, 'lazy': created_before_ms is not None, 'cutoff': created_before_ms}, fh)
315
+ shutil.rmtree(d, ignore_errors=True)
316
+ os.makedirs(os.path.dirname(d), exist_ok=True)
317
+ os.rename(tmp, d)
318
+ return True
319
+
320
+
321
+ def verify_classification(c):
322
+ """verification.ts classificationMacPayload 검증."""
323
+ if not isinstance(c, dict):
324
+ return False
325
+ payload = json.dumps(['classification', c.get('taskId'), c.get('tier'), c.get('inputsHash')],
326
+ separators=(',', ':'), ensure_ascii=False)
327
+ return _mac_ok(c.get('mac'), payload)
328
+
329
+
330
+ def tracker_state(tracker_path):
331
+ """(files, last_edit_ms) — 마지막 편집 = tracker ts 최댓값(없으면 파일 mtime)."""
332
+ try:
333
+ t = json.load(open(tracker_path))
334
+ except Exception:
335
+ return [], 0
336
+ files = [f for f in t.get('files', []) if isinstance(f, str)]
337
+ ts = t.get('ts') if isinstance(t.get('ts'), dict) else {}
338
+ last = 0
339
+ for f in files:
340
+ v = ts.get(f)
341
+ if not isinstance(v, (int, float)):
342
+ try:
343
+ v = os.path.getmtime(f) * 1000
344
+ except OSError:
345
+ v = 0
346
+ last = max(last, int(v))
347
+ return files, last
348
+
349
+
350
+ _ROOT_MARKERS = ('package.json', 'pyproject.toml', 'setup.py', 'go.mod', 'Cargo.toml', 'pom.xml',
351
+ 'build.gradle', 'build.gradle.kts')
352
+
353
+
354
+ def _package_root(f):
355
+ d = os.path.dirname(f)
356
+ for _ in range(12):
357
+ if any(os.path.exists(os.path.join(d, m)) for m in _ROOT_MARKERS):
358
+ return os.path.realpath(d)
359
+ parent = os.path.dirname(d)
360
+ if parent == d:
361
+ break
362
+ d = parent
363
+ return None
364
+
365
+
366
+ def _has_build_target(root):
367
+ """routines.ts detectBuildCommand 와 같은 판정 (빌드 대상 존재 여부만)."""
368
+ pkg = os.path.join(root, 'package.json')
369
+ if os.path.exists(pkg):
370
+ try:
371
+ sc = (json.load(open(pkg)).get('scripts') or {})
372
+ return bool(sc.get('build') or sc.get('typecheck'))
373
+ except Exception:
374
+ return False
375
+ return any(os.path.exists(os.path.join(root, m)) for m in (
376
+ 'Cargo.toml', 'go.mod', 'build.gradle', 'build.gradle.kts', 'pom.xml', 'pyproject.toml',
377
+ 'setup.py', 'Makefile', 'CMakeLists.txt', 'Package.swift'))
378
+
379
+
380
+ def _related(a, b):
381
+ return a == b or a.startswith(b + os.sep) or b.startswith(a + os.sep)
382
+
383
+
384
+ def build_status(tracker_path):
385
+ """서명된 build attestation 기준 빌드 상태: 'true' | 'false' | 'unknown' | 'na'.
386
+ 변경 파일의 패키지 루트 중 빌드 대상이 있는 루트마다, 그 루트와 관련된(조상/자손) 실빌드 중
387
+ 마지막 편집 이후 시작된 최신 결과가 성공이어야 'true'. 빌드 대상 루트가 없으면 'na'(채점기와 동일)."""
388
+ import time
389
+ files, last = tracker_state(tracker_path)
390
+ roots = sorted({r for r in (_package_root(f) for f in files) if r})
391
+ build_roots = [r for r in roots if _has_build_target(r)]
392
+ if files and not build_roots:
393
+ return 'na'
394
+ since = int(time.time() * 1000) - 24 * 3600 * 1000
395
+ rows = []
396
+ for a in read_attestations(since_ms=since, kinds=['build']):
397
+ d = a.get('detail') or {}
398
+ if not any(d.get(k) is not None for k in ('backend', 'frontend', 'standalone')):
399
+ continue
400
+ if int(d.get('startedAt') or a.get('ts') or 0) < last:
401
+ continue
402
+ rows.append(a)
403
+ rows.sort(key=lambda a: a.get('ts', 0))
404
+ if not build_roots:
405
+ # 변경 기록 없음 — 최신 실빌드 기준 (없으면 unknown)
406
+ return ('true' if rows[-1].get('success') else 'false') if rows else 'unknown'
407
+ status = 'true'
408
+ for r in build_roots:
409
+ rel = [a for a in rows if a.get('projectDir') and _related(os.path.realpath(a['projectDir']), r)]
410
+ if not rel:
411
+ return 'unknown'
412
+ if not rel[-1].get('success'):
413
+ status = 'false'
414
+ return status
415
+
416
+
417
+ ENTRY_HASH_MAX_FILES = 20000 # changeset.ts 와 동일
418
+
419
+
420
+ def _stream_hash(p):
421
+ import hashlib as _h
422
+ h = _h.sha256()
423
+ with open(p, 'rb') as fh:
424
+ while True:
425
+ b = fh.read(1 << 20)
426
+ if not b:
427
+ break
428
+ h.update(b)
429
+ return h.hexdigest()
430
+
431
+
432
+ def _file_hash(p):
433
+ """changeset.ts fileHash/entryHash 와 바이트 동일 (스트리밍·디렉터리 재귀·중첩 레포 ls-files·링크·상한)."""
434
+ try:
435
+ return _entry_hash(p, [0], 0)
436
+ except Exception:
437
+ return 'missing'
438
+
439
+
440
+ def _entry_hash(p, budget, link_depth):
441
+ import hashlib as _h
442
+ import stat as _st
443
+ try:
444
+ lst = os.lstat(p)
445
+ except Exception:
446
+ return 'missing'
447
+ if _st.S_ISLNK(lst.st_mode):
448
+ try:
449
+ target = os.readlink(p)
450
+ except Exception:
451
+ target = ''
452
+ inner = 'missing'
453
+ if link_depth < 8:
454
+ try:
455
+ os.stat(p)
456
+ inner = _entry_hash(os.path.realpath(p), budget, link_depth + 1)
457
+ except Exception:
458
+ inner = 'missing'
459
+ return _h.sha256(('link\0' + target + '\0' + inner).encode('utf-8')).hexdigest()
460
+ if _st.S_ISDIR(lst.st_mode):
461
+ kind = 'dir'
462
+ names = None
463
+ if os.path.exists(os.path.join(p, '.git')):
464
+ out = _git_raw(['ls-files', '-co', '--exclude-standard', '-z'], p)
465
+ if out is not None:
466
+ kind = 'repo'
467
+ names = sorted(n[:-1] if n.endswith('/') else n for n in out.split('\0') if n)
468
+ if names is None:
469
+ try:
470
+ names = sorted(n for n in os.listdir(p) if n != '.git')
471
+ except Exception:
472
+ return 'missing'
473
+ lines = []
474
+ for n in names:
475
+ budget[0] += 1
476
+ if budget[0] > ENTRY_HASH_MAX_FILES:
477
+ return 'toobig'
478
+ h = _entry_hash(os.path.join(p, n), budget, link_depth)
479
+ if h == 'toobig':
480
+ return 'toobig'
481
+ lines.append(n + '\t' + h)
482
+ return _h.sha256((kind + '\0' + '\n'.join(lines)).encode('utf-8')).hexdigest()
483
+ if not _st.S_ISREG(lst.st_mode):
484
+ return 'special'
485
+ try:
486
+ return _stream_hash(p)
487
+ except Exception:
488
+ return 'missing'
489
+
490
+
491
+ STATUS_CAP_BYTES = 32 * 1024 * 1024 # changeset.ts STATUS_CAP_BYTES 와 동일
492
+ # changeset.ts GIT_SAFE 와 동일 — 저장소 설정으로 git status 의 변경 감지를 끄는 우회 차단
493
+ GIT_SAFE = ['--no-replace-objects', '-c', 'core.fsmonitor=false', '-c', 'core.trustctime=true', '-c', 'core.checkStat=default',
494
+ '-c', 'core.ignoreStat=false', '-c', 'core.untrackedCache=false']
495
+
496
+
497
+ def _hidden_by_index_flags(top):
498
+ """changeset.ts hiddenByIndexFlags 와 동일: assume-unchanged(소문자 태그)·skip-worktree(S)."""
499
+ import subprocess
500
+ try:
501
+ out = subprocess.run(['git'] + GIT_SAFE + ['-C', top, 'ls-files', '-v', '-z'], capture_output=True, text=True, timeout=60).stdout
502
+ except Exception:
503
+ return []
504
+ res = []
505
+ for tok in out.split('\0'):
506
+ if len(tok) < 3:
507
+ continue
508
+ tag = tok[0]
509
+ if tag == 'S' or ('a' <= tag <= 'z'):
510
+ res.append(tok[2:])
511
+ return sorted(res)
512
+
513
+
514
+ def _git_raw(args, cwd, input_text=None, timeout=60):
515
+ import subprocess
516
+ try:
517
+ r = subprocess.run(['git'] + GIT_SAFE + ['-C', cwd] + args, capture_output=True, text=True,
518
+ timeout=timeout, input=input_text)
519
+ return r.stdout if r.returncode == 0 else None
520
+ except Exception:
521
+ return None
522
+
523
+
524
+ def _git_config_raw(key, cwd):
525
+ """changeset.ts gitConfigRaw — GIT_SAFE 오버라이드 없이 실제 설정값."""
526
+ import subprocess
527
+ try:
528
+ r = subprocess.run(['git', '-C', cwd, 'config', '--get', key], capture_output=True, text=True, timeout=5)
529
+ return r.stdout.strip() if r.returncode == 0 else ''
530
+ except Exception:
531
+ return ''
532
+
533
+
534
+ def _repo_of(f):
535
+ """changeset.ts repoOf 와 동일: ('repo'|'redirect'|'outside', top)."""
536
+ import sys as _sys
537
+ out = _git_raw(['rev-parse', '--show-toplevel'], os.path.dirname(f), timeout=5)
538
+ top = (out or '').strip()
539
+ if not top:
540
+ return 'outside', None
541
+ real_top = os.path.realpath(top)
542
+ cands = [os.path.abspath(f)]
543
+ try:
544
+ cands.append(os.path.join(os.path.realpath(os.path.dirname(f)), os.path.basename(f)))
545
+ except Exception:
546
+ pass
547
+ try:
548
+ cands.append(os.path.realpath(f))
549
+ except Exception:
550
+ pass
551
+ ci = _sys.platform == 'darwin' or _sys.platform.startswith('win')
552
+ norm = (lambda x: x.lower()) if ci else (lambda x: x)
553
+ roots = [norm(r) + os.sep for r in (real_top, os.path.abspath(top))]
554
+ if any(norm(c).startswith(r) for c in cands for r in roots):
555
+ return 'repo', real_top
556
+ if _git_config_raw('core.worktree', os.path.dirname(f)):
557
+ return 'redirect', real_top
558
+ return 'repo', real_top
559
+
560
+
561
+ def _filtered_files(top):
562
+ """changeset.ts filteredFiles 와 동일."""
563
+ lst = _git_raw(['ls-files', '-z'], top)
564
+ if not lst:
565
+ return []
566
+ out = _git_raw(['check-attr', '--stdin', '-z', 'filter'], top, input_text=lst)
567
+ if out is None:
568
+ return []
569
+ t = out.split('\0')
570
+ res = []
571
+ driver = {}
572
+ i = 0
573
+ while i + 2 < len(t):
574
+ v = t[i + 2]
575
+ if v not in ('unspecified', 'unset', '', 'set'):
576
+ if v not in driver:
577
+ driver[v] = bool(_git_config_raw('filter.%s.clean' % v, top) or _git_config_raw('filter.%s.process' % v, top))
578
+ if driver[v]:
579
+ res.append(t[i])
580
+ i += 3
581
+ return sorted(res)
582
+
583
+
584
+ def _repo_config_hash(top):
585
+ """changeset.ts repoConfigHash 와 바이트 동일."""
586
+ import hashlib as _h
587
+ h = _h.sha256()
588
+ git_dir = (_git_raw(['rev-parse', '--absolute-git-dir'], top, timeout=5) or '').strip()
589
+ for name in ('config', os.path.join('info', 'attributes')):
590
+ h.update((name + '\0').encode('utf-8'))
591
+ try:
592
+ with open(os.path.join(git_dir, name), 'rb') as fh:
593
+ h.update(fh.read())
594
+ except Exception:
595
+ pass
596
+ h.update(b'\0')
597
+ h.update(b'replace\0')
598
+ h.update((_git_raw(['for-each-ref', '--format=%(refname) %(objectname)', 'refs/replace'], top, timeout=10) or '').encode('utf-8'))
599
+ return h.hexdigest()
600
+
601
+
602
+ class _FpState:
603
+ oversize = []
604
+ redirect = []
605
+
606
+
607
+ _fp_state = _FpState()
608
+
609
+
610
+ def change_fingerprint(files):
611
+ import hashlib as _h
612
+ entries = fingerprint_entries(files)
613
+ # 호출측(hook·테스트) 호환: 직전 계산의 과대/리다이렉트 목록을 함수 속성으로 노출
614
+ change_fingerprint.oversize = list(_fp_state.oversize)
615
+ change_fingerprint.redirect = list(_fp_state.redirect)
616
+ return _h.sha256('\n'.join(entries).encode('utf-8')).hexdigest()
617
+
618
+
619
+ def fingerprint_entries(files):
620
+ """mcp-routinecode changeset.ts changeFingerprint 와 바이트 동일 알고리즘."""
621
+ import subprocess
622
+ tops, outside, entries = set(), [], []
623
+ redirect = []
624
+ for f in files:
625
+ kind, t = _repo_of(f)
626
+ if kind == 'repo':
627
+ tops.add(t)
628
+ else:
629
+ outside.append(f)
630
+ if kind == 'redirect':
631
+ redirect.append(f)
632
+ _fp_state.redirect = sorted(set(redirect))
633
+ for f in _fp_state.redirect:
634
+ entries.append('REDIRECT\t' + f)
635
+ _fp_state.oversize = []
636
+ for top in sorted(tops):
637
+ try:
638
+ head = subprocess.run(['git'] + GIT_SAFE + ['-C', top, 'rev-parse', 'HEAD'], capture_output=True, text=True, timeout=5)
639
+ head_sha = head.stdout.strip() if head.returncode == 0 else ''
640
+ except Exception:
641
+ head_sha = ''
642
+ entries.append(top + '\tHEAD\t' + head_sha)
643
+ entries.append(top + '\tCFG\t' + _repo_config_hash(top))
644
+ for f in _filtered_files(top):
645
+ entries.append(top + '\tFILTER\t' + f + '\t' + _file_hash(os.path.join(top, f)))
646
+ try:
647
+ out = subprocess.run(['git'] + GIT_SAFE + ['-C', top, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=none'],
648
+ capture_output=True, text=True, timeout=60).stdout
649
+ except Exception:
650
+ out = ''
651
+ cap = int(os.environ.get('ROUTINECODE_STATUS_CAP_BYTES') or 0) or STATUS_CAP_BYTES
652
+ if len(out.encode('utf-8')) > cap:
653
+ entries.append(top + '\tOVERSIZE\t-')
654
+ _fp_state.oversize.append(top)
655
+ continue
656
+ for f in _hidden_by_index_flags(top):
657
+ entries.append(top + '\tFLAG\t' + f + '\t' + _file_hash(os.path.join(top, f)))
658
+ toks = out.split('\0')
659
+ i = 0
660
+ while i < len(toks):
661
+ tok = toks[i]
662
+ if len(tok) >= 4:
663
+ x, pth = tok[0], tok[3:]
664
+ if x in ('R', 'C'):
665
+ i += 1
666
+ entries.append(top + '\t' + pth + '\t' + _file_hash(os.path.join(top, pth)))
667
+ i += 1
668
+ for f in sorted(outside):
669
+ rp = os.path.realpath(f) if os.path.exists(f) else f
670
+ entries.append('-\t' + rp + '\t' + _file_hash(f))
671
+ for f in sorted(set(files)):
672
+ entries.append('TRACK\t' + f + '\t' + _file_hash(f))
673
+ for e in entries:
674
+ if e.endswith('\ttoobig'):
675
+ _fp_state.oversize.append(' '.join(e.split('\t')[:2]))
676
+ import hashlib as _h
677
+ return sorted(entries)
678
+
679
+
680
+ def is_local_host(host):
681
+ """verification.ts isLocalTestHost 와 동일 규칙 — IP 는 실제 IP 로 파싱해 대역 검사
682
+ (정규식 접두 매칭은 127.evil.example 같은 도메인을 통과시킴)."""
683
+ import ipaddress
684
+ if not isinstance(host, str) or not host:
685
+ return False
686
+ h = host.lower().strip('[]').rstrip('.')
687
+ extra = [x.strip().lower() for x in os.environ.get('ROUTINECODE_TEST_HOSTS', '').split(',') if x.strip()]
688
+ if h in extra:
689
+ return True
690
+ try:
691
+ ip = ipaddress.ip_address(h)
692
+ return ip.is_loopback or ip.is_private or ip.is_unspecified or ip.is_link_local
693
+ except ValueError:
694
+ pass
695
+ return h in ('localhost', 'host.docker.internal') or h.endswith('.localhost') or h.endswith('.local')