code-context-control 2.156.0__py3-none-any.whl → 2.157.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cli/_shell_writes.py CHANGED
@@ -33,7 +33,73 @@ _PY_WRITE_TEXT_RE = re.compile(r"""Path\(\s*(?P<q>['"])(?P<t>[^'"]+)(?P=q)\s*\)\
33
33
  _FILE_CMDS = {"cp", "mv", "touch", "rm", "install"}
34
34
  _STREAMS = {"/dev/null", "/dev/stdout", "/dev/stderr", "nul", "&1", "&2", "-"}
35
35
  _SYNTAX = set("$`(){}|<>*?")
36
+ _MSYS_DRIVE_RE = re.compile(r"^/([a-zA-Z])(?=/|$)")
37
+ _QUOTED_RES = (re.compile(r'"([^"\n]{1,400})"'), re.compile(r"'([^'\n]{1,400})'"))
36
38
  MAX_TARGETS = 20
39
+ MAX_QUOTED = 64
40
+
41
+
42
+ def msys_drive(path: str) -> str:
43
+ """`/c/x` -> `c:/x` on Windows, where Git Bash spells drives that way.
44
+
45
+ Without it `cd /u/repo` resolves to `<cwd drive>:/u/repo`, a directory
46
+ that does not exist, and every relative path after it is judged there.
47
+ """
48
+ if os.name != "nt" or not _MSYS_DRIVE_RE.match(path):
49
+ return path
50
+ return f"{path[1]}:/{path[3:]}"
51
+
52
+
53
+ def _shell_quoted(cmd: str) -> list[str]:
54
+ """Quoted strings as the shell reads them: `'` is literal inside `"`."""
55
+ out: list[str] = []
56
+ buf: list[str] = []
57
+ quote, esc = None, False
58
+ for ch in cmd:
59
+ if quote is None:
60
+ if esc:
61
+ esc = False
62
+ elif ch == "\\":
63
+ esc = True
64
+ elif ch in "'\"":
65
+ quote, buf = ch, []
66
+ elif quote == '"' and esc:
67
+ buf.append(ch)
68
+ esc = False
69
+ elif quote == '"' and ch == "\\":
70
+ buf.append(ch)
71
+ esc = True
72
+ elif ch == quote:
73
+ out.append("".join(buf))
74
+ quote = None
75
+ else:
76
+ buf.append(ch)
77
+ return out
78
+
79
+
80
+ def quoted_paths(cmd: str) -> list[str]:
81
+ """Path-shaped quoted substrings of a command, for the access scans.
82
+
83
+ A quoted path with spaces (`"U:/1. Projects/x/.env"`) splits into
84
+ fragments under a whitespace tokenizer, and quoted code
85
+ (`node -e "fs.readFileSync('x/.env')"`, a heredoc body) hides its
86
+ path inside a larger token. So this returns the shell's own quoted
87
+ strings plus the string literals inside them and anywhere in the text.
88
+ Over-collecting is expected: callers judge each candidate against files
89
+ that exist.
90
+ """
91
+ out: list[str] = []
92
+ cmd = cmd or ""
93
+ tops = _shell_quoted(cmd)
94
+ for s in tops + [m.group(1) for t in tops + [cmd]
95
+ for rx in _QUOTED_RES for m in rx.finditer(t)]:
96
+ s = s.strip()
97
+ if (s and "\n" not in s and len(s) <= 400 and s not in out
98
+ and ("/" in s or "\\" in s or s.startswith("."))):
99
+ out.append(s)
100
+ if len(out) >= MAX_QUOTED:
101
+ break
102
+ return out
37
103
 
38
104
 
39
105
  def _clean(tok: str) -> str:
@@ -79,7 +145,7 @@ def _cd_target(segment: str, cwd: str) -> str | None:
79
145
  m = _CD_RE.match(segment)
80
146
  if not m:
81
147
  return None
82
- target = m.group("dir").strip("\"'")
148
+ target = msys_drive(os.path.expanduser(m.group("dir").strip("\"'")))
83
149
  try:
84
150
  return target if os.path.isabs(target) else os.path.normpath(os.path.join(cwd, target))
85
151
  except (OSError, ValueError):
@@ -99,8 +165,7 @@ def shell_write_targets(cmd: str, cwd: str) -> list[str]:
99
165
  try:
100
166
  for segment in _SEGMENT_SPLIT.split(cmd or ""):
101
167
  for tok in _segment_targets(segment):
102
- if re.match(r"^/[a-z]/", tok): # MSYS /c/foo -> C:/foo
103
- tok = f"{tok[1]}:{tok[2:]}"
168
+ tok = msys_drive(os.path.expanduser(tok))
104
169
  try:
105
170
  p = Path(tok) if os.path.isabs(tok) else Path(here) / tok
106
171
  key = os.path.normcase(os.path.normpath(str(p)))
cli/c3.py CHANGED
@@ -91,7 +91,7 @@ console = Console() if HAS_RICH else None
91
91
  # Config
92
92
  CONFIG_DIR = ".c3"
93
93
  CONFIG_FILE = ".c3/config.json"
94
- __version__ = "2.156.0"
94
+ __version__ = "2.157.2"
95
95
 
96
96
  # The PreToolUse matcher for native subagent calls (installer and hub migration).
97
97
  AGENT_MATCHER = "Agent|Task"
cli/guide/tools.html CHANGED
@@ -1610,7 +1610,7 @@ c3_task(action=<span class="str">'note_add'</span>, note=<span class="str">'Kanb
1610
1610
  <span class="tool-name">c3_schedule</span>
1611
1611
  <div class="tag-row">
1612
1612
  <span class="badge badge-purple">execute</span>
1613
- <span class="badge">v2.156.0</span>
1613
+ <span class="badge">v2.157.1</span>
1614
1614
  </div>
1615
1615
  <span class="tool-tagline">Scheduled tasks — a skill, prompt or command the Oracle fires on a cadence, autonomously or after a human approves each run</span>
1616
1616
  </div>
cli/hook_access_guard.py CHANGED
@@ -34,13 +34,19 @@ except Exception: # pragma: no cover — telemetry is never load-bearing
34
34
  # The same write-target extractor the edit ledger uses after the fact. Its
35
35
  # absence degrades the shell branch to the read-only scan, never to a crash.
36
36
  try:
37
- from _shell_writes import shell_write_targets
37
+ from _shell_writes import msys_drive, quoted_paths, shell_write_targets
38
38
  except Exception: # pragma: no cover — package-style import (dispatcher, tests)
39
39
  try:
40
- from cli._shell_writes import shell_write_targets
40
+ from cli._shell_writes import msys_drive, quoted_paths, shell_write_targets
41
41
  except Exception:
42
42
  shell_write_targets = None
43
43
 
44
+ def msys_drive(path: str) -> str:
45
+ return path
46
+
47
+ def quoted_paths(cmd: str) -> list:
48
+ return []
49
+
44
50
  _WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"}
45
51
  _READ_TOOLS = {"Read", "SearchText"}
46
52
  _SEARCH_TOOLS = {"Grep", "Glob", "FindFiles"}
@@ -112,7 +118,20 @@ _DOUBLE_COLON_RE = re.compile(r"::(?!\$)")
112
118
  # `<rev>:<path>` — how git names a blob: `git show HEAD:setup.py`,
113
119
  # `git cat-file -p origin/main:src/a.py`.
114
120
  _GIT_REVSPEC_RE = re.compile(r"^(?P<rev>[^:\s]+):(?P<path>[^:\s]+)$")
115
- _GIT_CMD_RE = re.compile(r"^\s*(?:[\w.\-]*[/\\])?git(?:\.exe)?\b", re.IGNORECASE)
121
+ # Loop and conditional bodies (`do git show …`) and env prefixes
122
+ # (`GIT_PAGER= git show …`) are still git commands.
123
+ _GIT_CMD_RE = re.compile(
124
+ r"^\s*(?:(?:do|then|else|time|exec|command)\s+|[!({]\s*|[A-Za-z_]\w*=\S*\s+)*"
125
+ r"(?:[\w.\-]*[/\\])?git(?:\.exe)?\b",
126
+ re.IGNORECASE,
127
+ )
128
+
129
+ # Refusals that judge how a path is SPELLED rather than which file it names.
130
+ # A shell token that trips one is usually not a path at all, so these are
131
+ # re-judged as the file they could reach (_spelling_verdict).
132
+ _SPELLING_RULES = frozenset({"<ads>", "<unc>", "<empty-component>", "<8.3-alias>"})
133
+ # `\\host\share` or `//host/share`: one separator between host and share.
134
+ _UNC_SHARE_RE = re.compile(r"^(?:\\\\|//)[^\\/\s]+[\\/][^\\/\s]+")
116
135
 
117
136
  # Where one command ends and the next begins. Anchoring "is this git?" to the
118
137
  # start of the whole string was wrong in the most ordinary way possible:
@@ -190,6 +209,56 @@ def _looks_like_a_path(tok: str) -> bool:
190
209
  return not (_SYNTAX_CHARS & set(tok))
191
210
 
192
211
 
212
+ def _exists(path: str) -> bool:
213
+ try:
214
+ return Path(path).exists()
215
+ except (OSError, ValueError):
216
+ return False
217
+
218
+
219
+ def _stream_base(path: str) -> str:
220
+ """`C:/x/f.txt:name:$DATA` -> `C:/x/f.txt`: the file a stream belongs to."""
221
+ head = path[:2] if re.match(r"^[A-Za-z]:", path) else ""
222
+ return head + path[len(head):].split(":", 1)[0]
223
+
224
+
225
+ def _dots_collapsed(path: str) -> str:
226
+ """The path Windows opens for a spelling with dot-only components.
227
+
228
+ Win32 strips trailing dots and spaces, so `a/.../b` and `a/x/../b` both
229
+ land somewhere real; model that before asking which file it is.
230
+ """
231
+ parts = re.split(r"[\\/]", path)
232
+ kept = [p if p in ("", ".", "..") or p.rstrip(". ") else "." for p in parts]
233
+ return os.path.normpath("/".join(kept))
234
+
235
+
236
+ def _spelling_verdict(denial, tok: str, probe: str, base: str):
237
+ """The deny a path-spelling refusal stands for in a shell command, or None.
238
+
239
+ The spelling rules keep a protected file from being reached under an odd
240
+ name. Tokens that trip them in shell text are mostly not paths
241
+ (`origin/main:x`, `// comment`, `taskkill //F`, `...`), so the token is
242
+ judged as the file it could name, with the usual existence gate, and
243
+ refused only when that file is denied. A real UNC share stays denied: a
244
+ network path cannot be judged locally.
245
+ """
246
+ if denial.rule == "<unc>":
247
+ unc = any(_UNC_SHARE_RE.match(t) for t in (tok, tok.replace("\\\\", "\\")))
248
+ return denial if unc else None
249
+ if denial.rule == "<ads>":
250
+ target = _stream_base(probe)
251
+ elif denial.rule == "<empty-component>":
252
+ target = _dots_collapsed(probe)
253
+ else:
254
+ return None # <8.3-alias>: a short name that does not exist names nothing
255
+ real = ag.check(target, "read", base)
256
+ if (real and real.kind == "deny" and not real.rule.startswith("<")
257
+ and _exists(target)):
258
+ return real
259
+ return None
260
+
261
+
193
262
  def _deny(reason: str) -> dict:
194
263
  return {
195
264
  "hookSpecificOutput": {
@@ -290,7 +359,8 @@ def _cd_target(segment: str, cwd: str) -> str | None:
290
359
  if not target or target.startswith("-"):
291
360
  return None
292
361
  try:
293
- return os.path.abspath(os.path.join(cwd, os.path.expanduser(target)))
362
+ return os.path.abspath(
363
+ os.path.join(cwd, msys_drive(os.path.expanduser(target))))
294
364
  except (OSError, ValueError):
295
365
  return None
296
366
 
@@ -300,12 +370,13 @@ def _scan_shell(cmd: str, base: str):
300
370
 
301
371
  Confident = the token resolves to an EXISTING path that a ``deny`` rule
302
372
  covers (existence-gating keeps regex/pattern arguments like '\\.env'
303
- from false-denying), or the evaluator flags the spelling itself.
373
+ from false-denying). A spelling refusal (``<ads>``, ``<unc>``, …) counts
374
+ only when the file the spelling could reach is itself denied
375
+ (``_spelling_verdict``). Quoted substrings are judged as well, so a
376
+ quoted path with spaces is not lost to whitespace splitting.
304
377
 
305
378
  Tokens that are shell syntax rather than path arguments are skipped
306
- outright, as are URLs and IPv6 literals: all of them trip the ADS spelling
307
- check, which is exempt from existence-gating, so a token naming nothing on
308
- disk would otherwise hard-deny (#50).
379
+ outright, as are URLs and IPv6 literals.
309
380
 
310
381
  Scanning is per **command segment**, not per whole string. A segment is what
311
382
  sits between `&&`, `||`, `;`, `|` or a newline, and each one answers "am I a
@@ -315,6 +386,7 @@ def _scan_shell(cmd: str, base: str):
315
386
  """
316
387
  budget = _MAX_TOKENS
317
388
  cwd = base
389
+ visited = [base]
318
390
  for segment in _SEGMENT_SPLIT.split(cmd or ""):
319
391
  if budget <= 0:
320
392
  break
@@ -347,8 +419,7 @@ def _scan_shell(cmd: str, base: str):
347
419
  from_revspec = revspec_path is not None
348
420
  if from_revspec:
349
421
  tok = revspec_path
350
- if re.match(r"^/[a-z]/", tok): # MSYS /c/foo → C:/foo
351
- tok = f"{tok[1]}:{tok[2:]}"
422
+ tok = msys_drive(tok)
352
423
  # Resolve against the cwd the command will actually run in, not the
353
424
  # session root. `cd /elsewhere && cat .env` used to compute the
354
425
  # denial correctly and then throw it away, because the existence
@@ -363,10 +434,12 @@ def _scan_shell(cmd: str, base: str):
363
434
  probe = tok
364
435
  denial = ag.check(probe, "read", base)
365
436
  if denial and denial.kind == "deny":
366
- try:
367
- exists = Path(probe).exists()
368
- except OSError:
369
- exists = False
437
+ if denial.rule in _SPELLING_RULES:
438
+ denial = _spelling_verdict(denial, tok, probe, base)
439
+ if denial is not None:
440
+ return denial, tok
441
+ continue
442
+ exists = _exists(probe)
370
443
  # A revspec names a path in HISTORY, so the working tree is the
371
444
  # wrong place to ask whether it is real. `git show HEAD~5:.env`
372
445
  # reads a denied file whether or not that file exists today, and
@@ -378,6 +451,34 @@ def _scan_shell(cmd: str, base: str):
378
451
  moved = _cd_target(segment, cwd)
379
452
  if moved is not None:
380
453
  cwd = moved
454
+ visited.append(cwd)
455
+ return _scan_quoted(cmd, visited, base)
456
+
457
+
458
+ def _scan_quoted(cmd: str, dirs: list, base: str):
459
+ """(denial, token) for a quoted path naming an existing denied file.
460
+
461
+ Quotes can span the segment separators, so this runs over the whole
462
+ command and resolves a relative path against every directory the scan
463
+ visited. A quoted `//host/path` is far more often a protocol-relative URL
464
+ in code than a share, so `<unc>` is not judged here; the token scan still
465
+ judges it.
466
+ """
467
+ for raw in quoted_paths(cmd):
468
+ if _is_network_token(raw):
469
+ continue
470
+ tok = msys_drive(os.path.expanduser(raw))
471
+ for here in ([base] if os.path.isabs(tok) else dirs):
472
+ probe = tok if os.path.isabs(tok) else os.path.join(here, tok)
473
+ denial = ag.check(probe, "read", base)
474
+ if not denial or denial.kind != "deny" or denial.rule == "<unc>":
475
+ continue
476
+ if denial.rule in _SPELLING_RULES:
477
+ denial = _spelling_verdict(denial, tok, probe, base)
478
+ elif not (_exists(probe) or denial.rule.startswith("<")):
479
+ denial = None
480
+ if denial is not None:
481
+ return denial, tok
381
482
  return None, ""
382
483
 
383
484
 
cli/hub_server.py CHANGED
@@ -31,7 +31,7 @@ sys.path.insert(0, str(Path(__file__).parent.parent))
31
31
 
32
32
  from cli._hook_utils import hook_command_arg
33
33
  from core.ide import PROFILES, detect_ide, get_profile, load_ide_config, normalize_ide_name
34
- from services import access_guard
34
+ from services import access_guard, fleet_overview
35
35
  from services.activity_log import ActivityLog
36
36
  from services.atomic_json import write_json_atomic
37
37
  from services.project_manager import ProjectManager
@@ -2710,38 +2710,11 @@ def api_hub_locks_overview():
2710
2710
  Per-row isolation like /api/hub/credentials/overview: one unreadable
2711
2711
  project must not blank the page. A project we cannot read reports
2712
2712
  ``error``/``initialized`` rather than an empty lease list — "0 leases"
2713
- would claim the repo is clear when we simply do not know.
2713
+ would claim the repo is clear when we simply do not know. Built by
2714
+ services.fleet_overview, which the Oracle gateway's /locks/overview
2715
+ shares, so Desk and the phone read the same rows.
2714
2716
  """
2715
- from services import agent_locks as al
2716
-
2717
- rows, total = [], 0
2718
- for p in _pm().list_registered():
2719
- ppath = str(p.get("path") or "")
2720
- row = {"name": p.get("name") or "", "path": ppath, "initialized": True,
2721
- "error": None, "enabled": True, "mode": "advisory",
2722
- "locks": [], "count": 0, "fencing": 0}
2723
- try:
2724
- if not (Path(ppath) / ".c3").is_dir():
2725
- row["initialized"] = False
2726
- else:
2727
- cfg = al.config(ppath)
2728
- row["enabled"] = cfg["enabled"]
2729
- row["mode"] = cfg["mode"]
2730
- snap = al.store_for(ppath).snapshot()
2731
- row["locks"] = snap["locks"]
2732
- row["count"] = snap["count"]
2733
- row["fencing"] = snap["fencing"]
2734
- total += snap["count"]
2735
- except Exception as e:
2736
- row["error"] = str(e)
2737
- rows.append(row)
2738
- return jsonify({"projects": rows, "total": total,
2739
- # Surfaced so the UI can state its own limits instead of
2740
- # implying a lease covers everything (spec §9).
2741
- "coverage_note": (
2742
- "Leases gate C3 tool surfaces only. A raw shell "
2743
- "redirect, a non-Claude agent, or a human in an editor "
2744
- "is not covered.")})
2717
+ return jsonify(fleet_overview.locks(_pm().list_registered()))
2745
2718
 
2746
2719
 
2747
2720
  @app.route("/api/projects/locks/force-release", methods=["POST"])
@@ -2798,84 +2771,10 @@ def api_hub_enforcement_overview():
2798
2771
 
2799
2772
  Denial counts come from services.access_telemetry, split by layer so the
2800
2773
  UI can point at the right lever: discipline blocks are cleared by changing
2801
- the mode here, path denials by editing Access Guard rules.
2774
+ the mode here, path denials by editing Access Guard rules. Shared with
2775
+ the gateway's /enforcement/overview through services.fleet_overview.
2802
2776
  """
2803
- from services import access_telemetry as at
2804
- from services import enforcement_policy as ep
2805
-
2806
- rows = []
2807
- totals = {"discipline": 0, "access": 0}
2808
- for p in _pm().list_registered():
2809
- ppath = str(p.get("path") or "")
2810
- row = {"name": p.get("name") or "", "path": ppath, "initialized": True,
2811
- "error": None, "mode": None, "scope": "", "set_by": "",
2812
- "signal_ttl_s": ep.DEFAULT_SIGNAL_TTL_S, "warnings": [],
2813
- "tier": "", "tier_implies": "", "denials": {}, "denial_total": 0}
2814
- try:
2815
- if not (Path(ppath) / ".c3").is_dir():
2816
- row["initialized"] = False
2817
- else:
2818
- policy = ep.resolve(ppath)
2819
- row["mode"] = policy.mode
2820
- row["scope"] = policy.scope
2821
- row["set_by"] = policy.set_by
2822
- row["signal_ttl_s"] = policy.signal_ttl_s
2823
- row["warnings"] = list(policy.warnings)
2824
- row["blocked_tools"] = sorted(policy.blocked_tools)
2825
-
2826
- cfg_path = Path(ppath) / ".c3" / "config.json"
2827
- try:
2828
- cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
2829
- tier = str(cfg.get("permission_tier") or "")
2830
- except Exception:
2831
- tier = ""
2832
- row["tier"] = tier
2833
- row["tier_implies"] = ep.derive_from_tier(tier) if tier else ""
2834
-
2835
- agg = at.aggregate(ppath)
2836
- row["denials"] = agg["by_layer"]
2837
- row["denial_total"] = agg["total"]
2838
- row["top_denials"] = [
2839
- {**r, "fix": at.suggest(r)} for r in agg["rows"][:5]
2840
- ]
2841
- for layer, count in agg["by_layer"].items():
2842
- totals[layer] = totals.get(layer, 0) + count
2843
- except Exception as e:
2844
- row["error"] = str(e)
2845
- rows.append(row)
2846
-
2847
- # The global (~/.c3) section, shown as its own card. A corrupt global
2848
- # config must not blank the tab — report the error inside the object.
2849
- try:
2850
- g = ep.resolve_global()
2851
- global_policy = {
2852
- "configured": g.scope == "global",
2853
- "mode": g.mode or None,
2854
- "set_by": g.set_by,
2855
- "signal_ttl_s": g.signal_ttl_s,
2856
- "blocked_tools": sorted(g.blocked_tools),
2857
- "warnings": list(g.warnings),
2858
- }
2859
- except Exception as e:
2860
- global_policy = {"configured": False, "mode": None, "error": str(e)}
2861
-
2862
- return jsonify({
2863
- "projects": rows,
2864
- "modes": [{"id": m, "help": ep.MODE_HELP[m]} for m in ep.MODES],
2865
- "default_mode": ep.DEFAULT_MODE,
2866
- "tier_map": ep.TIER_TO_MODE,
2867
- "totals": totals,
2868
- "global_policy": global_policy,
2869
- # Stated so the tab can never imply that turning discipline down also
2870
- # turns the security boundaries down. Mirrors docs/enforcement.md.
2871
- "coverage_note": (
2872
- "Tool discipline only governs whether native Edit/Write are "
2873
- "pushed through c3_edit. At every mode — including off — Access "
2874
- "Guard path rules, the credential-vault write guard, and agent "
2875
- "locks still enforce. The edit ledger records native writes "
2876
- "either way; strict additionally gets c3_edit's pre-edit snapshot."
2877
- ),
2878
- })
2777
+ return jsonify(fleet_overview.enforcement(_pm().list_registered()))
2879
2778
 
2880
2779
 
2881
2780
  @app.route("/api/projects/enforcement", methods=["GET"])
@@ -3526,12 +3425,9 @@ def api_hub_override_costs():
3526
3425
 
3527
3426
 
3528
3427
  #: Verbatim from the spec, and the one thing a toggle screen must not let the
3529
- #: reader forget: policy is a floor, not a promise.
3530
- _OVERRIDE_POLICY_NOTE = (
3531
- "Project and global policy merge by tightening only: a layer is "
3532
- "escalatable iff both scopes allow it, and the numeric limits take "
3533
- "the smaller value."
3534
- )
3428
+ #: reader forget: policy is a floor, not a promise. One copy, shared with the
3429
+ #: overview and the Oracle gateway.
3430
+ _OVERRIDE_POLICY_NOTE = fleet_overview.OVERRIDE_POLICY_NOTE
3535
3431
 
3536
3432
 
3537
3433
  def _hub_policy_audit(project_path: str, action: str, detail_extra: dict) -> None:
@@ -3650,51 +3546,10 @@ def api_hub_override_policy_overview():
3650
3546
  section is reported as corrupt rather than as the disabled policy it
3651
3547
  resolves to. ``project_keys`` names what the project pins itself, so a
3652
3548
  screen can tell an inherited value from a chosen one. The global scope is
3653
- served READ-ONLY: ``write_section`` is project-scope by design.
3549
+ served READ-ONLY: ``write_section`` is project-scope by design. Shared
3550
+ with the gateway's /overrides/policy/overview (services.fleet_overview).
3654
3551
  """
3655
- from services import override_policy as opol
3656
-
3657
- rows = []
3658
- for p in _pm().list_registered():
3659
- ppath = str(p.get("path") or "")
3660
- row = {"name": p.get("name") or Path(ppath).name, "path": ppath,
3661
- "initialized": True, "error": None, "policy": None,
3662
- "configured": False, "corrupt": False, "project_keys": []}
3663
- try:
3664
- if not (Path(ppath) / ".c3").is_dir():
3665
- row["initialized"] = False
3666
- else:
3667
- keys, present, corrupt = opol.scope_keys(ppath)
3668
- row["project_keys"] = keys
3669
- row["configured"] = present
3670
- row["corrupt"] = corrupt
3671
- row["policy"] = opol.resolve(ppath).as_dict()
3672
- except Exception as e:
3673
- row["error"] = str(e)
3674
- rows.append(row)
3675
-
3676
- try:
3677
- keys, present, corrupt = opol.global_scope_keys()
3678
- global_policy = {"configured": present, "corrupt": corrupt,
3679
- "keys": keys, "error": None,
3680
- "policy": opol.resolve_global().as_dict()}
3681
- except Exception as e:
3682
- global_policy = {"configured": False, "corrupt": False, "keys": [],
3683
- "error": str(e), "policy": None}
3684
-
3685
- return jsonify({
3686
- "projects": rows,
3687
- "global_policy": global_policy,
3688
- "defaults": {k: v for k, v in opol.DEFAULTS.items()
3689
- if k != opol.WAKE_KEY},
3690
- "layers": list(opol.LAYER_KEYS),
3691
- "typed_confirm_layers": sorted(opol.TYPED_CONFIRM_LAYERS),
3692
- "hard_max_ttl_s": opol.HARD_MAX_TTL_S,
3693
- "coverage_note": _OVERRIDE_POLICY_NOTE,
3694
- # What this Hub can do beyond the per-project GET/POST, so a client
3695
- # built against a newer C3 can hide what an older one cannot serve.
3696
- "features": ["clear"],
3697
- })
3552
+ return jsonify(fleet_overview.override_policy(_pm().list_registered()))
3698
3553
 
3699
3554
 
3700
3555
  @app.route("/api/hub/overrides/policy/clear", methods=["POST"])
@@ -3962,45 +3817,10 @@ def api_hub_access_overview():
3962
3817
  scope is reported as corrupt: it evaluates deny-all until repaired by
3963
3818
  hand, which is the opposite of what an empty list would suggest.
3964
3819
  Builtin rules are read once, from the global realm; a project-scope
3965
- builtin mode (set with the CLI) is not reflected per row.
3820
+ builtin mode (set with the CLI) is not reflected per row. Shared with the
3821
+ gateway's /access/overview through services.fleet_overview.
3966
3822
  """
3967
- empty = {"deny": [], "read_only": [], "confirm": [], "mask": 0,
3968
- "corrupt": False}
3969
- rows = []
3970
- for p in _pm().list_registered():
3971
- ppath = str(p.get("path") or "")
3972
- row = {"name": p.get("name") or Path(ppath).name, "path": ppath,
3973
- "initialized": True, "error": None, "rules": dict(empty)}
3974
- try:
3975
- if not (Path(ppath) / ".c3").is_dir():
3976
- row["initialized"] = False
3977
- else:
3978
- row["rules"] = access_guard.scope_rules("project", ppath)
3979
- except Exception as e:
3980
- row["error"] = str(e)
3981
- rows.append(row)
3982
-
3983
- try:
3984
- global_rules = {**access_guard.scope_rules("global"), "error": None}
3985
- except Exception as e:
3986
- global_rules = {**empty, "error": str(e)}
3987
- try:
3988
- home = access_guard._global_base()
3989
- b = access_guard.list_rules(str(home) if home else ".")["builtin"]
3990
- builtin = {"deny": list(b.get("deny") or []),
3991
- "read_only": list(b.get("read_only") or []),
3992
- "confirm": list(b.get("confirm") or []), "error": None}
3993
- except Exception as e:
3994
- builtin = {"deny": [], "read_only": [], "confirm": [], "error": str(e)}
3995
-
3996
- return jsonify({
3997
- "projects": rows,
3998
- "global": global_rules,
3999
- "builtin": builtin,
4000
- # Strictest last. "allow" is the absence of a rule, not a kind.
4001
- "kinds": ["confirm", "read_only", "deny"],
4002
- "coverage_note": access_guard.COVERAGE_MATRIX,
4003
- })
3823
+ return jsonify(fleet_overview.access(_pm().list_registered()))
4004
3824
 
4005
3825
 
4006
3826
  @app.route("/api/hub/access/rule", methods=["POST"])
@@ -4089,38 +3909,13 @@ def api_hub_access_builtin():
4089
3909
  so a mode listed here is one evaluation honours. ``projects`` holds only
4090
3910
  projects that set a mode of their own, or could not be read.
4091
3911
  ``strictness`` ranks each mode 0 (allow) to 3 (full deny), so a client
4092
- can tell loosening from tightening without knowing the tiers.
3912
+ can tell loosening from tightening without knowing the tiers. Shared
3913
+ with the gateway's /access/builtin through services.fleet_overview.
4093
3914
  """
4094
3915
  try:
4095
- global_modes = access_guard._scope_modes("global")
3916
+ return jsonify(fleet_overview.builtin(_pm().list_registered()))
4096
3917
  except Exception as e:
4097
3918
  return jsonify({"error": str(e)}), 500
4098
- home = access_guard._global_base()
4099
- guards = []
4100
- for glob in access_guard.DISABLEABLE_BUILTINS:
4101
- canon = access_guard._norm_builtin(glob)
4102
- guards.append({
4103
- "glob": canon,
4104
- "global": global_modes.get(canon, "default"),
4105
- "strictness": {m: access_guard.builtin_strictness(canon, m)
4106
- for m in (*access_guard.BUILTIN_MODES, "default")},
4107
- })
4108
- projects = []
4109
- for p in _pm().list_registered():
4110
- ppath = str(p.get("path") or "")
4111
- row = {"name": p.get("name") or Path(ppath).name, "path": ppath,
4112
- "modes": {}, "error": None}
4113
- try:
4114
- base = Path(ppath).resolve()
4115
- if (base / ".c3").is_dir() and base != home:
4116
- row["modes"] = access_guard._scope_modes("project", ppath)
4117
- except Exception as e:
4118
- row["error"] = str(e)
4119
- if row["modes"] or row["error"]:
4120
- projects.append(row)
4121
- from services import builtin_leases
4122
- return jsonify({"guards": guards, "projects": projects,
4123
- "leases": builtin_leases.active()})
4124
3919
 
4125
3920
 
4126
3921
  @app.route("/api/hub/access/builtin/mode", methods=["POST"])