Stevesolun commited on
Commit
7aaa36c
·
verified ·
1 Parent(s): 34ebeb1

Sync ctx c61de90 (part 2)

Browse files

GitHub commit: c61de902e8fdd2a4b2cfa061c5337a2fef078d0a

qa/feature_status.csv ADDED
The diff for this file is too large to render. See raw diff
 
scripts/audit_backup.py CHANGED
@@ -10,6 +10,14 @@ from pathlib import Path
10
 
11
  CLAUDE_HOME = Path(os.path.expanduser("~/.claude"))
12
  BACKUPS = CLAUDE_HOME / "backups"
 
 
 
 
 
 
 
 
13
 
14
 
15
  def latest_snapshot() -> Path:
@@ -17,8 +25,15 @@ def latest_snapshot() -> Path:
17
  return snaps[-1]
18
 
19
 
 
 
 
 
 
 
 
20
  def main() -> int:
21
- snap = Path(sys.argv[1]) if len(sys.argv) > 1 else latest_snapshot()
22
  manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8-sig"))
23
 
24
  print(f"snapshot: {snap}")
 
10
 
11
  CLAUDE_HOME = Path(os.path.expanduser("~/.claude"))
12
  BACKUPS = CLAUDE_HOME / "backups"
13
+ USAGE = """usage: python scripts/audit_backup.py [SNAPSHOT]
14
+
15
+ Summarize a backup snapshot and flag expected ~/.claude files missing from it.
16
+
17
+ Arguments:
18
+ SNAPSHOT Optional backup snapshot directory. Defaults to the latest
19
+ directory under ~/.claude/backups.
20
+ """
21
 
22
 
23
  def latest_snapshot() -> Path:
 
25
  return snaps[-1]
26
 
27
 
28
+ def _snapshot_arg(argv: list[str]) -> Path:
29
+ if len(argv) > 1 and argv[1] in {"-h", "--help"}:
30
+ print(USAGE)
31
+ raise SystemExit(0)
32
+ return Path(argv[1]) if len(argv) > 1 else latest_snapshot()
33
+
34
+
35
  def main() -> int:
36
+ snap = _snapshot_arg(sys.argv)
37
  manifest = json.loads((snap / "manifest.json").read_text(encoding="utf-8-sig"))
38
 
39
  print(f"snapshot: {snap}")
scripts/ci_classifier.py CHANGED
@@ -28,6 +28,7 @@ DOCS_PATTERNS = (
28
  "graph/README.md",
29
  "LICENSE",
30
  "mkdocs.yml",
 
31
  "requirements-docs.txt",
32
  )
33
  GRAPH_ARTIFACT_PATTERNS = (
@@ -115,30 +116,23 @@ def _is_graph_artifact_path(path: str) -> bool:
115
 
116
 
117
  def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
118
- files = [
119
- normalized
120
- for path in paths
121
- if (normalized := _normalize_path(path))
122
- ]
123
  ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
124
  docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
125
  graph_artifact_changed = any(_is_graph_artifact_path(path) for path in files)
126
  graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
127
  return {
128
- "browser_changed": ci_changed
129
- or any(_matches(path, BROWSER_PATTERNS) for path in files),
130
  "ci_changed": ci_changed,
131
  "docs_changed": docs_changed,
132
  "docs_only": bool(files) and all(_matches(path, DOCS_PATTERNS) for path in files),
133
  "graph_artifact_changed": graph_artifact_changed,
134
  "graph_changed": any(_matches(path, ("graph/**",)) for path in files),
135
  "graph_only": graph_only,
136
- "package_changed": ci_changed
137
- or any(_matches(path, PACKAGE_PATTERNS) for path in files),
138
  "similarity_changed": ci_changed
139
  or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
140
- "source_changed": ci_changed
141
- or any(_matches(path, SOURCE_PATTERNS) for path in files),
142
  "telemetry_changed": ci_changed
143
  or any(_matches(path, TELEMETRY_PATTERNS) for path in files),
144
  }
 
28
  "graph/README.md",
29
  "LICENSE",
30
  "mkdocs.yml",
31
+ "qa/feature_status.csv",
32
  "requirements-docs.txt",
33
  )
34
  GRAPH_ARTIFACT_PATTERNS = (
 
116
 
117
 
118
  def classify_paths(paths: Iterable[str]) -> dict[str, bool]:
119
+ files = [normalized for path in paths if (normalized := _normalize_path(path))]
 
 
 
 
120
  ci_changed = any(_matches(path, (".github/workflows/**",)) for path in files)
121
  docs_changed = any(_matches(path, DOCS_PATTERNS) for path in files)
122
  graph_artifact_changed = any(_is_graph_artifact_path(path) for path in files)
123
  graph_only = bool(files) and all(_matches(path, ("graph/**",)) for path in files)
124
  return {
125
+ "browser_changed": ci_changed or any(_matches(path, BROWSER_PATTERNS) for path in files),
 
126
  "ci_changed": ci_changed,
127
  "docs_changed": docs_changed,
128
  "docs_only": bool(files) and all(_matches(path, DOCS_PATTERNS) for path in files),
129
  "graph_artifact_changed": graph_artifact_changed,
130
  "graph_changed": any(_matches(path, ("graph/**",)) for path in files),
131
  "graph_only": graph_only,
132
+ "package_changed": ci_changed or any(_matches(path, PACKAGE_PATTERNS) for path in files),
 
133
  "similarity_changed": ci_changed
134
  or any(_matches(path, SIMILARITY_PATTERNS) for path in files),
135
+ "source_changed": ci_changed or any(_matches(path, SOURCE_PATTERNS) for path in files),
 
136
  "telemetry_changed": ci_changed
137
  or any(_matches(path, TELEMETRY_PATTERNS) for path in files),
138
  }
scripts/no_mistakes_codex_env.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # no-mistakes agents run in a stripped-down environment. Keep ctx validation fast
5
+ # by exposing the verified project Python toolchain and Codex-bundled ripgrep.
6
+ default_ctx_python_bin="/tmp/ctx-verify-venv/bin"
7
+ ctx_python_bin="${CTX_NO_MISTAKES_PYTHON_BIN:-${default_ctx_python_bin}}"
8
+ codex_resources="${CTX_NO_MISTAKES_CODEX_RESOURCES:-/Applications/Codex.app/Contents/Resources}"
9
+ real_codex="${CTX_NO_MISTAKES_REAL_CODEX:-${codex_resources}/codex}"
10
+
11
+ is_trusted_python_bin() {
12
+ local bin_dir="$1"
13
+ local venv_dir="${bin_dir%/bin}"
14
+
15
+ [[ -d "${bin_dir}" && -x "${bin_dir}/python" ]] || return 1
16
+ [[ -O "${venv_dir}" && -O "${bin_dir}" ]] || return 1
17
+ [[ -z "$(find "${venv_dir}" "${bin_dir}" -prune -perm -022 -print -quit)" ]]
18
+ }
19
+
20
+ trusted_ctx_python_bin=""
21
+ if [[ -n "${CTX_NO_MISTAKES_PYTHON_BIN:-}" ]]; then
22
+ trusted_ctx_python_bin="${ctx_python_bin}"
23
+ elif is_trusted_python_bin "${ctx_python_bin}"; then
24
+ trusted_ctx_python_bin="${ctx_python_bin}"
25
+ fi
26
+
27
+ if [[ -n "${trusted_ctx_python_bin}" ]]; then
28
+ export PATH="${trusted_ctx_python_bin}:${codex_resources}:${PATH}"
29
+ if [[ -x "${trusted_ctx_python_bin}/python" ]]; then
30
+ export VIRTUAL_ENV="${VIRTUAL_ENV:-${trusted_ctx_python_bin%/bin}}"
31
+ fi
32
+ else
33
+ export PATH="${codex_resources}:${PATH}"
34
+ fi
35
+ export PYTHONDONTWRITEBYTECODE="${PYTHONDONTWRITEBYTECODE:-1}"
36
+ export PIP_DISABLE_PIP_VERSION_CHECK="${PIP_DISABLE_PIP_VERSION_CHECK:-1}"
37
+
38
+ exec "${real_codex}" "$@"
scripts/tune_similarity_thresholds.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  tune_similarity_thresholds.py -- Sweep thresholds against the fixture corpus
3
- and print the precision/recall surface so we can pick sensible defaults.
4
 
5
  Run once after editing fixtures or changing the embedder; not part of CI.
6
  """
@@ -22,6 +22,14 @@ from ctx_config import cfg # noqa: E402
22
  from intake_gate import compose_corpus_text # noqa: E402
23
 
24
  FIXTURE_DIR = SRC_DIR / "tests" / "fixtures" / "similarity"
 
 
 
 
 
 
 
 
25
 
26
 
27
  @dataclass(frozen=True)
@@ -66,9 +74,31 @@ def _score(pair: _Pair, embedder, root: Path) -> float:
66
  return float(top[0].score) if top else 0.0
67
 
68
 
69
- def main() -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  import tempfile
71
 
 
 
 
 
 
 
 
 
72
  embedder = cfg.build_intake_embedder()
73
  near = _load("near_duplicates.jsonl")
74
  distinct = _load("distinct_pairs.jsonl")
@@ -83,14 +113,18 @@ def main() -> None:
83
  print("\n=== Near-duplicate scores (should be HIGH) ===")
84
  for pid, s in sorted(near_scores, key=lambda x: x[1]):
85
  print(f" {pid}: {s:.4f}")
86
- print(f" min={min(s for _, s in near_scores):.4f} "
87
- f"median={sorted(s for _, s in near_scores)[len(near_scores)//2]:.4f}")
 
 
88
 
89
  print("\n=== Distinct scores (should be LOW) ===")
90
  for pid, s in sorted(distinct_scores, key=lambda x: -x[1])[:10]:
91
  print(f" {pid}: {s:.4f}")
92
- print(f" max={max(s for _, s in distinct_scores):.4f} "
93
- f"median={sorted(s for _, s in distinct_scores)[len(distinct_scores)//2]:.4f}")
 
 
94
 
95
  print("\n=== Adversarial scores (should be LOW — precision traps) ===")
96
  for pid, s in sorted(adv_scores, key=lambda x: -x[1]):
@@ -100,15 +134,19 @@ def main() -> None:
100
  # Sweep: at each candidate near_dup threshold, compute P/R assuming a pair
101
  # is flagged iff top_score >= threshold.
102
  print("\n=== Threshold sweep (flag if score >= t) ===")
103
- print(f"{'threshold':>10} {'recall':>8} {'precision':>10} {'TP':>4} {'FN':>4} {'FP':>4}")
 
 
104
  for t in [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.82, 0.85, 0.88, 0.90, 0.93]:
105
- tp = sum(1 for _, s in near_scores if s >= t)
106
- fn = len(near_scores) - tp
107
- fp = sum(1 for _, s in distinct_scores + adv_scores if s >= t)
108
- recall = tp / (tp + fn) if (tp + fn) else 0
109
- precision = tp / (tp + fp) if (tp + fp) else 0
110
- print(f"{t:>10.2f} {recall:>8.3f} {precision:>10.3f} {tp:>4} {fn:>4} {fp:>4}")
 
 
111
 
112
 
113
  if __name__ == "__main__":
114
- main()
 
1
  """
2
  tune_similarity_thresholds.py -- Sweep thresholds against the fixture corpus
3
+ and print the precision/recall/F1 surface so we can pick sensible defaults.
4
 
5
  Run once after editing fixtures or changing the embedder; not part of CI.
6
  """
 
22
  from intake_gate import compose_corpus_text # noqa: E402
23
 
24
  FIXTURE_DIR = SRC_DIR / "tests" / "fixtures" / "similarity"
25
+ USAGE = """usage: python scripts/tune_similarity_thresholds.py
26
+
27
+ Sweep similarity thresholds against the fixture corpus and print precision,
28
+ recall, F1, and confusion counts for candidate defaults.
29
+
30
+ Requires the configured embedding backend. Use --help to show this message
31
+ without loading the embedding model.
32
+ """
33
 
34
 
35
  @dataclass(frozen=True)
 
74
  return float(top[0].score) if top else 0.0
75
 
76
 
77
+ def _precision_recall_f1(
78
+ near_scores: list[tuple[str, float]],
79
+ negative_scores: list[tuple[str, float]],
80
+ threshold: float,
81
+ ) -> tuple[float, float, float, int, int, int]:
82
+ tp = sum(1 for _, score in near_scores if score >= threshold)
83
+ fn = len(near_scores) - tp
84
+ fp = sum(1 for _, score in negative_scores if score >= threshold)
85
+ recall = tp / (tp + fn) if (tp + fn) else 0
86
+ precision = tp / (tp + fp) if (tp + fp) else 0
87
+ f1 = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0
88
+ return precision, recall, f1, tp, fn, fp
89
+
90
+
91
+ def main(argv: list[str] | None = None) -> int:
92
  import tempfile
93
 
94
+ args = sys.argv[1:] if argv is None else argv
95
+ if any(arg in {"-h", "--help"} for arg in args):
96
+ print(USAGE)
97
+ return 0
98
+ if args:
99
+ print(USAGE, file=sys.stderr)
100
+ return 2
101
+
102
  embedder = cfg.build_intake_embedder()
103
  near = _load("near_duplicates.jsonl")
104
  distinct = _load("distinct_pairs.jsonl")
 
113
  print("\n=== Near-duplicate scores (should be HIGH) ===")
114
  for pid, s in sorted(near_scores, key=lambda x: x[1]):
115
  print(f" {pid}: {s:.4f}")
116
+ print(
117
+ f" min={min(s for _, s in near_scores):.4f} "
118
+ f"median={sorted(s for _, s in near_scores)[len(near_scores) // 2]:.4f}"
119
+ )
120
 
121
  print("\n=== Distinct scores (should be LOW) ===")
122
  for pid, s in sorted(distinct_scores, key=lambda x: -x[1])[:10]:
123
  print(f" {pid}: {s:.4f}")
124
+ print(
125
+ f" max={max(s for _, s in distinct_scores):.4f} "
126
+ f"median={sorted(s for _, s in distinct_scores)[len(distinct_scores) // 2]:.4f}"
127
+ )
128
 
129
  print("\n=== Adversarial scores (should be LOW — precision traps) ===")
130
  for pid, s in sorted(adv_scores, key=lambda x: -x[1]):
 
134
  # Sweep: at each candidate near_dup threshold, compute P/R assuming a pair
135
  # is flagged iff top_score >= threshold.
136
  print("\n=== Threshold sweep (flag if score >= t) ===")
137
+ print(
138
+ f"{'threshold':>10} {'recall':>8} {'precision':>10} {'f1':>8} {'TP':>4} {'FN':>4} {'FP':>4}"
139
+ )
140
  for t in [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.82, 0.85, 0.88, 0.90, 0.93]:
141
+ precision, recall, f1, tp, fn, fp = _precision_recall_f1(
142
+ near_scores,
143
+ distinct_scores + adv_scores,
144
+ t,
145
+ )
146
+ print(f"{t:>10.2f} {recall:>8.3f} {precision:>10.3f} {f1:>8.3f} {tp:>4} {fn:>4} {fp:>4}")
147
+
148
+ return 0
149
 
150
 
151
  if __name__ == "__main__":
152
+ sys.exit(main())
src/ctx/__init__.py CHANGED
@@ -10,6 +10,7 @@ Four delivery surfaces (pick what fits your integration):
10
  2. **Generic harness CLI** — drive any LLM against a task:
11
  ctx run --model openrouter/anthropic/claude-opus-4.7 \\
12
  --task "fix the failing tests"
 
13
 
14
  3. **Python library** — use from your own harness / tool:
15
  from ctx import recommend_bundle, graph_query, wiki_search
 
10
  2. **Generic harness CLI** — drive any LLM against a task:
11
  ctx run --model openrouter/anthropic/claude-opus-4.7 \\
12
  --task "fix the failing tests"
13
+ The same CLI is available through ``python -m ctx``.
14
 
15
  3. **Python library** — use from your own harness / tool:
16
  from ctx import recommend_bundle, graph_query, wiki_search
src/ctx/__main__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """Run the model-agnostic harness via ``python -m ctx``."""
2
+
3
+ from ctx.cli.run import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ raise SystemExit(main())
src/ctx/api.py CHANGED
@@ -20,7 +20,8 @@ Four delivery paths, in increasing order of coupling to ctx:
20
 
21
  3. **Use ``ctx run`` directly.** The full harness-over-LiteLLM
22
  experience, no host-side code required. Good if you don't already
23
- have a loop.
 
24
 
25
  4. **Use the LoopFlow adapter.** If another runner already owns
26
  plan/act/observe, call ``python -m ctx.adapters.loopflow`` or
 
20
 
21
  3. **Use ``ctx run`` directly.** The full harness-over-LiteLLM
22
  experience, no host-side code required. Good if you don't already
23
+ have a loop. ``python -m ctx run`` reaches the same CLI when the
24
+ console script is unavailable.
25
 
26
  4. **Use the LoopFlow adapter.** If another runner already owns
27
  plan/act/observe, call ``python -m ctx.adapters.loopflow`` or
src/ctx/cli/__init__.py CHANGED
@@ -15,4 +15,6 @@ New CLIs (harness-facing, added H7):
15
  ctx run - drive any model autonomously against a task
16
  ctx resume - continue a previous session
17
  ctx sessions - list / inspect sessions
 
 
18
  """
 
15
  ctx run - drive any model autonomously against a task
16
  ctx resume - continue a previous session
17
  ctx sessions - list / inspect sessions
18
+
19
+ The package entrypoint ``python -m ctx`` delegates to the same harness CLI.
20
  """
src/ctx/telemetry/__init__.py CHANGED
@@ -38,9 +38,7 @@ RETENTION_STATUS_SCHEMA_VERSION = "ctx.telemetry.retention_status.v1"
38
  DEFAULT_TELEMETRY_PATH = Path(os.path.expanduser("~/.ctx/telemetry/events.jsonl"))
39
  DEFAULT_EXPORT_PATH = Path(os.path.expanduser("~/.ctx/telemetry/exported-events.jsonl"))
40
  DEFAULT_METRICS_PATH = Path(os.path.expanduser("~/.ctx/telemetry/metrics.jsonl"))
41
- DEFAULT_METRICS_EXPORT_PATH = Path(
42
- os.path.expanduser("~/.ctx/telemetry/exported-metrics.jsonl")
43
- )
44
  DEFAULT_OTLP_LOGS_ENDPOINT = "http://localhost:4318/v1/logs"
45
  DEFAULT_OTLP_METRICS_ENDPOINT = "http://localhost:4318/v1/metrics"
46
  DEFAULT_PRIVACY_MODE = "local_redacted"
@@ -71,31 +69,38 @@ _DEFAULT_HISTOGRAM_BOUNDS = (
71
  )
72
  _PRIVATE_DIR_MODE = 0o700
73
  _PRIVATE_FILE_MODE = 0o600
74
- _RAW_VALUE_KEYS = frozenset({
75
- "command",
76
- "command_output",
77
- "cwd",
78
- "goal",
79
- "input",
80
- "model_response",
81
- "output",
82
- "path",
83
- "prompt",
84
- "query",
85
- "raw_input",
86
- "raw_prompt",
87
- "repo",
88
- "response",
89
- "stderr",
90
- "stdout",
91
- "task",
92
- "tool_args",
93
- "tool_input",
94
- "tool_output",
95
- })
 
 
 
96
  _SCALAR_TYPES = (str, int, float, bool, type(None))
97
 
98
 
 
 
 
 
99
  @dataclass(frozen=True)
100
  class TelemetryEvent:
101
  """One canonical ctx telemetry event."""
@@ -781,7 +786,9 @@ def _record_metric(
781
  print(f"ctx telemetry: failed to write metric ({type(exc).__name__})", file=sys.stderr)
782
  return None
783
  if settings["metric_export_enabled"]:
784
- _export_recorded_metric(metric, settings=settings, source_path=target, trusted_root=trusted_root)
 
 
785
  return metric
786
 
787
 
@@ -1012,9 +1019,7 @@ def export_metrics(
1012
  trusted_root=trusted_root,
1013
  )
1014
  checkpoint_after_metric_id = last_metric.metric_id
1015
- checkpoint_advanced = (
1016
- checkpoint_after_metric_id != pending.checkpoint_before_metric_id
1017
- )
1018
  status_path = _metric_export_status_path(
1019
  settings,
1020
  source_path=source_path,
@@ -1080,9 +1085,7 @@ def preview_metrics_export(
1080
  include_exported=include_exported,
1081
  )
1082
  last_metric_id = (
1083
- pending.metrics[-1].metric_id
1084
- if pending.metrics
1085
- else pending.checkpoint_before_metric_id
1086
  )
1087
  status_path = _metric_export_status_path(
1088
  settings,
@@ -1142,7 +1145,9 @@ def preview_export(
1142
  trusted_root=trusted_root,
1143
  include_exported=include_exported,
1144
  )
1145
- last_event_id = pending.events[-1].event_id if pending.events else pending.checkpoint_before_event_id
 
 
1146
  status_path = _export_status_path(
1147
  settings,
1148
  source_path=source_path,
@@ -1229,7 +1234,11 @@ def _ctx_version() -> str | None:
1229
  try:
1230
  return package_version("claude-ctx")
1231
  except PackageNotFoundError:
1232
- return None
 
 
 
 
1233
 
1234
 
1235
  def _resolve_path(path: Path, *, trusted_root: Path | None = None) -> Path:
@@ -1288,9 +1297,7 @@ def _settings(config: Mapping[str, Any] | None) -> dict[str, Any]:
1288
  "otlp_timeout_seconds": float(_mapping_get(otlp, "timeout_seconds", 5.0)),
1289
  "otlp_service_name": str(_mapping_get(otlp, "service_name", "ctx")),
1290
  "otlp_service_namespace": str(_mapping_get(otlp, "service_namespace", "ctx")),
1291
- "otlp_deployment_environment": str(
1292
- _mapping_get(otlp, "deployment_environment", "local")
1293
- ),
1294
  "max_payload_keys": int(
1295
  _mapping_get(limits, "max_payload_keys", _MAX_PAYLOAD_KEYS),
1296
  ),
@@ -1342,9 +1349,7 @@ def _metric_settings(config: Mapping[str, Any] | None) -> dict[str, Any]:
1342
  "otlp_timeout_seconds": float(_mapping_get(otlp, "timeout_seconds", 5.0)),
1343
  "otlp_service_name": str(_mapping_get(otlp, "service_name", "ctx")),
1344
  "otlp_service_namespace": str(_mapping_get(otlp, "service_namespace", "ctx")),
1345
- "otlp_deployment_environment": str(
1346
- _mapping_get(otlp, "deployment_environment", "local")
1347
- ),
1348
  "histogram_bounds": _histogram_bounds(metrics),
1349
  "max_payload_keys": int(
1350
  _mapping_get(limits, "max_payload_keys", _MAX_PAYLOAD_KEYS),
@@ -1358,9 +1363,7 @@ def _metric_settings(config: Mapping[str, Any] | None) -> dict[str, Any]:
1358
  def _retention_settings(config: Mapping[str, Any] | None) -> dict[str, Any]:
1359
  raw = dict(config or _config_get("telemetry", {}) or {})
1360
  raw_retention = raw.get("retention")
1361
- retention: Mapping[str, Any] = (
1362
- raw_retention if isinstance(raw_retention, Mapping) else {}
1363
- )
1364
  events = retention.get("events")
1365
  metrics = retention.get("metrics")
1366
  return {
@@ -1387,16 +1390,8 @@ def _retention_policy(
1387
  policy: Mapping[str, Any] = signal_policy if isinstance(signal_policy, Mapping) else {}
1388
  raw_max_age_days = _mapping_get(policy, "max_age_days", None)
1389
  raw_max_records = _mapping_get(policy, "max_records", None)
1390
- max_age_days = (
1391
- max(0, int(raw_max_age_days))
1392
- if raw_max_age_days not in (None, "")
1393
- else None
1394
- )
1395
- max_records = (
1396
- max(0, int(raw_max_records))
1397
- if raw_max_records not in (None, "")
1398
- else None
1399
- )
1400
  return max_age_days, max_records
1401
 
1402
 
@@ -1590,9 +1585,7 @@ def _apply_retention_policy(
1590
  else:
1591
  kept.append(record)
1592
  effective_max_records = (
1593
- max(max_records, min_keep_records)
1594
- if max_records is not None and max_records > 0
1595
- else None
1596
  )
1597
  if effective_max_records is not None and len(kept) > effective_max_records:
1598
  overflow = len(kept) - effective_max_records
@@ -1610,9 +1603,7 @@ def _rewrite_retention_file(
1610
  drop_malformed: bool,
1611
  ) -> None:
1612
  lines: list[tuple[int, str]] = [
1613
- (record.index, record.raw_line)
1614
- for record in records
1615
- if record.index in kept_by_index
1616
  ]
1617
  if not drop_malformed:
1618
  lines.extend(malformed_lines)
@@ -2469,7 +2460,9 @@ def _otlp_logs_payload(events: list[TelemetryEvent], settings: Mapping[str, Any]
2469
  "scopeLogs": [
2470
  {
2471
  "scope": {"name": "ctx.telemetry", "version": SCHEMA_VERSION},
2472
- "logRecords": [_otlp_log_record(event, settings=settings) for event in events],
 
 
2473
  }
2474
  ],
2475
  }
@@ -2494,8 +2487,7 @@ def _otlp_metrics_payload(
2494
  {
2495
  "scope": {"name": "ctx.telemetry", "version": METRIC_SCHEMA_VERSION},
2496
  "metrics": [
2497
- _otlp_metric_record(metric, settings=settings)
2498
- for metric in metrics
2499
  ],
2500
  }
2501
  ],
@@ -2639,10 +2631,7 @@ def _iso_to_unix_nanos(value: str) -> int:
2639
 
2640
 
2641
  def _otlp_attributes(attributes: Mapping[str, Any]) -> list[dict[str, Any]]:
2642
- return [
2643
- {"key": key, "value": _otlp_value(value)}
2644
- for key, value in sorted(attributes.items())
2645
- ]
2646
 
2647
 
2648
  def _otlp_value(value: Any) -> dict[str, Any]:
@@ -2679,8 +2668,8 @@ def _sanitize_payload(
2679
  if secret_key_like(key):
2680
  sanitized[key] = "[redacted]"
2681
  continue
2682
- normalized = key.lower().replace("-", "_")
2683
- if privacy_mode == DEFAULT_PRIVACY_MODE and normalized in _RAW_VALUE_KEYS:
2684
  if value is not None:
2685
  sanitized[f"{key}_hash"] = hash_identifier(str(value), salt=hash_salt)
2686
  continue
 
38
  DEFAULT_TELEMETRY_PATH = Path(os.path.expanduser("~/.ctx/telemetry/events.jsonl"))
39
  DEFAULT_EXPORT_PATH = Path(os.path.expanduser("~/.ctx/telemetry/exported-events.jsonl"))
40
  DEFAULT_METRICS_PATH = Path(os.path.expanduser("~/.ctx/telemetry/metrics.jsonl"))
41
+ DEFAULT_METRICS_EXPORT_PATH = Path(os.path.expanduser("~/.ctx/telemetry/exported-metrics.jsonl"))
 
 
42
  DEFAULT_OTLP_LOGS_ENDPOINT = "http://localhost:4318/v1/logs"
43
  DEFAULT_OTLP_METRICS_ENDPOINT = "http://localhost:4318/v1/metrics"
44
  DEFAULT_PRIVACY_MODE = "local_redacted"
 
69
  )
70
  _PRIVATE_DIR_MODE = 0o700
71
  _PRIVATE_FILE_MODE = 0o600
72
+ _RAW_VALUE_KEYS = frozenset(
73
+ {
74
+ "command",
75
+ "command_output",
76
+ "cwd",
77
+ "goal",
78
+ "input",
79
+ "model_response",
80
+ "output",
81
+ "path",
82
+ "paths",
83
+ "prompt",
84
+ "query",
85
+ "raw_input",
86
+ "raw_prompt",
87
+ "repo",
88
+ "response",
89
+ "stderr",
90
+ "stdout",
91
+ "task",
92
+ "tool_args",
93
+ "tool_input",
94
+ "tool_output",
95
+ }
96
+ )
97
  _SCALAR_TYPES = (str, int, float, bool, type(None))
98
 
99
 
100
+ def _raw_value_key_like(normalized_key: str) -> bool:
101
+ return normalized_key in _RAW_VALUE_KEYS or normalized_key.endswith(("_path", "_paths"))
102
+
103
+
104
  @dataclass(frozen=True)
105
  class TelemetryEvent:
106
  """One canonical ctx telemetry event."""
 
786
  print(f"ctx telemetry: failed to write metric ({type(exc).__name__})", file=sys.stderr)
787
  return None
788
  if settings["metric_export_enabled"]:
789
+ _export_recorded_metric(
790
+ metric, settings=settings, source_path=target, trusted_root=trusted_root
791
+ )
792
  return metric
793
 
794
 
 
1019
  trusted_root=trusted_root,
1020
  )
1021
  checkpoint_after_metric_id = last_metric.metric_id
1022
+ checkpoint_advanced = checkpoint_after_metric_id != pending.checkpoint_before_metric_id
 
 
1023
  status_path = _metric_export_status_path(
1024
  settings,
1025
  source_path=source_path,
 
1085
  include_exported=include_exported,
1086
  )
1087
  last_metric_id = (
1088
+ pending.metrics[-1].metric_id if pending.metrics else pending.checkpoint_before_metric_id
 
 
1089
  )
1090
  status_path = _metric_export_status_path(
1091
  settings,
 
1145
  trusted_root=trusted_root,
1146
  include_exported=include_exported,
1147
  )
1148
+ last_event_id = (
1149
+ pending.events[-1].event_id if pending.events else pending.checkpoint_before_event_id
1150
+ )
1151
  status_path = _export_status_path(
1152
  settings,
1153
  source_path=source_path,
 
1234
  try:
1235
  return package_version("claude-ctx")
1236
  except PackageNotFoundError:
1237
+ try:
1238
+ from ctx import __version__
1239
+ except (ImportError, AttributeError):
1240
+ return None
1241
+ return __version__ or None
1242
 
1243
 
1244
  def _resolve_path(path: Path, *, trusted_root: Path | None = None) -> Path:
 
1297
  "otlp_timeout_seconds": float(_mapping_get(otlp, "timeout_seconds", 5.0)),
1298
  "otlp_service_name": str(_mapping_get(otlp, "service_name", "ctx")),
1299
  "otlp_service_namespace": str(_mapping_get(otlp, "service_namespace", "ctx")),
1300
+ "otlp_deployment_environment": str(_mapping_get(otlp, "deployment_environment", "local")),
 
 
1301
  "max_payload_keys": int(
1302
  _mapping_get(limits, "max_payload_keys", _MAX_PAYLOAD_KEYS),
1303
  ),
 
1349
  "otlp_timeout_seconds": float(_mapping_get(otlp, "timeout_seconds", 5.0)),
1350
  "otlp_service_name": str(_mapping_get(otlp, "service_name", "ctx")),
1351
  "otlp_service_namespace": str(_mapping_get(otlp, "service_namespace", "ctx")),
1352
+ "otlp_deployment_environment": str(_mapping_get(otlp, "deployment_environment", "local")),
 
 
1353
  "histogram_bounds": _histogram_bounds(metrics),
1354
  "max_payload_keys": int(
1355
  _mapping_get(limits, "max_payload_keys", _MAX_PAYLOAD_KEYS),
 
1363
  def _retention_settings(config: Mapping[str, Any] | None) -> dict[str, Any]:
1364
  raw = dict(config or _config_get("telemetry", {}) or {})
1365
  raw_retention = raw.get("retention")
1366
+ retention: Mapping[str, Any] = raw_retention if isinstance(raw_retention, Mapping) else {}
 
 
1367
  events = retention.get("events")
1368
  metrics = retention.get("metrics")
1369
  return {
 
1390
  policy: Mapping[str, Any] = signal_policy if isinstance(signal_policy, Mapping) else {}
1391
  raw_max_age_days = _mapping_get(policy, "max_age_days", None)
1392
  raw_max_records = _mapping_get(policy, "max_records", None)
1393
+ max_age_days = max(0, int(raw_max_age_days)) if raw_max_age_days not in (None, "") else None
1394
+ max_records = max(0, int(raw_max_records)) if raw_max_records not in (None, "") else None
 
 
 
 
 
 
 
 
1395
  return max_age_days, max_records
1396
 
1397
 
 
1585
  else:
1586
  kept.append(record)
1587
  effective_max_records = (
1588
+ max(max_records, min_keep_records) if max_records is not None and max_records > 0 else None
 
 
1589
  )
1590
  if effective_max_records is not None and len(kept) > effective_max_records:
1591
  overflow = len(kept) - effective_max_records
 
1603
  drop_malformed: bool,
1604
  ) -> None:
1605
  lines: list[tuple[int, str]] = [
1606
+ (record.index, record.raw_line) for record in records if record.index in kept_by_index
 
 
1607
  ]
1608
  if not drop_malformed:
1609
  lines.extend(malformed_lines)
 
2460
  "scopeLogs": [
2461
  {
2462
  "scope": {"name": "ctx.telemetry", "version": SCHEMA_VERSION},
2463
+ "logRecords": [
2464
+ _otlp_log_record(event, settings=settings) for event in events
2465
+ ],
2466
  }
2467
  ],
2468
  }
 
2487
  {
2488
  "scope": {"name": "ctx.telemetry", "version": METRIC_SCHEMA_VERSION},
2489
  "metrics": [
2490
+ _otlp_metric_record(metric, settings=settings) for metric in metrics
 
2491
  ],
2492
  }
2493
  ],
 
2631
 
2632
 
2633
  def _otlp_attributes(attributes: Mapping[str, Any]) -> list[dict[str, Any]]:
2634
+ return [{"key": key, "value": _otlp_value(value)} for key, value in sorted(attributes.items())]
 
 
 
2635
 
2636
 
2637
  def _otlp_value(value: Any) -> dict[str, Any]:
 
2668
  if secret_key_like(key):
2669
  sanitized[key] = "[redacted]"
2670
  continue
2671
+ normalized = key.lower().replace("-", "_").replace(".", "_")
2672
+ if privacy_mode == DEFAULT_PRIVACY_MODE and _raw_value_key_like(normalized):
2673
  if value is not None:
2674
  sanitized[f"{key}_hash"] = hash_identifier(str(value), salt=hash_salt)
2675
  continue
src/embedding_backend.py CHANGED
@@ -14,7 +14,10 @@ backend-agnostic. Both implementations return L2-normalised float32 vectors
14
  so downstream cosine similarity is a single dot product.
15
 
16
  Backend selection is centralised in ``get_embedder(name)``; callers pass the
17
- string from ``ctx_config.intake.embedding.backend``. Heavy imports
 
 
 
18
  (``sentence_transformers``, ``requests``) happen lazily inside the concrete
19
  class to keep the module cheap to import.
20
 
@@ -150,9 +153,7 @@ class OllamaEmbedder:
150
  def __post_init__(self) -> None:
151
  parsed = urlparse(self.base_url)
152
  if parsed.scheme not in ("http", "https"):
153
- raise ValueError(
154
- f"base_url scheme must be http or https: {self.base_url!r}"
155
- )
156
  host = (parsed.hostname or "").lower()
157
  if not host:
158
  raise ValueError(f"base_url has no host: {self.base_url!r}")
@@ -197,9 +198,7 @@ class OllamaEmbedder:
197
  except Exception as exc:
198
  raise OllamaEmbedderError(idx, str(exc)) from exc
199
  if "embedding" not in payload:
200
- raise OllamaEmbedderError(
201
- idx, f"response missing 'embedding' key: {payload!r}"
202
- )
203
  rows.append(payload["embedding"])
204
  return _l2_normalize(np.asarray(rows, dtype=np.float32))
205
 
@@ -222,12 +221,14 @@ def get_embedder(
222
  if key in ("", "sentence-transformers", "st", "sbert"):
223
  return SentenceTransformerEmbedder(model_name=model or DEFAULT_ST_MODEL)
224
  if key in ("ollama", "ol"):
 
 
 
225
  return OllamaEmbedder(
226
  model_name=model or DEFAULT_OLLAMA_MODEL,
227
- base_url=base_url or os.environ.get("OLLAMA_URL", DEFAULT_OLLAMA_URL),
228
  allow_remote=allow_remote,
229
  )
230
  raise ValueError(
231
- f"unknown embedding backend {backend!r}; expected "
232
- f"'sentence-transformers' or 'ollama'"
233
  )
 
14
  so downstream cosine similarity is a single dot product.
15
 
16
  Backend selection is centralised in ``get_embedder(name)``; callers pass the
17
+ string from ``ctx_config.intake.embedding.backend``. For the Ollama backend,
18
+ ``intake.embedding.base_url`` wins first, then ``OLLAMA_URL`` when set, then
19
+ ``http://localhost:11434``. An empty or malformed ``OLLAMA_URL`` is treated as
20
+ configuration and rejected instead of silently falling back. Heavy imports
21
  (``sentence_transformers``, ``requests``) happen lazily inside the concrete
22
  class to keep the module cheap to import.
23
 
 
153
  def __post_init__(self) -> None:
154
  parsed = urlparse(self.base_url)
155
  if parsed.scheme not in ("http", "https"):
156
+ raise ValueError(f"base_url scheme must be http or https: {self.base_url!r}")
 
 
157
  host = (parsed.hostname or "").lower()
158
  if not host:
159
  raise ValueError(f"base_url has no host: {self.base_url!r}")
 
198
  except Exception as exc:
199
  raise OllamaEmbedderError(idx, str(exc)) from exc
200
  if "embedding" not in payload:
201
+ raise OllamaEmbedderError(idx, f"response missing 'embedding' key: {payload!r}")
 
 
202
  rows.append(payload["embedding"])
203
  return _l2_normalize(np.asarray(rows, dtype=np.float32))
204
 
 
221
  if key in ("", "sentence-transformers", "st", "sbert"):
222
  return SentenceTransformerEmbedder(model_name=model or DEFAULT_ST_MODEL)
223
  if key in ("ollama", "ol"):
224
+ configured_base_url = (
225
+ os.environ["OLLAMA_URL"] if "OLLAMA_URL" in os.environ else DEFAULT_OLLAMA_URL
226
+ )
227
  return OllamaEmbedder(
228
  model_name=model or DEFAULT_OLLAMA_MODEL,
229
+ base_url=base_url or configured_base_url,
230
  allow_remote=allow_remote,
231
  )
232
  raise ValueError(
233
+ f"unknown embedding backend {backend!r}; expected 'sentence-transformers' or 'ollama'"
 
234
  )