# Foundry Knowledge Engine (FKE) Persistent memory for the Foundry and every project it generates: PostgreSQL with pgvector for facts, semantic search, graph links and session progress, reached only through the `Foundry.Knowledge` PowerShell module. Agents follow [skills/knowledge-management/SKILL.md](../skills/knowledge-management/SKILL.md); the mandatory policy is in [AGENTS.md](../AGENTS.md) and in every generated project's `AGENTS.md`. ## Set up (once) Needs Docker, PowerShell 7 and an Ollama with the `nomic-embed-text` model (768 dimensions). ```powershell pwsh -File scripts/Initialize-Foundry.ps1 # creates .env (random password), starts PostgreSQL, applies migrations, runs the health check ollama pull nomic-embed-text # if the health check says the model is missing pwsh -File scripts/Start-Foundry.ps1 # later sessions: start the container pwsh -File scripts/Stop-Foundry.ps1 ``` Ollama: the module uses an Ollama already running on the host (`http://localhost:11434`, override with `FOUNDRY_OLLAMA_URL`). `docker-compose.yml` also defines an optional Ollama container behind the `ollama-container` profile on port **11435** (not 11434, which a host Ollama usually holds): `pwsh -File scripts/Start-Foundry.ps1 -WithOllamaContainer`, then `$env:FOUNDRY_OLLAMA_URL='http://localhost:11435'` and `docker exec foundry-ollama ollama pull nomic-embed-text`. ## Using it ```powershell Import-Module ./powershell/Foundry.Knowledge/Foundry.Knowledge.psd1 # in a generated project: . ./tools/knowledge.ps1 Test-FoundryKnowledge Search-FoundryKnowledge -Query "C128 memory banking" -MaxTokens 3000 -IncludeRelated -AsJson ``` | Command | Purpose | |---|---| | `Add-FoundryKnowledge`, `Add-FoundryLesson`, `Add-FoundryDecision` | Store knowledge (refuses duplicates and credentials) | | `Search-FoundryKnowledge` | Hybrid vector + keyword search, graph expansion, token budget | | `Get-FoundryKnowledge`, `Update-FoundryKnowledge` | Read in full; correct or supersede | | `Add-FoundryRelationship`, `Get-FoundryRelationships` | Graph links and traversal | | `Start-FoundrySession`, `Save-FoundrySession`, `Resume-FoundrySession` | Session memory | | `Set-FoundryProjectContext`, `Get-FoundryProjectContext` | Default project key | | `Test-FoundryKnowledge`, `Update-FoundryDatabase` | Health check, migrations | | `Backup-FoundryKnowledge`, `Restore-FoundryKnowledge` | `pg_dump` to `backups/` (ignored by Git); restore needs `-Force` | ## Design - **One shared database** in the Foundry (Docker volume `foundry_postgres_data`). Entries with no `project_key` are global; generated projects write under their slug and read their own plus global. - **Generated projects depend on it for memory only.** Their `AGENTS.md` requires using it, but `tools/build.ps1`, `smoke.ps1` and the other scripts never touch it, and an agent that cannot reach it must say so and carry on. A generated repo finds the Foundry through `FOUNDRY_HOME`, else `generated.foundryRoot` in `project.json` (the Foundry's path at generation time). - **Layers:** public commands (input, orchestration) -> `Private/Domain.ps1` (rules: types, secrets guard, verified-needs-source, scope) -> `Private/Infrastructure.ps1` (PostgreSQL via `psql` in the container; embeddings via Ollama, replaceable behind `Get-FkeEmbedding`). - **Safe SQL without a driver:** values never enter SQL text. They travel as one JSON payload in a randomly tagged dollar-quoted literal and are read in SQL with `current_setting('fke.p')::jsonb`. Tested with quotes, backslashes, `$tag$`, unicode and a `DROP TABLE` title. (A native driver such as Npgsql was not used, to avoid installing anything on Windows.) - **Graph:** native `relationships` table with recursive queries (cycle-safe). Apache AGE is not used. - **Search ranking:** reciprocal-rank fusion (k=60) of the semantic and keyword rankings, scaled by `0.5 + 0.5 x confidence`; ties go to the more recently updated entry. Freshness is only a tie-breaker. Superseded entries are excluded. If Ollama is unreachable, search is keyword-only and says so (`mode`). - **Token budget:** `-MaxTokens` (default 3000; 0 = unlimited) uses a rough 4-characters-per-token estimate, not a tokenizer. The top result is always returned; `omittedForBudget` counts what was cut. - **Migrations:** `infrastructure/postgres/migrations/NNN-*.sql`, applied in order and recorded in `knowledge.schema_migrations` by `Update-FoundryDatabase`. (No Docker `initdb.d` script is used, so there is a single schema source.) ### Tunable values (defaults came from one measurement; adjust with evidence) | Setting | Default | Basis | |---|---|---| | `-DuplicateThreshold` (Add) | 0.80 | With `nomic-embed-text`, the same text under a different title scored 0.833, a reworded version 0.764, an unrelated entry 0.416 (2026-12-02, three samples). A same-title entry is always a duplicate. | | `-MinSimilarity` (Search) | 0 (off) | Query vs. relevant entry scored 0.57, vs. unrelated 0.35 in one test. Vector search returns the nearest entries even when none are relevant, so judge `similarity`; raise this to cut weak matches. | | `-MaxTokens`, `-ContentChars` | 3000, 500 | Starting values, not measured. | Changing the embedding model to one with a different dimension needs a new migration (the column is `VECTOR(768)`). ## Loading reference books `scripts/Import-ReferenceKnowledge.ps1 -Path ` loads reference text as **global** `technical-fact` entries (one JSON object per line: `title`, `content`, `source`, `tags`, `confidence`). Entries carry the book and PDF page as `source`, so `-Status verified` means "cited documentation", not "tested on hardware". Re-running skips titles already stored. The PDFs and the extracted JSONL live in `import/` (Git-ignored). The C64/C128 set (2026-12-02) came from `pdftotext -layout` on the PDFs in `import/`: | Book | Stored as | |---|---| | Mapping the Commodore 64 | one entry per memory location/range (title starts `C64 memory map ($hex) NAME`), long entries split in parts; confidence 0.85 | | Anatomy of the C64, Machine Language Book, Advanced ML Book, Anatomy of the 1541, Tool Kit: Kernal, Tool Kit: BASIC | section chunks of about 2,800 characters titled with the nearest heading and PDF page; confidence 0.7 (OCR noise remains) | Not loaded: *The Complete C64 ROM Disassembly* (OCR too corrupt to trust), *Invaluable Utilities* (mostly program listings and advertising), *Compiler Design and Implementation* (compiler theory, not platform reference). Chunks that were mostly code listings or OCR garbage were dropped by a quality filter. Search by the task's own words, for example `Search-FoundryKnowledge -Query "VIC-II sprite multicolor registers"`. ## Verification status Run on 2026-12-02, Windows, Docker 29.8.2, `pgvector/pgvector:pg16` (pgvector 0.8.7), host Ollama with `nomic-embed-text` (768 dimensions): ```powershell pwsh -File tests/Knowledge.Tests.ps1 # scratch database, dropped afterwards; your data is untouched ``` 17 checks: migrations (apply, re-apply), hostile-text round trip, domain rules, deduplication (title and embedding), semantic search without shared keywords, keyword-only fallback with Ollama down, project scoping, verified/type filters and updates, graph traversal (cycle, direction, depth, type), graph expansion in search, supersede, token budget, lessons/decisions, sessions, backup/restore, health check with a missing dependency. Not covered: Apache AGE (not implemented), large datasets and index tuning (tests use a few dozen rows), concurrent writers, restore into a different PostgreSQL major version, Pester (this machine has only Pester 3.4; the tests use the same check-runner style as `tests/Run-FoundryTests.ps1`), behavior of a real coding agent following the skill (not yet observed).