6e578579b3
- mark task #21 (commit-race + collapsible panels fix) as done — followup to v0.8.1 release commit 95c48c7
- add SECURITY_AUDIT_2026-04-25.md from the deep audit of v0.8.0 (1 critical, 4 high, 5 medium, 4 low findings — kept for reference; remediation tracked separately)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
281 lines
43 KiB
JSON
281 lines
43 KiB
JSON
{
|
||
"master": {
|
||
"tasks": [
|
||
{
|
||
"id": "1",
|
||
"title": "feat: search-mode split-view with PDF + page jump",
|
||
"description": "Render /kb/search results as a two-column split view: left column is the stack of ranked hit cards (kind, title, section, page label), right column is an iframe viewing the selected hit's PDF scrolled to page_number. Clicking any hit swaps the iframe. Text-only sources (law from Wikisource) fall back to a chunk/text panel with a Wikisource link so the right column never 404s.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "Before this change renderSearchResults produced plain vertical text cards — users got the chunk body and had to open the Wikisource link (or track down the PDF manually) to verify context. With 5 of 5 PDFs now carrying accurate page_number (shira-hermes e534709 + 1ca1cc0), the search UI can finally deep-link to the right page. Mirrors the ask-mode split view (v0.1.7 uncommitted).",
|
||
"testStrategy": "Search 'תקנה 37' → first hit should be a regulation/circular → right pane loads the PDF at page ~N where the section appears. Click a lower-ranked law hit → right pane swaps to a Wikisource link view. Search 'הגדרות' → hits span multiple sources → each click swaps iframe source.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-24T15:47:00Z"
|
||
},
|
||
{
|
||
"id": "2",
|
||
"title": "fix(kb/chunker): page_number propagation through split + packing (shira-hermes)",
|
||
"description": "Applied in shira-hermes commits e534709 + 1ca1cc0: (1) _split_oversized now re-derives page_number per piece from markers embedded in parent content + a virtual (offset 0, parent.page_number) anchor, (2) chunk_circular tracks absolute paragraph offsets in the original text so each packed sub-chunk reports its real starting page, (3) _as_dicts strips stray \\x00 bytes left behind when _split_oversized slices through a marker sentinel. Reference data: ספר הליקויים now 211 chunks × 210 pages (1-413) vs 209 × 1 before. Not work for this repo, but the search split-view in task #1 depends on it.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "Lives in espocrm-extensions/shira-hermes. Logged here for traceability because task #1 can't demonstrate correct page jumps without it.",
|
||
"testStrategy": "Query DB: SELECT source_id, MIN/MAX(page_number), COUNT(DISTINCT page_number) FROM kb_chunk GROUP BY source_id — every PDF source should span multiple distinct pages.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-24T15:47:00Z"
|
||
},
|
||
{
|
||
"id": "3",
|
||
"title": "feat(kb/search): LLM query expansion so ranked-by-title docs don't crowd everything else out (shira-hermes)",
|
||
"description": "User reports searching 'מהי תקנה 37' returns only the תקנה 37 circular and the law — never ספר הליקויים, even though that's where the underlying medical content lives. Root cause is a single-shot retrieval where any document whose title contains the query terms wins by a huge margin. Fix: ask the LLM (via ai-gateway) for up to 3 alternative phrasings, retrieve candidates for the original + each variant in parallel, merge by chunk_id keeping best RRF score, then rerank the union against the ORIGINAL query. After fix: src 29 (ספר הליקויים) shows up with 2 hits in the same query.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "Lives in espocrm-extensions/shira-hermes commit 1441a41. /kb/search now has expand=true by default, agent path (search_insurance_kb tool) keeps expand=false because the agent already does multi-query via tool calls.",
|
||
"testStrategy": "POST /kb/search {query:'מהי תקנה 37', top_k:8} should return hits from at least 2 distinct source_ids, including src 29 (ספר הליקויים) and src 26 (תקנה 37 חוזר).",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T10:00:00Z"
|
||
},
|
||
{
|
||
"id": "8",
|
||
"title": "feat(kb/ask): SSE streaming with live agent progress",
|
||
"description": "User wanted Shira's progress to be visible while she thinks — like Claude does — instead of just an incrementing seconds counter. Implementation: AgentRunner.run accepts an optional sync on_event callback that emits {type, label, ...} dicts at each agent step. New POST /kb/ask/stream returns text/event-stream, with the runner running in an asyncio task whose events feed an asyncio.Queue that the response generator drains as SSE. Client opens EventSource against a new EspoCRM EntryPoint KnowledgeBaseAskStream that proxies the SSE bytes through cURL with output buffering disabled (echo + flush + exit, bypassing the framework Response). The progress UI now stacks one line per event (thinking, tool_start with the query Shira chose, tool_done with the chunk count, writing) instead of just a seconds counter. v0.1.9 _activeAsk persistence pattern preserved — events accumulate at module scope so a view switch + return replays the live log.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "shira-hermes 76fd77f. EspoCRM EntryPoint registered in metadata/app/entryPoints.json. Hebrew labels live in agent_runner._tool_label / _tool_done_label so the wire format already carries display-ready strings (no client-side mapping). 15s heartbeats keep the connection open through proxy idle-timeouts.",
|
||
"testStrategy": "curl -N POST /kb/ask/stream {message:'מהי תקנה 36'} should produce data: lines with thinking → tool_start (with query) → tool_done (with chunk count) → ... → writing → answer. Browser EventSource should drive the same flow into the UI.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T13:00:00Z"
|
||
},
|
||
{
|
||
"id": "7",
|
||
"title": "fix: search preview duplicates left card for text sources",
|
||
"description": "User report: searching the law (Wikisource source 5) shows the same chunk content in both the left list-card and the right preview pane. The preview adds zero value when the matched source has no PDF — both panes are visually identical (modulo the left's 14em truncation), which reads as a bug. Fixed by fetching the matched chunk plus K=2 surrounding sections from /kb/source/{id}/chunks?around=N&ctx=2 and rendering them stacked: matched section is highlighted with a yellow header (#fff3cd), neighbors render as muted context blocks above and below. Adds a prominent 'פתח ב-Wikisource' button in the panel header, scrolls the matched section into view on render. Race-safe via _previewToken so a quick second click doesn't render stale results.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "shira-hermes b127caf added chunk_index to /kb/search hits + an `around`/`ctx` query param to /source/{id}/chunks. Espo controller passes them through. Client uses the new fields in showSearchPreview when the hit is a text source.",
|
||
"testStrategy": "Search 'מהי תקנה 36'; click the law-kind hit. Right pane: yellow-highlighted ס' 36 in the middle, ס' 35 above (muted), ס' 37 below (muted), Wikisource button in header. Click the תקנה 37 חוזר hit: right pane swaps to PDF iframe at the cited page (PDF path unchanged).",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T12:30:00Z"
|
||
},
|
||
{
|
||
"id": "5",
|
||
"title": "feat(kb): drag-to-resize splitter (both ask + search)",
|
||
"description": "Replace the fixed Bootstrap col-md-5/7 split with a flex layout containing a 6px drag handle. mousedown on the handle starts the drag; while dragging an invisible full-screen overlay covers any iframe so the PDF.js viewer doesn't swallow mouse events. The chosen ratio (15-85%) persists to localStorage as kb-split-pct so the layout sticks across sessions. Both modes share the same _buildSplitShell helper so the look stays consistent.",
|
||
"status": "done",
|
||
"priority": "normal",
|
||
"details": "Default ratio = 42% left (matches the previous col-md-5 ≈ 41.66%). Applied to renderSearchResults, renderAskAnswer, and showSearchPreview (which now uses 100%-height containers via flex column).",
|
||
"testStrategy": "Open ask mode, drag the divider; verify PDF iframe doesn't lose mouse focus mid-drag; reload — divider stays at last position. Repeat in search mode.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T11:00:00Z"
|
||
},
|
||
{
|
||
"id": "6",
|
||
"title": "fix: search survives view switch (parity with ask in v0.1.9)",
|
||
"description": "Search mode had the same view-bound promise problem as ask did before v0.1.9: navigating to another EspoCRM screen and back blanked the results. Hoisted {query, kind, promise} to a module-level _activeSearch with the same {query, kind, hits, selectedIdx} sessionStorage replay we already built for ask. Selected hit index also persists so the right pane comes back to the same source/page the user had open.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "Mirrors the v0.1.9 ask fix in _attachSearchHandlers + afterRender. Click handler updates _lastSearch.selectedIdx so a return-trip lands on the user's last-clicked hit, not always the top-ranked one.",
|
||
"testStrategy": "Search 'מהי תקנה 37'; click a result other than the first; navigate to Contacts; navigate back — same hit selected, same PDF page on the right.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T11:00:00Z"
|
||
},
|
||
{
|
||
"id": "4",
|
||
"title": "fix: ask survives view switch via module-level promise + sessionStorage",
|
||
"description": "User reports asking Shira a question and switching to a different EspoCRM view loses the in-flight request — coming back shows a blank screen as if nothing was asked. Cause: the Espo.Ajax promise was view-bound, so handlers fired against a detached DOM after re-mount. Fix: hoist {question, promise, startedAt} to a module-level _activeAsk; afterRender re-attaches handlers and resumes the progress UI with the original startedAt; completed answers persist to sessionStorage and replay on remount or a hard reload.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "All client-side, files/client/custom/modules/knowledge-base/src/views/kb/index.js. State is intentionally session-scoped — kept in sessionStorage so the next browser session starts clean.",
|
||
"testStrategy": "Ask a question; while the spinner shows, click Contacts (or any other navbar item); wait until the request would have finished; click back to בסיס ידע — the answer (or active spinner with correct elapsed-time) should be there.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T10:00:00Z"
|
||
},
|
||
{
|
||
"id": "9",
|
||
"title": "feat(kb/ask): rejoin in-flight SSE stream after browser reload",
|
||
"description": "When the user F5s or closes+reopens the tab while Shira is thinking, the asyncio task in shira-hermes keeps running (tokens burn) but the EventSource is gone — there's no way to reattach. After reload, the v0.1.9 sessionStorage replay only shows the LAST completed answer, not the live in-flight stream. Build a rejoinable SSE channel: POST /kb/ask/stream allocates a request_id and starts the runner; the SSE response writes events into an in-memory store keyed by request_id AND streams them. New GET /kb/ask/stream/{request_id} reconnects: replays accumulated events first, then continues with new ones as they arrive. Garbage-collect after 5 minutes past the answer event.",
|
||
"status": "pending",
|
||
"priority": "normal",
|
||
"details": "Architecture: in-process LRU dict {request_id -> {events:list, queue:asyncio.Queue, done:bool, last_used:ts}}. POST returns Set-Cookie or response header X-Request-Id; client stores it in _activeAsk.requestId + sessionStorage. afterRender: if _activeAsk has requestId and no live es, open EventSource to /kb/ask/stream/{requestId}. Server: re-emit all stored events on reconnect, then drain queue. Two-process safety: this works only because shira-hermes runs as a single FastAPI process — if we ever scale horizontally we'll need Redis pub/sub or sticky sessions. Note that for now it is single-process.",
|
||
"testStrategy": "1) Ask Shira a long question. 2) F5 after 10s. 3) After reload, KB tab should resume showing live events including those that arrived during the reload window. 4) Answer event arrives — refresh again still shows it (sessionStorage path, unchanged from v0.1.9). 5) After 5 minutes, GET /kb/ask/stream/{old_request_id} returns 410 Gone.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T13:30:00Z"
|
||
},
|
||
{
|
||
"id": "10",
|
||
"title": "ops: investigate n8n release-asset auto-attach failures",
|
||
"description": "The n8n workflow `Git: Gitea Push - Auto-Release + Mattermost` (id IcF30v1Pw3wbucbu, per ~/CLAUDE.md) is supposed to attach the built .zip as a release asset within ~12s of a tag push. Across every KnowledgeBase release in this period (v0.1.8 through v0.2.1) the workflow did NOT attach the zip — every release was published with zero assets and I had to upload manually via curl + the Gitea API. Investigate the workflow's recent execution history, find the failing step, and either fix the n8n workflow or document a better fallback.",
|
||
"status": "pending",
|
||
"priority": "low",
|
||
"details": "Test pattern: after `mcp__gitea-dev__create_release`, poll GET /api/v1/repos/.../releases/{id}/assets every 10s for ~60s. Currently always returns 0. The 'Check Existing Release → Release Exists?' branch works (skips creating a duplicate release). The asset-upload branch is what's silently failing. Possible causes: (a) the n8n workflow doesn't have the zip artifact (zip is built ad-hoc with `bash build.sh` from the workspace, not in CI), (b) bad credential to Gitea API, (c) the release-creation event doesn't trigger that node. Note this workflow is for OTHER extensions too — if it's broken for all of them, fixing helps the whole release pipeline.",
|
||
"testStrategy": "After fix: push v0.X.Y tag to KnowledgeBase via mcp__gitea-dev__create_release; verify the zip appears at GET /releases/{id}/assets within 30s without manual upload.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T13:30:00Z"
|
||
},
|
||
{
|
||
"id": "11",
|
||
"title": "feat(kb/ask): show text-source citations in the ask mode source picker",
|
||
"description": "/kb/ask currently filters sources_used through _filter_pdf_sources (kb_public.py) before returning, dropping any source whose original_path doesn't end with .pdf. The Wikisource law (source 5) is therefore invisible to the user even when Shira explicitly cites a section from it. With the v0.1.11 'section in context' preview that already exists for search mode, ask mode should be able to show the same. Drop the filter, and when the user clicks a non-PDF source pill, route to the same _renderSectionContext flow that search uses (factor it into a shared helper).",
|
||
"status": "pending",
|
||
"priority": "normal",
|
||
"details": "Server (shira-hermes): drop _filter_pdf_sources in both /kb/ask and /kb/ask/stream answer-event payload. Either return all sources, or re-introduce a different filter that keeps text sources but strips ones with no source_id. Client: in renderAskAnswer the source-pill click handler currently always rebuilds the iframe; route through showSearchPreview when the source is text-only. Probably easiest to extract _renderSectionContext / _renderSectionContextPlaceholder into a shared helper that both modes call. Need to add chunk_index to the sources returned from /kb/ask too — currently only on /kb/search hits.",
|
||
"testStrategy": "Ask 'מהי תקנה 36' — Shira's answer cites both תקנה 37 (PDF) and ס׳ 36 of the law (text). Source picker shows both. Click PDF pill → iframe at the cited page. Click law pill → section in context (matched section + 2 neighbors + Wikisource button) — same look as search mode.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T13:30:00Z"
|
||
},
|
||
{
|
||
"id": "12",
|
||
"title": "Phase 1 — Multi-topic KB foundation (DB schema, topic-aware endpoints, topic selector)",
|
||
"description": "Generalize the KB from being insurance-only to supporting multiple legal domains within one CRM (e.g. ביטוח לאומי, דיני עבודה, דין פלילי). A 'topic' is the firm-level grouping; each kb_source belongs to exactly one topic. Search/ask are scoped to a single topic at a time, chosen from a topic dropdown the user controls. The system_prompt for /kb/ask becomes per-topic so Shira's domain context is correct (today the prompt hardcodes 'Israeli National Insurance'). Backwards-compatible migration: all 6 existing sources move to topic_id=1 named 'ביטוח לאומי' with the existing system-prompt addendum, and the UI defaults to that topic so nothing visible changes for existing users until they choose another topic.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "DB migration (shira-hermes side, against insurance_kb DB):\n- New table kb_topic: id PK, slug TEXT UNIQUE, name TEXT NOT NULL, description TEXT, system_prompt_addendum TEXT, is_active BOOLEAN DEFAULT true, created_at TIMESTAMPTZ DEFAULT now(), updated_at TIMESTAMPTZ DEFAULT now().\n- Seed: INSERT (id=1, slug='national-insurance', name='ביטוח לאומי', system_prompt_addendum=<copy from current /kb/ask hardcoded text>, is_active=true). RENAME the DB itself? Probably leave as 'insurance_kb' — costly to rename, no real value. Document in memory.\n- ALTER TABLE kb_source ADD COLUMN topic_id INTEGER REFERENCES kb_topic(id). Backfill: UPDATE kb_source SET topic_id = 1. Then ALTER COLUMN SET NOT NULL.\n\nshira-hermes endpoints:\n- New GET /kb/topics — public, returns active topics with id, slug, name, description (no prompt).\n- /kb/search: accepts optional topic_id (single int). When present, the SQL adds AND s.topic_id = $N. When absent (back-compat), still returns all (might want to deprecate this and require topic_id later).\n- /kb/sources, /kb/source/{id}/chunks, /kb/source/{id}/pdf: same — optional topic filter on listings, no change to single-source endpoints.\n- /kb/ask + /kb/ask/stream: accept topic_id param; load topic.system_prompt_addendum and inject into system_prompt instead of the hardcoded insurance text in _build_ask_runner_context. Pin the legal_kb tool to topic_id too (so search_insurance_kb queries are constrained — RENAME the tool to search_legal_kb and pass topic_id at registration time).\n- _expand_query in kb_search.py: parametrize the prompt by topic name (currently hardcoded 'הביטוח הלאומי בישראל'). Pass topic.name in.\n\nKnowledgeBase extension (EspoCRM):\n- New route+action GET /KnowledgeBase/action/topics → proxies /kb/topics.\n- Service.search/ask gain topic_id, controller passes through.\n- Template gets a topic <select> at the top (above the tabs); fetches /KnowledgeBase/action/topics on mount, persists selection to localStorage 'kb-topic'. Default: topic id=1 if it exists, else first active topic.\n- this.kind etc. already pass through; add this.topicId. Pass topic_id with every search/ask call.\n\nConsequences for sessionStorage replay (v0.1.9, v0.1.10): the cached _lastAsk / _lastSearch should record topic_id; on remount only replay if the current topic matches. Else show empty state.",
|
||
"testStrategy": "1) After migration: SELECT count(*) FROM kb_source WHERE topic_id IS NULL → 0; SELECT name FROM kb_topic → 'ביטוח לאומי'. 2) GET /kb/topics returns the seeded topic. 3) Search/ask with topic_id=1 returns the same 6 sources as before. 4) Add a second topic (manually for the test) and a single test source under it; verify topic_id=1 search no longer surfaces the test source and vice versa. 5) /kb/ask system prompt confirmed via logs to include the topic-specific addendum, not the hardcoded text.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T13:30:00Z",
|
||
"updatedAt": "2026-04-25T14:34:08.086Z"
|
||
},
|
||
{
|
||
"id": "13",
|
||
"title": "Phase 2 — Document upload from the KB UI (file picker + async ingestion + job tracking)",
|
||
"description": "Today documents enter the KB by manually putting them in the MinIO inbox/ folder and waiting for the n8n cron to call /admin/kb/scan-inbox. End users have no path to upload via the UI. Add a file-upload form in the management panel: user picks a PDF/DOCX/TXT, picks a kind (law/regulation/circular), confirms the topic, optionally fills metadata (title, identifier, dates, source_url), and clicks upload. The file lands in MinIO under inbox/<topic_slug>/<kind>/, a kb_ingest_job row is created, and a background asyncio task processes it (parse → chunk → embed → upsert kb_source). The UI polls the job status and shows progress live; on done it links to the new source in the management table.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "DB:\n- New table kb_ingest_job: id PK, source_id INTEGER NULL FK kb_source(id) ON DELETE SET NULL, original_filename TEXT, s3_key TEXT, kind TEXT, topic_id INTEGER NOT NULL, metadata_json JSONB, status TEXT NOT NULL CHECK (status IN ('queued','processing','done','failed')), error_message TEXT, chunks_created INTEGER, created_at TIMESTAMPTZ DEFAULT now(), started_at TIMESTAMPTZ, completed_at TIMESTAMPTZ, requested_by_user TEXT.\n- Index: (status, created_at DESC) for the queued list.\n\nshira-hermes endpoints:\n- POST /admin/kb/upload (multipart): receives file, kind, topic_id, optional title/identifier/published_at/effective_at/source_url. Validates topic exists. Writes file to s3 inbox/<topic_slug>/<kind>/<uuid-prefixed filename>. Inserts kb_ingest_job with status=queued. Schedules asyncio.create_task(_process_ingest_job(job_id)) so processing starts immediately, not on the next n8n cron tick. Returns {job_id, status:'queued'}.\n- GET /admin/kb/jobs?topic_id=&status=&limit=: list jobs, newest first.\n- GET /admin/kb/jobs/{id}: single job detail.\n- _process_ingest_job(job_id): UPDATE status='processing', started_at=now. Calls existing kb_ingest.ingest_source. On success: UPDATE status='done', source_id=<new>, chunks_created=<n>, completed_at=now. On failure: UPDATE status='failed', error_message=<exception text>. The upload doesn't block the HTTP request — the user gets the job_id immediately and polls.\n- Reuses scan-inbox advisory lock pattern so a manually-uploaded file plus an n8n cron run don't double-process.\n\nKnowledgeBase extension:\n- EspoCRM PHP proxy for multipart upload — Controllers can read $request->getParsedBody() but multipart needs special handling. Look at how other extensions do it (LegalAssistance/DigitalSignature might have examples).\n- New tab 'ניהול' (visible only to non-portal users; can also gate to admin role later). The tab opens a panel with: (a) Upload form, (b) Sources table for current topic [implemented in Phase 3], (c) Recent jobs.\n- Upload form fields: file picker, kind dropdown, topic dropdown (defaulting to currently-selected topic), optional title/identifier/dates/source_url collapse. Submit → POST KnowledgeBase/action/upload → returns job_id → switch to job-status view that polls every 2s.\n- Job status view: shows the job's status badge (queued/processing/done/failed), elapsed time, and on done: link to the source in the management table (Phase 3).\n\nFile size: enforce 50MB limit at the FastAPI route + server-side. PDFs of עשרות-שעות could approach this.",
|
||
"testStrategy": "1) Upload a small test PDF (~1MB). Job goes queued → processing → done in <30s. UI shows progress live. 2) Upload a corrupt file. Job ends in failed with a useful error_message. 3) Upload while another large ingest is running — job shows 'processing' but doesn't deadlock. 4) Refresh the page mid-upload — job status restored from sessionStorage + a fresh poll. 5) /admin/kb/jobs returns the upload's row.",
|
||
"subtasks": [],
|
||
"dependencies": [
|
||
"12"
|
||
],
|
||
"createdAt": "2026-04-25T13:30:00Z",
|
||
"updatedAt": "2026-04-25T16:47:46.599Z"
|
||
},
|
||
{
|
||
"id": "14",
|
||
"title": "Phase 3 — Management panel UI (sources table, edit metadata, delete, re-ingest)",
|
||
"description": "Today the only way to manage existing sources is via SQL on the shared PG (DELETE FROM kb_source WHERE id=…) plus an mc command on MinIO. End users need a panel where they can: see all sources for the selected topic, with chunk counts and ingestion dates; edit source metadata (title, identifier, dates, source_url); delete a source (with confirm and clear cascade messaging); re-ingest a source (re-fetch its file from MinIO processed/, drop chunks, re-run parse+chunk+embed); see the most recent ingest jobs (success + failure both). The panel sits in the same KB extension under a new tab 'ניהול'.",
|
||
"status": "done",
|
||
"priority": "high",
|
||
"details": "shira-hermes endpoints:\n- GET /admin/kb/sources?topic_id=&kind=&limit=: list with id, kind, title, identifier, chunk_count, ingestion_date, last_ingest_status (joining kb_ingest_job).\n- PUT /admin/kb/sources/{id}: update editable fields (title, identifier, source_url, published_at, effective_at).\n- DELETE /admin/kb/sources/{id}: hard delete (cascades chunks via FK, drops processed/ files in S3 too).\n- POST /admin/kb/sources/{id}/reingest: requires source_id; finds the original file at original_path s3:// URI; creates a new kb_ingest_job row with status=queued and the existing source_id; background task replaces chunks+embeddings (does NOT change source_id, so all v0.1.11 chunk_index references remain valid IF the chunker output is stable; otherwise old _lastSearch sessionStorage will point at chunk_indexes that no longer exist — flag for testing). Should optionally just delete + re-create the source — simpler.\n\nEspoCRM client:\n- 'ניהול' tab. Top: header showing topic name + a count badge ('X מסמכים בנושא'). Below: 3 collapsed sections — uploaded jobs (collapsed if all done), sources table, recent failures.\n- Sources table: id, kind label, title, identifier, chunk_count, ingestion_date. Rightmost column: action buttons (✏ edit, 🗑 delete, ↻ re-ingest, 👁 view in browse mode).\n- Edit: opens a modal with the editable fields. PUT on save.\n- Delete: confirm modal that shows chunk_count + 'this will also remove the PDF from the search results'. Two-step confirmation if source has >100 chunks.\n- Re-ingest: confirms; submits POST /reingest; surfaces in the jobs section.\n- Use jQuery + Espo.Ui.dialog patterns consistent with the rest of the extension.\n\nACL gate: this tab visible only to users with role 'KB Admin' (define in EspoCRM if not present) or fall back to !isPortal for now.",
|
||
"testStrategy": "1) Open 'ניהול' tab. See the 6 existing sources for ביטוח לאומי. 2) Edit one source's title — refresh → new title sticks. 3) Re-ingest ספר הליקויים. Job appears in the jobs section processing → done. Source still searchable end-to-end after. 4) Delete one source. Confirm modal appears with chunk count. After delete: source gone from /kb/sources, /kb/search no longer surfaces it. 5) Failed re-ingest (e.g. delete the file in MinIO first) — surfaces in failures section with error_message.",
|
||
"subtasks": [],
|
||
"dependencies": [
|
||
"13"
|
||
],
|
||
"createdAt": "2026-04-25T13:30:00Z",
|
||
"updatedAt": "2026-04-25T17:28:47.359Z"
|
||
},
|
||
{
|
||
"id": "15",
|
||
"title": "Phase 4 — Topic CRUD UI (admins can add/edit/disable topics from the panel)",
|
||
"description": "Once Phase 1 ships there will be a single seeded topic ('ביטוח לאומי'). For Klear and other firms to actually use the multi-topic capability they need a UI to create new topics — דיני עבודה, דין פלילי, נדל\"ן — without anyone running SQL. Add a topics-management section in the 'ניהול' tab: list active+inactive topics, add new (slug + name + system_prompt_addendum), edit (rename, change prompt addendum), soft-delete (sets is_active=false). Soft-delete keeps the data but hides the topic from the user-facing dropdown.",
|
||
"status": "done",
|
||
"priority": "normal",
|
||
"details": "shira-hermes endpoints:\n- GET /admin/kb/topics: list including inactive ones (with source counts).\n- POST /admin/kb/topics: create. Validates slug (lowercase, hyphens only, unique). Returns created row.\n- PUT /admin/kb/topics/{id}: update name, description, system_prompt_addendum, is_active.\n- DELETE /admin/kb/topics/{id}: 409 Conflict if topic has sources; otherwise hard-delete. Soft-delete (is_active=false) is the normal path.\n\nEspoCRM client:\n- New section in 'ניהול' tab: 'נושאים' table — slug, name, source count, is_active toggle, edit button.\n- Add new: modal with slug, name, description, prompt-addendum textarea (pre-populated with a generic template like 'You are answering legal questions about <topic>. Cite sections explicitly when possible. Never answer from generic legal training if the KB has a matching section').\n- Edit: same modal pre-filled. Saving updates the topic; if name changed, the topic dropdown refreshes.\n- The 'ניהול' tab itself only shows the topics section if user is admin. Regular users see only sources management for the topics they have access to.\n\nDefault topic on first install of multi-topic version: still id=1 'ביטוח לאומי'. New installs get the same seed.",
|
||
"testStrategy": "1) Create topic 'דיני עבודה' (slug 'employment-law'). 2) Verify it appears in GET /kb/topics within seconds. 3) The user-facing topic dropdown lists it. 4) Upload a PDF under it (Phase 2 flow), verify search/ask scoped to it works. 5) Edit prompt addendum — /kb/ask answers in context of employment law. 6) Soft-delete the test topic — disappears from user dropdown but kept in admin list.",
|
||
"subtasks": [],
|
||
"dependencies": [
|
||
"12"
|
||
],
|
||
"createdAt": "2026-04-25T13:30:00Z",
|
||
"updatedAt": "2026-04-25T17:47:57.615Z"
|
||
},
|
||
{
|
||
"id": "17",
|
||
"title": "Deploy KnowledgeBase + shira-hermes to production (Hetzner)",
|
||
"description": "Right now the entire KB stack runs only on the dev server (192.168.10.206 / dev.marcus-law.co.il): shira-hermes, the insurance_kb Postgres database with pgvector, the MinIO bucket insurance-kb, and the KnowledgeBase EspoCRM extension installed on espocrm.dev. Production CRM (https://crm.prod.marcus-law.co.il, Hetzner 46.62.204.107) has none of it. Need to bring up an equivalent stack on prod so the live CRM can use the KB. Infrastructure pieces should be sized for production, not just copies of dev.",
|
||
"status": "pending",
|
||
"priority": "high",
|
||
"details": "Pieces to provision on Hetzner Coolify (project espoCRM/Useful MicroServices on prod, NOT dev):\n\n1. PostgreSQL with pgvector — image pgvector/pgvector:pg16 (matching dev). Either dedicated DB service for shira-hermes or extend a shared one. Create role shira_kb + DB insurance_kb + extension pgvector. Migrations: same DDL we ran on dev (kb_source, kb_chunk with vector(1024) embedding, hnsw + gin indexes). After multi-topic Phase 1 (#12) ships, also create kb_topic + kb_source.topic_id.\n\n2. MinIO — separate Coolify service, e.g. minio-prod. Bucket insurance-kb with the same inbox/{law,regulation,circular} + processed/{...} + failed/{...} layout. Or use Hetzner Object Storage as an S3-compatible alternative; KB code already uses any S3 endpoint.\n\n3. shira-hermes app — Coolify dockerimage app pulling gitea.dev.marcus-law.co.il/espocrm-extensions/shira-hermes:latest. Needs network access to: prod PG, prod MinIO, https://ai-gateway.prod.marcus-law.co.il (NOT the dev gateway), and the prod EspoCRM API. Domain: shira.prod.marcus-law.co.il. Health check at /api/health. Same env vars as dev shira (PORT, API_KEY, AI_GATEWAY_URL, AI_GATEWAY_API_KEY, CLAUDE_MODEL, ESPOCRM_URL, ESPOCRM_API_KEY, KB_DATABASE_URL, VOYAGE_API_KEY, VOYAGE_MODEL, KB_S3_*) but pointing at prod resources.\n\n4. Secrets in Infisical, environment 'prod':\n - /espocrm: KB_DATABASE_URL, ADMIN_USER, API_KEY, API_USER (mirroring dev keys but for prod)\n - /ai-gateway: API_KEY, ESPOCRM_URL=https://crm.prod.marcus-law.co.il, ESPOCRM_API_KEY (already exists for the prod gateway)\n - /external-apis/voyage: VOYAGE_API_KEY (decision: separate prod key for billing isolation, or share with dev — user's choice)\n - /minio (new folder): MINIO_ROOT_USER, MINIO_ROOT_PASSWORD, S3_ENDPOINT, CONSOLE_URL\n - /mattermost: WEBHOOK_KB_INGEST (or skip notifications on prod)\n - shira-hermes app pulls them via Coolify env_vars referencing Infisical (the n8n workflow Infisical→Coolify Sync (id U3FiSwdvjHtWK2rh) syncs them automatically once configured).\n\n5. Data: choose between (A) hot-migrate from dev — pg_dump --table=kb_source --table=kb_chunk + pg_restore on prod, then mc mirror s3://dev/insurance-kb to s3://prod/insurance-kb. Preserves the 1024-dim embeddings already computed (no Voyage cost). Or (B) fresh on prod — re-ingest the 5 PDFs via the inbox/scan-inbox flow + re-scrape the law from Wikisource. Voyage cost ~$2-3 in embeddings. Cleaner state but slower (~30-60 min). User should pick based on whether dev's data is considered authoritative or needs review.\n\n6. EspoCRM prod (crm.prod.marcus-law.co.il, image gitea.prod.marcus-law.co.il/chaim/legalcrm-espocrm:9.3.3):\n - Install KnowledgeBase extension: scp KnowledgeBase-X.Y.Z.zip → docker cp into the prod espocrm container → php /var/www/html/command.php extension --file=...\n - Configure SmartAssistant Integration via Admin UI: webhookUrl=https://shira.prod.marcus-law.co.il/, apiKey=<shared with shira>. The KB extension reads these from the SmartAssistant integration data field (KnowledgeBaseService::getBaseUrl + getApiKey).\n - Verify EspoCRM scope/role config so non-portal users get KB access (current dev rule).\n\n7. n8n prod (https://n8n.prod.marcus-law.co.il): clone the dev workflow 'EspoCRM | KB Auto-Scan' (id M2gyevYjiLkfDGav). Adjust the URL from https://shira.dev.marcus-law.co.il to https://shira.prod.marcus-law.co.il + use the prod admin key. Cron: every 15 min, same as dev. Optional — only needed if firms upload via the manual MinIO inbox flow (Phase 2/#13 will replace this with self-service UI uploads).\n\n8. DNS: add shira.prod.marcus-law.co.il pointing at the prod traefik (same as crm.prod.marcus-law.co.il). Coolify will provision the cert.\n\n9. Smoke test in this order: GET https://shira.prod.marcus-law.co.il/api/health 200; admin scan-inbox returns 0 items if data was migrated (else processes pending uploads); /kb/sources returns the 6 (or however many were migrated); /kb/search 'תקנה 36' returns hits; install KB ext on espocrm prod, open the בסיס ידע tab, run search + ask end-to-end; verify ask streams via SSE through the prod entry point.",
|
||
"testStrategy": "1) Each Coolify service status=running:healthy after deploy. 2) Health check curl https://shira.prod.marcus-law.co.il/api/health returns {status:'ok'} or equivalent. 3) From inside the espocrm prod container: curl with X-Api-Key against /kb/sources returns the migrated/seeded sources. 4) In the prod CRM browser: open בסיס ידע, search returns hits, ask streams progress and lands an answer. 5) PDF iframe (?entryPoint=KnowledgeBasePdf&sourceId=N) loads. 6) After 24h: confirm Voyage usage dashboard shows queries from the prod IP (rule out missing API key). 7) Backup baseline: pg_dump of insurance_kb on prod scheduled (Coolify's database_backups feature for the new PG).",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T14:00:00Z"
|
||
},
|
||
{
|
||
"id": "16",
|
||
"title": "Phase 5 (optional) — Per-topic ACL by EspoCRM role",
|
||
"description": "Not every user in a multi-topic firm should see every topic. Example: only the criminal-law department needs the criminal KB; the family-law team shouldn't. Wire EspoCRM's existing role/team model to the KB topics: each topic can be restricted to specific roles, with two permission levels — 'view' (use search/ask) and 'manage' (upload/edit/delete). Without role mapping, all non-portal users see all topics (current behavior). With mapping, the topic dropdown filters to topics the user has at least 'view' on, and the management UI gates 'manage' actions to users with the manage permission for that topic.",
|
||
"status": "deferred",
|
||
"priority": "low",
|
||
"details": "DB: new table kb_topic_acl: topic_id FK, role_name TEXT, permission TEXT CHECK in ('view', 'manage'), PRIMARY KEY (topic_id, role_name, permission).\n\nshira-hermes endpoints:\n- /kb/topics: filter by user's roles. The user's role list comes from the EspoCRM proxy (sent in a header or JWT claim — needs design).\n- /admin/kb/* actions: enforce 'manage' permission per source's topic_id.\n\nEspoCRM client:\n- Topic dropdown: only shows topics the user has 'view' on.\n- Management tab: only visible if user has 'manage' on at least one topic.\n- Edit/delete buttons in the sources table: visible only when user has 'manage' on that source's topic.\n\nThis is the most-likely-to-skip phase if the user's firm is small and everyone needs everything. Worth scoping out depth before committing.\n\n---\nDEFERRED 2026-04-25: small firm, all users need access to all topics. Re-open if the firm grows past ~3 lawyers AND topics start to genuinely need siloing (e.g. confidential criminal cases the partners shouldn't browse). Until then, the only access control is `User::isPortal()` already enforced in `Controller::checkAccess()`.",
|
||
"testStrategy": "Set up two test users: lawyer_a with role 'criminal-law', lawyer_b with role 'employment-law'. Topics: 'דין פלילי' restricted to 'criminal-law' role only, 'דיני עבודה' restricted to 'employment-law'. lawyer_a sees only the criminal topic; lawyer_b only employment. Cross-user attempts return 403.",
|
||
"subtasks": [],
|
||
"dependencies": [
|
||
"12",
|
||
"15"
|
||
],
|
||
"createdAt": "2026-04-25T13:30:00Z",
|
||
"updatedAt": "2026-04-25T17:51:07.124Z"
|
||
},
|
||
{
|
||
"id": "18",
|
||
"title": "feat(kb): add 'caselaw' (פסיקה) as a fourth kind",
|
||
"description": "Add 'caselaw' alongside law/regulation/circular across the whole stack. Touches: DB CHECK constraints (migration 003), shira-hermes Python (Literal types, _KINDS, kind validation, chunker section detection), EspoCRM Controller/Service validators, template dropdowns, JS kindHe mapping.",
|
||
"details": "DB: migration 003_caselaw_kind.sql alters CHECK on kb_source.kind and kb_ingest_job.kind to include 'caselaw'. shira-hermes: update Literal types in ingest.py, admin_kb.py, kb_public.py SearchRequest; add 'caselaw' to s3.py _KINDS; chunker.py — fall back to generic section detector (regex for 'פסק דין', 'תיק' / case number, paragraph numbers). EspoCRM: update validators in Controller postActionUpload + Service search/uploadFile; add 'caselaw' option to kind <select> in index.tpl (search box + upload form); update kindHe in index.js.",
|
||
"testStrategy": "",
|
||
"status": "done",
|
||
"dependencies": [],
|
||
"priority": "medium",
|
||
"subtasks": [],
|
||
"updatedAt": "2026-04-25T17:02:14.241Z"
|
||
},
|
||
{
|
||
"id": "19",
|
||
"title": "feat(kb): tag/label sub-topics within a topic (e.g. 'ילד נכה')",
|
||
"description": "Group multiple sources within a topic by sub-subject so users can find e.g. all 'ילד נכה' circulars together. Recommendation: many-to-many kb_label + kb_source_label so a source can carry multiple tags reflecting that legal docs commonly touch several subjects.",
|
||
"status": "pending",
|
||
"priority": "medium",
|
||
"details": "Three approaches considered:\n\n1. Free-text 'subject' column on kb_source (~1d): cheapest, typo-prone (ילד נכה / ילדים נכים → separate buckets).\n\n2. Many-to-many labels (~3d, RECOMMENDED): kb_label(id, topic_id, slug UNIQUE per topic, name) + kb_source_label(source_id, label_id, PK both). UI shows label chips on sources; click to filter. Naturally handles cross-cutting subjects (a circular tagged both 'ילד נכה' AND 'אזרח ותיק'). Needs admin UI to manage labels.\n\n3. Hierarchical sub-topics under kb_topic (~5d): clean tree, but a source can only live in one branch — wrong fit for the legal world. Also clashes with planned Phase 4 topic-CRUD UI.\n\nPragmatic path: ship #1 first (subject TEXT field on kb_source + dropdown of seen values + browse-view grouping); upgrade to #2 once we see how labels are used in practice.",
|
||
"testStrategy": "Upload 3 circulars all in 'ילד נכה' subject; verify they appear grouped together in browse view; verify search results show the subject chip; verify topic switch resets the subject filter.",
|
||
"subtasks": [],
|
||
"dependencies": [],
|
||
"createdAt": "2026-04-25T16:54:54.478470Z"
|
||
},
|
||
{
|
||
"id": "20",
|
||
"title": "v0.8.0 — kind 'tool' + labels + bulk upload with AI classification",
|
||
"description": "Phase 6. Adds 'tool' kind for academic assessment instruments (GMFCS, MACS, etc), label-based sub-topic grouping (kb_label many-to-many), multi-file drag-drop upload, and AI-extracted metadata via Claude/ai-gateway. Two-phase ingest: classify → await_review → embed. Replaces single-file upload with batch-review screen. Also creates 'תוויות' admin tab. Subsumes task #19 (labels). Plan: ~/.claude/plans/hidden-tickling-ullman.md",
|
||
"details": "See /home/chaim/.claude/plans/hidden-tickling-ullman.md for the full architecture, migration scripts, API surface, classifier prompt, UX, and file-level breakdown. ~7 days estimated.",
|
||
"testStrategy": "",
|
||
"status": "done",
|
||
"dependencies": [],
|
||
"priority": "medium",
|
||
"subtasks": [],
|
||
"updatedAt": "2026-04-25T20:19:47.523Z"
|
||
},
|
||
{
|
||
"id": "21",
|
||
"title": "fix(kb): prevent double-commit + collapse admin sections",
|
||
"description": "Fix UI race in commitAllBatch + collapse Sources/Labels/Recent Jobs panels",
|
||
"details": "Fix 1: in polling tick (index.js ~1217), don't downgrade local 'committing' status back to 'awaiting_review' from server. Fix 2: wrap Sources, Labels and Recent Jobs panel bodies in collapsible div with chevron toggle, default collapsed; lazy-load on first expand.",
|
||
"testStrategy": "",
|
||
"status": "done",
|
||
"dependencies": [],
|
||
"priority": "high",
|
||
"subtasks": [],
|
||
"updatedAt": "2026-04-26T11:09:41.057Z"
|
||
}
|
||
],
|
||
"metadata": {
|
||
"version": "1.0.0",
|
||
"lastModified": "2026-04-26T11:09:41.059Z",
|
||
"taskCount": 21,
|
||
"completedCount": 15,
|
||
"tags": [
|
||
"master"
|
||
]
|
||
}
|
||
}
|
||
} |