Files
Pulse/scripts/tests/test_public_docs_claims.py
pulse-triage[bot] 41f9f71c6c Align Alerting, Patrol, API, and Agent Security Help with runtime fixes
Document four recently landed monitoring, alerting, and Patrol runtime
changes in unclaimed in-app Help guides and their mirrored public copies,
with source-bound Python regression tests:

- docs/ALERTING.md (+ mirror): document single-snapshot latest-completion
  Prometheus poll freshness (#5246), stopped-scheduler exclusion from
  pulse_scheduler_queued_poll_overdue_seconds while blocked workers stay
  in pulse_scheduler_claimed_poll_overdue_seconds (#5238), and immediate
  non-retryable TLS terminal failures across email, webhook, and Apprise
  destinations without an email/webhook Skip TLS Verify toggle (#5167).
- docs/AI_AUTONOMY.md and docs/API.md (+ mirrors): document the 24-hour
  approval window for background and refreshed Patrol action plans
  (DefaultPatrolPlanTTL) versus the 5-minute default expiry for direct API
  and interactive plans (DefaultPlanTTL) (#5170).
- docs/AGENT_SECURITY.md (+ mirror): align the container failure-log AI
  disclosure line with the retired in-app Assistant chat (Patrol and
  legacy Pulse Mobile chat until 31 March 2027).
- scripts/tests/test_alerting_outage_help_docs.py and
  scripts/tests/test_public_docs_claims.py: bind each documented behaviour
  directly to live Go runtime sources.

Contract-Neutral: Documentation, mirrored in-app Help, and Python doc-regression test alignment for already-landed runtime behaviour with no runtime, API, schema, or subsystem contract changes.
Change-source: pulse-maintainer
2026-11-27 17:02:27 +00:00

443 lines
19 KiB
Python

#!/usr/bin/env python3
"""Guard public capability claims and complete, scan-local link validation."""
from __future__ import annotations
import importlib.util
from pathlib import Path
import sys
import tempfile
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "scripts" / "check_public_docs.py"
SPEC = importlib.util.spec_from_file_location("check_public_docs", SCRIPT)
assert SPEC is not None and SPEC.loader is not None
public_docs = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = public_docs
SPEC.loader.exec_module(public_docs)
class PublicDocsClaimsTest(unittest.TestCase):
def test_release_notes_are_in_the_public_claim_surface(self) -> None:
files = public_docs.public_markdown_files()
self.assertIn(ROOT / "docs/releases/RELEASE_NOTES_v6.4.0-rc.7.md", files)
def test_rejects_reversed_dead_man_direction(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
note = root / "note.md"
note.write_text(
"Dead-man checks can notify when an expected external signal "
"stops arriving.\n",
encoding="utf-8",
)
with mock.patch.object(public_docs, "ROOT", root):
errors = public_docs.check_public_claims([note])
self.assertEqual(len(errors), 1)
self.assertIn("dead-man direction is reversed", errors[0])
def test_accepts_outbound_watchdog_description(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
note = root / "note.md"
note.write_text(
"Pulse sends its own health signal to a watchdog on another host.\n",
encoding="utf-8",
)
with mock.patch.object(public_docs, "ROOT", root):
errors = public_docs.check_public_claims([note])
self.assertEqual(errors, [])
def test_rejects_removed_truenas_rest_probe(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
note = root / "note.md"
note.write_text(
"Test with https://nas.local/api/v2.0/system/info.\n",
encoding="utf-8",
)
with mock.patch.object(public_docs, "ROOT", root):
errors = public_docs.check_public_claims([note])
self.assertEqual(len(errors), 1)
self.assertIn("TrueNAS 26 removed", errors[0])
def test_contributing_references_live_repository_paths_and_commands(self) -> None:
text = (ROOT / "CONTRIBUTING.md").read_text(encoding="utf-8")
for required in (
"`cmd/pulse-agent`",
"`cmd/pulse-agent-helper`",
"`cmd/pulse-agent-runner`",
"`internal/monitoring`",
"`npm --prefix frontend-modern run build`",
"`make build-agents`",
):
self.assertIn(required, text)
for stale in (
"cmd/pulse-*-agent",
"`internal/monitor`",
"docs/internal/SCRIPT_LIBRARY.md",
"make bundle-scripts",
"MIGRATION_SCAFFOLDING.md",
):
self.assertNotIn(stale, text)
self.assertEqual(
(ROOT / "frontend-modern/public/docs/CONTRIBUTING.md").read_text(encoding="utf-8"),
text,
)
class PublicDocsLinksTest(unittest.TestCase):
def setUp(self) -> None:
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.root_patch = mock.patch.object(public_docs, "ROOT", self.root)
self.root_patch.start()
self.addCleanup(self.root_patch.stop)
def document(self, name: str, text: str) -> Path:
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
def test_repeated_links_scan_each_target_once_without_hiding_any_errors(self) -> None:
target = self.document("guide.md", "# Shared\n# Shared\n")
first = self.document(
"first.md", "[one](guide.md#shared) [two](guide.md#shared-1) "
"[bad](guide.md#missing)\n",
)
second = self.document(
"nested/second.md", "[same](../guide.md#shared) "
"[bad](../guide.md#missing)\n",
)
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
errors = public_docs.check_links([first, second])
self.assertEqual(errors, [
"first.md: missing anchor #missing in guide.md",
"nested/second.md: missing anchor #missing in guide.md",
])
scan.assert_called_once_with(target)
def test_empty_anchor_set_is_cached_and_each_link_still_fails(self) -> None:
target = self.document("empty.md", "There are no headings.\n")
source = self.document("source.md", "[one](empty.md#one) [two](empty.md#two)\n")
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
errors = public_docs.check_links([source])
self.assertEqual(errors, [
"source.md: missing anchor #one in empty.md",
"source.md: missing anchor #two in empty.md",
])
scan.assert_called_once_with(target)
def test_distinct_targets_with_the_same_filename_do_not_share_anchors(self) -> None:
first = self.document("first/guide.md", "# First\n")
second = self.document("second/guide.md", "# Second\n")
source = self.document(
"source.md", "[one](first/guide.md#first) [two](second/guide.md#second) "
"[bad](second/guide.md#first)\n",
)
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
errors = public_docs.check_links([source])
self.assertEqual(errors, ["source.md: missing anchor #first in second/guide.md"])
self.assertEqual(scan.call_args_list, [mock.call(first), mock.call(second)])
def test_next_check_reads_changed_headings_instead_of_reusing_an_old_scan(self) -> None:
target = self.document("guide.md", "# Before\n")
source = self.document("source.md", "[one](guide.md#before) [two](guide.md#before)\n")
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
self.assertEqual(public_docs.check_links([source]), [])
target.write_text("# After\n", encoding="utf-8")
errors = public_docs.check_links([source])
self.assertEqual(errors, ["source.md: missing anchor #before in guide.md"] * 2)
self.assertEqual(scan.call_args_list, [mock.call(target), mock.call(target)])
def test_self_links_decoding_and_heading_suffixes_keep_their_existing_rules(self) -> None:
source = self.document(
"source.md", "# Café\n# Café\n[one](#caf%C3%A9) [two](#café-1) [bad](#café-2)\n",
)
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
errors = public_docs.check_links([source])
self.assertEqual(errors, ["source.md: missing anchor #café-2 in source.md"])
scan.assert_called_once_with(source)
def test_code_heading_keeps_literal_underscores_but_prose_emphasis_does_not(self) -> None:
self.document("guide.md", "### `invalid_client` after _saving_\n")
source = self.document(
"source.md", "[direct](guide.md#invalid_client-after-saving) "
"[wrong](guide.md#invalidclient-after-saving)\n",
)
self.assertEqual(public_docs.check_links([source]), [
"source.md: missing anchor #invalidclient-after-saving in guide.md",
])
def test_missing_files_still_fail_without_scanning_external_or_nonmarkdown_targets(self) -> None:
self.document("image.svg", "<svg/>\n")
source = self.document(
"source.md", "[missing](missing.md#one) [external](https://example.invalid/#one) "
"![image](image.svg#one) [self](#)\n",
)
with mock.patch.object(public_docs, "anchors_for", wraps=public_docs.anchors_for) as scan:
errors = public_docs.check_links([source])
self.assertEqual(errors, ["source.md: missing local target missing.md#one"])
scan.assert_not_called()
def test_code_comments_do_not_create_recovery_destinations_or_shift_suffixes(self) -> None:
self.document(
"guide.md", "# Recovery\n```sh\n# Recovery\n# Reset lockout\n```\n# Recovery\n",
)
source = self.document(
"source.md", "[first](guide.md#recovery) [second](guide.md#recovery-1) "
"[phantom](guide.md#recovery-2) [comment](guide.md#reset-lockout)\n",
)
self.assertEqual(public_docs.check_links([source]), [
"source.md: missing anchor #recovery-2 in guide.md",
"source.md: missing anchor #reset-lockout in guide.md",
])
def test_fenced_markdown_and_html_examples_are_not_live_links(self) -> None:
source = self.document(
"source.md", "# Present\n```markdown\n[example](absent.md#one)\n"
'<a href="also-absent.md#two">example</a>\n```\n'
"~~~html\n<img src='absent.png'>\n~~~\n"
"[real](#present) [broken](#missing)\n",
)
self.assertEqual(public_docs.check_links([source]), [
"source.md: missing anchor #missing in source.md",
])
def test_closing_fence_needs_matching_character_and_enough_markers(self) -> None:
for opening, short, wrong, closing in [
("````sh", "```", "~~~~", "`````"),
("~~~~sh", "~~~", "````", "~~~~~"),
]:
with self.subTest(opening=opening):
guide = self.document(
"guide.md", f"{opening}\n# Hidden\n{short}\n# Still hidden\n"
f"{wrong}\n# Also hidden\n{closing}\n# Visible\n",
)
self.assertEqual(public_docs.anchors_for(guide), {"visible"})
def test_closing_fence_cannot_carry_an_info_string(self) -> None:
guide = self.document(
"guide.md", "```sh\n# Hidden\n```not-a-close\n# Still hidden\n```\n# Visible\n",
)
self.assertEqual(public_docs.anchors_for(guide), {"visible"})
def test_fences_allow_up_to_three_spaces_and_trailing_closing_whitespace(self) -> None:
for indent in range(4):
with self.subTest(indent=indent):
guide = self.document(
"guide.md", f"{' ' * indent}~~~sh\n# Hidden\n"
f"{' ' * indent}~~~ \t\n# Visible\n",
)
self.assertEqual(public_docs.anchors_for(guide), {"visible"})
def test_unclosed_fences_hide_examples_through_the_end_of_the_file(self) -> None:
source = self.document(
"source.md", "# Present\n```sh\n# Not a heading\n[example](absent.md)\n",
)
self.assertEqual(public_docs.anchors_for(source), {"present"})
self.assertEqual(public_docs.check_links([source]), [])
def test_backticks_in_backtick_info_do_not_open_a_fence(self) -> None:
guide = self.document("guide.md", "```not`a-fence\n# Visible\n")
self.assertEqual(public_docs.anchors_for(guide), {"visible"})
def test_closed_example_does_not_join_prose_into_an_accidental_link(self) -> None:
source = self.document(
"source.md", "[example]\n```markdown\nanything\n```\n(absent.md)\n",
)
self.assertEqual(public_docs.check_links([source]), [])
class PublicDocsProsePunctuationTest(unittest.TestCase):
def test_rejects_em_dash_and_semicolon_in_prose_only(self) -> None:
text = (
"Clean line with a period.\n"
"Line with an em dash \u2014 should fail.\n"
"Line with a semicolon; should fail.\n"
"Inline code `foo; bar \u2014 baz` and HTML &amp; entity and "
"[link](https://example.invalid/a;b) are allowed.\n"
"```sh\n"
"echo one; echo two # \u2014 inside code fence\n"
"```\n"
)
errors = public_docs.check_prose_punctuation_in_text("README.md", text)
self.assertEqual(
errors,
[
"README.md:2: avoid em dashes in public docs prose",
"README.md:3: avoid semicolons in public docs prose",
],
)
def test_diff_mode_checks_only_added_lines_and_ignores_existing_history(self) -> None:
import os
import subprocess
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
env = dict(
os.environ,
GIT_AUTHOR_NAME="Fixture",
GIT_AUTHOR_EMAIL="fixture@example.invalid",
GIT_COMMITTER_NAME="Fixture",
GIT_COMMITTER_EMAIL="fixture@example.invalid",
)
def git(*args: str) -> str:
return subprocess.run(
["git", *args],
cwd=root,
env=env,
text=True,
check=True,
capture_output=True,
timeout=5,
).stdout.strip()
git("init", "-q")
readme = root / "README.md"
readme.write_text("Legacy line; untouched.\n", encoding="utf-8")
git("add", "README.md")
git("commit", "-qm", "initial")
base_sha = git("rev-parse", "HEAD")
readme.write_text(
"Legacy line; untouched.\nAdded line with an em dash \u2014 here.\n",
encoding="utf-8",
)
git("add", "README.md")
with mock.patch.object(public_docs, "ROOT", root):
staged_errors = public_docs.check_changed_prose_punctuation([readme], staged=True)
self.assertEqual(
staged_errors,
["README.md:2: avoid em dashes in public docs prose"],
)
git("commit", "-qm", "add doc line")
with mock.patch.object(public_docs, "ROOT", root):
pr_errors = public_docs.check_changed_prose_punctuation(
[readme], base_ref=base_sha
)
self.assertEqual(
pr_errors,
["README.md:2: avoid em dashes in public docs prose"],
)
class AIAutonomyHelpDocsTest(unittest.TestCase):
def test_prometheus_section_matches_exported_metrics_and_endpoints(self) -> None:
doc = (ROOT / "docs/AI_AUTONOMY.md").read_text(encoding="utf-8")
mirror = (ROOT / "frontend-modern/public/docs/AI_AUTONOMY.md").read_text(
encoding="utf-8"
)
self.assertEqual(doc, mirror)
self.assertNotIn("Prometheus counters (prefix `pulse_patrol_*`) track:", doc)
self.assertIn(
"Pulse does not export a `pulse_patrol_*` Prometheus metric family.",
doc,
)
for metric in (
"`pulse_ai_agentic_iterations_total`",
"`pulse_ai_strict_resolution_block_total`",
"`pulse_ai_routing_mismatch_block_total`",
"`pulse_ai_phantom_detected_total`",
"`pulse_operational_trust_action_offers_total`",
"`pulse_operational_trust_action_verification_total`",
):
self.assertIn(metric, doc)
for endpoint in (
"`GET /api/ai/patrol/status`",
"`GET /api/ai/patrol/runs`",
"`GET /api/ai/patrol/findings`",
"`GET /api/ai/circuit/status`",
):
self.assertIn(endpoint, doc)
def test_relay_entitlements_and_investigation_runtime_limits_match_code(self) -> None:
normalized = " ".join(
(ROOT / "docs/AI_AUTONOMY.md").read_text(encoding="utf-8").split()
)
self.assertNotIn("Community and Relay baseline", normalized)
self.assertNotIn("Community and Relay can run Patrol with BYOK", normalized)
self.assertIn(
"Continuing Relay subscribers receive Pro entitlements",
normalized,
)
self.assertIn("retire on 31 March 2027", normalized)
self.assertIn(
"Pro, continuing Relay, legacy Pro+, or Cloud license",
normalized,
)
self.assertIn("`investigation_budget`", normalized)
self.assertIn("`investigation_timeout_sec`", normalized)
self.assertIn("up to 64 additional findings can wait in memory", normalized)
self.assertIn(
"20 minute cooldown after a failed fix or failed fix verification",
normalized,
)
self.assertIn("10 minute cooldown after a timed-out outcome", normalized)
self.assertIn("30-day budget (USD)", normalized)
def test_patrol_plan_approval_ttl_matches_actionplanner_source(self) -> None:
planner = (ROOT / "internal/actionplanner/planner.go").read_text(encoding="utf-8")
broker = (ROOT / "internal/api/patrol_action_broker.go").read_text(encoding="utf-8")
self.assertIn("DefaultPlanTTL = 5 * time.Minute", planner)
self.assertIn("DefaultPatrolPlanTTL = 24 * time.Hour", planner)
self.assertIn("opts.TTL = actionplanner.DefaultPatrolPlanTTL", broker)
autonomy = (ROOT / "docs/AI_AUTONOMY.md").read_text(encoding="utf-8")
autonomy_mirror = (ROOT / "frontend-modern/public/docs/AI_AUTONOMY.md").read_text(
encoding="utf-8"
)
self.assertEqual(autonomy, autonomy_mirror)
autonomy_norm = " ".join(autonomy.split())
for phrase in (
"background Patrol plans stay open for approval for 24 hours",
"Background Patrol action plans, including refreshed Patrol plans, stay open for approval for 24 hours before expiring, matching investigation retention",
"Direct API and interactive action plans keep the 5-minute default expiry",
"Live freshness, policy, and emergency-stop checks still run when an approved plan executes",
):
with self.subTest(autonomy_phrase=phrase):
self.assertIn(phrase, autonomy_norm)
api_doc = (ROOT / "docs/API.md").read_text(encoding="utf-8")
api_mirror = (ROOT / "frontend-modern/public/docs/API.md").read_text(encoding="utf-8")
self.assertEqual(api_doc, api_mirror)
api_norm = " ".join(api_doc.split())
self.assertIn(
"Direct API and interactive plans expire after 5 minutes by default, while background and refreshed Patrol plans stay open for approval for 24 hours.",
api_norm,
)
def test_agent_security_failure_log_disclosure_reflects_retired_web_assistant(self) -> None:
doc = (ROOT / "docs/AGENT_SECURITY.md").read_text(encoding="utf-8")
mirror = (ROOT / "frontend-modern/public/docs/AGENT_SECURITY.md").read_text(
encoding="utf-8"
)
self.assertEqual(doc, mirror)
normalized = " ".join(doc.split())
self.assertNotIn("when Patrol or the Assistant reads the container", normalized)
self.assertIn(
"when Patrol reads the container (or legacy Pulse Mobile chat until 31 March 2027)",
normalized,
)
if __name__ == "__main__":
unittest.main()