Compare commits
101
Commits
bdeea71f5d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a45f744604 | ||
|
|
ae080ac7f3 | ||
|
|
fb17d15fbe | ||
|
|
4f20c256d7 | ||
|
|
c6ffa050a6 | ||
|
|
47456a44df | ||
|
|
140a343b92 | ||
|
|
f20d40e4fe | ||
|
|
c054b47df5 | ||
|
|
644f7de696 | ||
|
|
632fb88e43 | ||
|
|
065304b52f | ||
|
|
7b5ea7c2ee | ||
|
|
b34b8ca672 | ||
|
|
814a400e6d | ||
|
|
6880bd0866 | ||
|
|
3d82a72b6f | ||
|
|
2b57180998 | ||
|
|
76887639f3 | ||
|
|
50658580e9 | ||
|
|
dad54a2854 | ||
|
|
149e753952 | ||
|
|
c6223c93dc | ||
|
|
36eddce672 | ||
|
|
dd119d534a | ||
|
|
2a5df7cb31 | ||
|
|
bd271a6f52 | ||
|
|
375169bbfc | ||
|
|
938d6cf09d | ||
|
|
da441ea799 | ||
|
|
a86caec821 | ||
|
|
f27106a638 | ||
|
|
b21b05eaee | ||
|
|
e9ae6e2ba3 | ||
|
|
c4f098d0c0 | ||
|
|
1200437bf8 | ||
|
|
abe7388dda | ||
|
|
542e568d25 | ||
|
|
a88a5a3713 | ||
|
|
05f7d0645e | ||
|
|
8fac4e64d4 | ||
|
|
a12fdcdf0a | ||
|
|
a2b2f283fd | ||
|
|
2ac37455f0 | ||
|
|
ab9391d019 | ||
|
|
b0c7aed613 | ||
|
|
8d70aa946c | ||
|
|
dcb1062b83 | ||
|
|
34d60efbc1 | ||
|
|
6ba46e735a | ||
|
|
74eb2e265c | ||
|
|
855fa27a30 | ||
|
|
eebc824636 | ||
|
|
690fd98036 | ||
|
|
051f62deb7 | ||
|
|
8172956c15 | ||
|
|
cb8767512a | ||
|
|
4d7d0f6297 | ||
|
|
aa297ea9b1 | ||
|
|
31bd903a93 | ||
|
|
3f752fb77f | ||
|
|
1513981c1c | ||
|
|
742eef955b | ||
|
|
c275735db4 | ||
|
|
966c4b0540 | ||
|
|
12fa69b7ea | ||
|
|
c7cfcd26b5 | ||
|
|
edf6048a0d | ||
|
|
9d4c813cae | ||
|
|
dd524246ec | ||
|
|
b233c8d714 | ||
|
|
863519e980 | ||
|
|
ab3f5f685b | ||
|
|
32a3ec4f5e | ||
|
|
486ceb4019 | ||
|
|
ba4841a811 | ||
|
|
aa65d2d691 | ||
|
|
a8c0402ad2 | ||
|
|
de49a03c4d | ||
|
|
152d4f2b88 | ||
|
|
281684dc8e | ||
|
|
9633eb7653 | ||
|
|
a86544a083
|
||
|
|
9e7262a5c8 | ||
|
|
1a657ce4ca | ||
|
|
0db6ab5df0 | ||
|
|
36ccf64f6a | ||
|
|
5e87622b30 | ||
|
|
0035bdf533 | ||
|
|
d3f8c7f2c8 | ||
|
|
fcac876d40 | ||
|
|
25de518dc9 | ||
|
|
4cb85e5baa | ||
|
|
101156bada | ||
|
|
c88c65641a | ||
|
|
2d0f608246 | ||
|
|
1139f007cf | ||
|
|
6e654df387 | ||
|
|
f50d4c8bc3 | ||
|
|
07fbc4c450 | ||
|
|
0c8018971f |
+49
-6
@@ -59,6 +59,7 @@ accounts (one admin + hand-out tokens is the model).
|
|||||||
| A18 | Docs push | Save-a-answer-as-doc: server-side draft (`doc_drafts`, long body never in a URL — unguessable `uuid4` token is the URL credential) pushed to a **generic git remote** (`BOR_DOCS_REPO`, URL or local path; no `gh`) on a dedicated branch, `--ff-only`, re-cut per push; **no PR tooling**; inert (hidden + 409) while the repo is unset |
|
| A18 | Docs push | Save-a-answer-as-doc: server-side draft (`doc_drafts`, long body never in a URL — unguessable `uuid4` token is the URL credential) pushed to a **generic git remote** (`BOR_DOCS_REPO`, URL or local path; no `gh`) on a dedicated branch, `--ff-only`, re-cut per push; **no PR tooling**; inert (hidden + 409) while the repo is unset |
|
||||||
| A19 | Deploys & caching | HTML pages `Cache-Control: no-cache` (no etag/last-modified); `/assets/*` versioned (`?v=<token>`) + `immutable, max-age=1y`; **the token is the deploy** (git `HEAD` short SHA; content-hash fallback) — a deploy is a commit the browser sees without a hard refresh |
|
| A19 | Deploys & caching | HTML pages `Cache-Control: no-cache` (no etag/last-modified); `/assets/*` versioned (`?v=<token>`) + `immutable, max-age=1y`; **the token is the deploy** (git `HEAD` short SHA; content-hash fallback) — a deploy is a commit the browser sees without a hard refresh |
|
||||||
| A20 | Security headers | Every response: `Content-Security-Policy: default-src 'self'` (+ the theme's inline-`<style>` hash on themed pages), `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`; login rate-limited 10 attempts / 15 min (in-memory, A12) |
|
| A20 | Security headers | Every response: `Content-Security-Policy: default-src 'self'` (+ the theme's inline-`<style>` hash on themed pages), `frame-ancestors 'none'`, `X-Content-Type-Options: nosniff`; login rate-limited 10 attempts / 15 min (in-memory, A12) |
|
||||||
|
| A21 | LLM call economics | **ALL LLM calls are free** (chat, vision, embed, `lite` — self-hosted aipi): the sync/import path may burn as many LLM/vision calls as quality requires — e.g. render + describe **every** sparse page of a pictorial PDF, no page caps, no call budgets (owner 2026-09-30). Latency targets bind the **interactive** path only (retrieval, inference, tool calling — the inference engine's job, not ours to micro-optimize): never cap, throttle, or skip work to save calls; a slower sync is acceptable, a lower-quality KB is not |
|
||||||
|
|
||||||
**UI/theming anchors (B):**
|
**UI/theming anchors (B):**
|
||||||
|
|
||||||
@@ -70,14 +71,38 @@ accounts (one admin + hand-out tokens is the model).
|
|||||||
| B5 | Admin-only nav views (Sources, Git sources, Tuning, History, Tokens, Theme) are hidden from non-admins; a monochrome theme must keep every state **text** label ("text + color, never color alone") |
|
| B5 | Admin-only nav views (Sources, Git sources, Tuning, History, Tokens, Theme) are hidden from non-admins; a monochrome theme must keep every state **text** label ("text + color, never color alone") |
|
||||||
|
|
||||||
**Key recent revisions (full log in the previous plan revision / phase
|
**Key recent revisions (full log in the previous plan revision / phase
|
||||||
records):** A10 — single-admin cookie auth, saved chats + shares +
|
records):** A21 — ALL LLM calls (chat, vision, embed, lite) are free for
|
||||||
staleness, client history budgets, access tokens.
|
this project (owner 2026-09-30): import/sync may burn unlimited
|
||||||
|
LLM/vision calls for quality (e.g. every page of a 500+ page pictorial
|
||||||
|
PDF, rendered + described); sync duration is not an optimization target,
|
||||||
|
interactive-path speed is the inference engine's job. A10 — single-admin
|
||||||
|
cookie auth, saved chats + shares + staleness, client history budgets,
|
||||||
|
access tokens.
|
||||||
A15 — `thinking`, `tool`, unlimited tool rounds under
|
A15 — `thinking`, `tool`, unlimited tool rounds under
|
||||||
`BOR_AGENT_MAX_ROUNDS`, `retry`, harness-aligned
|
`BOR_AGENT_MAX_ROUNDS`, `retry`, harness-aligned
|
||||||
`ls`/`read`/`grep` surface. A7 — the **retrieval** path's
|
`ls`/`read`/`grep` surface. A7 — the **retrieval** path's
|
||||||
never-truncated contract is unchanged; the `read`-tool cap is
|
never-truncated contract is unchanged; the `read`-tool cap is
|
||||||
the only exception, owner-permitted 2026-09-10.
|
the only exception, owner-permitted 2026-09-10.
|
||||||
|
|
||||||
|
Phase 182 (verbatim text display, owner chat 2026-10-14) adds
|
||||||
|
**`show_text(path, offset?, limit?)` as the fifth agent tool** — offered
|
||||||
|
only when `BOR_ANSWER_TEXT=1` (the default), gated exactly like
|
||||||
|
`show_image`, with its own `<tools>` clause and its own kill switch — and
|
||||||
|
the **additive `done.answer_text`** field above. The new settings are
|
||||||
|
`BOR_ANSWER_TEXT` (master switch, ON), `BOR_SHOW_TEXT_MAX_CHARS` (per-block
|
||||||
|
budget, 12 000) and `BOR_SHOW_TEXT_MAX_BLOCKS` (per-answer budget, 5), all
|
||||||
|
following the `agent_max_rounds` pattern (`0` inert, negative refuses
|
||||||
|
startup). The principle in one sentence: **the model points, the server
|
||||||
|
supplies the bytes** — a ` ```bor source/path 12-40 ` fence or a
|
||||||
|
`show_text` call names a location (canonical locator `source/path` or
|
||||||
|
`source/path#start-end`, 1-based and inclusive), and the displayed text is
|
||||||
|
sliced from `documents.content` server-side, so what the user copies is the
|
||||||
|
knowledge base, never a re-typed approximation. **A1–A6 and A15 are
|
||||||
|
otherwise
|
||||||
|
UNCHANGED:** no new SSE event type, no new table or column, no new model,
|
||||||
|
endpoint or transport, no change to retrieval, the honesty gate, the
|
||||||
|
persona text or the embedding dimension.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. High-Level Architecture
|
## 3. High-Level Architecture
|
||||||
@@ -123,7 +148,9 @@ POST /api/chat {message, history?} (auth: require_user)
|
|||||||
→ cosine top-100 ∪ FTS top-30 → RRF fuse (k=60) [A7]
|
→ cosine top-100 ∪ FTS top-30 → RRF fuse (k=60) [A7]
|
||||||
├─ HIGH (cosine ≥ 0.62 OR fts_hits > 0):
|
├─ HIGH (cosine ≥ 0.62 OR fts_hits > 0):
|
||||||
│ persona + <knowledge_base> + <tuning> + full top-2 <documents>
|
│ persona + <knowledge_base> + <tuning> + full top-2 <documents>
|
||||||
│ + <tools> → agent loop (ls/read/grep; round-capped
|
│ + <tools> → agent loop (ls/read/grep, plus show_image when
|
||||||
|
│ BOR_ANSWER_IMAGES=1 and show_text when BOR_ANSWER_TEXT=1 — the two
|
||||||
|
│ "show the user an artifact" tools, gated independently; round-capped
|
||||||
│ BOR_AGENT_MAX_ROUNDS=10, 0 = tools off) → turbo streamed
|
│ BOR_AGENT_MAX_ROUNDS=10, 0 = tools off) → turbo streamed
|
||||||
└─ LOW (A8): DEFLECT_MODE prompt (weak titles only, no tools,
|
└─ LOW (A8): DEFLECT_MODE prompt (weak titles only, no tools,
|
||||||
byte-identical direct-stream path) → turbo streamed
|
byte-identical direct-stream path) → turbo streamed
|
||||||
@@ -133,8 +160,20 @@ POST /api/chat {message, history?} (auth: require_user)
|
|||||||
SSE frames (`data: <json>\n\n`): `thinking` (before first delta) →
|
SSE frames (`data: <json>\n\n`): `thinking` (before first delta) →
|
||||||
`tool` (grounded turns, one per model call) → `retry` (pre-first-frame
|
`tool` (grounded turns, one per model call) → `retry` (pre-first-frame
|
||||||
restarts) → `delta` (answer tokens) → `done` `{deflected, sources[],
|
restarts) → `delta` (answer tokens) → `done` `{deflected, sources[],
|
||||||
suggestions[]}` (terminal). Failure: `error` (terminal — no `done`, no
|
suggestions[], budget_exhausted?, answer_text[]?}` (terminal). **Phase 182
|
||||||
`query_log` row; a pre-stream DB outage is a plain 503 JSON).
|
extends the `done` frame ADDITIVELY** — `answer_text` is the list of
|
||||||
|
server-resolved verbatim blocks (`locator`, `source`, `path`, `start`,
|
||||||
|
`end`, `total_lines`, `text`, `format`, `truncated`) the answer displayed;
|
||||||
|
there is **no eighth event type**, the key is OMITTED when no block was
|
||||||
|
displayed, and with `BOR_ANSWER_TEXT=0` it is absent on every turn (the
|
||||||
|
frame is then byte-identical to pre-phase). The same array persists on the
|
||||||
|
saved chat record, so restore and the anonymous shared page re-render the
|
||||||
|
panels from the server's bytes. Failure: `error` (terminal — no `done`, no
|
||||||
|
`query_log` row; a pre-stream DB outage is a plain 503 JSON). A
|
||||||
|
`tools=None` request never emits a `tool` frame; a round-capped turn
|
||||||
|
whose final reply carries no visible content answers with the budget
|
||||||
|
fallback instead of erroring (phase 160, recorded revision of the
|
||||||
|
phase-71 cap-path terminal, owner-confirmed 2026-10-05).
|
||||||
`BOR_STREAM_THINKING=0` suppresses `thinking` frames server-side (chars
|
`BOR_STREAM_THINKING=0` suppresses `thinking` frames server-side (chars
|
||||||
still counted). LLM retries (A15 extension): retry count and delay are
|
still counted). LLM retries (A15 extension): retry count and delay are
|
||||||
configurable (defaults: 3 retries, 5 s flat delay), **only before a
|
configurable (defaults: 3 retries, 5 s flat delay), **only before a
|
||||||
@@ -262,8 +301,12 @@ scripts.…`, and tests all honor it.
|
|||||||
```
|
```
|
||||||
question=… embed_ms=… top_score=… fts_hits=… summary_hits=… tuning=N
|
question=… embed_ms=… top_score=… fts_hits=… summary_hits=… tuning=N
|
||||||
kb_chars=N history_msgs=N threshold=… deflected=… sources=…
|
kb_chars=N history_msgs=N threshold=… deflected=… sources=…
|
||||||
thinking_chars=… tool_calls=N total_ms=… retries=N scaffold_stripped=N
|
thinking_chars=… tool_calls=N rounds=N cap_hit=0|1 total_ms=…
|
||||||
|
retries=N scaffold_stripped=N verbatim_blocks=N
|
||||||
```
|
```
|
||||||
|
(`verbatim_blocks=` — phase 182 — is the count of verbatim display blocks
|
||||||
|
actually SENT on the `done` frame, `0` on every turn without them,
|
||||||
|
deflected included.)
|
||||||
(`sources=` = retrieval + agent-read docs, deduped; `tool_calls=`
|
(`sources=` = retrieval + agent-read docs, deduped; `tool_calls=`
|
||||||
executed only; a cancelled turn writes neither line nor `query_log`
|
executed only; a cancelled turn writes neither line nor `query_log`
|
||||||
row.)
|
row.)
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Phase 127 — Incremental folder summaries: sync rewrites only the directories its changed files touch
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/api/sync.py` — `_run_sync` step 5 (the changed-KB full-regeneration call to `generate_folder_summaries`, the unchanged-walk gap probe, the `_summary_hook` progress closure, the `SyncStatus` phase machine); `app/rag/folder_summaries.py` — `folder_of`, `group_by_folder` (the recursive-subtree concept), `_candidates`, `_stored_keys`, `missing_folder_summaries`, `generate_folder_summaries` (full / `only_missing` modes, manual-row skip, fail-soft, prune pass, `on_progress` hook, "only flushes — the caller commits"); `app/rag/importer.py` — `ImportSummary` (L212, counts only — no path tracking), the `summary.added += 1` / `summary.updated += 1` increment sites (grep them: the text path ~L794, the image path ~L1068, the PDF path ~L1328, ~L1730, ~L1994) and `_prune` (L2015, deletes vanished docs); `scripts/import_docs.py` — the CLI caller (passes no changed set — full regeneration stays its contract); `tests/unit/test_folder_summaries.py`, `tests/unit/test_importer.py`, `tests/unit/test_sync_button.py` — the existing suites to extend; `tests/e2e/test_sync_summary_visibility.py` — the sync E2E pattern (local `kind=local` source fixture, autouse truncate cleanup, mock-only).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A KB-changing sync regenerates folder summaries for ONLY the folders affected by the documents that actually changed (each changed document's folder chain up to its source root) — one changed file rewrites a handful of rows, not the whole table. Unchanged folders keep their stored rows byte-identical (text AND `updated_at`). Full regeneration remains available and stays the exact behavior for callers that pass no change set (the CLI, any future full-regen need); the unchanged-walk gap probe is untouched.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `126_pdf_support` (complete) — last completed phase; this phase builds on the shipped sync pipeline (phases 32/64/98), the folder-summary generator (phases 94/96/97/98) and the importer.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Change tracking (task 01):** `ImportSummary` gains `changed_paths: list[tuple[str, str]] = field(default_factory=list)` — one `(source, path)` entry per document that was **added, updated, or pruned** in the run, in the order encountered (added/updated in walk order, pruned in `_prune` order). Recorded at EVERY `summary.added += 1` / `summary.updated += 1` site with the site's `(source, rel)` / `(doc.source, doc.path)`, and in `_prune` for each deleted doc (record before `db.delete`). No dedupe needed: a document is added-or-updated at most once per run and pruned docs are gone; the consumer builds a set anyway. `unchanged` / `summary_backfilled` / `dates_updated` NEVER record (their contract is no-regeneration, phase 106/118). The `log()` line is unchanged (the count is derivable: `len(changed_paths) == added + updated + pruned`).
|
||||||
|
- **Affected keys (task 02):** `app/rag/folder_summaries.py` gains a pure helper `affected_folder_keys(changed: Iterable[tuple[str, str]]) -> set[tuple[str, str]]` — for each `(source, path)`: the source-root key `(source, "")` plus every folder prefix obtained by walking `folder_of` from the document's nearest folder up to `""` (the SAME one concept `group_by_folder` pass 1 uses — a doc under `a/b/` affects `a/b`, `a`, and the root). `generate_folder_summaries` gains `changed_docs: Sequence[tuple[str, str]] | None = None`:
|
||||||
|
- `None` (default) → today's full regeneration, byte-identical (the CLI path and any explicit full-regen call).
|
||||||
|
- given → `keys = sorted(set(candidates) & affected_folder_keys(changed_docs))`; the generation loop, the manual-row skip (`kept_manual`), the per-folder fail-soft, and the `on_progress` hook (whose `total` becomes the affected count — the sync status's `summaries_total` then reports the affected count through the existing hook) all run over exactly those keys. An affected folder with NO stored row (a gap in an affected folder) is generated like any other candidate. Missing rows in UNaffected folders stay the unchanged-walk gap probe's job (untouched).
|
||||||
|
- the prune pass runs in BOTH modes, unchanged (vanished folders' rows are dropped there, manual rows exempt — the phase-97 rule).
|
||||||
|
- `only_missing=True` (the gap-fill) is untouched and orthogonal.
|
||||||
|
- **Sync wiring (task 03):** `app/api/sync.py` `_run_sync` step 5, the changed-KB branch only: `generate_folder_summaries(fs_db, llm, changed_docs=summary.changed_paths, on_progress=_summary_hook)`; the unchanged-walk gap probe branch is byte-identical. The module docstring's step-5 description and the `SyncStatus` docstring get updated to the incremental contract. The success log line names the change count (`sync: folder_summaries changed=N stats=…` — the stats dict stays log-only, the detail shape untouched, phase-98 convention).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_importer_changed_paths.md` — `ImportSummary.changed_paths` recorded at every added/updated/prune site.
|
||||||
|
2. `02_folder_summaries_affected_mode.md` — `affected_folder_keys` + `generate_folder_summaries(changed_docs=…)`.
|
||||||
|
3. `03_sync_wiring.md` — the sync's changed-KB branch passes the change set; docstrings + logging.
|
||||||
|
4. `04_e2e_incremental_sync.md` — dedicated Playwright E2E, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: every behavior above — the change-set contents/order (all three doc kinds + prune), the affected-keys math (nested folders, roots, multi-source, `#page=`-fragment paths), the generator's changed mode (only-affected upserts, untouched rows byte-identical text AND `updated_at`, manual skip, fail-soft, prune pass, hook total), the CLI no-change path (byte-identical full regen), the sync status's `summaries_total` = affected count.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation (`uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov`), mock-only.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a one-file change in a folder rewrites exactly that folder's chain (folder + ancestors + source root) — sibling and other-source rows keep their `updated_at` and text
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (CLI full regen, gap probe, manual rows, phase machine, keep-final-counts)
|
||||||
|
- [ ] one atomic Conventional Commit with `--no-gpg-sign` per the AGENTS.md git protocol
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Task 01 — `ImportSummary.changed_paths`: the importer records which documents it changed
|
||||||
|
|
||||||
|
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`ImportSummary` carries the identity of every document the run added, updated, or pruned — `(source, path)` tuples — so the sync path can scope the folder-summary regeneration to exactly the folders those documents touch.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/importer.py` — `ImportSummary` (L212): add the field with a docstring comment matching the house style:
|
||||||
|
```python
|
||||||
|
#: Documents this run ADDED, UPDATED, or PRUNED, as (source, path)
|
||||||
|
#: tuples in encounter order (added/updated in walk order, pruned in
|
||||||
|
#: _prune order). Drives the sync's incremental folder-summary
|
||||||
|
#: regeneration (phase 127): len(changed_paths) == added + updated +
|
||||||
|
#: pruned. Unchanged / backfilled / date-only refreshes NEVER record.
|
||||||
|
changed_paths: list[tuple[str, str]] = field(default_factory=list)
|
||||||
|
```
|
||||||
|
2. `app/rag/importer.py` — record at every increment site. Grep `summary.added +=` and `summary.updated +=` (currently the text path ~L794/796, the image path ~L1068/1070, the PDF path ~L1328/1330, ~L1730, ~L1994/1996 — the exact set may have shifted; the rule is: **every** site). At each, immediately beside the counter increment, append the site's identity: `summary.changed_paths.append((source, rel))` (the variables each site already has — `source` + `rel` for the index paths; where a site only has the `doc` row, use `(doc.source, doc.path)`).
|
||||||
|
3. `app/rag/importer.py` — `_prune` (L2015): in the delete loop, for each document that is actually deleted (i.e. NOT skipped by the images-off guard and NOT skipped by the phase-126 embedded-image parent rule), append `(doc.source, doc.path)` to `summary.changed_paths` BEFORE `session.delete(...)` — `_prune` needs the summary passed in (add a `summary: ImportSummary | None = None` parameter, recorded only when given; the existing callers — `import_sources`'s prune call — pass it; any other caller keeping `None` stays byte-identical). Check every existing `_prune` call site and update only the `import_sources` one.
|
||||||
|
4. `app/rag/importer.py` — do NOT touch `ImportSummary.log()` (the new count is derivable) and do NOT touch the sync's `detail` dict shape (task 03 keeps it log-only).
|
||||||
|
|
||||||
|
ASSUMPTION: one entry per changed document is enough (no per-file verb) — the consumer only needs folder keys, and the verb is already in the counters.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_importer.py` (extend) or a focused new file —
|
||||||
|
- a walk with 2 added + 1 updated + 1 pruned doc (text files, a temp source dir) → `changed_paths` holds exactly those 4 `(source, path)` pairs, added/updated in walk order, the pruned pair last (or in `_prune` order);
|
||||||
|
- an images-on run with a changed image file records its `(source, rel)` (the image increment site);
|
||||||
|
- a PDF run with a changed PDF records its pair (the PDF increment site);
|
||||||
|
- an unchanged re-run (all `unchanged`) → `changed_paths` empty;
|
||||||
|
- a backfill/date-only run (phase 118/106 shapes, if covered by existing fixtures) → still empty.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `ImportSummary()` default construction gives `changed_paths == []` (no migration of existing construction sites)
|
||||||
|
- [ ] every `added`/`updated`/`pruned` increment in the importer has a matching `changed_paths` append (a grep audit passes: same count of sites)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; full suite green; no behavior change in completed work
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
# Task 02 — `affected_folder_keys` + `generate_folder_summaries(changed_docs=…)`: regenerate only the folders a change touches
|
||||||
|
|
||||||
|
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The folder-summary generator can be told the set of changed documents and then regenerates ONLY the candidate folders whose recursive subtree contains at least one of them — the change's folder chain per document, plus each source root — with every existing guarantee (manual skip, fail-soft, prune pass, progress hook) intact.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/folder_summaries.py` — new pure helper (place it next to `folder_of` / `group_by_folder`, with a docstring tying it to the recursive-subtree concept):
|
||||||
|
```python
|
||||||
|
def affected_folder_keys(
|
||||||
|
changed: Iterable[tuple[str, str]],
|
||||||
|
) -> set[tuple[str, str]]:
|
||||||
|
"""The candidate folder keys a changed-document set invalidates.
|
||||||
|
|
||||||
|
For each ``(source, path)``: the source-root key ``(source, "")``
|
||||||
|
plus every folder prefix of *path* — ``folder_of`` walked from the
|
||||||
|
document's nearest folder up to ``""`` — the SAME prefix walk
|
||||||
|
``group_by_folder`` pass 1 uses (one concept): a doc under
|
||||||
|
``a/b/`` affects ``a/b``, ``a``, and the source root. A
|
||||||
|
root-level file (``folder_of(path) == ""``) affects ONLY the
|
||||||
|
source root. Embedded-image fragment paths (``x.pdf#page=…#img=…``,
|
||||||
|
phase 126) fold into their parent's folder chain with no special
|
||||||
|
case — ``folder_of`` never sees a ``/`` inside the fragment.
|
||||||
|
Returns a set; the generator sorts it (deterministic order).
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
Empty input → empty set.
|
||||||
|
2. `app/rag/folder_summaries.py` — `generate_folder_summaries`: add the kwarg `changed_docs: Sequence[tuple[str, str]] | None = None` (after `only_missing`, before `on_progress` — keyword-only section). Inside, after `candidates = _candidates(_catalog_rows(db))` and the `existing` fetch:
|
||||||
|
- `keys = sorted(candidates)` stays the full-mode default;
|
||||||
|
- when `changed_docs is not None`: `keys = sorted(set(candidates) & affected_folder_keys(changed_docs))` — generation is restricted to affected CANDIDATES (a folder that exists in the catalogue but is unaffected keeps its row; an affected folder with no stored row — a gap — is a candidate and gets generated);
|
||||||
|
- `only_missing=True` keeps its exact current semantics (restricts to missing candidates; the two kwargs are never combined by any caller — document that in the docstring);
|
||||||
|
- the generation loop, `kept_manual` skip, per-folder `LLMError` fail-soft, and the `on_progress(i + 1, len(keys), source, folder_path)` hook are untouched code — `total` simply becomes the affected count when restricted;
|
||||||
|
- the prune pass is untouched (runs in both modes, deletes rows for folders that dropped below the minimum, manual rows exempt).
|
||||||
|
Update the function docstring: the new mode, the one-line contract ("a document's change invalidates exactly its folder chain + source root — the folders whose subtree summary text can change"), and that `changed_docs=None` is the byte-identical full regeneration (the `scripts/import_docs.py` CLI).
|
||||||
|
3. `scripts/import_docs.py` — verify (do not modify) that the CLI call passes no `changed_docs` — it must stay a full regeneration.
|
||||||
|
|
||||||
|
ASSUMPTION: the intersection (`candidates & affected`) is the correct restriction — an affected folder that no longer has any document is handled by the prune pass, not by generation; an unaffected folder's summary cannot change because its subtree's documents and their first-summary-lines are untouched.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_folder_summaries.py` (extend) —
|
||||||
|
- `affected_folder_keys`: a root-level file → `{(src, "")}`; `a/b/c.md` → `{(src, ""), (src, "a"), (src, "a/b")}`; mixed multi-source input; an embedded-image fragment path (`img.pdf#page=2#img=0` under `dir/`) → the `dir` chain; empty input → empty.
|
||||||
|
- `changed_docs=` mode over a seeded catalogue (3 sources, nested folders, a manual row, a failing folder): exactly the affected keys are upserted (fake LLM counts calls — one per non-manual affected key); unaffected rows keep their stored `summary` AND `updated_at` (assert both); manual affected row → `kept_manual`, untouched; a failing affected folder → `failed`, its previous row kept, others still land; the hook fires `len(affected)` times with `total == len(affected)`; the prune pass still drops a vanished folder's row;
|
||||||
|
- `changed_docs=None` over the same catalogue → the pre-task full-regeneration behavior (all candidates, byte-identical stats shape).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `affected_folder_keys` is a pure function unit-tested on nested / root / multi-source / fragment paths
|
||||||
|
- [ ] `generate_folder_summaries(db, llm)` (no new kwarg) behaves exactly as before (existing suite green, unchanged)
|
||||||
|
- [ ] restricted mode leaves every unaffected row byte-identical (text AND `updated_at`)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; full suite green
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Task 03 — Sync wiring: the changed-KB branch regenerates only affected folders
|
||||||
|
|
||||||
|
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`POST /api/sync` passes the import's change set into the folder-summary generator, so a one-file sync burns `lite` calls only for that file's folder chain. The status phase machine, progress hook, gap probe, and terminal conventions are unchanged in behavior (the hook's `total` now naturally reports the affected count).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/api/sync.py` — `_run_sync`, step 5, the CHANGED-KB branch (the `if summary.added + summary.updated > 0:` arm that currently calls `generate_folder_summaries(fs_db, llm, on_progress=_summary_hook)`): pass `changed_docs=summary.changed_paths`. The else arm (unchanged walk → `missing_folder_summaries` gap probe → `only_missing=True`) stays byte-identical, including the no-gap skip's "stays `import`" phase behavior.
|
||||||
|
2. `app/api/sync.py` — logging: the changed-KB branch's existing `logger.info("sync: folder_summaries stats=%s", folder_stats)` becomes `logger.info("sync: folder_summaries changed=%d stats=%s", len(summary.changed_paths), folder_stats)` (PLAN §9 ample logging — the owner can see how many folders a sync actually rewrote). The gap-fill log line is unchanged.
|
||||||
|
3. `app/api/sync.py` — docstrings: the module docstring's step-5 paragraph (the "full regeneration" sentence) and the `SyncStatus` docstring's `summaries_done`/`summaries_total` note — update to the incremental contract: on a changed KB the phase runs over the CHANGED set's folder keys (the hook's `total` is the affected count, not the table's candidate count); on an unchanged walk the gap-fill total is the missing count (as before); terminal states keep the final counts (the phase-64 convention, unchanged).
|
||||||
|
4. Verify: the `detail` dict shape is untouched (no new key — the stats stay log-only, phase-98 convention); `GET /api/sync/status` shape is untouched (the chunk-free status fields are already there; no new fields in this phase).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: extend the sync unit suite (`tests/unit/test_sync_button.py` and/or the sync-pipeline test file that fakes `import_sources` + `generate_folder_summaries` — inspect the existing fakes first):
|
||||||
|
- a changed-KB sync (fake import returning 1 updated doc) → `generate_folder_summaries` receives `changed_docs=` equal to the fake's change set (assert on the fake's captured kwargs) and the success detail is unchanged in shape;
|
||||||
|
- an unchanged walk with a gap → still `only_missing=True`, no `changed_docs` (the gap probe is orthogonal);
|
||||||
|
- the status during the summaries phase reports `summaries_total == len(affected keys)` (fake generator whose hook total is its key count — follow the existing phase-machine test pattern).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a changed-KB sync calls the generator with `changed_docs=summary.changed_paths`; an unchanged walk calls it exactly as before
|
||||||
|
- [ ] `GET /api/sync/status` and the success `detail` shapes are byte-identical to pre-phase
|
||||||
|
- [ ] docstrings + log lines reflect the incremental contract
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; full suite green
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
# Task 04 — E2E: a one-file change rewrites only that folder's summary chain
|
||||||
|
|
||||||
|
**Phase:** `127_sync_incremental_folder_summaries` · **Source:** `TODO.md:3` — "On sync brain of reese rewrites all the summaries for every directory. So even if just one file changed this can result in 700+ directory summary rewrites in production which can take a very long time."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix end to end: after a first full sync, changing ONE file in ONE folder and re-syncing re-stamps exactly that folder's chain (the folder + its ancestors + the source root) and leaves every other stored row byte-identical.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_incremental_folder_summaries.py` (new) — follow `tests/e2e/test_sync_summary_visibility.py`'s house pattern exactly (module-level app fixture over the shared E2E Postgres, host temp-dir `kind=local` source registered via the admin git-sources API, autouse cleanup that truncates `documents`/`chunks`/`query_log`/`steering_notes`/`kb_overview`/`git_sources`/`folder_summaries` and waits for no running sync, mock-only — `E2E_REAL_LLM=1` unsupported). No slow-LLM proxy needed: the assertions are on POST-terminal DB state + the terminal status (the keep-final-counts convention), not on in-flight sampling.
|
||||||
|
KB fixture — one local source `incsum/` (temp dir) with FOUR folders `alpha/`, `bravo/`, `charlie/`, `delta/`, two markdown docs each, plus one root-level doc: the generator's candidate set is exactly 5 rows (source root + 4 folders — the recursive-subtree ≥ 1 rule).
|
||||||
|
2. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_first_sync_generates_all_rows` — admin sync #1 settles `success`; the `folder_summaries` table holds exactly the 5 rows (the mock's deterministic `FOLDER_SUMMARY_MODE` canned text names each folder — `tests/e2e/mock_llm.py`'s existing canned reply), each `updated_at` non-null.
|
||||||
|
- `test_one_file_change_restamps_only_that_folders_chain` — after test 1's state is re-seeded (autouse truncates, so seed again): re-run sync #1, capture each row's `(summary, updated_at)`; then modify ONE doc inside `alpha/` (change its content), sync #2 settles `success`; assert: `alpha` + the source root rows have a NEW `updated_at` (strictly after the captured ones) and the canned text; `bravo`/`charlie`/`delta` rows are byte-identical (same `summary` AND same `updated_at`); the terminal `GET /api/sync/status` keeps `summaries_done == summaries_total == 2` (the affected count — alpha + root, the keep-final-counts convention) and `detail.added/updated/unchanged/pruned` show the single-file change.
|
||||||
|
- `test_pruned_file_restamps_only_its_chain_and_prunes_the_vanished_folder` — seed + full sync; capture; delete `bravo/`'s LAST doc (the folder vanishes) and modify one doc in `charlie/`; sync settles; assert: the `bravo` row is PRUNED (gone — the prune pass), the source root + `charlie` rows re-stamped, `alpha`/`delta` byte-identical.
|
||||||
|
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov`), the mock-only gate, the fixture layout, and the test→observable table (the house format).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's unit/integration coverage bar (>90% on `app/`) is already carried by tasks 01–03; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_incremental_folder_summaries.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the three tests above map 1:1 to the TODO's observable: one changed file → a handful of rewrites, not 700+
|
||||||
|
- [ ] no behavior change in completed phases (the full-regen first sync, the gap probe, the phase machine)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Phase 128 — The sync label shows on mobile, count always visible
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L4 — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (the item is truncated in the TODO; ASSUMPTION A1 — read as: the running label must be fully visible on mobile, with the `(n/m)` position never clipped off-screen).
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/index.html` L449–451 — the `#sync-btn` / `#sync-label` markup (one span holds the whole label string); `frontend/assets/sources.js` — `fmtSyncLabel(kind, currentFile, done, total)` (~L650) and `fmtSyncPhaseLabel(status)` (~L669) build the running labels as ONE string, the poll loop applies them to `#sync-label` + the button `title` + `#sync-result` (the aria-live announcer — the untruncated text rides both, A4 convention); `frontend/assets/styles.css` — `.sync-label` (~L2067: `inline-block`, `max-width: min(16rem, 40vw)`, ellipsis, `nowrap`) and the mobile media query (~L5323: `.sync-btn { width: 100%; }`, `.sync-label { max-width: none; min-width: 0; }` — with `max-width: none` the inline-block sizes to its FULL content, so the label's tail — where `(n/m)` lives — runs off-screen: the reported bug); `tests/unit/test_frontend_sync_upload.py` — the pinned frontend label tests to update.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
On a phone, the running sync label is fully visible: the file path ellipsizes to fit, and the `(n/m)` position sits in its own non-shrinking span that is NEVER clipped — in the import phase (`Syncing… <file> (2/3)`) and the summaries phase (`Summarizing folders… <folder> (n/m)`). Desktop renders the same content with its existing visual layout (the cap, the ellipsis, the title/aria-live untruncated text all preserved).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `127_sync_incremental_folder_summaries` (todo) — pipeline order only; code dependencies are the completed phase-64/98 label contract.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Markup (task 01):** `#sync-label` gains two child spans — `<span class="sync-label-main"></span><span class="sync-label-count" hidden></span>` (static markup in `index.html`). The JS builders no longer return one string: a single `setSyncLabel(mainText, countText)` helper writes `textContent` into the parts (the createElement/textContent house rule — no HTML strings) and toggles the count span's `hidden` (absent count → hidden, empty). The FULL untruncated label (`mainText + (countText ? " " + countText : "")`) is still set on the button `title` and `#sync-result` exactly as today (A4 — screen readers hear the whole thing).
|
||||||
|
- **Label mapping (task 01):** main/count per state — prelude (null phase, no file): main `"Syncing…"`, no count; import: main `"Syncing… <file>"`, count `"(n/m)"` while `total > 0`; overview: main `"Writing KB overview…"`, no count; summaries: main `"Summarizing folders… <folder>"` (no folder part while `current_summary` is null), count `"(n/m)"`; upload: main `"Importing"`, no count (phase-90 contract — the upload status carries no file or counts); idle/settle labels (`"Sync sources"`, `"Synced HH:MM"`): main only. `fmtSyncPhaseLabel`'s decision tree is preserved 1:1 — only the OUTPUT shape changes (string → parts).
|
||||||
|
- **CSS (task 02):** `.sync-label` becomes a flex row (`display: inline-flex; align-items: baseline; gap: 0.35rem; min-width: 0; max-width: min(16rem, 40vw);`); `.sync-label-main { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }`; `.sync-label-count { flex: 0 0 auto; white-space: nowrap; }`. Mobile media query (the existing block at ~L5323): `.sync-label { max-width: none; flex: 1 1 auto; min-width: 0; }` — the label fills the full-width pill, the main part ellipsizes against the remaining width, the count span stays visible at the right edge. The `#sync-result` mobile clip (visually-hidden) is untouched.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_label_parts.md` — markup + `setSyncLabel` part builders in `sources.js` (all label states, A4 untruncated text preserved).
|
||||||
|
2. `02_mobile_css.md` — the flex-part CSS + the mobile media query.
|
||||||
|
3. `03_e2e_mobile_label.md` — dedicated Playwright E2E, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_frontend_sync_upload.py` — the pinned label outputs updated to the part shape (main/count per state, the byte-identical label strings where they must hold: prelude, upload, settle); the `title`/`#sync-result` untruncated text pins stay.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mobile viewport, slow-LLM pattern.
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend: the JS is covered by the pinned unit tests + the E2E; `app/` untouched this phase).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] at a phone viewport (390×844) the running label is fully in the viewport — file path ellipsized, `(n/m)` visible — in BOTH the import and summaries phases
|
||||||
|
- [ ] desktop label visually unchanged (same strings, same cap/ellipsis, same `title`/`#sync-result` untruncated text)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov` green in isolation
|
||||||
|
- [ ] `uv run pytest` (unit + integration) green; no behavior change in completed phases
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 01 — `#sync-label` becomes parts: the file path ellipsizes, the `(n/m)` count is pinned
|
||||||
|
|
||||||
|
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The label's string is split into a shrinks-to-fit main part (prefix + file/folder path) and a pinned count part (`(n/m)`), so CSS can ellipsize the path while the position always stays on-screen. Every existing label state keeps its exact rendered text.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/index.html` (L449–451) — inside `#sync-label`, replace the bare text with the two part spans (the initial text lives in the main span so the pre-JS idle label renders):
|
||||||
|
```html
|
||||||
|
<span class="sync-label" id="sync-label"><span class="sync-label-main">Sync sources</span><span class="sync-label-count" hidden></span></span>
|
||||||
|
```
|
||||||
|
2. `frontend/assets/sources.js` — one new helper where `fmtSyncLabel`/`fmtSyncPhaseLabel` live (~L650): `setSyncLabel(mainText, countText = "")` — sets `syncLabelMain.textContent = mainText`; if `countText`: `syncLabelCount.textContent = countText`, `syncLabelCount.hidden = false`; else `syncLabelCount.textContent = ""`, `hidden = true`; then sets the UNTRUNCATED full label — `mainText + (countText ? " " + countText : "")` — on `syncBtn.title` and `syncResult.textContent` (the A4 convention: title + aria-live always carry the whole thing). Get the part elements once at `mount` scope (the `querySelector` house pattern; null-guard like `syncLabel`).
|
||||||
|
- `fmtSyncLabel(kind, currentFile, done, total)` → return the PARTS: `main = currentFile ? `${prefix} ${currentFile}` : prefix` (prefix `"Syncing…"` / `"Importing"` as today), `count = total > 0 ? `(${done}/${total})` : ""`; call `setSyncLabel(main, count)`. The byte-identical full strings hold: `"Syncing…"` (no file), `"Syncing… <file>"` (no total), `"Syncing… <file> (n/m)"`, `"Importing"`.
|
||||||
|
- `fmtSyncPhaseLabel(status)` → same decision tree (overview / summaries / fall-through), emitting parts: overview → `("Writing KB overview…", "")`; summaries → `(`Summarizing folders…${folder}`, `(${status.summaries_done}/${status.summaries_total})`)` with the folder part omitted while `current_summary` is null (as today) — the count is ALWAYS emitted in this phase (the hook always carries a total); fall-through → the `fmtSyncLabel` parts. The full-string shape is byte-identical to the pre-task strings.
|
||||||
|
- Every OTHER call site that writes `#sync-label` (idle `"Sync sources"`, settle `"Synced HH:MM"`, the 202/409 click fallback, the re-attach `initSyncButton` path) goes through `setSyncLabel(main)` — count hidden.
|
||||||
|
- The upload job keeps the bare `"Importing"` (no file, no counts — phase-90 contract).
|
||||||
|
3. `tests/unit/test_frontend_sync_upload.py` — update the pinned label tests to the part shape: pin the main/count pair per state (prelude, import with/without total, overview, summaries with/without folder, upload, idle, settle) AND the `title` / `#sync-result` untruncated concatenation (the A4 pins).
|
||||||
|
|
||||||
|
ASSUMPTION (A1 restated): the truncated TODO item is satisfied by "label fully visible on mobile + count never clipped" — no wrapping, no progress bar.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the updated pins above green; no HTML strings anywhere in the label path (textContent only).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] every running/idle/settle label renders the SAME full string as pre-task on desktop (the part concatenation is byte-identical)
|
||||||
|
- [ ] the count span is `hidden` whenever there is no `(n/m)` to show
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Task 02 — CSS: the label parts flex — path ellipsizes, count pinned, mobile fully visible
|
||||||
|
|
||||||
|
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The label's two parts are laid out so the path can ellipsize against whatever width is available — and on a phone, where the pill is full-width, the path ellipsizes and the `(n/m)` count sits pinned at the right edge, always on-screen.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/styles.css` — replace the `.sync-label` rule (~L2067, the phase-64 comment block above it stays, updated to name the parts):
|
||||||
|
```css
|
||||||
|
.sync-label {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.35rem;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: min(16rem, 40vw);
|
||||||
|
}
|
||||||
|
.sync-label-main {
|
||||||
|
min-width: 0; /* the flex item that shrinks — what engages the ellipsis */
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.sync-label-count {
|
||||||
|
flex: 0 0 auto; /* NEVER clipped — the (n/m) position is the point */
|
||||||
|
white-space: nowrap;
|
||||||
|
font-family: var(--mono); /* the .sync-result mono language (position reads as data) */
|
||||||
|
}
|
||||||
|
```
|
||||||
|
(The old `display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom;` moves to `.sync-label-main` — `vertical-align` is gone: the flex row aligns it.)
|
||||||
|
2. `frontend/assets/styles.css` — the mobile media query block (~L5323, the "full-width LABELED pills" comment): update the two sync rules:
|
||||||
|
```css
|
||||||
|
.sync-btn { width: 100%; }
|
||||||
|
.sync-label { max-width: none; flex: 1 1 auto; min-width: 0; }
|
||||||
|
```
|
||||||
|
— the label now fills the full-width pill; `.sync-label-main` (min-width: 0 inside a flex row that can shrink) ellipsizes against the width left by the pinned count; the count stays visible at the right edge. Do NOT touch the `#sync-result` visually-hidden clip, the `#sync-btn` aria-label, or the other mobile rules in that block.
|
||||||
|
3. Audit: grep for every `.sync-label` reference in `styles.css` — the only rules are the base + this mobile block (the phase-64/98 history is in comments). Confirm no other stylesheet (theme override, page-scoped) styles the label; the built-in theme must stay byte-identical in the no-row case (B4 — no `ui_settings` dependency here, this is static CSS).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The visual gate is the E2E (task 03) — desktop vs mobile bounding-box + text assertions; no new Python surface.
|
||||||
|
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] desktop: long paths still ellipsize inside the `min(16rem, 40vw)` cap, count visible after the ellipsis
|
||||||
|
- [ ] mobile (390 px): label fills the pill, path ellipsized, `(n/m)` on-screen at the right edge (the E2E asserts bounding boxes)
|
||||||
|
- [ ] `uv run pytest` green; no behavior change in completed phases
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Task 03 — E2E: the running sync label is fully visible with its count on mobile (and unchanged on desktop)
|
||||||
|
|
||||||
|
**Phase:** `128_sync_label_mobile` · **Source:** `TODO.md:4` — "The `Syncing… name/of/file/here (2/3)` doesn't show up on mobile, it needs to" (A1: fully visible on mobile, count never clipped)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the label's geometry: at a phone viewport the rendered `#sync-label` fits the viewport with the `(n/m)` count span visible in BOTH long spans (import + summaries); at a desktop viewport the label keeps its pre-phase strings and cap.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_sync_label_mobile.py` (new) — follow `tests/e2e/test_sync_summary_visibility.py`'s house pattern (module app fixtures over the shared E2E Postgres, host temp-dir `kind=local` source, autouse truncate cleanup, mock-only). Use the SLOW app (the `tests/e2e/slow_llm.py` proxy, `SLOW_DELAY_S = 1.5` as there) so each phase span outlives the UI's 2 s poll — the rendered-label assertions are deterministic, not races.
|
||||||
|
KB fixture — one local source `synclabel/` with TWO files in `alpha/` and TWO in `bravo/` (the summaries phase then has 3 candidate folders: root + 2 — a non-trivial `(n/m)`).
|
||||||
|
2. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_mobile_label_fits_viewport_with_count_in_import` — admin page on the sources view at viewport **390×844** (mobile); click **Sync sources**; while the import phase is running (the page's own 2 s poll): the rendered `#sync-label`'s bounding box is INSIDE the viewport (left ≥ 0, right ≤ 390) — the bug's direct negation; `.sync-label-count` is visible (`boundingBox` non-null, not clipped: its right edge ≤ the button's right edge) with text matching `\(\d+/\d+\)` once a file is in flight; `.sync-label-main` carries `Syncing… <file>` (the file part may be visually ellipsized — assert the button `title` carries the UNTRUNCATED label, A4).
|
||||||
|
- `test_mobile_label_shows_summaries_count` — same mobile viewport; through to the summaries phase: `.sync-label-main` matches `Summarizing folders…` (folder part optional), `.sync-label-count` matches `\(\d+/3\)` and stays visible; settle: the button leaves the running label (`Synced HH:MM` or the phase-32 terminal shape), the count span hidden/empty.
|
||||||
|
- `test_desktop_label_unchanged` — viewport 1280×800; same sync: during import the FULL rendered label text (main + count concatenation) matches `Syncing… <full source/relative/path> (n/m)` — the pre-phase byte-identical string — and the label's width respects the `min(16rem, 40vw)` cap (bounding box width ≤ 256 px + slack); `title` carries the same untruncated string.
|
||||||
|
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov`), the mock-only + slow-proxy rationale (re-sized from the phase-98 suite's comment), the fixture layout, the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% bar is carried by task 01's updated unit pins (frontend JS); this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_label_mobile.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the mobile tests fail against the pre-phase markup/CSS (the count ran off-screen) — i.e. the suite actually pins the fix
|
||||||
|
- [ ] no behavior change in completed phases (label strings, phase machine, aria-live)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Phase 129 — The sync label shows what chunk we're on out of how many
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L5 — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (ASSUMPTION A6, owner-confirmed 2026-09-27: "chunk" = the current file's EMBEDDING CHUNKS; position reported at BATCH granularity — `n` = first chunk of the in-flight token-budgeted embed batch — because the transport embeds batches per HTTP call and per-chunk calls would be a latency regression; the summary-chunk embed is excluded from the counter; label `Syncing… <file> (2/3) · chunk 14/38`).
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append; a NEW feature — distinct from phase 128's mobile fix, per the owner).
|
||||||
|
**Context:** `app/rag/llm.py` — `LLMClient.embed(texts)` (L346: iterates `self._batch_texts(texts)` — token-budgeted batches, `BOR_EMBED_BATCH_SIZE` cap, `_REQUEST_TOKEN_BUDGET` ≈ 2800 chars), `_embed_batch` (L289: the halving backstop on `_TooLarge`), `self.embed_batches` counter (L249); `app/rag/importer.py` — `import_sources` (L408, the per-file `progress(source, rel, done, total)` hook fired BEFORE each `_index_file`), `_index_file` (L647 — text branch → `_replace_content_chunks`, image branch → `_index_image_file`, PDF branch → `_index_pdf_file`), `_replace_content_chunks` (L603 — chunks the content, `llm.embed([c.content for c in doc.chunks])` in ONE call, token-cap re-chunk retry loop), `_store_summary` (embeds the ONE summary chunk — EXCLUDED from the counter); `app/api/sync.py` — `SyncStatus` (the phase-64/98 progress fields: `current_file`, `files_done/total`, `phase`, `current_summary`, `summaries_done/total`; `_run_sync`'s `_hook` closure convention; terminal-state clearing); `frontend/assets/sources.js` — the phase-128 part builders (`setSyncLabel`, `.sync-label-main` / `.sync-label-count`); `tests/e2e/slow_llm.py` + `tests/e2e/test_sync_summary_visibility.py` — the slow-proxy sampling pattern.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
While a file is being imported, the sync status (endpoint + button label) shows the file's embedding-chunk position: `Syncing… <file> (2/3) · chunk 14/38` — 14 = the first chunk of the embed batch in flight, 38 = the file's total content chunks. The position climbs through the file's batches and is cleared when the file (or the run) moves on. Everything that passes no callback stays a zero-cost no-op (the CLI, the chat path).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `128_sync_label_mobile` (todo) — the label's part structure (`.sync-label-main` + pinned count span) is the carrier; this phase adds the pinned chunk span.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The embed hook (task 01):** `LLMClient.embed(texts, on_progress: Callable[[int, int], None] | None = None)` — before EACH top-level batch request, `on_progress(first_1based, len(texts))` where `first_1based` = 1 + the cumulative chunk counts of the already-sent batches. `None` (every existing caller — the chat retrieval path, `embed_one`, the summarizer, the CLI) is a zero-cost guarded no-op. The `_embed_batch` halving backstop does NOT sub-report — the top-level loop reports batch starts; a halved batch means the position is approximate (document in the docstring; the backstop is rare by construction).
|
||||||
|
- **Importer plumbing (task 02):** `import_sources(..., on_chunk_progress: Callable[[int, int], None] | None = None)` — a new keyword-only param, plumbed: `import_sources` → `_index_file(..., on_chunk=...)` (all three branches: text, image, PDF — the PDF branch's content embed is the same `_replace_content_chunks` call; the image branch's ONE description-chunk embed reports `1/1` — acceptable, it IS the file's only chunk) → `_replace_content_chunks(..., on_chunk=...)` → `llm.embed([...], on_progress=on_chunk)`. The token-cap re-chunk retry re-embeds with the NEW (smaller-target) chunk list — the hook naturally reports against the new total (no special case). `_store_summary`'s single summary-chunk embed NEVER receives the hook (the counter is content chunks only — no `1/1` noise after the real progress ends). The `scripts/import_docs.py` CLI passes nothing — byte-identical.
|
||||||
|
- **Sync status (task 03):** `SyncStatus` gains `current_chunk: int = 0` and `chunks_total: int = 0` (documented: the current file's embed-batch position — 0/0 before the first batch and in terminal states). `_run_sync`: reset to 0/0 at run start (with the other progress fields); a closure `_chunk_hook(chunk, total)` (the file's `_hook` convention) sets them; passed as `on_chunk_progress` to `import_sources`. CLEARED (0/0) when the import phase ends — set at the `phase = "overview"` and `phase = "summaries"` transitions AND in both terminal states (the `current_file` clearing points — same convention, same spots). `GET /api/sync/status` exposes both fields (0/0 idle — the dataclass defaults). The `SyncStatus` docstring + module docstring get the chunk-position paragraph (the phase-64/98 style).
|
||||||
|
- **UI (task 04):** `sources.js` — the import-phase label gains a THIRD pinned part `.sync-label-chunk` (markup in `index.html`'s `#sync-label`, `hidden` by default): when `status.chunks_total > 0` the import fall-through emits `· chunk ${status.current_chunk}/${status.chunks_total}` into it; every other phase/state leaves it hidden/empty (the summaries phase has its own `(n/m)` — no chunk part; the prelude has no file yet). The UNTRUNCATED concatenation (main + count + chunk part) rides the button `title` + `#sync-result` (A4). The pinned unit tests (`tests/unit/test_frontend_sync_upload.py`) gain the chunk-part pins.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_llm_embed_hook.md` — `LLMClient.embed`'s optional per-batch `on_progress`.
|
||||||
|
2. `02_importer_chunk_progress.md` — `import_sources` → `_index_file` → `_replace_content_chunks` → `embed` plumbing.
|
||||||
|
3. `03_sync_status_chunk_fields.md` — `SyncStatus` fields, the closure, clearing, the endpoint.
|
||||||
|
4. `04_ui_chunk_part.md` — the label's chunk part + unit pins.
|
||||||
|
5. `05_e2e_chunk_progress.md` — dedicated Playwright E2E, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: the embed hook's call sequence (batch boundaries, `None` no-op, halving-approximate documented); the importer plumbing (hook fires per file with its own total; the CLI path unchanged; the summary-chunk embed never fires it); the sync status (fields in the endpoint JSON, reset per run, cleared at phase transitions + terminal, 0/0 idle).
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, slow-LLM sampling.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `GET /api/sync/status` reports `current_chunk` climbing 1 → N with `chunks_total` = the file's true content-chunk count while a file imports (E2E, sampled)
|
||||||
|
- [ ] the rendered mobile/desktop label shows `· chunk n/m` during the import phase only; the untruncated text rides `title` + `#sync-result`
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (chat embed path, CLI import, the phase-64/98 label contract minus the new part)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Task 01 — `LLMClient.embed`'s optional per-batch `on_progress` hook
|
||||||
|
|
||||||
|
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`embed` can report, before each top-level batch request, which chunk of the input list starts that batch — `on_progress(first_1based, total)` — so a caller can render `chunk n/m`. No callback → zero-cost no-op, byte-identical behavior for every existing caller.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/llm.py` — `LLMClient.embed` (L346): new keyword-only param `on_progress: Callable[[int, int], None] | None = None`. In the batch loop, BEFORE `await self._embed_batch(chunk)` (and before the try/except, so a failing batch still announced its start):
|
||||||
|
```python
|
||||||
|
if on_progress is not None:
|
||||||
|
on_progress(len(out) + 1, len(texts)) # first chunk of THIS batch (1-based), total
|
||||||
|
```
|
||||||
|
(`len(out)` = chunks already embedded in earlier batches — the accumulator's length is exactly that, since each batch's vectors extend it 1:1.)
|
||||||
|
Docstring: the contract — called once per TOP-LEVEL batch, before the request, with `(first_chunk_1based, total_chunks)`; the `_embed_batch` halving backstop does not sub-report (a halved batch makes the position approximate — documented; the backstop is rare by construction, phase-114 `_TooLarge` handling); `None` is a zero-cost guarded no-op (every pre-task caller — chat retrieval, `embed_one`, the summarizer, the importer — passes nothing and is byte-identical).
|
||||||
|
2. Do NOT touch `_batch_texts` / `_embed_batch` internals, `embed_batches` counting, or `embed_one`.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/` (extend the existing LLM-client test file — inspect `tests/unit/test_llm*.py` first):
|
||||||
|
- N texts sized to force ≥ 3 batches (shrink the token budget via settings or pick chunk lengths against `_REQUEST_TOKEN_BUDGET`) → `on_progress` called with `(1, N)`, `(k2, N)`, … `total` always `len(texts)`, first-indices strictly increasing, each = previous first + previous batch size (assert against `_batch_texts`'s actual partition — call it directly to get the expected boundaries);
|
||||||
|
- `on_progress=None` → the call sequence and return value are identical to pre-task (the existing suite is the pin);
|
||||||
|
- empty `texts` → no hook calls (the early return).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the hook fires per top-level batch with the correct `(first, total)` pair (unit-pinned)
|
||||||
|
- [ ] every existing `embed`/`embed_one` call site is untouched and its tests green
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Task 02 — Importer plumbing: `on_chunk_progress` from `import_sources` to the content-chunk embed
|
||||||
|
|
||||||
|
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`import_sources` accepts an optional `on_chunk_progress` callback that fires with the CURRENT FILE's content-chunk position while that file's chunks embed — so the sync status can attribute the position to the file its per-file `progress` hook already named.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/importer.py` — `import_sources` (L408): new keyword-only param `on_chunk_progress: Callable[[int, int], None] | None = None` (documented in the docstring next to the `progress` paragraph: same "only when provided — `None` callers pay nothing" rule; it carries the in-flight FILE's chunk position, not the file identity — the per-file `progress` hook owns that).
|
||||||
|
2. `app/rag/importer.py` — the processing loop's `_index_file` call: pass `on_chunk=on_chunk_progress` (a new keyword-only param on `_index_file`, default `None`).
|
||||||
|
3. `app/rag/importer.py` — `_index_file`:
|
||||||
|
- the TEXT branch → `_replace_content_chunks(session, doc=doc, llm=llm, content=content, rel=rel, on_chunk=on_chunk)`;
|
||||||
|
- the IMAGE branch (`_index_image_file`) and the PDF branch (`_index_pdf_file`) → pass `on_chunk` through to THEIR `_replace_content_chunks` calls (the image branch's one description-chunk embed reports `1/1` — it IS the file's only chunk; the PDF branch's content embed is the primary target). Verify each branch's embed path: if a branch embeds chunks somewhere other than `_replace_content_chunks`, route the hook there too (one hook per branch, content chunks only).
|
||||||
|
4. `app/rag/importer.py` — `_replace_content_chunks` (L603): new keyword-only param `on_chunk: Callable[[int, int], None] | None = None`, forwarded to `llm.embed([c.content for c in doc.chunks], on_progress=on_chunk)`. The token-cap re-chunk retry loop (the `while True` that halves `target`) re-embeds with the new chunk list — the hook reports against the NEW total automatically (no special case; document it in the docstring). The `doc.chunks = []` empty-content `break` never embeds (no hook fire).
|
||||||
|
5. `_store_summary` (and its summary-chunk `embed_one`/`embed` call) NEVER receives the hook — the counter is content chunks only (A6: no `1/1` noise after the real progress ends). The `scripts/import_docs.py` CLI passes nothing — byte-identical (verify the call site).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_importer.py` (extend) —
|
||||||
|
- a text file that chunks into ≥ 2 batches (size the fixture against the token budget, or monkeypatch `_batch_texts`) with a fake `on_chunk_progress` recorder → the recorder sees `(first, total)` pairs with `total == the file's chunk count`, one batch-run per file, and a SECOND file in the same run gets its OWN sequence (the position restarts per file — the recorder's `(first, total)` pairs never mix the two files' totals);
|
||||||
|
- the image branch (images toggle on, a fixture image) → the recorder sees exactly `(1, 1)` for that file;
|
||||||
|
- `on_chunk_progress=None` (the CLI shape) → no recorder, behavior byte-identical (the existing suite is the pin);
|
||||||
|
- the summary-chunk embed never fires the hook (the recorder's call count == the content-embed batches only).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a multi-batch file's embed position is fully observable through `import_sources(on_chunk_progress=…)` (unit-pinned)
|
||||||
|
- [ ] the CLI path and the summary-chunk embed are untouched (byte-identical, verified by the existing suite)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Task 03 — `SyncStatus` chunk fields: `current_chunk` / `chunks_total` on the status endpoint
|
||||||
|
|
||||||
|
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`GET /api/sync/status` carries the in-flight file's embed-chunk position (`current_chunk`, `chunks_total`) so the UI can render `· chunk n/m` — reset per run, cleared when the import phase ends, 0/0 idle (the phase-64/98 field conventions).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/api/sync.py` — `SyncStatus` dataclass: add
|
||||||
|
```python
|
||||||
|
# Phase 129: the current file's EMBED chunk position — the first
|
||||||
|
# chunk of the in-flight token-budgeted batch and the file's total
|
||||||
|
# content chunks (the LLMClient.embed hook, batch granularity).
|
||||||
|
# 0/0 before the first batch, during the prelude/overview/summaries
|
||||||
|
# phases, and in terminal states.
|
||||||
|
current_chunk: int = 0
|
||||||
|
chunks_total: int = 0
|
||||||
|
```
|
||||||
|
Update the `SyncStatus` docstring (the phase-64/98 progress-field paragraph) to name the new fields and their clearing contract.
|
||||||
|
2. `app/api/sync.py` — `_run_sync`:
|
||||||
|
- run start: `_status.current_chunk = 0`, `_status.chunks_total = 0` (with the other progress-field resets);
|
||||||
|
- the closure (the file's `_hook` convention — closures capture the module `_status`):
|
||||||
|
```python
|
||||||
|
def _chunk_hook(chunk: int, total: int) -> None:
|
||||||
|
_status.current_chunk = chunk
|
||||||
|
_status.chunks_total = total
|
||||||
|
```
|
||||||
|
passed to `import_sources(..., on_chunk_progress=_chunk_hook)` (alongside the existing `progress=_hook`);
|
||||||
|
- CLEARING (0/0) at every point the import phase ends — the `_status.phase = "overview"` assignment, the `_status.phase = "summaries"` assignment, and BOTH terminal states (the success and except blocks where `_status.current_file = None` — the phase-64 keep-final-FILE-counts convention does NOT extend to the sub-file chunk position: the file counts survive the terminal for the result line's context, the chunk position is a sub-position of a file that's done — it clears, like `current_file`);
|
||||||
|
- the unchanged-walk / no-sync-idle paths never set them (defaults 0/0).
|
||||||
|
3. `app/api/sync.py` — `sync_status` endpoint: add `"current_chunk": _status.current_chunk, "chunks_total": _status.chunks_total` to the returned dict (place them after the `files_*` fields; the dataclass defaults make idle 0/0 with no special-casing). Update the endpoint docstring's field list (the phase-98 paragraph) and the module docstring's status paragraph with the chunk-position contract.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: extend the sync unit suite (the file that fakes `import_sources` — inspect `tests/unit/test_sync_button.py` and the sync-pipeline test first):
|
||||||
|
- idle → `current_chunk == 0`, `chunks_total == 0` in the JSON (the dataclass defaults — the endpoint shape test);
|
||||||
|
- a running sync whose fake `import_sources` invokes `on_chunk_progress(1, 38)` then `(13, 38)` → the status between ticks reports the pair (assert on `_status` directly or via the endpoint through the existing app fixture);
|
||||||
|
- phase transition to `overview`/`summaries` → the fields are 0/0 again; terminal success/failed → 0/0 while `files_done`/`files_total` keep their final values (the convention split, pinned).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the status endpoint JSON carries both fields; idle is 0/0; a running import reports the hook's pair
|
||||||
|
- [ ] the fields clear at phase transitions + terminal states while the file counts keep-final (pinned test)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Task 04 — The label's chunk part: `Syncing… <file> (2/3) · chunk 14/38`
|
||||||
|
|
||||||
|
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The running sync label shows the chunk position as a third pinned part — rendered ONLY while `chunks_total > 0` (the import phase, after the file's first batch), hidden in every other state — and the untruncated full label (main + count + chunk part) keeps riding the button `title` + `#sync-result` (A4).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/index.html` — `#sync-label` (the phase-128 two-part markup): add the third part after the count span: `<span class="sync-label-chunk" hidden></span>`.
|
||||||
|
2. `frontend/assets/styles.css` — `.sync-label-chunk { flex: 0 0 auto; white-space: nowrap; font-family: var(--mono); }` (the same pinned-part language as `.sync-label-count` — place it right after that rule; both mono parts read as data).
|
||||||
|
3. `frontend/assets/sources.js` —
|
||||||
|
- get the chunk part at `mount` scope (the phase-128 `querySelector` pattern, null-guarded);
|
||||||
|
- `setSyncLabel(mainText, countText = "", chunkText = "")` — the new third arg: when `chunkText`, set `.sync-label-chunk.textContent` + `hidden = false`, else `""` + `hidden = true`; the UNTRUNCATED concatenation for `title` + `#sync-result` becomes `mainText` + (count? `" " + countText`) + (chunk? `" " + chunkText`) (A4 — the announcer hears the whole `Syncing… <file> (2/3) · chunk 14/38`);
|
||||||
|
- the import fall-through (the `fmtSyncPhaseLabel` fall-through / the 202/409 click label site — everywhere the import label is emitted with a status): `chunkText = status.chunks_total > 0 ? `· chunk ${status.current_chunk}/${status.chunks_total}` : ""` — every OTHER state (prelude, overview, summaries, upload, idle, settle) passes no chunk text (the part hides): the summaries phase's own `(n/m)` count is its position — no chunk part there;
|
||||||
|
- the `title`/`#sync-result` set on EVERY running label (the house rule) automatically carries the chunk part via the concatenation.
|
||||||
|
4. `tests/unit/test_frontend_sync_upload.py` — extend the phase-128 part pins: the import state with `chunks_total > 0` emits the chunk part (`· chunk 14/38` for the fixture values) and the untruncated `title` string is `Syncing… <file> (2/3) · chunk 14/38`; the import state with `chunks_total == 0` (before the first batch) hides the part; every other state's pins stay (the part hidden).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pins above green; textContent-only (no HTML strings in the label path).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `· chunk n/m` renders only while `chunks_total > 0`; hidden in all other states (unit-pinned)
|
||||||
|
- [ ] the untruncated full label (with the chunk part) rides `title` + `#sync-result` (A4, unit-pinned)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed phases (phase-128 pins still pass)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Task 05 — E2E: the chunk position climbs through a large file's embed batches, endpoint + label
|
||||||
|
|
||||||
|
**Phase:** `129_sync_chunk_progress` · **Source:** `TODO.md:5` — "The `Syncing… name/of/file/here (2/3)` needs to show what chunk we're on out of how many" (A6: batch-granularity chunk position)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the feature at both surfaces: the endpoint's `current_chunk` climbs 1 → N with `chunks_total` = the file's true chunk count, and the rendered label shows `· chunk n/m` while the file's embed span runs (then the part clears).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_sync_chunk_progress.py` (new) — house pattern from `tests/e2e/test_sync_summary_visibility.py` (module app fixtures over the shared E2E Postgres, host temp-dir `kind=local` source, autouse truncate cleanup, mock-only, the `tests/e2e/slow_llm.py` proxy).
|
||||||
|
Sizing (the phase-98 rationale, re-sized for batches): the fixture is ONE local source `chunkprog/` holding ONE large markdown file (`big.md`, ~60 KB, ~30+ chunks at the default target — compute the expected chunk count deterministically in the test by calling `chunk_document` with the app's settings, the same function the importer uses — and assert `chunks_total` equals it) plus ONE tiny second file (the file counter then reads `(1/2)` → `(2/2)`, proving the chunk position restarts per file). `SLOW_DELAY_S` sized so each embed batch outlives the recorder's ~100 ms cadence (the proxy delays EVERY LLM call — embeds included — so the import span is densely sampled).
|
||||||
|
2. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_endpoint_reports_the_chunk_position` (the slow leg — tight-poll recorder on `GET /api/sync/status`, the phase-64 recorder pattern): while `phase == "import"`: some ticks have `chunks_total == <expected chunk count>` and `current_chunk` strictly climbing from 1 toward `chunks_total` (batch granularity — the sequence's LAST tick before the file ends is `chunks_total` or its final batch's first index; assert the climb + the total, not a contiguous run); while the second (tiny) file is in flight the position restarts (a later tick has `current_chunk == 1` with `chunks_total == 1`); the terminal state has `current_chunk == 0` and `chunks_total == 0` while `files_done == files_total == 2` (the keep-final-file-counts split, the phase-129 convention).
|
||||||
|
- `test_label_shows_the_chunk_part` (the slow leg — UI, the page's own 2 s poll): at the import span the rendered `#sync-label` parts: `.sync-label-main` matches `Syncing… chunkprog/big.md`, `.sync-label-count` matches `(1/2)`, and at some tick `.sync-label-chunk` is visible matching `· chunk \d+/\d+` with the total == the expected chunk count; the button `title` carries the UNTRUNCATED concatenation (A4 — assert it contains `· chunk` on the same tick); after the file's embed span the chunk part is hidden (`.sync-label-chunk.hidden` true) while the file label continues.
|
||||||
|
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov`), the mock-only gate, the sizing rationale (why the file is ~60 KB, why the slow proxy's delay doubles as the batch sampler), the fixture layout, the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% `app/` bar is carried by tasks 01–03; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_chunk_progress.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the endpoint's `chunks_total` equals the deterministic `chunk_document` count for the fixture (the total is the file's TRUE chunk count, not a batch count)
|
||||||
|
- [ ] the chunk part renders only during the import phase and clears at the phase transition/terminal (UI-pinned)
|
||||||
|
- [ ] no behavior change in completed phases (the phase-64/98 label contract + the keep-final-counts convention hold)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Phase 130 — Chat answer clusters: chips row, images row, bottom-right actions cluster
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L6 — "The chat output is getting messy. I think it's because the `source-chip`, `source-image`, `tune-btn`, `retry-btn`, and `save-as-doc-btn` end up in the same div which causes them to push each other in weird ways. Those three buttons should be in a button cluster in the bottom right. We don't need to display the `source-chip` for images, just the image itself is fine. `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/assets/app.js` — `appendSources` (~L1561: builds the FIRST `.msg-meta` row, interleaving a `.source-image` figure after each chip for refs carrying `image_url`), `appendRelated` (~L1618: the "Nearby docs" row, appended LAST among meta rows), `appendSourceImageFigure` (~L1660: the compact figure; on `img` error it removes the figure and the chip remains), `appendAnswerImage` (~L1735: the `.answer-image` figure — appended by callers right BEFORE `appendSources`), `appendTuneButton` (~L484, admin-gated), `appendRetryButton` (~L598), `appendSaveAsDocButton` (~L793, admin + docs-repo gated; `margin-inline-start: auto` pushes it right), `markLastRetryable` (~L620: re-appends the Retry button on the last bubble and re-appends the save button after it — "the auto margins split the free space"), `appendStoppedNote` / `appendFailedNote` (~L520/~L560: join the first `.msg-meta` row); `frontend/assets/styles.css` — the `.msg-meta`, `.source-chip`, `.source-image`, `.tune-btn`, `.retry-btn`, `.save-as-doc-btn` rules (grep each — the auto-margin rules live here); `frontend/index.html` — no chat markup changes expected (the bubble DOM is JS-built); E2E image-KB fixture patterns in `tests/e2e/test_chat_image_questions.py` / `test_image_documents.py` (the mock's `IMAGE_DESCRIPTION_MODE` canned vision reply makes image docs retrievable).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A completed brain bubble's metadata reads as organized clusters, top to bottom: the answer text → the answer figure (phase 124, unchanged) → the **source chips row** (text documents only — an image document gets NO chip, just its figure) → the **source images row** (all retrieved image figures) → the "Nearby docs" row (unchanged) → the **actions row** (a right-aligned cluster holding Tune / Retry / Save-as-doc and the Stopped/Failed notes) — never one soup div where buttons push chips around.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `129_sync_chunk_progress` (todo) — pipeline order only; code dependencies are the completed chat-render contract (phases 26/49/59/113/120/122/124).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Row structure per brain bubble (top → bottom):** (1) answer text; (2) `.answer-image` figure — the phase-124 position is UNCHANGED (below the text, before the source rows — A3); (3) `.msg-meta` chips row (`role=list`, `aria-label="Sources"`) — one `.source-chip` per NON-image ref; refs with `image_url` contribute NO chip (ASSUMPTION A3 — the figure is the citation for image docs); (4) `.msg-meta.msg-images` images row (`role=list`, `aria-label="Source images"`) — one `.source-image` figure per image ref, in ref order; the row is absent when there are no image refs; (5) `.msg-meta.related-docs` — the phase-113 row, UNCHANGED in content, placed after the images row (ASSUMPTION A4); (6) `.msg-meta.msg-actions` actions row (`role=list`, `aria-label="Answer actions"`) — the ONLY row the action buttons + the stopped/failed notes join (ASSUMPTION A7).
|
||||||
|
- **Call order at every render site** (the `done` branch, the empty-answer fallback, the stop finalize, the phase-14 restore path): answer image → `appendSources` (now builds the chips row AND the images row) → `appendRelated` → the action buttons/notes. The current "buttons claim the FIRST `.msg-meta` row" behavior is REPLACED — the buttons get-or-create `.msg-actions` instead.
|
||||||
|
- **Image-load failure (ASSUMPTION A3):** `appendSourceImageFigure`'s `img` error handler replaces the figure IN PLACE with a plain `.source-chip` anchor for that document (same `documentUrl` href, same modal click behavior, the label as text) — the citation survives a lost byte copy; no broken-image icon.
|
||||||
|
- **Actions row:** one get-or-create `.msg-actions` per bubble (the house pattern). DOM order = Tune, Retry, Save-as-doc (each present per its gate — non-admins see only Retry; a stopped bubble sees the note + Retry). The note (`appendStoppedNote` / `appendFailedNote`) joins this row. `markLastRetryable`'s re-append logic moves the Retry button into `.msg-actions` and DROPS the save-button re-append hack (row-level alignment replaces the per-button `margin-inline-start: auto` — CSS task). ARIA: `role=list` + `role=listitem` on every child (the existing convention).
|
||||||
|
- **CSS:** `.msg-actions { justify-content: flex-end; }` (the right-aligned cluster — "bottom right" = the bubble's last row, right edge); remove the per-button auto margins (`.save-as-doc-btn`'s `margin-inline-start: auto` + the tune/retry auto margins the `markLastRetryable` comment names); the chips row keeps its wrap; `.msg-images` wraps with the `.msg-meta` gap; the row ORDER is DOM order (no positioning tricks); mobile: rows stack naturally, the actions row stays right-aligned.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_sources_clusters.md` — `appendSources`/figure split: chips-only row + images-only row, no chip for image docs, the in-place chip fallback.
|
||||||
|
2. `02_actions_cluster.md` — the `.msg-actions` row: the three buttons + the notes, `markLastRetryable` rework, ARIA kept.
|
||||||
|
3. `03_css_clusters.md` — the cluster CSS (actions right-aligned, auto margins removed, images row).
|
||||||
|
4. `04_e2e_clusters.md` — dedicated Playwright E2E, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the frontend unit suite — the pinned behaviors that move (the button-row target, the no-chip-for-images rule, the fallback) — inspect `tests/unit/test_frontend_*.py` for the chat-render pins and update them.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, image-KB fixture (text doc + image doc both cited).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend: unit pins + E2E; `app/` untouched this phase).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a bubble citing a text doc + an image doc renders: chips row (text chip only, NO chip for the image) → images row (the figure) → actions row (bottom right) — asserted in the DOM, not the pixels
|
||||||
|
- [ ] Tune/Retry/Save-as-doc sit in ONE `.msg-actions` row, right-aligned; non-admin sees only Retry; the restore path renders the identical structure
|
||||||
|
- [ ] an image whose bytes 404 renders as its plain chip (the citation survives)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (chips still open the modal, the related row, the answer figure's position, the ARIA names)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 01 — Sources split: chips-only row, then images-only row; no chip for image docs
|
||||||
|
|
||||||
|
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...We don't need to display the `source-chip` for images, just the image itself is fine. `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`appendSources` stops interleaving figures after chips. It builds the chips row from the NON-image refs only, then (when any image ref exists) a separate images row holding all the figures — chips cluster first, images cluster second, image documents cited by their figure alone.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — `appendSources(wrap, sources)`:
|
||||||
|
- Partition the refs: `imageRefs = sources.filter(s => s.image_url)`, `textRefs = sources.filter(s => !s.image_url)` (the `image_url` presence is the existing image-doc signal — phase 122).
|
||||||
|
- CHIPS ROW: build it (the existing `.msg-meta` + `role=list` + `aria-label="Sources"` + per-chip `documentUrl`/modal click/`title`/clipped `aria-label` code) from `textRefs` ONLY. Skip the row entirely when `textRefs` is empty (an image-only citation still gets its images row + the actions row).
|
||||||
|
- IMAGES ROW: when `imageRefs.length > 0`, build a SECOND `.msg-meta` row — add the `msg-images` class, `role=list`, `aria-label="Source images"` — and append one `appendSourceImageFigure` per image ref (in ref order). No chips in this row.
|
||||||
|
- Preserve the existing post-build clipped-chip `aria-label` pass (the `scrollWidth > clientWidth` check) over the chips row only.
|
||||||
|
- The row ORDER in `.msg-body` is: answer figure (appended by the caller before `appendSources`, phase 124 — unchanged) → chips row → images row. `appendRelated` (the next caller) lands after both (task 02's call-order change guarantees the actions row is last).
|
||||||
|
2. `frontend/assets/app.js` — `appendSourceImageFigure(meta, s)`: the `img` error handler currently does `fig.remove()` (the chip remains — but there is no chip for image docs anymore). Change it to the IN-PLACE CHIP FALLBACK: build a plain `.source-chip` anchor for `s` (the same `documentUrl` href + `title` + left-click → modal handler the chips row uses; `textContent`/`aria-label` = the `source/path` label) and `replaceWith` the figure (the citation survives a lost byte copy — ASSUMPTION A3). The figure's fetch-summary swap is untouched.
|
||||||
|
3. `frontend/assets/app.js` — `appendRelated`: the related tier's refs ALSO carry `image_url` for image docs (phase 122 — `appendSourceImageFigure(row, s)` is called there today). Keep the related row's own behavior (its chips + figures) — the related row is a separate tier and is NOT reorganized by this phase (ASSUMPTION A4: it stays where it is, below the citation clusters). Do not change `appendRelated`'s chip/figure logic.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the frontend unit suite — inspect `tests/unit/test_frontend_*.py` for any `appendSources`/figure pins and update: no chip emitted for an `image_url` ref; the images row is built only when image refs exist; the in-place fallback replaces the figure with a chip (the figure's `img` error path).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a mixed citation (1 text + 2 image refs) renders a 1-chip row then a 2-figure row — no chip for either image
|
||||||
|
- [ ] an image-only citation renders NO chips row and a figures-only images row
|
||||||
|
- [ ] a figure whose bytes 404 becomes its plain chip in place (the citation survives)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Task 02 — The actions row: Tune / Retry / Save-as-doc + the notes in one bottom-right cluster
|
||||||
|
|
||||||
|
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...Those three buttons should be in a button cluster in the bottom right."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The three action buttons (and the Stopped/Failed notes) stop joining whatever the first `.msg-meta` row happens to be. They get-or-create a dedicated `.msg-actions` row — the bubble's LAST row, right-aligned by CSS (task 03) — so chips and images can never push the buttons around.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — a shared helper next to the button appenders: `getActionsRow(wrap)` — find or create the bubble's `.msg-meta.msg-actions` row inside `.msg-body` (`role=list`, `aria-label="Answer actions"`), the house get-or-create pattern (the same shape as the current "reuse the `.msg-meta` row when it exists" code, but scoped to the `msg-actions` class so it NEVER grabs the chips row).
|
||||||
|
2. `frontend/assets/app.js` — `appendTuneButton` (~L484), `appendRetryButton` (~L598), `appendSaveAsDocButton` (~L793): replace their "reuse the first `.msg-meta` row" logic with `getActionsRow(wrap)`; keep everything else (the gates, the one-button-per-bubble guards, the icons, the `role=listitem` when the row is `role=list`).
|
||||||
|
3. `frontend/assets/app.js` — `appendStoppedNote` (~L520) + `appendFailedNote` (~L560): join the actions row via `getActionsRow(wrap)` instead of the first `.msg-meta` row (ASSUMPTION A7 — the notes are answer-status markers; the actions row is their home). Keep the `failed-detail` textContent contract (no HTML from error strings).
|
||||||
|
4. `frontend/assets/app.js` — `markLastRetryable` (~L620): the retry button is removed from EVERY bubble and re-appended — but now into `getActionsRow(lastBrainWrap)`. DELETE the save-button re-append hack (the `saveDocBtn.parentElement.appendChild(saveDocBtn)` block) — the row's `justify-content: flex-end` (task 03) right-aligns the whole cluster; DOM order inside the row is the insertion order (Tune, Retry, Save-as-doc per their gates). Update the function's comment (the "auto margins split the free space" rationale is gone).
|
||||||
|
5. Call-order audit: at every site that renders a COMPLETED brain bubble (the `done` branch, the empty-answer fallback, the stop finalize, the phase-14 restore), confirm the order is answer figure → `appendSources` → `appendRelated` → action buttons/notes, so `.msg-actions` is the LAST row (the "bottom right" = the bubble's bottom, right edge). If a site appends actions before `appendRelated`, reorder the calls (the DOM order decides the visual order — no CSS tricks).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the frontend unit suite — update the pins that target the button row: the buttons/notes land in `.msg-actions` (not the chips row); `markLastRetryable` moves the Retry button into the actions row and no longer re-appends the save button.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a bubble with sources + all three buttons renders the actions row LAST, containing exactly the gated buttons (the notes when present)
|
||||||
|
- [ ] a non-admin bubble's actions row holds only Retry (the gate unchanged)
|
||||||
|
- [ ] the restore path renders the identical row (a saved chat re-opens with the buttons in `.msg-actions`)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Task 03 — CSS: the cluster rows (actions right-aligned, auto margins removed, images row)
|
||||||
|
|
||||||
|
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "...Those three buttons should be in a button cluster in the bottom right. ... `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The cluster layout is CSS: the actions row right-aligns its buttons as a cluster (no per-button auto margins), the images row wraps its figures like the chips row wraps chips, and the rows stack in DOM order with the existing `.msg-meta` rhythm.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/styles.css` — grep the current button-row rules (`.tune-btn`, `.retry-btn`, `.save-as-doc-btn`, and any `margin-inline-start: auto` on them — the `markLastRetryable`/phase-59 comments name the auto-margin mechanism; `.save-as-doc-btn`'s is explicit in the app.js comment at ~L653). Remove the per-button auto margins (the buttons become plain flex items of the actions row).
|
||||||
|
2. `frontend/assets/styles.css` — add the cluster rules (place them with the other `.msg-meta` / chip / figure rules — the house grouping):
|
||||||
|
```css
|
||||||
|
/* Phase 130: the actions cluster — the bubble's LAST row, right-aligned.
|
||||||
|
The row's justify does the "bottom right" (no per-button auto margins). */
|
||||||
|
.msg-meta.msg-actions {
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
/* Phase 130: the source-IMAGES cluster — wraps like the chips row. */
|
||||||
|
.msg-meta.msg-images {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.4rem; /* match the .msg-meta chip gap (read the existing value) */
|
||||||
|
}
|
||||||
|
```
|
||||||
|
(Match the EXISTING `.msg-meta` gap/align values — read the rule first; do not invent new spacing values that diverge from the chips row.)
|
||||||
|
3. Audit: confirm the chips row (`.msg-meta` with `role=list`) and the related row (`.msg-meta.related-docs`) rules are untouched; the `.source-image` figure styles are untouched (they were already sized for a row context); mobile: the rows stack naturally (the `.msg-body` flex gap handles it) — verify in the mobile media query block that no rule pins the actions row left; the actions row stays right-aligned at every width.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Visual gate: the E2E (task 04) — bounding-box assertions (the actions row's buttons' right edge ≈ the row's right edge; the row is the last `.msg-meta` in the bubble).
|
||||||
|
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the actions cluster is right-aligned by `.msg-actions` alone (the per-button auto margins are gone — grep confirms)
|
||||||
|
- [ ] the images row wraps its figures with the chips row's gap
|
||||||
|
- [ ] `uv run pytest` green; no behavior change in completed phases
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 04 — E2E: the answer renders as organized clusters (DOM-asserted), live + restored
|
||||||
|
|
||||||
|
**Phase:** `130_chat_answer_clusters` · **Source:** `TODO.md:6` — "The chat output is getting messy. ... Those three buttons should be in a button cluster in the bottom right. We don't need to display the `source-chip` for images ... `source-chips` should show up before images in their own cluster, then images in their own cluster to keep things organized."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix in the real DOM: a grounded answer citing a text doc AND an image doc renders the chips row (text chip only, NO chip for the image) before the images row (the figure), and the buttons sit in one right-aligned `.msg-actions` row that is the bubble's last row — on the live turn and after a page reload (the phase-14 restore path).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_chat_answer_clusters.py` (new) — house pattern (module app fixture over the shared E2E Postgres, autouse cleanup, mock-only). KB fixture: follow `tests/e2e/test_chat_image_questions.py` / `test_image_documents.py`'s image-KB pattern — a local source with ONE text doc (the mock's grounded-answer trigger, e.g. the existing "use your tools" / read flow that cites a doc) and ONE image doc (the mock's `IMAGE_DESCRIPTION_MODE` canned description makes it retrievable; the done frame's `sources` must carry both refs — the image ref with `image_url`). Inspect those suites first and reuse their fixture builders — do not invent a new mock flow unless the existing done-frame shape cannot cite both docs in one answer (if a new mock trigger is needed, add it to `tests/e2e/mock_llm.py` in the house style: a user-message marker, a deterministic reply, a module-header docstring entry).
|
||||||
|
Run as ADMIN (the whoami gate — the Tune + Save-as-doc buttons exist; the Retry button exists for everyone) with a configured docs repo (the `docsRepoConfigured` gate for Save-as-doc — follow the existing admin chat E2E setup).
|
||||||
|
2. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_answer_clusters_render_in_order` — send the question; on `done`: the LAST brain bubble's `.msg-body` direct children include, in order: the `.answer-image` (if the mock offers one — else skip) → a `.msg-meta` chips row containing EXACTLY the text doc's `.source-chip` and NO `.source-chip` for the image doc (assert by the chip's `source/path` label) → a `.msg-meta.msg-images` row containing the image's `.source-image` figure (the `img` loaded, the caption = the canned description/summary) → (the related row, if present) → a `.msg-meta.msg-actions` row that is the bubble's LAST `.msg-meta`, containing the `.tune-btn`, `.retry-btn`, `.save-as-doc-btn` (all three — admin); the actions row's buttons are right-aligned (the rightmost button's bounding-box right edge ≈ the row's right edge, slack for the row padding) and the row's bounding box is BELOW the images row's (the "bottom right" geometry).
|
||||||
|
- `test_image_without_chip_keeps_its_citation_via_figure` — in the same bubble: the image doc is cited (the figure's `href` = its `documentUrl`, left-click opens the same-page modal — the phase-26 affordance) and there is NO `.source-chip` whose label is the image's `source/path` (the owner's exact ask).
|
||||||
|
- `test_restore_renders_the_same_clusters` — the turn auto-saves (phase-66); reload the page; the restored last brain bubble has the IDENTICAL structure (chips row text-only, images row, `.msg-actions` last with the gated buttons — the restore path renders through the same appenders).
|
||||||
|
- `test_non_admin_sees_retry_only_actions` — a second, non-admin browser context on a FRESH chat (no admin cookie): send the same question; the `.msg-actions` row holds ONLY the `.retry-btn` (Tune/Save gated out — the phase-16/59 gates unchanged).
|
||||||
|
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov`), the mock-only gate, the fixture + mock-trigger notes, the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% bar is carried by tasks 01–02's updated frontend unit pins; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_chat_answer_clusters.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the DOM order assertion (chips → images → actions-last) is pinned for BOTH the live and the restored bubble
|
||||||
|
- [ ] the suite fails against the pre-phase markup (buttons inside the chips row) — i.e. it actually pins the fix
|
||||||
|
- [ ] no behavior change in completed phases (modal navigation, the related tier, the ARIA names)
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Phase 131 — `read` gains line ranges: grep finds the line, read(offset, limit) reads it
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L7 — "The agent is struggling with huge documents. It can search for the text it wants and it finds the text, including line number, but then it gets stuck saying 'However, read takes a path, not a line number.' and can't figure out how to read that part of the document. Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck. I have a huge test pdf (the DND player's handbook) in test_sources called 'pdf_tests.tar' that you can use for testing. It's a massive pdf. The question the agent got stuck on was 'What are the components of the find traps spell?' which is toward the end of the players handbook so it will need to search and read specific lines. I've been setting BOR_READ_MAX_CHARS to 24000 to keep things relatively quick so the agent realizes quickly its answer isn't in the first few pages."
|
||||||
|
(LOCKED A2, owner-confirmed 2026-09-27: the parameter names are `offset`/`limit` — 1-based line number + line count — mirroring the pi-harness `read` tool the model was trained on, the phase-70 "harness-aligned surface" anchor.)
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/agent.py` — `AGENT_TOOLS` (L258+: the `ls`/`read`/`grep` pi.dev-shaped schemas; the `read` schema at ~L304 takes ONLY `path`; the `grep` description promises `source/path:line: text` locators), `_execute_tool` (L1266+, the `read` branch at ~L1348: `arg` resolution, the `ALREADY_IN_CONTEXT` dedupe on `holder.read_docs`, the `BOR_READ_MAX_CHARS` truncation with `TRUNCATION_MARKER` + `READ_TRUNCATION_NOTICE` (~L506 — today it points at `grep` and then dead-ends), the `holder.read_truncations` tuples), `AgentHolder` (the `read_docs` / `read_truncations` bookkeeping); `app/rag/llm.py` — `ToolCallPiece` (the `arguments` dict the model sends); `tests/e2e/mock_llm.py` — the scripted tool-call flows (the "use your tools" / multi-read / grep patterns — the module header documents each trigger); `tests/unit/test_agent.py` — the read-branch unit suite (the `ALREADY_IN_CONTEXT` pins, the truncation pins); `test_sources/players_handbook.pdf` (the DND player's handbook from `pdf_tests.tar` — on disk, untracked); `settings.read_max_chars` (`BOR_READ_MAX_CHARS`).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The agent stops dead-ending on huge documents: `read` accepts an optional 1-based line `offset` + line-count `limit`, the truncation notice and tool descriptions teach the grep → read(offset/limit) workflow, and the dedupe rules allow the ONE case that matters — re-reading a range of a document whose first read was truncated — while still refusing pointless re-reads of text already in context. The owner's repro (the handbook, "find traps", `BOR_READ_MAX_CHARS=24000`) passes as an integration test.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `130_chat_answer_clusters` (todo) — pipeline order only; code dependencies are the completed agent surface (phases 70/72/95/118).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Schema + teaching (task 01):** `read` gains two OPTIONAL integer params — `offset` ("The first line to read, 1-based. Omit it to read from the beginning of the document.") and `limit` ("The maximum number of lines to read. Omit it to read as many lines as fit under the character cap."). `required` stays `["path"]`. The `read` description keeps its existing teaching and GAINS the workflow: for a very large document, use `grep` to find where your text is (it reports line numbers), then `read` that part with `offset` + `limit`; re-reading a document already read in full adds nothing. `READ_TRUNCATION_NOTICE` (L506) is REWRITTEN to end the dead-end: "…The rest is NOT shown. Use grep (pattern) to find what you need — it reports line numbers — then read that part with `offset` (1-based first line) and `limit` (number of lines)." The `grep` description gets the light touch: "read the winner with `read` — for a large document, use the reported line number as `offset`."
|
||||||
|
- **Execution (task 02):** in `_execute_tool`'s read branch:
|
||||||
|
- Validation: `offset`/`limit`, when present, must be ints ≥ 1 (NOT bools — the house `isinstance(x, int) and not isinstance(x, bool)` guard); a bad value → a teaching refusal echoing the bad value ("`offset` and `limit` are whole line numbers ≥ 1 — you passed `…`") — counts in nothing, consumes a round (the phase-72 refusal style).
|
||||||
|
- The dedupe matrix (`known` = the `read_docs` (source, path) set; `truncated` = the set of (source, path) from `holder.read_truncations`):
|
||||||
|
| call | doc in `known` | previously truncated | result |
|
||||||
|
|---|---|---|---|
|
||||||
|
| plain `read(path)` | no | — | full read (truncate at the cap as today) |
|
||||||
|
| plain `read(path)` | yes | yes | NEW teaching line (no re-emit, no count): "You already have the first {shown} characters of {source}/{path} in your context. To read the rest, find where your text is with grep (it reports line numbers), then call read with `offset` (1-based first line) and `limit` (lines)." — `{shown}` from the matching `read_truncations` tuple |
|
||||||
|
| plain `read(path)` | yes | no | `ALREADY_IN_CONTEXT` (byte-identical to today) |
|
||||||
|
| `read(path, offset, limit)` | yes | yes | ALLOWED (the stuck-scenario fix — the range the model names is exactly the part it does NOT have) |
|
||||||
|
| `read(path, offset, limit)` | yes | no | `ALREADY_IN_CONTEXT` (the full text is already in context — the range is a subset) |
|
||||||
|
| `read(path, offset, limit)` | no | — | ALLOWED (a range read of an unread doc) |
|
||||||
|
- `offset > total_lines` (the doc's `len(content.splitlines())`) → teaching refusal: "{source}/{path} is {total_lines} lines long — `offset` {offset} is past the end. Use a smaller offset (grep reports the exact line numbers)." Counts in nothing.
|
||||||
|
- Result shape: line 1 `Document {source}/{path}:` + line 2 `date: YYYY-MM-DD` stay BYTE-IDENTICAL for plain reads (the E2E mock's `_READ_RESULT_PREFIX` contract); a RANGE read inserts a third line `lines: {offset}-{end} of {total_lines}` (the actual end = min(offset + limit − 1, total_lines); the model sees the true extent), then the image-doc marker (as today), then the slice (`"\n".join(lines[offset-1 : offset-1+limit])`).
|
||||||
|
- The cap still applies to the SLICE: `len(slice) > settings.read_max_chars` → cut + `TRUNCATION_MARKER` + the (rewritten) notice; the `read_truncations` tuple for a range read is `(arg, cap, len(slice))` — the slice's requested size (documented: for range reads the tuple's `chars_total` is the slice length, not the document's).
|
||||||
|
- A range read appends the doc to `read_docs` ONCE (the `known` set prevents a re-append) — so a later plain read of a range-read doc is `ALREADY_IN_CONTEXT` (the model has committed to this doc; the range result's `lines:` line told it what it holds).
|
||||||
|
- **Handbook repro (task 03):** an integration test that imports `test_sources/players_handbook.pdf` as a local source (the mock LLM's deterministic embed/summary fakes — the in-process `tests/fakes.py` pattern; the handbook is ~1.5 MB of text ≈ 1200 chunks — in-process embedding is fast, keep the test under ~60 s) and drives the agent turn "What are the components of the find traps spell?" with `BOR_READ_MAX_CHARS=24000`: a scripted fake (the `test_agent.py` pattern) — round 1 → a `grep` tool call (pattern "find traps"), round 2 (the grep result carries the real line number) → a `read(path, offset=<that line>, limit=40)` call, round 3 → the answer echoing the read result's content (the phase-94 "read document reached the context" echo convention). Assert the echo contains the handbook's actual find-traps text (grep it from the extracted PDF text in the test — do not hardcode the handbook wording).
|
||||||
|
- **Mock flow + E2E (task 04):** `tests/e2e/mock_llm.py` gains ONE scripted flow (house style — a user-message marker, deterministic reply, module-header docstring entry): the marker `read the lines` → request 1: a `grep` tool call (a canned pattern); request 2 (a `tool`-role grep result with a `source/path:line:` line present): a `read` tool call with `offset` = the parsed line number and `limit` = 30; request 3 (the read result present): the answer "Found it at line N." + the first 80 chars of the read result (the existing read-echo shape). `tests/e2e/test_read_line_ranges.py` (dedicated, in isolation, mock-only): a KB fixture with ONE large doc (> 24000 chars, the marker line `TRAP_COMPONENTS_LINE` near line ~1500), `BOR_READ_MAX_CHARS=24000`; ask a question containing the marker → assert the SSE `tool` frames (grep, then read with `offset`/`limit` args) and the final answer echoing the marker line; a second test: a plain read of the large doc truncates with the REWRITTEN notice (the notice names `offset`/`limit` — assert the `tool_result`/result surface carries it).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_tool_surface.md` — the schema, the descriptions, the rewritten truncation notice.
|
||||||
|
2. `02_range_read_execution.md` — the read branch: validation, the dedupe matrix, the slicing, the result shape.
|
||||||
|
3. `03_handbook_repro.md` — the integration repro (the handbook + the owner's exact question) + the unit matrix.
|
||||||
|
4. `04_mock_flow_e2e.md` — the mock-LLM `read the lines` flow + the dedicated E2E.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the full dedupe matrix (6 rows), the validation refusals, the slice math (boundaries, offset past EOF, 1-line docs), the result shapes (plain reads byte-identical — the existing pins must pass unchanged), the cap on slices.
|
||||||
|
- Integration: the handbook repro (the owner's scenario, the owner's `BOR_READ_MAX_CHARS=24000`).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `read(path, offset, limit)` returns exactly the named lines with the `lines: a-b of N` header; plain reads are byte-identical to pre-phase
|
||||||
|
- [ ] a truncated first read followed by a range read SUCCEEDS (the stuck scenario is gone); every other re-read is refused with the teaching
|
||||||
|
- [ ] the handbook integration test answers the find-traps question from the real PDF text (no hardcoded wording)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (the grep/ls surfaces, the plain-read contract, the `ALREADY_IN_CONTEXT` full-read refusal)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Task 01 — The tool surface: `offset`/`limit` on `read`, the descriptions, the rewritten notice
|
||||||
|
|
||||||
|
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. It can search for the text it wants and it finds the text, including line number, but then it gets stuck saying 'However, read takes a path, not a line number.' ... Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The model's contract for `read` names the line-range capability (LOCKED A2: `offset`/`limit`, 1-based, pi-harness shape) and the truncation dead-end is rewritten into the working workflow: grep for the line numbers, then read that range.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/agent.py` — `AGENT_TOOLS`, the `read` entry (~L304): add to `properties`:
|
||||||
|
```python
|
||||||
|
"offset": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": (
|
||||||
|
"The first line to read, 1-based. Omit it to read from the "
|
||||||
|
"beginning of the document. Use it to read a specific part "
|
||||||
|
"of a large document — grep reports the line numbers of "
|
||||||
|
"what you found."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"type": "integer",
|
||||||
|
"description": (
|
||||||
|
"The maximum number of lines to read, starting at offset. "
|
||||||
|
"Omit it to read as many lines as fit under the character "
|
||||||
|
"cap. Keep it small — you are reading a part, not the "
|
||||||
|
"document."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
```
|
||||||
|
`required` stays `["path"]`.
|
||||||
|
2. `app/rag/agent.py` — the `read` `description`: keep the existing sentences (the `<documents>`-summaries teaching, the no-re-read rule, the truncation/`grep` paragraph — but REPLACE the truncation paragraph with the workflow): "Very large documents are truncated: you receive the first part plus a TRUNCATED notice naming how many more characters exist. To read the rest: use `grep` (pattern) to find where your text is — it reports line numbers — then call `read` again on the same document with `offset` (1-based first line) and `limit` (number of lines) to read exactly that part. Do not re-read a document you have already read in full — its full text is already in your prompt."
|
||||||
|
3. `app/rag/agent.py` — `READ_TRUNCATION_NOTICE` (~L506): rewrite the tail (keep the `TRUNCATED — this document is {total} characters; only the first {shown} are in your context. The rest is NOT shown.` opening): "Use grep (pattern) to find what you need — it reports line numbers — then read that part with `offset` (1-based first line) and `limit` (number of lines)."
|
||||||
|
4. `app/rag/agent.py` — the `grep` `description`: the "read the winner with `read`" sentence becomes "read the winner with `read` — for a large document, use the reported line number as `offset`".
|
||||||
|
5. `tests/unit/test_agent.py` — update/extend the `AGENT_TOOLS` schema pins: the `read` schema has `offset`/`limit` (integer, optional — `required` is still `["path"]`), the descriptions contain the `offset`/`limit` teaching (the pinned substrings), and `READ_TRUNCATION_NOTICE` names both parameters.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the schema/notice pins above green; the `ls`/`grep` schemas' OTHER pins unchanged (byte-identical where not rewritten).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a model reading `AGENT_TOOLS` knows: grep → line number → `read(offset, limit)` (schema + descriptions + notice all agree)
|
||||||
|
- [ ] the old dead-end sentence ("use grep to locate the rest" with no way to act on the line number) is gone from the notice
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Task 02 — Range-read execution: validation, the dedupe matrix, the slice, the result shape
|
||||||
|
|
||||||
|
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. ... then it gets stuck saying 'However, read takes a path, not a line number.' and can't figure out how to read that part of the document."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`_execute_tool`'s read branch executes `offset`/`limit`: it validates the arguments with teaching refusals, applies the six-row dedupe matrix (the truncated-then-range case is the one that must succeed), slices the document's lines, and shapes the result so plain reads stay byte-identical while range reads carry their `lines: a-b of N` extent.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/agent.py` — `_execute_tool`, the `read` branch (~L1348): after `arg` is resolved and before the dedupe check, parse the range args:
|
||||||
|
```python
|
||||||
|
offset = call.arguments.get("offset")
|
||||||
|
limit = call.arguments.get("limit")
|
||||||
|
```
|
||||||
|
with a helper `_read_range_args(offset, limit)` returning `(ok, error_line, offset, limit)`:
|
||||||
|
- absent/None → ok, `(1, None)` semantics = plain read (no range);
|
||||||
|
- present but not `isinstance(x, int) and not isinstance(x, bool)`, or `< 1` → the teaching refusal: "`offset` and `limit` are whole line numbers — pass integers ≥ 1 (you passed offset={offset!r}, limit={limit!r})." (echo the bad values; counts in nothing, consumes a round — the phase-72 refusal style, a new pinned constant `BAD_RANGE_ARGS`);
|
||||||
|
- ok → the (offset, limit) pair (either may be None — `offset` without `limit` reads to the end, `limit` without `offset` is treated as `offset=1` — document both in the constant's docstring).
|
||||||
|
2. `app/rag/agent.py` — the dedupe matrix (the phase-131 design table; `truncated_pairs = {(source, path) of holder.read_truncations}` — build it from the holder's tuples, matching on the RESOLVED pair, not the raw arg string):
|
||||||
|
- plain read + in `known` + truncated → the new pinned teaching line `REREAD_TRUNCATED` ("You already have the first {shown} characters of {source}/{path} in your context. To read the rest, find where your text is with grep (it reports line numbers), then call read with `offset` (1-based first line) and `limit` (lines).") — `{shown}` from the matching tuple; no re-emit, `tool_calls` NOT incremented (a refusal);
|
||||||
|
- plain read + in `known` + not truncated → `ALREADY_IN_CONTEXT` (the existing byte-identical path — do not touch that constant);
|
||||||
|
- range read + in `known` + truncated → PROCEED (the fix);
|
||||||
|
- range read + in `known` + not truncated → `ALREADY_IN_CONTEXT`;
|
||||||
|
- range read + not in `known` → PROCEED.
|
||||||
|
(The current code's dedupe check runs on the RAW arg before resolution for speed — keep that fast path for the plain-read `ALREADY_IN_CONTEXT` case; the truncated-set check needs the resolved pair, so it runs after `_resolve_path`, exactly where the `doc` is known. Restructure minimally: the raw-arg fast path handles "plain read + known"; everything else resolves first, then consults the matrix.)
|
||||||
|
3. `app/rag/agent.py` — the slice + result (after `doc` is resolved and the matrix passed):
|
||||||
|
- `lines = doc.content.splitlines()`; `total_lines = len(lines)`;
|
||||||
|
- `offset > total_lines` → the teaching refusal `OFFSET_PAST_END` ("{source}/{path} is {total_lines} lines long — `offset` {offset} is past the end. Use a smaller offset (grep reports the exact line numbers).") — no count;
|
||||||
|
- `end = min(offset + (limit or 1) - 1, total_lines)`; `slice_lines = lines[offset - 1 : end]`; `slice_text = "\n".join(slice_lines)`;
|
||||||
|
- `holder.read_docs.append(doc)` (the `known` check already guarantees no duplicate); `holder.tool_calls += 1` (a range read is a successful call — the plain-read convention);
|
||||||
|
- result: plain read → EXACTLY today's bytes (header, date, marker, content/truncated-content — the existing code path untouched); range read →
|
||||||
|
```
|
||||||
|
Document {source}/{path}:
|
||||||
|
date: YYYY-MM-DD
|
||||||
|
lines: {offset}-{end} of {total_lines}
|
||||||
|
{marker}{slice_text}
|
||||||
|
```
|
||||||
|
(the `lines:` line replaces the position the marker/`TRUNCATION_MARKER` occupy in the plain read — for a range read the marker line comes after `lines:` exactly as after the date line in the plain read);
|
||||||
|
- the cap on the slice: `len(slice_text) > settings.read_max_chars` → `slice_text[:cap]` + `\n{TRUNCATION_MARKER}\n{READ_TRUNCATION_NOTICE.format(shown=cap, total=len(slice_text))}` and `holder.read_truncations.append((arg, cap, len(slice_text)))` — for range reads the tuple's `chars_total` is the SLICE's requested size (document in the `AgentHolder.read_truncations` field comment: "for range reads the slice length, not the document's").
|
||||||
|
4. `tests/unit/test_agent.py` — the full matrix (six rows, each pinned): the six dedupe outcomes; `BAD_RANGE_ARGS` (a float, a string, a bool, a 0, a negative); `OFFSET_PAST_END` (offset = total+1 on a 10-line doc); the slice math (offset=1/limit=None → the whole doc; offset=total → the last line; limit overshoot → `end` clamps to `total_lines`; a 1-line doc; offset past EOF); the result shapes (the plain-read pins pass UNCHANGED — byte-identical; a range read's `lines: a-b of N` line + slice; the cap on a huge slice + the tuple's slice-length `chars_total`).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the matrix + the pins above — this task's suite.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the six-row matrix is pinned one test per row (the truncated-then-range row PASSES — the stuck scenario's unit proof)
|
||||||
|
- [ ] plain reads are byte-identical to pre-phase (the existing pins green, unmodified)
|
||||||
|
- [ ] a range read's result names its true extent (`lines: a-b of N`) and respects the cap
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Task 03 — The handbook repro: "find traps" on the real D&D player's handbook
|
||||||
|
|
||||||
|
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "I have a huge test pdf (the DND player's handbook) in test_sources called 'pdf_tests.tar' that you can use for testing. It's a massive pdf. The question the agent got stuck on was 'What are the components of the find traps spell?' which is toward the end of the players handbook so it will need to search and read specific lines. I've been setting BOR_READ_MAX_CHARS to 24000 to keep things relatively quick so the agent realizes quickly its answer isn't in the first few pages."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The owner's exact incident is an integration test: the real `players_handbook.pdf` is indexed, the agent is asked the find-traps question with the owner's `BOR_READ_MAX_CHARS=24000`, and the scripted agent loop performs the grep → read(offset/limit) dance against the REAL document and lands an answer grounded in the handbook's actual find-traps text.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/integration/test_read_line_ranges_handbook.py` (new) — the house integration pattern (inspect `tests/integration/` for the agent-loop test that runs a scripted fake LLM against a real-ish pipeline — `tests/unit/test_agent.py`'s fake-LLM/scripted-rounds pattern is the model; lift it into an integration test that ALSO runs the real PDF extraction + real chunking/embedding fakes from `tests/fakes.py`):
|
||||||
|
- Fixture: a temp source dir containing `test_sources/players_handbook.pdf` (copy — never mutate the untracked fixture), registered/imported with the REAL importer (`import_sources`, the mock embed/summary fakes — the in-process fakes make the ~1200-chunk embed fast; keep the whole test under ~60 s; if the import is slower, the test may pre-import once at module scope and share it across its tests).
|
||||||
|
- The scripted fake (deterministic, the `test_agent.py` round pattern):
|
||||||
|
- round 1 (no tool results yet) → a `grep` tool call, `pattern="find traps"` (lowercase — grep is case-insensitive);
|
||||||
|
- round 2 (the grep result carries `…:LINE: …find traps…` — parse the REAL line number from the grep result the loop produced, do not hardcode it) → a `read` tool call: `path` = the handbook's `source/path`, `offset` = the parsed line, `limit` = 40;
|
||||||
|
- round 3 (the read result present) → the answer: the read result's content, verbatim (the phase-94 "the read document reached the context" echo convention — the loop's reply IS the slice).
|
||||||
|
- Settings: `BOR_READ_MAX_CHARS=24000` (the owner's env — the handbook is far longer, so round 1's plain-read alternative would truncate; the script goes straight to grep, but the setting must be in force for the notice/teaching path to be realistic).
|
||||||
|
2. Assertions (the observable contract):
|
||||||
|
- the final answer contains the handbook's REAL find-traps text — derive the expected substring at test time: extract the PDF's text (the phase-126 `extract_pdf_text`), grep it for the find-traps passage in the test itself (the same way the model does), and assert the ANSWER contains that passage's first 60 chars (NO hardcoded handbook wording — the test stays true if the fixture is re-extracted);
|
||||||
|
- the agent's `read` call carried `offset`/`limit` (assert on the fake's captured round-2 tool call: `offset == the grep-reported line`, `limit == 40`);
|
||||||
|
- the loop made exactly 3 rounds (grep → range read → answer) with `tool_calls == 2` (the owner's stuck loop made 2 and dead-ended — the fixed loop closes in 3).
|
||||||
|
3. `tests/integration/test_read_line_ranges_handbook.py` — a SECOND test, the plain-read-first variant: the fake round 1 does a PLAIN `read(path)` (the handbook truncates at 24000 with the rewritten notice), round 2 does `read(path, offset=<grep line>, limit=40)` AFTER a grep — asserting the truncated-then-range matrix row works on the REAL document (the `REREAD_TRUNCATED` teaching is never needed because the model went straight to the range — the matrix row itself is unit-pinned in task 02; here the end-to-end path is the point).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Integration: this file IS the task's suite (plus task 02's unit matrix).
|
||||||
|
- Coverage: **>90%** on new/modified code (the test file is covered by the suite run; `app/` changes are task 02's).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/integration/test_read_line_ranges_handbook.py -v` green in ~60 s (the owner's scenario passes on the real PDF)
|
||||||
|
- [ ] the expected text is derived from the fixture at test time (grep the extracted text — no hardcoded handbook wording)
|
||||||
|
- [ ] the read call's `offset` is the grep-reported line (parsed, not literal)
|
||||||
|
- [ ] no behavior change in completed phases
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Task 04 — The mock flow `read the lines` + the dedicated E2E
|
||||||
|
|
||||||
|
**Phase:** `131_read_line_ranges` · **Source:** `TODO.md:7` — "The agent is struggling with huge documents. ... Does the read tool support that? If not, it should. If it does, improve the description so the agent doesn't get stuck."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The E2E mock deterministically performs the grep → read(offset/limit) dance, and a dedicated, in-isolation Playwright suite pins the full SSE surface: the `tool` frames carry the range args, the answer is grounded in the large doc's tail, and the truncation notice now teaches the workflow instead of dead-ending.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/mock_llm.py` — one new scripted flow in the house style (a user-message marker + a module-header docstring entry, exactly like the existing "use your tools" / multi-read / grep flows — read the module header first and match its format):
|
||||||
|
- Marker: the user message containing `read the lines` (a dedicated trigger — no overlap with the existing grep-flow trigger; if the existing grep flow's trigger could also match, make the new marker more specific, e.g. `read the lines of` — the header documents the exact string).
|
||||||
|
- Flow (classified by the count of `tool`-role results in the messages, the house pattern):
|
||||||
|
- 0 results → a `grep` tool call, `pattern="LINE_MARKER"` (a canned constant the fixture doc contains);
|
||||||
|
- a `tool`-role grep result present (a line matching `^[\w/]+:(\d+):` — parse the FIRST match's line number) → a `read` tool call: `path` = the grep result's `source/path`, `offset` = the parsed line number, `limit` = 30 (structured `tool_calls`, no reasoning — the terminal-shape convention);
|
||||||
|
- the read result present (a `tool`-role result whose content starts with `Document `) → the forced answer, byte-stable: `Found it at line N.` (N = the offset the model passed — parse it from the `read` call's arguments in the messages) + the first 80 chars of the read result's content (the phase-94 read-echo convention — proves the RANGE reached the model's context).
|
||||||
|
2. `tests/e2e/test_read_line_ranges.py` (new) — dedicated, in isolation, mock-only, house pattern (module app fixture, temp local source, autouse cleanup):
|
||||||
|
- KB fixture: ONE large markdown doc `linedoc/big.md` — ~100 KB, generated deterministically in the test (numbered filler lines `Line <i>: …`, so line numbers are exact), with the marker line `LINE_MARKER the trap components are documented here` at a known line ~1500 (far beyond the 24000-char cap — the doc's first 24000 chars hold NO marker);
|
||||||
|
- app env: `BOR_READ_MAX_CHARS=24000` (the owner's setting — the plain read MUST truncate).
|
||||||
|
- Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_range_read_flow_over_sse` — send a question containing `read the lines` → the SSE `tool` frames, in order: the `grep` call (args `pattern="LINE_MARKER"`), then the `read` call (args: `path` = the doc's `source/path`, `offset` an int == the marker's true line, `limit` == 30 — assert on the frame's args, not a substring); the `done` frame's answer contains `Found it at line <N>` (N == the marker's line) and the marker text's first 80 chars (the read-echo — the range reached the context); NO truncation-notice dead-end (the answer is the grounded echo, not a "I can't read that part" shape — assert the marker text is present).
|
||||||
|
- `test_plain_read_truncation_notice_teaches_the_workflow` — a SECOND trigger (reuse the mock's existing plain-read flow on this large doc — the `read` of `linedoc/big.md` truncates at 24000): the surfaced truncation (the `tool_result` frame / the result the model sees — assert on the SSE `tool_result` surface per A15) contains the REWRITTEN notice text naming `offset` and `limit` (the pinned substrings `"offset"` + `"limit"` in the notice — the old dead-end wording is gone).
|
||||||
|
3. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov`), the mock-only gate, the fixture's determinism (the generated line numbers), the `BOR_READ_MAX_CHARS=24000` rationale (the owner's env), the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% `app/` bar is carried by tasks 01–02; the handbook integration repro by task 03; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_read_line_ranges.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the `read` tool frame carries REAL `offset`/`limit` ints (parsed from the grep result — the mock does the owner's exact dance)
|
||||||
|
- [ ] the truncation notice surfaces the workflow teaching (the dead-end is gone)
|
||||||
|
- [ ] no behavior change in completed phases (the existing mock flows' triggers still fire unchanged)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Phase 132 — Chat image upload: visible "uploading" feedback
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L8 — "Uploading an image in the chat provides no feedback to the user. The user clicks the paperclick, selects and image, presses 'send' and then nothing happens. No loading bar, no 'uploading image', no indication. This results in the user spamming 'send' over and over because they think it's frozen. We need to visually show the user's image is uploading."
|
||||||
|
(A5, owner-confirmed 2026-09-27: the affordance = a spinner + "Uploading image…" in the preview strip AND the Send button disabled with the label "Uploading…" — the double-spam is blocked visually, not just by the internal guard.)
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/assets/app.js` — `handleSend` (~L2700: the `attachedImage` branch — the `attachUpload` double-fire guard, `await uploadAttachedImage(attachedImage.file)` with NO visual state between the await's start and its resolution, then `image = { path, src, alt }` + `runTurn`), `uploadAttachedImage` (~L2641: the `POST /api/chat-images` multipart — every failure path is an out-of-turn banner + null), `showAttachPreview` / `clearAttachedImage` (~L2680: the strip's reveal/clear — static markup, only `textContent`/`src` move), `setUiState` (the turn-state owner — NOT used for the upload: the upload is a PRE-turn operation, `uiState` stays `idle`, the turn loader must not spin during the upload); `frontend/index.html` L280–322 — the static attach markup (`#attach-preview` with `img` + `.attach-preview-name` + `#attach-remove`; `#send-btn` with `#send-label`); `frontend/assets/styles.css` — the `.attach-preview*` / `.send-btn` rules (the existing `:disabled` styles); `tests/unit/test_frontend_sync_upload.py` or a sibling — the pinned frontend JS unit pattern.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Between the user pressing Send and the upload resolving, the UI proves the image is moving: the preview strip shows a spinner + "Uploading image…" (the remove button disabled), and the Send button is disabled with the label "Uploading…". When the upload resolves — success proceeds to the turn exactly as today; failure clears the state and keeps the existing banner + the typed text + the attachment for the retry. No frozen-looking gap, no visible double-send.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `131_read_line_ranges` (todo) — pipeline order only; code dependencies are the completed phase-123 attach/upload contract.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **State scope (task 01):** the uploading state is the `attachedImage` branch of `handleSend` — from just after the `attachUpload = true` guard until the `attachUpload = false` line (success AND failure paths — the helper never throws). `setUiState` is NOT touched (the upload is pre-turn; `uiState` stays `idle`; the turn's own thinking/streaming feedback starts only when `runTurn` does). The `attachUpload` guard stays exactly as is (the visual state reinforces it — the disabled Send is the user-facing half).
|
||||||
|
- **Preview strip (task 01):** the static markup gains ONE status element inside `#attach-preview`: `<span class="attach-preview-status" hidden><svg spinner…></svg><span class="attach-preview-status-text">Uploading image…</span></span>`. The JS sets `attachPreview.classList.add("is-uploading")` + un-hides the status + `attachRemove.disabled = true` on entry; on exit it removes the class + hides the status + `attachRemove.disabled = false`. The thumbnail + filename stay visible (the user watches THEIR image uploading).
|
||||||
|
- **Send button (task 01):** `sendBtn.disabled = true` + `sendLabel.textContent = "Uploading…"` on entry; on exit (both paths) `sendBtn.disabled = false` + `sendLabel.textContent = "Send"` — restored BEFORE the success path calls `runTurn` (the turn's `setUiState("thinking")` then takes over the button as usual) and BEFORE the failure path returns (the banner + editable input + the still-attached image).
|
||||||
|
- **Reduced motion (task 02):** the spinner animation is still under `prefers-reduced-motion` (the house `@media (prefers-reduced-motion: reduce)` block pattern).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_upload_state.md` — the static markup + the uploading state in `handleSend` (enter/exit on both paths).
|
||||||
|
2. `02_css_upload_state.md` — the strip's uploading styles + the disabled Send + reduced motion.
|
||||||
|
3. `03_e2e_upload_feedback.md` — dedicated Playwright E2E, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pinned frontend JS suite — the state transitions (the strip's class/status/remove-disabled, the Send's disabled/label) on entry, on success exit, on failure exit (the banner path).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, with a route-delayed upload (Playwright `page.route` delaying `POST /api/chat-images`) so the in-flight window is observable.
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend: unit pins + E2E; `app/` untouched this phase).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] while the upload is in flight: the strip shows the spinner + "Uploading image…", the remove button is disabled, the Send button is disabled with "Uploading…" (E2E-asserted mid-flight)
|
||||||
|
- [ ] a second Send press during the flight does nothing (no second upload request — E2E request count)
|
||||||
|
- [ ] success: the indicator clears and the turn proceeds exactly as pre-phase (the user bubble carries the image); failure: the indicator clears, the banner shows, the text + attachment remain
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (the phase-123 upload contract, the A5 path-never-bytes rule, the out-of-turn banner)
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Task 01 — The uploading state: markup + `handleSend` enter/exit on both paths
|
||||||
|
|
||||||
|
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. ... We need to visually show the user's image is uploading."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The `attachedImage` branch of `handleSend` enters a visible uploading state the moment the upload starts and clears it the moment the upload resolves — success or failure — so the user always sees whether the app is moving.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/index.html` (L280–284, the `#attach-preview` block) — add the status element INSIDE the strip (after the name span, before the remove button), static + hidden by default (the house "ships hidden" rule):
|
||||||
|
```html
|
||||||
|
<span class="attach-preview-status" hidden>
|
||||||
|
<svg class="attach-preview-status-icon" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.2-8.56"/></svg>
|
||||||
|
<span class="attach-preview-status-text">Uploading image…</span>
|
||||||
|
</span>
|
||||||
|
```
|
||||||
|
(The spinner arc is the house loading glyph — check `#turn-loader`'s icon for the exact shape and reuse it; the spinner's spin animation is the CSS task. `aria-hidden` on the svg — the text carries the meaning; the strip's `role`/label are untouched.)
|
||||||
|
2. `frontend/assets/app.js` — get the new elements at module scope with the existing attach-family consts (L313–316, the null-guard pattern): `attachStatus = document.querySelector(".attach-preview-status")`, `attachStatusText` (not needed — the text is static), alongside `attachPreview`/`attachRemove`.
|
||||||
|
3. `frontend/assets/app.js` — two tiny helpers next to `showAttachPreview`/`clearAttachedImage`:
|
||||||
|
```js
|
||||||
|
function enterUploadState() {
|
||||||
|
if (attachPreview) attachPreview.classList.add("is-uploading");
|
||||||
|
if (attachStatus) attachStatus.hidden = false;
|
||||||
|
if (attachRemove) attachRemove.disabled = true;
|
||||||
|
sendBtn.disabled = true;
|
||||||
|
sendLabel.textContent = "Uploading…";
|
||||||
|
}
|
||||||
|
function exitUploadState() {
|
||||||
|
if (attachPreview) attachPreview.classList.remove("is-uploading");
|
||||||
|
if (attachStatus) attachStatus.hidden = true;
|
||||||
|
if (attachRemove) attachRemove.disabled = false;
|
||||||
|
sendBtn.disabled = false;
|
||||||
|
sendLabel.textContent = "Send";
|
||||||
|
}
|
||||||
|
```
|
||||||
|
(The label literals "Send"/"Uploading…" — check the idle label's exact current text in the markup/`setUiState` and match it byte-for-byte; if `setUiState` owns the idle label restore, use its restore helper instead of a literal — inspect first.)
|
||||||
|
4. `frontend/assets/app.js` — `handleSend`, the `attachedImage` branch (~L2700):
|
||||||
|
- after the `attachUpload = true;` line, BEFORE `await uploadAttachedImage(...)`: `enterUploadState();`
|
||||||
|
- on the `attachUpload = false;` line (the helper never throws — this is reached on BOTH success and failure): `exitUploadState();` — the success path then continues to `image = { path, src, alt }` + the rest of the send (the turn's `setUiState` takes the button over); the failure path (`path === null`) returns with the banner shown, the input text intact, and the attachment still attached (the strip is back in its normal preview state — the user can retry or remove).
|
||||||
|
- Do NOT touch the `attachUpload` guard, the `uploadAttachedImage` helper, or `clearAttachedImage` (the New-chat reset already hides the strip — the uploading class is transient and never persists: if a New chat happened mid-upload, the strip is hidden; the class on a hidden element is harmless, and `exitUploadState` still clears it when the upload resolves).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pinned frontend JS suite (extend `tests/unit/test_frontend_sync_upload.py` or the chat-frontend pin file — inspect what exists): the state transitions — entry sets the class/status/unhides/disables remove/disables Send with "Uploading…"; exit (success) clears everything and restores "Send"; exit (failure) clears everything the same way (the banner is the failure's signal, not the strip's); a second `handleSend` during the flight is a no-op (the existing `attachUpload` guard pin).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the uploading state is entered exactly once per upload (after the guard, before the await) and exited on BOTH resolution paths
|
||||||
|
- [ ] `uiState`/`setUiState`/the turn loader are untouched (the upload is pre-turn — the loader spins only when the turn starts)
|
||||||
|
- [ ] the idle label after exit matches the pre-phase idle label byte-for-byte
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Task 02 — CSS: the strip's uploading look, the disabled Send, reduced motion
|
||||||
|
|
||||||
|
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. ... We need to visually show the user's image is uploading."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The uploading state reads as "in motion": the strip's thumbnail dims with a spinning arc + the "Uploading image…" text beside it, and the Send button shows the disabled affordance the app already has for a disabled Send — no new color, no new weight, the existing `--ink-soft`/opacity language.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/styles.css` — with the other `.attach-preview*` rules (grep the existing block first — read the strip's current layout: the thumbnail, the name, the remove button):
|
||||||
|
```css
|
||||||
|
/* Phase 132: the uploading state — the strip proves the image is
|
||||||
|
moving (the TODO: no feedback → the user spams Send). The
|
||||||
|
thumbnail dims, the spinner arc spins, the status text stands in
|
||||||
|
the name's place. */
|
||||||
|
.attach-preview.is-uploading .attach-preview-img {
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
.attach-preview.is-uploading .attach-preview-name {
|
||||||
|
visibility: hidden; /* keep the layout; the status takes its spot */
|
||||||
|
}
|
||||||
|
.attach-preview-status {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
color: var(--ink-soft);
|
||||||
|
font-size: 0.85rem; /* the strip's small text (match the name's size) */
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.attach-preview-status-icon {
|
||||||
|
width: 14px;
|
||||||
|
height: 14px;
|
||||||
|
flex: 0 0 auto;
|
||||||
|
animation: spin 1s linear infinite; /* the .sync-icon spinner (the house spin keyframes) */
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.attach-preview-status-icon { animation: none; }
|
||||||
|
}
|
||||||
|
.attach-preview.is-uploading .attach-preview-remove {
|
||||||
|
opacity: 0.5; /* the disabled attribute's visual half (the house :disabled language) */
|
||||||
|
}
|
||||||
|
```
|
||||||
|
(Match the EXISTING values — the strip's font sizes, the `spin` keyframes' name (verify they exist — the `.sync-icon.is-spinning` rule uses `spin`), the disabled-button opacity. If the strip's name span has `overflow: hidden; text-overflow: ellipsis` (a long filename), the status span inherits the row's clamp — verify the "Uploading image…" text never clips at 320 px; if it does, let the status text wrap or ellipsize per the strip's existing pattern.)
|
||||||
|
2. `frontend/assets/styles.css` — verify the `#send-btn:disabled` rule exists and reads as disabled (the Send is disabled via the `disabled` attribute — the existing rule applies; if the disabled Send currently looks identical to the enabled one, add the house `opacity`/`cursor: wait` there — inspect the current rule first, do not invent a new visual).
|
||||||
|
3. Theme audit: every value used is a theme variable or a neutral (no raw hex/rgb — the B4 byte-identical built-in theme contract; the status text's `--ink-soft` on the strip's background meets 4.5:1 — the strip's bg is `--bg-soft` or similar, verify the pair's contrast the way the theme phases did).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Visual gate: the E2E (task 03) — the status is visible mid-flight, the thumbnail is dimmed (an `opacity` computed-style assertion is optional — the visibility of the status text is the pin).
|
||||||
|
- Coverage: **>90%** on new/modified code (CSS has no direct coverage — the E2E + unit pins carry it).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the uploading strip shows the spinning arc + "Uploading image…" with the dimmed thumbnail (E2E-asserted mid-flight)
|
||||||
|
- [ ] `prefers-reduced-motion` stills the arc (the house block)
|
||||||
|
- [ ] the disabled Send reads as disabled (the existing rule, verified)
|
||||||
|
- [ ] `uv run pytest` green; no behavior change in completed phases
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Task 03 — E2E: the upload window shows "uploading", blocks the double-send, then the turn proceeds
|
||||||
|
|
||||||
|
**Phase:** `132_image_upload_feedback` · **Source:** `TODO.md:8` — "Uploading an image in the chat provides no feedback to the user. The user clicks the paperclick, selects and image, presses 'send' and then nothing happens. ... This results in the user spamming 'send' over and over because they think it's frozen. We need to visually show the user's image is uploading."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) proving the owner-visible fix: while `POST /api/chat-images` is in flight (route-delayed so the window is observable), the strip shows the uploading state, the Send button is disabled with "Uploading…", a second press produces NO second upload request — and once the upload resolves, the state clears and the turn proceeds exactly as pre-phase.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_image_upload_feedback.py` (new) — house pattern (module app fixture over the shared E2E Postgres, autouse cleanup, mock-only). The app boots with `BOR_IMAGES=1` (the `/api/config` `images: true` gate reveals `#attach-btn` — follow `tests/e2e/test_chat_image_questions.py`'s app env). KB fixture: a minimal local source with ONE text doc (the mock's grounded answer for a plain question — the turn after the upload needs to complete normally).
|
||||||
|
2. The upload window (Playwright's `page.route`): intercept `POST /api/chat-images` — `route.waitForRequest`-style: the handler DELAYS (e.g. `await asyncio.sleep(2.0)` in the route handler, or `page.route` + a fixture that holds the response) then `route.continue_()` — the server's real handler runs, the response is just late. Count the intercepted upload requests (a module counter) for the double-send assertion. A small PNG fixture (the house test image — reuse the existing one the image E2E suites use; do not commit a new binary if one exists).
|
||||||
|
3. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_upload_window_shows_uploading_and_blocks_resend` — admin or anonymous (chat is public — anonymous is the simpler context) page on the chat view; click `#attach-btn` → `#attach-file` set_input_files (the small PNG); the strip is revealed (the phase-123 preview — `#attach-preview` not hidden, the thumbnail's `src` set); type a question; click Send. MID-FLIGHT (poll for the state within the delayed window): `#attach-preview` has the `is-uploading` class; `.attach-preview-status` is visible (not hidden) with the text "Uploading image…"; `#attach-remove` is disabled; `#send-btn` is disabled with `#send-label` text "Uploading…". THEN press `#send-btn` twice more (the user's exact spam — the button is disabled so the presses are no-ops; also try an Enter-to-submit while disabled — the form submit's `sendBtn.disabled` guard) → after the window, the upload-request counter is EXACTLY 1 (no double upload, no second turn).
|
||||||
|
- `test_upload_success_clears_and_turn_proceeds` — the SAME flow, past the window: the `is-uploading` class is gone, `.attach-preview-status` hidden, `#attach-remove` enabled, `#send-label` back to the idle "Send"; the strip HIDEs with the send (the phase-123 contract — the preview clears when the question goes out); the user bubble renders with the attached image (the phase-123 `attachBubbleImage` — the data-URL `img`), and the turn completes (the mock's grounded answer streams to `done` — the brain bubble is non-empty).
|
||||||
|
- `test_upload_failure_clears_state_and_keeps_the_draft` — a SECOND app/route that FAILS the upload (the route aborts or the handler is pointed at a 413 shape — the simplest: `route.abort("failed")` → `uploadAttachedImage`'s network-drop banner path): mid-flight the uploading state is visible (same assertions); after resolution: the state is CLEARED (no `is-uploading`, Send re-enabled with "Send"), the out-of-turn banner is shown ("Couldn't attach the image — try again." — the network-drop copy), the input text is INTACT, and the strip is back in its normal preview (the attachment remains for the retry — `#attach-preview` not hidden, no `is-uploading`).
|
||||||
|
4. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov`), the mock-only gate, the route-delay rationale (the in-flight window is otherwise ~50 ms — unsamplable), the fixture notes, the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% bar is carried by task 01's unit pins; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_image_upload_feedback.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the mid-flight assertions are deterministic (the route delay makes the window ≥ 2 s — the UI's no-poll direct state, asserted by waiting for the class, not a race)
|
||||||
|
- [ ] exactly ONE upload request per Send-press sequence (the spam is visibly AND functionally dead)
|
||||||
|
- [ ] no behavior change in completed phases (the phase-123 upload contract, the A5 path-never-bytes rule, the out-of-turn banner)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Phase 133 — Garbage PDF text is detected; the page-screenshot vision fallback extracts it
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L9 — "test_sources/hnb_2026_guide.tar.gz contains a pdf that is being read as binary. Figure out why. It contains images, tables, and text but none of that is being extracted correctly. Instead, the raw xml is being embedded and the preview shows the entire document as lines like `<illustrator:StartupProfile>Web</illustrator:StartupProfile>`. This project should support this kind of PDF and should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
|
||||||
|
|
||||||
|
**FINDING (diagnosed 2026-09-27, before phase authoring — the evidence, verified against the real fixture):**
|
||||||
|
1. The archive holds ONE file: `HBI-2026-Guide-Year-Round_260704_131221.pdf` (6.2 MB, 48 pages, PDFium-produced, **Adobe Illustrator export** — the raw bytes carry 222 × `illustrator:StartupProfile` + 138 × `<x:xmpmeta` uncompressed XMP blocks).
|
||||||
|
2. The CURRENT code (phase 126 onward) extracts it CORRECTLY: `extract_pdf_text` returns 2,585 lines, **0 XML-ish**; a full real-importer run stores clean content (`---PAGE-N---` blocks, "2026 U.S. Benefits Guide" first page), the title, and vision-described embedded images.
|
||||||
|
3. The garbage the owner saw is the **pre-126 import**: `pdf` was already in `BOR_IMPORT_EXTENSIONS` in the local `.env` (untracked — predates the parser) BEFORE `126_pdf_support` shipped (commit `e0f11e7`, 2026-09-27 09:36). The generic text path (`importer.py` L689: `read_text(encoding="utf-8", errors="replace").replace("\x00", "")`) read the raw PDF bytes — the uncompressed XMP/structure blocks survive as literal text (reproduced: 138,170 non-empty lines, **46% XML-ish** — `<</Pages 2 0 R /Type/Catalog>>`, `<illustrator:StartupProfile>Web</…>`, exactly the owner's preview) — and that garbage was chunked + embedded.
|
||||||
|
4. **Production fix is a re-sync**: the importer's content-hash delta sees the old garbage row's digest ≠ the newly extracted text's digest → the next sync re-indexes the file as `updated` with clean content (deploy phase 126 first — it is already on `main`). No migration needed. This is documented here, not a code task.
|
||||||
|
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/pdf.py` (phase 126 — `extract_pdf_text` (L109, `page.get_text("text")` per page, `PAGE_SEPARATOR` blocks, fail-soft `""`), `extract_pdf_images` (L145), the fitz import); `app/rag/importer.py` — `_index_pdf_file` (the phase-126 PDF branch: extract → doc row → digest over extracted text → chunk + embed → lite summary → embedded images via `_describe_or_skip` (L1779)); `app/rag/summarizer.py` — `describe_image` (L208: ONE chat-model call, multimodal user message, `data: bytes` + `mime`, returns `str | None`, no app-level retry); `ImportSummary` (L212, the stats counters + `log()` line); `tests/e2e/mock_llm.py` — the `IMAGE_DESCRIPTION_MODE` canned vision reply (deterministic for the E2E); `test_sources/hnb_2026_guide.tar.gz` (the untracked fixture, 2.6 MB compressed).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Two guarantees, one for today and one for the class of problem: (a) the owner's guide is pinned as a regression — it imports through the real pipeline with CLEAN content (the root cause is documented above: a pre-126 binary-text import, self-healed by a re-sync); (b) any future PDF whose extracted text is GARBAGE (XML/binary soup, empty text layer) is DETECTED by a deterministic gate and falls back to the owner's specified path — every page rendered to a screenshot and read by the vision model, preserving what the text layer couldn't.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `132_image_upload_feedback` (todo) — pipeline order only; code dependencies are the completed phase-126 PDF pipeline + the phase-122 vision path.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The gate (task 02):** `app/rag/pdf.py` gains `is_usable_pdf_text(text: str) -> bool` — pure, deterministic, unit-testable. Unusable when ANY of: `text.strip() == ""` (the empty text layer — the fallback's other target); the fraction of non-empty lines that look like XML is ≥ 0.30 (a line is XML-ish: `re.search(r"</?[A-Za-z_][\w:.-]*[\s/>=]", line)` — covers `<tag>`, `</tag>`, `<tag attr=`, and the PDF-structure `<</Key…` noise); the non-printable fraction (U+FFFD replacement chars + C0 control chars, over the whole text) is ≥ 0.05 (the binary-soup signal — the pre-126 read is 46% XML-ish AND heavy on U+FFFD; a real document about XML with ≥ 30% tag-like lines is a documented false-positive cost — ASSUMPTION A8). Applied in `_index_pdf_file` AFTER `extract_pdf_text` (the extractor stays pure).
|
||||||
|
- **The fallback (task 03):** when the gate fails, `_index_pdf_file` takes the owner's specified path — "screenshotting the pages and reading each one as an image": `app/rag/pdf.py` gains `render_pdf_pages(pdf_path: Path, dpi: int = 150) -> list[bytes]` (one PNG per page, PyMuPDF `page.get_pixmap(dpi=dpi).tobytes("png")`, in page order; an unreadable page → a zero-byte entry the caller replaces with the placeholder — no page index may shift); for each page, `describe_image(llm, data=png, mime="image/png")` — the phase-122 vision call, fail-soft per page (`None` → the placeholder line). The stored `content` = `PAGE_SEPARATOR` blocks of the page descriptions (`---PAGE-N---\n<description or "page N — description unavailable">`) — the SAME separator convention as the text path, so the chunker's page-boundary handling works unchanged. `is_image` stays `False` (it is a PDF document whose content happens to be vision text). The digest is over the constructed content (the phase-126 convention — the fallback output is stable for a stable file, so re-syncs don't re-burn vision: a cached row re-imports as unchanged). ONE loud log line (PLAN §9): `pdf: text layer unusable for <source>/<path> (xml_frac=… nonprint=…) — falling back to N page screenshots`. `ImportSummary` gains `pdfs_screenshotted: int = 0` (the counter + the `log()` field; the sync `detail` shape stays untouched — the stats log-only convention).
|
||||||
|
- **The regression pin (task 01):** the real guide, imported through the REAL importer (the fake LLM with a multimodal `chat` override for the embedded images), must land clean content — 0/low XML-ish fraction + the real first-page text present. The fixture stays the tar.gz (the test extracts it into `tmp_path` — never the repo, `test_sources/` is untracked).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_diagnosis_regression_test.md` — the FINDING is documented in this overview; the task pins the real guide's clean import as a regression integration test.
|
||||||
|
2. `02_pdf_text_gate.md` — `is_usable_pdf_text` (the heuristic) + the pre-126-garbage reproduction fixture.
|
||||||
|
3. `03_page_screenshot_fallback.md` — `render_pdf_pages` + `_index_pdf_file`'s fallback branch + the stats counter.
|
||||||
|
4. `04_e2e_garbage_pdf.md` — dedicated Playwright E2E, run in isolation (the real guide's happy path + a synthetic garbage PDF's fallback path).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the gate (clean text, the REAL pre-126 garbage string — reproduced by reading the fixture with the old `errors="replace"` recipe, XML-heavy text, empty text, a borderline document about XML); `render_pdf_pages` (page count, PNG magic bytes, the zero-byte unreadable-page placeholder); the fallback content assembly (separators, placeholders, the digest stability).
|
||||||
|
- Integration: the real-guide regression (task 01).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only (the `IMAGE_DESCRIPTION_MODE` canned reply is the fallback's vision surface).
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the real guide imports with clean content through the real pipeline (the regression test green — the owner's exact file)
|
||||||
|
- [ ] a PDF whose text layer is XML/binary garbage (synthetic) lands with the vision-described page content — the owner's specified fallback fires end to end
|
||||||
|
- [ ] a clean PDF NEVER burns a single vision call for the fallback (the gate is the only gate — the happy path is byte-identical to phase 126)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (the phase-126 clean-PDF path, the image pipeline, the sync)
|
||||||
|
- [ ] the production stale row is fixed by a re-sync (documented above — verify post-deploy: the guide's content no longer shows XML lines)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Task 01 — The regression pin: the real guide imports CLEAN through the real pipeline
|
||||||
|
|
||||||
|
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "test_sources/hnb_2026_guide.tar.gz contains a pdf that is being read as binary. Figure out why. ... This project should support this kind of PDF and should be able to extract it correctly"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The owner's exact file is a permanent regression: importing `test_sources/hnb_2026_guide.tar.gz`'s PDF through the REAL importer (extraction, digest, chunking, summary, embedded images) lands CLEAN content — the pre-126 XML-garbage import can never come back, and the phase-126 happy path on this 48-page Illustrator PDF is pinned.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/integration/test_pdf_hnb_guide_regression.py` (new) — the house integration pattern (the local compose Postgres, the `tmp_path` fixture, the `tests/fakes.py` `FakeEmbedder`):
|
||||||
|
- Fixture: extract `test_sources/hnb_2026_guide.tar.gz` into `tmp_path` (the test's local source dir — `test_sources/` is untracked, the tar.gz is the stable reference; the extraction is ~6 MB, seconds). The inner file keeps its name (`HBI-2026-Guide-Year-Round_260704_131221.pdf`).
|
||||||
|
- The fake LLM: `FakeEmbedder` with (a) `settings = Settings(_env_file=".env")` (the real extension set — `pdf` is in the owner's live config; a `_env_file=None` fake would silently skip the PDF — the exact trap that hid this class before) and (b) a `chat` override that returns a deterministic string for MULTIMODAL user content (the `list`-of-parts shape `describe_image` sends — the fake's string-only `chat` crashes on it; the override: `"A rendered page of the guide (test vision description)."` — the docstring names it as the task-03-style vision mock the `fakes.py` comment anticipates).
|
||||||
|
- Import with `import_sources([dir], llm)` (the real walk + the real PDF branch).
|
||||||
|
2. Assertions (the observable contract):
|
||||||
|
- `summary.added == 1` (the guide PDF) — the file is ADMITTED by the walk and indexed through the PDF branch (not the text branch: if the text branch ever ran on it again, the content assertions below fail);
|
||||||
|
- the stored `content` is CLEAN: the XML-ish line fraction (< the task-02 gate's 0.30 threshold — assert < 0.05 to be strict: the real extraction is 0/2,585) AND the non-printable fraction < 0.01;
|
||||||
|
- the real first-page text is present: `"2026 U.S. Benefits Guide"` in `content` (pinned fixture text — the file is a stable untracked fixture; if the owner ever re-cuts it, the test failure names the regression, which is the point);
|
||||||
|
- `is_image is False`, `title == "HBI-2026-Guide-Year-Round_260704_131221"` (the stem fallback — the PDF's metadata carries no title, only PDFium creator/producer), the content starts with `---PAGE-1---`;
|
||||||
|
- the embedded-image docs (the phase-126 `#page=…#img=…` rows) got the FAKE vision description (the multimodal `chat` was called — assert `llm.chat_calls` contains ≥ 1 multimodal message) or are absent when the fake "fails" (not this test's scope — the fail-soft is the phase-126 contract).
|
||||||
|
- Wall-time guard: the test completes in < 120 s (48 pages × in-process fakes; if it drifts, the test is too heavy — the suite must stay fast).
|
||||||
|
3. Header docstring: the FINDING summary (the pre-126 root cause in two lines — see the phase overview's FINDING block), the run command (`uv run pytest tests/integration/test_pdf_hnb_guide_regression.py -v`), the fixture provenance.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Integration: this file IS the task's suite.
|
||||||
|
- Coverage: **>90%** on new/modified code (test-only task — the bar is carried by the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/integration/test_pdf_hnb_guide_regression.py -v` green (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the test fails if the PDF is ever routed through the text branch again (a temporary experiment moving the branch order must break it — the pin has teeth)
|
||||||
|
- [ ] the test does not commit the extracted PDF (it lives in `tmp_path`; `git status` stays clean of binaries)
|
||||||
|
- [ ] no behavior change in completed phases
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Task 02 — `is_usable_pdf_text`: the deterministic garbage gate
|
||||||
|
|
||||||
|
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A pure, deterministic predicate decides whether an extracted PDF text layer is real content or garbage (the pre-126 XML/binary soup class, the empty text layer class) — so the screenshot fallback has exactly one trigger, unit-testable without any PDF.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/pdf.py` — new module-level predicate (place it after `extract_pdf_text`, with a docstring citing the FINDING — the pre-126 `read_text(errors="replace")` soup, the 46%-XML-ish reproduction, the owner's `<illustrator:StartupProfile>` preview):
|
||||||
|
```python
|
||||||
|
#: A line "looks like XML" when it carries a tag-shaped token — the
|
||||||
|
#: pre-126 garbage's signature (raw XMP blocks, PDF-structure noise).
|
||||||
|
_XMLISH_LINE_RE = re.compile(r"</?[A-Za-z_][\w:.-]*[\s/>=]")
|
||||||
|
|
||||||
|
def is_usable_pdf_text(text: str) -> bool:
|
||||||
|
"""Whether an extracted PDF text layer is REAL content (not garbage).
|
||||||
|
|
||||||
|
Unusable (→ the page-screenshot fallback) when ANY of:
|
||||||
|
* ``text.strip() == ""`` — the empty text layer (a scanned/image-
|
||||||
|
only PDF has nothing to read);
|
||||||
|
* ≥ :data:`XMLISH_LINE_FRACTION` (0.30) of the non-empty lines
|
||||||
|
match :data:`_XMLISH_LINE_RE` — the raw-XMP / binary-soup
|
||||||
|
signature (the FINDING's reproduced pre-126 read is 46%);
|
||||||
|
* ≥ :data:`NONPRINT_CHAR_FRACTION` (0.05) of all characters are
|
||||||
|
non-printable (U+FFFD replacement chars + C0 controls) — the
|
||||||
|
``errors="replace"`` binary-soup signal.
|
||||||
|
|
||||||
|
Pure + deterministic (no PDF, no I/O) — the unit tests pin the
|
||||||
|
thresholds against the REAL reproduced garbage string, not a
|
||||||
|
hand-drawn one. A real document ABOUT xml whose tag-like lines
|
||||||
|
reach 30% is a documented false positive (ASSUMPTION A8 — the
|
||||||
|
fallback still extracts it correctly via vision; the cost is a
|
||||||
|
few vision calls).
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
with the two threshold constants (`XMLISH_LINE_FRACTION = 0.30`, `NONPRINT_CHAR_FRACTION = 0.05`) — named, documented, not magic. Non-empty-line counting: `line.strip()` truthy (house convention); the non-printable set: `"\ufffd"` + `unicodedata.category(ch).startswith("C")` (or an explicit C0 range check — pick one, document it; exclude the structural `\\n`/`\\t` the extractor legitimately emits — Cc category would catch them, so use the explicit set: `"\ufffd"` + control chars EXCEPT `\\t\\n\\r` — document the exclusion).
|
||||||
|
2. `tests/unit/test_pdf.py` (extend — the phase-126 suite) — the gate's pins:
|
||||||
|
- clean text (a few real paragraphs + the `---PAGE-N---` separators) → `True`;
|
||||||
|
- THE REAL GARBAGE: reproduce the pre-126 read in the test — read `test_sources/hnb_2026_guide.tar.gz`'s PDF (extract to `tmp_path` — share a module-scoped fixture with the integration test's pattern, or a smaller inline reproduction: the test may instead read the tar.gz's PDF bytes with `read_text(errors="replace").replace("\\x00", "")` and pin `is_usable_pdf_text(garbage) is False` — the REAL string, the owner's exact file, the airtight pin);
|
||||||
|
- the empty text layer (`""` / whitespace) → `False`;
|
||||||
|
- an XML-heavy layer (≥ 30% tag-like lines) → `False`;
|
||||||
|
- a borderline document ABOUT xml (29% tag-like lines, printable) → `True` (the threshold's edge, from below) and 31% → `False` (from above);
|
||||||
|
- the U+FFFD-heavy soup (5%+ replacement chars, few tags) → `False` (the second signal fires alone);
|
||||||
|
- the structural `\\n`/`\\t` exclusion (text full of newlines/indents is printable).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pins above — this task's suite.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `is_usable_pdf_text` is pure (no PDF dependency) and pinned on the REAL reproduced garbage string (the owner's file, not a lookalike)
|
||||||
|
- [ ] both failure signals (XML-ish fraction, non-printable fraction) are tested independently
|
||||||
|
- [ ] the thresholds are named constants with the false-positive cost documented
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Task 03 — The screenshot fallback: unusable text layer → render pages, read each by vision
|
||||||
|
|
||||||
|
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image to preserve formatting when text/image/table extraction isn't working."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
When the gate (task 02) says the text layer is garbage or empty, `_index_pdf_file` takes the owner's specified path: every page is rendered to a PNG screenshot and read by the vision model — the stored content is the page-anchored descriptions, so tables/images/whatever the text layer lost are preserved as the model saw them on the page.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/pdf.py` — new pure renderer:
|
||||||
|
```python
|
||||||
|
def render_pdf_pages(pdf_path: Path, dpi: int = 150) -> list[bytes]:
|
||||||
|
"""Render every page of *pdf_path* to a PNG (page order, 1-based
|
||||||
|
meaning — list index i is page i+1).
|
||||||
|
|
||||||
|
The fallback's visual input (ASSUMPTION A8: fixed 150 DPI — the
|
||||||
|
balance of vision legibility vs data-URL payload; a page that
|
||||||
|
cannot be rendered yields b"" (the caller's placeholder — the
|
||||||
|
page index NEVER shifts, so ---PAGE-N--- stays truthful).
|
||||||
|
A file that cannot be OPENED yields [] (the caller's existing
|
||||||
|
empty-content path — the doc lands with the no-extractable-text
|
||||||
|
behavior, unchanged).
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
PyMuPDF: `page.get_pixmap(dpi=dpi).tobytes("png")` per page, per-page try/except (the `extract_pdf_text` fail-soft style — log a warning per skipped page).
|
||||||
|
2. `app/rag/importer.py` — `_index_pdf_file`: after `content = extract_pdf_text(full_path)`, insert the gate branch (BEFORE the doc-row upsert, so the digest/chunk/summary pipeline runs on the FINAL content exactly once):
|
||||||
|
```python
|
||||||
|
if not is_usable_pdf_text(content):
|
||||||
|
summary.pdfs_screenshotted += 1
|
||||||
|
content = await _fallback_page_screenshots(session, source=source, rel=rel,
|
||||||
|
full_path=full_path, llm=llm)
|
||||||
|
```
|
||||||
|
with the new module-level helper `_fallback_page_screenshots` (place it near `_index_pdf_file`):
|
||||||
|
- `pages = render_pdf_pages(full_path)`;
|
||||||
|
- the loud one-line log (PLAN §9, the FINDING's signature): `logger.warning("pdf: text layer unusable for %s/%s — falling back to %d page screenshots", source, rel, len(pages))` (the gate's fractions ride the log at DEBUG: `logger.debug("pdf: gate xml_frac=%.2f nonprint=%.2f …")` — computed by a small `_gate_fractions(text)` helper the unit tests pin too, if the warning wants them — optional, keep the required line exact);
|
||||||
|
- per page (index i, page = i+1): `png = pages[i]`; if `png == b""` → `block_text = f"page {page} — description unavailable"`; else `desc = await describe_image(llm, data=png, mime="image/png")` (the phase-122 call — `settings` default, `context` None); `desc is None` or blank → the same placeholder (fail-soft per page — a dead vision endpoint must not sink the doc, the phase-122 fail-soft spirit); else `block_text = desc.strip()`;
|
||||||
|
- `content = "\n\n".join(f"{PAGE_SEPARATOR.format(page=p)}\n{block}" for p, block in ...)` — the SAME separator convention as `extract_pdf_text` (the chunker's page-boundary handling works unchanged);
|
||||||
|
- an ALL-failed render (`pages == []` or every page placeholder) → return `""` (the existing empty-content path — the doc lands as a zero-text doc, the phase-126 no-extractable-text behavior);
|
||||||
|
- the embedded-image extraction (`extract_pdf_images` + `_describe_or_skip`) still runs AFTER the gate branch on BOTH paths — the fallback doc's embedded images join the pipeline exactly as a clean PDF's do (the screenshots are the CONTENT; the extracted images are the citation figures — both, no conflict).
|
||||||
|
3. `app/rag/importer.py` — `ImportSummary`: add `pdfs_screenshotted: int = 0` (documented: "PDFs whose text layer failed the gate and took the page-screenshot vision fallback (phase 133)") + the field in `log()`'s format string (append to the existing line — the house ample-logging shape).
|
||||||
|
4. `app/rag/importer.py` — the digest: the fallback's constructed content is what the sha256 runs over (the existing `digest = hashlib.sha256(content.encode(...))` line — no change needed, just verify it runs AFTER the gate branch so a fallback doc's row is stable across re-syncs: same pages + same vision model → same descriptions → same digest → unchanged on the next sync, no vision re-burn. If `describe_image`'s reply is non-deterministic in production, note it in the docstring — the re-burn is then a cost, not a bug).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_pdf.py` (extend) — `render_pdf_pages`: a 2-page temp PDF (built with fitz in the test — the phase-126 fixture pattern) → 2 PNGs (magic bytes `\\x89PNG`), page order; an unreadable path → `[]`; a corrupted page (if constructible — else the b"" path via a monkeypatched `get_pixmap` raising) → the zero-byte entry at its index, the index intact.
|
||||||
|
- Unit: `tests/unit/test_importer.py` (extend) — the fallback branch, with a REAL tiny garbage PDF (build one in the test: a fitz page whose inserted text is ONLY XML-ish lines — `<foo:bar>x</foo:bar>` repeated — so the gate fails deterministically) + a fake LLM whose multimodal `chat` returns a canned page description: the stored doc's content = `---PAGE-1---\\n<canned>` (the separator convention), `summary.pdfs_screenshotted == 1`, the loud warning logged (the caplog pin); a CLEAN tiny PDF (the phase-126 fixtures) → `pdfs_screenshotted == 0` and the vision multimodal `chat` is NEVER called for the fallback (only the embedded-image describes — the gate never burns vision on a clean layer).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a garbage-text PDF lands with the page-screenshot content (the synthetic test: `---PAGE-N---` + the canned descriptions)
|
||||||
|
- [ ] a clean PDF's path is byte-identical to phase 126 (no fallback, no extra vision calls, `pdfs_screenshotted == 0`)
|
||||||
|
- [ ] the fallback is fail-soft per page (a dead vision call → the placeholder line, the doc still lands)
|
||||||
|
- [ ] `uv run pytest tests/unit -q` green; no behavior change in completed work
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 04 — E2E: the real guide stays clean, a synthetic garbage PDF takes the screenshot path
|
||||||
|
|
||||||
|
**Phase:** `133_pdf_screenshot_fallback` · **Source:** `TODO.md:9` — "...the raw xml is being embedded and the preview shows the entire document as lines like `<illustrator:StartupProfile>Web</illustrator:StartupProfile>`. This project should support this kind of PDF and should be able to extract it correctly, even if that means screenshotting the pages and reading each one as an image..."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, mock-only Playwright suite (A16 — one per phase, run in isolation) pins both legs of the guarantee at the user surface: (a) the owner's REAL guide, imported through the admin sync, previews CLEAN text (no XML lines — the exact complaint, negated); (b) a synthetic PDF whose text layer is pure XML garbage takes the screenshot fallback end to end — its content is the mock's canned vision descriptions, and the preview shows them.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_garbage_pdf.py` (new) — house pattern (module app fixture over the shared E2E Postgres, host temp-dir `kind=local` source registered via the admin git-sources API, autouse truncate cleanup, mock-only — `E2E_REAL_LLM=1` unsupported: the fallback's vision surface is the deterministic `IMAGE_DESCRIPTION_MODE` canned reply).
|
||||||
|
App env: `BOR_IMPORT_EXTENSIONS` must include `pdf` (the owner's live config — the app fixture's env, the phase-126/127 suites' pattern) and `BOR_IMAGES=1` (the embedded-image pipeline is live).
|
||||||
|
2. Fixtures (two local sources, two tests):
|
||||||
|
- `hnb/` — the REAL guide: extract `test_sources/hnb_2026_guide.tar.gz` into the temp dir (module-scoped, once — the 6 MB extraction is seconds).
|
||||||
|
- `garbagedoc/` — a synthetic garbage PDF built IN the test with PyMuPDF (the fixture pattern from task 03's unit test, lifted here): 2 pages, each page's ONLY text = repeated XML-ish lines (`<illustrator:StartupProfile>Web</illustrator:StartupProfile>` × ~20 — the owner's exact line shape, so the test is a faithful reproduction of the report), plus one small embedded raster image per page (fitz `insert_image` from a tiny PNG built in the test — the fallback's embedded-image leg runs too).
|
||||||
|
3. Test → observable mapping (Playwright Mapping Rule):
|
||||||
|
- `test_real_guide_previews_clean_text` — admin sync over `hnb/` settles `success`; `GET /api/documents/content?source=hnb&path=<the guide's pdf>` (the PREVIEW surface — the endpoint the document viewer's content uses): the body contains `"2026 U.S. Benefits Guide"` (the real first-page text) and NO line matching the XML-ish regex (the owner's complaint, asserted on the served content, not the DB); the document viewer page (`/document.html?source=hnb&path=…`) renders that content (the preview shows real text, not `<illustrator:…>` lines).
|
||||||
|
- `test_garbage_pdf_takes_the_screenshot_path` — admin sync over `garbagedoc/` settles `success`; the stored doc's content (the same content endpoint): starts with `---PAGE-1---`, contains the mock's CANNED vision description (the `IMAGE_DESCRIPTION_MODE` reply's deterministic text — assert the first 40 chars) for BOTH pages (2 separators, 2 descriptions), and contains NO `<illustrator:StartupProfile>` line (the garbage text layer is NOT what got stored — the screenshot path replaced it); the sync's `detail` is `success` with `added == 1` (the garbage PDF is a normal import — the fallback is invisible in the status shape; the loud log line is server-side, PLAN §9).
|
||||||
|
- `test_clean_pdf_never_burns_the_fallback` — a third source `cleandoc/` with ONE small clean PDF (fitz, real prose text): sync → the stored content is the PROSE (the text layer, byte-faithful to the extraction) — NOT the canned vision description (the fallback did not fire on a clean layer — the gate's no-false-negative pin at the E2E level).
|
||||||
|
4. Header docstring: the run-in-isolation command (`uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov`), the mock-only gate + why (the canned vision reply makes the fallback deterministic), the fixture provenance (the real tar.gz + the synthetic builder), the test→observable table.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite — run in isolation, green.
|
||||||
|
- Coverage: the phase's >90% `app/` bar is carried by tasks 02–03; the real-guide regression by task 01; this task adds the in-isolation Playwright gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_garbage_pdf.py -v --no-cov` green in isolation (DB up: `podman compose up -d db`)
|
||||||
|
- [ ] the real guide's PREVIEW (the owner's exact surface) is clean — the `<illustrator:StartupProfile>` line is asserted ABSENT on the served content
|
||||||
|
- [ ] the synthetic garbage PDF's stored content is the canned vision descriptions (the fallback fired end to end, mock-deterministic)
|
||||||
|
- [ ] the clean PDF is byte-faithful to its text layer (no false-positive fallback)
|
||||||
|
- [ ] no behavior change in completed phases (the phase-126 pipeline, the sync, the document viewer)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Phase 134 — The owner can cancel a running sync from the Sources page
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Need to be able to cancel a sync after I've clicked the button."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/api/sync.py` — `SyncStatus` (the four-state dataclass: `idle` / `running` / `success` / `failed`, phase-64 progress fields, phase-98 phase-machine fields), the module-level `_status` + `_task`, `POST /api/sync` (202 / 409 one-sync-at-a-time), `GET /api/sync/status`, and `_run_sync` — the in-process `asyncio` background task: the blocking git prelude (`scripts.git_sync.clone_or_pull` → `subprocess.run`, no await inside), then `await import_sources(...)` (per-file LLM awaits — a cancellation point between files), then `await regenerate_overview(...)` and `await generate_folder_summaries(...)` (both only on a changed KB / gap). The module docstring's shutdown contract: `CancelledError` is deliberately NOT swallowed — app shutdown cancels the task, and swallowing would mask a real stop. `import_sources` closes its own private session in a `finally` (leak-safe under a mid-import cancel). `frontend/assets/sources.js` — the sync-button lifecycle: `enterSyncRunningState` (live click + re-attach + every running tick), `settleSyncButton` (every terminal), `applySyncSuccess` / `applySyncFailure` / `applySyncIdle`, `startSyncPolling` (the 2 s two-job decision tree, 7 branches), `initSyncButton` (load-time re-attach). `frontend/index.html` — the `#sync-btn` markup (the Sources view section). E2E patterns: `tests/e2e/test_sync_button.py` (per-module app on a dedicated port, the `file://` fixture repo, the `_wait_sync_done` status-poll helper), `tests/e2e/slow_llm.py` (the delay-injecting proxy that makes a run's duration deterministic), `tests/e2e/mock_llm.py`. Unit: `tests/unit/test_sync_button.py`; integration: `tests/integration/test_sync_api.py`.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A sync that is already running can be stopped by the owner: while a run is in flight the Sources page shows a **Cancel** button; one click requests the cancel, the pipeline stops at the next boundary, the run lands in a new `cancelled` terminal state (reported by the status endpoint and rendered by the UI as a neutral result — cancel is intent, not failure), and the controls settle back to the retry-ready idle state. A subsequent sync starts cleanly (the partial run leaves a consistent KB — the importer's content-hash delta makes the next run idempotent).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `133_pdf_screenshot_fallback` (todo) — pipeline order only; no code dependency.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The fifth state — `cancelled`** (ASSUMPTION A1): `SyncStatus.state` becomes `Literal["idle", "running", "success", "failed", "cancelled"]`. It is TERMINAL like `success` / `failed`: carries `finished_at`, clears `current_file` / `phase` / `current_summary` but keeps the run's final `files_done` / `files_total` and summary counts (the phase-64/98 keep-final-counts convention), `detail = {}`, and **`error = None`** (no error string — the UI never treats it as a failure: no error banner, no error modal, just the neutral "Sync cancelled" result line). `GET /api/sync/status` gains nothing structurally — the `state` key simply reports `"cancelled"`.
|
||||||
|
- **`POST /api/sync/cancel`** (same `router`, so `require_admin` — 403 anonymous): while a run is in flight → set the module-level `_cancel_event` (an `asyncio.Event`, next to `_status` / `_task`) AND call `_task.cancel()` (unblocks whatever `await` the pipeline is parked on — e.g. a per-file LLM call inside the import) → **202** `{"detail": "cancel requested"}`. No run in flight (`_task` None or done) → **409** `{"detail": "no sync is running"}`. `start_sync` resets `_cancel_event` (clear) when it starts a run.
|
||||||
|
- **Cancellation semantics — cooperative, best-effort** (ASSUMPTION A2): `_run_sync` gains (a) a private `_check_cancelled()` helper that raises `asyncio.CancelledError()` when `_cancel_event.is_set()`, called at the pipeline boundaries — the top of the per-source loop (before each clone/pull or local-dir check), immediately before `import_sources(...)`, and immediately before the `if summary.added + summary.updated > 0:` block (covers the overview + summaries spans); and (b) an `except asyncio.CancelledError:` clause (placed before the existing `except Exception`): if `_cancel_event.is_set()` → land the run in the `cancelled` terminal state + one INFO log line (PLAN §9: `sync: cancelled by user state=cancelled`), then `raise` (the task ends cancelled — `_task.done()` is True, the status object stays authoritative); otherwise (no user cancel — the app-shutdown path) → `raise` unchanged (the module docstring's shutdown contract holds: an unrequested cancellation is never swallowed). Consequence the UI/tests may rely on: a git subprocess already running at the cancel moment runs to completion (the blocking `subprocess.run` has no await inside) — the cancel takes effect at the NEXT boundary (after that source's git ops, between files, or before overview/summaries). During the import span the `_task.cancel()` from the endpoint interrupts at the next per-file await.
|
||||||
|
- **The UI** (ASSUMPTION A3): a `#sync-cancel-btn` button in the same sync-control area as `#sync-btn` (`frontend/index.html`), `hidden` by default; secondary button styling consistent with the theme (contrast ≥4.5:1, `:focus-visible` ring — house UI rules). `sources.js` rules: SHOWN + ENABLED only while a SYNC run is running (`enterSyncRunningState` with `kind === "sync"` — the upload job is NOT cancellable in this phase, so the cancel button stays hidden while only the upload run drives the button); HIDDEN + DISABLED by `settleSyncButton` (every terminal/idle settle) and by every `applySync*` path. Click → `requestCancel()`: the cancel button disables IMMEDIATELY (never stale, no double request), `POST /api/sync/cancel`; 403 → the whoami-backstop hide-everything branch (same as the other endpoints); 409 → a harmless race (the run ended between ticks — the poll settles on the next tick, no error copy); 202 → the button stays disabled until the terminal (the poll's new `cancelled` branch settles everything); any other non-2xx → the phase-55 neutral retry copy in `#sync-result` ("Couldn't cancel the sync — try again.") + the cancel button re-enables. New poll-tree branch (after the `failed` branch, before the idle branch): `syncStatus.state === "cancelled"` → stop polling, settle the main button to "Sync sources", `#sync-result` = "Sync cancelled" (the aria-live announcer reads it), hide the error banner, hide the cancel button, `emitSyncStatus`. `initSyncButton` re-attach: `state === "cancelled"` → the same neutral settle (a page reload during/right after a cancel shows "Sync cancelled", never a stuck running state).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_backend_cancel_state.md` — the `cancelled` state, `POST /api/sync/cancel`, and the cooperative cancel mechanics in `_run_sync`.
|
||||||
|
2. `02_frontend_cancel_button.md` — the `#sync-cancel-btn` UI: show/hide rules, the cancel request lifecycle, the `cancelled` terminal branch in the poll tree + re-attach.
|
||||||
|
3. `03_e2e_sync_cancel.md` — the dedicated Playwright E2E (the slow-LLM cancel window, the API contract, the full UI lifecycle, the clean re-sync after cancel).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the cancel endpoint's contract (202/409/403), `_check_cancelled`, the `CancelledError` conversion (event set → `cancelled` state + re-raise; event unset → re-raise with the state untouched), the `SyncStatus` reset on a fresh start (a stale cancel event cannot bleed into the next run).
|
||||||
|
- Integration: a real run started through the API is cancelled mid-run → the status reports `cancelled` (with `error: None`); a second run after the cancel completes successfully (the restart is clean).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation (`tests/e2e/test_sync_cancel.py`) — the mock-only app with the `slow_llm` proxy for a deterministic cancel window.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `POST /api/sync/cancel` (admin): 202 while a run is in flight, 409 `no sync is running` otherwise, 403 anonymous
|
||||||
|
- [ ] a cancelled run lands in the `cancelled` terminal state (`error: None`, final counts kept) and the status endpoint reports it
|
||||||
|
- [ ] the app-shutdown cancel contract is preserved (an unrequested `CancelledError` is never swallowed — a unit test pins it)
|
||||||
|
- [ ] the UI: the Cancel button is visible exactly while a sync run is running, the `cancelled` terminal settles to "Sync cancelled" with no error banner/modal, and a re-sync after a cancel succeeds
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_sync_cancel.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (the uncancelled run is byte-identical: same states, same labels, same 409 double-trigger)
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Task 01 — Backend: the `cancelled` state, `POST /api/sync/cancel`, and the cooperative cancel in `_run_sync`
|
||||||
|
|
||||||
|
**Phase:** `134_sync_cancel` · **Source:** `TODO.md:3` — "Need to be able to cancel a sync after I've clicked the button."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The sync API can stop its own in-flight run: a new admin-only `POST /api/sync/cancel` requests the cancel; `_run_sync` converts a user-requested cancellation into a new `cancelled` terminal state (never an error); the shutdown-cancel contract is untouched.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/api/sync.py` — the state machine:
|
||||||
|
- `SyncStatus.state`: `Literal["idle", "running", "success", "failed", "cancelled"]` (the docstring's four-state paragraph becomes five; `cancelled` is terminal like `success` / `failed`).
|
||||||
|
- Module level, next to `_status` / `_task`: `_cancel_event = asyncio.Event()`.
|
||||||
|
- `start_sync`: reset the run's cancellation — `_cancel_event.clear()` before `_task = asyncio.create_task(_run_sync())` (a stale event from a previous cancelled run must never bleed into the next run).
|
||||||
|
2. `app/api/sync.py` — the endpoint (same `router` → `require_admin` applies, 403 anonymous):
|
||||||
|
```python
|
||||||
|
@router.post("/cancel", status_code=202)
|
||||||
|
async def cancel_sync() -> dict[str, str]:
|
||||||
|
if _task is None or _task.done():
|
||||||
|
raise HTTPException(status_code=409, detail="no sync is running")
|
||||||
|
_cancel_event.set()
|
||||||
|
_task.cancel()
|
||||||
|
return {"detail": "cancel requested"}
|
||||||
|
```
|
||||||
|
202 is answered the moment the request is REGISTERED (the run may already be terminal — the UI's poll then settles on the terminal state; a 202-then-immediate-404-style race is impossible because the status object, not the task, is authoritative).
|
||||||
|
3. `app/api/sync.py` — `_run_sync` mechanics:
|
||||||
|
- A private helper: `def _check_cancelled() -> None:` — `if _cancel_event.is_set(): raise asyncio.CancelledError()`.
|
||||||
|
- Call it at the boundaries: (a) the top of the per-source loop (before the `kind == "git"` / `kind == "local"` split), (b) immediately before `await import_sources(...)`, (c) immediately before the `if summary.added + summary.updated > 0:` block (covers both the overview and the summaries spans).
|
||||||
|
- New `except asyncio.CancelledError:` clause placed BEFORE the existing `except Exception`:
|
||||||
|
```python
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
if _cancel_event.is_set():
|
||||||
|
_status.state = "cancelled"
|
||||||
|
_status.finished_at = datetime.now(UTC)
|
||||||
|
_status.error = None
|
||||||
|
_status.current_file = None
|
||||||
|
_status.phase = None
|
||||||
|
_status.current_summary = None
|
||||||
|
logger.info(
|
||||||
|
"sync: cancelled by user state=cancelled files_done=%d files_total=%d",
|
||||||
|
_status.files_done, _status.files_total,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
raise # app shutdown — the module-docstring contract: never swallow an unrequested cancel
|
||||||
|
```
|
||||||
|
The terminal keeps `files_done` / `files_total` and the summary counts (the phase-64/98 keep-final-counts convention); `detail` stays `{}` (a partial run reports no counts — ASSUMPTION A1: `error` is None, `detail` is empty).
|
||||||
|
- Update the module docstring: the state machine is five-state; the cancel semantics are cooperative (a git subprocess in flight at the cancel moment runs to completion — the cancel lands at the next boundary); the `CancelledError` paragraph now names BOTH conversion paths (user-requested → `cancelled` state + re-raise; unrequested → re-raise).
|
||||||
|
4. `GET /api/sync/status` — no shape change; update its docstring (the `state` value set now includes `cancelled`; `error` is null in that state).
|
||||||
|
5. Unit tests — `tests/unit/test_sync_button.py` (extend) or a new `tests/unit/test_sync_cancel.py` (your call — the existing file owns the endpoint's contract, so extending it is the default):
|
||||||
|
- `POST /api/sync/cancel` anonymous → 403; idle (never started, and after a terminal run) → 409 with the exact detail `no sync is running`.
|
||||||
|
- A started run: the endpoint returns 202 `{"detail": "cancel requested"}`, sets the event, and cancels the task (drive `_run_sync` with a controllable await — e.g. a monkeypatched `import_sources` that awaits a `asyncio.Event` the test controls — then cancel via the endpoint and assert the task finished + `_status.state == "cancelled"`, `error is None`, `finished_at` set, final counts kept, `detail == {}`).
|
||||||
|
- The shutdown contract pin: cancel the task WITHOUT setting the event (bare `task.cancel()`) → `_status.state` is NOT `cancelled` (stays `running` — the task died mid-run without a terminal state, exactly as today's shutdown path does) and the `CancelledError` propagated.
|
||||||
|
- The stale-event pin: a run that was cancelled, then a FRESH run starts → `_cancel_event` is cleared (the new run completes to `success` with no cancel request).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the behaviors in Work step 5 (the suite above IS the task's unit layer).
|
||||||
|
- Integration: `tests/integration/test_sync_api.py` (extend) — start a real run against the `file://` fixture pattern the file already uses (a slow/many-file fixture or a monkeypatched delay at the per-file hook seam — follow the file's existing fakes), `POST /api/sync/cancel` while running → poll `GET /api/sync/status` → `state == "cancelled"` (and `error is None`); then a second full run → `state == "success"` (the restart after a partial cancel is clean — the importer's hash delta re-imports what the cancel skipped).
|
||||||
|
- Coverage: **>90%** on new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_sync_button.py tests/integration/test_sync_api.py -v` green (plus the new test file, if split)
|
||||||
|
- [ ] the five-state machine is exercised in tests: `cancelled` is reachable ONLY through a user-requested cancel (the unrequested-cancel pin is green)
|
||||||
|
- [ ] the module docstring names the cooperative boundary semantics (a future reader sees why a long clone can outlive the click)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change for the uncancelled run (the existing sync tests stay green untouched)
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Task 02 — Frontend: the `#sync-cancel-btn` and the `cancelled` terminal branch in the poll tree
|
||||||
|
|
||||||
|
**Phase:** `134_sync_cancel` · **Source:** `TODO.md:3` — "Need to be able to cancel a sync after I've clicked the button."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The Sources page shows a Cancel button exactly while a sync run is in flight (live click, re-attached run, every running poll tick); clicking it requests the cancel and the UI settles into the neutral "Sync cancelled" terminal — no error banner, no modal, never stale.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/index.html` (the Sources view section, next to `#sync-btn`): add the cancel control —
|
||||||
|
```html
|
||||||
|
<button type="button" id="sync-cancel-btn" class="sync-cancel-btn" hidden>Cancel</button>
|
||||||
|
```
|
||||||
|
- `hidden` by default (anonymous-safe + the idle state; the module reveals it, the same convention as `#sync-btn`).
|
||||||
|
- A visible "Cancel" label (no icon-only — WCAG 2.4 name/role; the accessible name is the text).
|
||||||
|
- `frontend/assets/styles.css`: `.sync-cancel-btn` — a secondary button style consistent with the theme (the house tokens, contrast ≥4.5:1 on `--surface`, `:focus-visible` ring like the other buttons, disabled state). No layout regression on the sync-control row (mobile included — the row already wraps; verify the 360 px case).
|
||||||
|
2. `frontend/assets/sources.js` — the lifecycle (all inside the existing sync section; the §7.4 never-stale contract applies exactly as to the main button):
|
||||||
|
- Element lookup: `const syncCancelBtn = root.querySelector("#sync-cancel-btn");`
|
||||||
|
- Show/hide helpers: `showSyncCancelBtn()` (unhide + enable + `aria-label="Cancel sync"`) / `hideSyncCancelBtn()` (hide + disable).
|
||||||
|
- `enterSyncRunningState(kind, …, status)`: when `kind === "sync"` → `showSyncCancelBtn()`; when `kind === "upload"` → `hideSyncCancelBtn()` (the upload job is NOT cancellable in this phase — the cancel button belongs to the sync run only).
|
||||||
|
- `settleSyncButton(label)`: always `hideSyncCancelBtn()` (every terminal/idle settle — sync success/failed/cancelled, upload success/failed, both idle).
|
||||||
|
- `requestCancel()` + the click listener (armed next to `syncBtn.addEventListener("click", startSync)`):
|
||||||
|
- `syncCancelBtn.disabled = true` FIRST (never stale, one request at a time), `#sync-result` cleared.
|
||||||
|
- `POST /api/sync/cancel`: 403 → the whoami-backstop branch (stop polling, hide the main button, `applySyncIdle()`) — the same depth as every other 403 in this module; 409 → NO-OP (the run ended between the tick and the click — the poll settles on the next tick; the cancel button is hidden by that settle; no error copy); 202 → nothing (the button stays disabled — the poll's `cancelled` branch settles everything); any other non-2xx / network failure → `#sync-result` = "Couldn't cancel the sync — try again." (the phase-55 neutral retry copy) + `syncCancelBtn.disabled = false` (the run is still going — the owner can retry).
|
||||||
|
- New terminal branch in `startSyncPolling`'s tick — placed AFTER the `failed` branch and BEFORE the upload-success branch:
|
||||||
|
```js
|
||||||
|
if (syncStatus.state === "cancelled") {
|
||||||
|
stopSyncPolling();
|
||||||
|
applySyncCancelled(syncStatus);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `applySyncCancelled(status)`: `settleSyncButton("Sync sources")` (re-enables the main button, hides the cancel button), `syncResult.textContent = "Sync cancelled"`, `hideSyncError()`, `emitSyncStatus(status)`. No modal, no error styling (ASSUMPTION A1 — cancel is intent).
|
||||||
|
- `initSyncButton` re-attach: `status.state === "cancelled"` → `applySyncCancelled(status)` (a reload during/right after a cancel shows the neutral result, never a stuck running state).
|
||||||
|
- Update the section-header docstring (the decision tree gains the `cancelled` branch — the tree's "7" becomes "8" — and the cancel button's show/hide contract is documented there, the house pattern).
|
||||||
|
3. No change to the upload job, the main sync button's existing labels, or the `bor:sync-status` event shape (the `cancelled` state simply flows through `emitSyncStatus` — the event's `detail` is the status object, as for every other state).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- No JS unit layer in this repo — the UI contract is pinned by the phase's E2E (task 03) and by the never-stale rules above.
|
||||||
|
- Coverage: **>90%** on new/modified code (test-only-for-`app/` task — the bar is carried by the suite run; the JS is covered by the E2E).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the Cancel button is visible + enabled ONLY while a sync run is running (hidden on boot/idle, hidden while only the upload run drives the button, hidden on every terminal)
|
||||||
|
- [ ] clicking Cancel settles to "Sync cancelled" in `#sync-result` with the main button re-enabled, the cancel button hidden, no error banner and no modal
|
||||||
|
- [ ] a 409 cancel (race) is silent; a failed cancel request shows the neutral retry copy and re-enables the button (the run keeps going)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean; the page renders with no console errors (verified in the E2E, task 03)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Task 03 — E2E: `tests/e2e/test_sync_cancel.py` (the dedicated Playwright suite, run in isolation)
|
||||||
|
|
||||||
|
**Phase:** `134_sync_cancel` · **Source:** `TODO.md:3` — "Need to be able to cancel a sync after I've clicked the button."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The owner's cancel path is pinned end to end against the REAL pipeline: a real `file://` fixture sync whose duration is long enough to cancel (the `slow_llm` proxy), the API contract (403/409/202), the UI lifecycle (Cancel button visible → click → "Sync cancelled" settle), and the clean re-sync after a partial run.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_sync_cancel.py` (new) — the `test_sync_button.py` module-app pattern, adapted:
|
||||||
|
- **Ports/env:** per-module app on its own port — `APP_PORT = int(os.environ.get("E2E_APP_PORT_SYCNCEL", "8133"))`; `BOR_STATIC_DIR`, `BOR_RELEVANCE_THRESHOLD=0.30` (mock-calibrated, the conftest pattern), `BOR_ADMIN_PASSWORD` / `BOR_SESSION_SECRET` from `e2e.conftest`, `BOR_GIT_SOURCES=file://<fixture repo>`, a dedicated `BOR_SOURCES_DIR`.
|
||||||
|
- **The slow-LLM proxy:** spawn `tests/e2e/slow_llm.py` the conftest way (the `SLOW_LLM_DELAY_S` env — 0.3 s is a good default: ~40 fixture files → ~12+ s of import — a wide, deterministic cancel window against the UI's 2 s poll) in front of the mock LLM (the `mock_llm` fixture from `e2e.conftest`); `BOR_LLM_BASE_URL` points at the proxy.
|
||||||
|
- **The fixture repo** (module-scoped, `tmp_path_factory`, real `git` subprocess — the `sync_git_repo` pattern): ~40 small A9-format `.md` files under a `notes/` folder (each one unique enough to import independently; ONE sentinel file — `Marker: RESE-CANCEL-SENTINEL-4f1e` — the assertion target for the re-sync).
|
||||||
|
- **`_wait_sync_state(page, app_url, states, timeout_s)`** — the `test_sync_button._wait_sync_done` helper generalized to a set of terminal states (here `{"cancelled"}` and `{"success", "failed"}` for the re-sync).
|
||||||
|
2. Tests (Playwright Mapping Rule — each test names the behavior it pins):
|
||||||
|
- `test_anonymous_cancel_403` — anonymous: `POST /api/sync/cancel` → 403 (the admin-only surface, same as the other two endpoints); `#sync-cancel-btn` is never revealed (the whoami gate).
|
||||||
|
- `test_cancel_when_idle_409` — logged-in, no run in flight: `POST /api/sync/cancel` → 409 with the exact detail `no sync is running`; the Cancel button is hidden in the UI (boot + idle).
|
||||||
|
- `test_admin_cancel_lifecycle` — the owner's exact flow:
|
||||||
|
1. login (lands on `/sources.html`);
|
||||||
|
2. click `#sync-btn` → `#sync-label` "Syncing…", the main button disabled, **`#sync-cancel-btn` visible + enabled** (within the 2 s poll tick — the running state is already entered synchronously by the 202);
|
||||||
|
3. confirm via the status endpoint that the run is `running` (the deterministic layer — `page.request` poll at ~100 ms, the `slow_llm` module's convention);
|
||||||
|
4. click `#sync-cancel-btn` → the cancel button disables immediately (never stale);
|
||||||
|
5. `_wait_sync_state(…, {"cancelled"})` → the status endpoint reports `state == "cancelled"` with `error is None`;
|
||||||
|
6. the UI settles (timeout-bound): main button ENABLED + label "Sync sources", `#sync-cancel-btn` hidden, `#sync-result` text "Sync cancelled", the error banner hidden, no error modal in the DOM;
|
||||||
|
7. **the re-sync is clean:** click `#sync-btn` again → "Synced HH:MM" (the `SYNCED_LABEL` regex) + `#sync-result` includes "40 added" (or the fixture's file count — the first FULL pass; the cancelled run's partial import is idempotent under the hash delta — assert the sentinel row is present in the catalog via the drill-down tree, the `_expect_fixture_row` pattern) → the cancel never corrupted the KB.
|
||||||
|
- Wall-time guard: the whole module < 120 s (40 files × 0.3 s proxy delay + the re-sync's 40 × 0.3 s — if it drifts, cut the file count, not the guard).
|
||||||
|
3. Header docstring: the story ("the owner's TODO item, L3"), the run command (`uv run pytest tests/e2e/test_sync_cancel.py -v --no-cov`), the isolation note (per-module app, dedicated port — the combined-run convention), the slow-LLM provenance (the proxy is the only thing that makes the cancel window deterministic).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite; it runs in ISOLATION (`--no-cov`, the AGENTS.md rule 9 gate) with the DB up (`podman compose up -d db`) and git on PATH.
|
||||||
|
- Coverage: **>90%** on new/modified code (test-only task — the bar is carried by the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_cancel.py -v --no-cov` green in isolation
|
||||||
|
- [ ] the cancel window is deterministic (the test does not race the 2 s poll — the `slow_llm` delay is the gate; a rerun on a quiet machine passes)
|
||||||
|
- [ ] the re-sync after a cancel imports the FULL fixture (the sentinel row present — a partial cancel never leaves a corrupted or permanently-incomplete KB)
|
||||||
|
- [ ] the `cancelled` state's `error` is null end to end (the UI can never render it as a failure)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Phase 135 — A git source can pin the branch it mirrors
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L4 — "Need to be able to specify the branch for a git source"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/models.py::GitSource` (id, url, kind, path, ignore_paths, include_hidden, token, added_at — no branch column; the phase-121 `token` column is the nullable-write-only precedent); `alembic/versions/` (0023 is the newest; every migration is reversible — the house rule); `app/schemas.py` — `GitSourceIn` / `GitSourceOut` / `GitSourceRow` / `GitSourcePatchIn` (the token field is the write-trimmed precedent; the output shapes use `extra="forbid"`); `app/api/git_sources.py` — `POST` (the `_create_git_row` / `_create_local_row` split, the fixed-detail 422s, the token normalization), `PATCH /{source_id}` (the per-field present-wins tri-state — the token's absent/None = no change, `""` = clear, non-empty = replace), `GET` (DB rows vs the env-fallback synthetic rows); `scripts/git_sync.py::clone_or_pull(url, dest)` (fresh clone with full history; the shallow probe + one-time `git fetch --unshallow` self-heal (phase 107 D11); `git pull --ff-only` — the fail-loud D12 contract); the TWO call sites that resolve effective sources and clone git rows: `app/api/sync.py::_run_sync` and `scripts/import_docs.py::_resolve_sources` (both already pass `clone_url_for(row)` + `repo_name(row.url)`); `file_commit_dates` (walks the checkout — untouched); the UI: `frontend/index.html` — the add form `#git-source-form` (the url + token inputs) and the per-row editor dialog `#ignore-editor-dialog` (the source line, the ignore textarea, the token field); `frontend/assets/git-sources.js` — `loadSources` / `makeRow` (the "hidden on" text-tag idiom in the source cell), `wireAddForm` (`opts.body(value, token)` builds the POST body), the dialog open/save handlers (the PATCH body builder), the `toggleHidden` never-stale lifecycle as the per-row control precedent.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A git source can specify the branch it mirrors: the owner gives a branch when adding a git source (or edits it per-row later), the clone/pull honors it (a fresh clone checks the branch out; an existing checkout tracks it), BOTH entry points — the Sync button and the `import_docs` CLI — honor it, and every row without a branch (all existing rows + the env-fallback rows) behaves byte-identically to today (default branch, `git pull --ff-only`).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `134_sync_cancel` (todo) — pipeline order only; no code dependency (independent surfaces).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The column** (ASSUMPTION B1): `git_sources.branch` — `TEXT NULL`, server default NULL; alembic **0024** (reversible — `add_column` / `drop_column`, no data migration: NULL = "the repo's default branch", so every existing row is unchanged by definition). `GitSource.branch: Mapped[str | None] = mapped_column(Text, nullable=True)`.
|
||||||
|
- **Validation** (ASSUMPTION B2): a pure helper `validate_branch_name(raw: str) -> str` in `app/rag/git_sources.py` (next to `normalize_credential` — the write-path helper home; the API layer maps its `ValueError` to the fixed-detail 422). Contract: trim → reject empty; reject length > 200; reject anything not matching `^[A-Za-z0-9._/-]+$` (alphanumerics + dot, underscore, hyphen, slash — whitespace/`@`/`~`/`^`/`:`/`?`/`*`/`[`/backslash are all out); reject a name containing `..` or `//`; reject a leading `-`, `.`, or `/`; reject a trailing `/` or `.`; reject `HEAD` (case-insensitive — git's refname; a branch literally named `head` is a documented cost of the simple rule). Returns the trimmed value. The API's 422 detail is the FIXED string `not a valid branch name` (never echoes the input — the house credential-safety discipline, applied for consistency).
|
||||||
|
- **The write paths** (ASSUMPTION B3): `GitSourceIn.branch: str | None` (optional at create — absent/empty → NULL; trimmed in the schema before the length constraint, the `_trim_url` precedent). `GitSourcePatchIn.branch: str | None = None` — TRI-STATE exactly like the token: absent/None = no change; `""` = clear (stored NULL); non-empty = set (re-validated). A `branch` on a LOCAL row (POST or PATCH) → 422 fixed detail `branch is only valid for git sources` (local rows are walked, not cloned). `GitSourceOut.branch: str | None` + `GitSourceRow.branch: str | None` (env-fallback synthetic rows report `None` — no DB row to store one on, the `ignore_paths: []` precedent).
|
||||||
|
- **`clone_or_pull(url, dest, branch: str | None = None)`** (ASSUMPTION B4): `branch=None` → the EXISTING code path byte-identical (same argv: clone without `--branch`; probe; unshallow-if-shallow; `git pull --ff-only`). A fresh clone with a branch → `git clone --branch <b> url dest`. An existing checkout with a branch → (1) the HEAD GUARD first: `git rev-parse --abbrev-ref HEAD` — if the result is not `<b>` → `GitSyncError("checkout <dest> is on branch '<current>' but the source specifies branch '<b>' — remove and re-add the source to switch branches")` (ASSUMPTION B5 — fail loud, the D12 convention; NO silent checkout switch in this phase: the checkout may serve other rows' documents, and a switch would silently re-map the source's file set; phase 136's explicit-ref reset makes the ref unambiguous later without changing this guard); (2) the shallow probe + one-time unshallow (unchanged); (3) `git fetch origin <b>`; (4) `git merge --ff-only FETCH_HEAD` (the single-fetch ff pull — the sequence phase 136 extends with its reset fallback).
|
||||||
|
- **Wiring:** both call sites pass `row.branch` — `app/api/sync.py::_run_sync` and `scripts/import_docs.py::_resolve_sources`: `clone_or_pull(clone_url_for(row), sources_root / repo_name(row.url), row.branch)`. Env-fallback synthetic rows carry `branch=None` (the `GitSource(url=…, kind="git")` constructor default). `file_commit_dates`, the checkout naming (`repo_name` stays on the BARE url), and the ignore/hidden/date maps are untouched.
|
||||||
|
- **The UI** (ASSUMPTION B6): the add form gains an optional `#git-source-branch` text input (maxlength 200, `autocomplete="off"`, hint "optional — default: the repo's default branch") between the URL and Token fields; the submit body becomes `(url, token, branch) => ({ url, ...(branch ? { branch } : {}), ...(token ? { token } : {}) })` — a blank branch OMITS the key (NULL). The per-row editor dialog gains a `#ignore-editor-branch` field (visible for GIT rows only — local rows' dialogs hide it; it opens prefilled from `s.branch ?? ""`; the PATCH body for a git row ALWAYS includes `branch: <trimmed value>` — empty = the tri-state's clear leg, so clearing a branch is a deliberate empty save, unlike the token's blank = keep). Every STORED git row with a branch shows a `branch: <name>` text tag in the source cell (the "hidden on" tag idiom — text + background, WCAG: the text IS the signal, never color alone).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_branch_column.md` — the alembic 0024 migration, the `GitSource.branch` column, the schema fields, the migration round-trip test.
|
||||||
|
2. `02_branch_api.md` — `validate_branch_name` + POST/PATCH/GET wiring (the tri-state, the local-row 422, the env rows).
|
||||||
|
3. `03_clone_pull_branch.md` — `clone_or_pull(…, branch)` (the `--branch` clone, the HEAD guard, the fetch+ff sequence) + both call sites.
|
||||||
|
4. `04_branch_ui.md` — the add-form field, the per-row editor field, the row tag.
|
||||||
|
5. `05_e2e_git_source_branch.md` — the dedicated Playwright E2E (the two-branch `file://` fixture, the UI add-with-branch → sync → branch content, the fail-loud mismatch, the API contracts).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `validate_branch_name` (the full accept/reject matrix); `clone_or_pull`'s argv sequences with mocked `subprocess` (the `tests/unit/test_git_sync.py` pattern — fresh-clone `--branch`, the existing-checkout guard → probe → fetch → merge, the mismatch raise, `branch=None` byte-identical).
|
||||||
|
- Integration: the migration round-trip (0024); the API round-trips (create/patch/list, the tri-state, the 422s); a real `file://` two-branch clone through `clone_or_pull` (the `tests/integration/test_import_docs_git.py` pattern) + the sync pipeline importing the branch's content.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a git source added with a branch mirrors THAT branch (fresh clone + subsequent pulls) through both the Sync button and the CLI — pinned by the E2E + the integration test
|
||||||
|
- [ ] a row with no branch (all existing rows + env rows) behaves byte-identically to pre-phase (the `branch=None` argv pin is green)
|
||||||
|
- [ ] invalid branch names are rejected with the fixed 422 (never echoing input); a branch on a local row is a 422; the PATCH tri-state (set/change/clear) round-trips
|
||||||
|
- [ ] setting a branch on an existing checkout on a different branch fails the sync LOUDLY with the remove-and-re-add message (no silent switch)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_git_source_branch.py -v --no-cov` green in isolation
|
||||||
|
- [ ] no behavior change in completed phases (the token/ignore/hidden round-trips, the sync pipeline, the CLI — all existing tests green untouched)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Task 01 — The `git_sources.branch` column: migration 0024, the model field, the schema fields
|
||||||
|
|
||||||
|
**Phase:** `135_git_source_branch` · **Source:** `TODO.md:4` — "Need to be able to specify the branch for a git source"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The registry can store a per-source branch: a reversible alembic 0024 adds the nullable `branch` column, the ORM model carries it, and the four API schema shapes report/accept it — with NULL meaning "the repo's default branch" so every existing row is unchanged.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `alembic/versions/0024_git_source_branch.py` (new) — follow the shape of `0021_git_source_token.py` (read it first):
|
||||||
|
- `revision = "0024"`, `down_revision = "0023"` (verify the actual latest revision id in `alembic/versions/` at execution time — the file numbering is the convention, the `down_revision` chain is the truth).
|
||||||
|
- `upgrade`: `op.add_column("git_sources", sa.Column("branch", sa.Text(), nullable=True))`.
|
||||||
|
- `downgrade`: `op.drop_column("git_sources", "branch")` (reversible — the house rule; NULL = default branch means no data migration in either direction).
|
||||||
|
2. `app/models.py::GitSource` — add:
|
||||||
|
```python
|
||||||
|
#: The branch to mirror (phase 135): NULL = the repo's default branch
|
||||||
|
#: (every pre-phase-135 row and every env-fallback row — byte-identical
|
||||||
|
#: clone/pull behavior). A non-NULL value is validated at the API
|
||||||
|
#: boundary (app.rag.git_sources.validate_branch_name) — the column
|
||||||
|
#: itself is plain Text.
|
||||||
|
branch: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
```
|
||||||
|
3. `app/schemas.py` (the four shapes — each docstring gains its phase-135 paragraph):
|
||||||
|
- `GitSourceIn.branch: str | None = Field(default=None, max_length=200)` — optional at create (absent → NULL); a `field_validator` trims before the length constraint runs (the `_trim_url` precedent) — note the API layer treats a trimmed-EMPTY value as absent at create and as the tri-state's clear leg at PATCH (document that split in the docstring).
|
||||||
|
- `GitSourceOut.branch: str | None` — the stored value (NULL → null in the response); the shape keeps `extra="forbid"` (no new omission risk — the field is explicit).
|
||||||
|
- `GitSourceRow.branch: str | None` — DB rows report the stored value; env-fallback synthetic rows report `None` (the `ignore_paths: []` / `include_hidden: False` precedent — no DB row to store one on).
|
||||||
|
- `GitSourcePatchIn.branch: str | None = None` — the tri-state (absent/None = no change; `""` = clear; non-empty = set — the token's precedent, documented in the docstring).
|
||||||
|
4. `uv run alembic upgrade head` against the dev DB (and `downgrade -1` + `upgrade head` once — the reversibility proof).
|
||||||
|
5. `tests/integration/test_migration_0024.py` (new — the `test_migration_0021.py` pattern): the upgrade adds the nullable column to a table WITH pre-existing rows (all report NULL — the byte-identical guarantee), a row can take a branch value, the downgrade drops the column.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Integration: the migration round-trip (the suite above).
|
||||||
|
- Coverage: **>90%** on new/modified code (the model/schema surface is exercised by task 02's API tests — this task's own gate is the migration test + the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run alembic upgrade head && uv run alembic downgrade -1 && uv run alembic upgrade head` succeeds on a scratch DB (the reversibility proof)
|
||||||
|
- [ ] pre-existing rows read `branch: None` (the integration test asserts on seeded rows — no backfill, no default)
|
||||||
|
- [ ] `uv run pytest tests/integration/test_migration_0024.py -v` green
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Task 02 — API: branch validation, POST/PATCH/GET wiring (the tri-state, the local-row 422, the env rows)
|
||||||
|
|
||||||
|
**Phase:** `135_git_source_branch` · **Source:** `TODO.md:4` — "Need to be able to specify the branch for a git source"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The admin API accepts, validates, stores, and reports a branch per git source: a pure `validate_branch_name` helper is the single choke point, POST stores it (git rows only), PATCH edits it with the token's tri-state, and GET/POST-201/PATCH-200 report it — invalid names get a fixed-detail 422 that never echoes the input.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/git_sources.py` — the pure validator (next to `normalize_credential`; no DB, no logging of the raw value beyond the fixed reason):
|
||||||
|
```python
|
||||||
|
_BRANCH_RE = re.compile(r"^[A-Za-z0-9._/-]+$")
|
||||||
|
|
||||||
|
def validate_branch_name(raw: str) -> str:
|
||||||
|
"""Trim + validate a branch name (phase 135, ASSUMPTION B2).
|
||||||
|
|
||||||
|
Returns the trimmed name; raises ValueError (fixed reason strings,
|
||||||
|
for logs only — the API maps to the fixed-detail 422) when the
|
||||||
|
name is empty, > 200 chars, outside the safe charset
|
||||||
|
([A-Za-z0-9._/-]+), contains ".." or "//", starts with "-"/"."/"",
|
||||||
|
ends with "/" or ".", or is HEAD (case-insensitive).
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
(The leading-slash check is `startswith("/")`; write the helper with the checks in this order: trim → empty → length → charset → `..`/`//` → leading → trailing → HEAD.)
|
||||||
|
2. `app/api/git_sources.py`:
|
||||||
|
- `_create_git_row`: after the URL contract (and the token normalization — order: URL shape → credential normalization → duplicate check → branch): `branch = (payload.branch or "").strip()`; if `branch`: `validate_branch_name` → store; else store `None`. A `ValueError` → `HTTPException(422, detail="not a valid branch name")` (FIXED detail — the input is never echoed).
|
||||||
|
- `_create_local_row`: `payload.branch` present and non-empty after strip → `HTTPException(422, detail="branch is only valid for git sources")` (local rows are walked, not cloned — the fixed detail, the kind-field rules' precedent).
|
||||||
|
- `patch_git_source`: a new independent present-wins field — `if payload.branch is not None:` the row must be `kind == "git"` (local → the same fixed 422); `""` → `row.branch = None` (the tri-state's clear leg); non-empty → `validate_branch_name` → set. No Integrity interaction (branch never touches a unique index) — no 409 path. Update the docstring's field list (ignore_paths / include_hidden / token / branch).
|
||||||
|
- `list_git_sources`: DB rows report `branch=row.branch`; env-fallback rows report `branch=None`. Update the docstring.
|
||||||
|
- `create_git_source` / `patch_git_source` responses: include `branch=row.branch` in the `GitSourceOut` construction.
|
||||||
|
- The module docstring's route summary gains the branch clauses (the house one-paragraph-per-route contract).
|
||||||
|
3. Unit tests — `tests/unit/test_git_sources_branch.py` (new; the validator has no existing home):
|
||||||
|
- Accept: `main`, `release/1.2`, `feature_x`, `a.b/c`, `v2-rc.1` (trim applied: `" main "` → `main`).
|
||||||
|
- Reject (each → `ValueError`): `""`, `" "`, 201 chars, `a b`, `a@b`, `a~b`, `a:b`, `a?b`, `a*b`, `a[b`, `a\b`, `a..b`, `a//b`, `-x`, `.x`, `/x`, `x/`, `x.`, `HEAD`, `head`, `HeAd`.
|
||||||
|
4. Integration tests — `tests/integration/test_git_sources_api.py` (extend — the file already owns this router's contract):
|
||||||
|
- POST a git source with `branch: "release"` → 201 reports `branch: "release"`; GET reports it.
|
||||||
|
- POST with an invalid branch (`"a..b"`) → 422 `not a valid branch name` (the detail is EXACT — no input echo); the row is not created.
|
||||||
|
- POST a LOCAL source with a branch → 422 `branch is only valid for git sources`.
|
||||||
|
- PATCH the tri-state: set (`"hotfix/x"`) → 200 reports it; change (`"hotfix/y"`); clear (`""`) → 200 reports `null`; absent (PATCH `{"include_hidden": true}` only) → the branch is untouched.
|
||||||
|
- PATCH a local row's branch → 422.
|
||||||
|
- Env-fallback rows (empty table + `BOR_GIT_SOURCES` env): GET reports `branch: null` for every synthetic row.
|
||||||
|
- The existing token/ignore/hidden round-trips stay green (no regression).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the validator matrix (step 3).
|
||||||
|
- Integration: the API round-trips (step 4).
|
||||||
|
- Coverage: **>90%** on new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_git_sources_branch.py tests/integration/test_git_sources_api.py -v` green
|
||||||
|
- [ ] every 422 detail is a fixed string (a grep of the new code shows no f-string echoing the branch input)
|
||||||
|
- [ ] the tri-state matches the token's semantics field-for-field (the PATCH docstring documents both)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Task 03 — `clone_or_pull(…, branch)` and both call sites (sync pipeline + CLI)
|
||||||
|
|
||||||
|
**Phase:** `135_git_source_branch` · **Source:** `TODO.md:4` — "Need to be able to specify the branch for a git source"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The git plumbing honors a row's branch: a fresh clone checks it out (`--branch`), an existing checkout is tracked (fetch + ff-merge of that ref) with a fail-loud guard when the checkout is on a different branch, and `branch=None` keeps the pre-phase argv byte-identical — wired through BOTH entry points (the Sync button and the `import_docs` CLI).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `scripts/git_sync.py::clone_or_pull` — the new optional parameter (the module docstring's clone/pull paragraph + the function docstring gain the branch contract):
|
||||||
|
```python
|
||||||
|
def clone_or_pull(url: str, dest: Path | str, branch: str | None = None) -> Path:
|
||||||
|
```
|
||||||
|
- **`branch is None`** — the EXISTING code path, byte-identical: clone without `--branch`; `rev-parse --is-shallow-repository` probe; `fetch --unshallow` while shallow; `git pull --ff-only`. (The argv pin in the unit tests is the proof.)
|
||||||
|
- **Fresh clone + branch** (`dest` absent or no `.git`): `git clone --branch <b> url dest`.
|
||||||
|
- **Existing checkout + branch**, in order:
|
||||||
|
1. HEAD GUARD: `git rev-parse --abbrev-ref HEAD` → let `current` be the result. If `current != branch` → `GitSyncError(f"checkout {dest} is on branch '{current}' but the source specifies branch '{branch}' — remove and re-add the source to switch branches")` (ASSUMPTION B5 — fail loud per D12; the message names the checkout and both branch names — no URL, so no credential exposure).
|
||||||
|
2. the shallow probe + one-time `git fetch --unshallow` self-heal (UNCHANGED from today — the phase-107 D11 contract).
|
||||||
|
3. `git fetch origin <b>` → `git merge --ff-only FETCH_HEAD` (the single-fetch ff pull of the specified ref — the sequence phase 136 extends with its reset fallback; a non-ff merge still fails loud HERE — the force-push fix is phase 136, not this one).
|
||||||
|
- All commands go through `run_git` (the A11 single invocation site — unchanged).
|
||||||
|
2. The call sites — pass `row.branch`:
|
||||||
|
- `app/api/sync.py::_run_sync` (the per-source loop, the `kind == "git"` arm): `root = clone_or_pull(clone_url_for(row), sources_root / repo_name(row.url), row.branch)`.
|
||||||
|
- `scripts/import_docs.py::_resolve_sources` (the same shape): `root = clone_or_pull(clone_url_for(row), sources_root / repo_name(row.url), row.branch)`.
|
||||||
|
- Both files' docstrings/comments name the branch argument (the phase-106/121 comment style). Env-fallback synthetic rows carry `branch=None` (the `GitSource(url=…, kind="git")` constructor — no argument needed, the model default is None — verified by the env-fallback integration path).
|
||||||
|
- `file_commit_dates(root)` is untouched (it walks whatever the checkout holds — for a branch checkout that is the branch's tree, exactly the head-of-branch semantics the owner asked for).
|
||||||
|
3. Unit tests — `tests/unit/test_git_sync.py` (extend — the mocked-`subprocess` argv pattern the file already uses):
|
||||||
|
- `branch=None` fresh + existing: the argv sequence is byte-identical to the pre-phase expectations (the existing tests stay green + add an explicit argv-equality pin if the file doesn't already pin it).
|
||||||
|
- Fresh clone + `branch="release"`: `["git", "clone", "--branch", "release", url, dest]`.
|
||||||
|
- Existing + matching HEAD (`rev-parse --abbrev-ref HEAD` → `"release"`): the sequence `rev-parse --abbrev-ref HEAD` → `rev-parse --is-shallow-repository` → (`fetch --unshallow` when the probe says shallow) → `fetch origin release` → `merge --ff-only FETCH_HEAD`.
|
||||||
|
- Existing + mismatched HEAD (`"main"` vs `branch="release"`): raises `GitSyncError` whose message contains both branch names and the checkout path — and NO fetch/merge argv was invoked (the guard is first).
|
||||||
|
- The mismatch message never contains the URL (credential-safety — even for a plain URL the message is URL-free).
|
||||||
|
4. Integration tests — `tests/integration/test_import_docs_git.py` (extend — the real-`git`-`file://` pattern the file already uses):
|
||||||
|
- Build a two-branch fixture repo (real git: `main` with file A, `release` with file B — different content per branch).
|
||||||
|
- `clone_or_pull(url, dest, "release")` fresh → the checkout's HEAD branch is `release` and file B is present (file A absent).
|
||||||
|
- A second `clone_or_pull` after the origin gains a commit on `release` → ff-merged (file B updated, no error).
|
||||||
|
- The mismatch case: clone fresh with no branch (HEAD = `main`), then `clone_or_pull(url, dest, "release")` → `GitSyncError` (the remove-and-re-add message), the checkout untouched (still on `main`).
|
||||||
|
- The full sync pipeline with a branch row: a `git_sources` row (`kind="git"`, `branch="release"`) → `_run_sync`'s source resolution imports file B (the `tests/integration/test_sync_api.py` fixture shape) — or at minimum `_resolve_sources`-level for the CLI path (follow whichever seam the file already exercises; the E2E, task 05, pins the button path end to end).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the argv matrix (step 3) — the `branch=None` byte-identical pin is the regression gate for every existing deployment.
|
||||||
|
- Integration: the real-git two-branch scenarios (step 4).
|
||||||
|
- Coverage: **>90%** on new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_git_sync.py tests/integration/test_import_docs_git.py -v` green
|
||||||
|
- [ ] `branch=None` produces the exact pre-phase argv (the pin is in the suite — a future refactor that rewrites the default path breaks it)
|
||||||
|
- [ ] the mismatch fails loud BEFORE any fetch (the unit test asserts no fetch argv after the guard)
|
||||||
|
- [ ] both entry points pass `row.branch` (a grep of the two call sites + the integration test covering each)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Task 04 — UI: the add-form field, the per-row editor field, and the row tag
|
||||||
|
|
||||||
|
**Phase:** `135_git_source_branch` · **Source:** `TODO.md:4` — "Need to be able to specify the branch for a git source"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The Sources manager (git-sources view) lets the owner see, set, change, and clear a source's branch: an optional Branch input in the add form, a Branch field in the per-row editor dialog (git rows only, prefilled, empty-save = clear), and a `branch: <name>` text tag on every stored git row that has one — all on the §7.4 never-stale lifecycle.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/index.html` (the `#view-git-sources` section):
|
||||||
|
- **The add form** (`#git-source-form`) — between the URL field and the Token field:
|
||||||
|
```html
|
||||||
|
<label for="git-source-branch">Branch <span class="field-hint">optional — default: the repo's default branch</span></label>
|
||||||
|
<input id="git-source-branch" name="branch" type="text" maxlength="200" autocomplete="off" placeholder="main, release/1.2, …">
|
||||||
|
```
|
||||||
|
(The visible `<label for=…>` is the WCAG input-label rule, same as the url/token fields.)
|
||||||
|
- **The per-row editor dialog** (`#ignore-editor-dialog`) — after the source line, before the ignore textarea:
|
||||||
|
```html
|
||||||
|
<label for="ignore-editor-branch">Branch</label>
|
||||||
|
<input id="ignore-editor-branch" type="text" maxlength="200" autocomplete="off" placeholder="(default branch)">
|
||||||
|
<p class="ignore-editor-branch-hint">Leave empty for the repo's default branch.</p>
|
||||||
|
```
|
||||||
|
The hint uses the existing `.field-hint` / muted-copy idiom (match the token field's hint styling — no new CSS class unless the existing one doesn't fit).
|
||||||
|
2. `frontend/assets/git-sources.js`:
|
||||||
|
- **Element lookups:** `const branchInput = root.querySelector("#git-source-branch");` and `const ignoreBranchInput = root.querySelector("#ignore-editor-branch");` (next to the existing token lookups).
|
||||||
|
- **Add form:** thread the branch through `wireAddForm` — the opts object gains `branchInput`, and the git-kind body builder becomes `body: (url, token, branch) => ({ url, ...(branch ? { branch } : {}), ...(token ? { token } : {}) })` (a blank branch OMITS the key — the token's blank-omits precedent; the submit handler reads `branchInput.value.trim()` and clears it on 201 alongside the url/token — the credential-free inputs clear together).
|
||||||
|
- **Per-row editor dialog:**
|
||||||
|
- Open: for a git row (`s.kind === "git"`) — prefill `ignoreBranchInput.value = s.branch ?? ""` and show the field; for a local row — hide the field (label + input + hint) and the save body OMITS `branch` (local rows can't take one — the API's 422 is the backstop, the UI simply doesn't offer it).
|
||||||
|
- Save: the PATCH body for a git row ALWAYS includes `branch: ignoreBranchInput.value.trim()` (empty = the tri-state's clear leg — a deliberate empty save clears the branch, unlike the token's blank = keep; the docstring/section comment documents the asymmetry), composed with the existing `ignore_paths` + conditional `token` (the token stays the blank = keep tri-state — untouched).
|
||||||
|
- The never-stale lifecycle mirrors the existing save handler: the Save button disables in flight, 200 → close the dialog + `loadSources()` (the row re-renders from the server — the tag appears/disappears), failure → the dialog's error line (the existing pattern) + the inputs keep the user's text.
|
||||||
|
- **The row tag** (`makeRow` / the source-cell builder): when `s.id && s.branch` — append a text tag `branch: <name>` in the source cell, next to the existing "hidden on" tag (the SAME tag idiom: a span with the tag class — text + background, never color alone; the tag text is the signal). Env-fallback rows (no `s.id`) and NULL-branch rows show no tag. Update the source cell's `aria-label`/`title` to include the branch (the hover precision idiom).
|
||||||
|
- The module's section-header docstring gains the phase-135 paragraph (the house pattern — the field, the tri-state asymmetry, the tag rule).
|
||||||
|
3. No new API surface, no new fetches — the branch rides the existing POST/PATCH/GET payloads (task 02's shapes).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- No JS unit layer in this repo — the UI contract is pinned by the phase's E2E (task 05).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend-only task — the bar is carried by the suite run + the E2E).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] adding a git source with a branch sends `branch` (non-blank) / omits it (blank) — pinned by the E2E's request assertions
|
||||||
|
- [ ] the dialog prefills the stored branch; saving an empty value clears it (the row's tag disappears after `loadSources`); local rows' dialogs never show the field
|
||||||
|
- [ ] a stored git row with a branch shows the `branch: <name>` text tag (visible, text-based, in the source cell)
|
||||||
|
- [ ] the 360 px case renders (the form + dialog don't overflow — verified in the E2E's viewport assertions where applicable)
|
||||||
|
- [ ] no console errors on the view (the E2E pins it)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Task 05 — E2E: `tests/e2e/test_git_source_branch.py` (the dedicated Playwright suite, run in isolation)
|
||||||
|
|
||||||
|
**Phase:** `135_git_source_branch` · **Source:** `TODO.md:4` — "Need to be able to specify the branch for a git source"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The branch feature is pinned end to end against the REAL pipeline: a two-branch `file://` fixture repo, the owner adding a source WITH a branch through the UI (→ sync → the branch's content is indexed, not the default branch's), the row tag, the per-row editor's branch field (change + the fail-loud mismatch), and the API contracts (the tri-state, the fixed 422s, the local-row rejection).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_git_source_branch.py` (new) — the per-module app pattern (`test_git_sources_admin.py` + `test_sync_button.py` combined):
|
||||||
|
- **Ports/env:** `APP_PORT = int(os.environ.get("E2E_APP_PORT_GITBR", "8134"))`; the standard module env (`BOR_STATIC_DIR`, the mock LLM base URL, `BOR_RELEVANCE_THRESHOLD=0.30`, `BOR_ADMIN_PASSWORD` / `BOR_SESSION_SECRET`, a dedicated `BOR_SOURCES_DIR`). **No `BOR_GIT_SOURCES` env** — the sources under test are DB rows (the UI adds them), so the env fallback stays empty.
|
||||||
|
- **The fixture repo** (module-scoped, `tmp_path_factory`, real `git`): two branches — `main` (file `notes/main-only.md` with `Marker: RESE-BRANCH-MAIN-7a31`) and `release` (file `notes/release-only.md` with `Marker: RESE-BRANCH-REL-9c2d`, plus a shared `notes/common.md` whose content DIFFERS between the branches — `main` says `VERSION: 1`, `release` says `VERSION: 2`). Both branches pushed to the repo (a local bare-ish fixture: the test builds `main`, commits, then `git checkout -b release`, edits, commits — a normal two-branch repo; the app clones it via `file://`).
|
||||||
|
- **Helpers:** `add_git_source(page, url, branch=None, token=None)` (fills the UI form — the branch field when given), `sync_and_wait(page, app_url)` (clicks `#sync-btn` and polls the status endpoint to a terminal state — the `_wait_sync_done` pattern), `catalog_has_doc(page, doc_name)` (the drill-down tree assertion, the `_expect_fixture_row` pattern).
|
||||||
|
2. Tests:
|
||||||
|
- `test_add_with_branch_syncs_that_branch` — the owner's exact flow:
|
||||||
|
1. login (lands on the git-sources view — the `login` helper's `next` param or a nav click, per the existing suites);
|
||||||
|
2. add a source: url = `file://<fixture>`, branch = `release` → 201; the row appears with the `branch: release` tag (the text is in the source cell);
|
||||||
|
3. switch to the Sources/RAG view, `sync_and_wait` → `state == "success"`;
|
||||||
|
4. the catalog contains `release-only.md` (the branch's doc) AND `common.md` shows `VERSION: 2` (drill in and assert on the document's stored content via the document modal or the `GET /api/docs` row — follow the assertion idiom the dates suite uses for content checks); `main-only.md` is ABSENT (the default branch's doc was never indexed);
|
||||||
|
5. re-sync (idempotent): "0 added · 2 unchanged" (release's two files).
|
||||||
|
- `test_default_branch_source_unaffected` — a SECOND source row for the SAME url is impossible (the unique URL 409) — so this test uses a CLONE of the fixture (a second `file://` repo, identical history, `main` only): add it with NO branch → sync → `main-only.md` present, `release-only.md` absent (the `branch=None` path mirrors the pre-phase behavior — the byte-identical guarantee, observable through the UI).
|
||||||
|
- `test_row_editor_branch_change_fails_loud` — the fail-loud mismatch (ASSUMPTION B5, end to end):
|
||||||
|
1. take the `release` source from test 1's state (or a fresh module state — order the tests so the fixture state is explicit; the KB-truncate autouse fixture keeps them independent: re-add the source fresh);
|
||||||
|
2. open the per-row editor, change the branch field to `main`, save → the dialog closes, the row re-renders with the `branch: main` tag (the PATCH landed — the registry is updated);
|
||||||
|
3. sync → `state == "failed"`; the sanitized error banner/modal shows the fixed mismatch copy (assert on the user-visible fragment `remove and re-add the source` — the message is a fixed string, safe to pin);
|
||||||
|
4. restore: editor → branch field `release` → save → sync → success again (the guard is symmetric — back to the matching branch, the ff path works).
|
||||||
|
- `test_api_branch_contracts` — the API layer through `page.request` (admin cookie):
|
||||||
|
- POST a git source with `branch: "a..b"` → 422, detail EXACTLY `not a valid branch name` (no echo); the list is unchanged;
|
||||||
|
- POST a git source with `branch: "HEAD"` → 422 (same detail);
|
||||||
|
- PATCH the tri-state on a stored row: set `hotfix/x` → 200 reports it; clear with `""` → 200 reports `null`; a PATCH of `{"include_hidden": true}` leaves the branch untouched;
|
||||||
|
- POST a LOCAL source (an existing tmp dir) with `branch: "x"` → 422 `branch is only valid for git sources`;
|
||||||
|
- the token field is unaffected by all of the above (the existing token tests stay green — no regression pin needed here).
|
||||||
|
- Wall-time guard: the whole module < 180 s (three full syncs of a 3-file repo against the mock LLM — the `slow_llm` proxy is NOT needed: the branch assertions are about WHICH files land, not about a running window).
|
||||||
|
3. Header docstring: the story (the TODO item, L4), the run command (`uv run pytest tests/e2e/test_git_source_branch.py -v --no-cov`), the isolation note (per-module app, dedicated port, DB rows not env), the fixture's two-branch shape.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite; it runs in ISOLATION (`--no-cov`, the AGENTS.md rule 9 gate) with the DB up (`podman compose up -d db`) and git on PATH.
|
||||||
|
- Coverage: **>90%** on new/modified code (test-only task — the bar is carried by the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_git_source_branch.py -v --no-cov` green in isolation
|
||||||
|
- [ ] the branch's content is what gets indexed (the sentinel docs on the right branch present, the wrong branch's doc absent — the feature's core promise)
|
||||||
|
- [ ] the `branch=None` path imports the default branch exactly as pre-phase (the unaffected-source test)
|
||||||
|
- [ ] the mismatch is LOUD (the failed sync names the remove-and-re-add fix — the owner is never left with a silently-wrong checkout)
|
||||||
|
- [ ] every 422 detail is the fixed string (the test asserts on the exact detail, not a substring of the input)
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Phase 136 — A force push no longer breaks the sync: the checkout resets to the head of the tracked branch
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L5 — "Force pushes break brain of reese git pull. Brain of reese should always have the head of the branch specified, so if pull fails due to force pushes it should just reset origin/<branch>"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `scripts/git_sync.py::clone_or_pull` — today's existing-checkout path: the shallow probe + one-time `git fetch --unshallow` self-heal (phase 107 D11), then `git pull --ff-only` — a force push is a NON-fast-forward, so `--ff-only` refuses → `GitSyncError` → the whole sync lands `failed` (the owner's reported break; this is the bug). Phase 135 (the immediately preceding todo phase) lands the `branch` parameter: for a branched row the sequence is already `git fetch origin <b>` + `git merge --ff-only FETCH_HEAD` behind the HEAD guard; for a `NULL`-branch row it is still the legacy `git pull --ff-only`. `run_git` is the A11 single git invocation site; the two call sites (`app/api/sync.py::_run_sync`, `scripts/import_docs.py::_resolve_sources`) are untouched in shape — `clone_or_pull`'s signature is theirs to satisfy; `file_commit_dates` walks the post-update checkout (a reset checkout yields the NEW head's per-file dates — exactly the head-of-branch semantics the owner asked for). The sync's failure path (`_run_sync`'s `except Exception` → the `failed` state + the sanitized error) is what a force push hits today — after this phase it no longer does.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A force push (or any divergent remote head) never fails the sync: the existing-checkout update tries the fast-forward and, when that is impossible, **resets the checkout to the remote head of the tracked ref** — for a branched row `origin/<branch>` (the owner's verbatim "reset origin/<branch>"), for a `NULL`-branch row the head of the branch the checkout is on — with one loud log line. The checkout is a cache of the remote head (the app owns it, the KB is rebuilt from it on the same run), so "always the head of the branch" is the invariant this phase enforces.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `135_git_source_branch` (todo) — the `branch` parameter of `clone_or_pull` (the reset's target ref for branched rows) and the phase-135 HEAD guard, which stays in front of the update sequence.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The existing-checkout update sequence** (replaces BOTH today's `git pull --ff-only` path and phase 135's branch path — one unified sequence):
|
||||||
|
1. ref resolution: `branch` given → `ref = branch` (the HEAD guard from phase 135 runs FIRST, unchanged: checkout on a different branch → the remove-and-re-add `GitSyncError`); `branch` None → `ref = git rev-parse --abbrev-ref HEAD` (the checkout's own branch — the pre-phase default-branch behavior; if the result is `"HEAD"` (detached) → `GitSyncError` naming the checkout: the app never CREATES a detached checkout — a fresh clone always lands on a branch — so this is a genuinely broken checkout and fails loud per D12, not a force-push case).
|
||||||
|
2. the shallow probe + one-time `git fetch --unshallow` self-heal (UNCHANGED — phase 107 D11).
|
||||||
|
3. `git fetch origin <ref>` — a fetch FAILURE (network/auth, the branch gone from the remote, git missing) STILL raises `GitSyncError` (a loud failure — a force push is NOT a fetch failure; the owner's "if pull fails due to force pushes" scopes the reset to the merge step only).
|
||||||
|
4. try `git merge --ff-only FETCH_HEAD`.
|
||||||
|
5. **on merge failure — the reset fallback (this phase, ASSUMPTION C1):** capture `old = git rev-parse HEAD` and `new = git rev-parse FETCH_HEAD`, run `git reset --hard FETCH_HEAD`, log one WARNING line (PLAN §9): `git sync: divergent remote head on <dest> (force push) — reset <old[:7]> → <new[:7]> to origin/<ref>`, and RETURN the dest normally (the sync proceeds — a force push never fails a run). The merge's stderr is included in the log (diagnosability) but never in a user-facing error (there is no error — the run continues).
|
||||||
|
- **Unchanged:** the fresh-clone path (with and without `--branch`); the `run_git` discipline; the two call sites; `file_commit_dates`; the sync's status/progress surface. The `branch=None` argv CHANGES by design (the legacy `git pull --ff-only` becomes the explicit fetch + ff-or-reset sequence — that IS the fix, and it applies to every row, branched or not).
|
||||||
|
- **ASSUMPTION C2 — the dirty checkout:** the checkout is app-managed (a cache of the remote head; the KB is rebuilt from it by the same run's import), so local modifications are not expected and are not defended against: the `reset --hard` discards any by definition. No `git status` precheck (one fewer git call per source per sync; the house minimal-invocation discipline) — a dirty checkout simply resets, which is the desired end state either way.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_ff_or_reset.md` — the unified update sequence in `clone_or_pull` (ff-or-reset, the detached-HEAD fail-loud, the loud log) + the unit/integration matrix.
|
||||||
|
2. `02_e2e_force_push_resync.md` — the dedicated Playwright E2E (a real force push of the fixture repo between two UI sync runs — the pre-phase behavior, a failed sync, is the regression pin).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the mocked-`subprocess` argv matrix in `tests/unit/test_git_sync.py` (ff success — no reset argv; ff failure — the rev-parse pair + `reset --hard FETCH_HEAD` + return, no raise; fetch failure — still raises; detached `NULL`-branch — raises; the phase-135 mismatch guard still fires before the update sequence).
|
||||||
|
- Integration: real-`git` `file://` scenarios in `tests/integration/test_import_docs_git.py` (normal ff; a force push — the origin's history rewritten; an UNRELATED-history force push — different root commit; a branched row's force push — the reset targets `origin/<branch>`; `file_commit_dates` on the post-reset checkout reflects the new head).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation (the owner's exact reproduction: sync → force push the origin → sync again → success + the new head's content).
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/` — the change lives in `scripts/`, exercised through the `app/` sync pipeline tests; the coverage bar is carried by the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a force push of a source's branch no longer fails the sync — the next sync succeeds and the checkout (and therefore the KB) holds the NEW head (pinned by the integration + E2E)
|
||||||
|
- [ ] an unrelated-history force push (a rewritten root) is handled by the same reset (the E2E or integration covers it — pick the integration, the E2E stays on the owner's exact repro)
|
||||||
|
- [ ] a genuinely broken fetch (git missing / unreachable origin / branch deleted upstream) STILL fails loud (the `GitSyncError` pins are green — the reset is scoped to the merge step only)
|
||||||
|
- [ ] the WARNING log line lands on a reset (one line, the SHAs, the checkout path, `origin/<ref>` — no URL in it)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_force_push_resync.py -v --no-cov` green in isolation
|
||||||
|
- [ ] the phase-135 behavior is preserved (the `--branch` clone, the mismatch guard, the `branch=None` fresh-clone argv — the pins from phase 135 stay green)
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# Task 01 — `clone_or_pull`: ff-or-reset (the force push no longer fails the sync)
|
||||||
|
|
||||||
|
**Phase:** `136_force_push_reset` · **Source:** `TODO.md:5` — "Force pushes break brain of reese git pull. Brain of reese should always have the head of the branch specified, so if pull fails due to force pushes it should just reset origin/<branch>"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The existing-checkout update becomes: fetch the tracked ref → try the fast-forward → on a non-ff failure, reset the checkout hard to that ref's head and continue — with one loud WARNING line. A force push is now a logged, self-healing event, never a failed sync; genuinely broken fetches still fail loud.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `scripts/git_sync.py::clone_or_pull` — replace the existing-checkout tail (today: probe → unshallow-if-shallow → `git pull --ff-only`; phase 135's branch tail: HEAD guard → probe → unshallow-if-shallow → `fetch origin <b>` → `merge --ff-only FETCH_HEAD`) with the unified sequence from the phase overview:
|
||||||
|
```python
|
||||||
|
# existing checkout (the fresh-clone path above is untouched):
|
||||||
|
if branch is not None:
|
||||||
|
# phase-135 HEAD guard, UNCHANGED (runs first, before any update):
|
||||||
|
current = run_git(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=dest).strip()
|
||||||
|
if current != branch:
|
||||||
|
raise GitSyncError(
|
||||||
|
f"checkout {dest} is on branch '{current}' but the source specifies "
|
||||||
|
f"branch '{branch}' — remove and re-add the source to switch branches"
|
||||||
|
)
|
||||||
|
ref = branch
|
||||||
|
else:
|
||||||
|
ref = run_git(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=dest).strip()
|
||||||
|
if ref == "HEAD": # detached — the app never creates one (D12 fail-loud)
|
||||||
|
raise GitSyncError(
|
||||||
|
f"checkout {dest} is in a detached-HEAD state — remove and re-add the "
|
||||||
|
f"source to rebuild it"
|
||||||
|
)
|
||||||
|
shallow = run_git(["git", "rev-parse", "--is-shallow-repository"], cwd=dest).strip() == "true"
|
||||||
|
if shallow:
|
||||||
|
run_git(["git", "fetch", "--unshallow"], cwd=dest)
|
||||||
|
run_git(["git", "fetch", "origin", ref], cwd=dest) # fetch failure STILL raises
|
||||||
|
try:
|
||||||
|
run_git(["git", "merge", "--ff-only", "FETCH_HEAD"], cwd=dest)
|
||||||
|
except GitSyncError as ff:
|
||||||
|
old = run_git(["git", "rev-parse", "HEAD"], cwd=dest).strip()
|
||||||
|
new = run_git(["git", "rev-parse", "FETCH_HEAD"], cwd=dest).strip()
|
||||||
|
run_git(["git", "reset", "--hard", "FETCH_HEAD"], cwd=dest)
|
||||||
|
logger.warning(
|
||||||
|
"git sync: divergent remote head on %s (force push) — reset %s → %s to "
|
||||||
|
"origin/%s (%s)", dest, old[:7], new[:7], ref, ff,
|
||||||
|
)
|
||||||
|
return dest
|
||||||
|
```
|
||||||
|
Notes: the `branch=None` path deliberately LOSES the legacy `git pull --ff-only` (that is the fix — every row gets the ff-or-reset update); the `dest` in the log is the checkout path (NEVER the URL — credential-safety, the phase-121 discipline); the merge stderr rides the log only (the run continues — there is no user-facing error). Update the module + function docstrings (the D11/D12 paragraphs gain the phase-136 force-push contract: "a non-ff merge resets to the ref's head instead of failing — the checkout is a cache of the remote head").
|
||||||
|
2. Unit tests — `tests/unit/test_git_sync.py` (extend — the mocked-`subprocess` argv pattern; the mock needs per-argv responses: `rev-parse --abbrev-ref HEAD` → the branch, `rev-parse --is-shallow-repository` → `false`, the ff merge → non-zero on the failure case, the `rev-parse HEAD` / `FETCH_HEAD` → SHAs, the reset → zero):
|
||||||
|
- `branch=None`, ff SUCCESS: argv sequence `rev-parse --abbrev-ref HEAD` → `rev-parse --is-shallow-repository` → `fetch origin <branch-from-HEAD>` → `merge --ff-only FETCH_HEAD` — and NO `reset` argv, NO `rev-parse HEAD/FETCH_HEAD` pair (the capture is only on failure).
|
||||||
|
- `branch=None`, ff FAILURE (merge exit ≠ 0): the sequence gains `rev-parse HEAD` → `rev-parse FETCH_HEAD` → `reset --hard FETCH_HEAD` — and the function RETURNS the dest (no raise).
|
||||||
|
- `branch="release"` (matching HEAD), ff failure: same reset tail, `fetch origin release` — the reset targets the branch's ref (the owner's verbatim "reset origin/<branch>").
|
||||||
|
- the phase-135 mismatch (`branch="release"`, HEAD `main`): STILL raises before any fetch (the guard is first — the phase-135 pin stays green).
|
||||||
|
- `branch=None` + detached HEAD (`rev-parse --abbrev-ref HEAD` → `"HEAD"`): raises the detached `GitSyncError` (no fetch, no reset).
|
||||||
|
- fetch FAILURE (non-zero): raises `GitSyncError` (NOT the reset path — the reset is scoped to the merge step; a deleted upstream branch / dead network still fails loud).
|
||||||
|
- the shallow self-heal still fires in front of the fetch (the `--unshallow` argv pin, unchanged).
|
||||||
|
3. Integration tests — `tests/integration/test_import_docs_git.py` (extend — the real-`git` `file://` pattern):
|
||||||
|
- **Normal ff:** a fixture repo, `clone_or_pull` ×2 with a normal second commit → ff-merged, no reset (assert via `git -C dest log` — the second commit's message is the HEAD, no merge commit).
|
||||||
|
- **Force push (the owner's repro):** after the first clone, rewrite the origin's history (a NEW root commit — `git checkout --orphan` or `git reset --soft` + a fresh commit with different content — the origin's branch now diverges); `clone_or_pull` again → NO exception, the checkout's HEAD == the origin's new head (`git -C origin rev-parse <ref>` == `git -C dest rev-parse HEAD`), the working tree holds the NEW content.
|
||||||
|
- **Unrelated-history force push:** the rewritten origin has a DIFFERENT root commit (a fully unrelated tree) → the same reset path handles it (the ff merge of an unrelated history is exactly what `--ff-only` refuses).
|
||||||
|
- **Branched force push:** a two-branch fixture (the phase-135 shape), a row-shaped call `clone_or_pull(url, dest, "release")` after a force push of ONLY `release` → the reset lands `origin/release`'s head and `main`'s content is not involved.
|
||||||
|
- **`file_commit_dates` after a reset:** the dates map reflects the NEW head (the new root commit's date is what the walk returns for its files — the head-of-branch dates the owner asked for).
|
||||||
|
- **The sync pipeline end-to-end (the seam `tests/integration/test_sync_api.py` already exercises):** a forced-push fixture + a sync → `state == "success"` (the pre-phase code lands `failed` — this test is the regression pin at the API seam; if the file's existing fixtures make the seam awkward, the E2E, task 02, carries the API-seam pin and this step stays at the `clone_or_pull` level — document the choice in the test's docstring).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the argv matrix (step 2) — the ff-success pin (no reset argv) and the fetch-failure pin (still raises) are the two regression gates.
|
||||||
|
- Integration: the real-git matrix (step 3).
|
||||||
|
- Coverage: **>90%** on new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_git_sync.py tests/integration/test_import_docs_git.py -v` green
|
||||||
|
- [ ] a force push (normal divergence AND unrelated history) resets instead of failing — pinned by real-git integration tests
|
||||||
|
- [ ] the phase-135 pins (the mismatch guard, the `--branch` clone argv, the `branch=None` fresh-clone argv) stay green untouched
|
||||||
|
- [ ] the WARNING line is the ONLY observable side effect of a reset besides the checkout state (no user-facing error, no status change — the run continues)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Task 02 — E2E: `tests/e2e/test_force_push_resync.py` (the dedicated Playwright suite, run in isolation)
|
||||||
|
|
||||||
|
**Phase:** `136_force_push_reset` · **Source:** `TODO.md:5` — "Force pushes break brain of reese git pull. Brain of reese should always have the head of the branch specified, so if pull fails due to force pushes it should just reset origin/<branch>"
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The owner's exact reproduction is pinned end to end: sync (clone + import) → force-push the origin (its history rewritten) → sync again → SUCCESS, and the KB holds the NEW head's content. Pre-phase, that second sync landed `failed` — this test is the regression pin for the fix.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_force_push_resync.py` (new) — the `test_sync_button.py` module-app pattern:
|
||||||
|
- **Ports/env:** `APP_PORT = int(os.environ.get("E2E_APP_PORT_FPPUSH", "8135"))`; the standard module env (`BOR_STATIC_DIR`, the mock LLM, `BOR_RELEVANCE_THRESHOLD=0.30`, the admin/session secrets, `BOR_GIT_SOURCES=file://<fixture repo>`, a dedicated `BOR_SOURCES_DIR`).
|
||||||
|
- **The fixture repo** (module-scoped, `tmp_path_factory`, real `git` — the `sync_git_repo` pattern): `notes/doc.md` with `Marker: RESE-FPPUSH-V1-5e8a`, one commit, one branch.
|
||||||
|
- **The force-push helper:**
|
||||||
|
```python
|
||||||
|
def _force_push_new_head(repo: Path, content: str) -> None:
|
||||||
|
"""Rewrite the origin's history to a NEW root commit (a full
|
||||||
|
divergence — not just a new commit on top): delete the branch
|
||||||
|
ref and recreate it at a new orphan commit with `content`."""
|
||||||
|
```
|
||||||
|
(Implementation at execution time: `git checkout --orphan newroot` → replace `notes/doc.md`'s content → commit → `git branch -M <branch>` / `git push --force` is not applicable to a local fixture — the test rewrites the repo IN PLACE: `git update-ref -d <branch>`, commit on the orphan, `git update-ref <branch> HEAD`. The app's next `git fetch` sees the divergent head. The exact ref mechanics are the executor's call — the OBSERVABLE contract is: the origin's single branch now points at a commit with UNRELATED history and the new content.)
|
||||||
|
- **`_wait_sync_state`** — the `test_sync_button._wait_sync_done` pattern (terminal `{"success", "failed"}`), plus a UI-level settle wait on `#sync-label`.
|
||||||
|
2. Tests:
|
||||||
|
- `test_sync_survives_a_force_push` — the owner's exact flow:
|
||||||
|
1. login (lands on `/sources.html` — the button's home);
|
||||||
|
2. **run 1:** click `#sync-btn` → "Syncing…" → "Synced HH:MM" + "1 added"; the catalog shows `doc.md` (the drill-down assertion, the `_expect_fixture_row` pattern);
|
||||||
|
3. **the force push** (server-side, via the fixture helper — the test owns the origin repo): `_force_push_new_head(repo, "Marker: RESE-FPPUSH-V2-2b7f …")`;
|
||||||
|
4. **run 2:** click `#sync-btn` again → the status endpoint reaches `state == "success"` (NOT `failed` — the pre-phase regression: the `--ff-only` pull refused the divergent head and the run died) within the timeout; the UI settles to "Synced HH:MM" (the error banner is HIDDEN, no error modal);
|
||||||
|
5. **the KB holds the NEW head:** the document modal / `GET /api/docs` content for `notes/doc.md` contains `RESE-FPPUSH-V2-2b7f` (the reset's content flowed through the import — the digest delta re-indexed the file as `updated`; `#sync-result` shows "1 updated" or "0 added · 1 updated" — assert on the content, the counts are the secondary signal);
|
||||||
|
6. **run 3 (idempotent):** "0 added · 1 unchanged" (the checkout is stably at the new head — the reset was not a one-off fluke).
|
||||||
|
- `test_failed_pull_is_not_the_outcome` (the negative pin, cheap while the fixture exists): assert on the APP LOG or skip if the seam is awkward — PREFERRED: a direct API-level assertion instead — after the force push, `POST /api/sync` + poll → `state == "success"` (the same contract as run 2 without the UI; keeps the UI test focused). If the module app's fixture state makes two full UI+API passes heavy, fold it into the main test as step 4b (the API trigger of run 2) — document the choice in the docstring.
|
||||||
|
- Wall-time guard: the whole module < 120 s (three small syncs against the mock LLM — no `slow_llm` proxy needed: the point is the TERMINAL state, not a running window).
|
||||||
|
3. Header docstring: the story (the TODO item, L5 — the owner's verbatim repro), the run command (`uv run pytest tests/e2e/test_force_push_resync.py -v --no-cov`), the isolation note (per-module app, dedicated port), and the pre-phase behavior it pins against (run 2 used to land `failed` — the test fails on the pre-phase code, which is the point).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file IS the task's suite; it runs in ISOLATION (`--no-cov`, the AGENTS.md rule 9 gate) with the DB up (`podman compose up -d db`) and git on PATH.
|
||||||
|
- Coverage: **>90%** on new/modified code (test-only task — the bar is carried by the suite run).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_force_push_resync.py -v --no-cov` green in isolation
|
||||||
|
- [ ] the test FAILS on the pre-phase code (run 2 lands `failed` — verified by temporarily reverting the `clone_or_pull` change in a scratch branch, then restoring — the pin has teeth)
|
||||||
|
- [ ] the NEW head's content is what the KB serves (the sentinel V2 in the document — the reset's observable end-to-end effect)
|
||||||
|
- [ ] the third run is idempotent (the checkout is stably at the new head — no drift, no second reset)
|
||||||
|
- [ ] no error banner / modal on a force-push resync (a reset is a logged event, not a user-facing failure)
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Phase 137 — PDF-embedded images always carry the document context in their summary
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Images extracted from PDFs still don't have any relevant context in their summaries provided by the PDF. They're still just getting summarized 'as-is'. … Image summaries should always include the document context if the images come from a document (this includes markdown files) so the embedder can more effectively retrieve image sources."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/pdf.py` (phase 126 — `extract_pdf_text` (L87, per-page `get_text("text")` with `---PAGE-N---` separators, fail-soft `""`), `extract_pdf_images` (L145, one `PdfImage` per occurrence: `page` 1-indexed, `index` 0-based, `data`, `mime`)); `app/rag/importer.py` — `_index_pdf_embedded_images` (L1091, the per-PDF embedded-image pass after its document commit), `_index_one_embedded_image` (L1182, the phase-122 pipeline inline: mime gate → synthetic path `<pdf>#page=N#img=I.<ext>` → byte-digest skip → `_markdown_image_context` (L1403, the phase-125 reference scan) → `_describe_or_skip` (L1742, the single describe seam) → copy write → chunk + embed → `_store_summary`), `_markdown_image_context` (L1403) + `_md_ref_block` (L1436, the `Referenced in <source>/<md>:` block writer), `_enrich_pending_images` (L1627, the phase-125 task-04 post-index pass — the shape of the new backfill pass), `ImportSummary` (L212, stats counters + `log()` — stats are log-only, the sync `detail` API shape never changes); `app/rag/summarizer.py` — `describe_image` (L208, ONE chat-model vision call, `context` appended after the locked `DESCRIBE_PROMPT` as a `\n\nThis image is referenced in documentation with the following context:\n` prefix — the wording phase 137 generalizes), `DESCRIBE_PROMPT` / `IMAGE_DESCRIPTION_MODE` (L78/L57 — the mock's key; byte-identity criteria below); `app/rag/prompts.py` — `_extract_context_line` (L470, renders only `Referenced in …:` blocks, everything else degrades to `None`), `_image_context_line` (L536), `_document_body` (L548, the phase-125 context-line lead); `app/models.py` — `Document.image_context` (L170, TEXT nullable, migration 0023); `tests/e2e/mock_llm.py` — the `IMAGE_DESCRIPTION_MODE` canned vision reply (L2472 branch, `IMAGE_DESCRIPTION_ANSWER` L865) and the phase-125 `CONTEXT_LINE_TRIGGER` pattern (the model for this phase's mock trigger); `tests/e2e/test_pdf_support.py` (the synthetic PDF fixture recipe: PyMuPDF build, `page2.insert_image(…, stream=PNG_1X1)`, images-on/off module apps); `test_sources/players_handbook.pdf` (293 pages, 586 embedded images — the real multi-page fixture), `test_sources/hnb_2026_guide.tar.gz` (the owner's example — stock-photo descriptions with no document context).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Every image that comes from a document carries the document context in the text that gets embedded: the vision prompt for a PDF-embedded image includes WHERE it came from (source + PDF path + page) and the surrounding page text, so the model writes a description that names the document and what the image illustrates; the context is stored on `image_context` (idempotent, re-scanned on re-index) and rendered as a short locator line in the chat suggestion block; and every image document already in the KB is backfilled on the next sync. Markdown-referenced images (phase 125) keep working byte-for-byte; PDFs are the only importable format that embeds images, so this closes the TODO's gap completely.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `136_force_push_reset` (todo) — pipeline order only.
|
||||||
|
- Code: the completed phase-126 PDF pipeline + the phase-122 vision seam + the phase-125 context machinery (all on `main`); and pending `133_pdf_screenshot_fallback` — its `is_usable_pdf_text` gate (task 02 of that phase) runs BEFORE this phase in the pipeline and is reused to suppress garbage page text in the context (ASSUMPTION A7).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The context block (task 02, ASSUMPTIONS A2/A3):** one block per embedded image, built from the PDF's own text —
|
||||||
|
```
|
||||||
|
Extracted from <source>/<pdf path> (page <N>):
|
||||||
|
<page text, stripped, capped at PDF_IMAGE_CONTEXT_MAX_CHARS = 6000>
|
||||||
|
```
|
||||||
|
The origin line is ALWAYS present (even when the page has no text — the owner's core complaint is "no mention of the document it came from"); the page-text line is omitted for a text-less page. If phase 133's gate exists (`app.rag.pdf.is_usable_pdf_text`) and says the PDF's text layer is unusable, the page text is dropped (origin line only — ASSUMPTION A7). When the image ALSO has phase-125 markdown reference blocks, the stored/passed context is the document block FIRST, then the markdown blocks (provenance → purpose — ASSUMPTION A2); the combining helper is one shared function used by the forward path AND the backfill (task 03) so the two can never drift.
|
||||||
|
- **The seam (task 02, ASSUMPTION A5):** `describe_image`'s `context` prefix wording generalizes from "This image is referenced in documentation with the following context:" to neutral text that covers both provenance and reference (e.g. "This image is part of a document. The following context describes where it comes from and what it is used for:"). `DESCRIBE_PROMPT` (marker + locked instruction) stays byte-identical; `context=None` (standalone image) sends the bare prompt — byte-identical to today, so the phase-122 standalone path and every pre-existing E2E stay green.
|
||||||
|
- **The forward path (task 02):** `_index_pdf_embedded_images` calls the new `extract_pdf_page_texts` ONCE per PDF (a `dict[int, str]` page → stripped text — task 01) and passes it to `_index_one_embedded_image`, which builds the combined context, passes it as `context` to `_describe_or_skip`, and stores the SAME value on `image_context` (the phase-125 task-03 rule: context follows the current source state on re-index — a re-indexed image re-scans; the digest-skip for unchanged images is UNCHANGED: an unchanged image keeps its (now context-carrying) content).
|
||||||
|
- **The backfill (task 03, ASSUMPTION A4):** a post-index pass in `import_sources` next to `_enrich_pending_images` — the phase-118 A2 "best-effort until it sticks" shape. Candidates: `is_image=True` docs whose `path` matches the embedded-image pattern (`*.pdf#page=<N>#img=<I>.<ext>`) AND whose `image_context` does NOT start with `Extracted from ` (NULL or markdown-only) AND whose `image_path` copy still exists on disk. Per candidate: bytes from the copy, page text re-extracted from the parent PDF if it is still in the source (parent gone → origin line only, parsed from the doc's own synthetic path — no disk dependency), re-describe through the SAME seam, re-chunk + re-embed (`_replace_content_chunks`, one transaction per image), store the combined context. Idempotent by the stored-context gate: a success writes a context starting with `Extracted from ` → the doc never qualifies again. Fail-soft per image (a `None` description leaves the row untouched, counts `images_failed`, sync continues). New `ImportSummary.image_context_backfilled: int = 0` counter + `log()` field ONLY (the stats log-only convention — the sync `detail` API shape is untouched). One loud log line per backfilled image (PLAN §9).
|
||||||
|
- **The display line (task 04, ASSUMPTION A6):** `_extract_context_line` learns the `Extracted from <source>/<pdf path> (page <N>):` header (regex; the page-text body is NEVER rendered — same rule as the `Context:` body) and renders it as `From <source>/<pdf path> (page <N>)`. A value carrying BOTH block kinds renders the clauses in stored order (`From …; Referenced in …`). A value with no parsable block degrades to `None` exactly as today (pre-phase rows, markdown `IMAGE_CONTEXT:` records on text docs — the `is_image` guard already excludes those).
|
||||||
|
- **The E2E (task 05):** the mock gains ONE new trigger, following the phase-125 `CONTEXT_LINE_TRIGGER` pattern exactly: when the `IMAGE_DESCRIPTION_MODE` message's text part contains `Extracted from ` (the new provenance header), the canned reply becomes a context-aware description (fixed string, e.g. naming the document + page) instead of `IMAGE_DESCRIPTION_ANSWER` — the deterministic observable that the context REACHED the vision model. The suite uploads a synthetic PDF (text on page 1, one embedded PNG on page 2 — the `test_pdf_support.py` recipe) through the images-on module app, syncs, and asserts: the image doc's content/summary is the context-aware canned reply; its `image_context` starts with `Extracted from <source>/report.pdf (page 2)`; a chat question that retrieves the image shows the `From <source>/report.pdf (page 2)` line in the suggestion. A markdown-referencing case (a `.md` in the same archive referencing the synthetic path) asserts BOTH blocks, document first.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_pdf_page_texts.md` — `extract_pdf_page_texts` in `app/rag/pdf.py` (the shared per-page iteration, fail-soft) + unit tests on the real fixture PDFs.
|
||||||
|
2. `02_embedded_image_document_context.md` — the document-context block builder + the forward path (build once per PDF, combine with markdown blocks, pass through the seam, store on `image_context`) + the generalized seam prefix + unit tests with a capturing fake LLM.
|
||||||
|
3. `03_backfill_image_context.md` — the per-sync idempotent backfill pass + the `image_context_backfilled` counter + integration tests (existing row backfilled, idempotent no-op, parent-gone origin-only, standalone never touched).
|
||||||
|
4. `04_retrieval_display_line.md` — `_extract_context_line` renders the `Extracted from` block as the one-line `From … (page N)` locator + unit tests (both-blocks ordering, degradation, pre-phase byte-identity).
|
||||||
|
5. `05_e2e_pdf_image_context.md` — the mock's `Extracted from` trigger + the dedicated Playwright suite `tests/e2e/test_pdf_image_context.py`, run in isolation.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: task 01 — `extract_pdf_page_texts` on `test_sources/players_handbook.pdf` (293 pages, spot-check known page text, page count, 1-indexed keys) and `pdf_horse_test.pdf`; an unreadable path → `{}` (fail-soft); `extract_pdf_text` output byte-identical after the shared-iteration refactor (the phase-126 regression pin). Task 02 — the block builder (page text capped at 6000, text-less page → origin line only, garbage gate drops the page text when 133's gate exists); the combining order (document first, markdown second; markdown-only and document-only cases); the seam message (context present → neutral prefix + combined text AFTER the byte-identical `DESCRIBE_PROMPT`; context=None → byte-identical pre-137 message); the forward path via a capturing fake LLM (the stored `image_context` == the context passed; the title/unchanged-skip rules untouched). Task 04 — the renderer (`Extracted from` alone, both blocks in stored order, unparseable → `None`, the `is_image` guard). Task 05 — the mock trigger (context-aware reply only when `Extracted from ` is in the text part; the bare `IMAGE_DESCRIPTION_ANSWER` otherwise — the phase-122/126 suites stay green without edits).
|
||||||
|
- Integration: task 03 — a seeded PDF-embedded image row without context is backfilled through the real `import_sources` (the fake LLM records the context-bearing describe call; content/chunks/`image_context` updated); a second sync is a NO-OP (zero describe calls — the idempotency gate); a row whose parent PDF was deleted from the source gets the origin-line-only context; a standalone image (no `#page=`) is NEVER touched; a markdown-enriched row (context `Referenced in …`) gets the combined context (document block prepended).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation (AGENTS.md §4/§9), mock-only.
|
||||||
|
- Coverage: **>90%** on `app/` (`uv run pytest --cov=app --cov-report=term-missing`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a (re)indexed PDF's embedded images are described with the document context: the vision message carries `Extracted from <source>/<pdf> (page N):` + the capped page text (the unit/integration proofs above), and the stored `image_context`/summary carry it too
|
||||||
|
- [ ] a markdown-referenced PDF image carries BOTH blocks, document first — and a standalone image's describe message is byte-identical to pre-phase (the phase-122 regression pin)
|
||||||
|
- [ ] an existing context-free image doc (e.g. one of the HNB-guide stock photos) is re-described WITH context on the next sync, and the following sync burns zero vision calls for it (the idempotency test)
|
||||||
|
- [ ] the chat suggestion block for a backfilled/forward image leads with `From <source>/<pdf> (page N)`
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_pdf_image_context.py -v --no-cov` green in isolation; the pre-existing `test_pdf_support.py`, `test_image_anchor_context.py`, `test_image_documents.py` suites stay green UNEDITED
|
||||||
|
- [ ] no behavior change in completed phases (the phase-122 standalone path, the phase-125 markdown enrichment, the phase-126 PDF text path, the sync API shape)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` green
|
||||||
|
- [ ] one atomic Conventional Commits commit for the phase (`feat(rag): …`), `--no-gpg-sign`
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Task 01 — `extract_pdf_page_texts`: per-page text map for image context
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Image summaries should always include the document context if the images come from a document … so the embedder can more effectively retrieve image sources." (This task builds the per-page text source the context block is made from; the item itself is implemented across tasks 01–05.)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`app/rag/pdf.py` gains `extract_pdf_page_texts(pdf_path: Path) -> dict[int, str]` — one entry per page that has text, key = 1-indexed page number, value = the page's stripped text (the same `page.get_text("text")` read `extract_pdf_text` uses). Pages without text contribute nothing (no key). This is the raw material task 02 feeds the vision prompt: for one embedded image on page N, the document context is page N's text. The existing `extract_pdf_text` output stays **byte-identical** (the phase-126 contract — the `---PAGE-N---` blocks, blank-line join, fail-soft `""`).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. Read `app/rag/pdf.py` in full (phase 126). Note `extract_pdf_text` (L87): open → per-page `get_text("text")` → strip → skip empties → `PAGE_SEPARATOR` prefix → `"\n\n"` join; fail-soft per page and per file.
|
||||||
|
2. Refactor the shared page iteration into one private helper, e.g. `_iter_page_texts(doc) -> Iterator[tuple[int, str]]` yielding `(page_1_indexed, stripped_text)` for pages with non-empty text (the per-page try/except + warning logging moves into the helper, unchanged in behavior). `extract_pdf_text` becomes: open (fail-soft `""`) → consume the helper → build the separator-joined string. Its signature, output bytes, and log lines are UNCHANGED.
|
||||||
|
3. Add the public function:
|
||||||
|
```python
|
||||||
|
def extract_pdf_page_texts(pdf_path: Path) -> dict[int, str]:
|
||||||
|
"""One entry per page of *pdf_path* that has text (1-indexed page → stripped text). …"""
|
||||||
|
```
|
||||||
|
Same open/fail-soft contract as `extract_pdf_text` (unreadable file → `{}`, one warning — the `pdf:` logger prefix house style).
|
||||||
|
4. Update the module docstring's function list (the file documents every public function at the top).
|
||||||
|
5. Unit tests in `tests/unit/test_pdf.py` (the file that owns `app/rag/pdf` — extend it):
|
||||||
|
- `test_sources/players_handbook.pdf` (293 pages): 293 or fewer entries, keys 1-indexed, first key `1`, every value non-empty and stripped; spot-check one page's text equals the corresponding `extract_pdf_text` block body (parse a `---PAGE-N---` block and compare — the two functions must agree page-for-page).
|
||||||
|
- `test_sources/pdf_horse_test.pdf`: 1 page → exactly one entry (or `{}` if that page is text-less — assert against `extract_pdf_text`'s output for the same file, whatever it is).
|
||||||
|
- A missing path → `{}` (fail-soft, no raise).
|
||||||
|
- **Regression pin:** `extract_pdf_text` on both fixture files is byte-identical before/after the refactor (capture the current output NOW, in the test, by asserting the separator structure + a known substring from page 1 — do not hardcode a 300-page string).
|
||||||
|
6. Run the phase-126 pdf unit tests + `uv run ruff check . && uv run pyright` — green before moving on.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The tests above ARE the task's tests; all in the existing `app/rag/pdf` unit-test file (no new file unless the house layout says otherwise — check `tests/unit/` first).
|
||||||
|
- Coverage: `app/rag/pdf.py` stays >90% (the helper's per-page failure branch: reuse the existing unreadable-page test pattern if one exists; otherwise a temp file that fitz opens but fails mid-read is not worth fabricating — the existing coverage of that branch via `extract_pdf_text`'s tests carries over since both call sites share the helper).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `extract_pdf_page_texts` exists, is documented, fail-soft, and returns 1-indexed page → stripped text
|
||||||
|
- [ ] `extract_pdf_text` output is byte-identical (the regression pin green on both fixture PDFs)
|
||||||
|
- [ ] `uv run pytest tests/unit -k pdf -v --no-cov` green; `uv run ruff check . && uv run pyright` green
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Task 02 — The forward path: document context into the vision prompt + `image_context`
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Images extracted from PDFs still don't have any relevant context in their summaries … there are lots of stock photos in test_sources/hnb_2026_guide.tar.gz and they get summaries like 'A smiling woman with dark curly hair sits holding a grey laptop on her lap...' which has no mention of the document it came from or what it might have been helping to illustrate. … Image summaries should always include the document context if the images come from a document."
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
When a PDF is (re)indexed, every embedded image's vision call and stored `image_context` carry a document-context block — `Extracted from <source>/<pdf path> (page <N>):` plus the page's text (capped) — combined with any phase-125 markdown reference blocks (document block first). The vision model therefore writes a description that names the document and the page, and the stored `content`/`summary`/`image_context` carry the same context the embedder needs. Standalone images and the phase-125 markdown-only shape are untouched.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. Read, in full: `app/rag/importer.py` — `_index_pdf_embedded_images` (L1091), `_index_one_embedded_image` (L1182), `_markdown_image_context` (L1403), `_md_ref_block` (L1436), `_describe_or_skip` (L1742); `app/rag/summarizer.py` — `describe_image` (L208, esp. the `context_prefix` build near the message construction).
|
||||||
|
2. **The block builder** in `app/rag/importer.py` (next to `_markdown_image_context`):
|
||||||
|
```python
|
||||||
|
PDF_IMAGE_CONTEXT_MAX_CHARS = 6000 # ASSUMPTION A3 — module constant, no env var
|
||||||
|
|
||||||
|
def _pdf_image_context_block(
|
||||||
|
source: str, pdf_rel: str, page: int, page_texts: dict[int, str],
|
||||||
|
text_usable: bool = True,
|
||||||
|
) -> str:
|
||||||
|
"""The document-context block for one embedded image (phase 137, A2).
|
||||||
|
|
||||||
|
Always non-empty: the origin line is present even for a text-less
|
||||||
|
page. The page text is stripped, capped at
|
||||||
|
:data:`PDF_IMAGE_CONTEXT_MAX_CHARS` (overflow cut at the cap,
|
||||||
|
then ``TRUNCATION_MARKER`` on its own line — the summarizer's
|
||||||
|
existing truncation convention), and OMITTED entirely when the
|
||||||
|
page has no text OR when the phase-133 gate (see step 3) marks
|
||||||
|
the PDF's text layer unusable.
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
Shape (exactly):
|
||||||
|
```
|
||||||
|
Extracted from <source>/<pdf_rel> (page <N>):
|
||||||
|
<page text or — for a text-less page — nothing after the header line>
|
||||||
|
```
|
||||||
|
`TRUNCATION_MARKER` lives in `app.rag.retriever` (import it there-from, the same way `app/rag/summarizer.py` does — L49).
|
||||||
|
(header line `Extracted from {source}/{pdf_rel} (page {page}):` — `page` is the 1-indexed page number (the forward path passes `img.page`; the task-03 backfill passes the page parsed from the synthetic path — taking a plain `int`, NOT a `PdfImage`, is deliberate so the backfill needs no fake `PdfImage`); NO "of M" total — the total page count is not on `PdfImage` and the origin line must stay a stable single line for the task-04 renderer's regex.)
|
||||||
|
3. **The garbage-text guard (ASSUMPTION A7):** the phase-133 gate `is_usable_pdf_text` is added by pending `133_pdf_screenshot_fallback` (runs BEFORE this phase in the pipeline). In `_index_pdf_embedded_images`, import it defensively — module-level `from app.rag.pdf import extract_pdf_images, extract_pdf_page_texts` and, for the gate, `is_usable_pdf_text = getattr(_pdf_module, "is_usable_pdf_text", None)` (a small import-time probe or a try/except ImportError fallback) — and pass a `text_usable: bool` (default `True` when the gate is absent) down to `_index_one_embedded_image` → `_pdf_image_context_block`: `text_usable=False` → the block is the origin line only. Never import the gate unconditionally (the phase must run in isolation if 133 is skipped).
|
||||||
|
4. **`_index_pdf_embedded_images`:** after the `settings.images` gate, call `extract_pdf_page_texts(full_path)` ONCE (task 01's function) and pass the resulting `page_texts` + `text_usable` to `_index_one_embedded_image` (add keyword params — the function signature is internal, no other callers: verify with `rg "_index_one_embedded_image"`).
|
||||||
|
5. **`_index_one_embedded_image`:** where it currently computes `image_context = _markdown_image_context(...)` (the phase-125 task-03 scan), build the combined context with a NEW shared helper (task 03 reuses it — define it once, near the block builder):
|
||||||
|
```python
|
||||||
|
def _combine_image_contexts(doc_block: str, md_blocks: str | None) -> str:
|
||||||
|
"""Document block first, markdown reference block(s) second (A2).
|
||||||
|
|
||||||
|
``md_blocks`` is ``None``/empty → the doc block alone; the doc
|
||||||
|
block is ALWAYS present for embedded images (it is the provenance
|
||||||
|
— never empty). Markdown-only values (no doc block) are produced
|
||||||
|
by the standalone path only and never pass through this helper.
|
||||||
|
"""
|
||||||
|
```
|
||||||
|
Set `image_context = _combine_image_contexts(block, md)` — everything downstream is unchanged (the `context=` arg of `_describe_or_skip`, the `content = f"{image_context}\n\n{description}"` enrichment, the row write, `_store_summary`).
|
||||||
|
6. **The seam prefix (ASSUMPTION A5):** in `app/rag/summarizer.py`'s `describe_image`, replace the context prefix
|
||||||
|
`"\n\nThis image is referenced in documentation with the following context:\n{context}"`
|
||||||
|
with neutral wording covering both provenance and reference, e.g.
|
||||||
|
`"\n\nThis image is part of a document. The following context describes where it comes from and what it is used for:\n{context}"`.
|
||||||
|
`DESCRIBE_PROMPT` (marker + locked instruction) is UNTOUCHED; `context=None` still yields the bare prompt (byte-identical — assert it). Update `describe_image`'s docstring (`*context*` no longer means "markdown reference context" only — it means "the document/reference context built by the importer") and `_describe_or_skip`'s docstring likewise.
|
||||||
|
7. Unit tests (extend the importer's existing image tests — `rg "_markdown_image_context|_index_one_embedded_image" tests/unit`):
|
||||||
|
- **Block builder:** page with text → header + text; text capped at exactly 6000 + `TRUNCATION_MARKER` (build a page of ~7000 chars); text-less page → header line only; `text_usable=False` → header line only even with text present.
|
||||||
|
- **Combining:** doc-only; doc + markdown (doc block first, blank-line join — assert the exact joined string); markdown shape never lost (the `Referenced in …` block byte-identical inside the combined value).
|
||||||
|
- **Forward path with a capturing fake LLM** (the importer's existing fake pattern — `chat` records the message list): a PDF with page text + one embedded image → the `describe_image` message's text part == `DESCRIBE_PROMPT` + neutral prefix + combined context (assert the prefix bytes explicitly); the stored `Document.image_context` == the same combined value; `content`/`summary` == `context + "\n\n" + description`.
|
||||||
|
- **Regression pins:** standalone image (no markdown, no PDF) → message byte-identical to pre-phase (capture the current message in a test by asserting `DESCRIBE_PROMPT` is the entire text part — `context=None`); markdown-only reference for a STANDALONE image (the phase-125 path) → still the markdown block with the (now neutral) prefix — the stored value is byte-identical (only the prompt prefix wording moved, not the stored data).
|
||||||
|
- The phase-126 unchanged-image digest skip is untouched (an unchanged embedded image still re-describes nothing — add/keep the existing test).
|
||||||
|
8. `uv run pytest tests/unit -k "pdf or image" -v --no-cov`, then the full unit suite; `uv run ruff check . && uv run pyright` — green before moving on.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The tests in step 7; every one deterministic (fake LLM, fixture PDFs — no network, no real model).
|
||||||
|
- Coverage: new/modified lines in `app/rag/importer.py` + `app/rag/summarizer.py` covered by these tests (the cap boundary, both guard branches, both combining branches).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a (re)indexed PDF's embedded images reach the vision model with `Extracted from <source>/<pdf> (page N):` + the (capped) page text, and the stored `image_context`/`content`/`summary` carry the same value
|
||||||
|
- [ ] a markdown-referenced embedded image carries BOTH blocks, document first (exact-string test)
|
||||||
|
- [ ] the standalone image's describe message is byte-identical to pre-phase; `DESCRIBE_PROMPT` unchanged
|
||||||
|
- [ ] garbage-text guard: when the phase-133 gate exists and fails, the block is the origin line only; when the gate is absent, the block behaves normally (the phase runs in isolation)
|
||||||
|
- [ ] `uv run pytest --no-cov` green (full suite); `uv run ruff check . && uv run pyright` green
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Task 03 — Backfill: existing PDF-embedded image docs gain the document context on the next sync
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Images extracted from PDFs still don't have any relevant context in their summaries … That context is critical in the image summaries. Image summaries should always include the document context if the images come from a document …" (The forward path of task 02 only fixes images that get (re)indexed; this task fixes the images ALREADY in the KB — e.g. the HNB-guide stock photos the owner cited — without waiting for a byte change.)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A per-sync, idempotent, best-effort pass (the phase-118 A2 "until it sticks" shape, next to the phase-125 `_enrich_pending_images` post-index pass) re-describes every PDF-embedded image document that is missing the document-context block: bytes come from the `image_dir` copy, the page text is re-extracted from the parent PDF when it is still in the source (parent gone → origin line only), the new context-aware description goes through the SAME seam, and the row's `content`/`summary`/`image_context`/chunks are replaced. After a success the doc never qualifies again; a failure leaves the row untouched and retries next sync.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. Read, in full: `_enrich_pending_images` (L1627 — the shape to mirror: driven by committed doc rows, idempotent, fail-soft, one transaction per image, deletes nothing), the per-source loop in `import_sources` (L525–590: `source = root.name`, the `_enrich_pending_images` call site at L587), `ImportSummary` (L212 + its `log()` method — the stats log-only convention: new field + log field, the sync `detail` API shape never changes), `_store_summary` (the image-aware summary store — the description IS the summary, stored verbatim), `_replace_content_chunks` (the per-image re-chunk + re-embed), `_pdf_image_context_block` / `_combine_image_contexts` / `extract_pdf_page_texts` (tasks 01–02).
|
||||||
|
2. **The candidate query + gate** in a new function `async def _backfill_image_contexts(session, *, source: str, root: Path, llm: Embedder, summary: ImportSummary) -> None` in `app/rag/importer.py`:
|
||||||
|
- Select this source's `Document` rows with `is_image.is_(True)`.
|
||||||
|
- A doc is a CANDIDATE iff ALL hold:
|
||||||
|
1. its `path` parses as the phase-126 embedded-image synthetic path `<pdf_rel>#page=<N>#img=<I>.<ext>` (module-level compiled regex, e.g. `^.+\.pdf#page=(?P<page>\d+)#img=(?P<img>\d+)(?P<ext>\.\w+)$` — parse out `pdf_rel`, page, index, ext; non-matches — standalone images, screenshot-fallback PDFs are `is_image=False` anyway — are NEVER touched);
|
||||||
|
2. its `image_context` is `NULL` OR does not start with `"Extracted from "` (the idempotency gate — a markdown-only `"Referenced in …"` value STILL qualifies: the doc block is missing);
|
||||||
|
3. its `image_path` names a file that exists on disk (the `image_dir` copy — the bytes source; missing → debug log, skip, the doc stays as-is).
|
||||||
|
- If no candidates → return (the common case after the one-time backfill — zero cost per sync).
|
||||||
|
3. **Per candidate** (fail-soft, one transaction per image, mirroring `_enrich_pending_images`'s error handling):
|
||||||
|
- `page_texts`: call `extract_pdf_page_texts(root / pdf_rel)` ONCE per unique `pdf_rel` across the candidates (a local cache dict in the pass — one parent may own many images); parent missing/unreadable → `page_texts = {}` AND `text_usable = True` (origin line only — the origin is still valuable and needs no disk); parent present → apply the same phase-133 gate probe as task 02 (shared helper if task 02 factored one out — reuse it, do not duplicate the probe).
|
||||||
|
- Build `doc_block = _pdf_image_context_block(source, pdf_rel, page, page_texts, text_usable=text_usable)` (`page` from the regex — the builder takes a plain `int`, task 02), then `combined = _combine_image_contexts(doc_block, existing_md_blocks)` — where `existing_md_blocks` = the doc's current `image_context` if it starts with `"Referenced in "` (the markdown blocks are kept verbatim — re-scanning the disk for them is NOT the pass's job: the phase-125 pass owns the markdown context and ran first this sync), else `None`.
|
||||||
|
- `data = Path(doc.image_path).read_bytes()` (OSError → skip, debug log).
|
||||||
|
- `description = await _describe_or_skip(llm, data=data, source=source, rel=doc.path, full_path=Path(doc.image_path), context=combined)` — the SAME seam (the mime comes from the copy's extension, exactly like the forward path). `None` → the row is UNTOUCHED (no rollback of anything — nothing was written), `summary.images_failed += 1`, warning, move on (the next sync retries — the gate still matches).
|
||||||
|
- Write: `content = f"{combined}\n\n{description}"`; `image_context = combined`; `indexed_at = now`; then `_replace_content_chunks(...)` (same call shape as the forward path, L1311) in the image's own transaction (an embed failure rolls back THIS image only — `summary.errors += 1`, error line, the copy stays, move on); then `_store_summary(...)` (the image convention — the description is the summary, verbatim); commit; `summary.image_context_backfilled += 1`; one loud log line (PLAN §9): `import: backfilled image context source=<source> path=<doc.path> chunks=<n>`.
|
||||||
|
- Deliberately UNCHANGED on the row: `content_hash` (the byte digest — the image identity is untouched), `created_at`/`created_at_manual` (the SOURCE did not change — the phase-106 date rules do not apply), `title`, `image_path`.
|
||||||
|
4. **The counter:** `ImportSummary` gains `image_context_backfilled: int = 0` (docstring: "PDF-embedded image docs whose stored `image_context` was backfilled with the document-context block (phase 137, task 03) — the one-time best-effort pass; a success never repeats, a failure retries next sync") + its field in `ImportSummary.log()` (the per-turn/per-sync log line — append it next to `images_failed`; the sync `detail` API response shape is NOT changed — the stats log-only convention, phase 133).
|
||||||
|
5. **The call site:** in `import_sources`'s per-source loop, immediately AFTER the existing `await _enrich_pending_images(...)` (L587 — enrichment first: it owns the markdown-FIRST case and may set `image_context`; the backfill then prepends the document block to whatever is there). The pass is driven by committed rows (like the enrichment pass), so it is safe under `limit`.
|
||||||
|
6. **Integration tests** (extend the importer's existing integration file — `rg "_enrich_pending_images" tests/integration`):
|
||||||
|
- **Backfill happy path:** seed the DB with a PDF-embedded image row (the phase-126 synthetic path, `image_context=NULL`, `content`/`summary` = a bare description, an `image_path` pointing at a temp file with the image bytes) + the parent PDF on disk with page text; run the REAL `import_sources` over the source (fake LLM that records describe calls and returns a fixed context-aware reply); assert: exactly ONE describe call whose context carries `Extracted from <source>/<pdf> (page N):` + the page text; the row's `image_context` starts with `Extracted from `; `content`/`summary` = combined context + new description; chunks replaced; `image_context_backfilled == 1`.
|
||||||
|
- **Idempotency:** run `import_sources` a second time over the same source → ZERO describe calls, the row byte-identical (the gate no longer matches), `image_context_backfilled == 0`.
|
||||||
|
- **Parent gone:** the parent PDF is deleted from the source dir → the describe call's context is the origin line ONLY (no page-text line); the row is still backfilled (the gate matches again next sync iff it failed — here it succeeds once).
|
||||||
|
- **Markdown-only row:** `image_context = "Referenced in <source>/doc.md:\n- Alt text: \"x\""` (the phase-125 shape) → the backfilled `image_context` = doc block + blank line + the markdown block VERBATIM (document first).
|
||||||
|
- **Standalone image never touched:** an `is_image` row whose `path` has no `#page=` (a plain `pic.png`) with `image_context=NULL` → zero describe calls for it, across two runs.
|
||||||
|
- **Fail-soft:** a candidate whose describe call returns `None` (the fake fails once) → the row untouched, `images_failed == 1`; a second run with a healthy fake → backfilled.
|
||||||
|
7. `uv run pytest tests/integration -k "image or import" -v --no-cov`, then the full unit + integration suites; `uv run ruff check . && uv run pyright` — green before moving on.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The tests in step 6 (real `import_sources`, fake LLM, temp dirs + seeded session — the house integration pattern; no network, no real model).
|
||||||
|
- Coverage: every gate branch (pattern non-match, gate match, missing copy, parent gone), the happy path, idempotency, the fail-soft paths — all new lines covered.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] an existing context-free PDF-embedded image doc is re-described WITH the document context on the next sync (integration test), counted in the new log-only `image_context_backfilled` counter
|
||||||
|
- [ ] the pass is idempotent: the following sync burns zero vision calls for a backfilled doc (integration test)
|
||||||
|
- [ ] a parent-gone image gets the origin-line-only context; a markdown-enriched row keeps its markdown block verbatim, document block prepended
|
||||||
|
- [ ] standalone images and non-embedded rows are never touched; a describe failure leaves the row untouched and retries next sync
|
||||||
|
- [ ] the sync `detail` API shape is unchanged (the new counter is log-only — verify the sync response schema test still passes unedited)
|
||||||
|
- [ ] `uv run pytest --no-cov` green; `uv run ruff check . && uv run pyright` green
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Task 04 — The suggestion-block display line: `From <source>/<pdf> (page N)`
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "…so the embedder can more effectively retrieve image sources." (The summary itself now carries the context via tasks 02/03; this task makes the context VISIBLE in the chat suggestion block the way phase 125 did for markdown references — a short locator line, never the page-text body.)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`_extract_context_line` in `app/rag/prompts.py` renders the phase-137 document-context block — `Extracted from <source>/<pdf path> (page <N>):` — as the one-line clause `From <source>/<pdf path> (page <N>)`, so a PDF-embedded image's `<document>` suggestion body leads with where the image came from (before its description), exactly the way an enriched markdown image leads with `Referenced in …`. A context value carrying BOTH block kinds renders both clauses in stored order. Everything that parses to nothing degrades to `None` exactly as today (pre-phase rows, the `IMAGE_CONTEXT:` pending record, unparseable text).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. Read, in full: `_extract_context_line` (L470), `_image_ctx_clause` (L459), `_image_context_line` (L536), `_document_body` (L548) in `app/rag/prompts.py` — the phase-125 task-05 renderer: header regex `_IMAGE_CTX_HEADER_RE` (`^Referenced in (?P<ref>.+):$`), the alt-bullet regex, the clause join (`"Referenced in " + "; ".join(clauses)`), and the `expecting_alt` state machine.
|
||||||
|
2. Add the header regex for the new block (next to `_IMAGE_CTX_HEADER_RE`): `_PDF_CTX_HEADER_RE = re.compile(r"^Extracted from (?P<loc>.+) \(page (?P<page>\d+)\):$")` — `loc` is the `<source>/<pdf path>` locator (greedy to the last ` (page N):` — the pdf path may itself contain spaces).
|
||||||
|
3. Extend the state machine in `_extract_context_line` to handle the new header:
|
||||||
|
- A `Extracted from …` header STARTS a pdf clause: it needs NO following bullet (unlike the `Referenced in` header, whose next line MUST be the alt bullet or the block is dropped — the pdf block's next line is page-text body or the next header, and none of it changes the clause).
|
||||||
|
- Its clause text: `From {loc} (page {page})`.
|
||||||
|
- Clause JOINING: the current code prefixes `"Referenced in "` to the joined clauses — that prefix belongs to the REFERENCED clauses only. Restructure so each clause carries its own prefix: referenced clauses stay `Referenced in <ref>: "<alt>"` (byte-identical output for markdown-only values — the phase-125 regression pin), pdf clauses are `From <loc> (page N)`; the join is still `"; "` between clauses IN STORED ORDER (document block first per ASSUMPTION A2 → a both-blocks value renders `From a.pdf (page 2); Referenced in docs/a.md: "alt"`).
|
||||||
|
- A pdf clause followed by page-text body lines: the body lines are skipped by the existing "any other line is context body" fall-through — verify the state machine does not mis-read a page-text line that LOOKS like a header (e.g. a line of page text starting with `Referenced in ` — the existing spurious-header rule already handles the referenced case by demanding the alt bullet; a spurious `Extracted from … (page N):` line inside page text would emit a clause — accept that: it is the stored context the importer wrote, not model text; document it in the docstring).
|
||||||
|
- A value with NO parsable header of either kind → `None` (unchanged).
|
||||||
|
- Update `_extract_context_line`'s docstring (the stored value can now carry the `Extracted from` block first — tasks 02/03 write it — plus the markdown blocks) and the module-level comment block above the regexes (the phase-137 note).
|
||||||
|
4. `_image_context_line` / `_document_body` need NO changes (the `is_image` guard + the renderer call already do the right thing) — verify with a read, and note it in the commit message if so.
|
||||||
|
5. Unit tests (extend the prompts test file — `rg "_extract_context_line|_document_body" tests/unit`):
|
||||||
|
- pdf block alone → `"From <source>/guide.pdf (page 2)"` exactly.
|
||||||
|
- pdf block + page-text body (multi-line, including a blank line and a line starting with `Referenced in ` without the alt bullet) → the same single clause (the spurious referenced header is dropped by the existing rule).
|
||||||
|
- markdown block alone → byte-identical to the pre-task output (the phase-125 pin: `Referenced in docs/a.md: "alt a"; docs/b.md` from the existing test's shape).
|
||||||
|
- BOTH blocks in stored order (pdf first, markdown second — the tasks 02/03 combined shape) → `From <source>/guide.pdf (page 2); Referenced in docs/a.md: "alt"`.
|
||||||
|
- garbage/unparseable value → `None` (unchanged); the `IMAGE_CONTEXT:` pending record → `None` (unchanged).
|
||||||
|
- `_document_body` end-to-end: an `is_image` doc with the combined context → body leads with the one-line rendering, then the summary; a non-image doc with a non-NULL `image_context` → byte-identical body (the `is_image` guard).
|
||||||
|
6. `uv run pytest tests/unit -k prompt -v --no-cov`, then the full unit suite; `uv run ruff check . && uv run pyright` — green before moving on.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The tests in step 5; the markdown-only byte-identity pin is the load-bearing one (phase 125's display contract must not move).
|
||||||
|
- Coverage: the new header branch, both orderings, the degradation paths — all covered by step 5.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a PDF-embedded image doc's suggestion `<document>` body leads with `From <source>/<pdf> (page N)` (unit test), never rendering the page-text body
|
||||||
|
- [ ] a both-blocks context renders `From …; Referenced in …` in stored order; a markdown-only context renders byte-identically to pre-phase (the phase-125 pin green UNEDITED)
|
||||||
|
- [ ] unparseable values and the `IMAGE_CONTEXT:` record degrade to `None` as before; non-image docs are byte-identical
|
||||||
|
- [ ] `uv run pytest --no-cov` green; `uv run ruff check . && uv run pyright` green
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Task 05 — The dedicated E2E: `tests/e2e/test_pdf_image_context.py` (mock trigger + the story suite)
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — the whole item, end to end: "Images extracted from PDFs still don't have any relevant context in their summaries … Image summaries should always include the document context if the images come from a document (this includes markdown files) so the embedder can more effectively retrieve image sources." (AGENTS.md §4/§9: every phase carries its own Playwright E2E file, run in isolation; this is this phase's gate.)
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
One new Playwright suite proving the story through the REAL UI + REAL pipeline with the deterministic mock LLM: (a) an uploaded PDF's embedded image is described WITH the document context (the context-aware canned reply is the witness that the context reached the vision model), stored on `image_context`/`content`/`summary`; (b) the chat suggestion for that image leads with the `From <source>/<pdf> (page N)` line; (c) a markdown reference in the same source COMBINES with the document context, document block first. Plus the one mock-LLM change that makes (a) observable.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. Read, in full: `tests/e2e/test_pdf_support.py` (the module-app pattern: `_app_env` with the port/env overrides, `zip_path` fixture — the PyMuPDF PDF build: `doc.new_page().insert_text((72, 72), PAGE_ONE)`, `page2.insert_image(fitz.Rect(72, 150, 73, 151), stream=PNG_1X1)`, `doc.set_metadata({"title": PDF_TITLE})`, zip to `<source>.zip`; the `_truncate_all`, `_upload_zip` (admin login → git-sources page → `#archive-upload-file`/`#archive-upload-btn` → result line), `_sync_via_ui` (RAG page `#sync-btn` → `#sync-label` "Syncing…" → synced label + `#sync-result`), and `seeded` module fixture), `tests/e2e/test_image_anchor_context.py` (the `ANCHOR_QUESTION = "quote the image reference — what is shown in the homelab network diagram?"` pattern + the mock-calibrated gate env values + the standalone-doc "no reference line" witness), `tests/e2e/mock_llm.py` — the `IMAGE_DESCRIPTION_MODE` branch (L2472), `IMAGE_DESCRIPTION_ANSWER` (L865), `CONTEXT_LINE_TRIGGER` (L1886) + its branch (L2532, `_seeded_image_doc` / `_seed_context_line`), and the docstring's behavior list at the top (every new mock behavior is documented there).
|
||||||
|
2. **The mock change** (the ONLY edit to `tests/e2e/mock_llm.py`):
|
||||||
|
- New constant next to `IMAGE_DESCRIPTION_ANSWER`:
|
||||||
|
```python
|
||||||
|
#: The phase-137 witness — the mock's vision reply when the
|
||||||
|
#: ``IMAGE_DESCRIPTION_MODE`` message's text part carries the
|
||||||
|
#: document-context block (its ``Extracted from …`` header). It
|
||||||
|
#: names the document + page (the context reached the model — the
|
||||||
|
#: deterministic proof) and keeps the diagram wording of
|
||||||
|
#: :data:`IMAGE_DESCRIPTION_ANSWER` so the story question's
|
||||||
|
#: token-overlap retrieval still grounds on the image doc.
|
||||||
|
IMAGE_DESCRIPTION_CONTEXT_ANSWER = (
|
||||||
|
"From report.pdf, page 2: a network diagram of the homelab "
|
||||||
|
"server room: a core router on top, a core switch in the "
|
||||||
|
"middle, and three labeled subnets at the bottom — VLAN 10 "
|
||||||
|
"office, VLAN 20 lab, and VLAN 30 storage — with a legend of "
|
||||||
|
"cable runs. Title: Homelab Network Map."
|
||||||
|
)
|
||||||
|
```
|
||||||
|
- In the `IMAGE_DESCRIPTION_MODE` branch: `answer = IMAGE_DESCRIPTION_CONTEXT_ANSWER if "Extracted from " in user else IMAGE_DESCRIPTION_ANSWER` — the `Extracted from ` probe is the phase-137 provenance header (the importer's block builder — task 02); the bare path (standalone images, the pre-137 embedded shape, every existing suite's PDFs) stays on `IMAGE_DESCRIPTION_ANSWER` — byte-identical.
|
||||||
|
- Document the new branch behavior in the mock's top docstring (the house rule — every behavior is listed).
|
||||||
|
- NO other mock change: the `CONTEXT_LINE_TRIGGER` branch already echoes the seeded image doc's block FIRST line — which is now the task-04 `From …` rendering for PDF images (zero mock work for the display assertion).
|
||||||
|
3. **The suite** `tests/e2e/test_pdf_image_context.py` (run in isolation: `uv run pytest tests/e2e/test_pdf_image_context.py -v --no-cov`):
|
||||||
|
- Module app: ONE images-ON app, the `test_pdf_support.py` pattern — new env port (`E2E_APP_PORT_PDF_IMG_CTX`, default 8154 — check `8152/8153` are taken by test_pdf_support and pick the next free), scratch dirs via `tmp_path_factory`, the mock's port from the session `mock_llm` fixture; assert `/api/config` `images` is True in the seed (the suite is void otherwise).
|
||||||
|
- **Fixture archive 1** (`zip_path`): ONE PDF at the root, source `e2e-pdf-imgctx`, `report.pdf` — page 1 = `PAGE_ONE` text, page 2 = `PAGE_TWO` text + the 1×1 PNG embedded (the phase-126 recipe; define `PAGE_ONE`/`PAGE_TWO`/`PDF_TITLE`/`PNG_1X1` locally — do NOT import from test_pdf_support; the suites must stay standalone).
|
||||||
|
- **Seed 1** (module): `_truncate_all` → `_upload_zip` → `_sync_via_ui` (expected result line: the 2-added counts — the PDF doc + the image doc).
|
||||||
|
- **Test 1 — the forward path (the TODO's core complaint):** DB assertions (`SessionLocal`, like test_pdf_support's `seeded`):
|
||||||
|
- the image doc exists at `e2e-pdf-imgctx/report.pdf#page=2#img=0.png`, `is_image=True`;
|
||||||
|
- its `image_context` STARTS WITH exactly `Extracted from e2e-pdf-imgctx/report.pdf (page 2):` and CONTAINS the `PAGE_TWO` text (the document context reached the store — the owner's "no mention of the document it came from" is gone);
|
||||||
|
- its `content` == `image_context + "\n\n" + IMAGE_DESCRIPTION_CONTEXT_ANSWER` and `summary` == `content` (the image convention) — the CONTEXT-AWARE reply is the witness the describe call carried the context (the bare `IMAGE_DESCRIPTION_ANSWER` string must NOT appear in `content`).
|
||||||
|
- **Test 2 — the display line in chat:** the `ANCHOR_QUESTION` pattern (`"quote the image reference — what is shown in the homelab network diagram?"` — the diagram wording is in `IMAGE_DESCRIPTION_CONTEXT_ANSWER`, so the same retrieval grounds), the mock-calibrated gate env (the test_image_anchor_context values); assert the final answer contains `From e2e-pdf-imgctx/report.pdf (page 2)` (the mock's `CONTEXT_LINE_TRIGGER` echo of the block's first line — the task-04 rendering) and does NOT contain `stands alone` (the standalone witness is absent).
|
||||||
|
- **Fixture archive 2** (`zip_md_path`): the SAME PDF + `notes.md` at the root containing `` plus a paragraph of surrounding context (the phase-125 reference shape) — source `e2e-pdf-imgctx-md`.
|
||||||
|
- **Seed 2** (module): `_truncate_all` → upload archive 2 → sync (expected counts: PDF + image + the markdown doc).
|
||||||
|
- **Test 3 — markdown + document combined, document first:** the image doc's `image_context` == `Extracted from e2e-pdf-imgctx-md/report.pdf (page 2):` + `PAGE_TWO` text + `"\n\n"` + the markdown block starting `Referenced in e2e-pdf-imgctx-md/notes.md:` (assert the STARTS-WITH document block AND the `Referenced in` block's presence AND the document block's index < the `Referenced in` block's index — document first, ASSUMPTION A2); the chat display answer (the same anchor question) contains BOTH `From e2e-pdf-imgctx-md/report.pdf (page 2)` and `Referenced in e2e-pdf-imgctx-md/notes.md`.
|
||||||
|
- **Test 4 — standalone parity witness:** a plain standalone image upload in the SAME seeded source is overkill; instead assert against seed 1's KB: NO other `is_image` doc exists (the suite's KB is exactly the PDF + its image), and the mock's bare branch is pinned by test_pdf_support running green unedited (do not duplicate it).
|
||||||
|
4. **Regression run (the load-bearing gate):** `uv run pytest tests/e2e/test_pdf_support.py tests/e2e/test_image_anchor_context.py tests/e2e/test_image_documents.py -v --no-cov` — all three green UNEDITED (the mock change must not move their canned replies — the bare describe path is byte-identical; the `CONTEXT_LINE_TRIGGER` echo of a markdown-enriched doc is byte-identical).
|
||||||
|
5. `uv run ruff check . && uv run pyright` — green. (The suite itself is linted like its siblings; no type-check burden on the mock constants.)
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The suite in step 3 IS the phase's E2E deliverable; deterministic end to end (mock LLM, fixture PDFs built in tmp dirs — `test_sources/` is never touched, the house rule from phase 133's fixture handling).
|
||||||
|
- The mock edit is covered by the suite's tests 1–3 (the trigger) + the regression run step 4 (the non-trigger).
|
||||||
|
- Coverage gate (app/) is unaffected by test files; the phase's >90% comes from tasks 01–04.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `tests/e2e/test_pdf_image_context.py` exists and passes IN ISOLATION: `uv run pytest tests/e2e/test_pdf_image_context.py -v --no-cov`
|
||||||
|
- [ ] the embedded image's stored summary names the document + page (the context-aware canned reply — test 1); `image_context` leads with `Extracted from <source>/report.pdf (page 2):` + the page text
|
||||||
|
- [ ] the chat suggestion for the image leads with `From <source>/report.pdf (page 2)` (test 2, via the existing `CONTEXT_LINE_TRIGGER` echo — no new display mock branch)
|
||||||
|
- [ ] a markdown-referenced PDF image shows BOTH the document and the reference context, document first (test 3)
|
||||||
|
- [ ] `test_pdf_support.py`, `test_image_anchor_context.py`, `test_image_documents.py` green UNEDITED after the mock change
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` green
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Phase 138 — Markdown blockquotes render: `>` quotes become styled `<blockquote>`s
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "Markdown formatted ">" quotes aren't rendering"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/assets/markdown.js` — the shared escape-first renderer (loaded by all three pages: `index.html` chat, `document.html` viewer, `shared.html`): step 1 fence protection (`\u0000CODEn\u0000`), step 1b table protection (`\u0000TABLEn\u0000`, phase 44), step 2 `inline(escapeHtml(text))` (the inline chain: code → strong → em → h3/h4 → ul → ol), step 3 the paragraph pass (split on `\n{2,}`; the block-element guard `/^<(h\d|ul|ol|pre|li)/`), step 4 restore. Today a `>` line is escaped to `>` and renders as literal text in a `<p>` (verified: `renderMarkdown("> quoted")` → `<p>> quoted</p>`). `frontend/assets/styles.css` — the `:root` palette (`--ink-soft` 8.2:1 on `--surface`, `--line`, the `--brand-*` family; the `:root`-drift unit test parses the built-ins from this file — no second copy) and the chat-bubble / viewer typography. `tests/unit/test_markdown_tables.py` — the frontend source-pin + node-behavior unit pattern (`HAVE_NODE` skip); `tests/e2e/test_markdown_tables.py` — the phase-44 E2E pattern (mock flow with table output + the document viewer).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`>`-prefixed lines in any rendered markdown — a chat answer, the thinking block, a saved/shared chat (restore), the document viewer — render as a semantic `<blockquote class="md-quote">` with theme-safe styling; every non-quote input renders byte-identical to today (the phase-44 table suite and the renderer-dependent unit suites stay green unedited).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `137_pdf_image_context` (complete) — pipeline order only; the code dependencies are the shared renderer + `styles.css` on `main`.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The pass (task 01):** a new line-block pass in `markdown.js` BETWEEN step 2 (`inline(escapeHtml(text))`) and step 3 (paragraphs) — at that point the text is escaped (a quote line starts with `>`) and already inline-transformed (bold/emphasis/code work inside quotes for free — the pass never re-transforms). Group the maximal run of consecutive lines matching `^\s*>+ ?` into ONE `<blockquote class="md-quote">…</blockquote>`: strip the leading `>` run plus ONE optional space from each member (nested `>>` / `>>>` collapses to one level — ASSUMPTION A1), join members with `<br>` (the paragraph convention). A BLANK line terminates the group (a re-quoted line starts a new `<blockquote>` — simple, predictable). The step-3 guard extends to `/^<(h\d|ul|ol|pre|li|blockquote)/` so the paragraph pass leaves the block alone (no `<p>` wrap).
|
||||||
|
- **Precedence is untouched:** fences protect first (step 1 — a `>` inside a code block never reaches the pass), tables protect second (step 1b — cell content is escaped inside the `<td>` markup and restored in step 4, AFTER the pass). No other pass changes.
|
||||||
|
- **In-quote structure (documented limit):** a markdown STRUCTURE inside a quote (a `- list` line, a `# heading` line) renders as plain text inside the blockquote — the inline chain runs before the pass, so its line-start transforms never see the post-strip text. Inline (code/strong/em) still works. Acceptable — the scope is quote rendering (owner L3).
|
||||||
|
- **The CSS (task 02):** `.md-quote` in `styles.css` — theme-safe from the EXISTING `:root` palette only: left border + horizontal padding + vertical margin + a muted text color carrying a ≥4.5:1 contrast comment on the bubble surface (the house comment convention, cf. `--ink-soft`'s `/* 8.2:1 on --surface */`). ONE rule set serves all three contexts (chat `.bubble`, `.thinking-text`, the document viewer) — a scoped override only if the E2E proves a clash.
|
||||||
|
- **Byte-identity (task 03):** any input without a quote line renders byte-identical to the pre-phase renderer — pinned by the node behavior check and by the unedited `test_markdown_tables.py` / `test_thinking_scroll.py` / `test_document_viewer.py` suites.
|
||||||
|
- **E2E (task 03):** dedicated `tests/e2e/test_markdown_blockquotes.py`, run in isolation (AGENTS.md rules 4/9), mock-only.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_blockquote_pass.md` — the blockquote pass in `markdown.js` + the paragraph-guard extension.
|
||||||
|
2. `02_blockquote_css.md` — the `.md-quote` styling in `styles.css` (theme-safe, WCAG AA contrast).
|
||||||
|
3. `03_unit_and_e2e.md` — unit source-pins + node behavior + the dedicated Playwright E2E.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_markdown_blockquotes.py` (new — the phase-44 pattern): source pins (pass order fences → tables → escape+inline → **blockquotes** → paragraphs → restore; the guard regex includes `blockquote`; the exact `<blockquote class="md-quote">` marker; the `.md-quote` CSS rule references palette vars only) + node behavior (single-line quote, multi-line group, nested collapse, XSS quote inert, fence-wins, a table cell containing `>` untouched, non-quote input byte-identical).
|
||||||
|
- E2E: `tests/e2e/test_markdown_blockquotes.py` (new), in isolation.
|
||||||
|
- Coverage: **>90%** on `app/` (the gate runs the full suite — this phase adds no `app/` code, so the suite staying green IS the gate).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `>` quotes render as a styled `<blockquote class="md-quote">` in the chat answer, the thinking block, saved/shared chats (restore), and the document viewer
|
||||||
|
- [ ] nested `>>` collapses to one level; a `>` inside a code fence or a table cell is untouched
|
||||||
|
- [ ] non-quote input renders byte-identical (the phase-44 / renderer-dependent suites pass unedited)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` TOTAL >90%; `uv run pytest tests/e2e/test_markdown_blockquotes.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] one `--no-gpg-sign` Conventional Commit; phase dir moved to `.agents/phases/complete/` by the pipeline gate
|
||||||
|
|
||||||
|
## Locked decisions
|
||||||
|
- **A1 — nested quotes (`>>`, `>>>`) collapse to a single `<blockquote>` level (owner-confirmed 2026-09-30, roadmap confirmation).**
|
||||||
|
- **A2 — the quote style is a left border + padding + muted text color (NO background fill), built from the existing `:root` palette only (owner-confirmed 2026-09-30, roadmap confirmation).**
|
||||||
|
|
||||||
|
## Commit
|
||||||
|
```bash
|
||||||
|
git add frontend/ tests/ .agents/phases/ && git commit --no-gpg-sign -m "feat(ui): render markdown blockquotes in chat, viewer, and shared pages"
|
||||||
|
```
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Task 01 — The blockquote pass in the shared renderer
|
||||||
|
|
||||||
|
**Phase:** `138_markdown_blockquotes` · **Source:** `TODO.md:3` — "Markdown formatted ">" quotes aren't rendering"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`renderMarkdown` turns runs of `>`-prefixed lines into `<blockquote class="md-quote">` elements — after the escape + inline step, before the paragraph pass — with fences and tables keeping their precedence and non-quote input byte-identical.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/markdown.js` — new pass between the step-2 `text = inline(escapeHtml(text))` and the step-3 paragraph `.map(...)`: split the text on `\n`; group the maximal run of consecutive lines matching `^\s*>+ ?` (the escaped quote marker); strip the `>` run + one optional space from each member (nested `>>`/`>>>` collapses to one level — ASSUMPTION A1); join members with `<br>`; emit `<blockquote class="md-quote">…</blockquote>`. A blank line terminates the group.
|
||||||
|
2. `frontend/assets/markdown.js` — extend the step-3 block-element guard from `/^<(h\d|ul|ol|pre|li)/` to `/^<(h\d|ul|ol|pre|li|blockquote)/` so the paragraph pass leaves the block alone (no `<p>` wrap).
|
||||||
|
3. `frontend/assets/markdown.js` — update the module docstring: pass order is now fences → tables → escape+inline → **blockquotes** → paragraphs → restore; document the group rule (blank line terminates; nested collapses) and the documented limit (a list/heading line INSIDE a quote renders as plain text — the inline chain ran first; inline code/strong/em work).
|
||||||
|
- ASSUMPTION: a `>` inside a code fence is already protected by the step-1 placeholder (no handling needed); a `>` in a table cell is escaped inside the `<td>` markup and restored in step 4 — both are pinned in task 03's behavior checks.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: covered by task 03's file (the source pin + the node behavior listed there) — the frontend house pattern is one unit file per feature.
|
||||||
|
- Coverage: n/a (frontend) — the suite + the pins are the gate.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] node repro: `renderMarkdown("> a\n> b")` → `<blockquote class="md-quote">a<br>b</blockquote>`; `renderMarkdown("> quoted")` no longer emits a literal `>`
|
||||||
|
- [ ] a non-quote input (plain paragraph, list, table, fence) renders byte-identical to the pre-task renderer
|
||||||
|
- [ ] `uv run pytest` green (the renderer-dependent unit suites unedited); `uv run ruff check .` clean
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Task 02 — `.md-quote` styling (theme-safe, WCAG AA)
|
||||||
|
|
||||||
|
**Phase:** `138_markdown_blockquotes` · **Source:** `TODO.md:3` — "Markdown formatted ">" quotes aren't rendering"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The blockquote is visually distinct and readable in all three rendering contexts (chat bubble, thinking block, document viewer) with ONE rule set, using only the existing `:root` palette.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/styles.css` — add the `.md-quote` rule next to the other markdown element styles (the phase-44 `.md-table` / `.md-table-wrap` block is the anchor): `border-left: 3px solid <palette var>` (a visible-but-restrained border — pick from the existing `:root` palette, the executor's contrast judgment), `padding: 0.25rem 0.75rem`, `margin: 0.5rem 0`, `color: <muted palette var>` with a ≥4.5:1 contrast comment on the bubble surface per the house convention (`--ink-soft`'s `/* 8.2:1 on --surface */` qualifies — verify against the actual bubble background and document it).
|
||||||
|
2. `frontend/assets/styles.css` — no background fill (ASSUMPTION A2); verify the rule renders acceptably in the chat `.bubble`, the `.thinking-text` block, and the document-viewer content region — add a scoped override only if the task-03 E2E proves a clash.
|
||||||
|
- ASSUMPTION: the built-in dark palette is the single source of truth — the `:root`-drift unit test parses built-ins from this file, so no hex literal outside `:root` and no second copy.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_markdown_blockquotes.py` (task 03) source-pins the `.md-quote` rule's presence and its palette-var-only references (the phase-44 CSS-pin pattern).
|
||||||
|
- Coverage: n/a (frontend).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the `.md-quote` rule exists in `styles.css`, references only `:root` palette vars, and carries a ≥4.5:1 contrast comment
|
||||||
|
- [ ] the quote is visually distinct in chat + viewer (the E2E screenshot, task 03)
|
||||||
|
- [ ] the theme no-op (B4) is unaffected — the rule uses existing vars; no new `ui_settings` column
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Task 03 — Unit pins, node behavior, dedicated E2E
|
||||||
|
|
||||||
|
**Phase:** `138_markdown_blockquotes` · **Source:** `TODO.md:3` — "Markdown formatted ">" quotes aren't rendering"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Pin the renderer contract at the source level, prove the browser behavior, and ship the dedicated Playwright file, run in isolation (AGENTS.md rules 4/9).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/unit/test_markdown_blockquotes.py` (new) — the phase-44 pattern (source pins + a `HAVE_NODE`-skipped node behavior):
|
||||||
|
- Source pins: the blockquote pass runs after `inline(escapeHtml(text))` and before the paragraph split; the paragraph guard includes `blockquote`; the exact `<blockquote class="md-quote">` marker string; the `.md-quote` CSS rule references palette vars only (the task-02 pin).
|
||||||
|
- Node behavior: single-line quote → one blockquote; a 3-line group → one blockquote with `<br>` joins; `>> nested` collapses to one level; `> <script>alert(1)</script>` renders inert (no live tag in the output); a `>` inside a ``` fence stays fence content; a table cell containing `> x` renders as table-cell text, not a blockquote; non-quote input (a paragraph + list + table) renders byte-identical to the pre-phase renderer (fixture string checked into the test, per the phase-44 shape).
|
||||||
|
2. `tests/e2e/test_markdown_blockquotes.py` (new) — dedicated, run in isolation (`--no-cov`, DB up), mock-only, following `tests/e2e/test_markdown_tables.py`'s structure:
|
||||||
|
- (a) the chat: a mock flow whose answer contains `>` quotes (the phase-44 mock-flow pattern — a new user-message marker, a deterministic canned answer) → assert the DOM: the `.bubble` contains a `blockquote.md-quote` with the quote text and no literal `>` text at the block's start;
|
||||||
|
- (b) the viewer: a KB fixture with a `.md` document containing a quote block → open the document → assert the viewer content renders the `blockquote.md-quote`;
|
||||||
|
- (c) the restore: save the chat (or reload `/?chat=<id>`) → the restored bubble keeps the blockquote (the restore path runs the same renderer — a cheap assertion if the suite structure allows it).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: as above. E2E: as above. Coverage: **>90%** on `app/` (the gate runs the full suite; frontend changes add no `app/` code — the suite must stay green).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_markdown_blockquotes.py -v` green (node available → the behavior check runs)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_markdown_blockquotes.py -v --no-cov` green in isolation
|
||||||
|
- [ ] `uv run pytest` green, coverage TOTAL >90%, `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Phase 139 — The Reading tool line shows which lines are being read
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L4 — "The \"Reading\" tool UI output doesn't show what lines are being read, just the same file over and over which is confusing to the user"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/api/chat.py` — the SSE `tool` frame (`ChatToolEvent`) ALREADY carries `offset` / `limit` for a range `read` (phase 131 task 04 — the fields land on the frame only when well-formed via `_whole_line_number` (L307) and are omitted otherwise, so non-range frames are byte-identical); the frame is emitted at ~L928-952. `frontend/assets/app.js` — `appendToolLine(wrap, name, argument)` (L1119 — the read branch builds `📄 Reading ` + a `<code>{argument}</code>` child; the line bytes are pinned by the phase-87 emoji guard + the phase-117 disclosure pins), the live `tool` branch (L3103-3137 — reads only `ev.name` / `ev.argument`; `toolAcc.push({ name, argument })` L3116; the status label `is reading ${argument}` L3125), `toolAcc` (L2993 — the per-turn accumulator persisted as the saved chat's `tools` array at L3229 / L3310 / L3361 / L3395), the restore path (~L2030-2045 — `m.tools` → `appendToolLine(wrap, t.name, arg)` + the phase-95 truncation marker). `frontend/assets/shared.js` — `addToolLines(wrap, tools)` (~L175+ — the shared page's parity copy of `appendToolLine` with the pinned-identical line literals). `tests/integration/test_api.py` — the frontend emoji guard strips precisely the pinned emoji literals from `app.js` / `shared.js` (no new emoji may be introduced). `tests/e2e/test_read_line_ranges.py` + the phase-131 mock flow (`read the lines` marker → grep → `read(offset, limit)`) in `tests/e2e/mock_llm.py`.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
When the agent range-reads a document (`read(path, offset, limit)` — phase 131), the Reading tool line shows WHICH lines — `📄 Reading <code>source/path</code> (lines 42–71)` — so repeated reads of the same file are distinguishable, live, on restore, and on the shared page; a plain read renders byte-identical to today.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `138_markdown_blockquotes` (todo) — pipeline order only; no code overlap (139 touches the tool-line rendering, 138 the markdown renderer).
|
||||||
|
- Code: the phase-131 wire fields (complete) — nothing new server-side.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The suffix (task 01):** one new helper in `app.js` — `readRangeSuffix(offset, limit) → string | ""` — the single source of truth for the wording (used by both the tool line and the status label): both present → ` (lines {offset}–{offset + limit - 1})` (EN-DASH; the pinned copy — ASSUMPTION A1: the range shown is the model's REQUEST; the UI does not know the document length, so a `limit` past EOF renders the requested extent); offset only → ` (from line {offset})`; limit only → ` (first {limit} lines)`; neither / malformed → `""`. The JS well-formedness guard mirrors the server's `_whole_line_number`: `Number.isInteger(x) && x >= 1`.
|
||||||
|
- **`appendToolLine` (task 01):** the signature becomes `appendToolLine(wrap, name, argument, offset = null, limit = null)` — the read arm (`read` / `read_document`) appends, AFTER the `<code>` child, a `<span class="read-range">` with `textContent = readRangeSuffix(offset, limit)` ONLY when the suffix is non-empty (a plain read's line stays byte-identical — the phase-87/117 pins + the emoji guard stay green; no new emoji). `shared.js`'s `addToolLines` applies the identical suffix to its pinned-identical line (the parity contract — the shared page re-renders saved records that now carry the fields).
|
||||||
|
- **The live branch (task 02):** read `ev.offset` / `ev.limit` with the same guard (absent / malformed → `null`); `toolAcc.push({ name, argument, offset, limit })` with the fields included ONLY when non-null (a non-range record keeps the exact pre-phase `{name, argument}` shape — the `bor.chat.v1` save JSONB is additive; old records without the fields restore byte-identically, no migration); pass both to `appendToolLine`; the status label becomes `${brand()} is reading ${argument}${suffix}` (same helper — ASSUMPTION A2).
|
||||||
|
- **The restore path (task 02):** `t.offset` / `t.limit` (same guard) → `appendToolLine(wrap, t.name, arg, tOffset, tLimit)`; the phase-95 truncation note is untouched (it keys on the `<code>` argument — verify with the existing pins).
|
||||||
|
- **E2E (task 03):** ONE new mock flow following the phase-131 pattern (user-message marker, deterministic replies, module-header docstring entry): the model range-reads the SAME document twice with different `offset`/`limit` — the owner's exact "same file over and over" scenario.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_tool_line_range_suffix.md` — `readRangeSuffix` + the `appendToolLine` / `addToolLines` suffix rendering.
|
||||||
|
2. `02_live_restore_persist.md` — the live branch's `ev.offset`/`ev.limit`, the `toolAcc` persistence, the restore path, the status label.
|
||||||
|
3. `03_unit_and_e2e.md` — unit pins + node behavior + the mock flow + the dedicated Playwright E2E.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_read_range_tool_lines.py` (new — the `test_frontend_tool_states.py` pattern): source pins (the suffix template literals, the `Number.isInteger` guard, the `ev.offset`/`ev.limit` read, the `toolAcc` push carrying the fields, the restore pass-through, the shared.js parity) + node behavior (`appendToolLine` with a range vs without — the plain line byte-identical; the three suffix shapes).
|
||||||
|
- E2E: `tests/e2e/test_read_range_tool_lines.py` (new), in isolation.
|
||||||
|
- Coverage: **>90%** on `app/` (no `app/` code changes — the suite staying green IS the gate).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a range read renders `📄 Reading <code>path</code> (lines N–M)` live; two range reads of the same file show DIFFERENT ranges (the owner's confusion is gone)
|
||||||
|
- [ ] a plain read's line is byte-identical to pre-phase (the phase-87/117 pins + the emoji guard pass unedited)
|
||||||
|
- [ ] the suffix survives save → restore (the chat page + the shared page render it from the saved record)
|
||||||
|
- [ ] `uv run pytest` green; coverage TOTAL >90%; `uv run pytest tests/e2e/test_read_range_tool_lines.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] one `--no-gpg-sign` Conventional Commit; phase dir moved to `.agents/phases/complete/`
|
||||||
|
|
||||||
|
## Locked decisions
|
||||||
|
- **A1 — the suffix shows the model's REQUESTED range (`offset`…`offset+limit−1`); the UI cannot know the actual slice extent (owner-confirmed 2026-09-30, roadmap confirmation).**
|
||||||
|
- **A2 — the status label carries the same suffix (`Brain is reading source/path (lines 42–71)`) (owner-confirmed 2026-09-30, roadmap confirmation).**
|
||||||
|
|
||||||
|
## Commit
|
||||||
|
```bash
|
||||||
|
git add frontend/ tests/ .agents/phases/ && git commit --no-gpg-sign -m "feat(ui): show the read tool's line range in the Reading line"
|
||||||
|
```
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Task 01 — The range suffix on the Reading line (chat + shared page)
|
||||||
|
|
||||||
|
**Phase:** `139_read_range_tool_lines` · **Source:** `TODO.md:4` — "The \"Reading\" tool UI output doesn't show what lines are being read, just the same file over and over which is confusing to the user"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`appendToolLine` (and the shared page's `addToolLines`) render the requested line range as a suffix on the Reading line whenever a well-formed `offset`/`limit` is passed — createElement + textContent only, plain reads byte-identical.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — add a `readRangeSuffix(offset, limit)` helper next to `appendToolLine`: the well-formedness guard `Number.isInteger(x) && x >= 1` (mirrors the server's `_whole_line_number`); both present → ` (lines ${offset}–${offset + limit - 1})` (en-dash — the pinned copy); offset only → ` (from line ${offset})`; limit only → ` (first ${limit} lines)`; otherwise → `""`.
|
||||||
|
2. `frontend/assets/app.js` — `appendToolLine(wrap, name, argument, offset = null, limit = null)`: in the read arm (`read` / `read_document`), compute `readRangeSuffix(offset, limit)`; when non-empty, append a `<span class="read-range">` (textContent = the suffix) AFTER the `<code>` child. No other arm changes; no new emoji (the guard in `tests/integration/test_api.py` strips precisely the pinned literals).
|
||||||
|
3. `frontend/assets/shared.js` — `addToolLines`: the same suffix on the shared page's pinned-identical Reading line (the saved record carries the fields from task 02; a record without them renders exactly as today).
|
||||||
|
- ASSUMPTION: the span is a SIBLING of the `<code>` child — the phase-95 truncation note is the precedent (it appends a span sibling and never rewrites the line's pinned template text).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: covered by task 03's file (source pins + node behavior).
|
||||||
|
- Coverage: n/a (frontend).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] node repro: `appendToolLine` with `offset=42, limit=30` → the line's text is `📄 Reading <path> (lines 42–71)`; without the arguments → byte-identical to pre-task
|
||||||
|
- [ ] `uv run pytest` green (the phase-87/117 pins + the emoji guard unedited); `uv run ruff check .` clean
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Task 02 — Wire the range through live frames, persistence, and restore
|
||||||
|
|
||||||
|
**Phase:** `139_read_range_tool_lines` · **Source:** `TODO.md:4` — "The \"Reading\" tool UI output doesn't show what lines are being read, just the same file over and over which is confusing to the user"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The `offset`/`limit` already on the SSE `tool` frame (phase 131) reach the Reading line live, persist in the saved chat's `tools` record (additively), and re-render on restore — chat page + shared page.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — the live `tool` branch (~L3103): read `ev.offset` / `ev.limit` (the `Number.isInteger(x) && x >= 1` guard → `null` when absent / malformed); `toolAcc.push({ name, argument, offset, limit })` with the fields included ONLY when non-null (a non-range record keeps the exact pre-phase `{name, argument}` shape — the `bor.chat.v1` save JSONB is additive; old rows restore unchanged, no migration); pass both values to `appendToolLine`.
|
||||||
|
2. `frontend/assets/app.js` — the status label (~L3125): `${brand()} is reading ${argument}${readRangeSuffix(offset, limit)}` (the grep / ls labels are untouched).
|
||||||
|
3. `frontend/assets/app.js` — the restore path (~L2030): pass `t.offset` / `t.limit` (same guard) to `appendToolLine`; the phase-95 `appendTruncatedNote` call is untouched (it keys on the `<code>` argument).
|
||||||
|
4. `frontend/assets/app.js` — the save-payload sites (L3229 / L3310 / L3361 / L3395) need no code change (they serialize `toolAcc` as-is) — verify the phase-83 save-payload-limit tests are unaffected by the two extra fields.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: task 03's file (source pins for the `ev.offset`/`ev.limit` read, the `toolAcc` push shape, the restore pass-through).
|
||||||
|
- Coverage: n/a (frontend).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a live range read: the line shows the suffix AND the status label shows it AND `toolAcc` carries `{name, argument, offset, limit}`
|
||||||
|
- [ ] a saved chat restored (the `/?chat=<id>` path) + the shared page re-render the suffix; a pre-phase saved record (no fields) renders byte-identical
|
||||||
|
- [ ] `uv run pytest` green (the chat-persistence / save-payload suites unedited)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Task 03 — Unit pins, node behavior, mock flow, dedicated E2E
|
||||||
|
|
||||||
|
**Phase:** `139_read_range_tool_lines` · **Source:** `TODO.md:4` — "The \"Reading\" tool UI output doesn't show what lines are being read, just the same file over and over which is confusing to the user"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Pin the suffix contract at the source level, add the owner's "same file over and over" scenario to the deterministic mock, and prove it end-to-end in a dedicated Playwright file, run in isolation.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/unit/test_read_range_tool_lines.py` (new) — the `test_frontend_tool_states.py` pattern: source pins (the ` (lines ${offset}–${offset + limit - 1})` / ` (from line …)` / ` (first … lines)` literals; the `Number.isInteger` guard; the live branch's `ev.offset` / `ev.limit` read; the `toolAcc` push carrying the fields; the restore pass-through; the shared.js identical literals) + node behavior (the three suffix shapes; the plain-read line byte-identical to pre-phase; the shared-page parity).
|
||||||
|
2. `tests/e2e/mock_llm.py` — ONE new scripted flow (house style — a user-message marker, deterministic replies, a module-header docstring entry): the marker `read the same file twice` → round 1: a `read` tool call `(path, offset=10, limit=20)`; round 2: a `read` tool call `(path, offset=40, limit=15)`; round 3: the answer echoing both results (the phase-131 read-echo shape).
|
||||||
|
3. `tests/e2e/test_read_range_tool_lines.py` (new) — dedicated, run in isolation (`--no-cov`, DB up), mock-only; a KB fixture with ONE multi-hundred-line document:
|
||||||
|
- (a) the marker question → assert TWO Reading lines for the SAME `<code>` path carrying the distinct suffixes ` (lines 10–29)` and ` (lines 40–54)`;
|
||||||
|
- (b) a plain-read flow (an existing mock flow with a `read` call and no range — e.g. the phase-131 plain-read case or the phase-37 flow) → assert the Reading line has NO `.read-range` span (byte-identical shape);
|
||||||
|
- (c) save the chat → restore (reload `/?chat=<id>`) → assert the suffixes re-render from the saved record.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: as above. E2E: as above. Coverage: **>90%** on `app/` (the gate; no `app/` changes).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_read_range_tool_lines.py -v` green
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_read_range_tool_lines.py -v --no-cov` green in isolation
|
||||||
|
- [ ] `uv run pytest` green, coverage TOTAL >90%, `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Phase 140 — Pictorial PDFs: sparse pages are rendered and vision-described into the indexed content
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L5 — "I've added a new \"ikea_instructions.tar\" to test_sources. This is an example pdf that stil isn't working. There isn't much text, it's mostly graphical, but it doesn't have pictures. Take a screenshot of the first page or pages 8 onward, it's mostly pictographic illustrations of how to assemble a piece of furniture. We need to support this kind of pdf, and in this case showing rendered pages of the pdf is more helpful than the extracted text. We need a way to determine when that's neccesary. My suggestion is to screenshot the pdf, generate a text summary, compare it to the text extraction, and if the screenshot contains more information (you can use an LLM to judge) use the screenshot or rendered page rather in addition to the extracted text. More information is better when generating the text embeddings since that increases the chance the user's search will hit something."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** the owner's fixture `test_sources/ikea_instructions.tar` (gitignored, on disk — the phase-133 convention: tests extract to `tmp_path`, never the repo): `besta-frame-white__AA-1272068-11-100.pdf`, 24 pages, metadata title "Assembly Instructions" (Adobe InDesign) — pages 2–5 are text-heavy (multilingual warnings, 3,091–7,288 chars), the other 20 pages are sparse (4–73 chars, `Illustration N` markers) and carry **vector-drawn** pictograms (PyMuPDF `get_image_info()` → 0 embedded raster images — the phase-122/137 embedded-image pipeline sees nothing). Today the file passes the phase-133 garbage gate (`is_usable_pdf_text` — the text is usable, just thin) and is indexed as ~24 KB of page markers → a question about the assembly steps never hits. `app/rag/pdf.py` — `PAGE_SEPARATOR = "---PAGE-{page}---"` (L57), `extract_pdf_text` (L153), `extract_pdf_page_texts` (L178 — the phase-137 `dict[int, str]` helper), `is_usable_pdf_text` (L225 — the phase-133 gate), `render_pdf_pages` (L267 — all pages at 150 dpi, the zero-byte unreadable-page placeholder), `extract_pdf_images` (L300). `app/rag/importer.py` — `_index_pdf_file` (L1140 — extract → the phase-133 gate + `_fallback_page_screenshots` → digest over the FINAL content → upsert + the unchanged early-return → chunk + embed → `lite` summary → embedded images), `ImportSummary` (L212 — stats counters + the `log()` line; stats are LOG-ONLY, the sync `detail` API shape never changes). `app/rag/summarizer.py` — the marker convention (L36-95: `IMAGE_DESCRIPTION_MODE` / `DESCRIBE_PROMPT`), `describe_image` (L208 — ONE chat-model vision call, the multimodal user message, the `context` param, fail-soft `str | None`, no app-level retry). `app/config.py` — the toggle pattern (`images: bool = False` L379 — `BOR_IMAGES`; the house kill-switch: `0` disables, a negative value fails startup loudly). `tests/e2e/mock_llm.py` — the `IMAGE_DESCRIPTION_MODE` branch (L2685) + the canned reply + the phase-137 trigger pattern (a new marker branch is additive — the existing suites stay green unedited). `tests/e2e/test_pdf_support.py` — the synthetic-PDF fixture recipe (PyMuPDF build) + the module-app pattern.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A PDF whose pages are mostly pictorial (the IKEA assembly-instruction class) indexes with high-quality content: every sparse page (deterministic gate: stripped text below a threshold) is rendered to a screenshot and vision-described, and the description is appended to that page's content block — so the embeddings carry what the text layer couldn't and search hits the illustrations (the owner's L5 rationale: "More information is better when generating the text embeddings"). NO LLM judge (owner decision 2026-09-30) and NO page cap (PLAN A21 — the LLM calls are free; a slower sync is acceptable, a lower-quality KB is not).
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `139_read_range_tool_lines` (todo) — pipeline order only; no code overlap (140 is backend import + the mock; 139 is the frontend tool line).
|
||||||
|
- Code (all complete): phase 126 (the PDF pipeline), 133 (the garbage gate + `render_pdf_pages`), 137 (`extract_pdf_page_texts` + the vision seam).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The gate (task 01):** `app/rag/pdf.py` — `pictorial_pages(page_texts: dict[int, str], *, min_chars: int) -> list[int]`: the 1-based page numbers whose `len(text.strip()) < min_chars`, ascending — pure, deterministic, NO LLM call (ASSUMPTION A1). IKEA page 1 (`BESTÅ`, 5 chars) IS a candidate — a title page; describing it is useful (the logo + product name) and never harmful.
|
||||||
|
- **The settings (task 01):** `app/config.py` — `pdf_pictorial: bool = True` (`BOR_PDF_PICTORIAL`, the house kill-switch — `0`/`false` disables the pass entirely → content byte-identical to pre-phase; the `BOR_IMAGES` naming pattern) + `pdf_pictorial_min_chars: int = 100` (`BOR_PDF_PICTORIAL_MIN_CHARS`; validator: ≥ 0 — 0 = every page is a candidate (A21), negative fails startup loudly, the house pattern).
|
||||||
|
- **The vision seam (task 02):** `app/rag/summarizer.py` — `PICTORIAL_PAGE_MODE = "PICTORIAL_PAGE_MODE"` + `PICTORIAL_INSTRUCTION` (locked wording: describe in detail what the page shows — the assembly steps, part names, arrows, tool icons, before/after states — ESPECIALLY the information the extracted text does not contain) + `PICTORIAL_PROMPT = f"{PICTORIAL_PAGE_MODE}: {PICTORIAL_INSTRUCTION}"`; `describe_pdf_page(llm, *, data, mime, page, page_text) -> str | None` — the same one-chat-call multimodal contract as `describe_image` (no system prompt, no tools, no app-level retry, fail-soft `None`); the message text part = `PICTORIAL_PROMPT` + `\n\nPage {page} of the PDF. Text extracted from this page:\n{page_text.strip() or "(none)"}`. `DESCRIBE_PROMPT` / `IMAGE_DESCRIPTION_MODE` stay BYTE-IDENTICAL (the phase-122/126/137 suites pass unedited).
|
||||||
|
- **The render selector (task 02):** `app/rag/pdf.py` — `render_pdf_pages(pdf_path, *, dpi=150, pages: Sequence[int] | None = None)`: `pages` (1-based) restricts rendering to the named pages in ascending order (a 500-page PDF with 30 sparse pages renders 30 PNGs, not 500); `None` = all pages — the phase-133 caller stays byte-identical.
|
||||||
|
- **The import pass (task 03):** `_index_pdf_file` — AFTER the phase-133 gate (the precedence is locked: an unusable text layer takes the existing full-page screenshot fallback — NO pictorial pass, no double vision), when `settings.pdf_pictorial` and the content is usable:
|
||||||
|
1. `page_texts = extract_pdf_page_texts(full_path)`; `candidates = pictorial_pages(page_texts, min_chars=settings.pdf_pictorial_min_chars)` — **ALL candidates, no cap (A21)**; zero candidates → skip entirely (no render, no vision call — a clean-text PDF's path is byte-identical to pre-phase).
|
||||||
|
2. `render_pdf_pages(full_path, pages=candidates)` — a zero-byte placeholder page (unreadable) is skipped with a warning (the phase-133 handling).
|
||||||
|
3. each candidate in order: `describe_pdf_page(...)` fail-soft (`None` → skip that page, a warning log, continue — one dead page never kills the pass).
|
||||||
|
4. content assembly: every page 1..N as its `PAGE_SEPARATOR` + the page text + (when the page has a description: `\n\n[Page {n} illustration: {description}]`). The assembly with NO descriptions is byte-identical to `extract_pdf_text`'s output (a unit pin).
|
||||||
|
5. the digest over the FINAL content (the phase-126/133 convention — an unchanged file + a stable vision reply re-syncs as `unchanged`; a non-deterministic re-describe is a cost, not a bug — the phase-133 docstring documents it, A21 endorses it).
|
||||||
|
6. counters (stats log-only): `ImportSummary.pdfs_pictorial: int = 0` (a PDF with ≥1 described page) + `pdf_pictorial_pages: int = 0` (pages described) — `log()` fields only; the sync `detail` API shape is UNTOUCHED; ONE loud log line (PLAN §9): `pdf: pictorial pass source=<s> path=<p> — N candidate pages, M described (min_chars=<threshold>)`.
|
||||||
|
- **The viewer:** the description renders as plain text in the document viewer (A4 — PDFs are served as extracted text; the `[Page N illustration: …]` line IS content). No viewer change.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_settings_and_gate.md` — `BOR_PDF_PICTORIAL` + `BOR_PDF_PICTORIAL_MIN_CHARS` + `pictorial_pages` + unit tests.
|
||||||
|
2. `02_pictorial_vision_seam.md` — `PICTORIAL_PAGE_MODE` + `describe_pdf_page` + the `render_pdf_pages` page selector + the mock branch + unit tests.
|
||||||
|
3. `03_importer_pictorial_pass.md` — the `_index_pdf_file` pass + counters/log + the real IKEA-fixture integration repro + the unit/integration matrix.
|
||||||
|
4. `04_e2e_pictorial_pdf.md` — the dedicated Playwright suite, run in isolation, mock-only.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: task 01 — `pictorial_pages` (threshold boundaries `<`/`=`/`>`, a whitespace-only page → a candidate, an empty dict → `[]`, ascending order); task 02 — `describe_pdf_page`'s message shape (a capturing fake LLM: `PICTORIAL_PROMPT` first, the page block after, the data URL; `None` on an empty reply / client error; the `DESCRIBE_PROMPT` byte-identity), the `render_pdf_pages` selector (subset order + count, `None` = all); task 03 — the assembly byte-identity + the branch matrix.
|
||||||
|
- Integration: task 03 — the real IKEA tar through the REAL importer (the canned vision fake, capturing style): every candidate page (computed IN the test from `extract_pdf_page_texts` + `pictorial_pages` — no hardcoded page list) carries a `[Page N illustration: …]` block, the text-heavy pages (2–5) do NOT, the chunks carry the description, the title is "Assembly Instructions"; a re-sync with the same fake → `unchanged` (digest stable, zero added vision calls); a `BOR_PDF_PICTORIAL=0` module app → the content is byte-identical to `extract_pdf_text`.
|
||||||
|
- E2E: `tests/e2e/test_pictorial_pdf.py` (new, task 04) — in isolation, mock-only.
|
||||||
|
- Coverage: **>90%** on `app/`.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the owner's `ikea_instructions.tar` imports with described illustration blocks on every sparse page (the integration repro green — the owner's exact file)
|
||||||
|
- [ ] a chat question about the assembly content is grounded on the described pages (the E2E)
|
||||||
|
- [ ] a clean-text PDF never burns a vision call (the zero-candidates no-op is pinned) and a garbage-text PDF still takes the phase-133 fallback unchanged (the precedence pin)
|
||||||
|
- [ ] `BOR_PDF_PICTORIAL=0` → the content is byte-identical to pre-phase
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, TOTAL >90%; `uv run pytest tests/e2e/test_pictorial_pdf.py -v --no-cov` green in isolation; the pre-existing `test_pdf_support.py` / `test_garbage_pdf.py` / `test_pdf_image_context.py` suites green unedited
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] one atomic Conventional Commits commit, `--no-gpg-sign`; phase dir moved to `.agents/phases/complete/`
|
||||||
|
|
||||||
|
## Locked decisions
|
||||||
|
- **A1 — sparse-page detection is the deterministic per-page character threshold (default 100, `BOR_PDF_PICTORIAL_MIN_CHARS`) — no LLM call in the gate (owner-confirmed 2026-09-30, roadmap confirmation).**
|
||||||
|
- **A2 — NO LLM judge: every described sparse page's description appends to the content (owner-selected 2026-09-30).**
|
||||||
|
- **A3 — no page cap, no call budget (PLAN A21); `BOR_PDF_PICTORIAL` kill-switch, default ON (owner-confirmed 2026-09-30).**
|
||||||
|
- **A4 — the description appends to the page block as `[Page N illustration: …]`; the digest is over the final content (the phase-126/133 convention) (owner-confirmed 2026-09-30).**
|
||||||
|
|
||||||
|
## Commit
|
||||||
|
```bash
|
||||||
|
git add app/ tests/ .agents/phases/ && git commit --no-gpg-sign -m "feat(import): pictorial PDF support — sparse pages rendered + vision-described into the indexed content"
|
||||||
|
```
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Task 01 — The kill-switch, the threshold setting, and the sparse-page gate
|
||||||
|
|
||||||
|
**Phase:** `140_pictorial_pdf_pages` · **Source:** `TODO.md:5` — "…We need a way to determine when that's neccesary. …More information is better when generating the text embeddings since that increases the chance the user's search will hit something."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Two settings (the feature toggle + the sparseness threshold) and the pure, deterministic function that selects a PDF's pictorial pages — the TODO's "a way to determine when that's necessary", with no LLM call.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/config.py` — `pdf_pictorial: bool = True` (env `BOR_PDF_PICTORIAL` — the house kill-switch: `0`/`false` disables the pictorial pass entirely; the `images` toggle's naming/docstring pattern at L379) + `pdf_pictorial_min_chars: int = 100` (env `BOR_PDF_PICTORIAL_MIN_CHARS`; a `field_validator`: ≥ 0 — 0 = every page is a candidate (PLAN A21), negative raises with the named field, the house fail-loud pattern). Document both in the `Settings` docstring convention and in `.env.example` (the comment-block pattern of the neighboring settings).
|
||||||
|
2. `app/rag/pdf.py` — `def pictorial_pages(page_texts: dict[int, str], *, min_chars: int) -> list[int]`: the 1-based page numbers whose `len(text.strip()) < min_chars`, ascending — pure; the docstring carries the contract + the IKEA example (`{"1": "BESTÅ", "2": <7 KB of warnings>, "6": "Illustration 6"}` at `min_chars=100` → `[1, 6, …]`).
|
||||||
|
- ASSUMPTION: the threshold is STRICTLY less-than — a page with exactly `min_chars` stripped chars is NOT sparse (the boundary is pinned in the tests).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_pictorial_gate.py` (new) — the validators (0 ok, 100 ok, −1 raises with the named field, the defaults — toggle on, 100) and `pictorial_pages` (the `<`/`=`/`>` boundary, a whitespace-only page → a candidate, an empty dict → `[]`, ascending order, a large dict).
|
||||||
|
- Coverage: **>90%** on the new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_pictorial_gate.py -v` green
|
||||||
|
- [ ] `uv run pytest` green; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Task 02 — The `PICTORIAL_PAGE_MODE` vision seam + the render selector
|
||||||
|
|
||||||
|
**Phase:** `140_pictorial_pdf_pages` · **Source:** `TODO.md:5` — "…Take a screenshot of the first page or pages 8 onward… My suggestion is to screenshot the pdf, generate a text summary… use the screenshot or rendered page rather in addition to the extracted text."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A dedicated, deterministic, fail-soft vision call for one rendered PDF page (the page's own text as context, so the model describes what the text does NOT) — plus the ability to render only the candidate pages of a large PDF.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/summarizer.py` — `PICTORIAL_PAGE_MODE = "PICTORIAL_PAGE_MODE"` + `PICTORIAL_INSTRUCTION` (the locked wording from the phase overview's design) + `PICTORIAL_PROMPT = f"{PICTORIAL_PAGE_MODE}: {PICTORIAL_INSTRUCTION}"` — the marker convention next to `IMAGE_DESCRIPTION_MODE` (L75-95).
|
||||||
|
2. `app/rag/summarizer.py` — `async def describe_pdf_page(llm, *, data: bytes, mime: str, page: int, page_text: str | None, settings: Settings | None = None) -> str | None` — the same one-chat-call multimodal contract as `describe_image` (L208): the user message `[{type: "text", text: PICTORIAL_PROMPT + "\n\nPage {page} of the PDF. Text extracted from this page:\n" + (page_text.strip() or "(none)")}, {type: "image_url", image_url: {url: <data URL from data + mime>}}]` — no system prompt, no tools, no app-level retry; an empty reply → `None` (the house one-shot empty-content policy); a client failure → `None` (fail-soft — one dead page never stalls a sync).
|
||||||
|
3. `app/rag/pdf.py` — `render_pdf_pages(pdf_path, *, dpi: int = 150, pages: Sequence[int] | None = None)`: the optional 1-based selector — render only the named pages, ascending, one PNG each (an unreadable named page → the zero-byte placeholder at its position, as today); `None` = all pages — the phase-133 caller stays byte-identical (its existing tests pin it).
|
||||||
|
4. `tests/e2e/mock_llm.py` — ONE new deterministic branch (house style + a module-header docstring entry): a chat request whose text part contains `PICTORIAL_PAGE_MODE` → the fixed canned reply `PICTORIAL_PAGE_ANSWER` (a distinctive, retrieval-friendly string, e.g. "Pictorial page: the illustration shows two parts being joined with an arrow.") — additive; the `IMAGE_DESCRIPTION_MODE` branch and every existing flow are untouched.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_pictorial_seam.py` (new) — a capturing fake LLM: the message shape (the text part starts with `PICTORIAL_PROMPT`, then the page block; the `"(none)"` case; the image part's data URL from the bytes + mime), `None` on an empty reply and on a client exception, the `DESCRIBE_PROMPT` byte-identity (regression pin — the string is untouched); `render_pdf_pages`' selector (the subset's count + order + PNG magic bytes, `None` = all — a ≥2-page fixture PDF, the phase-126/133 recipe).
|
||||||
|
- Coverage: **>90%** on the new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/unit/test_pictorial_seam.py -v` green
|
||||||
|
- [ ] `uv run pytest` green (the pre-existing vision suites — `test_image_documents.py` et al. — pass unedited)
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Task 03 — The `_index_pdf_file` pictorial pass + the IKEA repro
|
||||||
|
|
||||||
|
**Phase:** `140_pictorial_pdf_pages` · **Source:** `TODO.md:5` — "I've added a new \"ikea_instructions.tar\" to test_sources. This is an example pdf that stil isn't working… We need to support this kind of pdf, and in this case showing rendered pages of the pdf is more helpful than the extracted text… use the screenshot or rendered page rather in addition to the extracted text."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The import pass itself: after the phase-133 garbage gate, a usable-text PDF's sparse pages are rendered + vision-described + appended to the page content — and the owner's exact IKEA file is pinned as an integration regression.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/importer.py` — `_index_pdf_file` (L1140): after the existing phase-133 gate block (the precedence is locked — an unusable layer takes `_fallback_page_screenshots` and the pass NEVER runs), when `settings.pdf_pictorial`: `page_texts = extract_pdf_page_texts(full_path)`; `candidates = pictorial_pages(page_texts, min_chars=settings.pdf_pictorial_min_chars)`; zero candidates → skip entirely (no render, no vision — a clean-text PDF is byte-identical to pre-phase); otherwise render (`render_pdf_pages(full_path, pages=candidates)`, the zero-byte placeholder page skipped with a warning), describe each candidate (`describe_pdf_page`, fail-soft: `None` → a warning + skip the page), and assemble the content: every page = its `PAGE_SEPARATOR` + the page text + `\n\n[Page {n} illustration: {description}]` for the described pages — the assembly with NO descriptions is byte-identical to `extract_pdf_text`'s output (a pin).
|
||||||
|
2. `app/rag/importer.py` — the digest over the FINAL content is the existing code (the pass runs before it, exactly as the phase-133 fallback does); the unchanged early-return, the chunk + embed, and the `lite` summary pipeline are untouched downstream.
|
||||||
|
3. `app/rag/importer.py` — `ImportSummary` (L212): `pdfs_pictorial: int = 0` + `pdf_pictorial_pages: int = 0` — `log()` fields only (the stats log-only convention; the sync `detail` API shape is untouched) + ONE loud log line (PLAN §9): `pdf: pictorial pass source=<s> path=<p> — N candidate pages, M described (min_chars=<threshold>)`.
|
||||||
|
4. `tests/integration/test_importer.py` (extend) — the IKEA repro (the phase-133 real-fixture convention: `test_sources/` is gitignored — extract the tar to `tmp_path`, never the repo; if the tar is absent the test fails loudly with a named message, the owner's machine always has it): run the REAL `import_sources` over the extracted PDF with a fake multimodal LLM (the canned per-page reply; a capturing fake that records every `PICTORIAL_PAGE_MODE` call):
|
||||||
|
- the candidates are computed IN the test from `extract_pdf_page_texts` + `pictorial_pages` (no hardcoded page list — the fixture is stable but the test must not rot);
|
||||||
|
- every candidate page's content block carries `[Page N illustration: <canned>]`; the text-heavy pages (2–5) carry NO block;
|
||||||
|
- the document's chunks carry the canned description (assert the string in the joined chunk text);
|
||||||
|
- the title is "Assembly Instructions" (the PDF metadata);
|
||||||
|
- a second `import_sources` run with the same fake → the file counts `unchanged` (digest stable, ZERO added vision calls);
|
||||||
|
- a `BOR_PDF_PICTORIAL=0` module app → the stored content == `extract_pdf_text`'s output (byte-identical);
|
||||||
|
- a garbage-text PDF (the phase-133 synthetic recipe) with `pdf_pictorial` ON → the phase-133 fallback fires (the content is the full-page descriptions), the pictorial pass does NOT run (the fake records zero `PICTORIAL_PAGE_MODE` calls) — the precedence pin.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `tests/unit/test_pictorial_import.py` (new) — the assembly byte-identity (no descriptions) + the branch matrix (feature off, zero candidates, a fail-soft `None` page, the unreadable-page placeholder skip) with a capturing fake LLM + the synthetic-PDF recipe (the `test_pdf_support.py` pattern).
|
||||||
|
- Integration: the step-4 matrix above.
|
||||||
|
- Coverage: **>90%** on the new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the IKEA tar imports with a description block on every sparse page + `unchanged` on the re-sync (the repro green)
|
||||||
|
- [ ] `uv run pytest tests/unit/test_pictorial_import.py -v` green
|
||||||
|
- [ ] `uv run pytest` green, coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Task 04 — The dedicated E2E (synthetic pictorial PDF, mock-only, in isolation)
|
||||||
|
|
||||||
|
**Phase:** `140_pictorial_pdf_pages` · **Source:** `TODO.md:5` — "…in this case showing rendered pages of the pdf is more helpful than the extracted text… More information is better when generating the text embeddings since that increases the chance the user's search will hit something."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
One dedicated Playwright file, run in isolation (AGENTS.md rules 4/9), proves the owner's scenario end to end: upload a pictorial PDF → sync → the indexed content carries the described page → a chat question grounded on the illustration is answered.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_pictorial_pdf.py` (new) — the `test_pdf_support.py` structure (synthetic-PDF module app, the admin upload flow): build a 2-page PDF with PyMuPDF (the recipe): page 1 = a 500+ char text paragraph; page 2 = an `Illustration 2` line + a drawn vector figure (a rectangle + an arrow — the sparse page); tar it → `POST /api/git-sources/upload` (202) → the Sync button → the document appears on the Sources page:
|
||||||
|
- (a) the document viewer's content shows the page-1 text WITHOUT an illustration block and page 2 WITH `[Page 2 illustration: <the mock's canned PICITORIAL_PAGE_ANSWER>]` (the task-02 `PICTORIAL_PAGE_MODE` branch — deterministic);
|
||||||
|
- (b) a chat question that ONLY the illustration answers (the canned reply names a distinctive phrase — the question: "How are the two parts joined on page two?") → the SSE completes without deflecting (the described page's embedding retrieves — the mock's deterministic token-overlap embeddings make the phrase → description hit) → the `done` event's `sources` includes the PDF and the answer echoes the phrase;
|
||||||
|
- (c) the sync response's `detail` JSON keeps its pre-phase keys (no new field — the stats log-only convention) — a cheap key-set assertion.
|
||||||
|
2. No other file changes (the mock branch shipped in task 02).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: this file, in isolation: `uv run pytest tests/e2e/test_pictorial_pdf.py -v --no-cov` (DB up: `podman compose up -d db`).
|
||||||
|
- Coverage: **>90%** on `app/` (the phase gate runs the full suite in the final pass).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_pictorial_pdf.py -v --no-cov` green in isolation
|
||||||
|
- [ ] the pre-existing `test_pdf_support.py` / `test_garbage_pdf.py` / `test_pdf_image_context.py` suites green unedited
|
||||||
|
- [ ] full gate: `uv run pytest --cov=app --cov-report=term-missing` TOTAL >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Phase 141 — `read` dedupe tells the truth: only fully-covered re-reads are refused
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "From a chat I was having, the LLM is trying to read different ranges of a document and keeps saying: 'The system is telling me the document is already in my context, but I haven't actually seen the full text of the Hail of Thorns spell entry. The read calls keep returning "Already in your context"…' This seems like a critical bug, fix it."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/agent.py` — `AgentHolder` (L1379+: `read_docs` / `read_truncations` / `shown_images` bookkeeping), `_execute_tool`'s `read` branch (L1512+: `_read_range_args` validation ~L1523, the dedupe `known` set ~L1539, the `truncated_shown` map ~L1548, the raw-arg fast path ~L1557, the range-read dedupe check ~L1577, the `read_docs` append ~L1600, the result shapes ~L1630+), the refusal texts `ALREADY_IN_CONTEXT` (L519), `REREAD_TRUNCATED` (L600), `OFFSET_PAST_END` (L616); `tests/unit/test_agent.py` (the read-branch unit suite — the phase-131 dedupe-matrix pins); `tests/e2e/mock_llm.py` (`_READ_RESULT_PREFIX` L1412 — the first-line header contract the mock parses), `tests/e2e/test_read_line_ranges.py` (the phase-131 flow). Root cause: `known` (the `read_docs` pair set) records ANY successful read — including a RANGE read — as if the FULL document were in context; the phase-131 matrix's "range read + doc in `known` + not truncated → `ALREADY_IN_CONTEXT`" row is false whenever the earlier read was a range (only the slice reached the model), so every attempt to read a DIFFERENT range is refused with a claim that the full text is in the prompt.
|
||||||
|
**Locked (owner-confirmed 2026-09-30, chat):** coverage-tracking dedupe — a range read proceeds unless the requested lines are FULLY covered by earlier reads; a plain re-read of a partially-covered document gets the "you have lines a–b — read the rest with `offset`/`limit`" teaching instead of the false `ALREADY_IN_CONTEXT`.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The agent stops dead-ending on multi-range documents: the holder tracks exactly WHICH line ranges of each document are in the model's context, the dedupe matrix refuses only genuinely-covered re-reads (now with a truthful claim), and the owner's stuck scenario — grep → read range A → read range B of the same document — completes with both ranges in context.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `140_pictorial_pdf_pages` (complete) — pipeline order only; code dependencies are the completed agent surface (phases 37/70/72/95/118/131/139).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Coverage state (task 01):** `AgentHolder` gains `read_coverage: list[tuple[str, str, int, int]]` — one `(source, path, first_line, last_line)` record per covered span, in read order, keyed by the RESOLVED pair (the phase-131 `truncated_shown` keying lesson: the raw-arg split and the resolved pair are the same pair by the `_resolve_path` first-slash contract, L1229+). Coverage recording:
|
||||||
|
- a plain read at-or-under-cap covers `(1, total_lines)`;
|
||||||
|
- a truncated plain read (char cap) covers `(1, the number of lines in content[:cap])` (counted from the actual cut, not derived from the char count);
|
||||||
|
- a range read covers `(first, end)` — the TRUE extent the `lines: {first}-{end} of {total}` header already reports (an overshooting `limit` is clamped); a truncated range read covers `(first, the last line inside slice[:cap])` the same way.
|
||||||
|
`read_docs` / `read_truncations` keep their EXACT current meaning (API-layer signal, SSE matching, per-turn log) — the coverage list is NEW state beside them, not a replacement.
|
||||||
|
- **Dedupe matrix (task 02)** — `covered(a, b)` = the requested span is contained in the union of that document's coverage records (merge overlapping/adjacent spans first; containment is per-line, inclusive):
|
||||||
|
| call | coverage of the doc | result |
|
||||||
|
|---|---|---|
|
||||||
|
| plain `read(path)` | empty | full read (unchanged) |
|
||||||
|
| plain `read(path)` | full doc covered (1–total) | `ALREADY_IN_CONTEXT` (byte-identical line) |
|
||||||
|
| plain `read(path)` | partial | NEW/retargeted teaching: the covered span(s) named, "read the rest with `offset`/`limit`" (the `REREAD_TRUNCATED` role — generalized: `REREAD_TRUNCATED` is RETIRED as the partial-plain-read line, its char-based copy replaced by the line-based one) |
|
||||||
|
| `read(path, offset, limit)` | empty | range read (unchanged) |
|
||||||
|
| `read(path, offset, limit)` | requested span fully covered | `ALREADY_IN_CONTEXT` — now TRUE (the named lines ARE in the prompt) |
|
||||||
|
| `read(path, offset, limit)` | not fully covered | range read PROCEEDS (the owner's stuck-scenario fix — includes the phase-131 truncated-then-range row, which the coverage state now covers: a truncated first read covers only its shown lines) |
|
||||||
|
The `BAD_RANGE_ARGS` and `OFFSET_PAST_END` refusals keep their exact firing order (before dedupe / after resolve respectively). The raw-arg fast path (no DB lookup) survives for the rows answerable from holder state alone (full-coverage plain re-read, fully-covered range — the `total_lines` for the latter's `OFFSET_PAST_END` still needs the resolve).
|
||||||
|
- **Prompt consistency (task 02, step 4):** `TOOLS_SECTION`'s re-read sentence ("Do not re-read a document you have already read — its full text is already in your prompt") is re-cut to the coverage-true form (read-IN-FULL docs: don't re-read; PARTIAL docs — range/truncated reads: read the other parts with `offset`/`limit`). Without this the model is still taught the pre-phase rule and would not bother trying the second range that task 02 now allows.
|
||||||
|
- **Repro (task 03):** unit matrix (every row above, incl. truncated variants and span-merge edges) + an integration test of the owner's scenario verbatim in spirit: one document, grep → read range A → read range B → both ranges' content reach the model, then a third read of range A is refused with `ALREADY_IN_CONTEXT`.
|
||||||
|
- **E2E (task 04):** `tests/e2e/mock_llm.py` gains ONE scripted flow (house style — user-message marker, module-header docstring entry): the marker `read two ranges` → request 1 a `read(path, offset, limit)` call, request 2 a SECOND `read` with a DIFFERENT offset on the same doc, request 3 the answer echoing a marker line from the second range (proving the second slice reached the model). `tests/e2e/test_read_range_dedupe.py` (dedicated, in isolation, mock-only): a KB fixture with ONE large doc carrying two distinct marker lines far apart; ask the marker question → assert both `read` tool frames succeeded (no refusal in the result surface) and the final answer echoes the second marker line.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_coverage_tracking.md` — `AgentHolder.read_coverage` + the coverage recording in the read branch.
|
||||||
|
2. `02_dedupe_matrix_rework.md` — the new matrix, the generalized partial-read teaching, `REREAD_TRUNCATED` retirement.
|
||||||
|
3. `03_two_range_repro.md` — the full unit matrix + the owner-scenario integration repro.
|
||||||
|
4. `04_e2e_mock_flow.md` — the mock `read two ranges` flow + the dedicated E2E file.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the full 6-row matrix with truncated variants; span-merge edges (adjacent, overlapping, contained, disjoint spans); coverage recording for all four read outcomes; the refusal-text pins; the fast-path no-DB rows.
|
||||||
|
- Integration: the two-range repro (task 03) — the owner's stuck scenario end-to-end through `run_agent`'s loop.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] two DIFFERENT ranges of the same document both reach the model (the owner's bug is gone); a re-read of fully-covered lines is still refused — with a claim that is now true
|
||||||
|
- [ ] a plain re-read of a partially-covered document gets the "read the rest with `offset`/`limit`" teaching (the false full-text claim is gone in BOTH refusal directions)
|
||||||
|
- [ ] plain-read results at-or-under-cap and the phase-131 result shapes are byte-identical (the existing pins pass unchanged)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_read_range_dedupe.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the grep/ls surfaces, the truncation notice, the `read_docs`/`read_truncations` API signals)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Task 01 — coverage tracking: which lines of each document are actually in the model's context
|
||||||
|
|
||||||
|
**Phase:** `141_read_range_dedupe_fix` · **Source:** `TODO.md:3` — "From a chat I was having, the LLM is trying to read different ranges of a document and keeps saying: 'The system is telling me the document is already in your context, but I haven't actually seen the full text of the Hail of Thorns spell entry. The read calls keep returning "Already in your context"…' This seems like a critical bug, fix it."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`AgentHolder` records, per document, exactly which line spans a successful `read` put in the model's context — the state the reworked dedupe matrix (task 02) decides on. No dedupe behavior changes in THIS task (task 02 does that); this task only adds the recording, so the suite stays green throughout.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/agent.py` — `AgentHolder` (L1379+): add `read_coverage: list[tuple[str, str, int, int]]` = one `(source, path, first_line, last_line)` record per covered span, in read order, keyed by the RESOLVED pair (the `_resolve_path` first-slash contract, L1229+ — the same pair `read_docs` keys on; the phase-131 `truncated_shown` keying comment ~L1546 is the precedent for why the raw-arg split and the resolved pair agree). Document the field on the dataclass docstring (the `read_truncations` doc-block style, L1386+): spans are inclusive line numbers over `content.splitlines()`; one span per SUCCESSFUL read (a refused read records nothing — the refusal style of every refusal: counts in nothing).
|
||||||
|
2. `app/rag/agent.py` — the read branch's four successful outcomes record their span (the `total_lines`/`end`/`first` locals already exist at the record sites, ~L1610+):
|
||||||
|
- plain read at-or-under-cap (~L1655): `(1, total_lines)`;
|
||||||
|
- truncated plain read (~L1636): `(1, len(doc.content[:cap].splitlines()))` — counted from the ACTUAL cut string (the last visible line is the one ending at or before `cap`; `splitlines()` on the cut is the truth — do not derive a line count from the char count);
|
||||||
|
- range read at-or-under-cap (~L1686): `(first, end)` — the TRUE extent the `lines: {first}-{end} of {total}` header reports (an overshooting `limit` is already clamped at ~L1678);
|
||||||
|
- truncated range read (~L1668): `(first, the last line fully inside slice[:cap])` — `len(slice_text[:cap].splitlines())` added to `first - 1`, clamped to `end` (a cut mid-line means that line is NOT fully in context — the span ends at the last COMPLETE line).
|
||||||
|
3. `tests/unit/test_agent.py` — unit tests: each of the four outcomes records exactly its span (assert the holder list after the call); a refused call (bad range args, unknown doc, offset past end, already-covered) records NOTHING; spans are keyed by the resolved pair (a doc read through its canonical `source/path` argument); existing `read_docs` / `read_truncations` assertions pass UNCHANGED (those signals are byte-identical).
|
||||||
|
|
||||||
|
- ASSUMPTION: the covered-line count for a truncated read is computed from the cut string's `splitlines()` (inclusive, whole lines only) — a trailing cut line that ends exactly at `cap` counts as covered; the char cap is never re-derived into lines arithmetically. (The TODO item left the counting rule open; whole-line containment is what makes "fully covered" checkable per line.)
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the four record sites + the five no-record refusals + resolved-pair keying (above); every pre-existing read-branch test passes unchanged.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] every successful read shape appends exactly one coverage span with the lines documented above; refusals append nothing
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the holder's existing fields, the result strings, the SSE frames)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Task 02 — the dedupe matrix rework: refuse only what is truly already in context
|
||||||
|
|
||||||
|
**Phase:** `141_read_range_dedupe_fix` · **Source:** `TODO.md:3` — "From a chat I was having, the LLM is trying to read different ranges of a document and keeps saying: 'The system is telling me the document is already in my context, but I haven't actually seen the full text of the Hail of Thorns spell entry. The read calls keep returning "Already in your context"…' This seems like a critical bug, fix it."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The read branch decides dedupe from the coverage state (task 01) instead of the pair set alone: a range read proceeds unless its lines are fully covered, a plain re-read of a partially-covered document is taught the "read the rest" path, and `ALREADY_IN_CONTEXT` fires only when its claim is true.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/agent.py` — a small coverage helper beside `_read_range_args` (L1490+): `covered_spans(records, source, path)` → the merged span list for one doc (merge overlapping/ADJACENT spans — `(1,10)+(11,20)` → `(1,20)` — so adjacency counts as continuous coverage), and `fully_covered(spans, first, last)` → bool (the requested span inside the merged union, per-line, inclusive). Pure functions over holder state — no DB.
|
||||||
|
2. `app/rag/agent.py` — rework the read branch's dedupe (L1539+), keeping the firing ORDER of the other refusals:
|
||||||
|
- the `BAD_RANGE_ARGS` check stays FIRST (before any dedupe — a bad range arg is refused regardless of context, phase-131 contract);
|
||||||
|
- the raw-arg fast path is RETIRED: whether a span is "full" needs the document's `total_lines`, which only the resolve knows — so EVERY dedupe row resolves the doc first (one cheap indexed lookup; the pre-phase fast path's only saving was that one query, and the owner's bug — a false refusal costs a whole stuck turn — is what forces the trade). After the resolve: `total_lines = len(doc.content.splitlines())`, then the matrix below runs against `(doc.source, doc.path, total_lines)` and the coverage state. A fully-covered PLAIN re-read — the only row the old fast path handled — still refuses with the byte-identical `ALREADY_IN_CONTEXT`; its implementation just goes through the resolve.
|
||||||
|
- matrix (the phase-131 table in 00_phase.md is authoritative):
|
||||||
|
| call | coverage | result |
|
||||||
|
|---|---|---|
|
||||||
|
| plain | empty | full read (the existing at-or-under-cap / truncated paths, untouched bytes) |
|
||||||
|
| plain | full doc (a merged span == `(1, total_lines)`) | `ALREADY_IN_CONTEXT` (byte-identical line, L519) |
|
||||||
|
| plain | partial | the NEW teaching line (below) |
|
||||||
|
| range | empty | range read (existing bytes) |
|
||||||
|
| range | requested `(first, end)` fully covered | `ALREADY_IN_CONTEXT` |
|
||||||
|
| range | not fully covered | range read PROCEEDS (the owner's fix) |
|
||||||
|
- the `OFFSET_PAST_END` refusal (L616, firing after the resolve, before the matrix's range rows) stays where it is — an offset past the end is refused regardless of coverage.
|
||||||
|
3. `app/rag/agent.py` — the partial-plain-read teaching: RETIRE `REREAD_TRUNCATED` (L600 — its char-based `{shown}` copy is replaced) and add `REREAD_PARTIAL`: one line, same refusal contract (counts in nothing, consumes a round, no re-emit), the covered span(s) named in line form and the working workflow pointed at: "You have lines {covered} of {source}/{path} in your context ({total} lines total). To read the rest, find where your text is with grep (it reports line numbers), then call read with `offset` (1-based first line) and `limit` (number of lines)." — `{covered}` renders the merged spans as comma-joined `a–b` pairs (one span → the bare `a–b`; a single line → `a`). The phase-131 truncated-then-plain-read scenario lands on THIS line now (a truncated first read covers a partial span) — same teaching role, line-based truth.
|
||||||
|
4. `app/rag/prompts.py` — `TOOLS_SECTION`'s re-read sentence stays consistent with the new semantics: "Do not re-read a document you have already read — its full text is already in your prompt; answer directly from it." becomes the coverage-true form: do not re-read a document you have already read IN FULL — its full text is in the prompt, answer from it — but if you have read only PART of a document (a range read, or a truncated read), read the other parts with `offset`/`limit` — the document is not complete in your context until you have read it all. The sentence stays in its current position (the `read` clause); the mock keys off the `<tools>` marker's PRESENCE, not the wording (the phase-37 contract), so the mock is untouched. The HIGH prompt's byte-identity pins that assert the OLD sentence are re-pinned to the new one (the section's other bytes are unchanged).
|
||||||
|
5. `tests/unit/test_agent.py` — re-pin the dedupe matrix (the phase-131 pins that asserted the OLD matrix's "range + known + not truncated → ALREADY_IN_CONTEXT" row are the ones that change — every other pin, incl. byte-identical result strings for plain reads, `BAD_RANGE_ARGS`, `OFFSET_PAST_END`, `MISSING_READ_ARGS`, the no-document refusals, passes unchanged):
|
||||||
|
- the 6 matrix rows × {truncated, non-truncated first read} where defined;
|
||||||
|
- the partial-plain-read line: span rendering (one span, multiple merged spans, a single line), `{total}` from the real doc;
|
||||||
|
- span-merge edges: adjacent spans merge (coverage contiguous), overlapping spans merge, disjoint spans stay separate (a gap → the requested span spanning the gap is NOT fully covered → proceeds);
|
||||||
|
- the fast-path retirement: a plain re-read of a fully-covered doc still refuses with the byte-identical `ALREADY_IN_CONTEXT` (the row's observable contract is unchanged; its implementation now resolves first).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the full matrix + edges above; the refusal-text pins (`ALREADY_IN_CONTEXT` byte-identical; `REREAD_PARTIAL` exact copy); the pre-existing read-branch suite minus the re-pinned rows.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a range read of a document earlier read ONLY as a different range proceeds (the owner's bug); a range read of fully-covered lines is refused with `ALREADY_IN_CONTEXT`
|
||||||
|
- [ ] a plain re-read of a partially-covered document gets `REREAD_PARTIAL` with the true covered span(s); `REREAD_TRUNCATED` no longer exists
|
||||||
|
- [ ] every byte-identical pin that is NOT re-pinned in task 02's matrix changes passes unchanged; `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work outside the documented matrix rows
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 03 — the owner's stuck scenario, proven: two ranges of one document both reach the model
|
||||||
|
|
||||||
|
**Phase:** `141_read_range_dedupe_fix` · **Source:** `TODO.md:3` — "From a chat I was having, the LLM is trying to read different ranges of a document and keeps saying: 'The system is telling me the document is already in my context, but I haven't actually seen the full text of the Hail of Thorns spell entry. The read calls keep returning "Already in your context"…' This seems like a critical bug, fix it."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The bug the owner hit is locked as a test: an agent turn that greps, reads range A of a large document, then reads range B — both ranges' content reach the model and the answer can cite both — and a third read of range A is refused with the (now true) `ALREADY_IN_CONTEXT`.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/integration/` (the read-branch integration home — the phase-131 handbook repro lives in the unit/integration suite per `.agents/phases/complete/131_read_line_ranges/03_handbook_repro.md`; follow that file's fixture conventions) — the two-range repro:
|
||||||
|
- fixture: ONE text document, ≥ 200 lines, with two distinct marker lines far apart (marker A near line ~50, marker B near line ~150) — the document's content is GENERATED in the test (no binary fixture; the handbook repro is the separate phase-131 asset, untouched);
|
||||||
|
- settings: `read_max_chars` high enough that the FULL document is under the cap is NOT the point — run BOTH variants: (a) doc under the cap (the pure dedupe case — the pre-phase code refused range B with `ALREADY_IN_CONTEXT`), (b) doc over the cap with a truncated first plain read (the phase-131 row, now via coverage: the range B read proceeds, the plain re-read gets `REREAD_PARTIAL`);
|
||||||
|
- scripted fake LLM (the `tests/unit/test_agent.py` round-shape pattern): round 1 → `read(path, offset=1, limit=40)` (range A); round 2 → `read(path, offset=<marker B's line − 10>, limit=30)` (range B); round 3 → `read(path, offset=1, limit=40)` again (the exact re-covered range A); round 4 → the answer echoing BOTH marker lines (the read-echo convention — the model can only echo what reached it).
|
||||||
|
- asserts: round 2's result is the range-B slice (its `lines:` header + the marker-B line present — NOT a refusal); round 3's result is `ALREADY_IN_CONTEXT`; round 4's echoed answer contains BOTH markers (the bug: pre-phase, the echo could contain only marker A).
|
||||||
|
2. `tests/unit/test_agent.py` — the matrix unit coverage from task 02 that is scenario-shaped rather than row-shaped: the adjacent-span edge as a scenario (two reads that together cover 1–100 of a 200-line doc → a plain re-read gets `REREAD_PARTIAL` naming `1–100`, and `read(offset=101)` proceeds).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Integration: the two-range repro (both variants) — the owner's scenario end-to-end through the agent loop.
|
||||||
|
- Unit: the scenario-shaped matrix edges above.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the two-range repro passes: range B's slice reaches the model after range A; the exact re-read of range A is refused; the final answer echoes both markers
|
||||||
|
- [ ] the truncated-variant passes: after a truncated first plain read, the range read proceeds and the plain re-read gets `REREAD_PARTIAL`
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the repro is additive; no existing test file is modified)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 04 — the mock `read two ranges` flow + the dedicated E2E
|
||||||
|
|
||||||
|
**Phase:** `141_read_range_dedupe_fix` · **Source:** `TODO.md:3` — "From a chat I was having, the LLM is trying to read different ranges of a document and keeps saying: 'The system is telling me the document is already in my context, but I haven't actually seen the full text of the Hail of Thorns spell entry. The read calls keep returning "Already in your context"…' This seems like a critical bug, fix it."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The browser-visible proof: the deterministic mock LLM drives a two-range turn, and the dedicated Playwright file asserts that both `read` tool frames succeed and the final answer carries content from the SECOND range — the owner's stuck scenario, end-to-end through the SSE stream.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/mock_llm.py` — ONE scripted flow, house style (a user-message marker; a module-header docstring entry like the phase-131 `read the lines` flow):
|
||||||
|
- marker: the user message contains `read two ranges`;
|
||||||
|
- request 1: a `read` tool call `{path: <the fixture doc>, offset: 1, limit: 100}`;
|
||||||
|
- request 2 (a `tool`-role read result whose FIRST line starts with `_READ_RESULT_PREFIX` (L1412) and which carries a `lines: 1-100 of …` header): a SECOND `read` tool call on the SAME doc with `{offset: 101, limit: 100}` — the pre-phase server would have answered the first read fine and refused the second; the flow only works if the second proceeds;
|
||||||
|
- request 3 (the second read result present — assert its `lines: 101-…` header to keep the mock's own keying honest): the answer "Both parts read." + the first 80 chars of the SECOND read result (the existing read-echo shape — the marker line lives in range B, so an echo of it proves the slice reached the model).
|
||||||
|
2. `tests/e2e/test_read_range_dedupe.py` — dedicated Playwright file, run in isolation, mock-only (the house fixture conventions of `tests/e2e/test_read_line_ranges.py` — truncate/re-import per module, `?v=` asset pins, the SSE assertion helpers):
|
||||||
|
- the KB fixture: ONE large text document (> 100 lines; range A lines 1–100 carry marker line `TWO_RANGES_A_LINE` near line ~50, range B lines 101+ carry marker line `TWO_RANGES_B_LINE` near line ~150);
|
||||||
|
- test 1: ask the `read two ranges` question → collect the SSE frames → assert exactly the two `tool` frames (both `read`, the second carrying `offset: 101`), NO refusal surface in either tool result (the results carry the `lines:` headers, not `Already in your context`), and the final `done` answer contains `TWO_RANGES_B_LINE`'s text;
|
||||||
|
- test 2 (the still-refused row, browser-visible): a second scripted marker flow is NOT added — instead reuse the phase-131 `read the lines` flow's existing E2E expectations (they still pass: the single-range behavior is unchanged) and add a focused integration-level assertion in `tests/unit/test_agent.py` if the mock surface can't express a refusal cleanly — the E2E's job is the HAPPY two-range path; the refusal row is unit-pinned in tasks 02/03.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: `uv run pytest tests/e2e/test_read_range_dedupe.py -v --no-cov` — green IN ISOLATION (DB up: `podman compose up -d db`), mock-only.
|
||||||
|
- Regression: `tests/e2e/test_read_line_ranges.py` + `tests/e2e/test_read_range_tool_lines.py` + `tests/e2e/test_read_truncation_cap.py` still pass in isolation (the phase-95/131/139 contracts).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the mock flow's second range read succeeds through the real server (no refusal) and the answer echoes the second range's marker line
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_read_range_dedupe.py -v --no-cov` green in isolation; the three pre-existing read E2E files still green in isolation
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the mock's pre-existing flows are byte-identical; the new flow is additive)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Phase 142 — the KB overview stays fresh: newest documents survive the cap, and the model is told the outline is partial
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L4 — "The agent is really struggling with questions like 'Summarize the last 10 phases of brain of Reese'. When I asked that to the current deployment it said 'I'll pull the details for the last 10 phases (104–113).' when it clearly had phase 137 loaded in the RAG… 'The <knowledge_base> section in the system prompt only generated summaries up to phase 113 at import time. The phases 128–137 exist as full markdown files… but their summaries weren't included in the initial KB index. This is a KB sync/generation gap, not a retrieval logic bug.'"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/overview.py` — `regenerate_overview` (the document-list query `order_by(Document.source, Document.path)` ~L232, best-effort change-gated per the module docstring), `build_overview_prompt` (one line per doc `source — path — title — {first summary line}`, capped at `max_chars` with the shared `TRUNCATION_MARKER`), `load_kb_overview`; `app/config.py` L216 — `overview_input_max_chars` (`BOR_OVERVIEW_INPUT_MAX_CHARS`, default 40 000); `app/rag/prompts.py` — `_KB_INTRO` (L128–132: literally says "(generated at import time)") and `build_kb_section` (L399+); `app/api/sync.py` ~L590 — the overview regeneration gate (`summary.added + summary.updated > 0` — the sync IS change-gated correctly; the staleness is inside the generation, not the trigger); `tests/e2e/test_kb_overview.py` (the mock's `KB_OVERVIEW_MODE` digest = first 8 tokens of the document list — ORDER-DEPENDENT, must be re-pinned), `tests/integration/test_import_docs_overview.py` (the import-time trigger), `app/models.py` — `Document.created_at` (L123 — the DOCUMENT's date, phase 106: git-history/mtime-derived and owner-correctable, the same date the `read` result's `date:` line shows — the "when is this document from" signal, exactly what "the last N …" means). Root cause (traced): on the owner's 1 000-doc KB the document list is ≈100k+ chars; the 40k cap cuts a LEXICOGRAPHIC prefix (`order_by (source, path)` — "113_…" sorts before "128_…", and "131_…"–"140_" sort after "13_…"), so the newest phases never reach the lite model and the stored outline confidently describes a KB that ends mid-11x; the model then anchors "the last 10 phases" on that stale image.
|
||||||
|
**Locked (owner-confirmed 2026-09-30, chat):** recency ordering (newest documents first so they survive the cap; the cap itself is unchanged) + the honest `<knowledge_base>` intro (drops "(generated at import time)"; tells the model the outline is compact/possibly partial and to verify "latest/complete" questions with `ls`/`grep` first). No map-reduce rewrite this phase.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
"Summarize the last 10 phases" stops being a guess: the overview's input is ordered newest-first so recent documents are the ones the outline covers when the cap bites, and the `<knowledge_base>` intro stops teaching the model that a partial outline is the whole KB — it now says the outline is a possibly-partial picture and points at `ls`/`grep` for "what's the latest / the complete set" questions.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `141_read_range_dedupe_fix` (todo) — pipeline order only; no code dependency.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Ordering (task 02):** `regenerate_overview`'s query becomes `order_by(Document.created_at.desc(), Document.source, Document.path)` — newest documents FIRST (`created_at` is the document's date per phase 106 — the same date the `date:` line in a read result shows; the owner's phase-128–137 files carry newer git dates than the 113-era files, so they lead the list and survive the cap). The (source, path) secondary keys keep the tie-break deterministic for same-date docs (the common case within one commit/import — those fall back to the old lexicographic order, so same-date fixtures stay byte-identical). The cap (`BOR_OVERVIEW_INPUT_MAX_CHARS`, default 40 000) and the cap's cut+`TRUNCATION_MARKER` behavior are UNCHANGED (house truncation convention; the env knob stays the owner's lever). Zero other call-site changes: the sync's change-gate (task-31/32 trigger) already regenerates whenever the KB changes — the staleness was purely inside the list.
|
||||||
|
- **Intro (task 03):** `_KB_INTRO` rewritten (it is a prompt constant — PLAN §4's convention: persona/prompt text changes ship with the phase's prompt tests; the `<knowledge_base>` TAG and the section's cap behavior in `build_kb_section` stay byte-stable): the outline is a COMPACT, possibly partial picture of the KB that favors RECENT documents — and for questions about the latest state or the complete set ("the last N …", "everything about …"), verify with `ls` (drill down) / `grep` before answering from the outline. One short paragraph, same tone as `SUGGEST_INTRO` (L152).
|
||||||
|
- **Repro (task 01):** before any fix, a failing test proves the traced root cause: `build_overview_prompt` given a doc list whose joined lines exceed `max_chars` keeps the lexicographic FIRST lines and drops the last; and (integration) a KB where the newest docs' paths sort lexicographically LAST is regenerated with the pre-fix ordering → the stored outline (the mock's 8-token digest) names the OLD docs, not the new ones. The repro is written against the CURRENT code (red), then tasks 02/03 flip it green.
|
||||||
|
- **E2E (task 04):** dedicated file — a fixture KB whose document count × line length exceeds a FORCED small cap (`BOR_OVERVIEW_INPUT_MAX_CHARS` set low via the E2E settings fixture) → regenerate through the mock → the stored outline's digest tokens come from the NEWEST document (recency ordering visible end-to-end through the real prompt path), and the served chat prompt's `<knowledge_base>` section carries the NEW intro copy (asserted from the echo path or the direct prompt-build surface — the phase-31 E2E already exposes the section to the UI via the first-bullet echo).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_cap_ordering_repro.md` — the red repro tests (unit: cap keeps the lexicographic prefix; integration: newest-sorting-last docs missing from the regenerated outline).
|
||||||
|
2. `02_recency_ordering.md` — the `created_at.desc()` ordering + the order-dependent digest re-pins.
|
||||||
|
3. `03_honest_kb_intro.md` — the `_KB_INTRO` rewrite + the prompt tests.
|
||||||
|
4. `04_e2e_outline_freshness.md` — the dedicated E2E (forced cap → newest doc in the outline; the new intro served).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: `build_overview_prompt` cap behavior unchanged (the cut + marker, the pathological budget); the new ordering (regeneration with mixed `created_at` docs → newest first; same-date tie-break by (source, path)); the intro copy pin.
|
||||||
|
- Integration: the import-time trigger still regenerates exactly on KB change (the pre-existing `tests/integration/test_import_docs_overview.py` green); the repro flipped green.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only; `tests/e2e/test_kb_overview.py` (phase 31) green with re-pinned digest.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] with the cap forced, the regenerated outline is built from the NEWEST documents (the 1 000-doc "ends at phase 113" failure mode is gone: the newest sort-last docs are the ones represented)
|
||||||
|
- [ ] the served `<knowledge_base>` section carries the new honest intro (no "(generated at import time)"; the verify-with-`ls`/`grep` teaching present)
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_kb_overview_freshness.py -v --no-cov` green in isolation; `tests/e2e/test_kb_overview.py` still green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the cap env knob, the change-gated trigger, the `build_kb_section` cap/marker behavior, the deflect path)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 01 — the red repro: the cap keeps a lexicographic prefix, so newest docs are the ones lost
|
||||||
|
|
||||||
|
**Phase:** `142_kb_overview_freshness` · **Source:** `TODO.md:4` — "The agent is really struggling with questions like 'Summarize the last 10 phases of brain of Reese'. When I asked that to the current deployment it said 'I'll pull the details for the last 10 phases (104–113).' when it clearly had phase 137 loaded in the RAG… this is a KB sync/generation gap, not a retrieval logic bug."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Lock the traced root cause as failing tests BEFORE the fix: `build_overview_prompt` cuts the document list at the cap keeping the FIRST lines (which, under the current `order_by (source, path)`, are the lexicographically first — NOT the newest), and a regeneration on a KB whose newest documents sort lexicographically LAST produces an outline that names the old documents. These tests are red on the current code and turn green in tasks 02/03.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/unit/test_overview.py` (the phase-31 unit home — if the overview units live elsewhere, e.g. inside `tests/unit/test_agent.py`'s neighbors, use the existing file for `build_overview_prompt`'s pins) — the cap-ordering repro, unit level, no LLM:
|
||||||
|
- build 20 fake doc rows whose `source — path` prefixes are `s — 01_old_a.md` … `s — 20_new_z.md` (a path ordering that ALSO puts the "newest" last — the owner's phase-dir shape: names like `113_…` vs `128_…` vs `131_…`), each line ~100 chars, `max_chars=500` → the prompt's user message holds ONLY the first lines (assert: `01_old_a` present, `20_new_z` ABSENT, the `TRUNCATION_MARKER` line present — the current behavior pinned as-is);
|
||||||
|
- the assertion this task ADDS is the one that will flip: a helper-level check that documents the INTENT — the list reaching the model should lead with the NEWEST rows — written as the expected post-fix order (fails pre-fix).
|
||||||
|
2. `tests/integration/test_import_docs_overview.py` (or its sibling for regeneration — the file that already drives `regenerate_overview` against the mock) — the KB-shape repro, integration level:
|
||||||
|
- a fixture KB shaped like the owner's: one source, folders/paths whose names sort lexicographically BEHIND their content's recency (e.g. an `old/…` batch + a `zz_new/…` batch whose paths sort LAST). The batches' `created_at` (the document date — phase 106 derives it from the file's mtime for a local fixture) must differ: set the files' mtimes (`os.utime`) before import so the old batch is genuinely older, OR update the old batch's `created_at` to a past date in a raw SQL step after import — the test owns its fixture, either seam is fine,
|
||||||
|
- regenerate through the mock `KB_OVERVIEW_MODE` (the 8-token digest of the document list, `tests/e2e/mock_llm.py` ~L2906) with a small `BOR_OVERVIEW_INPUT_MAX_CHARS` so the cap bites,
|
||||||
|
- assert the CURRENT failure: the stored outline's tokens come from the lexicographically-first (oldest) documents, NOT the newest — the exact "summaries only up to phase 113" shape, reproducible in a test.
|
||||||
|
- Mark both tests with the outcome they expect POST-fix (newest docs win); they FAIL now — that red is the repro. (Task 02 makes them green.)
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: the two repro tests above — RED on the current code (asserted by running them in this task), green after task 02 (+ task 03 for the intro).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (tests — coverage applies to `app/` as a whole).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the two repro tests exist and FAIL on the pre-fix code for the documented reason (lexicographic-prefix cap; oldest docs in the outline) — the failure output names the root cause
|
||||||
|
- [ ] no application code changed in this task (the repro is tests-only)
|
||||||
|
- [ ] the rest of `uv run pytest` stays green (the repro tests are the only new failures)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Task 02 — recency ordering: newest documents first in the overview's input
|
||||||
|
|
||||||
|
**Phase:** `142_kb_overview_freshness` · **Source:** `TODO.md:4` — "The agent is really struggling with questions like 'Summarize the last 10 phases of brain of Reese'. When I asked that to the current deployment it said 'I'll pull the details for the last 10 phases (104–113).' when it clearly had phase 137 loaded in the RAG… this is a KB sync/generation gap, not a retrieval logic bug."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`regenerate_overview` builds the lite model's document list newest-first, so when `BOR_OVERVIEW_INPUT_MAX_CHARS` cuts the list, the documents that fall off are the OLDEST — and the outline (the model's a-priori KB picture) always represents the recent state of the KB. Task 01's red repro turns green.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/overview.py` — `regenerate_overview`'s document-list query: `order_by(Document.created_at.desc(), Document.source, Document.path)`. Update the query's inline comment + the module docstring (the "one line per document" description): the ordering is RECENT-FIRST by the DOCUMENT's date (phase 106's `created_at` — git-history/mtime-derived, owner-correctable, `created_at_manual` rows included exactly as stored: the ordering reads the column, it never re-derives dates; the (source, path) tie-break keeps same-date docs in the old lexicographic order — deterministic for the mock's digest, and byte-identical for single-date fixtures). The cap, the cap's cut + `TRUNCATION_MARKER`, the zero-docs no-op, the `LLMError` fail-soft, the upsert — ALL unchanged.
|
||||||
|
2. `tests/unit/test_overview.py` — the unit pins:
|
||||||
|
- the task-01 cap test flips: with mixed `created_at` rows (the row shape `(source, path, title, summary)` is order-agnostic — the ORDER comes from the query, so the unit test for the QUERY ordering goes against the DB: a small session with 6 docs in two `created_at` batches → the SELECT returns newest batch first, (source, path) within a batch),
|
||||||
|
- the byte-identical pins for `build_overview_prompt` itself are UNTOUCHED (it still receives rows in whatever order the caller passes — its contract is order-preserving; only the CALLER's order changes).
|
||||||
|
3. `tests/integration/test_import_docs_overview.py` — the integration repro flips green: the second (newer) import batch's paths now lead the digest.
|
||||||
|
4. Re-pin the ORDER-DEPENDENT digest expectations that assumed the old order (the mock's 8 tokens are the first document line's tokens — under recency-first that is now the NEWEST doc's line):
|
||||||
|
- `tests/e2e/test_kb_overview.py` — `test_mock_generated_outline_is_stored_and_echoed`'s expected digest (compute it from the fixture's newest document, not the lexicographic first — the test's fixture documents and their `created_at` values decide; the test seeds its row directly for tests 1–3, so only test 4's regeneration digest is order-sensitive),
|
||||||
|
- any other pin asserting a specific first line of a regenerated overview (grep the suite for the digest literal — re-pin where the KB has more than one document with differing `created_at`; single-batch fixtures where every doc shares a `created_at` stay byte-identical by the (source, path) tie-break).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit/integration: the ordering tests + the flipped repro (task 01) + the re-pinned digests.
|
||||||
|
- Regression: the phase-31 `KB_OVERVIEW_MODE` branch in `tests/e2e/mock_llm.py` is UNCHANGED (it digests whatever list the app sends — the mock is order-agnostic by construction); `tests/e2e/test_kb_overview.py` green in isolation after the re-pins.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] task 01's two repro tests are GREEN (the newest documents lead the capped list; the outline represents the recent KB)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run pytest tests/e2e/test_kb_overview.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases beyond the list ORDER (the cap env knob, the trigger gate, the fail-soft, the upsert, the mock's generation branch — all byte-identical)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 03 — the honest `<knowledge_base>` intro: the outline is partial, and "latest" questions verify first
|
||||||
|
|
||||||
|
**Phase:** `142_kb_overview_freshness` · **Source:** `TODO.md:4` — "The agent is really struggling with questions like 'Summarize the last 10 phases of brain of Reese'. When I asked that to the current deployment it said 'I'll pull the details for the last 10 phases (104–113).' when it clearly had phase 137 loaded in the RAG…"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The model stops treating the outline as the KB's full, import-time-frozen inventory: `_KB_INTRO` says what the outline actually is (a compact, possibly partial picture that favors recent documents) and gives the one behavior that fixes the owner's question class — for "latest / complete set" questions, verify with the tools (`ls` drill-down / `grep`) before answering from the outline.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/prompts.py` — rewrite `_KB_INTRO` (L128–132). Current: `"The basic categories of everything in this knowledge base (generated at import time):\n"`. New copy (short — the section is char-budgeted by `build_kb_section`; keep it 1–2 lines): the outline is a COMPACT picture of the knowledge base's categories and topics that FAVORS RECENT DOCUMENTS and may omit older or lesser ones — it is a map of what exists, not a complete inventory; for questions about the LATEST state or the COMPLETE set ("the last N …", "every …", "all the …"), verify with `ls` (drill into the folders) or `grep` before answering from the outline. The "(generated at import time)" phrase is GONE (it is false — the sync regenerates the row on KB change — and it taught the model to discount/freeze the section).
|
||||||
|
2. `app/rag/prompts.py` — leave `build_kb_section` (L399+) byte-stable: same tag, same cap loop, same pathological-budget behavior — ONLY the intro constant changes. Update the constant's doc comment (the phase-31 note) with this phase's rationale in one line.
|
||||||
|
3. Prompt tests — the house prompt-suite pins (`tests/unit/` — the file pinning `build_kb_section` / the HIGH prompt's section order, the phase-31 pins):
|
||||||
|
- the new intro copy pinned verbatim (the exact string),
|
||||||
|
- a no-overview prompt stays byte-identical to the pre-phase text (the phase-15 convention — the existing pin passes unchanged: an empty overview omits the whole section),
|
||||||
|
- the section's cap/marker behavior pins pass unchanged (the intro is inside the budget loop — a one-line-longer intro changes the pathological-budget edge only if a test pinned the exact cut against the OLD intro length; re-pin any such test to the new intro length — the BEHAVIOR is unchanged),
|
||||||
|
- the HIGH prompt's section-order pin (`<relevance>` → `<knowledge_base>` → `<tuning>` → body) passes unchanged.
|
||||||
|
4. The deflect path is UNTOUCHED (the LOW prompt carries no `<knowledge_base>` section — the existing byte-identity pins pass as-is).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the intro copy pin; the section-build pins (cap, marker, pathological budget, empty-omission); the section-order pin.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `_KB_INTRO` no longer contains "(generated at import time)"; it names the recency bias and the verify-with-`ls`/`grep` behavior (pinned verbatim)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the section's tag/cap/marker, the deflect prompt's byte-identity, the section order)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Task 04 — the dedicated E2E: the regenerated outline leads with the newest document, and the new intro is served
|
||||||
|
|
||||||
|
**Phase:** `142_kb_overview_freshness` · **Source:** `TODO.md:4` — "The agent is really struggling with questions like 'Summarize the last 10 phases of brain of Reese'. When I asked that to the current deployment it said 'I'll pull the details for the last 10 phases (104–113).' when it clearly had phase 137 loaded in the RAG…"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The browser-visible proof of the whole phase: with the cap forced to bite, a sync-path regeneration produces a stored outline whose digest comes from the NEWEST document (recency ordering, end-to-end through the real prompt path), and the served chat prompt's `<knowledge_base>` section carries the new honest intro.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_kb_overview_freshness.py` — dedicated Playwright file, run in isolation, mock-only (the house conventions of `tests/e2e/test_kb_overview.py` — per-module truncate/re-import, the settings override fixture, the login helper, the SSE echo assertions):
|
||||||
|
- fixture: one source, TWO batches of documents whose document DATES differ (the old batch's files get past mtimes via `os.utime` before import, the new batch is current — phase 106's mtime fallback for local sources; the new batch's PATHS sort lexicographically LAST, e.g. `old/a.md`… vs `zz_new/z.md` — so the pre-fix lexicographic order and the post-fix recency order disagree about which document is first),
|
||||||
|
- settings: `BOR_OVERVIEW_INPUT_MAX_CHARS` set small enough (via the E2E settings override) that the document list is CUT — the cap must bite or the ordering is unobservable;
|
||||||
|
- test 1 (`test_regenerated_outline_leads_with_newest_doc`): import, then drive the regeneration through the mock the same way `test_kb_overview.py` test 4 does (the real `regenerate_overview` against the mock's `KB_OVERVIEW_MODE` digest) → the stored `kb_overview` row's 8 digest tokens come from the NEWEST batch's first (recency-ordered) line — assert the exact tokens (computed from the fixture in the test, not hardcoded wording);
|
||||||
|
- test 2 (`test_kb_section_carries_honest_intro`): the intro is a prompt constant — the deterministic surface is the section builder itself, called IN the E2E file the same way this file already calls `regenerate_overview`/`build_overview_prompt` directly against the app (the phase-31 file's own convention): `build_kb_section(<a seeded multi-line outline>)` → assert the section's lead line IS the new intro verbatim (no "generated at import time"), the tag + cap behavior intact; the UI injection path (the section reaching a rendered turn) is the phase-31 first-bullet echo, which a third lightweight test re-asserts here against the SEEDDED row so this file stands alone on the injection surface too;
|
||||||
|
- the pre-existing phase-31 file is NOT modified here (its re-pins landed in task 02).
|
||||||
|
2. Run the regression set in isolation (each file its own run — the suite-isolation contract): `test_kb_overview_freshness.py` (new), `test_kb_overview.py` (phase 31, task-02 re-pins).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: `uv run pytest tests/e2e/test_kb_overview_freshness.py -v --no-cov` — green IN ISOLATION (DB up: `podman compose up -d db`), mock-only.
|
||||||
|
- Integration: the intro-observation fallback (if test 2 takes the `build_kb_section` surface) lives in the unit/integration suite, not the E2E.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] with the cap biting, the regenerated outline's digest tokens come from the NEWEST document (the owner's "ends at phase 113" shape is impossible — the newest docs lead)
|
||||||
|
- [ ] the new intro copy is pinned verbatim as the section's lead line (the `build_kb_section` surface), and the section still reaches a rendered turn (the phase-31 echo path)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_kb_overview_freshness.py -v --no-cov` green in isolation; `tests/e2e/test_kb_overview.py` still green in isolation
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the phase-31 injection path, the mock's generation branch)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Phase 143 — the mobile keyboard stays down after an answer completes
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L5 — "mobile keyboard pops back up after answer is complete and that's annoying"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/assets/app.js` — the turn's `finally` block (~L3478–3493): `// done | error | stop → idle: always settle, always focus back.` … `input.focus({ preventScroll: true })` (L3492) — EVERY turn end (done, error, stop) re-focuses the composer; on a phone, focusing the textarea pops the virtual keyboard the moment the answer completes (the owner's annoyance). The existing `matchMedia` precedent in the file (L391: `reducedMotion` for `prefers-reduced-motion` — the module-level-constant shape); `tests/unit/test_frontend_scroll.py` — `test_turn_end_focus_does_not_scroll` (L213+: the source-level pin that the finally block contains the `preventScroll` focus line — must be EXTENDED, not broken); the composer is a ≥44px tap target on mobile (PLAN §7.1).
|
||||||
|
**Locked (owner-confirmed 2026-09-30, chat):** desktop-only refocus — the post-turn focus-back is skipped on coarse-pointer devices (`matchMedia("(pointer: coarse)")`), kept on desktop so the next question can be typed immediately.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A phone user reads the completed answer with the keyboard DOWN: the composer is only re-focused at turn end on fine-pointer (desktop) devices; a coarse-pointer device stays unfocused (the next question starts with a tap on the ≥44px composer). Desktop behavior — including the never-scroll focus contract — is byte-identical.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `142_kb_overview_freshness` (todo) — pipeline order only; no code dependency.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The gate (task 01):** a module-level constant beside the existing `reducedMotion` one (app.js ~L391): `const COARSE_POINTER = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;` (the L391 shape — the `typeof` guard keeps the constant safe where `matchMedia` is absent, the house style for the reduced-motion line). The finally block's focus line becomes GATED: `if (!COARSE_POINTER) input.focus({ preventScroll: true });` with a phase-143 comment explaining WHY (the keyboard pop) and the §7.1 tap-target note. The `preventScroll` argument and the never-scroll contract (phase 42 / the `test_turn_end_focus_does_not_scroll` intent) are UNCHANGED on desktop; the error/stop paths take the SAME gate (one focus line, one gate — the finally block is the single settle).
|
||||||
|
- **The pin (task 01):** `tests/unit/test_frontend_scroll.py::test_turn_end_focus_does_not_scroll` is EXTENDED: the finally block still contains the `preventScroll` focus call (now inside the `if (!COARSE_POINTER)` guard) and the `COARSE_POINTER` constant is defined from `matchMedia("(pointer: coarse)")` — the pin asserts the GATED shape (a bare ungated `input.focus(...)` line in the block is a failure, as today).
|
||||||
|
- **The E2E (task 02):** dedicated file, two contexts — desktop (default Chromium, no touch) and mobile (a Playwright device descriptor with `isMobile` + `hasTouch` — the descriptor's touch emulation makes Chromium report `pointer: coarse`). Each context: a mock-LLM turn to completion (the house E2E fixture — a single on-topic question, the done state, the same assertions as the chat story files), then assert `document.activeElement` — desktop: the composer's textarea (the phase-06 "always focus back" contract, preserved); mobile: NOT the composer (the keyboard stays down). A sanity assert in the mobile test: `page.evaluate(() => matchMedia("(pointer: coarse)").matches)` is true (the emulation is doing its job — if a future Playwright/Chromium change breaks the emulation, the test fails LOUDLY on the sanity line, not mysteriously on the focus line).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_coarse_pointer_focus_gate.md` — the constant + the gated focus line + the extended source pin.
|
||||||
|
2. `02_e2e_mobile_focus.md` — the dedicated two-context E2E.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the extended source-level pin (the gated focus shape; the constant definition); every other `app.js` pin passes unchanged.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only (desktop + mobile contexts).
|
||||||
|
- Coverage: **>90%** on new/modified code (this phase is frontend — the `app/` coverage gate is unaffected and must stay green).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] desktop: after a turn ends (done, error, stop), the composer is focused with `preventScroll` — byte-identical to pre-phase
|
||||||
|
- [ ] mobile (coarse pointer): after a turn ends, the composer is NOT focused — the keyboard stays down; the user's tap starts the next question
|
||||||
|
- [ ] `uv run pytest` green (the extended pin passes); `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run pytest tests/e2e/test_mobile_keyboard_focus.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the never-scroll focus contract on desktop, the stop path's single settle, the char counter, the send flow)
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
# Task 01 — the coarse-pointer gate on the post-turn focus-back
|
||||||
|
|
||||||
|
**Phase:** `143_mobile_keyboard_after_answer` · **Source:** `TODO.md:5` — "mobile keyboard pops back up after answer is complete and that's annoying"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The turn's `finally` block re-focuses the composer only on fine-pointer devices: a coarse-pointer (mobile) turn end leaves the page unfocused, so the virtual keyboard does not pop back up over the completed answer.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — beside the existing reduced-motion constant (~L391: `const reducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;`), add the twin constant: `const COARSE_POINTER = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;` — a short phase-143 comment: the coarse-pointer state of THIS device (touch phones/tablets), the keyboard-pop gate for the turn-end focus-back.
|
||||||
|
2. `frontend/assets/app.js` — the turn's `finally` block (~L3478–3493): the last line `input.focus({ preventScroll: true });` becomes:
|
||||||
|
```js
|
||||||
|
// Phase 143 (TODO L5): the focus-back is a DESKTOP courtesy — on a
|
||||||
|
// coarse pointer (a phone/tablet) focusing the composer pops the
|
||||||
|
// virtual keyboard over the completed answer, which is exactly what
|
||||||
|
// the owner found annoying. Fine pointers keep the immediate
|
||||||
|
// refocus (type the follow-up without moving a hand); a coarse
|
||||||
|
// pointer stays unfocused — the composer is a ≥44px tap target
|
||||||
|
// (PLAN §7.1), so the next question starts with a tap. The
|
||||||
|
// never-scroll contract (phase 42) and the single-settle rule are
|
||||||
|
// unchanged on every device — only the focus call is gated.
|
||||||
|
if (!COARSE_POINTER) input.focus({ preventScroll: true });
|
||||||
|
```
|
||||||
|
The comment above the line ("Focus back for the next question, but never move the viewport…") is folded into the phase-143 comment (one comment block, no stale duplicate). The block's SETTLE lines (clearTurnTimeout / stopThinkingClock / cancelStream / setUiState / the stop status line) are UNTOUCHED — the gate wraps the focus call alone.
|
||||||
|
3. `tests/unit/test_frontend_scroll.py` — EXTEND `test_turn_end_focus_does_not_scroll` (L213+):
|
||||||
|
- the finally block (located by the existing `// done | error | stop → idle: always settle, always focus back` anchor — KEEP the anchor comment in app.js verbatim or update the anchor in lockstep) now asserts the GATED shape: `if (!COARSE_POINTER) input.focus({ preventScroll: true })` is in the block, and a bare ungated `input.focus(` occurrence (the pre-phase line) is NOT,
|
||||||
|
- and the constant: `matchMedia("(pointer: coarse)")` appears in the file with the `COARSE_POINTER` binding (the L391-twin shape),
|
||||||
|
- the docstring is updated to state the phase-143 gate (the pin's job is now: focus-back exists, is preventScroll, and is coarse-gated).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the extended pin + every other frontend source pin green (`uv run pytest tests/unit/ -k frontend`).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate stays green: `uv run pytest --cov=app`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] desktop (fine pointer): the turn end focuses the composer with `preventScroll` — the phase-06/42 contract byte-preserved
|
||||||
|
- [ ] coarse pointer: the turn end does NOT focus the composer (the keyboard stays down)
|
||||||
|
- [ ] `uv run pytest` green; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the settle lines, the error/stop paths, the char counter, the send flow — the gate wraps the focus call alone)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 02 — the dedicated two-context E2E: the keyboard stays down on mobile
|
||||||
|
|
||||||
|
**Phase:** `143_mobile_keyboard_after_answer` · **Source:** `TODO.md:5` — "mobile keyboard pops back up after answer is complete and that's annoying"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The browser-visible proof on BOTH devices: a completed turn leaves the composer focused on desktop (the preserved contract) and UNFOCUSED on a mobile-emulated context (the owner's fix) — deterministic, mock-only, in one dedicated file.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_mobile_keyboard_focus.py` — dedicated Playwright file, run in isolation, mock-only (the house E2E conventions — the per-module fixture import, the login helper, the SSE/done-state waits from the chat story files):
|
||||||
|
- a small shared helper in the file: `turn_to_completion(page)` — asks one on-topic question (the fixture's marker question, the mock answers immediately), waits for the done state (the `aria-live` stream settled / the send button back to its idle contract — the same wait the chat story E2Es use).
|
||||||
|
- test 1 (`test_desktop_turn_end_refocuses_composer`): the DEFAULT Chromium context (no touch — `pointer: fine`): `turn_to_completion` → assert `page.evaluate("document.activeElement")` IS the composer's textarea (locate by the composer's selector — the `input` the app.js module owns; identify it via the existing selector the E2E helpers already use for typing questions). This is the regression guard: the phase-06 "always focus back" contract on desktop.
|
||||||
|
- test 2 (`test_mobile_turn_end_keeps_keyboard_down`): a MOBILE context — a Playwright device descriptor with `isMobile: true` + `hasTouch: true` (e.g. the built-in Pixel/iPhone descriptor, or an explicit `{ viewport, isMobile, hasTouch }` — the mobile ≤640px CSS breakpoint must also apply, so the descriptor's viewport is the deciding factor): FIRST a sanity assert `page.evaluate("matchMedia('(pointer: coarse)').matches")` is TRUE (the emulation flips the media feature — if a future Playwright/Chromium change breaks that, this line fails loudly and names why, instead of the focus assertion failing mysteriously), THEN `turn_to_completion` → assert `document.activeElement` is NOT the composer's textarea (the keyboard stays down — the owner's complaint is gone).
|
||||||
|
- both contexts run against the SAME fixture KB and the SAME question — the only variable is the device.
|
||||||
|
2. Run the regression set in isolation: this file + ONE chat story E2E that exercises the turn-end state (e.g. the phase-06 loading-feedback or the phase-48 stop-generation file — whichever asserts the post-turn UI) to prove the desktop contract survived.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: `uv run pytest tests/e2e/test_mobile_keyboard_focus.py -v --no-cov` — green IN ISOLATION (DB up: `podman compose up -d db`), mock-only.
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate unaffected).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] desktop context: after a completed turn, the composer is the active element
|
||||||
|
- [ ] mobile context: the `pointer: coarse` sanity assert passes AND after a completed turn the composer is NOT the active element
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_mobile_keyboard_focus.py -v --no-cov` green in isolation; the chosen chat story E2E still green in isolation
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the E2E is additive; no app/frontend change in this task)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Phase 144 — the browser back button closes the document modal, not the view behind it
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L6 — "back button doesn't close the modal of you're looking at but instead navigates back behind the modal which can lead to confusion"
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `frontend/assets/document-modal.js` — the single owner of `#doc-modal` (the near-fullscreen document viewer; `openDocumentModal` L141+ — trigger memory, the Escape/Tab capture, the `fetchSeq` stale-guard; `closeDocumentModal` — hide, drop the capture, restore focus to the trigger; the close affordances: `#doc-modal-close`, backdrop click, Escape); `frontend/assets/router.js` — the shell's popstate (L283–286: reads the PATHNAME only — a state-only entry's pop is a no-op for it); `frontend/assets/sources.js` — the existing STATE-ONLY-entry convention (L237–260, L1539: `history.pushState({ view: "rag", kb: target }, "")` — the second arg `""` keeps the current URL) and its popstate adopt/reset (L1949–1954: adopts the popped entry's `kb` or resets the drill — a pop onto the SAME state the view already shows is invisible); `tests/unit/test_remove_confirm_modal.py` (the source-level modal-pin precedent); the phase-99 D2 "the browser owns its entries" convention.
|
||||||
|
**Locked (owner-confirmed 2026-09-30, chat):** scope = the document modal (`#doc-modal`) only — the Sources-page admin confirm dialogs (the `remove-confirm` / `ignore-editor` `<dialog>` elements) are quick confirmations, not "modals you look at", and stay as-is. Back closes the modal via a state-only history entry; forward re-opens the modal (the browser owns its entries).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
On mobile and desktop alike, the browser Back button while the document modal is open CLOSES the modal and leaves the user exactly where they were (same view, same URL, same Sources drill) — instead of navigating the view behind the still-open modal. A Back-then-Forward re-opens the same document; a button/Escape/backdrop close leaves the history exactly as if the modal had never been opened.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `143_mobile_keyboard_after_answer` (todo) — pipeline order only; no code dependency.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
The modal becomes history-aware with ONE state-only entry per open — the `sources.js` convention, keyed on a `modal` state key the router (pathname-only) and the sources drill (`kb` key) both ignore:
|
||||||
|
- **Open** (`openDocumentModal`, after the skeleton guard — the `window.open` fallback path pushes NOTHING): remember the entry we are sitting on (`prev = history.state`), then — IF AND ONLY IF the current entry is not already a modal entry — `history.pushState({ modal: "doc", source, path }, "")` (state-only: the URL does not move). The "not already a modal entry" rule has exactly two callers: the normal open (sitting on the view's entry → push) and the forward re-open below (sitting on the modal's own entry → adopt, no push). If the modal is ALREADY open (defensive — the overlay makes it unreachable by pointer, but the programmatic contract must not stack entries), `replaceState` the existing modal entry in place (the remembered `prev` is kept) instead of pushing.
|
||||||
|
- **Back** (the popstate handler, armed once at module top level like the other bindings): `popstate` fires with the state of the entry we LANDED ON. The modal is open and the landed state is NOT a `modal` entry → the browser moved off the modal's entry → that is the back press: remember `lastPrev = the landed state` (the entry below the modal's — needed for the forward re-open's restore), close the modal (a `closingViaBack` flag around the call so the close does not also `replaceState`). The router's popstate is a no-op (same pathname → `name === current`); the sources drill re-adopts the SAME state it was already showing (its `kb` key is the state we sat on before the push — invisible). Net: the modal closes, nothing else moves.
|
||||||
|
- **Forward onto the modal's entry** (modal closed, `event.state.modal === "doc"`): the browser owns its entries (phase-99 D2) — re-open the document the entry names: `openDocumentModal(st.source, st.path, null)` (trigger null — focus goes to the content target, the normal open path). The open sees the current entry IS a modal entry → ADOPTS it instead of pushing: `entry = { prev: lastPrev, source, path }` (`lastPrev` — the below-entry remembered at the back-close; it is always available: a modal entry can only be in the forward stack because a back-close popped it first).
|
||||||
|
- **Button / Escape / backdrop close** (not a back press): the modal entry is still the current entry — remove it IN PLACE with `history.replaceState(entry.prev, "")` (no popstate fires, no other listener runs, the view state is restored byte-for-byte) — so the NEXT back behaves exactly as if the modal had never been opened. Guard: run the `replaceState` only when `history.state` is still a modal entry (the invariant — the three affordances are reachable only while open, and open means sitting on the modal entry; the check is the fail-safe if the invariant ever breaks: do nothing to the history rather than corrupt the current entry).
|
||||||
|
- Module state: `let entry = null` — `{ prev, source, path }` while the modal is open (the `prev` to restore, the doc the entry names); `let lastPrev = null` — the below-entry remembered at each back-close (the adopt's `prev`); both `null`/stale otherwise. The popstate handler and the open/close paths are the ONLY writers. Known edge (documented, accepted): if the user opens the modal, backs out, switches views, then FORWARDS onto the modal entry, the modal re-opens over the new view — the browser owns its entries (the sources drill does the same with its `kb` entries); the modal is always one close-away.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_history_aware_modal.md` — the push/replace/popstate mechanics in `document-modal.js` (open, back, forward, the three close affordances).
|
||||||
|
2. `02_unit_pins.md` — the source-level unit pins (the `test_remove_confirm_modal.py` pattern) for the entry lifecycle and the listener interplay.
|
||||||
|
3. `03_e2e_back_closes_modal.md` — the dedicated E2E: back closes the modal (URL + view + drill untouched), button-close keeps history sane, forward re-opens.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the source-level pins (the push on open, the `closingViaBack`-guarded close, the `replaceState(prev)` on non-back close, the popstate handler's two branches, the re-open suppression).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only — `page.goBack()` / `page.goForward()` drive the real history.
|
||||||
|
- Regression: `tests/e2e/test_document_back_navigation.py` (the phase-13 /document.html back-nav story — the FULL-PAGE viewer, a different page: it must stay green) and the phase-99 Sources drill E2E (the kb back/forward story — the interplay must not leak).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate stays green).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] with the modal open: Back → the modal closes, the URL is unchanged, the view is unchanged, the Sources drill (when opened from Sources) is unchanged; a SECOND Back then leaves the view as usual
|
||||||
|
- [ ] Back → Forward → the same document re-opens in the modal (no duplicate history entry)
|
||||||
|
- [ ] button / Escape / backdrop close → the next Back behaves exactly as if the modal had never been opened (no dead no-op back step)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run pytest tests/e2e/test_modal_back_button.py -v --no-cov` green in isolation; the two regression E2Es still green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the router's popstate, the sources drill's adopt/reset, the modal's focus trap / Escape / fetch-seq contracts, the admin confirm dialogs)
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# Task 01 — the history-aware modal: push, adopt, back-close, in-place removal
|
||||||
|
|
||||||
|
**Phase:** `144_modal_back_button` · **Source:** `TODO.md:6` — "back button doesn't close the modal of you're looking at but instead navigates back behind the modal which can lead to confusion"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
`#doc-modal` owns one state-only history entry per open: Back closes the modal (view/URL/drill untouched), a non-back close removes the entry in place (the next Back behaves as if the modal never opened), and Forward onto the modal's entry re-opens the same document.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/document-modal.js` — module state beside the existing `triggerEl` / `fetchSeq` lets: `let entry = null;` (`{ prev, source, path }` while the modal is open — `prev` is the below-entry to restore, `source`/`path` are the doc the entry names) and `let lastPrev = null;` (the below-entry remembered at each back-close — the forward re-open's restore source). Comment each on the `fetchSeq` house style (what it is, who writes it).
|
||||||
|
2. `frontend/assets/document-modal.js` — `openDocumentModal` (L141+), after the skeleton guard (the `window.open` fallback stays BEFORE this — it pushes nothing) and before `modalEl.hidden = false`:
|
||||||
|
```js
|
||||||
|
/* Phase 144 (TODO L6): the modal owns ONE state-only history entry —
|
||||||
|
* Back closes the modal instead of navigating the view behind it.
|
||||||
|
* The entry is state-only (second arg "" — the URL does not move),
|
||||||
|
* so the router's pathname-only popstate is a no-op and the Sources
|
||||||
|
* drill re-adopts the state it was already showing (the sources.js
|
||||||
|
* state-only-entry convention, L1539). The current entry is a modal
|
||||||
|
* entry only on the forward re-open (the popstate handler below
|
||||||
|
* calls us sitting on it) — then we ADOPT it; otherwise we push. */
|
||||||
|
const st = history.state;
|
||||||
|
if (entry) {
|
||||||
|
// Defensive re-open while open: replace our entry in place (the
|
||||||
|
// remembered prev is kept) — never stack a second entry.
|
||||||
|
entry.source = source;
|
||||||
|
entry.path = path;
|
||||||
|
history.replaceState({ modal: "doc", source, path }, "");
|
||||||
|
} else if (st && st.modal === "doc") {
|
||||||
|
// Forward onto our own entry: adopt — the browser already sits on
|
||||||
|
// it (lastPrev is the below-entry remembered at the back-close).
|
||||||
|
entry = { prev: lastPrev, source, path };
|
||||||
|
} else {
|
||||||
|
entry = { prev: st, source, path };
|
||||||
|
history.pushState({ modal: "doc", source, path }, "");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
(The rest of the open body — trigger memory, `showLoading`, the Escape/Tab capture, the fetch — is untouched.)
|
||||||
|
3. `frontend/assets/document-modal.js` — `closeDocumentModal` (L~200): at the top (after the existing `if (!modalEl || modalEl.hidden) return;`), before the hide, add the entry removal:
|
||||||
|
```js
|
||||||
|
/* Phase 144: a NON-back close removes the modal's entry IN PLACE —
|
||||||
|
* no popstate fires, no other listener runs, the view state is back
|
||||||
|
* byte-for-byte, so the next Back behaves as if the modal never
|
||||||
|
* opened. A back close (closingViaBack — the popstate handler) has
|
||||||
|
* already been moved off the entry by the browser: no replace. */
|
||||||
|
if (entry && !closingViaBack && history.state && history.state.modal === "doc") {
|
||||||
|
history.replaceState(entry.prev, "");
|
||||||
|
}
|
||||||
|
entry = null;
|
||||||
|
```
|
||||||
|
with `let closingViaBack = false;` beside the other lets (reset by the popstate handler after each close call — it is set ONLY around that call).
|
||||||
|
4. `frontend/assets/document-modal.js` — the popstate listener, armed ONCE at module top level (next to the existing `closeEl`/`backdropEl` bindings — a missing skeleton means the listener is a no-op via the `entry`/`modalEl` guards, the header.js pattern):
|
||||||
|
```js
|
||||||
|
/* Phase 144 (TODO L6): back/forward onto the modal's entry. popstate
|
||||||
|
* fires with the state of the entry we LANDED on. Back: the modal is
|
||||||
|
* open and we landed on a non-modal state — the browser moved off our
|
||||||
|
* entry; close the modal (remember the landed state as lastPrev for
|
||||||
|
* the forward re-open; closingViaBack keeps the close from also
|
||||||
|
* replaceState-ing). Forward: the modal is closed and we landed on a
|
||||||
|
* modal entry — the browser owns its entries (the phase-99 D2
|
||||||
|
* convention) — re-open the doc the entry names (the open adopts the
|
||||||
|
* entry — no second push). Every other popstate (the router's view
|
||||||
|
* entries, the drill's kb entries) passes through untouched. */
|
||||||
|
window.addEventListener("popstate", (event) => {
|
||||||
|
const st = event.state;
|
||||||
|
const isModalEntry = st && st.modal === "doc";
|
||||||
|
if (isModalEntry && modalEl && modalEl.hidden) {
|
||||||
|
openDocumentModal(st.source, st.path, null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isModalEntry && modalEl && !modalEl.hidden && entry) {
|
||||||
|
lastPrev = st;
|
||||||
|
closingViaBack = true;
|
||||||
|
closeDocumentModal();
|
||||||
|
closingViaBack = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
5. Update the module's header docstring contract block (the `openDocumentModal` / `closeDocumentModal` bullets, L12–20): one bullet for the history behavior (the entry, Back closes, the in-place removal, the forward re-open) — the file's self-documentation convention.
|
||||||
|
|
||||||
|
- ASSUMPTION: the state key is `modal: "doc"` (a string discriminator, not a unique token) — a second modal type would use its own key (the `kb` / `view` key convention); the value pair (`source`, `path`) rides in the state so the forward re-open names its document (percent-encoding is irrelevant — the state is structured, not a URL).
|
||||||
|
- ASSUMPTION: `lastPrev` (not `history.state`) is the adopt's `prev` — at a forward re-open the browser sits ON the modal entry, so the below-entry is only the one remembered at the back-close; a modal entry can reach the forward stack only through a back-close, so it is always available (the null case — e.g. a forward after a hard page reload into a modal URL — is impossible: modal entries are same-document pushes, never URL-deep-links).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: task 02's source-level pins (this task ships with them green — the pins are written against the final shape above).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate stays green).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] open → one state-only entry (URL unchanged); re-open-while-open → in-place replace, still one entry
|
||||||
|
- [ ] Back with the modal open → the modal closes, `lastPrev` remembered, no `replaceState` (the browser owns the pop)
|
||||||
|
- [ ] button/Escape/backdrop close → `replaceState(entry.prev)` runs (the entry is gone in place); the next Back is a real navigation step, not a dead no-op
|
||||||
|
- [ ] Forward onto the modal's entry → the same document re-opens, no second push
|
||||||
|
- [ ] `uv run pytest` green; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the router's popstate, the sources drill, the modal's focus trap / Escape / fetch-seq / trigger-focus contracts — the new state sits beside them)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Task 02 — the source-level pins: the entry lifecycle, the two popstate branches, the no-leak guarantees
|
||||||
|
|
||||||
|
**Phase:** `144_modal_back_button` · **Source:** `TODO.md:6` — "back button doesn't close the modal of you're looking at but instead navigates back behind the modal which can lead to confusion"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A silent regression in the history mechanics (a double push, a replaceState on the wrong entry, a listener leak, a lost `lastPrev`) is caught at the source level — the `test_remove_confirm_modal.py` house pattern for a frontend module whose real behavior is E2E-gated.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/unit/test_frontend_doc_modal.py` — new file (the `test_remove_confirm_modal.py` pattern: read `frontend/assets/document-modal.js` as text — the `_js()`-style loader, REPO-relative path; if a doc-modal unit file already exists, extend it instead):
|
||||||
|
- **the state:** `let entry = null` and `let lastPrev = null` and `let closingViaBack = false` are declared exactly once (one `let` each — no second writer site);
|
||||||
|
- **the open:** the push is `history.pushState({ modal: "doc", source, path }, "")` (state-only — the `""` second arg present — the URL must not move); the push sits INSIDE the else-branch behind the `st && st.modal === "doc"` adopt check (assert the adoption branch assigns `entry = { prev: lastPrev, source, path }` WITHOUT a pushState — the no-second-push rule); the defensive re-open branch uses `history.replaceState` and keeps `entry` (updates `source`/`path`);
|
||||||
|
- **the close:** the in-place removal `history.replaceState(entry.prev, "")` is guarded by `!closingViaBack` AND `history.state && history.state.modal === "doc"` (the fail-safe — a non-modal current entry is never overwritten); `entry = null` runs unconditionally in the close (the adopt's memory must not survive a close);
|
||||||
|
- **the popstate:** the listener is registered ONCE (one `window.addEventListener("popstate"` in the file); its two branches are mutually exclusive (the `isModalEntry && modalEl.hidden` forward-re-open branch RETURNS before the back-close branch); the back-close branch writes `lastPrev = st` BEFORE the `closingViaBack`-wrapped `closeDocumentModal()` call; no branch fires when `entry` is falsy / the modal is closed and the state is not a modal entry (the pass-through);
|
||||||
|
- **no leak:** the popstate listener and the entry state are the ONLY `history.*` call sites in the file (a grep-style assert: the file's `history.` occurrences are exactly the push, the two replaces, and nothing else — `history.back()` / `history.go()` must NOT appear — the browser owns its entries);
|
||||||
|
- **the contract unchanged:** the pre-phase pins that a regression could plausibly break still hold — the Escape → `closeDocumentModal()` capture, the `fetchSeq` stale-guard lines, the trigger-focus restore in the close, the `window.open(fullPageUrl…)` fallback BEFORE the entry logic (the fallback pushes nothing — assert its early `return` precedes the first `history.` use in the open).
|
||||||
|
2. Run the frontend unit set: `uv run pytest tests/unit/ -k frontend` green (this file + every pre-existing pin).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pins above (each one names the regression it catches in its docstring — the house pattern).
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate stays green).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `tests/unit/test_frontend_doc_modal.py` green; every pre-existing frontend unit pin green (`uv run pytest tests/unit/ -k frontend`)
|
||||||
|
- [ ] the pin set catches: a second push on forward re-open, a `replaceState` on a non-modal entry, a double-registered popstate listener, a `history.back()`/`go()` introduction, a lost `lastPrev` write, a fallback-path push
|
||||||
|
- [ ] `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (this task is tests-only)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 03 — the dedicated E2E: Back closes the modal, the history stays sane, Forward re-opens
|
||||||
|
|
||||||
|
**Phase:** `144_modal_back_button` · **Source:** `TODO.md:6` — "back button doesn't close the modal of you're looking at but instead navigates back behind the modal which can lead to confusion"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The browser-visible proof with the REAL history: `page.goBack()` / `page.goForward()` drive the owner's exact scenario — back closes the modal (nothing else moves), a button close leaves no dead step, forward re-opens the document.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_modal_back_button.py` — dedicated Playwright file, run in isolation, mock-only (the house E2E conventions — the per-module fixture import, the login helper, the chat-chip / sources-table open paths from the phase-26 story files):
|
||||||
|
- fixture: the standard E2E KB (at least one readable document); a helper `open_modal_via_chip(page)` — asks a question whose answer carries a source chip (the mock's citation echo), clicks the chip, waits for `#doc-modal` visible + the content rendered (the "Document loaded." desc state);
|
||||||
|
- test 1 (`test_back_closes_modal_view_unchanged`): boot on `/` (chat), `open_modal_via_chip`, note `page.url` (`/`) and the visible view (`#view-chat` not hidden) → `page.goBack()` → assert `#doc-modal` is hidden (closed), `page.url` STILL `/`, `#view-chat` still visible (the view behind was NOT navigated — the owner's confusion is gone) → one more `page.goBack()` is a REAL step: it leaves the app's shell history (in the test, assert the URL moved away from `/` or the page left the shell — the point: the second back did the navigation the first back should have done; if the test boots with no prior history, skip the second-back assert and note it — the modal entry's existence is proven by test 3's forward);
|
||||||
|
- test 2 (`test_button_close_leaves_no_dead_step`): boot, `open_modal_via_chip` → close via `#doc-modal-close` (the button affordance) → assert the modal hidden → assert the history depth is RESTORED: `page.evaluate("history.length")` equals the pre-open depth (the in-place `replaceState` removed the entry — the next Back is a real navigation step, not a silent no-op). (If the boot context's `history.length` baseline is flaky across Chromium versions, fall back to the OBSERVABLE: a `page.goBack()` after the button close leaves `/` immediately — one step, not two — and assert that instead; the depth assert is preferred when stable.);
|
||||||
|
- test 3 (`test_forward_reopens_same_document`): boot, `open_modal_via_chip` (document D) → `page.goBack()` (modal closes) → `page.goForward()` → assert `#doc-modal` visible again with D's title (the same document — `#doc-modal-title` text equals the pre-back title) and the history did NOT gain an entry (`history.length` unchanged by the re-open — the adopt, not a push);
|
||||||
|
- test 4 (`test_back_from_sources_keeps_drill` — the interplay guard): boot on `/sources.html` (the RAG view, admin — the login helper), open a document via a table link (the drill at the TOP level is the simplest case), `page.goBack()` → modal hidden, URL `/sources.html`, the Sources view still visible; if the fixture supports a drilled level (a folder with the phase-99 breadcrumb), open the document FROM a drilled level and assert the breadcrumb survived the back (the drill's popstate re-adopted its own state — no visible change).
|
||||||
|
2. Run the regression set in isolation (each its own run): this file; `tests/e2e/test_document_back_navigation.py` (the phase-13 FULL-PAGE /document.html back-nav — a different page, must stay green); the phase-99 Sources drill E2E (`test_kb_tree_table_and_back_nav.py` — the `kb` entry interplay must not leak).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: `uv run pytest tests/e2e/test_modal_back_button.py -v --no-cov` — green IN ISOLATION (DB up: `podman compose up -d db`), mock-only.
|
||||||
|
- Regression: the two named files green in isolation.
|
||||||
|
- Coverage: **>90%** on new/modified code (frontend — the `app/` gate unaffected).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] back with the modal open → modal closed, URL unchanged, view unchanged (tests 1 + 4)
|
||||||
|
- [ ] button close → no dead history step (test 2)
|
||||||
|
- [ ] back → forward → the same document re-opens without a new history entry (test 3)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_modal_back_button.py -v --no-cov` green in isolation; both regression E2Es green in isolation
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the E2E is additive; no app/frontend change in this task)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Phase 145 — the answer points at the original git source: the model links it, the modal shows it
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L7 — "there always needs to be a link to the original git source if possible. I've asked a few questions like 'how does the phased execution process work for pi.dev?' And the correct answer is an explanation and then point to the skills repo in the answer so I can go download the skills for my personal use. It's important to provide the full source so users get the complete answer at once rather than extracting it bit by bit with lots of questions."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/agent.py` — the read branch's result shapes (~L1630–1680: `Document {source}/{path}:\n` + `date: …\n` + image marker + content; the `E2E mock`'s `_READ_RESULT_PREFIX` = the FIRST line only — `tests/e2e/mock_llm.py` L1412 — so a new line BELOW the first line keeps the mock contract); `app/models.py` — `GitSource` (`url` L289, `kind` L292, `token` L316 — the PAT, never served, `branch` L333 — phase 135, NULL = default branch); `app/rag/git_sources.py` — `sanitize_url` (L~150: the phase-121 credential-free output mask — strips userinfo, byte-identical for clean URLs) and `clone_url_for` (the single credential-injection site); `app/schemas.py` — `DocContent` (the `GET /api/documents/content` payload — the phase-106 `created_at` field is the recent optional-metadata precedent) and `SourceRef` (UNCHANGED this phase — the done frame stays byte-identical, the origin rides the content payload instead); `app/api/docs.py` — the content endpoint (the `(source, path)` lookup, percent-encoding); `frontend/assets/document.js` — `renderDocument` (L172+: the shared meta-badge row — `metaBadge`/`pathCode` idioms — used by BOTH the doc modal and the full page); `app/rag/prompts.py` — the `<tools>` section (L162+: the `ls`/`read`/`grep` teaching, HIGH prompt only); `app/rag/retriever.py` — `source_ref_with_image` (untouched).
|
||||||
|
**Locked (owner-confirmed 2026-09-30, chat):** the model learns the origin from a new `origin:`/`branch:` line in read results (git sources only, credentials stripped) and is taught to include the original-source link in its answer — it builds the browse URL itself (no fragile server-side GitHub/Gitea URL construction); the doc modal + document page get the "Original" external link (one `renderDocument` site, fed by the content payload); local (non-git) sources get no link.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
An answer grounded in a git-sourced document comes with the way to the complete original in ONE step: the read result tells the model the repository origin (and pinned branch), the prompt teaches it to include the original-source link in its answer text (so it works in the UI AND through the API tokens), and the document modal + full page show the same origin as a visible "Original" external link.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `144_modal_back_button` (todo) — pipeline order only; code touch (the modal's meta row) is the same `renderDocument` surface, no ordering risk.
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The origin resolver (task 01):** `app/rag/git_sources.py` (the GitSource-domain home) — `origin_for_source(db, source_name) -> tuple[str, str | None] | None`: the source's directory basename (the importer's `source = root.name`) mapped to a `kind = "git"` row by the row's URL basename — the URL's path component, trailing `/` stripped, `.git` suffix stripped, last path segment (scp-style `git@host:owner/repo.git` → the part after `:` first; `sanitize_url` applied to the result so a legacy embedded-credential row never leaks; `branch` returned as-is — NULL means the default branch). EXACTLY ONE match → `(sanitized_url, branch)`; zero or TWO-OR-MORE matches (two repos with the same basename) → `None` (no line — never guess; the ambiguity is logged at WARNING with the sanitized names). No caching (the table is a handful of rows; a read's extra query is trivial).
|
||||||
|
- **The read result (task 01):** a git-sourced document's read result gains, IMMEDIATELY AFTER the `date:` line (before the image marker — the marker keeps its phase-122 position relative to the content): `origin: {sanitized_url}` and, when a branch is pinned, `branch: {branch}` — one line each, no URL for local sources, no lines at all for a source with no unambiguous git row (the result is byte-identical to pre-phase for every non-git doc — the existing pins pass unchanged; the mock's `_READ_RESULT_PREFIX` first-line contract is untouched — the new lines sit BELOW the header). The plain-read, truncated-plain, range-read, and truncated-range shapes all carry the lines at the same position (one insertion helper — the four result builders share it).
|
||||||
|
- **The teaching (task 02):** the `<tools>` section gains the citation-source rule (the `read` teaching's natural home — the model answers from what it READ): when an answer uses a document whose read result carries an `origin:` line, the answer INCLUDES the original source — a link to the repository (the `origin` line) with the document's path (from the `Document …` header) named, and the pinned branch when one is shown — formatted as the repository's file-view URL where the model can tell it (GitHub/Gitea/GitLab `…/blob/<branch>/<path>`), else the repo URL + path as text. The point (the owner's words, in the model's language): the user should get the complete source at once — one link, not a second question. Local-sourced documents carry no `origin` line — nothing to add. The `SUGGEST_INTRO` citation discipline (cite only what you read) is UNCHANGED — this rule extends the cited documents' answers, it does not widen the cite set.
|
||||||
|
- **The UI (task 03):** `DocContent` (the content payload) gains `origin_url: str | None = None` + `origin_branch: str | None = None` (the resolver's output for the document's source — NULL/absent for local sources, the `image_url`-style optional-metadata shape; a null field in the content payload is fine — the omission rule binds the SSE frames, not this payload). `renderDocument` (document.js L172+) — when `doc.origin_url` is present, the meta row gains, after the path code: an "Original" anchor (`<a>` — `createElement`, the never-build-HTML rule; `href = doc.origin_url`, `target="_blank" rel="noopener"` — the modal's "Full page" escape-hatch idiom; `textContent = doc.origin_url` VERBATIM — the copyable-link contract — in the `doc-path` ellipsis style, the full URL in a `title` attribute that also carries ` — branch: <name>` when `origin_branch` is present) — ONE site: the modal AND the full page show it (both call `renderDocument`).
|
||||||
|
- **The E2E (task 04):** a git row seeded over the fixture source's name (the resolver is name-based — a `kind="git"` row whose URL basename matches the fixture source name makes the fixture docs "git-sourced" for this phase's purposes), a scripted mock flow whose final answer carries the repo URL, and the modal's meta anchor asserted.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_origin_resolution.md` — the resolver + the read-result `origin:`/`branch:` lines (the four read shapes).
|
||||||
|
2. `02_prompt_teaching.md` — the `<tools>` original-source rule + the prompt pins.
|
||||||
|
3. `03_content_payload_render_link.md` — `DocContent` fields + the content endpoint + the `renderDocument` "Original" anchor (modal + full page).
|
||||||
|
4. `04_e2e_source_link.md` — the dedicated E2E (the answer carries the repo link; the modal shows the Original anchor; non-git docs stay byte-identical).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the resolver (the mapping, the sanitization, the ambiguity, the scp-form URL, the `.git` suffix, the no-row case); the read-result insertion (four shapes × {git, git+branch, local, ambiguous} — non-git byte-identical pins); the prompt copy pin; the payload/endpoint; the renderer (the anchor present/absent, the branch label, the ellipsis title).
|
||||||
|
- Integration: the content endpoint returns `origin_url` for a seeded git row (and null for a plain local source).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a git-sourced read result carries `origin: <sanitized url>` (+ `branch:` when pinned); every local-source read result is byte-identical to pre-phase
|
||||||
|
- [ ] the HIGH prompt's `<tools>` section teaches the original-source link rule (pinned verbatim); the LOW prompt is byte-identical
|
||||||
|
- [ ] the doc modal AND /document.html show the "Original" external link for git-sourced docs (the branch in the label when pinned); nothing new for local docs
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_git_source_links.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the read header's first line, the mock's parse, the done frame, the LOW prompt, the non-git read results)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 01 — the origin resolver + the read-result `origin:`/`branch:` lines
|
||||||
|
|
||||||
|
**Phase:** `145_git_source_links` · **Source:** `TODO.md:7` — "there always needs to be a link to the original git source if possible. I've asked a few questions like 'how does the phased execution process work for pi.dev?' And the correct answer is an explanation and then point to the skills repo in the answer so I can go download the skills for my personal use…"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A read result for a git-sourced document tells the model where the complete original lives — the sanitized repository URL (and the pinned branch, when one exists) — so the model can link it in its answer (task 02's teaching). Every non-git read result is byte-identical to pre-phase.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/git_sources.py` — `origin_for_source(db: Session, source_name: str) -> tuple[str, str | None] | None` beside `sanitize_url`:
|
||||||
|
- the candidate rows: `select(GitSource).where(GitSource.kind == "git")` (local rows are never origins — nothing to link to from the user's browser);
|
||||||
|
- the match: the row's URL basename == `source_name` — the URL's path component (after the `://`, or after `:` for scp-style `git@host:owner/repo`), trailing `/` stripped, a single trailing `.git` suffix stripped, last segment taken;
|
||||||
|
- EXACTLY one match → `(sanitize_url(row.url), row.branch)` — the phase-121 output mask keeps a legacy embedded-credential row's secret out of the prompt (the `clone_url_for` lesson: the stored URL may carry userinfo; the stored value is never modified);
|
||||||
|
- zero matches, or TWO-OR-MORE (two repos sharing a basename) → `None` + a WARNING log naming the sanitized candidates (never guess — the read result would otherwise carry a wrong origin into every answer);
|
||||||
|
- pure-DB helper (no git subprocess — `scripts/git_sync.py` stays the only git-invocation site, PLAN §13).
|
||||||
|
2. `app/rag/agent.py` — the read branch: after the doc resolves (all FOUR successful result builders — plain at-or-under-cap ~L1655, truncated plain ~L1636, range at-or-under-cap ~L1686, truncated range ~L1668), compute `origin = origin_for_source(db, doc.source)` ONCE per call (before the branching on ranged/truncated — the lines are identical in all four shapes) and insert IMMEDIATELY AFTER the `date:` line and BEFORE the image marker: the text-doc shape becomes `Document …: / date: / origin: / branch: / content`, the image-doc shape `Document …: / date: / origin: / branch: / marker / content` (the marker keeps its phase-122 position relative to the content — the origin lines ride above it). One line `origin: {url}` and, when `branch` is non-NULL, one line `branch: {branch}`. `origin is None` → NO lines (byte-identical to pre-phase). A shared tiny helper builds the two lines; the four result builders each call it once with the same strings.
|
||||||
|
3. `tests/unit/test_agent.py` (or the read-branch unit home) — the matrix: {git row matched, git row + pinned branch, local source (no git row), two rows same basename (ambiguous)} × the four read shapes → the exact result strings (the origin lines present at the exact position for the git cases, ABSENT for local/ambiguous); the first line of every result is still `Document {source}/{path}:` (the mock's `_READ_RESULT_PREFIX` contract — assert it); the image-doc shape keeps its marker position (the phase-122 pin).
|
||||||
|
4. `tests/unit/` — the resolver's own unit file (the git_sources unit home — `tests/unit/test_git_sources*.py` if it exists, else a new one): the basename mapping (`.git` suffix, trailing `/`, scp-style `git@host:owner/repo.git`, an `@` inside a PATH — not userinfo — stays), the `sanitize_url` application (a legacy `https://user:tok@host/x.git` row → the prompt line is `https://host/x.git`), the zero-match and two-match `None` + the WARNING (caplog), the `branch` passthrough (NULL → None → no `branch:` line).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the resolver matrix + the four-shape read-result matrix (above); every pre-existing read-branch pin passes UNCHANGED (non-git byte-identity is the point).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a git-sourced read result carries `origin: <sanitized url>` (+ `branch: <name>` when pinned) in all four read shapes, at the documented position; the first line is untouched
|
||||||
|
- [ ] local-source and ambiguous-basename read results are byte-identical to pre-phase (the existing pins prove it)
|
||||||
|
- [ ] no credential ever reaches a read result (the legacy embedded-token case is pinned sanitized)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed work (the grep/ls surfaces, the refusal lines, the `read_docs`/`read_truncations` signals, the SSE frames)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Task 02 — the `<tools>` teaching: the answer includes the link to the original source
|
||||||
|
|
||||||
|
**Phase:** `145_git_source_links` · **Source:** `TODO.md:7` — "there always needs to be a link to the original git source if possible. I've asked a few questions like 'how does the phased execution process work for pi.dev?' And the correct answer is an explanation and then point to the skills repo in the answer so I can go download the skills for my personal use. It's important to provide the full source so users get the complete answer at once rather than extracting it bit by bit with lots of questions."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The model that answers from a git-sourced document includes, in the answer text, the link to the complete original — repository (its read result's `origin` line), the file's path (the `Document …` header), and the pinned branch when one was shown — so the user gets the source in one step, in the UI AND through the API tokens (the answer is the only surface both share).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/prompts.py` — `TOOLS_SECTION` (L216+): append the original-source rule to the `read` clause (it is the read's contract — the `origin:` line is a read-result fact, and the rule binds the ANSWER that uses what the read added). Locked copy (pinned verbatim by the tests):
|
||||||
|
`A read result for a document from a git source carries an origin line (and a branch line when a branch is pinned): when your answer uses such a document, include the original source in the answer — a link to the repository from the origin line, with the document's path (from the Document header) named and the pinned branch when one is shown — as the repository's file-view URL where you can tell it (for example <repo-url>/blob/<branch>/<path>), or the repository URL plus the path as plain text otherwise. The user should be able to open the complete original from your answer in one step, not ask again for the source.`
|
||||||
|
Position: after the truncation workflow sentence (the `read` clause's end), BEFORE the `grep` clause begins — one appended sentence-group, the rest of the section byte-identical. The rule is CONDITIONAL on the `origin` line's presence — a local-sourced document's read result carries none, so the rule adds nothing to those answers (the model has no URL to cite; it must NOT invent one — the sentence's conditioning does that job; if a live run ever shows a fabricated origin, the phase-72-style teaching refusal is the follow-up, not this phase).
|
||||||
|
2. The `AGENT_TOOLS` `read` description (app/rag/agent.py L331+ — the most local text at call time, the phase-70 contract) gets the ONE-clause mirror: "For a document from a git source, the result also carries an `origin` line (and `branch` when pinned) — include that original source in your answer (see your tools instructions)." (the behavior detail stays in `TOOLS_SECTION` — the description points, the section teaches; the phase-124 `show_image` description's "see the instructions" shape is the precedent if the executor prefers a shorter pointer).
|
||||||
|
3. `tests/unit/` — the prompt pins (the HIGH-prompt suite that pins `TOOLS_SECTION`):
|
||||||
|
- the new rule pinned verbatim (the exact sentence-group, at its exact position — between the truncation sentence and the `grep` clause),
|
||||||
|
- the section's OTHER bytes byte-identical (a diff-style pin: the pre-phase section with ONLY the new sentence-group inserted),
|
||||||
|
- the LOW/deflect prompt stays byte-identical (the `<tools>` section is HIGH-only — the existing pin passes unchanged),
|
||||||
|
- the mock is untouched (it keys off the `<tools>` marker's presence — assert the marker line is unchanged),
|
||||||
|
- the `read` tool description pin updated with the new clause (the `AGENT_TOOLS` schema pins).
|
||||||
|
4. `SUGGEST_INTRO` (L152) and the citation discipline are UNCHANGED (the rule extends the answers of cited documents; it does not widen the cite set — the "cite only what you read" sentence passes byte-identical).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the pins above; every pre-existing prompt pin passes (the LOW prompt, the section order, the `DEFLECT_MODE` marker, the `SUGGEST_INTRO` copy).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the HIGH prompt's `read` clause carries the original-source rule (pinned verbatim, exact position); the tool description carries its pointer clause
|
||||||
|
- [ ] the LOW prompt is byte-identical; the mock's marker keying is untouched
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the section order, the deflect path, the citation discipline, the other tool clauses)
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Task 03 — the "Original" link: `DocContent` origin fields + the shared `renderDocument` anchor
|
||||||
|
|
||||||
|
**Phase:** `145_git_source_links` · **Source:** `TODO.md:7` — "there always needs to be a link to the original git source if possible. I've asked a few questions like 'how does the phased execution process work for pi.dev?' And the correct answer is an explanation and then point to the skills repo in the answer so I can go download the skills for my personal use…"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
Every surface that shows a document (the chat's doc modal AND the full /document.html page — one `renderDocument` site) shows the git origin as a visible, copyable "Original" external link — fed by the content endpoint's new origin fields. Non-git documents show nothing new (byte-identical meta row).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/schemas.py` — `DocContent` (L531+): `origin_url: str | None = None` and `origin_branch: str | None = None` — the `image_url`-style optional metadata (L557+): ABSENT from the wire when `None` (the `_drop_absent_share_url` omission precedent — the serializer drop, never `null`), so a non-git document's payload is byte-identical to pre-phase. `origin_url` is the sanitized clone URL (credential-free — the resolver's output, task 01's `sanitize_url` guarantee); `origin_branch` is the pinned branch (absent when the row pins none — NULL = the repo's default branch, nothing to show).
|
||||||
|
2. `app/api/docs.py` — `get_document_content` (L165+): after the document resolves, `origin = origin_for_source(db, doc.source)` (task 01's resolver — the SAME function the read branch uses, one mapping for the whole app) → set the two payload fields (`None` → absent on the wire). The endpoint's percent-encoding, 404, and image bytes are untouched.
|
||||||
|
3. `frontend/assets/document.js` — `renderDocument` (L172+): when `doc.origin_url` is present, the meta row gains, AFTER the path `code` and BEFORE the Created badge: an "Original" anchor — `createElement("a")` (the never-build-HTML rule), `className "doc-origin"` (a new class in `styles.css` mirroring the `doc-path` code style — ellipsis clip, the house dark-tech palette tokens only, `target=_blank` affordance color from the existing link tokens), `href = doc.origin_url`, `target="_blank"`, `rel="noopener"` (the modal's "Full page" escape-hatch idiom — index.html L1579), `textContent = doc.origin_url` — the full URL VERBATIM as the visible text (the copyable-link contract: no decorative label inside the anchor text — a ` (branch)` suffix would break copy-paste; the CSS ellipsis clips the display, and the `title` attribute carries the full URL, the `pathCode` precision idiom — plus, when `doc.origin_branch` is present, ` — branch: <name>` appended: `title = doc.origin_url + " — branch: " + doc.origin_branch`). `doc.origin_url` absent (the field simply missing on the wire for non-git docs) → the meta row is byte-identical to pre-phase (the badge row unchanged — the existing `renderDocument` pins pass as-is).
|
||||||
|
4. `frontend/assets/styles.css` — the `.doc-origin` class (the `doc-path` idiom: `code`-family font, ellipsis `white-space: nowrap; overflow: hidden; text-overflow: ellipsis`, the ≤640px row behavior mirroring the badge row's wrap rules — the meta row already wraps on mobile, the anchor is one more inline item).
|
||||||
|
5. `tests/unit/test_document_viewer.py` (the `renderDocument` pin home — or its neighbor per the existing layout) — the anchor: present + correct `href`/`target`/`rel`/`text`/`title` for a git doc (branch and no-branch variants); ABSENT (the meta row's exact pre-phase children) for a doc without `origin_url`; the never-build-HTML shape (no innerHTML/outerHTML in the new code).
|
||||||
|
6. `tests/integration/` — the content endpoint: a `kind="git"` row seeded with a URL basename matching a fixture source → `GET /api/documents/content` carries `origin_url` (+ `origin_branch` for a pinned row); a plain local fixture source → the field is ABSENT from the JSON (not `null` — the omission pinned on the wire).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the renderer pins (above) + the endpoint integration (above); every pre-existing `renderDocument` / content-endpoint pin passes unchanged (the non-git byte-identity).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the doc modal AND /document.html show the "Original" anchor (repo URL as text, `_blank` + `noopener`, the branch in the `title` when pinned) for git-sourced documents
|
||||||
|
- [ ] a non-git document's content payload and meta row are byte-identical to pre-phase (the field absent on the wire, the badge row unchanged)
|
||||||
|
- [ ] no credential in the payload (a legacy embedded-token URL is pinned sanitized — the resolver's guarantee, end-to-end)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the viewer's summary panel, the date editor, the image block, the done frame, the SSE contract)
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Task 04 — the dedicated E2E: the answer carries the repo link, the modal shows the Original anchor
|
||||||
|
|
||||||
|
**Phase:** `145_git_source_links` · **Source:** `TODO.md:7` — "there always needs to be a link to the original git source if possible. I've asked a few questions like 'how does the phased execution process work for pi.dev?' And the correct answer is an explanation and then point to the skills repo in the answer so I can go download the skills for my personal use. It's important to provide the full source so users get the complete answer at once rather than extracting it bit by bit with lots of questions."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The browser-visible proof of the owner's scenario: a question about a git-sourced document produces (1) an answer that contains the repository link (the model-side teaching, through the real read result that carries the `origin:` line) and (2) a document modal whose meta row carries the "Original" external anchor. A local-sourced document produces neither (the byte-identity guard).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/mock_llm.py` — ONE scripted flow, house style (module-header docstring entry):
|
||||||
|
- marker: the user message contains `original source link`;
|
||||||
|
- request 1: a `read` tool call for the fixture document (the flow's doc — its `origin:` line is added by the REAL server when the seeded git row matches — the mock does not fabricate it; the flow's request-2 keying must tolerate the extra line(s) between the `date:` line and the content — the mock's read-result parsing keys off the FIRST line (`_READ_RESULT_PREFIX`, L1412), so the new lines need no mock change; if the flow's echo shape copies a fixed slice of the result, the executor verifies the echo still lands on content, not the origin line, and adjusts the EOOCH slice if it does);
|
||||||
|
- request 2 (the read result present): the final answer — a DETERMINISTIC string containing the seeded repository URL verbatim (e.g. `The full source lives at https://example.com/reese/skills — see the repo for the complete original.` — the mock is scripted, so the "model includes the link" behavior is asserted on the scripted echo, while the SERVER-side half — the `origin:` line actually reaching the mock — is asserted on the request the server SENT: the E2E inspects nothing of the prompt directly (the mock records nothing), so the origin-line assertion goes through the read RESULT's surface: the SSE `tool_result`/tool frame shape the UI renders for the read — the phase-117 compact tool surface — which carries the result text; assert the rendered tool output contains `origin: https://example.com/reese/skills`).
|
||||||
|
2. `tests/e2e/test_git_source_links.py` — dedicated Playwright file, run in isolation, mock-only (the house conventions — the per-module fixture import + the git-source row seeding in the test's own DB session, the login helper, the SSE frame collection from the chat story files):
|
||||||
|
- fixture seeding: the standard E2E KB (one source, one readable doc) PLUS a `GitSource` row — `kind="git"`, `url="https://example.com/reese/skills"` (public form — no credential), `branch=None` for test 1 and `branch="main"` for the pinned-branch test — whose URL basename (`skills` after the `.git`-less path) MATCHES the fixture source's name (the resolver's name mapping — the fixture source is locally imported, but the mapping is name-based, which is the point of the seam); a SECOND plain local source (no git row) is the byte-identity control;
|
||||||
|
- test 1 (`test_answer_carries_origin_link`): ask the `original source link` question on the git-matched source's doc → collect the SSE → assert the rendered tool output for the `read` carries `origin: https://example.com/reese/skills` (the server put the line in the result the model saw) and the final `done` answer contains the repository URL (the scripted echo — the model-side contract, deterministic);
|
||||||
|
- test 2 (`test_modal_shows_original_anchor`): same setup → click the source chip → `#doc-modal` rendered → the meta row contains the `.doc-origin` anchor with `href="https://example.com/reese/skills"`, `target="_blank"`, `rel="noopener"`, `textContent` = the URL verbatim (and NO branch in the text — `branch=None`);
|
||||||
|
- test 3 (`test_pinned_branch_in_title`): the `branch="main"` row → the same anchor's `title` is `https://example.com/reese/skills — branch: main`;
|
||||||
|
- test 4 (`test_local_source_has_no_origin`): the control source's doc → the read's rendered tool output carries NO `origin:` line (byte-identical result shape) and the modal's meta row has NO `.doc-origin` anchor (the pre-phase badge row).
|
||||||
|
3. Run the regression set in isolation: this file + `tests/e2e/test_read_line_ranges.py` (the read-result shape contract through the mock) + `tests/e2e/test_document_viewer.py` (the `renderDocument` meta row).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: `uv run pytest tests/e2e/test_git_source_links.py -v --no-cov` — green IN ISOLATION (DB up: `podman compose up -d db`), mock-only.
|
||||||
|
- Regression: the two named files green in isolation.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the read's tool output carries the sanitized `origin:` line (git-matched source) and the done answer carries the repository URL (tests 1–3)
|
||||||
|
- [ ] the modal's meta row shows the "Original" anchor (URL verbatim text, `_blank`+`noopener`, the pinned branch in the `title` — tests 2–3)
|
||||||
|
- [ ] the local-source control is byte-identical: no `origin:` line in the read result, no anchor in the meta row (test 4)
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_git_source_links.py -v --no-cov` green in isolation; the regression E2Es green in isolation
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the mock's first-line parsing, the done frame, the local-source payloads/results)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Phase 146 — the search tool line shows WHERE the LLM is searching: a scoped grep carries its document
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L3 — "The "search" tool in the UI doesn't show where the LLM is searching. This results in, what looks like, multiple search tool calls with the same value, like the LLM is repeating itself."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/agent.py` — the `grep` tool definition (~L395–441: required `pattern` + optional `path` — "Rarely needed — only for re-searching one document you already know: that document's combined `source/path` identity"); `app/api/chat.py` — the `ToolCallPiece` → SSE `tool` frame builder (~L909–947: `argument = piece.arguments.get("pattern" if piece.name == "grep" else "path")` — a scoped grep's `path` argument is DROPPED today, so every search line renders the same pattern); `app/schemas.py` — `ChatToolEvent` (L182: `{name, argument, offset?, limit?}` — the additive-omission serializer precedent is `DocContent._serialize` dropping `image_url` when None); `frontend/assets/app.js` — `appendToolLine` (~L1122: the grep branch renders `🔎 Searching for <code>pattern</code>` — no scope, byte-identical for bare and scoped calls), the live tool-frame handler (~L3178–3230: `ev.offset`/`ev.limit` additive wire fields + the `toolRecord` stamp — the exact pattern this phase extends with `ev.path`), the restore path (~L2064–2086: re-renders saved `{name, argument, offset?, limit?}` records through the same helper); `tests/e2e/mock_llm.py` — the scripted-turn idiom (the phase-70/72 `grep` scripted branches — the house way of driving a model tool call deterministically).
|
||||||
|
**Locked (owner delegation 2026-09-30, chat — "pick the best choices"):** the fix is the missing SCOPE: the `tool` frame additively carries the grep's optional `path` (the re-searched document's combined `source/path`), and the UI renders it — `🔎 Searching for <pattern> in <source/path>` — so a whole-KB search and a re-search of one document are visibly different (the "repeating itself" confusion is gone). Bare greps render byte-identical to pre-phase. The scope also rides the status label ("… is searching for X in Y") and persists additively on the saved turn's tool record (`bor.chat.v1` JSONB — old records restore byte-identically, no migration).
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A grep that re-searches a specific document shows THAT document in the chat's tool line and status label, so repeated patterns with different scopes read as distinct searches; every bare-grep rendering (live, restored, persisted) is byte-identical to pre-phase.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `145_git_source_links` (todo) — pipeline order only; no shared code (this phase touches the tool-frame wire + the chat tool-line renderer; 145 touches read results + the doc viewer meta row).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The wire (task 01):** `ChatToolEvent` gains `path: str | None = None` — ADDITIVE-OMISSION: a `model_serializer(mode="wrap")` drops the key when None (the `DocContent` `image_url` precedent), so every frame that is not a scoped grep serializes byte-identical to pre-phase. The frame builder sets it ONLY for `piece.name == "grep"` when `piece.arguments.get("path")` is a string (a non-string `path` is a model error the backend already refuses — the guard just yields None → omitted). Legacy tool names never appear on the live wire (the server only emits current names), so no legacy handling.
|
||||||
|
- **The UI (task 02):** `appendToolLine` gains a fifth `scope` parameter (default null). The grep branch appends, ONLY when `scope` is a non-empty string, a sibling `<span>` AFTER the pattern `<code>`: text node ` in ` + a second `<code>` (the scope is data, never markup; NO new emoji — the frontend emoji guard strips precisely the existing template literals, which stay untouched — the phase-139 read-range-suffix span-append precedent). The live handler reads `ev.path` (string guard), persists it on the `toolRecord` ONLY when non-null (additive JSONB key — a bare-grep record keeps the exact pre-phase shape), and extends the grep status label with ` in ${scope}`. The restore path reads the saved `t.path` through the same helper — a record saved before this phase (no key) renders byte-identically.
|
||||||
|
- **The E2E (task 02):** `mock_llm.py` gains ONE scripted question branch: a scoped `grep` (`pattern` + `path`) followed by the terminal answer — the house scripted-turn idiom; the bare-grep scripted turns from phases 70/72 stay as the byte-identity pins.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_tool_frame_scope.md` — the additive `path` field on `ChatToolEvent` + the frame builder + the serialization matrix.
|
||||||
|
2. `02_ui_scope_render_e2e.md` — the tool line + status label + persisted record + restore path + the dedicated E2E.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the frame-serialization matrix (scoped grep / bare grep / read / ls / null-argument — non-scoped frames byte-identical pins).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only.
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a scoped grep streams `{"type": "tool", "name": "grep", "argument": <pattern>, "path": <source/path>}`; a bare grep's frame is byte-identical to pre-phase (`path` key ABSENT, not null); read/ls frames unchanged
|
||||||
|
- [ ] the chat tool line for a scoped grep reads `🔎 Searching for <pattern> in <source/path>` (two `<code>` spans, no new emoji); the bare-grep line is byte-identical (the phase-70/87/117 pins pass unchanged)
|
||||||
|
- [ ] the status label says "… is searching for <pattern> in <source/path>" for a scoped grep only
|
||||||
|
- [ ] a saved scoped-grep turn persists `path` on the tool record and re-renders the scope on restore; pre-phase saved records restore byte-identically
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_search_tool_scope.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the read/ls tool lines, the disclosure count, the saved-turn JSON shape for non-scoped records, the done frame)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Task 01 — the `tool` frame carries the grep's scope: additive `path` on `ChatToolEvent`
|
||||||
|
|
||||||
|
**Phase:** `146_search_tool_scope` · **Source:** `TODO.md:3` — "The "search" tool in the UI doesn't show where the LLM is searching. This results in, what looks like, multiple search tool calls with the same value, like the LLM is repeating itself."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The SSE `tool` frame for a SCOPED grep (a re-search of one document — `grep(pattern, path)`) carries the document's combined `source/path` identity as an additive `path` field, so the UI can show WHERE the search runs. Every frame that is not a scoped grep serializes byte-identical to pre-phase.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/schemas.py` — `ChatToolEvent` (L182): add `path: str | None = None` with a `@model_serializer(mode="wrap")` that pops `path` when it is None (the `DocContent._serialize` `image_url`-omission precedent — the key is ABSENT from the wire, never `null`). Update the class docstring: the A15 extension line gains the phase-146 note (a scoped grep's optional `path` — the re-searched document's combined `source/path` — is the ONLY case the field is present).
|
||||||
|
2. `app/api/chat.py` — the `ToolCallPiece` branch (~L915–947, where `argument` is extracted): compute, for `piece.name == "grep"` ONLY, `scope = piece.arguments.get("path")` and coerce with the same string guard as `argument` (`scope if isinstance(scope, str) else None` — a non-string `path` is a model error the agent already refuses; the guard just yields None → omitted). Pass `path=scope` to the `ChatToolEvent(...)` constructor. No other event type, tool name, or field is touched — read/ls frames and every non-scoped grep keep the exact pre-phase wire bytes (the wrap serializer does the omission).
|
||||||
|
3. `tests/unit/` — the `ChatToolEvent` serialization home (the existing SSE-frame unit file — `tests/unit/test_chat*.py`; if no frame serializer test exists yet, create one following the house layout): the matrix —
|
||||||
|
- scoped grep: `name="grep"`, `argument="pattern"`, `path="srcs/doc.md"` → the dumped dict has `type`, `name`, `argument`, AND `path` (exact values);
|
||||||
|
- bare grep: `path=None` → the dumped dict has NO `path` key (assert `"path" not in data` — not `null`);
|
||||||
|
- `read` (with and without offset/limit) and `ls` (with and without argument) → NO `path` key, byte-identical to pre-phase (assert the full dumped dict equality against the literal pre-phase shape);
|
||||||
|
- grep with a NON-string `path` (the model-error shape, e.g. a list) → the builder yields `path=None` → omitted (this case is pinned at the builder level in the step-4 test).
|
||||||
|
4. `tests/unit/` — the frame-builder test (the chat-endpoint unit home that already drives `ToolCallPiece` handling, if one exists — otherwise a focused unit test constructing the piece and invoking the same extraction): grep piece with `arguments={"pattern": "p", "path": "s/d.md"}` → event carries both; grep piece with `arguments={"pattern": "p"}` → no scope; grep piece with `arguments={"pattern": "p", "path": 42}` → scope None (omitted); read/ls pieces → scope never read from their arguments.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the two matrices above; every pre-existing frame pin passes UNCHANGED (byte-identity of non-scoped frames is the point).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a scoped grep's `tool` frame carries `path` = the model's `path` string; a bare grep's frame has no `path` key at all
|
||||||
|
- [ ] read/ls/null-argument frames dump to the exact pre-phase dict (equality pins)
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no other SSE event type or agent-tool surface is touched
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 02 — the tool line + status label show the search scope, live and restored; the dedicated E2E
|
||||||
|
|
||||||
|
**Phase:** `146_search_tool_scope` · **Source:** `TODO.md:3` — "The "search" tool in the UI doesn't show where the LLM is searching. This results in, what looks like, multiple search tool calls with the same value, like the LLM is repeating itself."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A scoped grep renders `🔎 Searching for <pattern> in <source/path>` in the tool line and "… is searching for <pattern> in <source/path>" in the status label — live, persisted on the saved turn (additively), and re-rendered on restore. Every bare-grep rendering is byte-identical to pre-phase.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/app.js` — `appendToolLine` (~L1122): add a fifth parameter `scope = null`. In the grep branch (the `(name === "grep" || name === "search_documents") && argument` arm), AFTER the pattern `<code>` child, append ONLY when `typeof scope === "string" && scope` — the phase-139 read-range-suffix pattern: a `<span>` (class `grep-scope`) containing a text node ` in ` and a second `<code>` whose `textContent = scope` (the scope is data, never markup). The existing `🔎 Searching for ` template literal and the pattern `<code>` are untouched (the frontend emoji guard strips precisely those glyphs in this file — NO new emoji is introduced). A null/empty scope → no span → the line is byte-identical to pre-phase.
|
||||||
|
2. `frontend/assets/app.js` — the live tool-frame handler (~L3178): read `const framePath = typeof ev.path === "string" && ev.path ? ev.path : null;` (the `ev.offset`/`ev.limit` guard style); add it to the `toolRecord` ONLY when non-null (`if (framePath !== null) toolRecord.path = framePath;` — the additive `bor.chat.v1` JSONB convention: a bare-grep record keeps the exact pre-phase `{name, argument}` shape, old records restore byte-identically, no migration); pass `framePath` as `appendToolLine`'s fifth argument; extend the grep status label — `(name === "grep" || name === "search_documents") && argument` → `` `${brand()} is searching for ${argument}${framePath ? ` in ${framePath}` : ""}` `` (bare grep → byte-identical label).
|
||||||
|
3. `frontend/assets/app.js` — the restore path (~L2064–2086): inside the `m.tools` loop, read the saved scope with the same guard (`const tPath = typeof t.path === "string" && t.path ? t.path : null;`) and pass it to `appendToolLine(wrap, t.name, arg, tOffset, tLimit, tPath)` — a record saved before this phase (no `path` key) renders byte-identically (the phase-95 truncation-note precedent: it keys on the `<code>` argument, not the scope).
|
||||||
|
4. `tests/e2e/mock_llm.py` — one new scripted-question branch (the house scripted-turn idiom, modeled on the phase-70/72 `grep` branches): a sentinel question → the model streams ONLY a `tool_calls` delta calling `grep` with `{"pattern": <sentinel>, "path": "<fixture source>/<fixture doc>"}` (id `call_0`) → the follow-up round (tool result present) streams the terminal answer. The fixture source/doc pair must exist in the session app's indexed KB (the same fixture the `grep` scripted branches already use — reuse its source/path so the agent's real grep finds matches; the exact path string the UI renders is the model's, so use the fixture's real combined identity). The EXISTING bare-grep scripted turns are untouched (they are the byte-identity pins).
|
||||||
|
5. `tests/e2e/test_search_tool_scope.py` — the dedicated E2E (one Playwright file, run in isolation, mock-only — the house module-app pattern if the scripted mock lives in the session app, else the session app directly):
|
||||||
|
- **scoped line:** ask the scripted question → after the tool frame, the `.tool-calls` list holds one `.tool-call` whose text is `🔎 Searching for <pattern> in <source/path>` — assert the TWO `<code>` spans (pattern, then scope) and the ` in ` text node between them (textContent structure, not a regex over the whole line — the pin style of the phase-139 range-suffix assertions);
|
||||||
|
- **status label:** while the turn is live (before the delta frames), the typing indicator/status carries `… is searching for <pattern> in <source/path>`;
|
||||||
|
- **bare-grep byte-identity:** an existing bare-grep scripted question renders exactly the pre-phase line `🔎 Searching for <pattern>` (ONE `<code>` span, no `.grep-scope` span) and the pre-phase status label;
|
||||||
|
- **restore:** save the scoped turn (the save affordance), reload the chat, the restored turn's tool line re-renders the scope through the same structure (folded disclosure — the phase-117 shape is unchanged).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: the assertions above; every pre-existing tool-line pin (phase-70 labels, phase-87 clock, phase-117 disclosure, phase-139 range suffix) passes UNCHANGED — the byte-identity of bare greps is the point.
|
||||||
|
- Coverage: n/a (frontend task — the E2E is the gate; `app/` coverage stays >90% from task 01).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a scoped grep's tool line shows the scope in a second `<code>` span after the pattern; the status label carries ` in <scope>`; both live and on restore
|
||||||
|
- [ ] a bare grep renders byte-identical to pre-phase in every surface (live line, status, saved record shape, restored line)
|
||||||
|
- [ ] the saved scoped record carries `path` additively; pre-phase saved records (no key) restore byte-identically
|
||||||
|
- [ ] `uv run pytest` green (all pre-existing suites); `uv run pytest tests/e2e/test_search_tool_scope.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no new emoji anywhere in `app.js` (the frontend emoji guard stays green)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Phase 147 — sync only what changed: the source file's byte hash is checked BEFORE extraction and vision
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L4 — "Local sources, like PDFs, are synced every time even if they haven't changed. This results in really long sync times for PDFs that are mostly pictoral. Only sync documents if they've changed since the last sync (hash the document contents to check)."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** `app/rag/importer.py` — `import_sources` (L560: the per-source walk; the `progress`/`on_chunk_progress` hooks fire per file before indexing — unchanged by this phase), `_index_file` (L879: the single upsert entry — dispatches image → `_index_image_file` (L2642), `.pdf` → `_index_pdf_file` (L1181), text fallback), and the three per-branch unchanged blocks that today run only AFTER the expensive work: text (L~928: digest over the read text — cheap, the read itself is the cost), image (L~2660: digest over `read_bytes()` — the vision description runs only on a digest MISS, already fine), PDF (L~1303: digest over the FINAL constructed content — reached only after `extract_pdf_text` (L162 of `app/rag/pdf.py`) ALWAYS runs and, for garbage layers, `_fallback_page_screenshots` (every page rendered + vision-described) or, for sparse layers with `pdf_pictorial` on, `_pictorial_pdf_pass` (every candidate page rendered + vision-described) — so an UNCHANGED pictorial PDF re-extracts and re-burns vision on EVERY sync; a non-deterministic vision model additionally flips the final-content digest and forces a full re-chunk/re-embed/re-summary each run — the owner's "synced every time even if they haven't changed"). `Document.content_hash` (app/models.py L112) is the FINAL-CONTENT digest (exposed via `app/rag/retriever.py` L203/426/555/611 — the dedupe/caching identity) and stays untouched; the new `file_hash` is the RAW SOURCE-FILE-BYTES digest, compared first, used for change detection only. `alembic/versions/` — the latest migration is `0024_git_source_branch.py`. The unchanged-block semantics that must survive the fast path (all three branches, identical shape): `summary.unchanged += 1` + log; the phase-118 (A2) summary-NULL backfill; the phase-106 (D1) `created_at_manual` early-return; the phase-106 (D4) date refresh (`normalize_doc_date` of the raw_date — mtime fallback — may go OLDER, counts `summary.dates_updated`, commits).
|
||||||
|
**Locked (owner delegation 2026-09-30, chat — "pick the best choices"):** change detection = sha256 of the RAW FILE BYTES (the owner's "hash the document contents"), computed ONCE at the top of `_index_file` — before the image/text/PDF dispatch — and compared against a new `documents.file_hash` column (migration 0025, nullable). A match takes a shared unchanged fast path: NO file read (beyond the streamed hash), NO PDF extraction, NO vision call, NO embed, NO summary call — only the preserved bookkeeping (summary-NULL backfill from the STORED `doc.content`, manual-date early-return, date refresh). Pre-phase rows (`file_hash` NULL) fall through to the branches' existing logic exactly as today and get their hash STAMPED on that first post-upgrade sync (one full pass, then fast forever). `content_hash` and everything built on it (retriever exposure, chunk identity) are untouched.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
An unchanged source file costs one streamed sha256 and a row lookup per sync — zero extraction, zero vision, zero embedding, zero summary LLM — across all three document classes (text, image, pictorial PDF), while every preserved unchanged-path behavior (summary backfill, manual-date lock, date refresh, counts) is byte-for-byte maintained.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `146_search_tool_scope` (todo) — pipeline order only; no shared code (this phase touches the importer + one migration; 146 touches the tool-frame wire + the chat renderer).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **The column (task 01):** `alembic/versions/0025_documents_file_hash.py` — `documents.file_hash` `String(64)`, **nullable, no index** (it is compared in Python after the unique `(source, path)` lookup — unlike `content_hash`, it is never a query surface and never exposed to the retriever); downgrade drops it. `Document.file_hash: Mapped[str | None]` + docstring (the raw source-file-bytes sha256 — the sync change signal; DISTINCT from `content_hash` — the final indexed content's digest, which for a pictorial PDF includes vision text and is the retriever's identity).
|
||||||
|
- **The fast path (task 02):**
|
||||||
|
- `_file_hash(path: Path) -> str` — sha256 over the raw bytes, streamed in 1 MiB chunks (a multi-hundred-MB PDF never loads fully; the `hashlib` incremental pattern).
|
||||||
|
- `_index_file` top (before the image/PDF/text dispatch): `file_digest = _file_hash(full_path)`; the row lookup (the `(source, path)` scalar select the branches already do — moved up); `if doc is not None and doc.file_hash == file_digest:` → `_unchanged_doc(...)` → **return**. The `raw_date` mtime fallback (the D2 convention: read before the unchanged early-return — the branches already do this; the fast path needs it for the date refresh) is computed in `_index_file` before the check when `raw_date is None`.
|
||||||
|
- `_unchanged_doc(session, doc, *, source, rel, llm, summary, raw_date)` — the ONE shared implementation of the three near-identical unchanged blocks: `summary.unchanged += 1` + the `import: unchanged` log line (unchanged wording); the phase-118 (A2) backfill when `doc.summary is None` — `content=doc.content` (EXACTLY what the bytes produced — for text the stored content IS the file text; for an image the stored description; for a PDF the stored final content — so the backfill never re-reads/re-extracts/re-describes); the D1 `created_at_manual` early-return; the D4 date refresh (`target = normalize_doc_date(raw_date)`; on change: commit + `summary.dates_updated` + the `import: date-refreshed` log line — unchanged wording). The three branches' existing unchanged blocks are REPLACED by the shared helper (the per-branch callsite passes the same arguments; behavior is identical, code is one site).
|
||||||
|
- **Hash stamping:** every branch writes `doc.file_hash = file_digest` on create AND update (all three — text, image, PDF — `file_digest` passed down from `_index_file`). The fast path makes the stamp redundant for the common case, but a bytes-changed/content-same edge (e.g. a PDF metadata edit with identical extracted text) lands in a branch whose content digest still matches — the branch's unchanged flow (now the shared helper) ALSO stamps `doc.file_hash = file_digest` and commits when it is dirty (the date-refresh commit may already have run — stamp BEFORE that block's final decision: set the attribute, and commit once at the end of the helper if dirty) so the NEXT sync takes the fast path. Pre-phase rows (`file_hash` NULL) take exactly this path on the first post-upgrade sync (full pipeline or the shared helper — whichever the branch's content digest decides) and are stamped either way.
|
||||||
|
- The `progress`/`on_chunk_progress` hooks are untouched (the `progress` call fires per file before `_index_file` as today — an unchanged file was already "the current file" pre-phase; the fast path just makes it cheap). `summary.files` counts the walked file either way. Pruning, `limit`, the per-source post-index passes (`_enrich_pending_images`, `_backfill_image_contexts` — row-driven) are untouched.
|
||||||
|
- **The E2E (task 03):** the `file://` fixture-repo module-app idiom (the `test_sync_button.py` recipe — real clone, mock LLM): run 1 (N added) → capture every document row's `indexed_at`/`content_hash` → run 2 → the settle line reads `0 added · 0 updated · N unchanged` and every row's `indexed_at`/`content_hash` is unchanged (the re-index would bump `indexed_at`) → commit a new file to the fixture repo → run 3 → only the new file is `added`.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_file_hash_column.md` — migration 0025 + the model field.
|
||||||
|
2. `02_unchanged_fast_path.md` — the streamed hash, the top-of-`_index_file` check, the shared unchanged helper, the stamping, the branch rewiring, the unit matrix.
|
||||||
|
3. `03_e2e_unchanged_second_run.md` — the dedicated E2E: the idempotent second sync is provably free of re-indexing.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the fast-path matrix (text / image / garbage-PDF / pictorial-PDF unchanged → zero LLM calls; changed → full pipeline + stamp; NULL hash → pre-phase behavior + stamp; D1/D4 pins on the fast path; the streamed hash on a >1 MiB file).
|
||||||
|
- Integration: the migration upgrade/downgrade round-trip (the house migration-test idiom).
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only (real git clone).
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `documents.file_hash` exists (nullable String(64), no index) via migration 0025; the upgrade/downgrade round-trips on the test DB
|
||||||
|
- [ ] an unchanged text file, image, garbage-layer PDF, and pictorial PDF each cost ZERO llm calls (embed + chat) and zero PDF extraction/vision on the second sync — `summary.unchanged` counts them; `indexed_at`/`content_hash` untouched
|
||||||
|
- [ ] a changed file (any byte) re-indexes fully and stamps the new hash; a bytes-changed/content-same file stamps the hash without a content change
|
||||||
|
- [ ] the preserved unchanged semantics are pinned: summary-NULL backfill, `created_at_manual` early-return, the date refresh (may go older, counts `dates_updated`, commits), the log-line wordings
|
||||||
|
- [ ] `content_hash` and the retriever's exposure of it are byte-identical to pre-phase
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_sync_changed_only.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (prune semantics, `limit`/`progress` contracts, the per-source post-index passes, the sync status/result wire)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Task 01 — migration 0025: `documents.file_hash` (the raw source-file-bytes digest)
|
||||||
|
|
||||||
|
**Phase:** `147_sync_changed_only` · **Source:** `TODO.md:4` — "Local sources, like PDFs, are synced every time even if they haven't changed. This results in really long sync times for PDFs that are mostly pictoral. Only sync documents if they've changed since the last sync (hash the document contents to check)."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The `documents` table gains `file_hash` — the sha256 of the RAW SOURCE FILE's bytes — the column the task-02 fast path compares before any extraction or vision work. Existing rows stay NULL (= "unknown" — one full pipeline pass stamps them on the next sync; no backfill is possible in a migration — the migration cannot see the source files on disk).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `alembic/versions/0025_documents_file_hash.py` — `revision = "0025"`, `down_revision = "0024"`:
|
||||||
|
- `upgrade`: `op.add_column("documents", sa.Column("file_hash", sa.String(length=64), nullable=True))` — **no index** (the fast path compares it in Python after the unique `(source, path)` lookup; unlike `content_hash` — indexed because it is a query/exposure surface — `file_hash` is internal bookkeeping) and no server default (NULL is the meaningful pre-phase state).
|
||||||
|
- `downgrade`: `op.drop_column("documents", "file_hash")`.
|
||||||
|
2. `app/models.py` — `Document` (L102): add, directly below `content_hash` (L112), `file_hash: Mapped[str | None] = mapped_column(String(64), default=None)` with a docstring in the house style: the sha256 of the RAW SOURCE FILE's bytes at index time (phase 147) — the sync's change signal, compared at the top of the importer's `_index_file` BEFORE the image/text/PDF dispatch (an unchanged file costs one streamed hash + one lookup — no extraction, no vision, no embed). NULL for pre-phase rows and until the first post-upgrade sync stamps it. DISTINCT from `content_hash` — the FINAL indexed content's digest (a pictorial PDF's includes vision text; `content_hash` is exposed via `app/rag/retriever.py` and is the dedupe/caching identity — untouched).
|
||||||
|
3. Tests (the house migration-test idiom — the integration test that upgrades the test DB to head, or the models unit home): the column exists, is nullable, is NOT indexed (assert against the live table metadata after `upgrade head`); the `Document` model exposes `file_hash` (default None); a row created with no `file_hash` round-trips NULL (the pre-phase shape).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Integration: migration upgrade (to head) + downgrade + re-upgrade round-trip on the test DB (the existing migration-test pattern — extend it, don't fork it).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `0025_documents_file_hash` chains from `0024` and upgrades/downgrades cleanly on the test DB
|
||||||
|
- [ ] `file_hash` is nullable String(64) with no index; `content_hash` (indexed, exposed) is untouched
|
||||||
|
- [ ] `Document.file_hash` defaults to None and carries the house-style docstring distinguishing it from `content_hash`
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Task 02 — the unchanged fast path: hash first, then skip extraction, vision, and embedding
|
||||||
|
|
||||||
|
**Phase:** `147_sync_changed_only` · **Source:** `TODO.md:4` — "Local sources, like PDFs, are synced every time even if they haven't changed. This results in really long sync times for PDFs that are mostly pictoral. Only sync documents if they've changed since the last sync (hash the document contents to check)."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
An unchanged file (raw bytes identical to the last index) is detected at the TOP of `_index_file` — before the image/text/PDF dispatch — and takes one shared unchanged path with ZERO llm calls, ZERO PDF extraction, and ZERO vision work, while the three branches' existing unchanged semantics (summary-NULL backfill, manual-date early-return, date refresh) survive verbatim, and every newly indexed/updated document stamps its file hash.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/rag/importer.py` — new helper `_file_hash(path: Path) -> str` (module level, near the other file helpers): sha256 of the raw bytes, streamed in 1 MiB chunks (`open(path, "rb")` + `hashlib.sha256()` incremental `update` in a loop — a large PDF never loads fully into memory).
|
||||||
|
2. `app/rag/importer.py` — new helper `async def _unchanged_doc(session, doc, *, source, rel, llm, summary, raw_date, file_digest)` — the ONE shared implementation of the three near-identical per-branch unchanged blocks (text ~L928, image ~L2660, PDF ~L1303), in this exact order with UNCHANGED log wordings and counts:
|
||||||
|
1. `summary.unchanged += 1` + `logger.info("import: unchanged source=%s path=%s", source, rel)`;
|
||||||
|
2. **stamp** `doc.file_hash = file_digest` (a pre-phase NULL row, or a bytes-changed/content-same row, learns its hash here — see step 5);
|
||||||
|
3. the phase-118 (A2) backfill when `doc.summary is None` — `await _store_summary(session, doc=doc, source=source, rel=rel, content=doc.content, llm=llm, summary=summary, backfill=True)` (EXACTLY what the file's bytes produced is already stored in `doc.content` for all three classes — text: the file text; image: the vision description; PDF: the final constructed content — so the backfill never re-reads the file, never re-extracts, never re-describes; the text branch's pre-phase `content` variable was the freshly-read file text — byte-identical to `doc.content` by the digest-equality invariant);
|
||||||
|
4. the D1 early-return: `if doc.created_at_manual: return` (no write at all — the manual correction survives);
|
||||||
|
5. the D4 date refresh: `target = normalize_doc_date(raw_date)`; `if target != doc.created_at:` set + `session.commit()` + `summary.dates_updated += 1` + the `import: date-refreshed` log line (unchanged wording) — the date may go OLDER, no monotonic guard;
|
||||||
|
6. **final commit for the stamp**: if the row is still dirty after the date block (the stamp set `file_hash` and the date did not change) → `session.commit()` (quiet bookkeeping — no count, no log: the `unchanged` line already fired; a date-change run already committed in step 5).
|
||||||
|
3. `app/rag/importer.py` — `_index_file` (L879): BEFORE the image/PDF/text dispatch:
|
||||||
|
- `file_digest = _file_hash(full_path)` (every class hashes the raw bytes — images, text, PDFs alike; this is the single change signal, per the owner's "hash the document contents");
|
||||||
|
- the row lookup moves up here: `doc = session.scalar(select(Document).where(Document.source == source, Document.path == rel))` (the branches keep their OWN lookups only if the fast path was not taken — see step 4);
|
||||||
|
- `if raw_date is None: raw_date = file_mtime_datetime(full_path)` (the D2 fallback, read before the unchanged early-return — the branches' existing convention, now once at the top);
|
||||||
|
- `if doc is not None and doc.file_hash == file_digest: await _unchanged_doc(session, doc, source=source, rel=rel, llm=llm, summary=summary, raw_date=raw_date, file_digest=file_digest); return` — **zero** further work: no `read_text`, no `read_bytes`, no `extract_pdf_text`, no fallback/pictorial vision, no `_replace_content_chunks`, no `_store_summary` (unless the backfill fires).
|
||||||
|
4. `app/rag/importer.py` — the three branches, rewired minimally:
|
||||||
|
- each branch receives `file_digest` (and the already-computed `raw_date`) from `_index_file`; their internal unchanged blocks are REPLACED by the `_unchanged_doc` call (same arguments — one code site for the semantics);
|
||||||
|
- their create/update writes gain `doc.file_hash = file_digest` (all three — the `Document(...)` constructor for new rows, the `doc.file_hash = ...` line for updates, next to `content_hash`);
|
||||||
|
- their existing row lookups and content-digest computations STAY (reachable only when `file_hash` is NULL — pre-phase row — or the bytes changed: the content digest then decides changed vs. the shared helper, and the helper stamps the new hash);
|
||||||
|
- the image branch's `data = full_path.read_bytes()` and the text branch's `read_text` happen only AFTER the fast-path return point (unchanged — the dispatch is what gates them), so the fast path genuinely pays nothing beyond the streamed hash + lookup.
|
||||||
|
5. `app/rag/importer.py` — docstrings: `_index_file`'s gains the phase-147 paragraph (the fast path: what it skips, the NULL-hash fall-through, the stamping rule); the three branches' "unchanged path" docstring lines are updated to point at the shared helper; the module docstring's A9-format paragraph is untouched.
|
||||||
|
6. `tests/unit/` — the importer unit home (the existing `tests/unit/test_importer*.py` matrix — extend it): with a call-counting fake llm (embed + chat both counted):
|
||||||
|
- **text unchanged:** index a file, capture the llm call count; re-run `import_sources` → `summary.unchanged == 1`, ZERO new llm calls, `summary.files == 1`, the doc's `indexed_at`/`content_hash` unchanged, `file_hash` stamped after run 1;
|
||||||
|
- **garbage-layer PDF unchanged:** a no-text-layer PDF (the house fixture recipe) indexed with the fake vision; re-run → `summary.unchanged == 1`, ZERO new llm calls (the fallback vision did NOT re-fire — the owner's core complaint), the content row byte-identical;
|
||||||
|
- **pictorial PDF unchanged:** a sparse-page PDF (`pdf_pictorial` on, fake vision) indexed; re-run → ZERO new llm calls (the pictorial pass did NOT re-fire);
|
||||||
|
- **image unchanged:** re-run → ZERO new llm calls;
|
||||||
|
- **changed file:** flip one byte → re-run → `summary.updated == 1`, the llm calls fire again, `file_hash` re-stamped, `indexed_at` bumped;
|
||||||
|
- **pre-phase row (NULL `file_hash`):** a row with content but NULL `file_hash` (seeded directly) + an unchanged file → the branch's content-digest path runs (today's behavior — the llm may or may not be called per the digest match) AND the hash ends stamped (both the changed and the shared-helper outcomes);
|
||||||
|
- **D1/D4 on the fast path:** an unchanged file with `created_at_manual=True` → no write at all (the date stays the manual value, no commit beyond the stamp — assert the row's date unchanged and the flag intact); an unchanged file whose mtime-derived date differs → the date refreshes (may go older), `dates_updated == 1`;
|
||||||
|
- **summary-NULL backfill on the fast path:** an unchanged doc with `summary=None` → the backfill runs from `doc.content` (ONE `is_summary` chunk, no content re-embed — the phase-118 pin, now via the shared helper);
|
||||||
|
- **streamed hash:** a >1 MiB temp file hashes identically to `hashlib.sha256(bytes).hexdigest()` (the chunking is transparent).
|
||||||
|
7. The sync status/result wire (`app/api/sync.py` + `ImportSummary` fields) is UNTOUCHED — the fast path feeds the same `unchanged`/`dates_updated`/`added`/`updated` counts the UI already renders.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the matrix above — the ZERO-llm-call assertions on the second sync are the load-bearing pins (the owner's "really long sync times for PDFs that are mostly pictoral" is fixed when a pictorial PDF's second sync burns no vision).
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`); the pre-phase importer pins (progress pre-walk, `limit`, prune, the post-index passes) pass UNCHANGED.
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] the fast path fires on a `file_hash` match for all three classes and returns before any branch code (zero llm/extraction/vision — pinned by call counters)
|
||||||
|
- [ ] the shared `_unchanged_doc` preserves the unchanged semantics verbatim: counts, log wordings, the backfill (from `doc.content`), the D1 early-return, the D4 refresh (may go older, commits, counts)
|
||||||
|
- [ ] every create/update in all three branches stamps `file_hash`; the shared helper stamps NULL/changed rows too (the next sync is always fast)
|
||||||
|
- [ ] pre-phase rows behave exactly as today on the first post-upgrade sync and are stamped
|
||||||
|
- [ ] `content_hash`, the retriever, the progress/chunk hooks, pruning, and the per-source post-index passes are byte-identical to pre-phase
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Task 03 — the dedicated E2E: the idempotent second sync provably re-indexes nothing
|
||||||
|
|
||||||
|
**Phase:** `147_sync_changed_only` · **Source:** `TODO.md:4` — "Local sources, like PDFs, are synced every time even if they haven't changed. This results in really long sync times for PDFs that are mostly pictoral. Only sync documents if they've changed since the last sync (hash the document contents to check)."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
End-to-end proof, through the real UI + the real sync path (a real `git clone` of a local `file://` fixture repo, a real import against the mock LLM): the second sync of an unchanged source reports everything unchanged and touches no document row; a source change syncs ONLY the changed part.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `tests/e2e/test_sync_changed_only.py` — the dedicated suite (one Playwright file, run in isolation; the `test_sync_button.py` module-app idiom — the module app boots with `BOR_GIT_SOURCES=file://<fixture repo>` + its own `BOR_SOURCES_DIR` on its own port (env-overridable, the house port-constant pattern), the real `git` clone prerequisite, the generous `SYNC_TIMEOUT_MS`):
|
||||||
|
- **Fixture:** the house fixture-repo builder (the `test_sync_button.py` recipe — a local git repo with a few importable docs, e.g. the `notes/sync-fixture.md` sentinel doc + one or two more, committed) — NO PDF needed (the unit matrix covers the vision-skip proof; this E2E pins the WIRE + the UI settle line + the row-level proof, and stays fast/deterministic).
|
||||||
|
- **Test 1 — `test_second_sync_unchanged`:** admin login (the house `login` helper); sync run 1 → wait for the settle line (the `Synced HH:MM` pattern) → capture EVERY document row's `indexed_at` + `content_hash` + `file_hash` (via `SessionLocal` + `select(Document)`, the `test_sync_button.py` DB-assertion idiom) → assert `file_hash` is non-NULL on every row (the first sync stamped them) → sync run 2 → the settle line matches the house count shape with `0 added`, `0 updated`, and the unchanged count == the run-1 document count (`fmtSyncResult` renders `N unchanged` — assert the visible `#sync-result` text) → re-query: every row's `indexed_at`/`content_hash` UNCHANGED (a re-index would bump `indexed_at` to now — the load-bearing assertion), `file_hash` unchanged.
|
||||||
|
- **Test 2 — `test_change_syncs_only_the_change`:** from the settled state, append a NEW doc file to the fixture repo working tree + `git commit` (the house `_git` helper) → sync run 3 → the settle line shows `1 added` (and the unchanged count == the run-1 count) → DB: the new row exists with `file_hash` non-NULL; the pre-existing rows' `indexed_at`/`content_hash` unchanged.
|
||||||
|
- **Test 3 — `test_changed_file_reindexes`:** modify the fixture sentinel doc's content (append a line) + `git commit` → sync run 4 → the settle line shows `1 updated` → DB: exactly that row's `indexed_at`/`content_hash`/`file_hash` changed; the others untouched.
|
||||||
|
2. Every test leaves the app stopped (the module-app fixture teardown — the house pattern); the suite is hermetic (its own `BOR_SOURCES_DIR` under a tmp dir, its own port) so `--no-cov` isolation holds.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- E2E: the three tests above, mock-only (the module app's LLM is the mock), real git + real import; each test asserts on the VISIBLE settle line (the owner's surface) AND the DB rows (the proof).
|
||||||
|
- Coverage: n/a (E2E task — `app/` coverage stays >90% from tasks 01–02).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] run 2 of an unchanged source: the settle line reads `0 added · 0 updated · N unchanged` (N = the KB size) and no document row's `indexed_at`/`content_hash`/`file_hash` moved
|
||||||
|
- [ ] a new file syncs as `1 added` without touching the other rows; a modified file syncs as `1 updated` and only its own row changes
|
||||||
|
- [ ] every synced row carries a non-NULL `file_hash` after the first run
|
||||||
|
- [ ] `uv run pytest tests/e2e/test_sync_changed_only.py -v --no-cov` green in isolation (DB up, git on PATH — the documented prerequisite); `uv run pytest` still green (the pre-existing sync E2Es — the idempotent-second-run pins of `test_sync_button.py` etc. — pass unchanged)
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Phase 148 — pictorial PDFs show their PAGES in the sources, not their page descriptions
|
||||||
|
|
||||||
|
**Source:** `TODO.md` L5 — "For primarily pictographic PDFs it's not super helpful to see the summaries of the pages. I want to see the PDF pages in the sources. For example, the test_sources/ikea_instructions.tar are really only helpful if I can see the instruction pages, a description won't really help me. I still want to be able to ask questions, so the summary and embedding is helpful, but not when shown to the user."
|
||||||
|
**Story:** n/a (TODO-derived phase, Protocol B append).
|
||||||
|
**Context:** the owner's named fixture is the **pictorial class** — `test_sources/ikea_instructions.tar` → `besta-frame-white__AA-1272068-11-100.pdf`: 24 pages, USABLE text layer (`is_usable_pdf_text` True) but 20 of 24 pages carry <100 stripped chars (3 dense text pages, 3k–7.3k chars) — so the phase-133 screenshot fallback does NOT fire for it; the phase-140 pictorial pass (`_pictorial_pdf_pass`, gated on `pdf_pictorial` — default ON — + `pictorial_pages(texts, min_chars=100)`) describes its 20 sparse pages and appends `[Page N illustration: …]` blocks. Today the document viewer (`frontend/assets/document.js` — `renderDocument` L172, the shared core of the doc modal AND `/document.html`) shows such a PDF as its raw text content in `<pre class="doc-raw">` + the labeled Summary panel — the descriptions the owner says are "not … helpful" to a human. The rendering machinery already exists: `app/rag/pdf.py` `render_pdf_pages(pdf_path, dpi=150, pages=None)` (L311 — every page to PNG, `b""` placeholder on a per-page failure, `[]` for an unopenable file; the phase-133/140 callers). The persistent-copy convention to follow: phase 122's image copies — `settings.image_dir` (app/config.py L397, raw string, `expanduser`'d by the importer), `<doc-id>.<ext>` naming, written only after success, stale copy deleted before replacement (importer ~L2790), deleted on prune (importer `_prune` ~L2924), because "the source file is disposable: uploads are replaced on every upload, git checkouts are re-cloned, local dirs are user-edited". The viewer payload: `DocContent` (app/schemas.py — `image_url`'s additive-omission serializer is the wire precedent; the content endpoint is `GET /api/documents/content`, app/api/docs.py L165 — no doc id in the payload today, so page URLs must ride as full routes). The bytes route precedent: `GET /api/documents/{doc_id}/image` (app/api/docs.py L216 — PUBLIC, the unguessable server-minted `uuid4` IS the credential — phase-124 A4, visible on the shared page; 404 `document not found` for every non-servable case; no path parameter reaches the filesystem — the path comes from the ROW).
|
||||||
|
**Locked (owner delegation 2026-09-30, chat — "pick the best choices"):**
|
||||||
|
- **Eligibility** — a PDF gets rendered pages iff the sync ALREADY decided its text is not the useful view: the phase-133 fallback fired (unusable text layer — the screenshot class) OR the phase-140 pictorial pass ran and described ≥1 page (the sparse-page class — the IKEA fixture). Text-heavy PDFs (usable layer, zero candidates) keep the text view; `BOR_PDF_PICTORIAL=0` keeps its kill-switch semantics (no pictorial descriptions → no page strip for the sparse class — the toggle off means the pre-phase-148 viewer for those PDFs).
|
||||||
|
- **Storage** — rendered at INDEX time (phase 147's fast path makes this cost one-time-per-real-change), persisted as PNGs in a NEW `settings.pdf_page_dir` (default `~/bor-sources/pages`, `BOR_PDF_PAGE_DIR` — the `image_dir` convention) named `<doc-id>-p{N}.png` (N 1-based, every page of the PDF); `documents.page_count` (migration 0026, nullable Int) = the PDF's page count (a per-page render failure leaves a gap — the route 404s that N, the viewer shows its unavailable note); stale copies deleted on re-index, pruned, and on a document that stops qualifying.
|
||||||
|
- **Display** — the shared `renderDocument` core: for a doc with `page_urls`, the page strip (lazy `<img>`s, "Page N" captions) REPLACES the text content AND the Summary panel (the owner: the description "is helpful … but not when shown to the user" — it stays embedded + summarized for Q&A, just not displayed); the meta badge row is untouched; both surfaces (modal + full page) get it through the one core.
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A pictorial-class PDF (the IKEA assembly-instruction class) opens in the sources with its actual pages — every page as a rendered image — while text-heavy PDFs, images, and text documents render byte-identically to pre-phase, and the Q&A machinery (embeddings, summaries) is untouched.
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
- `147_sync_changed_only` (todo) — REAL coupling: the page render happens in the PDF branch's new/changed path, which phase 147's fast path makes one-time-per-real-file-change (without it, an unchanged pictorial PDF would re-render its pages every sync — the same cost the owner complained about).
|
||||||
|
|
||||||
|
## Design (shared by all tasks — the executor reads this, not the chat)
|
||||||
|
- **Index (task 01):** in `_index_pdf_file`, AFTER the final content is decided (fallback/pictorial passes done) and the doc is flushed (it has an id): when `new_or_changed` (reaching this code IS new/changed — the fast path returned earlier) AND eligible (the fallback fired, or the pictorial pass returned non-None): `pages = render_pdf_pages(full_path)` (every page, 150 dpi — the existing constant); delete this doc's stale page copies first (the image-copy stale-replacement convention); write each non-empty PNG to `pdf_page_dir` (created on demand) as `<doc-id>-p{N}.png`; `doc.page_count = len(doc)` (the PDF's page count — gaps tolerated). NOT eligible, or zero pages rendered (unopenable file — `render_pdf_pages` `[]`): `doc.page_count = None` + delete any stale copies (a doc that stops qualifying loses its strip). Fail-soft: a render/write exception → `page_count = None`, warning, the document indexes exactly as today. In `_prune` (and the PDF parent's embedded-image deletion site), a deleted page-qualifying doc's copies are removed (a shared `_delete_page_copies(doc)` helper — the `_delete_image_copy` convention; `source_removal.py` deletes rows only — the image-copy convention there — and is untouched).
|
||||||
|
- **Serve (task 02):** `GET /api/documents/{doc_id}/pages/{n}` — public (the image route's trust model verbatim: the unguessable `uuid4` is the credential; a shared chat can cite the page), `n: int` path parameter ≥ 1; 404 `document not found` for: unparseable id, unknown doc, `page_count` NULL, `n` outside `1..page_count`, missing file on disk (defensive — the viewer's onerror note); the path is built from the ROW's id + `n` (no traversal surface — `n` is an int); `image/png` + `Cache-Control: private, max-age=3600` (the image route's header). `DocContent.page_urls: list[str] | None = None` — the content endpoint fills `[f"/api/documents/{doc.id}/pages/{i}" for i in 1..doc.page_count]`; the serializer drops the key when None (the `image_url` pattern — never `null`, absent for text/image docs and non-qualifying PDFs).
|
||||||
|
- **View (task 03):** `renderDocument` (the shared core — modal + page): `doc.page_urls` a non-empty array → a `.doc-pages` strip: one `<figure class="doc-page">` per URL — `<img loading="lazy" src=url alt="Page N of {doc.title}">` + `<figcaption>Page N</figcaption>`; the markdown/`.doc-raw` content block is NOT rendered for this doc, and the Summary panel is NOT rendered (the owner's contract — the text stays in the DB for Q&A, it is simply not displayed); the meta badge row renders as today; `onerror` on an `<img>` swaps its figure for a "Page N unavailable" note (the phase-122 image-unavailable idiom, `role="status"`); `createElement`-only (the XSS contract — never innerHTML from doc data). CSS: `.doc-pages` in the existing doc content column (the ≤46rem core), figures stacked, `img { max-width: 100% }`, theme vars for border/surface/ink (both themes), `overflow-wrap` not needed (no text flows), contrast AA, `prefers-reduced-motion` irrelevant (no motion).
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
1. `01_page_render_at_index.md` — `pdf_page_dir` setting + `page_count` migration/model + the PDF-branch render/persist/cleanup + the prune hook + the unit matrix.
|
||||||
|
2. `02_page_route_and_payload.md` — the public page-bytes route + `DocContent.page_urls` + the endpoint + unit/integration tests.
|
||||||
|
3. `03_viewer_page_strip.md` — the `renderDocument` strip (content + summary suppressed for qualifying docs) + the CSS.
|
||||||
|
4. `04_e2e_pdf_pages.md` — the dedicated E2E: a synthetic pictorial PDF shows its pages in the modal + full page; a text-heavy PDF renders byte-identical.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the eligibility matrix × {new, changed, unchanged-fast-path, unopenable}; copy naming/stale-cleanup/prune-deletion; the route matrix; the payload omission rule.
|
||||||
|
- Integration: the content endpoint returns `page_urls` for a seeded page-qualifying doc and omits the key otherwise.
|
||||||
|
- E2E: one dedicated Playwright file, run in isolation, mock-only (the house PyMuPDF fixture recipe).
|
||||||
|
- Coverage: **>90%** on new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a pictorial-class PDF (IKEA shape: usable layer, ≥1 sparse page) and a fallback-class PDF (unusable layer) get `<doc-id>-p{N}.png` copies for every page + `page_count` = the page count; a text-heavy PDF gets neither
|
||||||
|
- [ ] an unchanged qualifying PDF's second sync (phase 147 fast path) re-renders nothing (the copies persist, zero render calls)
|
||||||
|
- [ ] re-indexing a changed PDF replaces its copies (no stale `p{N}` orphans); a PDF that stops qualifying loses them; pruning deletes them
|
||||||
|
- [ ] `GET /api/documents/{id}/pages/{n}` serves the PNG (public, uuid4-credential model) and 404s every non-servable case; `DocContent.page_urls` is present for qualifying docs and the key is ABSENT otherwise
|
||||||
|
- [ ] the modal AND /document.html show the page strip for qualifying docs (lazy imgs, "Page N" captions) with the text content + Summary panel suppressed; every other document renders byte-identical to pre-phase
|
||||||
|
- [ ] `uv run pytest --cov=app --cov-report=term-missing` green, `app/` coverage >90%; `uv run pytest tests/e2e/test_pdf_pages_in_sources.py -v --no-cov` green in isolation; `uv run ruff check . && uv run pyright` clean
|
||||||
|
- [ ] no behavior change in completed phases (the fallback/pictorial content, `content_hash`, embeddings/summaries, the image route, the doc-edit/date/summary admin APIs)
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Task 01 — render qualifying PDF pages at index time: the persistent copies + `page_count`
|
||||||
|
|
||||||
|
**Phase:** `148_pdf_pages_in_sources` · **Source:** `TODO.md:5` — "For primarily pictographic PDFs it's not super helpful to see the summaries of the pages. I want to see the PDF pages in the sources. For example, the test_sources/ikea_instructions.tar are really only helpful if I can see the instruction pages…"
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
A qualifying PDF (fallback class or pictorial class) has every page rendered to a persistent PNG at index time — one-time per real file change (phase 147's fast path) — with `documents.page_count` recording the page count, stale copies cleaned on re-index/qualifier-loss/prune, and a fail-soft posture: a render failure never breaks the document's indexing.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/config.py` — beside `image_dir` (L397): `pdf_page_dir: str = "~/bor-sources/pages"` (`BOR_PDF_PAGE_DIR`) with the house docstring: where rendered PDF page PNGs are copied for serving (phase 148) — raw string, `Path.expanduser()` applied by the importer (the `sources_dir`/`upload_dir`/`image_dir` convention); deliberately separate from `sources_dir`/`upload_dir` (git checkouts re-cloned, uploads replaced, local dirs user-edited — the served copy must outlive the source file, the `image_dir` rationale).
|
||||||
|
2. `alembic/versions/0026_documents_page_count.py` — `revision = "0026"`, `down_revision = "0025"`: `op.add_column("documents", sa.Column("page_count", sa.Integer(), nullable=True))` (no index — a display fact, never a query surface); downgrade drops it. `app/models.py` — `Document.page_count: Mapped[int | None] = mapped_column(Integer, default=None)` + house docstring: the number of rendered page PNGs persisted in `pdf_page_dir` as `<doc-id>-p{N}.png` (phase 148) — the PDF's page count for a page-qualifying document (the phase-133 fallback class or the phase-140 pictorial class); NULL for every other document (text, images, text-heavy PDFs); set/cleared ONLY by the importer's PDF branch (+ prune cleanup deletes the copies).
|
||||||
|
3. `app/rag/importer.py` — `_index_pdf_file` (L1181), in the NEW/CHANGED path AFTER `session.flush()` (the doc has its id) and after the final content is decided (the fallback/pictorial passes have run — the eligibility signals are local: `fallback_fired` = the phase-133 gate fired (the `summary.pdfs_screenshotted += 1` site), `pictorial_described` = `_pictorial_pdf_pass` returned non-None):
|
||||||
|
- `eligible = fallback_fired or pictorial_described`;
|
||||||
|
- when eligible: `pages = render_pdf_pages(full_path)` (every page — `pages=None`, 150 dpi, the existing helper's contract: `b""` placeholder at a failed page's position, `[]` for an unopenable file); FIRST delete this doc's existing page copies (the stale-replacement convention — a changed PDF's old page set, e.g. a 30-page PDF that became 24, must not leak `p25..p30`); then write each non-empty PNG to `Path(llm.settings.pdf_page_dir).expanduser() / f"{doc.id}-p{N}.png"` (N 1-based, list-index aligned — the helper's "list index i is page i+1" default contract; the directory is `mkdir(parents=True, exist_ok=True)` on demand — the `image_dir` pattern); `doc.page_count = total_pages` where `total_pages` is the PDF's page count (the `fitz` doc length — re-derive via a tiny helper or `len(pages)` when the file opened: `render_pdf_pages` returns one slot per page, so `len(pages)` IS the page count for an openable file; `[]` → the unopenable case);
|
||||||
|
- when NOT eligible, or `pages == []` (unopenable), or ALL pages failed (zero non-empty PNGs): `doc.page_count = None` + delete any existing copies for this doc (a document that STOPPED qualifying loses its strip — e.g. a new version gained a real text layer);
|
||||||
|
- **fail-soft:** wrap the render/persist block — any exception → `page_count = None` + `logger.warning` (the house wording style) + the document proceeds to chunk/embed/summary EXACTLY as pre-phase (the render is a display concern — it never gates indexing); a per-page `b""` is NOT an exception (the gap is served as a 404 later, the viewer's note covers it).
|
||||||
|
- the UNCHANGED path (phase 147's fast path — `_unchanged_doc`) does NOT touch pages or `page_count` (the copies persist; zero render work — assert this).
|
||||||
|
4. `app/rag/importer.py` — a shared `_delete_page_copies(doc, page_dir) -> None` helper (the `_delete_image_copy` convention, L2626: missing files are a silent no-op, never an error): delete `<doc-id>-p1..p{page_count}.png` (iterate 1..`doc.page_count` — the row knows its own extent; a NULL/zero count is a no-op). Call sites: (a) the stale-replacement in step 3 (pass the doc BEFORE its `page_count` changes), (b) `_prune` (L2870) — beside the existing `_delete_image_copy(doc.image_path)` call (~L2924) for a pruned page-qualifying doc, (c) the embedded-image parent-PDF prune path (the pruned parent's copies too — the same site that deletes the parent's embedded-image copies). `app/rag/source_removal.py` is UNTOUCHED (row-only deletion — the image-copy convention there).
|
||||||
|
5. `tests/unit/` — the importer unit home:
|
||||||
|
- **eligibility × lifecycle matrix** (fake llm, tmp `pdf_page_dir`, the house PyMuPDF fixture recipes — the `test_pictorial_pdf.py` builder for the pictorial class, a textless/blank-page PDF for the fallback class, a dense-text PDF for the negative): new index of a qualifying PDF → copies `p1..p{N}` exist (N = page count), `page_count == N`, the PNG bytes are non-empty; re-run unchanged (phase 147 fast path) → ZERO render calls (count via monkeypatched `render_pdf_pages` or call counter), copies + `page_count` untouched; change the file (append a page to the fixture) → re-index → the OLD copy set replaced (a shrunk PDF leaves no stale `p{N}`), `page_count` updated;
|
||||||
|
- **qualifier loss:** a qualifying PDF's new version has a dense text layer (zero candidates, `pdf_pictorial` on) → `page_count` NULL + copies deleted;
|
||||||
|
- **unopenable:** `render_pdf_pages` returns `[]` (monkeypatched) → `page_count` NULL, no copies, no exception, the doc still indexed (chunks/summary ran);
|
||||||
|
- **per-page gap:** one page's render yields `b""` (monkeypatched) → the other copies written, `page_count` = the full count (the gap is a display-level 404, pinned in task 02);
|
||||||
|
- **render exception:** the writer raises → `page_count` NULL, warning logged (caplog), the doc indexed fully (fail-soft);
|
||||||
|
- **prune:** a qualifying doc pruned (its file removed from the source) → row gone + copies gone (no orphans in the tmp dir);
|
||||||
|
- **settings:** `pdf_page_dir` default `~/bor-sources/pages`, env override `BOR_PDF_PAGE_DIR` (the settings test home).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit: the matrix above; the phase-147 fast-path pins pass UNCHANGED (the fast path skips the render block by construction — it returns before the branch); the pre-phase PDF-branch pins (fallback content, pictorial blocks, `content_hash` over the final content, the embedded-image pass) pass UNCHANGED.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] qualifying PDFs (both classes) get `<doc-id>-p{N}.png` for every renderable page + `page_count` = the page count; non-qualifying PDFs, text docs, and images get neither
|
||||||
|
- [ ] unchanged re-syncs render nothing; changed re-syncs replace the copy set without orphans; qualifier-loss and prune delete the copies
|
||||||
|
- [ ] a render failure is fail-soft: the document indexes exactly as pre-phase, `page_count` NULL, a warning is the signal
|
||||||
|
- [ ] `settings.pdf_page_dir` follows the `image_dir` convention (raw string, expanduser'd at use); migration 0026 round-trips
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Task 02 — serve the pages: the public route + `DocContent.page_urls`
|
||||||
|
|
||||||
|
**Phase:** `148_pdf_pages_in_sources` · **Source:** `TODO.md:5` — "I want to see the PDF pages in the sources. For example, the test_sources/ikea_instructions.tar are really only helpful if I can see the instruction pages, a description won't really help me."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
The viewer payload names every rendered page (`page_urls`, full routes, additive-omitted), and a public bytes route serves one page PNG at a time — the image route's trust model and 404 posture verbatim.
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `app/api/docs.py` — new route beside `get_document_image` (L216): `@router.get("/documents/{doc_id}/pages/{n}", response_class=FileResponse)` → `def get_document_page(doc_id: str, n: int, db = Depends(get_db)) -> FileResponse` (the `{n}` int path parameter is parsed by FastAPI — a non-int 422s at the router, mirroring how the image route's unparseable `doc_id` maps to its 404 below):
|
||||||
|
- the docstring: PUBLIC (the phase-124 A4 trust model verbatim — a shared chat can cite a page figure, so the bytes serve ANONYMOUSLY; the document id is an unguessable server-minted `uuid4` — IT IS the credential, no enumeration value — exactly like the image route and the saved-chat id; the document's TEXT stays user-gated: only the page bytes are public);
|
||||||
|
- 404 `detail="document not found"` (the router's unknown-document shape) for EVERY non-servable case: unparseable `doc_id` (the `uuid.UUID` try/except → 404, not 422 — the image route's mapping), an unknown doc, `page_count` NULL (a non-qualifying doc — the route knows nothing of its pages), `n < 1` or `n > doc.page_count` (out of range — the int parameter makes `n < 0`/fractional impossible; a gap — a page whose render failed — hits the missing-file 404 below), or the file on disk missing (defensive — the copy was lost; the viewer's onerror note covers it);
|
||||||
|
- the path is built ONLY from the row's id + `n` (`Path(settings.pdf_page_dir).expanduser() / f"{doc.id}-p{n}.png"` — `settings` via the house import) — no request value reaches a filesystem path (no traversal surface, the image route's property);
|
||||||
|
- `FileResponse(page_file, media_type="image/png", headers={"Cache-Control": "private, max-age=3600"})` (the PNG is always PNG — `render_pdf_pages`'s `tobytes("png")`; the image route's header, the content-hashed-bytes rationale).
|
||||||
|
2. `app/schemas.py` — `DocContent`: add `page_urls: list[str] | None = None` + docstring (phase 148 — the rendered-page bytes routes `["/api/documents/<id>/pages/<i>" for i in 1..page_count]` for a page-qualifying PDF; ABSENT from the wire for every other document — `None` → dropped by the serializer, never `null`, the `image_url` omission precedent); extend `_serialize` to pop `page_urls` when None (beside the existing `image_url` pop).
|
||||||
|
3. `app/api/docs.py` — `get_document_content` (L165, the `GET /documents/content` endpoint): when `doc.page_count` is non-NULL, fill `page_urls = [f"/api/documents/{doc.id}/pages/{i}" for i in range(1, doc.page_count + 1)]` (the `/api` prefix — the `image_url` field carries the same full-route shape; check `image_url`'s exact construction and mirror it byte-for-byte in convention).
|
||||||
|
4. `tests/unit/` + the docs-endpoint integration home:
|
||||||
|
- **route matrix** (the TestClient idiom the image-route tests use): a seeded qualifying doc (row with `page_count=2` + real PNG files in a tmp `pdf_page_dir`) → `GET .../pages/1` and `/2` → 200, `content-type: image/png`, the `Cache-Control` header, the body bytes == the stored file's bytes; `n=0`, `n=3` → 404 `document not found`; a text doc row / an image doc row / a PDF row with `page_count=NULL` → 404 on any `n`; a qualifying row whose file was deleted on disk → 404; a non-uuid `doc_id` (`"abc"`) → 404 (not 422);
|
||||||
|
- **payload:** the content endpoint for a qualifying doc → `page_urls` == the exact route list (1-based, count == `page_count`); a text doc / an image doc / a non-qualifying PDF → the `page_urls` KEY is ABSENT from the JSON (assert `"page_urls" not in data` — the omission pin, the `image_url` pattern);
|
||||||
|
- **no traversal:** the route is structurally impossible to point at an arbitrary path (the int parameter + row-derived path — assert the code builds the path from `doc.id` + `n` only, pinned by the out-of-range 404s).
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- Unit + integration: the matrices above; every pre-existing `DocContent` pin passes UNCHANGED (a non-qualifying doc's payload is byte-identical — the key is absent, not null); the image route's tests are untouched.
|
||||||
|
- Coverage: **>90%** on this task's new/modified code (`app/`).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] `GET /api/documents/{id}/pages/{n}` serves the stored PNG (public, uuid4-credential, `image/png`, the image route's cache header) and 404s EVERY non-servable case with `document not found`
|
||||||
|
- [ ] `DocContent.page_urls` is the exact 1-based route list for qualifying docs and the key is ABSENT (never `null`) for every other document
|
||||||
|
- [ ] `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing` — `app/` coverage >90%; `uv run ruff check . && uv run pyright` clean
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Task 03 — the viewer shows the pages: the strip replaces the text and the summary panel
|
||||||
|
|
||||||
|
**Phase:** `148_pdf_pages_in_sources` · **Source:** `TODO.md:5` — "For primarily pictographic PDFs it's not super helpful to see the summaries of the pages. I want to see the PDF pages in the sources. … I still want to be able to ask questions, so the summary and embedding is helpful, but not when shown to the user."
|
||||||
|
**Story:** n/a
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
For a document whose payload carries `page_urls`, the shared `renderDocument` core renders the page strip — every page as a lazy image with a "Page N" caption — and suppresses the text content AND the Summary panel (the descriptions stay in the DB for Q&A, just not displayed). Every other document renders byte-identically to pre-phase, on both surfaces (the doc modal and `/document.html`).
|
||||||
|
|
||||||
|
## Work
|
||||||
|
1. `frontend/assets/document.js` — `renderDocument` (L172 — the ONE shared core; the modal and the full page both call it, no per-surface copy):
|
||||||
|
- the gate: `const pageUrls = Array.isArray(doc.page_urls) ? doc.page_urls : null;` — a non-empty array triggers the strip; `null`/absent/empty → the EXACT pre-phase rendering (assertable byte-identity for every other doc);
|
||||||
|
- the strip: a `<div class="doc-pages">` container (replacing what would become the content slot) holding one `<figure class="doc-page">` per URL — `<img loading="lazy" src={url}>` with `alt = `Page ${i} of ${doc.title}`` (the WCAG alt contract — the phase-122 image idiom, the title as the fallback context) and a `<figcaption class="doc-page-num">Page ${i}</figcaption>` (i 1-based over `page_urls`);
|
||||||
|
- **suppression:** when the strip renders, the markdown/`.doc-raw` content block is NOT built AND the labeled Summary panel (`.doc-summary`, phase 36 — including its admin edit affordance wiring, which is moot without the panel) is NOT built — the owner's contract: the page descriptions are "not … shown to the user"; the meta badge row (Created/Indexed, the phase-106 badges) renders exactly as today;
|
||||||
|
- **unavailable page:** each `<img>` gets an `onerror` handler (the phase-122 "Image unavailable" idiom) that swaps ITS figure's `<img>` for a small "Page N unavailable" note element (`role="status"`, muted styling) — the rest of the strip is untouched (one lost copy never hides the other pages; the defensive 404s of task 02's route are the trigger);
|
||||||
|
- **XSS contract:** `createElement`/`textContent` only — every document-derived string (title, URLs, the note) lands via properties/`textContent`, never innerHTML (the file's pinned contract — the module docstring's "XSS-safe by construction" line gains the phase-148 note).
|
||||||
|
2. `frontend/assets/styles.css` — the strip, in the existing doc content column (the core renders into the same `#doc-content` slot the `.doc-raw`/markdown path uses — no new column):
|
||||||
|
- `.doc-pages { display: grid; gap: <house spacing>; }` (vertical stack — one page per row, the natural reading order for instruction manuals);
|
||||||
|
- `.doc-page { margin: 0; } .doc-page img { display: block; width: 100%; max-width: 100%; height: auto; border: 1px solid <theme border var>; border-radius: <house radius>; background: <theme surface var>; }` (a page PNG on a dark theme must sit on a non-clashing surface — the image route's figures already have a dark/light precedent to mirror);
|
||||||
|
- `.doc-page-num { font: <house small meta style>; color: <muted ink var>; text-align: center; padding: <small>; }` (contrast ≥4.5:1 in BOTH themes — the WCAG gate);
|
||||||
|
- the "Page N unavailable" note reuses the phase-122 image-unavailable note styling (find the existing class — the same muted note, no new pattern).
|
||||||
|
3. Module docstring: the phase-148 paragraph (the gate, the suppression, the strip, the onerror note, both surfaces) in the house style of the file's leading changelog.
|
||||||
|
|
||||||
|
## Testing & Quality
|
||||||
|
- The house tests `document.js` through E2E + the frontend emoji guard (no JS unit harness) — the rendering pins live in task 04's E2E; this task's gate is that the pre-phase suites (the doc-modal, document-page, image-document, summary-panel E2Es) pass UNCHANGED (a non-qualifying doc is byte-identical — the load-bearing property).
|
||||||
|
- Coverage: n/a (frontend task — `app/` coverage stays >90% from tasks 01–02).
|
||||||
|
|
||||||
|
## Completion Criteria
|
||||||
|
- [ ] a payload with `page_urls` renders the strip (one figure per URL, lazy imgs, "Page N" captions, alt text) with NO text content block and NO Summary panel; the meta badges are untouched
|
||||||
|
- [ ] a payload without `page_urls` (text docs, images, text-heavy PDFs, pre-phase saved content) renders byte-identically to pre-phase on BOTH surfaces
|
||||||
|
- [ ] one failed page image swaps only its own figure for the "Page N unavailable" note
|
||||||
|
- [ ] no innerHTML from document data; the emoji guard stays green
|
||||||
|
- [ ] `uv run pytest` green (all pre-existing E2Es); `uv run ruff check . && uv run pyright` clean
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user