13 Commits

Author SHA1 Message Date
chaim 8a4f16a50f feat(KB): v0.8.0 — bulk upload, AI classifier, labels, tool kind
v0.8.0 ships the four-feature bundle from the v0.8.0 plan plus
mid-flight fixes discovered when batch-testing 5 circulars.

New capabilities:
  * Multi-file batch upload. AI classifier (Sonnet via ai-gateway)
    reads the first 3 pages of each PDF and proposes kind / title /
    identifier / labels / dates / summary. User reviews + edits per
    card before committing. Two-phase ingest: classify →
    awaiting_review → embed.
  * 'tool' kind for academic assessment instruments (GMFCS, MACS).
  * Labels (kb_label / kb_source_label) for sub-topic navigation;
    classifier proposes shared label slugs so the graph builds
    itself.
  * 'תוויות' admin sub-section for merge/delete of unused labels.
  * NEW 'ממתינים לאישור' panel: lists batches still in
    awaiting_review with status counters so a hard-refreshed user
    can resume their review — closes the RAM-only _activeBatch gap.

Mid-flight fixes folded in:
  * classifier timeout 45s→90s, concurrency 5→2. ai-gateway
    serializes through a single Claude OAuth session; with conc=5,
    jobs 4-5 of a 5-file batch consistently timed out.
  * labels schema array-of-string → comma-separated string. Claude
    via ai-gateway returned [{}, {}, {}] for items:{type:"string"}.
    _normalize accepts both shapes defensively.

Backfilled ai_classified_at + description + 1-3 labels for the 10
sources ingested in earlier sessions so the filter UX is uniform.

Backend (shira-hermes) in commits 0d678da (Phase 6) + bb23b8a
(this session's fixes).

Refs Task Master #20

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 20:18:34 +00:00
chaim 30a9c397e8 chore: add manifest.displayLabel for extension-platform catalog
Short Hebrew label shown in the admin "ההרחבות שלנו" panel.
Synced into extensions.description on next sync-registry run
(or on next /publish for this extension).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 18:07:59 +00:00
chaim db7b30e3c0 feat: Phase 4 — topic CRUD UI in 'ניהול' tab
Adds a topics-management panel above the sources table. Admins can
create new legal domains (דיני עבודה, דין פלילי, נדל"ן) without
running SQL — slug + name + description + system prompt addendum
all live in one inline form. Per-row actions:

  ✏ Edit          — opens inline form with all fields except slug
                    (slug is locked post-create — the S3 layout
                    depends on it)
  👁 Toggle active — soft-disable: hides the topic from the user-facing
                    <select> while keeping data intact. Eye icon
                    flips between "השבת" and "הפעל"
  🗑 Delete       — hard-delete; only allowed when source_count=0.
                    Otherwise the UI directs the user to soft-disable
                    instead

Any topic mutation (create / rename / toggle / delete) invalidates
the cached _topics list so the user-facing dropdown re-fetches
immediately — admins don't have to refresh the page to see their
own changes.

Service.request() now distinguishes 4xx from 5xx upstream errors:
4xx is rethrown as BadRequest (so the user sees "slug already exists"
instead of a generic 500), 5xx stays as Error.

Backend: depends on shira-hermes commit 49503ca (admin topic
endpoints). No new migration — kb_topic schema from migration 001
is sufficient.

Description field in manifest was rewritten to Hebrew to match the
in-CRM scopeNames label ("מאגר ידע").

Refs Task Master #15

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 17:46:51 +00:00
chaim d051b268dd feat: Phase 3 — sources management table in 'ניהול' tab
Adds full CRUD for KB sources from the EspoCRM UI: a sortable table at
the top of the 'ניהול' tab with kind / title-identifier-updated / chunk
count / actions columns, a kind filter (חוק / תקנות / חוזרים / פסיקה),
and three per-row actions:

  ✏ Edit       — inline form with title, identifier, dates, source URL
  ↻ Reingest   — re-parses the original file in place, replacing chunks
                 while keeping the source row + hand-edited metadata
  🗑 Delete    — confirm dialog with chunk count; double confirm above
                 100 chunks; also deletes the MinIO object

Browser polls the standard /KnowledgeBase/action/job endpoint for
re-ingest progress (same banner as upload). On terminal status
(done|failed) the sources table auto-refreshes so chunk_count and
last_ingest reflect the new state. Topic switch invalidates the
per-topic admin-sources cache so a stale list doesn't bleed across
topics.

Backend: depends on shira-hermes commit 17f93b5
(GET/PUT/DELETE /admin/kb/sources + POST /reingest).

Refs Task Master #14

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 17:27:45 +00:00
chaim e7b21919c2 feat: add 'caselaw' (פסיקה) kind alongside חוק/תקנות/חוזרים
Court rulings get their own kind so users can filter search results
to "פסיקה" specifically and upload case-law PDFs from the ניהול tab.
PHP validators in Controller + Service accept the new kind; the search
dropdown and upload kind dropdown gain a "פסיקה" option; kindHe in
index.js maps caselaw → "פסיקה" so jobs list, search results, and
browse view all label it consistently.

Backend: depends on shira-hermes commit 16eeeff (kind validators +
chunker fallback) and migration 003_caselaw_kind.sql (already applied
on dev — alters CHECK constraints on kb_source.kind and
kb_ingest_job.kind to include 'caselaw').

Refs Task Master #18

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 17:01:12 +00:00
chaim 6781ac4e37 feat: Phase 2 — document upload from KB UI
Adds a "ניהול" tab with multipart file upload, async job tracking, and
a recent-jobs list with live status polling. Browser POSTs to
/KnowledgeBase/action/upload (PHP proxy), which forwards as multipart
to shira-hermes /admin/kb/upload. shira-hermes returns a job_id
immediately and processes parse/chunk/embed in a background task; the
browser polls every 2s until status hits done|failed.

New EspoCRM endpoints:
  POST /KnowledgeBase/action/upload   (multipart, $_FILES['file'])
  GET  /KnowledgeBase/action/jobs     (list, filtered by topicId/status)
  GET  /KnowledgeBase/action/job?id   (single-job detail)

The X-User-Name header is forwarded so kb_ingest_job records who
uploaded each file. Cross-topic guard in switchTopic stops polling
when the user changes topics mid-upload (the job continues server-side).

Depends on shira-hermes commit 0cb89fb (admin upload endpoints +
migration 002).

Refs Task Master #13

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 16:46:42 +00:00
chaim dacb7f6256 feat: Phase 1 — multi-topic KB foundation
Generalize the Knowledge Base from insurance-only to multi-domain.
Introduces kb_topic table (shira-hermes), topic-aware endpoints
(/kb/topics, /kb/search, /kb/ask, /kb/ask/stream all accept topic_id),
a topic picker <select> in the EspoCRM UI (localStorage-persisted),
and renames the LLM tool search_insurance_kb → search_legal_kb.
All existing sources migrate to topic_id=1 (ביטוח לאומי); the UI
defaults to that topic so no visible regression for current users.

Refs Task Master #12

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-25 14:33:04 +00:00
chaim ba75463661 feat(kb): topic picker + topic-scoped client (Phase 1, no manifest bump)
Wires the EspoCRM extension to the multi-topic backend introduced in
shira-hermes commit f03721e. The KB page header now shows a topic
<select> ('נושא:'); the user's selection persists in localStorage
('kb-topic') and is sent with every search/ask/sources call so cross-
domain bleed-over is impossible. Single seeded topic ('ביטוח לאומי')
means existing users see no functional change until a second topic is
added in Phase 4 (Task Master #15).

- Resources/routes.json: GET /KnowledgeBase/action/topics.
- Controllers/KnowledgeBase.php: actionTopics + topicId passthrough on
  search/sources/ask. Numeric coercion for the request payload.
- Services/KnowledgeBaseService.php: listTopics(); search/listSources/
  ask take an optional topicId and forward it as topic_id to upstream.
- EntryPoints/KnowledgeBaseAskStream.php: ?topicId=N becomes topic_id
  in the JSON body sent to /kb/ask/stream.
- res/templates/kb/index.tpl: topic <select> in the page header,
  with a kb-topic-name-suffix span that JS fills with the active name.
- src/views/kb/index.js: module-level _topics cache + LS_TOPIC. setup
  reads localStorage; afterRender gates the picker fill + sources fetch
  on topics being loaded so a stale id from a deleted topic doesn't
  fire a 400-ing /sources call. switchTopic clears _activeAsk/Search +
  _lastAsk/Search + sessionStorage entries + this._sources, then
  reRenders. Cross-topic guard in afterRender drops cached state whose
  topicId !== this.topicId. _activeAsk / _lastAsk / _activeSearch /
  _lastSearch all carry topicId. EventSource URL gains &topicId.

Refs Task Master #12.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 14:15:36 +00:00
chaim 6f11895dd7 chore(tm): file #17 — production deployment plan
Comprehensive Coolify-prod runbook covering: pgvector PG provisioning,
MinIO bucket, shira-hermes dockerimage app, Infisical /prod secrets,
data migration choice (pg_dump+S3 mirror vs fresh ingest), KB extension
install on prod EspoCRM, SmartAssistant integration config,
optional n8n auto-scan workflow clone, DNS, and end-to-end smoke test
sequence. Currently the entire stack is dev-only — this task makes
KB live on the production CRM at crm.prod.marcus-law.co.il.
2026-04-25 13:45:44 +00:00
chaim 63d7a7922a chore(tm): file 8 new tasks — 3 carry-over + 5-phase multi-topic plan
Captures the open-but-not-blocking items from the v0.2.1 sessions plus
the comprehensive plan for generalizing the KB beyond ביטוח לאומי.

#9-11: carry-over polish noted at the v0.2.1 close
- #9  SSE rejoin (in-flight stream survives F5 / tab close)
- #10 n8n release-asset auto-attach has been failing for every release
      from v0.1.8 through v0.2.1; manual curl uploads as workaround
- #11 ask mode source picker hides text-source citations (Wikisource law)
      because /kb/ask filters sources_used to PDFs only

#12-16: multi-topic KB plan (next session)
- #12 Phase 1 — DB schema with kb_topic + kb_source.topic_id, /kb/topics
      endpoint, topic-aware system prompts, topic dropdown in UI;
      backwards-compat by seeding topic_id=1 ביטוח לאומי and migrating
      the 6 existing sources to it
- #13 Phase 2 — file upload from the management panel, async ingestion
      via kb_ingest_job table, live job-status polling
- #14 Phase 3 — sources management UI: edit metadata, delete (with
      cascade messaging), re-ingest, jobs/failures view
- #15 Phase 4 — topic CRUD UI for admins (add דיני עבודה, דין פלילי,
      etc., edit prompts, soft-disable)
- #16 Phase 5 (optional) — per-topic ACL by EspoCRM role with view vs
      manage permissions

Phases 1-3 are the must-ship subset for what the user asked. Phase 4 is
admin convenience. Phase 5 is scoped only if firms ask for it.
2026-04-25 13:33:51 +00:00
chaim e80ccb8bdf fix(kb): RTL-correct pane order + new-result button + 30-min auto-clear
Three issues from the v0.2.0 user test:

1. Sides flipped relative to expectation
   In our Hebrew/RTL CRM the user reads primary content (the answer or
   the hit list) on the visual right and the supporting reference
   (the PDF) on the visual left — that's how Hebrew layouts stage
   "main + sidebar". v0.1.10's _buildSplitShell forced direction:ltr on
   the splitter container (correct, for mouseX math) but laid the
   children in the order [primary, handle, reference], which under LTR
   put primary on the LEFT and PDF on the RIGHT. Fixed by renaming the
   helper params to {primaryHtml, referenceHtml} and ordering the
   children as [reference, handle, primary] — visual LEFT is now the
   PDF, visual RIGHT is the answer/list. Default split moved from 42%
   to 58% so the reference pane (now on the left) keeps the same
   absolute width the PDF column had under v0.1.9's bootstrap rows.

2. No way to start a new query
   afterRender replays _lastSearch / _lastAsk on every remount, which
   means the prior result hangs around forever. Added a "חיפוש חדש" /
   "שאלה חדשה" button next to the submit button. clearResults() cancels
   any in-flight request (closes the EventSource for ask, drops
   _activeSearch reference for search), removes the cached entry from
   sessionStorage, empties the results pane, and refocuses the input.

3. Stale results from another session
   Cached results now auto-expire after 30 minutes — _loadJson checks
   completedAt against STALE_AFTER_MS and silently drops anything
   older. So coming back tomorrow the KB tab opens clean instead of
   showing yesterday's answer to whatever you asked then.

Refs Task Master #4, #6
2026-04-25 13:16:30 +00:00
chaim a00fc3729c feat(kb/ask): live SSE streaming of Shira's progress (v0.2.0)
User wanted to see what Shira is doing while she thinks — like Claude
does — instead of staring at an incrementing seconds counter. Now the
ask UI shows one line per agent step as it happens:

  3s  🧠  קוראת את השאלה
  4s  🔍  מחפשת בבסיס הידע: "תקנה 36"
  9s  ✓   נמצאו 5 קטעים רלוונטיים
 10s  🔍  מחפשת בבסיס הידע: "תקנה 36 ביטוח לאומי"
 14s  ✓   נמצאו 5 קטעים רלוונטיים
 15s  🧠  ממשיכה לחקור
 22s  ✍️  מנסחת תשובה
 → תשובה

Client wiring:
- runAsk now opens an EventSource at ?entryPoint=KnowledgeBaseAskStream
  instead of POSTing JSON. Each SSE event of type thinking/tool_start/
  tool_done/tool_error/writing appends a row to a stacked progress log.
  The final {type:answer,text,sources} event triggers renderAskAnswer
  with the existing split view. {type:error} surfaces via showError.
- Module-level state from v0.1.9 unchanged in spirit but now stores the
  EventSource + accumulated events. afterRender on view re-mount replays
  the entire event list and re-binds onmessage/onerror — the SSE
  connection itself doesn't drop because it lives at module scope.
- Elapsed-time pill stays for cadence but is decoration; the real
  signal is the per-event log.

EspoCRM proxy:
- New EntryPoint KnowledgeBaseAskStream — required because EventSource
  is GET-only and ?message= must come via the URL. PHP buffering is
  disabled (zlib + ob + apache_setenv no-gzip), Apache headers are set
  for SSE (no-cache, X-Accel-Buffering: no), and we cURL into
  shira-hermes /kb/ask/stream with CURLOPT_WRITEFUNCTION echoing each
  byte and flushing immediately. The handler ends with exit; to bypass
  EspoCRM's Response wrapper which would otherwise emit headers/body
  on top of our raw stream.
- KnowledgeBaseService gained two public accessors (getStreamingUrl,
  getStreamingApiKey) so the EntryPoint can build the cURL without
  going through request() (which buffers the whole body).
- entryPoints.json registers the new class.

Server (shira-hermes 76fd77f):
- AgentRunner.run accepts an on_event sync callback fired before each
  LLM call (thinking) and around each tool call (tool_start, tool_done,
  tool_error). Hebrew labels in agent_runner._tool_label / _tool_done_label
  ship over the wire ready-to-display — keeps the client free of
  translation concerns.
- POST /kb/ask/stream wraps the existing agent runner in an asyncio
  task feeding an asyncio.Queue, returns StreamingResponse with proper
  SSE headers (X-Accel-Buffering, Cache-Control). 15s comment-line
  heartbeats keep the connection open through proxy idle-timeouts.
- Original POST /kb/ask still works — additive change.

Refs Task Master #8
2026-04-25 13:00:58 +00:00
chaim 2fe10727eb fix(kb): search preview shows section-in-context for text sources
User reported the search card "looks broken" when the selected hit is the
law (Wikisource source 5) — the right preview pane just duplicates the
chunk text already visible in the left list card. For PDF sources the
right pane shows the PDF page, but for text-only sources it had nothing
useful to add and fell back to a copy.

Fix:
- /kb/search hits gained chunk_index (shira-hermes b127caf), and
  /kb/source/{id}/chunks gained an `around=<chunk_index>&ctx=<k>` window.
- Espo proxy plumbing: getActionChunks reads `around`/`ctx` query
  params and forwards them; KnowledgeBaseService::sourceChunks accepts
  optional $around + $ctx and appends them to the upstream URL.
- showSearchPreview for non-PDF hits now fetches the matched chunk plus
  2 sections before and 2 after, renders them as stacked panels: the
  matched section gets a yellow #fff3cd highlight, neighbors render as
  muted context blocks. The panel header carries a prominent
  "פתח ב-Wikisource" button so users can jump to the public source page.
  After render the matched section auto-scrolls into view.
- Race protection via _previewToken: a click on a different hit while a
  fetch is in flight cancels the stale render so the user always sees
  the section that matches the currently-selected card.

PDF path unchanged.

Refs Task Master #7
2026-04-25 12:28:50 +00:00
10 changed files with 3238 additions and 138 deletions
+1 -1
View File
@@ -2,5 +2,5 @@
"currentTag": "master",
"lastSwitched": "2026-04-24T15:47:33.139Z",
"branchTagMapping": {},
"migrationNoticeShown": false
"migrationNoticeShown": true
}
+196 -10
View File
@@ -2,7 +2,7 @@
"master": {
"tasks": [
{
"id": 1,
"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",
@@ -14,7 +14,7 @@
"createdAt": "2026-04-24T15:47:00Z"
},
{
"id": 2,
"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",
@@ -26,7 +26,7 @@
"createdAt": "2026-04-24T15:47:00Z"
},
{
"id": 3,
"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",
@@ -38,7 +38,31 @@
"createdAt": "2026-04-25T10:00:00Z"
},
{
"id": 5,
"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",
@@ -50,7 +74,7 @@
"createdAt": "2026-04-25T11:00:00Z"
},
{
"id": 6,
"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",
@@ -62,7 +86,7 @@
"createdAt": "2026-04-25T11:00:00Z"
},
{
"id": 4,
"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",
@@ -72,12 +96,174 @@
"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": "in-progress",
"dependencies": [],
"priority": "medium",
"subtasks": [],
"updatedAt": "2026-04-25T18:21:44.731Z"
}
],
"metadata": {
"created": "2026-04-24T15:47:00Z",
"updated": "2026-04-25T10:30:00Z",
"description": "KnowledgeBase extension tasks"
"version": "1.0.0",
"lastModified": "2026-04-25T18:21:44.731Z",
"taskCount": 20,
"completedCount": 13,
"tags": [
"master"
]
}
}
}
}
@@ -1,6 +1,13 @@
<div class="kb-page" dir="rtl">
<div class="page-header">
<h3>בסיס ידע — ביטוח לאומי</h3>
<div class="page-header" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
<h3 style="margin:0;">בסיס ידע<span class="kb-topic-name-suffix"></span></h3>
<div class="kb-topic-picker" style="display:flex;align-items:center;gap:8px;">
<label for="kb-topic-select" class="text-muted" style="margin:0;font-weight:normal;">נושא:</label>
<select id="kb-topic-select" class="form-control kb-topic-select" data-name="topic"
style="min-width:180px;">
<option value="">טוען…</option>
</select>
</div>
</div>
<ul class="nav nav-tabs" style="margin-bottom:12px;">
@@ -13,6 +20,9 @@
<li class="{{#ifEqual mode 'browse'}}active{{/ifEqual}}">
<a href="#" role="button" data-action="switchMode" data-mode="browse">עיון</a>
</li>
<li class="{{#ifEqual mode 'manage'}}active{{/ifEqual}}">
<a href="#" role="button" data-action="switchMode" data-mode="manage">ניהול</a>
</li>
</ul>
{{#ifEqual mode 'search'}}
@@ -26,8 +36,12 @@
<option value="law">חוק</option>
<option value="regulation">תקנות</option>
<option value="circular">חוזרים</option>
<option value="caselaw">פסיקה</option>
<option value="tool">כלי הערכה</option>
</select>
<button type="button" class="btn btn-primary" data-action="submit">חפש</button>
<button type="button" class="btn btn-default" data-action="clearResults"
title="התחל חיפוש חדש (מנקה את התוצאות הקודמות)">חיפוש חדש</button>
</div>
<div class="small text-muted" style="margin-top:6px;">
חיפוש Hybrid: וקטורי + מילולי + rerank. מחזיר עד 8 קטעים רלוונטיים.
@@ -42,6 +56,8 @@
placeholder="שאלה בשפה חופשית…"
style="flex:1 1 320px;min-width:280px;" />
<button type="button" class="btn btn-primary" data-action="submit">שאל את שירה</button>
<button type="button" class="btn btn-default" data-action="clearResults"
title="התחל שאלה חדשה (מנקה את התשובה הקודמת)">שאלה חדשה</button>
</div>
<div class="small text-muted" style="margin-top:6px;">
שירה תחפש בבסיס הידע ותחזיר תשובה מסוכמת עם ציטוטים.
@@ -55,5 +71,116 @@
</div>
{{/ifEqual}}
{{#ifEqual mode 'manage'}}
<div class="kb-manage" style="display:flex;flex-direction:column;gap:16px;">
<div class="panel panel-default kb-topics-panel" style="padding:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<h4 style="margin:0;">נושאים (תחומי משפט)</h4>
<div style="display:flex;gap:8px;">
<button type="button" class="btn btn-default btn-sm" data-action="refreshTopics" title="רענן">
<span class="glyphicon glyphicon-refresh"></span>
</button>
<button type="button" class="btn btn-primary btn-sm" data-action="newTopic">
<span class="glyphicon glyphicon-plus"></span> נושא חדש
</button>
</div>
</div>
<div class="kb-topics-table">
<div class="text-muted">טוען נושאים…</div>
</div>
</div>
<div class="panel panel-default kb-sources-panel" style="padding:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<h4 style="margin:0;">מקורות בנושא<span class="kb-topic-name-suffix"></span></h4>
<div style="display:flex;gap:8px;align-items:center;">
<select class="form-control kb-sources-kind-filter" style="width:auto;">
<option value="">כל הסוגים</option>
<option value="law">חוק</option>
<option value="regulation">תקנות</option>
<option value="circular">חוזרים</option>
<option value="caselaw">פסיקה</option>
<option value="tool">כלי הערכה</option>
</select>
<button type="button" class="btn btn-default btn-sm" data-action="refreshSources" title="רענן">
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
</div>
<div class="kb-sources-table">
<div class="text-muted">טוען מקורות…</div>
</div>
</div>
<div class="panel panel-default kb-labels-panel" style="padding:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<h4 style="margin:0;">תוויות תת-נושא</h4>
<button type="button" class="btn btn-default btn-sm" data-action="refreshLabels" title="רענן">
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
<div class="kb-labels-table">
<div class="text-muted">טוען תוויות…</div>
</div>
<div class="text-muted small" style="margin-top:6px;">
תוויות נוצרות אוטומטית כשמעלים מסמך חדש ושירה מציעה תת-נושא. כאן ניתן למחוק תוויות שאינן בשימוש.
</div>
</div>
<div class="panel panel-default kb-pending-panel" style="padding:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<h4 style="margin:0;">ממתינים לאישור<span class="kb-pending-count text-muted" style="font-weight:normal;margin-right:6px;"></span></h4>
<button type="button" class="btn btn-default btn-sm" data-action="refreshPending" title="רענן">
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
<div class="kb-pending-list">
<div class="text-muted">טוען…</div>
</div>
<div class="text-muted small" style="margin-top:6px;">
באצ׳ים שעלו וממתינים לעריכה ואישור. לחץ "פתח" כדי לחזור למסך הסקירה.
</div>
</div>
<div class="panel panel-default kb-batch-panel" style="padding:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-bottom:8px;">
<h4 style="margin:0;">העלאת מסמכים</h4>
<div style="display:flex;gap:8px;align-items:center;">
<select id="kb-batch-kind" class="form-control" style="width:auto;">
<option value="circular" selected>חוזר</option>
<option value="law">חוק</option>
<option value="regulation">תקנות</option>
<option value="caselaw">פסיקה</option>
<option value="tool">כלי הערכה</option>
</select>
<input type="file" id="kb-batch-files" multiple
accept=".pdf,.docx,.txt" style="display:none;" />
<button type="button" class="btn btn-primary btn-sm" data-action="pickBatchFiles">
<span class="glyphicon glyphicon-cloud-upload"></span> בחר קבצים…
</button>
</div>
</div>
<div class="kb-batch-hint text-muted small" style="margin-bottom:8px;">
ניתן לבחור מספר קבצים בו-זמנית. שירה תנתח כל קובץ ותציע מטא-דאטה (סוג / כותרת / תוויות / סיכום) — תוכל לערוך לפני אישור הטמעה.
מקסימום 50MB לקובץ, עד 50 קבצים בקבוצה.
</div>
<div class="kb-batch-cards" style="display:flex;flex-direction:column;gap:10px;"></div>
<div class="kb-batch-actions" style="display:none;justify-content:space-between;align-items:center;margin-top:12px;padding-top:12px;border-top:1px solid #eee;">
<button type="button" class="btn btn-default btn-sm" data-action="discardAllBatch">בטל הכל</button>
<button type="button" class="btn btn-primary" data-action="commitAllBatch">
אישור והטמעה
<span class="kb-batch-commit-count"></span>
</button>
</div>
</div>
<div class="panel panel-default" style="padding:12px;">
<h4 style="margin-top:0;">משימות אחרונות</h4>
<div class="kb-jobs-list">
<div class="text-muted">טוען…</div>
</div>
</div>
</div>
{{/ifEqual}}
<div class="kb-results" style="margin-top:12px;"></div>
</div>
File diff suppressed because it is too large Load Diff
@@ -42,6 +42,27 @@ class KnowledgeBase
}
}
/**
* Coerce a request-supplied topic id (string from query, int from JSON body)
* to int|null. Lets the upstream resolver decide what an unknown id means.
*/
private function coerceTopicId($raw): ?int
{
if ($raw === null || $raw === '' || $raw === false) {
return null;
}
if (is_numeric($raw)) {
return (int) $raw;
}
return null;
}
public function getActionTopics(Request $request, Response $response): array
{
$this->checkAccess();
return $this->getService()->listTopics();
}
public function postActionSearch(Request $request, Response $response): array
{
$this->checkAccess();
@@ -54,14 +75,17 @@ class KnowledgeBase
return $this->getService()->search(
trim($data->query),
$data->kind ?? 'any',
(int) ($data->top_k ?? $data->topK ?? 8)
(int) ($data->top_k ?? $data->topK ?? 8),
$this->coerceTopicId($data->topicId ?? $data->topic_id ?? null)
);
}
public function getActionSources(Request $request, Response $response): array
{
$this->checkAccess();
return $this->getService()->listSources();
return $this->getService()->listSources(
$this->coerceTopicId($request->getQueryParam('topicId'))
);
}
public function getActionChunks(Request $request, Response $response): array
@@ -73,7 +97,12 @@ class KnowledgeBase
throw new BadRequest('sourceId (numeric) is required.');
}
return $this->getService()->sourceChunks((int) $sourceId);
$around = $request->getQueryParam('around');
$ctx = $request->getQueryParam('ctx');
$aroundInt = ($around !== null && is_numeric($around)) ? (int) $around : null;
$ctxInt = ($ctx !== null && is_numeric($ctx)) ? (int) $ctx : 2;
return $this->getService()->sourceChunks((int) $sourceId, $aroundInt, $ctxInt);
}
public function postActionAsk(Request $request, Response $response): array
@@ -88,7 +117,351 @@ class KnowledgeBase
return $this->getService()->ask(
trim($data->message),
$data->conversationId ?? null,
$data->conversationHistory ?? []
$data->conversationHistory ?? [],
$this->coerceTopicId($data->topicId ?? $data->topic_id ?? null)
);
}
/**
* Multipart upload to shira-hermes /admin/kb/upload. We rely on PHP's
* automatic multipart parsing via $_FILES because the EspoCRM Request
* interface doesn't expose uploaded files directly. The user's
* EspoCRM identity is forwarded as `X-User-Name` so the upstream job
* row records who uploaded what.
*/
public function postActionUpload(Request $request, Response $response): array
{
$this->checkAccess();
$files = $_FILES['file'] ?? null;
if (!$files || ($files['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
throw new BadRequest('No file uploaded (form field must be `file`).');
}
$tmpPath = $files['tmp_name'] ?? '';
if (!$tmpPath || !is_uploaded_file($tmpPath)) {
throw new BadRequest('Invalid upload — tmp_name missing.');
}
// For multipart/form-data EspoCRM's getParsedBody() returns an empty
// stdClass; the form fields land in $_POST as PHP parses them.
$kind = $_POST['kind'] ?? null;
if (!in_array($kind, ['law', 'regulation', 'circular', 'caselaw'], true)) {
throw new BadRequest('kind must be one of: law, regulation, circular, caselaw.');
}
$topicId = $this->coerceTopicId($_POST['topicId'] ?? $_POST['topic_id'] ?? null);
if ($topicId === null) {
throw new BadRequest('topicId is required.');
}
$metadata = [
'title' => isset($_POST['title']) ? trim((string) $_POST['title']) : '',
'identifier' => isset($_POST['identifier']) ? trim((string) $_POST['identifier']) : '',
'published_at' => $_POST['published_at'] ?? $_POST['publishedAt'] ?? '',
'effective_at' => $_POST['effective_at'] ?? $_POST['effectiveAt'] ?? '',
'source_url' => $_POST['source_url'] ?? $_POST['sourceUrl'] ?? '',
];
return $this->getService()->uploadFile(
$tmpPath,
(string) ($files['name'] ?? 'upload'),
(string) $kind,
$topicId,
$metadata,
(string) $this->user->get('userName')
);
}
public function getActionJobs(Request $request, Response $response): array
{
$this->checkAccess();
$topicId = $this->coerceTopicId($request->getQueryParam('topicId'));
$status = $request->getQueryParam('status');
$limit = $request->getQueryParam('limit');
$limitInt = ($limit !== null && is_numeric($limit)) ? (int) $limit : 50;
return $this->getService()->listJobs($topicId, $status, $limitInt);
}
public function getActionJob(Request $request, Response $response): array
{
$this->checkAccess();
$jobId = $request->getQueryParam('id');
if (!$jobId || !is_numeric($jobId)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->getJob((int) $jobId);
}
// ── Phase 3: source management (Task #14) ───────────────────────────────
public function getActionAdminSources(Request $request, Response $response): array
{
$this->checkAccess();
$topicId = $this->coerceTopicId($request->getQueryParam('topicId'));
$kind = $request->getQueryParam('kind');
$limit = $request->getQueryParam('limit');
$limitInt = ($limit !== null && is_numeric($limit)) ? (int) $limit : 200;
return $this->getService()->listAdminSources($topicId, $kind, $limitInt);
}
public function postActionUpdateSource(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
// Whitelist what we forward — never let arbitrary body fields hit
// upstream's PUT body. Empty strings are explicitly preserved as
// null clearing (the user wiping a date or identifier).
$payload = [];
foreach (['title', 'identifier', 'source_url', 'sourceUrl', 'published_at', 'publishedAt', 'effective_at', 'effectiveAt'] as $k) {
if (property_exists($body, $k)) {
$canon = $k;
if ($k === 'sourceUrl') $canon = 'source_url';
if ($k === 'publishedAt') $canon = 'published_at';
if ($k === 'effectiveAt') $canon = 'effective_at';
$payload[$canon] = $body->$k;
}
}
return $this->getService()->updateAdminSource((int) $id, $payload);
}
public function postActionDeleteSource(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->deleteAdminSource((int) $id);
}
public function postActionReingestSource(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->reingestAdminSource(
(int) $id,
(string) $this->user->get('userName')
);
}
// ── Phase 4: topic CRUD (Task #15) ──────────────────────────────────────
public function getActionAdminTopics(Request $request, Response $response): array
{
$this->checkAccess();
return $this->getService()->listAdminTopics();
}
public function postActionCreateTopic(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
if (empty($body->slug) || empty($body->name)) {
throw new BadRequest('slug and name are required.');
}
return $this->getService()->createAdminTopic([
'slug' => trim((string) $body->slug),
'name' => trim((string) $body->name),
'description' => isset($body->description) ? trim((string) $body->description) : null,
'system_prompt_addendum' => $body->system_prompt_addendum ?? $body->systemPromptAddendum ?? null,
'is_active' => isset($body->is_active) ? (bool) $body->is_active : true,
]);
}
public function postActionUpdateTopic(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
$payload = [];
foreach (['name', 'description', 'system_prompt_addendum', 'systemPromptAddendum', 'is_active', 'isActive'] as $k) {
if (property_exists($body, $k)) {
$canon = $k;
if ($k === 'systemPromptAddendum') $canon = 'system_prompt_addendum';
if ($k === 'isActive') $canon = 'is_active';
$payload[$canon] = $body->$k;
}
}
return $this->getService()->updateAdminTopic((int) $id, $payload);
}
public function postActionDeleteTopic(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->deleteAdminTopic((int) $id);
}
// ── Phase 6 (v0.8.0): bulk upload + AI classifier + labels ──────────────
public function postActionUploadBatch(Request $request, Response $response): array
{
$this->checkAccess();
// Multi-file: $_FILES['files'] is an array-of-arrays in PHP when
// the form submits files[] repeated. Normalize per-file.
$rawFiles = $_FILES['files'] ?? null;
if (!$rawFiles || !is_array($rawFiles['tmp_name'] ?? null)) {
throw new BadRequest('No files uploaded (form field must be `files[]`).');
}
$files = [];
$count = count($rawFiles['tmp_name']);
for ($i = 0; $i < $count; $i++) {
$err = $rawFiles['error'][$i] ?? UPLOAD_ERR_NO_FILE;
$tmp = $rawFiles['tmp_name'][$i] ?? '';
if ($err !== UPLOAD_ERR_OK || !$tmp || !is_uploaded_file($tmp)) {
continue; // server-side filter; client filters too
}
$files[] = [
'tmp_name' => $tmp,
'name' => (string) ($rawFiles['name'][$i] ?? 'upload'),
'type' => (string) ($rawFiles['type'][$i] ?? 'application/octet-stream'),
'size' => (int) ($rawFiles['size'][$i] ?? 0),
];
}
if (!$files) {
throw new BadRequest('No valid files in upload.');
}
$kind = $_POST['kind'] ?? null;
if (!in_array($kind, ['law', 'regulation', 'circular', 'caselaw', 'tool'], true)) {
throw new BadRequest('kind must be one of: law, regulation, circular, caselaw, tool.');
}
$topicId = $this->coerceTopicId($_POST['topicId'] ?? $_POST['topic_id'] ?? null);
if ($topicId === null) {
throw new BadRequest('topicId is required.');
}
return $this->getService()->uploadBatch(
$files,
(string) $kind,
$topicId,
(string) $this->user->get('userName'),
);
}
public function getActionBatch(Request $request, Response $response): array
{
$this->checkAccess();
$batchId = $request->getQueryParam('batchId');
if (!$batchId) {
throw new BadRequest('batchId is required.');
}
return $this->getService()->getBatch((string) $batchId);
}
public function getActionPendingBatches(Request $request, Response $response): array
{
$this->checkAccess();
$limit = (int) ($request->getQueryParam('limit') ?? 50);
if ($limit < 1) $limit = 1;
if ($limit > 200) $limit = 200;
return $this->getService()->listPendingBatches($limit);
}
public function postActionCommitJob(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
$kind = $body->kind ?? null;
if (!in_array($kind, ['law', 'regulation', 'circular', 'caselaw', 'tool'], true)) {
throw new BadRequest('kind must be one of: law, regulation, circular, caselaw, tool.');
}
$payload = [
'kind' => $kind,
'title' => isset($body->title) ? trim((string) $body->title) : '',
'identifier' => isset($body->identifier) ? trim((string) $body->identifier) : null,
'source_url' => $body->source_url ?? $body->sourceUrl ?? null,
'published_at' => $body->published_at ?? $body->publishedAt ?? null,
'effective_at' => $body->effective_at ?? $body->effectiveAt ?? null,
'summary' => isset($body->summary) ? trim((string) $body->summary) : null,
'label_slugs' => is_array($body->label_slugs ?? null) ? $body->label_slugs : [],
'new_labels' => is_array($body->new_labels ?? null) ? $body->new_labels : [],
];
return $this->getService()->commitJob(
(int) $id, $payload, (string) $this->user->get('userName')
);
}
public function postActionDiscardJob(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->discardJob(
(int) $id, (string) $this->user->get('userName')
);
}
public function getActionLabels(Request $request, Response $response): array
{
$this->checkAccess();
$topicId = $this->coerceTopicId($request->getQueryParam('topicId'));
$q = $request->getQueryParam('q');
$limit = $request->getQueryParam('limit');
$limitInt = ($limit !== null && is_numeric($limit)) ? (int) $limit : 50;
return $this->getService()->listLabels($topicId, $q, $limitInt);
}
public function postActionCreateLabel(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
if (empty($body->slug) || empty($body->name)) {
throw new BadRequest('slug and name are required.');
}
return $this->getService()->createLabel([
'slug' => trim((string) $body->slug),
'name' => trim((string) $body->name),
'topic_id' => isset($body->topic_id) ? (int) $body->topic_id : null,
], (string) $this->user->get('userName'));
}
public function postActionMergeLabels(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
$intoId = $body->into_label_id ?? $body->intoLabelId ?? null;
if (!$id || !is_numeric($id) || !$intoId || !is_numeric($intoId)) {
throw new BadRequest('id and into_label_id (numeric) are required.');
}
return $this->getService()->mergeLabels((int) $id, (int) $intoId);
}
public function postActionDeleteLabel(Request $request, Response $response): array
{
$this->checkAccess();
$body = $request->getParsedBody();
$id = $body->id ?? null;
if (!$id || !is_numeric($id)) {
throw new BadRequest('id (numeric) is required.');
}
return $this->getService()->deleteLabel((int) $id);
}
}
@@ -0,0 +1,140 @@
<?php
namespace Espo\Modules\KnowledgeBase\EntryPoints;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\EntryPoint\EntryPoint;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\InjectableFactory;
use Espo\Entities\User;
use Espo\Modules\KnowledgeBase\Services\KnowledgeBaseService;
/**
* Streams Server-Sent Events from shira-hermes /kb/ask/stream to the
* browser's EventSource. The browser opens this with a GET (EventSource
* has no POST), passes the question via ?message=, and we forward it
* to shira-hermes with the firm-wide API key — the credential never
* leaves the EspoCRM server.
*
* Response is text/event-stream with no buffering. We bypass EspoCRM's
* Response wrapper entirely (echo + flush + exit) because the framework
* is wired for buffered JSON responses, not infinite streams.
*
* Access: `?entryPoint=KnowledgeBaseAskStream&message=<urlencoded>`
*/
class KnowledgeBaseAskStream implements EntryPoint
{
public function __construct(
private InjectableFactory $injectableFactory,
private User $user,
) {}
public function run(Request $request, Response $response): void
{
if ($this->user->isPortal()) {
throw new Forbidden('Portal users have no KB access.');
}
$message = $request->getQueryParam('message');
if (!is_string($message) || trim($message) === '') {
throw new BadRequest('message (string) is required.');
}
if (strlen($message) > 2000) {
throw new BadRequest('message is too long.');
}
// Optional topic scope. EventSource is GET-only so the client passes
// it via ?topicId=N; we forward it as topic_id in the JSON body to
// /kb/ask/stream. Bad ints just become null and the upstream falls
// back to the lowest active topic.
$topicIdRaw = $request->getQueryParam('topicId');
$topicId = (is_string($topicIdRaw) && is_numeric($topicIdRaw))
? (int) $topicIdRaw : null;
$service = $this->injectableFactory->create(KnowledgeBaseService::class);
try {
$upstreamUrl = $service->getStreamingUrl('/kb/ask/stream');
$apiKey = $service->getStreamingApiKey();
} catch (\Throwable $e) {
throw new Error('SmartAssistant integration is not configured: ' . $e->getMessage());
}
// Disable PHP/Apache output buffering and compression so each SSE
// event flushes to the wire as soon as it arrives from upstream.
// Order matters: clean any open buffers BEFORE setting headers.
while (ob_get_level() > 0) {
@ob_end_clean();
}
@ini_set('zlib.output_compression', 'Off');
@ini_set('output_buffering', 'Off');
@ini_set('implicit_flush', '1');
if (function_exists('apache_setenv')) {
@apache_setenv('no-gzip', '1');
}
ignore_user_abort(false);
@set_time_limit(300);
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache, no-transform');
header('X-Accel-Buffering: no');
header('Connection: keep-alive');
// Defense in depth: same locked-down CSP we use for the PDF entry.
header("Content-Security-Policy: default-src 'self'");
$payloadArr = ['message' => $message];
if ($topicId !== null) {
$payloadArr['topic_id'] = $topicId;
}
$payload = json_encode($payloadArr, JSON_UNESCAPED_UNICODE);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $upstreamUrl,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: text/event-stream',
'X-Api-Key: ' . $apiKey,
],
CURLOPT_RETURNTRANSFER => false,
CURLOPT_BUFFERSIZE => 1024,
CURLOPT_TIMEOUT => 300,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_WRITEFUNCTION => function ($ch, $data) {
if (connection_aborted()) {
// Browser closed the EventSource — bail so cURL stops.
return -1;
}
echo $data;
@ob_flush();
@flush();
return strlen($data);
},
]);
$ok = curl_exec($ch);
$errno = curl_errno($ch);
$errmsg = curl_error($ch);
curl_close($ch);
if (!$ok && $errno !== 23 /* aborted by callback */) {
// Best effort: if upstream errored before any data was
// flushed, surface a final SSE error event so the client
// doesn't silently spin.
echo "data: " . json_encode(
['type' => 'error', 'message' => 'upstream: ' . $errmsg],
JSON_UNESCAPED_UNICODE,
) . "\n\n";
@ob_flush();
@flush();
}
// We've fully written the response. Bypass EspoCRM's Response
// emit() to avoid double-headers / extra buffering.
exit;
}
}
@@ -1,5 +1,8 @@
{
"KnowledgeBasePdf": {
"className": "Espo\\Modules\\KnowledgeBase\\EntryPoints\\KnowledgeBasePdf"
},
"KnowledgeBaseAskStream": {
"className": "Espo\\Modules\\KnowledgeBase\\EntryPoints\\KnowledgeBaseAskStream"
}
}
@@ -1,4 +1,12 @@
[
{
"route": "/KnowledgeBase/action/topics",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "topics"
}
},
{
"route": "/KnowledgeBase/action/search",
"method": "post",
@@ -30,5 +38,165 @@
"controller": "KnowledgeBase",
"action": "ask"
}
},
{
"route": "/KnowledgeBase/action/upload",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "upload"
}
},
{
"route": "/KnowledgeBase/action/jobs",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "jobs"
}
},
{
"route": "/KnowledgeBase/action/job",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "job"
}
},
{
"route": "/KnowledgeBase/action/adminSources",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "adminSources"
}
},
{
"route": "/KnowledgeBase/action/updateSource",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "updateSource"
}
},
{
"route": "/KnowledgeBase/action/deleteSource",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "deleteSource"
}
},
{
"route": "/KnowledgeBase/action/reingestSource",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "reingestSource"
}
},
{
"route": "/KnowledgeBase/action/adminTopics",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "adminTopics"
}
},
{
"route": "/KnowledgeBase/action/createTopic",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "createTopic"
}
},
{
"route": "/KnowledgeBase/action/updateTopic",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "updateTopic"
}
},
{
"route": "/KnowledgeBase/action/deleteTopic",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "deleteTopic"
}
},
{
"route": "/KnowledgeBase/action/uploadBatch",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "uploadBatch"
}
},
{
"route": "/KnowledgeBase/action/batch",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "batch"
}
},
{
"route": "/KnowledgeBase/action/pendingBatches",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "pendingBatches"
}
},
{
"route": "/KnowledgeBase/action/commitJob",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "commitJob"
}
},
{
"route": "/KnowledgeBase/action/discardJob",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "discardJob"
}
},
{
"route": "/KnowledgeBase/action/labels",
"method": "get",
"params": {
"controller": "KnowledgeBase",
"action": "labels"
}
},
{
"route": "/KnowledgeBase/action/createLabel",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "createLabel"
}
},
{
"route": "/KnowledgeBase/action/mergeLabels",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "mergeLabels"
}
},
{
"route": "/KnowledgeBase/action/deleteLabel",
"method": "post",
"params": {
"controller": "KnowledgeBase",
"action": "deleteLabel"
}
}
]
@@ -29,37 +29,440 @@ class KnowledgeBaseService
$this->log = $log;
}
public function search(string $query, string $kind, int $topK): array
public function listTopics(): array
{
return $this->get('/kb/topics');
}
public function search(string $query, string $kind, int $topK, ?int $topicId = null): array
{
$topK = max(1, min(15, $topK));
if (!in_array($kind, ['any', 'law', 'regulation', 'circular'], true)) {
if (!in_array($kind, ['any', 'law', 'regulation', 'circular', 'caselaw'], true)) {
$kind = 'any';
}
return $this->post('/kb/search', [
$payload = [
'query' => $query,
'kind' => $kind,
'top_k' => $topK,
];
if ($topicId !== null) {
$payload['topic_id'] = $topicId;
}
return $this->post('/kb/search', $payload);
}
public function listSources(?int $topicId = null): array
{
$path = '/kb/sources';
if ($topicId !== null) {
$path .= '?topic_id=' . rawurlencode((string) $topicId);
}
return $this->get($path);
}
public function sourceChunks(int $sourceId, ?int $around = null, int $ctx = 2): array
{
$path = '/kb/source/' . $sourceId . '/chunks';
if ($around !== null) {
$path .= '?around=' . $around . '&ctx=' . $ctx;
}
return $this->get($path);
}
/**
* Phase 2: async upload to /admin/kb/upload. Forwards the temp-uploaded
* file via cURL multipart and the EspoCRM username as `X-User-Name`
* so shira-hermes can record who uploaded what.
*
* @return array{job_id:int, status:string}
*/
public function uploadFile(
string $tmpPath,
string $filename,
string $kind,
int $topicId,
array $metadata,
string $username
): array {
if (!is_readable($tmpPath)) {
throw new Error('Uploaded file is not readable on disk.');
}
if (!in_array($kind, ['law', 'regulation', 'circular', 'caselaw'], true)) {
throw new BadRequest('kind must be one of: law, regulation, circular, caselaw.');
}
$url = $this->getBaseUrl() . '/admin/kb/upload';
$apiKey = $this->getApiKey();
if (!$apiKey) {
throw new Error('SmartAssistant API key is not configured.');
}
// Build the multipart form. CURLOPT_POSTFIELDS as an array makes
// cURL set the multipart Content-Type with a generated boundary.
$fields = [
'kind' => $kind,
'topic_id' => (string) $topicId,
'file' => new \CURLFile($tmpPath, $this->guessMime($filename), $filename),
];
foreach (['title', 'identifier', 'published_at', 'effective_at', 'source_url'] as $k) {
$val = $metadata[$k] ?? '';
if ($val !== '' && $val !== null) {
$fields[$k] = (string) $val;
}
}
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'X-Api-Key: ' . $apiKey,
'X-User-Name: ' . $username,
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_CONNECTTIMEOUT => 10,
]);
$body = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
$this->log->error("KnowledgeBase: upload transport error: {$err}");
throw new Error("Failed to reach Knowledge Base: {$err}");
}
if ($httpCode === 413) {
throw new BadRequest('File too large (max 50MB).');
}
if ($httpCode >= 400 && $httpCode < 500) {
$detail = $this->decodeDetail($body) ?: 'Bad request';
throw new BadRequest($detail);
}
if ($httpCode < 200 || $httpCode >= 300) {
$this->log->error("KnowledgeBase: upload HTTP {$httpCode}: {$body}");
throw new Error("Knowledge Base returned HTTP {$httpCode}");
}
$decoded = json_decode((string) $body, true);
if (!is_array($decoded) || !isset($decoded['job_id'])) {
throw new Error('Invalid response from Knowledge Base.');
}
return $decoded;
}
public function listSources(): array
public function listJobs(?int $topicId, ?string $status, int $limit): array
{
return $this->get('/kb/sources');
$limit = max(1, min(200, $limit));
$qs = ['limit' => $limit];
if ($topicId !== null) {
$qs['topic_id'] = $topicId;
}
if ($status !== null && $status !== '') {
$qs['status'] = $status;
}
$path = '/admin/kb/jobs?' . http_build_query($qs);
return $this->get($path);
}
public function sourceChunks(int $sourceId): array
public function getJob(int $jobId): array
{
return $this->get('/kb/source/' . $sourceId . '/chunks');
return $this->get('/admin/kb/jobs/' . $jobId);
}
public function ask(string $message, ?string $conversationId, array $history): array
// ── Phase 3: admin source management (Task #14) ─────────────────────────
public function listAdminSources(?int $topicId, ?string $kind, int $limit): array
{
return $this->post('/kb/ask', [
$limit = max(1, min(500, $limit));
$qs = ['limit' => $limit];
if ($topicId !== null) $qs['topic_id'] = $topicId;
if ($kind !== null && $kind !== '') $qs['kind'] = $kind;
return $this->get('/admin/kb/sources?' . http_build_query($qs));
}
public function updateAdminSource(int $sourceId, array $fields): array
{
return $this->request('PUT', '/admin/kb/sources/' . $sourceId, $fields);
}
public function deleteAdminSource(int $sourceId): array
{
return $this->request('DELETE', '/admin/kb/sources/' . $sourceId, null);
}
public function reingestAdminSource(int $sourceId, string $username): array
{
// Re-ingest needs the user identity for audit; piggyback on the
// X-User-Name header that the upload route already understands.
return $this->postWithUser(
'/admin/kb/sources/' . $sourceId . '/reingest',
null,
$username
);
}
// ── Phase 4: topic CRUD (Task #15) ──────────────────────────────────────
public function listAdminTopics(): array
{
return $this->get('/admin/kb/topics');
}
public function createAdminTopic(array $payload): array
{
return $this->request('POST', '/admin/kb/topics', $payload);
}
public function updateAdminTopic(int $topicId, array $fields): array
{
return $this->request('PUT', '/admin/kb/topics/' . $topicId, $fields);
}
public function deleteAdminTopic(int $topicId): array
{
return $this->request('DELETE', '/admin/kb/topics/' . $topicId, null);
}
// ── Phase 6 (v0.8.0): bulk upload + AI classifier + labels ──────────────
/**
* Multi-file upload. Each file is sent to /admin/kb/upload-batch in
* one multipart POST that repeats the `files` field. shira-hermes
* assigns the batch_id and fires per-file classify tasks.
*
* @param array<int,array{tmp_name:string,name:string,type:string,size:int}> $files
* @return array{batch_id:string, jobs:array<int,mixed>}
*/
public function uploadBatch(array $files, string $kind, int $topicId, string $username): array
{
if (!$files) {
throw new BadRequest('No files in batch.');
}
$url = $this->getBaseUrl() . '/admin/kb/upload-batch';
$apiKey = $this->getApiKey();
if (!$apiKey) {
throw new Error('SmartAssistant API key is not configured.');
}
$fields = [
'kind' => $kind,
'topic_id' => (string) $topicId,
];
// PHP cURL accepts repeated form fields by giving the array under
// a special "[]" suffix syntax — but actually CURLOPT_POSTFIELDS
// only sees the LAST value when the key repeats. Workaround:
// build the multipart body manually so we can repeat `files`.
$boundary = '----shira-hermes-' . bin2hex(random_bytes(8));
$body = '';
foreach ($fields as $k => $v) {
$body .= "--{$boundary}\r\n";
$body .= "Content-Disposition: form-data; name=\"{$k}\"\r\n\r\n";
$body .= $v . "\r\n";
}
foreach ($files as $f) {
$contents = @file_get_contents($f['tmp_name']);
if ($contents === false) {
throw new Error("Failed to read uploaded file: " . $f['name']);
}
$name = addslashes($f['name']);
$type = $f['type'] ?: $this->guessMime($f['name']);
$body .= "--{$boundary}\r\n";
$body .= "Content-Disposition: form-data; name=\"files\"; filename=\"{$name}\"\r\n";
$body .= "Content-Type: {$type}\r\n\r\n";
$body .= $contents . "\r\n";
}
$body .= "--{$boundary}--\r\n";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Accept: application/json',
'Content-Type: multipart/form-data; boundary=' . $boundary,
'X-Api-Key: ' . $apiKey,
'X-User-Name: ' . $username,
],
CURLOPT_RETURNTRANSFER => true,
// Batch upload of e.g. 10×10MB files is dominated by PHP→Python
// network transfer; bump from the single-file 120s.
CURLOPT_TIMEOUT => 300,
CURLOPT_CONNECTTIMEOUT => 10,
]);
$resp = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
$this->log->error("KnowledgeBase: batch upload transport error: {$err}");
throw new Error("Failed to reach Knowledge Base: {$err}");
}
if ($httpCode === 413) {
throw new BadRequest('Total upload too large.');
}
if ($httpCode >= 400 && $httpCode < 500) {
$detail = $this->decodeDetail($resp) ?: 'Bad request';
throw new BadRequest($detail);
}
if ($httpCode < 200 || $httpCode >= 300) {
$this->log->error("KnowledgeBase: batch upload HTTP {$httpCode}: {$resp}");
throw new Error("Knowledge Base returned HTTP {$httpCode}");
}
$decoded = json_decode((string) $resp, true);
if (!is_array($decoded) || !isset($decoded['batch_id'])) {
throw new Error('Invalid response from Knowledge Base.');
}
return $decoded;
}
public function getBatch(string $batchId): array
{
return $this->get('/admin/kb/batch/' . rawurlencode($batchId));
}
public function listPendingBatches(int $limit): array
{
return $this->get('/admin/kb/batches?' . http_build_query(['limit' => $limit]));
}
public function commitJob(int $jobId, array $payload, string $username): array
{
return $this->postWithUser(
'/admin/kb/jobs/' . $jobId . '/commit',
$payload,
$username,
);
}
public function discardJob(int $jobId, string $username): array
{
return $this->postWithUser(
'/admin/kb/jobs/' . $jobId . '/discard',
null,
$username,
);
}
public function listLabels(?int $topicId, ?string $q, int $limit): array
{
$qs = ['limit' => $limit];
if ($topicId !== null) $qs['topic_id'] = $topicId;
if ($q !== null && $q !== '') $qs['q'] = $q;
return $this->get('/admin/kb/labels?' . http_build_query($qs));
}
public function createLabel(array $payload, string $username): array
{
return $this->postWithUser('/admin/kb/labels', $payload, $username);
}
public function mergeLabels(int $labelId, int $intoLabelId): array
{
return $this->request(
'POST',
'/admin/kb/labels/' . $labelId . '/merge',
['into_label_id' => $intoLabelId],
);
}
public function deleteLabel(int $labelId): array
{
return $this->request('DELETE', '/admin/kb/labels/' . $labelId, null);
}
private function postWithUser(string $path, ?array $payload, string $username): array
{
$url = $this->getBaseUrl() . $path;
$apiKey = $this->getApiKey();
$headers = ['Accept: application/json', 'X-User-Name: ' . $username];
if ($apiKey) $headers[] = 'X-Api-Key: ' . $apiKey;
$ch = curl_init($url);
$opts = [
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 180,
CURLOPT_CONNECTTIMEOUT => 10,
];
if ($payload !== null) {
$headers[] = 'Content-Type: application/json';
$opts[CURLOPT_POSTFIELDS] = json_encode($payload);
}
$opts[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($ch, $opts);
$body = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$this->log->error("KnowledgeBase: HTTP error calling {$url}: {$error}");
throw new Error("Failed to reach Knowledge Base: {$error}");
}
if ($httpCode < 200 || $httpCode >= 300) {
$detail = $this->decodeDetail($body) ?: "HTTP {$httpCode}";
if ($httpCode >= 400 && $httpCode < 500) {
throw new BadRequest($detail);
}
throw new Error("Knowledge Base returned HTTP {$httpCode}");
}
$decoded = json_decode($body, true);
if (!is_array($decoded)) {
throw new Error('Invalid JSON from Knowledge Base.');
}
return $decoded;
}
private function guessMime(string $filename): string
{
$lower = strtolower($filename);
if (str_ends_with($lower, '.pdf')) {
return 'application/pdf';
}
if (str_ends_with($lower, '.docx')) {
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
}
if (str_ends_with($lower, '.txt')) {
return 'text/plain';
}
return 'application/octet-stream';
}
private function decodeDetail($body): ?string
{
if (!is_string($body)) {
return null;
}
$decoded = json_decode($body, true);
if (is_array($decoded) && isset($decoded['detail'])) {
return is_string($decoded['detail']) ? $decoded['detail'] : json_encode($decoded['detail']);
}
return null;
}
public function ask(
string $message,
?string $conversationId,
array $history,
?int $topicId = null
): array {
$payload = [
'message' => $message,
'conversation_id' => $conversationId,
'conversation_history' => $history,
]);
];
if ($topicId !== null) {
$payload['topic_id'] = $topicId;
}
return $this->post('/kb/ask', $payload);
}
/**
@@ -136,6 +539,25 @@ class KnowledgeBaseService
return $data->apiKey ?? null;
}
/**
* Public accessors so the streaming EntryPoint can build a cURL
* connection to shira-hermes without going through the JSON request()
* helper (which buffers the whole body).
*/
public function getStreamingUrl(string $path): string
{
return rtrim($this->getBaseUrl(), '/') . $path;
}
public function getStreamingApiKey(): string
{
$key = $this->getApiKey();
if (!$key) {
throw new Error('SmartAssistant API key is not configured.');
}
return $key;
}
private function get(string $path): array
{
return $this->request('GET', $path, null);
@@ -240,6 +662,13 @@ class KnowledgeBaseService
}
if ($httpCode < 200 || $httpCode >= 300) {
$this->log->error("KnowledgeBase: HTTP {$httpCode} from {$url}: {$body}");
// Surface 4xx error detail to the browser as BadRequest so the
// user sees the actual reason (bad slug, duplicate, conflict)
// rather than a generic 500.
if ($httpCode >= 400 && $httpCode < 500) {
$detail = $this->decodeDetail($body) ?: "HTTP {$httpCode}";
throw new BadRequest($detail);
}
throw new Error("Knowledge Base returned HTTP {$httpCode}");
}
$decoded = json_decode($body, true);
+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "KnowledgeBase",
"module": "KnowledgeBase",
"version": "0.1.10",
"version": "0.8.0",
"acceptableVersions": [
">=8.0.0"
],
@@ -10,5 +10,6 @@
],
"releaseDate": "2026-04-25",
"author": "klear",
"description": "Knowledge Base — Israeli National Insurance law, regulations, and circulars. Hybrid search + ask-shira, powered by shira-hermes KB."
"description": "Knowledge Base — Israeli National Insurance law, regulations, and circulars. Hybrid search + ask-shira, powered by shira-hermes KB.",
"displayLabel": "מאגר ידע"
}