[{"content":"A short report on Studies A to D of the agent-rule-compliance project. It continues the first post.\nA project has rules that its tests do not always examine. An architecture decision says \u0026ldquo;send webhooks through this function\u0026rdquo;. A security rule says \u0026ldquo;this record stays restricted after the customer is deleted\u0026rdquo;. When does an AI coding agent break such a rule, and what prevents it?\nI did four studies with 588 agent runs on a real codebase. The short answer:\nIf the code near the change breaks the rule, the agent breaks it again, in almost every run. The tests that the project has do not prevent this. One test written for the rule prevents it each time. A static check finds only one violation in four. But it finds the old wrong code before the change. One sentence at that old wrong code (\u0026ldquo;this breaks a rule, do not copy it\u0026rdquo;) prevents most violations. The setup Codebase: saleor, a large open-source shop system with written architecture decisions. Rules: six rules from those decisions. Three name a code form (for example \u0026ldquo;use pk, not id\u0026rdquo;). Three are about behaviour (for example \u0026ldquo;a gift card balance change must be atomic\u0026rdquo;). Agents: Claude Haiku and Claude Sonnet, with no project documentation. They could read all the code. Grading: hidden tests. Each grader was proven before the runs: it fails on the base, it passes on a correct solution, and it finds a solution that does the task but breaks the rule. The hypotheses, the tasks and the analysis of each study were published before its first run. Study A: what causes the violation 21 tickets. Each rule has a ticket at a site where the near code follows the rule, has no example, or breaks the rule. 210 runs.\nCode near the change Runs that broke the rule, Haiku Runs that broke the rule, Sonnet Follows the rule 17% 17% No example 23% 13% Breaks the rule 87% 97% A wrong precedent is copied. The difference is 70 points for Haiku and 80 points for Sonnet. A stronger model does not help. A missing precedent is not the problem. The risk is a wrong one. Among runs that did the task correctly, 0 of 117 broke a rule at sites without a wrong precedent. At sites with a wrong precedent, 37 of 42 broke it. Study B: what prevents it The six tickets with a wrong precedent. Each agent got nothing, the project tests to run, the rule text, or a test written for the rule. 234 runs.\nWhat the agent gets Haiku Sonnet Nothing 87% not tested The project tests to run 83% 83% The rule text from the project documentation 20% 22% A test written for the rule 0% 0% The project tests prevent almost nothing. They pass, because they do not examine the rule at the new place. The agent takes the pass as confirmation. The rule text helps much, but not always. It failed most where the near code was a strong opposite example. A rule test prevented all violations, and it was not more expensive. The agents read the failure and corrected the code. Study D: can a general static check find the violations? A fresh agent wrote one static check for each rule. It saw only the rule texts and the codebase, not the tickets or the results. I ran the checks one time on all 444 runs of Studies A and B.\nOn the changed lines, the checks found 26% of the 156 violations. One rule had 100%. One had 0%. 39% of the violations come from old code in the touched file. The agent did not write the forbidden form. It used a value from an old line that contains it. A check of the changed lines cannot see this. 35% have no static form. \u0026ldquo;The card stays restricted\u0026rdquo; is not a code pattern. Only a test found these. But the same checks find the wrong precedent before the change, for four of the six rules. Study C: tell the agent about the wrong precedent The six tickets again. Each agent got nothing, a two-line comment above each piece of old wrong code, or the same text in the ticket with a list of the places. The comment says: \u0026ldquo;the code below breaks a project rule and stays only until it is repaired. Do not copy it\u0026rdquo;, and the rule in one sentence. 144 runs.\nWhat the agent gets Haiku Sonnet Nothing 87% 94% A comment at the old wrong code 20% 18% The same text in the ticket, with the places 7% 33% The two measures are as effective as the full rule text, and a tool can make them. For the four rules where the static check found the places, both models had 0 to 2 violations in each group with a measure. Without it, they broke the rule in every run. With the text in the ticket, Haiku also repaired the old code in all 20 such runs. The precedent is then gone for the next change too. The change was larger, and a team must expect that. The measures fail when the agent uses the old code without a copy of its form. The comment said \u0026ldquo;do not copy\u0026rdquo;, and the agent did not copy. It used a variable from the marked line. What this means in practice An agent treats the near code as the specification. Each old violation is an instruction to the next agent. \u0026ldquo;The agent ran the tests and they passed\u0026rdquo; is not evidence that the change obeys the rules of the project. The order of measures that these studies support: Make the important rules executable. A test for the rule was the only measure with 0%. Scan for old violations and mark or repair them. This is cheap, a tool can do most of it, and it removes most of the risk. Document the rule. The text helps, but less than the two measures above. Do not expect a stronger model to solve this. In these studies it did not. Limits One codebase, one language and six rules. The intervals are over rules, and six is a small number. The models are from one supplier, and the author of the static checks also. Each rule test was written with knowledge of the ticket. A real project must write it before the change. In Study C the places of two rules were given by hand. The Sonnet parts are small: 3 runs for each ticket and group. An error in my test tooling made the first 36 Sonnet runs with a test command in Study B not valid. I did them again. This is not in the published plan. The report describes it, and the first attempts are public. Next All four studies looked at one change at a time. The next question is about time: does one violation make the next one more probable through a chain of changes, and do the measures above stop that?\nThe data, the graders, the checks, the analysis and the tool-call logs of all runs are public: github.com/mohaqeq/agent-rule-compliance. The full reports are in research/docs, documents 12 to 15.\nThe task authors, the coding agents, the author of the static checks and most reviewers in these studies were Claude models (Haiku, Sonnet, Opus, Fable).\n","permalink":"https://mohaqeq.github.io/posts/2026-11-agents-repeat-the-wrong-precedent/","summary":"Four pre-registered studies, 588 agent runs: agents copy the wrong precedent near a change, the project tests do not stop it, a test for the rule does, and one sentence at the old wrong code prevents most violations.","title":"Coding agents repeat the wrong precedent. Here is what stops them"},{"content":"Every team that uses coding agents ends up writing the same file. It\u0026rsquo;s called AGENTS.md, CLAUDE.md or .cursorrules: a few kilobytes of prose that say \u0026ldquo;the API layer must not import the CLI\u0026rdquo;, \u0026ldquo;never use Django signals\u0026rdquo;, \u0026ldquo;gift cards are bearer instruments\u0026rdquo;. The agent is supposed to read it and behave.\nProse is ambiguous, it drifts from the code, and it costs tokens on every run. So I asked a question that seemed obviously worth asking:\nCan a formal, compact language for requirements, architecture and decisions make coding agents follow them better than prose does?\nI spent a few weeks building that language, a checker for it, and the experiments to test it. The result was negative, and I think the reason is more interesting than the language.\nWhat I built UCN (Unified Context Notation) is a line-oriented text format. It sits on top of existing ideas rather than replacing them: C4-style containers and components, EARS-style requirements, ADR-style decisions and design-by-contract rules. A model looks like this:\ncomponent Api: public Python API code: sqlfluff/api/** forbids Cli convention NoDjangoSignals: call logic explicitly, never through signals check: only saleor/*/{migrations/**,apps.py} imports django.db.models.signals req PaymentHistoryProjection: customers see payment history only through an allowlisted projection rationale: docs/adr/0010-order-payment-history-is-a-projection.md deviation ErrorsTypeImports: errors may import rules, for type checking only expires: 2027-11-01 It comes with three tools:\nA deterministic validator that checks the model against the code: the import graph, conventions, links from requirements to tests, expiring deviations, and conflicts between what the docs say and what the code does. A projector that cuts a task-specific slice of the model to fit a token budget, and names everything it leaves out. An exporter that compiles the same rules to import-linter and dependency-cruiser configs. The idea was simple: give the agent the projection and the validator, and it will do better than with a wall of prose.\nThe tools worked Before any agent experiment, I pointed the validator at real repositories. It found real problems:\nsqlfluff: its own AGENTS.md says never import dialect modules directly. 12 modules do. Neither the docs nor the project\u0026rsquo;s import-linter contracts catch this. excalidraw: circular, undeclared runtime dependencies between published packages. Agreement with the established tools: run in containers against the real import-linter and dependency-cruiser, the exported configs gave identical results, after five bugs that only running the real tools could expose. Upkeep: replaying 600 commits of sqlfluff history, a deny-list model needed zero edits. So the checker is real. The question was whether the context helps agents.\nExperiment 1: the pilot (60 runs) I pre-registered the hypotheses and decision rules, then ran a pilot on sqlfluff:\nTasks: 12, written by a different model that had never seen UCN. 9 were \u0026ldquo;tempting\u0026rdquo;: the obvious implementation breaks an architecture rule. Graders: each task had a hidden grader, proven to fail on the unchanged code and to pass on a reference solution. Arms: a Claude Haiku agent got one of three setups: nothing; the project\u0026rsquo;s AGENTS.md plus import-linter in the loop; the UCN projection plus the validator in the loop. Arm Success Rule breaks (tempting tasks) Median tokens No docs 11/12 1 of 9 44.8k AGENTS.md + import-linter 24/24 0 of 18 55.2k UCN + validator 24/24 0 of 18 51.1k By my own pre-registered rules, UCN was \u0026ldquo;supported\u0026rdquo;: as successful, no more violations, cheaper. Then two independent reviews pointed out what I should have seen myself:\nA ceiling. Both checked arms were perfect, and even the no-docs agents almost never broke a rule, so the hypotheses could not fail. The token saving was just size. The UCN context was 2 KB, the AGENTS.md files 65 KB. Not the hard cases. The tasks only tested rules import-linter already enforces. I rewrote the conclusion: inconclusive.\nExperiment 2: a codebase where requirements matter (42 runs) The obvious objection was that sqlfluff is a developer tool with technical rules. UCN should shine where product requirements and architecture decisions decide what is correct. So I scanned 31 repositories for customer-facing products with written decisions, and picked saleor, an e-commerce API with ADRs like these:\nA gift card is a bearer instrument. Rejecting a restricted card must never reveal who it belongs to. Customer payment history is an allowlisted projection, never the raw transaction. Balance changes must be atomic; never read, decide and write back. Never use Django signals. Never read settings.SITE_ID. These are exactly the rules an agent cannot infer from types or imports. I modelled all 12 ADRs, linked them to 253 of saleor\u0026rsquo;s tests as evidence, and had two separate model instances write 20 tasks whose shortcuts break those rules.\nThis time every grader had to pass three checks in a container:\nthe behaviour tests fail on the unchanged code; the reference passes everything; a deliberately naive shortcut passes the behaviour tests but fails a rule test. A model from a different family (Nemotron, via OpenRouter\u0026rsquo;s free tier) reviewed every grader for assertions the ticket did not justify. The task hashes were committed before any run.\nThe pre-registration included a screen. First, run agents with no docs at all, 3 times per tempting task, and keep only the tasks where they break the rule at least twice. Only then compare the arms.\n2 of 14 tasks survived the screen. Agents with no AGENTS.md and no ADRs kept the documented rules in 27 of the 33 runs where a rule could be measured, and broke one in only 6. (In the other 9 runs, the grader review had removed every rule test.) The experiment stopped there, as pre-registered.\nWhy: the agents read the code The interesting part is how they kept rules they had never been told:\nRace-safe balance updates: the agent found saleor\u0026rsquo;s existing gift_card_qs_select_for_update helper and used it. \u0026ldquo;No signals\u0026rdquo;: the agent called the new logic explicitly from the existing balance paths, because that is what the surrounding code does. A new management command: the agent created the related settings row explicitly, not through a post_save hook. The task authors expected the shortcut: a signal, a read-modify-write loop, a module-level cache. An agent that reads the code next to its change doesn\u0026rsquo;t take it. In a well-kept codebase, the correct pattern sits right where the change goes, and the code itself is the context.\nAcross three repositories (sqlfluff, cosmicpython, saleor) I saw the same thing:\nThe code is the strongest context. Agents copy local patterns. A rule that the surrounding code already follows needs no documentation for an agent. When a rule does get broken, a check catches it. In every experiment, the arm with a checker in the loop had zero violations, whether the checker was import-linter or UCN\u0026rsquo;s validator. The checker did the work, not the context. Shorter context is cheaper. That\u0026rsquo;s true, but any tight summary would do; it isn\u0026rsquo;t an argument for a new notation. What I kept UCN is now a checker and governance tool, not an agent-context format. That part solved real problems in every trial:\nOne file for the rules, compiled to import-linter and dependency-cruiser configs. Checks for rules that are not imports: only \u0026lt;glob\u0026gt; uses \u0026lt;regex\u0026gt;, convention checks, and requirements linked to test results. Governance the existing tools lack: approved deviations that expire, and recorded conflicts between docs and code. What I\u0026rsquo;d still like to know Guidance could still matter where there is no good code to copy:\nEroded codebases, where the code next to a change shows the wrong pattern. Greenfield work, where nothing exists yet. Weaker agents. Rules whose correct pattern lives far from the change. The harness for testing that is ready and published: pinned tasks, proven graders, cross-model grader review and screening.\nLessons about running these experiments Pre-register, but make a ceiling count as \u0026ldquo;inconclusive\u0026rdquo;. My first decision rules turned \u0026ldquo;nothing happened\u0026rdquo; into \u0026ldquo;supported\u0026rdquo;. Screen before you compare. Forty-two cheap runs saved me from about 150 runs comparing arms on tasks nobody fails. Prove the temptation. A grader must fail on a naive shortcut, or you\u0026rsquo;re measuring nothing. Get a reviewer from another model family. Same-model authors and reviewers share blind spots. Publish the tool-call logs. \u0026ldquo;The agent ran the checker\u0026rdquo; should be something anyone can verify. Everything is open: the tool, the format, both pre-registrations, all 32 tasks with their hidden graders, the results, and the agents\u0026rsquo; tool-call logs. See github.com/mohaqeq/unified-context-notation.\nThe task authors, agents and most reviewers in these experiments were Claude models (Haiku, Sonnet, Fable). One grader review used Nvidia Nemotron.\nCorrection (2026-11-11): an earlier version said the no-docs agents kept the rules in \u0026ldquo;33 of 42 runs\u0026rdquo;. The right figure is 27 of the 33 runs where a rule could be measured (6 broke a rule; in 9 runs every rule test had been excluded by the grader review).\nFollow-up (2026-11-18): the next four studies test the \u0026ldquo;eroded codebase\u0026rdquo; case. See Coding agents repeat the wrong precedent. Here is what stops them.\n","permalink":"https://mohaqeq.github.io/posts/2026-11-agents-already-read-the-code/","summary":"Three pre-registered experiments, about 130 agent runs: a formal context language didn\u0026rsquo;t make coding agents follow architecture rules better, because they already read the code.","title":"I built a context language for AI coding agents. Three experiments said they didn't need it"},{"content":"Architecture tools usually start from a rule you have already written down. ArchUnit, import-linter and dependency-cruiser are excellent at enforcing \u0026ldquo;the domain must not import the web layer\u0026rdquo;. But when you open an unfamiliar codebase, the first question is different: what architecture does this actually have? Is it layered, hexagonal, a modular monolith or a big ball of mud? Where does it break its own pattern?\nI built architectural-pattern-auditor to answer that. It is a Claude Code agent skill, but every step is a plain script you can run without an AI.\nWhat it produces Two files: architecture-audit.md for humans and architecture-audit.json for tools. Findings are grouped in three levels:\nMacro, the system shape: monolith, modular monolith, microservices, event-driven, hexagonal, clean/onion, layered, CQRS, event sourcing, serverless, plugin architecture and more. Meso, components: MVC/MVVM/MVP, repository, unit of work, service layer, DDD aggregate, saga, outbox, circuit breaker, strangler fig, API gateway and others. Micro, idioms: the classic design patterns (factory, builder, strategy, observer, decorator, adapter…) and dependency injection. It also looks for anti-patterns: big ball of mud, distributed monolith, anemic domain model, god object, circular dependencies, layering violations, leaky abstractions, shotgun surgery and feature envy.\nHow it works A pipeline of five scripts:\npython scripts/scan_repo.py --root \u0026#34;$ROOT\u0026#34; --mode quick --out \u0026#34;$OUT\u0026#34; python scripts/build_import_graph.py --root \u0026#34;$ROOT\u0026#34; --out \u0026#34;$OUT/graph.json\u0026#34; python scripts/detect_layers.py --graph \u0026#34;$OUT/graph.json\u0026#34; --out \u0026#34;$OUT/layers.json\u0026#34; python scripts/detect_patterns.py --root \u0026#34;$ROOT\u0026#34; --inventory \u0026#34;$OUT/inventory.json\u0026#34; \\ --graph \u0026#34;$OUT/graph.json\u0026#34; --layers \u0026#34;$OUT/layers.json\u0026#34; --out \u0026#34;$OUT/findings.json\u0026#34; python scripts/render_report.py --findings \u0026#34;$OUT/findings.json\u0026#34; --template templates/audit-report.md.j2 ... It inventories the repository, builds an import graph across 13 languages (Python, TypeScript/JavaScript, Java, Kotlin, Scala, Groovy, Go, Rust, C#, Ruby, PHP, Swift, Dart), infers layers from the graph, and then runs structural checks per pattern. --mode quick uses folder and name heuristics for a first pass; --mode deep runs the full per-file checks.\nConservative by design The easiest way to make a tool like this useless is to let it guess. So it has three rules:\nNo pattern without two independent structural signals. A folder called domain/ alone proves nothing. Every \u0026ldquo;Incorrect\u0026rdquo; verdict carries file:line evidence, so a human can check it in seconds. Degradation is visible. It works offline and degrades gracefully: without ripgrep it uses a pure-Python grep; without networkx, a bounded depth-first search for cycles; without jinja2, a small built-in template engine. Every fallback is recorded in the findings and shown in the report\u0026rsquo;s appendix, so you know how much to trust a run. Why it\u0026rsquo;s a skill Inside Claude Code you can just ask: \u0026ldquo;audit the architecture of this repo\u0026rdquo;, \u0026ldquo;is this hexagonal?\u0026rdquo;, \u0026ldquo;find architectural anti-patterns\u0026rdquo;. The agent runs the scripts and reads the evidence. The deterministic scripts do the detecting, and the model explains the results. Per-language cheatsheets of idiomatic signals and a pattern catalogue ship with the skill as references.\nWhere it fits This is the discovery half of architecture work. Enforcement is the other half, and I explored it later in a much larger experiment: a checked notation for rules and decisions. Discover first, then write down the rules you want to keep, then let a checker hold the line.\n","permalink":"https://mohaqeq.github.io/posts/2026-05-architectural-pattern-auditor/","summary":"An agent skill that finds the architectural patterns and anti-patterns a repository actually has, across 13 languages, and grades each one with file:line evidence.","title":"Discovering a codebase's architecture instead of declaring it"},{"content":"Children today usually have a phone or tablet long before they have a laptop. So instead of asking \u0026ldquo;do you have a computer?\u0026rdquo;, I wrote a game-programming tutorial that runs where they already are: on Android, in Pydroid 3, with Pygame Zero.\nIt\u0026rsquo;s in German, because it was written for German-speaking kids: mohaqeq/pygame-zero-tutorial.\nWhy Pygame Zero Pygame Zero removes almost all boilerplate. You define draw() and update(), and the framework runs the game loop. A child\u0026rsquo;s first program draws something within minutes, which is what keeps them going. Touch input maps onto the mouse events, so the same code works on a phone screen.\nTwo parts, thirteen games Part 1: Basics, no images needed. Every game is drawn with shapes, so there are no assets to download or lose:\nDrawing shapes Understanding touch input Fang den Ball (catch the ball) A jumping box, like the Chrome dinosaur Flappy Box, like Flappy Bird Ping pong against the computer Breakout On-screen buttons for control Part 2: Images and sound. Once the logic makes sense, sprites and sounds make it feel like a \u0026ldquo;real\u0026rdquo; game:\nFlappy Bird with images Collecting coins A space shooter Ping pong with effects Animations How the material is built One idea per game. Each game adds one concept: coordinates, then input, then collision, gravity, a computer opponent, buttons. Games kids already know. Recreating a dinosaur jump or Flappy Bird gives them an immediate goal and a way to judge whether it works. Shapes before sprites. Part 1 needs no images at all, so nothing can go wrong with files on a phone. Short, readable code with German comments, meant to be typed in and changed, not just run. If you know a German-speaking kid with a phone and some curiosity, the tutorial starts with Tutorial_Teil1_Grundlagen.md.\n","permalink":"https://mohaqeq.github.io/posts/2026-01-pygame-zero-tutorial/","summary":"A German-language tutorial for children: thirteen small Pygame Zero games that run on an Android phone with Pydroid 3, from drawing shapes to a space shooter.","title":"Teaching kids to make games on a phone (in German)"},{"content":"Port operations have a planning problem that looks simple and isn\u0026rsquo;t. Vessels arrive, occupy a stretch of quay for a while, and leave. Two ships cannot overlap in space and time, and the plan changes all day. Planners need a board where they can see the quay over time and move things with the mouse.\nI built such a board as a reusable web component: mohaqeq/berthing-schedule, with a live demo at berthing.netlify.app.\nWhat it does A Gantt-like view of the quay: berths (and bollards) along one axis, time along the other, and each vessel call as a box. Drag and drop: move a vessel to another berth or time, or resize it to change arrival and departure. More than ships: non-working periods such as maintenance or planning blocks are items on the board too. Guard rails: lock options, voyage timing management and automatic timing adjustments keep the plan consistent while you edit it. Navigation: keyboard control, zoom from 0.5× to 2×, and scroll tracking. An event log shows what happened. Styling from outside: berths, bollards, timeline periods and colours are configurable, and the look is themed with CSS custom properties. Why a web component The board had to drop into any host application, whatever framework it uses, or none. A native custom element does exactly that. The host writes \u0026lt;berthing-schedule\u0026gt;, sets properties and listens to events.\nLit makes custom elements pleasant without turning them into a framework. The component is split into small parts: quay-panel, timeline-panel, grid-lines, corner-box and vessel-box, composed by the main berthing-schedule element. Types live in one types.ts. TypeScript targets ES2022, and Vite serves the demo and builds the bundle.\nThings that were harder than expected Time and pixels are two coordinate systems. Every drag, resize and zoom converts between them. Keeping one well-tested conversion in one place avoids off-by-one-hour bugs. Drag-and-drop must respect the domain, not just the mouse: locked items, minimum durations, and what happens to the next voyage when you stretch this one. Two scroll axes plus zoom in a grid with fixed headers is a classic source of misaligned rows. Separate panels with synchronised scrolling worked better than one giant scrolling element. Try it npm install npm run dev # the demo page npm run build # the distributable component ","permalink":"https://mohaqeq.github.io/posts/2026-01-berthing-schedule/","summary":"A Gantt-like, drag-and-drop schedule of vessels at a port\u0026rsquo;s berths, built with Lit and TypeScript as a standards-based custom element.","title":"A berth planning board as a native web component"},{"content":"Most retrieval-augmented generation (RAG) examples start by sending your documents to someone else\u0026rsquo;s API. I wanted the opposite: a service I could point at private PDFs, where nothing leaves the machine. The result is mohaqeq/local-rag: a Kotlin service built on Ktor, using Ollama for the models and PostgreSQL with pgvector for the embeddings.\nThe pieces Piece Role Ktor The HTTP service: POST /embed to ingest a PDF, a query endpoint to ask questions Ollama Local inference: mxbai-embed-large for embeddings, qwen3 for answers (both configurable) PostgreSQL + pgvector Stores chunks with their embeddings; similarity search in SQL Docker Compose Starts the database, and optionally Ollama with the models pre-pulled The code is split along those lines: clients/ for Ollama, the PDF processor and pgvector, and services/ for the embedding and query flows. Ktor modules hold routing, serialization, monitoring and the API docs.\nIngestion POST /embed takes a PDF upload. The text is extracted and cut into fixed-size chunks with a small overlap (7,500 characters with 100 characters of overlap by default, both in application.yaml). The overlap keeps a sentence that straddles a boundary from being lost to both chunks. Each chunk is embedded and stored in pgvector.\nAnswering: query expansion A single embedding of the user\u0026rsquo;s question is a fragile search key. If the document phrases things differently, distance search misses it. So the query service first asks the local model for five rephrasings of the question, from different perspectives. It embeds each one, takes the top 3 chunks for each, and merges them into one de-duplicated context. Only then does it ask the model to answer from that context.\nIf nothing relevant comes back, the service says so (\u0026ldquo;I couldn\u0026rsquo;t find any relevant information…\u0026rdquo;) instead of letting the model improvise. For a document Q\u0026amp;A tool, that is the most important line of code.\nRunning it docker compose --profile ollama up -d # Postgres + Ollama (pulls the models on first start) ./gradlew run # the service on http://localhost:8080 curl -X POST http://localhost:8080/embed -F \u0026#34;file=@document.pdf\u0026#34; If Ollama already runs elsewhere, start only the database and point ollamaBaseUrl at it.\nWhat I learned Local is good enough for many document tasks. A mid-size local model with decent retrieval answers factual questions about your own documents well. The quality ceiling is retrieval, not the model. Query expansion is cheap and effective. One extra generation call buys noticeably better recall than tuning chunk sizes. Postgres is a fine vector store. pgvector keeps embeddings next to everything else you already know how to back up and query. The boring parts matter: long request timeouts for big PDFs, a temp folder for uploads, and clear errors for non-PDF files. ","permalink":"https://mohaqeq.github.io/posts/2025-12-local-rag/","summary":"Upload PDFs, ask questions, keep everything on your machine: a small retrieval-augmented generation service with query expansion and no external API calls.","title":"A fully local RAG service with Kotlin, Ktor, Ollama and pgvector"},{"content":"There\u0026rsquo;s a particular joy in writing a program whose output is a picture. A ray tracer is one of the best examples: a few hundred lines of vector maths, and suddenly there are glass spheres reflecting each other on your screen.\nI worked through the first book of Peter Shirley\u0026rsquo;s Ray Tracing in One Weekend series in Kotlin rather than the book\u0026rsquo;s C++. The code is on GitHub: mohaqeq/kotlin-raytracer.\nThe shape of the code The book\u0026rsquo;s structure maps nicely onto small Kotlin files:\nFile What it holds Ray.kt A ray: origin, direction, and the point at distance t Hittable.kt, Sphere.kt Things a ray can hit; a sphere is the only primitive the first book needs Collision.kt The record of a hit: point, normal, which side of the surface, material Material.kt How light scatters: diffuse (Lambertian), metal and dielectric (glass) Camera.kt Field of view, position and defocus blur Main.kt The scene and the render loop Kotlin was a good fit. Data classes and operator overloading make the vector maths read almost like the book\u0026rsquo;s formulas (a + b * t instead of a.add(b.mul(t))). Sealed hierarchies keep materials honest.\nOutput: the humble PPM Like the book, the renderer writes a PPM file (image.ppm): a header followed by plain RGB triples. It\u0026rsquo;s the simplest image format there is, so there\u0026rsquo;s no dependency between you and the first picture. Any image viewer, or a one-line conversion, turns it into a PNG.\nMaking the final scene bearable The final scene of the first book, with many small spheres, antialiasing samples per pixel and several bounces per ray, is slow when rendered on one core. Rows of pixels are independent, so the render loop hands them to a FixedThreadPool sized to the number of available CPUs, then writes the rows back in order. It is the easiest speed-up in the whole project, and a nice reminder that \u0026ldquo;embarrassingly parallel\u0026rdquo; really is a technical term.\nRunning it ./gradlew run # writes image.ppm The state at the end of the first book is tagged v1.0.\nWhat I took away Write the maths first, then the abstractions. The book\u0026rsquo;s order (rays, then spheres, then materials) keeps every step visible as a picture. You debug with your eyes. Randomness everywhere. Diffuse scattering, antialiasing and defocus blur are all random sampling. Seeing noise shrink as samples go up is the best intuition for Monte Carlo methods I know. Kotlin is pleasant for numeric code, as long as you keep allocations in the inner loop in mind. ","permalink":"https://mohaqeq.github.io/posts/2023-09-kotlin-raytracer/","summary":"Working through Peter Shirley\u0026rsquo;s ray tracing book in Kotlin: small classes, a PPM file as output, and a thread pool to make the final render bearable.","title":"Ray Tracing in One Weekend, in Kotlin"},{"content":"I\u0026rsquo;m Hamidreza Mohaqeq, a software engineer. This is my personal blog. I write about things I build, experiments I run, things I learn, and whatever else I find worth writing down. Mostly software, but not only.\nWhen a post is about a project, it links to the code. When it\u0026rsquo;s about an experiment, it says how I measured it, including when the result is negative.\nElsewhere Code: github.com/mohaqeq LinkedIn: linkedin.com/in/mohaqeq Feed: RSS ","permalink":"https://mohaqeq.github.io/about/","summary":"\u003cp\u003eI\u0026rsquo;m Hamidreza Mohaqeq, a software engineer. This is my personal blog. I write about things I build, experiments I\nrun, things I learn, and whatever else I find worth writing down. Mostly software, but not only.\u003c/p\u003e\n\u003cp\u003eWhen a post is about a project, it links to the code. When it\u0026rsquo;s about an experiment, it says how I measured it,\nincluding when the result is negative.\u003c/p\u003e\n\u003ch2 id=\"elsewhere\"\u003eElsewhere\u003c/h2\u003e\n\u003cul\u003e\n\u003cli\u003eCode: \u003ca href=\"https://github.com/mohaqeq\"\u003egithub.com/mohaqeq\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003eLinkedIn: \u003ca href=\"https://www.linkedin.com/in/mohaqeq\"\u003elinkedin.com/in/mohaqeq\u003c/a\u003e\u003c/li\u003e\n\u003cli\u003eFeed: \u003ca href=\"/index.xml\"\u003eRSS\u003c/a\u003e\u003c/li\u003e\n\u003c/ul\u003e","title":"About"}]