code-context-control 2.158.3__py3-none-any.whl → 2.158.5__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.
cli/c3.py CHANGED
@@ -91,7 +91,7 @@ console = Console() if HAS_RICH else None
91
91
  # Config
92
92
  CONFIG_DIR = ".c3"
93
93
  CONFIG_FILE = ".c3/config.json"
94
- __version__ = "2.158.3"
94
+ __version__ = "2.158.5"
95
95
 
96
96
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
97
97
  AGENT_MATCHER = "Agent|Task"
cli/hook_session_open.py CHANGED
@@ -40,14 +40,19 @@ by the host pid both of them share and hands it the new id
40
40
  the same MCP process, and a "Session started" toast on every compaction
41
41
  would teach the user to ignore the real ones.
42
42
 
43
+ When the installed fastmcp and mcp cannot load together
44
+ (``core.mcp_stack``), the MCP server dies before its handshake and the host
45
+ reports only a closed connection; this hook then returns the mismatch and
46
+ the pip repair as context, so the session can say why C3's tools are gone.
47
+
43
48
  The MCP server's own ``session_start`` row is untouched — it carries the C3
44
49
  id and, when the host put its id in the environment, ``host_session_id``
45
50
  too. This hook is what lets a client see the session before the runtime has
46
51
  finished starting (~seconds), and it is the row the desktop's "MCP failed to
47
52
  connect" sentinel starts its 30 s clock from.
48
53
 
49
- Returns None always: SessionStart hook stdout becomes model context, and
50
- this hook has nothing to tell the model.
54
+ Returns None, or ``{"_text": <mismatch>}`` for the case above: SessionStart
55
+ hook stdout becomes model context.
51
56
  """
52
57
  from __future__ import annotations
53
58
 
@@ -249,10 +254,19 @@ def hand_off_runtime(project: Path, host: str, host_sid: str, start_source: str)
249
254
 
250
255
 
251
256
  def run(payload: dict, project_path: Path | None = None):
252
- """Core logic — importable by the dispatcher and tests. Returns None."""
257
+ """Core logic — importable by the dispatcher and tests.
258
+
259
+ Returns None, or ``{"_text": ...}`` naming a fastmcp/mcp mismatch.
260
+ """
253
261
  start_source = str(payload.get("source") or "").strip().lower()
254
262
  if start_source in _SILENT_SOURCES:
255
263
  return None
264
+ try:
265
+ from core.mcp_stack import problem
266
+ stack_problem = problem()
267
+ except Exception as exc:
268
+ log_hook_error("hook_session_open", exc)
269
+ stack_problem = None
256
270
  project = find_project(payload, project_path)
257
271
  if project is None:
258
272
  return None
@@ -278,7 +292,7 @@ def run(payload: dict, project_path: Path | None = None):
278
292
  pass
279
293
  hand_off_runtime(project, host, host_sid, start_source)
280
294
  ensure_ui(project, host_sid)
281
- return None
295
+ return {"_text": stack_problem} if stack_problem else None
282
296
 
283
297
 
284
298
  def main() -> None:
cli/mcp_server.py CHANGED
@@ -21,7 +21,16 @@ from typing import Any
21
21
  # Add parent to path for imports
22
22
  sys.path.insert(0, str(Path(__file__).parent.parent))
23
23
 
24
- from fastmcp import Context, FastMCP
24
+ try:
25
+ from fastmcp import Context, FastMCP
26
+ except Exception:
27
+ # The host shows only "connection closed"; stderr reaches its MCP log.
28
+ from core.mcp_stack import problem as _mcp_stack_problem
29
+ _stack_problem = _mcp_stack_problem()
30
+ if not _stack_problem:
31
+ raise
32
+ print(_stack_problem, file=sys.stderr)
33
+ raise SystemExit(1)
25
34
 
26
35
  from cli.tools import _grants
27
36
  from core.host import resolve_host
cli/server.py CHANGED
@@ -346,6 +346,10 @@ def api_projects_open():
346
346
  @app.route('/api/health')
347
347
  def api_health():
348
348
  """Lightweight health check with connection sources."""
349
+ # ?probe=1 is the liveness form: identity only. The hub sends it for every
350
+ # UI server on every /api/projects poll and only reads "service".
351
+ if request.args.get("probe") not in (None, "", "0", "false"):
352
+ return jsonify({"service": "c3-ui", "probe": True})
349
353
  sources = {"c3": True} # If this endpoint responds, C3 API is up
350
354
 
351
355
  # Check Ollama
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-context-control
3
- Version: 2.158.3
3
+ Version: 2.158.5
4
4
  Summary: Local MCP code-intelligence for AI coding tools: surgical search/read/edit, agent-config version history, path-level access + masking guards, and a multi-project hub.
5
5
  Author-email: Dimitri Tselenchuk <dtselenc@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -1,7 +1,7 @@
1
1
  cli/__init__.py,sha256=ec66drCZGNMRU4V6ov0zVhYZph1us12Vn8OvG_LJyRY,22
2
2
  cli/_hook_utils.py,sha256=RhfS2WS5VMSi2w2Jxcts1wg5WC-UFp89JOQvcO5Jjb8,23002
3
3
  cli/_shell_writes.py,sha256=iBbzK0v0d29rhrYgF3zKJIJbb1WSZhQjD_6w8-nOUec,7348
4
- cli/c3.py,sha256=1U8-jQ4LjeHnMzAJDDOQkleXM2aTIgMkf1Tff07N4CE,439372
4
+ cli/c3.py,sha256=fgDpzh09I0KH-AaM1XmMBINW7e6j3ndOc5ooN2Bl2qk,439372
5
5
  cli/docs.html,sha256=pPxcP5ieY0DcfEDvegwIcRxbz1woLZoKLVSF-4JVy0Q,146784
6
6
  cli/edits.html,sha256=UjAhoCmBmQ89cklGvJqzC6eyNP2tc8H6T-e01DVkLvE,43418
7
7
  cli/hook_access_guard.py,sha256=4UF2YHp5_vISH7Gvolc_Bz3ppSye2lGpGx38egRLj1g,32116
@@ -20,15 +20,15 @@ cli/hook_pretool_enforce.py,sha256=pSFYgqiXktJPpNuzGXiFPhcGQRDN9QjMjpQHliO_7XQ,3
20
20
  cli/hook_prompt_recall.py,sha256=LHyubu36pf5h3hbLBe0yH-yGhAlwLJdsc7hfa7WB1h4,3471
21
21
  cli/hook_read.py,sha256=ZWZldgqGSNz78COhlgETQ7yxdOW5vWIIHUet9gZKhxk,8176
22
22
  cli/hook_session_end.py,sha256=toFEPDKRoutDuVOmuOgHmQ8CM0o7tF7yALhMxJz7VEM,3482
23
- cli/hook_session_open.py,sha256=VXStM1vsA2kwLZxczAvetJGf4aDT1dPlWYMeEW4ow4Y,11387
23
+ cli/hook_session_open.py,sha256=Bq8zKPkucPYASQDxJcT1bGm975d__RbTvaiWj9yVcDs,11969
24
24
  cli/hook_session_stats.py,sha256=I-2NeLlV1NxeqKtTM2JH9haSpFU7r4qG0u8pfCJ80YU,8725
25
25
  cli/hook_terse_advisor.py,sha256=W_zaTfX2akgX-ifuUTsLu2H1atM8XmWt6jpPoeU7Pm0,6252
26
26
  cli/hub_server.py,sha256=CnpI0kqpVX-rJkPnGiVyuej8Ay0VHzBLWc-ZxDhEVZA,226168
27
27
  cli/hub_ui.html,sha256=v41R_JAH4Jwodpy3tbeBUel-80FbNmffBrey-QH5Q64,2963
28
28
  cli/mcp_proxy.py,sha256=r-Qhlie7gCtotex8yQUudCyBLRUK-IW6cNIW5RhBW0o,17648
29
- cli/mcp_server.py,sha256=Gg1Chz3j7Lu5ZuU3JFMACNZHWp7KphM_2E8eoNHpp3M,84132
29
+ cli/mcp_server.py,sha256=RcuX1Ljle6kRuMqzmwjsxkLHVQuATepaLJ1C3qIS4u4,84445
30
30
  cli/progress.py,sha256=qTkNy0howOD3hXraMo4ok3dYTpBW5yG_tenKfF4UDM0,1470
31
- cli/server.py,sha256=SQFONagf4Mmsv2Z0fdnr8cxAFUsBE3nPQ5XUZLgtjI8,174039
31
+ cli/server.py,sha256=kK9ZNwPaYmohexrLSYuhncbB_cNN7jWKpFXKewddpPs,174314
32
32
  cli/ui.html,sha256=uuPwIJNKDQH_fsaR3xNB2AKky9WzKfaXnKr_k3aTtxo,5715
33
33
  cli/ui_legacy.html,sha256=cI8tC6RKmE2NIJOcsu7CY-zT4VznjcbD6NTjxb_fvUY,378460
34
34
  cli/ui_nano.html,sha256=UAwQ6bbTOXAoGq191AZ7slhngR9edJSa3IhqpynveDg,27740
@@ -135,7 +135,7 @@ cli/ui/components/sessions.js,sha256=FIKtil76B8tCkAmcFV7hlj6GQ_DCJK2jCzvEmdK7NBE
135
135
  cli/ui/components/settings.js,sha256=FXcn-UQE2mXC6HFsLeEas-wAUFKt0OJaLySroZQMhGA,84095
136
136
  cli/ui/components/sidebar.js,sha256=K2ym2kUgpbyG-EBA_wBIIiqQY8qTatsiBZwzseMWuIQ,9939
137
137
  cli/ui/components/tasks.js,sha256=vyKQ3uwoppMwvdEaHlhWXW4oWcAisx4NveqzMhsYqHo,38438
138
- code_context_control-2.158.3.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
138
+ code_context_control-2.158.5.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
139
139
  core/__init__.py,sha256=TSDCEcM4V7gcZVM3w2ykJaqEUch4Dkon-rivV17T73s,2501
140
140
  core/codex_patch.py,sha256=CxvT_rQIwPNTRJZj9EHJmx0ZdOeSLxjiixuLI3Z7lPc,2107
141
141
  core/config.py,sha256=wCjrZKXRywUbR6WRcO7optyOirAQ2DeRNdPCU0X5zIY,23762
@@ -143,6 +143,7 @@ core/grok_payload.py,sha256=EEwhvkKnCT6Rk9tc-DWDA__toE44244Xr4d6p7SoJwE,5365
143
143
  core/hook_command.py,sha256=SvTDUaBLg1Qb4ZdAgpe14YA_8BSnkGJsd3ByPtqBsU0,1032
144
144
  core/host.py,sha256=WUzS-572l9azYvu1Y4fmAVvb_0g4xyXqzsayJP_zH3M,2075
145
145
  core/ide.py,sha256=0sk2MzrgIScE5fN1cIpjMrNqE5j1Hz_kyPfCT2w-ac8,7061
146
+ core/mcp_stack.py,sha256=ZCiCNKtN-IHFhwyRWz1djFFV1a3vbKBKB6Aefz1HvCo,4462
146
147
  core/mcp_toml.py,sha256=VNZCjJsr4II_jX3cmjYzDh_OQ7Nk34mLnkg528Tl1GM,7047
147
148
  core/web_security.py,sha256=HwgK5aBATfvRIeO_4gWgzK77gKwGuzVlmiuNGm4gGxI,7884
148
149
  oracle/__init__.py,sha256=-OTD7Jh4mUMA4QgPGthPLWXttgZLpkIPhGQ87ZfHBx0,63
@@ -167,8 +168,8 @@ oracle/services/insight_engine.py,sha256=lwcdXtjt3CSZLqHVpXx6SG5gDhZYUKwXt4Z8dGy
167
168
  oracle/services/local_session.py,sha256=nkawOjDbotUp5wtZQnC1wPDw3HopNYMkoYqWpP5ToCU,9227
168
169
  oracle/services/memory_reader.py,sha256=rSEmoIXQu2JkolHJIQWpn0piPJpyuf1KZvW_9liQwkU,3727
169
170
  oracle/services/memory_writer.py,sha256=hpvYsxjhl293jEjGcRKfjG5njUaAOXKqbmJaUu1WdUU,6997
170
- oracle/services/mobile_api.py,sha256=AmP0VBO0914EYCie1ETPhAbsaeQ1hbJqoYRyzgbA5bM,149397
171
- oracle/services/mobile_fleet.py,sha256=lhbmHlrGyLrp3SVqoVj0FsJWOUXHZmVMUsy4WsvHbPs,24045
171
+ oracle/services/mobile_api.py,sha256=xpv5EAVN-mA7Fc0BoWrqZZoVWau-nDgEB7aMCYlwA0I,149909
172
+ oracle/services/mobile_fleet.py,sha256=1M6vN4vOlYdVt1qFDSK97PLPHjvZkus4ZZSRm-ow2Nc,23968
172
173
  oracle/services/project_scanner.py,sha256=PkYJtwOLRME1EzwRy3GIkYk6Xw0u1_BzFcaMJ5gJ1_s,6118
173
174
  oracle/services/review_agent.py,sha256=m_fzoHowpiibf0_iz3dF72LWSrwB_FbDd1am-SbeWXg,11273
174
175
  oracle/services/schedule_api.py,sha256=wArv-2QE-P1qn5gNiMGisXA4kX-JJvsRabFpVqsClzQ,9212
@@ -247,7 +248,7 @@ services/embedding_index.py,sha256=-d6Gatqq5OCrneGbvDTGrWyzbVx7562SrwABOFBRhjY,4
247
248
  services/enforcement_policy.py,sha256=znjABRB-8TSl0ELazY2ALzux2YJ5nWf8TvxLRhDsL2w,18905
248
249
  services/error_reporting.py,sha256=HZ3ru8i5RLf8nq2R4iRnTs5sm1blUxknSbv5hdxuxs0,4139
249
250
  services/file_map.py,sha256=j37DTR-UE_PMNj7vG2HiHucpwpJNaKgiD94UNUU-UXE,17091
250
- services/file_memory.py,sha256=cFEUsf-_aD3uJZiNEkhEIOPB7GzyQmhL2Nj4P8JtmZg,41532
251
+ services/file_memory.py,sha256=6wPXRCnBuRpV3Yi2nTyCU5FD7PyYl93ctLPXI_g1CSY,42387
251
252
  services/fleet_overview.py,sha256=npWzUHoHVlgCafTE79GS7AUYYilMr5yuujuAns4fpLQ,19544
252
253
  services/git_context.py,sha256=FFdA8Y46op4DYsUnZsXLTqxIjgxb0q_d-hkFTbosC8Q,9518
253
254
  services/grok_integration.py,sha256=aiWVmG9e-0-9_MjrJ_p0dsbTSdAYFkLfsUMI7onmz0A,8299
@@ -276,7 +277,7 @@ services/memory_scorer.py,sha256=32wccyVFBgcNwKdjwj_7RDnPukxSWBng8ohsRPTpQMM,949
276
277
  services/metrics.py,sha256=X4D5TgcQSFaFLbBoa1s3bAWf00DMMjq3IrOACrK-uDg,3289
277
278
  services/notifications.py,sha256=9yy7Qkhe0-SjuxXDI8jxuee_a_f6S8s7uAB9BtcAa34,21426
278
279
  services/ollama_bridge.py,sha256=16ukWS98H4wFulOphUJDuXhN61GCiay793XLoyxTU-s,17455
279
- services/ollama_client.py,sha256=UiC5Abca622-ac-4goCkAjwo7iUye9g9JGFMN6Ea08M,7983
280
+ services/ollama_client.py,sha256=liTolLq23KEupT-qMRhpQlU4cA1oBD9JI1fFawmXfhg,9079
280
281
  services/ollama_credentials.py,sha256=EQx0YljYRrRBJ2voALlVTv11UBjfw-A6N7k7EP7fUFE,2770
281
282
  services/oracle_service.py,sha256=BH_3YtyYJKNsFtoi8MQMLo8s70dE8CGE4KfT811q8io,5973
282
283
  services/output_filter.py,sha256=lknQHs38JlRtXU4Ogoru6sveNokSKBQPfZXhf-fE0xM,21736
@@ -286,7 +287,7 @@ services/override_policy.py,sha256=TehVPxfQ8LZWIOUzCnnioIdMUPZZ7JZa1ja77smpW2c,3
286
287
  services/override_requests.py,sha256=vVWR6CQQSU04DkxHLljaNSr6k8f33O8Ysq4J4S2E4-Q,31504
287
288
  services/override_wake.py,sha256=HjSOXQTDi0irgeMyrTqngL7xLcSOOIgYsVW9yxod4ps,10363
288
289
  services/parser.py,sha256=S_YoKLS3r1xCUVHApXb3BTEfoRAzFhuo1_8XsG0qxVE,63505
289
- services/project_manager.py,sha256=dfA8jUjaEBQfX6JMVBy3iwXygb2gtPaI0sv_6QxLRFY,48983
290
+ services/project_manager.py,sha256=VxbEsTauIgH4DE3CjxSFArqiCCq9QsKxrOuTOdYTxLY,48991
290
291
  services/project_runtime.py,sha256=yyftX48BFjq4B2KcR4KGszDAAa4xR6gn6j0SgTyro1s,11603
291
292
  services/protocol.py,sha256=CWZ0BWWd-jPui-11hZlvGgkNk18gMFhhLWbp-BP35Kk,12861
292
293
  services/proxy_state.py,sha256=u5rd0k6CrOsywZA8FpRu_hMLwhR0TAJhZjy5MdWbCGc,6107
@@ -294,7 +295,7 @@ services/read_stamps.py,sha256=CTAy350FJ079-mDBXFZXU5OXhUdPobGnYelkC28W65Q,10654
294
295
  services/repo_map.py,sha256=o-Z3c7ZqIxRKPyqquGafTngdooe1n-yRIcqpmOz5i2M,23208
295
296
  services/repo_shape.py,sha256=QF0mXkY-bnBU8Q8mc5iimw2YBhMgZ4IYhoPc09Z8OBQ,4978
296
297
  services/reranker.py,sha256=pnyNSzM7gXQ3ZodjY3rGIRCwpD2OIjookYkAJXb_LVE,4694
297
- services/retention.py,sha256=I2_RV233kWBBXox5rc_w-1h1aPua93o9huuPf-pJVuE,18629
298
+ services/retention.py,sha256=Dw51RKc7Fv0uYbe7GMXj5ReNXtR5MDqpgk00MF_wezc,20569
298
299
  services/retrieval.py,sha256=ADESdXRWA66n2-6iLVdGZHIyseqQwcfpnX172iow0n8,2143
299
300
  services/retrieval_broker.py,sha256=9X67VZ_6AkbAzopHuuMFKmP4CGZLnW576kjSKMenBnw,5261
300
301
  services/router.py,sha256=Cz10nx2fKTbaGn14mSBePWIDrw5rdcs_1JFYXeik084,15626
@@ -350,8 +351,8 @@ tui/screens/search_view.py,sha256=MMHjVdlk3HZSuDBSvq8IGrqv_Mh5Us6YqXQ80bcWSMk,19
350
351
  tui/screens/session_view.py,sha256=eZ1eDwHTvPOck1wCCviixtOaCxIkBT_95ytNNNriGNA,5991
351
352
  tui/screens/stats.py,sha256=p81PjzdaIv7hllb8f45-rlVe4lJZwSdIMqu7e86_u5s,6223
352
353
  tui/screens/ui_view.py,sha256=1QJCgLh2YfgWIpvzRG1KOGXYEaOYX6ojN61Azjf2oX0,2125
353
- code_context_control-2.158.3.dist-info/METADATA,sha256=mbeDL5dANAqMjLr2gHjYl42TNJsnpeN722R9-CjJOeE,29355
354
- code_context_control-2.158.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
355
- code_context_control-2.158.3.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
356
- code_context_control-2.158.3.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
357
- code_context_control-2.158.3.dist-info/RECORD,,
354
+ code_context_control-2.158.5.dist-info/METADATA,sha256=ZUMWxBpNfAWcat8V8LehZxH6XJniKT7_3W90AZD8WW0,29355
355
+ code_context_control-2.158.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
356
+ code_context_control-2.158.5.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
357
+ code_context_control-2.158.5.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
358
+ code_context_control-2.158.5.dist-info/RECORD,,
core/mcp_stack.py ADDED
@@ -0,0 +1,114 @@
1
+ """Whether the installed fastmcp and mcp packages can load together.
2
+
3
+ fastmcp 3.x needs ``mcp<2`` and 4.x needs ``mcp>=2``, and pip installing some
4
+ other tool can move mcp out from under fastmcp anyway. Reads installed
5
+ metadata without importing either package, so the MCP server and the
6
+ SessionStart hook can name the mismatch and the pip command that repairs it.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from importlib import metadata
12
+ from pathlib import Path
13
+
14
+ # fastmcp-slim declares mcp under these extras; fastmcp 3.2 and earlier
15
+ # declare it unconditionally ("").
16
+ _EXTRAS = ("", "client", "server", "mcp")
17
+
18
+
19
+ def _packaging():
20
+ """packaging's (Requirement, InvalidRequirement, canonicalize_name), or None."""
21
+ try:
22
+ from packaging.requirements import InvalidRequirement, Requirement
23
+ from packaging.utils import canonicalize_name
24
+ except ImportError:
25
+ try:
26
+ from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
27
+ from pip._vendor.packaging.utils import canonicalize_name
28
+ except ImportError:
29
+ return None
30
+ return Requirement, InvalidRequirement, canonicalize_name
31
+
32
+
33
+ def _version(dist: str) -> str | None:
34
+ try:
35
+ return metadata.version(dist)
36
+ except metadata.PackageNotFoundError:
37
+ return None
38
+
39
+
40
+ def _mcp_requirement(requirement_cls, invalid_requirement, canonicalize_name):
41
+ """The mcp Requirement the installed fastmcp declares, or None."""
42
+ fastmcp = _version("fastmcp")
43
+ if fastmcp is None:
44
+ return None
45
+ # From 3.3 the fastmcp wheel only depends on fastmcp-slim, which carries
46
+ # the mcp pin. A slim left behind at another version is not the code in
47
+ # use, so read it only when the two versions match.
48
+ dists = ["fastmcp"]
49
+ if _version("fastmcp-slim") == fastmcp:
50
+ dists.insert(0, "fastmcp-slim")
51
+ for dist in dists:
52
+ for raw in metadata.requires(dist) or []:
53
+ try:
54
+ req = requirement_cls(raw)
55
+ except invalid_requirement:
56
+ continue
57
+ if canonicalize_name(req.name) != "mcp":
58
+ continue
59
+ if req.marker is None or any(
60
+ req.marker.evaluate({"extra": e}) for e in _EXTRAS):
61
+ return req
62
+ return None
63
+
64
+
65
+ def _console_python(executable: str) -> str:
66
+ """python.exe in place of pythonw.exe: the repair command needs a console."""
67
+ exe = Path(executable)
68
+ if exe.name.lower() == "pythonw.exe":
69
+ console = exe.with_name("python.exe")
70
+ if console.exists():
71
+ return str(console)
72
+ return executable
73
+
74
+
75
+ def problem(executable: str | None = None) -> str | None:
76
+ """Describe a fastmcp/mcp mismatch and how to repair it, or return None.
77
+
78
+ None also covers what this cannot judge: fastmcp not installed, no mcp pin
79
+ in its metadata, or no ``packaging`` to read the pin with.
80
+ """
81
+ tools = _packaging()
82
+ if tools is None:
83
+ return None
84
+ req = _mcp_requirement(*tools)
85
+ if req is None:
86
+ return None
87
+ fastmcp = _version("fastmcp")
88
+ mcp = _version("mcp")
89
+ spec = str(req.specifier)
90
+ python = _console_python(executable or sys.executable)
91
+ pip = f'"{python}" -m pip'
92
+ if mcp is None:
93
+ return (f"C3's MCP server cannot start: fastmcp {fastmcp} needs "
94
+ f"mcp{spec}, and mcp is not installed in {sys.prefix}.\n"
95
+ f'Repair: {pip} install "mcp{spec}", then restart the session.')
96
+ if req.specifier.contains(mcp, prereleases=True):
97
+ return None
98
+ too_new = any(s.operator in ("<", "<=") and not s.contains(mcp, prereleases=True)
99
+ for s in req.specifier)
100
+ lines = [
101
+ f"C3's MCP server cannot start: fastmcp {fastmcp} needs mcp{spec}, "
102
+ f"but mcp {mcp} is installed in {sys.prefix}. Installing another "
103
+ "package that wants a different mcp moves it; pip warns about the "
104
+ "conflict but installs anyway.",
105
+ "Repair with one of:",
106
+ ]
107
+ if too_new:
108
+ lines.append(f" {pip} install --upgrade fastmcp "
109
+ f"(moves fastmcp to the release built for mcp {mcp})")
110
+ lines.append(f' {pip} install "mcp{spec}" '
111
+ f"(moves mcp back to what fastmcp {fastmcp} needs)")
112
+ lines.append(f"Then run {pip} check to see whether another package "
113
+ "needs the other mcp line, and restart the session.")
114
+ return "\n".join(lines)
@@ -474,12 +474,28 @@ def _caller() -> str:
474
474
 
475
475
  # ── Path validation ───────────────────────────────────────
476
476
 
477
- def _resolve_registered(raw: str) -> Path | None:
477
+ def _registered_roots() -> list[Path]:
478
+ """Resolved path of every scanner-registered project with a .c3 dir."""
479
+ if _scanner is None:
480
+ return []
481
+ roots = []
482
+ for proj in _scanner.discover():
483
+ if not proj.get("has_c3"):
484
+ continue
485
+ try:
486
+ roots.append(Path(proj["path"]).resolve())
487
+ except (OSError, ValueError):
488
+ continue
489
+ return roots
490
+
491
+
492
+ def _resolve_registered(raw: str, roots: list[Path] | None = None) -> Path | None:
478
493
  """Resolve a request path to a scanner-registered project with a .c3 dir.
479
494
 
480
495
  Case-insensitive on Windows (normcase both sides). Returns None for
481
496
  anything unregistered — callers turn that into a 404 without ever
482
- touching the filesystem at the requested location.
497
+ touching the filesystem at the requested location. ``roots`` is a
498
+ ``_registered_roots()`` result to reuse across calls.
483
499
  """
484
500
  raw = (raw or "").strip()
485
501
  if not raw or _scanner is None:
@@ -488,19 +504,13 @@ def _resolve_registered(raw: str) -> Path | None:
488
504
  target = os.path.normcase(str(Path(raw).resolve()))
489
505
  except (OSError, ValueError):
490
506
  return None
491
- for proj in _scanner.discover():
492
- if not proj.get("has_c3"):
493
- continue
494
- try:
495
- candidate = os.path.normcase(str(Path(proj["path"]).resolve()))
496
- except (OSError, ValueError):
497
- continue
498
- if candidate == target:
499
- return Path(proj["path"]).resolve()
507
+ for root in (_registered_roots() if roots is None else roots):
508
+ if os.path.normcase(str(root)) == target:
509
+ return root
500
510
  return None
501
511
 
502
512
 
503
- def _serving_project(raw: str) -> Path | None:
513
+ def _serving_project(raw: str, roots: list[Path] | None = None) -> Path | None:
504
514
  """The registered project that serves an override row's ``project_path``:
505
515
  that project itself, or the deepest registered project containing it.
506
516
 
@@ -518,13 +528,7 @@ def _serving_project(raw: str) -> Path | None:
518
528
  return None
519
529
  best: Path | None = None
520
530
  best_len = -1
521
- for proj in _scanner.discover():
522
- if not proj.get("has_c3"):
523
- continue
524
- try:
525
- candidate = Path(proj["path"]).resolve()
526
- except (OSError, ValueError):
527
- continue
531
+ for candidate in (_registered_roots() if roots is None else roots):
528
532
  key = os.path.normcase(str(candidate))
529
533
  inside = target == key or target.startswith(key.rstrip("\\/") + os.sep)
530
534
  if inside and len(key) > best_len:
@@ -1022,8 +1026,7 @@ def mobile_jobs():
1022
1026
  # Cross-project listing must not leak rows for projects this gateway
1023
1027
  # does not serve (the store root is shared across every project on
1024
1028
  # the machine).
1025
- rows = [r for r in rows
1026
- if _resolve_registered(str(r.get("project_path") or "")) is not None]
1029
+ rows = _registered_rows(rows)
1027
1030
  if status:
1028
1031
  rows = [r for r in rows if r.get("status") == status]
1029
1032
  rows = rows[:limit]
@@ -1055,8 +1058,21 @@ def _schedule_row_or_404(schedule_id: str):
1055
1058
  return row, None
1056
1059
 
1057
1060
 
1058
- def _registered_rows(rows: list) -> list:
1059
- return [r for r in rows if _resolve_registered(str(r.get("project_path") or "")) is not None]
1061
+ def _registered_rows(rows: list, serving: bool = False) -> list:
1062
+ """The rows whose ``project_path`` is a registered project, or, with
1063
+ ``serving``, lies inside one. Resolves the registered projects once and
1064
+ each distinct row path once, not once per row and project."""
1065
+ roots = _registered_roots()
1066
+ lookup = _serving_project if serving else _resolve_registered
1067
+ keep: dict[str, bool] = {}
1068
+ out = []
1069
+ for r in rows:
1070
+ raw = str(r.get("project_path") or "")
1071
+ if raw not in keep:
1072
+ keep[raw] = lookup(raw, roots) is not None
1073
+ if keep[raw]:
1074
+ out.append(r)
1075
+ return out
1060
1076
 
1061
1077
 
1062
1078
  def _schedule_call(fn, *args, **kwargs):
@@ -2484,8 +2500,7 @@ def mobile_overrides_list():
2484
2500
  # Cross-project listing must not leak rows for projects this gateway
2485
2501
  # does not serve — the store is one file across every project on the
2486
2502
  # machine, including ones the scanner has since dropped.
2487
- rows = [r for r in rows
2488
- if _serving_project(str(r.get("project_path") or "")) is not None]
2503
+ rows = _registered_rows(rows, serving=True)
2489
2504
  channels = _override_channels(rows)
2490
2505
  cards = []
2491
2506
  for r in rows:
@@ -2770,8 +2785,7 @@ def mobile_overrides_costs():
2770
2785
  # Same rule as /overrides and /jobs: the store is one file for the
2771
2786
  # whole machine, and a cross-project view must not name a project
2772
2787
  # this token cannot otherwise see.
2773
- rules = [r for r in rules
2774
- if _serving_project(str(r.get("project_path") or "")) is not None]
2788
+ rules = _registered_rows(rules, serving=True)
2775
2789
  return jsonify({"days": days, "rules": rules, "count": len(rules),
2776
2790
  "project": project_path})
2777
2791
 
@@ -563,11 +563,10 @@ def mobile_now():
563
563
  jobs: list[dict] = []
564
564
  try:
565
565
  from services.shell_jobs import JobStore
566
- jobs = [r for r in JobStore().list_all(project_path=None,
567
- limit=m._SOURCE_CAP)
568
- if r.get("status") in ("queued", "running")
569
- and m._resolve_registered(str(r.get("project_path") or ""))
570
- is not None]
566
+ jobs = m._registered_rows(
567
+ [r for r in JobStore().list_all(project_path=None,
568
+ limit=m._SOURCE_CAP)
569
+ if r.get("status") in ("queued", "running")])
571
570
  except Exception:
572
571
  jobs = []
573
572
  body = fleet_overview.now(_registered(), job_rows=jobs)
services/file_memory.py CHANGED
@@ -405,11 +405,18 @@ class FileMemoryStore:
405
405
  Lists the store directory on every call but reads only records whose
406
406
  filename it has not seen before; removed records drop out.
407
407
  """
408
+ return list(self._tracked().values())
409
+
410
+ def _tracked(self) -> dict[str, str]:
411
+ """Record filename -> stored path for every readable record (a copy).
412
+
413
+ The refresh behind list_tracked(); {} when the store cannot be listed.
414
+ """
408
415
  try:
409
416
  names = {e.name for e in os.scandir(self.store_dir)
410
417
  if e.name.endswith(".json") and not e.name.startswith("_")}
411
418
  except OSError:
412
- return []
419
+ return {}
413
420
  with self._tracked_lock:
414
421
  known = self._tracked_paths
415
422
  for gone in known.keys() - names:
@@ -422,7 +429,7 @@ class FileMemoryStore:
422
429
  continue
423
430
  if path:
424
431
  known[name] = path
425
- return list(known.values())
432
+ return dict(known)
426
433
 
427
434
  def prune_stale(self) -> list[str]:
428
435
  """Remove records whose source file no longer exists on disk.
@@ -432,31 +439,39 @@ class FileMemoryStore:
432
439
  by the retention sweep. Records that fail to parse are left alone
433
440
  (unreadable is not the same as stale). Returns the pruned relative
434
441
  paths. Never raises.
442
+
443
+ Paths come from the list_tracked() cache, and existence is checked
444
+ with one listing per parent directory instead of a stat per record.
445
+ A name missing from its listing is confirmed with exists() before its
446
+ record is deleted, so a case-insensitive filesystem or an odd path
447
+ costs a stat, never a record.
435
448
  """
436
449
  pruned: list[str] = []
437
450
  try:
438
- for store_file in list(self.store_dir.glob("*.json")):
439
- if store_file.name.startswith("_"):
440
- continue
441
- try:
442
- with open(store_file, encoding="utf-8") as fh:
443
- data = json.load(fh)
444
- except Exception:
445
- continue
446
- rel = data.get("path", "")
447
- if not rel:
448
- continue
449
- try:
450
- if (self.project_path / rel).exists():
451
- continue
452
- except OSError:
453
- continue
451
+ by_dir: dict[str, list[tuple[str, str, str]]] = {}
452
+ for name, rel in self._tracked().items():
453
+ parent, _, base = rel.replace("\\", "/").rpartition("/")
454
+ by_dir.setdefault(parent, []).append((name, rel, base))
455
+ for parent, entries in by_dir.items():
454
456
  try:
455
- store_file.unlink()
457
+ with os.scandir(self.project_path / parent) as it:
458
+ present = {e.name for e in it}
456
459
  except OSError:
457
- continue
458
- pruned.append(rel)
459
- self._map_cache.pop(rel.replace("\\", "/"), None)
460
+ present = set()
461
+ for name, rel, base in entries:
462
+ if base in present:
463
+ continue
464
+ try:
465
+ if (self.project_path / rel).exists():
466
+ continue
467
+ except OSError:
468
+ continue
469
+ try:
470
+ (self.store_dir / name).unlink()
471
+ except OSError:
472
+ continue
473
+ pruned.append(rel)
474
+ self._map_cache.pop(rel.replace("\\", "/"), None)
460
475
  except Exception:
461
476
  return pruned
462
477
  if pruned:
services/ollama_client.py CHANGED
@@ -7,6 +7,8 @@ Includes integrated LLM response cache (formerly llm_cache.py).
7
7
  """
8
8
  import hashlib
9
9
  import json
10
+ import threading
11
+ import time
10
12
  import urllib.error
11
13
  import urllib.request
12
14
  from pathlib import Path
@@ -56,46 +58,76 @@ class LLMCache:
56
58
  pass
57
59
 
58
60
 
61
+ # Answers from /api/tags, shared by every OllamaClient in the process:
62
+ # base_url -> {"avail": (monotonic ts, bool), "models": (ts, list | None)}.
63
+ # Callers build clients per request and per agent, so a per-instance cache let
64
+ # each of them probe the server again.
65
+ _PROBE_TTL_SECONDS = 30.0
66
+ _probe_cache: dict[str, dict[str, tuple[float, object]]] = {}
67
+ _probe_lock = threading.Lock()
68
+
69
+
70
+ def clear_probe_cache() -> None:
71
+ """Forget every cached availability and model-list answer."""
72
+ with _probe_lock:
73
+ _probe_cache.clear()
74
+
75
+
59
76
  class OllamaClient:
60
77
  """Minimal Ollama REST client using urllib."""
61
78
 
62
- _AVAIL_TTL_SECONDS = 10.0
63
-
64
79
  def __init__(self, base_url: str = DEFAULT_BASE_URL, cache_dir: str = ".c3/cache/llm"):
65
80
  self.base_url = base_url.rstrip("/")
66
81
  self.cache = LLMCache(cache_dir)
67
- self._avail_value: bool | None = None
68
- self._avail_ts: float = 0.0
82
+
83
+ def _cached(self, key: str):
84
+ with _probe_lock:
85
+ hit = _probe_cache.get(self.base_url, {}).get(key)
86
+ if hit is not None and time.monotonic() - hit[0] < _PROBE_TTL_SECONDS:
87
+ return hit
88
+ return None
89
+
90
+ def _remember(self, key: str, value) -> None:
91
+ with _probe_lock:
92
+ _probe_cache.setdefault(self.base_url, {})[key] = (time.monotonic(), value)
69
93
 
70
94
  # ── Availability ──────────────────────────────────────
71
95
 
72
96
  def is_available(self, timeout: int | None = None) -> bool:
73
- """Check if Ollama is reachable. Cached for ``_AVAIL_TTL_SECONDS`` to
74
- avoid storm when many background agents poll concurrently."""
75
- import time
76
- now = time.monotonic()
77
- if self._avail_value is not None and (now - self._avail_ts) < self._AVAIL_TTL_SECONDS:
78
- return self._avail_value
97
+ """Check if Ollama is reachable. The answer is shared process-wide for
98
+ ``_PROBE_TTL_SECONDS``."""
99
+ hit = self._cached("avail")
100
+ if hit is not None:
101
+ return hit[1]
79
102
  try:
80
103
  req = urllib.request.Request(f"{self.base_url}/api/tags")
81
104
  with urllib.request.urlopen(req, timeout=timeout or _TIMEOUT):
82
- self._avail_value = True
105
+ available = True
83
106
  except Exception:
84
- self._avail_value = False
85
- self._avail_ts = now
86
- return self._avail_value
107
+ available = False
108
+ self._remember("avail", available)
109
+ return available
87
110
 
88
111
  # ── Models ────────────────────────────────────────────
89
112
 
90
113
  def list_models(self) -> list[str] | None:
91
- """Return list of locally available model names, or None on failure."""
114
+ """Return list of locally available model names, or None on failure.
115
+ The answer is shared process-wide for ``_PROBE_TTL_SECONDS``."""
116
+ hit = self._cached("models")
117
+ if hit is not None:
118
+ return list(hit[1]) if hit[1] is not None else None
92
119
  try:
93
120
  req = urllib.request.Request(f"{self.base_url}/api/tags")
94
121
  with urllib.request.urlopen(req, timeout=_TIMEOUT) as resp:
95
122
  data = json.loads(resp.read())
96
- return [m["name"] for m in data.get("models", [])]
123
+ models = [m["name"] for m in data.get("models", [])]
97
124
  except Exception:
98
- return None
125
+ models = None
126
+ self._remember("models", models)
127
+ if models is not None:
128
+ self._remember("avail", True)
129
+ return list(models)
130
+ return None
99
131
 
100
132
  def has_model(self, model: str) -> bool:
101
133
  """Check if a specific model is pulled locally."""
@@ -101,7 +101,7 @@ class ProjectManager:
101
101
  def _verify_c3_session(self, port: int) -> bool:
102
102
  """Verify that a given port is actually a C3 session UI."""
103
103
  try:
104
- url = f"http://127.0.0.1:{port}/api/health"
104
+ url = f"http://127.0.0.1:{port}/api/health?probe=1"
105
105
  # 2 s, not 0.8: a server re-indexing after a burst of file changes
106
106
  # answers late, and a late answer must not read as "not C3".
107
107
  with urllib.request.urlopen(url, timeout=2.0) as r:
services/retention.py CHANGED
@@ -329,6 +329,46 @@ def cap_session_files(sessions_dir, max_files: int = 50,
329
329
  return pruned
330
330
 
331
331
 
332
+ def _try_lock(path: Path):
333
+ """Take a non-blocking exclusive lock on ``path``; the open handle, or None.
334
+
335
+ The OS drops the lock when the holder dies, so a crashed sweep never
336
+ strands it.
337
+ """
338
+ try:
339
+ path.parent.mkdir(parents=True, exist_ok=True)
340
+ fh = open(path, "ab")
341
+ except OSError:
342
+ return None
343
+ try:
344
+ if os.name == "nt":
345
+ import msvcrt
346
+ fh.seek(0)
347
+ msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
348
+ else:
349
+ import fcntl
350
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
351
+ except OSError:
352
+ fh.close()
353
+ return None
354
+ return fh
355
+
356
+
357
+ def _unlock(fh) -> None:
358
+ try:
359
+ if os.name == "nt":
360
+ import msvcrt
361
+ fh.seek(0)
362
+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
363
+ else:
364
+ import fcntl
365
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
366
+ except OSError:
367
+ pass
368
+ finally:
369
+ fh.close()
370
+
371
+
332
372
  class RetentionManager:
333
373
  """Rate-limited retention sweep for a project's ``.c3`` directory.
334
374
 
@@ -341,6 +381,11 @@ class RetentionManager:
341
381
  happens at write time in their own modules; this sweep owns the
342
382
  structure-aware rotations (edit ledger, notifications), the session
343
383
  cap, file-memory pruning, and archive TTL purging.
384
+
385
+ Every C3 process on a project (each MCP server and the UI server) owns
386
+ one of these, so ``maybe_run`` sweeps only when no process has swept
387
+ within the interval: ``.c3/retention.lock`` keeps two sweeps from
388
+ overlapping and the mtime of ``.c3/retention.last`` records the last one.
344
389
  """
345
390
 
346
391
  def __init__(self, project_path, edit_ledger=None, notifications=None,
@@ -367,7 +412,27 @@ class RetentionManager:
367
412
  self._next_run = now + interval
368
413
  if not cfg.get("enabled", True):
369
414
  return None
370
- return self.run_sweep(cfg)
415
+ c3_dir = self.project_path / ".c3"
416
+ lock = _try_lock(c3_dir / "retention.lock")
417
+ if lock is None:
418
+ return None
419
+ try:
420
+ stamp = c3_dir / "retention.last"
421
+ try:
422
+ age = time.time() - stamp.stat().st_mtime
423
+ except OSError:
424
+ age = None
425
+ if age is not None and 0 <= age < interval:
426
+ self._next_run = now + (interval - age)
427
+ return None
428
+ summary = self.run_sweep(cfg)
429
+ try:
430
+ stamp.touch()
431
+ except OSError:
432
+ pass
433
+ return summary
434
+ finally:
435
+ _unlock(lock)
371
436
 
372
437
  def run_sweep(self, cfg: Optional[dict] = None) -> dict:
373
438
  """Execute one full retention sweep. Never raises."""