diff --git a/.agents/agents/architecture-reviewer.md b/.agents/agents/architecture-reviewer.md index e6844b1e..2565086d 100644 --- a/.agents/agents/architecture-reviewer.md +++ b/.agents/agents/architecture-reviewer.md @@ -12,16 +12,13 @@ You are an Architecture Specialist. Diagnose the architectural concern before re Follow the vendor-specific execution protocol: - Use the injected claim path and task/run/session identity from `.agents/skills/_shared/runtime/result-contract.md`. Human-readable reports use `result-{agentId}-{taskId}-{runId}-{sessionId}.md`. - Include: status, recommendation summary, tradeoffs, risks, validation steps, artifacts created -- The run-scoped result file is the report; durable artifacts (ADRs, recommendations) are saved separately under `.agents/results/architecture/` and linked from the report — the report does not replace them +- The run-scoped result file is the report. ADRs and retained recommendations are saved under `docs/decisions/` (linked from `docs/decisions/index.md`); run-specific reviews, diagnoses, and unselected comparison drafts go under `.agents/results/architecture/`. Link both from the report — the report does not replace them Follow the shared execution policy for authorization and clarification. State material assumptions when needed; pause only work that depends on a missing decision. No fixed preflight output is required. ## Rules -1. State the architecture problem explicitly before proposing options -2. Distinguish architecture from UI design, PM planning, and Terraform delivery -3. Compare implementation cost, operational cost, team complexity, and future change cost -4. Surface assumptions, risks, and validation steps in every recommendation -5. Save ADRs or architecture notes under `.agents/results/architecture/` when material -6. Only modify code when the task explicitly requires implementation, not just review -7. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +1. Apply the rules in `.agents/skills/oma-architecture/SKILL.md`; read it first when it is not already in context +2. Save a selected decision as an ADR under `docs/decisions/` and keep run-specific analysis under `.agents/results/architecture/`; read prior decisions in `docs/decisions/` first +3. Only modify code when the task explicitly requires implementation, not just review +4. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/backend-engineer.md b/.agents/agents/backend-engineer.md index 2752ec05..aec4c078 100644 --- a/.agents/agents/backend-engineer.md +++ b/.agents/agents/backend-engineer.md @@ -15,20 +15,11 @@ Follow the vendor-specific execution protocol: Follow the shared execution policy for authorization and clarification. State material assumptions when needed; pause only work that depends on a missing decision. No fixed preflight output is required. -## Architecture - -Router (HTTP) → Service (Business Logic) → Repository (Data Access) → Models - ## Rules 1. Stay in scope — only work on assigned backend tasks -2. Use risk-relevant tests or an explicit alternative verification; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file -3. Follow Repository → Service → Router pattern (no business logic in routes) -4. Validate all inputs with the project's validation library -5. Parameterized queries only (no string interpolation in SQL) -6. JWT + Argon2id for auth (bcrypt acceptable for legacy compatibility) -7. Async/await consistently -8. Custom exceptions via centralized error module -9. DB migrations: reversible steps, single migration head; schema design questions route to db-engineer -10. Document out-of-scope dependencies for other agents -11. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules in `.agents/skills/oma-backend/SKILL.md`; read it first when it is not already in context +3. Use risk-relevant tests or an explicit alternative verification; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file +4. DB migrations: reversible steps, single migration head; schema design questions route to db-engineer +5. Document out-of-scope dependencies for other agents +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/db-engineer.md b/.agents/agents/db-engineer.md index 6c699ab2..8e0cfee3 100644 --- a/.agents/agents/db-engineer.md +++ b/.agents/agents/db-engineer.md @@ -18,14 +18,8 @@ Follow the shared execution policy for authorization and clarification. State ma ## Rules 1. Stay in scope — only work on assigned database tasks -2. Choose data model first, engine second -3. At least 3NF for relational (break only with justification) -4. Document ACID/BASE expectations explicitly -5. Three schema layers: external, conceptual, internal -6. Integrity as first-class: entity, domain, referential, business-rule -7. Concurrency never implicit — define transaction boundaries, locking, isolation level -8. Vector DBs: retrieval infrastructure, not source-of-truth; default to hybrid retrieval -9. Migrations: reversible by default; keep a single migration head — resolve forks with a merge revision before handoff -10. Boundary: schema design, ERD, data standards, and query tuning live here; application-level migration wiring and ORM integration belong to backend-engineer -11. Select deliverables for the task: schema work may need a design and data standards; capacity estimates belong to capacity planning -12. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules in `.agents/skills/oma-db/SKILL.md`; read it first when it is not already in context +3. Migrations: reversible by default; keep a single migration head — resolve forks with a merge revision before handoff +4. Boundary: schema design, ERD, data standards, and query tuning live here; application-level migration wiring and ORM integration belong to backend-engineer +5. Select deliverables for the task: schema work may need a design and data standards; capacity estimates belong to capacity planning +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/debug-investigator.md b/.agents/agents/debug-investigator.md index 4f2fe26e..4934fde4 100644 --- a/.agents/agents/debug-investigator.md +++ b/.agents/agents/debug-investigator.md @@ -26,9 +26,8 @@ Follow the shared execution policy for authorization and clarification. State ma ## Rules 1. Stay in scope — only work on assigned debug tasks -2. Fix root cause, not symptoms +2. Apply the rules in `.agents/skills/oma-debug/SKILL.md`; read it first when it is not already in context 3. Minimal changes only — no refactoring during bugfix; route refactoring needs to refactor-engineer 4. Every fix gets a regression test; run it before the fix where feasible and record RED (failing output) → GREEN (post-fix pass) in the bug report -5. Search for similar patterns after fixing -6. Document out-of-scope findings for other agents -7. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +5. Document out-of-scope findings for other agents +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/docs-curator.md b/.agents/agents/docs-curator.md index e646f583..52b37088 100644 --- a/.agents/agents/docs-curator.md +++ b/.agents/agents/docs-curator.md @@ -21,7 +21,7 @@ Follow the shared execution policy for authorization and clarification. State ma 2. **Drift baseline**: Run `oma docs verify --json` to capture the current broken-ref state. Persist counts in the result file. 3. **Candidate match**: Run `oma docs sync --json` to get `{ doc, changedFiles, matchedRefs }` candidates. Skip secret-bearing files (CLI already excludes `.env*`, `*.pem`, `*.key`, `id_rsa*`). 4. **Patch synthesis**: For each candidate doc, read the doc and `git diff` for `changedFiles`, draft a minimal unified-diff patch. Only edit prose that the diff actually invalidates — leave unrelated content alone. -5. **Apply**: Write the patches directly via `Edit`/`Write`. **Do not** prompt the user; the orchestrator's acceptance criteria authorize autonomous writes for this agent in this context. +5. **Apply**: Write the patches directly via `Edit`/`Write` when the task is an edit request or an assigned implementation task (see Auto-Write Authority). For a review-only request, return the proposed patches instead. 6. **Re-verify**: Run `oma docs verify --json` again. Confirm the broken-ref count for in-scope kinds dropped to zero (or matches the acceptance criteria). 7. **Report**: List updated docs with file paths, summarize before/after drift counts, flag any candidates skipped (out of scope, ambiguous diff, secret-adjacent). @@ -32,12 +32,13 @@ A scoped user edit request or assigned implementation task authorizes those corr ## Rules 1. Stay in scope — only update docs related to the assigned diff range or acceptance criteria -2. Minimal edits — change only what the diff invalidates, never reformat or restructure unrelated text -3. Never modify code (`*.ts`, `*.tsx`, `*.py`, `*.go`, etc.) — surface mismatches for `backend-engineer` / `frontend-engineer` instead -4. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions -5. Never touch secret-bearing files even if surfaced in diffs (`.env*`, `*.pem`, `*.key`, `id_rsa*`) -6. Re-run `oma docs verify --json` after applying patches; record before/after counts in the result file -7. ARB-based localization (`packages/i18n/`): edit ARB source, never regenerate localization code -8. Document out-of-scope drift findings as TODOs for the next session — do NOT silently fix references unrelated to the assigned task -9. Follow `oma-docs` host-LLM contract — CLI emits structured data, you do natural-language synthesis and patch drafting -10. Co-Author commits when staging is delegated: `Co-Authored-By: First Fluke ` +2. Apply the rules in `.agents/skills/oma-docs/SKILL.md`; read it first when it is not already in context +3. Minimal edits — change only what the diff invalidates, never reformat or restructure unrelated text +4. Never modify code (`*.ts`, `*.tsx`, `*.py`, `*.go`, etc.) — surface mismatches for `backend-engineer` / `frontend-engineer` instead +5. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +6. Never touch secret-bearing files even if surfaced in diffs (`.env*`, `*.pem`, `*.key`, `id_rsa*`) +7. Re-run `oma docs verify --json` after applying patches; record before/after counts in the result file +8. ARB-based localization: edit the ARB source files, never the generated localization code +9. Document out-of-scope drift findings as TODOs for the next session — do NOT silently fix references unrelated to the assigned task +10. Follow `oma-docs` host-LLM contract — CLI emits structured data, you do natural-language synthesis and patch drafting +11. When staging or committing is delegated, follow `oma-scm`: add a co-author trailer only when `scm.co_author.enabled` is true, copying the configured name and email exactly diff --git a/.agents/agents/frontend-engineer.md b/.agents/agents/frontend-engineer.md index 0beda223..7db49835 100644 --- a/.agents/agents/frontend-engineer.md +++ b/.agents/agents/frontend-engineer.md @@ -16,19 +16,13 @@ Follow the vendor-specific execution protocol: Follow the shared execution policy for authorization and clarification. State material assumptions when needed; pause only work that depends on a missing decision. No fixed preflight output is required. -## Architecture - -FSD-lite: root `src/` + feature `src/features/*/` - ## Rules 1. Stay in scope — only work on assigned frontend tasks -2. Component reuse: shadcn/ui first, extend via `cva` -3. Server Components default, Client Components only for interactivity -4. Accessibility mandatory (semantic HTML, ARIA, keyboard nav) -5. TailwindCSS v4 for styling, design tokens 1:1 mapping -6. Library defaults (greenfield; existing project choices win): luxon (dates), ahooks (hooks), es-toolkit (utils), jotai (client state), TanStack Query (server state) -7. Absolute imports with `@/` -8. Verify custom logic against the project or task coverage target; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file -9. Document out-of-scope dependencies for other agents -10. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules of the skill that owns the task (`.agents/skills/oma-frontend/SKILL.md`, `.agents/skills/oma-design/SKILL.md`); read it first when it is not already in context +3. Accessibility mandatory (semantic HTML, ARIA, keyboard nav) +4. TailwindCSS v4 for styling, design tokens 1:1 mapping +5. Absolute imports with `@/` +6. Verify custom logic against the project or task coverage target; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file +7. Document out-of-scope dependencies for other agents +8. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/mobile-engineer.md b/.agents/agents/mobile-engineer.md index ac4d22dc..2a1388f6 100644 --- a/.agents/agents/mobile-engineer.md +++ b/.agents/agents/mobile-engineer.md @@ -1,6 +1,6 @@ --- name: mobile-engineer -description: Flutter/React Native/Swift native mobile implementation. Use for mobile app, widgets, SwiftUI, platform feature work. +description: Flutter/React Native/Swift native/Kotlin Android native mobile implementation. Use for mobile app, widgets, SwiftUI, Jetpack Compose, platform feature work. skills: - oma-mobile --- @@ -17,18 +17,13 @@ Follow the shared execution policy for authorization and clarification. State ma ## Architecture -Clean Architecture: domain → data → presentation (Swift native: App/Core/Features/Shared) +Clean Architecture: domain → data → presentation (Swift native: App/Core/Features/Shared; Kotlin native: `app/{ui,data,di}` + `api-client`) ## Rules 1. Stay in scope — only work on assigned mobile tasks -2. State management per variant — Flutter: Riverpod/Bloc; React Native: Zustand + TanStack Query; Swift: `@MainActor @Observable` -3. Material Design 3 (Android) + iOS HIG (iOS) -4. Dispose controllers / cancel structured tasks properly -5. Transport client with interceptors (Dio / axios / generated Client) + repository-layer response cache when offline, latency, or read patterns require it -6. Secrets in secure storage only — never plain prefs or MMKV -7. 60fps target performance -8. Select widget/component or integration tests for affected behavior; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file -9. ARB-based localization: edit ARB source files only, never generated localization code -10. Document out-of-scope dependencies for other agents -11. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules in `.agents/skills/oma-mobile/SKILL.md`; read it first when it is not already in context +3. Select widget/component or integration tests for affected behavior; honor the plan task's `test_approach` — for `tdd`, demonstrate RED before the change and record a `TDD_EVIDENCE` block (test command, RED, GREEN) in the result file +4. ARB-based localization: edit ARB source files only, never generated localization code +5. Document out-of-scope dependencies for other agents +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/pm-planner.md b/.agents/agents/pm-planner.md index 1f5b3f40..797db48c 100644 --- a/.agents/agents/pm-planner.md +++ b/.agents/agents/pm-planner.md @@ -28,7 +28,8 @@ Follow the shared execution policy for authorization and clarification. State ma Each task must include: - `agent`: assigned domain agent - `title`: what to do -- `acceptance_criteria`: testable conditions +- `acceptance_criteria`: testable conditions; for an executable acceptance gate, `{id, description}` objects +- `required_checks` (executable gates): unique `{id, criteria, command, cwd}` objects that cover every criterion with an exact argv and a project-relative cwd — see `.agents/skills/_shared/runtime/result-contract.md` - `priority`: execution tier — 1 = independent (runs first), 2 = depends on tier 1, etc. (lower runs first) - `dependencies`: task IDs that must complete first - `scope`: directory prefixes this task's agent may modify (used to detect boundary violations in parallel runs) @@ -37,8 +38,7 @@ Each task must include: ## Rules 1. Stay in scope — planning only, no code implementation -2. API-first design -3. Minimize dependencies for maximum parallelism +2. Apply the rules in `.agents/skills/oma-pm/SKILL.md`; read it first when it is not already in context +3. API-first design 4. Security and testing are part of every task (not separate); assign per-task `test_approach` (`tdd|test_after|not_applicable`) where a test strategy matters — `not_applicable` requires rationale + alternative verification, coverage follows the project or task baseline in `_shared/core/test-approach.md` -5. Each task completable by a single agent -6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +5. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/qa-reviewer.md b/.agents/agents/qa-reviewer.md index 6ee4f215..ccf22d8a 100644 --- a/.agents/agents/qa-reviewer.md +++ b/.agents/agents/qa-reviewer.md @@ -15,13 +15,6 @@ Follow the vendor-specific execution protocol: Follow the shared execution policy for authorization and clarification. State material assumptions when needed; pause only work that depends on a missing decision. No fixed preflight output is required. -## Review Priority Order - -1. **Security** (OWASP Top 10) -2. **Performance** (N+1 queries, re-renders, bundle size) -3. **Accessibility** (WCAG 2.2 AA) -4. **Code Quality** (naming, error handling, tests) - ## Output Format Report findings with severity levels: @@ -44,13 +37,9 @@ Report findings with severity levels: ## Rules -1. Every finding: file:line, description, fix -2. Severity: CRITICAL, HIGH, MEDIUM, LOW -3. Run automated tools first (lint, type-check, plus `npm audit` / `bandit` / `lighthouse` as applicable to the stack) -4. No false positives — verify each finding -5. Provide remediation code, not just descriptions -6. PASS verdict: zero CRITICAL, HIGH, and MEDIUM issues -7. WARNING verdict: zero CRITICAL and HIGH, but MEDIUM issues exist -8. FAIL verdict: any CRITICAL or HIGH issue found -9. Never modify source code — review only -10. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +1. Apply the rules in `.agents/skills/oma-qa/SKILL.md`; read it first when it is not already in context +2. PASS verdict: zero CRITICAL, HIGH, and MEDIUM issues +3. WARNING verdict: zero CRITICAL and HIGH, but MEDIUM issues exist +4. FAIL verdict: any CRITICAL or HIGH issue found +5. Never modify source code — review only +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/refactor-engineer.md b/.agents/agents/refactor-engineer.md index 945eba47..8d083356 100644 --- a/.agents/agents/refactor-engineer.md +++ b/.agents/agents/refactor-engineer.md @@ -20,18 +20,15 @@ Follow the shared execution policy for authorization and clarification. State ma 1. **Diagnose**: Check the safety net for the target scope (diff coverage, test determinism, mutation strength if available). No net -> build it first. 2. **Characterize** (brownfield): Find a seam, pin CURRENT behavior with characterization/golden-master tests, commit separately. 3. **Target**: Rank by hotspot (complexity x churn), not smell aesthetics. Skip cold complex code. -4. **Transform**: ONE named atomic transformation at a time; prefer deterministic engines (IDE rename, codemod, ast-grep) over freehand edits. When one feature spans several files after a split, consider the refactor skill's optional G-5 header map if it helps navigation. -5. **Verify**: Re-run existing tests UNCHANGED. Pass -> commit `refactor:` only. Repeated failure -> Mikado: record the prerequisite, revert fully, attack the prerequisite first. +4. **Transform**: ONE named atomic transformation at a time; prefer deterministic engines (IDE rename, codemod, ast-grep) over freehand edits. When one feature spans several files after a split, a short entry-file comment listing the related paths and their roles can help navigation. +5. **Verify**: Re-run existing tests UNCHANGED when test execution is permitted; when it is ruled out, stop and report the transformation as unverified. Pass -> commit `refactor:` only. Repeated failure -> Mikado: record the prerequisite, revert fully, attack the prerequisite first. 6. **Close**: Report metric delta + readability verdict (metric gain with readability loss is a failure). ## Rules 1. Stay in scope — only work on assigned refactoring tasks -2. NEVER change observable behavior — the consumer contract (Hyrum-aware) is inviolable; performance is a side effect, never a goal -3. Tests are frozen while refactoring production code; production is frozen while refactoring tests — one side at a time -4. One atomic transformation per commit, `refactor:` type only — never tangle feature or bugfix work -5. Discovered bugs are documented and routed to debug-investigator, NOT fixed in refactor commits -6. Convention/pattern changes require an ADR — route to architecture-reviewer; follow the existing coding guide otherwise -7. Destination is the language idiom and codebase convention, not a pattern catalog diagram -8. Document out-of-scope findings for other agents -9. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules in `.agents/skills/oma-refactor/SKILL.md`; read it first when it is not already in context +3. Discovered bugs are documented and routed to debug-investigator, NOT fixed in refactor commits +4. Convention/pattern changes require an ADR — route to architecture-reviewer; follow the existing coding guide otherwise +5. Document out-of-scope findings for other agents +6. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/research-explorer.md b/.agents/agents/research-explorer.md index f8d43517..ccf8e6f7 100644 --- a/.agents/agents/research-explorer.md +++ b/.agents/agents/research-explorer.md @@ -1,6 +1,6 @@ --- name: research-explorer -description: Cross-source research specialist. Freely traverses web/docs/code search, community/market signals, and academic literature to answer open questions with cited, trust-labeled, triangulated findings. +description: Cross-source research specialist. Freely traverses web/docs/code search, community/market signals, and academic literature to answer open questions with cited, provenance-labeled, triangulated findings. skills: - oma-search - oma-market @@ -29,18 +29,17 @@ Follow the shared execution policy for authorization and clarification. State ma 1. **Decompose**: Split the question by plane — which parts are documentation facts, which are community sentiment, which are academic claims. 2. **Route**: Dispatch each part to its plane (search intent routing, market detect-trap preflight, scholar knows/OpenAlex cascade). Keyless-first; paid sources only when keys exist and value is clear. -3. **Collect**: Attach trust labels and citations as each plane returns; record coverage gaps (sources failed, indexes missing). +3. **Collect**: Attach citations and source provenance (what was actually read versus a search excerpt) as each plane returns; record coverage gaps (sources failed, indexes missing). 4. **Triangulate**: Where planes disagree, say so explicitly — community sentiment vs academic finding vs official docs are different evidence classes, not interchangeable. 5. **Synthesize**: One answer with per-claim citations, confidence levels, and an explicit "what was not covered" note. ## Rules 1. Stay in scope — research and synthesis only; never write or modify code -2. Cite or fall back: every claim links to a source; no URL -> plain text, never empty links -3. Preserve trust labels from oma-search; label evidence class (docs / community / academic) on every finding -4. Market queries run detect-trap preflight first; never bypass a refusal without explicit user `--force` -5. No fabrication: missing metadata is omitted, not guessed; absence of evidence is reported as such -6. Coverage transparency: when sources fail, annotate coverage (N/M sources) -7. Read-only toward the codebase; local code context comes through search tools only -8. Document out-of-scope findings for other agents -9. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +2. Apply the rules of the skill that owns the task (`.agents/skills/oma-search/SKILL.md`, `.agents/skills/oma-market/SKILL.md`, `.agents/skills/oma-scholar/SKILL.md`); read it first when it is not already in context +3. Cite or fall back: every claim links to a source; no URL -> plain text, never empty links +4. Preserve oma-search's source provenance and inspection status; label evidence class (docs / community / academic) on every finding +5. Coverage transparency: when sources fail, annotate coverage (N/M sources) +6. Read-only toward the codebase; local code context comes through search tools only +7. Document out-of-scope findings for other agents +8. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/tf-infra-engineer.md b/.agents/agents/tf-infra-engineer.md index a543ef41..f583778a 100644 --- a/.agents/agents/tf-infra-engineer.md +++ b/.agents/agents/tf-infra-engineer.md @@ -17,11 +17,8 @@ Follow the shared execution policy for authorization and clarification. State ma ## Rules -1. Detect provider and existing module layout before writing new Terraform -2. Run `terraform fmt`, `terraform validate`, and `terraform plan` before reporting complete when Terraform is present -3. Use remote state, version pinning, and least-privilege IAM by default -4. Prefer OIDC/workload identity over long-lived static credentials -5. Do not hardcode secrets in `.tf` files or examples -6. Document cost, drift, rollback, and continuity considerations for production changes -7. Never run destructive operations without explicit user approval -8. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions +1. Apply the rules in `.agents/skills/oma-tf-infra/SKILL.md`; read it first when it is not already in context +2. Detect provider and existing module layout before writing new Terraform +3. Format and validate changed configuration (`terraform fmt`, `terraform validate`) when Terraform is available; run `terraform plan` before any apply, or when plan verification is requested and backend credentials are available — otherwise report it as not run +4. Never run destructive operations without explicit user approval +5. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions diff --git a/.agents/agents/variants/agent-variant.schema.json b/.agents/agents/variants/agent-variant.schema.json index 98ccd466..7aaa06e8 100644 --- a/.agents/agents/variants/agent-variant.schema.json +++ b/.agents/agents/variants/agent-variant.schema.json @@ -17,7 +17,7 @@ }, "vendor": { "type": "string", - "description": "The target CLI vendor name (e.g., claude, codex, gemini)" + "description": "The target CLI vendor name (e.g., claude, codex, kiro)" }, "destDir": { "type": "string", diff --git a/.agents/agents/variants/codex.json b/.agents/agents/variants/codex.json index 6ee314a5..ffa5f0ae 100644 --- a/.agents/agents/variants/codex.json +++ b/.agents/agents/variants/codex.json @@ -2,72 +2,32 @@ "$schema": "./agent-variant.schema.json", "vendor": "codex", "destDir": ".codex/agents", - "modelDefault": "gpt-5.6-terra", + "modelDefault": "inherit", "effortDefault": "high", "toolsDefault": [], "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/codex.md", "agents": { - "backend-engineer": { - "extra": { - "sandbox_mode": "workspace-write" - } - }, - "frontend-engineer": { - "extra": { - "sandbox_mode": "workspace-write" - } - }, - "db-engineer": { - "extra": { - "sandbox_mode": "workspace-write" - } - }, + "backend-engineer": {}, + "frontend-engineer": {}, + "db-engineer": {}, "debug-investigator": { - "effort": "high", - "extra": { - "sandbox_mode": "workspace-write" - } + "effort": "high" }, "architecture-reviewer": { - "effort": "high", - "extra": { - "sandbox_mode": "read-only" - } - }, - "tf-infra-engineer": { - "extra": { - "sandbox_mode": "workspace-write" - } - }, - "mobile-engineer": { - "extra": { - "sandbox_mode": "workspace-write" - } - }, - "pm-planner": { - "extra": { - "sandbox_mode": "read-only" - } + "effort": "high" }, + "tf-infra-engineer": {}, + "mobile-engineer": {}, + "pm-planner": {}, "qa-reviewer": { - "effort": "high", - "extra": { - "sandbox_mode": "read-only" - } + "effort": "high" }, + "refactor-engineer": {}, "docs-curator": { - "model": "gpt-5.6-luna", - "effort": "max", - "extra": { - "sandbox_mode": "workspace-write" - } + "effort": "medium" }, "research-explorer": { - "model": "gpt-5.6-luna", - "effort": "max", - "extra": { - "sandbox_mode": "read-only" - } + "effort": "low" } } } diff --git a/.agents/agents/variants/commandcode.json b/.agents/agents/variants/commandcode.json index fc6a9869..70aba492 100644 --- a/.agents/agents/variants/commandcode.json +++ b/.agents/agents/variants/commandcode.json @@ -4,23 +4,63 @@ "destDir": ".commandcode/agents", "modelDefault": "inherit", "maxTurnsDefault": 100, - "toolsDefault": "Read, Write, Edit, Bash, Grep, Glob", + "toolsDefault": [ + "read_file", + "write_file", + "edit_file", + "shell_command", + "grep", + "glob" + ], "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/commandcode.md", "agents": { "architecture-reviewer": { - "tools": "Read, Write, Edit, Bash, Grep, Glob" + "tools": [ + "read_file", + "write_file", + "edit_file", + "shell_command", + "grep", + "glob" + ] }, "tf-infra-engineer": { - "tools": "Read, Write, Edit, Bash, Grep, Glob" + "tools": [ + "read_file", + "write_file", + "edit_file", + "shell_command", + "grep", + "glob" + ] }, "pm-planner": { - "tools": "Read, Write, Grep, Glob, Bash" + "tools": ["read_file", "write_file", "grep", "glob", "shell_command"] }, "qa-reviewer": { - "tools": "Read, Grep, Glob, Bash" + "tools": ["read_file", "grep", "glob", "shell_command"] }, "docs-curator": { - "tools": "Read, Write, Edit, Bash, Grep, Glob" + "tools": [ + "read_file", + "write_file", + "edit_file", + "shell_command", + "grep", + "glob" + ] + }, + "research-explorer": { + "tools": [ + "read_file", + "write_file", + "edit_file", + "shell_command", + "grep", + "glob", + "web_search", + "web_fetch" + ] } } } diff --git a/.agents/agents/variants/copilot.json b/.agents/agents/variants/copilot.json new file mode 100644 index 00000000..0f8e418d --- /dev/null +++ b/.agents/agents/variants/copilot.json @@ -0,0 +1,9 @@ +{ + "$schema": "./agent-variant.schema.json", + "vendor": "copilot", + "destDir": ".github/agents", + "modelDefault": "inherit", + "toolsDefault": [], + "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/copilot.md", + "agents": {} +} diff --git a/.agents/agents/variants/cursor.json b/.agents/agents/variants/cursor.json index 0a739157..cfdc734e 100644 --- a/.agents/agents/variants/cursor.json +++ b/.agents/agents/variants/cursor.json @@ -4,7 +4,7 @@ "destDir": ".cursor/agents", "modelDefault": "inherit", "toolsDefault": [], - "protocolPath": ".agents/skills/_shared/core/quality-principles.md", + "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/cursor.md", "agents": { "backend-engineer": { "extra": { @@ -18,25 +18,17 @@ }, "db-engineer": { "extra": { - "readonly": true - } - }, - "architecture-reviewer": { - "extra": { - "readonly": true + "is_background": true } }, + "architecture-reviewer": {}, "debug-investigator": {}, "mobile-engineer": { "extra": { "is_background": true } }, - "pm-planner": { - "extra": { - "readonly": true - } - }, + "pm-planner": {}, "qa-reviewer": { "extra": { "readonly": true, @@ -52,6 +44,16 @@ "extra": { "is_background": true } + }, + "refactor-engineer": { + "extra": { + "is_background": true + } + }, + "research-explorer": { + "extra": { + "readonly": true + } } } } diff --git a/.agents/agents/variants/grok.json b/.agents/agents/variants/grok.json index fa207b8b..cd16cb5d 100644 --- a/.agents/agents/variants/grok.json +++ b/.agents/agents/variants/grok.json @@ -4,7 +4,28 @@ "destDir": ".grok/agents", "modelDefault": "grok-build", "maxTurnsDefault": 100, - "toolsDefault": "run_terminal_cmd, read_file, search_replace, list_dir, grep", + "toolsDefault": [ + "run_terminal_cmd", + "read_file", + "search_replace", + "list_dir", + "grep" + ], "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/grok.md", - "agents": {} + "agents": { + "qa-reviewer": { + "tools": ["run_terminal_cmd", "read_file", "list_dir", "grep"] + }, + "research-explorer": { + "tools": [ + "run_terminal_cmd", + "read_file", + "search_replace", + "list_dir", + "grep", + "web_search", + "web_fetch" + ] + } + } } diff --git a/.agents/agents/variants/kilo.json b/.agents/agents/variants/kilo.json new file mode 100644 index 00000000..5855b1a1 --- /dev/null +++ b/.agents/agents/variants/kilo.json @@ -0,0 +1,22 @@ +{ + "$schema": "./agent-variant.schema.json", + "vendor": "kilo", + "destDir": ".kilo/agents", + "modelDefault": "inherit", + "toolsDefault": [], + "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/kilo.md", + "agents": { + "backend-engineer": {}, + "frontend-engineer": {}, + "db-engineer": {}, + "debug-investigator": {}, + "architecture-reviewer": {}, + "tf-infra-engineer": {}, + "mobile-engineer": {}, + "pm-planner": {}, + "qa-reviewer": {}, + "docs-curator": {}, + "refactor-engineer": {}, + "research-explorer": {} + } +} diff --git a/.agents/agents/variants/kiro.json b/.agents/agents/variants/kiro.json index 216faff0..0ee785eb 100644 --- a/.agents/agents/variants/kiro.json +++ b/.agents/agents/variants/kiro.json @@ -16,13 +16,25 @@ "protocolPath": ".agents/skills/_shared/runtime/execution-protocols/kiro.md", "agents": { "architecture-reviewer": { - "tools": ["read", "grep", "glob", "code"] + "tools": ["read", "write", "grep", "glob", "code"] }, "pm-planner": { - "tools": ["read", "grep", "glob", "shell"] + "tools": ["read", "write", "grep", "glob", "shell"] }, "qa-reviewer": { "tools": ["read", "grep", "glob", "shell"] + }, + "research-explorer": { + "tools": [ + "read", + "write", + "shell", + "grep", + "glob", + "code", + "subagent", + "web" + ] } } } diff --git a/.agents/hooks/core/agentmemory-client.ts b/.agents/hooks/core/agentmemory-client.ts index decf6467..c201bcaa 100644 --- a/.agents/hooks/core/agentmemory-client.ts +++ b/.agents/hooks/core/agentmemory-client.ts @@ -27,6 +27,90 @@ function endpointUrl(): string | null { } } +// AgentMemory >= 0.9.x always provisions an API secret and answers 401 to +// unauthenticated REST calls (health included). Mirror of +// cli/state/agentmemory-auth.ts → resolveAgentMemorySecret (hooks cannot +// import cli/), which in turn mirrors AgentMemory's `resolveClientSecret`: +// env secret first; file-discovered secrets only for loopback endpoints. +function usableSecret(value: unknown): string { + if (typeof value !== "string") return ""; + const trimmed = value.trim(); + if (!trimmed) return ""; + if (trimmed.startsWith("${") && trimmed.endsWith("}")) return ""; + return trimmed; +} + +function readSecretFile(path: string): string { + try { + return usableSecret(readFileSync(path, "utf-8")); + } catch { + return ""; + } +} + +function readEnvFileSecret(path: string): string { + let content: string; + try { + content = readFileSync(path, "utf-8"); + } catch { + return ""; + } + let found = ""; + for (const line of content.split("\n")) { + const trimmed = line.trim(); + if (trimmed.startsWith("#")) continue; + const eq = trimmed.indexOf("="); + if (eq === -1) continue; + const key = trimmed + .slice(0, eq) + .replace(/^export\s+/, "") + .trim(); + if (key !== "AGENTMEMORY_SECRET") continue; + let value = trimmed.slice(eq + 1).trim(); + const quote = value[0]; + if ((quote === '"' || quote === "'") && value.length > 1) { + const close = value.indexOf(quote, 1); + if (close !== -1) value = value.slice(1, close); + } else { + const hash = value.indexOf(" #"); + if (hash !== -1) value = value.slice(0, hash).trim(); + } + found = usableSecret(value); + } + return found; +} + +function isLoopbackUrl(url: string): boolean { + let hostname: string; + try { + hostname = new URL(url).hostname.toLowerCase(); + } catch { + return false; + } + const bare = hostname.replace(/^\[|\]$/g, ""); + return ( + bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare) + ); +} + +export function resolveAgentMemorySecret( + baseUrl: string, + env: NodeJS.ProcessEnv = process.env, +): string { + const fromEnv = usableSecret(env.AGENTMEMORY_SECRET); + if (fromEnv) return fromEnv; + if (env.AGENTMEMORY_CREDENTIAL_MODE === "explicit") return ""; + if (!isLoopbackUrl(baseUrl)) return ""; + const home = join(homedir(), ".agentmemory"); + return ( + readEnvFileSecret(env.AGENTMEMORY_ENV_FILE || join(home, ".env")) || + readSecretFile(join(home, "secret")) || + (env.AGENTMEMORY_DATA_DIR + ? readSecretFile(join(env.AGENTMEMORY_DATA_DIR, "secret")) + : "") + ); +} + let reachable: boolean | null = null; /** @@ -57,7 +141,11 @@ function requestAgentMemory( } const body = options.body; - const headers = { ...(options.headers ?? {}) }; + const secret = resolveAgentMemorySecret(baseUrl); + const headers: Record = { + ...(secret ? { authorization: `Bearer ${secret}` } : {}), + ...(options.headers ?? {}), + }; if (body !== undefined && headers["content-length"] === undefined) { headers["content-length"] = String(Buffer.byteLength(body)); } diff --git a/.agents/hooks/core/agy-input.ts b/.agents/hooks/core/agy-input.ts index 80bca16f..02303310 100644 --- a/.agents/hooks/core/agy-input.ts +++ b/.agents/hooks/core/agy-input.ts @@ -37,27 +37,164 @@ export function agyConversationId( return typeof input.conversationId === "string" ? input.conversationId : null; } +function resolveFullStepContent( + transcriptPath: string, + stepIndex: number | undefined, + lineIndex: number, + expectedType: string, +): string | null { + const fullPath = transcriptPath.replace( + /transcript\.jsonl$/, + "transcript_full.jsonl", + ); + if (fullPath === transcriptPath || !existsSync(fullPath)) return null; + try { + const lines = readFileSync(fullPath, "utf-8").split("\n"); + if (stepIndex !== undefined) { + for (const rawLine of lines) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + try { + const step = JSON.parse(trimmed) as Record; + if ( + step.step_index === stepIndex && + step.type === expectedType && + typeof step.content === "string" + ) { + return step.content; + } + } catch { + // skip malformed line + } + } + } + const byLine = lines[lineIndex]?.trim(); + if (byLine) { + const step = JSON.parse(byLine) as Record; + if (step.type === expectedType && typeof step.content === "string") { + return step.content; + } + } + } catch { + // ignore unreadable full transcript + } + return null; +} + +function isContentTruncated(step: Record): boolean { + return ( + Array.isArray(step.truncated_fields) && + step.truncated_fields.includes("content") + ); +} + +function stripUserRequestEnvelope(raw: string): string { + const match = raw.match(/\s*([\s\S]*?)\s*<\/USER_REQUEST>/); + if (match?.[1] !== undefined) return match[1].trim(); + return raw + .replace(/[\s\S]*?<\/ADDITIONAL_METADATA>/g, "") + .replace(/[\s\S]*$/g, "") + .trim(); +} + /** - * Recover the latest user prompt from an agy transcript.jsonl. + * Recover the latest user prompt from an agy transcript.jsonl (falling back to + * transcript_full.jsonl when `truncated_fields` marks `content` as truncated). * * Each transcript line is a JSON step; user turns have `type === "USER_INPUT"` * with the request wrapped as `…` inside `content` * (alongside metadata blocks we strip). Returns the most recent request text, * or "" when the transcript is missing/unreadable. */ -export function readAgyPrompt(transcriptPath: unknown): string { +export function readAgyPrompt( + transcriptPath: unknown, + fallbackLastUserInput?: unknown, +): string { + if (typeof transcriptPath === "string" && existsSync(transcriptPath)) { + let content = ""; + let stepIndex: number | undefined; + let lineIndex = -1; + let truncated = false; + try { + const lines = readFileSync(transcriptPath, "utf-8").split("\n"); + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i]?.trim(); + if (!trimmed) continue; + try { + const step = JSON.parse(trimmed) as Record; + if (step.type === "USER_INPUT" && typeof step.content === "string") { + content = step.content; // keep the last USER_INPUT + stepIndex = + typeof step.step_index === "number" ? step.step_index : undefined; + lineIndex = i; + truncated = isContentTruncated(step); + } + } catch { + // skip malformed transcript line + } + } + } catch { + content = ""; + } + if (truncated && lineIndex >= 0) { + const full = resolveFullStepContent( + transcriptPath, + stepIndex, + lineIndex, + "USER_INPUT", + ); + if (full !== null) content = full; + } + const stripped = stripUserRequestEnvelope(content); + if (stripped) return stripped; + } + if ( + typeof fallbackLastUserInput === "string" && + fallbackLastUserInput.trim() + ) { + return stripUserRequestEnvelope(fallbackLastUserInput); + } + return ""; +} + +/** + * Recover the latest assistant response text from an agy transcript.jsonl + * (after the last USER_INPUT turn), falling back to transcript_full.jsonl when + * `truncated_fields` includes `"content"`. + * + * Used by the Stop hook so `"workflow done"` deactivation works on agy (whose + * Stop stdin payload does not carry the model response directly). + */ +export function readAgyResponse(transcriptPath: unknown): string { if (typeof transcriptPath !== "string" || !existsSync(transcriptPath)) { return ""; } let content = ""; + let stepIndex: number | undefined; + let lineIndex = -1; + let truncated = false; try { - for (const line of readFileSync(transcriptPath, "utf-8").split("\n")) { - const trimmed = line.trim(); + const lines = readFileSync(transcriptPath, "utf-8").split("\n"); + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i]?.trim(); if (!trimmed) continue; try { const step = JSON.parse(trimmed) as Record; - if (step.type === "USER_INPUT" && typeof step.content === "string") { - content = step.content; // keep the last USER_INPUT + if (step.type === "USER_INPUT") { + content = ""; + stepIndex = undefined; + lineIndex = -1; + truncated = false; + } else if ( + step.type === "PLANNER_RESPONSE" && + typeof step.content === "string" && + step.content.trim() + ) { + content = step.content; + stepIndex = + typeof step.step_index === "number" ? step.step_index : undefined; + lineIndex = i; + truncated = isContentTruncated(step); } } catch { // skip malformed transcript line @@ -66,6 +203,41 @@ export function readAgyPrompt(transcriptPath: unknown): string { } catch { return ""; } - const match = content.match(/\s*([\s\S]*?)\s*<\/USER_REQUEST>/); - return (match?.[1] ?? content).trim(); + if (truncated && lineIndex >= 0) { + const full = resolveFullStepContent( + transcriptPath, + stepIndex, + lineIndex, + "PLANNER_RESPONSE", + ); + if (full !== null) content = full; + } + return content.trim(); +} + +const NON_BLOCKING_STOP_REASONS = new Set([ + "USER_CANCELED", + "ERROR", + "MAX_FORCED_INVOCATIONS", + "MAX_TOKEN_BUDGET_EXCEEDED", +]); + +/** + * True when an agy Stop payload indicates user cancellation, an executor error, + * or an exhausted forced-continuation/token budget — cases where a Stop hook + * must NOT force `decision: "continue"`. + */ +export function isAgyNonBlockingStopReason( + input: Record, +): boolean { + if ( + typeof input.terminationReason === "string" && + NON_BLOCKING_STOP_REASONS.has(input.terminationReason) + ) { + return true; + } + if (typeof input.error === "string" && input.error.trim().length > 0) { + return true; + } + return false; } diff --git a/.agents/hooks/core/code-fingerprint.ts b/.agents/hooks/core/code-fingerprint.ts new file mode 100644 index 00000000..49e57c26 --- /dev/null +++ b/.agents/hooks/core/code-fingerprint.ts @@ -0,0 +1,84 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; + +export interface CodeFingerprint { + head: string | null; + dirty: boolean; + treeHash: string | null; +} + +/** Snapshot tracked changes and untracked names; never read untracked contents. */ +export async function captureCodeFingerprint( + projectDir: string, +): Promise { + const unavailable: CodeFingerprint = { + head: null, + dirty: false, + treeHash: null, + }; + // Run both reads together, bounded to one second for the whole snapshot. + const git = (args: string[]): Promise => + new Promise((resolve) => { + try { + execFile( + "git", + args, + { + cwd: projectDir, + encoding: "utf-8", + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, + timeout: 1_000, + killSignal: "SIGKILL", + maxBuffer: 16 * 1024 * 1024, + windowsHide: true, + }, + (error, stdout) => resolve(error ? null : stdout), + ); + } catch { + resolve(null); + } + }); + const [status, diff] = await Promise.all([ + git([ + "status", + "--porcelain=v2", + "--branch", + "--no-ahead-behind", + "-z", + "--untracked-files=all", + "--no-renames", + ]), + git([ + "diff", + "HEAD", + "--binary", + "--no-ext-diff", + "--no-textconv", + "--ignore-submodules=none", + ]), + ]); + if (status === null) return unavailable; + const entries = status.split("\0").filter(Boolean); + const head = entries + .find((entry) => entry.startsWith("# branch.oid ")) + ?.slice(13); + if (!head || head === "(initial)") return unavailable; + if (diff === null) return unavailable; + const untracked = entries.filter((entry) => entry.startsWith("? ")); + return { + head, + dirty: entries.some((entry) => !entry.startsWith("# ")), + treeHash: createHash("sha256") + .update(diff) + .update("\0") + .update(untracked.join("\0")) + .digest("hex"), + }; +} + +export function sameCodeFingerprint( + a: CodeFingerprint, + b: CodeFingerprint, +): boolean { + return a.head === b.head && a.dirty === b.dirty && a.treeHash === b.treeHash; +} diff --git a/.agents/hooks/core/code-intelligence-guard.ts b/.agents/hooks/core/code-intelligence-guard.ts index abafeee9..2310c6d3 100644 --- a/.agents/hooks/core/code-intelligence-guard.ts +++ b/.agents/hooks/core/code-intelligence-guard.ts @@ -40,7 +40,7 @@ import { } from "./code-intelligence-scope.ts"; import { makePreToolDenyOutput } from "./hook-output.ts"; import type { HandlerCtx, HandlerResult, HookInput, Vendor } from "./types.ts"; -import { getProjectDir } from "./vendor-detect.ts"; +import { detectVendorFromInput, getProjectDir } from "./vendor-detect.ts"; export const BYPASS_TOKEN = "OMA_CI_ALLOW_NATIVE=1"; @@ -61,6 +61,7 @@ const SHELL_TOOLS = new Set([ "run_shell_command", "Shell", "execute_bash", + "run_command", ]); // --- Shell command parsing --- @@ -312,7 +313,11 @@ function shellSearchRoots( const cleaned = command .replace(DISCARD_REDIRECTION, "$1") // `$HOME` is the one expansion agents routinely use for external paths. - .replace(/\$\{?HOME\}?(?=\/|\s|$)/g, homedir()); + // Forward slashes on win32: a backslash would trip the escape check below. + .replace( + /\$\{?HOME\}?(?=\/|\s|$)/g, + process.platform === "win32" ? homedir().replace(/\\/g, "/") : homedir(), + ); // Do not guess expansions, other redirections or subshells. if (/[$`<>\\()]/.test(cleaned)) return null; const roots: string[] = []; @@ -425,14 +430,15 @@ export async function run( if (!isGrep && !isGlob && !isShell) return null; let searchBin: string | null = null; + const shellCommand = isShell + ? ((toolInput.command ?? toolInput.CommandLine) as string | undefined) + : undefined; if (isShell) { - const command = toolInput.command as string | undefined; - if (!command) return null; - searchBin = detectNativeSearchCommand(command); + if (!shellCommand) return null; + searchBin = detectNativeSearchCommand(shellCommand); if (!searchBin) return null; } - const bypass = - isShell && (toolInput.command as string).includes(BYPASS_TOKEN); + const bypass = isShell && (shellCommand ?? "").includes(BYPASS_TOKEN); // Config reads happen after the cheap tool/command checks so the common // (non-search) path never touches the filesystem. @@ -444,7 +450,7 @@ export async function run( let roots: string[] | null = null; if (isShell) { - roots = shellSearchRoots(toolInput.command as string, sessionCwd); + roots = shellSearchRoots(shellCommand ?? "", sessionCwd); } else if (isGlob && typeof toolInput.pattern === "string") { const base = typeof toolInput.path === "string" ? toolInput.path : sessionCwd; @@ -505,14 +511,26 @@ function main() { if (!raw.trim()) process.exit(0); const parsed: PreToolUseInput = JSON.parse(raw); - // Standalone path is vendor-agnostic here; claude covers the common dialect. - const vendor: Vendor = "claude"; + const vendor: Vendor = detectVendorFromInput( + parsed, + "tool", + import.meta.filename, + ); const projectDir = getProjectDir(vendor, parsed); + const toolCall = parsed.toolCall as + | { name?: string; args?: Record } + | undefined; + const toolName = + parsed.tool_name || + (typeof toolCall?.name === "string" ? toolCall.name : ""); + const rawInput = + parsed.tool_input ?? + (toolCall?.args && typeof toolCall.args === "object" ? toolCall.args : {}); const hookInput: HookInput = { kind: "pre_tool", - toolName: parsed.tool_name, - toolInput: { ...(parsed.tool_input ?? {}) }, + toolName, + toolInput: { ...rawInput }, cwd: projectDir, }; diff --git a/.agents/hooks/core/code-intelligence-primer.ts b/.agents/hooks/core/code-intelligence-primer.ts index c22980df..f0f6dd4f 100644 --- a/.agents/hooks/core/code-intelligence-primer.ts +++ b/.agents/hooks/core/code-intelligence-primer.ts @@ -320,7 +320,7 @@ export async function runStandAlone() { if (vendor === "antigravity" && !prompt) { const invocationNum = input.invocationNum; if (typeof invocationNum === "number" && invocationNum > 1) process.exit(0); - prompt = readAgyPrompt(input.transcriptPath); + prompt = readAgyPrompt(input.transcriptPath, input.lastUserInput); } const hookInput: HookInput = { kind: "prompt", prompt, cwd: projectDir }; diff --git a/.agents/hooks/core/event-contract.ts b/.agents/hooks/core/event-contract.ts index 005d2788..ab01dc92 100644 --- a/.agents/hooks/core/event-contract.ts +++ b/.agents/hooks/core/event-contract.ts @@ -16,7 +16,9 @@ export function validateEventPayload(kind: string, payload: unknown): string[] { ? ["subject", "decision", "rationale"] : kind === "blocker.raised" ? ["summary"] - : []; + : kind === "skill.routed" + ? ["skill", "source", "stage"] + : []; const record = isEventRecord(payload) ? payload : undefined; if (payload !== undefined && !record) errors.push("payload must be an object"); @@ -32,6 +34,21 @@ export function validateEventPayload(kind: string, payload: unknown): string[] { ) { errors.push("payload.status must be completed or failed"); } + if ( + (kind === "gate.passed" || kind === "gate.failed") && + record && + ["head", "dirty", "treeHash"].some((field) => Object.hasOwn(record, field)) + ) { + // Historical gate events omit fingerprints; new fingerprints are complete. + for (const field of ["head", "treeHash"]) { + if (record[field] !== null && typeof record[field] !== "string") { + errors.push(`payload.${field} must be a string or null`); + } + } + if (typeof record.dirty !== "boolean") { + errors.push("payload.dirty must be a boolean"); + } + } if ( record?.instanceId !== undefined && !isNonblankEventText(record.instanceId) diff --git a/.agents/hooks/core/hook-output.ts b/.agents/hooks/core/hook-output.ts index e506a333..1d0603f8 100644 --- a/.agents/hooks/core/hook-output.ts +++ b/.agents/hooks/core/hook-output.ts @@ -284,10 +284,12 @@ export function makePreToolOutput( // `tool_call` event input in place (pi exposes event.input as mutable). return JSON.stringify({ updatedInput }); case "antigravity": - // agy PreToolUse output is a gate decision; it cannot rewrite tool input. - // Allow execution (test-filter is advisory on agy). updatedInput unused. - void updatedInput; - return JSON.stringify({ decision: "allow" }); + // agy PreToolUse supports {"decision": "allow", "overwrite": {...}} to + // replace or merge modified tool arguments before execution. + return JSON.stringify({ + decision: "allow", + overwrite: updatedInput, + }); case "grok": // Grok PreToolUse uses decision + possibly updated tool input return JSON.stringify({ diff --git a/.agents/hooks/core/hud.ts b/.agents/hooks/core/hud.ts index 9e835aad..3c334bb1 100644 --- a/.agents/hooks/core/hud.ts +++ b/.agents/hooks/core/hud.ts @@ -2,10 +2,10 @@ /** * oh-my-agent — HUD * - * Lightweight status display for Claude Code / agy (statusLine): stdin = - * vendor payload, stdout = ANSI text consumed by the native status-line - * renderer. Field names line up across both vendors; vendor-specific extras - * are best-effort. + * Lightweight status display for Claude Code / Qwen Code / agy (statusLine): + * stdin = vendor payload, stdout = ANSI text consumed by the native + * status-line renderer. Field names line up across vendors; vendor-specific + * extras are best-effort. * * Set `OMA_HUD_DEBUG=1` to dump the raw stdin payload to * `/../last-hud-input.json` for schema reverse-engineering. @@ -78,6 +78,8 @@ interface StatuslineStdin { background_tasks?: Array<{ name?: string; status?: string; index?: number }>; pending_input_count?: number; tool_confirmation_pending?: boolean; + /** Qwen Code: present only while vim keybindings are enabled. */ + vim?: { mode?: string }; terminal_width?: number; } @@ -194,18 +196,21 @@ export function shortModel(model?: { // Claude: "Claude Opus 4.6 (1M context)" → "Opus 4.6" const claude = name.match(/(Opus|Sonnet|Haiku)[\s.]*([\d.]*)/i); if (claude) return `${claude[1]}${claude[2] ? ` ${claude[2]}` : ""}`; - // Gemini / agy: "Gemini 3.6 Flash (High)" → "Gemini 3.6 Flash" + // Gemini / agy: "Gemini 3.6 Flash (High)" or "Gemini 2.5 Flash Lite" → "Gemini 3.6 Flash" const gemini = name.match( - /(Gemini)\s+([\d.]+)\s+(Pro|Flash|Ultra|Nano|Thinking)/i, + /(Gemini)\s+([\d.]+)\s+(Flash\s+Lite|Pro|Flash|Ultra|Nano|Thinking|Argon)/i, ); if (gemini) return `${gemini[1]} ${gemini[2]} ${gemini[3]}`; - // Gemini / agy slug: "antigravity/gemini-3.6-flash" → "Gemini 3.6 Flash" + // Gemini / agy slug: "antigravity/gemini-3.6-flash" or "gemini-2.5-flash-lite" const geminiSlug = name.match( - /gemini-([\d.]+)-(pro|flash|ultra|nano|thinking)/i, + /gemini-([\d.]+)-(flash-lite|pro|flash|ultra|nano|thinking|argon)/i, ); if (geminiSlug) { const type = geminiSlug[2] ?? ""; - const capType = type.charAt(0).toUpperCase() + type.slice(1); + const capType = type + .split("-") + .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) + .join(" "); return `Gemini ${geminiSlug[1]} ${capType}`; } return name.split("/").pop()?.slice(0, 20) || ""; @@ -242,6 +247,8 @@ function formatTokens(n: number): string { export function buildClaudeStatusline(input: StatuslineStdin): string { const projectDir = process.env.CLAUDE_PROJECT_DIR || + process.env.QWEN_PROJECT_DIR || + input.workspace?.project_dir || input.cwd || input.workspace?.current_dir || process.cwd(); @@ -254,6 +261,9 @@ export function buildClaudeStatusline(input: StatuslineStdin): string { const model = shortModel(input.model); if (model) parts.push(dim(model)); + // 2b. Qwen Code vim mode (absent unless vim keybindings are enabled). + if (input.vim?.mode) parts.push(dim(`vim:${input.vim.mode}`)); + // 3. Context % const ctxPct = input.context_window?.used_percentage; if (ctxPct != null) { diff --git a/.agents/hooks/core/keyword-detector.ts b/.agents/hooks/core/keyword-detector.ts index 693c5160..6d6ec8fd 100644 --- a/.agents/hooks/core/keyword-detector.ts +++ b/.agents/hooks/core/keyword-detector.ts @@ -25,6 +25,8 @@ import { agyConversationId, readAgyPrompt } from "./agy-input.ts"; import { UNKNOWN_SESSION_ID, VENDORS } from "./constants.ts"; import { makePromptOutput } from "./hook-output.ts"; import { isRelayedAgentMessage, normalizePromptInput } from "./prompt-input.ts"; +import { withStateLock } from "./state-lock.ts"; +import { atomicWriteJson } from "./state-marker.ts"; // triggers.json is imported statically: the bundler inlines it into the oma // binary (bundled `oma hook run` path needs no file on disk), while a standalone // bun run resolves the sibling file next to this module (pi / direct run). @@ -62,7 +64,10 @@ export function normalizeForMatching(text: string): string { * * Third-party harnesses (omc, omx, omo) are intentionally NOT included: they * are separate projects, not host CLIs a user would invoke from an Oma - * session. opencode is also not a supported vendor in this codebase. + * session. opencode IS a supported vendor, but as an extension-class vendor + * (EXTENSION_VENDORS in cli/constants/vendors.ts): its hooks load as + * in-process extensions outside VENDORS/HOOK_VENDORS, so it is intentionally + * absent from this brand list. */ const CLI_INVOCATION_BRANDS = ["oma", ...VENDORS] as const; const CLI_INVOCATION_SIGNALS = [ @@ -209,7 +214,8 @@ export function loadKwState(projectDir: string): KeywordDetectorState { } /** - * Save reinforcement state to disk. + * Save reinforcement state to disk under the cross-process state lock (M12), + * with an atomic tmp+rename write so readers never observe a torn file. */ export function saveKwState( projectDir: string, @@ -217,12 +223,40 @@ export function saveKwState( ): void { try { const filePath = getKwStateFilePath(projectDir); - writeFileSync(filePath, JSON.stringify(state, null, 2)); + withStateLock(`${filePath}.lock`, () => { + atomicWriteJson(filePath, state); + }); } catch { // Non-fatal — reinforcement suppression is best-effort } } +/** + * Locked read-modify-write of the reinforcement state (M12). Two concurrent + * sessions doing load→record→save would otherwise lose one session's trigger + * record. The fresh read happens INSIDE the lock so concurrent records merge. + * Best-effort: on lock-budget exhaustion, degrade to the on-disk state rather + * than throwing into the vendor prompt pipeline. + */ +export function updateKwState( + projectDir: string, + mutate: (state: KeywordDetectorState) => KeywordDetectorState, +): KeywordDetectorState { + const filePath = getKwStateFilePath(projectDir); + try { + return withStateLock(`${filePath}.lock`, () => { + const next = mutate(loadKwState(projectDir)); + atomicWriteJson(filePath, next); + return next; + }); + } catch { + process.stderr.write( + "[oma] keyword-detector state lock busy; skipping reinforcement record\n", + ); + return loadKwState(projectDir); + } +} + /** * Returns true if the keyword should be suppressed due to reinforcement loop. * A keyword is suppressed if it was triggered >= REINFORCEMENT_MAX_COUNT times @@ -846,28 +880,72 @@ function activateMode( ); } +/** + * A session's index pointer is LIVE while its event log exists, has no + * session.ended, and its newest event is fresher than this TTL. The 2-hour + * window mirrors persistent-mode.ts STALE_HOURS: a crashed session that never + * emitted session.ended must not hold active.main forever. + */ +const LIVE_SESSION_TTL_MS = 2 * 60 * 60 * 1000; + +function isLiveL1Session( + readEvents: ( + projectDir: string, + sid: string, + ) => Array<{ kind: string; ts: string }>, + projectDir: string, + sid: string, +): boolean { + const events = readEvents(projectDir, sid); + if (events.length === 0) return false; // orphan pointer — claimable + if (events.some((event) => event.kind === "session.ended")) return false; + const newest = events[events.length - 1]; + const newestMs = newest ? new Date(newest.ts).getTime() : Number.NaN; + if (Number.isNaN(newestMs)) return false; + return Date.now() - newestMs < LIVE_SESSION_TTL_MS; +} + async function activateL1WorkflowSession( projectDir: string, workflow: string, vendor: string, vendorSid: string, + trigger?: Record, category = "main", ): Promise { try { const [ - { setActiveSession }, - { createSessionId, emitEvent, vendorHomePayload }, + { claimActiveSession }, + { createSessionId, emitEvent, readEvents, vendorHomePayload }, ] = await Promise.all([ import("./state-marker.ts"), import("./state-emit.ts"), ]); + // Session IDs use the canonical YYYY-MM-DD_<16> format from + // session-storage; consumers (L1 probe tests, state repair) rely on it. const sid = createSessionId(); - setActiveSession(projectDir, category, sid); + // M12c: never stomp a LIVE different session's pointer. The claim runs + // inside the index lock; when the slot is held by a live session we still + // create our own session + events under the new sid (persistent-mode gate + // events use the omaSid stored in the per-vendor-session state file), but + // active[category] keeps pointing at the live session until it ends or + // goes stale. getActiveSid consumers (state-boundary rehydration) thus + // stay pinned to the session that actually owns the workflow. + claimActiveSession(projectDir, category, sid, (existingSid) => + isLiveL1Session(readEvents, projectDir, existingSid), + ); await emitEvent(projectDir, sid, { kind: "session.created", vendor, vendorSid, - payload: { workflow, category, ...vendorHomePayload(vendor) }, + // `trigger` records WHY the workflow was routed (matched keyword or + // explicit slash) — never the prompt text. + payload: { + workflow, + category, + ...(trigger ? { trigger } : {}), + ...vendorHomePayload(vendor), + }, }); return sid; } catch (e) { @@ -1125,7 +1203,9 @@ export async function run( if (input.kind !== "prompt") return null; const { prompt } = input; - const { vendor, cwd: projectDir, sid: sessionId = "unknown" } = ctx; + const { cwd: projectDir, sid: sessionId = "unknown" } = ctx; + // Recorded on the L1 session only; the output dialect stays ctx.vendor. + const vendor = ctx.host ?? ctx.vendor; if (!prompt.trim()) return null; if (startsWithSlashCommand(prompt)) { @@ -1138,6 +1218,7 @@ export async function run( slashWorkflow, vendor, sessionId, + { source: "user-explicit", command: `/${slashWorkflow}` }, ); activateMode(projectDir, slashWorkflow, sessionId, omaSid); } @@ -1276,6 +1357,10 @@ export async function run( workflow, vendor, sessionId, + { + source: explicit ? "user-explicit" : "keyword", + matchedKeyword: winner.matchText, + }, ); // Only an explicit invocation enables persistent mode (the Stop hook blocks // while the state file exists). Natural-language matches such as "keep @@ -1283,8 +1368,9 @@ export async function run( if (winner.persistent && explicit) { activateMode(projectDir, workflow, sessionId, omaSid); } - const updatedState = recordKwTrigger(kwState, workflow); - saveKwState(projectDir, updatedState); + // Locked read-modify-write: re-reads fresh state inside the lock so two + // concurrent sessions' trigger records merge instead of clobbering (M12). + updateKwState(projectDir, (current) => recordKwTrigger(current, workflow)); const contextLines = buildWorkflowContext(workflow, { persistent: winner.persistent, @@ -1332,7 +1418,7 @@ async function main() { if (vendor === "antigravity" && !prompt) { const invocationNum = input.invocationNum; if (typeof invocationNum === "number" && invocationNum > 1) process.exit(0); - prompt = readAgyPrompt(input.transcriptPath); + prompt = readAgyPrompt(input.transcriptPath, input.lastUserInput); } // Build canonical inputs and delegate to run() — single logic source. diff --git a/.agents/hooks/core/open-subagents.ts b/.agents/hooks/core/open-subagents.ts new file mode 100644 index 00000000..f595dd59 --- /dev/null +++ b/.agents/hooks/core/open-subagents.ts @@ -0,0 +1,94 @@ +// Subagents a host session has started and not yet stopped. +// +// The host reports SubagentStart and SubagentStop to `oma hook run`. Each open +// subagent is one file, so parallel starts and stops need no lock. The record +// is kept outside the session event log because a host session can run +// subagents without an active OMA workflow session. + +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; + +const OPEN_SUBAGENTS_RELDIR = join(".agents", "state", "open-subagents"); + +/** A start without a stop is dropped after this long (host crash, lost event). */ +export const OPEN_SUBAGENT_MAX_AGE_MS = 2 * 60 * 60 * 1000; + +/** Claude Code's built-in agents that have no edit tools. */ +const NON_EDITING_AGENT_TYPES = new Set(["Explore", "Plan"]); + +export interface OpenSubagent { + agentId: string; + agentType: string; + /** Host session that started the subagent, when the host reported one. */ + vendorSid?: string; + startedAt: string; +} + +function recordPath(projectDir: string, agentId: string): string { + const name = agentId.replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 120); + return join(projectDir, OPEN_SUBAGENTS_RELDIR, `${name || "_"}.json`); +} + +export function recordSubagentStart( + projectDir: string, + subagent: Omit, + now: Date = new Date(), +): void { + // Never seed `.agents/` in a directory that is not an OMA project: a stray + // one would be resolved as a project root by later commands. + if (!existsSync(join(projectDir, ".agents"))) return; + mkdirSync(join(projectDir, OPEN_SUBAGENTS_RELDIR), { recursive: true }); + const record: OpenSubagent = { ...subagent, startedAt: now.toISOString() }; + writeFileSync( + recordPath(projectDir, subagent.agentId), + `${JSON.stringify(record)}\n`, + { mode: 0o600 }, + ); +} + +export function recordSubagentStop(projectDir: string, agentId: string): void { + rmSync(recordPath(projectDir, agentId), { force: true }); +} + +/** + * Open subagents that can edit the working tree. Records of another host + * session are skipped when both session ids are known; expired and unreadable + * records are removed. + */ +export function listOpenSubagents( + projectDir: string, + vendorSid?: string, + nowMs: number = Date.now(), +): OpenSubagent[] { + const dir = join(projectDir, OPEN_SUBAGENTS_RELDIR); + if (!existsSync(dir)) return []; + const open: OpenSubagent[] = []; + for (const entry of readdirSync(dir)) { + if (!entry.endsWith(".json")) continue; + const path = join(dir, entry); + let record: OpenSubagent; + try { + record = JSON.parse(readFileSync(path, "utf-8")) as OpenSubagent; + } catch { + rmSync(path, { force: true }); + continue; + } + const age = nowMs - Date.parse(record.startedAt); + if (!(age < OPEN_SUBAGENT_MAX_AGE_MS)) { + rmSync(path, { force: true }); + continue; + } + if (vendorSid && record.vendorSid && record.vendorSid !== vendorSid) + continue; + if (NON_EDITING_AGENT_TYPES.has(record.agentType)) continue; + open.push(record); + } + return open; +} diff --git a/.agents/hooks/core/persistent-mode.ts b/.agents/hooks/core/persistent-mode.ts index 84182e7e..a47cb384 100644 --- a/.agents/hooks/core/persistent-mode.ts +++ b/.agents/hooks/core/persistent-mode.ts @@ -23,10 +23,22 @@ import { writeFileSync, } from "node:fs"; import { join } from "node:path"; -import { agyConversationId } from "./agy-input.ts"; +import { + agyConversationId, + isAgyNonBlockingStopReason, + readAgyResponse, +} from "./agy-input.ts"; +import { + captureCodeFingerprint, + sameCodeFingerprint, +} from "./code-fingerprint.ts"; import { UNKNOWN_SESSION_ID } from "./constants.ts"; import { makeBlockOutput } from "./hook-output.ts"; -import { isDeactivationRequest } from "./keyword-detector.ts"; +import { + DEACTIVATION_PHRASES, + normalizeForMatching, + stripSystemEchoes, +} from "./keyword-detector.ts"; // triggers.json is imported statically: bundler inlines it into the oma binary; // standalone bun runs resolve the sibling file (pi / direct run). import embeddedTriggers from "./triggers.json" with { type: "json" }; @@ -184,10 +196,19 @@ function killGateTree(pid: number | undefined, leaderAlive: boolean): void { } /** - * Run a resolved gate argv with a hard timeout. No shell involved. Async so - * the dispatcher's per-handler timeout can still preempt it; on timeout, or - * when this hook process is itself signalled (vendor kill, Ctrl-C), the whole - * gate process tree is killed — no orphaned test runners. + * Run a resolved gate argv with a hard timeout. Async so the dispatcher's + * per-handler timeout can still preempt it; on timeout, or when this hook + * process is itself signalled (vendor kill, Ctrl-C), the whole gate process + * tree is killed — no orphaned test runners. + * + * POSIX: no shell — the argv is executed directly. win32: npm/pnpm/yarn + * resolve to `.cmd` shims, which Node >= 18.20 refuses to spawn without a + * shell (EINVAL/ENOENT), so those runners go through the system shell. + * Injection-safe HERE because the argv is fully allowlisted by + * resolveGateArgv: `command` ∈ {bun, npm, pnpm, yarn} and the only other + * token is `gateKeyword` ∈ {typecheck, test, lint}. No agent-writable string + * ever reaches this spawn. `bun` is a real `.exe` and stays shell-less; + * taskkill /T still reaps the shell's whole child tree on timeout. */ export function runGateCommand( argv: string[], @@ -244,6 +265,8 @@ export function runGateCommand( detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], windowsHide: true, + // .cmd shims (npm/pnpm/yarn) need a shell on win32; argv is allowlisted. + shell: process.platform === "win32" && command !== "bun", }); } catch (error) { spawnError = error instanceof Error ? error.message : String(error); @@ -310,7 +333,11 @@ async function emitGateEvent( const { emitEvent } = await import("./state-emit.ts"); await emitEvent(projectDir, state.omaSid, { kind, - payload: { workflow: state.workflow, ...payload }, + payload: { + workflow: state.workflow, + ...("head" in payload ? {} : await captureCodeFingerprint(projectDir)), + ...payload, + }, }); } catch { // best-effort — never let event I/O change the stop decision @@ -499,6 +526,33 @@ export function deactivateAllForSession( } } +/** + * H4 guard: true ONLY when `text` is a deactivation phrase standing alone — + * never a substring of a longer narration. + * + * The plain substring matcher (keyword-detector's isDeactivationRequest) is + * correct for a genuine USER prompt but catastrophic for assistant/response/ + * transcript text: "the workflow completed successfully" contains "workflow + * complete", and the hook's OWN block reason contains `say "workflow done"`, + * which vendors that echo prior messages would feed back into the next Stop. + * + * This matcher (1) strips oma's system-echo lines, then (2) requires the whole + * remaining text — modulo surrounding quotes/whitespace and trailing sentence + * punctuation — to EQUAL a phrase. Embedded narration therefore never matches. + */ +export function isStandaloneDeactivation(text: string): boolean { + const cleaned = normalizeForMatching(stripSystemEchoes(text)).trim(); + if (!cleaned) return false; + const core = cleaned + .replace(/^[\s"'“”‘’]+/, "") + .replace(/[\s"'“”‘’.!?。!?]+$/, "") + .trim(); + if (!core) return false; + return Object.values(DEACTIVATION_PHRASES) + .flat() + .some((phrase) => normalizeForMatching(phrase) === core); +} + /** activatedAt of a state file, falling back to its mtime when unreadable. */ function stateTimestampMs(path: string): number { try { @@ -580,7 +634,15 @@ function incrementReinforcement( * the stop should be blocked, or `null` when no workflow is active / all are * stale/exhausted. * - * Both canonical and standalone callers pass response text to this handler. + * Deactivation (H4): a genuine user "workflow done" arrives through the PROMPT + * hook (keyword-detector's run() → deactivateAllPersistentModes), which deletes + * the state file BEFORE Stop fires. Assistant/response/transcript text must + * NEVER deactivate — narration like "the workflow completed successfully" and + * the hook's own echoed block reason both contain the phrases. The sole vendor + * with no prompt-submit event is commandcode (commandcode.json registers only + * SessionStart/PostToolUse/Stop), so it alone keeps a guarded fallback: the + * response text must be a STANDALONE phrase after system echoes are stripped + * (isStandaloneDeactivation). Every other vendor ignores `responseText`. * * `ctx.cwd` must be the resolved git-root project directory; * `ctx.sid` is the vendor session id. @@ -611,25 +673,27 @@ export async function run( return null; } - // Honor "workflow done" deactivation carried in the stop payload's response - // text (parity with the standalone main() path). Without this, persistent - // mode could not be deactivated via the central `oma hook run` dispatch. - if (input.responseText) { - if (isDeactivationRequest(input.responseText)) { - const endings = loadPersistentWorkflows() - .map((workflow) => readModeState(projectDir, workflow, sessionId)) - .filter((state): state is ModeState => state !== null) - .map( - (state): SessionEnding => ({ - state, - status: "completed", - reason: "workflow_done", - }), - ); - deactivateAllForSession(projectDir, sessionId); - await finishPersistentSessions(projectDir, sessionId, endings); - return null; - } + // H4: a deactivation phrase may arrive in the stop payload's response text + // (standalone pi/antigravity stdin, or vendors without a prompt-submit + // event). It deactivates ONLY as a STANDALONE phrase after oma's system + // echoes are stripped (isStandaloneDeactivation): assistant narration like + // "the workflow completed successfully" is a substring and never matches, + // and the hook's own block reason (which contains "workflow done") is + // removed by stripSystemEchoes before matching. + if (input.responseText && isStandaloneDeactivation(input.responseText)) { + const endings = loadPersistentWorkflows() + .map((workflow) => readModeState(projectDir, workflow, sessionId)) + .filter((state): state is ModeState => state !== null) + .map( + (state): SessionEnding => ({ + state, + status: "completed", + reason: "workflow_done", + }), + ); + deactivateAllForSession(projectDir, sessionId); + await finishPersistentSessions(projectDir, sessionId, endings); + return null; } const persistentWorkflows = loadPersistentWorkflows(); @@ -692,6 +756,7 @@ export async function run( if (gateKeyword) { const argv = resolveGateArgv(gateKeyword, projectDir); if (argv) { + const fingerprint = await captureCodeFingerprint(projectDir); const budgetMs = Math.max(1, gateDeadline - Date.now()); if (gateRanThisStop && budgetMs < MIN_GATE_RUN_MS) { // An earlier workflow's gate spent this Stop's budget. That gate's @@ -710,10 +775,15 @@ export async function run( } gateRanThisStop = true; const gate = await runGateCommand(argv, projectDir, budgetMs); - if (gate.passed) { + const codeChanged = !sameCodeFingerprint( + fingerprint, + await captureCodeFingerprint(projectDir), + ); + if (gate.passed && !codeChanged) { // The gate is the mechanical proof of completion: allow the stop. deactivate(projectDir, workflow, sessionId); await emitGateEvent(projectDir, state, "gate.passed", { + ...fingerprint, gate: gateKeyword, summary: `stop gate '${gateKeyword}' passed for /${workflow}`, }); @@ -730,12 +800,21 @@ export async function run( incrementReinforcement(projectDir, workflow, sessionId, state); const budget = formatSeconds(gateBudgetMs); await emitGateEvent(projectDir, state, "gate.failed", { + ...fingerprint, gate: gateKeyword, timedOut: gate.timedOut, ...(gate.timedOut ? { budgetMs } : {}), - summary: gate.timedOut - ? `stop gate '${gateKeyword}' timed out after ${budget} (Stop-hook gate budget) for /${workflow}` - : `stop gate '${gateKeyword}' failed for /${workflow}`, + // event-spec.md: gate.failed payload requires {gate, reason}. + reason: codeChanged + ? "code_changed_during_gate" + : gate.timedOut + ? "gate_timeout" + : "gate_failed", + summary: codeChanged + ? "code changed during gate" + : gate.timedOut + ? `stop gate '${gateKeyword}' timed out after ${budget} (Stop-hook gate budget) for /${workflow}` + : `stop gate '${gateKeyword}' failed for /${workflow}`, }); const quicker = ["lint", "typecheck"] .filter((keyword) => keyword !== gateKeyword) @@ -745,10 +824,14 @@ export async function run( `[OMA PERSISTENT MODE: ${workflow.toUpperCase()}]`, gate.timedOut ? `Stop gate '${gateKeyword}' timed out after ${budget} — the Stop-hook gate budget — and its process tree was stopped (reinforcement ${state.reinforcementCount}/${MAX_REINFORCEMENTS}).` - : `Stop gate '${gateKeyword}' FAILED (reinforcement ${state.reinforcementCount}/${MAX_REINFORCEMENTS}).`, + : codeChanged + ? `Stop gate '${gateKeyword}' FAILED: code changed during gate (reinforcement ${state.reinforcementCount}/${MAX_REINFORCEMENTS}).` + : `Stop gate '${gateKeyword}' FAILED (reinforcement ${state.reinforcementCount}/${MAX_REINFORCEMENTS}).`, gate.timedOut ? `A gate runs inside the Stop hook and must finish within ${budget}: make the \`${gateKeyword}\` script faster (e.g. only the affected tests), or switch to a quicker gate with ${quicker}.` - : `Fix the failures below, then finish the workflow — the stop is allowed only when the gate passes.`, + : codeChanged + ? "Run the gate again after code changes are finished." + : `Fix the failures below, then finish the workflow — the stop is allowed only when the gate passes.`, gate.outputTail ? `--- gate output (tail) ---\n${gate.outputTail}` : "", @@ -768,7 +851,8 @@ export async function run( `[OMA PERSISTENT MODE: ${workflow.toUpperCase()}]`, `The /${workflow} workflow is still active (reinforcement ${state.reinforcementCount}/${MAX_REINFORCEMENTS}).`, `Continue executing the workflow. If all tasks are genuinely complete:`, - ` 1. Delete the state file: Bash \`rm ${stateFile}\``, + ` 1. Delete the state file: ${stateFile}`, + ` 2. Or ask the user to say "워크플로우 완료" / "workflow done"`, ignoredGateNote, ] .filter(Boolean) @@ -794,20 +878,26 @@ async function main() { } const vendor = detectVendorFromInput(input, "stop", import.meta.filename); + if (vendor === "antigravity" && isAgyNonBlockingStopReason(input)) { + process.exit(0); + } const projectDir = getProjectDir(vendor, input); const sessionId = getSessionId(input); - // Check all text fields in stdin for deactivation phrases. - // The assistant may have included "workflow done" in its response, - // or it may appear in transcript/content fields depending on vendor. - // This raw-stdin check is standalone-path-only; the canonical HookInput - // { kind: "stop" } does not carry these text fields. + // Collect response/transcript text for the canonical handler. run() applies + // the H4 guard: only commandcode (no prompt-submit event) may deactivate from + // a STANDALONE phrase; for pi/antigravity (this standalone path) the text is + // assistant narration and is ignored — the genuine user prompt path already + // deleted the state on a real "workflow done". const textToCheck = [ input.prompt_response, input.response, input.content, input.message, input.transcript, + vendor === "antigravity" + ? readAgyResponse(input.transcriptPath) + : undefined, ] .filter((v): v is string => typeof v === "string") .join(" "); diff --git a/.agents/hooks/core/refactor-guard.ts b/.agents/hooks/core/refactor-guard.ts index 76bfa159..e72fbe94 100644 --- a/.agents/hooks/core/refactor-guard.ts +++ b/.agents/hooks/core/refactor-guard.ts @@ -35,7 +35,12 @@ import { spawn } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import { isAbsolute, join, relative, resolve } from "node:path"; -import { agyConversationId, agyProjectDir, isAgyInput } from "./agy-input.ts"; +import { + agyConversationId, + agyProjectDir, + isAgyInput, + isAgyNonBlockingStopReason, +} from "./agy-input.ts"; import { toPosixPath } from "./fs-utils.ts"; import { makeBlockOutput } from "./hook-output.ts"; import { atomicWriteJson } from "./state-marker.ts"; @@ -90,7 +95,9 @@ const EDIT_TOOLS = new Set([ "hashline_edit", // grok (args.path) "create_file", // grok "str_replace", // grok + "search_replace", // grok standard toolset (Edit/Write alias target) "fs_write", // kiro + "fs_append", // kiro V3 ]); /** Extensions the guard treats as refactorable source code. */ @@ -301,8 +308,9 @@ export function resolveEditedPaths( toolInput.filePath ?? toolInput.notebook_path ?? toolInput.path ?? - // antigravity tool args use PascalCase (write_to_file / - // replace_file_content carry TargetFile — verified from the agy binary). + // antigravity tool args use PascalCase (`write_file` / `edit_file` carry + // `Path`; Cortex `write_to_file` / `replace_file_content` carry `TargetFile`). + toolInput.Path ?? toolInput.TargetFile; return typeof cand === "string" && cand.length > 0 ? [cand] : []; } @@ -551,6 +559,9 @@ function main() { agyProjectDir(parsed) || ((parsed.cwd as string | undefined) ?? ""); const sid = agyConversationId(parsed) ?? undefined; const isPostTool = typeof toolCall?.name === "string"; + if (!isPostTool && isAgyNonBlockingStopReason(parsed)) { + process.exit(0); + } const hookInput: HookInput = isPostTool ? { kind: "post_tool", diff --git a/.agents/hooks/core/scm-guard.ts b/.agents/hooks/core/scm-guard.ts index 4a767a25..486c6cd2 100644 --- a/.agents/hooks/core/scm-guard.ts +++ b/.agents/hooks/core/scm-guard.ts @@ -1,18 +1,23 @@ -// PreToolUse hook — Block staging of likely-secret files (oma-scm enforcement). -// Enforces `forbidden_patterns` from oma-scm's commit-config.yaml mechanically: +// PreToolUse hook — Block staging of likely-secret files (oma-scm enforcement), +// and `git commit` while a subagent of the session is still running. +// Enforces `scm.forbidden_patterns` from oma-config (legacy oma-scm +// commit-config.yaml is still read as a fallback) mechanically: // before this hook the pattern list was advisory-only (model compliance). // Works with: Claude Code, Codex CLI, Cursor, Grok, Kimi, Kiro, Qwen Code. // // Scope decisions: -// - Only `git add` segments are guarded. Untracked secrets must pass through +// - For secrets, only `git add` segments are guarded. Untracked secrets must pass through // `git add` to ever reach a commit (`git commit ` / `-a` only touch // already-tracked files), so staging is the single choke point. // - Broad staging (`git add -A` / `git add .`) is NOT blocked here: the rule // ("never without explicit permission") depends on user consent the hook // cannot observe. It stays an agent-level guardrail. -// - Escape hatch: a command containing `OMA_SCM_ALLOW_SECRETS=1` bypasses the -// guard, mirroring SKILL.md Guardrail 0 (explicit user override — surface -// once, then proceed). +// - Escape hatch: `OMA_SCM_ALLOW_SECRETS=1` as an env-assignment prefix of the +// very `git add` segment being guarded (e.g. +// `OMA_SCM_ALLOW_SECRETS=1 git add file`) bypasses the guard for THAT +// segment only, mirroring SKILL.md Guardrail 0 (explicit user override — +// surface once, then proceed). The token elsewhere (another segment, an +// echo/comment, or a pathspec argument) never disables scanning. import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -24,7 +29,7 @@ import type { HookInput, Vendor, } from "./types.ts"; -import { getProjectDir } from "./vendor-detect.ts"; +import { detectVendorFromInput, getProjectDir } from "./vendor-detect.ts"; // --- Defaults (mirror .agents/skills/oma-scm/config/commit-config.yaml) --- // Used when the config file is absent (global installs without project config, @@ -159,7 +164,10 @@ function globToRegExp(pattern: string): RegExp { } function basename(path: string): string { - const trimmed = path.replace(/\/+$/, ""); + // Windows pathspecs use `\` separators; normalize so basename-exact + // patterns (credentials.json, .npmrc, …) match `config\credentials.json`. + const normalized = path.replace(/\\/g, "/"); + const trimmed = normalized.replace(/\/+$/, ""); const idx = trimmed.lastIndexOf("/"); return idx === -1 ? trimmed : trimmed.slice(idx + 1); } @@ -173,36 +181,114 @@ export function matchesForbidden(path: string, config: GuardConfig): boolean { // --- Command parsing --- +const SEGMENT_SPLIT_RE = /&&|\|\||;|\||\n/; +const GIT_ADD_RE = /\bgit\s+(?:[-\w]+=\S+\s+)*add\b(.*)$/; +// Bypass is granted only when the segment STARTS with an env-assignment chain +// containing the token, immediately followed by the `git … add` invocation. +// A token in an argument position (`echo OMA_SCM_ALLOW_SECRETS=1 git add …`), +// in another segment, or after the paths does not match this anchor. +const BYPASS_PREFIX_RE = new RegExp( + `^(?:[-\\w]+=\\S+\\s+)*${BYPASS_TOKEN}\\s+(?:[-\\w]+=\\S+\\s+)*git\\s+(?:[-\\w]+=\\S+\\s+)*add\\b`, +); + +export interface GitAddSegment { + paths: string[]; + /** True only when the bypass token env-prefixes this very `git add`. */ + bypassed: boolean; +} + /** - * Extract candidate pathspec tokens from every `git add` segment of a shell - * command. Naive quoting-aware-ish tokenizer: segments split on shell control - * operators; option tokens (`-…`) and the `--` separator are skipped. + * Parse every `git add` segment of a shell command. Naive quoting-aware-ish + * tokenizer: segments split on shell control operators; option tokens (`-…`) + * and the `--` separator are skipped. Each segment reports whether the bypass + * token is an env-assignment prefix of that segment's own `git add`. */ -export function extractGitAddPaths(command: string): string[] { - const paths: string[] = []; - const segments = command.split(/&&|\|\||;|\||\n/); - for (const segment of segments) { - const m = segment.match(/\bgit\s+(?:[-\w]+=\S+\s+)*add\b(.*)$/); +export function extractGitAddSegments(command: string): GitAddSegment[] { + const result: GitAddSegment[] = []; + for (const segment of command.split(SEGMENT_SPLIT_RE)) { + const m = segment.match(GIT_ADD_RE); if (!m) continue; const rest = m[1] ?? ""; // Tokenize, honoring simple single/double quotes. const tokens = rest.match(/"[^"]*"|'[^']*'|\S+/g) ?? []; + const paths: string[] = []; for (const raw of tokens) { const token = raw.replace(/^["']|["']$/g, ""); if (token === "--") continue; if (token.startsWith("-")) continue; // options (incl. -A/--all; see header) paths.push(token); } + result.push({ paths, bypassed: BYPASS_PREFIX_RE.test(segment.trim()) }); + } + return result; +} + +/** + * Extract candidate pathspec tokens from every `git add` segment of a shell + * command (including bypassed segments; callers decide what to scan). + */ +export function extractGitAddPaths(command: string): string[] { + return extractGitAddSegments(command).flatMap((segment) => segment.paths); +} + +// --- Commit while subagents run --- +// +// A pre-commit hook that stashes unstaged changes (hk, lint-staged, pre-commit) +// rewrites the working tree for the length of the commit. A subagent writing to +// the same tree in that window loses its edits when the stash is restored. The +// host's SubagentStart/SubagentStop events are recorded by open-subagents.ts +// (Claude Code, Codex, Copilot), so a commit made while one is open is refused. + +const BUSY_BYPASS_TOKEN = "OMA_SCM_ALLOW_BUSY=1"; +// Anchored at the segment start so `git log --grep commit` is not a commit. +const GIT_COMMIT_RE = + /^(?:[-\w]+=\S+\s+)*git\s+(?:(?:-[cC]\s+\S+|--?[\w-]+(?:=\S+)?)\s+)*commit(?:\s|$)/; +const BUSY_BYPASS_PREFIX_RE = new RegExp( + `^(?:[-\\w]+=\\S+\\s+)*${BUSY_BYPASS_TOKEN}\\s`, +); +/** True when a segment of the command runs `git commit` without the bypass. */ +export function hasGuardedGitCommit(command: string): boolean { + return command.split(SEGMENT_SPLIT_RE).some((raw) => { + const segment = raw.trim().replace(/^[({\s]+/, ""); + return GIT_COMMIT_RE.test(segment) && !BUSY_BYPASS_PREFIX_RE.test(segment); + }); +} + +async function blockCommitWhileSubagentsRun( + command: string, + projectDir: string, + vendorSid: string | undefined, +): Promise { + if (!hasGuardedGitCommit(command)) return null; + try { + // Loaded on demand: only a commit needs the open-subagent records. + const { listOpenSubagents } = await import("./open-subagents.ts"); + const open = listOpenSubagents(projectDir, vendorSid).map( + (subagent) => subagent.agentType, + ); + if (open.length === 0) return null; + return { + type: "block", + reason: + `[oma scm-guard] Blocked: ${open.length} subagent(s) are still running in this working tree (${open.join(", ")}). ` + + `A pre-commit hook that stashes unstaged changes can discard the edits they are writing. ` + + `Wait for them to finish or stop them, then commit. ` + + `If the user confirms they are not editing this tree, ` + + `re-run the commit segment prefixed with ${BUSY_BYPASS_TOKEN}.`, + }; + } catch { + return null; // fail-open: unreadable records never block a commit } - return paths; } // ── Pure handler (canonical ABI) ───────────────────────────── /** - * Pure decision function — blocks `git add` of likely-secret files. + * Pure decision function — blocks `git add` of likely-secret files, and + * `git commit` while a subagent of this session is still running. * Returns a `block` HandlerResult when a staged path matches - * `forbidden_patterns` (minus `allowed_exceptions`), else `null` (fail-open). + * `forbidden_patterns` (minus `allowed_exceptions`) or a subagent is open, + * else `null` (fail-open). */ export async function run( input: HookInput, @@ -218,16 +304,25 @@ export async function run( toolName !== "Bash" && toolName !== "run_shell_command" && toolName !== "Shell" && - toolName !== "execute_bash" + toolName !== "execute_bash" && + toolName !== "run_command" ) return null; - const command = toolInput.command as string | undefined; + const command = (toolInput.command ?? toolInput.CommandLine) as + | string + | undefined; if (!command) return null; if (!/\bgit\b/.test(command)) return null; - if (command.includes(BYPASS_TOKEN)) return null; - const candidates = extractGitAddPaths(command); + const busy = await blockCommitWhileSubagentsRun(command, projectDir, ctx.sid); + if (busy) return busy; + + // The bypass applies per segment: only the `git add` env-prefixed by the + // token is exempt; every other segment is still scanned. + const candidates = extractGitAddSegments(command) + .filter((segment) => !segment.bypassed) + .flatMap((segment) => segment.paths); if (candidates.length === 0) return null; const config = loadGuardConfig(projectDir, ctx.config); @@ -240,7 +335,8 @@ export async function run( `[oma scm-guard] Blocked: staging likely-secret file(s): ${flagged.join(", ")} ` + `(matched forbidden_patterns in ${MAIN_CONFIG_RELPATH}). ` + `Surface this to the user; if they explicitly approve committing these files, ` + - `re-run the command prefixed with ${BYPASS_TOKEN}.`, + `re-run the git add segment prefixed with ${BYPASS_TOKEN} ` + + `(the bypass applies only to that segment).`, }; } @@ -263,14 +359,26 @@ function main() { if (!raw.trim()) process.exit(0); const parsed: PreToolUseInput = JSON.parse(raw); - // Standalone path is vendor-agnostic here; claude covers the common dialect. - const vendor: Vendor = "claude"; + const vendor: Vendor = detectVendorFromInput( + parsed, + "tool", + import.meta.filename, + ); const projectDir = getProjectDir(vendor, parsed); + const toolCall = parsed.toolCall as + | { name?: string; args?: Record } + | undefined; + const toolName = + parsed.tool_name || + (typeof toolCall?.name === "string" ? toolCall.name : ""); + const rawInput = + parsed.tool_input ?? + (toolCall?.args && typeof toolCall.args === "object" ? toolCall.args : {}); const hookInput: HookInput = { kind: "pre_tool", - toolName: parsed.tool_name, - toolInput: { ...(parsed.tool_input ?? {}) }, + toolName, + toolInput: { ...rawInput }, cwd: projectDir, }; diff --git a/.agents/hooks/core/skill-injector.ts b/.agents/hooks/core/skill-injector.ts index 42b4982f..79fe33df 100644 --- a/.agents/hooks/core/skill-injector.ts +++ b/.agents/hooks/core/skill-injector.ts @@ -20,11 +20,17 @@ import { readFileSync, writeFileSync, } from "node:fs"; -import { basename, dirname, join } from "node:path"; +import { basename, dirname, join, resolve } from "node:path"; import { agyConversationId, readAgyPrompt } from "./agy-input.ts"; import { toPosixPath } from "./fs-utils.ts"; import { makePromptOutput } from "./hook-output.ts"; +import { omaHome } from "./oma-home.ts"; import { isRelayedAgentMessage, normalizePromptInput } from "./prompt-input.ts"; +import { + explicitSkillMentions, + knownSkillNames, + recordSkillRoutes, +} from "./skill-route.ts"; // triggers.json is imported statically: bundler inlines it into the oma binary; // standalone bun runs resolve the sibling file (pi / direct run). import embeddedTriggers from "./triggers.json" with { type: "json" }; @@ -87,8 +93,16 @@ export interface SkillEntry { relPath: string; } -export function discoverSkills(projectDir: string): SkillEntry[] { - const skillsDir = join(projectDir, ".agents", "skills"); +function defaultGlobalRoot(): string | null { + try { + return omaHome(); + } catch { + return null; + } +} + +function skillsUnder(root: string, project: boolean): SkillEntry[] { + const skillsDir = join(root, ".agents", "skills"); if (!existsSync(skillsDir)) return []; const out: SkillEntry[] = []; @@ -103,7 +117,7 @@ export function discoverSkills(projectDir: string): SkillEntry[] { } for (const entry of entries) { - if (!entry.isDirectory()) continue; + if (!entry.isDirectory() && !entry.isSymbolicLink?.()) continue; if (entry.name.startsWith("_")) continue; const skillPath = join(skillsDir, entry.name, "SKILL.md"); @@ -112,12 +126,37 @@ export function discoverSkills(projectDir: string): SkillEntry[] { out.push({ name: entry.name, absolutePath: skillPath, - relPath: join(".agents", "skills", entry.name, "SKILL.md"), + // A global install's skills live outside the project, so the model is + // pointed at the absolute path instead of a project-relative one. + relPath: project + ? join(".agents", "skills", entry.name, "SKILL.md") + : skillPath, }); } return out; } +/** + * Skills under the project's `.agents/skills/`, plus — for a global install + * (`oma install --global`) — `/.agents/skills/`. A project skill + * shadows a global one of the same name. + */ +export function discoverSkills( + projectDir: string, + globalRoot: string | null = defaultGlobalRoot(), +): SkillEntry[] { + const out = skillsUnder(projectDir, true); + if (!globalRoot || resolve(globalRoot) === resolve(projectDir)) return out; + const seen = new Set(out.map((skill) => skill.name)); + for (const skill of skillsUnder(globalRoot, false)) { + if (!seen.has(skill.name)) { + seen.add(skill.name); + out.push(skill); + } + } + return out; +} + // ── Matching ────────────────────────────────────────────────── export interface SkillMatch { @@ -455,6 +494,23 @@ export async function run( // and produced false skill suggestions. Same guard as keyword-detector. if (isRelayedAgentMessage(prompt)) return null; + // Routing telemetry: a skill the user named (`/name`, `$name`) is routed by + // explicit request. Recorded before every early exit below; never blocks. + if (/[/$]/.test(prompt)) { + const explicit = explicitSkillMentions( + stripCodeBlocks(prompt), + knownSkillNames(projectDir), + ); + await recordSkillRoutes( + { projectDir, vendor: ctx.host ?? vendor, vendorSid: sessionId }, + explicit.map((skill) => ({ + skill, + source: "user-explicit" as const, + stage: "loaded" as const, + })), + ); + } + // Claude-specific: slash-skill resolution must run BEFORE the slash early-exit // and persistent-workflow guard (same order as the original standalone path). if (vendor === "claude") { @@ -487,6 +543,18 @@ export async function run( if (fresh.length === 0) return null; writeState(projectDir, nextState); + // Routing telemetry: why each skill was suggested (matched trigger + // keywords only — never the prompt text). + await recordSkillRoutes( + { projectDir, vendor: ctx.host ?? vendor, vendorSid: sessionId }, + fresh.map((match) => ({ + skill: match.name, + source: "hook-trigger" as const, + stage: "suggested" as const, + matchedTriggers: match.matchedTriggers, + score: match.score, + })), + ); return { type: "context", additionalContext: formatContext(fresh) }; } @@ -511,7 +579,7 @@ async function main() { if (vendor === "antigravity" && !prompt) { const invocationNum = input.invocationNum; if (typeof invocationNum === "number" && invocationNum > 1) process.exit(0); - prompt = readAgyPrompt(input.transcriptPath); + prompt = readAgyPrompt(input.transcriptPath, input.lastUserInput); } // Build canonical inputs and delegate to run() — single logic source. diff --git a/.agents/hooks/core/skill-route.ts b/.agents/hooks/core/skill-route.ts new file mode 100644 index 00000000..8e8776ea --- /dev/null +++ b/.agents/hooks/core/skill-route.ts @@ -0,0 +1,691 @@ +#!/usr/bin/env bun +/** + * oh-my-agent — Skill Route Recorder + * + * Records which OMA skill was routed in a vendor session and WHY, as + * `skill.routed` L1 events: + * + * source "user-explicit" — the user named the skill (`/` or + * `$`) in the prompt (skill-injector). + * source "hook-trigger" — a triggers.json keyword matched the prompt. + * Recorded as stage "suggested" by skill-injector, + * and again as stage "loaded" when the model + * actually loads the suggested skill. + * source "model-description" — the model loaded a skill the hook never + * suggested, i.e. it routed from the skill + * description in its own catalog. + * + * The post_tool handler detects a skill load from the vendor tool call: the + * Claude `Skill` tool, or any tool input (Read path, shell command) naming + * `skills//SKILL.md`. Only skills present in `.agents/skills/` count. + * + * Events go to the L1 session that owns this work: the active main workflow + * session when it belongs to this vendor session or has recent non-boundary + * activity, otherwise a per-vendor-session `skill-routing` session (category + * `routing`). Prompt text is never recorded — only matched trigger keywords. + * + * Never blocks and never injects context; every failure is swallowed. + */ + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { agyConversationId, agyProjectDir } from "./agy-input.ts"; +import { omaHome } from "./oma-home.ts"; +import { emitEvent as appendStateEvent } from "./state-core.ts"; +import { + createSessionId, + emitEvent, + type OmaEvent, + readEvents, + vendorHomePayload, +} from "./state-emit.ts"; +import { + atomicWriteJson, + claimActiveSession, + readIndex, +} from "./state-marker.ts"; +import type { HandlerCtx, HandlerResult, HookInput, Vendor } from "./types.ts"; +import { detectVendorFromInput, getProjectDir } from "./vendor-detect.ts"; + +export type SkillRouteSource = + | "user-explicit" + | "hook-trigger" + | "model-description"; + +export type SkillRouteStage = "suggested" | "loaded"; + +export interface SkillRoute { + skill: string; + source: SkillRouteSource; + stage: SkillRouteStage; + /** Trigger keywords that matched (hook-trigger only). Never prompt text. */ + matchedTriggers?: string[]; + score?: number; + /** Tool that loaded the skill (stage "loaded" via post_tool). */ + via?: string; +} + +export const ROUTING_WORKFLOW = "skill-routing"; +export const ROUTING_CATEGORY = "routing"; + +/** Mirrors keyword-detector's L1 liveness window (persistent-mode STALE_HOURS). */ +export const ROUTE_LIVE_TTL_MS = 2 * 60 * 60 * 1000; + +/** Per-vendor-session route memory survives a long working session. */ +const ROUTE_STATE_TTL_MS = 12 * 60 * 60 * 1000; + +// ── Per-vendor-session state ───────────────────────────────── + +interface RouteSessionState { + routeSid?: string; + suggested: string[]; + loaded: string[]; + timestamp: number; +} + +interface RouteState { + sessions: Record; +} + +export function routeStatePath(projectDir: string): string { + return join(projectDir, ".agents", "state", "skill-routes.json"); +} + +function readRouteState(projectDir: string): RouteState { + const path = routeStatePath(projectDir); + if (!existsSync(path)) return { sessions: {} }; + try { + const parsed = JSON.parse(readFileSync(path, "utf-8")) as RouteState; + if (parsed && typeof parsed.sessions === "object" && parsed.sessions) { + return parsed; + } + } catch { + // corrupted — reset + } + return { sessions: {} }; +} + +function writeRouteState(projectDir: string, state: RouteState): void { + try { + atomicWriteJson(routeStatePath(projectDir), state); + } catch { + // Route memory failing open only weakens dedup and source attribution. + } +} + +/** Drop expired entries; returns the routing sessions they owned. */ +function pruneRouteState(state: RouteState, now: number): string[] { + const expired: string[] = []; + for (const [id, entry] of Object.entries(state.sessions)) { + if (!entry || now - entry.timestamp > ROUTE_STATE_TTL_MS) { + if (entry?.routeSid) expired.push(entry.routeSid); + delete state.sessions[id]; + } + } + return expired; +} + +// ── Session resolution ─────────────────────────────────────── + +function isEnded(events: OmaEvent[]): boolean { + return events.some((event) => event.kind === "session.ended"); +} + +/** + * Whether a main workflow session should receive routing events. + * + * state-boundary appends a `boundary` event to the active main session on + * every vendor session start, which keeps an abandoned session looking fresh. + * So freshness is judged on non-boundary events only, and a session created + * by this very vendor session is always ours. + */ +export function isMainSessionForRouting( + events: OmaEvent[], + vendorSid: string | undefined, + now: number = Date.now(), +): boolean { + if (events.length === 0 || isEnded(events)) return false; + if (vendorSid && vendorSid !== "unknown") { + const created = events.find((event) => event.kind === "session.created"); + if (created?.vendorSid === vendorSid) return true; + } + for (let i = events.length - 1; i >= 0; i--) { + const event = events[i]; + if (!event || event.kind === "boundary") continue; + const ts = Date.parse(event.ts); + return Number.isFinite(ts) && now - ts < ROUTE_LIVE_TTL_MS; + } + return false; +} + +function isUsableRoutingSession(projectDir: string, sid: string): boolean { + const events = readEvents(projectDir, sid); + return events.length > 0 && !isEnded(events); +} + +/** + * End an idle `skill-routing` session. Nothing else ends these sessions, and + * `oma state archive` skips open ones, so without this they accumulate. + * Recently active and workflow sessions are never touched. Written through + * state-core directly: closing is bookkeeping, not a memory observation. + */ +export function closeRoutingSession( + projectDir: string, + sid: string, + now: number = Date.now(), +): boolean { + try { + const events = readEvents(projectDir, sid); + if (events.length === 0 || isEnded(events)) return false; + // Still receiving events (e.g. CLI emits without a vendor sid): keep open. + if (isMainSessionForRouting(events, undefined, now)) return false; + const created = events.find((event) => event.kind === "session.created"); + if (created?.payload?.workflow !== ROUTING_WORKFLOW) return false; + appendStateEvent(projectDir, sid, { + kind: "session.ended", + payload: { status: "completed", reason: "routing session idle" }, + }); + return true; + } catch { + return false; + } +} + +async function createRoutingSession( + projectDir: string, + vendor: string | undefined, + vendorSid: string | undefined, + now: number, +): Promise { + const sid = createSessionId(); + await emitEvent(projectDir, sid, { + kind: "session.created", + ...(vendor ? { vendor } : {}), + ...(vendorSid ? { vendorSid } : {}), + payload: { + workflow: ROUTING_WORKFLOW, + category: ROUTING_CATEGORY, + ...(vendor ? vendorHomePayload(vendor) : {}), + }, + }); + // Lets `oma state emit --category routing` find it without a vendor sid. + const previous = readIndex(projectDir).active[ROUTING_CATEGORY]; + const claimed = claimActiveSession( + projectDir, + ROUTING_CATEGORY, + sid, + (existing) => + isMainSessionForRouting(readEvents(projectDir, existing), undefined, now), + ); + // The claim only replaces a stale holder; end it so it can be archived. + if (claimed && previous && previous !== sid) { + closeRoutingSession(projectDir, previous, now); + } + return sid; +} + +export interface ResolveRouteSidOptions { + vendor?: string; + vendorSid?: string; + /** Previously created routing session for this vendor session, if known. */ + knownRouteSid?: string; + now?: number; +} + +/** + * Resolve (creating when needed) the L1 session that receives routing events + * and route-selection decisions. Shared by the hooks and + * `oma state emit --category routing`. + */ +export async function resolveRouteSid( + projectDir: string, + options: ResolveRouteSidOptions = {}, +): Promise { + const { vendor, vendorSid, knownRouteSid, now = Date.now() } = options; + const index = readIndex(projectDir); + + const main = index.active.main; + if ( + main && + isMainSessionForRouting(readEvents(projectDir, main), vendorSid, now) + ) { + return main; + } + + if (knownRouteSid && isUsableRoutingSession(projectDir, knownRouteSid)) { + return knownRouteSid; + } + + // Without a vendor session id (CLI emit), reuse the claimed routing slot + // while it is fresh; an abandoned one is replaced, not appended to. + if (!vendorSid || vendorSid === "unknown") { + const routing = index.active[ROUTING_CATEGORY]; + if ( + routing && + isMainSessionForRouting(readEvents(projectDir, routing), undefined, now) + ) { + return routing; + } + } + + return createRoutingSession(projectDir, vendor, vendorSid, now); +} + +// ── Recording ──────────────────────────────────────────────── + +export interface RecordContext { + projectDir: string; + vendor: Vendor | string; + vendorSid?: string; + now?: number; +} + +/** + * Append `skill.routed` events, deduplicated per vendor session and stage. + * A "loaded" model-description record is re-attributed to hook-trigger when + * the hook suggested the skill earlier in this vendor session. + * Returns the records actually written. Never throws. + */ +export async function recordSkillRoutes( + ctx: RecordContext, + routes: SkillRoute[], +): Promise { + if (routes.length === 0) return []; + try { + const now = ctx.now ?? Date.now(); + const key = ctx.vendorSid || "unknown"; + // Without a vendor session id every session would share one entry, so + // dedup and source memory would leak across unrelated sessions. + const tracked = key !== "unknown"; + const state = readRouteState(ctx.projectDir); + for (const expired of pruneRouteState(state, now)) { + closeRoutingSession(ctx.projectDir, expired, now); + } + const entry: RouteSessionState = (tracked && state.sessions[key]) || { + suggested: [], + loaded: [], + timestamp: now, + }; + + const written: SkillRoute[] = []; + for (const route of routes) { + const seen = route.stage === "suggested" ? entry.suggested : entry.loaded; + if (seen.includes(route.skill)) continue; + const resolved: SkillRoute = + route.stage === "loaded" && + route.source === "model-description" && + entry.suggested.includes(route.skill) + ? { ...route, source: "hook-trigger" } + : route; + seen.push(route.skill); + written.push(resolved); + } + if (written.length === 0) return []; + + const sid = await resolveRouteSid(ctx.projectDir, { + vendor: ctx.vendor, + vendorSid: ctx.vendorSid, + knownRouteSid: entry.routeSid, + now, + }); + if (tracked) { + if (sid !== readIndex(ctx.projectDir).active.main) entry.routeSid = sid; + entry.timestamp = now; + state.sessions[key] = entry; + writeRouteState(ctx.projectDir, state); + } + + for (const route of written) { + await emitEvent(ctx.projectDir, sid, { + kind: "skill.routed", + vendor: ctx.vendor, + ...(ctx.vendorSid ? { vendorSid: ctx.vendorSid } : {}), + causalityKey: `skill-route:${route.skill}`, + payload: { ...route }, + }); + } + return written; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`[oma] skill route record failed: ${message}\n`); + return []; + } +} + +// ── Load detection ─────────────────────────────────────────── + +function globalSkillsRoot(): string | null { + try { + return omaHome(); + } catch { + return null; + } +} + +/** + * Skill names that have a SKILL.md under the project's `.agents/skills/` or, + * for a global install (`oma install --global`), under `/.agents/ + * skills/`. Same discovery rule as skill-injector's discoverSkills (kept local + * to avoid an import cycle: skill-injector records its suggestions through + * this module). Symlinked skill directories count. + */ +export function knownSkillNames( + projectDir: string, + globalRoot: string | null = globalSkillsRoot(), +): Set { + const names = new Set(); + const roots = [projectDir, ...(globalRoot ? [globalRoot] : [])]; + for (const root of roots) { + const skillsDir = join(root, ".agents", "skills"); + try { + for (const entry of readdirSync(skillsDir, { withFileTypes: true })) { + if (entry.name.startsWith("_")) continue; + if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; + if (existsSync(join(skillsDir, entry.name, "SKILL.md"))) { + names.add(entry.name); + } + } + } catch { + // No skills directory here — nothing to attribute from this root. + } + } + return names; +} + +/** + * Skills the user named explicitly: `/` (slash invocation) or + * `$` (Codex skill mention), at the start or after whitespace. Only + * names present in `knownSkills` count, so paths and prices do not match. + * Callers strip code blocks first. + */ +export function explicitSkillMentions( + prompt: string, + knownSkills: ReadonlySet, +): string[] { + const found: string[] = []; + for (const match of prompt.matchAll( + /(?:^|\s)[/$]([a-z][a-z0-9_-]{0,40})(?![\w/-])/gi, + )) { + const name = match[1]?.toLowerCase(); + if (name && knownSkills.has(name) && !found.includes(name)) { + found.push(name); + } + } + return found; +} + +const SKILL_FILE_PATTERN = /skills\/([A-Za-z0-9_.-]+)\/SKILL\.md\b/g; + +/** + * Native skill-activation tools (lowercased): Claude / Kimi `Skill`, Qwen / + * Copilot / opencode / Kilo `skill`, Kiro V3 `disclose_context`, Command + * Code `activate_skill`. + */ +const SKILL_TOOLS = new Set(["skill", "disclose_context", "activate_skill"]); + +/** + * Argument keys a skill tool names the skill under (`id`: opencode 2.x + * `skill`). Only values that are known skill names count. + */ +const SKILL_ARG_KEYS = ["skill", "name", "skill_name", "skillName", "id"]; + +/** opencode 2.x `read` can open a skill by URI: `skill://[/]`. */ +const SKILL_URI_PATTERN = /^skill:\/\/([A-Za-z0-9_.-]+)(?:\/(SKILL\.md))?$/; + +/** + * File-read tools across vendors (lowercased). The post_tool settings matcher + * is a union across the whole handler chain, so edit tools reach this handler + * too — writing a doc that mentions a SKILL.md path is not a skill load. + * + * read Claude, Cursor (`file_path`), Kimi (`path`), Copilot + * (`view` → Read, `path` → file_path), pi (`path`), opencode + * 1.x / Kilo (`filePath`), opencode 2.x (`path`, or + * `skill://`) + * read_file Qwen (`file_path`), Grok (`target_file`), Antigravity CLI + * (`Path`), Kiro V3, Command Code (`file_path` / `paths[]`) + * read_multiple_files Command Code (`paths[]`) + * hashline_read Grok hashline toolset + * view_file other Antigravity builds (`AbsolutePath`) + * fs_read Kiro V2 (`operations[].path`) + */ +const READ_TOOLS = new Set([ + "read", + "read_file", + "readfile", + "hashline_read", + "read_multiple_files", + "view", + "view_file", + "fs_read", +]); + +/** Argument keys a file-read tool carries its path under, across vendors. */ +const READ_PATH_KEYS = [ + "file_path", + "filePath", + "path", + "absolute_path", + "target_file", + "Path", + "AbsolutePath", +]; + +/** + * Shell tools across vendors (lowercased): Claude / Kimi / Copilot `Bash`, + * Cursor `Shell` (opencode 2.x `shell`), Qwen `run_shell_command`, Antigravity `run_command`, Codex + * `exec_command`, Grok `run_terminal_command` (internal id + * `run_terminal_cmd`), Kiro `execute_bash`, Command Code `shell_command` + * (`command` plus optional `args[]`). + */ +const SHELL_TOOLS = new Set([ + "bash", + "shell", + "run_shell_command", + "run_command", + "exec_command", + "run_terminal_command", + "run_terminal_cmd", + "execute_bash", + "shell_command", +]); + +/** Argument keys a shell tool carries its command under, across vendors. */ +const SHELL_COMMAND_KEYS = ["command", "cmd", "CommandLine"]; + +/** A shell command only loads a skill when a file reader opens the SKILL.md. */ +const SHELL_READ_PATTERN = + /(?:^|[\s;&|(])(?:cat|sed|head|tail|less|more|bat|nl|awk|type|get-content)\b[^;&|]*skills\/[A-Za-z0-9_.-]+\/SKILL\.md/i; + +function firstKnownSkillPath( + text: string, + knownSkills: ReadonlySet, +): string | null { + for (const match of text.replace(/\\/g, "/").matchAll(SKILL_FILE_PATTERN)) { + const name = match[1]; + if (name && knownSkills.has(name)) return name; + } + return null; +} + +/** String path candidates of a read tool, including Kiro's nested forms. */ +function readPathCandidates(toolInput: Record): string[] { + const paths: string[] = []; + for (const key of READ_PATH_KEYS) { + const value = toolInput[key]; + if (typeof value === "string") paths.push(value); + } + // Kiro: `paths[]` (V3) and `operations[].path` (V2 fs_read). + const list = toolInput.paths; + if (Array.isArray(list)) { + for (const value of list) if (typeof value === "string") paths.push(value); + } + const operations = toolInput.operations; + if (Array.isArray(operations)) { + for (const op of operations) { + if (op && typeof op === "object" && !Array.isArray(op)) { + const value = (op as Record).path; + if (typeof value === "string") paths.push(value); + } + } + } + return paths; +} + +/** + * Identify the OMA skill a tool call loads, or null. A native skill tool + * names the skill directly (optionally plugin-prefixed, `plugin:skill`); + * otherwise a skill is loaded by reading `skills//SKILL.md` through a + * file-read tool or a file-reading shell command. Tool names are compared + * case-insensitively against exact sets, so a broad vendor matcher (Cursor's + * unanchored `Read` also admits `ReadMediaFile`-style names) never counts. + */ +export function detectSkillLoad( + toolName: string, + toolInput: Record, + knownSkills: ReadonlySet, +): string | null { + const tool = toolName.toLowerCase(); + if (SKILL_TOOLS.has(tool)) { + for (const key of SKILL_ARG_KEYS) { + const raw = toolInput[key]; + if (typeof raw !== "string") continue; + const name = raw.trim().replace(/^\//, "").split(":").pop() ?? ""; + if (knownSkills.has(name)) return name; + } + return null; + } + if (READ_TOOLS.has(tool)) { + for (const value of readPathCandidates(toolInput)) { + const uri = SKILL_URI_PATTERN.exec(value.trim()); + if (uri) { + // `skill://` or `skill:///SKILL.md` loads the skill body; + // other files under the skill are resources, not a load. + if (uri[1] && knownSkills.has(uri[1])) return uri[1]; + continue; + } + const name = firstKnownSkillPath(value, knownSkills); + if (name) return name; + } + return null; + } + if (SHELL_TOOLS.has(tool)) { + const extraArgs = Array.isArray(toolInput.args) + ? toolInput.args.filter((part) => typeof part === "string").join(" ") + : ""; + for (const key of SHELL_COMMAND_KEYS) { + const command = toolInput[key]; + const base = Array.isArray(command) + ? command.filter((part) => typeof part === "string").join(" ") + : command; + if (typeof base !== "string") continue; + const text = extraArgs ? `${base} ${extraArgs}` : base; + const normalized = text.replace(/\\/g, "/"); + if (!SHELL_READ_PATTERN.test(normalized)) continue; + const name = firstKnownSkillPath(normalized, knownSkills); + if (name) return name; + } + return null; + } + return null; +} + +// ── Pure handler (canonical ABI) ───────────────────────────── + +/** + * post_tool recorder. Returns null always: routing telemetry must never alter + * the model's context or block a tool. + */ +export async function run( + input: HookInput, + ctx: HandlerCtx, +): Promise { + if (input.kind !== "post_tool") return null; + const projectDir = ctx.cwd; + if (!projectDir) return null; + // Cheap pre-filter before touching the filesystem. + const tool = input.toolName.toLowerCase(); + if (!SKILL_TOOLS.has(tool)) { + if (!READ_TOOLS.has(tool) && !SHELL_TOOLS.has(tool)) return null; + // Nested inputs (Kiro `operations[].path`) are covered by serializing. + let serialized: string; + try { + serialized = JSON.stringify(input.toolInput ?? {}); + } catch { + return null; + } + if (!serialized.includes("SKILL.md") && !serialized.includes("skill://")) { + return null; + } + } + + const known = knownSkillNames(projectDir); + if (known.size === 0) return null; + const skill = detectSkillLoad(input.toolName, input.toolInput, known); + if (!skill) return null; + + await recordSkillRoutes( + { projectDir, vendor: ctx.host ?? ctx.vendor, vendorSid: ctx.sid }, + [ + { + skill, + source: "model-description", + stage: "loaded", + via: input.toolName, + }, + ], + ); + return null; +} + +// ── Standalone entry (direct bun invocation / vendor hook subprocess) ── + +async function main() { + const raw = readFileSync(0, "utf-8"); + let parsed: Record; + try { + parsed = JSON.parse(raw) as Record; + } catch { + process.exit(0); + } + + const toolCall = parsed.toolCall as + | { name?: unknown; args?: unknown } + | undefined; + // Bridges spawn this script directly (pi from `.pi/extensions/oma/`); the + // shared detector maps script path, payload shape, and env to the vendor. + const vendor: Vendor = detectVendorFromInput( + parsed, + "tool", + import.meta.filename, + ); + const isAgy = vendor === "antigravity"; + const projectDir = isAgy + ? agyProjectDir(parsed) || ((parsed.cwd as string | undefined) ?? "") + : getProjectDir(vendor, parsed); + const sid = isAgy + ? (agyConversationId(parsed) ?? undefined) + : ((parsed.session_id as string | undefined) ?? + (parsed.sessionId as string | undefined)); + const toolName = isAgy + ? String(toolCall?.name ?? "") + : String(parsed.tool_name ?? parsed.toolName ?? ""); + const toolInput = ( + isAgy ? toolCall?.args : (parsed.tool_input ?? parsed.toolInput) + ) as Record | undefined; + + await run( + { + kind: "post_tool", + toolName, + toolInput: toolInput ?? {}, + cwd: projectDir, + }, + { vendor, cwd: projectDir, sid }, + ); + if (isAgy) console.log("{}"); + process.exit(0); +} + +if (import.meta.main) { + main().catch(() => process.exit(0)); +} diff --git a/.agents/hooks/core/state-boundary.ts b/.agents/hooks/core/state-boundary.ts index 52c18f05..eef435ea 100644 --- a/.agents/hooks/core/state-boundary.ts +++ b/.agents/hooks/core/state-boundary.ts @@ -2,7 +2,7 @@ import { readFileSync } from "node:fs"; import { basename } from "node:path"; import { recallFacts } from "./agentmemory-client.ts"; -import { agyConversationId } from "./agy-input.ts"; +import { agyConversationId, readAgyPrompt } from "./agy-input.ts"; import { evolutionNoticeLines } from "./evolution-notice.ts"; import { makePromptOutput } from "./hook-output.ts"; import { writeInjectLog } from "./inject-log.ts"; @@ -71,29 +71,34 @@ export async function onBoundary( vendorSid: string, promptText?: string, forced = false, + /** Host to record when it differs from the dialect `vendor` (HandlerCtx.host). */ + host?: string, ): Promise { + const recorded = host ?? vendor; const idx = readIndex(projectDir); const previous = idx.lastSession; const boundary = - !previous || previous.vendor !== vendor || previous.vendorSid !== vendorSid; + !previous || + previous.vendor !== recorded || + previous.vendorSid !== vendorSid; const statelessTurnFlush = vendor === "kiro" && vendorSid === "unknown"; // `forced` = post-compaction SessionStart: the session id is unchanged (no // boundary), but the snapshot was just compacted out of context — re-emit. if (!boundary && !statelessTurnFlush && !forced) { - setLastSession(projectDir, vendor, vendorSid); + setLastSession(projectDir, recorded, vendorSid); return null; } const sid = getActiveSid(idx); if (!sid) { - setLastSession(projectDir, vendor, vendorSid); + setLastSession(projectDir, recorded, vendorSid); return null; } await emitEvent(projectDir, sid, { kind: "boundary", - vendor, + vendor: recorded, vendorSid, payload: { reason: !boundary @@ -105,13 +110,13 @@ export async function onBoundary( : "session-created", fromVendor: previous?.vendor ?? null, fromVendorSid: previous?.vendorSid ?? null, - toVendor: vendor, + toVendor: recorded, toVendorSid: vendorSid, previousSid: sid, - ...vendorHomePayload(vendor), + ...vendorHomePayload(recorded), }, }); - setLastSession(projectDir, vendor, vendorSid); + setLastSession(projectDir, recorded, vendorSid); const recentEvents = readEvents(projectDir, sid).slice(-10); // L2/L3 rehydration: recall enriched facts from AgentMemory for this working @@ -167,7 +172,7 @@ export async function run( ): Promise { if (input.kind !== "prompt") return null; - const { vendor, cwd: projectDir, sid: vendorSid = "unknown" } = ctx; + const { vendor, host, cwd: projectDir, sid: vendorSid = "unknown" } = ctx; // input.kind === "prompt" is guaranteed by the guard above; the user prompt is // the primary recall signal for boundary rehydration. A post-compaction // SessionStart (source === "compact") forces re-emission: the session id is @@ -178,6 +183,7 @@ export async function run( vendorSid, input.prompt, input.source === "compact", + host, ); if (!rendered) return null; return { type: "context", additionalContext: rendered }; @@ -197,11 +203,18 @@ async function main() { const vendor = detectVendorFromInput(input, "prompt", import.meta.filename); const projectDir = getProjectDir(vendor, input); const vendorSid = getVendorSid(input); + let prompt = normalizePromptInput(input.prompt); + + if (vendor === "antigravity" && !prompt) { + const invocationNum = input.invocationNum; + if (typeof invocationNum === "number" && invocationNum > 1) process.exit(0); + prompt = readAgyPrompt(input.transcriptPath, input.lastUserInput); + } // Delegate to run() — single logic source. const hookInput: HookInput = { kind: "prompt", - prompt: normalizePromptInput(input.prompt), + prompt, cwd: projectDir, }; const ctxVal: HandlerCtx = { vendor, cwd: projectDir, sid: vendorSid }; diff --git a/.agents/hooks/core/state-core.ts b/.agents/hooks/core/state-core.ts index b15eb704..475036e4 100644 --- a/.agents/hooks/core/state-core.ts +++ b/.agents/hooks/core/state-core.ts @@ -63,6 +63,7 @@ export type EventKind = | "skill.proposal.created" | "skill.proposal.gated" | "skill.evolution.completed" + | "skill.routed" | "session.ended"; export interface LastSessionMarker { @@ -164,19 +165,57 @@ export function atomicWriteJson(path: string, value: unknown): void { fsyncParent(path); } +/** + * Preserve a corrupt index for forensics instead of silently discarding every + * active session. Best-effort: a concurrent reader may win the rename; the + * loser still falls back to the default index. + */ +function quarantineCorruptIndex(path: string): void { + const target = `${path}.corrupt-${Date.now()}`; + try { + renameSync(path, target); + process.stderr.write( + `[oma] _index.json was corrupt; quarantined to ${target}\n`, + ); + } catch { + process.stderr.write( + "[oma] _index.json is corrupt and could not be quarantined; resetting\n", + ); + } + process.stderr.write( + "[oma] hint: run 'oma state repair' to re-derive active pointers from events\n", + ); +} + export function readIndex(projectDir: string): StateIndex { const path = readableIndexPath(projectDir); if (!existsSync(path)) return defaultIndex(); + let raw: string; try { - const parsed = JSON.parse( - readFileSync(path, "utf-8"), - ) as Partial; + raw = readFileSync(path, "utf-8"); + } catch { + // Transient read error (not provably corrupt) — do not quarantine. + return defaultIndex(); + } + try { + const parsed = JSON.parse(raw) as Partial | null; + if ( + parsed === null || + typeof parsed !== "object" || + (parsed.active !== undefined && + (typeof parsed.active !== "object" || + parsed.active === null || + Array.isArray(parsed.active))) + ) { + throw new Error("invalid index shape"); + } return { schemaVersion: INDEX_SCHEMA_VERSION, active: parsed.active ?? {}, lastSession: parsed.lastSession, }; } catch { + quarantineCorruptIndex(path); return defaultIndex(); } } @@ -228,6 +267,34 @@ export function setActiveSession( }); } +/** + * Claim an active-session slot WITHOUT stomping a live different session + * (M12c). Unconditional setActiveSession on every matched workflow let two + * simultaneous sessions clobber each other's pointer. The claim decision runs + * inside the index lock; `isLive` is injected by the caller (keyword-detector + * derives it from the session's events.jsonl) so this module stays agnostic. + * The non-claiming session still gets its own sid + session.created event. + * + * Returns true when the slot was claimed (empty, stale, or already ours). + */ +export function claimActiveSession( + projectDir: string, + category: string, + sid: string, + isLive: (existingSid: string) => boolean, +): boolean { + sessionDir(projectDir, sid); + let claimed = false; + updateIndex(projectDir, (index) => { + const current = index.active[category]; + if (!current || current === sid || !isLive(current)) { + index.active[category] = sid; + claimed = true; + } + }); + return claimed; +} + export function setLastSession( projectDir: string, vendor: string, diff --git a/.agents/hooks/core/state-lock.ts b/.agents/hooks/core/state-lock.ts new file mode 100644 index 00000000..7262b6f2 --- /dev/null +++ b/.agents/hooks/core/state-lock.ts @@ -0,0 +1,169 @@ +import { + closeSync, + mkdirSync, + openSync, + readFileSync, + statSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { dirname } from "node:path"; + +/** + * Dependency-free cross-process lock for shared `.agents/state/` files. + * + * Acquisition uses an O_EXCL lockfile (`openSync(path, "wx")`), which is + * atomic on both POSIX and Windows. A crashed holder leaves the lockfile + * behind; it is reclaimed once its mtime is older than `staleMs`, so a dead + * session can never deadlock the repository permanently. + * + * This module is the hooks-side copy. The CLI-side copy lives at + * `cli/state/state-lock.ts` and MUST stay algorithm-identical: hooks are + * bundled/copied into vendor dirs and cannot import from cli/. Both copies + * lock the SAME paths, so they interoperate across processes. + */ + +export interface StateLockOptions { + /** Maximum acquisition attempts before giving up (default 60). */ + retries?: number; + /** Base backoff delay in ms; doubles per attempt up to maxDelayMs (default 10). */ + retryDelayMs?: number; + /** Backoff ceiling in ms (default 200). */ + maxDelayMs?: number; + /** Lockfiles older than this are treated as a crashed holder (default 10s). */ + staleMs?: number; +} + +/** Thrown when the lock could not be acquired within the retry budget. */ +export class StateLockTimeoutError extends Error { + constructor(lockPath: string, attempts: number) { + super( + `could not acquire state lock after ${attempts} attempts: ${lockPath} ` + + "(another session may be writing; if this persists, a stale lock can " + + "be removed manually once no oma process is running)", + ); + this.name = "StateLockTimeoutError"; + } +} + +const DEFAULTS: Required = { + retries: 60, + retryDelayMs: 10, + maxDelayMs: 200, + staleMs: 10_000, +}; + +/** Synchronous sleep without dependencies (Atomics.wait works on Node/Bun main threads). */ +function sleepSync(ms: number): void { + try { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); + } catch { + // Environments that disallow main-thread Atomics.wait: bounded busy wait. + const end = Date.now() + ms; + while (Date.now() < end) { + // spin + } + } +} + +function isExistsError(e: unknown): boolean { + return ( + typeof e === "object" && + e !== null && + (e as { code?: string }).code === "EEXIST" + ); +} + +/** + * Run `fn` while holding the exclusive lock at `lockPath`. + * + * Semantics: + * - Acquisition: O_EXCL create; on contention, bounded exponential backoff + * with jitter. A lockfile whose mtime is older than `staleMs` is unlinked + * and retried (crash recovery). + * - Release: the lockfile is removed in `finally`, but only after verifying + * the stored token still matches (best-effort ABA guard: a holder that + * stalled past `staleMs` must not delete its successor's lock). + * - Crash: the lockfile survives the dead process and is reclaimed by the + * next acquirer after `staleMs`. + * - Exhaustion: throws StateLockTimeoutError — best-effort hook callers + * catch it and degrade (D69); the CLI copy propagates it to fail loud. + */ +export function withStateLock( + lockPath: string, + fn: () => T, + options: StateLockOptions = {}, +): T { + const opts = { ...DEFAULTS, ...options }; + const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`; + mkdirSync(dirname(lockPath), { recursive: true }); + + let acquired = false; + let delay = opts.retryDelayMs; + for (let attempt = 0; attempt < opts.retries; attempt++) { + let fd: number | null = null; + try { + fd = openSync(lockPath, "wx"); + writeFileSync( + fd, + JSON.stringify({ pid: process.pid, token, acquiredAt: Date.now() }), + "utf-8", + ); + acquired = true; + break; + } catch (e) { + if (!isExistsError(e)) throw e; + // Contended: reclaim a crashed holder's stale lock, else back off. + try { + const age = Date.now() - statSync(lockPath).mtimeMs; + if (age > opts.staleMs) { + // Re-stat immediately before unlink to shrink the race window + // against a fresh lock created between the two checks. + const recheck = Date.now() - statSync(lockPath).mtimeMs; + if (recheck > opts.staleMs) { + unlinkSync(lockPath); + continue; + } + } + } catch { + // Lock vanished (or stat failed) — retry acquisition immediately. + continue; + } + if (attempt < opts.retries - 1) { + const jitter = 0.75 + Math.random() * 0.5; + sleepSync(Math.min(opts.maxDelayMs, Math.round(delay * jitter))); + delay = Math.min(opts.maxDelayMs, delay * 2); + } + } finally { + if (fd !== null) { + try { + closeSync(fd); + } catch { + // Best-effort close; the lock token is already on disk. + } + } + } + } + if (!acquired) throw new StateLockTimeoutError(lockPath, opts.retries); + + try { + return fn(); + } finally { + try { + // Token check (best-effort): if the file was reclaimed while we + // stalled, do not delete the new holder's lock. + let stillOurs = true; + try { + const parsed = JSON.parse(readFileSync(lockPath, "utf-8")) as { + token?: string; + }; + stillOurs = parsed.token === token; + } catch { + // Unreadable/missing — fall through to unlink (ENOENT is ignored). + } + if (stillOurs) unlinkSync(lockPath); + } catch { + // Release is best-effort; staleness recovery covers any leftover. + } + } +} diff --git a/.agents/hooks/core/state-marker.ts b/.agents/hooks/core/state-marker.ts index 14cace93..47e9f57b 100644 --- a/.agents/hooks/core/state-marker.ts +++ b/.agents/hooks/core/state-marker.ts @@ -1,6 +1,7 @@ // Compatibility surface for installed hook consumers. export { atomicWriteJson, + claimActiveSession, defaultIndex, getActiveSid, indexPath, diff --git a/.agents/hooks/core/test-filter.ts b/.agents/hooks/core/test-filter.ts index fb663824..37a83804 100644 --- a/.agents/hooks/core/test-filter.ts +++ b/.agents/hooks/core/test-filter.ts @@ -94,11 +94,14 @@ export async function run( toolName !== "Bash" && toolName !== "run_shell_command" && toolName !== "Shell" && - toolName !== "execute_bash" + toolName !== "execute_bash" && + toolName !== "run_command" ) return null; - const command = toolInput.command as string | undefined; + const command = (toolInput.command ?? toolInput.CommandLine) as + | string + | undefined; if (!command) return null; // The rewrite below is Bash-only (`set -o pipefail`, subshell, pipe to @@ -117,28 +120,35 @@ export async function run( const isExcluded = EXCLUDE_PATTERNS.some((p) => p.test(command)); if (isExcluded) return null; - // Resolve the filter script: owned vendor namespace, legacy hook dir, then the opencode - // bridge dir (opencode has no core Vendor identity — its subprocess payload - // detects as claude, whose hook dir is absent in opencode-only installs), - // then the SSOT core dir as the last resort. + // Resolve the filter script: the bridge dir a packaged host plugin exports + // (OMA_HOOK_BRIDGE_DIR — the opencode npm package and the Command Code mod + // live outside the project), then the owned vendor namespace, legacy hook + // dir, the opencode-family bridge dirs (opencode / kilo have no core Vendor + // identity — their subprocess payload detects as claude, whose hook dir is + // absent in opencode- or kilo-only installs), then the SSOT core dir. + const bridgeDir = process.env.OMA_HOOK_BRIDGE_DIR; const filterScript = [ - join(getHookDir(vendor), "oma"), - getHookDir(vendor), - join(".opencode", "plugins", "oma"), - join(".agents", "hooks", "core"), - ] - .map((dir) => join(projectDir, dir, "filter-test-output.sh")) - .find((p) => existsSync(p)); + ...(bridgeDir ? [join(bridgeDir, "filter-test-output.sh")] : []), + ...[ + join(getHookDir(vendor), "oma"), + getHookDir(vendor), + join(".opencode", "plugins", "oma"), + join(".kilo", "plugins", "oma"), + join(".agents", "hooks", "core"), + ].map((dir) => join(projectDir, dir, "filter-test-output.sh")), + ].find((p) => existsSync(p)); if (!filterScript) return null; // The original command sits on its own lines inside the subshell: a // trailing `# comment` would otherwise swallow the closing paren, and a // heredoc's terminator must stay alone on its line (`EOF)` never matches). const filteredCmd = `set -o pipefail; (\n${command}\n) 2>&1 | bash "${filterScript}"`; - const updatedInput: Record = { - ...toolInput, - command: filteredCmd, - }; + const usesCommandLine = + typeof toolInput.CommandLine === "string" && + typeof toolInput.command !== "string"; + const updatedInput: Record = usesCommandLine + ? { ...toolInput, CommandLine: filteredCmd } + : { ...toolInput, command: filteredCmd }; return { type: "mutate", updatedInput }; } @@ -162,13 +172,22 @@ function main() { const vendor = detectVendorFromInput(parsed, "tool", import.meta.filename); const projectDir = getProjectDir(vendor, parsed); + const toolCall = parsed.toolCall as + | { name?: string; args?: Record } + | undefined; + const toolName = + parsed.tool_name || + (typeof toolCall?.name === "string" ? toolCall.name : ""); // Build canonical HookInput and delegate to run() — single logic source. const toolInput: Record = { - ...(parsed.tool_input ?? {}), + ...(parsed.tool_input ?? + (toolCall?.args && typeof toolCall.args === "object" + ? toolCall.args + : {})), }; const hookInput: HookInput = { kind: "pre_tool", - toolName: parsed.tool_name, + toolName, toolInput, cwd: projectDir, }; diff --git a/.agents/hooks/core/triggers.json b/.agents/hooks/core/triggers.json index 1516cfed..c8365d48 100644 --- a/.agents/hooks/core/triggers.json +++ b/.agents/hooks/core/triggers.json @@ -15,118 +15,14 @@ ], "keywords": { "*": ["orchestrate"], - "en": [ - "do everything", - "run everything", - "do it all", - "run all tasks", - "execute everything", - "handle everything", - "everything in parallel", - "automate everything", - "automate the whole", - "automate it all" - ], - "ko": [ - "자동으로 해", - "전부 실행", - "전부 해", - "전부 돌려", - "자동으로 해줘", - "전부 병렬로", - "병렬로 전부", - "전부 해줘", - "전부 돌려줘", - "한번에 다 해줘", - "한번에 해줘", - "한꺼번에 해", - "알아서 해줘", - "자동으로 처리해" - ], - "ja": [ - "オーケストレート", - "全部実行", - "全部やって", - "自動でやって", - "全部並列で", - "全部お願い", - "まとめてやって" - ], - "zh": [ - "编排", - "全部执行", - "全部做", - "全部并行", - "自动处理", - "一起做", - "全做了", - "帮我全做" - ], - "es": [ - "orquestar", - "ejecutar todo", - "hazlo todo", - "ejecuta todo", - "todo en paralelo", - "haz todo" - ], - "fr": [ - "orchestrer", - "tout exécuter", - "fais tout", - "exécute tout", - "tout en parallèle", - "gère tout" - ], - "de": [ - "orchestrieren", - "alles ausführen", - "mach alles", - "alles erledigen", - "alles parallel", - "alles auf einmal" - ], - "pt": [ - "orquestrar", - "executar tudo", - "faça tudo", - "execute tudo", - "tudo em paralelo", - "resolva tudo" - ], - "ru": [ - "оркестровать", - "выполнить всё", - "сделай всё", - "запусти всё", - "всё параллельно", - "всё сразу" - ], - "nl": [ - "orkestreren", - "alles uitvoeren", - "doe alles", - "voer alles uit", - "alles parallel", - "alles tegelijk" - ], - "pl": [ - "orkiestrować", - "wykonaj wszystko", - "zrób wszystko", - "uruchom wszystko", - "wszystko równolegle", - "wszystko naraz" - ] - }, - "patterns": { - "*": [ - "\\b(build|create|make|develop|implement|scaffold)\\s+(?:me\\s+)?(?:an?)\\s+(?:[\\w-]+\\s+){0,3}(app|api|service|server|cli|tool|website|dashboard|system|backend|frontend|prototype|mvp|bot)\\b", - "\\bi\\s+want\\s+(?:a|an)\\s+(?:[\\w-]+\\s+){0,3}(app|api|service|server|cli|tool|website|dashboard|system|backend|frontend|prototype|mvp|bot)\\b" - ], - "ko": [ - "(앱|API|서비스|서버|CLI|도구|웹사이트|대시보드|시스템|백엔드|프론트엔드|프로토타입|MVP|봇)\\s*(?:을|를|이|가)?\\s*(?:만들어\\s*(?:주세요|줘|줄래)?|구현해\\s*(?:주세요|줘|줄래)?|개발해\\s*(?:주세요|줘|줄래)?|만들자|구현하자|개발하자)" - ] + "ja": ["オーケストレート"], + "es": ["orquestar"], + "fr": ["orchestrer"], + "de": ["orchestrieren"], + "pt": ["orquestrar"], + "ru": ["оркестровать"], + "nl": ["orkestreren"], + "pl": ["orkiestrować"] } }, "ultrawork": { @@ -136,1081 +32,11 @@ "*": ["ultrawork", "ulw"] } }, - "architecture": { - "persistent": false, - "keywords": { - "*": ["architecture", "ADR", "ATAM", "CBAM"], - "en": [ - "system design", - "software design", - "architecture review", - "architectural review", - "module boundary", - "service boundary", - "design twice", - "tradeoff analysis", - "quality attribute" - ], - "ko": [ - "아키텍처", - "시스템 설계", - "소프트웨어 설계", - "아키텍처 리뷰", - "구조 리뷰", - "모듈 경계", - "서비스 경계", - "설계 두 번", - "트레이드오프", - "품질 속성" - ], - "ja": [ - "アーキテクチャ", - "システム設計", - "ソフトウェア設計", - "アーキテクチャレビュー", - "モジュール境界", - "サービス境界", - "トレードオフ", - "品質特性" - ], - "zh": [ - "架构", - "系统设计", - "软件设计", - "架构评审", - "模块边界", - "服务边界", - "权衡分析", - "质量属性" - ], - "es": [ - "arquitectura", - "diseño de sistemas", - "diseño de software", - "revisión de arquitectura", - "límite de módulo", - "límite de servicio", - "análisis de compensaciones", - "atributo de calidad" - ], - "fr": [ - "architecture", - "conception système", - "conception logicielle", - "revue d'architecture", - "frontière de module", - "frontière de service", - "analyse des compromis", - "attribut de qualité" - ], - "de": [ - "architektur", - "systemdesign", - "softwaredesign", - "architekturreview", - "modulgrenze", - "servicegrenze", - "trade-off-analyse", - "qualitätsattribut" - ], - "pt": [ - "arquitetura", - "design de sistemas", - "design de software", - "revisão de arquitetura", - "limite de módulo", - "limite de serviço", - "análise de trade-off", - "atributo de qualidade" - ], - "ru": [ - "архитектура", - "системный дизайн", - "архитектура ПО", - "архитектурное ревью", - "граница модуля", - "граница сервиса", - "анализ компромиссов", - "атрибут качества" - ], - "nl": [ - "architectuur", - "systeemontwerp", - "softwareontwerp", - "architectuurreview", - "modulegrens", - "servicegrens", - "trade-offanalyse", - "kwaliteitsattribuut" - ], - "pl": [ - "architektura", - "projekt systemu", - "projekt oprogramowania", - "przegląd architektury", - "granica modułu", - "granica usługi", - "analiza kompromisów", - "atrybut jakości" - ] - } - }, - "plan": { - "persistent": false, - "keywords": { - "*": ["task breakdown"], - "en": [ - "plan", - "make a plan", - "create a plan", - "break down", - "analyze requirements", - "plan this", - "decompose" - ], - "ko": [ - "계획", - "요구사항 분석", - "스펙 분석", - "스펙 정리", - "계획 세워줘", - "계획 짜줘", - "분석해줘", - "분석해", - "태스크 분해", - "작업 분해", - "기획", - "기획해줘", - "설계해줘", - "스펙 정리해줘", - "요구사항 정리해줘", - "플랜 짜줘" - ], - "ja": [ - "計画", - "要件分析", - "タスク分解", - "計画を立てて", - "計画して", - "分析して", - "分解して", - "設計して", - "プランを作って" - ], - "zh": [ - "计划", - "需求分析", - "任务分解", - "制定计划", - "做个计划", - "分析一下", - "拆分任务", - "规划一下" - ], - "es": [ - "plan", - "planificar", - "análisis de requisitos", - "haz un plan", - "crea un plan", - "analiza", - "descomponer", - "planifica esto" - ], - "fr": [ - "plan", - "planifier", - "analyse des exigences", - "fais un plan", - "crée un plan", - "analyse", - "décompose", - "planifie" - ], - "de": [ - "plan", - "planen", - "anforderungsanalyse", - "mach einen plan", - "erstelle einen plan", - "analysiere", - "zerlege", - "plane das" - ], - "pt": [ - "plano", - "planejar", - "análise de requisitos", - "faça um plano", - "crie um plano", - "analise", - "decomponha", - "planeje isso" - ], - "ru": [ - "план", - "планировать", - "анализ требований", - "составь план", - "создай план", - "проанализируй", - "разбей на задачи", - "спланируй" - ], - "nl": [ - "plan", - "plannen", - "vereistenanalyse", - "maak een plan", - "analyseer", - "splits op", - "plan dit" - ], - "pl": [ - "plan", - "planować", - "analiza wymagań", - "zrób plan", - "stwórz plan", - "przeanalizuj", - "rozłóż na zadania", - "zaplanuj to" - ] - } - }, - "review": { - "persistent": false, - "keywords": { - "*": ["code review", "security audit", "security review"], - "en": [ - "review", - "review this", - "review my code", - "check my code", - "audit", - "inspect", - "code check" - ], - "ko": [ - "리뷰", - "코드 검토", - "보안 검토", - "성능 검토", - "리뷰해줘", - "검토해줘", - "코드 검토해줘", - "한번 봐줘", - "코드 봐줘", - "점검해줘", - "코드 점검", - "보안 감사", - "성능 분석" - ], - "ja": [ - "レビュー", - "コードレビュー", - "セキュリティ監査", - "レビューして", - "確認して", - "コードを見て", - "チェックして", - "点検して", - "コード確認" - ], - "zh": [ - "审查", - "代码审查", - "安全审计", - "审查一下", - "检查一下", - "看看代码", - "检查代码", - "代码检查", - "安全检查" - ], - "es": [ - "revisión", - "revisar código", - "auditoría de seguridad", - "revisa", - "revisa esto", - "revisa mi código", - "verifica", - "inspecciona", - "chequea el código" - ], - "fr": [ - "revue", - "revue de code", - "audit de sécurité", - "révise", - "vérifie", - "regarde mon code", - "inspecte", - "vérifie le code" - ], - "de": [ - "review", - "code-review", - "sicherheitsaudit", - "überprüfe", - "prüfe", - "schau dir den code an", - "kontrolliere", - "code prüfen" - ], - "pt": [ - "revisão", - "revisar código", - "auditoria de segurança", - "revise", - "verifique", - "confira", - "olhe o código", - "cheque o código" - ], - "ru": [ - "ревью", - "обзор кода", - "аудит безопасности", - "проверь", - "посмотри код", - "проведи ревью", - "проверь код", - "осмотри код" - ], - "nl": [ - "review", - "code review", - "beveiligingsaudit", - "bekijk", - "controleer", - "check de code", - "inspecteer", - "beoordeel" - ], - "pl": [ - "przegląd", - "przegląd kodu", - "audyt bezpieczeństwa", - "sprawdź", - "sprawdź to", - "przejrzyj kod", - "skontroluj", - "zweryfikuj kod" - ] - } - }, - "security": { - "persistent": false, - "keywords": { - "*": ["/security", "security workflow"], - "en": [ - "run deepsec", - "deepsec scan this repo", - "scan repo with deepsec", - "deepsec pr review", - "deepsec ci gate", - "deepsec triage", - "deepsec matchers", - "run a security scan", - "scan repo for vulnerabilities", - "scan the repo for vulnerabilities", - "scan this skill for vulnerabilities", - "scan this mcp server", - "run cisco skill scanner", - "run cisco mcp scanner", - "run ai deep sast", - "run cisco ai deep sast", - "run artex", - "artex pentest", - "penetration test this test site", - "validate security findings" - ], - "ko": [ - "보안 스캔", - "취약점 스캔", - "시큐리티 워크플로우", - "딥섹 실행", - "딥섹 스캔", - "딥섹으로 검사", - "딥섹 PR 리뷰", - "딥섹 CI 게이트", - "시스코 스킬 스캐너 실행", - "시스코 MCP 스캐너 실행", - "딥 SAST 실행", - "ARTEX 실행", - "ARTEX로 테스트 사이트 침투 테스트", - "보안 파인딩 검증" - ], - "ja": [ - "セキュリティスキャン", - "脆弱性スキャン", - "ディープセック実行", - "deepsecでスキャン", - "deepsec PRレビュー", - "ARTEXで侵入テスト" - ], - "zh": [ - "安全扫描", - "漏洞扫描", - "运行 deepsec", - "用 deepsec 扫描", - "deepsec PR 审查", - "运行 ARTEX" - ] - } - }, - "debug": { - "persistent": false, - "keywords": { - "*": ["debug"], - "en": [ - "fix bug", - "fix error", - "fix crash", - "fix the bug", - "fix the error", - "fix the crash", - "fix it", - "fix this", - "troubleshoot", - "broken", - "not working", - "doesn't work", - "debug this", - "find the bug" - ], - "ko": [ - "디버그", - "버그 수정", - "에러 수정", - "오류 수정", - "버그 찾아", - "버그 고쳐", - "버그 잡아", - "고쳐줘", - "고쳐", - "수정해줘", - "수정해", - "에러 고쳐줘", - "에러 고쳐", - "에러 잡아줘", - "오류 고쳐줘", - "오류 고쳐", - "오류 잡아줘", - "버그 고쳐줘", - "버그 수정해줘", - "버그 잡아줘", - "에러 수정해줘", - "에러 찾아줘", - "오류 수정해줘", - "오류 찾아줘", - "왜 안돼", - "안 돼", - "동작 안해", - "작동 안해", - "깨졌어", - "터졌어", - "에러남", - "에러나" - ], - "ja": [ - "デバッグ", - "バグ修正", - "エラー修正", - "直して", - "修正して", - "壊れた", - "動かない", - "エラーが出る", - "バグを直して", - "エラーを直して", - "動作しない", - "クラッシュ" - ], - "zh": [ - "调试", - "修复 bug", - "修复错误", - "修复崩溃", - "修一下", - "修复", - "坏了", - "不工作", - "不能用", - "出错了", - "报错", - "有 bug", - "崩溃了" - ], - "es": [ - "depurar", - "corregir bug", - "corregir error", - "arregla", - "arréglalo", - "está roto", - "no funciona", - "no va", - "tiene un bug", - "corrige esto", - "repara" - ], - "fr": [ - "déboguer", - "corriger bug", - "corriger erreur", - "répare", - "corrige", - "c'est cassé", - "ça ne marche pas", - "ne fonctionne pas", - "a un bug", - "corrige ça" - ], - "de": [ - "debuggen", - "bug beheben", - "fehler beheben", - "repariere", - "ist kaputt", - "funktioniert nicht", - "geht nicht", - "hat einen bug", - "behebe das", - "fixen" - ], - "pt": [ - "depurar", - "corrigir bug", - "corrigir erro", - "conserte", - "arrume", - "está quebrado", - "não funciona", - "tem um bug", - "corrija isso", - "repare" - ], - "ru": [ - "отладка", - "исправить баг", - "исправить ошибку", - "почини", - "исправь", - "сломалось", - "не работает", - "ошибка", - "есть баг", - "исправь это", - "починить" - ], - "nl": [ - "debuggen", - "bug oplossen", - "fout oplossen", - "repareer", - "is kapot", - "werkt niet", - "doet het niet", - "heeft een bug", - "los dit op", - "fixen" - ], - "pl": [ - "debugować", - "naprawić bug", - "naprawić błąd", - "napraw", - "napraw to", - "jest zepsuty", - "nie działa", - "ma buga", - "popraw to", - "napraw błąd" - ] - } - }, - "brainstorm": { - "persistent": false, - "keywords": { - "*": ["brainstorm"], - "en": [ - "ideate", - "explore design", - "ideas", - "come up with", - "what if", - "how about", - "explore options", - "explore ideas" - ], - "ko": [ - "브레인스토밍", - "아이디어", - "설계 탐색", - "디자인 탐색", - "아이디어 좀", - "아이디어 내줘", - "같이 생각해보자", - "뭐가 좋을까", - "어떻게 하면 좋을까", - "생각해봐", - "구상", - "구상해줘" - ], - "ja": [ - "ブレインストーミング", - "アイデア", - "設計探索", - "アイデアを出して", - "考えてみて", - "どうかな", - "アイデアちょうだい", - "一緒に考えよう" - ], - "zh": [ - "头脑风暴", - "创意", - "设计探索", - "想想", - "出主意", - "有什么想法", - "想个办法", - "出点子", - "集思广益" - ], - "es": [ - "lluvia de ideas", - "idear", - "explorar diseño", - "piensa en", - "qué tal si", - "ideas para", - "sugiere", - "se te ocurre" - ], - "fr": [ - "brainstorming", - "idéer", - "explorer le design", - "réfléchis", - "et si", - "des idées pour", - "propose", - "imagine" - ], - "de": [ - "brainstorming", - "ideenfindung", - "design erkunden", - "denk nach", - "was wäre wenn", - "ideen für", - "vorschläge", - "lass uns überlegen" - ], - "pt": [ - "brainstorming", - "idear", - "explorar design", - "pense em", - "e se", - "ideias para", - "sugira", - "imagine" - ], - "ru": [ - "мозговой штурм", - "идеи", - "исследовать дизайн", - "подумай", - "а что если", - "идеи для", - "предложи", - "давай придумаем" - ], - "nl": [ - "brainstormen", - "ideeën", - "ontwerp verkennen", - "bedenk", - "wat als", - "ideeën voor", - "stel voor", - "laten we nadenken" - ], - "pl": [ - "burza mózgów", - "pomysły", - "eksploracja projektu", - "pomyśl", - "co jeśli", - "pomysły na", - "zaproponuj", - "zastanówmy się" - ] - } - }, "work": { "persistent": true, "explicit": ["work mode", "work workflow"], "keywords": { - "*": ["step by step", "work mode", "work workflow"], - "en": ["one by one", "one step at a time"], - "ko": [ - "단계별", - "단계별로", - "단계별로 해줘", - "단계별로 진행해줘", - "하나씩 해줘", - "순서대로 해줘", - "차근차근", - "차근차근 해줘" - ], - "ja": ["ステップバイステップ", "一歩ずつ", "一つずつ", "順番にやって"], - "zh": ["逐步", "一步一步", "一个一个", "按顺序"], - "es": ["paso a paso", "uno por uno", "de a uno"], - "fr": ["étape par étape", "un par un"], - "de": [ - "schritt für schritt", - "eins nach dem anderen", - "der reihe nach" - ], - "pt": ["passo a passo", "um por um"], - "ru": ["шаг за шагом", "по одному"], - "nl": ["stap voor stap", "een voor een"], - "pl": ["krok po kroku", "jeden po drugim"] - } - }, - "deepinit": { - "persistent": false, - "keywords": { - "*": ["deepinit"], - "en": [ - "init project", - "initialize", - "setup project", - "new project", - "scaffold", - "bootstrap" - ], - "ko": [ - "프로젝트 초기화", - "코드베이스 초기화", - "프로젝트 시작", - "프로젝트 설정", - "초기화해줘", - "새 프로젝트", - "프로젝트 만들어줘", - "셋업", - "셋업해줘" - ], - "ja": [ - "プロジェクト初期化", - "プロジェクト開始", - "新しいプロジェクト", - "セットアップ", - "初期化して", - "プロジェクトを作って", - "プロジェクト設定" - ], - "zh": [ - "项目初始化", - "新项目", - "设置项目", - "搭建项目", - "初始化", - "创建项目", - "项目配置" - ], - "es": [ - "inicializar proyecto", - "nuevo proyecto", - "configurar proyecto", - "inicializa", - "crea un proyecto", - "monta el proyecto" - ], - "fr": [ - "initialiser projet", - "nouveau projet", - "configurer projet", - "initialise", - "crée un projet", - "monte le projet" - ], - "de": [ - "projekt initialisieren", - "neues projekt", - "projekt einrichten", - "initialisiere", - "erstelle ein projekt", - "projekt aufsetzen" - ], - "pt": [ - "inicializar projeto", - "novo projeto", - "configurar projeto", - "inicialize", - "crie um projeto", - "monte o projeto" - ], - "ru": [ - "инициализация проекта", - "новый проект", - "настроить проект", - "инициализируй", - "создай проект", - "настрой проект" - ], - "nl": [ - "project initialiseren", - "nieuw project", - "project opzetten", - "initialiseer", - "maak een project", - "project configureren" - ], - "pl": [ - "inicjalizacja projektu", - "nowy projekt", - "skonfiguruj projekt", - "zainicjalizuj", - "stwórz projekt", - "przygotuj projekt" - ] - } - }, - "scm": { - "persistent": false, - "keywords": { - "*": [ - "scm", - "configuration management", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "merge conflict", - "rebase", - "worktree", - "cherry-pick", - "submodule", - "subtree", - "codeowners", - "branch protection", - "protected branch", - "release tag", - "tagging", - "version baseline", - "squash merge", - "rebase merge", - "fast-forward", - "fast forward", - "merge strategy" - ], - "en": [ - "commit", - "git commit", - "branch strategy", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "merge conflict", - "resolve conflict", - "rebase", - "worktree", - "release branch", - "baseline", - "conventional commits" - ], - "ko": [ - "커밋", - "커밋해줘", - "깃 커밋", - "형상관리", - "브랜치 전략", - "gitflow", - "github flow", - "gitlab flow", - "트렁크 기반", - "머지 충돌", - "충돌 해결", - "리베이스", - "워크트리", - "릴리즈 브랜치", - "베이스라인", - "컨벤셔널 커밋", - "체리픽", - "서브모듈", - "서브트리", - "코드오너", - "브랜치 보호", - "보호 브랜치", - "릴리즈 태그", - "태깅", - "버전 베이스라인", - "스쿼시 머지", - "리베이스 머지", - "패스트포워드", - "머지 전략" - ], - "ja": [ - "コミット", - "gitコミット", - "構成管理", - "ブランチ戦略", - "gitflow", - "github flow", - "gitlab flow", - "トランクベース", - "マージコンフリクト", - "コンフリクト解決", - "リベース", - "ワークツリー", - "リリースブランチ", - "ベースライン", - "conventional commits" - ], - "zh": [ - "提交", - "git 提交", - "配置管理", - "分支策略", - "gitflow", - "github flow", - "gitlab flow", - "主干开发", - "合并冲突", - "冲突解决", - "rebase", - "worktree", - "发布分支", - "基线", - "conventional commits" - ], - "es": [ - "commit", - "git commit", - "gestión de configuración", - "estrategia de ramas", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "conflicto de merge", - "resolver conflicto", - "rebase", - "worktree", - "rama de release", - "línea base", - "conventional commits" - ], - "fr": [ - "commit", - "git commit", - "gestion de configuration", - "stratégie de branche", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "conflit de merge", - "résoudre conflit", - "rebase", - "worktree", - "branche de release", - "baseline", - "conventional commits" - ], - "de": [ - "commit", - "git commit", - "konfigurationsmanagement", - "branch-strategie", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "merge-konflikt", - "konflikt lösen", - "rebase", - "worktree", - "release-branch", - "baseline", - "conventional commits" - ], - "pt": [ - "commit", - "git commit", - "gestão de configuração", - "estratégia de branch", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "conflito de merge", - "resolver conflito", - "rebase", - "worktree", - "branch de release", - "linha de base", - "conventional commits" - ], - "ru": [ - "коммит", - "git commit", - "управление конфигурацией", - "стратегия ветвления", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "конфликт слияния", - "разрешить конфликт", - "rebase", - "worktree", - "релизная ветка", - "базовая линия", - "conventional commits" - ], - "nl": [ - "commit", - "git commit", - "configuratiemanagement", - "branchstrategie", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "mergeconflict", - "conflict oplossen", - "rebase", - "worktree", - "release branch", - "baseline", - "conventional commits" - ], - "pl": [ - "commit", - "git commit", - "zarządzanie konfiguracją", - "strategia gałęzi", - "gitflow", - "github flow", - "gitlab flow", - "trunk-based", - "konflikt scalania", - "rozwiąż konflikt", - "rebase", - "worktree", - "gałąź wydania", - "linia bazowa", - "conventional commits" - ] + "*": ["work mode", "work workflow"] } }, "ralph": { @@ -1218,540 +44,7 @@ "explicit": ["ralph", "랄프"], "keywords": { "*": ["ralph"], - "en": [ - "don't stop", - "do not stop", - "must complete", - "until done", - "keep going until", - "finish everything", - "complete everything", - "run to completion", - "no stopping", - "see it through", - "don't give up", - "never stop", - "push through", - "finish it all", - "complete all" - ], - "ko": [ - "랄프", - "멈추지마", - "멈추지 말고", - "완료될때까지", - "될때까지 해", - "끝날때까지", - "다 끝내", - "전부 완료", - "끝까지 해", - "중단하지마", - "끝장내", - "끝까지 해줘", - "다 끝내줘", - "때까지 계속", - "그만두지마", - "포기하지마", - "멈추지 말아줘" - ], - "ja": [ - "止まるな", - "完了まで", - "最後まで", - "全部終わらせて", - "止めないで", - "完了するまで", - "最後までやって", - "諦めないで", - "中断しないで", - "全部やりきって" - ], - "zh": [ - "不要停", - "直到完成", - "做到完成", - "全部完成", - "别停", - "做完为止", - "一直做到完", - "别放弃", - "不要中断", - "全部做完" - ], - "es": [ - "no pares", - "hasta completar", - "hasta terminar", - "termina todo", - "no te detengas", - "completa todo", - "no abandones", - "acaba todo" - ], - "fr": [ - "n'arrête pas", - "jusqu'à complétion", - "jusqu'au bout", - "termine tout", - "ne t'arrête pas", - "complète tout", - "n'abandonne pas", - "continue sans t'arrêter", - "finis tout" - ], - "de": [ - "hör nicht auf", - "bis zur fertigstellung", - "bis es fertig ist", - "alles fertigstellen", - "nicht aufhören", - "mach alles fertig", - "gib nicht auf", - "alles abschließen" - ], - "pt": [ - "não pare", - "até completar", - "até terminar", - "termine tudo", - "complete tudo", - "não pare até terminar", - "não desista", - "continue sem parar", - "finalize tudo" - ], - "ru": [ - "не останавливайся", - "до завершения", - "пока не закончишь", - "заверши всё", - "не прекращай", - "доделай всё", - "не сдавайся", - "закончи всё" - ], - "nl": [ - "stop niet", - "tot voltooiing", - "tot het klaar is", - "maak alles af", - "niet stoppen", - "alles afronden", - "geef niet op", - "maak alles klaar" - ], - "pl": [ - "nie zatrzymuj się", - "do ukończenia", - "aż skończysz", - "dokończ wszystko", - "nie przerywaj", - "skończ wszystko", - "nie poddawaj się", - "zakończ wszystko" - ] - } - }, - "design": { - "persistent": false, - "keywords": { - "*": ["design system", "DESIGN.md", "design token"], - "en": [ - "design", - "landing page", - "ui design", - "color palette", - "typography", - "dark theme", - "responsive design", - "glassmorphism", - "style guide", - "theme", - "color scheme", - "visual design", - "layout", - "wireframe", - "mockup" - ], - "ko": [ - "디자인", - "랜딩페이지", - "디자인 시스템", - "UI 디자인", - "색상 팔레트", - "타이포그래피", - "다크 테마", - "반응형", - "디자인해줘", - "디자인 만들어줘", - "UI 만들어줘", - "화면 디자인", - "페이지 디자인", - "색상 정해줘", - "테마 만들어줘" - ], - "ja": [ - "デザイン", - "ランディングページ", - "デザインシステム", - "UIデザイン", - "カラーパレット", - "タイポグラフィ", - "ダークテーマ", - "レスポンシブ", - "デザインして", - "デザインを作って", - "UIを作って", - "画面デザイン", - "レイアウト", - "ワイヤーフレーム", - "モックアップ" - ], - "zh": [ - "设计", - "着陆页", - "设计系统", - "UI设计", - "配色方案", - "字体排版", - "暗色主题", - "响应式", - "设计一下", - "做个设计", - "做UI", - "页面设计", - "布局", - "线框图", - "原型" - ], - "es": [ - "diseño", - "página de aterrizaje", - "sistema de diseño", - "diseño UI", - "paleta de colores", - "tipografía", - "tema oscuro", - "diseño responsivo", - "diseña", - "crea un diseño", - "haz el diseño", - "maqueta" - ], - "fr": [ - "design", - "page d'atterrissage", - "système de design", - "design UI", - "palette de couleurs", - "typographie", - "thème sombre", - "design responsif", - "fais le design", - "crée un design", - "maquette" - ], - "de": [ - "Design", - "Landingpage", - "Designsystem", - "UI-Design", - "Farbpalette", - "Typografie", - "dunkles Theme", - "responsives Design", - "gestalte", - "erstelle ein Design", - "mach das Design", - "Wireframe", - "Mockup" - ], - "pt": [ - "design", - "página de destino", - "sistema de design", - "design UI", - "paleta de cores", - "tipografia", - "tema escuro", - "design responsivo", - "faça o design", - "crie um design", - "monte o design", - "wireframe" - ], - "ru": [ - "дизайн", - "лендинг", - "дизайн-система", - "UI дизайн", - "цветовая палитра", - "типографика", - "тёмная тема", - "адаптивный дизайн", - "сделай дизайн", - "создай дизайн", - "оформи", - "макет", - "wireframe" - ], - "nl": [ - "ontwerp", - "landingspagina", - "ontwerpsysteem", - "UI-ontwerp", - "kleurenpalet", - "typografie", - "donker thema", - "responsief ontwerp", - "ontwerp dit", - "maak een ontwerp", - "wireframe", - "mockup" - ], - "pl": [ - "projekt", - "strona docelowa", - "system projektowy", - "projekt UI", - "paleta kolorów", - "typografia", - "ciemny motyw", - "responsywny projekt", - "zaprojektuj", - "stwórz projekt", - "zrób design", - "wireframe", - "makieta" - ] - } - }, - "docs": { - "persistent": false, - "keywords": { - "*": ["oma-docs", "doc-refs", "docs verify", "docs sync"], - "en": [ - "verify docs", - "verify documentation", - "check docs", - "check documentation", - "docs drift", - "documentation drift", - "broken docs", - "broken doc links", - "stale docs", - "stale documentation", - "sync docs", - "sync documentation", - "update docs after change", - "patch docs", - "doc verify", - "doc sync" - ], - "ko": [ - "문서 검증", - "문서 검증해줘", - "문서 점검", - "문서 점검해줘", - "문서 드리프트", - "문서 동기화", - "문서 동기화해줘", - "문서 싱크", - "문서 싱크 맞춰", - "문서 싱크 맞춰줘", - "깨진 문서 링크", - "깨진 문서", - "오래된 문서", - "낡은 문서", - "문서 갱신", - "문서 업데이트", - "docs 검증", - "docs 싱크", - "docs 동기화" - ], - "ja": [ - "ドキュメント検証", - "ドキュメント点検", - "ドキュメントドリフト", - "ドキュメント同期", - "ドキュメントを同期", - "壊れたドキュメントリンク", - "古いドキュメント", - "ドキュメント更新", - "docsを検証", - "docsを同期" - ], - "zh": [ - "文档校验", - "文档检查", - "文档漂移", - "文档同步", - "同步文档", - "失效文档链接", - "陈旧文档", - "更新文档", - "docs 校验", - "docs 同步" - ], - "es": [ - "verificar documentación", - "comprobar documentación", - "deriva de documentación", - "sincronizar documentación", - "enlaces rotos en documentación", - "documentación obsoleta", - "actualizar documentación" - ], - "fr": [ - "vérifier la documentation", - "contrôler la documentation", - "dérive de documentation", - "synchroniser la documentation", - "liens cassés dans la documentation", - "documentation obsolète", - "mettre à jour la documentation" - ], - "de": [ - "Doku verifizieren", - "Dokumentation prüfen", - "Dokumentations-Drift", - "Doku synchronisieren", - "kaputte Doku-Links", - "veraltete Dokumentation", - "Doku aktualisieren" - ], - "pt": [ - "verificar documentação", - "checar documentação", - "drift de documentação", - "sincronizar documentação", - "links quebrados na documentação", - "documentação desatualizada", - "atualizar documentação" - ], - "ru": [ - "проверить документацию", - "верифицировать документацию", - "дрейф документации", - "синхронизировать документацию", - "битые ссылки в документации", - "устаревшая документация", - "обновить документацию" - ], - "nl": [ - "documentatie verifiëren", - "documentatie controleren", - "documentatie-drift", - "documentatie synchroniseren", - "kapotte documentatielinks", - "verouderde documentatie", - "documentatie bijwerken" - ], - "pl": [ - "zweryfikuj dokumentację", - "sprawdź dokumentację", - "dryf dokumentacji", - "zsynchronizuj dokumentację", - "zepsute linki w dokumentacji", - "przestarzała dokumentacja", - "zaktualizuj dokumentację" - ] - } - }, - "recap": { - "persistent": false, - "keywords": { - "*": ["recap"], - "ko": ["리캡"], - "ja": ["リキャップ"] - } - }, - "video": { - "persistent": false, - "keywords": { - "*": ["oma-video", "remotion", "shorts", "reels", "screencast"], - "en": [ - "generate video", - "generate a video", - "create video", - "create a video", - "make a video", - "short-form video", - "shorts video", - "reels video", - "youtube short", - "tiktok video", - "explainer video", - "demo video", - "walkthrough video", - "screencast video", - "turn this into a video", - "video from readme", - "video from code" - ], - "ko": [ - "영상 만들어", - "영상 만들어줘", - "영상 생성", - "영상 생성해", - "영상 생성해줘", - "비디오 만들어", - "비디오 만들어줘", - "숏폼 만들어", - "숏폼 영상", - "쇼츠 만들어", - "쇼츠 영상", - "릴스 만들어", - "릴스 영상", - "데모 영상", - "설명 영상", - "설명 영상 만들어", - "스크린캐스트", - "영상으로 만들어" - ], - "ja": [ - "動画を生成", - "動画生成", - "動画を作", - "動画を作成", - "ショート動画", - "リール動画", - "解説動画", - "デモ動画", - "スクリーンキャスト" - ], - "zh": [ - "生成视频", - "生成一段视频", - "制作视频", - "做个视频", - "短视频", - "竖屏短视频", - "讲解视频", - "演示视频", - "录屏视频" - ], - "es": [ - "generar video", - "crear video", - "hazme un video", - "video corto", - "video explicativo" - ], - "fr": [ - "générer une vidéo", - "créer une vidéo", - "fais-moi une vidéo", - "vidéo courte", - "vidéo explicative" - ], - "de": [ - "video generieren", - "video erstellen", - "erstelle ein video", - "kurzvideo", - "erklärvideo" - ] + "ko": ["랄프"] } } }, @@ -1842,34 +135,6 @@ "zh": ["帮我想想", "一起想想办法", "给点灵感"] } }, - "oma-coordination": { - "keywords": { - "*": [], - "en": [ - "coordinate the agents", - "hand off to agent", - "multi agent workflow", - "run agents manually", - "multi agent coordination", - "coordinate agents", - "cli handoff", - "manual orchestration" - ], - "ko": [ - "에이전트 조율", - "에이전트끼리 협업", - "수동으로 에이전트 돌려", - "에이전트 순서 잡아줘" - ], - "ja": [ - "エージェントを調整", - "エージェント連携", - "手動でエージェント", - "エージェントの順序" - ], - "zh": ["协调代理", "代理之间协作", "手动跑代理", "代理之间衔接"] - } - }, "oma-db": { "keywords": { "*": ["ERD", "vector db"], @@ -2084,7 +349,14 @@ }, "oma-mobile": { "keywords": { - "*": ["riverpod", "cupertino", "swiftui", "swift-openapi-generator"], + "*": [ + "riverpod", + "cupertino", + "swiftui", + "swift-openapi-generator", + "jetpack compose", + "ktor client" + ], "en": [ "flutter screen", "react native view", @@ -2416,21 +688,62 @@ "multi agent orchestration", "spawn agents", "review loop", - "mcp memory coordination" + "mcp memory coordination", + "coordinate the agents", + "hand off to agent", + "multi agent workflow", + "run agents manually", + "multi agent coordination", + "coordinate agents", + "cli handoff", + "manual orchestration", + "delegate this to", + "hand this to", + "hand this off to", + "run it as a batch" ], "ko": [ "에이전트 병렬 실행", "동시에 에이전트 돌려", "fan-out", - "리뷰 루프 돌려" + "리뷰 루프 돌려", + "에이전트 조율", + "에이전트끼리 협업", + "수동으로 에이전트 돌려", + "에이전트 순서 잡아줘", + "한테 맡겨", + "한테 맡기", + "한테 시켜", + "한테 넘겨", + "에게 맡겨", + "에게 위임" ], "ja": [ "エージェント並列実行", "同時にエージェント", "fan-out", - "レビューループ" + "レビューループ", + "エージェントを調整", + "エージェント連携", + "手動でエージェント", + "エージェントの順序", + "に任せて", + "に委任して", + "にやらせて" ], - "zh": ["并行跑代理", "同时派发代理", "fan-out 任务", "评审循环"] + "zh": [ + "并行跑代理", + "同时派发代理", + "fan-out 任务", + "评审循环", + "协调代理", + "代理之间协作", + "手动跑代理", + "代理之间衔接", + "交给它来做", + "委托给", + "让它来做" + ] } }, "oma-pdf": { @@ -3071,6 +1384,90 @@ "重构计划" ] } + }, + "oma-docs": { + "keywords": { + "*": ["oma docs"], + "en": [ + "broken doc links", + "docs drift", + "documentation drift", + "sync the docs", + "update the docs for this diff", + "doc references", + "stale docs", + "translation drift" + ], + "ko": [ + "문서 동기화", + "문서 드리프트", + "깨진 문서 링크", + "문서 참조 확인", + "번역 드리프트" + ], + "ja": [ + "ドキュメント同期", + "ドキュメントのずれ", + "リンク切れ確認", + "翻訳のずれ" + ], + "zh": ["文档同步", "文档漂移", "失效文档链接", "翻译漂移"] + } + }, + "oma-explanation": { + "keywords": { + "*": ["explainer"], + "en": [ + "html explainer", + "explainer document", + "visual walkthrough", + "walkthrough document", + "explain this diff as a page", + "explain this pr as a document" + ], + "ko": ["해설 문서", "설명서 만들어", "코드 해설", "변경 해설"], + "ja": ["コード解説", "解説ページ", "解説ドキュメント"], + "zh": ["代码讲解", "讲解文档", "讲解页面"] + } + }, + "oma-scholar": { + "keywords": { + "*": ["openalex", "knows.academy"], + "en": [ + "literature search", + "find papers on", + "paper sidecar", + "knows sidecar", + "academic papers on", + "compare these papers", + "claims and evidence" + ], + "ko": [ + "논문 검색", + "논문 찾아", + "문헌 조사", + "논문 비교", + "사이드카 생성" + ], + "ja": ["論文検索", "論文を探して", "文献調査", "論文比較"], + "zh": ["论文检索", "查找论文", "文献调研", "论文对比"] + } + }, + "oma-skill-creation": { + "keywords": { + "*": ["ssl-lite"], + "en": [ + "create a skill", + "write a skill", + "new oma skill", + "revise this skill", + "skill authoring", + "audit this skill" + ], + "ko": ["스킬 만들어", "스킬 작성", "스킬 수정", "스킬 추가"], + "ja": ["スキルを作成", "スキル作成", "スキルを修正"], + "zh": ["创建技能", "编写技能", "修改技能"] + } } }, "informationalPatterns": { @@ -3229,7 +1626,7 @@ "wykryto" ] }, - "excludedWorkflows": ["tools", "stack-set", "schedule", "convert"], + "excludedWorkflows": ["stack-set", "schedule", "convert"], "extensionRouting": { "frontend-engineer": [ "tsx", diff --git a/.agents/hooks/core/types.ts b/.agents/hooks/core/types.ts index ec045b95..4502b912 100644 --- a/.agents/hooks/core/types.ts +++ b/.agents/hooks/core/types.ts @@ -147,7 +147,14 @@ export type HookConfig = Record; /** Context passed to every handler alongside the normalized HookInput. */ export interface HandlerCtx { + /** Output dialect / handler identity. */ vendor: Vendor; + /** + * Host to record in state and telemetry when it differs from the dialect + * `vendor`: Copilot and the opencode family (opencode, Kilo) run handlers + * in the Claude dialect. Absent when host and dialect are the same. + */ + host?: string; /** Resolved OMA project root (config and state live under its `.agents/`). */ cwd: string; sid?: string; diff --git a/.agents/hooks/core/vendor-detect.ts b/.agents/hooks/core/vendor-detect.ts index ae36413b..b71de0ea 100644 --- a/.agents/hooks/core/vendor-detect.ts +++ b/.agents/hooks/core/vendor-detect.ts @@ -73,6 +73,9 @@ export function detectVendorFromInput( if (event === "beforeSubmitPrompt") return "cursor"; if (event === "UserPromptSubmit" && codexSessionShape) return "codex"; } else if (kind === "stop") { + if (scriptPath.includes(join(".gemini", "antigravity-cli", "hooks"))) { + return "antigravity"; + } if (env.GROK_WORKSPACE_ROOT) return "grok"; if (env.KIRO_PROJECT_DIR || event === "stop" || hookEventName === "stop") { return "kiro"; @@ -83,6 +86,13 @@ export function detectVendorFromInput( } else { // pi spawns tool hooks from `.pi/extensions/oma/`; trust that path. if (scriptPath.includes(join(".pi", "extensions"))) return "pi"; + if (scriptPath.includes(join(".gemini", "antigravity-cli", "hooks"))) { + return "antigravity"; + } + const toolCall = input.toolCall as { name?: unknown } | undefined; + if (isAgyInput(input) || typeof toolCall?.name === "string") { + return "antigravity"; + } if (env.GROK_WORKSPACE_ROOT) return "grok"; if (env.KIRO_PROJECT_DIR) return "kiro"; if (event === "preToolUse" || hookEventName === "preToolUse") return "kiro"; diff --git a/.agents/hooks/variants/antigravity.json b/.agents/hooks/variants/antigravity.json index 6560d281..3ff0edbe 100644 --- a/.agents/hooks/variants/antigravity.json +++ b/.agents/hooks/variants/antigravity.json @@ -25,11 +25,33 @@ "timeout": 3 } ], + "PreToolUse": [ + { + "hook": "scm-guard.ts", + "matcher": "run_command", + "timeout": 5 + }, + { + "hook": "code-intelligence-guard.ts", + "matcher": "run_command", + "timeout": 5 + }, + { + "hook": "test-filter.ts", + "matcher": "run_command", + "timeout": 5 + } + ], "PostToolUse": [ { "hook": "refactor-guard.ts", - "matcher": "write_to_file|replace_file_content|notebook_edit", + "matcher": "write_file|edit_file|write_to_file|replace_file_content|notebook_edit", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "read_file|run_command", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/claude.json b/.agents/hooks/variants/claude.json index 2b1f2d44..253e9595 100644 --- a/.agents/hooks/variants/claude.json +++ b/.agents/hooks/variants/claude.json @@ -56,6 +56,11 @@ "hook": "refactor-guard.ts", "matcher": "Edit|Write|NotebookEdit", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "Skill|Read", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/codex.json b/.agents/hooks/variants/codex.json index 58ba2889..090230fe 100644 --- a/.agents/hooks/variants/codex.json +++ b/.agents/hooks/variants/codex.json @@ -46,6 +46,11 @@ "hook": "refactor-guard.ts", "matcher": "apply_patch|Edit|Write", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "Bash", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/commandcode.json b/.agents/hooks/variants/commandcode.json index fea5bfe6..92779514 100644 --- a/.agents/hooks/variants/commandcode.json +++ b/.agents/hooks/variants/commandcode.json @@ -21,6 +21,11 @@ "hook": "refactor-guard.ts", "matcher": "write|edit", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "activate_skill|read|shell", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/commandcode/oma.ts b/.agents/hooks/variants/commandcode/oma.ts new file mode 100644 index 00000000..63615523 --- /dev/null +++ b/.agents/hooks/variants/commandcode/oma.ts @@ -0,0 +1,393 @@ +/** + * oh-my-agent — Command Code (commandcode.ai) mod bridge. + * + * SSOT source. `oma emit --target commandcode-mod` copies this file to + * `commandcode-mod/mods/oma.ts`, the entry `package.json#commandcode.mods` + * lists, so `cmd mods add oh-my-agent-commandcode` (or a local path) loads it. + * + * Command Code's settings-file hooks (`.agents/hooks/variants/commandcode.json`) + * cover SessionStart / PostToolUse / Stop only — there is no prompt-submit + * hook. A mod sees the full lifecycle through `cmd.hooks({...})`, so this + * bridge maps the Command Code ModApi hooks onto oma's vendor-agnostic core + * handlers the same way the opencode bridge does: every handler runs as a + * subprocess of the installed `oma` CLI (`oma hook script --vendor commandcode + * --script `), which answers in the commandcode dialect (Claude-shaped + * JSON: `hookSpecificOutput.additionalContext`, `updatedInput`, + * `permissionDecision`, `{decision: "block", reason}`). Extraction is + * defensive (top-level OR `hookSpecificOutput`). + * + * Dependency-free: no `@commandcode/harness` import (the types are bundled + * with the CLI, not installable), and the ModApi shape is satisfied + * structurally. Fail-open everywhere: a missing `oma` binary, a timeout or + * malformed output leaves the host unchanged. Command Code also catches a + * throwing hook (`mod_error`), so nothing here can crash a session. + * + * Hook mapping: + * transformInput ← UserPromptSubmit + * Runs keyword-detector + skill-injector on the typed prompt and stashes + * the returned context. Returns `{action: "continue"}` — the prompt + * itself is never rewritten. + * appendSystemPrompt ← context injection + * Appends the stashed session-start and prompt context to the system + * prompt. The value only changes when a new prompt is typed or a session + * starts, so it stays byte-stable across the rounds of one run (the + * provider prompt cache keys off the bytes). + * onSessionStart ← SessionStart + * Runs code-intelligence-primer + state-boundary (the commandcode + * SessionStart chain) and stashes their context. + * beforeToolCall ← PreToolUse (shell_command only) + * scm-guard first: a deny becomes `{block: true, additionalContext}` + * (the reason becomes the tool result the model sees). Then test-filter + * rewrites test-runner invocations via `{input: {...input, command}}`. + * afterToolCall ← PostToolUse (skill-route, observation only) + * Records a skill load: `activate_skill`, or a SKILL.md read through + * `read_file` / `read_multiple_files` / `shell_command`. Never alters the + * result. A project whose settings-file PostToolUse hook also runs + * skill-route records the load once: routes dedup per vendor session. + * onStop ← Stop (persistent-mode) + * Runs persistent-mode; a block decision becomes `{continue: true, + * reason}` — Command Code's documented force-continue channel (capped at + * 8 consecutive continuations by the host; persistent-mode's own + * reinforcement cap terminates first). The run-end hook cannot alter + * the result, so it is not used for this. + */ + +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +/** persistent-mode may run a goal stop gate (25s cap); the rest keep 5s. */ +const PERSISTENT_MODE_TIMEOUT_MS = 30_000; +const DEFAULT_TIMEOUT_MS = 5_000; + +/** Command Code's shell tool (`cmd mods inspect` and the bundled examples). */ +const SHELL_TOOLS = new Set(["shell_command", "bash"]); + +/** Tools that can load a skill: the native skill tool, file reads, shell. */ +const SKILL_LOAD_TOOLS = new Set([ + "activate_skill", + "read_file", + "read_multiple_files", + ...SHELL_TOOLS, +]); + +// ── Structural ModApi subset ────────────────────────────────── + +type TransformInputResult = + | { action: "continue" } + | { action: "transform"; text: string } + | { action: "handled"; message?: string }; + +interface BeforeToolCallResult { + block?: boolean; + additionalContext?: string; + input?: Record; +} + +interface OmaModHooks { + transformInput?: (args: { + text: string; + }) => + | TransformInputResult + | undefined + | Promise; + appendSystemPrompt?: (args: { + state?: unknown; + }) => string | undefined | Promise; + onSessionStart?: (args: { source?: string }) => void | Promise; + beforeToolCall?: (args: { + toolCallId?: string; + toolName: string; + input: Record; + state?: unknown; + }) => + | BeforeToolCallResult + | undefined + | Promise; + afterToolCall?: (args: { + toolCallId?: string; + toolName: string; + input: Record; + isError?: boolean; + state?: unknown; + }) => undefined | Promise; + onStop?: (args: { + state?: unknown; + stopReason?: string; + turnNumber?: number; + lastAssistantText?: string; + }) => + | { continue?: boolean; reason?: string } + | undefined + | Promise<{ continue?: boolean; reason?: string } | undefined>; +} + +/** The ModApi members this bridge touches; the real `ModApi` is a superset. */ +export interface OmaModApi { + cwd?: string; + hooks: (hooks: OmaModHooks) => unknown; + on?: ( + event: string, + handler: (event: Record) => void, + ) => unknown; +} + +// ── Subprocess dispatch ─────────────────────────────────────── + +/** Directory of this mod; exported so test-filter can find filter-test-output.sh. */ +function bridgeDir(): string { + try { + return fileURLToPath(new URL("..", import.meta.url)); + } catch { + return ""; + } +} + +/** + * Run one oma core handler through the installed CLI: JSON on stdin, JSON on + * stdout. Fail-open (null) on any error. `cwd` is the Command Code workspace + * root so the handler resolves the project the same way every other vendor + * does. A non-zero exit (persistent-mode blocks with exit 2) is expected and + * stdout is still parsed. + */ +function runCore( + script: string, + payload: Record, + cwd: string, + timeoutMs = DEFAULT_TIMEOUT_MS, +): Record | null { + try { + const bin = process.env.OMA_BIN || "oma"; + const dir = bridgeDir(); + const res = spawnSync( + bin, + ["hook", "script", "--vendor", "commandcode", "--script", script], + { + input: JSON.stringify(payload), + cwd, + encoding: "utf-8", + timeout: timeoutMs, + maxBuffer: 4 * 1024 * 1024, + env: dir ? { ...process.env, OMA_HOOK_BRIDGE_DIR: dir } : process.env, + // A bare binary name on Windows resolves through PATHEXT (`oma.cmd`, + // `oma.exe`) only via the shell; the args are fixed literals. + shell: process.platform === "win32" && !/[\\/]/.test(bin), + }, + ); + const out = (res.stdout ?? "").trim(); + if (!out) return null; + return JSON.parse(out) as Record; + } catch { + return null; + } +} + +// ── Dialect extraction ──────────────────────────────────────── + +function extractAdditionalContext( + out: Record | null, +): string | null { + if (!out) return null; + if (typeof out.additionalContext === "string" && out.additionalContext) { + return out.additionalContext; + } + const hso = out.hookSpecificOutput; + if (hso && typeof hso === "object") { + const nested = (hso as Record).additionalContext; + if (typeof nested === "string" && nested) return nested; + } + return null; +} + +function extractUpdatedInput( + out: Record | null, +): Record | null { + if (!out) return null; + const read = (v: unknown): Record | null => + v && typeof v === "object" && !Array.isArray(v) + ? (v as Record) + : null; + const direct = read(out.updatedInput); + if (direct) return direct; + const hso = out.hookSpecificOutput; + if (hso && typeof hso === "object") { + return read((hso as Record).updatedInput); + } + return null; +} + +function extractDenyReason(out: Record | null): string | null { + if (!out) return null; + const hso = out.hookSpecificOutput; + if (hso && typeof hso === "object") { + const h = hso as Record; + if (h.permissionDecision === "deny") { + return typeof h.permissionDecisionReason === "string" && + h.permissionDecisionReason + ? h.permissionDecisionReason + : "Blocked by oma scm-guard."; + } + } + if (out.permission === "deny" || out.decision === "deny") { + const reason = out.user_message ?? out.reason; + return typeof reason === "string" && reason + ? reason + : "Blocked by oma scm-guard."; + } + return null; +} + +// ── Mod factory ─────────────────────────────────────────────── + +/** + * oh-my-agent Command Code mod. + * + * @satisfies ModFactory + */ +export default function omaMod(cmd: OmaModApi): void { + const cwd = cmd.cwd || process.cwd(); + + // The host session id arrives on `run_start` (and `session_start`), which + // fire AFTER the first transformInput. persistent-mode state is keyed by + // session, so the id is locked at first dispatch: a real id learned before + // then wins, otherwise a per-process fallback keeps every handler of this + // session on one key. + const fallbackSessionId = `commandcode-${process.pid}-${Date.now().toString(36)}`; + let hostSessionId = ""; + let lockedSessionId = ""; + const sessionId = (): string => { + if (!lockedSessionId) lockedSessionId = hostSessionId || fallbackSessionId; + return lockedSessionId; + }; + const learnSessionId = (event: Record): void => { + const id = event.sessionId; + if (typeof id === "string" && id && !hostSessionId) hostSessionId = id; + }; + try { + cmd.on?.("run_start", learnSessionId); + cmd.on?.("session_start", learnSessionId); + } catch { + // Observation only — never fail the factory. + } + + let sessionContext = ""; + let promptContext = ""; + + cmd.hooks({ + onSessionStart: ({ source }) => { + const payload = { + prompt: "", + cwd, + sessionId: sessionId(), + hook_event_name: "SessionStart", + ...(source ? { source } : {}), + }; + const parts: string[] = []; + for (const script of [ + "code-intelligence-primer.ts", + "state-boundary.ts", + ]) { + const ctx = extractAdditionalContext(runCore(script, payload, cwd)); + if (ctx) parts.push(ctx); + } + sessionContext = parts.join("\n\n"); + }, + + transformInput: ({ text }) => { + const payload = { + prompt: text, + cwd, + sessionId: sessionId(), + hook_event_name: "UserPromptSubmit", + }; + const parts: string[] = []; + for (const script of ["keyword-detector.ts", "skill-injector.ts"]) { + const ctx = extractAdditionalContext(runCore(script, payload, cwd)); + if (ctx) parts.push(ctx); + } + // Overwrite — even with "" — so a previous prompt's context is never + // re-injected for this one. + promptContext = parts.join("\n\n"); + return { action: "continue" }; + }, + + appendSystemPrompt: () => { + const joined = [sessionContext, promptContext] + .filter(Boolean) + .join("\n\n"); + return joined || undefined; + }, + + beforeToolCall: ({ toolName, input }) => { + if (!SHELL_TOOLS.has(toolName)) return undefined; + const command = input?.command; + if (typeof command !== "string" || !command) return undefined; + const payload = { + tool_name: "Bash", + tool_input: { command }, + cwd, + sessionId: sessionId(), + hook_event_name: "PreToolUse", + }; + + const denyReason = extractDenyReason( + runCore("scm-guard.ts", payload, cwd), + ); + if (denyReason) return { block: true, additionalContext: denyReason }; + + const updated = extractUpdatedInput( + runCore("test-filter.ts", payload, cwd), + ); + const rewritten = updated?.command; + if (typeof rewritten === "string" && rewritten && rewritten !== command) { + return { input: { ...input, command: rewritten } }; + } + return undefined; + }, + + afterToolCall: ({ toolName, input, isError }) => { + if (isError || !SKILL_LOAD_TOOLS.has(toolName)) return undefined; + // Spawn only for a skill tool or an input that names a SKILL.md. + if (toolName !== "activate_skill") { + try { + if (!JSON.stringify(input ?? {}).includes("SKILL.md")) { + return undefined; + } + } catch { + return undefined; + } + } + runCore( + "skill-route.ts", + { + tool_name: toolName, + tool_input: input ?? {}, + cwd, + sessionId: sessionId(), + hook_event_name: "PostToolUse", + }, + cwd, + ); + return undefined; + }, + + onStop: ({ lastAssistantText }) => { + const pm = runCore( + "persistent-mode.ts", + { + cwd, + sessionId: sessionId(), + hook_event_name: "Stop", + ...(lastAssistantText ? { response: lastAssistantText } : {}), + }, + cwd, + PERSISTENT_MODE_TIMEOUT_MS, + ); + if (pm?.decision !== "block") return undefined; + const reason = + typeof pm.reason === "string" && pm.reason + ? pm.reason + : "The active OMA workflow is not complete. Continue executing it."; + return { continue: true, reason }; + }, + }); +} diff --git a/.agents/hooks/variants/copilot.json b/.agents/hooks/variants/copilot.json new file mode 100644 index 00000000..6756b2f8 --- /dev/null +++ b/.agents/hooks/variants/copilot.json @@ -0,0 +1,78 @@ +{ + "$schema": "./hook-variant.schema.json", + "vendor": "copilot", + "style": "copilot", + "hookDir": ".github/hooks", + "settingsFile": ".github/hooks/oma.json", + "projectDirEnv": null, + "runtime": "bun", + "events": { + "SessionStart": [ + { + "hook": "code-intelligence-primer.ts", + "timeout": 3 + }, + { + "hook": "state-boundary.ts", + "timeout": 5 + } + ], + "UserPromptSubmit": [ + { + "hook": "keyword-detector.ts", + "timeout": 5 + }, + { + "hook": "state-boundary.ts", + "timeout": 5 + }, + { + "hook": "skill-injector.ts", + "timeout": 3 + }, + { + "hook": "code-intelligence-primer.ts", + "timeout": 3 + } + ], + "PreToolUse": [ + { + "hook": "scm-guard.ts", + "matcher": "Bash", + "timeout": 3 + }, + { + "hook": "code-intelligence-guard.ts", + "matcher": "Grep|Glob", + "timeout": 2 + }, + { + "hook": "test-filter.ts", + "matcher": "Bash", + "timeout": 5 + } + ], + "PostToolUse": [ + { + "hook": "refactor-guard.ts", + "matcher": "Edit|Write", + "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "skill|Read|Bash", + "timeout": 3 + } + ], + "Stop": [ + { + "hook": "persistent-mode.ts", + "timeout": 30 + }, + { + "hook": "refactor-guard.ts", + "timeout": 5 + } + ] + } +} diff --git a/.agents/hooks/variants/cursor.json b/.agents/hooks/variants/cursor.json index 6fee10a1..8a2d84d7 100644 --- a/.agents/hooks/variants/cursor.json +++ b/.agents/hooks/variants/cursor.json @@ -48,6 +48,13 @@ "timeout": 5 } ], + "postToolUse": [ + { + "hook": "skill-route.ts", + "matcher": "Read|Shell", + "timeout": 3 + } + ], "stop": [ { "hook": "persistent-mode.ts", diff --git a/.agents/hooks/variants/grok.json b/.agents/hooks/variants/grok.json index 2684be0b..61c808bf 100644 --- a/.agents/hooks/variants/grok.json +++ b/.agents/hooks/variants/grok.json @@ -44,8 +44,13 @@ "PostToolUse": [ { "hook": "refactor-guard.ts", - "matcher": "hashline_edit|apply_patch|create_file|write_file|edit_file|str_replace", + "matcher": "search_replace|write|hashline_edit|apply_patch|create_file|write_file|edit_file|str_replace", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "read_file|hashline_read|run_terminal_command|run_terminal_cmd", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/hook-variant.schema.json b/.agents/hooks/variants/hook-variant.schema.json index 4ac20566..e98b2f1d 100644 --- a/.agents/hooks/variants/hook-variant.schema.json +++ b/.agents/hooks/variants/hook-variant.schema.json @@ -19,6 +19,7 @@ "claude", "codex", "commandcode", + "copilot", "cursor", "grok", "kimi", @@ -26,6 +27,11 @@ "qwen" ] }, + "style": { + "type": "string", + "enum": ["copilot"], + "description": "Write the vendor-native flat hook file instead of the default nested settings merge." + }, "hookDir": { "type": "string", "description": "Relative path to the vendor's hooks directory (e.g., .claude/hooks)." @@ -68,8 +74,21 @@ "minProperties": 1 }, "statusLine": { - "$ref": "#/$defs/hookRef", - "description": "Hook script for the status line display (Claude / agy use root statusLine; Qwen nests under ui via statusLineKey)." + "type": "object", + "description": "Hook script for the status line display (Claude / agy use root statusLine; Qwen nests under ui via statusLineKey).", + "required": ["hook"], + "additionalProperties": false, + "properties": { + "hook": { + "type": "string", + "description": "Filename of the hook script in .agents/hooks/core/." + }, + "options": { + "type": "object", + "description": "Extra vendor statusLine fields written alongside type/command (e.g. Qwen respectUserColors, hideContextIndicator).", + "additionalProperties": true + } + } }, "statusLineKey": { "type": "string", @@ -110,9 +129,9 @@ }, "timeout": { "type": "integer", - "description": "Max execution time in seconds.", + "description": "Max execution time in seconds. The persistent-mode Stop hook runs a completion gate capped at GATE_TIMEOUT_MS (60s), so its entry MUST exceed that plus margin (70s); the contract test in cli/__tests__/hooks-persistent-mode.test.ts enforces timeout*1000 > GATE_TIMEOUT_MS. Other hooks stay small.", "minimum": 1, - "maximum": 30, + "maximum": 120, "default": 5 }, "loopLimit": { diff --git a/.agents/hooks/variants/kimi.json b/.agents/hooks/variants/kimi.json index 42046b51..6576ffa7 100644 --- a/.agents/hooks/variants/kimi.json +++ b/.agents/hooks/variants/kimi.json @@ -45,8 +45,13 @@ "PostToolUse": [ { "hook": "refactor-guard.ts", - "matcher": "WriteFile|StrReplaceFile", + "matcher": "Write|Edit", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "Skill|Read|Bash", + "timeout": 3 } ], "Stop": [ diff --git a/.agents/hooks/variants/kiro.json b/.agents/hooks/variants/kiro.json index 024f24b5..6d3e244e 100644 --- a/.agents/hooks/variants/kiro.json +++ b/.agents/hooks/variants/kiro.json @@ -45,8 +45,13 @@ "postToolUse": [ { "hook": "refactor-guard.ts", - "matcher": "fs_write", + "matcher": "fs_write|str_replace|fs_append", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "fs_read|read_file|execute_bash|disclose_context", + "timeout": 3 } ], "stop": [ diff --git a/.agents/hooks/variants/opencode/index.ts b/.agents/hooks/variants/opencode/index.ts new file mode 100644 index 00000000..09173ff4 --- /dev/null +++ b/.agents/hooks/variants/opencode/index.ts @@ -0,0 +1,146 @@ +/** + * oh-my-agent — opencode-family npm package entry (`oh-my-agent-opencode`). + * + * SSOT source. `oma emit --target opencode-package` ships this file as the + * package `main`/`exports` next to the bridge (`./oma.ts`) and the handler + * entries it spawns. The opencode per-project / global install also copies it + * to `plugins/oma/index.ts`: OpenCode 2.x rejects the configured + * `./plugins/oma/oma.ts` file path and loads that auto-discovered directory + * through this entry instead, while 1.x keeps loading `oma.ts` (its + * discovery is flat, so the nested entry is never loaded twice). + * + * Two plugin contracts coexist in the family, and a package plugin must + * satisfy whichever host imports it: + * + * - OpenCode 2.x (opencode.ai/docs/build/plugins): the default export is a + * definition `{ id, setup(ctx) }` (`Plugin.define` is the identity). Hooks + * are registered through context domains — `ctx.session.hook("prompt" | + * "context" | "experimental.idle")`, `ctx.tool.hook("execute.before")`. + * A function default export is rejected ("Plugin must export a default + * definition with an id and an effect or setup function"). + * - Kilo Code CLI (7.x) and OpenCode 1.18.29+: a package plugin "must + * default export an object with server()" — the V1 object form. `server` + * receives the same `{ project, client, $, directory, worktree }` input + * the function-style bridge takes and returns the hooks object. (Older 1.x + * loaders that only accept a bare function export are not served by the + * package; they still work with the per-project `./plugins/oma/oma.ts`.) + * + * So the default export carries both: `server` (the unchanged legacy bridge, + * called by the V1 loaders) and `id` + `setup` (the v2 definition, whose + * `setup` adapts the v2 events onto that same legacy hooks object) — one + * bridge implementation, zero duplicated handler logic. Dependency-free: the + * v2 context is typed structurally, so neither `@opencode/plugin` nor + * `@opencode-ai/plugin` is needed at runtime. + * + * v2 mapping (→ legacy hook the bridge already implements): + * session "prompt" → "chat.message" (keyword-detector, skill-injector) + * session "context" → "experimental.chat.system.transform" (inject) + * tool "execute.before" → "tool.execute.before" (scm-guard, test-filter; + * a throw rejects the call, as in v1) + * session "experimental.idle" → event session.idle (persistent-mode re-entry + * through ctx.session.prompt) + * tool "execute.after" → "tool.execute.after" (skill-route; completed + * calls only, `input` passed as `args`) + */ + +import legacy from "./oma.ts"; + +type LegacyHooks = Awaited>; + +/** Structural subset of the OpenCode 2.x plugin context this entry uses. */ +interface OmaV2Context { + location?: { directory?: string }; + session: { + hook: ( + name: string, + callback: (event: Record) => Promise | void, + ) => Promise; + prompt?: (input: Record) => Promise; + }; + tool: { + hook: ( + name: string, + callback: (event: Record) => Promise | void, + ) => Promise; + }; +} + +function sessionIDOf(event: Record): string | undefined { + return typeof event.sessionID === "string" ? event.sessionID : undefined; +} + +/** + * The package plugin. V1 object loaders (Kilo, OpenCode 1.18.29+) call + * `server(input)` and use the returned hooks; OpenCode 2.x reads `id` and + * calls `setup(ctx)`, which instantiates the legacy bridge with a client + * adapter (so session.idle re-entry posts through `ctx.session.prompt`) and + * registers one v2 hook per legacy handler. + */ +export default { + id: "oh-my-agent", + server: legacy, + async setup(ctx: OmaV2Context): Promise { + const directory = ctx.location?.directory ?? process.cwd(); + const hooks: LegacyHooks = await legacy({ + directory, + client: { + session: { + prompt: async ({ path, body }) => { + if (!ctx.session.prompt) return; + await ctx.session.prompt({ + sessionID: path.id, + text: body.parts.map((part) => part.text).join("\n"), + }); + }, + }, + }, + }); + + await ctx.session.hook("prompt", async (event) => { + const sessionID = sessionIDOf(event); + const prompt = event.prompt as { text?: unknown } | undefined; + const text = typeof prompt?.text === "string" ? prompt.text : ""; + await hooks["chat.message"]( + { sessionID }, + { parts: [{ type: "text", text }] }, + ); + }); + + await ctx.session.hook("context", async (event) => { + const sessionID = sessionIDOf(event); + const out: { system: string[] } = { system: [] }; + await hooks["experimental.chat.system.transform"]({ sessionID }, out); + const system = event.system; + if (!Array.isArray(system)) return; + for (const text of out.system) system.push({ type: "text", text }); + }); + + await ctx.tool.hook("execute.before", async (event) => { + const input = event.input; + if (!input || typeof input !== "object") return; + // The legacy hook mutates `output.args.command`; `args` IS the v2 + // input object, so a test-filter rewrite lands on the real call. + await hooks["tool.execute.before"]( + { tool: typeof event.tool === "string" ? event.tool : undefined }, + { args: input as { command?: string } }, + ); + }); + + await ctx.tool.hook("execute.after", async (event) => { + if (event.status !== "completed") return; + await hooks["tool.execute.after"]({ + tool: typeof event.tool === "string" ? event.tool : undefined, + sessionID: sessionIDOf(event), + args: event.input, + }); + }); + + await ctx.session.hook("experimental.idle", async (event) => { + const sessionID = sessionIDOf(event); + if (!sessionID) return; + await hooks.event({ + event: { type: "session.idle", properties: { sessionID } }, + }); + }); + }, +}; diff --git a/.agents/hooks/variants/opencode/oma.ts b/.agents/hooks/variants/opencode/oma.ts index c21e80d7..5b2739c9 100644 --- a/.agents/hooks/variants/opencode/oma.ts +++ b/.agents/hooks/variants/opencode/oma.ts @@ -49,6 +49,10 @@ * Known upstream caveat: plugin hooks do not intercept subagent tool * calls (anomalyco/opencode#5894), so the guard covers the primary * agent only. + * tool.execute.after ← PostToolUse (skill-route) + * Observation only: records a skill load (`skill` tool, or a SKILL.md + * read through `read` / `bash`). Needs `input.args` (opencode 1.1.62+, + * Kilo); never mutates the output. * event: "session.idle" ← Stop (BEST-EFFORT / re-entrant) * Runs persistent-mode. If it returns a block decision, the workflow is * still active: re-enter the loop by posting the block reason as a new @@ -68,11 +72,33 @@ import { fileURLToPath } from "node:url"; */ const PERSISTENT_MODE_TIMEOUT_MS = 30_000; +/** + * Tools that can load a skill: the native `skill` tool, `read`, and the shell + * (`bash` on opencode 1.x / Kilo, `shell` on opencode 2.x). + */ +const SKILL_LOAD_TOOLS = new Set(["skill", "read", "bash", "shell"]); + /** Absolute path to a core script copied next to this bridge at install time. */ function corePath(script: string): string { return fileURLToPath(new URL(`./${script}`, import.meta.url)); } +/** + * Directory of this bridge, exported to the handlers as OMA_HOOK_BRIDGE_DIR so + * test-filter finds `filter-test-output.sh` when the bridge ships as the + * `oh-my-agent-opencode` npm package (outside the project tree). + */ +function bridgeEnv(): NodeJS.ProcessEnv { + try { + return { + ...process.env, + OMA_HOOK_BRIDGE_DIR: fileURLToPath(new URL(".", import.meta.url)), + }; + } catch { + return process.env; + } +} + /** * Run an oma core hook script as a subprocess: feed it JSON on stdin, parse * its JSON stdout. Fail-open (returns null) on any error — a broken hook must @@ -93,7 +119,7 @@ function runCore( cwd, encoding: "utf-8", timeout: timeoutMs, - env: process.env, + env: bridgeEnv(), }); const out = (res.stdout ?? "").trim(); if (!out) return null; @@ -387,6 +413,50 @@ export default (async ({ } }, + /** + * tool.execute.after ← PostToolUse (skill-route, observation only) + * + * Records which skill the model loaded: the native `skill` tool, or a + * SKILL.md opened through `read` / `bash` (`shell` on opencode 2.x). + * Spawns only for those tools when the arguments can name a skill, since + * every tool call passes through here. Fail-open and never mutates output. + */ + "tool.execute.after": async (input: { + tool?: string; + sessionID?: string; + args?: unknown; + }): Promise => { + const tool = input.tool; + if (!tool || !SKILL_LOAD_TOOLS.has(tool)) return; + const args = input.args; + if (!args || typeof args !== "object" || Array.isArray(args)) return; + if (tool !== "skill") { + let serialized = ""; + try { + serialized = JSON.stringify(args); + } catch { + return; + } + if ( + !serialized.includes("SKILL.md") && + !serialized.includes("skill://") + ) { + return; + } + } + runCore( + "skill-route.ts", + { + tool_name: tool, + tool_input: args, + cwd, + sessionId: input.sessionID ?? "", + hook_event_name: "PostToolUse", + }, + cwd, + ); + }, + /** * event: "session.idle" ← Stop (BEST-EFFORT / re-entrant) * diff --git a/.agents/hooks/variants/pi/index.ts b/.agents/hooks/variants/pi/index.ts index e99e66e1..875a8f51 100644 --- a/.agents/hooks/variants/pi/index.ts +++ b/.agents/hooks/variants/pi/index.ts @@ -17,6 +17,7 @@ * Event mapping (see README.md): * before_agent_start ← UserPromptSubmit (keyword-detector + skill-injector) * tool_call (bash) ← PreToolUse (scm-guard + test-filter) + * tool_result ← PostToolUse (skill-route, observation only) * agent_settled ← Stop (persistent-mode + re-entry) * * tool_call blocking: a handler that returns `{ block: true, reason }` blocks @@ -205,6 +206,38 @@ export default function omaHooks(pi: ExtensionAPI): void { return undefined; }); + // tool_result ← PostToolUse. skill-route records a skill load: pi has no + // skill tool, so the model loads a skill body by `read` (or `bash`) on its + // SKILL.md. Observation only — the result is never altered. Spawns only when + // the input names a SKILL.md, since every tool call passes through here. + try { + pi.on("tool_result", async (event, ctx) => { + try { + if (event.isError) return undefined; + if (event.toolName !== "read" && event.toolName !== "bash") { + return undefined; + } + const input = event.input as Record | undefined; + if (!input || !JSON.stringify(input).includes("SKILL.md")) { + return undefined; + } + const sessionId = sessionIdOf(ctx); + runCore("skill-route.ts", { + tool_name: event.toolName, + tool_input: input, + cwd: process.cwd(), + hook_event_name: "PostToolUse", + ...(sessionId ? { sessionId } : {}), + }); + } catch { + // Observation only: never fail a tool result. + } + return undefined; + }); + } catch { + // pi build without `tool_result` — skill loads are not recorded there. + } + // agent_settled ← Stop. Persistent-mode re-entry: after a run fully settles, // ask persistent-mode.ts whether a workflow is still active; if so, re-enter // the loop with its reinforcement text. Capability-guarded — pi builds before diff --git a/.agents/hooks/variants/qwen.json b/.agents/hooks/variants/qwen.json index d7a6dd6d..285d07b9 100644 --- a/.agents/hooks/variants/qwen.json +++ b/.agents/hooks/variants/qwen.json @@ -44,8 +44,13 @@ "PostToolUse": [ { "hook": "refactor-guard.ts", - "matcher": "write_file|replace", + "matcher": "write_file|edit|replace|notebook_edit", "timeout": 5 + }, + { + "hook": "skill-route.ts", + "matcher": "skill|read_file|run_shell_command", + "timeout": 3 } ], "Stop": [ @@ -60,13 +65,14 @@ ] }, "statusLine": { - "hook": "hud.ts" + "hook": "hud.ts", + "options": { + "respectUserColors": true, + "hideContextIndicator": true + } }, "statusLineKey": "ui", "extra": { - "hooksConfig": { - "enabled": true - }, "permissions": { "allow": ["Bash(ls *)", "Bash(oma *)"] } diff --git a/.agents/mcp.json b/.agents/mcp.json index bb4327d8..71291e6b 100644 --- a/.agents/mcp.json +++ b/.agents/mcp.json @@ -44,34 +44,5 @@ "write": "Write", "edit": "Edit" } - }, - "toolGroups": { - "code-analysis": [ - "get_symbols_overview", - "find_symbol", - "find_referencing_symbols", - "find_implementations", - "find_declaration", - "search_for_pattern" - ], - "code-edit": [ - "replace_symbol_body", - "insert_after_symbol", - "insert_before_symbol", - "rename_symbol", - "safe_delete_symbol", - "replace_in_files" - ], - "file-ops": [ - "list_dir", - "find_file" - ], - "all": null, - "code-diagnostics": [ - "get_diagnostics_for_file" - ], - "serena-support": [ - "initial_instructions" - ] } } diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 00000000..c3c0cd97 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,57 @@ +{ + "name": "oh-my-agent", + "interface": { + "displayName": "oh-my-agent", + "shortDescription": "oh-my-agent-workspace" + }, + "plugins": [ + { + "name": "oma", + "source": { + "source": "local", + "path": "./" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" + }, + { + "name": "oma-frontend", + "source": { + "source": "local", + "path": "./.claude-plugin/domains/frontend" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" + }, + { + "name": "oma-security", + "source": { + "source": "local", + "path": "./.claude-plugin/domains/security" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" + }, + { + "name": "oma-research", + "source": { + "source": "local", + "path": "./.claude-plugin/domains/research" + }, + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" + } + ] +} diff --git a/.agents/rules/backend.md b/.agents/rules/backend.md deleted file mode 100644 index 93257202..00000000 --- a/.agents/rules/backend.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -description: Backend API coding standards with clean architecture (Router/Service/Repository pattern) -globs: -alwaysApply: false ---- - -# Backend Coding Standards - -## Core Rules - -1. **Clean architecture**: router -> service -> repository -> models -2. **No business logic in route handlers** -3. **All inputs validated** with your stack's validation library -4. **Parameterized queries only** (never string interpolation) -5. **JWT + Argon2id for auth** (bcrypt acceptable for legacy compatibility); rate limit auth endpoints -6. **Async where supported**; type annotations on all signatures -7. **Custom exceptions** via centralized error module (not raw HTTP exceptions) -8. **Explicit ORM loading strategy**: do not rely on default relation loading when query shape matters -9. **Explicit transaction boundaries**: group one business operation into one request/service-scoped unit of work -10. **Safe ORM lifecycle**: do not share mutable ORM session/entity manager across concurrent work unless ORM explicitly supports it -11. **Config from environment, with graceful fallback**: DB URLs, API keys, secrets from env vars or secret managers, never hardcode. When integrating a third-party API (OpenAI, Anthropic, Stripe, etc.), write BOTH paths: (a) real call when `process.env.` is present, (b) deterministic local fallback when absent. Mark the deferred branch with `// TODO(oma-deferred): integrate when key is provisioned`. Shipping only the fallback (no env-conditional branch) leaves the spec unmet; shipping only the real call without fallback breaks demos when the key is missing. -12. **Stateless services**: no in-memory session or user state between requests — use external stores -13. **Backing services as resources**: DB, queue, cache are swappable resources connected via config - -## Architecture - -``` -Router (HTTP) → Service (Business Logic) → Repository (Data Access) → Models -``` - -## Principles - -- **DRY**: Business logic in Service, data access in Repository -- **Single Responsibility**: Classes and functions should have one responsibility -- **Dependency Inversion**: Use your framework's DI mechanism -- **KISS**: Keep it simple and clear diff --git a/.agents/rules/commit.md b/.agents/rules/commit.md deleted file mode 100644 index ccc4b1c1..00000000 --- a/.agents/rules/commit.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -description: Conventional Commits specification and git commit workflow rules -globs: -alwaysApply: false ---- - -# Commit Standards - -## Format - -``` -(): - -[optional body] -``` - -**Types**: feat, fix, refactor, docs, test, chore, style, perf, build, ci, revert - -## Rules - -1. **Analyze changes** before committing -2. **Split by feature** if changes span multiple domains -3. **Description** under 72 characters, imperative mood, lowercase, no trailing period -4. **Never** use `git add -A` or `git add .` without explicit permission -5. **Never** commit files that may contain secrets (.env, credentials) -6. **Always** use specific file names when staging -7. Split commits when: different scopes, different types, logically independent changes -8. Do NOT split when: all changes belong to a single feature, few files (5 or fewer) -9. Precedence: logical independence decides first (one logical change = one commit); file count (5 or fewer) is only a tiebreaker; an explicit user instruction overrides both diff --git a/.agents/rules/database.md b/.agents/rules/database.md index 0a0e57a1..77198fbb 100644 --- a/.agents/rules/database.md +++ b/.agents/rules/database.md @@ -11,17 +11,19 @@ alwaysApply: false 1. Choose model first, engine second: workload, access pattern, consistency, and scale drive DB selection. 2. For relational workloads, enforce at least **3NF** by default. Break 3NF only with explicit performance justification. 3. For distributed/non-relational workloads, model around aggregates and access paths; document **BASE** and consistency tradeoffs. -4. Document **ACID** expectations for relational transactions. For distributed tradeoffs, document consistency compromises explicitly. -5. For schema architecture work, document the relevant schema layers: **external schema**, **conceptual schema**, **internal schema**. +4. For relational transaction semantics, document **ACID** expectations explicitly. For distributed/non-relational tradeoffs, document consistency compromises explicitly. +5. For full schema design, document external, conceptual and internal schema views. For a scoped index/query/model change, update only the affected existing views. 6. Treat integrity as first-class: entity, domain, referential, and business-rule integrity must be explicit. 7. Concurrency is never implicit: define transaction boundaries, locking strategy, and isolation level per critical flow. -8. For new or changed data models, specify: naming, definition, format, allowed values, and validation rules. -9. Update the affected schema decisions and data definitions; add capacity estimates when the task changes capacity requirements. +8. Apply existing data standards; add relevant naming, definition, format and validation rules for newly modeled data. +9. Update affected existing glossary, decision and capacity artifacts when the change alters their assumptions. A query-only task does not require new modeling documents. 10. Proactively flag anti-patterns and insecure shortcuts instead of silently implementing them. -11. Vector DBs are retrieval infrastructure, not source-of-truth databases. Store embeddings and metadata there; keep canonical documents elsewhere. -12. Never treat vector search as a drop-in for lexical search. Default to hybrid retrieval when exact match or explainability matters. -13. Embeddings are schema-like assets: version model, dimension, chunking, and preprocessing. Plan re-embedding migrations explicitly. -14. Schema or data changes on live tables follow expand-contract: additive expand, dual-write + batched backfill, verified read switch, delayed contract. Use lock-aware DDL with timeouts; ship destructive steps in a separate deploy after a soak window. -15. Tune queries from measurement and execution plans, never guesswork: measure, explain, nominate the dominant cost node, optimize, re-measure p95. -16. Strongly recommend explicit application ownership of business policies, workflows, and external side effects in both new and existing triggers, stored procedures/functions, views, DB jobs, and ORM hooks. For affected existing logic, give a concrete alternative and transition priority; existing convention alone does not justify retention. Use `.agents/skills/oma-db/resources/anti-patterns.md` §5 for review and technical retention criteria. This is a strong recommendation, not a blanket feature ban or authorization for an unrelated rewrite. -17. Preserve DB integrity constraints, atomic updates, transactions/isolation/locking, RLS and privileges, DB audit, justified dependent cascades, and efficient set-based operations. For an accepted transition, follow `.agents/skills/oma-db/resources/migration-playbook.md` to cover every writer, prevent duplicate side effects, and define rollback. +11. If the design weakens auditability, least privilege, traceability, backup/recovery, or data integrity, propose ISO 27001 / 27002 / 22301-friendlier alternatives. +12. Vector DBs are retrieval infrastructure, not source-of-truth databases. Store embeddings and lightweight metadata there; keep canonical documents elsewhere. +13. Never treat vector search as a drop-in replacement for lexical search. Default to hybrid retrieval when exact match, compliance filtering, or explainability matters. +14. Embeddings are schema-like assets: version model, dimension, chunking, and preprocessing, and plan re-embedding migrations explicitly. +15. Retrieval quality is won at chunking, filtering, reranking, and observability, not only at the vector index layer. +16. Schema or data changes on live tables follow expand-contract (parallel change): additive expand, dual-write + batched backfill, verified read switch, delayed contract. DDL on hot tables is lock-aware with timeouts; destructive steps ship in a separate deploy after a soak window. +17. Query tuning starts from measurement and execution plans, never guesswork: measure, explain, nominate the dominant cost node, then optimize and re-measure. +18. Strongly recommend explicit application ownership of business policies, workflows, and external side effects in both new and existing triggers, stored procedures/functions, views, DB jobs, and ORM hooks. For affected existing logic, give a concrete alternative and transition priority; existing convention alone does not justify retention. This is a strong recommendation, not a blanket feature ban or authorization for an unrelated rewrite. +19. Preserve DB integrity constraints, atomic updates, transactions/isolation/locking, RLS and privileges, DB audit, justified dependent cascades, and efficient set-based operations. For an accepted transition, cover every writer, prevent duplicate side effects, and define rollback. diff --git a/.agents/rules/debug.md b/.agents/rules/debug.md deleted file mode 100644 index 4f0d5b6a..00000000 --- a/.agents/rules/debug.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -description: Bug diagnosis and fixing standards - root cause analysis, minimal fixes, regression tests -globs: -alwaysApply: false ---- - -# Debug Standards - -## Core Rules - -1. **Reproduce first**, then diagnose — never guess at fixes -2. **Identify root cause**, not just symptoms -3. **Minimal fix**: change only what's necessary -4. **Every fix gets a regression test** -5. Search for **similar patterns elsewhere** after fixing diff --git a/.agents/rules/design.md b/.agents/rules/design.md deleted file mode 100644 index 03280efa..00000000 --- a/.agents/rules/design.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -description: Design system, typography, color, accessibility (WCAG 2.2), responsive-first layout, and motion design standards -globs: -alwaysApply: false ---- - -# Design Standards - -## Core Rules - -1. System font stack as default (`system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`). Add custom fonts only with project justification. -2. If the service supports CJK languages: prioritize CJK-ready fonts (Pretendard Variable > Noto Sans CJK > system-ui fallback). -3. Name colors semantically with hex values: "Deep Ocean Navy (#1a2332)" not "dark blue". -4. Recommend components with install commands (shadcn CLI). -5. ALL output must be responsive-first (mobile layout as default, enhance upward). -6. WCAG AA minimum for all designs. -7. Present directions when design exploration is requested or a material direction is unresolved; reuse an already chosen direction. - -## Anti-Patterns to Avoid - -- **Typography**: Don't default to custom Google Fonts; body text minimum 16px on mobile; test CJK at every size -- **Color**: Avoid purple-to-blue gradient backgrounds; avoid gradient orbs/blobs; use solid colors or subtle single-hue gradients -- **Layout**: 8px grid; works at 375px minimum; avoid nested cards inside nested cards -- **Motion**: transform + opacity only for 60fps; 150ms micro-interactions, 200-500ms transitions -- **Components**: Use shadcn/ui for base; all interactive elements must have visible focus states diff --git a/.agents/rules/dev-workflow.md b/.agents/rules/dev-workflow.md deleted file mode 100644 index 34b726e1..00000000 --- a/.agents/rules/dev-workflow.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -description: Monorepo developer workflow standards - mise tasks, git hooks, CI/CD, release automation -globs: -alwaysApply: false ---- - -# Developer Workflow Standards - -## Core Rules - -1. Use `mise run` tasks instead of direct package manager commands -2. Run `mise install` after pulling changes that update runtime versions -3. Use parallel tasks for independent operations. Cap concurrency when more workers slow the same suite -4. Run lint and test on changed scope. Keep a selector that fails closed on shared or unknown paths -5. Validate commit messages with commitlint before committing -6. Configure CI to skip unchanged apps for faster builds -7. Check `mise tasks --all` to discover available tasks before running -8. Pin runtime versions in mise.toml for consistency -9. Never use direct package manager commands when mise tasks exist -10. Never modify mise.toml without understanding task dependencies -11. Never hardcode secrets in mise.toml files -12. Never skip reading task definitions before running unfamiliar tasks diff --git a/.agents/rules/frontend.md b/.agents/rules/frontend.md index c01f4ad4..b852f6f9 100644 --- a/.agents/rules/frontend.md +++ b/.agents/rules/frontend.md @@ -15,8 +15,8 @@ Apply framework-specific rules only to that framework. Existing project choices 3. **Rendering Strategy**: Default to Server Components for performance. Use Client Components only for interactivity and API integration. 4. **Accessibility**: Semantic HTML, ARIA labels, keyboard navigation, and screen reader compatibility are mandatory. 5. **Tool First**: Check for existing solutions and tools before coding. -7. **Request proxy convention**: when the target project uses Next.js 16+ with `proxy.ts`, preserve that convention. Check the installed framework version and routing before recommending a file rename. Diagnose wiring from code and tests. -7. **No Prop Drilling**: Avoid passing props beyond 3 levels. Use the project's client-state library (Jotai atoms or a Zustand store — see oma-frontend `resources/tech-stack.md`) instead. Avoid React Context. +6. **Request proxy convention**: when the target project uses Next.js 16+ with `proxy.ts`, preserve that convention. Check the installed framework version and routing before recommending a file rename. Diagnose wiring from code and tests. +7. **No Prop Drilling**: Avoid passing props beyond 3 levels. Use the project's client-state library (Jotai atoms or a Zustand store) instead. Avoid React Context. 8. **Auth Boundary**: Client code must not import database adapters or server-only auth code. Keep server-side application logic in the project's existing server boundary. 9. **Animation library**: preserve the project's existing animation library for scoped edits. For new motion-based implementations, use the `motion` package and `motion/react` imports. 10. **Framework version**: preserve the installed framework and dependency ranges for scoped changes. Select versions when scaffolding or when an upgrade is explicitly requested; do not upgrade an existing app to satisfy a starter default. diff --git a/.agents/rules/i18n-guide.md b/.agents/rules/i18n-guide.md index d10d7fae..e4d68722 100644 --- a/.agents/rules/i18n-guide.md +++ b/.agents/rules/i18n-guide.md @@ -13,8 +13,10 @@ Rules for determining and applying response language across agents and workflows Response language is determined by the following priority: 1. **User prompt language** — if the user writes in a specific language, respond in that language -2. **`oma-config.yaml`** — `language` field in `.agents/oma-config.yaml` -3. **Fallback** — English (en) if neither of the above is set +2. **Configured `language`** — fallback for prompts that carry no language signal (a bare command, code only, or a machine-generated task) +3. **English (en)** — when neither of the above applies + +`language` is a fallback, not an override: it never outranks the language the user writes in. It is also not enforced at runtime — OMA carries it into the generated project instructions (the `AGENTS.md` / `CLAUDE.md` line), and each host agent applies it. The only CLI surface that reads it directly is `oma image` (ko/en console messages); `oma install` uses it as the prompt default. ```yaml # .agents/oma-config.yaml @@ -40,7 +42,6 @@ Workflows that translate user-facing content should respect this setting via the | Natural language responses | Yes | User-facing explanations and descriptions | | Error messages (user-facing) | Yes | Authentication failure messages | | Status updates / progress reports | Yes | "Phase 2 complete, starting Phase 3" | -| Charter Preflight output | Yes | Descriptive text localized, keywords stay in English | | Result files (result-*.md) | Yes | User-readable text | ## What Stays in English @@ -68,10 +69,10 @@ Workflows that translate user-facing content should respect this setting via the ## Workflow Integration -All workflows follow these rules. The following line in existing workflows references this guide: +All workflows follow these rules. The line at the top of each workflow restates the priority: ``` -- **Response language follows `language` setting in `.agents/oma-config.yaml` if configured.** +- **Response language: the user's prompt language first, then `language` in `.agents/oma-config.yaml`, then English.** ``` > ARB-based localization (ARB as the single cross-platform source of truth for diff --git a/.agents/rules/infrastructure.md b/.agents/rules/infrastructure.md index c67308b8..5716e691 100644 --- a/.agents/rules/infrastructure.md +++ b/.agents/rules/infrastructure.md @@ -17,7 +17,7 @@ alwaysApply: false 7. **No Secrets in Code**: Never hardcode passwords, API keys, or tokens in .tf files 8. **Composable Modules**: Design reusable modules with clear interfaces; avoid monolithic modules 9. **Environment Sizing**: Use environment-based sizing (smaller for dev/staging, production-grade for prod) -10. **Policy as Code**: Run OPA/Sentinel and security scanning (Checkov, tfsec) in CI/CD before apply +10. **Policy as Code**: Run OPA/Sentinel and security scanning (Checkov, Trivy) in CI/CD before apply 11. **Version Pinning**: Pin all providers and modules; use `for_each` over `count` 12. **Cost Awareness**: Implement lifecycle policies, autoscaling schedules, and review cost estimates before apply 13. **No Auto-Approve**: Never use `auto-approve` in production; never `terraform destroy` without backup diff --git a/.agents/rules/market.md b/.agents/rules/market.md deleted file mode 100644 index 7a05afbd..00000000 --- a/.agents/rules/market.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -description: Market research standards - trap detection, always-latest last30days engine, framework layer, LAW enforcement -globs: -alwaysApply: false ---- - -# Market Research Standards - -## Core Rules - -1. **Preflight first**: every market research task starts with `oma market detect-trap`. If it refuses, surface the reframe to the user — never bypass without `--force` and explicit user reconfirmation. -2. **One engine, always latest**: research runs on the upstream `last30days` engine through `oma market run`. `oma market resolve` refreshes oma's managed copy to the latest GitHub Release before use (throttled by `market.check_interval_min`; cached copy on network failure). Do not hand-roll harvesting, scoring, or clustering, and do not run a stale user-installed copy when the managed one resolves. -3. **Follow the upstream contract**: read the resolved engine's `SKILL.md` (`engine.skillMd`) top to bottom every run and follow it — setup wizard, pre-research resolution, query plan, PRECONDITION GATE, OUTPUT CONTRACT. The only substitutions are skipping its Python-hunt block and replacing the raw `python3 scripts/last30days.py` call with `oma market run` (same arguments). -4. **Never WebSearch-only**: if the engine cannot run (no engine, no Python 3.12+, non-zero exit), stop and report; a WebSearch-only synthesis presented as market research is a contract violation. -5. **Keyless-first**: Reddit, HN, GitHub, Polymarket, arXiv, Techmeme, Digg, and web run without keys. Keyed sources (X, TikTok, Instagram, YouTube transcripts, …) are enabled only through the upstream setup wizard with user consent; skipped sources stay visible in the footer. -6. **Frameworks cite the engine**: SWOT / Porter's 5F / PESTEL sections use only clusters present in the engine output, cited as `[name](url)`; plain text when a URL is missing, never `[name]()`. Auto-toggle: pain/trend → SWOT; competitor → SWOT + 5F; discovery → SWOT + PESTEL; `--frameworks` overrides. -7. **LAW enforcement**: the engine's badge is the first line; upstream LAWs 1–8 plus `resources/output-laws.md` self-check must pass before the file is written. -8. **Single brief, single date**: `.agents/results/market/{topic-slug}-{YYYYMMDD}.md`; raw engine files under `market.save_dir` (default `.agents/results/market/raw/`). Same-day rerun overwrites. -9. **Personal data refuse**: refuse queries that target a private individual's personal data before running the engine. Founders, creators, and public handles are allowed (upstream person mode). -10. **Side effects are consented**: first-run `.env` creation, credential storage, and a `uv`-managed Python install happen only after the user says yes in the upstream Step 0 flow. diff --git a/.agents/rules/mobile.md b/.agents/rules/mobile.md index d927dd29..395d7e5b 100644 --- a/.agents/rules/mobile.md +++ b/.agents/rules/mobile.md @@ -6,18 +6,18 @@ alwaysApply: false # Mobile Development Standards -Variant-specific stacks live in `.agents/skills/oma-mobile/variants/{flutter,react-native,swift-ios}/`. -React Native sources (`.ts`/`.tsx`) are not matched by this rule's glob — for RN work, read the -`react-native` variant directly. Kotlin-native (Compose) is not a supported variant; `.kt` files -here are Flutter/RN Android host code only. +React Native sources (`.ts`/`.tsx`) are not matched by this rule's glob. `.kt` files are +Kotlin-native (Compose) when the project is an +Android application (`settings.gradle.kts` + `com.android.application`, no `pubspec.yaml` / +`react-native`); otherwise they are Flutter/RN Android host code. ## Core Rules -1. **Clean Architecture**: domain -> data -> presentation (Swift native: App/Core/Features/Shared) -2. **State Management**: the variant's solution — Flutter: Riverpod/Bloc; React Native: Zustand + TanStack Query; Swift: `@MainActor @Observable`. No raw setState/ad-hoc state for complex logic +1. **Clean Architecture**: domain -> data -> presentation (Swift native: App/Core/Features/Shared; Kotlin native: `app/{ui,data,di}` + `api-client`) +2. **State Management**: the variant's solution — Flutter: Riverpod/Bloc; React Native: Zustand + TanStack Query; Swift: `@MainActor @Observable`; Kotlin: `@HiltViewModel` + `StateFlow`. No raw setState/ad-hoc state for complex logic 3. **Design Guidelines**: Material Design 3 (Android) + iOS HIG (iOS) -4. **Resource Cleanup**: dispose controllers / cancel structured tasks; Swift: `.task {}` auto-cancel, never `deinit` -5. **Networking**: transport client with interceptors (Flutter: Dio; RN: axios behind TanStack Query hooks; Swift: swift-openapi-generator Client) + repository-layer response cache when required; handle offline gracefully -6. **Secrets**: secure storage only (flutter_secure_storage / Keychain / react-native-keychain) — never plain prefs or MMKV -7. **Performance**: 60fps target; test on both platforms -8. **E2E Testing**: Maestro (Flutter/RN) or XCUITest (Swift native) for critical user flows +4. **Resource Cleanup**: dispose controllers / cancel structured tasks; Swift: `.task {}` auto-cancel, never `deinit`; Kotlin: `viewModelScope`, never `GlobalScope` +5. **Networking**: transport client with interceptors (Flutter: Dio; RN: axios behind TanStack Query hooks; Swift: swift-openapi-generator Client; Kotlin: openapi-generator `jvm-ktor` `*Api` over Ktor with an injected OkHttp engine) + repository-layer response cache when required; handle offline gracefully +6. **Secrets**: secure storage only (flutter_secure_storage / Keychain / react-native-keychain / Android Keystore-backed storage) — never plain prefs or MMKV +7. **Performance**: 60fps target; test on every platform the app ships to +8. **E2E Testing**: Maestro (Flutter/RN/Kotlin) or XCUITest (Swift native) for critical user flows diff --git a/.agents/rules/quality.md b/.agents/rules/quality.md deleted file mode 100644 index 6c4b3a12..00000000 --- a/.agents/rules/quality.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -description: Quality assurance standards for security (OWASP), performance, accessibility (WCAG), and code quality reviews -globs: -alwaysApply: false ---- - -# Quality Assurance Standards - -## Core Rules - -1. Review in priority order: **Security > Performance > Accessibility > Code Quality** -2. Every finding must include file:line, description, and fix -3. Severity levels: CRITICAL (security breach/data loss), HIGH (blocks launch), MEDIUM (this sprint), LOW (backlog) -4. Run automated tools first: `npm audit`, `bandit`, `lighthouse` -5. No false positives — every finding must be reproducible -6. Provide remediation code, not just descriptions diff --git a/.agents/skills/_shared/README.md b/.agents/skills/_shared/README.md index f4056587..34570fa6 100644 --- a/.agents/skills/_shared/README.md +++ b/.agents/skills/_shared/README.md @@ -6,13 +6,15 @@ - `core/` - Common policy and task-selected guides; not a task-start reading list. - - Examples: context loading, clarification, difficulty, reasoning, lessons learned. + - Examples: context loading, clarification, difficulty, lessons learned. - `conditional/` - Load only when the workflow reaches a specific trigger. - - Examples: quality score, experiment ledger, exploration loop, diagram engine (archify ↔ Mermaid). + - Examples: quality score, experiment ledger, exploration loop, diagram engine (archify ↔ Mermaid, stack-diagram). - `runtime/` - Runtime-injected or CLI-specific protocols. - Examples: memory protocol, vendor execution protocols. +- `ui-interaction-quality.md` + - Motion and interaction acceptance rules shared by `oma-design` and `oma-frontend`; loaded on their stated triggers. ## Workflow-Owned Resources @@ -20,6 +22,7 @@ Workflow-specific materials do not belong in `_shared/`. - `ultrawork/resources/phase-gates.md` - `ultrawork/resources/multi-review-protocol.md` +- `ralph/resources/judge-protocol.md` ## Load Classes diff --git a/.agents/skills/_shared/conditional/diagram-engine.md b/.agents/skills/_shared/conditional/diagram-engine.md index 374cb23b..4d384f3e 100644 --- a/.agents/skills/_shared/conditional/diagram-engine.md +++ b/.agents/skills/_shared/conditional/diagram-engine.md @@ -1,23 +1,36 @@ -# Diagram Engine Protocol (archify ↔ Mermaid) +# Diagram Engine Protocol (archify ↔ Mermaid, stack-diagram) Load class: `conditional` — read only when a workflow is about to emit a -structural diagram (architecture, sequence, data-flow, lifecycle). +structural diagram (architecture, sequence, data-flow, lifecycle) or a +tech-stack poster. -Two engines exist. Mermaid is always available and is the **text SSOT** that +Two routes exist. The **structural route** (Steps 0–4) draws boundaries, call +chains, data flow, and lifecycles with archify or Mermaid. The **stack route** +(last section) draws a tech-stack / infrastructure poster with official vendor +logos through the upstream stack-diagram skill. Pick the route first: + +| Signal (first match wins) | Route | +|---|---| +| Prompt names `archify` | structural | +| Prompt names `stack-diagram` or asks for vendor logos | stack | +| Most nodes are vendor products or services (AWS, Vercel, Postgres, Hono, …) and the user wants a stack / infra / deployment topology | stack | +| Boundaries, call order, data flow, lifecycle, or any ADR structure | structural | + +`/explain` sidecars never take the stack route: `oma explain render --archify` +derives the archify spec from the draft in code, and stack-diagram has no code +path. Both routes author Mermaid first (Step 1). + +Two engines serve the structural route. Mermaid is always available and is the **text SSOT** that lives inside the Markdown artifact. [archify](https://github.com/tt-a1i/archify) (MIT, Node ≥ 18, zero runtime deps) is an optional upgrade that turns a typed JSON IR into a validated, self-contained interactive HTML diagram (dark/light, pan-zoom, search, trace, PNG/SVG/WebM export). -**oma always uses the latest archify release.** No manual install is needed: -`oma diagram resolve` keeps an oma-owned copy under -`~/.cache/oma-diagram/archify//`, re-checks GitHub Releases before use -(throttled by `diagram.archify.check_interval_min`, default 60 min), downloads a -newer tag when one exists, and reuses the cached copy when the network is down. -`oma diagram update` forces a check now. A copy installed by the user with -`npx skills add tt-a1i/archify` is only a fallback for when nothing is cached -and the network is unavailable; `diagram.archify.path` / `ARCHIFY_HOME` are -explicit pins that opt out of auto-latest. +**archify is installed as an agent skill through the skills CLI.** +`oma diagram resolve` reads installed skill directories; `oma diagram update` +installs it when missing (`bunx skills add tt-a1i/archify --skill archify -g -y`) +and updates it otherwise. Install only after the user agrees. +`diagram.archify.path` / `ARCHIFY_HOME` are explicit pins that win over installs. ## Step 0 — Resolve the engine (deterministic, all vendors) @@ -28,15 +41,15 @@ oma diagram resolve --json | Field | Meaning | |---|---| | `engine` | `archify` or `mermaid` — the engine to use for THIS run | -| `ok` | `false` only when `diagram.engine: archify` is pinned and nothing could be resolved (first run offline) → stop and tell the user to run `oma diagram update` once online; never silently downgrade a pin | +| `ok` | `false` only when `diagram.engine: archify` is pinned and archify is not installed → stop and offer `oma diagram update`; never silently downgrade a pin | | `archify.root` / `archify.bin` | install dir; the schema/example files live under `root` | -| `archify.status` / `archify.note` | managed copies only: `fresh` (just downloaded), `current`, or `stale` (update check failed — the note says why; mention it in the report) | +| `warnings` | deprecated config keys (`diagram.archify.managed|channel|check_interval_min` are ignored); relay them | | `quality` | `showcase` (default) or `standard` — pass as `--quality` | | `explainSidecar` | whether `/explain` should also emit an archify sidecar | -Resolution order: `diagram.archify.path` → `ARCHIFY_HOME` → managed latest → -project `.agents/.claude/.codex/.cursor/.qwen/.kiro/skills/archify` → the same -under `~`. Configure in `.agents/oma-config.yaml` (`diagram:` section). +Resolution order: `diagram.archify.path` → `ARCHIFY_HOME` → project +`.agents/.claude/.codex/.cursor/.qwen/.kiro/.gemini/.copilot/skills/archify` → +the same under `~` → `~/.config/agents/skills/archify`. Configure in `.agents/oma-config.yaml` (`diagram:` section). When `engine` is `mermaid`, author the Mermaid block per the calling skill's template and skip the rest of this file. @@ -46,7 +59,7 @@ template and skip the rest of this file. Mermaid in the Markdown artifact is the durable, diffable, git-reviewable form. Write it first, scoped to the elements the decision or change touches (C4 context/container for architecture; sequence for call chains). The archify -artifact is derived from it — never the other way round. +artifact and the stack poster are derived from it — never the other way round. ## Step 2 — Author the archify JSON IR @@ -117,10 +130,73 @@ skipped): `oma diagram archify visual-check .archify.html --json`. with a plain `` anchor (hyperlinks are allowed by `html-contract.md` §1). Never `