Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(search): fetch Wayback snapshots by URL (#7317)

LearningCircuitef7a1b19f647
diff --git a/README.md b/README.md
index a975743f0a..e9da4cfd3b 100644
--- a/README.md
+++ b/README.md
@@ -253,7 +253,7 @@ Picking a local model? The same community-maintained dataset tracks accuracy acr
- **Academic**: arXiv, PubMed, Semantic Scholar
- **General**: Wikipedia, SearXNG
- **Technical**: GitHub, Elasticsearch
-- **Historical**: Wayback Machine
+- **Archived pages**: Wayback Machine URL fetching
- **News**: The Guardian, Wikinews
#### Premium Search Engines
diff --git a/changelog.d/+archive-fetch.feature.md b/changelog.d/+archive-fetch.feature.md
new file mode 100644
index 0000000000..816f47c125
--- /dev/null
+++ b/changelog.d/+archive-fetch.feature.md
@@ -0,0 +1,23 @@
+Add the LangGraph agent's `fetch_archive(url, date="YYYY-MM-DD")` tool for
+reading Wayback captures of URLs found with a configured search provider.
+Omitting the date selects the latest capture; date-based lookup selects the
+nearest capture and preserves its actual date for citations. Archive and
+live-page fetching share fetch modes, content limits, and each agent's topic
+budget. Agent archive reads skip the shared research content cache for page
+text: `fetch_archive`, and `fetch_content` given a
+`web.archive.org/web/<timestamp>/` capture URL or the citation of an archived
+page, never read or store cached page text and are not merged with a
+concurrent fetch of the same URL. The existing Wayback
+agent toggle enables archive fetching for the lead agent and subagents.
+Wayback is removed from the primary search picker
+while saved selections, settings, and legacy programmatic URL lookups remain
+available; users with Wayback saved should select a configured topic-search
+provider. The legacy Wayback search adapter looks up each complete `http://`
+or `https://` URL in a query, including its port, path, query string and
+fragment, instead of only its host, with the scheme in any case and with
+bracketed IPv6 hosts; a query that is only a domain, optionally with a port,
+path or query, is looked up too, and any other query returns no results. In
+running text the adapter drops most punctuation and quotes that end a URL, but
+words that follow a URL without a space become part of it. It skips a URL
+with a user name or password before its host, an invalid port or no host,
+and looks up at most `max_results` URLs per query.
diff --git a/changelog.d/7310.removal.md b/changelog.d/7310.removal.md
index fc4fe82a74..0e0bdecce8 100644
--- a/changelog.d/7310.removal.md
+++ b/changelog.d/7310.removal.md
@@ -1 +1 @@
-Remove LDR's dormant DuckDuckGo adapter and direct search dependency. Wayback no longer silently queries another provider to discover URLs. It keeps its lookup of the host of each lowercase `http://` or `https://` URL in a query, or of a query that is only a bare domain, and tells research agents to discover URLs through a configured provider first. Any other query now returns no results, including a dotted topic, a domain with a path but no scheme, a URL with an uppercase scheme or a bracketed IPv6 host, and a bare domain with a punycode top-level domain such as `.xn--p1ai` (give it as a full URL); Wayback used to look a dotted query up as a URL when discovery found no URLs. A URL with a user name or password before the host is not supported: the start of the user name is looked up instead of the host. SearXNG's upstream engine configuration remains available.
+Remove LDR's dormant DuckDuckGo adapter and its direct search dependency, including the Wayback engine's use of DuckDuckGo to discover URLs for a topic query. SearXNG's upstream engine configuration remains available.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 0aa90185a4..ce1dbbe4e0 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -597,18 +597,18 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.tinyfish.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_TINYFISH_SUPPORTS_FULL_SEARCH` | `true` | Whether this search engine can return extracted page content. | SEARCH |
| `search.engine.web.tinyfish.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_TINYFISH_USE_IN_AUTO_SEARCH` | `false` | Include TinyFish in auto search mode | SEARCH |
| `search.engine.web.tinyfish.weaknesses` | `LDR_SEARCH_ENGINE_WEB_TINYFISH_WEAKNESSES` | ``["requires hosted API key", "external network requests leave the local environment", "fetch latency depends on target page rendering"]`` | Weaknesses of this search engine. | SEARCH |
-| `search.engine.web.wayback.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_AGENT_ENABLED` | `true` | Include Wayback as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH |
-| `search.engine.web.wayback.default_params.closest_only` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_CLOSEST_ONLY` | `false` | When enabled, only return the snapshot closest to the target date instead of all available snapshots. | SEARCH |
-| `search.engine.web.wayback.default_params.language` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_LANGUAGE` | `English` | Preferred language for archived content when multiple versions are available. | SEARCH |
-| `search.engine.web.wayback.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_MAX_RESULTS` | `15` | Maximum number of archived snapshots to return per search query. | SEARCH |
-| `search.engine.web.wayback.default_params.max_snapshots_per_url` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_MAX_SNAPSHOTS_PER_URL` | `3` | Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history. | SEARCH |
-| `search.engine.web.wayback.description` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DESCRIPTION` | `Search the Internet Archive's Wayback Machine.` | Human-readable description of the search engine. | SEARCH |
+| `search.engine.web.wayback.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_AGENT_ENABLED` | `true` | Enable the fetch_archive tool for the lead LangGraph research agent and its subagents. Find URLs with a configured search provider, then fetch an archived version with an optional date. Uses search.fetch.mode and the shared search.fetch.max_per_topic budget; disabled fetch mode or egress policy can still block archive fetching. | SEARCH |
+| `search.engine.web.wayback.default_params.closest_only` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_CLOSEST_ONLY` | `false` | Legacy URL adapter: When enabled, only return the snapshot closest to the target date instead of all available snapshots. Does not control fetch_archive. | SEARCH |
+| `search.engine.web.wayback.default_params.language` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_LANGUAGE` | `English` | Legacy URL adapter: Preferred language for archived content when multiple versions are available. Does not control fetch_archive. | SEARCH |
+| `search.engine.web.wayback.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_MAX_RESULTS` | `15` | Legacy URL adapter: Maximum number of archived snapshots to return per search query. Does not control fetch_archive. | SEARCH |
+| `search.engine.web.wayback.default_params.max_snapshots_per_url` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DEFAULT_PARAMS_MAX_SNAPSHOTS_PER_URL` | `3` | Legacy URL adapter: Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history. Does not control fetch_archive. | SEARCH |
+| `search.engine.web.wayback.description` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DESCRIPTION` | `Fetch archived versions of known URLs from the Internet Archive's Wayback Machine.` | Human-readable description of the search engine. | SEARCH |
| `search.engine.web.wayback.display_name` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_DISPLAY_NAME` | `Wayback` | Display name to use in the U.I. for this search engine. | SEARCH |
| `search.engine.web.wayback.reliability` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_RELIABILITY` | `0.5` | Reliability score (0-1). Wayback rated moderate (0.5) - great for historical content but archives may be incomplete. | SEARCH |
| `search.engine.web.wayback.requires_api_key` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_REQUIRES_API_KEY` | `false` | Wayback Machine is free and does not require an API key. | SEARCH |
| `search.engine.web.wayback.strengths` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_STRENGTHS` | ``["historical web content", "archived websites", "content verification", "deleted or changed web pages", "website evolution tracking"]`` | Advantages: Access to historical web content, archived/deleted pages, content verification, and website evolution. | SEARCH |
| `search.engine.web.wayback.supports_full_search` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_SUPPORTS_FULL_SEARCH` | `true` | Indicates this engine can fetch full archived page content, not just metadata. | SEARCH |
-| `search.engine.web.wayback.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_USE_IN_AUTO_SEARCH` | `false` | Include Wayback in auto search mode | SEARCH |
+| `search.engine.web.wayback.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_USE_IN_AUTO_SEARCH` | `false` | Legacy setting retained for compatibility. Wayback accepts URLs only and is excluded from topic and auto search; choose a configured search provider for topics. | SEARCH |
| `search.engine.web.wayback.weaknesses` | `LDR_SEARCH_ENGINE_WEB_WAYBACK_WEAKNESSES` | ``["limited to previously archived content", "may miss recent changes", "archiving quality varies"]`` | Limitations: Only finds previously archived content, may miss recent changes, archive quality varies by site. | SEARCH |
| `search.engine.web.webz.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_WEBZ_AGENT_ENABLED` | `false` | Include Webz.io as an additional specialized news tool for the research agent. Disabled by default; selecting Webz.io as search.tool still uses it as the primary engine. | SEARCH |
| `search.engine.web.webz.api_key` | `LDR_SEARCH_ENGINE_WEB_WEBZ_API_KEY` | `` | Webz.io API token with api_news permission and available credits. Stored as a password setting. Requests use HTTPS only with no redirects; direct documentation shows HTTP, and live TLS compatibility has not been smoke-tested. | SEARCH |
@@ -654,9 +654,9 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.zenodo.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_ZENODO_USE_IN_AUTO_SEARCH` | `false` | Include Zenodo in auto search mode | SEARCH |
| `search.engine.web.zenodo.weaknesses` | `LDR_SEARCH_ENGINE_WEB_ZENODO_WEAKNESSES` | ``["research focus", "variable quality", "metadata only"]`` | Limitations of Zenodo. | SEARCH |
| `search.favorites` | `LDR_SEARCH_FAVORITES` | ``["arxiv", "searxng", "library", "openalex"]`` | List of favorite search engine IDs that appear at the top of the dropdown. Edit as JSON array, e.g. ["arxiv", "brave"] | SEARCH |
-| `search.fetch.content_max_length` | `LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH` | `10000` | Maximum page text (in characters) passed to the fetch_content tool per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content tool; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
-| `search.fetch.max_per_topic` | `LDR_SEARCH_FETCH_MAX_PER_TOPIC` | `2` | Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets). | SEARCH |
-| `search.fetch.mode` | `LDR_SEARCH_FETCH_MODE` | `summary_focus_query` | Controls the LangGraph agent's fetch_content tool. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
+| `search.fetch.content_max_length` | `LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH` | `10000` | Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
+| `search.fetch.max_per_topic` | `LDR_SEARCH_FETCH_MAX_PER_TOPIC` | `2` | Maximum number of page content fetches (fetch_content and fetch_archive calls sharing one budget) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets). | SEARCH |
+| `search.fetch.mode` | `LDR_SEARCH_FETCH_MODE` | `summary_focus_query` | Controls the LangGraph agent's fetch_content and fetch_archive tools. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes both tools entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
| `search.final_max_results` | `LDR_SEARCH_FINAL_MAX_RESULTS` | `100` | Maximum unique sources to include in the final research output. Applied in pipeline/source-based strategies once after all search iterations complete, deduplicating and filtering across all accumulated results. Note: Autonomous agent strategies (like langgraph-agent) manage context autonomously and do not cap final results. | SEARCH |
| `search.iterations` | `LDR_SEARCH_ITERATIONS` | `3` | Number of search-and-refine cycles to run. Each iteration generates follow-up questions based on previous results to progressively deepen the research. More iterations yield better coverage but increase search and LLM API usage. | SEARCH |
| `search.journal_reputation.enable_llm_scoring` | `LDR_SEARCH_JOURNAL_REPUTATION_ENABLE_LLM_SCORING` | `false` | Enable Tier 4 LLM journal scoring via SearXNG. When disabled (default), only bundled data (OpenAlex, DOAJ, predatory lists) is used for scoring journal reputation. Tier 4 adds significant latency (1 SearXNG search + 1 LLM call per unknown journal) and only helps for journals outside the 217K-row reference DB. Requires SearXNG to be available. | SEARCH |
@@ -679,7 +679,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.skip_relevance_filter` | `LDR_SEARCH_SKIP_RELEVANCE_FILTER` | `true` | When checked, LLM-based relevance filtering is suppressed for general-purpose search engines that do not require it. Keyword-based engines (arXiv, PubMed, Wikipedia, GitHub, etc.) always run the filter regardless of this checkbox; per-engine settings override both. | SEARCH |
| `search.snippets_only` | `LDR_SEARCH_SNIPPETS_ONLY` | `true` | Only retrieve search snippets instead of full webpage content for pipeline/source-based search strategies (source-based, iterative, topic organization, etc.). Reduces API usage and processing time, but provides less context for analysis. Note: Autonomous agent strategies (like langgraph-agent) always return snippets from web_search and retrieve full webpage content on-demand via the fetch_content tool (governed by search.fetch.mode). | SEARCH |
| `search.time_period` | `LDR_SEARCH_TIME_PERIOD` | `all` | Time range filter for search results. Limits results to content published within the specified period (day, week, month, year, or all time). | SEARCH |
-| `search.tool` | `LDR_SEARCH_TOOL` | `searxng` | Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately. | SEARCH |
+| `search.tool` | `LDR_SEARCH_TOOL` | `searxng` | Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately. Wayback is available through fetch_archive for known URLs. If your saved engine is Wayback, choose a configured search provider for topic queries; saved values are not changed automatically. | SEARCH |
| `security.account_lockout_duration_minutes` | `LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES` | `15` | Duration in minutes that an account remains locked after exceeding the failed login threshold. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_DURATION_MINUTES). | APP |
| `security.account_lockout_threshold` | `LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD` | `10` | Number of consecutive failed login attempts before an account is temporarily locked out. Only configurable via environment variable (LDR_SECURITY_ACCOUNT_LOCKOUT_THRESHOLD). | APP |
| `security.rate_limit_default` | `LDR_SECURITY_RATE_LIMIT_DEFAULT` | `5000 per hour;50000 per day` | Default rate limit for all HTTP endpoints. Configured via LDR_SECURITY_RATE_LIMIT_DEFAULT environment variable. Multiple limits can be separated by semicolons (e.g., '5000 per hour;50000 per day'). Format: 'N per hour/minute/day'. Requires server restart. | APP |
diff --git a/docs/search-engines.md b/docs/search-engines.md
index 72abf12661..1e379fa807 100644
--- a/docs/search-engines.md
+++ b/docs/search-engines.md
@@ -15,7 +15,7 @@ LDR supports three categories of search engines:
### Dynamic Engine Selection (Recommended)
-The default `langgraph-agent` strategy selects the most appropriate engines dynamically per query: every enabled engine (and any registered retriever or local collection) is exposed to the research agent as a tool, and the agent decides which to call for each sub-question. You only pick a primary engine (`searxng` is the recommended default):
+The default `langgraph-agent` strategy selects the most appropriate engines dynamically per query: every enabled query-search engine (and any registered retriever or local collection) is exposed to the research agent as a tool, and the agent decides which to call for each sub-question. Wayback is available separately through `fetch_archive` for known URLs. You only pick a primary engine (`searxng` is the recommended default):
```python
result = quick_summary(
@@ -88,30 +88,110 @@ result = quick_summary(
- **Best for**: Searching your own indexed data
- **Configuration**: See [Elasticsearch Setup Guide](elasticsearch_search_engine.md)
-### Historical Search
+### Archive Fetching
#### Wayback Machine
- **Specialization**: Historical web content
- **Best for**: Finding deleted content, tracking changes over time
- **Results**: Archived web pages with timestamps
- **Rate Limit**: Moderate
-- **Input**: A query that contains full `http://` or `https://` URLs, or a
- query that is only a bare domain, such as `example.com`. For these, only
- the host is looked up; the port, path, query string and fragment are
- ignored. Not looked up: a domain inside a sentence, a domain with a path
- but without `http://` or `https://`, a URL with an uppercase scheme such
- as `HTTPS://`, a URL with a bracketed IPv6 host, and a bare domain with a
- punycode top-level domain such as `.xn--p1ai` (give it as a full
- `http://` or `https://` URL instead). A URL with a user name or password
- before the host is not supported: Wayback looks up the start of the user
- name instead of the host, so give the plain URL. A host name is read only
- as far as letters, digits, hyphens, underscores, dots and percent-escapes
- run, so one written with other characters, such as the combining marks of
- some scripts, is cut short (as a bare domain it is not recognised); use
- its `xn--` form in a full URL. For a topic query, first find page URLs
- with your configured search provider, such as SearXNG, then pass those
- URLs to Wayback, which looks up their hosts. Wayback does not send
- queries to another search provider.
+- **Input**: A page URL and an optional date in `YYYY-MM-DD` format
+- **Agent tool**: `fetch_archive`, available to the lead LangGraph research
+ agent and its subagents when archive fetching is enabled
+
+For a topic query, first find page URLs with your configured search provider,
+such as SearXNG, then fetch the historical version of a chosen URL:
+
+```python
+# Full mode, after the configured search provider finds this URL:
+fetch_archive("https://example.org/policy", date="2020-01-01")
+fetch_archive("https://example.org/policy") # Latest available capture
+
+# Summary modes require a focus question:
+fetch_archive("https://example.org/policy", date="2020-01-01",
+ focus="What did the policy require at that time?")
+```
+
+These are agent tool calls. A requested date selects the nearest available
+capture, which may fall before or after that date. The result preserves the
+original URL, archive URL, and actual capture timestamp in UTC; cite the actual
+capture date rather than the requested date. With the date omitted or `None`, the tool selects
+the latest available capture. An unarchived URL may have no capture.
+
+Archive fetch reads saved content statically and refuses redirects to live
+pages or outside the selected capture, keeping the returned metadata tied to
+the capture actually read.
+
+Enable or disable this tool with `search.engine.web.wayback.agent_enabled`
+(**Enable Archive Fetch** in Settings). It uses the same `search.fetch.mode`
+as `fetch_content`: `full` returns extracted text without a `focus` argument,
+`summary_focus` and `summary_focus_query` require `focus` and return focused
+summaries, and `disabled` removes both
+fetch tools. `search.fetch.content_max_length` also applies to archive text.
+For each lead agent or subagent, archive and live-page fetch calls share the
+`search.fetch.max_per_topic` budget for the topic. Archive requests still
+follow the configured egress policy.
+
+Wayback is excluded from the primary search picker and topic/auto search.
+Saved `search.tool=wayback` values are not rewritten: choose a configured search
+provider in Settings for topic queries. The research form selects an available
+provider when the saved choice is absent from its picker; check that selection
+before starting research. Existing Wayback settings remain available, and the legacy
+`WaybackSearchEngine` class and engine factory registration still support
+programmatic URL or domain lookups, optionally with a path. Its
+`search.engine.web.wayback.default_params.*` settings configure that legacy
+adapter; they do not control `fetch_archive`. Wayback does not discover URLs
+through another search provider.
+
+The legacy adapter looks up each `http://` or `https://` URL in its query,
+with the scheme in any case, or a query that is only a bare domain,
+optionally with a port, path, query string or fragment. It sends the
+complete URL, including its port, path, query string and fragment, to the
+Internet Archive and keeps it in its results. A comma or semicolon, ASCII
+or fullwidth, or an ideographic comma right before another URL separates
+the two, except in a query string, in a fragment, or in the path of a URL
+in straight quotes, parentheses, square or angle brackets, or backticks. A
+query that is only one URL, and a URL in straight quotes, angle brackets or
+backticks, keep their punctuation. Curly quotes and guillemets do not
+delimit a URL: it follows the running-text rules below, and a German
+closing quote stays part of it, as in `„https://example.com/a“`.
+Otherwise, in running text the adapter drops what ends a URL rather than
+belongs to it: sentence punctuation (ASCII, CJK or fullwidth, and an
+ellipsis), Markdown `*` emphasis, straight and curly closing quotes and
+closing guillemets, and a closing bracket without its opening partner in
+the URL, whether ASCII (`)`, `]` or `}`), fullwidth (such as `)`) or CJK
+(such as `】` or `」`). A balanced pair stays, as in
+`https://ja.wikipedia.org/wiki/【推しの子】` or
+`https://zh.wikipedia.org/wiki/苹果(水果)`. A URL right after `(` or `[`
+ends at its matching closer and drops only trailing commas and semicolons.
+
+Known limits: words that follow a URL without a space stay part of it, such
+as a possessive `'s`, CJK text, a parenthetical as in
+`https://example.com(see note)`, a second URL, or the label of a
+reference-style link as in `[text https://example.com/a][1]`; put a space
+after the URL. In running text, a URL that ends in `。`, `…`, `*` or `'`
+loses that character, as in `https://ja.wikipedia.org/wiki/君の名は。`, a
+query ending in `?a=*`, or a Wayback-style
+`https://web.archive.org/web/*/example.com/*`; give such a URL alone or in
+straight quotes, angle brackets or backticks. Bracket balance is counted over
+the whole URL, not by position, so a stray closer earlier in a URL makes a
+balanced pair at its end look unmatched: in running text
+`https://example.com/a)(b)` becomes `https://example.com/a)(b`. A URL right
+after `(` or `[` keeps a fullwidth or CJK closer at its end, as in
+`[https://example.com/a]`, because only the matching ASCII closer ends it
+there. A bare domain written with combining marks is not recognised; give
+it as a full URL.
+
+Like `fetch_archive`, the adapter skips a URL with a user name or password
+before its host, an invalid port or no host; a credential inside a query
+value is sent as written. It looks up at most `max_results` URLs per query.
+The configured egress policy allows or blocks the adapter as a whole;
+unlike `fetch_archive`, it does not also check each target URL against that
+policy.
+
+With Wayback saved as the primary engine, the LangGraph agent omits the
+generic `web_search` tool for Wayback; it can still use enabled archive
+fetching and other allowed configured tools.
### News Search
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 25f603a9e5..a4ca7d9920 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -99,19 +99,21 @@ This guide covers common issues and their solutions.
### Wayback Returning No Results
-Wayback looks up archived versions of the host of each `http://` or
-`https://` URL, or of a bare domain. It does not discover page URLs through
-another search provider. Search for the topic with your configured provider,
-such as SearXNG, and pass a resulting URL to Wayback, which looks up its
-host. An empty archive result can also mean that the archive has no capture
-of that host.
-
-Wayback also returns nothing for a URL with an uppercase scheme or a
-bracketed IPv6 host, and for a bare domain with a punycode top-level domain
-such as `.xn--p1ai`; give a punycode domain as a full `http://` or `https://`
-URL. A URL with a user name or password before the host is not supported:
-Wayback looks up the start of the user name instead of the host, so remove
-it.
+Wayback looks up archived versions of each `http://` or `https://` URL in a
+query, or of a query that is only a bare domain. It does not discover page
+URLs through another search provider. Search for the topic with your
+configured provider, such as SearXNG, and pass a resulting URL to Wayback.
+An empty archive result can also mean that the archive has no capture of
+that URL.
+
+Wayback looks up the complete URL, including its path, query string and
+fragment, so a URL with session or tracking parameters may have no capture;
+try it without them. In running text, Wayback drops most punctuation and
+quotes that end a URL, but words that follow a URL without a space, such as
+a possessive `'s`, text in a language written without spaces, or a
+parenthetical as in `https://example.com(see note)`, become part of it; put
+a space after the URL. Wayback skips a URL with a user name or password
+before its host, and it looks up at most `max_results` URLs per query.
### SearXNG Setup Issues
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 402b7a63e7..1aa16060f7 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -71,6 +71,7 @@ from ..tools.search_availability import (
run_search,
wait_for_cooldown,
)
+from ..tools.archive import build_archive_fetch_tool
from ..tools.fetch import (
DEFAULT_MAX_FETCHES_PER_TOPIC,
FETCH_MODES,
@@ -441,6 +442,9 @@ class SearchResultsCollector:
# whenever the report dropped or replaced that particular entry.
# Persists across ``reset()``, like the dedup maps above.
self._doc_fetched_title: dict[str, str] = {}
+ # Verified capture provenance belongs to the exact replay URL,
+ # including every excerpt and subsection citation for it.
+ self._archive_provenance: dict[str, dict] = {}
# Highest seeded citation index — used by ``add_results`` and
# ``find_or_add_result`` so newly-allocated indices never collide
# with sparse seeded indices.
@@ -497,6 +501,21 @@ class SearchResultsCollector:
except (ValueError, TypeError):
pass
self._max_idx = max_seeded_idx
+ for entry in self._all_links:
+ if (
+ isinstance(entry, dict)
+ and entry.get("source_type") == "archive"
+ ):
+ key = _citation_dedup_key(
+ entry.get("link") or entry.get("url") or ""
+ )
+ if key:
+ self._archive_provenance.setdefault(
+ key, self._archive_fields(entry)
+ )
+ for entry in self._all_links:
+ if isinstance(entry, dict):
+ self._apply_archive_provenance(entry)
# -- public API ----------------------------------------------------------
@@ -704,6 +723,7 @@ class SearchResultsCollector:
# is restored here. A later subsection re-citing a fetched
# document reuses its index but appends THIS fresh dict,
# which the earlier fetch could not have annotated.
+ self._apply_archive_provenance(r)
self._apply_doc_fetched_title(r)
self._results.append(r)
self._count_result_locked()
@@ -896,6 +916,30 @@ class SearchResultsCollector:
if _citation_dedup_key(link) == doc_key:
yield entry
+ @staticmethod
+ def _archive_fields(entry: dict) -> dict:
+ return {
+ field: entry[field]
+ for field in (
+ "source_type",
+ "original_url",
+ "requested_url",
+ "timestamp",
+ "formatted_date",
+ )
+ if field in entry
+ }
+
+ def _apply_archive_provenance(self, entry: dict) -> None:
+ key = _citation_dedup_key(entry.get("link") or entry.get("url") or "")
+ provenance = self._archive_provenance.get(key)
+ if provenance:
+ if entry.get("source_type") == "archive":
+ for field, value in provenance.items():
+ entry.setdefault(field, value)
+ else:
+ entry.update(provenance)
+
def _apply_doc_fetched_title(self, entry: dict) -> None:
"""Stamp the recorded page title onto one entry for that document.
@@ -960,7 +1004,16 @@ class SearchResultsCollector:
# LRU-cached.
key = _citation_dedup_key(url)
snippet_key = _snippet_dedup_key(result)
+ incoming_archive = result.get("source_type") == "archive"
with self._lock:
+ if key and result.get("source_type") == "archive":
+ self._archive_provenance.setdefault(key, {}).update(
+ self._archive_fields(result)
+ )
+ for entry in self._entries_for_doc(key):
+ self._apply_archive_provenance(entry)
+ result = dict(result)
+ self._apply_archive_provenance(result)
# Record the source before branching: all three paths below end
# with *url* tracked (reused via either dedup path, or freshly
# registered), and ``_sources`` is per-subsection state that
@@ -1069,6 +1122,18 @@ class SearchResultsCollector:
reused_key = idx_str
break
+ if reused is not None and result.get("source_type") == "archive":
+ tracked = self._index_to_result.get(reused_key or str(reused))
+ if tracked is not None:
+ for field, value in self._archive_fields(result).items():
+ if incoming_archive:
+ # The latest successful read records the URL
+ # requested for this exact capture and excerpt.
+ tracked[field] = value
+ else:
+ tracked.setdefault(field, value)
+ if incoming_archive and result.get("title"):
+ tracked["title"] = result["title"]
if reused is not None:
# The fetch path reuses an index just as ``add_results``
# does, so it must upgrade the stored spelling too or the
@@ -1092,6 +1157,22 @@ class SearchResultsCollector:
# repeated fetch inside one subsection still does not
# grow ``_results``.
echoed = dict(result)
+ tracked = self._index_to_result.get(
+ reused_key or str(reused)
+ )
+ if tracked and tracked.get("source_type") == "archive":
+ for field in (
+ "source_type",
+ "original_url",
+ "requested_url",
+ "timestamp",
+ "formatted_date",
+ ):
+ if field in tracked:
+ echoed[field] = tracked[field]
+ echoed["title"] = tracked.get(
+ "title", echoed.get("title")
+ )
# The reuse branch builds its own copy, so it needs
# the same producer-key strip as the allocate branch.
echoed.pop(CHUNK_DISPLAY_KEY, None)
@@ -1164,6 +1245,22 @@ class SearchResultsCollector:
self._apply_doc_fetched_title(tracked)
return index
+ def find_archive_by_url(self, url: str) -> dict | None:
+ """Find persistent capture provenance across this URL's excerpts.
+
+ A search hit can own the first index while a successful archive
+ fetch owns a later one. Keep both excerpts, but let any reread of
+ the replay URL use the verified capture's transport boundary.
+ """
+ key = _citation_dedup_key(url)
+ if not key:
+ return None
+ with self._lock:
+ for entry in self._entries_for_doc(key):
+ if entry.get("source_type") == "archive":
+ return dict(entry)
+ return None
+
def find_by_url(self, url: str) -> int | None:
"""Return the 1-based citation index if *url* is already tracked, else ``None``.
@@ -1363,6 +1460,7 @@ _TOOL_DISPLAY_NAMES = {
"search_nasa_ads": "NASA ADS",
"search_local": "your library",
"fetch_content": "the page",
+ "fetch_archive": "the archived page",
"research_subtopic": "subtopic researcher",
}
@@ -1373,6 +1471,7 @@ _TOOL_DISPLAY_NAMES = {
# every other tool falls through to ``_display_tool_name``.
_HEARTBEAT_TOOL_LABELS = {
"fetch_content": "page fetching",
+ "fetch_archive": "archive fetching",
"research_subtopic": "subtopic research",
}
@@ -1441,17 +1540,17 @@ def _format_results(results: list[dict], start_idx: int) -> str:
# ``_make_fetch_progress_adapter`` for backwards compatibility with
# existing tests.
-# Appended to both Wayback tool descriptions. The engine looks up the host
-# of each lowercase http(s) URL in its input, or an input that is only a bare
-# domain; it does not discover URLs or pick a domain out of a sentence. The
-# "Not supported" sentence names the inputs its patterns miss or misread.
+# Appended to both Wayback tool descriptions. The engine looks up each
+# complete http(s) URL in its input, or an input that is only a bare domain;
+# it does not discover URLs or pick a domain out of a sentence. It drops
+# punctuation that ends a URL, but not words that follow it without a space.
_WAYBACK_INPUT_HINT = (
" Input must contain a full http:// or https:// URL, or be only a bare"
- " domain such as example.com. Only the host is looked up, so a URL's"
- " port, path, query and fragment are ignored. Not supported: an"
- " uppercase scheme, a bracketed IPv6 host, a user name or password"
- " before the host, and a bare domain with a punycode (xn--) top-level"
- " domain. Use a configured search provider to discover URLs before"
+ " domain such as example.com, optionally with a port, path or query."
+ " The complete URL, including its port, path, query and fragment, is"
+ " looked up; words that follow a URL without a space, such as 's, become"
+ " part of it. A URL with a user name or password before its host is not"
+ " looked up. Use a configured search provider to discover URLs before"
" looking up their archives."
)
@@ -1664,7 +1763,11 @@ def _load_specialized_engine_tools(
for name, config in eligible.items():
try:
- if name == skip_engine:
+ if (
+ name == skip_engine
+ or name == "wayback"
+ or config.get("supports_query_search") is False
+ ):
continue
# Per-engine usability switch (independent of egress). Collection
@@ -1891,9 +1994,11 @@ def _make_research_subtopic_tool(
# is safe. ``research_subtopic`` is itself excluded so subagents
# cannot recurse. All tools share the single research-scoped
# content cache so subagents serve pages/chunks the lead agent (or
- # a sibling subagent, or the quick phase) already fetched.
+ # a sibling subagent, or the quick phase) already fetched; archive
+ # reads (fetch_archive, or fetch_content on a capture URL or its
+ # citation) never read or store page content there.
sub_tools: list = []
- if search_enabled:
+ if search_enabled and search_engine_name != "wayback":
sub_tools.append(
_make_web_search_tool(
search_engine_name,
@@ -1918,9 +2023,23 @@ def _make_research_subtopic_tool(
max_fetches=max_fetches_per_topic,
subagent_id="subagent",
content_cache=content_cache,
+ availability=availability,
)
if sub_fetch is not None:
sub_tools.append(sub_fetch)
+ sub_archive = build_archive_fetch_tool(
+ fetch_mode,
+ collector,
+ model=model,
+ overall_query=overall_query,
+ settings_snapshot=settings_snapshot,
+ egress_context=egress_context,
+ max_fetches=max_fetches_per_topic,
+ subagent_id="subagent",
+ availability=availability,
+ )
+ if sub_archive is not None:
+ sub_tools.append(sub_archive)
# Give subagents the same specialized-engine set the lead agent
# gets, filtered by the same egress policy / agent_enabled gate via
# the shared helper — without this, a subagent researching a
@@ -2025,6 +2144,12 @@ def _make_research_subtopic_tool(
"Reference sources by their [N] index numbers. "
"Do NOT ask clarifying questions — provide your findings directly."
)
+ if any(t.name == "fetch_archive" for t in sub_tools):
+ subagent_prompt += (
+ " Use fetch_archive for supplied or discovered URLs when historical "
+ "evidence is needed. Its optional date selects the nearest capture; "
+ "cite the archive URL and actual capture date."
+ )
specialized_names = [
t.name
for t in sub_tools
@@ -2756,7 +2881,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# `fetch_content` carries a URL arg; the search tools carry a query
# arg. Either way, show the meaningful arg in quotes so the user
# sees what the agent is actually looking up.
- if raw_name == "fetch_content":
+ if raw_name in {"fetch_content", "fetch_archive"}:
target = _truncate_arg(str(tc_args.get("url", "")))
return f'📖 Reading {display_name}: "{target}"'
if raw_name == "research_subtopic":
@@ -2824,7 +2949,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# still surfaces normally — the suppression is about the
# ``fetch_content`` denial framing, not a generic string-substring
# match.
- if tool_name == "fetch_content" and (
+ if tool_name in {"fetch_content", "fetch_archive"} and (
raw.startswith("Cannot fetch ")
or raw.startswith("Error fetching ")
or raw.startswith("Fetch content budget exhausted")
@@ -3022,7 +3147,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
primary_search_description = NEUTRAL_PRIMARY_SEARCH_DESCRIPTION
# Web search (always present if we have a search engine)
- if self.search is not None:
+ if self.search is not None and self._search_engine_name != "wayback":
try:
from ...web_search_engines.search_engines_config import (
search_config,
@@ -3133,9 +3258,23 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
max_fetches=self.max_fetches_per_topic,
subagent_id="lead",
content_cache=self.get_content_cache(),
+ availability=self.engine_availability,
)
if fetch is not None:
tools.append(fetch)
+ archive_fetch = build_archive_fetch_tool(
+ self.fetch_mode,
+ self.collector,
+ model=self.model,
+ overall_query=overall_query,
+ settings_snapshot=self.settings_snapshot,
+ egress_context=policy_ctx,
+ max_fetches=self.max_fetches_per_topic,
+ subagent_id="lead",
+ availability=self.engine_availability,
+ )
+ if archive_fetch is not None:
+ tools.append(archive_fetch)
# Specialized search engines (pre-filtered by egress policy).
#
@@ -3241,6 +3380,13 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
else: # full
fetch_line = "3. Use fetch_content to read full pages when snippets aren't enough.\n"
+ if "fetch_archive" in self._tool_names:
+ fetch_line += (
+ "For historical versions, use fetch_archive with a URL and an optional "
+ "YYYY-MM-DD date; supply focus in summary mode. Find URLs using the "
+ "configured search tools first. Cite the archive link and actual capture date, "
+ "which may differ from the requested date.\n"
+ )
# Build the policy addendum once so the system prompt can carry
# explicit guidance to the LLM about which tools actually exist.
# Closing the timing-leak attack requires both halves: the tool
@@ -3263,6 +3409,17 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
"this session and will not work. Use web_search and "
"research_subtopic for everything.\n"
)
+ if self._search_engine_name == "wayback":
+ archive_instruction = (
+ "Use fetch_archive only for supplied URLs. "
+ if "fetch_archive" in self._tool_names
+ else "Archive fetching is unavailable in this session. "
+ )
+ policy_addendum = (
+ "\nRESTRICTED MODE: Wayback is an archive fetch tool. "
+ + archive_instruction
+ + "Topic discovery requires selecting a configured search provider.\n"
+ )
elif ctx is not None and ctx.scope == EgressScope.PRIVATE_ONLY:
policy_addendum = (
"\nPRIVATE-ONLY MODE: public search engines (arxiv, "
diff --git a/src/local_deep_research/advanced_search_system/tools/archive.py b/src/local_deep_research/advanced_search_system/tools/archive.py
new file mode 100644
index 0000000000..54afc530f5
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/tools/archive.py
@@ -0,0 +1,184 @@
+"""Fetch a historical URL through the existing page-fetch pipeline."""
+
+from typing import Any
+
+from langchain_core.tools import tool
+from loguru import logger
+
+from ...security import redact_url_for_log, sanitize_error_for_agent
+from ...security.egress.policy import PolicyDeniedError, evaluate_engine
+from ...utilities.type_utils import resolve_boolean_setting
+from ...web_search_engines.engine_availability import failure_from_exception
+from ...web_search_engines.wayback_client import (
+ AVAILABLE_API,
+ lookup_archive_snapshot,
+ normalize_archive_date,
+ validate_capture_fetch_url,
+ validate_archive_url,
+)
+from .fetch import (
+ FETCH_MODES,
+ _check_and_record_fetch,
+ _enforce_url_policy,
+ _read_max_fetches_setting,
+ build_fetch_tool,
+)
+
+
+def _enforce_archive_engine(egress_context, settings_snapshot):
+ if egress_context is not None:
+ decision = evaluate_engine(
+ "wayback", egress_context, settings_snapshot=settings_snapshot or {}
+ )
+ if not decision.allowed:
+ raise PolicyDeniedError(decision, target=AVAILABLE_API)
+
+
+def build_archive_fetch_tool(
+ mode: str,
+ collector: Any,
+ *,
+ model=None,
+ overall_query: str = "",
+ settings_snapshot: dict | None = None,
+ egress_context=None,
+ max_fetches: int | None = None,
+ subagent_id: str | None = None,
+ availability=None,
+):
+ """Build fetch_archive, following the run's fetch mode and shared quota."""
+ if mode not in FETCH_MODES:
+ raise ValueError(f"Unknown fetch mode {mode!r}")
+ if mode == "disabled":
+ return None
+ if not resolve_boolean_setting(
+ settings_snapshot, "search.engine.web.wayback.agent_enabled", True
+ ):
+ return None
+ if (
+ egress_context is not None
+ and not evaluate_engine(
+ "wayback", egress_context, settings_snapshot=settings_snapshot or {}
+ ).allowed
+ ):
+ return None
+ if mode != "full" and model is None:
+ raise ValueError(f"{mode} fetch mode requires a model")
+ limit = (
+ max_fetches
+ if max_fetches is not None
+ else _read_max_fetches_setting(settings_snapshot)
+ )
+ description = (
+ "Read an archived version of one absolute HTTP(S) URL. Discover URLs "
+ "with a configured search provider first, or use a URL supplied by the user. "
+ "Optionally pass date as YYYY-MM-DD to select the closest available capture; "
+ "omit date for the most recent available capture. The actual capture date "
+ "can differ from the requested date. Never substitutes the live page. "
+ "Shares the fetch_content budget and fetch mode."
+ )
+ if mode != "full":
+ description += " Pass focus as the specific question to extract from the archived page."
+
+ def fetch(url: str, date: str | None, focus: str | None = None) -> str:
+ try:
+ url = validate_archive_url(url)
+ timestamp = normalize_archive_date(date)
+ if availability is not None:
+ state = availability.state("wayback")
+ if state is not None:
+ return state.describe()
+ _enforce_archive_engine(egress_context, settings_snapshot)
+ # Check the target before sending it to an external archive, and
+ # gate the API before reserving the shared quota slot.
+ _enforce_url_policy(url, egress_context)
+ _enforce_url_policy(AVAILABLE_API, egress_context)
+ error, count = _check_and_record_fetch(
+ collector, limit, subagent_id=subagent_id
+ )
+ if error is not None:
+ return error
+ snapshot = lookup_archive_snapshot(url, timestamp)
+ if snapshot is None:
+ if availability is not None:
+ availability.record_success("wayback")
+ return f"No accessible archive capture was found for {url}. Try another date or URL."
+ replay = snapshot["url"]
+ embedded_target = replay.split(f"/web/{snapshot['timestamp']}/", 1)[
+ 1
+ ]
+ _enforce_url_policy(embedded_target, egress_context)
+ _enforce_url_policy(replay, egress_context)
+ metadata = {
+ "source_type": "archive",
+ "original_url": snapshot["original_url"],
+ "requested_url": snapshot["requested_url"],
+ "timestamp": snapshot["timestamp"],
+ "formatted_date": snapshot["formatted_date"],
+ }
+
+ def capture_guard(candidate):
+ validate_capture_fetch_url(
+ candidate, snapshot["timestamp"], snapshot["original_url"]
+ )
+
+ page_fetch = build_fetch_tool(
+ mode,
+ collector,
+ model=model,
+ overall_query=overall_query,
+ settings_snapshot=settings_snapshot,
+ egress_context=egress_context,
+ max_fetches=limit,
+ subagent_id=subagent_id,
+ record_fetch=False,
+ source_metadata=metadata,
+ url_guard=capture_guard,
+ availability=availability,
+ )
+ arguments: dict[str, Any] = {"url": replay}
+ if mode != "full":
+ arguments["focus"] = focus
+ message = page_fetch.invoke(arguments)
+ # Shared fetching displays provenance on successful reads,
+ # including ordinary rereads of the resulting citation.
+ if date is not None:
+ message += (
+ f"\nRequested date: {date} (closest available capture)"
+ )
+ if limit > 0 and count is not None:
+ message += f"\n\n({count} of {limit} page fetches used)"
+ return message
+ except PolicyDeniedError as exc:
+ return sanitize_error_for_agent(
+ f"Cannot fetch archive: blocked by egress policy ({exc.decision.reason}). "
+ "Use an allowed source or choose an appropriate search provider."
+ )
+ except Exception as exc:
+ logger.opt(exception=False).warning(
+ "Archive fetch failed for {} ({})",
+ redact_url_for_log(url),
+ type(exc).__name__,
+ )
+ failure = failure_from_exception(exc)
+ if availability is not None and failure is not None:
+ return availability.disable("wayback", failure).describe()
+ return sanitize_error_for_agent(f"Cannot fetch archive: {exc}")
+
+ if mode == "full":
+
+ @tool("fetch_archive", description=description)
+ def fetch_archive(url: str, date: str | None = None) -> str:
+ """Read the archived page at URL, optionally near a calendar date."""
+ return fetch(url, date)
+
+ return fetch_archive
+
+ @tool("fetch_archive", description=description)
+ def fetch_archive_summary(
+ url: str, focus: str, date: str | None = None
+ ) -> str:
+ """Extract facts relevant to focus from an archived page."""
+ return fetch(url, date, focus)
+
+ return fetch_archive_summary
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index b90a2011ed..357cd39210 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -254,6 +254,7 @@ def _register_in_collector(
url: str,
title: str,
snippet_source: str,
+ source_metadata: dict | None = None,
) -> int:
"""Register a fetched URL in the collector and return its 1-based citation index.
@@ -277,14 +278,20 @@ def _register_in_collector(
any repo we can see, which is precisely what the paragraph above
forbids. That growth was reverted rather than shipped.
"""
+ metadata = _complete_archive_metadata(url, source_metadata) or {}
+ source_engine = (
+ "wayback" if metadata.get("source_type") == "archive" else "fetch"
+ )
+ if metadata.get("source_type") == "archive":
+ title = f"{title or metadata['original_url']} (archived {metadata['formatted_date']})"
snippet = snippet_source[:200].strip()
if len(snippet_source) > 200:
snippet += "..."
if not hasattr(collector, "find_or_add_result"):
# Legacy/custom collectors without find_or_add_result fallback
_, indexed = collector.add_results(
- [{"title": title, "link": url, "snippet": snippet}],
- engine_name="fetch",
+ [{**metadata, "title": title, "link": url, "snippet": snippet}],
+ engine_name=source_engine,
)
if indexed:
raw_idx = indexed[0].get("index")
@@ -304,11 +311,24 @@ def _register_in_collector(
)
return collector.find_or_add_result(
- {"title": title, "link": url, "snippet": snippet},
- engine_name="fetch",
+ {**metadata, "title": title, "link": url, "snippet": snippet},
+ engine_name=source_engine,
)
+def _format_fetch_message(cite_idx, title, url, content, source_metadata):
+ message = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"
+ if source_metadata and source_metadata.get("source_type") == "archive":
+ message += (
+ f"\n\nOriginal URL: {source_metadata['original_url']}"
+ f"\nCaptured: {source_metadata['formatted_date']}"
+ )
+ requested = source_metadata.get("requested_url")
+ if requested and requested != source_metadata["original_url"]:
+ message += f"\nRequested URL: {requested}"
+ return message
+
+
def _enforce_url_policy(url: str, egress_context: Any) -> None:
"""Run ``evaluate_url`` against ``egress_context`` and raise
``PolicyDeniedError`` on denial.
@@ -554,6 +574,137 @@ def _try_resolve_url(
return None
+def _complete_archive_metadata(url: str, metadata: dict | None) -> dict | None:
+ """Recover missing provenance from a verified capture before using it."""
+ if metadata is None or metadata.get("source_type") != "archive":
+ return metadata
+ from local_deep_research.web_search_engines.wayback_client import (
+ capture_metadata_from_replay_url,
+ validate_capture_fetch_url,
+ )
+
+ captured = capture_metadata_from_replay_url(url)
+ if captured is None:
+ raise ValueError("Archive provenance requires an exact replay URL")
+ # Missing metadata is recoverable, but supplied constraints must not
+ # be replaced silently when they disagree with the actual capture.
+ timestamp = metadata.get("timestamp")
+ original_url = metadata.get("original_url")
+ if timestamp is None or timestamp == "":
+ timestamp = captured["timestamp"]
+ if original_url is None or original_url == "":
+ original_url = captured["original_url"]
+ if not isinstance(timestamp, str) or not isinstance(original_url, str):
+ raise ValueError("Invalid archive provenance")
+ validate_capture_fetch_url(url, timestamp, original_url)
+ return {
+ **metadata,
+ **captured,
+ "requested_url": metadata.get("requested_url")
+ or captured["requested_url"],
+ }
+
+
+def _archive_fetch_context(
+ url: str,
+ collector: Any,
+ source_metadata: dict | None,
+ url_guard: Any,
+) -> tuple[dict | None, Any]:
+ """Retain a tracked capture's provenance when fetching it again.
+
+ Resolve both citation chains and literal replay links using the
+ collector's persistent index, including after a subsection reset.
+ The resulting guard stays local to this call.
+ """
+ metadata = source_metadata
+ if is_citation_reference(url) is not None:
+ # Use the HTTP path's cycle/depth checks to reach the final target.
+ # Leave local document reads to that path's actual library resolver.
+ resolved = _try_resolve_url(url, None, collector)
+ if resolved is None or resolved[0] != _KIND_REWRITTEN:
+ return metadata, url_guard
+ url = resolved[1]
+ tracked = None
+ if metadata is None and collector is not None:
+ find_url = getattr(collector, "find_by_url", None)
+ find_index = getattr(collector, "find_by_index", None)
+ if callable(find_url) and callable(find_index):
+ index = find_url(url)
+ if isinstance(index, int):
+ tracked = find_index(index)
+ if (
+ not isinstance(tracked, dict)
+ or tracked.get("source_type") != "archive"
+ ):
+ replay = (
+ tracked.get("link") or tracked.get("url")
+ if isinstance(tracked, dict)
+ else url
+ )
+ find_archive = getattr(collector, "find_archive_by_url", None)
+ if isinstance(replay, str) and callable(find_archive):
+ archived = find_archive(replay)
+ if isinstance(archived, dict):
+ tracked = archived
+ if (
+ isinstance(tracked, dict)
+ and tracked.get("source_type") == "archive"
+ ):
+ metadata = {
+ field: tracked[field]
+ for field in (
+ "source_type",
+ "original_url",
+ "requested_url",
+ "timestamp",
+ "formatted_date",
+ )
+ if field in tracked
+ }
+ from local_deep_research.web_search_engines.wayback_client import (
+ capture_metadata_from_replay_url,
+ validate_capture_fetch_url,
+ )
+
+ candidate = (
+ tracked.get("link") or tracked.get("url")
+ if collector is not None and isinstance(tracked, dict)
+ else url
+ )
+ if metadata is None:
+ if isinstance(candidate, str):
+ metadata = capture_metadata_from_replay_url(candidate)
+ if metadata is None or metadata.get("source_type") != "archive":
+ return metadata, url_guard
+ metadata = _complete_archive_metadata(candidate, metadata)
+
+ def capture_guard(candidate):
+ validate_capture_fetch_url(
+ candidate, metadata["timestamp"], metadata["original_url"]
+ )
+ if url_guard is not None:
+ url_guard(candidate)
+
+ return metadata, capture_guard
+
+
+def _archive_failure_message(exc, availability, source_metadata):
+ """Classify archive outages without disabling a live fetch provider."""
+ if availability is None or not source_metadata:
+ return None
+ if source_metadata.get("source_type") != "archive":
+ return None
+ from local_deep_research.web_search_engines.engine_availability import (
+ failure_from_exception,
+ )
+
+ failure = failure_from_exception(exc)
+ if failure is not None:
+ return availability.disable("wayback", failure).describe()
+ return None
+
+
def _fetch_raw_content(
url: str,
library_resolver: Any,
@@ -565,6 +716,9 @@ def _fetch_raw_content(
subagent_id: str | None = None,
content_cache: Any = None,
content_max_length: int | None = None,
+ url_guard: Any = None,
+ availability: Any = None,
+ source_metadata: dict | None = None,
) -> tuple[dict | None, str, str | None, int | None]:
"""Pre-resolve non-network URL shapes or fetch via HTTP.
@@ -573,7 +727,8 @@ def _fetch_raw_content(
cache bound to the current research (if any) is used via
``ContentFetcher``'s own registry fallback. Repeat URLs are therefore
served from previously fetched content instead of hitting the network
- on the spot.
+ on the spot. A guarded archive read (``url_guard`` set) never reads or
+ stores cached page content.
Returns:
(result, final_url, error_string, current_count)
@@ -590,6 +745,12 @@ def _fetch_raw_content(
_cache = resolve_cache(content_cache)
except Exception: # pragma: no cover - defensive
_cache = None
+ if url_guard is not None:
+ # A guarded (archive) read neither reads nor stores cached page
+ # content, here or in ContentFetcher: an entry under the same replay
+ # URL can come from an unguarded fetch whose redirects left the
+ # capture.
+ _cache = None
effective_max_length = (
content_max_length
@@ -629,6 +790,34 @@ def _fetch_raw_content(
# PolicyDeniedError on an out-of-scope URL.
# Check the egress gate BEFORE recording the fetch so that
# egress denials do not consume budget slots.
+ if source_metadata and source_metadata.get("source_type") == "archive":
+ if availability is not None:
+ state = availability.state("wayback")
+ if state is not None:
+ return None, url, state.describe(), None
+ if max_fetches is not None:
+ # An ordinary reread reserves its slot here. The archive
+ # wrapper has already checked these gates before lookup.
+ from local_deep_research.security.egress.policy import (
+ PolicyDeniedError,
+ evaluate_engine,
+ )
+ from local_deep_research.web_search_engines.wayback_client import (
+ AVAILABLE_API,
+ )
+
+ if egress_context is not None:
+ decision = evaluate_engine(
+ "wayback",
+ egress_context,
+ settings_snapshot=settings_snapshot or {},
+ )
+ if not decision.allowed:
+ raise PolicyDeniedError(decision, target=AVAILABLE_API)
+ _enforce_url_policy(
+ source_metadata["original_url"], egress_context
+ )
+ url_guard(url)
_enforce_url_policy(url, egress_context)
# Egress check passed! Only count fetches that reach the network.
@@ -653,13 +842,24 @@ def _fetch_raw_content(
_hit = None
enable_js = _read_js_rendering_setting(settings_snapshot)
- with ContentFetcher(
- timeout=CONTENT_FETCH_TIMEOUT,
- enable_js_rendering=enable_js,
- egress_context=egress_context,
- content_cache=_cache,
- ) as fetcher:
+ fetcher_options = {
+ "timeout": CONTENT_FETCH_TIMEOUT,
+ "enable_js_rendering": enable_js,
+ "egress_context": egress_context,
+ "content_cache": _cache,
+ }
+ if url_guard is not None:
+ fetcher_options["url_guard"] = url_guard
+ with ContentFetcher(**fetcher_options) as fetcher:
result = fetcher.fetch(url, max_length=effective_max_length)
+ if (
+ source_metadata
+ and source_metadata.get("source_type") == "archive"
+ and availability is not None
+ and result.get("status") == "success"
+ and (result.get("content") or "").strip()
+ ):
+ availability.record_success("wayback")
if (
_hit is not None
@@ -714,6 +914,10 @@ def _make_full_fetch_tool(
subagent_id: str | None = None,
content_cache: Any = None,
content_max_length: int | None = None,
+ record_fetch: bool = True,
+ source_metadata: dict | None = None,
+ url_guard: Any = None,
+ availability: Any = None,
):
mode_label = "full"
limit = (
@@ -735,7 +939,11 @@ def _make_full_fetch_tool(
PolicyDeniedError,
)
+ archive_metadata = source_metadata
try:
+ archive_metadata, archive_guard = _archive_fetch_context(
+ url, collector, source_metadata, url_guard
+ )
result, url, err_msg, current_count = _fetch_raw_content(
url,
library_resolver,
@@ -743,10 +951,13 @@ def _make_full_fetch_tool(
egress_context,
settings_snapshot,
mode_label,
- max_fetches=limit,
+ max_fetches=limit if record_fetch else None,
subagent_id=subagent_id,
content_cache=content_cache,
content_max_length=content_max_length,
+ url_guard=archive_guard,
+ source_metadata=archive_metadata,
+ availability=availability,
)
if err_msg is not None:
return err_msg
@@ -754,10 +965,14 @@ def _make_full_fetch_tool(
if result.get("status") == "success":
title = result.get("title", "")
content = result.get("content", "")
+ if archive_metadata is not None and not (content or "").strip():
+ return f"NOT RELEVANT (no extractable content at {url})"
cite_idx = _register_in_collector(
- collector, url, title, content
+ collector, url, title, content, archive_metadata
+ )
+ msg = _format_fetch_message(
+ cite_idx, title, url, content, archive_metadata
)
- msg = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"
if limit > 0 and current_count is not None:
msg += f"\n\n({current_count} of {limit} page fetches used)"
return msg
@@ -781,6 +996,11 @@ def _make_full_fetch_tool(
f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}"
)
except Exception as exc:
+ archive_failure = _archive_failure_message(
+ exc, availability, archive_metadata
+ )
+ if archive_failure is not None:
+ return archive_failure
# logger.opt(exception=False).error — explicit no-traceback form
# that satisfies both custom-checks (no bare logger.error in an
# except block) and the security contract (no logger.exception
@@ -810,6 +1030,10 @@ def _make_summary_fetch_tool(
subagent_id: str | None = None,
content_cache: Any = None,
content_max_length: int | None = None,
+ record_fetch: bool = True,
+ source_metadata: dict | None = None,
+ url_guard: Any = None,
+ availability: Any = None,
):
"""Build the summary-mode fetch tool.
@@ -843,7 +1067,11 @@ def _make_summary_fetch_tool(
PolicyDeniedError,
)
+ archive_metadata = source_metadata
try:
+ archive_metadata, archive_guard = _archive_fetch_context(
+ url, collector, source_metadata, url_guard
+ )
result, url, err_msg, current_count = _fetch_raw_content(
url,
library_resolver,
@@ -851,10 +1079,13 @@ def _make_summary_fetch_tool(
egress_context,
settings_snapshot,
mode_label,
- max_fetches=limit,
+ max_fetches=limit if record_fetch else None,
subagent_id=subagent_id,
content_cache=content_cache,
content_max_length=content_max_length,
+ url_guard=archive_guard,
+ source_metadata=archive_metadata,
+ availability=availability,
)
if err_msg is not None:
return err_msg
@@ -938,8 +1169,12 @@ def _make_summary_fetch_tool(
f"page_chars={len(content)} summary_chars={len(summary)}"
)
- cite_idx = _register_in_collector(collector, url, title, summary)
- msg = f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"
+ cite_idx = _register_in_collector(
+ collector, url, title, summary, archive_metadata
+ )
+ msg = _format_fetch_message(
+ cite_idx, title, url, summary, archive_metadata
+ )
if limit > 0 and current_count is not None:
msg += f"\n\n({current_count} of {limit} page fetches used)"
return msg
@@ -954,6 +1189,11 @@ def _make_summary_fetch_tool(
f"({_denial_reason(exc)}). {_EGRESS_DENIAL_HINT}"
)
except Exception as exc:
+ archive_failure = _archive_failure_message(
+ exc, availability, archive_metadata
+ )
+ if archive_failure is not None:
+ return archive_failure
# logger.opt(exception=False).error — explicit no-traceback form
# that satisfies both custom-checks (no bare logger.error in an
# except block) and the security contract (no logger.exception
@@ -985,9 +1225,17 @@ def build_fetch_tool(
subagent_id: str | None = None,
content_cache: Any = None,
content_max_length: int | None = None,
+ record_fetch: bool = True,
+ source_metadata: dict | None = None,
+ url_guard: Any = None,
+ availability: Any = None,
):
"""Build the agent-facing ``fetch_content`` tool for *mode*.
+ ``record_fetch=False`` is used by the archive wrapper after it reserves
+ the shared fetch slot before archive lookup. ``source_metadata`` carries
+ that capture's provenance into the citation collector.
+
Returns ``None`` when ``mode == 'disabled'``; the caller should not
register the tool with the agent in that case (and the system prompt
should also drop the corresponding instruction line so the agent
@@ -1026,6 +1274,10 @@ def build_fetch_tool(
subagent_id=subagent_id,
content_cache=content_cache,
content_max_length=content_max_length,
+ record_fetch=record_fetch,
+ source_metadata=source_metadata,
+ url_guard=url_guard,
+ availability=availability,
)
if mode == "summary_focus":
if model is None:
@@ -1041,6 +1293,10 @@ def build_fetch_tool(
subagent_id=subagent_id,
content_cache=content_cache,
content_max_length=content_max_length,
+ record_fetch=record_fetch,
+ source_metadata=source_metadata,
+ url_guard=url_guard,
+ availability=availability,
)
if mode == "summary_focus_query":
if model is None:
@@ -1058,6 +1314,10 @@ def build_fetch_tool(
subagent_id=subagent_id,
content_cache=content_cache,
content_max_length=content_max_length,
+ record_fetch=record_fetch,
+ source_metadata=source_metadata,
+ url_guard=url_guard,
+ availability=availability,
)
raise ValueError(
f"Unknown fetch mode {mode!r}; expected one of {FETCH_MODES}"
diff --git a/src/local_deep_research/advanced_search_system/tools/search_availability.py b/src/local_deep_research/advanced_search_system/tools/search_availability.py
index c1783b7a1f..4ad083853e 100644
--- a/src/local_deep_research/advanced_search_system/tools/search_availability.py
+++ b/src/local_deep_research/advanced_search_system/tools/search_availability.py
@@ -22,6 +22,7 @@ from ...web_search_engines.engine_availability import (
failure_from_exception,
http_status,
is_query_error,
+ search_engines_for_tools,
)
@@ -30,7 +31,7 @@ class NoResearchToolsAvailable(RuntimeError):
Raised instead of calling the model with an empty tool list: several
providers reject a request that carries tool-call history but defines
- no tools. This covers only an empty list: if ``fetch_content`` survives
+ no tools. This covers only an empty list: if a fetch tool survives
while every search engine is disabled, the model keeps it, since it can
still read URLs from the query or from earlier results. It can then also
answer without searching; the prompt tells it to say when evidence is
@@ -232,16 +233,24 @@ class SearchAvailabilityMiddleware(AgentMiddleware):
relevant = {
engine_for_tool(name, self.primary_engine) for name in names
} - {None}
+ # Archive fetching tracks provider health but cannot replace URL
+ # discovery. Preserve search recovery even when it remains available.
disabled = self.availability.disabled()
+ waiting_engines = search_engines_for_tools(names, self.primary_engine)
+ if self.availability.seconds_until_retry(waiting_engines) is None:
+ # Discovery may be permanently unavailable while a known URL's
+ # archive can recover. Keep its bounded cooldown wait as well.
+ waiting_engines = relevant
if (
- relevant
- and relevant <= disabled.keys()
- and self.availability.seconds_until_retry(relevant) is not None
+ waiting_engines
+ and waiting_engines <= disabled.keys()
+ and self.availability.seconds_until_retry(waiting_engines)
+ is not None
):
- # Nothing can search right now, but something will again: a
+ # Nothing can use these providers now, but something will again: a
# transient failure must not end the run or leave the model
# answering from memory. Wait instead of filtering.
- self.wait(relevant)
+ self.wait(waiting_engines)
disabled = self.availability.disabled()
available = available_tool_names(names, self.primary_engine, disabled)
tools = [t for t in request.tools if t.name in available]
diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.py
index 597414974f..4b8d508e90 100644
--- a/src/local_deep_research/content_fetcher/fetcher.py
+++ b/src/local_deep_research/content_fetcher/fetcher.py
@@ -55,6 +55,7 @@ class ContentFetcher:
enable_js_rendering: bool = False,
egress_context: Any = None,
content_cache: Any = None,
+ url_guard: Any = None,
):
"""
Initialize the content fetcher.
@@ -85,12 +86,18 @@ class ContentFetcher:
current research (if any) is used, so the quick-report
phase, detailed subsections, lead agent and subagents
share previously fetched pages instead of re-fetching.
+ url_guard: Optional extra URL boundary checked before each
+ static request, including redirects. Guarded documents use
+ static extraction without browser or source enrichment.
+ They never read or store page content in the shared cache;
+ only its per-run SSRF validation memo is shared.
"""
self.timeout = timeout
self.language = language
self.enable_js_rendering = enable_js_rendering
self.egress_context = egress_context
self.content_cache = content_cache
+ self.url_guard = url_guard
self._downloaders: Dict[URLType, Any] = {}
def _resolve_cache(self) -> Any:
@@ -108,6 +115,10 @@ class ContentFetcher:
def _get_downloader(self, url_type: URLType):
"""Get or create the appropriate downloader for a URL type."""
+ if self.url_guard is not None:
+ # A replay URL is saved evidence, even when its embedded target
+ # resembles a specialized source. Avoid live metadata enrichment.
+ url_type = URLType.HTML
if url_type in self._downloaders:
return self._downloaders[url_type]
@@ -167,15 +178,26 @@ class ContentFetcher:
elif url_type == URLType.HTML:
try:
- from ..research_library.downloaders.playwright_html import (
- AutoHTMLDownloader as HTMLDownloader,
- )
+ if self.url_guard is not None:
+ # Archived evidence must stay within its capture. Static
+ # extraction avoids browser navigation and live resources.
+ from ..research_library.downloaders.html import (
+ HTMLDownloader as StaticHTMLDownloader,
+ )
- downloader = HTMLDownloader(
- timeout=self.timeout,
- language=self.language,
- enable_js_rendering=self.enable_js_rendering,
- )
+ downloader = StaticHTMLDownloader(
+ timeout=self.timeout, language=self.language
+ )
+ else:
+ from ..research_library.downloaders.playwright_html import (
+ AutoHTMLDownloader as HTMLDownloader,
+ )
+
+ downloader = HTMLDownloader(
+ timeout=self.timeout,
+ language=self.language,
+ enable_js_rendering=self.enable_js_rendering,
+ )
except ImportError:
logger.warning("content_fetcher.html_downloader_unavailable")
@@ -215,6 +237,15 @@ class ContentFetcher:
so setting it post-construction takes effect. Cloud-metadata IPs stay
blocked regardless (``is_ip_blocked`` always rejects them).
"""
+ if self.url_guard is not None and downloader is not None:
+ from ..security.safe_requests import SafeSession
+
+ session = getattr(downloader, "session", None)
+ if not isinstance(session, SafeSession):
+ raise ValueError(
+ "Content downloader cannot enforce the URL boundary"
+ )
+ session.url_guard = self.url_guard
if downloader is None or self.egress_context is None:
return
session = getattr(downloader, "session", None)
@@ -382,7 +413,13 @@ class ContentFetcher:
# call via ``get_or_fetch``. Only successful (full pre-truncation)
# text is cached, so transient errors still retry. The cache sits
# AFTER the egress gate above — no policy bypass.
- _cache = self._resolve_cache()
+ # A guarded (archive) read neither reads nor stores cached page
+ # content; only the SSRF gate above shares the run cache's
+ # validation memo. An entry under the same replay URL can come from
+ # an unguarded fetch whose redirects left the capture, and the
+ # guarded caller needs this read's own transport failure, not a
+ # cached or coalesced result.
+ _cache = None if self.url_guard is not None else self._resolve_cache()
content_type = ContentType.TEXT if prefer_text else ContentType.PDF
def _download_once() -> Dict[str, Any] | None:
@@ -391,7 +428,8 @@ class ContentFetcher:
Returns a cache-shaped success dict with the FULL pre-truncation
text on success, or an error-shaped dict (no ``content``) on
failure so ``get_or_fetch`` passes it through without caching
- while waiters retry with their own fetch.
+ while waiters retry with their own fetch. A guarded read
+ re-raises download failures instead.
"""
downloader = self._get_downloader(url_type)
if not downloader and url_type not in _NO_IMPORT_FALLBACK:
@@ -404,8 +442,12 @@ class ContentFetcher:
"error": "No suitable downloader available",
}
try:
- result = downloader.download_with_result(url, content_type)
- if not result.is_success and url_type not in _NO_HTML_FALLBACK:
+ result = self._download_content(downloader, url, content_type)
+ if (
+ not result.is_success
+ and self.url_guard is None
+ and url_type not in _NO_HTML_FALLBACK
+ ):
logger.debug(
"content_fetcher.html_fallback_started url={url}",
url=redact_url_for_log(url),
@@ -474,6 +516,10 @@ class ContentFetcher:
"error": result.skip_reason or "Download failed",
}
except Exception as e:
+ if self.url_guard is not None:
+ # The guarded fetch tool classifies this failure and emits
+ # its safe message. Ordinary callers retain dict errors.
+ raise
logger.opt(exception=False).error(
"content_fetcher.download_error url={url}",
url=redact_url_for_log(url),
@@ -561,6 +607,22 @@ class ContentFetcher:
result_out["published_date"] = cached.get("published_date")
return result_out
+ def _download_content(self, downloader, url, content_type):
+ if self.url_guard is None:
+ return downloader.download_with_result(url, content_type)
+ # Guarded archive reads need the actual terminal failure (including
+ # Retry-After), rather than a sanitized skip reason. State is local
+ # to the call, so concurrent fetches cannot overwrite each other.
+ transport_errors: list[BaseException] = []
+ result = downloader.download_with_result(
+ url,
+ content_type,
+ on_transport_error=transport_errors.append,
+ )
+ if transport_errors:
+ raise transport_errors[-1]
+ return result
+
def fetch_text(
self, url: str, max_length: Optional[int] = None
) -> Optional[str]:
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 72d1729881..8a93818775 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -997,7 +997,7 @@
},
"search.fetch.mode": {
"category": "search_parameters",
- "description": "Controls the LangGraph agent's fetch_content tool. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Controls the LangGraph agent's fetch_content and fetch_archive tools. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes both tools entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -1028,7 +1028,7 @@
},
"search.fetch.content_max_length": {
"category": "search_parameters",
- "description": "Maximum page text (in characters) passed to the fetch_content tool per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content tool; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
"editable": true,
"max_value": 50000,
"min_value": 1000,
@@ -1042,7 +1042,7 @@
},
"search.fetch.max_per_topic": {
"category": "search_parameters",
- "description": "Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",
+ "description": "Maximum number of page content fetches (fetch_content and fetch_archive calls sharing one budget) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",
"editable": true,
"max_value": 50,
"min_value": 0,
@@ -1623,7 +1623,7 @@
},
"search.tool": {
"category": "search_general",
- "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately.",
+ "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately. Wayback is available through fetch_archive for known URLs. If your saved engine is Wayback, choose a configured search provider for topic queries; saved values are not changed automatically.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -1684,10 +1684,6 @@
{
"label": "Mojeek",
"value": "mojeek"
- },
- {
- "label": "Wayback",
- "value": "wayback"
}
],
"step": null,
@@ -3195,12 +3191,12 @@
"step": null,
"type": "SEARCH",
"ui_element": "text",
- "value": "Search the Internet Archive's Wayback Machine.",
+ "value": "Fetch archived versions of known URLs from the Internet Archive's Wayback Machine.",
"visible": false
},
"search.engine.web.wayback.default_params.closest_only": {
"category": "wayback",
- "description": "When enabled, only return the snapshot closest to the target date instead of all available snapshots.",
+ "description": "Legacy URL adapter: When enabled, only return the snapshot closest to the target date instead of all available snapshots. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -3214,7 +3210,7 @@
},
"search.engine.web.wayback.default_params.language": {
"category": "wayback",
- "description": "Preferred language for archived content when multiple versions are available.",
+ "description": "Legacy URL adapter: Preferred language for archived content when multiple versions are available. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -3228,7 +3224,7 @@
},
"search.engine.web.wayback.default_params.max_results": {
"category": "wayback",
- "description": "Maximum number of archived snapshots to return per search query.",
+ "description": "Legacy URL adapter: Maximum number of archived snapshots to return per search query. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": 1,
@@ -3242,7 +3238,7 @@
},
"search.engine.web.wayback.default_params.max_snapshots_per_url": {
"category": "wayback",
- "description": "Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history.",
+ "description": "Legacy URL adapter: Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": 1,
@@ -3903,7 +3899,7 @@
},
"search.engine.web.wayback.use_in_auto_search": {
"category": "wayback",
- "description": "Include Wayback in auto search mode",
+ "description": "Legacy setting retained for compatibility. Wayback accepts URLs only and is excluded from topic and auto search; choose a configured search provider for topics.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -3917,11 +3913,11 @@
},
"search.engine.web.wayback.agent_enabled": {
"category": "wayback",
- "description": "Include Wayback as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",
+ "description": "Enable the fetch_archive tool for the lead LangGraph research agent and its subagents. Find URLs with a configured search provider, then fetch an archived version with an optional date. Uses search.fetch.mode and the shared search.fetch.max_per_topic budget; disabled fetch mode or egress policy can still block archive fetching.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Available to Research Agent",
+ "name": "Enable Archive Fetch",
"options": null,
"step": null,
"type": "SEARCH",
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 0693191752..e4af75c2d1 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -689,10 +689,12 @@ def search(
engine: Search engine to use (e.g., "arxiv", "wikipedia", "searxng", "brave").
This is required — use list_search_engines() to see available options.
For "wayback", the query must contain a full http:// or https://
- URL, or be only a bare domain such as example.com; only the
- host is looked up. Not supported: an uppercase scheme, a
- bracketed IPv6 host, a user name or password before the host,
- and a bare domain with a punycode (xn--) top-level domain.
+ URL, or be only a bare domain such as example.com, optionally
+ with a port, path or query. The complete URL, including its
+ port, path, query and fragment, is looked up; words that
+ follow a URL without a space become part of it. A URL with a
+ user name or password before its host is not looked up, and
+ at most max_results URLs are.
max_results: Maximum number of results to return (1-100). Default is 10.
Returns:
diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.py
index 595ec8ac5b..bd936747a4 100644
--- a/src/local_deep_research/research_library/downloaders/html.py
+++ b/src/local_deep_research/research_library/downloaders/html.py
@@ -11,6 +11,7 @@ from loguru import logger
from bs4 import BeautifulSoup
from requests.exceptions import ConnectionError as RequestsConnectionError
from requests.exceptions import Timeout as RequestsTimeout
+from requests.exceptions import HTTPError as RequestsHTTPError
from .base import (
_DOCUMENT_ABSENT_STATUSES,
@@ -207,16 +208,30 @@ class HTMLDownloader(BaseDownloader):
return None
def download_with_result(
- self, url: str, content_type: ContentType = ContentType.TEXT
+ self,
+ url: str,
+ content_type: ContentType = ContentType.TEXT,
+ *,
+ on_transport_error: Optional[Callable[[BaseException], None]] = None,
) -> DownloadResult:
- """Download content and return detailed result with skip reason."""
+ """Download content, optionally reporting the typed terminal failure.
+
+ The callback receives only transport failures, before their details
+ are reduced to a client-safe skip reason. Extraction failures and
+ missing documents (404/410) remain per-document results.
+ """
if content_type == ContentType.PDF:
return DownloadResult(
skip_reason="HTML downloader does not support PDF downloads"
)
try:
- html_content = self._fetch_html(url)
+ if on_transport_error is None:
+ html_content = self._fetch_html(url)
+ else:
+ html_content, _ = self._fetch_html_with_final_url(
+ url, on_transport_error=on_transport_error
+ )
if not html_content:
kind, payload, final_url = self._consume_recovery(url)
if kind == "pdf" and isinstance(payload, bytes):
@@ -302,6 +317,7 @@ class HTMLDownloader(BaseDownloader):
url: str,
*,
on_transport_failure: Optional[Callable[[], None]] = None,
+ on_transport_error: Optional[Callable[[BaseException], None]] = None,
on_rate_limited: Optional[Callable[[], None]] = None,
max_attempts: int = 3,
) -> tuple[Optional[str], Optional[str]]:
@@ -402,6 +418,8 @@ class HTMLDownloader(BaseDownloader):
)
if on_transport_failure is not None:
on_transport_failure()
+ if on_transport_error is not None:
+ on_transport_error(exc)
return None, None
wait_time = 0.0
@@ -525,6 +543,11 @@ class HTMLDownloader(BaseDownloader):
and status not in _DOCUMENT_ABSENT_STATUSES
):
on_transport_failure()
+ if (
+ on_transport_error is not None
+ and status not in _DOCUMENT_ABSENT_STATUSES
+ ):
+ on_transport_error(RequestsHTTPError(response=response))
if status in (429, 503) and on_rate_limited is not None:
# Fires exactly once: this branch is terminal (the
# retried 429/503s never reach it — see the NOTE above).
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index f1be58320d..cadb61a8d6 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -12,7 +12,7 @@ import threading
import time
import types
import weakref
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Callable, Optional
from urllib.parse import urljoin
import requests
@@ -965,6 +965,7 @@ class SafeSession(requests.Session):
self.allow_localhost = allow_localhost
self.allow_private_ips = allow_private_ips
self.block_link_local = block_link_local
+ self.url_guard: Optional[Callable[[str], None]] = None
self.block_https_downgrade = block_https_downgrade
self.egress_context = egress_context
# Per-thread, because one session is shared across search engines.
@@ -1117,6 +1118,9 @@ class SafeSession(requests.Session):
therefore validated twice (once in ``request()``, once here);
this is intentional defense-in-depth.
"""
+ url_guard = getattr(self, "url_guard", None)
+ if url_guard is not None:
+ url_guard(request.url or "")
if (
self.block_https_downgrade
and request.url
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 86724a6de3..36e4efa106 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -11,6 +11,7 @@ from local_deep_research.text_optimization.citation_formatter import (
from .url_utils import (
CHUNK_DISPLAY_KEY,
FETCHED_TITLE_KEY,
+ _is_wayback_replay_url,
canonical_url_key,
library_display_url,
preferred_chunk_display,
@@ -202,6 +203,12 @@ def extract_links_from_search_results(search_results: List[Dict]) -> List[Dict]:
"venue",
"publisher",
"source_type",
+ # Keep verified capture provenance through the live
+ # Sources rebuild, including its archived-date suffix.
+ "original_url",
+ "requested_url",
+ "timestamp",
+ "formatted_date",
"openalex_source_id",
"source",
"source_engine",
@@ -319,6 +326,24 @@ def source_url_field(link: Dict) -> object:
_MAX_RANGE_SPAN = 1000
_MAX_TOTAL_EXPANSION = 5000
_MAX_RANGE_ENDPOINT_DIGITS = 18
+# This bounds candidate expansion work, not the report or its context. On
+# exhaustion the parser becomes indeterminate and keeps the full bibliography.
+_MAX_URL_CANDIDATE_CHARS = 1_000_000
+
+
+class _URLCandidateBudgetExceeded(Exception):
+ """The citation parser must fall back before expanding more candidates."""
+
+
+class _URLCandidateBudget:
+ def __init__(self):
+ self.remaining = _MAX_URL_CANDIDATE_CHARS
+
+ def consume(self, characters: int) -> None:
+ if characters > self.remaining:
+ raise _URLCandidateBudgetExceeded
+ self.remaining -= characters
+
_FENCE_MARKERS = ("```", "~~~")
@@ -366,16 +391,39 @@ _IP_LITERAL_AUTHORITY = (
)
_IP_LITERAL_URL_RE = re.compile(_IP_LITERAL_AUTHORITY, re.IGNORECASE)
+# Replay targets can contain IP authorities and bracketed path/query values.
+# A replay-specific scanner retains nested pairs while unmatched closing
+# brackets still delimit surrounding prose, as they do for ordinary URLs.
+_WAYBACK_REPLAY_PREFIX = (
+ r"https?://web\.archive\.org(?::(?:80|443))?/web/"
+ r"[0-9]{14}(?:id_|if_)?/https?://"
+)
+_WAYBACK_REPLAY_PREFIX_RE = re.compile(_WAYBACK_REPLAY_PREFIX, re.IGNORECASE)
+_WAYBACK_REPLAY_URL = _WAYBACK_REPLAY_PREFIX + r'[^\s<>"]+'
+
# In addition to absolute URLs and markdown-link destinations
# (``](/library/…)``), bare library routes (``/library/document/…``,
# ``/lib/document/…``) are in scope by design: prose commonly mentions
# them outside link syntax, and dropping a bare-path mention is the same
# citation-loss class as dropping a markdown destination.
-_URL_RE = re.compile(
- rf"(?P<absolute>{_IP_LITERAL_AUTHORITY}[^\s<>\[\]\"]*"
- r"|https?://[^\s<>\[\]\"]+)"
+_ORDINARY_ABSOLUTE_URL = (
+ rf"{_IP_LITERAL_AUTHORITY}[^\s<>\[\]\"]*"
+ r"|https?://[^\s<>\[\]\"]+"
+)
+_RELATIVE_CITATION_URL = (
r"|\]\([ \t]*(?P<relative>/[^\s<>\"]*)"
- r"|(?P<bare_library>/(?:library|lib)/document/[^\s<>\[\]\"]+)",
+ r"|(?P<bare_library>/(?:library|lib)/document/[^\s<>\[\]\"]+)"
+)
+_URL_RE = re.compile(
+ rf"(?P<absolute>{_WAYBACK_REPLAY_URL}|{_ORDINARY_ABSOLUTE_URL})"
+ + _RELATIVE_CITATION_URL,
+ re.IGNORECASE,
+)
+# Find a replay prefix before scanning its target. Capturing the whole
+# remaining suffix here would rescan adjacent wrapped links quadratically.
+_URL_START_RE = re.compile(
+ rf"(?P<absolute>{_WAYBACK_REPLAY_PREFIX}|{_ORDINARY_ABSOLUTE_URL})"
+ + _RELATIVE_CITATION_URL,
re.IGNORECASE,
)
@@ -715,14 +763,19 @@ def _peel_url_candidate(raw: str) -> str:
return url[:end]
-def _url_citation_candidates(match: re.Match) -> Set[str]:
+def _url_citation_candidates(
+ match: re.Match, budget: Optional[_URLCandidateBudget] = None
+) -> Set[str]:
"""Preserve exact destinations; keep ambiguous bare URL interpretations."""
+ if budget is None:
+ budget = _URLCandidateBudget()
group = next(
name
for name in ("absolute", "relative", "bare_library")
if match.group(name) is not None
)
raw = match.group(group)
+ budget.consume(len(raw))
start = match.start(group)
text = match.string
following = text[match.end() : match.end() + 1]
@@ -732,6 +785,7 @@ def _url_citation_candidates(match: re.Match) -> Set[str]:
if start and text[start - 1] == '"' and following == '"':
# Quotes delimit the URL, but sentence punctuation inside them may
# belong to the surrounding sentence; keep both readings.
+ budget.consume(len(raw))
return {raw, _peel_url_candidate(raw)}
prefix = start
@@ -749,6 +803,7 @@ def _url_citation_candidates(match: re.Match) -> Set[str]:
depth += 1
elif char == ")":
if not depth:
+ budget.consume(position)
return {_MARKDOWN_URL_ESCAPE_RE.sub(r"\1", raw[:position])}
depth -= 1
if not depth and _MARKDOWN_URL_END_RE.match(text, match.end()):
@@ -756,7 +811,11 @@ def _url_citation_candidates(match: re.Match) -> Set[str]:
# Remove one sentence mark outside any surrounding wrappers. Further
# punctuation, underscores and stars may be significant URL content.
- url = raw[:-1] if raw and raw[-1] in _URL_SENTENCE_PUNCT else raw
+ if raw and raw[-1] in _URL_SENTENCE_PUNCT:
+ budget.consume(len(raw) - 1)
+ url = raw[:-1]
+ else:
+ url = raw
wrapped = False
for _ in range(32):
if not start:
@@ -768,6 +827,15 @@ def _url_citation_candidates(match: re.Match) -> Set[str]:
if closer == "]" and authority and authority.end() == len(url):
# The captured bracket closes the host, not an outer wrapper.
break
+ if (
+ closer in "])"
+ and _WAYBACK_REPLAY_PREFIX_RE.match(url)
+ and url.count(text[start - 1]) == url.count(closer)
+ ):
+ # The replay branch excludes an unmatched outer closer, so a
+ # balanced final bracket/parenthesis belongs to the target.
+ break
+ budget.consume(len(url) - len(closer))
url = url[: -len(closer)]
start -= 1
wrapped = True
@@ -775,23 +843,46 @@ def _url_citation_candidates(match: re.Match) -> Set[str]:
# The wrapper closer is prose, but any sentence mark it hides may
# be URL content or sentence punctuation; keep both readings so
# ``"https://x.example/a."`` cites ``a`` and ``a.`` alike.
+ budget.consume(len(url))
return {url, url.rstrip(_URL_SENTENCE_PUNCT)}
candidates = {raw, url}
+ if _WAYBACK_REPLAY_PREFIX_RE.match(url):
+ # A bare replay followed immediately by [N] can spell either a
+ # target suffix or a prose reference. Keep both readings; exact
+ # angle/Markdown destinations already returned above.
+ # Find the final contiguous run without retaining a match object
+ # for every bracket. Charge each interpretation BEFORE slicing it:
+ # preserving all prefixes as strings otherwise takes quadratic space.
+ run_start = None
+ previous_end = -1
+ for reference in _BRACKET_NUMERIC_RE.finditer(url):
+ if reference.start() != previous_end:
+ run_start = reference.start()
+ previous_end = reference.end()
+ if previous_end == len(url) and run_start is not None:
+ for reference in _BRACKET_NUMERIC_RE.finditer(url, run_start):
+ end = reference.start()
+ budget.consume(end)
+ candidates.add(url[:end])
# A run of three or more trailing sentence marks reads as an
# ellipsis-sized prose unit (``See https://x.example/a... Also``), so
# the fully-peeled reading stays plausible too. Shorter runs peel
# exactly one mark: a sentence contributes a single terminator, and
# peeling deeper would strip real URL content (``Read
# https://x.example/a..`` where the path genuinely ends in ``.``).
- fully_peeled = raw.rstrip(_URL_SENTENCE_PUNCT)
- if len(raw) - len(fully_peeled) >= 3:
- candidates.add(fully_peeled)
+ peeled_end = len(raw)
+ while peeled_end and raw[peeled_end - 1] in _URL_SENTENCE_PUNCT:
+ peeled_end -= 1
+ if len(raw) - peeled_end >= 3:
+ budget.consume(peeled_end)
+ candidates.add(raw[:peeled_end])
authority = _IP_LITERAL_URL_RE.match(url)
suffix = url[authority.end() :] if authority else url
if suffix.count(")") > suffix.count("("):
# A closing parenthesis can be URL content or belong to prose
# whose opening parenthesis precedes intervening words.
+ budget.consume(len(raw))
candidates.add(_peel_url_candidate(raw))
return candidates
@@ -813,15 +904,84 @@ def _has_malformed_numeric_brackets(text: str) -> bool:
return False
-def _mask_ip_literal_authority(match: re.Match) -> str:
+def _mask_replay_ip_literal(match: re.Match) -> str:
+ """Mask only a parseable IP authority inside a verified replay target."""
+ authority = match.group(0)
+ try:
+ _ = urlsplit(authority).port
+ except ValueError:
+ return authority
+ return authority.replace("[", "(").replace("]", ")")
+
+
+def _citation_url_matches(text: str) -> List[re.Match]:
+ """Scan replay targets once, retaining balanced URL brackets/wrappers."""
+ matches: List[re.Match] = []
+ position = 0
+ while (match := _URL_START_RE.search(text, position)) is not None:
+ raw = match.group("absolute")
+ if raw and _WAYBACK_REPLAY_PREFIX_RE.match(raw):
+ prefix = match.start("absolute")
+ while prefix and text[prefix - 1] in " \t\r\n":
+ prefix -= 1
+ parenthesized = bool(prefix and text[prefix - 1] == "(")
+ bracket_depth = 0
+ paren_depth = 0
+ escaped = False
+ end = match.end()
+ while end < len(text):
+ character = text[end]
+ if character.isspace() or character in '<>"':
+ break
+ if escaped:
+ escaped = False
+ elif parenthesized and character == "\\":
+ escaped = True
+ elif character == "[":
+ bracket_depth += 1
+ elif character == "]":
+ if not bracket_depth:
+ break
+ bracket_depth -= 1
+ elif parenthesized and character == "(":
+ paren_depth += 1
+ elif parenthesized and character == ")":
+ if not paren_depth:
+ break
+ paren_depth -= 1
+ end += 1
+ bounded = _URL_RE.match(text, match.start(), end)
+ if bounded is not None:
+ match = bounded
+ matches.append(match)
+ position = match.end()
+ return matches
+
+
+def _mask_ip_literal_authority(
+ match: re.Match, budget: Optional[_URLCandidateBudget] = None
+) -> str:
"""Keep valid captured URL hosts out of the numeric citation parser."""
url = match.group("absolute")
if not url:
return match.group(0)
authority_match = _IP_LITERAL_URL_RE.match(url)
if authority_match is None:
+ if _WAYBACK_REPLAY_PREFIX_RE.match(url):
+ for candidate in _url_citation_candidates(match, budget):
+ try:
+ if not _is_wayback_replay_url(
+ candidate, urlsplit(candidate)
+ ):
+ continue
+ except ValueError:
+ continue
+ # Only IP-host brackets are masked. Path/query brackets
+ # and surrounding numeric or malformed references remain
+ # visible to the normal citation parser.
+ return _IP_LITERAL_URL_RE.sub(_mask_replay_ip_literal, url)
return url
- for candidate in _url_citation_candidates(match):
+ for candidate in _url_citation_candidates(match, budget):
if _IP_LITERAL_URL_RE.match(candidate) is None:
# A malformed Markdown destination can end before its host.
continue
@@ -899,8 +1059,9 @@ def extract_cited_indices_and_urls(
Returns ``(cited_indices, cited_url_keys, indeterminate)`` where
``cited_url_keys`` are ``canonical_url_key`` values. ``indeterminate``
- is True when a range, bracket, or fence is ambiguous and the result
- must be treated as unreliable (caller falls back to the full list).
+ is True when a range, bracket, or fence is ambiguous or the shared URL
+ candidate-work budget is exhausted. The result must then be treated as
+ unreliable (caller falls back to the full list without truncating prose).
Recognized signals: numeric brackets (outer spaces allowed:
``[ 1, 2 ]``), tagged citations, ``Source N`` phrases, absolute URLs,
@@ -929,6 +1090,7 @@ def extract_cited_indices_and_urls(
indices: Set[int] = set()
url_keys: Set[str] = set()
state = {"indeterminate": False, "expanded": 0}
+ candidate_budget = _URLCandidateBudget()
if not prose or not prose.strip():
return indices, url_keys, False
@@ -940,7 +1102,20 @@ def extract_cited_indices_and_urls(
# must not look like a broken [N] citation and force all sources back in.
# Use the same capture boundaries as URL extraction below. An IPv6
# literal inside another URL's path or query is not a separate host.
- citation_text = _URL_RE.sub(_mask_ip_literal_authority, text)
+ url_matches = _citation_url_matches(text)
+ citation_parts: List[str] = []
+ position = 0
+ try:
+ for match in url_matches:
+ citation_parts.append(text[position : match.start()])
+ citation_parts.append(
+ _mask_ip_literal_authority(match, candidate_budget)
+ )
+ position = match.end()
+ except _URLCandidateBudgetExceeded:
+ return indices, url_keys, True
+ citation_parts.append(text[position:])
+ citation_text = "".join(citation_parts)
for m in _BRACKET_NUMERIC_RE.finditer(citation_text):
_parse_bracket_content(m.group(1), indices, state)
@@ -975,8 +1150,11 @@ def extract_cited_indices_and_urls(
nums_norm = re.sub(r"\s*(?:and|&)\s*", ",", nums, flags=re.IGNORECASE)
_parse_bracket_content(nums_norm, indices, state)
- for m in _URL_RE.finditer(text):
- candidates = _url_citation_candidates(m)
+ for m in url_matches:
+ try:
+ candidates = _url_citation_candidates(m, candidate_budget)
+ except _URLCandidateBudgetExceeded:
+ return indices, url_keys, True
# Case-variant library routes (``/LIBRARY/Document/d2``): the regex
# captures them (bare mentions and markdown destinations) but the
# canonical key is prefix-case-sensitive, so also key the
@@ -985,6 +1163,11 @@ def extract_cited_indices_and_urls(
# not lose while the bare mention of the same route retains.
for base in list(candidates):
if _BARE_LIBRARY_PREFIX_RE.match(base):
+ try:
+ # /lib/ can expand to /library/; account before copying.
+ candidate_budget.consume(len(base) + 4)
+ except _URLCandidateBudgetExceeded:
+ return indices, url_keys, True
candidates.add(_normalize_bare_library_prefix(base))
for candidate in candidates:
if not candidate:
@@ -1111,12 +1294,9 @@ def format_links_to_markdown(
logger.info(f"Formatting {len(all_links)} links to markdown...")
if all_links:
- # Group links by canonical URL (collapses trailing slash, utm
- # params, fragments, default ports, scheme/host case, userinfo).
- # The canonical form is also what gets displayed so the Sources
- # section stays clean — no utm_*/fbclid clutter, no embedded
- # credentials, no scheme/host casing noise. Click-through is
- # unaffected (tracking params carry no content).
+ # Group and display ordinary URLs in canonical form. Timestamped
+ # Wayback replays keep their complete spelling: their embedded
+ # target path/query identifies the historical resource.
# Group links by (canonical URL, chunk display URL).
# Canonical key remains per-document so count_distinct_sources,
# MCP sources, and news metrics do not inflate, while grouping on
@@ -1126,10 +1306,11 @@ def format_links_to_markdown(
# an unanchored /pdf view deliberately renders on its own line when
# cited alongside chunks (reversing #5685's collapse so anchorless
# indices honestly link to /pdf rather than mis-pointing at an arbitrary chunk).
- # Non-library sources display their canonical URL, so tracking params
- # and credentials stay out of the report.
+ # Non-library sources display their canonical URL, including the
+ # exact replay spelling preserved by canonical_url_key.
url_to_indices: dict[tuple[str, str], list] = {}
group_to_title: dict[tuple[str, str], str] = {}
+ group_to_capture_date: dict[tuple[str, str], str] = {}
# Keyed by canonical URL alone, unlike its neighbours. A document
# cited through both its chunk anchor and its bare URL renders one
# line per group, and its page title is the same on both; keying
@@ -1170,6 +1351,10 @@ def format_links_to_markdown(
url_to_indices.setdefault(key, []).append(link.get("index", ""))
group_to_title.setdefault(key, link.get("title", "Untitled"))
+ if link.get("source_type") == "archive":
+ capture_date = link.get("formatted_date")
+ if isinstance(capture_date, str) and capture_date.strip():
+ group_to_capture_date.setdefault(key, capture_date.strip())
# A page's own title, recorded by the fetch ingest path beside a
# citation whose stored title a search engine scraped. First
# non-empty wins, as for quality and collection below.
@@ -1221,6 +1406,11 @@ def format_links_to_markdown(
# a non-str, taking the whole Sources block with it.
if title is not None and not isinstance(title, str):
title = str(title)
+ capture_date = group_to_capture_date.get(key)
+ if capture_date:
+ suffix = f" (archived {capture_date})"
+ if not (title or "").endswith(suffix):
+ title = f"{title or 'Untitled'}{suffix}"
if title:
title = _sanitize_sources_field(
title.replace(LDR_APPENDED_SOURCES_SENTINEL, "")
diff --git a/src/local_deep_research/utilities/url_utils.py b/src/local_deep_research/utilities/url_utils.py
index 53020c509f..779f489ae5 100644
--- a/src/local_deep_research/utilities/url_utils.py
+++ b/src/local_deep_research/utilities/url_utils.py
@@ -3,7 +3,7 @@
from functools import lru_cache
from typing import Optional
import re
-from urllib.parse import unquote, urlsplit, urlunsplit
+from urllib.parse import SplitResult, unquote, urlsplit, urlunsplit
from loguru import logger
@@ -419,6 +419,43 @@ def preferred_chunk_display(raw: str) -> str | None:
return display
+def _is_wayback_replay_url(url: str, parsed: SplitResult) -> bool:
+ """Recognize a capture URL whose embedded target must stay verbatim.
+
+ Capture availability and redirect safety are checked by the archive
+ client. This only keeps citation normalization from changing its target.
+ """
+ if any(character.isspace() or ord(character) < 32 for character in url):
+ return False
+ try:
+ if (
+ parsed.scheme not in {"http", "https"}
+ or parsed.hostname != "web.archive.org"
+ or parsed.port not in {None, 80, 443}
+ or parsed.username is not None
+ or parsed.password is not None
+ ):
+ return False
+ replay = re.fullmatch(
+ r"/web/[0-9]{14}(?:id_|if_)?/(https?://.+)", parsed.path
+ )
+ if replay is None:
+ return False
+ target = urlsplit(replay.group(1))
+ # Match the archive client's absolute, credential-free target
+ # boundary without importing transport code into this utility.
+ if (
+ not target.hostname
+ or target.username is not None
+ or target.password is not None
+ ):
+ return False
+ target.port
+ except ValueError:
+ return False
+ return True
+
+
@lru_cache(maxsize=1024)
def canonical_url_key(url: str) -> str:
"""Return a canonical form of ``url`` suitable for deduplication and
@@ -443,6 +480,11 @@ def canonical_url_key(url: str) -> str:
param order is preserved as-is here; callers that need
order-insensitivity (e.g. download-tracker hashing) sort afterwards.
+ Timestamped Wayback replay URLs retain their complete spelling,
+ including the capture modifier and embedded target's path, query and
+ fragment. Removing a trailing slash or a tracking parameter there
+ changes the captured target rather than merely cleaning a live link.
+
Internal library-document routes (``/library/document/<id>``, plus its
``/pdf`` and ``/chunks#chunk-<n>`` views) collapse to a per-document
key, because they are views of one source and belong on one
@@ -496,6 +538,9 @@ def canonical_url_key(url: str) -> str:
# control characters to spaces.
return url.strip()
+ if _is_wayback_replay_url(url, parsed):
+ return url
+
scheme = parsed.scheme.lower()
# Strip userinfo (user:pass@host) from netloc.
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index e528296849..bc282fd0c8 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -4078,6 +4078,8 @@ def api_get_available_search_engines(
)
for engine_id, engine_data in search_engines.items():
+ if not engine_data.get("supports_query_search", True):
+ continue
# Try to load the engine class to get metadata
engine_class = None
try:
diff --git a/src/local_deep_research/web/services/report_assembly_service.py b/src/local_deep_research/web/services/report_assembly_service.py
index f63b985b7a..df4bcb86fc 100644
--- a/src/local_deep_research/web/services/report_assembly_service.py
+++ b/src/local_deep_research/web/services/report_assembly_service.py
@@ -260,6 +260,13 @@ def _build_sources_markdown(
"title": str(r.title) if r.title else "Untitled",
"index": index,
"journal_quality": original.get("journal_quality"),
+ # A fetched title can predate an archive upgrade. Retain
+ # the capture metadata so the renderer still adds its date.
+ "source_type": original.get("source_type", r.source_type),
+ "original_url": original.get("original_url"),
+ "requested_url": original.get("requested_url"),
+ "timestamp": original.get("timestamp"),
+ "formatted_date": original.get("formatted_date"),
# ``title`` above is the column, which the search hit wrote.
# Rows saved before this key existed return None, which the
# renderer ignores.
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 858ce2b181..bef384e593 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -4884,6 +4884,9 @@
SafeLogger.log('Setting initial search engine value:', currentValue);
dropdown.setValue(currentValue, false);
searchEngineHiddenInput.value = currentValue;
+ if (currentValue === 'wayback') {
+ searchEngineInput.value = 'Wayback (saved; choose a configured search provider for topics)';
+ }
}
// --- ADD CHANGE LISTENER TO HIDDEN INPUT ---
@@ -5351,6 +5354,9 @@
if (currentValue && dropdownInstance && dropdownInstance.setValue) {
SafeLogger.log(`Setting initial value for ${settingKey}:`, currentValue);
dropdownInstance.setValue(currentValue, false); // Don't fire event on init
+ if (settingKey === 'search.tool' && currentValue === 'wayback') {
+ dropdownInput.value = 'Wayback (saved; choose a configured search provider for topics)';
+ }
// --- MODIFICATION START: Set hidden input initial value ---
if (hiddenInput) {
hiddenInput.value = currentValue;
diff --git a/src/local_deep_research/web_search_engines/engine_availability.py b/src/local_deep_research/web_search_engines/engine_availability.py
index 337b6672c0..5ce8a8c46d 100644
--- a/src/local_deep_research/web_search_engines/engine_availability.py
+++ b/src/local_deep_research/web_search_engines/engine_availability.py
@@ -162,6 +162,14 @@ def failure_from_exception(
return SearchFailure("Search request timed out")
if isinstance(error, (requests.ConnectionError, ConnectionError)):
return SearchFailure("Could not connect to the search provider")
+ if isinstance(
+ error,
+ (
+ requests.exceptions.ChunkedEncodingError,
+ requests.exceptions.ContentDecodingError,
+ ),
+ ):
+ return SearchFailure("Could not read the provider response")
if isinstance(error, ValueError) and "security validation" in str(error):
# The SSRF validator also refuses a host it cannot resolve, and
# its ValueError does not say which. A transient DNS failure must
@@ -503,6 +511,8 @@ def engine_failure(engine) -> SearchFailure | None:
def engine_for_tool(name: str, primary_engine: str) -> str | None:
+ if name == "fetch_archive":
+ return "wayback"
if name == "web_search":
return primary_engine
if name.startswith("search_"):
@@ -510,9 +520,19 @@ def engine_for_tool(name: str, primary_engine: str) -> str | None:
return None
+def search_engines_for_tools(names, primary_engine) -> set[str]:
+ """Providers that discover URLs; archive fetching only reads known URLs."""
+ engines = {
+ engine_for_tool(name, primary_engine)
+ for name in names
+ if name == "web_search" or name.startswith("search_")
+ }
+ return {engine for engine in engines if engine is not None}
+
+
def search_exhausted(names, primary_engine, disabled) -> bool:
- """The toolbox had search tools, and every one of them is disabled."""
- engines = {engine_for_tool(name, primary_engine) for name in names} - {None}
+ """The toolbox had query search tools, and every one is disabled."""
+ engines = search_engines_for_tools(names, primary_engine)
return bool(engines) and engines <= disabled.keys()
@@ -520,7 +540,7 @@ def available_tool_names(names, primary_engine, disabled) -> list[str]:
"""Filter an already policy-approved toolbox, including empty delegation.
Delegation is dropped once availability has removed every search tool:
- its subagents would be left with ``fetch_content`` alone and no URLs
+ its subagents would be left with fetch tools alone and no URLs
to read. (A toolbox configured without search is left as it is.)
"""
available = [
diff --git a/src/local_deep_research/web_search_engines/engine_registry.py b/src/local_deep_research/web_search_engines/engine_registry.py
index a37454c55f..2b4292876a 100644
--- a/src/local_deep_research/web_search_engines/engine_registry.py
+++ b/src/local_deep_research/web_search_engines/engine_registry.py
@@ -22,6 +22,7 @@ class EngineEntry:
class_name: str
full_search_module: Optional[str] = None
full_search_class: Optional[str] = None
+ supports_query_search: bool = True
ENGINE_REGISTRY: Dict[str, EngineEntry] = {
@@ -89,6 +90,7 @@ ENGINE_REGISTRY: Dict[str, EngineEntry] = {
"wayback": EngineEntry(
module_path=".engines.search_engine_wayback",
class_name="WaybackSearchEngine",
+ supports_query_search=False,
),
"wikinews": EngineEntry(
module_path=".engines.search_engine_wikinews",
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
index a5a30677b2..8a4bb397bf 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_wayback.py
@@ -10,8 +10,40 @@ from ...security import redact_url_for_log
from ...security.safe_requests import safe_get
from ...security.secure_logging import logger
from ..rate_limiting import RateLimitError
+from ..wayback_client import get_availability_response, validate_archive_url
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
+# Characters that separate list entries: ASCII and fullwidth commas and
+# semicolons, and the ideographic comma. None is valid in a host name.
+_LIST_SEPARATORS = ",;\uff0c\uff1b\u3001"
+
+# Characters that end a URL in running text rather than belong to it:
+# sentence stops (ASCII, CJK, fullwidth, ellipsis), Markdown emphasis,
+# straight and curly closing quotes, and closing guillemets.
+_PROSE_URL_ENDINGS = frozenset(
+ ".,;:!?*'\u2019\u201d\u00bb\u203a"
+ "\u3001\u3002\uff0c\uff1b\uff1a\uff01\uff1f\uff0e\u2026"
+)
+
+# Opening and closing bracket pairs, ASCII, fullwidth and CJK. In running
+# text a closing bracket ends a URL only when the URL holds more of it than
+# of its opener, so a balanced pair in a path stays, as in a Wikipedia title
+# that ends in a bracket.
+_URL_BRACKET_PAIRS: Tuple[Tuple[str, str], ...] = (
+ ("(", ")"),
+ ("[", "]"),
+ ("{", "}"),
+ ("\uff08", "\uff09"),
+ ("\uff3b", "\uff3d"),
+ ("\uff5b", "\uff5d"),
+ ("\u300c", "\u300d"),
+ ("\u300e", "\u300f"),
+ ("\u3010", "\u3011"),
+ ("\u3008", "\u3009"),
+ ("\u300a", "\u300b"),
+ ("\u3014", "\u3015"),
+)
+
class WaybackSearchEngine(BaseSearchEngine):
"""
@@ -63,21 +95,7 @@ class WaybackSearchEngine(BaseSearchEngine):
def _extract_urls_from_query(self, query: str) -> List[str]:
"""
- Extract the scheme and host of each lowercase ``http://`` or
- ``https://`` URL in a query, or read a query that is only a bare
- domain as a URL. After the scheme, a URL match keeps letters and
- digits of any script, underscores, hyphens, dots and percent-escapes
- and ends at the first other character, so a port, path, query
- string or fragment is dropped and only the host is looked up. The
- same rule cuts short a host written with other characters, such as
- combining marks, and keeps a bare domain written with them from
- matching. Not read: a URL with an uppercase scheme or a bracketed
- IPv6 host, which does not match, and the host of a URL with a user
- name or password before it, where the match ends at or before the
- ``@`` and so looks up the start of the user name instead. The last
- label of a bare domain may hold only letters, digits and
- underscores, so a punycode top-level domain such as ``.xn--p1ai`` is
- not read as a bare domain, though the same domain in a full URL is.
+ Extract explicit URLs or interpret a bare domain/path as a URL.
Topic queries need URL discovery through a configured search
provider before they can be looked up in the Wayback Machine.
@@ -87,24 +105,218 @@ class WaybackSearchEngine(BaseSearchEngine):
Returns:
List of URLs to search in the Wayback Machine
"""
- # Check if the query is already a URL
- url_pattern = re.compile(r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+")
- urls = url_pattern.findall(query)
+ # Accept a complete bare domain, optionally with a port, path,
+ # query or fragment, before looking for embedded URLs: query
+ # parameters can themselves contain another URL.
+ target = query.strip()
+ domain_pattern = re.compile(
+ r"(?:[-\w.]|%[\da-fA-F]{2})+\.[\w-]+"
+ r"(?::\d+)?(?:[/?#][^\s<>\"`]*)?"
+ )
+ if domain_pattern.fullmatch(target):
+ logger.info("Query appears to be a domain or partial URL")
+ return [f"http://{target}"]
+
+ # Inline Markdown link labels are display text, not archive
+ # destinations. Track balanced brackets, including IPv6 labels;
+ # escaped brackets do not open or close a label.
+ label_starts = []
+ label_spans = []
+ for bracket in re.finditer(r"\\.|[\[\]]", query):
+ if bracket.group() == "[":
+ label_starts.append(bracket.start())
+ elif bracket.group() == "]" and label_starts:
+ start = label_starts.pop()
+ if query[bracket.end() : bracket.end() + 1] == "(":
+ label_spans.append((start, bracket.end() + 1))
+
+ # Labels nest like the brackets that delimit them, and URL starts
+ # only move forward, so a stack of the labels open at each URL
+ # finds its innermost label without rescanning every label.
+ label_spans.sort()
+ open_labels: List[Tuple[int, int]] = []
+ next_label = 0
+
+ # A URL's greedy run ends at whitespace, a double quote, a
+ # backtick or an angle bracket, and every URL of a compact list
+ # shares one run. No URL slices or rescans the rest of its run:
+ # searches that look past it are cached for the run's later URLs,
+ # so a long pasted list stays linear.
+ url_start = re.compile(r"https?://(?=[^\s<>\"`])", re.IGNORECASE)
+ run_boundary = re.compile(r"[\s<>\"`]")
+ quote_separator = re.compile(
+ rf"'[{_LIST_SEPARATORS}]*'(?=https?://)", re.IGNORECASE
+ )
+ path_separator = re.compile(
+ rf"[{_LIST_SEPARATORS}](?=https?://)", re.IGNORECASE
+ )
+ path_mark = re.compile(r"[?#]")
+ authority_mark = re.compile(r"[/?#]")
+ host_separator = re.compile(rf"[{_LIST_SEPARATORS}]")
+ bracket_pairs = {"(": re.compile(r"[()]"), "[": re.compile(r"[\[\]]")}
+ run_end = 0
+ closing_quote = None
+ first_hits: Dict[re.Pattern, Optional[int]] = {}
+
+ def first_in_run(pattern: re.Pattern, position: int) -> Optional[int]:
+ # A run's URLs are visited in order. An earlier search that
+ # found nothing, or found a match at or after this position,
+ # already answers the question.
+ hit = first_hits.get(pattern, -1)
+ if hit is not None and hit < position:
+ found = pattern.search(query, position, run_end)
+ hit = found.start() if found else None
+ first_hits[pattern] = hit
+ return hit
+
+ def host_separator_in(
+ scheme_end: int, authority_end: int
+ ) -> Optional[int]:
+ # The host follows the authority's last "@".
+ host_start = query.rfind("@", scheme_end, authority_end) + 1
+ cut = host_separator.search(
+ query, max(host_start, scheme_end), authority_end
+ )
+ return cut.start() if cut else None
+
+ urls = []
+ cursor = 0
+ while match := url_start.search(query, cursor):
+ start = match.start()
+ while (
+ next_label < len(label_spans)
+ and label_spans[next_label][0] < start
+ ):
+ label = label_spans[next_label]
+ next_label += 1
+ while open_labels and open_labels[-1][1] <= label[0]:
+ open_labels.pop()
+ open_labels.append(label)
+ while open_labels and open_labels[-1][1] <= start:
+ open_labels.pop()
+ if open_labels:
+ cursor = open_labels[-1][1]
+ continue
+ if start >= run_end:
+ boundary = run_boundary.search(query, start)
+ run_end = boundary.start() if boundary else len(query)
+ first_hits.clear()
+ # An unmatched opening prose quote must not turn an
+ # internal apostrophe into a closing delimiter: the run's
+ # last apostrophe closes a quote only when nothing but
+ # closing punctuation follows it. The backward scan stops
+ # at this URL's scheme at the latest.
+ tail = run_end
+ while query[tail - 1] in ".,;:!?)]}":
+ tail -= 1
+ closing_quote = tail - 1 if query[tail - 1] == "'" else None
+
+ # List separators after the host are prose/list separators,
+ # including a compact list with no whitespace. Keep these
+ # characters in userinfo, paths and query values.
+ # The authority read stops at the next "/", "?" or "#", and a
+ # following URL's scheme supplies one, so it never spans the
+ # rest of a compact list.
+ scheme_end = match.end()
+ authority_match = authority_mark.search(query, scheme_end, run_end)
+ authority_end = (
+ authority_match.start() if authority_match else run_end
+ )
+ host_separator_at = host_separator_in(scheme_end, authority_end)
+
+ url_end = run_end
+ preceding = query[start - 1] if start else ""
+ quoted = False
+ if preceding == "'":
+ # Strip the enclosing quote, retaining apostrophes in
+ # the target. A following quoted URL can start a list.
+ separator = first_in_run(quote_separator, start)
+ quote_end = closing_quote if separator is None else separator
+ if quote_end is not None:
+ url_end = quote_end
+ quoted = True
+
+ # Markdown links, parentheses and square brackets add a
+ # closing delimiter. Preserve balanced pairs inside the URL,
+ # including IPv6 hosts, and literal closers in raw URLs. A
+ # closer after a separator in the host cannot change the
+ # target, so the scan stops there.
+ wrapped = preceding in bracket_pairs
+ if wrapped:
+ depth = 0
+ for bracket in bracket_pairs[preceding].finditer(
+ query,
+ start,
+ run_end if host_separator_at is None else host_separator_at,
+ ):
+ if bracket.group() == preceding:
+ depth += 1
+ elif depth:
+ depth -= 1
+ else:
+ url_end = bracket.start()
+ break
+
+ delimited = quoted or (bool(preceding) and preceding in '"<`')
+ if not wrapped and not delimited:
+ # A compact list may separate complete path URLs too.
+ # Query/fragment values can contain literal nested URLs;
+ # explicitly delimited targets also retain literal paths.
+ path_end = first_in_run(path_mark, start)
+ separator = first_in_run(path_separator, start)
+ if separator is not None and (
+ path_end is None or separator < path_end
+ ):
+ url_end = separator
+
+ if host_separator_at is not None and url_end >= host_separator_at:
+ url_end = host_separator_at
+ elif url_end < authority_end:
+ # A cut inside the authority shortens it: an "@" after
+ # the cut no longer marks userinfo, so re-read the host.
+ separator = host_separator_in(scheme_end, url_end)
+ if separator is not None:
+ url_end = separator
+ url = query[start:url_end]
+
+ # A complete raw URL or an explicitly delimited destination
+ # keeps literal punctuation. Inside a parenthesis or square
+ # bracket, a list puts its separator before the closer or the
+ # next space. In prose, peel sentence endings, quotes, emphasis,
+ # CJK punctuation and a closer (ASCII, fullwidth or CJK) without
+ # its opener, without damaging balanced pairs in URL paths.
+ if wrapped:
+ url = url.rstrip(_LIST_SEPARATORS)
+ elif not delimited and url != target:
+ unmatched = {
+ closer: max(0, url.count(closer) - url.count(opener))
+ for opener, closer in _URL_BRACKET_PAIRS
+ }
+ end = len(url)
+ while end:
+ character = url[end - 1]
+ if character in _PROSE_URL_ENDINGS:
+ end -= 1
+ elif unmatched.get(character):
+ end -= 1
+ unmatched[character] -= 1
+ else:
+ break
+ url = url[:end]
+
+ urls.append(url)
+ # Resume after the actual target, not the rest of its run:
+ # the run may also hold the next URL or Markdown link.
+ cursor = start + len(url)
if urls:
logger.info(f"Found {len(urls)} URLs in query")
return urls
- # Check if query is a domain without http prefix
- domain_pattern = re.compile(r"^(?:[-\w.]|(?:%[\da-fA-F]{2}))+\.\w+$")
- if domain_pattern.match(query):
- logger.info("Query appears to be a domain")
- return [f"http://{query}"]
-
# Return empty list if nothing worked
logger.warning(
- "Wayback needs an http(s) URL, or a query that is only a bare "
- "domain; discover URLs with a configured search provider first"
+ "Wayback needs a URL or domain; discover URLs with a configured "
+ "search provider first"
)
return []
@@ -140,7 +352,7 @@ class WaybackSearchEngine(BaseSearchEngine):
try:
if self.closest_only:
# Get only the closest snapshot
- response = safe_get(self.available_api, params={"url": url})
+ response = get_availability_response(url, request_get=safe_get)
# Check for rate limit
if response.status_code == 429:
@@ -248,8 +460,26 @@ class WaybackSearchEngine(BaseSearchEngine):
"""
logger.info("Getting Wayback Machine previews")
- # Extract URLs from query
- urls = self._extract_urls_from_query(query)
+ urls = []
+ for url in self._extract_urls_from_query(query):
+ # fetch_archive's URL check: a user name or password before the
+ # host never reaches the archive or the results. A credential in
+ # a query value is sent as written, as with fetch_archive, and
+ # unlike fetch_archive no per-target egress check runs here.
+ try:
+ urls.append(validate_archive_url(url))
+ except ValueError:
+ logger.warning(
+ f"Skipping Wayback target {redact_url_for_log(url)}: not "
+ "one absolute HTTP(S) URL without credentials"
+ )
+ # Each target costs an archive request, so look up no more targets
+ # than this search returns results.
+ if len(urls) > self.max_results:
+ logger.info(
+ f"Looking up the first {self.max_results} of {len(urls)} URLs"
+ )
+ urls = urls[: self.max_results]
if not urls:
logger.warning("No URLs found in the query")
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 164bd3915e..d175cff4ce 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -219,6 +219,8 @@ def search_config(
if name in search_engines:
search_engines[name]["module_path"] = entry.module_path
search_engines[name]["class_name"] = entry.class_name
+ if not entry.supports_query_search:
+ search_engines[name]["supports_query_search"] = False
if entry.full_search_module:
search_engines[name]["full_search_module"] = (
entry.full_search_module
@@ -664,8 +666,9 @@ def get_available_engines(
exclude_engines: Optional[set] = None,
) -> Dict[str, Any]:
"""
- Return search engines that are actually usable: enabled for auto-search
- and with valid API keys when required.
+ Return query search engines that are actually usable: enabled for
+ auto-search and with valid API keys when required. URL-only archive
+ adapters remain in ``list_eligible_engine_configs`` for archive fetching.
This is the single shared filter used by ``auto``-mode search so the
LangGraph agent agrees with the rest of the system on which engines
@@ -694,7 +697,7 @@ def get_available_engines(
return {
name: config
for name, config in eligible.items()
- if name not in excluded
+ if name not in excluded and config.get("supports_query_search", True)
}
diff --git a/src/local_deep_research/web_search_engines/wayback_client.py b/src/local_deep_research/web_search_engines/wayback_client.py
new file mode 100644
index 0000000000..e673a3932e
--- /dev/null
+++ b/src/local_deep_research/web_search_engines/wayback_client.py
@@ -0,0 +1,215 @@
+"""URL-based Wayback availability lookup shared by archive callers."""
+
+import posixpath
+import re
+from datetime import datetime
+from urllib.parse import unquote, urlsplit
+
+from requests import Request
+
+from ..security.safe_requests import safe_get
+from ..utilities.resource_utils import safe_close
+from .rate_limiting import RateLimitError
+
+AVAILABLE_API = "https://archive.org/wayback/available"
+
+
+def _archive_target_key(url: str):
+ """Ignore scheme/www/default ports/fragments, retaining prepared path/query."""
+ prepared = Request("GET", validate_archive_url(url)).prepare().url or ""
+ parsed = urlsplit(prepared)
+ default_port = 443 if parsed.scheme == "https" else 80
+ port = parsed.port if parsed.port != default_port else None
+ return (
+ (parsed.hostname or "").removeprefix("www."),
+ port,
+ parsed.path or "/",
+ parsed.query,
+ )
+
+
+def validate_capture_fetch_url(
+ url: str, timestamp: str, expected_url: str | None = None
+) -> None:
+ """Keep page retrieval and every redirect inside the selected capture."""
+ parsed = urlsplit(url)
+ if (
+ parsed.scheme != "https"
+ or parsed.hostname != "web.archive.org"
+ or parsed.port not in {None, 443}
+ or parsed.username is not None
+ or parsed.password is not None
+ or not re.match(
+ rf"^/web/{re.escape(timestamp)}(?:id_|if_)?/https?://", parsed.path
+ )
+ ):
+ raise ValueError("Archive replay left the selected capture")
+ if expected_url is not None:
+ target = url.split(f"/web/{timestamp}", 1)[1].split("/", 1)[1]
+ if _archive_target_key(target) != _archive_target_key(expected_url):
+ raise ValueError("Archive replay changed the captured URL")
+
+
+def capture_metadata_from_replay_url(url: str) -> dict | None:
+ """Identify an exact supplied capture without an availability request.
+
+ A direct replay read needs the same boundary as a discovered capture,
+ even before any citation exists. Unsupported capture forms fail before
+ network access instead of becoming an ordinary live-page fetch.
+ """
+ parsed = urlsplit(url)
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
+ return None
+ # Detection includes the spelling Requests will send. These aliases
+ # must not fall through to an unrestricted live-page fetch, but only
+ # the original, canonical capture spelling is accepted below.
+ prepared = urlsplit(Request("GET", url).prepare().url or "")
+ if (prepared.hostname or "").rstrip(".") != "web.archive.org":
+ return None
+
+ def has_replay_path(path):
+ # Inspect the wrapper, not the embedded target's path. Decode one
+ # layer for detection only; never fetch a normalized substitute.
+ wrapper = unquote(path.split("://", 1)[0]).replace("\\", "/")
+ return any(
+ candidate.lstrip("/").partition("/")[0] == "web"
+ for candidate in (wrapper, posixpath.normpath(wrapper))
+ )
+
+ if not any(has_replay_path(path) for path in (parsed.path, prepared.path)):
+ return None
+ replay = re.match(r"^/web/([0-9]{14})(?:id_|if_)?/https?://", parsed.path)
+ if replay is None:
+ raise ValueError("Unsupported archive replay capture URL")
+ timestamp = replay.group(1)
+ captured_date = datetime.strptime(timestamp, "%Y%m%d%H%M%S")
+ target = url.split(f"/web/{timestamp}", 1)[1].split("/", 1)[1]
+ validate_archive_url(target)
+ validate_capture_fetch_url(url, timestamp, target)
+ return {
+ "source_type": "archive",
+ "original_url": target,
+ "requested_url": target,
+ "timestamp": timestamp,
+ "formatted_date": captured_date.strftime("%Y-%m-%d %H:%M:%S UTC"),
+ }
+
+
+def validate_archive_url(url: str) -> str:
+ """Require one absolute HTTP(S) URL without embedded credentials."""
+ url = url.strip()
+ if not url or any(
+ character.isspace() or ord(character) < 32 for character in url
+ ):
+ raise ValueError(
+ "Supply a single absolute HTTP(S) URL to fetch_archive"
+ )
+ parsed = urlsplit(url)
+ if (
+ parsed.scheme.lower() not in {"http", "https"}
+ or not parsed.hostname
+ or parsed.username is not None
+ or parsed.password is not None
+ ):
+ raise ValueError("Supply an absolute HTTP(S) URL without credentials")
+ # Accessing port validates malformed/non-numeric/out-of-range ports.
+ parsed.port
+ return url
+
+
+def normalize_archive_date(value: str | None) -> str | None:
+ """Convert a calendar date to the availability API's YYYYMMDD input."""
+ if value is None:
+ return None
+ if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
+ return datetime.strptime(value, "%Y-%m-%d").strftime("%Y%m%d")
+ if re.fullmatch(r"\d{8}", value):
+ return datetime.strptime(value, "%Y%m%d").strftime("%Y%m%d")
+ raise ValueError("Archive date must be a valid YYYY-MM-DD or YYYYMMDD date")
+
+
+def get_availability_response(url: str, timestamp=None, *, request_get=None):
+ """Request the fixed archive API without following redirects."""
+ params = {"url": url}
+ if timestamp is not None:
+ params["timestamp"] = timestamp
+ getter = request_get if request_get is not None else safe_get
+ return getter(
+ AVAILABLE_API, params=params, timeout=30, allow_redirects=False
+ )
+
+
+def lookup_archive_snapshot(url: str, timestamp=None, *, request_get=None):
+ """Return an accessible snapshot, preserving its actual capture time.
+
+ With no timestamp the API selects the most recent available capture;
+ otherwise it selects a capture near the requested date. Never substitute
+ the live page when the archive has no capture.
+ """
+ url = validate_archive_url(url)
+ response = get_availability_response(
+ url, timestamp, request_get=request_get
+ )
+ try:
+ if response.status_code == 429:
+ raise RateLimitError(
+ "Wayback archive lookup rate limit exceeded",
+ retry_after=response.headers.get("Retry-After"),
+ )
+ response.raise_for_status()
+ if response.status_code != 200:
+ raise ValueError(
+ "Archive availability API returned an unexpected status"
+ )
+ data = response.json()
+ if not isinstance(data, dict) or not isinstance(
+ data.get("archived_snapshots"), dict
+ ):
+ raise ValueError("Invalid archive availability response")
+ closest = data["archived_snapshots"].get("closest")
+ if closest is None:
+ return None
+ if not isinstance(closest, dict):
+ raise ValueError("Invalid archive snapshot")
+ if (
+ closest.get("available") is not True
+ or str(closest.get("status")) != "200"
+ ):
+ return None
+ captured = closest.get("timestamp")
+ if not isinstance(captured, str) or not re.fullmatch(
+ r"\d{14}", captured
+ ):
+ raise ValueError("Invalid archive capture timestamp")
+ captured_date = datetime.strptime(captured, "%Y%m%d%H%M%S")
+ replay = closest.get("url")
+ if not isinstance(replay, str):
+ raise ValueError("Invalid archive replay URL")
+ parsed = urlsplit(replay)
+ prefix = f"/web/{captured}/"
+ if (
+ parsed.scheme.lower() not in {"http", "https"}
+ or parsed.hostname != "web.archive.org"
+ or parsed.port not in {None, 443, 80}
+ or parsed.username is not None
+ or parsed.password is not None
+ or not parsed.path.startswith(prefix)
+ ):
+ raise ValueError("Invalid archive replay URL")
+ # Preserve the embedded target's query, punctuation and fragment.
+ embedded = replay.split(prefix, 1)[1]
+ validate_archive_url(embedded)
+ if _archive_target_key(embedded) != _archive_target_key(url):
+ raise ValueError("Archive capture does not match the requested URL")
+ replay = "https://web.archive.org" + replay[replay.index(prefix) :]
+ return {
+ "original_url": embedded,
+ "requested_url": url,
+ "url": replay,
+ "timestamp": captured,
+ "formatted_date": captured_date.strftime("%Y-%m-%d %H:%M:%S UTC"),
+ "available": True,
+ "status": "200",
+ }
+ finally:
+ safe_close(response, "Wayback availability response")
diff --git a/tests/advanced_search_system/tools/test_archive_fetch.py b/tests/advanced_search_system/tools/test_archive_fetch.py
new file mode 100644
index 0000000000..7ff9507869
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_archive_fetch.py
@@ -0,0 +1,2667 @@
+"""Offline archive lookup and fetch behavior through the real tool pipeline."""
+
+from contextlib import nullcontext
+from functools import partial
+from io import BytesIO
+import uuid
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock
+
+import pytest
+import requests
+from pydantic import ValidationError
+
+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+)
+from local_deep_research.advanced_search_system.tools import archive
+from local_deep_research.advanced_search_system.tools.fetch import (
+ FETCH_MODES,
+ build_fetch_tool,
+)
+from local_deep_research.security import clear_active_context
+from local_deep_research.security.egress import policy
+from local_deep_research.web_search_engines import wayback_client
+from local_deep_research.web_search_engines.engine_availability import (
+ SearchEngineAvailability,
+)
+from local_deep_research.web_search_engines.rate_limiting import RateLimitError
+
+
+ORIGINAL = "https://example.com/history"
+CAPTURED = "20240203112233"
+FORMATTED_DATE = "2024-02-03 11:22:33 UTC"
+API = "https://archive.org/wayback/available"
+REPLAY = f"https://web.archive.org/web/{CAPTURED}/{ORIGINAL}"
+_SESSION_REQUEST = requests.sessions.Session.request
+
+
+MISMATCHED_TARGETS = [
+ pytest.param(
+ ORIGINAL, "https://unrelated.example/history", id="other_host"
+ ),
+ pytest.param(ORIGINAL, "https://example.com/other", id="other_path"),
+ pytest.param(ORIGINAL, "https://example.com/History", id="path_case"),
+ pytest.param(
+ ORIGINAL + "?version=1", ORIGINAL + "?version=2", id="query_value"
+ ),
+ pytest.param(
+ ORIGINAL + "?a=1&b=2", ORIGINAL + "?b=2&a=1", id="query_order"
+ ),
+ pytest.param(
+ ORIGINAL + "?next=https%3A%2F%2Fother.example%2Fa",
+ ORIGINAL + "?next=https://other.example/a",
+ id="literal_query_encoding",
+ ),
+ pytest.param(
+ "https://example.com:8443/history",
+ "https://example.com:8444/history",
+ id="nondefault_port",
+ ),
+ pytest.param(
+ ORIGINAL,
+ "http://example.com:443/history",
+ id="wrong_scheme_default_port",
+ ),
+]
+
+
+CANONICAL_TARGETS = [
+ pytest.param("http://example.com/history", ORIGINAL, id="http_to_https"),
+ pytest.param(ORIGINAL, "http://example.com/history", id="https_to_http"),
+ pytest.param(
+ "https://example.com:443/history", ORIGINAL, id="https_default_port"
+ ),
+ pytest.param(
+ "http://example.com:80/history",
+ "http://example.com/history",
+ id="http_default_port",
+ ),
+ pytest.param("https://www.example.com/history", ORIGINAL, id="remove_www"),
+ pytest.param(ORIGINAL, "https://www.example.com/history", id="add_www"),
+ pytest.param(
+ "HTTPS://WWW.Example.com:443/history", ORIGINAL, id="host_case"
+ ),
+ pytest.param(
+ "https://example.com", "https://example.com/", id="empty_to_root_path"
+ ),
+ pytest.param(
+ "https://example.com/", "https://example.com", id="root_to_empty_path"
+ ),
+ pytest.param(
+ "https://www.example.com:443?next=https://other.example/a&version=1",
+ "http://example.com:80/?next=https://other.example/a&version=1",
+ id="combined_canonicalization_preserves_query",
+ ),
+]
+
+
+def _available_payload(
+ url=ORIGINAL, *, timestamp=CAPTURED, replay=None, **overrides
+):
+ closest = {
+ "available": True,
+ "status": "200",
+ "timestamp": timestamp,
+ "url": replay or f"http://web.archive.org/web/{timestamp}/{url}",
+ }
+ closest.update(overrides)
+ return {"url": url, "archived_snapshots": {"closest": closest}}
+
+
+def _response(payload=None, *, status=200):
+ response = Mock()
+ response.status_code = status
+ response.headers = {}
+ response.json.return_value = (
+ _available_payload() if payload is None else payload
+ )
+ return response
+
+
[email protected](autouse=True)
+def _offline(monkeypatch):
+ clear_active_context()
+ monkeypatch.setattr(
+ requests.sessions.Session,
+ "request",
+ Mock(side_effect=AssertionError("Unexpected outbound request")),
+ )
+ yield
+ clear_active_context()
+
+
+def runtime(monkeypatch):
+ """Only HTTP, content extraction, and the summary model are substitutes."""
+ response = _response()
+ getter = Mock(return_value=response)
+ monkeypatch.setattr(wayback_client, "safe_get", getter)
+ fetcher = MagicMock()
+ fetcher.fetch.return_value = {
+ "status": "success",
+ "title": "Historical page",
+ "content": "Archived evidence from the selected capture.",
+ }
+ cm = MagicMock()
+ cm.__enter__.return_value = fetcher
+ cm.__exit__.return_value = False
+ factory = Mock(return_value=cm)
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", factory
+ )
+ model = Mock()
+ model.invoke.return_value = SimpleNamespace(content="The archived fact.")
+ return SimpleNamespace(
+ response=response,
+ getter=getter,
+ fetcher=fetcher,
+ factory=factory,
+ model=model,
+ )
+
+
+def _arguments(mode, *, url=ORIGINAL, **extra):
+ arguments = {"url": url, **extra}
+ if mode != "full":
+ arguments["focus"] = "What did the page say at that time?"
+ return arguments
+
+
+def _assert_source(collector, *, replay=REPLAY, timestamp=CAPTURED):
+ assert len(collector.results) == 1
+ source = collector.results[0]
+ assert source["link"] == replay
+ assert source["original_url"] == ORIGINAL
+ assert source["requested_url"] == ORIGINAL
+ assert source["timestamp"] == timestamp
+ assert source["formatted_date"] == FORMATTED_DATE
+ assert source["source_type"] == "archive"
+ assert collector.find_by_index(int(source["index"]))["link"] == replay
+ assert collector.find_by_url(ORIGINAL) is None
+ return source
+
+
[email protected]("timestamp", [None, "20240115"])
+def test_lookup_uses_fixed_https_api_and_preserves_actual_capture(timestamp):
+ response = _response()
+ getter = Mock(return_value=response)
+
+ snapshot = wayback_client.lookup_archive_snapshot(
+ ORIGINAL, timestamp, request_get=getter
+ )
+
+ params = {"url": ORIGINAL}
+ if timestamp is not None:
+ params["timestamp"] = timestamp
+ getter.assert_called_once_with(
+ API, params=params, timeout=30, allow_redirects=False
+ )
+ assert snapshot == {
+ "original_url": ORIGINAL,
+ "requested_url": ORIGINAL,
+ "url": REPLAY,
+ "timestamp": CAPTURED,
+ "formatted_date": FORMATTED_DATE,
+ "available": True,
+ "status": "200",
+ }
+ response.close.assert_called_once()
+
+
[email protected](("requested", "actual"), MISMATCHED_TARGETS)
+def test_lookup_provenance_rejects_unrelated_replay_target(requested, actual):
+ replay = f"http://web.archive.org/web/{CAPTURED}/{actual}"
+ response = _response(_available_payload(requested, replay=replay))
+ getter = Mock(return_value=response)
+
+ with pytest.raises(ValueError, match="requested URL"):
+ wayback_client.lookup_archive_snapshot(requested, request_get=getter)
+
+ getter.assert_called_once_with(
+ API, params={"url": requested}, timeout=30, allow_redirects=False
+ )
+ response.close.assert_called_once()
+
+
[email protected](("requested", "actual"), MISMATCHED_TARGETS)
[email protected]("mode", ["full", "summary_focus_query"])
+def test_archive_provenance_mismatch_never_fetches_or_registers_source(
+ requested, actual, mode, runtime
+):
+ replay = f"http://web.archive.org/web/{CAPTURED}/{actual}"
+ runtime.response.json.return_value = _available_payload(
+ requested, replay=replay
+ )
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode, collector, model=runtime.model
+ )
+
+ output = tool.invoke(_arguments(mode, url=requested))
+
+ assert not output.startswith("[1]")
+ assert "requested URL" in output
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ runtime.factory.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
[email protected](("requested", "actual"), CANONICAL_TARGETS)
+def test_lookup_canonical_target_keeps_actual_and_requested_urls(
+ requested, actual
+):
+ response = _response(
+ _available_payload(
+ requested, replay=f"http://web.archive.org/web/{CAPTURED}/{actual}"
+ )
+ )
+ getter = Mock(return_value=response)
+
+ snapshot = wayback_client.lookup_archive_snapshot(
+ requested, request_get=getter
+ )
+
+ assert snapshot["original_url"] == actual
+ assert snapshot["requested_url"] == requested
+ assert snapshot["url"] == f"https://web.archive.org/web/{CAPTURED}/{actual}"
+ assert snapshot["timestamp"] == CAPTURED
+ assert snapshot["formatted_date"] == FORMATTED_DATE
+ getter.assert_called_once_with(
+ API, params={"url": requested}, timeout=30, allow_redirects=False
+ )
+ response.close.assert_called_once()
+
+
[email protected](("requested", "actual"), CANONICAL_TARGETS)
[email protected]("mode", ["full", "summary_focus_query"])
+def test_archive_canonical_target_keeps_actual_provenance_in_citation_and_output(
+ requested, actual, mode, runtime
+):
+ replay = f"https://web.archive.org/web/{CAPTURED}/{actual}"
+ runtime.response.json.return_value = _available_payload(
+ requested, replay=replay
+ )
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode, collector, model=runtime.model
+ )
+
+ output = tool.invoke(_arguments(mode, url=requested))
+
+ assert output.startswith("[1] ")
+ assert f"URL: {replay}" in output
+ assert f"Original URL: {actual}" in output
+ assert f"Requested URL: {requested}" in output
+ assert len(collector.results) == 1
+ source = collector.results[0]
+ assert source["link"] == replay
+ assert source["original_url"] == actual
+ assert source["requested_url"] == requested
+ assert source["source_type"] == "archive"
+ assert source["timestamp"] == CAPTURED
+ assert source["formatted_date"] == FORMATTED_DATE
+ assert collector.find_by_index(1)["original_url"] == actual
+ assert collector.find_by_index(1)["requested_url"] == requested
+ assert collector.fetch_count == 1
+ runtime.fetcher.fetch.assert_called_once_with(replay, max_length=10_000)
+ assert runtime.getter.call_args.kwargs["params"]["url"] == requested
+
+
[email protected]("first_kind", ["ordinary", "archive"])
+def test_regular_fetch_preserves_existing_archive_citation_metadata(
+ first_kind, runtime
+):
+ actual = "http://www.example.com:80/history"
+ replay = f"https://web.archive.org/web/{CAPTURED}/{actual}"
+ runtime.response.json.return_value = _available_payload(
+ ORIGINAL, replay=replay
+ )
+ collector = SearchResultsCollector([])
+ ordinary = build_fetch_tool("full", collector, max_fetches=3)
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=3
+ )
+ if first_kind == "ordinary":
+ assert ordinary.invoke({"url": replay}).startswith("[1] ")
+
+ assert archived.invoke({"url": ORIGINAL}).startswith("[1] ")
+ metadata = {
+ "source_type": "archive",
+ "original_url": actual,
+ "requested_url": ORIGINAL,
+ "timestamp": CAPTURED,
+ "formatted_date": FORMATTED_DATE,
+ }
+ assert all(
+ collector.find_by_index(1)[key] == value
+ for key, value in metadata.items()
+ )
+
+ output = ordinary.invoke({"url": replay})
+
+ assert output.startswith("[1] ")
+ assert len(collector.results) == 1
+ assert collector.results[0]["link"] == replay
+ assert all(
+ collector.results[0][key] == value for key, value in metadata.items()
+ )
+ assert collector.fetch_count == (3 if first_kind == "ordinary" else 2)
+ runtime.getter.assert_called_once()
+
+
+ "payload",
+ [
+ {"archived_snapshots": {}},
+ _available_payload(available=False),
+ _available_payload(status="404"),
+ _available_payload(status="500"),
+ ],
+ ids=["no_capture", "unavailable", "archived_404", "archived_500"],
+)
+def test_unavailable_lookup_returns_none_and_never_fetches_live(payload):
+ response = _response(payload)
+ getter = Mock(return_value=response)
+
+ assert (
+ wayback_client.lookup_archive_snapshot(ORIGINAL, request_get=getter)
+ is None
+ )
+ getter.assert_called_once_with(
+ API, params={"url": ORIGINAL}, timeout=30, allow_redirects=False
+ )
+ response.close.assert_called_once()
+
+
+MALFORMED_PAYLOADS = [
+ pytest.param([], id="non_object_response"),
+ pytest.param({}, id="missing_snapshots"),
+ pytest.param({"archived_snapshots": []}, id="non_object_snapshots"),
+ pytest.param(
+ {"archived_snapshots": {"closest": []}}, id="non_object_capture"
+ ),
+ pytest.param(
+ _available_payload(timestamp="20240203"), id="short_timestamp"
+ ),
+ pytest.param(
+ _available_payload(timestamp="20240230112233"), id="impossible_capture"
+ ),
+ pytest.param(_available_payload(timestamp=None), id="missing_timestamp"),
+ pytest.param(
+ _available_payload(
+ replay="https://example.net/web/" + CAPTURED + "/" + ORIGINAL
+ ),
+ id="foreign_replay_host",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://web.archive.org.evil.example/web/{CAPTURED}/{ORIGINAL}"
+ ),
+ id="lookalike_replay_host",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://[email protected]/web/{CAPTURED}/{ORIGINAL}"
+ ),
+ id="credentialed_replay_host",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://web.archive.org:8443/web/{CAPTURED}/{ORIGINAL}"
+ ),
+ id="foreign_replay_port",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://web.archive.org/web/20240101000000/{ORIGINAL}"
+ ),
+ id="replay_timestamp_mismatch",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://web.archive.org/web/{CAPTURED}/ftp://example.com/file"
+ ),
+ id="unsupported_embedded_scheme",
+ ),
+ pytest.param(
+ _available_payload(
+ replay=f"https://web.archive.org/web/{CAPTURED}/https://user:[email protected]/"
+ ),
+ id="credentialed_embedded_target",
+ ),
+ pytest.param(
+ _available_payload(replay=f"https://web.archive.org/web/{CAPTURED}/"),
+ id="missing_embedded_target",
+ ),
+ pytest.param(_available_payload(replay=API), id="api_is_not_replay"),
+]
+
+
[email protected]("payload", MALFORMED_PAYLOADS)
+def test_malformed_lookup_closes_response_and_rejects_capture(payload):
+ response = _response(payload)
+ getter = Mock(return_value=response)
+
+ with pytest.raises(ValueError):
+ wayback_client.lookup_archive_snapshot(ORIGINAL, request_get=getter)
+
+ getter.assert_called_once()
+ response.close.assert_called_once()
+
+
+def test_lookup_429_is_rate_limit_and_closes_response():
+ response = _response(status=429)
+ response.headers = {"Retry-After": "120"}
+ getter = Mock(return_value=response)
+
+ with pytest.raises(RateLimitError):
+ wayback_client.lookup_archive_snapshot(ORIGINAL, request_get=getter)
+
+ response.json.assert_not_called()
+ response.close.assert_called_once()
+ getter.assert_called_once()
+
+
[email protected]("status", [302, 503])
+def test_lookup_does_not_follow_failed_or_redirected_api(status):
+ response = _response(status=status)
+ if status == 503:
+ response.raise_for_status.side_effect = requests.HTTPError("HTTP 503")
+ getter = Mock(return_value=response)
+
+ with pytest.raises((ValueError, requests.HTTPError)):
+ wayback_client.lookup_archive_snapshot(ORIGINAL, request_get=getter)
+
+ response.json.assert_not_called()
+ response.close.assert_called_once()
+ assert getter.call_args.kwargs["allow_redirects"] is False
+
+
+def test_disabled_mode_returns_none_without_work(runtime):
+ assert (
+ archive.build_archive_fetch_tool("disabled", SearchResultsCollector([]))
+ is None
+ )
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+def test_archive_schema_matches_fetch_mode(mode, runtime):
+ tool = archive.build_archive_fetch_tool(
+ mode, SearchResultsCollector([]), model=runtime.model
+ )
+
+ assert tool.name == "fetch_archive"
+ assert set(tool.args) == (
+ {"url", "date"} if mode == "full" else {"url", "date", "focus"}
+ )
+ schema = tool.args_schema.model_json_schema()
+ assert set(schema["required"]) == (
+ {"url"} if mode == "full" else {"url", "focus"}
+ )
+ assert schema["properties"]["date"]["default"] is None
+ if mode != "full":
+ with pytest.raises(ValidationError):
+ tool.invoke({"url": ORIGINAL})
+ runtime.getter.assert_not_called()
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
+def test_summary_archive_requires_model(mode, runtime):
+ with pytest.raises(ValueError, match="requires a model"):
+ archive.build_archive_fetch_tool(mode, SearchResultsCollector([]))
+ runtime.getter.assert_not_called()
+
+
+def test_unknown_archive_mode_is_rejected(runtime):
+ with pytest.raises(ValueError, match="Unknown fetch mode"):
+ archive.build_archive_fetch_tool("unknown", SearchResultsCollector([]))
+ runtime.getter.assert_not_called()
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
[email protected]("date", [None, "2024-01-15", "20240115", "2024-02-29"])
+def test_successful_archive_fetch_keeps_replay_citation_and_nearest_date(
+ mode, date, runtime
+):
+ collector = SearchResultsCollector([])
+ overall_query = "How did the policy change over time?"
+ tool = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ overall_query=overall_query,
+ max_fetches=1,
+ )
+ arguments = _arguments(mode)
+ if date is not None:
+ arguments["date"] = date
+
+ output = tool.invoke(arguments)
+
+ assert output.startswith("[1] ")
+ assert f"URL: {REPLAY}" in output
+ assert FORMATTED_DATE in output
+ assert ORIGINAL in output
+ assert "Requested URL:" not in output
+ _assert_source(collector)
+ params = {"url": ORIGINAL}
+ if date is not None:
+ params["timestamp"] = date.replace("-", "")
+ assert date in output
+ runtime.getter.assert_called_once_with(
+ API, params=params, timeout=30, allow_redirects=False
+ )
+ runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ assert collector.fetch_count == 1
+ if mode == "full":
+ assert "Archived evidence" in output
+ runtime.model.invoke.assert_not_called()
+ else:
+ assert "The archived fact." in output
+ prompt = runtime.model.invoke.call_args.args[0]
+ assert REPLAY in prompt
+ assert "Archived evidence" in prompt
+ assert arguments["focus"] in prompt
+ if mode == "summary_focus":
+ assert "Overall research question" not in prompt
+ assert overall_query not in prompt
+ else:
+ assert f"Overall research question: {overall_query}" in prompt
+
+
+ "url",
+ [
+ "https://example.com/wiki/Foo_(bar)",
+ "https://example.com/path,segment;version?values=a,b;c",
+ "https://example.com/page?next=https://other.example/a?x=1&y=2#part",
+ "https://example.com:8443/path)?q=%2F%3F%26&next=https://other.example/a",
+ ],
+)
+def test_absolute_url_punctuation_and_nested_query_are_preserved(url, runtime):
+ runtime.response.json.return_value = _available_payload(url)
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector)
+
+ output = tool.invoke({"url": url})
+
+ replay = f"https://web.archive.org/web/{CAPTURED}/{url}"
+ assert runtime.getter.call_args.kwargs["params"]["url"] == url
+ runtime.fetcher.fetch.assert_called_once_with(replay, max_length=10_000)
+ assert collector.results[0]["original_url"] == url
+ assert collector.results[0]["requested_url"] == url
+ assert collector.results[0]["link"] == replay
+ assert f"URL: {replay}" in output
+
+
+ "url",
+ [
+ "",
+ "historical information about a topic",
+ "example.com/page",
+ "https:///missing-host",
+ "ftp://example.com/file",
+ "file:///etc/passwd",
+ "https://user:[email protected]/page",
+ "https://example.com:bad/page",
+ "https://example.com:99999/page",
+ "https://example.com/path with spaces",
+ ],
+)
+def test_invalid_original_url_never_uses_budget_or_transport(url, runtime):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector)
+
+ output = tool.invoke({"url": url})
+
+ assert not output.startswith("[1]")
+ assert "secret" not in output
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
+ "date",
+ [
+ "",
+ "2024",
+ "2024-2-03",
+ "2024-13-01",
+ "2023-02-29",
+ "20240230",
+ "2024-01-01T00:00:00",
+ "20240203112233",
+ ],
+)
+def test_invalid_calendar_date_never_uses_budget_or_transport(date, runtime):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector)
+
+ output = tool.invoke({"url": ORIGINAL, "date": date})
+
+ assert not output.startswith("[1]")
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
[email protected]("payload", MALFORMED_PAYLOADS)
+def test_malformed_snapshot_does_not_fetch_or_register_live_page(
+ payload, runtime
+):
+ runtime.response.json.return_value = payload
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector, max_fetches=1)
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ assert not output.startswith("[1]")
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ runtime.factory.assert_not_called()
+
+
+ "failure", ["no_capture", "unavailable", "429", "bad_json", "connection"]
+)
+def test_lookup_failure_consumes_one_slot_and_never_falls_back(
+ failure, runtime
+):
+ if failure == "no_capture":
+ runtime.response.json.return_value = {"archived_snapshots": {}}
+ elif failure == "unavailable":
+ runtime.response.json.return_value = _available_payload(available=False)
+ elif failure == "429":
+ runtime.response.status_code = 429
+ elif failure == "bad_json":
+ runtime.response.json.side_effect = ValueError("Invalid JSON")
+ else:
+ runtime.getter.side_effect = requests.ConnectionError(
+ "Archive unavailable"
+ )
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector, max_fetches=1)
+
+ first = tool.invoke({"url": ORIGINAL})
+ second = tool.invoke({"url": ORIGINAL, "date": "2024-01-01"})
+
+ assert not first.startswith("[1]")
+ assert "budget exhausted" in second.lower()
+ assert collector.fetch_count == 1
+ assert collector.results == []
+ runtime.getter.assert_called_once()
+ runtime.factory.assert_not_called()
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
[email protected]("empty_stage", ["content", "summary"])
+def test_empty_archive_content_or_summary_does_not_register_source(
+ mode, empty_stage, runtime
+):
+ if empty_stage == "content":
+ runtime.fetcher.fetch.return_value["content"] = " \n\t "
+ else:
+ runtime.model.invoke.return_value.content = " \n\t "
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode, collector, model=runtime.model, max_fetches=1
+ )
+
+ output = tool.invoke(_arguments(mode))
+
+ assert "NOT RELEVANT" in output
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ if empty_stage == "content":
+ runtime.model.invoke.assert_not_called()
+ else:
+ runtime.model.invoke.assert_called_once()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
[email protected]("failure", ["result", "exception"])
+def test_replay_fetch_failure_never_substitutes_live_original(
+ mode, failure, runtime
+):
+ if failure == "result":
+ runtime.fetcher.fetch.return_value = {
+ "status": "error",
+ "error": "HTTP 404",
+ }
+ else:
+ runtime.fetcher.fetch.side_effect = requests.ConnectionError(
+ "Replay unavailable"
+ )
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode, collector, model=runtime.model
+ )
+
+ output = tool.invoke(_arguments(mode))
+
+ assert not output.startswith("[1]")
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.model.invoke.assert_not_called()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+def test_archive_delegates_settings_limits_and_metadata_to_shared_fetch(
+ mode, runtime, monkeypatch
+):
+ settings = {
+ "search.fetch.content_max_length": {"value": 3000},
+ "web.enable_javascript_rendering": {
+ "value": True,
+ "ui_element": "checkbox",
+ },
+ }
+ context = object()
+ monkeypatch.setattr(
+ archive,
+ "evaluate_engine",
+ Mock(return_value=policy.Decision(True, "allowed")),
+ )
+ monkeypatch.setattr(
+ policy,
+ "evaluate_url",
+ Mock(return_value=policy.Decision(True, "allowed")),
+ )
+ delegate = Mock(wraps=build_fetch_tool)
+ monkeypatch.setattr(archive, "build_fetch_tool", delegate)
+ body = "A" * 4000 + "EXCLUDED_TRAILING_EVIDENCE"
+ runtime.fetcher.fetch.side_effect = lambda url, *, max_length: {
+ "status": "success",
+ "title": "Historical page",
+ "content": body[:max_length],
+ }
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ overall_query="Original question",
+ settings_snapshot=settings,
+ egress_context=context,
+ max_fetches=1,
+ subagent_id="archive_worker",
+ )
+
+ output = tool.invoke(_arguments(mode))
+
+ runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=3000)
+ assert runtime.factory.call_args.kwargs["enable_js_rendering"] is True
+ assert runtime.factory.call_args.kwargs["egress_context"] is context
+ assert "EXCLUDED_TRAILING_EVIDENCE" not in output
+ if mode == "full":
+ assert "A" * 3000 in output
+ assert "A" * 3001 not in output
+ else:
+ prompt = runtime.model.invoke.call_args.args[0]
+ assert "A" * 3000 in prompt
+ assert "A" * 3001 not in prompt
+ assert "EXCLUDED_TRAILING_EVIDENCE" not in prompt
+ delegate.assert_called_once()
+ assert delegate.call_args.args == (mode, collector)
+ kwargs = delegate.call_args.kwargs
+ assert kwargs["record_fetch"] is False
+ assert kwargs["settings_snapshot"] is settings
+ assert kwargs["model"] is runtime.model
+ assert kwargs["overall_query"] == "Original question"
+ assert kwargs["egress_context"] is context
+ assert kwargs["subagent_id"] == "archive_worker"
+ assert kwargs["max_fetches"] == 1
+ assert kwargs["source_metadata"] == {
+ "source_type": "archive",
+ "original_url": ORIGINAL,
+ "requested_url": ORIGINAL,
+ "timestamp": CAPTURED,
+ "formatted_date": FORMATTED_DATE,
+ }
+ _assert_source(collector)
+ assert collector.fetch_count == 1
+ assert collector.get_fetch_count("archive_worker") == 1
+
+
[email protected]("first_kind", ["archive", "ordinary"])
+def test_archive_and_ordinary_fetch_use_the_same_quota(first_kind, runtime):
+ collector = SearchResultsCollector([])
+ tools = {
+ "archive": archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=1
+ ),
+ "ordinary": build_fetch_tool("full", collector, max_fetches=1),
+ }
+ second_kind = "ordinary" if first_kind == "archive" else "archive"
+
+ first = tools[first_kind].invoke({"url": ORIGINAL})
+ second = tools[second_kind].invoke({"url": ORIGINAL})
+
+ assert first.startswith("[1] ")
+ assert "budget exhausted" in second.lower()
+ assert collector.fetch_count == 1
+ runtime.fetcher.fetch.assert_called_once()
+ assert runtime.getter.call_count == (1 if first_kind == "archive" else 0)
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+def test_successful_archive_uses_one_slot_and_exhaustion_prevents_lookup(
+ mode, runtime
+):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode, collector, model=runtime.model, max_fetches=1
+ )
+
+ first = tool.invoke(_arguments(mode))
+ second = tool.invoke(_arguments(mode, date="2024-01-01"))
+
+ assert first.startswith("[1] ")
+ assert "budget exhausted" in second.lower()
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ runtime.fetcher.fetch.assert_called_once()
+
+
[email protected]("limit", [1, {"value": 1}])
+def test_archive_reads_shared_budget_from_settings(limit, runtime):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full",
+ collector,
+ settings_snapshot={"search.fetch.max_per_topic": limit},
+ )
+
+ assert tool.invoke({"url": ORIGINAL}).startswith("[1] ")
+ assert "budget exhausted" in tool.invoke({"url": ORIGINAL}).lower()
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+
+
+def test_explicit_unlimited_archive_budget_overrides_settings(runtime):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full",
+ collector,
+ max_fetches=0,
+ settings_snapshot={"search.fetch.max_per_topic": 1},
+ )
+
+ for _ in range(3):
+ assert tool.invoke({"url": ORIGINAL}).startswith("[1] ")
+
+ assert collector.fetch_count == 3
+ assert runtime.getter.call_count == runtime.fetcher.fetch.call_count == 3
+
+
+def test_subagent_archive_budget_is_shared_with_its_ordinary_fetch_only(
+ runtime,
+):
+ collector = SearchResultsCollector([])
+ lead = build_fetch_tool(
+ "full", collector, max_fetches=1, subagent_id="lead"
+ )
+ worker_archive = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=1, subagent_id="worker"
+ )
+ worker_ordinary = build_fetch_tool(
+ "full", collector, max_fetches=1, subagent_id="worker"
+ )
+
+ assert lead.invoke({"url": ORIGINAL}).startswith("[1] ")
+ assert worker_archive.invoke({"url": ORIGINAL}).startswith("[2] ")
+ assert (
+ "budget exhausted" in worker_ordinary.invoke({"url": ORIGINAL}).lower()
+ )
+ assert collector.get_fetch_count("lead") == 1
+ assert collector.get_fetch_count("worker") == 1
+ assert collector.fetch_count == 2
+ assert runtime.fetcher.fetch.call_count == 2
+ runtime.getter.assert_called_once()
+
+
+def test_distinct_snapshots_of_same_original_have_distinct_citations(runtime):
+ second_timestamp = "20250304123456"
+ runtime.response.json.side_effect = [
+ _available_payload(),
+ _available_payload(timestamp=second_timestamp),
+ ]
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector, max_fetches=2)
+
+ first = tool.invoke({"url": ORIGINAL, "date": "2024-02-01"})
+ second = tool.invoke({"url": ORIGINAL, "date": "2025-03-01"})
+
+ assert first.startswith("[1] ")
+ assert second.startswith("[2] ")
+ assert len(collector.results) == 2
+ assert [source["timestamp"] for source in collector.results] == [
+ CAPTURED,
+ second_timestamp,
+ ]
+ assert [source["link"] for source in collector.results] == [
+ REPLAY,
+ f"https://web.archive.org/web/{second_timestamp}/{ORIGINAL}",
+ ]
+ assert len(set(collector.sources)) == 2
+ assert all(
+ source["original_url"] == ORIGINAL for source in collector.results
+ )
+ assert all(
+ source["source_type"] == "archive" for source in collector.results
+ )
+ assert collector.results[1]["formatted_date"] == "2025-03-04 12:34:56 UTC"
+ assert collector.fetch_count == 2
+
+
+ "flag", [False, 0, "0", "false", "off", "no", " false "]
+)
[email protected]("wrapped", [False, True], ids=["raw", "wrapped"])
+def test_agent_enabled_flag_hides_archive_tool(flag, wrapped, runtime):
+ setting = {"value": flag, "ui_element": "checkbox"} if wrapped else flag
+ assert (
+ archive.build_archive_fetch_tool(
+ "full",
+ SearchResultsCollector([]),
+ settings_snapshot={
+ "search.engine.web.wayback.agent_enabled": setting
+ },
+ )
+ is None
+ )
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
+def test_builder_policy_denial_hides_archive_tool(runtime, monkeypatch):
+ context = object()
+ gate = Mock(return_value=policy.Decision(False, "scope_mismatch"))
+ monkeypatch.setattr(archive, "evaluate_engine", gate)
+
+ assert (
+ archive.build_archive_fetch_tool(
+ "full", SearchResultsCollector([]), egress_context=context
+ )
+ is None
+ )
+
+ assert gate.call_args.args == ("wayback", context)
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
+def test_engine_policy_is_rechecked_before_each_archive_call(
+ runtime, monkeypatch
+):
+ context = object()
+ gate = Mock(return_value=policy.Decision(True, "allowed"))
+ monkeypatch.setattr(archive, "evaluate_engine", gate)
+ url_gate = Mock(return_value=policy.Decision(True, "allowed"))
+ monkeypatch.setattr(policy, "evaluate_url", url_gate)
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full", collector, egress_context=context
+ )
+ gate.return_value = policy.Decision(False, "scope_mismatch")
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ assert "egress policy" in output.lower()
+ assert gate.call_count == 2
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+ url_gate.assert_not_called()
+
+
[email protected]("denied_url", [None, ORIGINAL, API, REPLAY])
+def test_url_policy_gates_before_lookup_and_replay_transport(
+ denied_url, runtime, monkeypatch
+):
+ context = object()
+ events = []
+ monkeypatch.setattr(
+ archive,
+ "evaluate_engine",
+ Mock(return_value=policy.Decision(True, "allowed")),
+ )
+
+ def evaluate_url(url, ctx):
+ assert ctx is context
+ events.append(("gate", url))
+ return policy.Decision(
+ url != denied_url,
+ "scope_mismatch" if url == denied_url else "allowed",
+ )
+
+ def get(*args, **kwargs):
+ events.append(("lookup", args[0]))
+ return runtime.response
+
+ def fetch(url, **kwargs):
+ events.append(("fetch", url))
+ return {
+ "status": "success",
+ "title": "Page",
+ "content": "Archived evidence",
+ }
+
+ monkeypatch.setattr(policy, "evaluate_url", evaluate_url)
+ runtime.getter.side_effect = get
+ runtime.fetcher.fetch.side_effect = fetch
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full", collector, egress_context=context
+ )
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ if denied_url in {ORIGINAL, API}:
+ assert collector.fetch_count == 0
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+ else:
+ assert collector.fetch_count == 1
+ assert events.index(("gate", ORIGINAL)) < events.index(("lookup", API))
+ assert events.index(("gate", API)) < events.index(("lookup", API))
+ runtime.getter.assert_called_once()
+ if denied_url == REPLAY:
+ runtime.factory.assert_not_called()
+ else:
+ assert events.index(("gate", REPLAY)) < events.index(
+ ("fetch", REPLAY)
+ )
+ assert output.startswith("[1] ")
+ if denied_url is not None:
+ assert "egress policy" in output.lower()
+ assert collector.results == []
+
+
+def test_redirected_original_inside_capture_is_also_policy_gated(
+ runtime, monkeypatch
+):
+ redirected = "http://www.example.com:80/history"
+ replay = f"https://web.archive.org/web/{CAPTURED}/{redirected}"
+ runtime.response.json.return_value = _available_payload(replay=replay)
+ context = object()
+ monkeypatch.setattr(
+ archive,
+ "evaluate_engine",
+ Mock(return_value=policy.Decision(True, "allowed")),
+ )
+ urls = []
+
+ def evaluate_url(url, ctx):
+ urls.append(url)
+ return policy.Decision(
+ url != redirected,
+ "scope_mismatch" if url == redirected else "allowed",
+ )
+
+ monkeypatch.setattr(policy, "evaluate_url", evaluate_url)
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full", collector, egress_context=context
+ )
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ assert "egress policy" in output.lower()
+ assert urls == [ORIGINAL, API, redirected]
+ assert collector.fetch_count == 1
+ assert collector.results == []
+ runtime.getter.assert_called_once()
+ runtime.factory.assert_not_called()
+
+
+def test_archive_cooldown_is_shared_and_prevents_new_lookup(runtime):
+ availability = SearchEngineAvailability()
+ collector = SearchResultsCollector([])
+ runtime.response.status_code = 429
+ runtime.response.headers = {"Retry-After": "120"}
+ first_tool = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=2, availability=availability
+ )
+ second_tool = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=2, availability=availability
+ )
+
+ first = first_tool.invoke({"url": ORIGINAL})
+ second = second_tool.invoke({"url": ORIGINAL, "date": "2024-01-01"})
+
+ assert not first.startswith("[1]")
+ assert not second.startswith("[1]")
+ assert availability.state("wayback") is not None
+ assert collector.fetch_count == 1
+ assert collector.results == []
+ runtime.getter.assert_called_once()
+ runtime.factory.assert_not_called()
+
+
+def scripted_transport(monkeypatch):
+ """Use real Requests redirect handling with a completely local adapter."""
+ from local_deep_research.content_fetcher import fetcher as fetcher_module
+ from local_deep_research.security import safe_requests
+
+ routes = {}
+ sent = []
+ # Offline transport tests do not learn or wait on persisted host limits.
+ # The downloader's real retry loop still runs against the adapter.
+ rate = Mock()
+ rate.apply_rate_limit.return_value = 0
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.base.AdaptiveRateLimitTracker",
+ Mock(return_value=rate),
+ )
+ # This fixture replaces the autouse request blocker with an adapter that
+ # rejects anything not explicitly scripted. No socket or DNS is used.
+ monkeypatch.setattr(requests.sessions.Session, "request", _SESSION_REQUEST)
+ monkeypatch.setattr(
+ safe_requests.ssrf_validator, "validate_url", Mock(return_value=True)
+ )
+ monkeypatch.setattr(
+ safe_requests.dns_pinning,
+ "pinned_request",
+ lambda *args, **kwargs: nullcontext(),
+ )
+ monkeypatch.setattr(
+ fetcher_module, "policy_aware_validate_url", Mock(return_value=True)
+ )
+
+ def send(adapter, request, **kwargs):
+ sent.append(request.url)
+ assert request.url in routes, f"Unscripted request: {request.url}"
+ spec = routes[request.url]
+ if "error" in spec:
+ raise spec["error"]
+ response = requests.Response()
+ response.request = request
+ response.url = request.url
+ response.status_code = spec.get("status", 200)
+ body = spec.get("body", b"")
+ response.headers.update(
+ {
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Length": str(len(body)),
+ **spec.get("headers", {}),
+ }
+ )
+ response.encoding = "utf-8"
+ response.raw = BytesIO(body)
+ response._content = body
+ response._content_consumed = True
+ if "body_error" in spec:
+
+ class BrokenBody(BytesIO):
+ def stream(self, *args, **kwargs):
+ raise spec["body_error"]
+
+ response.raw = BrokenBody()
+ response._content = False
+ response._content_consumed = False
+ return response
+
+ monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", send)
+ return SimpleNamespace(routes=routes, sent=sent)
+
+
+DENIED_REDIRECTS = [
+ pytest.param(ORIGINAL, id="live_original"),
+ pytest.param("https://other.example/history", id="foreign_host"),
+ pytest.param(
+ REPLAY.replace("https://web.archive", "http://web.archive"),
+ id="http_downgrade",
+ ),
+ pytest.param(
+ REPLAY.replace(CAPTURED, "20240203112234"), id="different_capture"
+ ),
+]
+
+
[email protected]("redirect", DENIED_REDIRECTS)
+def test_real_safe_session_blocks_redirect_outside_selected_capture(
+ redirect, scripted_transport
+):
+ from local_deep_research.security.safe_requests import SafeSession
+
+ scripted_transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": redirect},
+ }
+ with SafeSession() as session:
+ session.url_guard = partial(
+ wayback_client.validate_capture_fetch_url,
+ timestamp=CAPTURED,
+ expected_url=ORIGINAL,
+ )
+ with pytest.raises(ValueError, match="selected capture"):
+ session.get(REPLAY, allow_redirects=True, timeout=30)
+
+ assert scripted_transport.sent == [REPLAY]
+
+
[email protected]("modifier", ["", "id_", "if_"])
+def test_real_safe_session_allows_redirect_with_same_capture_timestamp(
+ modifier, scripted_transport
+):
+ from local_deep_research.security.safe_requests import SafeSession
+
+ redirect = f"https://web.archive.org/web/{CAPTURED}{modifier}/http://www.example.com:80/history"
+ scripted_transport.routes.update(
+ {
+ REPLAY: {"status": 302, "headers": {"Location": redirect}},
+ redirect: {"body": b"Archived final page"},
+ }
+ )
+ with SafeSession() as session:
+ session.url_guard = partial(
+ wayback_client.validate_capture_fetch_url,
+ timestamp=CAPTURED,
+ expected_url=ORIGINAL,
+ )
+ with session.get(REPLAY, allow_redirects=True, timeout=30) as response:
+ assert response.status_code == 200
+ assert response.url == redirect
+ assert response.text == "Archived final page"
+
+ assert scripted_transport.sent == [REPLAY, redirect]
+
+
[email protected]("redirect", DENIED_REDIRECTS)
+def test_real_content_fetcher_archive_redirect_denial_leaves_no_citation(
+ redirect, runtime, scripted_transport, monkeypatch
+):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", ContentFetcher
+ )
+ scripted_transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": redirect},
+ }
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full",
+ collector,
+ max_fetches=1,
+ settings_snapshot={"web.enable_javascript_rendering": True},
+ )
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ assert not output.startswith("[1]")
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ assert scripted_transport.sent == [REPLAY]
+
+
[email protected]("modifier", ["", "id_", "if_"])
+def test_real_content_fetcher_extracts_same_capture_after_redirect_without_browser(
+ modifier, runtime, scripted_transport, monkeypatch
+):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", ContentFetcher
+ )
+ browser = Mock(side_effect=AssertionError("Archive must use static HTML"))
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html"
+ ".AutoHTMLDownloader",
+ browser,
+ )
+ redirect = f"https://web.archive.org/web/{CAPTURED}{modifier}/http://www.example.com:80/history"
+ paragraph = (
+ "Archived policy evidence is retained from the historical page. "
+ "The published policy describes the original service and its limits. "
+ "This capture records the information before the policy changed. "
+ )
+ html = (
+ "<html><head><title>Historical policy</title></head><body><main><article>"
+ "<h1>Historical policy</h1>"
+ + "".join(f"<p>{paragraph}</p>" for _ in range(4))
+ + '<img src="https://live-resources.example/image.png">'
+ + '<script src="https://live-resources.example/app.js"></script>'
+ + "</article></main></body></html>"
+ ).encode()
+ scripted_transport.routes.update(
+ {
+ REPLAY: {"status": 302, "headers": {"Location": redirect}},
+ redirect: {"body": html},
+ }
+ )
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full",
+ collector,
+ max_fetches=1,
+ settings_snapshot={"web.enable_javascript_rendering": True},
+ )
+
+ output = tool.invoke({"url": ORIGINAL})
+
+ assert output.startswith("[1] ")
+ assert "Archived policy evidence" in output
+ assert collector.results[0]["link"] == REPLAY
+ assert collector.results[0]["timestamp"] == CAPTURED
+ assert collector.fetch_count == 1
+ assert scripted_transport.sent[:2] == [REPLAY, redirect]
+ assert set(scripted_transport.sent) == {REPLAY, redirect}
+ runtime.getter.assert_called_once()
+ browser.assert_not_called()
+
+
[email protected](("requested", "actual"), MISMATCHED_TARGETS)
+def test_real_safe_session_blocks_same_timestamp_target_mismatch(
+ requested, actual, scripted_transport
+):
+ from local_deep_research.security.safe_requests import SafeSession
+
+ initial = f"https://web.archive.org/web/{CAPTURED}/{requested}"
+ redirect = f"https://web.archive.org/web/{CAPTURED}/{actual}"
+ scripted_transport.routes[initial] = {
+ "status": 302,
+ "headers": {"Location": redirect},
+ }
+ with SafeSession() as session:
+ session.url_guard = partial(
+ wayback_client.validate_capture_fetch_url,
+ timestamp=CAPTURED,
+ expected_url=requested,
+ )
+ with pytest.raises(ValueError, match="captured URL"):
+ session.get(initial, allow_redirects=True, timeout=30)
+
+ assert scripted_transport.sent == [initial]
+
+
[email protected](("requested", "actual"), MISMATCHED_TARGETS)
+def test_real_content_fetcher_blocks_same_timestamp_target_mismatch_without_citation(
+ requested, actual, runtime, scripted_transport, monkeypatch
+):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", ContentFetcher
+ )
+ initial = f"https://web.archive.org/web/{CAPTURED}/{requested}"
+ redirect = f"https://web.archive.org/web/{CAPTURED}/{actual}"
+ runtime.response.json.return_value = _available_payload(requested)
+ scripted_transport.routes[initial] = {
+ "status": 302,
+ "headers": {"Location": redirect},
+ }
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool("full", collector, max_fetches=1)
+
+ output = tool.invoke({"url": requested})
+
+ assert not output.startswith("[1]")
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ assert scripted_transport.sent == [initial]
+ runtime.getter.assert_called_once()
+
+
+def real_replay(runtime, scripted_transport, monkeypatch):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", ContentFetcher
+ )
+ browser = Mock(side_effect=AssertionError("Archive must use static HTML"))
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ browser,
+ )
+ return SimpleNamespace(transport=scripted_transport, browser=browser)
+
+
+def _historical_html():
+ paragraph = (
+ "Archived policy evidence describes the original service and its limits. "
+ "This historical capture records the published information before it changed. "
+ )
+ return (
+ "<html><head><title>Historical policy</title></head><body><article>"
+ + "".join(f"<p>{paragraph}</p>" for _ in range(8))
+ + "<p>ARCHIVED_FACT: the fee was 10 units.</p></article></body></html>"
+ ).encode()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "reference", ["[1]", REPLAY], ids=["citation", "replay_url"]
+)
+ "reset", [False, True], ids=["same_section", "new_section"]
+)
[email protected]("redirect", DENIED_REDIRECTS)
+def test_ordinary_reread_retains_archive_boundary(
+ mode, reference, reset, redirect, runtime, real_replay
+):
+ transport = real_replay.transport
+ transport.routes[REPLAY] = {"body": _historical_html()}
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=3
+ )
+ assert archived.invoke({"url": ORIGINAL}).startswith("[1] ")
+ original_source = collector.find_by_index(1)
+ if reset:
+ collector.reset()
+ transport.sent.clear()
+ transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": redirect},
+ }
+ transport.routes[ORIGINAL] = {"body": b"LIVE_FACT: the fee is 100 units."}
+ availability = SearchEngineAvailability()
+ ordinary = build_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ max_fetches=3,
+ availability=availability,
+ settings_snapshot={"web.enable_javascript_rendering": True},
+ )
+
+ output = ordinary.invoke(_arguments(mode, url=reference))
+
+ assert not output.startswith("[1]")
+ assert "LIVE_FACT" not in output
+ assert transport.sent == [REPLAY]
+ assert collector.find_by_index(1) == original_source
+ assert collector.fetch_count == (1 if reset else 2)
+ assert availability.state("wayback") is None
+ runtime.model.invoke.assert_not_called()
+ real_replay.browser.assert_not_called()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "reference", ["[1]", REPLAY], ids=["citation", "replay_url"]
+)
+def test_ordinary_reread_echoes_archive_provenance_in_new_section(
+ mode, reference, runtime, real_replay
+):
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.web_search_engines.wayback_client import (
+ validate_capture_fetch_url,
+ )
+
+ real_replay.transport.routes[REPLAY] = {"body": _historical_html()}
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool("full", collector)
+ assert archived.invoke({"url": ORIGINAL}).startswith("[1] ")
+ collector.reset()
+ runtime.model.invoke.return_value.content = collector.find_by_index(1)[
+ "snippet"
+ ]
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url=reference))
+
+ assert output.startswith("[1] ")
+ assert f"Captured: {FORMATTED_DATE}" in output
+ assert f"Original URL: {ORIGINAL}" in output
+ source = _assert_source(collector)
+ rendered = format_links_to_markdown(
+ collector.results, uncited_mode="disabled"
+ )
+ assert REPLAY in rendered
+ assert FORMATTED_DATE in rendered
+ validate_capture_fetch_url(source["link"], CAPTURED, source["original_url"])
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ real_replay.browser.assert_not_called()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "spec,delay,attempts",
+ [
+ ({"status": 429, "headers": {"Retry-After": "120"}}, 120, 3),
+ ({"status": 503, "headers": {"Retry-After": "120"}}, 120, 3),
+ ({"status": 403}, 300, 1),
+ (
+ {"error": requests.ConnectionError("Replay connection failed")},
+ 60,
+ 3,
+ ),
+ ({"error": requests.Timeout("Replay timed out")}, 60, 3),
+ ],
+ ids=["429", "503", "403", "connection", "timeout"],
+)
+def test_terminal_replay_outage_disables_archive_fetch_and_ordinary_rereads(
+ mode, spec, delay, attempts, runtime, real_replay
+):
+ availability = SearchEngineAvailability()
+ success = Mock(wraps=availability.record_success)
+ availability.record_success = success
+ collector = SearchResultsCollector([])
+ real_replay.transport.routes[REPLAY] = spec
+ archived = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ availability=availability,
+ max_fetches=3,
+ )
+
+ first = archived.invoke(_arguments(mode))
+ state = availability.state("wayback")
+ assert state is not None
+ assert state.failure.cooldown_seconds == delay
+ assert first.startswith("wayback")
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ assert real_replay.transport.sent == [REPLAY] * attempts
+ success.assert_not_called()
+
+ second = archived.invoke(_arguments(mode))
+ assert second == state.describe()
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ # A tracked citation must also observe this run-wide outage before
+ # using another network slot through the ordinary fetch tool.
+ collector.find_or_add_result(
+ {
+ "link": REPLAY,
+ "title": "Archived source",
+ "snippet": "Previously archived evidence",
+ "source_type": "archive",
+ "original_url": ORIGINAL,
+ "timestamp": CAPTURED,
+ },
+ engine_name="wayback",
+ )
+ ordinary = build_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ availability=availability,
+ max_fetches=3,
+ )
+ assert ordinary.invoke(_arguments(mode, url="[1]")) == state.describe()
+ assert collector.fetch_count == 1
+ assert real_replay.transport.sent == [REPLAY] * attempts
+ real_replay.browser.assert_not_called()
+
+
[email protected]("status", [404, 410])
+def test_missing_replay_is_a_document_failure_not_an_archive_outage(
+ status, runtime, real_replay
+):
+ real_replay.transport.routes[REPLAY] = {"status": status}
+ availability = SearchEngineAvailability()
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, availability=availability, max_fetches=2
+ )
+
+ for _ in range(2):
+ assert not archived.invoke({"url": ORIGINAL}).startswith("[1]")
+ assert availability.state("wayback") is None
+ assert collector.results == []
+ assert collector.fetch_count == 2
+ assert real_replay.transport.sent == [REPLAY, REPLAY]
+ assert runtime.getter.call_count == 2
+
+
+def test_healthy_lookup_does_not_reset_repeated_replay_outage_streak(
+ runtime, real_replay
+):
+ clock = [0.0]
+ # A tracker no longer ends cooldowns after a streak by default (#6930),
+ # so give it an explicit cap: a healthy availability lookup must not
+ # reset the streak of failing replay reads before that cap is reached.
+ # Production (langgraph_agent_strategy.py) builds SearchEngineAvailability
+ # without max_consecutive_cooldowns, so this pins the opt-in cap only.
+ availability = SearchEngineAvailability(
+ clock=lambda: clock[0], max_consecutive_cooldowns=3
+ )
+ collector = SearchResultsCollector([])
+ real_replay.transport.routes[REPLAY] = {
+ "status": 429,
+ "headers": {"Retry-After": "120"},
+ }
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, availability=availability, max_fetches=0
+ )
+
+ for attempt in range(4):
+ archived.invoke({"url": ORIGINAL})
+ state = availability.state("wayback")
+ assert state is not None
+ if attempt < 3:
+ assert state.deadline is not None
+ clock[0] += 121
+ else:
+ assert state.deadline is None
+ assert "3 cooldowns in a row" in state.describe()
+ assert collector.fetch_count == 4
+ assert runtime.getter.call_count == 4
+ assert real_replay.transport.sent == [REPLAY] * 12
+
+
+# A research run binds one shared content cache, and fetch paths without an
+# explicit cache resolve it. Archive reads must not use it: an entry for the
+# same replay URL can come from an unguarded fetch whose redirects left the
+# capture, and the archive tool needs the read's own transport failure.
+_CACHED_REPLAY_TEXT = "CACHED_FACT: an unguarded fetch stored this text."
+
+
+def bound_research_cache(monkeypatch):
+ """Bind a real run cache the way AdvancedSearchSystem does."""
+ from local_deep_research.utilities.research_content_cache import (
+ ResearchContentCache,
+ bind_cache_to_research,
+ unbind_cache_from_research,
+ )
+ from local_deep_research.utilities.thread_context import (
+ clear_search_context,
+ set_search_context,
+ )
+
+ research_id = f"archive-cache-{uuid.uuid4().hex}"
+ cache = ResearchContentCache()
+ bind_cache_to_research(research_id, cache)
+ set_search_context({"research_id": research_id})
+ # The fetch tool's own cache gate validates through the egress module;
+ # keep it offline like the fetcher gate that scripted_transport replaces.
+ monkeypatch.setattr(
+ "local_deep_research.security.egress.fetch.policy_aware_validate_url",
+ Mock(return_value=True),
+ )
+ yield cache
+ clear_search_context()
+ unbind_cache_from_research(research_id, cache=cache)
+
+
+def _content_counters(cache):
+ """Counters that any cached-page read, store or merged fetch changes."""
+ stats = cache.stats()
+ return {key: stats[key] for key in ("hits", "misses", "puts", "entries")}
+
+
+def _seed_replay_entry(cache):
+ # put() files the entry under content_cache_key(REPLAY), the same key
+ # every production read and store of this replay URL computes.
+ cache.put(REPLAY, _CACHED_REPLAY_TEXT, title="Cached copy", url_out=REPLAY)
+ return _content_counters(cache)
+
+
+def _capture_guard():
+ return partial(
+ wayback_client.validate_capture_fetch_url,
+ timestamp=CAPTURED,
+ expected_url=ORIGINAL,
+ )
+
+
+def test_guarded_fetcher_skips_cached_replay_and_raises_its_own_429(
+ bound_research_cache, real_replay
+):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ before = _seed_replay_entry(bound_research_cache)
+ real_replay.transport.routes[REPLAY] = {
+ "status": 429,
+ "headers": {"Retry-After": "120"},
+ }
+
+ with ContentFetcher(url_guard=_capture_guard()) as fetcher:
+ with pytest.raises(requests.HTTPError) as raised:
+ fetcher.fetch(REPLAY)
+
+ assert raised.value.response.status_code == 429
+ assert real_replay.transport.sent == [REPLAY] * 3
+ assert _content_counters(bound_research_cache) == before
+ assert bound_research_cache.get(REPLAY)["content"] == _CACHED_REPLAY_TEXT
+ real_replay.browser.assert_not_called()
+
+
+def test_guarded_fetcher_does_not_store_its_capture_in_the_run_cache(
+ bound_research_cache, real_replay
+):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ before = _content_counters(bound_research_cache)
+ real_replay.transport.routes[REPLAY] = {"body": _historical_html()}
+
+ with ContentFetcher(url_guard=_capture_guard()) as fetcher:
+ result = fetcher.fetch(REPLAY)
+
+ assert result["status"] == "success"
+ assert "ARCHIVED_FACT" in result["content"]
+ # The page read and its metadata read both go to the capture itself.
+ assert set(real_replay.transport.sent) == {REPLAY}
+ assert _content_counters(bound_research_cache) == before
+ assert bound_research_cache.get(REPLAY) is None
+
+
+def test_unguarded_fetcher_serves_the_same_cached_replay(
+ bound_research_cache, real_replay
+):
+ """Control: the seeded entry is reachable, so only the guard skips it."""
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+
+ before = _seed_replay_entry(bound_research_cache)
+
+ with ContentFetcher() as fetcher:
+ result = fetcher.fetch(REPLAY)
+
+ assert result["status"] == "success"
+ assert result["content"] == _CACHED_REPLAY_TEXT
+ assert real_replay.transport.sent == []
+ after = _content_counters(bound_research_cache)
+ assert after["hits"] == before["hits"] + 1
+ assert after["puts"] == before["puts"]
+ real_replay.browser.assert_not_called()
+
+
+def test_archive_tool_skips_cached_replay_and_classifies_its_429(
+ bound_research_cache, runtime, real_replay
+):
+ before = _seed_replay_entry(bound_research_cache)
+ availability = SearchEngineAvailability()
+ collector = SearchResultsCollector([])
+ real_replay.transport.routes[REPLAY] = {
+ "status": 429,
+ "headers": {"Retry-After": "120"},
+ }
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, availability=availability, max_fetches=3
+ )
+
+ output = archived.invoke({"url": ORIGINAL})
+
+ state = availability.state("wayback")
+ assert state is not None
+ assert state.failure.cooldown_seconds == 120
+ assert output.startswith("wayback")
+ assert "CACHED_FACT" not in output
+ assert collector.results == []
+ assert real_replay.transport.sent == [REPLAY] * 3
+ assert _content_counters(bound_research_cache) == before
+ runtime.getter.assert_called_once()
+ real_replay.browser.assert_not_called()
+
+
+def test_archive_tool_does_not_probe_or_store_the_run_cache(
+ bound_research_cache, runtime
+):
+ # The shared fetch path alone, with runtime's stub fetcher: its log
+ # probe and write-back would use the run cache around any successful
+ # read, so the stub succeeds and the cache must stay untouched.
+ before = _content_counters(bound_research_cache)
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=3
+ )
+
+ output = archived.invoke({"url": ORIGINAL})
+
+ assert output.startswith("[1] ")
+ runtime.fetcher.fetch.assert_called_once()
+ assert runtime.fetcher.fetch.call_args.args[0] == REPLAY
+ options = runtime.factory.call_args.kwargs
+ assert options["content_cache"] is None
+ assert options["url_guard"] is not None
+ assert _content_counters(bound_research_cache) == before
+ assert bound_research_cache.get(REPLAY) is None
+ runtime.getter.assert_called_once()
+
+
+def test_unguarded_fetch_path_serves_the_same_cached_replay(
+ bound_research_cache, real_replay
+):
+ """Control: the tools' shared fetch path reaches the seeded entry."""
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _fetch_raw_content,
+ )
+
+ before = _seed_replay_entry(bound_research_cache)
+
+ result, url, error, _count = _fetch_raw_content(
+ REPLAY, None, SearchResultsCollector([]), None, {}, "full"
+ )
+
+ assert error is None
+ assert url == REPLAY
+ assert result["status"] == "success"
+ assert result["content"] == _CACHED_REPLAY_TEXT
+ assert real_replay.transport.sent == []
+ after = _content_counters(bound_research_cache)
+ assert after["hits"] > before["hits"]
+ assert after["puts"] == before["puts"]
+ real_replay.browser.assert_not_called()
+
+
+def test_collector_reuse_keeps_archive_metadata_after_section_reset(runtime):
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool("full", collector)
+ archived.invoke({"url": ORIGINAL})
+ source = collector.find_by_index(1)
+ collector.reset()
+
+ index = collector.find_or_add_result(
+ {"link": REPLAY, "title": "Plain title", "snippet": source["snippet"]},
+ engine_name="fetch",
+ )
+
+ assert index == 1
+ echoed = _assert_source(collector)
+ assert echoed["title"] == source["title"]
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "reference", ["[1]", REPLAY], ids=["citation", "replay_url"]
+)
+ "spec,delay,attempts",
+ [
+ ({"status": 429, "headers": {"Retry-After": "120"}}, 120, 3),
+ ({"status": 503, "headers": {"Retry-After": "120"}}, 120, 3),
+ (
+ {"error": requests.ConnectionError("Replay connection failed")},
+ 60,
+ 3,
+ ),
+ ],
+ ids=["429", "503", "connection"],
+)
+def test_ordinary_archive_reread_reports_outage_to_shared_cooldown(
+ mode, reference, spec, delay, attempts, runtime, real_replay
+):
+ transport = real_replay.transport
+ transport.routes[REPLAY] = {"body": _historical_html()}
+ availability = SearchEngineAvailability()
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, availability=availability
+ )
+ assert archived.invoke({"url": ORIGINAL}).startswith("[1] ")
+ collector.reset()
+ transport.sent.clear()
+ transport.routes[REPLAY] = spec
+ ordinary = build_fetch_tool(
+ mode, collector, model=runtime.model, availability=availability
+ )
+
+ ordinary.invoke(_arguments(mode, url=reference))
+
+ state = availability.state("wayback")
+ assert state is not None
+ assert state.failure.cooldown_seconds == delay
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ assert transport.sent == [REPLAY] * attempts
+ assert archived.invoke({"url": ORIGINAL}) == state.describe()
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ real_replay.browser.assert_not_called()
+
+
+ "first,second",
+ [
+ ("https://example.com/history", "https://example.com/history/"),
+ (
+ "https://example.com/history?utm_source=first",
+ "https://example.com/history?utm_source=second",
+ ),
+ ],
+ ids=["target_path", "target_query"],
+)
+def test_collector_and_sources_keep_distinct_replay_targets(first, second):
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+ from local_deep_research.web_search_engines.wayback_client import (
+ validate_capture_fetch_url,
+ )
+
+ collector = SearchResultsCollector([])
+ replays = []
+ for index, target in enumerate((first, second), 1):
+ replay = f"https://web.archive.org/web/{CAPTURED}/{target}"
+ replays.append(replay)
+ assigned = collector.find_or_add_result(
+ {
+ "link": replay,
+ "title": "Historical policy",
+ "snippet": "Identical archived excerpt",
+ "source_type": "archive",
+ "original_url": target,
+ "timestamp": CAPTURED,
+ "formatted_date": FORMATTED_DATE,
+ },
+ engine_name="wayback",
+ )
+ assert assigned == index
+ assert collector.find_by_url(replay) == index
+
+ rendered = format_links_to_markdown(
+ collector.results, uncited_mode="disabled"
+ )
+ displayed = [
+ line.removeprefix(" URL: ")
+ for line in rendered.splitlines()
+ if line.startswith(" URL: ")
+ ]
+ assert displayed == replays
+ for replay, target in zip(displayed, (first, second)):
+ validate_capture_fetch_url(replay, CAPTURED, target)
+
+
[email protected]("source_type", [None, "web", "html"])
+def test_successful_archive_upgrades_prior_generic_citation(
+ source_type, runtime
+):
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+
+ collector = SearchResultsCollector([])
+ generic = {
+ "link": REPLAY,
+ "title": "Generic search title",
+ "snippet": runtime.fetcher.fetch.return_value["content"],
+ "original_url": "https://unrelated.example/old-metadata",
+ }
+ if source_type is not None:
+ generic["source_type"] = source_type
+ assert collector.find_or_add_result(generic, engine_name="web") == 1
+ archived = archive.build_archive_fetch_tool("full", collector)
+
+ assert archived.invoke({"url": ORIGINAL}).startswith("[1] ")
+ source = _assert_source(collector)
+ assert FORMATTED_DATE in source["title"]
+ assert FORMATTED_DATE in format_links_to_markdown(
+ collector.results, uncited_mode="disabled"
+ )
+ collector.reset()
+ ordinary = build_fetch_tool("full", collector)
+ assert ordinary.invoke({"url": "[1]"}).startswith("[1] ")
+ _assert_source(collector)
+ # The tracked capture is guarded even though its initial search hit
+ # was not classified as an archive source.
+ runtime.factory.call_args.kwargs["url_guard"](REPLAY)
+ with pytest.raises(ValueError):
+ runtime.factory.call_args.kwargs["url_guard"](ORIGINAL)
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "error",
+ [
+ requests.exceptions.ChunkedEncodingError("Body transfer aborted"),
+ requests.exceptions.ContentDecodingError("Body decoding aborted"),
+ ],
+ ids=["chunked_transfer", "content_decoding"],
+)
+def test_aborted_replay_body_is_a_shared_archive_transport_outage(
+ mode, error, runtime, real_replay
+):
+ real_replay.transport.routes[REPLAY] = {"body_error": error}
+ availability = SearchEngineAvailability()
+ collector = SearchResultsCollector([])
+ archived = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ availability=availability,
+ max_fetches=3,
+ )
+
+ first = archived.invoke(_arguments(mode))
+ state = availability.state("wayback")
+ assert state is not None
+ assert state.failure.cooldown_seconds == 60
+ assert "Could not read the provider response" in first
+ assert archived.invoke(_arguments(mode)) == state.describe()
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.getter.assert_called_once()
+ assert real_replay.transport.sent == [REPLAY]
+ runtime.model.invoke.assert_not_called()
+
+
+ "reference", ["[1]", REPLAY], ids=["generic_citation", "replay_url"]
+)
+ "reset", [False, True], ids=["same_section", "new_section"]
+)
+def test_reread_finds_verified_capture_after_different_search_excerpt(
+ reference, reset, runtime, real_replay
+):
+ transport = real_replay.transport
+ collector = SearchResultsCollector([])
+ assert (
+ collector.find_or_add_result(
+ {
+ "link": REPLAY,
+ "title": "Search listing title",
+ "snippet": "A different search excerpt",
+ "source_type": "web",
+ },
+ engine_name="web",
+ )
+ == 1
+ )
+ transport.routes[REPLAY] = {"body": _historical_html()}
+ archived = archive.build_archive_fetch_tool(
+ "full", collector, max_fetches=3
+ )
+ assert archived.invoke({"url": ORIGINAL}).startswith("[2] ")
+ first = collector.find_by_index(1)
+ second = collector.find_by_index(2)
+ assert first["snippet"] != second["snippet"]
+ assert collector.find_by_url(REPLAY) == 1
+ if reset:
+ collector.reset()
+ transport.sent.clear()
+ transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": ORIGINAL},
+ }
+ transport.routes[ORIGINAL] = {"body": b"LIVE_FACT: the fee is 100 units."}
+ ordinary = build_fetch_tool("full", collector, max_fetches=3)
+
+ output = ordinary.invoke({"url": reference})
+
+ assert not output.startswith("[")
+ assert "LIVE_FACT" not in output
+ assert transport.sent == [REPLAY]
+ assert collector.find_by_index(1) == first
+ assert collector.find_by_index(2) == second
+ assert collector.fetch_count == (1 if reset else 2)
+ runtime.getter.assert_called_once()
+ real_replay.browser.assert_not_called()
+
+
[email protected]("same_excerpt", [False, True])
[email protected]("cited", ["[1]", "[2]"])
+def test_verified_capture_date_survives_prose_citing_one_excerpt(
+ same_excerpt, cited, runtime
+):
+ from local_deep_research.utilities.search_utilities import (
+ format_links_to_markdown,
+ )
+
+ collector = SearchResultsCollector([])
+ content = runtime.fetcher.fetch.return_value["content"]
+ collector.find_or_add_result(
+ {
+ "link": REPLAY,
+ "title": "Generic fetched title",
+ "snippet": content if same_excerpt else "Different fetched excerpt",
+ },
+ engine_name="fetch",
+ )
+ archived = archive.build_archive_fetch_tool("full", collector)
+ archived.invoke({"url": ORIGINAL})
+ if same_excerpt and cited == "[2]":
+ cited = "[1]"
+
+ rendered = format_links_to_markdown(
+ collector.results, prose=f"Evidence {cited}.", uncited_mode="strict"
+ )
+
+ assert FORMATTED_DATE in rendered
+ assert REPLAY in rendered
+ assert len(collector.results) == (1 if same_excerpt else 2)
+ assert collector.find_by_index(1)["snippet"] == (
+ content if same_excerpt else "Different fetched excerpt"
+ )
+ collector.reset()
+ _, indexed = collector.add_results(
+ [
+ {
+ "link": REPLAY,
+ "title": "New search title",
+ "snippet": "New excerpt",
+ }
+ ]
+ )
+ assert indexed[0]["formatted_date"] == FORMATTED_DATE
+ assert indexed[0]["source_type"] == "archive"
+ assert FORMATTED_DATE in format_links_to_markdown(
+ collector.results, uncited_mode="disabled"
+ )
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+ "missing", ["original_url", "timestamp", "formatted_date", "all", "nulls"]
+)
[email protected]("reference,reset", [(REPLAY, False), ("[1]", True)])
+def test_partial_archive_provenance_is_recovered_before_fetch(
+ mode, missing, reference, reset, runtime
+):
+ requested = "http://www.example.com/history"
+ row = {
+ "link": REPLAY,
+ "title": "Historical page",
+ "snippet": runtime.fetcher.fetch.return_value["content"],
+ "source_type": "archive",
+ "original_url": ORIGINAL,
+ "requested_url": requested,
+ "timestamp": CAPTURED,
+ "formatted_date": FORMATTED_DATE,
+ }
+ fields = ("original_url", "timestamp", "formatted_date")
+ for field in fields if missing in {"all", "nulls"} else [missing]:
+ if missing == "nulls":
+ row[field] = None
+ else:
+ row.pop(field)
+ collector = SearchResultsCollector([])
+ collector.add_results([row], engine_name="wayback")
+ if reset:
+ collector.reset()
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url=reference))
+
+ assert output.startswith("[")
+ assert f"Original URL: {ORIGINAL}" in output
+ assert f"Requested URL: {requested}" in output
+ assert f"Captured: {FORMATTED_DATE}" in output
+ assert collector.fetch_count == 1
+ recovered = collector.find_by_index(int(output[1 : output.index("]")]))
+ assert recovered["original_url"] == ORIGINAL
+ assert recovered["requested_url"] == requested
+ assert recovered["timestamp"] == CAPTURED
+ assert recovered["formatted_date"] == FORMATTED_DATE
+ guard = runtime.factory.call_args.kwargs["url_guard"]
+ guard(REPLAY)
+ with pytest.raises(ValueError):
+ guard(ORIGINAL)
+ runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.getter.assert_not_called()
+ assert runtime.model.invoke.call_count == (0 if mode == "full" else 1)
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+ "url,metadata",
+ [
+ pytest.param(ORIGINAL, {}, id="non_replay"),
+ pytest.param(REPLAY, {"timestamp": "20240101000000"}, id="wrong_time"),
+ pytest.param(
+ REPLAY, {"original_url": ORIGINAL + "/other"}, id="wrong_target"
+ ),
+ ],
+)
+def test_partial_archive_provenance_never_overrides_capture_constraints(
+ mode, url, metadata, runtime
+):
+ collector = SearchResultsCollector([])
+ collector.add_results(
+ [{"link": url, "source_type": "archive", **metadata}],
+ engine_name="wayback",
+ )
+ before = dict(collector.find_by_index(1))
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert not output.startswith("[")
+ assert collector.find_by_index(1) == before
+ assert collector.fetch_count == 0
+ runtime.factory.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+ runtime.getter.assert_not_called()
+
+
+def test_direct_registration_recovers_partial_archive_metadata():
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ _register_in_collector,
+ )
+
+ collector = SearchResultsCollector([])
+ index = _register_in_collector(
+ collector, REPLAY, "", "Historical evidence", {"source_type": "archive"}
+ )
+
+ assert index == 1
+ source = _assert_source(collector)
+ assert source["title"] == f"{ORIGINAL} (archived {FORMATTED_DATE})"
+
+
[email protected]("mode", ["full", "summary_focus_query"])
+def test_non_capture_archive_page_keeps_ordinary_fetch_behavior(mode, runtime):
+ url = "https://web.archive.org/about/"
+ collector = SearchResultsCollector([])
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url=url))
+
+ assert output.startswith("[1]")
+ assert "Captured:" not in output
+ assert runtime.factory.call_args.kwargs.get("url_guard") is None
+ assert collector.fetch_count == 1
+ runtime.fetcher.fetch.assert_called_once_with(url, max_length=10_000)
+ runtime.getter.assert_not_called()
+
+
[email protected]("mode", ["full", "summary_focus_query"])
[email protected]("modifier", ["", "id_", "if_"])
+def test_first_direct_replay_read_is_confined_without_archive_lookup(
+ mode, modifier, runtime, real_replay
+):
+ replay = f"https://web.archive.org/web/{CAPTURED}{modifier}/{ORIGINAL}"
+ real_replay.transport.routes[replay] = {
+ "status": 302,
+ "headers": {"Location": ORIGINAL},
+ }
+ real_replay.transport.routes[ORIGINAL] = {
+ "body": b"LIVE_FACT: current page"
+ }
+ collector = SearchResultsCollector([])
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url=replay))
+
+ assert not output.startswith("[")
+ assert "LIVE_FACT" not in output
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ assert real_replay.transport.sent == [replay]
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+ real_replay.browser.assert_not_called()
+
+
[email protected]("modifier", ["", "id_", "if_"])
+def test_first_direct_replay_success_keeps_capture_metadata_without_lookup(
+ modifier, runtime, real_replay
+):
+ replay = f"https://web.archive.org/web/{CAPTURED}{modifier}/{ORIGINAL}"
+ real_replay.transport.routes[replay] = {"body": _historical_html()}
+ collector = SearchResultsCollector([])
+ ordinary = build_fetch_tool("full", collector)
+
+ output = ordinary.invoke({"url": replay})
+
+ assert output.startswith("[1] ")
+ assert f"Captured: {FORMATTED_DATE}" in output
+ _assert_source(collector, replay=replay)
+ runtime.getter.assert_not_called()
+ real_replay.browser.assert_not_called()
+
+
+ "replay",
+ [
+ REPLAY.replace("https://web.archive.org", "http://web.archive.org"),
+ REPLAY.replace(CAPTURED, "20240230112233"),
+ REPLAY.replace(CAPTURED, CAPTURED + "im_"),
+ REPLAY.replace("https://", "https://user:password@", 1),
+ REPLAY.replace("web.archive.org", "web.archive.org:8443"),
+ REPLAY.replace("web.archive.org", "web.archive.org."),
+ REPLAY.replace("/web/", "//web/"),
+ REPLAY.replace("/web/", "/web//"),
+ REPLAY.replace("web.archive.org", "%77eb.archive.org"),
+ REPLAY.replace("/web/", "/%77eb/"),
+ REPLAY.replace(CAPTURED, "%32" + CAPTURED[1:]),
+ REPLAY.replace("/web/", "/about/../web/"),
+ REPLAY.replace(CAPTURED, "2024"),
+ REPLAY.replace(CAPTURED, "*"),
+ ],
+ ids=[
+ "http_capture",
+ "invalid_date",
+ "unsupported_modifier",
+ "credentials",
+ "port",
+ "trailing_dot_host",
+ "double_leading_slash",
+ "double_capture_slash",
+ "prepared_host",
+ "prepared_path",
+ "prepared_timestamp",
+ "prepared_dot_segments",
+ "partial_timestamp",
+ "wildcard_timestamp",
+ ],
+)
+def test_invalid_direct_capture_never_uses_transport_or_budget(replay, runtime):
+ collector = SearchResultsCollector([])
+ ordinary = build_fetch_tool("full", collector)
+
+ assert not ordinary.invoke({"url": replay}).startswith("[1]")
+ assert collector.results == []
+ assert collector.fetch_count == 0
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+
+
+def chain_replay(runtime, scripted_transport, monkeypatch):
+ from local_deep_research.content_fetcher.fetcher import ContentFetcher
+ from local_deep_research.research_library.downloaders.playwright_html import (
+ AutoHTMLDownloader,
+ )
+
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", ContentFetcher
+ )
+ auto = Mock(wraps=AutoHTMLDownloader)
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
+ auto,
+ )
+ browser = Mock(side_effect=AssertionError("Unexpected browser rendering"))
+ monkeypatch.setattr(
+ "local_deep_research.research_library.downloaders.playwright_html.PlaywrightHTMLDownloader",
+ browser,
+ )
+ return SimpleNamespace(
+ transport=scripted_transport, auto=auto, browser=browser
+ )
+
+
+def _chained_collector(target=REPLAY, *, length=2, verified=False):
+ entries = [
+ {
+ "index": str(index),
+ "link": f"[{index + 1}]" if index < length else target,
+ "title": f"Chained source {index}",
+ "snippet": f"Discovery excerpt {index}",
+ }
+ for index in range(1, length + 1)
+ ]
+ if verified:
+ entries[-1].update(
+ source_type="archive",
+ original_url=ORIGINAL,
+ requested_url=ORIGINAL,
+ timestamp=CAPTURED,
+ formatted_date=FORMATTED_DATE,
+ )
+ return SearchResultsCollector(entries)
+
+
[email protected]("mode", FETCH_MODES[1:])
+ "length", [2, 4], ids=["two_markers", "depth_boundary"]
+)
[email protected]("verified", [False, True], ids=["generic", "archive"])
+def test_chained_archive_read_cannot_follow_live_redirect(
+ mode, length, verified, runtime, chain_replay
+):
+ collector = _chained_collector(length=length, verified=verified)
+ collector.reset()
+ before = collector.find_by_index(length)
+ chain_replay.transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": ORIGINAL},
+ }
+ chain_replay.transport.routes[ORIGINAL] = {
+ "body": _historical_html().replace(b"ARCHIVED_FACT", b"LIVE_FACT")
+ }
+ availability = SearchEngineAvailability()
+ ordinary = build_fetch_tool(
+ mode, collector, model=runtime.model, availability=availability
+ )
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert not output.startswith("[")
+ assert "selected capture" in output
+ assert "LIVE_FACT" not in output
+ assert collector.results == []
+ assert collector.find_by_index(length) == before
+ assert collector.fetch_count == 1
+ assert chain_replay.transport.sent == [REPLAY]
+ assert availability.state("wayback") is None
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+ chain_replay.auto.assert_not_called()
+ chain_replay.browser.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
[email protected]("verified", [False, True], ids=["generic", "archive"])
+def test_chained_archive_success_keeps_terminal_capture_provenance(
+ mode, verified, runtime, chain_replay
+):
+ collector = _chained_collector(verified=verified)
+ collector.reset()
+ chain_replay.transport.routes[REPLAY] = {"body": _historical_html()}
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert output.startswith("[3] ")
+ assert f"Original URL: {ORIGINAL}" in output
+ assert f"Captured: {FORMATTED_DATE}" in output
+ assert collector.fetch_count == 1
+ source = _assert_source(collector)
+ assert source["index"] == "3"
+ assert set(chain_replay.transport.sent) == {REPLAY}
+ runtime.getter.assert_not_called()
+ chain_replay.auto.assert_not_called()
+ chain_replay.browser.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
+def test_chained_archive_outage_respects_shared_retry_after(
+ mode, runtime, chain_replay
+):
+ collector = _chained_collector()
+ collector.reset()
+ chain_replay.transport.routes[REPLAY] = {
+ "status": 429,
+ "headers": {"Retry-After": "400"},
+ }
+ availability = SearchEngineAvailability()
+ ordinary = build_fetch_tool(
+ mode, collector, model=runtime.model, availability=availability
+ )
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ state = availability.state("wayback")
+ assert state is not None
+ assert state.failure.cooldown_seconds == 400
+ assert output == state.describe()
+ assert ordinary.invoke(_arguments(mode, url="[1]")) == state.describe()
+ assert chain_replay.transport.sent == [REPLAY] * 3
+ assert collector.results == []
+ assert collector.fetch_count == 1
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
[email protected]("denial", ["engine", ORIGINAL, REPLAY])
+def test_chained_archive_policy_denial_precedes_transport_and_quota(
+ mode, denial, runtime, chain_replay, monkeypatch
+):
+ collector = _chained_collector()
+ collector.reset()
+
+ def decision(target):
+ return SimpleNamespace(allowed=target != denial, reason="chain_policy")
+
+ monkeypatch.setattr(
+ policy, "evaluate_engine", lambda *args, **kwargs: decision("engine")
+ )
+ monkeypatch.setattr(
+ policy, "evaluate_url", lambda url, *args, **kwargs: decision(url)
+ )
+ ordinary = build_fetch_tool(
+ mode, collector, model=runtime.model, egress_context=object()
+ )
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert "blocked by egress policy" in output
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ assert chain_replay.transport.sent == []
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
+ "target,length,message",
+ [
+ ("[1]", 2, "Circular citation reference"),
+ (REPLAY, 5, "Citation resolution depth limit"),
+ ("[99]", 2, "No registered citation matches [99]"),
+ ("", 2, "Citation [2] has no URL field"),
+ (REPLAY.replace(CAPTURED, "20240230112233"), 2, "Error fetching"),
+ ],
+ ids=[
+ "cycle",
+ "depth",
+ "missing_citation",
+ "missing_url",
+ "invalid_capture",
+ ],
+)
+def test_chained_resolution_errors_keep_existing_limits_without_quota(
+ mode, target, length, message, runtime, chain_replay
+):
+ collector = _chained_collector(target, length=length)
+ collector.reset()
+ ordinary = build_fetch_tool(mode, collector, model=runtime.model)
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert message in output
+ assert collector.results == []
+ assert collector.fetch_count == 0
+ assert chain_replay.transport.sent == []
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
+def test_chained_live_read_survives_archive_cooldown(
+ mode, runtime, chain_replay
+):
+ from local_deep_research.web_search_engines.engine_availability import (
+ SearchFailure,
+ )
+
+ collector = _chained_collector(ORIGINAL)
+ collector.reset()
+ chain_replay.transport.routes[ORIGINAL] = {"body": _historical_html()}
+ availability = SearchEngineAvailability()
+ availability.disable("wayback", SearchFailure("Archive unavailable", 400))
+ ordinary = build_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ availability=availability,
+ settings_snapshot={"web.enable_javascript_rendering": False},
+ )
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert output.startswith("[3] ")
+ assert "Captured:" not in output
+ assert collector.fetch_count == 1
+ assert set(chain_replay.transport.sent) == {ORIGINAL}
+ assert collector.find_by_index(3).get("source_type") != "archive"
+ runtime.getter.assert_not_called()
+
+
[email protected]("mode", FETCH_MODES[1:])
+def test_chained_library_read_resolves_once_without_transport_or_quota(
+ mode, runtime, monkeypatch
+):
+ local = "/library/document/0123456789abcdef0123456789abcdef"
+ collector = _chained_collector(local, length=4)
+ collector.reset()
+ resolver = Mock(
+ return_value={"title": "Local policy", "content": "LOCAL_FACT " * 400}
+ )
+ gate = Mock(side_effect=AssertionError("Local read must skip egress"))
+ monkeypatch.setattr(policy, "evaluate_url", gate)
+ ordinary = build_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ library_resolver=resolver,
+ egress_context=object(),
+ content_max_length=1000,
+ )
+
+ output = ordinary.invoke(_arguments(mode, url="[1]"))
+
+ assert output.startswith("[5] ")
+ assert "Captured:" not in output
+ assert collector.fetch_count == 0
+ resolver.assert_called_once_with(local)
+ gate.assert_not_called()
+ runtime.factory.assert_not_called()
+ runtime.getter.assert_not_called()
+ if mode == "full":
+ assert output.endswith(("LOCAL_FACT " * 400)[:1000])
+ else:
+ prompt = runtime.model.invoke.call_args.args[0]
+ assert ("LOCAL_FACT " * 400)[:1000] in prompt
+ assert ("LOCAL_FACT " * 400)[:1001] not in prompt
+
+
[email protected]("mode", FETCH_MODES[1:])
+def test_chained_archive_read_uses_one_shared_budget(
+ mode, runtime, chain_replay
+):
+ collector = _chained_collector()
+ collector.reset()
+ chain_replay.transport.routes[REPLAY] = {
+ "status": 302,
+ "headers": {"Location": ORIGINAL},
+ }
+ ordinary = build_fetch_tool(
+ mode, collector, model=runtime.model, max_fetches=1
+ )
+
+ ordinary.invoke(_arguments(mode, url="[1]"))
+ output = ordinary.invoke(_arguments(mode, url="[2]"))
+
+ assert "budget exhausted (1/1)" in output
+ assert collector.fetch_count == 1
+ assert chain_replay.transport.sent == [REPLAY]
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.model.invoke.assert_not_called()
diff --git a/tests/js/components/settings-wayback-transition.test.js b/tests/js/components/settings-wayback-transition.test.js
new file mode 100644
index 0000000000..2337982f3e
--- /dev/null
+++ b/tests/js/components/settings-wayback-transition.test.js
@@ -0,0 +1,114 @@
+/** Run both shipped settings picker initializers with the real dropdown. */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import '@js/security/xss-protection.js';
+import '@js/components/custom_dropdown.js';
+
+const source = readFileSync(resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/settings.js',
+), 'utf8');
+const initializers = ['initializeSearchEngineDropdowns', 'setupCustomDropdowns'];
+const options = [
+ { value: 'wikipedia', label: 'Wikipedia' },
+ { value: 'duckduckgo', label: 'DuckDuckGo' },
+ { value: 'local_all', label: 'Local All' },
+];
+
+function initialize(name, saved, availableOptions) {
+ const start = source.indexOf(` function ${name}(`);
+ const end = source.indexOf('\n }\n', start);
+ if (start < 0 || end < 0) throw new Error(`Cannot locate ${name} in settings.js`);
+ const body = source.slice(start, end + '\n }'.length);
+ const settings = [{ key: 'search.tool', value: saved }];
+ const save = vi.fn();
+ // The IIFE does not export these initializers. Execute their literal
+ // source with the same closure values and the actual dropdown component.
+ // eslint-disable-next-line no-new-func
+ new Function(
+ 'searchEngineOptions', 'allSettings', 'handleInputChange', 'initAutoSaveHandlers',
+ `${body}\n${name}();`,
+ )(availableOptions, settings, save, () => {});
+ return { save, settings };
+}
+
+describe.each(initializers)('%s — Wayback saved selection', (name) => {
+ let input, hidden, list, controls, optionSources;
+
+ beforeEach(() => {
+ window.searchEngineDropdownInitialized = false;
+ input = document.createElement('input');
+ input.id = 'search.tool';
+ input.className = 'ldr-custom-dropdown-input';
+ hidden = document.createElement('input');
+ hidden.type = 'hidden';
+ hidden.id = 'search.tool_hidden';
+ list = document.createElement('div');
+ list.id = 'setting-search-tool-dropdown-list';
+ list.className = 'ldr-custom-dropdown-list';
+ const wrapper = document.createElement('div');
+ wrapper.className = 'ldr-custom-dropdown';
+ wrapper.append(input, hidden, list);
+ document.body.append(wrapper);
+
+ controls = [];
+ optionSources = [];
+ const setup = window.setupCustomDropdown;
+ vi.spyOn(window, 'setupCustomDropdown').mockImplementation((...args) => {
+ optionSources.push(args[2]);
+ const control = setup(...args);
+ controls.push(control);
+ return control;
+ });
+ });
+
+ afterEach(() => {
+ controls.forEach(control => control.destroy());
+ input.closest('.ldr-custom-dropdown')?.remove();
+ list.remove();
+ delete window.searchEngineDropdownInitialized;
+ vi.restoreAllMocks();
+ });
+
+ it.each([['runtime options', options], ['fallback options', []]])(
+ 'preserves saved Wayback without saving or offering it in %s', (_label, available) => {
+ const changed = vi.fn();
+ hidden.addEventListener('change', changed);
+ const { save, settings } = initialize(name, 'wayback', available);
+
+ expect(hidden.value).toBe('wayback');
+ expect(input.value).toContain('choose a configured search provider for topics');
+ expect(optionSources[0]().some(option => option.value === 'wayback')).toBe(false);
+ expect(changed).not.toHaveBeenCalled();
+ expect(save).not.toHaveBeenCalled();
+ expect(settings[0].value).toBe('wayback');
+ },
+ );
+
+ it('retains unrelated dynamic provider options and normal saved selections', () => {
+ const changed = vi.fn();
+ hidden.addEventListener('change', changed);
+ initialize(name, 'wikipedia', options);
+
+ expect(optionSources[0]()).toEqual(options);
+ expect(input.value).toBe('Wikipedia');
+ expect(hidden.value).toBe('wikipedia');
+ expect(changed).not.toHaveBeenCalled();
+ });
+
+ it('lets the user explicitly replace saved Wayback with a configured provider', () => {
+ initialize(name, 'wayback', options);
+ const changed = vi.fn();
+ hidden.addEventListener('change', changed);
+ input.value = 'Wiki';
+ input.dispatchEvent(new Event('input'));
+ expect(hidden.value).toBe('wayback');
+ expect(changed).not.toHaveBeenCalled();
+ list.querySelector('[data-value="wikipedia"]').click();
+
+ expect(hidden.value).toBe('wikipedia');
+ expect(input.value).toBe('Wikipedia');
+ expect(changed).toHaveBeenCalled();
+ expect(list.querySelector('[data-value="wayback"]')).toBeNull();
+ });
+});
diff --git a/tests/mcp/test_mcp_protocol.py b/tests/mcp/test_mcp_protocol.py
index 345ff7a27b..8ef4931db0 100644
--- a/tests/mcp/test_mcp_protocol.py
+++ b/tests/mcp/test_mcp_protocol.py
@@ -122,18 +122,24 @@ class TestMCPToolRegistration:
assert "config" in get_configuration.__doc__.lower()
def test_search_docstring_states_wayback_input_contract(self):
- """The wayback hint names the inputs the engine cannot read."""
+ """The wayback hint states what the engine looks up."""
from local_deep_research.mcp.server import search
doc = " ".join(search.__doc__.split())
assert "full http:// or https:// URL" in doc
- for unsupported in (
- "an uppercase scheme",
- "a bracketed IPv6 host",
- "a user name or password before the host",
- "a bare domain with a punycode (xn--) top-level domain",
- ):
- assert unsupported in doc
+ assert "or be only a bare domain such as example.com" in doc
+ assert (
+ "The complete URL, including its port, path, query and "
+ "fragment, is looked up" in doc
+ )
+ assert (
+ "words that follow a URL without a space become part of it" in doc
+ )
+ assert (
+ "A URL with a user name or password before its host is not "
+ "looked up" in doc
+ )
+ assert "at most max_results URLs" in doc
class TestMCPLogging:
diff --git a/tests/search_engines/test_search_engine_wayback.py b/tests/search_engines/test_search_engine_wayback.py
index 5c87930017..900ed06d77 100644
--- a/tests/search_engines/test_search_engine_wayback.py
+++ b/tests/search_engines/test_search_engine_wayback.py
@@ -119,10 +119,9 @@ class TestWaybackURLExtraction:
return WaybackSearchEngine()
def test_extract_url_from_http_url(self, engine):
- """Test extraction of full HTTP URL (domain portion)."""
+ """Test extraction of the complete HTTP URL."""
urls = engine._extract_urls_from_query("https://example.com/page")
- # The regex extracts the domain portion of the URL
- assert urls == ["https://example.com"]
+ assert urls == ["https://example.com/page"]
def test_extract_url_from_multiple_urls(self, engine):
"""Test extraction of multiple URLs."""
@@ -137,10 +136,10 @@ class TestWaybackURLExtraction:
urls = engine._extract_urls_from_query("example.com")
assert "http://example.com" in urls
- def test_partial_path_without_scheme_is_not_extracted(self, engine):
- """A domain with a path but no scheme is not an archive target."""
+ def test_extract_url_from_partial_path(self, engine):
+ """Test extraction from partial URL path."""
urls = engine._extract_urls_from_query("example.com/page/test")
- assert urls == []
+ assert "http://example.com/page/test" in urls
class TestWaybackTimestampFormatting:
diff --git a/tests/search_engines/test_wayback_archive_only.py b/tests/search_engines/test_wayback_archive_only.py
index aaec84be7a..174534f498 100644
--- a/tests/search_engines/test_wayback_archive_only.py
+++ b/tests/search_engines/test_wayback_archive_only.py
@@ -1,5 +1,7 @@
-"""Wayback looks up the hosts of supplied targets without another provider."""
+"""Wayback uses supplied archive targets without another search provider."""
+import gc
+import time
from unittest.mock import Mock
import pytest
@@ -29,110 +31,264 @@ def discovery_guards(monkeypatch):
[
("https://example.com", ["https://example.com"]),
("example.com", ["http://example.com"]),
- ("sub.example.co.uk", ["http://sub.example.co.uk"]),
+ ("example.com/page", ["http://example.com/page"]),
+ (
+ "https://example.com:8443/page?x=1#section",
+ ["https://example.com:8443/page?x=1#section"],
+ ),
+ (
+ "example.com:8080/page?x=1#section",
+ ["http://example.com:8080/page?x=1#section"],
+ ),
pytest.param(
- "Check https://example.com/page archive",
- ["https://example.com"],
- id="running_text_path",
+ "example.com:8080/page?next=https://other.example/a",
+ ["http://example.com:8080/page?next=https://other.example/a"],
+ id="nested_bare_target",
),
pytest.param(
- "https://example.com:8443/page?token=secret#access_token=x",
- ["https://example.com"],
- id="port_query_and_fragment_dropped",
+ "[source](https://example.com:8443/page?x=1)",
+ ["https://example.com:8443/page?x=1"],
+ id="markdown_link_target",
),
pytest.param(
"[source](https://example.com:8443/page?x=1).",
- ["https://example.com"],
- id="markdown_link",
+ ["https://example.com:8443/page?x=1"],
+ id="markdown_sentence_target",
+ ),
+ (
+ "(https://example.com/wiki/Foo_(bar)).",
+ ["https://example.com/wiki/Foo_(bar)"],
+ ),
+ (
+ "(https://example.com/wiki/Foo_(bar))",
+ ["https://example.com/wiki/Foo_(bar)"],
+ ),
+ (
+ "https://example.com/wiki/Foo_(bar)",
+ ["https://example.com/wiki/Foo_(bar)"],
+ ),
+ ("https://example.com/page)", ["https://example.com/page)"]),
+ (
+ "https://example.com/page?next=https://other.example/a",
+ ["https://example.com/page?next=https://other.example/a"],
+ ),
+ (
+ "https://web.archive.org/web/20240101000000/https://example.com/page",
+ [
+ "https://web.archive.org/web/20240101000000/https://example.com/page"
+ ],
),
+ ("This sentence has a period.", []),
+ ("topic.with.dots and words", []),
+ ("topic/with.a.path and words", []),
+ ("historical information about a topic", []),
+ ("", []),
+ # The documented contract: a scheme in any case, and a bare domain
+ # only as the whole query. A combining mark is not a bare-domain
+ # character, but a full URL keeps it.
+ ("sub.example.co.uk", ["http://sub.example.co.uk"]),
+ ("Find example.com", []),
+ ("https://", []),
+ ("HTTPS://EXAMPLE.COM/page", ["HTTPS://EXAMPLE.COM/page"]),
+ ("bu\u0308cher.de", []),
+ ("https://bu\u0308cher.de/x", ["https://bu\u0308cher.de/x"]),
+ # Running text: a closing bracket (ASCII, fullwidth or CJK) without
+ # its opener, straight and curly closing quotes, emphasis, and CJK
+ # or fullwidth stops end a URL; a balanced bracket pair stays in
+ # it. Inside a parenthesis or square bracket, a list separator
+ # before the closer or the next space ends it too.
+ # Fullwidth commas and semicolons and the ideographic comma
+ # separate compact lists like ASCII ones.
pytest.param(
"[source: https://example.com] for details",
["https://example.com"],
- id="bracket_closer_after_host",
+ id="prose_unmatched_square_closer",
),
pytest.param(
"Citations: [1: https://example.com], [2: https://example.org]",
["https://example.com", "https://example.org"],
- id="bracketed_citations",
+ id="prose_bracketed_citations",
),
pytest.param(
"Archived versions of [https://a.example, https://b.example]",
["https://a.example", "https://b.example"],
- id="bracketed_list",
+ id="bracketed_root_list",
),
pytest.param(
- "Pages (https://a.example/about, https://b.example/about) in 2010",
- ["https://a.example", "https://b.example"],
- id="parenthesised_list",
+ "[https://a.example/x, https://b.example/y]",
+ ["https://a.example/x", "https://b.example/y"],
+ id="bracketed_path_list",
),
pytest.param(
- "What did https://example.com's homepage say in 2005?",
- ["https://example.com"],
- id="ascii_possessive",
+ "(https://a.example/x; https://b.example/y)",
+ ["https://a.example/x", "https://b.example/y"],
+ id="parenthesized_semicolon_path_list",
+ ),
+ pytest.param(
+ "Pages (https://a.example/about, https://b.example/about) in 2010",
+ ["https://a.example/about", "https://b.example/about"],
+ id="prose_parenthesized_path_list",
),
pytest.param(
"The bot said 'see https://example.com' twice",
["https://example.com"],
- id="closing_quote_without_adjacent_opener",
+ id="prose_closing_quote_without_opener",
+ ),
+ pytest.param(
+ "He said \u201chttps://a.example/x\u201d twice",
+ ["https://a.example/x"],
+ id="curly_double_quotes",
+ ),
+ pytest.param(
+ "Find it at \u2018https://a.example/x\u2019 now",
+ ["https://a.example/x"],
+ id="curly_single_quotes",
),
pytest.param(
- "**https://example.com**'s homepage",
+ "Read **https://a.example/x** first",
+ ["https://a.example/x"],
+ id="markdown_emphasis",
+ ),
+ pytest.param(
+ "See {https://a.example/x} now",
+ ["https://a.example/x"],
+ id="braces",
+ ),
+ pytest.param(
+ "\u53c2\u89c1https://example.com\u3002",
["https://example.com"],
- id="emphasis_then_possessive",
+ id="cjk_full_stop",
+ ),
+ pytest.param(
+ "\uff08https://a.example/x\uff09",
+ ["https://a.example/x"],
+ id="fullwidth_parentheses",
+ ),
+ pytest.param(
+ "see https://ja.wikipedia.org/wiki/"
+ "\u3010\u63a8\u3057\u306e\u5b50\u3011 for details",
+ [
+ "https://ja.wikipedia.org/wiki/"
+ "\u3010\u63a8\u3057\u306e\u5b50\u3011"
+ ],
+ id="balanced_lenticular_brackets",
+ ),
+ pytest.param(
+ "see https://zh.wikipedia.org/wiki/"
+ "\u82f9\u679c\uff08\u6c34\u679c\uff09 ok",
+ [
+ "https://zh.wikipedia.org/wiki/\u82f9\u679c\uff08\u6c34\u679c\uff09"
+ ],
+ id="balanced_fullwidth_parentheses",
+ ),
+ pytest.param(
+ "see https://ja.wikipedia.org/wiki/\u300e\u30c6\u30b9\u30c8\u300f now",
+ ["https://ja.wikipedia.org/wiki/\u300e\u30c6\u30b9\u30c8\u300f"],
+ id="balanced_white_corner_brackets",
+ ),
+ pytest.param(
+ "\uff08\u53c2\u89c1 https://zh.wikipedia.org/wiki/"
+ "\u82f9\u679c\uff08\u6c34\u679c\uff09\uff09\u3002",
+ [
+ "https://zh.wikipedia.org/wiki/\u82f9\u679c\uff08\u6c34\u679c\uff09"
+ ],
+ id="balanced_pair_inside_fullwidth_parenthetical",
+ ),
+ pytest.param(
+ "see https://a.example/x\u3011 now",
+ ["https://a.example/x"],
+ id="unmatched_cjk_closer",
+ ),
+ pytest.param(
+ "\u300chttps://a.example/x\u300d",
+ ["https://a.example/x"],
+ id="cjk_corner_quotes",
+ ),
+ pytest.param(
+ "see https://a.example/x\u2026 and",
+ ["https://a.example/x"],
+ id="ellipsis",
+ ),
+ pytest.param(
+ "https://example.com\uff0chttps://example.org",
+ ["https://example.com", "https://example.org"],
+ id="fullwidth_comma_roots",
+ ),
+ pytest.param(
+ "https://a.example\u3001https://b.example",
+ ["https://a.example", "https://b.example"],
+ id="ideographic_comma_roots",
+ ),
+ pytest.param(
+ "https://a.example/x\uff1bhttps://b.example/y",
+ ["https://a.example/x", "https://b.example/y"],
+ id="fullwidth_semicolon_paths",
+ ),
+ # Documented limits (docs/search-engines.md): what follows a URL
+ # without a space stays in it, because the same characters can
+ # belong to an IRI path.
+ pytest.param(
+ "What did https://example.com's homepage say in 2005?",
+ ["https://example.com's"],
+ id="limit_possessive",
+ ),
+ pytest.param(
+ "\u8bf7\u67e5\u770bhttps://example.com/about\u7684\u5386\u53f2\u7248\u672c",
+ ["https://example.com/about\u7684\u5386\u53f2\u7248\u672c"],
+ id="limit_cjk_text_after_path",
),
pytest.param(
"https://example.com(see note)",
- ["https://example.com"],
- id="parenthesis_after_host",
+ ["https://example.com(see"],
+ id="limit_parenthesis_after_url",
),
pytest.param(
"see https://example.com/a(x)https://example.org/b now",
- ["https://example.com", "https://example.org"],
- id="urls_jammed_without_space",
+ ["https://example.com/a(x)https://example.org/b"],
+ id="limit_urls_written_together",
),
+ # A URL that itself ends in a character that also ends prose loses
+ # it in running text; alone, in straight quotes, in angle brackets
+ # or in backticks it keeps it. Of the quote styles, only straight
+ # quotes delimit a URL.
pytest.param(
- "[read https://example.com/label-url][1]",
- ["https://example.com"],
- id="reference_style_label",
+ "see https://ja.wikipedia.org/wiki/\u541b\u306e\u540d\u306f\u3002 now",
+ ["https://ja.wikipedia.org/wiki/\u541b\u306e\u540d\u306f"],
+ id="limit_url_ending_in_cjk_full_stop",
),
pytest.param(
- "请查看https://example.com/about的历史版本",
- ["https://example.com"],
- id="cjk_text_around_url",
+ "see https://web.archive.org/web/*/example.com/* now",
+ ["https://web.archive.org/web/*/example.com/"],
+ id="limit_url_ending_in_asterisk",
),
pytest.param(
- "参见https://example.com。",
- ["https://example.com"],
- id="cjk_full_stop_after_host",
+ "see <https://ja.wikipedia.org/wiki/\u541b\u306e\u540d\u306f\u3002> now",
+ ["https://ja.wikipedia.org/wiki/\u541b\u306e\u540d\u306f\u3002"],
+ id="angle_brackets_keep_url_final_stop",
),
pytest.param(
- "https://example.com,https://example.org",
- ["https://example.com", "https://example.org"],
- id="fullwidth_comma_list",
+ "see `https://web.archive.org/web/*/example.com/*` now",
+ ["https://web.archive.org/web/*/example.com/*"],
+ id="backticks_keep_url_final_asterisk",
+ ),
+ pytest.param(
+ 'see "https://example.com/search?a=*" now',
+ ["https://example.com/search?a=*"],
+ id="straight_quotes_keep_url_final_asterisk",
+ ),
+ pytest.param(
+ "Er schrieb \u201ehttps://example.com/a\u201c dazu",
+ ["https://example.com/a\u201c"],
+ id="limit_german_closing_quote",
+ ),
+ pytest.param(
+ "[read https://example.com/label-url][1]",
+ ["https://example.com/label-url][1"],
+ id="limit_reference_style_link",
),
- ("https://", []),
- ("example.com/page", []),
- ("Find example.com", []),
- ("This sentence has a period.", []),
- ("topic.with.dots and words", []),
- ("topic/with.a.path and words", []),
- ("historical information about a topic", []),
- ("", []),
- # Inputs the tool descriptions and docs name as unsupported: userinfo
- # reads the user name instead of the host, and an uppercase scheme, a
- # bracketed IPv6 host and a punycode TLD in a bare domain match
- # nothing, while the same punycode domain in a full URL is read. A
- # combining mark is not a host character and ends the host early.
- ("https://user:[email protected]/?api_key=x", ["https://user"]),
- ("HTTPS://EXAMPLE.COM/page", []),
- ("https://[2001:db8::1]/page", []),
- ("xn--e1afmkfd.xn--p1ai", []),
- ("http://xn--e1afmkfd.xn--p1ai/", ["http://xn--e1afmkfd.xn--p1ai"]),
- ("https://bu\u0308cher.de/x", ["https://bu"]),
- ("bu\u0308cher.de", []),
],
)
-def test_extract_archive_hosts_without_discovery(
+def test_extract_archive_targets_without_discovery(
query, expected, discovery_guards
):
discovery, request = discovery_guards
@@ -143,13 +299,110 @@ def test_extract_archive_hosts_without_discovery(
request.assert_not_called()
+def _fastest(extract, query, fastest):
+ started = time.perf_counter()
+ extract(query)
+ return min(fastest, time.perf_counter() - started)
+
+
+ ("entry", "joiner", "target"),
+ [
+ pytest.param(
+ "https://h{i}.example/p{i}",
+ ",",
+ "https://h{i}.example/p{i}",
+ id="comma_paths",
+ ),
+ pytest.param(
+ "https://h{i}.example/p{i}",
+ ";",
+ "https://h{i}.example/p{i}",
+ id="semicolon_paths",
+ ),
+ pytest.param(
+ "https://h{i}.example",
+ ",",
+ "https://h{i}.example",
+ id="comma_roots",
+ ),
+ pytest.param(
+ "(https://h{i}.example/p{i})",
+ ",",
+ "https://h{i}.example/p{i}",
+ id="parenthesized",
+ ),
+ pytest.param(
+ "[https://h{i}.example/p{i}]",
+ ",",
+ "https://h{i}.example/p{i}",
+ id="bracketed",
+ ),
+ pytest.param(
+ "'https://h{i}.example/p{i}'",
+ ",",
+ "https://h{i}.example/p{i}",
+ id="single_quoted",
+ ),
+ pytest.param(
+ "(https://h{i}.example",
+ ",",
+ "https://h{i}.example",
+ id="unclosed_parentheses",
+ ),
+ pytest.param(
+ "[x](https://h{i}.example/p{i})",
+ "",
+ "https://h{i}.example/p{i}",
+ id="adjacent_markdown",
+ ),
+ pytest.param(
+ "[x](https://h{i}.example/p{i})",
+ " ",
+ "https://h{i}.example/p{i}",
+ id="spaced_markdown",
+ ),
+ ],
+)
+def test_compact_target_lists_scale_linearly(entry, joiner, target):
+ """Each URL costs work in proportion to itself, not to the list.
+
+ A compact list is one run with no whitespace. Rescanning the rest of
+ the run for every URL, or every Markdown label for every URL, made
+ 16 times the URLs take hundreds of times as long. The bound compares
+ growth on one machine instead of fixed milliseconds, so a loaded
+ runner slows both sizes alike; linear growth is about 16 times.
+ """
+ extract = WaybackSearchEngine()._extract_urls_from_query
+ small = joiner.join(entry.format(i=i) for i in range(250))
+ large = joiner.join(entry.format(i=i) for i in range(4000))
+ assert extract(small) == [target.format(i=i) for i in range(250)]
+ assert extract(large) == [target.format(i=i) for i in range(4000)]
+
+ gc.collect()
+ gc_was_enabled = gc.isenabled()
+ gc.disable()
+ try:
+ small_time = large_time = float("inf")
+ for _attempt in range(5):
+ small_time = _fastest(extract, small, small_time)
+ large_time = _fastest(extract, large, large_time)
+ if large_time < 64 * small_time:
+ break
+ finally:
+ if gc_was_enabled:
+ gc.enable()
+ assert large_time < 64 * small_time, (
+ f"16x the URLs took {large_time / small_time:.0f}x as long"
+ )
+
+
@pytest.mark.parametrize(
"query",
[
"historical information about a topic",
"This sentence has a period.",
"topic/with.a.path and words",
- "example.com/page",
"",
],
)
@@ -167,23 +420,534 @@ def test_plain_text_previews_do_not_search_or_request_archives(
@pytest.mark.parametrize("closest_only", [False, True])
-def test_archive_previews_look_up_only_the_host(
- closest_only, discovery_guards, monkeypatch
+ ("query", "targets"),
+ [
+ pytest.param(
+ "See [https://example.org] for history.",
+ ["https://example.org"],
+ id="bracket_followup_root_prose",
+ ),
+ pytest.param(
+ "See [https://example.org/page?v=2] for history.",
+ ["https://example.org/page?v=2"],
+ id="bracket_followup_path_prose",
+ ),
+ pytest.param(
+ "See [https://[2001:db8::1]] for history.",
+ ["https://[2001:db8::1]"],
+ id="bracket_followup_ipv6_root",
+ ),
+ pytest.param(
+ "See [https://[2001:db8::1]:8443/a[b]?values=[x,y]"
+ "&next=https://nested.example/c[d]#part] for history.",
+ [
+ "https://[2001:db8::1]:8443/a[b]?values=[x,y]"
+ "&next=https://nested.example/c[d]#part"
+ ],
+ id="bracket_followup_ipv6_complete",
+ ),
+ pytest.param(
+ "See [https://example.org/a[b[c]]?values=[x[y]]].",
+ ["https://example.org/a[b[c]]?values=[x[y]]"],
+ id="bracket_followup_nested_literal_pairs",
+ ),
+ pytest.param(
+ "See [https://example.org/O'Reilly?x=[1]"
+ "&next=https://nested.example/a] for history.",
+ [
+ "https://example.org/O'Reilly?x=[1]"
+ "&next=https://nested.example/a"
+ ],
+ id="bracket_followup_apostrophe_nested_query",
+ ),
+ pytest.param(
+ "[https://example.org/a[b]][https://second.example/c[d]?x=[1]]",
+ [
+ "https://example.org/a[b]",
+ "https://second.example/c[d]?x=[1]",
+ ],
+ id="bracket_followup_adjacent_wrappers",
+ ),
+ pytest.param(
+ "See [https://example.org/a[b]?v=[2]",
+ ["https://example.org/a[b]?v=[2]"],
+ id="bracket_followup_unclosed_wrapper",
+ ),
+ pytest.param(
+ "See ``https://example.org/article?v=2`` for history.",
+ ["https://example.org/article?v=2"],
+ id="bracket_followup_double_backtick_control",
+ ),
+ pytest.param(
+ "See ```https://example.org/a[b]?values=[x,]"
+ "&next=https://nested.example/a#part``` for history.",
+ [
+ "https://example.org/a[b]?values=[x,]"
+ "&next=https://nested.example/a#part"
+ ],
+ id="bracket_followup_triple_backtick_control",
+ ),
+ pytest.param(
+ "example.org:8080/a[b]?values=[x]&next=https://nested.example/p[q]",
+ [
+ "http://example.org:8080/a[b]?values=[x]"
+ "&next=https://nested.example/p[q]"
+ ],
+ id="bracket_followup_bare_literal_pairs",
+ ),
+ pytest.param(
+ "example.org/a]?values=[x]]",
+ ["http://example.org/a]?values=[x]]"],
+ id="bracket_followup_bare_literal_closers",
+ ),
+ pytest.param(
+ "[https://[2001:db8::1]/a[b]](https://target.example/p[q]?x=[v])",
+ ["https://target.example/p[q]?x=[v]"],
+ id="bracket_followup_url_label_control",
+ ),
+ *[
+ pytest.param(
+ template.format(target=target),
+ [target],
+ id=f"bracket_followup_{wrapper}_{case}",
+ )
+ for wrapper, template in [
+ ("raw", "{target}"),
+ ("single_quote", "See '{target}' for history."),
+ ("double_quote", 'See "{target}" for history.'),
+ ("angle", "See <{target}> for history."),
+ ]
+ for case, target in [
+ (
+ "ipv6_literal_pairs",
+ "https://[2001:db8::1]:8443/a[b]?x=[v]"
+ "&next=https://other.example/p[q]#part",
+ ),
+ ("literal_closers", "https://example.org/a]?x=[v]]"),
+ ("empty_literal_pairs", "https://example.org/a[]?values=[]"),
+ ]
+ ],
+ pytest.param(
+ "https://example.com/O'Reilly",
+ ["https://example.com/O'Reilly"],
+ id="regression_apostrophe_path",
+ ),
+ pytest.param(
+ "https://example.com/page?author=O'Reilly&version=1",
+ ["https://example.com/page?author=O'Reilly&version=1"],
+ id="regression_apostrophe_query",
+ ),
+ pytest.param(
+ "example.com/page?author=O'Reilly&version=1",
+ ["http://example.com/page?author=O'Reilly&version=1"],
+ id="regression_bare_apostrophe_query",
+ ),
+ pytest.param(
+ "example.com:8080/O'Reilly?next=https://other.example/a#part",
+ [
+ "http://example.com:8080/O'Reilly"
+ "?next=https://other.example/a#part"
+ ],
+ id="regression_bare_apostrophe_nested_query",
+ ),
+ pytest.param(
+ "[source](https://example.com/O'Reilly)",
+ ["https://example.com/O'Reilly"],
+ id="regression_markdown_apostrophe",
+ ),
+ pytest.param(
+ "<https://example.com/O'Reilly>",
+ ["https://example.com/O'Reilly"],
+ id="regression_angle_apostrophe",
+ ),
+ pytest.param(
+ "'https://example.com/O'Reilly?value=a,'",
+ ["https://example.com/O'Reilly?value=a,"],
+ id="regression_single_quote_apostrophe",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly",
+ ["https://example.com/O'Reilly"],
+ id="quote_boundary_regression_unclosed_path",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly.",
+ ["https://example.com/O'Reilly"],
+ id="quote_boundary_regression_unclosed_sentence",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/page?author=O'Reilly&version=1",
+ ["https://example.com/page?author=O'Reilly&version=1"],
+ id="quote_boundary_regression_unclosed_query",
+ ),
+ pytest.param(
+ "Compare 'https://example.com:8443/O'Reilly"
+ "?next=https://other.example/a#part",
+ [
+ "https://example.com:8443/O'Reilly"
+ "?next=https://other.example/a#part"
+ ],
+ id="quote_boundary_regression_unclosed_nested_query",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly and 'https://example.org/a'",
+ ["https://example.com/O'Reilly", "https://example.org/a"],
+ id="quote_boundary_regression_unclosed_first_target",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly'.",
+ ["https://example.com/O'Reilly"],
+ id="quote_boundary_control_closed_sentence",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly',"
+ "'https://example.org/O'Brien'",
+ ["https://example.com/O'Reilly", "https://example.org/O'Brien"],
+ id="quote_boundary_control_comma_separated_targets",
+ ),
+ pytest.param(
+ "Compare 'https://example.com/O'Reilly' "
+ "and 'https://example.org/O'Brien'",
+ ["https://example.com/O'Reilly", "https://example.org/O'Brien"],
+ id="quote_boundary_control_separated_targets",
+ ),
+ pytest.param(
+ '"https://example.com/O\'Reilly?value=a,"',
+ ["https://example.com/O'Reilly?value=a,"],
+ id="regression_double_quote_apostrophe",
+ ),
+ pytest.param(
+ "Read https://example.com/O'Reilly.",
+ ["https://example.com/O'Reilly"],
+ id="regression_prose_apostrophe",
+ ),
+ pytest.param(
+ "https://example.com/path'",
+ ["https://example.com/path'"],
+ id="regression_raw_trailing_apostrophe",
+ ),
+ pytest.param(
+ "'https://example.com/path''",
+ ["https://example.com/path'"],
+ id="regression_quoted_trailing_apostrophe",
+ ),
+ pytest.param(
+ "[https://example.com](https://example.org)",
+ ["https://example.org"],
+ id="regression_markdown_url_label",
+ ),
+ pytest.param(
+ "[https://example.com/a]"
+ "(https://example.org:8443/Foo_(bar)?version=1#part)",
+ ["https://example.org:8443/Foo_(bar)?version=1#part"],
+ id="regression_markdown_url_label_complete_target",
+ ),
+ pytest.param(
+ "[https://example.com/a](<https://example.org/b?version=1>)",
+ ["https://example.org/b?version=1"],
+ id="regression_markdown_url_label_angle_target",
+ ),
+ pytest.param(
+ "[read https://example.com/a](https://example.org/b?version=1)",
+ ["https://example.org/b?version=1"],
+ id="regression_markdown_url_label_with_text",
+ ),
+ pytest.param(
+ "[https://[2001:db8::1]:8443/a](https://example.org/b)",
+ ["https://example.org/b"],
+ id="regression_markdown_ipv6_url_label",
+ ),
+ pytest.param(
+ "[https://example.com/a](https://example.org/b)"
+ "[source](https://third.example/c)",
+ ["https://example.org/b", "https://third.example/c"],
+ id="regression_adjacent_markdown_url_label",
+ ),
+ pytest.param(
+ "`https://example.com/page?version=1`",
+ ["https://example.com/page?version=1"],
+ id="regression_code_span_complete_target",
+ ),
+ pytest.param(
+ "`https://example.org`",
+ ["https://example.org"],
+ id="regression_code_span_root",
+ ),
+ pytest.param(
+ "``https://example.com:8443/O'Reilly"
+ "?next=https://other.example/a#part``",
+ [
+ "https://example.com:8443/O'Reilly"
+ "?next=https://other.example/a#part"
+ ],
+ id="regression_multibacktick_span_nested_query",
+ ),
+ pytest.param(
+ "`https://example.com/page?value=a,`",
+ ["https://example.com/page?value=a,"],
+ id="regression_code_span_literal_punctuation",
+ ),
+ pytest.param(
+ "Read 'https://example.com/page?value=a,'.",
+ ["https://example.com/page?value=a,"],
+ id="control_single_quote_literal_punctuation",
+ ),
+ pytest.param(
+ "'https://example.com/a','https://example.org/b'",
+ ["https://example.com/a", "https://example.org/b"],
+ id="control_adjacent_single_quoted_targets",
+ ),
+ pytest.param(
+ "example.com:8080/page?next=https://other.example/a",
+ ["http://example.com:8080/page?next=https://other.example/a"],
+ id="nested_bare_target",
+ ),
+ pytest.param(
+ "[source](https://example.com:8443/page?x=1)",
+ ["https://example.com:8443/page?x=1"],
+ id="markdown_link_target",
+ ),
+ pytest.param(
+ "[source](https://example.com:8443/page?x=1).",
+ ["https://example.com:8443/page?x=1"],
+ id="markdown_sentence_target",
+ ),
+ pytest.param(
+ "https://example.com:8443/page?version=1",
+ ["https://example.com:8443/page?version=1"],
+ id="complete_absolute_target",
+ ),
+ pytest.param(
+ "Compare https://example.com, https://example.org",
+ ["https://example.com", "https://example.org"],
+ id="prose_comma",
+ ),
+ pytest.param(
+ "See https://example.com; then compare https://example.org",
+ ["https://example.com", "https://example.org"],
+ id="prose_semicolon",
+ ),
+ pytest.param(
+ "https://example.com,https://example.org",
+ ["https://example.com", "https://example.org"],
+ id="compact_comma_roots",
+ ),
+ pytest.param(
+ "https://example.com/history,https://example.org/archive",
+ ["https://example.com/history", "https://example.org/archive"],
+ id="compact_comma_paths",
+ ),
+ pytest.param(
+ "https://example.com/history;https://example.org/archive",
+ ["https://example.com/history", "https://example.org/archive"],
+ id="compact_semicolon_paths",
+ ),
+ pytest.param(
+ "Compare https://example.com/history,https://example.org/archive",
+ ["https://example.com/history", "https://example.org/archive"],
+ id="prose_compact_comma_paths",
+ ),
+ pytest.param(
+ "Compare https://example.com/history;https://example.org/archive",
+ ["https://example.com/history", "https://example.org/archive"],
+ id="prose_compact_semicolon_paths",
+ ),
+ pytest.param(
+ "'https://example.com/history,https://example.org/archive'",
+ ["https://example.com/history,https://example.org/archive"],
+ id="quoted_literal_comma_http_path",
+ ),
+ pytest.param(
+ '"https://example.com/history;https://example.org/archive"',
+ ["https://example.com/history;https://example.org/archive"],
+ id="quoted_literal_semicolon_http_path",
+ ),
+ pytest.param(
+ "https://example.com,'https://example.org/a'",
+ ["https://example.com", "https://example.org/a"],
+ id="compact_root_then_quoted_target",
+ ),
+ pytest.param(
+ "(https://example.com,(https://example.org",
+ ["https://example.com", "https://example.org"],
+ id="compact_unclosed_parenthesized_roots",
+ ),
+ pytest.param(
+ "[https://example.com,[https://example.org",
+ ["https://example.com", "https://example.org"],
+ id="compact_unclosed_bracketed_roots",
+ ),
+ pytest.param(
+ "[https://a.example](https://b.example) "
+ "[x](https://c.example) https://d.example",
+ ["https://b.example", "https://c.example", "https://d.example"],
+ id="markdown_url_label_then_links_and_raw_url",
+ ),
+ pytest.param(
+ "[first](https://example.com)[second](https://example.org)",
+ ["https://example.com", "https://example.org"],
+ id="adjacent_markdown",
+ ),
+ pytest.param(
+ "[first](https://example.com/wiki/Foo_(bar))"
+ "[second](https://example.org/wiki/Baz_(qux))",
+ [
+ "https://example.com/wiki/Foo_(bar)",
+ "https://example.org/wiki/Baz_(qux)",
+ ],
+ id="adjacent_markdown_balanced_paths",
+ ),
+ pytest.param(
+ "[first](https://example.com/page?next=https://other.example/a)"
+ "[second](https://example.org/page?next=https://third.example/b)",
+ [
+ "https://example.com/page?next=https://other.example/a",
+ "https://example.org/page?next=https://third.example/b",
+ ],
+ id="adjacent_markdown_nested_queries",
+ ),
+ pytest.param(
+ "xn--e1afmkfd.xn--p1ai",
+ ["http://xn--e1afmkfd.xn--p1ai"],
+ id="bare_punycode_host",
+ ),
+ pytest.param(
+ "xn--e1afmkfd.xn--p1ai/page",
+ ["http://xn--e1afmkfd.xn--p1ai/page"],
+ id="bare_punycode_path",
+ ),
+ pytest.param(
+ "xn--e1afmkfd.xn--p1ai:8080",
+ ["http://xn--e1afmkfd.xn--p1ai:8080"],
+ id="bare_punycode_port",
+ ),
+ pytest.param(
+ "xn--e1afmkfd.xn--p1ai?x=1",
+ ["http://xn--e1afmkfd.xn--p1ai?x=1"],
+ id="bare_punycode_query",
+ ),
+ pytest.param(
+ "xn--e1afmkfd.xn--p1ai:8080/page?next=https://other.example/a#part",
+ [
+ "http://xn--e1afmkfd.xn--p1ai:8080/page"
+ "?next=https://other.example/a#part"
+ ],
+ id="bare_punycode_complete_nested_target",
+ ),
+ pytest.param(
+ "https://example.com/page?next=https://other.example/a",
+ ["https://example.com/page?next=https://other.example/a"],
+ id="nested_absolute_target",
+ ),
+ pytest.param(
+ "(https://example.com/wiki/Foo_(bar)).",
+ ["https://example.com/wiki/Foo_(bar)"],
+ id="parenthesized_balanced_path_sentence",
+ ),
+ pytest.param(
+ "(https://example.com/wiki/Foo_(bar))",
+ ["https://example.com/wiki/Foo_(bar)"],
+ id="parenthesized_balanced_path",
+ ),
+ pytest.param(
+ "https://example.com/wiki/Foo_(bar)",
+ ["https://example.com/wiki/Foo_(bar)"],
+ id="unwrapped_balanced_path",
+ ),
+ pytest.param(
+ "https://example.com/page)",
+ ["https://example.com/page)"],
+ id="unwrapped_literal_closing_parenthesis",
+ ),
+ pytest.param(
+ "https://example.com/path,segment;version?values=a,b;c",
+ ["https://example.com/path,segment;version?values=a,b;c"],
+ id="literal_path_and_query_punctuation",
+ ),
+ pytest.param(
+ "https://example.com/path,",
+ ["https://example.com/path,"],
+ id="literal_trailing_path_comma",
+ ),
+ pytest.param(
+ "https://example.com/path;",
+ ["https://example.com/path;"],
+ id="literal_trailing_path_semicolon",
+ ),
+ pytest.param(
+ "https://example.com/page?value=a,",
+ ["https://example.com/page?value=a,"],
+ id="literal_trailing_query_comma",
+ ),
+ pytest.param(
+ "https://example.com/page?value=a;",
+ ["https://example.com/page?value=a;"],
+ id="literal_trailing_query_semicolon",
+ ),
+ pytest.param(
+ "https://example.com/page"
+ "?next=https://other.example/a,https://third.example/b",
+ [
+ "https://example.com/page"
+ "?next=https://other.example/a,https://third.example/b"
+ ],
+ id="literal_nested_query_comma",
+ ),
+ pytest.param(
+ "https://example.com/page"
+ "?next=https://other.example/a;https://third.example/b",
+ [
+ "https://example.com/page"
+ "?next=https://other.example/a;https://third.example/b"
+ ],
+ id="literal_nested_query_semicolon",
+ ),
+ *[
+ pytest.param(
+ template.format(target=target),
+ [target],
+ id=f"{wrapper}_{case}",
+ )
+ for wrapper, template in [
+ ("angle_markdown", "[source](<{target}>)"),
+ ("autolink", "<{target}>"),
+ ]
+ for case, target in [
+ ("literal_path_period", "https://example.com/a."),
+ ("literal_path_comma", "https://example.com/a,"),
+ ("literal_path_semicolon", "https://example.com/a;"),
+ ("literal_query_period", "https://example.com/page?value=a."),
+ ("literal_query_comma", "https://example.com/page?value=a,"),
+ (
+ "literal_query_semicolon",
+ "https://example.com/page?value=a;",
+ ),
+ ]
+ ],
+ ],
+)
+def test_archive_previews_keep_the_complete_target(
+ query, targets, closest_only, discovery_guards, monkeypatch
):
from local_deep_research.web_search_engines.engines import (
search_engine_wayback as wayback,
)
discovery, request = discovery_guards
- query = (
- "See https://example.com:8443/page?token=secret#access_token=x "
- "and https://example.org/a"
- )
- hosts = ["https://example.com", "https://example.org"]
timestamp = "20240101000000"
+ replay_urls = [
+ f"https://web.archive.org/web/{timestamp}/{target}"
+ for target in targets
+ ]
- def archive_response(_endpoint, *, params):
+ def archive_response(_endpoint, *, params, **kwargs):
+ if closest_only:
+ assert kwargs == {"timeout": 30, "allow_redirects": False}
target = params["url"]
+ # Only intended URLs have captures: malformed targets must not
+ # receive an archive response that could hide the parser defect.
+ captured = target in targets
response = Mock(status_code=200, headers={})
if closest_only:
response.json.return_value = {
@@ -194,33 +958,103 @@ def test_archive_previews_look_up_only_the_host(
"url": f"https://web.archive.org/web/{timestamp}/{target}",
}
}
+ if captured
+ else {}
}
else:
response.json.return_value = [
["timestamp", "original", "statuscode", "mimetype"],
- [timestamp, target, "200", "text/html"],
]
+ if captured:
+ response.json.return_value.append(
+ [timestamp, target, "200", "text/html"]
+ )
return response
archive_lookup = Mock(side_effect=archive_response)
monkeypatch.setattr(wayback, "safe_get", archive_lookup)
- engine = WaybackSearchEngine(closest_only=closest_only)
- engine.rate_tracker = Mock()
+ engine = WaybackSearchEngine(
+ closest_only=closest_only, settings_snapshot={}
+ )
+ engine._configure_programmatic_mode(True)
previews = engine._get_previews(query)
+ calls = archive_lookup.call_args_list
endpoint = engine.available_api if closest_only else engine.cdx_api
+ assert [call.args[0] for call in calls] == [endpoint] * len(targets)
+ assert [call.kwargs["params"]["url"] for call in calls] == targets
+ assert [preview["original_url"] for preview in previews] == targets
+ assert [preview["link"] for preview in previews] == replay_urls
+ assert [preview["timestamp"] for preview in previews] == [timestamp] * len(
+ targets
+ )
+ discovery.assert_not_called()
+ request.assert_not_called()
+
+
+def _no_capture(_endpoint, *, params, **_kwargs):
+ response = Mock(status_code=200, headers={})
+ if params.get("output") == "json":
+ response.json.return_value = [
+ ["timestamp", "original", "statuscode", "mimetype"]
+ ]
+ else:
+ response.json.return_value = {"archived_snapshots": {}}
+ return response
+
+
[email protected]("closest_only", [False, True])
+def test_previews_skip_targets_that_fetch_archive_refuses(
+ closest_only, discovery_guards, monkeypatch, loguru_caplog
+):
+ """A user name or password never reaches the archive or the logs."""
+ from local_deep_research.web_search_engines.engines import (
+ search_engine_wayback as wayback,
+ )
+
+ discovery, request = discovery_guards
+ secret = "pw-" + "x" * 8
+ archive_lookup = Mock(side_effect=_no_capture)
+ monkeypatch.setattr(wayback, "safe_get", archive_lookup)
+ engine = WaybackSearchEngine(
+ closest_only=closest_only, settings_snapshot={}
+ )
+ engine._configure_programmatic_mode(True)
+
+ with loguru_caplog.at_level("INFO"):
+ engine._get_previews(
+ f"Compare https://user:{secret}@example.com/page, "
+ "https://example.com:99999/old and https://example.org/a"
+ )
+
calls = archive_lookup.call_args_list
- assert [call.args[0] for call in calls] == [endpoint] * len(hosts)
- assert [call.kwargs["params"]["url"] for call in calls] == hosts
- assert [preview["original_url"] for preview in previews] == hosts
- assert [preview["link"] for preview in previews] == [
- f"https://web.archive.org/web/{timestamp}/{host}" for host in hosts
+ assert [call.kwargs["params"]["url"] for call in calls] == [
+ "https://example.org/a"
]
- # Nothing after a host reaches the archive or the stored results.
- for preview in previews:
- for value in (preview["title"], preview["link"], preview["id"]):
- assert "8443" not in value
- assert "token" not in value
+ assert secret not in loguru_caplog.text
+ assert "Skipping Wayback target https://example.com:" in loguru_caplog.text
+ discovery.assert_not_called()
+ request.assert_not_called()
+
+
+def test_previews_look_up_at_most_max_results_targets(
+ discovery_guards, monkeypatch
+):
+ from local_deep_research.web_search_engines.engines import (
+ search_engine_wayback as wayback,
+ )
+
+ discovery, request = discovery_guards
+ archive_lookup = Mock(side_effect=_no_capture)
+ monkeypatch.setattr(wayback, "safe_get", archive_lookup)
+ engine = WaybackSearchEngine(max_results=2, settings_snapshot={})
+ engine._configure_programmatic_mode(True)
+
+ engine._get_previews(" ".join(f"https://h{i}.example/p" for i in range(5)))
+
+ assert [
+ call.kwargs["params"]["url"] for call in archive_lookup.call_args_list
+ ] == ["https://h0.example/p", "https://h1.example/p"]
discovery.assert_not_called()
request.assert_not_called()
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 81878eff40..192d7ba56d 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -8514,11 +8514,11 @@
},
"search.engine.web.wayback.agent_enabled": {
"category": "wayback",
- "description": "Include Wayback as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections.",
+ "description": "Enable the fetch_archive tool for the lead LangGraph research agent and its subagents. Find URLs with a configured search provider, then fetch an archived version with an optional date. Uses search.fetch.mode and the shared search.fetch.max_per_topic budget; disabled fetch mode or egress policy can still block archive fetching.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Available to Research Agent",
+ "name": "Enable Archive Fetch",
"options": null,
"step": null,
"type": "SEARCH",
@@ -8528,7 +8528,7 @@
},
"search.engine.web.wayback.default_params.closest_only": {
"category": "wayback",
- "description": "When enabled, only return the snapshot closest to the target date instead of all available snapshots.",
+ "description": "Legacy URL adapter: When enabled, only return the snapshot closest to the target date instead of all available snapshots. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8542,7 +8542,7 @@
},
"search.engine.web.wayback.default_params.language": {
"category": "wayback",
- "description": "Preferred language for archived content when multiple versions are available.",
+ "description": "Legacy URL adapter: Preferred language for archived content when multiple versions are available. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -8556,7 +8556,7 @@
},
"search.engine.web.wayback.default_params.max_results": {
"category": "wayback",
- "description": "Maximum number of archived snapshots to return per search query.",
+ "description": "Legacy URL adapter: Maximum number of archived snapshots to return per search query. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": 1,
@@ -8570,7 +8570,7 @@
},
"search.engine.web.wayback.default_params.max_snapshots_per_url": {
"category": "wayback",
- "description": "Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history.",
+ "description": "Legacy URL adapter: Maximum historical snapshots to retrieve for each URL. Lower values are faster; higher shows more history. Does not control fetch_archive.",
"editable": true,
"max_value": null,
"min_value": 1,
@@ -8593,7 +8593,7 @@
"step": null,
"type": "SEARCH",
"ui_element": "text",
- "value": "Search the Internet Archive's Wayback Machine.",
+ "value": "Fetch archived versions of known URLs from the Internet Archive's Wayback Machine.",
"visible": false
},
"search.engine.web.wayback.display_name": {
@@ -8674,7 +8674,7 @@
},
"search.engine.web.wayback.use_in_auto_search": {
"category": "wayback",
- "description": "Include Wayback in auto search mode",
+ "description": "Legacy setting retained for compatibility. Wayback accepts URLs only and is excluded from topic and auto search; choose a configured search provider for topics.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -9345,7 +9345,7 @@
},
"search.fetch.content_max_length": {
"category": "search_parameters",
- "description": "Maximum page text (in characters) passed to the fetch_content tool per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content tool; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
"editable": true,
"max_value": 50000,
"min_value": 1000,
@@ -9359,7 +9359,7 @@
},
"search.fetch.max_per_topic": {
"category": "search_parameters",
- "description": "Maximum number of page content fetches (fetch_content calls) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",
+ "description": "Maximum number of page content fetches (fetch_content and fetch_archive calls sharing one budget) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",
"editable": true,
"max_value": 50,
"min_value": 0,
@@ -9373,7 +9373,7 @@
},
"search.fetch.mode": {
"category": "search_parameters",
- "description": "Controls the LangGraph agent's fetch_content tool. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Controls the LangGraph agent's fetch_content and fetch_archive tools. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes both tools entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -9821,7 +9821,7 @@
},
"search.tool": {
"category": "search_general",
- "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately.",
+ "description": "Search engine to use for research queries. The default langgraph-agent strategy can additionally pick specialized engines per query as tools. Each engine may require its own API key or service to be configured separately. Wayback is available through fetch_archive for known URLs. If your saved engine is Wayback, choose a configured search provider for topic queries; saved values are not changed automatically.",
"editable": true,
"max_value": null,
"min_value": null,
@@ -9882,10 +9882,6 @@
{
"label": "Mojeek",
"value": "mojeek"
- },
- {
- "label": "Wayback",
- "value": "wayback"
}
],
"step": null,
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 849fdf5f19..aff7eb04c3 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -8572,26 +8572,36 @@ def test_wayback_tool_description_states_accepted_input(specialized):
assert "full http:// or https:// URL" in search.description
assert "or be only a bare domain" in search.description
- assert "Only the host is looked up" in search.description
+ assert "The complete URL" in search.description
+ assert (
+ "words that follow a URL without a space, such as 's, become part of it"
+ in search.description
+ )
+ assert (
+ "A URL with a user name or password before its host is not looked up"
+ in search.description
+ )
assert "configured search provider" in search.description
- # It also names the inputs the patterns miss or misread; each form is
- # pinned in test_wayback_archive_only.py.
- for unsupported in (
- "an uppercase scheme",
- "a bracketed IPv6 host",
- "a user name or password before the host",
- "a bare domain with a punycode (xn--) top-level domain",
- ):
- assert unsupported in search.description
- # The description is the parser's contract: the host of a full URL
- # anywhere in the input, but a bare domain only when it is the whole
- # input.
+ # The description is the parser's contract: every complete URL anywhere
+ # in the input, but a bare domain only when it is the whole input.
engine = WaybackSearchEngine()
assert engine._extract_urls_from_query("example.com") == [
"http://example.com"
]
assert engine._extract_urls_from_query("Find example.com") == []
- assert engine._extract_urls_from_query("example.com/page") == []
- assert engine._extract_urls_from_query("Find https://example.com/page") == [
- "https://example.com"
+ assert engine._extract_urls_from_query("example.com:8080/page?x=1") == [
+ "http://example.com:8080/page?x=1"
+ ]
+ assert engine._extract_urls_from_query(
+ "Find https://example.com:8443/page?x=1#top"
+ ) == ["https://example.com:8443/page?x=1#top"]
+ assert engine._extract_urls_from_query("Find HTTPS://example.com/a") == [
+ "HTTPS://example.com/a"
+ ]
+ # Following words join the URL, while closing punctuation does not.
+ assert engine._extract_urls_from_query("See https://example.com's") == [
+ "https://example.com's"
+ ]
+ assert engine._extract_urls_from_query("See (https://example.com/a).") == [
+ "https://example.com/a"
]
diff --git a/tests/strategies/test_langgraph_archive_tool.py b/tests/strategies/test_langgraph_archive_tool.py
new file mode 100644
index 0000000000..402ecac0f8
--- /dev/null
+++ b/tests/strategies/test_langgraph_archive_tool.py
@@ -0,0 +1,268 @@
+"""Archive tool wiring for the real lead-agent and subagent factories."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock
+
+import pytest
+import requests
+
+from local_deep_research.advanced_search_system.strategies import (
+ langgraph_agent_strategy as strategy_module,
+)
+from local_deep_research.security import clear_active_context
+from local_deep_research.web_search_engines.engine_availability import (
+ SearchFailure,
+ available_tool_names,
+ engine_for_tool,
+)
+
+
[email protected](autouse=True)
+def _offline(monkeypatch):
+ clear_active_context()
+ monkeypatch.setattr(
+ requests.sessions.Session,
+ "request",
+ Mock(side_effect=AssertionError("Unexpected outbound request")),
+ )
+ yield
+ clear_active_context()
+
+
+def factories(monkeypatch):
+ """Mock search discovery and agent execution, retaining both fetch builders."""
+ configs = {
+ "searxng": {"description": "Web search", "strengths": []},
+ "wayback": {"description": "Historical pages", "strengths": []},
+ "arxiv": {"description": "Research papers", "strengths": []},
+ }
+ discovery = Mock(return_value=configs)
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.search_engines_config"
+ ".list_eligible_engine_configs",
+ discovery,
+ )
+ monkeypatch.setattr(
+ "local_deep_research.web_search_engines.search_engines_config"
+ ".search_config",
+ Mock(return_value=configs),
+ )
+ web_search = Mock(return_value=SimpleNamespace(name="web_search"))
+ specialized_search = Mock(
+ side_effect=lambda name, *args, **kwargs: SimpleNamespace(
+ name=f"search_{name}"
+ )
+ )
+ monkeypatch.setattr(strategy_module, "_make_web_search_tool", web_search)
+ monkeypatch.setattr(
+ strategy_module, "_make_specialized_search_tool", specialized_search
+ )
+ created = []
+
+ def create_agent(*, model, tools, system_prompt, **kwargs):
+ created.append(SimpleNamespace(tools=tools, prompt=system_prompt))
+ agent = MagicMock()
+ agent.invoke.return_value = {
+ "messages": [SimpleNamespace(content="Findings from the subagent")]
+ }
+ return agent
+
+ monkeypatch.setattr("langchain.agents.create_agent", create_agent)
+ return SimpleNamespace(
+ configs=configs,
+ discovery=discovery,
+ web_search=web_search,
+ specialized_search=specialized_search,
+ created=created,
+ )
+
+
+def _strategy(
+ *, primary="searxng", mode="full", scope="public_only", extra=None
+):
+ snapshot = {
+ "search.tool": primary,
+ "search.fetch.mode": mode,
+ "search.fetch.max_per_topic": 2,
+ "policy.egress_scope": scope,
+ }
+ snapshot.update(extra or {})
+ return strategy_module.LangGraphAgentStrategy(
+ model=MagicMock(),
+ search=MagicMock(),
+ citation_handler=object(),
+ max_sub_iterations=1,
+ include_sub_research=True,
+ settings_snapshot=snapshot,
+ programmatic_mode=True,
+ )
+
+
+def _lead_and_subagent_tools(strategy, factories):
+ lead = strategy._build_tools("How did this page change over time?")
+ research = next(tool for tool in lead if tool.name == "research_subtopic")
+ research.invoke({"subtopics": ["Historical policy changes"]})
+ assert len(factories.created) == 1
+ return lead, factories.created[0].tools
+
+
[email protected]("primary", ["searxng", "wayback"])
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+def test_lead_and_subagent_get_archive_fetch_instead_of_wayback_search(
+ primary, mode, factories
+):
+ strategy = _strategy(primary=primary, mode=mode)
+
+ lead, subagent = _lead_and_subagent_tools(strategy, factories)
+
+ for tools in (lead, subagent):
+ names = [tool.name for tool in tools]
+ assert names.count("fetch_archive") == 1
+ assert "fetch_content" in names
+ assert "search_arxiv" in names
+ assert "search_wayback" not in names
+ if primary == "wayback":
+ assert "web_search" not in names
+ else:
+ assert "web_search" in names
+ archive_tool = next(
+ tool for tool in tools if tool.name == "fetch_archive"
+ )
+ assert set(archive_tool.args) == (
+ {"url", "date"} if mode == "full" else {"url", "date", "focus"}
+ )
+ assert "search_wayback" not in factories.created[0].prompt
+ assert "wayback" not in {
+ call.args[0] for call in factories.specialized_search.call_args_list
+ }
+ if primary == "wayback":
+ factories.web_search.assert_not_called()
+ else:
+ assert factories.web_search.call_count == 2
+
+
[email protected]("primary", ["searxng", "wayback"])
+ "extra",
+ [
+ {"search.engine.web.wayback.agent_enabled": False},
+ {
+ "search.engine.web.wayback.agent_enabled": {
+ "value": False,
+ "ui_element": "checkbox",
+ }
+ },
+ {"search.fetch.mode": "disabled"},
+ ],
+ ids=["disabled_archive", "wrapped_disabled_archive", "disabled_fetch_mode"],
+)
+def test_archive_flag_and_fetch_mode_hide_tool_from_both_agent_roles(
+ primary, extra, factories
+):
+ strategy = _strategy(primary=primary, extra=extra)
+
+ lead, subagent = _lead_and_subagent_tools(strategy, factories)
+
+ for tools in (lead, subagent):
+ names = {tool.name for tool in tools}
+ assert "fetch_archive" not in names
+ assert "search_wayback" not in names
+ assert "search_arxiv" in names
+ if primary == "wayback":
+ assert "web_search" not in names
+ if extra.get("search.fetch.mode") == "disabled":
+ assert "fetch_content" not in names
+ else:
+ assert "fetch_content" in names
+ assert "wayback" not in {
+ call.args[0] for call in factories.specialized_search.call_args_list
+ }
+
+
[email protected]("primary", ["searxng", "wayback"])
[email protected]("flag", [0, "off", "no", " false "])
[email protected]("wrapped", [False, True], ids=["raw", "wrapped"])
+def test_disabled_boolean_encodings_hide_archive_from_both_agent_roles(
+ primary, flag, wrapped, factories
+):
+ setting = {"value": flag, "ui_element": "checkbox"} if wrapped else flag
+ strategy = _strategy(
+ primary=primary,
+ extra={"search.engine.web.wayback.agent_enabled": setting},
+ )
+
+ lead, subagent = _lead_and_subagent_tools(strategy, factories)
+
+ for tools in (lead, subagent):
+ names = {tool.name for tool in tools}
+ assert "fetch_archive" not in names
+ assert "search_wayback" not in names
+ assert "fetch_content" in names
+ assert "search_arxiv" in names
+ assert ("web_search" in names) == (primary != "wayback")
+
+
[email protected]("scope", ["private_only", "strict"])
+def test_egress_policy_hides_archive_tool_from_lead_and_subagents(
+ scope, factories
+):
+ strategy = _strategy(scope=scope)
+
+ lead, subagent = _lead_and_subagent_tools(strategy, factories)
+
+ for tools in (lead, subagent):
+ names = {tool.name for tool in tools}
+ assert "fetch_archive" not in names
+ assert "search_wayback" not in names
+ assert "web_search" in names
+
+
+def test_archive_availability_is_bound_to_wayback_not_primary(factories):
+ strategy = _strategy()
+ names = [tool.name for tool in strategy._build_tools("Historical changes")]
+ assert "fetch_archive" in names
+ assert engine_for_tool("fetch_archive", "searxng") == "wayback"
+
+ strategy.engine_availability.disable(
+ "wayback", SearchFailure("Archive temporarily unavailable", None)
+ )
+ available = available_tool_names(
+ names, "searxng", strategy.engine_availability.disabled()
+ )
+
+ assert "fetch_archive" not in available
+ assert "fetch_content" in available
+ assert "web_search" in available
+ assert "search_arxiv" in available
+
+
[email protected]("enabled", [False, True])
+def test_strict_saved_wayback_prompt_only_names_available_archive_tool(
+ enabled, factories, monkeypatch
+):
+ strategy = _strategy(
+ primary="wayback",
+ scope="strict",
+ extra={"search.engine.web.wayback.agent_enabled": enabled},
+ )
+ captured = []
+
+ def capture_prompt(**kwargs):
+ captured.append(kwargs)
+ raise RuntimeError("Stop after capturing the prompt")
+
+ monkeypatch.setattr("langchain.agents.create_agent", capture_prompt)
+ monkeypatch.setattr(strategy, "_update_progress", Mock())
+ monkeypatch.setattr(strategy, "check_termination", Mock())
+ strategy.analyze_topic("Read https://example.com/history as it was in 2024")
+
+ assert len(captured) == 1
+ names = {tool.name for tool in captured[0]["tools"]}
+ prompt = captured[0]["system_prompt"]
+ assert ("fetch_archive" in names) is enabled
+ assert ("fetch_archive" in prompt) is enabled
+ if not enabled:
+ assert "Archive fetching is unavailable" in prompt
diff --git a/tests/strategies/test_langgraph_subagent_specialized_engines.py b/tests/strategies/test_langgraph_subagent_specialized_engines.py
index ed49bb571f..9e742ff585 100644
--- a/tests/strategies/test_langgraph_subagent_specialized_engines.py
+++ b/tests/strategies/test_langgraph_subagent_specialized_engines.py
@@ -269,7 +269,10 @@ class TestSubagentSpecializedEngines:
tool = strat._make_research_subtopic_tool(
search_engine_name="duckduckgo",
model=MagicMock(),
- settings_snapshot={"search.tool": "duckduckgo"},
+ settings_snapshot={
+ "search.tool": "duckduckgo",
+ "search.engine.web.wayback.agent_enabled": False,
+ },
collector=MagicMock(),
max_sub_iterations=1,
search_enabled=False,
diff --git a/tests/strategies/test_search_availability.py b/tests/strategies/test_search_availability.py
index b22980ada3..16d3b224b6 100644
--- a/tests/strategies/test_search_availability.py
+++ b/tests/strategies/test_search_availability.py
@@ -246,7 +246,7 @@ def test_subagent_uses_shared_availability_in_real_model_call(tracker):
availability=tracker,
)
assert "Subtopic findings" in tool.invoke({"subtopics": ["one"]})
- assert model.seen_tools == [["search_pubmed"]]
+ assert model.seen_tools == [["fetch_archive", "search_pubmed"]]
def test_heartbeat_shows_only_working_choices_and_explains_disabled(
@@ -503,12 +503,13 @@ def test_transient_failure_on_the_only_engine_waits_instead_of_ending(
assert model.seen_tools == [["web_search"]] * 3
[email protected]("fetch_name", ["fetch_content", "fetch_archive"])
def test_cooling_engines_are_waited_for_even_when_fetch_survives(
- tracker, clock
+ tracker, clock, fetch_name
):
"""Fetch alone cannot find sources; a cooldown ends before it helps."""
- @make_langchain_tool
+ @make_langchain_tool(fetch_name)
def fetch_content(url: str) -> str:
"""Fetch."""
return ""
@@ -537,10 +538,84 @@ def test_cooling_engines_are_waited_for_even_when_fetch_survives(
assert waited == [{"searxng", "pubmed"}]
assert [t.name for t in captured[0].tools] == [
"web_search",
- "fetch_content",
+ fetch_name,
]
+def test_archive_only_cooldown_waits_for_wayback(tracker, clock):
+ @make_langchain_tool
+ def fetch_archive(url: str) -> str:
+ """Read an archive capture."""
+ return ""
+
+ tracker.disable("wayback", SearchFailure("Archive unavailable", 60))
+ request = ModelRequest(model=Mock(), messages=[], tools=[fetch_archive])
+ waited = []
+
+ def wait(engines):
+ waited.append(engines)
+ clock.now = 60
+
+ captured = []
+ SearchAvailabilityMiddleware(tracker, "searxng", wait=wait).wrap_model_call(
+ request, captured.append
+ )
+ assert waited == [{"wayback"}]
+ assert [t.name for t in captured[0].tools] == ["fetch_archive"]
+
+
+def test_archive_outage_keeps_search_available_without_waiting(tracker):
+ @make_langchain_tool
+ def fetch_archive(url: str) -> str:
+ """Read an archive capture."""
+ return ""
+
+ tracker.disable("wayback", SearchFailure("Archive unavailable", 60))
+ request = ModelRequest(
+ model=Mock(),
+ messages=[],
+ tools=[make_tool("web_search", tracker), fetch_archive],
+ )
+ wait = Mock()
+ captured = []
+ SearchAvailabilityMiddleware(tracker, "searxng", wait=wait).wrap_model_call(
+ request, captured.append
+ )
+ wait.assert_not_called()
+ assert [t.name for t in captured[0].tools] == ["web_search"]
+ assert "Archive unavailable" in captured[0].system_message.content
+
+
+def test_archive_recovers_after_discovery_is_permanently_disabled(
+ tracker, clock
+):
+ @make_langchain_tool
+ def fetch_archive(url: str) -> str:
+ """Read an archive capture."""
+ return ""
+
+ tracker.disable("searxng", SearchFailure("Search unavailable", None))
+ tracker.disable("wayback", SearchFailure("Archive unavailable", 60))
+ request = ModelRequest(
+ model=Mock(),
+ messages=[HumanMessage(content="Read https://example.org in 2020")],
+ tools=[make_tool("web_search", tracker), fetch_archive],
+ )
+ waited = []
+
+ def wait(engines):
+ waited.append(engines)
+ clock.now = 60
+
+ captured = []
+ SearchAvailabilityMiddleware(tracker, "searxng", wait=wait).wrap_model_call(
+ request, captured.append
+ )
+ assert waited == [{"searxng", "wayback"}]
+ assert [t.name for t in captured[0].tools] == ["fetch_archive"]
+ assert "Search unavailable" in captured[0].system_message.content
+
+
def test_default_wait_sleeps_until_the_soonest_cooldown(tracker, clock):
tracker.disable("searxng", SearchFailure("offline", 3))
sleeps = []
@@ -725,7 +800,7 @@ def test_subagent_stops_cleanly_when_tools_are_exhausted(tracker, own_sources):
tool = strategy_module._make_research_subtopic_tool(
"searxng",
model,
- {},
+ {"search.engine.web.wayback.agent_enabled": False},
collector,
3,
search_enabled=False,
diff --git a/tests/test_advertised_but_dead_sweep.py b/tests/test_advertised_but_dead_sweep.py
index dd8743e6bb..dc614031b0 100644
--- a/tests/test_advertised_but_dead_sweep.py
+++ b/tests/test_advertised_but_dead_sweep.py
@@ -980,7 +980,9 @@ def test_search_engine_inventories_are_populated():
assert len(registry) >= 25, (
f"only {len(registry)} ENGINE_REGISTRY entries parsed"
)
- assert len(options) >= 15, (
+ # DDG/local_all are removed by the picker fix; Wayback is now a fetch
+ # tool. Retain a meaningful floor for the remaining search providers.
+ assert len(options) >= 14, (
f"only {len(options)} search.tool dropdown options parsed"
)
for landmark in ("searxng", "wikipedia", "brave"):
diff --git a/tests/utilities/test_archive_replay_citations.py b/tests/utilities/test_archive_replay_citations.py
new file mode 100644
index 0000000000..b255eb7b69
--- /dev/null
+++ b/tests/utilities/test_archive_replay_citations.py
@@ -0,0 +1,480 @@
+"""Archive citation identity and actual Sources display regression controls."""
+
+import pytest
+
+from local_deep_research.utilities import search_utilities
+from local_deep_research.utilities.search_utilities import (
+ count_distinct_sources,
+ extract_cited_indices_and_urls,
+ filter_cited_links,
+ format_links_to_markdown,
+)
+from local_deep_research.utilities.url_utils import canonical_url_key
+from local_deep_research.web_search_engines.wayback_client import (
+ validate_capture_fetch_url,
+)
+
+
+CAPTURE = "20240203112233"
+
+
+def replay_url(target, *, timestamp=CAPTURE, modifier="", scheme="https"):
+ return f"{scheme}://web.archive.org/web/{timestamp}{modifier}/{target}"
+
+
[email protected]("scheme", ["http", "https"])
[email protected]("modifier", ["", "id_", "if_"])
+ "target",
+ [
+ "https://example.com/history/",
+ "http://example.com/history/?utm_source=first&fbclid=capture#section",
+ "https://example.com/history?%75tm_source=first&&q=a+b&q=a%20b&",
+ "https://example.com/page?next=https://other.example/path/&version=1",
+ ],
+)
+def test_replay_canonical_key_preserves_complete_spelling(
+ scheme, modifier, target
+):
+ replay = replay_url(target, scheme=scheme, modifier=modifier)
+
+ assert canonical_url_key(replay) == replay
+
+
+ "first,second",
+ [
+ (
+ replay_url("https://example.com/history"),
+ replay_url("https://example.com/history/"),
+ ),
+ (
+ replay_url("https://example.com/history?utm_source=first"),
+ replay_url("https://example.com/history?utm_source=second"),
+ ),
+ (
+ replay_url("https://example.com/history?fbclid=first"),
+ replay_url("https://example.com/history?fbclid=second"),
+ ),
+ (
+ replay_url("https://example.com/history?x=1&y=2"),
+ replay_url("https://example.com/history?y=2&x=1"),
+ ),
+ (
+ replay_url("https://example.com/history"),
+ replay_url(
+ "https://example.com/history", timestamp="20250304123456"
+ ),
+ ),
+ (
+ replay_url("https://example.com/history"),
+ replay_url("https://example.com/history", modifier="id_"),
+ ),
+ ],
+)
+def test_distinct_capture_targets_have_distinct_canonical_keys(first, second):
+ assert canonical_url_key(first) != canonical_url_key(second)
+
+
[email protected]("modifier", ["", "id_", "if_"])
[email protected]("with_metadata", [False, True])
+def test_sources_renderer_preserves_guard_valid_replay_targets(
+ modifier, with_metadata
+):
+ targets = [
+ "https://example.com/history/?utm_source=first&fbclid=one#section",
+ "https://example.com/history?utm_source=second&fbclid=two#section",
+ ]
+ links = []
+ for index, target in enumerate(targets, 1):
+ link = {
+ "title": "Historical policy",
+ "link": replay_url(target, modifier=modifier),
+ "index": str(index),
+ }
+ if with_metadata:
+ link.update(
+ source_type="archive",
+ original_url=target,
+ timestamp=CAPTURE,
+ )
+ links.append(link)
+
+ rendered = format_links_to_markdown(links, uncited_mode="disabled")
+ displayed = [
+ line.removeprefix(" URL: ")
+ for line in rendered.splitlines()
+ if line.startswith(" URL: ")
+ ]
+
+ assert displayed == [link["link"] for link in links]
+ assert count_distinct_sources(links) == 2
+ for replay, target in zip(displayed, targets):
+ validate_capture_fetch_url(replay, CAPTURE, target)
+
+
+def test_repeated_exact_replay_still_groups_citation_indices():
+ replay = replay_url("https://example.com/history/?utm_source=first")
+ links = [
+ {"link": replay, "title": "Historical policy", "index": "1"},
+ {"link": replay, "title": "Historical policy", "index": "2"},
+ ]
+
+ rendered = format_links_to_markdown(links, uncited_mode="disabled")
+
+ assert rendered.count(" URL: ") == 1
+ assert f" URL: {replay}\n" in rendered
+ assert "[1, 2]" in rendered
+ assert count_distinct_sources(links) == 1
+
+
+ "url,expected",
+ [
+ (
+ "HTTPS://EXAMPLE.COM:443/history/?utm_source=x&v=1#part",
+ "https://example.com/history?v=1",
+ ),
+ (
+ "http://user:[email protected]:80/history/?fbclid=x",
+ "http://example.com/history",
+ ),
+ (
+ "https://web.archive.org/about/?utm_source=x#part",
+ "https://web.archive.org/about",
+ ),
+ (
+ "https://web.archive.org/web/20240203/https://example.com/history/?utm_source=x",
+ "https://web.archive.org/web/20240203/https://example.com/history",
+ ),
+ (
+ "https://web.archive.org.evil.example/web/20240203112233/https://example.com/history/?utm_source=x",
+ "https://web.archive.org.evil.example/web/20240203112233/https://example.com/history",
+ ),
+ (
+ "https://user:[email protected]/web/20240203112233/https://example.com/history/?utm_source=x",
+ "https://web.archive.org/web/20240203112233/https://example.com/history",
+ ),
+ ],
+)
+def test_live_and_non_capture_urls_keep_existing_canonical_behavior(
+ url, expected
+):
+ assert canonical_url_key(url) == expected
+
+
+def test_sources_renderer_keeps_existing_live_url_normalization():
+ rendered = format_links_to_markdown(
+ [
+ {
+ "link": "HTTPS://EXAMPLE.COM:443/history/?utm_source=x&v=1#part",
+ "title": "Current policy",
+ "index": "1",
+ }
+ ],
+ uncited_mode="disabled",
+ )
+
+ assert " URL: https://example.com/history?v=1\n" in rendered
+ assert "utm_source" not in rendered
+
+
+ "suffix",
+ [
+ "20240203112233im_/https://example.com/history/",
+ "٢٠٢٤٠٢٠٣١١٢٢٣٣/https://example.com/history/",
+ "20240203112233/https://example.com:65536/history/",
+ "20240203112233/https://example.com/his\ntory/",
+ "20240203112233/https://example.com/his\ttory/",
+ ],
+)
+def test_invalid_replay_shapes_use_existing_normalization(suffix):
+ replay = f"https://web.archive.org/web/{suffix}?utm_source=x"
+ expected_path = suffix.replace("\n", "").replace("\t", "").rstrip("/")
+
+ assert canonical_url_key(replay) == (
+ f"https://web.archive.org/web/{expected_path}"
+ )
+
+
+ "replay",
+ [
+ "HTTP://WEB.ARCHIVE.ORG:80/web/20240203112233/https://example.com/history/?utm_source=x",
+ "https://web.archive.org:443/web/20240203112233/https://example.com/history/?fbclid=x",
+ replay_url("https://example.com/history/?"),
+ replay_url("https://example.com/history/#"),
+ ],
+)
+def test_replay_wrapper_and_empty_delimiters_stay_verbatim(replay):
+ assert canonical_url_key(replay) == replay
+
+
+def test_sources_renderer_preserves_legacy_http_replay_spelling():
+ replay = replay_url(
+ "https://example.com/history/?utm_source=first#section", scheme="http"
+ )
+
+ rendered = format_links_to_markdown(
+ [{"link": replay, "title": "Historical policy", "index": "1"}],
+ uncited_mode="disabled",
+ )
+
+ assert f" URL: {replay}\n" in rendered
+
+
+ "target",
+ [
+ "http://[::ffff:8.8.8.8]:80/history/?utm_source=first#part",
+ "https://[2001:4860:4860::8888]:8443/owner's/history/"
+ "?next=https://other.example/a/&fbclid=one#part",
+ "https://example.com/history/"
+ "?next=http://[::ffff:8.8.8.8]:8080/a/&q=owner's#part",
+ "https://example.com/history/[Part]/"
+ "?next=https://[2001:4860:4860::8888]:443/a/&q[range]=[alpha]#part",
+ "https://[2606:4700:4700::1111]",
+ "https://example.org/a[b[c]]?values=[x[y]]",
+ "https://[2001:4860:4860::8888]:8443/a[b[c]]"
+ "?values=[x[y]]&next=https://[2606:4700:4700::1111]/a/#part",
+ ],
+)
+ "template",
+ [
+ "Read {url}. See [4].",
+ "Read [History]({url}). See [4].",
+ "Read [History](<{url}>). See [4].",
+ "Read <{url}>. See [4].",
+ "Read [{url}]. See [4].",
+ "Read {url}[4].",
+ ],
+)
+def test_replay_url_citations_preserve_brackets_and_select_one_capture(
+ target, template
+):
+ replay = replay_url(target)
+ cited = {"index": "7", "title": "Archived", "url": replay}
+ other_capture = {
+ "index": "8",
+ "title": "Other capture",
+ "url": replay_url(target, timestamp="20250304123456"),
+ }
+ truncated = {
+ "index": "9",
+ "title": "Truncated target",
+ "url": f"https://web.archive.org/web/{CAPTURE}/https:",
+ }
+ other = {"index": "4", "title": "Other", "url": "https://other.example/a"}
+ prose = template.format(url=replay)
+ links = [cited, other_capture, truncated, other]
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {4}
+ assert replay in urls
+ assert not indeterminate
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, prose, mode=mode) == [cited, other]
+ rendered = format_links_to_markdown(
+ links, prose=prose, uncited_mode="strict"
+ )
+ assert f" URL: {replay}\n" in rendered
+ assert "Other capture" not in rendered
+ assert "Truncated target" not in rendered
+ assert rendered.count(" URL: ") == 2
+ validate_capture_fetch_url(replay, CAPTURE, target)
+
+
+ "template",
+ [
+ "Reference [1, {url},bad]. See [4].",
+ "Reference [1,\n{url} bad]. See [4].",
+ "Read {url} and [1,abc,3]. See [4].",
+ ],
+)
+def test_replay_ip_masking_preserves_malformed_body_reference_fallback(
+ template,
+):
+ replay = replay_url("https://[2001:4860:4860::8888]/history/")
+ links = [
+ {"index": "7", "url": replay},
+ {"index": "8", "url": replay_url("https://other.example/a")},
+ {"index": "4", "url": "https://other.example/four"},
+ ]
+ prose = template.format(url=replay)
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ assert filter_cited_links(links, prose, mode="strict") == links
+
+
+def test_bare_replay_preserves_consecutive_numeric_reference_boundaries():
+ target = "http://[::ffff:8.8.8.8]:80/history/[Part]/?values=[x[y]]"
+ replay = replay_url(target)
+ archived = {"index": "7", "url": replay, "title": "Archived"}
+ other_capture = {
+ "index": "8",
+ "url": replay_url(target, timestamp="20250304123456"),
+ "title": "Other capture",
+ }
+ fourth = {"index": "4", "url": "https://other.example/four"}
+ third = {"index": "3", "url": "https://other.example/three"}
+ links = [archived, other_capture, fourth, third]
+ prose = f"Read {replay}[4][3]."
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {3, 4}
+ assert replay in urls
+ assert not indeterminate
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, prose, mode=mode) == [
+ archived,
+ fourth,
+ third,
+ ]
+ rendered = format_links_to_markdown(
+ links, prose=prose, uncited_mode="strict"
+ )
+ assert f" URL: {replay}\n" in rendered
+ assert rendered.count(" URL: ") == 3
+ assert "Other capture" not in rendered
+ validate_capture_fetch_url(replay, CAPTURE, target)
+
+
+ "template", ["[old]({first})[new]({second})", "({first})({second})"]
+)
+def test_adjacent_wrapped_replays_keep_both_captures_and_balanced_parentheses(
+ template,
+):
+ target = "https://[2001:4860:4860::8888]:8443/a_(history)[b[c]]?values=[x[y]]&doc=(a)"
+ first = replay_url(target)
+ second = replay_url(target, timestamp="20250304123456")
+ links = [
+ {"index": "7", "url": first, "title": "Old"},
+ {"index": "8", "url": second, "title": "New"},
+ {"index": "9", "url": replay_url(target, timestamp="20260101000000")},
+ ]
+ prose = template.format(first=first, second=second)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert not indices
+ assert {first, second} <= urls
+ assert not indeterminate
+ assert filter_cited_links(links, prose, mode="strict") == links[:2]
+ rendered = format_links_to_markdown(
+ links, prose=prose, uncited_mode="strict"
+ )
+ assert f" URL: {first}\n" in rendered
+ assert f" URL: {second}\n" in rendered
+ assert rendered.count(" URL: ") == 2
+ validate_capture_fetch_url(first, CAPTURE, target)
+ validate_capture_fetch_url(second, "20250304123456", target)
+
+
[email protected]("remaining", [-1, 0, 1])
+def test_replay_candidate_work_budget_boundary_includes_both_passes(
+ monkeypatch, remaining
+):
+ replay = replay_url("https://example.com/history")
+ # One exact candidate is inspected by IP masking and URL extraction.
+ monkeypatch.setattr(
+ search_utilities,
+ "_MAX_URL_CANDIDATE_CHARS",
+ 2 * len(replay) + remaining,
+ )
+ _, urls, indeterminate = extract_cited_indices_and_urls(replay)
+
+ assert indeterminate is (remaining < 0)
+ if not indeterminate:
+ assert urls == {replay}
+
+
+def test_replay_candidate_work_budget_is_shared_across_urls_and_passes(
+ monkeypatch,
+):
+ monkeypatch.setattr(search_utilities, "_MAX_URL_CANDIDATE_CHARS", 50_000)
+ first = replay_url("https://example.com/first") + "[1]" * 80
+ second = replay_url("https://example.com/other") + "[2]" * 80
+ assert not extract_cited_indices_and_urls(first)[2]
+ assert not extract_cited_indices_and_urls(second)[2]
+
+ prose = f"{first} {second}"
+ _, partial_urls, indeterminate = extract_cited_indices_and_urls(prose)
+ assert partial_urls # The first URL was already parsed successfully.
+ assert indeterminate
+ links = [
+ {"index": "7", "url": first},
+ {"index": "8", "url": second},
+ {"index": "9", "url": "https://uncited.example/kept"},
+ ]
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, prose, mode=mode) is links
+
+
+def test_bare_replay_candidates_keep_intermediate_literal_bracket_suffixes():
+ base = replay_url("https://example.com/history")
+ middle = base + "[1]"
+ full = base + "[1][2][3]"
+ links = [
+ {"index": "10", "url": base},
+ {"index": "20", "url": middle},
+ {"index": "30", "url": full},
+ {"index": "40", "url": "https://uncited.example/omitted"},
+ ]
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(full)
+
+ assert indices == {1, 2, 3}
+ assert not indeterminate
+ assert {base, middle, base + "[1][2]", full} <= urls
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, full, mode=mode) == links[:3]
+
+
[email protected]("template", ["<{url}>", "[capture]({url})"])
+def test_exact_replay_destination_does_not_gain_prefix_interpretations(
+ template,
+):
+ base = replay_url("https://example.com/history")
+ full = base + "[1][2][3]"
+ links = [
+ {"index": "10", "url": base},
+ {"index": "20", "url": base + "[1]"},
+ {"index": "30", "url": full},
+ ]
+ prose = template.format(url=full)
+
+ _, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert not indeterminate
+ assert urls == {full}
+ assert filter_cited_links(links, prose, mode="strict") == links[2:]
+
+
[email protected]("mode", ["strict", "fallback"])
+def test_long_replay_reference_run_keeps_complete_bibliography(mode):
+ base = replay_url("https://example.com/history")
+ middle = base + "[1]" * 512
+ full = base + "[1]" * 1024
+ links = [
+ {"index": "10", "title": "Base", "url": base},
+ {"index": "20", "title": "Middle", "url": middle},
+ {"index": "30", "title": "Full", "url": full},
+ {
+ "index": "40",
+ "title": "Uncited",
+ "url": "https://uncited.example/kept",
+ },
+ ]
+
+ assert extract_cited_indices_and_urls(full)[2]
+ assert filter_cited_links(links, full, mode=mode) is links
+ rendered = format_links_to_markdown(links, prose=full, uncited_mode=mode)
+ for link in links:
+ assert f" URL: {link['url']}\n" in rendered
+ assert rendered.count(" URL: ") == len(links)
diff --git a/tests/web/routers/test_wayback_picker_transition.py b/tests/web/routers/test_wayback_picker_transition.py
new file mode 100644
index 0000000000..7ec632c396
--- /dev/null
+++ b/tests/web/routers/test_wayback_picker_transition.py
@@ -0,0 +1,78 @@
+"""Execute the real runtime options endpoint without mutating saved choices."""
+
+from contextlib import nullcontext
+from copy import deepcopy
+from unittest.mock import Mock
+
+import pytest
+from starlette.requests import Request
+
+from local_deep_research.config.thread_settings import get_setting_from_snapshot
+from local_deep_research.security import module_whitelist
+from local_deep_research.web.routers import settings as settings_router
+from local_deep_research.web_search_engines import search_engines_config
+from local_deep_research.web_search_engines.retriever_registry import (
+ retriever_registry,
+)
+from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+)
+
+
+ "query", [b"", b"egress_scope=public_only&primary=wayback"]
+)
+def test_runtime_picker_omits_only_archive_adapter(monkeypatch, query):
+ snapshot = {
+ "search.tool": "wayback",
+ "search.favorites": ["wayback", "wikipedia", "local_all"],
+ "search.engine.library.enabled": False,
+ "search.engine.web.wayback.display_name": "Wayback",
+ "search.engine.web.wayback.agent_enabled": True,
+ "search.engine.web.wayback.use_in_auto_search": True,
+ "search.engine.web.wikipedia.display_name": "Wikipedia",
+ # Preserve unrelated provider entries even if they lack registry
+ # wiring; the canonical picker cleanup is a separate change.
+ "search.engine.web.duckduckgo.display_name": "DuckDuckGo",
+ "search.engine.web.local_all.display_name": "Local All",
+ }
+ before = deepcopy(snapshot)
+ manager = Mock()
+ manager.get_setting.side_effect = lambda key, default=None: (
+ get_setting_from_snapshot(key, default, settings_snapshot=snapshot)
+ )
+ manager.get_settings_snapshot.return_value = snapshot
+ session = Mock()
+ monkeypatch.setattr(
+ settings_router,
+ "get_user_db_session",
+ lambda username: nullcontext(session),
+ )
+ monkeypatch.setattr(
+ settings_router, "get_settings_manager", lambda *args: manager
+ )
+ monkeypatch.setattr(
+ search_engines_config, "get_settings_manager", lambda *args: manager
+ )
+ monkeypatch.setattr(retriever_registry, "list_registered", lambda **kw: [])
+ monkeypatch.setattr(
+ module_whitelist,
+ "get_safe_module_class",
+ lambda *args: BaseSearchEngine,
+ )
+ request = Request(
+ {"type": "http", "method": "GET", "path": "/", "query_string": query}
+ )
+
+ result = settings_router.api_get_available_search_engines(
+ request, username="archive-picker-user"
+ )
+
+ expected = {"wikipedia", "duckduckgo", "local_all"}
+ assert isinstance(result, dict)
+ assert {option["value"] for option in result["engine_options"]} == expected
+ assert set(result["engines"]) == expected
+ assert result["favorites"] == before["search.favorites"]
+ assert snapshot == before
+ manager.set_setting.assert_not_called()
+ session.commit.assert_not_called()
diff --git a/tests/web/services/test_archive_report_citations.py b/tests/web/services/test_archive_report_citations.py
new file mode 100644
index 0000000000..428699c432
--- /dev/null
+++ b/tests/web/services/test_archive_report_citations.py
@@ -0,0 +1,368 @@
+"""Archive provenance survives live and persisted Sources reconstruction."""
+
+from copy import deepcopy
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.base_strategy import (
+ BaseSearchStrategy,
+)
+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+)
+from local_deep_research.advanced_search_system.tools.fetch import (
+ _register_in_collector,
+)
+from local_deep_research.database.models.research import (
+ ResearchHistory,
+ ResearchResource,
+)
+from local_deep_research.utilities.search_utilities import (
+ extract_links_from_search_results,
+)
+from local_deep_research.utilities.url_utils import FETCHED_TITLE_KEY
+from local_deep_research.web.services.report_assembly_service import (
+ assemble_full_report,
+)
+from local_deep_research.web_search_engines.wayback_client import (
+ validate_capture_fetch_url,
+)
+
+
+CAPTURE = "20240203112233"
+DATE = "2024-02-03 11:22:33 UTC"
+TARGET = (
+ "https://example.com/owner's/history/"
+ "?utm_source=first&fbclid=one&next=https://nested.example/path/#part"
+)
+REPLAY = f"https://web.archive.org/web/{CAPTURE}/{TARGET}"
+ARCHIVE_METADATA = {
+ "source_type": "archive",
+ "original_url": TARGET,
+ "requested_url": TARGET.replace(
+ "https://example.com", "http://www.example.com"
+ ),
+ "timestamp": CAPTURE,
+ "formatted_date": DATE,
+}
+CITATION_CASES = [
+ pytest.param(True, 1, id="same-excerpt-upgraded-index"),
+ pytest.param(False, 1, id="different-excerpt-original-index"),
+ pytest.param(False, 2, id="different-excerpt-archive-index"),
+]
+
+
+def _archived_results(same_excerpt, cited_index, reset):
+ collector = SearchResultsCollector([])
+ assert (
+ _register_in_collector(
+ collector, REPLAY, "First fetched title", "Original excerpt"
+ )
+ == 1
+ )
+ archive_index = _register_in_collector(
+ collector,
+ REPLAY,
+ "Historical page",
+ "Original excerpt" if same_excerpt else "Different archived excerpt",
+ ARCHIVE_METADATA,
+ )
+ assert archive_index == (1 if same_excerpt else 2)
+ assert collector.find_by_index(1)["snippet"] == "Original excerpt"
+ assert collector.find_by_index(archive_index)[FETCHED_TITLE_KEY] == (
+ "First fetched title"
+ )
+ if reset:
+ tracked = collector.find_by_index(cited_index)
+ collector.reset()
+ assert (
+ collector.find_or_add_result(
+ {
+ "link": REPLAY,
+ "title": "Later generic title",
+ "snippet": tracked["snippet"],
+ }
+ )
+ == cited_index
+ )
+ return collector.results
+
+
+def _assert_archive_sources(output, cited_index):
+ assert output.count("## Sources") == 1
+ sources = output.split("## Sources\n\n", 1)[1]
+ assert sources.startswith(
+ f"[{cited_index}] First fetched title (archived {DATE}) "
+ )
+ assert sources.count(f"(archived {DATE})") == 1
+ displayed = [
+ line.removeprefix(" URL: ")
+ for line in sources.splitlines()
+ if line.startswith(" URL: ")
+ ]
+ assert displayed == [REPLAY]
+ validate_capture_fetch_url(displayed[0], CAPTURE, TARGET)
+
+
[email protected]("same_excerpt,cited_index", CITATION_CASES)
+ "reset", [False, True], ids=["same-section", "after-reset"]
+)
+def test_live_sources_preserve_archive_date_after_metadata_rebuild(
+ same_excerpt, cited_index, reset
+):
+ results = _archived_results(same_excerpt, cited_index, reset)
+ before = deepcopy(results)
+ settings_owner = SimpleNamespace(get_setting=Mock(return_value="strict"))
+ body = f"Historical finding [{cited_index}]."
+
+ output = BaseSearchStrategy._format_citations(settings_owner, body, results)
+
+ _assert_archive_sources(output, cited_index)
+ settings_owner.get_setting.assert_called_once_with(
+ "report.uncited_sources_mode"
+ )
+ assert results == before
+
+
[email protected]("same_excerpt,cited_index", CITATION_CASES)
+ "reset", [False, True], ids=["same-section", "after-reset"]
+)
+def test_saved_report_preserves_archive_date_after_json_round_trip(
+ report_db, same_excerpt, cited_index, reset
+):
+ results = _archived_results(same_excerpt, cited_index, reset)
+ research = report_db.get(ResearchHistory, "report-errors")
+ body = f"Historical finding [{cited_index}]."
+ research.report_content = body
+ research.research_meta = {
+ "settings_snapshot": {"report.uncited_sources_mode": "strict"}
+ }
+ for result in results:
+ report_db.add(
+ ResearchResource(
+ research_id=research.id,
+ title=result["title"],
+ url=result["link"],
+ source_type=result["source_type"],
+ resource_metadata={"original_data": dict(result)},
+ created_at="2026-10-11T00:00:00+00:00",
+ )
+ )
+ report_db.commit()
+ report_db.expire_all()
+
+ output = assemble_full_report(research, report_db)
+
+ _assert_archive_sources(output, cited_index)
+ assert research.report_content == body
+ resources = report_db.query(ResearchResource).all()
+ assert all(
+ resource.resource_metadata["original_data"]["formatted_date"] == DATE
+ for resource in resources
+ )
+
+
+def test_live_link_extraction_preserves_complete_archive_provenance():
+ results = _archived_results(False, 2, False)
+ before = deepcopy(results)
+
+ extracted = extract_links_from_search_results(results)
+
+ assert [link["index"] for link in extracted] == ["1", "2"]
+ assert all(link["url"] == REPLAY for link in extracted)
+ for link in extracted:
+ assert all(
+ link[field] == value for field, value in ARCHIVE_METADATA.items()
+ )
+ assert results == before
+
+
+def test_live_sources_keep_existing_url_normalization():
+ result = {
+ "link": "HTTPS://EXAMPLE.COM:443/current/?utm_source=ignored&v=1#part",
+ "title": "Current page",
+ "index": "1",
+ }
+ settings_owner = SimpleNamespace(get_setting=lambda key: "strict")
+
+ output = BaseSearchStrategy._format_citations(
+ settings_owner, "Current finding [1].", [result]
+ )
+
+ assert " URL: https://example.com/current?v=1\n" in output
+ assert "archived" not in output
+
+
+REPLAY_TARGETS = [
+ "http://[::ffff:8.8.8.8]:80/owner's/history/"
+ "?utm_source=first&next=https://other.example/a/#part",
+ "https://example.com/history/[Part]/"
+ "?next=https://[2001:4860:4860::8888]:8443/a/&q[range]=[alpha]#part",
+ "https://example.org/a[b[c]]?values=[x[y]]",
+ "https://[2001:4860:4860::8888]:8443/a[b[c]]"
+ "?values=[x[y]]&next=https://[2606:4700:4700::1111]/a/#part",
+]
+REPLAY_TEMPLATES = [
+ "Historical finding {url}. See [4].",
+ "Historical finding [History]({url}). See [4].",
+ "Historical finding [History](<{url}>). See [4].",
+ "Historical finding {url}[4].",
+]
+
+
+def _url_cited_archive_results(target):
+ replay = f"https://web.archive.org/web/{CAPTURE}/{target}"
+ archive = {
+ "link": replay,
+ "title": "Historical page",
+ "index": "7",
+ FETCHED_TITLE_KEY: "First fetched title",
+ "source_type": "archive",
+ "original_url": target,
+ "requested_url": target,
+ "timestamp": CAPTURE,
+ "formatted_date": DATE,
+ }
+ later = dict(
+ archive,
+ link=f"https://web.archive.org/web/20250304123456/{target}",
+ index="8",
+ timestamp="20250304123456",
+ formatted_date="2025-03-04 12:34:56 UTC",
+ )
+ other = {
+ "link": "https://other.example/four",
+ "title": "Other source",
+ "source_type": "web",
+ "index": "4",
+ }
+ return [archive, later, other]
+
+
+def _assert_url_cited_archive_sources(output, results):
+ sources = output.split("## Sources\n\n", 1)[1]
+ assert f"[7] First fetched title (archived {DATE}) " in sources
+ assert "[4] Other source " in sources
+ assert "[8]" not in sources
+ assert "2025-03-04" not in sources
+ assert sources.count(f"(archived {DATE})") == 1
+ displayed = [
+ line.removeprefix(" URL: ")
+ for line in sources.splitlines()
+ if line.startswith(" URL: ")
+ ]
+ assert displayed == [results[0]["link"], results[2]["link"]]
+ validate_capture_fetch_url(
+ displayed[0], CAPTURE, results[0]["original_url"]
+ )
+
+
[email protected]("target", REPLAY_TARGETS)
[email protected]("template", REPLAY_TEMPLATES)
+def test_live_sources_keep_url_cited_replay_with_ipv6_and_other_index(
+ target, template
+):
+ results = _url_cited_archive_results(target)
+ before = deepcopy(results)
+ body = template.format(url=results[0]["link"])
+ owner = SimpleNamespace(get_setting=lambda key: "strict")
+
+ output = BaseSearchStrategy._format_citations(owner, body, results)
+
+ _assert_url_cited_archive_sources(output, results)
+ assert results == before
+
+
[email protected]("target", REPLAY_TARGETS)
[email protected]("template", REPLAY_TEMPLATES)
+def test_saved_sources_keep_url_cited_replay_with_ipv6_and_other_index(
+ report_db, target, template
+):
+ results = _url_cited_archive_results(target)
+ research = report_db.get(ResearchHistory, "report-errors")
+ body = template.format(url=results[0]["link"])
+ research.report_content = body
+ research.research_meta = {
+ "settings_snapshot": {"report.uncited_sources_mode": "strict"}
+ }
+ for result in results:
+ report_db.add(
+ ResearchResource(
+ research_id=research.id,
+ title=result["title"],
+ url=result["link"],
+ source_type=result["source_type"],
+ resource_metadata={"original_data": dict(result)},
+ created_at="2026-10-11T00:00:00+00:00",
+ )
+ )
+ report_db.commit()
+ report_db.expire_all()
+
+ output = assemble_full_report(research, report_db)
+
+ _assert_url_cited_archive_sources(output, results)
+ assert research.report_content == body
+
+
+def _assert_adjacent_capture_sources(output, results):
+ sources = output.split("## Sources\n\n", 1)[1]
+ assert f"[7] First fetched title (archived {DATE}) " in sources
+ assert (
+ "[8] First fetched title (archived 2025-03-04 12:34:56 UTC) " in sources
+ )
+ assert "[4] Other source " in sources
+ displayed = [
+ line.removeprefix(" URL: ")
+ for line in sources.splitlines()
+ if line.startswith(" URL: ")
+ ]
+ assert displayed == [result["link"] for result in results]
+ for result in results[:2]:
+ validate_capture_fetch_url(
+ result["link"], result["timestamp"], result["original_url"]
+ )
+
+
+def test_live_sources_keep_adjacent_markdown_capture_links():
+ target = "https://[2001:4860:4860::8888]:8443/a_(history)[b[c]]?values=[x[y]]&doc=(a)"
+ results = _url_cited_archive_results(target)
+ body = f"[old]({results[0]['link']})[new]({results[1]['link']}). See [4]."
+ owner = SimpleNamespace(get_setting=lambda key: "strict")
+
+ output = BaseSearchStrategy._format_citations(owner, body, results)
+
+ _assert_adjacent_capture_sources(output, results)
+
+
+def test_saved_sources_keep_adjacent_markdown_capture_links(report_db):
+ target = "https://[2001:4860:4860::8888]:8443/a_(history)[b[c]]?values=[x[y]]&doc=(a)"
+ results = _url_cited_archive_results(target)
+ research = report_db.get(ResearchHistory, "report-errors")
+ body = f"[old]({results[0]['link']})[new]({results[1]['link']}). See [4]."
+ research.report_content = body
+ research.research_meta = {
+ "settings_snapshot": {"report.uncited_sources_mode": "strict"}
+ }
+ for result in results:
+ report_db.add(
+ ResearchResource(
+ research_id=research.id,
+ title=result["title"],
+ url=result["link"],
+ source_type=result["source_type"],
+ resource_metadata={"original_data": dict(result)},
+ created_at="2026-10-11T00:00:00+00:00",
+ )
+ )
+ report_db.commit()
+ report_db.expire_all()
+
+ output = assemble_full_report(research, report_db)
+
+ _assert_adjacent_capture_sources(output, results)
+ assert research.report_content == body
diff --git a/tests/web_search_engines/engines/test_search_engine_wayback.py b/tests/web_search_engines/engines/test_search_engine_wayback.py
index 47be632d94..fb70bda04c 100644
--- a/tests/web_search_engines/engines/test_search_engine_wayback.py
+++ b/tests/web_search_engines/engines/test_search_engine_wayback.py
@@ -87,13 +87,12 @@ class TestExtractUrlsFromQuery:
engine = WaybackSearchEngine()
- # Note: The regex only captures domain, not path
urls = engine._extract_urls_from_query(
"Check https://example.com/page archive"
)
assert len(urls) == 1
- assert urls[0] == "https://example.com"
+ assert urls[0] == "https://example.com/page"
def test_extract_multiple_urls(self):
"""Extract multiple URLs from query."""
@@ -122,8 +121,8 @@ class TestExtractUrlsFromQuery:
assert len(urls) == 1
assert urls[0] == "http://example.com"
- def test_partial_url_without_scheme_is_not_extracted(self):
- """A domain with a path but no scheme is not an archive target."""
+ def test_extract_partial_url(self):
+ """Extract partial URL with path."""
from local_deep_research.web_search_engines.engines.search_engine_wayback import (
WaybackSearchEngine,
)
@@ -132,7 +131,8 @@ class TestExtractUrlsFromQuery:
urls = engine._extract_urls_from_query("example.com/page")
- assert urls == []
+ assert len(urls) == 1
+ assert urls[0] == "http://example.com/page"
def test_extract_no_urls_found(self):
"""Return empty when no URLs found."""
diff --git a/tests/web_search_engines/engines/test_search_engine_wayback_coverage.py b/tests/web_search_engines/engines/test_search_engine_wayback_coverage.py
index 0d1f9663ad..77dd99f0ef 100644
--- a/tests/web_search_engines/engines/test_search_engine_wayback_coverage.py
+++ b/tests/web_search_engines/engines/test_search_engine_wayback_coverage.py
@@ -3,8 +3,8 @@ Coverage tests for WaybackSearchEngine targeting statements not hit by
the existing test_search_engine_wayback.py.
Covers:
-- _extract_urls_from_query: plain text and partial URLs without a scheme
- return no targets; a bare domain is accepted without provider discovery
+- _extract_urls_from_query: plain text returns no targets; complete domains
+ and partial URLs are accepted without provider discovery
- _format_timestamp: exception path returns raw timestamp
- _get_wayback_snapshots: CDX rate-limit (429); CDX response with only header row;
generic exception is swallowed and returns []
@@ -54,8 +54,10 @@ class TestExtractUrlsFromQueryExtra:
def test_plain_text_has_no_archive_target(self):
assert _engine()._extract_urls_from_query("some plain text query") == []
- def test_partial_url_without_scheme_has_no_archive_target(self):
- assert _engine()._extract_urls_from_query("example.com/some/path") == []
+ def test_partial_url_dot_and_slash_branch(self):
+ assert _engine()._extract_urls_from_query("example.com/some/path") == [
+ "http://example.com/some/path"
+ ]
def test_domain_without_protocol(self):
assert _engine()._extract_urls_from_query("example.org") == [
diff --git a/tests/web_search_engines/test_engine_availability.py b/tests/web_search_engines/test_engine_availability.py
index 51ceaf07f7..cfca2e0b86 100644
--- a/tests/web_search_engines/test_engine_availability.py
+++ b/tests/web_search_engines/test_engine_availability.py
@@ -104,6 +104,8 @@ def test_retry_after_seconds_and_http_date(clock):
(RateLimitError("secret", retry_after=90), "Rate limit", 90),
(requests.Timeout("secret"), "timed out", 60),
(requests.ConnectionError("secret"), "connect", 60),
+ (requests.exceptions.ChunkedEncodingError("secret"), "read", 60),
+ (requests.exceptions.ContentDecodingError("secret"), "read", 60),
# The validator also refuses unresolvable hosts, so a transient DNS
# failure must not disable the engine for the whole research.
(ValueError("URL failed security validation: secret"), "blocked", 300),
@@ -501,25 +503,26 @@ def test_error_before_previews_is_still_an_engine_failure():
assert "connect" in engine.last_search_failure.reason
-def test_delegation_is_not_offered_when_only_fetch_remains():
[email protected]("fetch_name", ["fetch_content", "fetch_archive"])
+def test_delegation_is_not_offered_when_only_fetch_remains(fetch_name):
names = [
"web_search",
"search_pubmed",
- "fetch_content",
+ fetch_name,
"research_subtopic",
]
disabled = {"searxng": object(), "pubmed": object()}
- assert available_tool_names(names, "searxng", disabled) == ["fetch_content"]
+ assert available_tool_names(names, "searxng", disabled) == [fetch_name]
# While any search tool works, delegation stays.
assert available_tool_names(names, "searxng", {"pubmed": object()}) == [
"web_search",
- "fetch_content",
+ fetch_name,
"research_subtopic",
]
# A toolbox configured without search is not availability's business.
assert available_tool_names(
- ["fetch_content", "research_subtopic"], "searxng", disabled
- ) == ["fetch_content", "research_subtopic"]
+ [fetch_name, "research_subtopic"], "searxng", disabled
+ ) == [fetch_name, "research_subtopic"]
def test_run_long_failure_upgrades_an_active_cooldown(tracker, clock):
diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.py
index 378a4dfa10..55609fb1ff 100644
--- a/tests/web_search_engines/test_engine_success_path.py
+++ b/tests/web_search_engines/test_engine_success_path.py
@@ -879,9 +879,10 @@ TINYFISH_PAYLOAD = {
}
# CDX returns a header row followed by one row per capture.
+WAYBACK_URL = "https://example.com/page?version=1"
WAYBACK_CDX_PAYLOAD = [
["timestamp", "original", "statuscode", "mimetype"],
- ["20200101120000", "https://example.com/", "200", "text/html"],
+ ["20200101120000", WAYBACK_URL, "200", "text/html"],
]
WIKINEWS_TIMESTAMP = (datetime.now(UTC) - timedelta(days=3)).strftime(
@@ -1465,11 +1466,15 @@ def _drive_wayback(tracker):
tracker,
)
with patch.object(
- wayback_engine, "safe_get", const_response(payload=WAYBACK_CDX_PAYLOAD)
- ):
- # Wayback only works when the query *is* a URL -- see
- # ``test_wayback_returns_nothing_for_a_plain_research_question``.
- return engine._get_previews("https://example.com/")
+ wayback_engine,
+ "safe_get",
+ side_effect=const_response(payload=WAYBACK_CDX_PAYLOAD),
+ ) as archive_request:
+ previews = engine._get_previews(WAYBACK_URL)
+ archive_request.assert_called_once()
+ assert archive_request.call_args.args[0] == engine.cdx_api
+ assert archive_request.call_args.kwargs["params"]["url"] == WAYBACK_URL
+ return previews
def _wikinews_router(url, *_args, **kwargs):
@@ -1863,10 +1868,8 @@ CASES = [
Case(
"wayback",
_drive_wayback,
- # ``_extract_urls_from_query``'s regex stops at the path
- # separator, so the trailing slash of the query URL is dropped.
- "Archive of https://example.com (2020-01-01 12:00:00)",
- "https://web.archive.org/web/20200101120000/https://example.com",
+ f"Archive of {WAYBACK_URL} (2020-01-01 12:00:00)",
+ f"https://web.archive.org/web/20200101120000/{WAYBACK_URL}",
"Archived version",
),
Case(
@@ -2352,7 +2355,7 @@ class TestDownstreamSilentDrops:
def test_wayback_returns_nothing_for_a_plain_research_question(
self, inert_tracker
):
- """Wayback looks up hosts of supplied URLs; topics need discovery.
+ """Wayback only looks up supplied URLs; topics need discovery first.
The same adapter and archive payload produce usable results for
explicit URLs, while plain topics make no archive request.
diff --git a/tests/web_search_engines/test_wayback_picker_transition.py b/tests/web_search_engines/test_wayback_picker_transition.py
new file mode 100644
index 0000000000..36c92b2aa3
--- /dev/null
+++ b/tests/web_search_engines/test_wayback_picker_transition.py
@@ -0,0 +1,123 @@
+"""Keep Wayback archive configuration while excluding it from topic search."""
+
+from copy import deepcopy
+
+import pytest
+
+from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.web_search_engines import search_engines_config
+from local_deep_research.web_search_engines.engine_registry import (
+ ENGINE_REGISTRY,
+ EngineEntry,
+)
+from local_deep_research.web_search_engines.retriever_registry import (
+ retriever_registry,
+)
+
+
+def snapshot(monkeypatch):
+ monkeypatch.setattr(retriever_registry, "list_registered", lambda **kw: [])
+ # Availability is independent of the query-search capability. Avoid
+ # service probes so these configuration tests never require a network.
+ monkeypatch.setattr(
+ search_engines_config, "_engine_class_is_available", lambda *args: True
+ )
+ return {
+ "search.tool": "wayback",
+ "search.engine.library.enabled": False,
+ "search.engine.web.wayback.display_name": "Wayback",
+ "search.engine.web.wayback.agent_enabled": True,
+ "search.engine.web.wayback.use_in_auto_search": True,
+ "search.engine.web.wayback.default_params.max_snapshots_per_url": 7,
+ "search.engine.web.wikipedia.display_name": "Wikipedia",
+ "search.engine.web.wikipedia.agent_enabled": True,
+ "search.engine.web.wikipedia.use_in_auto_search": True,
+ }
+
+
+def test_registry_keeps_legacy_wayback_implementation():
+ wayback = ENGINE_REGISTRY["wayback"]
+ assert wayback.module_path == ".engines.search_engine_wayback"
+ assert wayback.class_name == "WaybackSearchEngine"
+ assert wayback.supports_query_search is False
+ assert EngineEntry(".custom", "CustomEngine").supports_query_search is True
+ assert all(
+ entry.supports_query_search
+ for name, entry in ENGINE_REGISTRY.items()
+ if name != "wayback"
+ )
+
+
+def test_config_marks_only_wayback_and_preserves_saved_settings(snapshot):
+ before = deepcopy(snapshot)
+ configs = search_engines_config.search_config(settings_snapshot=snapshot)
+
+ assert configs["wayback"]["supports_query_search"] is False
+ assert "supports_query_search" not in configs["wikipedia"]
+ assert configs["wayback"]["default_params"]["max_snapshots_per_url"] == 7
+ assert configs["wayback"]["agent_enabled"] is True
+ assert snapshot == before
+ assert snapshot["search.tool"] == "wayback"
+
+
+def test_saved_capability_cannot_promote_wayback_to_topic_search(snapshot):
+ snapshot["search.engine.web.wayback.supports_query_search"] = True
+ configs = search_engines_config.search_config(settings_snapshot=snapshot)
+ assert configs["wayback"]["supports_query_search"] is False
+
+
+def test_eligible_archive_config_survives_but_auto_search_excludes_it(snapshot):
+ eligible = search_engines_config.list_eligible_engine_configs(
+ settings_snapshot=snapshot, check_agent_enabled=True
+ )
+ assert set(eligible) == {"wayback", "wikipedia"}
+ assert eligible["wayback"]["supports_query_search"] is False
+
+ available = search_engines_config.get_available_engines(
+ settings_snapshot=snapshot
+ )
+ assert set(available) == {"wikipedia"}
+ assert (
+ search_engines_config.get_available_engines(
+ settings_snapshot=snapshot, exclude_engines={"wikipedia"}
+ )
+ == {}
+ )
+
+
+def test_archive_agent_toggle_still_controls_eligible_config(snapshot):
+ snapshot["search.engine.web.wayback.agent_enabled"] = False
+ configs = search_engines_config.search_config(settings_snapshot=snapshot)
+ assert "wayback" in configs
+ eligible = search_engines_config.list_eligible_engine_configs(
+ settings_snapshot=snapshot, check_agent_enabled=True
+ )
+ assert set(eligible) == {"wikipedia"}
+
+
+def test_catalog_preserves_unrelated_options_and_legacy_values():
+ defaults = SettingsManager(db_session=None).default_settings
+ options = {option["value"] for option in defaults["search.tool"]["options"]}
+ assert "wayback" not in options
+ assert {"searxng", "wikipedia", "brave"} <= options
+ assert defaults["search.tool"]["value"] == "searxng"
+ assert (
+ "choose a configured search provider"
+ in defaults["search.tool"]["description"]
+ )
+ assert defaults["search.engine.web.wayback.agent_enabled"]["value"] is True
+ assert (
+ defaults["search.engine.web.wayback.use_in_auto_search"]["value"]
+ is False
+ )
+ assert (
+ defaults[
+ "search.engine.web.wayback.default_params.max_snapshots_per_url"
+ ]["value"]
+ == 3
+ )
+ assert (
+ "fetch_archive"
+ in defaults["search.engine.web.wayback.agent_enabled"]["description"]
+ )