DEV Community

Valeriy
Valeriy

Posted on

Configuring Codex/Claude CLI Agents: Practical Experience Organizing Work and the PrinciplesDriven Approach.

Version 19; 22.10.2026; ~3 thousand words; ~25-minute read; Difficulty: intermediate.

What the Principles Are

This is a condensed account of my experience configuring rules and agents for Codex and Claude, tested through several months of daily use, dozens of personal projects, and a migration between two LLM harnesses. The principles define goals and constraints for an audit; how they are implemented depends on the tasks and workspace.

Repository with the prompt and principles

How My Principles Differ from Similar Approaches

It comes down to a combination of several features:

  • The principles form a separate layer of assessment: they are used to check rules and skills for drift. They are independent of any particular implementation.
  • Periodic auditing of the rule corpus against the principles.
  • The approach grew out of a personal workspace with isolated projects and agents working in parallel. It contains substantially more documentation and rules than source code maintained by agents.
  • The principles emphasize project isolation, coordination of parallel writes, loading instructions on demand, and resuming work from a saved plan. This mitigates agents' main challenges: long-running autonomous work and context rot when working with long contexts.

A list of similar approaches appears at the end of the article. There are many similarities, but no exact match.

Who Might Find the Principles Useful

People who enjoy optimizing the rules for autonomous operation. Those who work extensively with agent skills and keep pushing for reliable behavior, against the odds.

I call my approach PrinciplesDriven. In it, the principles provide a basis for auditing and changing the rule corpus. The approach complements SpecDriven and EvalDriven: it helps optimize rules so that agents complete tasks faster and at lower cost while meeting defined input/output contracts and verifiable criteria for result quality.

I have also found the principles useful for sharing my experience and finding an existing rule corpus or set of principles suited to my tasks more quickly. My experience and rule corpus are now collected in a concise, carefully reviewed form. I know my way around them and can use or discuss them without a learning curve.

The Agents' Contribution to This Article

Agents helped distill the rules in use, check for duplication, errors, and conflicts, and find and compare similar approaches. For the most part, the agent acted as an editor.

I edited almost every line after each review iteration. I worked to stabilize the meaning of the principles and their prose description based on my projects' business goals and my own engineering experience.

I could not fully entrust the article to agents. The meaning and style changed, and errors appeared. Principles and business goals grounded in my experience mutated and shifted into areas I had not tested.

How the Principles Came About

The rules and skills were developed for Claude Opus from May through August 2026. In September, I moved them to Codex Astra because of OpenAI's less restrictive policies. I spent October documenting them and preparing the repository for publication.

The main configuration goal was to increase autonomy.

By autonomy, I meant achieving these business goals:

  • minimal user confirmations
  • work within project boundaries and documentation of changes
  • agents working on multiple projects in parallel
  • work spanning multiple days, with stopping and resuming
  • planning a sequence of tasks
  • compliance with limits and budgets
  • consistent quality.

The rule corpus for my current environment was built from scratch, without relying on publicly available recommendations. I refined it while gradually increasing the complexity of the tasks and the number of projects.

To identify obvious errors, I checked the resulting principles against published experiments and recommendations for organizing long-running autonomous agent work: Cursor, Anthropic 1, Anthropic 2, and OpenAI.

Some recommendations matched the principles I was using. Others would not have suited my tasks, implied costs beyond my budget, or required changes to the harness—the environment that executes and coordinates agents. That is why I consider the gradual, evolutionary approach I used justified.

Gradually developing the rule corpus gave me the experience I needed to choose suitable solutions. Without that experience, I would have struggled to distinguish useful additions from unnecessary ones and spent time filtering out recommendations that did not fit my tasks and constraints.

Once I considered the rules mature enough, I expressed their essence as principles. I condensed them into a short list that both people and agents could understand. This provides a basis for maintaining the connection between rules and business goals as skills, the model, the harness, and tools change.

A Word of Caution

The rule and skill corpus being stabilized has been through several months of almost daily use, dozens of projects, and a migration between two LLMs. I spent another month formalizing the principles. I consider that experience necessary before sharing it, but still not entirely sufficient for production use. Apply the principles with your own task context and budgets in mind.

Having a ready-made set of principles may accelerate rule development, but adapting them to your workspace can require an unreasonably large time and token budget. By now, the risks of budget overruns have earned their place of honor in statistics and forecasts and are actively discussed at conferences and in AI communities.

Applying the principles must account for acceptable trade-offs and context. For example, one characteristic of my environment and projects is the small share of code and large share of documents, so the principles concerning coding conventions have been tested less extensively.

So let us raise a glass to every risk being mitigated and every methodology being adapted to the capabilities and limitations of the environment and the tasks at hand. Variable naming and tab usage conventions deserve particularly careful adaptation.

Why Principles Are Needed

I needed to automate tasks spanning multiple days, with stopping and resuming, while 5–10 agents worked in parallel in a shared project directory.

Eventually, my workspace grew to about 50 projects.

Category File Types Files, thousands Lines, thousands
Documentation md 3 419
Code js/ts, css/html, py/sh 1.5 229
Rules/instructions agent, skill, md 0.5 30

The main obstacles to automation turned out to be the models' explicit and hidden constraints. Attempts to increase autonomy regularly ran into model and harness safeguards and repeated requests for user confirmation.

My experience suggests that LLM developers and users have conflicting goals. For example, model vendors introduce restrictions to prevent harm. This reduces agent autonomy and forces users to add permissions on top of prohibitive policies.

Agents often have to act with limited knowledge of the context surrounding the task. Conflicting instructions and safeguards make this work even harder.

In addition, increasing autonomy ran into a fundamental limitation: the nondeterminism (variability) of agent behavior. Put simply, the same prompt run at different times can produce different results.

If you want to explore variability in more depth, you can read this article. From there, you can look into the random selection of the starting point for gradient descent during training, or the probabilistic selection of a continuation when a trained model generates a response.

Back to the corpus. Variability kept me in a cycle of fixing errors with new instructions. The rule corpus grew longer, while the original requirements drifted away from the initial business goals. Long rules became difficult to read and monitor. Constantly reworking them burned time and tokens.

It seemed that I might eventually stabilize them, but no: updating or switching the model started the correction cycles all over again.

Fixing the input and output contracts did not stabilize the instructions. Conflicts or gaps in the rules burned through the token budget in repeated attempts to complete a task. There is a methodology for formalizing this loop-based approach: the Ralph loop. However, it does not solve the problem of optimizing rules, even with fixed input and output contracts.

Tests/evals could have helped localize the logic problem. But finding where degradation occurred in a sequence or group of rules would have required tracing or greater test coverage of rule steps. Implementing and debugging more detailed tests could have burned far more time and tokens than optimizing the rules without them.

So I took a step back to the goals behind the rules. I added a separate assessment layer to the corpus: key principles. And a way to apply them: a rule audit.

An audit makes it possible to identify and constrain degradation or drift in rule logic more precisely. The principles establish the boundaries or goals of rules based on business goals, workspace constraints, and task types.

I chose periodic audits as the assessment method. Approaches similar to mine sometimes call for an audit after every rule change, but I believe periodic checks will be cheaper and easier to implement.

The principles should be short enough for a person to maintain and clear enough to leave an agent little room for interpretation. Their wording is therefore simplified to control the constraints that most strongly affect the quality, speed, and cost of the final result.

As models evolve, some corpus instructions may become redundant or interfere with agent work after a model update. That is why the audit checks not only whether instructions conform to the principles, but also how the model applies them.

Model vendor recommendations help revise the principles. The rule corpus changes to reflect the new principles. Running typical scenarios checks whether the new rules are compatible with the model, whether execution has become faster or cheaper, and whether the result falls within acceptable parameters.

A Brief Introduction to the Principles

Why I Use a Shared Project Directory

In my workspace, agents working in parallel have access to the same files in a working directory divided into project subdirectories. This is convenient for individual work: all projects are available in the IDE or CLI without switching branches or working trees.

A shared Git index is used, with restrictions on which files are included in a commit. The command git commit --only -- <PATH1 PATH2 PATH3 ...> includes only the tracked files specified in PATHSPEC in the commit.

There is another approach. Model vendors recommend using git worktree to create separate working directories with their own index and HEAD.

Agents can change files independently in different working trees, but conflicting changes will have to be merged, for example through a PR or git merge. Agents can handle this too, so the difference may seem negligible.

Still, I believe git worktree is better suited to teams working on large codebases than to personal projects. For teams, git merge or PR review is routine. A map of module relationships and CI/CD automation help them coordinate changes.

Individual documentation and MVP projects are easy to isolate and can rely on advisory locking. If several agents want to change the same project, they wait for the lock to be released. If projects acquire dependencies, however, git worktree becomes preferable.

In simplified terms, the choice between these approaches is clear: a queue of plans and lock coordination versus a queue of PR reviews and coordination (synchronization) of changes in trees that have not yet been merged.

My approach uses a lock file containing a session identifier and timestamp to coordinate project locks. The session is considered the lock owner. Its tasks and subagents are not isolated from one another by this lock. Conflicting writes within a session are coordinated at the plan and task level.

Writes by other agent sessions to a locked directory wait for the lock to be released or for user approval, including after the TTL expires. Lock acquisition, release, and recovery are specified in detail when the principles are implemented in agent rules and skills.

Why Every Task Needs a Plan and a Commit

A plan is needed to describe sequential or parallel work by agents and subagents. It describes the necessary input and output contracts and the sequence of steps, and helps work continue after context compaction or an agent interruption.

For a small task, a plan can be just a few lines: the goal, change boundaries, a method for verifying the result, and the Definition of Done.

In my workspace, project directories and supporting files define how files are organized. Each project directory has a root AGENTS.md. Among other things, it specifies the project's full and short names. These are used to coordinate locks or select a project when invoking skills in the CLI.

Unfinished plans reside in the project's drafts subdirectory. They are archived after completion or replacement by other plans. The execution queue and follow-ups to completed plans are stored in the roadmap, while the backlog groups them by business goals. “It just evolved that way”: for a long time, I used only the roadmap to store plan execution priorities, and the backlog came much later.

The specification for maintaining mandatory documents is collected in a separate project, project-document-maintenance. I did not include a summary of its rules in the principles or the prose article.

A commit is mandatory after task execution. It records file changes, execution status, the plan, and the execution report. The commit creates a recovery point with a templated message that states not only the scope of the changes but also their WHY. If a commit cannot be created, the task is not declared complete. Canceled or failed tasks receive separate statuses.

Task state must be saved at more than just completion. Long-running work needs intermediate checkpoints, execution statuses, time and retry limits, and methods for stopping and reversing changes. On resumption, the saved state is checked against files, processes, and external actions already performed.

A Git commit preserves the state of the repository files included in it. Changes to external services, systems, and directories require separate methods for recovery and change history.

I prefer to make the mutable state of external services ephemeral or recoverable. For example, through configuration files and containers or virtual machine snapshots, and scripts for checking and configuring environments.

Why Instructions Need On-Demand Loading

One of the main limitations of modern LLMs is context size. It pushes up RAM and SSD prices. And the more context is filled, the higher the probability of errors.

That is why models have automatic context compaction/clearing, which can also be triggered manually with /compact. I supplemented this with decomposition into sequences of plans, delegation to subagents with clean contexts, and on-demand instruction loading.

In my environment, an agent's rule-reading sequence starts with the workspace root file, followed by the selected project's root file. These are AGENTS.md or CLAUDE.md. Skills can use a separate mechanism for progressively loading rules into context. To load rules, an agent needs a short instruction and a path to the rule file. Without directions on what to load and when, on-demand loading will not work.

The main/parent agent can launch auxiliary/child subagents. A subagent receives a limited set of instructions and returns its prepared result. This reduces the amount of the parent agent's context that is occupied and allows independent subtasks to run in parallel. Tasks suitable for delegation are those whose execution is easy to isolate and whose inputs and outputs can be formalized. Testing and search are examples.

Delegation to subagents has overhead: reloading instructions from the parent context, passing the assignment to the subagent, and checking and integrating the results. The cost of repeated loading must therefore be assessed, taking prompt caching into account.

Although avoiding subagents is becoming popular, when choosing between agents and subagents, I still consider reducing the risk of errors more important than the final execution cost.

A decision not to use subagents needs to account for side effects. compaction incurs costs for compression and subsequent restoration of necessary information from files. Some context data is deleted with no guarantee that it has been saved to disk. What remains may change in meaning.

A full cost assessment of delegation and context clearing seems difficult to me. I therefore take a simpler view of them as ways to reduce risk, without a detailed justification.

At one point, my rule corpus grew large enough to cause an incident in which instructions were forgotten because there were too many rules in context. I will quote the investigation here. It is interesting.

**Symptom:** In a 2026-05-05 ... an Opus agent traced an observed regression in rule adherence after a downgrade to Sonnet on the same workspace. The pre-rewrite CLAUDE.md held 444 lines / 47 distinct behavioral rules / 18 with conditional logic — analysis concluded ~20+ rules were active at any decision point. On Sonnet the agent silently shed rules under load (propose-before-write rule + Phase 5 commit-syntax rule were the most visibly missed).

**Root cause:** ... Session-derived estimate: Sonnet ~8–12 concurrent rules vs. Opus ~20+. When the active ruleset exceeds the lower model's working-memory ceiling, salience decay + momentum cause rule-shedding rather than rule-violation errors. The specific 8–12 / 20+ numbers are internal extrapolation from a single session's observed behavior — not Anthropic-published. Directionally consistent with Chroma "Context Rot" (13–85% perf drop with input length) and the OpenAI GPT-4.1 literal-following framing ...
Enter fullscreen mode Exit fullscreen mode

Since then, I have considered this a significant and growing risk, because the rule corpus keeps growing. To mitigate it further, I manually run /compact before executing a sequence of plans.

After introducing on-demand rule loading, I have had no incidents of forgotten instructions. If they recur, I will start using compact hooks to manage context compaction and restoration.

PreCompact and PostCompact are hooks for running handlers before and after compaction. They are available in the regular codex harness cli and can pause compaction through continue: false. However, they do not allow the agent to initiate compaction.

There are options for managing context compaction beyond hooks. These are directions for my future research, the next steps in the effort to increase agent autonomy.

Full control of compaction, including agent initiation, requires App Server. It provides the JSON-RPC method thread/compact/start. Using it, however, requires running AppServer and an MCP server for integration with the codex harness.

At the end of the article, there is a table of App+MCP+harness implementations for managing context compaction. Judging by the repositories' creation dates, this is the frontier of agent wrangling. I have not used them yet, because it looks like a month-long adventure.

It would make sense to add prompt routing to that adventure: routing prompts to reasoning modes of a single model with different costs, or to multiple models at different price points. This is currently standard practice for LLMs in production. But a cheaper call does not make the whole task cheaper: result verification, retries, and KV cache resets after model switches must be taken into account.

How to Optimize Rules and Skills

The main way to determine the extent of drift between agent skills, hooks, and rules and the principles is a periodic audit. The report contains a table of discrepancies and proposals for addressing them. Proposals must consider whether they introduce new gaps, duplicates, and conflicts into the rule corpus. Resolving one discrepancy can create another.

With on-demand loading, checking files separately is not enough. What is assessed is the combination of instructions the agent receives in a particular scenario: general rules, project rules, and loaded skills. Exceptional cases must be considered—for example, a required file may be referenced but not loaded by the agent because its loading conditions do not align. Shared/core rules are therefore assessed together with representative scenarios of their use in projects.

Auditing the text of the rule corpus does not prove that behavior improves after fixes. That requires checks on typical tasks and known incident scenarios, comparing results before and after the changes.

It is better to compare the current rules with versions optimized through the audit using the same scenarios and fixed model and harness settings. The cheapest starting point is a few of the most frequent scenarios or representative failures.

If my list does not contain a principle suited to your scenario, you can formulate one. The new principle can be used in combination with my audit prompt. Below, I have listed many similar approaches where you can look for suitable principles or rule sets.

Comparing the Principles with LLM Vendor Recommendations

Let us compare the coverage of my audit approach with the recommendations in OpenAI's article on evaluating skills.

The approaches align on checking the DoD and artifacts, combining script- and agent-based assessments, using recorded incident scenarios, and accounting for costs.

The OpenAI methodology does not explicitly describe recovery after execution stops or how to label unverified aspects. Its described regression detection after a skill change can stand in for the missing check of instruction compatibility with a model after a model update.

My principles do not separately check whether skill selection matches the task: explicit invocation, selection based on the task without naming the skill, selection with additional context, and not triggering on similar tasks outside its purpose. The principles for evaluating the evals themselves are not detailed either.

These differences grew out of my experience trying to increase agent autonomy. That effort focused on model and harness characteristics and context rot. Practical experience made them apparent.

Additional Links

Context Problems

Rule Evaluation

  • promptfoo - Open-source CLI/library for evals, prompt/model comparisons, red teaming, and CI/CD
  • LangSmith - Datasets, experiments, tracing, run comparisons, and online/offline evaluators
  • Braintrust - Evals, prompt evaluation, production monitoring, quality/cost/latency tracking
  • TruLens - Evaluation and observability for LLM/RAG applications
  • Arize Phoenix / Galileo / Langfuse - LLM observability, tracing, evals, and monitoring
  • OpenAI Evals - Documentation for an evaluation platform whose deprecation has been announced. Status and timelines are listed in deprecations. The vendor recommends migrating to promptfoo.

Similar Principle Collections and Ready-Made Rule Corpora

There are many similarities, but no exact match. A summary of the differences appears at the beginning of the article. Beyond that, any third-party solution has to be studied, adopted, and refined.

Article or Tool Similarities to the Principles Main Difference
Nick Tune - Coding Agent Development Workflows January 7, 2026 Principles are separated from a particular implementation: teams choose tools and the rules for using them. Shared conventions serve as a single source for different agents and review tools. The process improves in response to discovered errors; subagents help limit context. The main focus is the development process and the quality of its results, through to a completed PR. The article does not present a separate systematic audit of the instruction corpus against principles, with assessments of descriptions, application, and unverified aspects.
Synaptic Labs - Principle-Driven AI Collaboration June 18, 2025 Principles are explicitly communicated to the agent; decomposition, result verification, iterative improvement, and engineering constraints are used. The principles primarily describe the quality of generated code: component responsibilities, dependencies, error handling, and other conventions. They are included directly in implementation assignments.
Superpowers Plans, delegation to subagents, result verification, and skill loading. Testing the skills themselves against scenarios before and after a change is especially close to this approach. A ready-made set of skills and development processes; principles are tied to specific working methods, including design approval, TDD, and reviews.
GitHub Spec Kit The project “constitution” sets principles for subsequent stages. The analyze command checks consistency among the specification, plan, and tasks, detecting gaps and contradictions. This is a direct counterpart to the principles, but it primarily checks development documentation for an individual feature. The principles have a broader audit subject: general and project rules, skills, hooks, and their combined effect. Spec Kit Documentation
GSD Core Decomposition into phases and plans, parallel work, subagents with separate contexts, and state persistence. It has its own design and workflow conventions. A ready-made product development process. The principles describe GSD's structure and operation; my document focuses on auditing the workspace rule corpus.
OpenSpec Intent, requirements, design, and tasks are saved in Markdown; completed changes are archived. This aligns well with the requirement to preserve decision rationales outside the conversation. The approach centers on the lifecycle of a requirements change. Agent coordination and rule quality assessment are not its primary purpose.
Beads Persistent task memory, dependencies, selection of work ready for execution, and state handoff between sessions. Instead of Markdown plans and a roadmap, it uses a dedicated tracker built on Dolt. It addresses task state storage but does not, by itself, define audit principles.
MCP Agent Mail Messages between agents and advisory file reservations reduce conflicts in parallel work. Reservations are tied to an agent and an expiration time. Under the principles, the owner is a session, and TTL expiration alone does not authorize takeover. Reservations also do not block arbitrary filesystem writes.
12-Factor Agents - HumanLayer Context control, explicit state, stopping and resuming, small specialized agents, and moving suitable logic into ordinary code. Principles for building agent applications and harnesses. My text concerns configuring rules in an existing harness CLI environment.
Advanced Context Engineering - HumanLayer Research → plan → execution; subagents isolate search context and return summaries; decisions are saved before a context change. The main focus is working with complex existing codebases. Human review of research and plans plays a major role.

More Complex Alternatives

This section collects AppServer+MCP+harness combinations that work with codex. Directions for future work.

Repository Created / Updated Main Capabilities and Limitations
aresyn/codex-control-plane-mcp 2026-06-17 / 2026-09-09 Provides asynchronous operations, approvals, Plan Mode, protection against duplicate submission, state persistence in SQLite, diagnostics, and compaction management.
j-pollack/codex-app-server-mcp 2026-08-31 / 2026-08-31 A pool of parallel Codex agents through a single App Server; nonblocking launch, collection of group results, steering, resume/fork, approvals, and bounded event output. In-memory worker registry.
wyrd-company/async-codex-mcp 2026-05-29 / 2026-10-18 Connection to an already running App Server, asynchronous tasks, JSON session records on disk, questions and notifications through callback tools, and integration with Claude Code. Interactive App Server requests are not supported: its own callback questions do not replace all types of approvals.
redmikarimo/codex-supervisor-mcp 2026-07-31 / 2026-08-14 Launch, monitoring, steering, interruption, and reading saved conversations; explicit approvals for commands and files; Linux instructions. Event buffers and pending requests are held in memory.
xihuai18/codex-mcp 2026-02-16 / 2026-04-03 Four MCP tools, asynchronous sessions, event polling, permission management, and fork; App Server and a fallback codex exec mode. Interactive approvals are unavailable in exec mode;
zai-one/codex-mcp 2026-08-05 / 2026-09-26 SQLite jobs, schedules, retries, goals and budgets, approvals, compact, an audit trail, and worktree lanes. The repository is archived. Suitable for studying the architecture or creating a fork.

Top comments (0)