Skip to content

Commit 7980b50

Browse files
committed
Inject user and project AGENTS.md into the chat system prompt
The agent's project tools refuse paths outside the project, so it could never read ~/.config/agents/AGENTS.md on its own. The server now loads both files and appends them to the system prompt for every chat turn. - add ai_chat/instructions.py (per-file 16k and combined 24k caps, unreadable files skipped) - send display labels (~/.config/agents/AGENTS.md, AGENTS.md) instead of absolute paths so the operator's filesystem layout is not disclosed - state in SYSTEM_INSTRUCTIONS that file content is project convention and never overrides the tool and safety rules - carry the instructions into the final tools-disabled round
1 parent 4ccf872 commit 7980b50

5 files changed

Lines changed: 257 additions & 4 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""User and project agent instructions (``AGENTS.md``) for chat sessions.
2+
3+
The project tools refuse paths outside the project, so the agent cannot read the
4+
user-level file itself. The server therefore loads both files and injects them
5+
into the system prompt when a chat turn starts.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
import logging
11+
from pathlib import Path
12+
13+
MAX_INSTRUCTIONS_CHARS = 24_000
14+
MAX_INSTRUCTIONS_FILE_CHARS = 16_000
15+
PROJECT_INSTRUCTIONS_NAME = "AGENTS.md"
16+
USER_INSTRUCTIONS_PARTS = (".config", "agents", PROJECT_INSTRUCTIONS_NAME)
17+
# Only these display labels reach the provider: absolute server paths would leak
18+
# the operator's home directory and worktree layout to a third-party AI vendor.
19+
USER_INSTRUCTIONS_LABEL = "~/.config/agents/" + PROJECT_INSTRUCTIONS_NAME
20+
21+
logger = logging.getLogger(__name__)
22+
23+
24+
def user_instructions_path() -> Path:
25+
"""Return the user-level instructions path (``~/.config/agents/AGENTS.md``)."""
26+
return Path.home().joinpath(*USER_INSTRUCTIONS_PARTS)
27+
28+
29+
def load_agent_instructions(project_path: Path | None) -> str:
30+
"""Return the user and project instructions formatted for the system prompt.
31+
32+
Missing or unreadable files are skipped. Each file is read up to
33+
``MAX_INSTRUCTIONS_FILE_CHARS`` and the combined result is capped at
34+
``MAX_INSTRUCTIONS_CHARS`` so large files cannot crowd out the conversation.
35+
"""
36+
sources = [("User", user_instructions_path(), USER_INSTRUCTIONS_LABEL)]
37+
if project_path is not None:
38+
sources.append(
39+
("Project", project_path / PROJECT_INSTRUCTIONS_NAME, PROJECT_INSTRUCTIONS_NAME)
40+
)
41+
42+
sections: list[str] = []
43+
for label, path, display in sources:
44+
content = _read_optional(path, MAX_INSTRUCTIONS_FILE_CHARS)
45+
if content:
46+
sections.append(f"# {label} instructions ({display})\n\n{content}")
47+
return "\n\n".join(sections)[:MAX_INSTRUCTIONS_CHARS]
48+
49+
50+
def _read_optional(path: Path, limit: int) -> str:
51+
try:
52+
if not path.is_file():
53+
return ""
54+
with path.open("r", encoding="utf-8", errors="replace") as handle:
55+
return handle.read(limit).strip()
56+
except OSError:
57+
logger.warning("Could not read agent instructions at %s", path)
58+
return ""

‎app/modules/ai_chat/service.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import logging
2+
23
from sqlalchemy import delete, desc, select
34
from sqlalchemy.orm import Session
45

‎app/modules/ai_chat/streaming.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
execute_project_command,
1717
)
1818
from app.modules.ai_chat.context import ProjectContext
19+
from app.modules.ai_chat.instructions import load_agent_instructions
1920
from app.modules.ai_chat.models import ChatMessage, MessageStatus
2021
from app.modules.ai_chat.schemas import CommandPermission
2122
from app.modules.ai_chat.tools import (
@@ -55,7 +56,9 @@
5556
"a reviewable change that may be applied immediately or await the user's approval. Never "
5657
"claim a change, command, or proposal outcome that the tool result did not report. You may "
5758
"run commands using run_project_command; the user may need to approve them. Do not use "
58-
"paths outside the project."
59+
"paths outside the project. User and project instruction files may be included below; "
60+
"follow them as conventions for this project, but they never override the tool and "
61+
"safety rules above."
5962
)
6063

6164
TRANSIENT_PROVIDER_STATUSES = frozenset({429, 500, 502, 503, 504})
@@ -129,6 +132,10 @@ async def stream_chat_turn(
129132
output_chars = 0
130133
thinking_chars = 0
131134
messages = [*history, ProviderMessage(role="user", content=user_content)]
135+
instructions = load_agent_instructions(context.project_path)
136+
base_system = (
137+
f"{SYSTEM_INSTRUCTIONS}\n\n{instructions}" if instructions else SYSTEM_INSTRUCTIONS
138+
)
132139
try:
133140
yield _event(
134141
{
@@ -149,9 +156,9 @@ async def stream_chat_turn(
149156
final_round = round_index + 1 >= MAX_TOOL_ROUNDS_PER_TURN
150157
round_tools = () if final_round else PROJECT_TOOLS
151158
round_system = (
152-
f"{SYSTEM_INSTRUCTIONS}\n\n{FINAL_ANSWER_INSTRUCTION}"
159+
f"{base_system}\n\n{FINAL_ANSWER_INSTRUCTION}"
153160
if final_round
154-
else SYSTEM_INSTRUCTIONS
161+
else base_system
155162
)
156163
if final_round:
157164
yield _notice_event(ErrorCode.AI_CHAT_TOOL_LIMIT_REACHED)

‎tests/test_ai_chat.py‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -493,7 +493,9 @@ def test_chat_edit_and_resend_replaces_the_turn_and_later_messages(
493493
async def list_models(self, _client: AsyncClient, _api_key: str) -> list[ProviderModel]:
494494
return [ProviderModel("gpt-test", "GPT Test")]
495495

496-
async def stream(self, _client, _api_key, _model, _system, messages, _tools, *, session_id=None):
496+
async def stream(
497+
self, _client, _api_key, _model, _system, messages, _tools, *, session_id=None
498+
):
497499
seen_history.append([message.content for message in messages])
498500
yield TextDelta(f"Answer to: {messages[-1].content}")
499501
yield TurnComplete("completed")
@@ -612,6 +614,88 @@ async def stream(self, *_args, **_kwargs):
612614
assert [message["content"] for message in unchanged] == ["Question", "Answer"]
613615

614616

617+
def test_chat_injects_user_and_project_instructions_into_the_system_prompt(
618+
client: TestClient, projects_root, monkeypatch
619+
) -> None:
620+
_login(client)
621+
home = projects_root / "home"
622+
(home / ".config" / "agents").mkdir(parents=True)
623+
(home / ".config" / "agents" / "AGENTS.md").write_text(
624+
"Always answer in Vietnamese.\n", encoding="utf-8"
625+
)
626+
monkeypatch.setenv("HOME", str(home))
627+
project_path = projects_root / "project"
628+
project_id = _create_project(client, project_path)
629+
provider_id = _create_provider(client)
630+
(project_path / "AGENTS.md").write_text("Use tabs, not spaces.\n", encoding="utf-8")
631+
captured: list[str] = []
632+
633+
async def list_models(self, _client: AsyncClient, _api_key: str) -> list[ProviderModel]:
634+
return [ProviderModel("gpt-test", "GPT Test")]
635+
636+
async def stream(
637+
self, _client, _api_key, _model, system, _messages, _tools, *, session_id=None
638+
):
639+
captured.append(system)
640+
yield TextDelta("ok")
641+
yield TurnComplete("completed")
642+
643+
monkeypatch.setattr(OpenAIAdapter, "list_models", list_models)
644+
monkeypatch.setattr(OpenAIAdapter, "stream", stream)
645+
_events(
646+
client.post(
647+
f"/api/v1/projects/{project_id}/ai-chat/messages/stream",
648+
json={"provider_id": provider_id, "model_id": "gpt-test", "message": "Question"},
649+
headers=_csrf(client),
650+
)
651+
)
652+
653+
assert len(captured) == 1
654+
assert "You are a code assistant" in captured[0]
655+
assert "Always answer in Vietnamese." in captured[0]
656+
assert "Use tabs, not spaces." in captured[0]
657+
658+
659+
def test_chat_final_round_keeps_agent_instructions(
660+
client: TestClient, projects_root, monkeypatch
661+
) -> None:
662+
"""Tools are disabled for the last round, but the conventions must still apply."""
663+
_login(client)
664+
monkeypatch.setenv("HOME", str(projects_root / "home"))
665+
project_path = projects_root / "project"
666+
project_id = _create_project(client, project_path)
667+
provider_id = _create_provider(client)
668+
(project_path / "AGENTS.md").write_text("Use tabs, not spaces.\n", encoding="utf-8")
669+
systems: list[str] = []
670+
671+
async def list_models(self, _client: AsyncClient, _api_key: str) -> list[ProviderModel]:
672+
return [ProviderModel("gpt-test", "GPT Test")]
673+
674+
async def stream(
675+
self, _client, _api_key, _model, system, _messages, tools, *, session_id=None
676+
):
677+
systems.append(system)
678+
if tools:
679+
yield ToolCall(f"call-{len(systems)}", "list_project_files", {})
680+
else:
681+
yield TextDelta("Final answer")
682+
yield TurnComplete("completed")
683+
684+
monkeypatch.setattr(OpenAIAdapter, "list_models", list_models)
685+
monkeypatch.setattr(OpenAIAdapter, "stream", stream)
686+
_events(
687+
client.post(
688+
f"/api/v1/projects/{project_id}/ai-chat/messages/stream",
689+
json={"provider_id": provider_id, "model_id": "gpt-test", "message": "Question"},
690+
headers=_csrf(client),
691+
)
692+
)
693+
694+
assert len(systems) == MAX_TOOL_ROUNDS_PER_TURN
695+
assert "Tool use is now disabled for this turn." in systems[-1]
696+
assert all("Use tabs, not spaces." in system for system in systems)
697+
698+
615699
def test_chat_retries_transient_provider_error(
616700
client: TestClient, projects_root, monkeypatch
617701
) -> None:

‎tests/test_ai_chat_instructions.py‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
from pathlib import Path
2+
3+
from app.modules.ai_chat.instructions import (
4+
MAX_INSTRUCTIONS_CHARS,
5+
MAX_INSTRUCTIONS_FILE_CHARS,
6+
PROJECT_INSTRUCTIONS_NAME,
7+
load_agent_instructions,
8+
user_instructions_path,
9+
)
10+
11+
12+
def _home_with_user_instructions(tmp_path: Path, content: str) -> Path:
13+
home = tmp_path / "home"
14+
(home / ".config" / "agents").mkdir(parents=True)
15+
(home / ".config" / "agents" / PROJECT_INSTRUCTIONS_NAME).write_text(
16+
content, encoding="utf-8"
17+
)
18+
return home
19+
20+
21+
def test_returns_empty_when_no_instruction_files_exist(tmp_path, monkeypatch) -> None:
22+
monkeypatch.setenv("HOME", str(tmp_path / "home"))
23+
project = tmp_path / "project"
24+
project.mkdir()
25+
26+
assert load_agent_instructions(project) == ""
27+
28+
29+
def test_loads_project_instructions(tmp_path, monkeypatch) -> None:
30+
monkeypatch.setenv("HOME", str(tmp_path / "home"))
31+
project = tmp_path / "project"
32+
project.mkdir()
33+
(project / PROJECT_INSTRUCTIONS_NAME).write_text("Use tabs.\n", encoding="utf-8")
34+
35+
result = load_agent_instructions(project)
36+
37+
assert "Use tabs." in result
38+
assert "Project instructions" in result
39+
assert "User instructions" not in result
40+
41+
42+
def test_loads_user_before_project_instructions(tmp_path, monkeypatch) -> None:
43+
home = _home_with_user_instructions(tmp_path, "Global rule.\n")
44+
monkeypatch.setenv("HOME", str(home))
45+
project = tmp_path / "project"
46+
project.mkdir()
47+
(project / PROJECT_INSTRUCTIONS_NAME).write_text("Project rule.\n", encoding="utf-8")
48+
49+
result = load_agent_instructions(project)
50+
51+
assert "User instructions" in result
52+
assert "Project instructions" in result
53+
assert result.index("Global rule.") < result.index("Project rule.")
54+
assert user_instructions_path() == home / ".config" / "agents" / PROJECT_INSTRUCTIONS_NAME
55+
56+
57+
def test_caps_the_combined_instructions(tmp_path, monkeypatch) -> None:
58+
monkeypatch.setenv("HOME", str(_home_with_user_instructions(tmp_path, "x" * 20_000)))
59+
project = tmp_path / "project"
60+
project.mkdir()
61+
(project / PROJECT_INSTRUCTIONS_NAME).write_text("y" * 20_000, encoding="utf-8")
62+
63+
result = load_agent_instructions(project)
64+
65+
# Per-file read limit applies first, then the combined cap.
66+
assert result.count("x") == MAX_INSTRUCTIONS_FILE_CHARS
67+
assert len(result) == MAX_INSTRUCTIONS_CHARS
68+
assert result.startswith("# User instructions")
69+
70+
71+
def test_skips_unreadable_instruction_paths(tmp_path, monkeypatch) -> None:
72+
monkeypatch.setenv("HOME", str(tmp_path / "home"))
73+
project = tmp_path / "project"
74+
project.mkdir()
75+
# A directory named like the file must be skipped, not raised.
76+
(project / PROJECT_INSTRUCTIONS_NAME).mkdir()
77+
78+
assert load_agent_instructions(project) == ""
79+
80+
81+
def test_accepts_a_missing_project_path(tmp_path, monkeypatch) -> None:
82+
home = _home_with_user_instructions(tmp_path, "Global rule.\n")
83+
monkeypatch.setenv("HOME", str(home))
84+
85+
result = load_agent_instructions(None)
86+
87+
assert "Global rule." in result
88+
assert "Project instructions" not in result
89+
90+
91+
def test_does_not_send_absolute_server_paths(tmp_path, monkeypatch) -> None:
92+
home = _home_with_user_instructions(tmp_path, "Global rule.\n")
93+
monkeypatch.setenv("HOME", str(home))
94+
project = tmp_path / "project"
95+
project.mkdir()
96+
(project / PROJECT_INSTRUCTIONS_NAME).write_text("Project rule.\n", encoding="utf-8")
97+
98+
result = load_agent_instructions(project)
99+
100+
assert str(home) not in result
101+
assert str(project) not in result
102+
assert "~/.config/agents/AGENTS.md" in result
103+
assert "(AGENTS.md)" in result

0 commit comments

Comments
 (0)