Skip to content

feat(agent): Ollama tool-call adapter with parameterized timeouts (fixes #205) - #210

Open
mike-011 wants to merge 130 commits into
VectifyAI:mainfrom
mike-011:feat/ollama-tool-call-loop
Open

mike-011 wants to merge 130 commits into
VectifyAI:mainfrom
mike-011:feat/ollama-tool-call-loop

Conversation

@mike-011

@mike-011 mike-011 commented Jul 29, 2026 •

Copy link
Copy Markdown

Summary

Fixes #205

When using Ollama models with openkb query and openkb chat, the openai-agents SDK tool-calling loop fails in three ways:

  1. LiteLLM prompt injection — ollama/ prefix causes LiteLLM to strip tools and inject them into prompt text with format: json. Model returns tool-call JSON in content instead of tool_calls.
  2. Tool-name hallucination — small models call non-existent tools, causing ModelBehaviorError.
  3. Timeouts — local models take 60-130s per turn; default timeout too short.

Fix

1. Model rewrite: ollama/ to ollama_chat/

Primary fix — LiteLLM uses native Ollama Chat API with tool support.

2. Retry on hallucination

Catches ModelBehaviorError, appends corrective message, retries (configurable, default 3).

3. Parameterized timeouts and retries

New ollama: config block in config.yaml:

ollama:
  timeout: 300
  tool_call_retries: 3

4. drop_params + api_base propagation

Testing

  • 56 adapter unit tests, all passing
  • 1131 total tests, 0 regressions
  • Live E2E: gemma4:12b full tool-loop, 132s

See docs/ollama_tool_call_adapter.md for full documentation.

rejojer and others added 30 commits April 11, 2026 23:45
Add interactive chat REPL with persistent sessions
* Skip lint when knowledge base has no indexed documents
Use rich's Live + Markdown to progressively render LLM responses
in the chat REPL with proper formatting (headings, bold, code
blocks, lists, etc.) instead of raw text output. Falls back to
plain text when --no-color is set. Tool call lines still use
prompt_toolkit styled output.
Apply the same rich Live + Markdown streaming render to `openkb query`
as was added to chat. Falls back to plain text when stdout is not a tty.
- Create a fresh Live instance after each tool call instead of
  stop/start on the same instance, preventing the auto-refresh
  thread from overwriting stdout text with CURSOR_UP sequences
- Respect NO_COLOR env var in query.py (consistent with chat.py)
- Fix print("\n") → print() in chat.py finally block to avoid
  extra blank line when Live is active
Extract core logic from CLI commands into reusable functions
(print_status, print_list, run_lint) so the chat REPL can call
them directly instead of duplicating code. /add uses
asyncio.to_thread since _add_single_file internally calls
asyncio.run which cannot be nested.
- Rename _add_single_file → add_single_file (public API, consistent
  with print_status/print_list/run_lint already being public)
- Add progress counter [i/total] for /add when processing directories
- Move `import asyncio` to module-level imports in chat.py
- Add 12 tests covering all new slash commands in _handle_slash
When users type /add '/path/to file' the quotes were included as
part of the path, causing "Path does not exist" errors. Now single
and double quotes wrapping the argument are stripped.
- Tab on / prefix completes slash commands (/status, /list, etc.)
- Tab after /add completes file paths with expanduser support
- Handles quoted paths (strips leading quote before path completion)
Store prompt history in .openkb/chat_history so users can press
up/down arrows to recall previous inputs across chat sessions.
- Show command descriptions next to completions (e.g. /status → "Show
  knowledge base status")
- Switch completion display to MULTI_COLUMN (zsh-like, listed below
  the prompt instead of a dropdown menu)
- Filter out dotfiles from /add path completion unless the user
  explicitly types a dot prefix (e.g. /add ./. will show dotfiles)
- Restyle completion menu: transparent background, subtle text colors,
  no heavy inverted bar
Disable complete_while_typing so completions only appear on Tab
press. Subsequent Tabs cycle through candidates, like zsh.
Custom key bindings so that:
- Tab with no menu open: trigger completion
- Arrow keys: navigate candidates in the menu
- Tab with menu open: accept current selection and insert
Guard against current_completion being None when the menu is open
but no item is highlighted. Falls back to selecting the first item.
When only one candidate matches, Tab inserts it directly without
requiring arrow key selection first.
Custom Rich Theme: bold headings without color, dark background for
inline code, subtle link/list/blockquote colors. Shared via
_make_rich_console() used by both chat and query.
- Headings: blue (#5fa0e0)
- Code: yellow-ish on dark background
- List bullets: green (#6ac0a0)
- Bold: bright white, italic: light gray
- Paragraph text: light gray for visibility
- Restore underscore in test_add_single_file_calls_helper (accidental
  removal during _add_single_file rename)
- Catch KeyboardInterrupt around _handle_slash so Ctrl-C during /add
  or /lint aborts the command instead of triggering the exit prompt
- Add test for Ctrl-C behavior during slash command execution
- Append closing quote for file completions so quotes stay paired
- Skip closing quote for directory completions to allow continued navigation
- Fallback strip unmatched leading quote in _handle_slash
feat: Add slash commands to chat REPL
Two issues in the Live-based markdown streaming:

1. After a tool call, the new Live instance re-rendered the entire
   response so far because `collected` was never reset. Text before
   and after the tool call would be rendered together as one markdown
   block in the new Live region, with no separator between the two
   parts. Track the current segment separately from the full answer.

2. The tool_call_item handler started a new Live immediately after
   printing the tool line, which then had to be stopped in the text
   handler before the blank line. The empty Live start/stop plus the
   explicit `print()` produced two blank lines. Drop the premature
   start and let the next text delta create the new Live.
The previous approach used rich.markdown.Markdown with a hand-written
Theme. Two problems:
- Rich centers h1/h2 headings in a Panel, which looks out of place in
  chat output.
- The Theme pinned a gray paragraph color (`#d0d0d0`) that overrode
  the terminal's default foreground for every line of assistant text.

Replace with a renderer (openkb/agent/_markdown.py) that parses with
markdown-it-py and maps each token to Rich primitives directly: Text
for inline content, Syntax for code blocks, Group for block stacking.
Plain text, bold, italic, and strikethrough keep the terminal's
default color and only carry style attributes. Headings are left-
aligned (bold, with h1 also italic + underline), list nesting uses
decimal / letters / roman numerals by depth, blockquotes prefix
non-blank lines with a dim vertical bar, tables render as pipes and
dashes, and links emit OSC 8 hyperlinks where applicable.

_make_rich_console loses the Theme (no reason to carry one now) and
_make_markdown wraps the new renderer. query.py imports it from
chat.py instead of constructing Markdown itself.
- Drop eager Live restart after a tool call, mirroring the lazy pattern
  used in chat.py (commit 6815094 applied the fix only to chat.py)
- Start Live inside the try block so a synchronous raise cannot leak it
- Preserve list item indent on multi-line paragraphs and block children
- Render fenced/code blocks inside lists and blockquotes as plain text
  instead of leaking <rich.syntax.Syntax object at ...> repr
- Preserve mailto link text when it differs from the email address
- Hoist MarkdownIt to a module-level singleton instead of rebuilding it
  on every call to render()
- Re-render the Live region only when a text delta contains a newline,
  using the content up to the last newline as the visible snapshot.
  Flush the full segment once before stopping Live around tool calls
  and in the finally block so the trailing partial line is not lost
KylinMountain and others added 25 commits July 1, 2026 15:44
…tifyAI#155)

* perf(mutation): don't snapshot the whole blob store on every add

The serial crash-safe add path (VectifyAI#142) listed `.openkb/files` (the PageIndex
blob store) in both the snapshot path set and `hardlink_dirs`, so every add
hardlinked the entire store into the rollback backup — one `os.link` per
existing blob, plus the matching unlink on commit — a cost that scales with
total KB size, not with the document being added. On a filesystem without
hardlink support (cross-device staging, some Windows / cloud-sync folders)
`_hardlink_or_copy` fell back to a full byte copy of the whole store on
*every* add.

The blob store is append-only by `{doc_id}`: an add only ever creates the new
doc's blob, and that name is assigned during indexing — after the snapshot is
taken. So instead of snapshotting the whole tree up front, register just the
new blob once indexing has run, via `MutationSnapshot.track_new()`, which
records it with no backup and rewrites the active journal so both in-process
rollback and crash recovery remove exactly this doc's artifacts.

Cloud import never writes a local blob, so `.openkb/files` is dropped from its
snapshot entirely (it was pure waste there).

- `MutationSnapshot.track_new(paths)`: register post-snapshot-created paths for
  removal on rollback; persists to the journal for crash recovery.
- add: drop `.openkb/files` from the eager snapshot + `hardlink_dirs`; call
  `track_new(files/*/<doc_id>*)` right after `index_long_document`.
- cloud import: drop `.openkb/files` from `hardlink_dirs`.

Tests: new-blob rollback removes exactly the doc's blob + images subtree and
leaves existing blobs untouched (same inode); track_new persists so
recover_pending_journals cleans a crashed add; `_snapshot_add_paths` no longer
lists `.openkb/files`. Full suite green (pre-existing trafilatura-missing
url_ingest failures aside).

Claude-Session: https://claude.ai/code/session_018WiFnTo1YW9mtw47Fzir9K

* fix(mutation): only track blobs this add created (dedup-hit rollback bug)

Self-review of the previous commit found a regression it introduced: track_new
globbed `.openkb/files/*/<doc_id>*` and registered whatever matched for removal
on rollback. But PageIndex content-dedups — `add_document` returns an EXISTING
doc_id and writes no new blob when the same content is already indexed. If
hashes.json and pageindex.db diverge (e.g. a prior `remove` whose PageIndex
cleanup failed left the row + blob but dropped the hashes.json entry),
re-adding that content makes col.add() return the OLD doc_id, so a subsequent
compile failure would roll back and DELETE that prior document's blob. The old
whole-store hardlink snapshot did not have this bug (a dedup-hit blob shares
the backup inode and is left in place on rollback).

Fix: capture the blob set *before* indexing and register only the paths this
add actually created (set difference), guarded by `if index_result.doc_id`.
That also neutralizes an unexpected empty/falsy doc_id, which would otherwise
glob `*/*` and register — then delete on rollback — the entire blob store.

Tests (tests/test_add_command.py):
- test_long_doc_rollback_removes_only_the_new_blob: a failed long-doc add rolls
  back its own new blob + images subtree while a pre-existing blob survives.
- test_long_doc_dedup_hit_does_not_delete_existing_blob: a dedup hit (existing
  doc_id, no new blob) must not delete the pre-existing blob on rollback —
  verified this test FAILS on the pre-fix code.

Claude-Session: https://claude.ai/code/session_018WiFnTo1YW9mtw47Fzir9K
…golden principles, file-size lint (VectifyAI#159)

* chore: track docs/, ignore only docs/internal/

Flip the gitignore default so public dev docs (AGENTS.md map, golden
principles) can live under docs/, while design/spec history stays local
under docs/internal/.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* docs: add golden principles for agent-first development

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* docs: add AGENTS.md map + CLAUDE.md import pointer

Single source of truth is AGENTS.md; CLAUDE.md imports it so both Codex
and Claude Code load the same map.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* test: enforce 800-line module limit (grandfather existing debt)

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* ci: add ruff+mypy+pytest gate and pin tool config

Add ruff==0.9.7 and mypy==1.15.0 to the dev extra, configure both in
pyproject.toml, and add .github/workflows/ci.yml (pinned action SHAs,
Python 3.12, matching publish.yml style) running ruff check, ruff
format --check, mypy, and pytest on push to main and on PRs.

Config choices to reach a green gate on a codebase with no prior
lint/type config:
- ruff: select = ["E", "F", "I"], ignore E501 (ruff format already
  wraps code; remaining long lines are unsplittable string literals —
  docstrings/help text/prompt templates). openkb/cli.py gets a
  per-file-ignore for E402/I001 because it deliberately interleaves
  imports with side-effecting setup code (warning filters, tracing
  disable, an env var default) that must run in a specific order.
- mypy: lenient starting config (ignore_missing_imports,
  check_untyped_defs=false) plus follow_imports="skip" (a transitive
  pydantic->numpy stub uses PEP 695 `type` syntax that crashes mypy
  under python_version="3.10") and disable_error_code for
  union-attr/var-annotated/arg-type/return-value/operator/type-var/
  dict-item, concentrated almost entirely in agent/compiler.py's
  loosely-typed LLM-JSON handling. Ratcheting these back on is future
  tech debt, not this task.

Also includes real (non-cosmetic) fixes found along the way: removed
unused imports/f-strings/local variables (F401/F541/F841), moved two
accidentally-misplaced imports in agent/linter.py and agent/query.py,
and moved two test-file imports that had drifted mid-file back to the
top (I001) in tests/test_compiler.py and tests/test_generator.py.

Ran `ruff format .` across the repo to establish a formatting
baseline; the bulk of this diff (94 files) is that reformat, verified
cosmetic-only (blank-line-after-docstring, re-wrapping under the new
100-char line-length) via an AST diff against openkb/cli.py, the
largest changed file.

Verified locally (not pushed — CI is not triggered by this commit):
ruff check . && ruff format --check . && mypy openkb && pytest all
exit 0; full suite (914 tests) passes.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* docs: clarify agent/tools.py consumer relationship in AGENTS.md map

chat.py uses the tools indirectly via query.build_chat_agent, not directly.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* test: harden file-size gate (robust root, strict boundary, CR-safe count)

- Resolve the package via openkb.__file__ instead of test-file path math,
  and assert the scan is non-empty, so the gate fails loudly rather than
  going silently vacuous if files move.
- Pass the relativize root explicitly, removing the try/except fallback
  whose pkg-relative keys could never match the repo-relative allowlist.
- Count lines via splitlines() so bare-CR files cannot under-count.
- Flag files AT the limit (n >= limit) to match the documented
  "under 800 lines" contract.
- Reword the failure message so external contributors get an instruction
  they can actually fulfill (tech-debt.md is maintainer-local).

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* chore: scope ruff E501 and mypy suppressions to offending files

- E501 moves from a global ignore to per-file-ignores for the 5 source
  files + 3 test files whose violations are long string literals; every
  other file now gets the 100-column limit enforced.
- The global 8-code mypy disable_error_code becomes per-module overrides
  (compiler, cli, lint, indexer, skill.workspace), restoring full
  checking of those codes for the other 35 modules.
- Add types-PyYAML (exact pin) to the dev extra, eliminating all six
  yaml [import-untyped] suppressions outright.
- Drop check_untyped_defs/warn_unused_ignores lines that restated mypy
  defaults and read as active leniency choices.
- follow_imports = "skip" stays global: experimentally confirmed that a
  scoped override cannot prevent the fatal numpy-stub parse.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* ci: install from uv.lock, add least-privilege token and concurrency

- Replace bare `pip install -e .[dev]` with `uv sync --locked --extra dev`
  so CI installs the exact locked resolution (transitive deps included)
  instead of floating them on every run, honoring the exact-pin
  supply-chain policy. Lock now includes the dev toolchain.
- setup-uv (pinned by SHA, uv 0.10.2) with enable-cache replaces the
  uncached cold pip install.
- Add `permissions: contents: read` and `persist-credentials: false` so
  dependency build code never sees a writable token.
- Add a concurrency group cancelling superseded runs on the same ref.
- Fix the checkout pin comment in both workflows: SHA 692973e3 is
  v4.1.7, not v4.2.2.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* docs: restore docs/ safety net and fix uv sync instruction

- docs/.gitignore: default-closed allowlist so a design doc accidentally
  written outside docs/internal/ cannot be swept into a commit, matching
  the guarantee the old blanket docs/ ignore provided.
- AGENTS.md: `uv sync` alone does not install the dev extra (pytest,
  ruff, mypy); document `uv sync --extra dev`.
- golden-principles: annotate the tech-debt.md reference as
  maintainer-local so external readers don't chase a gitignored path.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* chore: re-ignore examples/docs/ for future test-input drops

The old blanket docs/ ignore matched examples/docs/ at any depth; the
anchored docs/internal/ rule does not. Already-tracked PDFs on main are
unaffected (ignore rules only apply to untracked files).

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg
…ifyAI#160)

Two relative source images with the same basename but different paths
(e.g. a/logo.png and b/logo.png) overwrote each other in
sources/images/<doc>/, collapsing both markdown links onto one file.
Track the destination assigned to each source (so an image referenced
twice is copied once) and suffix genuine basename collisions
(logo.png -> logo_1.png).

Adapted from VectifyAI#122 by @jichaowang02-lang; drops that PR's second commit,
which seeded the taken-name set from the existing images_dir and thereby
broke re-convert idempotency (a changed same-basename image got a fresh
suffix each run, orphaning the old file and churning links).


Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

Co-authored-by: jichao wang <[email protected]>
…uncated LLM output (VectifyAI#161)

* fix(compiler): guard concept/entity generation against malformed & truncated LLM output

Two silent-data-loss bugs in _compile_concepts, both from trusting the
per-page LLM response shape:

- VectifyAI#158: a response returned as a JSON array (e.g. [{...}] or a multi-item
  list) reached .get() on a list and raised AttributeError, which the local
  except (JSONDecodeError, ValueError) did not catch — the page was dropped
  and, because the doc index records it as written, never retried. New
  _parse_page_json unwraps a single-element [{...}] array (recovering the
  common case) and returns None for other wrong shapes so the page is skipped
  cleanly instead of writing the raw JSON as its body.

- VectifyAI#148: a response that hit finish_reason=length was repaired by json_repair
  and written anyway, overwriting an existing concept page with truncated
  content while still reporting [OK]. _warn_if_truncated now reports whether it
  truncated, and the four page-generation calls pass raise_on_truncation=True
  so a truncated response skips the write (existing page preserved). Other
  callers (plan, summary, overview) keep the warn-only behavior.

Closes VectifyAI#158. Closes VectifyAI#148.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg

* refactor(compiler): extract _page_fields + _llm_call_page_async; cover entity/prose paths

Addresses code-review findings on the VectifyAI#158/VectifyAI#148 fix, no behavior change:

- Collapse the four near-identical parse/fallback blocks in the concept and
  entity generation closures into a shared _page_fields() helper, so a future
  edge case is fixed in one place instead of four copies that can drift.
- Add _llm_call_page_async() which hard-codes raise_on_truncation=True, so a
  page-generating call site can't silently forget the truncation guard and
  regress VectifyAI#148.
- Tests: a _page_fields shape unit test (object / single-element-array unwrap /
  wrong-shape skip / non-JSON prose fallback) and an entity-path
  truncation-skip integration test.

Claude-Session: https://claude.ai/code/session_01UtbmJxjtw6FtP8fUXUKVtg
…fyAI#156)

* Add serial add mutation coordinator

* Route serial add paths through coordinator

* fix(cloud-import): resolve final doc name under ingest lock

* test(add): cover coordinator conflict edge cases

* fix(indexer): roll back the PageIndex blob when indexing fails after col.add

Since the add mutation stopped eagerly snapshotting .openkb/files (it registers the new blob via track_new only on success), a blob written by col.add() leaks if index_long_document raises afterward: pageindex.db is rolled back by the snapshot but the blob file is not, and nothing reclaims it. Delete the doc on the failure path so the indexer owns cleanup of a half-applied add, restoring the .openkb/files rollback-surface guarantee.

* fix(cloud-import): surface real error instead of mislabeling snapshot prep

run_add_mutation handles snapshot/body failures itself and returns False, so the broad except only ever catches pre-mutation errors (name resolution, registry read, plan construction). Echo the real exception instead of the old 'Failed to prepare mutation snapshot' label, which hid the cause at DEBUG level.

* style: wrap long lines for ruff E501 (CI gate from VectifyAI#159)

* style: apply ruff format to add_coordinator.py and test_add_command.py

* refactor(cli): drop duplicate _cleanup_staging, reuse coordinator helper

cli._cleanup_staging duplicated add_coordinator._cleanup_staging_dirs (both guard None then shutil.rmtree with ignore_errors). Drop the cli copy and route its two pre-coordinator call sites through the coordinator helper.

* refactor(add_coordinator): drop unused rollback_error_message field

AddMutationPlan.rollback_error_message had zero callers — every construction site (cli.py x2, tests x6) used the default. Remove the field and inline the literal at its single read site.
…ck query/chat (VectifyAI#175) (VectifyAI#177)

* fix(agent): make parallel_tool_calls configurable; fixes Bedrock query/chat (VectifyAI#175)
* feat(indexer): expose pageindex_max_concurrency to cap indexing concurrency

PageIndex fans out one indexing LLM call per structure node; on a large
document that can open a socket per node and exhaust the process
file-descriptor limit ("[Errno 24] Too many open files"). This wires an
OpenKB config knob through to PageIndex's IndexConfig.max_concurrency cap.

- New `pageindex_max_concurrency` KB config key (default None = let PageIndex
  apply its own default).
- indexer forwards it via `_build_index_config` only when set AND the installed
  PageIndex's IndexConfig declares the field, so OpenKB keeps working against a
  pinned PageIndex that predates it (IndexConfig forbids unknown kwargs).

* feat(config): make compile concurrency configurable (closes VectifyAI#173)

Concept/entity generation ran at a hardcoded concurrency of 5
(DEFAULT_COMPILE_CONCURRENCY) with no way to lower it when the LLM provider
rate-limits. Add a `compile_concurrency` config key (default 5) and thread it
through every add / recompile / cloud-import compile call via a shared
`_compile_concurrency` resolver (null / non-positive → the compiler default).

Pairs with `pageindex_max_concurrency` (indexing side) from this PR — both
concurrency knobs are now KB-configurable.

* fix(config): address xhigh code-review findings on the concurrency knobs

- resolve_compile_concurrency moves to config.py (matching resolve_timeout's
  convention) and now rejects bool (bool is an int subclass, so
  `compile_concurrency: true` previously silently became concurrency=1) and
  logs a warning on any malformed value, same as the other resolvers.
- _build_index_config now warns when pageindex_max_concurrency is configured
  but the installed PageIndex doesn't support the field yet, instead of
  silently dropping it with no signal to the user.
- Replaced the tautological test_forwards_max_concurrency_when_supported
  (which branched on the same runtime condition as the code under test, so it
  never exercised the forwarding assertion under CI's pinned PageIndex) with
  fake IndexConfig doubles that make both branches deterministic regardless
  of the installed pageindex version.
- Added a cross-check test pinning DEFAULT_CONFIG["compile_concurrency"]
  against the compiler's own DEFAULT_COMPILE_CONCURRENCY so the two literals
  can't silently drift apart.
- Added an end-to-end test proving index_long_document's own loaded config
  (not just a hand-built dict) reaches PageIndexClient's IndexConfig.
- Hoisted the compile-concurrency resolution out of `recompile --all`'s
  per-document loop (was recomputed every iteration despite being
  loop-invariant).
- Documented both new config.yaml keys in config.yaml.example and
  examples/configuration/README.md (kept in sync).

* refactor(config): unify pageindex_max_concurrency + compile_concurrency into `concurrency`

PageIndex indexing and OpenKB's own concept/entity compilation never run
concurrently with each other for the same document (they're sequential
phases of one add), and both knobs exist for the exact same reason — the
user hit a provider rate limit or an fd ceiling. Splitting them by internal
subsystem leaked OpenKB's architecture into the config surface for no
practical benefit, since a user tuning one for a rate limit would set the
other to the same value anyway.

- Single `concurrency` config key (default null = each stage keeps its own
  built-in default).
- config.resolve_concurrency(config) -> int | None: validates (rejects bool
  and non-positive values with a warning), returns None on unset/invalid —
  no default substitution inside; callers decide what None means for them.
- cli.py's compile call sites: `resolve_concurrency(config) or
  DEFAULT_COMPILE_CONCURRENCY`.
- indexer.py's _build_index_config now routes through resolve_concurrency
  (openkb validates before forwarding to PageIndex, rather than relying
  solely on PageIndex's own future validator) instead of raw config.get.
- This also removes the prior dual-literal-default drift risk entirely:
  there's no second numeric default to keep in sync, since an unset
  `concurrency` simply forwards nothing to PageIndex and lets the compiler
  use its own DEFAULT_COMPILE_CONCURRENCY.
- Updated config.yaml.example and examples/configuration/README.md (kept in
  sync) to the single key.

* build(deps): bump pageindex to 0.3.0.dev2 (ships IndexConfig.max_concurrency)

0.3.0.dev2 is the first published release that declares
IndexConfig.max_concurrency, so `concurrency` in config.yaml now takes
effect for the indexing stage in a normal `pip install` / `uv sync`, not
just against a local editable checkout. Vetted: downloaded the wheel and
confirmed its sha256 matches PyPI (b0cb1f6e…) and that IndexConfig declares
`max_concurrency: int | None` with a positivity field_validator. uv.lock
regenerated via `uv lock --upgrade-package pageindex`.

The runtime `"max_concurrency" in IndexConfig.model_fields` guard in
indexer._build_index_config is now always-true under the pinned dependency,
but is kept as graceful degradation for mismatched local installs.

* refactor(config): keep concurrency out of DEFAULT_CONFIG (align with other optional knobs)

Every other optional tuning knob (timeout, extra_headers, litellm,
entity_types, parallel_tool_calls) is resolved via its resolver's .get()
and lives only in config.yaml.example, not DEFAULT_CONFIG — which holds just
the core keys openkb init writes (model, language, pageindex_threshold).
concurrency was the lone exception; resolve_concurrency already reads it via
.get(), so the DEFAULT_CONFIG entry was redundant. Remove it for consistency.

* build(deps): bump pageindex 0.3.0.dev2 -> 0.3.0.dev3

Vetted: identical Requires-Dist/Requires-Python to dev2; IndexConfig,
PageIndexClient, and IndexConfig.max_concurrency (used by VectifyAI#174) all still
present; wheel/sdist hashes verified against PyPI. uv.lock regenerated via
`uv lock` (change scoped to the pageindex entry). Also aligns the stale
dev1 reference in the config README.

* feat(cli): add --version flag

The CLI group had no way to report its version (`openkb version` / `openkb -v`
both fail). Add `@click.version_option(package_name="openkb")` so `openkb
--version` prints "openkb <version>", read from installed package metadata
(tracks the hatch-vcs-derived version, no hardcoded string).
…yAI#181)

Short-doc source pages live at wiki/sources/<doc>.md but embedded
their images with wiki-root-relative links
(sources/images/<doc>/file.png). Markdown renderers resolve links
relative to the containing file — Obsidian, GitHub, VS Code — so
every image resolved to the non-existent
wiki/sources/sources/images/... and rendered broken.

- New md_image_ref() helper emits note-relative images/<doc>/...
  links, used by the three .md-visible writers
  (convert_pdf_with_images, extract_base64_images,
  copy_relative_images).
- Long-doc JSON page metadata keeps wiki-root-relative paths: it is
  internal, consumed by get_wiki_page_content/read_wiki_image against
  the wiki root. Now documented explicitly in the docstrings.
- read_wiki_image() retries note-relative paths under sources/, so
  agents can pass image paths verbatim as seen in either surface.
- Query/skill-factory prompts and the openkb skill's wiki-schema.md
  updated to describe both path forms.

Existing KBs keep their old-style links (the read_wiki_image fallback
does not cover them in renderers); a migration helper for already
ingested sources pages is left as a follow-up.

Co-authored-by: Aldominguez12 <[email protected]>
* update readme

* add chat slash commands to readme

* update readme
* update readme

* update readme

* update readme

* update readme

* update readme
* feat: add REST API server and Knowledge Workbench web UI

Add a production-ready REST API (FastAPI) and a bundled React single-page
app ("Knowledge Workbench") served at the same origin, so OpenKB can be
driven from the browser, Postman, or other HTTP clients without the CLI.

REST API (openkb/api.py):
- Endpoints under /api/v1: /kbs, /init, /add, /query, /chat,
  /chat/sessions{,/load,/delete}, /list, /status, /lint, /remove,
  /recompile, /watch/{start,stop,status}, /watch/events (SSE)
- Bearer-token auth, SSE streaming for query/chat/add/remove/recompile,
  multipart upload, and KB name resolution via OPENKB_KB_ROOT
- Shared SSE event layer (iter_agent_response_events) reused by query/chat
  so the CLI and API emit identical event streams
- Background file-watcher service (openkb/watch_service.py) for auto-compile

Knowledge Workbench (frontend/, built to web/):
- React + Vite dark three-pane workbench: Overview, Documents, Query,
  Chat, Maintenance, with a live retrieval/reasoning inspector timeline
- Streamed answers, multi-turn chat with persisted sessions, drag-and-drop
  upload with per-file progress, lint/recompile/watch controls
- Markdown via react-markdown + remark-gfm + rehype-highlight

Also: initialize_kb inherits project-root config.yaml and .env (filtering
OPENKB_* server vars) so a KB created from the UI runs out of the box;
POSTMAN collection; README docs.

Co-authored-by: jidechao <[email protected]>

* chore: address PR VectifyAI#150 review — revert config defaults, strip BOM, unvendor web/

- config.yaml.example: restore gpt-5.4 / en (unintentional flip to local
  dev values openai/deepseek-v4-flash / zh)
- openkb/cli.py, tests/test_api.py: remove stray UTF-8 BOM
- web/: stop vendoring the built bundle; add web/ to .gitignore; README
  notes the Workbench UI requires `npm run build` (API-only otherwise)

Refs: PR VectifyAI#150
Co-authored-by: jidechao <[email protected]>

* fix(rest-api): address all PR VectifyAI#150 review feedback (VectifyAI#150)

Must-fix (correctness/data):
- Serialize same-KB mutations with an asyncio.Lock before kb_ingest_lock.
  The ingest lock tracks reentrancy in threading.local, but the event loop
  runs every request on one thread, so concurrent same-KB requests were
  mis-counted as re-entrant and bypassed mutual exclusion. [init/lint --fix/recompile]
- Watcher stop() now joins the worker before clearing state and leaves a
  draining marker, so a restart can no longer orphan an in-flight compile
  and double-ingest raw/. [watch_service.py]
- Extract a shared save_exploration() used by both CLI and REST: strips
  ghost wikilinks, generates a CJK-safe slug (hash fallback), uniquifies
  on collision, and escapes the question for YAML frontmatter. [cli.py]

Should-fix:
- Cap /watch/events SSE with a default timeout and an is_disconnected check.
- Abort the in-flight SSE on component unmount / KB switch (AbortController).
- Force allow_credentials off when CORS origins is a wildcard.
- Constant-time token compare (hmac.compare_digest); the SPA warns when the
  configured API base is cross-origin and non-HTTPS.
- Isolate per-KB LLM credentials via LlmCredentialBundle (dotenv_values, no
  os.environ pollution; a per-request LitellmModel instance).

Regression (introduced by the per-KB bundle isolation above):
- build_run_config_from_bundle passed model=f"litellm/{model}" to LitellmModel,
  but LitellmModel feeds model verbatim to litellm.acompletion, so the prefix
  produced "litellm/openai/deepseek-v4-flash" and litellm rejected it as an
  unknown provider. CLI was unaffected (bundle=None); all REST query/chat failed.

Refactor/cleanup:
- Extract _is_kb_dir; move _setup_llm_key to cli; model_dump() (pydantic v2).
- Drop the hand-maintained openkb-postman.json (OpenAPI is served at /docs).
- Slim README to short subsections + links; move the REST reference and
  Workbench tour to examples/rest-api/README.md.

Frontend:
- Default the UI to English with a zh/en toggle (i18n.jsx).
- index.html lang/title default to English.

Tests: 118 passed (query/api/api_watch/watch_service/per_request_overrides/save_exploration).
Co-authored-by: jidechao <[email protected]>

* fix(rest-api): complete review hardening

Co-authored-by: jidechao <[email protected]>

* fix(rest-api): isolate request configuration

Co-authored-by: jidechao <[email protected]>

* fix(rest-api): harden uploads, streaming, and credential resolution

- Split add-upload handling into a fast reservation (unique-path allocation +
  placeholder, under the per-KB mutation lock) and the body transfer (outside
  the lock), so a large or slow upload no longer blocks lint/recompile/other
  adds on the same KB while same-name uploads stay race-free.
- Persist a query stream's final answer (save + log) before the disconnect
  check, so a client that drops at the last moment does not lose a save=True
  write; only the client-facing SSE frame is skipped. Mirrors the chat stream,
  which records the turn before yielding.
- resolve_credential_bundle now falls back kb-local .env -> process env ->
  global ~/.config/openkb/.env (kb-local wins), so process-env and global-.env
  deployments (Docker/systemd) keep working, still without mutating os.environ.
- Move process-wide setup (load_dotenv/tracing/litellm) into create_app() and
  run via uvicorn factory, so importing the module has no global side effects.
- Return a JSON 404 for unknown /api/* paths instead of the SPA's index.html.
- watch/stop reports the real post-stop status; the watcher resolves a per-KB
  credential bundle at start and threads it through background ingests.
- Tests: update _add_for_api mocks for the bundle arg and cover the credential
  fallback. Add fastapi/uvicorn/python-multipart (api extra) and httpx (dev).

* fix(workbench): reset view state on KB switch, relax connection gating

- Chat and Query clear their message list (and Chat its session) when the
  active KB changes, so stale answers from the previous KB do not linger.
- hasConnection() again treats a configured token as connected; a cross-origin
  non-HTTPS base is advisory only (checkBaseSafety warns before each request)
  and no longer blocks LAN/dev http:// endpoints from connecting.

* feat(rest-api): ship the Workbench UI in the published package

Previously the bundled web UI existed only after a source-tree
`cd frontend && npm run build`, so `pip install "openkb[api]"` from PyPI served
no UI (`/` 404'd). Build the SPA into the package and ship it in the wheel so
the Workbench is available straight from a normal install, while keeping the
generated bundle out of git (the unvendor decision stands):

- Vite builds into openkb/web (was ../web), so the bundle lives inside the
  package rather than a top-level dir that would pollute site-packages.
- hatchling `artifacts` force-includes openkb/web in the sdist and wheel even
  though it stays git-ignored, so the built UI ships without committing
  generated JS. The build still succeeds when the bundle is absent (API-only).
- publish.yml builds the frontend (npm ci && npm run build) before packaging.
- _mount_web_ui resolves the bundle next to the module (openkb/web), covering
  installed wheels and source checkouts alike.
- README: install via `pip install "openkb[api]"` + `openkb-api`; the
  from-source npm build is now just a dev note. Trim the overlong Workbench
  feature bullet to match its siblings.

The UI is "optional" via the [api] extra (server deps) — no second package
needed; the ~520KB static bundle is inert without the server.

Verified locally: `uv build` includes openkb/web in both sdist and wheel, and
the server serves index.html + assets at /.

* feat(rest-api): make bearer auth opt-in for zero-config local use

The Workbench is a local-first tool: it should start and open in the browser
with no configuration. Auth was mandatory (require_bearer_token returned 500
when OPENKB_API_TOKEN was unset), and the SPA popped a Connection dialog
demanding a token before it would even talk to its own same-origin API.

Flip auth to opt-in:
- require_bearer_token: with no OPENKB_API_TOKEN configured the API is open
  (the local default). Set it and every request must carry the bearer token;
  a missing/wrong one is 401.
- main(): warn on startup when bound to a non-loopback host without a token,
  so an exposed server can't be silently world-open.
- Frontend: don't prompt on load. The SPA calls the same-origin API directly;
  the Connection dialog opens only reactively when a request 401s (i.e. the
  server has a token configured) via the existing openkb:unauthorized event.
- Tests: replace the old "no token -> 500" assertions (test_api / test_api_watch)
  with the new contract — no token -> requests allowed; token set -> 401 when
  the header is missing.

A deployer who exposes the server sets OPENKB_API_TOKEN to require auth.

* docs(rest-api): align README + guide with packaged UI and opt-in auth

- Install via `pip install "openkb[api]"` and run `openkb-api` with zero config;
  the bundled UI now ships in the wheel, so the npm build is only a
  source-checkout note. Drop the stale "no build -> / returns 404" claim.
- Document auth as opt-in in the guide's Authentication section: OPENKB_API_TOKEN
  unset -> open (local default), set -> bearer token required (else 401), with
  an "exposing the server" warning. Fix the stale "OPENKB_API_TOKEN is required"
  line and the "500 when not configured" status code.
- Note the Workbench connects to the local API with no prompt when no token is
  set (the Connection dialog is now only for a configured token / remote base).

* ci: build the Workbench frontend on PRs

Add a `web` job (npm ci && npm run build) so a broken frontend — vite/config
error, stale package-lock, JS error — is caught at PR time instead of only in
publish.yml after a release tag is pushed. Mirrors the release build step and
its pinned action SHAs.

* fix(rest-api): warn about disabled auth at server startup, not just the CLI

The exposed-without-token warning lived only in main(), so a non-CLI launch
(uvicorn/gunicorn --factory) that binds a public interface without a token got
a silently world-open API with no warning. Move it into create_app()'s lifespan
startup so it fires for every launch path. create_app() can't see the bind host
under a factory launch, so the check is host-agnostic (warn whenever no token is
configured) — a single calm log line, harmless on loopback, and silent in the
unit suite (tests don't enter the TestClient context manager, so lifespan never
runs there).

* chore: fix lint, format, and type errors so the PR passes CI

PR VectifyAI#150's CI had never actually run — fork-PR workflows sat in `action_required`
pending maintainer approval — so several failures accumulated undetected across
the PR's own new code:

- ruff E402: hoist mid-file imports to the top of tests/test_api.py.
- ruff format: reformat 6 PR-touched files (cli.py, agent/chat.py,
  agent/compiler.py, watch_service.py, tests/test_remove.py,
  tests/test_watch_service.py) — deterministic, no logic change.
- mypy (cli.py iter_recompile): assert the guarded non-None doc_name before
  _resolve_doc_identifier, and annotate the per-doc result dict as
  dict[str, Any] so the float `elapsed` entries type-check.

All four CI steps (ruff check ., ruff format --check ., mypy openkb, pytest)
pass locally; 1102 tests green.

* ci: install the api extra so REST tests can import fastapi

The check job ran `uv sync --locked --extra dev`, which omits fastapi/uvicorn
(the `api` extra), so tests/test_api*.py failed at collection with
ModuleNotFoundError: fastapi. Add --extra api to the sync.

* fix(config): derive global-config lock path from GLOBAL_CONFIG_DIR

_with_global_config_lock() mkdir'd GLOBAL_CONFIG_DIR but opened the lock via the
import-time GLOBAL_CONFIG_LOCK_PATH constant, so the two diverged whenever
GLOBAL_CONFIG_DIR was redirected. Tests monkeypatch GLOBAL_CONFIG_DIR to a tmp
dir but not the lock constant, so the lock opened the real ~/.config/openkb/
global.lock — present on a dev machine, absent on a fresh CI runner — making the
/api/v1/init tests crash with FileNotFoundError (500) only in CI. Derive the
lock path from GLOBAL_CONFIG_DIR at call time so it co-locates with the dir
just created.

---------

Co-authored-by: mountain <[email protected]>
…ting backend (VectifyAI#189)

* feat(workbench): scaffold new Tailwind/shadcn/TypeScript frontend

* feat(workbench): wire KB list and Home stats to real /api/v1/kbs

* feat(api): add /api/v1/graph and /api/v1/page endpoints

* feat(workbench): wire KbDetail browse tab to real page/list endpoints

* feat(workbench): wire real streaming query/chat with citation page lookup

* fix(workbench): prevent session-adopting navigate from clobbering live chat state

* refactor(generator): thread optional credential bundle through skill/deck generation

* feat(api): add /api/v1/deck and /api/v1/skill generate/list/download endpoints

* feat(workbench): wire deck/skill/graph slash commands to real generator endpoints

* feat(workbench): wire KbDetail sources and jobs tabs to real add/watch/recompile/lint

* feat(api): add GET/PATCH /api/v1/kb/config with merge-patch semantics

* feat(workbench): wire Settings page to real kb/config endpoint

* feat(workbench): shell-aware TitleBar, 401 handling, final Kimi-adoption pass

* fix(api): atomic .env write for credential rotation; lock in path-traversal tests

* feat(workbench): Apple token layer + theming infrastructure + motion

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): ambient-ground shell; remove browser title strip

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): glass sidebar, larger nav font, bottom settings/version cluster, theme toggle

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): reflow Home to bottom-pinned input with sessions above and tagline footer

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(api): surface entities in /api/v1/list

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): KbDetail per-type tabs with entities + pagination + materials

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): tokenize chat surfaces + ChatInput; spring-animate artifact preview

Migrate ChatInput, ChatSession, and ArtifactCard off hardcoded
bg-white/bg-blue-*/border-black/text-neutral-* colors onto the Apple
token layer (.glass/.glass-2, border-[hsl(var(--glass-border))],
bg-accent-brand, text-foreground/text-muted-foreground). Fixes the
shared ChatInput box + slash-command menu rendering white against the
dark shell (flagged in Task 4). Source chips gain active:scale-[0.97]
+ transition duration-fast ease-out-apple press feedback.

Wrap the deck preview panel in motion AnimatePresence + a critically-
damped spring (bounce:0, 0.24s), degrading to an opacity-only cross-fade
under prefers-reduced-motion via useReducedMotion. The sandboxed iframe
(sandbox=allow-scripts, src={previewUrl} blob URL) and its blob-URL
revocation lifecycle are unchanged; the spring only wraps the panel.

Slash-command logic, streaming, citations, and session handling are
untouched. Semantic deck/skill/graph accent colors are preserved.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): tokenize Settings and connection dialog

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): materialize KbList; final token sweep + motion review

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): compile the Apple easing utility; scope KbList transition + press feedback

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): dark-mode variants for KbDetail status colors

KbDetail kept light-only semantic status colors (bg-*-50 / text-*-500 /
text-*-600) with no dark: pair, so red error cards and emerald/red status
pills rendered as bright light patches in dark mode. Add dark: variants
only (no light-mode, layout, or logic changes), matching the app-wide
pattern from ChatSession.tsx (red) and ArtifactCard.tsx StatusBadge
(emerald): dark:bg-red-500/10 dark:border-red-500/25 dark:text-red-400 and
dark:bg-emerald-500/10 dark:text-emerald-400.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(api): graph HTML endpoint + extract graph endpoints to APIRouter

* feat(workbench): ArtifactPanel docked component + getGraphBlobUrl client

* fix(workbench): clamp artifact-panel width to viewport + clean up resize listeners on unmount

* feat(workbench): open deck/graph in a docked artifact panel (compact in-chat cards)

* feat(workbench): connector cards → GitHub demand-vote (shared component)

* fix(workbench): dedupe artifact-panel switcher by identity (no duplicate React keys)

* feat(api): GET /api/v1/meta exposing the real openkb version

* feat(workbench): render fenced code blocks + Mermaid diagrams in markdown

* feat(workbench): Settings 关于 tab (real version + intro + links)

* refactor(workbench): declutter sidebar bottom, icon theme toggle, drop redundant KB badge

* feat(workbench): KB Overview stat cards + default to index.md wiki home

* refactor(workbench): stop promoting Obsidian in-app (keep the plain-Markdown/no-lock-in message)

* refactor(workbench): drop redundant /ask command (default chat already answers from the wiki)

* feat(api): give the Workbench chat agent write_file (delegate to build_chat_agent)

* feat(api): emit an artifact SSE event when chat write_file produces output/**.html

* feat(api): GET /api/v1/output serves path-validated output/**.html (new router)

* fix(api): narrow GET /api/v1/output to output/-only (least privilege for the HTML sink)

* feat(workbench): file Artifact variant + getOutputBlobUrl + panel wiring

* feat(workbench): surface conversationally-written output/**.html as openable cards

Fold the artifact SSE event (kind:"file", path, name) into ChatTurnState
so a normal chat turn can carry files the agent wrote via write_file.
AssistantMessage renders an ArtifactCard per file (kb attached by the
caller, since the event itself carries no kb), reusing the existing
setPanelArtifact/ArtifactPanel wiring deck/skill/graph already use.
viewableArtifacts folds these into the panel switcher too.

* fix(workbench): capture kb per file-artifact at fold time (survive mid-session KB switch)

* feat(config): add resolve_effective_config three-layer resolver

* refactor(runtime): compile/index core resolves config via resolve_effective_config

* test(config): make compile-core global-config test exercise convert_document (was vacuous)

* refactor(runtime): chat/query/linter resolve config via resolve_effective_config

* refactor(runtime): REST query/deck/skill/session resolve config via resolve_effective_config

* refactor(runtime): migrate 12 CLI compile/query/chat/lint sites to resolve_effective_config

* feat(api): kb/config PATCH null removes key (RFC 7386 revert-to-inherited)

* fix(api): kb/config PATCH writes only explicit KB keys (don't materialize defaults, preserve inheritance)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(api): kb/config GET reports effective values + inheritance metadata

* feat(api): add GET/PATCH /api/v1/config global-defaults endpoint

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(api): hold global-config lock across the whole PATCH read-modify-write (protect KB registry)

* feat(web): global-config API client + KbConfig inheritance fields

* refactor(web): PageTypeTabs -> PageList with fixed type prop

Drop PageList's internal Concepts/Entities/Summaries/Reports segmented
control; the type is now a required prop set by the caller (Task 13 will
drive it from the active Overview card). Pagination (PAGE_SIZE=50),
pathFor(), and the onOpen(path)/activePath interface are preserved
verbatim.

KbDetail.tsx is updated minimally to import PageList and pass a fixed
type="concepts" stopgap so the build stays green; full card-nav wiring
lands in Task 13.

* feat(web): KbOverviewCards become six-card nav with spring layoutId indicator

* feat(web): KbSettingsSheet (config inherit/override + moved maintenance) + scroll-edge util

* fix(web): threshold override rejects non-integer input (no silent revert); critically-damped sheet spring

* feat(web): KbDetail card-nav — cards are the tab bar, settings sheet, spring switch

* fix(web): screen-adaptive content widths + clickable wiki-links in the reader

* feat(web): global top-right theme chrome cluster + MotionConfig root

* fix(web): reserve top-right chrome lane so KbList/KbDetail controls clear the theme pill (+ room for i18n)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): global Settings edits global defaults (KB picker + credentials removed)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* refactor(web): drop dead `large` prop; Home input is 2 rows

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(web): parse [[target|alias]] wikilinks; test-guard global scalar-key whitelist parity

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): i18n infra (react-i18next) + language switcher + common namespace

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): i18n home namespace

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): i18n kbList namespace

* feat(web): i18n kb namespace (KbDetail + overview cards + page list)

* feat(web): i18n kbSettings namespace (per-KB gear sheet + maintenance)

* feat(web): i18n settings namespace (Settings + About)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): i18n chat namespace (ChatSession + ChatInput)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): i18n artifacts namespace (ArtifactCard + ArtifactPanel)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* chore(web): i18n full-sweep fixes + leftover-CJK guard

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(web): KB reader fills the window on large screens (generous cap + padding)

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(web): a11y — KbSettingsSheet modal dialog semantics + ArtifactPanel labeled region

KbSettingsSheet (modal): compose @radix-ui/react-dialog around the existing
motion.aside via asChild + forceMount so AnimatePresence keeps the D-era spring
and reduced-motion. Radix supplies focus trap, initial focus, and Escape-close;
add aria-modal + aria-labelledby (Dialog.Title on the heading) explicitly, and
drive focus return to the opening gear via on{Open,Close}AutoFocus (we open from
external state, so Radix's own triggerRef is null and would drop focus to body).
Scrim/backdrop-dismiss, config inherit/override, watch/recompile/lint, threshold
validation and all i18n preserved.

ArtifactPanel (non-modal docked): add role=complementary + aria-label (active
artifact label), aria-label on the header controls, and a one-time initial focus
to the panel on open. No focus trap and no background inert — Tab still flows out
to the chat. iframe/blob/new-tab/download, switcher, motion and i18n preserved.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): wire New knowledge base create flow + de-dup entries

The KB list page had two "New knowledge base" controls (top-right button +
in-grid dashed card) and NEITHER had an onClick — the frontend never wired KB
creation. The sidebar's "+" was a third dead trigger.

- add createKb() -> POST /api/v1/init (api/kb.ts)
- new CreateKbDialog: Radix modal (Dialog.Trigger asChild for focus-trap/Escape/
  focus-return), name-only field (model/creds inherit global defaults), inline
  backend-error surfacing, success -> navigate to the new KB
- KbList: remove the dashed card; wire the single top-right button as the trigger
- AppSidebar: wire the "+" to the same dialog

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): interleaved chat trace + drop /compile from palette

Previously all streamed delta text (planning narration + the answer) was
concatenated into one blob and tool reads showed only as separate chips.

- chat.ts: fold SSE events into an ordered TurnStep[] preserving arrival order
  (text segments interleaved with tool steps); tool_call marks the prior read
  done; final reconciles the trailing text with the authoritative answer. The
  flat `answer`/`sources`/`reading` fields are retained for restore/consumers.
- ChatSession.tsx: render steps in order — narration via MarkdownView, each read
  as a status line (spinner -> green check), page reads stay click-through.
- drop `/compile` from the slash palette (runTurn never had a compile branch;
  recompile lives on the KB gear) and remove its now-unused icon import + keys.
  Chat is for Q&A + generation; KB-lifecycle actions live on the KB surface.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): global default credentials, drop dead footer, UN-language picker

Settings global config surface:
- backend: GET/PATCH /api/v1/config now also read/write global default credentials
  (LLM_API_KEY / OPENAI_API_BASE) in ~/.config/openkb/.env, mirroring the per-KB
  .env write (0o600, atomic, RFC-7386 null-removal, key value never returned/
  logged), under the existing global-config lock. GlobalConfigResponse gains
  openai_api_base + has_api_key; GlobalConfigPatchRequest gains api_key
  (SecretStr) + openai_api_base. +6 tests.
- Settings.tsx: add a Default credentials section (masked key, set/unset hint,
  deferred clear, API base) folded into the merge-patch save; remove the dead
  brand/privacy footer card + its i18n key.

Wiki output language now offers the six official UN languages as a datalist
combobox (still free-text, so e.g. 日本語 works) in both the global Settings
and the per-KB gear. Also a one-line LanguageToggle doc-comment fix.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): persist per-turn chat trace so restored sessions keep the trace

Revisiting a saved session collapsed the interleaved trace back to one text
block, because only the flat answer was persisted. Now the ordered trace
(narration text + tool reads) is stored per turn and rebuilt on restore.

Backend:
- ChatSession gains `assistant_traces` (parallel to assistant_texts, 1:1 by
  index); to_dict/load_session round-trip it; record_turn accepts a `trace` and
  back-fills empty traces for older turns so a pre-existing session that gets a
  new turn stays index-aligned. Old files without the key load as [] (no crash).
- iter_chat_turn_events accumulates the trace from delta/tool_call events (same
  order the frontend folds live) and persists it via record_turn.
- ChatSessionLoadResponse returns assistant_traces (new ChatTraceStep model).

Frontend:
- loadSession exposes assistant_traces; ChatSession restore rebuilds steps via
  stepsFromTrace (tool steps re-derived through the same read-only whitelist),
  falling back to a single text step for trace-less (old / CLI) turns.
- fix a latent live bug: on `final`, do NOT overwrite the trailing text step
  with final.answer (which is the full narration+answer concatenation) — that
  duplicated narration once tool reads split the text; keep the streamed trace
  and only inject the answer when nothing streamed.

Backward compatible: only sessions created after this change carry a trace;
older ones render their saved text as before.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): record only read-tool calls in the persisted chat trace

Review follow-up. The trace recorded every tool_call, including write_file,
whose `arguments` carries the entire generated file `content`. That bloated the
session JSON and was shipped to the browser on restore only to be dropped by
the frontend's read-only whitelist. Gate recording to _TRACE_READ_TOOLS
(read_file / get_page_content) — the only tools the UI renders — which also
fixes a live-vs-restore text-grouping divergence a dropped write_file caused.
Plus a tidy-up of the languages.ts doc comment (drop raw CJK).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): render LaTeX math (KaTeX) and thematic-break rules in MarkdownView

Answers that contain LaTeX (\[ … \] block, \( … \) inline) and `---` rules
showed the raw delimiters/dashes as literal text. Add math + horizontal-rule
support to the hand-rolled MarkdownView: block/inline math render via KaTeX
(bundled + self-contained, no CDN; malformed TeX falls back to a code box), and
a `---`/`***`/`___` line renders an <hr>. Adds katex (pinned exact, matching the
mermaid/motion convention) + @types/katex.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): drop the not-yet-live openkb.ai website link from About

The About tab linked a "Website openkb.ai" that does not exist yet; remove the
link entry and its i18n key (both locales). The Globe icon stays (still used by
the Vectify AI company link).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): strip wiki frontmatter in the reader (no leading rule / junk)

GET /api/v1/page serves pages verbatim, so every concept/entity/summary page's
OKF `--- … ---` frontmatter leaked into the reader as junk metadata lines — and,
now that MarkdownView renders `---` as an <hr>, as a horizontal rule at the very
top. Strip a leading frontmatter block before rendering (reader only; chat
answers carry no frontmatter and are untouched). Second-review follow-up.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(config): harden credential .env writes + config resolution (review)

- credential .env: consolidate the KB and global read-modify-write into one
  _merge_patch_env helper that strips a leading `export ` before parsing (so an
  `export LLM_API_KEY=…` line is actually cleared/rotated, not leaked); reject
  api_key/openai_api_base values containing newlines (400) so a value can't
  inject extra KEY=VALUE lines python-dotenv would parse.
- resolve_effective_config: coerce a non-dict config.yaml/global.yaml to {} so a
  malformed (esp. global) YAML degrades to defaults instead of AttributeError-ing
  KB-wide on every command's hot path.
- PATCH /api/v1/config: run the blocking global-config flock via run_in_threadpool
  so a contended lock no longer stalls the async event loop.
+4 tests.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(chat): atomic wiki write + whitespace-answer + tool-call id fallback (review)

- write_kb_file now uses atomic_write_text (temp + os.replace) instead of a plain
  write_text, so a REST /chat-triggered wiki/output write can't be observed torn
  by a concurrent lint/recompile (and it goes through locks.py per the invariant).
- iter_chat_turn_events: inject the final answer into the persisted trace unless a
  text step with NON-whitespace content exists, so a whitespace-only delta no
  longer makes a restored turn render empty.
- iter_agent_response_events: derive the tool-call correlation id via a shared
  helper using the SDK's call_id-or-id fallback on BOTH the call and output sides,
  so LiteLLM/ChatCompletions-routed writes still fire the output artifact card.
+8 tests.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(web): chat/input correctness fixes (review)

- foldSseEvent final: inject the answer unless a non-whitespace text step exists
  (whitespace-only delta no longer hides the answer); export markToolStepsDone and
  run it in runTurn's catch/finally so a stream error settles the tool spinner.
- App: wrap the /chat/:id route in a keyed ChatSessionRoute so a route-param change
  remounts and re-runs restore (no more stale previous session on nav).
- ChatInput: guard Enter with !isComposing (CJK/IME users no longer submit
  mid-composition); use || so an empty kbId shows the placeholder, not blank.
- Settings: reject a negative pageindex_threshold, matching the per-KB gear.
- KbDetail: stripFrontmatter only strips a real YAML-mapping frontmatter block, so
  a page whose body legitimately opens with a --- rule keeps its first content.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): restore GFM links/italic/strikethrough/ordered-lists in MarkdownView

The hand-rolled renderer dropped several GFM features vs the old react-markdown.
Add [text](url) links (URL-scheme-guarded), *italic*/_italic_, ~~strikethrough~~,
and real <ol> ordered lists — with load-bearing alternation order ([[wikilink]]
before link, **bold** before italic) so existing tokens still parse. GFM tables
and code syntax highlighting remain out (they need react-markdown re-adoption).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(backend): atomic write_wiki_file + _setup_llm_key uses effective config

- write_wiki_file now uses atomic_write_text (its sibling write_kb_file already
  did), so a REST /chat-triggered exploration write can't be observed torn.
- _setup_llm_key resolves `model` via resolve_effective_config (DEFAULT ->
  global.yaml -> KB) instead of KB-only load_config, so a global-default model
  drives provider extraction; drop the now-unused load_config import. +1 test.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): restore stop/abort, document delete, upload progress, GFM tables

Re-establishes capabilities the plain-CSS app had and closes review gaps:
- Stream cancellation: apiStream/streamChat/streamQuery/runRecompile take an
  optional AbortSignal; ChatSession shows a Stop button while running and aborts
  the in-flight turn on unmount (no wasted tokens, clean settle — abort ≠ error);
  KbSettingsSheet aborts a recompile on close.
- Documents: per-row delete (POST /api/v1/remove, confirm) + streaming upload
  with per-file progress (SSE /api/v1/add) replacing the single spinner.
- Sidebar KB list refreshes on an `openkb:reload-kbs` event dispatched after a
  create, so a new KB appears without a full reload.
- MarkdownView renders GFM tables (aligned, scrollable, inline-formatted cells).
- client.ts warns once when the API base is cross-origin plain-http (token leak).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(backend): configurable KB root, custom-path init, union KB discovery

- kb_root_dir() precedence: env OPENKB_KB_ROOT > global.yaml `kb_root` > default
  <config>/kbs; GET/PATCH /api/v1/config expose/set `kb_root` (+ `kb_root_env_pinned`).
- POST /api/v1/init accepts an optional absolute `path`; a custom-path KB is
  registered (register_kb_alias) so it still resolves by name (resolve_init_kb_dir;
  relative path -> 400).
- KB discovery (moved to api_kbs.py to keep api.py/api_helpers.py < 800) now unions
  kb_root children with registered known_kbs/kb_aliases outside the root, deduped by
  resolved path; each /api/v1/kbs item gains `path`.
+15 tests.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): surface KB location — create-path preview, custom path, KB-root setting

- CreateKbDialog shows a live "Will be created at <root>/<name>" preview (fetched
  from /api/v1/kbs root) and an optional Custom path field that overrides it.
- Settings › General adds a Knowledge base root field (top-level kb_root merge-patch;
  empty -> null/default) with a note when it's pinned by OPENKB_KB_ROOT.
- KbList cards show each KB's path (now that KBs can live outside the root).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(backend): allow Unicode KB names + resolve known_kbs KBs by basename

Union KB discovery surfaced registered KBs outside kb_root (e.g. a CJK-named
`笔记` at ~/Documents/笔记), but they couldn't be opened: validate_kb_name only
allowed ASCII so a name-based endpoint 400'd on "笔记", and resolve_kb_alias only
checked kb_aliases + the kb_root fallback, never known_kbs.

- KB_NAME_RE relaxed to `[\w-]+` (Unicode letters/digits/_/-, still no spaces,
  dots, or path separators) so a Chinese-named KB is a valid, traversal-safe name.
- resolve_kb_alias now matches a known_kbs path by its directory basename (after
  aliases, before the root fallback), consistent with the KB list — so a
  registered out-of-root KB is addressable by the name the UI shows.
+2 tests.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix issue in review

* fix(web): translate KbDetail comments to English so i18n guard passes

The i18n build guard (check-i18n.mjs) flagged raw CJK inside comments in
KbDetail.tsx, failing `npm run build`. Its comment-stripper is a naive
state machine with no regex-literal handling, so a regex/quote earlier in
the file desyncs it into "string" state; from there `{/* ... */}` JSX
comments are read as string content and their CJK leaks past the strip.

All flagged lines are comments (no real UI string carries CJK in this
file), so converting the comments to English resolves the build failure
with zero functional risk and matches the codebase norm (English code
comments; CJK only in locale JSON).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG
VectifyAI#191)

* fix(deps): pin openai==2.44.0 to avoid InputTokensDetails breaking change (VectifyAI#187)

openai 2.45.0 added a required, no-default field cache_write_tokens to
InputTokensDetails. openai-agents 0.17.3 builds that object without the
field, so every LLM response crashes usage parsing with a pydantic
ValidationError. openkb did not pin openai, so fresh installs resolved it
to 2.45/2.46 and broke on any model. Pin below 2.45 until openai-agents
adapts.

* chore(deps): update uv.lock for openai==2.44.0 pin (VectifyAI#187)
…e slim packaging (VectifyAI#186)

* perf(converter): lazy-import markitdown to cut startup and enable slim packaging

markitdown is only used for the non-PDF, non-Markdown ingest branch, but it
was imported at module top level — so every `import openkb` eagerly pulled in
markitdown → magika → onnxruntime (tens of MB, slow). Move the import into the
branch that actually uses it.

Effects (measured):
- `import openkb.cli` cold start 4.64s → 3.53s (~24% faster); magika /
  onnxruntime / markitdown no longer load unless an Office-format document is
  converted.
- A packaged (PyInstaller) build can now exclude magika/onnxruntime for a
  slimmer artifact when Office-format ingest isn't needed. Previously the
  unconditional module-level markitdown import made magika load-bearing at
  startup, so excluding it crashed the whole app on launch.

markitdown appends warning filters on import but leaves the CLI's front
"ignore" filter at index 0, so no re-suppression is needed at the new import
site. test_converter patches `markitdown.MarkItDown` (the real attribute the
local import binds) instead of the removed `openkb.converter.MarkItDown`.

Claude-Session: https://claude.ai/code/session_01KZyUSGAzVL9yxpsWWPv6Y2

* test(converter): guard that importing converter stays markitdown-free

Adds a regression test that spawns a fresh interpreter and asserts
`import openkb.converter` loads none of markitdown / magika / onnxruntime.
This locks in the lazy-import optimization: if a future change reintroduces a
module-level markitdown import, startup cost and the slim-packaging benefit
regress silently while every functional test still passes. The check runs in a
subprocess so it is deterministic regardless of what earlier tests imported
into this process's sys.modules.

Claude-Session: https://claude.ai/code/session_01KZyUSGAzVL9yxpsWWPv6Y2

---------

Co-authored-by: Claude <[email protected]>
…es kept) + panel chrome-lane fix (VectifyAI#193)

* feat(api): default port 7566 + name the install extra/command "web"

The API server also serves the Knowledge Workbench UI, so `web` reads truer
than `api` for what people install and run. Make `[web]` the canonical extra
and add an `openkb-web` console script; keep `[api]` (as a self-referential
alias) and `openkb-api` working for backwards compatibility. README and the
rest-api example now lead with the `web` names. `python -m openkb.api` (the
module path) is unchanged.

Also move the default API port off the crowded 8000 to 7566 ("KB" = ASCII
75,66) to cut collisions with other local dev servers. Updated: the argparse
default, the default CORS origins, the Vite dev-proxy target, the
connection-dialog placeholder, and the README/examples. A server already
running on 8000 keeps its port; the new default only applies to freshly
started servers.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): keep ArtifactPanel header buttons out from under the global chrome pills

The docked artifact panel's header action buttons (open-in-tab / download /
close) sit at the panel's top-right — exactly where App.tsx's global floating
chrome cluster (theme + i18n toggles, `absolute right-3 z-40`) renders. The
cluster's higher stacking context covered the download and close buttons.

Reserve the ~112px chrome lane on the header with `pr-28`, matching the
existing convention used by KbList's header row and KbDetail's gear row, so
the panel buttons always clear the pills.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG
…es (VectifyAI#198)

* feat(api): delete a knowledge base (POST /api/v1/kb/delete + openkb delete-kb)

Physical, irreversible KB deletion with a type-the-name confirmation.

- config.delete_kb: rmtree the KB directory + unregister it from the global
  registry (known_kbs / kb_aliases / default_kb, via the new unregister_kb).
  Guards against deleting a non-KB path; tolerates a ghost registry entry
  (directory already gone) by just unregistering.
- POST /api/v1/kb/delete: confirm_name must equal kb, re-checked server-side.
  Lives in a new api_kbs_router (sibling of the config/graph/output routers) so
  api.py stays under the 800-line gate; delete_kb self-locks (config lock), no
  create_app closure needed.
- openkb delete-kb NAME: type-the-name prompt (or --yes) then delete.

Tests: endpoint (success + unregister, confirm mismatch, non-KB target) in
test_api.py; config (physical delete + unregister, refuse non-KB, ghost
tolerance) in test_config.py.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(api): delete a wiki page (POST /api/v1/page/delete) with backlink impact

Delete a concept/entity page and degrade references cleanly instead of leaving
them dangling:

- page_ops.delete_wiki_page: dry_run reports the backlink pages (whose inbound
  [[wikilinks]] would be demoted) without touching anything; execute removes the
  page under the KB ingest lock, strips its index.md entry outright
  (compiler.remove_doc_from_index — the entry is a [[link]] line), and demotes
  the now-dangling inbound [[links]] to plain text in ONLY those backlink pages
  (lint.fix_broken_links restrict_to). The page ref is "section/stem", validated
  to concepts/ or entities/ only (path-traversal-safe).
- New api_pages_router hosts POST /api/v1/page (read — relocated here from
  api.py to keep it under the 800-line gate) + POST /api/v1/page/delete.

Tests: dry-run impact + execute (page gone, inbound link demoted to text, index
entry removed, sibling kept), 404 on missing page, and rejection of unsafe /
non-editable refs.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(api): edit a wiki page (PUT /api/v1/page) + link context (POST /api/v1/page/links)

- page_ops.edit_wiki_page: replace a concept/entity page's BODY while preserving
  its code-managed OKF frontmatter (type/description/sources) verbatim; any
  frontmatter in the submitted content is dropped. Dead [[wikilinks]] the user
  typed are demoted to plain text on save (OpenKB keeps the wiki broken-link-free)
  and returned as ghosts_stripped so the UI can warn. Atomic write under the KB
  ingest lock.
- page_ops.page_link_context (POST /api/v1/page/links): outbound + inbound links
  for the edit-impact panel. Editing the body does not break either (links are
  path-based), so this is context, not a blocker — the honest impact model.
- PUT /api/v1/page added to api_pages_router.

Tests: edit preserves frontmatter + keeps a resolvable link + demotes a dead one
(reports ghosts_stripped) + replaces the body; 404 on a missing page; links
reports out/backlinks.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): delete a knowledge base from the settings sheet (type-name confirm)

Adds a Danger Zone section to KbSettingsSheet: a type-the-name confirmation
gates deleteKb() (POST /api/v1/kb/delete); on success KbDetail navigates back
to the KB list. New deleteKb client + kbSettings danger* keys + common cancel
(zh + en, identical key sets).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): in-reader page edit + delete with impact preview (F2/F3)

For an open concept/entity page, the reader header now shows Edit and Delete:
- Delete: a dry-run first (deletePage dryRun) surfaces the backlink pages whose
  [[links]] will demote to plain text; a red confirm card lists them, then the
  real delete closes the page and refreshes the inventory.
- Edit: a body textarea (frontmatter is preserved server-side), Save via
  PUT /api/v1/page, a links panel (getPageLinks: out/backlinks), a "recompile
  may overwrite" note, and a toast listing any dead links demoted to text.

Adds the deletePage/editPage/getPageLinks wiki clients and kb:pageOps.* locale
keys (zh + en, identical key sets). Build green (i18n guard + tsc + vite).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(workbench): address code-review findings (content-mgmt correctness + concurrency)

Backend (page_ops / kb_admin / lint):
- delete/edit now do their read-modify-write INSIDE the KB ingest lock and
  re-check the page exists under it: no stale backlink snapshot, no resurrecting
  a concurrently-deleted page, no 500 on a racing unlink (missing_ok=True). [#4,#5,#6]
- delete_kb serializes rmtree under the ingest lock (was fully unlocked). Moved
  delete_kb/unregister_kb into a new openkb/kb_admin.py so config.py drops back
  under the per-file line gate (751 lines). [#1,#15]
- page deletion no longer scans or rewrites lint's _EXCLUDED_FILES
  (AGENTS.md/SCHEMA.md/log.md); fix_broken_links(restrict_to) also refuses them,
  which protects `openkb remove` too. [#2]
- edit_wiki_page treats `content` as the body verbatim — no naive frontmatter
  split that silently dropped a body opening with a '---' block. [#3]
- delete uses the real on-disk stem for the exact-match index-entry removal
  (case-insensitive FS), and adds index.md to the demotion set so a [[target]]
  embedded in another entry's brief no longer dangles. [#7,#9]

API / CLI:
- delete-KB endpoint & CLI can now clean a ghost registry entry (registered name
  whose directory was removed by hand), catch delete_kb's ValueError -> 400, and
  the endpoint is typed `-> KbDeleteResponse`. [#8,#13,E5]

Frontend (KbDetail):
- Deleting a KB dispatches `openkb:reload-kbs` so the sidebar refreshes
  immediately (was stale until a manual reload) — live-test fix.
- Removed the dead `pageReloadSeq` path (editPage always returns content). [#14]

Tests: excluded-doc-untouched, '---'-body preservation, ghost-KB unregister;
non-KB-target test updated to the new resolution model. Backend 1234 passed,
mypy/ruff clean, frontend build green.

Not changed (intentional): pages_linking_to is NOT folded into build_graph (that
excludes explorations/ backlinks) [#10]; the preview+confirm delete inherently
scans per request [#11]; EDITABLE_SECTIONS stays duplicated in the frontend,
which can't import the Python constant [#12].

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(workbench): allow editing summary pages (edit ⊇ delete section sets)

Summaries are compiled markdown like concepts/entities (a recompile regenerates
them), so they are now editable via PUT /api/v1/page. They remain NOT
independently deletable — a summary is removed by deleting its source document.

Split page_ops into EDITABLE_SECTIONS (concepts/entities/summaries) vs
DELETABLE_SECTIONS (concepts/entities); validate_page_ref takes the allowlist.
Frontend ReaderBody gates Edit on canEdit (incl. summaries), Delete on canDelete.

Test: summary editable (frontmatter preserved) + summary delete rejected (400).

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(api): cross-platform delete_kb + endpoint OSError handling (xhigh review #1,#2)

- delete_kb no longer holds the ingest lock DURING rmtree (the lock file lives
  inside the KB dir; Windows cannot delete an open file — the prior review-fix
  regressed this). It now takes the lock as a BARRIER (drain + wait out any
  in-flight mutation), releases it, re-checks existence, then rmtrees. [#1]
- delete-KB endpoint maps FileNotFoundError to an idempotent success (a
  concurrent delete already removed the tree) and other OSError to a clean 500
  with a message, instead of an uncaught 500 stack trace. [#2]

Tests: endpoint OSError -> clean 500, FileNotFoundError -> 200 deleted.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG
…ane (VectifyAI#197) (VectifyAI#199)

* feat(web): read a document's converted source text in the Documents pane (VectifyAI#197)

The Documents pane listed each ingested doc (name/type/hash) with no way to
read the converted full text ingestion produced under wiki/sources/.

Backend: new POST /api/v1/document/source resolves a doc hash to its source
text — short docs read <doc_name>.md; long docs concatenate the per-page
<doc_name>.json (page text joined by a thematic break). Hash is the identifier
(unique, avoids doc_name/stem collisions); resolution prefers the registry's
stored source_path then falls back to the wiki/sources/<doc_name>.{md,json}
convention, with a path-traversal guard. Read-only (sources are do-not-edit).

Frontend: document rows are now clickable and open a wide read-only slide-out
reader (MarkdownView) — ESC/overlay/close to dismiss, independent scroll,
content cached + memoized per hash, native find-in-page preserved (no
virtualization). Delete stays inline (stopPropagation). Closed drawer is inert.

Known limitation: images embedded in long-doc pages are not rendered inline yet.

* fix(web): address xhigh code-review findings for the document reader (VectifyAI#197)

Correctness / a11y:
- Rebuild the reader drawer on Radix Dialog (like KbSettingsSheet) instead of
  a hand-rolled overlay: proper modal focus trap, initial + return focus,
  Escape, and background inert (was: aria-modal with none of it) [#4]. This
  also removes the hand-rolled window keydown listener that re-subscribed every
  render [#7].
- Restructure each document row so the open-reader target is a real <button>
  and the delete control is a SIBLING, not nested. Keyboard-activating delete
  no longer bubbles into opening the reader, and the invalid nested-interactive
  markup is gone [#1, #5].
- Resolve a source file by the doc's own type (long → .json first, else .md),
  so two docs sharing a doc_name each resolve to their own file rather than
  whichever extension is tried first [#2].
- Guard source reads: skip non-dict page entries, reject non-list JSON, and
  return a controlled 500 on corrupt/unreadable sources instead of an
  unhandled exception [#3].
- Invalidate the per-hash content cache when the inventory changes, so a
  reopen after recompile refetches instead of serving stale text [#6].

Fetch/cache/memoized body moved to DocumentsPane so they survive the drawer's
unmount-on-close. #8 (frontmatter stripping) intentionally not applied: source
docs render verbatim (a user's own frontmatter is content, unlike wiki-page OKF
metadata). Adds tests for the collision and malformed-JSON paths.
…verride) (VectifyAI#200)

* feat(api): configurable entity_types (global + per-KB) via the config API

entity_types (the entity-extraction vocabulary) is now surfaced through the
config read/write API, layering global.yaml -> KB config.yaml like the other
scalars: a KB list overrides the global list wholesale, an explicit null
inherits, and unset falls back to DEFAULT_ENTITY_TYPES. The compiler already
consumed config["entity_types"] via resolve_entity_types; this just exposes it.

- GLOBAL_SCALAR_KEYS gains "entity_types" (layering + per-key `sources` tracking;
  the value-not-None-wins rule is type-agnostic, so it works for a list).
- _KbConfigWritable / GlobalConfigValues / KbConfigResponse / GlobalConfigResponse
  carry entity_types; read_kb_config/read_global_config report the cleaned
  EFFECTIVE list (resolve_entity_types) plus the raw global value for the badge.
- PATCH /api/v1/kb/config and PATCH /api/v1/config accept entity_types.

Tests: KB override (cleaned + source 'kb') + null revert, global patch, global
inheritance; updated the global-defaults shape assertion. Frontend UI follows.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* feat(web): entity-types config UI — chips editor (global default + per-KB override)

- EntityTypesEditor: shared controlled chips editor (Enter/comma to add, x to
  remove; "other" is a fixed always-included chip; IME-safe composition).
- KbSettingsSheet: an EntityTypesRow with the same inherit/override Switch as the
  scalar rows — turning override on seeds+persists the KB's own list, off reverts
  via null; inherited state shows the global/default list as a badge. Each chip
  change persists and adopts the server-cleaned response.
- Settings (general tab): a global entity-types chips editor, order-sensitive
  diff into the save patch (joins the existing dirty/SaveBar flow).
- "changes affect future recompiles only" note on both surfaces.

New keys in common/kbSettings/settings (zh + en, identical sets). Build green
(i18n guard OK). Backend was committed in 92f8f41.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG

* fix(entity-types): address xhigh review — DEFAULT_CONFIG parity, empty-list inherit, silent reads, set-diff

- config: define DEFAULT_ENTITY_TYPES before DEFAULT_CONFIG and add
  `entity_types` to DEFAULT_CONFIG so the key layers like every other
  GLOBAL_SCALAR_KEY and always appears in the effective config (#1).
- config: resolve_effective_config treats an empty entity_types list the
  same as null → inherit, so a KB that cleared its override doesn't pin an
  empty vocabulary (#2).
- config: resolve_entity_types(config, *, warn=True); config-read paths pass
  warn=False so a plain GET doesn't spam coercion warnings (#4).
- api_config: both read paths call resolve_entity_types(..., warn=False).
- KbSettingsSheet: inherited badge shows the effective list, not
  `globalValue ?? effective`; drop the now-unused globalValue prop (#3).
- Settings: global entity_types diff is order-insensitive — the vocabulary
  is a set, so re-adding a removed type is not a change (#6).

Backend pytest 1240 passed; ruff/format/mypy clean; frontend build green.

Claude-Session: https://claude.ai/code/session_01XMxbhmAkxxVV8CFWCZDBaG
Add openkb/agent/ollama_adapter.py — a resilient wrapper that catches
ModelBehaviorError when Ollama models hallucinate tool names and retries
with a corrective message listing the actual available tools.

- is_ollama_backend(): detect Ollama models (ollama/ and litellm/ollama/ prefixes)
- arun_with_retry(): wraps Runner.run() with retry on ModelBehaviorError
- run_streamed_with_retry(): wraps Runner.run_streamed() with retry
- _RetryableStreamResult: seamless stream retry via generator
- 26 new tests in tests/test_ollama_adapter.py (all passing)
- query.py patched to use retry wrapper for Ollama backends only
- Non-Ollama path unchanged

Issue: VectifyAI#205
Key improvements over v1:

1. rewrite_ollama_model(): convert ollama/ → ollama_chat/ so LiteLLM
   uses native Ollama Chat API with tool support (primary fix).
   Without this, LiteLLM falls back to prompt injection and tool calls
   never work through the SDK.

2. Configurable timeout: _ensure_ollama_timeout() injects 300s default
   into ModelSettings.extra_args for Ollama models, preventing premature
   timeouts on slow local hardware.

3. Updated query.py: rewrite applied in build_query_agent() and
   build_run_config_from_bundle().

4. 41 tests (up from 26), all passing.
5. 1116 existing tests, all passing.
6. Live test: gemma4:12b full tool-loop completes in 132s.

Issue: VectifyAI#205
Fixes for the full add+query pipeline with Ollama:

1. Module-level OLLAMA_API_BASE propagation in ollama_adapter.py:
   - OPENAI_API_BASE → OLLAMA_API_BASE (env var)
   - litellm.api_base module setting
   So ollama_chat LiteLLM provider finds the endpoint on all paths.

2. compiler.py: pass api_base from env when bundle is None (CLI path)
   so litellm.completion/acompletion reaches Ollama for add/concepts.

3. cli.py: rewrite_ollama_model applied to all model resolutions (12 sites)
   so ollama/ → ollama_chat/ everywhere, not just query.

4. add_coordinator.py: import ollama_adapter for side effects.

5. drop_params=True set in _ensure_ollama_settings for ollama_chat
   (rejects parallel_tool_calls).

Tests: 1116 passed, 0 failed.
Live: add summary=77s OK; query tool-loop=132s OK (SDK E2E verified).
Issue: VectifyAI#205
Add resolve_ollama_settings() to read the 'ollama:' config block:
  ollama:
    timeout: 300            # per-request timeout (s), default 300
    tool_call_retries: 3    # max retries on hallucinated tool names

Timeout precedence: ollama.timeout > litellm.timeout > top-level timeout > 300
Retry precedence: ollama.tool_call_retries > default 3

Changes:
- ollama_adapter.py: resolve_ollama_settings() + all retry/timeout
  functions now resolve from config when not explicitly passed
- config.yaml.example: documented ollama: section
- docs/ollama_tool_call_adapter.md: full configuration documentation
- tests/test_ollama_adapter.py: 15 new tests for resolve_ollama_settings
  (56 total, all passing; 1131 total suite, 0 failures)

Issue: VectifyAI#205
@mike-011 mike-011 changed the title feat(agent): Ollama tool-call retry adapter (fixes #205) feat(agent): Ollama tool-call adapter with parameterized timeouts (fixes #205) Jul 29, 2026
@mike-011
mike-011 force-pushed the feat/ollama-tool-call-loop branch from 2ea9930 to 1a4e830 Compare November 23, 2026 16:22
mike-011 added a commit to mike-011/OpenKB that referenced this pull request Nov 23, 2026
When a local Ollama model (12-14B) returns a final answer without calling
any tools, the adapter now retries with an escalating nudge message:

  Attempt 1: 'You answered without reading wiki files. Call read_file
  with path summaries/index.md first.'
  Attempt 2: 'You MUST use the read_file tool. Do NOT answer without
  reading files first.'
  Attempt 3: 'IMPORTANT: Your previous answer was not grounded. Call
  read_file now. Do not answer until you have called a tool.'

Detection: _has_tool_calls() checks result.new_items for ToolCallItem.
If none found and agent has tools, nudge and retry (up to tool_call_retries).

Bounded by tool_call_retries (default 3) — no infinite loops.
Shares retry budget with ModelBehaviorError retry.

Tests: 73 adapter tests (17 new), 1148 total, 0 failures.
Docs: docs/ollama_no_tools_retry.md

Complements PR VectifyAI#210 (ollama_chat/ rewrite + ModelBehaviorError retry).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ollama tool-calling loop does not complete for query/chat on v0.4.5 and v0.5.0-rc1