返回 last30days-skill
test_doctor_cache.py
根目录 / tests / test_doctor_cache.py
1 """U5: doctor cache — results persist across invocations with a TTL.
2
3 Covers the plan's U5 scenarios (R5, R7, KTD 8):
4 1. Fresh cache within TTL -> `--cached` returns the stored result and
5 spawns zero probes (probe layer spied, never called).
6 2. Stale or missing cache -> live run executes and rewrites the cache.
7 3. Explicit `doctor` (no `--cached`) -> always live; cache refreshed
8 even when a fresh cache exists.
9 4. TTL env override (LAST30DAYS_DOCTOR_TTL, seconds) respected;
10 malformed/corrupt cache treated as absent — never a crash.
11 5. No secret values in the cache file under seeded fake credentials.
12 6. SKILL.md contract (test_onboarding_contract.py pattern): doctor
13 trigger phrases and the cached standing rule are present, so future
14 SKILL.md edits cannot silently erode the integration.
15 """
16
17 import datetime
18 import io
19 import json
20 import os
21 import re
22 import sys
23 import tempfile
24 import unittest
25 from contextlib import redirect_stderr, redirect_stdout
26 from pathlib import Path
27 from unittest import mock
28
29 import yaml
30
31 import last30days as cli
32 from lib import doctor, health
33
34 ROOT = Path(__file__).resolve().parents[1]
35 SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"
36
37 # Hermes clamps every skill description at SKILL_PROMPT_DESC_LIMIT = 60 when it
38 # builds the routing index, so anything past this budget never reaches the
39 # model choosing a skill. Other hosts apply their own caps; this is the floor.
40 DESCRIPTION_ROUTING_BUDGET = 60
41
42 # Line-anchored on purpose: splitting the text on the "---" substring cuts the
43 # frontmatter early when a comment, quoted value or indented block scalar holds
44 # a horizontal rule, and an unclosed fence would feed the body to the parser.
45 _FRONTMATTER_FENCE = re.compile(
46 r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL
47 )
48 _DESCRIPTION_LINE = re.compile(r"description\s*:")
49
50
51 def _frontmatter_block(text):
52 match = _FRONTMATTER_FENCE.match(text)
53 assert match, "SKILL.md must open with a line-anchored '---' frontmatter fence"
54 return match.group(1)
55
56
57 def _checked_description(block, needles=()):
58 """Validate the description a host indexes and return it.
59
60 YAML lets a scalar wrap onto continuation lines or use a block, but hosts
61 that read frontmatter line-wise would see only the first line, so the
62 value must sit entirely on one physical ``description:`` line. Measure the
63 parsed YAML value, not the source line: a wrapped scalar passes at its
64 prefix and fails at its real length.
65 """
66 sources = [line for line in block.splitlines() if _DESCRIPTION_LINE.match(line)]
67 assert len(sources) == 1, f"description must be one physical line, found {len(sources)}"
68 try:
69 source_value = yaml.safe_load(sources[0])
70 block_value = yaml.safe_load(block)
71 except yaml.YAMLError as exc:
72 raise AssertionError(f"frontmatter is not valid YAML: {exc}") from exc
73 assert isinstance(source_value, dict) and isinstance(source_value.get("description"), str), (
74 "the description source line must parse to a YAML string"
75 )
76 description = source_value["description"]
77 assert isinstance(block_value, dict) and block_value.get("description") == description, (
78 "description spills beyond its single source line"
79 )
80 assert description == description.strip(), "description has surrounding whitespace"
81 assert not re.search(r"[\r\n\t]", description), "description contains a line break or tab"
82 assert len(description) <= DESCRIPTION_ROUTING_BUDGET, (
83 "description must fit the "
84 f"{DESCRIPTION_ROUTING_BUDGET}-char routing budget, got {len(description)}"
85 )
86 for needle in needles:
87 assert needle in description.lower(), f"description missing keyword: {needle!r}"
88 return description
89
90
91 def _skill_description(skill_root, needles=()):
92 text = (skill_root / "SKILL.md").read_text(encoding="utf-8")
93 return _checked_description(_frontmatter_block(text), needles=needles)
94
95 BIRD_STATUS_OFF = {
96 "installed": False,
97 "authenticated": False,
98 "username": None,
99 "can_install": True,
100 }
101
102 # Obvious dummies only (repo security hygiene).
103 FAKE_SECRETS = {
104 "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",
105 "XAI_API_KEY": "dummy-xai-secret-000",
106 "BRAVE_API_KEY": "dummy-brave-secret-000",
107 "AUTH_TOKEN": "dummy-auth-token-secret-000",
108 "CT0": "dummy-ct0-secret-000",
109 "BSKY_HANDLE": "dummy.example.social",
110 "BSKY_APP_PASSWORD": "dummy-bsky-secret-000",
111 "TRUTHSOCIAL_TOKEN": "dummy-truth-secret-000",
112 "GITHUB_TOKEN": "dummy-github-secret-000",
113 }
114
115
116 def _iso_utc(seconds_ago: float = 0.0) -> str:
117 return (
118 datetime.datetime.now(datetime.timezone.utc)
119 - datetime.timedelta(seconds=seconds_ago)
120 ).isoformat()
121
122
123 def _fake_probe(name, timeout=health.PROBE_TIMEOUT):
124 return health.DependencyProbe(
125 name=name,
126 status=health.MISSING,
127 detail=f"{name} probe simulated missing",
128 prescription=f"install {name}",
129 owner_pkg_manager="brew",
130 )
131
132
133 class _Hermetic:
134 """Machine-independent doctor runs (mirrors tests/test_doctor.py)."""
135
136 def __init__(self, probe=None):
137 self.probe_spy = mock.Mock(side_effect=probe or _fake_probe)
138 self._patches = [
139 mock.patch("lib.health.probe_dependency", self.probe_spy),
140 mock.patch("lib.doctor._probe_sources", return_value={}),
141 mock.patch("lib.bird_x.is_bird_installed", return_value=False),
142 mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),
143 mock.patch("lib.bird_x.get_bird_status", return_value=dict(BIRD_STATUS_OFF)),
144 # Doctor path is local-only for xurl: the live `xurl whoami`
145 # network check must never run (no-network guarantee).
146 mock.patch(
147 "lib.xurl_x.is_available",
148 side_effect=AssertionError(
149 "doctor path ran the live `xurl whoami` network check"
150 ),
151 ),
152 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
153 mock.patch(
154 "lib.xurl_x.stored_auth_status",
155 return_value=("missing", "no token store at ~/.xurl"),
156 ),
157 mock.patch("lib.backends.which", lambda name: None),
158 ]
159
160 def __enter__(self):
161 for p in self._patches:
162 p.start()
163 return self
164
165 def __exit__(self, *exc):
166 for p in reversed(self._patches):
167 p.stop()
168 return False
169
170
171 class _CacheDirCase(unittest.TestCase):
172 """Base: isolated CONFIG_DIR + clean TTL env for every test."""
173
174 def setUp(self):
175 self._tmp = tempfile.TemporaryDirectory()
176 self.addCleanup(self._tmp.cleanup)
177 self.config_dir = Path(self._tmp.name)
178 patcher = mock.patch.object(cli.env, "CONFIG_DIR", self.config_dir)
179 patcher.start()
180 self.addCleanup(patcher.stop)
181 env_patcher = mock.patch.dict(os.environ, {}, clear=False)
182 env_patcher.start()
183 self.addCleanup(env_patcher.stop)
184 os.environ.pop("LAST30DAYS_DOCTOR_TTL", None)
185
186 @property
187 def cache_file(self) -> Path:
188 return self.config_dir / doctor.CACHE_FILENAME
189
190 @staticmethod
191 def valid_report(marker="cached-sentinel-report"):
192 """A report satisfying the render contract, carrying a marker."""
193 return {
194 "engine_version": marker,
195 "config": {"global_env": None, "config_source": None},
196 "setup": {"setup_complete": False, "keys_present": {}},
197 "permissions": {"status": "ok"},
198 "sources": {
199 "hackernews": {
200 "tier": "ok", "status": "ok", "mode": "single",
201 "backends": None, "active_backend": None, "fix": "",
202 "requires": "none", "note": marker, "detail": "",
203 "pin_var": None, "pin_flag": None, "pinned": False,
204 },
205 },
206 }
207
208 def write_cache(
209 self,
210 *,
211 seconds_ago=0.0,
212 marker="cached-sentinel-report",
213 config=None,
214 schema=None,
215 fingerprint=None,
216 report=None,
217 ):
218 """Seed a valid cached payload (schema + fingerprint stamped)."""
219 if report is None:
220 report = self.valid_report(marker)
221 payload = {
222 "schema": doctor.DOCTOR_CACHE_SCHEMA_VERSION if schema is None else schema,
223 "fingerprint": (
224 doctor._config_fingerprint(dict(config or {}))
225 if fingerprint is None
226 else fingerprint
227 ),
228 "timestamp": _iso_utc(seconds_ago),
229 "report": report,
230 }
231 self.cache_file.write_text(json.dumps(payload), encoding="utf-8")
232 return report
233
234 def run_doctor(self, config=None, *, cached, emit_json=True):
235 with _Hermetic() as h:
236 stdout = io.StringIO()
237 with redirect_stdout(stdout):
238 rc = doctor.run(dict(config or {}), emit_json=emit_json, cached=cached)
239 return rc, stdout.getvalue(), h.probe_spy
240
241
242 class FreshCacheServed(_CacheDirCase):
243 """Scenario 1: fresh cache within TTL -> stored result, zero probes."""
244
245 def test_cached_returns_stored_report(self):
246 self.write_cache(seconds_ago=1)
247 rc, out, _ = self.run_doctor(cached=True)
248 self.assertEqual(0, rc)
249 self.assertIn("cached-sentinel-report", out)
250 payload = json.loads(out)
251 self.assertIn("sources", payload)
252
253 def test_cached_spawns_zero_probes_and_no_live_aggregation(self):
254 self.write_cache(seconds_ago=1)
255 with mock.patch(
256 "lib.doctor.build_report",
257 side_effect=AssertionError("live aggregation must not run"),
258 ) as build:
259 rc, out, probe_spy = self.run_doctor(cached=True)
260 self.assertEqual(0, rc)
261 self.assertFalse(probe_spy.called, "probe layer must not be touched")
262 self.assertFalse(build.called)
263
264 def test_cached_hit_does_not_rewrite_cache(self):
265 self.write_cache(seconds_ago=1)
266 before = self.cache_file.read_text(encoding="utf-8")
267 self.run_doctor(cached=True)
268 self.assertEqual(before, self.cache_file.read_text(encoding="utf-8"))
269
270 def test_cached_text_render_from_cache(self):
271 self.write_cache(seconds_ago=1)
272 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
273 self.assertEqual(0, rc)
274 self.assertIn("last30days doctor", out)
275 self.assertFalse(probe_spy.called)
276
277
278 class StaleOrMissingCacheRunsLive(_CacheDirCase):
279 """Scenario 2: stale or missing cache -> live run rewrites the cache."""
280
281 def test_stale_cache_falls_through_to_live_run(self):
282 self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)
283 rc, out, probe_spy = self.run_doctor(cached=True)
284 self.assertEqual(0, rc)
285 self.assertNotIn("cached-sentinel-report", out)
286 self.assertTrue(probe_spy.called, "stale cache must trigger live probes")
287
288 def test_stale_cache_is_rewritten(self):
289 self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)
290 self.run_doctor(cached=True)
291 payload = json.loads(self.cache_file.read_text(encoding="utf-8"))
292 self.assertNotIn("cached-sentinel-report", json.dumps(payload))
293 self.assertIn("report", payload)
294 self.assertIn("sources", payload["report"])
295 # New timestamp is fresh.
296 age = datetime.datetime.now(datetime.timezone.utc) - datetime.datetime.fromisoformat(
297 payload["timestamp"]
298 )
299 self.assertLess(age.total_seconds(), 60)
300
301 def test_missing_cache_runs_live_and_creates_file(self):
302 self.assertFalse(self.cache_file.exists())
303 rc, out, probe_spy = self.run_doctor(cached=True)
304 self.assertEqual(0, rc)
305 self.assertTrue(probe_spy.called)
306 self.assertTrue(self.cache_file.exists())
307 payload = json.loads(self.cache_file.read_text(encoding="utf-8"))
308 self.assertEqual(
309 set(doctor.SOURCE_ORDER), set(payload["report"]["sources"].keys())
310 )
311
312
313 class ExplicitDoctorAlwaysLive(_CacheDirCase):
314 """Scenario 3: no --cached -> live run even when a fresh cache exists."""
315
316 def test_fresh_cache_ignored_without_cached_flag(self):
317 self.write_cache(seconds_ago=1)
318 rc, out, probe_spy = self.run_doctor(cached=False)
319 self.assertEqual(0, rc)
320 self.assertNotIn("cached-sentinel-report", out)
321 self.assertTrue(probe_spy.called)
322
323 def test_live_run_refreshes_fresh_cache(self):
324 self.write_cache(seconds_ago=1)
325 self.run_doctor(cached=False)
326 raw = self.cache_file.read_text(encoding="utf-8")
327 self.assertNotIn("cached-sentinel-report", raw)
328 self.assertIn("sources", json.loads(raw)["report"])
329
330
331 class TtlOverrideAndCorruptCache(_CacheDirCase):
332 """Scenario 4: TTL env override respected; corrupt cache = absent."""
333
334 def test_ttl_env_override_shrinks_window(self):
335 self.write_cache(seconds_ago=10)
336 os.environ["LAST30DAYS_DOCTOR_TTL"] = "1"
337 rc, out, probe_spy = self.run_doctor(cached=True)
338 self.assertEqual(0, rc)
339 self.assertNotIn("cached-sentinel-report", out)
340 self.assertTrue(probe_spy.called)
341
342 def test_ttl_env_override_widens_window(self):
343 self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)
344 os.environ["LAST30DAYS_DOCTOR_TTL"] = str(doctor.DEFAULT_CACHE_TTL_SECONDS * 10)
345 rc, out, probe_spy = self.run_doctor(cached=True)
346 self.assertIn("cached-sentinel-report", out)
347 self.assertFalse(probe_spy.called)
348
349 def test_ttl_from_config_layer(self):
350 # Registered env key: a .env-set value reaches doctor via config.
351 self.write_cache(seconds_ago=10)
352 rc, out, probe_spy = self.run_doctor({"LAST30DAYS_DOCTOR_TTL": "1"}, cached=True)
353 self.assertNotIn("cached-sentinel-report", out)
354 self.assertTrue(probe_spy.called)
355
356 def test_ttl_zero_disables_cache_reuse(self):
357 self.write_cache(seconds_ago=0)
358 os.environ["LAST30DAYS_DOCTOR_TTL"] = "0"
359 rc, out, probe_spy = self.run_doctor(cached=True)
360 self.assertNotIn("cached-sentinel-report", out)
361 self.assertTrue(probe_spy.called)
362
363 def test_garbage_ttl_falls_back_to_default(self):
364 self.write_cache(seconds_ago=1)
365 os.environ["LAST30DAYS_DOCTOR_TTL"] = "not-a-number"
366 rc, out, probe_spy = self.run_doctor(cached=True)
367 self.assertIn("cached-sentinel-report", out)
368 self.assertFalse(probe_spy.called)
369
370 def test_corrupt_cache_files_treated_as_absent(self):
371 for corrupt in (
372 "not json at all {",
373 json.dumps(["a", "list"]),
374 json.dumps({"timestamp": _iso_utc(), "report": "not-a-dict"}),
375 json.dumps({"timestamp": "garbage-timestamp", "report": {"sources": {}}}),
376 json.dumps({"report": {"sources": {}}}), # no timestamp
377 json.dumps({"timestamp": _iso_utc(), "report": {}}), # no sources
378 ):
379 with self.subTest(corrupt=corrupt[:40]):
380 self.cache_file.write_text(corrupt, encoding="utf-8")
381 rc, out, probe_spy = self.run_doctor(cached=True)
382 self.assertEqual(0, rc, "corrupt cache must never crash")
383 self.assertTrue(probe_spy.called, "corrupt cache must fall through")
384 # And the corrupt file is replaced by a valid one.
385 payload = json.loads(self.cache_file.read_text(encoding="utf-8"))
386 self.assertIn("sources", payload["report"])
387
388 def test_no_config_dir_runs_live_without_crash(self):
389 with mock.patch.object(cli.env, "CONFIG_DIR", None):
390 rc, out, probe_spy = self.run_doctor(cached=True)
391 self.assertEqual(0, rc)
392 self.assertTrue(probe_spy.called)
393
394 def test_ttl_env_var_is_registered(self):
395 # The repo foot-gun: unregistered keys are silently swallowed from
396 # .env. LAST30DAYS_DOCTOR_TTL must be in env.py's get_config registry.
397 import inspect
398
399 from lib import env as env_mod
400
401 self.assertIn("LAST30DAYS_DOCTOR_TTL", inspect.getsource(env_mod.get_config))
402
403
404 class DriftedCacheShapes(_CacheDirCase):
405 """F3: cached reports that drift from the render contract fall through
406 to a live run — never a KeyError crash — in text mode too."""
407
408 def _write_payload(self, report, *, with_envelope=True, seconds_ago=1.0):
409 payload = {"timestamp": _iso_utc(seconds_ago), "report": report}
410 if with_envelope:
411 payload["schema"] = doctor.DOCTOR_CACHE_SCHEMA_VERSION
412 payload["fingerprint"] = doctor._config_fingerprint({})
413 self.cache_file.write_text(json.dumps(payload), encoding="utf-8")
414
415 def test_fresh_drifted_report_text_mode_no_crash(self):
416 # Exact F3 repro: fresh timestamp, report missing engine_version /
417 # config / setup / permissions, record missing tier.
418 self._write_payload({"sources": {"hackernews": {"status": "ok"}}})
419 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
420 self.assertEqual(0, rc, "drifted cache must never crash")
421 self.assertTrue(probe_spy.called, "drifted cache must fall through live")
422 self.assertIn("last30days doctor", out)
423
424 def test_fresh_drifted_report_pre_schema_envelope_no_crash(self):
425 # The original repro shape (no schema stamp at all).
426 self._write_payload(
427 {"sources": {"hackernews": {"status": "ok"}}}, with_envelope=False
428 )
429 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
430 self.assertEqual(0, rc)
431 self.assertTrue(probe_spy.called)
432
433 def test_shape_validator_rejects_each_drift(self):
434 good = self.valid_report()
435 drifted = []
436 for key in ("engine_version", "config", "setup", "permissions"):
437 broken = json.loads(json.dumps(good))
438 del broken[key]
439 drifted.append((f"missing {key}", broken))
440 for key in ("config", "setup", "permissions"):
441 broken = json.loads(json.dumps(good))
442 broken[key] = "not-a-dict"
443 drifted.append((f"{key} not a dict", broken))
444 broken = json.loads(json.dumps(good))
445 broken["sources"]["hackernews"] = "not-a-record"
446 drifted.append(("record not a dict", broken))
447 broken = json.loads(json.dumps(good))
448 broken["sources"]["hackernews"]["tier"] = "sideways"
449 drifted.append(("unknown tier", broken))
450 broken = json.loads(json.dumps(good))
451 del broken["sources"]["hackernews"]["tier"]
452 drifted.append(("missing tier", broken))
453 broken = json.loads(json.dumps(good))
454 broken["sources"]["hackernews"]["status"] = 7
455 drifted.append(("non-str status", broken))
456 for label, report in drifted:
457 with self.subTest(drift=label):
458 self._write_payload(report)
459 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
460 self.assertEqual(0, rc, f"{label}: must never crash")
461 self.assertTrue(probe_spy.called, f"{label}: must fall through")
462
463 def test_run_survives_shapes_the_validator_misses(self):
464 # Even if a bad shape slips past read_cached_report, run()'s
465 # try/except falls through to a live build (never-crash contract).
466 bad = self.valid_report()
467 with mock.patch(
468 "lib.doctor.read_cached_report",
469 return_value={"sources": bad["sources"]}, # renders would KeyError
470 ):
471 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
472 self.assertEqual(0, rc)
473 self.assertTrue(probe_spy.called)
474 self.assertIn("last30days doctor", out)
475
476
477 class SchemaStamp(_CacheDirCase):
478 """F8: payloads without the current schema stamp are treated as absent."""
479
480 def test_schema_mismatch_runs_live(self):
481 self.write_cache(seconds_ago=1, schema="last30days-doctor-cache/v0")
482 rc, out, probe_spy = self.run_doctor(cached=True)
483 self.assertEqual(0, rc)
484 self.assertNotIn("cached-sentinel-report", out)
485 self.assertTrue(probe_spy.called)
486
487 def test_absent_schema_runs_live(self):
488 payload = {
489 "fingerprint": doctor._config_fingerprint({}),
490 "timestamp": _iso_utc(1),
491 "report": self.valid_report(),
492 }
493 self.cache_file.write_text(json.dumps(payload), encoding="utf-8")
494 rc, out, probe_spy = self.run_doctor(cached=True)
495 self.assertEqual(0, rc)
496 self.assertNotIn("cached-sentinel-report", out)
497 self.assertTrue(probe_spy.called)
498
499 def test_live_run_stamps_schema_and_fingerprint(self):
500 self.run_doctor(cached=False)
501 payload = json.loads(self.cache_file.read_text(encoding="utf-8"))
502 self.assertEqual(doctor.DOCTOR_CACHE_SCHEMA_VERSION, payload["schema"])
503 self.assertEqual(doctor._config_fingerprint({}), payload["fingerprint"])
504
505
506 class FingerprintInvalidation(_CacheDirCase):
507 """F12a: credential/pin/opt-in changes invalidate the cache."""
508
509 def test_key_added_invalidates(self):
510 self.write_cache(seconds_ago=1) # fingerprint for empty config
511 rc, out, probe_spy = self.run_doctor(
512 {"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}, cached=True
513 )
514 self.assertEqual(0, rc)
515 self.assertNotIn("cached-sentinel-report", out)
516 self.assertTrue(probe_spy.called, "new credential must invalidate cache")
517
518 def test_key_removed_invalidates(self):
519 cfg = {"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}
520 self.write_cache(seconds_ago=1, config=cfg)
521 rc, out, probe_spy = self.run_doctor({}, cached=True)
522 self.assertNotIn("cached-sentinel-report", out)
523 self.assertTrue(probe_spy.called, "removed credential must invalidate cache")
524
525 def test_pin_change_invalidates(self):
526 self.write_cache(seconds_ago=1)
527 rc, out, probe_spy = self.run_doctor(
528 {"LAST30DAYS_X_BACKEND": "bird"}, cached=True
529 )
530 self.assertNotIn("cached-sentinel-report", out)
531 self.assertTrue(probe_spy.called, "pin change must invalidate cache")
532
533 def test_include_sources_change_invalidates(self):
534 self.write_cache(seconds_ago=1)
535 rc, out, probe_spy = self.run_doctor({"INCLUDE_SOURCES": "linkedin"}, cached=True)
536 self.assertNotIn("cached-sentinel-report", out)
537 self.assertTrue(probe_spy.called)
538
539 def test_fingerprint_ignores_non_signal_config(self):
540 # TTL knob is not a fingerprint signal; same-fingerprint serve holds.
541 self.write_cache(seconds_ago=1)
542 rc, out, probe_spy = self.run_doctor(
543 {"LAST30DAYS_DOCTOR_TTL": str(doctor.DEFAULT_CACHE_TTL_SECONDS)},
544 cached=True,
545 )
546 self.assertIn("cached-sentinel-report", out)
547 self.assertFalse(probe_spy.called)
548
549
550 class StalenessSignals(_CacheDirCase):
551 """F12b: from_cache + generated_at surfaced on every doctor report."""
552
553 def test_matching_fingerprint_serves_cache_with_signals(self):
554 self.write_cache(seconds_ago=120)
555 original_ts = json.loads(self.cache_file.read_text(encoding="utf-8"))["timestamp"]
556 rc, out, probe_spy = self.run_doctor(cached=True)
557 self.assertEqual(0, rc)
558 self.assertFalse(probe_spy.called)
559 data = json.loads(out)
560 self.assertTrue(data["from_cache"])
561 self.assertEqual(original_ts, data["generated_at"])
562
563 def test_live_run_marks_from_cache_false_with_fresh_generated_at(self):
564 rc, out, probe_spy = self.run_doctor(cached=False)
565 self.assertTrue(probe_spy.called)
566 data = json.loads(out)
567 self.assertFalse(data["from_cache"])
568 age = datetime.datetime.now(datetime.timezone.utc) - datetime.datetime.fromisoformat(
569 data["generated_at"]
570 )
571 self.assertLess(age.total_seconds(), 60)
572
573 def test_text_mode_prints_cache_status_line(self):
574 self.write_cache(seconds_ago=1)
575 rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)
576 self.assertFalse(probe_spy.called)
577 self.assertIn("generated:", out)
578 self.assertIn("(cached)", out)
579
580 def test_text_mode_live_status_line(self):
581 rc, out, _ = self.run_doctor(cached=False, emit_json=False)
582 self.assertIn("generated:", out)
583 self.assertIn("(live)", out)
584
585
586 class CacheWriteFailureWarns(_CacheDirCase):
587 """F11: a failing cache write warns on stderr and stays non-fatal."""
588
589 def test_write_failure_warns_and_exits_zero(self):
590 with _Hermetic() as h:
591 stdout, stderr = io.StringIO(), io.StringIO()
592 with mock.patch.object(
593 doctor.private_files, "replace_private_text", side_effect=OSError("disk full")
594 ), redirect_stdout(stdout), redirect_stderr(stderr):
595 rc = doctor.run({}, emit_json=True, cached=False)
596 self.assertEqual(0, rc, "cache write failure must never be fatal")
597 self.assertTrue(h.probe_spy.called)
598 err = stderr.getvalue()
599 self.assertIn("WARNING", err)
600 self.assertIn("doctor cache", err)
601 self.assertIn("disk full", err)
602 # The report itself still rendered.
603 self.assertIn("sources", json.loads(stdout.getvalue()))
604
605
606 class NoSecretsInCacheFile(_CacheDirCase):
607 """Scenario 5: seeded fake credentials never land in the cache file."""
608
609 def test_cache_file_has_no_secret_values(self):
610 rc, out, _ = self.run_doctor(dict(FAKE_SECRETS), cached=False)
611 self.assertEqual(0, rc)
612 raw = self.cache_file.read_text(encoding="utf-8")
613 for var, secret in FAKE_SECRETS.items():
614 if var == "BSKY_HANDLE":
615 continue # a handle is an identifier, not a credential
616 self.assertNotIn(secret, raw, var)
617
618 def test_fingerprint_field_carries_no_secret_values(self):
619 rc, out, _ = self.run_doctor(dict(FAKE_SECRETS), cached=False)
620 self.assertEqual(0, rc)
621 payload = json.loads(self.cache_file.read_text(encoding="utf-8"))
622 fingerprint = payload["fingerprint"]
623 # An opaque sha256 hex digest only — no raw values of any kind.
624 self.assertRegex(fingerprint, r"^[0-9a-f]{64}$")
625 for var, secret in FAKE_SECRETS.items():
626 self.assertNotIn(secret, fingerprint, var)
627
628
629 class CliCachedPassthrough(_CacheDirCase):
630 """`doctor --cached` is an accepted passthrough flag wired to doctor.run."""
631
632 def _cli(self, argv):
633 with mock.patch("lib.doctor.run", return_value=0) as run, \
634 mock.patch.object(cli.env, "get_config", return_value={}), \
635 mock.patch.object(sys, "argv", ["last30days.py"] + argv):
636 stdout, stderr = io.StringIO(), io.StringIO()
637 with redirect_stdout(stdout), redirect_stderr(stderr):
638 rc = cli.main()
639 return rc, run
640
641 def test_cached_flag_passes_through(self):
642 rc, run = self._cli(["doctor", "--cached"])
643 self.assertEqual(0, rc)
644 self.assertTrue(run.call_args.kwargs.get("cached"))
645
646 def test_cached_json_combination(self):
647 rc, run = self._cli(["doctor", "--cached", "--json"])
648 self.assertEqual(0, rc)
649 self.assertTrue(run.call_args.kwargs.get("cached"))
650 self.assertTrue(run.call_args.kwargs.get("emit_json"))
651
652 def test_plain_doctor_is_live(self):
653 rc, run = self._cli(["doctor"])
654 self.assertEqual(0, rc)
655 self.assertFalse(run.call_args.kwargs.get("cached"))
656
657 def test_cached_rejected_for_research_topics(self):
658 with mock.patch.object(sys, "argv", ["last30days.py", "some", "topic", "--cached"]):
659 stderr = io.StringIO()
660 with redirect_stderr(stderr), self.assertRaises(SystemExit) as exc:
661 cli.main()
662 self.assertEqual(2, exc.exception.code)
663 self.assertIn("--cached", stderr.getvalue())
664
665
666 class DoctorSkillContract(unittest.TestCase):
667 """Scenario 6: SKILL.md integration locked against silent erosion
668 (same read-the-runtime-contract pattern as test_onboarding_contract.py)."""
669
670 @classmethod
671 def setUpClass(cls):
672 from tests.skill_contract import reference_text
673
674 cls.text = reference_text("research-runbook")
675
676 def test_doctor_trigger_phrases_present(self):
677 for phrase in (
678 "health check",
679 "is X working",
680 "why is a source missing",
681 "what's broken",
682 ):
683 self.assertIn(phrase, self.text, f"missing doctor trigger phrase: {phrase!r}")
684
685 def test_cached_standing_rule_present(self):
686 self.assertIn("doctor --cached --json", self.text)
687 self.assertIn("login-backed", self.text)
688 self.assertIn("doctor-cache.json", self.text)
689 self.assertIn("LAST30DAYS_DOCTOR_TTL", self.text)
690
691 def test_rerun_live_only_when_stale_or_degraded(self):
692 self.assertIn("stale", self.text)
693 self.assertIn("degraded login-backed source", self.text)
694
695 def test_standing_rule_is_marked_mandatory(self):
696 # The pre-research cache consult is a must-fire rule; it uses the
697 # same bold MANDATORY marker style as Step 0.45 so it cannot read
698 # as soft advisory prose (F16b).
699 self.assertIn("**MANDATORY standing rule.**", self.text)
700
701 def test_frontmatter_description_routes_research_and_health(self):
702 # Cold-start prompts like "is my last30days X search broken?" can only
703 # load the skill if the machine-parsed frontmatter description mentions
704 # the health surface (F16a); an ordinary research prompt still needs
705 # the research surface in the same line. Both must fit the 60-char
706 # routing index truncating hosts apply (Hermes clips every description
707 # at SKILL_PROMPT_DESC_LIMIT = 60 before the model sees it). The phrase
708 # "health check" itself lives in the body.
709 desc = _skill_description(
710 SKILL_MD.parent,
711 needles=("research", "30 days", "doctor", "diagnose", "broken"),
712 )
713 self.assertLessEqual(len(desc), DESCRIPTION_ROUTING_BUDGET)
714
715 def test_predicted_backend_announcement(self):
716 self.assertIn("active_backend", self.text)
717
718 def test_configuration_md_documents_doctor(self):
719 config_text = (ROOT / "CONFIGURATION.md").read_text(encoding="utf-8")
720 for needle in (
721 "doctor --json",
722 "doctor --cached",
723 "doctor-cache.json",
724 "LAST30DAYS_DOCTOR_TTL",
725 "LAST30DAYS_X_BACKEND",
726 "LAST30DAYS_REDDIT_BACKEND",
727 "--web-backend",
728 ):
729 self.assertIn(needle, config_text, f"CONFIGURATION.md missing: {needle!r}")
730
731
732 class SkillRoutingDescriptionContract(unittest.TestCase):
733 """The frontmatter description is routing text; its YAML shape is a gate."""
734
735 def test_description_contract_rejects_wrapped_folded_or_health_only_lines(self):
736 # Fixtures an earlier revision accepted: a wrapped scalar whose first
737 # source line is 50 chars, a folded block that parses to one short
738 # line, a literal block, and a health-only line with no research
739 # surface. Each must fail the contract, not just measure short.
740 rejected = {
741 "wrapped plain scalar": (
742 "name: probe\n"
743 "description: Research the last 30 days; doctor diagnoses broken\n"
744 " sources and keeps going past the routing budget.\n"
745 ),
746 "folded scalar": (
747 "name: probe\n"
748 "description: >-\n"
749 " Research the last 30 days; doctor diagnoses broken sources.\n"
750 ),
751 "literal scalar": (
752 "name: probe\n"
753 "description: |\n"
754 " Research the last 30 days; doctor diagnoses broken sources.\n"
755 ),
756 "health only": (
757 'name: probe\ndescription: "Doctor diagnoses broken sources."\n'
758 ),
759 }
760 for label, block in rejected.items():
761 with self.subTest(label):
762 with self.assertRaises(AssertionError):
763 _checked_description(
764 block,
765 needles=("research", "30 days", "doctor", "diagnose", "broken"),
766 )
767
768 def test_frontmatter_fence_ignores_dashes_inside_values(self):
769 # A horizontal rule in a quoted value must not end the frontmatter
770 # early, and an unclosed fence must not be read as valid.
771 text = (
772 "---\n"
773 "name: probe\n"
774 "argument-hint: 'run a --- b'\n"
775 'description: "Research the last 30 days; doctor diagnoses broken sources."\n'
776 "---\n"
777 "# body\n"
778 )
779 block = _frontmatter_block(text)
780 self.assertIn("argument-hint", block)
781 self.assertEqual(
782 "Research the last 30 days; doctor diagnoses broken sources.",
783 _checked_description(
784 block,
785 needles=("research", "30 days", "doctor", "diagnose", "broken"),
786 ),
787 )
788 with self.assertRaises(AssertionError):
789 _frontmatter_block("---\nname: probe\ndescription: unclosed\n# body\n")
790
791 def test_every_skill_description_fits_the_routing_index_budget(self):
792 skill_dirs = sorted(path.parent for path in (ROOT / "skills").glob("*/SKILL.md"))
793 self.assertTrue(skill_dirs, "no skills/*/SKILL.md found to check")
794 for skill_dir in skill_dirs:
795 with self.subTest(skill_dir.name):
796 _skill_description(skill_dir)
797
798
799 if __name__ == "__main__":
800 unittest.main()
801
801 lines PYTHON