code-context-control 2.64.0__py3-none-any.whl → 2.65.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
@@ -92,7 +92,7 @@ console = Console() if HAS_RICH else None
92
92
  # Config
93
93
  CONFIG_DIR = ".c3"
94
94
  CONFIG_FILE = ".c3/config.json"
95
- __version__ = "2.64.0"
95
+ __version__ = "2.65.0"
96
96
 
97
97
 
98
98
  def _compress_file_cli(compressor, path, mode="smart", **kw):
@@ -257,7 +257,8 @@ _C3_MCP_ALLOW = [
257
257
  "mcp__c3__c3_session", "mcp__c3__c3_status", "mcp__c3__c3_filter",
258
258
  "mcp__c3__c3_memory", "mcp__c3__c3_validate", "mcp__c3__c3_edit",
259
259
  "mcp__c3__c3_agent", "mcp__c3__c3_delegate", "mcp__c3__c3_edits",
260
- "mcp__c3__c3_impact", "mcp__c3__c3_shell", "mcp__c3__c3_bitbucket",
260
+ "mcp__c3__c3_impact", "mcp__c3__c3_locks", "mcp__c3__c3_shell",
261
+ "mcp__c3__c3_bitbucket",
261
262
  "mcp__c3__c3_jira", "mcp__c3__c3_credentials",
262
263
  "mcp__c3__c3_project", "mcp__c3__c3_task", "mcp__c3__c3_artifacts",
263
264
  ]
@@ -5208,6 +5209,7 @@ def cmd_install_mcp(args):
5208
5209
  "mcp__c3__c3_edit",
5209
5210
  "mcp__c3__c3_edits",
5210
5211
  "mcp__c3__c3_impact",
5212
+ "mcp__c3__c3_locks",
5211
5213
  "mcp__c3__c3_status",
5212
5214
  "mcp__c3__c3_delegate",
5213
5215
  "mcp__c3__c3_session",
@@ -5923,12 +5925,90 @@ def _creds_cmd_import(args, project_path: str) -> None:
5923
5925
  "(use --overwrite to replace)")
5924
5926
 
5925
5927
 
5928
+ def cmd_locks(args):
5929
+ """Agent Locks — human surface. force-release lives here, never in c3_locks."""
5930
+ from services import agent_locks as al
5931
+
5932
+ sub = getattr(args, "locks_cmd", None) or "list"
5933
+ project_path = getattr(args, "project_path", ".") or "."
5934
+ store = al.store_for(project_path)
5935
+ cfg = al.config(project_path)
5936
+
5937
+ if sub == "list":
5938
+ snap = store.snapshot()
5939
+ print(f"{snap['count']} active lease(s) — mode={cfg['mode']}, "
5940
+ f"enabled={cfg['enabled']}, fencing={snap['fencing']}")
5941
+ if not snap["locks"]:
5942
+ return
5943
+ print(f" {'file':<44} {'holder':<24} {'left':<8} intent")
5944
+ for row in snap["locks"]:
5945
+ left = int(max(0, row.get("expires_in_s", 0)))
5946
+ print(f" {row['relpath']:<44} {row['agent_id']:<24} "
5947
+ f"{left//60}m{left % 60:02d}s {row.get('intent', '')}")
5948
+ return
5949
+
5950
+ if sub == "release":
5951
+ res = store.release(session_id=args.session)
5952
+ print(f"Released {res['count']} lease(s)"
5953
+ + (f": {', '.join(res['released'])}" if res["released"] else ""))
5954
+ return
5955
+
5956
+ if sub == "force-release":
5957
+ res = store.force_release(args.file, by="cli", note=args.note)
5958
+ if not res.get("forced"):
5959
+ print(f"[error] {res.get('error')}: {res.get('reason', '')}")
5960
+ return
5961
+ _locks_audit(args.file, res, project_path, args.note)
5962
+ if res["was_locked"]:
5963
+ print(f"[OK] Broke the lease on {res['relpath']} "
5964
+ f"(was held by {res['previous_owner']}).")
5965
+ print(" The fencing token moved, so the old holder is stale "
5966
+ "even if it thinks it still holds it.")
5967
+ else:
5968
+ print(f"[=] {res['relpath']} was not locked; fencing bumped anyway.")
5969
+ return
5970
+
5971
+ if sub == "sweep":
5972
+ res = store.sweep()
5973
+ print(f"Swept {res['count']} expired lease(s)"
5974
+ + (f": {', '.join(res['expired'])}" if res["expired"] else ""))
5975
+ return
5976
+
5977
+ print("Usage: c3 locks {list,release,force-release,sweep}")
5978
+
5979
+
5980
+ def _locks_audit(target: str, res: dict, project_path: str, note: str) -> None:
5981
+ """Ledger + activity log for a human lease override. Failure-safe."""
5982
+ try:
5983
+ from services.activity_log import ActivityLog
5984
+ ActivityLog(project_path).log("lock_force_release", {
5985
+ "kind": "locks", "relpath": res.get("relpath"),
5986
+ "previous_owner": res.get("previous_owner"), "via": "cli",
5987
+ })
5988
+ except Exception:
5989
+ pass
5990
+ try:
5991
+ from services.edit_ledger import EditLedger
5992
+ EditLedger(project_path).log_edit(
5993
+ file=f"lock://{res.get('relpath', target)}",
5994
+ change_type="lock_force_release",
5995
+ summary=f"force-released lease on {res.get('relpath', target)}"
5996
+ + (f" — {note}" if note else ""),
5997
+ tags=["locks", "force_release"],
5998
+ detail={"kind": "locks", "previous_owner": res.get("previous_owner"),
5999
+ "was_locked": res.get("was_locked"), "note": note},
6000
+ )
6001
+ except Exception:
6002
+ pass
6003
+
6004
+
5926
6005
  def cmd_access(args):
5927
6006
  """Access Guard rule management — human-only mutation surface (spec §1)."""
5928
6007
  sub = getattr(args, "access_cmd", None)
5929
6008
  if not sub:
5930
- print("Usage: c3 access {list,add,remove,check,mask} [args]")
6009
+ print("Usage: c3 access {list,add,remove,check,mask,builtin} [args]")
5931
6010
  print(" c3 access mask {add,rm,status,activate,preview} [args]")
6011
+ print(" c3 access builtin {disable,enable} <glob>")
5932
6012
  return
5933
6013
 
5934
6014
  project_path = getattr(args, "project_path", ".") or "."
@@ -5943,6 +6023,8 @@ def cmd_access(args):
5943
6023
  _access_cmd_check(args, project_path)
5944
6024
  elif sub == "mask":
5945
6025
  _access_cmd_mask(args, project_path)
6026
+ elif sub == "builtin":
6027
+ _access_cmd_builtin(args, project_path)
5946
6028
  else:
5947
6029
  print(f"Unknown access subcommand: {sub}")
5948
6030
 
@@ -5998,6 +6080,21 @@ def _access_cmd_list(args, project_path: str) -> None:
5998
6080
  print(" [warn] access section invalid — scope fails closed "
5999
6081
  "(deny-all); fix config.json 'access' by hand")
6000
6082
  if scope == "builtin":
6083
+ off = sec.get("disabled") or []
6084
+ if off:
6085
+ print(" DISABLED by you (not enforced):")
6086
+ for glob in off:
6087
+ print(f" {'off':<10} {glob}")
6088
+ print(" re-enable: c3 access builtin enable <glob>")
6089
+ can = [g for g in (sec.get("disableable") or [])
6090
+ if access_guard._norm_builtin(g) not in set(off)]
6091
+ if can:
6092
+ print(" disableable (currently on): "
6093
+ + ", ".join(can))
6094
+ print(" disable: c3 access builtin disable <glob>")
6095
+ if sec.get("absolute"):
6096
+ print(" absolute (credential vault, cannot be disabled): "
6097
+ + ", ".join(sec["absolute"]))
6001
6098
  print(" spelling rules (deny by how a path is written, no glob):")
6002
6099
  for name, why in access_guard.SYNTHETIC_RULES:
6003
6100
  print(f" {name:<18} {why}")
@@ -6010,6 +6107,58 @@ def _access_cmd_list(args, project_path: str) -> None:
6010
6107
  print(access_guard.COVERAGE_MATRIX)
6011
6108
 
6012
6109
 
6110
+ def _access_cmd_builtin(args, project_path: str) -> None:
6111
+ """Switch a Tier-1 builtin off or back on. Human-only; always global scope.
6112
+
6113
+ Disabling asks for typed confirmation unless --yes: these guards are what
6114
+ stop an agent rewriting its own hooks, settings or git history, and the
6115
+ consequence deserves a beat of friction.
6116
+ """
6117
+ from services import access_guard
6118
+
6119
+ action = getattr(args, "builtin_cmd", None)
6120
+ glob = getattr(args, "glob", None)
6121
+ if action not in ("disable", "enable") or not glob:
6122
+ print("Usage: c3 access builtin {disable,enable} <glob>")
6123
+ print(" disableable: "
6124
+ + ", ".join(access_guard.DISABLEABLE_BUILTINS))
6125
+ return
6126
+
6127
+ disabling = action == "disable"
6128
+ if disabling and not getattr(args, "yes", False):
6129
+ print(f"About to STOP enforcing the builtin guard on: {glob}")
6130
+ print(" While off, any agent with C3 tools can write those paths.")
6131
+ if glob.endswith("settings*.json") or ".claude" in glob:
6132
+ print(" This is the file that configures the agent itself — hooks,")
6133
+ print(" permissions, model. An agent could rewrite its own rules.")
6134
+ reply = input("Type the glob again to confirm: ").strip()
6135
+ if reply != glob:
6136
+ print("[abort] Not confirmed; nothing changed.")
6137
+ return
6138
+
6139
+ try:
6140
+ result = access_guard.set_builtin_disabled(glob, disabling)
6141
+ except ValueError as exc:
6142
+ print(f"[error] {exc}")
6143
+ return
6144
+
6145
+ _access_audit(f"builtin_{action}", result["glob"], "builtin", "global",
6146
+ project_path)
6147
+ if not result["changed"]:
6148
+ state = "already disabled" if disabling else "already enforced"
6149
+ print(f"[=] {result['glob']} — {state}")
6150
+ return
6151
+ if disabling:
6152
+ print(f"[OK] Builtin '{result['glob']}' DISABLED (global scope).")
6153
+ print(" Re-enable with: c3 access builtin enable "
6154
+ f"{result['glob']}")
6155
+ else:
6156
+ print(f"[OK] Builtin '{result['glob']}' re-enforced.")
6157
+ if not result["attested"]:
6158
+ print(" [warn] keyring attestation could not be cleared; the "
6159
+ "builtin is enforced anyway (config entry removed).")
6160
+
6161
+
6013
6162
  def _access_cmd_add(args, project_path: str) -> None:
6014
6163
  from services import access_guard
6015
6164
 
@@ -7583,6 +7732,7 @@ def main():
7583
7732
  "jira": cmd_jira,
7584
7733
  "creds": cmd_creds,
7585
7734
  "access": cmd_access,
7735
+ "locks": cmd_locks,
7586
7736
  "oracle": cmd_oracle,
7587
7737
  "upgrade": cmd_upgrade,
7588
7738
  }
cli/commands/parser.py CHANGED
@@ -447,6 +447,30 @@ def build_parser(version: str, parse_cli_ide_arg):
447
447
  cr_import.add_argument("--overwrite", action="store_true", help="Replace entries already registered in the target scope")
448
448
  cr_import.add_argument("--path", dest="project_path", default=".", help="Project directory (default: current)")
449
449
 
450
+ # ── Agent Locks (docs/agent-locks.md) ───────────────────────────────
451
+ # force-release is human-only: it bumps the fencing counter so a holder
452
+ # that comes back is stale by construction. Agents get c3_locks instead,
453
+ # which deliberately has no force action.
454
+ p_locks = subparsers.add_parser(
455
+ "locks", help="Agent leases — see who holds which file, release a stuck one")
456
+ locks_subs = p_locks.add_subparsers(dest="locks_cmd")
457
+
458
+ lk_list = locks_subs.add_parser("list", help="Show active leases")
459
+ lk_list.add_argument("--path", dest="project_path", default=".")
460
+
461
+ lk_rel = locks_subs.add_parser("release", help="Release leases held by a session")
462
+ lk_rel.add_argument("--session", required=True, help="session_id to release")
463
+ lk_rel.add_argument("--path", dest="project_path", default=".")
464
+
465
+ lk_force = locks_subs.add_parser(
466
+ "force-release", help="Break one lease regardless of holder (audited)")
467
+ lk_force.add_argument("file", help="Project-relative path to unlock")
468
+ lk_force.add_argument("--note", default="", help="Why — recorded in the ledger")
469
+ lk_force.add_argument("--path", dest="project_path", default=".")
470
+
471
+ lk_sweep = locks_subs.add_parser("sweep", help="Drop expired leases now")
472
+ lk_sweep.add_argument("--path", dest="project_path", default=".")
473
+
450
474
  # ── Access Guard (v2.62.0) ──────────────────────────────────────────
451
475
  # Human-only mutation surface (frozen spec docs/access-guard.md §1):
452
476
  # rule changes happen here or in the UI tab, never via an agent tool.
@@ -483,6 +507,24 @@ def build_parser(version: str, parse_cli_ide_arg):
483
507
  help="Operation to evaluate (default: read)")
484
508
  ac_check.add_argument("--path", dest="project_path", default=".", help="Project directory (default: current)")
485
509
 
510
+ # ── Builtin opt-out (two-key) ───────────────────────────────────────
511
+ # Builtins are on by default. Switching one off needs a config entry AND
512
+ # a keyring attestation, so an agent that writes config.json alone still
513
+ # cannot loosen the guard. Global scope only — project scopes may only
514
+ # ever tighten. The credential-vault builtins are never disableable.
515
+ ac_builtin = access_subs.add_parser(
516
+ "builtin", help="Disable or re-enable a built-in guard (global, needs confirmation)")
517
+ builtin_subs = ac_builtin.add_subparsers(dest="builtin_cmd")
518
+ for _name, _help in (("disable", "Stop enforcing a built-in guard"),
519
+ ("enable", "Re-enforce a built-in guard")):
520
+ _p = builtin_subs.add_parser(_name, help=_help)
521
+ _p.add_argument("glob", help="One of: **/.env*, **/.c3/**, **/.claude/settings*.json, **/.git/**")
522
+ _p.add_argument("--path", dest="project_path", default=".",
523
+ help="Project directory used for the audit log (default: current)")
524
+ if _name == "disable":
525
+ _p.add_argument("--yes", action="store_true",
526
+ help="Skip the typed confirmation (scripts/CI)")
527
+
486
528
  # ── Mask Guard (v2.63.0, docs/mask-guard.md) ────────────────────────
487
529
  # Masking exposes a path but transforms what the agent sees. Rules are
488
530
  # human-only, like the rest of Access Guard.
cli/hub_server.py CHANGED
@@ -335,6 +335,7 @@ _HUB_JS_FILES = [
335
335
  "hub_ui/components/drill_panel.js",
336
336
  "hub_ui/components/drill_views.js",
337
337
  "hub_ui/components/hub_credentials.js",
338
+ "hub_ui/components/hub_locks.js",
338
339
  "hub_ui/components/drill_subprojects.js",
339
340
  "hub_ui/components/drill_health.js",
340
341
  "hub_ui/components/drill_tasks.js",
@@ -433,8 +434,9 @@ def api_hub_config_set():
433
434
  cfg["projects_view"] = projects_view
434
435
  if "main_view" in data:
435
436
  main_view = str(data["main_view"]).strip().lower()
436
- if main_view not in {"projects", "board", "creds"}:
437
- return jsonify({"error": "main_view must be 'projects', 'board' or 'creds'"}), 400
437
+ if main_view not in {"projects", "board", "creds", "locks"}:
438
+ return jsonify({"error": "main_view must be 'projects', 'board', "
439
+ "'creds' or 'locks'"}), 400
438
440
  cfg["main_view"] = main_view
439
441
  if "oracle_url" in data:
440
442
  cfg["oracle_url"] = str(data["oracle_url"]).strip()
@@ -2039,6 +2041,96 @@ def api_hub_credentials_overview():
2039
2041
  return jsonify({"global": {"entries": global_out}, "projects": projects_out})
2040
2042
 
2041
2043
 
2044
+ # ── Agent Locks (hub) ────────────────────────────────────────────────────────
2045
+ # Read + one human override. force-release is here and in `c3 locks`, never in
2046
+ # the c3_locks agent tool: it bumps the fencing counter so a holder that comes
2047
+ # back is stale by construction, which is a decision for a person.
2048
+
2049
+
2050
+ @app.route("/api/hub/locks/overview", methods=["GET"])
2051
+ def api_hub_locks_overview():
2052
+ """Cross-project lease snapshot for the Locks tab.
2053
+
2054
+ Per-row isolation like /api/hub/credentials/overview: one unreadable
2055
+ project must not blank the page. A project we cannot read reports
2056
+ ``error``/``initialized`` rather than an empty lease list — "0 leases"
2057
+ would claim the repo is clear when we simply do not know.
2058
+ """
2059
+ from services import agent_locks as al
2060
+
2061
+ rows, total = [], 0
2062
+ for p in _pm().list_projects():
2063
+ ppath = str(p.get("path") or "")
2064
+ row = {"name": p.get("name") or "", "path": ppath, "initialized": True,
2065
+ "error": None, "enabled": True, "mode": "advisory",
2066
+ "locks": [], "count": 0, "fencing": 0}
2067
+ try:
2068
+ if not (Path(ppath) / ".c3").is_dir():
2069
+ row["initialized"] = False
2070
+ else:
2071
+ cfg = al.config(ppath)
2072
+ row["enabled"] = cfg["enabled"]
2073
+ row["mode"] = cfg["mode"]
2074
+ snap = al.store_for(ppath).snapshot()
2075
+ row["locks"] = snap["locks"]
2076
+ row["count"] = snap["count"]
2077
+ row["fencing"] = snap["fencing"]
2078
+ total += snap["count"]
2079
+ except Exception as e:
2080
+ row["error"] = str(e)
2081
+ rows.append(row)
2082
+ return jsonify({"projects": rows, "total": total,
2083
+ # Surfaced so the UI can state its own limits instead of
2084
+ # implying a lease covers everything (spec §9).
2085
+ "coverage_note": (
2086
+ "Leases gate C3 tool surfaces only. A raw shell "
2087
+ "redirect, a non-Claude agent, or a human in an editor "
2088
+ "is not covered.")})
2089
+
2090
+
2091
+ @app.route("/api/projects/locks/force-release", methods=["POST"])
2092
+ def api_projects_locks_force_release():
2093
+ """Break one lease regardless of holder. Human-only, audited on the target."""
2094
+ from services import agent_locks as al
2095
+
2096
+ data = request.get_json(force=True) or {}
2097
+ path = (data.get("path") or "").strip()
2098
+ relpath = (data.get("relpath") or "").strip()
2099
+ note = (data.get("note") or "").strip()
2100
+ if not path or not relpath:
2101
+ return jsonify({"error": "path and relpath are required"}), 400
2102
+ try:
2103
+ resolved = _resolve_project_path(path)
2104
+ except ValueError as e:
2105
+ return jsonify({"error": str(e)}), 404
2106
+
2107
+ res = al.store_for(resolved).force_release(relpath, by="hub", note=note)
2108
+ if not res.get("forced"):
2109
+ return jsonify({"error": res.get("error", "force-release failed"),
2110
+ "reason": res.get("reason", "")}), 400
2111
+
2112
+ try:
2113
+ from services.activity_log import ActivityLog
2114
+ ActivityLog(resolved).log("lock_force_release", {
2115
+ "kind": "locks", "relpath": res.get("relpath"),
2116
+ "previous_owner": res.get("previous_owner"), "via": "hub"})
2117
+ except Exception:
2118
+ pass
2119
+ try:
2120
+ from services.edit_ledger import EditLedger
2121
+ EditLedger(resolved).log_edit(
2122
+ file=f"lock://{res.get('relpath', relpath)}",
2123
+ change_type="lock_force_release",
2124
+ summary=f"force-released lease on {res.get('relpath', relpath)}"
2125
+ + (f" — {note}" if note else ""),
2126
+ tags=["locks", "force_release"],
2127
+ detail={"kind": "locks", "previous_owner": res.get("previous_owner"),
2128
+ "was_locked": res.get("was_locked"), "note": note})
2129
+ except Exception:
2130
+ pass
2131
+ return jsonify(res)
2132
+
2133
+
2042
2134
  @app.route("/api/projects/config", methods=["PUT"])
2043
2135
  def api_projects_config_put():
2044
2136
  """Whitelisted section write: deep-merge, atomic replace, audited on the target."""
cli/hub_ui/app.js CHANGED
@@ -17,7 +17,7 @@ function App() {
17
17
  const [version, setVersion] = useState('');
18
18
  const [projects, setProjects] = useState([]);
19
19
  const [loaded, setLoaded] = useState(false);
20
- const [mainView, setMainView] = useState('projects'); // projects | board | creds
20
+ const [mainView, setMainView] = useState('projects'); // projects | board | creds | locks
21
21
  const [filter, setFilter] = useState('all'); // all | active | idle | tag:<x>
22
22
  const [search, setSearch] = useState('');
23
23
  const [view, setView] = useState('list'); // list | grid
@@ -44,7 +44,7 @@ function App() {
44
44
  if (cfg.projects_view === 'grid') setView('grid');
45
45
  if (cfg.sidebar_collapsed != null) setSidebarCollapsed(!!cfg.sidebar_collapsed);
46
46
  if (cfg.sidebar_group) setFilter(cfg.sidebar_group);
47
- if (cfg.main_view === 'board' || cfg.main_view === 'creds') setMainView(cfg.main_view);
47
+ if (['board', 'creds', 'locks'].includes(cfg.main_view)) setMainView(cfg.main_view);
48
48
  } catch { }
49
49
  try { const v = await api.get('/api/version'); setVersion(v.c3_version || ''); } catch { }
50
50
  }, []);
@@ -114,6 +114,8 @@ function App() {
114
114
  <TaskBoard projects={projects} onOpenDrill={openDrill} />
115
115
  ) : mainView === 'creds' ? (
116
116
  <HubCredentials projects={projects} onOpenDrill={openDrill} />
117
+ ) : mainView === 'locks' ? (
118
+ <HubLocks projects={projects} onOpenDrill={openDrill} />
117
119
  ) : (
118
120
  <React.Fragment>
119
121
  <SummaryBar projects={projects} search={search} setSearch={setSearch}
@@ -0,0 +1,248 @@
1
+ // ─── Agent Locks (cross-project) ──────────────────────────────────────────
2
+ // Who holds which file, across every registered project, and the one human
3
+ // override: force-release. That bumps the fencing counter so a holder which
4
+ // comes back is stale by construction — a decision for a person, which is why
5
+ // the agent-facing c3_locks tool deliberately has no force action.
6
+ //
7
+ // Honesty rules this view must keep (docs/agent-locks.md §4, §9):
8
+ // - never render "protected" for a repo we cannot actually protect;
9
+ // - a project we could not READ is not a project with zero leases;
10
+ // - the coverage caveat stays visible, because a lease gates C3 tool
11
+ // surfaces only — a raw shell redirect is not covered.
12
+
13
+ function LockBadge({ row }) {
14
+ const pill = (label, fg, bg, title) => (
15
+ <span title={title} className="mono" style={{
16
+ fontSize: 10, padding: '2px 7px', borderRadius: 4,
17
+ color: fg, background: bg, whiteSpace: 'nowrap',
18
+ }}>{label}</span>
19
+ );
20
+ if (row.error) {
21
+ return pill('UNREADABLE', T.error, T.errorDim,
22
+ `Lock state could not be read: ${row.error}. This is not the same as "no leases".`);
23
+ }
24
+ if (!row.initialized) {
25
+ return pill('NO .c3', T.textDim, T.surfaceAlt,
26
+ 'C3 is not initialized here, so nothing coordinates edits in this repo.');
27
+ }
28
+ if (!row.enabled) {
29
+ return pill('DISABLED', T.warn, T.warnDim,
30
+ 'locks.enabled=false in .c3/config.json — leases are not taken or honoured here.');
31
+ }
32
+ return pill(String(row.mode || 'advisory').toUpperCase(), T.accent, T.accentDim,
33
+ 'Advisory: enforced on C3 tool surfaces. A raw shell redirect or a '
34
+ + 'non-Claude agent is not covered.');
35
+ }
36
+
37
+ function LeaseRow({ row, lease, onForce }) {
38
+ // Draining bar: TTL is the real release mechanism, so how much is left is
39
+ // the most useful thing on the row.
40
+ const total = 900;
41
+ const left = Math.max(0, lease.expires_in_s || 0);
42
+ const pct = Math.max(2, Math.min(100, (left / total) * 100));
43
+ const mins = Math.floor(left / 60), secs = Math.floor(left % 60);
44
+ const low = left < 120;
45
+
46
+ return (
47
+ <div style={{
48
+ display: 'grid',
49
+ gridTemplateColumns: 'minmax(0,2fr) minmax(0,1.2fr) minmax(0,1.6fr) 96px 30px',
50
+ gap: 10, alignItems: 'center', padding: '7px 10px',
51
+ borderTop: `1px solid ${T.border}`, fontSize: 12,
52
+ }}>
53
+ <span className="mono" title={lease.relpath} style={{
54
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: T.text,
55
+ }}>{lease.relpath}</span>
56
+
57
+ <span className="mono" title={`session ${lease.session_id || 'unknown'}`} style={{
58
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
59
+ color: T.blue, fontSize: 11,
60
+ }}>{lease.agent_id || 'unknown'}</span>
61
+
62
+ <span title={lease.intent || 'no intent declared'} style={{
63
+ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
64
+ color: lease.intent ? T.textMuted : T.textDim,
65
+ fontStyle: lease.intent ? 'normal' : 'italic',
66
+ }}>{lease.intent || 'no intent'}</span>
67
+
68
+ <div title={`lease expires in ${mins}m${String(secs).padStart(2, '0')}s`}>
69
+ <div className="mono" style={{
70
+ fontSize: 10, color: low ? T.warn : T.textMuted, marginBottom: 3,
71
+ }}>{mins}m{String(secs).padStart(2, '0')}s</div>
72
+ <div style={{ height: 3, background: T.surfaceAlt, borderRadius: 2 }}>
73
+ <div style={{
74
+ width: `${pct}%`, height: '100%', borderRadius: 2,
75
+ background: low ? T.warn : T.accent,
76
+ }} />
77
+ </div>
78
+ </div>
79
+
80
+ <div title="Force-release: breaks the lease and bumps the fencing token, so the current holder goes stale even if it thinks it still holds it."
81
+ onClick={() => onForce(row, lease)}
82
+ style={{
83
+ cursor: 'pointer', display: 'flex', justifyContent: 'center',
84
+ padding: 4, borderRadius: 4,
85
+ }}>
86
+ <I name="xCircle" size={13} color={T.error} />
87
+ </div>
88
+ </div>
89
+ );
90
+ }
91
+
92
+ function HubLocks({ projects, onOpenDrill }) {
93
+ const { useState, useCallback } = React;
94
+ const [data, setData] = useState(null);
95
+ const [err, setErr] = useState('');
96
+ const [confirm, setConfirm] = useState(null);
97
+
98
+ const load = useCallback(async () => {
99
+ try {
100
+ setData(await api.get('/api/hub/locks/overview'));
101
+ setErr('');
102
+ } catch (e) {
103
+ // Keep the last good snapshot rather than blanking to an empty page,
104
+ // which would read as "nothing is locked".
105
+ setErr(String(e && e.message ? e.message : e));
106
+ }
107
+ }, []);
108
+
109
+ React.useEffect(() => { load(); }, [load]);
110
+ usePoll(load, 5000);
111
+
112
+ const doForce = async (row, lease) => {
113
+ try {
114
+ await api.post('/api/projects/locks/force-release', {
115
+ path: row.path, relpath: lease.relpath, note: 'released from the Hub',
116
+ });
117
+ } catch (e) {
118
+ setErr(String(e && e.message ? e.message : e));
119
+ }
120
+ setConfirm(null);
121
+ load();
122
+ };
123
+
124
+ const rows = (data && data.projects) || [];
125
+ const withLeases = rows.filter(r => (r.count || 0) > 0);
126
+ const problems = rows.filter(r => r.error || (r.initialized && !r.enabled));
127
+
128
+ return (
129
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
130
+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
131
+ <I name="lock" size={15} color={T.accent} />
132
+ <span style={{ fontSize: 14, color: T.text }}>Agent Locks</span>
133
+ <span className="mono" style={{ fontSize: 11, color: T.textMuted }}>
134
+ {data ? `${data.total} active lease(s) across ${rows.length} project(s)` : 'loading…'}
135
+ </span>
136
+ <div style={{ flex: 1 }} />
137
+ <div onClick={load} title="Refresh"
138
+ style={{ cursor: 'pointer', padding: 4 }}>
139
+ <I name="refresh" size={13} color={T.textMuted} />
140
+ </div>
141
+ </div>
142
+
143
+ {/* Never let the page imply more protection than exists. */}
144
+ <div style={{
145
+ fontSize: 11, color: T.textMuted, background: T.surface,
146
+ border: `1px solid ${T.border}`, borderRadius: 6, padding: '8px 10px',
147
+ lineHeight: 1.5,
148
+ }}>
149
+ {(data && data.coverage_note)
150
+ || 'Leases gate C3 tool surfaces only.'}
151
+ {' '}A lease is cooperative coordination, not containment.
152
+ </div>
153
+
154
+ {err && (
155
+ <div style={{
156
+ fontSize: 11, color: T.error, background: T.errorDim,
157
+ border: `1px solid ${T.error}`, borderRadius: 6, padding: '8px 10px',
158
+ }}>
159
+ Could not refresh: {err} — showing the last snapshot, which may be stale.
160
+ </div>
161
+ )}
162
+
163
+ {data && withLeases.length === 0 && (
164
+ <div style={{
165
+ fontSize: 12, color: T.textMuted, padding: '18px 10px', textAlign: 'center',
166
+ border: `1px dashed ${T.border}`, borderRadius: 6,
167
+ }}>
168
+ No active leases. Agents take one automatically when they edit a file.
169
+ </div>
170
+ )}
171
+
172
+ {withLeases.map(row => (
173
+ <div key={row.path} style={{
174
+ background: T.surface, border: `1px solid ${T.border}`, borderRadius: 6,
175
+ }}>
176
+ <div style={{
177
+ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
178
+ }}>
179
+ <I name="folder" size={13} color={T.textMuted} />
180
+ <span onClick={() => onOpenDrill && onOpenDrill(
181
+ projects.find(p => p.path === row.path) || { path: row.path, name: row.name })}
182
+ style={{ fontSize: 12, color: T.text, cursor: onOpenDrill ? 'pointer' : 'default' }}>
183
+ {row.name || row.path}
184
+ </span>
185
+ <LockBadge row={row} />
186
+ <span className="mono" style={{ fontSize: 11, color: T.textMuted }}>
187
+ {row.count} lease{row.count === 1 ? '' : 's'}
188
+ </span>
189
+ <div style={{ flex: 1 }} />
190
+ <span className="mono" title="Monotonic fencing counter — force-release bumps it."
191
+ style={{ fontSize: 10, color: T.textDim }}>fencing {row.fencing}</span>
192
+ </div>
193
+ <div style={{
194
+ display: 'grid',
195
+ gridTemplateColumns: 'minmax(0,2fr) minmax(0,1.2fr) minmax(0,1.6fr) 96px 30px',
196
+ gap: 10, padding: '0 10px 5px', fontSize: 10, color: T.textDim,
197
+ }}>
198
+ <span>FILE</span><span>HOLDER</span><span>INTENT</span>
199
+ <span>LEASE LEFT</span><span />
200
+ </div>
201
+ {row.locks.map(lease => (
202
+ <LeaseRow key={lease.relpath} row={row} lease={lease}
203
+ onForce={(r, l) => setConfirm({ row: r, lease: l })} />
204
+ ))}
205
+ </div>
206
+ ))}
207
+
208
+ {/* Projects that cannot coordinate are listed explicitly — silence here
209
+ would read as "all clear". */}
210
+ {problems.length > 0 && (
211
+ <div style={{
212
+ background: T.surface, border: `1px solid ${T.border}`,
213
+ borderRadius: 6, padding: '8px 10px',
214
+ }}>
215
+ <div style={{ fontSize: 11, color: T.textMuted, marginBottom: 6 }}>
216
+ Not coordinating
217
+ </div>
218
+ {problems.map(row => (
219
+ <div key={row.path} style={{
220
+ display: 'flex', alignItems: 'center', gap: 8, padding: '3px 0', fontSize: 11,
221
+ }}>
222
+ <I name="alertTriangle" size={12} color={row.error ? T.error : T.warn} />
223
+ <span className="mono" style={{ color: T.textMuted }}>{row.name || row.path}</span>
224
+ <LockBadge row={row} />
225
+ {row.error && <span style={{ color: T.textDim }}>{row.error}</span>}
226
+ </div>
227
+ ))}
228
+ </div>
229
+ )}
230
+
231
+ {confirm && (
232
+ <ConfirmDialog
233
+ title="Break this lease?"
234
+ danger
235
+ confirmLabel="Force-release"
236
+ message={
237
+ `${confirm.lease.relpath} is held by ${confirm.lease.agent_id}`
238
+ + (confirm.lease.intent ? ` ("${confirm.lease.intent}")` : '')
239
+ + '. Force-releasing bumps the fencing token, so that agent goes '
240
+ + 'stale even if it still believes it holds the file — it may be '
241
+ + 'mid-edit. Prefer waiting for the lease to expire.'
242
+ }
243
+ onConfirm={() => doForce(confirm.row, confirm.lease)}
244
+ onCancel={() => setConfirm(null)} />
245
+ )}
246
+ </div>
247
+ );
248
+ }