AI coding without amnesia: inside the MyGuard workflow

Claude and Codex share one set of Markdown workflow instructions here, and the long-term memory behind our AI coding workflow is a SQLite full-text index. That’s a deliberately boring foundation for something people keep trying to sell with pictures of glowing brains, and boring is easier to inspect when something breaks.

In short: this is how MyGuard splits AI-assisted coding into mirrored project memory, shared skills, an autonomous workflow called grind, deterministic checks and two review gates. You get what each part is for, where a safeguard is only documented rather than proven, and the smallest version worth copying.

The real question is practical. Can an agent find the right project, remember last month’s decision, change one function without trampling someone else’s work, test the result and survive a context reset without starting over? Then somebody still has to check the work.

I inspected this setup in September 2026. The parts that move fastest (context limits, stop rules and the review tooling) were checked again against the current workflow files on 27 November 2026 and are corrected below. Where a safeguard is documented but I haven’t watched it work, I’ll say so. Measured productivity and defect-reduction figures still don’t exist.

Table of Contents

What do we mean by memory?

A coding agent’s conversation is temporary working space. It holds the current task, the files it just read, tool results and instructions. Sooner or later that space fills up, gets summarised or vanishes with the session.

Writing a lesson to disk gives the next session something to retrieve. It doesn’t train the model, and saving a Markdown file or a SQLite record changes none of its weights.

Think of a workshop. The conversation is what the people on the current shift remember. Persistent memory is the job board, the maintenance log and the note explaining why the apparently redundant valve must stay open. You want the next shift to read that note before it “cleans up” the plumbing.

The mirror follows the projects

Our memory tree mirrors the repository layout. Project knowledge lives under the matching project path, with a small index pointing to the relevant files. That answers a practical question: whose knowledge is this?

A packaging constraint shouldn’t quietly become a rule for every application. A workaround in one nginx module shouldn’t spread to unrelated modules because an agent retrieved a familiar-looking paragraph. Scope is part of the fact.

File or record What belongs there
Project index Where to look next
Issues and TODOs Work that remains, with enough detail to act
Lessons Verified causes, constraints, and decisions worth remembering
History Outcomes that need a durable record
Handoff The current state needed to resume interrupted work

The mirror gives Claude and Codex one place to read and write. They don’t keep competing notebooks and reconcile them now and then; the shared tree is the working record.

That still needs coordination. Two agents can overwrite the same file, and a filesystem will happily preserve the last mistake it receives.

Remember the expensive part

Useful memory captures something that’s costly to rediscover. “The parser is in this file” is cheap to find again with code search. “This harmless-looking configuration change breaks an older consumer, and here is the evidence” has a far better claim on permanent storage.

Keeping every command from an investigation gives you a transcript. Keeping the cause of the failure and the condition that triggers it gives you a lesson. That difference matters when the next agent only has room for a few paragraphs.

Our memory workflow checks for structure, stale claims, oversized context, orphaned material and duplication. Cold history can leave the small working files without losing its durable evidence.

Memory needs retirement rules as much as it needs an “add” button. Otherwise it turns into a museum where every exhibit is labelled “current”.

Where does SQLite fit in an AI coding workflow?

SQLite holds the searchable long-term corpora, while Markdown stays the editable working surface. Small, hand-edited records live in Markdown; SQLite adds structured storage and bounded search over everything that has to last.

Internal memories and curated external knowledge sit in separate corpora. A project decision and a paragraph lifted from upstream documentation have different origins, so their provenance and freshness have to stay visible when they come back from a search.

Diagram of memory retrieval: project working notes and sourced external knowledge kept as separate durable corpora, with search results checked before use
Working notes and sourced external knowledge use separate durable corpora. Search results still need verification.

Searchable doesn’t mean intelligent

When I inspected it in September, the store used SQLite FTS5, a full-text search extension, with BM25 relevance ranking. It searches words and tokens. It isn’t a vector database, and nothing in it is an embedding.

The phrase “semantic chunks” can blur that. Here it means chunks follow meaningful document boundaries such as headings and checklist items, which keeps context around a passage. It doesn’t mean each paragraph was turned into a mathematical representation of its meaning. SQLite documents how FTS5 works.

Technical material is full of distinctive project names, function names and error messages, so lexical search fits it well. But a query using different words can miss the right lesson, and a highly ranked result can be obsolete. Retrieval hands you candidates to inspect, not answers.

Small results protect the working context

The search interface returns bounded results: identifiers, metadata, short snippets, and a note when results were truncated or the query widened. The agent then loads only the records that matter.

That keeps the archive out of every conversation. It also makes the search inspectable: you can see which record supported a decision, instead of accepting “I remember something about this” as an engineering reference.

Agents only get named commands such as search, get, archive and history. There’s no raw SQL and no delete or rewrite operation, so a confused agent can’t quietly edit history.

While researching this article, I found an older instruction claiming every query term was required. The implementation actually widened an empty result to any-term matching and flagged it, which is useful: a broad fallback deserves a more sceptical reading. It also shows that instructions about a search engine can go stale while the engine keeps working.

Preserve the source, then question it

The store keeps a manifest for each document plus its ordered chunks. Verification can rebuild the document and check recorded lengths and a SHA-256 digest, a compact fingerprint of the bytes. The fingerprint answers “did we keep the same document?” Whether the document is right needs a separate check.

External knowledge is only admitted with provenance: source identity, publisher, a digest and a retrieval timestamp with a timezone. Those fields make later verification possible. Filling in a publisher field doesn’t authenticate the publisher.

Archiving is ordered for interruptions. It commits and verifies the SQLite copy first, then publishes the Markdown archive, then rewrites the live file. A crash between stages can leave a duplicate, which beats losing evidence, and exact re-ingestion is deduplicated.

That’s the sort of ordering you learn to appreciate once the power cut stops being theoretical.

Use the configuration that exists

In September the memory store ran SQLite in rollback-journal mode, specifically DELETE, with synchronous=FULL, foreign-key enforcement, a busy timeout and trusted_schema=OFF.

Describing it as using write-ahead logging, or WAL, would be wrong. WAL is a different SQLite mode with its own concurrency and checkpoint behaviour. Readers can overlap a writer under WAL, but there’s still only one writer at a time. SQLite’s WAL documentation explains the constraints.

A popular tuning article isn’t evidence about our database.

Two operational questions deserve as much attention as search. First, what happens when a record goes stale? The ranking doesn’t enforce every review deadline, so the reader still checks current evidence.

Second, what survives a clean clone? The databases are gitignored, so cloning the repository alone won’t bring them back.

Backups, retained source material and tested restores need their own attention. A green Git status is a remarkably poor backup strategy.

How do Claude and Codex share skills?

A skill is a reusable procedure: when it applies, what evidence to gather, which actions to take and how to recognise that you’re done. Memory records what we learned. Skills describe how we work.

The canonical workflow files live in the Claude skill tree. Codex discovers mirrored entries that mostly point at those same files through symbolic links, filesystem pointers to another path. Two discovery layouts reach one maintained document.

Fix the canonical procedure once and both agents see the fix. That cuts duplicate editing. It doesn’t make the two runtimes identical.

Shared procedure, different adapters

Both products document skills, but the bridge between them is our integration choice, not a promise that their native instruction handling is interchangeable. OpenAI’s skill documentation and Claude Code’s skill documentation describe each product’s interface.

The bridge maps workflow intent onto whatever the current runtime offers. A model label in a procedure describes an intended cost or reasoning tier. It doesn’t license pretending an unavailable model exists.

A specialised workflow can have a bounded fallback, but the fallback must report what actually ran. It can’t claim an independent review happened because the same agent reread its own answer with a more serious expression.

Routing has a few jobs: identify the repository, pick the workflow, check which capabilities are available and hand repeatable work to tools. Stronger reasoning goes where uncertainty or consequences justify it. Separate workers go where their output can be integrated and checked.

Give tools the repeatable work

Code lookup has a fixed order. First comes Serena, a code-navigation server the agents reach over the Model Context Protocol, or MCP. Next is our own code-context router for finding the right project, then plain text search and structural search with ast-grep. Detailed reading comes last, when the evidence calls for it.

None of these dumps a whole repository into the conversation. MCP is a way to expose tools and data, and for plenty of local work a command-line interface, or CLI, is enough. An MCP entry in a config file doesn’t prove the tool started, that this session can call it, or that what it returns is trustworthy.

The division of labour is deliberate. Use a script for a repeated transform, a linter for an established rule and model judgement for whatever stays ambiguous. Asking a large model to count files is an expensive way to get a less reliable wc.

The same thrift applies to instructions. A session loads a small router, the selected skill and only the references the task triggers. A WordPress publishing rule has no business in a C ownership investigation unless the task really spans both.

Instructions and interlocks are different things

A Markdown rule can tell an agent to stop. A hook can reject the tool call.

Our Codex hook configuration routes the shared hook scripts through an adapter that translates each runtime’s payloads, so the enforcement logic exists once. But three states have to stay separate:

State What it establishes
Configured A rule or hook is declared
Checked A particular checker examined part of the setup
Enforced The running system applied the restriction

A parity checker can pass without proving the two agents behave the same. Detecting that a trusted hook hash is present, for example, is weaker than showing every current hook hash is trusted.

A box labelled “sandbox” in a diagram doesn’t establish isolation. The code, the launch configuration and the observed behaviour have to agree.

How does grind’s warden-supervisor-worker workflow work?

Grind is our autonomous backlog workflow. It takes an approved queue through implementation, verification and delivery using three layers. A warden keeps the run alive, a supervisor manages the engineering, and a worker implements one bounded assignment.

Each layer has its own context and its own reason to exist. The top layer solves a practical problem: a backlog can outlive one supervisor’s conversation, and a supervisor can’t arrange its own next shift after its current one has ended. Somebody outside that conversation has to start the replacement.

Diagram of grind's three roles: the warden manages the run, the supervisor owns engineering decisions and the worker implements one assigned slice
The warden manages lifecycle; the supervisor owns engineering decisions; the worker implements its assigned slice.

The warden keeps the run alive

The warden is always the main chat session. It fixes the approved repository scope and worktree arrangement, starts a supervisor, waits for it to return and decides whether to start another cycle or stop.

It deliberately stays out of project source and technical decisions. Its checks are small: does the returned status have the required fields, did the handoff file change during the cycle, and do the claimed merges appear in the supervisor’s list of verified PRs?

That proves the reporting is consistent, not that a patch is correct. The warden can’t judge an nginx ownership bug from a cycle counter, and nobody asks it to.

Keeping the role small is the point. A warden that reads every diff and debug transcript becomes one more overloaded supervisor.

The supervisor owns the engineering decisions

The supervisor reads the saved handoff, checks it against the current repository state and picks work from the queue. It owns acceptance criteria, dependencies, tier selection, worker dispatch, verification, review, delivery and the next handoff.

The queue has two phases: findings first, then the roadmap. In-flight fixes and correctness problems beat cosmetic work. Finishing a phase triggers a recount and a transition. It doesn’t authorise inventing a new project to keep busy.

For each item, the supervisor searches durable memory once and passes the record identifiers and constraints to the worker. A worker shouldn’t spend its first ten minutes rediscovering why last week’s obvious shortcut was rejected.

When the worker returns, the supervisor checks the branch and commits, the actual diff, the test evidence and any reported PR. A worker saying “done” is a claim. The supervisor wants evidence before it marks the row done, and that check still doesn’t replace the CodeRabbit and PR-Agent review gates.

The worker receives a job, not a blank cheque

A worker implements one queue slice on one branch at one model tier. A slice may bundle related small sweep items when they share scope and don’t break dependencies.

The packet names the item, what must stay true, the completion criterion, the verifier, the worktree and the relevant memory. The worker runs the required checks, keeps its work and returns concrete identifiers and evidence.

If the job needs an architecture or contract decision the worker can’t settle, it returns a decision packet. It doesn’t quietly rewrite the acceptance criterion until its patch qualifies.

Workers also don’t spawn more workers, widen the repository scope, ask the user questions or approve their own review. Three layers are enough. An org chart that reproduces by mitosis is an incident waiting for a budget.

Three layers doesn’t mean a swarm editing one tree

Delegation happens in the foreground. The warden waits for its supervisor, and the supervisor normally runs one implementer at a time. It’s a chain of responsibility, not several workers writing to the same checkout at once.

External work can stay in flight. A PR can wait on remote CI while the supervisor handles another item that doesn’t depend on it. The handoff records the branch, PR, review state, last poll and next action, so waiting work doesn’t vanish from view.

Parallel work needs isolated ownership. A slow remote job needs a cursor and a time to look again. Neither problem is solved by letting two agents share an index and hoping they’re polite.

A complete cycle has an observable result

A cycle starts by reading the handoff and comparing its recorded progress with Git, the queue, the verifiers and remote state. The supervisor checks whether the ledger files changed, rechecks the next row against live state and only then dispatches a worker.

After verifying the return, it applies the review and delivery rules, revisits in-flight PRs, updates the ledgers and writes the next handoff. Related sweep items can reach a validated commit without a separate PR for every tiny change.

The supervisor’s return is a compact status record with counts and identifiers, not pasted logs. The warden routes it like this:

Returned state Meaning and next action
continue Resume in a fresh supervisor cycle.
done All approved repositories passed completion checks; stop.
gated Preserve the classified hard blocker and stop.
ask Relay if attended; otherwise record the question and gate.
Invalid return Retry once; stop after a second failure.

A continue needs an updated handoff, or the replacement supervisor has nothing to continue from.

The completion check is stronger than finding a heading that says “zero open”. An actual row enumeration and a separate mechanical recount must agree. The warden checks the reported counts; it doesn’t read the backlog itself.

Our nginx module template with working CI is a good starting point here: a project should already have meaningful checks the worker can run and the supervisor can assess.

What happens when context reaches 150k?

For a grind worker, 150k is the hard guard. At that point it stops starting new work, finishes the step it’s on and hands over. Each worker tier also has a lower soft reference, and these are our workflow thresholds, not advertised model limits.

A token is a piece of text as the model sees it. “150k context” is what one agent currently carries: instructions, files it read and tool results. It isn’t 150,000 words, 150,000 tool calls or the lifetime usage of the whole run, and the thresholds apply to each agent separately.

The numbers have changed since September. Back then the supervisor had a 125k soft ceiling and a 200k hard stop, and workers stopped at 200k too. The current workflow files no longer state those supervisor numbers, and the diagram below still shows the old ones.

Diagram of grind context thresholds as documented in September 2026: preparation margin, soft ceiling and hard stop
Thresholds as documented in September 2026. The table below gives the current worker values.

Start the handover before the window is full

Here are the current worker references, checked on 27 November 2026:

Worker tier Soft reference Hard guard
Haiku 70k 150k
Sonnet 100k 150k
Opus 140k 150k

The soft reference is a decision point, not an automatic handover. The worker weighs what finishing costs against what a fresh start costs, and it can carry on with a coherent piece of work below the hard guard. Both values scale down for a model with a smaller usable window.

At the hard guard, nothing new starts until the state is saved. A Claude worker can’t see its own token count and can’t compact itself, so a hook tells it when it has reached the guard. It then finishes the current step and returns continue with its evidence paths and the exact next action. Codex compacts natively at the role’s limit instead.

The main chat has its own signal. In an ordinary session, a warning at 120k on a 200k window (scaled to the actual window) means “write the handoff now”. A main chat acting as grind’s warden doesn’t stop for that warning and keeps dispatching, because its state already lives on disk.

These are documented procedures. I haven’t verified that every agent stops at exactly these numbers, and a bigger advertised context window doesn’t cancel the local guard.

A fresh worker is cheaper than restarting the whole run

When a worker hits its guard, it saves its assigned artifact and the exact next steps, then returns to the supervisor. The supervisor checks what exists and can give the rest of the slice to a fresh worker in the same phase.

The approved scope, acceptance criteria and delivery cycle all survive. A context replacement doesn’t create a new feature or justify another sweep PR. The supervisor may still have plenty of room, so rotating a worker doesn’t throw away the queue manager’s context.

A fresh supervisor starts from the saved state

Every cycle, the supervisor writes the ledgers and the handoff before it returns. On a continue, the warden checks the return and starts the next cycle with a fresh supervisor.

The new supervisor reads the handoff and compares the recorded commit, next item, verifier result, live queue row and in-flight PR state with what exists now. A mismatch becomes a reconciliation job: find out what changed before doing anything else.

It doesn’t rebuild the plan from the original prompt or reopen a finished criterion because the explanation got lost in the reset. Closed work stays closed unless new contradicting evidence is recorded. The conversation changes; the engineering state stays anchored to saved evidence.

Diagram of a grind handover: the outgoing supervisor saves its state and a fresh supervisor reconciles it before continuing the same goal
The outgoing supervisor persists state. Its replacement reconciles that state before continuing the same goal.

What must survive the handover?

The handoff is a short checkpoint. It points to evidence instead of pasting whole logs or diffs. The ledgers keep the backlog, while the checkpoint carries enough state for a stranger to resume.

It names the approved repositories and the active phase, the goal and acceptance criteria, the next item, verified decisions and exact blockers. For in-flight work it records the branch and PR, CI and review state, the last progress and the next action.

Polling cursors matter too: when the last check ran and which bot comments were already handled. Otherwise a fresh supervisor spends its first cycle answering yesterday’s comments again.

A progress fingerprint ties the goal, current commit, next item and verifier result together, and ledger timestamps tell the next cycle whether its saved queue view is stale. Keep evidence in its own files and record the paths. Every new supervisor pays to read the checkpoint again.

Compaction and handover have different rules

Compaction condenses a conversation so it can carry on. A handover saves the state and lets another context take over. Neither may erase the acceptance contract.

Supervisors don’t compact themselves to stretch their windows. They save their state and return. The main session is always the warden, and the workflow never starts an extra warden below it.

The warden can’t ask Claude to compact itself mid-run, so automatic compaction is its supported recovery. Afterwards the warden rereads its instructions and the handoff and reconciles ownership before routing anything. Compaction can keep a conversation going, but it isn’t the auditable record of what was delivered.

A worked example: CI is still running

Here’s an illustrative case, not a specific run. A worker reaches its guard while a PR’s required CI is still running.

It records the PR and head commit, the CI state it saw, the last poll time, the review evidence and the next action. Once its local work is consistent and saved, it returns continue to the supervisor.

The successor checks the recorded head against the current job state. If the same head is still running, it follows the recorded polling cadence or does other work that doesn’t depend on it. It doesn’t rebuild the patch, reset the review history or call normal waiting a hard blocker.

If the PR head changed, the successor works out which evidence went stale. A fresh context must not inherit a green badge without checking what that badge approved.

A reset must not reset the loop guard

Fresh context only helps if the run remembers its failures as well as its achievements. A new cycle never resets the no-progress history or speeds up polling.

The September version had fixed counts: stop after a few no-progress cycles, and a 25-cycle allowance per run. Both are gone. Cycle, spending and time totals are now telemetry, and none of them ends a run.

What replaced them is stricter. After a failure the workflow has to change its approach, and repeating the same action with the same result requires a different recovery method. A run stops only for proven completion, a verified external dependency or a decision outside its approved authority. Repeated CI failures get three recovery attempts without real progress, then the retries stop.

A useful drill at a milestone: from the saved records and the repository alone, can a fresh context name the goal, the settled criteria, the forbidden shortcuts, the next action and the verifier? If an answer still lives only in the old conversation, fix the handoff while that conversation exists. The next shift should be able to work without holding a seance.

How does a change reach a pull request?

A pull request, or PR, proposes a change for review before it lands on a shared branch. Our PR workflow starts with the repository’s delivery policy, because not every repository uses PRs.

The superrepo takes signed direct commits on master. The packaging checkout takes signed direct commits on main. Project work that needs a PR goes through a temporary worktree and remote CI (continuous integration: automated jobs that build and check a proposed change).

For PR work, the long-lived checkout is the control checkout. Changes happen in a temporary linked worktree based on a freshly fetched default branch. A linked worktree is a separate working directory sharing the same Git storage, which keeps the main checkout out of the middle of several unfinished jobs.

Diagram of the delivery path for an eligible production pull request, where repairs send the candidate back for fresh review evidence
The eligible production PR path. Repository policy controls applicability; repairs renew the relevant review evidence.

Freeze the thing being reviewed

Before final review, the candidate is staged and checked. Staging selects what goes into the next commit; relevant tests and deterministic lint run first.

Coverage gaps stay visible. A missing analyser hasn’t examined the code, and the output must say so instead of turning that absence into a clean result.

Reviewers get bounded delivery context: intended behaviour, relevant constraints, and verified linked issues or a concrete reason none applies. Then the candidate must hold still.

A review of yesterday’s tree doesn’t approve a function changed five minutes ago. The local process ties evidence to identifiers such as the staged tree and digests of the diff and context. A receipt shows which artifact was reviewed. It doesn’t certify the artifact is bug-free.

Every finding needs an outcome

Reviewer output is a list of claims to investigate. A confirmed finding gets fixed or recorded in the right ledger. A wrong finding gets refuted with evidence. “Non-blocking” describes merge risk; it doesn’t make the observation disappear.

That stops reviews turning into archaeological layers of unresolved comments.

Repairs change the candidate. PR-Agent runs again on every changed candidate until a run comes back clean. The local CodeRabbit CLI runs once per pre-commit cycle and isn’t rerun just because its own finding was repaired. A moving progress bar proves very little; the evidence has to belong to the change.

Green must belong to the current change

Remote CI has to be substantive and green for the current PR head. A pass on an earlier commit is stale evidence, and a job that does almost nothing can be green too. What the check means matters as much as its colour.

After the push, CodeRabbit’s GitHub app reviews the PR as well, and merging waits until both CI and that review are green on the current head. If the app is rate-limited, the PR stays open and the pending review is recorded.

Our nginx test harness article shows the underlying concern: checking behaviour needs deliberately chosen tests. A process that starts successfully hasn’t proved anything about its shutdown, reload or resource handling.

Commits are signed, but a signature proves something different from a test: it ties the commit to a signing identity. Neither replaces the other.

After the merge, a clean control checkout already on its default branch can be fast-forwarded. A dirty or differently parked checkout gets reported instead of forcibly “fixed”. Where the superrepo tracks the project as a submodule, its gitlink then catches up to the merged commit. That restraint protects work the current task doesn’t own.

Why both CodeRabbit and PR-Agent?

CodeRabbit and PR-Agent are the standing review gates for eligible production code. Eligibility comes first, and GitHub hosting alone doesn’t make a change eligible.

Documentation-only work, memory, repository housekeeping, operations and infrastructure troubleshooting don’t get these gates just because a script or a Git checkout is involved. Checks should match the task and its risk. A gate that can’t say anything useful about a change burns time and money without adding evidence, which is why this article never went through either.

What CodeRabbit contributes

CodeRabbit offers AI-assisted code review through several surfaces, including a CLI. The CLI reviews uncommitted changes and can emit structured findings for an agent. Its documentation separates CLI review from PR review, which serves a later stage. CodeRabbit CLI reference

We run the CLI before commit, after the deterministic checks, and the GitHub app reviews again after the push. The benefit is another chance to catch a wrong assumption or an overlooked behaviour, and its output still needs verifying.

We haven’t measured a defect-reduction rate for this setup. Claiming it catches some fraction of bugs would be invented.

Our PR-Agent runs through a local wrapper

In September, our PR-agent was a custom review harness of its own. That has changed. It now runs a locally patched copy of the upstream PR-Agent review engine through our own wrapper.

The wrapper uses subscription CLIs, never a model API key: Claude Code’s CLI or Codex’s CLI. A successful run has to produce non-empty Markdown and parseable JSON, and exit status alone isn’t a pass.

One engine per run, the other as fallback

Each run picks one of the two CLIs at random and keeps the other as the fallback. A review served by the fallback is a complete review; nobody reruns it just to hear from the other engine. If both fail, the review is incomplete and the gate blocks.

A provider failure can trigger the fallback. An unfavourable finding can’t. Otherwise the loop becomes “keep asking until someone says yes”, which is less a quality system than an expensive permission slip.

Different model families can offer different perspectives, and they can share blind spots too. Agreement between reviewers isn’t a correctness proof.

Give the reviewer a defined boundary

The September harness built a separate candidate snapshot with read-only source files. Its configuration restricted source writes and tool networking, with disposable scratch space for builds, tests and caches.

Configuration shows the intended boundary. Proving isolation takes runtime verification. Restricting tool networking also doesn’t make a hosted-model review offline, because talking to the provider and letting tools reach the network are different questions.

Repository content stays untrusted. A changed instruction file is part of the candidate under review, not permission for the reviewer to change its own rules. Commands suggested in review output need scrutiny before anyone runs them.

The same gap between declared restrictions and tested behaviour shows up in our guide to Docker hardening. Controls protect different boundaries, and their configuration has to match the workload.

Why build our own ast-grep rules?

Once we understand a recurring mistake, the next question is whether a deterministic rule can recognise it. That’s the job of myguard-labs/ast-grep-essentials, our public rule corpus: handcrafted structural checks with explicit fixtures and stated limits. A reviewed detector catches the same recognisable mistake on the next change.

A model may draft a rule, but it doesn’t get the final word. The fixtures and ast-grep’s own test run decide whether the rule passes.

Diagram of turning a recurring mistake into a tested ast-grep rule with positive cases, safe near misses and integration checks
A rule is a maintained detector: test its positive cases, safe near misses and integration behaviour.

Text search and structural search see different things

Text search sees characters. Structural search works on the parsed shape of the code, the abstract syntax tree or AST. A rule can express relationships such as one call appearing inside a particular construct.

Depending on the matcher, words inside comments or strings can be ignored because they aren’t the relevant syntax node. Ast-grep’s rule language combines patterns and structural conditions.

That’s useful for local conventions that generic scanners don’t know. Our nginx work has project-specific APIs and lifecycle expectations, and a repeatable shape can be worth checking automatically even when the original explanation took real reasoning.

Syntax is only part of behaviour. An AST match doesn’t establish types, ownership, dataflow across functions or whether a pattern is an actual vulnerability. Those questions stay with other analysers, tests and review.

Test the detector’s boundary

A rule needs examples it should flag and examples it should leave alone. Ast-grep supports invalid and valid fixtures for exactly that, and its documentation separates correct detection, correct silence, missed detection and noise. Ast-grep rule testing

Our authoring workflow requires positive examples, safe near misses, and comment or string controls. Fixtures are parsed as inert snippets, never executed.

Near misses show whether a rule recognises the intended condition or merely something nearby. A detector that flags every call to an API might catch all the bad examples. It might also ruin everyone’s afternoon.

Some advisory rules deliberately match code that can be safe. That’s fine when the limitation is stated and the message asks for the right review.

A passing run can still be useless

Did the runner find the intended fixtures? Does the rule identifier match? Did anyone independently review the changed expected output?

An empty run can pass, and a snapshot can be regenerated to match a broken detector. So the workflow checks inventory and discovery, requires snapshot review, and expects a behaviour fix to fail with the old matcher and pass with the new one.

Integration needs the same care. A warning can print output while the process still exits successfully. Promoting a rule to blocking has to be deliberate and verified; writing “mandatory” above its command doesn’t make it a gate.

This loop is also why a concrete defect story such as the zstd module fixes is useful beyond the patch. Once the cause is understood, ask which part can become a regression check: a test, a structural rule or a deeper analysis obligation.

Make a rule when it earns its maintenance

Every finding needs a disposition. A new lint rule also needs a convincing maintenance case.

A good candidate repeats, has a recognisable local shape and can be detected with manageable noise. A poor one depends on deep context the matcher can’t represent. Rejected experiments stay out of active rule discovery.

The aim is to move repeatable work into cheap, reviewable checks and leave the uncertain reasoning to tools and reviewers suited to it. No need to hire a philosopher every time somebody forgets the same guard clause.

What still needs attention?

This architecture has more moving parts than “agent writes code”. That buys useful controls and more things that can drift. These questions deserve an operational answer, not a reassuring box in a diagram.

Does the memory survive a rebuild?

Markdown, database files, retained source documents, configuration and credentials all have different recovery needs. For the gitignored corpora, the useful test is a demonstrated restore: recover the records and rebuild their documents.

A documented backup command proves a capability, not when the last good backup or restore happened. I didn’t establish the backup schedule or restore evidence for this article, so I won’t pretend I did.

Are stale records getting retired?

Search relevance doesn’t measure truth. Records need source dates, review routes and a way to mark superseded decisions. Otherwise a well-written obsolete answer outranks an awkward current one.

The query-widening mismatch in our own instructions is a small example. This article needed the same treatment: several of its grind numbers were out of date within three months of writing. The maintenance system needs maintenance too.

Do the checks detect what we think they detect?

Coverage needs its own evidence: fixture discovery, negative controls, analyser availability, the right repository scope and proof that review receipts belong to the final artifact.

More checks can mean more assurance. They can also mean more empty jobs, and counting jobs doesn’t tell the two apart.

Are we measuring the benefits?

The expected benefits are less repeated investigation, more consistent handling of familiar defects, continuity across sessions and extra review perspectives. We have no reliable measurements for defect reduction, false-positive rates, total cost or delivery speed.

Useful measures would be accepted versus refuted reviewer findings, escaped regressions, rule noise, failed memory searches and time spent waiting on gates. Track those before claiming the workflow is faster or safer by any percentage.

Can the workflow explain why it stopped?

Permissions, unavailable providers, stalled progress and resource limits need distinct outcomes. A provider outage isn’t a finding. A missing analyser isn’t a clean scan. The stop reason should name the operation and the way to recover.

Counting work and deciding when to stop are separate choices. Cycle and spending counts are recorded for observation but never end a run on their own. A stop has to come from completion, a verified external wait or a decision outside the run’s authority.

Start with the smallest useful system

You don’t need our whole arrangement to use these ideas. Start with repository instructions, a small project memory index and one task with checkable acceptance criteria. Keep changes isolated, and add meaningful tests and an independent review route.

Then watch what repeats.

If knowledge keeps getting lost, improve retrieval. If the same mistake comes back, consider a tested rule. If work repeats after interruptions, improve the saved state and the reconciliation. Let observed failures justify the machinery.

The apprentice types very quickly. Keep the job board readable.