Skip to content

feat: distill knowledge through the running MCP server with OpenAI-compatible synthesis - #145

Merged
jflowers merged 14 commits into
unbound-force:mainfrom
jflowers:opsx/dewey-distill
Nov 5, 2026
Merged

jflowers merged 14 commits into
unbound-force:mainfrom
jflowers:opsx/dewey-distill

Conversation

@jflowers

@jflowers jflowers commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements #133: knowledge distillation through the running MCP server with an OpenAI-compatible synthesizer, plus batch promotion and namespace-aware page resolution (subsumes #91).

  • Adds the openai-compatible synthesis provider (enmaas-ready) with bearer auth, configurable timeout/max_tokens, bounded 429 retry, truncation detection, redirect blocking, and credential redaction.
  • dewey serve builds one synthesizer and passes it to the MCP compile and curate tools (and background curation). Unconfigured or unavailable providers keep the existing prompt-mode fallback byte-for-byte.
  • compile joins the pipeline-wide index mutex used by indexing and curation, so server-side synthesis cannot race a background index.
  • promote accepts a pages batch (validate-all-then-mutate, atomic transaction) and resolves bare tags, case differences, knowledge/* pages, and source-doc ids, fixing bug: dewey_promote MCP tool fails with 'Page not found' for compiled articles #91.
  • Adds the gated /dewey-distill slash command (lint → inventory → scope gate → compile/curate → review gate → batch promote → report).
  • dewey doctor validates the new provider without live calls and without exposing credentials.
  • Documentation updated in README.md and AGENTS.md; website sync issue filed as docs: sync dewey distill documentation website#371.

Verification

  • go build ./...
  • go vet ./...
  • go test -race -count=1 -coverprofile=coverage.out ./...
  • Gaze: CRAPload: 48/48 (PASS) | GazeCRAPload: 38/45 (PASS)
  • golangci-lint run clean for all changed files
  • openspec validate dewey-distill --strict valid
  • Review council: APPROVE from Architect, Adversary, Guard, Testing, and SRE

Closes #133
Closes #91

@jflowers jflowers left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superseded by review #145 (review). This duplicate review was posted by a parallel run of /uf.review-pr 145; its inline comments have been removed. The council verdict in the superseding review remains REQUEST CHANGES.

@jflowers jflowers left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Posting note: GitHub rejects REQUEST_CHANGES on a pull request authored by the authenticated account, so this review is posted as COMMENT. The council verdict remains REQUEST CHANGES.

Review verdict: REQUEST CHANGES

The distillation pipeline is complete and the acceptance criteria for #133 and #91 are covered. CI is green (build-and-test, MegaLinter), the provider core is well-hardened, and prompt mode preserves prior behavior for non-empty inputs. Merge is blocked by one compound trust-boundary defect, one YAML-injection defect, and spec drift.

Council: Seven personas reviewed the immutable head 5f6e3a0 through direct subagent dispatch; the deterministic review-dispatch plugin was unavailable in this session, so no consolidated dispatch artifact exists. All seven return REQUEST CHANGES.

Blocking findings

  • CRITICAL (compound) — validated compiled knowledge can be deleted or demoted. clearCompiled (tools/compile.go:463) deletes every compiled page and removes the compiled directory when the learning set is empty; removeStaleTopics (tools/compile.go:373) deletes a compiled article when its topic loses its last learning; and persistCompiledArticle writes the tier captured after synthesis unconditionally (tools/compile.go:330,812; store/store.go:472-480), so a concurrent promote reverts to draft and a discarded findErr silently demotes. None of the deletion paths filters validated.
  • HIGH — curation frontmatter injection. renderKnowledgeQualityFlags interpolates flag.Type and flag.Sources with %s (curate/curate.go:490,495), and isValidKnowledgeFile does not validate QualityFlags. A newline in LLM output injects top-level YAML keys.
  • HIGH — unplanned behavior changes contradict canonical specs. reIngestLearnings forces draft (main.go:1204), reversing specs/015-curated-knowledge-stores/spec.md:147; StoreCompiled refuses validated overwrite (tools/compile.go:956), contradicting specs/016-pluggable-providers/spec.md:66; curation silently drops invalid items and preserves validated on auto-index. None appears in the delta spec, proposal, design, or tasks.
  • HIGH — missing regression test for curated validated-tier preservation. Reverting the guard at tools/curate.go:319 passes every test.

Remaining medium findings

  • Store/file replacement is not atomic. persistCompiledArticle runs UpdatePage -> DeleteBlocksByPage -> PersistBlocks before the file rename (tools/compile.go:814-826); a failure after the delete leaves the page with zero blocks while the old file remains. The replaceArticles doc at :380-382 claims the previous page and file stay intact.
  • Dead code and stale GoDoc. store.UpdatePageTier has no production caller and carries two concatenated doc comments, the first falsely saying it is "used by the promote MCP tool" (store/store.go:1069-1075). CompiledPrefix/LearningPrefix have no consumers while the literals are hardcoded in about ten places (store/store.go:179-182).
  • Third copy of the option-introspection idiom. buildSharedSynthesizer re-applies every serverOption to a throwaway config to recover the vault path (main.go:289,791-810). Extract one resolver or pass the already-known vaultPath.
  • Documentation accuracy. AGENTS.md:359 claims Embedder supports openai-compatible, but embed/provider.go accepts only ollama/vertex. Bare-tag namespaces omit knowledge/* in cli.go:2469-2471, types/tools.go:344, tools/promote.go:39, and AGENTS.md:306, while README.md:448 and server.go:531 include it. ReadSynthesisConfig's GoDoc says environment variables do not override config (llm/config.go:131-133), but DEWEY_SYNTHESIS_API_KEY does. README.md:377 implies doctor probes connectivity for all providers; server.go:492 describes store_compiled as the post-compile path even when server-side synthesis is configured; AGENTS.md:81 omits openai-compatible; design.md:94-96,148-150 diverges from the shipped timeout parser and lock text; .opencode/commands/dewey-distill.md:100 says "item counts" but curate returns files_created; proposal.md:87-88 claims the website issue is filed without a URL; two delta-spec scenarios omit GIVEN (spec.md:286-289,359-364); cli.go:2476 uses a legacy learning identity; the constructor GoDoc omits redirect-block and cleartext-warning behavior (llm/openai_compatible.go:95-102).
  • Website sync bookkeeping. unbound-force/website#371 exists and is accurate but has no docs label, and tasks.md:173-179 omits --label docs from the recorded command.
  • Test gaps in changed guards. URL-encoded key redaction, the 50 MiB response cap, client-timeout behavior, non-429 no-retry attempt counts, endpoint fragment rejection, metadata sanitization for category/confidence/store/source fields, unknown-confidence normalization, literal % resolution, and the tool-level promote rollback mapping are untested.

Low-severity findings

  • vertexSynthRetryDelay now delegates to the shared helper (llm/vertex.go:221-224), changing Retry-After: 0 semantics without a Vertex-specific retry test.
  • No ctx.Err() check between synthesis and publishing, so a cancelled call can still write articles and _index.md (tools/compile.go:265-280).
  • A compile or curate can hold indexMutex for up to roughly six 300-second attempts plus backoff per cluster, with no per-run budget or per-cluster latency log.
  • truncateBody's 512-rune marker is untested; the promote tool-level transaction-rollback mapping is unreachable; RetryAfterZeroIsImmediate relies on a wall-clock bound and the background-curation test uses time.Sleep(50ms).
  • Advisories: redact does not cover JSON-escaped key forms; non-loopback plaintext HTTP only warns while sending the bearer key; the internal hostname api.enmaas.devshift.net is hardcoded across docs and tests; store_compiled/store_learning remain outside the index mutex (pre-existing); buildCompiledArticle writes learning identities unsanitized (pre-existing); .tmp files can survive SIGKILL.

What is working

  • Provider hardening is genuine: redirect refusal via http.ErrUseLastResponse, endpoint rejection of userinfo/query/fragment, default TLS verification, 429-only retry with capped Retry-After and bounded jitter, finish_reason: length as a hard error, a 50 MiB response cap, context cancellation, and key redaction.
  • Server wiring is single-instance and nil-safe: one synthesizer from executeServe, shared by compile, curate, and background curation; absent or unavailable synthesizers fall back to prompt mode.
  • Batch promotion is validate-all-then-mutate with conditional UPDATE ... AND tier='draft' inside a transaction, deduplication, case-insensitive resolution, and the additive pages schema preserves the single-page result shape.
  • Compile uses TryLock and shares the pipeline index mutex without nesting or deadlock; staging plus rename protects the previous file on most failure paths.
  • Tests use httptest, in-memory SQLite, t.TempDir(), and the real MCP in-memory transport; the 37 inherited tools remain unchanged; there are no new dependencies, no CGO, and no schema migration.
  • Acceptance matrix: #133 - 12/12 COVERED; #91 - COVERED.

This review was generated by /uf.review-pr (AI-assisted).

Comment thread tools/compile.go Resolved
Comment thread tools/compile.go Resolved
Comment thread tools/compile.go Resolved
Comment thread curate/curate.go Resolved
Comment thread main.go Resolved
Comment thread llm/openai_compatible.go Resolved
Comment thread tools/compile.go Resolved
Comment thread llm/retry.go Resolved
Comment thread store/store.go Resolved
Comment thread tools/compile.go Resolved
jflowers added a commit to jflowers/dewey that referenced this pull request Nov 4, 2026
…ance

Retry honors Retry-After and cancels between attempts (new retry_test),
provider error bodies are scrubbed of the API key before size bounding
and truncation, the key resolves from DEWEY_SYNTHESIS_API_KEY or
synthesis.api_key with a warning when both are set, finish_reason
length is reported as truncation, and the doctor credential check
explains that the per-vault config is git-tracked.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
jflowers added a commit to jflowers/dewey that referenced this pull request Nov 4, 2026
Replace the store-side FindPage resolution ladder with three narrow
index-backed list queries — ListPagesByNameFoldCase,
ListKnowledgePagesFoldCase (index range instead of per-row LIKE), and
GetPageBySourceDoc — so the store stays resolution-policy-free. Schema
v3 adds idx_pages_name_nocase and idx_pages_source_doc_nocase via an
additive, index-only v2→v3 migration; EXPLAIN QUERY PLAN tests pin
each query to an index SEARCH and a migration test covers v2→v3
(index creation, version bump, data survival, idempotency).

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
jflowers added a commit to jflowers/dewey that referenced this pull request Nov 4, 2026
…ntion

Move page resolution into resolvePromotePage, a tools-side ladder over
the new index-backed store queries (exact, case-insensitive, bare-tag
namespaces with a capped ambiguity list, source doc ids), replacing the
store.FindPage call. Compile retains validated articles through
zero-learnings and full recompiles (retained_validated in results,
never silently destroyed), store_compiled refuses to overwrite a
validated article and suggests a new tag, topic synthesis fails loudly
when page lookups fail, and tag validation moves to the sanitize
package (ValidTag, SafeFrontmatterScalar) for reuse by compile and
curate.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
jflowers added a commit to jflowers/dewey that referenced this pull request Nov 4, 2026
Record the PR 145 amendments across the change and main specs: compile
retains validated articles (zero-learnings and full recompiles report
retained_validated), store_compiled refuses validated overwrite, the
/dewey-distill prompt-mode step notes that refusal, learning
re-ingestion is tier-neutral, prompt-mode byte compatibility is scoped
to non-empty learning collections, and the resolution ladder is
documented as tools-side resolvePromotePage over index-backed store
queries with the additive v3 index migration. The embedded
slash-command map and AGENTS.md recent-changes entry are synced.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
- add an openai-compatible synthesis provider with bounded 429 retry,
  truncation detection, redirect blocking, and credential redaction
- wire one synthesizer into MCP compile/curate and background curation,
  with prompt-mode fallback when unconfigured or unavailable
- share the pipeline index mutex with compile
- add batch promote with all-or-nothing semantics and namespace-aware,
  case-insensitive page resolution (unbound-force#91)
- add the gated /dewey-distill slash command and doctor diagnostics

Refs unbound-force#133
Closes unbound-force#91
- add an openai-compatible synthesis provider with bounded 429 retry,
  truncation detection, redirect blocking, and credential redaction
- wire one synthesizer into MCP compile/curate and background curation,
  with prompt-mode fallback when unconfigured or unavailable
- share the pipeline index mutex with compile
- add batch promote with all-or-nothing semantics and namespace-aware,
  case-insensitive page resolution (unbound-force#91)
- add the gated /dewey-distill slash command and doctor diagnostics

Refs unbound-force#133
Closes unbound-force#91
…ance

Retry honors Retry-After and cancels between attempts (new retry_test),
provider error bodies are scrubbed of the API key before size bounding
and truncation, the key resolves from DEWEY_SYNTHESIS_API_KEY or
synthesis.api_key with a warning when both are set, finish_reason
length is reported as truncation, and the doctor credential check
explains that the per-vault config is git-tracked.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
…ntion

Move page resolution into resolvePromotePage, a tools-side ladder over
the new index-backed store queries (exact, case-insensitive, bare-tag
namespaces with a capped ambiguity list, source doc ids), replacing the
store.FindPage call. Compile retains validated articles through
zero-learnings and full recompiles (retained_validated in results,
never silently destroyed), store_compiled refuses to overwrite a
validated article and suggests a new tag, topic synthesis fails loudly
when page lookups fail, and tag validation moves to the sanitize
package (ValidTag, SafeFrontmatterScalar) for reuse by compile and
curate.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Record the PR 145 amendments across the change and main specs: compile
retains validated articles (zero-learnings and full recompiles report
retained_validated), store_compiled refuses validated overwrite, the
/dewey-distill prompt-mode step notes that refusal, learning
re-ingestion is tier-neutral, prompt-mode byte compatibility is scoped
to non-empty learning collections, and the resolution ladder is
documented as tools-side resolvePromotePage over index-backed store
queries with the additive v3 index migration. The embedded
slash-command map and AGENTS.md recent-changes entry are synced.

Addresses PR unbound-force#145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Consolidate the duplicated knowledge-store indexing into an exported
tools.IndexKnowledgeStore, retire redundant store tier mutators behind
the UpdatePage tier guard, decompose tools-side promote resolution into
focused helpers, harden the openai-compatible synthesis provider, quote
rendered frontmatter scalars, and strengthen compile/lint/curate test
coverage with _index.md retention assertions.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Round 3 of /uf.review-council returned APPROVE WITH ADVISORIES from
all five reviewers (adversary, architect, curator, guard, testing)
with zero REQUEST CHANGES findings, satisfying task 7.7. The 23
advisory findings are recorded as follow-ups; no code changed after
the reviewed commit c71a329.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Restore the 017 union behaviors dropped by the rebase (compile and
curate unavailable_reason reporting, the gateway synthesis endpoint
fallback, and the doctor degradation tests), reduce the openaicompat
transport to embedding-only, record the 017 synthesis supersession in
the delta spec, design decisions, and credential documentation, align
every promote resolution ladder description, harden the compiled_by
frontmatter gate and clearCompiled logging, and add retry-backoff,
promote rollback, re-ingestion precedence, and synthesis doctor
regression tests.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Round 5 of /uf.review-council returned APPROVE WITH ADVISORIES from all
five reviewers (adversary, architect, curator, guard, testing) with zero
REQUEST CHANGES findings, on commit 707d695.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
Replace bare defer s.Close() and defer rows.Close() with the repo's
established defer func() { _ = x.Close() }() convention so errcheck
(passed by MegaLinter on CI) no longer flags the unchecked error
returns.

Addresses the MegaLinter failure on PR unbound-force#145.
@jflowers
jflowers merged commit 7f365ba into unbound-force:main Nov 5, 2026
2 checks passed
jflowers added a commit that referenced this pull request Nov 5, 2026
…ance

Retry honors Retry-After and cancels between attempts (new retry_test),
provider error bodies are scrubbed of the API key before size bounding
and truncation, the key resolves from DEWEY_SYNTHESIS_API_KEY or
synthesis.api_key with a warning when both are set, finish_reason
length is reported as truncation, and the doctor credential check
explains that the per-vault config is git-tracked.

Addresses PR #145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
jflowers added a commit that referenced this pull request Nov 5, 2026
…ntion

Move page resolution into resolvePromotePage, a tools-side ladder over
the new index-backed store queries (exact, case-insensitive, bare-tag
namespaces with a capped ambiguity list, source doc ids), replacing the
store.FindPage call. Compile retains validated articles through
zero-learnings and full recompiles (retained_validated in results,
never silently destroyed), store_compiled refuses to overwrite a
validated article and suggests a new tag, topic synthesis fails loudly
when page lookups fail, and tag validation moves to the sanitize
package (ValidTag, SafeFrontmatterScalar) for reuse by compile and
curate.

Addresses PR #145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
jflowers added a commit that referenced this pull request Nov 5, 2026
Record the PR 145 amendments across the change and main specs: compile
retains validated articles (zero-learnings and full recompiles report
retained_validated), store_compiled refuses validated overwrite, the
/dewey-distill prompt-mode step notes that refusal, learning
re-ingestion is tier-neutral, prompt-mode byte compatibility is scoped
to non-empty learning collections, and the resolution ladder is
documented as tools-side resolvePromotePage over index-backed store
queries with the additive v3 index migration. The embedded
slash-command map and AGENTS.md recent-changes entry are synced.

Addresses PR #145 review feedback from @jflowers.

Signed-off-by: Jay Flowers <[email protected]>
Assisted-by: glm-5
@jflowers
jflowers deleted the opsx/dewey-distill branch November 15, 2026 20:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant