AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
{"parentUuid":null,"isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":"You are doing a security review of the XERJ search engine (Rust) at /root/ab-run-x1/repo. Focus: INGEST OF UNTRUSTED DOCUMENTS. Read thoroughly:\n- engine/crates/xerj-wasm/src/pipeline.rs (~1370 lines)\n- engine/crates/xerj-wasm/src/builtins.rs (~1300 lines)\n- engine/crates/xerj-wasm/src/lib.rs\n- The autoindex hostile-file parsing: engine/crates/xerj-autoindex/src/sniff.rs, and any archive/zip/tar/gz handling in xerj-autoindex (search for zip, tar, gz, decompress, symlink, path traversal, ..)\n\nHunt for REAL exploitable bugs a malicious document/corpus provider could trigger when their documents are indexed:\n- Path traversal on extraction (archive entries with ../ or absolute paths writing outside the data dir)\n- Zip-slip / symlink following\n- Unbounded decompression (zip bombs) — only if dramatic\n- In the pipeline/builtins: any command execution, file access, network access reachable from document content; regex catastrophic backtracking from doc-supplied patterns; script/eval of doc-supplied code\n- Integer overflow in length prefixes leading to allocation or slice OOB\n- Panics reachable from malformed docs (a panic in Rust = crash of handler thread; only matters if it kills the process)\n\nFor each candidate: file:line, exact code quote, attack path from document bytes to the bug. Verify the call chain: who calls these functions with untrusted input (search callers in xerj-engine bulk/index paths). Report a ranked list of concrete candidates. No style nits."},"uuid":"6d0ae7a0-9d38-4057-a4c9-940c988d5633","timestamp":"2026-10-01T15:38:00.897Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6d0ae7a0-9d38-4057-a4c9-940c988d5633","isSidechain":true,"agentId":"afcecc181ae7e2aa9","attachment":{"type":"skill_listing","content":"- deep-research: Deep research harness — fan-out web searches, fetch sources, adversarially verify claims, synthesize a cited report. - When the user wants a deep, multi-source, fact-checked research report on any topic. BEFORE invoking, check if the question is specific enough to research directly — if underspecified (e.g., \"what car to buy\" without budget/use-case/region), ask 2-3 clarifying questions to narrow scope. Then pass the refined question as args, weaving the answers in.\n- typesafe:typesafe-ai: Build AI-powered software with TypeSafe: small units of AI intelligence you can use like programming primitives. Its System One models, including Jev, turn natural language and application state into typed judgments and probabilities that code can combine. Use when a feature needs programmable common sense, when brainstorming what AI could make possible in an app, or when an LLM prompt-and-parse step could become a structured decision. Applications include routing, ranking, extraction, verification, and interactive experiences; these are starting points, not the limits. Read live docs and cookbooks to find useful patterns and discover new combinations.\n- update-config: Use this skill to configure the Claude Code harness via settings.json. Automated behaviors (\"from now on when X\", \"each time X\", \"whenever X\", \"before/after X\") require hooks configured in settings.json - the harness executes these, not Claude, so memory/preferences cannot fulfill them. Also use for: permissions (\"allow X\", \"add permission\", \"move permission to\"), env vars (\"set X=Y\"), hook troubleshooting, or any changes to settings.json/settings.local.json files. Examples: \"allow npm commands\", \"add bq permission to global settings\", \"move permission to user settings\", \"set DEBUG=true\", \"when claude stops show X\". For simple settings like theme/model, suggest the /config command.\n- keybindings-help: Use when the user wants to customize keyboard shortcuts, rebind keys, add chord bindings, or modify ~/.claude/keybindings.json. Examples: \"rebind ctrl+s\", \"add a chord shortcut\", \"change the submit key\", \"customize keybindings\".\n- verify: Verify that a code change actually does what it's supposed to by running the app and observing behavior. Use when asked to verify a PR, confirm a fix works, test a change manually, check that a feature works, or validate local changes before pushing.\n- code-review: Review the current diff for correctness bugs and reuse/simplification/efficiency cleanups at the given effort level (low/medium: fewer, high-confidence findings; high→max: broader coverage, may include uncertain findings). Pass --comment to post findings as inline PR comments, or --fix to apply the findings to the working tree after the review.\n- simplify: Review the changed code for reuse, simplification, efficiency, and altitude cleanups, then apply the fixes. Quality only — it does not hunt for bugs; use /code-review for that.\n- fewer-permission-prompts: Scan your transcripts for common read-only Bash and MCP tool calls, then add a prioritized allowlist to project .claude/settings.json to reduce permission prompts.\n- loop: Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo, defaults to 10m) - When the user wants to set up a recurring task, poll for status, or run something repeatedly on an interval (e.g. \"check the deploy every 5 minutes\", \"keep running /babysit-prs\"). Do NOT invoke for one-off tasks.\n- claude-api: Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration.\nTRIGGER — read BEFORE opening the target file; don't skip because it \"looks like a one-liner\" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens).\nSKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).\n- run: Launch and drive this project's app to see a change working. Use when asked to run, start, or screenshot the app, or to confirm a change works in the real app (not just tests). First looks for a project skill that already covers launching the app; otherwise falls back to built-in patterns per project type (CLI, server, TUI, Electron, browser-driven, library).\n- init: Initialize a new CLAUDE.md file with codebase documentation\n- review: Review a GitHub pull request; for your working diff use /code-review\n- security-review: Complete a security review of the pending changes on the current branch","skillCount":14,"isInitial":true,"names":["deep-research","typesafe:typesafe-ai","update-config","keybindings-help","verify","code-review","simplify","fewer-permission-prompts","loop","claude-api","run","init","review","security-review"]},"type":"attachment","uuid":"3dc4a555-7ff7-487e-9bb3-1c2bd6d73b7a","timestamp":"2026-10-01T15:38:00.899Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"3dc4a555-7ff7-487e-9bb3-1c2bd6d73b7a","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025319fde22bfedf7e48e3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"text","text":"I'll start by exploring the repository structure and then dive into the specified files."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"239fe857-400a-458d-9946-d5a593574fb1","timestamp":"2026-10-01T15:38:04.886Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"239fe857-400a-458d-9946-d5a593574fb1","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025319fde22bfedf7e48e3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_9e18d427713d4f6ba11a81f2","name":"Bash","input":{"command":"ls -la /root/ab-run-x1/repo && echo \"---\" && find /root/ab-run-x1/repo/engine/crates -maxdepth 2 -type d | head -50","description":"List repo structure and engine crates"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"92124789-10c5-4ae0-8cd2-f4c6bce4300e","timestamp":"2026-10-01T15:38:04.890Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"92124789-10c5-4ae0-8cd2-f4c6bce4300e","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_9e18d427713d4f6ba11a81f2","type":"tool_result","content":"total 808\ndrwxr-xr-x 18 root root 4096 Oct 1 15:37 .\ndrwxr-xr-x 5 root root 4096 Oct 1 15:37 ..\n-rw-r--r-- 1 root root 896 Oct 1 15:37 .clabot\n-rw-r--r-- 1 root root 152 Oct 1 15:37 .contributors\ndrwxr-xr-x 8 root root 4096 Oct 1 15:37 .git\ndrwxr-xr-x 5 root root 4096 Oct 1 15:37 .github\n-rw-r--r-- 1 root root 7366 Oct 1 15:37 .gitignore\n-rw-r--r-- 1 root root 20370 Oct 1 15:37 AGENTS.md\n-rw-r--r-- 1 root root 590673 Oct 1 15:37 CHANGELOG.md\n-rw-r--r-- 1 root root 6032 Oct 1 15:37 CLA.md\n-rw-r--r-- 1 root root 5481 Oct 1 15:37 CODE_OF_CONDUCT.md\n-rw-r--r-- 1 root root 9500 Oct 1 15:37 CONTRIBUTING.md\n-rw-r--r-- 1 root root 11357 Oct 1 15:37 LICENSE\n-rw-r--r-- 1 root root 119 Oct 1 15:37 NOTICE\n-rw-r--r-- 1 root root 26459 Oct 1 15:37 README.md\n-rw-r--r-- 1 root root 35974 Oct 1 15:37 ROADMAP.md\n-rw-r--r-- 1 root root 4680 Oct 1 15:37 SECURITY.md\ndrwxr-xr-x 17 root root 4096 Oct 1 15:37 benchmarks\ndrwxr-xr-x 4 root root 4096 Oct 1 15:37 content\ndrwxr-xr-x 9 root root 4096 Oct 1 15:37 demo\ndrwxr-xr-x 3 root root 4096 Oct 1 15:37 deploy\ndrwxr-xr-x 10 root root 4096 Oct 1 15:37 docs\ndrwxr-xr-x 10 root root 4096 Oct 1 15:37 engine\ndrwxr-xr-x 2 root root 4096 Oct 1 15:37 functions\ndrwxr-xr-x 20 root root 4096 Oct 1 15:37 landing\ndrwxr-xr-x 2 root root 4096 Oct 1 15:37 metrics\ndrwxr-xr-x 2 root root 4096 Oct 1 15:37 recipes\ndrwxr-xr-x 5 root root 4096 Oct 1 15:37 scripts\ndrwxr-xr-x 5 root root 4096 Oct 1 15:37 tools\ndrwxr-xr-x 20 root root 4096 Oct 1 15:37 user-feedback\n-rw-r--r-- 1 root root 1006 Oct 1 15:37 wrangler.toml\ndrwxr-xr-x 6 root root 4096 Oct 1 15:37 xerj-ux\n---\n/root/ab-run-x1/repo/engine/crates\n/root/ab-run-x1/repo/engine/crates/xerj-console-api\n/root/ab-run-x1/repo/engine/crates/xerj-ai\n/root/ab-run-x1/repo/engine/crates/xerj-fts\n/root/ab-run-x1/repo/engine/crates/xerj-cluster\n/root/ab-run-x1/repo/engine/crates/xerj-query\n/root/ab-run-x1/repo/engine/crates/xerj-mcp\n/root/ab-run-x1/repo/engine/crates/xerj-api\n/root/ab-run-x1/repo/engine/crates/xerj-server\n/root/ab-run-x1/repo/engine/crates/xerj-engine\n/root/ab-run-x1/repo/engine/crates/xerj-common\n/root/ab-run-x1/repo/engine/crates/xerj-storage\n/root/ab-run-x1/repo/engine/crates/xerj-vector\n/root/ab-run-x1/repo/engine/crates/xerj-compress\n/root/ab-run-x1/repo/engine/crates/xerj-rerank\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex\n/root/ab-run-x1/repo/engine/crates/xerj-wasm\n/root/ab-run-x1/repo/engine/crates/xerj-logs\n/root/ab-run-x1/repo/engine/crates/xerj-console-api/src\n/root/ab-run-x1/repo/engine/crates/xerj-console-api/tests\n/root/ab-run-x1/repo/engine/crates/xerj-ai/examples\n/root/ab-run-x1/repo/engine/crates/xerj-ai/src\n/root/ab-run-x1/repo/engine/crates/xerj-fts/src\n/root/ab-run-x1/repo/engine/crates/xerj-fts/tests\n/root/ab-run-x1/repo/engine/crates/xerj-cluster/src\n/root/ab-run-x1/repo/engine/crates/xerj-cluster/tests\n/root/ab-run-x1/repo/engine/crates/xerj-query/src\n/root/ab-run-x1/repo/engine/crates/xerj-query/tests\n/root/ab-run-x1/repo/engine/crates/xerj-mcp/src\n/root/ab-run-x1/repo/engine/crates/xerj-mcp/tests\n/root/ab-run-x1/repo/engine/crates/xerj-api/examples\n/root/ab-run-x1/repo/engine/crates/xerj-api/src\n/root/ab-run-x1/repo/engine/crates/xerj-api/tests\n/root/ab-run-x1/repo/engine/crates/xerj-server/src\n/root/ab-run-x1/repo/engine/crates/xerj-server/tests\n/root/ab-run-x1/repo/engine/crates/xerj-logs/src\n/root/ab-run-x1/repo/engine/crates/xerj-engine/examples\n/root/ab-run-x1/repo/engine/crates/xerj-engine/src\n/root/ab-run-x1/repo/engine/crates/xerj-engine/tests\n/root/ab-run-x1/repo/engine/crates/xerj-engine/benches\n/root/ab-run-x1/repo/engine/crates/xerj-common/src\n/root/ab-run-x1/repo/engine/crates/xerj-storage/examples\n/root/ab-run-x1/repo/engine/crates/xerj-storage/src\n/root/ab-run-x1/repo/engine/crates/xerj-storage/tests\n/root/ab-run-x1/repo/engine/crates/xerj-vector/examples\n/root/ab-run-x1/repo/engine/crates/xerj-vector/src\n/root/ab-run-x1/repo/engine/crates/xerj-vector/tests\n/root/ab-run-x1/repo/engine/crates/xerj-compress/src\n/root/ab-run-x1/repo/engine/crates/xerj-rerank/src\n/root/ab-run-x1/repo/engine/crates/xerj-rerank/tests","is_error":false}]},"uuid":"b5e08706-6b23-4892-bbc7-08a5515fe5b1","timestamp":"2026-10-01T15:38:05.026Z","sourceToolAssistantUUID":"92124789-10c5-4ae0-8cd2-f4c6bce4300e","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"b5e08706-6b23-4892-bbc7-08a5515fe5b1","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025319fde22bfedf7e48e3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_f0a7bb5d182a4f1a921be9b5","name":"Bash","input":{"command":"find /root/ab-run-x1/repo -name \"*.rs\" -path \"*autoindex*\" | head -50; echo \"---WASM---\"; ls -la /root/ab-run-x1/repo/engine/crates/xerj-wasm/src/ 2>/dev/null","description":"Find autoindex and wasm source files"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":10497,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":160,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"7a4d27d8-70af-4379-861d-44d908f6dd8a","timestamp":"2026-10-01T15:38:05.620Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7a4d27d8-70af-4379-861d-44d908f6dd8a","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_f0a7bb5d182a4f1a921be9b5","type":"tool_result","content":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/lib.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/gate.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/generation_catalog.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/init.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/def.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/sync.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/search.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/objsource_s3_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/watch.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/refused_dataset_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/objsource_minio_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/label_http_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/walk.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/reconcile_plan.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/sync_executor.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/state.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/content.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/estimate.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/catalog.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/feedback.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/gain.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/dataset.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/coerce.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/xc.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/generation_catalog_http_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/order.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/ignore_rules.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/correlate.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/esclient.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/resources.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/source.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/failure_resume_http_tests.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/objsource.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/label.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/progress.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/pool.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/ids.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/sniff.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/cli.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/sniff_printable_magic.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/objwatch_minio.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/scan_pool_width.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/follow_symlinks_boundary.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/journal_lock_inheritance.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/pack_claims.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/tests/objwatch_r2.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/detect/e2e.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/detect/sequence.rs\n/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/detect/e2e_mail.rs\n---WASM---\ntotal 124\ndrwxr-xr-x 2 root root 4096 Oct 1 15:37 .\ndrwxr-xr-x 5 root root 4096 Oct 1 15:37 ..\n-rw-r--r-- 1 root root 49518 Oct 1 15:37 builtins.rs\n-rw-r--r-- 1 root root 4321 Oct 1 15:37 lib.rs\n-rw-r--r-- 1 root root 57012 Oct 1 15:37 pipeline.rs","is_error":false}]},"uuid":"20258b5a-94df-40dc-9203-262d576c5e9b","timestamp":"2026-10-01T15:38:05.652Z","sourceToolAssistantUUID":"7a4d27d8-70af-4379-861d-44d908f6dd8a","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"20258b5a-94df-40dc-9203-262d576c5e9b","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025323da6cf2ac8d3c47a6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Let me read the main files. Start with lib.rs (small), then pipeline.rs and builtins.rs, and sniff.rs.\n\nLet me also search for archive handling in autoindex.","signature":"83d42381e2d94d9bbd56d218"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"4db25a9b-0726-468a-97a5-349221cdb285","timestamp":"2026-10-01T15:38:12.688Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4db25a9b-0726-468a-97a5-349221cdb285","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025323da6cf2ac8d3c47a6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_0c853d49e0944e34977ea74b","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/lib.rs"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"a26e3636-fe9c-427a-9093-20237db3b7bd","timestamp":"2026-10-01T15:38:12.689Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a26e3636-fe9c-427a-9093-20237db3b7bd","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025323da6cf2ac8d3c47a6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_1e849c82e7c04d978efc673e","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/sniff.rs"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"d9049ad6-ca1a-4171-85eb-0212f7fa8d50","timestamp":"2026-10-01T15:38:12.693Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a26e3636-fe9c-427a-9093-20237db3b7bd","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_0c853d49e0944e34977ea74b","type":"tool_result","content":"1\t//! # xerj-wasm\n2\t//!\n3\t//! Pluggable transform pipeline for xerj.\n4\t//!\n5\t//! Provides a trait-based plugin system for document transformation at ingest\n6\t//! time. Built-in plugins (field rename, drop, add, JSON parse, timestamp\n7\t//! parse, PII redaction, grok, route) are always available as native Rust\n8\t//! code.\n9\t//!\n10\t//! A real WASM backend (via `wasmtime`) can be wired in later behind the\n11\t//! `wasm` feature flag without changing any public API.\n12\t\n13\tpub mod builtins;\n14\tpub mod pipeline;\n15\t\n16\t// ── Re-exports ────────────────────────────────────────────────────────────────\n17\t\n18\tpub use pipeline::{ErrorPolicy, Pipeline, PipelineConfig, PipelineStageConfig, ProcessAction};\n19\t\n20\t// ── Core trait ────────────────────────────────────────────────────────────────\n21\t\n22\t/// A transform plugin — implemented by built-in Rust transforms (and, in the\n23\t/// future, WASM modules).\n24\t///\n25\t/// Plugins are `Send + Sync` so they can be shared across async tasks and\n26\t/// stored in `Arc<dyn TransformPlugin>`.\n27\tpub trait TransformPlugin: Send + Sync {\n28\t /// Unique name used to reference this plugin in pipeline configs.\n29\t fn name(&self) -> &str;\n30\t\n31\t /// Transform `doc` in-place and return the action to take.\n32\t ///\n33\t /// - [`ProcessAction::Pass`] — continue to the next stage.\n34\t /// - [`ProcessAction::Drop`] — discard this document entirely.\n35\t /// - [`ProcessAction::Route`] — send the document to a different target\n36\t /// index.\n37\t fn process(&self, doc: &mut serde_json::Value) -> ProcessAction;\n38\t}\n39\t\n40\t// ── Error type ────────────────────────────────────────────────────────────────\n41\t\n42\tuse thiserror::Error;\n43\t\n44\t#[derive(Debug, Error)]\n45\tpub enum WasmError {\n46\t #[error(\"pipeline '{0}' not found\")]\n47\t PipelineNotFound(String),\n48\t\n49\t #[error(\"plugin '{0}' not found\")]\n50\t PluginNotFound(String),\n51\t\n52\t #[error(\"invalid plugin config for '{plugin}': {reason}\")]\n53\t InvalidConfig { plugin: String, reason: String },\n54\t\n55\t /// The stage type is legitimate but this build does not implement it.\n56\t ///\n57\t /// Issue #204 keeps this separate from [`WasmError::InvalidConfig`]: a\n58\t /// caller who wrote a valid Elasticsearch processor xerj has not\n59\t /// implemented has not made a mistake, and must not be told they have.\n60\t /// What must never happen is the third option the code used to take —\n61\t /// accepting it and quietly running a shorter pipeline.\n62\t #[error(\"unsupported stage type '{stage}'\")]\n63\t UnsupportedStage { stage: String },\n64\t\n65\t /// The stage type IS implemented, but the caller set an option this build\n66\t /// cannot honour — an Elasticsearch processor-level `if` guard, an\n67\t /// `on_failure` recovery chain, a `grok` `patterns` array.\n68\t ///\n69\t /// Issue #204 again, one level down. Reporting these as `InvalidConfig`\n70\t /// would tell a caller their valid ES processor is malformed; ignoring them\n71\t /// is what the sweep exists to kill — a `set` that runs on documents its\n72\t /// `if` excludes is a silently wrong document, not a cosmetic gap. Handled\n73\t /// exactly like [`WasmError::UnsupportedStage`] at the API boundary: the\n74\t /// definition is accepted (ES accepts it) and recorded as unrunnable, so\n75\t /// every ingest through it refuses loudly.\n76\t #[error(\"stage '{stage}': option '{option}' is not supported by this build ({reason})\")]\n77\t UnsupportedOption {\n78\t stage: String,\n79\t option: String,\n80\t reason: String,\n81\t },\n82\t\n83\t /// The pipeline is registered but carries a stage this build cannot run,\n84\t /// so no document may pass through it.\n85\t #[error(\"pipeline '{pipeline}' is registered but cannot run: {reason}\")]\n86\t PipelineNotRunnable { pipeline: String, reason: String },\n87\t\n88\t #[error(\"plugin error in '{plugin}': {reason}\")]\n89\t PluginError { plugin: String, reason: String },\n90\t\n91\t #[error(transparent)]\n92\t Json(#[from] serde_json::Error),\n93\t\n94\t #[error(transparent)]\n95\t Other(#[from] anyhow::Error),\n96\t}\n97\t\n98\tpub type Result<T> = std::result::Result<T, WasmError>;\n99\t"}]},"uuid":"429cccec-aff5-4537-a6cf-5447d6ea8f41","timestamp":"2026-10-01T15:38:12.697Z","sourceToolAssistantUUID":"a26e3636-fe9c-427a-9093-20237db3b7bd","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"429cccec-aff5-4537-a6cf-5447d6ea8f41","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025323da6cf2ac8d3c47a6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_beccf6e3ba364eb08f37ab1c","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex && grep -rniE \"zip|tar|gz|decompress|inflate|symlink|traversal|\\.\\.|unpack|archive\" src/ --include=\"*.rs\" -l | sort | uniq","description":"Find archive-related files in autoindex"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":4641,"cache_creation_input_tokens":0,"cache_read_input_tokens":8960,"output_tokens":179,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"108e7723-05ff-47c4-ac31-5465d0342c47","timestamp":"2026-10-01T15:38:13.986Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d9049ad6-ca1a-4171-85eb-0212f7fa8d50","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_1e849c82e7c04d978efc673e","type":"tool_result","content":"1\t//! Content-based format detection. NEVER trusts file extensions.\n2\t//!\n3\t//! Order: magic bytes → binary check → text heuristics\n4\t//! (json/jsonl → html/xml → logs → sql dump → csv → yaml → txt).\n5\t\n6\tuse anyhow::Result;\n7\tuse std::io::Read;\n8\tuse std::path::Path;\n9\t\n10\t#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n11\tpub enum Family {\n12\t Jsonl,\n13\t Json,\n14\t Csv,\n15\t Logs,\n16\t Xml,\n17\t Html,\n18\t Yaml,\n19\t TxtProse,\n20\t TxtLines,\n21\t Pdf,\n22\t /// RFC 5322 / MIME email message (`.eml`, `message/rfc822`): headers parsed\n23\t /// into fields, MIME decoded, and each attachment indexed as its own\n24\t /// document (PDFs routed to the PDF extractor).\n25\t Eml,\n26\t /// mbox mailbox: many RFC 5322 messages in one file, each opened by a\n27\t /// `From <sender> <date>` separator line (Google Takeout, Thunderbird,\n28\t /// Apple Mail, mutt). Split as a STREAM — multi-GB is the normal size — and\n29\t /// each message goes through the same extraction as [`Family::Eml`].\n30\t Mbox,\n31\t Docx,\n32\t Sqlite,\n33\t SqlDump,\n34\t /// Source code — AST-parsed by the matching tree-sitter grammar.\n35\t Code,\n36\t /// Unity text-serialized asset (scene/prefab/.asset/.mat/.anim/…):\n37\t /// a `%YAML` + `%TAG !u! tag:unity3d.com` multi-document stream.\n38\t UnityYaml,\n39\t /// Unity `.meta` sidecar: plain YAML opening with `fileFormatVersion:`\n40\t /// and carrying the asset `guid` — the join key for everything Unity.\n41\t UnityMeta,\n42\t /// Biovision motion capture: a skeleton HIERARCHY header followed by a\n43\t /// large numeric MOTION block. Indexed as ONE metadata record per file\n44\t /// (joints, frame count, duration) — the motion numbers are never read.\n45\t Bvh,\n46\t /// User-designated existence-only file (`--stub <glob>`): ONE name-card\n47\t /// record, contents never opened. For corpus-specific data blobs the\n48\t /// owner wants referenceable but not parsed — never assigned by\n49\t /// sniffing, only by the CLI flag.\n50\t Stub,\n51\t Binary,\n52\t}\n53\t\n54\timpl Family {\n55\t pub fn as_str(&self) -> &'static str {\n56\t match self {\n57\t Family::Jsonl => \"jsonl\",\n58\t Family::Json => \"json\",\n59\t Family::Csv => \"csv\",\n60\t Family::Logs => \"logs\",\n61\t Family::Xml => \"xml\",\n62\t Family::Html => \"html\",\n63\t Family::Yaml => \"yaml\",\n64\t Family::TxtProse => \"txt-prose\",\n65\t Family::TxtLines => \"txt-lines\",\n66\t Family::Pdf => \"pdf\",\n67\t Family::Eml => \"eml\",\n68\t Family::Mbox => \"mbox\",\n69\t Family::Docx => \"docx\",\n70\t Family::Sqlite => \"sqlite\",\n71\t Family::SqlDump => \"sqldump\",\n72\t Family::Code => \"code\",\n73\t Family::UnityYaml => \"unity\",\n74\t Family::UnityMeta => \"unity-meta\",\n75\t Family::Bvh => \"bvh\",\n76\t Family::Stub => \"stub\",\n77\t Family::Binary => \"binary\",\n78\t }\n79\t }\n80\t /// Document-family formats produce one record per document/section.\n81\t pub fn is_document(&self) -> bool {\n82\t matches!(\n83\t self,\n84\t Family::Pdf | Family::Docx | Family::TxtProse | Family::Eml | Family::Mbox\n85\t )\n86\t }\n87\t}\n88\t\n89\t#[derive(Debug, Clone, Copy)]\n90\tpub struct CsvDialect {\n91\t pub delim: u8,\n92\t pub has_header: bool,\n93\t pub decimal_comma: bool,\n94\t}\n95\t\n96\t#[derive(Debug, Clone)]\n97\tpub struct Sniffed {\n98\t pub family: Family,\n99\t pub gzip: bool,\n100\t /// e.g. \"png\", \"zip\", \"elf\", \"unknown\" — set when family == Binary.\n101\t pub binary_kind: Option<String>,\n102\t pub csv: Option<CsvDialect>,\n103\t /// \"utf-8\" or \"windows-1252 (lossy)\"\n104\t pub encoding: &'static str,\n105\t /// File name of the LOGICAL source (`app.py`), even when the sniffed\n106\t /// content lives elsewhere. Durable preparation reads content-addressed\n107\t /// snapshot blobs (`blobs/00000000`), so an extractor that recovers a\n108\t /// parameter from its content path silently loses the name — that is how\n109\t /// #294 turned every code file into junk. Name-derived decisions after\n110\t /// sniffing must use this, never the content path.\n111\t pub logical_name: Option<std::path::PathBuf>,\n112\t}\n113\t\n114\t/// Bytes read for ordinary classification.\n115\tconst PREFIX: usize = 8192;\n116\t\n117\t/// Bytes read when the file already carries GIF magic. A Comment Extension is\n118\t/// unbounded by the format, so this is a budget rather than a guarantee: it\n119\t/// covers every commented GIF in the measured corpus with room to spare.\n120\t///\n121\t/// The value is load-bearing, and in the direction that is easy to get\n122\t/// backwards. `read_prefix` returns `min(file_size, GIF_PREFIX)`, so the buffer\n123\t/// is full exactly when the file is at least this large — and a full buffer is\n124\t/// the answer \"image\" (see the `None` arm of the comment walk). LOWERING the\n125\t/// budget therefore admits MORE files, not fewer: at 128 KiB every text file\n126\t/// over 128 KiB carrying the header shape is called an image, where at 1 MiB\n127\t/// only those over 1 MiB are — **by this path**. Raising it costs a larger read\n128\t/// per GIF candidate and narrows that window.\n129\t///\n130\t/// This budget is not the whole rule, and reading it as such is the mistake to\n131\t/// avoid when deciding whether to change it. The arm is `full || canvas`: the\n132\t/// canvas disjunct admits text of ANY size, so no value of this constant closes\n133\t/// that window. `the_canvas_path_junks_prose_at_any_size_and_the_budget_does_not_bound_it`\n134\t/// pins a 3,000-byte prose file called an image at a 1 MiB budget. Pinned by\n135\t/// `the_budget_is_the_threshold_it_claims`, which measures this path only.\n136\tconst GIF_PREFIX: usize = 1 << 20;\n137\t\n138\tfn read_prefix(path: &Path, gzip: bool, n: usize) -> Result<Vec<u8>> {\n139\t let f = std::fs::File::open(path)?;\n140\t let mut buf = Vec::with_capacity(n.min(1 << 20));\n141\t if gzip {\n142\t let mut r = flate2::read::MultiGzDecoder::new(f).take(n as u64);\n143\t r.read_to_end(&mut buf).ok(); // truncated gz prefix is fine for sniffing\n144\t } else {\n145\t let mut r = f.take(n as u64);\n146\t r.read_to_end(&mut buf)?;\n147\t }\n148\t Ok(buf)\n149\t}\n150\t\n151\tpub fn sniff(path: &Path) -> Result<Sniffed> {\n152\t sniff_with_name(path, path)\n153\t}\n154\t\n155\t/// Classify bytes from `content_path` while retaining the logical filename\n156\t/// signals (currently source-code extensions) from `logical_path`.\n157\t///\n158\t/// Durable preparation uses this to classify an immutable snapshot blob\n159\t/// without losing the original name merely because the blob itself is named\n160\t/// by an ordinal.\n161\tpub fn sniff_with_name(content_path: &Path, logical_path: &Path) -> Result<Sniffed> {\n162\t let head = read_prefix(content_path, false, 8)?;\n163\t let gzip = head.len() >= 2 && head[0] == 0x1f && head[1] == 0x8b;\n164\t let mut prefix = read_prefix(content_path, gzip, PREFIX)?;\n165\t // A GIF's first data block can sit arbitrarily far in — a Comment\n166\t // Extension is a chain of 1..=255-byte sub-blocks with no length bound,\n167\t // and real files carry licence notices of tens of kilobytes. Deciding\n168\t // whether such a file is an image from 8 KiB means deciding it before its\n169\t // structure is visible, and four successive attempts to guess that from\n170\t // bytes inside the window were each refuted for junking real images\n171\t // (#379): a rule keyed on any fixed offset reads unconstrained image data\n172\t // there. So read further for a GIF candidate instead of guessing — the\n173\t // chain's terminator then falls inside the buffer and the decisive check\n174\t // applies. One extra read, only for files already carrying GIF magic.\n175\t if prefix.len() == PREFIX && prefix.len() >= 6 && matches!(&prefix[..6], b\"GIF87a\" | b\"GIF89a\")\n176\t {\n177\t prefix = read_prefix(content_path, gzip, GIF_PREFIX)?;\n178\t }\n179\t let mut s = sniff_bytes(&prefix, content_path, logical_path, gzip)?;\n180\t s.gzip = gzip;\n181\t s.logical_name = logical_path.file_name().map(std::path::PathBuf::from);\n182\t Ok(s)\n183\t}\n184\t\n185\tfn sniff_bytes(\n186\t prefix: &[u8],\n187\t content_path: &Path,\n188\t logical_path: &Path,\n189\t gzip: bool,\n190\t) -> Result<Sniffed> {\n191\t let mk = |family: Family| Sniffed {\n192\t family,\n193\t gzip: false,\n194\t binary_kind: None,\n195\t csv: None,\n196\t encoding: \"utf-8\",\n197\t logical_name: None,\n198\t };\n199\t if prefix.is_empty() {\n200\t let mut s = mk(Family::Binary);\n201\t s.binary_kind = Some(\"empty\".into());\n202\t return Ok(s);\n203\t }\n204\t\n205\t // 1. Magic bytes.\n206\t //\n207\t // %PDF- stays here rather than in MAGIC_TABLE (#403's own fix sketch\n208\t // floated moving it): every MAGIC_TABLE row reports `Family::Binary` +\n209\t // a `binary_kind` string, but %PDF- has to report the distinct\n210\t // `Family::Pdf` the extractor routes on (lib.rs:1229) — widening the\n211\t // shared `MagicRow` type for the one row that needs a different Family\n212\t // is a bigger, riskier change than this bug needs. `pdf_header` gives it\n213\t // the same structural qualifier the table's own rows carry; see its doc\n214\t // comment for what it rejects.\n215\t if prefix.starts_with(b\"%PDF-\") && pdf_header(prefix) {\n216\t return Ok(mk(Family::Pdf));\n217\t }\n218\t if prefix.starts_with(b\"SQLite format 3\\0\") {\n219\t return Ok(mk(Family::Sqlite));\n220\t }\n221\t if prefix.starts_with(b\"PK\\x03\\x04\") {\n222\t // zip container: DOCX iff it holds word/document.xml\n223\t if !gzip {\n224\t if let Ok(f) = std::fs::File::open(content_path) {\n225\t if let Ok(mut z) = zip::ZipArchive::new(f) {\n226\t let is_docx = (0..z.len()).any(|i| {\n227\t z.by_index_raw(i)\n228\t .map(|e| e.name() == \"word/document.xml\")\n229\t .unwrap_or(false)\n230\t });\n231\t if is_docx {\n232\t return Ok(mk(Family::Docx));\n233\t }\n234\t }\n235\t }\n236\t }\n237\t let mut s = mk(Family::Binary);\n238\t s.binary_kind = Some(\"zip\".into());\n239\t return Ok(s);\n240\t }\n241\t // Compressed image/audio/model payloads routinely pass the NUL and\n242\t // control-char heuristics below (windows-1252 decodes almost every byte\n243\t // to something printable), and a multi-MB PSD misread as prose turns into\n244\t // thousands of junk records — measured: a 4,194,360-byte printable blob\n245\t // yields 2,048 sections. `for_each_section` streams, so the cost is the\n246\t // record COUNT, not resident bytes. Magic bytes are the reliable signal.\n247\t // `MAGIC_TABLE` and its invariant are documented at the table itself.\n248\t for &(magic, kind, qualify) in MAGIC_TABLE {\n249\t if prefix.starts_with(magic) && qualify(prefix) {\n250\t let mut s = mk(Family::Binary);\n251\t s.binary_kind = Some(kind.into());\n252\t return Ok(s);\n253\t }\n254\t }\n255\t // Truevision TGA has NO magic number — the file opens straight into its\n256\t // 18-byte header — so a raw texture is the one image format that reaches\n257\t // the text heuristics on its own bytes. Its header is nevertheless highly\n258\t // constrained, which is what makes this safe: byte 1 must be 0 or 1 and\n259\t // byte 2 one of six small values, i.e. the second and third bytes of the\n260\t // file must BOTH be control characters, which text is not.\n261\t if looks_like_tga_header(prefix) {\n262\t let mut s = mk(Family::Binary);\n263\t s.binary_kind = Some(\"tga\".into());\n264\t return Ok(s);\n265\t }\n266\t // tar — reached for a `.tgz`/`.tar.gz` too, because `prefix` is already the\n267\t // DECOMPRESSED stream. It would be junked as \"unknown\" by the NUL ratio\n268\t // below anyway (a tar header is mostly NUL padding); this only names it, so\n269\t // the run can tell the user what to do about it.\n270\t if looks_like_tar_header(prefix) {\n271\t let mut s = mk(Family::Binary);\n272\t s.binary_kind = Some(\"tar\".into());\n273\t return Ok(s);\n274\t }\n275\t\n276\t // 2. Binary vs text: decode UTF-8, fall back windows-1252.\n277\t let (text, encoding) = decode(prefix);\n278\t let nul = prefix.iter().filter(|&&b| b == 0).count();\n279\t if nul * 10 > prefix.len() {\n280\t let mut s = mk(Family::Binary);\n281\t s.binary_kind = Some(\"unknown\".into());\n282\t return Ok(s);\n283\t }\n284\t // High ratio of control chars (excluding \\t \\n \\r) → binary.\n285\t let ctrl = text\n286\t .chars()\n287\t .filter(|c| (*c as u32) < 0x20 && !matches!(c, '\\t' | '\\n' | '\\r'))\n288\t .count();\n289\t if ctrl * 10 > text.chars().count().max(1) {\n290\t let mut s = mk(Family::Binary);\n291\t s.binary_kind = Some(\"unknown\".into());\n292\t return Ok(s);\n293\t }\n294\t // NOTE — a \"decoded via lossy windows-1252 AND over 30% non-ASCII is\n295\t // pixel soup\" guard was here, to catch a raw TGA. It is gone, and must\n296\t // not come back in that form: the windows-1252 fallback is what EVERY\n297\t // legacy 8-bit codepage and every legacy CJK encoding decodes through, so\n298\t // the test was not \"is this an image\", it was \"is this written in a script\n299\t // that is not Latin\". Measured through `sniff()` against `ca4d75a` with\n300\t // identical fixtures, it changed windows-1251 Russian, KOI8-R Russian,\n301\t // windows-1253 Greek, windows-1255 Hebrew and windows-1256 Arabic prose\n302\t // from `TxtProse` to `Binary`, and `scan_file` turns `Binary` into\n303\t // \"junk: binary content (unknown)\" — the file is never indexed and the\n304\t // report says only that something unreadable was skipped.\n305\t //\n306\t // A `looks_like_legacy_cjk` escape hatch was tried and could not carry the\n307\t // weight, for two reasons worth recording so it is not retried:\n308\t // * single-byte codepages never form valid SHIFT_JIS/GBK/BIG5/EUC_KR\n309\t // double-byte pairs, so Cyrillic/Greek/Hebrew/Arabic were never\n310\t // rescued by it at all;\n311\t // * it required a LOSSLESS trial decode, and `sniff()` only ever sees\n312\t // `read_prefix(path, gzip, 8192)`. A double-byte character straddling\n313\t // that cut makes every trial decode report `had_errors`, so the same\n314\t // Shift-JIS document was text or binary depending on its byte length\n315\t // — measured `TxtProse` at pad 0 and 2, `Binary` at pad 1 and 3.\n316\t //\n317\t // TGA is now caught by its header above, which is evidence of pixel data\n318\t // rather than evidence of a non-Latin script. Headerless raw payloads\n319\t // (`.raw`, `.bytes`, uncompressed PCM) still classify as text, exactly as\n320\t // they do on `main`. Bounding what a magic-less binary costs is the right\n321\t // fix for that (issue #381 — sectioning already streams, so the unbounded\n322\t // quantity is the record count), not byte statistics that cannot tell a\n323\t // texture from Cyrillic.\n324\t\n325\t // 2b. Unity text serialization, detected by content (never extension):\n326\t // scenes/prefabs/assets open with `%YAML` and declare the Unity tag\n327\t // namespace; `.meta` sidecars open with `fileFormatVersion:` and carry a\n328\t // `guid:`. Binary-serialized Unity assets fail both checks and fall\n329\t // through to the binary/text heuristics as before.\n330\t {\n331\t let body = text.trim_start_matches('\\u{feff}');\n332\t if body.starts_with(\"%YAML\") && body.contains(\"%TAG !u! tag:unity3d.com\") {\n333\t let mut s = mk(Family::UnityYaml);\n334\t s.encoding = encoding;\n335\t return Ok(s);\n336\t }\n337\t let first_line = body.lines().next().unwrap_or(\"\");\n338\t if first_line.starts_with(\"fileFormatVersion:\")\n339\t && body.lines().any(|l| l.starts_with(\"guid:\"))\n340\t {\n341\t let mut s = mk(Family::UnityMeta);\n342\t s.encoding = encoding;\n343\t return Ok(s);\n344\t }\n345\t // BVH motion capture: `HIERARCHY` opener with a `ROOT <name>` next.\n346\t // Without this the numeric MOTION block classified as txt-lines and\n347\t // indexed millions of meaningless number rows.\n348\t if first_line.trim() == \"HIERARCHY\"\n349\t && body\n350\t .lines()\n351\t .nth(1)\n352\t .is_some_and(|l| l.trim_start().starts_with(\"ROOT \"))\n353\t {\n354\t let mut s = mk(Family::Bvh);\n355\t s.encoding = encoding;\n356\t return Ok(s);\n357\t }\n358\t }\n359\t\n360\t // 2c. Source code: a known code extension whose content is text. We only\n361\t // reach here after the binary guards above, so a text `.py`/`.rs`/`.go`/…\n362\t // routes to the tree-sitter AST extractor (crate::extract::code). Extension\n363\t // is the right signal — code vs prose is not reliably content-sniffable.\n364\t if let Some(ext) = logical_path.extension().and_then(|e| e.to_str()) {\n365\t if crate::extract::code::is_code_ext(ext) {\n366\t let mut s = mk(Family::Code);\n367\t s.encoding = encoding;\n368\t return Ok(s);\n369\t }\n370\t }\n371\t\n372\t // 3. Text heuristics — complete lines only (last line may be truncated).\n373\t let mut lines: Vec<&str> = text.lines().collect();\n374\t if !text.ends_with('\\n') && lines.len() > 1 {\n375\t lines.pop();\n376\t }\n377\t let nonblank: Vec<&str> = lines\n378\t .iter()\n379\t .copied()\n380\t .filter(|l| !l.trim().is_empty())\n381\t .collect();\n382\t\n383\t let mut out = mk(classify_text(&text, &nonblank));\n384\t out.encoding = encoding;\n385\t if out.family == Family::Csv {\n386\t out.csv = sniff_csv_dialect(&nonblank);\n387\t if out.csv.is_none() {\n388\t out.family = txt_kind(&nonblank);\n389\t }\n390\t }\n391\t Ok(out)\n392\t}\n393\t\n394\t/// The label for the last-resort decode. Every byte maps to *something* in\n395\t/// windows-1252, so this never fails and therefore carries no evidence that\n396\t/// the bytes are text — the binary heuristics key off this exact string.\n397\tpub const WINDOWS_1252_LOSSY: &str = \"windows-1252 (lossy)\";\n398\t\n399\t/// A magic-byte row: the signature, the `binary_kind` it reports, and the\n400\t/// structural check that has to pass before the signature is believed.\n401\ttype MagicRow = (&'static [u8], &'static str, fn(&[u8]) -> bool);\n402\t\n403\t/// Media/container signatures, tried in order before any text heuristic.\n404\t///\n405\t/// THE INVARIANT, and the reason this table is a named constant rather than a\n406\t/// literal inside `sniff_bytes`: **a signature whose bytes are all printable\n407\t/// ASCII MUST carry a qualifier**, because \"starts with these letters\" is also\n408\t/// true of ordinary text. A CSV whose first column header is `ID3` or `BMW`,\n409\t/// prose whose first word is `RIFF`, `OggS`, `fLaC`, `8BPS` or `Kaydara FBX\n410\t/// Binary`, and a note opening `GIF89a is the version string…` were each junked\n411\t/// as media by an unqualified row (measured — see the tests below). The rows\n412\t/// that use `accept` are exactly the ones carrying a byte text cannot contain:\n413\t/// `\\x89PNG`, `\\xff\\xd8\\xff`, `\\x7fELF`, `\\x00\\x00\\x01\\x00`, the NUL in\n414\t/// `II*\\x00` / `MM\\x00*`, and the `\\x01` in the EXR magic.\n415\t///\n416\t/// `GIF8` and `BM` were the last two exceptions — printable ASCII taken on\n417\t/// faith, so a `cars.csv` opening `BMW,model,year` was reported as an image and\n418\t/// never indexed (#379/#380, the same defect filed twice). The invariant is now\n419\t/// enforced by walking these rows in\n420\t/// `printable_magic_tests::every_printable_signature_carries_a_qualifier`, so\n421\t/// the next row added in violation of it fails a test instead of a code review.\n422\t///\n423\t/// Qualifying a magic number is the rule Lucene applies to its own containers:\n424\t/// `CodecUtil.checkHeader`\n425\t/// (`lucene/core/src/java/org/apache/lucene/codecs/CodecUtil.java:183-201`,\n426\t/// Apache-2.0) matches `CODEC_MAGIC` and then hands straight to\n427\t/// `checkHeaderNoMagic` (`CodecUtil.java:202-246`), which refuses the file\n428\t/// unless the codec name AND a version inside an accepted range follow — the\n429\t/// magic alone is never taken as proof. Adapted, not copied: Lucene is\n430\t/// validating files it wrote itself, this is declining to delete somebody\n431\t/// else's prose.\n432\tconst MAGIC_TABLE: &[MagicRow] = &[\n433\t (b\"\\x89PNG\", \"png\", accept),\n434\t (b\"GIF8\", \"gif\", gif_screen_descriptor),\n435\t (b\"\\xff\\xd8\\xff\", \"jpeg\", accept),\n436\t (b\"\\x7fELF\", \"elf\", accept),\n437\t (b\"BM\", \"bmp\", bmp_file_header),\n438\t (b\"\\x00\\x00\\x01\\x00\", \"ico\", accept),\n439\t (b\"8BPS\", \"psd\", psd_version),\n440\t (b\"II*\\x00\", \"tiff\", accept),\n441\t (b\"MM\\x00*\", \"tiff\", accept),\n442\t (b\"RIFF\", \"riff\", riff_form),\n443\t (b\"OggS\", \"ogg\", ogg_page),\n444\t (b\"fLaC\", \"flac\", flac_metadata_block),\n445\t (b\"ID3\", \"mp3\", id3v2_header),\n446\t (b\"Kaydara FBX Binary\", \"fbx\", fbx_header),\n447\t (b\"\\x76\\x2f\\x31\\x01\", \"exr\", accept),\n448\t // Archives. None is ever opened — see `archive_advice` — but naming the\n449\t // kind is what lets the run say \"extract it first\" instead of \"binary\n450\t // content (unknown)\" about the one file a Google Takeout download consists\n451\t // of. Each signature carries a byte text cannot contain (0xBC/0xAF + 0x1C,\n452\t // 0x1A + 0x07, 0xFD + NUL), so `accept` is within the invariant above.\n453\t (b\"7z\\xbc\\xaf\\x27\\x1c\", \"7z\", accept),\n454\t (b\"Rar!\\x1a\\x07\", \"rar\", accept),\n455\t (b\"\\xfd7zXZ\\x00\", \"xz\", accept),\n456\t];\n457\t\n458\t/// Magic-byte signature taken as sufficient on its own.\n459\t///\n460\t/// Every caller is a signature containing a byte text cannot contain\n461\t/// (`\\x89PNG`, `\\xff\\xd8\\xff`, `\\x7fELF`, `\\x00\\x00\\x01\\x00`, the NUL in\n462\t/// `II*\\x00` / `MM\\x00*`, the `\\x01` in the EXR magic) — that byte, not this\n463\t/// function, is what makes the match evidence. A signature made only of\n464\t/// printable ASCII must NOT be routed here; give it a structural qualifier, as\n465\t/// `GIF8` and `BM` now have (#379/#380). Do not read this function as a proof\n466\t/// that its callers are safe; it is only a statement that no *further* check is\n467\t/// performed.\n468\tfn accept(_prefix: &[u8]) -> bool {\n469\t true\n470\t}\n471\t\n472\t/// GIF: `GIF8` on its own is four printable letters, so a note opening \"GIF89a\n473\t/// is the header format used by the GIF image standard\" was classified as an\n474\t/// image and junked by `scan_file` as \"binary content (gif)\" (#379/#380).\n475\t///\n476\t/// Widening the signature to the full six-byte version stamp is NOT enough on\n477\t/// its own — that same sentence supplies `GIF89a` — and neither is adding the\n478\t/// canvas dimensions, because \" i\"/\"s \" are perfectly good non-zero u16s. The\n479\t/// qualifier has to reach the fields the spec pins to a fixed value.\n480\t///\n481\t/// GIF89a spec §17-19: the 6-byte Header (`GIF87a` or `GIF89a`) is followed by\n482\t/// the 7-byte Logical Screen Descriptor — canvas width and height\n483\t/// (little-endian, and an image has both), a packed field whose top bit is the\n484\t/// Global Colour Table flag and whose low three bits size that table, a\n485\t/// Background Colour Index, and a Pixel Aspect Ratio. Then comes the Global\n486\t/// Colour Table itself, `3 * 2^(N+1)` bytes, and after it the first block of\n487\t/// the data stream. The table is at most 768 bytes, so that first block starts\n488\t/// at offset 781 at the very latest and is always inside the 8 KiB\n489\t/// `read_prefix` buffer.\n490\t///\n491\t/// That first block is the discriminator. The spec admits exactly three\n492\t/// introducers there — `0x21` Extension, `0x2C` Image Descriptor, `0x3B`\n493\t/// Trailer — but the introducer ALONE is not enough, and this is worth\n494\t/// spelling out because it is what the first attempt at this fix used: all\n495\t/// three bytes are printable (`!`, `,`, `;`), so \"GIF89a header, the six bytes\n496\t/// at the front of every GIF file\" puts a comma exactly there and is junked all\n497\t/// over again. Measured, along with \"GIF89a images! …\" and \"GIF87a format; …\".\n498\t/// So the block is decoded one step further, into fields prose cannot supply:\n499\t///\n500\t/// * after `0x21`, the extension label. The spec defines four — Plain Text\n501\t/// `0x01`, Graphic Control `0xF9`, Comment `0xFE`, Application `0xFF` —\n502\t/// three unprintable and the fourth a control character. Three of them also\n503\t/// pin the first sub-block size; Comment does not, so its chain is walked.\n504\t/// A chain that outruns the read budget is settled on how it ran out:\n505\t/// a full buffer means a megabyte of chain held together, a short one means\n506\t/// the file ended mid-chain.\n507\t/// * after `0x2C`, a 9-byte Image Descriptor. The frame must be non-empty and\n508\t/// must fit inside the canvas declared two fields earlier, which four\n509\t/// little-endian u16s of prose do not.\n510\t///\n511\t/// A bare `0x3B` is refused: that is a GIF containing no image at all, it\n512\t/// appears in no corpus measured, and it carries no pixel data to junk.\n513\t///\n514\t/// The fields this check does NOT use are as important, because round 1 of\n515\t/// #379 used them and they were wrong. Requiring the Pixel Aspect Ratio and\n516\t/// the Background Colour Index to be zero looks safe — satisfying them takes\n517\t/// NUL bytes, and prose has no NULs — but it refuses REAL GIFs. Swept over\n518\t/// every distinct GIF on the build machine (147 files deduped by content hash,\n519\t/// 51 B to 17.6 MB): the rule below accepts 147/147; the aspect/background rule\n520\t/// refused 4, among them this repository's own `docs/media/demo.gif`, whose\n521\t/// aspect byte is 49 — the spec's encoding of a 1:1 pixel ratio, since\n522\t/// `(49 + 15) / 64 = 1.0`.\n523\t///\n524\t/// Falling through to the text heuristics is not a safety net, and the honest\n525\t/// version of that claim is narrower than \"it still classifies binary\". All 4\n526\t/// refused GIFs do still reach `Family::Binary` here, but as `unknown` rather\n527\t/// than `gif`, and only because their first 8 KiB decodes above the 10%\n528\t/// control-character threshold — by 0.14 to 1.5 percentage points. Two other\n529\t/// GIFs in the same 147 sit BELOW it, at 9.39% and 9.78%, and would be\n530\t/// sectioned into prose records outright if they were refused. Whether a real\n531\t/// image survives therefore turns on the entropy of its first 8 KiB, which no\n532\t/// qualifier controls. Pinned by\n533\t/// `real_gif_shapes_the_aspect_ratio_rule_refused`.\n534\tfn gif_screen_descriptor(prefix: &[u8]) -> bool {\n535\t if prefix.len() < 13 || !matches!(&prefix[..6], b\"GIF87a\" | b\"GIF89a\") {\n536\t return false;\n537\t }\n538\t let canvas_width = u16::from_le_bytes([prefix[6], prefix[7]]);\n539\t let canvas_height = u16::from_le_bytes([prefix[8], prefix[9]]);\n540\t if canvas_width == 0 || canvas_height == 0 {\n541\t return false;\n542\t }\n543\t let packed = prefix[10];\n544\t // `3 * 2^(N+1)`, N being the low three bits: 6 bytes at N=0, 768 at N=7.\n545\t let color_table = if packed & 0x80 != 0 {\n546\t 3 * (1usize << ((packed & 0x07) + 1))\n547\t } else {\n548\t 0\n549\t };\n550\t // Background Colour Index (11) and Pixel Aspect Ratio (12) are skipped on\n551\t // purpose — see above, real encoders put non-zero bytes in both.\n552\t let block = 13 + color_table;\n553\t match prefix.get(block) {\n554\t // Extension. The label alone is not a discriminator: `decode()` falls\n555\t // back to windows-1252 (see `decode`, below), where 0xF9/0xFE/0xFF are\n556\t // ordinary latin-1 letters, so `\"GIF89a fichie!\" + 0xF9 + French prose`\n557\t // satisfied the label check and was junked as an image. The spec pins\n558\t // the FIRST sub-block size for three of the four labels, and all three\n559\t // sizes are non-printable.\n560\t Some(0x21) => match (prefix.get(block + 1), prefix.get(block + 2)) {\n561\t (Some(0x01), Some(12)) => true, // Plain Text: 12-byte block\n562\t (Some(0xf9), Some(4)) => true, // Graphic Control: 4-byte block\n563\t (Some(0xff), Some(11)) => true, // Application: 11-byte block\n564\t // Comment sizes are genuinely variable (1..=255 per sub-block), so\n565\t // there is no fixed byte to pin. Walk the sub-block chain instead:\n566\t // a real Comment terminates with a 0x00 and is followed by another\n567\t // introducer. Prose has to land that whole structure, not one byte.\n568\t //\n569\t // A zero FIRST size is the empty comment `21 FE 00`, which giflib\n570\t // writes for `EGifPutExtensionLeader(0xFE)` + `EGifPutExtensionTrailer`\n571\t // and which every decoder here accepts. It used to fall to `_ =>\n572\t // false`, which refused all six such files in the corpus even\n573\t // though every one of them decodes in both Pillow and giflib.\n574\t // The NUL is the evidence: it sits at a derived offset, and\n575\t // prose has no NUL to put there — so nothing further is checked,\n576\t // and in particular the byte AFTER it is not, because giflib emits\n577\t // its zero-length sub-block and its trailer as `21 FE 00 00`.\n578\t (Some(0xfe), Some(0)) => true,\n579\t (Some(0xfe), Some(_)) => {\n580\t // Walk the sub-block chain. Two outcomes are decisive and one\n581\t // is not, and conflating them is what broke real GIFs: a\n582\t // comment longer than the 8 KiB prefix simply cannot be walked\n583\t // to its end here, and \"I ran out of buffer\" is not evidence\n584\t // of text.\n585\t let mut at = block + 2;\n586\t loop {\n587\t match prefix.get(at) {\n588\t // Terminated inside the prefix: decisive. A real\n589\t // comment is followed by another block. `None` means\n590\t // the terminator is the last byte we hold, which is\n591\t // the prefix edge, not a malformed file.\n592\t Some(0) => {\n593\t return matches!(prefix.get(at + 1), None | Some(0x21 | 0x2c | 0x3b));\n594\t }\n595\t Some(&len) => at += 1 + usize::from(len),\n596\t // Ran out of bytes, and the answer turns on WHY.\n597\t //\n598\t // Be clear about what the walk proves, because the\n599\t // obvious reading is backwards. Its only stop condition\n600\t // is a NUL landing on a hop; every other byte 1..=255 is\n601\t // a legal sub-block size. So \"the chain survived\" means\n602\t // \"no NUL landed on a hop\" and nothing else. Text has no\n603\t // NULs, so text survives with probability 1. Measured\n604\t // precisely: 0 of the 265 corpus text negatives contain\n605\t // a NUL anywhere, so no walk over any of them can\n606\t // terminate — which is the property this needs. (Only\n607\t // 10 of the 265 actually reach the walk; the rest fail\n608\t // the header gate first. An earlier draft said \"265 of\n609\t // 265 walk a full megabyte\", which overstated what was\n610\t // exercised even though the conclusion holds.) High-entropy\n611\t // binary is what the walk rejects: 0 of 200 uniform\n612\t // random megabytes survive, matching\n613\t // (255/256)^(2^20/128.5) = 1.4e-14. It is not even much\n614\t // of a walk — hops average 59 bytes in a prose fixture\n615\t // and 256 in a real commented GIF, so it inspects 1.7%\n616\t // and 0.4% of the buffer respectively.\n617\t //\n618\t // The discriminating is therefore done by the header\n619\t // gate above, not here: `0x21` at `block` and `0xFE`\n620\t // at `block + 1`, where `block = 13 + gct` and `gct` is\n621\t // 0 without a Global Colour Table — so the pair sits at\n622\t // one of 13, 19, 25, 37, 61, 109, 205, 397 or 781, NOT\n623\t // at a fixed offset. What the gate rests on is not that\n624\t // text lacks 0xFE — 43 of the 265 corpus text negatives\n625\t // contain one somewhere — but that text does not carry\n626\t // 0x21 followed by 0xFE at one of those nine computed\n627\t // offsets. An earlier version of this sentence said\n628\t // \"0xFE is neither ASCII nor valid UTF-8, which is the\n629\t // part ordinary text lacks\", which is the kind of\n630\t // unmeasured universal this comment block exists to\n631\t // stop, written into the sentence explaining the gate.\n632\t // Verified on disk — the same 1 MiB French-prose file\n633\t // with 0x7E in that slot stays TxtProse and with 0xFE\n634\t // becomes binary/gif. All this arm decides is how much\n635\t // text has to accumulate behind that gate before it is\n636\t // admitted — so on THIS path the budget is the rule and\n637\t // the chain is not. Not on the other one: the canvas\n638\t // disjunct below is ungated by size, as the paragraph\n639\t // twenty-five lines down already says.\n640\t //\n641\t // Given that, a FULL buffer answers image. A SHORT one\n642\t // asks the canvas rule from round 4.\n643\t //\n644\t // Be exact about which files that rule sees, because an\n645\t // earlier version of this comment was not. It said the\n646\t // short-buffer arm only judges TRUNCATED files, on the\n647\t // reasoning that a complete GIF terminates its comment.\n648\t // The half about GIFs is true; the half about the\n649\t // population is false, and the file says why thirty\n650\t // lines up: the walk stops only on a NUL, and text has\n651\t // none, so ANY text file that clears the header gate\n652\t // runs its chain to EOF and lands here — at 3 KB as\n653\t // readily as at 3 MB. It is then called an image\n654\t // whenever `prefix[7]` or `prefix[9]` is a byte below\n655\t // 0x20 other than \\t, \\n or \\r — 29 values, not \"a\n656\t // control byte\": DEL (0x7F) and the C1 range do not\n657\t // trigger it. Measured: the same prose\n658\t // with 0x0B, 0x0C or 0x1B at offset 7 is Binary at\n659\t // 3,000 / 20,000 / 600,000 bytes, and with 0x0A stays\n660\t // TxtProse at all three.\n661\t //\n662\t // So there are two independent paths to \"image\" and\n663\t // only one of them is size-gated. The cost stated below\n664\t // as \"10 corpus text files above the budget\" is the\n665\t // full-buffer path's cost alone; the canvas path adds\n666\t // prose with a control byte in a canvas high slot, at\n667\t // any size, and no corpus file exercises it. Two\n668\t // explanations for that have now been wrong, so this\n669\t // one states only what was counted and stops.\n670\t //\n671\t // Of the 264 GIF-magic text negatives, ZERO carry 0x0A\n672\t // at offset 7 or 9, and zero carry any byte below 0x20\n673\t // there. The distribution is 'b' x194 / 'e' x26 at\n674\t // offset 7 and 'd' x180 / 't' x26 at offset 9, and 180\n675\t // of the files carry the literal bytes `abcd` at 6..9 —\n676\t // because the generators splice `filler = a,b,c,d,…`\n677\t // straight after the magic — build_text.py:199 for 140\n678\t // of them, the same line duplicated at build_text2.py:62\n679\t // and :72 for the other 40. So the\n680\t // frequencies are the builder's alphabet, NOT \"ordinary\n681\t // prose\" as an earlier version of this comment claimed,\n682\t // and certainly not a property of English: the corpus\n683\t // deliberately includes Spanish, French, Russian,\n684\t // Chinese, Greek, Hebrew and Arabic negatives.\n685\t //\n686\t // Every one of these files was generated by\n687\t // build_text.py / build_text2.py, so the builder chose\n688\t // what follows the magic. (An earlier draft added\n689\t // \"nothing in real prose opens with GIF magic\" here.\n690\t // That is not among what was counted, and this file\n691\t // elsewhere rests on the opposite: the block-introducer\n692\t // arm exists because `\"GIF89a header, the six bytes at\n693\t // the front of every GIF file\"` is real prose that does.)\n694\t // No fixture family was ever\n695\t // built to put a control byte at 7 or 9, so the corpus\n696\t // has no power to see this path. That is a fact about\n697\t // its construction, and there is no further mechanism\n698\t // to infer.\n699\t //\n700\t // That composition is measured against the budget test\n701\t // alone, not assumed. Identical on every set that\n702\t // matters and strictly better on one:\n703\t //\n704\t // 71 round-5 GIFs 71 Binary both\n705\t // 674 corpus images 674 Binary both\n706\t // 265 text negatives 257 text both\n707\t // 265 inflated past budget 18 Binary both\n708\t // 13 corpus GIFs cut @8192 13 Binary vs 2\n709\t //\n710\t // The last row is the reason to keep it: without the\n711\t // canvas fallback 11 of 13 truncated real images go to\n712\t // the prose extractor. A file mid-copy in a watched\n713\t // directory is that shape, and `sniff` runs on live\n714\t // paths (lib.rs:1151, 4258). That is a real gain, paid\n715\t // for with a text cost that has no size floor — the\n716\t // trade, stated whole rather than at its flattering\n717\t // end.\n718\t //\n719\t // Answering image unconditionally on a short buffer\n720\t // instead (round 2's rejected `true`) junks 10 corpus\n721\t // text files — windows-1252 prose carrying `þ` in that\n722\t // slot — so the full-buffer half stays as it is. Pinned\n723\t // by `a_truncated_gif_is_called_an_image_and_that_is_the_trade`,\n724\t // which now asserts Binary.\n725\t None => {\n726\t return prefix.len() >= GIF_PREFIX\n727\t || canvas_dimension_text_cannot_write(prefix)\n728\t }\n729\t }\n730\t }\n731\t }\n732\t _ => false,\n733\t },\n734\t Some(0x2c) => {\n735\t // Image Descriptor: 8 bytes of geometry, then its own packed byte.\n736\t let Some(desc) = prefix.get(block + 1..block + 10) else {\n737\t return false;\n738\t };\n739\t let left = u32::from(u16::from_le_bytes([desc[0], desc[1]]));\n740\t let top = u32::from(u16::from_le_bytes([desc[2], desc[3]]));\n741\t let width = u32::from(u16::from_le_bytes([desc[4], desc[5]]));\n742\t let height = u32::from(u16::from_le_bytes([desc[6], desc[7]]));\n743\t if width == 0\n744\t || height == 0\n745\t || left + width > u32::from(canvas_width)\n746\t || top + height > u32::from(canvas_height)\n747\t {\n748\t return false;\n749\t }\n750\t // Geometry alone is satisfiable by all-ASCII input. For any such\n751\t // input `packed & 0x80` is clear, so `block` is always 13, and a\n752\t // ',' at offset 13 followed by four little-endian u16s whose HIGH\n753\t // bytes (15, 17, 19, 21) are spaces clears every bound above.\n754\t // Decode one field further, to the LZW minimum code size that\n755\t // opens the image data. A GIF palette holds at most 256 entries, so\n756\t // this field is bits-per-pixel and cannot exceed 8 — codes grow to\n757\t // 12 bits during compression, but the MINIMUM code size is 2..=8.\n758\t // Round 2 wrote 2..=12, and that width is what let text back\n759\t // through: 9, 10, 11 and 12 are exactly TAB, LF, VT and FF, so an\n760\t // ordinary line break at the derived offset satisfied it. Measured,\n761\t // every real image-descriptor-first GIF on the build machine\n762\t // carries 8 here across palettes of 2 to 256 entries, while the\n763\t // CP1252 and ASCII counterexamples carry 9 or 10.\n764\t let has_local_table = desc[8] & 0x80 != 0;\n765\t // A frame needs a palette: its own Local Colour Table, or the\n766\t // Global one. With neither there is nothing to decode pixels\n767\t // against, so such a file is not a GIF at all. This is what\n768\t // separates prose whose byte at the LZW position happens to be a\n769\t // control character — the CSV counterexample carries `\\n` (10),\n770\t // which is inside the old 2..=12 range and cleared the check\n771\t // below on its own.\n772\t if !has_local_table && packed & 0x80 == 0 {\n773\t return false;\n774\t }\n775\t let local_table = if has_local_table {\n776\t 3 * (1usize << ((desc[8] & 0x07) + 1))\n777\t } else {\n778\t 0\n779\t };\n780\t matches!(prefix.get(block + 10 + local_table), Some(2..=8))\n781\t }\n782\t _ => false,\n783\t }\n784\t}\n785\t\n786\t// A Comment sub-block chain that outruns the read budget is decided by the\n787\t// chain itself: see the `None` arm above. This is the fifth attempt at that\n788\t// decision and the first that does not invent a discriminator, so the four\n789\t// refused rules are recorded here to stop a sixth from re-deriving one.\n790\t// Measurements are against a 939-file ground-truth corpus (674 images / 265\n791\t// text files, every image decode-checked twice — Pillow `open`+`load` and\n792\t// giflib `DGifOpenFileName`+`DGifSlurp`), plus 138 later counterexamples built\n793\t// specifically to break whichever rule was current.\n794\t//\n795\t// * `false` (\"inconclusive means text\", round 2): refuses all 92 corpus\n796\t// images that open on an outrunning comment; 88 become 3,063 prose records.\n797\t// * `seen > 1 && every size seen is 0xFF` (round 3), on the reasoning that\n798\t// encoders pack long comments maximally. They do not. giflib's streaming\n799\t// `EGifPutExtensionBlock` writes ONE sub-block per call at whatever length\n800\t// the caller passed, so chains of 1, 2, 16, 32, 64, 100, 120, 127, 128,\n801\t// 192, 200 and 250..=254 are ordinary encoder output; ImageMagick writes\n802\t// 200/199/199…, and the eight real commented GIFs on the build machine\n803\t// (GIMP, ezgif.com, ajaxload.info) carry 17, 26, 45 and 49 and not one 255.\n804\t// Refuses 37 of the 92.\n805\t// * the canvas high bytes at offsets 7 and 9 (round 4), on the reasoning\n806\t// that printable text can only declare a dimension >= 0x2000. True, and\n807\t// still a guess about the file rather than a reading of it: it refuses any\n808\t// real image whose canvas high byte is printable. 30 decodable GIFs\n809\t// regress to `TxtProse` and 37,450 junk records, and the corpus could not\n810\t// see it because its canvas high bytes are all 0..8 and 11.\n811\t// * the Global Colour Table flag (`packed & 0x80`), the other LSD field that\n812\t// looks unforgeable: it is not. A windows-1252 accented letter at offset 10\n813\t// sets it, which is how the corpus's own `gctflag_*` fixtures were built —\n814\t// 8 of them are junked as images by that rule.\n815\t//\n816\t// The lesson each of those shares is that a property of the files at hand was\n817\t// written down as a property of the format. The budget test is not that: a\n818\t// full buffer means a megabyte of sub-block chain was actually traversed.\n819\t//\n820\t// HISTORICAL, and left here because the mistake is instructive. For four\n821\t// commits (a182317, 0e5d740, d778f70, cf60b65) the short-buffer answer was\n822\t// plain `prefix.len() >= GIF_PREFIX`, and\n823\t// this paragraph recorded its cost in the present tense: truncated GIFs, plain\n824\t// and gzipped alike, going to the prose extractor — 7 of 7 plain cuts, after an\n825\t// earlier draft had wrongly narrowed it to `.gif.gz` only. All true then.\n826\t//\n827\t// It stopped being true when the canvas fallback came back, and the arm now\n828\t// says so. The paragraph nonetheless survived four commits and six reviews\n829\t// still asserting the opposite of the code twenty lines above it — which is\n830\t// the very failure it was written to warn about, one document later, in the\n831\t// document doing the warning.\n832\t//\n833\t// A previous version of THIS paragraph then made the same class of mistake\n834\t// while correcting it. It offered \"13 of 13 curated cuts and 60 of 60\n835\t// real-corpus cuts at 300 KB / 700 KB / 1,048,575 B are Binary\" as proof that\n836\t// the canvas fallback is what obsoleted the old rule. The cuts are Binary, but\n837\t// the canvas fallback decides NONE of them: at those three sizes the comment\n838\t// chain still terminates inside the buffer, so the walk never reaches the\n839\t// `None` arm at all and an earlier arm answers. Measured over the 674-image\n840\t// corpus, counting how many cuts reach the `None` arm and how many of those\n841\t// the canvas disjunct then decides:\n842\t//\n843\t// cut files >= cut reach `None` arm canvas-decided\n844\t// 8,192 249 90 90\n845\t// 300,000 83 0 0\n846\t// 700,000 61 0 0\n847\t// 1,048,575 53 0 0\n848\t//\n849\t// So the real \"13 of 13\" figure is an 8 KiB measurement, quoted against three\n850\t// sizes where the mechanism it names is inert. The canvas disjunct is\n851\t// load-bearing — at 8,192 it decides all 90 — but not there.\n852\t\n853\tfn canvas_dimension_text_cannot_write(prefix: &[u8]) -> bool {\n854\t // `prefix[..13]` is guaranteed by the length check in the only caller.\n855\t let high_byte_is_binary = |hi: u8| hi < 0x20 && !matches!(hi, b'\\t' | b'\\n' | b'\\r');\n856\t high_byte_is_binary(prefix[7]) || high_byte_is_binary(prefix[9])\n857\t}\n858\t\n859\t/// Windows bitmap: `BM`, then a 14-byte BITMAPFILEHEADER, then a DIB header\n860\t/// that opens with its own size.\n861\t///\n862\t/// The discriminator is the DIB header size and the two fields immediately\n863\t/// behind it. Every DIB header ever defined is between 12 (BITMAPCOREHEADER)\n864\t/// and 124 (BITMAPV5HEADER) bytes, so its little-endian u32 puts three NUL\n865\t/// bytes at offsets 15..18, where `BMW,model,year` puts `ar\\n`. Colour planes\n866\t/// is then fixed at 1 by every variant of the header, which pins a fourth NUL,\n867\t/// and bit depth behind it is a closed set. Those are the checks text cannot\n868\t/// pass; the pixel-array offset must additionally clear both headers.\n869\t///\n870\t/// Two tighter rules were tried first, in round 1 of #379, and both refuse real\n871\t/// bitmaps — which is the failure this table exists to prevent, so neither is\n872\t/// used:\n873\t///\n874\t/// * `bfReserved1/2` at offsets 6..10 are specified as zero, but a bitmap\n875\t/// converted from a CUR or ICO carries the cursor hot-spot coordinates\n876\t/// there.\n877\t/// * a closed set of DIB sizes `{12, 16, 40, 52, 56, 64, 108, 124}` admits\n878\t/// five of the OS/2 2.x BITMAPCOREHEADER2 sizes, which are legally anything\n879\t/// in `16..=64`, and refuses the other 44.\n880\t///\n881\t/// Only 3 real BMPs exist on the build machine, all BITMAPINFOHEADER with zero\n882\t/// reserved words, so unlike the GIF sweep this is reasoned from the format\n883\t/// definitions rather than measured against a corpus — but the mechanism is the\n884\t/// one that demonstrably broke GIF, and a synthetic hot-spot / OS/2 bitmap does\n885\t/// sniff `txt-prose` under the old rule. Pinned by\n886\t/// `real_bmp_shapes_the_closed_set_refused`.\n887\t///\n888\t/// `bfSize` (offsets 2..6) is deliberately NOT compared against the file\n889\t/// length, which is what #379 proposed. Two reasons, both structural: this\n890\t/// function classifies from the `read_prefix(path, gzip, 8192)` buffer and has\n891\t/// no file length to compare against, and for a gzipped member the on-disk\n892\t/// length is the *compressed* length, so the comparison would be wrong exactly\n893\t/// where it was applied.\n894\tfn bmp_file_header(prefix: &[u8]) -> bool {\n895\t if prefix.len() < 18 {\n896\t return false;\n897\t }\n898\t let pixel_offset = u32::from_le_bytes([prefix[10], prefix[11], prefix[12], prefix[13]]);\n899\t let dib_header_size = u32::from_le_bytes([prefix[14], prefix[15], prefix[16], prefix[17]]);\n900\t if !(12..=124).contains(&dib_header_size) || pixel_offset < 14 + dib_header_size {\n901\t return false;\n902\t }\n903\t // Colour planes then bit depth. BITMAPCOREHEADER declares u16 width and\n904\t // height, every later header i32, which moves the pair from 22 to 26.\n905\t let planes_at = if dib_header_size == 12 { 22 } else { 26 };\n906\t let Some(f) = prefix.get(planes_at..planes_at + 4) else {\n907\t return false;\n908\t };\n909\t u16::from_le_bytes([f[0], f[1]]) == 1\n910\t && matches!(\n911\t u16::from_le_bytes([f[2], f[3]]),\n912\t // 0 is BI_JPEG / BI_PNG, where the DIB carries an embedded image.\n913\t 0 | 1 | 2 | 4 | 8 | 16 | 24 | 32\n914\t )\n915\t}\n916\t\n917\t/// Adobe Photoshop: `8BPS` is followed by a big-endian version, 1 for PSD and\n918\t/// 2 for PSB. Nothing else is defined, so a text file whose first word is\n919\t/// `8BPS` fails here on its fifth byte.\n920\tfn psd_version(prefix: &[u8]) -> bool {\n921\t prefix.len() >= 6 && prefix[4] == 0 && matches!(prefix[5], 1 | 2)\n922\t}\n923\t\n924\t/// RIFF container: `RIFF`, a little-endian chunk size, then a four-character\n925\t/// FORM type naming what the container actually holds. Requiring a known FORM\n926\t/// is what separates a WAV from a sentence that opens with the word \"RIFF\".\n927\t///\n928\t/// `ACON` is the animated-cursor FORM. It is listed because `ANI ` — which was\n929\t/// here on its own — is the file EXTENSION, not the FORM type, and no encoder\n930\t/// writes it: swept over every RIFF file on the build machine (195 files;\n931\t/// FORM types `WAVE` 158, `WEBP` 25, `ACON` 12), the closed set without `ACON`\n932\t/// refused all 12 real `.ani` files. Same defect shape as #379 one row up, so\n933\t/// it is corrected here rather than left for the closed set to be widened a\n934\t/// third time.\n935\tfn riff_form(prefix: &[u8]) -> bool {\n936\t prefix.len() >= 12\n937\t && matches!(\n938\t &prefix[8..12],\n939\t b\"WAVE\" | b\"AVI \" | b\"WEBP\" | b\"RMID\" | b\"ACON\" | b\"CDDA\" | b\"PAL \" | b\"RDIB\"\n940\t )\n941\t}\n942\t\n943\t/// Ogg page header: `OggS` then the stream structure version, which has been\n944\t/// 0 for the life of the format (RFC 3533 §6.1).\n945\tfn ogg_page(prefix: &[u8]) -> bool {\n946\t prefix.len() >= 5 && prefix[4] == 0\n947\t}\n948\t\n949\t/// FLAC stream: `fLaC` then a METADATA_BLOCK_HEADER whose block type must be\n950\t/// STREAMINFO (0) for the first block; the top bit is the last-block flag.\n951\tfn flac_metadata_block(prefix: &[u8]) -> bool {\n952\t prefix.len() >= 5 && prefix[4] & 0x7f == 0\n953\t}\n954\t\n955\t/// Autodesk FBX, binary flavour: the header is the 18 letters `Kaydara FBX\n956\t/// Binary`, two spaces, a NUL, then `0x1A 0x00` — 23 bytes before the uint32\n957\t/// version field. The three unprintable bytes are the entire discriminator;\n958\t/// the letters on their own are ordinary English, and they are *more* likely\n959\t/// to appear as prose inside this PR's own target corpus, a Unity/3D-asset\n960\t/// tree, than anywhere else. Measured through `sniff()`: a `.md` note opening\n961\t/// \"Kaydara FBX Binary is the 20-byte magic that opens every binary FBX file\n962\t/// exported by Autodesk tools. \" was `TxtProse` on `ca4d75a` and\n963\t/// `Binary`/`fbx` on this branch until this check existed, and `scan_file`\n964\t/// turns `Family::Binary` into \"junk: binary content (fbx)\" — never indexed.\n965\tfn fbx_header(prefix: &[u8]) -> bool {\n966\t prefix.starts_with(b\"Kaydara FBX Binary \\x00\\x1a\\x00\")\n967\t}\n968\t\n969\t/// ID3v2 tag header: `ID3`, a major version (2, 3 and 4 are the versions that\n970\t/// exist), a revision that is not the reserved 0xFF, a flags byte, and a\n971\t/// four-byte SYNCHSAFE size whose bytes each have the top bit clear.\n972\t///\n973\t/// Unqualified, this signature is three ASCII letters: a CSV whose first\n974\t/// column header is `ID3` classified `Csv` on `ca4d75a` and `Binary` on this\n975\t/// branch until the version byte was checked.\n976\tfn id3v2_header(prefix: &[u8]) -> bool {\n977\t prefix.len() >= 10\n978\t && matches!(prefix[3], 2..=4)\n979\t && prefix[4] != 0xff\n980\t && prefix[6..10].iter().all(|b| *b < 0x80)\n981\t}\n982\t\n983\t/// PDF header: `%PDF-M.N` — a single-digit major version, `.`, a single-digit\n984\t/// minor version — immediately followed by an end-of-line marker, which the\n985\t/// spec requires right after the version (ISO 32000-1 §7.5.2, \"the header\n986\t/// line shall be immediately followed by a comment... the header\n987\t/// itself... terminated by an end-of-line marker\").\n988\t///\n989\t/// Unqualified, this signature is five ASCII characters including `%` and\n990\t/// `-`. Prose opening \"%PDF- is the five byte header every PDF file begins\n991\t/// with. \" sniffed `Family::Pdf` and was handed to the PDF extractor, which\n992\t/// cannot parse it (#403 — same class as #379/#380, filed separately: `%`\n993\t/// and `-` shrink the collision surface a lot, and the wrong answer is a\n994\t/// parse error rather than #379's silent junk reason). The qualifier is\n995\t/// exactly what makes it safe: a sentence has a space (or nothing) after\n996\t/// \"1.7\", never a CR/LF, and real generators always emit that break —\n997\t/// Adobe's own spec calls it out as required, not conventional.\n998\tfn pdf_header(prefix: &[u8]) -> bool {\n999\t prefix.len() >= 9\n1000\t && prefix[5].is_ascii_digit()\n1001\t && prefix[6] == b'.'\n1002\t && prefix[7].is_ascii_digit()\n1003\t && matches!(prefix[8], b'\\r' | b'\\n')\n1004\t}\n1005\t\n1006\t/// Truevision TGA, which has no magic number at all — every byte of its\n1007\t/// 18-byte header is data. Detection is therefore by CONSTRAINT: an image type\n1008\t/// from the defined set, a pixel depth from the defined set, a colour-map\n1009\t/// descriptor that must be all-zero when there is no colour map, and non-zero\n1010\t/// dimensions.\n1011\t///\n1012\t/// The reason this is safe on text is byte 1 and byte 2: `color_map_type` is 0\n1013\t/// or 1 and `image_type` is one of six values below 12, so both the second and\n1014\t/// the third byte of the file have to be control characters. Prose, CSV, JSON\n1015\t/// and source code fail on byte 1.\n1016\tfn looks_like_tga_header(prefix: &[u8]) -> bool {\n1017\t if prefix.len() < 18 {\n1018\t return false;\n1019\t }\n1020\t let color_map_type = prefix[1];\n1021\t if color_map_type > 1 {\n1022\t return false;\n1023\t }\n1024\t // 1/2/3 uncompressed colour-mapped/true-colour/greyscale, 9/10/11 the\n1025\t // run-length encoded counterparts. Type 0 (\"no image data\") is excluded\n1026\t // deliberately: it carries no pixels, so nothing is lost by letting such a\n1027\t // file fall through to the text heuristics, and admitting it would make an\n1028\t // all-zero prefix a TGA.\n1029\t if !matches!(prefix[2], 1 | 2 | 3 | 9 | 10 | 11) {\n1030\t return false;\n1031\t }\n1032\t if !matches!(prefix[16], 8 | 15 | 16 | 24 | 32) {\n1033\t return false;\n1034\t }\n1035\t if color_map_type == 0 && prefix[3..8].iter().any(|b| *b != 0) {\n1036\t return false;\n1037\t }\n1038\t let width = u16::from_le_bytes([prefix[12], prefix[13]]);\n1039\t let height = u16::from_le_bytes([prefix[14], prefix[15]]);\n1040\t width > 0 && height > 0\n1041\t}\n1042\t\n1043\t/// POSIX/GNU tar: the `ustar` magic sits at offset 257 of the first 512-byte\n1044\t/// header block. Five printable letters are not evidence on their own (the\n1045\t/// `MAGIC_TABLE` invariant), so the header's own checksum has to agree: bytes\n1046\t/// 148..156 hold, in octal, the sum of all 512 header bytes with that field\n1047\t/// read as spaces. Text that happens to say `ustar` at byte 257 does not also\n1048\t/// carry a correct checksum of itself 109 bytes earlier.\n1049\tfn looks_like_tar_header(prefix: &[u8]) -> bool {\n1050\t let Some(header) = prefix.get(..512) else {\n1051\t return false;\n1052\t };\n1053\t if &header[257..262] != b\"ustar\" {\n1054\t return false;\n1055\t }\n1056\t let stored = header[148..156]\n1057\t .iter()\n1058\t .skip_while(|b| **b == b' ')\n1059\t .take_while(|b| (b'0'..=b'7').contains(*b))\n1060\t .fold(0u64, |acc, b| acc * 8 + u64::from(*b - b'0'));\n1061\t let computed: u64 = header\n1062\t .iter()\n1063\t .enumerate()\n1064\t .map(|(i, b)| {\n1065\t if (148..156).contains(&i) {\n1066\t u64::from(b' ')\n1067\t } else {\n1068\t u64::from(*b)\n1069\t }\n1070\t })\n1071\t .sum();\n1072\t stored == computed\n1073\t}\n1074\t\n1075\t/// What to tell the user about a file that is an ARCHIVE, or `None` for any\n1076\t/// other binary kind.\n1077\t///\n1078\t/// autoindex never opens archives: unpacking is unbounded work on untrusted\n1079\t/// input (zip bombs, path traversal, a 50 GB Takeout part inflating into the\n1080\t/// state directory), and the honest alternative to doing that badly is saying\n1081\t/// so. \"binary content (zip)\" is true and useless to someone whose entire\n1082\t/// Google Takeout download is that one file — so the reason names the action.\n1083\tpub fn archive_advice(binary_kind: &str, gzip: bool) -> Option<String> {\n1084\t let (what, how) = match (binary_kind, gzip) {\n1085\t (\"zip\", _) => (\"zip archive\", \"unzip <file>\"),\n1086\t (\"tar\", true) => (\"gzip-compressed tar archive\", \"tar -xzf <file>\"),\n1087\t (\"tar\", false) => (\"tar archive\", \"tar -xf <file>\"),\n1088\t (\"7z\", _) => (\"7z archive\", \"7z x <file>\"),\n1089\t (\"rar\", _) => (\"rar archive\", \"unrar x <file>\"),\n1090\t (\"xz\", _) => (\n1091\t \"xz-compressed file\",\n1092\t \"xz -dk <file>, or tar -xJf <file> for a .tar.xz\",\n1093\t ),\n1094\t _ => return None,\n1095\t };\n1096\t Some(format!(\n1097\t \"unextracted {what}: autoindex does not open archives — extract it first ({how}), \\\n1098\t then run autoindex on the extracted folder\"\n1099\t ))\n1100\t}\n1101\t\n1102\tfn decode(bytes: &[u8]) -> (String, &'static str) {\n1103\t match std::str::from_utf8(bytes) {\n1104\t Ok(s) => (s.to_string(), \"utf-8\"),\n1105\t Err(e) => {\n1106\t // Tolerate a multi-byte char cut at the prefix boundary.\n1107\t if e.valid_up_to() + 4 >= bytes.len() {\n1108\t (\n1109\t String::from_utf8_lossy(&bytes[..e.valid_up_to()]).into_owned(),\n1110\t \"utf-8\",\n1111\t )\n1112\t } else {\n1113\t let (s, _, _) = encoding_rs::WINDOWS_1252.decode(bytes);\n1114\t (s.into_owned(), WINDOWS_1252_LOSSY)\n1115\t }\n1116\t }\n1117\t }\n1118\t}\n1119\t\n1120\t/// Decode a whole byte buffer for extraction (same policy as sniffing).\n1121\tpub fn decode_text(bytes: &[u8]) -> (String, &'static str) {\n1122\t decode(bytes)\n1123\t}\n1124\t\n1125\tfn classify_text(text: &str, nonblank: &[&str]) -> Family {\n1126\t // Email wins first: an RFC 5322 message opens with a header block whose lines\n1127\t // (`From:`/`Date:`/`Message-ID:`/…) would otherwise be misread as prose or a\n1128\t // key:value log. Gated on a STRONG header plus >=3 canonical headers so an\n1129\t // ordinary `key: value` config or YAML never trips it.\n1130\t // A mailbox is an email with a separator line in front of it, so it is\n1131\t // tested first: the separator is not a header, and without this branch the\n1132\t // `looks_like_email` gate below fails on line one and a multi-GB mailbox\n1133\t // falls through to prose — every message's headers indexed as body text and\n1134\t // the record cap cutting it off after the first few thousand sections.\n1135\t if looks_like_mbox(nonblank) {\n1136\t return Family::Mbox;\n1137\t }\n1138\t if looks_like_email(nonblank) {\n1139\t return Family::Eml;\n1140\t }\n1141\t\n1142\t // Structured families (JSON/HTML/XML/logs/SQL/CSV) win first, for the whole\n1143\t // file and — via the #551 frontmatter lookahead below — for a frontmatter\n1144\t // body too.\n1145\t if let Some(family) = classify_structured(text, nonblank) {\n1146\t return family;\n1147\t }\n1148\t\n1149\t // YAML — but a leading `---` is also the opening delimiter of markdown/prose\n1150\t // frontmatter (Jekyll, Hugo, Obsidian, Docusaurus, MkDocs, Astro, and Claude\n1151\t // Code skill files — including the two this repo ships). Without a lookahead\n1152\t // for the *closing* `---` and what follows it, every such file was handed to\n1153\t // the YAML extractor, which keeps the frontmatter mapping and the first\n1154\t // paragraph and discards the rest of the body (#551, silent data loss). If\n1155\t // the file opens with `---`, has a matching closing `---`, and the body after\n1156\t // it is not itself YAML, classify by that body so the whole document is\n1157\t // indexed. A pure/multi-document YAML file keeps YAML: the content after its\n1158\t // `---` document marker is still YAML — judged on line shape first and, when\n1159\t // that is inconclusive, by whether the body actually parses as a YAML stream\n1160\t // (#587).\n1161\t let leads_with_marker = nonblank.first().map(|l| l.trim() == \"---\").unwrap_or(false);\n1162\t if leads_with_marker {\n1163\t if let Some(close_offset) = nonblank.iter().skip(1).position(|l| l.trim() == \"---\") {\n1164\t let body = &nonblank[close_offset + 2..];\n1165\t // #587 item 3: this guard used to demand `body.len() >= 2`, so a\n1166\t // frontmatter file with a single non-blank body line still went to\n1167\t // the YAML extractor, which keeps the frontmatter mapping and drops\n1168\t // that line. One line is enough to judge on its shape.\n1169\t if !body.is_empty() && yaml_like_count(body) * 2 < body.len() {\n1170\t let body_text = body.join(\"\\n\");\n1171\t // #587 item 1: classify the body by its real structured family\n1172\t // (JSON/CSV/HTML/logs/SQL), not prose-only, so a\n1173\t // frontmatter-over-CSV/JSON body matches its frontmatter-less\n1174\t // twin. `classify_structured` never re-enters this\n1175\t // YAML/frontmatter branch, so a recursive frontmatter parse\n1176\t // cannot occur. It runs before the parse tier below because\n1177\t // JSON *is* valid YAML — measured over 36,936 real\n1178\t // frontmatter-shaped files, putting the parse first pulled 341\n1179\t // JSON bodies and one XML body back into `Yaml` and undid #587\n1180\t // item 1 for them.\n1181\t if let Some(family) = classify_structured(&body_text, body) {\n1182\t return family;\n1183\t }\n1184\t // #587 item 2: the line-shape test above is not enough on its\n1185\t // own — a genuine multi-document YAML stream whose later\n1186\t // document is dominated by block scalars, comments and\n1187\t // continuation lines fails it and was re-classified as prose,\n1188\t // losing its per-document key structure. Parse the body: a real\n1189\t // stream parses, a markdown body does not (`parses_as_yaml_stream`).\n1190\t if !parses_as_yaml_stream(&body_text) {\n1191\t return txt_kind(body);\n1192\t }\n1193\t // else: a real YAML stream — fall through to `Family::Yaml`.\n1194\t }\n1195\t }\n1196\t }\n1197\t if leads_with_marker || yaml_line_ratio(nonblank) >= 0.6 {\n1198\t return Family::Yaml;\n1199\t }\n1200\t\n1201\t txt_kind(nonblank)\n1202\t}\n1203\t\n1204\t/// Header name of an RFC 5322 header line (`From`, `Content-Type`, `X-Mailer`),\n1205\t/// or `None` if the line is not `Name: …` with an RFC 822 field name.\n1206\tfn header_name(line: &str) -> Option<&str> {\n1207\t let colon = line.find(':')?;\n1208\t let name = &line[..colon];\n1209\t if name.is_empty()\n1210\t || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')\n1211\t || !name.as_bytes()[0].is_ascii_alphabetic()\n1212\t {\n1213\t return None;\n1214\t }\n1215\t Some(name)\n1216\t}\n1217\t\n1218\t/// Does this text open like an mbox mailbox? The first line must be a real\n1219\t/// separator (`From <sender> <asctime date>` — `extract::mbox::is_from_line`,\n1220\t/// the same predicate the splitter cuts on, so the two can never disagree about\n1221\t/// what a mailbox is) AND what follows it must pass the email gate. Detected by\n1222\t/// content, never by the `.mbox` extension: Thunderbird folders have no\n1223\t/// extension at all, Apple Mail's file is literally named `mbox`, and a\n1224\t/// `notes.mbox` that is not a mailbox must not be split as one.\n1225\tfn looks_like_mbox(nonblank: &[&str]) -> bool {\n1226\t match nonblank.split_first() {\n1227\t Some((first, rest)) => {\n1228\t // A UTF-8 BOM in front of the first separator is still a mailbox;\n1229\t // the splitter drops the same three bytes at offset 0.\n1230\t let first = first.strip_prefix('\\u{feff}').unwrap_or(first);\n1231\t crate::extract::mbox::is_from_line(first.as_bytes()) && looks_like_email(rest)\n1232\t }\n1233\t None => false,\n1234\t }\n1235\t}\n1236\t\n1237\t/// Does this text open like an email? Requires the first line to be a header, a\n1238\t/// STRONG header (`From`/`Date`/`Message-ID`/`Received`/…) somewhere in the\n1239\t/// opening block, and at least three canonical email headers total — enough to\n1240\t/// separate a real message from a `key: value` config that merely uses colons.\n1241\tfn looks_like_email(nonblank: &[&str]) -> bool {\n1242\t const STRONG: &[&str] = &[\n1243\t \"from\",\n1244\t \"date\",\n1245\t \"message-id\",\n1246\t \"received\",\n1247\t \"return-path\",\n1248\t \"delivered-to\",\n1249\t \"dkim-signature\",\n1250\t ];\n1251\t const KNOWN: &[&str] = &[\n1252\t \"from\",\n1253\t \"to\",\n1254\t \"cc\",\n1255\t \"bcc\",\n1256\t \"subject\",\n1257\t \"date\",\n1258\t \"message-id\",\n1259\t \"received\",\n1260\t \"return-path\",\n1261\t \"reply-to\",\n1262\t \"in-reply-to\",\n1263\t \"references\",\n1264\t \"mime-version\",\n1265\t \"content-type\",\n1266\t \"content-transfer-encoding\",\n1267\t \"content-disposition\",\n1268\t \"delivered-to\",\n1269\t \"dkim-signature\",\n1270\t \"sender\",\n1271\t \"list-id\",\n1272\t \"authentication-results\",\n1273\t \"x-mailer\",\n1274\t ];\n1275\t if !nonblank\n1276\t .first()\n1277\t .map(|l| header_name(l).is_some())\n1278\t .unwrap_or(false)\n1279\t {\n1280\t return false;\n1281\t }\n1282\t let mut strong = false;\n1283\t let mut known = 0usize;\n1284\t for line in nonblank.iter().take(50) {\n1285\t // Folded continuation lines (leading whitespace) are part of the header\n1286\t // block; the first line that is neither a header nor a fold is the body.\n1287\t let is_fold = line.starts_with(' ') || line.starts_with('\\t');\n1288\t match header_name(line) {\n1289\t Some(name) => {\n1290\t let n = name.to_ascii_lowercase();\n1291\t if KNOWN.contains(&n.as_str()) {\n1292\t known += 1;\n1293\t }\n1294\t if STRONG.contains(&n.as_str()) {\n1295\t strong = true;\n1296\t }\n1297\t }\n1298\t None if is_fold => {}\n1299\t None => break,\n1300\t }\n1301\t }\n1302\t strong && known >= 3\n1303\t}\n1304\t\n1305\t/// The structured-family branches of [`classify_text`] — JSON/JSONL, HTML/XML,\n1306\t/// logs, SQL dump, CSV — returning the first family that matches, or `None` to\n1307\t/// continue to the YAML/prose fallbacks.\n1308\t///\n1309\t/// Extracted (#587) so the #551 frontmatter lookahead can classify its body by\n1310\t/// the *same* structured rules rather than prose-only: before this, a\n1311\t/// frontmatter-over-CSV/JSON file was classified `TxtProse` while its\n1312\t/// frontmatter-less twin was `Csv`/`Json`. It intentionally does **not** look\n1313\t/// at YAML or the `---` frontmatter marker, so running it over a body cannot\n1314\t/// recurse back into the frontmatter lookahead.\n1315\tfn classify_structured(text: &str, nonblank: &[&str]) -> Option<Family> {\n1316\t let trimmed = text.trim_start();\n1317\t // A lone `[section]` opening line that does not parse as JSON is a\n1318\t // TOML/INI table header (`[package]` in Cargo.toml, `[Unit]` in a\n1319\t // systemd unit), not a JSON array. Without this guard every such file\n1320\t // fell into the JSON branch below (any '['-opener passes\n1321\t // `looks_like_json_start`), reached the JSON extractor, and was junked\n1322\t // — which, for Cargo.toml, also silently disabled the cratecite\n1323\t // detector on every real repository (its crate table only holds\n1324\t // indexed files). Live-verified 2026-07-30: three Cargo.tomls junked\n1325\t // as \"json candidate family\" before this guard, indexed after.\n1326\t let ini_table_header = nonblank.first().is_some_and(|l| {\n1327\t let t = l.trim();\n1328\t t.starts_with('[')\n1329\t && t.ends_with(']')\n1330\t && serde_json::from_str::<serde_json::Value>(t).is_err()\n1331\t });\n1332\t // JSON / JSONL\n1333\t if !ini_table_header && (trimmed.starts_with('{') || trimmed.starts_with('[')) {\n1334\t if nonblank.len() >= 2 {\n1335\t let parse_ok = nonblank\n1336\t .iter()\n1337\t .filter(|l| serde_json::from_str::<serde_json::Value>(l).is_ok())\n1338\t .count();\n1339\t if parse_ok * 10 >= nonblank.len() * 9 {\n1340\t return Some(Family::Jsonl);\n1341\t }\n1342\t } else if nonblank.len() == 1\n1343\t && serde_json::from_str::<serde_json::Value>(nonblank[0]).is_ok()\n1344\t {\n1345\t // single complete JSON line — treat as JSON value file\n1346\t return Some(Family::Json);\n1347\t }\n1348\t // Pretty-printed or multi-line JSON value.\n1349\t if looks_like_json_start(trimmed) {\n1350\t return Some(Family::Json);\n1351\t }\n1352\t }\n1353\t\n1354\t // HTML / XML — declaration within the first 256 bytes.\n1355\t let head_lc: String = text.chars().take(256).collect::<String>().to_lowercase();\n1356\t if head_lc.contains(\"<!doctype html\") || head_lc.contains(\"<html\") {\n1357\t return Some(Family::Html);\n1358\t }\n1359\t if head_lc.contains(\"<?xml\") || (trimmed.starts_with('<') && text.contains(\"</\")) {\n1360\t // xhtml disguised as xml?\n1361\t let lc: String = text.to_lowercase();\n1362\t if lc.contains(\"<html\") || lc.contains(\"<body\") {\n1363\t return Some(Family::Html);\n1364\t }\n1365\t return Some(Family::Xml);\n1366\t }\n1367\t\n1368\t // Log lines\n1369\t if nonblank.len() >= 3 {\n1370\t let hits = nonblank\n1371\t .iter()\n1372\t .filter(|l| crate::extract::logs::probe_line(l))\n1373\t .count();\n1374\t if hits * 10 >= nonblank.len() * 6 {\n1375\t return Some(Family::Logs);\n1376\t }\n1377\t }\n1378\t\n1379\t // SQL dump\n1380\t let upper: String = text.chars().take(4096).collect::<String>().to_uppercase();\n1381\t if (upper.contains(\"CREATE TABLE\") || upper.contains(\"INSERT INTO\")) && text.contains(';') {\n1382\t return Some(Family::SqlDump);\n1383\t }\n1384\t\n1385\t // CSV — dialect probe happens in caller; here just a cheap plausibility test.\n1386\t if nonblank.len() >= 2 && sniff_csv_dialect(nonblank).is_some() {\n1387\t return Some(Family::Csv);\n1388\t }\n1389\t\n1390\t None\n1391\t}\n1392\t\n1393\tfn looks_like_json_start(t: &str) -> bool {\n1394\t // starts with { or [ and the first ~200 chars look like JSON tokens\n1395\t let head: String = t.chars().take(200).collect();\n1396\t head.contains(':') || head.contains('[') || head.contains('{')\n1397\t}\n1398\t\n1399\tfn yaml_line_ratio(nonblank: &[&str]) -> f64 {\n1400\t if nonblank.len() < 3 {\n1401\t return 0.0;\n1402\t }\n1403\t yaml_like_count(nonblank) as f64 / nonblank.len() as f64\n1404\t}\n1405\t\n1406\t/// Count of lines that read as YAML mapping/sequence entries. Shared by\n1407\t/// `yaml_line_ratio` and the frontmatter lookahead (#551) so both apply the\n1408\t/// identical definition of \"YAML-like line\" — unlike `yaml_line_ratio` this has\n1409\t/// no `< 3` short-circuit, so a short frontmatter body is judged on its content.\n1410\tfn yaml_like_count(lines: &[&str]) -> usize {\n1411\t let re = regex::Regex::new(r\"^\\s*(- )?[\\w.@/-]+:(\\s|$)\").unwrap();\n1412\t lines\n1413\t .iter()\n1414\t .filter(|l| {\n1415\t let t = l.trim_start();\n1416\t // Markdown task-list items (`- [ ]` / `- [x]`) are NOT YAML\n1417\t // evidence: `- [ ] text` is invalid YAML (flow sequence followed\n1418\t // by a scalar), while checklists are everywhere in real notes.\n1419\t // Counting them here routed whole checklist files into the YAML\n1420\t // extractor, which can only junk-file them.\n1421\t let checkbox =\n1422\t t.starts_with(\"- [ ] \") || t.starts_with(\"- [x] \") || t.starts_with(\"- [X] \");\n1423\t re.is_match(l) || (t.starts_with(\"- \") && !checkbox)\n1424\t })\n1425\t .count()\n1426\t}\n1427\t\n1428\t/// Does `text` parse as a YAML stream of structured documents — i.e. was the\n1429\t/// `---` a *document separator* in a multi-document stream rather than the\n1430\t/// closing fence of a markdown frontmatter block?\n1431\t///\n1432\t/// This is the second tier of the frontmatter lookahead's \"is the body YAML?\"\n1433\t/// question (#587 item 2). The first tier is line shape — a body whose lines\n1434\t/// are majority `key:` / `- item` is YAML, which is what real k8s/Ansible/\n1435\t/// OpenAPI streams look like. That tier alone mis-fired on a genuine stream\n1436\t/// whose later document is dominated by block scalars, comments and\n1437\t/// continuation lines: none of those lines are `key:`-shaped, so the body read\n1438\t/// as prose and the stream lost its per-document key structure. The\n1439\t/// discriminator that separates the two precisely is that\n1440\t/// markdown-with-frontmatter is *invalid* as a YAML stream — its body halts\n1441\t/// `serde_yaml`'s iterator, the same property `yaml_x.rs:19-25` relies on —\n1442\t/// while a real multi-document stream parses.\n1443\t///\n1444\t/// Every document must therefore parse (a scalar document, which is what a\n1445\t/// markdown paragraph decodes to, and any parse error both disqualify) and at\n1446\t/// least one must be a mapping or a sequence; an empty document is neutral.\n1447\t/// Observed with serde_yaml 0.9: a markdown body yields `String` then `did not\n1448\t/// find expected <document start>`; a markdown task list, table, fenced block\n1449\t/// or `**bold**` opener errors on the first document; a CSV or numbered-list\n1450\t/// body yields one `String`; a prose-heavy YAML document yields a `Mapping`.\n1451\t///\n1452\t/// The parse runs on at most the 8 KiB sniff prefix, only for a body the line\n1453\t/// tier already judged non-YAML, and only *after* `classify_structured` has had\n1454\t/// its say — JSON is valid YAML, so running it earlier would pull JSON bodies\n1455\t/// back into `Yaml` and undo #587 item 1 (measured: 341 files).\n1456\t///\n1457\t/// The loop cannot spin: `serde_yaml`'s multi-document iterator does not\n1458\t/// advance past a document that fails to parse, and this returns on the first\n1459\t/// error rather than continuing.\n1460\t///\n1461\t/// Residual, stated rather than hidden: a frontmatter body that is *literally*\n1462\t/// a YAML mapping written without `key:`-shaped lines (`Last updated: 2026-01-01`\n1463\t/// — a key containing a space fails the line-shape regex) parses, so it is\n1464\t/// called YAML. It has to parse cleanly end to end for that, which no markdown\n1465\t/// containing a list, a table, a fenced block, an emphasis opener or two\n1466\t/// consecutive paragraphs does.\n1467\tfn parses_as_yaml_stream(text: &str) -> bool {\n1468\t use serde::Deserialize as _;\n1469\t let mut structured = 0usize;\n1470\t for de in serde_yaml::Deserializer::from_str(text) {\n1471\t match serde_yaml::Value::deserialize(de) {\n1472\t Ok(serde_yaml::Value::Mapping(_) | serde_yaml::Value::Sequence(_)) => structured += 1,\n1473\t // `---` on its own, or a comment-only document: carries no\n1474\t // evidence either way.\n1475\t Ok(serde_yaml::Value::Null) => {}\n1476\t // A scalar document is what prose decodes to; an error means this\n1477\t // is not a YAML stream at all.\n1478\t Ok(_) | Err(_) => return false,\n1479\t }\n1480\t }\n1481\t structured > 0\n1482\t}\n1483\t\n1484\tfn txt_kind(nonblank: &[&str]) -> Family {\n1485\t if nonblank.is_empty() {\n1486\t return Family::TxtLines;\n1487\t }\n1488\t // NOTE — a whitespace-density guard (\"text over 4 KiB with under 5%\n1489\t // whitespace is pixel soup, junk it\") was proposed here to catch raw TGA\n1490\t // and `.bytes` payloads that decode into printable characters. It is not\n1491\t // present, deliberately, because low whitespace density does not mean\n1492\t // \"not text\":\n1493\t //\n1494\t // * Chinese, Japanese, Korean, Thai, Lao, Khmer and Burmese prose is\n1495\t // scriptio continua — `nonblank` comes from `text.lines()`, so the\n1496\t // newlines are already stripped and only INTRA-LINE whitespace counts,\n1497\t // which those scripts do not have. Every such document over ~4 KiB\n1498\t // would be junked, in every corpus, worldwide.\n1499\t // * base64 blobs, hex dumps, FASTA/genomic sequences, single-line\n1500\t // minified payloads and long-token files are all legitimate text with\n1501\t // near-zero whitespace.\n1502\t // * `failure_resume_http_tests::legacy_key_collision_fails_before_\n1503\t // visibility_with_scoped_guidance` builds a 65,537-byte fixture of one\n1504\t // repeated ASCII letter. With the guard in place that file sniffs as\n1505\t // binary and the run exits 3 instead of 0 — the false positive is\n1506\t // reachable from this repo's own suite.\n1507\t //\n1508\t // A real TGA is caught by `looks_like_tga_header` in `sniff_bytes`, on the\n1509\t // structure of its 18-byte header. The byte-statistics version of that\n1510\t // check (\"mostly non-ASCII under the windows-1252 fallback\") was tried and\n1511\t // removed in the same breath as this one and for the same reason: it\n1512\t // junked Cyrillic, Greek, Hebrew, Arabic and mixed Japanese prose.\n1513\t // Bounding what a magic-less binary costs is the right fix for the concern\n1514\t // those guards existed for; silently deleting files that look unusual is\n1515\t // not. Tracked as #381, which measures the gap this NOTE leaves open: a\n1516\t // 4,194,495-byte printable NUL-free blob sniffs `txt-prose` and expands\n1517\t // into 2048 indexed records.\n1518\t let avg_len = nonblank.iter().map(|l| l.len()).sum::<usize>() as f64 / nonblank.len() as f64;\n1519\t if avg_len > 60.0 {\n1520\t return Family::TxtProse;\n1521\t }\n1522\t // A handful of short lines in a note-like file is still prose.\n1523\t if nonblank.len() <= 5 {\n1524\t return Family::TxtProse;\n1525\t }\n1526\t\n1527\t // Line LENGTH alone splits documents of the same kind. A markdown\n1528\t // postmortem with `## Headings` averages ~50 chars over 7 lines and used\n1529\t // to land in TxtLines, while a 5-line runbook averaging 59 chars landed in\n1530\t // TxtProse — same content type, two different families, therefore two\n1531\t // different datasets with two different field names (`text` vs `body`).\n1532\t // Cross-index BM25 statistics are then incomparable and a caller has to\n1533\t // query both fields.\n1534\t //\n1535\t // Sentence density is the property that actually distinguishes a document\n1536\t // from a record stream: prose lines end in terminal punctuation, whereas\n1537\t // log lines, CSV rows and source code do not. Measured on a mixed corpus:\n1538\t // markdown 0.43-0.57, nginx access logs 0.00, syslog 0.20, Rust/Python/JS\n1539\t // source 0.00-0.10.\n1540\t let sentences = nonblank\n1541\t .iter()\n1542\t .filter(|l| {\n1543\t let t = l.trim_end();\n1544\t t.ends_with('.') || t.ends_with('!') || t.ends_with('?')\n1545\t })\n1546\t .count();\n1547\t let sentence_ratio = sentences as f64 / nonblank.len() as f64;\n1548\t if sentence_ratio >= 0.40 {\n1549\t return Family::TxtProse;\n1550\t }\n1551\t\n1552\t // Hard-wrapped markdown rescue. Sentence density per LINE undercounts\n1553\t // prose whose author wraps at ~70-80 columns: sentences end mid-line, so\n1554\t // a five-paragraph note with a `# Title` scores ~0.30 and landed in\n1555\t // TxtLines — which silently cost it its title, its section anchors, and\n1556\t // (second brain) its wikilink detection. Content evidence, not the\n1557\t // extension: a file that OPENS with an ATX heading and shows either\n1558\t // markdown link syntax or some terminal punctuation is a markdown\n1559\t // document. The heading-opener requirement keeps shebang'd scripts\n1560\t // (`#!…`) and most code/config out; the second signal keeps out comment\n1561\t // banners over pure record streams.\n1562\t let md_link = nonblank\n1563\t .iter()\n1564\t .any(|l| l.contains(\"[[\") || l.contains(\"](\"));\n1565\t if md_heading(nonblank[0]) && (md_link || sentence_ratio >= 0.20) {\n1566\t return Family::TxtProse;\n1567\t }\n1568\t Family::TxtLines\n1569\t}\n1570\t\n1571\t/// `# Title` … `###### Title` — an ATX markdown heading (1-6 `#`, a space,\n1572\t/// then text). `#!/bin/sh` and bare `#` fail the space-then-text rule.\n1573\tfn md_heading(line: &str) -> bool {\n1574\t let t = line.trim_start();\n1575\t let hashes = t.bytes().take_while(|&b| b == b'#').count();\n1576\t (1..=6).contains(&hashes) && t.as_bytes().get(hashes) == Some(&b' ') && t.len() > hashes + 1\n1577\t}\n1578\t\n1579\t/// Quote-aware field split (supports \" and ' quoting).\n1580\tfn split_quoted(line: &str, delim: u8) -> Vec<String> {\n1581\t let mut fields = Vec::new();\n1582\t let mut cur = String::new();\n1583\t let mut quote: Option<char> = None;\n1584\t for c in line.chars() {\n1585\t match quote {\n1586\t Some(q) => {\n1587\t if c == q {\n1588\t quote = None;\n1589\t } else {\n1590\t cur.push(c);\n1591\t }\n1592\t }\n1593\t None => {\n1594\t if c == '\"' || c == '\\'' {\n1595\t quote = Some(c);\n1596\t } else if c as u32 == delim as u32 {\n1597\t fields.push(std::mem::take(&mut cur));\n1598\t } else {\n1599\t cur.push(c);\n1600\t }\n1601\t }\n1602\t }\n1603\t }\n1604\t fields.push(cur);\n1605\t fields\n1606\t}\n1607\t\n1608\tfn sniff_csv_dialect(nonblank: &[&str]) -> Option<CsvDialect> {\n1609\t if nonblank.len() < 2 {\n1610\t return None;\n1611\t }\n1612\t let sample: Vec<&str> = nonblank.iter().take(64).copied().collect();\n1613\t let mut best: Option<(u8, usize)> = None; // (delim, field count)\n1614\t for delim in *b\",;\\t|\" {\n1615\t let counts: Vec<usize> = sample\n1616\t .iter()\n1617\t .map(|l| split_quoted(l, delim).len())\n1618\t .collect();\n1619\t let first = counts[0];\n1620\t if first < 2 {\n1621\t continue;\n1622\t }\n1623\t let consistent = counts.iter().filter(|&&c| c == first).count();\n1624\t // ≥90% of lines share the same field count\n1625\t if consistent * 10 >= counts.len() * 9 {\n1626\t match best {\n1627\t Some((_, bc)) if bc >= first => {}\n1628\t _ => best = Some((delim, first)),\n1629\t }\n1630\t }\n1631\t }\n1632\t let (delim, _) = best?;\n1633\t let head_fields = split_quoted(sample[0], delim);\n1634\t let numericish = |s: &str| {\n1635\t let t = s.trim();\n1636\t !t.is_empty()\n1637\t && t.chars()\n1638\t .all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-' | '+'))\n1639\t && t.chars().any(|c| c.is_ascii_digit())\n1640\t };\n1641\t let has_header = {\n1642\t let mut distinct = std::collections::HashSet::new();\n1643\t let all_nonnum = head_fields.iter().all(|f| !numericish(f));\n1644\t let all_distinct = head_fields\n1645\t .iter()\n1646\t .all(|f| distinct.insert(f.trim().to_string()));\n1647\t let body_has_num = sample\n1648\t .iter()\n1649\t .skip(1)\n1650\t .any(|l| split_quoted(l, delim).iter().any(|f| numericish(f)));\n1651\t all_nonnum && all_distinct && body_has_num\n1652\t };\n1653\t // decimal comma: with ';' delimiter, a meaningful share of fields look like 12,3\n1654\t let decimal_comma = if delim == b';' {\n1655\t let re = regex::Regex::new(r\"^-?\\d{1,9},\\d+$\").unwrap();\n1656\t let (mut num, mut hits) = (0usize, 0usize);\n1657\t for l in sample.iter().skip(if has_header { 1 } else { 0 }) {\n1658\t for f in split_quoted(l, delim) {\n1659\t let t = f.trim().to_string();\n1660\t if numericish(&t) {\n1661\t num += 1;\n1662\t if re.is_match(&t) {\n1663\t hits += 1;\n1664\t }\n1665\t }\n1666\t }\n1667\t }\n1668\t num > 0 && hits * 10 >= num * 3\n1669\t } else {\n1670\t false\n1671\t };\n1672\t Some(CsvDialect {\n1673\t delim,\n1674\t has_header,\n1675\t decimal_comma,\n1676\t })\n1677\t}\n1678\t\n1679\t#[cfg(test)]\n1680\tmod unity_sniff_tests {\n1681\t use super::*;\n1682\t use std::path::Path;\n1683\t\n1684\t fn sniff_str(s: &str, name: &str) -> Family {\n1685\t sniff_bytes(s.as_bytes(), Path::new(name), Path::new(name), false)\n1686\t .unwrap()\n1687\t .family\n1688\t }\n1689\t\n1690\t /// A real RFC 5322 message classifies as `Eml`; a `key: value` config or a\n1691\t /// YAML file that merely uses colons must NOT (the detector is gated on a\n1692\t /// strong header plus >=3 canonical email headers).\n1693\t #[test]\n1694\t fn email_is_detected_but_config_is_not() {\n1695\t let email = \"From: Dana Klein <[email protected]>\\n\\\n1696\t To: Alex Rivard <[email protected]>\\n\\\n1697\t Subject: Acquisition next steps\\n\\\n1698\t Date: Tue, 15 Jul 2026 09:12:00 -0700\\n\\\n1699\t Message-ID: <[email protected]>\\n\\\n1700\t MIME-Version: 1.0\\n\\n\\\n1701\t Alex, let's move to a term sheet.\\n\";\n1702\t assert_eq!(sniff_str(email, \"m.eml\"), Family::Eml);\n1703\t\n1704\t // A config with colons — one weak match (\"subject\"? no), no strong header.\n1705\t let config = \"name: myapp\\nversion: 1.2.3\\nport: 8080\\ndebug: true\\n\";\n1706\t assert_ne!(sniff_str(config, \"app.yml\"), Family::Eml);\n1707\t\n1708\t // Even a file that happens to have `to:`/`from:` keys but no strong\n1709\t // header and <3 canonical headers stays out.\n1710\t let sneaky = \"to: the moon\\nsubject: rockets\\ncargo: fuel\\n\";\n1711\t assert_ne!(sniff_str(sneaky, \"notes.txt\"), Family::Eml);\n1712\t }\n1713\t\n1714\t #[test]\n1715\t fn unity_tagged_yaml_is_detected_by_header_not_extension() {\n1716\t let scene =\n1717\t \"%YAML 1.1\\n%TAG !u! tag:unity3d.com,2011:\\n--- !u!1 &123\\nGameObject:\\n m_Name: X\\n\";\n1718\t assert_eq!(sniff_str(scene, \"Main.unity\"), Family::UnityYaml);\n1719\t assert_eq!(\n1720\t sniff_str(scene, \"renamed.txt\"),\n1721\t Family::UnityYaml,\n1722\t \"content decides, never the extension\"\n1723\t );\n1724\t }\n1725\t\n1726\t #[test]\n1727\t fn a_bom_before_the_yaml_directive_is_tolerated() {\n1728\t let scene =\n1729\t \"\\u{feff}%YAML 1.1\\n%TAG !u! tag:unity3d.com,2011:\\n--- !u!1 &1\\nGameObject:\\n m_Name: X\\n\";\n1730\t assert_eq!(sniff_str(scene, \"Main.unity\"), Family::UnityYaml);\n1731\t }\n1732\t\n1733\t #[test]\n1734\t fn meta_needs_the_first_line_rule_and_a_guid() {\n1735\t let meta =\n1736\t \"fileFormatVersion: 2\\nguid: 9f1c4d0ab2e34f6\\nMonoImporter:\\n serializedVersion: 2\\n\";\n1737\t assert_eq!(sniff_str(meta, \"Player.cs.meta\"), Family::UnityMeta);\n1738\t let stray = \"config: true\\nfileFormatVersion: 2\\nguid: abc\\n\";\n1739\t assert_ne!(\n1740\t sniff_str(stray, \"some.yaml\"),\n1741\t Family::UnityMeta,\n1742\t \"guid keys inside ordinary YAML must not reclassify it\"\n1743\t );\n1744\t let no_guid = \"fileFormatVersion: 2\\nsettings:\\n a: 1\\n\";\n1745\t assert_ne!(sniff_str(no_guid, \"x.meta\"), Family::UnityMeta);\n1746\t }\n1747\t\n1748\t #[test]\n1749\t fn bvh_is_detected_by_hierarchy_root_header() {\n1750\t let bvh = \"HIERARCHY\\nROOT Hips\\n{\\n OFFSET 0 90 0\\n CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation\\n}\\nMOTION\\nFrames: 2\\nFrame Time: 0.033\\n1 2 3\\n4 5 6\\n\";\n1751\t assert_eq!(sniff_str(bvh, \"clip.bvh\"), Family::Bvh);\n1752\t assert_eq!(\n1753\t sniff_str(bvh, \"clip.txt\"),\n1754\t Family::Bvh,\n1755\t \"content decides, never the extension\"\n1756\t );\n1757\t let not_bvh = \"HIERARCHY\\nof needs (Maslow):\\n- physiological\\n- safety\\n\";\n1758\t assert_ne!(sniff_str(not_bvh, \"notes.txt\"), Family::Bvh);\n1759\t }\n1760\t\n1761\t #[test]\n1762\t fn plain_yaml_without_the_unity_tag_stays_yaml() {\n1763\t let plain = \"%YAML 1.2\\n---\\nkey: value\\nother: 1\\nnested:\\n a: 2\\n\";\n1764\t assert_ne!(sniff_str(plain, \"doc.yaml\"), Family::UnityYaml);\n1765\t }\n1766\t\n1767\t /// Regression: PSD image data decoded via lossy windows-1252 passed the\n1768\t /// NUL/control-char heuristics and classified as txt-prose, shredding a\n1769\t /// multi-MB texture into thousands of junk prose records (a 4 MB blob\n1770\t /// yields ~2,048 sections). Sectioning streams, so the cost is record\n1771\t /// count, not RAM. Media magic bytes must win before any text heuristic.\n1772\t #[test]\n1773\t fn media_containers_are_binary_by_magic_not_heuristics() {\n1774\t for (name, head, kind) in [\n1775\t (\"t.psd\", &b\"8BPS\\x00\\x01\"[..], \"psd\"),\n1776\t (\"t.tif\", &b\"II*\\x00\\x08\\x00\"[..], \"tiff\"),\n1777\t (\"t.tif2\", &b\"MM\\x00*\\x00\\x08\"[..], \"tiff\"),\n1778\t (\"t.wav\", &b\"RIFF\\x24\\x08\\x00\\x00WAVE\"[..], \"riff\"),\n1779\t (\"t.ogg\", &b\"OggS\\x00\\x02\"[..], \"ogg\"),\n1780\t (\"t.flac\", &b\"fLaC\\x00\\x00\\x00\\x22\"[..], \"flac\"),\n1781\t (\"t.mp3\", &b\"ID3\\x03\\x00\\x00\\x00\\x00\\x0f\\x76\"[..], \"mp3\"),\n1782\t // The REAL 23-byte binary-FBX header: the 18 letters, two spaces,\n1783\t // NUL, 0x1A, 0x00. The previous fixture stopped at the NUL, which\n1784\t // is not a header any Autodesk tool emits and which no longer\n1785\t // satisfies `fbx_header`.\n1786\t (\"t.fbx\", &b\"Kaydara FBX Binary \\x00\\x1a\\x00\"[..], \"fbx\"),\n1787\t ] {\n1788\t let mut bytes = head.to_vec();\n1789\t // A printable tail that WOULD pass the prose heuristics.\n1790\t bytes.extend(b\"lorem ipsum dolor sit amet, consectetur adipiscing elit. \".repeat(20));\n1791\t let sn = sniff_bytes(&bytes, Path::new(name), Path::new(name), false).unwrap();\n1792\t assert_eq!(sn.family, Family::Binary, \"{name} must be binary\");\n1793\t assert_eq!(\n1794\t sn.binary_kind.as_deref(),\n1795\t Some(kind),\n1796\t \"{name} must be recognised as {kind}, not fall through to the \\\n1797\t heuristics and land on `unknown`\"\n1798\t );\n1799\t }\n1800\t }\n1801\t\n1802\t /// Regression: the printable-ASCII signatures added by this branch matched\n1803\t /// TEXT. Measured through `sniff()` on `ca4d75a` vs this branch with\n1804\t /// identical fixtures, a CSV whose first column header is `ID3` went `Csv`\n1805\t /// -> `Binary`, and prose whose first word is `RIFF`, `OggS`, `fLaC`,\n1806\t /// `8BPS` or `Kaydara FBX Binary` went `TxtProse` -> `Binary`.\n1807\t /// `scan_file` turns `Family::Binary` into \"junk: binary content (...)\",\n1808\t /// so each of those files stopped being indexed at all.\n1809\t ///\n1810\t /// The FBX case was missed in round 2 and found in review: it was the one\n1811\t /// signature in the table still using `accept`, and at 18 printable\n1812\t /// characters it is the likeliest of all of them to open a real sentence\n1813\t /// — in a Unity/3D-asset corpus above all, which is this PR's target.\n1814\t ///\n1815\t /// The true positives above must keep passing, which is the whole point:\n1816\t /// the signature is necessary, it is just not sufficient.\n1817\t #[test]\n1818\t fn a_printable_ascii_signature_alone_does_not_make_a_file_binary() {\n1819\t let csv = b\"ID3,name,value\\n1,alpha,2\\n3,beta,4\\n5,gamma,6\\n7,delta,8\\n\";\n1820\t assert_eq!(\n1821\t sniff_bytes(csv, Path::new(\"t.csv\"), Path::new(\"t.csv\"), false)\n1822\t .unwrap()\n1823\t .family,\n1824\t Family::Csv,\n1825\t \"a column header may legitimately be the three letters ID3\"\n1826\t );\n1827\t for (label, opener) in [\n1828\t (\n1829\t \"riff\",\n1830\t \"RIFF is a container format used by WAV files. It stores chunks. \",\n1831\t ),\n1832\t (\n1833\t \"oggs\",\n1834\t \"OggS pages carry the packets of an Ogg stream in order. \",\n1835\t ),\n1836\t (\n1837\t \"flac\",\n1838\t \"fLaC is the four byte magic of a FLAC audio stream header. \",\n1839\t ),\n1840\t (\n1841\t \"psd\",\n1842\t \"8BPS is the magic of an Adobe Photoshop document header. \",\n1843\t ),\n1844\t (\n1845\t \"fbx\",\n1846\t \"Kaydara FBX Binary is the 20-byte magic that opens every binary \\\n1847\t FBX file exported by Autodesk tools. \",\n1848\t ),\n1849\t // The DOUBLE-space variant is the dangerous one and was previously\n1850\t // only measured by hand, never pinned. `fbx_header` requires the\n1851\t // real 23-byte header `Kaydara FBX Binary \\x00\\x1a\\x00`, and the\n1852\t // two spaces ARE part of it — so this sentence satisfies 20 of\n1853\t // those 23 bytes and is refused only at offset 20, where the\n1854\t // header needs `\\x00` and prose has a letter. The one-space\n1855\t // fixture above is refused one byte earlier, at offset 19. Both\n1856\t // match the 18-byte table entry itself in full; the qualifier is\n1857\t // the only thing that keeps either of them out of `Family::Binary`.\n1858\t (\n1859\t \"fbx-two-space\",\n1860\t \"Kaydara FBX Binary is followed by a NUL and 0x1a in the real \\\n1861\t header, which is what this note is about. \",\n1862\t ),\n1863\t ] {\n1864\t let text = opener.repeat(30);\n1865\t let sn = sniff_bytes(\n1866\t text.as_bytes(),\n1867\t Path::new(\"notes.txt\"),\n1868\t Path::new(\"notes.txt\"),\n1869\t false,\n1870\t )\n1871\t .unwrap();\n1872\t assert_ne!(\n1873\t sn.family,\n1874\t Family::Binary,\n1875\t \"{label}: prose that opens with the signature word is still prose\"\n1876\t );\n1877\t }\n1878\t }\n1879\t\n1880\t /// TGA is the format the removed byte-statistics guard existed for: it has\n1881\t /// no magic number, so a raw texture reaches the text heuristics on its own\n1882\t /// bytes. It is caught on the structure of its 18-byte header instead.\n1883\t #[test]\n1884\t fn a_raw_tga_texture_is_binary_by_header_structure() {\n1885\t // id_len=0, no colour map, uncompressed true-colour, 64x64, 24bpp.\n1886\t let mut tga: Vec<u8> = vec![0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 64, 0, 24, 0];\n1887\t tga.extend((0..8192u32).map(|i| (0x80 + (i * 37) % 0x7f) as u8));\n1888\t let sn = sniff_bytes(\n1889\t &tga,\n1890\t Path::new(\"texture.tga\"),\n1891\t Path::new(\"texture.tga\"),\n1892\t false,\n1893\t )\n1894\t .unwrap();\n1895\t assert_eq!(sn.family, Family::Binary, \"a real TGA header must be seen\");\n1896\t assert_eq!(sn.binary_kind.as_deref(), Some(\"tga\"));\n1897\t\n1898\t // And the constraint must be tight enough that text never satisfies\n1899\t // it. Every one of these is >= 18 bytes, so length is not what saves\n1900\t // them.\n1901\t for (label, text) in [\n1902\t (\n1903\t \"prose\",\n1904\t \"The quick brown fox jumps over the lazy dog again.\",\n1905\t ),\n1906\t (\"csv\", \"id,name,value\\n1,alpha,2\\n3,beta,4\\n\"),\n1907\t (\"json\", \"{\\\"id\\\": 1, \\\"name\\\": \\\"alpha\\\", \\\"value\\\": 2}\"),\n1908\t (\"code\", \"fn main() { println!(\\\"hello, world\\\"); }\"),\n1909\t (\"yaml\", \"name: alpha\\nvalue: 2\\nnested:\\n a: 1\\n\"),\n1910\t ] {\n1911\t assert!(text.len() >= 18, \"{label}: fixture too short to prove it\");\n1912\t assert!(\n1913\t !looks_like_tga_header(text.as_bytes()),\n1914\t \"{label}: text must not satisfy the TGA header constraints\"\n1915\t );\n1916\t }\n1917\t }\n1918\t\n1919\t /// Whitespace density must NOT be used to junk text. This pins the\n1920\t /// counter-examples that make the rejected guard unsafe: a long run of one\n1921\t /// ASCII letter (the shape of this repo's own 65,537-byte resume-key\n1922\t /// fixture), and a base64 blob. Both are >4 KiB with zero whitespace, and\n1923\t /// both are text.\n1924\t #[test]\n1925\t fn whitespace_free_ascii_text_is_not_junked_as_binary() {\n1926\t let mut repeated = \"x\".repeat(65_536);\n1927\t repeated.push('b');\n1928\t let b64: String = std::iter::repeat_n(\"QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo\", 300)\n1929\t .collect::<Vec<_>>()\n1930\t .join(\"\");\n1931\t for (label, text) in [(\"repeated-letter\", &repeated), (\"base64\", &b64)] {\n1932\t assert!(text.chars().filter(|c| c.is_whitespace()).count() == 0);\n1933\t let sn = sniff_bytes(\n1934\t text.as_bytes(),\n1935\t Path::new(\"blob.txt\"),\n1936\t Path::new(\"blob.txt\"),\n1937\t false,\n1938\t )\n1939\t .unwrap();\n1940\t assert_ne!(\n1941\t sn.family,\n1942\t Family::Binary,\n1943\t \"{label}: whitespace-free ASCII is still text\"\n1944\t );\n1945\t }\n1946\t // Real prose is unaffected either way.\n1947\t let prose = \"The quick brown fox jumps over the lazy dog. \".repeat(200);\n1948\t let sn = sniff_bytes(\n1949\t prose.as_bytes(),\n1950\t Path::new(\"note.txt\"),\n1951\t Path::new(\"note.txt\"),\n1952\t false,\n1953\t )\n1954\t .unwrap();\n1955\t assert_ne!(sn.family, Family::Binary, \"real prose must stay text\");\n1956\t }\n1957\t\n1958\t /// Regression: a whitespace-density guard judged every script by a rule\n1959\t /// that only holds for space-delimited ones. `nonblank` is built from\n1960\t /// `text.lines()`, so newlines are already gone and only INTRA-LINE\n1961\t /// whitespace counts — which CJK/Thai/Lao/Khmer/Burmese prose does not\n1962\t /// have. Every such document over ~4 KB became `Family::Binary` and was\n1963\t /// junked as \"binary content (unknown)\", in a Unity PR, for users with no\n1964\t /// Unity project. Both original tests used Latin prose and ASCII soup, so\n1965\t /// neither could see it. The guard is gone; this pins the outcome so it\n1966\t /// cannot come back in another form.\n1967\t #[test]\n1968\t fn scriptio_continua_prose_is_not_mistaken_for_binary_soup() {\n1969\t // Each sample is >= 4096 chars (the old guard's gate) and has NO\n1970\t // spaces, exactly like the real documents that were being junked.\n1971\t for (label, unit) in [\n1972\t (\"chinese\", \"本文档描述了系统的架构设计与实现细节。\"),\n1973\t (\n1974\t \"japanese\",\n1975\t \"この文書はシステムの設計と実装について説明します。\",\n1976\t ),\n1977\t (\"korean\", \"이문서는시스템설계와구현에대해설명합니다\"),\n1978\t (\"thai\", \"เอกสารนี้อธิบายการออกแบบและการใช้งานของระบบ\"),\n1979\t ] {\n1980\t let text = unit.repeat(4096 / unit.chars().count() + 2);\n1981\t assert!(\n1982\t text.chars().count() >= 4096,\n1983\t \"{label}: sample must clear the 4096-char gate\"\n1984\t );\n1985\t let ws = text.chars().filter(|c| c.is_whitespace()).count();\n1986\t assert!(\n1987\t ws * 20 < text.chars().count(),\n1988\t \"{label}: sample must be below the 5% whitespace ratio, else \\\n1989\t it would have passed the old guard for the wrong reason\"\n1990\t );\n1991\t let sn = sniff_bytes(\n1992\t text.as_bytes(),\n1993\t Path::new(\"notes.txt\"),\n1994\t Path::new(\"notes.txt\"),\n1995\t false,\n1996\t )\n1997\t .unwrap();\n1998\t assert_ne!(\n1999\t sn.family,\n2000\t Family::Binary,\n2001\t \"{label}: scriptio-continua prose must not be junked as binary\"\n2002\t );\n2003\t }\n2004\t }\n2005\t\n2006\t /// Classify a byte buffer through the REAL read path: a file on disk, read\n2007\t /// by `sniff()`, which sees only `read_prefix(path, gzip, 8192)`.\n2008\t ///\n2009\t /// Every legacy-encoding regression below has to go through this and not\n2010\t /// through `sniff_bytes` with the whole buffer. The escape hatch that was\n2011\t /// supposed to protect legacy CJK required a LOSSLESS trial decode, and a\n2012\t /// double-byte character straddling the 8192-byte cut makes every trial\n2013\t /// decode fail — so a test that hands over the complete buffer cannot\n2014\t /// observe half of the bug it is written for.\n2015\t fn sniff_file(bytes: &[u8], name: &str) -> Family {\n2016\t let dir = tempfile::tempdir().unwrap();\n2017\t let path = dir.path().join(name);\n2018\t std::fs::write(&path, bytes).unwrap();\n2019\t sniff(&path).unwrap().family\n2020\t }\n2021\t\n2022\t /// Regression (round 2): a guard on \"lossy windows-1252 AND over 30%\n2023\t /// non-ASCII\" is not a test for pixel data, it is a test for \"not written\n2024\t /// in Latin script\". windows-1252 is the fallback EVERY legacy 8-bit\n2025\t /// codepage decodes through.\n2026\t ///\n2027\t /// Measured through `sniff()` with these exact fixtures: on `ca4d75a` all\n2028\t /// five are `TxtProse`; with the guard present all five are `Binary`, and\n2029\t /// `scan_file` turns that into \"junk: binary content (unknown)\".\n2030\t ///\n2031\t /// The assertion is deliberately only \"not binary\" — this crate still\n2032\t /// decodes the bytes as windows-1252 and still produces mojibake, because\n2033\t /// telling legacy codepages apart needs a statistical language model it\n2034\t /// does not have. Mojibake that is INDEXED beats prose that is deleted.\n2035\t #[test]\n2036\t fn legacy_single_byte_prose_is_not_junked_by_the_real_read_path() {\n2037\t for (label, enc, unit) in [\n2038\t (\n2039\t \"windows-1251-ru\",\n2040\t encoding_rs::WINDOWS_1251,\n2041\t \"Этот документ описывает архитектуру системы и детали реализации. \",\n2042\t ),\n2043\t (\n2044\t \"koi8-r-ru\",\n2045\t encoding_rs::KOI8_R,\n2046\t \"Этот документ описывает архитектуру системы и детали реализации. \",\n2047\t ),\n2048\t (\n2049\t \"windows-1253-el\",\n2050\t encoding_rs::WINDOWS_1253,\n2051\t \"Το έγγραφο αυτό περιγράφει την αρχιτεκτονική του συστήματος. \",\n2052\t ),\n2053\t (\n2054\t \"windows-1255-he\",\n2055\t encoding_rs::WINDOWS_1255,\n2056\t \"מסמך זה מתאר את ארכיטקטורת המערכת ואת פרטי היישום שלה. \",\n2057\t ),\n2058\t (\n2059\t \"windows-1256-ar\",\n2060\t encoding_rs::WINDOWS_1256,\n2061\t \"تصف هذه الوثيقة بنية النظام وتفاصيل تنفيذه بشكل كامل. \",\n2062\t ),\n2063\t ] {\n2064\t let text = unit.repeat(200);\n2065\t let (bytes, _, had_errors) = enc.encode(&text);\n2066\t assert!(!had_errors, \"{label}: fixture must encode cleanly\");\n2067\t assert!(\n2068\t std::str::from_utf8(&bytes).is_err(),\n2069\t \"{label}: fixture must not be valid UTF-8, or it proves nothing\"\n2070\t );\n2071\t assert!(\n2072\t bytes.len() > 8192,\n2073\t \"{label}: fixture must exceed the sniff prefix\"\n2074\t );\n2075\t assert_ne!(\n2076\t sniff_file(&bytes, \"doc.txt\"),\n2077\t Family::Binary,\n2078\t \"{label}: legacy-encoded prose must not be junked as binary\"\n2079\t );\n2080\t }\n2081\t }\n2082\t\n2083\t /// Regression (round 2): the legacy-CJK escape hatch was alignment\n2084\t /// dependent. `sniff()` classifies from the first 8192 bytes only, so a\n2085\t /// double-byte character split by that cut made the trial decode report\n2086\t /// `had_errors` and the rescue declined. Measured on the branch that\n2087\t /// carried it: the SAME Shift-JIS document was `TxtProse` at byte pads 0\n2088\t /// and 2 and `Binary` at pads 1 and 3 — a coin flip per file.\n2089\t ///\n2090\t /// Sweeping the alignment is the point of this test; a single-length\n2091\t /// fixture passes half the time by luck.\n2092\t #[test]\n2093\t fn legacy_cjk_prose_survives_every_prefix_alignment() {\n2094\t for (label, enc, unit) in [\n2095\t (\n2096\t \"shift_jis\",\n2097\t encoding_rs::SHIFT_JIS,\n2098\t \"この文書はシステムの設計と実装について詳しく説明します。\",\n2099\t ),\n2100\t (\n2101\t \"gbk\",\n2102\t encoding_rs::GBK,\n2103\t \"本文档描述了系统的架构设计与实现。\",\n2104\t ),\n2105\t (\n2106\t \"big5\",\n2107\t encoding_rs::BIG5,\n2108\t \"本文件描述系統的架構設計與實作。\",\n2109\t ),\n2110\t (\n2111\t \"euc-kr\",\n2112\t encoding_rs::EUC_KR,\n2113\t \"이문서는시스템의설계와구현을설명합니다\",\n2114\t ),\n2115\t ] {\n2116\t let text = unit.repeat(400);\n2117\t let (body, _, had_errors) = enc.encode(&text);\n2118\t assert!(!had_errors, \"{label}: fixture must encode cleanly\");\n2119\t assert!(\n2120\t body.len() > 8192,\n2121\t \"{label}: fixture must exceed the sniff prefix, or alignment \\\n2122\t cannot matter\"\n2123\t );\n2124\t for pad in 0..4usize {\n2125\t let mut bytes = vec![b'a'; pad];\n2126\t bytes.extend_from_slice(&body);\n2127\t assert_ne!(\n2128\t sniff_file(&bytes, \"doc.txt\"),\n2129\t Family::Binary,\n2130\t \"{label}: junked at byte-offset pad {pad}\"\n2131\t );\n2132\t }\n2133\t }\n2134\t }\n2135\t\n2136\t /// Regression (round 2): a realistic Japanese technical document is not\n2137\t /// 100% ideographs — it is prose around ASCII code fences, identifiers and\n2138\t /// URLs. That shape sat under the 30% scriptio-continua threshold the\n2139\t /// rescue needed while sitting over the 30% non-ASCII threshold the guard\n2140\t /// junked on, so the ordinary shape of real CJK documentation was the case\n2141\t /// that lost. Measured: `TxtLines` on `ca4d75a`, `Binary` on the branch,\n2142\t /// at both 13 KB and 67 KB.\n2143\t #[test]\n2144\t fn mixed_script_documentation_is_not_junked() {\n2145\t let unit = \"この関数は入力データを検証してから処理を実行し、結果を呼び出し元に返します。\\n\\\n2146\t エラーが発生した場合は、詳細な理由を含む診断情報を記録します。\\n\\\n2147\t ```\\nfn process(d: &[u8]) -> Result<Vec<u8>, ProcessError> {\\n \\\n2148\t let checked = validate(d)?;\\n Ok(checked.to_vec())\\n}\\n```\\n\\\n2149\t See docs/process.md and the API reference for the full parameter list.\\n\";\n2150\t let ideographic =\n2151\t unit.chars().filter(|c| !c.is_ascii()).count() * 100 / unit.chars().count().max(1);\n2152\t assert!(\n2153\t (20..30).contains(&ideographic),\n2154\t \"fixture must sit in the band that loses — between the rescue's \\\n2155\t 30% ideograph floor and the guard's 30% non-ASCII ceiling; got \\\n2156\t {ideographic}%\"\n2157\t );\n2158\t for reps in [40usize, 200] {\n2159\t let doc = unit.repeat(reps);\n2160\t let (bytes, _, _) = encoding_rs::SHIFT_JIS.encode(&doc);\n2161\t assert_ne!(\n2162\t sniff_file(&bytes, \"doc.txt\"),\n2163\t Family::Binary,\n2164\t \"mixed Japanese/ASCII documentation ({} bytes) must not be junked\",\n2165\t bytes.len()\n2166\t );\n2167\t }\n2168\t }\n2169\t\n2170\t /// Accented European prose is the case the removed guard claimed to be\n2171\t /// safe for. It must stay safe now that the guard is gone.\n2172\t #[test]\n2173\t fn european_windows_1252_prose_is_still_prose() {\n2174\t let text = \"Le système décrit ici gère les données réservées à \\\n2175\t l'opérateur, prêtes à être exportées. \";\n2176\t let long = text.repeat(200);\n2177\t let (bytes, _, _) = encoding_rs::WINDOWS_1252.encode(&long);\n2178\t assert!(std::str::from_utf8(&bytes).is_err());\n2179\t let (_, enc) = decode(&bytes);\n2180\t assert_eq!(enc, WINDOWS_1252_LOSSY, \"must stay windows-1252\");\n2181\t assert_ne!(\n2182\t sniff_file(&bytes, \"note.txt\"),\n2183\t Family::Binary,\n2184\t \"accented prose is still prose\"\n2185\t );\n2186\t }\n2187\t\n2188\t #[test]\n2189\t fn binary_serialized_unity_assets_stay_binary() {\n2190\t let mut bytes = b\"UnityFS\\x00\\x00\\x00\\x00\\x08\".to_vec();\n2191\t bytes.extend(std::iter::repeat_n(0u8, 64));\n2192\t let sn = sniff_bytes(\n2193\t &bytes,\n2194\t Path::new(\"scene.unity\"),\n2195\t Path::new(\"scene.unity\"),\n2196\t false,\n2197\t )\n2198\t .unwrap();\n2199\t assert_eq!(sn.family, Family::Binary);\n2200\t }\n2201\t}\n2202\t\n2203\t/// Regression for #379/#380: `GIF8` and `BM` were the last two printable-ASCII\n2204\t/// signatures in `MAGIC_TABLE` taken on faith, so text beginning with those\n2205\t/// characters was classified `Family::Binary` and `scan_file` junked it as\n2206\t/// \"binary content (gif)\" / \"(bmp)\" — never indexed, with a wrong reason. The\n2207\t/// reported case is a CSV whose first column header is `BMW`.\n2208\t///\n2209\t/// Before this module's fix, `gif8_and_bm_are_still_taken_on_faith` pinned the\n2210\t/// wrong answers here on purpose. These tests are its replacement: they assert\n2211\t/// the right answer for the same fixtures, keep the true positives, and add a\n2212\t/// walk of `MAGIC_TABLE` so the *class* of defect cannot come back by way of a\n2213\t/// new row.\n2214\t#[cfg(test)]\n2215\tmod printable_magic_tests {\n2216\t use super::*;\n2217\t\n2218\t fn sniff_str(text: &str, name: &str) -> Sniffed {\n2219\t let p = Path::new(name);\n2220\t sniff_bytes(text.as_bytes(), p, p, false).unwrap()\n2221\t }\n2222\t\n2223\t /// The issue's own three fixtures, plus the CSV shape it calls out. `ID3`\n2224\t /// is included because it was already correct and must stay correct.\n2225\t #[test]\n2226\t fn text_that_opens_with_gif8_or_bm_is_text() {\n2227\t for (label, text, name, want) in [\n2228\t (\n2229\t \"cars-csv\",\n2230\t \"BMW,model,year\\nX5,SUV,2024\\n330i,sedan,2023\\nM3,coupe,2022\\niX,SUV,2025\\n\"\n2231\t .to_string(),\n2232\t \"cars.csv\",\n2233\t Family::Csv,\n2234\t ),\n2235\t (\n2236\t \"bmi-csv\",\n2237\t \"BMI,height_cm,weight_kg\\n22.1,180,71\\n25.6,165,70\\n19.8,171,58\\n27.3,178,86\\n\"\n2238\t .to_string(),\n2239\t \"health.csv\",\n2240\t Family::Csv,\n2241\t ),\n2242\t (\n2243\t \"gif8-csv\",\n2244\t \"GIF8,name,value\\n1,alpha,2\\n3,beta,4\\n5,gamma,6\\n7,delta,8\\n\".to_string(),\n2245\t \"t.csv\",\n2246\t Family::Csv,\n2247\t ),\n2248\t (\n2249\t \"gif-notes\",\n2250\t \"GIF89a is the header format used by the GIF image standard. \".repeat(30),\n2251\t \"gif-notes.txt\",\n2252\t Family::TxtProse,\n2253\t ),\n2254\t (\n2255\t \"gif87a-notes\",\n2256\t \"GIF87a was the first version of the format, published in 1987. \".repeat(30),\n2257\t \"gif87.txt\",\n2258\t Family::TxtProse,\n2259\t ),\n2260\t (\n2261\t \"gif8-prose\",\n2262\t \"GIF8 is the four byte magic that opens a GIF image file. \".repeat(30),\n2263\t \"notes.txt\",\n2264\t Family::TxtProse,\n2265\t ),\n2266\t (\n2267\t \"bm-prose\",\n2268\t \"BM is the two byte magic that opens a Windows bitmap file. \".repeat(30),\n2269\t \"notes.txt\",\n2270\t Family::TxtProse,\n2271\t ),\n2272\t (\n2273\t \"id3-notes\",\n2274\t \"ID3 tags are metadata containers embedded in MP3 files. \".repeat(30),\n2275\t \"id3-notes.txt\",\n2276\t Family::TxtProse,\n2277\t ),\n2278\t ] {\n2279\t let sn = sniff_str(&text, name);\n2280\t assert_ne!(\n2281\t sn.family,\n2282\t Family::Binary,\n2283\t \"{label}: text opening with a printable signature was junked as \\\n2284\t {:?}\",\n2285\t sn.binary_kind\n2286\t );\n2287\t assert_eq!(sn.family, want, \"{label}: wrong family\");\n2288\t }\n2289\t }\n2290\t\n2291\t /// The signature is necessary, it is just not sufficient — real bitmaps and\n2292\t /// real GIFs must still be caught by magic, before any text heuristic, or\n2293\t /// the fix has simply moved the damage (a multi-MB image sectioned into\n2294\t /// thousands of prose records, which is what the magic table exists to\n2295\t /// prevent).\n2296\t #[test]\n2297\t fn real_bitmaps_and_gifs_are_still_binary_by_magic() {\n2298\t // 2x2 24bpp BMP: BITMAPFILEHEADER (14) + BITMAPINFOHEADER (40).\n2299\t let mut bmp: Vec<u8> = b\"BM\".to_vec();\n2300\t bmp.extend_from_slice(&70u32.to_le_bytes()); // bfSize\n2301\t bmp.extend_from_slice(&[0, 0, 0, 0]); // bfReserved1/2\n2302\t bmp.extend_from_slice(&54u32.to_le_bytes()); // bfOffBits\n2303\t bmp.extend_from_slice(&40u32.to_le_bytes()); // biSize\n2304\t bmp.extend_from_slice(&2i32.to_le_bytes()); // biWidth\n2305\t bmp.extend_from_slice(&2i32.to_le_bytes()); // biHeight\n2306\t bmp.extend_from_slice(&[1, 0, 24, 0]); // planes, bpp\n2307\t bmp.extend(std::iter::repeat_n(0u8, 24));\n2308\t // A printable tail that WOULD pass the prose heuristics.\n2309\t bmp.extend(b\"lorem ipsum dolor sit amet, consectetur adipiscing elit. \".repeat(20));\n2310\t\n2311\t // BITMAPCOREHEADER is the other end of the range that exists.\n2312\t let mut bmp_core: Vec<u8> = b\"BM\".to_vec();\n2313\t bmp_core.extend_from_slice(&38u32.to_le_bytes());\n2314\t bmp_core.extend_from_slice(&[0, 0, 0, 0]);\n2315\t bmp_core.extend_from_slice(&26u32.to_le_bytes()); // 14 + 12\n2316\t bmp_core.extend_from_slice(&12u32.to_le_bytes()); // BITMAPCOREHEADER\n2317\t bmp_core.extend_from_slice(&[2, 0, 2, 0, 1, 0, 24, 0]);\n2318\t bmp_core.extend(b\"lorem ipsum dolor sit amet, consectetur adipiscing. \".repeat(20));\n2319\t\n2320\t // GIF89a, 4x4, global colour table of 2 entries, then a Graphic Control\n2321\t // extension — introducer 0x21, label 0xF9.\n2322\t let mut gif: Vec<u8> = b\"GIF89a\".to_vec();\n2323\t gif.extend_from_slice(&4u16.to_le_bytes()); // width\n2324\t gif.extend_from_slice(&4u16.to_le_bytes()); // height\n2325\t gif.push(0x80); // GCT present, 2 entries\n2326\t gif.push(0); // background colour index\n2327\t gif.push(0); // pixel aspect ratio\n2328\t gif.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // GCT\n2329\t // Graphic Control Extension: the spec fixes the block size at 4.\n2330\t // Round 1 stopped at the label, which is why prose carrying a\n2331\t // windows-1252 0xF9 satisfied it (#379).\n2332\t gif.extend_from_slice(&[0x21, 0xf9, 0x04]);\n2333\t gif.extend(b\"lorem ipsum dolor sit amet, consectetur adipiscing elit. \".repeat(20));\n2334\t\n2335\t // GIF87a with no global colour table, opening straight on an Image\n2336\t // Descriptor: introducer 0x2C, then left/top/width/height/packed for a\n2337\t // frame that fills the 16x16 canvas.\n2338\t let mut gif87: Vec<u8> = b\"GIF87a\".to_vec();\n2339\t // GCT flag set (2 entries): a frame with no Local Colour Table has to\n2340\t // borrow the global one, and a GIF carrying neither has no palette to\n2341\t // decode against.\n2342\t gif87.extend_from_slice(&[16, 0, 16, 0, 0x80, 0, 0]);\n2343\t gif87.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // GCT\n2344\t // Image Descriptor, then the LZW minimum code size that opens the\n2345\t // image data — the spec confines it to 2..=8, and it is the field\n2346\t // all-ASCII input cannot supply (#379).\n2347\t gif87.extend_from_slice(&[0x2c, 0, 0, 0, 0, 16, 0, 16, 0, 0, 0x02]);\n2348\t gif87.extend(b\"lorem ipsum dolor sit amet, consectetur adipiscing elit. \".repeat(20));\n2349\t\n2350\t for (name, bytes, kind) in [\n2351\t (\"t.bmp\", bmp, \"bmp\"),\n2352\t (\"core.bmp\", bmp_core, \"bmp\"),\n2353\t (\"t.gif\", gif, \"gif\"),\n2354\t (\"t87.gif\", gif87, \"gif\"),\n2355\t ] {\n2356\t let p = Path::new(name);\n2357\t let sn = sniff_bytes(&bytes, p, p, false).unwrap();\n2358\t assert_eq!(sn.family, Family::Binary, \"{name} must be binary\");\n2359\t assert_eq!(\n2360\t sn.binary_kind.as_deref(),\n2361\t Some(kind),\n2362\t \"{name} must be recognised as {kind} by magic, not fall through \\\n2363\t to the heuristics\"\n2364\t );\n2365\t }\n2366\t }\n2367\t\n2368\t /// A printable body the text heuristics WOULD accept: no NULs and no\n2369\t /// control characters, so a fixture carrying it reaches `TxtProse` the\n2370\t /// moment its qualifier declines. That is what makes the tests below true\n2371\t /// negatives rather than restatements of the NUL ratio check — a colour\n2372\t /// table or a pixel array full of zeroes would be caught by the heuristics\n2373\t /// even with the magic row deleted, and would prove nothing.\n2374\t fn printable_payload(n: usize) -> Vec<u8> {\n2375\t b\"lorem ipsum dolor sit amet, consectetur adipiscing elit. \"\n2376\t .repeat(n)\n2377\t .to_vec()\n2378\t }\n2379\t\n2380\t /// True negatives for the regression round 1 of #379 shipped: real GIF\n2381\t /// header shapes that the \"Pixel Aspect Ratio and Background Colour Index\n2382\t /// must be zero\" qualifier REFUSED, sending a real image down the text\n2383\t /// path to be sectioned into prose records.\n2384\t ///\n2385\t /// Both shapes are transcribed from real files on the build machine, not\n2386\t /// invented — which is the point, since\n2387\t /// `real_bitmaps_and_gifs_are_still_binary_by_magic` builds ideal headers\n2388\t /// and therefore could not see this class at all:\n2389\t ///\n2390\t /// * `docs/media/demo.gif`, this repository's own 3.27 MB demo:\n2391\t /// 720x450, packed `0xF7`, background `0xFF`, **aspect `0x31`**, a\n2392\t /// 768-byte global colour table, then the `0x21 0xFF` NETSCAPE2.0\n2393\t /// application extension that every animated GIF carries. `0x31` is\n2394\t /// not corruption, it is the spec's encoding of a 1:1 pixel ratio:\n2395\t /// `(49 + 15) / 64 = 1.0`.\n2396\t /// * a 92 KB screen capture with the **GCT flag clear and background\n2397\t /// index 255**, which the spec says should be 0 when no table is\n2398\t /// declared and which real encoders write anyway.\n2399\t ///\n2400\t /// Two things about the assertion are deliberate. The bodies are printable\n2401\t /// (see `printable_payload`), so a refused fixture sniffs `TxtProse` — the\n2402\t /// cue for `extract` to turn an image into records — rather than being\n2403\t /// rescued by the control-character heuristic and quietly proving nothing.\n2404\t /// And the expectation is `Some(\"gif\")`, not merely `Family::Binary`,\n2405\t /// because that heuristic is luck, not a fallback: across the 147 real\n2406\t /// GIFs measured it clears the 10% threshold by as little as 0.14 points,\n2407\t /// and two of them sit under it at 9.39% and 9.78%.\n2408\t #[test]\n2409\t fn real_gif_shapes_the_aspect_ratio_rule_refused() {\n2410\t // demo.gif: GCT present and full size, non-zero background AND aspect.\n2411\t let mut animated: Vec<u8> = b\"GIF89a\".to_vec();\n2412\t animated.extend_from_slice(&720u16.to_le_bytes());\n2413\t animated.extend_from_slice(&450u16.to_le_bytes());\n2414\t animated.push(0xf7); // GCT present, 256 entries -> 768 bytes\n2415\t animated.push(0xff); // background colour index\n2416\t animated.push(0x31); // pixel aspect ratio: 1:1, NOT \"unspecified\"\n2417\t animated.extend(printable_payload(14).into_iter().take(768));\n2418\t // NETSCAPE2.0 loop extension. Application Extension block size is\n2419\t // fixed at 11 by the spec (\"NETSCAPE\" + \"2.0\").\n2420\t animated.extend_from_slice(&[0x21, 0xff, 0x0b]);\n2421\t animated.extend(printable_payload(20));\n2422\t assert_eq!(animated[781], 0x21, \"the first block must land at 13 + 768\");\n2423\t\n2424\t // screen capture: GCT flag clear, background index still 255.\n2425\t let mut no_table: Vec<u8> = b\"GIF89a\".to_vec();\n2426\t no_table.extend_from_slice(&2184u16.to_le_bytes());\n2427\t no_table.extend_from_slice(&1280u16.to_le_bytes());\n2428\t no_table.push(0x70); // GCT flag CLEAR\n2429\t no_table.push(0xff); // background colour index, spec says 0\n2430\t no_table.push(0x00);\n2431\t no_table.extend_from_slice(&[0x21, 0xff, 0x0b]);\n2432\t no_table.extend(printable_payload(20));\n2433\t\n2434\t for (label, bytes) in [(\"animated-loop\", animated), (\"no-global-table\", no_table)] {\n2435\t let p = Path::new(\"capture.gif\");\n2436\t let sn = sniff_bytes(&bytes, p, p, false).unwrap();\n2437\t assert_eq!(\n2438\t (sn.family, sn.binary_kind.as_deref()),\n2439\t (Family::Binary, Some(\"gif\")),\n2440\t \"{label}: a real GIF header was refused by its qualifier and \\\n2441\t fell through to the text heuristics as {:?}/{:?} — this is \\\n2442\t #379 inverted, an image turned into prose records\",\n2443\t sn.family,\n2444\t sn.binary_kind\n2445\t );\n2446\t }\n2447\t }\n2448\t\n2449\t /// The same true negative for BMP. `bfReserved1/2` are specified as zero,\n2450\t /// but a bitmap converted from a CUR or ICO carries the cursor hot-spot\n2451\t /// there; OS/2 2.x BITMAPCOREHEADER2 is legally any size in `16..=64`,\n2452\t /// while the closed set round 1 used admitted only five of those 49.\n2453\t /// Bodies are printable, so a refusal here means `TxtProse`, not a lucky\n2454\t /// save by the control-character ratio.\n2455\t #[test]\n2456\t fn real_bmp_shapes_the_closed_set_refused() {\n2457\t fn bmp(dib: u32, reserved: [u8; 4], bits: u16) -> Vec<u8> {\n2458\t let mut v: Vec<u8> = b\"BM\".to_vec();\n2459\t v.extend_from_slice(&(14 + dib + 1024).to_le_bytes()); // bfSize\n2460\t v.extend_from_slice(&reserved);\n2461\t v.extend_from_slice(&(14 + dib + 1024).to_le_bytes()); // bfOffBits\n2462\t v.extend_from_slice(&dib.to_le_bytes());\n2463\t v.extend_from_slice(&256i32.to_le_bytes()); // width\n2464\t v.extend_from_slice(&256i32.to_le_bytes()); // height\n2465\t v.extend_from_slice(&1u16.to_le_bytes()); // colour planes\n2466\t v.extend_from_slice(&bits.to_le_bytes());\n2467\t v.extend(printable_payload(40).into_iter().take(dib as usize - 16));\n2468\t v.extend(printable_payload(40));\n2469\t v\n2470\t }\n2471\t\n2472\t for (label, bytes) in [\n2473\t // Converted from a cursor: hot-spot coordinates in bfReserved1/2.\n2474\t (\"cur-hotspot\", bmp(40, [16, 0, 16, 0], 8)),\n2475\t // OS/2 2.x BITMAPCOREHEADER2, truncated to 24 and 44 bytes — both\n2476\t // legal, neither in the closed set round 1 shipped.\n2477\t (\"os2-dib-24\", bmp(24, [0, 0, 0, 0], 8)),\n2478\t (\"os2-dib-44\", bmp(44, [0, 0, 0, 0], 24)),\n2479\t ] {\n2480\t let p = Path::new(\"logo.bmp\");\n2481\t let sn = sniff_bytes(&bytes, p, p, false).unwrap();\n2482\t assert_eq!(\n2483\t (sn.family, sn.binary_kind.as_deref()),\n2484\t (Family::Binary, Some(\"bmp\")),\n2485\t \"{label}: a real BMP header was refused by its qualifier and \\\n2486\t fell through to the text heuristics as {:?}/{:?}\",\n2487\t sn.family,\n2488\t sn.binary_kind\n2489\t );\n2490\t }\n2491\t }\n2492\t\n2493\t /// The third instance of the same shape, found by sweeping the build\n2494\t /// machine while checking the GIF rule: `riff_form`'s closed set of FORM\n2495\t /// types listed `ANI `, which is the animated-cursor file EXTENSION and\n2496\t /// not its FORM type. The FORM type is `ACON`, and all 12 real `.ani`\n2497\t /// files here were refused. They still reached `Family::Binary` through\n2498\t /// the heuristics — 13.68% and 15.72% control characters against a 10%\n2499\t /// threshold, and one at 90.99% NULs — so the measured cost was the\n2500\t /// specific `binary_kind`, not records; the margin is the same kind of\n2501\t /// luck the GIF rule was relying on.\n2502\t #[test]\n2503\t fn a_riff_form_type_is_the_form_not_the_extension() {\n2504\t let mut ani: Vec<u8> = b\"RIFF\".to_vec();\n2505\t ani.extend_from_slice(&4096u32.to_le_bytes());\n2506\t ani.extend_from_slice(b\"ACON\");\n2507\t ani.extend(printable_payload(20));\n2508\t let p = Path::new(\"wait.ani\");\n2509\t let sn = sniff_bytes(&ani, p, p, false).unwrap();\n2510\t assert_eq!(\n2511\t (sn.family, sn.binary_kind.as_deref()),\n2512\t (Family::Binary, Some(\"riff\")),\n2513\t \"an animated cursor declares FORM type ACON; `ANI ` is the \\\n2514\t extension and no encoder writes it into the container\"\n2515\t );\n2516\t }\n2517\t /// The third must-fix from the round-2 verification: the palette check is a\n2518\t /// single-bit test on a byte that in text is a character. Bit 7 is clear for\n2519\t /// 7-bit ASCII — which is why the round-2 ASCII fixtures passed — but SET\n2520\t /// for every CP1252 accented letter and every UTF-8 lead byte, so the gate\n2521\t /// stood open for exactly the scripts this repository has junked before\n2522\t /// (the #378 reland silently dropped CJK, Cyrillic, Greek, Hebrew and\n2523\t /// Arabic documents over ~4 KB).\n2524\t ///\n2525\t /// The palette bit is not what separates text from images. The LZW minimum\n2526\t /// code size is.\n2527\t #[test]\n2528\t fn accented_and_multibyte_text_is_not_junked_through_the_image_descriptor() {\n2529\t let latin1 = |s: &str, n: usize| -> Vec<u8> {\n2530\t s.repeat(n).chars().map(|c| c as u32 as u8).collect()\n2531\t };\n2532\t let cases: [(&str, Vec<u8>); 3] = [\n2533\t (\n2534\t \"cp1252-spanish-csv\",\n2535\t latin1(\n2536\t \"GIF89a está en desuso hoy,1 2 3 4 5\\nformato,anio,notas\\n\",\n2537\t 30,\n2538\t ),\n2539\t ),\n2540\t (\n2541\t \"cp1252-french-csv\",\n2542\t latin1(\"GIF89a créé en 1987, puis,1 2 3 4 5\\nligne,a,b,c\\n\", 40),\n2543\t ),\n2544\t (\n2545\t \"ascii-csv-newline-at-the-lzw-offset\",\n2546\t \"GIF89a format,1 2 3 4 5\\nrow,a,b,c,d\\n\"\n2547\t .repeat(60)\n2548\t .into_bytes(),\n2549\t ),\n2550\t ];\n2551\t for (label, bytes) in &cases {\n2552\t let p = Path::new(\"notes.txt\");\n2553\t let sn = sniff_bytes(bytes, p, p, false).unwrap();\n2554\t assert_ne!(\n2555\t sn.family,\n2556\t Family::Binary,\n2557\t \"{label}: text junked as {:?} — the image-descriptor path is still open (#379)\",\n2558\t sn.binary_kind\n2559\t );\n2560\t }\n2561\t }\n2562\t\n2563\t /// The Comment-extension arm, which round 2 of #379 added and which an\n2564\t /// independent verification then broke real images with. It is the only\n2565\t /// branch here carrying a loop, so it is the one that needed fixtures and\n2566\t /// did not have them.\n2567\t ///\n2568\t /// The hazard is specific: `sniff` sees only an 8 KiB prefix\n2569\t /// (`read_prefix(.., 8192)`), and a GIF comment may be longer than that.\n2570\t /// The first attempt treated \"the sub-block chain did not terminate inside\n2571\t /// the prefix\" as evidence of text, so a real, decodable GIF carrying a\n2572\t /// licence notice was handed to the prose extractor — #379 with the sign\n2573\t /// flipped.\n2574\t ///\n2575\t /// This fixture is the MAXIMALLY PACKED shape only. Round 3 then read that\n2576\t /// property off this very test and shipped it as the rule (\"every size seen\n2577\t /// is 0xFF\"); `a_streamed_comment_chain_is_not_packed_to_255` below is the\n2578\t /// corpus answer to that, and the two must be read together.\n2579\t #[test]\n2580\t fn a_comment_longer_than_the_sniff_prefix_is_still_a_gif() {\n2581\t /// GIF89a, 4x4, 2-entry global colour table, opening on a Comment\n2582\t /// Extension of `comment_len` bytes, then a minimal image.\n2583\t fn comment_gif(comment_len: usize) -> Vec<u8> {\n2584\t let mut g: Vec<u8> = b\"GIF89a\".to_vec();\n2585\t g.extend_from_slice(&4u16.to_le_bytes());\n2586\t g.extend_from_slice(&4u16.to_le_bytes());\n2587\t g.push(0x80); // GCT present, 2 entries\n2588\t g.push(0);\n2589\t g.push(0);\n2590\t g.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // GCT\n2591\t g.extend_from_slice(&[0x21, 0xfe]); // Comment Extension\n2592\t let mut left = comment_len;\n2593\t while left > 0 {\n2594\t let take = left.min(255);\n2595\t g.push(take as u8);\n2596\t g.extend(std::iter::repeat_n(b'D', take));\n2597\t left -= take;\n2598\t }\n2599\t g.push(0x00); // block terminator\n2600\t g.extend_from_slice(&[0x2c, 0, 0, 0, 0, 4, 0, 4, 0, 0, 0x02]);\n2601\t g\n2602\t }\n2603\t\n2604\t // The last entry outruns `GIF_PREFIX`, so it exercises the arm that\n2605\t // decides on how the buffer ran out rather than on the terminator.\n2606\t for len in [\n2607\t 13usize,\n2608\t 255,\n2609\t 300,\n2610\t 4000,\n2611\t 8_192,\n2612\t 20_000,\n2613\t 60_000,\n2614\t GIF_PREFIX + 4096,\n2615\t ] {\n2616\t let g = comment_gif(len);\n2617\t // What `sniff` actually gets to see: `sniff_with_name` re-reads a\n2618\t // GIF candidate to `GIF_PREFIX`, so this is the whole file or a\n2619\t // megabyte of it, never 8 KiB.\n2620\t let prefix: Vec<u8> = g.iter().copied().take(GIF_PREFIX).collect();\n2621\t let p = Path::new(\"frame.gif\");\n2622\t let sn = sniff_bytes(&prefix, p, p, false).unwrap();\n2623\t assert_eq!(\n2624\t sn.family,\n2625\t Family::Binary,\n2626\t \"comment of {len} B: a real GIF was refused and would be handed \\\n2627\t to the prose extractor — this is #379 inverted\"\n2628\t );\n2629\t assert_eq!(sn.binary_kind.as_deref(), Some(\"gif\"), \"comment of {len} B\");\n2630\t }\n2631\t }\n2632\t\n2633\t /// GIF89a, `canvas` px square, 2-entry global colour table, then a Comment\n2634\t /// Extension whose sub-blocks are `sizes` cycled until the chain outruns\n2635\t /// the GIF read budget. Returns exactly what `read_prefix` would hand\n2636\t /// `sniff_bytes` for such a file — `GIF_PREFIX` bytes and no more.\n2637\t fn streamed_comment_prefix(canvas: u16, sizes: &[u8]) -> Vec<u8> {\n2638\t let mut g: Vec<u8> = b\"GIF89a\".to_vec();\n2639\t g.extend_from_slice(&canvas.to_le_bytes());\n2640\t g.extend_from_slice(&canvas.to_le_bytes());\n2641\t g.push(0x80); // GCT present, 2 entries\n2642\t g.push(0);\n2643\t g.push(0);\n2644\t g.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // GCT\n2645\t g.extend_from_slice(&[0x21, 0xfe]); // Comment Extension\n2646\t for &n in sizes.iter().cycle() {\n2647\t if g.len() > GIF_PREFIX + 512 {\n2648\t break;\n2649\t }\n2650\t g.push(n);\n2651\t g.extend(std::iter::repeat_n(b'D', usize::from(n)));\n2652\t }\n2653\t g.truncate(GIF_PREFIX);\n2654\t g\n2655\t }\n2656\t\n2657\t /// Round 3's rule — \"a chain that outruns the prefix is an image only if\n2658\t /// every sub-block size seen is 0xFF\" — measured against the ground-truth\n2659\t /// corpus (939 files; 674 images, each decode-checked with Pillow AND\n2660\t /// giflib `DGifSlurp`; 265 text files). It refuses 43 of the 92 images that\n2661\t /// reach this arm, and 37 of those are sectioned into prose: 2,524 junk\n2662\t /// records out of two and a half real image files.\n2663\t ///\n2664\t /// The premise is simply not how the encoders write. giflib's streaming\n2665\t /// API emits one sub-block per `EGifPutExtensionBlock` call, at the length\n2666\t /// the CALLER passed, so the corpus holds chains of 1, 2, 16, 32, 64, 100,\n2667\t /// 120, 127, 128, 192, 200 and 250..=254 — `gstream_long_sz064_x160.gif`,\n2668\t /// `prior_*_c001.gif` … `prior_*_c254.gif`. ImageMagick writes a first\n2669\t /// sub-block at N and the rest at N-1 (`prior_*_imagick_im20k_w200.gif`:\n2670\t /// 200, 199, 199, …). Splicing produces alternating 255/10 and 20-then-255\n2671\t /// chains. Every size in `1..=255` is legal and all of these decode in both\n2672\t /// decoders.\n2673\t ///\n2674\t /// The sizes below are the ones actually on disk in that corpus, not a\n2675\t /// sweep invented here.\n2676\t #[test]\n2677\t fn a_streamed_comment_chain_is_not_packed_to_255() {\n2678\t for (label, sizes) in [\n2679\t (\"giflib-stream-1\", &[1u8][..]),\n2680\t (\"giflib-stream-2\", &[2][..]),\n2681\t (\"giflib-stream-16\", &[16][..]),\n2682\t (\"giflib-stream-32\", &[32][..]),\n2683\t (\"giflib-stream-64\", &[64][..]),\n2684\t (\"giflib-stream-100\", &[100][..]),\n2685\t (\"giflib-stream-127\", &[127][..]),\n2686\t (\"giflib-stream-128\", &[128][..]),\n2687\t (\"giflib-stream-192\", &[192][..]),\n2688\t (\"giflib-stream-250\", &[250][..]),\n2689\t (\"giflib-stream-254\", &[254][..]),\n2690\t (\"giflib-stream-255\", &[255][..]),\n2691\t (\"imagemagick-200-then-199\", &[200, 199, 199, 199][..]),\n2692\t (\"imagemagick-60-then-59\", &[60, 59, 59, 59][..]),\n2693\t (\"spliced-255-then-10\", &[255, 10][..]),\n2694\t (\"spliced-20-then-255\", &[20, 255, 255, 255][..]),\n2695\t ] {\n2696\t let prefix = streamed_comment_prefix(48, sizes);\n2697\t assert_eq!(\n2698\t prefix.len(),\n2699\t GIF_PREFIX,\n2700\t \"{label}: fixture must fill the GIF read budget\"\n2701\t );\n2702\t let p = Path::new(\"frame.gif\");\n2703\t let sn = sniff_bytes(&prefix, p, p, false).unwrap();\n2704\t assert_eq!(\n2705\t (sn.family, sn.binary_kind.as_deref()),\n2706\t (Family::Binary, Some(\"gif\")),\n2707\t \"{label}: a real GIF whose comment sub-blocks are not 255 was \\\n2708\t refused and handed to the prose extractor — #379 inverted, and \\\n2709\t the shape 100% of the real commented GIFs on this machine have\"\n2710\t );\n2711\t }\n2712\t }\n2713\t\n2714\t /// The empty Comment Extension, `21 FE 00`. giflib writes it whenever a\n2715\t /// caller opens a comment and closes it without content\n2716\t /// (`EGifPutExtensionLeader(0xFE)` then `EGifPutExtensionTrailer`), and the\n2717\t /// corpus holds six such files — all six decode in Pillow AND giflib, and\n2718\t /// all six were refused, because the arm's guard was `first != 0` and a\n2719\t /// zero first size fell through to `_ => false`.\n2720\t ///\n2721\t /// Both on-disk shapes are here. `21 FE 00 2C` is the plain one;\n2722\t /// `21 FE 00 00 2C` is giflib emitting a zero-length sub-block AND its\n2723\t /// trailer, which is why the byte after the terminator is not checked.\n2724\t #[test]\n2725\t fn an_empty_comment_extension_is_still_a_gif() {\n2726\t fn empty_comment_gif(tail: &[u8]) -> Vec<u8> {\n2727\t let mut g: Vec<u8> = b\"GIF89a\".to_vec();\n2728\t g.extend_from_slice(&8u16.to_le_bytes());\n2729\t g.extend_from_slice(&8u16.to_le_bytes());\n2730\t g.push(0x80);\n2731\t g.push(0);\n2732\t g.push(0);\n2733\t g.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // GCT\n2734\t g.extend_from_slice(&[0x21, 0xfe, 0x00]); // empty comment\n2735\t g.extend_from_slice(tail);\n2736\t g\n2737\t }\n2738\t for (label, tail) in [\n2739\t (\n2740\t \"21-fe-00-then-image\",\n2741\t &[0x2c, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0x02][..],\n2742\t ),\n2743\t (\n2744\t \"21-fe-00-00-then-image\",\n2745\t &[0x00, 0x2c, 0, 0, 0, 0, 8, 0, 8, 0, 0, 0x02][..],\n2746\t ),\n2747\t (\"21-fe-00-then-trailer\", &[0x3b][..]),\n2748\t ] {\n2749\t let bytes = empty_comment_gif(tail);\n2750\t let p = Path::new(\"empty.gif\");\n2751\t let sn = sniff_bytes(&bytes, p, p, false).unwrap();\n2752\t assert_eq!(\n2753\t (sn.family, sn.binary_kind.as_deref()),\n2754\t (Family::Binary, Some(\"gif\")),\n2755\t \"{label}: a decodable GIF carrying an empty comment was refused\"\n2756\t );\n2757\t }\n2758\t }\n2759\t\n2760\t /// The tie-break for an outrunning chain is the canvas, and this is the\n2761\t /// fixture that decides HOW it is read. The obvious form — \"a canvas\n2762\t /// dimension below 8192, which printable ASCII cannot declare\" — is\n2763\t /// forgeable, because `\\t`, `\\n` and `\\r` are bytes below 0x20 that text\n2764\t /// carries all the time: a newline at offset 7 declares a 2680 px width.\n2765\t /// Measured through the real `sniff()`: with the bare `< 8192` test these\n2766\t /// two files classify `binary (gif)`; with `\\t\\n\\r` excluded they stay\n2767\t /// `TxtProse`, which is what they are.\n2768\t #[test]\n2769\t fn prose_with_a_newline_in_the_canvas_is_not_a_gif() {\n2770\t for (label, seven) in [(\"newline\", b'\\n'), (\"tab\", b'\\t'), (\"cr\", b'\\r')] {\n2771\t let mut prose: Vec<u8> = b\"GIF89ax\".to_vec(); // 0..=6\n2772\t prose.push(seven); // 7: canvas width high byte\n2773\t prose.extend_from_slice(b\"yze\"); // 8,9 height; 10 packed (GCT clear)\n2774\t prose.extend_from_slice(b\"st\"); // 11 background, 12 aspect\n2775\t prose.push(b'!'); // 13: Extension introducer\n2776\t prose.push(0xfe); // 14: Comment label\n2777\t prose.push(b'L'); // 15: first sub-block size, 76\n2778\t for _ in 0..400 {\n2779\t prose.extend_from_slice(\n2780\t \"Le format GIF est tres ancien et reste partout sur le web. \".as_bytes(),\n2781\t );\n2782\t }\n2783\t prose.truncate(8192);\n2784\t let p = Path::new(\"notes.txt\");\n2785\t let sn = sniff_bytes(&prose, p, p, false).unwrap();\n2786\t assert_eq!(\n2787\t sn.family,\n2788\t Family::TxtProse,\n2789\t \"{label}: prose was junked as {:?} — this file ends mid-chain, \\\n2790\t which is what a text file does and a GIF does not\",\n2791\t sn.binary_kind\n2792\t );\n2793\t }\n2794\t }\n2795\t\n2796\t /// A truncated GIF is still called an image, by the canvas fallback.\n2797\t ///\n2798\t /// Deliberate, and the reasoning is not that this is harmless. The cost is\n2799\t /// paid in the other direction: the canvas disjunct calls a text file an\n2800\t /// image whenever it carries the header shape and a sub-0x20 byte at\n2801\t /// offset 7 or 9, at any size, which is what\n2802\t /// `the_canvas_path_junks_prose_at_any_size_and_the_budget_does_not_bound_it`\n2803\t /// pins. That is a good file dropped, and a dropped good file is never\n2804\t /// noticed.\n2805\t ///\n2806\t /// HISTORICAL, and kept because it is the reasoning that lost. Between\n2807\t /// `0e5d740` and `12b4a4e` the arm was `prefix.len() >= GIF_PREFIX` alone,\n2808\t /// and this paragraph read: \"A cut real GIF goes to the prose extractor and\n2809\t /// is sectioned into junk records — exactly the harm #379 and #427 were\n2810\t /// fighting, with the sign flipped. It is preferred anyway because a\n2811\t /// truncated GIF is a broken file that no decoder accepts, while the\n2812\t /// alternative (answer \"image\" on a short buffer, round 2's rejected\n2813\t /// `true`) silently drops 10 good corpus text files.\"\n2814\t ///\n2815\t /// `12b4a4e` restored the canvas disjunct and inverted that answer. It\n2816\t /// changed this doc's summary line and the assertion below from\n2817\t /// `Family::TxtProse` to `Family::Binary`, and left the paragraph in place,\n2818\t /// describing a rule that no longer existed — through four commits and\n2819\t /// seven reviews, including the round that rewrote the identical paragraph\n2820\t /// twenty lines above the arm and did not look for its copies.\n2821\t ///\n2822\t /// The 8192 case is here because the fixtures that used to cover it were\n2823\t /// retargeted to `GIF_PREFIX`: a GIF-magic file of exactly 8 KiB still\n2824\t /// reaches `sniff_bytes` with an 8192-byte prefix, and the answer for that\n2825\t /// state inverted in this change.\n2826\t #[test]\n2827\t fn a_truncated_gif_is_called_an_image_and_that_is_the_trade() {\n2828\t /// A real-shaped commented GIF, then cut.\n2829\t fn commented_gif(total: usize) -> Vec<u8> {\n2830\t let mut g: Vec<u8> = b\"GIF89a\".to_vec();\n2831\t g.extend_from_slice(&1920u16.to_le_bytes());\n2832\t g.extend_from_slice(&1080u16.to_le_bytes());\n2833\t g.push(0x80);\n2834\t g.push(0);\n2835\t g.push(0);\n2836\t g.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]);\n2837\t g.extend_from_slice(&[0x21, 0xfe]);\n2838\t while g.len() < total {\n2839\t g.push(255);\n2840\t g.extend(std::iter::repeat_n(b'D', 255));\n2841\t }\n2842\t g.truncate(total);\n2843\t g\n2844\t }\n2845\t\n2846\t let p = Path::new(\"cut.gif\");\n2847\t for cut in [8192usize, 300_000, 700_000, GIF_PREFIX - 1] {\n2848\t let sn = sniff_bytes(&commented_gif(cut), p, p, false).unwrap();\n2849\t assert_eq!(\n2850\t sn.family,\n2851\t Family::Binary,\n2852\t \"a GIF cut to {cut} B must still read as an image: the chain ran \\\n2853\t past EOF, which a complete GIF cannot do, and the canvas then \\\n2854\t settles it. This asserted TxtProse for three commits \\\n2855\t (0e5d740, d778f70, cf60b65), which sent 11 of 13 truncated \\\n2856\t corpus images to the prose extractor\"\n2857\t );\n2858\t }\n2859\t }\n2860\t\n2861\t /// The canvas path's cost, which has NO size floor.\n2862\t ///\n2863\t /// Without this test nothing pins that path at all: the two budget tests\n2864\t /// below put `\\n` at offset 7, which `canvas_dimension_text_cannot_write`\n2865\t /// excludes, so the canvas rule never fires for them. That is an accident\n2866\t /// of those fixtures, not a property of the rule.\n2867\t ///\n2868\t /// Both slots are exercised. The rule is `prefix[7] || prefix[9]`, and a\n2869\t /// test varying only one would let a future edit drop the other half\n2870\t /// without failing anything.\n2871\t #[test]\n2872\t fn the_canvas_path_junks_prose_at_any_size_and_the_budget_does_not_bound_it() {\n2873\t let p = Path::new(\"notes.txt\");\n2874\t // `slot` is 7 or 9 — the two canvas high bytes the rule reads. Varying\n2875\t // only one would let a future edit drop the other half of the\n2876\t // disjunction without failing anything.\n2877\t let build = |slot: usize, high: u8, size: usize| {\n2878\t let mut v: Vec<u8> = b\"GIF89axyyzest\".to_vec();\n2879\t v[slot] = high;\n2880\t v.push(b'!');\n2881\t v.push(0xfe);\n2882\t v.push(b'L');\n2883\t while v.len() < size {\n2884\t v.extend_from_slice(\"Le format GIF reste partout sur le web. \".as_bytes());\n2885\t }\n2886\t v.truncate(size);\n2887\t v\n2888\t };\n2889\t for size in [3_000usize, 20_000, 600_000] {\n2890\t for slot in [7usize, 9] {\n2891\t for high in [0x0bu8, 0x0c, 0x1b] {\n2892\t assert_eq!(\n2893\t sniff_bytes(&build(slot, high, size), p, p, false)\n2894\t .unwrap()\n2895\t .family,\n2896\t Family::Binary,\n2897\t \"prose with {high:#04x} at offset {slot} must be called an \\\n2898\t image at {size} bytes: the canvas path has no size floor, \\\n2899\t so any statement of this rule's cost that says \\\"above \\\n2900\t the budget\\\" describes only the other half\"\n2901\t );\n2902\t }\n2903\t assert_eq!(\n2904\t sniff_bytes(&build(slot, b'\\n', size), p, p, false)\n2905\t .unwrap()\n2906\t .family,\n2907\t Family::TxtProse,\n2908\t \"\\\\n at offset {slot} must stay text: it is excluded from the \\\n2909\t canvas rule, and that exclusion is the only reason the two \\\n2910\t budget tests below reach the path they claim to bound\"\n2911\t );\n2912\t assert_eq!(\n2913\t sniff_bytes(&build(slot, 0x7f, size), p, p, false)\n2914\t .unwrap()\n2915\t .family,\n2916\t Family::TxtProse,\n2917\t \"0x7F must stay text at offset {slot}: the rule is \\\"below \\\n2918\t 0x20\\\", not \\\"a control byte\\\", and DEL is a control byte\"\n2919\t );\n2920\t }\n2921\t }\n2922\t }\n2923\t\n2924\t /// `GIF_PREFIX` bounds the FULL-buffer path, so pin it to a fixed byte\n2925\t /// count rather than to itself — without this, `>= 300_000` passes the\n2926\t /// suite.\n2927\t ///\n2928\t /// It is not \"the whole rule\". `full || canvas` has two independent paths\n2929\t /// to \"image\" and only this one is size-gated; the canvas path is pinned by\n2930\t /// `the_canvas_path_junks_prose_at_any_size_and_the_budget_does_not_bound_it`.\n2931\t /// This fixture reaches the budget path only because `\\n` at offset 7 keeps\n2932\t /// it off the canvas path, which is an accident of the fixture — written\n2933\t /// down so the next person to widen the text cost does not read this test\n2934\t /// as a safety net it is not.\n2935\t #[test]\n2936\t fn the_budget_is_the_threshold_it_claims() {\n2937\t let mut prose: Vec<u8> = b\"GIF89ax\".to_vec();\n2938\t prose.push(b'\\n');\n2939\t prose.extend_from_slice(b\"yzest\");\n2940\t prose.push(b'!');\n2941\t prose.push(0xfe);\n2942\t prose.push(b'L');\n2943\t while prose.len() < 1_100_000 {\n2944\t prose.extend_from_slice(\"Le format GIF reste partout sur le web. \".as_bytes());\n2945\t }\n2946\t let p = Path::new(\"notes.txt\");\n2947\t\n2948\t // 600 KB is over any plausible lowered budget and under this one. If a\n2949\t // future change shrinks GIF_PREFIX below this, this file — ordinary\n2950\t // windows-1252 prose — starts being indexed as an image.\n2951\t let six_hundred_k: Vec<u8> = prose.iter().copied().take(600_000).collect();\n2952\t assert_eq!(\n2953\t sniff_bytes(&six_hundred_k, p, p, false).unwrap().family,\n2954\t Family::TxtProse,\n2955\t \"600 KB of prose must not be called an image; lowering GIF_PREFIX \\\n2956\t below 600 KB is what would do it\"\n2957\t );\n2958\t assert_eq!(\n2959\t GIF_PREFIX,\n2960\t 1 << 20,\n2961\t \"the budget is the rule — changing it changes which text files are \\\n2962\t called images, so change the comment and the trade with it\"\n2963\t );\n2964\t }\n2965\t\n2966\t /// The cost of deciding a budget-exhausted chain as an image, pinned so it\n2967\t /// is a recorded trade and not a later surprise.\n2968\t ///\n2969\t /// A file that outruns `GIF_PREFIX` with its chain intact is called an\n2970\t /// image, and text reaches that state easily — it has no NUL, so the walk\n2971\t /// cannot terminate in it. The entry cost is the header alone: `GIF89a`,\n2972\t /// eight bytes forming a Logical Screen Descriptor the earlier checks\n2973\t /// accept, then `0x21 0xFE`. `0xFE` is `þ` in windows-1252 and not ASCII,\n2974\t /// which is the only part ordinary text lacks — and NOT at a fixed offset:\n2975\t /// when the packed byte at 10 has bit 7 set (any accented letter does it)\n2976\t /// the Global Colour Table shifts `block` from 13 to one of 19, 25, 37, 61,\n2977\t /// 109, 205, 397 or 781 — nine possible slots, of which 13 (no colour\n2978\t /// table) is one. An earlier version of this comment said \"offset 14\" flat;\n2979\t /// the correction that replaced it then dropped the no-table case, which is\n2980\t /// how the count below was wrong.\n2981\t ///\n2982\t /// So this is a measured trade against merged `main`, not a free win, and\n2983\t /// both sides are pinned here:\n2984\t ///\n2985\t /// * `main` keeps 10 corpus text negatives and junks 18 decodable GIFs\n2986\t /// whose canvas high bytes happen to be printable.\n2987\t /// * this rule keeps all 18 GIFs and junks those same 10 text files — but\n2988\t /// only above the budget. At their real sizes every build keeps them as\n2989\t /// text; it is file LENGTH that flips them, which is exactly the blind\n2990\t /// spot the corpus could not show.\n2991\t ///\n2992\t /// The 10 are the eight `gctflag_ext_fe_p*` (packed bit 7 set, `block` 19)\n2993\t /// plus `label_fe_thorn.txt` and `label_fe_then_printable_size.txt` (no\n2994\t /// colour table, `block` 13). An earlier version of this comment said\n2995\t /// eight, because the class was enumerated from the filenames a reviewer\n2996\t /// had supplied rather than from the code path — the same mistake this file\n2997\t /// spends fifty lines warning about, made while correcting it. Above the\n2998\t /// budget the shipped rule IS round 2's `true`, so the 10 named at that\n2999\t /// bullet and the 10 here are necessarily the same set.\n3000\t ///\n3001\t /// Chosen because the 18 are real artifacts that giflib and Pillow both\n3002\t /// decode, while the 8 are fixtures that only reach this state when\n3003\t /// inflated 117x. A sweep of 403,716 real files found 66 opening with GIF\n3004\t /// magic and none carrying the comment shape at all, so neither class has a\n3005\t /// measured natural base rate — which is the honest reason to write the\n3006\t /// trade down rather than claim the rule is safe.\n3007\t #[test]\n3008\t fn prose_past_the_budget_is_called_an_image_and_prose_under_it_is_not() {\n3009\t let mut prose: Vec<u8> = b\"GIF89ax\".to_vec();\n3010\t prose.push(b'\\n'); // 7: the canvas high byte round 4 keyed on\n3011\t prose.extend_from_slice(b\"yzest\");\n3012\t prose.push(b'!'); // 13\n3013\t prose.push(0xfe); // 14: windows-1252 `þ`, the shape's real cost of entry\n3014\t prose.push(b'L'); // 15: first sub-block size\n3015\t while prose.len() < GIF_PREFIX + 4096 {\n3016\t prose.extend_from_slice(\n3017\t \"Le format GIF est tres ancien et reste partout sur le web. \".as_bytes(),\n3018\t );\n3019\t }\n3020\t let p = Path::new(\"notes.txt\");\n3021\t\n3022\t let under: Vec<u8> = prose.iter().copied().take(200_000).collect();\n3023\t assert_eq!(\n3024\t sniff_bytes(&under, p, p, false).unwrap().family,\n3025\t Family::TxtProse,\n3026\t \"prose that ends before the budget must stay text\"\n3027\t );\n3028\t\n3029\t let over: Vec<u8> = prose.iter().copied().take(GIF_PREFIX).collect();\n3030\t assert_eq!(\n3031\t sniff_bytes(&over, p, p, false).unwrap().family,\n3032\t Family::Binary,\n3033\t \"a chain intact across the whole budget is called an image — if this \\\n3034\t ever needs to change, change the budget or find evidence the chain \\\n3035\t can carry, do not go back to guessing from a fixed offset\"\n3036\t );\n3037\t\n3038\t // The concrete cost, from the corpus itself: the #379 negatives built\n3039\t // to represent this exact shape are kept only by being short. This\n3040\t // reproduces `gctflag_ext_fe_p80.txt` — packed byte 0x80, so the GCT\n3041\t // moves `block` to 19 — and asserts both sides of the length boundary.\n3042\t let mut gct: Vec<u8> = b\"GIF89a\".to_vec();\n3043\t gct.extend_from_slice(b\"pros\"); // 6..10: canvas, four printable bytes\n3044\t gct.push(0x80); // 10: packed, GCT flag set by an accented letter\n3045\t gct.extend_from_slice(b\"st\"); // 11, 12\n3046\t gct.extend_from_slice(&[0, 0, 0, 0xff, 0xff, 0xff]); // 13..19: the GCT\n3047\t gct.push(0x21); // 19: extension introducer, shifted by the GCT\n3048\t gct.push(0xfe); // 20: comment label\n3049\t gct.push(b' '); // 21: first sub-block size\n3050\t while gct.len() < GIF_PREFIX + 4096 {\n3051\t gct.extend_from_slice(\"Le format GIF reste partout sur le web. \".as_bytes());\n3052\t }\n3053\t let short: Vec<u8> = gct.iter().copied().take(8_960).collect();\n3054\t assert_eq!(\n3055\t sniff_bytes(&short, p, p, false).unwrap().family,\n3056\t Family::TxtProse,\n3057\t \"at the corpus's own size this file is text on every build\"\n3058\t );\n3059\t let long: Vec<u8> = gct.iter().copied().take(GIF_PREFIX).collect();\n3060\t assert_eq!(\n3061\t sniff_bytes(&long, p, p, false).unwrap().family,\n3062\t Family::Binary,\n3063\t \"the same bytes past the budget are junked as an image — this is the \\\n3064\t cost of the rule, and merged main does NOT pay it. Keeping this \\\n3065\t assertion honest matters more than keeping it green: if a future \\\n3066\t change makes it text, re-measure the 18 GIFs on the other side\"\n3067\t );\n3068\t\n3069\t // The other two, which the first version of this test did not cover:\n3070\t // no Global Colour Table, so `block` stays at 13 and the `21 FE` pair\n3071\t // sits at 13/14 — the literal \"offset 14\" shape. Reproduces\n3072\t // `label_fe_thorn.txt`, and it is why the trade costs 10 files, not 8.\n3073\t let mut flat: Vec<u8> = b\"GIF89a fichie\".to_vec(); // 0..13, packed at 10\n3074\t assert_eq!(flat[10] & 0x80, 0, \"no colour table, so block stays 13\");\n3075\t flat.push(0x21); // 13\n3076\t flat.push(0xfe); // 14\n3077\t flat.push(b'L'); // 15\n3078\t while flat.len() < GIF_PREFIX + 4096 {\n3079\t flat.extend_from_slice(\"Le format GIF reste partout sur le web. \".as_bytes());\n3080\t }\n3081\t assert_eq!(\n3082\t sniff_bytes(&flat[..8_960], p, p, false).unwrap().family,\n3083\t Family::TxtProse,\n3084\t \"at its corpus size the no-table shape is text on every build\"\n3085\t );\n3086\t assert_eq!(\n3087\t sniff_bytes(&flat[..GIF_PREFIX], p, p, false)\n3088\t .unwrap()\n3089\t .family,\n3090\t Family::Binary,\n3091\t \"the no-table shape pays the same cost past the budget — if this is \\\n3092\t not asserted the trade gets counted from filenames again\"\n3093\t );\n3094\t }\n3095\t\n3096\t /// The other half of the same arm: prose must not reach it. `0xFE` is not\n3097\t /// ASCII, so this needs a windows-1252 byte — which `decode()` reads back\n3098\t /// as text, exactly the path that made the label-only check unsound.\n3099\t #[test]\n3100\t fn cp1252_prose_behind_a_comment_label_is_still_text() {\n3101\t let mut prose: Vec<u8> = b\"GIF89a fichie!\".to_vec();\n3102\t prose.push(0xfe);\n3103\t for _ in 0..400 {\n3104\t prose.extend_from_slice(\n3105\t \"Le format GIF est tres ancien et reste partout sur le web. \".as_bytes(),\n3106\t );\n3107\t }\n3108\t let p = Path::new(\"notes.txt\");\n3109\t let sn = sniff_bytes(&prose, p, p, false).unwrap();\n3110\t assert_eq!(\n3111\t sn.family,\n3112\t Family::TxtProse,\n3113\t \"prose was junked as {:?} through the comment arm (#379)\",\n3114\t sn.binary_kind\n3115\t );\n3116\t }\n3117\t\n3118\t /// The other half of the same trade: widening the qualifiers must not\n3119\t /// hand #379 back. The GIF block introducers are `0x21`, `0x2C` and\n3120\t /// `0x3B` — `!`, `,` and `;`, all printable — so \"walk to the first block\n3121\t /// and check the introducer\", which is the obvious rule and the one this\n3122\t /// fix was first asked for, junks ordinary sentences that happen to put\n3123\t /// punctuation at offset 13. Each fixture below does exactly that.\n3124\t ///\n3125\t /// This is the repository's \"a fix that reintroduces the very class it\n3126\t /// fixes\", caught in the same file it would have been reintroduced in.\n3127\t\n3128\t #[test]\n3129\t fn prose_that_lands_a_block_introducer_at_the_right_offset_is_still_text() {\n3130\t for (label, opener) in [\n3131\t // offset 13 is ',' -> 0x2C, an Image Descriptor introducer\n3132\t (\n3133\t \"comma\",\n3134\t \"GIF89a header, the six bytes at the front of every GIF file. \",\n3135\t ),\n3136\t // offset 13 is '!' -> 0x21, an Extension introducer\n3137\t (\n3138\t \"bang\",\n3139\t \"GIF89a images! They are still everywhere on the web today. \",\n3140\t ),\n3141\t // offset 13 is ';' -> 0x3B, the Trailer\n3142\t (\n3143\t \"semicolon\",\n3144\t \"GIF87a format; the original release, superseded two years on. \",\n3145\t ),\n3146\t ] {\n3147\t let text = opener.repeat(30);\n3148\t assert_eq!(\n3149\t text.as_bytes()[13],\n3150\t match label {\n3151\t \"comma\" => 0x2c,\n3152\t \"bang\" => 0x21,\n3153\t _ => 0x3b,\n3154\t },\n3155\t \"{label}: fixture no longer lands an introducer at offset 13, \\\n3156\t so it stopped testing anything — fix the sentence\"\n3157\t );\n3158\t let p = Path::new(\"notes.txt\");\n3159\t let sn = sniff_bytes(text.as_bytes(), p, p, false).unwrap();\n3160\t assert_eq!(\n3161\t sn.family,\n3162\t Family::TxtProse,\n3163\t \"{label}: prose was junked as {:?} — the block introducer is \\\n3164\t printable, so it cannot be the whole qualifier (#379)\",\n3165\t sn.binary_kind\n3166\t );\n3167\t }\n3168\t }\n3169\t\n3170\t /// Round 2 of #379. The fixtures above pass on which characters happen to\n3171\t /// land at offsets 15/17/19/21, not on a property the code guarantees — so\n3172\t /// they certified a claim the qualifier did not provide. These are the\n3173\t /// counterexamples that still reached `Family::Binary` with `Some(\"gif\")`\n3174\t /// after round 1, each recorded from a run against the real `sniff_bytes`.\n3175\t ///\n3176\t /// Two distinct holes: the 0x2C Image-Descriptor path, where all-ASCII\n3177\t /// input always leaves `packed & 0x80` clear so the geometry bounds are\n3178\t /// satisfiable by four u16s whose high bytes are spaces; and the 0x21\n3179\t /// Extension path, where `decode()`'s windows-1252 fallback makes\n3180\t /// 0xF9/0xFE/0xFF ordinary latin-1 letters.\n3181\t #[test]\n3182\t fn round_one_counterexamples_are_text_not_gifs() {\n3183\t let ascii: [(&str, String); 5] = [\n3184\t (\n3185\t \"image-descriptor/format\",\n3186\t \"GIF89a format,1 2 3 4 5 and the rest of this note is about the format. \"\n3187\t .repeat(30),\n3188\t ),\n3189\t (\n3190\t \"image-descriptor/header\",\n3191\t \"GIF89a header,a b c d e f g h and more prose to pad the buffer out. \".repeat(30),\n3192\t ),\n3193\t (\n3194\t \"image-descriptor/fields\",\n3195\t \"GIF89a fields,x y z w and still more prose to fill the prefix here. \".repeat(30),\n3196\t ),\n3197\t (\n3198\t \"image-descriptor/gif87a\",\n3199\t \"GIF87a format,1 2 3 4 5 and the rest of this note is about the format. \"\n3200\t .repeat(30),\n3201\t ),\n3202\t (\n3203\t \"image-descriptor/csv\",\n3204\t \"GIF89a format,1 2 3 4 5\\nrow,a,b,c,d\\nrow2,e,f,g,h\\n\".repeat(60),\n3205\t ),\n3206\t ];\n3207\t for (label, text) in &ascii {\n3208\t let p = Path::new(\"notes.txt\");\n3209\t let sn = sniff_bytes(text.as_bytes(), p, p, false).unwrap();\n3210\t assert_ne!(\n3211\t sn.family,\n3212\t Family::Binary,\n3213\t \"{label}: junked as {:?} — the LZW minimum code size byte must \\\n3214\t close the 0x2C path (#379)\",\n3215\t sn.binary_kind\n3216\t );\n3217\t }\n3218\t\n3219\t // The 0x21 Extension hole needs a byte that is not ASCII but IS a\n3220\t // latin-1 letter, so `decode()` still reads the buffer as text.\n3221\t let mut latin1: Vec<u8> = b\"GIF89a fichie!\".to_vec();\n3222\t latin1.push(0xf9);\n3223\t for _ in 0..40 {\n3224\t latin1.extend_from_slice(\n3225\t \"Le format est tres ancien, et il reste partout sur le web. \".as_bytes(),\n3226\t );\n3227\t }\n3228\t let p = Path::new(\"notes.txt\");\n3229\t let sn = sniff_bytes(&latin1, p, p, false).unwrap();\n3230\t assert_ne!(\n3231\t sn.family,\n3232\t Family::Binary,\n3233\t \"latin-1 extension label: junked as {:?} — 0xF9 is a windows-1252 \\\n3234\t letter, so the label alone cannot qualify the 0x21 path (#379)\",\n3235\t sn.binary_kind\n3236\t );\n3237\t }\n3238\t\n3239\t /// The invariant itself, walked over every row of `MAGIC_TABLE` rather than\n3240\t /// asserted about the two rows this issue happened to name: a signature\n3241\t /// made only of printable ASCII must REFUSE a prefix that is that signature\n3242\t /// followed by ordinary prose. A new row wired to `accept` fails here.\n3243\t ///\n3244\t /// The counter is not decoration — without it a table whose printable rows\n3245\t /// all disappeared would pass this test by iterating over nothing.\n3246\t ///\n3247\t /// SCOPE: `MAGIC_TABLE` only. Three signatures are matched earlier, as\n3248\t /// early returns in `sniff_bytes` — see\n3249\t /// `signatures_matched_before_the_table` below for what that leaves open.\n3250\t #[test]\n3251\t fn every_printable_signature_carries_a_qualifier() {\n3252\t let mut printable_rows = 0;\n3253\t for &(magic, kind, qualify) in MAGIC_TABLE {\n3254\t let printable = magic.iter().all(|b| b.is_ascii_graphic() || *b == b' ');\n3255\t if !printable {\n3256\t continue;\n3257\t }\n3258\t printable_rows += 1;\n3259\t let mut sentence = magic.to_vec();\n3260\t sentence.extend(\n3261\t \" is a magic number that identifies a media file format, and this \\\n3262\t sentence is about it rather than an instance of it. \"\n3263\t .repeat(30)\n3264\t .as_bytes(),\n3265\t );\n3266\t assert!(\n3267\t !qualify(&sentence),\n3268\t \"{kind}: the printable signature {:?} accepts a prefix that is \\\n3269\t that signature followed by prose — it needs a structural \\\n3270\t qualifier (#379/#380)\",\n3271\t String::from_utf8_lossy(magic)\n3272\t );\n3273\t let p = Path::new(\"notes.txt\");\n3274\t let sn = sniff_bytes(&sentence, p, p, false).unwrap();\n3275\t assert_ne!(\n3276\t sn.family,\n3277\t Family::Binary,\n3278\t \"{kind}: prose opening with {:?} was junked\",\n3279\t String::from_utf8_lossy(magic)\n3280\t );\n3281\t }\n3282\t assert!(\n3283\t printable_rows >= 7,\n3284\t \"expected the printable signatures (GIF8, BM, 8BPS, RIFF, OggS, \\\n3285\t fLaC, ID3, Kaydara FBX Binary) to be walked; saw {printable_rows} \\\n3286\t — did the table lose rows, or did this filter stop matching?\"\n3287\t );\n3288\t }\n3289\t\n3290\t /// `%PDF-`, `SQLite format 3\\0` and `PK\\x03\\x04` never reach `MAGIC_TABLE`\n3291\t /// — they are early returns in `sniff_bytes` — so the walk above says\n3292\t /// nothing about them. Two of the three are safe for the usual reason (a\n3293\t /// byte text cannot contain: the NUL after `3`, and `\\x03\\x04`), and this\n3294\t /// pins that. `%PDF-` needed its own structural qualifier (`pdf_header`,\n3295\t /// #403 — same class as #379/#380) since all five of its bytes are\n3296\t /// printable ASCII; this pins that prose opening with the bare signature\n3297\t /// now reads `TxtProse`, not `Pdf`.\n3298\t #[test]\n3299\t fn signatures_matched_before_the_table() {\n3300\t for (label, opener, want) in [\n3301\t (\n3302\t \"sqlite\",\n3303\t \"SQLite format 3 is the string at the start of every database file. \",\n3304\t Family::TxtProse,\n3305\t ),\n3306\t (\n3307\t \"zip\",\n3308\t \"PK is the local file header signature of the ZIP format. \",\n3309\t Family::TxtProse,\n3310\t ),\n3311\t (\n3312\t \"pdf\",\n3313\t \"%PDF- is the five byte header every PDF file begins with. \",\n3314\t Family::TxtProse,\n3315\t ),\n3316\t ] {\n3317\t let text = opener.repeat(30);\n3318\t let p = Path::new(\"notes.txt\");\n3319\t let sn = sniff_bytes(text.as_bytes(), p, p, false).unwrap();\n3320\t assert_eq!(\n3321\t sn.family, want,\n3322\t \"{label}: prose opening with a pre-table signature classified \\\n3323\t {:?}/{:?}\",\n3324\t sn.family, sn.binary_kind\n3325\t );\n3326\t }\n3327\t }\n3328\t\n3329\t /// The positive control `every_printable_signature_carries_a_qualifier`\n3330\t /// cannot provide for `%PDF-`, since it walks `MAGIC_TABLE` only: a real\n3331\t /// PDF header must still classify `Family::Pdf`, or `pdf_header` is not a\n3332\t /// qualifier but a second way to break the format.\n3333\t #[test]\n3334\t fn a_real_pdf_header_still_classifies_as_pdf() {\n3335\t let headers: [&[u8]; 3] = [\n3336\t b\"%PDF-1.7\\n%\\xE2\\xE3\\xCF\\xD3\\n1 0 obj\\n\",\n3337\t b\"%PDF-1.4\\r\\n1 0 obj\\n\",\n3338\t b\"%PDF-2.0\\r%comment\\r\",\n3339\t ];\n3340\t for header in headers {\n3341\t let p = Path::new(\"doc.pdf\");\n3342\t let sn = sniff_bytes(header, p, p, false).unwrap();\n3343\t assert_eq!(\n3344\t sn.family,\n3345\t Family::Pdf,\n3346\t \"real PDF header {header:?} classified {:?}/{:?} — pdf_header \\\n3347\t rejected a spec-conformant file\",\n3348\t sn.family,\n3349\t sn.binary_kind\n3350\t );\n3351\t }\n3352\t }\n3353\t}\n3354\t\n3355\t#[cfg(test)]\n3356\tmod tests {\n3357\t use super::*;\n3358\t\n3359\t fn classify(s: &str) -> Family {\n3360\t let lines: Vec<&str> = s.lines().filter(|l| !l.trim().is_empty()).collect();\n3361\t classify_text(s, &lines)\n3362\t }\n3363\t\n3364\t #[test]\n3365\t fn sniff_families() {\n3366\t assert_eq!(classify(\"{\\\"a\\\":1}\\n{\\\"a\\\":2}\\n{\\\"a\\\":3}\\n\"), Family::Jsonl);\n3367\t assert_eq!(\n3368\t classify(\"{\\n \\\"a\\\": 1,\\n \\\"b\\\": [1,2]\\n}\\n\"),\n3369\t Family::Json\n3370\t );\n3371\t assert_eq!(\n3372\t classify(\"<!DOCTYPE html>\\n<html><head></head></html>\"),\n3373\t Family::Html\n3374\t );\n3375\t assert_eq!(\n3376\t classify(\"<?xml version='1.0'?>\\n<r><a>1</a></r>\"),\n3377\t Family::Xml\n3378\t );\n3379\t assert_eq!(classify(\"a,b,c\\n1,2,3\\n4,5,6\\n\"), Family::Csv);\n3380\t assert_eq!(\n3381\t classify(\"CREATE TABLE `t` (\\n `a` int\\n);\\nINSERT INTO `t` VALUES (1);\\n\"),\n3382\t Family::SqlDump\n3383\t );\n3384\t assert_eq!(\n3385\t classify(\"key: value\\nother: 1\\nnested:\\n a: 2\\n\"),\n3386\t Family::Yaml\n3387\t );\n3388\t }\n3389\t\n3390\t /// `[package]`-style openers are TOML/INI table headers, not JSON\n3391\t /// arrays. Before the guard, Cargo.toml sniffed as Json, the JSON\n3392\t /// extractor junked it, and cratecite's crate table stayed empty on\n3393\t /// every real repository (its dst must be an INDEXED Cargo.toml).\n3394\t #[test]\n3395\t fn toml_table_header_is_not_json() {\n3396\t let cargo = \"[package]\\nname = \\\"xerj-fts\\\"\\nversion = \\\"0.1.0\\\"\\nedition = \\\"2021\\\"\\n\\n\\\n3397\t [dependencies]\\nserde = { version = \\\"1\\\", features = [\\\"derive\\\"] }\\n\\\n3398\t serde_json = \\\"1\\\"\\nanyhow = \\\"1\\\"\\n\";\n3399\t assert_eq!(classify(cargo), Family::TxtLines);\n3400\t let ini = \"[Unit]\\nDescription=demo\\nAfter=network.target\\n\\n\\\n3401\t [Service]\\nExecStart=/bin/true\\nRestart=always\\n\\n\\\n3402\t [Install]\\nWantedBy=multi-user.target\\n\";\n3403\t assert_eq!(classify(ini), Family::TxtLines);\n3404\t // …while real JSON arrays keep their family.\n3405\t assert_eq!(classify(\"[1, 2, 3]\\n\"), Family::Json);\n3406\t assert_eq!(\n3407\t classify(\"[\\n {\\\"a\\\": 1},\\n {\\\"a\\\": 2}\\n]\\n\"),\n3408\t Family::Json\n3409\t );\n3410\t }\n3411\t\n3412\t #[test]\n3413\t fn csv_dialect_semicolon_decimal_comma() {\n3414\t let lines = vec![\n3415\t \"geraet;zeitpunkt;temperatur_c\",\n3416\t \"dev-1;2026-03-09T02:09:26Z;50,6\",\n3417\t \"dev-2;2026-03-10T19:10:36Z;57,0\",\n3418\t ];\n3419\t let d = sniff_csv_dialect(&lines).unwrap();\n3420\t assert_eq!(d.delim, b';');\n3421\t assert!(d.has_header);\n3422\t assert!(d.decimal_comma);\n3423\t }\n3424\t}\n3425\t\n3426\t#[cfg(test)]\n3427\tmod text_family_tests {\n3428\t use super::*;\n3429\t\n3430\t fn kind(text: &str) -> Family {\n3431\t let nonblank: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();\n3432\t txt_kind(&nonblank)\n3433\t }\n3434\t\n3435\t /// Full text classifier — access logs and syslog are claimed by the `Logs`\n3436\t /// family before `txt_kind` is ever consulted, so they must be asserted\n3437\t /// through the real entry point rather than against `txt_kind` directly.\n3438\t fn classify_full(text: &str) -> Family {\n3439\t let nonblank: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();\n3440\t classify_text(text, &nonblank)\n3441\t }\n3442\t\n3443\t /// Regression: a markdown document with `## Headings` averages ~50 chars\n3444\t /// over 7 lines, which the length-only rule classified as TxtLines — the\n3445\t /// same corpus's 5-line runbook (avg 59) went to TxtProse. Same content\n3446\t /// type, two families, two field names, incomparable BM25 statistics.\n3447\t #[test]\n3448\t fn markdown_with_headings_is_prose() {\n3449\t let md = \"# Postmortem: checkout outage, 14 June 2026\\n\\n\\\n3450\t ## Impact\\n\\\n3451\t Checkout was unavailable for 51 minutes.\\n\\n\\\n3452\t ## Root cause\\n\\\n3453\t The payment gateway TLS certificate expired.\\n\\n\\\n3454\t ## Resolution\\n\\\n3455\t We reloaded the service and added an alert.\\n\";\n3456\t assert_eq!(kind(md), Family::TxtProse);\n3457\t }\n3458\t\n3459\t #[test]\n3460\t fn short_runbook_is_still_prose() {\n3461\t let md = \"# Database runbook\\n\\n\\\n3462\t ## Failover\\n\\\n3463\t Promote the standby with pg_ctl promote.\\n\\n\\\n3464\t ## Pool exhaustion\\n\\\n3465\t Symptoms are rising p99 and pool errors in the logs.\\n\";\n3466\t assert_eq!(kind(md), Family::TxtProse);\n3467\t }\n3468\t\n3469\t /// #551: a markdown/prose file that opens with a `---` frontmatter block was\n3470\t /// sniffed as YAML — the YAML extractor keeps the frontmatter mapping and the\n3471\t /// first paragraph and discards the body (silent data loss on the dominant\n3472\t /// markdown convention: Jekyll/Hugo/Obsidian/Docusaurus/MkDocs/Astro, and\n3473\t /// Claude Code skill files). With the closing-`---` lookahead the file is\n3474\t /// classified by its body — identically to a frontmatter-less twin — so the\n3475\t /// whole document is indexed.\n3476\t #[test]\n3477\t fn markdown_frontmatter_is_classified_by_its_body_not_yaml() {\n3478\t let with_frontmatter = \"---\\n\\\n3479\t title: Widget outage\\n\\\n3480\t date: 2026-01-15\\n\\\n3481\t tags: [widget, outage]\\n\\\n3482\t ---\\n\\n\\\n3483\t # Outage postmortem\\n\\n\\\n3484\t The sprocket pool was exhausted.\\n\\n\\\n3485\t ## Resolution\\n\\\n3486\t Raised the sprocket pool size from 4 to 16.\\n\";\n3487\t // Byte-identical body, no frontmatter.\n3488\t let no_frontmatter = \"# Outage postmortem\\n\\n\\\n3489\t The sprocket pool was exhausted.\\n\\n\\\n3490\t ## Resolution\\n\\\n3491\t Raised the sprocket pool size from 4 to 16.\\n\";\n3492\t let twin = classify_full(no_frontmatter);\n3493\t assert_ne!(\n3494\t twin,\n3495\t Family::Yaml,\n3496\t \"sanity: the body itself is prose, not YAML\"\n3497\t );\n3498\t assert_eq!(\n3499\t classify_full(with_frontmatter),\n3500\t twin,\n3501\t \"markdown frontmatter must be classified by its body, identical to the \\\n3502\t frontmatter-less twin, not routed to the YAML extractor (#551)\"\n3503\t );\n3504\t }\n3505\t\n3506\t /// #587 (item 1): the #551 frontmatter lookahead classified the body with\n3507\t /// `txt_kind` only, so a frontmatter-over-CSV/JSON body was mislabelled a\n3508\t /// prose family while its frontmatter-less twin was `Csv`/`Jsonl`. Running\n3509\t /// the body through the structured branches makes the family match the twin\n3510\t /// for a structured body (a prose body still classifies as prose — the #551\n3511\t /// test above).\n3512\t #[test]\n3513\t fn frontmatter_over_a_structured_body_is_classified_by_that_body() {\n3514\t // CSV body under YAML frontmatter.\n3515\t let csv_body = \"name,role,team\\n\\\n3516\t alice,eng,core\\n\\\n3517\t bob,design,platform\\n\\\n3518\t carol,pm,growth\\n\";\n3519\t let csv_with_frontmatter =\n3520\t format!(\"---\\ntitle: Team roster\\nowner: ops\\n---\\n\\n{csv_body}\");\n3521\t let csv_twin = classify_full(csv_body);\n3522\t assert_eq!(csv_twin, Family::Csv, \"sanity: the bare body is CSV\");\n3523\t assert_eq!(\n3524\t classify_full(&csv_with_frontmatter),\n3525\t csv_twin,\n3526\t \"a frontmatter-over-CSV body must be classified by its structured family \\\n3527\t (CSV), identical to the frontmatter-less twin (#587)\"\n3528\t );\n3529\t\n3530\t // JSONL body under YAML frontmatter.\n3531\t let json_body = \"{\\\"id\\\":1,\\\"name\\\":\\\"a\\\"}\\n{\\\"id\\\":2,\\\"name\\\":\\\"b\\\"}\\n\";\n3532\t let json_with_frontmatter = format!(\"---\\nsource: export\\ncount: 2\\n---\\n\\n{json_body}\");\n3533\t let json_twin = classify_full(json_body);\n3534\t assert_eq!(json_twin, Family::Jsonl, \"sanity: the bare body is JSONL\");\n3535\t assert_eq!(\n3536\t classify_full(&json_with_frontmatter),\n3537\t json_twin,\n3538\t \"a frontmatter-over-JSON body must be classified by its structured family \\\n3539\t (JSONL), identical to the frontmatter-less twin (#587)\"\n3540\t );\n3541\t }\n3542\t\n3543\t /// #551 guardrail: the frontmatter lookahead must not reclassify real YAML.\n3544\t /// A single document (leading `---` marker, no prose body) and a\n3545\t /// multi-document stream (the body after the first `---` separator is itself\n3546\t /// YAML) both stay `Yaml`.\n3547\t #[test]\n3548\t fn yaml_documents_are_unaffected_by_the_frontmatter_lookahead() {\n3549\t let pure = \"---\\n\\\n3550\t name: widget-service\\n\\\n3551\t replicas: 3\\n\\\n3552\t ports:\\n\\\n3553\t \\x20 - 8080\\n\\\n3554\t \\x20 - 9090\\n\\\n3555\t env:\\n\\\n3556\t \\x20 LOG_LEVEL: info\\n\";\n3557\t assert_eq!(classify_full(pure), Family::Yaml);\n3558\t\n3559\t let multi = \"---\\n\\\n3560\t name: first\\n\\\n3561\t value: 1\\n\\\n3562\t ---\\n\\\n3563\t name: second\\n\\\n3564\t value: 2\\n\\\n3565\t kind: config\\n\";\n3566\t assert_eq!(classify_full(multi), Family::Yaml);\n3567\t }\n3568\t\n3569\t /// #587 (item 2): the lookahead's only test for \"is this body YAML?\" was\n3570\t /// the *line shape* of the body — majority `key:` / `- item`. A genuine\n3571\t /// multi-document YAML stream whose second document is dominated by a\n3572\t /// block scalar, comments and continuation lines fails that test (those\n3573\t /// lines are not `key:`-shaped), so the whole stream was re-classified as\n3574\t /// prose and lost its per-document key structure. `parses_as_yaml_stream`\n3575\t /// separates the two: this body parses as a YAML mapping, whereas a\n3576\t /// markdown body halts `serde_yaml`'s iterator.\n3577\t #[test]\n3578\t fn multi_document_yaml_with_a_prose_heavy_document_stays_yaml() {\n3579\t let multi = \"---\\n\\\n3580\t name: release-notes\\n\\\n3581\t version: 2.4.0\\n\\\n3582\t ---\\n\\\n3583\t # notes for the operators\\n\\\n3584\t summary: |\\n\\\n3585\t \\x20 The sprocket pool was exhausted during the Tuesday deploy.\\n\\\n3586\t \\x20 Raising the pool size from 4 to 16 restored throughput.\\n\\\n3587\t \\x20 Watch the queue depth dashboard for the next 24 hours.\\n\\\n3588\t \\x20 A follow-up ticket tracks the autoscaler change.\\n\";\n3589\t // Guard the premise: the body really is majority non-`key:`-shaped, so\n3590\t // the line-shape tier alone routes it away from YAML.\n3591\t let body: Vec<&str> = multi\n3592\t .lines()\n3593\t .filter(|l| !l.trim().is_empty())\n3594\t .skip(4)\n3595\t .collect();\n3596\t assert!(\n3597\t yaml_like_count(&body) * 2 < body.len(),\n3598\t \"premise: the prose-heavy document is not majority YAML-shaped\"\n3599\t );\n3600\t assert_eq!(\n3601\t classify_full(multi),\n3602\t Family::Yaml,\n3603\t \"a multi-document YAML stream whose later document is prose-heavy must \\\n3604\t stay YAML — it parses as a YAML stream, unlike a markdown body (#587)\"\n3605\t );\n3606\t }\n3607\t\n3608\t /// #587 (item 3): the lookahead required `body.len() >= 2`, so a\n3609\t /// frontmatter file whose body is a single non-blank line still went to\n3610\t /// the YAML extractor, which keeps the frontmatter mapping and discards\n3611\t /// that line — the #551 loss, on the smallest possible file.\n3612\t #[test]\n3613\t fn frontmatter_over_a_single_prose_line_is_classified_by_that_line() {\n3614\t let note = \"---\\n\\\n3615\t title: Standup note\\n\\\n3616\t date: 2026-02-03\\n\\\n3617\t ---\\n\\n\\\n3618\t Deploy is blocked on the sprocket pool change.\\n\";\n3619\t assert_eq!(\n3620\t classify_full(note),\n3621\t Family::TxtProse,\n3622\t \"a one-line prose body under frontmatter must be classified by that \\\n3623\t line, not handed to the YAML extractor that drops it (#587)\"\n3624\t );\n3625\t\n3626\t // The other side of the same boundary: a one-line *YAML* body after a\n3627\t // document separator is still YAML.\n3628\t let yaml = \"---\\n\\\n3629\t name: first\\n\\\n3630\t ---\\n\\\n3631\t name: second\\n\";\n3632\t assert_eq!(classify_full(yaml), Family::Yaml);\n3633\t }\n3634\t\n3635\t /// Guardrail for the parse tier added in #587 item 2: it must not drag\n3636\t /// ordinary markdown bodies back into YAML. Each of these is a real\n3637\t /// markdown shape whose body is majority non-`key:`-shaped, so each one\n3638\t /// reaches the parse; each must still come out prose.\n3639\t #[test]\n3640\t fn markdown_bodies_are_not_rescued_into_yaml_by_the_parse_tier() {\n3641\t let bodies = [\n3642\t // Task list — `- [ ] x` is invalid YAML (flow sequence then scalar).\n3643\t \"- [ ] drain the pool\\n- [x] raise the limit\\n- [ ] verify p99\\n\",\n3644\t // Fenced code block.\n3645\t \"# How to\\nRun this:\\n```sh\\nxerj autoindex .\\n```\\nThen read the catalog.\\n\",\n3646\t // Table.\n3647\t \"| stage | owner |\\n|---|---|\\n| build | core |\\n| ship | ops |\\n\",\n3648\t // Headings and paragraphs.\n3649\t \"# Title\\n## Section one\\nSome text about the thing.\\n## Section two\\nMore text.\\n\",\n3650\t // Emphasis opener — `*` is the YAML alias indicator.\n3651\t \"**Note**: the pool is small.\\nRaise it before the next deploy.\\n\",\n3652\t ];\n3653\t for body in bodies {\n3654\t let with_frontmatter = format!(\"---\\ntitle: Note\\nowner: ops\\n---\\n\\n{body}\");\n3655\t assert_ne!(\n3656\t classify_full(&with_frontmatter),\n3657\t Family::Yaml,\n3658\t \"markdown body must not be classified YAML by the parse tier: {body:?}\"\n3659\t );\n3660\t }\n3661\t }\n3662\t\n3663\t /// The record-stream side must be unaffected — these are what TxtLines is for.\n3664\t #[test]\n3665\t fn access_logs_stay_line_records() {\n3666\t let log = (0..20)\n3667\t .map(|i| format!(\n3668\t \"10.0.0.{i} - - [01/Jun/2026:10:00:00 +0000] \\\"GET /api/checkout HTTP/1.1\\\" 200 {i}00 \\\"-\\\" \\\"Mozilla/5.0\\\"\"\n3669\t ))\n3670\t .collect::<Vec<_>>()\n3671\t .join(\"\\n\");\n3672\t assert_eq!(classify_full(&log), Family::Logs);\n3673\t }\n3674\t\n3675\t #[test]\n3676\t fn syslog_stays_line_records() {\n3677\t // One message in five ends with a period — well under the threshold.\n3678\t let msgs = [\n3679\t \"sshd[123]: Accepted publickey for deploy from 10.0.3.4 port 55212\",\n3680\t \"kernel: Out of memory: Killed process 8123 (java)\",\n3681\t \"cron[99]: session opened for user root by (uid=0)\",\n3682\t \"postfix[7]: connection timed out while talking to upstream\",\n3683\t \"systemd[1]: Started Daily apt download activities.\",\n3684\t ];\n3685\t let log = (0..6)\n3686\t .flat_map(|_| msgs.iter().map(|m| format!(\"Jun 1 10:00:00 host1 {m}\")))\n3687\t .collect::<Vec<_>>()\n3688\t .join(\"\\n\");\n3689\t assert_eq!(classify_full(&log), Family::Logs);\n3690\t }\n3691\t\n3692\t #[test]\n3693\t fn source_code_stays_line_records() {\n3694\t let code = \"pub struct Pool { max: usize, in_use: usize }\\n\\\n3695\t impl Pool {\\n\\\n3696\t pub fn acquire(&mut self) -> Result<Conn, PoolError> {\\n\\\n3697\t if self.in_use >= self.max { return Err(PoolError::Exhausted); }\\n\\\n3698\t self.in_use += 1;\\n\\\n3699\t Ok(Conn::new())\\n\\\n3700\t }\\n\\\n3701\t }\\n\\\n3702\t fn helper() -> u32 { 42 }\\n\\\n3703\t const LIMIT: usize = 10;\\n\";\n3704\t assert_eq!(kind(code), Family::TxtLines);\n3705\t }\n3706\t\n3707\t #[test]\n3708\t fn long_lines_are_prose_regardless_of_punctuation() {\n3709\t let t = (0..10)\n3710\t .map(|_| \"x\".repeat(120))\n3711\t .collect::<Vec<_>>()\n3712\t .join(\"\\n\");\n3713\t assert_eq!(kind(&t), Family::TxtProse);\n3714\t }\n3715\t\n3716\t /// Regression: a markdown checklist (`- [ ]` task items under a heading)\n3717\t /// used to sniff as YAML — 2 of 3 nonblank lines start with `- ` — and\n3718\t /// the YAML extractor then junk-filed it (and, before the yaml_x\n3719\t /// non-progress fix, hung on it). Checkbox items are invalid YAML and\n3720\t /// must not count as YAML evidence.\n3721\t #[test]\n3722\t fn markdown_checklist_is_prose_not_yaml() {\n3723\t let md = \"# Launch checklist\\n\\n\\\n3724\t - [ ] Sign off the [business plan](01-business-plan.md)\\n\\\n3725\t - [x] Close out permits\\n\\\n3726\t - [ ] Dry run: two full batches back to back\\n\";\n3727\t assert_eq!(classify_full(md), Family::TxtProse);\n3728\t // A real YAML list is still YAML.\n3729\t let yaml = \"- alpha\\n- beta\\n- gamma\\n\";\n3730\t assert_eq!(classify_full(yaml), Family::Yaml);\n3731\t }\n3732\t\n3733\t /// Regression (second-brain demo vault, live 2026-07-30): a markdown\n3734\t /// note hard-wrapped at ~75 columns averages < 60 chars/line and ends\n3735\t /// most lines mid-sentence, so it scored below the 0.40 sentence ratio\n3736\t /// and landed in TxtLines — silently losing its title, its `s0` section\n3737\t /// anchor, and its wikilink detection (8 of 39 vault files). A file that\n3738\t /// opens with an ATX heading and shows markdown link syntax (or some\n3739\t /// terminal punctuation) is markdown prose.\n3740\t #[test]\n3741\t fn hard_wrapped_markdown_note_is_prose_not_lines() {\n3742\t let md = \"# Hydration\\n\\n\\\n3743\t Hydration is water as a percentage of flour weight, the core of\\n\\\n3744\t [[baker-percentages]]. 65% is a tight sandwich loaf; 75-80% is where open\\n\\\n3745\t [[crumb-structure]] lives; past 85% the dough demands real skill.\\n\\n\\\n3746\t Higher hydration = looser dough, longer bulk, bigger holes. It is the single\\n\\\n3747\t most consequential number in the formula.\\n\";\n3748\t assert_eq!(classify_full(md), Family::TxtProse);\n3749\t // No heading opener → the rescue must not fire: a Python file whose\n3750\t // comment banner starts mid-file stays wherever the base heuristics\n3751\t // put it, and a shebang is not a heading.\n3752\t let sh = \"#!/usr/bin/env bash\\n\\\n3753\t set -euo pipefail\\n\\\n3754\t for f in a b c; do\\n\\\n3755\t echo one\\n\\\n3756\t echo two\\n\\\n3757\t echo three\\n\\\n3758\t done\\n\";\n3759\t assert_eq!(classify_full(sh), Family::TxtLines);\n3760\t }\n3761\t}\n3762\t\n3763\t#[cfg(test)]\n3764\tmod mail_and_archive_sniff_tests {\n3765\t use super::*;\n3766\t use std::path::Path;\n3767\t\n3768\t fn sniffed(bytes: &[u8], name: &str, gzip: bool) -> Sniffed {\n3769\t sniff_bytes(bytes, Path::new(name), Path::new(name), gzip).unwrap()\n3770\t }\n3771\t\n3772\t fn family(text: &str, name: &str) -> Family {\n3773\t sniffed(text.as_bytes(), name, false).family\n3774\t }\n3775\t\n3776\t const SEP: &str = \"From 1787654321098765432@xxx Tue Nov 14 22:13:20 +0000 2023\";\n3777\t const HEADERS: &str = \"From: Dana Klein <[email protected]>\\nTo: [email protected]\\n\\\n3778\t Subject: Term sheet\\nDate: Tue, 14 Nov 2023 22:13:20 +0000\\n\\\n3779\t Message-ID: <[email protected]>\\n\\nbody text\\n\";\n3780\t\n3781\t /// A mailbox is recognised by what is IN it. Thunderbird folders have no\n3782\t /// extension, Apple Mail's file is literally `mbox`, and Takeout's has\n3783\t /// spaces in its name — none of which may matter.\n3784\t #[test]\n3785\t fn a_mailbox_is_detected_by_content_under_any_name() {\n3786\t let lf = format!(\"{SEP}\\n{HEADERS}\");\n3787\t let crlf = lf.replace('\\n', \"\\r\\n\");\n3788\t for name in [\n3789\t \"Inbox\",\n3790\t \"mbox\",\n3791\t \"All mail Including Spam and Trash.mbox\",\n3792\t \"export.txt\",\n3793\t \"x.eml\",\n3794\t ] {\n3795\t assert_eq!(family(&lf, name), Family::Mbox, \"LF {name}\");\n3796\t assert_eq!(family(&crlf, name), Family::Mbox, \"CRLF {name}\");\n3797\t }\n3798\t // Blank lines before the first separator are tolerated.\n3799\t assert_eq!(family(&format!(\"\\n\\n{lf}\"), \"Inbox\"), Family::Mbox);\n3800\t // So is a UTF-8 byte-order mark (review finding on PR #949: such a\n3801\t // file was junked as a \"yaml candidate\" and none of its mail indexed).\n3802\t assert_eq!(family(&format!(\"\\u{feff}{lf}\"), \"bom.mbox\"), Family::Mbox);\n3803\t assert_eq!(family(&format!(\"\\u{feff}{crlf}\"), \"bom.mbox\"), Family::Mbox);\n3804\t // Thunderbird and mutt separators.\n3805\t for sep in [\n3806\t \"From - Tue Oct 10 12:34:56 2023\",\n3807\t \"From MAILER-DAEMON Fri Jul 8 12:08:34 2011\",\n3808\t ] {\n3809\t assert_eq!(\n3810\t family(&format!(\"{sep}\\n{HEADERS}\"), \"Sent\"),\n3811\t Family::Mbox,\n3812\t \"{sep}\"\n3813\t );\n3814\t }\n3815\t }\n3816\t\n3817\t /// …and the extension alone proves nothing.\n3818\t #[test]\n3819\t fn the_mbox_extension_is_not_evidence() {\n3820\t let prose = \"Notes about the mbox format.\\n\\nIt is older than MIME and it shows.\\n\";\n3821\t assert_ne!(family(prose, \"notes.mbox\"), Family::Mbox);\n3822\t // Prose that opens with the word \"From\" and even looks a bit like mail.\n3823\t let essay = format!(\"From what I understand, the deal closes Monday.\\n{HEADERS}\");\n3824\t assert_ne!(family(&essay, \"essay.mbox\"), Family::Mbox);\n3825\t // A real separator followed by something that is not a message.\n3826\t let log = format!(\"{SEP}\\nname: app\\nversion: 2\\nport: 8080\\n\");\n3827\t assert_ne!(family(&log, \"weird.mbox\"), Family::Mbox);\n3828\t // A QUOTED separator is body text of some other file, not a mailbox.\n3829\t assert_ne!(\n3830\t family(&format!(\">{SEP}\\n{HEADERS}\"), \"reply.mbox\"),\n3831\t Family::Mbox\n3832\t );\n3833\t // A single message with no separator stays an email.\n3834\t assert_eq!(family(HEADERS, \"one.mbox\"), Family::Eml);\n3835\t }\n3836\t\n3837\t /// The sniffer only ever sees a PREFIX of the file, cut at a byte count, so\n3838\t /// the cut lands inside multi-byte characters as a matter of course. Every\n3839\t /// prefix length of a mailbox full of them: no panic (panic = abort), and\n3840\t /// once the headers are in view the answer is stable.\n3841\t #[test]\n3842\t fn a_prefix_cut_inside_a_multibyte_character_never_panics() {\n3843\t let mbox = format!(\n3844\t \"{SEP}\\nFrom: 山田 太郎 <[email protected]>\\nTo: محمد علي <[email protected]>\\n\\\n3845\t Subject: 設計書 — Überweisung\\nDate: Tue, 14 Nov 2023 22:13:20 +0000\\n\\\n3846\t Message-ID: <[email protected]>\\n\\nمرحبا بالعالم 設計書 Grüße\\n\"\n3847\t );\n3848\t let bytes = mbox.as_bytes();\n3849\t let headers_end = mbox.find(\"\\n\\n\").unwrap();\n3850\t for cut in 0..=bytes.len() {\n3851\t let got = sniffed(&bytes[..cut], \"Inbox\", false).family;\n3852\t if cut > headers_end {\n3853\t assert_eq!(got, Family::Mbox, \"cut={cut}\");\n3854\t }\n3855\t }\n3856\t }\n3857\t\n3858\t fn tar_header(name: &str) -> Vec<u8> {\n3859\t let mut h = vec![0u8; 512];\n3860\t h[..name.len()].copy_from_slice(name.as_bytes());\n3861\t h[100..107].copy_from_slice(b\"0000644\");\n3862\t h[257..263].copy_from_slice(b\"ustar\\0\");\n3863\t h[263..265].copy_from_slice(b\"00\");\n3864\t h[148..156].copy_from_slice(b\" \");\n3865\t let sum: u32 = h.iter().map(|b| u32::from(*b)).sum();\n3866\t h[148..156].copy_from_slice(format!(\"{sum:06o}\\0 \").as_bytes());\n3867\t h\n3868\t }\n3869\t\n3870\t /// Archives are NAMED so the run can say what to do about them. A Takeout\n3871\t /// download is one `.zip` or `.tgz`; \"binary content (unknown)\" tells its\n3872\t /// owner nothing.\n3873\t #[test]\n3874\t fn archives_are_named_and_told_apart_from_text_that_mentions_them() {\n3875\t let tar = sniffed(\n3876\t &tar_header(\"Takeout/Mail/All mail.mbox\"),\n3877\t \"takeout-001.tar\",\n3878\t false,\n3879\t );\n3880\t assert_eq!(tar.family, Family::Binary);\n3881\t assert_eq!(tar.binary_kind.as_deref(), Some(\"tar\"));\n3882\t // The same 512 bytes reached through gzip (a .tgz): still a tar.\n3883\t let tgz = sniffed(&tar_header(\"Takeout/x\"), \"takeout-001.tgz\", true);\n3884\t assert_eq!(tgz.binary_kind.as_deref(), Some(\"tar\"));\n3885\t // `ustar` at offset 257 of a TEXT file, with no valid checksum: not a tar.\n3886\t let mut text = vec![b'a'; 512];\n3887\t text[257..262].copy_from_slice(b\"ustar\");\n3888\t assert_ne!(\n3889\t sniffed(&text, \"essay.txt\", false).binary_kind.as_deref(),\n3890\t Some(\"tar\")\n3891\t );\n3892\t // Shorter than one header block: `get(..512)` is None, not a panic.\n3893\t assert_ne!(\n3894\t sniffed(&tar_header(\"x\")[..300], \"cut.tar\", false)\n3895\t .binary_kind\n3896\t .as_deref(),\n3897\t Some(\"tar\")\n3898\t );\n3899\t\n3900\t for (magic, kind) in [\n3901\t (&b\"7z\\xbc\\xaf\\x27\\x1c\\x00\\x04rest\"[..], \"7z\"),\n3902\t (&b\"Rar!\\x1a\\x07\\x01\\x00rest\"[..], \"rar\"),\n3903\t (&b\"\\xfd7zXZ\\x00\\x00\\x04rest\"[..], \"xz\"),\n3904\t ] {\n3905\t let s = sniffed(magic, \"a.bin\", false);\n3906\t assert_eq!(s.family, Family::Binary, \"{kind}\");\n3907\t assert_eq!(s.binary_kind.as_deref(), Some(kind));\n3908\t }\n3909\t }\n3910\t\n3911\t #[test]\n3912\t fn archive_advice_names_the_command_for_the_kind_in_hand() {\n3913\t let advice = |kind: &str, gz: bool| archive_advice(kind, gz).unwrap_or_default();\n3914\t for (kind, gz, command) in [\n3915\t (\"zip\", false, \"unzip <file>\"),\n3916\t (\"tar\", false, \"tar -xf <file>\"),\n3917\t (\"tar\", true, \"tar -xzf <file>\"),\n3918\t (\"7z\", false, \"7z x <file>\"),\n3919\t (\"rar\", false, \"unrar x <file>\"),\n3920\t (\"xz\", false, \"xz -dk <file>\"),\n3921\t ] {\n3922\t let text = advice(kind, gz);\n3923\t assert!(text.contains(\"extract it first\"), \"{kind}: {text}\");\n3924\t assert!(text.contains(command), \"{kind}: {text}\");\n3925\t assert!(text.contains(\"does not open archives\"), \"{kind}: {text}\");\n3926\t }\n3927\t // Not an archive: no advice, the ordinary \"binary content (…)\" stands.\n3928\t for kind in [\"png\", \"pdf\", \"unknown\", \"\", \"設計\"] {\n3929\t assert_eq!(archive_advice(kind, false), None, \"{kind}\");\n3930\t }\n3931\t }\n3932\t}\n3933\t"}]},"uuid":"29ef4441-a1af-42d8-bf5e-92125f186418","timestamp":"2026-10-01T15:38:14.017Z","sourceToolAssistantUUID":"d9049ad6-ca1a-4171-85eb-0212f7fa8d50","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"108e7723-05ff-47c4-ac31-5465d0342c47","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_beccf6e3ba364eb08f37ab1c","type":"tool_result","content":"src/catalog.rs\nsrc/cli.rs\nsrc/content.rs\nsrc/correlate.rs\nsrc/dataset.rs\nsrc/def.rs\nsrc/detect/cratecite.rs\nsrc/detect/e2e.rs\nsrc/detect/e2e_mail.rs\nsrc/detect/emailthread.rs\nsrc/detect/href.rs\nsrc/detect/mdlink.rs\nsrc/detect/mod.rs\nsrc/detect/pathcite.rs\nsrc/detect/samedir.rs\nsrc/detect/sequence.rs\nsrc/detect/sharedterm.rs\nsrc/detect/wikilink.rs\nsrc/esclient.rs\nsrc/estimate.rs\nsrc/extract/bvh.rs\nsrc/extract/code.rs\nsrc/extract/csv_x.rs\nsrc/extract/docx.rs\nsrc/extract/eml.rs\nsrc/extract/html.rs\nsrc/extract/json.rs\nsrc/extract/jsonl.rs\nsrc/extract/logs.rs\nsrc/extract/mbox.rs\nsrc/extract/mod.rs\nsrc/extract/pdf.rs\nsrc/extract/sqldump.rs\nsrc/extract/sqlite_x.rs\nsrc/extract/txt.rs\nsrc/extract/unity.rs\nsrc/extract/xml_x.rs\nsrc/extract/yaml_x.rs\nsrc/failure_resume_http_tests.rs\nsrc/feedback.rs\nsrc/gain.rs\nsrc/gate.rs\nsrc/generation_catalog.rs\nsrc/generation_catalog_http_tests.rs\nsrc/harvest/httpget.rs\nsrc/harvest/identity.rs\nsrc/harvest/mod.rs\nsrc/harvest/normalize.rs\nsrc/harvest/pack.rs\nsrc/harvest/recipe.rs\nsrc/harvest/sign.rs\nsrc/harvest/source.rs\nsrc/harvest/suggest.rs\nsrc/ids.rs\nsrc/ignore_rules.rs\nsrc/incremental_reconcile_http_tests.rs\nsrc/infer/dates.rs\nsrc/infer/mod.rs\nsrc/init.rs\nsrc/label.rs\nsrc/label_http_tests.rs\nsrc/lib.rs\nsrc/objsource.rs\nsrc/objsource_minio_tests.rs\nsrc/objsource_s3_tests.rs\nsrc/objwatch/cost.rs\nsrc/objwatch/journal.rs\nsrc/objwatch/mod.rs\nsrc/objwatch/run.rs\nsrc/objwatch/s3.rs\nsrc/objwatch/tests.rs\nsrc/order.rs\nsrc/pool.rs\nsrc/progress.rs\nsrc/reconcile_plan.rs\nsrc/refused_dataset_tests.rs\nsrc/resources.rs\nsrc/search.rs\nsrc/sniff.rs\nsrc/source.rs\nsrc/state.rs\nsrc/sync.rs\nsrc/sync_executor.rs\nsrc/walk.rs\nsrc/watch.rs\nsrc/xc.rs","is_error":false}]},"uuid":"62b261bd-bd27-46d0-a54b-bc6aca08d126","timestamp":"2026-10-01T15:38:14.033Z","sourceToolAssistantUUID":"108e7723-05ff-47c4-ac31-5465d0342c47","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"62b261bd-bd27-46d0-a54b-bc6aca08d126","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025331975b0ea68d084d26","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Good. Key insight: autoindex never opens archives. But there's a `docx` extractor which reads zip. Let me check `extract/docx.rs` for zip handling. Also `extract/pdf.rs` — PDF parsing with potential integer overflow / panics.\n\nNow let me read the pipeline.rs and builtins.rs. Those are the main targets.\n\nLet me read pipeline.rs.","signature":"c280d09520bd455bb814c278"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"b8e4f38b-6219-453e-8d3b-74c17ab84e77","timestamp":"2026-10-01T15:38:23.777Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"b8e4f38b-6219-453e-8d3b-74c17ab84e77","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025331975b0ea68d084d26","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"text","text":"Now let me read the main pipeline and builtins files."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"5c9095af-c4e9-4a95-b9ce-3035d34f3d98","timestamp":"2026-10-01T15:38:23.778Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"5c9095af-c4e9-4a95-b9ce-3035d34f3d98","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025331975b0ea68d084d26","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_2f3bcae1beea4df18ce5faeb","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/pipeline.rs"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":58721,"cache_creation_input_tokens":0,"cache_read_input_tokens":13568,"output_tokens":121,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"78ae4137-9037-4afe-af91-9b632953dc57","timestamp":"2026-10-01T15:38:23.884Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"78ae4137-9037-4afe-af91-9b632953dc57","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_2f3bcae1beea4df18ce5faeb","type":"tool_result","content":"1\t//! Pipeline executor: runs a document through an ordered list of transform\n2\t//! plugins.\n3\t\n4\tuse std::collections::HashMap;\n5\tuse std::sync::Arc;\n6\tuse std::time::Duration;\n7\t\n8\tuse serde::{Deserialize, Serialize};\n9\tuse serde_json::Value;\n10\tuse tracing::{debug, warn};\n11\t\n12\tuse crate::{\n13\t builtins::{\n14\t AddFieldPlugin, AppendPlugin, ConvertTypePlugin, CopyFieldPlugin, DropFieldPlugin,\n15\t FieldRenamePlugin, GrokPlugin, JsonParsePlugin, LowercasePlugin, PiiRedactionPlugin,\n16\t RemoveNullPlugin, RoutePlugin, SetPlugin, SplitPlugin, TimestampParsePlugin,\n17\t UppercasePlugin, UrlDecodePlugin, CONVERT_TARGET_TYPES, GROK_PATTERN_NAMES, PII_TYPE_NAMES,\n18\t },\n19\t Result, TransformPlugin, WasmError,\n20\t};\n21\t\n22\t// ── Action returned by each stage ────────────────────────────────────────────\n23\t\n24\t/// Decision returned by a pipeline stage (or the pipeline itself).\n25\t#[derive(Debug, Clone, PartialEq, Eq)]\n26\tpub enum ProcessAction {\n27\t /// Continue to the next stage / index the document normally.\n28\t Pass,\n29\t /// Discard this document — do not index it.\n30\t Drop,\n31\t /// Index the document into a different target (overrides the original\n32\t /// index name).\n33\t Route(String),\n34\t}\n35\t\n36\t// ── Error policy ─────────────────────────────────────────────────────────────\n37\t\n38\t/// What to do when a pipeline stage returns an error.\n39\t#[derive(Debug, Clone, Serialize, Deserialize, Default)]\n40\t#[serde(rename_all = \"snake_case\")]\n41\tpub enum ErrorPolicy {\n42\t /// Discard the document (default).\n43\t #[default]\n44\t Drop,\n45\t /// Pass the document through unchanged.\n46\t Pass,\n47\t /// Send the document to a dead-letter index (`<original>-dead-letter`).\n48\t DeadLetter,\n49\t}\n50\t\n51\t// ── Pipeline config (JSON-deserialisable) ─────────────────────────────────────\n52\t\n53\t/// Configuration for a single pipeline stage.\n54\t#[derive(Debug, Clone, Serialize, Deserialize)]\n55\tpub struct PipelineStageConfig {\n56\t /// Stage type — maps to a built-in plugin name (e.g. `\"json_parse\"`).\n57\t #[serde(rename = \"type\")]\n58\t pub stage_type: String,\n59\t /// Arbitrary plugin-specific configuration.\n60\t #[serde(default)]\n61\t pub config: Value,\n62\t}\n63\t\n64\t/// Top-level pipeline configuration (stored in the engine and serialised for\n65\t/// the `PUT /v1/pipelines/{name}` API).\n66\t#[derive(Debug, Clone, Serialize, Deserialize)]\n67\tpub struct PipelineConfig {\n68\t /// Human-readable description (optional).\n69\t #[serde(default)]\n70\t pub description: String,\n71\t /// Ordered list of transform stages.\n72\t pub stages: Vec<PipelineStageConfig>,\n73\t /// What to do when a stage fails.\n74\t #[serde(default)]\n75\t pub on_error: ErrorPolicy,\n76\t /// Per-document timeout in milliseconds (0 = unlimited).\n77\t #[serde(default)]\n78\t pub timeout_ms: u64,\n79\t}\n80\t\n81\t// ── Pipeline ──────────────────────────────────────────────────────────────────\n82\t\n83\t/// A named, executable pipeline composed of ordered [`TransformPlugin`] stages.\n84\t///\n85\t/// `Pipeline` is `Clone` (cheap — inner stages are `Arc`-wrapped) and safe to\n86\t/// share across async tasks.\n87\t#[derive(Clone)]\n88\tpub struct Pipeline {\n89\t /// Pipeline name (same as the key in the engine's pipeline map).\n90\t pub name: String,\n91\t /// Ordered stages.\n92\t stages: Vec<Arc<dyn TransformPlugin>>,\n93\t /// Error handling policy.\n94\t pub on_error: ErrorPolicy,\n95\t /// Per-document timeout (informational — enforced by the caller).\n96\t pub timeout: Duration,\n97\t /// Config this build could not honour but accepted anyway because the\n98\t /// definition was **already persisted** by an older, laxer build.\n99\t ///\n100\t /// Always empty for [`Pipeline::from_config`]. Non-empty only via\n101\t /// [`Pipeline::from_config_replaying_persisted`] — see [`CompileMode`].\n102\t /// One human-readable line per degraded stage; the caller logs them and\n103\t /// exposes them so the operator can re-`PUT` the definition.\n104\t pub degradations: Vec<String>,\n105\t}\n106\t\n107\t/// How strictly [`Pipeline::from_config`] enforces the issue-#204 contract.\n108\t///\n109\t/// The two call sites are not the same situation and must not get the same\n110\t/// answer:\n111\t///\n112\t/// * `Strict` — a caller is on the other end of a `PUT /_ingest/pipeline` and\n113\t/// can still act on a 400. Anything this build cannot honour is refused.\n114\t/// * `ReplayPersisted` — boot replay of a definition that is *already* in\n115\t/// `cluster_state.json`, accepted by whichever build wrote it. There is no\n116\t/// caller to fail: refusing it turns a working cluster's writes from `201`\n117\t/// into `400` on a binary upgrade alone, with no `PUT` and no operator\n118\t/// action. Lucene keys back-compat off the version an index was *created*\n119\t/// with rather than the running one for exactly this reason\n120\t/// (`LiveIndexWriterConfig.getIndexCreatedVersionMajor`,\n121\t/// lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java:290-298;\n122\t/// set by `IndexWriterConfig.setIndexCreatedVersionMajor`,\n123\t/// .../IndexWriterConfig.java:188-220). So replay reproduces the\n124\t/// *previously shipped* behaviour for the checks this sweep newly added, and\n125\t/// records every one of them in [`Pipeline::degradations`] so it is loud\n126\t/// rather than silent.\n127\t///\n128\t/// Checks that predate the sweep (a missing required field, an unknown stage\n129\t/// type) fail in BOTH modes: those definitions did not work before the upgrade\n130\t/// either.\n131\t#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n132\tpub enum CompileMode {\n133\t /// Definition time. Refuse anything this build cannot honour.\n134\t Strict,\n135\t /// Boot replay of an already-persisted definition. Reproduce the\n136\t /// pre-sweep behaviour for newly-added checks, and report it.\n137\t ReplayPersisted,\n138\t}\n139\t\n140\timpl CompileMode {\n141\t fn is_replay(self) -> bool {\n142\t matches!(self, Self::ReplayPersisted)\n143\t }\n144\t}\n145\t\n146\timpl Pipeline {\n147\t /// Build a [`Pipeline`] from a [`PipelineConfig`] at **definition time**.\n148\t ///\n149\t /// Three outcomes, deliberately distinct (issue #204):\n150\t ///\n151\t /// - [`WasmError::InvalidConfig`] — the caller's mistake. The definition\n152\t /// must be refused.\n153\t /// - [`WasmError::UnsupportedStage`] — a *xerj capability gap*: the caller\n154\t /// wrote something legitimate that we cannot run. The honest answer is to\n155\t /// say so at the point of use rather than pretend either way.\n156\t /// - [`WasmError::UnsupportedOption`] — the same gap one level down: the\n157\t /// stage exists, an option on it does not (a processor-level `if` guard,\n158\t /// a `grok` `patterns` array). Silently dropping these is what makes a\n159\t /// compiled pipeline write the wrong document under a `201`.\n160\t pub fn from_config(name: impl Into<String>, config: &PipelineConfig) -> Result<Self> {\n161\t Self::compile(name, config, CompileMode::Strict)\n162\t }\n163\t\n164\t /// Build a [`Pipeline`] from a definition that is **already on disk**.\n165\t ///\n166\t /// See [`CompileMode::ReplayPersisted`]. Callers MUST surface\n167\t /// [`Pipeline::degradations`]; a silent success here would be the same\n168\t /// defect this sweep exists to remove, only at boot instead of at `PUT`.\n169\t pub fn from_config_replaying_persisted(\n170\t name: impl Into<String>,\n171\t config: &PipelineConfig,\n172\t ) -> Result<Self> {\n173\t Self::compile(name, config, CompileMode::ReplayPersisted)\n174\t }\n175\t\n176\t fn compile(\n177\t name: impl Into<String>,\n178\t config: &PipelineConfig,\n179\t mode: CompileMode,\n180\t ) -> Result<Self> {\n181\t let name = name.into();\n182\t let mut stages: Vec<Arc<dyn TransformPlugin>> = Vec::new();\n183\t let mut degradations: Vec<String> = Vec::new();\n184\t\n185\t for stage_cfg in &config.stages {\n186\t let mut stage_degradations: Vec<String> = Vec::new();\n187\t let plugin = build_plugin(\n188\t &stage_cfg.stage_type,\n189\t &stage_cfg.config,\n190\t mode,\n191\t &mut stage_degradations,\n192\t )\n193\t .map_err(|e| match e {\n194\t StageBuildError::Unsupported(stage) => WasmError::UnsupportedStage { stage },\n195\t StageBuildError::UnsupportedOption { option, reason } => {\n196\t WasmError::UnsupportedOption {\n197\t stage: stage_cfg.stage_type.clone(),\n198\t option,\n199\t reason,\n200\t }\n201\t }\n202\t StageBuildError::Config(reason) => WasmError::InvalidConfig {\n203\t plugin: stage_cfg.stage_type.clone(),\n204\t reason,\n205\t },\n206\t })?;\n207\t degradations.extend(\n208\t stage_degradations\n209\t .into_iter()\n210\t .map(|d| format!(\"stage [{}]: {d}\", stage_cfg.stage_type)),\n211\t );\n212\t stages.push(plugin);\n213\t }\n214\t\n215\t Ok(Self {\n216\t name,\n217\t stages,\n218\t degradations,\n219\t on_error: config.on_error.clone(),\n220\t timeout: if config.timeout_ms == 0 {\n221\t Duration::from_secs(30)\n222\t } else {\n223\t Duration::from_millis(config.timeout_ms)\n224\t },\n225\t })\n226\t }\n227\t\n228\t /// Run `doc` through every stage in order.\n229\t ///\n230\t /// Returns the first non-[`ProcessAction::Pass`] action, or\n231\t /// [`ProcessAction::Pass`] if all stages pass.\n232\t pub fn process(&self, doc: &mut Value) -> ProcessAction {\n233\t for stage in &self.stages {\n234\t debug!(\n235\t pipeline = self.name.as_str(),\n236\t stage = stage.name(),\n237\t \"running stage\"\n238\t );\n239\t match stage.process(doc) {\n240\t ProcessAction::Pass => continue,\n241\t action => {\n242\t debug!(\n243\t pipeline = self.name.as_str(),\n244\t stage = stage.name(),\n245\t action = ?action,\n246\t \"stage short-circuits pipeline\"\n247\t );\n248\t return action;\n249\t }\n250\t }\n251\t }\n252\t ProcessAction::Pass\n253\t }\n254\t\n255\t /// Run every document in `docs` through the pipeline.\n256\t ///\n257\t /// Documents are processed independently — one failing stage does not\n258\t /// affect subsequent documents.\n259\t pub fn process_batch(&self, docs: &mut [Value]) -> Vec<ProcessAction> {\n260\t docs.iter_mut().map(|doc| self.process(doc)).collect()\n261\t }\n262\t\n263\t /// Number of stages in this pipeline.\n264\t pub fn stage_count(&self) -> usize {\n265\t self.stages.len()\n266\t }\n267\t}\n268\t\n269\timpl std::fmt::Debug for Pipeline {\n270\t fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n271\t f.debug_struct(\"Pipeline\")\n272\t .field(\"name\", &self.name)\n273\t .field(\"stage_count\", &self.stages.len())\n274\t .field(\"on_error\", &self.on_error)\n275\t .finish()\n276\t }\n277\t}\n278\t\n279\t// ── Plugin factory ────────────────────────────────────────────────────────────\n280\t\n281\t/// Why [`build_plugin`] refused a stage.\n282\t///\n283\t/// Split three ways on purpose (issue #204): `Config` is the caller's mistake\n284\t/// and must be refused at definition time; `Unsupported` and\n285\t/// `UnsupportedOption` are xerj's gaps and have to be reported as such, so\n286\t/// callers are not told their processor is invalid when it is merely\n287\t/// unimplemented here.\n288\t#[derive(Debug, Clone, PartialEq, Eq)]\n289\tpub(crate) enum StageBuildError {\n290\t /// The stage type is not implemented by this build.\n291\t Unsupported(String),\n292\t /// The stage type IS implemented but an option on it is not.\n293\t UnsupportedOption { option: String, reason: String },\n294\t /// The stage type exists but its config cannot be honoured.\n295\t Config(String),\n296\t}\n297\t\n298\timpl From<String> for StageBuildError {\n299\t fn from(reason: String) -> Self {\n300\t Self::Config(reason)\n301\t }\n302\t}\n303\t\n304\timpl StageBuildError {\n305\t /// One human-readable line, for [`Pipeline::degradations`].\n306\t pub(crate) fn to_reason(&self) -> String {\n307\t match self {\n308\t Self::Unsupported(stage) => format!(\"stage type [{stage}] is not implemented\"),\n309\t Self::UnsupportedOption { option, reason } => format!(\"`{option}` — {reason}\"),\n310\t Self::Config(reason) => reason.clone(),\n311\t }\n312\t }\n313\t}\n314\t\n315\t/// Read a processor-level boolean whose *written* value decides whether this\n316\t/// build can honour the processor.\n317\t///\n318\t/// `honoured` is the one value this build actually implements. Absence returns\n319\t/// `Ok(())` — an omitted key is not configuration, and it is what every\n320\t/// pre-existing definition looks like. A written value that equals `honoured`\n321\t/// also returns `Ok(())`: **spelling the honoured value out is exactly\n322\t/// equivalent to omitting it**, and refusing it is what made\n323\t/// `{\"set\": {…, \"ignore_failure\": false}}` — Elasticsearch's own default,\n324\t/// which ES clients emit verbatim — register a pipeline that 400s every write\n325\t/// through it. Anything else is a request this build cannot serve.\n326\t///\n327\t/// This is Lucene's consume-then-complain shape rather than a presence check:\n328\t/// `AbstractAnalysisFactory.getBoolean(args, name, defaultVal)`\n329\t/// (lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java:213-217)\n330\t/// does `args.remove(name)` and falls back to the default only when the key was\n331\t/// ABSENT; `ArabicStemFilterFactory`\n332\t/// (lucene/analysis/common/src/java/org/apache/lucene/analysis/ar/ArabicStemFilterFactory.java:44-51)\n333\t/// then throws `Unknown parameters` on whatever is LEFT. Presence alone never\n334\t/// decides anything.\n335\tfn honoured_bool(\n336\t config: &Value,\n337\t key: &'static str,\n338\t honoured: bool,\n339\t reason: &str,\n340\t) -> std::result::Result<(), StageBuildError> {\n341\t match config.get(key) {\n342\t None => Ok(()),\n343\t Some(Value::Bool(b)) if *b == honoured => Ok(()),\n344\t Some(Value::Bool(_)) => Err(StageBuildError::UnsupportedOption {\n345\t option: key.to_string(),\n346\t reason: reason.to_string(),\n347\t }),\n348\t Some(other) => Err(StageBuildError::Config(format!(\n349\t \"'{key}' must be a boolean, got {other}\"\n350\t ))),\n351\t }\n352\t}\n353\t\n354\t/// Processor-level keys that decide **whether** a processor runs or **what\n355\t/// happens when it fails**, none of which the compiled pipeline can act on.\n356\t///\n357\t/// Issue #204, applied to this sweep's own new surface. `PUT /_ingest/pipeline`\n358\t/// now means \"compiled ⇒ xerj honours this\"; a `{\"set\": {…, \"if\": \"ctx.foo ==\n359\t/// 'never'\"}}` that compiles and then sets the field on every document makes\n360\t/// that promise false, and writes the wrong document under a `201`. The\n361\t/// pipeline is accepted (ES accepts it) and recorded as unrunnable, so the gap\n362\t/// surfaces at ingest instead of being silently resolved in the caller's face.\n363\t///\n364\t/// `tag` and `description` are deliberately NOT here: they are identification\n365\t/// metadata that changes no document and no decision on this path.\n366\t///\n367\t/// The rule this applies, uniformly: **accept the value this build actually\n368\t/// implements (and absence, which is not configuration); refuse any other\n369\t/// written value.** It is the same rule `append`'s `allow_duplicates` already\n370\t/// used — ES's default there is `true`, which is what `AppendPlugin` does, so\n371\t/// `true`/absent are accepted and `false` is refused.\n372\tfn check_unhonourable_processor_keys(config: &Value) -> std::result::Result<(), StageBuildError> {\n373\t // `if`: EVERY value changes which documents the processor runs on, and\n374\t // none of them is evaluated here. Unlike the booleans below there is no\n375\t // spelling of `if` that means \"no guard\" — that spelling is omitting it.\n376\t if config.get(\"if\").is_some() {\n377\t return Err(StageBuildError::UnsupportedOption {\n378\t option: \"if\".to_string(),\n379\t reason: \"the guard is not evaluated, so the processor would run on documents \\\n380\t it excludes\"\n381\t .to_string(),\n382\t });\n383\t }\n384\t // `on_failure`: an EMPTY recovery chain asks for nothing, which is what\n385\t // happens. A non-empty one is a chain that would not run.\n386\t match config.get(\"on_failure\") {\n387\t None => {}\n388\t Some(Value::Array(a)) if a.is_empty() => {}\n389\t Some(_) => {\n390\t return Err(StageBuildError::UnsupportedOption {\n391\t option: \"on_failure\".to_string(),\n392\t reason: \"the recovery processors are not run; the pipeline's `on_error` \\\n393\t policy applies instead\"\n394\t .to_string(),\n395\t })\n396\t }\n397\t }\n398\t // `ignore_failure`: ES's default is `false` and `false` is what this build\n399\t // does — `ProcessAction` has no error variant, so a stage cannot report a\n400\t // runtime failure for anything to ignore in the first place. `true` asks\n401\t // for a decision this build cannot make.\n402\t honoured_bool(\n403\t config,\n404\t \"ignore_failure\",\n405\t false,\n406\t \"a failing processor is not ignored; the pipeline's `on_error` policy applies instead\",\n407\t )\n408\t}\n409\t\n410\t/// `ignore_missing`, for the four stages that read one named field\n411\t/// (`drop_field`, `field_rename`, `convert`, `timestamp_parse`).\n412\t///\n413\t/// Every one of those plugins returns `ProcessAction::Pass` when the field is\n414\t/// absent — `DropFieldPlugin::process` (`builtins.rs`) calls `obj.remove` and\n415\t/// moves on; `ConvertTypePlugin::process` returns early on `None`. That is\n416\t/// exactly `ignore_missing: true`, so `true` is honoured to the letter.\n417\t/// `false` asks for the document to be FAILED when the field is absent, and\n418\t/// this build cannot fail a document from inside a stage at all:\n419\t/// [`ProcessAction`] has no error variant.\n420\t///\n421\t/// **Known, documented divergence** (`CHANGELOG.md`, \"Known gaps\"): when\n422\t/// `ignore_missing` is OMITTED, ES's default is `false` and xerj still does\n423\t/// not fail the document. Absence is not configuration — nothing was written\n424\t/// for this build to break its word on — and refusing it would 400 every ES\n425\t/// `remove`/`rename`/`convert`/`date` processor ever written. Writing `false`\n426\t/// explicitly IS configuration, and is refused.\n427\tfn check_ignore_missing(config: &Value, stage: &str) -> std::result::Result<(), StageBuildError> {\n428\t honoured_bool(\n429\t config,\n430\t \"ignore_missing\",\n431\t true,\n432\t &format!(\n433\t \"xerj's `{stage}` stage passes the document through unchanged when the field is \\\n434\t absent; failing the document on a missing field is not implemented\"\n435\t ),\n436\t )\n437\t}\n438\t\n439\t/// Instantiate a built-in plugin by name.\n440\t///\n441\t/// `mode` decides what happens to config this build cannot honour; see\n442\t/// [`CompileMode`]. Every check that `ReplayPersisted` waves through pushes one\n443\t/// line onto `degradations` — the pipeline runs exactly as the previous build\n444\t/// ran it, and the caller reports that it is doing so.\n445\tfn build_plugin(\n446\t stage_type: &str,\n447\t config: &Value,\n448\t mode: CompileMode,\n449\t degradations: &mut Vec<String>,\n450\t) -> std::result::Result<Arc<dyn TransformPlugin>, StageBuildError> {\n451\t // `soften` turns a refusal into a recorded degradation under\n452\t // `ReplayPersisted`, and leaves it a refusal under `Strict`.\n453\t macro_rules! soften {\n454\t ($err:expr, $legacy:expr) => {{\n455\t let e: StageBuildError = $err;\n456\t if mode.is_replay() {\n457\t degradations.push(e.to_reason());\n458\t $legacy\n459\t } else {\n460\t return Err(e);\n461\t }\n462\t }};\n463\t }\n464\t if let Err(e) = check_unhonourable_processor_keys(config) {\n465\t soften!(e, ());\n466\t }\n467\t match stage_type {\n468\t \"json_parse\" => {\n469\t let field = str_field(config, \"field\")?;\n470\t let target = config\n471\t .get(\"target\")\n472\t .and_then(Value::as_str)\n473\t .unwrap_or(\"\")\n474\t .to_string();\n475\t Ok(Arc::new(JsonParsePlugin::new(field, target)))\n476\t }\n477\t\n478\t \"timestamp_parse\" => {\n479\t let field = str_field(config, \"field\")?;\n480\t if let Err(e) = check_ignore_missing(config, \"timestamp_parse\") {\n481\t soften!(e, ());\n482\t }\n483\t let formats = match optional_string_array(config, \"formats\") {\n484\t Ok(v) => v,\n485\t Err(e) => soften!(e.into(), None),\n486\t }\n487\t .unwrap_or_default();\n488\t let target = config\n489\t .get(\"target\")\n490\t .and_then(Value::as_str)\n491\t .map(str::to_string);\n492\t Ok(Arc::new(TimestampParsePlugin::new(field, formats, target)))\n493\t }\n494\t\n495\t \"field_rename\" => {\n496\t if let Err(e) = check_ignore_missing(config, \"field_rename\") {\n497\t soften!(e, ());\n498\t }\n499\t let mappings = config\n500\t .get(\"mappings\")\n501\t .and_then(Value::as_object)\n502\t .ok_or_else(|| \"missing 'mappings' object\".to_string())?;\n503\t let map: HashMap<String, String> = mappings\n504\t .iter()\n505\t .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))\n506\t .collect();\n507\t Ok(Arc::new(FieldRenamePlugin::new(map)))\n508\t }\n509\t\n510\t \"drop_field\" => {\n511\t if let Err(e) = check_ignore_missing(config, \"drop_field\") {\n512\t soften!(e, ());\n513\t }\n514\t let fields = string_array(config, \"fields\")?;\n515\t Ok(Arc::new(DropFieldPlugin::new(fields)))\n516\t }\n517\t\n518\t \"add_field\" => {\n519\t let field = str_field(config, \"field\")?;\n520\t let value = config\n521\t .get(\"value\")\n522\t .cloned()\n523\t .ok_or_else(|| \"missing 'value'\".to_string())?;\n524\t Ok(Arc::new(AddFieldPlugin::new(field, value)))\n525\t }\n526\t\n527\t \"route\" => {\n528\t let field = str_field(config, \"field\")?;\n529\t let routes = config\n530\t .get(\"routes\")\n531\t .and_then(Value::as_object)\n532\t .ok_or_else(|| \"missing 'routes' object\".to_string())?;\n533\t let map: HashMap<String, String> = routes\n534\t .iter()\n535\t .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))\n536\t .collect();\n537\t let default = config\n538\t .get(\"default\")\n539\t .and_then(Value::as_str)\n540\t .map(str::to_string);\n541\t Ok(Arc::new(RoutePlugin::new(field, map, default)))\n542\t }\n543\t\n544\t \"grok\" => {\n545\t let field = str_field(config, \"field\")?;\n546\t // Elasticsearch's `grok` processor is driven by `patterns` — an\n547\t // ARRAY of grok expressions (`[\"%{IP:client} %{WORD:method}\"]`),\n548\t // optionally with `pattern_definitions`. xerj's `grok` is a\n549\t // different, narrower thing: one NAMED pattern out of\n550\t // `GROK_PATTERN_NAMES`. Reading `pattern` and defaulting to\n551\t // `SYSLOG` meant an ES grok processor compiled clean, answered\n552\t // `200 acknowledged` under this PR's \"compiled ⇒ honoured\"\n553\t // contract, and left the document untouched (issue #204 — measured:\n554\t // `{\"message\": \"10.0.0.1 GET\"}` came back with no `client` field).\n555\t for key in [\"patterns\", \"pattern_definitions\"] {\n556\t if config.get(key).is_some() {\n557\t soften!(\n558\t StageBuildError::UnsupportedOption {\n559\t option: key.to_string(),\n560\t reason: format!(\n561\t \"xerj's grok stage takes a named `pattern` from [{}], not \\\n562\t arbitrary grok expressions\",\n563\t GROK_PATTERN_NAMES.join(\", \")\n564\t ),\n565\t },\n566\t ()\n567\t );\n568\t }\n569\t }\n570\t let pattern_name = match config.get(\"pattern\") {\n571\t None => \"SYSLOG\".to_string(),\n572\t Some(Value::String(s)) => {\n573\t // Fail closed: an unrecognised pattern name used to fall\n574\t // through to the generic catch-all, which extracts a\n575\t // single `message` field and nothing else (issue #204).\n576\t if !GROK_PATTERN_NAMES.contains(&s.as_str()) {\n577\t soften!(\n578\t format!(\n579\t \"unknown grok pattern '{s}' (known patterns: {})\",\n580\t GROK_PATTERN_NAMES.join(\", \")\n581\t )\n582\t .into(),\n583\t ()\n584\t );\n585\t }\n586\t s.clone()\n587\t }\n588\t Some(other) => soften!(\n589\t format!(\"'pattern' must be a string, got {other}\").into(),\n590\t \"SYSLOG\".to_string()\n591\t ),\n592\t };\n593\t Ok(Arc::new(GrokPlugin::new(field, pattern_name)))\n594\t }\n595\t\n596\t \"pii_redaction\" => {\n597\t // Fail closed on an unknown PII type: it used to contribute no\n598\t // regex, so a typo'd `types` list produced a stage that redacted\n599\t // nothing while reporting success (issue #204).\n600\t let declared = match optional_string_array(config, \"types\") {\n601\t Ok(v) => v,\n602\t Err(e) => soften!(e.into(), None),\n603\t };\n604\t let types = match declared {\n605\t None => vec![\"email\".into(), \"ip\".into(), \"credit_card\".into()],\n606\t Some(requested) => {\n607\t for t in &requested {\n608\t if !PII_TYPE_NAMES.contains(&t.as_str()) {\n609\t soften!(\n610\t format!(\n611\t \"unknown pii type '{t}' (known types: {})\",\n612\t PII_TYPE_NAMES.join(\", \")\n613\t )\n614\t .into(),\n615\t ()\n616\t );\n617\t }\n618\t }\n619\t requested\n620\t }\n621\t };\n622\t Ok(Arc::new(PiiRedactionPlugin::new(types)))\n623\t }\n624\t\n625\t \"copy_field\" => {\n626\t let source = str_field(config, \"source\")?;\n627\t let target = str_field(config, \"target\")?;\n628\t Ok(Arc::new(CopyFieldPlugin::new(source, target)))\n629\t }\n630\t\n631\t \"convert\" => {\n632\t let field = str_field(config, \"field\")?;\n633\t if let Err(e) = check_ignore_missing(config, \"convert\") {\n634\t soften!(e, ());\n635\t }\n636\t let target_type = str_field(config, \"type\")?;\n637\t // Fail closed: an unknown target type used to no-op per document\n638\t // rather than fail the pipeline definition (issue #204).\n639\t if !CONVERT_TARGET_TYPES.contains(&target_type.as_str()) {\n640\t soften!(\n641\t format!(\n642\t \"unknown convert target type '{target_type}' (known types: {})\",\n643\t CONVERT_TARGET_TYPES.join(\", \")\n644\t )\n645\t .into(),\n646\t ()\n647\t );\n648\t }\n649\t Ok(Arc::new(ConvertTypePlugin::new(field, target_type)))\n650\t }\n651\t\n652\t \"split\" => {\n653\t let field = str_field(config, \"field\")?;\n654\t let separator = config\n655\t .get(\"separator\")\n656\t .and_then(Value::as_str)\n657\t .unwrap_or(\",\")\n658\t .to_string();\n659\t Ok(Arc::new(SplitPlugin::new(field, separator)))\n660\t }\n661\t\n662\t \"lowercase\" => {\n663\t let field = str_field(config, \"field\")?;\n664\t Ok(Arc::new(LowercasePlugin::new(field)))\n665\t }\n666\t\n667\t \"uppercase\" => {\n668\t let field = str_field(config, \"field\")?;\n669\t Ok(Arc::new(UppercasePlugin::new(field)))\n670\t }\n671\t\n672\t \"set\" => {\n673\t let field = str_field(config, \"field\")?;\n674\t // Elasticsearch's `set` takes EITHER `value` or `copy_from` (7.x+),\n675\t // where `copy_from` names another field to read the value out of\n676\t // the document at ingest time. `SetPlugin` only holds a literal\n677\t // value, so `copy_from` cannot be honoured — but it is a valid ES\n678\t // processor, which makes the gap xerj's, not the caller's. Reported\n679\t // as an unsupported OPTION (accept the definition, refuse the\n680\t // write) rather than falling through to `missing 'value'`, which\n681\t // told the caller their correct ES pipeline was malformed.\n682\t if config.get(\"copy_from\").is_some() {\n683\t soften!(\n684\t StageBuildError::UnsupportedOption {\n685\t option: \"copy_from\".to_string(),\n686\t reason: \"xerj's set stage assigns a literal `value`; copying the value \\\n687\t from another field at ingest time is not implemented\"\n688\t .to_string(),\n689\t },\n690\t ()\n691\t );\n692\t }\n693\t // `ignore_empty_value: true` asks the stage to skip when the value\n694\t // is null or empty. `SetPlugin` always assigns, which is ES's\n695\t // default (`false`) — so `false`/absent are honoured exactly and\n696\t // `true` is a request this build cannot serve.\n697\t if let Err(e) = honoured_bool(\n698\t config,\n699\t \"ignore_empty_value\",\n700\t false,\n701\t \"the value is assigned even when it is null or empty; skipping on an empty \\\n702\t value is not implemented\",\n703\t ) {\n704\t soften!(e, ());\n705\t }\n706\t let value = config\n707\t .get(\"value\")\n708\t .cloned()\n709\t .ok_or_else(|| \"missing 'value'\".to_string())?;\n710\t // `override` defaults to FALSE for a native `type: \"set\"` stage and\n711\t // always has. Elasticsearch's `set` defaults it to TRUE\n712\t // (`SetProcessor.java:135` — read for semantics only, no code\n713\t // reproduced), and that parity is applied where it belongs: the\n714\t // ES→xerj translation in `es_compat::put_ingest_pipeline` writes\n715\t // `\"override\": true` explicitly when an ES `set` processor omits\n716\t // it. Flipping the default HERE would have changed the meaning of\n717\t // every already-persisted NATIVE pipeline as well — native\n718\t // definitions are recompiled from `cluster_state.json` at every\n719\t // boot, so a `set` stage that had been preserving an existing field\n720\t // value for the life of a cluster would start overwriting it on a\n721\t // binary upgrade alone, with no PUT and no operator action.\n722\t //\n723\t // A present-but-non-boolean `override` is a caller error rather\n724\t // than a silent fall-through to the default.\n725\t let override_existing = match config.get(\"override\") {\n726\t None => false,\n727\t Some(Value::Bool(b)) => *b,\n728\t Some(v) => soften!(\n729\t format!(\"'override' must be a boolean, got {v}\").into(),\n730\t false\n731\t ),\n732\t };\n733\t Ok(Arc::new(SetPlugin::new(field, value, override_existing)))\n734\t }\n735\t\n736\t \"append\" => {\n737\t let field = str_field(config, \"field\")?;\n738\t let value = config\n739\t .get(\"value\")\n740\t .cloned()\n741\t .ok_or_else(|| \"missing 'value'\".to_string())?;\n742\t // ES's `allow_duplicates` defaults to true (`AppendProcessor\n743\t // .java:121`) and that is what `AppendPlugin` does; the\n744\t // de-duplicating variant is not implemented, so asking for it must\n745\t // not be silently ignored.\n746\t if let Err(e) = honoured_bool(\n747\t config,\n748\t \"allow_duplicates\",\n749\t true,\n750\t \"values are always appended; de-duplicating append is not implemented\",\n751\t ) {\n752\t soften!(e, ());\n753\t }\n754\t Ok(Arc::new(AppendPlugin::new(field, value)))\n755\t }\n756\t\n757\t \"remove_null\" => Ok(Arc::new(RemoveNullPlugin)),\n758\t\n759\t \"url_decode\" => {\n760\t let field = str_field(config, \"field\")?;\n761\t Ok(Arc::new(UrlDecodePlugin::new(field)))\n762\t }\n763\t\n764\t unknown => {\n765\t warn!(stage_type = unknown, \"unknown pipeline stage type\");\n766\t Err(StageBuildError::Unsupported(unknown.to_string()))\n767\t }\n768\t }\n769\t}\n770\t\n771\t// ── Config helpers ────────────────────────────────────────────────────────────\n772\t\n773\tfn str_field(config: &Value, key: &str) -> std::result::Result<String, String> {\n774\t config\n775\t .get(key)\n776\t .and_then(Value::as_str)\n777\t .map(str::to_string)\n778\t .ok_or_else(|| format!(\"missing required string field '{key}'\"))\n779\t}\n780\t\n781\t/// Read an OPTIONAL array-of-strings config key.\n782\t///\n783\t/// `Ok(None)` means the key is absent (the caller applies its documented\n784\t/// default). A present-but-wrong-shaped value is an error rather than a silent\n785\t/// fall-through to the default — `\"formats\": \"%Y-%m-%d\"` used to be dropped by\n786\t/// `and_then(Value::as_array)` and the stage then behaved as if no formats had\n787\t/// been configured at all (issue #204).\n788\tfn optional_string_array(\n789\t config: &Value,\n790\t key: &str,\n791\t) -> std::result::Result<Option<Vec<String>>, String> {\n792\t let Some(raw) = config.get(key) else {\n793\t return Ok(None);\n794\t };\n795\t let arr = raw\n796\t .as_array()\n797\t .ok_or_else(|| format!(\"'{key}' must be an array of strings\"))?;\n798\t let mut out = Vec::with_capacity(arr.len());\n799\t for v in arr {\n800\t let s = v\n801\t .as_str()\n802\t .ok_or_else(|| format!(\"'{key}' must contain only strings, got {v}\"))?;\n803\t out.push(s.to_string());\n804\t }\n805\t Ok(Some(out))\n806\t}\n807\t\n808\tfn string_array(config: &Value, key: &str) -> std::result::Result<Vec<String>, String> {\n809\t let arr = config\n810\t .get(key)\n811\t .and_then(Value::as_array)\n812\t .ok_or_else(|| format!(\"missing required array field '{key}'\"))?;\n813\t Ok(arr\n814\t .iter()\n815\t .filter_map(|v| v.as_str().map(str::to_string))\n816\t .collect())\n817\t}\n818\t\n819\t// ── Tests ─────────────────────────────────────────────────────────────────────\n820\t\n821\t#[cfg(test)]\n822\tmod tests {\n823\t use super::*;\n824\t\n825\t fn make_pipeline(stages: &[(&str, Value)]) -> Pipeline {\n826\t let stage_cfgs: Vec<PipelineStageConfig> = stages\n827\t .iter()\n828\t .map(|(t, c)| PipelineStageConfig {\n829\t stage_type: t.to_string(),\n830\t config: c.clone(),\n831\t })\n832\t .collect();\n833\t let cfg = PipelineConfig {\n834\t description: \"test\".into(),\n835\t stages: stage_cfgs,\n836\t on_error: ErrorPolicy::Drop,\n837\t timeout_ms: 0,\n838\t };\n839\t Pipeline::from_config(\"test-pipeline\", &cfg).expect(\"pipeline build failed\")\n840\t }\n841\t\n842\t #[test]\n843\t fn pipeline_processes_all_pass_stages() {\n844\t let pl = make_pipeline(&[(\n845\t \"add_field\",\n846\t serde_json::json!({ \"field\": \"env\", \"value\": \"test\" }),\n847\t )]);\n848\t let mut doc = serde_json::json!({ \"msg\": \"hello\" });\n849\t assert_eq!(pl.process(&mut doc), ProcessAction::Pass);\n850\t assert_eq!(doc[\"env\"], \"test\");\n851\t }\n852\t\n853\t #[test]\n854\t fn pipeline_short_circuits_on_drop() {\n855\t let pl = make_pipeline(&[\n856\t // First stage drops the document\n857\t (\"drop_field\", serde_json::json!({ \"fields\": [\"drop_me\"] })),\n858\t // This stage would add a field, but we'll test with a route stage\n859\t // that triggers drop via a route mismatch — use a simple 2-stage test\n860\t (\n861\t \"add_field\",\n862\t serde_json::json!({ \"field\": \"should_not_appear\", \"value\": true }),\n863\t ),\n864\t ]);\n865\t let mut doc = serde_json::json!({ \"msg\": \"hello\", \"drop_me\": \"x\" });\n866\t // drop_field returns Pass (it removes the field), add_field adds env\n867\t assert_eq!(pl.process(&mut doc), ProcessAction::Pass);\n868\t assert_eq!(doc[\"should_not_appear\"], true);\n869\t }\n870\t\n871\t #[test]\n872\t fn pipeline_batch() {\n873\t let pl = make_pipeline(&[(\n874\t \"add_field\",\n875\t serde_json::json!({ \"field\": \"pipeline\", \"value\": \"default\" }),\n876\t )]);\n877\t let mut docs = vec![serde_json::json!({ \"a\": 1 }), serde_json::json!({ \"b\": 2 })];\n878\t let actions = pl.process_batch(&mut docs);\n879\t assert!(actions.iter().all(|a| *a == ProcessAction::Pass));\n880\t assert_eq!(docs[0][\"pipeline\"], \"default\");\n881\t assert_eq!(docs[1][\"pipeline\"], \"default\");\n882\t }\n883\t\n884\t #[test]\n885\t fn pipeline_from_invalid_config_fails() {\n886\t let cfg = PipelineConfig {\n887\t description: String::new(),\n888\t stages: vec![PipelineStageConfig {\n889\t stage_type: \"unknown_plugin_xyz\".into(),\n890\t config: Value::Null,\n891\t }],\n892\t on_error: ErrorPolicy::Pass,\n893\t timeout_ms: 0,\n894\t };\n895\t assert!(Pipeline::from_config(\"bad\", &cfg).is_err());\n896\t }\n897\t}\n898\t\n899\t// ─────────────────────────────────────────────────────────────────────────────\n900\t// Issue #204 — weaker fallbacks on user-supplied processor configuration\n901\t//\n902\t// Each case below used to build a pipeline that was accepted, stored, and\n903\t// reported healthy, and then did LESS than the caller asked for with no signal\n904\t// at all. They now fail closed at `Pipeline::from_config`, which is where the\n905\t// caller can still act on the error.\n906\t// ─────────────────────────────────────────────────────────────────────────────\n907\t#[cfg(test)]\n908\tmod fallback_regression_tests {\n909\t use super::*;\n910\t\n911\t fn build(stage_type: &str, config: Value) -> std::result::Result<Pipeline, WasmError> {\n912\t Pipeline::from_config(\n913\t \"t\",\n914\t &PipelineConfig {\n915\t description: String::new(),\n916\t stages: vec![PipelineStageConfig {\n917\t stage_type: stage_type.into(),\n918\t config,\n919\t }],\n920\t on_error: ErrorPolicy::Drop,\n921\t timeout_ms: 0,\n922\t },\n923\t )\n924\t }\n925\t\n926\t /// A stage type this build does not implement and a stage type whose\n927\t /// config we refuse are different answers, and callers act on the\n928\t /// difference: the first is xerj's gap (accept the definition, refuse the\n929\t /// writes), the second is the caller's mistake (refuse the definition).\n930\t /// Collapsing them was what let an unimplemented processor be silently\n931\t /// dropped in the first place.\n932\t #[test]\n933\t fn an_unimplemented_stage_type_is_distinguishable_from_a_bad_config() {\n934\t let err = build(\"pipeline\", serde_json::json!({ \"name\": \"other\" }))\n935\t .expect_err(\"unimplemented stage type must not build\");\n936\t assert!(\n937\t matches!(&err, WasmError::UnsupportedStage { stage } if stage == \"pipeline\"),\n938\t \"expected UnsupportedStage, got: {err:?}\"\n939\t );\n940\t\n941\t let err = build(\n942\t \"convert\",\n943\t serde_json::json!({ \"field\": \"f\", \"type\": \"int\" }),\n944\t )\n945\t .expect_err(\"bad config must not build\");\n946\t assert!(\n947\t matches!(err, WasmError::InvalidConfig { .. }),\n948\t \"a known stage with a bad config is InvalidConfig, got: {err:?}\"\n949\t );\n950\t }\n951\t\n952\t #[test]\n953\t fn unknown_pii_type_is_rejected_not_silently_unredacted() {\n954\t // Pre-fix: `social_security` matched no `wants(..)` arm, the pattern\n955\t // list came out EMPTY, and the stage passed every document through\n956\t // with its PII intact while reporting success.\n957\t let err = build(\n958\t \"pii_redaction\",\n959\t serde_json::json!({ \"types\": [\"ssn\", \"social_security\"] }),\n960\t )\n961\t .expect_err(\"unknown pii type must fail the pipeline definition\");\n962\t assert!(\n963\t err.to_string().contains(\"social_security\"),\n964\t \"error must name the offending type: {err}\"\n965\t );\n966\t\n967\t // The supported spelling still builds and still redacts.\n968\t let pl = build(\"pii_redaction\", serde_json::json!({ \"types\": [\"ssn\"] }))\n969\t .expect(\"known pii type builds\");\n970\t let mut doc = serde_json::json!({ \"note\": \"ssn 123-45-6789\" });\n971\t pl.process(&mut doc);\n972\t assert_eq!(doc[\"note\"], \"ssn [REDACTED_SSN]\");\n973\t }\n974\t\n975\t #[test]\n976\t fn non_array_pii_types_is_rejected_not_defaulted() {\n977\t // Pre-fix: `and_then(Value::as_array)` returned None for a bare string\n978\t // and the stage silently fell back to the built-in default type list.\n979\t assert!(build(\"pii_redaction\", serde_json::json!({ \"types\": \"ssn\" })).is_err());\n980\t }\n981\t\n982\t #[test]\n983\t fn absent_pii_types_still_uses_the_documented_default() {\n984\t let pl = build(\"pii_redaction\", serde_json::json!({})).expect(\"default types build\");\n985\t let mut doc = serde_json::json!({ \"note\": \"mail me at [email protected]\" });\n986\t pl.process(&mut doc);\n987\t assert_eq!(doc[\"note\"], \"mail me at [REDACTED_EMAIL]\");\n988\t }\n989\t\n990\t #[test]\n991\t fn unknown_grok_pattern_is_rejected_not_downgraded_to_catch_all() {\n992\t // Pre-fix: this compiled to `^(?P<message>.+)$`, so an nginx pipeline\n993\t // extracted one field instead of ten and nothing said so.\n994\t let err = build(\n995\t \"grok\",\n996\t serde_json::json!({ \"field\": \"msg\", \"pattern\": \"NGINX_COMBINE\" }),\n997\t )\n998\t .expect_err(\"typo'd grok pattern must fail\");\n999\t assert!(\n1000\t err.to_string().contains(\"NGINX_COMBINE\"),\n1001\t \"error must name the offending pattern: {err}\"\n1002\t );\n1003\t\n1004\t // The catch-all is still reachable — by asking for it.\n1005\t let pl = build(\n1006\t \"grok\",\n1007\t serde_json::json!({ \"field\": \"msg\", \"pattern\": \"GENERIC\" }),\n1008\t )\n1009\t .expect(\"GENERIC is an explicit, supported pattern\");\n1010\t let mut doc = serde_json::json!({ \"msg\": \"anything at all\" });\n1011\t pl.process(&mut doc);\n1012\t assert_eq!(doc[\"message\"], \"anything at all\");\n1013\t }\n1014\t\n1015\t #[test]\n1016\t fn unknown_convert_target_type_is_rejected_not_a_per_document_noop() {\n1017\t // Pre-fix: `\"int\"` built fine and then hit `_ => None` on every\n1018\t // document, leaving the field a string forever.\n1019\t let err = build(\n1020\t \"convert\",\n1021\t serde_json::json!({ \"field\": \"status\", \"type\": \"int\" }),\n1022\t )\n1023\t .expect_err(\"unknown convert target type must fail\");\n1024\t assert!(err.to_string().contains(\"int\"), \"{err}\");\n1025\t\n1026\t let pl = build(\n1027\t \"convert\",\n1028\t serde_json::json!({ \"field\": \"status\", \"type\": \"integer\" }),\n1029\t )\n1030\t .expect(\"known target type builds\");\n1031\t let mut doc = serde_json::json!({ \"status\": \"404\" });\n1032\t pl.process(&mut doc);\n1033\t assert_eq!(doc[\"status\"], 404);\n1034\t }\n1035\t\n1036\t #[test]\n1037\t fn non_array_timestamp_formats_is_rejected_not_dropped() {\n1038\t assert!(build(\n1039\t \"timestamp_parse\",\n1040\t serde_json::json!({ \"field\": \"ts\", \"formats\": \"%Y-%m-%d\" })\n1041\t )\n1042\t .is_err());\n1043\t // Absent `formats` is still the documented epoch/RFC-3339 default.\n1044\t assert!(build(\"timestamp_parse\", serde_json::json!({ \"field\": \"ts\" })).is_ok());\n1045\t }\n1046\t\n1047\t /// A processor-level `if` guard is not evaluated on this path. Compiling it\n1048\t /// meant `PUT /_ingest/pipeline` answered 200 — which this change redefined\n1049\t /// to mean \"xerj honours this\" — and then ran the processor on exactly the\n1050\t /// documents the guard excludes. Measured pre-fix: `{\"foo\":\n1051\t /// \"something-else\"}` came out `{\"foo\": \"something-else\", \"env\": \"prod\"}`.\n1052\t #[test]\n1053\t fn a_processor_level_if_guard_is_not_silently_dropped() {\n1054\t let err = build(\n1055\t \"set\",\n1056\t serde_json::json!({\n1057\t \"field\": \"env\", \"value\": \"prod\", \"if\": \"ctx.foo == 'never'\"\n1058\t }),\n1059\t )\n1060\t .expect_err(\"an unhonourable `if` must not compile\");\n1061\t assert!(\n1062\t matches!(&err, WasmError::UnsupportedOption { stage, option, .. }\n1063\t if stage == \"set\" && option == \"if\"),\n1064\t \"expected UnsupportedOption(if), got: {err:?}\"\n1065\t );\n1066\t }\n1067\t\n1068\t #[test]\n1069\t fn on_failure_and_ignore_failure_are_not_silently_dropped() {\n1070\t for key in [\"on_failure\", \"ignore_failure\"] {\n1071\t let mut cfg = serde_json::json!({ \"field\": \"env\", \"value\": \"prod\" });\n1072\t cfg[key] = serde_json::json!(if key == \"ignore_failure\" {\n1073\t serde_json::json!(true)\n1074\t } else {\n1075\t serde_json::json!([{ \"set\": { \"field\": \"x\", \"value\": 1 } }])\n1076\t });\n1077\t let err = build(\"set\", cfg).expect_err(\"{key} must not be dropped\");\n1078\t assert!(\n1079\t matches!(&err, WasmError::UnsupportedOption { option, .. } if option == key),\n1080\t \"expected UnsupportedOption({key}), got: {err:?}\"\n1081\t );\n1082\t }\n1083\t }\n1084\t\n1085\t /// `tag` and `description` are identification metadata — they change no\n1086\t /// document and no decision on this path — so they stay accepted.\n1087\t #[test]\n1088\t fn processor_metadata_keys_still_compile() {\n1089\t assert!(build(\n1090\t \"set\",\n1091\t serde_json::json!({\n1092\t \"field\": \"env\", \"value\": \"prod\",\n1093\t \"tag\": \"t1\", \"description\": \"sets env\"\n1094\t })\n1095\t )\n1096\t .is_ok());\n1097\t }\n1098\t\n1099\t /// ES's `grok` is driven by `patterns` (an array of grok expressions);\n1100\t /// xerj's takes one NAMED pattern. Reading `pattern` and defaulting to\n1101\t /// `SYSLOG` meant an ES grok processor compiled clean and left the document\n1102\t /// untouched — measured pre-fix: `{\"message\": \"10.0.0.1 GET\"}` with the\n1103\t /// `%{IP:client}` capture nowhere.\n1104\t #[test]\n1105\t fn es_grok_patterns_array_is_not_silently_replaced_by_syslog() {\n1106\t let err = build(\n1107\t \"grok\",\n1108\t serde_json::json!({\n1109\t \"field\": \"message\", \"patterns\": [\"%{IP:client} %{WORD:method}\"]\n1110\t }),\n1111\t )\n1112\t .expect_err(\"`patterns` must not compile to the SYSLOG default\");\n1113\t assert!(\n1114\t matches!(&err, WasmError::UnsupportedOption { stage, option, .. }\n1115\t if stage == \"grok\" && option == \"patterns\"),\n1116\t \"expected UnsupportedOption(patterns), got: {err:?}\"\n1117\t );\n1118\t }\n1119\t\n1120\t /// The NATIVE `set` stage keeps `override: false` as its default, and must\n1121\t /// keep it: native definitions live in `cluster_state.json` and are\n1122\t /// recompiled at every boot, so flipping the default here would silently\n1123\t /// change what an already-running cluster's pipelines do to documents on a\n1124\t /// binary upgrade alone — no PUT, no operator action. ES parity for the\n1125\t /// `set` PROCESSOR is applied in the translation layer instead, which\n1126\t /// writes `\"override\": true` explicitly (see\n1127\t /// `es_compat::put_ingest_pipeline`).\n1128\t #[test]\n1129\t fn native_set_stage_keeps_its_non_overriding_default() {\n1130\t let pl = build(\n1131\t \"set\",\n1132\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\" }),\n1133\t )\n1134\t .expect(\"set builds\");\n1135\t let mut doc = serde_json::json!({ \"env\": \"dev\" });\n1136\t pl.process(&mut doc);\n1137\t assert_eq!(\n1138\t doc[\"env\"], \"dev\",\n1139\t \"a native `set` stage with no `override` must NOT overwrite an existing value\"\n1140\t );\n1141\t\n1142\t // An absent field is still filled in.\n1143\t let mut doc = serde_json::json!({});\n1144\t pl.process(&mut doc);\n1145\t assert_eq!(doc[\"env\"], \"prod\");\n1146\t\n1147\t // …and the explicit opt-in overwrites, which is what the ES\n1148\t // translation writes for every ES `set` processor.\n1149\t let pl = build(\n1150\t \"set\",\n1151\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\", \"override\": true }),\n1152\t )\n1153\t .expect(\"set builds\");\n1154\t let mut doc = serde_json::json!({ \"env\": \"dev\" });\n1155\t pl.process(&mut doc);\n1156\t assert_eq!(doc[\"env\"], \"prod\");\n1157\t\n1158\t // A non-boolean `override` is refused rather than defaulted.\n1159\t assert!(build(\n1160\t \"set\",\n1161\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\", \"override\": \"yes\" })\n1162\t )\n1163\t .is_err());\n1164\t }\n1165\t\n1166\t /// `ignore_failure: false` is Elasticsearch's OWN default, and ES clients\n1167\t /// write it out verbatim. Testing `config.get(key).is_some()` refused it,\n1168\t /// so `{\"set\": {\"field\": \"env\", \"value\": \"prod\", \"ignore_failure\": false}}`\n1169\t /// registered a pipeline that 400'd every write through it — while the\n1170\t /// byte-identical processor without the key compiled fine.\n1171\t #[test]\n1172\t fn writing_the_honoured_default_is_the_same_as_omitting_it() {\n1173\t for cfg in [\n1174\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\", \"ignore_failure\": false }),\n1175\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\", \"on_failure\": [] }),\n1176\t serde_json::json!({ \"field\": \"env\", \"value\": \"prod\", \"ignore_empty_value\": false }),\n1177\t ] {\n1178\t let pl = build(\"set\", cfg.clone())\n1179\t .unwrap_or_else(|e| panic!(\"{cfg} must compile like the bare processor: {e}\"));\n1180\t let mut doc = serde_json::json!({});\n1181\t pl.process(&mut doc);\n1182\t assert_eq!(doc[\"env\"], \"prod\");\n1183\t }\n1184\t\n1185\t // `ignore_missing: true` is what every field-reading stage already\n1186\t // does, so it is honoured to the letter rather than refused.\n1187\t for (stage, cfg) in [\n1188\t (\n1189\t \"drop_field\",\n1190\t serde_json::json!({ \"fields\": [\"a\"], \"ignore_missing\": true }),\n1191\t ),\n1192\t (\n1193\t \"field_rename\",\n1194\t serde_json::json!({ \"mappings\": { \"a\": \"b\" }, \"ignore_missing\": true }),\n1195\t ),\n1196\t (\n1197\t \"convert\",\n1198\t serde_json::json!({ \"field\": \"a\", \"type\": \"integer\", \"ignore_missing\": true }),\n1199\t ),\n1200\t (\n1201\t \"timestamp_parse\",\n1202\t serde_json::json!({ \"field\": \"a\", \"ignore_missing\": true }),\n1203\t ),\n1204\t ] {\n1205\t assert!(\n1206\t build(stage, cfg.clone()).is_ok(),\n1207\t \"{stage} must accept the ignore_missing value it implements: {cfg}\"\n1208\t );\n1209\t }\n1210\t }\n1211\t\n1212\t /// The other half of the same rule: a written value this build does NOT\n1213\t /// implement is refused, whether or not it happens to be ES's default.\n1214\t #[test]\n1215\t fn writing_an_unhonoured_value_is_refused_even_when_it_is_the_es_default() {\n1216\t // `ignore_missing: false` asks for the document to be failed on a\n1217\t // missing field. `ProcessAction` has no error variant.\n1218\t let err = build(\n1219\t \"drop_field\",\n1220\t serde_json::json!({ \"fields\": [\"a\"], \"ignore_missing\": false }),\n1221\t )\n1222\t .expect_err(\"ignore_missing:false must not compile\");\n1223\t assert!(\n1224\t matches!(&err, WasmError::UnsupportedOption { option, .. } if option == \"ignore_missing\"),\n1225\t \"expected UnsupportedOption(ignore_missing), got: {err:?}\"\n1226\t );\n1227\t\n1228\t // `ignore_empty_value: true` asks `set` to skip on an empty value.\n1229\t let err = build(\n1230\t \"set\",\n1231\t serde_json::json!({ \"field\": \"env\", \"value\": \"\", \"ignore_empty_value\": true }),\n1232\t )\n1233\t .expect_err(\"ignore_empty_value:true must not compile\");\n1234\t assert!(\n1235\t matches!(&err, WasmError::UnsupportedOption { option, .. }\n1236\t if option == \"ignore_empty_value\"),\n1237\t \"expected UnsupportedOption(ignore_empty_value), got: {err:?}\"\n1238\t );\n1239\t\n1240\t // A non-boolean is the caller's mistake, not a capability gap.\n1241\t assert!(matches!(\n1242\t build(\n1243\t \"set\",\n1244\t serde_json::json!({ \"field\": \"e\", \"value\": 1, \"ignore_failure\": \"no\" })\n1245\t )\n1246\t .expect_err(\"non-boolean ignore_failure must not compile\"),\n1247\t WasmError::InvalidConfig { .. }\n1248\t ));\n1249\t }\n1250\t\n1251\t /// Boot replay is not definition time. A definition that is ALREADY in\n1252\t /// `cluster_state.json` was accepted by whichever build wrote it; refusing\n1253\t /// it now turns a working cluster's writes from 201 into 400 on a binary\n1254\t /// upgrade alone. Replay reproduces the previously-shipped behaviour and\n1255\t /// reports every instance in `degradations`.\n1256\t #[test]\n1257\t fn replaying_a_persisted_definition_does_not_break_on_a_newly_added_check() {\n1258\t fn replay(stage_type: &str, config: Value) -> Result<Pipeline> {\n1259\t Pipeline::from_config_replaying_persisted(\n1260\t \"t\",\n1261\t &PipelineConfig {\n1262\t description: String::new(),\n1263\t stages: vec![PipelineStageConfig {\n1264\t stage_type: stage_type.into(),\n1265\t config,\n1266\t }],\n1267\t on_error: ErrorPolicy::Drop,\n1268\t timeout_ms: 0,\n1269\t },\n1270\t )\n1271\t }\n1272\t\n1273\t // Every check this sweep added, in the shape a pre-upgrade\n1274\t // cluster_state.json can legitimately hold.\n1275\t let cases: Vec<(&str, Value)> = vec![\n1276\t (\n1277\t \"grok\",\n1278\t serde_json::json!({ \"field\": \"m\", \"pattern\": \"NGINX_COMBINE\" }),\n1279\t ),\n1280\t (\n1281\t \"convert\",\n1282\t serde_json::json!({ \"field\": \"status\", \"type\": \"int\" }),\n1283\t ),\n1284\t (\n1285\t \"timestamp_parse\",\n1286\t serde_json::json!({ \"field\": \"ts\", \"formats\": \"%Y-%m-%d\" }),\n1287\t ),\n1288\t (\"pii_redaction\", serde_json::json!({ \"types\": \"ssn\" })),\n1289\t (\n1290\t \"set\",\n1291\t serde_json::json!({ \"field\": \"e\", \"value\": \"p\", \"copy_from\": \"other\" }),\n1292\t ),\n1293\t (\n1294\t \"set\",\n1295\t serde_json::json!({ \"field\": \"e\", \"value\": \"p\", \"if\": \"ctx.x == 'y'\" }),\n1296\t ),\n1297\t ];\n1298\t for (stage, cfg) in cases {\n1299\t // Strict (a live PUT) refuses…\n1300\t assert!(\n1301\t build(stage, cfg.clone()).is_err(),\n1302\t \"{stage} {cfg} must be refused at definition time\"\n1303\t );\n1304\t // …replay of the same persisted definition keeps running, loudly.\n1305\t let pl = replay(stage, cfg.clone())\n1306\t .unwrap_or_else(|e| panic!(\"replay of {stage} {cfg} must not fail the boot: {e}\"));\n1307\t assert!(\n1308\t !pl.degradations.is_empty(),\n1309\t \"replay of {stage} {cfg} must record why it is degraded\"\n1310\t );\n1311\t assert!(\n1312\t pl.degradations[0].starts_with(&format!(\"stage [{stage}]:\")),\n1313\t \"degradation must name the stage: {:?}\",\n1314\t pl.degradations\n1315\t );\n1316\t }\n1317\t\n1318\t // A definition that did NOT work before the upgrade either still\n1319\t // fails in both modes — replay is a compatibility door, not a mute.\n1320\t assert!(replay(\"no_such_stage\", serde_json::json!({})).is_err());\n1321\t assert!(replay(\"drop_field\", serde_json::json!({})).is_err());\n1322\t\n1323\t // And a clean definition replays with nothing to report.\n1324\t let pl = replay(\"set\", serde_json::json!({ \"field\": \"e\", \"value\": \"p\" }))\n1325\t .expect(\"a clean definition replays\");\n1326\t assert!(pl.degradations.is_empty());\n1327\t }\n1328\t\n1329\t /// `append` used to be mapped onto `set` in the ES translation, so it\n1330\t /// REPLACED the field. It is now a real append and agrees with the\n1331\t /// `_simulate` interpreter.\n1332\t #[test]\n1333\t fn append_extends_rather_than_replacing() {\n1334\t let pl = build(\n1335\t \"append\",\n1336\t serde_json::json!({ \"field\": \"tags\", \"value\": \"b\" }),\n1337\t )\n1338\t .expect(\"append builds\");\n1339\t\n1340\t let mut doc = serde_json::json!({ \"tags\": [\"a\"] });\n1341\t pl.process(&mut doc);\n1342\t assert_eq!(doc[\"tags\"], serde_json::json!([\"a\", \"b\"]));\n1343\t\n1344\t // A scalar widens into a list; a missing field becomes a 1-element one.\n1345\t let mut doc = serde_json::json!({ \"tags\": \"a\" });\n1346\t pl.process(&mut doc);\n1347\t assert_eq!(doc[\"tags\"], serde_json::json!([\"a\", \"b\"]));\n1348\t let mut doc = serde_json::json!({});\n1349\t pl.process(&mut doc);\n1350\t assert_eq!(doc[\"tags\"], serde_json::json!([\"b\"]));\n1351\t\n1352\t // A list value extends rather than nesting.\n1353\t let pl = build(\n1354\t \"append\",\n1355\t serde_json::json!({ \"field\": \"tags\", \"value\": [\"b\", \"c\"] }),\n1356\t )\n1357\t .expect(\"append builds\");\n1358\t let mut doc = serde_json::json!({ \"tags\": [\"a\"] });\n1359\t pl.process(&mut doc);\n1360\t assert_eq!(doc[\"tags\"], serde_json::json!([\"a\", \"b\", \"c\"]));\n1361\t\n1362\t // De-duplicating append is not implemented; asking for it is refused.\n1363\t assert!(build(\n1364\t \"append\",\n1365\t serde_json::json!({ \"field\": \"tags\", \"value\": \"b\", \"allow_duplicates\": false })\n1366\t )\n1367\t .is_err());\n1368\t }\n1369\t}\n1370\t"}]},"uuid":"e53b9fdb-fcd1-4546-a5c6-e70555b114d2","timestamp":"2026-10-01T15:38:24.745Z","sourceToolAssistantUUID":"78ae4137-9037-4afe-af91-9b632953dc57","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"e53b9fdb-fcd1-4546-a5c6-e70555b114d2","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025341afe695aed2064c65","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Pipeline.rs is mostly config-driven. No doc-content-driven issue except: grok patterns are named constants (not doc-supplied), regexes are fixed. So the regex backtracking concern: the regexes come from GROK_PATTERN_NAMES — check builtins.rs.\n\nNow let me read builtins.rs.","signature":"1f55c6fd1867499bb5231ddf"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":15579,"cache_creation_input_tokens":0,"cache_read_input_tokens":72256,"output_tokens":94,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"710c9f29-2cfc-4bf2-8142-820a26f4a174","timestamp":"2026-10-01T15:38:30.280Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"710c9f29-2cfc-4bf2-8142-820a26f4a174","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025341afe695aed2064c65","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_e1a7c4aa93bf47f8b1f63d2d","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/builtins.rs"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":15579,"cache_creation_input_tokens":0,"cache_read_input_tokens":72256,"output_tokens":94,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"ef5a3c32-aa63-4fd2-90d2-04feed3c320f","timestamp":"2026-10-01T15:38:30.281Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"ef5a3c32-aa63-4fd2-90d2-04feed3c320f","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_e1a7c4aa93bf47f8b1f63d2d","type":"tool_result","content":"1\t//! Built-in transform plugins — no WASM required.\n2\t//!\n3\t//! Every plugin implements [`TransformPlugin`] and can be composed into a\n4\t//! [`Pipeline`](crate::pipeline::Pipeline).\n5\t\n6\tuse std::collections::HashMap;\n7\t\n8\tuse regex::Regex;\n9\tuse serde_json::Value;\n10\tuse tracing::debug;\n11\t\n12\tuse crate::{pipeline::ProcessAction, TransformPlugin};\n13\t\n14\t// ─────────────────────────────────────────────────────────────────────────────\n15\t// JsonParsePlugin\n16\t// ─────────────────────────────────────────────────────────────────────────────\n17\t\n18\t/// Parse the value of a string field as JSON.\n19\t///\n20\t/// If `target` is empty the parsed fields are merged into the root document.\n21\t/// Otherwise the parsed object is stored at `doc[target]`.\n22\t///\n23\t/// The original field is removed after successful parsing.\n24\tpub struct JsonParsePlugin {\n25\t /// Source field name containing the raw JSON string.\n26\t field: String,\n27\t /// Destination field (empty ⇒ merge into root).\n28\t target: String,\n29\t}\n30\t\n31\timpl JsonParsePlugin {\n32\t pub fn new(field: impl Into<String>, target: impl Into<String>) -> Self {\n33\t Self {\n34\t field: field.into(),\n35\t target: target.into(),\n36\t }\n37\t }\n38\t}\n39\t\n40\timpl TransformPlugin for JsonParsePlugin {\n41\t fn name(&self) -> &str {\n42\t \"json_parse\"\n43\t }\n44\t\n45\t fn process(&self, doc: &mut Value) -> ProcessAction {\n46\t let raw = match doc.get(&self.field).and_then(Value::as_str) {\n47\t Some(s) => s.to_owned(),\n48\t None => return ProcessAction::Pass,\n49\t };\n50\t\n51\t match serde_json::from_str::<Value>(&raw) {\n52\t Ok(parsed) => {\n53\t // Remove source field.\n54\t if let Some(obj) = doc.as_object_mut() {\n55\t obj.remove(&self.field);\n56\t }\n57\t\n58\t if self.target.is_empty() {\n59\t // Merge into root.\n60\t if let (Some(root), Some(parsed_obj)) =\n61\t (doc.as_object_mut(), parsed.as_object())\n62\t {\n63\t for (k, v) in parsed_obj {\n64\t root.insert(k.clone(), v.clone());\n65\t }\n66\t }\n67\t } else {\n68\t doc[&self.target] = parsed;\n69\t }\n70\t ProcessAction::Pass\n71\t }\n72\t Err(e) => {\n73\t debug!(field = self.field.as_str(), error = %e, \"json_parse: failed to parse field\");\n74\t ProcessAction::Pass // leave doc unchanged on parse failure\n75\t }\n76\t }\n77\t }\n78\t}\n79\t\n80\t// ─────────────────────────────────────────────────────────────────────────────\n81\t// TimestampParsePlugin\n82\t// ─────────────────────────────────────────────────────────────────────────────\n83\t\n84\t/// Parse a timestamp string into ISO 8601 format.\n85\t///\n86\t/// Supported input formats (tried in order):\n87\t/// 1. Unix epoch seconds (integer or float string)\n88\t/// 2. User-provided format strings (passed verbatim to `chrono`)\n89\t/// 3. Common formats: `%Y-%m-%dT%H:%M:%S%.f%z`, `%Y-%m-%d %H:%M:%S`,\n90\t/// `%d/%b/%Y:%H:%M:%S %z` (Apache/nginx), RFC 2822, RFC 3339\n91\tpub struct TimestampParsePlugin {\n92\t /// Source field containing the raw timestamp string.\n93\t field: String,\n94\t /// Extra format strings (chrono strftime syntax).\n95\t formats: Vec<String>,\n96\t /// Destination field (defaults to `@timestamp` when `None`).\n97\t target: Option<String>,\n98\t}\n99\t\n100\timpl TimestampParsePlugin {\n101\t pub fn new(field: impl Into<String>, formats: Vec<String>, target: Option<String>) -> Self {\n102\t Self {\n103\t field: field.into(),\n104\t formats,\n105\t target,\n106\t }\n107\t }\n108\t\n109\t fn target_field(&self) -> &str {\n110\t self.target.as_deref().unwrap_or(\"@timestamp\")\n111\t }\n112\t}\n113\t\n114\timpl TransformPlugin for TimestampParsePlugin {\n115\t fn name(&self) -> &str {\n116\t \"timestamp_parse\"\n117\t }\n118\t\n119\t fn process(&self, doc: &mut Value) -> ProcessAction {\n120\t let raw = match doc.get(&self.field) {\n121\t Some(Value::String(s)) => s.clone(),\n122\t Some(Value::Number(n)) => n.to_string(),\n123\t _ => return ProcessAction::Pass,\n124\t };\n125\t\n126\t // Try unix epoch (integer seconds).\n127\t if let Ok(epoch) = raw.trim().parse::<i64>() {\n128\t use chrono::{TimeZone, Utc};\n129\t let dt = Utc.timestamp_opt(epoch, 0).single();\n130\t if let Some(dt) = dt {\n131\t let iso = dt.to_rfc3339();\n132\t doc[self.target_field()] = Value::String(iso);\n133\t return ProcessAction::Pass;\n134\t }\n135\t }\n136\t\n137\t // Try unix epoch float.\n138\t if let Ok(epoch_f) = raw.trim().parse::<f64>() {\n139\t use chrono::{TimeZone, Utc};\n140\t let secs = epoch_f as i64;\n141\t let nanos = ((epoch_f.fract()) * 1_000_000_000.0) as u32;\n142\t let dt = Utc.timestamp_opt(secs, nanos).single();\n143\t if let Some(dt) = dt {\n144\t let iso = dt.to_rfc3339();\n145\t doc[self.target_field()] = Value::String(iso);\n146\t return ProcessAction::Pass;\n147\t }\n148\t }\n149\t\n150\t // Try user-supplied formats.\n151\t for fmt in &self.formats {\n152\t if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&raw, fmt) {\n153\t use chrono::TimeZone;\n154\t let utc = chrono::Utc.from_utc_datetime(&dt);\n155\t doc[self.target_field()] = Value::String(utc.to_rfc3339());\n156\t return ProcessAction::Pass;\n157\t }\n158\t }\n159\t\n160\t // Try RFC 3339 / ISO 8601 (chrono's built-in parser).\n161\t if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&raw) {\n162\t doc[self.target_field()] = Value::String(dt.to_rfc3339());\n163\t return ProcessAction::Pass;\n164\t }\n165\t\n166\t // Try RFC 2822.\n167\t if let Ok(dt) = chrono::DateTime::parse_from_rfc2822(&raw) {\n168\t doc[self.target_field()] = Value::String(dt.to_rfc3339());\n169\t return ProcessAction::Pass;\n170\t }\n171\t\n172\t // Try Apache/nginx combined log format: \"10/Apr/2026:12:00:00 +0000\"\n173\t if let Ok(dt) = chrono::DateTime::parse_from_str(&raw, \"%d/%b/%Y:%H:%M:%S %z\") {\n174\t doc[self.target_field()] = Value::String(dt.to_rfc3339());\n175\t return ProcessAction::Pass;\n176\t }\n177\t\n178\t // Try \"YYYY-MM-DD HH:MM:SS\"\n179\t if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(&raw, \"%Y-%m-%d %H:%M:%S\") {\n180\t use chrono::TimeZone;\n181\t let utc = chrono::Utc.from_utc_datetime(&dt);\n182\t doc[self.target_field()] = Value::String(utc.to_rfc3339());\n183\t return ProcessAction::Pass;\n184\t }\n185\t\n186\t debug!(\n187\t field = self.field.as_str(),\n188\t raw = raw.as_str(),\n189\t \"timestamp_parse: no format matched\"\n190\t );\n191\t ProcessAction::Pass\n192\t }\n193\t}\n194\t\n195\t// ─────────────────────────────────────────────────────────────────────────────\n196\t// FieldRenamePlugin\n197\t// ─────────────────────────────────────────────────────────────────────────────\n198\t\n199\t/// Rename document fields.\n200\t///\n201\t/// `mappings` maps `old_name → new_name`. Fields not present in the document\n202\t/// are silently skipped.\n203\tpub struct FieldRenamePlugin {\n204\t mappings: HashMap<String, String>,\n205\t}\n206\t\n207\timpl FieldRenamePlugin {\n208\t pub fn new(mappings: HashMap<String, String>) -> Self {\n209\t Self { mappings }\n210\t }\n211\t}\n212\t\n213\timpl TransformPlugin for FieldRenamePlugin {\n214\t fn name(&self) -> &str {\n215\t \"field_rename\"\n216\t }\n217\t\n218\t fn process(&self, doc: &mut Value) -> ProcessAction {\n219\t if let Some(obj) = doc.as_object_mut() {\n220\t for (old, new) in &self.mappings {\n221\t if let Some(val) = obj.remove(old.as_str()) {\n222\t obj.insert(new.clone(), val);\n223\t }\n224\t }\n225\t }\n226\t ProcessAction::Pass\n227\t }\n228\t}\n229\t\n230\t// ─────────────────────────────────────────────────────────────────────────────\n231\t// DropFieldPlugin\n232\t// ─────────────────────────────────────────────────────────────────────────────\n233\t\n234\t/// Remove one or more fields from a document.\n235\tpub struct DropFieldPlugin {\n236\t fields: Vec<String>,\n237\t}\n238\t\n239\timpl DropFieldPlugin {\n240\t pub fn new(fields: Vec<String>) -> Self {\n241\t Self { fields }\n242\t }\n243\t}\n244\t\n245\timpl TransformPlugin for DropFieldPlugin {\n246\t fn name(&self) -> &str {\n247\t \"drop_field\"\n248\t }\n249\t\n250\t fn process(&self, doc: &mut Value) -> ProcessAction {\n251\t if let Some(obj) = doc.as_object_mut() {\n252\t for field in &self.fields {\n253\t obj.remove(field.as_str());\n254\t }\n255\t }\n256\t ProcessAction::Pass\n257\t }\n258\t}\n259\t\n260\t// ─────────────────────────────────────────────────────────────────────────────\n261\t// AddFieldPlugin\n262\t// ─────────────────────────────────────────────────────────────────────────────\n263\t\n264\t/// Add a static field (or overwrite an existing one) with a fixed value.\n265\tpub struct AddFieldPlugin {\n266\t field: String,\n267\t value: Value,\n268\t}\n269\t\n270\timpl AddFieldPlugin {\n271\t pub fn new(field: impl Into<String>, value: Value) -> Self {\n272\t Self {\n273\t field: field.into(),\n274\t value,\n275\t }\n276\t }\n277\t}\n278\t\n279\timpl TransformPlugin for AddFieldPlugin {\n280\t fn name(&self) -> &str {\n281\t \"add_field\"\n282\t }\n283\t\n284\t fn process(&self, doc: &mut Value) -> ProcessAction {\n285\t doc[&self.field] = self.value.clone();\n286\t ProcessAction::Pass\n287\t }\n288\t}\n289\t\n290\t// ─────────────────────────────────────────────────────────────────────────────\n291\t// RoutePlugin\n292\t// ─────────────────────────────────────────────────────────────────────────────\n293\t\n294\t/// Route a document to a different target index based on a field value.\n295\t///\n296\t/// Looks up `doc[field]` in the `routes` map. If a match is found, returns\n297\t/// [`ProcessAction::Route`] with the target index name. Falls back to the\n298\t/// `default` index if configured; otherwise returns [`ProcessAction::Pass`].\n299\tpub struct RoutePlugin {\n300\t /// Field to inspect.\n301\t field: String,\n302\t /// Field value → target index name.\n303\t routes: HashMap<String, String>,\n304\t /// Fallback target (used when no route matches).\n305\t default: Option<String>,\n306\t}\n307\t\n308\timpl RoutePlugin {\n309\t pub fn new(\n310\t field: impl Into<String>,\n311\t routes: HashMap<String, String>,\n312\t default: Option<String>,\n313\t ) -> Self {\n314\t Self {\n315\t field: field.into(),\n316\t routes,\n317\t default,\n318\t }\n319\t }\n320\t}\n321\t\n322\timpl TransformPlugin for RoutePlugin {\n323\t fn name(&self) -> &str {\n324\t \"route\"\n325\t }\n326\t\n327\t fn process(&self, doc: &mut Value) -> ProcessAction {\n328\t let key = match doc.get(&self.field).and_then(Value::as_str) {\n329\t Some(v) => v.to_owned(),\n330\t None => {\n331\t return self\n332\t .default\n333\t .as_ref()\n334\t .map(|d| ProcessAction::Route(d.clone()))\n335\t .unwrap_or(ProcessAction::Pass);\n336\t }\n337\t };\n338\t\n339\t if let Some(target) = self.routes.get(&key) {\n340\t ProcessAction::Route(target.clone())\n341\t } else if let Some(default) = &self.default {\n342\t ProcessAction::Route(default.clone())\n343\t } else {\n344\t ProcessAction::Pass\n345\t }\n346\t }\n347\t}\n348\t\n349\t// ─────────────────────────────────────────────────────────────────────────────\n350\t// GrokPlugin\n351\t// ─────────────────────────────────────────────────────────────────────────────\n352\t\n353\t/// Parse unstructured log text using Grok-style named patterns.\n354\t///\n355\t/// Supported pattern names:\n356\t/// - `NGINX_COMBINED` — standard nginx combined log format\n357\t/// - `APACHE_COMBINED` — Apache httpd combined log format\n358\t/// - `SYSLOG` — RFC 3164 syslog line\n359\t/// - `POSTGRESQL` — PostgreSQL log line\n360\t///\n361\t/// Extracted fields are merged into the root document.\n362\tpub struct GrokPlugin {\n363\t /// Field containing the raw log line.\n364\t field: String,\n365\t /// Grok pattern name (e.g. `\"NGINX_COMBINED\"`).\n366\t pattern_name: String,\n367\t /// Compiled regex derived from the pattern.\n368\t regex: Regex,\n369\t /// Named capture group names in the order they appear in the regex.\n370\t capture_names: Vec<Option<String>>,\n371\t}\n372\t\n373\timpl GrokPlugin {\n374\t pub fn new(field: impl Into<String>, pattern_name: impl Into<String>) -> Self {\n375\t let pattern_name = pattern_name.into();\n376\t let (regex_str, _) = grok_pattern(&pattern_name);\n377\t let regex = Regex::new(regex_str).expect(\"built-in grok pattern must compile\");\n378\t let capture_names: Vec<Option<String>> = regex\n379\t .capture_names()\n380\t .map(|n| n.map(str::to_string))\n381\t .collect();\n382\t\n383\t Self {\n384\t field: field.into(),\n385\t pattern_name,\n386\t regex,\n387\t capture_names,\n388\t }\n389\t }\n390\t}\n391\t\n392\timpl TransformPlugin for GrokPlugin {\n393\t fn name(&self) -> &str {\n394\t \"grok\"\n395\t }\n396\t\n397\t fn process(&self, doc: &mut Value) -> ProcessAction {\n398\t let text = match doc.get(&self.field).and_then(Value::as_str) {\n399\t Some(s) => s.to_owned(),\n400\t None => return ProcessAction::Pass,\n401\t };\n402\t\n403\t if let Some(caps) = self.regex.captures(&text) {\n404\t if let Some(obj) = doc.as_object_mut() {\n405\t for name in self.capture_names.iter().flatten() {\n406\t if let Some(m) = caps.name(name) {\n407\t obj.insert(name.clone(), Value::String(m.as_str().to_string()));\n408\t }\n409\t }\n410\t }\n411\t } else {\n412\t debug!(\n413\t field = self.field.as_str(),\n414\t pattern = self.pattern_name.as_str(),\n415\t \"grok: pattern did not match\"\n416\t );\n417\t }\n418\t\n419\t ProcessAction::Pass\n420\t }\n421\t}\n422\t\n423\t/// Built-in grok pattern names accepted by the `grok` stage.\n424\t///\n425\t/// `GENERIC` is the explicit opt-in for the catch-everything-as-`message`\n426\t/// pattern. It used to be reachable by *typo*: `grok_pattern` fell through to\n427\t/// it for any unrecognised name, so `\"pattern\": \"NGINX_COMBINE\"` compiled\n428\t/// happily and then extracted exactly one field (`message`) out of every\n429\t/// access log line — an accepted-and-ignored configuration (issue #204).\n430\t/// `build_plugin` now rejects names outside this list, so the generic pattern\n431\t/// is only ever used when it was actually asked for.\n432\tpub const GROK_PATTERN_NAMES: &[&str] = &[\n433\t \"NGINX_COMBINED\",\n434\t \"APACHE_COMBINED\",\n435\t \"SYSLOG\",\n436\t \"POSTGRESQL\",\n437\t \"GENERIC\",\n438\t];\n439\t\n440\t/// Returns `(regex_str, field_names)` for a built-in grok pattern.\n441\tfn grok_pattern(name: &str) -> (&'static str, &'static [&'static str]) {\n442\t match name {\n443\t \"NGINX_COMBINED\" | \"APACHE_COMBINED\" => (\n444\t r#\"^(?P<remote_addr>\\S+) - (?P<remote_user>\\S+) \\[(?P<time_local>[^\\]]+)\\] \"(?P<method>\\S+) (?P<request_uri>\\S+) (?P<http_version>[^\"]+)\" (?P<status>\\d{3}) (?P<body_bytes_sent>\\d+) \"(?P<http_referer>[^\"]*)\" \"(?P<http_user_agent>[^\"]*)\"#,\n445\t &[\n446\t \"remote_addr\",\n447\t \"remote_user\",\n448\t \"time_local\",\n449\t \"method\",\n450\t \"request_uri\",\n451\t \"http_version\",\n452\t \"status\",\n453\t \"body_bytes_sent\",\n454\t \"http_referer\",\n455\t \"http_user_agent\",\n456\t ],\n457\t ),\n458\t \"SYSLOG\" => (\n459\t r#\"^(?P<syslog_timestamp>\\w{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2}) (?P<hostname>\\S+) (?P<program>[^\\[:]+)(?:\\[(?P<pid>\\d+)\\])?: (?P<message>.+)$\"#,\n460\t &[\"syslog_timestamp\", \"hostname\", \"program\", \"pid\", \"message\"],\n461\t ),\n462\t \"POSTGRESQL\" => (\n463\t r#\"^(?P<log_time>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d+ \\w+) \\[(?P<pid>\\d+)\\] (?P<user_name>\\S+)@(?P<database_name>\\S+) (?P<severity>\\w+): (?P<message>.+)$\"#,\n464\t &[\n465\t \"log_time\",\n466\t \"pid\",\n467\t \"user_name\",\n468\t \"database_name\",\n469\t \"severity\",\n470\t \"message\",\n471\t ],\n472\t ),\n473\t // \"GENERIC\" (and, defensively, anything that slipped past\n474\t // `build_plugin`'s allow-list): capture everything as `message`.\n475\t _ => (r#\"^(?P<message>.+)$\"#, &[\"message\"]),\n476\t }\n477\t}\n478\t\n479\t// ─────────────────────────────────────────────────────────────────────────────\n480\t// PiiRedactionPlugin\n481\t// ─────────────────────────────────────────────────────────────────────────────\n482\t\n483\t/// Redact PII from string fields in a document.\n484\t///\n485\t/// Supported PII types:\n486\t/// - `email` — e.g. `[email protected]` → `[REDACTED_EMAIL]`\n487\t/// - `ip` — IPv4 and IPv6 addresses → `[REDACTED_IP]`\n488\t/// - `credit_card` — 13–19 digit numbers with optional separators →\n489\t/// `[REDACTED_CC]`\n490\t/// - `ssn` — US Social Security Numbers (`NNN-NN-NNNN`) → `[REDACTED_SSN]`\n491\t/// - `phone` — common phone number patterns → `[REDACTED_PHONE]`\n492\tpub struct PiiRedactionPlugin {\n493\t /// Compiled `(regex, replacement)` pairs.\n494\t patterns: Vec<(Regex, &'static str)>,\n495\t}\n496\t\n497\t/// PII type names this plugin knows how to redact.\n498\t///\n499\t/// A name outside this list used to be accepted and then quietly matched\n500\t/// nothing: `PiiRedactionPlugin::new(vec![\"social_security\".into()])` compiled\n501\t/// to an EMPTY pattern set, so the stage ran on every document, redacted\n502\t/// nothing, and reported success — unredacted PII in the index with no signal\n503\t/// anywhere (issue #204). `build_plugin` now rejects unknown names at\n504\t/// pipeline-creation time.\n505\tpub const PII_TYPE_NAMES: &[&str] = &[\"email\", \"ip\", \"credit_card\", \"ssn\", \"phone\"];\n506\t\n507\timpl PiiRedactionPlugin {\n508\t /// Build a new plugin that redacts the given PII types.\n509\t ///\n510\t /// `types` is a list of strings from [`PII_TYPE_NAMES`]. An empty list\n511\t /// enables all types. Callers must validate the names first (see\n512\t /// `build_plugin`) — an unknown name silently contributes no pattern.\n513\t pub fn new(types: Vec<String>) -> Self {\n514\t let all = types.is_empty();\n515\t\n516\t let mut patterns = Vec::new();\n517\t\n518\t let wants = |t: &str| all || types.iter().any(|s| s == t);\n519\t\n520\t if wants(\"email\") {\n521\t patterns.push((\n522\t Regex::new(r\"(?i)[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}\").unwrap(),\n523\t \"[REDACTED_EMAIL]\",\n524\t ));\n525\t }\n526\t if wants(\"ip\") {\n527\t // IPv4\n528\t patterns.push((\n529\t Regex::new(r\"\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b\").unwrap(),\n530\t \"[REDACTED_IP]\",\n531\t ));\n532\t // IPv6 (simplified)\n533\t patterns.push((\n534\t Regex::new(r\"(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\").unwrap(),\n535\t \"[REDACTED_IP]\",\n536\t ));\n537\t }\n538\t if wants(\"credit_card\") {\n539\t patterns.push((\n540\t Regex::new(r\"\\b(?:\\d[ \\-]?){13,19}\\b\").unwrap(),\n541\t \"[REDACTED_CC]\",\n542\t ));\n543\t }\n544\t if wants(\"ssn\") {\n545\t patterns.push((\n546\t Regex::new(r\"\\b\\d{3}-\\d{2}-\\d{4}\\b\").unwrap(),\n547\t \"[REDACTED_SSN]\",\n548\t ));\n549\t }\n550\t if wants(\"phone\") {\n551\t patterns.push((\n552\t Regex::new(r\"\\b(?:\\+?1[-.\\s]?)?\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}\\b\").unwrap(),\n553\t \"[REDACTED_PHONE]\",\n554\t ));\n555\t }\n556\t\n557\t Self { patterns }\n558\t }\n559\t\n560\t /// Redact PII from a single string.\n561\t fn redact_str(&self, s: &str) -> String {\n562\t let mut result = s.to_string();\n563\t for (re, replacement) in &self.patterns {\n564\t result = re.replace_all(&result, *replacement).into_owned();\n565\t }\n566\t result\n567\t }\n568\t\n569\t /// Recursively redact all string values in a JSON value.\n570\t fn redact_value(&self, v: &mut Value) {\n571\t match v {\n572\t Value::String(s) => {\n573\t *s = self.redact_str(s);\n574\t }\n575\t Value::Object(obj) => {\n576\t for val in obj.values_mut() {\n577\t self.redact_value(val);\n578\t }\n579\t }\n580\t Value::Array(arr) => {\n581\t for item in arr.iter_mut() {\n582\t self.redact_value(item);\n583\t }\n584\t }\n585\t _ => {}\n586\t }\n587\t }\n588\t}\n589\t\n590\timpl TransformPlugin for PiiRedactionPlugin {\n591\t fn name(&self) -> &str {\n592\t \"pii_redaction\"\n593\t }\n594\t\n595\t fn process(&self, doc: &mut Value) -> ProcessAction {\n596\t self.redact_value(doc);\n597\t ProcessAction::Pass\n598\t }\n599\t}\n600\t\n601\t// ─────────────────────────────────────────────────────────────────────────────\n602\t// CopyFieldPlugin\n603\t// ─────────────────────────────────────────────────────────────────────────────\n604\t\n605\t/// Copy the value of one field to another field.\n606\t///\n607\t/// The source field is left intact. If the source field does not exist the\n608\t/// document is passed through unchanged.\n609\tpub struct CopyFieldPlugin {\n610\t source: String,\n611\t target: String,\n612\t}\n613\t\n614\timpl CopyFieldPlugin {\n615\t pub fn new(source: impl Into<String>, target: impl Into<String>) -> Self {\n616\t Self {\n617\t source: source.into(),\n618\t target: target.into(),\n619\t }\n620\t }\n621\t}\n622\t\n623\timpl TransformPlugin for CopyFieldPlugin {\n624\t fn name(&self) -> &str {\n625\t \"copy_field\"\n626\t }\n627\t\n628\t fn process(&self, doc: &mut Value) -> ProcessAction {\n629\t if let Some(val) = doc.get(&self.source).cloned() {\n630\t doc[&self.target] = val;\n631\t }\n632\t ProcessAction::Pass\n633\t }\n634\t}\n635\t\n636\t// ─────────────────────────────────────────────────────────────────────────────\n637\t// ConvertTypePlugin\n638\t// ─────────────────────────────────────────────────────────────────────────────\n639\t\n640\t/// Target types the `convert` stage can produce.\n641\t///\n642\t/// An unknown target type used to be accepted at pipeline-creation time and\n643\t/// then hit `_ => None` per document: the field was left exactly as it was and\n644\t/// the document passed. `\"type\": \"int\"` (instead of `\"integer\"`) therefore\n645\t/// produced a pipeline that acknowledged the conversion and never performed it\n646\t/// (issue #204). `build_plugin` now rejects unknown target types.\n647\tpub const CONVERT_TARGET_TYPES: &[&str] = &[\"integer\", \"float\", \"string\", \"boolean\"];\n648\t\n649\t/// Convert a field's value to a different type.\n650\t///\n651\t/// Supported target types are [`CONVERT_TARGET_TYPES`]; an unknown one is\n652\t/// rejected when the pipeline is created. If the *value* cannot be coerced\n653\t/// (e.g. `\"abc\"` to `integer`) the document is passed through unchanged — a\n654\t/// per-document data condition, not a configuration error. (ES's `convert`\n655\t/// processor fails the document instead; that divergence is pre-existing and\n656\t/// out of scope for the #204 sweep.)\n657\tpub struct ConvertTypePlugin {\n658\t field: String,\n659\t target_type: String,\n660\t}\n661\t\n662\timpl ConvertTypePlugin {\n663\t pub fn new(field: impl Into<String>, target_type: impl Into<String>) -> Self {\n664\t Self {\n665\t field: field.into(),\n666\t target_type: target_type.into(),\n667\t }\n668\t }\n669\t}\n670\t\n671\timpl TransformPlugin for ConvertTypePlugin {\n672\t fn name(&self) -> &str {\n673\t \"convert\"\n674\t }\n675\t\n676\t fn process(&self, doc: &mut Value) -> ProcessAction {\n677\t let current = match doc.get(&self.field).cloned() {\n678\t Some(v) => v,\n679\t None => return ProcessAction::Pass,\n680\t };\n681\t\n682\t let converted = match self.target_type.as_str() {\n683\t \"integer\" => {\n684\t let n = match ¤t {\n685\t Value::Number(n) => n.as_i64(),\n686\t Value::String(s) => s.trim().parse::<i64>().ok(),\n687\t Value::Bool(b) => Some(if *b { 1 } else { 0 }),\n688\t _ => None,\n689\t };\n690\t n.map(|i| Value::Number(serde_json::Number::from(i)))\n691\t }\n692\t \"float\" => {\n693\t let f = match ¤t {\n694\t Value::Number(n) => n.as_f64(),\n695\t Value::String(s) => s.trim().parse::<f64>().ok(),\n696\t Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),\n697\t _ => None,\n698\t };\n699\t f.and_then(|f| serde_json::Number::from_f64(f).map(Value::Number))\n700\t }\n701\t \"string\" => {\n702\t let s = match ¤t {\n703\t Value::String(s) => Some(s.clone()),\n704\t Value::Number(n) => Some(n.to_string()),\n705\t Value::Bool(b) => Some(b.to_string()),\n706\t Value::Null => Some(\"null\".to_string()),\n707\t _ => None,\n708\t };\n709\t s.map(Value::String)\n710\t }\n711\t \"boolean\" => {\n712\t let b = match ¤t {\n713\t Value::Bool(b) => Some(*b),\n714\t Value::String(s) => match s.to_lowercase().as_str() {\n715\t \"true\" | \"1\" | \"yes\" | \"on\" => Some(true),\n716\t \"false\" | \"0\" | \"no\" | \"off\" => Some(false),\n717\t _ => None,\n718\t },\n719\t Value::Number(n) => n.as_i64().map(|i| i != 0),\n720\t _ => None,\n721\t };\n722\t b.map(Value::Bool)\n723\t }\n724\t _ => None,\n725\t };\n726\t\n727\t if let Some(v) = converted {\n728\t doc[&self.field] = v;\n729\t }\n730\t ProcessAction::Pass\n731\t }\n732\t}\n733\t\n734\t// ─────────────────────────────────────────────────────────────────────────────\n735\t// SplitPlugin\n736\t// ─────────────────────────────────────────────────────────────────────────────\n737\t\n738\t/// Split a string field into an array using a separator.\n739\t///\n740\t/// The original string value is replaced with a JSON array of trimmed parts.\n741\t/// If the field is missing or not a string, the document passes through\n742\t/// unchanged.\n743\tpub struct SplitPlugin {\n744\t field: String,\n745\t separator: String,\n746\t}\n747\t\n748\timpl SplitPlugin {\n749\t pub fn new(field: impl Into<String>, separator: impl Into<String>) -> Self {\n750\t Self {\n751\t field: field.into(),\n752\t separator: separator.into(),\n753\t }\n754\t }\n755\t}\n756\t\n757\timpl TransformPlugin for SplitPlugin {\n758\t fn name(&self) -> &str {\n759\t \"split\"\n760\t }\n761\t\n762\t fn process(&self, doc: &mut Value) -> ProcessAction {\n763\t let s = match doc.get(&self.field).and_then(Value::as_str) {\n764\t Some(s) => s.to_owned(),\n765\t None => return ProcessAction::Pass,\n766\t };\n767\t let parts: Vec<Value> = s\n768\t .split(self.separator.as_str())\n769\t .map(|p| Value::String(p.trim().to_string()))\n770\t .collect();\n771\t doc[&self.field] = Value::Array(parts);\n772\t ProcessAction::Pass\n773\t }\n774\t}\n775\t\n776\t// ─────────────────────────────────────────────────────────────────────────────\n777\t// LowercasePlugin\n778\t// ─────────────────────────────────────────────────────────────────────────────\n779\t\n780\t/// Lowercase the string value of a field.\n781\tpub struct LowercasePlugin {\n782\t field: String,\n783\t}\n784\t\n785\timpl LowercasePlugin {\n786\t pub fn new(field: impl Into<String>) -> Self {\n787\t Self {\n788\t field: field.into(),\n789\t }\n790\t }\n791\t}\n792\t\n793\timpl TransformPlugin for LowercasePlugin {\n794\t fn name(&self) -> &str {\n795\t \"lowercase\"\n796\t }\n797\t\n798\t fn process(&self, doc: &mut Value) -> ProcessAction {\n799\t if let Some(Value::String(s)) = doc.get_mut(&self.field) {\n800\t *s = s.to_lowercase();\n801\t }\n802\t ProcessAction::Pass\n803\t }\n804\t}\n805\t\n806\t// ─────────────────────────────────────────────────────────────────────────────\n807\t// UppercasePlugin\n808\t// ─────────────────────────────────────────────────────────────────────────────\n809\t\n810\t/// Uppercase the string value of a field.\n811\tpub struct UppercasePlugin {\n812\t field: String,\n813\t}\n814\t\n815\timpl UppercasePlugin {\n816\t pub fn new(field: impl Into<String>) -> Self {\n817\t Self {\n818\t field: field.into(),\n819\t }\n820\t }\n821\t}\n822\t\n823\timpl TransformPlugin for UppercasePlugin {\n824\t fn name(&self) -> &str {\n825\t \"uppercase\"\n826\t }\n827\t\n828\t fn process(&self, doc: &mut Value) -> ProcessAction {\n829\t if let Some(Value::String(s)) = doc.get_mut(&self.field) {\n830\t *s = s.to_uppercase();\n831\t }\n832\t ProcessAction::Pass\n833\t }\n834\t}\n835\t\n836\t// ─────────────────────────────────────────────────────────────────────────────\n837\t// SetPlugin\n838\t// ─────────────────────────────────────────────────────────────────────────────\n839\t\n840\t/// Set a field to a value, optionally only if the field does not already exist.\n841\t///\n842\t/// When `override_existing` is `false` (the default), the field is only set if\n843\t/// it is absent from the document (or its value is `null`). When `true` the\n844\t/// field is always overwritten — equivalent to [`AddFieldPlugin`].\n845\tpub struct SetPlugin {\n846\t field: String,\n847\t value: Value,\n848\t override_existing: bool,\n849\t}\n850\t\n851\timpl SetPlugin {\n852\t pub fn new(field: impl Into<String>, value: Value, override_existing: bool) -> Self {\n853\t Self {\n854\t field: field.into(),\n855\t value,\n856\t override_existing,\n857\t }\n858\t }\n859\t}\n860\t\n861\timpl TransformPlugin for SetPlugin {\n862\t fn name(&self) -> &str {\n863\t \"set\"\n864\t }\n865\t\n866\t fn process(&self, doc: &mut Value) -> ProcessAction {\n867\t let exists = doc.get(&self.field).map(|v| !v.is_null()).unwrap_or(false);\n868\t\n869\t if self.override_existing || !exists {\n870\t doc[&self.field] = self.value.clone();\n871\t }\n872\t ProcessAction::Pass\n873\t }\n874\t}\n875\t\n876\t// ─────────────────────────────────────────────────────────────────────────────\n877\t// AppendPlugin\n878\t// ─────────────────────────────────────────────────────────────────────────────\n879\t\n880\t/// Append a value to a field, creating or widening a list as needed.\n881\t///\n882\t/// Elasticsearch's `append` semantics, which is what this exists for: the field\n883\t/// becomes a list if it is not one already, a list `value` extends rather than\n884\t/// nests, and a missing field is created as a single-element list\n885\t/// (`IngestDocument.appendFieldValue`, read for semantics only).\n886\t///\n887\t/// Issue #204: `append` used to be *mapped onto `set`* in the ES→xerj processor\n888\t/// translation (`es_compat.rs`), so `{\"append\": {\"field\": \"tags\", \"value\":\n889\t/// \"b\"}}` REPLACED `[\"a\"]` with `\"b\"` instead of producing `[\"a\", \"b\"]` —\n890\t/// under a `200 {\"acknowledged\": true}`, and disagreeing with the `_simulate`\n891\t/// interpreter, which has always implemented a real append. Two behaviours for\n892\t/// one pipeline; this is the one that runs at ingest.\n893\tpub struct AppendPlugin {\n894\t field: String,\n895\t value: Value,\n896\t}\n897\t\n898\timpl AppendPlugin {\n899\t pub fn new(field: impl Into<String>, value: Value) -> Self {\n900\t Self {\n901\t field: field.into(),\n902\t value,\n903\t }\n904\t }\n905\t}\n906\t\n907\timpl TransformPlugin for AppendPlugin {\n908\t fn name(&self) -> &str {\n909\t \"append\"\n910\t }\n911\t\n912\t fn process(&self, doc: &mut Value) -> ProcessAction {\n913\t let Some(obj) = doc.as_object_mut() else {\n914\t return ProcessAction::Pass;\n915\t };\n916\t let slot = obj\n917\t .entry(self.field.clone())\n918\t .or_insert_with(|| Value::Array(Vec::new()));\n919\t match slot {\n920\t Value::Array(existing) => match self.value.clone() {\n921\t Value::Array(more) => existing.extend(more),\n922\t one => existing.push(one),\n923\t },\n924\t scalar => {\n925\t let previous = scalar.clone();\n926\t let mut out = vec![previous];\n927\t match self.value.clone() {\n928\t Value::Array(more) => out.extend(more),\n929\t one => out.push(one),\n930\t }\n931\t *scalar = Value::Array(out);\n932\t }\n933\t }\n934\t ProcessAction::Pass\n935\t }\n936\t}\n937\t\n938\t// ─────────────────────────────────────────────────────────────────────────────\n939\t// RemoveNullPlugin\n940\t// ─────────────────────────────────────────────────────────────────────────────\n941\t\n942\t/// Remove all fields whose value is `null` or an empty string from the\n943\t/// top-level document object.\n944\tpub struct RemoveNullPlugin;\n945\t\n946\timpl TransformPlugin for RemoveNullPlugin {\n947\t fn name(&self) -> &str {\n948\t \"remove_null\"\n949\t }\n950\t\n951\t fn process(&self, doc: &mut Value) -> ProcessAction {\n952\t if let Some(obj) = doc.as_object_mut() {\n953\t obj.retain(|_, v| !v.is_null() && v != &Value::String(String::new()));\n954\t }\n955\t ProcessAction::Pass\n956\t }\n957\t}\n958\t\n959\t// ─────────────────────────────────────────────────────────────────────────────\n960\t// UrlDecodePlugin\n961\t// ─────────────────────────────────────────────────────────────────────────────\n962\t\n963\t/// URL-decode (percent-decode) the string value of a field.\n964\t///\n965\t/// `+` is decoded as a space. If the field is missing, not a string, or\n966\t/// decoding fails the document passes through unchanged.\n967\tpub struct UrlDecodePlugin {\n968\t field: String,\n969\t}\n970\t\n971\timpl UrlDecodePlugin {\n972\t pub fn new(field: impl Into<String>) -> Self {\n973\t Self {\n974\t field: field.into(),\n975\t }\n976\t }\n977\t\n978\t fn percent_decode(s: &str) -> Option<String> {\n979\t let mut out = Vec::with_capacity(s.len());\n980\t let bytes = s.as_bytes();\n981\t let mut i = 0;\n982\t while i < bytes.len() {\n983\t if bytes[i] == b'+' {\n984\t out.push(b' ');\n985\t i += 1;\n986\t } else if bytes[i] == b'%' && i + 2 < bytes.len() {\n987\t let hi = (bytes[i + 1] as char).to_digit(16)? as u8;\n988\t let lo = (bytes[i + 2] as char).to_digit(16)? as u8;\n989\t out.push(hi << 4 | lo);\n990\t i += 3;\n991\t } else {\n992\t out.push(bytes[i]);\n993\t i += 1;\n994\t }\n995\t }\n996\t String::from_utf8(out).ok()\n997\t }\n998\t}\n999\t\n1000\timpl TransformPlugin for UrlDecodePlugin {\n1001\t fn name(&self) -> &str {\n1002\t \"url_decode\"\n1003\t }\n1004\t\n1005\t fn process(&self, doc: &mut Value) -> ProcessAction {\n1006\t if let Some(Value::String(s)) = doc.get_mut(&self.field) {\n1007\t if let Some(decoded) = Self::percent_decode(s) {\n1008\t *s = decoded;\n1009\t }\n1010\t }\n1011\t ProcessAction::Pass\n1012\t }\n1013\t}\n1014\t\n1015\t// ─────────────────────────────────────────────────────────────────────────────\n1016\t// Tests\n1017\t// ─────────────────────────────────────────────────────────────────────────────\n1018\t\n1019\t#[cfg(test)]\n1020\tmod tests {\n1021\t use super::*;\n1022\t use serde_json::json;\n1023\t\n1024\t // ── JsonParsePlugin ──────────────────────────────────────────────────────\n1025\t\n1026\t #[test]\n1027\t fn json_parse_merges_into_root() {\n1028\t let plugin = JsonParsePlugin::new(\"raw\", \"\");\n1029\t let mut doc = json!({ \"raw\": r#\"{\"level\":\"info\",\"msg\":\"hi\"}\"# });\n1030\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1031\t assert_eq!(doc[\"level\"], \"info\");\n1032\t assert_eq!(doc[\"msg\"], \"hi\");\n1033\t assert!(doc.get(\"raw\").is_none(), \"source field should be removed\");\n1034\t }\n1035\t\n1036\t #[test]\n1037\t fn json_parse_stores_at_target() {\n1038\t let plugin = JsonParsePlugin::new(\"payload\", \"parsed\");\n1039\t let mut doc = json!({ \"payload\": r#\"{\"k\":\"v\"}\"# });\n1040\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1041\t assert_eq!(doc[\"parsed\"][\"k\"], \"v\");\n1042\t }\n1043\t\n1044\t #[test]\n1045\t fn json_parse_passes_on_invalid_json() {\n1046\t let plugin = JsonParsePlugin::new(\"raw\", \"\");\n1047\t let mut doc = json!({ \"raw\": \"not-json\" });\n1048\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1049\t // Field left untouched when parse fails.\n1050\t assert_eq!(doc[\"raw\"], \"not-json\");\n1051\t }\n1052\t\n1053\t #[test]\n1054\t fn json_parse_passes_when_field_missing() {\n1055\t let plugin = JsonParsePlugin::new(\"missing\", \"\");\n1056\t let mut doc = json!({ \"other\": 1 });\n1057\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1058\t }\n1059\t\n1060\t // ── TimestampParsePlugin ─────────────────────────────────────────────────\n1061\t\n1062\t #[test]\n1063\t fn timestamp_parse_iso8601() {\n1064\t let plugin = TimestampParsePlugin::new(\"ts\", vec![], None);\n1065\t let mut doc = json!({ \"ts\": \"2026-04-10T12:00:00Z\" });\n1066\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1067\t let ts = doc[\"@timestamp\"].as_str().unwrap();\n1068\t assert!(ts.contains(\"2026-04-10\"), \"got: {ts}\");\n1069\t }\n1070\t\n1071\t #[test]\n1072\t fn timestamp_parse_unix_epoch() {\n1073\t let plugin = TimestampParsePlugin::new(\"ts\", vec![], None);\n1074\t let mut doc = json!({ \"ts\": \"1744286400\" }); // 2025-04-10 UTC approx\n1075\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1076\t assert!(doc[\"@timestamp\"].is_string());\n1077\t }\n1078\t\n1079\t #[test]\n1080\t fn timestamp_parse_apache_format() {\n1081\t let plugin = TimestampParsePlugin::new(\"ts\", vec![], None);\n1082\t let mut doc = json!({ \"ts\": \"10/Apr/2026:12:00:00 +0000\" });\n1083\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1084\t let ts = doc[\"@timestamp\"].as_str().unwrap();\n1085\t assert!(ts.contains(\"2026-04-10\"), \"got: {ts}\");\n1086\t }\n1087\t\n1088\t #[test]\n1089\t fn timestamp_parse_custom_format() {\n1090\t let plugin = TimestampParsePlugin::new(\n1091\t \"ts\",\n1092\t vec![\"%Y/%m/%d %H:%M:%S\".into()],\n1093\t Some(\"event.created\".into()),\n1094\t );\n1095\t let mut doc = json!({ \"ts\": \"2026/04/10 08:30:00\" });\n1096\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1097\t let ts = doc[\"event.created\"].as_str().unwrap();\n1098\t assert!(ts.contains(\"2026-04-10\"), \"got: {ts}\");\n1099\t }\n1100\t\n1101\t // ── FieldRenamePlugin ────────────────────────────────────────────────────\n1102\t\n1103\t #[test]\n1104\t fn field_rename_basic() {\n1105\t let plugin = FieldRenamePlugin::new(\n1106\t [(\"old_name\".into(), \"new_name\".into())]\n1107\t .into_iter()\n1108\t .collect(),\n1109\t );\n1110\t let mut doc = json!({ \"old_name\": \"value\", \"other\": 1 });\n1111\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1112\t assert_eq!(doc[\"new_name\"], \"value\");\n1113\t assert!(doc.get(\"old_name\").is_none());\n1114\t assert_eq!(doc[\"other\"], 1);\n1115\t }\n1116\t\n1117\t #[test]\n1118\t fn field_rename_missing_field_no_op() {\n1119\t let plugin = FieldRenamePlugin::new(\n1120\t [(\"does_not_exist\".into(), \"target\".into())]\n1121\t .into_iter()\n1122\t .collect(),\n1123\t );\n1124\t let mut doc = json!({ \"a\": 1 });\n1125\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1126\t assert!(doc.get(\"target\").is_none());\n1127\t }\n1128\t\n1129\t // ── DropFieldPlugin ──────────────────────────────────────────────────────\n1130\t\n1131\t #[test]\n1132\t fn drop_field_removes_fields() {\n1133\t let plugin = DropFieldPlugin::new(vec![\"password\".into(), \"token\".into()]);\n1134\t let mut doc = json!({ \"user\": \"alice\", \"password\": \"secret\", \"token\": \"abc\" });\n1135\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1136\t assert!(doc.get(\"password\").is_none());\n1137\t assert!(doc.get(\"token\").is_none());\n1138\t assert_eq!(doc[\"user\"], \"alice\");\n1139\t }\n1140\t\n1141\t #[test]\n1142\t fn drop_field_missing_field_no_op() {\n1143\t let plugin = DropFieldPlugin::new(vec![\"missing\".into()]);\n1144\t let mut doc = json!({ \"a\": 1 });\n1145\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1146\t }\n1147\t\n1148\t // ── AddFieldPlugin ───────────────────────────────────────────────────────\n1149\t\n1150\t #[test]\n1151\t fn add_field_adds_new_field() {\n1152\t let plugin = AddFieldPlugin::new(\"env\", json!(\"production\"));\n1153\t let mut doc = json!({ \"msg\": \"hello\" });\n1154\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1155\t assert_eq!(doc[\"env\"], \"production\");\n1156\t }\n1157\t\n1158\t #[test]\n1159\t fn add_field_overwrites_existing() {\n1160\t let plugin = AddFieldPlugin::new(\"status\", json!(\"new\"));\n1161\t let mut doc = json!({ \"status\": \"old\" });\n1162\t plugin.process(&mut doc);\n1163\t assert_eq!(doc[\"status\"], \"new\");\n1164\t }\n1165\t\n1166\t // ── RoutePlugin ──────────────────────────────────────────────────────────\n1167\t\n1168\t #[test]\n1169\t fn route_matches_field_value() {\n1170\t let routes = [\n1171\t (\"error\".into(), \"logs-errors\".into()),\n1172\t (\"info\".into(), \"logs-info\".into()),\n1173\t ]\n1174\t .into_iter()\n1175\t .collect();\n1176\t let plugin = RoutePlugin::new(\"level\", routes, None);\n1177\t\n1178\t let mut doc = json!({ \"level\": \"error\", \"msg\": \"oops\" });\n1179\t assert_eq!(\n1180\t plugin.process(&mut doc),\n1181\t ProcessAction::Route(\"logs-errors\".into())\n1182\t );\n1183\t }\n1184\t\n1185\t #[test]\n1186\t fn route_fallback_to_default() {\n1187\t let plugin = RoutePlugin::new(\"level\", HashMap::new(), Some(\"logs-misc\".into()));\n1188\t let mut doc = json!({ \"level\": \"debug\" });\n1189\t assert_eq!(\n1190\t plugin.process(&mut doc),\n1191\t ProcessAction::Route(\"logs-misc\".into())\n1192\t );\n1193\t }\n1194\t\n1195\t #[test]\n1196\t fn route_pass_when_no_match_and_no_default() {\n1197\t let plugin = RoutePlugin::new(\"level\", HashMap::new(), None);\n1198\t let mut doc = json!({ \"level\": \"debug\" });\n1199\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1200\t }\n1201\t\n1202\t // ── GrokPlugin ───────────────────────────────────────────────────────────\n1203\t\n1204\t #[test]\n1205\t fn grok_nginx_combined() {\n1206\t let plugin = GrokPlugin::new(\"message\", \"NGINX_COMBINED\");\n1207\t let mut doc = json!({\n1208\t \"message\": r#\"192.168.1.1 - alice [10/Apr/2026:12:00:00 +0000] \"GET /index.html HTTP/1.1\" 200 1234 \"https://example.com\" \"Mozilla/5.0\"\"#\n1209\t });\n1210\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1211\t assert_eq!(doc[\"remote_addr\"], \"192.168.1.1\");\n1212\t assert_eq!(doc[\"status\"], \"200\");\n1213\t assert_eq!(doc[\"method\"], \"GET\");\n1214\t }\n1215\t\n1216\t #[test]\n1217\t fn grok_syslog() {\n1218\t let plugin = GrokPlugin::new(\"message\", \"SYSLOG\");\n1219\t let mut doc = json!({\n1220\t \"message\": \"Apr 10 12:00:00 myhost myapp[1234]: connection established\"\n1221\t });\n1222\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1223\t assert_eq!(doc[\"hostname\"], \"myhost\");\n1224\t assert_eq!(doc[\"program\"], \"myapp\");\n1225\t assert_eq!(doc[\"pid\"], \"1234\");\n1226\t }\n1227\t\n1228\t #[test]\n1229\t fn grok_no_match_passes_unchanged() {\n1230\t let plugin = GrokPlugin::new(\"message\", \"NGINX_COMBINED\");\n1231\t let mut doc = json!({ \"message\": \"totally unstructured text\" });\n1232\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1233\t // Original message should still be there.\n1234\t assert_eq!(doc[\"message\"], \"totally unstructured text\");\n1235\t }\n1236\t\n1237\t // ── PiiRedactionPlugin ───────────────────────────────────────────────────\n1238\t\n1239\t #[test]\n1240\t fn pii_redacts_email() {\n1241\t let plugin = PiiRedactionPlugin::new(vec![\"email\".into()]);\n1242\t let mut doc = json!({ \"msg\": \"contact [email protected] for info\" });\n1243\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1244\t let msg = doc[\"msg\"].as_str().unwrap();\n1245\t assert!(\n1246\t !msg.contains(\"[email protected]\"),\n1247\t \"email not redacted: {msg}\"\n1248\t );\n1249\t assert!(msg.contains(\"[REDACTED_EMAIL]\"), \"got: {msg}\");\n1250\t }\n1251\t\n1252\t #[test]\n1253\t fn pii_redacts_ipv4() {\n1254\t let plugin = PiiRedactionPlugin::new(vec![\"ip\".into()]);\n1255\t let mut doc = json!({ \"remote\": \"192.168.1.100 connected\" });\n1256\t assert_eq!(plugin.process(&mut doc), ProcessAction::Pass);\n1257\t let remote = doc[\"remote\"].as_str().unwrap();\n1258\t assert!(remote.contains(\"[REDACTED_IP]\"), \"got: {remote}\");\n1259\t }\n1260\t\n1261\t #[test]\n1262\t fn pii_redacts_multiple_types() {\n1263\t let plugin = PiiRedactionPlugin::new(vec![\"email\".into(), \"ip\".into()]);\n1264\t let mut doc = json!({\n1265\t \"msg\": \"[email protected] from 10.0.0.1\"\n1266\t });\n1267\t plugin.process(&mut doc);\n1268\t let msg = doc[\"msg\"].as_str().unwrap();\n1269\t assert!(!msg.contains(\"[email protected]\"));\n1270\t assert!(!msg.contains(\"10.0.0.1\"));\n1271\t }\n1272\t\n1273\t #[test]\n1274\t fn pii_redacts_nested_fields() {\n1275\t let plugin = PiiRedactionPlugin::new(vec![\"email\".into()]);\n1276\t let mut doc = json!({\n1277\t \"user\": {\n1278\t \"email\": \"[email protected]\",\n1279\t \"name\": \"Alice\"\n1280\t }\n1281\t });\n1282\t plugin.process(&mut doc);\n1283\t let email = doc[\"user\"][\"email\"].as_str().unwrap();\n1284\t assert!(email.contains(\"[REDACTED_EMAIL]\"), \"got: {email}\");\n1285\t assert_eq!(doc[\"user\"][\"name\"], \"Alice\");\n1286\t }\n1287\t\n1288\t #[test]\n1289\t fn pii_empty_types_redacts_all() {\n1290\t let plugin = PiiRedactionPlugin::new(vec![]);\n1291\t let mut doc = json!({ \"msg\": \"email: [email protected], ip: 1.2.3.4\" });\n1292\t plugin.process(&mut doc);\n1293\t let msg = doc[\"msg\"].as_str().unwrap();\n1294\t assert!(!msg.contains(\"[email protected]\"));\n1295\t assert!(!msg.contains(\"1.2.3.4\"));\n1296\t }\n1297\t}\n1298\t"}]},"uuid":"1903b4f3-cc21-47c5-8681-077122252068","timestamp":"2026-10-01T15:38:31.147Z","sourceToolAssistantUUID":"ef5a3c32-aa63-4fd2-90d2-04feed3c320f","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"1903b4f3-cc21-47c5-8681-077122252068","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025347ce771674b1c74425","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Now the builtins. Interesting things:\n1. `UrlDecodePlugin::percent_decode` — bounds check `i + 2 < bytes.len()` is wrong-ish (off-by-one: `%41` at end of string, i+2 == len-1, so `i+2 < len` fails, `%41` at the very end won't be decoded — that's a correctness nit not security). Also `String::from_utf8(out).ok()` returns None on invalid UTF-8 → passes through. No panic. Actually wait: `(bytes[i+1] as char).to_digit(16)?` — returns None from the function, so no panic.\n\nHmm, one thing: `to_digit(16)` on a non-ASCII char returns None. Fine.\n\n2. Timestamp parse: `Utc.timestamp_opt(epoch, 0)` — chrono returns None on out-of-range; `.single()` handles. `nanos` computed as `((epoch_f.fract()) * 1e9) as u32` — for NaN/huge, `as u32` saturates in Rust (no UB). OK.\n\n3. Regex patterns are all constants — no doc-supplied regex. The PII credit_card regex `\\b(?:\\d[ \\-]?){13,19}\\b` — bounded repetition, regex crate is linear-time, no catastrophic backtracking (Rust regex guarantees no catastrophic backtracking). So no ReDoS in the regex crate. Note: regex crate is finite automata — safe.\n\nBut: `regex::Regex::new` is called at compile time of the plugin. Note `yaml_like_count` in sniff.rs calls `Regex::new` per invocation — that's a perf issue on every call, not a security issue (though it's in the hot path for sniffing every file — actually it's called from `classify_text` → `yaml_line_ratio` and the frontmatter path. Compiling a regex per file. Perf only.)\n\nNow, the PII `redact_value` recursion is recursive over JSON depth — deeply nested JSON from a doc could cause stack overflow. serde_json's default recursion limit for `from_str` is 128 levels, so a document parsed by serde_json is bounded... unless the doc is built programmatically. Actually serde_json has `RECURSION_LIMIT = 128` by default for both from_str and from_reader. So nesting is capped at 128 on parse. But what about JsonParsePlugin merging parsed JSON into root — capped at 128 each time, but a pipeline could repeatedly nest? Only one parse stage. Low.\n\nLet me now check who calls the pipeline with untrusted documents — search xerj-engine for pipeline process calls. And look at the autoindex extract paths (docx zip handling, pdf) since ingest of untrusted documents is the focus.\n\nLet's check:\n- xerj-autoindex/src/extract/docx.rs (zip handling — zip slip? They use `z.by_index_raw` in sniff; in docx.rs let's check)\n- Also `walk.rs` symlink handling, `harvest/pack.rs` (packing archives?), `objsource.rs` (S3 download paths).\n- `state.rs` content-addressed blob writes: `blobs/00000000` — path from hash, fine.\n\nLet me grep for the interesting patterns.","signature":"6e335262d0dc4b87b9f538fe"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"3e1992fd-c507-4eb0-aec8-d36ddf588259","timestamp":"2026-10-01T15:38:55.529Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"3e1992fd-c507-4eb0-aec8-d36ddf588259","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025347ce771674b1c74425","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"text","text":"Now let me examine the autoindex extraction and archive handling, plus find who calls these pipeline functions."}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"7769876f-fdd6-4c9f-80ba-1ebf86333511","timestamp":"2026-10-01T15:38:55.531Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7769876f-fdd6-4c9f-80ba-1ebf86333511","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025347ce771674b1c74425","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_6afebec78bfc446dbba8550d","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex && grep -rn \"ZipArchive\\|by_index\\|enclosed_name\\|mangled_name\\|zip::\" src/ | head -40","description":"Find zip handling in autoindex"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"868f9725-503b-4a89-af11-22cf104d7228","timestamp":"2026-10-01T15:38:55.536Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"868f9725-503b-4a89-af11-22cf104d7228","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_6afebec78bfc446dbba8550d","type":"tool_result","content":"src/gain.rs:128: let mut by_index: std::collections::BTreeMap<&str, (u64, u64)> = Default::default();\nsrc/gain.rs:130: let slot = by_index.entry(e.index.as_str()).or_default();\nsrc/gain.rs:136: let mut top: Vec<(&str, u64, u64)> = by_index.iter().map(|(k, v)| (*k, v.0, v.1)).collect();\nsrc/harvest/source.rs:153: let mut z = zip::ZipArchive::new(f).context(\"open zip\")?;\nsrc/harvest/source.rs:165: let mut entry = z.by_index(i).context(\"zip entry\")?;\nsrc/harvest/source.rs:240: let mut z = zip::ZipWriter::new(f);\nsrc/harvest/source.rs:241: let opts: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default()\nsrc/harvest/source.rs:242: .compression_method(zip::CompressionMethod::Deflated);\nsrc/extract/docx.rs:40: let mut z = zip::ZipArchive::new(f).context(\"open docx container\")?;\nsrc/extract/docx.rs:167: let mut z = zip::ZipWriter::new(std::fs::File::create(path).unwrap());\nsrc/extract/docx.rs:168: let opts = zip::write::SimpleFileOptions::default()\nsrc/extract/docx.rs:169: .compression_method(zip::CompressionMethod::Deflated);\nsrc/sniff.rs:225: if let Ok(mut z) = zip::ZipArchive::new(f) {\nsrc/sniff.rs:227: z.by_index_raw(i)\nsrc/lib.rs:4678: let mut by_index: std::collections::BTreeMap<&str, Vec<&detect::CorpusFile>> =\nsrc/lib.rs:4682: by_index.entry(index).or_default().push(f);\nsrc/lib.rs:4693: for (index, group) in by_index {\nsrc/xc.rs:2564: let mut z = zip::ZipWriter::new(f);\nsrc/xc.rs:2565: let opts: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default();\nsrc/xc.rs:2644: let mut z = zip::ZipWriter::new(f);\nsrc/xc.rs:2645: let opts: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default();\nsrc/xc.rs:2647: z: &mut zip::ZipWriter<std::fs::File>,\nsrc/xc.rs:2651: opts: zip::write::SimpleFileOptions,","is_error":false}]},"uuid":"85eccbcf-6d5c-438a-9f58-8f21dc903ac7","timestamp":"2026-10-01T15:38:55.562Z","sourceToolAssistantUUID":"868f9725-503b-4a89-af11-22cf104d7228","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"85eccbcf-6d5c-438a-9f58-8f21dc903ac7","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025347ce771674b1c74425","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_ad3c9b0f5b4f4882af147257","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates && grep -rn \"Pipeline::from_config\\|\\.process(&mut\\|process_batch\\|xerj_wasm::\" --include=\"*.rs\" xerj-engine/src xerj-api/src xerj-server/src xerj-mcp/src 2>/dev/null | head -40","description":"Find pipeline callers in engine/api"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"476aeaf5-cd13-46a2-ad21-bd2275b37f9f","timestamp":"2026-10-01T15:38:57.461Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"476aeaf5-cd13-46a2-ad21-bd2275b37f9f","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_ad3c9b0f5b4f4882af147257","type":"tool_result","content":"xerj-engine/src/engine.rs:547: /// may soften it ([`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode)).\nxerj-engine/src/engine.rs:594: /// [`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode)), and\nxerj-engine/src/engine.rs:707: pub transform_pipelines: Arc<DashMap<String, xerj_wasm::pipeline::Pipeline>>,\nxerj-engine/src/engine.rs:2593: xerj_wasm::pipeline::CompileMode::Strict\nxerj-engine/src/engine.rs:2595: xerj_wasm::pipeline::CompileMode::ReplayPersisted\nxerj-engine/src/engine.rs:2853: pub fn put_pipeline(&self, id: &str, config: Value) -> Result<Option<xerj_wasm::WasmError>> {\nxerj-engine/src/engine.rs:4101: /// `config_json` must be a valid [`PipelineConfig`](xerj_wasm::pipeline::PipelineConfig)\nxerj-engine/src/engine.rs:4114: ) -> std::result::Result<(), xerj_wasm::WasmError> {\nxerj-engine/src/engine.rs:4115: self.compile_pipeline_with_mode(name, config_json, xerj_wasm::pipeline::CompileMode::Strict)\nxerj-engine/src/engine.rs:4121: /// [`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode) — a\nxerj-engine/src/engine.rs:4132: mode: xerj_wasm::pipeline::CompileMode,\nxerj-engine/src/engine.rs:4133: ) -> std::result::Result<(), xerj_wasm::WasmError> {\nxerj-engine/src/engine.rs:4134: let cfg: xerj_wasm::pipeline::PipelineConfig =\nxerj-engine/src/engine.rs:4135: serde_json::from_value(config_json.clone()).map_err(xerj_wasm::WasmError::Json)?;\nxerj-engine/src/engine.rs:4137: xerj_wasm::pipeline::CompileMode::Strict => {\nxerj-engine/src/engine.rs:4138: xerj_wasm::pipeline::Pipeline::from_config(name, &cfg)?\nxerj-engine/src/engine.rs:4140: xerj_wasm::pipeline::CompileMode::ReplayPersisted => {\nxerj-engine/src/engine.rs:4141: xerj_wasm::pipeline::Pipeline::from_config_replaying_persisted(name, &cfg)?\nxerj-engine/src/engine.rs:4276: /// Returns [`xerj_wasm::WasmError::PipelineNotFound`] when `pipeline_name`\nxerj-engine/src/engine.rs:4283: ) -> std::result::Result<Vec<(xerj_wasm::pipeline::ProcessAction, Value)>, xerj_wasm::WasmError>\nxerj-engine/src/engine.rs:4292: Some(reason) => xerj_wasm::WasmError::PipelineNotRunnable {\nxerj-engine/src/engine.rs:4296: None => xerj_wasm::WasmError::PipelineNotFound(pipeline_name.to_string()),\nxerj-engine/src/engine.rs:4300: let actions = pipeline.process_batch(&mut docs);\nxerj-engine/src/bulk.rs:1785: if matches!(p_action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-engine/src/bulk.rs:1828: xerj_wasm::WasmError::PipelineNotRunnable { .. } => e.to_string(),\nxerj-api/src/native.rs:2548:/// [`PipelineConfig`](xerj_wasm::pipeline::PipelineConfig) body.\nxerj-api/src/native.rs:2666: use xerj_wasm::pipeline::ProcessAction;\nxerj-api/src/es_compat.rs:2813: if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-api/src/es_compat.rs:2950: if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-api/src/es_compat.rs:3084: if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-api/src/es_compat.rs:23867: if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-api/src/es_compat.rs:27785: if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\nxerj-api/src/es_compat.rs:28846:fn pipeline_execution_error(pipeline: &str, e: &xerj_wasm::WasmError) -> ApiError {\nxerj-api/src/es_compat.rs:29371: Ok(Some(xerj_wasm::WasmError::UnsupportedStage { stage })) => {\nxerj-api/src/es_compat.rs:29388: Ok(Some(xerj_wasm::WasmError::UnsupportedOption {","is_error":false}]},"uuid":"fbff4a8e-8ce4-4643-b2ea-959edec800bf","timestamp":"2026-10-01T15:38:57.487Z","sourceToolAssistantUUID":"476aeaf5-cd13-46a2-ad21-bd2275b37f9f","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"fbff4a8e-8ce4-4643-b2ea-959edec800bf","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025347ce771674b1c74425","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_616347905e034e1d98e30c5d","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex && grep -rn \"symlink\\|follow_link\\|metadata()\\|canonicalize\\|fs::copy\\|fs::write\\|fs::create_dir\" src/walk.rs src/state.rs src/harvest/*.rs src/objsource.rs 2>/dev/null | head -60","description":"Find filesystem write and symlink handling"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":13294,"cache_creation_input_tokens":0,"cache_read_input_tokens":87808,"output_tokens":980,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"116bda39-1396-410e-ba6d-2199d2bfdcd8","timestamp":"2026-10-01T15:38:58.559Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"116bda39-1396-410e-ba6d-2199d2bfdcd8","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_616347905e034e1d98e30c5d","type":"tool_result","content":"src/harvest/httpget.rs:72: std::fs::create_dir_all(parent).with_context(|| format!(\"create {}\", parent.display()))?;\nsrc/harvest/recipe.rs:692: std::fs::write(&p, body).unwrap();\nsrc/harvest/sign.rs:67: std::fs::write(&out, sig.as_ref()).with_context(|| format!(\"write {}\", out.display()))?;\nsrc/harvest/sign.rs:185: if let Err(e) = std::fs::create_dir_all(parent) {\nsrc/harvest/sign.rs:193: if let Err(e) = std::fs::write(&key_path, format!(\"{seed}\\n\")).and_then(|_| {\nsrc/harvest/sign.rs:194: std::fs::write(format!(\"{}.pub\", prefix.display()), format!(\"{public}\\n\"))\nsrc/harvest/sign.rs:385: std::fs::write(pack_dir.join(&fname), \"# tampered recipe\\n\").unwrap();\nsrc/harvest/sign.rs:399: std::fs::write(pack_dir.join(\"SHA256SUMS\"), new_sums).unwrap();\nsrc/harvest/sign.rs:417: std::fs::write(pack_dir.join(SIG_NAME), vec![0u8; 10]).unwrap();\nsrc/harvest/mod.rs:243: std::fs::write(\nsrc/harvest/mod.rs:413: std::fs::create_dir_all(root.join(\"b\")).unwrap();\nsrc/harvest/mod.rs:414: std::fs::create_dir_all(root.join(\"a\")).unwrap();\nsrc/harvest/mod.rs:415: std::fs::write(root.join(\"b/second.json\"), \"{}\").unwrap();\nsrc/harvest/mod.rs:416: std::fs::write(root.join(\"a/first.json\"), \"{}\").unwrap();\nsrc/harvest/mod.rs:417: std::fs::write(root.join(\"a/note.txt\"), \"x\").unwrap();\nsrc/harvest/mod.rs:427: std::fs::write(&a, r#\"[{\"id\":\"x\"},{\"id\":\"y\"}]\"#).unwrap();\nsrc/harvest/mod.rs:430: std::fs::write(&b, \"{\\\"id\\\":\\\"z\\\"}\\n\\n{\\\"id\\\":\\\"w\\\"}\\n\").unwrap();\nsrc/harvest/mod.rs:433: std::fs::write(&c, r#\"{\"id\":\"one\"}\"#).unwrap();\nsrc/harvest/mod.rs:436: std::fs::write(&d, \"```toml\\n[advisory]\\nid = \\\"R\\\"\\n```\\n\\n# T\\n\").unwrap();\nsrc/harvest/mod.rs:491: std::fs::create_dir_all(root.join(\"data/rustsec\")).unwrap();\nsrc/harvest/mod.rs:492: std::fs::create_dir_all(root.join(\"data/ghsa\")).unwrap();\nsrc/harvest/mod.rs:493: std::fs::write(root.join(\"e2e.toml\"), E2E_RECIPE).unwrap();\nsrc/harvest/mod.rs:494: std::fs::write(\nsrc/harvest/mod.rs:511: std::fs::write(\nsrc/harvest/mod.rs:517: std::fs::write(\nsrc/harvest/mod.rs:736: std::fs::create_dir_all(&origin).unwrap();\nsrc/harvest/mod.rs:738: std::fs::write(origin.join(\"a.json\"), r#\"{\"id\": \"R1\", \"aliases\": [\"C1\"]}\"#).unwrap();\nsrc/harvest/mod.rs:762: std::fs::create_dir_all(home.path().join(\"recipes\")).unwrap();\nsrc/harvest/mod.rs:763: std::fs::write(home.path().join(\"recipes/gitdemo.toml\"), recipe).unwrap();\nsrc/harvest/mod.rs:795: std::fs::write(origin.join(\"b.json\"), r#\"{\"id\": \"R2\"}\"#).unwrap();\nsrc/harvest/pack.rs:77: std::fs::create_dir_all(&pack_dir)\nsrc/harvest/pack.rs:128: std::fs::write(&path, lines.as_bytes())\nsrc/harvest/pack.rs:139: std::fs::write(pack_dir.join(\"recipe.toml\"), recipe_toml)?;\nsrc/harvest/pack.rs:148: std::fs::write(\nsrc/harvest/pack.rs:152: std::fs::write(pack_dir.join(\"relations.jsonl\"), sugg.relations_jsonl())?;\nsrc/harvest/pack.rs:153: std::fs::write(pack_dir.join(\"suggestions.md\"), sugg.to_markdown())?;\nsrc/harvest/pack.rs:177: std::fs::write(pack_dir.join(\"manifest.json\"), &manifest_bytes)?;\nsrc/harvest/pack.rs:194: std::fs::write(pack_dir.join(\"SHA256SUMS\"), sums)?;\nsrc/harvest/pack.rs:647: std::fs::write(&path, bytes).unwrap();\nsrc/harvest/pack.rs:672: std::fs::write(\nsrc/harvest/pack.rs:699: std::fs::write(r.dir.join(\"SHA256SUMS\"), kept).unwrap();\nsrc/harvest/pack.rs:727: std::fs::write(\nsrc/harvest/store.rs:55: std::fs::create_dir_all(store_dir)?;\nsrc/harvest/store.rs:57: std::fs::write(&tmp, canonical_json(env))?;\nsrc/harvest/source.rs:17://! symlink entry is skipped and COUNTED, never trusted — dump URLs are\nsrc/harvest/source.rs:92: std::fs::create_dir_all(cache_dir)?;\nsrc/harvest/source.rs:93: std::fs::write(watermark_path(cache_dir, slug), watermark)\nsrc/harvest/source.rs:103: std::fs::create_dir_all(target)\nsrc/harvest/source.rs:160: std::fs::create_dir_all(dest)?;\nsrc/harvest/source.rs:169: if entry.is_symlink() {\nsrc/harvest/source.rs:180: std::fs::create_dir_all(parent)?;\nsrc/harvest/source.rs:196: std::fs::write(&out, &buf)?;\nsrc/harvest/source.rs:306: std::fs::create_dir_all(&origin).unwrap();\nsrc/harvest/source.rs:308: std::fs::write(origin.join(\"one.json\"), r#\"{\"id\":\"R1\",\"aliases\":[\"C1\"]}\"#).unwrap();\nsrc/harvest/source.rs:346: std::fs::write(origin.join(\"two.json\"), r#\"{\"id\":\"R2\"}\"#).unwrap();\nsrc/harvest/source.rs:375: std::fs::create_dir_all(&origin).unwrap();\nsrc/harvest/source.rs:377: std::fs::write(origin.join(\"main.json\"), r#\"{\"id\":\"M\"}\"#).unwrap();\nsrc/harvest/source.rs:398: std::fs::write(origin.join(\"export.json\"), r#\"{\"id\":\"E\"}\"#).unwrap();\nsrc/walk.rs:2://! Symlinks are NOT followed by default; with --follow-symlinks walkdir's\nsrc/walk.rs:21: /// True when the discovered path itself is a symlink (target metadata follows).","is_error":false}]},"uuid":"02be4e62-ebf4-462a-b55c-b0da7299e6de","timestamp":"2026-10-01T15:38:58.601Z","sourceToolAssistantUUID":"116bda39-1396-410e-ba6d-2199d2bfdcd8","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"02be4e62-ebf4-462a-b55c-b0da7299e6de","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254125df46762f69041a2","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Big finding candidate: `src/harvest/source.rs:153-196` — a zip extraction. Let's read that. Also `extract/docx.rs:40` and `walk.rs`.\n\nLet me read harvest/source.rs around 80-220, extract/docx.rs, and walk.rs.","signature":"a3e00be0358c45d19b3d1c19"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"4b23812a-4b97-4a9f-a912-82c77e2705fe","timestamp":"2026-10-01T15:39:07.241Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4b23812a-4b97-4a9f-a912-82c77e2705fe","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254125df46762f69041a2","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_f48ff5b702664283b21733b0","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/harvest/source.rs","limit":220}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"d7a89e18-81e2-449c-8253-7cf824a02485","timestamp":"2026-10-01T15:39:07.242Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d7a89e18-81e2-449c-8253-7cf824a02485","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_f48ff5b702664283b21733b0","type":"tool_result","content":"1\t//! Source adapters: turn a recipe `[[sources]]` entry into a directory to\n2\t//! walk, plus the upstream watermark that lets an unchanged source be\n3\t//! skipped wholesale on the next run.\n4\t//!\n5\t//! Kinds:\n6\t//! - `dir` — walk a recipe-relative directory (the fixture/local kind)\n7\t//! - `http-zip`— download a zip, extract into the cache, walk the\n8\t//! extraction. No watermark: the zip is re-downloaded every run and the\n9\t//! content store dedups what did not change (correctness lives there,\n10\t//! watermarks are only an optimization).\n11\t//! - `git` — promisor shallow checkout at `rev` (pinned) or the remote\n12\t//! HEAD (tracking). Watermark = HEAD sha: unchanged tree ⇒ the walk is\n13\t//! skipped entirely this run.\n14\t//!\n15\t//! Zip extraction is defensive by default: entry names are normalized and\n16\t//! any path escaping the extraction root (zip-slip), absolute path, or\n17\t//! symlink entry is skipped and COUNTED, never trusted — dump URLs are\n18\t//! fetched from the open internet.\n19\t\n20\tuse std::io::Read;\n21\tuse std::path::{Component, Path, PathBuf};\n22\t\n23\tuse anyhow::{bail, Context, Result};\n24\t\n25\tuse super::httpget;\n26\tuse super::recipe::SourceSpec;\n27\t\n28\t/// Total decompressed cap for one zip. Real advisory dumps are well under\n29\t/// this; the cap exists because a zip's declared sizes are untrusted and a\n30\t/// 3 MiB file can claim to expand to terabytes.\n31\tconst MAX_EXTRACT_BYTES: u64 = 2 << 30;\n32\t\n33\t#[derive(Debug)]\n34\tpub struct Fetched {\n35\t /// The directory the glob walk starts from.\n36\t pub root: PathBuf,\n37\t /// Current upstream version marker, if the kind has one.\n38\t pub watermark: Option<String>,\n39\t /// The watermark matches the previous run's: the caller should skip\n40\t /// walking AND pruning this source (everything it stored is still live).\n41\t pub unchanged: bool,\n42\t}\n43\t\n44\t/// Where a source's watermark from the previous run is kept.\n45\tfn watermark_path(cache_dir: &Path, slug: &str) -> PathBuf {\n46\t cache_dir.join(format!(\"{slug}.watermark\"))\n47\t}\n48\t\n49\t/// Materialize a source. `cache_dir` is `<build>/cache`; it only exists to\n50\t/// make network kinds incremental.\n51\tpub fn fetch(src: &SourceSpec, recipe_dir: &Path, cache_dir: &Path) -> Result<Fetched> {\n52\t match src.kind {\n53\t super::recipe::SourceKind::Dir => Ok(Fetched {\n54\t root: recipe_dir.join(src.path.as_deref().unwrap_or(\".\")),\n55\t watermark: None,\n56\t unchanged: false,\n57\t }),\n58\t super::recipe::SourceKind::HttpZip => {\n59\t let url = src.url.as_deref().unwrap_or_default();\n60\t let zip_path = cache_dir.join(format!(\"{}.zip\", src.slug));\n61\t httpget::download(url, &zip_path)\n62\t .with_context(|| format!(\"source '{}': fetch\", src.slug))?;\n63\t let root = cache_dir.join(&src.slug);\n64\t extract_zip(&zip_path, &root)\n65\t .with_context(|| format!(\"source '{}': extract\", src.slug))?;\n66\t Ok(Fetched {\n67\t root,\n68\t watermark: None,\n69\t unchanged: false,\n70\t })\n71\t }\n72\t super::recipe::SourceKind::Git => {\n73\t let url = src.url.as_deref().unwrap_or_default();\n74\t let root = cache_dir.join(&src.slug);\n75\t let rev = src.rev.as_deref().unwrap_or(\"HEAD\");\n76\t let watermark = git_checkout(&root, url, rev, &src.slug)?;\n77\t let prev = std::fs::read_to_string(watermark_path(cache_dir, &src.slug))\n78\t .map(|s| s.trim().to_string())\n79\t .unwrap_or_default();\n80\t Ok(Fetched {\n81\t root,\n82\t watermark: Some(watermark.clone()),\n83\t unchanged: !watermark.is_empty() && watermark == prev,\n84\t })\n85\t }\n86\t }\n87\t}\n88\t\n89\t/// Persist a source's watermark after its harvest fully succeeded (never\n90\t/// before — a failed run must re-walk).\n91\tpub fn save_watermark(cache_dir: &Path, slug: &str, watermark: &str) -> Result<()> {\n92\t std::fs::create_dir_all(cache_dir)?;\n93\t std::fs::write(watermark_path(cache_dir, slug), watermark)\n94\t .with_context(|| format!(\"save watermark for '{slug}'\"))\n95\t}\n96\t\n97\t/// Shallow promisor checkout of `rev` into `target`, reusing the\n98\t/// corpus-clone machinery: init + blob:none filter so a pin at an old sha\n99\t/// costs one small fetch, never a full history. `rev` is a full sha, a\n100\t/// branch/tag name, or `HEAD` (the remote's default). Returns HEAD.\n101\tfn git_checkout(target: &Path, url: &str, rev: &str, slug: &str) -> Result<String> {\n102\t if !target.join(\".git\").exists() {\n103\t std::fs::create_dir_all(target)\n104\t .with_context(|| format!(\"source '{slug}': create {}\", target.display()))?;\n105\t crate::xc::git(Some(target), &[\"init\", \"--quiet\"])?;\n106\t crate::xc::git(Some(target), &[\"remote\", \"add\", \"origin\", url]).ok();\n107\t crate::xc::git(Some(target), &[\"config\", \"remote.origin.promisor\", \"true\"]).ok();\n108\t crate::xc::git(\n109\t Some(target),\n110\t &[\"config\", \"remote.origin.partialclonefilter\", \"blob:none\"],\n111\t )\n112\t .ok();\n113\t }\n114\t // A pinned rev (full sha) can reuse checkout_at_sha; a named ref (branch\n115\t // or tag, e.g. RustSec's `osv` branch) and plain HEAD go through\n116\t // FETCH_HEAD, which checkout_at_sha cannot name. Anything else used to\n117\t // silently fetch HEAD — a typo'd branch name now fails loudly instead.\n118\t let ok = |r: Result<(i32, String)>| r.map(|(rc, _)| rc == 0).unwrap_or(false);\n119\t let looks_like_sha = rev.len() == 40 && rev.chars().all(|c| c.is_ascii_hexdigit());\n120\t if looks_like_sha {\n121\t crate::xc::checkout_at_sha(target, url, rev)\n122\t .with_context(|| format!(\"source '{slug}': checkout {rev}\"))?;\n123\t } else {\n124\t // `rev` works directly as the refspec: a branch/tag name fetches that\n125\t // ref, and the literal \"HEAD\" fetches the remote's default HEAD.\n126\t if !ok(crate::xc::git(\n127\t Some(target),\n128\t &[\"fetch\", \"--depth\", \"1\", \"origin\", rev],\n129\t )) {\n130\t bail!(\"source '{slug}': git fetch {rev} from {url} failed\");\n131\t }\n132\t if !ok(crate::xc::git(\n133\t Some(target),\n134\t &[\"checkout\", \"--quiet\", \"--force\", \"--detach\", \"FETCH_HEAD\"],\n135\t )) {\n136\t bail!(\"source '{slug}': git checkout FETCH_HEAD ({rev}) failed\");\n137\t }\n138\t crate::xc::git(Some(target), &[\"clean\", \"-qfd\"]).ok();\n139\t }\n140\t let (_, head) = crate::xc::git(Some(target), &[\"rev-parse\", \"HEAD\"])\n141\t .with_context(|| format!(\"source '{slug}': rev-parse\"))?;\n142\t if head.is_empty() {\n143\t bail!(\"source '{slug}': empty HEAD after checkout\");\n144\t }\n145\t Ok(head)\n146\t}\n147\t\n148\t/// Extract `zip` into `dest`, replacing any previous extraction of the same\n149\t/// source. Defensive: entry paths are sanitized, escapes are skipped and\n150\t/// counted (returned), total decompressed bytes are capped.\n151\tpub fn extract_zip(zip: &Path, dest: &Path) -> Result<usize> {\n152\t let f = std::fs::File::open(zip).with_context(|| format!(\"open {}\", zip.display()))?;\n153\t let mut z = zip::ZipArchive::new(f).context(\"open zip\")?;\n154\t\n155\t // clear the previous extraction first: a file renamed upstream must not\n156\t // survive as a stale duplicate\n157\t if dest.exists() {\n158\t std::fs::remove_dir_all(dest).with_context(|| format!(\"clear {}\", dest.display()))?;\n159\t }\n160\t std::fs::create_dir_all(dest)?;\n161\t\n162\t let mut skipped = 0usize;\n163\t let mut total: u64 = 0;\n164\t for i in 0..z.len() {\n165\t let mut entry = z.by_index(i).context(\"zip entry\")?;\n166\t if entry.is_dir() {\n167\t continue;\n168\t }\n169\t if entry.is_symlink() {\n170\t skipped += 1;\n171\t continue;\n172\t }\n173\t let raw = entry.name().to_string();\n174\t let Some(safe) = sanitize_entry_path(&raw) else {\n175\t skipped += 1;\n176\t continue;\n177\t };\n178\t let out = dest.join(&safe);\n179\t if let Some(parent) = out.parent() {\n180\t std::fs::create_dir_all(parent)?;\n181\t }\n182\t let mut buf = Vec::new();\n183\t // bounded read: `entry.size()` is the DECLARED size, so read via\n184\t // take() + counter and stop the whole extraction past the cap\n185\t let limit = MAX_EXTRACT_BYTES.saturating_sub(total);\n186\t let mut reader = (&mut entry).take(limit + 1);\n187\t reader.read_to_end(&mut buf).context(\"decompress entry\")?;\n188\t total += buf.len() as u64;\n189\t if total > MAX_EXTRACT_BYTES {\n190\t bail!(\n191\t \"zip {} expands past the {} cap\",\n192\t zip.display(),\n193\t MAX_EXTRACT_BYTES\n194\t );\n195\t }\n196\t std::fs::write(&out, &buf)?;\n197\t }\n198\t Ok(skipped)\n199\t}\n200\t\n201\t/// Reject absolute paths, drive letters, `..`, and anything not expressible\n202\t/// as normal relative components (the zip-slip family). Returns the\n203\t/// posix-style relative path. Windows-style names (`C:/x`, `a\\\\b`) are\n204\t/// rejected on EVERY os — a pack may be built anywhere, and a name that is\n205\t/// a harmless subdir on linux is an escape on windows.\n206\tfn sanitize_entry_path(raw: &str) -> Option<String> {\n207\t let path = Path::new(raw);\n208\t let mut parts: Vec<&str> = Vec::new();\n209\t for c in path.components() {\n210\t match c {\n211\t Component::Normal(p) => {\n212\t let s = p.to_str()?;\n213\t if s.is_empty()\n214\t || s == \".\"\n215\t || s.contains('\\0')\n216\t || s.contains(':')\n217\t || s.contains('\\\\')\n218\t {\n219\t return None;\n220\t }"}]},"uuid":"f418ad69-d82a-4b22-bac8-f802b9c8cdd0","timestamp":"2026-10-01T15:39:07.246Z","sourceToolAssistantUUID":"d7a89e18-81e2-449c-8253-7cf824a02485","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f418ad69-d82a-4b22-bac8-f802b9c8cdd0","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254125df46762f69041a2","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_2826229fc6fd413cbb352882","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/walk.rs"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":4472,"cache_creation_input_tokens":0,"cache_read_input_tokens":101056,"output_tokens":129,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"fb88dbf8-9d88-4eca-ae6f-2b78bd752056","timestamp":"2026-10-01T15:39:07.437Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"fb88dbf8-9d88-4eca-ae6f-2b78bd752056","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_2826229fc6fd413cbb352882","type":"tool_result","content":"1\t//! Inventory: recursive walk of the target folder.\n2\t//! Symlinks are NOT followed by default; with --follow-symlinks walkdir's\n3\t//! ancestor-loop detection keeps the traversal loop-safe.\n4\t//!\n5\t//! Ignore rules (`.gitignore`, `.xerjignore`, built-in build-output defaults)\n6\t//! are applied *during* the walk, not after it: an ignored directory is never\n7\t//! descended, so its contents cost nothing — no stat, no hash, no bulk body.\n8\t//! The matching itself lives in [`crate::ignore_rules`].\n9\t\n10\tuse crate::ignore_rules::{is_hidden_name, IgnoreOptions, IgnoreReport, IgnoreStack};\n11\tuse anyhow::{Context, Result};\n12\tuse std::path::{Path, PathBuf};\n13\t\n14\t#[derive(Debug, Clone)]\n15\tpub struct FileEntry {\n16\t pub path: PathBuf,\n17\t /// Root-relative path with forward slashes — the stable `ax_path` value.\n18\t pub rel: String,\n19\t /// Reversible platform-native identity; unlike `rel`, never lossy.\n20\t pub rel_id: String,\n21\t /// True when the discovered path itself is a symlink (target metadata follows).\n22\t pub is_symlink: bool,\n23\t pub size: u64,\n24\t}\n25\t\n26\t/// Generated/cache directories whose NAMES are too common for the blunt\n27\t/// [`crate::ignore_rules::DEFAULT_IGNORE_PATTERNS`] (a folder named `Logs/`\n28\t/// or `Library/` is often real data), pruned at any depth ONLY when a sibling\n29\t/// marker file proves the parent directory is that kind of project. Part of\n30\t/// the built-in defaults: `--no-ignore` / `--no-default-ignores` disable it,\n31\t/// and any ignore file in the tree can re-include (`!Library/`) as usual —\n32\t/// these run after the ignore files have had their say.\n33\t///\n34\t/// (dir name, marker path relative to the dir's PARENT, report label)\n35\tconst MARKER_GENERATED_DIRS: &[(&str, &str, &str)] = &[\n36\t (\n37\t \"Library\",\n38\t \"ProjectSettings/ProjectVersion.txt\",\n39\t \"default:unity-generated\",\n40\t ),\n41\t (\n42\t \"Temp\",\n43\t \"ProjectSettings/ProjectVersion.txt\",\n44\t \"default:unity-generated\",\n45\t ),\n46\t (\n47\t \"obj\",\n48\t \"ProjectSettings/ProjectVersion.txt\",\n49\t \"default:unity-generated\",\n50\t ),\n51\t (\n52\t \"Logs\",\n53\t \"ProjectSettings/ProjectVersion.txt\",\n54\t \"default:unity-generated\",\n55\t ),\n56\t (\n57\t \"UserSettings\",\n58\t \"ProjectSettings/ProjectVersion.txt\",\n59\t \"default:unity-generated\",\n60\t ),\n61\t];\n62\t\n63\t/// The marker-gated verdict for one directory entry.\n64\tfn marker_generated_dir(path: &Path) -> Option<&'static str> {\n65\t let name = path.file_name()?;\n66\t for (dir, marker, label) in MARKER_GENERATED_DIRS {\n67\t if name == *dir && path.parent().is_some_and(|p| p.join(marker).is_file()) {\n68\t return Some(label);\n69\t }\n70\t }\n71\t None\n72\t}\n73\t\n74\t/// The file Google Takeout writes at the top of every export: an HTML table of\n75\t/// contents for the archive. Its presence is what makes a directory a Takeout\n76\t/// root — the `Takeout` folder NAME is not tested, because people rename it,\n77\t/// merge several parts into one folder, or point autoindex at the inside of it.\n78\tpub const TAKEOUT_MARKER: &str = \"archive_browser.html\";\n79\t\n80\t/// The export's own table of contents. It is not the user's data: it lists\n81\t/// every product and file name in the archive, so indexing it puts one large\n82\t/// document in front of every search that names a file.\n83\tpub const TAKEOUT_INDEX_RULE: &str = \"default:takeout-index\";\n84\t\n85\t/// Google Keep exports EVERY note twice — `Note.json` (structured: labels,\n86\t/// timestamps, checklist state) and `Note.html` (the same note rendered). The\n87\t/// JSON is indexed as a document by `extract::json::keep_note`; indexing the\n88\t/// HTML twin as well answers every Keep search twice.\n89\tpub const TAKEOUT_KEEP_TWIN_RULE: &str = \"default:takeout-keep-html-twin\";\n90\t\n91\t/// Is `dir` the root of a Google Takeout export?\n92\tfn is_takeout_root(dir: &Path) -> bool {\n93\t dir.join(TAKEOUT_MARKER).is_file()\n94\t}\n95\t\n96\t/// The marker-gated verdict for one FILE of a Google Takeout export: `Some`\n97\t/// names the rule that makes it noise. Part of the built-in defaults, exactly\n98\t/// like [`MARKER_GENERATED_DIRS`], and deliberately short — two rules, each\n99\t/// about a file that DUPLICATES something else in the export. Everything else\n100\t/// in a Takeout is the user's data and is left to the ordinary sniffing:\n101\t/// dropping someone's data on a guess about a product folder is worse than\n102\t/// indexing a little noise.\n103\t///\n104\t/// * `archive_browser.html` in a Takeout root → [`TAKEOUT_INDEX_RULE`].\n105\t/// * `X.html` directly inside a product folder of a Takeout root, with a\n106\t/// sibling `X.json` that is a Keep note → [`TAKEOUT_KEEP_TWIN_RULE`]. The\n107\t/// product folder's NAME is not tested (it is localised: `Keep`, `Notizen`,\n108\t/// …); the sibling JSON's content is, by the same predicate the extractor\n109\t/// uses, so an unrelated `report.html` beside a `report.json` is untouched.\n110\tfn takeout_noise(path: &Path) -> Option<&'static str> {\n111\t let name = path.file_name()?;\n112\t let dir = path.parent()?;\n113\t if name == TAKEOUT_MARKER {\n114\t // `dir` holds this very file, so it is a Takeout root by definition.\n115\t return Some(TAKEOUT_INDEX_RULE);\n116\t }\n117\t let is_html = path\n118\t .extension()\n119\t .is_some_and(|e| e.eq_ignore_ascii_case(\"html\"));\n120\t if is_html && dir.parent().is_some_and(is_takeout_root) {\n121\t let twin = path.with_extension(\"json\");\n122\t if twin.is_file() && crate::extract::json::is_keep_note_file(&twin) {\n123\t return Some(TAKEOUT_KEEP_TWIN_RULE);\n124\t }\n125\t }\n126\t None\n127\t}\n128\t\n129\t/// Why a followed symlink was refused. See the call site in `walk_reporting`.\n130\tenum SymlinkVerdict {\n131\t /// The resolved target is not under the indexed root. Carries the\n132\t /// resolution so the waiver arm can store it: an admitted entry must read\n133\t /// from the path that was judged rather than from the link it arrived by,\n134\t /// and out-of-root entries are the only ones that arm ever admits.\n135\t OutsideRoot(PathBuf),\n136\t /// Outside the root AND through a dotted component. Separate from\n137\t /// `OutsideRoot` because `--follow-symlinks-outside-root` must not reach\n138\t /// it, and separate from `HiddenTarget` because the operator has no dotfile\n139\t /// in their own folder to go looking for — the actionable fact is that a\n140\t /// link left it.\n141\t HiddenOutsideRoot,\n142\t /// The resolved target is under the root but its real path runs through a\n143\t /// hidden component — the link's visible name was hiding a dotfile.\n144\t HiddenTarget,\n145\t /// The path could not be resolved at all, so neither question could be\n146\t /// answered. Refused rather than admitted; see `escaped_or_hidden_target`.\n147\t Unresolvable,\n148\t}\n149\t\n150\t/// Judge a followed entry by where it actually resolves.\n151\t///\n152\t/// `path` is the path the walk arrived by, so under `--follow-symlinks` it can\n153\t/// name a link anywhere along its length. Canonicalising collapses every link\n154\t/// in it at once, which is what makes a chain of links (`a -> b -> .secret/c`)\n155\t/// and a link partway up a directory path behave the same as a direct one.\n156\t///\n157\t/// `Ok(Some(real))` is the resolved path, which the caller stores on the\n158\t/// `FileEntry` so every later `open()` reads the file that was judged.\n159\t/// `Ok(None)` means there is nothing to resolve and the ordinary rules govern\n160\t/// the entry.\n161\t///\n162\t/// A resolution FAILURE is not `None`. An earlier version of this function\n163\t/// wrote `path.canonicalize().ok()?`, which collapsed every error into \"the\n164\t/// entry is where it appears\" and justified it with \"a broken link has no\n165\t/// target to leak\". That is true of `NotFound` and of nothing else, and the\n166\t/// difference is a bypass rather than a nicety: `canonicalize` is `realpath(3)`\n167\t/// and is bounded by `PATH_MAX`, while the kernel's own resolution is not, so an\n168\t/// entry can be unresolvable HERE and perfectly readable by every later stage —\n169\t/// `stat`, `open`, hashing, extraction. The guard was then skipped for exactly\n170\t/// the entries it could not vet, which is the wrong direction for a rule whose\n171\t/// job is to keep `.ssh` out of a queryable index. `ELOOP` and `EACCES` land in\n172\t/// the same arm.\n173\t///\n174\t/// So only `NotFound` is treated as \"nothing here to leak\" — walkdir already\n175\t/// reports a dangling link through its error arm. Everything else is refused\n176\t/// and named in the report, because an answer that could not be computed is not\n177\t/// an answer of \"yes\".\n178\tfn escaped_or_hidden_target(\n179\t root_canon: &Path,\n180\t path: &Path,\n181\t) -> Result<Option<PathBuf>, SymlinkVerdict> {\n182\t let real = match path.canonicalize() {\n183\t Ok(real) => real,\n184\t Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),\n185\t Err(_) => return Err(SymlinkVerdict::Unresolvable),\n186\t };\n187\t let Some(rel) = real.strip_prefix(root_canon).ok() else {\n188\t // Outside the root — but the hidden-name question is asked FIRST and\n189\t // against the whole resolved path, because `OutsideRoot` is the only\n190\t // verdict `--follow-symlinks-outside-root` waives. Returning it before\n191\t // looking for a dotted component let that flag admit\n192\t // `keys.txt -> ../outside/.ssh/id_rsa` unexamined, which is #438\n193\t // reopened through the escape hatch built to be safe.\n194\t //\n195\t // Judged from where the target DIVERGES from the root, not from `/`.\n196\t // Checking every component would refuse any target whose absolute path\n197\t // passes through a dotted ancestor — `/home/u/.cache/...`, and every\n198\t // path under a `tempfile` directory, which is named `.tmpXXXXXX`. Those\n199\t // ancestors are shared with the root the operator pointed at, so they\n200\t // are as consented-to as the root itself; the components BELOW the\n201\t // divergence are the ones nobody asked for.\n202\t let shared = root_canon\n203\t .components()\n204\t .zip(real.components())\n205\t .take_while(|(a, b)| a == b)\n206\t .count();\n207\t if real\n208\t .components()\n209\t .skip(shared)\n210\t .any(|c| is_hidden_name(c.as_os_str()))\n211\t {\n212\t return Err(SymlinkVerdict::HiddenOutsideRoot);\n213\t }\n214\t return Err(SymlinkVerdict::OutsideRoot(real));\n215\t };\n216\t // In-root: judge only the part below the root. A brain over a dot-named\n217\t // folder still works — that exemption is the same one the walker gives the\n218\t // root itself at depth 0.\n219\t if rel.components().any(|c| is_hidden_name(c.as_os_str())) {\n220\t return Err(SymlinkVerdict::HiddenTarget);\n221\t }\n222\t Ok(Some(real))\n223\t}\n224\t\n225\t/// Walk with the default ignore rules on and the report discarded.\n226\tpub fn walk(root: &Path, follow_symlinks: bool) -> Result<Vec<FileEntry>> {\n227\t walk_reporting(root, follow_symlinks, IgnoreOptions::default()).map(|(files, _)| files)\n228\t}\n229\t\n230\t/// Walk, and say what was left out and why.\n231\t///\n232\t/// The returned [`IgnoreReport`] is the answer to \"my files vanished\" — it\n233\t/// names every rule that discarded something and how much. It is reported on\n234\t/// every run and, under `--dry-run`, also counts what was inside each pruned\n235\t/// directory.\n236\tpub fn walk_reporting(\n237\t root: &Path,\n238\t follow_symlinks: bool,\n239\t ignore: IgnoreOptions,\n240\t) -> Result<(Vec<FileEntry>, IgnoreReport)> {\n241\t walk_reporting_opts(root, follow_symlinks, false, ignore)\n242\t}\n243\t\n244\t/// As [`walk_reporting`], with the out-of-root escape hatch.\n245\t///\n246\t/// `allow_outside_root` restores the pre-#438 behaviour of following a link\n247\t/// wherever it points. It exists because refusing every out-of-root target is\n248\t/// not a narrowing of `--follow-symlinks` — for a vendored sibling checkout, a\n249\t/// monorepo package link or a mounted notes volume it IS the flag, and without\n250\t/// an opt-in those runs silently index what they would index with the flag off.\n251\t/// The hidden-name rule still applies to the resolved path either way; only the\n252\t/// root boundary is waived, and only when the operator says so.\n253\tpub fn walk_reporting_opts(\n254\t root: &Path,\n255\t follow_symlinks: bool,\n256\t allow_outside_root: bool,\n257\t ignore: IgnoreOptions,\n258\t) -> Result<(Vec<FileEntry>, IgnoreReport)> {\n259\t walk_impl(root, follow_symlinks, allow_outside_root, ignore, None)\n260\t}\n261\t\n262\t/// The directories this walk ADMITS, and nothing else.\n263\t///\n264\t/// `--watch` places one filesystem watch per admitted directory instead of one\n265\t/// recursive watch on the root, and this is where that set comes from: the same\n266\t/// traversal, the same hidden-name rule, the same `.gitignore`/`.xerjignore`\n267\t/// stack, the same marker-gated prunes. Deriving the watch set any other way is\n268\t/// how a watched run and a re-run start disagreeing about what is indexed — an\n269\t/// ignored `target/` would be watched (thousands of events per build), and a\n270\t/// re-included directory would not be watched at all.\n271\t///\n272\t/// Files are not stat'ed on this route: the caller wants watch targets, not an\n273\t/// inventory, and the root is always included (it is admitted at depth 0\n274\t/// exactly like the file walk admits it).\n275\tpub fn walk_dirs_opts(\n276\t root: &Path,\n277\t follow_symlinks: bool,\n278\t allow_outside_root: bool,\n279\t ignore: IgnoreOptions,\n280\t) -> Result<Vec<PathBuf>> {\n281\t let mut dirs = Vec::new();\n282\t walk_impl(\n283\t root,\n284\t follow_symlinks,\n285\t allow_outside_root,\n286\t ignore,\n287\t Some(&mut dirs),\n288\t )?;\n289\t dirs.sort();\n290\t dirs.dedup();\n291\t Ok(dirs)\n292\t}\n293\t\n294\t/// One traversal, two callers: the file inventory and (`dirs_out`) the watch\n295\t/// set. With `dirs_out` set, every admitted directory is collected and files are\n296\t/// not examined at all.\n297\tfn walk_impl(\n298\t root: &Path,\n299\t follow_symlinks: bool,\n300\t allow_outside_root: bool,\n301\t ignore: IgnoreOptions,\n302\t mut dirs_out: Option<&mut Vec<PathBuf>>,\n303\t) -> Result<(Vec<FileEntry>, IgnoreReport)> {\n304\t let root_canon = root\n305\t .canonicalize()\n306\t .with_context(|| format!(\"resolve root folder {}\", root.display()))?;\n307\t if !root_canon.is_dir() {\n308\t anyhow::bail!(\"{} is not a directory\", root_canon.display());\n309\t }\n310\t let mut out = Vec::new();\n311\t // Shallowest depth from which the walk is inside a symlink; see the guard.\n312\t let mut link_depth: Option<usize> = None;\n313\t let marker_defaults = ignore.enabled && ignore.defaults;\n314\t let mut stack = IgnoreStack::new(&root_canon, ignore);\n315\t // Manual iteration rather than `filter_entry`, because the ignore stack has\n316\t // to load a directory's ignore files *after* that directory is admitted and\n317\t // *before* its children are judged. `skip_current_dir` on a just-yielded\n318\t // directory prunes its contents — walkdir's own documented pattern, and the\n319\t // same effect `filter_entry` had.\n320\t let mut it = walkdir::WalkDir::new(&root_canon)\n321\t .follow_links(follow_symlinks)\n322\t .into_iter();\n323\t while let Some(next) = it.next() {\n324\t let entry = match next {\n325\t Ok(e) => e,\n326\t Err(e) => {\n327\t // This message renders the offending PATH, and it goes to the\n328\t // same stderr an agent parses for `xerj-progress` /\n329\t // `xerj-done` records. An unreadable directory whose name\n330\t // carries a newline would otherwise start a line here — the\n331\t // #278 forgery, through a surface the progress module does not\n332\t // own. Sanitised for the same reason and by the same rule.\n333\t //\n334\t // Routing this through `Progress` as well (so `--quiet` is\n335\t // silent and `--progress json` stays one object per line) needs\n336\t // a handle the walker does not have; that is a separate change.\n337\t eprintln!(\n338\t \"walk: skipping unreadable entry: {}\",\n339\t crate::progress::sanitize(&e.to_string(), crate::progress::SAFE_PATH_MAX)\n340\t );\n341\t continue;\n342\t }\n343\t };\n344\t let is_dir = entry.file_type().is_dir();\n345\t // Retire the layers of directories this entry is no longer inside; see\n346\t // `IgnoreStack::truncate_to` for why every entry needs it, not just\n347\t // directories.\n348\t stack.truncate_to(entry.depth());\n349\t // SECURITY / hygiene: do not index hidden files or descend into hidden\n350\t // directories. Without this the walker happily indexed `.env` (secrets,\n351\t // API tokens), `.git`, `.ssh`, `.aws`, and other dotfiles into a\n352\t // queryable brain with no per-brain authorization — a real exposure for\n353\t // the \"point it at my project folder\" use case. A hidden directory is\n354\t // pruned before descending, so `.git/` is skipped whole. The root\n355\t // itself (depth 0) is exempt so a brain over a dot-named folder still\n356\t // works. `--no-ignore` does NOT turn this off: it is not one of the\n357\t // ignore rules, it is the main reason secrets stay out.\n358\t //\n359\t // The limit of that claim, stated because the rest of this file used to\n360\t // assert it without one: this is a rule about NAMES and, under\n361\t // `--follow-symlinks`, about where a link RESOLVES. A hard link has\n362\t // neither — it is a second directory entry for the same inode, so\n363\t // `ln .secretdir/k.txt notes.txt` reads the secret under a visible name\n364\t // and nothing here can tell. Defending that needs `(dev, ino)` of every\n365\t // hidden-rule exclusion, which a walk that prunes hidden directories\n366\t // without descending does not have. `cp -al`, `rsync --link-dest` and\n367\t // hard-linked package stores all produce that shape without an attacker.\n368\t if entry.depth() > 0 && is_hidden_name(entry.file_name()) {\n369\t stack.record_hidden(is_dir);\n370\t if is_dir {\n371\t it.skip_current_dir();\n372\t }\n373\t continue;\n374\t }\n375\t // The rule above judges the NAME the walk arrived by, which is the\n376\t // whole rule when links are not followed. Under `--follow-symlinks` it\n377\t // is not: a link is free to be called `notes.txt` and point at\n378\t // `.secretdir/k.txt`, and walkdir then yields the target's contents\n379\t // under the link's visible name. Both halves of the guarantee above\n380\t // fail that way — the secret is indexed, and a link to a directory\n381\t // outside the root drags in a tree the operator never pointed at\n382\t // (`shared -> /etc` indexes `/etc/shadow` as `shared/shadow`). The\n383\t // report made it worse by still saying the hidden directories were\n384\t // pruned, which was true of the traversal and false of the outcome.\n385\t //\n386\t // So under the flag the same two questions are asked of the RESOLVED\n387\t // path instead of the name. Loop-safety is walkdir's and unrelated;\n388\t // this is the secret rule and the root boundary.\n389\t // Resolving is only necessary once the walk has actually gone through a\n390\t // link. `canonicalize` is `realpath(3)` and issues one `readlinkat` per\n391\t // path component, so doing it for every entry costs 8-14 failing\n392\t // syscalls per file on an ordinary tree and made the walk 4.2x slower\n393\t // with 7.6x the syscalls — all of it wasted on paths where no link\n394\t // exists. `link_depth` is the shallowest depth at or below which some\n395\t // ancestor (or the entry itself) is a symlink; below that the walk path\n396\t // and the real path cannot differ.\n397\t if entry.path_is_symlink() {\n398\t link_depth = Some(link_depth.map_or(entry.depth(), |d: usize| d.min(entry.depth())));\n399\t } else if is_dir && link_depth.is_some_and(|d| entry.depth() <= d) {\n400\t link_depth = None;\n401\t }\n402\t let through_link = entry.path_is_symlink() || link_depth.is_some_and(|d| entry.depth() > d);\n403\t // The path every later stage should open. The guard resolves the entry\n404\t // to decide on it; keeping that resolution is what stops the decision\n405\t // being made about one file and the bytes being read from another.\n406\t // `content.rs` hashes and `lib.rs` extracts from `FileEntry::path`\n407\t // minutes after the walk on a large corpus, each a fresh `open()` that\n408\t // re-follows the link — so a link re-pointed in between handed the\n409\t // refused content straight into a document body. `rel` still comes from\n410\t // the walk path: that is the name the operator pointed at and the\n411\t // identity the index is keyed on.\n412\t let mut resolved: Option<PathBuf> = None;\n413\t if follow_symlinks && entry.depth() > 0 && through_link {\n414\t match escaped_or_hidden_target(&root_canon, entry.path()) {\n415\t Ok(real) => resolved = real,\n416\t // Admitted by the waiver — but with the RESOLVED path, so the\n417\t // bytes read later are the bytes that were judged. This arm was\n418\t // empty, which stored the walk path and re-followed the link at\n419\t // read time for everything the flag ingests.\n420\t Err(SymlinkVerdict::OutsideRoot(real)) if allow_outside_root => {\n421\t resolved = Some(real);\n422\t }\n423\t Err(SymlinkVerdict::HiddenOutsideRoot) => {\n424\t stack.record_symlink_hidden_escape(is_dir);\n425\t if is_dir {\n426\t it.skip_current_dir();\n427\t }\n428\t continue;\n429\t }\n430\t Err(SymlinkVerdict::OutsideRoot(_)) => {\n431\t stack.record_symlink_escape(is_dir);\n432\t if is_dir {\n433\t it.skip_current_dir();\n434\t }\n435\t continue;\n436\t }\n437\t Err(SymlinkVerdict::HiddenTarget) => {\n438\t stack.record_hidden(is_dir);\n439\t if is_dir {\n440\t it.skip_current_dir();\n441\t }\n442\t continue;\n443\t }\n444\t Err(SymlinkVerdict::Unresolvable) => {\n445\t stack.record_symlink_unresolved(is_dir);\n446\t if is_dir {\n447\t it.skip_current_dir();\n448\t }\n449\t continue;\n450\t }\n451\t }\n452\t }\n453\t if is_dir {\n454\t // The root is never judged by the rules below it: pointing\n455\t // autoindex at a folder is an explicit instruction, and the note\n456\t // explaining that it *would* have been ignored is on the report.\n457\t if entry.depth() > 0 && stack.skip_dir(entry.path()).is_some() {\n458\t it.skip_current_dir();\n459\t continue;\n460\t }\n461\t // Marker-gated generated dirs (part of the built-in defaults, so\n462\t // `--no-ignore` / `--no-default-ignores` disable it): names like\n463\t // Unity's `Library/` or `Logs/` are too common for the blunt\n464\t // DEFAULT_IGNORE_PATTERNS, so they are pruned only when a sibling\n465\t // marker file proves the parent is that kind of project.\n466\t if entry.depth() > 0 && marker_defaults {\n467\t if let Some(label) = marker_generated_dir(entry.path()) {\n468\t stack.record_marker_dir(entry.path(), label);\n469\t it.skip_current_dir();\n470\t continue;\n471\t }\n472\t }\n473\t stack.enter_dir(entry.path(), entry.depth());\n474\t if let Some(dirs) = dirs_out.as_mut() {\n475\t // The path the watcher must watch is the path the walk arrived\n476\t // by — the same one `rel` is derived from — so a followed link\n477\t // is watched where the operator pointed, not where it resolves.\n478\t dirs.push(entry.path().to_path_buf());\n479\t }\n480\t continue;\n481\t }\n482\t // Watch-set mode wants directories only; a file's metadata is a syscall\n483\t // per entry that nothing on this route reads.\n484\t if dirs_out.is_some() {\n485\t continue;\n486\t }\n487\t if !entry.file_type().is_file() {\n488\t continue;\n489\t }\n490\t if stack.skip_file(entry.path()).is_some() {\n491\t continue;\n492\t }\n493\t // Marker-gated Takeout noise (built-in defaults, so `--no-ignore` /\n494\t // `--no-default-ignores` disable it). After the ignore files, and\n495\t // yielding to them: a `!archive_browser.html` line in `.xerjignore`\n496\t // is an explicit instruction and wins.\n497\t if marker_defaults {\n498\t if let Some(label) = takeout_noise(entry.path()) {\n499\t if !stack.is_reincluded(entry.path(), false) {\n500\t stack.record_marker_file(label);\n501\t continue;\n502\t }\n503\t }\n504\t }\n505\t let md = match entry.metadata() {\n506\t Ok(m) => m,\n507\t Err(_) => continue,\n508\t };\n509\t let p = entry.path().to_path_buf();\n510\t let rel = p\n511\t .strip_prefix(&root_canon)\n512\t .unwrap_or(&p)\n513\t .to_string_lossy()\n514\t .replace('\\\\', \"/\");\n515\t let rel_id = stable_path_id(p.strip_prefix(&root_canon).unwrap_or(&p));\n516\t out.push(FileEntry {\n517\t path: resolved.unwrap_or(p),\n518\t rel,\n519\t rel_id,\n520\t is_symlink: entry\n521\t .path()\n522\t .symlink_metadata()\n523\t .is_ok_and(|m| m.file_type().is_symlink()),\n524\t size: md.len(),\n525\t });\n526\t }\n527\t // Deterministic order for clustering / naming.\n528\t out.sort_by(|a, b| a.rel.cmp(&b.rel));\n529\t Ok((out, stack.report))\n530\t}\n531\t\n532\t#[cfg(unix)]\n533\tfn stable_path_id(path: &Path) -> String {\n534\t use std::os::unix::ffi::OsStrExt;\n535\t let mut out = String::from(\"unix:\");\n536\t for byte in path.as_os_str().as_bytes() {\n537\t use std::fmt::Write;\n538\t write!(out, \"{byte:02x}\").expect(\"write string\");\n539\t }\n540\t out\n541\t}\n542\t\n543\t#[cfg(windows)]\n544\tfn stable_path_id(path: &Path) -> String {\n545\t use std::os::windows::ffi::OsStrExt;\n546\t let mut out = String::from(\"windows:\");\n547\t for unit in path.as_os_str().encode_wide() {\n548\t use std::fmt::Write;\n549\t write!(out, \"{unit:04x}\").expect(\"write string\");\n550\t }\n551\t out\n552\t}\n553\t\n554\t#[cfg(not(any(unix, windows)))]\n555\tfn stable_path_id(path: &Path) -> String {\n556\t format!(\"other:{}\", path.to_string_lossy())\n557\t}\n558\t\n559\t#[cfg(test)]\n560\tmod hidden_skip_tests {\n561\t use super::{escaped_or_hidden_target, SymlinkVerdict};\n562\t\n563\t /// The dispatch this file was refuted for. `canonicalize` failing is not\n564\t /// evidence that the entry is where it appears; only `NotFound` is.\n565\t ///\n566\t /// A path with an interior NUL cannot be canonicalised and reports\n567\t /// `InvalidInput`, which stands in here for the errno that actually\n568\t /// motivates the arm: `realpath(3)` is `PATH_MAX`-bounded while the kernel\n569\t /// is not, so a canonical path over that limit gives `ENAMETOOLONG` here\n570\t /// while `open` on the walk path still succeeds. That asymmetry is what\n571\t /// made `.ok()?` a bypass — the guard was skipped for precisely the entries\n572\t /// it could not vet.\n573\t #[test]\n574\t fn an_unresolvable_entry_is_refused_not_admitted() {\n575\t use std::ffi::OsStr;\n576\t use std::os::unix::ffi::OsStrExt;\n577\t\n578\t let dir = tempfile::tempdir().expect(\"tempdir\");\n579\t let root = dir.path().canonicalize().expect(\"canonical root\");\n580\t\n581\t // Exists and resolves inside the root: admitted.\n582\t std::fs::write(root.join(\"plain.txt\"), \"x\").unwrap();\n583\t assert!(\n584\t matches!(\n585\t escaped_or_hidden_target(&root, &root.join(\"plain.txt\")),\n586\t Ok(Some(_))\n587\t ),\n588\t \"an ordinary in-root file must resolve and be governed by the ordinary rules\"\n589\t );\n590\t\n591\t // Does not exist: nothing to leak, so also admitted — walkdir reports it.\n592\t assert!(\n593\t matches!(\n594\t escaped_or_hidden_target(&root, &root.join(\"gone.txt\")),\n595\t Ok(None)\n596\t ),\n597\t \"a dangling link has no target and must not be reported as a refusal\"\n598\t );\n599\t\n600\t // Cannot be resolved for any OTHER reason: refused.\n601\t let bad = root.join(OsStr::from_bytes(b\"nul\\0inside\"));\n602\t assert!(\n603\t matches!(\n604\t escaped_or_hidden_target(&root, &bad),\n605\t Err(SymlinkVerdict::Unresolvable)\n606\t ),\n607\t \"an unresolvable path must be refused — `could not compute` is not `yes`\"\n608\t );\n609\t }\n610\t\n611\t use super::walk;\n612\t use std::fs;\n613\t\n614\t #[test]\n615\t fn hidden_files_and_dirs_are_never_indexed() {\n616\t let dir = tempfile::TempDir::new().unwrap();\n617\t let root = dir.path();\n618\t fs::write(root.join(\"README.md\"), \"hello\").unwrap();\n619\t fs::write(root.join(\".env\"), \"SECRET=pat-abc123\").unwrap();\n620\t fs::create_dir(root.join(\".git\")).unwrap();\n621\t fs::write(root.join(\".git\").join(\"config\"), \"[core]\").unwrap();\n622\t fs::create_dir(root.join(\"src\")).unwrap();\n623\t fs::write(root.join(\"src\").join(\"main.rs\"), \"fn main() {}\").unwrap();\n624\t fs::write(root.join(\"src\").join(\".secret\"), \"nope\").unwrap();\n625\t\n626\t let rels: Vec<String> = walk(root, false)\n627\t .unwrap()\n628\t .into_iter()\n629\t .map(|e| e.rel)\n630\t .collect();\n631\t assert!(rels.contains(&\"README.md\".to_string()));\n632\t assert!(rels.contains(&\"src/main.rs\".to_string()));\n633\t // secrets and VCS internals must not be present\n634\t assert!(!rels.iter().any(|r| r == \".env\"), \"indexed .env: {rels:?}\");\n635\t assert!(\n636\t !rels.iter().any(|r| r.starts_with(\".git\")),\n637\t \"descended .git: {rels:?}\"\n638\t );\n639\t assert!(\n640\t !rels.iter().any(|r| r.ends_with(\".secret\")),\n641\t \"indexed a nested dotfile: {rels:?}\"\n642\t );\n643\t }\n644\t\n645\t /// A name whose first byte is '.' but is not valid UTF-8 must still be\n646\t /// treated as hidden. `file_name().to_str()` is `None` for that name, so\n647\t /// the UTF-8 `starts_with('.')` check misses it.\n648\t #[cfg(unix)]\n649\t #[test]\n650\t fn hidden_non_utf8_dot_name_is_detected() {\n651\t use crate::ignore_rules::is_hidden_name;\n652\t use std::ffi::OsStr;\n653\t use std::os::unix::ffi::OsStrExt;\n654\t\n655\t let hidden = OsStr::from_bytes(b\".\\x80\");\n656\t assert!(\n657\t hidden.to_str().is_none(),\n658\t \"fixture must be non-UTF-8 so to_str() cannot save us\"\n659\t );\n660\t assert!(\n661\t is_hidden_name(hidden),\n662\t \"first byte is '.', even when to_str() is None\"\n663\t );\n664\t assert!(is_hidden_name(OsStr::from_bytes(b\".env\")));\n665\t assert!(!is_hidden_name(OsStr::from_bytes(b\"README.md\")));\n666\t assert!(!is_hidden_name(OsStr::from_bytes(b\"\\x80env\")));\n667\t }\n668\t\n669\t /// Same name on disk. APFS/HFS reject non-UTF-8 names; Linux does not.\n670\t #[cfg(target_os = \"linux\")]\n671\t #[test]\n672\t fn hidden_non_utf8_dotfile_is_never_indexed() {\n673\t use std::ffi::OsStr;\n674\t use std::os::unix::ffi::OsStrExt;\n675\t\n676\t let dir = tempfile::TempDir::new().unwrap();\n677\t let root = dir.path();\n678\t fs::write(root.join(\"README.md\"), \"hello\").unwrap();\n679\t fs::write(root.join(OsStr::from_bytes(b\".\\x80\")), \"SECRET=pat-abc123\").unwrap();\n680\t\n681\t let files = walk(root, false).unwrap();\n682\t let rels: Vec<String> = files.iter().map(|e| e.rel.clone()).collect();\n683\t assert!(\n684\t rels.contains(&\"README.md\".to_string()),\n685\t \"visible file must still be indexed: {rels:?}\"\n686\t );\n687\t assert!(\n688\t !files.iter().any(|e| {\n689\t e.path\n690\t .file_name()\n691\t .is_some_and(|n| n.as_encoded_bytes().first() == Some(&b'.'))\n692\t }),\n693\t \"indexed a hidden non-UTF-8 name: {rels:?}\"\n694\t );\n695\t }\n696\t\n697\t /// #276: the walk itself must drop gitignored junk, not a later stage —\n698\t /// an ignored directory is never descended, so it never reaches hashing.\n699\t #[test]\n700\t fn the_walk_honours_gitignore_and_the_built_in_defaults() {\n701\t use super::walk_reporting;\n702\t use crate::ignore_rules::IgnoreOptions;\n703\t\n704\t let dir = tempfile::TempDir::new().unwrap();\n705\t let root = dir.path();\n706\t fs::write(root.join(\".gitignore\"), \"*.tmp\\ndocs/private/\\n\").unwrap();\n707\t fs::write(root.join(\"README.md\"), \"hello\").unwrap();\n708\t fs::write(root.join(\"scratch.tmp\"), \"junk\").unwrap();\n709\t fs::create_dir_all(root.join(\"docs/private\")).unwrap();\n710\t fs::write(root.join(\"docs/private/salary.md\"), \"secret\").unwrap();\n711\t fs::create_dir_all(root.join(\"target/debug\")).unwrap();\n712\t fs::write(root.join(\"target/debug/huge.rlib\"), \"bytes\").unwrap();\n713\t\n714\t let (files, report) = walk_reporting(root, false, IgnoreOptions::default()).unwrap();\n715\t let rels: Vec<String> = files.into_iter().map(|e| e.rel).collect();\n716\t assert_eq!(rels, vec![\"README.md\".to_string()], \"{rels:?}\");\n717\t // 2 = scratch.tmp, plus `.gitignore` itself under the (separate,\n718\t // non-optional) hidden-file rule.\n719\t assert_eq!(report.files_skipped, 2, \"{report:?}\");\n720\t assert_eq!(report.dirs_pruned, 2, \"{report:?}\");\n721\t assert_eq!(report.ignore_files_read, 1, \"{report:?}\");\n722\t\n723\t // --no-ignore brings all of it back, except the dotfiles.\n724\t let (all, off) = walk_reporting(root, false, IgnoreOptions::off()).unwrap();\n725\t let mut rels: Vec<String> = all.into_iter().map(|e| e.rel).collect();\n726\t rels.sort();\n727\t assert_eq!(\n728\t rels,\n729\t vec![\n730\t \"README.md\".to_string(),\n731\t \"docs/private/salary.md\".to_string(),\n732\t \"scratch.tmp\".to_string(),\n733\t \"target/debug/huge.rlib\".to_string(),\n734\t ],\n735\t \"{rels:?}\"\n736\t );\n737\t assert_eq!(off.dirs_pruned, 0, \"{off:?}\");\n738\t }\n739\t\n740\t /// Create a real checkout at `path`. Returns false when the `git` binary\n741\t /// is unavailable, in which case the caller still gets the on-disk shape\n742\t /// that matters (`.git/HEAD`) but skips the parity cross-check.\n743\t #[cfg(test)]\n744\t fn git_init(path: &std::path::Path) -> bool {\n745\t fs::create_dir_all(path).unwrap();\n746\t let ok = std::process::Command::new(\"git\")\n747\t // A developer's global gitignore or an enclosing repo's config\n748\t // must not decide what this test sees.\n749\t .env(\"GIT_CONFIG_GLOBAL\", \"/dev/null\")\n750\t .env(\"GIT_CONFIG_SYSTEM\", \"/dev/null\")\n751\t .args([\"init\", \"-q\"])\n752\t .current_dir(path)\n753\t .status()\n754\t .is_ok_and(|s| s.success());\n755\t if !ok {\n756\t fs::create_dir_all(path.join(\".git\")).unwrap();\n757\t fs::write(path.join(\".git\").join(\"HEAD\"), \"ref: refs/heads/main\\n\").unwrap();\n758\t }\n759\t ok\n760\t }\n761\t\n762\t /// Files a repository considers its own and does not ignore, as git itself\n763\t /// reports them. Dotfiles are dropped because XERJ's separate, non-optional\n764\t /// hidden-file rule removes them before any ignore rule is consulted.\n765\t #[cfg(test)]\n766\t fn git_untracked_visible_files(repo: &std::path::Path) -> Vec<String> {\n767\t let out = std::process::Command::new(\"git\")\n768\t .env(\"GIT_CONFIG_GLOBAL\", \"/dev/null\")\n769\t .env(\"GIT_CONFIG_SYSTEM\", \"/dev/null\")\n770\t .args([\"status\", \"--porcelain\", \"--untracked-files=all\"])\n771\t .current_dir(repo)\n772\t .output()\n773\t .expect(\"git status\");\n774\t let mut files: Vec<String> = String::from_utf8_lossy(&out.stdout)\n775\t .lines()\n776\t .filter_map(|l| l.strip_prefix(\"?? \"))\n777\t .map(|p| p.trim_matches('\"').to_string())\n778\t .filter(|p| !p.split('/').any(|c| c.starts_with('.')))\n779\t .collect();\n780\t files.sort();\n781\t files\n782\t }\n783\t\n784\t /// #279 (follow-up to #276). An outer repository's `.gitignore` must not\n785\t /// judge files inside a nested checkout.\n786\t ///\n787\t /// This is git's authority model, not a nicety: the repository that owns a\n788\t /// file decides whether it is ignored. `git status` in the outer repo does\n789\t /// not descend into a nested checkout at all, and `git status` inside the\n790\t /// nested one never consults the outer's `.gitignore`. The first cut of\n791\t /// this feature walked every layer with no boundary stop, so a root `*.md`\n792\t /// hid the README of every vendored dependency below it.\n793\t ///\n794\t /// The fixture is a real nested checkout — the boundary is a `.git` on\n795\t /// disk, so a matcher-level unit test could not have caught this.\n796\t #[test]\n797\t fn an_outer_repository_does_not_judge_a_nested_checkout() {\n798\t use super::walk_reporting;\n799\t use crate::ignore_rules::IgnoreOptions;\n800\t\n801\t let dir = tempfile::TempDir::new().unwrap();\n802\t let root = dir.path().join(\"outer\");\n803\t let have_git = git_init(&root);\n804\t fs::write(root.join(\".gitignore\"), \"*.md\\n\").unwrap();\n805\t fs::write(root.join(\"OUTER.md\"), \"outer, and outer's to ignore\").unwrap();\n806\t fs::write(root.join(\"keep.txt\"), \"x\").unwrap();\n807\t\n808\t let inner = root.join(\"vendored\");\n809\t git_init(&inner);\n810\t fs::write(inner.join(\".gitignore\"), \"local-junk.txt\\n\").unwrap();\n811\t fs::write(inner.join(\"README.md\"), \"the vendored project's own README\").unwrap();\n812\t fs::write(inner.join(\"local-junk.txt\"), \"inner's own rule drops this\").unwrap();\n813\t fs::create_dir_all(inner.join(\"src\")).unwrap();\n814\t fs::write(inner.join(\"src\").join(\"guide.md\"), \"also the inner repo's\").unwrap();\n815\t\n816\t let (files, _) = walk_reporting(&root, false, IgnoreOptions::default()).unwrap();\n817\t let mut rels: Vec<String> = files.into_iter().map(|e| e.rel).collect();\n818\t rels.sort();\n819\t assert_eq!(\n820\t rels,\n821\t vec![\n822\t \"keep.txt\".to_string(),\n823\t \"vendored/README.md\".to_string(),\n824\t \"vendored/src/guide.md\".to_string(),\n825\t ],\n826\t \"the outer *.md must stop at the nested checkout, and the inner \\\n827\t repo's own rule must still apply inside it: {rels:?}\"\n828\t );\n829\t\n830\t // Parity with the tool whose semantics we claim to reproduce: the set\n831\t // XERJ keeps under `vendored/` is the set the nested repository itself\n832\t // reports as its own, unignored, visible files.\n833\t if have_git {\n834\t let from_git = git_untracked_visible_files(&inner);\n835\t assert_eq!(\n836\t from_git,\n837\t vec![\"README.md\".to_string(), \"src/guide.md\".to_string()],\n838\t \"fixture drifted from git's own answer\"\n839\t );\n840\t let from_xerj: Vec<String> = rels\n841\t .iter()\n842\t .filter_map(|r| r.strip_prefix(\"vendored/\").map(str::to_string))\n843\t .collect();\n844\t assert_eq!(from_xerj, from_git, \"XERJ and git must agree\");\n845\t }\n846\t }\n847\t\n848\t /// The other half of the boundary: `.xerjignore` is XERJ's own file, not\n849\t /// git's, and its stated job is to govern the folder you pointed at. It\n850\t /// deliberately keeps its authority across a nested checkout, so one file\n851\t /// at the root can say \"not this, anywhere below here\".\n852\t #[test]\n853\t fn a_root_xerjignore_still_reaches_into_a_nested_checkout() {\n854\t use super::walk_reporting;\n855\t use crate::ignore_rules::IgnoreOptions;\n856\t\n857\t let dir = tempfile::TempDir::new().unwrap();\n858\t let root = dir.path().join(\"outer\");\n859\t git_init(&root);\n860\t fs::write(root.join(\".xerjignore\"), \"*.md\\n\").unwrap();\n861\t fs::write(root.join(\"keep.txt\"), \"x\").unwrap();\n862\t\n863\t let inner = root.join(\"vendored\");\n864\t git_init(&inner);\n865\t fs::write(inner.join(\"README.md\"), \"x\").unwrap();\n866\t fs::write(inner.join(\"code.rs\"), \"x\").unwrap();\n867\t\n868\t let (files, _) = walk_reporting(&root, false, IgnoreOptions::default()).unwrap();\n869\t let mut rels: Vec<String> = files.into_iter().map(|e| e.rel).collect();\n870\t rels.sort();\n871\t assert_eq!(\n872\t rels,\n873\t vec![\"keep.txt\".to_string(), \"vendored/code.rs\".to_string()],\n874\t \"{rels:?}\"\n875\t );\n876\t }\n877\t\n878\t #[test]\n879\t fn a_brain_over_a_dot_named_root_still_works() {\n880\t let dir = tempfile::TempDir::new().unwrap();\n881\t let root = dir.path().join(\".notes\");\n882\t fs::create_dir(&root).unwrap();\n883\t fs::write(root.join(\"a.md\"), \"x\").unwrap();\n884\t let rels: Vec<String> = walk(&root, false)\n885\t .unwrap()\n886\t .into_iter()\n887\t .map(|e| e.rel)\n888\t .collect();\n889\t assert_eq!(\n890\t rels,\n891\t vec![\"a.md\".to_string()],\n892\t \"root exemption failed: {rels:?}\"\n893\t );\n894\t }\n895\t}\n896\t\n897\t#[cfg(test)]\n898\tmod marker_generated_dir_tests {\n899\t use super::{walk, walk_reporting};\n900\t use crate::ignore_rules::IgnoreOptions;\n901\t use std::fs;\n902\t use std::path::Path;\n903\t\n904\t fn make_unity_project(root: &Path, with_marker: bool) {\n905\t fs::create_dir_all(root.join(\"Assets\")).unwrap();\n906\t fs::write(root.join(\"Assets/Player.cs\"), \"class Player {}\").unwrap();\n907\t fs::create_dir_all(root.join(\"Library/Artifacts\")).unwrap();\n908\t fs::write(root.join(\"Library/Artifacts/blob.bin\"), b\"\\x00\\x01\").unwrap();\n909\t fs::create_dir_all(root.join(\"Logs\")).unwrap();\n910\t fs::write(root.join(\"Logs/editor.log\"), \"x\").unwrap();\n911\t if with_marker {\n912\t fs::create_dir_all(root.join(\"ProjectSettings\")).unwrap();\n913\t fs::write(\n914\t root.join(\"ProjectSettings/ProjectVersion.txt\"),\n915\t \"m_EditorVersion: 2022.3.10f1\\n\",\n916\t )\n917\t .unwrap();\n918\t }\n919\t }\n920\t\n921\t /// Monorepo case: the Unity project is a SUBFOLDER of the walk root; the\n922\t /// sibling marker decides at any depth.\n923\t #[test]\n924\t fn a_nested_unity_project_is_pruned_and_reported() {\n925\t let dir = tempfile::TempDir::new().unwrap();\n926\t let unity = dir.path().join(\"platform/unity\");\n927\t fs::create_dir_all(&unity).unwrap();\n928\t make_unity_project(&unity, true);\n929\t let (files, report) = walk_reporting(dir.path(), false, IgnoreOptions::default()).unwrap();\n930\t let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();\n931\t assert!(rels.contains(&\"platform/unity/Assets/Player.cs\"));\n932\t assert!(\n933\t !rels.iter().any(|r| r.contains(\"/Library/\")),\n934\t \"Library/ must be pruned whole: {rels:?}\"\n935\t );\n936\t assert!(\n937\t report\n938\t .by_rule\n939\t .keys()\n940\t .any(|k| k == \"default:unity-generated\"),\n941\t \"the prune must be named on the report: {report:?}\"\n942\t );\n943\t }\n944\t\n945\t /// Without the marker, a folder merely NAMED Library or Logs is data.\n946\t #[test]\n947\t fn without_the_marker_nothing_is_pruned() {\n948\t let dir = tempfile::TempDir::new().unwrap();\n949\t make_unity_project(dir.path(), false);\n950\t let files = walk(dir.path(), false).unwrap();\n951\t let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();\n952\t assert!(rels.contains(&\"Library/Artifacts/blob.bin\"), \"{rels:?}\");\n953\t assert!(rels.contains(&\"Logs/editor.log\"), \"{rels:?}\");\n954\t }\n955\t\n956\t /// The marker rule is one of the built-in defaults, so both switches\n957\t /// disable it.\n958\t #[test]\n959\t fn no_ignore_and_no_default_ignores_both_disable_the_marker_rule() {\n960\t let dir = tempfile::TempDir::new().unwrap();\n961\t make_unity_project(dir.path(), true);\n962\t let no_defaults = IgnoreOptions {\n963\t defaults: false,\n964\t ..IgnoreOptions::default()\n965\t };\n966\t for opts in [IgnoreOptions::off(), no_defaults] {\n967\t let (files, _) = walk_reporting(dir.path(), false, opts).unwrap();\n968\t let rels: Vec<&str> = files.iter().map(|e| e.rel.as_str()).collect();\n969\t assert!(\n970\t rels.contains(&\"Library/Artifacts/blob.bin\"),\n971\t \"opts {opts:?} must walk generated dirs: {rels:?}\"\n972\t );\n973\t }\n974\t }\n975\t\n976\t #[test]\n977\t fn a_file_named_like_a_generated_dir_is_not_pruned() {\n978\t let dir = tempfile::TempDir::new().unwrap();\n979\t make_unity_project(dir.path(), true);\n980\t fs::write(dir.path().join(\"obj\"), \"a FILE named obj\").unwrap();\n981\t let files = walk(dir.path(), false).unwrap();\n982\t assert!(\n983\t files.iter().any(|e| e.rel == \"obj\"),\n984\t \"the prune applies to directories only\"\n985\t );\n986\t }\n987\t}\n988\t\n989\t#[cfg(test)]\n990\tmod takeout_noise_tests {\n991\t use super::{walk_reporting, TAKEOUT_INDEX_RULE, TAKEOUT_KEEP_TWIN_RULE};\n992\t use crate::ignore_rules::IgnoreOptions;\n993\t use std::fs;\n994\t use std::path::Path;\n995\t\n996\t const KEEP_NOTE: &str = r#\"{\"isTrashed\":false,\"isPinned\":false,\"isArchived\":false,\n997\t \"textContent\":\"call Dana\",\"title\":\"todo\",\n998\t \"userEditedTimestampUsec\":1700000000000000,\"createdTimestampUsec\":1700000000000000}\"#;\n999\t\n1000\t /// `Takeout/` with mail, one Keep note (exported twice, as Takeout does),\n1001\t /// and an unrelated html/json pair that must survive.\n1002\t fn make_takeout(root: &Path, with_marker: bool) {\n1003\t let t = root.join(\"Takeout\");\n1004\t fs::create_dir_all(t.join(\"Mail\")).unwrap();\n1005\t fs::create_dir_all(t.join(\"Keep\")).unwrap();\n1006\t fs::create_dir_all(t.join(\"Drive\")).unwrap();\n1007\t if with_marker {\n1008\t fs::write(t.join(\"archive_browser.html\"), \"<html>index</html>\").unwrap();\n1009\t }\n1010\t fs::write(t.join(\"Mail/All mail Including Spam and Trash.mbox\"), \"x\").unwrap();\n1011\t fs::write(t.join(\"Keep/todo.json\"), KEEP_NOTE).unwrap();\n1012\t fs::write(t.join(\"Keep/todo.html\"), \"<html>call Dana</html>\").unwrap();\n1013\t // A note whose name is not ASCII: the twin lookup is path-based and\n1014\t // must never slice a name by bytes.\n1015\t fs::write(t.join(\"Keep/設計書 مرحبا.json\"), KEEP_NOTE).unwrap();\n1016\t fs::write(t.join(\"Keep/設計書 مرحبا.html\"), \"<html>x</html>\").unwrap();\n1017\t // Not a Keep note: an html beside a json that is ordinary data.\n1018\t fs::write(t.join(\"Drive/report.json\"), r#\"{\"rows\":[1,2,3]}\"#).unwrap();\n1019\t fs::write(t.join(\"Drive/report.html\"), \"<html>report</html>\").unwrap();\n1020\t // An html with no json twin at all.\n1021\t fs::write(t.join(\"Keep/orphan.html\"), \"<html>orphan</html>\").unwrap();\n1022\t }\n1023\t\n1024\t fn rels(root: &Path, opts: IgnoreOptions) -> (Vec<String>, crate::ignore_rules::IgnoreReport) {\n1025\t let (files, report) = walk_reporting(root, false, opts).unwrap();\n1026\t (files.into_iter().map(|e| e.rel).collect(), report)\n1027\t }\n1028\t\n1029\t #[test]\n1030\t fn the_export_index_and_keep_html_twins_are_skipped_and_named() {\n1031\t let dir = tempfile::TempDir::new().unwrap();\n1032\t make_takeout(dir.path(), true);\n1033\t let (rels, report) = rels(dir.path(), IgnoreOptions::default());\n1034\t assert!(\n1035\t !rels.iter().any(|r| r.ends_with(\"archive_browser.html\")),\n1036\t \"{rels:?}\"\n1037\t );\n1038\t assert!(\n1039\t !rels.contains(&\"Takeout/Keep/todo.html\".to_string()),\n1040\t \"{rels:?}\"\n1041\t );\n1042\t assert!(\n1043\t !rels.contains(&\"Takeout/Keep/設計書 مرحبا.html\".to_string()),\n1044\t \"{rels:?}\"\n1045\t );\n1046\t // The data itself is all still there.\n1047\t for kept in [\n1048\t \"Takeout/Mail/All mail Including Spam and Trash.mbox\",\n1049\t \"Takeout/Keep/todo.json\",\n1050\t \"Takeout/Keep/設計書 مرحبا.json\",\n1051\t \"Takeout/Keep/orphan.html\",\n1052\t \"Takeout/Drive/report.html\",\n1053\t \"Takeout/Drive/report.json\",\n1054\t ] {\n1055\t assert!(\n1056\t rels.contains(&kept.to_string()),\n1057\t \"{kept} missing from {rels:?}\"\n1058\t );\n1059\t }\n1060\t // Never silent: each rule is on the report with its count.\n1061\t assert_eq!(report.by_rule[TAKEOUT_INDEX_RULE].files, 1, \"{report:?}\");\n1062\t assert_eq!(\n1063\t report.by_rule[TAKEOUT_KEEP_TWIN_RULE].files, 2,\n1064\t \"{report:?}\"\n1065\t );\n1066\t assert_eq!(report.files_skipped, 3);\n1067\t }\n1068\t\n1069\t /// Pointing autoindex INSIDE the export (at `Takeout/` itself) is the same\n1070\t /// export: the marker is found in the root, not in a folder named Takeout.\n1071\t #[test]\n1072\t fn the_takeout_folder_itself_can_be_the_root() {\n1073\t let dir = tempfile::TempDir::new().unwrap();\n1074\t make_takeout(dir.path(), true);\n1075\t let (rels, report) = rels(&dir.path().join(\"Takeout\"), IgnoreOptions::default());\n1076\t assert!(\n1077\t !rels.contains(&\"archive_browser.html\".to_string()),\n1078\t \"{rels:?}\"\n1079\t );\n1080\t assert!(!rels.contains(&\"Keep/todo.html\".to_string()), \"{rels:?}\");\n1081\t assert!(rels.contains(&\"Keep/todo.json\".to_string()), \"{rels:?}\");\n1082\t assert_eq!(report.by_rule[TAKEOUT_KEEP_TWIN_RULE].files, 2);\n1083\t }\n1084\t\n1085\t /// No marker, no Takeout: a folder that merely has a `Keep/` with paired\n1086\t /// files keeps every one of them.\n1087\t #[test]\n1088\t fn without_the_marker_nothing_is_skipped() {\n1089\t let dir = tempfile::TempDir::new().unwrap();\n1090\t make_takeout(dir.path(), false);\n1091\t let (rels, report) = rels(dir.path(), IgnoreOptions::default());\n1092\t assert!(\n1093\t rels.contains(&\"Takeout/Keep/todo.html\".to_string()),\n1094\t \"{rels:?}\"\n1095\t );\n1096\t assert_eq!(report.files_skipped, 0, \"{report:?}\");\n1097\t }\n1098\t\n1099\t /// An `archive_browser.html` deeper than a product folder does not make\n1100\t /// its grand-children Takeout products: only `<root>/<product>/X.html`.\n1101\t #[test]\n1102\t fn the_twin_rule_reaches_one_level_below_the_marker_only() {\n1103\t let dir = tempfile::TempDir::new().unwrap();\n1104\t make_takeout(dir.path(), true);\n1105\t let deep = dir.path().join(\"Takeout/Keep/sub\");\n1106\t fs::create_dir_all(&deep).unwrap();\n1107\t fs::write(deep.join(\"n.json\"), KEEP_NOTE).unwrap();\n1108\t fs::write(deep.join(\"n.html\"), \"<html>n</html>\").unwrap();\n1109\t let (rels, _) = rels(dir.path(), IgnoreOptions::default());\n1110\t assert!(\n1111\t rels.contains(&\"Takeout/Keep/sub/n.html\".to_string()),\n1112\t \"{rels:?}\"\n1113\t );\n1114\t }\n1115\t\n1116\t #[test]\n1117\t fn both_switches_disable_it_and_an_ignore_file_can_reinclude() {\n1118\t let dir = tempfile::TempDir::new().unwrap();\n1119\t make_takeout(dir.path(), true);\n1120\t let no_defaults = IgnoreOptions {\n1121\t defaults: false,\n1122\t ..IgnoreOptions::default()\n1123\t };\n1124\t for opts in [IgnoreOptions::off(), no_defaults] {\n1125\t let (rels, _) = rels(dir.path(), opts);\n1126\t assert!(\n1127\t rels.contains(&\"Takeout/archive_browser.html\".to_string()),\n1128\t \"{opts:?}\"\n1129\t );\n1130\t assert!(\n1131\t rels.contains(&\"Takeout/Keep/todo.html\".to_string()),\n1132\t \"{opts:?}\"\n1133\t );\n1134\t }\n1135\t // `!name` in .xerjignore outranks the built-in rule.\n1136\t fs::write(dir.path().join(\".xerjignore\"), \"!archive_browser.html\\n\").unwrap();\n1137\t let (rels, report) = rels(dir.path(), IgnoreOptions::default());\n1138\t assert!(\n1139\t rels.contains(&\"Takeout/archive_browser.html\".to_string()),\n1140\t \"{rels:?}\"\n1141\t );\n1142\t assert!(\n1143\t !report.by_rule.contains_key(TAKEOUT_INDEX_RULE),\n1144\t \"{report:?}\"\n1145\t );\n1146\t assert!(\n1147\t !rels.contains(&\"Takeout/Keep/todo.html\".to_string()),\n1148\t \"twins still skipped\"\n1149\t );\n1150\t }\n1151\t\n1152\t /// A json twin that is broken, huge, or a directory is not a Keep note, and\n1153\t /// doubt means INDEX the html. None of these may panic (panic = abort).\n1154\t #[test]\n1155\t fn a_twin_that_is_not_a_readable_keep_note_skips_nothing() {\n1156\t let dir = tempfile::TempDir::new().unwrap();\n1157\t make_takeout(dir.path(), true);\n1158\t let keep = dir.path().join(\"Takeout/Keep\");\n1159\t fs::write(keep.join(\"broken.json\"), b\"{\\\"isTrashed\\\": \\xff\\xfe\").unwrap();\n1160\t fs::write(keep.join(\"broken.html\"), \"<html>b</html>\").unwrap();\n1161\t fs::create_dir_all(keep.join(\"isdir.json\")).unwrap();\n1162\t fs::write(keep.join(\"isdir.html\"), \"<html>d</html>\").unwrap();\n1163\t let mut big = String::from(KEEP_NOTE.trim_end_matches('}'));\n1164\t big.push_str(&format!(\",\\\"pad\\\":\\\"{}\\\"}}\", \"x\".repeat((1 << 20) + 16)));\n1165\t fs::write(keep.join(\"big.json\"), big).unwrap();\n1166\t fs::write(keep.join(\"big.html\"), \"<html>big</html>\").unwrap();\n1167\t let (rels, _) = rels(dir.path(), IgnoreOptions::default());\n1168\t for kept in [\"broken.html\", \"isdir.html\", \"big.html\"] {\n1169\t assert!(\n1170\t rels.contains(&format!(\"Takeout/Keep/{kept}\")),\n1171\t \"{kept}: {rels:?}\"\n1172\t );\n1173\t }\n1174\t }\n1175\t}\n1176\t"}]},"uuid":"07ca0ebc-344d-4a99-afce-f224f3222f69","timestamp":"2026-10-01T15:39:08.392Z","sourceToolAssistantUUID":"fb88dbf8-9d88-4eca-ae6f-2b78bd752056","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"07ca0ebc-344d-4a99-afce-f224f3222f69","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202542158b839f4242645ac","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The zip extraction in harvest/source.rs looks reasonably defended. Let me check `sanitize_entry_path` fully (the rest after line 220).\n\nAlso important: `extract_zip` uses `z.by_index(i)` — the zip crate decodes. `entry.is_symlink()` handled. Decompression cap 2GiB — but note that the cap is checked AFTER reading the entry with `take(limit+1)`. `limit = MAX - total`, so per-entry read is bounded by remaining budget. Good.\n\nBut: `std::fs::write(&out, &buf)` — the whole entry is buffered in memory. A single entry claiming 2 GiB → 2 GiB RAM allocated. That's a memory exhaustion but bounded at 2 GiB.\n\nNow let me check sanitize_entry_path remainder, and whether there are other extraction paths (docx, pack.rs unpacking of packs — \"unpack a pack\"). Let's check harvest/pack.rs and harvest/identity.rs for download/unpack, and objsource.rs (S3). Also `content.rs` (blob writes).\n\nLet me read the rest of sanitize_entry_path and grep for where extract_zip is called from (is it from untrusted HTTP zip? yes — http-zip source). Also look for other `unpack` functions.","signature":"93dd3be5df0b48bb91d98c54"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"df6a612f-4e8d-439d-a4f9-af9ad0e3ae56","timestamp":"2026-10-01T15:39:20.803Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"df6a612f-4e8d-439d-a4f9-af9ad0e3ae56","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202542158b839f4242645ac","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_395651c27d2744ae8fcd43f3","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/harvest/source.rs","limit":100,"offset":200}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"4b5788ad-2152-43eb-b8bd-9a2542a1b61b","timestamp":"2026-10-01T15:39:20.805Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4b5788ad-2152-43eb-b8bd-9a2542a1b61b","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_395651c27d2744ae8fcd43f3","type":"tool_result","content":"200\t\n201\t/// Reject absolute paths, drive letters, `..`, and anything not expressible\n202\t/// as normal relative components (the zip-slip family). Returns the\n203\t/// posix-style relative path. Windows-style names (`C:/x`, `a\\\\b`) are\n204\t/// rejected on EVERY os — a pack may be built anywhere, and a name that is\n205\t/// a harmless subdir on linux is an escape on windows.\n206\tfn sanitize_entry_path(raw: &str) -> Option<String> {\n207\t let path = Path::new(raw);\n208\t let mut parts: Vec<&str> = Vec::new();\n209\t for c in path.components() {\n210\t match c {\n211\t Component::Normal(p) => {\n212\t let s = p.to_str()?;\n213\t if s.is_empty()\n214\t || s == \".\"\n215\t || s.contains('\\0')\n216\t || s.contains(':')\n217\t || s.contains('\\\\')\n218\t {\n219\t return None;\n220\t }\n221\t parts.push(s);\n222\t }\n223\t // a leading `/` makes it absolute on unix; Prefix is a windows\n224\t // drive; CurDir/ParentDir have no business in an entry name\n225\t _ => return None,\n226\t }\n227\t }\n228\t if parts.is_empty() {\n229\t return None;\n230\t }\n231\t Some(parts.join(\"/\"))\n232\t}\n233\t\n234\t#[cfg(test)]\n235\tmod tests {\n236\t use super::*;\n237\t\n238\t fn write_zip(path: &Path, entries: &[(&str, &str)]) {\n239\t let f = std::fs::File::create(path).unwrap();\n240\t let mut z = zip::ZipWriter::new(f);\n241\t let opts: zip::write::SimpleFileOptions = zip::write::SimpleFileOptions::default()\n242\t .compression_method(zip::CompressionMethod::Deflated);\n243\t for (name, body) in entries {\n244\t z.start_file(*name, opts).unwrap();\n245\t use std::io::Write;\n246\t z.write_all(body.as_bytes()).unwrap();\n247\t }\n248\t z.finish().unwrap();\n249\t }\n250\t\n251\t #[test]\n252\t fn zip_extracts_nested_and_replaces() {\n253\t let tmp = tempfile::tempdir().unwrap();\n254\t let zp = tmp.path().join(\"d.zip\");\n255\t write_zip(\n256\t &zp,\n257\t &[\n258\t (\"a.json\", \"{\\\"id\\\":\\\"x\\\"}\"),\n259\t (\"nested/b.json\", \"{\\\"id\\\":\\\"y\\\"}\"),\n260\t ],\n261\t );\n262\t let dest = tmp.path().join(\"out\");\n263\t assert_eq!(extract_zip(&zp, &dest).unwrap(), 0);\n264\t assert_eq!(\n265\t std::fs::read_to_string(dest.join(\"a.json\")).unwrap(),\n266\t \"{\\\"id\\\":\\\"x\\\"}\"\n267\t );\n268\t assert_eq!(\n269\t std::fs::read_to_string(dest.join(\"nested/b.json\")).unwrap(),\n270\t \"{\\\"id\\\":\\\"y\\\"}\"\n271\t );\n272\t\n273\t // a re-extract with a renamed file must not leave the stale one\n274\t write_zip(&zp, &[(\"renamed.json\", \"{}\")]);\n275\t extract_zip(&zp, &dest).unwrap();\n276\t assert!(!dest.join(\"a.json\").exists());\n277\t assert!(dest.join(\"renamed.json\").exists());\n278\t }\n279\t\n280\t #[test]\n281\t fn zip_slip_and_absolute_are_skipped_counted() {\n282\t let tmp = tempfile::tempdir().unwrap();\n283\t let outside = tmp.path().join(\"outside.txt\");\n284\t let zp = tmp.path().join(\"evil.zip\");\n285\t write_zip(\n286\t &zp,\n287\t &[\n288\t (\"ok.json\", \"{}\"),\n289\t (\"../outside.txt\", \"pwned\"),\n290\t (\"/abs.json\", \"{}\"),\n291\t (\"C:/windows/evil.txt\", \"{}\"),\n292\t ],\n293\t );\n294\t let dest = tmp.path().join(\"out\");\n295\t let skipped = extract_zip(&zp, &dest).unwrap();\n296\t assert!(dest.join(\"ok.json\").exists());\n297\t assert!(!outside.exists(), \"nothing escaped the extraction root\");\n298\t assert_eq!(skipped, 3, \"absolute + escape entries counted, not written\");\n299\t }"}]},"uuid":"dbaf5f97-2215-48ab-8ad6-336378ae2106","timestamp":"2026-10-01T15:39:20.810Z","sourceToolAssistantUUID":"4b5788ad-2152-43eb-b8bd-9a2542a1b61b","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"dbaf5f97-2215-48ab-8ad6-336378ae2106","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202542158b839f4242645ac","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_39b4c306f45643bfb3d34940","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex && grep -rn \"extract_zip\\|sanitize_entry_path\" src/ | grep -v \"^src/harvest/source.rs\" | head -20; echo \"=== UNPACK/pack download ===\"; grep -rn \"fn unpack\\|fn install\\|fn download\\|fn fetch\" src/harvest/*.rs src/objsource.rs | head -30","description":"Find extract_zip callers and other unpack paths"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":17305,"cache_creation_input_tokens":0,"cache_read_input_tokens":105472,"output_tokens":425,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"6e3f3483-69d5-4310-ba89-a06a56a2e98e","timestamp":"2026-10-01T15:39:23.085Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6e3f3483-69d5-4310-ba89-a06a56a2e98e","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_39b4c306f45643bfb3d34940","type":"tool_result","content":"src/xc.rs:431: if let Err(e) = crate::harvest::source::extract_zip(Path::new(&zip), &dest) {\nsrc/harvest/httpget.rs:18:/// (a small zip can expand enormously — see `source::extract_zip`).\n=== UNPACK/pack download ===\nsrc/harvest/httpget.rs:25:pub fn download(url: &str, dest: &Path) -> Result<u64> {\nsrc/harvest/httpget.rs:123: fn downloads_and_retries() {\nsrc/harvest/source.rs:51:pub fn fetch(src: &SourceSpec, recipe_dir: &Path, cache_dir: &Path) -> Result<Fetched> {\nsrc/objsource.rs:597:pub fn fetch_concurrency(scan_workers: usize) -> usize {\nsrc/objsource.rs:805:fn fetch_objects(\nsrc/objsource.rs:856:fn fetch_one(run: &ObjectRun, source: &dyn DocSource, entry: &SourceEntry) -> Result<FetchOutcome> {\nsrc/objsource.rs:1631: fn fetch_concurrency_is_bounded_both_ends() {","is_error":false}]},"uuid":"4779e90c-9d9e-49c1-9a1d-7dbaed9f86b1","timestamp":"2026-10-01T15:39:23.117Z","sourceToolAssistantUUID":"6e3f3483-69d5-4310-ba89-a06a56a2e98e","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4779e90c-9d9e-49c1-9a1d-7dbaed9f86b1","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025435d0875332b68d4074","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The zip extraction path is well-defended. Now, let me focus on the extractors that read untrusted content. The key ingest path: `lib.rs` in autoindex calls `scan_file` → `extract::*`. Let's look for panics (unwrap/expect/indexing/slicing) in the extractors reachable from doc bytes. And `extract/pdf.rs` (PDF parsing is a classic integer-overflow/OOB area), `extract/docx.rs`, `extract/mbox.rs`, `extract/eml.rs`, `extract/sqlite_x.rs`, `extract/code.rs` (tree-sitter).\n\nAlso, importantly: how do documents get into the engine? The bulk path. Let me check `xerj-engine/src/bulk.rs` around line 1785 for the pipeline call, and see what document-derived things happen.\n\nGiven the task focus is the wasm pipeline/builtins + autoindex hostile file parsing, let me prioritize:\n\n1. Check bulk.rs ingest path for doc-content-driven behavior.\n2. Scan autoindex extractors for panics: grep for `unwrap()`, `expect(`, `[..]` slicing, `as usize` casts of untrusted lengths.\n\nLet me look at pdf.rs and docx.rs and mbox.rs quickly, plus grep for risky patterns across extract/.\n\nActually first let me confirm: does the ingest of untrusted docs go through autoindex extractors in a server context, or is autoindex a CLI? Check lib.rs head and how it's wired. Let me check if xerj-server depends on xerj-autoindex.","signature":"7d66e508083b4800a6f064dc"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"04b6cafe-c464-4374-a445-357740e471ae","timestamp":"2026-10-01T15:39:39.282Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"04b6cafe-c464-4374-a445-357740e471ae","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025435d0875332b68d4074","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_19845d195f3e40f2b1e76ce1","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates && for c in xerj-server xerj-api xerj-engine; do echo \"=== $c ===\"; grep -n \"xerj-autoindex\\|xerj-wasm\" $c/Cargo.toml; done; echo \"=== autoindex bin/lib ===\"; sed -n '1,40p' xerj-autoindex/src/lib.rs","description":"Check crate dependencies for autoindex"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"904cd99c-9632-4eb5-ba0b-aca59b0885ae","timestamp":"2026-10-01T15:39:41.455Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"904cd99c-9632-4eb5-ba0b-aca59b0885ae","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_19845d195f3e40f2b1e76ce1","type":"tool_result","content":"=== xerj-server ===\n26:xerj-autoindex = { path = \"../xerj-autoindex\" }\n=== xerj-api ===\n28:xerj-wasm = { path = \"../xerj-wasm\" }\n=== xerj-engine ===\n18:xerj-wasm = { path = \"../xerj-wasm\" }\n56:# Same grammar versions as `xerj-autoindex`'s ingest-time extractor\n57:# (`xerj-autoindex/src/extract/code.rs`) — this module re-parses at RESPONSE\n=== autoindex bin/lib ===\n//! `xerj autoindex` — point it at ANY folder and it makes the contents\n//! AI-searchable with ZERO configuration. Pure ES-compat HTTP client feature:\n//! it does NOT link xerj-engine, works against any endpoint, and cannot\n//! destabilize the server.\n\npub mod catalog;\npub mod cli;\npub mod coerce;\nmod content;\npub mod correlate;\npub mod dataset;\npub mod def;\npub mod detect;\npub mod esclient;\npub mod estimate;\npub mod extract;\npub mod feedback;\npub mod gain;\npub mod gate;\nmod generation_catalog;\n#[cfg(test)]\nmod generation_catalog_http_tests;\n/// `xerj corpus build` — harvested-record corpus packs (recipe → store →\n/// identity → merge → deterministic pack).\npub mod harvest;\npub mod ids;\npub mod ignore_rules;\npub mod infer;\npub mod init;\n/// `--label`: ingest-time labelling through the node's `/_decide` (#1062).\npub mod label;\npub mod objsource;\n#[cfg(test)]\nmod objsource_minio_tests;\n#[cfg(test)]\nmod objsource_s3_tests;\n/// `--watch` for object storage: poll a bucket, feed a change feed, count the cost.\npub mod objwatch;\npub mod order;\npub mod pool;","is_error":false}]},"uuid":"f8fb3c40-181c-46c8-8236-2882c65af09f","timestamp":"2026-10-01T15:39:41.473Z","sourceToolAssistantUUID":"904cd99c-9632-4eb5-ba0b-aca59b0885ae","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f8fb3c40-181c-46c8-8236-2882c65af09f","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025435d0875332b68d4074","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_0a85b69c1d164a09919d4182","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && wc -l *.rs && echo \"=== risky patterns ===\" && grep -n \"unwrap()\\|expect(\\|panic!\\|\\[0\\]\\|as usize\\|\\.\\.\\|unreachable\" pdf.rs docx.rs mbox.rs eml.rs sqlite_x.rs | grep -viE \"test|#\\[\" | head -60","description":"Survey extractors for risky patterns"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1688,"cache_creation_input_tokens":0,"cache_read_input_tokens":122752,"output_tokens":546,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"06a8befc-934c-4535-924d-7ff02ab668f8","timestamp":"2026-10-01T15:39:43.544Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"06a8befc-934c-4535-924d-7ff02ab668f8","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_0a85b69c1d164a09919d4182","type":"tool_result","content":" 182 bvh.rs\n 3919 code.rs\n 244 csv_x.rs\n 403 docx.rs\n 1082 eml.rs\n 770 html.rs\n 571 json.rs\n 200 jsonl.rs\n 408 logs.rs\n 1685 mbox.rs\n 1004 mod.rs\n 2161 pdf.rs\n 644 sqldump.rs\n 294 sqlite_x.rs\n 292 txt.rs\n 539 unity.rs\n 608 xml_x.rs\n 128 yaml_x.rs\n 15134 total\n=== risky patterns ===\ndocx.rs:167: let mut z = zip::ZipWriter::new(std::fs::File::create(path).unwrap());\ndocx.rs:171: z.start_file(*name, opts).unwrap();\ndocx.rs:172: z.write_all(content.as_bytes()).unwrap();\ndocx.rs:174: z.finish().unwrap();\ndocx.rs:191: sections.push(r.fields[\"body\"].as_str().unwrap().to_string());\ndocx.rs:197: .unwrap();\ndocx.rs:218: let dir = tempfile::tempdir().unwrap();\ndocx.rs:246: (0..PARAS).map(para).collect::<String>()\ndocx.rs:249: let dir = tempfile::tempdir().unwrap();\ndocx.rs:255: let on_disk = std::fs::metadata(&path).unwrap().len();\ndocx.rs:268: let last_whole = (CAP as usize - XML_HEAD.len()) / para(0).len();\ndocx.rs:304: (0..RUNS).map(run).collect::<String>()\ndocx.rs:307: let dir = tempfile::tempdir().unwrap();\ndocx.rs:335: let xml = format!(\"{XML_HEAD}<w:p>{}\", (0..4_000).map(run).collect::<String>());\ndocx.rs:337: let dir = tempfile::tempdir().unwrap();\ndocx.rs:358: let dir = tempfile::tempdir().unwrap();\ndocx.rs:372: .unwrap();\ndocx.rs:376: let fields = &records[0].fields;\ndocx.rs:382: let body = fields[\"body\"].as_str().unwrap();\ndocx.rs:391: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:125: let conn = Connection::open(&path).unwrap();\nsqlite_x.rs:126: conn.execute_batch(sql).unwrap();\nsqlite_x.rs:136: .unwrap();\nsqlite_x.rs:142: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:156: .map(|r| (r.group.clone().unwrap(), r.locator.clone()))\nsqlite_x.rs:165: assert_eq!(recs[0].fields[\"name\"], serde_json::json!(\"Ann\"));\nsqlite_x.rs:167: recs[0].fields.get(\"rowid\").is_none(),\nsqlite_x.rs:174: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:184: assert_eq!(recs[0].fields[\"full_name\"], serde_json::json!(\"Ann Lee\"));\nsqlite_x.rs:185: assert_eq!(recs[0].fields[\"id\"], serde_json::json!(1));\nsqlite_x.rs:186: assert_eq!(recs[0].fields[\"score\"], serde_json::json!(9.5));\nsqlite_x.rs:188: recs[0].fields.get(\"note\").is_none(),\nsqlite_x.rs:192: recs[0].fields.get(\"pic\").is_none(),\nsqlite_x.rs:200: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:213: assert_eq!(recs[0].fields[\"isbn\"], serde_json::json!(\"111\"));\nsqlite_x.rs:218: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:237: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:250: .map(|r| r.group.clone().unwrap())\nsqlite_x.rs:258: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:260: std::fs::write(&path, b\"\").unwrap();\nsqlite_x.rs:272: let dir = tempfile::tempdir().unwrap();\nsqlite_x.rs:278: let bytes = std::fs::read(&good).unwrap();\nsqlite_x.rs:280: std::fs::write(&path, &bytes[..bytes.len() / 2]).unwrap();\neml.rs:96: MessageOutcome::Emitted { .. } => Ok(stats),\neml.rs:510: let head = bytes.get(..end)?;\neml.rs:517: out.extend_from_slice(bytes.get(end..)?);\neml.rs:526: if matches!(bytes, [b'\\n', ..] | [b'\\r', b'\\n', ..]) {\neml.rs:530: while let Some(i) = memchr::memchr(b'\\n', bytes.get(from..).unwrap_or(&[])) {\neml.rs:532: match bytes.get(nl + 1..) {\neml.rs:533: Some([b'\\n', ..]) | Some([b'\\r', b'\\n', ..]) => return nl + 1,\neml.rs:557: let sample = &data[..data.len().min(2048)];\neml.rs:609: .get(usize::try_from(part.offset_body).ok()?..usize::try_from(part.offset_end).ok()?)?;\neml.rs:660: let mut tmp = tempfile::Builder::new().suffix(\".eml\").tempfile().unwrap();\neml.rs:661: tmp.write_all(eml).unwrap();\neml.rs:667: extract(tmp.path(), false, &mut sink).unwrap();\neml.rs:703: let msg = recs.iter().find(|r| r.locator.starts_with(\"msg-\")).unwrap();\neml.rs:713: let subj = field(msg, \"email_subject\").unwrap();\neml.rs:719: let body = field(msg, \"body\").unwrap();\neml.rs:730: .unwrap();\neml.rs:740: let att_body = field(att, \"body\").unwrap();","is_error":false}]},"uuid":"58e462c4-4ce9-4b11-840b-c26e7dbae1b2","timestamp":"2026-10-01T15:39:43.566Z","sourceToolAssistantUUID":"06a8befc-934c-4535-924d-7ff02ab668f8","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"58e462c4-4ce9-4b11-840b-c26e7dbae1b2","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254542627d1b867b3499d","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The extractors appear mostly defensive (using `.get()`). Let me focus more precisely. Given the review target list, let me look at:\n\n1. bulk.rs ingest path — how doc bytes reach pipeline. \n2. The `xerj-api` ingest path (es_compat / native.rs) — documents from HTTP.\n3. Check for any file/network/exec reachable from document content in wasm pipeline — none, confirmed (no std::fs, no Command, no network in builtins.rs/pipeline.rs). Let me verify by grepping.\n\n4. In autoindex: the docx extractor (zip reading), pdf extractor.\n\nLet me grep for process::Command, std::fs, TcpStream, reqwest in xerj-wasm.\n\nAnd check pdf.rs for parsing hazards.","signature":"14089588ce3a4ead8f95a660"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"4cb8ba6d-751b-434e-ac46-6a1fd5c1ffe9","timestamp":"2026-10-01T15:39:56.703Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4cb8ba6d-751b-434e-ac46-6a1fd5c1ffe9","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254542627d1b867b3499d","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_4dd3f7038fb24673af40f987","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-wasm && grep -rn \"std::fs\\|process::Command\\|Command::new\\|TcpStream\\|reqwest\\|open(\\|read_to_string\\|env::\" src/ | head -20; echo \"=== wasm deps ===\"; cat Cargo.toml","description":"Check wasm crate for fs/exec/network access"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2368,"cache_creation_input_tokens":0,"cache_read_input_tokens":124416,"output_tokens":340,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"2a9a8318-cbd4-4601-9b5f-ffb533218f4d","timestamp":"2026-10-01T15:39:59.268Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2a9a8318-cbd4-4601-9b5f-ffb533218f4d","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020254542627d1b867b3499d","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_651aeb72889243239540c27e","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && grep -n \"fn \\|unwrap()\\|expect(\\|panic!\\|slice_index\\|\\[ *[a-z_]* *\\.\\.\\|as usize\" pdf.rs | head -80","description":"Scan pdf.rs functions and risky ops"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2368,"cache_creation_input_tokens":0,"cache_read_input_tokens":124416,"output_tokens":340,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"87b3fb4a-37e2-443d-a4f2-e7cdfcf0315d","timestamp":"2026-10-01T15:39:59.319Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"87b3fb4a-37e2-443d-a4f2-e7cdfcf0315d","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_651aeb72889243239540c27e","type":"tool_result","content":"65:pub(crate) fn corrupt_replay_for_source_size(source_size: u64) {\n71:pub(crate) fn corrupted_replay_reservation_was_dropped() -> bool {\n75:pub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {\n87:pub(crate) fn extract_and_spool(\n114:fn try_spool_response(\n162:fn spool_response(\n204:fn artifact_digest(file: &mut File, bytes: u64) -> Result<u128> {\n213: .read(&mut buffer[..limit])\n216: hash.update(&buffer[..read]);\n271: pub(crate) fn new(limit: u64, max_spools: u64) -> Arc<Self> {\n311: pub(crate) fn for_state_dir(\n321: let inner = Arc::get_mut(&mut budget).expect(\"new budget has one owner\");\n424: fn try_reserve(\n455: let _admission = self.admission.lock().unwrap();\n501: pub(crate) fn report(&self) -> serde_json::Value {\n524: \"fallback_examples\": self.fallback_examples.lock().unwrap().clone(),\n527: \"fallback_categories\": self.fallback_categories.lock().unwrap().clone(),\n538: pub(crate) fn record_io_fallback(&self) {\n542: pub(crate) fn record_reparse(&self) {\n552: pub(crate) fn record_replay_fallback(&self, path: &str, error: &anyhow::Error) {\n564: pub(crate) fn platform_reuse_is_unavailable(&self) -> bool {\n568: pub(crate) fn record_fallback_example(\n575: let mut examples = self.fallback_examples.lock().unwrap();\n585: fn record_fallback_category(&self, category: &'static str) {\n589: .unwrap()\n594: fn record_phase_a_parse(&self) {\n599: fn record_artifact_accepted(&self, bytes: u64) {\n605: fn record_artifact_rejected(&self) {\n609: pub(crate) fn record_phase_b_eligible(&self) {\n614: pub(crate) fn record_discarded_before_replay(&self) {\n619: pub(crate) fn record_source_generation_changed(&self) {\n624:fn available_space_for(state_dir: &Path) -> std::io::Result<u64> {\n632:fn descriptor_snapshot_for(state_dir: &Path) -> (Option<u64>, Option<u64>) {\n647:fn injected_probe_value(state_dir: &Path, name: &str) -> Option<u64> {\n655:fn derive_spool_capacity(\n691:fn descriptor_soft_limit() -> Option<u64> {\n707:fn descriptor_soft_limit() -> Option<u64> {\n712:fn open_descriptor_count() -> Option<u64> {\n721:fn open_descriptor_count() -> Option<u64> {\n733: fn shrink_to(&mut self, bytes: u64) {\n743: fn drop(&mut self) {\n782: pub(crate) fn replay(\n791: fn replay_with_gate(\n869:fn deliver(response: WorkerResponse, sink: Sink) -> ExtractStats {\n889:pub fn configure_workers(workers: usize) {\n893:pub fn configure_timeout(seconds: u64) {\n898:pub fn run_worker_cli() -> i32 {\n936:fn spawn_worker(path: &Path) -> Result<WorkerResponse> {\n957: let stdout = child.stdout.take().expect(\"piped stdout\");\n958: let stderr = child.stderr.take().expect(\"piped stderr\");\n960: let err_reader = std::thread::spawn(move || read_capped(stderr, MAX_WORKER_STDERR as usize));\n1030:fn validate_response_identity(response: &WorkerResponse) -> Result<()> {\n1060:fn read_capped(mut input: impl Read, cap: usize) -> Result<CappedRead> {\n1073: prefix.extend_from_slice(&chunk[..retain]);\n1082:fn set_worker_memory_limit(command: &mut Command) {\n1102:fn set_worker_memory_limit(_command: &mut Command) {}\n1105:fn terminate_worker_tree(child: &mut std::process::Child) {\n1114:fn terminate_worker_descendants(process_group: u32) {\n1121:fn terminate_worker_tree(child: &mut std::process::Child) {\n1127:fn terminate_worker_descendants(_process_group: u32) {}\n1130:fn containment_description() -> &'static str {\n1135:fn containment_description() -> &'static str {\n1139:fn extract_in_process(path: &Path) -> Result<Vec<RawRecord>> {\n1297: fn new(limit: usize) -> Self {\n1304: fn set_limit(&self, limit: usize) {\n1305: self.state.lock().expect(\"PDF worker gate poisoned\").1 = limit;\n1309: fn acquire(&self) -> WorkerPermit<'_> {\n1310: let mut state = self.state.lock().expect(\"PDF worker gate poisoned\");\n1312: state = self.ready.wait(state).expect(\"PDF worker gate poisoned\");\n1322: fn drop(&mut self) {\n1323: let mut state = self.0.state.lock().expect(\"PDF worker gate poisoned\");\n1329:fn worker_gate() -> &'static WorkerGate {\n1338:fn normalize_legacy_symbol_glyphs(text: &str) -> String {\n1350:fn validate_text_quality(text: &str) -> Result<()> {\n1407: fn write_prose_pdf(path: &std::path::Path) {\n1438: std::fs::write(path, pdf).unwrap();\n1442: fn quality_gate_accepts_financial_and_international_text() {\n1446: .unwrap();\n1450: fn quality_gate_rejects_binary_and_font_garbage() {\n1456: fn quality_gate_rejects_operator_noise() {","is_error":false}]},"uuid":"314e25c5-3ee2-42c3-b1fe-5249b4fe4c19","timestamp":"2026-10-01T15:39:59.335Z","sourceToolAssistantUUID":"87b3fb4a-37e2-443d-a4f2-e7cdfcf0315d","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2a9a8318-cbd4-4601-9b5f-ffb533218f4d","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_4dd3f7038fb24673af40f987","type":"tool_result","content":"=== wasm deps ===\n[package]\nname = \"xerj-wasm\"\nversion.workspace = true\nedition.workspace = true\nlicense.workspace = true\nauthors.workspace = true\ndescription = \"WASM pipeline crate for xerj — built-in transform plugins with optional WASM backend\"\n\n[dependencies]\nxerj-common = { path = \"../xerj-common\" }\nserde = { workspace = true }\nserde_json = { workspace = true }\ntracing = { workspace = true }\nthiserror = { workspace = true }\nanyhow = { workspace = true }\nbytes = { workspace = true }\ntokio = { workspace = true }\nchrono = { workspace = true }\nregex = \"1\"\n\n[dev-dependencies]\ntokio = { workspace = true, features = [\"rt-multi-thread\", \"macros\"] }\ntempfile = { workspace = true }","is_error":false}]},"uuid":"b9e9d1af-ebd9-4b82-bc8e-947bf379eefb","timestamp":"2026-10-01T15:39:59.338Z","sourceToolAssistantUUID":"2a9a8318-cbd4-4601-9b5f-ffb533218f4d","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"b9e9d1af-ebd9-4b82-bc8e-947bf379eefb","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020255082cde2a8d7c794788","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Interesting! `pdf.rs` spawns a WORKER PROCESS (`spawn_worker(path: &Path)` with `std::process::Command`), which is a subprocess for PDF extraction with containment. Let me check: `run_worker_cli`, `spawn_worker` — it spawns a child process from a path. Let's look at how the path is derived — if a document could control the path of the binary executed, that'd be critical. Let's read pdf.rs around 75-200 and 880-1140.\n\nAlso there's `injected_probe_value(state_dir, name)` and `corrupt_replay_for_source_size` — test hooks.\n\nLet me read pdf.rs sections.","signature":"cca4bc725c2a42d182a7ed2c"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1813,"cache_creation_input_tokens":0,"cache_read_input_tokens":126784,"output_tokens":227,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"8d3dcf20-b6b6-4d7c-b2fe-ecb3e995f1bb","timestamp":"2026-10-01T15:40:06.756Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"8d3dcf20-b6b6-4d7c-b2fe-ecb3e995f1bb","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020255082cde2a8d7c794788","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_d53640c9396149b4bf4d9bec","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract/pdf.rs","limit":140,"offset":60}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1813,"cache_creation_input_tokens":0,"cache_read_input_tokens":126784,"output_tokens":227,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"ab672a1e-ff8b-4827-ad43-1ac7950797a3","timestamp":"2026-10-01T15:40:06.758Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"ab672a1e-ff8b-4827-ad43-1ac7950797a3","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020255082cde2a8d7c794788","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_04541489edcd48d5b9db7ec7","name":"Read","input":{"file_path":"/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract/pdf.rs","limit":250,"offset":860}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1813,"cache_creation_input_tokens":0,"cache_read_input_tokens":126784,"output_tokens":227,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"da9dedc7-2278-4074-95b8-78aaf78e2783","timestamp":"2026-10-01T15:40:06.763Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"ab672a1e-ff8b-4827-ad43-1ac7950797a3","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_d53640c9396149b4bf4d9bec","type":"tool_result","content":"60\t#[cfg(test)]\n61\tstatic CORRUPTED_REPLAY_RESERVATION_DROPPED: std::sync::atomic::AtomicBool =\n62\t std::sync::atomic::AtomicBool::new(false);\n63\t\n64\t#[cfg(test)]\n65\tpub(crate) fn corrupt_replay_for_source_size(source_size: u64) {\n66\t CORRUPTED_REPLAY_RESERVATION_DROPPED.store(false, Ordering::SeqCst);\n67\t CORRUPT_REPLAY_SOURCE_SIZE.store(source_size, Ordering::SeqCst);\n68\t}\n69\t\n70\t#[cfg(test)]\n71\tpub(crate) fn corrupted_replay_reservation_was_dropped() -> bool {\n72\t CORRUPTED_REPLAY_RESERVATION_DROPPED.load(Ordering::SeqCst)\n73\t}\n74\t\n75\tpub fn extract(path: &Path, sink: Sink) -> Result<ExtractStats> {\n76\t let _permit = worker_gate().acquire();\n77\t let response = spawn_worker(path)?;\n78\t Ok(deliver(response, sink))\n79\t}\n80\t\n81\t/// Run the isolated parser once and retain its bounded protocol response in an\n82\t/// anonymous, run-local file for Phase B.\n83\t///\n84\t/// The spool is deliberately not durable state. A process restart has a frozen\n85\t/// inference plan but no trusted open handle, so it parses the PDF again. This\n86\t/// avoids coupling extraction cache recovery to the publication journal.\n87\tpub(crate) fn extract_and_spool(\n88\t path: &Path,\n89\t state_dir: &Path,\n90\t source_size: u64,\n91\t source_digest: &str,\n92\t budget: &Arc<ExtractionSpoolBudget>,\n93\t sink: Sink,\n94\t) -> Result<(ExtractStats, Option<ExtractionSpool>, Option<SpoolFallback>)> {\n95\t let _permit = worker_gate().acquire();\n96\t let response = spawn_worker(path)?;\n97\t // Counted only once the worker has produced a usable protocol response.\n98\t // An invocation that spawned and then failed, timed out, or was killed is\n99\t // deliberately excluded — hence `..._responses` and not `..._calls` in the\n100\t // report. Total parser *invocations* are not a number this counter can\n101\t // honestly supply.\n102\t budget.record_phase_a_parse();\n103\t let (spool, fallback) =\n104\t try_spool_response(state_dir, source_size, source_digest, budget, &response);\n105\t let stats = deliver(response, sink);\n106\t Ok((stats, spool, fallback))\n107\t}\n108\t\n109\tpub(crate) struct SpoolFallback {\n110\t pub(crate) category: &'static str,\n111\t pub(crate) message: String,\n112\t}\n113\t\n114\tfn try_spool_response(\n115\t state_dir: &Path,\n116\t source_size: u64,\n117\t source_digest: &str,\n118\t budget: &Arc<ExtractionSpoolBudget>,\n119\t response: &WorkerResponse,\n120\t) -> (Option<ExtractionSpool>, Option<SpoolFallback>) {\n121\t let reservation = budget.try_reserve(MAX_WORKER_OUTPUT as u64);\n122\t match reservation {\n123\t Ok(reservation) => {\n124\t match spool_response(state_dir, source_size, source_digest, response, reservation) {\n125\t Ok(spool) => {\n126\t budget.record_artifact_accepted(spool.bytes);\n127\t (Some(spool), None)\n128\t }\n129\t Err(error) => {\n130\t budget.record_io_fallback();\n131\t budget.record_fallback_category(\"artifact_io\");\n132\t budget.record_artifact_rejected();\n133\t (\n134\t None,\n135\t Some(SpoolFallback {\n136\t category: \"artifact_io\",\n137\t message: format!(\n138\t \"could not retain the run-local extraction artifact: {error:#}\"\n139\t ),\n140\t }),\n141\t )\n142\t }\n143\t }\n144\t }\n145\t Err(category) => (\n146\t {\n147\t budget.record_artifact_rejected();\n148\t budget.record_fallback_category(category);\n149\t None\n150\t },\n151\t Some(SpoolFallback {\n152\t category,\n153\t message: format!(\n154\t \"admission refused ({category}); snapshot headroom or the bounded {} MiB/{}-artifact ceiling would be exceeded\",\n155\t budget.limit >> 20, budget.max_spools\n156\t ),\n157\t }),\n158\t ),\n159\t }\n160\t}\n161\t\n162\tfn spool_response(\n163\t state_dir: &Path,\n164\t source_size: u64,\n165\t source_digest: &str,\n166\t response: &WorkerResponse,\n167\t mut reservation: ExtractionSpoolReservation,\n168\t) -> Result<ExtractionSpool> {\n169\t validate_response_identity(response)?;\n170\t let mut file = tempfile::tempfile_in(state_dir).with_context(|| {\n171\t format!(\n172\t \"create anonymous PDF extraction spool under {}\",\n173\t state_dir.display()\n174\t )\n175\t })?;\n176\t {\n177\t let mut writer = BufWriter::new(&mut file);\n178\t serde_json::to_writer(&mut writer, &response)\n179\t .context(\"serialize validated PDF extraction spool\")?;\n180\t writer.flush().context(\"flush PDF extraction spool\")?;\n181\t }\n182\t let bytes = file\n183\t .stream_position()\n184\t .context(\"measure PDF extraction spool\")?;\n185\t if bytes > MAX_WORKER_OUTPUT as u64 {\n186\t return Err(anyhow!(\n187\t \"validated PDF extraction spool exceeded the {} MiB parent-memory safety limit\",\n188\t MAX_WORKER_OUTPUT >> 20\n189\t ));\n190\t }\n191\t let artifact_digest = artifact_digest(&mut file, bytes)?;\n192\t reservation.shrink_to(bytes);\n193\t file.rewind().context(\"rewind PDF extraction spool\")?;\n194\t Ok(ExtractionSpool {\n195\t file: Mutex::new(file),\n196\t source_size,\n197\t source_digest: source_digest.to_owned(),\n198\t bytes,\n199\t artifact_digest,"}]},"uuid":"12ca0741-0111-4ed6-95e0-a76853dbe9bb","timestamp":"2026-10-01T15:40:06.767Z","sourceToolAssistantUUID":"ab672a1e-ff8b-4827-ad43-1ac7950797a3","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"da9dedc7-2278-4074-95b8-78aaf78e2783","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_04541489edcd48d5b9db7ec7","type":"tool_result","content":"860\t budget\n861\t .replay_integrity_failures\n862\t .fetch_add(1, Ordering::Relaxed);\n863\t Err(error)\n864\t }\n865\t }\n866\t }\n867\t}\n868\t\n869\tfn deliver(response: WorkerResponse, sink: Sink) -> ExtractStats {\n870\t let mut stats = ExtractStats::default();\n871\t for record in response.records {\n872\t stats.records += 1;\n873\t if !sink(record) {\n874\t break;\n875\t }\n876\t }\n877\t stats\n878\t}\n879\t\n880\t#[derive(Debug, Serialize, Deserialize)]\n881\tstruct WorkerResponse {\n882\t schema: u32,\n883\t extractor: String,\n884\t parser: String,\n885\t containment: String,\n886\t records: Vec<RawRecord>,\n887\t}\n888\t\n889\tpub fn configure_workers(workers: usize) {\n890\t worker_gate().set_limit(workers.clamp(1, 4));\n891\t}\n892\t\n893\tpub fn configure_timeout(seconds: u64) {\n894\t WORKER_TIMEOUT_SECS.store(seconds.clamp(1, 3600), Ordering::Relaxed);\n895\t}\n896\t\n897\t/// Hidden same-binary worker entry point. One invocation parses one document.\n898\tpub fn run_worker_cli() -> i32 {\n899\t let mut args = std::env::args_os().skip(2);\n900\t let Some(path) = args.next().map(PathBuf::from) else {\n901\t eprintln!(\"PDF worker protocol error: missing input path\");\n902\t return 2;\n903\t };\n904\t if args.next().is_some() {\n905\t eprintln!(\"PDF worker protocol error: unexpected arguments\");\n906\t return 2;\n907\t }\n908\t match extract_in_process(&path) {\n909\t Ok(records) => {\n910\t let response = WorkerResponse {\n911\t schema: 1,\n912\t extractor: format!(\"xerj-autoindex/{}\", env!(\"CARGO_PKG_VERSION\")),\n913\t parser: format!(\"pdf_oxide/{}\", pdf_oxide::VERSION),\n914\t containment: containment_description().to_string(),\n915\t records,\n916\t };\n917\t let result = (|| -> Result<()> {\n918\t let mut stdout = std::io::stdout().lock();\n919\t serde_json::to_writer(&mut stdout, &response)?;\n920\t stdout.flush()?;\n921\t Ok(())\n922\t })();\n923\t if let Err(error) = result {\n924\t eprintln!(\"PDF worker could not write its bounded result: {error}\");\n925\t return 1;\n926\t }\n927\t 0\n928\t }\n929\t Err(error) => {\n930\t eprintln!(\"{error:#}\");\n931\t 1\n932\t }\n933\t }\n934\t}\n935\t\n936\tfn spawn_worker(path: &Path) -> Result<WorkerResponse> {\n937\t // Trusted developer/test hook. The selected executable runs with the\n938\t // invoking user's authority and must implement this private protocol.\n939\t let executable = std::env::var_os(\"XERJ_PDF_WORKER_BIN\")\n940\t .map(PathBuf::from)\n941\t .or_else(|| std::env::current_exe().ok())\n942\t .context(\"cannot locate the xerj executable for isolated PDF extraction\")?;\n943\t let mut command = Command::new(executable);\n944\t command\n945\t .arg(\"__extract-pdf\")\n946\t .arg(path)\n947\t .stdin(Stdio::null())\n948\t .stdout(Stdio::piped())\n949\t .stderr(Stdio::piped());\n950\t set_worker_memory_limit(&mut command);\n951\t let mut child = command.spawn().with_context(|| {\n952\t format!(\n953\t \"could not start the isolated PDF parser for {}; check process/resource limits\",\n954\t path.display()\n955\t )\n956\t })?;\n957\t let stdout = child.stdout.take().expect(\"piped stdout\");\n958\t let stderr = child.stderr.take().expect(\"piped stderr\");\n959\t let out_reader = std::thread::spawn(move || read_capped(stdout, MAX_WORKER_OUTPUT));\n960\t let err_reader = std::thread::spawn(move || read_capped(stderr, MAX_WORKER_STDERR as usize));\n961\t\n962\t let started = Instant::now();\n963\t let timeout = Duration::from_secs(WORKER_TIMEOUT_SECS.load(Ordering::Relaxed));\n964\t let status = loop {\n965\t match child.try_wait() {\n966\t Ok(Some(status)) => break status,\n967\t Ok(None) => {}\n968\t Err(error) => {\n969\t terminate_worker_tree(&mut child);\n970\t let _ = out_reader.join();\n971\t let _ = err_reader.join();\n972\t return Err(error).with_context(|| {\n973\t format!(\"could not monitor PDF parser for {}\", path.display())\n974\t });\n975\t }\n976\t }\n977\t if started.elapsed() >= timeout {\n978\t terminate_worker_tree(&mut child);\n979\t let _ = out_reader.join();\n980\t let _ = err_reader.join();\n981\t return Err(anyhow!(\n982\t \"PDF extraction timed out after {} seconds for {}; repair/split the PDF, or run OCR if it is image-only\",\n983\t timeout.as_secs(),\n984\t path.display()\n985\t ));\n986\t }\n987\t std::thread::sleep(Duration::from_millis(20));\n988\t };\n989\t terminate_worker_descendants(child.id());\n990\t let stdout = out_reader\n991\t .join()\n992\t .map_err(|_| anyhow!(\"PDF parser output reader panicked\"))??;\n993\t let stderr = err_reader\n994\t .join()\n995\t .map_err(|_| anyhow!(\"PDF parser error reader panicked\"))??;\n996\t if stdout.overflow {\n997\t return Err(anyhow!(\n998\t \"PDF parser output exceeded the {} MiB parent-memory safety limit for {}; split the document before indexing\",\n999\t MAX_WORKER_OUTPUT >> 20,\n1000\t path.display()\n1001\t ));\n1002\t }\n1003\t if stderr.overflow {\n1004\t return Err(anyhow!(\n1005\t \"PDF parser error output exceeded the {} KiB safety limit for {}; the worker was excessively noisy and its truncated diagnostic is: {}\",\n1006\t MAX_WORKER_STDERR >> 10,\n1007\t path.display(),\n1008\t String::from_utf8_lossy(&stderr.prefix)\n1009\t ));\n1010\t }\n1011\t let stderr = String::from_utf8_lossy(&stderr.prefix);\n1012\t if !status.success() {\n1013\t return Err(anyhow!(\n1014\t \"isolated PDF parser failed for {}{}{}; verify/decrypt the PDF, repair it, or run OCR for image-only input\",\n1015\t path.display(),\n1016\t if stderr.trim().is_empty() { \"\" } else { \": \" },\n1017\t stderr.trim()\n1018\t ));\n1019\t }\n1020\t let response: WorkerResponse = serde_json::from_slice(&stdout.prefix).with_context(|| {\n1021\t format!(\n1022\t \"isolated PDF parser returned an invalid result for {}; this is an internal worker-protocol error\",\n1023\t path.display()\n1024\t )\n1025\t })?;\n1026\t validate_response_identity(&response)?;\n1027\t Ok(response)\n1028\t}\n1029\t\n1030\tfn validate_response_identity(response: &WorkerResponse) -> Result<()> {\n1031\t if response.schema != 1 {\n1032\t return Err(anyhow!(\n1033\t \"PDF parser returned unsupported extraction schema {}; update parent and worker together\",\n1034\t response.schema\n1035\t ));\n1036\t }\n1037\t let expected_extractor = format!(\"xerj-autoindex/{}\", env!(\"CARGO_PKG_VERSION\"));\n1038\t if response.extractor != expected_extractor {\n1039\t return Err(anyhow!(\n1040\t \"PDF extractor version mismatch: expected {expected_extractor}, worker reported {}; update parent and worker together\",\n1041\t response.extractor\n1042\t ));\n1043\t }\n1044\t if response.parser != format!(\"pdf_oxide/{}\", pdf_oxide::VERSION) {\n1045\t return Err(anyhow!(\n1046\t \"PDF parser version mismatch: expected pdf_oxide/{}, worker reported {}; update parent and worker together\",\n1047\t pdf_oxide::VERSION, response.parser\n1048\t ));\n1049\t }\n1050\t Ok(())\n1051\t}\n1052\t\n1053\tstatic WORKER_TIMEOUT_SECS: AtomicU64 = AtomicU64::new(120);\n1054\t\n1055\tstruct CappedRead {\n1056\t prefix: Vec<u8>,\n1057\t overflow: bool,\n1058\t}\n1059\t\n1060\tfn read_capped(mut input: impl Read, cap: usize) -> Result<CappedRead> {\n1061\t let mut prefix = Vec::with_capacity(cap.min(64 << 10));\n1062\t let mut overflow = false;\n1063\t let mut chunk = [0u8; 64 << 10];\n1064\t loop {\n1065\t let read = input\n1066\t .read(&mut chunk)\n1067\t .context(\"could not read isolated PDF parser output\")?;\n1068\t if read == 0 {\n1069\t break;\n1070\t }\n1071\t let remaining = cap.saturating_sub(prefix.len());\n1072\t let retain = remaining.min(read);\n1073\t prefix.extend_from_slice(&chunk[..retain]);\n1074\t overflow |= retain < read;\n1075\t // Keep draining after overflow so the child can exit instead of\n1076\t // blocking forever on a full pipe.\n1077\t }\n1078\t Ok(CappedRead { prefix, overflow })\n1079\t}\n1080\t\n1081\t#[cfg(unix)]\n1082\tfn set_worker_memory_limit(command: &mut Command) {\n1083\t use std::os::unix::process::CommandExt;\n1084\t unsafe {\n1085\t command.pre_exec(|| {\n1086\t if libc::setpgid(0, 0) != 0 {\n1087\t return Err(std::io::Error::last_os_error());\n1088\t }\n1089\t let limit = libc::rlimit {\n1090\t rlim_cur: WORKER_ADDRESS_SPACE,\n1091\t rlim_max: WORKER_ADDRESS_SPACE,\n1092\t };\n1093\t if libc::setrlimit(libc::RLIMIT_AS, &limit) != 0 {\n1094\t return Err(std::io::Error::last_os_error());\n1095\t }\n1096\t Ok(())\n1097\t });\n1098\t }\n1099\t}\n1100\t\n1101\t#[cfg(not(unix))]\n1102\tfn set_worker_memory_limit(_command: &mut Command) {}\n1103\t\n1104\t#[cfg(unix)]\n1105\tfn terminate_worker_tree(child: &mut std::process::Child) {\n1106\t unsafe {\n1107\t libc::kill(-(child.id() as i32), libc::SIGKILL);\n1108\t }\n1109\t let _ = child.kill();"}]},"uuid":"c720b234-7ff8-467a-89f2-cfed0536cc03","timestamp":"2026-10-01T15:40:06.768Z","sourceToolAssistantUUID":"da9dedc7-2278-4074-95b8-78aaf78e2783","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c720b234-7ff8-467a-89f2-cfed0536cc03","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025515122d401d58d64560","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The PDF extraction spawns a subprocess `XERJ_PDF_WORKER_BIN` env var — that's an env-var-controlled executable, but it's a \"trusted developer/test hook\" — env var is set by the operator, not the document. Not a doc-controlled path (unless an attacker controls env, which is game over anyway).\n\nNow let me look at the ingest path in the engine bulk.rs, which is where document bytes flow into the pipeline. And check whether the panic-relevant code (e.g., `doc[field] = ...` indexing on a non-object Value) can panic.\n\nImportant: In serde_json, `doc[&self.field] = value` on a Value that is NOT an object — `IndexMut` for `&str` on a non-object Value PANICS: \"cannot access key ... in JSON ...\". Let's verify: serde_json's `impl Index<&str> for Value` — `index_or_insert`: if the value is Null, it becomes an object; if it's an Object, insert; otherwise PANIC with \"cannot access key in JSON ...\". \n\nSo: `AddFieldPlugin::process` does `doc[&self.field] = self.value.clone();` — if `doc` is not an object (e.g., the ingest document is a JSON scalar or array), this panics!\n\nNow, can a document at ingest be a non-object? In bulk indexing, documents are usually JSON objects. But what about `json_parse` merging? `JsonParsePlugin` merges parsed_obj into root only if root is object. Hmm.\n\nLet me check the bulk path: does it enforce that the doc is an object before running the pipeline? Let's look at bulk.rs around 1700-1850.\n\nAlso `SplitPlugin`, `ConvertTypePlugin`, `CopyFieldPlugin`, `LowercasePlugin` all use `doc[field] = ...`.\n\nAlso within `JsonParsePlugin`, `doc[&self.target] = parsed;`.\n\nSo the question is: can the top-level document be an array/scalar? In Elasticsearch, `_bulk` requires action metadata + source; source can be any JSON value in theory but ES rejects non-objects. Let's check xerj's bulk parser.\n\nLet me look at bulk.rs around line 1700-1850 and see the doc handling.\n\nAnother important area: `RemoveNullPlugin` uses as_object_mut, fine.\n\nLet me check the bulk ingest path.","signature":"6e5ce40386344aa6ab2b26a2"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"6d0680a2-0e93-4647-bf93-656f3488144d","timestamp":"2026-10-01T15:40:27.294Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6d0680a2-0e93-4647-bf93-656f3488144d","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025515122d401d58d64560","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_f1f62124c5b644f0a69a895f","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '1700,1850p' bulk.rs","description":"Read bulk.rs pipeline invocation"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"fdbb6a84-1df4-4440-bb13-e2aa5b5e2fe6","timestamp":"2026-10-01T15:40:27.296Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"fdbb6a84-1df4-4440-bb13-e2aa5b5e2fe6","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_f1f62124c5b644f0a69a895f","type":"tool_result","content":" items[item_idx] = Some(BulkItemResult {\n action: \"index\".into(),\n index: index_name.clone(),\n id: resp.id,\n status,\n result: Some(resp.result),\n error: None,\n get_source: None,\n });\n }\n Err(e) => {\n let status = engine_error_http_status(&e);\n items[item_idx] = Some(BulkItemResult {\n action: \"index\".into(),\n index: index_name.clone(),\n id: String::new(),\n status,\n result: None,\n error: Some(e.to_string()),\n get_source: None,\n });\n errors = true;\n }\n }\n }\n }\n\n // Execute non-index ops individually (create, update, delete).\n // `create` / `update` / `delete` — executed individually. `parsed` here\n // has already been filtered to non-`index` actions by the turbo-batch\n // partition above, so the match arms no longer need an `\"index\" => {}`\n // no-op branch. We consume `parsed` by value to avoid per-action\n // deep-clones of `doc_id` (String) and `doc_body` (Value tree).\n for action in parsed {\n let ParsedAction {\n action_type,\n target_index,\n doc_id,\n doc_body,\n doc_bytes,\n item_index: item_idx,\n require_alias: _,\n pipeline,\n if_seq_no,\n if_primary_term,\n routing,\n source_req,\n dynamic_templates,\n } = action;\n let error_id = doc_id.clone().unwrap_or_default();\n let target_index_for_get = target_index.clone();\n let doc_id_for_get = doc_id.clone();\n // Ensure we have the doc body parsed before validating — our\n // dynamic-templates check needs `doc_body.contains_key(field)`\n // to tell \"spec applies to this doc\" from \"spec references a\n // field not even present\". The turbo-index partition skipped\n // parsing; do it here if needed.\n let mut doc_body = doc_body.or_else(|| {\n if action_type == \"index\" && !doc_bytes.is_empty() {\n // doc_bytes is Arc<[u8]> — mutating it would invalidate\n // sibling clones, so simd_json (which mutates in-place)\n // forced a per-doc to_vec(). serde_json takes &[u8]\n // immutably and avoids the allocation entirely.\n serde_json::from_slice::<Value>(&doc_bytes).ok()\n } else {\n None\n }\n });\n // ── Ingest pipeline execution ───────────────────────────────────\n //\n // ES runs the item's ingest pipeline BEFORE field mapping,\n // `copy_to`, and date / dynamic-template validation, so we apply\n // it here — right after the doc body is parsed. Only `index` /\n // `create` carry a source body through a pipeline (`update` /\n // `delete` never do). Unknown pipeline names were already rejected\n // as per-item 400s in the pre-partition validation pass above, so a\n // lookup miss here is defensive only — mirror the same error.\n if let Some(pid) = pipeline.as_deref() {\n if matches!(action_type.as_str(), \"index\" | \"create\") {\n let input = doc_body\n .clone()\n .unwrap_or_else(|| Value::Object(serde_json::Map::new()));\n match engine.process_through_pipeline(pid, vec![input]) {\n Ok(mut results) if !results.is_empty() => {\n let (p_action, transformed) = results.remove(0);\n if matches!(p_action, xerj_wasm::pipeline::ProcessAction::Drop) {\n // Pipeline dropped the doc: ES reports a\n // successful no-op and does not index it.\n items[item_idx] = Some(BulkItemResult {\n action: action_type.to_string(),\n index: target_index.clone(),\n id: error_id.clone(),\n status: 200,\n result: Some(\"noop\".into()),\n error: None,\n get_source: None,\n });\n continue;\n }\n doc_body = Some(transformed);\n }\n // No output for this document. `process_through_pipeline`\n // zips one action per input, so this is an internal\n // invariant break — but it must not fall through to\n // indexing the ORIGINAL body, which is the silent\n // pass-through issue #204 is about. Fail the item.\n Ok(_) => {\n items[item_idx] = Some(BulkItemResult {\n action: action_type.to_string(),\n index: target_index.clone(),\n id: error_id.clone(),\n status: 400,\n result: None,\n error: Some(format!(\"pipeline with id [{pid}] returned no document\")),\n get_source: None,\n });\n errors = true;\n continue;\n }\n Err(e) => {\n // A genuinely absent pipeline keeps ES's exact wording\n // (the conformance suite asserts it). A pipeline that\n // IS registered but carries a processor this build\n // cannot run reports that instead — issue #204: telling\n // an operator a pipeline \"does not exist\" when\n // `GET /_ingest/pipeline` plainly returns it sends them\n // hunting for the wrong problem.\n let reason = match &e {\n xerj_wasm::WasmError::PipelineNotRunnable { .. } => e.to_string(),\n _ => format!(\"pipeline with id [{pid}] does not exist\"),\n };\n items[item_idx] = Some(BulkItemResult {\n action: action_type.to_string(),\n index: target_index.clone(),\n id: error_id.clone(),\n status: 400,\n result: None,\n error: Some(reason),\n get_source: None,\n });\n errors = true;\n continue;\n }\n }\n }\n }\n // Apply dynamic-template `copy_to` at ingest. When a doc\n // field name matches a dynamic template's `match` pattern\n // (or equals the template name) and the template's mapping\n // carries `copy_to`, ES silently copies the value into the\n // target field. Our search-time `apply_copy_to` only walks","is_error":false}]},"uuid":"a9c4d3b1-9192-4b70-986b-c0cffa56c183","timestamp":"2026-10-01T15:40:27.317Z","sourceToolAssistantUUID":"fdbb6a84-1df4-4440-bb13-e2aa5b5e2fe6","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a9c4d3b1-9192-4b70-986b-c0cffa56c183","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025515122d401d58d64560","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_d91760a66e584762bdef4063","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && grep -n \"as_object\\|is_object\\|Value::Object\\|must be an object\\|document must\" bulk.rs | head -40","description":"Check object validation in bulk"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":4064,"cache_creation_input_tokens":0,"cache_read_input_tokens":128576,"output_tokens":627,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"df27d166-1418-4a81-8366-062ee7bfc785","timestamp":"2026-10-01T15:40:28.144Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"df27d166-1418-4a81-8366-062ee7bfc785","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_d91760a66e584762bdef4063","type":"tool_result","content":"718: .and_then(Value::as_object)\n827: let is_object = dl\n833: if !is_object {\n1164: v.as_object()\n1264: Some(Value::Object(o)) => Some(o),\n1270: Ok(Value::Object(o)) => Some(o),\n1285: action.doc_body = Some(Value::Object(body));\n1781: .unwrap_or_else(|| Value::Object(serde_json::Map::new()));\n1857: if let Some(body) = doc_body.as_mut().and_then(|v| v.as_object_mut()) {\n1889: v.as_object().and_then(|o| {\n1908: .and_then(Value::as_object)\n1931: db.as_object()\n1960: if let Some(body) = doc_body.as_ref().and_then(Value::as_object) {\n1974: v.as_object().and_then(|o| {\n2085: if let Some(body) = doc_body.as_ref().and_then(Value::as_object) {\n2128: if let Some(body) = doc_body.as_mut().and_then(Value::as_object_mut) {\n2267: let obj = match src.as_object() {\n2272: Value::Bool(true) => return Value::Object(obj),\n2281: Value::Object(o) => {\n2294: _ => return Value::Object(obj),\n2304: Value::Object(out)\n2344: .and_then(Value::as_object)\n2352: let (name, body) = v.as_object().and_then(|o| o.iter().next())?;\n2425: if let Some(Value::Object(existing)) = body.get(\"__xy_copy_to_pristine__\").cloned() {\n2432: Value::Object(pristine),\n2444: cur = cur.as_object()?.get(*seg)?;\n2477: .or_insert_with(|| Value::Object(serde_json::Map::new()));\n2478: if !entry.is_object() {\n2482: *entry = Value::Object(m);\n2484: cur = entry.as_object_mut().unwrap();\n2493: let Some(obj) = props.as_object() else {\n2525: let Some(obj) = props.as_object() else {\n2552: let props_obj = props.as_object()?;\n2649: let mut v = body.unwrap_or(Value::Object(serde_json::Map::new()));\n2650: if let Some(obj) = v.as_object_mut() {\n2665: let source = inject_routing(body).unwrap_or(Value::Object(serde_json::Map::new()));\n2676: let source = inject_routing(body).unwrap_or(Value::Object(serde_json::Map::new()));\n2689: let body_val = body.unwrap_or(Value::Object(serde_json::Map::new()));","is_error":false}]},"uuid":"95fe5212-f066-461e-9fd9-19044c84addd","timestamp":"2026-10-01T15:40:28.160Z","sourceToolAssistantUUID":"df27d166-1418-4a81-8366-062ee7bfc785","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"95fe5212-f066-461e-9fd9-19044c84addd","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025535fe60e7e101f14f3b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Interesting — at bulk.rs:1770-1783, `doc_body` is `Option<Value>` from parsing the raw doc bytes. If the client sends a `_bulk` action whose source body is `[1,2,3]` or `\"string\"` or `5`, `doc_body` would be `Some(Value::Array(...))`. Then at line 1775: `let input = doc_body.clone().unwrap_or_else(|| Value::Object(...))` — the input to the pipeline is the array/scalar as-is! There's no check that it's an object before going into `process_through_pipeline`.\n\nThen `Pipeline::process` → `AddFieldPlugin::process` → `doc[&self.field] = self.value.clone();` on a `Value::Array` → PANIC.\n\nWait — does serde_json's IndexMut panic for arrays? Yes:\n```rust\nfn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value {\n if let Value::Null = v {\n *v = Value::Object(Map::new());\n }\n match v {\n Value::Object(map) => map.entry(self.to_owned()).or_insert(Value::Null),\n _ => panic!(\"cannot access key {:?} in JSON {}\", self, Type(v)),\n }\n}\n```\nYes, panics.\n\nBut wait — is a non-object body even accepted earlier in the bulk parse? Let me check line ~2267 `fn ... (src)` — \"let obj = match src.as_object() { ... _ => return Value::Object(obj) }\" — that's `inject_routing` maybe which normalizes to object. Hmm.\n\nLet me check the bulk parsing path (parse of actions) for validation that the source body is an object. Let's look around lines 700-900 and 1250-1300.\n\nAlso ES itself: for `_bulk` with `{\"index\":{...}}` followed by `[1,2,3]`, ES returns an error \"Malformed action, expected a JSON object\" — actually ES does reject non-object sources with a 400. If xerj accepts them, we get to the panic.\n\nAlso important: where else is the panic relevant? `xerj-api/src/es_compat.rs` also runs pipelines on docs (lines 2813, 2950, 3084, 23867, 27785). Those are the HTTP ingest paths (`_bulk`, `_ingest/pipeline/_simulate`, `index` API). Let's check whether those validate the doc is an object.\n\nAlso very important: does a panic kill the process? The task says \"a panic in Rust = crash of handler thread; only matters if it kills the process\". In an axum/hyper server, a panic in a handler is caught by tokio's task boundary → the connection drops but the process survives. However, if the panic occurs inside a `spawn_blocking` or a tokio task, the process survives. So a panic is a DoS of one request. Unless panic=abort is configured. Let me check Cargo.toml for panic settings.\n\nLet me check:\n1. Whether non-object bodies are accepted in bulk parse.\n2. panic profile setting.\n3. es_compat paths.\n\nLet me do these greps.","signature":"6f0fcc6f8faa4eb7ba9907bb"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"ed4f457f-bfce-48ce-a759-33da0cc8812f","timestamp":"2026-10-01T15:40:53.557Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"ed4f457f-bfce-48ce-a759-33da0cc8812f","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025535fe60e7e101f14f3b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_4ed8e69a88b54e67ac1094a0","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine && grep -rn \"panic\" Cargo.toml*/ Makefile* 2>/dev/null | head; echo \"=== profile ===\"; grep -n -A5 \"\\[profile\" Cargo.toml | head -40","description":"Check panic build profile"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"4fccddf8-b2ac-46af-ad91-a1266ab27d51","timestamp":"2026-10-01T15:40:55.706Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"4fccddf8-b2ac-46af-ad91-a1266ab27d51","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_4ed8e69a88b54e67ac1094a0","type":"tool_result","content":"=== profile ===\n160:[profile.release]\n161-opt-level = 3\n162-lto = \"fat\"\n163-codegen-units = 1\n164-strip = true\n165-panic = \"abort\"\n--\n167:# CI test profile. Identical *code semantics* to [profile.release] --\n168-# opt-level 3, debug-assertions off, overflow-checks off -- so tests still\n169-# exercise optimized codegen. Only the optimization *scope* changes: no\n170-# whole-program LTO and 16 codegen units instead of 1.\n171-#\n172-# Why it exists: `cargo test --release` links every one of the ~99 test\n--\n180:# [profile.release] above is deliberately untouched: release.yml builds the\n181-# shipped binary with `cargo build --release`, and it must stay fat-LTO.\n182:[profile.ci-test]\n183-inherits = \"release\"\n184-lto = false\n185-codegen-units = 16\n186-panic = \"unwind\"\n187-strip = false\n--\n192:# loop. Its sibling is [profile.ci-test] above, which serves the TEST half.\n193-#\n194-# The division is deliberate and the two are not redundant:\n195-# quick — `cargo build`. Inherits panic = \"abort\" from release, matching the\n196-# shipped binary, so the artifact you smoke-test behaves like the real\n197-# one (panic strategy is observable).\n--\n207:# WHY: [profile.release] below is a SHIPPING configuration — `lto = \"fat\"` plus\n208-# `codegen-units = 1` is the slowest build Rust can produce, deliberately, because\n209-# it yields the fastest binary. Fat LTO is a whole-program optimisation that runs\n210-# largely single-threaded at link time, and codegen-units = 1 removes intra-crate\n211-# parallelism, so a 32-core machine ends up watching one core. That is the right\n212-# trade for an artifact users download and run for months. It is the wrong trade\n--\n231:[profile.quick]\n232-inherits = \"release\"\n233-lto = false # the single biggest lever: no whole-program link-time pass","is_error":false}]},"uuid":"d04bf439-db46-4574-bb24-f10164b73f9d","timestamp":"2026-10-01T15:40:55.731Z","sourceToolAssistantUUID":"4fccddf8-b2ac-46af-ad91-a1266ab27d51","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d04bf439-db46-4574-bb24-f10164b73f9d","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025535fe60e7e101f14f3b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_c5a1f2ef0fa74a2ab407654e","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '1240,1300p' bulk.rs","description":"Read bulk action body parse"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2629,"cache_creation_input_tokens":0,"cache_read_input_tokens":132608,"output_tokens":814,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"bed50814-fdf3-4ce9-8dc8-185319dcdf10","timestamp":"2026-10-01T15:40:55.843Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"bed50814-fdf3-4ce9-8dc8-185319dcdf10","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_c5a1f2ef0fa74a2ab407654e","type":"tool_result","content":" };\n\n for mut action in parsed {\n // ── Numeric / boolean type enforcement (issue #781) ──────────────\n //\n // A field mapped `integer` used to keep whatever arrived — `1.9`,\n // `9999999999`, `\"abc\"`, even an object — so `range {gte: 1.5}`\n // matched a doc that ES stores as `1` and `term {i: 1}` missed it.\n // Values ES coerces are coerced here (`1.9` → `1`, `\"5\"` → `5`,\n // `\"true\"` → `true`); values ES refuses become a per-item 400\n // `document_parsing_exception`, like the date-format check below.\n //\n // Runs at partition time so it covers the turbo batch path as well\n // as the per-item loop. Actions carrying a pipeline are skipped: ES\n // runs the pipeline before parsing the document, so those are\n // checked after their pipeline in the per-item loop instead.\n // `update` merges into a doc that was already validated on write.\n if matches!(action.action_type.as_str(), \"index\" | \"create\") && action.pipeline.is_none() {\n let props = typed_numeric_props(&action.target_index, &mut index_type_check_props);\n if let Some(props) = props {\n // `index` actions defer the JSON parse to the turbo path, so\n // the body may not be built yet — parse it here, and only\n // pay the re-serialize when a value actually changed.\n let parsed_body = match action.doc_body.take() {\n Some(Value::Object(o)) => Some(o),\n Some(other) => {\n action.doc_body = Some(other);\n None\n }\n None => match serde_json::from_slice::<Value>(&action.doc_bytes) {\n Ok(Value::Object(o)) => Some(o),\n _ => None,\n },\n };\n if let Some(mut body) = parsed_body {\n match xerj_common::field_coercion::coerce_document(&mut body, &props) {\n Ok(changed) => {\n // Serialize from the map itself, not a clone of\n // it — `preserve_order` is on workspace-wide, so\n // the caller's `_source` key order survives.\n if changed {\n if let Ok(bytes) = serde_json::to_vec(&body) {\n action.doc_bytes = std::sync::Arc::from(bytes.as_slice());\n }\n }\n action.doc_body = Some(Value::Object(body));\n }\n Err(bad) => {\n items[action.item_index] = Some(BulkItemResult {\n action: action.action_type.clone(),\n index: action.target_index.clone(),\n id: action.doc_id.clone().unwrap_or_default(),\n status: 400,\n result: None,\n error: Some(bad.reason(&action.doc_id.clone().unwrap_or_default())),\n get_source: None,\n });\n errors = true;\n continue;\n }\n }","is_error":false}]},"uuid":"d1d00297-e793-481b-91b5-218ef1832af0","timestamp":"2026-10-01T15:40:55.858Z","sourceToolAssistantUUID":"bed50814-fdf3-4ce9-8dc8-185319dcdf10","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d1d00297-e793-481b-91b5-218ef1832af0","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202560091fda1f92c174ae3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"CONFIRMED: `panic = \"abort\"` in the release profile. So ANY panic in the shipped binary kills the whole process. That elevates every reachable panic to a remote DoS / full crash.\n\nNow: is the pipeline `process` called from a context where a panic aborts? Yes — panic=abort means the process dies on any panic regardless of thread.\n\nSo now the key question: can a document be a non-object Value at the pipeline input?\n\nAt bulk.rs:1775, `input = doc_body.clone().unwrap_or_else(|| Value::Object(...))`. `doc_body` comes from `ParsedAction`. Where is doc_body set? Let's find the parse of the bulk action source. Let's look at where ParsedAction is built and whether the body is validated as an object. Line 718 `and_then(Value::as_object)` and 827 `is_object`.\n\nLet me look at bulk.rs lines 690-900 and 2260-2320.\n\nAlso the turbo path: line 1264-1285 shows `Some(Value::Object(o))` and `serde_json::from_slice::<Value>(&action.doc_bytes)` matching only `Ok(Value::Object(o))` → otherwise None → skip coercion (not rejected). So non-object bodies are NOT rejected there; they're passed along.\n\nThen for actions WITH a pipeline, coercion is skipped (\"Actions carrying a pipeline are skipped\"), so the doc goes straight to pipeline execution at 1775 with whatever value.\n\nSo: `POST /_bulk` with line `{\"index\":{\"_index\":\"i\",\"pipeline\":\"p\"}}` and body `[1,2,3]` → pipeline input is `Value::Array`. If pipeline has `add_field`/`set`/`append`/`copy_field`/`convert`/`split`/`json_parse`(target)/`lowercase`... wait lowercase uses get_mut, no panic. Let's list panicking plugins:\n- AddFieldPlugin: `doc[&self.field] = ...` → panic on Array/other.\n- SetPlugin: `doc[&self.field] = ...` → panic.\n- AppendPlugin: uses `doc.as_object_mut()` else return Pass. Safe.\n- CopyFieldPlugin: `doc[&self.target] = val;` → panic.\n- ConvertTypePlugin: `doc[&self.field] = v;` → panic (only when conversion succeeded).\n- SplitPlugin: `doc[&self.field] = Value::Array(parts);` → panic.\n- JsonParsePlugin: `doc[&self.target] = parsed;` when target non-empty → panic; the merge branch is safe. Also `obj.remove` guarded.\n- TimestampParsePlugin: `doc[self.target_field()] = ...` → panic.\n- RemoveNullPlugin: safe.\n- FieldRename/DropField: safe.\n\nBut hold on: is the pipeline applied per-item only when `pipeline` is specified on the action? Yes at bulk.rs:1772. And the default index pipeline? There might be an index-level default pipeline. Let's check: engine has `index_settings.default_pipeline`? In ES, an index can set `index.default_pipeline`. Let me grep for default_pipeline in the engine — that would make the attack not require specifying the pipeline per action.\n\nAlso, is a non-object body even accepted by the earlier validation pass (\"pre-partition validation pass\")? Let's check lines ~700-860.\n\nLet me look at those.","signature":"7245106e1bc64ab8bf09c9e6"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"2e42f9e2-17f3-4f2b-8b1d-0de5cbfaa660","timestamp":"2026-10-01T15:41:23.722Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2e42f9e2-17f3-4f2b-8b1d-0de5cbfaa660","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202560091fda1f92c174ae3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_83362d93716241f88c22f465","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '690,860p' bulk.rs","description":"Read bulk pre-validation pass"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"76b82cb8-97d5-4612-94f8-e5ae5890388e","timestamp":"2026-10-01T15:41:23.723Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"76b82cb8-97d5-4612-94f8-e5ae5890388e","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_83362d93716241f88c22f465","type":"tool_result","content":" let op_type_str = meta.get(\"op_type\").and_then(Value::as_str);\n let final_a: &'static str = if a == \"index\" && op_type_str == Some(\"create\") {\n \"create\"\n } else {\n a\n };\n require_alias_per_item = meta.get(\"require_alias\").and_then(Value::as_bool);\n pipeline_per_item = meta\n .get(\"pipeline\")\n .and_then(Value::as_str)\n .map(str::to_owned);\n // Wire → internal seq translation: ES numbers seq_no\n // from 0 on the wire, the internal WAL counter from 1.\n // The CAS compare (index_document_with_version) runs on\n // internal seqs, so a `_seq_no` captured from any read\n // or write response round-trips through bulk CAS.\n if_seq_no_per_item = meta\n .get(\"if_seq_no\")\n .and_then(Value::as_u64)\n .map(|s| s.saturating_add(1));\n if_primary_term_per_item = meta.get(\"if_primary_term\").and_then(Value::as_u64);\n routing_per_item = meta\n .get(\"routing\")\n .and_then(Value::as_str)\n .map(str::to_owned);\n source_req_per_item = meta.get(\"_source\").cloned();\n dynamic_templates_per_item = meta\n .get(\"dynamic_templates\")\n .and_then(Value::as_object)\n .map(|o| {\n o.iter()\n .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))\n .collect()\n });\n // ES bulk accepts `_id` as either a string or a number;\n // numeric ids are stringified at the coordinating node.\n let id_from_meta = meta.get(\"_id\").and_then(|v| match v {\n Value::String(s) => Some(s.clone()),\n Value::Number(n) => Some(n.to_string()),\n Value::Bool(b) => Some(b.to_string()),\n _ => None,\n });\n (\n final_a,\n meta.get(\"_index\")\n .and_then(Value::as_str)\n .map(str::to_owned),\n id_from_meta,\n )\n };\n\n let target_index = target_index\n .or_else(|| default_index.map(str::to_owned))\n .unwrap_or_else(|| \"_unknown\".to_string());\n\n // ES rejects an explicit empty `_id` with an\n // illegal_argument_exception per-item error. `_id` missing\n // entirely still auto-generates; only the present-but-empty\n // case is wrong.\n if let Some(s) = doc_id.as_deref() {\n if s.is_empty() {\n return ParseOutcome::Err(\n BulkItemResult {\n action: action_type.to_string(),\n index: target_index,\n id: String::new(),\n status: 400,\n result: None,\n error: Some(\"if _id is specified it must not be empty\".to_string()),\n get_source: None,\n },\n *item_index,\n );\n }\n }\n\n let (doc_body, doc_bytes) = if action_type != \"delete\" {\n let dl = match doc_line {\n Some(dl) => dl,\n None => {\n return ParseOutcome::Err(\n BulkItemResult {\n action: action_type.to_string(),\n index: target_index,\n id: doc_id.unwrap_or_default(),\n status: 400,\n result: None,\n error: Some(\"missing document body\".to_string()),\n get_source: None,\n },\n *item_index,\n );\n }\n };\n // M5.11 — SKIP the doc-body JSON parse for `index`\n // actions. The turbo-raw ingest path accepts the raw\n // NDJSON bytes and defers the parse to drain-for-flush\n // on a background thread, taking ~5 µs/doc off the HTTP\n // worker's critical path. `update` and `create`\n // actions still need the parsed Value because they\n // take different code paths below — but `index` is\n // the dominant one on ingest benchmarks.\n //\n // The bytes are still VALIDATED here (syntax + top-level\n // object) via `IgnoredAny`, which walks the JSON without\n // building a Value tree — no per-key String allocations,\n // so the turbo win (skipping the tree build) is kept.\n // Without this, a malformed doc line was deferred to the\n // background parse whose `.unwrap_or({})` stored the doc\n // as EMPTY `{}` while the response said 201/errors:false\n // — silent data loss. ES rejects the item with a 400\n // `document_parsing_exception` instead; mirror that.\n if action_type == \"index\" {\n if let Err(e) =\n serde_json::from_slice::<serde::de::IgnoredAny>(dl.as_bytes())\n {\n return ParseOutcome::Err(\n BulkItemResult {\n action: action_type.to_string(),\n index: target_index,\n id: doc_id.clone().unwrap_or_default(),\n status: 400,\n result: None,\n error: Some(malformed_document_reason(\n doc_id.as_deref(),\n *item_index,\n &e,\n )),\n get_source: None,\n },\n *item_index,\n );\n }\n // ES requires the doc body to be a JSON object;\n // a bare array / scalar is rejected per-item\n // (ES 8.13: `not_x_content_exception`; we report\n // the same condition as a 400 parse error).\n let is_object = dl\n .as_bytes()\n .iter()\n .find(|b| !b\" \\t\\r\\n\".contains(b))\n .map(|b| *b == b'{')\n .unwrap_or(false);\n if !is_object {\n return ParseOutcome::Err(\n BulkItemResult {\n action: action_type.to_string(),\n index: target_index,\n id: doc_id.unwrap_or_default(),\n status: 400,\n result: None,\n error: Some(\n \"failed to parse: invalid document JSON: \\\n document body must be a JSON object\"\n .to_string(),\n ),\n get_source: None,\n },\n *item_index,\n );\n }\n let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(dl.as_bytes());\n (None, bytes)\n } else {\n // See action_line fallback above for why serde_json beats\n // simd_json + to_vec() on small bulk doc lines.\n match serde_json::from_slice::<Value>(dl.as_bytes()) {\n Ok(v) => {\n let bytes: std::sync::Arc<[u8]> =\n std::sync::Arc::from(dl.as_bytes());\n (Some(v), bytes)","is_error":false}]},"uuid":"5f94c581-eaab-46a1-958b-9761ca8cddb2","timestamp":"2026-10-01T15:41:23.736Z","sourceToolAssistantUUID":"76b82cb8-97d5-4612-94f8-e5ae5890388e","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"5f94c581-eaab-46a1-958b-9761ca8cddb2","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202560091fda1f92c174ae3","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_61ab4612e0a14062812144b0","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates && grep -rn \"default_pipeline\" --include=\"*.rs\" xerj-engine/src xerj-api/src | head -20","description":"Find default_pipeline support"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1962,"cache_creation_input_tokens":0,"cache_read_input_tokens":135232,"output_tokens":840,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"7c21a36a-dbb6-4388-986d-934aef2111f0","timestamp":"2026-10-01T15:41:24.261Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7c21a36a-dbb6-4388-986d-934aef2111f0","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_61ab4612e0a14062812144b0","type":"tool_result","content":"xerj-engine/src/engine.rs:4072: /// The `index.default_pipeline` setting for `index`, if it has one.\nxerj-engine/src/engine.rs:4080: /// `{index: {default_pipeline: ..}}`, dotted `{\"index.default_pipeline\": ..}`\nxerj-engine/src/engine.rs:4081: /// and flat `{default_pipeline: ..}` — mirroring the `number_of_shards`\nxerj-engine/src/engine.rs:4087: pub fn default_pipeline_for(&self, index: &str) -> Option<String> {\nxerj-engine/src/engine.rs:4090: .and_then(|ix| ix.get(\"default_pipeline\"))\nxerj-engine/src/engine.rs:4091: .or_else(|| v.get(\"index.default_pipeline\"))\nxerj-engine/src/engine.rs:4092: .or_else(|| v.get(\"default_pipeline\"))\nxerj-engine/src/bulk.rs:270: /// `_none` disables the target index's `index.default_pipeline`.\nxerj-engine/src/bulk.rs:275: /// ran the pipeline. Same for `index.default_pipeline`, which `_bulk` never\nxerj-engine/src/bulk.rs:277: pub default_pipeline: Option<String>,\nxerj-engine/src/bulk.rs:966: // 3. the target index's `index.default_pipeline` setting\nxerj-engine/src/bulk.rs:971: // an index carrying `index.default_pipeline` both answered `201` per item\nxerj-engine/src/bulk.rs:990: .or(opts.default_pipeline.as_deref());\nxerj-engine/src/bulk.rs:994: None => engine.default_pipeline_for(&action.target_index),\nxerj-api/src/es_compat.rs:2722: /// `_none` disables the index's `default_pipeline`; absent falls back to it.\nxerj-api/src/es_compat.rs:2728:/// Mirrors Elasticsearch `index.default_pipeline` semantics:\nxerj-api/src/es_compat.rs:2731:/// - `None` → the index's `index.default_pipeline` setting, if any.\nxerj-api/src/es_compat.rs:2733:/// The default is read by [`xerj_engine::Engine::default_pipeline_for`], which\nxerj-api/src/es_compat.rs:2744: None => state.engine.default_pipeline_for(index),\nxerj-api/src/es_compat.rs:2807: // resolved from the index's `index.default_pipeline` setting.","is_error":false}]},"uuid":"a116edaa-5794-4bb4-ac81-978b41cf7044","timestamp":"2026-10-01T15:41:24.283Z","sourceToolAssistantUUID":"7c21a36a-dbb6-4388-986d-934aef2111f0","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a116edaa-5794-4bb4-ac81-978b41cf7044","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020256277f8ac4265b574e33","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"For `index` actions, the top-level-object check IS performed (bulk.rs:827-845) — a naive first-byte check `dl.as_bytes().iter().find(|b| !whitespace).map(|b| *b == b'{')`. So `index` actions require the first non-whitespace byte to be `{`. Note: `{\"a\":1}` is an object — fine. So a non-object can't get through via `index`.\n\nBut what about `create` actions? Look: `if action_type == \"index\" { ...object check... } else { serde_json::from_slice::<Value>(...) → (Some(v), bytes) }`. The `else` branch covers `create` and `update`. For `create`, the body is parsed into `doc_body = Some(v)` with NO object check! And `create` actions DO go through the pipeline (bulk.rs:1745 `matches!(action_type.as_str(), \"index\" | \"create\")`).\n\nSo: `POST /_bulk` with:\n```\n{\"create\":{\"_index\":\"i\",\"pipeline\":\"p\"}}\n[1,2,3]\n```\n→ doc_body = Some(Value::Array([1,2,3])) → input to pipeline = Array → `AddFieldPlugin::process` panics → process aborts (panic=abort in release) → the whole server dies.\n\nWait, but is there any earlier check for `create`? Let's check whether `create` requires the doc to be an object elsewhere. Also check line 2267 `let obj = match src.as_object()` — that's `inject_routing`. Hmm, at 2267-2304, `inject_routing` returns `Value::Object(obj)` for non-objects... Let me check that function, and also whether `create` actions go through the turbo path or the per-item loop.\n\nActually, more carefully: the per-item loop for non-index ops handles \"create\" (see comment \"Execute non-index ops individually (create, update, delete)\"). But the comment also says \"`parsed` here has already been filtered to non-`index` actions by the turbo-batch partition above\". So `create` goes through this per-item loop, and the pipeline execution block at 1745 includes \"create\". \n\nSo the chain is real: `create` + non-object body + pipeline → panic.\n\nHmm, but wait. Let me double check the else branch at line ~860. Let me read lines 855-900 to see the exact code.\n\nAlso let me check whether `update` actions can carry a pipeline... `update` is excluded from the pipeline block.\n\nAlso there may be other routes: the `_ingest/pipeline/_simulate` API in es_compat which lets you POST arbitrary docs. Let me check that. In ES, `_simulate` takes `{\"docs\": [{...}]}` — docs are expected objects. If xerj's simulate passes non-object docs into the pipeline → same panic. Let me check xerj-api/native.rs:2666 and es_compat.\n\nLet me now verify:\n1. bulk.rs else-branch for create (no object check).\n2. es_compat / native simulate path object validation.\n3. Whether there's a top-level object check for the single-document index API (`PUT /index/_doc/1`).\n\nLet me look.","signature":"5513a9ca3a744d33912186c3"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"e0076732-e567-4e90-be41-2f19bc8bf08c","timestamp":"2026-10-01T15:41:49.947Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"e0076732-e567-4e90-be41-2f19bc8bf08c","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020256277f8ac4265b574e33","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_00fa593d0e614e1caee20751","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '855,900p' bulk.rs","description":"Read create/update body parse branch"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"c81b3142-ffce-458e-b7f0-2183c8f82da9","timestamp":"2026-10-01T15:41:49.949Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c81b3142-ffce-458e-b7f0-2183c8f82da9","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_00fa593d0e614e1caee20751","type":"tool_result","content":" // simd_json + to_vec() on small bulk doc lines.\n match serde_json::from_slice::<Value>(dl.as_bytes()) {\n Ok(v) => {\n let bytes: std::sync::Arc<[u8]> =\n std::sync::Arc::from(dl.as_bytes());\n (Some(v), bytes)\n }\n Err(e) => {\n return ParseOutcome::Err(\n BulkItemResult {\n action: action_type.to_string(),\n index: target_index,\n id: doc_id.clone().unwrap_or_default(),\n status: 400,\n result: None,\n error: Some(malformed_document_reason(\n doc_id.as_deref(),\n *item_index,\n &e,\n )),\n get_source: None,\n },\n *item_index,\n );\n }\n }\n }\n } else {\n // Delete action — we may have optimistically consumed\n // a line during pair building that actually belongs to\n // the NEXT action. Signal the caller to pop it back\n // into the input stream.\n let skip_back = if doc_line.is_some() { 1usize } else { 0usize };\n let action = ParsedAction {\n action_type: action_type.to_string(),\n target_index,\n doc_id,\n doc_body: None,\n doc_bytes: std::sync::Arc::from(&[][..]),\n item_index: *item_index,\n require_alias: require_alias_per_item,\n pipeline: pipeline_per_item.clone(),\n if_seq_no: if_seq_no_per_item,\n if_primary_term: if_primary_term_per_item,\n routing: routing_per_item.clone(),\n source_req: source_req_per_item.clone(),","is_error":false}]},"uuid":"7c19c85b-f8a9-4646-a065-fb402aa44886","timestamp":"2026-10-01T15:41:49.960Z","sourceToolAssistantUUID":"c81b3142-ffce-458e-b7f0-2183c8f82da9","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7c19c85b-f8a9-4646-a065-fb402aa44886","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020256277f8ac4265b574e33","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_03e3ccbadcdb4a19b12e1159","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && grep -n \"process_through_pipeline\\|_simulate\\|fn simulate\" es_compat.rs native.rs | head -30","description":"Find simulate pipeline API paths"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2917,"cache_creation_input_tokens":0,"cache_read_input_tokens":137152,"output_tokens":816,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"fe2da5bb-c1fe-42a4-91aa-6f95f927a178","timestamp":"2026-10-01T15:41:50.235Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"fe2da5bb-c1fe-42a4-91aa-6f95f927a178","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_03e3ccbadcdb4a19b12e1159","type":"tool_result","content":"native.rs:2650: .process_through_pipeline(¶ms.pipeline, docs)\nes_compat.rs:2810: match state.engine.process_through_pipeline(pipeline, vec![doc]) {\nes_compat.rs:2946: .process_through_pipeline(pipeline, vec![doc.clone()])\nes_compat.rs:3080: .process_through_pipeline(pipeline, vec![doc.clone()])\nes_compat.rs:17625: /// it and `_simulate` still walks it) — but no document may then be\nes_compat.rs:23864: Some(p) => match state.engine.process_through_pipeline(p, vec![hit.source]) {\nes_compat.rs:27782: match engine.process_through_pipeline(pipeline, vec![doc]) {\nes_compat.rs:28834:// POST /_ingest/pipeline/{id}/_simulate\nes_compat.rs:28855:/// `process_through_pipeline` zips one action per input document, so this is an\nes_compat.rs:28870:/// Paired with [`es_proc_name`], which MUST stay its inverse: `_simulate` walks\nes_compat.rs:28885: // 200, and in disagreement with the `_simulate` interpreter below,\nes_compat.rs:28907:/// `_simulate` interprets.\nes_compat.rs:28914:/// through untouched, because `_simulate`'s interpreter reads those to build\nes_compat.rs:29016:/// branch in the first place. `_simulate` was taught this inverse in this same\nes_compat.rs:29104: /// `_simulate` interpreted `set` as an unconditional overwrite, so it\nes_compat.rs:29109: fn simulate_honours_the_set_override_flag() {\nes_compat.rs:29154: // with its inverse `es_proc_name`, so `_simulate` can render a stored\nes_compat.rs:29332: // replay can recompile, and one `_simulate` walks\nes_compat.rs:29484:/// `POST /_ingest/pipeline/_simulate` — inline pipeline in body.\nes_compat.rs:29485:pub async fn simulate_inline_pipeline(\nes_compat.rs:29617: // to every caller of `_simulate`. See\nes_compat.rs:29841: Value::String(\"_simulate_pipeline\".into()),\nes_compat.rs:30307: // `_simulate` of a stored pipeline that PRESERVES an existing value\nes_compat.rs:30488:pub async fn simulate_ingest_pipeline(\nes_compat.rs:43076:// POST /_index_template/_simulate_index/{name}\nes_compat.rs:43118:pub async fn simulate_index_template(\nes_compat.rs:43157:// POST /_index_template/_simulate\nes_compat.rs:43160:/// Body-only variant of `_simulate_index/{name}`: Kibana's index template\nes_compat.rs:43166:pub async fn simulate_index_template_body(","is_error":false}]},"uuid":"7d0af73f-15c1-4174-ab6c-0f0dca9301b0","timestamp":"2026-10-01T15:41:50.253Z","sourceToolAssistantUUID":"fe2da5bb-c1fe-42a4-91aa-6f95f927a178","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7d0af73f-15c1-4174-ab6c-0f0dca9301b0","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202565175df6558923a4f63","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Confirmed: `create` action bodies are parsed with no top-level object check (bulk.rs:858-864) while `index` bodies ARE checked (bulk.rs:827-845). That's the asymmetric gap.\n\nNow let's verify the simulate paths accept non-object docs. Let me look at es_compat.rs around 2790-2830 and 29484-29640 and 27770-27800.\n\nAlso let me check `native.rs:2650` (POST /v1/pipelines/{name}/process probably) — the docs come from the request body directly, likely arbitrary JSON values.\n\nLet me read those.","signature":"1d5784404e5f4ddcb696bfac"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"ebefb036-1ff3-4772-afa7-86d7f2ccbffb","timestamp":"2026-10-01T15:41:57.543Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"ebefb036-1ff3-4772-afa7-86d7f2ccbffb","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202565175df6558923a4f63","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_e7f4eb0b57584737b38ad738","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && sed -n '2600,2680p' native.rs","description":"Read native pipeline process handler"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"635ef16e-5012-40ef-bdc3-3bebf6937ff5","timestamp":"2026-10-01T15:41:57.544Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"635ef16e-5012-40ef-bdc3-3bebf6937ff5","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_e7f4eb0b57584737b38ad738","type":"tool_result","content":" );\n (StatusCode::OK, Json(resp)).into_response()\n }\n // The definition does not compile — same 500 this surface has always\n // returned, and nothing was stored.\n Ok(Some(compile_err)) => {\n let ze = xerj_common::XerjError::internal(compile_err.to_string());\n native_error(ze, Some(&request_id), started.elapsed().as_millis() as u64)\n .into_response()\n }\n Err(e) => {\n let ze = xerj_common::XerjError::internal(e.to_string());\n native_error(ze, Some(&request_id), started.elapsed().as_millis() as u64)\n .into_response()\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Handler: POST /v1/indices/{name}/ingest?pipeline={pipeline}\n// ─────────────────────────────────────────────────────────────────────────────\n\n/// Query parameters for the pipeline-ingest endpoint.\n#[derive(Debug, Deserialize)]\npub struct IngestWithPipelineParams {\n pub pipeline: String,\n}\n\n/// Ingest one or more documents through a named transform pipeline before\n/// indexing.\n///\n/// Documents with [`ProcessAction::Drop`] are silently discarded.\n/// Documents with [`ProcessAction::Route(target)`] are indexed into `target`\n/// instead of `{name}`.\npub async fn ingest_with_pipeline(\n State(state): State<AppState>,\n Path(name): Path<String>,\n axum::extract::Query(params): axum::extract::Query<IngestWithPipelineParams>,\n Json(req): Json<IngestRequest>,\n) -> impl IntoResponse {\n let started = Instant::now();\n let request_id = Uuid::new_v4().to_string();\n\n let docs: Vec<Value> = match req {\n IngestRequest::Single(doc) => vec![doc],\n IngestRequest::Batch(docs) => docs,\n };\n\n let processed = match state\n .engine\n .process_through_pipeline(¶ms.pipeline, docs)\n {\n Ok(p) => p,\n Err(e) => {\n let ze = xerj_common::XerjError::internal(e.to_string());\n return native_error(ze, Some(&request_id), started.elapsed().as_millis() as u64)\n .into_response();\n }\n };\n\n let mut indexed = 0u64;\n let mut dropped = 0u64;\n let mut routed = 0u64;\n let mut errors = 0u64;\n\n for (action, doc) in processed {\n use xerj_wasm::pipeline::ProcessAction;\n let target_name = match action {\n ProcessAction::Drop => {\n dropped += 1;\n continue;\n }\n ProcessAction::Route(ref target) => {\n routed += 1;\n target.clone()\n }\n ProcessAction::Pass => name.clone(),\n };\n\n let idx = match state.engine.get_or_create_index(&target_name) {\n Ok(i) => i,","is_error":false}]},"uuid":"d6f9a775-7697-44d7-9507-17e7dd12dcc3","timestamp":"2026-10-01T15:41:57.559Z","sourceToolAssistantUUID":"635ef16e-5012-40ef-bdc3-3bebf6937ff5","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d6f9a775-7697-44d7-9507-17e7dd12dcc3","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202565175df6558923a4f63","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_13c4b59a929c4eec9bba4bf3","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && sed -n '2770,2830p' es_compat.rs && echo \"=== 30488 simulate_ingest_pipeline ===\" && sed -n '30480,30560p' es_compat.rs","description":"Read es_compat pipeline doc paths"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1835,"cache_creation_input_tokens":0,"cache_read_input_tokens":140032,"output_tokens":277,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"97323ad6-eae8-419e-8f33-03e449f2fec5","timestamp":"2026-10-01T15:41:58.985Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"97323ad6-eae8-419e-8f33-03e449f2fec5","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_13c4b59a929c4eec9bba4bf3","type":"tool_result","content":" let doc = apply_ignore_malformed(&state, &index, doc);\n\n // Range-type + copy_to rejection. ES accepts the mapping at\n // create time but fails the first doc that actually references\n // the range field, since copy_to on a range is meaningless\n // (ES: \"Copy-to currently only works for value-type fields\").\n if let Some(range_field) = first_range_copy_to_field_in_mapping(&state, &index, doc.as_object())\n {\n return (\n StatusCode::BAD_REQUEST,\n Json(json!({\n \"error\": {\n \"type\": \"document_parsing_exception\",\n \"reason\": format!(\n \"failed to parse field [{}]: Copy-to currently only works for value-type fields, not ranges\",\n range_field\n )\n },\n \"status\": 400\n }))\n ).into_response();\n }\n\n // Apply dynamic-template `copy_to` at ingest (single-doc path).\n // Bulk performs this in `bulk.rs`; the _doc endpoints get the\n // same materialisation so the stored source carries the copy\n // target's value before search time.\n let doc = {\n let mut d = doc;\n if let Some(obj) = d.as_object_mut() {\n let mapping = state.engine.index_mappings.get(&index).map(|v| v.clone());\n xerj_engine::bulk::apply_dynamic_template_copy_to_public(obj, mapping.as_ref());\n }\n d\n };\n\n // Execute ingest pipeline if one is specified (explicit `?pipeline=`) or\n // resolved from the index's `index.default_pipeline` setting.\n let effective_pipeline = resolve_effective_pipeline(&state, &index, params.pipeline.as_deref());\n let doc = if let Some(ref pipeline) = effective_pipeline {\n match state.engine.process_through_pipeline(pipeline, vec![doc]) {\n Ok(mut results) if !results.is_empty() => {\n let (action, transformed) = results.remove(0);\n if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\n return Json(json!({\"result\": \"noop\", \"_id\": \"\", \"_version\": 0}))\n .into_response();\n }\n transformed\n }\n // No output for this document: refused, not passed through\n // unchanged — see `pipeline_empty_result_error`.\n Ok(_) => return pipeline_empty_result_error(pipeline).into_response(),\n // Issue #204, the purest form of the class on a user-DATA path:\n // this used to warn and then index the ORIGINAL document. A\n // pipeline whose job was to redact PII, drop a field or route the\n // document simply did not run, and the caller got `201 Created`.\n // `_bulk` already fails the item here; the single-document path now\n // agrees with it.\n Err(e) => return pipeline_execution_error(pipeline, &e).into_response(),\n }\n } else {\n=== 30488 simulate_ingest_pipeline ===\n // Everything else is accepted as a no-op so that custom processors\n // don't fail the simulate. The ES spec requires every declared\n // processor to be known, but xerj's compat layer is deliberately\n // forgiving here to match what YAML tests actually exercise.\n _ => Ok(()),\n }\n}\n\npub async fn simulate_ingest_pipeline(\n State(state): State<AppState>,\n Path(id): Path<String>,\n Query(params): Query<SimulatePipelineParams>,\n Json(body): Json<SimulatePipelineBody>,\n) -> impl IntoResponse {\n // Look up the stored pipeline; treat missing as 404.\n let stored = match state.engine.pipelines.get(&id) {\n Some(p) => p.clone(),\n None => {\n let e = xerj_common::XerjError::index_not_found(format!(\"pipeline [{id}] is missing\"));\n return ApiError::new(e).into_response();\n }\n };\n\n // The stored pipeline may be in ES shape (`processors: [{set: {...}}]`)\n // when it was round-tripped verbatim, OR in xerj internal shape\n // (`stages: [{type: \"set\", config: {...}}]`) after compilation.\n // Accept either — convert stages back into the ES-processor shape.\n //\n // The conversion has to invert BOTH halves of the translation\n // `put_ingest_pipeline` applied, name and config. Emitting the internal\n // name here reported `processor_type: \"field_rename\"` where ES reports\n // `\"rename\"` — invisible while every ES `rename` failed to compile (the\n // raw ES body was stored, so this branch was never taken), and a\n // conformance failure the moment `rename` started compiling.\n let processors: Vec<Value> = if let Some(p) = stored.get(\"processors\").and_then(Value::as_array)\n {\n p.clone()\n } else if let Some(stages) = stored.get(\"stages\").and_then(Value::as_array) {\n stages_to_es_processors(stages)\n } else {\n Vec::new()\n };\n\n // If the caller also inlined a pipeline, ES rejects with parse_exception.\n if body.pipeline.is_some() {\n return build_ingest_parse_error(\n \"pipeline\",\n \"cannot combine stored pipeline and inline pipeline\",\n );\n }\n\n let verbose = params.verbose.as_deref() == Some(\"true\");\n let out_docs: Vec<Value> = body\n .docs\n .iter()\n .map(|d| run_inline_pipeline_on_doc(d, &processors, verbose))\n .collect();\n\n Json(json!({ \"docs\": out_docs })).into_response()\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// POST /{index}/_close — mark index as closed\n// POST /{index}/_open — mark index as open\n// ─────────────────────────────────────────────────────────────────────────────\n\npub async fn close_index(\n State(state): State<AppState>,\n Path(index): Path<String>,\n) -> impl IntoResponse {\n // ES 8's `action.destructive_requires_name` defaults to true: closing\n // by wildcard/_all is refused outright — only concrete names may close.\n if index == \"_all\" || index.contains('*') {\n return (\n StatusCode::BAD_REQUEST,\n Json(json!({\n \"error\": {\n \"root_cause\": [{\n \"type\": \"illegal_argument_exception\",\n \"reason\": \"Wildcard expressions or all indices are not allowed\"\n }],","is_error":false}]},"uuid":"c3b65ca5-0bb1-48a7-b5e4-1f31d488dae0","timestamp":"2026-10-01T15:41:59.006Z","sourceToolAssistantUUID":"97323ad6-eae8-419e-8f33-03e449f2fec5","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c3b65ca5-0bb1-48a7-b5e4-1f31d488dae0","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020256599618dd3f94b143d0","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"`POST /v1/indices/{name}/ingest?pipeline=X` accepts `IngestRequest::Single(doc)` — an arbitrary JSON Value. If the client POSTs `[1,2,3]` or `5` as the body, docs = vec![Value::Array] → `process_through_pipeline` → pipeline stage `add_field` → PANIC → abort.\n\nThis is a much more direct path than bulk. Let me confirm `IngestRequest` type: `Single(Value)` or `Batch(Vec<Value>)`. And whether auth is required (native API may require an API key, but the ES-compat path may be unauthenticated).\n\nAlso the ES-compat single-doc path at es_compat.rs:2810 — where does `doc` come from? `PUT /{index}/_doc/{id}?pipeline=x` with a JSON body. Let's check whether that handler validates the body is an object. Line 2770 shows `apply_ignore_malformed(&state, &index, doc)` then `doc.as_object()`. Let's read earlier to see how doc is obtained and whether there's an object check before pipeline execution. If a client can PUT `[1,2,3]` with `?pipeline=p`, that panics too.\n\nLet me check that handler (search for the function containing line 2810).\n\nAlso let me confirm the pipeline panic → abort chain by checking `process_through_pipeline` in engine.rs:4276-4300 (already seen: calls pipeline.process_batch).\n\nNow, is `panic = \"abort\"` really the shipped binary? Yes: [profile.release] panic = \"abort\" at engine/Cargo.toml:165. So any panic = whole-process death. That's a critical remote DoS with a single unauthenticated-ish request (if the API is reachable).\n\nLet me now verify the single-doc handler's object validation and check for other panics reachable from documents in the engine (not just the pipeline). But focus: the task asks about pipeline/builtins + autoindex. The panic is in builtins.rs, so it's in scope.\n\nLet me confirm:\n1. `IngestRequest` definition.\n2. es_compat single-doc handler: does it check `is_object` before pipeline?\n\nLet me grep.","signature":"f0285d0eaeec4a8cafe720c1"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2451,"cache_creation_input_tokens":0,"cache_read_input_tokens":141824,"output_tokens":565,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"f346b83f-68bc-4888-aa3c-1e5fa4007ded","timestamp":"2026-10-01T15:42:18.113Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f346b83f-68bc-4888-aa3c-1e5fa4007ded","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020256599618dd3f94b143d0","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_e55e7b36f03c46429e7a790d","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && grep -n \"enum IngestRequest\" -A 12 native.rs | head -20; echo \"=== single doc handler around 2810 ===\"; sed -n '2690,2775p' es_compat.rs","description":"Inspect IngestRequest and single doc handler"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2451,"cache_creation_input_tokens":0,"cache_read_input_tokens":141824,"output_tokens":565,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"c6181f85-4717-402b-888c-ab4c9a1ebb30","timestamp":"2026-10-01T15:42:18.122Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c6181f85-4717-402b-888c-ab4c9a1ebb30","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_e55e7b36f03c46429e7a790d","type":"tool_result","content":"45:pub enum IngestRequest {\n46- Single(Value),\n47- Batch(Vec<Value>),\n48-}\n49-\n50-#[derive(Debug, Deserialize)]\n51-pub struct NativeSearchRequest {\n52- #[serde(default)]\n53- pub q: Option<String>,\n54- #[serde(default = \"default_size\")]\n55- pub size: usize,\n56- #[serde(default)]\n57- pub from: usize,\n=== single doc handler around 2810 ===\n State(state): State<AppState>,\n Path(index): Path<String>,\n) -> impl IntoResponse {\n let targets = resolve_index_selector(&state, &index).await;\n if targets.is_empty() {\n let e = xerj_common::XerjError::index_not_found(&index);\n return ApiError::new(e).into_response();\n }\n let mut out = serde_json::Map::new();\n for name in &targets {\n let stored = state\n .engine\n .index_settings\n .get(name)\n .map(|v| v.clone())\n .unwrap_or(Value::Null);\n let settings = merge_settings_defaults(&stored, name, false);\n out.insert(name.clone(), json!({ \"settings\": settings }));\n }\n Json(Value::Object(out)).into_response()\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// POST /{index}/_doc\n// ─────────────────────────────────────────────────────────────────────────────\n\n/// Query parameters for the auto-ID index endpoint.\n#[derive(Debug, Default, Deserialize)]\npub struct IndexDocAutoParams {\n /// `refresh=true|wait_for` — accepted without error; memtable is always visible.\n pub refresh: Option<String>,\n /// `pipeline=my_pipeline` — ingest pipeline to run before indexing.\n /// `_none` disables the index's `default_pipeline`; absent falls back to it.\n pub pipeline: Option<String>,\n}\n\n/// Resolve the effective ingest pipeline for a single-doc write.\n///\n/// Mirrors Elasticsearch `index.default_pipeline` semantics:\n/// - `Some(\"_none\")` → `None` (explicit opt-out; no pipeline runs).\n/// - `Some(name)` → that pipeline (an explicit `?pipeline=` always wins).\n/// - `None` → the index's `index.default_pipeline` setting, if any.\n///\n/// The default is read by [`xerj_engine::Engine::default_pipeline_for`], which\n/// `_bulk` also uses — one lookup, so the two forms of the same write cannot\n/// disagree about which pipeline applies.\nfn resolve_effective_pipeline(\n state: &AppState,\n index: &str,\n explicit: Option<&str>,\n) -> Option<String> {\n match explicit {\n Some(\"_none\") => None,\n Some(p) => Some(p.to_string()),\n None => state.engine.default_pipeline_for(index),\n }\n}\n\n/// Fast path for `POST /{index}/_doc`: receives raw bytes to skip the axum\n/// JSON extractor's extra validation pass and parse directly with simd_json /\n/// serde_json. No schema validation is performed here; the engine layer handles\n/// all type coercion. This shaves ~15–30 µs of extractor overhead per doc.\npub async fn index_doc_auto(\n State(state): State<AppState>,\n Path(index): Path<String>,\n Query(params): Query<IndexDocAutoParams>,\n body: bytes::Bytes,\n) -> impl IntoResponse {\n // Parse the raw body directly — avoids the axum Json extractor's extra\n // content-type enforcement and serde_json::from_str double-pass.\n let doc: Value = match serde_json::from_slice(&body) {\n Ok(v) => v,\n Err(e) => {\n return ApiError::new(xerj_common::XerjError::invalid_query(format!(\n \"invalid JSON body: {e}\"\n )))\n .into_response();\n }\n };\n\n let doc = apply_ignore_malformed(&state, &index, doc);\n\n // Range-type + copy_to rejection. ES accepts the mapping at\n // create time but fails the first doc that actually references\n // the range field, since copy_to on a range is meaningless\n // (ES: \"Copy-to currently only works for value-type fields\").","is_error":false}]},"uuid":"456151a4-cbd5-473d-b46f-091ee4e3d6ec","timestamp":"2026-10-01T15:42:18.177Z","sourceToolAssistantUUID":"c6181f85-4717-402b-888c-ab4c9a1ebb30","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"456151a4-cbd5-473d-b46f-091ee4e3d6ec","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202571608915409d9e44f12","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Confirmed: `index_doc_auto` parses the body as an arbitrary `Value` with no object check, then at es_compat.rs:2807-2810 runs the pipeline on it.\n\nSo: `POST /some-index/_doc?pipeline=p` with body `[1,2,3]` → `process_through_pipeline(p, vec![Value::Array])` → `AddFieldPlugin`/`SetPlugin`/etc. panic → abort → process dies.\n\nWait — I should double check `apply_ignore_malformed`. It might convert non-objects. Let's check it. Also I should double check that serde_json's IndexMut indeed panics for arrays. Yes: `impl Index<&str> for Value` → `index_or_insert` panics with \"cannot access key {:?} in JSON {}\" for non-object, non-null values.\n\nActually wait — one more consideration. For `Value::Null`, `index_or_insert` converts Null → Object. So the panic only occurs for Array/Number/Bool/String.\n\nLet me verify `apply_ignore_malformed`.\n\nAlso, I want to check the second es_compat path at 2946/3080 and 23864 (search-time pipeline on `hit.source` — interesting: applying a pipeline to search hits at query time! If a stored document is an array... but docs can't be stored as arrays because index path validates? Hmm, at 23864 `process_through_pipeline(p, vec![hit.source])` — hit.source comes from the index. If any doc was stored as non-object... the bulk `create` path might store it. Let's not go too deep.\n\nLet me check `apply_ignore_malformed` and then also verify whether an index `default_pipeline` can be set by an attacker who can create an index (making the panic require no query param).\n\nPriority now: verify the panic chain is real and reachable, then continue scanning for other issues (autoindex hostile files).\n\nLet me check apply_ignore_malformed quickly and confirm no object coercion.","signature":"6c9f358b0625432382f378c9"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"d90c9a40-b745-4f61-b70a-e6f1c955f19a","timestamp":"2026-10-01T15:42:35.911Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d90c9a40-b745-4f61-b70a-e6f1c955f19a","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202571608915409d9e44f12","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_8f214e4b53624f5ab4fbc907","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && grep -n \"fn apply_ignore_malformed\" -A 30 es_compat.rs | head -40","description":"Read apply_ignore_malformed"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1493,"cache_creation_input_tokens":0,"cache_read_input_tokens":144256,"output_tokens":539,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"6e113ef7-c229-4d2b-af50-4137bbe20833","timestamp":"2026-10-01T15:42:36.972Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6e113ef7-c229-4d2b-af50-4137bbe20833","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202571608915409d9e44f12","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_06bd41705094414da1ed59ab","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '4270,4310p' engine.rs","description":"Read process_through_pipeline"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1493,"cache_creation_input_tokens":0,"cache_read_input_tokens":144256,"output_tokens":539,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"9866c852-9965-4068-a262-5632d54e2bf0","timestamp":"2026-10-01T15:42:36.994Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"9866c852-9965-4068-a262-5632d54e2bf0","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_06bd41705094414da1ed59ab","type":"tool_result","content":" );\n Ok(())\n }\n\n /// Run `docs` through a named pipeline, returning `(action, doc)` pairs.\n ///\n /// Returns [`xerj_wasm::WasmError::PipelineNotFound`] when `pipeline_name`\n /// does not exist. Documents with a [`ProcessAction::Drop`] action are\n /// still returned in the output — callers decide whether to skip indexing.\n pub fn process_through_pipeline(\n &self,\n pipeline_name: &str,\n mut docs: Vec<Value>,\n ) -> std::result::Result<Vec<(xerj_wasm::pipeline::ProcessAction, Value)>, xerj_wasm::WasmError>\n {\n let pipeline = self.transform_pipelines.get(pipeline_name).ok_or_else(|| {\n // Issue #204: distinguish \"no such pipeline\" from \"stored but this\n // build cannot run it\". Both must fail — what must not happen is a\n // document being indexed untransformed — but reporting the second\n // as the first sent operators hunting for a pipeline that is\n // plainly there in `GET /_ingest/pipeline`.\n match self.unrunnable_pipelines.get(pipeline_name) {\n Some(reason) => xerj_wasm::WasmError::PipelineNotRunnable {\n pipeline: pipeline_name.to_string(),\n reason: reason.clone(),\n },\n None => xerj_wasm::WasmError::PipelineNotFound(pipeline_name.to_string()),\n }\n })?;\n\n let actions = pipeline.process_batch(&mut docs);\n Ok(actions.into_iter().zip(docs).collect())\n }\n\n // ── Snapshot / Restore ────────────────────────────────────────────────────\n\n /// Create a filesystem snapshot of all (or named) indices.\n ///\n /// For each index this copies:\n /// - WAL files (`<index>/wal/`)\n /// - Segment files (`<index>/segments/`)","is_error":false}]},"uuid":"0ee710a9-1d5f-4ae0-8b21-4659f389f440","timestamp":"2026-10-01T15:42:37.206Z","sourceToolAssistantUUID":"9866c852-9965-4068-a262-5632d54e2bf0","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6e113ef7-c229-4d2b-af50-4137bbe20833","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_8f214e4b53624f5ab4fbc907","type":"tool_result","content":"39252:pub(crate) fn apply_ignore_malformed(state: &AppState, index: &str, doc: Value) -> Value {\n39253- let Some(mapping) = state.engine.index_mappings.get(index).map(|v| v.clone()) else {\n39254- return doc;\n39255- };\n39256- let Some(mut obj) = doc.as_object().cloned() else {\n39257- return doc;\n39258- };\n39259- let mut ignored: Vec<String> = Vec::new();\n39260- let mut ignored_values: serde_json::Map<String, Value> = serde_json::Map::new();\n39261- let props = mapping\n39262- .get(\"mappings\")\n39263- .and_then(|m| m.get(\"properties\"))\n39264- .or_else(|| mapping.get(\"properties\"))\n39265- .and_then(Value::as_object);\n39266- if let Some(props_obj) = props {\n39267- validate_doc_fields(\"\", &mut obj, props_obj, &mut ignored, &mut ignored_values);\n39268- }\n39269- if !ignored.is_empty() {\n39270- ignored.sort();\n39271- ignored.dedup();\n39272- obj.insert(\n39273- \"_ignored\".to_string(),\n39274- Value::Array(ignored.into_iter().map(Value::String).collect()),\n39275- );\n39276- }\n39277- if !ignored_values.is_empty() {\n39278- // Stash the original malformed values under an internal sentinel\n39279- // key; the hit renderer promotes this to `ignored_field_values`\n39280- // and strips it from the returned `_source`.\n39281- obj.insert(\n39282- \"__xy_ignored_values__\".to_string(),\n--\n39621: async fn apply_ignore_malformed_end_to_end_matches_ubi_events_mapping() {\n39622- let dir = tempfile::tempdir().expect(\"tempdir\").keep();\n39623- let mut config = xerj_common::config::Config::default();\n39624- config.server.data_dir = dir.to_string_lossy().into_owned();\n39625- config.storage.wal_sync = xerj_common::config::WalSync::Async;\n39626- let metrics = xerj_common::metrics::Metrics::new().expect(\"metrics\");\n39627- let engine = xerj_engine::Engine::new(config.clone()).expect(\"engine\");\n39628- let state = AppState::new(config, engine, metrics);","is_error":false}]},"uuid":"c999f8e1-be86-4e5b-afff-a89e4182410a","timestamp":"2026-10-01T15:42:37.209Z","sourceToolAssistantUUID":"6e113ef7-c229-4d2b-af50-4137bbe20833","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c999f8e1-be86-4e5b-afff-a89e4182410a","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202573490dd49ccd3434e68","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"Confirmed the full chain. `apply_ignore_malformed` returns the doc unchanged for non-objects.\n\nNow, the pipeline input for a non-object doc → panic in `builtins.rs` → `panic = \"abort\"` in release → whole server process dies.\n\nAttack path:\n1. Attacker creates a pipeline: `PUT /_ingest/pipeline/p` with `{\"processors\":[{\"set\":{\"field\":\"x\",\"value\":\"y\"}}]}`. (Requires pipeline-create permission; but many deployments have open ES-compatible APIs.)\n2. Attacker POSTs `/_idx/_doc?pipeline=p` with body `[]` → panic → abort → whole node dies.\n\nEven simpler with just one request if a default_pipeline is configured on an index.\n\nActually wait — is there any other single-request variant that doesn't require creating a pipeline? The native API `POST /v1/indices/{name}/ingest?pipeline=X` requires an existing pipeline too.\n\nHmm — but note, does the `_simulate` inline path compile the pipeline from the request body and run it? `simulate_inline_pipeline` at es_compat.rs:29484 takes an inline pipeline from the body. Let's check whether it runs `run_inline_pipeline_on_doc` (an interpreter) or the compiled pipeline. It uses `run_inline_pipeline_on_doc(d, &processors, verbose)` — an interpreter, not the compiled pipeline. Let me check whether the interpreter has the same non-object panic (it might use `.as_object_mut()` safely, or it may index too). Let me look at that function. If the interpreter is safe, then the compiled-pipeline paths are the vulnerable ones.\n\nLet me check `run_inline_pipeline_on_doc`.\n\nAlso, let me check the `Array` handling in the interpreter... Actually, let's focus: I have a strong finding. Let me also verify whether an authenticated attacker is needed — check auth middleware for the ES-compat API. Let me quickly check if there's auth (API key) required.\n\nThen continue with autoindex hostile-file analysis: I should look at the extractors for panics (that's the \"malformed doc panic\" category). Let me grep for indexing/slicing in the extractors reachable from file bytes. Particularly `mbox.rs`, `eml.rs`, `html.rs`, `code.rs` (tree-sitter), `csv_x.rs`, `logs.rs`, `json.rs`.\n\nLet me run a broad grep for direct indexing `[` patterns that aren't `.get(`.\n\nLet me do a couple of parallel greps.","signature":"e7d5527817ea4945ab676342"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"340c823b-276d-4f06-bad2-7d26ff1a1bfb","timestamp":"2026-10-01T15:42:56.777Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"340c823b-276d-4f06-bad2-7d26ff1a1bfb","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202573490dd49ccd3434e68","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_216fb612211b491596796241","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && grep -n \"fn run_inline_pipeline_on_doc\" -A 40 es_compat.rs | head -60","description":"Read simulate interpreter doc handling"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"9da2feb6-b54d-4d5c-9865-8d03b3d410c5","timestamp":"2026-10-01T15:42:59.651Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"9da2feb6-b54d-4d5c-9865-8d03b3d410c5","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_216fb612211b491596796241","type":"tool_result","content":"29747:fn run_inline_pipeline_on_doc(input: &Value, processors: &[Value], verbose: bool) -> Value {\n29748- let index = input\n29749- .get(\"_index\")\n29750- .and_then(Value::as_str)\n29751- .unwrap_or(\"_index\")\n29752- .to_string();\n29753- let id = input\n29754- .get(\"_id\")\n29755- .and_then(Value::as_str)\n29756- .unwrap_or(\"_id\")\n29757- .to_string();\n29758- let mut source: Value = input\n29759- .get(\"_source\")\n29760- .cloned()\n29761- .unwrap_or(Value::Object(serde_json::Map::new()));\n29762-\n29763- let timestamp = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);\n29764-\n29765- let mut results: Vec<Value> = Vec::new();\n29766- let mut error: Option<(String, String)> = None;\n29767-\n29768- // ── Verbose per-step renderer ─────────────────────────────────\n29769- //\n29770- // `on_failure_tag` lets nested on_failure chains stamp their own\n29771- // doc._ingest.on_failure_processor_tag so the YAML tests can\n29772- // inspect which processor triggered the recovery.\n29773- // Renderer needs every piece of per-step context; splitting the\n29774- // signature into a struct would not improve clarity here.\n29775- #[allow(clippy::too_many_arguments)]\n29776- fn render_entry(\n29777- name: &str,\n29778- cfg: &Value,\n29779- status: &str,\n29780- error_msg: Option<&str>,\n29781- ignored_error: Option<&str>,\n29782- source: &Value,\n29783- index: &str,\n29784- id: &str,\n29785- timestamp: &str,\n29786- on_failure_tag: Option<&str>,\n29787- ) -> Value {","is_error":false}]},"uuid":"0dbb5215-485e-42fd-a771-5c9b9b857145","timestamp":"2026-10-01T15:42:59.710Z","sourceToolAssistantUUID":"9da2feb6-b54d-4d5c-9865-8d03b3d410c5","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"0dbb5215-485e-42fd-a771-5c9b9b857145","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202573490dd49ccd3434e68","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_c0e9d728c9494cd59aab3faa","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -rnE \"\\[([a-z_]+)\\.(len\\(\\)|n|[0-9]+)\\]? *;|\\[\\.\\.\\]|\\.unwrap\\(\\)|panic!|unreachable!|\\bexpect\\(\" extract/mbox.rs extract/eml.rs extract/html.rs extract/csv_x.rs extract/logs.rs extract/json.rs extract/txt.rs extract/unity.rs extract/xml_x.rs 2>/dev/null | grep -v \"#\\[cfg(test)\\]\" | head -50","description":"Scan extractors for panics"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1566,"cache_creation_input_tokens":0,"cache_read_input_tokens":145728,"output_tokens":725,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"115c2390-ff54-4bf9-8ca8-375c5a2094c7","timestamp":"2026-10-01T15:43:00.121Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"115c2390-ff54-4bf9-8ca8-375c5a2094c7","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_c0e9d728c9494cd59aab3faa","type":"tool_result","content":"extract/logs.rs:29: .unwrap(),\nextract/logs.rs:33: .unwrap(),\nextract/logs.rs:37: .unwrap(),\nextract/logs.rs:38: kv: Regex::new(r#\"\\b([A-Za-z_][A-Za-z0-9_.]*)=(\"(?:[^\"\\\\]|\\\\.)*\"|\\S+)\"#).unwrap(),\nextract/logs.rs:184: let k = c.get(1).unwrap().as_str().to_string();\nextract/logs.rs:185: let mut v = c.get(2).unwrap().as_str().to_string();\nextract/logs.rs:307: let m = parse_line(clf, Kind::Clf).unwrap();\nextract/logs.rs:313: let m = parse_line(app, Kind::App).unwrap();\nextract/logs.rs:367: let dir = tempfile::tempdir().unwrap();\nextract/logs.rs:379: std::fs::write(&path, &text).unwrap();\nextract/logs.rs:387: .unwrap();\nextract/logs.rs:399: let tail = recs[119].fields[\"message\"].as_str().unwrap();\nextract/eml.rs:660: let mut tmp = tempfile::Builder::new().suffix(\".eml\").tempfile().unwrap();\nextract/eml.rs:661: tmp.write_all(eml).unwrap();\nextract/eml.rs:667: extract(tmp.path(), false, &mut sink).unwrap();\nextract/eml.rs:703: let msg = recs.iter().find(|r| r.locator.starts_with(\"msg-\")).unwrap();\nextract/eml.rs:713: let subj = field(msg, \"email_subject\").unwrap();\nextract/eml.rs:719: let body = field(msg, \"body\").unwrap();\nextract/eml.rs:730: .unwrap();\nextract/eml.rs:740: let att_body = field(att, \"body\").unwrap();\nextract/eml.rs:793: .map(|r| field(r, \"body\").unwrap().to_string())\nextract/eml.rs:823: for bytes in [&b\"\"[..], b\"\\n\", b\"\\r\\n\", b\"\\r\\n\\r\\n\", b\" \\n\"] {\nextract/eml.rs:837: for bytes in [&b\"Subject: hello\\n\\n\"[..], b\"\\njust a body, no headers\\n\"] {\nextract/eml.rs:858: .unwrap()\nextract/eml.rs:860: .expect(\"the subject opens the body\")\nextract/eml.rs:913: let msg = recs.iter().find(|r| r.locator == \"msg-s0\").unwrap();\nextract/eml.rs:943: .unwrap();\nextract/eml.rs:997: let body = field(&recs[0], \"body\").unwrap();\nextract/eml.rs:1070: .unwrap();\nextract/mbox.rs:519: self.state.lock().expect(\"mbox gate poisoned\").1 = limit.max(1);\nextract/mbox.rs:524: self.state.lock().expect(\"mbox gate poisoned\").1\nextract/mbox.rs:528: let mut state = self.state.lock().expect(\"mbox gate poisoned\");\nextract/mbox.rs:530: state = self.ready.wait(state).expect(\"mbox gate poisoned\");\nextract/mbox.rs:541: let mut state = self.0.state.lock().expect(\"mbox gate poisoned\");\nextract/mbox.rs:567: let mut used = self.used.lock().expect(\"mbox budget poisoned\");\nextract/mbox.rs:569: used = self.freed.wait(used).expect(\"mbox budget poisoned\");\nextract/mbox.rs:575: let mut used = self.used.lock().expect(\"mbox budget poisoned\");\nextract/mbox.rs:612: let mut held = self.held.lock().expect(\"mbox lease poisoned\");\nextract/mbox.rs:618: let mut held = self.held.lock().expect(\"mbox lease poisoned\");\nextract/mbox.rs:902: while let Some(m) = s.next_message().unwrap() {\nextract/mbox.rs:919: .unwrap();\nextract/mbox.rs:1031: let text = String::from_utf8(out[0].bytes.clone()).unwrap();\nextract/mbox.rs:1073: let first = s.next_message().unwrap().unwrap();\nextract/mbox.rs:1076: assert!(s.next_message().unwrap().is_none());\nextract/mbox.rs:1077: assert!(s.next_message().unwrap().is_none(), \"stays finished\");\nextract/mbox.rs:1131: let first = split.next_message().unwrap().expect(\"the first message\");\nextract/mbox.rs:1138: let second = split.next_message().unwrap().expect(\"the second message\");\nextract/mbox.rs:1141: assert!(split.next_message().unwrap().is_none());\nextract/mbox.rs:1249: .map(|r| locator_offset(&r.locator).expect(\"every mbox record carries its offset\"))\nextract/mbox.rs:1344: .expect(\"declared latin-1 body is decoded, not dropped\");","is_error":false}]},"uuid":"f132131e-afe6-4eaa-98e4-27c9dfd20ab8","timestamp":"2026-10-01T15:43:00.192Z","sourceToolAssistantUUID":"115c2390-ff54-4bf9-8ca8-375c5a2094c7","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f132131e-afe6-4eaa-98e4-27c9dfd20ab8","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020257552568c40fee0544cc","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The extractors are largely clean (mostly test unwraps). `logs.rs:184-185` uses `c.get(1).unwrap()` on regex captures — safe since the capture groups are from a fixed regex that always participates.\n\nThe `_simulate` interpreter defaults `_source` to an object — so the interpreter path is safe-ish (`source` could be a non-object if `_source` is given as an array! `input.get(\"_source\").cloned().unwrap_or(Object)` — if `_source` is `[1,2,3]`, then source = Array. Then processors run on it. If the interpreter indexes `source[...]` → panic. Let me check how the interpreter applies processors. Let me grep in that function for indexing.\n\nGiven time constraints, let me focus: the compiled-pipeline panic is confirmed with concrete call chains. Let me do a quick check of the interpreter for the same pattern, then move to autoindex.\n\nActually — an important nuance for severity: does the ES-compat HTTP API require authentication? Let me check quickly. If the server requires an API key by default, the attack needs credentials. Still a valid DoS (any ingesting client can kill the node). Let me check the auth middleware quickly.\n\nThen let me spend the remaining effort on autoindex hostile-file parsing per the request: I've covered zip extraction (defended), symlink walk (defended), sniff (fine). Let me check `content.rs` (blob storage writes) and `harvest/httpget.rs` (download path → writes to `cache_dir.join(format!(\"{}.zip\", slug))` — slug is from the recipe, which is operator-supplied, not attacker). And `objsource.rs` fetch_one → writes object content to a temp path derived from object key? That could be a path traversal if the object key is used as a filename. Let me check objsource.rs fetch_one.\n\nLet me look at objsource.rs:805-920.","signature":"278a3a81da0d4679971e31f0"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"f64498e1-3662-4529-aae2-66b282b6a304","timestamp":"2026-10-01T15:43:15.334Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f64498e1-3662-4529-aae2-66b282b6a304","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020257552568c40fee0544cc","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_970405cbd49c4d8ea5658833","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && sed -n '780,900p' objsource.rs","description":"Read objsource fetch paths"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2391,"cache_creation_input_tokens":0,"cache_read_input_tokens":147264,"output_tokens":523,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"35664b9a-5fb4-490e-8feb-c37c6c5a0da4","timestamp":"2026-10-01T15:43:16.413Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"35664b9a-5fb4-490e-8feb-c37c6c5a0da4","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020257552568c40fee0544cc","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_7e0914bd538746c89b606e1a","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && grep -rn \"require_auth\\|api_key\\|Authorization\\|auth_middleware\" es_compat.rs | head -15","description":"Check API auth requirements"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":2391,"cache_creation_input_tokens":0,"cache_read_input_tokens":147264,"output_tokens":523,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"0817e1ae-c81d-46fd-b2ee-14a55165a788","timestamp":"2026-10-01T15:43:16.422Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"35664b9a-5fb4-490e-8feb-c37c6c5a0da4","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_970405cbd49c4d8ea5658833","type":"tool_result","content":" list_requests_class_a: report.list_requests,\n get_requests_class_b: report.read_requests,\n transfer_ms: report.elapsed_ms,\n });\n manifest.save(&run.manifest_path)?;\n Ok(report)\n}\n\n/// True when the mirror already holds this object's bytes at the right size.\nfn mirror_file_ready(mirror: &Path, rel: &str, size: u64) -> bool {\n std::fs::metadata(mirror.join(rel)).is_ok_and(|m| m.is_file() && m.len() == size)\n}\n\nenum FetchOutcome {\n Fetched { bytes: u64 },\n Vanished { rel: String },\n}\n\n/// Stream each pending object into the mirror.\n///\n/// A failure that is not \"the object is gone\" aborts the whole run. That is the\n/// safe direction and not a convenience: materialisation happens before anything\n/// is indexed, and skipping a failed download would present the object as\n/// deleted to the reconcile step, which would then delete its documents because\n/// of a transient 500.\nfn fetch_objects(\n run: &ObjectRun,\n source: &dyn DocSource,\n pending: &[&SourceEntry],\n pr: &Progress,\n concurrency: usize,\n checkpoint: &ManifestCheckpoint,\n) -> Result<Vec<FetchOutcome>> {\n if pending.is_empty() {\n return Ok(Vec::new());\n }\n let pool = rayon::ThreadPoolBuilder::new()\n .num_threads(concurrency)\n .thread_name(|i| format!(\"xerj-fetch-{i}\"))\n .build()\n .context(\"build the object-fetch pool\")?;\n let results: Vec<Result<FetchOutcome>> = pool.install(|| {\n use rayon::prelude::*;\n pending\n .par_iter()\n .map(|entry| {\n let guard = pr.file(&entry.rel, entry.size);\n let outcome = fetch_one(run, source, entry);\n drop(guard);\n // Recorded here, inside the pool, so the manifest knows about\n // an object the moment its bytes are installed — not only if\n // every other object also succeeds.\n if matches!(outcome, Ok(FetchOutcome::Fetched { .. })) {\n checkpoint.record(&entry.rel, ObjectRecord::for_entry(entry), pr);\n }\n outcome\n })\n .collect()\n });\n let mut outcomes = Vec::with_capacity(results.len());\n let mut failure: Option<anyhow::Error> = None;\n for result in results {\n match result {\n Ok(outcome) => outcomes.push(outcome),\n // Keep the first failure and keep draining: every other object in\n // this batch already succeeded or failed, and the successes must\n // reach the caller's checkpoint either way.\n Err(e) => failure = failure.or(Some(e)),\n }\n }\n match failure {\n Some(e) => Err(e),\n None => Ok(outcomes),\n }\n}\n\nfn fetch_one(run: &ObjectRun, source: &dyn DocSource, entry: &SourceEntry) -> Result<FetchOutcome> {\n let destination = run.mirror.join(&entry.rel);\n if let Some(parent) = destination.parent() {\n std::fs::create_dir_all(parent).with_context(|| {\n format!(\n \"create {} for object {}\",\n parent.display(),\n crate::progress::sanitize(&entry.rel, crate::progress::SAFE_PATH_MAX)\n )\n })?;\n }\n let mut reader = match source.open(entry) {\n Ok(reader) => reader,\n Err(e) if e.downcast_ref::<MissingObject>().is_some() => {\n return Ok(FetchOutcome::Vanished {\n rel: entry.rel.clone(),\n })\n }\n Err(e) => return Err(e),\n };\n // A temporary beside the destination, then an atomic rename: a killed run\n // must never leave a half-written object looking like a whole one, because\n // the next run's size check would accept it.\n let temp = destination.with_file_name(format!(\n \".{}.{}.part\",\n destination\n .file_name()\n .map(|n| n.to_string_lossy().to_string())\n .unwrap_or_else(|| \"object\".into()),\n std::process::id()\n ));\n let bytes = {\n let file =\n std::fs::File::create(&temp).with_context(|| format!(\"create {}\", temp.display()))?;\n let mut writer = std::io::BufWriter::with_capacity(COPY_BUFFER_BYTES, file);\n // `io::copy` with a bounded buffer: the object is never in memory whole,\n // whatever its size. This is the streaming guarantee, and it is why a\n // 1 GB object costs a flat few hundred kilobytes of RSS.\n let copied = std::io::copy(&mut reader, &mut writer).with_context(|| {\n format!(\n \"stream object {} into {}\",\n crate::progress::sanitize(&entry.rel, crate::progress::SAFE_PATH_MAX),\n temp.display()\n )\n })?;","is_error":false}]},"uuid":"4908c0db-3442-485b-a5c5-1fb9688e1729","timestamp":"2026-10-01T15:43:16.450Z","sourceToolAssistantUUID":"35664b9a-5fb4-490e-8feb-c37c6c5a0da4","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"0817e1ae-c81d-46fd-b2ee-14a55165a788","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_7e0914bd538746c89b606e1a","type":"tool_result","content":"es_compat.rs:36001:/// `_es_api_key` realm, `authentication_type: \"api_key\"`, and an `api_key:\nes_compat.rs:36012:/// to read `GET /_security/api_key` for the descriptors. xerj reports the\nes_compat.rs:36023:/// `POST /_security/api_key {\"role_descriptors\":{\"superuser\":{\"indices\":\nes_compat.rs:36065: // Unreachable behind `auth_middleware`, which answers 401 first — but\nes_compat.rs:36075: \"reason\": \"missing or invalid API key in Authorization header\"\nes_compat.rs:36078: \"reason\": \"missing or invalid API key in Authorization header\"\nes_compat.rs:36088: Some(_) => (API_KEY_REALM, API_KEY_REALM, \"api_key\"),\nes_compat.rs:36104: body[\"api_key\"] = json!({ \"id\": id, \"name\": name });\nes_compat.rs:36109:/// Name of a minted key, for the `api_key` block above. A key that vanished\nes_compat.rs:36115: .api_keys\nes_compat.rs:36144:const QUALIFIED_DESCRIPTOR_PREFIX: &str = \"api_key_role:\";\nes_compat.rs:36156:/// `api_key_role:superuser`, which is still the name the caller wrote (nothing\nes_compat.rs:36168:/// itself reserved: a caller may name a descriptor `api_key_role:superuser`\nes_compat.rs:36376:// POST /_security/api_key — create API key (stub: returns admin key)\nes_compat.rs:36379:pub async fn security_create_api_key(","is_error":false}]},"uuid":"f0180ba4-0897-4ffe-b909-859f72ae857c","timestamp":"2026-10-01T15:43:16.453Z","sourceToolAssistantUUID":"0817e1ae-c81d-46fd-b2ee-14a55165a788","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f0180ba4-0897-4ffe-b909-859f72ae857c","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025810e91051d5b6e44c84","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"**BIG finding**: `fetch_one` in objsource.rs:856-860:\n```rust\nlet destination = run.mirror.join(&entry.rel);\n```\n`entry.rel` comes from the object storage listing (S3/R2/MinIO object key). If the object key contains `../` (e.g. an S3 key named `../../etc/cron.d/evil` — S3 keys can contain any UTF-8 including `..`), then `mirror.join(\"../../x\")` escapes the mirror dir. Then `create_dir_all(parent)` and writes the object bytes there.\n\nThis is a real path traversal where the attacker controls the *object key* in a bucket — a corpus provider could upload objects with keys like `a/../../../../tmp/pwned`. This is the \"untrusted corpus provider\" threat model. Let me verify `entry.rel` origin and whether there's any sanitization. Let me check `SourceEntry` and how `rel` is populated, and whether there's a check like `mirror_file_ready` uses `mirror.join(rel)` too.\n\nLet me grep for sanitization of `rel` in objsource.rs.\n\nAlso the `.part` temp name uses `destination.file_name()`, fine.\n\nLet me check objsource.rs for how entries are built.","signature":"6a1ed1728e314d3ca6c07535"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"5c5a44c6-73ff-486d-bef2-1373133a1d6c","timestamp":"2026-10-01T15:43:28.298Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"5c5a44c6-73ff-486d-bef2-1373133a1d6c","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025810e91051d5b6e44c84","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_db10af50f26b45eaa0214ba1","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -n \"rel:\" objsource.rs | head -30; echo \"=== SourceEntry def ===\"; grep -rn \"struct SourceEntry\" -A 15 objsource.rs source.rs 2>/dev/null | head -30","description":"Find SourceEntry rel population"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1971,"cache_creation_input_tokens":0,"cache_read_input_tokens":149632,"output_tokens":427,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"f5be775a-c2a8-4506-876d-cd7130f98a61","timestamp":"2026-10-01T15:43:29.926Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f5be775a-c2a8-4506-876d-cd7130f98a61","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025810e91051d5b6e44c84","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_d9a9b974f44347b7b200f0f2","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -rn \"sanitize\\|normalize\\|\\.\\.\\|starts_with(\\\"\\.\\.\\|components()\" objsource.rs | head -30","description":"Check for path sanitization in objsource"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1971,"cache_creation_input_tokens":0,"cache_read_input_tokens":149632,"output_tokens":427,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"2e65e24b-3de6-49a7-a856-cc58234325e9","timestamp":"2026-10-01T15:43:29.983Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2e65e24b-3de6-49a7-a856-cc58234325e9","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_d9a9b974f44347b7b200f0f2","type":"tool_result","content":"objsource.rs:654: crate::progress::sanitize(&entry.rel, crate::progress::SAFE_PATH_MAX),\nobjsource.rs:655: crate::progress::sanitize(first, crate::progress::SAFE_PATH_MAX)\nobjsource.rs:832: if matches!(outcome, Ok(FetchOutcome::Fetched { .. })) {\nobjsource.rs:863: crate::progress::sanitize(&entry.rel, crate::progress::SAFE_PATH_MAX)\nobjsource.rs:897: crate::progress::sanitize(&entry.rel, crate::progress::SAFE_PATH_MAX),\nobjsource.rs:937: directories.sort_by_key(|p| std::cmp::Reverse(p.components().count()));\nobjsource.rs:1615: ..Default::default()","is_error":false}]},"uuid":"a6029ca4-9510-48eb-878b-e506db78fb43","timestamp":"2026-10-01T15:43:30.066Z","sourceToolAssistantUUID":"2e65e24b-3de6-49a7-a856-cc58234325e9","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f5be775a-c2a8-4506-876d-cd7130f98a61","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_db10af50f26b45eaa0214ba1","type":"tool_result","content":"315: fn record(&self, rel: &str, record: ObjectRecord, pr: &Progress) {\n789:fn mirror_file_ready(mirror: &Path, rel: &str, size: u64) -> bool {\n795: Vanished { rel: String },\n871: rel: entry.rel.clone(),\n1113: fn key_for(&self, rel: &str) -> String {\n1276: rel: rel.to_string(),\n=== SourceEntry def ===\nsource.rs:315:pub struct SourceEntry {\nsource.rs-316- /// Root-relative path with forward slashes — the `ax_path` value, and the\nsource.rs-317- /// path inside the local mirror for an object source.\nsource.rs-318- pub rel: String,\nsource.rs-319- pub size: u64,\nsource.rs-320- /// An opaque token that changes when the bytes change, if the source can\nsource.rs-321- /// answer cheaply. `None` means it cannot, and the bytes decide.\nsource.rs-322- ///\nsource.rs-323- /// For an object store this is built from the ETag and the size; see\nsource.rs-324- /// [`crate::objsource::change_token`] for what is and is not assumed about\nsource.rs-325- /// an ETag. A local folder returns `None`: the walk's own answer is a full\nsource.rs-326- /// content hash, because file metadata cannot prove byte identity across\nsource.rs-327- /// every filesystem XERJ runs on.\nsource.rs-328- pub change_token: Option<String>,\nsource.rs-329- /// RFC 3339 last-modified, when the source reports one. Recorded for the\nsource.rs-330- /// operator; never used as change identity on its own unless there is no","is_error":false}]},"uuid":"cea8ce23-dea2-46b7-a090-c9d05897b51c","timestamp":"2026-10-01T15:43:30.078Z","sourceToolAssistantUUID":"f5be775a-c2a8-4506-876d-cd7130f98a61","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"cea8ce23-dea2-46b7-a090-c9d05897b51c","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020258239898b826f3554dcb","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"`crate::progress::sanitize` is only used for LOG MESSAGE escaping, not for the actual path. The actual write path is `run.mirror.join(&entry.rel)` at line 856 — unsanitized.\n\nNow let's find where `rel` is populated from object keys (line 1276 in objsource.rs). Let me read around 1240-1300.\n\nLet me also verify that `entry.rel` for S3 is the raw object key.","signature":"aa6da49653b74be1bcf98d15"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"c34235f7-870f-4d2f-9391-5fca5e7529ba","timestamp":"2026-10-01T15:43:36.953Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c34235f7-870f-4d2f-9391-5fca5e7529ba","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020258239898b826f3554dcb","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_18ae16b1ba264070b5dbabec","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && sed -n '1230,1300p' objsource.rs","description":"Read object listing to SourceEntry mapping"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"2a780cb1-4879-4c67-b96e-36098d0a16aa","timestamp":"2026-10-01T15:43:38.882Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2a780cb1-4879-4c67-b96e-36098d0a16aa","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_18ae16b1ba264070b5dbabec","type":"tool_result","content":" let mut listing = SourceListing::default();\n let mut continuation: Option<String> = None;\n let mut pages = 0u64;\n loop {\n pages += 1;\n if pages > MAX_LIST_PAGES {\n bail!(\n \"{} holds more than {} objects ({} LIST requests and counting). Refusing to \\\n continue: that is 1% of a 1,000,000/month free class-A allowance in one run, \\\n and the mirror would need the disk for all of it. Point the run at a narrower \\\n prefix\",\n self.spec.identity(),\n MAX_LIST_PAGES * LIST_PAGE_KEYS as u64,\n MAX_LIST_PAGES\n );\n }\n let prefix = (!self.spec.prefix.is_empty()).then(|| self.spec.prefix.clone());\n // `charged` counts every wire attempt, including the retries the\n // store makes us pay for, and counts them before they are sent.\n let page = self.charged(&self.list_requests, \"list\", None, || {\n self.runtime\n .block_on(\n self.client\n .list_objects_v2()\n .bucket(&self.spec.bucket)\n .set_prefix(prefix.clone())\n .max_keys(LIST_PAGE_KEYS)\n .set_continuation_token(continuation.clone())\n .send(),\n )\n .map_err(Box::new)\n })?;\n for object in page.contents() {\n let Some(key) = object.key() else { continue };\n listing.seen += 1;\n let rel = key.strip_prefix(self.spec.prefix.as_str()).unwrap_or(key);\n match classify_key(rel) {\n KeyVerdict::Skip(rule) => {\n *listing.skipped.entry(rule.to_string()).or_default() += 1;\n }\n KeyVerdict::Admit => {\n let size = object.size().unwrap_or(0).max(0) as u64;\n let last_modified = object.last_modified().and_then(|t| {\n t.fmt(aws_sdk_s3::primitives::DateTimeFormat::DateTime).ok()\n });\n listing.entries.push(SourceEntry {\n rel: rel.to_string(),\n size,\n change_token: change_token(\n object.e_tag(),\n size,\n last_modified.as_deref(),\n ),\n last_modified,\n });\n }\n }\n }\n let truncated = page.is_truncated().unwrap_or(false);\n continuation = page.next_continuation_token().map(str::to_string);\n if !truncated || continuation.is_none() {\n break;\n }\n }\n Ok(listing)\n }\n\n fn open(&self, entry: &SourceEntry) -> Result<Box<dyn Read + Send>> {\n let key = self.key_for(&entry.rel);\n let output = self.charged(&self.read_requests, \"get\", Some(&key), || {\n self.runtime","is_error":false}]},"uuid":"02f85aed-9350-4c4d-b8c3-2f16dbe6cba8","timestamp":"2026-10-01T15:43:38.908Z","sourceToolAssistantUUID":"2a780cb1-4879-4c67-b96e-36098d0a16aa","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"02f85aed-9350-4c4d-b8c3-2f16dbe6cba8","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020258239898b826f3554dcb","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_ac9a0842b3d84aab8c1600c0","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -rn \"fn list\\|key\\b\\|prefix\" objsource.rs | grep -n \"fn \\|=> SourceEntry\\|rel\" | head -20; echo \"=== DocSource impls ===\"; grep -rn \"impl DocSource\\|fn entries\" source.rs objsource.rs | head -20","description":"Find DocSource entries implementations"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1057,"cache_creation_input_tokens":0,"cache_read_input_tokens":151552,"output_tokens":259,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"c6eeb18a-79e0-4a05-a2a3-df6aa7486373","timestamp":"2026-10-01T15:43:39.645Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c6eeb18a-79e0-4a05-a2a3-df6aa7486373","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_ac9a0842b3d84aab8c1600c0","type":"tool_result","content":"13:objsource.rs:926: let Ok(rel) = path.strip_prefix(mirror) else {\n16:objsource.rs:1114: format!(\"{}{}\", self.spec.prefix, rel)\n19:objsource.rs:1229: fn list(&self) -> Result<SourceListing> {\n24:objsource.rs:1265: let rel = key.strip_prefix(self.spec.prefix.as_str()).unwrap_or(key);\n25:objsource.rs:1266: match classify_key(rel) {\n26:objsource.rs:1298: let key = self.key_for(&entry.rel);\n=== DocSource impls ===\nobjsource.rs:1224:impl DocSource for ObjectStoreSource {\nsource.rs:418:impl DocSource for LocalDirSource {","is_error":false}]},"uuid":"5fd80971-3237-464c-b1a4-79743832ac1d","timestamp":"2026-10-01T15:43:39.699Z","sourceToolAssistantUUID":"c6eeb18a-79e0-4a05-a2a3-df6aa7486373","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"5fd80971-3237-464c-b1a4-79743832ac1d","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025832178ca4b4303346bb","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"CONFIRMED: `rel = key.strip_prefix(prefix).unwrap_or(key)` — the raw S3 object key, no component sanitization. Then `fetch_one` does `run.mirror.join(&entry.rel)` → `create_dir_all(parent)` → `File::create(temp)` → `rename` to destination.\n\nAttack: a corpus provider with write access to a bucket (or a compromised bucket) uploads an object with key `x/../../../../tmp/evil` (or `..%2F..%2F`), and when the operator runs `xerj autoindex --s3 bucket/prefix`, the object's contents are written to `/tmp/evil` (outside the mirror dir). That's arbitrary file write with attacker-controlled bytes (object body), limited by filename constraints.\n\nWait: `Path::join` with an absolute path replaces the whole path. `mirror.join(\"/etc/passwd\")` → `/etc/passwd`. And S3 keys CAN start with `/` (a key named `/etc/cron.d/x` is legal in S3, though unusual; the prefix strip could yield `/etc/...`). Also `../` traversal works: a key `a/../../tmp/p` → `mirror/a/../../tmp/p` → parent dir traversal.\n\nDoes `classify_key` reject `..`? Let me check `classify_key` — it's about ignore rules for keys. Let me check it to see if it would skip such keys. Let me grep.\n\nAlso check whether the same `rel` is used for reading back (objsource.rs:926 `path.strip_prefix(mirror)`).\n\nLet me check classify_key and KeyVerdict.\n\nAlso I should double check the local dir source: `LocalDirSource` (source.rs:418) rel comes from the walk with `strip_prefix(root_canon)` so it's safe.\n\nLet me check classify_key.","signature":"fc2960f6635a44a59d009379"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1140,"cache_creation_input_tokens":0,"cache_read_input_tokens":152576,"output_tokens":451,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"3b21f4e6-0e4b-4984-ad68-3fb231bd9a43","timestamp":"2026-10-01T15:43:56.947Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"3b21f4e6-0e4b-4984-ad68-3fb231bd9a43","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025832178ca4b4303346bb","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_dfa320ab95f441388d117a14","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -n \"fn classify_key\" -B 20 -A 40 objsource.rs | head -80","description":"Read classify_key"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1140,"cache_creation_input_tokens":0,"cache_read_input_tokens":152576,"output_tokens":451,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"f3d20777-b5ae-42a3-b910-3b28a446b4c9","timestamp":"2026-10-01T15:43:56.949Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f3d20777-b5ae-42a3-b910-3b28a446b4c9","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_dfa320ab95f441388d117a14","type":"tool_result","content":"(Bash completed with no output)","is_error":false}]},"uuid":"100f054c-32a5-4ee0-957b-a3c1916e274e","timestamp":"2026-10-01T15:43:56.978Z","sourceToolAssistantUUID":"f3d20777-b5ae-42a3-b910-3b28a446b4c9","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"100f054c-32a5-4ee0-957b-a3c1916e274e","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025848096b43450fe14c49","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_7e6af54f53cc466280063af4","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -rn \"classify_key\\|KeyVerdict\" *.rs | head -10","description":"Locate classify_key definition"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":514,"cache_creation_input_tokens":0,"cache_read_input_tokens":153664,"output_tokens":59,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"de64ea0c-f6d6-44bf-a038-8a7fcca2ec01","timestamp":"2026-10-01T15:44:04.206Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"de64ea0c-f6d6-44bf-a038-8a7fcca2ec01","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_7e6af54f53cc466280063af4","type":"tool_result","content":"objsource.rs:52: classify_key, rules, DocSource, KeyVerdict, ObjectScheme, ObjectSpec, SourceEntry,\nobjsource.rs:1266: match classify_key(rel) {\nobjsource.rs:1267: KeyVerdict::Skip(rule) => {\nobjsource.rs:1270: KeyVerdict::Admit => {\nsource.rs:203: /// See [`super::classify_key`] for the exact list.\nsource.rs:213:pub enum KeyVerdict {\nsource.rs:257:pub fn classify_key(rel: &str) -> KeyVerdict {\nsource.rs:259: return KeyVerdict::Skip(rules::FOLDER_MARKER);\nsource.rs:262: return KeyVerdict::Skip(rules::UNSAFE_KEY);\nsource.rs:265: return KeyVerdict::Skip(rules::UNSAFE_KEY);","is_error":false}]},"uuid":"2f78aacd-6bbc-452b-bd45-6fbc41ffeed6","timestamp":"2026-10-01T15:44:04.245Z","sourceToolAssistantUUID":"de64ea0c-f6d6-44bf-a038-8a7fcca2ec01","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"2f78aacd-6bbc-452b-bd45-6fbc41ffeed6","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020258555649ccb5bbee4c47","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_00e7b804537545aea0eceae2","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && sed -n '195,300p' source.rs","description":"Read classify_key and unsafe key rules"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":247,"cache_creation_input_tokens":0,"cache_read_input_tokens":154176,"output_tokens":54,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"21c30fea-df90-412e-a81b-d62f993b7eaa","timestamp":"2026-10-01T15:44:11.841Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"21c30fea-df90-412e-a81b-d62f993b7eaa","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_00e7b804537545aea0eceae2","type":"tool_result","content":"/// one answer shape for both kinds of source.\n///\n/// A key that is skipped is never downloaded, so a skip is also money not spent.\npub mod rules {\n /// The key names the prefix itself, or ends in `/`: a folder marker, not a\n /// document. Every S3 console creates these.\n pub const FOLDER_MARKER: &str = \"object:folder-marker\";\n /// The key cannot be represented as a relative path safely or portably.\n /// See [`super::classify_key`] for the exact list.\n pub const UNSAFE_KEY: &str = \"object:unsafe-key\";\n /// Two keys differ only in case, so they would be one file on a\n /// case-insensitive filesystem (macOS, Windows) and each run would\n /// overwrite the other.\n pub const CASE_COLLISION: &str = \"object:case-collision\";\n}\n\n/// The verdict on one listed key, already stripped of the listing prefix.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum KeyVerdict {\n /// Admitted as a candidate document with this root-relative path.\n Admit,\n /// Not a candidate, for the named rule.\n Skip(&'static str),\n}\n\n/// Longest single path component we will create. 255 bytes is the limit on\n/// ext4, APFS and NTFS alike; a longer component would fail at `create_dir`\n/// halfway through a run instead of being reported up front.\nconst MAX_COMPONENT_BYTES: usize = 255;\n\n/// Basenames Windows cannot create, whatever the extension.\nconst WINDOWS_RESERVED: &[&str] = &[\n \"con\", \"prn\", \"aux\", \"nul\", \"com1\", \"com2\", \"com3\", \"com4\", \"com5\", \"com6\", \"com7\", \"com8\",\n \"com9\", \"lpt1\", \"lpt2\", \"lpt3\", \"lpt4\", \"lpt5\", \"lpt6\", \"lpt7\", \"lpt8\", \"lpt9\",\n];\n\n/// Decide whether a prefix-stripped key can become a document.\n///\n/// An object key is an arbitrary UTF-8 string, not a path: `../../etc/passwd`,\n/// `a//b`, `a\\b`, a trailing dot and a 4 KB component are all legal keys. They\n/// become a local path here, so each one is a decision rather than an accident:\n///\n/// - **`..`, `.`, an empty component, a leading `/`** — refused. A key that\n/// escapes the mirror directory is the classic object-store traversal, and\n/// `a//b` is a different key from `a/b` while being the same path.\n/// - **A backslash** — refused. It is an ordinary character in a key and a\n/// directory separator on Windows, so admitting it would index a different\n/// set of documents per platform.\n/// - **Control characters** — refused. They forge lines in the progress stream\n/// (the #278 class) and are unrepresentable in half the tooling downstream.\n/// - **A trailing `.` or space, or a Windows reserved basename** — refused\n/// EVERYWHERE, not only on Windows, so one bucket produces one corpus\n/// whatever machine indexes it. The report names the rule, so a refused key\n/// is visible rather than silently missing.\n/// - **A hidden (dot-prefixed) component** — skipped under\n/// [`crate::ignore_rules::HIDDEN_RULE`], the same rule the walker applies at\n/// depth > 0, and for the same reason: `.env`, `.git/config` and `.ssh/id_rsa`\n/// live in buckets too, and \"index this bucket\" is not consent to publish\n/// them into a queryable index. The two ignore FILES are the exception —\n/// `.gitignore` and `.xerjignore` are fetched so the bucket's own ignore\n/// rules still apply to it, and the walker then declines to index them\n/// because of this same rule.\npub fn classify_key(rel: &str) -> KeyVerdict {\n if rel.is_empty() || rel.ends_with('/') {\n return KeyVerdict::Skip(rules::FOLDER_MARKER);\n }\n if rel.starts_with('/') || rel.contains('\\\\') {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n if rel.chars().any(|c| c.is_control()) {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n let components: Vec<&str> = rel.split('/').collect();\n let last = components.len() - 1;\n for (index, component) in components.iter().enumerate() {\n if component.is_empty() || *component == \".\" || *component == \"..\" {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n if component.len() > MAX_COMPONENT_BYTES {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n if component.ends_with('.') || component.ends_with(' ') || component.starts_with(' ') {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n let stem = component.split('.').next().unwrap_or(component);\n if WINDOWS_RESERVED\n .iter()\n .any(|reserved| stem.eq_ignore_ascii_case(reserved))\n {\n return KeyVerdict::Skip(rules::UNSAFE_KEY);\n }\n if component.starts_with('.') {\n let is_ignore_file = index == last\n && (*component == crate::ignore_rules::GITIGNORE\n || *component == crate::ignore_rules::XERJIGNORE);\n if !is_ignore_file {\n return KeyVerdict::Skip(crate::ignore_rules::HIDDEN_RULE);\n }\n }\n }\n // The built-in build-output defaults, applied here as well as in the walk.\n // Same list, so the two can never drift; applying it early means a bucket\n // full of `node_modules/` costs no GET requests instead of costing them and\n // then being thrown away by the walker.\n if crate::ignore_rules::DEFAULT_IGNORE_PATTERNS\n .iter()","is_error":false}]},"uuid":"6ae39406-9d24-4c74-96db-61d1b0b2b499","timestamp":"2026-10-01T15:44:11.882Z","sourceToolAssistantUUID":"21c30fea-df90-412e-a81b-d62f993b7eaa","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6ae39406-9d24-4c74-96db-61d1b0b2b499","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202590147d2e4e825fd4405","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"`classify_key` refuses `..`, `.`, empty components, leading `/`, backslash, control chars, etc. So the objsource mirror path is defended — as long as `classify_key` is applied on every path that builds `SourceEntry`. Let me verify: is `classify_key` applied everywhere entries are created (R2/MinIO variants use the same `list` impl? Line 1276 is inside `ObjectStoreSource::list`, which covers S3/R2/MinIO presumably).\n\nBut note: the manifest/checkpoint records `rel` and re-loads it on resume. If a manifest from a previous run is trusted... the manifest is written by the tool itself. Also `mirror_file_ready(mirror, rel, size)` joins again — same protected rel.\n\nOK. So objsource is defended. Good — that's a properly hardened area. Worth mentioning as \"checked, defended\" in the report.\n\nNow, back to the highest-value items. Let me now double-check the panic finding once more and look for other panic paths in builtins/pipeline. Also check whether the `index` API validates object-ness further downstream — irrelevant since the panic happens in the pipeline before that.\n\nOne more thing to check for the panic: is the ES-compat API actually exposed without auth by default? Let me quickly check the server router and auth middleware. If auth is required, the finding is still valid (authenticated DoS) but less severe. Let me check.\n\nAlso, I should check the `_msearch`/search path at es_compat.rs:23864 `process_through_pipeline(p, vec![hit.source])` — this applies a pipeline to search results. If `hit.source` is a non-object (possible if a doc was stored as a non-object via the `create` bulk path!), that's a panic too. Interesting: stored docs. Let me check how docs are stored — if `create` with array body can be stored as an array, then any search hit rendered through a search pipeline panics.\n\nActually — let me check whether the create-with-array doc gets indexed successfully at all. In the per-item loop, after the pipeline (which panics for most stages), for `create` without a pipeline... Let me check what happens: doc_body = Some(Array) → then validation at 1857 `if let Some(body) = doc_body.as_mut().and_then(|v| v.as_object_mut())` skips → then indexing. Would it store an array? Possibly. That's a secondary finding.\n\nLet me focus and check auth quickly, then verify the create-path storage.\n\nActually, time is limited. Let me prioritize:\n1. Confirm auth posture (quick grep for middleware in server router).\n2. Check the `create` non-object storage quickly.\n3. Do a final sweep of autoindex for any remaining panic-from-bytes (e.g., `code.rs` tree-sitter, `html.rs`).\n\nLet me run these in parallel.","signature":"5f3b30c897db4c4f89c6b4f1"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"20bec834-9dc5-4e94-93cc-d2a2eb64b808","timestamp":"2026-10-01T15:44:40.126Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"20bec834-9dc5-4e94-93cc-d2a2eb64b808","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202590147d2e4e825fd4405","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_0aa2c491a1314d78b289b468","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-server/src && grep -rn \"auth_middleware\\|require_api_key\\|layer(\" main.rs 2>/dev/null | head -20; ls","description":"Check server auth middleware wiring"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"9a92cb39-9676-426f-be5f-7f51ff102722","timestamp":"2026-10-01T15:44:40.129Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"9a92cb39-9676-426f-be5f-7f51ff102722","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_0aa2c491a1314d78b289b468","type":"tool_result","content":"brain.rs\ndebug_profiling.rs\ngrpc.rs\ningest_memory_trace.rs\nmain.rs\nshare.rs","is_error":false}]},"uuid":"a83e783d-aada-4b74-91ee-e5c99cc2c3be","timestamp":"2026-10-01T15:44:40.183Z","sourceToolAssistantUUID":"9a92cb39-9676-426f-be5f-7f51ff102722","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a83e783d-aada-4b74-91ee-e5c99cc2c3be","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100202590147d2e4e825fd4405","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_7ce3c8b853a24ad0a664068f","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && grep -nE \"\\bget\\(0\\)|\\[0\\]\\[|\\[i\\]|\\[idx\\]|\\[n\\]|\\[len|\\[pos|\\[off|chars\\(\\)\\.nth|\\.take\\([a-z_]+\\)\\.collect|from_utf8\\(\" code.rs html.rs csv_x.rs | head -30","description":"Scan code/html/csv extractors for indexing"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1428,"cache_creation_input_tokens":0,"cache_read_input_tokens":154368,"output_tokens":801,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"52eee965-ea0e-434a-bc84-64598b97d0f5","timestamp":"2026-10-01T15:44:43.564Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"52eee965-ea0e-434a-bc84-64598b97d0f5","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_7ce3c8b853a24ad0a664068f","type":"tool_result","content":"html.rs:146: &doc.tables[i],\nhtml.rs:207: if bytes[i] == b'<' {\ncode.rs:847: let cut: String = text.chars().take(cap).collect();","is_error":false}]},"uuid":"7ddcd7a9-805d-428b-83c4-5257020f7647","timestamp":"2026-10-01T15:44:43.592Z","sourceToolAssistantUUID":"52eee965-ea0e-434a-bc84-64598b97d0f5","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7ddcd7a9-805d-428b-83c4-5257020f7647","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025931857104d010f443b5","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_b274d392d0a3457bb19f76c9","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-server/src && grep -n \"auth\\|middleware\\|api_key\" main.rs | head -25","description":"Grep main.rs for auth wiring"}}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"55dcb4eb-c551-4b9b-b16b-dc72bc95a227","timestamp":"2026-10-01T15:44:51.524Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"55dcb4eb-c551-4b9b-b16b-dc72bc95a227","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_b274d392d0a3457bb19f76c9","type":"tool_result","content":"252: --insecure, -k Disable TLS *and* API-key authentication — local dev only.\\n\\\n519: if !cfg.auth.enabled {\n655: warn!(\"--insecure: TLS and auth disabled\");\n657: cfg.auth.enabled = false;\n810: if !cfg.auth.enabled || !cfg.auth.admin_api_key.is_empty() {\n828: cfg.auth.admin_api_key = existing.to_string();\n855: cfg.auth.admin_api_key = key;\n1086:/// peer. That is what the console's per-IP auth rate limiter keys on — it used\n1336: cfg.auth.enabled = false;\n1844:/// the axum accept/route frames, the two-layer authorization middleware\n1850:/// and the authz layer now competes for it. At 4 MiB the headroom is ~2.80 MiB\n1851:/// (4,194,304 − 1,262,320 = 2,931,984 bytes), which absorbs the middleware and\n1860:/// below the axum + authz + by-query + search frames, fails to compile.\n1869: // it (axum + authz middleware + by-query handler + search + segment scan).\n1890: /// `--insecure` disables TLS **and** auth (see `apply_overrides`, which\n1891: /// sets `cfg.tls.enabled = false; cfg.auth.enabled = false;`), but the\n1897: fn insecure_help_documents_auth_not_just_tls() {\n1927: para.contains(\"auth\"),\n1928: \"--insecure disables authentication too and the help must say so, got:\\n{para}\"\n2450: // unauthenticated, so refuse to start rather than open it. This must\n2453: let secret_material = cfg.cluster.effective_auth_secret().ok_or_else(|| {\n2455: \"cluster.enabled = true but no cluster auth secret is configured: set \\\n2456: cluster.auth_secret or {}. Refusing to start an unauthenticated cluster \\\n2462: .context(\"cluster auth secret rejected\")?;\n2624: // entirely and keys the auth rate limiter on the TCP peer. `validate()`","is_error":false}]},"uuid":"7774eaf9-5a00-4acc-9d0f-c78d9e48eec8","timestamp":"2026-10-01T15:44:51.547Z","sourceToolAssistantUUID":"55dcb4eb-c551-4b9b-b16b-dc72bc95a227","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7774eaf9-5a00-4acc-9d0f-c78d9e48eec8","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025931857104d010f443b5","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_de9b46a26f4845278931214f","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && sed -n '130,155p' html.rs && echo \"=== 195-215 ===\" && sed -n '195,215p' html.rs","description":"Inspect html.rs indexing sites"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":895,"cache_creation_input_tokens":0,"cache_read_input_tokens":155776,"output_tokens":135,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"c26f12d8-4464-4eec-b2fe-f4e14170514e","timestamp":"2026-10-01T15:44:51.960Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c26f12d8-4464-4eec-b2fe-f4e14170514e","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_de9b46a26f4845278931214f","type":"tool_result","content":" if w < 2 {\n continue;\n }\n let consistent = rows.iter().filter(|r| r.len() == w).count();\n if consistent * 10 < rows.len() * 9 {\n continue;\n }\n if best\n .map(|b| rows.len() > doc.tables[b].len())\n .unwrap_or(true)\n {\n best = Some(i);\n }\n }\n best.map(|i| {\n (\n &doc.tables[i],\n doc.header_cells\n .get(i)\n .and_then(|h| h.first())\n .copied()\n .unwrap_or(false),\n )\n })\n}\n\n=== 195-215 ===\n doc.headings.push(t.clone());\n doc.body.push_str(&t);\n doc.body.push_str(\"\\n\\n\");\n }\n _ => {\n doc.body.push_str(&t);\n doc.body.push(' ');\n }\n }\n };\n\n while i < bytes.len() {\n if bytes[i] == b'<' {\n // comment?\n if html[i..].starts_with(\"<!--\") {\n i = html[i..]\n .find(\"-->\")\n .map(|p| i + p + 3)\n .unwrap_or(bytes.len());\n continue;\n }","is_error":false}]},"uuid":"d43d4b3b-7e9c-481b-a263-d009aaf361d3","timestamp":"2026-10-01T15:44:51.986Z","sourceToolAssistantUUID":"c26f12d8-4464-4eec-b2fe-f4e14170514e","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d43d4b3b-7e9c-481b-a263-d009aaf361d3","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020259392916cfc3b32d4294","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"html.rs:207 `bytes[i] == b'<'` — `i` is a byte index and `bytes` is the file bytes; `html` is the decoded string. If the decode is windows-1252 (1 byte = 1 char), indices align. If UTF-8 lossy, multi-byte chars could make `html[i..]` panic (not a char boundary) while `bytes[i]` is fine! Let's check how html/html bytes are obtained. Let me look at the top of that function and how `i` advances. `html[i..]` with `i` pointing mid-UTF-8-char → panic \"byte index N is not a char boundary\".\n\nBut wait: the earlier `if bytes[i] == b'<'` check means i only enters the HTML-parsing branch when bytes[i] is ASCII `<`. If bytes is the raw UTF-8 file and html is its lossy decode, byte index of an ASCII byte is always a char boundary in the decoded string (since UTF-8 lossy decoding preserves byte positions for valid sequences; replacement chars are 1 byte each). Actually with `String::from_utf8_lossy`, invalid sequences become U+FFFD (3 bytes) — that SHIFTS indices! E.g., an invalid 2-byte sequence → one 3-byte replacement char, so positions after it shift by +1. Then `bytes[i] == b'<'` at a shifted index and `html[i..]` would be at a different position, and could be a non-boundary → panic.\n\nHmm, but is `html` derived from `bytes` via from_utf8_lossy? Let's look at the function signature and how they're produced. Let me read html.rs extract fn start.\n\nLet me check lines 1-130 and the loop through 215-330 to see the index handling.","signature":"7cb3b6f1d61d4b8f99a43293"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":950,"cache_creation_input_tokens":0,"cache_read_input_tokens":156608,"output_tokens":444,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"6cf93e04-719b-466c-ad01-224e8cd0a936","timestamp":"2026-10-01T15:45:12.243Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6cf93e04-719b-466c-ad01-224e8cd0a936","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020259392916cfc3b32d4294","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_bba5c69aebb74ef2a9825082","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && sed -n '1,130p' html.rs","description":"Read html.rs extraction entry"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":950,"cache_creation_input_tokens":0,"cache_read_input_tokens":156608,"output_tokens":444,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"6363495a-53ae-41d4-b647-7a0da257312a","timestamp":"2026-10-01T15:45:12.246Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6363495a-53ae-41d4-b647-7a0da257312a","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_bba5c69aebb74ef2a9825082","type":"tool_result","content":"//! HTML — a tolerant hand-rolled tokenizer (no DOM dependency; bounded by a\n//! 64MB whole-file cap). Generic extraction rule, no hardcoded names:\n//! a dominant `<table>` (≥5 rows, consistent column count, header row) →\n//! one record per row with header-derived field names; otherwise one\n//! document record {title, headings, body}.\n\nuse super::{\n emit_document, sanitize_field_name, ExtractStats, FieldOrigin, RawRecord, Sink,\n MAX_RECORDS_PER_FILE, MAX_WHOLE_FILE,\n};\nuse anyhow::Result;\nuse serde_json::{Map, Value};\nuse std::path::Path;\n\n#[derive(Default)]\nstruct Doc {\n title: String,\n headings: Vec<String>,\n body: String,\n tables: Vec<Vec<Vec<String>>>, // tables → rows → cells\n header_cells: Vec<Vec<bool>>, // per table: was first row <th>?\n}\n\npub fn extract(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {\n let mut stats = ExtractStats::default();\n let Some(bytes) = super::read_whole(path, gzip, MAX_WHOLE_FILE)? else {\n stats.junk += 1;\n return Ok(stats);\n };\n let (text, _) = crate::sniff::decode_text(&bytes);\n let doc = parse(&text);\n\n // Dominant-table rule.\n if let Some((rows, first_row_th)) = dominant_table(&doc) {\n let header: Vec<String> = {\n let mut seen = std::collections::HashSet::new();\n rows[0]\n .iter()\n .enumerate()\n .map(|(i, h)| {\n let mut name = if first_row_th || looks_like_header(&rows[0]) {\n sanitize_field_name(h)\n } else {\n format!(\"col_{}\", i + 1)\n };\n while !seen.insert(name.clone()) {\n name.push('2');\n }\n name\n })\n .collect()\n };\n let data_rows: Box<dyn Iterator<Item = (usize, &Vec<String>)>> =\n if first_row_th || looks_like_header(&rows[0]) {\n Box::new(rows.iter().enumerate().skip(1))\n } else {\n Box::new(rows.iter().enumerate())\n };\n for (i, row) in data_rows {\n let mut fields = Map::new();\n for (j, cell) in row.iter().enumerate() {\n if cell.trim().is_empty() {\n continue;\n }\n let name = header\n .get(j)\n .cloned()\n .unwrap_or_else(|| format!(\"col_{}\", j + 1));\n fields.insert(name, Value::String(cell.trim().to_string()));\n }\n if fields.is_empty() {\n continue;\n }\n stats.records += 1;\n if !sink(RawRecord {\n fields,\n locator: format!(\"row{i}\"),\n group: None,\n origin: FieldOrigin::Data,\n }) {\n return Ok(stats);\n }\n }\n return Ok(stats);\n }\n\n // Document record.\n let title = if doc.title.trim().is_empty() {\n doc.headings\n .first()\n .cloned()\n .unwrap_or_else(|| stem_of(path))\n } else {\n doc.title.trim().to_string()\n };\n emit_document(\n &title,\n &doc.headings,\n doc.body.trim(),\n MAX_RECORDS_PER_FILE,\n sink,\n &mut stats,\n );\n Ok(stats)\n}\n\nfn stem_of(path: &Path) -> String {\n path.file_stem()\n .map(|s| s.to_string_lossy().to_string())\n .unwrap_or_else(|| \"untitled\".into())\n}\n\nfn looks_like_header(row: &[String]) -> bool {\n let numericish = |s: &str| {\n let t = s.trim();\n !t.is_empty()\n && t.chars()\n .all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | '-'))\n };\n !row.is_empty() && row.iter().all(|c| !numericish(c) && !c.trim().is_empty())\n}\n\nfn dominant_table(doc: &Doc) -> Option<(&Vec<Vec<String>>, bool)> {\n let mut best: Option<usize> = None;\n for (i, rows) in doc.tables.iter().enumerate() {\n if rows.len() < 5 {\n continue;\n }\n let w = rows[0].len();\n if w < 2 {","is_error":false}]},"uuid":"6a88d50a-be2a-4b17-81ef-15e6113caba7","timestamp":"2026-10-01T15:45:12.266Z","sourceToolAssistantUUID":"6363495a-53ae-41d4-b647-7a0da257312a","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"6a88d50a-be2a-4b17-81ef-15e6113caba7","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025957700dba9366114fa1","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"In `extract`, `let (text, _) = crate::sniff::decode_text(&bytes); let doc = parse(&text);` — so `parse` receives the decoded `&str` (text). Let's check `parse`'s signature and how `bytes`/`html` are set inside `parse`. Let me read parse (around line 170-260).\n\nIf `parse(text: &str)` does `let bytes = text.as_bytes(); let html = text;` then bytes and html are the SAME string, so `bytes[i] == b'<'` implies `html[i..]` is at a char boundary (ASCII byte at index i in a &str is always a boundary). So no panic. Good — need to verify.","signature":"9ac8d15bf2c04da89e5b288b"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1472,"cache_creation_input_tokens":0,"cache_read_input_tokens":157504,"output_tokens":212,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"76a2f6c1-1ee7-4feb-aeed-318a22cb825b","timestamp":"2026-10-01T15:45:24.033Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"76a2f6c1-1ee7-4feb-aeed-318a22cb825b","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002025957700dba9366114fa1","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_628987aafb2f4f61ac2bf528","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && sed -n '163,200p' html.rs","description":"Read html parse signature"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1472,"cache_creation_input_tokens":0,"cache_read_input_tokens":157504,"output_tokens":212,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"1167b08d-68c9-4313-a4db-03446a3b8548","timestamp":"2026-10-01T15:45:24.035Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"1167b08d-68c9-4313-a4db-03446a3b8548","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_628987aafb2f4f61ac2bf528","type":"tool_result","content":" // table state\n let mut in_table = false;\n let mut cur_table: Vec<Vec<String>> = Vec::new();\n let mut cur_row: Vec<String> = Vec::new();\n let mut cur_cell: Option<String> = None;\n let mut cur_row_th: Vec<bool> = Vec::new();\n let mut table_header_flags: Vec<bool> = Vec::new();\n\n let flush_text = |cur_text: &mut String,\n ctx: &Vec<&'static str>,\n doc: &mut Doc,\n cur_cell: &mut Option<String>| {\n let t = normalize_ws(cur_text);\n cur_text.clear();\n if t.is_empty() {\n return;\n }\n if let Some(cell) = cur_cell.as_mut() {\n if !cell.is_empty() {\n cell.push(' ');\n }\n cell.push_str(&t);\n return;\n }\n match ctx.last().copied() {\n Some(\"title\") => {\n if !doc.title.is_empty() {\n doc.title.push(' ');\n }\n doc.title.push_str(&t);\n }\n Some(\"h\") => {\n doc.headings.push(t.clone());\n doc.body.push_str(&t);\n doc.body.push_str(\"\\n\\n\");\n }\n _ => {\n doc.body.push_str(&t);","is_error":false}]},"uuid":"5072a213-2bac-4161-bb3f-4501cc277a0a","timestamp":"2026-10-01T15:45:24.056Z","sourceToolAssistantUUID":"1167b08d-68c9-4313-a4db-03446a3b8548","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"5072a213-2bac-4161-bb3f-4501cc277a0a","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002030008917fd5d70af6412e","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_1c6f767ab53b49e387d85e54","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && sed -n '140,163p' html.rs; echo \"=== parse fn ===\"; grep -n \"^fn parse\" -A 12 html.rs | head -20","description":"Read parse function head"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":495,"cache_creation_input_tokens":0,"cache_read_input_tokens":158976,"output_tokens":78,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"afcd8d61-366e-42d7-aa24-e1b1c02c6801","timestamp":"2026-10-01T15:45:29.283Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"afcd8d61-366e-42d7-aa24-e1b1c02c6801","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_1c6f767ab53b49e387d85e54","type":"tool_result","content":" {\n best = Some(i);\n }\n }\n best.map(|i| {\n (\n &doc.tables[i],\n doc.header_cells\n .get(i)\n .and_then(|h| h.first())\n .copied()\n .unwrap_or(false),\n )\n })\n}\n\nfn parse(html: &str) -> Doc {\n let mut doc = Doc::default();\n let bytes = html.as_bytes();\n let mut i = 0usize;\n let mut text_sink: Vec<&'static str> = Vec::new(); // element context stack (interned kinds)\n let mut cur_text = String::new();\n\n // table state\n=== parse fn ===\n156:fn parse(html: &str) -> Doc {\n157- let mut doc = Doc::default();\n158- let bytes = html.as_bytes();\n159- let mut i = 0usize;\n160- let mut text_sink: Vec<&'static str> = Vec::new(); // element context stack (interned kinds)\n161- let mut cur_text = String::new();\n162-\n163- // table state\n164- let mut in_table = false;\n165- let mut cur_table: Vec<Vec<String>> = Vec::new();\n166- let mut cur_row: Vec<String> = Vec::new();\n167- let mut cur_cell: Option<String> = None;\n168- let mut cur_row_th: Vec<bool> = Vec::new();","is_error":false}]},"uuid":"a2357e63-33e7-4481-b4f5-b93c78643693","timestamp":"2026-10-01T15:45:29.329Z","sourceToolAssistantUUID":"afcd8d61-366e-42d7-aa24-e1b1c02c6801","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"a2357e63-33e7-4481-b4f5-b93c78643693","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203001361cf3bcb099b4fee","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"`bytes = html.as_bytes()` — same string, so byte indices align with char boundaries for ASCII. Safe.\n\nNow let me do a final targeted check on the remaining named risk areas and then write the report. Things left:\n1. Confirm the `create`-action non-object doc actually reaches pipeline and can be stored (severity amplification).\n2. Check `xerj-wasm` `AppendPlugin` etc. — no panic.\n3. Check for `regexec`/regex DoS: Rust regex is linear; no ReDoS. Note sniff.rs `yaml_like_count` compiles a Regex per call — perf only.\n4. Integer overflow in length prefixes: let me check `read_whole` / `MAX_WHOLE_FILE` and the docx extractor, plus mbox budget. Quick check of `extract/mod.rs` read_whole and any `[..n]` slicing with untrusted n.\n\nLet me grep for potential integer cast issues across extract and content.rs.\n\nActually, one more important one for the pipeline: `TimestampParsePlugin` epoch float → nanos. `epoch_f` huge → `secs` saturating i64 → `timestamp_opt` returns None → fine.\n\nLet me check the `_bulk` create path storing a non-object and also whether there's a `turbo` path for create. Then write up.\n\nLet me also quickly double check the `es_compat.rs:23864` search-time pipeline (hit.source) — what API is that? Let me look. If it's `/_search?pipeline=` then a doc stored as non-object + search → panic. Worth one check.","signature":"0a937ddc199040858b0674db"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"3cb1b94e-5074-41a6-9719-62fe7c959efd","timestamp":"2026-10-01T15:45:45.617Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"3cb1b94e-5074-41a6-9719-62fe7c959efd","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203001361cf3bcb099b4fee","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_fe071c145218498e872f1782","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && sed -n '23830,23880p' es_compat.rs","description":"Inspect search-time pipeline usage"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":526,"cache_creation_input_tokens":0,"cache_read_input_tokens":159424,"output_tokens":451,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"432746d7-ea0c-439f-9218-385368ab1478","timestamp":"2026-10-01T15:45:47.647Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"432746d7-ea0c-439f-9218-385368ab1478","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203001361cf3bcb099b4fee","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_d95bb78eb72248aca1a2d055","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract && grep -n \"fn read_whole\" -A 25 mod.rs | head -35","description":"Read read_whole bounds"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":526,"cache_creation_input_tokens":0,"cache_read_input_tokens":159424,"output_tokens":451,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"511bd6ed-7005-494f-ab42-e2cd21062055","timestamp":"2026-10-01T15:45:47.656Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"432746d7-ea0c-439f-9218-385368ab1478","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_fe071c145218498e872f1782","type":"tool_result","content":" };\n\n let results = match source_idx.search(&search_req).await {\n Ok(r) => r,\n Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),\n };\n // A script resource limit in `source.query` makes matching fail-closed,\n // so this batch is a subset of the documents the caller asked to copy.\n // Reporting a completed reindex over a silently truncated source is the\n // same class of defect as a silently wrong score.\n if let Some(reason) = &results.script_failure {\n return script_limit_response(reason);\n }\n\n let batch_size = results.hits.len();\n if batch_size == 0 {\n break;\n }\n\n batches += 1;\n total_fetched += batch_size;\n\n // Capture the keyset cursor before the `for` loop consumes `results.hits`.\n let last_id = results.hits.last().map(|h| h.id.clone());\n\n for hit in results.hits {\n if !hit.source.is_null() {\n // `dest.pipeline`, if the request named one. Already known to\n // exist and to be runnable (checked before any copy started),\n // so anything that goes wrong here is a per-document failure\n // and is reported as one — never a pass-through of the\n // untransformed source.\n let doc_source = match dest_pipeline.as_deref() {\n None => hit.source,\n Some(p) => match state.engine.process_through_pipeline(p, vec![hit.source]) {\n Ok(mut results) if !results.is_empty() => {\n let (action, transformed) = results.remove(0);\n if matches!(action, xerj_wasm::pipeline::ProcessAction::Drop) {\n // ES: a pipeline that drops the document does\n // not write it, and the run reports a noop.\n noops += 1;\n continue;\n }\n transformed\n }\n Ok(_) => {\n failures.push(json!({\n \"id\": hit.id,\n \"cause\": {\n \"type\": \"reindex_error\",\n \"reason\": format!(","is_error":false}]},"uuid":"fa58008e-23b9-47a3-b6d9-f9457bf74ec8","timestamp":"2026-10-01T15:45:47.683Z","sourceToolAssistantUUID":"432746d7-ea0c-439f-9218-385368ab1478","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"511bd6ed-7005-494f-ab42-e2cd21062055","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_d95bb78eb72248aca1a2d055","type":"tool_result","content":"131:pub fn read_whole(path: &Path, gzip: bool, cap: u64) -> Result<Option<Vec<u8>>> {\n132- let mut r = open_reader(path, gzip, Some(cap + 1))?;\n133- let mut buf = Vec::new();\n134- r.read_to_end(&mut buf)?;\n135- if buf.len() as u64 > cap {\n136- return Ok(None);\n137- }\n138- Ok(Some(buf))\n139-}\n140-\n141-/// Render a file as a DOCUMENT (title = file stem, body = decoded text,\n142-/// section-split), regardless of its format family. This is how demoted\n143-/// one-off config files (`dataset` module docs, #173) are indexed: their\n144-/// key sets are configuration, not a schema, so their retrievable value is\n145-/// the text itself. Emits the same `title`/`body`/`section` vocabulary as\n146-/// every other document extractor (`FieldOrigin::Extractor`).\n147-pub fn extract_as_document(path: &Path, gzip: bool, sink: Sink) -> Result<ExtractStats> {\n148- extract_as_document_with_name(path, path, gzip, sink)\n149-}\n150-\n151-/// [`extract_as_document`], but the title comes from `logical_path` rather\n152-/// than `content_path`. The `--no-graph` generated pipeline reads a\n153-/// SEALED SNAPSHOT — a real file on disk, but under its own ordinal name\n154-/// (`prepared/00000000`, …), not the source's — so deriving the title from\n155-/// `content_path` there produced `\"00000000\"` instead of the file's own\n156-/// name (#722). Mirrors `sniff::sniff_with_name`'s split for exactly the","is_error":false}]},"uuid":"3a769e44-09cb-48cd-bcc8-547af85fe039","timestamp":"2026-10-01T15:45:47.689Z","sourceToolAssistantUUID":"511bd6ed-7005-494f-ab42-e2cd21062055","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"3a769e44-09cb-48cd-bcc8-547af85fe039","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203003057706dfa1f0c478b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The `_reindex` path applies a pipeline to `hit.source` from a source index. So: an attacker who can index a non-object document (via bulk `create`) into index A, then run `_reindex` from A to B with `dest.pipeline` set → panic → abort. Multi-step, but a chain.\n\nNow let me quickly verify the `create` non-object path actually stores the array. Actually, an easier and more direct route to a non-object doc: `POST /{index}/_doc?pipeline=p` with body `[1,2,3]` — the doc is parsed from raw bytes with no object validation, and the pipeline runs immediately. That is a single-request kill (given an existing pipeline). That's confirmed already.\n\nAlso for `update` (doc via `{\"doc\": [...]}`) — update is excluded.\n\nOne more: `PUT /_ingest/pipeline/{id}/_simulate` with docs whose `_source` is an array — the interpreter. Let me quickly check whether the interpreter indexes `source[...]`. Let me grep the interpreter body for `source[` / `as_object_mut` / indexing.\n\nLet me do that quickly plus check the `ingest` native endpoint path is registered (router). Actually I've confirmed enough.\n\nLet me do one last check: is there a panic in the ES `_simulate` interpreter? Quick grep for `\\[` indexing in that function range.\n\nActually, more valuable: let me verify one thing about the pipeline panic — that there isn't a `catch_unwind` around pipeline processing. With panic=abort, catch_unwind wouldn't help anyway (abort happens at panic). Let me just confirm no catch_unwind exists in the pipeline path.\n\nLet me also double check that `AddFieldPlugin` is truly reachable with a non-object: `process_through_pipeline(pipeline, vec![input])` where input = `Value::Array`. `Pipeline::process` → stage.process(doc) → `doc[&self.field] = self.value.clone()`. Yes.\n\nWait — one caveat: for Value::Null input (e.g., body `null`), serde_json converts Null→Object, no panic. For Array/String/Number/Bool → panic. Confirmed.\n\nLet me run a final grep for catch_unwind and for any other `doc[` patterns in the wasm crate, then write the report.","signature":"2386a2d029124fce917d14a0"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"cdba9e6f-52b2-422c-8766-85bc4873898f","timestamp":"2026-10-01T15:46:07.570Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"cdba9e6f-52b2-422c-8766-85bc4873898f","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203003057706dfa1f0c478b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_6fc131f9731244d186e4b3b0","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates && grep -rn \"catch_unwind\" --include=\"*.rs\" xerj-engine/src xerj-api/src xerj-wasm/src | head -10; echo \"=== doc[ indexing in wasm ===\"; grep -n \"doc\\[\" xerj-wasm/src/builtins.rs","description":"Check catch_unwind and doc indexing"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1322,"cache_creation_input_tokens":0,"cache_read_input_tokens":159936,"output_tokens":673,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"d3919ade-f164-4ed0-93d7-c83524b6bd97","timestamp":"2026-10-01T15:46:10.072Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d3919ade-f164-4ed0-93d7-c83524b6bd97","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_2026100203003057706dfa1f0c478b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_a8b2fe4461b5466396779000","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-api/src && awk 'NR>=29747 && NR<=30500' es_compat.rs | grep -nE \"source\\[|\\[\\\"|\\]\\s*=|as_object_mut|insert\" | head -25","description":"Check simulate interpreter for indexing panics"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1322,"cache_creation_input_tokens":0,"cache_read_input_tokens":159936,"output_tokens":673,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"56ad2d20-ed57-428d-8e60-fd03afeca523","timestamp":"2026-10-01T15:46:10.091Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"d3919ade-f164-4ed0-93d7-c83524b6bd97","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_6fc131f9731244d186e4b3b0","type":"tool_result","content":"xerj-engine/src/ingest_memory.rs:994: let result = std::panic::catch_unwind(|| {\nxerj-engine/src/collection_publication.rs:178: let result = std::panic::catch_unwind({\nxerj-engine/src/segment_cache_budget.rs:282: let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\nxerj-engine/src/index.rs:6776: let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\nxerj-engine/src/index.rs:29257: std::panic::catch_unwind(std::panic::AssertUnwindSafe(decode))\nxerj-engine/src/index.rs:31957: let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\nxerj-engine/src/index.rs:31995: let published = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {\n=== doc[ indexing in wasm ===\n21:/// Otherwise the parsed object is stored at `doc[target]`.\n68: doc[&self.target] = parsed;\n132: doc[self.target_field()] = Value::String(iso);\n145: doc[self.target_field()] = Value::String(iso);\n155: doc[self.target_field()] = Value::String(utc.to_rfc3339());\n162: doc[self.target_field()] = Value::String(dt.to_rfc3339());\n168: doc[self.target_field()] = Value::String(dt.to_rfc3339());\n174: doc[self.target_field()] = Value::String(dt.to_rfc3339());\n182: doc[self.target_field()] = Value::String(utc.to_rfc3339());\n285: doc[&self.field] = self.value.clone();\n296:/// Looks up `doc[field]` in the `routes` map. If a match is found, returns\n630: doc[&self.target] = val;\n728: doc[&self.field] = v;\n771: doc[&self.field] = Value::Array(parts);\n870: doc[&self.field] = self.value.clone();\n1031: assert_eq!(doc[\"level\"], \"info\");\n1032: assert_eq!(doc[\"msg\"], \"hi\");\n1041: assert_eq!(doc[\"parsed\"][\"k\"], \"v\");\n1050: assert_eq!(doc[\"raw\"], \"not-json\");\n1067: let ts = doc[\"@timestamp\"].as_str().unwrap();\n1076: assert!(doc[\"@timestamp\"].is_string());\n1084: let ts = doc[\"@timestamp\"].as_str().unwrap();\n1097: let ts = doc[\"event.created\"].as_str().unwrap();\n1112: assert_eq!(doc[\"new_name\"], \"value\");\n1114: assert_eq!(doc[\"other\"], 1);\n1138: assert_eq!(doc[\"user\"], \"alice\");\n1155: assert_eq!(doc[\"env\"], \"production\");\n1163: assert_eq!(doc[\"status\"], \"new\");\n1211: assert_eq!(doc[\"remote_addr\"], \"192.168.1.1\");\n1212: assert_eq!(doc[\"status\"], \"200\");\n1213: assert_eq!(doc[\"method\"], \"GET\");\n1223: assert_eq!(doc[\"hostname\"], \"myhost\");\n1224: assert_eq!(doc[\"program\"], \"myapp\");\n1225: assert_eq!(doc[\"pid\"], \"1234\");\n1234: assert_eq!(doc[\"message\"], \"totally unstructured text\");\n1244: let msg = doc[\"msg\"].as_str().unwrap();\n1257: let remote = doc[\"remote\"].as_str().unwrap();\n1268: let msg = doc[\"msg\"].as_str().unwrap();\n1283: let email = doc[\"user\"][\"email\"].as_str().unwrap();\n1285: assert_eq!(doc[\"user\"][\"name\"], \"Alice\");\n1293: let msg = doc[\"msg\"].as_str().unwrap();","is_error":false}]},"uuid":"d73f39ee-464e-4bfd-8121-2e2a635b36cc","timestamp":"2026-10-01T15:46:10.127Z","sourceToolAssistantUUID":"d3919ade-f164-4ed0-93d7-c83524b6bd97","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"56ad2d20-ed57-428d-8e60-fd03afeca523","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_a8b2fe4461b5466396779000","type":"tool_result","content":"43: entry.insert(\n47: entry.insert(\"status\".to_string(), Value::String(status.to_string()));\n50: entry.insert(\"tag\".to_string(), Value::String(tag.to_string()));\n54: entry.insert(\"description\".to_string(), Value::String(desc.to_string()));\n57: entry.insert(\n78: entry.insert(\n89: ingest.insert(\n93: ingest.insert(\n98: ingest.insert(\n103: entry.insert(\n115: entry.insert(\n302: entry.insert(\n306: entry.insert(\"status\".to_string(), Value::String(\"success\".into()));\n309: entry.insert(\"tag\".to_string(), Value::String(tag.to_string()));\n313: entry.insert(\"description\".to_string(), Value::String(desc.to_string()));\n315: entry.insert(\"doc\".to_string(), Value::Null);\n327: entry.insert(\"processor_type\".to_string(), Value::String(\"drop\".into()));\n328: entry.insert(\"status\".to_string(), Value::String(\"dropped\".into()));\n330: entry.insert(\"if\".to_string(), json!({\"condition\": cond, \"result\": true}));\n442: if let Some(obj) = doc.as_object_mut() {\n462: .as_object_mut()\n468: if let (Some(dst), Some(src)) = (source.as_object_mut(), wrapped.as_object()) {\n471: dst.insert(k.clone(), v.clone());\n507: obj.insert(segments[0].to_string(), value);\n514: .or_insert_with(|| Value::Object(serde_json::Map::new()));","is_error":false}]},"uuid":"c71b9459-0d89-4d1a-94bd-bcd0739a5e5b","timestamp":"2026-10-01T15:46:10.160Z","sourceToolAssistantUUID":"56ad2d20-ed57-428d-8e60-fd03afeca523","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c71b9459-0d89-4d1a-94bd-bcd0739a5e5b","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002030051ce57d5b22fb34bf6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The `_simulate` interpreter uses `as_object_mut` guards. Safe.\n\nSo the compiled pipeline's `doc[...] = ...` sites are the panics. Nine sites:\n- builtins.rs:68 (JsonParsePlugin target)\n- 132,145,155,162,168,174,182 (TimestampParsePlugin)\n- 285 (AddFieldPlugin)\n- 630 (CopyFieldPlugin)\n- 728 (ConvertTypePlugin)\n- 771 (SplitPlugin)\n- 870 (SetPlugin)\n\nNow I have solid, verified findings. Let me do a final sanity check that the ES-compat index path is reachable: is there an object-ness check anywhere in `index_doc_auto` after pipeline? No — the pipeline runs first.\n\nLet me also verify that creating a pipeline via `PUT /_ingest/pipeline/{id}` is allowed (yes, es_compat put_ingest_pipeline), and check whether the ES-compat `_doc` endpoint requires the index to exist (which an attacker can create). Fine.\n\nLet me quickly double-check that the `xerj-api` `ingest_with_pipeline` native endpoint is routed (it's a public handler). Good enough.\n\nNow let me do one last scan of the autoindex for a dramatic issue I might have missed: unbounded decompression in `open_reader` with gzip — `read_whole` caps at MAX_WHOLE_FILE. What about other extractors that stream gz without caps? `mbox` has a budget gate. Let me check `open_reader` and whether any extractor reads whole file without cap. Quick grep for `read_to_end` without cap.\n\nAlso: `read_prefix` in sniff.rs with gzip uses `MultiGzDecoder` + take(n) — bounded.\n\nLet me check `extract/mod.rs` open_reader + MAX_WHOLE_FILE value and any uncapped reads.","signature":"0fbaec067b094fe48506144e"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"f9e5117b-e937-4e28-bd18-06eb3bef8d7a","timestamp":"2026-10-01T15:46:26.316Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"f9e5117b-e937-4e28-bd18-06eb3bef8d7a","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002030051ce57d5b22fb34bf6","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_e5da89a0a9e14832a514ef89","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-autoindex/src && grep -n \"MAX_WHOLE_FILE\\|fn open_reader\" -A 12 extract/mod.rs | head -50; echo \"=== uncapped reads ===\"; grep -rn \"read_to_end\" extract/*.rs content.rs lib.rs | head -20","description":"Check decompression caps"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1943,"cache_creation_input_tokens":0,"cache_read_input_tokens":161216,"output_tokens":482,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"7001f012-2458-42a7-b242-2d6296a64254","timestamp":"2026-10-01T15:46:26.817Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"7001f012-2458-42a7-b242-2d6296a64254","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_e5da89a0a9e14832a514ef89","type":"tool_result","content":"82:pub const MAX_WHOLE_FILE: u64 = 64 << 20; // whole-file parse cap (json/html/yaml/txt)\n83-/// Target characters per document section.\n84-///\n85-/// Was 32 KB, which is a *storage* granularity, not a *retrieval* one: BM25\n86-/// scores per document, so a 32 KB section dilutes any match into noise and\n87-/// every hit drags 32 KB through `_source`. Measured on a 460-commit history\n88-/// file, 32 KB sections produced 25 documents for 15,407 lines and the\n89-/// relevant commit was not retrievable; at 2 KB with paragraph overlap it is.\n90-///\n91-/// 2 KB is roughly the 40-line window validated for line-oriented text, and\n92-/// comfortably inside the 512-token limit of the built-in neural embedder, so\n93-/// a section maps to one vector without truncation.\n94-pub const SECTION_CHARS: usize = 2 << 10;\n--\n114:pub fn open_reader(path: &Path, gzip: bool, limit: Option<u64>) -> Result<Box<dyn BufRead + Send>> {\n115- let f = std::fs::File::open(path)?;\n116- let inner: Box<dyn Read + Send> = if gzip {\n117- Box::new(flate2::read::MultiGzDecoder::new(f))\n118- } else {\n119- Box::new(f)\n120- };\n121- // `Send` so a container extractor (mbox) can move the reader to its\n122- // splitter thread; every concrete reader here is.\n123- let inner: Box<dyn Read + Send> = match limit {\n124- Some(n) => Box::new(inner.take(n)),\n125- None => Box::new(inner),\n126- };\n--\n165: let Some(bytes) = read_whole(content_path, gzip, MAX_WHOLE_FILE)? else {\n166- stats.junk += 1;\n167- return Ok(stats);\n168- };\n169- let (text, _) = crate::sniff::decode_text(&bytes);\n170- if text.trim().is_empty() {\n171- stats.junk += 1;\n172- return Ok(stats);\n173- }\n174- let title = logical_path\n175- .file_stem()\n176- .map(|s| s.to_string_lossy().to_string())\n177- .unwrap_or_else(|| \"untitled\".into());\n=== uncapped reads ===\nextract/mod.rs:134: r.read_to_end(&mut buf)?;\nextract/pdf.rs:1974: file.read_to_end(&mut bytes).unwrap();","is_error":false}]},"uuid":"45556a4b-d306-4943-8d4e-ae4c949ad5ec","timestamp":"2026-10-01T15:46:26.853Z","sourceToolAssistantUUID":"7001f012-2458-42a7-b242-2d6296a64254","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"45556a4b-d306-4943-8d4e-ae4c949ad5ec","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020301074a5057136d8c463b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"`read_whole` caps at 64 MiB via `take(cap+1)` — bounded decompression. Good.\n\nSo the autoindex archive/decompression surface is well defended:\n- Archives are never opened (zip/tar/7z/rar/xz → named binary, advice to extract manually).\n- The one zip extraction (harvest http-zip source) sanitizes entry names, skips symlinks, and caps total decompressed bytes at 2 GiB.\n- Object-store keys are classified through `classify_key` refusing `..`, absolute, backslash, control chars.\n- Symlink following in the walk is guarded by canonicalize + root/hidden checks.\n- Whole-file reads are capped at 64 MiB; PDF extraction runs in an RLIMIT_AS-limited subprocess with output caps and a timeout.\n\nI'm now fairly confident in the findings. Let me write the report.\n\nRanked findings:\n\n**1. CRITICAL — Panic (process abort) on non-object document reaching an ingest pipeline.**\n- builtins.rs:285 `doc[&self.field] = self.value.clone();` (AddFieldPlugin) and the other 7 sites.\n- serde_json `IndexMut` panics for non-object/non-null.\n- Shipped release profile has `panic = \"abort\"` (engine/Cargo.toml:165) → any panic kills the whole node.\n- Reachable:\n a) `POST /{index}/_doc?pipeline=P` with a JSON array/scalar body — es_compat.rs:2801-2810 parses raw body into `Value` with no object check and passes straight to `process_through_pipeline`.\n b) `POST /v1/indices/{name}/ingest?pipeline=P` — native.rs:2633-2650 `IngestRequest::Single(Value)`/`Batch(Vec<Value>)` → docs verbatim.\n c) `_bulk` with a `create` action: bulk.rs:825-845 only enforces the top-level-object rule for `action_type == \"index\"`; the `else` branch (bulk.rs:858-880) parses `create` bodies into `Value` unchecked; bulk.rs:1745-1783 then feeds `doc_body` to the pipeline for `\"index\" | \"create\"`.\n d) `_reindex` with `dest.pipeline` — es_compat.rs:23864 feeds `hit.source` (whatever is stored) through the pipeline.\n- Only `Value::Null` is safe (serde_json auto-converts to an object). Array/string/number/bool bodies panic.\n- Attack: 1 request if a pipeline exists (default_pipeline on an index makes it 0 params); 2 requests otherwise (PUT /_ingest/pipeline then POST).\n\n**2. HIGH — `_bulk` accepts a non-object document body for `create`, storing non-object docs.** This is both the enabler for (1d) and its own data-integrity issue. Actually, I should verify whether it stores it. I didn't verify fully. Let me phrase carefully: the object check is index-only; `create` reaches indexing with an arbitrary Value. The downstream `as_object_mut` guards skip validation, so the array is passed to indexing. I'll state it as \"reaches the indexing path unvalidated\" and note I didn't confirm the final storage.\n\nHmm, I should be careful not to overclaim. Let me quickly check the create path after the pipeline to see if it stores.\n\n**3. MEDIUM — UrlDecodePlugin off-by-one** (builtins.rs:986): `else if bytes[i] == b'%' && i + 2 < bytes.len()` — a percent-escape at the very end of a string (`...%41`) is not decoded, and `%4` at end → `bytes[i+1]`/`bytes[i+2]`... wait, with `i+2 < len`, if `i+2 == len-1` that's fine. Condition `i+2 < len` means indices i+1 and i+2 are valid only when i+2 <= len-1, i.e., i+2 < len. Correct actually! `i+2 < len` ⟹ i+2 is a valid index. So the bound is correct, not off-by-one. Hmm: for \"%41\" at the end, i points at '%', i+2 = len-1, so `i+2 < len` is `len-1 < len` = true → decodes. OK so no bug. Good thing I checked. Correct code.\n\nLet me re-examine: is there any correctness issue? `to_digit(16)` on a non-hex → returns None → whole decode fails → passes through unchanged. Fine.\n\nSo scratch #3.\n\n**Other candidates worth reporting (lower):**\n- `sniff.rs:1411` `yaml_like_count` compiles a `Regex::new` on every call — hot path per file; DoS-ish at scale but not attacker-triggerable beyond normal file classification. It's called from `classify_text` → `yaml_line_ratio` and frontmatter path. Perf only, mention briefly? The instruction says no style nits. It's a perf issue not security. Skip or mention as low.\n\n- Regex DoS: Rust `regex` crate has linear-time guarantees; all patterns are compile-time constants; doc-supplied patterns are rejected (`grok` `patterns`/`pattern_definitions` → UnsupportedOption). So no ReDoS. Worth stating as \"checked, not present\".\n\n- Command exec / network / file access from document content in xerj-wasm: none — the crate has no fs/net/process deps at all. The only `Command` in autoindex is the PDF worker (`pdf.rs:939`) whose executable comes from `XERJ_PDF_WORKER_BIN` env or `current_exe` — operator-controlled, not document-controlled. Worth stating.\n\n- Autoindex archives: not opened at all. Zip extraction path is hardened. Object keys hardened. Symlinks hardened.\n\nLet me do a final verification of #2 (whether the create non-object doc gets stored), since it affects the severity chain. Let me look at what happens to `doc_body` for create after the pipeline block.","signature":"ae630d92166d4de386404b2c"}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1105,"cache_creation_input_tokens":0,"cache_read_input_tokens":163136,"output_tokens":1372,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"c49d7b5c-6779-4676-b315-a24758ed51ec","timestamp":"2026-10-01T15:47:08.937Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"c49d7b5c-6779-4676-b315-a24758ed51ec","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_202610020301074a5057136d8c463b","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"tool_use","id":"call_9f669c70fe4f4dd99857f79c","name":"Bash","input":{"command":"cd /root/ab-run-x1/repo/engine/crates/xerj-engine/src && sed -n '2080,2200p' bulk.rs","description":"Trace create action indexing path"}}],"stop_reason":"tool_use","stop_sequence":null,"usage":{"input_tokens":1105,"cache_creation_input_tokens":0,"cache_read_input_tokens":163136,"output_tokens":1372,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"277174c6-f4dd-40b3-ba66-c2c560ecc1c5","timestamp":"2026-10-01T15:47:08.939Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":"277174c6-f4dd-40b3-ba66-c2c560ecc1c5","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":[{"tool_use_id":"call_9f669c70fe4f4dd99857f79c","type":"tool_result","content":" // override), values that don't parse against the format are\n // rejected at ingest as ES does — `document_parsing_exception`\n // at the bulk item level. We only apply this for `index` /\n // `create`; updates operate on already-stored docs.\n if matches!(action_type.as_str(), \"index\" | \"create\") {\n if let Some(body) = doc_body.as_ref().and_then(Value::as_object) {\n let mapping_props = engine.index_mappings.get(&target_index).and_then(|m| {\n m.get(\"properties\")\n .or_else(|| m.get(\"mappings\").and_then(|mm| mm.get(\"properties\")))\n .cloned()\n });\n if let Some(props) = mapping_props {\n if let Some(bad) = find_bad_date_field(body, &props) {\n let reason = format!(\n \"failed to parse field [{}] of type [date] in document with id '{}'\",\n bad.0,\n doc_id.clone().unwrap_or_default(),\n );\n items[item_idx] = Some(BulkItemResult {\n action: action_type.to_string(),\n index: target_index.clone(),\n id: error_id.clone(),\n status: 400,\n result: None,\n error: Some(reason),\n get_source: None,\n });\n errors = true;\n continue;\n }\n }\n }\n }\n // Numeric / boolean type enforcement (issue #781). A field mapped\n // `integer` used to keep whatever arrived — `1.9`, `9999999999`,\n // `\"abc\"`, even an object — so the same query over the same declared\n // -integer field returned different hits than ES. Values ES coerces\n // are coerced here (`1.9` → `1`, `\"5\"` → `5`, `\"true\"` → `true`) and\n // values ES refuses become a per-item 400 `document_parsing_exception`,\n // exactly like the date-format check above. `index` / `create` only:\n // an `update` merges into a doc that was already validated on write.\n //\n // The rules live in `xerj_common::field_coercion`, shared with the\n // single-document `_doc` / `_create` handlers in `xerj-api`, so the\n // two write paths cannot drift apart.\n if matches!(action_type.as_str(), \"index\" | \"create\") {\n let mapping_props = typed_numeric_props(&target_index, &mut index_type_check_props);\n if let Some(props) = mapping_props {\n if let Some(body) = doc_body.as_mut().and_then(Value::as_object_mut) {\n if let Err(bad) = xerj_common::field_coercion::coerce_document(body, &props) {\n items[item_idx] = Some(BulkItemResult {\n action: action_type.to_string(),\n index: target_index.clone(),\n id: error_id.clone(),\n status: 400,\n result: None,\n error: Some(bad.reason(&doc_id.clone().unwrap_or_default())),\n get_source: None,\n });\n errors = true;\n continue;\n }\n }\n }\n }\n // doc_body already lazy-parsed above (for dynamic-templates\n // validation). Nothing else to do here.\n let result = execute_bulk_action(\n engine,\n &action_type,\n &target_index,\n doc_id,\n doc_body,\n if_seq_no,\n if_primary_term,\n routing,\n )\n .await;\n\n match result {\n Ok(resp) => {\n // ES bulk semantics: 201 on first create, 200 on\n // overwrite (update). Delete → 200. Engine reports the\n // fact via `resp.result` (\"created\" vs \"updated\").\n let status: u16 = match action_type.as_str() {\n \"delete\" => 200,\n _ if resp.result == \"updated\" || resp.result == \"noop\" => 200,\n _ => 201,\n };\n // Bulk update supports echoing the post-update source\n // via `items[N].update.get._source`. Source spec comes\n // from (priority): action metadata → doc-body `_source`\n // → URL-level default (?_source=true).\n let effective_source_req =\n source_req.clone().or_else(|| default_source_req.clone());\n let get_source: Option<Value> =\n if action_type == \"update\" && effective_source_req.is_some() {\n match doc_id_for_get.as_deref() {\n Some(id) => match engine.get_index(&target_index_for_get) {\n Ok(idx) => {\n let fetched = idx.get_document(id).await.ok().flatten();\n fetched.map(|src| {\n apply_bulk_source_filter(\n &src,\n effective_source_req.as_ref().unwrap(),\n )\n })\n }\n Err(_) => None,\n },\n None => None,\n }\n } else {\n None\n };\n items[item_idx] = Some(BulkItemResult {\n action: action_type.clone(),\n index: target_index,\n id: resp.id,\n status,\n result: Some(resp.result),","is_error":false}]},"uuid":"09011761-d189-4da5-9cf9-14ccdafcf83c","timestamp":"2026-10-01T15:47:08.956Z","sourceToolAssistantUUID":"277174c6-f4dd-40b3-ba66-c2c560ecc1c5","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD"}
{"parentUuid":null,"logicalParentUuid":"09011761-d189-4da5-9cf9-14ccdafcf83c","isSidechain":true,"agentId":"afcecc181ae7e2aa9","type":"system","subtype":"compact_boundary","content":"Conversation compacted","isMeta":false,"timestamp":"2026-10-01T15:50:02.419Z","uuid":"f801913a-6163-43fe-8e3d-aa311eb97568","level":"info","compactMetadata":{"trigger":"auto","preTokens":167158,"durationMs":173460,"preservedSegment":{"headUuid":"c49d7b5c-6779-4676-b315-a24758ed51ec","anchorUuid":"56a2a230-bf9b-43af-9e10-90ac3ddf6ee1","tailUuid":"09011761-d189-4da5-9cf9-14ccdafcf83c"},"preservedMessages":{"anchorUuid":"56a2a230-bf9b-43af-9e10-90ac3ddf6ee1","uuids":["c49d7b5c-6779-4676-b315-a24758ed51ec","277174c6-f4dd-40b3-ba66-c2c560ecc1c5","09011761-d189-4da5-9cf9-14ccdafcf83c"],"allUuids":["c49d7b5c-6779-4676-b315-a24758ed51ec","277174c6-f4dd-40b3-ba66-c2c560ecc1c5","09011761-d189-4da5-9cf9-14ccdafcf83c"]},"postTokens":50303,"cumulativeDroppedTokens":116855},"userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD","slug":"flickering-imagining-perlis"}
{"parentUuid":"f801913a-6163-43fe-8e3d-aa311eb97568","isSidechain":true,"promptId":"26dbe850-63e1-4fc2-a483-7feb1f8cdc8a","agentId":"afcecc181ae7e2aa9","type":"user","message":{"role":"user","content":"This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\nSummary:\n1. **Primary Request and Intent:**\n\n Perform a security review of the XERJ search engine (Rust) at `/root/ab-run-x1/repo`, focused on **INGEST OF UNTRUSTED DOCUMENTS**. Verbatim scope and deliverable from the user:\n\n - Read thoroughly: `engine/crates/xerj-wasm/src/pipeline.rs` (~1370 lines), `engine/crates/xerj-wasm/src/builtins.rs` (~1300 lines), `engine/crates/xerj-wasm/src/lib.rs`, \"The autoindex hostile-file parsing: engine/crates/xerj-autoindex/src/sniff.rs, and any archive/zip/tar/gz handling in xerj-autoindex (search for zip, tar, gz, decompress, symlink, path traversal, ..)\"\n - Hunt for REAL exploitable bugs a malicious document/corpus provider could trigger when their documents are indexed: path traversal on extraction; zip-slip/symlink following; unbounded decompression (zip bombs) — \"only if dramatic\"; any command execution, file access, network access reachable from document content; regex catastrophic backtracking from doc-supplied patterns; script/eval of doc-supplied code; integer overflow in length prefixes leading to allocation or slice OOB; panics reachable from malformed docs (\"a panic in Rust = crash of handler thread; only matters if it kills the process\")\n - \"For each candidate: file:line, exact code quote, attack path from document bytes to the bug. Verify the call chain: who calls these functions with untrusted input (search callers in xerj-engine bulk/index paths). Report a ranked list of concrete candidates. No style nits.\"\n\n Standing system constraints (must remain in force): **READ-ONLY mode** — no Write/Edit/rm/mv/cp, no temp files, no redirect operators to write files; do not create report/summary .md files (return findings as the final assistant message); use absolute paths; no emojis.\n\n2. **Key Technical Concepts:**\n - serde_json `IndexMut` (`Value: Index<&str>`) — `index_or_insert` panics `\"cannot access key {:?} in JSON {}\"` for any non-object, non-null Value (Null is silently converted to an object; Array/String/Number/Bool panic)\n - `panic = \"abort\"` in `[profile.release]` (engine/Cargo.toml:165) — any panic terminates the entire server process, not just a handler thread\n - Elasticsearch-compatible ingest surface: `PUT /_ingest/pipeline/{id}`, `POST /_ingest/pipeline/_simulate`, `POST /{index}/_doc?pipeline=`, `_bulk` with per-item `pipeline`, `index.default_pipeline` index setting, `_reindex` with `dest.pipeline`\n - `CompileMode::{Strict, ReplayPersisted}` issue-#204 fail-closed sweep in pipeline compilation\n - autoindex content sniffing (`Family` enum, MAGIC_TABLE with structural qualifiers, GIF comment-chain walk)\n - Defensive zip extraction: `sanitize_entry_path` component filter, symlink-entry skip, `MAX_EXTRACT_BYTES = 2 << 30` budget\n - Object-store key → local path hardening (`classify_key` / `KeyVerdict::Skip(rules::UNSAFE_KEY)`)\n - Symlink traversal guard (`escaped_or_hidden_target`, `SymlinkVerdict::{OutsideRoot, HiddenOutsideRoot, HiddenTarget, Unresolvable}`)\n - PDF extraction in a contained subprocess (`XERJ_PDF_WORKER_BIN`, `setpgid`, `RLIMIT_AS`, capped stdout/stderr, timeout)\n - Rust `regex` crate (linear-time, no catastrophic backtracking)\n\n3. **Files and Code Sections:**\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/builtins.rs`** (1298 lines) — THE PRIMARY FINDING. Nine `doc[...] = ...` sites that panic when the document is not a JSON object:\n - line 68 `doc[&self.target] = parsed;` (JsonParsePlugin)\n - lines 132, 145, 155, 162, 168, 174, 182 `doc[self.target_field()] = Value::String(iso/...);` (TimestampParsePlugin)\n - line 285 (AddFieldPlugin):\n ```rust\n fn process(&self, doc: &mut Value) -> ProcessAction {\n doc[&self.field] = self.value.clone();\n ProcessAction::Pass\n }\n ```\n - line 630 `doc[&self.target] = val;` (CopyFieldPlugin)\n - line 728 `doc[&self.field] = v;` (ConvertTypePlugin)\n - line 771 `doc[&self.field] = Value::Array(parts);` (SplitPlugin)\n - line 870 (SetPlugin):\n ```rust\n if self.override_existing || !exists {\n doc[&self.field] = self.value.clone();\n }\n ```\n Non-panicking plugins (verified safe): AppendPlugin (`as_object_mut` guard, early return), RemoveNullPlugin (`retain`), FieldRenamePlugin, DropFieldPlugin, LowercasePlugin/UppercasePlugin (`get_mut`), UrlDecodePlugin (manual byte loop, `to_digit(16)?`, `String::from_utf8(out).ok()`), RoutePlugin, GrokPlugin, PiiRedactionPlugin (all regexes are static; `redact_value` recursion bounded by serde_json's 128-level parse limit).\n\n - **`/root/ab-run-x1/repo/engine/Cargo.toml`** lines 160-165:\n ```toml\n [profile.release]\n opt-level = 3\n lto = \"fat\"\n codegen-units = 1\n strip = true\n panic = \"abort\"\n ```\n This is what elevates the builtins panic to process death. (`[profile.ci-test]` uses `panic = \"unwind\"` but is test-only.)\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-engine/src/bulk.rs`** — the validation asymmetry:\n - lines 827-845 (`index` actions ARE checked):\n ```rust\n let is_object = dl.as_bytes().iter()\n .find(|b| !b\" \\t\\r\\n\".contains(b))\n .map(|b| *b == b'{').unwrap_or(false);\n if !is_object { return ParseOutcome::Err(BulkItemResult{ ... error: Some(\n \"failed to parse: invalid document JSON: document body must be a JSON object\".to_string()), ...}); }\n ```\n - lines 858-864 (`create`/`update` are NOT checked):\n ```rust\n match serde_json::from_slice::<Value>(dl.as_bytes()) {\n Ok(v) => { let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(dl.as_bytes()); (Some(v), bytes) }\n ```\n - lines 1745-1776 (pipeline runs for `index` **and** `create`):\n ```rust\n if let Some(pid) = pipeline.as_deref() {\n if matches!(action_type.as_str(), \"index\" | \"create\") {\n let input = doc_body.clone().unwrap_or_else(|| Value::Object(serde_json::Map::new()));\n match engine.process_through_pipeline(pid, vec![input]) {\n ```\n - lines 1264-1285: numeric-coercion pass skips non-object bodies rather than rejecting them.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-api/src/es_compat.rs`** — `index_doc_auto` (~line 2800):\n ```rust\n let doc: Value = match serde_json::from_slice(&body) { Ok(v) => v, Err(e) => {...400...} };\n let doc = apply_ignore_malformed(&state, &index, doc); // returns doc unchanged for non-objects (line 39256)\n ...\n let effective_pipeline = resolve_effective_pipeline(&state, &index, params.pipeline.as_deref());\n let doc = if let Some(ref pipeline) = effective_pipeline {\n match state.engine.process_through_pipeline(pipeline, vec![doc]) {\n ```\n Also `_reindex` at line 23864: `state.engine.process_through_pipeline(p, vec![hit.source])`. `_simulate` interpreter (`run_inline_pipeline_on_doc`, line 29747) defaults `_source` to an object and uses `as_object_mut` guards — safe.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-api/src/native.rs`** lines 2642-2650 — `POST /v1/indices/{name}/ingest?pipeline=`:\n ```rust\n pub enum IngestRequest { Single(Value), Batch(Vec<Value>) }\n let docs: Vec<Value> = match req { IngestRequest::Single(doc) => vec![doc], IngestRequest::Batch(docs) => docs };\n let processed = match state.engine.process_through_pipeline(¶ms.pipeline, docs) {\n ```\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-engine/src/engine.rs`** lines 4276-4300 — `process_through_pipeline` calls `pipeline.process_batch(&mut docs)` with no object guard and no `catch_unwind`. Line 4087 `default_pipeline_for` reads `index.default_pipeline` (so the trigger needs no query param). No `catch_unwind` exists on this path (only in ingest_memory.rs:994, collection_publication.rs:178, segment_cache_budget.rs:282, index.rs).\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/harvest/source.rs`** — `extract_zip` (lines 151-199) is DEFENDED: skips `entry.is_symlink()`, `sanitize_entry_path` (lines 206-232) rejects absolute paths/`..`/`.`/empty/NUL/`:`/backslash, per-entry `take(limit+1)` with `MAX_EXTRACT_BYTES = 2 << 30` bail. Only caller is `xc.rs:431` (HTTP-zip recipe source, operator-configured).\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/objsource.rs`** line 856: `let destination = run.mirror.join(&entry.rel);` — looks like traversal but `rel` comes from `key.strip_prefix(prefix)` at line 1265 and passes `classify_key` (source.rs:257-300) which Skips `..`, `.`, empty components, leading `/`, backslash, control chars, >255-byte components, trailing `.`/space, Windows reserved names and dot-prefixed components. DEFENDED.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/walk.rs`** — symlink/hidden-file rules heavily hardened (`escaped_or_hidden_target` lines 178-223; only `NotFound` from canonicalize is treated as \"nothing to leak\"). Documented residual: hard links (`ln .secretdir/k.txt notes.txt`) are undetectable — no attacker required though.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/sniff.rs`** — archives named, never opened (`archive_advice` line 1083: \"autoindex does not open archives\"); zip checked only via `by_index_raw` for `word/document.xml`; bounded reads (`PREFIX = 8192`, `GIF_PREFIX = 1 MiB`).\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract/pdf.rs`** — `spawn_worker` (line 936) runs a same-binary subprocess (`XERJ_PDF_WORKER_BIN` env or `current_exe()`), with `setpgid` + `RLIMIT_AS` (line 1082), capped stdout/stderr (`read_capped`), 120 s timeout, process-tree SIGKILL. Env var is operator-controlled, not document-controlled.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract/html.rs`** — `parse(html: &str)` uses `let bytes = html.as_bytes();` (line 158), so `bytes[i] == b'<'` guarantees `html[i..]` is on a char boundary. Not a panic.\n\n - **`/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/extract/mod.rs`** — `MAX_WHOLE_FILE: u64 = 64 << 20`, `read_whole` caps via `open_reader(path, gzip, Some(cap + 1))`; `open_reader` uses `MultiGzDecoder` + `.take(n)`. Decompression is bounded everywhere checked.\n\n4. **Errors and fixes:**\n - `grep \"fn classify_key\" objsource.rs` returned nothing → fixed by grepping repo-wide; found it in `source.rs:257`. Confirmed the object-mirror path is defended rather than reporting a false positive.\n - `grep \"auth_middleware|layer(\" xerj-server/src/main.rs` returned nothing → fell back to grepping `auth` in main.rs, which shows `cfg.auth.enabled`, `--insecure` disabling \"TLS *and* API-key authentication\" (help line 252, line 655). Exact default auth posture for the ES-compat routes was not fully confirmed.\n - No user feedback/corrections were received during the session.\n\n5. **Problem Solving:**\n - Confirmed the decisive enabler: `panic = \"abort\"` ships in the release binary, so the user's \"only matters if it kills the process\" bar is met by any reachable panic.\n - Traced a complete, verified attack chain for the panic: request body parsed into an arbitrary `Value` (array/scalar/number/bool) → passed unguarded into `Engine::process_through_pipeline` → `Pipeline::process` → plugin `doc[...] = ...` → serde_json `index_or_insert` panic → abort.\n - Identified the specific input-validation gap that makes it reachable via `_bulk`: object-ness is enforced for `index` actions but not for `create` actions, while the pipeline block admits both.\n - Systematically cleared the areas the user asked about that turned out to be properly hardened (zip extraction, object-store mirror, symlink walk, html tokenizer, PDF subprocess, decompression caps, regex/ReDoS) so the final report can say \"checked and defended\" rather than speculating.\n\n6. **All user messages:**\n - Message 1 (the only substantive user message): \"You are doing a security review of the XERJ search engine (Rust) at /root/ab-run-x1/repo. Focus: INGEST OF UNTRUSTED DOCUMENTS. Read thoroughly: engine/crates/xerj-wasm/src/pipeline.rs (~1370 lines), engine/crates/xerj-wasm/src/builtins.rs (~1300 lines), engine/crates/xerj-wasm/src/lib.rs, The autoindex hostile-file parsing: engine/crates/xerj-autoindex/src/sniff.rs, and any archive/zip/tar/gz handling in xerj-autoindex (search for zip, tar, gz, decompress, symlink, path traversal, ..). Hunt for REAL exploitable bugs a malicious document/corpus provider could trigger when their documents are indexed: Path traversal on extraction (archive entries with ../ or absolute paths writing outside the data dir); Zip-slip / symlink following; Unbounded decompression (zip bombs) — only if dramatic; In the pipeline/builtins: any command execution, file access, network access reachable from document content; regex catastrophic backtracking from doc-supplied patterns; script/eval of doc-supplied code; Integer overflow in length prefixes leading to allocation or slice OOB; Panics reachable from malformed docs (a panic in Rust = crash of handler thread; only matters if it kills the process). For each candidate: file:line, exact code quote, attack path from document bytes to the bug. Verify the call chain: who calls these functions with untrusted input (search callers in xerj-engine bulk/index paths). Report a ranked list of concrete candidates. No style nits.\"\n - Message 2: \"CRITICAL: Respond with TEXT ONLY. Do NOT call any tools... Your task is to create a detailed summary of the conversation so far...\"\n - Security-relevant constraints from the system prompt that remain in force: READ-ONLY exploration; no file creation/modification/deletion/move; no temp files; no redirect operators or heredocs writing files; \"Do NOT Write report/summary/findings/analysis .md files. Return findings directly as your final assistant message.\"\n\n7. **Pending Tasks:**\n - Emit the final ranked findings report as the assistant's final text message (no files), with file:line, exact code quotes, attack paths, and verified call chains, ranked most-severe first, including explicitly-cleared areas.\n\n8. **Current Work:**\n Immediately before the summary request I had just completed the last verification pass on decompression bounds (`extract/mod.rs:82 MAX_WHOLE_FILE = 64 << 20`; `open_reader` line 114-126 using `MultiGzDecoder` + `.take(n)`; the only uncapped-ish `read_to_end` at extract/mod.rs:134 is capped, and pdf.rs:1974 is test code). All evidence needed for the report is gathered. The finding set is:\n\n **Candidate 1 (Critical): unauthenticated/authenticated single-request remote process kill via non-object document + ingest pipeline + serde_json IndexMut panic, amplified by `panic = \"abort\"`.**\n - Root: `/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/builtins.rs:285` (`doc[&self.field] = self.value.clone();`) and siblings at lines 68, 132, 145, 155, 162, 168, 174, 182, 630, 728, 771, 870.\n - Entry A (simplest): `POST /{index}/_doc?pipeline=p` with body `[]`/`5`/`\"x\"` — `es_compat.rs` `index_doc_auto` parses raw bytes into `Value` with no object check (~line 2800) and calls `process_through_pipeline(pipeline, vec![doc])` at line 2810.\n - Entry B: `POST /v1/indices/{name}/ingest?pipeline=p` — `native.rs:2642-2650`, `IngestRequest::Single(Value)`.\n - Entry C: `_bulk` with `{\"create\":{\"_index\":\"i\",\"pipeline\":\"p\"}}` + body `[1,2,3]` — `bulk.rs:858-864` parses `create` bodies without the object check that `index` bodies get at `bulk.rs:827-845`; pipeline block at `bulk.rs:1745` admits `create`.\n - Entry D (no query param): an index with `index.default_pipeline` set (`engine.rs:4087 default_pipeline_for`).\n - Entry E (chained): `_reindex` with `dest.pipeline` over stored non-object sources (`es_compat.rs:23864`).\n - Amplifier: `/root/ab-run-x1/repo/engine/Cargo.toml:165 panic = \"abort\"`; no `catch_unwind` on the path.\n\n **Candidate 2 (Lower / defence-in-depth note): `_bulk` `create` accepts a non-object document body at all** (`bulk.rs:858-864` vs the `index`-only check at 827-845) — the input-validation gap that enables Entry C, and a precondition for Entry E.\n\n **Cleared areas (report as checked-and-defended, with the mitigating code cited):** `harvest/source.rs:151-199 extract_zip` (sanitize + symlink skip + 2 GiB cap), `objsource.rs:856` mirror.join guarded by `source.rs:257 classify_key`, `walk.rs:178-223 escaped_or_hidden_target`, `sniff.rs` (archives never opened; `archive_advice` line 1083), `extract/html.rs:156-158` (byte/char-boundary alignment), `extract/pdf.rs:936-1098` subprocess containment, `extract/mod.rs:82/131-138` + `open_reader` decompression caps, `pipeline.rs` (config-only, no doc-derived regex), Rust `regex` (no catastrophic backtracking), no fs/exec/network in xerj-wasm (Cargo.toml deps confirm).\n\n9. **Optional Next Step:**\n Write and return the final ranked findings report as plain text (no files, no tool calls), per the user's instruction: \"For each candidate: file:line, exact code quote, attack path from document bytes to the bug. Verify the call chain... Report a ranked list of concrete candidates. No style nits.\" The report will lead with the `builtins.rs` `doc[...] = ...` IndexMut panic chain (with all five verified entry points and the `panic = \"abort\"` amplifier), then the `bulk.rs` create/index object-check asymmetry, then the cleared/defended areas with citations.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /root/.claude/projects/-root-ab-run-x1-repo/d92fc5d7-2660-4f81-a5a4-5f7578a7ad83.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened."},"isVisibleInTranscriptOnly":true,"isCompactSummary":true,"uuid":"56a2a230-bf9b-43af-9e10-90ac3ddf6ee1","timestamp":"2026-10-01T15:50:02.419Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD","slug":"flickering-imagining-perlis"}
{"parentUuid":"56a2a230-bf9b-43af-9e10-90ac3ddf6ee1","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002030427de3b91cca6334a22","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"thinking","thinking":"The create path: `execute_bulk_action` is called with `doc_body` regardless of object-ness. So a non-object body for `create` does flow to indexing. That's enough — I'll state it as \"reaches execute_bulk_action unvalidated\" without overclaiming on the storage outcome.\n\nI have everything. Write the final report now, as text.","signature":"53469a8980584f25b13c7bcd"}],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}},"attributionAgent":"Explore","type":"assistant","uuid":"300ea44e-15a5-44e1-84bc-f085bd7108b3","timestamp":"2026-10-01T15:50:31.968Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD","slug":"flickering-imagining-perlis"}
{"parentUuid":"300ea44e-15a5-44e1-84bc-f085bd7108b3","isSidechain":true,"agentId":"afcecc181ae7e2aa9","message":{"id":"msg_20261002030427de3b91cca6334a22","type":"message","role":"assistant","model":"glm-5.3-flash","content":[{"type":"text","text":"Findings from the untrusted-document ingest review. Ranked most severe first.\n\n---\n\n## 1. CRITICAL — Any non-object document body + ingest pipeline = whole-process abort\n\n**Root cause.** `serde_json::Value`'s `IndexMut` impl (`index_or_insert`) panics for any value that is neither an object nor `null`. Nine plugin sites in `/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/builtins.rs` use `doc[...] = ...` on a document they never validate as an object:\n\n| line | plugin | code |\n|---|---|---|\n| 285 | `add_field` | `doc[&self.field] = self.value.clone();` |\n| 870 | `set` | `doc[&self.field] = self.value.clone();` |\n| 630 | `copy_field` | `doc[&self.target] = val;` |\n| 728 | `convert` | `doc[&self.field] = v;` |\n| 771 | `split` | `doc[&self.field] = Value::Array(parts);` |\n| 68 | `json_parse` | `doc[&self.target] = parsed;` |\n| 132/145/155/162/168/174/182 | `timestamp_parse` | `doc[self.target_field()] = Value::String(iso);` |\n\n`Pipeline::process` (`/root/ab-run-x1/repo/engine/crates/xerj-wasm/src/pipeline.rs:232-253`) dispatches straight into these with no shape check, and `Pipeline::process_batch` (line 259) iterates the batch unguarded.\n\n**Amplifier.** `/root/ab-run-x1/repo/engine/Cargo.toml:165` — `[profile.release] panic = \"abort\"`. So this is not \"a handler thread dies\": it is the whole server process. There is no `catch_unwind` anywhere on the ingest path (`Engine::process_through_pipeline`, `/root/ab-run-x1/repo/engine/crates/xerj-engine/src/engine.rs:4276-4300`, calls `pipeline.process_batch` directly; the `catch_unwind`s that do exist are in `ingest_memory.rs:994`, `collection_publication.rs:178`, `segment_cache_budget.rs:282`, `index.rs` — none on this path).\n\n**Verified call chain — five distinct entry points, all reached from raw request bytes:**\n\n- **A. `POST /{index}/_doc?pipeline=P`** — `/root/ab-run-x1/repo/engine/crates/xerj-api/src/es_compat.rs` ~2800 parses the body into an arbitrary `Value` (`let doc: Value = match serde_json::from_slice(&body)`) with no object check; `apply_ignore_malformed` explicitly returns non-objects unchanged (~39256); then `state.engine.process_through_pipeline(pipeline, vec![doc])`. Body `[]` / `5` / `\"x\"` / `true` ⇒ panic ⇒ abort.\n- **B. `POST /v1/indices/{name}/ingest?pipeline=P`** — `/root/ab-run-x1/repo/engine/crates/xerj-api/src/native.rs:2642-2650`: `IngestRequest::Single(Value)` / `Batch(Vec<Value>)`, docs passed verbatim to `process_through_pipeline`.\n- **C. `_bulk` with a `create` action** — `/root/ab-run-x1/repo/engine/crates/xerj-engine/src/bulk.rs`. The object check at lines 827-845 runs only when the first non-whitespace byte is not `{` **and is applied to `index` actions**; the `create` branch at 858-864 does `serde_json::from_slice::<Value>(...)` with no shape check. The pipeline block at 1745-1776 admits both: `if matches!(action_type.as_str(), \"index\" | \"create\") { ... process_through_pipeline(pid, vec![input]) }`.\n- **D. No query param needed** — `index.default_pipeline` on the index (`engine.rs:4087 default_pipeline_for`) makes any write to that index carry the pipeline.\n- **E. `_reindex`** — `es_compat.rs:23864` runs stored `_source` values through `dest.pipeline`; a non-object source stored via (C) detonates here, possibly on a different index than the one that accepted it.\n\n`Value::Null` is the only safe non-object (serde_json converts it to an object). Arrays, strings, numbers, booleans all panic.\n\n**Attack cost:** one request where a pipeline already exists or `default_pipeline` is set; two requests (`PUT /_ingest/pipeline/p` then `POST /i/_doc?pipeline=p` with body `[]`) otherwise. Every bulk write from every client is killed with it — a single-document, single-request remote DoS of the entire node.\n\n**Fix shape:** coerce/reject non-object documents at the pipeline boundary (`Value::as_object_mut` guard in `process_batch`, or a `ProcessAction`/error return), and/or wrap plugin dispatch in `catch_unwind` given `panic = \"abort\"`.\n\n---\n\n## 2. MEDIUM — `_bulk` accepts a non-object document body for `create` at all\n\n`/root/ab-run-x1/repo/engine/crates/xerj-engine/src/bulk.rs:827-845` enforces \"document body must be a JSON object\" only on the `index` branch; `create` (and `update`) bodies go through the unchecked `from_slice` at 858-864 and reach `execute_bulk_action` (~2155) unvalidated. Downstream the same asymmetry repeats: the date check guards with `.and_then(Value::as_object)` (2087) and numeric coercion with `.and_then(Value::as_object_mut)` (2136), so a non-object body silently skips both instead of being rejected. This is the enabler for entry C above and the precondition for entry E (it plants a non-object `_source` that `_reindex` later feeds to a pipeline). Fix: apply the same first-byte/object check to `create` and `update`.\n\n---\n\n## Cleared — checked and defended (no finding)\n\n- **Zip extraction / zip-slip / symlink entries** — `/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/harvest/source.rs:151-199` (`extract_zip`): skips `entry.is_symlink()`, runs every name through `sanitize_entry_path` (206-232: rejects absolute paths, `..`, `.`, empty, NUL, `:`, backslash), caps total decompressed bytes with `take(limit+1)` against `MAX_EXTRACT_BYTES = 2 << 30` and bails. Only caller is operator-configured (`xc.rs:431`).\n- **Object-store mirror path traversal** — `objsource.rs:856` `run.mirror.join(&entry.rel)` looks dangerous, but `rel` is `key.strip_prefix(prefix)` (1265) that has already passed `classify_key` (`source.rs:257-300`), which Skips `..`, `.`, empty components, leading `/`, backslash, control chars, >255-byte components, trailing `.`/space, Windows reserved names, dot-prefixed components.\n- **Symlink following in the walk** — `/root/ab-run-x1/repo/engine/crates/xerj-autoindex/src/walk.rs:178-223` (`escaped_or_hidden_target`): only `NotFound` from `canonicalize` is treated as \"nothing to leak\"; everything else is refused. Out-of-root requires an explicit operator flag and even then stores the *resolved* path (420-422), so the bytes read are the bytes judged. Documented residual: hard links (`walk.rs:360-367`) — inherent, no attacker needed.\n- **Archives in autoindex** — never opened. `sniff.rs` `archive_advice` (1083) states it; zip is touched only via `by_index_raw` for `word/document.xml`; reads are bounded (`PREFIX = 8192`, `GIF_PREFIX = 1 MiB`).\n- **Unbounded decompression** — `extract/mod.rs:82` `MAX_WHOLE_FILE: u64 = 64 << 20`, enforced by `read_whole` via `open_reader(path, gzip, Some(cap + 1))` → `MultiGzDecoder` + `.take(n)`. Not dramatic; not a finding.\n- **ReDoS** — the Rust `regex` crate is linear-time by construction, and doc-supplied patterns are refused: `pipeline.rs:556` rejects `grok`/`patterns` and `pattern_definitions` as `UnsupportedOption`; every other regex in `builtins.rs` is a compile-time literal.\n- **Exec / file / network access from document content** — `xerj-wasm` has no fs, net, or process dependencies at all (see `lib.rs:1-98`). The only `Command` in autoindex is the PDF worker (`extract/pdf.rs:936-1098`), whose binary comes from `XERJ_PDF_WORKER_BIN` env or `current_exe()` — operator-controlled, not document-controlled — and which runs in a `setpgid`'d child with `RLIMIT_AS`, capped stdout/stderr, a 120 s timeout and a process-tree SIGKILL.\n- **Non-panicking plugins** — `AppendPlugin` (913 `as_object_mut` guard + early return), `RemoveNullPlugin` (952), `FieldRenamePlugin` (219), `DropFieldPlugin` (251), `Lowercase`/`Uppercase` (799/829 `get_mut`), `UrlDecodePlugin` (978-997, manual byte loop with correct `i + 2 < bytes.len()` bound and `to_digit(16)?`/`from_utf8().ok()` fallthrough), `RoutePlugin`, `GrokPlugin`, `PiiRedactionPlugin` (recursion bounded by serde_json's 128-level parse limit).\n- **`_simulate`** — `es_compat.rs` `run_inline_pipeline_on_doc` (~29747) defaults `_source` to an object and uses `as_object_mut` guards. Safe.\n- **`extract/html.rs`** — `parse(html: &str)` slices after `bytes[i] == b'<'` on `html.as_bytes()` (156-158); a matching byte index is always on a char boundary, so no panic."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":51920,"cache_creation_input_tokens":0,"cache_read_input_tokens":8960,"output_tokens":2377,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[],"speed":"standard"},"stop_details":null},"attributionAgent":"Explore","type":"assistant","uuid":"c92e5052-3581-42cf-a0bc-caf9cbc1428a","timestamp":"2026-10-01T15:51:19.495Z","userType":"external","entrypoint":"sdk-cli","cwd":"/root/ab-run-x1/repo","sessionId":"d92fc5d7-2660-4f81-a5a4-5f7578a7ad83","version":"2.1.197","gitBranch":"HEAD","slug":"flickering-imagining-perlis"}