code-context-control 2.159.1__py3-none-any.whl → 2.159.2__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
@@ -96,7 +96,7 @@ console = Console() if HAS_RICH else None
96
96
  # Config
97
97
  CONFIG_DIR = ".c3"
98
98
  CONFIG_FILE = ".c3/config.json"
99
- __version__ = "2.159.1"
99
+ __version__ = "2.159.2"
100
100
 
101
101
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
102
102
  AGENT_MATCHER = "Agent|Task"
cli/mcp_server.py CHANGED
@@ -354,26 +354,33 @@ async def lifespan(server):
354
354
 
355
355
  threading.Thread(target=_bg_build, daemon=True, name="c3-initial-index").start()
356
356
  else:
357
- services.indexer._load_index()
358
- # Build/update embedding index + warm SLTM in background. Deferred off
359
- # the handshake path: build()/warm() lazily init the heavy backends, so
360
- # this must NOT gate on .ready synchronously here.
361
- if services.embedding_index or services.vector_store:
362
- import threading
357
+ # Bound here too: the `import threading` lines in this function make
358
+ # the name local, so the module import is not visible.
359
+ import threading
363
360
 
364
- def _bg_embed():
365
- if services.embedding_index:
366
- try:
367
- services.embedding_index.build(services.indexer)
368
- except Exception:
369
- pass
370
- if services.vector_store:
371
- try:
372
- services.vector_store.warm()
373
- except Exception:
374
- pass
361
+ services.indexer._load_index()
362
+ # In the background: re-check the stored index against the files (a
363
+ # git pull while no server ran leaves it stale), then build/update the
364
+ # embedding index and warm SLTM. Deferred off the handshake path:
365
+ # build()/warm() lazily init the heavy backends, so this must NOT gate
366
+ # on .ready synchronously here.
367
+ def _bg_embed():
368
+ try:
369
+ services.indexer.refresh_stale()
370
+ except Exception:
371
+ pass
372
+ if services.embedding_index:
373
+ try:
374
+ services.embedding_index.build(services.indexer)
375
+ except Exception:
376
+ pass
377
+ if services.vector_store:
378
+ try:
379
+ services.vector_store.warm()
380
+ except Exception:
381
+ pass
375
382
 
376
- threading.Thread(target=_bg_embed, daemon=True, name="c3-embed-index").start()
383
+ threading.Thread(target=_bg_embed, daemon=True, name="c3-embed-index").start()
377
384
 
378
385
  # Build/update doc index in background for Local RAG Pipeline
379
386
  if services.doc_index:
cli/server.py CHANGED
@@ -4535,6 +4535,15 @@ def run_server(
4535
4535
  print("Building index for the first time...")
4536
4536
  result = indexer.build_index()
4537
4537
  print(f" Indexed {result['files_indexed']} files, {result['chunks_created']} chunks")
4538
+ else:
4539
+ # A git pull while no server ran leaves the stored index stale.
4540
+ def _bg_refresh():
4541
+ try:
4542
+ indexer.refresh_stale()
4543
+ except Exception:
4544
+ pass
4545
+
4546
+ threading.Thread(target=_bg_refresh, daemon=True, name="c3-index-refresh").start()
4538
4547
 
4539
4548
  port = find_free_port(port)
4540
4549
  start_path = "/nano" if nano else ""
cli/tools/search.py CHANGED
@@ -51,6 +51,13 @@ _KIND_RANK = {"source": 0, "config": 1, "doc": 2, "test": 3}
51
51
  # separators.
52
52
  _PATHLIKE_RE = re.compile(r"/|^[\w.\-]+\.[A-Za-z0-9]{1,6}$")
53
53
  _REGEX_META = set("\\^$.|?*+()[]{}")
54
+ # `exact` walked the tree on every call (150 ms of 670 ms on this repo). The
55
+ # walk is reused while the project's watcher runs and nothing changed: the
56
+ # watcher bumps structure_generation on every create, delete or move, and
57
+ # the rules, the root .gitignore and the walk settings are compared too. The
58
+ # TTL bounds what a missed file-system event could cost.
59
+ _MANIFEST_TTL_S = 30.0
60
+ _manifest_cache: dict = {} # project -> (generation, state, monotonic stamp, rels)
54
61
 
55
62
 
56
63
  def _read_denied(path, svc) -> bool:
@@ -230,6 +237,20 @@ def _search_manifest(svc) -> list:
230
237
  if isinstance(prefixes, list) and prefixes and callable(is_excluded):
231
238
  def exclude_parts(parts, _c=is_excluded, _p=prefixes):
232
239
  return _c(parts, _p)
240
+ else:
241
+ prefixes = None
242
+
243
+ # Read before the walk: an event landing during it moves the generation
244
+ # on, so the next call walks again.
245
+ generation = _watcher_generation(svc)
246
+ state = _manifest_state(project, exts, prefixes) if generation is not None else None
247
+ key = str(project)
248
+ if state is not None:
249
+ hit = _manifest_cache.get(key)
250
+ if (hit is not None and hit[0] == generation and hit[1] == state
251
+ and time.monotonic() - hit[2] < _MANIFEST_TTL_S):
252
+ return list(hit[3])
253
+
233
254
  rels = []
234
255
  for fpath in iter_files(project, exts=exts, skip_dirs=set(SKIP_DIRS),
235
256
  exclude_parts=exclude_parts):
@@ -237,9 +258,45 @@ def _search_manifest(svc) -> list:
237
258
  rels.append(fpath.relative_to(project).as_posix())
238
259
  except ValueError:
239
260
  continue
261
+ if state is not None:
262
+ _manifest_cache[key] = (generation, state, time.monotonic(), tuple(rels))
240
263
  return rels
241
264
 
242
265
 
266
+ def _watcher_generation(svc):
267
+ """The running watcher's structure_generation, or None (then: no cache)."""
268
+ watcher = getattr(svc, "watcher", None)
269
+ try:
270
+ if getattr(watcher, "running", False) is not True:
271
+ return None
272
+ generation = watcher.structure_generation
273
+ except Exception:
274
+ return None
275
+ return generation if isinstance(generation, int) else None
276
+
277
+
278
+ def _manifest_state(project: Path, exts, prefixes):
279
+ """Everything besides the file tree that decides what the walk yields."""
280
+ try:
281
+ rules = access_guard.load_all(str(project))
282
+ except Exception:
283
+ return None
284
+ try:
285
+ st = (project / ".gitignore").stat()
286
+ gitignore = (st.st_mtime_ns, st.st_size)
287
+ except OSError:
288
+ gitignore = None
289
+ return (tuple(sorted(exts)), tuple(prefixes or ()), rules, gitignore)
290
+
291
+
292
+ def _deny_rules_only(svc) -> bool:
293
+ """True when Access Guard decides reads by path and deny rules alone."""
294
+ try:
295
+ return bool(access_guard.deny_rules_decide_reads(svc.project_path))
296
+ except Exception:
297
+ return False
298
+
299
+
243
300
  def _guard_rules_active(svc) -> bool:
244
301
  """True when any user access rule (deny/read_only/mask) applies — or when
245
302
  that cannot be determined. Fails closed: ripgrep reads raw bytes, so it
@@ -326,19 +383,25 @@ def _exact_search(query, top_k, max_tokens, svc, finalize, ignore_case: bool = F
326
383
  allowed = set(candidates)
327
384
  targets = [rel for rel in manifest if rel in allowed]
328
385
 
386
+ # With no mask, corrupt scope or read-pausing confirm rule, the walk's
387
+ # deny filtering is the whole read verdict, so the scan reads each file
388
+ # directly instead of evaluating it again (2.159.2).
389
+ direct = _deny_rules_only(svc)
390
+
329
391
  def _scan_file(rel):
330
392
  """Scan one file for regex matches. Returns (rel, lines) or None."""
331
393
  full = project / rel
332
- if not full.exists():
333
- return None
334
394
  # Mask Guard: regex-scan the VIEW, never the raw bytes. An exact
335
395
  # search that matched real content and printed it verbatim would be a
336
396
  # complete bypass of the mask (docs/mask-guard.md §6).
337
397
  try:
338
- from services.indexer import _masked_content
339
- text = _masked_content(full, svc.project_path)
340
- if text is None:
341
- return None
398
+ if direct:
399
+ text = full.read_text(encoding="utf-8", errors="replace")
400
+ else:
401
+ from services.indexer import _masked_content
402
+ text = _masked_content(full, svc.project_path)
403
+ if text is None:
404
+ return None
342
405
  lines = text.splitlines()
343
406
  except Exception:
344
407
  return None
@@ -454,6 +517,12 @@ def _rank_filenames(query: str, docs: dict) -> list:
454
517
 
455
518
  def _indexed_documents(svc):
456
519
  indexer = getattr(svc, "indexer", None)
520
+ sync = getattr(indexer, "sync_pending", None)
521
+ if callable(sync):
522
+ try:
523
+ sync() # files the watcher saw appear or go since the last search
524
+ except Exception:
525
+ pass
457
526
  docs = getattr(indexer, "documents", None)
458
527
  if isinstance(docs, dict) and not docs:
459
528
  loader = getattr(indexer, "_load_index", None)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-context-control
3
- Version: 2.159.1
3
+ Version: 2.159.2
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=tzpdF413jakQKMbTru_GdHxQXxLLQKiZzVkTm4Fo_eU,23258
3
3
  cli/_shell_writes.py,sha256=iBbzK0v0d29rhrYgF3zKJIJbb1WSZhQjD_6w8-nOUec,7348
4
- cli/c3.py,sha256=ehUpVJac8-Kdwng2kL40jaUSxb7NUIEs_k38M7AUxj8,439506
4
+ cli/c3.py,sha256=INiXT7TcVT_nomOGTjiTRM6KPyk2IBduf_MGRlvvGxQ,439506
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
@@ -26,9 +26,9 @@ cli/hook_terse_advisor.py,sha256=W_zaTfX2akgX-ifuUTsLu2H1atM8XmWt6jpPoeU7Pm0,625
26
26
  cli/hub_server.py,sha256=8tBGc6q1xF9Ujo6sY0AJ95MjfbZNFpjpIaiySL96B68,226916
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=72wdZbf0ea0qy2h8O8CKaCbzneFPhQAIwGlEgzCcEUw,84589
29
+ cli/mcp_server.py,sha256=DisVVExGIbeEABxtDPzdaGJpu7P1okA4l_dzu-VFD3E,84862
30
30
  cli/progress.py,sha256=qTkNy0howOD3hXraMo4ok3dYTpBW5yG_tenKfF4UDM0,1470
31
- cli/server.py,sha256=kK9ZNwPaYmohexrLSYuhncbB_cNN7jWKpFXKewddpPs,174314
31
+ cli/server.py,sha256=zadPID9SZVzb84Tlf_KxmJvfvkPcfssrt8Lyow5bKME,174623
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
@@ -105,7 +105,7 @@ cli/tools/override.py,sha256=LiZFgoDN-35NXVwldnYrcCzfBl8MhQQ3tKVVkOG5d_o,9217
105
105
  cli/tools/project.py,sha256=CWnrE-tJuNm8koiGNmzUNFAfrIUlhr7Joz6W64YVea4,24843
106
106
  cli/tools/read.py,sha256=9W-FhALienlmWeLQnsUA9tvbTgh9IGJzbSYyoT9Wd7I,21439
107
107
  cli/tools/schedule.py,sha256=lOLEAMy7ANuxIm9GsA3GNVaKG1KnXOtAMeCNCWrcJDg,11390
108
- cli/tools/search.py,sha256=BZh3E7YggjCWOC1lJz0YNcRsdDLWsJiEmONtgUW2rEo,32397
108
+ cli/tools/search.py,sha256=dDViIwZ7XH0b-fmZ5S1MU3236aB2nD6FTqT_u1MF-5s,35145
109
109
  cli/tools/session.py,sha256=IYNgcNz_saQDvilX6iB-SClLpfsGmz_grgMY5PFztPI,9371
110
110
  cli/tools/shell.py,sha256=Yx7_EkWAISIKFT1oFLBhsQuzMH2zy1lGCl9VQYJl1EI,61495
111
111
  cli/tools/shell_job.py,sha256=_ilFBL3ulmqx8mwQJFUG6xW5dN-4NHqe0EZfRJL2e-4,16451
@@ -135,8 +135,8 @@ 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.159.1.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
139
- core/__init__.py,sha256=TSDCEcM4V7gcZVM3w2ykJaqEUch4Dkon-rivV17T73s,2501
138
+ code_context_control-2.159.2.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
139
+ core/__init__.py,sha256=qiheEC2r3KCd3vscukDVkjCXFcadzGgNhDhs9PbLVPA,2835
140
140
  core/blas_threads.py,sha256=Do7pR9YdumshhOmP6TV5oAv65i3gN7Lvt93b5EAO1bo,1256
141
141
  core/codex_patch.py,sha256=CxvT_rQIwPNTRJZj9EHJmx0ZdOeSLxjiixuLI3Z7lPc,2107
142
142
  core/config.py,sha256=wCjrZKXRywUbR6WRcO7optyOirAQ2DeRNdPCU0X5zIY,23762
@@ -197,7 +197,7 @@ oracle/ui/chat/send.js,sha256=X_Uc6EuuIxkUTlRWGGYOq6gQkJCQeCE3p5NMyxx7RzQ,11911
197
197
  oracle/ui/chat/stream_renderer.js,sha256=RZndI2mu5xbzZF-4NG9jeOqXTcmIqfZqxgkrBvTzWmk,29861
198
198
  oracle/ui/chat/toolbar.js,sha256=ZDexIIpGwsQ6XsY4Tyo082rJoofdD_JBTV97-mLQUVM,12027
199
199
  services/__init__.py,sha256=3Kn4cZweLm7at8wFdBdZ-Zwo8hHcnVIsmY5f29nzi2Y,116
200
- services/access_guard.py,sha256=x1B6MLIgzUTKh9HvuiQb-7vDY50KrVUvoNdfhHTAt3w,86836
200
+ services/access_guard.py,sha256=CYRgths6F2cxkPHKPKgoK5z4R8RcSFTMOdlmRgdZQlA,87552
201
201
  services/access_telemetry.py,sha256=9pOCLS9LgDtM7Z4cCEyl7osxhj-m3wsPubcXolBKuV4,9568
202
202
  services/activity_log.py,sha256=pA1n4Ryjo_AMUFUplhToISM-HByK0bnkIfvP6dRD57U,8400
203
203
  services/agent_base.py,sha256=a-gdSd_jtZtbjXo1WS8CnWCagXgKaGZd5ShcG6s0kT4,4809
@@ -258,8 +258,8 @@ services/grok_transcript.py,sha256=E4im_OIUrU-jDfw3sum_gCuG6FiONgZdlYsIhS-zdlM,2
258
258
  services/host_handoff.py,sha256=zCPbPwSFGXuNUlGlHAWlmy7V7TizhduwS0upD3EYMsw,12103
259
259
  services/host_sessions.py,sha256=5R0DSU8z-CI6kKek4yLCwe1FShxZTOLe6dlYnH5-hoI,3722
260
260
  services/hub_service.py,sha256=z2MZ2Rg9NLNXxQ17e05XGF_f6qSTDWLYtoC3WpuQfGU,2634
261
- services/index_store.py,sha256=SWHHKQB_wYww1ubtKgkLo5FFEqaWhPbw0OAN8x3gk9Q,16453
262
- services/indexer.py,sha256=AByWHaLy-0c8nxZMJF08a11d-cd106I__2ZIucUDNMM,59946
261
+ services/index_store.py,sha256=78DSUxfz0qLdW8RVRJdOtCKPL9Bdp6wbtWWgfA4E46Q,16921
262
+ services/indexer.py,sha256=765nPLJWiCrcJgJ6pd0LAnVE7PyDn_nyM7WKRb0gVKI,67461
263
263
  services/jira_client.py,sha256=C7gpxr2r7uHQuU0SIgp9lCJpFtTzQqClsRO0eccn4iY,26276
264
264
  services/jira_cloud.py,sha256=M8Sd_eCSMbcEh52ilT7xb9v4XZAK32TfQxYQcWvflfQ,13272
265
265
  services/jira_credentials.py,sha256=QmODZa2ivZ1DwsxSpnmM1XhPxNBiTJCR1LrdCPh7Nuk,9124
@@ -302,7 +302,7 @@ services/retention.py,sha256=9EtXE4IRzM6eX6gN-QyWFQFQQviyplLuybMXzbtrIV0,21290
302
302
  services/retrieval.py,sha256=ADESdXRWA66n2-6iLVdGZHIyseqQwcfpnX172iow0n8,2143
303
303
  services/retrieval_broker.py,sha256=9X67VZ_6AkbAzopHuuMFKmP4CGZLnW576kjSKMenBnw,5261
304
304
  services/router.py,sha256=Cz10nx2fKTbaGn14mSBePWIDrw5rdcs_1JFYXeik084,15626
305
- services/runtime.py,sha256=931eux-zdsXh0M6i6RmXEGAKiXLfa9aDra9V12Q5Z_Y,13767
305
+ services/runtime.py,sha256=W7Og5gmLVEjm6IG3oT-l046-b6pmz5VUaZ1asZu4W-o,13898
306
306
  services/scanner.py,sha256=lH0aiDCdCRruKS-VTAD_LsF4zrhMLpMRhFlOZZlw4VM,9613
307
307
  services/schedule_approvals.py,sha256=tzf_YTnOoJf-DOx3m83m54EQnNBXE752nv4eE6N0PwU,8516
308
308
  services/schedule_runner.py,sha256=WkWrPhLa2j_Z06l7R9cJEE6zhlzn4aV58w619Ewarvk,11997
@@ -325,7 +325,7 @@ services/transcript_index.py,sha256=VQhvgkSyLVEYamXi_YIbiIhBnd0mqFHZlWG2HQu_1EA,
325
325
  services/ui_registry.py,sha256=K_wzK0x_-jvJFdl28HCBpKow3td_BKhg3vPuei8vU7E,9121
326
326
  services/validation_cache.py,sha256=tXDgqQCezBJel8n_mdXzzcx2zI1kEsVB2d_l9gst00M,5759
327
327
  services/vector_store.py,sha256=satc4MJanC1Wsu_iveMCUXG6K2fd0Ke87JSyy2BMikw,13041
328
- services/watcher.py,sha256=Irmk7QJurQon30SJFYtjijRBKtpcGB4Fwv1A1XiZxlo,10995
328
+ services/watcher.py,sha256=DXNKCkDIgHHT-kUh8MSBVWr5zNcjTXf9Ohx86B58Uuc,13194
329
329
  services/win_subprocess.py,sha256=nt8Uwc2PrqsRW3-jcViEsoKj56GudW8TV3CQwryx8y4,4271
330
330
  services/bench/__init__.py,sha256=WLEJIWJeaUj6FnH2nDO1qWugJDKfOKeM6WvKLSreYjI,231
331
331
  services/bench/delegate_eval.py,sha256=gi_cG8yYlYqBr_yOfyTibdeUJujYYFVyjcVqeIMXlUo,26072
@@ -354,8 +354,8 @@ tui/screens/search_view.py,sha256=MMHjVdlk3HZSuDBSvq8IGrqv_Mh5Us6YqXQ80bcWSMk,19
354
354
  tui/screens/session_view.py,sha256=eZ1eDwHTvPOck1wCCviixtOaCxIkBT_95ytNNNriGNA,5991
355
355
  tui/screens/stats.py,sha256=p81PjzdaIv7hllb8f45-rlVe4lJZwSdIMqu7e86_u5s,6223
356
356
  tui/screens/ui_view.py,sha256=1QJCgLh2YfgWIpvzRG1KOGXYEaOYX6ojN61Azjf2oX0,2125
357
- code_context_control-2.159.1.dist-info/METADATA,sha256=M71H8FLV6nj0tfAPI3OXbH07UZVlqUUgiPce_stCG-M,29355
358
- code_context_control-2.159.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
- code_context_control-2.159.1.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
- code_context_control-2.159.1.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
- code_context_control-2.159.1.dist-info/RECORD,,
357
+ code_context_control-2.159.2.dist-info/METADATA,sha256=2oY2_v39_If6YULwuQyI06tF0oZ1WQcEZYH8ITXYT3c,29355
358
+ code_context_control-2.159.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
+ code_context_control-2.159.2.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
+ code_context_control-2.159.2.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
+ code_context_control-2.159.2.dist-info/RECORD,,
core/__init__.py CHANGED
@@ -15,7 +15,7 @@ def _cached_count(content_hash: str, length: int, text: str) -> int:
15
15
  """Count tokens with LRU memoization. length param ensures hash collisions are safe."""
16
16
  encoder = _get_encoder()
17
17
  if encoder:
18
- return len(encoder.encode(text))
18
+ return len(encoder.encode(text, disallowed_special=()))
19
19
  tokens = re.findall(r'\w+|[^\w\s]', text)
20
20
  count = 0
21
21
  for t in tokens:
@@ -41,6 +41,11 @@ def count_tokens(text: str) -> int:
41
41
  Count tokens using tiktoken (cl100k_base) with LRU caching.
42
42
  Repeated calls with identical text hit the cache (~0ms vs ~1-2ms).
43
43
  Falls back to heuristic if tiktoken is unavailable.
44
+
45
+ Text that spells a special token (the end-of-text marker, say) counts
46
+ as ordinary text. tiktoken raises on it by default, and before 2.159.2
47
+ one file quoting it failed every index build and refresh of its
48
+ project, and any c3 tool call whose input or output contained it.
44
49
  """
45
50
  if not text:
46
51
  return 0
@@ -48,7 +53,7 @@ def count_tokens(text: str) -> int:
48
53
  if len(text) < 50:
49
54
  encoder = _get_encoder()
50
55
  if encoder:
51
- return len(encoder.encode(text))
56
+ return len(encoder.encode(text, disallowed_special=()))
52
57
  return len(re.findall(r'\w+|[^\w\s]', text))
53
58
  h = hashlib.md5(text.encode("utf-8", errors="replace")).hexdigest()
54
59
  return _cached_count(h, len(text), text)
services/access_guard.py CHANGED
@@ -1027,6 +1027,24 @@ def has_mask_rules(project_path: str = ".") -> bool:
1027
1027
  return bool(mask_rules or corrupt)
1028
1028
 
1029
1029
 
1030
+ def deny_rules_decide_reads(project_path: str = ".") -> bool:
1031
+ """True when a read verdict can only come from path checks and deny rules.
1032
+
1033
+ That is exactly what ``scanner.make_access_excluder`` applies during a
1034
+ walk, so a file the walk yielded may be read as-is without a per-file
1035
+ ``verdict``. False while any mask rule, corrupt scope or read-pausing
1036
+ confirm rule (``confirm_ops == "all"``) exists, or when the rules cannot
1037
+ be loaded.
1038
+ """
1039
+ try:
1040
+ rules, mask_rules, corrupt = load_all(project_path)
1041
+ except Exception:
1042
+ return False
1043
+ if mask_rules or corrupt:
1044
+ return False
1045
+ return not any(r.kind == _KIND_CONFIRM and r.confirm_ops == "all" for r in rules)
1046
+
1047
+
1030
1048
  def has_active_rules(project_path: str = ".") -> bool:
1031
1049
  """True when any user rules (or corrupt scopes) exist — drives S4."""
1032
1050
  # The baseline counts the install-dir rule only when it actually loaded:
services/index_store.py CHANGED
@@ -259,6 +259,18 @@ class IndexStore:
259
259
  conn.close()
260
260
  return rows
261
261
 
262
+ def set_mtimes(self, mtimes: dict) -> None:
263
+ """Record new mtimes for documents whose content did not change."""
264
+ if not mtimes or not self.path.exists():
265
+ return
266
+ conn = self._connect()
267
+ try:
268
+ with conn:
269
+ conn.executemany("UPDATE docs SET mtime = ? WHERE doc_id = ?",
270
+ [(float(m), doc_id) for doc_id, m in mtimes.items()])
271
+ finally:
272
+ conn.close()
273
+
262
274
  # ── read ────────────────────────────────────────────────────────────────
263
275
 
264
276
  def load(self) -> dict | None:
services/indexer.py CHANGED
@@ -10,6 +10,7 @@ import logging
10
10
  import math
11
11
  import os
12
12
  import re
13
+ import threading
13
14
  import time
14
15
  from collections import Counter, OrderedDict
15
16
  from pathlib import Path
@@ -149,6 +150,16 @@ class CodeIndex:
149
150
  self._store = IndexStore(self.index_dir)
150
151
  self._hashes: dict = {} # doc_id -> content hash; drives refresh()
151
152
  self._lexical_ok = False
153
+ # Writers (build_index, refresh) take turns on this lock. Searches do
154
+ # not take it: refresh builds its documents and chunks in copies and
155
+ # swaps them in, so a search sees the old index or the new one.
156
+ self._write_lock = threading.RLock()
157
+ # True during a full build or a refresh of many files: sync_pending
158
+ # then searches the index as it is instead of waiting.
159
+ self._long_write = False
160
+ # The runtime points this at CodeWatcher.take_index_changes, so a
161
+ # search first re-reads the files changed since the last one.
162
+ self.pending_changes = None
152
163
 
153
164
  # Hybrid fusion (services/retrieval, plan P3): a dense backend — any
154
165
  # object with `.ready` and `.candidates(query, limit)`, in practice the
@@ -248,10 +259,11 @@ class CodeIndex:
248
259
  n = self._rerank_top_n
249
260
  head = ranked[:n]
250
261
  exact_head = [(cid, s) for cid, s in head if cid in exact_ids]
251
- block = [(cid, s) for cid, s in head if cid not in exact_ids and cid in self.chunks]
262
+ chunks = self.chunks
263
+ block = [(cid, s) for cid, s in head if cid not in exact_ids and cid in chunks]
252
264
  if len(block) < 2:
253
265
  return ranked
254
- docs = [(cid, passage_text(self.chunks[cid])) for cid, _ in block]
266
+ docs = [(cid, passage_text(chunks[cid])) for cid, _ in block]
255
267
  try:
256
268
  scored = self.reranker.rerank(query, docs)
257
269
  except Exception as exc:
@@ -350,6 +362,15 @@ class CodeIndex:
350
362
  on_progress: callable(entries_seen, files_indexed, chunks_created),
351
363
  invoked during the scan (directory granularity plus per file).
352
364
  """
365
+ # Set before the lock is taken: sync_pending must not wait out a build.
366
+ prev, self._long_write = self._long_write, True
367
+ try:
368
+ with self._write_lock:
369
+ return self._build_index(max_files, on_progress)
370
+ finally:
371
+ self._long_write = prev
372
+
373
+ def _build_index(self, max_files, on_progress) -> dict:
353
374
  if max_files is None:
354
375
  max_files = self._configured_max_files()
355
376
 
@@ -444,22 +465,32 @@ class CodeIndex:
444
465
 
445
466
  # ── Shared build steps ─────────────────────────────────────────────────
446
467
 
447
- def _ingest_file(self, doc_id: str, fpath: Path, content: str) -> list:
448
- """Register one file: document entry, chunks, hash, mtime. Returns its chunks."""
449
- self.documents[doc_id] = {
468
+ def _ingest_file(self, doc_id: str, fpath: Path, content: str, mtime=None, maps=None) -> list:
469
+ """Register one file: document entry, chunks, hash, mtime. Returns its chunks.
470
+
471
+ ``maps`` is ``(documents, chunks, hashes, mtimes)`` to write into
472
+ instead of the live dicts; ``mtime`` is one the caller read before
473
+ the content, so a write landing in between is caught next time.
474
+ """
475
+ documents, chunks, hashes, mtimes = maps or (self.documents, self.chunks,
476
+ self._hashes, self._file_mtimes)
477
+ documents[doc_id] = {
450
478
  "path": doc_id,
451
479
  "full_path": str(fpath),
452
480
  "lines": len(content.splitlines()),
453
481
  "tokens": count_tokens(content),
454
482
  }
455
- self._hashes[doc_id] = content_hash(content)
483
+ hashes[doc_id] = content_hash(content)
456
484
  file_chunks = self._chunk_file(content, fpath.suffix.lower(), doc_id)
457
485
  for chunk in file_chunks:
458
- self.chunks[chunk["id"]] = chunk
459
- try:
460
- self._file_mtimes[doc_id] = os.path.getmtime(str(fpath))
461
- except Exception:
462
- pass
486
+ chunks[chunk["id"]] = chunk
487
+ if mtime is None:
488
+ try:
489
+ mtime = os.path.getmtime(str(fpath))
490
+ except Exception:
491
+ pass
492
+ if mtime is not None:
493
+ mtimes[doc_id] = mtime
463
494
  return file_chunks
464
495
 
465
496
  def _rebuild_symbols(self) -> None:
@@ -510,16 +541,28 @@ class CodeIndex:
510
541
  return exclude_parts
511
542
  return None
512
543
 
513
- def refresh(self, paths=None, on_progress=None) -> dict:
544
+ def refresh(self, paths=None, on_progress=None, trust_mtime: bool = False) -> dict:
514
545
  """Incremental update: re-chunk only files whose content hash changed.
515
546
 
516
547
  ``paths``: absolute or project-relative paths the caller knows changed
517
548
  (the watcher's list); a path that no longer exists drops its document.
518
549
  ``None`` walks the whole manifest and compares every file's hash —
519
550
  reading and hashing, not chunking and tokenizing, so it stays cheap.
551
+ ``trust_mtime`` (walk only): an indexed file whose mtime equals the
552
+ stored one counts as unchanged without being read. It is ignored while
553
+ mask rules exist, since a rule change alters a file's indexed view
554
+ without touching the file.
520
555
  Falls back to :meth:`build_index` when no store exists yet, when only a
521
556
  legacy layout is on disk, or when the incremental write fails.
522
557
  """
558
+ with self._write_lock:
559
+ prev = self._long_write
560
+ try:
561
+ return self._refresh(paths, on_progress, trust_mtime)
562
+ finally:
563
+ self._long_write = prev
564
+
565
+ def _refresh(self, paths, on_progress, trust_mtime) -> dict:
523
566
  t0 = time.perf_counter()
524
567
  if not self.chunks and not self._load_index():
525
568
  result = self.build_index(on_progress=on_progress)
@@ -533,6 +576,7 @@ class CodeIndex:
533
576
  mask_active = _ag.has_mask_rules(str(self.project_path))
534
577
  except Exception:
535
578
  mask_active = False
579
+ trust = trust_mtime and paths is None and not mask_active
536
580
 
537
581
  candidates: list = []
538
582
  removed: list = []
@@ -568,45 +612,68 @@ class CodeIndex:
568
612
  elif rel in self.documents:
569
613
  removed.append(rel)
570
614
 
571
- by_doc: dict = {}
572
- for cid, chunk in self.chunks.items():
573
- by_doc.setdefault(chunk.get("doc_id"), []).append(cid)
574
-
575
- upserts: dict = {}
615
+ fresh: list = [] # (rel, path, content, mtime) to re-chunk
616
+ touched: dict = {} # rel -> new mtime, content unchanged
617
+ seen: set = set() # the watcher's list can name a file twice
576
618
  changed = added = unchanged = skipped = 0
577
619
  for fpath in candidates:
578
620
  rel = str(fpath.relative_to(self.project_path))
621
+ if rel in seen:
622
+ continue
623
+ seen.add(rel)
624
+ known = rel in self.documents
625
+ try:
626
+ mtime = fpath.stat().st_mtime
627
+ except OSError:
628
+ mtime = None
629
+ if trust and known and mtime is not None and mtime == self._file_mtimes.get(rel):
630
+ unchanged += 1
631
+ continue
579
632
  content = self._read_indexable(fpath, mask_active)
580
633
  if content is None:
581
634
  skipped += 1
582
635
  continue
583
- digest = content_hash(content)
584
- if rel in self.documents and self._hashes.get(rel) == digest:
636
+ if known and self._hashes.get(rel) == content_hash(content):
585
637
  unchanged += 1
638
+ if mtime is not None and mtime != self._file_mtimes.get(rel):
639
+ touched[rel] = mtime
586
640
  continue
587
- existed = rel in self.documents
588
- for cid in by_doc.pop(rel, []):
589
- self.chunks.pop(cid, None)
590
- file_chunks = self._ingest_file(rel, fpath, content)
591
- upserts[rel] = (self.documents[rel], [(c["id"], c) for c in file_chunks])
592
- if existed:
641
+ fresh.append((rel, fpath, content, mtime))
642
+ if known:
593
643
  changed += 1
594
644
  else:
595
645
  added += 1
596
- if on_progress is not None:
597
- try:
598
- on_progress(len(candidates), changed + added, len(self.chunks))
599
- except Exception:
600
- pass
601
- for rel in removed:
602
- for cid in by_doc.pop(rel, []):
603
- self.chunks.pop(cid, None)
604
- self.documents.pop(rel, None)
605
- self._hashes.pop(rel, None)
606
- self._file_mtimes.pop(rel, None)
607
646
 
608
647
  rows = 0
609
- if upserts or removed:
648
+ upserts: dict = {}
649
+ if len(fresh) + len(removed) > self._SYNC_INLINE_MAX:
650
+ self._long_write = True # searches stop waiting for this one
651
+ if fresh or removed:
652
+ by_doc: dict = {}
653
+ for cid, chunk in self.chunks.items():
654
+ by_doc.setdefault(chunk.get("doc_id"), []).append(cid)
655
+ maps = (dict(self.documents), dict(self.chunks), dict(self._hashes), dict(self._file_mtimes))
656
+ documents, chunks, hashes, mtimes = maps
657
+ for rel, fpath, content, mtime in fresh:
658
+ for cid in by_doc.pop(rel, []):
659
+ chunks.pop(cid, None)
660
+ file_chunks = self._ingest_file(rel, fpath, content, mtime=mtime, maps=maps)
661
+ upserts[rel] = (documents[rel], [(c["id"], c) for c in file_chunks])
662
+ if on_progress is not None:
663
+ try:
664
+ on_progress(len(candidates), len(upserts), len(chunks))
665
+ except Exception:
666
+ pass
667
+ for rel in removed:
668
+ for cid in by_doc.pop(rel, []):
669
+ chunks.pop(cid, None)
670
+ documents.pop(rel, None)
671
+ hashes.pop(rel, None)
672
+ mtimes.pop(rel, None)
673
+ mtimes.update(touched)
674
+ # Swapped in whole, never edited in place: a search running now
675
+ # keeps reading the dicts it started with.
676
+ self.documents, self.chunks, self._hashes, self._file_mtimes = maps
610
677
  self._finish_build()
611
678
  try:
612
679
  rows = self._store.apply(upserts, removed, self._file_mtimes, self._hashes,
@@ -615,6 +682,15 @@ class CodeIndex:
615
682
  log.warning("incremental index write failed (%s); rebuilding", exc)
616
683
  return self.build_index(on_progress=on_progress)
617
684
  self._lexical_ok = self._lexical_wanted() and bool(self.chunks)
685
+ elif touched:
686
+ self._file_mtimes = {**self._file_mtimes, **touched}
687
+ if touched:
688
+ # A checkout or touch that kept the content: store the new mtime
689
+ # so the next trust_mtime pass does not read the file again.
690
+ try:
691
+ self._store.set_mtimes(touched)
692
+ except Exception as exc:
693
+ log.debug("index mtime update failed (%s)", exc)
618
694
 
619
695
  return {
620
696
  "mode": "incremental",
@@ -631,6 +707,75 @@ class CodeIndex:
631
707
  "lexical": {"engine": self.lexical_engine},
632
708
  }
633
709
 
710
+ # Re-indexing one changed file took 33-140 ms on C3's own repository. A
711
+ # search waits for this many; more (a branch switch, a big pull) are
712
+ # re-indexed behind the search instead of in front of it.
713
+ _SYNC_INLINE_MAX = 25
714
+
715
+ def sync_pending(self, wait_s: float = 2.0) -> dict | None:
716
+ """Re-index the files the watcher saw change since the last sync.
717
+
718
+ Search calls this first, so a hit never shows the old content of a
719
+ file the watcher already reported. It waits up to ``wait_s`` for
720
+ another writer (the startup re-check, the staleness agent), but not
721
+ for a full build or a refresh of many files, and it hands more than
722
+ ``_SYNC_INLINE_MAX`` paths to a background thread. Returns the
723
+ refresh result, or None when nothing was synced inline.
724
+ """
725
+ take = self.pending_changes
726
+ if take is None or self._long_write or not self.documents:
727
+ return None
728
+ deadline = time.monotonic() + wait_s
729
+ # Short polls, so a write that turns long while this search waits
730
+ # (the startup check finding a big pull) stops holding it up.
731
+ while not self._write_lock.acquire(timeout=0.05):
732
+ if self._long_write or time.monotonic() >= deadline:
733
+ return None
734
+ try:
735
+ paths = take()
736
+ if not paths:
737
+ return None
738
+ if len(paths) > self._SYNC_INLINE_MAX:
739
+ threading.Thread(target=self._refresh_behind, args=(paths,), daemon=True,
740
+ name="c3-index-sync").start()
741
+ return None
742
+ try:
743
+ return self.refresh(paths=paths)
744
+ except Exception as exc:
745
+ # Not queued again: a file that breaks the refresh would fail
746
+ # every search. The staleness agent and the next start retry it.
747
+ log.warning("index sync of %d changed file(s) failed (%s)", len(paths), exc)
748
+ return None
749
+ finally:
750
+ self._write_lock.release()
751
+
752
+ def _refresh_behind(self, paths) -> None:
753
+ prev, self._long_write = self._long_write, True
754
+ try:
755
+ self.refresh(paths=paths)
756
+ except Exception as exc:
757
+ log.warning("background index sync failed (%s)", exc)
758
+ finally:
759
+ self._long_write = prev
760
+
761
+ def refresh_stale(self) -> dict | None:
762
+ """Bring a stored index up to date with the files on disk.
763
+
764
+ Servers run this once at start, off the request path. While no
765
+ server ran, a git pull or branch switch could change, add or delete
766
+ files with no watcher to see it, and search kept returning the old
767
+ code. Files whose mtime matches the stored one are not read. Returns
768
+ None when there is no stored index to check, or when the check fails
769
+ (logged as a warning).
770
+ """
771
+ if not self.documents and not self._load_index():
772
+ return None
773
+ try:
774
+ return self.refresh(trust_mtime=True)
775
+ except Exception as exc:
776
+ log.warning("index check against the files failed (%s)", exc)
777
+ return None
778
+
634
779
  def _store_meta(self) -> dict:
635
780
  return {"cooccurrence": getattr(self, "_cooccurrence_stats", {}),
636
781
  "cooccurrence_map": self._cooccurrence}
@@ -1143,13 +1288,14 @@ class CodeIndex:
1143
1288
  """Exact symbol matches first; then score; then named/structural
1144
1289
  chunks and shorter paths on ties."""
1145
1290
  def key(item):
1146
- chunk = self.chunks[item[0]]
1291
+ # .get: a refresh may have swapped this chunk out since it ranked.
1292
+ chunk = self.chunks.get(item[0]) or {}
1147
1293
  return (
1148
1294
  1 if item[0] in exact_ids else 0,
1149
1295
  item[1],
1150
1296
  1 if chunk.get("name") else 0,
1151
1297
  1 if chunk.get("type") in {"function", "class", "method", "declaration"} else 0,
1152
- -len(chunk["doc_id"]),
1298
+ -len(chunk.get("doc_id") or ""),
1153
1299
  )
1154
1300
  return key
1155
1301
 
@@ -1238,6 +1384,10 @@ class CodeIndex:
1238
1384
  candidates (services/lexical_index.Filters). ``fusion=False`` returns
1239
1385
  the lexical ranking alone even when a dense backend is attached.
1240
1386
  """
1387
+ try:
1388
+ self.sync_pending()
1389
+ except Exception as exc:
1390
+ log.debug("index sync before search failed (%s)", exc)
1241
1391
  if not self.chunks:
1242
1392
  self._load_index()
1243
1393
  if not self.chunks:
@@ -1247,9 +1397,12 @@ class CodeIndex:
1247
1397
  fuse = bool(fusion) and self._dense_ready()
1248
1398
  rerank_now = self._rerank_ready()
1249
1399
  cache_key = (query, int(top_k), int(max_tokens), bool(include_content), filters.key(), fuse, rerank_now)
1250
- cached = self._search_cache.get(cache_key)
1400
+ # Held for the whole search: when a refresh swaps in a new cache
1401
+ # meanwhile, this search's results go to the old one, not the new.
1402
+ cache = self._search_cache
1403
+ cached = cache.get(cache_key)
1251
1404
  if cached is not None:
1252
- self._search_cache.move_to_end(cache_key)
1405
+ cache.move_to_end(cache_key)
1253
1406
  return [dict(item) for item in cached]
1254
1407
 
1255
1408
  query_tokens, query_bigrams = self._expand_query_tokens(query)
@@ -1258,10 +1411,11 @@ class CodeIndex:
1258
1411
  base_tokens = tokenize_code(query, dedupe=True)
1259
1412
 
1260
1413
  max_mtime = max(self._file_mtimes.values()) if self._file_mtimes else 0.0
1414
+ chunks = self.chunks
1261
1415
  exact_ids = {
1262
1416
  cid for cid in self._exact_symbol_ids(query)
1263
- if cid in self.chunks
1264
- and filters.chunk_ok(self.chunks[cid]["doc_id"], self.chunks[cid].get("type") or "")
1417
+ if cid in chunks
1418
+ and filters.chunk_ok(chunks[cid]["doc_id"], chunks[cid].get("type") or "")
1265
1419
  }
1266
1420
 
1267
1421
  ranked = None
@@ -1289,7 +1443,9 @@ class CodeIndex:
1289
1443
  seen_docs = set()
1290
1444
 
1291
1445
  for chunk_id, score in ranked[:top_k * 4]:
1292
- chunk = self.chunks[chunk_id]
1446
+ chunk = self.chunks.get(chunk_id)
1447
+ if chunk is None:
1448
+ continue
1293
1449
  chunk_tokens = chunk.get("tokens") or count_tokens(chunk["content"])
1294
1450
  window = None
1295
1451
 
@@ -1339,9 +1495,9 @@ class CodeIndex:
1339
1495
  if len(results) >= top_k or token_budget <= 0:
1340
1496
  break
1341
1497
 
1342
- self._search_cache[cache_key] = [dict(item) for item in results]
1343
- if len(self._search_cache) > self._search_cache_max:
1344
- self._search_cache.popitem(last=False)
1498
+ cache[cache_key] = [dict(item) for item in results]
1499
+ if len(cache) > self._search_cache_max:
1500
+ cache.popitem(last=False)
1345
1501
  return results
1346
1502
 
1347
1503
  def get_context(self, query: str, top_k: int = 5, max_tokens: int = 4000) -> str:
services/runtime.py CHANGED
@@ -179,6 +179,8 @@ def build_runtime(project_path: str, ide_name: str | None = None) -> C3Runtime:
179
179
  convo_store = ConversationStore(str(project))
180
180
  snapshots = ContextSnapshot(str(project))
181
181
  watcher = CodeWatcher(str(project))
182
+ # Search re-reads the files the watcher saw change before it answers.
183
+ indexer.pending_changes = watcher.take_index_changes
182
184
  file_memory = FileMemoryStore(str(project))
183
185
  validate_cfg = hybrid_config.get("validation_pipeline", {})
184
186
  validation_cache = ValidationCache(str(project), validate_cfg) if validate_cfg.get("enabled", True) else None
services/watcher.py CHANGED
@@ -53,6 +53,13 @@ class _ChangeHandler(FileSystemEventHandler):
53
53
  super().__init__()
54
54
  self._lock = threading.Lock()
55
55
  self._changes = []
56
+ # Paths the code index has not re-read yet. Kept apart from _changes,
57
+ # which other agents read through change_count, so the index taking
58
+ # its paths early does not hide a change from them.
59
+ self._index_pending: set = set()
60
+ # Bumped by every file or directory created, deleted or moved outside
61
+ # the pruned directories; a cached file listing is valid while it holds.
62
+ self.structure_generation = 0
56
63
  self._excluder = excluder # sub-project folders tracked by their own .c3
57
64
  self._root = Path(root) if root else None
58
65
  self._pruned = make_dir_pruner(root) if root else (lambda d: d in SKIP_DIRS)
@@ -123,22 +130,41 @@ class _ChangeHandler(FileSystemEventHandler):
123
130
  "path": path,
124
131
  "timestamp": datetime.now(timezone.utc).isoformat(),
125
132
  })
133
+ self._index_pending.add(path)
134
+
135
+ def _note_structure(self, path: str, is_directory: bool):
136
+ """Count a create, delete or move unless a pruned directory holds it."""
137
+ parts = self._rel_parts(Path(path))
138
+ dirs = parts if is_directory else parts[:-1]
139
+ if any(self._pruned(d) for d in dirs) or self._under_nested_checkout(dirs):
140
+ return
141
+ with self._lock:
142
+ self.structure_generation += 1
126
143
 
127
144
  def on_modified(self, event):
128
145
  if not event.is_directory:
129
146
  self._record("modified", event.src_path)
130
147
 
131
148
  def on_created(self, event):
149
+ self._note_structure(event.src_path, event.is_directory)
132
150
  if not event.is_directory:
133
151
  self._record("created", event.src_path)
134
152
 
135
153
  def on_deleted(self, event):
154
+ self._note_structure(event.src_path, event.is_directory)
136
155
  if not event.is_directory:
137
156
  self._record("deleted", event.src_path)
138
157
 
139
158
  def on_moved(self, event):
159
+ self._note_structure(event.src_path, event.is_directory)
160
+ self._note_structure(event.dest_path, event.is_directory)
140
161
  if not event.is_directory:
141
162
  self._record("moved", event.src_path)
163
+ # An editor's atomic save renames a temp file over the target:
164
+ # the index must re-read the destination too.
165
+ if self._should_track(event.dest_path):
166
+ with self._lock:
167
+ self._index_pending.add(event.dest_path)
142
168
 
143
169
  def get_and_clear(self) -> list:
144
170
  with self._lock:
@@ -146,6 +172,13 @@ class _ChangeHandler(FileSystemEventHandler):
146
172
  self._changes.clear()
147
173
  return changes
148
174
 
175
+ def take_index_pending(self) -> list:
176
+ """Paths changed since the last call, for the code index; forgets them."""
177
+ with self._lock:
178
+ paths = sorted(self._index_pending)
179
+ self._index_pending.clear()
180
+ return paths
181
+
149
182
  @property
150
183
  def change_count(self) -> int:
151
184
  with self._lock:
@@ -240,6 +273,19 @@ class CodeWatcher:
240
273
  if self._worker_thread:
241
274
  self._worker_thread.join(timeout=2)
242
275
 
276
+ @property
277
+ def running(self) -> bool:
278
+ """True while the observer thread delivers file-system events."""
279
+ return self._observer.is_alive() and not self._stop_event.is_set()
280
+
281
+ @property
282
+ def structure_generation(self) -> int:
283
+ return self._handler.structure_generation
284
+
285
+ def take_index_changes(self) -> list:
286
+ """Changed paths the code index has not re-read yet (see CodeIndex.sync_pending)."""
287
+ return self._handler.take_index_pending()
288
+
243
289
  def get_changes(self) -> list:
244
290
  """Return accumulated changes and clear the buffer."""
245
291
  changes = self._handler.get_and_clear()