STATIYA_POLUCHATEL_1
SP-04 · SOURCE PREFLIGHT
P1 / DISCOVER FIRST · CRAWL SECOND

Preflight ресурса и построение плана обхода

Один URL не должен мгновенно запускать слепой обход. Сначала сервис строит карту источника: robots, sitemaps, feeds, архивы, категории, pagination, типовые страницы, предполагаемый порядок и конечные условия. Пользователь видит этот план в интерфейсе и по логам понимает, что механизм собирается делать.

1 URLinput
10discovery layers
3preflight verdicts
0blind mass crawls

01 / Главный контракт

PRECHECK → SOURCE MAP → TRAVERSAL PLAN → FIRST-BATCH CRAWL.

Mass crawl запрещён, пока сервис не понимает хотя бы на достаточном уровне, где у ресурса статьи, какими путями они перечисляются, какие hosts допустимы и что будет считаться концом обхода.

Preflight не заменяет финальную article classification.

Здесь механизм только строит структуру и вероятные patterns. Точное INCLUDE/EXCLUDE каждой страницы относится к SP-06. Сомнительные страницы не должны насильно попадать в базу.

02 / State machine preflight

CREATED

URL accepted; no network traversal beyond safety/normalization.

SCOPE_VALIDATING

Normalize URL, resolve host rules, confirm allowed crawl scope.

ROBOTS_DISCOVERY

Fetch and parse robots.txt where available.

SITEMAP_DISCOVERY

Discover sitemap declarations and conventional sitemap locations.

FEED_DISCOVERY

Discover RSS/Atom/JSON feeds from HTML and conventional paths.

ARCHIVE_DISCOVERY

Inspect archive/category/tag/pagination surfaces as navigation candidates.

SAMPLE_ANALYSIS

Sample candidate pages and listing pages to infer URL/page patterns.

ORDERING_ANALYSIS

Choose a deterministic article ordering strategy with evidence/confidence.

PLAN_BUILDING

Compile traversal graph, include/exclude rules and stop conditions.

PREFLIGHT_READY

Plan is coherent enough to show the user and unlock first-batch crawl.

PREFLIGHT_PARTIAL

Some structures unavailable, but a bounded defensible plan exists.

PREFLIGHT_FAILED

No credible bounded route to article corpus; mass crawl must not start.

03 / Слои исследования источника

L1
SOURCE IDENTITY

Normalize scheme/host, strip fragments, detect canonical host, decide allowed same-site host variants.

L2
ROBOTS

Read robots.txt for access policy, crawl-delay/request-rate hints and sitemap declarations.

L3
SITEMAPS

Parse sitemap index and nested sitemaps with bounded recursion; record URL count and types.

L4
FEEDS

Find RSS/Atom/JSON feed links; use as ordering/candidate evidence, not necessarily full historical corpus.

L5
LISTINGS

Discover archive, category, tag, issue, pagination and date-based listing pages.

L6
PAGE SAMPLES

Sample likely article/listing/service pages to infer structural differences without crawling entire source.

L7
PATTERNS

Infer candidate article URL patterns and obvious exclude patterns from evidence.

L8
ORDER

Evaluate chronological archive, datePublished metadata, feed order, sitemap order and deterministic fallback.

L9
GRAPH

Build traversal nodes/edges, priorities, bounds, limits, retry rules and termination criteria.

L10
REPORT

Render human plan + machine manifest; do not start bulk crawl unless plan status permits.

04 / Как выбирать порядок статей

PriorityStrategyRule
1Official chronological archive/category sequencePrefer when listings explicitly represent publication chronology and samples confirm it.
2Article-level publication metadataUse datePublished or equivalent only if present consistently and plausibly across samples.
3Official feed orderUseful when feed is complete enough for target scope; often only recent history, so coverage must be stated.
4Sitemap orderAllowed only if evidence shows it reflects publication order; XML element order alone is not proof.
5Deterministic discovery orderFallback using a stable traversal order derived from the selected source graph.
Важно про sitemap lastmod.

lastmod часто означает последнее изменение URL, а не дату публикации. Механизм может использовать его только после source-specific proof. Иначе ordering должен опираться на другой источник.

05 / Machine-readable crawl_plan

FieldPurpose
plan_idStable per-job preflight plan ID.
job_idJob that owns the plan.
source_idStable dataset/source identity.
input_urlExact user input.
normalized_source_urlCanonical source root chosen by preflight.
allowed_hosts[]Hosts permitted for crawl.
blocked_hosts[]Explicitly disallowed external/private hosts.
robotsFetched URL, status, parsed policy, sitemaps.
sitemaps[]URL, type, parent, child count, status.
feeds[]URL, type, item count/sample, coverage note.
navigation_surfaces[]Archive/category/tag/pagination candidates and confidence.
candidate_patterns[]Observed patterns likely to contain article pages.
exclude_patterns[]Observed service/listing/video-only/utility patterns.
ordering_strategySelected strategy.
ordering_confidenceHIGH / MEDIUM / LOW.
ordering_evidence[]Concrete observations supporting the strategy.
estimated_candidate_countEstimate only; may be unknown.
coverage_notes[]Known blind spots and limitations.
traversal_nodes[]Ordered crawl graph nodes.
limitsDepth, pages, recursion, concurrency/rate placeholders.
termination_conditions[]When this plan considers source exhausted.
statusREADY / PARTIAL / FAILED.
generated_atTimestamp.
evidence_refs[]Paths/URLs/log events supporting decisions.
Human UI показывает из этого же объекта: SOURCE → что нашли → какие sitemap/feed/archive поверхности используются → что исключаем → в каком порядке идём → приблизительный масштаб → какие есть ограничения → когда остановимся → READY / PARTIAL / FAILED UI и crawler обязаны ссылаться на один и тот же plan_id.

06 / Ограничители против плохого обхода

01
Same-site by default

Do not follow arbitrary external links discovered inside articles. External assets and referenced websites are not part of the source corpus.

02
Canonical host normalization

www/non-www or equivalent redirects may be unified when verified; do not invent cross-domain equivalence.

03
Private-network protection

User-supplied URL and redirects must later pass SSRF/private-network rules from SP-13 before fetch.

04
Bound sitemap recursion

Prevent sitemap-index loops and pathological nesting; track visited sitemap URLs.

05
Bound pagination

Detect repeated/looping pages; maintain visited normalized listing URLs and stable termination signals.

06
Do not fill quotas

If only 17 valid articles exist, stop at 17. Do not include uncertain pages to reach 30.

07
No publication-date invention

lastmod can mean page update. Treat as publication date only after source-specific proof.

08
No anti-bot bypass

CAPTCHA/login/challenge is a blocker/partial condition, not permission to stealth-bypass.

09
Evidence before pattern

A URL regex/prefix becomes a rule only after observed samples support it.

10
Plan first, crawl second

Bulk candidate enumeration starts only after PREFLIGHT_READY/PARTIAL with explicit scope and stop conditions.

07 / Минимальный объём evidence до READY

SurfaceSampleЧто доказывает
Homepage1–3 pagesNavigation, feed links, archive/category entry points, canonical host.
robots.txt1Access policy + sitemap declarations.
Sitemap indexall discovered index files within bounded recursionCorpus topology, child sitemaps.
Sitemap samplessmall sample per sitemap typeURL shape, possible content type separation.
Archive/category pages2–5 per patternPagination, ordering, article-link structure.
Candidate article pages5–15 representative samplesCanonical, title, text/image presence, date metadata, article structure.
Non-article pages5–10 representative samplesService/category/video-only patterns for exclusion evidence.
Не надо заранее скачивать весь сайт.

Preflight должен быть дешёвым относительно полного crawl: topology + representative sampling + decision evidence. Полная enumeration кандидатов начинается в SP-05.

08 / Failure modes

IDSituationRequired behavior
F-01robots disallows relevant pathsMark blocked scope; do not bypass; plan may become PARTIAL/FAILED.
F-02no sitemap existsUse feeds + archive/category/pagination + bounded link discovery; disclose lower confidence.
F-03sitemap contains mixed contentPartition by sampled patterns; do not treat every URL as article.
F-04sitemap hugeUse sitemap topology and bounded sampling to infer routes before mass enumeration; crawler later streams/paginates.
F-05JS-only archiveMark browser-required navigation surface; Playwright fallback considered only for that surface.
F-06dates contradictoryDo not silently merge; select another deterministic ordering or mark LOW confidence.
F-07infinite calendar/tag spaceRestrict to evidence-backed archive branches and visited normalized URLs.
F-08redirect leaves source domainStop unless destination is a verified canonical host of the same source.
F-09source has <30 articlesPreflight/crawl remains valid; first owner gate uses the smaller complete set.
F-10no credible bounded traversalPREFLIGHT_FAILED; require rule tuning or owner intervention.

09 / Definition of Done

IDCriterion
A-04-01One URL is sufficient to start preflight.
A-04-02Mass crawling never begins before scope, traversal surfaces and stop conditions are established.
A-04-03The UI can render a plain-language crawl plan from the machine plan.
A-04-04Every sitemap/feed/archive surface in the plan has evidence and status.
A-04-05Allowed hosts and cross-domain redirect behavior are explicit.
A-04-06Ordering strategy is deterministic and has confidence/evidence.
A-04-07Sitemap lastmod is not silently treated as publication date.
A-04-08Potential article and obvious non-article patterns are both represented.
A-04-09Traversal has explicit loop prevention and termination conditions.
A-04-10If the source cannot be mapped defensibly, status is FAILED rather than blind crawl.
A-04-11Plan output is persisted with the job so logs and later crawler behavior can reference the same plan_id.
A-04-12Preflight result is compact enough for Luna Medium task context: full raw corpus is evidence, not embedded prompt text.

10 / Bounded implementation под Luna Medium

BlockScopeOutcome
LUNA-04-AURL + scope normalizationImplement only source identity/allowed-host decision and tests.
LUNA-04-Brobots + sitemap discoveryImplement bounded robots/sitemap topology, visited-set and evidence.
LUNA-04-Cfeed + archive discoveryImplement feed declarations and listing-surface discovery.
LUNA-04-Dsample classifier signalsExtract structural samples only; do not implement final SP-06 classifier.
LUNA-04-Eordering analyzerImplement strategy scoring/evidence contract.
LUNA-04-Fplan compilerCompile machine crawl_plan + human-readable plan payload.
LUNA-04-Gpreflight integration testsRun against representative static fixtures and later real benchmark sources.
Каждый блок отдельно.

Нельзя выдавать Luna одну задачу «сделай весь preflight». Сначала URL/scope, затем robots/sitemaps, затем feeds/listings, затем ordering, затем plan compiler, затем интеграционные fixtures.

11 / Handoff

NEXT EXACT ACTION SP-03 runtime facts → choose implementation path for preflight modules → implement SP-04 bounded blocks → persist crawl_plan → expose human-readable plan in operator UI contract → only then create/execute SP-05 URL DISCOVERY CRAWLER Next planning artifact: Statiya_poluchatel_1_05_URL_DISCOVERY_CRAWLER.html