@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.
Files changed (244) hide show
  1. package/README.md +2 -2
  2. package/bin/cli.sh +23 -0
  3. package/bin/prompt-vault.dat +1 -0
  4. package/bin/prompt-vault.js +51 -1
  5. package/bin/rc-board.js +58 -0
  6. package/bin/rc-config.js +756 -1
  7. package/bin/rc-credit-turn.js +2 -1
  8. package/bin/rc-grant.js +2 -1
  9. package/bin/rc-login.js +2 -0
  10. package/bin/rc-map.js +132 -0
  11. package/bin/rc-privacy.js +200 -0
  12. package/bin/rc-skills.js +31 -0
  13. package/bin/rc-team.js +2 -1
  14. package/bin/setup.js +4 -0
  15. package/hooks/cc-compat-watch.js +2 -1
  16. package/hooks/claim-questions.json +40 -0
  17. package/hooks/hooks-config.json +108 -1
  18. package/hooks/lib/agent_budget.py +122 -0
  19. package/hooks/lib/agent_telemetry.py +143 -0
  20. package/hooks/lib/attest_reader.py +15 -6
  21. package/hooks/lib/attribution_judge.py +109 -0
  22. package/hooks/lib/board-golden.json +268 -0
  23. package/hooks/lib/board.py +503 -0
  24. package/hooks/lib/board_sync.py +535 -0
  25. package/hooks/lib/cc-surface.json +1 -1
  26. package/hooks/lib/claim_structure.py +412 -0
  27. package/hooks/lib/completion_log.py +12 -5
  28. package/hooks/lib/config_bash_track.py +114 -28
  29. package/hooks/lib/config_guard.py +137 -5
  30. package/hooks/lib/edit_tracker.py +182 -0
  31. package/hooks/lib/error_line.py +94 -0
  32. package/hooks/lib/escalation_restore.py +66 -0
  33. package/hooks/lib/i18n.py +37 -15
  34. package/hooks/lib/knowledge_items.py +1407 -0
  35. package/hooks/lib/knowledge_scope.py +123 -0
  36. package/hooks/lib/known_solution.py +37 -9
  37. package/hooks/lib/log_compact.py +85 -0
  38. package/hooks/lib/metacog_signals.py +228 -0
  39. package/hooks/lib/orch_decision.py +690 -0
  40. package/hooks/lib/premise-golden.json +96 -0
  41. package/hooks/lib/presence.py +10 -3
  42. package/hooks/lib/privacy_log.py +35 -0
  43. package/hooks/lib/receipt.py +137 -14
  44. package/hooks/lib/review_gate.py +83 -0
  45. package/hooks/lib/routine_skill_eval.py +213 -0
  46. package/hooks/lib/secret_filter.py +2 -1
  47. package/hooks/lib/skill_drafts.py +188 -0
  48. package/hooks/lib/sync_manager.py +121 -26
  49. package/hooks/lib/usage_v2.py +680 -0
  50. package/hooks/lib/work_kind.py +198 -0
  51. package/hooks/lib/work_kind_events.py +361 -0
  52. package/hooks/pending-drainer.sh +28 -0
  53. package/hooks/post-agent-budget.sh +50 -0
  54. package/hooks/post-agent-return.sh +89 -3
  55. package/hooks/post-bash-failure.sh +39 -0
  56. package/hooks/post-bash-knowledge.sh +15 -34
  57. package/hooks/post-bash-verify.sh +33 -16
  58. package/hooks/post-build-check.sh +16 -18
  59. package/hooks/post-config-context.sh +13 -0
  60. package/hooks/post-delegation-nudge.sh +12 -1
  61. package/hooks/post-edit-track.sh +19 -28
  62. package/hooks/post-orch-decision.sh +35 -0
  63. package/hooks/post-read-config-context.sh +20 -0
  64. package/hooks/pre-account-guard.sh +1 -1
  65. package/hooks/pre-agent-spawn.mjs +2 -1
  66. package/hooks/pre-agent-spawn.sh +12 -1
  67. package/hooks/pre-bash-guard.sh +61 -3
  68. package/hooks/pre-bash-knowledge.sh +46 -0
  69. package/hooks/pre-credit-guard.sh +1 -1
  70. package/hooks/pre-edit-board.sh +44 -0
  71. package/hooks/pre-edit-check.sh +29 -5
  72. package/hooks/pre-edit-config-gate.sh +1 -1
  73. package/hooks/pre-edit-domain-gate.sh +23 -22
  74. package/hooks/pre-mark-complete.sh +32 -4
  75. package/hooks/pre-read-knowledge-inject.sh +34 -24
  76. package/hooks/pre-review-gate.sh +17 -0
  77. package/hooks/recorder-runner.sh +25 -2
  78. package/hooks/session-start-compact.sh +28 -0
  79. package/hooks/session-start.sh +167 -19
  80. package/hooks/skill-knowledge.sh +37 -0
  81. package/hooks/stop-claim-check.v3.sh +21 -3
  82. package/hooks/stop-usage-metrics.sh +138 -83
  83. package/hooks/subagent-stop-usage.sh +25 -0
  84. package/hooks/user-prompt-submit.sh +10 -4
  85. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  86. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  87. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  88. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  89. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  90. package/mcp-db-manager/dist/index.js +1 -1
  91. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  92. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  93. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  94. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  95. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  96. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  97. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  98. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  99. package/mcp-dev-tester/dist/attestation.js +1 -1
  100. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  101. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  102. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  103. package/mcp-dev-tester/dist/index.js +1 -1
  104. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  105. package/mcp-doc-fetcher/dist/index.js +1 -1
  106. package/mcp-html-renderer/dist/index.js +1 -1
  107. package/mcp-html-renderer/dist/preview.js +1 -1
  108. package/mcp-html-renderer/dist/template-engine.js +1 -1
  109. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  110. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  111. package/mcp-intelligence/dist/config-auth.js +1 -1
  112. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  113. package/mcp-intelligence/dist/domain-templates.js +1 -1
  114. package/mcp-intelligence/dist/grounding.js +1 -1
  115. package/mcp-intelligence/dist/handlers.js +1 -1
  116. package/mcp-intelligence/dist/index.js +1 -1
  117. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  118. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  119. package/mcp-intelligence/dist/knowledge-guide.js +1 -0
  120. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  121. package/mcp-intelligence/dist/knowledge-migrate.js +1 -0
  122. package/mcp-intelligence/dist/knowledge-record.js +1 -0
  123. package/mcp-intelligence/dist/knowledge-scope.js +1 -0
  124. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  125. package/mcp-intelligence/dist/provenance.js +1 -1
  126. package/mcp-intelligence/dist/sanitize.generated.js +242 -0
  127. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  128. package/mcp-log-watcher/dist/config-auth.js +1 -1
  129. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  130. package/mcp-log-watcher/dist/index.js +1 -1
  131. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  132. package/mcp-log-watcher/dist/log-store.js +1 -1
  133. package/mcp-log-watcher/dist/sanitize.generated.js +242 -0
  134. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  135. package/mcp-log-watcher/package.json +1 -1
  136. package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
  137. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  138. package/mcp-plan-manager/dist/file-ops.js +1 -1
  139. package/mcp-plan-manager/dist/index.js +1 -1
  140. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  141. package/mcp-project-context/dist/git-ops.js +1 -1
  142. package/mcp-project-context/dist/index.js +1 -1
  143. package/mcp-project-context/dist/project-analysis.js +1 -1
  144. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  145. package/mcp-routinecode/dist/analysis-ledger.js +590 -0
  146. package/mcp-routinecode/dist/attestation.js +1 -1
  147. package/mcp-routinecode/dist/blast-radius.js +1 -1
  148. package/mcp-routinecode/dist/board.js +1 -0
  149. package/mcp-routinecode/dist/build-id.js +1 -0
  150. package/mcp-routinecode/dist/changeset.js +1 -1
  151. package/mcp-routinecode/dist/config-auth.js +1 -1
  152. package/mcp-routinecode/dist/config-map/applied.js +1 -0
  153. package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
  154. package/mcp-routinecode/dist/config-map/architect-store.js +1132 -1
  155. package/mcp-routinecode/dist/config-map/assign.js +1 -1
  156. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  157. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  158. package/mcp-routinecode/dist/config-map/blocks.js +1 -1
  159. package/mcp-routinecode/dist/config-map/briefing.js +541 -1
  160. package/mcp-routinecode/dist/config-map/certify.js +10 -5
  161. package/mcp-routinecode/dist/config-map/const-use.js +1 -1
  162. package/mcp-routinecode/dist/config-map/context.js +219 -0
  163. package/mcp-routinecode/dist/config-map/convention-candidates.js +1 -0
  164. package/mcp-routinecode/dist/config-map/decisions.js +1 -1
  165. package/mcp-routinecode/dist/config-map/decls.js +1 -1
  166. package/mcp-routinecode/dist/config-map/drift.js +1 -1
  167. package/mcp-routinecode/dist/config-map/dup-safety.js +1 -1
  168. package/mcp-routinecode/dist/config-map/extract.js +1 -1
  169. package/mcp-routinecode/dist/config-map/field-contract.js +1 -1
  170. package/mcp-routinecode/dist/config-map/gate.js +796 -1
  171. package/mcp-routinecode/dist/config-map/hash.js +1 -1
  172. package/mcp-routinecode/dist/config-map/ident-norm.js +1 -1
  173. package/mcp-routinecode/dist/config-map/index-store.js +1051 -1
  174. package/mcp-routinecode/dist/config-map/light-eval.js +253 -1
  175. package/mcp-routinecode/dist/config-map/link.js +1 -1
  176. package/mcp-routinecode/dist/config-map/linked-repos.js +1 -1
  177. package/mcp-routinecode/dist/config-map/lookup.js +1 -1
  178. package/mcp-routinecode/dist/config-map/louvain.js +1 -1
  179. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  180. package/mcp-routinecode/dist/config-map/names.js +1 -1
  181. package/mcp-routinecode/dist/config-map/post-bash-eval.js +105 -0
  182. package/mcp-routinecode/dist/config-map/proposals.js +1 -1
  183. package/mcp-routinecode/dist/config-map/ratchet.js +148 -0
  184. package/mcp-routinecode/dist/config-map/recheck.js +148 -1
  185. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  186. package/mcp-routinecode/dist/config-map/route-security.js +1 -1
  187. package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
  188. package/mcp-routinecode/dist/config-map/scc.js +1 -1
  189. package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
  190. package/mcp-routinecode/dist/config-map/shape.js +1 -1
  191. package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
  192. package/mcp-routinecode/dist/config-map/sole-impl.js +1 -1
  193. package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
  194. package/mcp-routinecode/dist/config-map/store.js +1 -1
  195. package/mcp-routinecode/dist/config-map/swagger-check.js +1 -1
  196. package/mcp-routinecode/dist/config-map/task-eval.js +369 -1
  197. package/mcp-routinecode/dist/config-map/templates.js +1 -1
  198. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  199. package/mcp-routinecode/dist/coverage.js +1 -1
  200. package/mcp-routinecode/dist/edit-tracker.js +1 -0
  201. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  202. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  203. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  204. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  205. package/mcp-routinecode/dist/index.js +1 -1
  206. package/mcp-routinecode/dist/known-solutions.js +1 -1
  207. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  208. package/mcp-routinecode/dist/normalize-sig.js +1 -0
  209. package/mcp-routinecode/dist/observed-draft.js +1 -1
  210. package/mcp-routinecode/dist/observed-escalation.js +1 -0
  211. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  212. package/mcp-routinecode/dist/route-match.js +1 -1
  213. package/mcp-routinecode/dist/routines.js +1 -1
  214. package/mcp-routinecode/dist/rule-engine.js +1 -1
  215. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  216. package/mcp-routinecode/dist/sanitize.generated.js +242 -0
  217. package/mcp-routinecode/dist/session-registry.js +1 -0
  218. package/mcp-routinecode/dist/skill-pack/sync.js +629 -0
  219. package/mcp-routinecode/dist/skill-pack/validate.js +278 -0
  220. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  221. package/mcp-routinecode/dist/test-runner.js +1 -1
  222. package/mcp-routinecode/dist/verification.js +1 -1
  223. package/mcp-routinecode/dist/viral-loop.js +1 -1
  224. package/mcp-routinecode/package.json +1 -1
  225. package/package.json +3 -3
  226. package/plugin/.claude-plugin/plugin.json +1 -1
  227. package/plugin/agents/analyzer.md.sealed +1 -1
  228. package/plugin/agents/architect.md.sealed +1 -1
  229. package/plugin/agents/crawler.md.sealed +1 -1
  230. package/plugin/agents/explorer.md.sealed +1 -1
  231. package/plugin/agents/implementor.md.sealed +1 -1
  232. package/plugin/agents/looker.md.sealed +1 -1
  233. package/plugin/agents/planner.md.sealed +1 -1
  234. package/plugin/agents/recorder.md.sealed +1 -1
  235. package/plugin/agents/reviewer.md.sealed +1 -1
  236. package/plugin/agents/verifier.md.sealed +1 -1
  237. package/plugin/commands/analyze.md.sealed +1 -1
  238. package/plugin/commands/plan.md.sealed +1 -1
  239. package/plugin/commands/rc.md.sealed +1 -1
  240. package/plugin/commands/receipt.md.sealed +1 -1
  241. package/plugin/commands/recharge.md.sealed +1 -1
  242. package/plugin/commands/routines.md.sealed +1 -1
  243. package/plugin/commands/share.md.sealed +1 -1
  244. package/plugin/routinecode-prompt.md.sealed +1 -1
@@ -0,0 +1,535 @@
1
+ # -*- coding: utf-8 -*-
2
+ """팀 작업 현황(설계 33 §4.1, 클라 쪽) — 공유 판 이벤트·편집 접촉을 knowledge 서버로 올린다.
3
+
4
+ 흐름: board.append_event · post-edit-track.sh · (MCP) board.ts appendEvent
5
+ → <knowledge>/board-outbox.jsonl 에 전송 형식 그대로 한 줄 추가(핫 경로 = 파일 추가만)
6
+ → flush_background() 가 띄운 별도 프로세스가 POST {serverUrl}/api/v1/board/events 로 ≤200건씩 보낸다.
7
+
8
+ 지키는 것:
9
+ - 동의(설계 33 V2·V6): 지도 meta.json 의 repoId 가 형식에 맞고 detailOptIn 이 True, shared 가 False 아님 — 아니면 적재하지 않는다.
10
+ 지도 위치 = <configMapDir>/<sha1(realpath 메인 작업트리)[:16]>/meta.json (index-store.ts storeDirFor 와 같다).
11
+ - 보내는 것: 종류·시각·repoId·세션 앞 12자·과제 id·제목(비밀값 가림, ≤100자, post·claim 만)·막힘 범주·
12
+ 레포 기준 상대 경로(edit 만)·착지 증거 요약. 파일 내용·노트 본문·절대 경로는 보내지 않는다.
13
+ - 표준 라이브러리만, Python 3.9. 어떤 실패도 예외를 올리지 않는다(fail-open).
14
+ - ROUTINECODE_BOARD_SYNC=0 이면 적재·전송 모두 끈다.
15
+
16
+ CLI: python3 board_sync.py --flush → 대기열 전송(백그라운드 프로세스용)
17
+ """
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ import time
24
+ from datetime import datetime, timezone
25
+
26
+ HERE = os.path.dirname(os.path.abspath(__file__))
27
+ if HERE not in sys.path:
28
+ sys.path.insert(0, HERE)
29
+
30
+ OUTBOX_NAME = 'board-outbox.jsonl'
31
+ SENDING_NAME = 'board-outbox.sending.jsonl'
32
+ LOCK_NAME = 'board-outbox.lock'
33
+ FLUSH_LOCK_NAME = 'board-outbox.flush.lock'
34
+ FLUSH_STAMP = 'board-outbox.flush-at'
35
+ ENDPOINT = '/api/v1/board/events'
36
+ CONSENT_VERSION = 1
37
+ BATCH_MAX = 200
38
+ MAX_BATCHES_PER_FLUSH = 10
39
+ FLUSH_MIN_INTERVAL_S = 30
40
+ MAX_FILE_BYTES = 2 * 1024 * 1024
41
+ TIMEOUT_S = 5
42
+ TITLE_MAX = 100
43
+ PATH_MAX = 512
44
+
45
+ KINDS = ('task.post', 'task.claim', 'task.release', 'task.block', 'task.land', 'task.expire', 'note', 'edit')
46
+ BOARD_KINDS = KINDS[:-1]
47
+ REPO_ID_RE = re.compile(r'^[A-Za-z0-9_-]{1,64}$')
48
+ _CTRL_RE = re.compile(r'[\x00-\x1f\x7f]')
49
+ # 착지 증거 문자열 = '<kind>@<ISO>'(board.ts evidenceFor)
50
+ EVIDENCE_KINDS = ('build', 'tests', 'typecheck')
51
+
52
+
53
+ def enabled():
54
+ return os.environ.get('ROUTINECODE_BOARD_SYNC', '') != '0'
55
+
56
+
57
+ def knowledge_base():
58
+ return os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.join(
59
+ os.path.expanduser('~'), '.routinecode', 'knowledge')
60
+
61
+
62
+ def config_map_dir():
63
+ return os.environ.get('ROUTINECODE_CONFIG_MAP_DIR') or os.path.join(
64
+ os.path.expanduser('~'), '.routinecode', 'knowledge', 'config-map')
65
+
66
+
67
+ def outbox_path():
68
+ return os.path.join(knowledge_base(), OUTBOX_NAME)
69
+
70
+
71
+ # ── 레포·동의 ────────────────────────────────────────────────
72
+
73
+ def _realpath_loose(p):
74
+ """존재하는 가장 가까운 조상까지 realpath 하고 나머지를 붙인다(index-store.ts realpathLoose)."""
75
+ cur = os.path.abspath(p)
76
+ rest = []
77
+ for _ in range(64):
78
+ if os.path.exists(cur):
79
+ return os.path.join(os.path.realpath(cur), *reversed(rest))
80
+ parent = os.path.dirname(cur)
81
+ if parent == cur:
82
+ break
83
+ rest.append(os.path.basename(cur))
84
+ cur = parent
85
+ return os.path.abspath(p)
86
+
87
+
88
+ def find_toplevel(p):
89
+ """'.git'(폴더·파일)이 있는 가장 가까운 조상(index-store.ts findToplevel)."""
90
+ cur = _realpath_loose(p)
91
+ for _ in range(64):
92
+ if os.path.exists(os.path.join(cur, '.git')):
93
+ return cur
94
+ parent = os.path.dirname(cur)
95
+ if parent == cur:
96
+ return None
97
+ cur = parent
98
+ return None
99
+
100
+
101
+ def main_worktree_of(top):
102
+ """worktree 면 메인 작업트리, 아니면 None(index-store.ts mainWorktreeOf 와 같은 판정, git 실행 없음)."""
103
+ try:
104
+ dotgit = os.path.join(top, '.git')
105
+ if not os.path.isfile(dotgit):
106
+ return None
107
+ with open(dotgit, encoding='utf-8') as f:
108
+ m = re.search(r'^gitdir:\s*(.+?)\s*$', f.read(), re.M)
109
+ if not m:
110
+ return None
111
+ gitdir = os.path.normpath(os.path.join(top, m.group(1)))
112
+ if os.path.basename(os.path.dirname(gitdir)) != 'worktrees':
113
+ return None
114
+ with open(os.path.join(gitdir, 'commondir'), encoding='utf-8') as f:
115
+ cd = f.read().strip()
116
+ if not cd:
117
+ return None
118
+ common = os.path.normpath(os.path.join(gitdir, cd))
119
+ if os.path.basename(common) != '.git':
120
+ return None
121
+ main = os.path.dirname(common)
122
+ if os.path.realpath(os.path.join(main, '.git')) != os.path.realpath(common) or not os.path.isdir(common):
123
+ return None
124
+ return os.path.realpath(main)
125
+ except Exception:
126
+ return None
127
+
128
+
129
+ _META = {}
130
+
131
+
132
+ def repo_meta_for(file_or_dir):
133
+ """경로 → {'toplevel','repoId','detailOptIn','shared','allowed'} 또는 None(지도 밖). 프로세스 안 캐시."""
134
+ try:
135
+ top = find_toplevel(file_or_dir)
136
+ if not top:
137
+ return None
138
+ if top in _META:
139
+ return _META[top]
140
+ map_top = main_worktree_of(top) or top
141
+ store = os.path.join(config_map_dir(), hashlib.sha1(map_top.encode('utf-8')).hexdigest()[:16])
142
+ try:
143
+ with open(os.path.join(store, 'meta.json'), encoding='utf-8') as f:
144
+ meta = json.load(f)
145
+ if not isinstance(meta, dict):
146
+ meta = {}
147
+ except Exception:
148
+ meta = {}
149
+ rid = meta.get('repoId')
150
+ out = {
151
+ 'toplevel': top,
152
+ 'repoId': rid if isinstance(rid, str) else None,
153
+ 'detailOptIn': meta.get('detailOptIn') is True,
154
+ 'shared': meta.get('shared') is not False,
155
+ }
156
+ out['allowed'] = bool(out['repoId'] and REPO_ID_RE.match(out['repoId'])
157
+ and out['detailOptIn'] and out['shared'])
158
+ _META[top] = out
159
+ return out
160
+ except Exception:
161
+ return None
162
+
163
+
164
+ def _board_repo_path(d):
165
+ """판 폴더 → 레포 안 경로(판 기준 = git common dir 이면 그 부모)."""
166
+ try:
167
+ import board
168
+ base = board._DIR_BASE.get(d) or board._board_base(d)
169
+ except Exception:
170
+ base = None
171
+ if not base:
172
+ return None
173
+ if os.path.basename(base) == '.git':
174
+ return os.path.dirname(base)
175
+ # submodule 등 .git 내부 경로는 레포를 특정할 수 없다
176
+ if (os.sep + '.git' + os.sep) in (base + os.sep):
177
+ return None
178
+ return base
179
+
180
+
181
+ # ── 전송 형식 ────────────────────────────────────────────────
182
+
183
+ def mask_title(s):
184
+ if not isinstance(s, str) or not s:
185
+ return None
186
+ try:
187
+ import secret_filter
188
+ s = secret_filter.redact(s)[0]
189
+ except Exception:
190
+ pass
191
+ return s[:TITLE_MAX]
192
+
193
+
194
+ def block_reason(reason):
195
+ """막힘 이유 → 범주(본문은 보내지 않는다). 관찰 기반 3회 실패 = knowledge_items 의 '3회 실패: …'."""
196
+ r = str(reason or '')
197
+ if r.startswith('3회 실패') or '3strike' in r:
198
+ return 'observed-3strike'
199
+ if 'refuted' in r:
200
+ return 'refuted'
201
+ return 'manual'
202
+
203
+
204
+ def evidence_of(ev):
205
+ """착지 증거(['build@…','typecheck@…']) → {build?, tests?, typecheck?}. 시험 수를 모르면 tests 는 뺀다
206
+ (counts = {'pass','fail'} 를 아는 쪽이 넘긴다). 증거가 없으면 None, 있었으면 최소 {}."""
207
+ if not isinstance(ev, list) or not ev:
208
+ return None
209
+ out = {}
210
+ counts = None
211
+ for x in ev:
212
+ if isinstance(x, dict):
213
+ counts = x
214
+ continue
215
+ k = str(x).split('@', 1)[0]
216
+ if k in ('build', 'typecheck'):
217
+ out[k] = True
218
+ elif k == 'tests':
219
+ out['tests'] = None
220
+ if 'tests' in out:
221
+ if isinstance(counts, dict) and isinstance(counts.get('pass'), int) and isinstance(counts.get('fail'), int):
222
+ out['tests'] = {'pass': counts['pass'], 'fail': counts['fail']}
223
+ else:
224
+ del out['tests']
225
+ # 증거가 있던 착지는 시험 수를 몰라도 null 로 두지 않는다(서버는 증거 없는 착지를 완료로 보이지 않는다)
226
+ return out
227
+
228
+
229
+ def rel_path(top, file_path):
230
+ """레포 기준 상대 경로(posix). 밖·절대·'..'·제어문자·과다 길이는 None."""
231
+ try:
232
+ if not isinstance(file_path, str) or not file_path or _CTRL_RE.search(file_path):
233
+ return None
234
+ real = _realpath_loose(file_path)
235
+ rel = os.path.relpath(real, top)
236
+ rel = rel.replace(os.sep, '/')
237
+ if rel in ('.', '') or rel.startswith('/') or rel == '..' or rel.startswith('../') or '/../' in rel:
238
+ return None
239
+ if _CTRL_RE.search(rel) or len(rel) > PATH_MAX:
240
+ return None
241
+ return rel
242
+ except Exception:
243
+ return None
244
+
245
+
246
+ def wire_record(kind, at, repo_id, session, task=None, title=None, reason=None, path=None, evidence=None, topic=None):
247
+ """§4.1 이벤트 한 건 — 칸 순서 고정(board.ts boardOutboxRecord 와 같은 줄이 나온다).
248
+ reason: task.block = 이유 범주, note = 주제가 refuted 일 때만 'refuted'(본문 없음), 그 외 null."""
249
+ return {
250
+ 'id': None, 'kind': kind, 'at': at, 'repoId': repo_id, 'session': str(session or 'unknown')[:12],
251
+ 'task': task if isinstance(task, str) and task else None,
252
+ 'title': mask_title(title) if kind in ('task.post', 'task.claim') else None,
253
+ 'reason': block_reason(reason) if kind == 'task.block' else ('refuted' if kind == 'note' and topic == 'refuted' else None),
254
+ 'path': path if kind == 'edit' else None,
255
+ 'evidence': evidence if kind == 'task.land' else None,
256
+ }
257
+
258
+
259
+ def record_of_board_event(ev, repo_id, title=None):
260
+ """판 이벤트(board.py/board.ts 형식) → 전송 레코드. 제목은 task.post 는 data.title, claim 은 넘겨받은 것."""
261
+ d = ev.get('data') if isinstance(ev.get('data'), dict) else {}
262
+ kind = ev.get('kind')
263
+ if kind == 'task.post':
264
+ title = d.get('title')
265
+ rec = wire_record(kind, ev.get('at'), repo_id, (ev.get('by') or {}).get('session'), ev.get('task'),
266
+ title=title, reason=d.get('reason'), evidence=evidence_of(d.get('evidence')), topic=d.get('topic'))
267
+ rec['id'] = str(ev.get('id') or '')[:64] or None
268
+ return rec
269
+
270
+
271
+ def line_of(rec):
272
+ return json.dumps(rec, ensure_ascii=False, separators=(',', ':'))
273
+
274
+
275
+ # ── 대기열 ───────────────────────────────────────────────────
276
+
277
+ def _lock(blocking=True, name=LOCK_NAME):
278
+ from orch_decision import _Lock
279
+ return _Lock(knowledge_base(), blocking=blocking, name=name)
280
+
281
+
282
+ def _append_line(line):
283
+ from orch_decision import _cap_file
284
+ os.makedirs(knowledge_base(), exist_ok=True)
285
+ p = outbox_path()
286
+ with _lock():
287
+ with open(p, 'a', encoding='utf-8') as f:
288
+ f.write(line + '\n')
289
+ _cap_file(p, MAX_FILE_BYTES)
290
+
291
+
292
+ def enqueue(rec):
293
+ """완성된 전송 레코드를 대기열에 추가한다. 형식이 어긋나면 버린다. 성공 True."""
294
+ try:
295
+ if not enabled() or not isinstance(rec, dict):
296
+ return False
297
+ if rec.get('kind') not in KINDS or not rec.get('id') or not REPO_ID_RE.match(str(rec.get('repoId') or '')):
298
+ return False
299
+ if rec['kind'] == 'edit' and not rec.get('path'):
300
+ return False
301
+ _append_line(line_of(rec))
302
+ return True
303
+ except Exception:
304
+ return False
305
+
306
+
307
+ def _title_of_task(d, task):
308
+ try:
309
+ import board
310
+ t = board.fold(board.read_events(d))['tasks'].get(task) or {}
311
+ return t.get('title') or None
312
+ except Exception:
313
+ return None
314
+
315
+
316
+ def enqueue_board_event(d, ev):
317
+ """board.append_event 직후 — 판 폴더 d 의 레포가 동의했으면 적재."""
318
+ try:
319
+ if not enabled() or not isinstance(ev, dict) or ev.get('kind') not in BOARD_KINDS:
320
+ return False
321
+ rp = _board_repo_path(d)
322
+ meta = repo_meta_for(rp) if rp else None
323
+ if not meta or not meta['allowed']:
324
+ return False
325
+ title = _title_of_task(d, ev.get('task')) if ev.get('kind') == 'task.claim' else None
326
+ return enqueue(record_of_board_event(ev, meta['repoId'], title))
327
+ except Exception:
328
+ return False
329
+
330
+
331
+ def _now_iso():
332
+ return datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.') + '%03dZ' % (int(time.time() * 1000) % 1000)
333
+
334
+
335
+ def edit_id(session, rel, now=None):
336
+ minute = int((now if now is not None else time.time()) // 60)
337
+ raw = '%s%s%d' % (str(session or '')[:12], rel, minute)
338
+ return 'x' + hashlib.sha1(raw.encode('utf-8')).hexdigest()[:16]
339
+
340
+
341
+ def _claimed_task(file_path, session):
342
+ """이 세션이 그 레포 판에서 맡은 과제(가장 최근 선점). 모르면 None."""
343
+ try:
344
+ import board
345
+ mine = board.claims_of_session(board.board_dir(file_path), session)
346
+ mine = [c for c in mine if c.get('taskId')]
347
+ if not mine:
348
+ return None
349
+ mine.sort(key=lambda c: str(c.get('at') or ''))
350
+ return mine[-1].get('taskId')
351
+ except Exception:
352
+ return None
353
+
354
+
355
+ def enqueue_edit(session, file_path, now=None):
356
+ """편집 접촉 — 같은 세션·파일·분 은 한 번만(id 로 로컬·서버 모두 중복 제거)."""
357
+ try:
358
+ if not enabled() or not file_path:
359
+ return False
360
+ meta = repo_meta_for(file_path)
361
+ if not meta or not meta['allowed']:
362
+ return False
363
+ rel = rel_path(meta['toplevel'], file_path)
364
+ if not rel:
365
+ return False
366
+ sid = str(session or 'unknown')[:12]
367
+ eid = edit_id(sid, rel, now)
368
+ if _seen_recent(eid):
369
+ return False
370
+ rec = wire_record('edit', _now_iso(), meta['repoId'], sid, _claimed_task(file_path, sid), path=rel)
371
+ rec['id'] = eid
372
+ return enqueue(rec)
373
+ except Exception:
374
+ return False
375
+
376
+
377
+ def _seen_recent(eid, tail_bytes=64 * 1024):
378
+ """대기열 끝부분에 같은 id 가 있으면 True(1분 안 중복 편집 접촉)."""
379
+ for name in (OUTBOX_NAME, SENDING_NAME):
380
+ p = os.path.join(knowledge_base(), name)
381
+ try:
382
+ with open(p, 'rb') as f:
383
+ size = os.path.getsize(p)
384
+ if size > tail_bytes:
385
+ f.seek(size - tail_bytes)
386
+ if ('"id":"%s"' % eid).encode('utf-8') in f.read():
387
+ return True
388
+ except Exception:
389
+ continue
390
+ return False
391
+
392
+
393
+ # ── 전송 ─────────────────────────────────────────────────────
394
+
395
+ def _post(base, key, events):
396
+ """(status, body). 네트워크 실패는 (0, {})."""
397
+ import urllib.request
398
+ import urllib.error
399
+ data = json.dumps({'consentVersion': CONSENT_VERSION, 'events': events}, ensure_ascii=False).encode('utf-8')
400
+ req = urllib.request.Request(base + ENDPOINT, data=data, method='POST', headers={
401
+ 'Content-Type': 'application/json',
402
+ 'Authorization': 'Bearer ' + key,
403
+ })
404
+ try:
405
+ resp = urllib.request.urlopen(req, timeout=TIMEOUT_S)
406
+ body = resp.read().decode('utf-8', 'replace')
407
+ try:
408
+ return resp.status, json.loads(body or '{}')
409
+ except Exception:
410
+ return resp.status, {}
411
+ except urllib.error.HTTPError as e:
412
+ return e.code, {}
413
+ except Exception:
414
+ return 0, {}
415
+
416
+
417
+ def flush(post=None):
418
+ """대기열을 ≤200건씩 보낸다 → {'sent','dropped','status'}. post(body) 는 시험 주입용(body = 요청 본문 dict).
419
+ 전송 중 추가된 줄을 지우지 않게, 대기열을 '보내는 중' 파일로 옮긴 뒤 그것만 다룬다.
420
+ 성공 → 보낸 줄 제거, 400 → 다시 보내도 받지 않으니 버림, 그 외 → 남겨 다음에 다시."""
421
+ out = {'sent': 0, 'dropped': 0, 'status': 'idle'}
422
+ try:
423
+ if not enabled():
424
+ out['status'] = 'skip:disabled'
425
+ return out
426
+ from orch_decision import _read_lines, _write_lines
427
+ if post is None:
428
+ from orch_decision import _sync_config
429
+ base, key, ok = _sync_config()
430
+ if not ok or not base or not key:
431
+ out['status'] = 'skip:no-sync'
432
+ return out
433
+ post = lambda body: _post(base, key, body['events']) # noqa: E731
434
+ kb = knowledge_base()
435
+ if not os.path.isdir(kb):
436
+ return out
437
+ src = os.path.join(kb, OUTBOX_NAME)
438
+ sending = os.path.join(kb, SENDING_NAME)
439
+ with _lock(blocking=False, name=FLUSH_LOCK_NAME) as lk:
440
+ if not lk.ok:
441
+ out['status'] = 'skip:busy'
442
+ return out
443
+ with _lock():
444
+ if os.path.exists(src):
445
+ if os.path.exists(sending):
446
+ # 지난 전송분 뒤에 새 줄을 붙인다(순서 보존)
447
+ _write_lines(sending, _read_lines(sending) + _read_lines(src))
448
+ os.remove(src)
449
+ else:
450
+ os.replace(src, sending)
451
+ for _ in range(MAX_BATCHES_PER_FLUSH):
452
+ lines = _read_lines(sending)
453
+ if not lines:
454
+ break
455
+ batch = lines[:BATCH_MAX]
456
+ events, bad = [], 0
457
+ for ln in batch:
458
+ try:
459
+ e = json.loads(ln)
460
+ if isinstance(e, dict):
461
+ events.append(e)
462
+ else:
463
+ bad += 1
464
+ except Exception:
465
+ bad += 1
466
+ status = post({'consentVersion': CONSENT_VERSION, 'events': events})[0] if events else 200
467
+ if status == 200 or status == 201:
468
+ _write_lines(sending, lines[len(batch):])
469
+ out['sent'] += len(events)
470
+ out['dropped'] += bad
471
+ out['status'] = 'ok'
472
+ elif status == 400:
473
+ _write_lines(sending, lines[len(batch):])
474
+ out['dropped'] += len(batch)
475
+ out['status'] = 'dropped:invalid'
476
+ else:
477
+ out['status'] = 'retry:%s' % status
478
+ break
479
+ try:
480
+ if os.path.exists(sending) and os.path.getsize(sending) == 0:
481
+ os.remove(sending)
482
+ except Exception:
483
+ pass
484
+ return out
485
+ except Exception as e:
486
+ out['status'] = 'error:%s' % type(e).__name__
487
+ return out
488
+
489
+
490
+ def _pending():
491
+ for name in (OUTBOX_NAME, SENDING_NAME):
492
+ p = os.path.join(knowledge_base(), name)
493
+ try:
494
+ if os.path.getsize(p) > 0:
495
+ return True
496
+ except Exception:
497
+ continue
498
+ return False
499
+
500
+
501
+ def flush_background():
502
+ """쌓인 것이 있으면 분리된 프로세스로 flush(훅을 막지 않는다). 30초에 한 번까지."""
503
+ try:
504
+ if not enabled() or not _pending():
505
+ return False
506
+ stamp = os.path.join(knowledge_base(), FLUSH_STAMP)
507
+ try:
508
+ if time.time() - os.path.getmtime(stamp) < FLUSH_MIN_INTERVAL_S:
509
+ return False
510
+ except Exception:
511
+ pass
512
+ with open(stamp, 'w') as f:
513
+ f.write(str(int(time.time())))
514
+ import subprocess
515
+ devnull = open(os.devnull, 'wb')
516
+ subprocess.Popen([sys.executable or 'python3', os.path.abspath(__file__), '--flush'],
517
+ stdin=subprocess.DEVNULL, stdout=devnull, stderr=devnull,
518
+ start_new_session=True, close_fds=True)
519
+ return True
520
+ except Exception:
521
+ return False
522
+
523
+
524
+ if __name__ == '__main__':
525
+ try:
526
+ args = sys.argv[1:]
527
+ if '--flush' in args:
528
+ flush()
529
+ elif args[:1] == ['wire'] and len(args) > 2:
530
+ # 시험용: 판 이벤트 JSON 파일 + repoId → 전송 줄(board.ts 와 같은지 비교)
531
+ with open(args[1], encoding='utf-8') as f:
532
+ ev = json.load(f)
533
+ print(line_of(record_of_board_event(ev, args[2], args[3] if len(args) > 3 else None)))
534
+ except Exception:
535
+ pass
@@ -12,7 +12,7 @@
12
12
  {
13
13
  "id": "hooks.output_contract",
14
14
  "keywords": ["systemmessage", "permissiondecision", "decision block", "hook output", "continue:false", "continue false", "hookspecificoutput", "additionalcontext", "suppressoutput", "updatedinput"],
15
- "affects": ["hooks/session-start.sh", "hooks/pre-credit-guard.sh", "hooks/pre-edit-check.sh", "hooks/pre-agent-spawn.sh", "hooks/pre-webfetch-guard.sh", "hooks/pre-secret-guard.sh", "hooks/pre-edit-config-gate.sh", "hooks/pre-agent-briefing.sh", "hooks/post-edit-track.sh", "hooks/user-prompt-submit.sh", "hooks/stop-claim-check.v3.sh"],
15
+ "affects": ["hooks/session-start.sh", "hooks/pre-credit-guard.sh", "hooks/pre-edit-check.sh", "hooks/pre-agent-spawn.sh", "hooks/pre-webfetch-guard.sh", "hooks/pre-secret-guard.sh", "hooks/pre-edit-config-gate.sh", "hooks/pre-agent-briefing.sh", "hooks/post-edit-track.sh", "hooks/post-read-config-context.sh", "hooks/post-config-context.sh", "hooks/user-prompt-submit.sh", "hooks/stop-claim-check.v3.sh"],
16
16
  "severity_default": "breaking",
17
17
  "probe": "hook_output_accepted"
18
18
  },