code-context-control 2.159.1__py3-none-any.whl → 2.160.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/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.160.0"
100
100
 
101
101
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
102
102
  AGENT_MATCHER = "Agent|Task"
@@ -5172,12 +5172,19 @@ def _ensure_global_claude_md() -> None:
5172
5172
  - Creates the file if it doesn't exist.
5173
5173
  - Updates the C3 section if present but outdated.
5174
5174
  - Preserves any user-written content outside the C3 section.
5175
+
5176
+ Every install-mcp calls this, and the hub's batch update runs several
5177
+ installs at once. An unchanged file is left alone, and a changed one is
5178
+ replaced atomically: a plain truncate-and-write let a concurrent run read
5179
+ the file empty and write back the C3 block alone, dropping the user's text.
5175
5180
  """
5181
+ from services.atomic_json import write_text_atomic
5182
+
5176
5183
  global_md = Path.home() / ".claude" / "CLAUDE.md"
5177
5184
  global_md.parent.mkdir(parents=True, exist_ok=True)
5178
5185
 
5179
5186
  if not global_md.exists():
5180
- global_md.write_text(_GLOBAL_CLAUDE_MD_CONTENT, encoding="utf-8")
5187
+ write_text_atomic(global_md, _GLOBAL_CLAUDE_MD_CONTENT)
5181
5188
  print(f"Wrote {global_md} (global C3 enforcement)")
5182
5189
  return
5183
5190
 
@@ -5193,7 +5200,11 @@ def _ensure_global_claude_md() -> None:
5193
5200
 
5194
5201
  # Markers already present → surgical, marker-bounded replacement.
5195
5202
  if C3_BLOCK_BEGIN in existing:
5196
- global_md.write_text(merge_c3_block(existing, wrapped), encoding="utf-8")
5203
+ merged = merge_c3_block(existing, wrapped)
5204
+ if merged == existing:
5205
+ print(f"Kept {global_md} (C3 enforcement up to date)")
5206
+ return
5207
+ write_text_atomic(global_md, merged)
5197
5208
  print(f"Updated {global_md} (refreshed C3 enforcement)")
5198
5209
  return
5199
5210
 
@@ -5217,13 +5228,13 @@ def _ensure_global_claude_md() -> None:
5217
5228
  before = existing[:start].rstrip()
5218
5229
  after = existing[end:].lstrip()
5219
5230
  parts = [p for p in (before, wrapped, after) if p]
5220
- global_md.write_text("\n\n".join(parts) + "\n", encoding="utf-8")
5231
+ write_text_atomic(global_md, "\n\n".join(parts) + "\n")
5221
5232
  print(f"Updated {global_md} (migrated C3 enforcement to markers)")
5222
5233
  return
5223
5234
 
5224
5235
  # User has their own CLAUDE.md with no C3 content — append the marked block.
5225
5236
  merged = existing.rstrip() + "\n\n" + wrapped + "\n"
5226
- global_md.write_text(merged, encoding="utf-8")
5237
+ write_text_atomic(global_md, merged)
5227
5238
  print(f"Updated {global_md} (appended C3 enforcement)")
5228
5239
 
5229
5240
 
cli/hub_server.py CHANGED
@@ -526,6 +526,11 @@ def api_hub_config_set():
526
526
  cfg["runtime_cache_size"] = max(1, int(data["runtime_cache_size"]))
527
527
  except (ValueError, TypeError):
528
528
  return jsonify({"error": "runtime_cache_size must be an integer"}), 400
529
+ if "update_workers" in data:
530
+ try:
531
+ cfg["update_workers"] = max(1, min(int(data["update_workers"]), _UPDATE_WORKERS_MAX))
532
+ except (ValueError, TypeError):
533
+ return jsonify({"error": "update_workers must be an integer"}), 400
529
534
  _write_hub_config(cfg)
530
535
  return jsonify({"saved": True, "config": cfg})
531
536
 
@@ -1246,12 +1251,90 @@ def api_run_component():
1246
1251
  return jsonify({"error": str(e), "success": False}), 500
1247
1252
 
1248
1253
 
1254
+ # A first embedding build on a large project takes minutes, far past the
1255
+ # _run_c3 default.
1256
+ _UPDATE_TIMEOUT_S = 600
1257
+ _UPDATE_WORKERS_DEFAULT = 3
1258
+ _UPDATE_WORKERS_MAX = 8
1259
+
1260
+
1261
+ def _update_workers() -> int:
1262
+ """Projects updated at once: hub config ``update_workers``, clamped to 1-8."""
1263
+ try:
1264
+ n = int(_read_hub_config().get("update_workers") or _UPDATE_WORKERS_DEFAULT)
1265
+ except (ValueError, TypeError):
1266
+ n = _UPDATE_WORKERS_DEFAULT
1267
+ return max(1, min(n, _UPDATE_WORKERS_MAX))
1268
+
1269
+
1270
+ def _run_pooled(items: list, run_one, state: dict, lock, workers: int) -> None:
1271
+ """Run ``run_one(item) -> row`` over ``items`` on up to ``workers`` threads.
1272
+
1273
+ Records each row in ``state["results"]`` as it finishes and keeps the
1274
+ paths being worked on in ``state["in_progress"]``. Items not yet started
1275
+ when ``state["cancelled"]`` is set are skipped; running ones finish.
1276
+ ``run_one`` must return a row rather than raise.
1277
+ """
1278
+ from concurrent.futures import ThreadPoolExecutor
1279
+
1280
+ def task(index, item):
1281
+ path = item.get("path")
1282
+ with lock:
1283
+ if state["cancelled"]:
1284
+ return
1285
+ state["in_progress"].append(path)
1286
+ state["current"] = item.get("name") or path
1287
+ state["current_index"] = index
1288
+ t0 = time.time()
1289
+ row = run_one(item)
1290
+ row.setdefault("elapsed_ms", int((time.time() - t0) * 1000))
1291
+ with lock:
1292
+ state["results"].append(row)
1293
+ state["in_progress"].remove(path)
1294
+ if not state["in_progress"]:
1295
+ state["current"] = None
1296
+
1297
+ with ThreadPoolExecutor(max_workers=max(1, workers),
1298
+ thread_name_prefix="c3-hub-update") as pool:
1299
+ list(pool.map(task, range(len(items)), items))
1300
+
1301
+
1302
+ def _dedupe_by_path(items: list) -> list:
1303
+ seen, out = set(), []
1304
+ for item in items:
1305
+ key = os.path.normcase(os.path.normpath(str(item.get("path") or "")))
1306
+ if key and key not in seen:
1307
+ seen.add(key)
1308
+ out.append(item)
1309
+ return out
1310
+
1311
+
1312
+ def _update_project_row(p: dict) -> dict:
1313
+ """Run ``c3 init --force`` for one project and return its result row."""
1314
+ path = p["path"]
1315
+ row = {"path": path, "name": p.get("name")}
1316
+ if not Path(path).is_dir():
1317
+ row.update(success=False, skipped=True, output="Project folder not found.",
1318
+ returncode=None)
1319
+ return row
1320
+ args = ["init", path, "--force"]
1321
+ ide = p.get("ide")
1322
+ if ide and ide not in ("unknown", "auto"):
1323
+ args += ["--ide", ide]
1324
+ res = _run_c3(args, timeout=_UPDATE_TIMEOUT_S)
1325
+ row.update(success=res.get("success"), output=res.get("output"),
1326
+ returncode=res.get("returncode"))
1327
+ return row
1328
+
1329
+
1249
1330
  _batch_state = {
1250
1331
  "running": False,
1251
1332
  "cancelled": False,
1252
1333
  "results": [],
1253
1334
  "current": None,
1254
1335
  "current_index": 0,
1336
+ "in_progress": [],
1337
+ "workers": 1,
1255
1338
  "total": 0,
1256
1339
  "done": False,
1257
1340
  "error": None,
@@ -1259,37 +1342,19 @@ _batch_state = {
1259
1342
  _batch_lock = threading.Lock()
1260
1343
 
1261
1344
 
1262
- def _batch_worker(projects):
1345
+ def _batch_worker(projects, workers: int = 1):
1263
1346
  """Run batch init in background thread, updating _batch_state."""
1264
- global _batch_state
1265
- for i, p in enumerate(projects):
1347
+ try:
1348
+ _run_pooled(projects, _update_project_row, _batch_state, _batch_lock, workers)
1349
+ except Exception as e:
1266
1350
  with _batch_lock:
1267
- if _batch_state["cancelled"]:
1268
- break
1269
- _batch_state["current"] = p.get("name") or p["path"]
1270
- _batch_state["current_index"] = i
1271
-
1272
- path = p["path"]
1273
- args = ["init", path, "--force"]
1274
- ide = p.get("ide")
1275
- if ide and ide != "unknown":
1276
- args += ["--ide", ide]
1277
-
1278
- res = _run_c3(args)
1279
- result = {
1280
- "path": path,
1281
- "name": p.get("name"),
1282
- "success": res.get("success"),
1283
- "output": res.get("output"),
1284
- "returncode": res.get("returncode"),
1285
- }
1351
+ _batch_state["error"] = str(e)
1352
+ finally:
1286
1353
  with _batch_lock:
1287
- _batch_state["results"].append(result)
1288
-
1289
- with _batch_lock:
1290
- _batch_state["running"] = False
1291
- _batch_state["done"] = True
1292
- _batch_state["current"] = None
1354
+ _batch_state["running"] = False
1355
+ _batch_state["done"] = True
1356
+ _batch_state["current"] = None
1357
+ _batch_state["in_progress"] = []
1293
1358
 
1294
1359
 
1295
1360
  @app.route("/api/projects/run-init/batch", methods=["POST"])
@@ -1301,9 +1366,10 @@ def api_run_init_batch():
1301
1366
  return jsonify({"error": "Batch update already in progress"}), 409
1302
1367
  try:
1303
1368
  data = request.get_json(force=True) or {}
1304
- projects = data.get("projects") or _pm().list_projects()
1369
+ projects = _dedupe_by_path(data.get("projects") or _pm().list_projects())
1305
1370
  if not projects:
1306
1371
  return jsonify({"error": "No projects to update"}), 400
1372
+ workers = _update_workers()
1307
1373
  with _batch_lock:
1308
1374
  _batch_state = {
1309
1375
  "running": True,
@@ -1311,13 +1377,15 @@ def api_run_init_batch():
1311
1377
  "results": [],
1312
1378
  "current": None,
1313
1379
  "current_index": 0,
1380
+ "in_progress": [],
1381
+ "workers": workers,
1314
1382
  "total": len(projects),
1315
1383
  "done": False,
1316
1384
  "error": None,
1317
1385
  }
1318
- t = threading.Thread(target=_batch_worker, args=(projects,), daemon=True)
1386
+ t = threading.Thread(target=_batch_worker, args=(projects, workers), daemon=True)
1319
1387
  t.start()
1320
- return jsonify({"started": True, "total": len(projects)})
1388
+ return jsonify({"started": True, "total": len(projects), "workers": workers})
1321
1389
  except Exception as e:
1322
1390
  return jsonify({"error": str(e)}), 500
1323
1391
 
@@ -1326,7 +1394,10 @@ def api_run_init_batch():
1326
1394
  def api_batch_status():
1327
1395
  """Return current batch update state for polling."""
1328
1396
  with _batch_lock:
1329
- return jsonify(dict(_batch_state))
1397
+ snap = dict(_batch_state)
1398
+ snap["results"] = list(snap.get("results") or [])
1399
+ snap["in_progress"] = list(snap.get("in_progress") or [])
1400
+ return jsonify(snap)
1330
1401
 
1331
1402
 
1332
1403
  @app.route("/api/projects/run-init/batch/cancel", methods=["POST"])
@@ -1695,59 +1766,65 @@ def api_subprojects_reconcile():
1695
1766
 
1696
1767
  _sub_cascade_state = {
1697
1768
  "running": False, "cancelled": False, "results": [],
1698
- "current": None, "current_index": 0, "total": 0,
1699
- "done": False, "error": None, "op": None, "parent": None,
1769
+ "current": None, "current_index": 0, "in_progress": [], "workers": 1,
1770
+ "total": 0, "done": False, "error": None, "op": None, "parent": None,
1700
1771
  }
1701
1772
  _sub_cascade_lock = threading.Lock()
1702
1773
 
1703
1774
 
1704
- def _sub_cascade_worker(op: str, targets: list):
1705
- """Per-child cascade in a background thread (progress + cancel like batch init)."""
1706
- global _sub_cascade_state
1707
- for i, child in enumerate(targets):
1775
+ def _sub_cascade_row(op: str, child: dict) -> dict:
1776
+ path = child.get("path")
1777
+ row = {"path": path, "name": child.get("name"), "success": False, "output": ""}
1778
+ try:
1779
+ if child.get("status") == "missing_folder":
1780
+ row["output"] = "missing_folder"
1781
+ elif child.get("status") == "missing_c3" and op != "update":
1782
+ row["output"] = "missing_c3"
1783
+ elif op == "update":
1784
+ res = _run_c3(["init", path, "--force"], timeout=_UPDATE_TIMEOUT_S)
1785
+ row["success"] = bool(res.get("success"))
1786
+ row["output"] = res.get("output", "")
1787
+ elif op == "reindex":
1788
+ from services.doc_index import DocIndex
1789
+ from services.indexer import CodeIndex
1790
+ r = CodeIndex(path).build_index()
1791
+ try:
1792
+ DocIndex(path).build()
1793
+ except Exception:
1794
+ pass
1795
+ row["success"] = True
1796
+ row["output"] = (f"{r.get('files_indexed', 0)} files, "
1797
+ f"{r.get('chunks_created', 0)} chunks")
1798
+ elif op == "health":
1799
+ from cli.c3 import _check_c3_health
1800
+ info = _check_c3_health(path)
1801
+ row["success"] = bool(info.get("healthy"))
1802
+ row["output"] = "healthy" if row["success"] else "; ".join(info.get("issues", []))
1803
+ except Exception as e:
1804
+ row["output"] = str(e)
1805
+ return row
1806
+
1807
+
1808
+ def _sub_cascade_worker(op: str, targets: list, workers: int = 1):
1809
+ """Per-child cascade in a background thread (progress + cancel like batch init).
1810
+
1811
+ Only ``update`` runs in subprocesses, so only it uses more than one worker;
1812
+ reindex and health build indexes inside the hub process.
1813
+ """
1814
+ try:
1815
+ _run_pooled(targets, lambda child: _sub_cascade_row(op, child),
1816
+ _sub_cascade_state, _sub_cascade_lock,
1817
+ workers if op == "update" else 1)
1818
+ except Exception as e:
1708
1819
  with _sub_cascade_lock:
1709
- if _sub_cascade_state["cancelled"]:
1710
- break
1711
- _sub_cascade_state["current"] = child.get("name") or child.get("path")
1712
- _sub_cascade_state["current_index"] = i
1713
- path = child.get("path")
1714
- t0 = time.time()
1715
- row = {"path": path, "name": child.get("name"), "success": False, "output": ""}
1716
- try:
1717
- if child.get("status") == "missing_folder":
1718
- row["output"] = "missing_folder"
1719
- elif child.get("status") == "missing_c3" and op != "update":
1720
- row["output"] = "missing_c3"
1721
- elif op == "update":
1722
- res = _run_c3(["init", path, "--force"], timeout=600)
1723
- row["success"] = bool(res.get("success"))
1724
- row["output"] = res.get("output", "")
1725
- elif op == "reindex":
1726
- from services.doc_index import DocIndex
1727
- from services.indexer import CodeIndex
1728
- r = CodeIndex(path).build_index()
1729
- try:
1730
- DocIndex(path).build()
1731
- except Exception:
1732
- pass
1733
- row["success"] = True
1734
- row["output"] = (f"{r.get('files_indexed', 0)} files, "
1735
- f"{r.get('chunks_created', 0)} chunks")
1736
- elif op == "health":
1737
- from cli.c3 import _check_c3_health
1738
- info = _check_c3_health(path)
1739
- row["success"] = bool(info.get("healthy"))
1740
- row["output"] = "healthy" if row["success"] else "; ".join(info.get("issues", []))
1741
- except Exception as e:
1742
- row["output"] = str(e)
1743
- row["elapsed_ms"] = int((time.time() - t0) * 1000)
1820
+ _sub_cascade_state["error"] = str(e)
1821
+ finally:
1744
1822
  with _sub_cascade_lock:
1745
- _sub_cascade_state["results"].append(row)
1746
- with _sub_cascade_lock:
1747
- _sub_cascade_state["running"] = False
1748
- _sub_cascade_state["done"] = True
1749
- _sub_cascade_state["current"] = None
1750
- _invalidate_subproject_links()
1823
+ _sub_cascade_state["running"] = False
1824
+ _sub_cascade_state["done"] = True
1825
+ _sub_cascade_state["current"] = None
1826
+ _sub_cascade_state["in_progress"] = []
1827
+ _invalidate_subproject_links()
1751
1828
 
1752
1829
 
1753
1830
  @app.route("/api/projects/subprojects/cascade", methods=["POST"])
@@ -1777,19 +1854,23 @@ def api_subprojects_cascade():
1777
1854
  targets = [t for t in listed if t not in skipped]
1778
1855
  if data.get("include_parent"):
1779
1856
  targets.append({"name": "(parent)", "path": sm.parent_path, "status": "ok"})
1857
+ targets = _dedupe_by_path(targets)
1858
+ workers = _update_workers() if op == "update" else 1
1780
1859
  if not targets:
1781
1860
  return jsonify({"error": "No cascade-eligible sub-projects"
1782
1861
  + (f" ({len(skipped)} skipped)" if skipped else "")}), 400
1783
1862
  with _sub_cascade_lock:
1784
1863
  _sub_cascade_state = {
1785
1864
  "running": True, "cancelled": False, "results": [],
1786
- "current": None, "current_index": 0, "total": len(targets),
1865
+ "current": None, "current_index": 0, "in_progress": [],
1866
+ "workers": workers, "total": len(targets),
1787
1867
  "done": False, "error": None, "op": op, "parent": sm.parent_path,
1788
1868
  }
1789
- t = threading.Thread(target=_sub_cascade_worker, args=(op, targets), daemon=True)
1869
+ t = threading.Thread(target=_sub_cascade_worker, args=(op, targets, workers),
1870
+ daemon=True)
1790
1871
  t.start()
1791
1872
  return jsonify({"started": True, "total": len(targets), "op": op,
1792
- "skipped": len(skipped)})
1873
+ "skipped": len(skipped), "workers": workers})
1793
1874
  except ValueError as e:
1794
1875
  return jsonify({"error": str(e)}), 404
1795
1876
  except Exception as e:
@@ -1799,7 +1880,10 @@ def api_subprojects_cascade():
1799
1880
  @app.route("/api/projects/subprojects/cascade/status", methods=["GET"])
1800
1881
  def api_subprojects_cascade_status():
1801
1882
  with _sub_cascade_lock:
1802
- return jsonify(dict(_sub_cascade_state))
1883
+ snap = dict(_sub_cascade_state)
1884
+ snap["results"] = list(snap.get("results") or [])
1885
+ snap["in_progress"] = list(snap.get("in_progress") or [])
1886
+ return jsonify(snap)
1803
1887
 
1804
1888
 
1805
1889
  @app.route("/api/projects/subprojects/cascade/cancel", methods=["POST"])
@@ -1325,12 +1325,14 @@ function BatchUpdateModal({ projects, onClose, onChanged }) {
1325
1325
  const total = (state && state.total) || (targets ? targets.length : 0) || 1;
1326
1326
  const findResult = (p) => results.find(r => (r.path || '').toLowerCase() === (p.path || '').toLowerCase());
1327
1327
  const okCount = results.filter(r => r.success).length;
1328
- const failCount = results.filter(r => !r.success).length;
1328
+ const skipCount = results.filter(r => r.skipped).length;
1329
+ const failCount = results.filter(r => !r.success && !r.skipped).length;
1330
+ const inProgress = ((state && state.in_progress) || []).map(x => (x || '').toLowerCase());
1329
1331
 
1330
- const rowStatus = (p, idx) => {
1332
+ const rowStatus = (p) => {
1331
1333
  const r = findResult(p);
1332
- if (r) return r.success ? 'done' : 'failed';
1333
- if (phase === 'running' && state && state.running && idx === (state.current_index || 0)) return 'running';
1334
+ if (r) return r.success ? 'done' : r.skipped ? 'skipped' : 'failed';
1335
+ if (phase === 'running' && state && state.running && inProgress.includes((p.path || '').toLowerCase())) return 'running';
1334
1336
  return 'pending';
1335
1337
  };
1336
1338
 
@@ -1353,8 +1355,8 @@ function BatchUpdateModal({ projects, onClose, onChanged }) {
1353
1355
  {!targets.length && (
1354
1356
  <div style={{ padding: 14, fontSize: 12, color: T.textDim }}>No projects registered.</div>
1355
1357
  )}
1356
- {targets.map((p, idx) => {
1357
- const st = rowStatus(p, idx);
1358
+ {targets.map((p) => {
1359
+ const st = rowStatus(p);
1358
1360
  const r = findResult(p);
1359
1361
  return (
1360
1362
  <div key={p.path} style={{ padding: '7px 10px', borderBottom: `1px solid ${T.border}40` }}>
@@ -1362,7 +1364,7 @@ function BatchUpdateModal({ projects, onClose, onChanged }) {
1362
1364
  {st === 'done' && <I name="check" size={13} color={T.accent} />}
1363
1365
  {st === 'failed' && <I name="xCircle" size={13} color={T.error} />}
1364
1366
  {st === 'running' && <GlowDot color={T.warn} />}
1365
- {st === 'pending' && <GlowDot color={T.textDim} />}
1367
+ {(st === 'pending' || st === 'skipped') && <GlowDot color={T.textDim} />}
1366
1368
  <span style={{ fontSize: 13, color: T.text, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
1367
1369
  {p.name || p.path}
1368
1370
  </span>
@@ -1372,8 +1374,8 @@ function BatchUpdateModal({ projects, onClose, onChanged }) {
1372
1374
  color: st === 'done' ? T.accent : st === 'failed' ? T.error : st === 'running' ? T.warn : T.textDim,
1373
1375
  }}>{st === 'running' ? 'running…' : st}</span>
1374
1376
  </div>
1375
- {st === 'failed' && r && r.output && (
1376
- <div className="mono" style={{ fontSize: 11, color: T.error, marginTop: 3, paddingLeft: 21, whiteSpace: 'pre-wrap' }}>
1377
+ {(st === 'failed' || st === 'skipped') && r && r.output && (
1378
+ <div className="mono" style={{ fontSize: 11, color: st === 'failed' ? T.error : T.textDim, marginTop: 3, paddingLeft: 21, whiteSpace: 'pre-wrap' }}>
1377
1379
  {r.output.split('\n').filter(l => l.trim()).slice(-2).join('\n')}
1378
1380
  </div>
1379
1381
  )}
@@ -1386,14 +1388,17 @@ function BatchUpdateModal({ projects, onClose, onChanged }) {
1386
1388
  {(phase === 'running' || phase === 'done') && (
1387
1389
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
1388
1390
  <ProgressBar value={results.length} max={total} />
1389
- <span className="mono" style={{ fontSize: 11, color: T.textMuted }}>{results.length}/{total}</span>
1391
+ <span className="mono" style={{ fontSize: 11, color: T.textMuted }}>
1392
+ {results.length}/{total}{state && state.workers > 1 ? ` · ${state.workers} at once` : ''}
1393
+ </span>
1390
1394
  </div>
1391
1395
  )}
1392
1396
 
1393
1397
  {phase === 'done' && (
1394
1398
  <div style={{ fontSize: 12, marginTop: 10, color: failCount ? T.error : T.accent }}>
1395
1399
  Batch {state && state.cancelled ? 'cancelled' : 'finished'} — {okCount} succeeded, {failCount} failed
1396
- {state && state.cancelled ? ` (${Math.max(0, total - results.length)} skipped)` : ''}.
1400
+ {skipCount ? `, ${skipCount} skipped (folder missing)` : ''}
1401
+ {state && state.cancelled ? ` (${Math.max(0, total - results.length)} not started)` : ''}.
1397
1402
  </div>
1398
1403
  )}
1399
1404
 
@@ -1,6 +1,6 @@
1
1
  // ─── Hub settings modal ─────────────────────────────────────────
2
2
  // Config: GET/POST /api/hub/config {port, auto_open_browser, oracle_url,
3
- // runtime_cache_size}. Hub service: GET /api/hub/service + POST
3
+ // runtime_cache_size, update_workers}. Hub service: GET /api/hub/service + POST
4
4
  // /api/hub/service/install|uninstall|start|stop. Restart: POST /api/hub/restart.
5
5
  // Oracle service: GET /api/oracle/service + POST
6
6
  // /api/oracle/service/install|uninstall|start|stop — runs `c3 oracle serve`
@@ -16,6 +16,7 @@ function SettingsModal({ onClose, onChanged }) {
16
16
  const [oracleUrl, setOracleUrl] = useState('');
17
17
  const [agentCmd, setAgentCmd] = useState(''); // ide_cmds['claude-code']
18
18
  const [cacheSize, setCacheSize] = useState(8);
19
+ const [updateWorkers, setUpdateWorkers] = useState(3);
19
20
  const [saving, setSaving] = useState(false);
20
21
  const [svc, setSvc] = useState(null); // hub: {installed, running, method, port, log_path} | {error}
21
22
  const [svcBusy, setSvcBusy] = useState('');
@@ -54,6 +55,7 @@ function SettingsModal({ onClose, onChanged }) {
54
55
  setOracleUrl(d.oracle_url || '');
55
56
  setAgentCmd(((d.ide_cmds || {})['claude-code']) || '');
56
57
  setCacheSize(d.runtime_cache_size || 8);
58
+ setUpdateWorkers(d.update_workers || 3);
57
59
  } catch {
58
60
  notify('Could not load hub config', 'err');
59
61
  }
@@ -70,6 +72,7 @@ function SettingsModal({ onClose, onChanged }) {
70
72
  return;
71
73
  }
72
74
  const cache = Math.max(1, parseInt(cacheSize, 10) || 8);
75
+ const workers = Math.min(8, Math.max(1, parseInt(updateWorkers, 10) || 3));
73
76
  setSaving(true);
74
77
  try {
75
78
  // Blank restores the stock `claude`; other IDE overrides are left alone.
@@ -79,7 +82,7 @@ function SettingsModal({ onClose, onChanged }) {
79
82
  await api.post('/api/hub/config', {
80
83
  port: portVal, auto_open_browser: autoBrowser,
81
84
  oracle_url: oracleUrl.trim(), runtime_cache_size: cache,
82
- ide_cmds: ideCmds,
85
+ update_workers: workers, ide_cmds: ideCmds,
83
86
  });
84
87
  const portChanged = cfg && portVal !== cfg.port;
85
88
  notify(portChanged
@@ -229,6 +232,10 @@ function SettingsModal({ onClose, onChanged }) {
229
232
  <input type="number" value={cacheSize} onChange={e => setCacheSize(e.target.value)}
230
233
  min={1} className="mono" style={inputStyle(110)} />
231
234
  ), 'Max project runtimes kept warm for drill-in and global search.')}
235
+ {fieldRow('Parallel updates', (
236
+ <input type="number" value={updateWorkers} onChange={e => setUpdateWorkers(e.target.value)}
237
+ min={1} max={8} className="mono" style={inputStyle(110)} />
238
+ ), 'Projects "Update all" and sub-project cascades update at once (1-8). Each one is a separate c3 process.')}
232
239
  {fieldRow('Agent command', (
233
240
  <input value={agentCmd} onChange={e => setAgentCmd(e.target.value)}
234
241
  placeholder="claude" className="mono" style={inputStyle(220)} />
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 ""