@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,122 @@
1
+ #!/usr/bin/env python3
2
+ """작업자 도구 호출 수를 세고 한도마다 인계를 안내한다. --context 면 메인의 큰 맥락을 안내한다."""
3
+ import json
4
+ import os
5
+ import re
6
+ import sys
7
+ import time
8
+
9
+ EXEMPT = ('reviewer', 'verifier')
10
+ REPEAT = 30
11
+ NOTICE = ('[RoutineCode] 이 작업자의 도구 호출이 %d회입니다. 지금 단계를 마무리하고, 끝낸 일, 남은 일, 수정한 파일을 '
12
+ '적어 반환하세요. 오케스트레이터가 새 작업자로 이어갑니다. 끝까지 몇 호출이면 완료되는 일이면 끝내도 됩니다.')
13
+ CONTEXT_NOTICE = ('[RoutineCode] 맥락이 %d만입니다. 이번 작업을 끝낸 뒤 /compact 를 권하세요. '
14
+ '서로 영향 없는 긴 작업은 작업자에게 나눌 수 있습니다.')
15
+ CONTEXT_DEFAULT = 300000
16
+ TAIL = 64 * 1024
17
+ KEEP = 7 * 86400
18
+ ID = re.compile(r'[A-Za-z0-9_-]{1,80}')
19
+
20
+
21
+ def env_int(name, default):
22
+ try:
23
+ return int(os.environ.get(name, default))
24
+ except ValueError:
25
+ return default
26
+
27
+
28
+ def emit(text):
29
+ print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PostToolUse', 'additionalContext': text}}, ensure_ascii=False))
30
+
31
+
32
+ def worker(inp):
33
+ agent, kind = inp.get('agent_id'), str(inp.get('agent_type') or '')
34
+ cap = env_int('ROUTINECODE_AGENT_CALL_LIMIT', 60)
35
+ if not isinstance(agent, str) or not ID.fullmatch(agent) or cap <= 0:
36
+ return
37
+ if any(x in kind for x in EXEMPT):
38
+ return
39
+ path = os.path.join(os.environ['RC_RUNDIR'], 'agent-budget', agent)
40
+ try:
41
+ with open(path) as f:
42
+ count = int(f.read().strip() or 0)
43
+ except (OSError, ValueError):
44
+ count = 0
45
+ count += 1
46
+ with open(path, 'w') as f:
47
+ f.write(str(count))
48
+ if count >= cap and (count - cap) % REPEAT == 0:
49
+ emit(NOTICE % count)
50
+
51
+
52
+ def last_context(path):
53
+ """transcript 끝에서 메인의 마지막 실제 호출 맥락 크기를 찾는다. 못 찾으면 None."""
54
+ size = os.path.getsize(path)
55
+ with open(path, 'rb') as f:
56
+ f.seek(max(0, size - TAIL))
57
+ data = f.read()
58
+ lines = data.split(b'\n')
59
+ if size > TAIL:
60
+ lines = lines[1:]
61
+ for line in reversed(lines):
62
+ if b'"assistant"' not in line:
63
+ continue
64
+ try:
65
+ row = json.loads(line)
66
+ except ValueError:
67
+ continue
68
+ msg = row.get('message') or {}
69
+ if row.get('type') != 'assistant' or row.get('isSidechain') or msg.get('model') == '<synthetic>':
70
+ continue
71
+ usage = msg.get('usage') or {}
72
+ total = sum(usage.get(k) or 0 for k in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'))
73
+ if total > 0:
74
+ return total
75
+ return None
76
+
77
+
78
+ def sweep(folder):
79
+ limit = time.time() - KEEP
80
+ for name in os.listdir(folder):
81
+ path = os.path.join(folder, name)
82
+ try:
83
+ if os.path.getmtime(path) < limit:
84
+ os.unlink(path)
85
+ except OSError:
86
+ pass
87
+
88
+
89
+ def context(inp):
90
+ threshold = env_int('ROUTINECODE_CONTEXT_NOTICE', CONTEXT_DEFAULT)
91
+ sid, transcript = inp.get('session_id'), inp.get('transcript_path')
92
+ if threshold <= 0 or inp.get('agent_id') or not isinstance(sid, str) or not ID.fullmatch(sid) or not isinstance(transcript, str):
93
+ return
94
+ folder = os.path.join(os.environ['RC_RUNDIR'], 'context-notice')
95
+ sweep(folder)
96
+ value = last_context(transcript)
97
+ if value is None:
98
+ return
99
+ done = os.path.join(folder, sid + '.done')
100
+ if value < threshold:
101
+ try:
102
+ os.unlink(done)
103
+ except FileNotFoundError:
104
+ pass
105
+ return
106
+ try:
107
+ os.close(os.open(done, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
108
+ except FileExistsError:
109
+ return
110
+ emit(CONTEXT_NOTICE % (value // 10000))
111
+
112
+
113
+ def main():
114
+ inp = json.load(sys.stdin)
115
+ if '--context' in sys.argv[1:]:
116
+ context(inp)
117
+ else:
118
+ worker(inp)
119
+
120
+
121
+ if __name__ == '__main__':
122
+ main()
@@ -0,0 +1,143 @@
1
+ # -*- coding: utf-8 -*-
2
+ """agent-telemetry.jsonl 완료 행 — SubagentStop 이 쓴다(설계 31 §18).
3
+
4
+ 예전에는 완료 행을 모델이 complete_agent_spawn 을 직접 불러야만 남겼다. 지침이 "훅이 자동 기록"으로
5
+ 바뀐 뒤(2.31.85) 그 일을 하는 훅이 없어 2026-11-04 이후 완료 행이 0 이었다(차단 행만 pre-agent-spawn 이 씀).
6
+ SubagentStop 은 동기·백그라운드 모두 발화하므로 여기 한 곳에서 쓴다. 같은 에이전트가 재개돼 다시 멈춰도
7
+ spawnId(= 시작한 Agent 도구의 tool_use id, 없으면 agent id)로 한 번만 쓴다.
8
+
9
+ 형식은 agent-tracker.ts Spawn 과 같다(telemetry-analyzer 가 그대로 읽는다):
10
+ spawnId agentType parentAgent promptHash promptSnippet invocationMode startedAt completedAt
11
+ result toolCallCount tokensIn tokensOut projectHash (+ tokensInBilled, source)
12
+ promptSnippet 은 비밀값을 가린다. 표준 라이브러리만, 예외를 올리지 않는다.
13
+ """
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+
19
+ TAIL_BYTES = 256 * 1024
20
+
21
+
22
+ def path():
23
+ return os.path.join(os.environ.get('ROUTINECODE_KNOWLEDGE_DIR') or os.path.expanduser('~/.routinecode/knowledge'),
24
+ 'agent-telemetry.jsonl')
25
+
26
+
27
+ def norm_type(t):
28
+ t = str(t or 'unknown')
29
+ return t.split(':', 1)[1] if t.startswith('routinecode:') else t
30
+
31
+
32
+ def project_hash(project_dir):
33
+ # agent-tracker.ts: sha256(PROJECT_DIR || cwd)[:12]
34
+ return hashlib.sha256((project_dir or '').encode('utf-8')).hexdigest()[:12]
35
+
36
+
37
+ def _mask(s):
38
+ try:
39
+ import secret_filter
40
+ out = secret_filter.redact(s)[0]
41
+ return out if isinstance(out, str) else ''
42
+ except Exception:
43
+ return re.sub(r'[A-Za-z0-9_\-+/=]{32,}', '[REDACTED]', s)
44
+
45
+
46
+ def already(spawn_id, p=None):
47
+ """끝부분만 본다 — 재개 중복은 같은 세션 안의 가까운 시점이다."""
48
+ try:
49
+ with open(p or path(), 'rb') as f:
50
+ f.seek(0, 2)
51
+ n = f.tell()
52
+ f.seek(max(0, n - TAIL_BYTES))
53
+ tail = f.read().decode('utf-8', 'ignore')
54
+ return ('"spawnId": "%s"' % spawn_id) in tail or ('"spawnId":"%s"' % spawn_id) in tail
55
+ except Exception:
56
+ return False
57
+
58
+
59
+ def _text(content):
60
+ if isinstance(content, str):
61
+ return content
62
+ if isinstance(content, list):
63
+ return '\n'.join(b.get('text', '') for b in content if isinstance(b, dict) and b.get('type') == 'text')
64
+ return ''
65
+
66
+
67
+ def summarize(entries):
68
+ """서브에이전트 transcript → (prompt, startedAt, completedAt, toolCalls, 입력 합계, 출력 합계, isError, 마지막 맥락 크기)."""
69
+ prompt, started, ended = '', None, None
70
+ calls, seen_ids, tin, tout, err, last_ctx = 0, set(), 0, 0, False, 0
71
+ for e in entries:
72
+ ts = e.get('timestamp')
73
+ if isinstance(ts, str):
74
+ started = started or ts
75
+ ended = ts
76
+ msg = e.get('message') if isinstance(e.get('message'), dict) else {}
77
+ if not prompt and e.get('type') == 'user':
78
+ prompt = _text(msg.get('content'))
79
+ if e.get('type') != 'assistant':
80
+ continue
81
+ mid = msg.get('id')
82
+ u = msg.get('usage') if isinstance(msg.get('usage'), dict) else None
83
+ if u and mid not in seen_ids: # 같은 message.id 는 한 번만(설계 15 §2.1)
84
+ seen_ids.add(mid)
85
+ ctx = sum(int(u.get(k) or 0) for k in ('input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens'))
86
+ tin += ctx
87
+ last_ctx = ctx
88
+ tout += int(u.get('output_tokens') or 0)
89
+ for b in msg.get('content') or []:
90
+ if isinstance(b, dict) and b.get('type') == 'tool_use':
91
+ calls += 1
92
+ if e.get('isApiErrorMessage') is True:
93
+ err = True
94
+ return prompt, started, ended, calls, tin, tout, err, last_ctx
95
+
96
+
97
+ def record(row, p=None):
98
+ try:
99
+ p = p or path()
100
+ os.makedirs(os.path.dirname(p), exist_ok=True)
101
+ with open(p, 'a', encoding='utf-8') as f:
102
+ f.write(json.dumps(row, ensure_ascii=False) + '\n')
103
+ return True
104
+ except Exception:
105
+ return False
106
+
107
+
108
+ def from_stop(inp, agent_path, entries, meta, p=None):
109
+ """SubagentStop 입력 → 완료 행(이미 있으면 None). fork 는 위임이 아니라 쓰지 않는다."""
110
+ try:
111
+ agent_type = inp.get('agent_type') or meta.get('agentType') or 'unknown'
112
+ if agent_type == 'fork':
113
+ return None
114
+ aid = str(inp.get('agent_id') or os.path.basename(agent_path)[:-len('.jsonl')]).replace('agent-', '', 1)
115
+ spawn_id = meta.get('toolUseId') or aid
116
+ if not spawn_id or already(spawn_id, p):
117
+ return None
118
+ prompt, started, ended, calls, tin, tout, err, last_ctx = summarize(entries)
119
+ m = re.search(r'INVOCATION_MODE:\s*(sequential|parallel)', prompt, re.I)
120
+ parent = meta.get('parentAgentId') if isinstance(meta.get('parentAgentId'), str) else 'main'
121
+ project = os.environ.get('PROJECT_DIR') or os.environ.get('CLAUDE_PROJECT_DIR') or inp.get('cwd') or os.getcwd()
122
+ row = {
123
+ 'spawnId': spawn_id,
124
+ 'agentType': norm_type(agent_type),
125
+ 'parentAgent': parent,
126
+ 'promptHash': hashlib.sha256(prompt.encode('utf-8')).hexdigest()[:16],
127
+ 'promptSnippet': _mask(prompt[:200]),
128
+ 'invocationMode': m.group(1).lower() if m else 'sequential',
129
+ 'startedAt': started,
130
+ 'completedAt': ended,
131
+ 'result': 'error' if err else 'success',
132
+ 'toolCallCount': calls,
133
+ # tokensIn = 마지막 맥락 크기(예전 자기신고 행과 같은 뜻: Agent 결과의 totalTokens).
134
+ # 캐시 읽기까지 합친 청구 기준 합계는 따로 둔다.
135
+ 'tokensIn': last_ctx,
136
+ 'tokensOut': tout,
137
+ 'tokensInBilled': tin,
138
+ 'projectHash': project_hash(project),
139
+ 'source': 'subagent-stop',
140
+ }
141
+ return row if record(row, p) else None
142
+ except Exception:
143
+ return None
@@ -61,12 +61,21 @@ def verify_state(v):
61
61
  """verification.ts saveState 의 mac 검증 — stateMacPayload 와 바이트 동일 직렬화."""
62
62
  if not isinstance(v, dict) or not isinstance(v.get('mac'), str):
63
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)
64
+ base = [v.get('phase'), v.get('targetId'), v.get('currentScore'), v.get('passed'),
65
+ bool(v.get('forcedPass')), v.get('adjustedScore'), v.get('scoredAt'), v.get('changeFingerprint')]
66
+ enc = lambda xs: json.dumps(xs, separators=(',', ':'), ensure_ascii=False)
67
+ # 설계 18 T6: 끝에 정수 2개(newL1Growth, signedViolations). 구형식(8칸, 구버전 MCP 세션)은 전환 기간에 받고 값은 0 으로 본다(structure_debt)
68
+ return _mac_ok(v['mac'], enc(base + [v.get('newL1Growth', 0), v.get('signedViolations', 0)])) or _mac_ok(v['mac'], enc(base))
69
+
70
+
71
+ def structure_debt(v):
72
+ """서명으로 보호되는 새 L1 복제 + 서명 제약 위반 수. verify_state 통과 후에만 쓴다. 구형식 서명이면 0"""
73
+ base = [v.get('phase'), v.get('targetId'), v.get('currentScore'), v.get('passed'),
74
+ bool(v.get('forcedPass')), v.get('adjustedScore'), v.get('scoredAt'), v.get('changeFingerprint')]
75
+ payload = json.dumps(base + [v.get('newL1Growth', 0), v.get('signedViolations', 0)], separators=(',', ':'), ensure_ascii=False)
76
+ if not _mac_ok(v.get('mac'), payload):
77
+ return 0
78
+ return max(0, int(v.get('newL1Growth') or 0)) + max(0, int(v.get('signedViolations') or 0))
70
79
 
71
80
 
72
81
  def _mac_ok(mac, payload):
@@ -0,0 +1,109 @@
1
+ """메타지능 v1 귀속 루프의 판정 — 설계 28 T3.
2
+
3
+ 주입 원장(ledger) 대기 행마다, 주입 이후의 실행·편집 기록으로 결과를 판정한다.
4
+ bad — 주입 대상 파일을 편집한 뒤에도 같은 오류 서명의 점검 실패가 다시 났다(편집을 사이에 둔 재발 = 가설 기각)
5
+ good — 주입 대상 파일의 마지막 편집 뒤에, 그 파일을 덮는 점검(빌드·테스트)이 성공했다
6
+ neutral — 판정 재료 없이 오래 지났다(분모에만 — 무리한 판정 금지)
7
+ None — 아직 판정하지 않는다(대기 유지)
8
+ 단순 편집 횟수는 쓰지 않는다(정상 작업도 한 파일을 여러 번 고친다 — 설계 28 §0.2).
9
+ 판정은 실행 기록 대조뿐 — LLM·자기 점수 없음.
10
+ """
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from datetime import datetime
15
+
16
+ import claim_structure as cs
17
+
18
+ SCHEMA = 2
19
+ STALE_SEC = 6 * 3600
20
+ _CHECK_DOMAINS = ('build_ok', 'test_ok')
21
+
22
+
23
+ def file_keys(path):
24
+ """원장 행에 쓰는 파일 키 — file(옛: basename sha1[:8]) + file_full(전체 경로 sha1[:12])"""
25
+ if not path:
26
+ return {'file': None, 'file_full': None}
27
+ return {'file': hashlib.sha1(os.path.basename(path).encode('utf-8', 'replace')).hexdigest()[:8],
28
+ 'file_full': hashlib.sha1(os.path.abspath(path).encode('utf-8', 'replace')).hexdigest()[:12]}
29
+
30
+
31
+ def _row_matches(row, path):
32
+ k = file_keys(path)
33
+ if row.get('file_full'):
34
+ return row['file_full'] == k['file_full']
35
+ return bool(row.get('file')) and row['file'] == k['file']
36
+
37
+
38
+ def _iso_ts(v):
39
+ try:
40
+ return datetime.fromisoformat(str(v).replace('Z', '+00:00')).timestamp()
41
+ except Exception:
42
+ return 0.0
43
+
44
+
45
+ def _is_check(run, questions):
46
+ doms = questions.get('domains', {})
47
+ return any(cs._matches(run, doms[d]) for d in _CHECK_DOMAINS if d in doms)
48
+
49
+
50
+ def judge_row(row, activity, now_ts, questions=None):
51
+ q = questions or cs.load_questions()
52
+ at = _iso_ts(row.get('at'))
53
+ edits = [e for e in activity.get('edits', []) if e.get('ts', 0) >= at and _row_matches(row, e.get('path'))]
54
+ checks = [r for r in activity.get('runs', []) if r.get('ts', 0) >= at and _is_check(r, q)]
55
+ if edits:
56
+ paths = {e['path'] for e in edits}
57
+ covering = [r for r in checks if any(cs._covers(r.get('dir'), p) for p in paths)]
58
+ edit_ts = sorted(e['ts'] for e in edits)
59
+ fails = [r for r in covering if not r['ok'] and r.get('sig')]
60
+ for i, f1 in enumerate(fails):
61
+ for f2 in fails[i + 1:]:
62
+ lo, hi = sorted((f1['ts'], f2['ts']))
63
+ if f1['sig'] == f2['sig'] and any(lo < t < hi for t in edit_ts):
64
+ return 'bad'
65
+ last_edit = edit_ts[-1]
66
+ if any(r['ok'] and r['ts'] > last_edit for r in covering):
67
+ return 'good'
68
+ if at and now_ts - at > STALE_SEC:
69
+ return 'neutral'
70
+ return None
71
+
72
+
73
+ def migrate_stats(stats_path):
74
+ """설계 28 이전 판정(87건 전부 bad — 편집 횟수 기준)은 새 기준과 섞지 않는다: 이름만 바꿔 보존하고 새로 센다."""
75
+ try:
76
+ with open(stats_path) as f:
77
+ old = json.load(f)
78
+ except Exception:
79
+ return {'_schema': SCHEMA}
80
+ if isinstance(old, dict) and old.get('_schema') == SCHEMA:
81
+ return old
82
+ inv = os.path.join(os.path.dirname(stats_path), 'stats.v1-invalid.json')
83
+ try:
84
+ if not os.path.exists(inv):
85
+ os.replace(stats_path, inv)
86
+ except Exception:
87
+ pass
88
+ return {'_schema': SCHEMA}
89
+
90
+
91
+ def apply(pending, activity, stats, now_ts, today, questions=None):
92
+ """대기 행을 판정해 stats 를 갱신. 반환 = 바뀐 행이 있는가. 행에는 done 을 적는다."""
93
+ changed = False
94
+ for row in pending:
95
+ v = judge_row(row, activity, now_ts, questions)
96
+ if v is None:
97
+ continue
98
+ grp = 'holdout' if row.get('holdout') else 'exposed'
99
+ rec = stats.setdefault(row.get('kid') or 'unknown', {
100
+ 'exposed': 0, 'holdout': 0, 'exposed_bad': 0, 'holdout_bad': 0,
101
+ 'exposed_good': 0, 'holdout_good': 0, 'exposed_neutral': 0, 'holdout_neutral': 0,
102
+ 'kind': row.get('kind', ''), 'last_seen': today})
103
+ rec[grp] = rec.get(grp, 0) + 1
104
+ rec[grp + '_' + v] = rec.get(grp + '_' + v, 0) + 1
105
+ rec['last_seen'] = today
106
+ row['done'] = v
107
+ changed = True
108
+ return changed
109
+
@@ -0,0 +1,268 @@
1
+ {
2
+ "events": [
3
+ {
4
+ "v": 1,
5
+ "id": "e01",
6
+ "at": "2026-11-11T00:01:00.000Z",
7
+ "kind": "task.post",
8
+ "task": "t1",
9
+ "by": {
10
+ "session": "sessA0000000",
11
+ "agent": null
12
+ },
13
+ "personId": null,
14
+ "tenantId": null,
15
+ "data": {
16
+ "title": "로그인 오류",
17
+ "desc": "fix",
18
+ "files": [
19
+ "/r/a.ts"
20
+ ],
21
+ "parent": null,
22
+ "planRef": "p-1"
23
+ }
24
+ },
25
+ {
26
+ "v": 1,
27
+ "id": "e02",
28
+ "at": "2026-11-11T00:02:00.000Z",
29
+ "kind": "task.post",
30
+ "task": "t2",
31
+ "by": {
32
+ "session": "sessA0000000",
33
+ "agent": null
34
+ },
35
+ "personId": null,
36
+ "tenantId": null,
37
+ "data": {
38
+ "title": "결제 API",
39
+ "files": [
40
+ "/r/b.ts"
41
+ ]
42
+ }
43
+ },
44
+ {
45
+ "v": 1,
46
+ "id": "e03",
47
+ "at": "2026-11-11T00:03:00.000Z",
48
+ "kind": "task.post",
49
+ "task": "t1",
50
+ "by": {
51
+ "session": "sessB0000000",
52
+ "agent": "implementor:x"
53
+ },
54
+ "personId": null,
55
+ "tenantId": null,
56
+ "data": {
57
+ "title": "duplicate ignored"
58
+ }
59
+ },
60
+ {
61
+ "v": 1,
62
+ "id": "e04",
63
+ "at": "2026-11-11T00:04:00.000Z",
64
+ "kind": "task.claim",
65
+ "task": "t1",
66
+ "by": {
67
+ "session": "sessB0000000",
68
+ "agent": "implementor:x"
69
+ },
70
+ "personId": null,
71
+ "tenantId": null,
72
+ "data": {}
73
+ },
74
+ {
75
+ "v": 1,
76
+ "id": "e05",
77
+ "at": "2026-11-11T00:05:00.000Z",
78
+ "kind": "note",
79
+ "task": "t1",
80
+ "by": {
81
+ "session": "sessB0000000",
82
+ "agent": "implementor:x"
83
+ },
84
+ "personId": null,
85
+ "tenantId": null,
86
+ "data": {
87
+ "topic": "refuted",
88
+ "text": "캐시 지우기는 원인 아님"
89
+ }
90
+ },
91
+ {
92
+ "v": 1,
93
+ "id": "e06",
94
+ "at": "2026-11-11T00:06:00.000Z",
95
+ "kind": "task.release",
96
+ "task": "t1",
97
+ "by": {
98
+ "session": "sessB0000000",
99
+ "agent": "implementor:x"
100
+ },
101
+ "personId": null,
102
+ "tenantId": null,
103
+ "data": {
104
+ "reason": "x"
105
+ }
106
+ },
107
+ {
108
+ "v": 1,
109
+ "id": "e07",
110
+ "at": "2026-11-11T00:07:00.000Z",
111
+ "kind": "task.claim",
112
+ "task": "t1",
113
+ "by": {
114
+ "session": "sessA0000000",
115
+ "agent": null
116
+ },
117
+ "personId": null,
118
+ "tenantId": null,
119
+ "data": {}
120
+ },
121
+ {
122
+ "v": 1,
123
+ "id": "e08",
124
+ "at": "2026-11-11T00:08:00.000Z",
125
+ "kind": "task.land",
126
+ "task": "t1",
127
+ "by": {
128
+ "session": "sessA0000000",
129
+ "agent": null
130
+ },
131
+ "personId": null,
132
+ "tenantId": null,
133
+ "data": {
134
+ "evidence": [
135
+ "build@x"
136
+ ],
137
+ "files": [
138
+ "/r/a.ts"
139
+ ],
140
+ "commit": null
141
+ }
142
+ },
143
+ {
144
+ "v": 1,
145
+ "id": "e09",
146
+ "at": "2026-11-11T00:09:00.000Z",
147
+ "kind": "task.block",
148
+ "task": "t1",
149
+ "by": {
150
+ "session": "sessB0000000",
151
+ "agent": "implementor:x"
152
+ },
153
+ "personId": null,
154
+ "tenantId": null,
155
+ "data": {
156
+ "reason": "ignored after land"
157
+ }
158
+ },
159
+ {
160
+ "v": 1,
161
+ "id": "e10",
162
+ "at": "2026-11-11T00:10:00.000Z",
163
+ "kind": "task.claim",
164
+ "task": "t2",
165
+ "by": {
166
+ "session": "sessB0000000",
167
+ "agent": "implementor:x"
168
+ },
169
+ "personId": null,
170
+ "tenantId": null,
171
+ "data": {}
172
+ },
173
+ {
174
+ "v": 1,
175
+ "id": "e11",
176
+ "at": "2026-11-11T00:11:00.000Z",
177
+ "kind": "task.block",
178
+ "task": "t2",
179
+ "by": {
180
+ "session": "sessB0000000",
181
+ "agent": "implementor:x"
182
+ },
183
+ "personId": null,
184
+ "tenantId": null,
185
+ "data": {
186
+ "reason": "3회 실패"
187
+ }
188
+ },
189
+ {
190
+ "v": 1,
191
+ "id": "e12",
192
+ "at": "2026-11-11T00:12:00.000Z",
193
+ "kind": "note",
194
+ "task": null,
195
+ "by": {
196
+ "session": "sessA0000000",
197
+ "agent": null
198
+ },
199
+ "personId": null,
200
+ "tenantId": null,
201
+ "data": {
202
+ "topic": "announce",
203
+ "text": "기다리지 말고 다음 과제를 잡아라"
204
+ }
205
+ },
206
+ {
207
+ "v": 1,
208
+ "id": "e13",
209
+ "at": "2026-11-11T00:13:00.000Z",
210
+ "kind": "note",
211
+ "task": "zz",
212
+ "by": {
213
+ "session": "sessA0000000",
214
+ "agent": null
215
+ },
216
+ "personId": null,
217
+ "tenantId": null,
218
+ "data": {
219
+ "topic": "progress",
220
+ "text": "unknown task note goes board-wide"
221
+ }
222
+ },
223
+ {
224
+ "v": 2,
225
+ "kind": "task.post",
226
+ "task": "bad",
227
+ "by": {
228
+ "session": "sessA0000000",
229
+ "agent": null
230
+ },
231
+ "data": {}
232
+ },
233
+ {
234
+ "v": 1,
235
+ "id": "e14",
236
+ "at": "2026-11-11T00:14:00.000Z",
237
+ "kind": "task.expire",
238
+ "task": "t2",
239
+ "by": {
240
+ "session": "sessA0000000",
241
+ "agent": null
242
+ },
243
+ "personId": null,
244
+ "tenantId": null,
245
+ "data": {
246
+ "prev": {}
247
+ }
248
+ },
249
+ {
250
+ "v": 1,
251
+ "id": "e15",
252
+ "at": "2026-11-11T00:15:00.000Z",
253
+ "kind": "task.post",
254
+ "task": "t3",
255
+ "by": {
256
+ "session": "sessA0000000",
257
+ "agent": null
258
+ },
259
+ "personId": null,
260
+ "tenantId": null,
261
+ "data": {
262
+ "title": "자식",
263
+ "parent": "t2",
264
+ "files": "notalist"
265
+ }
266
+ }
267
+ ]
268
+ }