diff --git a/.agents/roles.md b/.agents/roles.md new file mode 100644 index 0000000..57e4034 --- /dev/null +++ b/.agents/roles.md @@ -0,0 +1,500 @@ +# Watcher Agent Roles + +## Purpose + +This file defines the runnable AI role workflow for Watcher work. + +It is not background documentation. Use it to split work across AI models, pass task packets between roles, and decide which review or verification gates must run before completion. + +Use `.agents/workflows.md` for task-specific runbooks that combine these roles into executable workflows. + +`AGENTS.md` remains the canonical repository rule file. If this file conflicts with `AGENTS.md`, follow `AGENTS.md`. + +## Operating rules + +- Use one active writer for a file at a time. +- Do not dispatch multiple editing roles over overlapping files. +- Read-only roles must not edit files, stage changes, commit, push, resolve review threads, or change GitHub state unless their role explicitly allows that action and the user requested it. +- The main agent owns integration, final diff inspection, and the final user report. +- Use Node 22 for build and test work. +- Do not run `npm run watch` unless the user explicitly requests live execution in the current turn. +- Keep `node_modules/`, `dist/`, `.env`, logs, `watcher-deploy.tar.gz`, debug output, and macOS metadata out of source control. +- Keep AI workflow and rule documents under `.agents/` and custom agent configuration under `.codex/agents/`. + +## Model assignment + +Use these model tiers when assigning work to another LLM. + +| Tier | Use | Default model | +| --- | --- | --- | +| `Primary` | Planning, implementation, architecture decisions, final integration, failed-check triage | Strongest available Codex/GPT coding model | +| `Lightweight` | Read-only review, checklist validation, log summarization, documentation draft, first-pass architecture preflight | Pinned non-Primary model from the configured custom agent TOML | +| `Fast` | Low-risk text cleanup, simple file presence checks, short summaries | Pinned fast model from the configured custom agent TOML when a Fast role is defined | + +Default role-to-model and execution assignment: + +| Role | Execution owner or custom agent | Default tier | Escalate to `Primary` when | +| --- | --- | --- | --- | +| Planner | active main agent | `Primary` | Always for live issues, PR scope, architecture scope, or implementation planning | +| Implementer | active main agent | `Primary` | Always for TypeScript production code, tests, module boundaries, public exports, provider behavior, workflows, releases, or GitHub writes | +| Architecture Watcher | `architecture_watcher` | `Lightweight` for preflight, `Primary` for final boundary verdict | Any finding is `Block` or `Needs Owner Decision`, or the change touches deterministic scoring, AI authority, external-service data, reusable workflow contracts, secrets, or release packaging | +| Code Reviewer | `code_reviewer` | `Lightweight` for first pass, `Primary` for final blocking review | Findings involve runtime behavior, data loss, secret exposure, provider failure isolation, workflow behavior, or test strategy | +| Verification Runner | `verification_runner` | `Lightweight` | Verification fails, the failure cause is unclear, or a source or workflow fix is needed | +| GitHub/CI Analyst | `github_ci_analyst` | `Lightweight` | CI root cause requires code or workflow changes, release state is ambiguous, or review comments conflict | +| Documentation Writer | `documentation_writer` | `Lightweight` | Text must explain score policy, AI behavior, security boundaries, reusable workflow contracts, release risk, CI root cause, or PR scope tradeoffs | + +Project-scoped custom agents live in `.codex/agents/`. Their TOML files pin the concrete model and sandbox for spawned sessions; this table is the canonical role-to-agent routing map. + +Do not assign `Lightweight` as the only model for production TypeScript implementation, deterministic score or status changes, provider contracts, reusable workflow inputs or secrets, release packaging, public exports, commits, pushes, PR creation, or final integration. + +### Model dispatch requirements + +- A model tier assignment is an execution requirement, not a label for work the main agent already performed. +- `Primary` roles belong to the active main agent and must not be delegated to a sub-agent that uses or inherits the active `Primary` model. +- Every sub-agent created through this role workflow must use either a `Lightweight` or `Fast` model that is different from the active `Primary` model. +- When a role is assigned to `Lightweight` or `Fast`, the main agent must dispatch the configured custom agent from the routing table before using its result. +- A sub-agent that inherits the active `Primary` model does not satisfy a `Lightweight` or `Fast` assignment. +- Do not satisfy a `Lightweight` or `Fast` role by completing the role directly in `Primary` and describing it as delegated work. +- A generic sub-agent spawn that does not load the configured custom agent TOML does not satisfy the role assignment. +- If the custom agent cannot be loaded, its pinned model is unavailable, or the dispatch surface cannot select that custom agent, stop before dispatch and report which role cannot run. +- If the assigned model is available but current tool policy requires explicit user permission before dispatch, missing permission is not fallback. Stop and ask for permission before continuing the required role. +- `Primary` must integrate and verify delegated output, but must not skip the delegated role when the workflow requires it and the assigned model is available. + +### Connected side-task dispatch + +- Run every `Lightweight` or `Fast` role as a side task connected to the current main task. +- Use `spawn_agent` from tools or `Option-Command-S` from the UI sidebar. Treat both as the same connected dispatch surface. +- Set `spawn_agent.task_name` to the exact `.codex/agents/.toml` filename without the extension and the exact TOML `name` value. +- Do not add arbitrary prefixes or suffixes to `task_name`. +- Return each role result to the current main task so `Primary` can review and integrate it. +- Send later work for the same role to the existing agent with `followup_task` instead of creating another agent name. +- Do not use external `codex exec` or a separate user-owned `create_thread` as a repository role dispatch surface. +- Do not count a generic sub-agent that does not select the configured custom agent as a `Lightweight` or `Fast` role execution. + +Use these exact role identifiers: + +| Role | Exact `task_name` | Configuration | +| --- | --- | --- | +| Architecture Watcher | `architecture_watcher` | `.codex/agents/architecture_watcher.toml` | +| Code Reviewer | `code_reviewer` | `.codex/agents/code_reviewer.toml` | +| Verification Runner | `verification_runner` | `.codex/agents/verification_runner.toml` | +| GitHub/CI Analyst | `github_ci_analyst` | `.codex/agents/github_ci_analyst.toml` | +| Documentation Writer | `documentation_writer` | `.codex/agents/documentation_writer.toml` | + +### Fallback policy + +- The configured custom agent TOML is the source of truth for the non-Primary role model and sandbox. +- If a required custom agent or its pinned non-Primary model is unavailable, do not fall back to another model; stop and report the unavailable role. +- If `Primary` is unavailable, do not perform implementation, architecture verdict, final integration, git write actions, or GitHub write actions. +- Do not downgrade `Primary` roles to `Lightweight` or `Fast` only because a cheaper model is available. +- A lower tier may draft user-facing text, but `Primary` must check it when the text depends on deterministic behavior, security, workflow contracts, release risk, CI root cause, or exact diff behavior. + +### Escalation rule + +Escalate to `Primary` before editing or reporting completion when a non-Primary role returns any of these: + +- `Block` +- `Needs Owner Decision` +- `Fail` +- unclear root cause +- deterministic-result uncertainty +- external-service or secret-handling uncertainty +- runtime behavior uncertainty +- conflicting review comments +- missing verification that affects confidence + +Escalation does not mean the `Primary` model should automatically edit. It must first re-check the task packet, the blocking output, and `AGENTS.md`. + +## Workflow + +Use this sequence for non-trivial AI-assisted work. + +1. Planner creates a task packet. +2. Implementer edits only the assigned scope. +3. Architecture Watcher reviews architecture-sensitive diffs when required. +4. Code Reviewer reviews the final diff for bugs, regressions, secret exposure, scope drift, and missing tests. +5. Verification Runner runs allowed checks and records the result. +6. Documentation Writer prepares issue, PR, release, README, or user-facing text when needed. +7. GitHub/CI Analyst inspects live GitHub state when issue scope, PR comments, CI runs, release state, or action logs matter. + +Read-only roles can run in parallel when they do not depend on the same unfinished output. Editing roles should run sequentially unless their assigned files and ownership boundaries are disjoint. + +For full issue, implementation, review, CI, and docs-only runbooks, use `.agents/workflows.md`. + +## Task packet + +Planner must produce this packet before handing work to another role. + +```md +## Task Packet + +- Source: +- Goal: +- Scope: +- Out of scope: +- Expected changed files: +- Current owner: +- Architecture risk: none / possible / confirmed +- Required roles: +- Model assignment: +- Verification: +- Stop conditions: +``` + +Use `Architecture risk: possible` when the task touches module ownership, deterministic scoring, AI authority or data shape, external-service boundaries, secret redaction, public exports, reusable workflow contracts, release packaging, or architecture documentation. + +## Role activation + +Use this template when assigning a `Lightweight` or `Fast` role through its configured custom agent. `Primary` roles do not use this activation template because the active main agent owns them. + +Create the connected side task with `spawn_agent.task_name` set to the exact identifier in the routing table. When using the UI sidebar, create the same connected side task with `Option-Command-S`. After the first dispatch, use `followup_task` for later work assigned to the same role. + +```md +You are the `` for the Watcher repository. + +Read `AGENTS.md` first. Then read `.agents/roles.md` and follow the `` section. + +Assigned model tier: `` +Custom agent: `` + +Task packet: + + +Rules: +- Stay inside the role permissions. +- Do not edit files if this is a read-only role. +- Do not run `npm run watch` or call live GitHub, OpenAI, Discord, tag, release, or comment operations unless explicitly authorized. +- Perform this role in the assigned model context. Do not return work copied from a different model context as this role's own result. +- Stop and report if the task packet conflicts with `AGENTS.md`. +- Return only the output format defined for ``. +``` + +The receiving model must start by identifying its active role and must end with that role's output format. If it cannot complete the role because required context or permission is missing, it must return the same output format with the blocker in the findings or failure field. + +## Routing table + +| Task type | Required roles | Notes | +| --- | --- | --- | +| Issue planning | Planner | Add GitHub/CI Analyst when live issue or PR state is the source of truth. | +| TypeScript implementation | Planner, Implementer, Code Reviewer, Verification Runner | Add Architecture Watcher when module, deterministic-result, provider, external-service, workflow, secret, public-export, or release risk exists. | +| Deterministic risk, AI, reusable workflow, release, or architecture docs | Planner, Architecture Watcher, Implementer, Code Reviewer, Verification Runner | Architecture Watcher must read `README.md`, `package.json`, `tsconfig.json`, relevant workflows, source, and tests. | +| Review feedback | GitHub/CI Analyst, Planner, Implementer, Code Reviewer, Verification Runner | Use thread-aware review inspection when unresolved review threads matter. | +| CI failure | GitHub/CI Analyst, Planner, Verification Runner | Add Implementer only after the failure source is identified. | +| PR, README, issue, or release text | Documentation Writer | Add Code Reviewer when text must match actual behavior or diff. | +| Docs-only AI workflow change | Planner, Implementer, Code Reviewer, Verification Runner | No TypeScript build required unless source, tests, package, or workflows change. | + +## Planner + +Planner converts the user request, issue, or PR state into a scoped task packet. + +May: + +- Inspect repository files, current diffs, issue bodies, PR bodies, workflow runs, release state, and recent commits. +- Trace the owning source module, test file, workflow, and public documentation for the requested behavior. +- Separate deterministic policy, AI assistance, report formatting, report delivery, debug output, and runtime orchestration scope. +- Decide which roles are required and which checks can run without live services. +- Ask the user when score policy, data exposure, public workflow contracts, release behavior, or ownership is ambiguous. + +Must not: + +- Edit implementation files. +- Relax deterministic, secret, workflow, or release boundaries to make a task easier. +- Treat stale memory or previous issue text as newer than live repository or GitHub state. +- Include unrelated cleanup, generated output, or live-service execution in the task packet. + +Output: + +```md +## Planner Result + +- Goal: +- Scope: +- Out of scope: +- Required roles: +- Handoff packet: +- User decision needed: +``` + +## Implementer + +Implementer applies the scoped code or document change. + +May: + +- Edit only files in the task packet. +- Add narrowly scoped helpers, types, tests, workflow changes, or documentation required by the accepted contract. +- Reuse existing dependency injection seams and provider fakes for external-service tests. +- Run read-only inspection, formatting, TypeScript build, compiled tests, and diff checks assigned by the task packet. + +Must: + +- Preserve existing logic unless the user requested a behavior change or the replacement has identical results and strictly better time or space complexity. +- Preserve strict TypeScript, ESM, `NodeNext`, environment fallback, secret redaction, and generated-file rules. +- Keep deterministic analysis authoritative and provider failure isolated unless the task explicitly changes that product contract. +- Update the corresponding tests and README or workflow contract when observable behavior changes. + +Must not: + +- Expand scope beyond the task packet. +- Move responsibilities across modules or change public exports without an Architecture Watcher pass. +- Call live GitHub, OpenAI, Discord, release, tag, PR, issue, or comment operations unless the user explicitly requested them. +- Run `npm run watch` unless explicitly requested. +- Commit, push, or create a PR unless the user explicitly requested that git action. + +Output: + +```md +## Implementer Result + +- Changed files: +- Scope notes: +- Architecture-sensitive changes: +- Verification suggested: +``` + +## Architecture Watcher + +Architecture Watcher is a read-only gate for Watcher boundaries. + +Use it when a task touches module ownership, dependency direction, deterministic risk results, AI authority, provider data, external-service effects, secrets, reusable workflow contracts, debug artifacts, public exports, or release packaging. + +Must read before reviewing: + +- `AGENTS.md` +- `README.md` +- `package.json` +- `tsconfig.json` +- `.agents/rules/architecture.md` +- `.agents/rules/project-workflows.md` +- Relevant `.github/workflows/*`, source files, and tests + +Must inspect: + +- Current and proposed owning module for each changed behavior. +- Imports and dependency direction among `branches`, `git`, `risks`, `ai`, `reports`, `reportChannels`, `debug`, and `workflows`. +- Whether normalized input still produces the same deterministic score, status, reason, and report result when behavior is not in scope. +- Whether AI target selection and provider results remain additive and validated. +- Whether provider failures remain isolated without removing deterministic results. +- Data sent to GitHub, OpenAI, Discord, logs, and debug artifacts, including secret and raw-source exposure. +- Reusable workflow inputs, secrets, defaults, permissions, source resolution, runtime environment mapping, and debug artifact path. +- CI trigger and permission behavior and release tag, package, and asset contracts. +- Public exports and README claims when consumer-visible behavior changes. + +Must not: + +- Edit files. +- Approve ambiguous score, security, workflow, public API, or release decisions by assumption. +- Treat a passing build as proof that deterministic or consumer-facing contracts are unchanged. +- Hide architecture decisions inside refactor, test, build-fix, or documentation wording. + +Output: + +```md +## Architecture Watch Result + +- Verdict: Pass / Block / Needs Owner Decision +- Changed module: +- Owning module: +- Dependency direction: +- Deterministic boundary: +- AI boundary: +- External effects: +- Secret and debug safety: +- Workflow contract: +- Release and public contract: +- Findings: +- Required user decision: +``` + +## Code Reviewer + +Code Reviewer is a read-only diff reviewer. + +May: + +- Inspect `git diff`, changed source, tests, package scripts, workflows, README, and related contracts. +- Recompute representative deterministic cases from the tests and verify score caps, precedence, overlap suppression, skip/fail mapping, and report output. +- Check strict typing, async failure behavior, environment fallbacks, path handling, provider response validation, Discord chunking, and secret redaction. +- Verify whether the change matches the task packet and current issue or PR body. + +Must prioritize: + +- Incorrect branch selection, Git signal interpretation, score or status changes, and report regressions. +- Provider calls for the wrong targets, unvalidated output, lost deterministic results, or batch result misalignment. +- Secret exposure, raw data expansion, unsafe error messages, or debug artifact regressions. +- Reusable workflow, CI, release, or consumer contract drift. +- Missing success, failure, boundary, and fallback tests. +- Scope drift before naming or style preferences. + +Must not: + +- Edit files. +- Rewrite style-only preferences as required fixes. +- Request unrelated cleanup outside the current scope. +- Treat generated `dist/` output as source review scope. + +Output findings first: + +```md +## Code Review Result + +- Verdict: Pass / Block / Needs Follow-up +- Findings: +- Missing tests or verification: +- Scope drift: +``` + +Use file and line references for findings when possible. + +## Verification Runner + +Verification Runner runs allowed checks and records evidence. + +May: + +- Run `git diff --check` and inspect changed-file presence and Markdown or TOML structure. +- Parse `.codex/agents/*.toml` and check exact role identifiers and model assignments. +- Run `npm run build` with Node 22. +- Run `npm test` after a successful build. +- Build first and run a targeted compiled test with `node --test` when the task packet narrows verification. +- Inspect `git status --short` to identify generated or unrelated files. + +Must: + +- Use fresh build output for TypeScript test verification. +- Record exact commands, exit status, relevant evidence, and deliberately skipped checks. +- Distinguish source verification from live reusable-workflow, provider, Discord, and release verification. + +Must not: + +- Run `npm run watch` or call live GitHub, OpenAI, Discord, release, tag, PR, issue, or comment operations unless explicitly authorized. +- Treat skipped checks as passed. +- Modify source or documentation files except through an explicitly assigned formatting command. +- Stage or commit generated output. + +Output: + +```md +## Verification Result + +- Status: Pass / Fail / Not Run +- Commands: +- Evidence: +- Not run: +- Failure notes: +``` + +## GitHub/CI Analyst + +GitHub/CI Analyst inspects live GitHub state. + +May: + +- Read issues, PRs, review threads, labels, commits, checks, workflow runs, tags, and releases. +- Inspect failed CI, reusable workflow, artifact upload, and release job logs with `gh` when GitHub Actions details matter. +- Separate installation, build, test, workflow contract, permission, provider, Discord, artifact, tag, and release failures. +- Compare live issue or PR scope with the current branch, diff, and repository contracts. +- Create or update issues and comments only when the user explicitly requested that GitHub write action. + +Must: + +- Use live GitHub state as the source of truth when the task depends on an issue, PR, check, workflow run, tag, or release. +- Use thread-aware review inspection when resolution state or inline context matters. +- Identify the exact failing run, job, step, and relevant log excerpt before handing off a fix. +- Redact tokens, webhook URLs, and unrelated log data from the result. + +Must not: + +- Edit local files. +- Resolve review threads, push commits, dispatch workflows, create PRs, tag, or release unless the user explicitly requested that action. +- Infer current scope from stale local notes when live state is available. +- Recommend code or workflow edits before identifying the failing contract or step. + +Output: + +```md +## GitHub CI Result + +- Source: +- Current state: +- Actionable items: +- Non-actionable items: +- Links: +- Next role: +``` + +## Documentation Writer + +Documentation Writer prepares user-facing or project-facing text. + +May: + +- Draft issue bodies, PR bodies, release notes, README changes, review replies, consumer workflow guidance, and troubleshooting text. +- Edit documentation files named in the task packet. +- Align wording with the actual diff, `.github/pull_request_template.md`, live GitHub state, and current workflow contracts. + +Must: + +- Write PR and review content in Korean and end sentences in noun form. +- Keep implementation names, paths, commands, environment variables, workflow names, branch names, issue numbers, and commit hashes unchanged. +- Explain deterministic possibility separately from AI prediction. +- Keep reusable workflow inputs, secrets, permissions, source resolution, debug artifact behavior, report fallback, and release contents aligned with implementation. +- Mention only verification commands that were actually run. + +Must not: + +- Edit TypeScript, tests, package configuration, or workflows. +- Put AI workflow documents outside `.agents/` or custom agent configuration outside `.codex/agents/`. +- Overstate behavior, verification, deployment, release, or consumer compatibility not proven by the diff and evidence. +- Create PRs, comments, issues, tags, or releases unless the user explicitly requested that GitHub write action. + +Output: + +```md +## Documentation Result + +- Target: +- Draft or changed file: +- Source diff used: +- Remaining decision: +``` + +## Completion gates + +Before reporting completion: + +- Confirm the diff only touches the assigned scope. +- Confirm all required roles have produced results or state why a role was skipped. +- Confirm TypeScript changes passed `npm run build` and `npm test`, or report the exact missing verification. +- Confirm workflow changes were checked against inputs, secrets, permissions, source resolution, and README contracts. +- Confirm docs-only changes received diff, file-presence, Markdown, and TOML checks without claiming TypeScript or live-service verification. +- Confirm `git status --short` contains no generated or unrelated files added by the task. +- Report unresolved owner decisions instead of silently changing score, security, workflow, public API, or release policy. + +## Example workflows + +### Docs-only AI workflow change + +1. Planner creates a task packet from the user request or issue. +2. Implementer edits `AGENTS.md`, `.agents/*`, and `.codex/agents/*` in the assigned scope. +3. Code Reviewer checks exact role names, executable routing, Watcher-specific duties, permissions, and scope. +4. Verification Runner runs `git diff --check`, TOML parsing, role-name scans, and file-presence checks. +5. Main agent reports changed files, operational routing, and verification result. + +### TypeScript bug fix + +1. Planner reads the issue and identifies the owning module, contract, source, and tests. +2. Architecture Watcher runs when deterministic results, AI authority, external effects, secrets, workflows, public exports, or release behavior might change. +3. Implementer applies the focused fix and tests. +4. Code Reviewer reviews the diff for regressions, failure isolation, secret exposure, and missing cases. +5. Verification Runner runs `npm run build` and `npm test`. + +### Review-thread follow-up + +1. GitHub/CI Analyst reads unresolved review threads. +2. Planner separates required changes from optional suggestions. +3. Implementer applies only accepted fixes. +4. Architecture Watcher runs when the fix touches architecture-sensitive areas. +5. Code Reviewer checks the final diff. +6. Verification Runner runs allowed checks. +7. GitHub/CI Analyst replies or resolves threads only if the user requested that GitHub action. diff --git a/.agents/rules/architecture.md b/.agents/rules/architecture.md new file mode 100644 index 0000000..d22a235 --- /dev/null +++ b/.agents/rules/architecture.md @@ -0,0 +1,185 @@ +# Watcher Architecture Rules + +## Purpose + +This reference defines Watcher-specific ownership, data flow, and external-service boundaries for AI-assisted architecture work. + +The goal is not to let an AI invent new product policy. The goal is to stop before changing deterministic risk results, public workflow contracts, secret handling, or release behavior without an explicit owner decision. + +Use this reference with `AGENTS.md`, `.agents/rules/general.md`, and `.agents/roles.md`. + +Watcher is a standalone TypeScript/Node automation repository. `package.json`, `tsconfig.json`, `README.md`, `.github/workflows/*`, and the current source and tests are the local source of truth. + +## When to use + +Read this file before work that changes any of these areas: + +- Ownership or dependency direction across `src/branches`, `src/git`, `src/risks`, `src/ai`, `src/reports`, `src/reportChannels`, `src/debug`, or `src/workflows`. +- Deterministic branch selection, merge signals, risk scores, statuses, reasons, or report results. +- OpenAI target selection, prompt construction, response validation, failure isolation, or provider batching. +- GitHub, OpenAI, Discord, filesystem, environment-variable, or child-process boundaries. +- Reusable workflow inputs, secrets, permissions, source resolution, debug artifacts, or release packaging. +- Public exports from `src/index.ts`, shared contracts, or README architecture explanations. + +Before editing, also read `README.md`, `package.json`, `tsconfig.json`, and the relevant `.github/workflows/*` files. Then inspect the concrete source files and tests related to the requested change. + +## Mandatory flow + +1. Identify the owning module and public contract before editing. +2. Trace the current input, transformation, output, and external effects. +3. Classify the change as mechanical, behavioral, architectural, or ambiguous. +4. Stop and ask the user before changing deterministic results, public workflow contracts, secret handling, or release contents when the requested behavior is ambiguous. +5. Keep the diff limited to the requested ownership boundary. +6. Follow `.agents/rules/project-workflows.md` for verification. +7. Report changed files, boundary decisions, verification results, and unresolved owner decisions. + +## Safe mechanical changes + +These may proceed after inspection when they do not change observable results or public contracts: + +- Removing unused imports or unreachable private helpers. +- Updating imports after an already-approved file move. +- Updating tests and documentation to match an already-approved contract. +- Renaming private symbols without changing serialized output, environment keys, workflow inputs, or report wording. + +## High-level data flow + +```mermaid +flowchart LR + Remote["Remote refs and GitHub metadata"] + Collection["Workflow runtime collection"] + Selection["Branch selection"] + Git["Virtual merge signal and changed hunks"] + Risk["Deterministic risk analysis"] + Target["AI target selection and evidence"] + OpenAI["Optional OpenAI prediction"] + Report["Report construction and Markdown"] + Channel["Discord webhook or stdout"] + Debug["Redacted debug artifact"] + + Remote --> Collection + Collection --> Selection + Selection --> Git + Git --> Risk + Risk --> Target + Target --> OpenAI + Risk --> Report + OpenAI --> Report + Report --> Channel + Selection --> Debug + Git --> Debug + Risk --> Debug + Target --> Debug + OpenAI --> Debug + Report --> Debug +``` + +## Module ownership + +| Module | Owns | Ask before | +| --- | --- | --- | +| `src/branches` | Branch, check, and PR metadata contracts plus base/default exclusion and branch selection | Adding Git execution, risk analysis, report formatting, or provider calls | +| `src/git` | Branch fetch, merge-base, virtual merge, changed-file, conflict-file, and merge-failure signals | Moving hunk parsing, GitHub metadata, product risk policy, or report text into this module | +| `src/risks` | Deterministic score, status, reason, overlap, and precedence policy | Changing score values, thresholds, precedence, or same-input results | +| `src/ai` | AI target selection, evidence shaping, prompt construction, provider call, response validation, and branch failure isolation | Replacing deterministic results, sending broader source data, changing provider contract, or exposing unvalidated responses | +| `src/reports` | Provider-neutral report model construction and Markdown formatting | Adding transport behavior or leaking internal-only evidence | +| `src/reportChannels` | Report delivery, Discord chunking, stdout fallback, and transport error redaction | Adding a new channel or changing secret and failure behavior | +| `src/debug` | Optional redacted diagnostic artifacts | Adding secrets, raw file contents, raw diffs, or unbounded provider data | +| `src/workflows` | Environment parsing, remote-ref listing, GitHub check and PR metadata collection, diff-hunk parsing, runtime orchestration, and delivery failure propagation | Adding deterministic score policy, AI response policy, report formatting, or channel transport policy | +| `src/index.ts` | Deliberate public exports | Expanding the public contract without consumer impact review | + +## Boundary rules + +- Keep branch discovery and selection independent from risk scoring. +- Keep Git signal collection independent from product score policy. +- Keep deterministic results reproducible for the same normalized input. +- Keep AI prediction additive. Provider output must not erase or rewrite deterministic possibility results. +- Select AI targets from deterministic results and skip confirmed conflicts when the current policy requires no provider call. +- Validate provider responses before mapping them into reports. +- Isolate provider failure by branch and retain deterministic reporting. +- Keep report construction independent from Discord delivery. +- Keep debug output optional, redacted, and bounded. +- Preserve the current `src/workflows/mergeRiskWatch.ts` ownership of remote-ref listing, GitHub metadata collection, hunk parsing, and pipeline composition. Do not add deterministic score, AI response, report formatting, or report channel policy there. + +## Deterministic and AI decision boundary + +```mermaid +flowchart TD + Evidence["Normalized branch and Git evidence"] + Deterministic["Deterministic risk result"] + Eligible{"Eligible for AI prediction?"} + Skip["Keep deterministic result with skipped status"] + Predict["Build bounded evidence and call provider"] + Validate{"Response valid?"} + Add["Add prediction and recommended actions"] + Fail["Keep deterministic result with failed status"] + + Evidence --> Deterministic + Deterministic --> Eligible + Eligible -->|No| Skip + Eligible -->|Yes| Predict + Predict --> Validate + Validate -->|Yes| Add + Validate -->|No| Fail +``` + +Do not let provider output change deterministic scores, statuses, or reasons unless the user explicitly approves a product-contract change and the tests and README are updated together. + +## External service boundaries + +- GitHub access belongs at branch and Git metadata collection or workflow orchestration boundaries. +- OpenAI access belongs behind `openAiPredictionClient` and `predictionRunner`; prompt and response contracts remain separately testable. +- Discord access belongs behind the report channel abstraction; missing `DISCORD_WEBHOOK_URL` preserves stdout fallback. +- Tests must replace external providers and report channels with fakes or injected functions and must not call live services. +- Error messages and debug artifacts must not expose credentials or webhook URLs. +- Do not add new outbound data fields without checking data minimization and debug artifact impact. + +## Reusable workflow boundary + +- `.github/workflows/merge-risk-watch.yml` is a consumer-facing API. +- Preserve documented `workflow_call` inputs, secret names, defaults, permissions, and source-resolution behavior unless the task explicitly changes that contract. +- Keep consumer secret names distinct from runtime environment-variable names where the workflow maps them deliberately. +- Tag references use the matching release asset; branch and SHA references use source checkout, `npm ci`, and `npm run build`. +- `upload_debug_artifact` must remain opt-in and upload only the redacted artifact directory. + +## CI and release boundary + +- `.github/workflows/ci.yml` runs on pull requests and owns build/test validation and failure reporting. +- `.github/workflows/release.yml` is a manual semantic-version release path that builds, tests, packages `package.json` and `dist/src`, tags, and creates a GitHub Release. +- Do not change action versions, permissions, triggers, packaging contents, tag behavior, or release asset naming as incidental cleanup. +- `dist/` and `watcher-deploy.tar.gz` are generated outputs and must not be committed. + +## Processing and import direction + +The runtime processing order is: + +```text +workflow collection -> branch selection -> virtual merge and hunk evidence -> risks -> AI assistance -> reports -> report channel +workflow orchestration writes optional debug artifacts throughout the run +``` + +This processing order is not the TypeScript import direction. Preserve the current source dependency shape unless the user approves an ownership change: + +```text +git -> branches +risks -> branches, git +ai -> branches, git, risks +reports -> branches, risks, ai +workflows -> branches, git, risks, ai, reports, reportChannels, debug +``` + +`reportChannels` and `debug` do not import analysis modules. They receive already-built values from workflow orchestration. + +Shared types should stay with the module that owns their meaning. Do not create a generic shared module only because multiple modules import a type. + +## Ambiguity gate + +Stop and ask the user before editing when any of these decisions are not already fixed by the request or current repository contract: + +- A score, threshold, signal precedence, branch exclusion, or report status changes. +- AI becomes authoritative over deterministic results. +- Additional source, diff, PR, check, prompt, response, or secret data leaves the process or enters debug artifacts. +- A reusable workflow input, secret, permission, default, trigger, or release resolution rule changes. +- A public export, report schema, release asset, environment key, or documented consumer example changes. +- A build fix requires weakening strict TypeScript, test isolation, secret redaction, or failure isolation. +- The change expands beyond the current issue or task scope. diff --git a/.agents/rules/general.md b/.agents/rules/general.md new file mode 100644 index 0000000..c93de7d --- /dev/null +++ b/.agents/rules/general.md @@ -0,0 +1,42 @@ +# Watcher General Agent Rules + +## Logic preservation and optimization + +- Reuse the existing program logic as-is whenever possible. +- Change logic only when the new approach produces exactly the same result and strictly improves time or space complexity. +- If there is no clear complexity improvement, keep the original logic. + +## Code modification response style + +- When asked to modify code, return only the precise changed locations and the modified code for those locations. +- Do not include full files, unrelated code, or explanatory text unless explicitly requested. +- You do not need to paste code in the prompt after updating it in the repository. + +## TypeScript style + +- Keep `tsconfig.json` strict-mode compatibility. +- Preserve the repository's ESM and `NodeNext` module conventions. +- Use `import type` when an import is used only as a type. +- Follow the existing no-semicolon style. +- Name implementation types with their full role or type name in camel case. +- Use the shortest clear local variable name unless it conflicts or becomes unclear in the same scope. + +## External effects and secrets + +- Do not run `npm run watch` unless the user explicitly requests it in the current turn. +- Treat GitHub, OpenAI, Discord, release, tag, PR, issue, and comment operations as external effects. +- Do not hardcode or print `GITHUB_TOKEN`, `WATCHER_GITHUB_TOKEN`, `OPENAI_API_KEY`, or `DISCORD_WEBHOOK_URL`. +- Preserve explicit environment-variable fallback behavior. +- Do not add secrets, raw file contents, or raw diff bodies to debug artifacts. + +## Documentation placement + +- Keep AI workflow and rule documents under `.agents/`. +- Keep custom agent configuration under `.codex/agents/`. +- Do not add app-repository, Swift, iOS, Firebase, or Simulator rules to this repository. + +## Repository-local rules + +- Watcher-specific working rules belong in this repository, not in global agent memory. +- Treat `AGENTS.md` and the routed `.agents/` documents as the canonical Watcher AI working rules. +- If global memory conflicts with this repository, follow the repository. diff --git a/.agents/rules/project-workflows.md b/.agents/rules/project-workflows.md new file mode 100644 index 0000000..fe60441 --- /dev/null +++ b/.agents/rules/project-workflows.md @@ -0,0 +1,85 @@ +# Watcher Workflow Rules + +This reference holds Watcher-specific working rules that should live with the project, not in global agent memory. + +## Canonical source + +- Treat this repository's `AGENTS.md` and routed `.agents/` documents as the canonical Watcher working rules. +- Treat `package.json`, `tsconfig.json`, `.github/workflows/*`, and `.github/pull_request_template.md` as the local source of truth. +- Use global memory only as historical context. If global memory conflicts with this repository, follow the repository. + +## Build and verification + +- Use Node 22. +- Prefer `npm ci` when dependencies must be installed. +- Run `npm run build` before `npm test` because tests execute compiled JavaScript from `dist/tests`. +- For a targeted test, build first and then run the matching compiled test with `node --test`. +- Do not run `npm run watch` unless the user explicitly requests live execution in the current turn. +- Do not treat an existing `dist/` result as proof that the current TypeScript source passes. +- Keep strict-mode, ESM, and `NodeNext` compatibility. +- Report exact commands and whether each command passed, failed, or was not run. + +## Generated and local files + +- Do not commit `node_modules/`, `dist/`, `.env`, logs, macOS metadata, `watcher-deploy.tar.gz`, or temporary debug artifacts. +- Build output may be recreated and should not be included in review scope. +- Check `git status --short` before staging or reporting completion. + +## GitHub Actions + +- CI should run for pull requests, not every branch push. +- PR branch updates are covered by the `pull_request` workflow. +- Keep Node and action runtime versions aligned with GitHub runtime requirements. +- Preserve reusable workflow input, secret, permission, source-resolution, and artifact contracts unless the task explicitly changes them. +- Preserve manual semantic-version validation, build/test ordering, tag checks, package contents, and release asset naming in `release.yml` unless the task explicitly changes release behavior. +- Do not run or dispatch workflows unless the user explicitly requests that GitHub write action. + +## CI diagnosis + +- Inspect the failing run, job, step, and relevant log excerpt before proposing a change. +- Separate dependency installation, TypeScript build, test, reusable-workflow runtime, token permission, provider, report channel, artifact upload, and release failures. +- Reproduce locally with `npm run build` and `npm test` when the failure can be checked without live services. +- Do not run `npm run watch` as a local reproduction unless the user explicitly requests it and supplies the required environment context. +- Do not edit workflow files until the failing step and contract are identified. + +## PR and review handling + +- Write Watcher PR and review text in Korean and end sentences in noun form. +- Follow `.github/pull_request_template.md` for PR body structure. +- Base PR text on the actual branch diff and live issue or PR state. +- If the user asks for PR content only, return the Markdown directly and do not create files. +- Use thread-aware inspection when unresolved GitHub review threads matter. +- Verify each suggestion against the current code, tests, and diff before accepting it. +- Apply only accepted fixes and keep unrelated cleanup out of the diff. + +## Commit guidance + +- Commit messages must start with a prefix such as `feat`, `fix`, `refactor`, or `chore`. +- Write commit message prose in Korean. +- Keep implementation names, file paths, commands, branch names, workflow names, issue numbers, and commit hashes in their original form. +- Do not write a commit message body. +- Commit only files related to the current change. +- Check `git status --short` before staging. +- Do not stage, commit, push, create a PR, reply, resolve a thread, tag, or release unless the user explicitly requests that action. + +## Consumer workflow contract + +- Treat `.github/workflows/merge-risk-watch.yml` and the corresponding README sections as one consumer-facing contract. +- Keep `repository`, `base_branch`, `default_branch`, `critical_file_patterns`, `watcher_version`, and `upload_debug_artifact` aligned across workflow and documentation. +- Keep `watcher_github_token`, `openai_api_key`, and optional `discord_webhook_url` aligned with runtime environment mapping. +- Preserve release-tag asset download and branch/SHA source-build fallback behavior unless the change explicitly revises it. +- Update consumer examples only when their public contract changes. + +## Release work + +- Treat release creation, tag creation, tag push, and asset upload as external writes requiring explicit user authorization. +- Verify semantic version format and existing tags before release actions. +- Run `npm run build` and `npm test` before claiming release readiness. +- Keep `watcher-deploy.tar.gz` limited to the files expected by the reusable workflow. +- Do not commit the release archive or `dist/`. + +## Documentation alignment + +- Update README behavior descriptions when public inputs, secrets, environment variables, score policy, AI behavior, debug artifacts, report behavior, or release behavior changes. +- Do not update README for an internal refactor that leaves the documented contract unchanged. +- Keep AI workflow documents under `.agents/` and custom agent configurations under `.codex/agents/`. diff --git a/.agents/workflows.md b/.agents/workflows.md new file mode 100644 index 0000000..a6cd473 --- /dev/null +++ b/.agents/workflows.md @@ -0,0 +1,409 @@ +# Watcher Agent Workflows + +## Purpose + +This file defines executable AI workflows for Watcher work. + +Use this after reading `AGENTS.md` and `.agents/roles.md`. `.agents/roles.md` defines what each role may do. This file defines how to combine those roles for common project tasks. + +If this file conflicts with `AGENTS.md`, follow `AGENTS.md`. + +## Main-agent protocol + +The main agent must run every workflow with this protocol. + +1. Read `AGENTS.md`, then `.agents/roles.md`, then this file. +2. Select one workflow from this file. +3. Create the task packet. +4. Assign only the roles required by the selected workflow. +5. Assign each role a model tier from `.agents/roles.md`. +6. Keep `Primary` roles with the active main agent. +7. Find the exact custom agent name in `.agents/roles.md` and its matching `.codex/agents/.toml` before dispatching a `Lightweight` or `Fast` role. +8. Create the role as a side task connected to the current main task with `spawn_agent.task_name` set to that exact name, or use `Option-Command-S` from the UI sidebar for the same connected dispatch surface. +9. Do not use external `codex exec`, a separate user-owned `create_thread`, or an arbitrary `task_name` for repository role dispatch. +10. Reuse the existing role agent with `followup_task` when assigning later work to the same role. +11. Return every delegated role result to the current main task for `Primary` review and integration. +12. Do not complete a required `Lightweight` or `Fast` role directly in `Primary`, and do not substitute a generic sub-agent for the configured custom agent. +13. Dispatch read-only `Lightweight` or `Fast` roles in parallel only when they do not depend on unfinished edits. +14. Keep `Primary` editing roles sequential unless the files and ownership boundaries are disjoint. +15. Integrate role outputs. +16. Escalate any `Lightweight` or `Fast` blocker to a `Primary` model before editing. +17. Run completion gates. +18. Report changed files, architecture decision, verification result, delegated roles, model tiers used, and unresolved decisions. + +Do not skip the task packet. The task packet is the contract between models. + +## Universal stop conditions + +Stop and ask the user before editing when: + +- The task packet conflicts with `AGENTS.md`. +- The requested fix requires changing deterministic scores, statuses, signal precedence, AI authority, data exposure, secret handling, public workflow inputs, release packaging, or public exports without an explicit contract. +- A role needs to call live GitHub, OpenAI, Discord, workflow dispatch, tag, release, PR, issue, or comment operations without current-turn authorization. +- A required `Lightweight` or `Fast` custom agent cannot be loaded or selected through the connected side-task surface with its exact `task_name`, its pinned model is unavailable, or current tool policy requires user permission that has not been granted. +- The current issue or PR scope is unclear after live GitHub inspection. +- Two editing roles would touch the same file. +- A read-only role reports `Block` or `Needs Owner Decision`. +- Verification fails for a reason that suggests a scope, product-policy, security, workflow-contract, or release decision. + +Do not apply the custom-agent stop condition only because external `codex exec`, a separate `create_thread`, or an arbitrary `task_name` failed. Retry through the connected side-task surface with the exact configured name first. + +## Workflow selection + +| User request | Workflow | +| --- | --- | +| "이슈 구현", issue number, feature, bug fix | Issue-driven implementation | +| Deterministic score, AI, external service, reusable workflow, release, public export, architecture docs | Architecture-sensitive implementation | +| PR review comment, unresolved thread, requested changes | Review-thread follow-up | +| Failing GitHub Actions, CI log, reusable workflow, release failure | CI failure triage | +| PR body, release note, README, issue wording | Documentation-only writing | +| AI role, AGENTS, workflow, or architecture-rule docs | AI workflow maintenance | + +## Issue-driven implementation + +Use when implementing a live issue or user-scoped code change. + +### Role order + +1. GitHub/CI Analyst, if live issue or PR state matters. +2. Planner. +3. Architecture Watcher, if `Architecture risk` is `possible` or `confirmed`. +4. Implementer. +5. Code Reviewer. +6. Verification Runner. +7. Documentation Writer, if PR, release, README, or issue text is needed. + +### Task packet source + +```md +## Task Packet + +- Source: +- Goal: +- Scope: +- Out of scope: +- Expected changed files: +- Current owner: +- Architecture risk: none / possible / confirmed +- Required roles: +- Model assignment: +- Verification: +- Stop conditions: +``` + +### Execution + +- Planner must identify the owning module, input and output contract, external effects, source files, tests, and documentation before Implementer edits TypeScript. +- Implementer must edit only files listed in the task packet unless Planner updates the packet. +- Behavior changes must include tests for success, boundary, and failure or fallback cases that are relevant to the contract. +- Code Reviewer must check deterministic result drift, provider failure isolation, secret exposure, workflow contract drift, and scope drift before style concerns. +- Verification Runner must build fresh TypeScript output before running compiled tests. +- Do not use `npm run watch` to prove implementation correctness unless the user explicitly requests a live integration run. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: Issue-driven implementation +- Changed files: +- Architecture decision: +- Verification: +- Remaining decisions: +``` + +## Architecture-sensitive implementation + +Use when the task touches module ownership, dependency direction, deterministic risk results, AI target or provider behavior, external-service data, secret redaction, debug artifacts, reusable workflow contracts, CI or release behavior, public exports, or architecture documentation. + +### Role order + +1. Planner. +2. Architecture Watcher before editing. +3. Implementer, only after Architecture Watcher returns `Pass`. +4. Architecture Watcher after editing, if ownership, dependency, deterministic, AI, external-effect, workflow, release, or public contracts changed. +5. Code Reviewer. +6. Verification Runner. + +### Architecture Watcher gate + +Architecture Watcher must return: + +- `Pass` before Implementer edits. +- `Block` when the requested change violates current rules. +- `Needs Owner Decision` when the repository rules require user confirmation. + +Implementer must not proceed on `Block` or `Needs Owner Decision`. + +### Required inspection + +- Relevant source imports and module ownership. +- Existing source and tests for the changed contract. +- Deterministic score, status, reason, precedence, and same-input behavior. +- AI target selection, evidence shape, prompt, response validation, failure isolation, and batching. +- GitHub, OpenAI, Discord, environment-variable, child-process, filesystem, and debug-artifact data flow. +- `package.json`, `tsconfig.json`, `src/index.ts`, `README.md`, and relevant `.github/workflows/*` when affected. +- Reusable workflow inputs, secrets, permissions, source resolution, and release asset compatibility. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: Architecture-sensitive implementation +- Architecture Watcher verdict: +- Changed files: +- Boundary decision: +- Verification: +- Remaining decisions: +``` + +## Review-thread follow-up + +Use when the user asks to address PR review comments or unresolved review threads. + +### Role order + +1. GitHub/CI Analyst. +2. Planner. +3. Architecture Watcher, if a requested fix touches architecture-sensitive areas. +4. Implementer. +5. Code Reviewer. +6. Verification Runner. +7. GitHub/CI Analyst, only if the user requested replies or thread resolution. + +### Execution + +- GitHub/CI Analyst must use thread-aware inspection when unresolved review threads matter. +- Planner must classify each comment as required, optional, already handled, rejected, or needing owner decision. +- Planner must map accepted comments to concrete source, test, workflow, or documentation files. +- Implementer must apply only accepted fixes. +- Code Reviewer must verify that the final diff addresses accepted comments without unrelated cleanup or contract drift. +- Verification Runner must run fresh build and tests for TypeScript changes and docs checks for documentation-only changes. +- GitHub/CI Analyst must mirror the existing PR reply style when replying and must change GitHub state only when explicitly authorized. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: Review-thread follow-up +- Addressed comments: +- Deferred or rejected comments: +- Changed files: +- Verification: +- GitHub actions: +``` + +## CI failure triage + +Use when GitHub Actions CI, `merge-risk-watch.yml`, debug artifact upload, or `release.yml` fails. + +### Role order + +1. GitHub/CI Analyst. +2. Planner. +3. Verification Runner, if a local reproduction is possible without live services. +4. Implementer, only after a concrete root cause is identified. +5. Code Reviewer. +6. Verification Runner. + +### Execution + +- GitHub/CI Analyst must inspect the failing run, job, step, and relevant log excerpt before proposing fixes. +- Planner must separate dependency installation, TypeScript build, test, reusable-workflow source resolution, checkout or token permission, OpenAI, Discord, artifact upload, tag, and release failures. +- Verification Runner must use Node 22, run `npm run build`, then `npm test` when local source verification applies. +- Live provider, consumer repository, permission, workflow dispatch, or release reproduction requires explicit user authorization. +- Implementer must not edit workflow files until the failing step and contract are identified. +- Verification Runner must not treat CI polling as a substitute for local verification when local checks are available. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: CI failure triage +- Failing run: +- Root cause: +- Changed files: +- Verification: +- Remaining CI risk: +``` + +## Documentation-only writing + +Use for PR body, issue text, release note, README wording, review reply draft, consumer workflow guidance, or user-facing explanation. + +### Role order + +1. Documentation Writer. +2. Code Reviewer, if wording must match a diff or runtime contract. +3. GitHub/CI Analyst, if live issue, PR, workflow run, tag, or release state matters. +4. Verification Runner, for file presence, Markdown, link, and diff checks when files changed. + +### Execution + +- Documentation Writer must inspect the actual diff and current implementation before writing PR, release, or behavior text. +- When live state matters, GitHub/CI Analyst must provide the issue, PR, run, tag, or release source before the draft is finalized. +- When the Documentation Writer role is required, the main agent must dispatch the draft through `documentation_writer` before writing the final response. +- If dispatch requires explicit user permission and it has not been granted, ask before drafting, returning, or posting the Documentation Writer output. +- `Primary` must review the output against `.github/pull_request_template.md`, issue scope, implementation, tests, workflows, and actual diff. +- Keep deterministic possibility separate from AI prediction and do not claim live-service verification that was not run. +- If the user asks only for text, return text directly and do not create files. +- If documentation files are changed, keep the change scoped to the requested document. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: Documentation-only writing +- Target: +- Changed files: +- Source checked: +- Verification: +``` + +## AI workflow maintenance + +Use for `AGENTS.md`, `.agents/roles.md`, this file, `.agents/rules`, or `.codex/agents` role-routing changes. + +### Role order + +1. Planner. +2. Implementer. +3. Code Reviewer. +4. Verification Runner. + +Architecture Watcher is required only if the change modifies ownership maps, deterministic or AI boundaries, external-service or secret rules, reusable workflow contracts, release contracts, ambiguity gates, or architecture rules. + +### Execution + +- Keep `AGENTS.md` as the short repository-root AI workflow entrypoint. +- Do not add app-repository, Swift, iOS, Firebase, or Simulator rules. +- `.agents/roles.md` defines role permissions, model routing, output formats, and task packet shape. +- `.agents/workflows.md` defines executable role sequences. +- `.agents/rules/general.md` defines logic preservation, response style, TypeScript style, external effects, and documentation placement. +- `.agents/rules/architecture.md` defines Watcher ownership, deterministic and AI boundaries, service effects, reusable workflow contracts, release contracts, and ambiguity gates. +- `.agents/rules/project-workflows.md` defines build, test, CI, PR, commit, release, and documentation-delivery rules. +- `.codex/agents/*.toml` must use the exact role identifiers from `.agents/roles.md`. +- Preserve the approved reference document structure and role names when that is the task contract; adapt only Watcher-specific duties and examples. + +### Verification + +Verification Runner must run: + +```sh +git diff --check -- AGENTS.md .agents .codex/agents +python_path="" +for candidate in python3.14 python3.13 python3.12 python3.11 /opt/homebrew/bin/python3 python3; do + if candidate_path="$(command -v "$candidate" 2>/dev/null)" && "$candidate_path" -c 'import tomllib' 2>/dev/null; then + python_path="$candidate_path" + break + fi +done +test -n "$python_path" +"$python_path" -c 'import pathlib, tomllib; [tomllib.loads(path.read_text()) for path in pathlib.Path(".codex/agents").glob("*.toml")]' +rg -n 'gpt-5\.3-codex-spark|\bPrimary\b|\bLightweight\b|\bFast\b' --glob '*.md' --glob '*.toml' AGENTS.md .agents .codex/agents +git status --short +``` + +If only Markdown and TOML AI workflow files changed, no TypeScript build is required. + +### Completion + +Report: + +```md +## Workflow Result + +- Workflow: AI workflow maintenance +- Changed files: +- Operational change: +- Verification: +- Remaining decisions: +``` + +## Parallel dispatch guide + +Use only side tasks connected to the current main task for parallel role dispatch. Create them with exact configured custom agent names through `spawn_agent` or with `Option-Command-S` in the UI sidebar. + +Parallelize only these combinations: + +- GitHub/CI Analyst reading live GitHub state while Planner inspects local files. +- Architecture Watcher reviewing boundaries while Code Reviewer reviews non-architecture risks after the diff is complete. +- Documentation Writer drafting PR or release text while Verification Runner runs checks, after the diff is stable. + +Do not parallelize: + +- Two Implementers over overlapping files. +- Implementer and Code Reviewer before Implementer finishes the diff. +- Verification Runner before the relevant files are saved. +- GitHub write actions with local code edits. +- Any role that would run `npm run watch` with another role changing runtime code or environment contracts. + +## Role prompt snippets + +Use the activation template from `.agents/roles.md`, then set `` to one of: + +- `Planner` +- `Implementer` +- `Architecture Watcher` +- `Code Reviewer` +- `Verification Runner` +- `GitHub/CI Analyst` +- `Documentation Writer` + +Include the selected workflow name in the task packet `Source` or `Goal` field so the receiving model can align its output to this runbook. + +## Task packet examples + +### Issue-driven implementation example + +```md +## Task Packet + +- Source: https://github.com/opficdev/Watcher/issues/41 +- Goal: Define AI agent roles and executable role-based workflows for Watcher. +- Scope: Update root AI workflow files and custom agent configuration only. +- Out of scope: TypeScript source, tests, package scripts, GitHub Actions, README, live services, git and GitHub writes. +- Expected changed files: `AGENTS.md`, `.agents/roles.md`, `.agents/workflows.md`, `.agents/rules/*.md`, `.codex/agents/*.toml` +- Current owner: repository workflow documentation +- Architecture risk: possible +- Required roles: Planner, Architecture Watcher, Implementer, Code Reviewer, Verification Runner +- Model assignment: Planner=Primary, Architecture Watcher=architecture_watcher (Lightweight), Implementer=Primary, Code Reviewer=code_reviewer (Lightweight), Verification Runner=verification_runner (Lightweight) +- Custom agent `task_name`: Architecture Watcher=`architecture_watcher`, Code Reviewer=`code_reviewer`, Verification Runner=`verification_runner` +- Result recipient: `Primary` of the current main task +- Verification: diff check, TOML parsing, exact role and model scan, `git status --short` +- Stop conditions: role-name changes, README changes, TypeScript or workflow changes, public consumer contract changes, live-service execution +``` + +### Review-thread follow-up example + +```md +## Task Packet + +- Source: +- Goal: Address accepted review feedback without expanding PR scope. +- Scope: Apply only required review fixes confirmed by GitHub/CI Analyst and Planner. +- Out of scope: Optional suggestions, unrelated cleanup, new score or architecture policy, live `npm run watch`, release actions. +- Expected changed files: +- Current owner: +- Architecture risk: none / possible / confirmed +- Required roles: GitHub/CI Analyst, Planner, Implementer, Code Reviewer, Verification Runner +- Model assignment: GitHub/CI Analyst=github_ci_analyst (Lightweight), Planner=Primary, Implementer=Primary, Code Reviewer=code_reviewer (Lightweight) -> Primary if blocking, Verification Runner=verification_runner (Lightweight) +- Custom agent `task_name`: GitHub/CI Analyst=`github_ci_analyst`, Code Reviewer=`code_reviewer`, Verification Runner=`verification_runner` +- Result recipient: `Primary` of the current main task +- Verification: `npm run build`, `npm test`, and workflow or docs checks when applicable +- Stop conditions: unresolved thread requires owner decision, fix changes deterministic or public workflow behavior, two comments conflict, CI failure source is unrelated to review feedback +``` diff --git a/.codex/agents/architecture_watcher.toml b/.codex/agents/architecture_watcher.toml new file mode 100644 index 0000000..a5b393b --- /dev/null +++ b/.codex/agents/architecture_watcher.toml @@ -0,0 +1,13 @@ +name = "architecture_watcher" +description = "Read-only Watcher architecture boundary reviewer for module ownership, deterministic risk, AI assistance, external services, workflow contracts, secrets, debug artifacts, and release packaging." +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Read AGENTS.md and .agents/roles.md before reviewing. +Act only as the Architecture Watcher defined in .agents/roles.md. +Inspect the assigned source, tests, package configuration, relevant GitHub Actions workflows, and README contracts without editing files or changing GitHub state. +Check module ownership, dependency direction, deterministic-result preservation, AI authority and validation, provider failure isolation, external data, secret redaction, debug artifacts, reusable workflow inputs and secrets, public exports, and release packaging. +Do not run npm run watch or call live GitHub, OpenAI, Discord, tag, release, PR, issue, or comment operations. +Return exactly the Architecture Watch Result format from .agents/roles.md. +""" diff --git a/.codex/agents/code_reviewer.toml b/.codex/agents/code_reviewer.toml new file mode 100644 index 0000000..1275686 --- /dev/null +++ b/.codex/agents/code_reviewer.toml @@ -0,0 +1,13 @@ +name = "code_reviewer" +description = "Read-only Watcher code reviewer focused on correctness, deterministic regressions, AI failure isolation, secret safety, workflow contracts, scope drift, and missing verification." +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Read AGENTS.md and .agents/roles.md before reviewing. +Act only as the Code Reviewer defined in .agents/roles.md. +Review the assigned diff and related source, tests, workflows, and documentation without editing files, staging changes, committing, pushing, or changing GitHub state. +Prioritize branch selection, Git signal handling, deterministic scores and statuses, AI target and response mapping, provider failure isolation, secret exposure, debug artifacts, report output, workflow contracts, release behavior, scope drift, and missing tests over style preferences. +Do not review generated dist output as source and do not run npm run watch. +Return exactly the Code Review Result format from .agents/roles.md with file and line references when possible. +""" diff --git a/.codex/agents/documentation_writer.toml b/.codex/agents/documentation_writer.toml new file mode 100644 index 0000000..2b33cd7 --- /dev/null +++ b/.codex/agents/documentation_writer.toml @@ -0,0 +1,14 @@ +name = "documentation_writer" +description = "Watcher documentation writer for PR bodies, issue text, review replies, release notes, README behavior, consumer workflow guidance, and troubleshooting." +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Read AGENTS.md and .agents/roles.md before drafting. +Act only as the Documentation Writer defined in .agents/roles.md. +Match .github/pull_request_template.md, the actual diff, current implementation, tests, workflows, and live issue or PR state when available. +Write PR and review prose in Korean with noun-form endings while preserving implementation names, paths, commands, environment variables, workflow names, branch names, issue numbers, and commit hashes. +Keep deterministic possibility distinct from AI prediction and keep inputs, secrets, permissions, debug artifacts, report fallback, and release behavior aligned with the repository. +Edit only documentation files named in the task packet. Do not edit TypeScript, tests, package configuration, or workflows, and do not create GitHub content unless explicitly authorized. +Return exactly the Documentation Result format from .agents/roles.md unless the task packet requests direct Markdown draft output. +""" diff --git a/.codex/agents/github_ci_analyst.toml b/.codex/agents/github_ci_analyst.toml new file mode 100644 index 0000000..1644fa2 --- /dev/null +++ b/.codex/agents/github_ci_analyst.toml @@ -0,0 +1,14 @@ +name = "github_ci_analyst" +description = "Read-only Watcher GitHub and CI analyst for live issues, PR review threads, checks, reusable workflows, tags, releases, and Actions logs." +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "read-only" +developer_instructions = """ +Read AGENTS.md and .agents/roles.md before analysis. +Act only as the GitHub/CI Analyst defined in .agents/roles.md. +Use live GitHub state as the source of truth and use thread-aware review inspection when resolution state matters. +For failures, identify the exact run, job, step, and relevant log excerpt, then separate installation, TypeScript build, test, source resolution, checkout or token permission, OpenAI, Discord, artifact upload, tag, and release causes. +Redact secrets and unrelated log data. +Do not edit local files, reply, resolve threads, submit reviews, dispatch workflows, push, tag, release, or change GitHub state unless the task packet explicitly authorizes that write action. +Return exactly the GitHub CI Result format from .agents/roles.md. +""" diff --git a/.codex/agents/verification_runner.toml b/.codex/agents/verification_runner.toml new file mode 100644 index 0000000..b20142d --- /dev/null +++ b/.codex/agents/verification_runner.toml @@ -0,0 +1,15 @@ +name = "verification_runner" +description = "Watcher verification runner for fresh TypeScript builds, compiled tests, targeted tests, Markdown and TOML checks, diff validation, and generated-file inspection." +model = "gpt-5.3-codex-spark" +model_reasoning_effort = "medium" +sandbox_mode = "workspace-write" +developer_instructions = """ +Read AGENTS.md and .agents/roles.md before verification. +Act only as the Verification Runner defined in .agents/roles.md. +Run only the checks assigned in the task packet and record exact commands, exit status, evidence, skipped checks, and failure notes. +Use Node 22. Run npm run build before npm test or targeted compiled tests when TypeScript source or tests changed. +For AI workflow documents, run diff checks, TOML parsing, exact role and model scans, file-presence checks, and git status inspection. +Do not edit source or documentation files except through an explicitly assigned formatting command. +Do not run npm run watch or call live GitHub, OpenAI, Discord, workflow dispatch, tag, release, PR, issue, or comment operations unless explicitly authorized. +Return exactly the Verification Result format from .agents/roles.md. +""" diff --git a/AGENTS.md b/AGENTS.md index 1fff94f..72ce2df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,45 +1,26 @@ -# AGENTS.md +# Watcher Agent Instructions -## Repository Scope -- Watcher is a standalone TypeScript/Node automation repository. -- Keep app-repository specific rules out of this repository. -- Treat `package.json`, `tsconfig.json`, `.github/workflows/*`, and `.github/pull_request_template.md` as the local source of truth. +## Scope -## Build and Verification -- Use Node 22 for project build/test execution. -- Prefer `npm ci` for dependency installation. -- Use `npm test` for verification because it includes the TypeScript build. -- Do not run `npm run start` unless explicitly requested, because it can call GitHub, Gemini, or Discord services. +- These instructions apply only to the repository root. +- Read every route that matches the current task. Routes are cumulative. -## Generated and Local Files -- Do not commit `node_modules/`, `dist/`, `.env`, logs, or macOS metadata. -- `dist/` is generated by the TypeScript build and can be recreated. -- Secrets such as `DISCORD_WEBHOOK_URL`, `GITHUB_TOKEN`, and `GEMINI_API_KEY` must not be hardcoded. +## Required routing -## GitHub Actions -- CI should run for pull requests, not every branch push. -- PR branch updates should be covered by the `pull_request` workflow. -- Keep action runtime versions current with GitHub's Node runtime requirements. +| Task | Required document | +| --- | --- | +| Every task | `.agents/rules/general.md` | +| Non-trivial planning, implementation, review, or verification | `.agents/roles.md` | +| Repeatable role-based execution | `.agents/workflows.md` | +| Module ownership, dependency direction, deterministic analysis, external-service boundaries, reusable workflow contracts, secrets, or release packaging | `.agents/rules/architecture.md` | +| PR, review thread, commit, CI, verification, release, or GitHub Actions work | `.agents/rules/project-workflows.md` | -## Code Changes -- Preserve existing logic unless a change clearly improves correctness or complexity. -- Keep TypeScript strict-mode compatibility. -- Keep environment-variable fallback behavior explicit and documented in code or README. +## Routing rules -## Commit Instructions -- Commit messages must start with a predefined prefix such as `feat`, `fix`, `refactor`, or `chore`. -- Write prose in Korean. -- Keep implementation names such as `GitHubClient`, `sendDiscordWebhook`, `buildDiscordReport`, `merge-risk-watch.yml`, file paths, commands, branch names, and commit hashes in their original form. -- Do not translate implementation names into Korean unless the user explicitly asks for a user-facing Korean label. -- Do not write a commit message body. -- Commit only the files related to the current change. -- Check `git status --short` before staging to avoid including generated or unrelated files. - -## Pull Request Instructions -- All pull requests must follow the provided PR template file. -- Write all content in Korean. -- End sentences in noun form. -- Base PR summaries on the actual branch diff, not on stale stash contents or unrelated local files. -- Keep implementation names, commands, file paths, branch names, issue numbers, and workflow names in their original form. -- Mention verification using commands that were actually run. -- Do not add screenshots or images unless they are relevant to the change. +- `AGENTS.md` is the repository entrypoint and routing source. +- `.agents/rules/general.md` applies to every task. +- Read all matching task-specific documents before planning, editing, reviewing, or verifying. +- For architecture work, also read `README.md`, `package.json`, `tsconfig.json`, and the relevant `.github/workflows/*` files before editing. +- For a delegated role, read `.agents/roles.md` and follow the assigned role section and output format. +- Use `.agents/workflows.md` when the task matches one of its executable workflows. +- If repository-local instructions conflict with global memory, follow the repository-local instructions.