devtorch-core 3.0.1__py3-none-any.whl

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 (193) hide show
  1. devtorch_core/__init__.py +158 -0
  2. devtorch_core/aggphi_textual.py +275 -0
  3. devtorch_core/alerts/__init__.py +23 -0
  4. devtorch_core/alerts/base.py +46 -0
  5. devtorch_core/alerts/config.py +60 -0
  6. devtorch_core/alerts/dispatcher.py +110 -0
  7. devtorch_core/alerts/jira.py +96 -0
  8. devtorch_core/alerts/linear.py +72 -0
  9. devtorch_core/alerts/pagerduty.py +66 -0
  10. devtorch_core/alerts/slack.py +81 -0
  11. devtorch_core/alerts/teams.py +70 -0
  12. devtorch_core/audit/__init__.py +43 -0
  13. devtorch_core/audit/exporter.py +297 -0
  14. devtorch_core/audit/privacy.py +101 -0
  15. devtorch_core/audit/scrubber.py +149 -0
  16. devtorch_core/audit/service.py +67 -0
  17. devtorch_core/audit/signing.py +127 -0
  18. devtorch_core/broadcast/__init__.py +4 -0
  19. devtorch_core/broadcast/broadcaster.py +100 -0
  20. devtorch_core/broadcast/watcher.py +71 -0
  21. devtorch_core/capability.py +639 -0
  22. devtorch_core/cloud/__init__.py +1 -0
  23. devtorch_core/cloud/client_config.py +472 -0
  24. devtorch_core/cloud/client_configs/.claude-opencode-fallback.json +8 -0
  25. devtorch_core/cloud/client_configs/.claude-stdio.json +13 -0
  26. devtorch_core/cloud/client_configs/.cursor-mcp.json +13 -0
  27. devtorch_core/cloud/client_configs/.opencode-bridge.json +13 -0
  28. devtorch_core/cloud/client_configs/.opencode.json +15 -0
  29. devtorch_core/cloud/client_configs/.vscode-mcp.json +13 -0
  30. devtorch_core/cloud/devtorch-mcp-bridge.js +357 -0
  31. devtorch_core/cloud/mcp_client.py +229 -0
  32. devtorch_core/cloud/setup.py +144 -0
  33. devtorch_core/cloud/sync.py +143 -0
  34. devtorch_core/cloud/sync_bundle.py +603 -0
  35. devtorch_core/cloud/sync_conflicts.py +159 -0
  36. devtorch_core/cloud/sync_state.py +159 -0
  37. devtorch_core/cloud/team_sync.py +283 -0
  38. devtorch_core/codex/__init__.py +9 -0
  39. devtorch_core/codex/__main__.py +97 -0
  40. devtorch_core/codex/capture.py +208 -0
  41. devtorch_core/codex/proxy.py +412 -0
  42. devtorch_core/concept_catalog.py +209 -0
  43. devtorch_core/consolidation/__init__.py +3 -0
  44. devtorch_core/consolidation/synthesizer.py +87 -0
  45. devtorch_core/consolidation/workflow.py +175 -0
  46. devtorch_core/daemon/__init__.py +27 -0
  47. devtorch_core/daemon/supervisor.py +293 -0
  48. devtorch_core/daemon/watcher.py +244 -0
  49. devtorch_core/dashboard_api.py +2012 -0
  50. devtorch_core/deltaf.py +97 -0
  51. devtorch_core/disclosure.py +50 -0
  52. devtorch_core/divergence/__init__.py +3 -0
  53. devtorch_core/divergence/detector.py +166 -0
  54. devtorch_core/gateway/__init__.py +32 -0
  55. devtorch_core/gateway/key_manager.py +124 -0
  56. devtorch_core/gateway/metrics_webhook.py +252 -0
  57. devtorch_core/gateway/policy.py +262 -0
  58. devtorch_core/gateway/server.py +727 -0
  59. devtorch_core/gateway/sso.py +233 -0
  60. devtorch_core/gcc.py +1246 -0
  61. devtorch_core/github/__init__.py +35 -0
  62. devtorch_core/github/app.py +240 -0
  63. devtorch_core/github/comment_builder.py +113 -0
  64. devtorch_core/github/pat.py +76 -0
  65. devtorch_core/github/pr_parser.py +82 -0
  66. devtorch_core/github/pr_reporter.py +555 -0
  67. devtorch_core/gitlab/__init__.py +177 -0
  68. devtorch_core/hitl/__init__.py +4 -0
  69. devtorch_core/hitl/channels.py +129 -0
  70. devtorch_core/hitl/orchestrator.py +95 -0
  71. devtorch_core/hooks/__init__.py +17 -0
  72. devtorch_core/hooks/claude_code.py +228 -0
  73. devtorch_core/hooks/git_capture.py +341 -0
  74. devtorch_core/hooks/git_commit.py +182 -0
  75. devtorch_core/hooks/installer.py +733 -0
  76. devtorch_core/hooks/pre_commit.py +157 -0
  77. devtorch_core/hooks/runner.py +344 -0
  78. devtorch_core/identity/__init__.py +4 -0
  79. devtorch_core/identity/agent.py +86 -0
  80. devtorch_core/identity/providers.py +85 -0
  81. devtorch_core/invariants.py +182 -0
  82. devtorch_core/mcp/__init__.py +10 -0
  83. devtorch_core/mcp/auth.py +177 -0
  84. devtorch_core/mcp/server.py +1049 -0
  85. devtorch_core/metrics/__init__.py +35 -0
  86. devtorch_core/metrics/aggregate.py +215 -0
  87. devtorch_core/metrics/calibrate.py +198 -0
  88. devtorch_core/metrics/calibration.py +125 -0
  89. devtorch_core/metrics/credibility.py +288 -0
  90. devtorch_core/metrics/delivery_time.py +70 -0
  91. devtorch_core/metrics/dhs.py +126 -0
  92. devtorch_core/metrics/mcs.py +96 -0
  93. devtorch_core/metrics/roi.py +88 -0
  94. devtorch_core/metrics/session_writer.py +81 -0
  95. devtorch_core/metrics/shadow_ai.py +117 -0
  96. devtorch_core/metrics/sprint_writer.py +243 -0
  97. devtorch_core/observability/__init__.py +78 -0
  98. devtorch_core/observability/datadog.py +157 -0
  99. devtorch_core/observability/formatter.py +119 -0
  100. devtorch_core/observability/report.py +264 -0
  101. devtorch_core/observability/servicenow.py +147 -0
  102. devtorch_core/observability/splunk.py +218 -0
  103. devtorch_core/observability/webhook.py +227 -0
  104. devtorch_core/parser/__init__.py +30 -0
  105. devtorch_core/parser/blocks.py +216 -0
  106. devtorch_core/parser/inference.py +159 -0
  107. devtorch_core/parser/thinking.py +112 -0
  108. devtorch_core/projects.py +169 -0
  109. devtorch_core/prompt_artifact.py +76 -0
  110. devtorch_core/proxy/__init__.py +9 -0
  111. devtorch_core/proxy/routes/__init__.py +1 -0
  112. devtorch_core/proxy/routes/anthropic.py +264 -0
  113. devtorch_core/proxy/routes/azure_openai.py +336 -0
  114. devtorch_core/proxy/routes/gemini.py +331 -0
  115. devtorch_core/proxy/routes/groq.py +284 -0
  116. devtorch_core/proxy/routes/ollama.py +279 -0
  117. devtorch_core/proxy/routes/openai.py +287 -0
  118. devtorch_core/proxy/server.py +356 -0
  119. devtorch_core/query/__init__.py +15 -0
  120. devtorch_core/query/grep.py +181 -0
  121. devtorch_core/query/hybrid.py +86 -0
  122. devtorch_core/query/semantic.py +157 -0
  123. devtorch_core/rdp.py +105 -0
  124. devtorch_core/reasoning/__init__.py +4 -0
  125. devtorch_core/reasoning/entry.py +31 -0
  126. devtorch_core/reasoning/store.py +122 -0
  127. devtorch_core/reasoning_plus/__init__.py +70 -0
  128. devtorch_core/reasoning_plus/augmenter.py +326 -0
  129. devtorch_core/reasoning_plus/capture.py +51 -0
  130. devtorch_core/reasoning_plus/config.py +256 -0
  131. devtorch_core/reasoning_plus/context.py +262 -0
  132. devtorch_core/reasoning_plus/learning/__init__.py +72 -0
  133. devtorch_core/reasoning_plus/learning/analytics.py +141 -0
  134. devtorch_core/reasoning_plus/learning/api.py +313 -0
  135. devtorch_core/reasoning_plus/learning/chain.py +285 -0
  136. devtorch_core/reasoning_plus/learning/composer.py +74 -0
  137. devtorch_core/reasoning_plus/learning/cross_project.py +234 -0
  138. devtorch_core/reasoning_plus/learning/embeddings.py +209 -0
  139. devtorch_core/reasoning_plus/learning/extractor.py +207 -0
  140. devtorch_core/reasoning_plus/learning/models.py +116 -0
  141. devtorch_core/reasoning_plus/learning/provenance.py +126 -0
  142. devtorch_core/reasoning_plus/learning/recorder.py +81 -0
  143. devtorch_core/reasoning_plus/learning/relevance.py +122 -0
  144. devtorch_core/reasoning_plus/learning/state.py +86 -0
  145. devtorch_core/reasoning_plus/learning/store.py +160 -0
  146. devtorch_core/reasoning_plus/learning/theta_learning_bridge.py +94 -0
  147. devtorch_core/reasoning_plus/prompt.py +90 -0
  148. devtorch_core/rep.py +134 -0
  149. devtorch_core/rep_network/__init__.py +25 -0
  150. devtorch_core/rep_network/merge.py +70 -0
  151. devtorch_core/rep_network/node.py +137 -0
  152. devtorch_core/rep_network/server.py +140 -0
  153. devtorch_core/rep_network/sync.py +207 -0
  154. devtorch_core/sensitivity.py +182 -0
  155. devtorch_core/serve.py +258 -0
  156. devtorch_core/session/__init__.py +39 -0
  157. devtorch_core/session/disagreement.py +188 -0
  158. devtorch_core/session/models.py +114 -0
  159. devtorch_core/session/orchestrator.py +182 -0
  160. devtorch_core/session/planner.py +169 -0
  161. devtorch_core/session/simulator.py +132 -0
  162. devtorch_core/signing.py +290 -0
  163. devtorch_core/sis.py +197 -0
  164. devtorch_core/storage.py +308 -0
  165. devtorch_core/templates/__init__.py +6 -0
  166. devtorch_core/templates/engine.py +122 -0
  167. devtorch_core/templates/go.py +18 -0
  168. devtorch_core/templates/infra.py +19 -0
  169. devtorch_core/templates/library/__init__.py +18 -0
  170. devtorch_core/templates/library/api_design.md +27 -0
  171. devtorch_core/templates/library/bug_fix.md +27 -0
  172. devtorch_core/templates/library/decision_record.md +27 -0
  173. devtorch_core/templates/library/engine.py +228 -0
  174. devtorch_core/templates/library/security_review.md +30 -0
  175. devtorch_core/templates/python.py +19 -0
  176. devtorch_core/templates/react.py +18 -0
  177. devtorch_core/templates/typescript.py +18 -0
  178. devtorch_core/theta.py +221 -0
  179. devtorch_core/theta_synthesis.py +268 -0
  180. devtorch_core/topics.py +320 -0
  181. devtorch_core/variance.py +219 -0
  182. devtorch_core/wrapper/__init__.py +52 -0
  183. devtorch_core/wrapper/anthropic.py +487 -0
  184. devtorch_core/wrapper/base.py +562 -0
  185. devtorch_core/wrapper/bedrock.py +342 -0
  186. devtorch_core/wrapper/gemini.py +422 -0
  187. devtorch_core/wrapper/ollama.py +527 -0
  188. devtorch_core/wrapper/openai.py +461 -0
  189. devtorch_core-3.0.1.dist-info/METADATA +867 -0
  190. devtorch_core-3.0.1.dist-info/RECORD +193 -0
  191. devtorch_core-3.0.1.dist-info/WHEEL +5 -0
  192. devtorch_core-3.0.1.dist-info/entry_points.txt +2 -0
  193. devtorch_core-3.0.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,412 @@
1
+ """
2
+ devtorch_core.codex.proxy
3
+ =========================
4
+ Lightweight HTTP proxy server for intercepting OpenAI Codex CLI traffic.
5
+
6
+ Uses only stdlib (http.server, urllib.request, threading) — no FastAPI or
7
+ httpx dependency required.
8
+
9
+ Default port: 8766 (main DevTorch proxy runs on 8765)
10
+ Upstream: https://api.openai.com
11
+
12
+ Routes:
13
+ POST /v1/* → inject RACP, forward, capture response
14
+ GET /health → 200 {"status": "ok"}
15
+ * (everything else) → transparent forward
16
+
17
+ Errors always return 502 JSON — never crash the proxy.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import logging
23
+ import threading
24
+ import urllib.error
25
+ import urllib.request
26
+ from http.server import BaseHTTPRequestHandler, HTTPServer
27
+ from pathlib import Path
28
+ from typing import Optional
29
+
30
+ logger = logging.getLogger("devtorch.codex.proxy")
31
+
32
+ DEFAULT_PORT = 8766
33
+ DEFAULT_UPSTREAM = "https://api.openai.com"
34
+
35
+ # Headers that must NOT be forwarded to the upstream (they are hop-by-hop or
36
+ # set by the proxy itself when re-encoding the body).
37
+ _HOP_BY_HOP = frozenset(
38
+ [
39
+ "connection",
40
+ "keep-alive",
41
+ "proxy-authenticate",
42
+ "proxy-authorization",
43
+ "te",
44
+ "trailers",
45
+ "transfer-encoding",
46
+ "upgrade",
47
+ "host",
48
+ "content-length", # recalculated after body modification
49
+ ]
50
+ )
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Request handler
55
+ # ---------------------------------------------------------------------------
56
+
57
+ class _CodexRequestHandler(BaseHTTPRequestHandler):
58
+ """One instance per incoming HTTP connection."""
59
+
60
+ # Injected by CodexProxy on the server object
61
+ upstream: str = DEFAULT_UPSTREAM
62
+
63
+ # Silence the default access log — we write our own on error
64
+ def log_message(self, fmt: str, *args) -> None: # type: ignore[override]
65
+ pass
66
+
67
+ # ------------------------------------------------------------------
68
+ # Routing
69
+ # ------------------------------------------------------------------
70
+
71
+ def do_GET(self) -> None:
72
+ if self.path == "/health":
73
+ self._send_json(200, {"status": "ok", "proxy": "devtorch-codex"})
74
+ return
75
+ self._forward_transparent()
76
+
77
+ def do_POST(self) -> None:
78
+ if self.path.startswith("/v1/"):
79
+ self._handle_v1_post()
80
+ else:
81
+ self._forward_transparent()
82
+
83
+ # Support additional methods by transparent proxy
84
+ def do_PUT(self) -> None:
85
+ self._forward_transparent()
86
+
87
+ def do_DELETE(self) -> None:
88
+ self._forward_transparent()
89
+
90
+ def do_PATCH(self) -> None:
91
+ self._forward_transparent()
92
+
93
+ def do_HEAD(self) -> None:
94
+ self._forward_transparent()
95
+
96
+ def do_OPTIONS(self) -> None:
97
+ self._forward_transparent()
98
+
99
+ # ------------------------------------------------------------------
100
+ # v1 POST handler — RACP injection + capture
101
+ # ------------------------------------------------------------------
102
+
103
+ def _handle_v1_post(self) -> None:
104
+ try:
105
+ body_bytes = self._read_body()
106
+ except Exception as exc:
107
+ self._send_error_502(f"failed to read request body: {exc}")
108
+ return
109
+
110
+ # Parse JSON — if not parseable, forward raw
111
+ try:
112
+ request_body = json.loads(body_bytes) if body_bytes else {}
113
+ except Exception:
114
+ request_body = None
115
+
116
+ # Inject RACP prefix
117
+ modified_body_bytes = body_bytes
118
+ if request_body is not None:
119
+ try:
120
+ from devtorch_core.codex.capture import CodexCaptureHandler
121
+ import uuid
122
+
123
+ session_id = str(uuid.uuid4())
124
+ handler = CodexCaptureHandler()
125
+ modified_body = handler.pre_execute(request_body, session_id)
126
+ modified_body_bytes = json.dumps(modified_body).encode("utf-8")
127
+ except Exception as exc:
128
+ logger.warning("devtorch codex RACP injection failed — %s", exc)
129
+ session_id = ""
130
+ handler = None
131
+ else:
132
+ session_id = ""
133
+ handler = None
134
+
135
+ # Forward to upstream
136
+ upstream_url = self.upstream.rstrip("/") + self.path
137
+ fwd_headers = self._build_forward_headers(len(modified_body_bytes))
138
+
139
+ try:
140
+ req = urllib.request.Request(
141
+ upstream_url,
142
+ data=modified_body_bytes,
143
+ headers=fwd_headers,
144
+ method="POST",
145
+ )
146
+ with urllib.request.urlopen(req) as resp:
147
+ resp_bytes = resp.read()
148
+ resp_status = resp.status
149
+ resp_headers = dict(resp.headers)
150
+ except urllib.error.HTTPError as exc:
151
+ resp_bytes = exc.read()
152
+ resp_status = exc.code
153
+ resp_headers = dict(exc.headers)
154
+ except Exception as exc:
155
+ self._send_error_502(f"upstream request failed: {exc}")
156
+ return
157
+
158
+ # Send response back to Codex CLI
159
+ self._relay_response(resp_status, resp_headers, resp_bytes)
160
+
161
+ # Fire post_execute in background — never blocks the response
162
+ if handler is not None and request_body is not None:
163
+ try:
164
+ resp_body = json.loads(resp_bytes) if resp_bytes else {}
165
+ except Exception:
166
+ resp_body = {}
167
+ t = threading.Thread(
168
+ target=_safe_post_execute,
169
+ args=(handler, request_body, resp_body, session_id),
170
+ daemon=True,
171
+ )
172
+ t.start()
173
+
174
+ # ------------------------------------------------------------------
175
+ # Transparent forward
176
+ # ------------------------------------------------------------------
177
+
178
+ def _forward_transparent(self) -> None:
179
+ try:
180
+ body_bytes = self._read_body()
181
+ except Exception as exc:
182
+ self._send_error_502(f"failed to read request body: {exc}")
183
+ return
184
+
185
+ upstream_url = self.upstream.rstrip("/") + self.path
186
+ fwd_headers = self._build_forward_headers(len(body_bytes) if body_bytes else 0)
187
+
188
+ try:
189
+ req = urllib.request.Request(
190
+ upstream_url,
191
+ data=body_bytes if body_bytes else None,
192
+ headers=fwd_headers,
193
+ method=self.command,
194
+ )
195
+ with urllib.request.urlopen(req) as resp:
196
+ resp_bytes = resp.read()
197
+ resp_status = resp.status
198
+ resp_headers = dict(resp.headers)
199
+ except urllib.error.HTTPError as exc:
200
+ resp_bytes = exc.read()
201
+ resp_status = exc.code
202
+ resp_headers = dict(exc.headers)
203
+ except Exception as exc:
204
+ self._send_error_502(f"upstream request failed: {exc}")
205
+ return
206
+
207
+ self._relay_response(resp_status, resp_headers, resp_bytes)
208
+
209
+ # ------------------------------------------------------------------
210
+ # Helpers
211
+ # ------------------------------------------------------------------
212
+
213
+ def _read_body(self) -> bytes:
214
+ length = int(self.headers.get("Content-Length", 0))
215
+ if length > 0:
216
+ return self.rfile.read(length)
217
+ return b""
218
+
219
+ def _build_forward_headers(self, content_length: int) -> dict:
220
+ """Build headers to send upstream, stripping hop-by-hop headers."""
221
+ headers: dict = {}
222
+ for key, val in self.headers.items():
223
+ if key.lower() not in _HOP_BY_HOP:
224
+ headers[key] = val
225
+ if content_length > 0:
226
+ headers["Content-Length"] = str(content_length)
227
+ # Ensure Host is set to the upstream host
228
+ from urllib.parse import urlparse
229
+ parsed = urlparse(self.upstream)
230
+ headers["Host"] = parsed.netloc
231
+ return headers
232
+
233
+ def _relay_response(self, status: int, headers: dict, body: bytes) -> None:
234
+ """Write upstream response back to the Codex CLI connection."""
235
+ self.send_response(status)
236
+ for key, val in headers.items():
237
+ if key.lower() not in ("transfer-encoding", "connection"):
238
+ self.send_header(key, val)
239
+ self.send_header("Content-Length", str(len(body)))
240
+ self.end_headers()
241
+ if body:
242
+ self.wfile.write(body)
243
+
244
+ def _send_json(self, status: int, payload: dict) -> None:
245
+ body = json.dumps(payload).encode("utf-8")
246
+ self.send_response(status)
247
+ self.send_header("Content-Type", "application/json")
248
+ self.send_header("Content-Length", str(len(body)))
249
+ self.end_headers()
250
+ self.wfile.write(body)
251
+
252
+ def _send_error_502(self, detail: str) -> None:
253
+ logger.warning("devtorch codex proxy 502 — %s", detail)
254
+ self._send_json(502, {"error": "bad_gateway", "detail": detail})
255
+
256
+
257
+ # ---------------------------------------------------------------------------
258
+ # Background post_execute helper
259
+ # ---------------------------------------------------------------------------
260
+
261
+ def _safe_post_execute(
262
+ handler: object,
263
+ request_body: dict,
264
+ response_body: dict,
265
+ session_id: str,
266
+ ) -> None:
267
+ try:
268
+ handler.post_execute(request_body, response_body, session_id) # type: ignore[attr-defined]
269
+ except Exception as exc:
270
+ logger.warning("devtorch codex post_execute background error — %s", exc)
271
+
272
+
273
+ # ---------------------------------------------------------------------------
274
+ # CodexProxy
275
+ # ---------------------------------------------------------------------------
276
+
277
+ class CodexProxy:
278
+ """
279
+ Lightweight stdlib-only HTTP proxy for intercepting Codex CLI traffic.
280
+
281
+ Parameters
282
+ ----------
283
+ port:
284
+ Local port to bind on (default 8766).
285
+ upstream:
286
+ Base URL of the real OpenAI API (default https://api.openai.com).
287
+ """
288
+
289
+ def __init__(
290
+ self,
291
+ port: int = DEFAULT_PORT,
292
+ upstream: str = DEFAULT_UPSTREAM,
293
+ ) -> None:
294
+ self.port = port
295
+ self.upstream = upstream
296
+ self._server: Optional[HTTPServer] = None
297
+ self._thread: Optional[threading.Thread] = None
298
+
299
+ def start(self) -> None:
300
+ """Start the proxy server (blocking — press Ctrl+C to stop)."""
301
+ self._server = self._make_server()
302
+ try:
303
+ self._server.serve_forever()
304
+ except KeyboardInterrupt:
305
+ pass
306
+ finally:
307
+ self._server.server_close()
308
+
309
+ def start_background(self) -> threading.Thread:
310
+ """
311
+ Start the proxy in a daemon thread.
312
+
313
+ Returns the thread (already started). Call stop() to shut down.
314
+ """
315
+ self._server = self._make_server()
316
+ t = threading.Thread(target=self._server.serve_forever, daemon=True)
317
+ t.start()
318
+ self._thread = t
319
+ return t
320
+
321
+ def stop(self) -> None:
322
+ """Shut down the proxy server gracefully."""
323
+ if self._server is not None:
324
+ self._server.shutdown()
325
+ self._server.server_close()
326
+ self._server = None
327
+
328
+ # ------------------------------------------------------------------
329
+ # Internal
330
+ # ------------------------------------------------------------------
331
+
332
+ def _make_server(self) -> HTTPServer:
333
+ upstream = self.upstream
334
+
335
+ class _Handler(_CodexRequestHandler):
336
+ pass
337
+
338
+ _Handler.upstream = upstream # type: ignore[assignment]
339
+ server = HTTPServer(("127.0.0.1", self.port), _Handler)
340
+ server.timeout = 30
341
+ return server
342
+
343
+
344
+ # ---------------------------------------------------------------------------
345
+ # install_codex_hook
346
+ # ---------------------------------------------------------------------------
347
+
348
+ def install_codex_hook(project_root: str) -> tuple[bool, str]:
349
+ """
350
+ Create `.codex/config.json` under *project_root* pointing at the local
351
+ DevTorch Codex proxy.
352
+
353
+ Idempotent — does not overwrite an existing config.
354
+
355
+ Returns (True, config_path) on success, (False, error_message) on failure.
356
+ """
357
+ try:
358
+ codex_dir = Path(project_root) / ".codex"
359
+ codex_dir.mkdir(parents=True, exist_ok=True)
360
+
361
+ config_path = codex_dir / "config.json"
362
+
363
+ # Idempotent — do not overwrite if already present
364
+ if config_path.exists():
365
+ return True, str(config_path)
366
+
367
+ config = {
368
+ "apiBase": f"http://localhost:{DEFAULT_PORT}/v1",
369
+ "provider": "openai",
370
+ }
371
+ config_path.write_text(json.dumps(config, indent=2), encoding="utf-8")
372
+ return True, str(config_path)
373
+
374
+ except Exception as exc:
375
+ return False, str(exc)
376
+
377
+
378
+ # ---------------------------------------------------------------------------
379
+ # get_codex_hook_status
380
+ # ---------------------------------------------------------------------------
381
+
382
+ def get_codex_hook_status(project_root: str) -> dict:
383
+ """
384
+ Return the install and runtime status of the DevTorch Codex proxy.
385
+
386
+ Returns::
387
+
388
+ {
389
+ "codex_config": bool, # .codex/config.json exists
390
+ "codex_config_path": str, # absolute path to config file
391
+ "proxy_running": bool, # True if GET /health returns 200
392
+ }
393
+ """
394
+ config_path = Path(project_root) / ".codex" / "config.json"
395
+ codex_config = config_path.exists()
396
+
397
+ proxy_running = False
398
+ try:
399
+ req = urllib.request.Request(
400
+ f"http://localhost:{DEFAULT_PORT}/health",
401
+ method="GET",
402
+ )
403
+ with urllib.request.urlopen(req, timeout=2) as resp:
404
+ proxy_running = resp.status == 200
405
+ except Exception:
406
+ proxy_running = False
407
+
408
+ return {
409
+ "codex_config": codex_config,
410
+ "codex_config_path": str(config_path),
411
+ "proxy_running": proxy_running,
412
+ }
@@ -0,0 +1,209 @@
1
+ """
2
+ devtorch_core.concept_catalog
3
+ ==============================
4
+ Unified concept enumeration across all DevTorch data sources.
5
+
6
+ Sources:
7
+ - I3 concept definitions (.GCC/concepts/*.json)
8
+ - Theta coordination vector (.GCC/theta.json)
9
+ - Sensitivity events (.GCC/sensitivities/events.jsonl)
10
+ - Learning trigger_concepts (.GCC/reasoning_learnings/learnings/*.json)
11
+ - Commit concepts (.GCC/commits/*.json)
12
+ - Call concepts (.GCC/reasoning_learnings/calls/*.json)
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from devtorch_core.topics import TopicStore
22
+
23
+ logger = logging.getLogger("devtorch.concept_catalog")
24
+
25
+
26
+ class ConceptCatalog:
27
+ """Unify all concept sources into a single enumerator."""
28
+
29
+ def __init__(self, gcc_dir: Path | str) -> None:
30
+ self._gcc_dir = Path(gcc_dir)
31
+
32
+ def enumerate_all(self) -> dict[str, list[str]]:
33
+ """Return {concept_name: [source1, source2, ...]} from all sources.
34
+
35
+ All concept names are lowercased for deduplication.
36
+ """
37
+ result: dict[str, list[str]] = {}
38
+
39
+ def _add(concept: str, source: str) -> None:
40
+ key = concept.lower()
41
+ if key not in result:
42
+ result[key] = []
43
+ if source not in result[key]:
44
+ result[key].append(source)
45
+
46
+ for name in self._i3_concepts():
47
+ _add(name, "i3_definition")
48
+ for name in self._theta_concepts():
49
+ _add(name, "theta")
50
+ for name in self._sensitivity_concepts():
51
+ _add(name, "sensitivity")
52
+ for name in self._learning_concepts():
53
+ _add(name, "learning")
54
+ for name in self._commit_concepts():
55
+ _add(name, "commit")
56
+ for name in self._call_concepts():
57
+ _add(name, "call")
58
+
59
+ return dict(sorted(result.items()))
60
+
61
+ def enumerate_learned(self) -> dict[str, dict[str, Any]]:
62
+ """Return {concept: {learning_count, active, stale, deprecated, success_rate, avg_confidence}}.
63
+
64
+ Only concepts that have at least one learning are included.
65
+ """
66
+ from devtorch_core.reasoning_plus.learning.analytics import concept_stats
67
+ from devtorch_core.reasoning_plus.learning.store import LearningStore
68
+
69
+ store = LearningStore(self._gcc_dir)
70
+ stats = concept_stats(store)
71
+ result: dict[str, dict[str, Any]] = {}
72
+ for cname, data in stats.items():
73
+ if cname == "__untyped__":
74
+ continue
75
+ result[cname] = {
76
+ "learning_count": data["total"],
77
+ "active": data["active"],
78
+ "stale": data["stale"],
79
+ "deprecated": data["deprecated"],
80
+ "success_rate": data["success_rate"],
81
+ "avg_confidence": data["avg_confidence"],
82
+ }
83
+ return result
84
+
85
+ def concepts_for_topic(
86
+ self, topic: str, hide_empty: bool = True,
87
+ ) -> dict[str, Any]:
88
+ """Return concepts associated with a topic.
89
+
90
+ Returns a dict with:
91
+ - "concepts": list of {name, sources, has_data} for concepts with data
92
+ - "taxonomy_only": list of concept names that have no data (if hide_empty)
93
+ """
94
+ store = TopicStore(self._gcc_dir)
95
+ concepts = store.get_concepts(topic)
96
+ if not concepts:
97
+ return {"concepts": [], "taxonomy_only": []}
98
+
99
+ all_concepts = self.enumerate_all()
100
+ learned = self.enumerate_learned()
101
+
102
+ with_data: list[dict[str, Any]] = []
103
+ without_data: list[str] = []
104
+
105
+ for concept in concepts:
106
+ sources = all_concepts.get(concept.lower(), [])
107
+ if sources:
108
+ entry: dict[str, Any] = {"name": concept, "sources": sources}
109
+ if concept.lower() in learned:
110
+ stats = learned[concept.lower()]
111
+ entry["learning_count"] = stats["learning_count"]
112
+ entry["success_rate"] = stats["success_rate"]
113
+ entry["avg_confidence"] = stats["avg_confidence"]
114
+ with_data.append(entry)
115
+ else:
116
+ without_data.append(concept)
117
+
118
+ return {
119
+ "concepts": with_data,
120
+ "taxonomy_only": without_data if hide_empty else [],
121
+ }
122
+
123
+ def topic_for_concept(self, concept: str) -> str | None:
124
+ """Reverse lookup: which topic does this concept belong to?"""
125
+ store = TopicStore(self._gcc_dir)
126
+ cname = concept.lower()
127
+
128
+ for topic in store.list_topics():
129
+ topic_concepts = [c.lower() for c in topic["concepts"]]
130
+ if cname in topic_concepts:
131
+ return topic["name"]
132
+
133
+ return None
134
+
135
+ def _i3_concepts(self) -> list[str]:
136
+ concepts_dir = self._gcc_dir / "concepts"
137
+ if not concepts_dir.exists():
138
+ return []
139
+ return [p.stem for p in concepts_dir.glob("*.json")]
140
+
141
+ def _theta_concepts(self) -> list[str]:
142
+ path = self._gcc_dir / "theta.json"
143
+ if not path.exists():
144
+ return []
145
+ try:
146
+ data = json.loads(path.read_text(encoding="utf-8"))
147
+ return list(data.get("coordination_vector", {}).keys())
148
+ except (json.JSONDecodeError, OSError):
149
+ return []
150
+
151
+ def _sensitivity_concepts(self) -> list[str]:
152
+ path = self._gcc_dir / "sensitivities" / "events.jsonl"
153
+ if not path.exists():
154
+ return []
155
+ concepts: set[str] = set()
156
+ try:
157
+ for line in path.read_text(encoding="utf-8").splitlines():
158
+ if not line.strip():
159
+ continue
160
+ ev = json.loads(line)
161
+ payload = ev.get("payload", ev)
162
+ concept = payload.get("target_concept", "")
163
+ if concept:
164
+ concepts.add(concept)
165
+ except (json.JSONDecodeError, OSError):
166
+ pass
167
+ return list(concepts)
168
+
169
+ def _learning_concepts(self) -> list[str]:
170
+ path = self._gcc_dir / "reasoning_learnings" / "learnings"
171
+ if not path.exists():
172
+ return []
173
+ concepts: set[str] = set()
174
+ for p in path.glob("*.json"):
175
+ try:
176
+ data = json.loads(p.read_text(encoding="utf-8"))
177
+ for c in data.get("trigger_concepts", []):
178
+ concepts.add(c)
179
+ except (json.JSONDecodeError, OSError):
180
+ continue
181
+ return list(concepts)
182
+
183
+ def _commit_concepts(self) -> list[str]:
184
+ path = self._gcc_dir / "commits"
185
+ if not path.exists():
186
+ return []
187
+ concepts: set[str] = set()
188
+ for p in path.glob("*.json"):
189
+ try:
190
+ data = json.loads(p.read_text(encoding="utf-8"))
191
+ for c in data.get("concepts", []):
192
+ concepts.add(c)
193
+ except (json.JSONDecodeError, OSError):
194
+ continue
195
+ return list(concepts)
196
+
197
+ def _call_concepts(self) -> list[str]:
198
+ path = self._gcc_dir / "reasoning_learnings" / "calls"
199
+ if not path.exists():
200
+ return []
201
+ concepts: set[str] = set()
202
+ for p in path.glob("*.json"):
203
+ try:
204
+ data = json.loads(p.read_text(encoding="utf-8"))
205
+ for c in data.get("concepts", []):
206
+ concepts.add(c)
207
+ except (json.JSONDecodeError, OSError):
208
+ continue
209
+ return list(concepts)
@@ -0,0 +1,3 @@
1
+ from .workflow import ConsolidationRecord, ConsolidationWorkflow
2
+
3
+ __all__ = ["ConsolidationRecord", "ConsolidationWorkflow"]