Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 24 additions & 37 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

**Generated:** 2025-01-20T00:00:00Z
**Branch:** main
**Refresh:** reconciled against actual file tree and `plans/*`; verified scheduled event routing, config loader, handler symbols, manual `/zai update-agents` command, action.yml inputs, and test coverage. Fixed stale workflow filenames (replaced nonexistent `code-review.yml` with actual `zai-code-bot.yml`, `zai-agents-init-example.yml`). Confirmed: scheduled test coverage exists (`tests/handlers/scheduled.test.js`, `tests/scheduled-config.test.js`, `tests/repository-context.test.js`, `tests/agents-validation.test.js`); `docs/scheduled-tasks.md` present; README updated with scheduled-tasks section and `/zai update-agents` command.
**Refresh:** reconciled against actual file tree, source code, and `plans/*`. Updated authorization descriptions to match current `src/lib/auth.js` implementation (permissive policy for identifiable users; collaborator-check helpers exported but inactive in main path). Updated `src/lib/code-scope.js` descriptions to reflect actual exports (`extractWindow`, `extractTargetBlock`, `extractEnclosingBlock`) — no `calculateTokenBudget` function exists. Verified scheduled event routing, config loader, handler symbols, manual `/zai update-agents` command, action.yml inputs, and test coverage. Confirmed: scheduled test coverage exists (`tests/handlers/scheduled.test.js`, `tests/scheduled-config.test.js`, `tests/repository-context.test.js`, `tests/agents-validation.test.js`); `docs/scheduled-tasks.md` present; README updated with scheduled-tasks section and `/zai update-agents` command.

## OVERVIEW
JavaScript GitHub Action with three event flows: (1) PR auto-review, (2) collaborator-gated `/zai` PR comment commands, and (3) cron-triggered scheduled tasks (`.zai-scheduled.yml`) that regenerate AGENTS.md files and open PRs. Runtime executes bundled `dist/index.js`; maintained logic lives in `src/index.js` plus modular services in `src/lib/*`.
JavaScript GitHub Action with three event flows: (1) PR auto-review, (2) `/zai` PR comment commands with an authorization gate, and (3) cron-triggered scheduled tasks (`.zai-scheduled.yml`) that regenerate AGENTS.md files and open PRs. Runtime executes bundled `dist/index.js`; maintained logic lives in `src/index.js` plus modular services in `src/lib/*`.

## STRUCTURE
```text
Expand All @@ -17,7 +17,7 @@ zai-code-bot/
├── src/lib/auto-review.js # Large PR batching and synthesis
├── src/lib/changed-files.js # Paginated changed-files fetch (3000 file limit)
├── src/lib/pr-context.js # Shared PR context fetch (files, content at ref, refs)
├── src/lib/code-scope.js # Token-budget calculation for prompt sizing
├── src/lib/code-scope.js # Code window/block extraction for prompt scoping
├── src/lib/context.js # Changed-file fetch + truncation/range helpers
├── src/lib/config/scheduled-config.js # Scheduled-task config loader (.zai-scheduled.yml)
├── src/lib/repository-context.js # Real repo context collection (tree + AGENTS.md discovery + key files)
Expand Down Expand Up @@ -49,13 +49,13 @@ zai-code-bot/
| Route events and command execution | `src/index.js` | `run()`, pull_request path, issue_comment command path, schedule path |
| Schedule event detection | `src/lib/events.js` | `getEventType` returns `schedule`; `shouldProcessEvent` always processes cron events |
| Parse commands and enforce allowlist | `src/lib/commands.js` | `/zai` parser, command normalization, help fallback; `update-agents` in allowlist |
| Authorization and fork policy | `src/lib/auth.js` | Collaborator checks and fork-safe behavior |
| Authorization gate | `src/lib/auth.js` | Currently permissive: authorizes any identifiable user; silent-blocks fork PR comments with no identifiable commenter. Collaborator helpers (`isCollaborator`, `AUTHORIZED_PERMISSIONS`) exported but not called in main path. See `SECURITY.md` for documented policy. |
| Comment/reaction behavior | `src/lib/comments.js` | Marker-based upsert, threaded reply (`replyToId`), reactions |
| API retry/error handling | `src/lib/api.js`, `src/lib/logging.js` | Retry policy, categorized safe errors |
| Large PR batching and synthesis | `src/lib/auto-review.js` | Batch creation, context limit handling, synthesis prompt |
| Paginated changed-files fetch | `src/lib/changed-files.js` | Handles GitHub's 3000 file API limit |
| Shared PR context fetch | `src/lib/pr-context.js` | `fetchPrFiles`, `fetchFileAtRef`, `resolvePrRefs`; user-safe fallbacks, size limits |
| Token budget calculation | `src/lib/code-scope.js` | Window extraction, enclosing block detection for prompt sizing |
| Code window/block extraction | `src/lib/code-scope.js` | `extractWindow`, `extractTargetBlock`, `extractEnclosingBlock` for scoped prompt context |
| Scheduled-task config loading | `src/lib/config/scheduled-config.js` | `loadScheduledConfig`, `getTasksToRun`, `validateAndNormalizeConfig`, `validateAgentsConfig`, `getGistUrl`; scoping fields (`context_paths`/`target_paths`/`exclude_paths`/budgets) |
| Scheduled-task execution | `src/lib/handlers/scheduled.js` | `handleScheduledEvent`, `handleUpdateAgentsTask` (grounded flow: context→prompt→validate→PR), `SCHEDULED_HANDLERS`; see child `src/lib/handlers/AGENTS.md` |
| Repository context for AGENTS.md gen | `src/lib/repository-context.js` | `collectRepositoryContext` (git tree + existing AGENTS.md discovery + key files, budgeted), `renderRepositoryContext` |
Expand All @@ -80,7 +80,7 @@ zai-code-bot/
| `dispatchCommand` | function | `src/index.js` | high | Handler selection and response management |
| `enforceCommandAuthorization` | function | `src/index.js` | medium | Auth gate before command dispatch |
| `parseCommand` | function | `src/lib/commands.js` | high | Command extraction and validation |
| `checkForkAuthorization` | function | `src/lib/auth.js` | medium | Fork-aware security policy |
| `checkForkAuthorization` | function | `src/lib/auth.js` | medium | Fork-aware auth gate; currently permissive for identifiable users, silent-blocks unidentifiable fork commenters |
| `buildHandlerContext` | function | `src/lib/context.js` | medium | Shared context for handlers |
| `upsertComment` | function | `src/lib/comments.js` | high | Marker idempotency + threaded reply support |
| `callWithRetry` | function | `src/lib/api.js` | medium | API retry/backoff wrapper |
Expand All @@ -91,7 +91,7 @@ zai-code-bot/
| `fetchFileAtRef` | function | `src/lib/pr-context.js` | medium | File content at base/head ref, sliding-window scoping |
| `resolvePrRefs` | function | `src/lib/pr-context.js` | low | Resolves base/head refs for diff context |
| `MAX_PR_FILES_API_LIMIT` | constant | `src/lib/changed-files.js` | low | GitHub API ceiling (3000) |
| `calculateTokenBudget` | function | `src/lib/code-scope.js` | medium | Token/char budget sizing for prompts |
| `extractWindow` / `extractEnclosingBlock` | functions | `src/lib/code-scope.js` | medium | Window and enclosing-block extraction for scoped prompt context |
| `getEventType` | function | `src/lib/events.js` | low | Event-type detection for routing (incl. `schedule`) |
| `shouldProcessEvent` | function | `src/lib/events.js` | low | Event filter; always-process gate for cron events |
| `loadScheduledConfig` | function | `src/lib/config/scheduled-config.js` | low | Parses `.zai-scheduled.yml` task config |
Expand All @@ -116,36 +116,23 @@ zai-code-bot/
- Edit maintained code in `src/`; do not hand-edit generated `dist/index.js`.
- After source changes, run `npm run build` and commit `dist/index.js` + `dist/licenses.txt`.
- Use marker-based idempotent comments; preserve marker constants and update semantics.
- Command responses should stay threaded to the invoking comment via `replyToId`.
- Keep security posture strict: collaborator/fork checks before command execution, no secret leakage.
- Command responses should stay threaded to the invoking comment (`replyToId`).
- Keep prompts bounded via window/block extraction helpers (`code-scope.js`) and batching (`auto-review.js`); never pass raw unbounded patches.
- Return user-safe error messages; route internal details through `src/lib/logging.js` categorized safe-error wrappers.
- Authorization checks (`enforceCommandAuthorization` → `checkForkAuthorization`) must run before any handler dispatch, even though the current policy is permissive.

## ANTI-PATTERNS (THIS PROJECT)
- Bypassing authorization/fork checks for command handlers.
- Executing command logic for non-PR issue comments.
- Allowing unbounded context payloads into prompts.
- Asking an LLM to "scan the repo" without providing real repo context (causes hallucinated AGENTS.md — PR #15 bug).
- Committing AGENTS.md output that references files/languages not present in the repo.
- Editing `dist/` manually or shipping source changes without rebuilt artifacts.
- Confusing consumer-facing workflow examples (README snippet) with this repo's own `.github/workflows/` runtime logic.

## UNIQUE STYLES
- Event-first architecture: `src/index.js` orchestrates; `src/lib/*` isolates concerns.
- Reactions communicate command lifecycle (`eyes`/`thinking`/`rocket`/`x`).
- Continuity is encoded with hidden markers in comments, not external storage.

## COMMANDS
```bash
npm install
npm test # vitest run --coverage
npm run build # ncc build src/index.js -o dist --license licenses.txt
npm audit --audit-level=moderate # security audit gate (CI)
```
After source changes: run `npm run build` and commit `dist/index.js` + `dist/licenses.txt` (CI fails on dist drift).
## ANTI-PATTERNS
- Hand-editing `dist/index.js` instead of editing `src/` and rebuilding.
- Bypassing `enforceCommandAuthorization` before dispatching a command handler.
- Returning raw exception details or stack traces in PR comments.
- Passing unbounded diffs or full-file patches into Z.ai prompts.
- Introducing cross-handler coupling when a local helper within the handler module suffices.
- Creating ad-hoc GitHub API calls in handlers instead of routing through shared service modules (`api.js`, `pr-context.js`, `comments.js`).

## NOTES
- CI (`.github/workflows/ci.yml`) enforces tests, build, dist drift, and security audit across Node 20 + 22.
- No linting/formatting configs (ESLint, Prettier) — rely on code review and CI gates.
- 7 command handlers + scheduled pipeline: `ask`, `review`, `explain`, `describe`, `impact`, `help`, plus `scheduled` (largest handler, drives cron tasks via `.zai-scheduled.yml`).
- Scheduled test coverage: `tests/handlers/scheduled.test.js`, `tests/scheduled-config.test.js`, `tests/repository-context.test.js`, `tests/agents-validation.test.js` (unit-level); end-to-end schedule integration test is still a gap.
- Scheduled-tasks configuration reference: `docs/scheduled-tasks.md`.
- Architecture and invariants catalog: `ARCHITECTURE.md`.
- `dist/` is committed to the repository; the GitHub Actions runner executes `dist/index.js` directly without `npm install` or build steps.
- CI (`ci.yml`) includes a `dist-drift` gate that fails if committed `dist/` does not match a fresh `npm run build`.
- Test framework is Vitest v3 with coverage via `@vitest/coverage-v8`; run with `npm test`.
- The current `src/lib/auth.js` implements a permissive authorization policy: any identifiable user (with a `login`) is authorized. Collaborator-check infrastructure (`isCollaborator`, `AUTHORIZED_PERMISSIONS`, `AUTHORIZED_ASSOCIATIONS`, `isTrustedCommentAuthor`) is exported but not called in the main authorization path. `SECURITY.md` documents the intended collaborator-gated policy.
- See `ARCHITECTURE.md` for the full layered-architecture description, dependency-direction rules, and life-of-request flows.
- See `src/lib/AGENTS.md`, `src/lib/handlers/AGENTS.md`, `tests/AGENTS.md`, and `tests/integration/AGENTS.md` for subtree-specific guidance.