Stevesolun commited on
Commit
b9238de
·
verified ·
1 Parent(s): 916f576

Add files using upload-large-folder tool

Browse files
src/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
- __version__ = "0.7.7"
 
1
  """ctx — skill and agent recommendation for Claude Code."""
2
 
3
+ __version__ = "0.7.9"
src/ctx/__init__.py CHANGED
@@ -30,7 +30,7 @@ Package layout:
30
  ctx.utils - low-level primitives (safe names, atomic IO)
31
  """
32
 
33
- __version__ = "0.7.7"
34
 
35
 
36
  # Public library surface — anything listed here is safe for third-
 
30
  ctx.utils - low-level primitives (safe names, atomic IO)
31
  """
32
 
33
+ __version__ = "0.7.9"
34
 
35
 
36
  # Public library surface — anything listed here is safe for third-
src/ctx/adapters/generic/ctx_core_tools.py CHANGED
@@ -135,6 +135,20 @@ class CtxCoreToolbox:
135
  "minimum": 1,
136
  "maximum": 5,
137
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  },
139
  "required": ["query"],
140
  },
@@ -256,6 +270,10 @@ class CtxCoreToolbox:
256
  return self._dispatch_lifecycle(args, "load_entity")
257
  if local_name == "mark_entity_used":
258
  return self._dispatch_lifecycle(args, "mark_entity_used")
 
 
 
 
259
  if local_name == "unload_entity":
260
  return self._dispatch_lifecycle(args, "unload_entity")
261
  if local_name == "session_end":
@@ -331,7 +349,24 @@ class CtxCoreToolbox:
331
  }
332
  for r in raw
333
  ]
334
- return json.dumps({"query": query, "tags": tags, "results": results})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
 
336
  def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
337
  seeds_raw = args.get("seeds") or []
@@ -465,6 +500,28 @@ class CtxCoreToolbox:
465
  slug=str(args.get("slug") or ""),
466
  reason=str(args.get("reason") or "") or None,
467
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  elif name == "session_end":
469
  result = self._lifecycle.end_session(
470
  session_id=str(args.get("session_id") or ""),
@@ -569,6 +626,48 @@ def _query_to_tags(query: str) -> list[str]:
569
  return query_to_tags(query)
570
 
571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  def _lifecycle_tool_definitions() -> list[ToolDefinition]:
573
  entity_enum = list(RECOMMENDABLE_ENTITY_TYPES)
574
  session = {
@@ -635,6 +734,63 @@ def _lifecycle_tool_definitions() -> list[ToolDefinition]:
635
  "required": ["session_id", "entity_type", "slug"],
636
  },
637
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
  ToolDefinition(
639
  name=f"{_NAMESPACE}unload_entity",
640
  description=(
@@ -669,8 +825,9 @@ def _lifecycle_tool_definitions() -> list[ToolDefinition]:
669
  name=f"{_NAMESPACE}session_state",
670
  description=(
671
  "Read the current lifecycle state for a session, including "
672
- "loaded entities, used entities, and unload candidates that "
673
- "were loaded but have no usage evidence."
 
674
  ),
675
  parameters={
676
  "type": "object",
 
135
  "minimum": 1,
136
  "maximum": 5,
137
  },
138
+ "model_provider": {
139
+ "type": "string",
140
+ "description": (
141
+ "Optional custom/local model provider, used only "
142
+ "for companion harness recommendations."
143
+ ),
144
+ },
145
+ "model": {
146
+ "type": "string",
147
+ "description": (
148
+ "Optional model slug, used only for companion "
149
+ "harness recommendations."
150
+ ),
151
+ },
152
  },
153
  "required": ["query"],
154
  },
 
270
  return self._dispatch_lifecycle(args, "load_entity")
271
  if local_name == "mark_entity_used":
272
  return self._dispatch_lifecycle(args, "mark_entity_used")
273
+ if local_name == "record_validation":
274
+ return self._dispatch_lifecycle(args, "record_validation")
275
+ if local_name == "record_escalation":
276
+ return self._dispatch_lifecycle(args, "record_escalation")
277
  if local_name == "unload_entity":
278
  return self._dispatch_lifecycle(args, "unload_entity")
279
  if local_name == "session_end":
 
349
  }
350
  for r in raw
351
  ]
352
+ model_provider = _optional_str(args.get("model_provider"))
353
+ model = _optional_str(args.get("model"))
354
+ companion_harnesses = (
355
+ _recommend_companion_harnesses(
356
+ query,
357
+ top_k=top_k,
358
+ model_provider=model_provider,
359
+ model=model,
360
+ )
361
+ if model_provider or model
362
+ else []
363
+ )
364
+ return json.dumps({
365
+ "query": query,
366
+ "tags": tags,
367
+ "results": results,
368
+ "companion_harnesses": companion_harnesses,
369
+ })
370
 
371
  def _dispatch_graph_query(self, args: dict[str, Any]) -> str:
372
  seeds_raw = args.get("seeds") or []
 
500
  slug=str(args.get("slug") or ""),
501
  reason=str(args.get("reason") or "") or None,
502
  )
503
+ elif name == "record_validation":
504
+ result = self._lifecycle.record_validation(
505
+ session_id=str(args.get("session_id") or ""),
506
+ check_name=str(args.get("check_name") or ""),
507
+ status=str(args.get("status") or ""),
508
+ command=str(args.get("command") or "") or None,
509
+ summary=str(args.get("summary") or "") or None,
510
+ entity_type=str(args.get("entity_type") or "") or None,
511
+ slug=str(args.get("slug") or "") or None,
512
+ payload=_dict_arg(args.get("payload")),
513
+ )
514
+ elif name == "record_escalation":
515
+ result = self._lifecycle.record_escalation(
516
+ session_id=str(args.get("session_id") or ""),
517
+ trigger=str(args.get("trigger") or ""),
518
+ reason=str(args.get("reason") or ""),
519
+ severity=str(args.get("severity") or "") or None,
520
+ status=str(args.get("status") or "") or None,
521
+ entity_type=str(args.get("entity_type") or "") or None,
522
+ slug=str(args.get("slug") or "") or None,
523
+ payload=_dict_arg(args.get("payload")),
524
+ )
525
  elif name == "session_end":
526
  result = self._lifecycle.end_session(
527
  session_id=str(args.get("session_id") or ""),
 
626
  return query_to_tags(query)
627
 
628
 
629
+ def _optional_str(raw: Any) -> str | None:
630
+ if not isinstance(raw, str):
631
+ return None
632
+ value = raw.strip()
633
+ return value or None
634
+
635
+
636
+ def _recommend_companion_harnesses(
637
+ query: str,
638
+ *,
639
+ top_k: int,
640
+ model_provider: str | None,
641
+ model: str | None,
642
+ ) -> list[dict[str, Any]]:
643
+ try:
644
+ from ctx_init import recommend_harnesses # noqa: PLC0415
645
+
646
+ raw = recommend_harnesses(
647
+ query,
648
+ top_k=top_k,
649
+ model_provider=model_provider,
650
+ model=model,
651
+ )
652
+ except Exception as exc: # noqa: BLE001
653
+ _logger.warning("ctx harness companion recommendation failed: %s", exc)
654
+ return []
655
+ return [
656
+ {
657
+ "name": row.get("name"),
658
+ "type": "harness",
659
+ "fit_score": row.get("fit_score"),
660
+ "normalized_score": row.get("normalized_score"),
661
+ "matching_tags": row.get("matching_tags", []),
662
+ "provider_match": row.get("provider_match"),
663
+ "detail_url": row.get("detail_url"),
664
+ "install_command": row.get("install_command"),
665
+ }
666
+ for row in raw
667
+ if row.get("name")
668
+ ]
669
+
670
+
671
  def _lifecycle_tool_definitions() -> list[ToolDefinition]:
672
  entity_enum = list(RECOMMENDABLE_ENTITY_TYPES)
673
  session = {
 
734
  "required": ["session_id", "entity_type", "slug"],
735
  },
736
  ),
737
+ ToolDefinition(
738
+ name=f"{_NAMESPACE}record_validation",
739
+ description=(
740
+ "Record a harness validation check result outside the chat "
741
+ "transcript so state can be inspected and replayed."
742
+ ),
743
+ parameters={
744
+ "type": "object",
745
+ "properties": {
746
+ "session_id": session,
747
+ "check_name": {
748
+ "type": "string",
749
+ "description": "Stable name of the check that ran.",
750
+ },
751
+ "status": {
752
+ "type": "string",
753
+ "enum": ["passed", "failed", "skipped", "error"],
754
+ },
755
+ "command": {"type": "string"},
756
+ "summary": {"type": "string"},
757
+ "entity_type": entity_type,
758
+ "slug": slug,
759
+ "payload": {"type": "object"},
760
+ },
761
+ "required": ["session_id", "check_name", "status"],
762
+ },
763
+ ),
764
+ ToolDefinition(
765
+ name=f"{_NAMESPACE}record_escalation",
766
+ description=(
767
+ "Record that a predefined escalation condition was reached "
768
+ "so the host can ask the user instead of hiding state in chat."
769
+ ),
770
+ parameters={
771
+ "type": "object",
772
+ "properties": {
773
+ "session_id": session,
774
+ "trigger": {
775
+ "type": "string",
776
+ "description": "Stable escalation trigger name.",
777
+ },
778
+ "reason": {"type": "string"},
779
+ "severity": {
780
+ "type": "string",
781
+ "enum": ["info", "warning", "blocking"],
782
+ },
783
+ "status": {
784
+ "type": "string",
785
+ "enum": ["open", "resolved", "ignored"],
786
+ },
787
+ "entity_type": entity_type,
788
+ "slug": slug,
789
+ "payload": {"type": "object"},
790
+ },
791
+ "required": ["session_id", "trigger", "reason"],
792
+ },
793
+ ),
794
  ToolDefinition(
795
  name=f"{_NAMESPACE}unload_entity",
796
  description=(
 
825
  name=f"{_NAMESPACE}session_state",
826
  description=(
827
  "Read the current lifecycle state for a session, including "
828
+ "loaded entities, used entities, validation checks, "
829
+ "escalations, and unload candidates that were loaded but "
830
+ "have no usage evidence."
831
  ),
832
  parameters={
833
  "type": "object",
src/ctx/adapters/generic/runtime_lifecycle.py CHANGED
@@ -17,6 +17,8 @@ from ctx.utils._fs_utils import reject_symlink_path
17
 
18
  _SESSION_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
19
  _ENTITY_TYPES = set(RECOMMENDABLE_ENTITY_TYPES)
 
 
20
 
21
 
22
  @dataclass(frozen=True)
@@ -91,6 +93,54 @@ class RuntimeLifecycleStore:
91
  reason=reason,
92
  )
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  def end_session(
95
  self,
96
  *,
@@ -114,14 +164,27 @@ class RuntimeLifecycleStore:
114
  session_id = _validate_session_id(session_id)
115
  loaded: dict[tuple[str, str], dict[str, Any]] = {}
116
  unloaded: list[dict[str, Any]] = []
 
 
117
  min_age = max(0.0, float(min_unused_seconds))
118
  now = time.time()
 
119
 
120
  for event in self._events_for_session(session_id):
 
 
 
 
 
 
 
 
 
 
121
  key = (str(event.get("entity_type") or ""), str(event.get("slug") or ""))
122
  if not key[0] or not key[1]:
123
  continue
124
- if event.get("action") == "load_requested":
125
  loaded[key] = {
126
  "entity_type": key[0],
127
  "slug": key[1],
@@ -132,14 +195,15 @@ class RuntimeLifecycleStore:
132
  "use_count": 0,
133
  "last_used_at": None,
134
  "evidence": [],
 
135
  }
136
- elif event.get("action") == "used" and key in loaded:
137
  loaded[key]["used"] = True
138
  loaded[key]["use_count"] = int(loaded[key]["use_count"]) + 1
139
  loaded[key]["last_used_at"] = event.get("created_at")
140
  if event.get("evidence"):
141
  loaded[key]["evidence"].append(event["evidence"])
142
- elif event.get("action") == "unload_requested":
143
  current = loaded.pop(key, None)
144
  unloaded.append({
145
  "entity_type": key[0],
@@ -154,6 +218,7 @@ class RuntimeLifecycleStore:
154
  unload_candidates = [
155
  entry for entry in loaded_entries
156
  if not entry["used"]
 
157
  and (min_age == 0 or now - float(entry.get("loaded_at_epoch") or 0) >= min_age)
158
  ]
159
  return {
@@ -163,6 +228,14 @@ class RuntimeLifecycleStore:
163
  "used": [entry for entry in loaded_entries if entry["used"]],
164
  "unload_candidates": unload_candidates,
165
  "unloaded": unloaded,
 
 
 
 
 
 
 
 
166
  }
167
 
168
  def _record(self, **event: Any) -> dict[str, Any]:
@@ -228,3 +301,53 @@ def _validate_slug(raw: str) -> str:
228
  value = raw.strip()
229
  validate_skill_name(value)
230
  return value
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  _SESSION_RE = re.compile(r"^[A-Za-z0-9_.:-]{1,128}$")
19
  _ENTITY_TYPES = set(RECOMMENDABLE_ENTITY_TYPES)
20
+ _VALIDATION_STATUSES = {"passed", "failed", "skipped", "error"}
21
+ _ESCALATION_STATUSES = {"open", "resolved", "ignored"}
22
 
23
 
24
  @dataclass(frozen=True)
 
93
  reason=reason,
94
  )
95
 
96
+ def record_validation(
97
+ self,
98
+ *,
99
+ session_id: str,
100
+ check_name: str,
101
+ status: str,
102
+ command: str | None = None,
103
+ summary: str | None = None,
104
+ entity_type: str | None = None,
105
+ slug: str | None = None,
106
+ payload: dict[str, Any] | None = None,
107
+ ) -> dict[str, Any]:
108
+ return self._record(
109
+ action="validation",
110
+ session_id=session_id,
111
+ check_name=_validate_nonempty(check_name, "check_name"),
112
+ status=_validate_choice(status, _VALIDATION_STATUSES, "status"),
113
+ command=command,
114
+ summary=summary,
115
+ entity_type=entity_type,
116
+ slug=slug,
117
+ payload=payload or {},
118
+ )
119
+
120
+ def record_escalation(
121
+ self,
122
+ *,
123
+ session_id: str,
124
+ trigger: str,
125
+ reason: str,
126
+ severity: str | None = None,
127
+ status: str | None = None,
128
+ entity_type: str | None = None,
129
+ slug: str | None = None,
130
+ payload: dict[str, Any] | None = None,
131
+ ) -> dict[str, Any]:
132
+ return self._record(
133
+ action="escalation",
134
+ session_id=session_id,
135
+ trigger=_validate_nonempty(trigger, "trigger"),
136
+ reason=_validate_nonempty(reason, "reason"),
137
+ severity=severity or "blocking",
138
+ status=_validate_choice(status or "open", _ESCALATION_STATUSES, "status"),
139
+ entity_type=entity_type,
140
+ slug=slug,
141
+ payload=payload or {},
142
+ )
143
+
144
  def end_session(
145
  self,
146
  *,
 
164
  session_id = _validate_session_id(session_id)
165
  loaded: dict[tuple[str, str], dict[str, Any]] = {}
166
  unloaded: list[dict[str, Any]] = []
167
+ validations: list[dict[str, Any]] = []
168
+ escalations: list[dict[str, Any]] = []
169
  min_age = max(0.0, float(min_unused_seconds))
170
  now = time.time()
171
+ latest_dev_event_epoch: float | None = None
172
 
173
  for event in self._events_for_session(session_id):
174
+ action = event.get("action")
175
+ if action == "dev_event":
176
+ latest_dev_event_epoch = float(event.get("created_at_epoch") or 0)
177
+ continue
178
+ if action == "validation":
179
+ validations.append(_validation_state(event))
180
+ continue
181
+ if action == "escalation":
182
+ escalations.append(_escalation_state(event))
183
+ continue
184
  key = (str(event.get("entity_type") or ""), str(event.get("slug") or ""))
185
  if not key[0] or not key[1]:
186
  continue
187
+ if action == "load_requested":
188
  loaded[key] = {
189
  "entity_type": key[0],
190
  "slug": key[1],
 
195
  "use_count": 0,
196
  "last_used_at": None,
197
  "evidence": [],
198
+ "dev_event_epoch": latest_dev_event_epoch,
199
  }
200
+ elif action == "used" and key in loaded:
201
  loaded[key]["used"] = True
202
  loaded[key]["use_count"] = int(loaded[key]["use_count"]) + 1
203
  loaded[key]["last_used_at"] = event.get("created_at")
204
  if event.get("evidence"):
205
  loaded[key]["evidence"].append(event["evidence"])
206
+ elif action == "unload_requested":
207
  current = loaded.pop(key, None)
208
  unloaded.append({
209
  "entity_type": key[0],
 
218
  unload_candidates = [
219
  entry for entry in loaded_entries
220
  if not entry["used"]
221
+ and _loaded_before_latest_dev_event(entry, latest_dev_event_epoch)
222
  and (min_age == 0 or now - float(entry.get("loaded_at_epoch") or 0) >= min_age)
223
  ]
224
  return {
 
228
  "used": [entry for entry in loaded_entries if entry["used"]],
229
  "unload_candidates": unload_candidates,
230
  "unloaded": unloaded,
231
+ "validations": validations,
232
+ "escalations": escalations,
233
+ "latest_validation_status": (
234
+ str(validations[-1]["status"]) if validations else None
235
+ ),
236
+ "open_escalations": [
237
+ event for event in escalations if event["status"] == "open"
238
+ ],
239
  }
240
 
241
  def _record(self, **event: Any) -> dict[str, Any]:
 
301
  value = raw.strip()
302
  validate_skill_name(value)
303
  return value
304
+
305
+
306
+ def _validate_nonempty(raw: str, field: str) -> str:
307
+ value = raw.strip()
308
+ if not value:
309
+ raise ValueError(f"{field} must be non-empty")
310
+ return value
311
+
312
+
313
+ def _validate_choice(raw: str, allowed: set[str], field: str) -> str:
314
+ value = raw.strip().lower()
315
+ if value not in allowed:
316
+ raise ValueError(f"{field} must be one of {', '.join(sorted(allowed))}")
317
+ return value
318
+
319
+
320
+ def _validation_state(event: dict[str, Any]) -> dict[str, Any]:
321
+ return {
322
+ "check_name": event.get("check_name"),
323
+ "status": event.get("status"),
324
+ "command": event.get("command"),
325
+ "summary": event.get("summary"),
326
+ "entity_type": event.get("entity_type"),
327
+ "slug": event.get("slug"),
328
+ "payload": event.get("payload") or {},
329
+ }
330
+
331
+
332
+ def _escalation_state(event: dict[str, Any]) -> dict[str, Any]:
333
+ return {
334
+ "trigger": event.get("trigger"),
335
+ "reason": event.get("reason"),
336
+ "severity": event.get("severity"),
337
+ "status": event.get("status"),
338
+ "entity_type": event.get("entity_type"),
339
+ "slug": event.get("slug"),
340
+ "payload": event.get("payload") or {},
341
+ }
342
+
343
+
344
+ def _loaded_before_latest_dev_event(
345
+ entry: dict[str, Any],
346
+ latest_dev_event_epoch: float | None,
347
+ ) -> bool:
348
+ if latest_dev_event_epoch is None:
349
+ return True
350
+ loaded_window = entry.get("dev_event_epoch")
351
+ if loaded_window is None:
352
+ return True
353
+ return float(loaded_window) < latest_dev_event_epoch
src/ctx/cli/run.py CHANGED
@@ -55,6 +55,7 @@ from ctx.adapters.generic.tools import McpRouter, McpServerConfig
55
 
56
  _logger = logging.getLogger(__name__)
57
  _CTX_SESSION_MARKER = "ctx runtime session id:"
 
58
 
59
 
60
  # ── Provider key-env defaults ───────────────────────────────────────────────
@@ -92,6 +93,53 @@ def _resolve_api_key_env(
92
  return key if key else None
93
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  # ── MCP spec parsing ───────────────────────────────────────────────────────
96
 
97
 
@@ -413,11 +461,11 @@ def _build_parser() -> argparse.ArgumentParser:
413
  )
414
  r.add_argument(
415
  "--model",
416
- required=True,
417
  help=(
418
  "Model slug in LiteLLM form, e.g. "
419
  "'openrouter/anthropic/claude-opus-4.7', "
420
- "'ollama/llama3.1:70b', 'openai/gpt-5.5'."
 
421
  ),
422
  )
423
  r.add_argument(
@@ -649,6 +697,11 @@ def _build_parser() -> argparse.ArgumentParser:
649
 
650
 
651
  def _cmd_run(args: argparse.Namespace) -> int:
 
 
 
 
 
652
  sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
653
 
654
  api_key_env = _resolve_api_key_env(args.api_key_env, args.model, args.provider)
 
55
 
56
  _logger = logging.getLogger(__name__)
57
  _CTX_SESSION_MARKER = "ctx runtime session id:"
58
+ _MODEL_PROFILE_NAME = "ctx-model-profile.json"
59
 
60
 
61
  # ── Provider key-env defaults ───────────────────────────────────────────────
 
93
  return key if key else None
94
 
95
 
96
+ def _claude_dir() -> Path:
97
+ return Path(os.path.expanduser("~/.claude"))
98
+
99
+
100
+ def _load_model_profile() -> dict[str, Any]:
101
+ path = _claude_dir() / _MODEL_PROFILE_NAME
102
+ try:
103
+ data = json.loads(path.read_text(encoding="utf-8"))
104
+ except FileNotFoundError:
105
+ return {}
106
+ except (OSError, json.JSONDecodeError) as exc:
107
+ _logger.warning("ctx model profile could not be loaded: %s", exc)
108
+ return {}
109
+ return data if isinstance(data, dict) else {}
110
+
111
+
112
+ def _profile_str(profile: dict[str, Any], key: str) -> str | None:
113
+ value = profile.get(key)
114
+ if not isinstance(value, str):
115
+ return None
116
+ value = value.strip()
117
+ return value or None
118
+
119
+
120
+ def _apply_model_profile_defaults(args: argparse.Namespace) -> str | None:
121
+ """Apply ctx-init's saved model profile to `ctx run` args."""
122
+ profile = _load_model_profile()
123
+ profile_model = _profile_str(profile, "model")
124
+ if not args.model and profile_model:
125
+ args.model = profile_model
126
+ if not args.model:
127
+ return (
128
+ "error: --model is required unless "
129
+ f"{_claude_dir() / _MODEL_PROFILE_NAME} contains a model"
130
+ )
131
+ if profile_model != args.model:
132
+ return None
133
+
134
+ if args.provider is None:
135
+ args.provider = _profile_str(profile, "provider")
136
+ if args.api_key_env is None and isinstance(profile.get("api_key_env"), str):
137
+ args.api_key_env = profile["api_key_env"]
138
+ if args.base_url is None:
139
+ args.base_url = _profile_str(profile, "base_url")
140
+ return None
141
+
142
+
143
  # ── MCP spec parsing ───────────────────────────────────────────────────────
144
 
145
 
 
461
  )
462
  r.add_argument(
463
  "--model",
 
464
  help=(
465
  "Model slug in LiteLLM form, e.g. "
466
  "'openrouter/anthropic/claude-opus-4.7', "
467
+ "'ollama/llama3.1:70b', 'openai/gpt-5.5'. "
468
+ "Default: ~/.claude/ctx-model-profile.json when configured."
469
  ),
470
  )
471
  r.add_argument(
 
697
 
698
 
699
  def _cmd_run(args: argparse.Namespace) -> int:
700
+ profile_error = _apply_model_profile_defaults(args)
701
+ if profile_error:
702
+ print(profile_error, file=sys.stderr)
703
+ return 2
704
+
705
  sdir = Path(args.sessions_dir) if args.sessions_dir else default_sessions_dir()
706
 
707
  api_key_env = _resolve_api_key_env(args.api_key_env, args.model, args.provider)
src/ctx/config.json CHANGED
@@ -72,12 +72,13 @@
72
  },
73
 
74
  "graph": {
75
- "_comment": "Knowledge-graph edge weighting for wiki_graphify. Base edges between entity pages (skill ↔ agent ↔ mcp-server ↔ harness, any combination) come from semantic similarity, explicit tags, slug tokens, source overlap, or direct wikilinks. Semantic/tag/token weights must sum to 1.0. Edge boosts then add explainable rank signals (direct links, source overlap, Adamic-Adar, type affinity, usage, quality) without creating edges by themselves. Override any key in your user config (~/.claude/skill-system-config.json).",
76
  "edge_weights": {
77
  "semantic": 0.70,
78
  "tags": 0.15,
79
  "slug_tokens": 0.15
80
  },
 
81
  "semantic": {
82
  "_comment": "Semantic edge construction uses two thresholds so you can tune display strictness WITHOUT paying to rebuild the graph. build_floor is the low bar for inclusion (all pairs at or above this survive to graph.json); min_cosine is the query/display filter that consumers (resolve, visualize, recommend) apply at read time. build_floor must be <= min_cosine. Rebuilding is only required when you change top_k, build_floor, or the entity body text that drives the cached embeddings — min_cosine alone is rebuild-free.",
83
  "top_k": 20,
 
72
  },
73
 
74
  "graph": {
75
+ "_comment": "Knowledge-graph edge weighting for wiki_graphify. Base edges between entity pages (skill ↔ agent ↔ mcp-server ↔ harness, any combination) come from semantic similarity, explicit tags, slug tokens, source overlap, or direct wikilinks. Semantic/tag/token weights must sum to 1.0. min_edge_weight drops weak final blended edges after scoring; default 0.03 is the calibrated shipped graph floor. Edge boosts then add explainable rank signals (direct links, source overlap, Adamic-Adar, type affinity, usage, quality) without creating edges by themselves. Override any key in your user config (~/.claude/skill-system-config.json).",
76
  "edge_weights": {
77
  "semantic": 0.70,
78
  "tags": 0.15,
79
  "slug_tokens": 0.15
80
  },
81
+ "min_edge_weight": 0.03,
82
  "semantic": {
83
  "_comment": "Semantic edge construction uses two thresholds so you can tune display strictness WITHOUT paying to rebuild the graph. build_floor is the low bar for inclusion (all pairs at or above this survive to graph.json); min_cosine is the query/display filter that consumers (resolve, visualize, recommend) apply at read time. build_floor must be <= min_cosine. Rebuilding is only required when you change top_k, build_floor, or the entity body text that drives the cached embeddings — min_cosine alone is rebuild-free.",
84
  "top_k": 20,
src/ctx/core/wiki/artifact_promotion.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from __future__ import annotations
4
 
 
5
  import hashlib
6
  import json
7
  import os
@@ -71,6 +72,7 @@ def promote_staged_artifact(
71
  started_at = _timestamp(now)
72
  previous = _snapshot(target)
73
  candidate = _snapshot(staged)
 
74
  pending_record = {
75
  "schema_version": 1,
76
  "status": "staged",
@@ -78,6 +80,8 @@ def promote_staged_artifact(
78
  "started_at": started_at,
79
  "previous": previous,
80
  "candidate": candidate,
 
 
81
  }
82
  atomic_write_json(metadata, pending_record, indent=2)
83
 
@@ -104,6 +108,37 @@ def _default_metadata_path(target: Path) -> Path:
104
  return target.with_name(f"{target.name}.promotion.json")
105
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  def _recover_completed_promotion(
108
  *,
109
  target: Path,
@@ -139,6 +174,8 @@ def _recover_completed_promotion(
139
  "status": "promoted",
140
  "promoted_at": _timestamp(),
141
  "current": current,
 
 
142
  }
143
  atomic_write_json(metadata, promoted_record, indent=2)
144
  return ArtifactPromotionResult(
@@ -171,6 +208,16 @@ def _snapshot(path: Path) -> dict[str, Any]:
171
  }
172
 
173
 
 
 
 
 
 
 
 
 
 
 
174
  def _sha256_file(path: Path) -> str:
175
  digest = hashlib.sha256()
176
  with path.open("rb") as f:
 
2
 
3
  from __future__ import annotations
4
 
5
+ import gzip
6
  import hashlib
7
  import json
8
  import os
 
72
  started_at = _timestamp(now)
73
  previous = _snapshot(target)
74
  candidate = _snapshot(staged)
75
+ rollback = _rollback_record(target, previous)
76
  pending_record = {
77
  "schema_version": 1,
78
  "status": "staged",
 
80
  "started_at": started_at,
81
  "previous": previous,
82
  "candidate": candidate,
83
+ "last_good": previous,
84
+ "rollback": rollback,
85
  }
86
  atomic_write_json(metadata, pending_record, indent=2)
87
 
 
108
  return target.with_name(f"{target.name}.promotion.json")
109
 
110
 
111
+ def validate_json_artifact(path: Path, *, required_keys: tuple[str, ...] = ()) -> None:
112
+ """Raise if *path* is not a readable JSON object artifact."""
113
+ try:
114
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
115
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
116
+ raise ValueError(f"invalid JSON artifact: {path}") from exc
117
+ if not isinstance(data, dict):
118
+ raise ValueError(f"invalid JSON artifact: {path} must contain an object")
119
+ missing = [key for key in required_keys if key not in data]
120
+ if missing:
121
+ raise ValueError(f"invalid JSON artifact: {path} missing keys {missing}")
122
+
123
+
124
+ def validate_gzip_json_artifact(
125
+ path: Path,
126
+ *,
127
+ required_keys: tuple[str, ...] = (),
128
+ ) -> None:
129
+ """Raise if *path* is not a readable gzip-compressed JSON object artifact."""
130
+ try:
131
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
132
+ data = json.load(fh)
133
+ except (OSError, EOFError, UnicodeDecodeError, json.JSONDecodeError) as exc:
134
+ raise ValueError(f"invalid gzip JSON artifact: {path}") from exc
135
+ if not isinstance(data, dict):
136
+ raise ValueError(f"invalid gzip JSON artifact: {path} must contain an object")
137
+ missing = [key for key in required_keys if key not in data]
138
+ if missing:
139
+ raise ValueError(f"invalid gzip JSON artifact: {path} missing keys {missing}")
140
+
141
+
142
  def _recover_completed_promotion(
143
  *,
144
  target: Path,
 
174
  "status": "promoted",
175
  "promoted_at": _timestamp(),
176
  "current": current,
177
+ "last_good": record.get("last_good", previous),
178
+ "rollback": record.get("rollback", _rollback_record(target, previous)),
179
  }
180
  atomic_write_json(metadata, promoted_record, indent=2)
181
  return ArtifactPromotionResult(
 
208
  }
209
 
210
 
211
+ def _rollback_record(target: Path, previous: dict[str, Any]) -> dict[str, Any]:
212
+ return {
213
+ "available": bool(previous.get("exists")),
214
+ "target": str(target),
215
+ "sha256": previous.get("sha256"),
216
+ "size": previous.get("size"),
217
+ "mtime_ns": previous.get("mtime_ns"),
218
+ }
219
+
220
+
221
  def _sha256_file(path: Path) -> str:
222
  digest = hashlib.sha256()
223
  with path.open("rb") as f:
src/ctx/core/wiki/wiki_graphify.py CHANGED
@@ -33,6 +33,11 @@ from ctx.core.entity_types import (
33
  entity_wikilink,
34
  mcp_shard,
35
  )
 
 
 
 
 
36
  from ctx.core.wiki.wiki_utils import parse_frontmatter as _parse_fm
37
  from ctx.utils._fs_utils import safe_atomic_write_text
38
 
@@ -632,7 +637,7 @@ def build_graph(
632
  "quality": w_quality * quality,
633
  }
634
  final = min(sum(components.values()), 1.0)
635
- if final <= 0.0:
636
  # Useless edge — only happens when every signal dropped to
637
  # zero or landed below its floor. Skip materialisation.
638
  continue
@@ -757,6 +762,7 @@ def build_graph(
757
  # edges were never materialised).
758
  G.graph["semantic_build_floor"] = round(_cfg.graph_semantic_build_floor, 4)
759
  G.graph["semantic_min_cosine_default"] = round(_cfg.graph_semantic_min_cosine, 4)
 
760
 
761
  print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
762
  print(
@@ -1505,10 +1511,13 @@ def export_graph(
1505
  graph_meta["export_id"] = export_id
1506
  else:
1507
  graph_data["graph"] = {"export_id": export_id}
1508
- safe_atomic_write_text(
1509
- GRAPH_OUT / "graph.json",
1510
  json.dumps(graph_data, indent=2, default=str),
1511
- encoding="utf-8",
 
 
 
1512
  )
1513
 
1514
  # No binary sidecar. An earlier revision wrote ``graph.pickle`` next
@@ -1524,10 +1533,13 @@ def export_graph(
1524
  # stat a single file to detect changes.
1525
  delta = _build_delta(G, delta_nodes or set())
1526
  delta["export_id"] = export_id
1527
- safe_atomic_write_text(
1528
- GRAPH_OUT / "graph-delta.json",
1529
  json.dumps(delta, indent=2, default=str),
1530
- encoding="utf-8",
 
 
 
1531
  )
1532
 
1533
  # Community labels
@@ -1535,8 +1547,8 @@ def export_graph(
1535
  for cid, members in communities.items():
1536
  labels[cid] = label_community(G, members)
1537
 
1538
- safe_atomic_write_text(
1539
- GRAPH_OUT / "communities.json",
1540
  json.dumps({
1541
  "export_id": export_id,
1542
  "communities": {str(cid): {"label": labels[cid], "members": members}
@@ -1544,7 +1556,10 @@ def export_graph(
1544
  "total_communities": len(communities),
1545
  "generated": TODAY,
1546
  }, indent=2),
1547
- encoding="utf-8",
 
 
 
1548
  )
1549
 
1550
  # God nodes (highest degree)
@@ -1567,13 +1582,12 @@ def export_graph(
1567
  for cid, members in sorted(communities.items(), key=lambda x: -len(x[1])):
1568
  report_lines.append(f"- **{labels[cid]}** — {len(members)} members")
1569
 
1570
- safe_atomic_write_text(
1571
- GRAPH_OUT / "graph-report.md",
1572
  "\n".join(report_lines),
1573
- encoding="utf-8",
1574
  )
1575
- safe_atomic_write_text(
1576
- GRAPH_OUT / GRAPH_EXPORT_MANIFEST,
1577
  json.dumps({
1578
  "version": 1,
1579
  "export_id": export_id,
@@ -1590,11 +1604,26 @@ def export_graph(
1590
  "communities": len(communities),
1591
  },
1592
  }, indent=2),
1593
- encoding="utf-8",
 
 
 
1594
  )
1595
  print(f"Graph exported to {GRAPH_OUT}/")
1596
 
1597
 
 
 
 
 
 
 
 
 
 
 
 
 
1598
  def main() -> None:
1599
  parser = argparse.ArgumentParser(description="Build knowledge graph from wiki entities")
1600
  parser.add_argument(
 
33
  entity_wikilink,
34
  mcp_shard,
35
  )
36
+ from ctx.core.wiki.artifact_promotion import (
37
+ ArtifactValidator,
38
+ promote_staged_artifact,
39
+ validate_json_artifact,
40
+ )
41
  from ctx.core.wiki.wiki_utils import parse_frontmatter as _parse_fm
42
  from ctx.utils._fs_utils import safe_atomic_write_text
43
 
 
637
  "quality": w_quality * quality,
638
  }
639
  final = min(sum(components.values()), 1.0)
640
+ if final <= 0.0 or final < _cfg.graph_edge_min_weight:
641
  # Useless edge — only happens when every signal dropped to
642
  # zero or landed below its floor. Skip materialisation.
643
  continue
 
762
  # edges were never materialised).
763
  G.graph["semantic_build_floor"] = round(_cfg.graph_semantic_build_floor, 4)
764
  G.graph["semantic_min_cosine_default"] = round(_cfg.graph_semantic_min_cosine, 4)
765
+ G.graph["min_edge_weight"] = round(_cfg.graph_edge_min_weight, 4)
766
 
767
  print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
768
  print(
 
1511
  graph_meta["export_id"] = export_id
1512
  else:
1513
  graph_data["graph"] = {"export_id": export_id}
1514
+ _stage_and_promote_graph_artifact(
1515
+ "graph.json",
1516
  json.dumps(graph_data, indent=2, default=str),
1517
+ validate=lambda path: validate_json_artifact(
1518
+ path,
1519
+ required_keys=("nodes", "edges", "graph"),
1520
+ ),
1521
  )
1522
 
1523
  # No binary sidecar. An earlier revision wrote ``graph.pickle`` next
 
1533
  # stat a single file to detect changes.
1534
  delta = _build_delta(G, delta_nodes or set())
1535
  delta["export_id"] = export_id
1536
+ _stage_and_promote_graph_artifact(
1537
+ "graph-delta.json",
1538
  json.dumps(delta, indent=2, default=str),
1539
+ validate=lambda path: validate_json_artifact(
1540
+ path,
1541
+ required_keys=("version", "full_rebuild", "export_id"),
1542
+ ),
1543
  )
1544
 
1545
  # Community labels
 
1547
  for cid, members in communities.items():
1548
  labels[cid] = label_community(G, members)
1549
 
1550
+ _stage_and_promote_graph_artifact(
1551
+ "communities.json",
1552
  json.dumps({
1553
  "export_id": export_id,
1554
  "communities": {str(cid): {"label": labels[cid], "members": members}
 
1556
  "total_communities": len(communities),
1557
  "generated": TODAY,
1558
  }, indent=2),
1559
+ validate=lambda path: validate_json_artifact(
1560
+ path,
1561
+ required_keys=("export_id", "communities", "total_communities"),
1562
+ ),
1563
  )
1564
 
1565
  # God nodes (highest degree)
 
1582
  for cid, members in sorted(communities.items(), key=lambda x: -len(x[1])):
1583
  report_lines.append(f"- **{labels[cid]}** — {len(members)} members")
1584
 
1585
+ _stage_and_promote_graph_artifact(
1586
+ "graph-report.md",
1587
  "\n".join(report_lines),
 
1588
  )
1589
+ _stage_and_promote_graph_artifact(
1590
+ GRAPH_EXPORT_MANIFEST,
1591
  json.dumps({
1592
  "version": 1,
1593
  "export_id": export_id,
 
1604
  "communities": len(communities),
1605
  },
1606
  }, indent=2),
1607
+ validate=lambda path: validate_json_artifact(
1608
+ path,
1609
+ required_keys=("version", "export_id", "artifacts", "counts"),
1610
+ ),
1611
  )
1612
  print(f"Graph exported to {GRAPH_OUT}/")
1613
 
1614
 
1615
+ def _stage_and_promote_graph_artifact(
1616
+ name: str,
1617
+ text: str,
1618
+ *,
1619
+ validate: ArtifactValidator | None = None,
1620
+ ) -> None:
1621
+ target = GRAPH_OUT / name
1622
+ staged = target.with_name(f"{target.name}.staged")
1623
+ safe_atomic_write_text(staged, text, encoding="utf-8")
1624
+ promote_staged_artifact(staged, target, validate=validate)
1625
+
1626
+
1627
  def main() -> None:
1628
  parser = argparse.ArgumentParser(description="Build knowledge graph from wiki entities")
1629
  parser.add_argument(
src/ctx/core/wiki/wiki_queue.py CHANGED
@@ -7,13 +7,14 @@ future processor leases jobs with explicit worker IDs.
7
 
8
  from __future__ import annotations
9
 
 
10
  import json
11
  import sqlite3
12
  import time
13
  from hashlib import sha256
14
  from dataclasses import dataclass
15
  from pathlib import Path
16
- from typing import Any, Iterable
17
 
18
  from ctx.utils._fs_utils import reject_symlink_path
19
 
@@ -21,6 +22,9 @@ STATUS_PENDING = "pending"
21
  STATUS_RUNNING = "running"
22
  STATUS_SUCCEEDED = "succeeded"
23
  STATUS_FAILED = "failed"
 
 
 
24
 
25
  ENTITY_UPSERT_JOB = "entity-upsert"
26
  GRAPH_EXPORT_JOB = "graph-export"
@@ -81,6 +85,10 @@ class QueueJob:
81
  updated_at: float
82
 
83
 
 
 
 
 
84
  def init_queue(db_path: Path) -> None:
85
  """Create the queue database and enable SQLite WAL mode."""
86
  with _connect(db_path) as conn:
@@ -160,6 +168,7 @@ def enqueue_maintenance_job(
160
  content_hash=content_hash,
161
  max_attempts=max_attempts,
162
  available_at=available_at,
 
163
  now=now,
164
  )
165
 
@@ -173,6 +182,7 @@ def enqueue(
173
  content_hash: str | None = None,
174
  max_attempts: int = 3,
175
  available_at: float | None = None,
 
176
  now: float | None = None,
177
  ) -> QueueJob:
178
  """Insert a pending job or return the existing job for an idempotency key."""
@@ -186,14 +196,24 @@ def enqueue(
186
  with _connect(db_path) as conn:
187
  conn.execute("BEGIN IMMEDIATE")
188
  try:
 
 
 
 
 
189
  if idempotency_key:
190
  row = conn.execute(
191
  "SELECT * FROM wiki_queue_jobs WHERE idempotency_key = ?",
192
  (idempotency_key,),
193
  ).fetchone()
194
  if row is not None:
195
- conn.execute("COMMIT")
196
- return _row_to_job(row)
 
 
 
 
 
197
  cur = conn.execute(
198
  """
199
  INSERT INTO wiki_queue_jobs (
@@ -234,8 +254,7 @@ def lease_next(
234
  now: float | None = None,
235
  ) -> QueueJob | None:
236
  """Lease the oldest available pending job, recovering expired leases first."""
237
- if not worker_id.strip():
238
- raise ValueError("worker_id must be non-empty")
239
  if lease_seconds <= 0:
240
  raise ValueError(f"lease_seconds must be > 0 (got {lease_seconds})")
241
  timestamp = _now(now)
@@ -264,7 +283,7 @@ def lease_next(
264
  """,
265
  (
266
  STATUS_RUNNING,
267
- worker_id,
268
  timestamp + float(lease_seconds),
269
  timestamp,
270
  job_id,
@@ -278,13 +297,21 @@ def lease_next(
278
  raise
279
 
280
 
281
- def mark_succeeded(db_path: Path, job_id: int, *, now: float | None = None) -> QueueJob:
 
 
 
 
 
 
282
  """Mark a leased job as succeeded and clear lease metadata."""
283
  timestamp = _now(now)
 
284
  with _connect(db_path) as conn:
285
  conn.execute("BEGIN IMMEDIATE")
286
  try:
287
- _select_job(conn, job_id)
 
288
  conn.execute(
289
  """
290
  UPDATE wiki_queue_jobs
@@ -309,6 +336,7 @@ def mark_failed(
309
  db_path: Path,
310
  job_id: int,
311
  *,
 
312
  error: str,
313
  retry: bool,
314
  delay_seconds: float = 0.0,
@@ -317,10 +345,12 @@ def mark_failed(
317
  """Record a job failure, retrying if allowed and attempts remain."""
318
  timestamp = _now(now)
319
  delay = max(0.0, float(delay_seconds))
 
320
  with _connect(db_path) as conn:
321
  conn.execute("BEGIN IMMEDIATE")
322
  try:
323
  current = _row_to_job(_select_job(conn, job_id))
 
324
  should_retry = retry and current.attempts < current.max_attempts
325
  status = STATUS_PENDING if should_retry else STATUS_FAILED
326
  available_at = timestamp + delay if should_retry else current.available_at
@@ -345,6 +375,69 @@ def mark_failed(
345
  raise
346
 
347
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  def get_job(db_path: Path, job_id: int) -> QueueJob:
349
  """Return one queue job by ID."""
350
  with _connect(db_path) as conn:
@@ -372,23 +465,82 @@ def list_jobs(
372
  return [_row_to_job(row) for row in rows]
373
 
374
 
375
- def _connect(db_path: Path) -> sqlite3.Connection:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  path = Path(db_path)
377
  reject_symlink_path(path)
378
  path.parent.mkdir(parents=True, exist_ok=True)
379
  reject_symlink_path(path)
380
- conn = sqlite3.connect(path, timeout=30.0, isolation_level=None)
381
- conn.row_factory = sqlite3.Row
382
- conn.execute("PRAGMA busy_timeout = 30000")
383
- conn.execute("PRAGMA journal_mode = WAL")
384
- conn.execute("PRAGMA synchronous = NORMAL")
385
- conn.execute("PRAGMA foreign_keys = ON")
386
- conn.executescript(_SCHEMA)
387
- return conn
388
-
389
-
390
- def _recover_expired_leases(conn: sqlite3.Connection, now: float) -> None:
391
- conn.execute(
 
 
 
 
 
 
 
 
 
 
392
  """
393
  UPDATE wiki_queue_jobs
394
  SET status = ?,
@@ -402,20 +554,28 @@ def _recover_expired_leases(conn: sqlite3.Connection, now: float) -> None:
402
  """,
403
  (STATUS_PENDING, now, STATUS_RUNNING, now),
404
  )
405
- conn.execute(
406
  """
407
  UPDATE wiki_queue_jobs
408
  SET status = ?,
409
  worker_id = NULL,
410
  leased_until = NULL,
 
411
  updated_at = ?
412
  WHERE status = ?
413
  AND leased_until IS NOT NULL
414
  AND leased_until <= ?
415
  AND attempts >= max_attempts
416
  """,
417
- (STATUS_FAILED, now, STATUS_RUNNING, now),
 
 
 
 
 
 
418
  )
 
419
 
420
 
421
  def _select_next_ready(
@@ -450,6 +610,24 @@ def _select_next_ready(
450
  ).fetchone()
451
 
452
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
  def _select_job(conn: sqlite3.Connection, job_id: int) -> sqlite3.Row:
454
  row = conn.execute(
455
  "SELECT * FROM wiki_queue_jobs WHERE id = ?",
@@ -503,11 +681,33 @@ def _validate_kind(kind: str) -> None:
503
  raise ValueError("kind must be a non-empty string")
504
 
505
 
 
 
 
 
 
 
506
  def _validate_maintenance_kind(kind: str) -> None:
507
  _validate_kind(kind)
508
  if kind not in MAINTENANCE_JOB_KINDS:
509
  raise ValueError(f"unsupported maintenance job kind: {kind}")
510
 
511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  def _now(now: float | None) -> float:
513
  return time.time() if now is None else float(now)
 
7
 
8
  from __future__ import annotations
9
 
10
+ from contextlib import contextmanager
11
  import json
12
  import sqlite3
13
  import time
14
  from hashlib import sha256
15
  from dataclasses import dataclass
16
  from pathlib import Path
17
+ from typing import Any, Iterable, Iterator
18
 
19
  from ctx.utils._fs_utils import reject_symlink_path
20
 
 
22
  STATUS_RUNNING = "running"
23
  STATUS_SUCCEEDED = "succeeded"
24
  STATUS_FAILED = "failed"
25
+ STATUS_CANCELLED = "cancelled"
26
+ TERMINAL_STATUSES = (STATUS_SUCCEEDED, STATUS_FAILED, STATUS_CANCELLED)
27
+ ACTIVE_STATUSES = (STATUS_PENDING, STATUS_RUNNING)
28
 
29
  ENTITY_UPSERT_JOB = "entity-upsert"
30
  GRAPH_EXPORT_JOB = "graph-export"
 
85
  updated_at: float
86
 
87
 
88
+ class QueueStorageError(RuntimeError):
89
+ """Raised when the durable queue DB cannot be opened or initialized."""
90
+
91
+
92
  def init_queue(db_path: Path) -> None:
93
  """Create the queue database and enable SQLite WAL mode."""
94
  with _connect(db_path) as conn:
 
168
  content_hash=content_hash,
169
  max_attempts=max_attempts,
170
  available_at=available_at,
171
+ reuse_terminal=False,
172
  now=now,
173
  )
174
 
 
182
  content_hash: str | None = None,
183
  max_attempts: int = 3,
184
  available_at: float | None = None,
185
+ reuse_terminal: bool = True,
186
  now: float | None = None,
187
  ) -> QueueJob:
188
  """Insert a pending job or return the existing job for an idempotency key."""
 
196
  with _connect(db_path) as conn:
197
  conn.execute("BEGIN IMMEDIATE")
198
  try:
199
+ if idempotency_key and not reuse_terminal and content_hash:
200
+ row = _select_active_duplicate(conn, kind, content_hash)
201
+ if row is not None:
202
+ conn.execute("COMMIT")
203
+ return _row_to_job(row)
204
  if idempotency_key:
205
  row = conn.execute(
206
  "SELECT * FROM wiki_queue_jobs WHERE idempotency_key = ?",
207
  (idempotency_key,),
208
  ).fetchone()
209
  if row is not None:
210
+ existing = _row_to_job(row)
211
+ if reuse_terminal or existing.status not in TERMINAL_STATUSES:
212
+ conn.execute("COMMIT")
213
+ return existing
214
+ idempotency_key = (
215
+ f"{idempotency_key}:run:{timestamp:.6f}:{time.monotonic_ns()}"
216
+ )
217
  cur = conn.execute(
218
  """
219
  INSERT INTO wiki_queue_jobs (
 
254
  now: float | None = None,
255
  ) -> QueueJob | None:
256
  """Lease the oldest available pending job, recovering expired leases first."""
257
+ claimed_worker_id = _validate_worker_id(worker_id)
 
258
  if lease_seconds <= 0:
259
  raise ValueError(f"lease_seconds must be > 0 (got {lease_seconds})")
260
  timestamp = _now(now)
 
283
  """,
284
  (
285
  STATUS_RUNNING,
286
+ claimed_worker_id,
287
  timestamp + float(lease_seconds),
288
  timestamp,
289
  job_id,
 
297
  raise
298
 
299
 
300
+ def mark_succeeded(
301
+ db_path: Path,
302
+ job_id: int,
303
+ *,
304
+ worker_id: str | None = None,
305
+ now: float | None = None,
306
+ ) -> QueueJob:
307
  """Mark a leased job as succeeded and clear lease metadata."""
308
  timestamp = _now(now)
309
+ expected_worker_id = _validate_worker_id(worker_id) if worker_id is not None else None
310
  with _connect(db_path) as conn:
311
  conn.execute("BEGIN IMMEDIATE")
312
  try:
313
+ current = _row_to_job(_select_job(conn, job_id))
314
+ _assert_job_leased_by_worker(current, expected_worker_id)
315
  conn.execute(
316
  """
317
  UPDATE wiki_queue_jobs
 
336
  db_path: Path,
337
  job_id: int,
338
  *,
339
+ worker_id: str | None = None,
340
  error: str,
341
  retry: bool,
342
  delay_seconds: float = 0.0,
 
345
  """Record a job failure, retrying if allowed and attempts remain."""
346
  timestamp = _now(now)
347
  delay = max(0.0, float(delay_seconds))
348
+ expected_worker_id = _validate_worker_id(worker_id) if worker_id is not None else None
349
  with _connect(db_path) as conn:
350
  conn.execute("BEGIN IMMEDIATE")
351
  try:
352
  current = _row_to_job(_select_job(conn, job_id))
353
+ _assert_job_leased_by_worker(current, expected_worker_id)
354
  should_retry = retry and current.attempts < current.max_attempts
355
  status = STATUS_PENDING if should_retry else STATUS_FAILED
356
  available_at = timestamp + delay if should_retry else current.available_at
 
375
  raise
376
 
377
 
378
+ def cancel_job(
379
+ db_path: Path,
380
+ job_id: int,
381
+ *,
382
+ worker_id: str | None = None,
383
+ reason: str | None = None,
384
+ now: float | None = None,
385
+ ) -> QueueJob:
386
+ """Cancel a pending/running job and clear any active lease.
387
+
388
+ Cancellation is idempotent for an already-cancelled job. Succeeded and
389
+ failed jobs remain immutable terminal records.
390
+ """
391
+ timestamp = _now(now)
392
+ expected_worker_id = _validate_worker_id(worker_id) if worker_id is not None else None
393
+ detail = reason.strip() if isinstance(reason, str) and reason.strip() else None
394
+ with _connect(db_path) as conn:
395
+ conn.execute("BEGIN IMMEDIATE")
396
+ try:
397
+ current = _row_to_job(_select_job(conn, job_id))
398
+ if current.status == STATUS_CANCELLED:
399
+ conn.execute("COMMIT")
400
+ return current
401
+ if current.status in (STATUS_SUCCEEDED, STATUS_FAILED):
402
+ raise RuntimeError(
403
+ f"queue job {current.id} is already terminal: {current.status}"
404
+ )
405
+ if current.status == STATUS_RUNNING and expected_worker_id is not None:
406
+ _assert_job_leased_by_worker(current, expected_worker_id)
407
+ conn.execute(
408
+ """
409
+ UPDATE wiki_queue_jobs
410
+ SET status = ?,
411
+ worker_id = NULL,
412
+ leased_until = NULL,
413
+ last_error = ?,
414
+ updated_at = ?
415
+ WHERE id = ?
416
+ """,
417
+ (STATUS_CANCELLED, detail, timestamp, int(job_id)),
418
+ )
419
+ row = _select_job(conn, job_id)
420
+ conn.execute("COMMIT")
421
+ return _row_to_job(row)
422
+ except Exception:
423
+ conn.execute("ROLLBACK")
424
+ raise
425
+
426
+
427
+ def recover_expired_leases(db_path: Path, *, now: float | None = None) -> dict[str, int]:
428
+ """Recover expired running jobs without leasing a new job."""
429
+ timestamp = _now(now)
430
+ with _connect(db_path) as conn:
431
+ conn.execute("BEGIN IMMEDIATE")
432
+ try:
433
+ recovered = _recover_expired_leases(conn, timestamp)
434
+ conn.execute("COMMIT")
435
+ return recovered
436
+ except Exception:
437
+ conn.execute("ROLLBACK")
438
+ raise
439
+
440
+
441
  def get_job(db_path: Path, job_id: int) -> QueueJob:
442
  """Return one queue job by ID."""
443
  with _connect(db_path) as conn:
 
465
  return [_row_to_job(row) for row in rows]
466
 
467
 
468
+ def count_jobs_by_status(db_path: Path) -> dict[str, int]:
469
+ """Return queue job counts grouped by status."""
470
+ with _connect(db_path) as conn:
471
+ rows = conn.execute(
472
+ """
473
+ SELECT status, COUNT(*) AS count
474
+ FROM wiki_queue_jobs
475
+ GROUP BY status
476
+ """,
477
+ ).fetchall()
478
+ return {str(row["status"]): int(row["count"]) for row in rows}
479
+
480
+
481
+ def list_recent_jobs(
482
+ db_path: Path,
483
+ *,
484
+ limit: int = 20,
485
+ statuses: Iterable[str] | None = None,
486
+ ) -> list[QueueJob]:
487
+ """List the newest queue jobs, bounded in SQLite."""
488
+ bounded_limit = max(0, int(limit))
489
+ if bounded_limit == 0:
490
+ return []
491
+ status_filter = tuple(statuses or ())
492
+ with _connect(db_path) as conn:
493
+ if status_filter:
494
+ placeholders = ",".join("?" for _ in status_filter)
495
+ rows = conn.execute(
496
+ f"""
497
+ SELECT * FROM wiki_queue_jobs
498
+ WHERE status IN ({placeholders})
499
+ ORDER BY id DESC
500
+ LIMIT ?
501
+ """,
502
+ (*status_filter, bounded_limit),
503
+ ).fetchall()
504
+ else:
505
+ rows = conn.execute(
506
+ """
507
+ SELECT * FROM wiki_queue_jobs
508
+ ORDER BY id DESC
509
+ LIMIT ?
510
+ """,
511
+ (bounded_limit,),
512
+ ).fetchall()
513
+ return [_row_to_job(row) for row in rows]
514
+
515
+
516
+ @contextmanager
517
+ def _connect(db_path: Path) -> Iterator[sqlite3.Connection]:
518
  path = Path(db_path)
519
  reject_symlink_path(path)
520
  path.parent.mkdir(parents=True, exist_ok=True)
521
  reject_symlink_path(path)
522
+ conn: sqlite3.Connection | None = None
523
+ try:
524
+ conn = sqlite3.connect(path, timeout=30.0, isolation_level=None)
525
+ conn.row_factory = sqlite3.Row
526
+ conn.execute("PRAGMA busy_timeout = 30000")
527
+ conn.execute("PRAGMA journal_mode = WAL")
528
+ conn.execute("PRAGMA synchronous = NORMAL")
529
+ conn.execute("PRAGMA foreign_keys = ON")
530
+ conn.executescript(_SCHEMA)
531
+ except sqlite3.DatabaseError as exc:
532
+ if conn is not None:
533
+ conn.close()
534
+ raise QueueStorageError(f"queue database is not readable: {path}") from exc
535
+ try:
536
+ yield conn
537
+ finally:
538
+ if conn is not None:
539
+ conn.close()
540
+
541
+
542
+ def _recover_expired_leases(conn: sqlite3.Connection, now: float) -> dict[str, int]:
543
+ requeued = conn.execute(
544
  """
545
  UPDATE wiki_queue_jobs
546
  SET status = ?,
 
554
  """,
555
  (STATUS_PENDING, now, STATUS_RUNNING, now),
556
  )
557
+ failed = conn.execute(
558
  """
559
  UPDATE wiki_queue_jobs
560
  SET status = ?,
561
  worker_id = NULL,
562
  leased_until = NULL,
563
+ last_error = ?,
564
  updated_at = ?
565
  WHERE status = ?
566
  AND leased_until IS NOT NULL
567
  AND leased_until <= ?
568
  AND attempts >= max_attempts
569
  """,
570
+ (
571
+ STATUS_FAILED,
572
+ "lease expired; max attempts exhausted",
573
+ now,
574
+ STATUS_RUNNING,
575
+ now,
576
+ ),
577
  )
578
+ return {"requeued": int(requeued.rowcount or 0), "failed": int(failed.rowcount or 0)}
579
 
580
 
581
  def _select_next_ready(
 
610
  ).fetchone()
611
 
612
 
613
+ def _select_active_duplicate(
614
+ conn: sqlite3.Connection,
615
+ kind: str,
616
+ content_hash: str,
617
+ ) -> sqlite3.Row | None:
618
+ return conn.execute(
619
+ """
620
+ SELECT * FROM wiki_queue_jobs
621
+ WHERE kind = ?
622
+ AND content_hash = ?
623
+ AND status IN (?, ?)
624
+ ORDER BY id DESC
625
+ LIMIT 1
626
+ """,
627
+ (kind, content_hash, *ACTIVE_STATUSES),
628
+ ).fetchone()
629
+
630
+
631
  def _select_job(conn: sqlite3.Connection, job_id: int) -> sqlite3.Row:
632
  row = conn.execute(
633
  "SELECT * FROM wiki_queue_jobs WHERE id = ?",
 
681
  raise ValueError("kind must be a non-empty string")
682
 
683
 
684
+ def _validate_worker_id(worker_id: str) -> str:
685
+ if not isinstance(worker_id, str) or not worker_id.strip():
686
+ raise ValueError("worker_id must be non-empty")
687
+ return worker_id.strip()
688
+
689
+
690
  def _validate_maintenance_kind(kind: str) -> None:
691
  _validate_kind(kind)
692
  if kind not in MAINTENANCE_JOB_KINDS:
693
  raise ValueError(f"unsupported maintenance job kind: {kind}")
694
 
695
 
696
+ def _assert_job_leased_by_worker(job: QueueJob, worker_id: str | None) -> None:
697
+ if job.status != STATUS_RUNNING:
698
+ actual = job.worker_id or "<none>"
699
+ target = worker_id or actual
700
+ raise RuntimeError(
701
+ f"queue job {job.id} is not leased by worker {target} "
702
+ f"(status={job.status}, worker_id={actual})"
703
+ )
704
+ if worker_id is not None and job.worker_id != worker_id:
705
+ actual = job.worker_id or "<none>"
706
+ raise RuntimeError(
707
+ f"queue job {job.id} is not leased by worker {worker_id} "
708
+ f"(status={job.status}, worker_id={actual})"
709
+ )
710
+
711
+
712
  def _now(now: float | None) -> float:
713
  return time.time() if now is None else float(now)
src/ctx/core/wiki/wiki_queue_worker.py CHANGED
@@ -61,6 +61,7 @@ def process_next(
61
  failed = wiki_queue.mark_failed(
62
  db_path,
63
  job.id,
 
64
  error=str(exc),
65
  retry=True,
66
  delay_seconds=retry_delay_seconds,
@@ -73,7 +74,7 @@ def process_next(
73
  message=str(failed.last_error or exc),
74
  )
75
 
76
- succeeded = wiki_queue.mark_succeeded(db_path, job.id, now=now)
77
  return ProcessResult(
78
  job_id=succeeded.id,
79
  kind=succeeded.kind,
@@ -136,6 +137,12 @@ def _process_entity_upsert(wiki_path: Path, payload: dict[str, Any]) -> str:
136
  )
137
 
138
  update_index(str(wiki_path), [slug], subject_type=subject_type)
 
 
 
 
 
 
139
  return f"refreshed {subject_type} index for {slug}"
140
 
141
 
 
61
  failed = wiki_queue.mark_failed(
62
  db_path,
63
  job.id,
64
+ worker_id=worker_id,
65
  error=str(exc),
66
  retry=True,
67
  delay_seconds=retry_delay_seconds,
 
74
  message=str(failed.last_error or exc),
75
  )
76
 
77
+ succeeded = wiki_queue.mark_succeeded(db_path, job.id, worker_id=worker_id, now=now)
78
  return ProcessResult(
79
  job_id=succeeded.id,
80
  kind=succeeded.kind,
 
137
  )
138
 
139
  update_index(str(wiki_path), [slug], subject_type=subject_type)
140
+ wiki_queue.enqueue_maintenance_job(
141
+ wiki_path,
142
+ kind=wiki_queue.GRAPH_EXPORT_JOB,
143
+ payload={"graph_only": True, "incremental": True},
144
+ source="entity-upsert",
145
+ )
146
  return f"refreshed {subject_type} index for {slug}"
147
 
148
 
src/tests/test_artifact_promotion.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  import json
4
  from datetime import datetime, timezone
5
  from pathlib import Path
@@ -34,6 +35,9 @@ def test_promote_staged_artifact_validates_replaces_and_records_metadata(
34
  assert metadata["previous"]["size"] == 4
35
  assert metadata["candidate"]["size"] == 4
36
  assert metadata["current"]["sha256"] == metadata["candidate"]["sha256"]
 
 
 
37
 
38
 
39
  def test_promote_staged_artifact_validation_failure_preserves_target(
@@ -58,6 +62,21 @@ def test_promote_staged_artifact_validation_failure_preserves_target(
58
  assert staged.exists()
59
  assert not target.with_name("artifact.txt.promotion.json").exists()
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  def test_promote_staged_artifact_replace_failure_preserves_target_and_last_good(
63
  tmp_path: Path,
@@ -83,6 +102,8 @@ def test_promote_staged_artifact_replace_failure_preserves_target_and_last_good(
83
  assert staged.exists()
84
  assert metadata["status"] == "staged"
85
  assert metadata["previous"]["sha256"] != metadata["candidate"]["sha256"]
 
 
86
 
87
 
88
  def test_promote_staged_artifact_recovers_after_post_replace_crash(
 
1
  from __future__ import annotations
2
 
3
+ import gzip
4
  import json
5
  from datetime import datetime, timezone
6
  from pathlib import Path
 
35
  assert metadata["previous"]["size"] == 4
36
  assert metadata["candidate"]["size"] == 4
37
  assert metadata["current"]["sha256"] == metadata["candidate"]["sha256"]
38
+ assert metadata["last_good"] == metadata["previous"]
39
+ assert metadata["rollback"]["available"] is True
40
+ assert metadata["rollback"]["sha256"] == metadata["previous"]["sha256"]
41
 
42
 
43
  def test_promote_staged_artifact_validation_failure_preserves_target(
 
62
  assert staged.exists()
63
  assert not target.with_name("artifact.txt.promotion.json").exists()
64
 
65
+ malformed_json = tmp_path / "broken.json"
66
+ malformed_json.write_text("{", encoding="utf-8")
67
+ with pytest.raises(ValueError, match="invalid JSON artifact"):
68
+ artifact_promotion.validate_json_artifact(malformed_json)
69
+
70
+ truncated_gzip = tmp_path / "broken.json.gz"
71
+ truncated_gzip.write_bytes(b"\x1f\x8b")
72
+ with pytest.raises(ValueError, match="invalid gzip JSON artifact"):
73
+ artifact_promotion.validate_gzip_json_artifact(truncated_gzip)
74
+
75
+ valid_gzip = tmp_path / "catalog.json.gz"
76
+ with gzip.open(valid_gzip, "wt", encoding="utf-8") as fh:
77
+ json.dump({"skills": []}, fh)
78
+ artifact_promotion.validate_gzip_json_artifact(valid_gzip, required_keys=("skills",))
79
+
80
 
81
  def test_promote_staged_artifact_replace_failure_preserves_target_and_last_good(
82
  tmp_path: Path,
 
102
  assert staged.exists()
103
  assert metadata["status"] == "staged"
104
  assert metadata["previous"]["sha256"] != metadata["candidate"]["sha256"]
105
+ assert metadata["last_good"] == metadata["previous"]
106
+ assert metadata["rollback"]["available"] is True
107
 
108
 
109
  def test_promote_staged_artifact_recovers_after_post_replace_crash(
src/tests/test_ci_classifier.py CHANGED
@@ -24,7 +24,9 @@ def test_docs_only_classification() -> None:
24
  assert flags == {
25
  "browser_changed": False,
26
  "ci_changed": False,
 
27
  "docs_only": True,
 
28
  "graph_changed": True,
29
  "graph_only": False,
30
  "package_changed": False,
@@ -37,6 +39,7 @@ def test_docs_tooling_changes_are_docs_only() -> None:
37
  flags = classify_paths(["mkdocs.yml", "requirements-docs.txt"])
38
 
39
  assert flags["docs_only"] is True
 
40
  assert flags["graph_only"] is False
41
  assert flags["source_changed"] is False
42
 
@@ -44,21 +47,48 @@ def test_docs_tooling_changes_are_docs_only() -> None:
44
  def test_graph_artifacts_are_graph_only_not_docs_only() -> None:
45
  flags = classify_paths(["graph/wiki-graph.tar.gz", "graph/communities.json"])
46
 
 
47
  assert flags["docs_only"] is False
 
48
  assert flags["graph_changed"] is True
49
  assert flags["graph_only"] is True
50
  assert flags["similarity_changed"] is False
51
  assert flags["source_changed"] is False
52
 
53
 
 
 
 
 
 
 
 
 
 
 
54
  def test_mixed_graph_and_source_change_is_not_graph_only() -> None:
55
  flags = classify_paths(["graph/wiki-graph.tar.gz", "src/ctx/adapters/generic/loop.py"])
56
 
 
57
  assert flags["graph_changed"] is True
58
  assert flags["graph_only"] is False
59
  assert flags["source_changed"] is True
60
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def test_source_change_marks_source_and_package() -> None:
63
  flags = classify_paths(["src/ctx/adapters/generic/loop.py"])
64
 
@@ -75,6 +105,7 @@ def test_workflow_change_fails_open_for_future_gates() -> None:
75
  assert flags["package_changed"] is True
76
  assert flags["similarity_changed"] is True
77
  assert flags["source_changed"] is True
 
78
  assert flags["docs_only"] is False
79
 
80
 
@@ -94,6 +125,14 @@ def test_ci_workflows_default_to_read_only_token_permissions() -> None:
94
  assert "\npermissions:\n contents: read\n" in workflow
95
 
96
 
 
 
 
 
 
 
 
 
97
  def test_publish_oidc_permission_is_limited_to_publish_job() -> None:
98
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
99
  header = workflow.split("\njobs:\n", maxsplit=1)[0]
@@ -184,9 +223,23 @@ def test_main_writes_github_outputs(tmp_path: Path, monkeypatch) -> None:
184
  written = output.read_text(encoding="utf-8").splitlines()
185
  assert "package_changed=true" in written
186
  assert "source_changed=true" in written
 
187
  assert "docs_only=false" in written
188
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  def test_ci_required_allows_pr_policy_skip_on_push_only() -> None:
191
  needs = _required_needs(**{"no-test-no-merge": {"result": "skipped"}})
192
 
@@ -227,7 +280,12 @@ def test_ci_required_allows_heavy_jobs_to_skip_on_docs_only_pr() -> None:
227
  needs = _required_needs(
228
  classify={
229
  "result": "success",
230
- "outputs": {"browser_changed": "false", "docs_only": "true"},
 
 
 
 
 
231
  },
232
  **{
233
  "graph-check": {"result": "skipped"},
@@ -250,7 +308,10 @@ def test_ci_required_allows_heavy_jobs_to_skip_on_docs_only_pr() -> None:
250
 
251
  def test_ci_required_rejects_missing_docs_check_on_docs_only_pr() -> None:
252
  needs = _required_needs(
253
- classify={"result": "success", "outputs": {"docs_only": "true"}},
 
 
 
254
  **{"docs-check": {"result": "skipped"}},
255
  )
256
 
@@ -265,7 +326,9 @@ def test_ci_required_allows_heavy_jobs_to_skip_on_graph_only_pr() -> None:
265
  "result": "success",
266
  "outputs": {
267
  "browser_changed": "false",
 
268
  "docs_only": "false",
 
269
  "graph_only": "true",
270
  },
271
  },
@@ -290,7 +353,10 @@ def test_ci_required_allows_heavy_jobs_to_skip_on_graph_only_pr() -> None:
290
 
291
  def test_ci_required_rejects_missing_graph_check_on_graph_only_pr() -> None:
292
  needs = _required_needs(
293
- classify={"result": "success", "outputs": {"graph_only": "true"}},
 
 
 
294
  **{"graph-check": {"result": "skipped"}},
295
  )
296
 
@@ -315,7 +381,11 @@ def test_ci_required_rejects_missing_similarity_gate_on_source_pr() -> None:
315
  needs = _required_needs(
316
  classify={
317
  "result": "success",
318
- "outputs": {"docs_only": "false", "graph_only": "false"},
 
 
 
 
319
  },
320
  **{"similarity-integration": {"result": "skipped"}},
321
  )
@@ -364,3 +434,31 @@ def test_ci_required_rejects_browser_skip_when_classifier_requests_it() -> None:
364
  assert failed_required_jobs(needs, event_name="pull_request") == {
365
  "browser-security": "skipped",
366
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  assert flags == {
25
  "browser_changed": False,
26
  "ci_changed": False,
27
+ "docs_changed": True,
28
  "docs_only": True,
29
+ "graph_artifact_changed": False,
30
  "graph_changed": True,
31
  "graph_only": False,
32
  "package_changed": False,
 
39
  flags = classify_paths(["mkdocs.yml", "requirements-docs.txt"])
40
 
41
  assert flags["docs_only"] is True
42
+ assert flags["docs_changed"] is True
43
  assert flags["graph_only"] is False
44
  assert flags["source_changed"] is False
45
 
 
47
  def test_graph_artifacts_are_graph_only_not_docs_only() -> None:
48
  flags = classify_paths(["graph/wiki-graph.tar.gz", "graph/communities.json"])
49
 
50
+ assert flags["docs_changed"] is False
51
  assert flags["docs_only"] is False
52
+ assert flags["graph_artifact_changed"] is True
53
  assert flags["graph_changed"] is True
54
  assert flags["graph_only"] is True
55
  assert flags["similarity_changed"] is False
56
  assert flags["source_changed"] is False
57
 
58
 
59
+ def test_graph_readme_is_docs_not_graph_artifact() -> None:
60
+ flags = classify_paths(["graph/README.md"])
61
+
62
+ assert flags["docs_changed"] is True
63
+ assert flags["docs_only"] is True
64
+ assert flags["graph_artifact_changed"] is False
65
+ assert flags["graph_changed"] is True
66
+ assert flags["graph_only"] is True
67
+
68
+
69
  def test_mixed_graph_and_source_change_is_not_graph_only() -> None:
70
  flags = classify_paths(["graph/wiki-graph.tar.gz", "src/ctx/adapters/generic/loop.py"])
71
 
72
+ assert flags["graph_artifact_changed"] is True
73
  assert flags["graph_changed"] is True
74
  assert flags["graph_only"] is False
75
  assert flags["source_changed"] is True
76
 
77
 
78
+ def test_mixed_source_docs_and_graph_artifact_requests_specific_gates() -> None:
79
+ flags = classify_paths([
80
+ "src/ctx/core/wiki/wiki_graphify.py",
81
+ "docs/knowledge-graph.md",
82
+ "graph/wiki-graph.tar.gz",
83
+ ])
84
+
85
+ assert flags["docs_changed"] is True
86
+ assert flags["docs_only"] is False
87
+ assert flags["graph_artifact_changed"] is True
88
+ assert flags["graph_only"] is False
89
+ assert flags["source_changed"] is True
90
+
91
+
92
  def test_source_change_marks_source_and_package() -> None:
93
  flags = classify_paths(["src/ctx/adapters/generic/loop.py"])
94
 
 
105
  assert flags["package_changed"] is True
106
  assert flags["similarity_changed"] is True
107
  assert flags["source_changed"] is True
108
+ assert flags["docs_changed"] is False
109
  assert flags["docs_only"] is False
110
 
111
 
 
125
  assert "\npermissions:\n contents: read\n" in workflow
126
 
127
 
128
+ def test_graph_artifact_job_has_lfs_budget_fallback() -> None:
129
+ workflow = Path(".github/workflows/test.yml").read_text(encoding="utf-8")
130
+
131
+ assert "Resolve graph LFS artifacts" in workflow
132
+ assert "Git LFS artifact download failed; validating pointer metadata only." in workflow
133
+ assert "Validate graph artifact pointer when LFS unavailable" in workflow
134
+
135
+
136
  def test_publish_oidc_permission_is_limited_to_publish_job() -> None:
137
  workflow = Path(".github/workflows/publish.yml").read_text(encoding="utf-8")
138
  header = workflow.split("\njobs:\n", maxsplit=1)[0]
 
223
  written = output.read_text(encoding="utf-8").splitlines()
224
  assert "package_changed=true" in written
225
  assert "source_changed=true" in written
226
+ assert "docs_changed=false" in written
227
  assert "docs_only=false" in written
228
 
229
 
230
+ def test_main_handles_utf8_bom_changed_files(tmp_path: Path, monkeypatch) -> None:
231
+ changed = tmp_path / "changed-files.txt"
232
+ output = tmp_path / "github-output.txt"
233
+ changed.write_text("\ufeffgraph/wiki-graph.tar.gz\n", encoding="utf-8")
234
+ monkeypatch.setenv("GITHUB_OUTPUT", str(output))
235
+
236
+ assert main([str(changed)]) == 0
237
+
238
+ written = output.read_text(encoding="utf-8").splitlines()
239
+ assert "graph_artifact_changed=true" in written
240
+ assert "graph_only=true" in written
241
+
242
+
243
  def test_ci_required_allows_pr_policy_skip_on_push_only() -> None:
244
  needs = _required_needs(**{"no-test-no-merge": {"result": "skipped"}})
245
 
 
280
  needs = _required_needs(
281
  classify={
282
  "result": "success",
283
+ "outputs": {
284
+ "browser_changed": "false",
285
+ "docs_changed": "true",
286
+ "docs_only": "true",
287
+ "graph_artifact_changed": "false",
288
+ },
289
  },
290
  **{
291
  "graph-check": {"result": "skipped"},
 
308
 
309
  def test_ci_required_rejects_missing_docs_check_on_docs_only_pr() -> None:
310
  needs = _required_needs(
311
+ classify={
312
+ "result": "success",
313
+ "outputs": {"docs_changed": "true", "docs_only": "true"},
314
+ },
315
  **{"docs-check": {"result": "skipped"}},
316
  )
317
 
 
326
  "result": "success",
327
  "outputs": {
328
  "browser_changed": "false",
329
+ "docs_changed": "false",
330
  "docs_only": "false",
331
+ "graph_artifact_changed": "true",
332
  "graph_only": "true",
333
  },
334
  },
 
353
 
354
  def test_ci_required_rejects_missing_graph_check_on_graph_only_pr() -> None:
355
  needs = _required_needs(
356
+ classify={
357
+ "result": "success",
358
+ "outputs": {"graph_artifact_changed": "true", "graph_only": "true"},
359
+ },
360
  **{"graph-check": {"result": "skipped"}},
361
  )
362
 
 
381
  needs = _required_needs(
382
  classify={
383
  "result": "success",
384
+ "outputs": {
385
+ "docs_only": "false",
386
+ "graph_only": "false",
387
+ "similarity_changed": "true",
388
+ },
389
  },
390
  **{"similarity-integration": {"result": "skipped"}},
391
  )
 
434
  assert failed_required_jobs(needs, event_name="pull_request") == {
435
  "browser-security": "skipped",
436
  }
437
+
438
+
439
+ def test_ci_required_rejects_missing_docs_check_on_mixed_docs_pr() -> None:
440
+ needs = _required_needs(
441
+ classify={
442
+ "result": "success",
443
+ "outputs": {"docs_changed": "true", "docs_only": "false"},
444
+ },
445
+ **{"docs-check": {"result": "skipped"}},
446
+ )
447
+
448
+ assert failed_required_jobs(needs, event_name="pull_request") == {
449
+ "docs-check": "skipped",
450
+ }
451
+
452
+
453
+ def test_ci_required_rejects_missing_graph_check_on_mixed_artifact_pr() -> None:
454
+ needs = _required_needs(
455
+ classify={
456
+ "result": "success",
457
+ "outputs": {"graph_artifact_changed": "true", "graph_only": "false"},
458
+ },
459
+ **{"graph-check": {"result": "skipped"}},
460
+ )
461
+
462
+ assert failed_required_jobs(needs, event_name="pull_request") == {
463
+ "graph-check": "skipped",
464
+ }
src/tests/test_ctx_config.py CHANGED
@@ -128,10 +128,10 @@ class TestDefaults:
128
  assert c.intent_boost_per_signal == 5
129
  assert c.graph_edge_weight_semantic == 0.70
130
  assert c.graph_edge_weight_tags == 0.15
131
- assert c.graph_edge_weight_tokens == 0.15
132
- assert c.graph_semantic_top_k == 20
133
- assert c.graph_semantic_build_floor == 0.50
134
- assert c.graph_semantic_min_cosine == 0.80
135
  assert c.intake_enabled is True
136
 
137
  def test_meta_skills_default(self) -> None:
@@ -185,13 +185,13 @@ class TestRecommendationTopK:
185
 
186
 
187
  class TestEdgeWeights:
188
- def test_custom_weights_summing_to_one(self) -> None:
189
- c = Config({
190
- "graph": {
191
- "edge_weights": {"semantic": 0.5, "tags": 0.3, "slug_tokens": 0.2}
192
- }
193
- })
194
- assert c.graph_edge_weight_semantic == 0.5
195
 
196
  def test_weights_must_sum_to_one(self) -> None:
197
  with pytest.raises(ValueError, match="edge_weights must sum"):
@@ -203,27 +203,27 @@ class TestEdgeWeights:
203
  }
204
  })
205
 
206
- def test_negative_weight_rejected(self) -> None:
207
- with pytest.raises(ValueError, match=r"edge_weights\.\w+ must be >= 0"):
208
- Config({
209
- "graph": {
210
- "edge_weights": {
211
- "semantic": 1.1, "tags": -0.05, "slug_tokens": -0.05,
212
- }
213
- }
214
- })
215
-
216
- def test_tolerance_within_1e6(self) -> None:
217
- """Floats summing to 1.0000001 must still pass."""
218
- c = Config({
219
- "graph": {
220
- "edge_weights": {
221
- "semantic": 0.5000001, "tags": 0.25, "slug_tokens": 0.25,
222
- }
223
- }
224
- })
225
- assert c.graph_edge_weight_semantic == pytest.approx(0.5000001)
226
-
227
 
228
  # ── Semantic thresholds ──────────────────────────────────────────────────────
229
 
 
128
  assert c.intent_boost_per_signal == 5
129
  assert c.graph_edge_weight_semantic == 0.70
130
  assert c.graph_edge_weight_tags == 0.15
131
+ assert c.graph_edge_weight_tokens == 0.15
132
+ assert c.graph_semantic_top_k == 20
133
+ assert c.graph_semantic_build_floor == 0.50
134
+ assert c.graph_semantic_min_cosine == 0.80
135
  assert c.intake_enabled is True
136
 
137
  def test_meta_skills_default(self) -> None:
 
185
 
186
 
187
  class TestEdgeWeights:
188
+ def test_custom_weights_summing_to_one(self) -> None:
189
+ c = Config({
190
+ "graph": {
191
+ "edge_weights": {"semantic": 0.5, "tags": 0.3, "slug_tokens": 0.2}
192
+ }
193
+ })
194
+ assert c.graph_edge_weight_semantic == 0.5
195
 
196
  def test_weights_must_sum_to_one(self) -> None:
197
  with pytest.raises(ValueError, match="edge_weights must sum"):
 
203
  }
204
  })
205
 
206
+ def test_negative_weight_rejected(self) -> None:
207
+ with pytest.raises(ValueError, match=r"edge_weights\.\w+ must be >= 0"):
208
+ Config({
209
+ "graph": {
210
+ "edge_weights": {
211
+ "semantic": 1.1, "tags": -0.05, "slug_tokens": -0.05,
212
+ }
213
+ }
214
+ })
215
+
216
+ def test_tolerance_within_1e6(self) -> None:
217
+ """Floats summing to 1.0000001 must still pass."""
218
+ c = Config({
219
+ "graph": {
220
+ "edge_weights": {
221
+ "semantic": 0.5000001, "tags": 0.25, "slug_tokens": 0.25,
222
+ }
223
+ }
224
+ })
225
+ assert c.graph_edge_weight_semantic == pytest.approx(0.5000001)
226
+
227
 
228
  # ── Semantic thresholds ──────────────────────────────────────────────────────
229
 
src/tests/test_ctx_init.py CHANGED
@@ -399,6 +399,167 @@ repo_url: https://github.com/earthtojake/text-to-cad
399
  assert "openscad" in results[0]["fit_signals"]
400
 
401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  def test_recommend_harnesses_avoids_semantic_model_load_by_default(
403
  tmp_path: Path,
404
  monkeypatch,
 
399
  assert "openscad" in results[0]["fit_signals"]
400
 
401
 
402
+ def test_recommend_harnesses_surfaces_reliability_rubric(
403
+ tmp_path: Path,
404
+ monkeypatch,
405
+ ) -> None:
406
+ wiki = tmp_path / "wiki"
407
+ harness_dir = wiki / "entities" / "harnesses"
408
+ harness_dir.mkdir(parents=True)
409
+ (harness_dir / "reliable-agent.md").write_text(
410
+ """---
411
+ title: Reliable Agent
412
+ type: harness
413
+ tags:
414
+ - agents
415
+ model_providers:
416
+ - openai
417
+ capabilities:
418
+ - Persistent project context and task state
419
+ - Permission limits, sandbox rules, and policy checks
420
+ - Automated tests, evals, retry loops, and validation gates
421
+ verify_commands:
422
+ - pytest
423
+ repo_url: https://example.test/reliable-agent
424
+ ---
425
+ # Reliable Agent
426
+ """,
427
+ encoding="utf-8",
428
+ )
429
+ graph = nx.Graph()
430
+ graph.add_node(
431
+ "harness:reliable-agent",
432
+ label="reliable-agent",
433
+ type="harness",
434
+ tags=["agents"],
435
+ )
436
+ monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
437
+ import ctx_config
438
+
439
+ monkeypatch.setattr(
440
+ ctx_config,
441
+ "cfg",
442
+ SimpleNamespace(
443
+ wiki_dir=wiki,
444
+ claude_dir=tmp_path / ".claude",
445
+ recommendation_top_k=5,
446
+ harness_recommendation_min_fit_score=0.20,
447
+ harness_reliability_weights={
448
+ "context": 0.34,
449
+ "constraints": 0.33,
450
+ "convergence": 0.33,
451
+ },
452
+ ),
453
+ )
454
+
455
+ results = ci.recommend_harnesses(
456
+ "openai agent workflow with tests and sandbox",
457
+ model_provider="openai",
458
+ model="openai/gpt-5.5",
459
+ )
460
+
461
+ assert results
462
+ recommendation = results[0]
463
+ assert recommendation["name"] == "reliable-agent"
464
+ assert recommendation["reliability_score"] >= 0.90
465
+ assert set(recommendation["reliability_dimensions"]) == {
466
+ "context",
467
+ "constraints",
468
+ "convergence",
469
+ }
470
+ assert recommendation["reliability_dimensions"]["context"]["matched_terms"]
471
+ assert recommendation["reliability_dimensions"]["constraints"]["matched_terms"]
472
+ assert recommendation["reliability_dimensions"]["convergence"]["matched_terms"]
473
+ assert "context" in recommendation["reliability_reason"]
474
+ assert "constraints" in recommendation["reliability_reason"]
475
+ assert "convergence" in recommendation["reliability_reason"]
476
+
477
+
478
+ def test_recommend_harnesses_prefers_reliable_harness_when_fit_ties(
479
+ tmp_path: Path,
480
+ monkeypatch,
481
+ ) -> None:
482
+ wiki = tmp_path / "wiki"
483
+ harness_dir = wiki / "entities" / "harnesses"
484
+ harness_dir.mkdir(parents=True)
485
+ (harness_dir / "thin-agent.md").write_text(
486
+ """---
487
+ title: Thin Agent
488
+ type: harness
489
+ tags:
490
+ - agents
491
+ model_providers:
492
+ - openai
493
+ capabilities:
494
+ - Agent workflow orchestration
495
+ repo_url: https://example.test/thin-agent
496
+ ---
497
+ # Thin Agent
498
+ """,
499
+ encoding="utf-8",
500
+ )
501
+ (harness_dir / "reliable-agent.md").write_text(
502
+ """---
503
+ title: Reliable Agent
504
+ type: harness
505
+ tags:
506
+ - agents
507
+ model_providers:
508
+ - openai
509
+ capabilities:
510
+ - Agent workflow orchestration
511
+ - Persistent context state and durable task documents
512
+ - Permission limits, sandbox boundaries, and approval policies
513
+ - Automated tests, evals, validation gates, and retry loops
514
+ verify_commands:
515
+ - pytest
516
+ repo_url: https://example.test/reliable-agent
517
+ ---
518
+ # Reliable Agent
519
+ """,
520
+ encoding="utf-8",
521
+ )
522
+ graph = nx.Graph()
523
+ for slug in ("thin-agent", "reliable-agent"):
524
+ graph.add_node(
525
+ f"harness:{slug}",
526
+ label=slug,
527
+ type="harness",
528
+ tags=["agents"],
529
+ )
530
+ monkeypatch.setattr(ci, "_load_recommendation_graph", lambda: graph)
531
+ import ctx_config
532
+
533
+ monkeypatch.setattr(
534
+ ctx_config,
535
+ "cfg",
536
+ SimpleNamespace(
537
+ wiki_dir=wiki,
538
+ claude_dir=tmp_path / ".claude",
539
+ recommendation_top_k=5,
540
+ harness_recommendation_min_fit_score=0.20,
541
+ harness_reliability_weights={
542
+ "context": 0.34,
543
+ "constraints": 0.33,
544
+ "convergence": 0.33,
545
+ },
546
+ ),
547
+ )
548
+
549
+ results = ci.recommend_harnesses(
550
+ "openai agent workflow",
551
+ model_provider="openai",
552
+ model="openai/gpt-5.5",
553
+ )
554
+
555
+ assert [row["name"] for row in results[:2]] == [
556
+ "reliable-agent",
557
+ "thin-agent",
558
+ ]
559
+ assert results[0]["fit_score"] == results[1]["fit_score"]
560
+ assert results[0]["reliability_score"] > results[1]["reliability_score"]
561
+
562
+
563
  def test_recommend_harnesses_avoids_semantic_model_load_by_default(
564
  tmp_path: Path,
565
  monkeypatch,
src/tests/test_ctx_monitor.py CHANGED
@@ -40,6 +40,14 @@ def _write_events(claude: Path, records: list[dict]) -> None:
40
  )
41
 
42
 
 
 
 
 
 
 
 
 
43
  def _write_sidecar(claude: Path, slug: str, body: dict) -> None:
44
  (claude / "skill-quality" / f"{slug}.json").write_text(
45
  json.dumps(body), encoding="utf-8",
@@ -311,11 +319,20 @@ def test_queue_status_summarizes_worker_jobs(fake_claude: Path) -> None:
311
  source="test",
312
  now=11.0,
313
  )
 
 
 
 
 
 
 
314
  leased = wiki_queue.lease_next(db_path, worker_id="worker-a", now=12.0)
315
  assert leased is not None
316
  wiki_queue.mark_failed(db_path, leased.id, error="boom", retry=False, now=13.0)
 
317
 
318
  status = cm._queue_status()
 
319
 
320
  assert status["available"] is True
321
  assert status["counts"] == {
@@ -323,10 +340,12 @@ def test_queue_status_summarizes_worker_jobs(fake_claude: Path) -> None:
323
  wiki_queue.STATUS_RUNNING: 0,
324
  wiki_queue.STATUS_SUCCEEDED: 0,
325
  wiki_queue.STATUS_FAILED: 1,
 
326
  }
327
- assert status["total"] == 2
328
- assert [job["id"] for job in status["recent_jobs"]] == [second.id, first.id]
329
- assert status["recent_jobs"][0]["kind"] == wiki_queue.TAR_REFRESH_JOB
 
330
 
331
 
332
  def test_artifact_status_reads_promotion_metadata(
@@ -398,6 +417,33 @@ def test_status_page_and_api_show_queue_and_artifacts(
398
  server.server_close()
399
 
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  def test_render_loaded_shows_manifest_entries(fake_claude: Path) -> None:
402
  (fake_claude / "skill-manifest.json").write_text(
403
  json.dumps({
@@ -434,6 +480,92 @@ def test_render_loaded_shows_harness_install_without_unload_button(fake_claude:
434
  assert "data-slug='langgraph'" not in html
435
 
436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  def test_render_logs_filters_and_renders(fake_claude: Path) -> None:
438
  _write_audit(fake_claude, [
439
  {"ts": "t1", "event": "skill.loaded", "subject_type": "skill",
 
40
  )
41
 
42
 
43
+ def _write_runtime_events(path: Path, records: list[dict]) -> None:
44
+ path.parent.mkdir(parents=True, exist_ok=True)
45
+ path.write_text(
46
+ "\n".join(json.dumps(r) for r in records) + "\n",
47
+ encoding="utf-8",
48
+ )
49
+
50
+
51
  def _write_sidecar(claude: Path, slug: str, body: dict) -> None:
52
  (claude / "skill-quality" / f"{slug}.json").write_text(
53
  json.dumps(body), encoding="utf-8",
 
319
  source="test",
320
  now=11.0,
321
  )
322
+ third = wiki_queue.enqueue_maintenance_job(
323
+ wiki,
324
+ kind=wiki_queue.CATALOG_REFRESH_JOB,
325
+ payload={"catalog": "graph/skills-sh-catalog.json.gz"},
326
+ source="test",
327
+ now=12.0,
328
+ )
329
  leased = wiki_queue.lease_next(db_path, worker_id="worker-a", now=12.0)
330
  assert leased is not None
331
  wiki_queue.mark_failed(db_path, leased.id, error="boom", retry=False, now=13.0)
332
+ wiki_queue.cancel_job(db_path, third.id, reason="operator skipped", now=14.0)
333
 
334
  status = cm._queue_status()
335
+ html_out = cm._render_status()
336
 
337
  assert status["available"] is True
338
  assert status["counts"] == {
 
340
  wiki_queue.STATUS_RUNNING: 0,
341
  wiki_queue.STATUS_SUCCEEDED: 0,
342
  wiki_queue.STATUS_FAILED: 1,
343
+ wiki_queue.STATUS_CANCELLED: 1,
344
  }
345
+ assert status["total"] == 3
346
+ assert [job["id"] for job in status["recent_jobs"]] == [third.id, second.id, first.id]
347
+ assert status["recent_jobs"][0]["status"] == wiki_queue.STATUS_CANCELLED
348
+ assert "cancelled: 1" in html_out
349
 
350
 
351
  def test_artifact_status_reads_promotion_metadata(
 
417
  server.server_close()
418
 
419
 
420
+ def test_status_page_shows_queue_db_errors(
421
+ fake_claude: Path,
422
+ monkeypatch: pytest.MonkeyPatch,
423
+ ) -> None:
424
+ db_path = wiki_queue.queue_db_path(fake_claude / "skill-wiki")
425
+ db_path.parent.mkdir(parents=True)
426
+ db_path.write_bytes(b"exists")
427
+
428
+ def fail_count_jobs_by_status(_db_path: Path) -> dict[str, int]:
429
+ raise RuntimeError("cannot read queue")
430
+
431
+ monkeypatch.setattr(
432
+ cm.wiki_queue,
433
+ "count_jobs_by_status",
434
+ fail_count_jobs_by_status,
435
+ )
436
+
437
+ status = cm._queue_status()
438
+ html_out = cm._render_status()
439
+
440
+ assert status["available"] is False
441
+ assert status["error"] == "cannot read queue"
442
+ assert "Queue DB error" in html_out
443
+ assert "cannot read queue" in html_out
444
+ assert "Durable worker DB: error" in html_out
445
+
446
+
447
  def test_render_loaded_shows_manifest_entries(fake_claude: Path) -> None:
448
  (fake_claude / "skill-manifest.json").write_text(
449
  json.dumps({
 
480
  assert "data-slug='langgraph'" not in html
481
 
482
 
483
+ def test_runtime_lifecycle_summary_reads_validation_and_escalation_events(
484
+ tmp_path: Path,
485
+ monkeypatch: pytest.MonkeyPatch,
486
+ ) -> None:
487
+ events = tmp_path / "runtime" / "events.jsonl"
488
+ monkeypatch.setattr(cm, "_runtime_lifecycle_path", lambda: events)
489
+ _write_runtime_events(events, [
490
+ {
491
+ "action": "validation",
492
+ "session_id": "s-1",
493
+ "check_name": "pytest",
494
+ "status": "passed",
495
+ "created_at": "2026-05-08T01:00:00Z",
496
+ },
497
+ {
498
+ "action": "validation",
499
+ "session_id": "s-1",
500
+ "check_name": "mypy",
501
+ "status": "failed",
502
+ "summary": "type gate failed",
503
+ "created_at": "2026-05-08T01:05:00Z",
504
+ },
505
+ {
506
+ "action": "escalation",
507
+ "session_id": "s-1",
508
+ "trigger": "validation-failed",
509
+ "reason": "mypy failed after retry",
510
+ "status": "open",
511
+ "severity": "blocking",
512
+ "created_at": "2026-05-08T01:06:00Z",
513
+ },
514
+ {
515
+ "action": "escalation",
516
+ "session_id": "s-2",
517
+ "trigger": "user-review",
518
+ "reason": "review completed",
519
+ "status": "resolved",
520
+ "severity": "info",
521
+ "created_at": "2026-05-08T01:07:00Z",
522
+ },
523
+ ])
524
+
525
+ summary = cm._runtime_lifecycle_summary()
526
+
527
+ assert summary["validations_total"] == 2
528
+ assert summary["validation_failures"] == 1
529
+ assert summary["open_escalations_total"] == 1
530
+ assert summary["latest_validation"]["check_name"] == "mypy"
531
+ assert summary["open_escalations"][0]["trigger"] == "validation-failed"
532
+
533
+
534
+ def test_render_runtime_lifecycle_surfaces_checks_and_open_escalations(
535
+ tmp_path: Path,
536
+ monkeypatch: pytest.MonkeyPatch,
537
+ ) -> None:
538
+ events = tmp_path / "runtime" / "events.jsonl"
539
+ monkeypatch.setattr(cm, "_runtime_lifecycle_path", lambda: events)
540
+ _write_runtime_events(events, [
541
+ {
542
+ "action": "validation",
543
+ "session_id": "s-1",
544
+ "check_name": "mypy",
545
+ "status": "failed",
546
+ "summary": "<type gate failed>",
547
+ "created_at": "2026-05-08T01:05:00Z",
548
+ },
549
+ {
550
+ "action": "escalation",
551
+ "session_id": "s-1",
552
+ "trigger": "validation-failed",
553
+ "reason": "<mypy failed>",
554
+ "status": "open",
555
+ "severity": "blocking",
556
+ "created_at": "2026-05-08T01:06:00Z",
557
+ },
558
+ ])
559
+
560
+ html = cm._render_runtime_lifecycle()
561
+
562
+ assert "Runtime lifecycle" in html
563
+ assert "mypy" in html
564
+ assert "validation-failed" in html
565
+ assert "&lt;type gate failed&gt;" in html
566
+ assert "&lt;mypy failed&gt;" in html
567
+
568
+
569
  def test_render_logs_filters_and_renders(fake_claude: Path) -> None:
570
  _write_audit(fake_claude, [
571
  {"ts": "t1", "event": "skill.loaded", "subject_type": "skill",
src/tests/test_ctx_monitor_3type.py CHANGED
@@ -206,6 +206,38 @@ class TestWikiIndexEntries:
206
  # ────────────────────────────────────────────────────────────────────
207
 
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  class TestRenderHome3Type:
210
  def test_wiki_card_shows_mcp_count(self, wiki_3type, monkeypatch):
211
  # Other dependencies of _render_home need shims that don't touch
 
206
  # ────────────────────────────────────────────────────────────────────
207
 
208
 
209
+ def test_wiki_index_sampling_is_sorted_by_slug(wiki_3type: Path) -> None:
210
+ (wiki_3type / "entities" / "skills" / "aaa-first.md").write_text(
211
+ "---\ntype: skill\ndescription: first\n---\n# aaa-first\n",
212
+ encoding="utf-8",
213
+ )
214
+
215
+ entries = _cm._wiki_index_entries(limit_per_type=1)
216
+ skill_entries = [entry for entry in entries if entry["type"] == "skill"]
217
+
218
+ assert [entry["slug"] for entry in skill_entries] == ["aaa-first"]
219
+
220
+
221
+ def test_wiki_entity_page_marks_truncated_body_and_frontmatter(
222
+ wiki_3type: Path,
223
+ ) -> None:
224
+ long_description = "x" * 160
225
+ long_body = "body-line\n" * 1400
226
+ (wiki_3type / "entities" / "skills" / "long-page.md").write_text(
227
+ "---\n"
228
+ f"description: {long_description}\n"
229
+ "type: skill\n"
230
+ "---\n"
231
+ f"{long_body}",
232
+ encoding="utf-8",
233
+ )
234
+
235
+ html = _cm._render_wiki_entity("long-page", entity_type="skill")
236
+
237
+ assert "Body preview truncated at 12,000 characters." in html
238
+ assert "(truncated)" in html
239
+
240
+
241
  class TestRenderHome3Type:
242
  def test_wiki_card_shows_mcp_count(self, wiki_3type, monkeypatch):
243
  # Other dependencies of _render_home need shims that don't touch
src/tests/test_harness_cli_run.py CHANGED
@@ -218,6 +218,13 @@ class TestToolPolicy:
218
 
219
 
220
  class TestRunCommand:
 
 
 
 
 
 
 
221
  def test_happy_path_writes_session(
222
  self, fake_litellm: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str],
223
  ) -> None:
@@ -239,6 +246,101 @@ class TestRunCommand:
239
  captured = capsys.readouterr()
240
  assert "final answer" in captured.out
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  def test_session_id_flag_pins_id(
243
  self, fake_litellm: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str],
244
  ) -> None:
@@ -397,10 +499,15 @@ class TestRunCommand:
397
  assert "session_id" in payload
398
 
399
  def test_model_required(
400
- self, capsys: pytest.CaptureFixture[str],
 
 
 
401
  ) -> None:
402
- with pytest.raises(SystemExit):
403
- main(["run", "--task", "hi"])
 
 
404
 
405
  def test_task_required(
406
  self, capsys: pytest.CaptureFixture[str],
 
218
 
219
 
220
  class TestRunCommand:
221
+ def _write_model_profile(self, root: Path, data: dict[str, Any]) -> None:
222
+ root.mkdir(parents=True)
223
+ (root / "ctx-model-profile.json").write_text(
224
+ json.dumps(data),
225
+ encoding="utf-8",
226
+ )
227
+
228
  def test_happy_path_writes_session(
229
  self, fake_litellm: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str],
230
  ) -> None:
 
246
  captured = capsys.readouterr()
247
  assert "final answer" in captured.out
248
 
249
+ def test_run_uses_ctx_init_model_profile_when_model_omitted(
250
+ self,
251
+ fake_litellm: Any,
252
+ tmp_path: Path,
253
+ monkeypatch: pytest.MonkeyPatch,
254
+ capsys: pytest.CaptureFixture[str],
255
+ ) -> None:
256
+ claude = tmp_path / "claude"
257
+ sessions = tmp_path / "sessions"
258
+ self._write_model_profile(
259
+ claude,
260
+ {
261
+ "mode": "custom",
262
+ "provider": "openai",
263
+ "model": "openai/gpt-5.5",
264
+ "api_key_env": "OPENAI_API_KEY",
265
+ "base_url": "https://api.example.test/v1",
266
+ "goal": "build agents",
267
+ },
268
+ )
269
+ monkeypatch.setattr(run_cli, "_claude_dir", lambda: claude)
270
+ monkeypatch.setenv("OPENAI_API_KEY", "profile-secret")
271
+
272
+ exit_code = main(
273
+ [
274
+ "run",
275
+ "--task", "say hi",
276
+ "--sessions-dir", str(sessions),
277
+ "--session-id", "profile-run",
278
+ "--no-ctx-tools",
279
+ "--quiet",
280
+ ],
281
+ )
282
+
283
+ assert exit_code == 0
284
+ call = fake_litellm._calls[0]
285
+ assert call["model"] == "openai/gpt-5.5"
286
+ assert call["api_key"] == "profile-secret"
287
+ assert call["api_base"] == "https://api.example.test/v1"
288
+ first_line = (sessions / "profile-run.jsonl").read_text(
289
+ encoding="utf-8",
290
+ ).splitlines()[0]
291
+ event = json.loads(first_line)
292
+ assert event["model"] == "openai/gpt-5.5"
293
+ assert event["provider"] == "openai"
294
+ assert event["api_key_env"] == "OPENAI_API_KEY"
295
+ captured = capsys.readouterr()
296
+ assert "final answer" in captured.out
297
+
298
+ def test_cli_model_override_does_not_inherit_stale_profile_provider(
299
+ self,
300
+ fake_litellm: Any,
301
+ tmp_path: Path,
302
+ monkeypatch: pytest.MonkeyPatch,
303
+ ) -> None:
304
+ claude = tmp_path / "claude"
305
+ sessions = tmp_path / "sessions"
306
+ self._write_model_profile(
307
+ claude,
308
+ {
309
+ "mode": "custom",
310
+ "provider": "openai",
311
+ "model": "openai/gpt-5.5",
312
+ "api_key_env": "OPENAI_API_KEY",
313
+ "base_url": "https://api.example.test/v1",
314
+ },
315
+ )
316
+ monkeypatch.setattr(run_cli, "_claude_dir", lambda: claude)
317
+ monkeypatch.setenv("OPENAI_API_KEY", "profile-secret")
318
+
319
+ exit_code = main(
320
+ [
321
+ "run",
322
+ "--model", "ollama/qwen",
323
+ "--task", "say hi",
324
+ "--sessions-dir", str(sessions),
325
+ "--session-id", "override-run",
326
+ "--no-ctx-tools",
327
+ "--quiet",
328
+ ],
329
+ )
330
+
331
+ assert exit_code == 0
332
+ call = fake_litellm._calls[0]
333
+ assert call["model"] == "ollama/qwen"
334
+ assert "api_key" not in call
335
+ assert "api_base" not in call
336
+ first_line = (sessions / "override-run.jsonl").read_text(
337
+ encoding="utf-8",
338
+ ).splitlines()[0]
339
+ event = json.loads(first_line)
340
+ assert event["provider"] == "ollama"
341
+ assert event["api_key_env"] == ""
342
+ assert event["base_url"] == ""
343
+
344
  def test_session_id_flag_pins_id(
345
  self, fake_litellm: Any, tmp_path: Path, capsys: pytest.CaptureFixture[str],
346
  ) -> None:
 
499
  assert "session_id" in payload
500
 
501
  def test_model_required(
502
+ self,
503
+ tmp_path: Path,
504
+ monkeypatch: pytest.MonkeyPatch,
505
+ capsys: pytest.CaptureFixture[str],
506
  ) -> None:
507
+ monkeypatch.setattr(run_cli, "_claude_dir", lambda: tmp_path / "claude")
508
+
509
+ assert main(["run", "--task", "hi"]) == 2
510
+ assert "--model is required" in capsys.readouterr().err
511
 
512
  def test_task_required(
513
  self, capsys: pytest.CaptureFixture[str],
src/tests/test_harness_ctx_core.py CHANGED
@@ -159,6 +159,8 @@ class TestToolDefinitions:
159
  "ctx__observe_dev_event",
160
  "ctx__load_entity",
161
  "ctx__mark_entity_used",
 
 
162
  "ctx__unload_entity",
163
  "ctx__session_end",
164
  "ctx__session_state",
@@ -228,6 +230,19 @@ class TestRuntimeLifecycle:
228
  "slug": "fastapi-pro",
229
  "evidence": "used in implementation",
230
  }),
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  ("ctx__unload_entity", {
232
  "session_id": "s-1",
233
  "entity_type": "skill",
@@ -253,6 +268,8 @@ class TestRuntimeLifecycle:
253
  "dev_event",
254
  "load_requested",
255
  "used",
 
 
256
  "unload_requested",
257
  "session_end",
258
  ]
@@ -315,7 +332,138 @@ class TestRuntimeLifecycle:
315
  ]
316
 
317
 
318
- # ── recommend_bundle ───────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
 
320
 
321
  class TestRecommendBundle:
@@ -338,6 +486,97 @@ class TestRecommendBundle:
338
  names = [r["name"] for r in result["results"]]
339
  assert "fastapi-pro" in names
340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  def test_empty_query(self, toolbox: CtxCoreToolbox) -> None:
342
  result = json.loads(
343
  toolbox.dispatch(
 
159
  "ctx__observe_dev_event",
160
  "ctx__load_entity",
161
  "ctx__mark_entity_used",
162
+ "ctx__record_validation",
163
+ "ctx__record_escalation",
164
  "ctx__unload_entity",
165
  "ctx__session_end",
166
  "ctx__session_state",
 
230
  "slug": "fastapi-pro",
231
  "evidence": "used in implementation",
232
  }),
233
+ ("ctx__record_validation", {
234
+ "session_id": "s-1",
235
+ "check_name": "pytest",
236
+ "status": "passed",
237
+ "command": "python -m pytest",
238
+ "summary": "all tests passed",
239
+ }),
240
+ ("ctx__record_escalation", {
241
+ "session_id": "s-1",
242
+ "trigger": "destructive-action",
243
+ "reason": "delete requires user approval",
244
+ "severity": "blocking",
245
+ }),
246
  ("ctx__unload_entity", {
247
  "session_id": "s-1",
248
  "entity_type": "skill",
 
268
  "dev_event",
269
  "load_requested",
270
  "used",
271
+ "validation",
272
+ "escalation",
273
  "unload_requested",
274
  "session_end",
275
  ]
 
332
  ]
333
 
334
 
335
+ # -- runtime validation ledger ----------------------------------------------
336
+
337
+
338
+ class TestRuntimeValidationLedger:
339
+ def test_session_state_surfaces_validation_and_escalation_ledger(
340
+ self,
341
+ toolbox: CtxCoreToolbox,
342
+ ) -> None:
343
+ for name, arguments in [
344
+ ("ctx__record_validation", {
345
+ "session_id": "s-ledger",
346
+ "check_name": "mypy",
347
+ "status": "failed",
348
+ "command": "python -m mypy src",
349
+ "summary": "type gate failed",
350
+ "payload": {"errors": 3},
351
+ }),
352
+ ("ctx__record_escalation", {
353
+ "session_id": "s-ledger",
354
+ "trigger": "validation-failed",
355
+ "reason": "mypy failed after retry",
356
+ "severity": "blocking",
357
+ "payload": {"check_name": "mypy"},
358
+ }),
359
+ ]:
360
+ result = json.loads(
361
+ toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
362
+ )
363
+ assert result["ok"] is True
364
+
365
+ state = json.loads(
366
+ toolbox.dispatch(ToolCall(
367
+ id="c1",
368
+ name="ctx__session_state",
369
+ arguments={"session_id": "s-ledger"},
370
+ ))
371
+ )
372
+
373
+ assert state["validations"] == [{
374
+ "check_name": "mypy",
375
+ "status": "failed",
376
+ "command": "python -m mypy src",
377
+ "summary": "type gate failed",
378
+ "entity_type": None,
379
+ "slug": None,
380
+ "payload": {"errors": 3},
381
+ }]
382
+ assert state["escalations"] == [{
383
+ "trigger": "validation-failed",
384
+ "reason": "mypy failed after retry",
385
+ "severity": "blocking",
386
+ "status": "open",
387
+ "entity_type": None,
388
+ "slug": None,
389
+ "payload": {"check_name": "mypy"},
390
+ }]
391
+ assert state["latest_validation_status"] == "failed"
392
+ assert state["open_escalations"] == state["escalations"]
393
+
394
+ def test_invalid_validation_status_is_structured(
395
+ self,
396
+ toolbox: CtxCoreToolbox,
397
+ ) -> None:
398
+ result = json.loads(
399
+ toolbox.dispatch(ToolCall(
400
+ id="c1",
401
+ name="ctx__record_validation",
402
+ arguments={
403
+ "session_id": "s-ledger",
404
+ "check_name": "pytest",
405
+ "status": "maybe",
406
+ },
407
+ ))
408
+ )
409
+
410
+ assert result["ok"] is False
411
+ assert "status" in result["error"]
412
+
413
+
414
+ # -- recommend_bundle --------------------------------------------------------
415
+
416
+
417
+ def test_session_state_suppresses_current_dev_window_unloads(
418
+ toolbox: CtxCoreToolbox,
419
+ monkeypatch: pytest.MonkeyPatch,
420
+ ) -> None:
421
+ from ctx.adapters.generic import runtime_lifecycle
422
+
423
+ timestamps = iter([100.0, 101.0, 102.0, 103.0, 104.0, 105.0])
424
+ monkeypatch.setattr(runtime_lifecycle.time, "time", lambda: next(timestamps))
425
+
426
+ for name, arguments in [
427
+ ("ctx__observe_dev_event", {
428
+ "session_id": "s-window",
429
+ "event_type": "task",
430
+ }),
431
+ ("ctx__load_entity", {
432
+ "session_id": "s-window",
433
+ "entity_type": "skill",
434
+ "slug": "fastapi-pro",
435
+ }),
436
+ ]:
437
+ toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
438
+
439
+ current_window = json.loads(
440
+ toolbox.dispatch(ToolCall(
441
+ id="c1",
442
+ name="ctx__session_state",
443
+ arguments={"session_id": "s-window"},
444
+ ))
445
+ )
446
+ assert current_window["unload_candidates"] == []
447
+
448
+ for name, arguments in [
449
+ ("ctx__session_end", {"session_id": "s-window"}),
450
+ ("ctx__observe_dev_event", {
451
+ "session_id": "s-window",
452
+ "event_type": "resume",
453
+ }),
454
+ ]:
455
+ toolbox.dispatch(ToolCall(id="c1", name=name, arguments=arguments))
456
+
457
+ next_window = json.loads(
458
+ toolbox.dispatch(ToolCall(
459
+ id="c1",
460
+ name="ctx__session_state",
461
+ arguments={"session_id": "s-window"},
462
+ ))
463
+ )
464
+ assert [entry["slug"] for entry in next_window["unload_candidates"]] == [
465
+ "fastapi-pro",
466
+ ]
467
 
468
 
469
  class TestRecommendBundle:
 
486
  names = [r["name"] for r in result["results"]]
487
  assert "fastapi-pro" in names
488
 
489
+ def test_companion_harnesses_are_separate_from_dev_results(
490
+ self,
491
+ toolbox: CtxCoreToolbox,
492
+ monkeypatch: pytest.MonkeyPatch,
493
+ ) -> None:
494
+ import ctx_init
495
+
496
+ calls: list[dict[str, Any]] = []
497
+
498
+ def fake_recommend_harnesses(
499
+ goal: str,
500
+ *,
501
+ top_k: int = 5,
502
+ model_provider: str | None = None,
503
+ model: str | None = None,
504
+ ) -> list[dict[str, Any]]:
505
+ calls.append({
506
+ "goal": goal,
507
+ "top_k": top_k,
508
+ "model_provider": model_provider,
509
+ "model": model,
510
+ })
511
+ return [{
512
+ "name": "langgraph",
513
+ "fit_score": 0.92,
514
+ "normalized_score": 0.88,
515
+ "matching_tags": ["agents"],
516
+ "provider_match": "openai",
517
+ "detail_url": "https://example.test/langgraph",
518
+ "install_command": "ctx-harness-install langgraph",
519
+ }]
520
+
521
+ monkeypatch.setattr(ctx_init, "recommend_harnesses", fake_recommend_harnesses)
522
+
523
+ result = json.loads(
524
+ toolbox.dispatch(
525
+ ToolCall(
526
+ id="c1",
527
+ name="ctx__recommend_bundle",
528
+ arguments={
529
+ "query": "python agent workflow",
530
+ "top_k": 5,
531
+ "model_provider": "openai",
532
+ "model": "openai/gpt-5.5",
533
+ },
534
+ )
535
+ )
536
+ )
537
+
538
+ assert calls == [{
539
+ "goal": "python agent workflow",
540
+ "top_k": 5,
541
+ "model_provider": "openai",
542
+ "model": "openai/gpt-5.5",
543
+ }]
544
+ assert all(row["type"] != "harness" for row in result["results"])
545
+ assert result["companion_harnesses"] == [{
546
+ "name": "langgraph",
547
+ "type": "harness",
548
+ "fit_score": 0.92,
549
+ "normalized_score": 0.88,
550
+ "matching_tags": ["agents"],
551
+ "provider_match": "openai",
552
+ "detail_url": "https://example.test/langgraph",
553
+ "install_command": "ctx-harness-install langgraph",
554
+ }]
555
+
556
+ def test_companion_harnesses_can_be_empty(
557
+ self,
558
+ toolbox: CtxCoreToolbox,
559
+ monkeypatch: pytest.MonkeyPatch,
560
+ ) -> None:
561
+ import ctx_init
562
+
563
+ monkeypatch.setattr(ctx_init, "recommend_harnesses", lambda *a, **kw: [])
564
+
565
+ result = json.loads(
566
+ toolbox.dispatch(
567
+ ToolCall(
568
+ id="c1",
569
+ name="ctx__recommend_bundle",
570
+ arguments={
571
+ "query": "python web api",
572
+ "model_provider": "ollama",
573
+ },
574
+ )
575
+ )
576
+ )
577
+
578
+ assert result["companion_harnesses"] == []
579
+
580
  def test_empty_query(self, toolbox: CtxCoreToolbox) -> None:
581
  result = json.loads(
582
  toolbox.dispatch(
src/tests/test_import_skills_sh_catalog.py CHANGED
@@ -4,6 +4,7 @@ import json
4
  import sys
5
  import tarfile
6
  import zlib
 
7
  from io import BytesIO
8
  from pathlib import Path
9
  from typing import Any
@@ -16,6 +17,7 @@ from import_skills_sh_catalog import (
16
  drop_body_unavailable_skills,
17
  normalize_catalog,
18
  update_wiki_tarball,
 
19
  )
20
 
21
 
@@ -36,6 +38,52 @@ def _read_json(tf: tarfile.TarFile, name: str) -> dict[str, Any]:
36
  return data
37
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def test_normalize_catalog_resolves_truncated_ctx_slug_collisions(monkeypatch) -> None:
40
  monkeypatch.setattr(
41
  "import_skills_sh_catalog._read_site_reported_total",
@@ -71,6 +119,7 @@ def test_normalize_catalog_resolves_truncated_ctx_slug_collisions(monkeypatch) -
71
 
72
  def test_update_wiki_tarball_adds_skills_sh_as_first_class_skill_nodes_and_pages(
73
  tmp_path: Path,
 
74
  ) -> None:
75
  tarball = tmp_path / "wiki-graph.tar.gz"
76
  graph = {
@@ -120,6 +169,15 @@ def test_update_wiki_tarball_adds_skills_sh_as_first_class_skill_nodes_and_pages
120
  ],
121
  }
122
 
 
 
 
 
 
 
 
 
 
123
  update_wiki_tarball(tarball, catalog)
124
 
125
  with tarfile.open(tarball, "r:gz") as tf:
@@ -148,6 +206,8 @@ def test_update_wiki_tarball_adds_skills_sh_as_first_class_skill_nodes_and_pages
148
  assert catalog_out["body_available_count"] == 0
149
  assert "body_available: false" in page
150
  assert "Security review: metadata-only" in page
 
 
151
 
152
 
153
  def test_update_wiki_tarball_preserves_existing_skills_sh_semantic_edges(
 
4
  import sys
5
  import tarfile
6
  import zlib
7
+ import gzip
8
  from io import BytesIO
9
  from pathlib import Path
10
  from typing import Any
 
17
  drop_body_unavailable_skills,
18
  normalize_catalog,
19
  update_wiki_tarball,
20
+ write_gzip_json,
21
  )
22
 
23
 
 
38
  return data
39
 
40
 
41
+ def _read_gzip_json(path: Path) -> dict[str, Any]:
42
+ with gzip.open(path, "rt", encoding="utf-8") as fh:
43
+ data = json.load(fh)
44
+ assert isinstance(data, dict)
45
+ return data
46
+
47
+
48
+ def test_write_gzip_json_promotes_validated_catalog_with_metadata(tmp_path: Path) -> None:
49
+ catalog_path = tmp_path / "skills-sh-catalog.json.gz"
50
+ write_gzip_json(catalog_path, {"skills": [{"ctx_slug": "old"}]})
51
+
52
+ write_gzip_json(catalog_path, {"skills": [{"ctx_slug": "new"}]})
53
+
54
+ assert _read_gzip_json(catalog_path)["skills"][0]["ctx_slug"] == "new"
55
+ assert not catalog_path.with_name("skills-sh-catalog.json.gz.staged").exists()
56
+ metadata = json.loads(
57
+ catalog_path.with_name("skills-sh-catalog.json.gz.promotion.json").read_text(
58
+ encoding="utf-8",
59
+ ),
60
+ )
61
+ assert metadata["status"] == "promoted"
62
+ assert metadata["target"].endswith("skills-sh-catalog.json.gz")
63
+ assert metadata["last_good"]["exists"] is True
64
+ assert metadata["rollback"]["available"] is True
65
+
66
+
67
+ def test_write_gzip_json_validation_failure_preserves_previous_catalog(
68
+ tmp_path: Path,
69
+ monkeypatch: Any,
70
+ ) -> None:
71
+ catalog_path = tmp_path / "skills-sh-catalog.json.gz"
72
+ write_gzip_json(catalog_path, {"skills": [{"ctx_slug": "old"}]})
73
+ original = catalog_path.read_bytes()
74
+
75
+ def fail_validation(_path: Path, *, required_keys: tuple[str, ...] = ()) -> None:
76
+ raise ValueError("catalog candidate invalid")
77
+
78
+ monkeypatch.setattr(importer, "validate_gzip_json_artifact", fail_validation)
79
+
80
+ with pytest.raises(ValueError, match="catalog candidate invalid"):
81
+ write_gzip_json(catalog_path, {"skills": [{"ctx_slug": "new"}]})
82
+
83
+ assert catalog_path.read_bytes() == original
84
+ assert _read_gzip_json(catalog_path)["skills"][0]["ctx_slug"] == "old"
85
+
86
+
87
  def test_normalize_catalog_resolves_truncated_ctx_slug_collisions(monkeypatch) -> None:
88
  monkeypatch.setattr(
89
  "import_skills_sh_catalog._read_site_reported_total",
 
119
 
120
  def test_update_wiki_tarball_adds_skills_sh_as_first_class_skill_nodes_and_pages(
121
  tmp_path: Path,
122
+ monkeypatch: Any,
123
  ) -> None:
124
  tarball = tmp_path / "wiki-graph.tar.gz"
125
  graph = {
 
169
  ],
170
  }
171
 
172
+ real_promote = importer.promote_staged_artifact
173
+ promoted_paths: list[tuple[str, str]] = []
174
+
175
+ def capture_promotion(staged_path: Path, target_path: Path, **kwargs: Any) -> Any:
176
+ promoted_paths.append((Path(staged_path).name, Path(target_path).name))
177
+ return real_promote(staged_path, target_path, **kwargs)
178
+
179
+ monkeypatch.setattr(importer, "promote_staged_artifact", capture_promotion)
180
+
181
  update_wiki_tarball(tarball, catalog)
182
 
183
  with tarfile.open(tarball, "r:gz") as tf:
 
206
  assert catalog_out["body_available_count"] == 0
207
  assert "body_available: false" in page
208
  assert "Security review: metadata-only" in page
209
+ assert promoted_paths == [("wiki-graph.tar.gz.staged", "wiki-graph.tar.gz")]
210
+ assert not tarball.with_name("wiki-graph.tar.gz.staged").exists()
211
 
212
 
213
  def test_update_wiki_tarball_preserves_existing_skills_sh_semantic_edges(
src/tests/test_mcp_server.py CHANGED
@@ -60,6 +60,8 @@ _EXPECTED_TOOL_NAMES = {
60
  "ctx__observe_dev_event",
61
  "ctx__load_entity",
62
  "ctx__mark_entity_used",
 
 
63
  "ctx__unload_entity",
64
  "ctx__session_end",
65
  "ctx__session_state",
 
60
  "ctx__observe_dev_event",
61
  "ctx__load_entity",
62
  "ctx__mark_entity_used",
63
+ "ctx__record_validation",
64
+ "ctx__record_escalation",
65
  "ctx__unload_entity",
66
  "ctx__session_end",
67
  "ctx__session_state",
src/tests/test_public_api.py CHANGED
@@ -365,6 +365,8 @@ class TestCtxCoreToolboxRexport:
365
  "ctx__observe_dev_event",
366
  "ctx__load_entity",
367
  "ctx__mark_entity_used",
 
 
368
  "ctx__unload_entity",
369
  "ctx__session_end",
370
  "ctx__session_state",
 
365
  "ctx__observe_dev_event",
366
  "ctx__load_entity",
367
  "ctx__mark_entity_used",
368
+ "ctx__record_validation",
369
+ "ctx__record_escalation",
370
  "ctx__unload_entity",
371
  "ctx__session_end",
372
  "ctx__session_state",
src/tests/test_validate_graph_artifacts.py CHANGED
@@ -5,6 +5,7 @@ import json
5
  import tarfile
6
  from io import BytesIO
7
  from pathlib import Path
 
8
 
9
  import pytest
10
  import yaml # type: ignore[import-untyped]
@@ -48,8 +49,20 @@ def _write_archive(
48
  include_converted: bool = True,
49
  include_original: bool = False,
50
  include_lock: bool = False,
 
 
 
 
 
 
 
 
51
  ) -> None:
 
 
 
52
  graph = {
 
53
  "nodes": [
54
  {
55
  "id": "skill:skills-sh-example-skill",
@@ -69,7 +82,39 @@ def _write_archive(
69
  with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
70
  _add_text(tf, "./index.md", "# Wiki\n")
71
  _add_text(tf, "./graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
72
- _add_text(tf, "./graphify-out/communities.json", json.dumps({"total_communities": 1}))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  _add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
74
  _add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
75
  _add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
@@ -145,6 +190,79 @@ def test_validate_graph_artifacts_checks_catalog_paths_and_deep_graph_stats(
145
  )
146
 
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
149
  tmp_path: Path,
150
  ) -> None:
@@ -242,7 +360,46 @@ def test_scan_graph_json_handles_pretty_printed_graph() -> None:
242
  }
243
  payload = json.dumps(graph, indent=2).encode("utf-8")
244
 
245
- assert _scan_graph_json(BytesIO(payload)) == (2, 2, 1, 1, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
 
248
  def test_graph_only_workflow_uses_exact_release_counts() -> None:
 
5
  import tarfile
6
  from io import BytesIO
7
  from pathlib import Path
8
+ from typing import Any
9
 
10
  import pytest
11
  import yaml # type: ignore[import-untyped]
 
49
  include_converted: bool = True,
50
  include_original: bool = False,
51
  include_lock: bool = False,
52
+ include_delta: bool = True,
53
+ include_report: bool = True,
54
+ include_manifest: bool = True,
55
+ graph_export_id: str = "export-test",
56
+ delta_export_id: str = "export-test",
57
+ communities_export_id: str | None = None,
58
+ report_export_id: str | None = None,
59
+ manifest_export_id: str | None = None,
60
  ) -> None:
61
+ communities_export_id = communities_export_id or graph_export_id
62
+ report_export_id = report_export_id or graph_export_id
63
+ manifest_export_id = manifest_export_id or graph_export_id
64
  graph = {
65
+ "graph": {"export_id": graph_export_id},
66
  "nodes": [
67
  {
68
  "id": "skill:skills-sh-example-skill",
 
82
  with tarfile.open(graph_dir / "wiki-graph.tar.gz", "w:gz") as tf:
83
  _add_text(tf, "./index.md", "# Wiki\n")
84
  _add_text(tf, "./graphify-out/graph.json", json.dumps(graph, separators=(",", ":")))
85
+ if include_delta:
86
+ _add_text(
87
+ tf,
88
+ "./graphify-out/graph-delta.json",
89
+ json.dumps({"export_id": delta_export_id, "nodes": [], "edges": []}),
90
+ )
91
+ _add_text(
92
+ tf,
93
+ "./graphify-out/communities.json",
94
+ json.dumps({"export_id": communities_export_id, "total_communities": 1}),
95
+ )
96
+ if include_report:
97
+ _add_text(
98
+ tf,
99
+ "./graphify-out/graph-report.md",
100
+ f"# Graph Report\n\n> Export ID: {report_export_id}\n",
101
+ )
102
+ if include_manifest:
103
+ _add_text(
104
+ tf,
105
+ "./graphify-out/graph-export-manifest.json",
106
+ json.dumps({
107
+ "version": 1,
108
+ "export_id": manifest_export_id,
109
+ "artifacts": {
110
+ "graph": "graph.json",
111
+ "delta": "graph-delta.json",
112
+ "communities": "communities.json",
113
+ "report": "graph-report.md",
114
+ },
115
+ "counts": {"nodes": 2, "edges": 1, "communities": 1},
116
+ }),
117
+ )
118
  _add_text(tf, "./external-catalogs/skills-sh/catalog.json", "{}")
119
  _add_text(tf, "./entities/skills/skills-sh-example-skill.md", "# Example\n")
120
  _add_text(tf, "./entities/harnesses/langgraph.md", "# LangGraph\n")
 
190
  )
191
 
192
 
193
+ def test_validate_graph_artifacts_rejects_mixed_export_generation(
194
+ tmp_path: Path,
195
+ ) -> None:
196
+ _write_catalog(
197
+ tmp_path,
198
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
199
+ )
200
+ (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
201
+ _write_archive(tmp_path, graph_export_id="new-export", delta_export_id="old-export")
202
+
203
+ with pytest.raises(GraphArtifactError, match="export_id mismatch"):
204
+ validate_graph_artifacts(
205
+ tmp_path,
206
+ deep=True,
207
+ min_nodes=2,
208
+ min_edges=1,
209
+ min_skills_sh_nodes=1,
210
+ min_semantic_edges=1,
211
+ expected_harnesses={"langgraph"},
212
+ )
213
+
214
+
215
+ @pytest.mark.parametrize(
216
+ ("archive_kwargs", "missing_name"),
217
+ [
218
+ ({"include_delta": False}, "graph-delta.json"),
219
+ ({"include_report": False}, "graph-report.md"),
220
+ ({"include_manifest": False}, "graph-export-manifest.json"),
221
+ ],
222
+ )
223
+ def test_validate_graph_artifacts_rejects_missing_graph_export_files(
224
+ tmp_path: Path,
225
+ archive_kwargs: dict[str, Any],
226
+ missing_name: str,
227
+ ) -> None:
228
+ _write_catalog(
229
+ tmp_path,
230
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
231
+ )
232
+ (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
233
+ _write_archive(tmp_path, **archive_kwargs)
234
+
235
+ with pytest.raises(GraphArtifactError, match=missing_name):
236
+ validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
237
+
238
+
239
+ @pytest.mark.parametrize(
240
+ "archive_kwargs",
241
+ [
242
+ {"graph_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
243
+ {"delta_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
244
+ {
245
+ "communities_export_id": "artifact-export",
246
+ "manifest_export_id": "manifest-export",
247
+ },
248
+ {"report_export_id": "artifact-export", "manifest_export_id": "manifest-export"},
249
+ ],
250
+ )
251
+ def test_validate_graph_artifacts_rejects_artifact_export_id_mismatch(
252
+ tmp_path: Path,
253
+ archive_kwargs: dict[str, Any],
254
+ ) -> None:
255
+ _write_catalog(
256
+ tmp_path,
257
+ converted_path="converted/skills-sh-example-skill/SKILL.md",
258
+ )
259
+ (tmp_path / "communities.json").write_text("{}", encoding="utf-8")
260
+ _write_archive(tmp_path, **archive_kwargs)
261
+
262
+ with pytest.raises(GraphArtifactError, match="export_id mismatch"):
263
+ validate_graph_artifacts(tmp_path, expected_harnesses={"langgraph"})
264
+
265
+
266
  def test_validate_graph_artifacts_rejects_missing_converted_catalog_path(
267
  tmp_path: Path,
268
  ) -> None:
 
360
  }
361
  payload = json.dumps(graph, indent=2).encode("utf-8")
362
 
363
+ assert _scan_graph_json(BytesIO(payload)) == (2, 2, 1, 1, 1, None)
364
+
365
+
366
+ def test_scan_graph_json_extracts_top_level_graph_export_id() -> None:
367
+ graph = {
368
+ "directed": False,
369
+ "graph": {
370
+ "source_catalog_nodes": {"skills.sh": 1},
371
+ "source_catalog_edges": {"skills.sh": 0},
372
+ "export_id": "graph-export",
373
+ },
374
+ "nodes": [
375
+ {
376
+ "id": "skill:skills-sh-example-skill",
377
+ "type": "skill",
378
+ "source_catalog": "skills.sh",
379
+ },
380
+ ],
381
+ "edges": [],
382
+ }
383
+ payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
384
+
385
+ assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, "graph-export")
386
+
387
+
388
+ def test_scan_graph_json_ignores_node_level_export_id() -> None:
389
+ graph = {
390
+ "nodes": [
391
+ {
392
+ "id": "skill:skills-sh-example-skill",
393
+ "type": "skill",
394
+ "source_catalog": "skills.sh",
395
+ "export_id": "node-export",
396
+ },
397
+ ],
398
+ "edges": [],
399
+ }
400
+ payload = json.dumps(graph, separators=(",", ":")).encode("utf-8")
401
+
402
+ assert _scan_graph_json(BytesIO(payload)) == (1, 0, 0, 1, 0, None)
403
 
404
 
405
  def test_graph_only_workflow_uses_exact_release_counts() -> None:
src/tests/test_wiki_graphify_density.py CHANGED
@@ -363,6 +363,8 @@ def test_source_overlap_creates_explainable_edge_without_tags(
363
  tmp_path,
364
  monkeypatch,
365
  ) -> None:
 
 
366
  wiki, _ = _isolate_graphify(tmp_path, monkeypatch)
367
  shared_source = "https://github.com/acme/toolkit"
368
  _write_entity(
@@ -387,6 +389,18 @@ def test_source_overlap_creates_explainable_edge_without_tags(
387
  assert "source-overlap" in edge["edge_reasons"]
388
  assert edge["score_components"]["source_overlap"] > 0
389
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
391
  def test_direct_links_quality_usage_type_and_adamic_are_explainable(
392
  tmp_path,
 
363
  tmp_path,
364
  monkeypatch,
365
  ) -> None:
366
+ import ctx_config
367
+
368
  wiki, _ = _isolate_graphify(tmp_path, monkeypatch)
369
  shared_source = "https://github.com/acme/toolkit"
370
  _write_entity(
 
389
  assert "source-overlap" in edge["edge_reasons"]
390
  assert edge["score_components"]["source_overlap"] > 0
391
 
392
+ custom_config = ctx_config.Config({"graph": {"min_edge_weight": 0.09}})
393
+ assert custom_config.graph_edge_min_weight == 0.09
394
+ try:
395
+ ctx_config.Config({"graph": {"min_edge_weight": 1.01}})
396
+ except ValueError as exc:
397
+ assert "min_edge_weight" in str(exc)
398
+ else: # pragma: no cover - the assertion above is the behavior under test
399
+ raise AssertionError("graph.min_edge_weight above 1.0 must be rejected")
400
+ monkeypatch.setattr(ctx_config.cfg, "graph_edge_min_weight", 0.09)
401
+ filtered, _ = wg.build_graph(incremental=False)
402
+ assert not filtered.has_edge("skill:alpha-source", "agent:beta-target")
403
+
404
 
405
  def test_direct_links_quality_usage_type_and_adamic_are_explainable(
406
  tmp_path,
src/tests/test_wiki_graphify_security.py CHANGED
@@ -273,7 +273,7 @@ def test_export_graph_uses_atomic_writer_for_artifacts(
273
  graphify_out: Path,
274
  monkeypatch: pytest.MonkeyPatch,
275
  ) -> None:
276
- """Graphify artifacts are large enough that direct writes can truncate state."""
277
  from ctx.core.wiki import wiki_graphify
278
 
279
  calls: list[str] = []
@@ -291,14 +291,27 @@ def test_export_graph_uses_atomic_writer_for_artifacts(
291
 
292
  wiki_graphify.export_graph(_make_sample_graph(), communities={})
293
 
294
- assert set(calls) == {
 
 
 
 
 
 
 
 
295
  "graph.json",
296
  "graph-delta.json",
297
  "communities.json",
298
  "graph-report.md",
299
  "graph-export-manifest.json",
300
- }
301
- assert calls[-1] == "graph-export-manifest.json"
 
 
 
 
 
302
 
303
 
304
  def test_load_prior_graph_rejects_post_graph_replace_crash(
@@ -317,17 +330,18 @@ def test_load_prior_graph_rejects_post_graph_replace_crash(
317
  new_graph = _make_sample_graph()
318
  new_graph.add_node("skill:new", label="new", type="skill", tags=["python"])
319
 
320
- real_atomic = wiki_graphify.safe_atomic_write_text
321
 
322
- def crash_after_graph(path: Path, text: str, encoding: str = "utf-8") -> None:
323
- real_atomic(path, text, encoding=encoding)
324
- if path.name == "graph.json":
325
  raise RuntimeError("simulated crash after graph replacement")
 
326
 
327
  monkeypatch.setattr(
328
  wiki_graphify,
329
- "safe_atomic_write_text",
330
- crash_after_graph,
331
  raising=False,
332
  )
333
 
 
273
  graphify_out: Path,
274
  monkeypatch: pytest.MonkeyPatch,
275
  ) -> None:
276
+ """Graphify artifacts are staged, validated, promoted, and metadata-backed."""
277
  from ctx.core.wiki import wiki_graphify
278
 
279
  calls: list[str] = []
 
291
 
292
  wiki_graphify.export_graph(_make_sample_graph(), communities={})
293
 
294
+ assert {name for name in calls if name.endswith(".staged")} == {
295
+ "graph.json.staged",
296
+ "graph-delta.json.staged",
297
+ "communities.json.staged",
298
+ "graph-report.md.staged",
299
+ "graph-export-manifest.json.staged",
300
+ }
301
+ assert calls[-1] == "graph-export-manifest.json.staged"
302
+ for name in (
303
  "graph.json",
304
  "graph-delta.json",
305
  "communities.json",
306
  "graph-report.md",
307
  "graph-export-manifest.json",
308
+ ):
309
+ metadata = json.loads(
310
+ (graphify_out / f"{name}.promotion.json").read_text(encoding="utf-8")
311
+ )
312
+ assert metadata["status"] == "promoted"
313
+ assert metadata["target"].endswith(name)
314
+ assert "last_good" in metadata
315
 
316
 
317
  def test_load_prior_graph_rejects_post_graph_replace_crash(
 
330
  new_graph = _make_sample_graph()
331
  new_graph.add_node("skill:new", label="new", type="skill", tags=["python"])
332
 
333
+ real_promote = wiki_graphify.promote_staged_artifact
334
 
335
+ def crash_after_graph_promotion(*args, **kwargs):
336
+ result = real_promote(*args, **kwargs)
337
+ if Path(args[1]).name == "graph.json":
338
  raise RuntimeError("simulated crash after graph replacement")
339
+ return result
340
 
341
  monkeypatch.setattr(
342
  wiki_graphify,
343
+ "promote_staged_artifact",
344
+ crash_after_graph_promotion,
345
  raising=False,
346
  )
347
 
src/tests/test_wiki_queue.py CHANGED
@@ -4,18 +4,50 @@ from __future__ import annotations
4
 
5
  import sqlite3
6
  from pathlib import Path
 
7
 
8
  import pytest
9
 
10
  from ctx.core.wiki import wiki_queue
11
 
12
 
13
- def test_init_queue_enables_wal_and_creates_schema(tmp_path: Path) -> None:
 
 
 
14
  db_path = tmp_path / "wiki-queue.sqlite3"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  wiki_queue.init_queue(db_path)
17
 
18
- with sqlite3.connect(db_path) as conn:
 
19
  assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
20
  table_count = conn.execute(
21
  "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='wiki_queue_jobs'",
@@ -48,6 +80,7 @@ def test_enqueue_is_idempotent_by_key(tmp_path: Path) -> None:
48
 
49
  def test_enqueue_maintenance_job_is_idempotent_by_payload(tmp_path: Path) -> None:
50
  wiki = tmp_path / "wiki"
 
51
 
52
  first = wiki_queue.enqueue_maintenance_job(
53
  wiki,
@@ -68,7 +101,31 @@ def test_enqueue_maintenance_job_is_idempotent_by_payload(tmp_path: Path) -> Non
68
  assert second.kind == wiki_queue.GRAPH_EXPORT_JOB
69
  assert second.payload["source"] == "test"
70
  assert second.payload["graph_only"] is True
71
- assert wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki)) == [first]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
 
74
  def test_enqueue_maintenance_job_rejects_unknown_kind(tmp_path: Path) -> None:
@@ -81,6 +138,25 @@ def test_enqueue_maintenance_job_rejects_unknown_kind(tmp_path: Path) -> None:
81
  )
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def test_lease_next_claims_oldest_available_job(tmp_path: Path) -> None:
85
  db_path = tmp_path / "wiki-queue.sqlite3"
86
  first = wiki_queue.enqueue(db_path, kind="graph-export", payload={"n": 1}, now=10.0)
@@ -180,6 +256,68 @@ def test_expired_running_job_is_recovered_for_retry(tmp_path: Path) -> None:
180
  assert recovered.worker_id == "worker-b"
181
  assert recovered.attempts == 2
182
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
  def test_mark_succeeded_makes_job_unavailable(tmp_path: Path) -> None:
185
  db_path = tmp_path / "wiki-queue.sqlite3"
@@ -194,8 +332,54 @@ def test_mark_succeeded_makes_job_unavailable(tmp_path: Path) -> None:
194
  assert done.worker_id is None
195
  assert wiki_queue.lease_next(db_path, worker_id="worker-a", now=22.0) is None
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  def test_queue_rejects_symlinked_database_path(tmp_path: Path) -> None:
 
 
 
 
 
199
  real = tmp_path / "real.sqlite3"
200
  link = tmp_path / "queue.sqlite3"
201
  real.write_text("", encoding="utf-8")
 
4
 
5
  import sqlite3
6
  from pathlib import Path
7
+ from typing import Any
8
 
9
  import pytest
10
 
11
  from ctx.core.wiki import wiki_queue
12
 
13
 
14
+ def test_init_queue_enables_wal_and_creates_schema(
15
+ tmp_path: Path,
16
+ monkeypatch: pytest.MonkeyPatch,
17
+ ) -> None:
18
  db_path = tmp_path / "wiki-queue.sqlite3"
19
+ raw_connect = sqlite3.connect
20
+ closed = 0
21
+
22
+ class TrackingConnection:
23
+ def __init__(self, conn: sqlite3.Connection) -> None:
24
+ self._conn = conn
25
+
26
+ def __getattr__(self, name: str) -> object:
27
+ return getattr(self._conn, name)
28
+
29
+ @property
30
+ def row_factory(self) -> Any:
31
+ return self._conn.row_factory
32
+
33
+ @row_factory.setter
34
+ def row_factory(self, value: Any) -> None:
35
+ self._conn.row_factory = value
36
+
37
+ def close(self) -> None:
38
+ nonlocal closed
39
+ closed += 1
40
+ self._conn.close()
41
+
42
+ def tracking_connect(*args: Any, **kwargs: Any) -> TrackingConnection:
43
+ return TrackingConnection(raw_connect(*args, **kwargs))
44
+
45
+ monkeypatch.setattr(wiki_queue.sqlite3, "connect", tracking_connect)
46
 
47
  wiki_queue.init_queue(db_path)
48
 
49
+ assert closed == 1
50
+ with raw_connect(db_path) as conn:
51
  assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
52
  table_count = conn.execute(
53
  "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='wiki_queue_jobs'",
 
80
 
81
  def test_enqueue_maintenance_job_is_idempotent_by_payload(tmp_path: Path) -> None:
82
  wiki = tmp_path / "wiki"
83
+ db_path = wiki_queue.queue_db_path(wiki)
84
 
85
  first = wiki_queue.enqueue_maintenance_job(
86
  wiki,
 
101
  assert second.kind == wiki_queue.GRAPH_EXPORT_JOB
102
  assert second.payload["source"] == "test"
103
  assert second.payload["graph_only"] is True
104
+ assert wiki_queue.list_jobs(db_path) == [first]
105
+
106
+ leased = wiki_queue.lease_next(db_path, worker_id="worker-a", now=20.0)
107
+ assert leased is not None
108
+ wiki_queue.mark_succeeded(db_path, leased.id, worker_id="worker-a", now=21.0)
109
+
110
+ third = wiki_queue.enqueue_maintenance_job(
111
+ wiki,
112
+ kind=wiki_queue.GRAPH_EXPORT_JOB,
113
+ payload={"incremental": True, "graph_only": True},
114
+ source="test",
115
+ now=30.0,
116
+ )
117
+ fourth = wiki_queue.enqueue_maintenance_job(
118
+ wiki,
119
+ kind=wiki_queue.GRAPH_EXPORT_JOB,
120
+ payload={"graph_only": True, "incremental": True},
121
+ source="test",
122
+ now=31.0,
123
+ )
124
+
125
+ assert third.id != first.id
126
+ assert third.status == wiki_queue.STATUS_PENDING
127
+ assert fourth.id == third.id
128
+ assert [job.id for job in wiki_queue.list_jobs(db_path)] == [first.id, third.id]
129
 
130
 
131
  def test_enqueue_maintenance_job_rejects_unknown_kind(tmp_path: Path) -> None:
 
138
  )
139
 
140
 
141
+ def test_count_jobs_by_status_and_list_recent_jobs_are_bounded(tmp_path: Path) -> None:
142
+ db_path = tmp_path / "wiki-queue.sqlite3"
143
+ jobs = [
144
+ wiki_queue.enqueue(
145
+ db_path,
146
+ kind="graph-export",
147
+ payload={"n": index},
148
+ now=float(index),
149
+ )
150
+ for index in range(25)
151
+ ]
152
+
153
+ assert wiki_queue.count_jobs_by_status(db_path) == {wiki_queue.STATUS_PENDING: 25}
154
+ assert [job.id for job in wiki_queue.list_recent_jobs(db_path, limit=5)] == [
155
+ job.id for job in reversed(jobs[-5:])
156
+ ]
157
+ assert wiki_queue.list_recent_jobs(db_path, limit=0) == []
158
+
159
+
160
  def test_lease_next_claims_oldest_available_job(tmp_path: Path) -> None:
161
  db_path = tmp_path / "wiki-queue.sqlite3"
162
  first = wiki_queue.enqueue(db_path, kind="graph-export", payload={"n": 1}, now=10.0)
 
256
  assert recovered.worker_id == "worker-b"
257
  assert recovered.attempts == 2
258
 
259
+ with pytest.raises(RuntimeError, match="not leased by worker worker-a"):
260
+ wiki_queue.mark_succeeded(db_path, job.id, worker_id="worker-a", now=27.0)
261
+
262
+ current = wiki_queue.get_job(db_path, job.id)
263
+ assert current.status == wiki_queue.STATUS_RUNNING
264
+ assert current.worker_id == "worker-b"
265
+
266
+ with pytest.raises(RuntimeError, match="not leased by worker worker-a"):
267
+ wiki_queue.mark_failed(
268
+ db_path,
269
+ job.id,
270
+ worker_id="worker-a",
271
+ error="late failure",
272
+ retry=True,
273
+ now=27.0,
274
+ )
275
+
276
+ current = wiki_queue.get_job(db_path, job.id)
277
+ assert current.status == wiki_queue.STATUS_RUNNING
278
+ assert current.worker_id == "worker-b"
279
+ assert current.last_error is None
280
+
281
+ recovery_db = tmp_path / "wiki-queue-recovery.sqlite3"
282
+ retryable = wiki_queue.enqueue(
283
+ recovery_db,
284
+ kind="graph-export",
285
+ payload={"n": 1},
286
+ max_attempts=2,
287
+ now=30.0,
288
+ )
289
+ exhausted = wiki_queue.enqueue(
290
+ recovery_db,
291
+ kind="tar-refresh",
292
+ payload={"n": 2},
293
+ max_attempts=1,
294
+ now=31.0,
295
+ )
296
+ first_lease = wiki_queue.lease_next(
297
+ recovery_db,
298
+ worker_id="worker-a",
299
+ lease_seconds=5.0,
300
+ now=40.0,
301
+ )
302
+ assert first_lease is not None
303
+ assert first_lease.id == retryable.id
304
+ second_lease = wiki_queue.lease_next(
305
+ recovery_db,
306
+ worker_id="worker-b",
307
+ lease_seconds=5.0,
308
+ now=41.0,
309
+ )
310
+ assert second_lease is not None
311
+ assert second_lease.id == exhausted.id
312
+
313
+ recovered_counts = wiki_queue.recover_expired_leases(recovery_db, now=47.0)
314
+
315
+ assert recovered_counts == {"requeued": 1, "failed": 1}
316
+ assert wiki_queue.get_job(recovery_db, retryable.id).status == wiki_queue.STATUS_PENDING
317
+ terminal = wiki_queue.get_job(recovery_db, exhausted.id)
318
+ assert terminal.status == wiki_queue.STATUS_FAILED
319
+ assert terminal.last_error == "lease expired; max attempts exhausted"
320
+
321
 
322
  def test_mark_succeeded_makes_job_unavailable(tmp_path: Path) -> None:
323
  db_path = tmp_path / "wiki-queue.sqlite3"
 
332
  assert done.worker_id is None
333
  assert wiki_queue.lease_next(db_path, worker_id="worker-a", now=22.0) is None
334
 
335
+ first = wiki_queue.enqueue(db_path, kind="graph-export", payload={"n": 1}, now=30.0)
336
+ second = wiki_queue.enqueue(db_path, kind="tar-refresh", payload={"n": 2}, now=31.0)
337
+
338
+ cancelled = wiki_queue.cancel_job(
339
+ db_path,
340
+ first.id,
341
+ reason="superseded by newer artifact refresh",
342
+ now=32.0,
343
+ )
344
+
345
+ assert cancelled.status == wiki_queue.STATUS_CANCELLED
346
+ assert cancelled.last_error == "superseded by newer artifact refresh"
347
+ assert cancelled.worker_id is None
348
+ assert cancelled.leased_until is None
349
+ assert wiki_queue.cancel_job(db_path, first.id, now=33.0).id == first.id
350
+ leased_second = wiki_queue.lease_next(db_path, worker_id="worker-a", now=40.0)
351
+ assert leased_second is not None
352
+ assert leased_second.id == second.id
353
+ assert wiki_queue.count_jobs_by_status(db_path) == {
354
+ wiki_queue.STATUS_SUCCEEDED: 1,
355
+ wiki_queue.STATUS_CANCELLED: 1,
356
+ wiki_queue.STATUS_RUNNING: 1,
357
+ }
358
+
359
+ running_job = wiki_queue.enqueue(db_path, kind="graph-export", payload={}, now=50.0)
360
+ running_lease = wiki_queue.lease_next(db_path, worker_id="worker-b", now=60.0)
361
+ assert running_lease is not None
362
+ assert running_lease.id == running_job.id
363
+
364
+ cancelled_running = wiki_queue.cancel_job(
365
+ db_path,
366
+ running_job.id,
367
+ worker_id="worker-b",
368
+ reason="operator cancelled hung graph export",
369
+ now=61.0,
370
+ )
371
+
372
+ assert cancelled_running.status == wiki_queue.STATUS_CANCELLED
373
+ with pytest.raises(RuntimeError, match="not leased by worker worker-b"):
374
+ wiki_queue.mark_succeeded(db_path, running_job.id, worker_id="worker-b", now=62.0)
375
+
376
 
377
  def test_queue_rejects_symlinked_database_path(tmp_path: Path) -> None:
378
+ corrupt = tmp_path / "corrupt.sqlite3"
379
+ corrupt.write_bytes(b"not a sqlite database")
380
+ with pytest.raises(wiki_queue.QueueStorageError, match="queue database is not readable"):
381
+ wiki_queue.count_jobs_by_status(corrupt)
382
+
383
  real = tmp_path / "real.sqlite3"
384
  link = tmp_path / "queue.sqlite3"
385
  real.write_text("", encoding="utf-8")
src/tests/test_wiki_queue_worker.py CHANGED
@@ -55,6 +55,17 @@ def test_process_next_entity_upsert_succeeds_and_refreshes_index(
55
  wiki_queue.STATUS_SUCCEEDED
56
  )
57
  update_index.assert_called_once_with(str(wiki), ["alpha"], subject_type="skills")
 
 
 
 
 
 
 
 
 
 
 
58
 
59
 
60
  def test_process_next_retries_hash_mismatch(
@@ -145,6 +156,39 @@ def test_process_next_graph_export_job_uses_maintenance_handler(
145
  assert result.message == "graph exported"
146
  assert calls == [(wiki, {"graph_only": True, "source": "test"})]
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  def test_process_next_maintenance_job_retries_handler_failure(
150
  tmp_path: Path,
 
55
  wiki_queue.STATUS_SUCCEEDED
56
  )
57
  update_index.assert_called_once_with(str(wiki), ["alpha"], subject_type="skills")
58
+ jobs = wiki_queue.list_jobs(wiki_queue.queue_db_path(wiki))
59
+ assert [job.kind for job in jobs] == [
60
+ wiki_queue.ENTITY_UPSERT_JOB,
61
+ wiki_queue.GRAPH_EXPORT_JOB,
62
+ ]
63
+ assert jobs[1].status == wiki_queue.STATUS_PENDING
64
+ assert jobs[1].payload == {
65
+ "graph_only": True,
66
+ "incremental": True,
67
+ "source": "entity-upsert",
68
+ }
69
 
70
 
71
  def test_process_next_retries_hash_mismatch(
 
156
  assert result.message == "graph exported"
157
  assert calls == [(wiki, {"graph_only": True, "source": "test"})]
158
 
159
+ db_path = wiki_queue.queue_db_path(wiki)
160
+ stolen_job = wiki_queue.enqueue_maintenance_job(
161
+ wiki,
162
+ kind=wiki_queue.GRAPH_EXPORT_JOB,
163
+ payload={"graph_only": True},
164
+ source="lease-stolen-test",
165
+ now=30.0,
166
+ )
167
+
168
+ def steal_lease(_path: Path, _payload: dict[str, Any]) -> str:
169
+ stolen = wiki_queue.lease_next(db_path, worker_id="worker-b", now=46.0)
170
+ assert stolen is not None
171
+ assert stolen.id == stolen_job.id
172
+ return "graph exported too late"
173
+
174
+ monkeypatch.setitem(
175
+ wiki_queue_worker.MAINTENANCE_HANDLERS,
176
+ wiki_queue.GRAPH_EXPORT_JOB,
177
+ steal_lease,
178
+ )
179
+
180
+ with pytest.raises(RuntimeError, match="not leased by worker worker-a"):
181
+ wiki_queue_worker.process_next(
182
+ wiki,
183
+ worker_id="worker-a",
184
+ lease_seconds=5.0,
185
+ now=40.0,
186
+ )
187
+
188
+ current = wiki_queue.get_job(db_path, stolen_job.id)
189
+ assert current.status == wiki_queue.STATUS_RUNNING
190
+ assert current.worker_id == "worker-b"
191
+
192
 
193
  def test_process_next_maintenance_job_retries_handler_failure(
194
  tmp_path: Path,
src/validate_graph_artifacts.py CHANGED
@@ -32,6 +32,8 @@ _NODE_ID_RE = re.compile(rb'"id"\s*:')
32
  _EDGE_TARGET_RE = re.compile(rb'"target"\s*:')
33
  _SOURCE_SKILLS_SH_RE = re.compile(rb'"source_catalog"\s*:\s*"skills\.sh"')
34
  _HARNESS_TYPE_RE = re.compile(rb'"type"\s*:\s*"harness"')
 
 
35
  _SEMANTIC_SIM_RE = re.compile(
36
  rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
37
  )
@@ -101,12 +103,17 @@ def _count_lines(payload: bytes) -> int:
101
  return len(payload.decode("utf-8", errors="replace").splitlines())
102
 
103
 
104
- def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int]:
105
  nodes = edges = semantic_edges = skills_sh_nodes = harness_nodes = 0
 
106
  tail = b""
 
107
  while chunk := stream.read(1024 * 1024):
108
  old_tail = tail
109
  data = tail + chunk
 
 
 
110
  nodes += len(_NODE_ID_RE.findall(data)) - len(_NODE_ID_RE.findall(old_tail))
111
  edges += len(_EDGE_TARGET_RE.findall(data)) - len(_EDGE_TARGET_RE.findall(old_tail))
112
  semantic_edges += (
@@ -122,7 +129,59 @@ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int]:
122
  - len(_HARNESS_TYPE_RE.findall(old_tail))
123
  )
124
  tail = data[-512:]
125
- return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
 
127
 
128
  def _count_nonzero_semantic_matches(data: bytes) -> int:
@@ -200,6 +259,8 @@ def validate_graph_artifacts(
200
  harness_nodes = 0
201
  skill_pages = agent_pages = mcp_pages = harness_pages = skills_sh_converted = 0
202
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
 
 
203
 
204
  with tarfile.open(tarball, "r:gz") as tf:
205
  for member in tf:
@@ -221,17 +282,42 @@ def validate_graph_artifacts(
221
  harness_pages += 1
222
  if name.startswith("converted/skills-sh-") and name.endswith("/SKILL.md"):
223
  skills_sh_converted += 1
224
- if member.isfile() and deep and name == "graphify-out/graph.json":
225
  f = tf.extractfile(member)
226
  if f is None:
227
  raise GraphArtifactError("graphify-out/graph.json could not be read")
228
- (
229
- graph_nodes,
230
- graph_edges,
231
- graph_semantic_edges,
232
- skills_sh_nodes,
233
- harness_nodes,
234
- ) = _scan_graph_json(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
236
  if name.endswith("/SKILL.md") or "/references/" in name:
237
  f = tf.extractfile(member)
@@ -247,12 +333,24 @@ def validate_graph_artifacts(
247
  required_names = {
248
  "index.md",
249
  "graphify-out/graph.json",
 
250
  "graphify-out/communities.json",
 
 
251
  "external-catalogs/skills-sh/catalog.json",
252
  }
253
  missing_required = sorted(required_names - names)
254
  if missing_required:
255
  raise GraphArtifactError(f"wiki graph archive is missing: {missing_required}")
 
 
 
 
 
 
 
 
 
256
  missing_pages = sorted(required_skill_pages - names)
257
  if missing_pages:
258
  raise GraphArtifactError(f"missing Skills.sh entity pages: {missing_pages[:5]}")
@@ -330,6 +428,86 @@ def validate_graph_artifacts(
330
  return stats
331
 
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  def main() -> None:
334
  parser = argparse.ArgumentParser(description=__doc__)
335
  parser.add_argument("--graph-dir", type=Path, default=Path("graph"))
 
32
  _EDGE_TARGET_RE = re.compile(rb'"target"\s*:')
33
  _SOURCE_SKILLS_SH_RE = re.compile(rb'"source_catalog"\s*:\s*"skills\.sh"')
34
  _HARNESS_TYPE_RE = re.compile(rb'"type"\s*:\s*"harness"')
35
+ _GRAPH_KEY_RE = re.compile(rb'"graph"\s*:\s*\{')
36
+ _REPORT_EXPORT_ID_RE = re.compile(r"^>\s*Export ID:\s*(\S+)\s*$", re.MULTILINE)
37
  _SEMANTIC_SIM_RE = re.compile(
38
  rb'"semantic_sim"\s*:\s*(-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)',
39
  )
 
103
  return len(payload.decode("utf-8", errors="replace").splitlines())
104
 
105
 
106
+ def _scan_graph_json(stream: IO[bytes]) -> tuple[int, int, int, int, int, str | None]:
107
  nodes = edges = semantic_edges = skills_sh_nodes = harness_nodes = 0
108
+ export_id: str | None = None
109
  tail = b""
110
+ graph_probe = b""
111
  while chunk := stream.read(1024 * 1024):
112
  old_tail = tail
113
  data = tail + chunk
114
+ if export_id is None:
115
+ graph_probe = (graph_probe + chunk)[-1024 * 1024:]
116
+ export_id = _extract_graph_export_id(graph_probe)
117
  nodes += len(_NODE_ID_RE.findall(data)) - len(_NODE_ID_RE.findall(old_tail))
118
  edges += len(_EDGE_TARGET_RE.findall(data)) - len(_EDGE_TARGET_RE.findall(old_tail))
119
  semantic_edges += (
 
129
  - len(_HARNESS_TYPE_RE.findall(old_tail))
130
  )
131
  tail = data[-512:]
132
+ return nodes, edges, semantic_edges, skills_sh_nodes, harness_nodes, export_id
133
+
134
+
135
+ def _scan_graph_export_id(stream: IO[bytes], *, max_bytes: int = 1024 * 1024) -> str | None:
136
+ payload = stream.read(max_bytes)
137
+ return _extract_graph_export_id(payload)
138
+
139
+
140
+ def _extract_graph_export_id(payload: bytes) -> str | None:
141
+ match = _GRAPH_KEY_RE.search(payload)
142
+ if match is None:
143
+ return None
144
+ start = match.end() - 1
145
+ end = _json_object_end(payload, start)
146
+ if end is None:
147
+ return None
148
+ try:
149
+ graph_meta = json.loads(payload[start : end + 1].decode("utf-8"))
150
+ except json.JSONDecodeError:
151
+ return None
152
+ if not isinstance(graph_meta, dict):
153
+ return None
154
+ raw = graph_meta.get("export_id")
155
+ if not isinstance(raw, str) or not raw.strip():
156
+ return None
157
+ return raw.strip()
158
+
159
+
160
+ def _json_object_end(payload: bytes, start: int) -> int | None:
161
+ if start >= len(payload) or payload[start:start + 1] != b"{":
162
+ return None
163
+ depth = 0
164
+ in_string = False
165
+ escaped = False
166
+ for idx in range(start, len(payload)):
167
+ char = payload[idx]
168
+ if in_string:
169
+ if escaped:
170
+ escaped = False
171
+ elif char == 0x5C: # backslash
172
+ escaped = True
173
+ elif char == 0x22: # double quote
174
+ in_string = False
175
+ continue
176
+ if char == 0x22:
177
+ in_string = True
178
+ elif char == 0x7B: # {
179
+ depth += 1
180
+ elif char == 0x7D: # }
181
+ depth -= 1
182
+ if depth == 0:
183
+ return idx
184
+ return None
185
 
186
 
187
  def _count_nonzero_semantic_matches(data: bytes) -> int:
 
259
  harness_nodes = 0
260
  skill_pages = agent_pages = mcp_pages = harness_pages = skills_sh_converted = 0
261
  expected_harnesses = DEFAULT_HARNESSES if expected_harnesses is None else expected_harnesses
262
+ export_ids: dict[str, str] = {}
263
+ manifest: dict[str, Any] | None = None
264
 
265
  with tarfile.open(tarball, "r:gz") as tf:
266
  for member in tf:
 
282
  harness_pages += 1
283
  if name.startswith("converted/skills-sh-") and name.endswith("/SKILL.md"):
284
  skills_sh_converted += 1
285
+ if member.isfile() and name == "graphify-out/graph.json":
286
  f = tf.extractfile(member)
287
  if f is None:
288
  raise GraphArtifactError("graphify-out/graph.json could not be read")
289
+ if deep:
290
+ (
291
+ graph_nodes,
292
+ graph_edges,
293
+ graph_semantic_edges,
294
+ skills_sh_nodes,
295
+ harness_nodes,
296
+ graph_export_id,
297
+ ) = _scan_graph_json(f)
298
+ else:
299
+ graph_export_id = _scan_graph_export_id(f)
300
+ _record_export_id(export_ids, name, graph_export_id)
301
+ elif member.isfile() and name == "graphify-out/graph-delta.json":
302
+ data = _read_tar_json(tf, member, name)
303
+ _record_export_id(export_ids, name, _export_id_from_json(data, name))
304
+ elif member.isfile() and name == "graphify-out/communities.json":
305
+ data = _read_tar_json(tf, member, name)
306
+ _record_export_id(
307
+ export_ids,
308
+ name,
309
+ _export_id_from_json(data, name),
310
+ )
311
+ elif member.isfile() and name == "graphify-out/graph-export-manifest.json":
312
+ data = _read_tar_json(tf, member, name)
313
+ if not isinstance(data, dict):
314
+ raise GraphArtifactError(f"{name} did not contain a JSON object")
315
+ manifest = data
316
+ elif member.isfile() and name == "graphify-out/graph-report.md":
317
+ f = tf.extractfile(member)
318
+ if f is None:
319
+ raise GraphArtifactError(f"{member.name} could not be read")
320
+ _record_export_id(export_ids, name, _export_id_from_report(f.read()))
321
  elif member.isfile() and deep and name.startswith("converted/skills-sh-"):
322
  if name.endswith("/SKILL.md") or "/references/" in name:
323
  f = tf.extractfile(member)
 
333
  required_names = {
334
  "index.md",
335
  "graphify-out/graph.json",
336
+ "graphify-out/graph-delta.json",
337
  "graphify-out/communities.json",
338
+ "graphify-out/graph-report.md",
339
+ "graphify-out/graph-export-manifest.json",
340
  "external-catalogs/skills-sh/catalog.json",
341
  }
342
  missing_required = sorted(required_names - names)
343
  if missing_required:
344
  raise GraphArtifactError(f"wiki graph archive is missing: {missing_required}")
345
+ manifest_export_id = _validate_graph_export_manifest(manifest, names)
346
+ _record_export_id(
347
+ export_ids,
348
+ "graphify-out/graph-export-manifest.json",
349
+ manifest_export_id,
350
+ )
351
+ if "graphify-out/graph.json" not in export_ids:
352
+ raise GraphArtifactError("graphify-out/graph.json is missing export_id")
353
+ _validate_export_ids(export_ids, expected=manifest_export_id)
354
  missing_pages = sorted(required_skill_pages - names)
355
  if missing_pages:
356
  raise GraphArtifactError(f"missing Skills.sh entity pages: {missing_pages[:5]}")
 
428
  return stats
429
 
430
 
431
+ def _read_tar_json(tf: tarfile.TarFile, member: tarfile.TarInfo, name: str) -> Any:
432
+ f = tf.extractfile(member)
433
+ if f is None:
434
+ raise GraphArtifactError(f"{member.name} could not be read")
435
+ try:
436
+ return json.loads(f.read().decode("utf-8"))
437
+ except json.JSONDecodeError as exc:
438
+ raise GraphArtifactError(f"{name} is not valid JSON: {exc}") from exc
439
+
440
+
441
+ def _export_id_from_json(data: Any, name: str) -> str:
442
+ if not isinstance(data, dict):
443
+ raise GraphArtifactError(f"{name} did not contain a JSON object")
444
+ raw = data.get("export_id")
445
+ if not isinstance(raw, str) or not raw.strip():
446
+ raise GraphArtifactError(f"{name} is missing export_id")
447
+ return raw.strip()
448
+
449
+
450
+ def _export_id_from_report(payload: bytes) -> str:
451
+ text = payload.decode("utf-8", errors="replace")
452
+ match = _REPORT_EXPORT_ID_RE.search(text)
453
+ if match is None:
454
+ raise GraphArtifactError("graphify-out/graph-report.md is missing Export ID")
455
+ return match.group(1).strip()
456
+
457
+
458
+ def _record_export_id(export_ids: dict[str, str], key: str, export_id: str | None) -> None:
459
+ if not export_id:
460
+ raise GraphArtifactError(f"{key} is missing export_id")
461
+ export_ids[key] = export_id
462
+
463
+
464
+ def _validate_graph_export_manifest(
465
+ manifest: dict[str, Any] | None,
466
+ names: set[str],
467
+ ) -> str:
468
+ if manifest is None:
469
+ raise GraphArtifactError("graphify-out/graph-export-manifest.json is missing")
470
+ if manifest.get("version") != 1:
471
+ raise GraphArtifactError("graph export manifest version must be 1")
472
+ export_id = _export_id_from_json(manifest, "graphify-out/graph-export-manifest.json")
473
+ artifacts = manifest.get("artifacts")
474
+ if not isinstance(artifacts, dict):
475
+ raise GraphArtifactError("graph export manifest missing artifacts map")
476
+ expected = {
477
+ "graph": "graph.json",
478
+ "delta": "graph-delta.json",
479
+ "communities": "communities.json",
480
+ "report": "graph-report.md",
481
+ }
482
+ if set(artifacts) != set(expected):
483
+ raise GraphArtifactError(
484
+ "graph export manifest artifacts map must contain exactly "
485
+ f"{sorted(expected)}",
486
+ )
487
+ for key, filename in expected.items():
488
+ actual = artifacts.get(key)
489
+ if actual != filename:
490
+ raise GraphArtifactError(
491
+ f"graph export manifest artifact {key!r} expected {filename!r}, got {actual!r}",
492
+ )
493
+ archive_name = f"graphify-out/{filename}"
494
+ if archive_name not in names:
495
+ raise GraphArtifactError(f"graph export manifest references missing {archive_name}")
496
+ return export_id
497
+
498
+
499
+ def _validate_export_ids(export_ids: dict[str, str], *, expected: str) -> None:
500
+ mismatches = {
501
+ key: value
502
+ for key, value in sorted(export_ids.items())
503
+ if value != expected
504
+ }
505
+ if mismatches:
506
+ raise GraphArtifactError(
507
+ f"graph export_id mismatch: expected {expected}, mismatches={mismatches}",
508
+ )
509
+
510
+
511
  def main() -> None:
512
  parser = argparse.ArgumentParser(description=__doc__)
513
  parser.add_argument("--graph-dir", type=Path, default=Path("graph"))