<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Valentin Sasek on Medium]]></title>
        <description><![CDATA[Stories by Valentin Sasek on Medium]]></description>
        <link>https://medium.com/@dsl400?source=rss-391e67dd7ac2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qLw8eRgn7zgIVNKSqkKEZw.jpeg</url>
            <title>Stories by Valentin Sasek on Medium</title>
            <link>https://medium.com/@dsl400?source=rss-391e67dd7ac2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:59:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsl400/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Burning Tokens: A Practical Guide to Efficient AI Coding]]></title>
            <link>https://medium.com/@dsl400/stop-burning-tokens-a-practical-guide-to-efficient-ai-coding-ca79a43667d4?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca79a43667d4</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 04:13:19 GMT</pubDate>
            <atom:updated>2026-10-14T04:24:13.177Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>A Systematic Approach to Reducing Token Waste and Maximizing Agent Precision</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdLhj2yKBHIWsGICV8aFRA.png" /></figure><p>This article mainly discusses about Claude Code, but the techniques apply to any coding agent.</p><p>Efficiently managing AI agents requires a shift in mindset. You shouldn’t just “chat” with a model; you need to architect its environment. Here is how I approach reducing token usage while keeping agent performance high.</p><p>The economics of LLM usage are heavily weighted toward generation. As of October 2026, frontier models cost between $2 and $10 per million input tokens and between $10 and $50 per million output tokens at standard API rates, depending on the model you are using.</p><p>Since the model’s responses are many times more expensive than the prompts you provide, reducing unnecessary generation is where the savings are. Most of what follows comes down to one question: what is the model writing that it didn’t need to write?</p><h3>1. Treat Conversations as Disposable</h3><p><strong>Kill Rogue Sessions.</strong> The easiest way to save tokens is to stop trying to “fix” a broken conversation. A malfunctioning conversation creates a loop of ineffective instructions. If the model acknowledges a mistake but repeats the error, terminate the session immediately. Every round of correction is another apology, another explanation, and another rewrite of the same code, all billed at the output rate. A clean start is cheaper and more reliable than a lengthy correction process.</p><p><strong>Avoid Expired Caches.</strong> While the prompt cache is warm, the history you resend with each message is billed at a fraction of the input price. Once it expires, the next message pays full input price for the entire history again. Instead of resuming an expired session, start a new one and ask the agent to extract only the relevant highlights from the previous chat. This eliminates the token overhead caused by accumulated tool call logs.</p><p><strong>Skip the “Summarization” Trap.</strong> Avoid using “compaction” or asking the model to summarize the complete conversation. This forces the model to spend output tokens rewriting information that already exists in the history. Instead, start a fresh session and copy-paste only the verbatim, essential parts of the previous conversation or ask the agent to extract them.</p><h3>2. Trim the Toolset</h3><p>A bloated agent environment is a slow agent environment. Every extra tool or subagent instruction increases the “noise” the model has to process. These are input tokens, cheaper per token, but they ride along with every new session.</p><p>Here is one token breakdown from my setup, measured on October 13, 2026, using Claude Code version 2.1.289:</p><pre>Type    Name                                               Tokens<br>------  ------------------------------------------------  -------<br>tool    Artifact, including ArtifactComments               11,338<br>        and ArtifactData<br>tool    Workflow                                            8,239<br>skill   Bundled skills (dataviz, claude-api,                2,690<br>        code-review, loop, schedule, …)<br>tool    claude.ai connectors (Claude Docs, Gmail,          ~1,873<br>        Google Calendar, Google Drive)<br>tool    ScheduleWakeup                                      1,698<br>tool    ReportFindings                                        822<br>memory  Automatic memory                                      736<br>tool    ListAgents                                            401<br>skill   anthropic-skills:* and plugin-authoring               159<br>------  ------------------------------------------------  -------<br>Total   Listed components                                 ~27,956</pre><p>Artifact and Workflow alone account for 19,577 tokens, about 70% of the listed total.</p><p><strong>Prune Unused Tools.</strong> Most agent harnesses come with a heavy set of default tools. If you don’t need them for the current task, disable them. A leaner toolset makes the model faster and more accurate.</p><pre>{<br>  &quot;permissions&quot;: {<br>    &quot;deny&quot;: [<br>      &quot;AskUserQuestion&quot;,<br>      &quot;Workflow&quot;,<br>      &quot;ScheduleWakeup&quot;,<br>      &quot;Artifact&quot;,<br>      &quot;ReportFindings&quot;,<br>      &quot;ListAgents&quot;<br>    ]<br>  },<br>  &quot;disableBundledSkills&quot;: true,<br>  &quot;skillOverrides&quot;: {<br>    &quot;anthropic-skills:built-in-browser&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:chrome-browser&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:computer-use&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:deep-research&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:docs&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:docx&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:google-workspace&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:import-memory&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:morning&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:pdf&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:pptx&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:skill-creator&quot;: &quot;off&quot;,<br>    &quot;anthropic-skills:xlsx&quot;: &quot;off&quot;,<br>    &quot;plugin-authoring&quot;: &quot;off&quot;<br>  },<br>  &quot;disableClaudeAiConnectors&quot;: true,<br>  &quot;autoMemoryEnabled&quot;: false<br>}</pre><p><strong>Control Subagent Delegation.</strong> Avoid letting the main agent autonomously spawn subagents. Main agents often write poor, vague prompts for their subordinates. You pay output tokens for the main agent to write that prompt, then again for the subagent’s work, and a third time when the result has to be redone. Instead, take control. Use explicit instructions like: <em>“Ask [Model Name] to [Specific Action].”</em> This ensures the delegation is precise and uses fewer tokens.</p><h3>3. Optimize Data and Workflow</h3><p><strong>Keep Files Granular.</strong> Large files are a trap. When a model encounters an oversized file, it often tries to use scripts to “peek” at the content rather than reading it. Each of those scripts is output the model writes just to look around, and it can still lead to skipping the lines that matter. Keep your files small and focused to ensure the model processes the entire context.</p><p><strong>Turn Repetition into Tools.</strong> If you notice the agent performing the same sequence of steps repeatedly, identify the pattern and turn it into a dedicated skill, script, or tool. By moving repetitive logic from the “chat” into a “tool call,” you replace high-token instructions with a single, efficient command. The agent writes the script once instead of regenerating the same steps every time.</p><p>A good example here would be to ask the agent to build a script that extracts relevant context from a previous session using a single tool call.</p><h3>Bonus: Implement a Decision Journal</h3><p>Context drift makes every following turn more expensive. When an agent loses alignment with your project’s intent or the established direction of the codebase, every subsequent interaction requires expensive, multi-turn corrections. While a simple “yes” or “agreed” makes perfect sense in the current conversation, these confirmations are effectively invisible to an agent attempting to reconstruct context from a previous session.</p><p>To solve this, instruct your agent to maintain a persistent <strong>Decision Journal</strong>.</p><p>By requiring the agent to log every significant architectural or logic change into a dedicated file, you ensure that new sessions start by reading the current state of the project. This lets them align right away without the need for expensive, multi-turn reasoning loops to rediscover lost information.</p><p><strong>Example Log Structure:</strong></p><pre>## [YYYY-MM-DD] — [Module/Feature Name]<br>Decision: [Describe the specific rule or change implemented].<br>Reference: [Session ID or Task Identifier].</pre><p>You might think this increases token usage, and it does add output. But a log entry is a few lines written once, while re-establishing project alignment means the model explaining, proposing, and rewriting across several turns in every new session.</p><p>Once you have optimized your environment, the next challenge is reliability. Learn how to enforce strict instruction following here: <a href="https://medium.com/@dsl400/how-to-get-claude-code-to-follow-your-rules-like-a-train-on-rails-46e4284fd598">How to Get Claude Code to Follow Your Rules Like a Train on Rails</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca79a43667d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Claude Code to Follow Your Rules Like a Train on Rails]]></title>
            <link>https://medium.com/@dsl400/how-to-get-claude-code-to-follow-your-rules-like-a-train-on-rails-46e4284fd598?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e4284fd598</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 09:30:02 GMT</pubDate>
            <atom:updated>2026-10-11T09:30:02.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discover the syntax that turns AI agents into bulletproof execution engines.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNu7JEjHHvmoDTymujK5zw.png" /></figure><p>You spent hours writing your CLAUDE.md and added very explicit rules in .claude/rules/. Yet, halfway through a complex task, Claude seems to ignore them.</p><p>The model isn’t ignoring your rules. It can see them clearly in the context window. The problem is that natural language rules lack a <strong>trigger</strong>. There is no instruction telling the model <em>at which specific moment</em> it should pause and look at a particular rule. Without a structural trigger, the model’s attention drifts toward the immediate task, leaving your constraints behind.</p><p>To fix this, you need to move from descriptive instructions to a structural flow.</p><h3>The Scenario: Adding a “Delete User” Feature</h3><p>Imagine you are asking Claude to add a new feature: a button to delete a user from your application.</p><h3>Approach 1: The Natural Language Method (The “Drift” Pattern)</h3><p>In this approach, we provide instructions in standard English.</p><p><strong>The Rules:</strong></p><ul><li>Always verify the database schema before changing the code.</li><li>Always update the api-docs.md file after a change.</li><li>Ensure all new functions have unit tests.</li></ul><p><strong>The Prompt:</strong></p><blockquote><em>“Add a feature to delete a user. This involves adding a button to the UI and a new endpoint in the backend.”</em></blockquote><p><strong>The Result:</strong> Claude generates the backend logic and the UI component. It writes the code perfectly. However, it skips the database verification, forgets to update api-docs.md, and fails to write the unit tests.</p><p>The rules were present in the context, but they were not part of the <strong>execution path</strong>. The model treated them as “background information” rather than “active checkpoints.”</p><h3>Approach 2: The Flow Method</h3><p>Here we write the same rules the way a programming language writes a program: labels, branches, and checks in a fixed order. ASK branches, JUMP moves to a label, and CHECK blocks the path until a condition holds. The model has read a great deal of code, so it already knows how to follow a control flow written this way.</p><p><strong>Provide The Rules As A Flow:</strong></p><pre>&lt;project-rules&gt;<br>&lt;flow&gt;<br>START:<br>  ASK   is a database schema change required?<br>  JUMP  VERIFY_SCHEMA IF yes<br>  JUMP  PROCEED<br>VERIFY_SCHEMA:<br>  CHECK database/schema.sql matches the new endpoint requirements<br>  JUMP  PROCEED<br>PROCEED:<br>  DO    implement the feature<br>  CHECK all new functions have unit tests<br>  CHECK api-docs.md is updated<br>END<br>&lt;/flow&gt;<br>&lt;/project-rules&gt;</pre><p><strong>The Prompt:</strong></p><blockquote><em>“Add a feature to delete a user. This involves adding a button to the UI and a new endpoint in the backend.”</em></blockquote><p><strong>The Result:</strong> Claude begins the task. Because the START instruction is the entry point for every user message, the model is forced to process the ASK instruction first.</p><ol><li>It stops to check the schema.</li><li>It executes the implementation.</li><li>It reaches the CHECK statements, which act as high-density attention anchors, forcing it to validate the tests and the documentation before reaching END.</li></ol><p>The model stays on the rails because the rails are the only path provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E69hZwUmke4tmqjQV06VEg.png" /></figure><h3>Why This Works</h3><p>The difference is found in how the model’s attention mechanism handles the input.</p><p><strong>Natural language instructions are passive.</strong> They exist in the context, but they do not command the attention mechanism during the generation of new tokens. They are “static” data.</p><p><strong>Flow instructions are active.</strong> The CHECK and ASK statements create high-weight anchors. During the generation of the code, the model must constantly attend to these tokens to satisfy the structural requirements of the flow.</p><p>Write each rule as a step on the path the model walks, and it meets the rule at the moment the rule applies.</p><p>The syntax used here is LNL. The full language and its linter are described in <a href="https://medium.com/@dsl400/a-lintable-language-is-all-you-need-3ecbefa69e6b">A Lintable Language Is All You Need</a> and at <a href="https://github.com/dsl400/lnl">github.com/dsl400/lnl</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e4284fd598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Lintable Language Is All You Need]]></title>
            <link>https://medium.com/@dsl400/a-lintable-language-is-all-you-need-3ecbefa69e6b?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ecbefa69e6b</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 21:53:24 GMT</pubDate>
            <atom:updated>2026-10-12T06:58:02.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>The model is a multilingual, fault-tolerant execution runtime that switches between deterministic and nondeterministic execution, with the largest standard library ever shipped and the batteries actually included.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OyW1AbspCNxG4jsCP1lEg.png" /></figure><p>If you paste this into a chat window:</p><pre>act as a js runtime and execute this program<br>&lt;the first stanza of &quot;Jingle Bells&quot;&gt;<br>  .map(line =&gt; ({ words: line.wordCount(), mood: line.sentiment(), fr: line.translate(&quot;fr&quot;) }))<br>  .forEach(x =&gt; console.log(JSON.stringify(x)))</pre><p>It will most likely output this:</p><pre>{&quot;words&quot;:4,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Filant à travers la neige&quot;}<br>{&quot;words&quot;:5,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Dans un traîneau ouvert tiré par un cheval&quot;}<br>{&quot;words&quot;:5,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Par-dessus les champs nous allons&quot;}<br>{&quot;words&quot;:4,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Riant tout le long du chemin&quot;}<br>{&quot;words&quot;:5,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Les grelots de la queue courte tintent&quot;}<br>{&quot;words&quot;:3,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Rendant les cœurs joyeux&quot;}<br>{&quot;words&quot;:8,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Quelle joie de rouler et de chanter&quot;}<br>{&quot;words&quot;:4,&quot;mood&quot;:&quot;positive&quot;,&quot;fr&quot;:&quot;Une chanson de traîneau ce soir !&quot;}</pre><p>The execution of this snippet relies on the model’s ability to perform semantic mapping across a learned syntax. In a traditional runtime, the symbols wordCount(), sentiment() and translate() would trigger a ReferenceError due to the absence of a defined scope or instruction set. The model treats the syntax as a structural template. It identifies the control flow (the .map and .forEach iterations) and uses the function names as semantic anchors.</p><p>Because the model has internalized vast amounts of documentation, API references, and implementation logic, the “standard library” is functionally infinite and covers almost any domain — from natural language processing to complex mathematical operations.</p><p>This paradigm shifts the focus of programming from implementation to specification, prioritizing the semantic clarity of intent. However, for a specification to be actionable, it must provide enough structural constraint to bound the model’s probabilistic inference.</p><p>The instability observed in LLM outputs is often attributed to the model itself, but the volatility resides in the input. Natural language lacks the structural constraints required to guide probabilistic inference reliably. However, the model’s capacity for near-deterministic precision is unlocked when provided with an explicit control flow. The objective is to move from unstructured prompts to a syntax that enforces this flow.</p><p>The natural candidate for providing this structural constraint is the existing repertoire of programming languages. However, these languages are fundamentally mismatched for semantic specification. They are built to manage the complexities of procedural execution, imposing implementation-heavy details that obscure high-level intent. We do not need a language to manage hardware resources, but a language to govern semantic structure.</p><p>The limitations of both natural language and procedural programming necessitate a synthesis. We require a notation that retains the semantic transparency of human communication but is governed by the structural boundaries of a formal language. This syntax must be expressive enough to describe intent, yet rigid enough to be validated.</p><p>This brings us to the concept of a Lintable Natural Language. A language that serves as a framework of structural constraints for an inference engine. The compilation phase focuses on passing a static analysis tool, effectively replacing traditional machine code generation with structural validation.</p><p>The following is a demonstration of such a syntax that you can copy into your AGENTS.md</p><pre>&lt;project-rules enforcement=&quot;strict, no exceptions allowed&quot;&gt;<br>&lt;rule name=&quot;entrypoint&quot;&gt;This program is how you work. WHEN a user message<br>arrives, you SHALL run the program below from `START`, before any other<br>action, and follow it line by line until `END`.&lt;/rule&gt;<br>&lt;rule name=&quot;same-language&quot;&gt;WHEN you write a skill or a rule, use the<br>language below. After every edit, validate the file using lnl.js.&lt;/rule&gt;<br>&lt;flow&gt;<br>START:                                              ; entrypoint: each user message<br>  ASK   does the user ask me to prevent a repeated error?   ; for example &quot;never do<br>                                                    ; this again&quot;, &quot;how do we<br>                                                    ; prevent this from happening&quot;<br>  JUMP  PREVENT IF yes<br>  ASK   is the request a question that changes no file?<br>  JUMP  REVIEW IF yes<br>  ASK   is the request a minor change?              ; it touches only the files<br>                                                    ; the request names and changes<br>                                                    ; no behaviour it does not name<br>  JUMP  MINOR IF yes<br>  JUMP  RESEARCH<br>PREVENT:<br>  ASK   can a lint rule of the file that shows the error catch it?<br>  JUMP  PREVENT_RULE IF no<br>  WRITE ./reports/&lt;task&gt;/proposal.md &quot;rung 1: the lint rule, one input that leaves it, one that passes&quot;<br>  JUMP  REVIEW<br>PREVENT_RULE:<br>  ASK   can one EARS sentence in .claude/rules/&lt;topic&gt;.md, with a `paths` list of the files where the error happens, guide the agent away from it?<br>  JUMP  PREVENT_CHECK IF no<br>  WRITE ./reports/&lt;task&gt;/proposal.md &quot;rung 2: the sentence, and why a lint rule cannot catch it&quot;<br>  JUMP  REVIEW<br>PREVENT_CHECK:<br>  WRITE ./reports/&lt;task&gt;/proposal.md &quot;rung 3: one CHECK line for REVIEW, and why rungs 1 and 2 cannot catch the error&quot;<br>  JUMP  REVIEW<br>MINOR:<br>  ADD   1 to &lt;p&gt;<br>  WRITE ./reports/&lt;task&gt;/plan-&lt;p&gt;.md &quot;one line: file, what, how to verify&quot;<br>  ASK   is the change irreversible or outward-facing?<br>  STOP  ask the human to approve the change IF yes<br>  JUMP  WORK<br>RESEARCH:<br>  ADD   1 to &lt;r&gt;<br>  STOP  ask the human the open questions IF &lt;r&gt; &gt;= 4<br>  ASK   do I have, with a source, each fact the plan needs?<br>  JUMP  PLAN IF yes<br>  WRITE ./reports/&lt;r&gt;/research-&lt;r&gt;.md &quot;each fact with file:line or URL; the established system, standard, or library that already solves the need, with the section that covers it, when one exists&quot;<br>  JUMP  RESEARCH<br>PLAN:<br>  ADD   1 to &lt;p&gt;<br>  STOP  ask the human, with the last plan IF &lt;p&gt; &gt;= 4<br>  WRITE ./reports/&lt;task&gt;/plan-&lt;p&gt;.md &quot;one line per change: file, what, why, how to verify; the plan is as big as the work&quot;<br>PLAN_CHECK:<br>  ASK   does each part of the user request have its line in the plan?<br>  JUMP  PLAN IF no<br>  ASK   does the plan leave a question without a sourced answer?<br>  JUMP  RESEARCH IF yes<br>  ASK   does the plan hold an irreversible or outward-facing action?<br>  STOP  ask the human to approve the plan IF yes<br>  JUMP  WORK<br>WORK:<br>  ADD   1 to &lt;w&gt;<br>  STOP  report the lines of the plan not done and ask the human how to continue IF &lt;w&gt; &gt;= 21<br>  ASK   does the plan hold a line that is not done?<br>  JUMP  REVIEW IF no<br>  ASK   does the line hold the information it needs: file, what, how to verify?<br>  STOP  report that the plan does not cover this change, the change, and its reason IF no<br>  DO    the change of the line<br>  DO    verify the change and mark the line done<br>  JUMP  WORK<br>REVIEW:<br>  ; Check the changes of the turn, each file they use or that uses them,<br>  ; and each file read in the turn; their content is already in your context.<br>  ; A turn without changes gets [N/A] on the checks of code.<br>  ; Append to ./reports/&lt;task&gt;/audit.md one entry:<br>  ;   ## &lt;date&gt; &lt;time&gt; · session &lt;id&gt;<br>  ;   Turn: &quot;&lt;user_message&gt;&quot;<br>  ;   - [OK] &lt;check&gt; ? &lt;file&gt;:&lt;line&gt;<br>  ;   - [N/A] &lt;check&gt; ? &lt;reason the changes give&gt;<br>  ;   - [NOT OK] &lt;check&gt;<br>  ;     - &lt;file&gt;:&lt;line&gt; &lt;what breaks the check&gt;<br>  ;       Proof: &lt;evidence&gt;<br>  ;       Repair: &lt;what changed&gt; | Rejected: &lt;reason from the discussion&gt;<br>  ;   - [NOT OK] correction ? &lt;what the earlier turn did&gt; ? &lt;what the user wanted&gt;<br>  ;     Proposal: rung &lt;n&gt;, &lt;file&gt; ? &lt;the mitigation&gt;<br>  ;     Rung &lt;n-1&gt;: &lt;why it cannot catch the error&gt;<br>  ;   - [OK] decision ? docs/tmp.md marker &lt;marker&gt;<br>  ;   - [OK] user correction of the turn that repeats an earlier one is recorded in ~/agent-problems/<br>  ;   - [OK] user correction of the turn has a [NOT OK] correction line with its Proposal<br>  CHECK code moved out of a loop when it does not change inside the loop (LICM)<br>  CHECK values known early are computed once, not on each run (binding-time analysis)<br>  CHECK each specialized path stays valid for the inputs it serves (specialization validity)<br>  CHECK each cache is invalidated when its source changes (cache invalidation)<br>  CHECK each file, function, and rule has one responsibility (SRP)<br>  CHECK each fact, rule, and piece of code lives in one place (DRY)<br>  CHECK each derived value matches the state it derives from (derived-state consistency)<br>  CHECK each change keeps the contract of what it implements or calls (contract conformance)<br>  CHECK each count or numbered heading matches the structure near it<br>  CHECK each report of the turn lives in ./reports/&lt;task&gt;/<br>  CHECK each requirement of docs/reference/ reads complete alone: it names in words what it uses and puts a pointer to another identifier in parentheses at the end of a sentence<br>  CHECK each text of docs/reference/ speaks about what is required, not about its implementation<br>  CHECK each design, rule, or mechanism the turn invents either uses the established system, standard, or library that already defines it, naming its section, or states why that system does not fit<br>  CHECK a user decision of the turn is appended to docs/tmp.md<br>  CHECK a user correction of the turn that repeats an earlier one is recorded in ~/agent-problems/<br>  CHECK a user correction of the turn has a [NOT OK] correction line with its Proposal<br>  ASK   does a [NOT OK] lack a Repair, a Rejected with its reason, or a Proposal?<br>  JUMP  REPLY IF no<br>  ASK   did a STOP bring me here?<br>  JUMP  REPLY IF yes                                ; REPLY lists the open [NOT OK]<br>  ADD   1 to &lt;v&gt;<br>  STOP  ask the human, with the open [N/O] lines IF &lt;v&gt; &gt;= 4<br>  WRITE ./reports/&lt;task&gt;/plan-&lt;p&gt;.md &quot;append each missing Repair as a new line, not done&quot;<br>  JUMP  WORK<br>REPLY:<br>  ASK   did a STOP bring me here?<br>  JUMP  REPLY_SAY IF yes<br>  ASK   is the report, plan, or handover of the turn longer than one sentence?<br>  JUMP  REPLY_SAY IF no<br>  WRITE ./reports/&lt;task&gt;/&lt;kebab-title&gt;.md &quot;the report, plan, or handover of the turn&quot;<br>REPLY_SAY:<br>  SAY   &quot;the message of the STOP when a STOP brought me here; the answer, as short as it can be while it holds the limits and the questions the user needs; the proposal when PREVENT wrote one; a link to the report when REPLY wrote one; a link to the audit.md entry and its [NOT OK] lines when REVIEW ran&quot;<br>  END<br>&lt;flow&gt;<br>&lt;/project-rules&gt;</pre><p>The syntax establishes a control flow through ASK, JUMP, and STOP instructions. The CHECK statements act as the linting layer. These statements define the criteria for a valid execution state. If a generated response fails a CHECK condition, the program logic requires a correction via the REPLY or WORK loops. This transforms the model from a text generator into a validator of its own output against a formal specification.</p><p>With the control flow made explicit, an analyzer can detect jumps to missing labels, unreachable steps, or loops without a stopping condition. A flow editor can use the same instructions as its data: labels become nodes, jumps become connections, and edits to the graph can be written back to the file.</p><p>The adoption of a lintable syntax decouples high-level intent from implementation. The developer provides the structural boundaries through ASK, JUMP, and CHECK instructions, while the model executes the underlying semantic logic.</p><p>In this paradigm, the role of the programmer shifts from writing procedural instructions to defining the formal constraints of a valid execution. The code is no longer a sequence of operations to be performed, but a set of assertions to be satisfied. The program is the specification, and the runtime is the validator</p><p>If you are looking for the technical explanation on why this actually works here are a few guesses</p><p>Semantic Anchoring The model does not execute instructions via a CPU instruction pointer; it performs semantic mapping. Keywords like ASK, JUMP, and CHECK act as high-weight anchors in the model’s attention mechanism. These symbols trigger the retrieval of learned logical patterns associated with conditional branching and validation. The syntax serves as a retrieval prompt for the model’s internalized documentation and implementation logic.</p><p>Entropy Reduction Natural language prompts possess high entropy, providing a vast and unpredictable search space for the next token. The llmmd syntax imposes a structural template that narrows this search space. By defining a fixed control flow (e.g., START → → RESEARCH → → PLAN), the syntax reduces the probability of divergent or irrelevant token sequences. The structure constrains the model’s probabilistic inference to a specific logical trajectory.</p><p>Attention-Based Validation The CHECK statements function as explicit constraints on the attention mechanism. In a standard prompt, the model’s attention is distributed across the entire context. In a lintable language, the CHECK block creates a high-density zone of requirements. During the generation of a response, the model must attend to these CHECK tokens to maintain consistency. This transforms the generation process from simple text prediction into a self-correcting loop where the model evaluates its output against the provided assertions.</p><p>The project repository is <a href="https://github.com/dsl400/lnl">dsl400/lnl on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ecbefa69e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Rulez! Or does it?!]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@dsl400/llm-rulez-or-does-it-96793bc579f6?source=rss-391e67dd7ac2------2"><img src="https://cdn-images-1.medium.com/max/1536/1*tnt10MN0dM8LtBQZLfKIKQ.png" width="1536"></a></p><p class="medium-feed-snippet">Why your project rules get ignored, and what to write instead</p><p class="medium-feed-link"><a href="https://medium.com/@dsl400/llm-rulez-or-does-it-96793bc579f6?source=rss-391e67dd7ac2------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@dsl400/llm-rulez-or-does-it-96793bc579f6?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/96793bc579f6</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[prompt-engineer]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Mon, 18 May 2026 16:53:09 GMT</pubDate>
            <atom:updated>2026-05-18T16:53:09.760Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Context Engineers: You Are Holding It Wrong!!]]></title>
            <link>https://medium.com/@dsl400/context-engineers-you-are-holding-it-wrong-878c0a38b735?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/878c0a38b735</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 11:20:21 GMT</pubDate>
            <atom:updated>2026-04-12T11:20:21.168Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Context Engineers You Are Holding It Wrong</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XwEDRNE-xKzRIwj58ZAdA.png" /><figcaption>Compaction squeezes noise into a smaller space. Scoping removes it entirely.</figcaption></figure><h3>Stop wasting time with compaction!!!</h3><p>You’ve seen the pattern. Your agent runs for a while, the context window fills up, and the model starts forgetting things. The fix everyone reaches for: compaction. Summarize old messages. Trim the fat. Squeeze more conversation into the same window.</p><p>It doesn’t work! It does not scale well! It is a complete compute waste! It is a complete time waste!</p><p>The real problem isn’t that your context is too long. It’s that it’s full of the wrong things.</p><h3>What compaction actually does</h3><p>Compaction is lossy compression applied to the message array. When you summarize a 50-message sub-conversation into three sentences, three things break:</p><p><strong>The reasoning chain disappears.</strong> The model sees “searched for database tools and selected the right one” instead of the actual search results, the comparison it made, the alternatives it rejected. If it needs to revisit that decision, it’s working from a summary written by a past version of itself. A summary that may have been wrong.</p><p><strong>Uncertainty collapses.</strong> A model that was 60% sure about something writes “I found X.” The future model reading that summary treats it as established fact. Confidence scores don’t survive summarization.</p><p><strong>It compounds.</strong> Summarize a summary and you’re running telephone inside a single conversation. By the third compression pass, the model is making decisions based on a distilled representation of a distilled representation.</p><p>I’ve seen agents with 200k context windows perform worse than agents with 8k windows on the same task. The difference wasn’t capacity. It was signal-to-noise ratio.</p><h3>The attention problem</h3><p>The mental model that gets people in trouble: context window = memory. More is better. When you run out, compress.</p><p><strong>But attention isn’t memory.</strong> It’s a weighted average across all tokens in the window. Every irrelevant token dilutes the weight assigned to tokens that matter. This is measurable. The “lost in the middle” problem is well-documented. Models degrade at retrieving information placed in the center of long contexts. Not because of a bug, but because that’s how attention mechanisms distribute weight across large sequences.</p><p>More context can make the model objectively worse at the things it should be good at. You’re not giving it more information. You’re giving it more noise.</p><h3>A solved problem: the call stack</h3><p>Here’s the part that frustrates me. We solved this problem fifty years ago. It’s called a call stack.</p><p>Every programming language manages complexity the same way. Functions have local scope. Variables declared inside a block don’t leak into the caller. When a function returns, only the return value survives. Local variables, intermediate calculations, scratch work, all gone. The calling function doesn’t know or care how the callee did its job. It gets the result.</p><blockquote>This isn’t an analogy. It’s the same problem.</blockquote><p>An LLM agent doing multi-step work accumulates intermediate state in its context window. Tool results, search outputs, API responses, reasoning traces. All of it piles up in a flat message array. That’s the equivalent of a program where every function shares a single global scope. Every variable from every function call lives forever. We know exactly what happens to programs like that: they break.</p><p>The call stack exists because local scope is a prerequisite for managing complexity. There’s no reason this shouldn’t apply to LLM conversations.</p><p><strong>Call stack over LLM: how it works</strong></p><p>The implementation is straightforward. Instead of one flat conversation that grows until you compact it, you maintain a frame stack. Each frame is a scoped sub-conversation with its own tool set, its own messages, and a single exit point: <em>ret(value)</em>.</p><pre>main conversation (frame 0)<br>  └─ tool_selection (frame 1)    ← child frame<br>       └─ [search, compare, select]  ← local work<br>       └─ ret(&quot;mcp_gitea_list_issues&quot;)  ← return value</pre><p>When the child frame calls <em>ret</em>:</p><p>1. Everything inside frame 1 (messages, tool calls, results) gets filtered out of the parent’s context<br>2. The return value surfaces in the parent<br>3. Any side effects (tools attached, state changes) persist in the parent scope</p><p>The parent conversation never sees the child’s intermediate work. Not compressed. Not summarized. Structurally absent.</p><p>This is <em>call</em> and <em>ret</em>. Push a frame, do scoped work, pop the frame, return a value. The same primitive that makes every non-trivial program possible.</p><h3>Proof of concept: 26B parameters, zero compaction</h3><p>Here’s a real trace. The model is `gemma-4–26B-A4B-it-Q8_0.gguf`, a quantized 26-billion-parameter model running locally.</p><p><a href="https://gist.github.com/dsl400/7f84d39542f7b596ce848a74a1adea39">https://gist.github.com/dsl400/7f84d39542f7b596ce848a74a1adea39</a></p><p>The model doesn’t have a Gitea tool. It needs to discover one from 35 available MCP tools. In a flat conversation, all of that discovery stays in context forever. 120+ lines of tool names, descriptions, comparisons. Every subsequent turn attends over that noise.</p><p>With a frame stack:</p><p><strong>Turn 1-3: inside <em>tool_selection</em> frame.</strong> The model sees exactly 5 tools: <em>search_tools</em>, <em>describe_tool</em>, <em>select_tool</em>, <em>drop_tool</em>, <em>ret</em>. It searches for “gitea,” gets 35 results, selects <em>mcp_gitea_list_issue</em>`. Three turns of scoped work.</p><p><strong>Frame closes via <em>ret</em>.</strong> The 35-tool search result, the selection process, the three turns of scratch work. All filtered from the parent context.</p><p><strong>Turn 4: back in parent frame.</strong> The model sees a 3-message conversation: system prompt, user request, scene block showing tools attached to this frame: <em>mcp_gitea_list_issues</em>. Clean. It calls the tool directly.</p><p>The parent context went from 3 messages to 3 messages. Not from 50k tokens to 15k via compaction. It never grew in the first place. The intermediate work existed in a local scope that was collected on <em>ret</em>, exactly like stack-allocated memory after a function returns.</p><h3>Why this outperforms compaction</h3><p>Three technical reasons:</p><p><strong>Constant context size in the parent frame.</strong> A flat conversation grows linearly with every sub-task. A frame-based conversation stays bounded. Sub-tasks contribute only their return values. After 10 sub-tasks, the flat conversation has 10 sub-tasks worth of raw output. The frame-based conversation has 10 return values.</p><p><strong>No attention dilution.</strong> The parent model doesn’t allocate attention weights to tokens that aren’t there. This isn’t a theoretical benefit. It’s the difference between a 26B model succeeding at a task and a much larger model getting confused by irrelevant context.</p><p><strong>Deterministic information boundaries.</strong> With compaction, what survives is decided by a summarization model, a second LLM call that introduces its own error rate. With a frame stack, what survives is decided by the <em>ret</em> value: an explicit, deterministic API contract between caller and callee. You define the interface. The model operates within it.</p><h3><strong>Applying the pattern</strong></h3><p>You don’t need to build a full orchestrator. The principle maps directly:</p><p><strong>Tool results are local variables.</strong> Your agent reads a 500-line file to answer a question. In a flat conversation, those 500 lines sit in context for every subsequent turn. In a frame, they’re local to the scope that needed them. The return value is what the parent gets.</p><p><strong>Multi-step tasks are function calls.</strong> “Research, implement, test” is three frames. The research frame returns findings. The implementation frame takes those findings as input, not the raw research process. Each frame gets a clean context tailored to its job.</p><p><strong>Return values are the interface contract.</strong> When a sub-task completes, you decide what the caller needs. This is a design decision, same as choosing a function’s return type. A return value that says “selected <em>mcp_gitea_list_issues</em>” is more useful than a compacted summary that says “the assistant searched for tools and found one.”</p><p><strong>If you need compaction, you have a scope problem.</strong> Compaction means your context is doing too many things in the same scope. The fix isn’t better compression. It’s decomposition into frames.</p><h3>The bottom line</h3><p>The call stack is arguably the most proven abstraction in computing. Every program you’ve ever run depends on it. It solves exactly the problem that context engineering is struggling with: managing growing state across sequential operations without letting intermediate work pollute the caller’s scope.</p><p>Compaction is an ad-hoc patch for the absence of this structure. It tries to solve with compression what should be solved with scope. And it fails in predictable ways: information loss, confidence distortion, compounding error.</p><p>A 26B quantized model with a frame stack outperforms at a multi-step tool-discovery task. Not because it’s smarter. Because it has less noise to cut through. The context window isn’t the bottleneck. What you put in it is.</p><p>Stop compacting. Start scoping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878c0a38b735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pg_cron worker running every second]]></title>
            <link>https://medium.com/@dsl400/pg-cron-worker-running-every-second-188ed552c4ca?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/188ed552c4ca</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[postgresql-tutorials]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 19:04:27 GMT</pubDate>
            <atom:updated>2026-02-11T19:24:36.976Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Forbidden Fruit</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqswnV1XA4gQFv2Wn9cQwQ.png" /></figure><pre>SELECT cron.schedule(&#39;worker&#39;, &#39;1 seconds&#39;, &#39;CALL background_worker()&#39;);</pre><p>You type this into your editor and Uncle Bob appears behind you like a disappointed ghost. ‘Every second?’</p><p>Blasphemy. A query every second, 86,400 times a day, hammering your database into the ground. Except… it doesn’t. Here’s why</p><p>The typical setup feels like hiring someone to check an empty mailbox every second. They walk over, open it, find nothing, write down “nothing”, walk back, and do it again. Every tick: a new connection (or a background worker wake-up), a query against <em>cron.job_run_details</em>, and a write to the job log. Multiply that by 86,400 seconds in a day and you’ve got a diligent employee who’s done a full shift of absolutely nothing useful.</p><p>The first instinct is usually to use a trigger and skip the polling entirely. Reacting to modifications sounds way more efficient than polling every second, but it comes with some serious caveats.</p><pre>```sql<br>CREATE OR REPLACE FUNCTION on_insert() RETURNS trigger AS $$<br>BEGIN<br>  -- do work here<br>  RETURN NEW;<br>END;<br>$$ LANGUAGE plpgsql;<br><br>CREATE TRIGGER trg AFTER INSERT ON job_queue<br>FOR EACH ROW EXECUTE FUNCTION on_insert();<br>```</pre><p>Clean. Elegant. And potentially catastrophic.</p><p>A trigger runs <strong>inside the caller’s transaction</strong>. Whatever your trigger does, the original query has to wait for it. If your trigger takes 50ms, every query now takes 50ms longer. If your trigger calls an external service, touches another table, or, god forbid, does a `FOR UPDATE` on a hot row, you’ve just welded your write path to your processing path.</p><p>It gets worse. If the trigger throws an error, <strong>the original insert rolls back</strong>. Your application wanted to write a row to a queue. Instead it got a 500 because some downstream processing logic had a bug. The data never made it to the table.</p><p>And it gets worse still. Under load, trigger overhead compounds. Ten concurrent inserts, each waiting on trigger execution, each holding row locks longer than necessary. What was a simple append-only queue is now a contention point. I’ve seen well-meaning `AFTER INSERT` triggers turn a table that handled 10,000 inserts/second into one that struggled with 500.</p><p>So triggers are actually worse than the mindless mailbox worker. Now you have to debug weird locks and work around scenarios you never thought of. But there’s a middle ground. A pattern that’s not perfect, but surprisingly effective for what it is.</p><h3><strong>What we actually want</strong></h3><p>Let’s say you’re building a todo app. Users mark tasks as done, and you need some background work to happen, send a notification, update a summary, sync to another service, whatever. You want it to feel snappy. Within a second of the user clicking “done”, the background work should kick in.</p><p>You also want to keep things simple. No Redis. No separate worker service. No extra infrastructure to deploy and monitor. Just PostgreSQL doing its thing.</p><p>Going back to our mailbox worker, the naive pg_cron approach looks like this:</p><pre>SELECT cron.schedule(&#39;worker&#39;, &#39;1 seconds&#39;, $$<br>UPDATE todos SET notified = true<br>WHERE id IN (<br>SELECT id FROM todos<br>WHERE done = true AND notified = false<br>ORDER BY id LIMIT 100<br>FOR UPDATE SKIP LOCKED<br>)<br>$$);<br>```</pre><p>(note: the `’N seconds’` syntax requires <strong>pg_cron v1.5.0+</strong>, released February 2023; the valid range is 1-59 seconds)</p><p>This works. But it’s the same restless employee from before. Every second, pg_cron sends them to check. You can make their trip shorter with `cron.use_background_workers = on` (reuse a background worker instead of hailing a cab each time). You can tell them to stop filing reports with `cron.log_run = off`. But they still make the trip. Every. Single. Second. Even at 3 AM when nobody is using your app.</p><p>What you really want is an employee who sits next to the mailbox, glances at it periodically, and only stands up when there’s something inside.</p><h3><strong>The pattern: teach the worker to nap</strong></h3><p>Instead of pg_cron poking the worker every second, you let the worker manage itself. pg_cron launches a procedure. That procedure checks for work. If there’s nothing to do, it takes a nap with `pg_sleep()`. When something shows up, it handles it and clocks out. pg_cron notices the shift is over and sends the worker back in.</p><pre>CREATE OR REPLACE PROCEDURE background_worker() AS $$<br>DECLARE<br>_deadline timestamptz := clock_timestamp() + interval &#39;5 minutes&#39;;<br>BEGIN<br>LOOP<br> - Shift&#39;s over. Clock out and let pg_cron send us back in.<br>EXIT WHEN clock_timestamp() &gt;= _deadline;<br> - Glance at the mailbox<br>IF NOT EXISTS (SELECT 1 FROM todos WHERE done = true AND notified = false) THEN<br> - Nothing there. Take a nap.<br>PERFORM pg_sleep(1);<br>CONTINUE;<br>END IF;<br> - Something&#39;s here. Do the work.<br>UPDATE todos SET notified = true<br>WHERE id IN (<br>SELECT id FROM todos<br>WHERE done = true AND notified = false<br>ORDER BY id LIMIT 100<br>FOR UPDATE SKIP LOCKED<br>);<br> - Done. Clock out.<br>EXIT;<br>END LOOP;<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>To schedule it:</p><pre>SELECT cron.schedule(&#39;bg-worker&#39;, &#39;1 seconds&#39;, &#39;CALL background_worker()&#39;);</pre><p>That’s it. Your worker now naps when idle and wakes up when there’s something to do.</p><h3><strong>Why this actually works</strong></h3><p>Here’s the trick. pg_cron has a simple rule: it won’t start a second copy of a job if the first one is still running. From the [documentation](https://github.com/citusdata/pg_cron):</p><p>&gt; <em>pg_cron runs at most one instance of a job at a time. If a second run is supposed to start before the first one finishes, then the second run is queued and started as soon as the first run completes.</em></p><p>Your procedure is always “running” as far as pg_cron is concerned. It’s either napping or working. pg_cron sees it as busy and doesn’t send another worker. No duplicate connections. No wasted resources. The 1-second schedule is just a safety net. If the procedure ever crashes, pg_cron restarts it within a second.</p><p>Think of it this way:</p><p><strong>Nobody’s using your app:</strong> The worker is napping next to the mailbox. Every second it opens one eye, sees nothing, goes back to sleep. One sleeping process. Practically zero cost.</p><p><strong>A user marks a todo as done:</strong> On the next wake-up (within 1 second), the worker sees the new row, processes it, and clocks out. pg_cron sends it right back in on the next tick, and it starts napping again.</p><p><strong>Something goes wrong:</strong> The procedure crashes. pg_cron doesn’t care why, it just sends a new worker on the next tick. Automatic recovery, no babysitting required.</p><h3><strong>Making it work well</strong></h3><p>A few things to get right so this pattern runs smoothly.</p><p><strong>Give the worker a fast way to check the mailbox.</strong> That `EXISTS` check needs to be quick. Add a partial index so PostgreSQL only has to look at rows that actually need processing:</p><pre>CREATE INDEX idx_todos_pending ON todos (id) WHERE done = true AND notified = false;</pre><p>When there’s nothing to do, this index is empty. Checking it takes microseconds.</p><p><strong>Tell pg_cron to be quiet.</strong> Two settings in `postgresql.conf`:</p><pre># postgresql.conf<br>cron.use_background_workers = on<br>cron.log_run = off</pre><p>The first one tells pg_cron to reuse a background worker instead of opening a new database connection every time. The second one stops it from writing a log entry for every single execution. Without this, you’d end up with millions of “I ran and nothing happened” rows in `cron.job_run_details`.</p><p><strong>Use COMMIT if you need other queries to see the changes right away.</strong> By default, everything the procedure does lives inside one big transaction. If you want processed rows to be visible immediately (say, your API is polling for the notification status), add `COMMIT` calls:</p><pre>CREATE OR REPLACE PROCEDURE background_worker() AS $$<br>DECLARE<br>_deadline timestamptz := clock_timestamp() + interval &#39;5 minutes&#39;;<br>BEGIN<br>LOOP<br>EXIT WHEN clock_timestamp() &gt;= _deadline;<br>IF NOT EXISTS (SELECT 1 FROM todos WHERE done = true AND notified = false) THEN<br>COMMIT;<br>PERFORM pg_sleep(1);<br>CONTINUE;<br>END IF;<br>UPDATE todos SET notified = true<br>WHERE id IN (<br>SELECT id FROM todos<br>WHERE done = true AND notified = false<br>ORDER BY id LIMIT 100<br>FOR UPDATE SKIP LOCKED<br>);<br>COMMIT;<br>EXIT;<br>END LOOP;<br>END;<br>$$ LANGUAGE plpgsql;</pre><p>The `COMMIT` between iterations isn’t just about visibility. It also releases the procedure’s transaction snapshot, which lets PostgreSQL’s autovacuum clean up dead tuples in the tables you’re querying. Without it, a long-running procedure can hold onto an old snapshot and silently block vacuum from doing its job, causing table bloat over time.</p><p><strong>Adjust the nap length.</strong> `pg_sleep(1)` means the worker checks once per second. That’s fine for most apps. If you need faster reactions, use `pg_sleep(0.5)` or even `pg_sleep(0.1)`. The cost is the same either way, a sleeping process uses almost nothing, no matter how often it peeks at an empty index.</p><p><strong>When this isn’t the right fit</strong></p><p>This pattern is great for simple background work, but it has limits.</p><p>If you need near-instant reactions (sub-second), use LISTEN/NOTIFY with an external worker process. The napping worker will always have a small delay.</p><p>If you need retries, dead letter queues, or priority lanes, you want a proper job queue like pgmq, Graphile Worker, or River. This pattern doesn’t track failures or reorder work.</p><p>If you need cross-database coordination, this pattern won’t help. pg_cron runs in a single database, so your worker can only touch tables in that database.</p><p>If your managed PostgreSQL provider doesn’t support pg_cron or limits background workers, this won’t work at all.</p><p>But for the common case, “I need to do something in the background, within a second, without adding infrastructure”, this is hard to beat.</p><h3><strong>A few pg_cron tips while we’re here</strong></h3><p>pg_cron gets dismissed a lot. “It’s a toy.” “Use a real queue.” And sure, if you’re building a distributed pipeline with fan-out and observability dashboards, pg_cron is not your tool.</p><p>But most of us aren’t building that. Most of us need to process some rows, on a schedule, without adding another service that can break at 3 AM.</p><p>A few things that help:</p><p><strong>Keep your logic in a procedure, not in the schedule string.**</strong> This matters more than you’d think. Debugging SQL that’s buried inside a `cron.schedule()` call is miserable. Put your logic in a named procedure, schedule the procedure call. You’ll thank yourself in six months.</p><h4>Hard to read, test, or modify</h4><pre>SELECT cron.schedule(&#39;worker&#39;, &#39;10 seconds&#39;, $$<br>WITH batch AS (<br>SELECT id FROM todos WHERE done = true AND notified = false<br>ORDER BY id LIMIT 50<br>FOR UPDATE SKIP LOCKED<br>)<br>UPDATE todos SET notified = true WHERE id IN (SELECT id FROM batch)<br>$$);</pre><p>A better approach is</p><pre>SELECT cron.schedule(&#39;worker&#39;, &#39;10 seconds&#39;, &#39;CALL process_todos()&#39;);</pre><p><strong>Clean up the log table if you leave logging on.</strong> If you don’t set `cron.log_run = off`, pg_cron writes a row to `cron.job_run_details` for every execution. With the self-sleeping pattern, quiet days are fine since the worker holds the slot and you only get a few log entries per hour (once per deadline cycle). But on a busy day, the worker keeps finding work, clocking out, and getting sent right back in on the next tick. That can mean up to 86,400 log entries per day.</p><p>To schedule a cleanup:</p><pre>SELECT cron.schedule(&#39;cleanup-logs&#39;, &#39;0 3 * * *&#39;, $$<br>DELETE FROM cron.job_run_details<br>WHERE end_time &lt; now() - interval &#39;3 days&#39;<br>$$);</pre><p><strong>The one-at-a-time rule is a feature, not a limitation.</strong> pg_cron won’t start a second instance of a job while the first is still running. That’s exactly what makes the self-sleeping pattern work. Your worker holds the slot, pg_cron respects it, and you get single-worker processing without having to build any locking yourself.</p><p><strong>Know the boundaries.</strong> pg_cron runs in the `postgres` database by default (you can change this with `cron.database_name`). Schedules are in UTC. The `’N seconds’` syntax supports 1–59 seconds (and requires pg_cron v1.5.0+). No job dependencies, no fan-out. If those are dealbreakers, look elsewhere. But for “run this SQL on a schedule, inside my database, with zero external dependencies” pg_cron is exactly the right tool.</p><p><strong>What if you don’t have pg_cron v1.5.0?</strong> On older versions, the shortest schedule is once per minute. You can still use the same pattern. But you’re reacting once a minute, not once a second.</p><p>That’s a 60-second worst-case delay instead of 1 second. For many background tasks that’s perfectly fine. If you need sub-minute reactions, upgrade to pg_cron v1.5.0+ or use LISTEN/NOTIFY with an external worker.</p><p><strong>The full setup</strong></p><p>Here’s everything in one place. Copy, adapt the table and the processing logic to your use case, and you’re done.</p><pre>- Your table (whatever it looks like)<br>CREATE TABLE todos (<br>id bigserial PRIMARY KEY,<br>title text NOT NULL,<br>done boolean DEFAULT false,<br>notified boolean DEFAULT false,<br>created_at timestamptz DEFAULT now()<br>);<br> - Fast check for pending work<br>CREATE INDEX idx_todos_pending ON todos (id) WHERE done = true AND notified = false;<br> - The worker<br>CREATE OR REPLACE PROCEDURE background_worker() AS $$<br>DECLARE<br>_deadline timestamptz := clock_timestamp() + interval &#39;5 minutes&#39;;<br>BEGIN<br>LOOP<br>EXIT WHEN clock_timestamp() &gt;= _deadline;<br>IF NOT EXISTS (SELECT 1 FROM todos WHERE done = true AND notified = false) THEN<br>COMMIT;<br>PERFORM pg_sleep(1);<br>CONTINUE;<br>END IF;<br>UPDATE todos SET notified = true<br>WHERE id IN (<br>SELECT id FROM todos<br>WHERE done = true AND notified = false<br>ORDER BY id LIMIT 100<br>FOR UPDATE SKIP LOCKED<br>);<br>COMMIT;<br>EXIT;<br>END LOOP;<br>END;<br>$$ LANGUAGE plpgsql;</pre><pre>SELECT cron.schedule(&#39;bg-worker&#39;, &#39;1 seconds&#39;, &#39;CALL background_worker()&#39;);</pre><pre># postgresql.conf<br>cron.use_background_workers = on<br>cron.log_run = off</pre><p>One table. One procedure. One pg_cron entry. Two config lines. A worker that naps when there’s nothing to do and gets to work the moment something shows up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188ed552c4ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AI-Assisted Development: The Paradigm Shift Every Developer Needs]]></title>
            <link>https://medium.com/@dsl400/mastering-ai-assisted-development-the-paradigm-shift-every-developer-needs-4c635ba8a319?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c635ba8a319</guid>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-tools]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 12:47:47 GMT</pubDate>
            <atom:updated>2025-10-19T13:02:27.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ot2KeECW5MBe6buKweyxFg.png" /><figcaption>Today is the day you learn how to interact with the machine</figcaption></figure><p>Stop fighting AI. Start architecting with it. Here’s how to transform from skeptic to AI whisperer.</p><p><strong>A Few Words Before We Begin</strong></p><p>I’ve been to a few meetings where the majority of people were non-believers, and almost everyone argued that AI is “NOT YET THERE.”</p><p>I am glad to announce: <strong>IT IS HERE!!!</strong></p><p>AI is here and it’s here <strong>to stay!</strong> No matter how imperfect the code might be initially, it can write more code faster than we ever could. The real problem we’re facing is that we don’t know how to use it effectively, and we tend to look at it as a problem rather than the solution.</p><h3><strong>The Reverse Engineering Mindset</strong></h3><p>Think about human innovation: we first invented the wheel, then made the carriage, then added a motor. As the motor got better, the carriage had to be stronger and more aerodynamic, then safer… and eventually, humans got bored of driving and invented self-driving cars!</p><p><strong>AI is programmed to think these steps in reverse.</strong> It will build you a fancy, modern mocked chassis because it wants you to see results fast! Now that you have a clear image of how the car will look, it will start adding details … if you ask it to!</p><h3><strong>The Paradigm Shift</strong></h3><blockquote>Ask not what the AI can do for you! Ask what you can do for the AI… to actually get good results!</blockquote><p><strong>Structured vs Unstructured Data</strong></p><p>Before we continue, we need to define the concept of structured and unstructured data. This is fundamental to understanding how AI works and how to work with it effectively.</p><p><strong>Structured Data:</strong></p><p>Databases (SQL, Excel, etc.), Data serialization formats (JSON, XML, YAML, HTML, CSV), Code (yes, code is actually a data structure!), Configuration files, API schemas</p><p><strong>Unstructured Data:</strong></p><p>Human-readable text (articles, documentation, comments), Random websites, Documents (PDF, Word, etc.), Images and media, AI-generated output (initially unstructured until validated)</p><p><strong>Key insight:</strong> AI excels at transforming unstructured requests into structured code, but you need to create solid tests in the structured world to confirm that this unstructured tool doesn’t mess up your codebase. And I mean, don’t just test functionality, test code quality itself!</p><h3><strong>Document &gt; Plan &gt; Develop &gt; Test &gt; Repeat</strong></h3><p><strong>1. Document</strong></p><p>Before you start prompting the AI agent, you need to know the answers to these critical questions:</p><p><strong>What exactly are you trying to accomplish?</strong> Be specific. “Make the app better” won’t work. “Add user authentication with OAuth2 support” will.<br><strong>What are the end results you want the AI to deliver?</strong> Define success criteria. What does “done” look like?<br><strong>How are you trying to solve that problem?</strong> Do you have architectural preferences? Existing patterns to follow?<br><strong>What are the restrictions?</strong> Technology stack, performance requirements, security constraints, budget limitations.<br><strong>Where is the AI going to get the required information?</strong> Existing codebase? Documentation? API specs? Examples from similar projects?</p><blockquote><strong>Pro tip 1:</strong> Write this down in a requirements document or project brief. The AI can reference it throughout the development process.</blockquote><blockquote><strong>Pro tip 2:</strong> If the AI failed to deliver the expected results, it is most likely because you didn’t provide enough information.</blockquote><p><strong>2. Plan</strong></p><p>Once you have clear documentation, work with the AI to create a structured plan:</p><p><strong>Break down the work into manageable tasks,</strong> Each task should be completable in 20 to 30 minutes by a professional developer.<br><strong>Identify dependencies </strong>What needs to be done first? What can be done in parallel?<br><strong>Define milestones </strong>Create checkpoints where you can validate progress.<br><strong>Establish testing criteria</strong> How will you know each task is complete and working?<br>Use task management tools when available. Modern AI assistants can create, track, and update task lists to keep complex projects organized.</p><p><strong>3. Develop</strong></p><p>This is where the magic happens, but remember:</p><p><strong>Start with tests (TDD approach) </strong>Write tests first, then implement. This gives the AI clear success criteria.<br><strong>Provide examples </strong>Show the AI similar code from your codebase. AI learns from examples during training, leverage this!<br><strong>Iterate incrementally </strong>Don’t ask for everything at once. Build feature by feature, validating as you go.<br><strong>Review the code </strong>The AI will generate code fast, but you’re the architect. Review for quality, patterns, and maintainability.</p><blockquote><strong>Pro tip 3:</strong> The AI is far more capable than you think. Learn software architecture, design patterns, and best practices.This will help you ask the right questions. The AI will learn from your codebase and replicate it.</blockquote><blockquote><strong>Pro tip 4:</strong> If the AI fails to deliver the expected results, it is most likely because the architecture is too complex. Simplify it and try again.</blockquote><blockquote><strong>Pro tip 5:</strong> The AI will try to deliver something easy to understand, not something maintainable or scalable. Get better at understanding maintainability and scalability, then ask for something maintainable and scalable.</blockquote><blockquote><strong>Pro tip 6:</strong> Always close the loop! Give the AI clear steps to verify its work.</blockquote><p><strong>4. Test</strong></p><p>Testing is not optional, it’s your safety net:</p><p>Unit tests for individual components, Integration tests for system interactions, End-to-end tests for critical user flows, Code quality tests (linting, formatting, security scans)</p><p><strong>5. Guardrails, similar to tests but focused on improving the AI results</strong></p><p>Ask the AI to write tests that prevent it from repeating mistakes!</p><p>Place the tests in the right place in the codebase: Git pre-commit hooks to prevent `console.log` in codebase, Runtime checks to confirm environment variables are set correctly every time the app starts, exit the app with a clear error message if not.</p><p><strong>6. Monitor</strong></p><p>The biggest mistake almost everyone makes is not using git.</p><p>You convince the AI to give you something, it gave it to you, you ask it to do one small improvement and then you lose the changes because you didn’t commit them.</p><p><strong>ALWAYS USE GIT</strong> stage or commit regularly. You can simply identify mistakes looking at the changes the AI made.</p><p>You do not even have to know the whole codebase to understand what is going on. When it breaks something or when it does not give you the expected results look at the changes it made and you will understand what went wrong.</p><p><strong>Never consider a task complete if the tests for the current task you are working on do not pass.</strong></p><h3><strong>Understanding and Preventing Hallucinations</strong></h3><p>AI hallucinations happen when the model generates plausible-sounding but incorrect or nonsensical output. Here’s how to minimize them:</p><p><strong>Factors That Cause Hallucinations:</strong></p><p>1. Lack of context. The AI doesn’t have enough information<br>2. Ambiguous instructions. Vague requests lead to guesswork<br>3. Context window exhaustion. Too much information overwhelms the model<br>4. Missing validation loops. The model has no method of testing it’s solution relies on you to report problems.<br>5. Insufficient examples. The AI doesn’t understand your patterns</p><p><strong>HELP the AI Help You</strong></p><p>The AI will spin in circles if you don’t provide the right tools. Set it up for success:</p><p><strong>Give the AI all the information it needs to do its job and all the tools it needs to do its job.</strong></p><p>Create startup scripts (`./start.sh`, `npm run dev`, etc.) to automate common tasks so the AI can quickly test its changes.</p><p>Provide clear documentation: README files, architecture diagrams, API documentation.</p><p>Set up proper logging to configure your application to output detailed logs so the AI can debug effectively.</p><p>Include example code to show the AI how similar problems were solved in your codebase.</p><p>Write software that fails fast with clear feedback. The agent should learn from its mistakes. Don’t let errors fail silently. Make them loud and informative!</p><p><strong>Close the Loop!</strong></p><p>This is critical: <strong>Always give the AI agent clear steps to validate its work.</strong></p><p><strong>The Validation Loop:</strong></p><p>1. <strong>How to reproduce the problem </strong>“Run `npm test` and you’ll see the authentication test failing.”<br>2. <strong>How to view the results of its actions </strong>“Start the dev server with `./start.sh` and navigate to http://localhost:3000/login&quot;<br>3. <strong>What is the expected outcome </strong>“The login form should accept valid credentials and redirect to /dashboard”<br>4. <strong>Encouragements and constraints </strong>“Write tests for this functionality”, “Review the changes for security issues”, “Look for similar patterns in the auth module”, “Don’t modify the database schema without asking”, “Don’t commit or push changes automatically”</p><p><strong>Improve Visibility</strong></p><p>To get better visibility into what’s happening, configure your application to output detailed logs. Set up structured logging with timestamps, Output API requests and responses, Log state changes and transitions, Include stack traces for errors.</p><p><strong>Automate (But Not Too Much!)</strong></p><p><strong>DO Automate:</strong></p><p>Time is precious for both you and the AI. Automate repetitive tasks:</p><p><strong>Development environment setup </strong>`./start.sh` should handle everything: install dependencies, run migrations, start services.</p><p><strong>Testing workflows</strong>`npm test`, `pytest`, `cargo test` one command to run all tests.</p><p><strong>Build and deployment </strong>CI/CD pipelines that run automatically on commits.</p><p><strong>Code quality checks </strong>Linting, formatting, security scans integrated into your workflow.</p><p>Why? Every command the AI has to type manually is time wasted and an opportunity for errors. Automation creates a consistent, repeatable process.</p><p><strong>DO NOT Over-Automate:</strong></p><p>Some things should require human approval:</p><p>Review before committing, carefully analize database migrations, look for unneeded dependency updates, Do not allow the AI to deploy to production! Even though, if I think about it a little bit more, the AI mite do it better ! :)) , just kidding!! NEVER ALLOW AI TO PUSH TO PRODUCTION!</p><p><strong>The rule:</strong> Automate the safe, repetitive tasks. Require approval for anything that could cause damage or data loss.</p><h3><strong>Advanced Techniques</strong></h3><p><strong>The Handover Pattern</strong></p><p>Because of context window limitations, the AI agent will start to slow down and hallucinate after extended sessions.</p><p><strong>Solution:</strong> Ask the agent to hand over its knowledge to a fresh session.</p><p><strong>How it works:</strong></p><p>1. Ask the AI to create a context handover document. The document should include: current state, completed tasks, pending work, known issues, important decisions.<br>2. Start a new session and provide the handover document. This is where you can even see what the AI has actually planned to do ;) <br>3. The fresh AI picks up where the previous one left off. And even better you get to correct some decisions the AI made.</p><p><strong>Example prompt:</strong> “Please create a context handover document for the next AI agent, including what we’ve accomplished, what’s left to do, and any important context about the architecture decisions we made.”</p><p><strong>The Power of Examples</strong></p><p>During training, AI models are fed millions of examples. Leverage this:</p><p><strong>Show, don’t just tell </strong>Instead of “use our error handling pattern,” show an example of it in action.<br><strong>Reference similar code </strong>“Implement this feature similar to how we did it in `user-service.ts`”<br><strong>Provide templates </strong>Create boilerplate templates for common patterns in your codebase.<br><strong>Use existing tests as examples </strong>“Write tests similar to those in `auth.test.ts`”<br><strong>Remember:</strong> Code is structured data. Random text is unstructured. The AI is better at learning from structured examples than from vague descriptions.</p><h3><strong>The Master Prompt Template</strong></h3><p>After all this theory, let’s get practical. Here’s the template that brings it all together:</p><p>```Hi &lt;agent-name&gt;!<br>Feeling ready for a new challenge?<br>Here are some things you need to know before you start coding:<br>&lt;inline instructions&gt; or Please read &lt;path to the instructions file&gt;</p><p>The problems we have to solve are:<br>- &lt;task 1&gt;<br>- &lt;task 2&gt;<br>- &lt;task 3&gt;</p><p>Success criteria:<br>- &lt;success criteria 1&gt;<br>- &lt;success criteria 2&gt;<br>- &lt;success criteria 3&gt;<br>It is important that you follow these instructions:<br>- work until 100% complete<br>- &lt;instruction 1&gt;<br>- &lt;instruction 2&gt;<br>- &lt;instruction 3&gt;<br>Thanks for your help! // randomly change this line<br>&lt;your name&gt;```</p><p><strong>Why this works:</strong></p><p>1. Personal greeting: Sets a collaborative tone<br>2. Context upfront: Instructions or file references<br>3. Clear tasks: Specific, actionable items<br>4. Success criteria: Defines “done”<br>5. Explicit instructions: No assumptions<br>6. Human touch: The sign-off matters (and vary it to keep things fresh!)</p><p><strong>It all comes down to this:</strong> Give the AI everything it needs, define success clearly, and close the loop with validation steps.</p><h3><strong>Common Pitfalls and How to Avoid Them</strong></h3><p><strong>Pitfall #1: Environment Coupling</strong></p><p><strong>Problem:</strong> hardcoded URLs in the code that couple it to the development environment, hardcoded values that aren’t configurable, hardcoded values in the final bundle that tie it to a specific environment</p><p><strong>How to detect:</strong> Start the project on another port, Start the project on another machine or cloud server, Try to run the production build locally</p><p><strong>Proper fix:</strong> Use environment variables and propagate values from the environment to the code, Use configuration files (`.env`, `config.json`, etc.), Use a combination of both with sensible defaults</p><p><strong>Critical principle: Do not hide defaults in code!</strong> All values should be in the environment and propagated to the code. If a value is not provided, the code should fail with clear instructions on what’s missing.</p><p>```javascript<br>// Bad — Hidden defaults<br>const API_URL = ‘http://localhost:3000/api&#39;;<br>// Also Bad — Silent fallback<br>const API_URL = process.env.REACT_APP_API_URL || ‘/api’;</p><p>// Good — Fail fast with clear feedback<br>const API_URL = process.env.REACT_APP_API_URL;<br>if (!API_URL) {<br> throw new Error(‘REACT_APP_API_URL environment variable is required. Please set it in your .env file.’);<br>}```</p><p><strong>Pitfall #2: Bad Coding Practices</strong></p><p><strong>Bad news:</strong> It’s on you, not the AI, to set the coding standards!</p><p>The agent will try to do the minimal effort to finish the task. If you don’t set clear standards, you’ll get minimal-effort code.</p><p><strong>Solutions:</strong> Create a `CODING_STANDARDS.md` document, Use linters and formatters (ESLint, Prettier, Black, etc.), Provide examples of good code from your codebase, Include code quality in your test criteria, Review AI-generated code before accepting it</p><p><strong>Pitfall #3: Assuming Too Much</strong></p><p><strong>Expect the worst!</strong></p><p>Do not assume anything! The AI is programmed to follow exact instructions. If you point out a problem, it will fix <strong>only that problem</strong>.</p><p><strong>Example scenario:</strong> You say “The login button doesn’t work” and the AI fixes the login button. But the entire auth flow is broken, and the AI only fixed the button position or click event, if it logs to console the it will consider the job done.</p><p><strong>Better approach:</strong> “The authentication system isn’t working. Test the entire flow from login to accessing protected routes. Here’s how to test it: [steps]”</p><p><strong>Pitfall #4: One-Shot Actions Without Validation</strong></p><p>To avoid actions that cause build errors, always give clear instructions on how the agent can confirm the problem has been fixed.</p><p><strong>Bad:</strong> “Fix the broken test”</p><p><strong>Good:</strong> “Fix the broken test in `auth.test.ts`. Run `npm test` to verify it passes. The test should complete in under 2 seconds and all assertions should pass.”</p><p><strong>Pitfall #5: Context Window Exhaustion</strong></p><p>Long conversations lead to slower responses, increased hallucinations, and forgotten context from earlier in the conversation.</p><p><strong>Solutions:</strong> Use the handover pattern (described earlier), Break large tasks into smaller sessions, Summarize progress periodically, Reference documentation instead of repeating information</p><h3><strong>Key Takeaways</strong></h3><p>Before we test your knowledge, let’s recap the essential principles:<br>1. AI is a tool, not a magic wand. It needs proper guidance and context!<br>2. Document first, code later. Clear requirements lead to better results!<br>3. Close the loop. Always provide validation steps!<br>4. Automate wisely. Speed up safe tasks, gate dangerous ones!<br>5. Test everything. Functionality AND code quality.<br>6. Expect the worst. Be explicit, don’t assume!<br>7. Use examples. Show, don’t just tell!<br>8. Manage context. Use handovers for long projects</p><h3><strong>Knowledge Check: Who Wants to Be an AI Whisperer?</strong></h3><p>Let’s see if you actually got something out of this! Answer these questions to test your understanding.</p><p><strong>Question 1: Where should coding standards be documented?</strong></p><p>A) In your head, the AI will figure it out.<br>B) In a CODING_STANDARDS.md file and enforced with linters.<br>C) Nowhere. AI knows best practices automatically.<br>D) In Slack messages to the team.</p><p><strong>Answer: B </strong>In a CODING_STANDARDS.md file and enforced with linters</p><p>The AI needs explicit standards. Document them clearly and use automated tools to enforce them. The AI will follow your standards, but only if you define them!</p><p><strong>Question 2: What should you do when the AI starts hallucinating after a long session?</strong></p><p>A) Keep pushing! it will eventually get it right!<br>B) Restart your computer.<br>C) Use the handover pattern to start a fresh session with context.<br>D) Give up and write the code yourself!</p><p><strong>Answer: C </strong>Use the handover pattern to start a fresh session with context</p><p>Context window exhaustion is real. Ask the AI to create a handover document, then start a fresh session. This gives you a clean context window while preserving important information.</p><p><strong>Question 3: What’s the correct order for the development cycle?</strong></p><p>A) Develop &gt; Test &gt; Document &gt; Plan<br>B) Plan &gt; Develop &gt; Document &gt; Test<br>C) Document &gt; Plan &gt; Develop &gt; Test<br>D) Test &gt; Develop &gt; Plan &gt; Document</p><p><strong>Answer: C </strong>Document &gt; Plan &gt; Develop &gt; Test</p><p>Always start with clear documentation of what you’re trying to achieve. Then plan the approach, develop the solution, and test thoroughly. This order sets the AI up for success.</p><p><strong>Question 4: Which of these should NOT be tasked to the AI agent?</strong></p><p>A) Running tests<br>B) Code formatting<br>C) Deploying to production<br>D) Starting the development server</p><p><strong>Answer: C </strong>Deploying to production</p><p>Automate safe, repetitive tasks. But dangerous actions like production deployments, database migrations, and data deletion should require human approval. The AI should help, not have the keys to the kingdom!</p><p><strong>Question 5: What’s the most important thing to include when asking AI to fix a bug?</strong></p><p>A) A detailed explanation of why you think the bug exists<br>B) The exact error message only<br>C) Steps to reproduce, how to verify the fix, and expected outcome<br>D) A link to Stack Overflow</p><p><strong>Answer: C </strong>Steps to reproduce, how to verify the fix, and expected outcome</p><p>Close the loop! The AI needs to know how to reproduce the problem, how to verify its fix worked, and what the expected outcome is. This creates a validation loop that prevents one-shot fixes that don’t actually solve the problem.</p><p><strong>Question 6: Why should you provide code examples to the AI?</strong></p><p>A) To make the AI feel more comfortable<br>B) Because AI learns from examples and can match your patterns<br>C) To fill up the context window<br>D) Examples don’t help, just describe what you want</p><p><strong>Answer: B </strong>Because AI learns from examples and can match your patterns</p><p>AI models are trained on millions of examples. When you show the AI how similar problems were solved in your codebase, it can match those patterns. Code is structured data the AI learns better from examples than from vague descriptions.</p><p><strong>Question 7: What’s the difference between structured and unstructured data?</strong></p><p>A) Structured data is organized (code, JSON, databases); unstructured is not (text, images)<br>B) There is no difference it’s all just data<br>C) Structured data is newer technology<br>D) Unstructured data is better for AI</p><p><strong>Answer: A </strong>Structured data is organized (code, JSON, databases); unstructured is not (text, images)</p><p>Understanding this distinction is fundamental. AI excels at transforming unstructured requests into structured code, but you need structured tests to validate the output. This is why testing is so critical!</p><p><strong>Question 8: What’s the #1 rule when working with AI?</strong></p><p>A) Let the AI do whatever it wants because it knows best<br>B) Never trust the AI, write everything yourself.<br>C) You have to be a great developer first; AI amplifies your skills<br>D) AI will replace developers soon anyway</p><p><strong>Answer: C </strong>You have to be a great developer first; AI amplifies your skills</p><p>This is the ultimate truth. AI is a force multiplier, not a replacement. If you’re a mediocre developer, AI will help you write mediocre code faster. If you’re a great developer who understands architecture, patterns, testing, and best practices, AI will help you build amazing things at incredible speed.</p><blockquote><strong>The AI is only as good as the architect guiding it.</strong></blockquote><h3><strong>Final Thoughts</strong></h3><p>AI-assisted development isn’t about replacing developers it’s about amplifying great ones.</p><p>The developers who will thrive in this new era are those who understand software architecture deeply, can design robust testable systems, know how to communicate clearly and precisely, embrace testing and validation, and see AI as a tireless junior developer who needs good mentorship.</p><p><strong>The paradigm has shifted. The question isn’t whether AI will change how we code! It already has changed this.</strong></p><p>The question is: <strong>Will you adapt and master it, or will you be left behind?</strong></p><p><strong>Scoring Your Quiz Results</strong></p><p>0–2 correct: AI Apprentice, time to re-read this article!<br>3–4 correct: AI Practitioner, you’re getting there!<br>5–6 correct: AI Expert! You understand the fundamentals!<br>7–8 correct: AI Whisperer!! You’re ready to build amazing things!</p><p><strong>What’s your score? Share in the comments below!</strong></p><p>And if you found this helpful, give it a clap 👏 and follow for more insights on mastering AI-assisted development.</p><p><em>*Ready to transform your development workflow? Start with the Master Prompt Template and watch your productivity soar.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c635ba8a319" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common pitfalls hidden in angular templates]]></title>
            <link>https://medium.com/@dsl400/common-pitfalls-hidden-in-angular-templates-7098f07cede6?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7098f07cede6</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 19:08:08 GMT</pubDate>
            <atom:updated>2025-07-09T19:19:57.120Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Just because modern template languages are powerful and provide advanced functionality does not mean that we have to abuse them!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4rp6lts7dHGXD4PbiAakQ.png" /><figcaption>Angular spagetti code</figcaption></figure><p>Angular templates are powerful and can do a lot of things, but they should not be used to write complex logic. The template should mainly focus on how things look, while the component should handle the logic. Here are some common mistakes when writing Angular templates and how to avoid them.</p><h3>🚫 multiple copies of the same element</h3><p>The most common mistake when writing angular templates is to have multiple copies of the same element and let the template decide which element to display.</p><pre>&lt;div *ngIf=&quot;noInternet&quot;&gt;<br>  &lt;div class=&quot;errorIcon wifi&quot;&gt;&lt;/div&gt;<br>  &lt;span class=&quot;error&quot;&gt;you have no internet&lt;/span&gt;<br>&lt;/div&gt;<br>&lt;div *ngIf=&quot;serverError&quot;&gt;<br>  &lt;div class=&quot;errorIcon server&quot;&gt;&lt;/div&gt;<br>  &lt;span class=&quot;error&quot;&gt;server responded with error: {{serverError}}&lt;/span&gt;<br>&lt;/div&gt;<br>&lt;div *ngIf=&quot;responseError&quot;&gt;<br>  &lt;div class=&quot;errorIcon message&quot;&gt;&lt;/div&gt;<br>  &lt;span class=&quot;error&quot;&gt;server responded with error: {{responseError}}&lt;/span&gt;<br>&lt;/div&gt;</pre><pre>showNoInternetError(){<br>  if(this.serverError()){<br>    return<br>  }<br>  this.noInternetError = true;<br>  this.serverError = &#39;&#39;;<br>  this.responseError = &#39;&#39;;<br>}<br><br>showServerError(){<br>  if(this.serverError()){<br>    return<br>  }<br>  this.noInternetError = false;<br>  this.serverError = &#39;error on server&#39;;<br>  this.responseError = &#39;&#39;;<br>}</pre><p>This approach leads to:</p><ul><li>Redundant and complicated code</li><li>Difficult state management</li><li>Bug-prone logic</li><li>Performance issues</li></ul><h3>✅ Solution:</h3><p>Instead of having multiple copies of the same element, we can have a single element and use a property to determine which error to display.</p><pre>&lt;div *ngIf=&quot;error&quot;&gt;<br>  &lt;div class=&quot;errorIcon&quot;&gt;{{error.icon}}&lt;/div&gt;<br>  &lt;span class=&quot;error&quot;&gt;{{error.message}}&lt;/span&gt;<br>&lt;/div&gt;</pre><pre>showError(message:string, icon:string){<br>  this.error = { message, icon}<br>}<br>hideError(){<br>  this.error = null<br>}</pre><h3>🚫 creating additional html elements</h3><p>Another common mistake is to wrap the content of a template inside an element to capture a click event on the component.</p><pre>@Component({<br>  template:&quot;&lt;div (click)=\&quot;onClick($event)\&quot;&gt; ... &lt;/div&gt;&quot;<br>})<br>export class MyComponent{<br>  onClick(event:MouseEvent)<br>}</pre><h3>✅ Solution:</h3><p>The component is a container and angular provides the HostListener decorator that facilitates the binding of events.</p><pre>@Component({<br>  template:&quot;...&quot;<br>})<br>export class MyComponent{<br>  <br>  @HostListener(&#39;click&#39;) <br>  onClick(event:MouseEvent)<br>}</pre><p>A similar case is wrapping custom elements inside a div because it needs an *ngIf directive instead of placing the *ngIf directive on the custom element.</p><pre>&lt;div *ngIf=&quot;someCondition&quot;&gt;<br>  &lt;app-my-component&gt;&lt;/app-my-component&gt;<br>&lt;/div&gt;</pre><h3>✅ solution</h3><pre>&lt;app-my-component *ngIf=&quot;someCondition&quot;&gt;&lt;/app-my-component&gt;</pre><h3>🚫 redundant ngIf</h3><p>Most of the times wrapping an *ngFor inside an *ngIf is redundant, *ngFor will not render if the list is empty. The programmer now has to manage two properties instead of one.</p><pre>&lt;div *ngIf=&quot;haveItems&quot;&gt; &lt;&lt; this if is redundant, ngFor will not render elements on empty array<br>  &lt;div *ngFor=&quot;let i of items&quot;&gt; ... &lt;/div&gt;<br>&lt;/div&gt;</pre><h3>✅ solution</h3><p>If for some reason you do need to wrap *ngFor inside *ngIf use ng-container instead of div because it will not create an extra html element.</p><pre>&lt;ng-container *ngIf=&quot;haveItems&quot;&gt; &lt;&lt; this if is redundant, ngFor will not render elements on empty array<br>  &lt;div *ngFor=&quot;let i of items&quot;&gt; ... &lt;/div&gt;<br>&lt;/ng-container&gt;</pre><h3>🚫 multiple async pipes</h3><p>All the mistakes presented above are close to nothing when compared to using multiple async pipes inside the same component. One can only imagine the complexity required to manage multiple observable properties and how hard is to sync the state between them.</p><pre>&lt;div&gt;<br>  &lt;div&gt;{{prop1 | async}}&lt;/div&gt;<br>  &lt;div&gt;{{prop2 | async}}&lt;/div&gt;<br>&lt;/div&gt;</pre><h3>✅ Solution:</h3><p>Avoid using multiple observable properties in the template, instead harness the power of rxjs and combine all the streams into a single stream and wrap the content of the template into a single subscription.</p><pre>&lt;ng-container *ngIf=&quot;viewModel | async as vm&quot;&gt;<br>  &lt;div&gt;<br>    &lt;div&gt;{{vm.p1}}&lt;/div&gt;<br>    &lt;div&gt;{{vm.p2}}&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/ng-container&gt;</pre><p>By following these guidelines, you can keep your Angular templates clean, maintainable, and efficient. Remember that the template’s primary role is to define the view, while the component should handle the logic and state management. This separation of concerns leads to better code organization and easier debugging.</p><h3>Programming should be easy and fun, not a painful experience!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7098f07cede6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Custom Directive to Capture Clicks on ng-template]]></title>
            <link>https://medium.com/@dsl400/adding-an-event-listener-to-the-content-of-ngtemplateoutlet-or-ng-template-4cf2c68af3fa?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf2c68af3fa</guid>
            <category><![CDATA[angular-tips-and-tricks]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[advanced-angular]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 14:35:29 GMT</pubDate>
            <atom:updated>2025-03-22T17:08:33.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HP4WOQBUaUAIsw6YzjZRaA.png" /></figure><p>If you are reading this, you are probably as obsessed as me about performance and optimization. First you tried this, but it did not work.</p><pre>&lt;ng-container *ngFor=&quot;let item of items&quot; (click)=&quot;onItemClick(item)&quot;&gt;<br>    &lt;ng-template [ngTemplateOutlet]=&quot;row&quot; [ngTemplateOutletContext]=&quot;{$implicit:item}&quot;&gt;&lt;/ng-template&gt;<br>&lt;/ng-container&gt;</pre><p>Then you tried this and it also did not work.</p><pre>&lt;ng-container *ngFor=&quot;let item of items&quot; &gt;<br>    &lt;ng-template (click)=&quot;onItemClick(item)&quot; [ngTemplateOutlet]=&quot;row&quot; [ngTemplateOutletContext]=&quot;{$implicit:item}&quot;&gt;&lt;/ng-template&gt;<br>&lt;/ng-container&gt;</pre><p>Every tutorial out here you kindly guides you to wrap your template inside a div or a span to be able to capture a click event.</p><pre>&lt;ng-container *ngFor=&quot;let item of items&quot; &gt;<br>    &lt;div (click)=&quot;onClick(item)&quot;&gt;<br>        &lt;ng-template [ngTemplateOutlet]=&quot;row&quot; [ngTemplateOutletContext]=&quot;{$implicit:item}&quot;&gt;&lt;/ng-template&gt;<br>    &lt;/div&gt;<br>&lt;/ng-container&gt;</pre><p>The thought of wrapping ng-template inside an element just to be able to capture a click event gave me a lot of sleepless nights. No! I will not submit to this madness. I will not wrap my ng-template inside an element.</p><p>Hmmm, I am sure there has to be a better way. Directives! Yes, directives should be able to help me out.</p><pre>@Directive({<br>  selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>  @Input(&#39;rowClicked&#39;) item: any;<br>  constructor(private el: ElementRef) {}<br>  @HostListener(&#39;click&#39;) onClick() {<br>    console.log(&#39;row clicked&#39;, this.item);<br>  }<br>}</pre><pre>&lt;ng-container [rowClicked]=&quot;item&quot; *ngFor=&quot;let item of items&quot;  [ngTemplateOutlet]=&quot;rowTemplate&quot; [ngTemplateOutletContext]=&quot;{$implicit:item}&quot;&gt;<br>    &lt;/ng-container&gt;</pre><p>Looks so good. So clean. So elegant. Aaaaaaand it does not work. This is the moment you start to question your life choices.</p><p>Let’s investigate further more.</p><pre>@Directive({<br>  selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>  constructor(private el: ElementRef) {<br>    console.log(el);<br>  }<br>}</pre><p>you will see in your console ElementRef {nativeElement: comment}. This means that you received a reference to a comment. This is because angular uses comment elements to make ng-template work. Not really sure how it works but it not relevant to us at this point.</p><p>In this state the element reference is not useful to us. There in not much you can do with it. You could try to use createEmbeddedView to render it but this is not needed in our case because it will be rendered in the end by Angular.</p><p>Binding an event</p><pre>@Directive({<br>  selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>  constructor(private el: ElementRef) {<br>    el.nativeElement.addEventListener(&#39;click&#39;, () =&gt; {<br>      console.log(&#39;row clicked&#39;);<br>    });<br>  }<br>}</pre><p>Ok, no errors, but it still does not work. Mainly because comment elements are not visible. Looking at the html output you will see that the comment element right under our desired content. Content that neatly stays there unwrapped by any element. :D</p><pre>&lt;my-component&gt; <br>    row 1 <br>    &lt;!--ng-container--&gt; <br>    row 2 <br>    &lt;!--ng-container--&gt; <br>    row 3<br>    &lt;!--ng-container--&gt;<br>    ....<br>&lt;/my-compoent&gt;</pre><p>So close yet so far. Hmmm … so close … so close … like peer close … just like siblings. Hmmm siblings … what if we could reference the sibling of the comment element.</p><pre>@Directive({<br>    selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>    constructor(private el: ElementRef) {<br>        console.log( el.nativeElement.previousSibling); <br>    }<br>}</pre><p>Aaaaand we get a bunch of nulls. Bummer … so close. Now that’s something that pisses me off. I am sure I am missing something. Back to the drawing board.</p><p>The content is there … or it will be there when Angular finishes its job. Hmmm … it will be there … let’s try to get a reference after Angular finishes its job.</p><pre>@Directive({<br>    selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>    constructor(private el: ElementRef) {<br>        setTimeout(() =&gt; {<br>            console.log( el.nativeElement.previousSibling); <br>        }, 0);<br>    }<br>}</pre><p>WOW! It works, we can get a reference to the sibling!!! Kind’a messy but it works. Let’s try to improve it a bit because setTimeout is not quite the best solution. I know … it works … but it might cause trouble on slower devices. How can we find out when Angular finishes rendering the content? Turns out Angular has a life cycle hook for that. One that it is actually abused and I personally hate using it.<br>ngAfterViewInit is the method angular uses to signal that the view has been fully initialized.</p><pre>@Directive({<br>    selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>    constructor(private el: ElementRef) {}<br>    ngAfterViewInit() {<br>        console.log( this.el.nativeElement.previousSibling); <br>    }<br>}</pre><p>Yep, it works. We can now get a reference to the sibling. Now we can use this reference to bind an event.</p><pre>@Directive({<br>    selector: &#39;[rowClicked]&#39;,<br>})<br>export class ClickDirective {<br>    @Input(&#39;rowClicked&#39;) item: any;<br>    constructor(private el: ElementRef) {}<br>    ngAfterViewInit() {<br>        const eventListener = () =&gt; {<br>            console.log(&#39;row clicked&#39;,this.item);<br>        }<br>        this.el.nativeElement.previousSibling.addEventListener(&#39;click&#39;, eventListener);<br>    }<br><br>    ngOnDestroy(){<br>      this.el.nativeElement.previousSibling.removeEentListener(&#39;click&#39;, eventListener);<br>    }<br>}</pre><p>So there it is … a directive that binds an click event to ng-template without the need to wrap it in an element. And they said it could not be done.</p><p>PS: Because nothing is perfect in this world, this method comes with a drawback. You will have to remove the event handler when the directive is destroyed because Angular is not aware of its existence. Many thanks to <a href="https://www.reddit.com/user/JeanMeche">u/JeanMeche</a> for pointing this out.</p><p>PS2: Turns out you can only attach event listener to node elements. This means that if you have a text node as a sibling you will not be able to attach an event listener to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf2c68af3fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Security Done Right: Limiting Access at the Endpoint Level]]></title>
            <link>https://medium.com/@dsl400/database-security-done-right-limiting-access-at-the-endpoint-level-a854441f8726?source=rss-391e67dd7ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a854441f8726</guid>
            <category><![CDATA[database-security]]></category>
            <category><![CDATA[rest-api-security]]></category>
            <dc:creator><![CDATA[Valentin Sasek]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 13:53:52 GMT</pubDate>
            <atom:updated>2025-02-15T11:40:47.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8OJmOsBSPQukAaXnfO64w.jpeg" /></figure><p>Almost every web-based project has a database. It stores all the data, making it the most critical part of your project. If you lose your database, you lose everything. That’s why securing it properly is essential.</p><p>When starting a project, you typically create a database user, grant it full access and then use this database user accross the entire application. This means that if a bad actor exploits any endpoint in your project, they gain unrestricted database access.</p><p>While it’s impossible to make a project 100% secure, just like you can’t make a ship unsinkable, you can make it significantly harder for attackers to access your data.</p><p>One of the main reasons early 20th-century ships sometimes sank was poor compartmentalization. When the vessel suffered damage, water entered through the breach and spread freely throughout the hull</p><p>The maritime industry improved ship safety by introducing compartments that could be sealed to contain flooding. The same principle applies to database security. Relying solely on endpoint logic while using a database user with unrestricted privileges introduces significant risk. Just as a ship without internal compartments is vulnerable to catastrophic flooding, a compromised endpoint with broad database access can lead to severe data breaches.</p><p>Database security is often approached by focusing on user permissions. Since users require permissions to perform operations, security efforts tend to center on controlling what users can and cannot do. However, this approach has a critical flaw: if an attacker exploits an endpoint, they inherit the same database permissions as the user they impersonate. If that user has administrative rights, the attacker gains full control over the database.</p><p>Instead of enforcing security at the user level, I believe it should be enforced at the endpoint level. The database should determine permissions based on the calling endpoint, not just the user.</p><p>This way, even if an attacker exploits an endpoint, their actions remain limited by the permissions assigned to that endpoint.</p><p>Depending on the database type, endpoint-based security can be enforced in several ways:</p><ul><li>Separate Users for Each Endpoint: Create a dedicated database user for each endpoint and grant only the necessary permissions to perform its operations.</li><li>Stored Procedures for Controlled Access: Use stored procedures to encapsulate database operations, restricting direct table access while enforcing specific execution rules.</li><li>Role-Based Access Control (RBAC): Assign roles with fine-grained permissions to endpoints, ensuring they can only execute permitted actions.</li></ul><p>By structuring your database security like a modern ship with watertight compartments, you minimize the damage a security breach can cause. Endpoint-based access control ensures that even if an attacker finds an entry point, they won’t gain unrestricted access to your entire database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a854441f8726" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>