code-context-control 2.49.2__py3-none-any.whl → 2.50.0__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/tools/edit.py CHANGED
@@ -8,6 +8,7 @@ Parallel safety:
8
8
  - Same file: serialized via per-file threading.Lock (_file_locks).
9
9
  - Same file, multiple hunks: use the `edits` batch parameter — one read/write cycle.
10
10
  """
11
+ import difflib
11
12
  import json
12
13
  import threading
13
14
  from pathlib import Path
@@ -33,12 +34,16 @@ def _read_preserving_newlines(path: Path) -> tuple[str, str]:
33
34
  `newline` is the EOL to write back: ``\r\n`` if CRLF dominates the
34
35
  file, otherwise ``\n``. This avoids Python's text-mode write rewriting
35
36
  every line to ``os.linesep`` on Windows.
37
+
38
+ Decodes with errors="surrogateescape" so files containing non-UTF-8
39
+ bytes are still editable: invalid bytes round-trip losslessly through
40
+ _write_preserving_newlines instead of raising UnicodeDecodeError.
36
41
  """
37
42
  raw = path.read_bytes()
38
43
  crlf = raw.count(b"\r\n")
39
44
  lf_only = raw.count(b"\n") - crlf
40
45
  newline = "\r\n" if crlf > lf_only else "\n"
41
- content = raw.decode("utf-8")
46
+ content = raw.decode("utf-8", errors="surrogateescape")
42
47
  # Normalize to \n internally so replacement matching is EOL-agnostic.
43
48
  content = content.replace("\r\n", "\n").replace("\r", "\n")
44
49
  return content, newline
@@ -52,7 +57,8 @@ def _write_preserving_newlines(path: Path, content: str, newline: str) -> None:
52
57
  """
53
58
  if newline != "\n":
54
59
  content = content.replace("\n", newline)
55
- with open(path, "w", encoding="utf-8", newline="") as fh:
60
+ with open(path, "w", encoding="utf-8", errors="surrogateescape",
61
+ newline="") as fh:
56
62
  fh.write(content)
57
63
 
58
64
 
@@ -66,9 +72,23 @@ _LOOKALIKE_TRANS = str.maketrans({
66
72
  "′": "'", "″": '"', # prime / double prime
67
73
  "‐": "-", "‑": "-", "‒": "-", "–": "-", # hyphen / dashes
68
74
  "—": "-", "―": "-", "−": "-",
69
- " ": " ", "": " ", "": " ", # non-breaking / figure / narrow-nbsp
75
+ "\u00a0": " ", "\u2007": " ", "\u202f": " ", # non-breaking / figure / narrow-nbsp
70
76
  })
71
77
 
78
+ # Bytes that aren't valid UTF-8 decode to lone surrogates U+DC80-U+DCFF under
79
+ # errors="surrogateescape" (how _read_preserving_newlines reads files), while
80
+ # c3_read renders those same bytes as U+FFFD (errors="replace"). Fold both to
81
+ # U+FFFD — 1:1 like the lookalikes — so an old_string copied from c3_read
82
+ # output still matches file content around undecodable bytes.
83
+ _SURROGATE_TRANS = {c: "\ufffd" for c in range(0xDC80, 0xDD00)}
84
+ _LOOKALIKE_TRANS.update(_SURROGATE_TRANS)
85
+
86
+
87
+ def _display_safe(s: str) -> str:
88
+ """Fold surrogateescape'd bytes to U+FFFD for error-message display —
89
+ lone surrogates cannot be encoded for MCP transport."""
90
+ return s.translate(_SURROGATE_TRANS) if s else s
91
+
72
92
 
73
93
  def _norm(s: str) -> str:
74
94
  return s.translate(_LOOKALIKE_TRANS) if s else s
@@ -125,6 +145,81 @@ def _apply_replacement(content: str, old: str, new: str, replace_all: bool):
125
145
  return (_positional_replace(content, nc, no, new, replace_all), count, True)
126
146
 
127
147
 
148
+ def _closest_region(content: str, old: str,
149
+ max_scan_lines: int = 40000, context: int = 2):
150
+ """Locate the file region most similar to a failed old_string.
151
+
152
+ Returns (start_line, end_line, region_text, ratio) — 1-based inclusive
153
+ line numbers, region padded with `context` lines each side — or None when
154
+ no region clears the similarity floor. Powers the 'closest match' payload
155
+ in not-found errors so a mismatched edit can be repaired without
156
+ re-reading the file (the moment agents historically drifted back to
157
+ native Read).
158
+ """
159
+ file_lines = content.split("\n")
160
+ old_lines = old.split("\n")
161
+ n, total = len(old_lines), len(file_lines)
162
+ if not old.strip() or total > max_scan_lines:
163
+ return None
164
+
165
+ # Anchor on old_string's most distinctive line, shortlist file lines that
166
+ # resemble it (cheap quick_ratio pass), then score full windows aligned
167
+ # to each shortlisted line (expensive ratio, capped at 8 candidates).
168
+ anchor_off, anchor_line = max(enumerate(old_lines),
169
+ key=lambda p: len(p[1].strip()))
170
+ anchor = anchor_line.strip()
171
+ sm = difflib.SequenceMatcher(autojunk=False)
172
+ sm.set_seq2(anchor)
173
+ scored = []
174
+ for i, line in enumerate(file_lines):
175
+ sm.set_seq1(line.strip())
176
+ if sm.real_quick_ratio() < 0.6:
177
+ continue
178
+ q = sm.quick_ratio()
179
+ if q >= 0.6:
180
+ scored.append((q, i))
181
+ if not scored:
182
+ return None
183
+ scored.sort(key=lambda t: -t[0])
184
+
185
+ win = difflib.SequenceMatcher(autojunk=False)
186
+ win.set_seq2(old)
187
+ best_ratio, best_start = 0.0, None
188
+ for _, i in scored[:8]:
189
+ start = max(0, min(i - anchor_off, total - n))
190
+ win.set_seq1("\n".join(file_lines[start:start + n]))
191
+ r = win.ratio()
192
+ if r > best_ratio:
193
+ best_ratio, best_start = r, start
194
+ if best_start is None or best_ratio < 0.5:
195
+ return None
196
+ lo = max(0, best_start - context)
197
+ hi = min(total, best_start + n + context)
198
+ return lo + 1, hi, "\n".join(file_lines[lo:hi]), best_ratio
199
+
200
+
201
+ _REGION_CAP = 4000
202
+
203
+
204
+ def _not_found_payload(near, file_label: str) -> str:
205
+ """Render a _closest_region result as an error-message appendix. The
206
+ region text is emitted verbatim (no indentation) so it can be copied
207
+ straight into a retry old_string."""
208
+ if not near:
209
+ return ""
210
+ lo, hi, region, ratio = near
211
+ region = _display_safe(region)
212
+ if len(region) > _REGION_CAP:
213
+ region = (region[:_REGION_CAP]
214
+ + f"\n⟦trimmed — run c3_read(file_path='{file_label}', "
215
+ f"lines=[{lo},{hi}]) for the rest⟧")
216
+ return (f"\n closest match: L{lo}-L{hi} ({ratio:.0%} similar). "
217
+ f"Actual file text between the markers:\n"
218
+ f"⟦L{lo}-L{hi}⟧\n{region}\n⟦end⟧\n"
219
+ f" Retry with old_string copied exactly from the text above "
220
+ f"(markers excluded) — no need to re-read the file.")
221
+
222
+
128
223
  def handle_edit(file_path: str, old_string: str, new_string: str,
129
224
  summary: str, tags: str, replace_all: bool,
130
225
  svc, finalize, edits: str = "") -> str:
@@ -209,8 +304,10 @@ def handle_edit(file_path: str, old_string: str, new_string: str,
209
304
  f"Read error: {e}", "read error")
210
305
 
211
306
  results = []
307
+ statuses = [] # parallel to results: 'ok' | 'miss' | 'ambiguous' | 'skipped'
212
308
  any_normalized = False
213
309
  any_applied = False
310
+ first_miss = ""
214
311
  for i, patch in enumerate(edit_list):
215
312
  old = patch.get("old_string", "")
216
313
  new = patch.get("new_string", "")
@@ -219,15 +316,23 @@ def handle_edit(file_path: str, old_string: str, new_string: str,
219
316
 
220
317
  if not old:
221
318
  results.append(f" patch[{i}]: skipped — empty old_string")
319
+ statuses.append("skipped")
222
320
  continue
223
321
 
224
322
  new_content, count, used_fallback = _apply_replacement(content, old, new, r_all)
225
323
  if new_content is None and count == 0:
226
- results.append(f" patch[{i}]: NOT FOUND — {old[:80]!r}")
324
+ near = _closest_region(content, old)
325
+ loc = (f" (closest: L{near[0]}-L{near[1]}, {near[3]:.0%} similar)"
326
+ if near else "")
327
+ results.append(f" patch[{i}]: NOT FOUND — {old[:80]!r}{loc}")
328
+ statuses.append("miss")
329
+ if near and not first_miss:
330
+ first_miss = _not_found_payload(near, file_path)
227
331
  continue
228
332
  if new_content is None:
229
333
  tag = " (unicode-normalized)" if used_fallback else ""
230
334
  results.append(f" patch[{i}]: AMBIGUOUS ({count} matches){tag} — {old[:60]!r}")
335
+ statuses.append("ambiguous")
231
336
  continue
232
337
 
233
338
  content = new_content
@@ -243,6 +348,7 @@ def handle_edit(file_path: str, old_string: str, new_string: str,
243
348
  + (f" ({n}x)" if n > 1 else "")
244
349
  + (" [norm]" if used_fallback else "")
245
350
  + f" | {desc}")
351
+ statuses.append("ok")
246
352
 
247
353
  # Only touch the file when at least one patch actually changed it —
248
354
  # avoids rewriting (and re-EOL-normalizing) an unchanged file and
@@ -266,12 +372,17 @@ def handle_edit(file_path: str, old_string: str, new_string: str,
266
372
  ]}
267
373
  _log_to_ledger(rel, summary or f"Batch edit: {len(edit_list)} patches", tag_list, svc, detail=batch_detail)
268
374
 
269
- applied = sum(1 for r in results if "NOT FOUND" not in r and "AMBIGUOUS" not in r and "skipped" not in r)
375
+ # Classify from the structured status list, not by substring-scanning
376
+ # the human-readable result lines — a patch *summary* containing words
377
+ # like 'NOT FOUND' used to be miscounted as a failure.
378
+ applied = statuses.count("ok")
270
379
  norm_tag = " [unicode-normalized]" if any_normalized else ""
271
380
  short = f"✓ {rel} — {applied}/{len(edit_list)} patches applied{norm_tag}"
272
381
  if applied < len(edit_list):
273
- failed = [r for r in results if "NOT FOUND" in r or "AMBIGUOUS" in r or "skipped" in r]
382
+ failed = [r for r, s in zip(results, statuses) if s != "ok"]
274
383
  short += "\n" + "\n".join(failed)
384
+ if first_miss:
385
+ short += first_miss
275
386
  return finalize("c3_edit", {"file": file_path}, short,
276
387
  f"{rel} patched ({len(edit_list)} patches)")
277
388
 
@@ -293,6 +404,7 @@ def handle_edit(file_path: str, old_string: str, new_string: str,
293
404
  hint = ""
294
405
  if _norm(old_string) != old_string or _norm(content) != content:
295
406
  hint = "\n hint: unicode-lookalike normalization also failed to match."
407
+ hint += _not_found_payload(_closest_region(content, old_string), file_path)
296
408
  return finalize("c3_edit", {"file": file_path},
297
409
  f"old_string not found in {file_path}\n"
298
410
  f" searched for: {old_string[:120]!r}{hint}",
cli/tools/read.py CHANGED
@@ -172,7 +172,14 @@ def handle_read(file_path: str, symbols: Any = None, lines: Any = None,
172
172
  pass
173
173
 
174
174
  raw_text = full.read_text(encoding="utf-8", errors="replace")
175
- content_lines = raw_text.splitlines()
175
+ # EOL-normalize exactly the way c3_edit's matcher does (\r\n and \r → \n),
176
+ # then split on \n ONLY. splitlines() also breaks on \x0c/\u2028/\x85 etc.,
177
+ # which rendered those in-line chars as line breaks — an old_string copied
178
+ # from that output (with \n) could never match the actual file bytes.
179
+ raw_text = raw_text.replace("\r\n", "\n").replace("\r", "\n")
180
+ content_lines = raw_text.split("\n")
181
+ if content_lines and content_lines[-1] == "":
182
+ content_lines.pop() # trailing \n would otherwise add a phantom empty line
176
183
  # Lazy: only count full file tokens when needed for the summary string
177
184
  _full_tok_cache = [None]
178
185
 
@@ -254,8 +261,9 @@ def handle_read(file_path: str, symbols: Any = None, lines: Any = None,
254
261
 
255
262
  if not ranges:
256
263
  file_map = svc.file_memory.get_or_build_map(rel_path)
257
- map_tok = count_tokens(file_map)
258
- resp = file_map
264
+ resp = (file_map
265
+ + "\n[map only — pass lines=[start,end] or symbols=[...] for exact source]")
266
+ map_tok = count_tokens(resp)
259
267
  return finalize_with_tokens(
260
268
  finalize, svc, "c3_read", {"file": file_path},
261
269
  resp, f"{full_file_tokens()}->{map_tok}tok",
@@ -278,13 +286,23 @@ def handle_read(file_path: str, symbols: Any = None, lines: Any = None,
278
286
  header = f"[read:{file_path}]"
279
287
 
280
288
  parts = []
289
+ prev_end = None
281
290
  for start, end in ranges:
282
291
  s_idx = max(0, start - 1)
283
292
  e_idx = min(len(content_lines), end)
284
293
  chunk = content_lines[s_idx:e_idx]
285
294
  if len(ranges) > 1:
286
- parts.append(f"--- L{start}-L{end} ---")
295
+ # ⟦…⟧ markers are tool chrome, not file content. The gap note makes
296
+ # the discontinuity explicit so a copied old_string never spans it.
297
+ if prev_end is None:
298
+ parts.append(f"⟦L{start}-L{end}⟧")
299
+ else:
300
+ parts.append(
301
+ f"⟦L{start}-L{end} — {start - prev_end - 1} lines "
302
+ f"(L{prev_end + 1}-L{start - 1}) omitted; blocks are NOT "
303
+ f"contiguous, never span this marker in a c3_edit old_string⟧")
287
304
  parts.extend(chunk)
305
+ prev_end = end
288
306
 
289
307
  final_content = "\n".join(parts)
290
308
  tokens = count_tokens(final_content)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-context-control
3
- Version: 2.49.2
3
+ Version: 2.50.0
4
4
  Summary: Local code-intelligence layer for AI coding tools (Claude Code, Codex, Gemini, Copilot). Retrieve less, read less, edit safer — and version the configs that shape your agent (CLAUDE.md, skills, hooks, MCP).
5
5
  Author-email: Dimitri Tselenchuk <dtselenc@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -63,14 +63,14 @@ cli/tools/artifacts.py,sha256=98shRIs3cdC8r0E1gfsEOIDUopqSP1WpYwzFiWfdtg0,7491
63
63
  cli/tools/bitbucket.py,sha256=_hgORCW9-IF5xZJaznoONVfaTGKaX8VcU7ALrBeLhWo,27518
64
64
  cli/tools/compress.py,sha256=aZ4owwqaQLtkszDr_g7yv5KkvtQPuqaSyMk-aM_hsCY,10060
65
65
  cli/tools/delegate.py,sha256=mwsEUsPXlC1ldkhhSk-i4_JUMsXy9ptIwlYV2_-kOoI,53812
66
- cli/tools/edit.py,sha256=GB3qdMhWEly4TYyU-P66Uqe87Nw6ZBzH-9ZO6_Q64t4,16604
66
+ cli/tools/edit.py,sha256=_3QosNcdZ_DaFRYn0Pa7qPsOuMaw7A9zcavb2HvgK2U,21493
67
67
  cli/tools/edits.py,sha256=8zM01TzLmjm7ULQlCmXOmitlJd84zQHVzE0z7UHJUdA,5520
68
68
  cli/tools/federate.py,sha256=wmC2QN7A6aay3cT7U9LDPYRCZKL1m_T6qFdZzpZmPx4,4650
69
69
  cli/tools/filter.py,sha256=_yhjOncC1kb-aRxjT7pkSILcMC-yXarBMh7oNS057rQ,12083
70
70
  cli/tools/impact.py,sha256=jjWkFTxHu-gBpZZNd2HTdBl22itA6-wwwOZXxk_qBl8,6257
71
71
  cli/tools/memory.py,sha256=yDDRsEngeFcjb6nXUrhRZXuboasXfixJeyltKhDbZD4,24935
72
72
  cli/tools/project.py,sha256=_2a2Rjw2xwbE-muJtH28uT7vjnPGQLGDDXbhmDO6Gh0,16407
73
- cli/tools/read.py,sha256=Lp-JCBToro1stV6tKrnKHLQA-K0x4eMM_L3QrNq7VHw,12350
73
+ cli/tools/read.py,sha256=U5VJFBGk-Ht_iBIj-TUlvPvTJR-G-5KnehQPlha_2YQ,13490
74
74
  cli/tools/search.py,sha256=6rsqZMaa11-5cmf75KtGwB5pn-fNq66hRT_1ffxEI-A,14680
75
75
  cli/tools/session.py,sha256=LIZbmEhNdh6rAsT6Dbpb21UY8xF9oubvpjGwfnXxQK4,4573
76
76
  cli/tools/shell.py,sha256=vGsvzQLISo-daKF40ZhRJXS5lDA6OV1t9RWoyqdlpt4,12617
@@ -93,7 +93,7 @@ cli/ui/components/sessions.js,sha256=FIKtil76B8tCkAmcFV7hlj6GQ_DCJK2jCzvEmdK7NBE
93
93
  cli/ui/components/settings.js,sha256=8LVTV2TQl9tcRXhXbtBEJOCBdiyk-x2QASoVYZUAuEA,71442
94
94
  cli/ui/components/sidebar.js,sha256=cAY_jwYB-o1X_wWn__VXlG4IegVObuE3NmVsuFWqxtg,7417
95
95
  cli/ui/components/tasks.js,sha256=OxLhspzzEQjxxtSEpOpugO2KptD4xNrimf_xM0wiVv8,12752
96
- code_context_control-2.49.2.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
96
+ code_context_control-2.50.0.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
97
97
  core/__init__.py,sha256=TSDCEcM4V7gcZVM3w2ykJaqEUch4Dkon-rivV17T73s,2501
98
98
  core/config.py,sha256=9R8bIcHhjSPdrfcCeMPnS4YgLCyRNWwlt_Z75PZcBDE,14780
99
99
  core/ide.py,sha256=9LzsDVK2LL8RVpL40l6oNGiasZ3D8OCU_9i9A0gJKBo,6876
@@ -219,8 +219,8 @@ tui/screens/search_view.py,sha256=MMHjVdlk3HZSuDBSvq8IGrqv_Mh5Us6YqXQ80bcWSMk,19
219
219
  tui/screens/session_view.py,sha256=eZ1eDwHTvPOck1wCCviixtOaCxIkBT_95ytNNNriGNA,5991
220
220
  tui/screens/stats.py,sha256=p81PjzdaIv7hllb8f45-rlVe4lJZwSdIMqu7e86_u5s,6223
221
221
  tui/screens/ui_view.py,sha256=1QJCgLh2YfgWIpvzRG1KOGXYEaOYX6ojN61Azjf2oX0,2125
222
- code_context_control-2.49.2.dist-info/METADATA,sha256=sjs_CXZq5EB_laB6l6Uz0kXUFxLaEJT7Bzfer1f5BPU,24369
223
- code_context_control-2.49.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
224
- code_context_control-2.49.2.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
225
- code_context_control-2.49.2.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
226
- code_context_control-2.49.2.dist-info/RECORD,,
222
+ code_context_control-2.50.0.dist-info/METADATA,sha256=WvENBhPvlRdAFzDNpbLW77Sju4IL9hAU7jZCFvHNzag,24369
223
+ code_context_control-2.50.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
224
+ code_context_control-2.50.0.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
225
+ code_context_control-2.50.0.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
226
+ code_context_control-2.50.0.dist-info/RECORD,,