Commit graph

1790 commits

Author SHA1 Message Date
LLLin000
27e45f9419 feat(#37): auto-backup fulltext before rebuild
backup_render_before_rebuild() copies render/fulltext.md (and
render-map.json, heading-events.json) to versions/v{N}/ before
rebuild overwrites them. Creates/updates versions/manifest.json
with version metadata. Idempotent: skips when no render exists.

Hook placed between phase 3 and phase 4 in _rebuild_one_paper.

6 new tests.
2026-07-10 00:34:44 +08:00
LLLin000
06fec04651 feat: Phase 0, 1, 3a — legacy OCR fix, ChromaDB migration, search bar UI
Phase 0 (#35): _needs_derived_rebuild returns (False, 'legacy_ocr') for
papers without structured blocks and derived_version. _can_rebuild adds
has_structured check. No misleading rebuild suggestions for legacy users.

Phase 1 (#36): migrate_chroma_to_vec0() copies existing ChromaDB vectors
to vec0 tables with zero API calls. Idempotent (skips by paper_id).
delete_paper_vectors() cleans both ChromaDB and vec0. CLI: embed migrate.
5 new tests.

Phase 3a (#39): Search bar in collection panel — two-mode input
(M metadata / @ deep) with card results display. JSON output parsed
from search/retrieve CLI. 289 lines TypeScript, 175 lines CSS.
Build passes clean.

Co-authored-by: Phase0LegacyOcr <agent>
Co-authored-by: ChromaMigration <agent>
Co-authored-by: SearchBarUI <agent>
2026-07-10 00:02:02 +08:00
LLLin000
8699733b09 feat(#21): show structured_content_hash in paperforge status output
Add structured_content_hash field to OCRMaintenanceRow for display.
- Terminal table: new 'Hash' column showing first 12 chars of hash
- JSON output: structured_content_hash included in to_dict()
- Empty hash displayed as '-'
2026-07-09 18:14:15 +08:00
LLLin000
d24c78c5dc feat(#27 #28 #29 #30 #32): migrate write/read/status/build_state from ChromaDB to sqlite-vec
#27: write_encoded_payload and delete_paper_vectors use sqlite-vec
  - builder.py: writes to vec0 tables + companion meta tables
  - _chroma.py: delete_paper_vectors deletes from vec0 + meta by paper_id
  - Stores body_units_hash, object_units_hash, retrieval_policy_version in meta tables

#28: merge_retrieve and retrieve_chunks use vec0 k-NN search
  - search.py: vec0 k-NN queries with companion meta JOINs
  - Same dedup/per-paper-cap logic, same result shapes

#29: build_state migrated from JSON file to SQLite build_state table

#30: E2E embed+retrieve test with sqlite-vec + FixedProvider
  - 3 tests: body roundtrip, source correctness, per-paper cap

#32: E2E OCR pipeline test with fixture PDFs

Additional changes:
- schema.py: bump to v6, add hash/policy columns to vec companion meta tables
- embed.py: _assert_collections_healthy uses sqlite-vec; resume hash checks read from meta tables
- status.py: chunk counts from SQL COUNT on companion tables
- Removed unused get_collection/embed_paper imports from embed.py
- All tests updated: 76 pass (was 72, +4 new E2E tests, +4 for migration)
- FixedFixedProvider to generate 1536-dim vectors (matching vec0 schema)
- Fixed health check tests for sqlite-vec path
2026-07-09 17:52:45 +08:00
LLLin000
49f84a1aad feat(#31): OpenAICompatibleProvider uses openai SDK with requests fallback
Rewrite embedding provider to use openai.OpenAI client instead of
raw requests.post. Old code preserved in requests_fallback.py,
selectable via VECTOR_DB_PROVIDER_TYPE env/setting.

Changes:
- paperforge/embedding/providers/openai_compatible.py: rewrite to SDK
- paperforge/embedding/providers/requests_fallback.py: NEW old impl
- paperforge/embedding/_config.py: add get_provider_type()
- tests/test_openai_compatible.py: 6 new tests (encode, timeout,
  provider_type switch, no-key error, custom base url)

feat(#33): E2E test fixtures — 3 synthetic PDFs + expected outputs

3 synthetic papers generated with PyMuPDF, each 3 pages:
- paper_a: The Effect of Machine Learning on Clinical Outcomes
- paper_b: A Randomized Trial of Remimazolam vs Propofol (with tables)
- paper_c: Deep Learning for Medical Image Segmentation (with figures)

Changes:
- tests/fixtures/papers/: 3 PDFs
- tests/fixtures/expected_outputs/: expected blocks + body units
- tests/conftest.py: e2e_fixture_dir + synthetic_paper_paths fixtures

feat(#26): sqlite-vec schema — vec0 virtual tables + build_state

Schema version bumped 4→5. Adds:
- 3 vec0 virtual tables: vec_fulltext, vec_body, vec_objects (1536-dim)
- 3 companion metadata tables: vec_*_meta (paper_id, chunk_index, text)
- build_state table (key/value/updated_at)
- ensure_vec_extension() in db.py for extension loading

Changes:
- paperforge/memory/schema.py: schema v5, new tables in ensure_schema()
- paperforge/memory/db.py: ensure_vec_extension() helper
- tests/test_vector_schema.py: 5 new tests (tables, virtual, idempotent, v5)
2026-07-09 17:15:19 +08:00
LLLin000
970f147d59 chore(deps, markers): add sqlite-vec dep, e2e_fast marker
- Add sqlite-vec>=0.1.0 to vector optional deps
- Add e2e_fast marker for quick E2E tests
2026-07-09 17:12:48 +08:00
LLLin000
2b23ad716f feat(#20): hash-based OCR change detection — two-tier mtime+xxhash staleness
Replace version-constant-only detection with two-tier content-hash
detection against blocks.structured.jsonl.

Tier 1 (stat): compare st_mtime + st_size of blocks.structured.jsonl
against stored values in meta.json. Microsecond skip for unchanged files.

Tier 2 (hash): compute xxhash of the file when stat changes. If the hash
matches stored structured_content_hash, update mtime/size only (false
alarm recovery). If it differs, mark paper for rebuild.

Changes:
- pyproject.toml: add xxhash>=3.4.0 dependency
- paperforge/worker/ocr_versions.py: add compute_structured_hash()
- paperforge/worker/ocr_rebuild.py: _apply_post_rebuild_version_flags()
  writes hash+mtime+size to meta.json when vault+key provided
- paperforge/commands/ocr.py: _needs_derived_rebuild() two-tier check
  before version-constant fallback
- New tests: hash compute (hex, determinism, missing file),
  stat skip, hash match (false alarm recovery), hash mismatch trigger

61 tests pass (14 existing + 3 hash rebuild + 4 hash compute + 40 other).
2026-07-09 17:09:28 +08:00
LLLin000
9d150d1d95 test: add regression assertion for health-probe get(limit=1) and guard against query() 2026-07-09 02:17:49 +08:00
LLLin000
1397063c30 fix: replace dim-dependent query probe with metadata get(limit=1) in health check
The 256-dim zero vector probe crashes on any collection with real
1536-dim embeddings (text-embedding-3-small). get(limit=1) has no
dimension dependency and still verifies collection accessibility.
2026-07-09 02:17:14 +08:00
LLLin000
a588bd884a fix(#18): atomic build_state writes with .tmp fallback recovery
test(#17): integration tests for embed pipeline against EphemeralChromaDB

- build_state: write to .tmp first, leave as backup; read falls back to
  .tmp if main file corrupt. Extracted default/fallback state helpers.
- integration: 10 tests covering payload prep, encode→write→retrieve
  round-trip for all 3 collections, per-paper cap, delete, and
  encode_paper_job — all against real ChromaDB EphemeralClient with
  mocked provider
2026-07-09 02:03:20 +08:00
LLLin000
cc064bd74a fix: address 5 PR9 embedding pipeline issues from triage
- #13: Critical — swap delete/write order in _complete_one (write new
  vectors before deleting old ones) to prevent data loss on write failure
- #12: Add logger.warning() to 3 resume-skip except blocks so silent
  re-embed fallbacks are observable
- #14: Add lightweight HNSW query probe to _assert_collections_healthy
- #11: Log collection query failures in merge_retrieve instead of silent
  continue
- #16: Reuse provider across payloads in encode_paper_job — one creation
  per worker per paper instead of per payload
2026-07-09 01:46:22 +08:00
LLLin000
45022c3e16 docs: archive superpowers specs/plans, commit PR9A-C plan files
- Archive 173 design/plan/analysis docs from docs/superpowers/ →
  docs/archive/superpowers/ (all features shipped)
- Commit 5 PR9A-C plan files to docs/plans/ (historical record)
- Rebuild plugin bundle (main.js: 2172→49 lines, minified)
- Fix settings.ts type assertion
2026-07-09 00:39:39 +08:00
LLLin000
077c190b60 docs: update project management for PR9A-C embedding pipeline work 2026-07-09 00:30:50 +08:00
LLLin000
d94096f4d8 fix: plugin shows total chunks across all collections
Previously only showed paperforge_fulltext chunk_count (345).
Now sums chunk_count + body_chunk_count (14338) + object_chunk_count (5972).
2026-07-07 02:18:04 +08:00
LLLin000
9c85b30d7f fix: write_vector_build_state fallback when file locked
Windows: tmp.replace(path) fails when Obsidian plugin is reading
vector-build-state.json. Fall back to direct write to avoid crashing
the embed build. Stale tmp files cleaned up lazily.
2026-07-07 02:12:27 +08:00
LLLin000
db2988d8f0 PR9C: Streaming embed pipeline with continuous progress
Replace two-phase (prepare all, then encode+write) with sliding-window
pipeline. Maintains bounded in-flight window (max_workers * 4 = 16),
emits EMBED_PROGRESS from the first paper completion (~2s vs ~30s).

Key changes:
- producer/consumer loop: prepare + submit one paper at a time
- wait(FIRST_COMPLETED) in main thread for encode results
- processed_count = skip + embedded, monotonic EMBED_PROGRESS
- resume skip and no-payload paths also advance processed_count
- encode failure fails closed (return 1, no silent skip)
- removed PR9B_BATCH_SIZE and _batched() (replaced by sliding window)
- 4 integration tests for progress counting, failure, and write cycle
2026-07-07 02:04:12 +08:00
LLLin000
7d5fffda16 fix: emit EMBED_PROGRESS during Phase 1 (PREPARE)
Previously Phase 1 processed all papers silently, then Phase 2+3
emitted EMBED_PROGRESS. The plugin's progress bar showed 0/729 for
~30s during preparation, then jumped, looking disconnected.

Now Phase 1 emits EMBED_PROGRESS for each prepared paper, so the
progress bar starts updating immediately. Phase 2+3 continues with
its own counter for actual encode/write progress.
2026-07-07 01:41:50 +08:00
LLLin000
2022785101 fix: add missing jobs list initialization
PaperEmbeddingJob list was used (jobs.append) but never initialized,
causing NameError on embed build. Added
before the PREPARE loop.
2026-07-07 01:35:38 +08:00
LLLin000
a71796536a fix: OpenAICompatibleProvider uses requests instead of openai client
The openai Python client (v2.44.0) has compatibility issues with
SiliconFlow API — calls hang indefinitely even with TCP keepalive.
Replace with plain requests, which is simpler and works reliably.

- Removed openai/httpx/socket dependencies
- Uses requests.post() directly, 60s timeout
- ~0.3s per batch vs 2.3s+ with openai client
2026-07-06 23:15:58 +08:00
LLLin000
6ff0f6d38b PR9B: Embed Parallel Encode
- Four new dataclasses: EmbeddingPayload, EncodedPayload, PaperEmbeddingJob, PaperEncodedBundle
- prepare_legacy/body/object_payload: extract prepare phase from legacy embed functions
- encode_payload / encode_paper_job: worker-thread-safe encode functions
- write_encoded_payload: ChromaDB serial write
- prepare_payloads_for_entry: routing to correct prepare function
- Existing embed_body_units/embed_paper/embed_object_units refactored as wrappers
- Embed main loop: three-phase pipeline (PREPARE -> ENCODE -> WRITE) with ThreadPoolExecutor
- Bounded batch processing (BATCH_SIZE=8, MAX_WORKERS=4)
- Encode-success-gated delete: old vectors only removed after encode succeeds
- 23 regression tests for new functions
2026-07-06 22:41:25 +08:00
LLLin000
89f5a3fce6 PR9A: Resume & Rebuild Correctness
- OCR rebuild --all: version/artifact-based selection via _needs_derived_rebuild()
- --status and explicit keys: manual override, no version filter
- Removed .done.{key} checkpoint markers from selection logic
- _apply_post_rebuild_version_flags now writes derived_version
- Embed resume entry: three-gate protection (stale state / missing DB / corrupt DB)
- _pid_alive() cross-platform PID health check
- _assert_collections_healthy() explicit ChromaDB probe
- 14 regression tests for selection logic, version flags, and resume guards
2026-07-06 22:33:08 +08:00
LLLin000
6afcdc1830 fix: PR8.1 — status healthy init + object_units rebuild + version bump
- status.py: healthy=True init before if exists: (was UnboundLocalError
  when vector DB doesn't exist)
- manifest.py: RETRIEVAL_POLICY_VERSION l4.body.v1 → l4.body.v2 to
  trigger object_units rebuild with PR7 fix (unit_id fallback)
- Object_units corrected from 20→311 after rebuild (was INSERT OR
  REPLACE overwrite from old empty unit_id)
- Coverage parity: 20 papers have body_units = 20 have object_units 
  (body=811 chunks, object=311 chunks, expected difference due to
   section-split vs 1:1 caption structure)
- Unit tests: 97 pass (subset)
2026-07-06 20:08:51 +08:00
LLLin000
0dfbf2a68d feat: PR 8 — Object Vector Retrieval (paperforge_objects collection)
New paperforge_objects collection in ChromaDB for figure/table caption
vector search, completing the memory layer retrieval triad:

  paperforge_fulltext → legacy_chunk
  paperforge_body     → body_unit
  paperforge_objects  → object_unit (NEW)

Changes:
- manifest.py: compute_object_units_hash(), manifest records both hashes
- _chroma.py: _COLLECTION_NAMES includes paperforge_objects
- builder.py: get_object_units_for_embedding() + embed_object_units()
- status.py: object_chunk_count, total_chunks
- state_snapshot.py: write_vector_runtime() extended with new fields
- search.py: 3rd collection, dict-based source mapping, object_kind/label
- __init__.py: exports for new functions
- commands/embed.py: _has_object_units_in_db, body+object structured
  path routing with dual-hash resume, extended counters
- Test fix: test_build_paper_manifest data complete for hash functions

Verification: 20 object vectors embedded, all per-paper counts match,
status total consistent (58266 = 57435 + 811 + 20),
object caption queries return object_unit results via merge_retrieve.
Unit tests: 153 pass, 1 skip.
2026-07-06 19:58:46 +08:00
LLLin000
e551f79a77 fix: PR 7 post-test hardening — object units, node_id, expanded tests
P0 fixes from test report review:
- object unit_id: fallback to f"{obj_type}:p{page}:{block_id}" when
  figure_id/table_id missing (prevents DB overwrite on INSERT OR REPLACE)
- object caption_key: page-qualified f"p{page}:{caption_bid}" to match
  page-qualified subtree_block_ids in find_owning_node
- object block_map: page-qualified keys for consistency with body_units
- structure node_id: changed from sec:{block_id} to sec:p{page}:{block_id}
  for stability (reduces vector ID churn from emitted_order changes)

New tests:
- Section 4b: Object units DB persistence (unit_id unique, non-empty labels,
  DB count == list count after upsert)
- Section 5b: Coverage gate (v2_tree / render_map / body_papers counts)

Layer A: 1669/1669 pass (+60 checks from 4b + 5b)
Unit tests: 153 pass, 1 skip
2026-07-06 19:34:05 +08:00
LLLin000
01461330bb fix: final hardening — policy revision + Layer A all green
- _body_unit_role_kind now excludes only reference_item/reference_heading
  (per policy: everything in fulltext except ref zone)
- backmatter_body unit_kind removed; all units are 'body'
- bounds_map in structure_tree uses page-qualified key (fixes collision
  when same block_id appears on different pages)
- Layer A test plan: emitted_ids uses page-qualified keys + handles
  block_id=0 (falsy value)
- Layer A: 1609 passed, 0 failed on real vault (22 papers)
- Unit tests: 152 passed, 1 pre-existing skip
2026-07-06 19:08:54 +08:00
LLLin000
77a6e0cfec fix: heading→emitted events, backmatter→heading events, page-qualified keys
- Section/subsection headings now appear in BOTH heading_events and
  emitted_block_events (emitted_as='heading') for complete event stream
- Backmatter headings (Funding/Acknowledgments/Data Availability/Conflicts)
  now generate heading_events → appear as structure tree sections with
  their own body_units
- Page-qualified block IDs (p{page}:{block_id}) in tree own/subtree_block_ids
  and body_units block_map: eliminates ambiguous block_id collisions when
  same block_id appears on multiple pages in real OCR data
- TC-9.2 wording fix, KEYS empty guard, global unit_id uniqueness check
2026-07-06 18:19:17 +08:00
LLLin000
897afdaecb fix: token cap recursive split + policy version check + test plan update
- _split_if_oversized: recursive _halve_text until every part <= 1000 tokens
- _incremental_units_only: also checks retrieval_policy_version match
- _rebuild_paper_units: use RETRIEVAL_POLICY_VERSION constant
- Functional test plan: Layer A (artifact) + Layer B (API), all 8 review
  fixes incorporated (persisted artifacts, no jump-assertion, stronger
  object/backmatter/abstract tests, proper embed flow)
2026-07-06 17:05:13 +08:00
LLLin000
1ef0899fec docs: comprehensive functional test plan for memory layer
10 sections covering Render Events, Structure Tree, Body Units,
Object Units, FTS, Content Discovery, Memory Builder, Embed Build,
Retrieve Merge, and Regression. Includes auto-test script skeleton.
2026-07-06 16:59:31 +08:00
LLLin000
9f79ac3482 fix: hardening — FTS per-paper, object_units keys, unit_id collision, resume hash
P0-1: FTS per-paper insert — move SELECT INTO body_units_fts inside the
per-paper loop with WHERE paper_id = ? to avoid re-inserting other papers'
rows during full rebuild. Fix sqlite3.DatabaseError on empty FTS table.

P0-2: object_units real role_index keys — read from 'captions'/'tables'
(what build_role_indexes actually outputs) with fallback to old key names.

P1-1: unit_id collision for mixed body/backmatter — include unit_kind
suffix (:backmatter_body) in unit_id. Also fix duplicate tree node_ids
(block_id reused on different pages) by appending order{emitted_order}.

P1-2: Embed resume body_units_hash — add compute_body_units_hash() to
manifest.py, write hash + retrieval_policy_version to Chroma metadata,
resume compares both before skipping.
2026-07-06 16:56:33 +08:00
LLLin000
cb845362de fix: block_map in build_body_units handles duplicate block_ids across pages
Real OCR output has the same block_id on multiple pages (e.g. running
headers). block_map[str(bid)] = b overwrites correct entries with
wrong-page duplicates. Fix: prefer blocks with non-empty text content
when multiple blocks share the same block_id.
2026-07-06 16:50:12 +08:00
LLLin000
76aaedf4cc feat: PR 5 — Retrieve uses merge_retrieve from dual collections
- retrieve command calls merge_retrieve instead of retrieve_chunks
- Checks total_chunks (both collections) for empty DB detection
- Display uses section_path field from merge_retrieve response format
2026-07-06 16:43:07 +08:00
LLLin000
9f47245179 feat: PR 4 — Dual collection embedding with body_units
- get_collection(name=) supports paperforge_fulltext or paperforge_body
- delete_paper_vectors deletes from both collections
- embed_body_units + get_body_units_for_embedding (reads from memory DB)
- Status reports chunk_count, body_chunk_count, total_chunks
- Embed build routes to body_units path when DB has body_units
- merge_retrieve queries both collections with unit-level dedup
2026-07-06 16:42:54 +08:00
LLLin000
cb0eabddde feat: PR 3 — Content Discovery no silent fallback
- Add _get_body_coverage helper (body_papers, ocr_papers, library_papers)
- _run_body_unit_discovery returns coverage + next_action on empty results
- FTS query exceptions return error + coverage (no metadata fallback)
- Keep _run_compat_content_discovery for other callers
2026-07-06 16:42:41 +08:00
LLLin000
8dca070b75 feat: PR 2 — Memory Builder incremental update
- Replace _read_result_hash with _resolve_ocr_result_hash (3-level fallback:
  result-hash.txt → SHA-256 of structured artifacts → meta.json derived_version)
- Change fast-path to incremental mode: hash-match calls _incremental_units_only
  instead of early return
- _incremental_units_only: per-paper OCR hash comparison, rebuild only changed
- _rebuild_paper_units: DELETE + rebuild + insert + FTS refresh
- _upsert_body_units updated with schema v4 columns
2026-07-06 16:42:28 +08:00
LLLin000
288829bb5b feat: PR 1 — nested structure tree + body_units correctness
- RenderOutput dataclass with heading_events/emitted_block_events tracking
- Stack-algorithm structure tree with own/subtree block IDs
- Recursive body_units builder with role helper + token cap splitting
- Schema v4: section_path_json, section_level, section_title, part_ordinal
- Phase 4/5 reorder in ocr_rebuild.py and ocr.py
- 12 new test cases for tree nesting, own_block_ids, rendered-order intervals
2026-07-06 16:42:08 +08:00
LLLin000
b12ef301f9 fix: two regression fixes
1. sidecar match record now includes 'text': caption legend was
   missing from the rendered figure_001.md because the sidecar
   materialization did not copy the text field.

2. _find_table_caption_continuation now rejects actual <table> HTML
   blocks as continuations. Previously the very next block after a
   truncated caption (which was the table_html itself) got merged into
   caption_text.
2026-07-06 02:49:42 +08:00
LLLin000
36d7f79d50 fix: rescue single narrow side-caption figure layouts
Add a narrow sidecar rescue for the 37-like pattern:
- one formal narrow figure caption on a page
- same-row right-side image
- no x-overlap required
- bounded x-gap and strong y-overlap
- only when primary same-page matching missed the caption

This preserves the existing >=2 narrow-caption sidecar behavior while
rescuing left-caption/right-image layouts that previously fell to
cross_page_reservation.

Verified on real vault:
- 37LK5T97 page 2: FIG. 1 now matches as figure_001 via sidecar
- QGCAFI3P page 4: narrow side-caption rescued
- QZXT9L27 page 11: narrow side-caption rescued

Targeted tests: 296 passed
2026-07-06 02:38:59 +08:00
LLLin000
7b29ab68ca feat: improve vnext figure matching and split OCR status
This batch implements the validated PR-2 / PR-3 workstreams.

PR-2b: continued captions in vnext
- add figure continuation helpers
- mark continuation legends in candidate indexing
- run ContinuationCaptionPass before PrimarySamePagePass
- emit unique continuation records with trace metadata
- skip continuation legends in ordinary same-page proposals

PR-2a: short-caption geometry
- reuse _TRUNCATED_LEGEND_ONLY_PATTERN
- add narrow short-caption branch at the vnext group/page seam
- require same page, same column/x-overlap, tight gap, and local uniqueness
- avoid global threshold changes or score_figure_match edits

PR-3: completeness normalization and additive status split
- normalize legacy/vnext figure completeness shapes
- keep overall unchanged
- add structure_status, figure_status, table_status,
  dimension_statuses, status_reasons

Verification:
- 443 targeted tests passing
- real-vault rebuilds:
  * SKXTCE6M: unmatched_legends 6->0, overall green
  * SRNJDAA2: unmatched_legends 9->0, figure green
  * 6QNRHRKX: matched 0->4, figure yellow (improved, not solved)
  * 9DM6MCIF: unmatched_legends 3->0, figure green
  * XGT9Z257: unmatched_legends 4->0, figure green
  * V4UTP5X7: figure green while structure remains red
2026-07-06 00:55:40 +08:00
LLLin000
7c702b1bcf fix: exclude table-owned media and inline figure body refs from figure matching
PR-1 of the architecture review fixes.

Two entry-level filters before figure matching:

1. _is_table_owned_media(): excludes media_asset blocks with table
   roles/raw_labels/hints from the figure asset pool. Previously these
   entered as figure candidates and ended up as unmatched legends/orphans.

2. _looks_like_inline_figure_body_reference(): detects body text like
   'Figure 11-10 shows...' (hyphenated ranges, list ranges) and flags
   it as an inline reference, not a figure legend. Applied in both
   ocr_figures.py and ocr_roles.py for consistent early rejection.

Verified on real vault:
  SKXTCE6M: unmatched_legends 6→0, overall yellow→green
  SRNJDAA2: unmatched_legends 9→0

Tests: 384 pass (+9 new), 0 fail
2026-07-05 22:36:17 +08:00
LLLin000
cd352cb007 fix: rebuild path writes meta.ocr_health_overall
_phase4_render_health now returns (markdown, health_overall),
_phase5_finalize writes it to meta before write_json.

Also adds ADR with architecture review decisions:
- #2 Meta divergence — fixed
- #3 Quality signals for consumers — deferred to role-override v1
- #4 Health report richness — keep all fields
- #5 PDF lines cache — rejected
- #6 Integration tests — deferred to role-override v1
2026-07-05 22:02:40 +08:00
LLLin000
d50ea4631b fix: final cleanup before merge — stale test, helper, RGB safety
1. Stale test: test_extract_objects_renders_same_page_once_for_multiple_crops
   now asserts render_pdf_page_cached is NOT called (new PageRenderContext path)
   and pages/page_001.jpg is NOT created.

2. Extract _resolve_object_crop_pdf_path() helper with 4-case test.
   Phase 4 now uses it instead of inline fallback logic.
   Test locks in: Phase 1 resolved path beats stale meta['source_pdf'].

3. PageRenderContext: use fitz.csRGB in get_pixmap() for safe CMYK/n>3 handling.
   Removed fragile pix.n mode detection.

4. Added test_extract_and_write_objects_with_use_disk_page_cache_false_and_valid_pdf
2026-07-05 21:36:17 +08:00
LLLin000
643052489a fix: determinism + correctness fixes before further optimization
6 fixes bundled:

1. Cleanup: remove accidental empty file '6s}'

2. Rebuild determinism: add 'use_disk_page_cache' gate to _crop_asset_from_pdf.
   Rebuild (use_disk_page_cache=False) never reads or writes pages/page_XXX.jpg.
   All rendering goes through PageRenderContext in-memory.
   Legacy callers keep backward-compat behavior (default True).

3. PageRenderContext safety:
   - Only use when page_width>0 and page_height>0 and not rotation_deg
   - Fix Pixmap.n mode detection (L/RGB/RGBA -> convert to RGB)
   - Fix Image.Resampling name bug (Image -> PILImage)
   - Rotated crops always fall back to direct PDF clip path

4. Phase 1+2a merged traversal: always extract PDF lines on every page,
   regardless of whether span_metadata already exists. Fixes figure inventory
   data gaps when pages have pre-existing span coverage.

5. Phase 4: use resolved source_pdf_path from Phase 1, not ocr_meta['source_pdf']
   fallback (which may be stale or missing).

6. Added 5 determinism tests
2026-07-05 21:32:05 +08:00
LLLin000
b977adc1d8 perf: PageRenderContext — in-memory page rendering for Phase 4a, no disk writes
Add PageRenderContext class that renders each page once into memory
(PIL Image via get_pixmap + frombytes), shared across all crop tasks
in a single rebuild session. No full-page JPG is written to disk.

- _crop_asset_from_pdf: new fast path (page_render_context kwarg)
- Three task functions pass context through
- extract_and_write_objects opens PDF once, creates context, closes after
- Cold Phase 4a: 4.0s → 1.24s (60p, 30 unique pages, 42 crops)
- Full cold rebuild: 10.9s → 7.17s
2026-07-05 21:13:29 +08:00
LLLin000
9ebd1f3dcb perf: merge Phase 1+2a into single PDF pass, add _extract_lines_from_rawdict
- Extract PDF lines from rawdict data that was already fetched for span backfill,
  eliminating the separate page.get_text('dict') pass (~6s for 60 pages)
- Add _extract_lines_from_rawdict() helper to avoid rawdict re-parse
- Keep extract_pdf_lines_normalized() as backward-compatible API
- First-rebuild: 14.2s -> 10.9s (60p), 8.8s -> 8.0s (81p)
2026-07-05 20:55:10 +08:00
LLLin000
83b516aac0 fix: optimize span backfill with per-page rawdict batching and incremental re-extraction
- Group raw_blocks by page, call get_text('rawdict') once per page instead of once per block
  (1433 calls → 60 calls, 68s → 16.6s for a 60-page paper)
- Add _spans_from_rawdict() helper to filter cached rawdict by char bbox center overlap
- Keep extract_pdf_spans_for_block() as single-block compatibility API unchanged
- Add incremental backfill: skip pages where all blocks already have span_metadata
- Remove figure_title from _is_text_like_raw_block() coverage count (figure titles are
  typically image-rendered, not selectable PDF text)
- Add regression test: fast path output matches single-block API
2026-07-05 20:39:52 +08:00
LLLin000
c34ebbce81 feat: rebuild speed-up with parallel rebuild, threaded asset cropping, maintenance refactor, embed progress, CLI docs 2026-07-05 19:43:07 +08:00
LLLin000
380f935f83 docs: add fulltext rebuild safety implementation plan 2026-07-05 17:14:13 +08:00
LLLin000
7931f658bd feat: add rebuild-time fulltext backups and provenance 2026-07-05 17:00:41 +08:00
LLLin000
cdf969d85e feat: persist machine fulltext hash for initial OCR 2026-07-05 16:58:23 +08:00
LLLin000
1474c061a8 feat: surface drift state and invalidate maintenance cache 2026-07-05 16:52:17 +08:00