@routinecrew/routinecode 2.31.71 → 2.31.77

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 (150) hide show
  1. package/bin/prompt-vault.js +1 -1
  2. package/bin/rc-config.js +1 -1
  3. package/bin/rc-credit-turn.js +1 -1
  4. package/bin/rc-grant.js +1 -1
  5. package/bin/rc-team.js +1 -1
  6. package/hooks/cc-compat-watch.js +1 -1
  7. package/hooks/maintenance-runner.sh +5 -0
  8. package/hooks/pre-agent-spawn.mjs +1 -1
  9. package/mcp-db-manager/dist/analyzers/duplicate-detector.js +1 -1
  10. package/mcp-db-manager/dist/core/model-parser.js +1 -1
  11. package/mcp-db-manager/dist/core/schema-reader.js +1 -1
  12. package/mcp-db-manager/dist/executors/migration-executor.js +1 -1
  13. package/mcp-db-manager/dist/generators/migration-generator.js +1 -1
  14. package/mcp-db-manager/dist/index.js +1 -1
  15. package/mcp-db-manager/dist/validators/schema-validator.js +1 -1
  16. package/mcp-dev-tester/dist/analyzers/auth-diagnoser.js +1 -1
  17. package/mcp-dev-tester/dist/analyzers/backend-analyzer.js +1 -1
  18. package/mcp-dev-tester/dist/analyzers/endpoint-diagnoser.js +1 -1
  19. package/mcp-dev-tester/dist/analyzers/frontend-analyzer.js +1 -1
  20. package/mcp-dev-tester/dist/analyzers/runtime-diagnoser.js +1 -1
  21. package/mcp-dev-tester/dist/analyzers/type-comparator.js +1 -1
  22. package/mcp-dev-tester/dist/analyzers/validation-diagnoser.js +1 -1
  23. package/mcp-dev-tester/dist/attestation.js +1 -1
  24. package/mcp-dev-tester/dist/browser/playwright-manager.js +1 -1
  25. package/mcp-dev-tester/dist/browser/ui-tester.js +1 -1
  26. package/mcp-dev-tester/dist/config/project-config.js +1 -1
  27. package/mcp-dev-tester/dist/index.js +1 -1
  28. package/mcp-dev-tester/dist/testers/api-tester.js +1 -1
  29. package/mcp-doc-fetcher/dist/index.js +1 -1
  30. package/mcp-html-renderer/dist/index.js +1 -1
  31. package/mcp-html-renderer/dist/preview.js +1 -1
  32. package/mcp-html-renderer/dist/template-engine.js +1 -1
  33. package/mcp-intelligence/dist/concept-catalog.js +1 -1
  34. package/mcp-intelligence/dist/concept-server-proxy.js +1 -1
  35. package/mcp-intelligence/dist/config-auth.js +1 -1
  36. package/mcp-intelligence/dist/contracts.generated.js +1 -1
  37. package/mcp-intelligence/dist/domain-templates.js +1 -1
  38. package/mcp-intelligence/dist/grounding.js +1 -1
  39. package/mcp-intelligence/dist/handlers.js +1 -1
  40. package/mcp-intelligence/dist/index.js +1 -1
  41. package/mcp-intelligence/dist/intelligence-file.js +1 -1
  42. package/mcp-intelligence/dist/knowledge-critic.js +1 -1
  43. package/mcp-intelligence/dist/knowledge-handlers.js +1 -1
  44. package/mcp-intelligence/dist/mention-extractor.js +1 -1
  45. package/mcp-intelligence/dist/provenance.js +1 -1
  46. package/mcp-intelligence/dist/semantic-embedder.js +1 -1
  47. package/mcp-log-watcher/dist/config-auth.js +1 -1
  48. package/mcp-log-watcher/dist/file-watcher.js +1 -1
  49. package/mcp-log-watcher/dist/index.js +1 -1
  50. package/mcp-log-watcher/dist/known-solutions.js +1 -1
  51. package/mcp-log-watcher/dist/log-store.js +1 -1
  52. package/mcp-log-watcher/dist/websocket-server.js +1 -1
  53. package/mcp-plan-manager/dist/__tests__/file-ops-knowledge-dir.test.js +1 -1
  54. package/mcp-plan-manager/dist/__tests__/plan-parser.test.js +1 -1
  55. package/mcp-plan-manager/dist/file-ops.js +1 -1
  56. package/mcp-plan-manager/dist/index.js +1 -1
  57. package/mcp-plan-manager/dist/plan-parser.js +1 -1
  58. package/mcp-project-context/dist/git-ops.js +1 -1
  59. package/mcp-project-context/dist/index.js +1 -1
  60. package/mcp-project-context/dist/project-analysis.js +1 -1
  61. package/mcp-routinecode/dist/agent-tracker.js +1 -1
  62. package/mcp-routinecode/dist/attestation.js +1 -1
  63. package/mcp-routinecode/dist/blast-radius.js +1 -1
  64. package/mcp-routinecode/dist/changeset.js +1 -1
  65. package/mcp-routinecode/dist/config-auth.js +1 -1
  66. package/mcp-routinecode/dist/config-map/arch-graph.js +1 -1
  67. package/mcp-routinecode/dist/config-map/architect-store.js +1 -1
  68. package/mcp-routinecode/dist/config-map/assign.js +1 -1
  69. package/mcp-routinecode/dist/config-map/audit-cli.js +1 -1
  70. package/mcp-routinecode/dist/config-map/audit.js +1 -1
  71. package/mcp-routinecode/dist/config-map/blocks.js +1 -0
  72. package/mcp-routinecode/dist/config-map/briefing.js +1 -1
  73. package/mcp-routinecode/dist/config-map/cert-gate.js +346 -0
  74. package/mcp-routinecode/dist/config-map/cert-lib.js +363 -0
  75. package/mcp-routinecode/dist/config-map/cert-wiring.js +266 -0
  76. package/mcp-routinecode/dist/config-map/certify.js +240 -0
  77. package/mcp-routinecode/dist/config-map/const-use.js +1 -0
  78. package/mcp-routinecode/dist/config-map/decisions.js +1 -1
  79. package/mcp-routinecode/dist/config-map/decls.js +1 -1
  80. package/mcp-routinecode/dist/config-map/drift.js +1 -0
  81. package/mcp-routinecode/dist/config-map/dup-safety.js +1 -0
  82. package/mcp-routinecode/dist/config-map/extract.js +1 -1
  83. package/mcp-routinecode/dist/config-map/field-contract.js +1 -0
  84. package/mcp-routinecode/dist/config-map/gate.js +1 -1
  85. package/mcp-routinecode/dist/config-map/hash.js +1 -1
  86. package/mcp-routinecode/dist/config-map/ident-norm.js +1 -1
  87. package/mcp-routinecode/dist/config-map/index-store.js +1 -1
  88. package/mcp-routinecode/dist/config-map/light-eval.js +1 -1
  89. package/mcp-routinecode/dist/config-map/link.js +1 -1
  90. package/mcp-routinecode/dist/config-map/linked-repos.js +1 -0
  91. package/mcp-routinecode/dist/config-map/lookup.js +1 -1
  92. package/mcp-routinecode/dist/config-map/louvain.js +1 -1
  93. package/mcp-routinecode/dist/config-map/maintenance-cli.js +1 -1
  94. package/mcp-routinecode/dist/config-map/names.js +1 -1
  95. package/mcp-routinecode/dist/config-map/proposals.js +1 -1
  96. package/mcp-routinecode/dist/config-map/recheck.js +1 -1
  97. package/mcp-routinecode/dist/config-map/repo-id.js +1 -1
  98. package/mcp-routinecode/dist/config-map/route-security.js +1 -0
  99. package/mcp-routinecode/dist/config-map/rule-import.js +1 -1
  100. package/mcp-routinecode/dist/config-map/scc.js +1 -1
  101. package/mcp-routinecode/dist/config-map/shape-eval.js +1 -1
  102. package/mcp-routinecode/dist/config-map/shape.js +1 -1
  103. package/mcp-routinecode/dist/config-map/snapshot.js +1 -1
  104. package/mcp-routinecode/dist/config-map/sole-impl.js +1 -0
  105. package/mcp-routinecode/dist/config-map/stable-id.js +1 -1
  106. package/mcp-routinecode/dist/config-map/store.js +1 -1
  107. package/mcp-routinecode/dist/config-map/swagger-check.js +1 -0
  108. package/mcp-routinecode/dist/config-map/task-eval.js +1 -1
  109. package/mcp-routinecode/dist/config-map/templates.js +1 -1
  110. package/mcp-routinecode/dist/contracts.generated.js +1 -1
  111. package/mcp-routinecode/dist/coverage.js +1 -1
  112. package/mcp-routinecode/dist/explorer-advisor.js +1 -1
  113. package/mcp-routinecode/dist/failure-tracker.js +1 -1
  114. package/mcp-routinecode/dist/file-lock-registry.js +1 -1
  115. package/mcp-routinecode/dist/file-risk-scorer.js +1 -1
  116. package/mcp-routinecode/dist/index.js +1 -1
  117. package/mcp-routinecode/dist/known-solutions.js +1 -1
  118. package/mcp-routinecode/dist/ledger-miner.js +1 -1
  119. package/mcp-routinecode/dist/observed-draft.js +1 -1
  120. package/mcp-routinecode/dist/pattern-matcher.js +1 -1
  121. package/mcp-routinecode/dist/route-match.js +1 -1
  122. package/mcp-routinecode/dist/routines.js +1 -1
  123. package/mcp-routinecode/dist/rule-engine.js +1 -1
  124. package/mcp-routinecode/dist/rule-promoter.js +1 -1
  125. package/mcp-routinecode/dist/telemetry-analyzer.js +1 -1
  126. package/mcp-routinecode/dist/test-runner.js +1 -1
  127. package/mcp-routinecode/dist/verification.js +1 -1
  128. package/mcp-routinecode/dist/viral-loop.js +1 -1
  129. package/package.json +8 -2
  130. package/plugin/agents/analyzer.md.sealed +1 -1
  131. package/plugin/agents/architect.md.sealed +1 -1
  132. package/plugin/agents/crawler.md.sealed +1 -1
  133. package/plugin/agents/explorer.md.sealed +1 -1
  134. package/plugin/agents/implementor.md.sealed +1 -1
  135. package/plugin/agents/looker.md.sealed +1 -1
  136. package/plugin/agents/planner.md.sealed +1 -1
  137. package/plugin/agents/recorder.md.sealed +1 -1
  138. package/plugin/agents/reviewer.md.sealed +1 -1
  139. package/plugin/agents/verifier.md.sealed +1 -1
  140. package/plugin/commands/analyze.md.sealed +1 -1
  141. package/plugin/commands/plan.md.sealed +1 -1
  142. package/plugin/commands/rc.md.sealed +1 -1
  143. package/plugin/commands/receipt.md.sealed +1 -1
  144. package/plugin/commands/recharge.md.sealed +1 -1
  145. package/plugin/commands/routines.md.sealed +1 -1
  146. package/plugin/commands/share.md.sealed +1 -1
  147. package/plugin/routinecode-prompt.md.sealed +1 -1
  148. package/hooks/lib/tests/test_config_bash_track.py +0 -189
  149. package/hooks/lib/tests/test_maintenance_sync.py +0 -190
  150. package/hooks/lib/tests/test_w1_core.py +0 -441
@@ -1,441 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- W1 핵심 경로 단위 실행 테스트 (05 §2·§3·§9 W1).
4
-
5
- fakehome + mock _post 로 실서버 호출 없이:
6
- 1. normalize_sig 골든 10종 통과 + 충돌 반례
7
- 2. emit_raw 화이트리스트·at 필수·8종
8
- 3. 커서 v1→v2 마이그레이션(offset 0 리셋 + 재전송)
9
- 4. rotation 후 무유실
10
- 5. 400 격리(pending-quarantine)
11
- 6. 게이트 off 시 신규 8종 비전송 + 기존 이벤트 정상 전송(+ 커서 비전진)
12
-
13
- 실행: python3 test_w1_core.py (exit 0 = 전부 통과)
14
- """
15
-
16
- import os
17
- import sys
18
- import json
19
- import tempfile
20
- import shutil
21
-
22
- HERE = os.path.dirname(os.path.abspath(__file__))
23
- LIB = os.path.dirname(HERE)
24
- sys.path.insert(0, LIB)
25
-
26
- PASS = []
27
- FAIL = []
28
-
29
-
30
- def check(name, cond, detail=""):
31
- if cond:
32
- PASS.append(name)
33
- print(f" PASS {name}")
34
- else:
35
- FAIL.append((name, detail))
36
- print(f" FAIL {name} :: {detail}")
37
-
38
-
39
- # ────────────────────────────────────────────────────────────
40
- # 1. normalize_sig 골든
41
- # ────────────────────────────────────────────────────────────
42
- def test_golden():
43
- print("[1] normalize_sig golden fixture")
44
- import normalize_sig as ns
45
- fixture = json.load(open(os.path.join(LIB, "normalize-golden.json")))
46
- check("golden.norm_version", fixture.get("norm_version") == ns.NORM_VERSION,
47
- f"{fixture.get('norm_version')} != {ns.NORM_VERSION}")
48
- cases = fixture["cases"]
49
- check("golden.count>=10", len(cases) >= 10, str(len(cases)))
50
- for i, c in enumerate(cases):
51
- sig, head, norm = ns.normalize_sig(c["raw"])
52
- check(f"golden[{i}].sig", sig == c["sig"], f"{sig} != {c['sig']} for {c['raw']!r}")
53
- check(f"golden[{i}].normalized", norm == c["normalized"],
54
- f"{norm!r} != {c['normalized']!r}")
55
- # idempotency
56
- _, _, n2 = ns.normalize_sig(norm)
57
- check(f"golden[{i}].idempotent", n2 == norm, f"{n2!r} != {norm!r}")
58
- for i, p in enumerate(fixture.get("collision_same", [])):
59
- check(f"collision_same[{i}]", ns.sig_of(p["a"]) == ns.sig_of(p["b"]),
60
- f"{p['a']!r} vs {p['b']!r}")
61
- for i, p in enumerate(fixture.get("collision_diff", [])):
62
- check(f"collision_diff[{i}]", ns.sig_of(p["a"]) != ns.sig_of(p["b"]),
63
- f"{p['a']!r} vs {p['b']!r} collide")
64
-
65
-
66
- # ────────────────────────────────────────────────────────────
67
- # 2. emit_raw
68
- # ────────────────────────────────────────────────────────────
69
- def test_emit_raw(home):
70
- print("[2] emit_raw whitelist + at 필수 + 8종")
71
- import importlib
72
- import emit_raw
73
- importlib.reload(emit_raw)
74
- events_path = os.path.join(home, ".routinecode", "usage", "events.jsonl")
75
- emit_raw.EVENTS_PATH = events_path
76
-
77
- # 미지 타입 drop
78
- check("emit.unknown_drop", emit_raw.emit_raw("bogus", {"x": 1}) is False)
79
-
80
- # 화이트리스트: junk_key drop, sig 통과
81
- ok = emit_raw.emit_raw("encounter", {"sig": "abc", "tech": ["seq"], "junk": "DROP"},
82
- session="s1", at="2026-01-01T00:00:00+00:00")
83
- check("emit.encounter_ok", ok is True)
84
- lines = open(events_path).read().strip().split("\n")
85
- ev = json.loads(lines[-1])
86
- check("emit.whitelist_sig", ev["metadata"].get("sig") == "abc")
87
- check("emit.whitelist_tech", ev["metadata"].get("tech") == ["seq"])
88
- check("emit.whitelist_junk_dropped", "junk" not in ev["metadata"])
89
- check("emit.at_preserved", ev["at"] == "2026-01-01T00:00:00+00:00")
90
- check("emit.no_tenant_in_envelope", "tenant_id" not in ev.get("metadata", {}))
91
-
92
- # at 미지정 → UTC 채움
93
- emit_raw.emit_raw("search", {"qsig": "q", "result_count": 0}, session="s1")
94
- ev2 = json.loads(open(events_path).read().strip().split("\n")[-1])
95
- check("emit.at_autofill", bool(ev2["at"]) and "T" in ev2["at"])
96
-
97
- # 8종 전부 방출 가능
98
- for et in ("exposure", "resolution", "rule_applied", "krecord", "kverify", "task"):
99
- r = emit_raw.emit_raw(et, {"kid": "ef:1", "sig": "s", "rule_id": "R",
100
- "result": "prevented", "task_sig": "t"}, session="s1")
101
- check(f"emit.{et}", r is True)
102
-
103
-
104
- # ────────────────────────────────────────────────────────────
105
- # sync_manager 헬퍼 (mock)
106
- # ────────────────────────────────────────────────────────────
107
- def _setup_sync(home, sm, telemetry=True, api_key="k", raw_enabled=True):
108
- """fakehome 경로로 sync_manager 상수 리바인드 + config/flags 작성."""
109
- usage = os.path.join(home, ".routinecode", "usage")
110
- os.makedirs(usage, exist_ok=True)
111
- sm.CONFIG_PATH = os.path.join(home, ".routinecode", "config.json")
112
- sm.EVENTS_PATH = os.path.join(usage, "events.jsonl")
113
- sm.COHORT_PATH = os.path.join(usage, "cohort.json")
114
- sm.PENDING_PATH = os.path.join(usage, "pending-sync.jsonl")
115
- sm.QUARANTINE_PATH = os.path.join(usage, "pending-quarantine.jsonl")
116
- sm.SYNC_STATE_PATH = os.path.join(usage, "sync-state.json")
117
- sm.SYNC_LOG_PATH = os.path.join(usage, "sync.log")
118
- sm.SYNC_LOCK_PATH = os.path.join(usage, "sync.lock")
119
- sm.REMOTE_FLAGS_PATH = os.path.join(home, ".routinecode", "remote-flags.json")
120
-
121
- cfg = {"userId": 42, "tenantId": 7, "serverUrl": "http://mock", "apiKey": api_key}
122
- if not telemetry:
123
- cfg["telemetryEnabled"] = False
124
- json.dump(cfg, open(sm.CONFIG_PATH, "w"))
125
- json.dump({"flags": {"raw_events_enabled": raw_enabled}}, open(sm.REMOTE_FLAGS_PATH, "w"))
126
-
127
-
128
- def _write_events(path, events):
129
- with open(path, "w") as f:
130
- for e in events:
131
- f.write(json.dumps(e, ensure_ascii=False) + "\n")
132
-
133
-
134
- def test_cursor_migration(home):
135
- print("[3] 커서 v1→v2 마이그레이션 (offset 0 리셋 + 재전송)")
136
- import importlib, sync_manager as sm
137
- importlib.reload(sm)
138
- _setup_sync(home, sm, raw_enabled=True)
139
-
140
- ev = [
141
- {"at": "2026-01-01T00:00:01+00:00", "session": "s1", "type": "tokens", "total_tokens": 100},
142
- {"at": "2026-01-01T00:00:02+00:00", "session": "s1", "type": "turn", "cost": 1},
143
- ]
144
- _write_events(sm.EVENTS_PATH, ev)
145
- # 구 라인 커서(version 부재) 심음
146
- json.dump({"last_synced_line": 1}, open(sm.SYNC_STATE_PATH, "w"))
147
-
148
- sent = []
149
- sm._post = lambda base, key, path, body: (sent.append(body) or {"result": True, "data": {"accepted": len(body.get("events", [])), "duplicates": 0}}) if path == "/usage/ingest" else {"result": True, "data": {}}
150
- sm._sync_features = lambda *a, **k: None
151
- sm._sync_cohort = lambda *a, **k: None
152
-
153
- res = sm.sync()
154
- all_sent = [e for b in sent for e in b.get("events", [])]
155
- # v1 감지 → offset 0 리셋 → 두 건 모두 재전송(라인 커서 무시)
156
- check("cursor.migrate_resend_all", len(all_sent) == 2, f"sent={len(all_sent)} res={res}")
157
- st = json.load(open(sm.SYNC_STATE_PATH))
158
- check("cursor.v2_written", st.get("version") == 2, str(st))
159
- check("cursor.has_byte_offset", "byte_offset" in st)
160
-
161
-
162
- def test_rotation_no_loss(home):
163
- print("[4] rotation 후 무유실 (sync된 offset까지만 절단)")
164
- import importlib, sync_manager as sm
165
- importlib.reload(sm)
166
- _setup_sync(home, sm, raw_enabled=True)
167
-
168
- ev = [{"at": f"2026-01-01T00:00:0{i}+00:00", "session": "s1", "type": "tokens", "total_tokens": i} for i in range(1, 4)]
169
- _write_events(sm.EVENTS_PATH, ev)
170
-
171
- sent = []
172
- sm._post = lambda base, key, path, body: (sent.append(body) or {"result": True, "data": {"accepted": len(body.get("events", [])), "duplicates": 0}}) if path == "/usage/ingest" else {"result": True, "data": {}}
173
- sm._sync_features = lambda *a, **k: None
174
- sm._sync_cohort = lambda *a, **k: None
175
-
176
- res = sm.sync()
177
- all_sent = [e for b in sent for e in b.get("events", [])]
178
- check("rotation.sent_all", len(all_sent) == 3, f"{len(all_sent)}")
179
- # rotation: 전송 완료 후 events.jsonl 절단 → 남은 tail 없음
180
- remaining = open(sm.EVENTS_PATH).read().strip()
181
- check("rotation.truncated", remaining == "", f"remaining={remaining!r}")
182
- # inode 갱신 후 커서 offset=0
183
- st = json.load(open(sm.SYNC_STATE_PATH))
184
- check("rotation.cursor_reset", st.get("byte_offset") == 0, str(st))
185
-
186
- # 두 번째 sync: 새 이벤트 추가 → 이전 것 재전송 없이 새 것만
187
- sent.clear()
188
- with open(sm.EVENTS_PATH, "a") as f:
189
- f.write(json.dumps({"at": "2026-01-01T00:00:09+00:00", "session": "s2", "type": "turn", "cost": 9}) + "\n")
190
- sm.sync()
191
- all_sent2 = [e for b in sent for e in b.get("events", [])]
192
- check("rotation.second_sync_only_new", len(all_sent2) == 1, f"{len(all_sent2)}")
193
-
194
-
195
- def test_400_quarantine(home):
196
- print("[5] 400 격리 (pending-quarantine, 드롭 금지)")
197
- import importlib, sync_manager as sm
198
- importlib.reload(sm)
199
- _setup_sync(home, sm, raw_enabled=True)
200
-
201
- ev = [{"at": f"2026-01-01T00:00:0{i}+00:00", "session": "s1", "type": "tokens", "total_tokens": i} for i in range(1, 3)]
202
- _write_events(sm.EVENTS_PATH, ev)
203
-
204
- import urllib.error
205
-
206
- def fake_post(base, key, path, body):
207
- if path == "/usage/ingest":
208
- raise sm._BatchQuarantine()
209
- return {"result": True, "data": {}}
210
- sm._post = fake_post
211
- sm._sync_features = lambda *a, **k: None
212
- sm._sync_cohort = lambda *a, **k: None
213
-
214
- res = sm.sync()
215
- check("quarantine.status_ok", res.get("status") == "ok", str(res))
216
- check("quarantine.count", res.get("quarantined") == 2, str(res))
217
- q = open(sm.QUARANTINE_PATH).read().strip().split("\n")
218
- check("quarantine.file_written", len([l for l in q if l]) == 2, str(q))
219
- # 격리 후 pending에는 없어야(드롭도 아니고 pending 오염도 아님)
220
- check("quarantine.not_in_pending", not os.path.exists(sm.PENDING_PATH) or open(sm.PENDING_PATH).read().strip() == "")
221
-
222
-
223
- def test_gate_off(home):
224
- print("[6] 게이트 off: 신규 8종 비전송 + 기존 정상 전송 + 커서 비전진")
225
- import importlib, sync_manager as sm
226
- importlib.reload(sm)
227
- _setup_sync(home, sm, raw_enabled=False) # raw_events_enabled off
228
-
229
- ev = [
230
- {"at": "2026-01-01T00:00:01+00:00", "session": "s1", "type": "tokens", "total_tokens": 100}, # 기존
231
- {"at": "2026-01-01T00:00:02+00:00", "session": "s1", "type": "encounter", "metadata": {"sig": "x", "junk": "d"}}, # 신규 8종
232
- {"at": "2026-01-01T00:00:03+00:00", "session": "s1", "type": "turn", "cost": 1}, # 기존
233
- ]
234
- _write_events(sm.EVENTS_PATH, ev)
235
-
236
- sent = []
237
- sm._post = lambda base, key, path, body: (sent.append(body) or {"result": True, "data": {"accepted": len(body.get("events", [])), "duplicates": 0}}) if path == "/usage/ingest" else {"result": True, "data": {}}
238
- sm._sync_features = lambda *a, **k: None
239
- sm._sync_cohort = lambda *a, **k: None
240
-
241
- res = sm.sync()
242
- all_sent = [e for b in sent for e in b.get("events", [])]
243
- types_sent = sorted(e["eventType"] for e in all_sent)
244
- check("gate.only_legacy_sent", types_sent == ["tokens", "turn"], f"sent={types_sent}")
245
- check("gate.encounter_not_sent", "encounter" not in types_sent)
246
- check("gate.withheld_reported", res.get("withheld") == 1, str(res))
247
- # 커서 비전진(off 기간 데이터 보존): events.jsonl 그대로, encounter 여전히 존재
248
- body = open(sm.EVENTS_PATH).read()
249
- check("gate.encounter_preserved", "encounter" in body)
250
- # 커서가 전진하지 않았으므로 재sync 시 다시 시도 가능(state 미저장 또는 offset 0)
251
- st = {}
252
- try:
253
- st = json.load(open(sm.SYNC_STATE_PATH))
254
- except Exception:
255
- pass
256
- check("gate.cursor_not_advanced", st.get("byte_offset", 0) == 0, str(st))
257
-
258
- # 게이트 on 전환 후: 축적된 encounter가 정상 sync
259
- json.dump({"flags": {"raw_events_enabled": True}}, open(sm.REMOTE_FLAGS_PATH, "w"))
260
- sent.clear()
261
- sm.sync()
262
- all_sent2 = [e for b in sent for e in b.get("events", [])]
263
- types2 = sorted(e["eventType"] for e in all_sent2)
264
- check("gate.on_flush_includes_encounter", "encounter" in types2, f"sent2={types2}")
265
-
266
-
267
- def test_transform_raw_metadata():
268
- print("[7] _transform 8종 metadata 화이트리스트")
269
- import importlib, sync_manager as sm
270
- importlib.reload(sm)
271
- e = {"at": "2026-01-01T00:00:00+00:00", "session": "s1", "type": "exposure",
272
- "metadata": {"kid": "ef:14", "k_author": 5, "k_problem": "p", "k_scope": "tenant",
273
- "kind": "error-fix", "path": "search", "LEAK": "no"}}
274
- t = sm._transform(e, user_id=42, tenant_id=7)
275
- md = t["metadata"]
276
- check("transform.exposure_kid", md.get("kid") == "ef:14")
277
- check("transform.exposure_kauthor", md.get("k_author") == 5)
278
- check("transform.exposure_leak_dropped", "LEAK" not in md)
279
- check("transform.tenant_injected", md.get("tenant_id") == 7)
280
- check("transform.idempotency", t["idempotencyKey"] == "42:s1:2026-01-01T00:00:00+00:00:exposure")
281
-
282
-
283
- def test_sync_401_marker(home):
284
- print("[8] W0' sync 401 → auth-failure 마커 write + pending 보존")
285
- import importlib, sync_manager as sm
286
- importlib.reload(sm)
287
- _setup_sync(home, sm, raw_enabled=True)
288
- _write_events(sm.EVENTS_PATH, [{"at": "2026-01-01T00:00:01+00:00", "session": "s1", "type": "tokens", "total_tokens": 5}])
289
-
290
- marker = {"done": False}
291
- def fake_note(label):
292
- marker["done"] = True
293
- marker["label"] = label
294
- sm._note_auth_failure = fake_note
295
- def raise401(*a, **k):
296
- raise sm._AuthFailed()
297
- sm._post = raise401
298
- sm._sync_features = lambda *a, **k: None
299
-
300
- res = sm.sync()
301
- check("w0.status_auth_failed", res.get("status") == "auth_failed", str(res))
302
- check("w0.marker_written", marker["done"] is True)
303
- check("w0.marker_label_sync", marker.get("label") == "sync", str(marker))
304
- check("w0.pending_preserved", os.path.exists(sm.PENDING_PATH))
305
-
306
-
307
- def test_backoff(home):
308
- print("[9] 429/503 backoff → 잔여 즉시 중단 (pending 보존)")
309
- import importlib, sync_manager as sm
310
- importlib.reload(sm)
311
- _setup_sync(home, sm, raw_enabled=True)
312
- _write_events(sm.EVENTS_PATH, [{"at": f"2026-01-01T00:00:0{i}+00:00", "session": "s1", "type": "tokens", "total_tokens": i} for i in range(1, 3)])
313
- def raise_backoff(*a, **k):
314
- raise sm._Backoff()
315
- sm._post = raise_backoff
316
- sm._sync_features = lambda *a, **k: None
317
- sm._sync_cohort = lambda *a, **k: None
318
- res = sm.sync()
319
- check("backoff.status", res.get("status") == "backoff", str(res))
320
- check("backoff.pending_preserved", os.path.exists(sm.PENDING_PATH))
321
-
322
-
323
- def test_400_per_event_joi(home):
324
- print("[10] 400 per-event 격리: 500건 중 1건 불량 → 1건만 격리 + 499건 전송 (Joi 인덱스)")
325
- import importlib, sync_manager as sm
326
- importlib.reload(sm)
327
- _setup_sync(home, sm, raw_enabled=True)
328
- # 500건 (index 37을 불량으로 표시). at 유니크 보장.
329
- ev = [{"at": f"2026-01-01T00:{i//60:02d}:{i%60:02d}+00:00", "session": "s1",
330
- "type": "tokens", "total_tokens": i, "bad": (i == 37)} for i in range(500)]
331
- _write_events(sm.EVENTS_PATH, ev)
332
-
333
- sent_ok = []
334
-
335
- def fake_post(base, key, path, body):
336
- if path != "/usage/ingest":
337
- return {"result": True, "data": {}}
338
- events = body.get("events", [])
339
- # 불량 찾기: metadata 없음. 원본 bad 플래그는 _transform에서 사라지므로
340
- # 여기선 total_tokens==37인 이벤트를 불량으로 간주(재현용). Joi 스타일 400 반환.
341
- bad_local = [j for j, e in enumerate(events) if e.get("value") == 37 or (e.get("metadata", {}).get("total_tokens") == 37)]
342
- if bad_local:
343
- body_json = json.dumps({"error": "ValidationError",
344
- "details": [{"path": ["events", bad_local[0], "metadata"],
345
- "message": f"\"events[{bad_local[0]}].metadata\" invalid"}]})
346
- raise sm._BatchQuarantine(body=body_json)
347
- sent_ok.extend(events)
348
- return {"result": True, "data": {"accepted": len(events), "duplicates": 0}}
349
-
350
- sm._post = fake_post
351
- sm._sync_features = lambda *a, **k: None
352
- sm._sync_cohort = lambda *a, **k: None
353
-
354
- res = sm.sync()
355
- check("joi.status_ok", res.get("status") == "ok", str(res))
356
- check("joi.quarantined_1", res.get("quarantined") == 1, str(res))
357
- check("joi.sent_499", len(sent_ok) == 499, f"sent={len(sent_ok)}")
358
- q = [l for l in open(sm.QUARANTINE_PATH).read().strip().split("\n") if l]
359
- check("joi.quarantine_file_1", len(q) == 1, str(q))
360
- # 격리된 것이 정확히 value==37 이벤트
361
- qe = json.loads(q[0])
362
- check("joi.correct_event", qe.get("value") == 37, str(qe))
363
-
364
-
365
- def test_400_bisect_fallback(home):
366
- print("[11] 400 인덱스 파싱 불가 → bisect로 1건만 격리 + 499건 전송")
367
- import importlib, sync_manager as sm
368
- importlib.reload(sm)
369
- _setup_sync(home, sm, raw_enabled=True)
370
- ev = [{"at": f"2026-01-01T00:{i//60:02d}:{i%60:02d}+00:00", "session": "s1",
371
- "type": "tokens", "total_tokens": i} for i in range(500)]
372
- _write_events(sm.EVENTS_PATH, ev)
373
-
374
- sent_ok = []
375
-
376
- def fake_post(base, key, path, body):
377
- if path != "/usage/ingest":
378
- return {"result": True, "data": {}}
379
- events = body.get("events", [])
380
- has_bad = any(e.get("value") == 37 for e in events)
381
- if has_bad:
382
- # 인덱스 정보 없는 불투명 400 (파싱 불가) → bisect 유도
383
- raise sm._BatchQuarantine(body="Bad Request")
384
- sent_ok.extend(events)
385
- return {"result": True, "data": {"accepted": len(events), "duplicates": 0}}
386
-
387
- sm._post = fake_post
388
- sm._sync_features = lambda *a, **k: None
389
- sm._sync_cohort = lambda *a, **k: None
390
-
391
- res = sm.sync()
392
- check("bisect.status_ok", res.get("status") == "ok", str(res))
393
- check("bisect.quarantined_1", res.get("quarantined") == 1, str(res))
394
- check("bisect.sent_499", len(sent_ok) == 499, f"sent={len(sent_ok)}")
395
- q = [l for l in open(sm.QUARANTINE_PATH).read().strip().split("\n") if l]
396
- check("bisect.correct_event", len(q) == 1 and json.loads(q[0]).get("value") == 37, str(q))
397
-
398
-
399
- def test_transform_empty_project_omitted():
400
- print("[12] cwd 없는 이벤트 → project 키 생략 (빈 문자열 400 방지)")
401
- import importlib, sync_manager as sm
402
- importlib.reload(sm)
403
- # cwd 없음
404
- e1 = {"at": "2026-01-01T00:00:00+00:00", "session": "s1", "type": "turn", "cost": 1}
405
- t1 = sm._transform(e1, user_id=42, tenant_id=7)
406
- check("proj.omitted_when_empty", "project" not in t1["metadata"], str(t1["metadata"]))
407
- check("proj.tenant_still_present", t1["metadata"].get("tenant_id") == 7)
408
- # cwd 있음 → project 존재
409
- e2 = {"at": "2026-01-01T00:00:00+00:00", "session": "s1", "type": "turn", "cost": 1, "cwd": "/x/y/myproj"}
410
- t2 = sm._transform(e2, user_id=42, tenant_id=7)
411
- check("proj.present_when_cwd", t2["metadata"].get("project") == "myproj", str(t2["metadata"]))
412
-
413
-
414
- def main():
415
- test_golden()
416
- home = tempfile.mkdtemp(prefix="rc-w1-")
417
- try:
418
- os.environ["HOME"] = home # emit_raw uses expanduser at import; we override const anyway
419
- test_emit_raw(home)
420
- # sync tests each get a fresh usage dir under the same fakehome subdir
421
- for t in (test_cursor_migration, test_rotation_no_loss, test_400_quarantine,
422
- test_gate_off, test_sync_401_marker, test_backoff,
423
- test_400_per_event_joi, test_400_bisect_fallback):
424
- sub = tempfile.mkdtemp(prefix="rc-w1s-")
425
- t(sub)
426
- test_transform_raw_metadata()
427
- test_transform_empty_project_omitted()
428
- finally:
429
- shutil.rmtree(home, ignore_errors=True)
430
-
431
- print()
432
- print(f"RESULT: {len(PASS)} passed, {len(FAIL)} failed")
433
- if FAIL:
434
- for name, detail in FAIL:
435
- print(f" FAILED: {name} :: {detail}")
436
- sys.exit(1)
437
- sys.exit(0)
438
-
439
-
440
- if __name__ == "__main__":
441
- main()