Skip to content

Commit 5b91595

Browse files
krokokobgagentcursoragent
authored
docs(agents): split AGENTS.md and add post-merge lint workflow (#191) (#533)
Restructure agent context into a root router plus package guides (cdk, cli, agent, docs) with commands-first layout, testing sections, and tri-tier boundaries. Document the post-merge eslint workflow from #191 and cross-link from CONTRIBUTING and the developer guide. Co-authored-by: bgagent <bgagent@noreply.github.com> Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 98736c1 commit 5b91595

10 files changed

Lines changed: 427 additions & 131 deletions

File tree

.github/CODEOWNERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
.semgrep @aws-samples/coding-agents-admin
1919
.threat-composer @aws-samples/coding-agents-admin
2020
AGENTS.md @aws-samples/coding-agents-admin
21+
**/AGENTS.md @aws-samples/coding-agents-admin
2122
CLAUDE.md @aws-samples/coding-agents-admin
2223
CODE_OF_CONDUCT.md @aws-samples/coding-agents-admin
2324
contracts @aws-samples/coding-agents-admin

AGENTS.md

Lines changed: 80 additions & 127 deletions
Large diffs are not rendered by default.

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Describe what you intend to contribute. This avoids duplicate work and gives mai
1616

1717
Follow the [Quick Start](./docs/guides/QUICK_START.mdx) to clone, install, and build the project. See the [Developer guide](./docs/guides/DEVELOPER_GUIDE.md) for local testing and the development workflow.
1818

19-
Use **[AGENTS.md](./AGENTS.md)** to understand where to make changes (CDK vs CLI vs agent vs docs), which tests to extend, and common pitfalls (generated docs, mirrored API types, `mise` tasks).
19+
Use **[AGENTS.md](./AGENTS.md)** to understand where to make changes (CDK vs CLI vs agent vs docs), which tests to extend, and common pitfalls (generated docs, mirrored API types, `mise` tasks). Package-specific detail lives in **`AGENTS.md`** under `cdk/`, `cli/`, `agent/`, and `docs/`.
2020

2121
### 3. Implement your change
2222

agent/AGENTS.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# Agent runtime — agent context
2+
3+
Parent guide: [../AGENTS.md](../AGENTS.md)
4+
5+
You maintain the **Python agent runtime** bundled into the CDK-deployed image: pipeline, runner, hooks, prompts, policy, and progress events.
6+
7+
## Commands (run these)
8+
9+
```bash
10+
mise //agent:quality # lint, type-check, pytest
11+
mise //agent:security # agent-scoped security checks
12+
cd agent && uv run pytest -v # verbose single run
13+
cd agent && uv run pytest tests/test_progress_writer.py -v
14+
```
15+
16+
Root `mise run build` includes `//agent:quality` in parallel with `//cdk:build`.
17+
18+
## Testing
19+
20+
- **Full quality gate:** `mise //agent:quality`
21+
- **Verbose pytest:** `cd agent && uv run pytest -v`
22+
- **Single file:** `cd agent && uv run pytest tests/test_hooks.py -k test_name`
23+
- **With coverage:** see `agent/mise.toml` / `pyproject.toml` for project defaults
24+
25+
| Code | Test location |
26+
|------|---------------|
27+
| `progress_writer.py` | `agent/tests/test_progress_writer.py` |
28+
| `hooks.py`, `policy.py` | `agent/tests/test_hooks.py`, `test_policy.py` |
29+
| `pipeline.py`, `runner.py` | `agent/tests/test_pipeline.py`, etc. |
30+
31+
Use `@pytest.fixture(autouse=True)` to reset shared module state between tests when handlers use circuit breakers or caches.
32+
33+
## Primary locations
34+
35+
| Path | Access | Purpose |
36+
|------|--------|---------|
37+
| `agent/src/pipeline.py`, `runner.py` | WRITE | Task execution loop |
38+
| `agent/src/config.py`, `hooks.py`, `policy.py` | WRITE | Runtime config and gates |
39+
| `agent/src/prompts/` | WRITE | System prompts per workflow |
40+
| `agent/src/progress_writer.py` | WRITE | TaskEvents emission |
41+
| `agent/tests/` | WRITE | pytest suite |
42+
| `agent/README.md` | WRITE | Env vars, PAT notes |
43+
| `cli/src/commands/watch.ts` | WRITE (if event schema changes) | Event consumer |
44+
45+
## Code style
46+
47+
**Progress events** — use `_ProgressWriter`; do not write DynamoDB directly from random call sites:
48+
49+
```python
50+
# ✅ Good — typed writer method (table from TASK_EVENTS_TABLE_NAME env)
51+
from progress_writer import _ProgressWriter
52+
53+
writer = _ProgressWriter(task_id=task_id)
54+
writer.write_agent_milestone("clone_complete", "Repository cloned")
55+
56+
# ❌ Bad — raw boto3, no circuit breaker, ad-hoc shape
57+
dynamodb.put_item(TableName=table, Item={"event_type": {"S": "done"}})
58+
```
59+
60+
**Tests** — pytest classes, explicit fixtures for shared state:
61+
62+
```python
63+
# ✅ Good
64+
@pytest.fixture(autouse=True)
65+
def _reset_shared_circuit_breaker_state():
66+
_reset_circuit_breakers()
67+
yield
68+
_reset_circuit_breakers()
69+
70+
class TestGenerateUlid:
71+
def test_length_is_26(self):
72+
assert len(_generate_ulid()) == 26
73+
74+
# ❌ Bad — no isolation, test order dependency
75+
def test_a():
76+
_ProgressWriter._circuit_open = True # poisons test_b
77+
```
78+
79+
**Silent failures** — do not `except: pass` or return empty defaults without justification; semgrep `AI004` blocks masking (use `nosemgrep` with reason if intentional).
80+
81+
## Boundaries
82+
83+
-**Always:** Add tests under `agent/tests/` for behavior changes; update `agent/README.md` for new env vars; emit structured progress events for operator-visible milestones
84+
- ⚠️ **Ask first:** Changes to agent–orchestrator contract, Dockerfile base image, new system dependencies in `pyproject.toml`
85+
- 🚫 **Never:** Bump `cedarpy` without bumping `@cedar-policy/cedar-wasm` and refreshing `contracts/cedar-parity/` fixtures; edit only `agent/` and skip `mise //agent:quality` before PR
86+
87+
## Common mistakes
88+
89+
- **Cedar parity**`cedarpy==4.8.4` (agent) and `@cedar-policy/cedar-wasm` 4.8.2 (cdk) must move together. See [cdk/AGENTS.md](../cdk/AGENTS.md) and `docs/design/CEDAR_HITL_GATES.md` §15.6.
90+
- **Forgotten consumer** — Progress event schema changes need `cli/src/commands/watch.ts` and `test_progress_writer.py` updates.
91+
- **Image bundle** — CDK deploys this tree; root `mise run build` always runs agent quality.

cdk/AGENTS.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# CDK package — agent context
2+
3+
Parent guide: [../AGENTS.md](../AGENTS.md)
4+
5+
You are an **ABCA platform engineer** for the `@abca/cdk` package: Lambda handlers, orchestration, CDK stacks/constructs, IAM, and shared API types.
6+
7+
## Commands (run these)
8+
9+
```bash
10+
mise //cdk:compile # TypeScript compile
11+
mise //cdk:test # Jest unit tests
12+
mise //cdk:synth # synth to cdk/cdk.out/
13+
mise //cdk:eslint # ESLint --fix (run after merging main)
14+
mise //cdk:deploy # deploy stack (requires AWS creds)
15+
mise //cdk:diff # diff vs deployed
16+
mise //cdk:destroy # destroy stack
17+
```
18+
19+
## Testing
20+
21+
- **Full suite:** `mise //cdk:test`
22+
- **Single file:** `cd cdk && npx jest test/handlers/shared/validation.test.ts`
23+
- **Pattern:** `cd cdk && npx jest --testPathPattern=orchestrate-task`
24+
25+
**Extend tests when you change:**
26+
27+
| Code | Test location |
28+
|------|---------------|
29+
| Shared handler logic | `cdk/test/handlers/shared/*.test.ts` |
30+
| Handler entrypoints | `cdk/test/handlers/orchestrate-task.test.ts`, `create-task.test.ts`, `webhook-create-task.test.ts` |
31+
| Constructs | `cdk/test/constructs/task-orchestrator.test.ts`, `task-api.test.ts` |
32+
33+
Construct tests: synthesize each distinct stack config once in `beforeAll`, assert against cached `Template` — do not re-synth per test. Bundling is disabled globally via `test/setup/disable-bundling.ts` (see Common mistakes).
34+
35+
## Primary locations
36+
37+
| Path | Access | Purpose |
38+
|------|--------|---------|
39+
| `cdk/src/handlers/` | WRITE | Lambda handlers |
40+
| `cdk/src/stacks/` | WRITE | Stack definitions |
41+
| `cdk/src/constructs/` | WRITE | Reusable constructs |
42+
| `cdk/src/handlers/shared/types.ts` | WRITE | API types (mirror to `cli/src/types.ts`) |
43+
| `cdk/test/` | WRITE | Unit / snapshot tests |
44+
| `cli/src/types.ts` | WRITE (sync) | Must match shared types |
45+
46+
## Code style
47+
48+
**API responses** — use `successResponse` / `errorResponse` from `shared/response.ts`; never hand-roll JSON envelopes:
49+
50+
```typescript
51+
// ✅ Good — contract envelope + typed ErrorCode
52+
import { successResponse, errorResponse, ErrorCode } from '../shared/response';
53+
54+
return successResponse(200, { task_id: taskId }, requestId);
55+
return errorResponse(422, ErrorCode.VALIDATION_ERROR, 'Invalid workflow_ref', requestId);
56+
57+
// ❌ Bad — ad-hoc body, no request ID
58+
return { statusCode: 400, body: JSON.stringify({ error: 'bad' }) };
59+
```
60+
61+
**Unit tests** — colocate under `cdk/test/`, descriptive `describe`/`test` names:
62+
63+
```typescript
64+
// ✅ Good
65+
describe('parseBody', () => {
66+
test('returns null for invalid JSON', () => {
67+
expect(parseBody('not json')).toBeNull();
68+
});
69+
});
70+
71+
// ❌ Bad — vague name, no edge cases
72+
test('works', () => { expect(parseBody('{}')).toBeTruthy(); });
73+
```
74+
75+
**Construct tests** — cache synth output:
76+
77+
```typescript
78+
// ✅ Good
79+
let template: Template;
80+
beforeAll(() => {
81+
const app = new App();
82+
template = Template.fromStack(new MyStack(app, 'Test'));
83+
});
84+
```
85+
86+
## Boundaries
87+
88+
-**Always:** Update `cli/src/types.ts` when changing `shared/types.ts`; add/extend tests in `cdk/test/`; use mise tasks not raw `cdk` CLI
89+
- ⚠️ **Ask first:** New stacks or constructs, IAM policy changes, DynamoDB schema changes, enabling Lambda bundling in unit tests
90+
- 🚫 **Never:** Bump `@cedar-policy/cedar-wasm` without bumping `cedarpy` and refreshing `contracts/cedar-parity/` fixtures; re-enable global Lambda bundling in tests; use constructor `context` for `aws:cdk:bundling-stacks` (use `postCliContext` instead — see #366)
91+
92+
## Common mistakes
93+
94+
- **Lambda bundling in unit tests**`Template.fromStack()` synths the stack but bundling is disabled via `CDK_CONTEXT_JSON`. Do not re-enable globally; opt in per-test with `postCliContext` only when asserting on bundle output. Details: `test/setup/disable-bundling.ts`, #366.
95+
- **Cedar engine drift**`@cedar-policy/cedar-wasm` and `cedarpy` share a Rust core. Bump both + parity fixtures in one commit. See `docs/design/CEDAR_HITL_GATES.md` §15.6 and `mise.toml` parity banner.
96+
- **Types out of sync**`cdk/src/handlers/shared/types.ts` and `cli/src/types.ts` must match; CI runs `check-types-sync`.

cli/AGENTS.md

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# CLI package — agent context
2+
3+
Parent guide: [../AGENTS.md](../AGENTS.md)
4+
5+
You maintain the **`bgagent` CLI** (`@backgroundagent/cli`): Commander commands, Cognito auth, HTTP client, and API types mirrored from CDK.
6+
7+
## Commands (run these)
8+
9+
```bash
10+
mise //cli:build # compile + test + lint
11+
cd cli && mise run test # Jest only
12+
cd cli && mise run compile # tsc only
13+
mise //cli:eslint # ESLint --fix (run after merging main)
14+
```
15+
16+
## Testing
17+
18+
- **Full suite:** `cd cli && mise run test` or `mise //cli:build`
19+
- **Single file:** `cd cli && npx jest test/commands/status.test.ts`
20+
- **Pattern:** `cd cli && npx jest --testPathPattern=auth`
21+
22+
Mock `ApiClient` in command tests; reset `process.exitCode` in `beforeEach`/`afterEach` (commands set exit codes — see `status.test.ts`).
23+
24+
## Primary locations
25+
26+
| Path | Access | Purpose |
27+
|------|--------|---------|
28+
| `cli/src/bin/bgagent.ts` | WRITE | Commander entry point |
29+
| `cli/src/commands/` | WRITE | One file per subcommand |
30+
| `cli/src/api-client.ts` | WRITE | Authenticated `fetch` wrapper |
31+
| `cli/src/auth.ts` | WRITE | Cognito login, token cache (`~/.bgagent/credentials.json`) |
32+
| `cli/src/types.ts` | WRITE | API types (mirror of `cdk/.../types.ts`) |
33+
| `cli/test/` | WRITE | Jest tests |
34+
35+
## Code style
36+
37+
**New command** — factory function + `Command` from commander; throw `CliError` for user-facing errors:
38+
39+
```typescript
40+
// ✅ Good — factory, validated options, CliError
41+
import { Command } from 'commander';
42+
import { CliError } from '../errors';
43+
44+
export function makeStatusCommand(): Command {
45+
return new Command('status')
46+
.argument('<task-id>', 'Task ID')
47+
.option('--output <format>', 'text or json', 'text')
48+
.action(async (taskId: string, opts) => {
49+
if (!taskId) throw new CliError('Task ID is required.');
50+
// ...
51+
});
52+
}
53+
54+
// ❌ Bad — side effects at import, console.error + process.exit
55+
export const status = new Command('status').action(() => {
56+
console.error('failed'); process.exit(1);
57+
});
58+
```
59+
60+
**Command tests** — mock `ApiClient`, spy `console.log`:
61+
62+
```typescript
63+
// ✅ Good
64+
jest.mock('../../src/api-client');
65+
beforeEach(() => { process.exitCode = undefined; });
66+
67+
test('renders snapshot from combined payload', async () => {
68+
mockGetStatusSnapshot.mockResolvedValue({ task: { task_id: 'abc', status: 'RUNNING', ... } });
69+
await program.parseAsync(['node', 'status', 'abc']);
70+
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('RUNNING'));
71+
});
72+
```
73+
74+
**Conventions:** `no-console` ESLint rule is disabled in CLI source (console output is the product). API URL from stack output includes `/v1/` — append only resource paths (`/tasks`, `/tasks/{id}`).
75+
76+
## Boundaries
77+
78+
-**Always:** Add tests in `cli/test/` for new commands; keep `types.ts` in sync with CDK; use `CliError` / `ApiError` for failures
79+
- ⚠️ **Ask first:** New runtime dependencies, changes to auth/token storage format
80+
- 🚫 **Never:** Change `cli/src/types.ts` without updating `cdk/src/handlers/shared/types.ts`; hardcode API URLs with stage prefix duplicated
81+
82+
## Common mistakes
83+
84+
- **API type drift** — Update both `cli/src/types.ts` and `cdk/src/handlers/shared/types.ts` in the same PR. See [cdk/AGENTS.md](../cdk/AGENTS.md).
85+
- **Exit code leaks** — Command tests must reset `process.exitCode` or Jest exits non-zero despite green assertions.

docs/AGENTS.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Docs package — agent context
2+
3+
Parent guide: [../AGENTS.md](../AGENTS.md)
4+
5+
You are a **technical writer for ABCA**: source guides and design docs, ADRs, and Starlight site mirrors. Write for developers new to the codebase — concise, specific, value-dense.
6+
7+
## Commands (run these)
8+
9+
```bash
10+
mise //docs:sync # regenerate docs/src/content/docs/ (<1 s)
11+
mise //docs:build # sync + Astro/Starlight build
12+
mise //docs:check # sync + astro check (MDX/components)
13+
```
14+
15+
Pre-commit hook `docs-sync` runs sync automatically when prek hooks are installed.
16+
17+
## Testing
18+
19+
- **Sync + build:** `mise //docs:build` (required before PR if you touched guides, design, ADRs, or `CONTRIBUTING.md`)
20+
- **Sync only:** `mise //docs:sync` then `git diff docs/src/content/docs/` — commit mirror changes alongside sources
21+
- **Astro check:** `mise //docs:check` (or `cd docs && npm run docs:check`)
22+
23+
CI **"Fail build on mutation"** rejects PRs where committed Starlight mirrors do not match what sync produces.
24+
25+
## Primary locations
26+
27+
| Path | Access | Purpose |
28+
|------|--------|---------|
29+
| `docs/guides/` | WRITE | User and developer guides |
30+
| `docs/design/` | WRITE | Architecture and design docs |
31+
| `docs/decisions/` | WRITE | ADRs |
32+
| `docs/imgs/` | WRITE | Static images |
33+
| `CONTRIBUTING.md` (repo root) | WRITE | Mirrored to Starlight |
34+
| `docs/src/content/docs/` | READ only | Generated — never edit by hand |
35+
| `docs/scripts/sync-starlight.mjs` | READ | Sync logic (change only if adding new mirror rules) |
36+
37+
Site renders `docs/design/` at `/architecture/` on the published docs site.
38+
39+
## Code style
40+
41+
**Edit source, then sync** — write guides in `docs/guides/`, not the Starlight mirror:
42+
43+
```markdown
44+
<!-- ✅ Good — edit docs/guides/DEVELOPER_GUIDE.md -->
45+
For routing and pitfalls, see **[AGENTS.md](../../AGENTS.md)** at the repo root.
46+
47+
Then run: `mise //docs:sync` and commit both source and `docs/src/content/docs/` changes.
48+
```
49+
50+
```markdown
51+
<!-- ❌ Bad — editing the generated mirror directly -->
52+
<!-- File: docs/src/content/docs/developer-guide/Contributing.md -->
53+
<!-- CI will fail or your edit will be overwritten on next sync -->
54+
```
55+
56+
**Cross-links** — prefer relative links in source (`../../AGENTS.md`, `../design/ARCHITECTURE.md`); sync rewrites them for the site.
57+
58+
**ADRs** — add under `docs/decisions/`, follow existing naming (`ADR-NNN-title.md`), run sync.
59+
60+
## Boundaries
61+
62+
-**Always:** Edit `docs/guides/`, `docs/design/`, or `docs/decisions/`; run `mise //docs:sync` and commit mirrors; keep links relative in sources
63+
- ⚠️ **Ask first:** Major IA changes, new top-level guide sections, editing `sync-starlight.mjs` mirror rules
64+
- 🚫 **Never:** Edit `docs/src/content/docs/` by hand; skip sync after source changes; promise unshipped platform features without labeling them future
65+
66+
## Common mistakes
67+
68+
- **Stale mirrors** — Source changed but `docs/src/content/docs/` not regenerated → CI mutation failure.
69+
- **Wrong tree**`docs/design/` is authoritative; the Starlight copy under `architecture/` is generated.
70+
- **CONTRIBUTING.md** — Root file is mirrored; sync after edits.

docs/guides/DEVELOPER_GUIDE.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Before editing, decide which part of the monorepo owns the behavior. This keeps
2626
| Agent runtime | `agent/` | Bundled into the image CDK deploys; run `mise run quality` in `agent/` or root build. |
2727
| Docs (source) | `docs/guides/`, `docs/design/` | After edits, run **`mise //docs:sync`** or **`mise //docs:build`**. Do not edit `docs/src/content/docs/` directly. |
2828

29-
For a concise duplicate of this table, common pitfalls, and a CDK test file map, see **[AGENTS.md](../../AGENTS.md)** at the repo root (oriented toward automation-assisted contributors).
29+
For a concise duplicate of this table, common pitfalls, and a CDK test file map, see **[AGENTS.md](../../AGENTS.md)** at the repo root (oriented toward automation-assisted contributors). Package-specific detail lives in **`AGENTS.md`** under `cdk/`, `cli/`, `agent/`, and `docs/`.
3030

3131
## Repository preparation
3232

docs/src/content/docs/developer-guide/Contributing.md

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docs/src/content/docs/developer-guide/Where-to-make-changes.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ Before editing, decide which part of the monorepo owns the behavior. This keeps
1212
| Agent runtime | `agent/` | Bundled into the image CDK deploys; run `mise run quality` in `agent/` or root build. |
1313
| Docs (source) | `docs/guides/`, `docs/design/` | After edits, run **`mise //docs:sync`** or **`mise //docs:build`**. Do not edit `docs/src/content/docs/` directly. |
1414

15-
For a concise duplicate of this table, common pitfalls, and a CDK test file map, see **[AGENTS.md](/sample-autonomous-cloud-coding-agents/architecture/agents)** at the repo root (oriented toward automation-assisted contributors).
15+
For a concise duplicate of this table, common pitfalls, and a CDK test file map, see **[AGENTS.md](/sample-autonomous-cloud-coding-agents/architecture/agents)** at the repo root (oriented toward automation-assisted contributors). Package-specific detail lives in **`AGENTS.md`** under `cdk/`, `cli/`, `agent/`, and `docs/`.

0 commit comments

Comments
 (0)