Architecture
WCHT combines a local Python-standard-library retrieval engine with OMP-backed Wiki Chat and an instant lexical-search fallback. wcht/kb.py implements preparation, indexing, search, and explicit source removal; wcht/__main__.py exposes JSON-producing commands. The corrected D-167 web contract uses wcht/web.py for HTTP and wcht/chat.py for conversation orchestration. SQLite must provide FTS5; no embedding service or second direct provider client is introduced.
The public Quartz site at wiki.wcht.loca.zone explains the system. The separate Wiki Chat app uses existing OMP OAuth for generated answers, grounded by kb-answer and actual wcht.kb.search evidence. runbook describes operation, decisions the trade-offs, and eval-results the current measured boundary. Implementation and live deployment proof are distinct: this corrected contract does not itself attest runtime gates.
flowchart TD A[Captured guide and provenance] --> B[prepare_corpus.py] B --> C[Approved local Markdown] C --> D[Hash and normalize selected files] D --> E[Heading-aware chunks and source metadata] E --> F[Atomic SQLite transaction] F --> G[Sources and chunks] F --> H[FTS5 index and token index] Q[OMP user question] --> R[Read-only search] G --> R H --> R R --> S[BM25 and token-coverage ranks] S --> T[Reciprocal rank fusion] T --> U[Bounded passages with citations] U --> V[kb-answer reads source spans] V --> W{Requested claim supported} W -->|Yes| X[OMP cited synthesis] W -->|No| Y[Explicit evidence gap]
Wiki Chat and search boundary
The loopback service remains python3 -m wcht.web --host 127.0.0.1 --port 51167 --db /home/loca/dev/wcht/data/kb.sqlite, managed by wcht-web.service. Every HTTPS route belongs behind Authelia. GET / serves the chat shell; /assets/app.js and /assets/style.css serve same-origin assets. GET /api/search?q= retains instant lexical evidence retrieval: one q, at most 512 characters and five public hits. GET /healthz is process liveness, not database or inference readiness. The protected static /showcase/ alias is separate from chat and requires its own publication proof.
Chat/history endpoints require a nonempty validated Remote-User injected by trusted nginx; clients cannot choose an owner. Missing identity returns 401 and another user’s or unknown session returns 404. GET /api/sessions lists only that user’s conversations; POST /api/sessions creates one; GET /api/sessions/<id> restores its messages. Session records live under isolated owner-key paths in .omp/runtime/web, with 0700 directories and 0600 files, and must survive child teardown and service restart. Authentication does not authorize private-corpus retrieval.
POST /api/chat accepts bounded JSON containing session_id and message. Fetch-based SSE streams queued, start, available real thinking, text, sanitized tool, citations, done, and error events. There is no fabricated thinking or raw tool-output disclosure. Cross-origin writes are rejected; authorized CLI requests without Origin remain possible. The browser treats generated text as untrusted and offers cancellation through AbortController.
The backend uses persistent native omp acp over newline-delimited JSON on stdio: initialize, session/new, session/prompt, and session/update. Immediate follow-ups reuse the conversation’s live ACP session. The installed ACP session/load path ignores the custom session directory, so after teardown or restart the backend creates a fresh ACP session and replays only that owner’s persisted user/assistant transcript. This is not print-mode continuation or a claim of native session-load restoration.
ACP handles session control and tool lifecycle, but its native text stream can flatten provider errors into assistant text. The explicit project-local safety extension therefore emits privately tagged, genuine SDK text/thinking deltas and terminal events over a dedicated inherited file-descriptor pipe, separate from ACP stdio. This separation matters because installed OMP redirects extension stdout writes to stderr while isolating protocol stdout. A bounded Python reader consumes the private pipe; the backend deduplicates events and requires both the ACP response and successful guard-terminal attestation before completion. Browser text/thinking comes from those typed SDK events, not fabricated progress or raw provider diagnostics. Raw tool output is not forwarded. The private channel adds no external network connection or credentials; its corrected runtime proof remains separate.
Capacity is at most two OMP child roots globally, one active request per user, FIFO per user, and at most four waiting requests per user / sixteen globally. Queue plus execution has a 300-second timeout; idle children expire after 90 seconds and may be evicted for capacity. Cancellation, timeout, or unexpected stream disconnect terminates/reaps the child process group and releases its slot. A queued cancellation records no submitted turn; a started interrupted request preserves its user message and partial assistant response. Web history stores neither thinking nor raw tool output.
The detached retrieval MCP child also arms Linux parent-death SIGKILL with a parent-race check, so it cannot survive its OMP parent’s death. This supplements process-group cleanup rather than replacing it.
Approved retrieval is a fixed child-local read-only stdio MCP capability, wcht.search, backed by actual wcht.kb.search plus hash-verified source-line readback. The system prompt includes the native kb-answer skill text with an explicit CLI-to-search-tool adaptation. An exact tool allowlist and deny guard are required in the project-local safety extension because --no-tools/--no-extensions alone do not establish confinement. Child-local runtime settings disable memory, automatic learning, automatic QA, and discovery; global OMP settings remain untouched. No generic shell, filesystem, network tool, credential inspection, or other user’s history is exposed to the model. These are implementation semantics supplied by the backend owner, not independent runtime acceptance.
The child uses a fresh private PI_CONFIG_DIR discovery root so ambient npm custom-tool modules cannot load. PI_CODING_AGENT_DIR explicitly points to the unchanged native OAuth agent directory; profiles are empty. Discovery isolation is separate from credential storage: no credentials are copied, symlinked, inspected, or exported, and no global configuration or key is changed. The explicitly loaded guard remains necessary and deduplicates final-snapshot/late-delta races.
Public evidence retains source URLs, captured source-file line bounds, and chunk IDs; wiki_url links to the matching dissection heading (or its page fallback) without replacing the original citation. Search JSON omits local source_path. Browser assets and telemetry do not require external requests, but actual OMP inference sends the question, retrieved evidence, and relevant conversation to the configured external OAuth provider.
Citation continuity is not blind reuse of stored metadata. When a follow-up answer mentions a chunk previously cited in that conversation, the backend resolves its ID again against the current public index and verifies actual source hashes, line spans, and private-path exclusions before rebuilding citation metadata for SSE and history. Missing, stale, or private chunks are not promoted to current citations. This supports contextual answers when the current lexical query alone misses earlier evidence; it does not turn conversation memory into independent source authority.
Source preparation is not source invention
scripts/prepare_corpus.py reads exactly ten captured official guide articles and their provenance. It verifies source text digests, URLs, capture metadata, and the known article boundaries before generating Markdown. The transformation removes known navigation furniture, adds a title, and fences the code blocks already identified by the capture. It does not generate summaries or answers, fetch new pages, or execute code from a source.
The prepared corpus is corpus/tutorial/; its _manifest.json records the input/output hashes. Every article has a stable official-guide: source identity, its real guide URL, a capture date, and evidence_class: official_companion_guide. The corpus has no video timestamps. The 20-question evaluation and its reference answers remain outside it.
The preserved video metadata, pinned repository, supplied automatic captions, and sampled frames are separate evidence classes supporting tutorial-dissection. JSON3 normalization preserved text/timing across 1,307 nonblank cues from 2,655 events; VTT differs and neither is an independently audio-verified verbatim transcript. The 56 unique 1280×720 frames cover all 12 chapter starts plus two seconds and 44 scene samples, not continuous playback or a full-video download. These media artifacts were not added to the frozen guide-derived evaluation corpus.
Input and metadata contract
The ingest command accepts explicit files or directories containing UTF-8 .md, .markdown, .mdx, .txt, .html, and .htm files. A file is bounded at 10 MiB. MDX is treated as source text; no React, JavaScript, shell command, or template is executed.
Optional frontmatter starts at the beginning of a file and supports simple scalar key: value entries. It is not a general YAML parser: collections, tags, block scalars, duplicate keys, malformed values, and unterminated frontmatter are rejected. JSON-quoted strings are a convenient unambiguous representation. In particular, private must be the boolean true or false, not a quoted string.
| Metadata | Implemented meaning |
|---|---|
source_id | Explicit stable identity; otherwise src- plus SHA-256 of the canonical local path |
title | Preferred display title; otherwise HTML title, first heading, or filename stem |
source_url | Optional absolute HTTP(S) source URL; no URL is invented when absent |
captured_at | Preserved source/capture metadata, distinct from a video position |
timestamp | Optional source-supported position; absent values remain null, not guessed |
evidence_class | Declared provenance category carried into search output |
private | Strict boolean privacy marker; private-directory placement independently applies |
Additional scalar metadata is stored with the source, but not every field is projected into search results. Source metadata is asserted by the source author/preparer; the engine does not certify the truth of a URL, date, owner, or evidence-class label. The guide preparer adds the separate digest/allowlist verification appropriate to this corpus.
Normalization and chunks
The engine removes script/style content and HTML comments from Markdown processing while preserving physical newline accounting. HTML parsing extracts inert text, headings, title, and image alt text; it never interprets alt text as proof of an image. Markdown headings supply a section path, and fenced code stays textual evidence rather than executable instructions.
Chunks target 1,200 characters and cap individual split pieces at 1,800 characters. Heading boundaries start new chunk context; oversized text is split near whitespace where possible. Each chunk records its source line range and section hierarchy. Whitespace and markup can be normalized, so a source span locates the original passage rather than promising byte-identical raw formatting or an exact character offset. Long source blocks can give several chunks the same enclosing line range.
A chunk ID is chk- followed by the full SHA-256 of a structured identity containing source ID, section path, normalized chunk text, and occurrence number for repeated identical chunks. Line numbers and database row IDs are not the chunk identity. An unchanged chunk whose boundaries and source identity remain the same can retain its ID when preceding lines move. A substantive edit, different section, changed chunk boundary, or changed source identity can change it. Old answers must not assume their IDs are still current after re-ingestion.
Incremental indexing and explicit retirement
Raw input bytes, including metadata, are SHA-256 hashed. For unchanged content and the same identity/privacy state, re-ingestion retains the existing chunks instead of recomputing and duplicating them. Changed selected sources replace their prior source/chunk representation inside one SQLite transaction. An error in the selected ingest operation rolls that operation back rather than leaving half its sources updated.
Schema version 2, recorded in SQLite’s user_version, has four logical stores:
| Store | Purpose |
|---|---|
sources | Stable ID, canonical path, raw hash, title, URL, capture/video metadata, evidence class, privacy/index state, and remaining scalar metadata |
chunks | Source-linked normalized passage text, section, ordinal, stable chunk ID, and source line bounds |
chunks_fts | FTS5 external-content index over title, section, and text; insert/delete triggers keep it aligned with chunks |
chunk_terms | Deduplicated normalized tokens per chunk for the independent lexical coverage ranking |
Version 2 invalidates earlier derived indexes affected by a parser offset collision that could produce incorrect citation line spans. Version-1 databases fail closed for ingest, search, and removal. Preserve any old database needed as evidence, then rebuild from approved source documents into a new database path. Merely reusing matching input hashes, changing the version field by hand, or trusting an earlier lexical score cannot repair citation provenance.
Ingestion is upsert, not directory synchronization. An absent file remains indexed until explicitly retired with remove SOURCE_ID. Removal accepts one or more exact source IDs and removes source/chunk/derived-index records atomically; an unknown requested ID aborts the whole removal. Ingest reports source_id for each input, and search hits carry it too, so an operator need not guess a path-derived digest.
Distinct live files cannot silently take the same explicit source ID. A moved document can preserve its identity if the former path is no longer present; explicit source IDs are preferable when a path is expected to change. Renaming a path-derived source requires accounting for its old identity rather than assuming a directory scan will remove it.
The actual lexical retrieval algorithm
Search opens the database read-only and reads within a transaction. It does not initialize a missing index, silently substitute another database, or generate an answer. FTS5 is required; there is no semantic fallback.
- Normalize the query with case folding, Unicode decomposition, accent removal, token extraction, and a fixed stopword set. Use distinct meaningful tokens, not token repetition as extra weight.
- Retrieve FTS5 candidates using an OR query over those terms and BM25 weights of
2.0for title,1.5for section, and1.0for passage text. FTS5 usesunicode61with diacritic removal. - Independently rank token-index candidates by the number of distinct query terms they contain.
- Take up to
max(100, 20 × requested_limit)candidates from each ranking. For each rank starting at one, add1 / (60 + rank)to that candidate’s fused score. The two rankings contribute equally; their raw scores are not averaged. - Order by descending fused score, then source ID, source ordinal, and chunk ID for deterministic ties. Return at most the requested limit, default five; allowed limits are one through 100.
Queries are capped at 4,096 characters and 128 distinct meaningful terms. An empty meaningful query or no matching candidates produces status: no_evidence and an empty hit list. Otherwise the response is status: evidence. This status means lexical candidates exist, not that they answer the question, preserve a negation, or authorize a policy decision.
The implementation has no embeddings, learned reranker, synonym model, or remote search call. “Lexical hybrid” is the precise description. It can miss paraphrases and return related-but-insufficient passages; those are limitations to measure or disclose, not reasons to fabricate support.
Evidence and OMP answer flow
Each hit returns chunk_id, source_id, title, text, url, source_path, start_line, end_line, timestamp, captured_at, evidence_class, section, private, score, and citation.
The citation uses the actual source URL when supplied, otherwise the canonical local path, followed by the captured line bounds and full chk- identifier. It does not invent a public URL or a timestamp. For this guide corpus the line bounds locate the generated Markdown; the original guide URL and capture manifest establish its provenance.
The kb-answer skill runs real retrieval, reads back the relevant source spans, checks that the source has not changed, and then decides whether each claim is supported. A stale passage requires re-ingestion and a fresh search. Every factual claim must carry the returned citation; a mixed-source sentence needs all relevant citations or should be split. The assistant must refuse unsupported details and distinguish an absent rule from explicit approval or prohibition.
The class-level skill correction requires self-contained subjects, exact technical identifiers, named source actors, and source topic spelling. It corrects answer composition rather than relaxing retrieval, evaluator normalization, reference expectations, or the 0.90 threshold.
Retrieved instructions remain untrusted source text. Neither a passage nor a remembered answer can override the skill, authorize private retrieval, request credential disclosure, or become an automatic source update. kb-ingest owns the procedural path for approved source changes; answers are not automatically re-ingested as facts.
Privacy and publication are different boundaries
Ingestion treats boolean private: true and a private or .private path segment as private. Without explicit ingestion opt-in, private content is not chunked or indexed. If a formerly public known source becomes private, default re-ingestion removes its old chunks atomically. Limited source bookkeeping can remain; exclusion is not a promise that the database contains no trace of a source path or ID.
Private ingestion does not enable private search. Search filters both candidate rankings and returned rows unless the operator separately supplies --include-private. These are CLI controls, not protection against a process with direct filesystem/database access. Operational commands and access details are kept on the restricted operations page.
The browser adapter does not expose --include-private. Signing in at the app’s edge permits use of public-corpus search; it does not authorize private-corpus retrieval or provider disclosure.
Local ingestion and retrieval do not make OMP inference local. Questions and retrieved passages placed in the OMP context may leave the machine for its configured OAuth model provider. The public wiki is a further disclosure boundary: only sanitized documentation belongs there. The existing Quartz split excludes the private directory from the public build; frontmatter alone is not that publishing filter.
Exercised implementation boundary
The corrected schema-2 engine ingested ten official-guide documents into 54 chunks. Integration exercised nine CLI scenarios successfully, and an independent scan found all 54 citation spans within their actual source files. A focused source-line regression passed; restoring the original parser-offset defect in a disposable copy made that regression fail. This is bounded runtime evidence, not a promise that every parser or concurrency edge case has been covered.
The fresh native OMP run passed retrieval and the actual-answer lexical contract at 20/20 with all answers present and passing citation/refusal integrity. It used 20 actual CLI queries and 19 cited source-span readbacks without reading gold or old answers. The earlier 17/20 and its three term failures remain in receipts/history-d161-before-media-completion/; eval-results distinguishes this historical baseline from the fresh 2026-09-26T11:23:09Z evaluation and from semantic correctness.
D-167 observed runtime boundary
The integration owner reported real HTTPS cited OMP text, contextual marker recall with native ACP session reuse, actual MCP retrieval activity, unsupported-payroll refusal, owner isolation and cross-origin rejection, a two-child OS capacity observation with queued requests, FIFO ordering, queued cancellation, active browser Stop cleanup, a shortened-deadline cleanup, and eleven guard fault cases. Mobile interaction at 390 pixels had no overflow and source links were clickable after the historical-citation fix. eval-results records exact observed counts and timing.
The real provider returned no thinking blocks: only an actual-extension fixture exercised thinking transport. No real-provider thinking-stream claim is made. The integration owner restored canonical nginx after backup, passed its configuration check, and reloaded it; the former loopback proof request with Remote-User again returned 302 to Authelia. Temporary auth/browser/timeout services were stopped, and the database SHA-256 stayed unchanged through the chat proofs. The protected /showcase/ alias exists with an empty content directory permitted by the user; no showcase content is claimed available. Active wiki builds and live publication checks are recorded separately in the final deployment receipt.
Wiki sync
D-167 supersedes lexical-only browser scope with OMP-backed Wiki Chat and an instant-search fallback. Final D-161 publication/mission evidence belongs in receipts/wcht-first-task.json; its old exact version remains in receipts/history-d161-before-media-completion/wcht-first-task.json. D-167 app deployment observations remain in receipts/wcht-web.json, whose final field is current_state after wiki_sync; this source-level update does not attest new runtime gates.
State block
Schema-2 implementation and bounded runtime proof documented on 2026-09-26; no semantic-search parity is claimed. Fresh guide-derived retrieval and answer lexical contracts pass 20/20 at unchanged 0.90. Supplied-caption analysis and 56 sampled frames support the verified reconstruction, with automatic-caption and sampling limits intact.
Full D-161 publication/completion is governed by receipts/wcht-first-task.json and its identical external copy /home/loca/.flowmaster-d161/wcht-first-task.json, not a signal assertion here. D-167 web status remains separate in receipts/wcht-web.json; no new D-167 runtime proof is claimed.