Agent Instructions Plugin
The Agent Instructions plugin folds two kinds of extra prose into the agent's
prompt:
- Operator
custom_instructions— global directives set viaprompt.custom_instructions. Always injected when set. - Per-user custom instructions — each signed-in user's own standing preferences, edited under Settings → Custom instructions (web and TUI) and injected below the operator block. Appended to the operator's
custom_instructions, never replacing them. On by default (user_instructions_enabled), capped atuser_instructions_max_chars. Design:doc/core-dev/design/custom-instructions.md. - Repo-local instruction files:
AGENTS.md,CLAUDE.md,GEMINI.md,.cursor/rules, Copilot / Windsurf / Cline rules and anything else you list, discovered in the repositories under analysis. They are injected when the agent's work touches their scope, not all up front. Opt-in; off by default. Design:doc/core-dev/design/dynamic-agent-instructions.md(phases 1-2 built).
It is a builtin, not a config-listed plugin. Do not add it to
plugins:. Override behaviour with a top-levelagent_instructions:
section. Listing it underplugins:would skipcustom_instructionson
any deployment that forgot the entry.
Repo-local discovery is off by default so existing deployments keep their
current prompt: custom_instructions still apply, and a repository's own
CLAUDE.md is not mixed in until you enable it.
How repo-local guidance reaches the agent
When repo_local_enabled: true, each repository is indexed once (at first
use, and again when its HEAD, an indexed file or a scope directory changes,
or after the repositories were updated). Nothing is walked per prompt.
Units. Every instruction file whose scope is the same directory joins one
unit, whatever agent it was written for: the repo root's AGENTS.md +
CLAUDE.md + .cursor/rules/* form the unit <repo>:, and ui/AGENTS.md
forms <repo>:ui. Files identical after normalizing (frontmatter stripped,
whitespace collapsed) collapse into one; the rest are concatenated in
filenames order.
Merging per-agent variants. A unit with two or more distinct files is
merged into one text by an offline LLM call (merge: auto, the default),
routed through the model role agent_instructions_merge (a housekeeping
role, assignable like auto_title). The merge runs in the background after
indexing; until it is done the unit is the concatenation, so no prompt waits
for it. The call gets each file with its path, its agent and its last commit
date, and returns the merged text, a one-line summary, the conflicts (the
more recently changed file wins) and the agent-specific mechanics that do not
translate. A deterministic gate then checks that every backticked span,
make … target and file path of the sources survives (in the merged text,
an agent-specific part, or a conflict's dropped side) and that the merged
text is no longer than the sources. A failed gate is retried once, telling
the model what it lost; after that the unit stays concatenated
(merge_status: fallback). Outcomes are cached under the instance home's
data directory (agent_instructions_merges/, one JSON file each), keyed by
the sources' hashes, the prompt version and the model id: shared by every
user, kept across restarts. A merged unit's text carries <agent_specific source="…"> parts and one <conflicts> line after the merged guidance (the settings pane marks it merge_status: llm). When a merge finishes its unit gets
a new rev; a conversation that already holds the older text gets the new
one on its next touch. Eager units are pinned per conversation: a running
conversation keeps the eager text its prefix was first sent until a source
file changes, so a finished merge never rewrites its prefix (new
conversations get the merged text). The catalog line is taken from the
sources, never from the merge, for the same reason. merge: off (or a
merge_overrides entry for a scope) keeps the concatenation.
Rules with their own trigger. A rule file whose frontmatter declares a
condition is a unit of its own, <repo>:<path> (declared_triggers):
| Source | Becomes |
|---|---|
.cursor/rules/* alwaysApply: true | part of its folder's unit |
.cursor/rules/* globs: | a rule injected when a matching path is touched |
.cursor/rules/* description: only | agent-requested: a catalog line; loads when read |
.cursor/rules/* without any of these | manual: a catalog line; loads when read |
.claude/rules/, .clinerules/ paths: | a path rule (no paths: the folder's unit) |
.github/instructions/*.instructions.md applyTo: | a path rule (empty or **: the folder's unit) |
.windsurf/rules/* trigger: always_on / glob / model_decision / manual | folder unit / path rule / agent-requested / manual |
Globs are repo-relative; a rule in pkg/ gets pkg/ in front, and a pattern
without / matches at any depth (.ts = /.ts). Comma lists and
{a,b} braces expand. Frontmatter that does not parse joins the folder's
unit (fail open).
Nested directories are indexed by default (recursive, bounded by
max_depth / max_nested_files). Vendored and generated trees
(node_modules, vendor, third_party, .venv, dist, build, target,
…) and hidden directories are pruned at any depth.
Catalog. The prefix carries an <agent_instruction_catalog> with one line
per unit (- Codumentor/ui: … [Codumentor/ui/AGENTS.md], - Codumentor rule), grouped by
"migrations" (agent-requested): … [ …/migrations.mdc]
repository; above catalog_max_units it lists only repository names.
Injection mid-turn. When a tool call touches a path, the applicable units
are appended to that tool result: the repo root's unit, then each ancestor
directory's unit, root to leaf (the nearest sits lowest), then the path rules
that match.
| Signal | Source |
|---|---|
| paths | read_file / write_file / replace_in_file file_path, ripgrep search_dir |
| shell_cd | a shell command's cd <dir> (cd repo/ui && npm test); a second cd, pushd or $VAR target is no signal |
| direct read | read_file of an instruction file itself: a <unit-loaded/> marker when it is the unit's only source, else the combined unit |
<agent_instructions repo="Codumentor" trigger="read_file Codumentor/src/x.py">
<note>Guidance from the repository, now in scope. …</note>
<unit id="Codumentor:" rev="3f2a…" sources="CLAUDE.md, .cursor/rules/project.mdc">
…
</unit>
</agent_instructions>
A unit goes in once: before each LLM call the plugin reads which
<unit id rev> / <unit-loaded> markers the prompt holds, and skips those
(two parallel reads of one repository inject once). A unit whose tool result
was cleared by compaction or summarized away comes back
on the next touch, and an edited file comes back with its new rev. With
sticky_guidance: true a stripped (or forgotten) result keeps its block:
the prompt reads [tool result removed] followed by the block, so the unit
stays active and is not injected again. A <unit-loaded/> marker is never
kept, since the file it stands for leaves with the result. Units
past per_injection_max_bytes go out as [… and <repo>/<dir> guidance: read pointers.
<path>]ripgrep without search_dir and path words in a shell
command without cd are no signals.
A client recognizes guidance in a stored tool result by its text: a block
from <agent_instructions repo="…" trigger="…"> to </agent_instructions>
appended to the result, or a bare <unit-loaded id="…" rev="…"/> line.
Injection at turn start. Two signals act before the turn's message is
stored (onInputReceived). What they bring in is written to the history as
one durable note (a user-role message) just above the message, so it
stays where it was on every later turn and the prompt cache holds:
| Signal | Source |
|---|---|
| query | the user's message (a subagent's briefing) names a repository the user may see, as a whole word (case-insensitive), or an existing repo-relative path (Codumentor/ui/src/App.tsx): the root unit, or the path's units |
| focus | the conversation holds exactly one repository: its root unit is eager in the prefix from the start; if the set narrows to one repository later, its root unit goes into a durable note instead |
Units already active are skipped; the note is capped by
query_inject_max_bytes. The stored message carries metadata.durable_note,
metadata.synthetic_note, metadata.source: "agent_instructions" and
metadata.agent_instructions: {"signals": ["S4"|"S6"], "repos": [...],, which is how a client finds it to draw a "Repository
"units": [...]}
guidance" chip. Every query match logs event=query_match.
Modes. Each unit is auto (catalog + injection, the default), eager
(a prefix note from turn 1, the pre-index behaviour), on_request (catalog
line only; loads when its file is read) or excluded (never shown).
mode_overrides sets them per glob over <repo>/<path>; a pattern may name a
file or a scope directory, and the last matching entry wins. Excluding one
file drops it from its unit and keeps the rest. include_global files are
always eager. total_max_bytes caps the eager block only.
Per-user modes. A user may set any unit's mode for themselves (stored as
instruction_modes: {unit id: mode} in this plugin's per-user settings),
unless an operator locked glob covers the unit's key (<repo>/<scope>, or
<repo>/<file> for a rule) or one of its files. Whether repo-local guidance
is on at all stays operator-only. A change to an eager or catalog unit costs
one prompt-cache miss in that user's open conversations.
The stored note does not reach the web client (it reads events, not stored
history), so the plugin also emits plugin.agent_instructions.guidance_note
(status, summary, signals, repos, units, text = the block). The web
transcript draws it as a collapsed "Repository guidance:
the turn's message, the same chip a tool result's <agent_instructions> block
or <unit-loaded/> marker becomes; the TUI folds both to one line.
Settings-pane API
The web client's Settings → Repository guidance section uses these
routes. PUT /ui/settings merges per key, so saving custom instructions there
leaves instruction_modes alone.
Mounted under /ui/plugins/agent_instructions (authenticated; the plugin
declares repo_access: per_repo, and every answer is filtered to the
repositories the caller's access profile holds).
GET /guidance[?preview=false]:
{
"repo_local_enabled": true,
"modes": ["eager", "auto", "on_request", "excluded"],
"default_mode": "auto",
"repos": [{
"repo": "Codumentor",
"units": [{
"id": "Codumentor:", "key": "Codumentor", "repo": "Codumentor",
"label": "Codumentor (root)", "kind": "group", "scope_dir": "",
"trigger": {"kind": "scope", "always": false, "paths": ["**"],
"description": null, "manual": false},
"sources": [{"path": "CLAUDE.md", "also": ["AGENTS.md"],
"family": "claude", "sha256": "…", "text": "…"}],
"summary": "…", "rev": "3f2a…", "bytes": 4210, "merge_status": "single",
"merge": {"status": "single"},
"operator_mode": "auto", "user_mode": null, "mode": "auto", "locked": false,
"preview": "<unit id=\"Codumentor:\" rev=\"3f2a…\" …>…</unit>"
}]
}]
}
trigger.kind is scope (a folder's unit), paths, description
(agent-requested) or manual. merge_status is single (one distinct
file), concat (merge off), pending (merge running, concatenated
meanwhile), llm (merged) or fallback (the merge failed: no model, a model
error, or the gate twice). For llm and fallback, merge also carries the
record: merged, summary, conflicts (topic, kept, dropped,
reason), agent_specific (source, text), gate (passed, reason,
missing), model, attempts, created_at, last_changed (path → commit
date) and ms. preview is the exact text injected, and each source's
text the file itself; both are left out with ?preview=false. The pane
shows a merged unit's text, conflicts and gate verdict beside its sources.
PUT /guidance/mode with {"unit_id": "Codumentor:ui", "mode": "eager"}
(null clears the user's mode) returns that unit's view without preview.
Errors: 403 the unit is locked, 404 no such unit for this caller, 409
repo-local guidance is off, 422 an unknown mode. Note that the generic
PUT /ui/settings replaces a plugin's whole settings record: a client saving
custom_instructions that way must send back the instruction_modes it
loaded.
Debug events. Every decision is one DEBUG line on
codumentor.plugins.agent_instructions: event=signal|inject|activate|, each with
late_guidance|unused_injection|active_budget|index|query_matchconv,
agent, turn and iter; event=merge (repo, units, ms,
merge_status, conflicts, gate, attempts) logs each finished merge.
Mine them with rg 'event=inject'. The CLI
session report adds a "Repository guidance" line.
Binary-looking files (NUL bytes) are skipped; each file is truncated to
per_file_max_bytes and each unit to per_unit_max_bytes. Repo-provided
guidance is labeled as subordinate to the agent's core operating
instructions. @path imports are off by default (resolve_imports); imports
that leave the repo, form a cycle, or exceed max_import_depth become a
visible [import skipped: …] notice.
Configuration
Override under a top-level agent_instructions: section (builtin — do not
add it to plugins:). Set the prose itself under prompt.custom_instructions:
prompt:
custom_instructions:
- "Always answer in the user's language."
agent_instructions:
enabled: true # master switch (custom_instructions + repo-local)
user_instructions_enabled: true # Settings → Custom instructions, per user
user_instructions_max_chars: 4000 # cap (form, PUT /ui/settings, injection)
user_instructions_placement: prefix # prefix | pre_query (just before the live query)
repo_local_enabled: true # index repos for CLAUDE.md / AGENTS.md / … (default on)
filenames:
- AGENTS.md
- AGENTS.override.md
- CLAUDE.md
- GEMINI.md
- .clinerules
- .claude/rules
- .cursorrules
- .cursor/rules
- .windsurf/rules
- .github/copilot-instructions.md
- .github/instructions # *.instructions.md only
include_global: false # also ~/.codumentor/<file> + config_file_dir/<file> (eager)
recursive: true # index nested scopes; injected only when touched
max_depth: 6
max_nested_files: 100
default_mode: auto # eager | auto | on_request
mode_overrides: {} # "<repo>/<path glob>": eager | auto | on_request | excluded
locked: [] # globs users may not override with their own mode
declared_triggers: true # .mdc / paths / applyTo / trigger frontmatter -> rule units
signals: [paths, shell_cd, query, focus]
catalog_max_units: 200
per_file_max_bytes: 32000
per_unit_max_bytes: 32000
per_injection_max_bytes: 24000
query_inject_max_bytes: 8000 # the turn-start durable note
active_max_bytes: 64000 # soft: exceeding it is only logged
total_max_bytes: 96000 # eager block only
merge: auto # auto | off: LLM merge of a folder's per-agent files
merge_overrides: {} # "<repo>" / "<repo>/<scope>" glob: auto | off
sticky_guidance: false # keep a block in the prompt after its result is stripped
reread: mtime # mtime | always | once (index rebuilds)
resolve_imports: false # @path includes
max_import_depth: 5
target_agents: all # main | subagent | all
Parameters
- enabled (optional): Master switch. When false, nothing is injected — neither
custom_instructionsnor repo-local files (default:true) - repo_local_enabled (optional): Discover and inject repo-local instruction files.
custom_instructionsis unaffected (default:true) - filenames (optional): File or directory names to index in each scope directory; a unit concatenates its files in this order. Defaults to the list above.
- include_global (optional): Also look in
~/.codumentor/<file>and<config_file_dir>/<file>; these are always eager (default:false) - recursive (optional): Index nested scope directories (default:
true) - max_depth / max_nested_files (optional): Bounds of the nested scan (defaults:
6/100per repository) - default_mode (optional): Mode of every unit no override names —
auto,eageroron_request(default:auto) - mode_overrides (optional): Glob over
<repo>/<path>→ mode, last match wins;excludedremoves a file from its unit (default:{}) - locked (optional): Globs over
<repo>/<path>whose units users may not give their own mode (default:[]) - declared_triggers (optional): Parse rule-file frontmatter into rule units; off, every file joins its folder's unit (default:
true) - signals (optional): Which signals inject:
paths,shell_cd,query,focus(default: all). The retiredrepo_args(the removedgit_committool's repository) is still accepted and ignored - catalog_max_units (optional): Above this the catalog lists repository names only (default:
200) - per_file_max_bytes / per_unit_max_bytes (optional): Truncation budgets per file and per unit (default:
32000each) - per_injection_max_bytes (optional): Cap on one block appended to a tool result; the rest go out as pointers (default:
24000) - query_inject_max_bytes (optional): Cap on the turn-start durable note (query / focus); the rest go out as pointers (default:
8000) - active_max_bytes (optional): Soft cap on all active units; exceeding it is logged, nothing is evicted (default:
64000) - total_max_bytes (optional): Ceiling on the eager prefix block; overflow is dropped with a visible notice (default:
96000) - merge (optional):
automerges a unit's distinct files with theagent_instructions_mergemodel role in the background (cached, gated, concatenated until ready or when it fails);offconcatenates (default:auto) - merge_overrides (optional): Glob over a unit's key (
<repo>for the root,<repo>/<scope>for a folder) →auto/off, last match wins (default:{}) - sticky_guidance (optional): Keep an injected block in the prompt after its tool result is cleared by compaction or is forgotten; the unit stays active instead of being re-injected on the next touch. Applies to results written while it is on (default:
false) - reread (optional): When the index is rebuilt —
"mtime"(on aHEAD, file or scope-directory change),"always"(before every prompt) or"once"(once per process) (default:"mtime") - resolve_imports (optional): Resolve
@pathimports (default:false) - max_import_depth (optional): Max import recursion depth (default:
5) - target_agents (optional): Which agents receive the instructions —
"main","subagent", or"all"(default:"all")
Notes
- Prompt assembly never fails because of this plugin: on error it injects nothing and the turn continues.
- If a deployment ships a custom prompt template that still embeds
<additional-instructions>itself,custom_instructionswould appear twice. - Repo-local discovery reads repository content into the prompt, so it is off by default and left to the operator to enable per deployment.
- Access profiles. Only repositories the user's access profile holds appear in the catalog, the eager block or a tool result: a chat-only user gets none, a scoped user gets their repositories'. The
repo=attribute is the configured repository name. Global files (include_global) are the deployment's and are not scoped.