code-context-control 2.163.0__py3-none-any.whl → 2.164.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.163.0"
99
+ __version__ = "2.164.1"
100
100
 
101
101
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
102
102
  AGENT_MATCHER = "Agent|Task"
@@ -6635,11 +6635,19 @@ def _creds_cmd_backup(args, project_path: str) -> None:
6635
6635
  from services import credential_backup as backup
6636
6636
 
6637
6637
  action = args.backup_cmd
6638
- if action in ("init", "restore", "passphrase") and not sys.stdin.isatty():
6638
+ if action == "init" and backup.is_enabled() and not backup.has_passphrase():
6639
+ # C3 already turned the backup on with a device key; the user is
6640
+ # here to add the passphrase.
6641
+ action = "passphrase"
6642
+ needs_passphrase = action in ("init", "passphrase") or (
6643
+ action == "restore" and not backup.device_opens())
6644
+ if needs_passphrase and not sys.stdin.isatty():
6639
6645
  print("[error] run this in your own terminal: the passphrase is read from "
6640
6646
  "the keyboard, never from a pipe or an argument.")
6641
6647
  return
6642
6648
  try:
6649
+ if action in ("status", "sync"):
6650
+ backup.ensure_default(_creds_known_projects(project_path))
6643
6651
  if action == "init":
6644
6652
  print("Choose a passphrase for the vault backup. Without it the backup "
6645
6653
  "cannot be opened -- keep it in your password manager.")
@@ -6666,6 +6674,19 @@ def _creds_cmd_backup(args, project_path: str) -> None:
6666
6674
  if st["enabled"]:
6667
6675
  print(f"Vault backup: on ({st['path']}, created {st['created']}) -- "
6668
6676
  f"{st['backed_up']} value(s) held.")
6677
+ if st["device"]:
6678
+ print(" opens on this Windows account without a prompt: a value "
6679
+ "the keychain loses is put back the next time it is read.")
6680
+ if st["device"] and st["device_scheme"] == "dpapi-machine":
6681
+ print(" [warn] Windows could not use this account's own DPAPI key, "
6682
+ "so the copy is locked with this computer's key: an "
6683
+ "administrator, or anyone with the unencrypted disk, can "
6684
+ "open it.")
6685
+ if not st["passphrase"]:
6686
+ print(" no passphrase set: if the Windows profile is reset this "
6687
+ "copy is lost too. Add one with `c3 creds backup passphrase`.")
6688
+ elif not st["device"]:
6689
+ print(" opens with the passphrase only (`c3 creds backup restore`).")
6669
6690
  else:
6670
6691
  print("Vault backup: off -- values live only in the OS keychain. "
6671
6692
  "Turn it on with `c3 creds backup init`.")
@@ -6675,7 +6696,8 @@ def _creds_cmd_backup(args, project_path: str) -> None:
6675
6696
  if st[key] and (st["enabled"] or key == "lost"):
6676
6697
  print(f" {label}: {', '.join(st[key])}")
6677
6698
  elif action == "restore":
6678
- passphrase = _creds_read_passphrase("Backup passphrase: ")
6699
+ passphrase = (_creds_read_passphrase("Backup passphrase: ")
6700
+ if needs_passphrase else None)
6679
6701
  only = [n.strip() for n in (args.only or "").split(",") if n.strip()]
6680
6702
  out = backup.restore(passphrase, only=only or None)
6681
6703
  print(f"[OK] Restored {len(out['restored'])} value(s)"
@@ -6688,12 +6710,14 @@ def _creds_cmd_backup(args, project_path: str) -> None:
6688
6710
  if out["restored"]:
6689
6711
  _creds_log_restore(out["restored"])
6690
6712
  else: # passphrase
6691
- old = _creds_read_passphrase("Current passphrase: ")
6713
+ had = backup.has_passphrase()
6714
+ old = _creds_read_passphrase("Current passphrase: ") if had else None
6692
6715
  new = _creds_read_passphrase(
6693
6716
  f"New passphrase (min {backup.MIN_PASSPHRASE} chars): ", confirm=True)
6694
- if old and new:
6717
+ if new and (old or not had):
6695
6718
  backup.change_passphrase(old, new)
6696
- print("[OK] Backup passphrase changed.")
6719
+ print("[OK] Backup passphrase changed." if had else
6720
+ "[OK] Backup passphrase set. Keep it in your password manager.")
6697
6721
  except backup.BackupError as exc:
6698
6722
  print(f"[error] {exc}")
6699
6723
 
@@ -248,7 +248,7 @@ c3 creds import .env --only STRIPE_KEY,DB_URL</code></pre>
248
248
  </tr>
249
249
  <tr>
250
250
  <td><code>~/.c3/vault_backup.json</code></td>
251
- <td>Optional, off by default. A passphrase-locked copy of every value, so a keyring wipe is not the only copy lost. See <a href="#backup">Vault backup</a>.</td>
251
+ <td>A sealed copy of every value, so a keyring wipe is not the only copy lost. On by default on Windows (v2.164.0), optional elsewhere. See <a href="#backup">Vault backup</a>.</td>
252
252
  </tr>
253
253
  </table>
254
254
 
@@ -428,7 +428,9 @@ c3_shell(cmd=<span class="str">'terraform apply'</span>, env_creds=<span class="
428
428
 
429
429
  <p>The OS keyring is the only copy of a value. On this project's own dev box, Windows emptied Credential Manager on a restart and took fourteen global credentials with it — the registry entries survived, but every value was gone. <code>c3 creds list</code> and <code>c3_credentials(action='list')</code> mark an entry like that <code>VALUE MISSING</code> / a "value missing" badge, computed live from whether the keychain still resolves it.</p>
430
430
 
431
- <p><code>c3 creds backup init</code> turns on a second copy at <code>~/.c3/vault_backup.json</code>. It does not depend on the OS keyring or DPAPI: each value is sealed to an X25519 public key (ephemeral ECDH, HKDF-SHA256, AES-GCM bound to the realm and name), and the matching private key is wrapped under a key derived from a passphrase you choose — <strong>16 characters minimum</strong>. From that point on, every value write (CLI, Hub, project UI, <code>c3_credentials</code>, a <code>.env</code> import) also seals a copy, with no extra prompt.</p>
431
+ <p><strong>On Windows the backup is on by default (v2.164.0).</strong> The first value you store creates <code>~/.c3/vault_backup.json</code> with a <em>device key</em> (the backup's key protected by Windows DPAPI, no passphrase) and copies every value that currently resolves. A value the keychain loses is then put back the next time it is listed or used, with no prompt, and the restore is logged by name. Set <code>C3_VAULT_BACKUP=off</code> to opt out. If Windows cannot use your account's own DPAPI key, the device key is protected with the computer's key instead and <code>c3 creds backup status</code> warns: an administrator, or anyone with the unencrypted disk, could open the copy. A device key does not survive a reset Windows profile or a new PC, so add a passphrase with <code>c3 creds backup init</code>.</p>
432
+
433
+ <p><code>c3 creds backup init</code> turns on a second copy at <code>~/.c3/vault_backup.json</code>, or adds a passphrase to the one Windows created. It does not depend on the OS keyring or DPAPI: each value is sealed to an X25519 public key (ephemeral ECDH, HKDF-SHA256, AES-GCM bound to the realm and name), and the matching private key is wrapped under a key derived from a passphrase you choose — <strong>16 characters minimum</strong>. From that point on, every value write (CLI, Hub, project UI, <code>c3_credentials</code>, a <code>.env</code> import) also seals a copy, with no extra prompt.</p>
432
434
 
433
435
  <table class="params-table action-table">
434
436
  <thead><tr><th>Command</th><th>Does</th></tr></thead>
cli/tools/credentials.py CHANGED
@@ -106,6 +106,9 @@ def _act_list(project_path: str) -> str:
106
106
  from services import credential_backup
107
107
  way_back = ("The user restores them in a terminal with `c3 creds backup "
108
108
  "restore` (it asks for the backup passphrase)"
109
+ if credential_backup.has_passphrase() else
110
+ "The vault backup holds no copy that opens here; the user "
111
+ "re-enters them (Credentials UI or `c3 creds set`)"
109
112
  if credential_backup.is_enabled() else
110
113
  "No vault backup is configured; the user re-enters them "
111
114
  "(Credentials UI or `c3 creds set`)")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: code-context-control
3
- Version: 2.163.0
3
+ Version: 2.164.1
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=RibfGcmUvnBSFFFBp89y78JUBBaBFjNxV1ym7WpBtdo,440934
4
+ cli/c3.py,sha256=cZynrrDHqfd9-TP-CMNxsXN5NHByO7f5-qybH99gMQA,442512
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
@@ -38,7 +38,7 @@ cli/commands/parser.py,sha256=tBJPvAcsP50VsXysBLeBtUoUTwc3PNFOyK1rgR85YFI,73772
38
38
  cli/guide/access.html,sha256=54KbBEZhr3ef_UbWPZzK6Ad91w_47qsMdx6rDmvF8DQ,47279
39
39
  cli/guide/bitbucket.html,sha256=lDm94czbl2iiAMmJ4gLxXB9m5As-8Dy5Q7b39jR_eKI,37012
40
40
  cli/guide/ci.html,sha256=-N1RZPyeJv4GyQ55rlIUT__trqpUCS_W--USdAs7Vbk,37438
41
- cli/guide/credentials.html,sha256=zC3jLZcVieiKNxKPN7gqXhfE8KuoRlXoMjmvMLCYTlM,66385
41
+ cli/guide/credentials.html,sha256=Jyb77QxePM-r0DvZL8ulWPjFDupltu1v4IhtoAUJ5iI,67285
42
42
  cli/guide/delegate.html,sha256=sS96lGojyAZ296rQBaq0liAV01KeaYOImGSlaPTRl1g,47601
43
43
  cli/guide/getting-started.html,sha256=lELRulCRHuU0So9rKn6rGYGYvCgDqka-lexM3xV1a3E,29529
44
44
  cli/guide/index.html,sha256=5yDe8gJTX2aH8seYwVmWKoL4wx5jrwgfb2_Z25zzamI,28666
@@ -90,7 +90,7 @@ cli/tools/artifacts.py,sha256=SjazShDFIzOpAZW7uMv9itBktXnc6pqQKZeaen8GgzI,9379
90
90
  cli/tools/bitbucket.py,sha256=xNmjL4d0E2Q7N5tMSgYvRBoZaX7Euop4bRUstOBhMxM,49237
91
91
  cli/tools/ci.py,sha256=1--Ak18ikHkO7q4HWlDCVac-U969eEFejkd-24T0xuY,20057
92
92
  cli/tools/compress.py,sha256=PcgxEw7KfofmJsTLfRf3mjWMxyNlqkcSNzMTlT27SW0,12534
93
- cli/tools/credentials.py,sha256=NczO0KT3LTJlD3ZedXWRAtH_8YTPhya0Txja3ystdzE,20039
93
+ cli/tools/credentials.py,sha256=J6fNyH7Ck02oMjPcbKIxpWhGnT4ElgXetShyxC93Yzk,20254
94
94
  cli/tools/delegate.py,sha256=qKyDu6fjqRRY4SpfhqaU1T4al-LT6Z_laOtnoPW-ivw,129514
95
95
  cli/tools/edit.py,sha256=9AOUtEG6sLEsbtKpd6cQyq66vCXNaOeoEKit3ikVJyc,44769
96
96
  cli/tools/edit_verify.py,sha256=3Y156LikO3Q4v0OSNjKDJUaOB3nRfceFvXCmpSV8amA,11858
@@ -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.163.0.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
138
+ code_context_control-2.164.1.dist-info/licenses/LICENSE,sha256=l8Kh5QCNWNvR6kIt8L0BUZvc2LAFiHv2c-FnsGnUZf4,11301
139
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
@@ -232,8 +232,8 @@ services/context_snapshot.py,sha256=2f_bxY3xX4ZC653ncYno8YSeSTFSavwBjrorytHA0Ns,
232
232
  services/conversation_store.py,sha256=RKA0nk09VAI8Ip935kSVlQdF-cQEzFLrgHbZiEJ7G1E,37518
233
233
  services/cred_audit.py,sha256=tdxnRzbB0c8nJ7dqA9HOJrcOeRWivEzq6yhwu6ksmZI,10240
234
234
  services/cred_telemetry.py,sha256=LwDd4x0Mu6YXeDUrgICHnX9o1Ym_4hoouRp98qx0zlI,10926
235
- services/credential_backup.py,sha256=TeOAwDAEG-BLnpO0E861m3AeFSbD8tQ_q3ydNYcMDds,13223
236
- services/credential_store.py,sha256=S5WnwPmaCJdo3wIZlWh7BRuT057pHPf1cdlzZOWPOgc,74627
235
+ services/credential_backup.py,sha256=zJurQAroHC0GiV9aQcKmggO_UygGaQzMm3zf_xON2xY,23774
236
+ services/credential_store.py,sha256=pTCv-3F7ldchQCabt8Qm1FuPIXvpLdwP7ZhSqCI0P50,75671
237
237
  services/cron_expr.py,sha256=rJMnFPWmCPZooy_C1GmS9hkZKA8sWIQuNRGFpqrshAY,10936
238
238
  services/delegate_agents.py,sha256=dIQAWepQgtDdV6s8WoCLvf7qAjlwMZHcVWWzsSO3qjE,4745
239
239
  services/delegate_hints.py,sha256=h65rOfY7PJDl5C8Z4b-L4vGcGri0h4J7canL0QWYQ28,8341
@@ -245,7 +245,7 @@ services/e2e_evaluator.py,sha256=FsB4vMzcFUcmicfIwRtA8JZ_XeMpuk2_-86F2iVNEDc,177
245
245
  services/e2e_tasks.py,sha256=Ln5VbGDIcS3NY3aml5ERbgjfjLxEslmRZ8AyaYxpWEo,34524
246
246
  services/edit_blobs.py,sha256=iPxHo7k_FMq8tsAKmEyb1e7yVlDZmt5_udmTYJPrlNA,6548
247
247
  services/edit_ledger.py,sha256=YwC247dzzxY2kGk97Srnipx5AdD5XZ2IqrnWIDsJ-8s,35426
248
- services/embedding_index.py,sha256=-d6Gatqq5OCrneGbvDTGrWyzbVx7562SrwABOFBRhjY,44294
248
+ services/embedding_index.py,sha256=b9W45Pu36jX94Fm--iQl1I3tkYWFsfwJbWWg_SjVYzE,45050
249
249
  services/enforcement_policy.py,sha256=znjABRB-8TSl0ELazY2ALzux2YJ5nWf8TvxLRhDsL2w,18905
250
250
  services/error_reporting.py,sha256=HZ3ru8i5RLf8nq2R4iRnTs5sm1blUxknSbv5hdxuxs0,4139
251
251
  services/file_map.py,sha256=j37DTR-UE_PMNj7vG2HiHucpwpJNaKgiD94UNUU-UXE,17091
@@ -259,7 +259,7 @@ services/host_handoff.py,sha256=zCPbPwSFGXuNUlGlHAWlmy7V7TizhduwS0upD3EYMsw,1210
259
259
  services/host_sessions.py,sha256=5R0DSU8z-CI6kKek4yLCwe1FShxZTOLe6dlYnH5-hoI,3722
260
260
  services/hub_service.py,sha256=z2MZ2Rg9NLNXxQ17e05XGF_f6qSTDWLYtoC3WpuQfGU,2634
261
261
  services/index_store.py,sha256=78DSUxfz0qLdW8RVRJdOtCKPL9Bdp6wbtWWgfA4E46Q,16921
262
- services/indexer.py,sha256=765nPLJWiCrcJgJ6pd0LAnVE7PyDn_nyM7WKRb0gVKI,67461
262
+ services/indexer.py,sha256=WiT0GRdBGe_LmTYpnetjoxjlzeracHl6txC9CNEyI54,69733
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
@@ -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.163.0.dist-info/METADATA,sha256=H1u3YADW4tESb8-v13FxtFTEjyb64HhNE7MSBKkkX5k,29476
358
- code_context_control-2.163.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
- code_context_control-2.163.0.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
- code_context_control-2.163.0.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
- code_context_control-2.163.0.dist-info/RECORD,,
357
+ code_context_control-2.164.1.dist-info/METADATA,sha256=J3RbZSArEBgzNA9_FQ61kmoYyDHRv3MgrxLg0br7zSE,29476
358
+ code_context_control-2.164.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
359
+ code_context_control-2.164.1.dist-info/entry_points.txt,sha256=7kX_WUsDCF2hbXzvbNyscyaBb9AeA-DJY5v_5hN0DlU,93
360
+ code_context_control-2.164.1.dist-info/top_level.txt,sha256=wRt41zBybVF3qAiNXHz9BURbkKvUvfhmWWtKMhaw6eE,29
361
+ code_context_control-2.164.1.dist-info/RECORD,,
@@ -1,24 +1,35 @@
1
- """Passphrase-locked second copy of every credential value.
1
+ """Second copy of every credential value, outside the OS keychain.
2
2
 
3
3
  The OS keychain is the vault's only copy of a value, and Windows Credential
4
- Manager can lose every entry at once (it did twice on one box in September
5
- 2026). ``~/.c3/vault_backup.json`` keeps a copy that depends on neither the
6
- keychain nor DPAPI:
4
+ Manager can lose every entry at once. ``~/.c3/vault_backup.json`` keeps a
5
+ copy that does not depend on the keychain:
7
6
 
8
7
  * each value is sealed to an X25519 public key (ephemeral ECDH, HKDF-SHA256,
9
8
  AES-GCM with ``realm|name`` as associated data). Sealing needs no secret,
10
9
  so every value write updates the backup without a prompt;
11
- * the matching private key is stored wrapped under a key derived from a
12
- passphrase the user chose (scrypt). Reading anything back needs it.
13
-
14
- Only :func:`restore` decrypts, and it writes each value straight back into
15
- the keychain; no function here returns a value.
10
+ * the matching private key is stored wrapped, up to twice:
11
+
12
+ - ``device_key`` (Windows): protected with DPAPI, for the signed-in user
13
+ or, when Windows cannot use the user's key, for the computer (see
14
+ :func:`_device_protect`). It opens with no prompt, so a value the
15
+ keychain lost is put back the next time something reads it
16
+ (:func:`heal`). On Windows this wrap is created automatically the first
17
+ time a value is stored (:func:`ensure_default`), so the backup is on by
18
+ default there.
19
+ - ``wrapped_key``: under a key derived from a passphrase the user chose
20
+ (scrypt). It depends on neither the keychain nor DPAPI, and is the only
21
+ way back when the Windows profile itself is lost.
22
+
23
+ Only :func:`restore` and :func:`heal` decrypt, and they write each value
24
+ straight back into the keychain; no function here returns a value.
16
25
  """
17
26
  from __future__ import annotations
18
27
 
19
28
  import base64
20
29
  import json
21
30
  import os
31
+ import sys
32
+ import threading
22
33
  from datetime import datetime, timezone
23
34
  from pathlib import Path
24
35
  from typing import Optional
@@ -33,6 +44,11 @@ SCRYPT_P = 1
33
44
  MIN_PASSPHRASE = 16
34
45
  _HKDF_INFO = FORMAT.encode("ascii")
35
46
  _WRAP_AAD = (FORMAT + "|private-key").encode("ascii")
47
+ _DEVICE_ENTROPY = (FORMAT + "|device-key").encode("ascii")
48
+ # Set to off/0/false/no to keep C3 from creating a backup on its own.
49
+ AUTO_ENV = "C3_VAULT_BACKUP"
50
+ # heal() reads the vault, and vault reads call heal(): one level only.
51
+ _HEALING = threading.local()
36
52
 
37
53
 
38
54
  class BackupError(RuntimeError):
@@ -101,6 +117,124 @@ def is_enabled() -> bool:
101
117
  return path is not None and path.exists()
102
118
 
103
119
 
120
+ def _dpapi(raw: bytes, *, protect: bool, machine: bool = False) -> Optional[bytes]:
121
+ """CryptProtectData / CryptUnprotectData. ``machine`` protects with the
122
+ computer's key instead of the signed-in user's; unprotecting detects the
123
+ scope from the blob. None when this is not Windows or Windows refuses
124
+ (no prompt is shown)."""
125
+ if sys.platform != "win32":
126
+ return None
127
+ try:
128
+ import ctypes
129
+ from ctypes import wintypes
130
+
131
+ class _Blob(ctypes.Structure):
132
+ _fields_ = [("cbData", wintypes.DWORD),
133
+ ("pbData", ctypes.POINTER(ctypes.c_char))]
134
+
135
+ def blob(data: bytes):
136
+ buf = ctypes.create_string_buffer(data, len(data))
137
+ return _Blob(len(data), ctypes.cast(
138
+ buf, ctypes.POINTER(ctypes.c_char))), buf
139
+
140
+ source, _source_buf = blob(raw)
141
+ entropy, _entropy_buf = blob(_DEVICE_ENTROPY)
142
+ out = _Blob()
143
+ crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
144
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
145
+ kernel32.LocalFree.argtypes = [ctypes.c_void_p]
146
+ call = crypt32.CryptProtectData if protect else crypt32.CryptUnprotectData
147
+ flags = 0x1 # CRYPTPROTECT_UI_FORBIDDEN
148
+ if protect and machine:
149
+ flags |= 0x4 # CRYPTPROTECT_LOCAL_MACHINE
150
+ if not call(ctypes.byref(source), None, ctypes.byref(entropy), None,
151
+ None, flags, ctypes.byref(out)):
152
+ return None
153
+ try:
154
+ return ctypes.string_at(out.pbData, out.cbData)
155
+ finally:
156
+ kernel32.LocalFree(ctypes.cast(out.pbData, ctypes.c_void_p))
157
+ except Exception:
158
+ return None
159
+
160
+
161
+ def device_available() -> bool:
162
+ """Whether this platform can hold a device key (Windows DPAPI)."""
163
+ return sys.platform == "win32"
164
+
165
+
166
+ def _device_protect(raw: bytes) -> Optional[tuple]:
167
+ """``(scheme, blob)``. The user's own DPAPI key when Windows can use it.
168
+ A profile whose DPAPI master key is unreadable is also one whose
169
+ Credential Manager cannot save to disk, so that case falls back to the
170
+ computer's key: weaker (any administrator, or anyone holding the
171
+ unencrypted disk, can open it) but it is the case the backup exists for."""
172
+ blob = _dpapi(raw, protect=True)
173
+ if blob:
174
+ return "dpapi", blob
175
+ blob = _dpapi(raw, protect=True, machine=True)
176
+ return ("dpapi-machine", blob) if blob else None
177
+
178
+
179
+ def _device_unprotect(blob: bytes) -> Optional[bytes]:
180
+ return _dpapi(blob, protect=False)
181
+
182
+
183
+ def auto_enabled() -> bool:
184
+ return os.environ.get(AUTO_ENV, "").strip().lower() not in (
185
+ "off", "0", "false", "no")
186
+
187
+
188
+ def _private_raw(c: dict, private) -> bytes:
189
+ ser = c["serialization"]
190
+ return private.private_bytes(
191
+ ser.Encoding.Raw, ser.PrivateFormat.Raw, ser.NoEncryption())
192
+
193
+
194
+ def _device_wrap(private_raw: bytes) -> Optional[dict]:
195
+ if not device_available():
196
+ return None
197
+ wrapped = _device_protect(private_raw)
198
+ if not wrapped:
199
+ return None
200
+ return {"scheme": wrapped[0], "blob": _b64(wrapped[1]), "at": _now()}
201
+
202
+
203
+ def _device_private(c: dict, data: dict):
204
+ """The private key from the device wrap, or None when there is no wrap,
205
+ Windows no longer opens it, or it is not this backup's key."""
206
+ wrap = data.get("device_key")
207
+ if not isinstance(wrap, dict) or not device_available():
208
+ return None
209
+ try:
210
+ raw = _device_unprotect(_unb64(str(wrap["blob"])))
211
+ if not raw or len(raw) != 32:
212
+ return None
213
+ private = c["X25519PrivateKey"].from_private_bytes(raw)
214
+ if _b64(_raw_public(c, private.public_key())) != data.get("public_key"):
215
+ return None
216
+ return private
217
+ except (KeyError, ValueError):
218
+ return None
219
+
220
+
221
+ def has_passphrase() -> bool:
222
+ """Whether the backup can be opened with a passphrase. False when off."""
223
+ try:
224
+ return "wrapped_key" in _load()
225
+ except BackupError:
226
+ return False
227
+
228
+
229
+ def device_opens() -> bool:
230
+ """Whether the backup opens on this device right now, with no prompt."""
231
+ try:
232
+ data = _load()
233
+ return bool(data) and _device_private(_crypto(), data) is not None
234
+ except BackupError:
235
+ return False
236
+
237
+
104
238
  def _kek(c: dict, passphrase: str, kdf: dict) -> bytes:
105
239
  return c["Scrypt"](salt=_unb64(kdf["salt"]), length=32, n=int(kdf["n"]),
106
240
  r=int(kdf["r"]), p=int(kdf["p"])).derive(
@@ -116,7 +250,11 @@ def _wrap(c: dict, private_raw: bytes, passphrase: str) -> tuple:
116
250
 
117
251
 
118
252
  def _unwrap(c: dict, data: dict, passphrase: str):
119
- wrapped = data["wrapped_key"]
253
+ wrapped = data.get("wrapped_key")
254
+ if not isinstance(wrapped, dict) or "kdf" not in data:
255
+ raise BackupError(
256
+ "this vault backup has no passphrase; it opens only on the Windows "
257
+ "account that created it")
120
258
  try:
121
259
  raw = c["AESGCM"](_kek(c, passphrase, data["kdf"])).decrypt(
122
260
  _unb64(wrapped["nonce"]), _unb64(wrapped["ct"]), _WRAP_AAD)
@@ -141,34 +279,100 @@ def _record_key(c: dict, shared: bytes, epk: bytes, pub: bytes) -> bytes:
141
279
  info=_HKDF_INFO).derive(shared)
142
280
 
143
281
 
144
- def init(passphrase: str) -> None:
145
- """Create the backup file. Refuses to replace one that exists."""
146
- _check_passphrase(passphrase)
282
+ def _create(passphrase: Optional[str]) -> None:
147
283
  if is_enabled():
148
284
  raise BackupError(f"a backup already exists at {backup_path()}")
149
285
  c = _crypto()
150
- ser = c["serialization"]
151
286
  private = c["X25519PrivateKey"].generate()
152
- private_raw = private.private_bytes(
153
- ser.Encoding.Raw, ser.PrivateFormat.Raw, ser.NoEncryption())
154
- kdf, wrapped = _wrap(c, private_raw, passphrase)
155
- _save({"format": FORMAT, "created": _now(),
156
- "public_key": _b64(_raw_public(c, private.public_key())),
157
- "kdf": kdf, "wrapped_key": wrapped, "records": {}})
287
+ private_raw = _private_raw(c, private)
288
+ data = {"format": FORMAT, "created": _now(),
289
+ "public_key": _b64(_raw_public(c, private.public_key()))}
290
+ device = _device_wrap(private_raw)
291
+ if device:
292
+ data["device_key"] = device
293
+ if passphrase is not None:
294
+ data["kdf"], data["wrapped_key"] = _wrap(c, private_raw, passphrase)
295
+ elif not device:
296
+ raise BackupError(
297
+ "no device key is available on this system; run `c3 creds backup "
298
+ "init` to protect the backup with a passphrase")
299
+ data["records"] = {}
300
+ _save(data)
301
+
302
+
303
+ def init(passphrase: str) -> None:
304
+ """Create the backup file, locked with a passphrase (and, on Windows, a
305
+ device key as well). Refuses to replace one that exists."""
306
+ _check_passphrase(passphrase)
307
+ _create(passphrase)
308
+
309
+
310
+ def init_device() -> None:
311
+ """Create a backup that opens only on this Windows account, with no
312
+ passphrase. Refuses to replace one that exists."""
313
+ _create(None)
314
+
315
+
316
+ def ensure_default(project_paths=()) -> bool:
317
+ """Turn the backup on where that needs no question: Windows, no backup
318
+ file yet, not opted out with ``C3_VAULT_BACKUP=off``. Copies every value
319
+ that currently resolves. True when this call created the backup."""
320
+ if is_enabled() or not device_available() or not auto_enabled():
321
+ return False
322
+ try:
323
+ init_device()
324
+ sync(project_paths)
325
+ except (BackupError, OSError):
326
+ return False
327
+ return True
328
+
329
+
330
+ def _refresh_device_key(c: dict, private) -> None:
331
+ """Give the backup a device wrap that opens here. Best effort."""
332
+ try:
333
+ data = _load()
334
+ if not data or _device_private(c, data) is not None:
335
+ return
336
+ device = _device_wrap(_private_raw(c, private))
337
+ if device:
338
+ data["device_key"] = device
339
+ _save(data)
340
+ except (BackupError, OSError):
341
+ pass
158
342
 
159
343
 
160
- def change_passphrase(old: str, new: str) -> None:
161
- """Re-wrap the private key; the sealed records stay as they are."""
344
+ def _unlock(c: dict, data: dict, passphrase: Optional[str]):
345
+ """The private key, from the passphrase when one is given, else from the
346
+ device key."""
347
+ if passphrase is not None:
348
+ return _unwrap(c, data, passphrase)
349
+ private = _device_private(c, data)
350
+ if private is not None:
351
+ return private
352
+ if "wrapped_key" in data:
353
+ raise BackupError(
354
+ "the vault backup does not open on this device; its passphrase "
355
+ "is needed")
356
+ raise BackupError(
357
+ "the vault backup no longer opens on this device and has no "
358
+ "passphrase, so its values cannot be recovered. Delete "
359
+ f"{backup_path()} and re-enter the values")
360
+
361
+
362
+ def change_passphrase(old: Optional[str], new: str) -> None:
363
+ """Set or replace the passphrase; the sealed records stay as they are.
364
+
365
+ ``old`` is the current passphrase. A backup that has none yet is opened
366
+ with its device key instead, and ``old`` is ignored."""
162
367
  _check_passphrase(new)
163
368
  data = _load()
164
369
  if not data:
165
370
  raise BackupError("no vault backup to change")
166
371
  c = _crypto()
167
- ser = c["serialization"]
168
- private = _unwrap(c, data, old)
169
- data["kdf"], data["wrapped_key"] = _wrap(c, private.private_bytes(
170
- ser.Encoding.Raw, ser.PrivateFormat.Raw, ser.NoEncryption()), new)
372
+ private = _unlock(c, data, old if "wrapped_key" in data else None)
373
+ data["kdf"], data["wrapped_key"] = _wrap(c, _private_raw(c, private), new)
171
374
  _save(data)
375
+ _refresh_device_key(c, private)
172
376
 
173
377
 
174
378
  def seal(realm_s: str, name: str, value: str) -> str:
@@ -180,7 +384,10 @@ def seal(realm_s: str, name: str, value: str) -> str:
180
384
  try:
181
385
  data = _load()
182
386
  if not data:
183
- return "off"
387
+ scope, project_path = _realm_target(realm_s)
388
+ if not ensure_default((project_path,) if scope == "project" else ()):
389
+ return "off"
390
+ data = _load()
184
391
  c = _crypto()
185
392
  pub_raw = _unb64(data["public_key"])
186
393
  ephemeral = c["X25519PrivateKey"].generate()
@@ -231,11 +438,53 @@ def _realm_target(realm_s: str) -> tuple:
231
438
  return "", ""
232
439
 
233
440
 
234
- def restore(passphrase: str, *, only=None) -> dict:
441
+ def _restore_with(c: dict, data: dict, private, *, only=None,
442
+ realm_only: str = "") -> tuple:
443
+ """``(report, [(realm, name) restored])``. ``_HEALING`` is held so the
444
+ vault reads made here do not start a heal of their own."""
445
+ wanted = set(only) if only else None
446
+ out: dict = {"restored": [], "present": [], "orphaned": [], "failed": []}
447
+ done: list = []
448
+ was_healing = getattr(_HEALING, "on", False)
449
+ _HEALING.on = True
450
+ try:
451
+ for realm_s, records in sorted(data.get("records", {}).items()):
452
+ if realm_only and realm_s != realm_only:
453
+ continue
454
+ scope, project_path = _realm_target(realm_s)
455
+ for name, rec in sorted(records.items()):
456
+ if wanted is not None and name not in wanted:
457
+ continue
458
+ label = name if scope == "global" else f"{name} ({project_path})"
459
+ if not scope or not Path(project_path).is_dir() \
460
+ or name not in cs._read_entries(scope, project_path):
461
+ out["orphaned"].append(label)
462
+ continue
463
+ if cs.is_resolvable(name, project_path=project_path, scope=scope):
464
+ out["present"].append(label)
465
+ continue
466
+ try:
467
+ value = _open(c, private, realm_s, name, rec)
468
+ cs.restore_value(name, value, scope=scope,
469
+ project_path=project_path)
470
+ out["restored"].append(label)
471
+ done.append((realm_s, name))
472
+ except (c["InvalidTag"], cs.CredentialError, KeyError,
473
+ ValueError) as exc:
474
+ out["failed"].append(f"{label}: {type(exc).__name__}")
475
+ finally:
476
+ _HEALING.on = was_healing
477
+ return out, done
478
+
479
+
480
+ def restore(passphrase: Optional[str] = None, *, only=None) -> dict:
235
481
  """Write every backed-up value whose entry is registered but has lost its
236
482
  value back into the keychain. A value that still resolves is never
237
483
  overwritten, and an entry deleted since is not recreated.
238
484
 
485
+ With no passphrase the backup is opened with its device key, and a
486
+ :class:`BackupError` says so when that does not work here.
487
+
239
488
  Returns name lists: ``restored``, ``present`` (value still there),
240
489
  ``orphaned`` (entry or project gone), ``failed``. Restored entries come
241
490
  back injection-only; see ``credential_store.restore_value``."""
@@ -243,31 +492,56 @@ def restore(passphrase: str, *, only=None) -> dict:
243
492
  if not data:
244
493
  raise BackupError("no vault backup found — nothing to restore from")
245
494
  c = _crypto()
246
- private = _unwrap(c, data, passphrase)
247
- wanted = set(only) if only else None
248
- out: dict = {"restored": [], "present": [], "orphaned": [], "failed": []}
249
- for realm_s, records in sorted(data.get("records", {}).items()):
250
- scope, project_path = _realm_target(realm_s)
251
- for name, rec in sorted(records.items()):
252
- if wanted is not None and name not in wanted:
253
- continue
254
- label = name if scope == "global" else f"{name} ({project_path})"
255
- if not scope or not Path(project_path).is_dir() \
256
- or name not in cs._read_entries(scope, project_path):
257
- out["orphaned"].append(label)
258
- continue
259
- if cs.is_resolvable(name, project_path=project_path, scope=scope):
260
- out["present"].append(label)
261
- continue
262
- try:
263
- value = _open(c, private, realm_s, name, rec)
264
- cs.restore_value(name, value, scope=scope, project_path=project_path)
265
- out["restored"].append(label)
266
- except (c["InvalidTag"], cs.CredentialError, KeyError, ValueError) as exc:
267
- out["failed"].append(f"{label}: {type(exc).__name__}")
495
+ private = _unlock(c, data, passphrase)
496
+ out, _done = _restore_with(c, data, private, only=only)
497
+ if passphrase is not None:
498
+ _refresh_device_key(c, private)
268
499
  return out
269
500
 
270
501
 
502
+ def heal(realm_s: str, names) -> list:
503
+ """Put back the values of ``names`` in one realm that the keychain lost,
504
+ using the device key. Returns the names restored. No prompt, never
505
+ raises, and does nothing when the backup cannot be opened here.
506
+
507
+ Called by the vault's own read paths, so a wipe repairs itself the first
508
+ time a value is listed or used."""
509
+ if getattr(_HEALING, "on", False) or not names:
510
+ return []
511
+ try:
512
+ if not is_enabled():
513
+ return []
514
+ data = _load()
515
+ held = data.get("records", {}).get(realm_s, {})
516
+ wanted = [n for n in names if n in held]
517
+ if not wanted or "device_key" not in data:
518
+ return []
519
+ c = _crypto()
520
+ private = _device_private(c, data)
521
+ if private is None:
522
+ return []
523
+ out, done = _restore_with(c, data, private, only=wanted,
524
+ realm_only=realm_s)
525
+ except (BackupError, OSError, KeyError, ValueError):
526
+ return []
527
+ if out["restored"]:
528
+ _log_heal(out["restored"])
529
+ return [name for _realm, name in done]
530
+
531
+
532
+ def _log_heal(labels: list) -> None:
533
+ """Names only, to the global activity log that `c3 creds audit` reads."""
534
+ try:
535
+ from services.activity_log import ActivityLog
536
+ home = cs.global_base()
537
+ if home is not None:
538
+ ActivityLog(str(home)).log("cred_action", {
539
+ "kind": "creds", "action": "restore", "names": labels,
540
+ "via": "auto"})
541
+ except (ImportError, OSError, ValueError):
542
+ pass
543
+
544
+
271
545
  def _realm_entries(project_paths) -> list:
272
546
  """``(scope, project_path, realm, name)`` for every registered entry in the
273
547
  global vault and the given projects."""
@@ -293,7 +567,7 @@ def sync(project_paths=()) -> dict:
293
567
  """Seal every value that still resolves in the global vault and the given
294
568
  projects. Returns ``{"saved": n, "missing": [names without a value],
295
569
  "failed": [...]}``."""
296
- if not is_enabled():
570
+ if not is_enabled() and not ensure_default(project_paths):
297
571
  raise BackupError("no vault backup configured — run `c3 creds backup init`")
298
572
  out: dict = {"saved": 0, "missing": [], "failed": []}
299
573
  for scope, pp, realm_s, name in _realm_entries(project_paths):
@@ -321,6 +595,9 @@ def status(project_paths=(), presence=None) -> dict:
321
595
  records = data.get("records", {}) if data else {}
322
596
  out: dict = {"enabled": bool(data), "path": str(backup_path() or ""),
323
597
  "created": data.get("created", "") if data else "",
598
+ "passphrase": "wrapped_key" in data,
599
+ "device": bool(data) and _device_private(_crypto(), data) is not None,
600
+ "device_scheme": str((data.get("device_key") or {}).get("scheme", "")),
324
601
  "backed_up": sum(len(r) for r in records.values()),
325
602
  "restorable": [], "lost": [], "not_backed_up": []}
326
603
  known = dict(presence or {})
@@ -746,7 +746,7 @@ def _display_projection(ctype: str, fields: dict) -> dict:
746
746
 
747
747
 
748
748
  def _store_value(name: str, value: str, *, scope: str, project_path: str,
749
- realm_s: str) -> tuple:
749
+ realm_s: str, backup: bool = True) -> tuple:
750
750
  """Write the value to whichever backend its size calls for.
751
751
 
752
752
  Returns ``(storage, raw_bytes, backup)`` where ``backup`` is the
@@ -755,6 +755,8 @@ def _store_value(name: str, value: str, *, scope: str, project_path: str,
755
755
  and the "clean up the backend we are no longer using" half exist once —
756
756
  a value that grew past the threshold must leave the keyring, and one
757
757
  that shrank must leave the sidecar, or a stale copy outlives the entry.
758
+ ``backup=False`` skips the seal (result ``"kept"``): the value came out
759
+ of the backup, so its copy there is already current.
758
760
  """
759
761
  from services import credential_backup
760
762
  raw = value.encode("utf-8")
@@ -772,7 +774,8 @@ def _store_value(name: str, value: str, *, scope: str, project_path: str,
772
774
  _keyring_module().delete_password(KEYRING_SERVICE, _account(realm_s, name))
773
775
  except Exception:
774
776
  pass
775
- return storage, raw, credential_backup.seal(realm_s, name, value)
777
+ return storage, raw, (credential_backup.seal(realm_s, name, value)
778
+ if backup else "kept")
776
779
 
777
780
 
778
781
  def set_credential(
@@ -977,7 +980,8 @@ def restore_value(name: str, value: str, *, scope: str, project_path: str = ".")
977
980
  if entry is None:
978
981
  raise CredentialError(f"{name!r} is not registered in {scope} scope")
979
982
  realm_s = realm(scope, project_path)
980
- _store_value(name, value, scope=scope, project_path=project_path, realm_s=realm_s)
983
+ _store_value(name, value, scope=scope, project_path=project_path,
984
+ realm_s=realm_s, backup=False)
981
985
  ctype = str(entry.get("type") or "")
982
986
  if ctype in STRUCTURED_TYPES:
983
987
  _write_struct_attestation(realm_s, name, ctype)
@@ -1194,6 +1198,12 @@ def value_presence(scope: str, project_path: str = ".", names=None) -> dict:
1194
1198
  except Exception:
1195
1199
  attested = ""
1196
1200
  out[name] = attested not in STRUCTURED_TYPES
1201
+ missing = [n for n, ok in out.items() if not ok]
1202
+ if missing:
1203
+ from services import credential_backup
1204
+ healed = credential_backup.heal(realm_s, missing)
1205
+ if healed:
1206
+ out.update(value_presence(scope, project_path, names=healed))
1197
1207
  return out
1198
1208
 
1199
1209
 
@@ -1220,8 +1230,20 @@ def _get_raw(name: str, *, project_path: str = ".", scope: str = "") -> Optional
1220
1230
  if not isinstance(entry, dict):
1221
1231
  return None
1222
1232
  realm_s = realm(owning, project_path)
1233
+ raw = _read_stored(entry, owning, project_path, realm_s, name)
1234
+ if raw is None:
1235
+ from services import credential_backup
1236
+ if credential_backup.heal(realm_s, [name]):
1237
+ # The restore may have moved the value between backends.
1238
+ entry = _read_entries(owning, project_path).get(name) or entry
1239
+ raw = _read_stored(entry, owning, project_path, realm_s, name)
1240
+ return raw
1241
+
1242
+
1243
+ def _read_stored(entry: dict, scope: str, project_path: str, realm_s: str,
1244
+ name: str) -> Optional[str]:
1223
1245
  if entry.get("storage") == "file":
1224
- return _file_get(owning, project_path, realm_s, name)
1246
+ return _file_get(scope, project_path, realm_s, name)
1225
1247
  try:
1226
1248
  return _keyring_module().get_password(KEYRING_SERVICE, _account(realm_s, name))
1227
1249
  except Exception:
@@ -31,6 +31,13 @@ DEFAULT_MIN_SCORE_OTHER = 0.55
31
31
  # A redundant build is worth far less than a responsive server, so we give up
32
32
  # and degrade rather than block. See _acquire_build_lock().
33
33
  _BUILD_LOCK_WAIT_SECONDS = 30.0
34
+ # The embedding model reads about 2k tokens, so text past this changes no
35
+ # vector; chromadb stores each document several times (row, full-text index,
36
+ # write queue), so every stored character costs several on disk.
37
+ _EMBED_MAX_CHARS = 8000
38
+ # A file this large is data, not something to find by meaning. The lexical
39
+ # index still covers it.
40
+ _EMBED_MAX_FILE_TOKENS = 250_000
34
41
 
35
42
  # ── Store safety (issue #180) ─────────────────────────────
36
43
  # A damaged HNSW segment does not just fail to load. chromadb's loader
@@ -860,12 +867,20 @@ class EmbeddingIndex:
860
867
  # Remove old chunks for this file before re-embedding
861
868
  self._remove_file_chunks(doc_id)
862
869
 
870
+ doc = (getattr(code_index, "documents", None) or {}).get(doc_id) or {}
871
+ if doc.get("tokens", 0) > _EMBED_MAX_FILE_TOKENS:
872
+ self._file_hashes[doc_id] = new_hash
873
+ files_skipped += 1
874
+ chunks_skipped += len(file_chunks)
875
+ _report()
876
+ continue
877
+
863
878
  # Batch embed
864
879
  batch_ids = []
865
880
  batch_texts = []
866
881
  batch_metas = []
867
882
  for chunk_id, chunk in file_chunks:
868
- text = chunk.get("content", "").strip()
883
+ text = chunk.get("content", "").strip()[:_EMBED_MAX_CHARS]
869
884
  if not text or len(text) < 20:
870
885
  chunks_skipped += 1
871
886
  continue
services/indexer.py CHANGED
@@ -103,6 +103,23 @@ DEFAULT_CODE_EXTS = frozenset({
103
103
  # stands in for it.
104
104
  _WINDOW_MAX_TOKENS = 400
105
105
 
106
+ # A chunk is a slice of whole lines, so sections sharing one line (every key
107
+ # of a minified JSON file) each carry the entire line. Nesting repeats text
108
+ # legitimately, so the bound is a ratio plus a floor small files never reach;
109
+ # past it the fallback chunker, which covers the file once, takes over.
110
+ _CHUNK_MAX_AMPLIFICATION = 4
111
+ _CHUNK_AMPLIFICATION_FLOOR = 64 * 1024
112
+ # A line longer than this is minified or data; the fallback then cuts the
113
+ # file into character windows, because 40 such lines are not a chunk.
114
+ _LONG_LINE_CHARS = 2000
115
+ _CHAR_WINDOW = 4000
116
+
117
+
118
+ def _amplified(chunks: list, content: str) -> bool:
119
+ """True when the chunks hold far more text than the file they came from."""
120
+ total = sum(len(c.get("content") or "") for c in chunks)
121
+ return total > _CHUNK_MAX_AMPLIFICATION * len(content) + _CHUNK_AMPLIFICATION_FLOOR
122
+
106
123
 
107
124
  class CodeIndex:
108
125
  """TF-IDF based code search index with structural awareness."""
@@ -790,7 +807,7 @@ class CodeIndex:
790
807
  ast_sections = extract_sections_ast(content, ext)
791
808
  if ast_sections:
792
809
  ast_chunks = self._chunk_by_ast(ast_sections, lines, doc_id)
793
- if ast_chunks:
810
+ if ast_chunks and not _amplified(ast_chunks, content):
794
811
  return ast_chunks
795
812
  except Exception:
796
813
  pass
@@ -800,11 +817,43 @@ class CodeIndex:
800
817
  chunks = self._chunk_by_indent(lines, doc_id, ext)
801
818
  elif ext in ('.js', '.ts', '.tsx', '.jsx'):
802
819
  chunks = self._chunk_by_braces(lines, doc_id, ext)
820
+ if chunks and _amplified(chunks, content):
821
+ chunks = []
803
822
 
804
- # Fallback: fixed-size chunks with overlap
823
+ # Fallback: fixed-size chunks with overlap, or character windows when
824
+ # the lines are too long for a line count to bound a chunk.
805
825
  if not chunks:
806
- chunks = self._chunk_fixed(lines, doc_id, chunk_size=40, overlap=10)
826
+ if any(len(line) > _LONG_LINE_CHARS for line in lines):
827
+ chunks = self._chunk_by_chars(content, doc_id)
828
+ else:
829
+ chunks = self._chunk_fixed(lines, doc_id, chunk_size=40, overlap=10)
830
+
831
+ return chunks
807
832
 
833
+ def _chunk_by_chars(self, content: str, doc_id: str,
834
+ window: int = _CHAR_WINDOW) -> list:
835
+ """Cut a minified or data file into adjacent character windows.
836
+
837
+ No overlap, so the chunks hold the file exactly once. Line numbers are
838
+ 0-indexed like the other chunkers and name the lines a window touches.
839
+ """
840
+ chunks = []
841
+ line = 0
842
+ for start in range(0, len(content), window):
843
+ piece = content[start:start + window]
844
+ newlines = piece.count('\n')
845
+ if piece.strip():
846
+ chunks.append({
847
+ "id": f"{doc_id}::chars_{start}",
848
+ "doc_id": doc_id,
849
+ "content": piece,
850
+ "tokens": count_tokens(piece),
851
+ "type": "block",
852
+ "name": None,
853
+ "line_start": line,
854
+ "line_end": line + newlines - (1 if piece.endswith('\n') and newlines else 0),
855
+ })
856
+ line += newlines
808
857
  return chunks
809
858
 
810
859
  def _chunk_by_ast(self, sections: list, lines: list, doc_id: str) -> list: