From b869509f5066ea830c7581118c86c4b6b12d0301 Mon Sep 17 00:00:00 2001 From: Fabro Date: Thu, 19 Mar 2026 20:27:02 -0400 Subject: [PATCH] checkpoint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚒️ Generated with [Fabro](https://fabro.sh) --- checkpoint.json | 73 +- nodes/implement/diff.patch | 3249 ++++++++++++++++++++++++ nodes/simplify_opus/prompt.md | 179 ++ nodes/simplify_opus/provider_used.json | 5 + nodes/simplify_opus/response.md | 18 + nodes/simplify_opus/status.json | 6 + 6 files changed, 3509 insertions(+), 21 deletions(-) create mode 100644 nodes/implement/diff.patch create mode 100644 nodes/simplify_opus/prompt.md create mode 100644 nodes/simplify_opus/provider_used.json create mode 100644 nodes/simplify_opus/response.md create mode 100644 nodes/simplify_opus/status.json diff --git a/checkpoint.json b/checkpoint.json index e62195573..21521095d 100644 --- a/checkpoint.json +++ b/checkpoint.json @@ -1,46 +1,51 @@ { - "timestamp": "2026-03-20T00:20:08.716538Z", - "current_node": "implement", + "timestamp": "2026-03-20T00:27:02.170801Z", + "current_node": "simplify_opus", "completed_nodes": [ "start", "toolchain", "preflight_compile", "preflight_lint", - "implement" + "implement", + "simplify_opus" ], "node_retries": { "toolchain": 1, "preflight_compile": 1, "start": 1, + "simplify_opus": 1, "preflight_lint": 1, "implement": 1 }, "context_values": { - "internal.retry_count.preflight_lint": 1, - "internal.run_id": "01KM48VREXY70R1G29AQNTBP6Y", "internal.retry_count.implement": 1, - "thread.preflight_lint.current_node": "implement", + "internal.retry_count.simplify_opus": 1, "graph.model_stylesheet": "\n * { backend: api; model: claude-opus-4-6;}\n ", - "internal.thread_id": "preflight_lint", - "current_node": "implement", "outcome": "success", - "internal.retry_count.toolchain": 1, - "last_stage": "implement", - "current.preamble": "Goal: # Plan: Merge fabro-linear and GitHub tracker into fabro-tracker\n\n## Context\n\nThe tracker ecosystem currently has three crates:\n- **fabro-tracker** — trait-only (57 lines): `Tracker` trait, `Issue`, `BlockerRef`\n- **fabro-linear** — standalone Linear functions that duplicate the `Issue`/`BlockerRef` types and don't implement the `Tracker` trait. Entirely unused.\n- **fabro-github** — mixed crate: GitHub App auth/PRs/branches (~70%) + `GitHubTracker` implementing `Tracker` (~30%). The `GitHubTracker` is also unused by consumers.\n\nGoal: consolidate both tracker implementations into `fabro-tracker`, keeping non-tracker GitHub code in `fabro-github`, and deleting `fabro-linear`.\n\n## Dependency Direction Change\n\n**Current:** `fabro-github → fabro-tracker` (for trait re-export)\n**After:** `fabro-tracker → fabro-github` (for auth primitives: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`)\n\n`fabro-github` no longer depends on `fabro-tracker`. No circular dependency.\n\n## Steps\n\n### 1. Update `lib/crates/fabro-tracker/Cargo.toml`\n\nAdd dependencies needed by both implementations:\n```toml\n[dependencies]\nfabro-github = { path = \"../fabro-github\" }\nasync-trait.workspace = true\nserde.workspace = true\nserde_json.workspace = true\nreqwest.workspace = true\ntracing.workspace = true\ntokio = { workspace = true }\n\n[dev-dependencies]\nmockito = \"1\"\ntokio = { workspace = true, features = [\"test-util\", \"macros\"] }\n```\n\n### 2. Update `lib/crates/fabro-github/Cargo.toml`\n\nRemove:\n- `fabro-tracker = { path = \"../fabro-tracker\" }`\n- `async-trait.workspace = true`\n\n### 3. Remove tracker code from `lib/crates/fabro-github/src/lib.rs`\n\nRemove these items (keep everything else):\n- `use async_trait::async_trait;` (line 1)\n- `use tokio::sync::OnceCell;` (line 3)\n- `pub use fabro_tracker::{BlockerRef, Issue, Tracker};` (line 5)\n- `execute_github_graphql()` fn (~line 796)\n- `GitHubTracker` struct, `impl GitHubTracker`, `impl Tracker for GitHubTracker` (~line 866-1315)\n- `normalize_github_item()` fn (~line 981)\n- `fetch_project_items_page()` fn (~line 1035)\n- All tracker-related tests (~line 2172-2841): `execute_github_graphql` tests, tracker helpers (`mock_github_tracker`, `make_test_issue`, etc.), and all `GitHubTracker` method tests\n\n**Keep** `create_installation_access_token_for_projects()` — it stays in fabro-github as a public function alongside the other `create_installation_access_token_*` variants.\n\n### 4. Create `lib/crates/fabro-tracker/src/linear.rs`\n\nAdapt `fabro-linear/src/lib.rs` code:\n- **Remove** the duplicate `Issue` and `BlockerRef` struct definitions — use `crate::Issue` and `crate::BlockerRef`\n- **Adapt** `normalize_issue()` to return `crate::Issue` with `project_item_id: None`\n- **Create** `LinearTracker` struct wrapping `LinearConfig`, `reqwest::Client`, and `project_slug: String`\n- **Implement** `Tracker for LinearTracker` by delegating to the existing functions\n- **Keep** private: `execute_graphql`, `normalize_issue`, `extract_issues`, `ISSUE_FIELDS`, `BLOCKS_RELATION_TYPE`\n- **Keep** public: `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT`\n- **Move** all tests, updating assertions for the added `project_item_id` field\n\n### 5. Create `lib/crates/fabro-tracker/src/github.rs`\n\nMove tracker code from fabro-github:\n- Import from fabro-github: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`\n- Contains: `GitHubTracker` struct + impls, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page`\n- Uses `crate::Issue` and `crate::BlockerRef` (same types, just different import path)\n- Move all GitHubTracker tests (duplicate `test_rsa_key()` helper since test code isn't importable across crates)\n\n### 6. Update `lib/crates/fabro-tracker/src/lib.rs`\n\nAdd module declarations and re-exports:\n```rust\npub mod github;\npub mod linear;\n\npub use github::GitHubTracker;\npub use linear::{LinearConfig, LinearTracker, LINEAR_API_ENDPOINT};\n```\n\n### 7. Delete `lib/crates/fabro-linear/`\n\nRemove entire directory. Workspace glob `members = [\"lib/crates/*\"]` handles the rest.\n\n## Verification\n\n```bash\ncargo build --workspace\ncargo test --workspace\ncargo clippy --workspace -- -D warnings\ncargo fmt --check --all\n```\n\nKey things to verify:\n- No circular dependency (fabro-tracker → fabro-github, fabro-github has no fabro-tracker dep)\n- Linear `normalize_issue` sets `project_item_id: None`\n- All moved tests pass in their new home\n- `test_rsa_key()` helper is duplicated in fabro-tracker's github test module\n\n\n## Completed stages\n- **toolchain**: success\n - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`\n - Stdout:\n ```\n cargo 1.94.0 (85eff7c80 2026-01-15)\n ```\n - Stderr: (empty)\n- **preflight_compile**: success\n - Script: `cargo check -q --workspace 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **preflight_lint**: success\n - Script: `cargo clippy -q --workspace -- -D warnings 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n", + "last_stage": "simplify_opus", + "current.preamble": "Goal: # Plan: Merge fabro-linear and GitHub tracker into fabro-tracker\n\n## Context\n\nThe tracker ecosystem currently has three crates:\n- **fabro-tracker** — trait-only (57 lines): `Tracker` trait, `Issue`, `BlockerRef`\n- **fabro-linear** — standalone Linear functions that duplicate the `Issue`/`BlockerRef` types and don't implement the `Tracker` trait. Entirely unused.\n- **fabro-github** — mixed crate: GitHub App auth/PRs/branches (~70%) + `GitHubTracker` implementing `Tracker` (~30%). The `GitHubTracker` is also unused by consumers.\n\nGoal: consolidate both tracker implementations into `fabro-tracker`, keeping non-tracker GitHub code in `fabro-github`, and deleting `fabro-linear`.\n\n## Dependency Direction Change\n\n**Current:** `fabro-github → fabro-tracker` (for trait re-export)\n**After:** `fabro-tracker → fabro-github` (for auth primitives: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`)\n\n`fabro-github` no longer depends on `fabro-tracker`. No circular dependency.\n\n## Steps\n\n### 1. Update `lib/crates/fabro-tracker/Cargo.toml`\n\nAdd dependencies needed by both implementations:\n```toml\n[dependencies]\nfabro-github = { path = \"../fabro-github\" }\nasync-trait.workspace = true\nserde.workspace = true\nserde_json.workspace = true\nreqwest.workspace = true\ntracing.workspace = true\ntokio = { workspace = true }\n\n[dev-dependencies]\nmockito = \"1\"\ntokio = { workspace = true, features = [\"test-util\", \"macros\"] }\n```\n\n### 2. Update `lib/crates/fabro-github/Cargo.toml`\n\nRemove:\n- `fabro-tracker = { path = \"../fabro-tracker\" }`\n- `async-trait.workspace = true`\n\n### 3. Remove tracker code from `lib/crates/fabro-github/src/lib.rs`\n\nRemove these items (keep everything else):\n- `use async_trait::async_trait;` (line 1)\n- `use tokio::sync::OnceCell;` (line 3)\n- `pub use fabro_tracker::{BlockerRef, Issue, Tracker};` (line 5)\n- `execute_github_graphql()` fn (~line 796)\n- `GitHubTracker` struct, `impl GitHubTracker`, `impl Tracker for GitHubTracker` (~line 866-1315)\n- `normalize_github_item()` fn (~line 981)\n- `fetch_project_items_page()` fn (~line 1035)\n- All tracker-related tests (~line 2172-2841): `execute_github_graphql` tests, tracker helpers (`mock_github_tracker`, `make_test_issue`, etc.), and all `GitHubTracker` method tests\n\n**Keep** `create_installation_access_token_for_projects()` — it stays in fabro-github as a public function alongside the other `create_installation_access_token_*` variants.\n\n### 4. Create `lib/crates/fabro-tracker/src/linear.rs`\n\nAdapt `fabro-linear/src/lib.rs` code:\n- **Remove** the duplicate `Issue` and `BlockerRef` struct definitions — use `crate::Issue` and `crate::BlockerRef`\n- **Adapt** `normalize_issue()` to return `crate::Issue` with `project_item_id: None`\n- **Create** `LinearTracker` struct wrapping `LinearConfig`, `reqwest::Client`, and `project_slug: String`\n- **Implement** `Tracker for LinearTracker` by delegating to the existing functions\n- **Keep** private: `execute_graphql`, `normalize_issue`, `extract_issues`, `ISSUE_FIELDS`, `BLOCKS_RELATION_TYPE`\n- **Keep** public: `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT`\n- **Move** all tests, updating assertions for the added `project_item_id` field\n\n### 5. Create `lib/crates/fabro-tracker/src/github.rs`\n\nMove tracker code from fabro-github:\n- Import from fabro-github: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`\n- Contains: `GitHubTracker` struct + impls, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page`\n- Uses `crate::Issue` and `crate::BlockerRef` (same types, just different import path)\n- Move all GitHubTracker tests (duplicate `test_rsa_key()` helper since test code isn't importable across crates)\n\n### 6. Update `lib/crates/fabro-tracker/src/lib.rs`\n\nAdd module declarations and re-exports:\n```rust\npub mod github;\npub mod linear;\n\npub use github::GitHubTracker;\npub use linear::{LinearConfig, LinearTracker, LINEAR_API_ENDPOINT};\n```\n\n### 7. Delete `lib/crates/fabro-linear/`\n\nRemove entire directory. Workspace glob `members = [\"lib/crates/*\"]` handles the rest.\n\n## Verification\n\n```bash\ncargo build --workspace\ncargo test --workspace\ncargo clippy --workspace -- -D warnings\ncargo fmt --check --all\n```\n\nKey things to verify:\n- No circular dependency (fabro-tracker → fabro-github, fabro-github has no fabro-tracker dep)\n- Linear `normalize_issue` sets `project_item_id: None`\n- All moved tests pass in their new home\n- `test_rsa_key()` helper is duplicated in fabro-tracker's github test module\n\n\n## Completed stages\n- **toolchain**: success\n - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`\n - Stdout:\n ```\n cargo 1.94.0 (85eff7c80 2026-01-15)\n ```\n - Stderr: (empty)\n- **preflight_compile**: success\n - Script: `cargo check -q --workspace 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **preflight_lint**: success\n - Script: `cargo clippy -q --workspace -- -D warnings 2>&1`\n - Stdout: (empty)\n - Stderr: (empty)\n- **implement**: success\n - Model: claude-opus-4-6, 113.7k tokens in / 38.3k out\n - Files: /home/daytona/workspace/lib/crates/fabro-github/Cargo.toml, /home/daytona/workspace/lib/crates/fabro-github/src/lib.rs, /home/daytona/workspace/lib/crates/fabro-tracker/Cargo.toml, /home/daytona/workspace/lib/crates/fabro-tracker/src/github.rs, /home/daytona/workspace/lib/crates/fabro-tracker/src/lib.rs, /home/daytona/workspace/lib/crates/fabro-tracker/src/linear.rs\n", "failure_signature": "", - "thread.start.current_node": "toolchain", - "internal.node_visit_count": 1, - "command.output": "", "internal.retry_count.preflight_compile": 1, - "command.stderr": "", - "response.implement": "Here's a summary of all changes made:\n\n## Summary of Changes\n\n### 1. `lib/crates/fabro-tracker/Cargo.toml` — Updated dependencies\nAdded `fabro-github`, `serde`, `serde_json`, `reqwest`, `tracing`, `tokio` as dependencies, and `mockito`/`tokio` as dev-dependencies to support both tracker implementations.\n\n### 2. `lib/crates/fabro-tracker/src/lib.rs` — Added module declarations and re-exports\nAdded `pub mod github;`, `pub mod linear;`, and re-exports: `GitHubTracker`, `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT`.\n\n### 3. `lib/crates/fabro-tracker/src/github.rs` — New file (moved from fabro-github)\nContains `GitHubTracker` struct + impl, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page`, and all GitHub tracker tests. Imports auth primitives from `fabro_github` and types from `crate::`.\n\n### 4. `lib/crates/fabro-tracker/src/linear.rs` — New file (adapted from fabro-linear)\nContains `LinearTracker` struct implementing `Tracker` trait, `LinearConfig`, all Linear API functions, and all tests. Uses `crate::{BlockerRef, Issue}` instead of duplicate struct definitions. `normalize_issue` now sets `project_item_id: None`.\n\n### 5. `lib/crates/fabro-github/Cargo.toml` — Removed tracker dependencies\nRemoved `fabro-tracker` and `async-trait` dependencies.\n\n### 6. `lib/crates/fabro-github/src/lib.rs` — Removed tracker code\nRemoved: `use async_trait`, `use tokio::sync::OnceCell`, `pub use fabro_tracker::*`, `execute_github_graphql`, `GitHubTracker` struct/impls, `normalize_github_item`, `fetch_project_items_page`, and all tracker-related tests. Kept `create_installation_access_token_for_projects` and all non-tracker code.\n\n### 7. Deleted `lib/crates/fabro-linear/` — Entire directory removed\nWorkspace glob `members = [\"lib/crates/*\"]` handles the workspace membership automatically.\n\n### Dependency direction change\n- **Before:** `fabro-github → fabro-tracker` \n- **After:** `fabro-tracker → fabro-github` (no circular dependency)", + "command.output": "", + "thread.implement.current_node": "simplify_opus", "failure_class": "", - "last_response": "Here's a summary of all changes made:\n\n## Summary of Changes\n\n### 1. `lib/crates/fabro-tracker/Cargo.toml` — Updated dependencies\nAdded `fabro-github`, `serde`, `serde_json`, `reqwest`, `tracing`, `", - "graph.rankdir": "LR", "internal.fidelity": "compact", - "thread.toolchain.current_node": "preflight_compile", "internal.retry_count.start": 1, "graph.goal": "# Plan: Merge fabro-linear and GitHub tracker into fabro-tracker\n\n## Context\n\nThe tracker ecosystem currently has three crates:\n- **fabro-tracker** — trait-only (57 lines): `Tracker` trait, `Issue`, `BlockerRef`\n- **fabro-linear** — standalone Linear functions that duplicate the `Issue`/`BlockerRef` types and don't implement the `Tracker` trait. Entirely unused.\n- **fabro-github** — mixed crate: GitHub App auth/PRs/branches (~70%) + `GitHubTracker` implementing `Tracker` (~30%). The `GitHubTracker` is also unused by consumers.\n\nGoal: consolidate both tracker implementations into `fabro-tracker`, keeping non-tracker GitHub code in `fabro-github`, and deleting `fabro-linear`.\n\n## Dependency Direction Change\n\n**Current:** `fabro-github → fabro-tracker` (for trait re-export)\n**After:** `fabro-tracker → fabro-github` (for auth primitives: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`)\n\n`fabro-github` no longer depends on `fabro-tracker`. No circular dependency.\n\n## Steps\n\n### 1. Update `lib/crates/fabro-tracker/Cargo.toml`\n\nAdd dependencies needed by both implementations:\n```toml\n[dependencies]\nfabro-github = { path = \"../fabro-github\" }\nasync-trait.workspace = true\nserde.workspace = true\nserde_json.workspace = true\nreqwest.workspace = true\ntracing.workspace = true\ntokio = { workspace = true }\n\n[dev-dependencies]\nmockito = \"1\"\ntokio = { workspace = true, features = [\"test-util\", \"macros\"] }\n```\n\n### 2. Update `lib/crates/fabro-github/Cargo.toml`\n\nRemove:\n- `fabro-tracker = { path = \"../fabro-tracker\" }`\n- `async-trait.workspace = true`\n\n### 3. Remove tracker code from `lib/crates/fabro-github/src/lib.rs`\n\nRemove these items (keep everything else):\n- `use async_trait::async_trait;` (line 1)\n- `use tokio::sync::OnceCell;` (line 3)\n- `pub use fabro_tracker::{BlockerRef, Issue, Tracker};` (line 5)\n- `execute_github_graphql()` fn (~line 796)\n- `GitHubTracker` struct, `impl GitHubTracker`, `impl Tracker for GitHubTracker` (~line 866-1315)\n- `normalize_github_item()` fn (~line 981)\n- `fetch_project_items_page()` fn (~line 1035)\n- All tracker-related tests (~line 2172-2841): `execute_github_graphql` tests, tracker helpers (`mock_github_tracker`, `make_test_issue`, etc.), and all `GitHubTracker` method tests\n\n**Keep** `create_installation_access_token_for_projects()` — it stays in fabro-github as a public function alongside the other `create_installation_access_token_*` variants.\n\n### 4. Create `lib/crates/fabro-tracker/src/linear.rs`\n\nAdapt `fabro-linear/src/lib.rs` code:\n- **Remove** the duplicate `Issue` and `BlockerRef` struct definitions — use `crate::Issue` and `crate::BlockerRef`\n- **Adapt** `normalize_issue()` to return `crate::Issue` with `project_item_id: None`\n- **Create** `LinearTracker` struct wrapping `LinearConfig`, `reqwest::Client`, and `project_slug: String`\n- **Implement** `Tracker for LinearTracker` by delegating to the existing functions\n- **Keep** private: `execute_graphql`, `normalize_issue`, `extract_issues`, `ISSUE_FIELDS`, `BLOCKS_RELATION_TYPE`\n- **Keep** public: `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT`\n- **Move** all tests, updating assertions for the added `project_item_id` field\n\n### 5. Create `lib/crates/fabro-tracker/src/github.rs`\n\nMove tracker code from fabro-github:\n- Import from fabro-github: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`\n- Contains: `GitHubTracker` struct + impls, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page`\n- Uses `crate::Issue` and `crate::BlockerRef` (same types, just different import path)\n- Move all GitHubTracker tests (duplicate `test_rsa_key()` helper since test code isn't importable across crates)\n\n### 6. Update `lib/crates/fabro-tracker/src/lib.rs`\n\nAdd module declarations and re-exports:\n```rust\npub mod github;\npub mod linear;\n\npub use github::GitHubTracker;\npub use linear::{LinearConfig, LinearTracker, LINEAR_API_ENDPOINT};\n```\n\n### 7. Delete `lib/crates/fabro-linear/`\n\nRemove entire directory. Workspace glob `members = [\"lib/crates/*\"]` handles the rest.\n\n## Verification\n\n```bash\ncargo build --workspace\ncargo test --workspace\ncargo clippy --workspace -- -D warnings\ncargo fmt --check --all\n```\n\nKey things to verify:\n- No circular dependency (fabro-tracker → fabro-github, fabro-github has no fabro-tracker dep)\n- Linear `normalize_issue` sets `project_item_id: None`\n- All moved tests pass in their new home\n- `test_rsa_key()` helper is duplicated in fabro-tracker's github test module\n", + "internal.retry_count.preflight_lint": 1, + "response.simplify_opus": "All clean. Here's a summary of what was fixed:\n\n## Summary\n\n**4 issues fixed, 2 skipped as expected/acceptable:**\n\n### Fixed\n1. **Unified duplicate GraphQL execution functions** (HIGH) — Extracted `execute_graphql_request()` into `lib.rs` as a `pub(crate)` shared helper. Both `github.rs::execute_github_graphql()` and `linear.rs::execute_graphql()` now delegate to it, eliminating ~80 lines of duplicated request/error-handling logic while preserving provider-specific auth headers and error labels.\n\n2. **Added `make_test_issue()` helper to linear.rs tests** (MEDIUM) — Replaced 4 identical 14-field `Issue` struct constructions with a shared test helper, removing ~55 lines of boilerplate and matching the pattern already used in `github.rs` tests.\n\n3. **Removed unused `serde` dependency** (MEDIUM) — `fabro-tracker/Cargo.toml` listed `serde.workspace = true` but no file in the crate imports or derives from `serde` directly (only `serde_json` is used). Removed the phantom dependency.\n\n4. **Fixed missing trailing newline in `fabro-github/Cargo.toml`** (LOW) — The file was missing a POSIX trailing newline, causing `\\ No newline at end of file` in diffs.\n\n### Skipped (acceptable)\n- **`test_rsa_key()` duplication** between `fabro-github` and `fabro-tracker` — Expected; Rust `#[cfg(test)]` code can't be shared across crate boundaries without a test-utils crate.\n- **`fetch_issues_by_ids` ordering pattern** in both modules — Idiomatic; the provider-specific fetch logic differs enough that extraction would be forced.", + "internal.run_id": "01KM48VREXY70R1G29AQNTBP6Y", + "thread.preflight_lint.current_node": "implement", + "internal.thread_id": "implement", + "current_node": "simplify_opus", + "internal.retry_count.toolchain": 1, + "response.implement": "Here's a summary of all changes made:\n\n## Summary of Changes\n\n### 1. `lib/crates/fabro-tracker/Cargo.toml` — Updated dependencies\nAdded `fabro-github`, `serde`, `serde_json`, `reqwest`, `tracing`, `tokio` as dependencies, and `mockito`/`tokio` as dev-dependencies to support both tracker implementations.\n\n### 2. `lib/crates/fabro-tracker/src/lib.rs` — Added module declarations and re-exports\nAdded `pub mod github;`, `pub mod linear;`, and re-exports: `GitHubTracker`, `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT`.\n\n### 3. `lib/crates/fabro-tracker/src/github.rs` — New file (moved from fabro-github)\nContains `GitHubTracker` struct + impl, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page`, and all GitHub tracker tests. Imports auth primitives from `fabro_github` and types from `crate::`.\n\n### 4. `lib/crates/fabro-tracker/src/linear.rs` — New file (adapted from fabro-linear)\nContains `LinearTracker` struct implementing `Tracker` trait, `LinearConfig`, all Linear API functions, and all tests. Uses `crate::{BlockerRef, Issue}` instead of duplicate struct definitions. `normalize_issue` now sets `project_item_id: None`.\n\n### 5. `lib/crates/fabro-github/Cargo.toml` — Removed tracker dependencies\nRemoved `fabro-tracker` and `async-trait` dependencies.\n\n### 6. `lib/crates/fabro-github/src/lib.rs` — Removed tracker code\nRemoved: `use async_trait`, `use tokio::sync::OnceCell`, `pub use fabro_tracker::*`, `execute_github_graphql`, `GitHubTracker` struct/impls, `normalize_github_item`, `fetch_project_items_page`, and all tracker-related tests. Kept `create_installation_access_token_for_projects` and all non-tracker code.\n\n### 7. Deleted `lib/crates/fabro-linear/` — Entire directory removed\nWorkspace glob `members = [\"lib/crates/*\"]` handles the workspace membership automatically.\n\n### Dependency direction change\n- **Before:** `fabro-github → fabro-tracker` \n- **After:** `fabro-tracker → fabro-github` (no circular dependency)", + "thread.start.current_node": "toolchain", + "internal.node_visit_count": 1, + "last_response": "All clean. Here's a summary of what was fixed:\n\n## Summary\n\n**4 issues fixed, 2 skipped as expected/acceptable:**\n\n### Fixed\n1. **Unified duplicate GraphQL execution functions** (HIGH) — Extracted `", + "command.stderr": "", + "graph.rankdir": "LR", + "thread.toolchain.current_node": "preflight_compile", "thread.preflight_compile.current_node": "preflight_lint" }, "logs": [], @@ -102,14 +107,40 @@ "start": { "status": "success", "duration_ms": 0 + }, + "simplify_opus": { + "status": "success", + "context_updates": { + "last_response": "All clean. Here's a summary of what was fixed:\n\n## Summary\n\n**4 issues fixed, 2 skipped as expected/acceptable:**\n\n### Fixed\n1. **Unified duplicate GraphQL execution functions** (HIGH) — Extracted `", + "response.simplify_opus": "All clean. Here's a summary of what was fixed:\n\n## Summary\n\n**4 issues fixed, 2 skipped as expected/acceptable:**\n\n### Fixed\n1. **Unified duplicate GraphQL execution functions** (HIGH) — Extracted `execute_graphql_request()` into `lib.rs` as a `pub(crate)` shared helper. Both `github.rs::execute_github_graphql()` and `linear.rs::execute_graphql()` now delegate to it, eliminating ~80 lines of duplicated request/error-handling logic while preserving provider-specific auth headers and error labels.\n\n2. **Added `make_test_issue()` helper to linear.rs tests** (MEDIUM) — Replaced 4 identical 14-field `Issue` struct constructions with a shared test helper, removing ~55 lines of boilerplate and matching the pattern already used in `github.rs` tests.\n\n3. **Removed unused `serde` dependency** (MEDIUM) — `fabro-tracker/Cargo.toml` listed `serde.workspace = true` but no file in the crate imports or derives from `serde` directly (only `serde_json` is used). Removed the phantom dependency.\n\n4. **Fixed missing trailing newline in `fabro-github/Cargo.toml`** (LOW) — The file was missing a POSIX trailing newline, causing `\\ No newline at end of file` in diffs.\n\n### Skipped (acceptable)\n- **`test_rsa_key()` duplication** between `fabro-github` and `fabro-tracker` — Expected; Rust `#[cfg(test)]` code can't be shared across crate boundaries without a test-utils crate.\n- **`fetch_issues_by_ids` ordering pattern** in both modules — Idiomatic; the provider-specific fetch logic differs enough that extraction would be forced.", + "last_stage": "simplify_opus" + }, + "notes": "Stage completed: simplify_opus", + "usage": { + "model": "claude-opus-4-6", + "input_tokens": 96177, + "output_tokens": 12100, + "cache_read_tokens": 2622332, + "cache_write_tokens": 155992, + "reasoning_tokens": 591, + "cost": 2.350155 + }, + "files_touched": [ + "/home/daytona/workspace/lib/crates/fabro-tracker/Cargo.toml", + "/home/daytona/workspace/lib/crates/fabro-tracker/src/github.rs", + "/home/daytona/workspace/lib/crates/fabro-tracker/src/lib.rs", + "/home/daytona/workspace/lib/crates/fabro-tracker/src/linear.rs" + ], + "duration_ms": 410020 } }, - "next_node_id": "simplify_opus", + "next_node_id": "simplify_gpt", "node_visits": { "preflight_compile": 1, "start": 1, "toolchain": 1, "preflight_lint": 1, - "implement": 1 + "implement": 1, + "simplify_opus": 1 } } \ No newline at end of file diff --git a/nodes/implement/diff.patch b/nodes/implement/diff.patch new file mode 100644 index 000000000..c90f3f8d5 --- /dev/null +++ b/nodes/implement/diff.patch @@ -0,0 +1,3249 @@ +diff --git a/Cargo.lock b/Cargo.lock +index 92687d0f..5a17acb2 100644 +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -1505,10 +1505,8 @@ dependencies = [ + name = "fabro-github" + version = "0.176.2" + dependencies = [ +- "async-trait", + "base64", + "chrono", +- "fabro-tracker", + "jsonwebtoken", + "mockito", + "reqwest 0.12.28", +@@ -1561,20 +1559,6 @@ dependencies = [ + "tokio", + ] + +-[[package]] +-name = "fabro-linear" +-version = "0.176.2" +-dependencies = [ +- "async-trait", +- "fabro-tracker", +- "mockito", +- "reqwest 0.12.28", +- "serde", +- "serde_json", +- "tokio", +- "tracing", +-] +- + [[package]] + name = "fabro-llm" + version = "0.176.2" +@@ -1736,6 +1720,13 @@ name = "fabro-tracker" + version = "0.176.2" + dependencies = [ + "async-trait", ++ "fabro-github", ++ "mockito", ++ "reqwest 0.12.28", ++ "serde", ++ "serde_json", ++ "tokio", ++ "tracing", + ] + + [[package]] +diff --git a/lib/crates/fabro-github/Cargo.toml b/lib/crates/fabro-github/Cargo.toml +index abf39218..6bfbe579 100644 +--- a/lib/crates/fabro-github/Cargo.toml ++++ b/lib/crates/fabro-github/Cargo.toml +@@ -9,8 +9,6 @@ description = "GitHub App authentication and API helpers for Fabro" + doctest = false + + [dependencies] +-fabro-tracker = { path = "../fabro-tracker" } +-async-trait.workspace = true + serde.workspace = true + serde_json.workspace = true + reqwest.workspace = true +@@ -22,4 +20,4 @@ tokio = { workspace = true } + [dev-dependencies] + mockito = "1" + tokio = { workspace = true, features = ["test-util", "macros"] } +-base64.workspace = true ++base64.workspace = true +\ No newline at end of file +diff --git a/lib/crates/fabro-github/src/lib.rs b/lib/crates/fabro-github/src/lib.rs +index 9f0533cc..18e9c0eb 100644 +--- a/lib/crates/fabro-github/src/lib.rs ++++ b/lib/crates/fabro-github/src/lib.rs +@@ -1,8 +1,4 @@ +-use async_trait::async_trait; + use serde::Deserialize; +-use tokio::sync::OnceCell; +- +-pub use fabro_tracker::{BlockerRef, Issue, Tracker}; + + pub const GITHUB_API_BASE_URL: &str = "https://api.github.com"; + +@@ -792,57 +788,6 @@ pub async fn close_pull_request( + } + } + +-/// Execute a GitHub GraphQL request and return the response JSON. +-async fn execute_github_graphql( +- client: &reqwest::Client, +- token: &str, +- endpoint: &str, +- query: &str, +- variables: serde_json::Value, +-) -> Result { +- let body = serde_json::json!({ +- "query": query, +- "variables": variables, +- }); +- +- let resp = client +- .post(endpoint) +- .header("Authorization", format!("Bearer {token}")) +- .header("Content-Type", "application/json") +- .header("User-Agent", "fabro") +- .timeout(std::time::Duration::from_secs(30)) +- .json(&body) +- .send() +- .await +- .map_err(|e| format!("GitHub GraphQL request failed: {e}"))?; +- +- let status = resp.status(); +- if !status.is_success() { +- let body_text = resp.text().await.unwrap_or_default(); +- tracing::warn!(status = %status, "GitHub GraphQL API error"); +- return Err(format!( +- "GitHub GraphQL API returned HTTP {status}: {body_text}" +- )); +- } +- +- let response: serde_json::Value = resp +- .json() +- .await +- .map_err(|e| format!("Failed to parse GitHub GraphQL response: {e}"))?; +- +- if let Some(errors) = response["errors"].as_array() { +- if !errors.is_empty() { +- let messages: Vec<&str> = errors +- .iter() +- .filter_map(|e| e["message"].as_str()) +- .collect(); +- return Err(format!("GitHub GraphQL errors: {}", messages.join("; "))); +- } +- } +- +- Ok(response) +-} +- + /// Request a scoped Installation Access Token with `issues: write` + /// and `organization_projects: write`. Used for GitHub Projects V2. + pub async fn create_installation_access_token_for_projects( +@@ -863,457 +808,6 @@ pub async fn create_installation_access_token_for_projects( + .await + } + +-/// A `Tracker` implementation backed by GitHub Projects V2. +-/// +-/// Scoped to a single project board identified by `project_number`. +-pub struct GitHubTracker { +- creds: GitHubAppCredentials, +- client: reqwest::Client, +- owner: String, +- repo: String, +- project_number: u64, +- base_url: String, +- project_node_id: OnceCell, +-} +- +-impl GitHubTracker { +- pub fn new( +- creds: GitHubAppCredentials, +- client: reqwest::Client, +- owner: String, +- repo: String, +- project_number: u64, +- base_url: String, +- ) -> Self { +- Self { +- creds, +- client, +- owner, +- repo, +- project_number, +- base_url, +- project_node_id: OnceCell::new(), +- } +- } +- +- fn graphql_url(&self) -> String { +- format!("{}/graphql", self.base_url) +- } +- +- async fn fresh_token(&self) -> Result { +- let jwt = sign_app_jwt(&self.creds.app_id, &self.creds.private_key_pem)?; +- create_installation_access_token_for_projects( +- &self.client, +- &jwt, +- &self.owner, +- &self.repo, +- &self.base_url, +- ) +- .await +- } +- +- async fn resolve_project_node_id(&self, token: &str) -> Result<&str, String> { +- self.project_node_id +- .get_or_try_init(|| async { +- tracing::debug!( +- owner = %self.owner, +- project_number = self.project_number, +- "Resolving GitHub project node ID" +- ); +- let graphql_url = self.graphql_url(); +- let query = r#" +- query($owner: String!, $number: Int!) { +- organization(login: $owner) { +- projectV2(number: $number) { id } +- } +- } +- "#; +- let variables = serde_json::json!({ +- "owner": self.owner, +- "number": self.project_number, +- }); +- +- let resp = execute_github_graphql( +- &self.client, +- token, +- &graphql_url, +- query, +- variables.clone(), +- ) +- .await?; +- +- // Try org path first, fall back to user path +- if let Some(id) = resp["data"]["organization"]["projectV2"]["id"].as_str() { +- return Ok(id.to_string()); +- } +- +- let user_query = r#" +- query($owner: String!, $number: Int!) { +- user(login: $owner) { +- projectV2(number: $number) { id } +- } +- } +- "#; +- let user_resp = execute_github_graphql( +- &self.client, +- token, +- &graphql_url, +- user_query, +- variables, +- ) +- .await?; +- +- user_resp["data"]["user"]["projectV2"]["id"] +- .as_str() +- .map(|s| s.to_string()) +- .ok_or_else(|| { +- format!( +- "Project #{} not found for owner '{}'", +- self.project_number, self.owner +- ) +- }) +- }) +- .await +- .map(|s| s.as_str()) +- } +-} +- +-fn normalize_github_item(item: &serde_json::Value) -> Option { +- let project_item_id = item["id"].as_str()?.to_string(); +- let content = &item["content"]; +- +- let id = content["id"].as_str()?.to_string(); +- let number = content["number"].as_u64()?; +- let identifier = format!("#{number}"); +- let title = content["title"].as_str()?.to_string(); +- let url = content["url"].as_str()?.to_string(); +- let description = content["body"].as_str().map(|s| s.to_string()); +- +- let state = item["fieldValueByName"]["name"] +- .as_str() +- .unwrap_or("") +- .to_string(); +- +- let assignee_id = content["assignees"]["nodes"] +- .as_array() +- .and_then(|arr| arr.first()) +- .and_then(|a| a["id"].as_str()) +- .map(|s| s.to_string()); +- +- let labels = content["labels"]["nodes"] +- .as_array() +- .map(|arr| { +- arr.iter() +- .filter_map(|l| l["name"].as_str()) +- .map(|s| s.to_lowercase()) +- .collect() +- }) +- .unwrap_or_default(); +- +- let created_at = content["createdAt"].as_str().map(|s| s.to_string()); +- let updated_at = content["updatedAt"].as_str().map(|s| s.to_string()); +- +- Some(Issue { +- id, +- project_item_id: Some(project_item_id), +- identifier, +- title, +- description, +- priority: None, +- state, +- branch_name: None, +- url, +- assignee_id, +- labels, +- blocked_by: vec![], +- created_at, +- updated_at, +- }) +-} +- +-/// Fetch one page of project items. Returns (items, has_next_page, end_cursor). +-async fn fetch_project_items_page( +- client: &reqwest::Client, +- token: &str, +- graphql_url: &str, +- project_node_id: &str, +- cursor: Option<&str>, +-) -> Result<(Vec, bool, Option), String> { +- let query = r#" +- query($projectId: ID!, $cursor: String) { +- node(id: $projectId) { +- ... on ProjectV2 { +- items(first: 100, after: $cursor) { +- nodes { +- id +- fieldValueByName(name: "Status") { +- ... on ProjectV2ItemFieldSingleSelectValue { +- name +- } +- } +- content { +- ... on Issue { +- id +- number +- title +- body +- url +- createdAt +- updatedAt +- assignees(first: 1) { nodes { id } } +- labels(first: 20) { nodes { name } } +- } +- } +- } +- pageInfo { hasNextPage endCursor } +- } +- } +- } +- } +- "#; +- +- let variables = serde_json::json!({ +- "projectId": project_node_id, +- "cursor": cursor, +- }); +- +- let resp = execute_github_graphql(client, token, graphql_url, query, variables).await?; +- +- let items_node = &resp["data"]["node"]["items"]; +- let nodes = items_node["nodes"].as_array().cloned().unwrap_or_default(); +- let has_next = items_node["pageInfo"]["hasNextPage"] +- .as_bool() +- .unwrap_or(false); +- let end_cursor = items_node["pageInfo"]["endCursor"] +- .as_str() +- .map(|s| s.to_string()); +- +- Ok((nodes, has_next, end_cursor)) +-} +- +-#[async_trait] +-impl Tracker for GitHubTracker { +- async fn fetch_viewer_id(&self) -> Result { +- tracing::debug!("Fetching viewer ID from GitHub"); +- let token = self.fresh_token().await?; +- let query = "query { viewer { id } }"; +- let resp = execute_github_graphql( +- &self.client, +- &token, +- &self.graphql_url(), +- query, +- serde_json::json!({}), +- ) +- .await?; +- +- resp["data"]["viewer"]["id"] +- .as_str() +- .map(|s| s.to_string()) +- .ok_or_else(|| "Missing viewer id in GitHub response".to_string()) +- } +- +- async fn create_comment(&self, issue: &Issue, body: &str) -> Result<(), String> { +- tracing::debug!(issue_id = %issue.id, "Creating comment on GitHub issue"); +- let token = self.fresh_token().await?; +- let query = r#" +- mutation($subjectId: ID!, $body: String!) { +- addComment(input: { subjectId: $subjectId, body: $body }) { +- clientMutationId +- } +- } +- "#; +- let variables = serde_json::json!({ +- "subjectId": issue.id, +- "body": body, +- }); +- execute_github_graphql(&self.client, &token, &self.graphql_url(), query, variables).await?; +- Ok(()) +- } +- +- async fn update_issue_state(&self, issue: &Issue, state_name: &str) -> Result<(), String> { +- let project_item_id = issue +- .project_item_id +- .as_deref() +- .ok_or("update_issue_state requires project_item_id")?; +- +- tracing::debug!( +- project_item_id, +- state_name, +- "Updating GitHub project item status" +- ); +- +- let token = self.fresh_token().await?; +- let project_node_id = self.resolve_project_node_id(&token).await?; +- let graphql_url = self.graphql_url(); +- +- // Step 1: Get the Status field ID and the target option ID +- let field_query = r#" +- query($projectId: ID!) { +- node(id: $projectId) { +- ... on ProjectV2 { +- field(name: "Status") { +- ... on ProjectV2SingleSelectField { +- id +- options { id name } +- } +- } +- } +- } +- } +- "#; +- let field_resp = execute_github_graphql( +- &self.client, +- &token, +- &graphql_url, +- field_query, +- serde_json::json!({ "projectId": project_node_id }), +- ) +- .await?; +- +- let field = &field_resp["data"]["node"]["field"]; +- let field_id = field["id"] +- .as_str() +- .ok_or("Missing Status field id")? +- .to_string(); +- +- let option_id = field["options"] +- .as_array() +- .and_then(|opts| { +- opts.iter().find(|o| { +- o["name"] +- .as_str() +- .is_some_and(|n| n.eq_ignore_ascii_case(state_name)) +- }) +- }) +- .and_then(|o| o["id"].as_str()) +- .ok_or_else(|| format!("Status option '{state_name}' not found in project"))? +- .to_string(); +- +- // Step 2: Update the field value +- let update_query = r#" +- mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { +- updateProjectV2ItemFieldValue(input: { +- projectId: $projectId +- itemId: $itemId +- fieldId: $fieldId +- value: { singleSelectOptionId: $optionId } +- }) { +- projectV2Item { id } +- } +- } +- "#; +- execute_github_graphql( +- &self.client, +- &token, +- &graphql_url, +- update_query, +- serde_json::json!({ +- "projectId": project_node_id, +- "itemId": project_item_id, +- "fieldId": field_id, +- "optionId": option_id, +- }), +- ) +- .await?; +- +- Ok(()) +- } +- +- async fn fetch_candidate_issues(&self, state_names: &[&str]) -> Result, String> { +- tracing::debug!( +- owner = %self.owner, +- project_number = self.project_number, +- ?state_names, +- "Fetching candidate issues from GitHub project" +- ); +- +- let token = self.fresh_token().await?; +- let project_node_id = self.resolve_project_node_id(&token).await?; +- let graphql_url = self.graphql_url(); +- +- let mut all_issues = Vec::new(); +- let mut cursor: Option = None; +- +- loop { +- let (nodes, has_next, end_cursor) = fetch_project_items_page( +- &self.client, +- &token, +- &graphql_url, +- project_node_id, +- cursor.as_deref(), +- ) +- .await?; +- +- for node in &nodes { +- if let Some(issue) = normalize_github_item(node) { +- if state_names +- .iter() +- .any(|s| s.eq_ignore_ascii_case(&issue.state)) +- { +- all_issues.push(issue); +- } +- } +- } +- +- if has_next { +- cursor = end_cursor; +- } else { +- break; +- } +- } +- +- Ok(all_issues) +- } +- +- async fn fetch_issues_by_ids(&self, ids: &[&str]) -> Result, String> { +- if ids.is_empty() { +- return Ok(Vec::new()); +- } +- +- tracing::debug!( +- count = ids.len(), +- "Fetching GitHub issues by ID from project" +- ); +- +- let token = self.fresh_token().await?; +- let project_node_id = self.resolve_project_node_id(&token).await?; +- let graphql_url = self.graphql_url(); +- +- let id_set: std::collections::HashSet<&str> = ids.iter().copied().collect(); +- let mut issue_map: std::collections::HashMap = +- std::collections::HashMap::new(); +- let mut cursor: Option = None; +- +- loop { +- let (nodes, has_next, end_cursor) = fetch_project_items_page( +- &self.client, +- &token, +- &graphql_url, +- project_node_id, +- cursor.as_deref(), +- ) +- .await?; +- +- for node in &nodes { +- if let Some(issue) = normalize_github_item(node) { +- if id_set.contains(issue.id.as_str()) { +- issue_map.insert(issue.id.clone(), issue); +- } +- } +- } +- +- if has_next { +- cursor = end_cursor; +- } else { +- break; +- } +- } +- +- // Return in the same order as the input IDs +- Ok(ids.iter().filter_map(|id| issue_map.remove(*id)).collect()) +- } +-} +- + #[cfg(test)] + mod tests { + use super::*; +@@ -2168,674 +1662,4 @@ mod tests { + assert!(err.contains("not found"), "got: {err}"); + assert!(err.contains("#999"), "got: {err}"); + } +- +- // ----------------------------------------------------------------------- +- // execute_github_graphql +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn execute_github_graphql_success() { +- let mut server = mockito::Server::new_async().await; +- +- let mock = server +- .mock("POST", "/graphql") +- .match_header("Authorization", "Bearer test-token") +- .match_header("Content-Type", "application/json") +- .match_header("User-Agent", "fabro") +- .with_status(200) +- .with_body(r#"{"data": {"viewer": {"id": "U_abc"}}}"#) +- .create_async() +- .await; +- +- let client = reqwest::Client::new(); +- let result = execute_github_graphql( +- &client, +- "test-token", +- &format!("{}/graphql", server.url()), +- "query { viewer { id } }", +- serde_json::json!({}), +- ) +- .await +- .unwrap(); +- +- assert_eq!(result["data"]["viewer"]["id"], "U_abc"); +- mock.assert_async().await; +- } +- +- #[tokio::test] +- async fn execute_github_graphql_http_error() { +- let mut server = mockito::Server::new_async().await; +- +- server +- .mock("POST", "/graphql") +- .with_status(500) +- .with_body("Internal Server Error") +- .create_async() +- .await; +- +- let client = reqwest::Client::new(); +- let err = execute_github_graphql( +- &client, +- "token", +- &format!("{}/graphql", server.url()), +- "query { viewer { id } }", +- serde_json::json!({}), +- ) +- .await +- .unwrap_err(); +- +- assert!(err.contains("500"), "got: {err}"); +- } +- +- #[tokio::test] +- async fn execute_github_graphql_graphql_errors() { +- let mut server = mockito::Server::new_async().await; +- +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": null, "errors": [{"message": "Field 'foo' doesn't exist"}]}"#) +- .create_async() +- .await; +- +- let client = reqwest::Client::new(); +- let err = execute_github_graphql( +- &client, +- "token", +- &format!("{}/graphql", server.url()), +- "query { foo }", +- serde_json::json!({}), +- ) +- .await +- .unwrap_err(); +- +- assert!(err.contains("Field 'foo' doesn't exist"), "got: {err}"); +- } +- +- #[tokio::test] +- async fn execute_github_graphql_correct_headers() { +- let mut server = mockito::Server::new_async().await; +- +- let mock = server +- .mock("POST", "/graphql") +- .match_header("Authorization", "Bearer my-token") +- .match_header("Content-Type", "application/json") +- .match_header("User-Agent", "fabro") +- .with_status(200) +- .with_body(r#"{"data": {}}"#) +- .create_async() +- .await; +- +- let client = reqwest::Client::new(); +- execute_github_graphql( +- &client, +- "my-token", +- &format!("{}/graphql", server.url()), +- "query { viewer { id } }", +- serde_json::json!({}), +- ) +- .await +- .unwrap(); +- +- mock.assert_async().await; +- } +- +- // ----------------------------------------------------------------------- +- // GitHubTracker helpers +- // ----------------------------------------------------------------------- +- +- fn mock_github_tracker(server_url: &str, pem: String) -> GitHubTracker { +- GitHubTracker::new( +- GitHubAppCredentials { +- app_id: "test-app".to_string(), +- private_key_pem: pem, +- }, +- reqwest::Client::new(), +- "owner".to_string(), +- "repo".to_string(), +- 1, +- server_url.to_string(), +- ) +- } +- +- fn make_test_issue(state: &str) -> Issue { +- Issue { +- id: "I_issue1".to_string(), +- project_item_id: Some("PVTI_item1".to_string()), +- identifier: "#42".to_string(), +- title: "Fix bug".to_string(), +- description: None, +- priority: None, +- state: state.to_string(), +- branch_name: None, +- url: "https://github.com/owner/repo/issues/42".to_string(), +- assignee_id: None, +- labels: vec![], +- blocked_by: vec![], +- created_at: None, +- updated_at: None, +- } +- } +- +- fn org_project_node_id_response() -> &'static str { +- r#"{"data": {"organization": {"projectV2": {"id": "PVT_abc123"}}}}"# +- } +- +- fn empty_items_response() -> &'static str { +- r#"{"data": {"node": {"items": {"nodes": [], "pageInfo": {"hasNextPage": false, "endCursor": null}}}}}"# +- } +- +- fn single_item_response(status: &str) -> String { +- serde_json::json!({ +- "data": { +- "node": { +- "items": { +- "nodes": [ +- { +- "id": "PVTI_item1", +- "fieldValueByName": {"name": status}, +- "content": { +- "id": "I_issue1", +- "number": 42, +- "title": "Fix bug", +- "body": "Description", +- "url": "https://github.com/owner/repo/issues/42", +- "createdAt": "2026-01-01T00:00:00Z", +- "updatedAt": "2026-01-02T00:00:00Z", +- "assignees": {"nodes": []}, +- "labels": {"nodes": [{"name": "bug"}]} +- } +- } +- ], +- "pageInfo": {"hasNextPage": false, "endCursor": null} +- } +- } +- } +- }) +- .to_string() +- } +- +- // ----------------------------------------------------------------------- +- // project node ID resolution +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn project_node_id_resolved_via_org() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(empty_items_response()) +- .create_async() +- .await; +- +- let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); +- assert!(issues.is_empty()); +- } +- +- #[tokio::test] +- async fn project_node_id_falls_back_to_user() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- // Org query returns null → fall back to user +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"organization": null}}"#) +- .create_async() +- .await; +- // User query succeeds +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"user": {"projectV2": {"id": "PVT_user1"}}}}"#) +- .create_async() +- .await; +- // Items page (empty) +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(empty_items_response()) +- .create_async() +- .await; +- +- let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); +- assert!(issues.is_empty()); +- } +- +- // ----------------------------------------------------------------------- +- // fetch_viewer_id (GitHubTracker) +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn github_tracker_fetch_viewer_id_success() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"viewer": {"id": "U_xyz"}}}"#) +- .create_async() +- .await; +- +- let id = tracker.fetch_viewer_id().await.unwrap(); +- assert_eq!(id, "U_xyz"); +- } +- +- // ----------------------------------------------------------------------- +- // create_comment (GitHubTracker) +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn github_tracker_create_comment_success() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"addComment": {"clientMutationId": null}}}"#) +- .create_async() +- .await; +- +- let issue = make_test_issue("In Progress"); +- tracker.create_comment(&issue, "Great work!").await.unwrap(); +- } +- +- // ----------------------------------------------------------------------- +- // update_issue_state (GitHubTracker) +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn github_tracker_update_issue_state_success() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- // Resolve project node ID (org path) +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- // Field query +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"node": {"field": {"id": "FLD_1", "options": [{"id": "opt-done", "name": "Done"}, {"id": "opt-todo", "name": "Todo"}]}}}}"#) +- .create_async() +- .await; +- // Update mutation +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"updateProjectV2ItemFieldValue": {"projectV2Item": {"id": "PVTI_item1"}}}}"#) +- .create_async() +- .await; +- +- let issue = make_test_issue("In Progress"); +- tracker.update_issue_state(&issue, "Done").await.unwrap(); +- } +- +- #[tokio::test] +- async fn github_tracker_update_issue_state_status_not_found() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- // Resolve project node ID +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- // Field query — options don't include "Nonexistent" +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(r#"{"data": {"node": {"field": {"id": "FLD_1", "options": [{"id": "opt-done", "name": "Done"}]}}}}"#) +- .create_async() +- .await; +- +- let issue = make_test_issue("Todo"); +- let err = tracker +- .update_issue_state(&issue, "Nonexistent") +- .await +- .unwrap_err(); +- assert!(err.contains("Nonexistent"), "got: {err}"); +- assert!(err.contains("not found"), "got: {err}"); +- } +- +- // ----------------------------------------------------------------------- +- // fetch_candidate_issues (GitHubTracker) +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn github_tracker_fetch_candidate_issues_single_page() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(single_item_response("In Progress")) +- .create_async() +- .await; +- +- let issues = tracker +- .fetch_candidate_issues(&["In Progress"]) +- .await +- .unwrap(); +- +- assert_eq!(issues.len(), 1); +- assert_eq!(issues[0].identifier, "#42"); +- assert_eq!(issues[0].state, "In Progress"); +- assert_eq!(issues[0].id, "I_issue1"); +- assert_eq!(issues[0].project_item_id.as_deref(), Some("PVTI_item1")); +- assert_eq!(issues[0].labels, vec!["bug"]); +- assert!(issues[0].branch_name.is_none()); +- assert!(issues[0].priority.is_none()); +- } +- +- #[tokio::test] +- async fn github_tracker_fetch_candidate_issues_empty() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(empty_items_response()) +- .create_async() +- .await; +- +- let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); +- assert!(issues.is_empty()); +- } +- +- #[tokio::test] +- async fn github_tracker_fetch_candidate_issues_status_filtering() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- let items_body = serde_json::json!({ +- "data": { +- "node": { +- "items": { +- "nodes": [ +- { +- "id": "PVTI_done", +- "fieldValueByName": {"name": "Done"}, +- "content": { +- "id": "I_done1", "number": 10, "title": "Done issue", +- "body": null, "url": "https://github.com/owner/repo/issues/10", +- "createdAt": null, "updatedAt": null, +- "assignees": {"nodes": []}, "labels": {"nodes": []} +- } +- }, +- { +- "id": "PVTI_inprog", +- "fieldValueByName": {"name": "In Progress"}, +- "content": { +- "id": "I_inprog1", "number": 20, "title": "Active issue", +- "body": null, "url": "https://github.com/owner/repo/issues/20", +- "createdAt": null, "updatedAt": null, +- "assignees": {"nodes": []}, "labels": {"nodes": []} +- } +- } +- ], +- "pageInfo": {"hasNextPage": false, "endCursor": null} +- } +- } +- } +- }) +- .to_string(); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(items_body) +- .create_async() +- .await; +- +- let issues = tracker +- .fetch_candidate_issues(&["In Progress"]) +- .await +- .unwrap(); +- +- assert_eq!(issues.len(), 1); +- assert_eq!(issues[0].identifier, "#20"); +- } +- +- // ----------------------------------------------------------------------- +- // fetch_issues_by_ids (GitHubTracker) +- // ----------------------------------------------------------------------- +- +- #[tokio::test] +- async fn github_tracker_fetch_issues_by_ids_ordering() { +- let mut server = mockito::Server::new_async().await; +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker(&server.url(), pem); +- +- // Page returns issues in reverse order of what we request +- let items_body = serde_json::json!({ +- "data": { +- "node": { +- "items": { +- "nodes": [ +- { +- "id": "PVTI_b", +- "fieldValueByName": {"name": "Todo"}, +- "content": { +- "id": "I_b", "number": 2, "title": "B", +- "body": null, "url": "https://github.com/owner/repo/issues/2", +- "createdAt": null, "updatedAt": null, +- "assignees": {"nodes": []}, "labels": {"nodes": []} +- } +- }, +- { +- "id": "PVTI_a", +- "fieldValueByName": {"name": "Todo"}, +- "content": { +- "id": "I_a", "number": 1, "title": "A", +- "body": null, "url": "https://github.com/owner/repo/issues/1", +- "createdAt": null, "updatedAt": null, +- "assignees": {"nodes": []}, "labels": {"nodes": []} +- } +- } +- ], +- "pageInfo": {"hasNextPage": false, "endCursor": null} +- } +- } +- } +- }) +- .to_string(); +- +- server +- .mock("GET", "/repos/owner/repo/installation") +- .with_status(200) +- .with_body(r#"{"id": 1}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/app/installations/1/access_tokens") +- .with_status(201) +- .with_body(r#"{"token": "ghs_test"}"#) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(org_project_node_id_response()) +- .create_async() +- .await; +- server +- .mock("POST", "/graphql") +- .with_status(200) +- .with_body(items_body) +- .create_async() +- .await; +- +- // Request in A, B order — should get back in A, B order despite page returning B, A +- let issues = tracker.fetch_issues_by_ids(&["I_a", "I_b"]).await.unwrap(); +- +- assert_eq!(issues.len(), 2); +- assert_eq!(issues[0].id, "I_a"); +- assert_eq!(issues[1].id, "I_b"); +- } +- +- #[tokio::test] +- async fn github_tracker_fetch_issues_by_ids_empty() { +- let pem = test_rsa_key(); +- let tracker = mock_github_tracker("http://unused", pem); +- +- // Empty input → no HTTP calls at all +- let issues = tracker.fetch_issues_by_ids(&[]).await.unwrap(); +- assert!(issues.is_empty()); +- } + } +diff --git a/lib/crates/fabro-linear/Cargo.toml b/lib/crates/fabro-linear/Cargo.toml +deleted file mode 100644 +index 113f8d19..00000000 +--- a/lib/crates/fabro-linear/Cargo.toml ++++ /dev/null +@@ -1,21 +0,0 @@ +-[package] +-name = "fabro-linear" +-edition.workspace = true +-version.workspace = true +-license.workspace = true +-description = "Linear issue tracker API helpers for Fabro" +- +-[lib] +-doctest = false +- +-[dependencies] +-fabro-tracker = { path = "../fabro-tracker" } +-async-trait.workspace = true +-serde.workspace = true +-serde_json.workspace = true +-reqwest.workspace = true +-tracing.workspace = true +- +-[dev-dependencies] +-mockito = "1" +-tokio = { workspace = true, features = ["test-util", "macros"] } +diff --git a/lib/crates/fabro-tracker/Cargo.toml b/lib/crates/fabro-tracker/Cargo.toml +index dc4092e6..f3861748 100644 +--- a/lib/crates/fabro-tracker/Cargo.toml ++++ b/lib/crates/fabro-tracker/Cargo.toml +@@ -9,4 +9,14 @@ description = "Tracker trait and types for issue tracking integrations" + doctest = false + + [dependencies] ++fabro-github = { path = "../fabro-github" } + async-trait.workspace = true ++serde.workspace = true ++serde_json.workspace = true ++reqwest.workspace = true ++tracing.workspace = true ++tokio = { workspace = true } ++ ++[dev-dependencies] ++mockito = "1" ++tokio = { workspace = true, features = ["test-util", "macros"] } +diff --git a/lib/crates/fabro-tracker/src/github.rs b/lib/crates/fabro-tracker/src/github.rs +new file mode 100644 +index 00000000..0a9c437d +--- /dev/null ++++ b/lib/crates/fabro-tracker/src/github.rs +@@ -0,0 +1,1204 @@ ++use async_trait::async_trait; ++use tokio::sync::OnceCell; ++ ++use fabro_github::{ ++ create_installation_access_token_for_projects, sign_app_jwt, GitHubAppCredentials, ++}; ++ ++use crate::{Issue, Tracker}; ++ ++/// Execute a GitHub GraphQL request and return the response JSON. ++async fn execute_github_graphql( ++ client: &reqwest::Client, ++ token: &str, ++ endpoint: &str, ++ query: &str, ++ variables: serde_json::Value, ++) -> Result { ++ let body = serde_json::json!({ ++ "query": query, ++ "variables": variables, ++ }); ++ ++ let resp = client ++ .post(endpoint) ++ .header("Authorization", format!("Bearer {token}")) ++ .header("Content-Type", "application/json") ++ .header("User-Agent", "fabro") ++ .timeout(std::time::Duration::from_secs(30)) ++ .json(&body) ++ .send() ++ .await ++ .map_err(|e| format!("GitHub GraphQL request failed: {e}"))?; ++ ++ let status = resp.status(); ++ if !status.is_success() { ++ let body_text = resp.text().await.unwrap_or_default(); ++ tracing::warn!(status = %status, "GitHub GraphQL API error"); ++ return Err(format!( ++ "GitHub GraphQL API returned HTTP {status}: {body_text}" ++ )); ++ } ++ ++ let response: serde_json::Value = resp ++ .json() ++ .await ++ .map_err(|e| format!("Failed to parse GitHub GraphQL response: {e}"))?; ++ ++ if let Some(errors) = response["errors"].as_array() { ++ if !errors.is_empty() { ++ let messages: Vec<&str> = errors ++ .iter() ++ .filter_map(|e| e["message"].as_str()) ++ .collect(); ++ return Err(format!("GitHub GraphQL errors: {}", messages.join("; "))); ++ } ++ } ++ ++ Ok(response) ++} ++ ++/// A `Tracker` implementation backed by GitHub Projects V2. ++/// ++/// Scoped to a single project board identified by `project_number`. ++pub struct GitHubTracker { ++ creds: GitHubAppCredentials, ++ client: reqwest::Client, ++ owner: String, ++ repo: String, ++ project_number: u64, ++ base_url: String, ++ project_node_id: OnceCell, ++} ++ ++impl GitHubTracker { ++ pub fn new( ++ creds: GitHubAppCredentials, ++ client: reqwest::Client, ++ owner: String, ++ repo: String, ++ project_number: u64, ++ base_url: String, ++ ) -> Self { ++ Self { ++ creds, ++ client, ++ owner, ++ repo, ++ project_number, ++ base_url, ++ project_node_id: OnceCell::new(), ++ } ++ } ++ ++ fn graphql_url(&self) -> String { ++ format!("{}/graphql", self.base_url) ++ } ++ ++ async fn fresh_token(&self) -> Result { ++ let jwt = sign_app_jwt(&self.creds.app_id, &self.creds.private_key_pem)?; ++ create_installation_access_token_for_projects( ++ &self.client, ++ &jwt, ++ &self.owner, ++ &self.repo, ++ &self.base_url, ++ ) ++ .await ++ } ++ ++ async fn resolve_project_node_id(&self, token: &str) -> Result<&str, String> { ++ self.project_node_id ++ .get_or_try_init(|| async { ++ tracing::debug!( ++ owner = %self.owner, ++ project_number = self.project_number, ++ "Resolving GitHub project node ID" ++ ); ++ let graphql_url = self.graphql_url(); ++ let query = r#" ++ query($owner: String!, $number: Int!) { ++ organization(login: $owner) { ++ projectV2(number: $number) { id } ++ } ++ } ++ "#; ++ let variables = serde_json::json!({ ++ "owner": self.owner, ++ "number": self.project_number, ++ }); ++ ++ let resp = execute_github_graphql( ++ &self.client, ++ token, ++ &graphql_url, ++ query, ++ variables.clone(), ++ ) ++ .await?; ++ ++ // Try org path first, fall back to user path ++ if let Some(id) = resp["data"]["organization"]["projectV2"]["id"].as_str() { ++ return Ok(id.to_string()); ++ } ++ ++ let user_query = r#" ++ query($owner: String!, $number: Int!) { ++ user(login: $owner) { ++ projectV2(number: $number) { id } ++ } ++ } ++ "#; ++ let user_resp = execute_github_graphql( ++ &self.client, ++ token, ++ &graphql_url, ++ user_query, ++ variables, ++ ) ++ .await?; ++ ++ user_resp["data"]["user"]["projectV2"]["id"] ++ .as_str() ++ .map(|s| s.to_string()) ++ .ok_or_else(|| { ++ format!( ++ "Project #{} not found for owner '{}'", ++ self.project_number, self.owner ++ ) ++ }) ++ }) ++ .await ++ .map(|s| s.as_str()) ++ } ++} ++ ++fn normalize_github_item(item: &serde_json::Value) -> Option { ++ let project_item_id = item["id"].as_str()?.to_string(); ++ let content = &item["content"]; ++ ++ let id = content["id"].as_str()?.to_string(); ++ let number = content["number"].as_u64()?; ++ let identifier = format!("#{number}"); ++ let title = content["title"].as_str()?.to_string(); ++ let url = content["url"].as_str()?.to_string(); ++ let description = content["body"].as_str().map(|s| s.to_string()); ++ ++ let state = item["fieldValueByName"]["name"] ++ .as_str() ++ .unwrap_or("") ++ .to_string(); ++ ++ let assignee_id = content["assignees"]["nodes"] ++ .as_array() ++ .and_then(|arr| arr.first()) ++ .and_then(|a| a["id"].as_str()) ++ .map(|s| s.to_string()); ++ ++ let labels = content["labels"]["nodes"] ++ .as_array() ++ .map(|arr| { ++ arr.iter() ++ .filter_map(|l| l["name"].as_str()) ++ .map(|s| s.to_lowercase()) ++ .collect() ++ }) ++ .unwrap_or_default(); ++ ++ let created_at = content["createdAt"].as_str().map(|s| s.to_string()); ++ let updated_at = content["updatedAt"].as_str().map(|s| s.to_string()); ++ ++ Some(Issue { ++ id, ++ project_item_id: Some(project_item_id), ++ identifier, ++ title, ++ description, ++ priority: None, ++ state, ++ branch_name: None, ++ url, ++ assignee_id, ++ labels, ++ blocked_by: vec![], ++ created_at, ++ updated_at, ++ }) ++} ++ ++/// Fetch one page of project items. Returns (items, has_next_page, end_cursor). ++async fn fetch_project_items_page( ++ client: &reqwest::Client, ++ token: &str, ++ graphql_url: &str, ++ project_node_id: &str, ++ cursor: Option<&str>, ++) -> Result<(Vec, bool, Option), String> { ++ let query = r#" ++ query($projectId: ID!, $cursor: String) { ++ node(id: $projectId) { ++ ... on ProjectV2 { ++ items(first: 100, after: $cursor) { ++ nodes { ++ id ++ fieldValueByName(name: "Status") { ++ ... on ProjectV2ItemFieldSingleSelectValue { ++ name ++ } ++ } ++ content { ++ ... on Issue { ++ id ++ number ++ title ++ body ++ url ++ createdAt ++ updatedAt ++ assignees(first: 1) { nodes { id } } ++ labels(first: 20) { nodes { name } } ++ } ++ } ++ } ++ pageInfo { hasNextPage endCursor } ++ } ++ } ++ } ++ } ++ "#; ++ ++ let variables = serde_json::json!({ ++ "projectId": project_node_id, ++ "cursor": cursor, ++ }); ++ ++ let resp = execute_github_graphql(client, token, graphql_url, query, variables).await?; ++ ++ let items_node = &resp["data"]["node"]["items"]; ++ let nodes = items_node["nodes"].as_array().cloned().unwrap_or_default(); ++ let has_next = items_node["pageInfo"]["hasNextPage"] ++ .as_bool() ++ .unwrap_or(false); ++ let end_cursor = items_node["pageInfo"]["endCursor"] ++ .as_str() ++ .map(|s| s.to_string()); ++ ++ Ok((nodes, has_next, end_cursor)) ++} ++ ++#[async_trait] ++impl Tracker for GitHubTracker { ++ async fn fetch_viewer_id(&self) -> Result { ++ tracing::debug!("Fetching viewer ID from GitHub"); ++ let token = self.fresh_token().await?; ++ let query = "query { viewer { id } }"; ++ let resp = execute_github_graphql( ++ &self.client, ++ &token, ++ &self.graphql_url(), ++ query, ++ serde_json::json!({}), ++ ) ++ .await?; ++ ++ resp["data"]["viewer"]["id"] ++ .as_str() ++ .map(|s| s.to_string()) ++ .ok_or_else(|| "Missing viewer id in GitHub response".to_string()) ++ } ++ ++ async fn create_comment(&self, issue: &Issue, body: &str) -> Result<(), String> { ++ tracing::debug!(issue_id = %issue.id, "Creating comment on GitHub issue"); ++ let token = self.fresh_token().await?; ++ let query = r#" ++ mutation($subjectId: ID!, $body: String!) { ++ addComment(input: { subjectId: $subjectId, body: $body }) { ++ clientMutationId ++ } ++ } ++ "#; ++ let variables = serde_json::json!({ ++ "subjectId": issue.id, ++ "body": body, ++ }); ++ execute_github_graphql(&self.client, &token, &self.graphql_url(), query, variables).await?; ++ Ok(()) ++ } ++ ++ async fn update_issue_state(&self, issue: &Issue, state_name: &str) -> Result<(), String> { ++ let project_item_id = issue ++ .project_item_id ++ .as_deref() ++ .ok_or("update_issue_state requires project_item_id")?; ++ ++ tracing::debug!( ++ project_item_id, ++ state_name, ++ "Updating GitHub project item status" ++ ); ++ ++ let token = self.fresh_token().await?; ++ let project_node_id = self.resolve_project_node_id(&token).await?; ++ let graphql_url = self.graphql_url(); ++ ++ // Step 1: Get the Status field ID and the target option ID ++ let field_query = r#" ++ query($projectId: ID!) { ++ node(id: $projectId) { ++ ... on ProjectV2 { ++ field(name: "Status") { ++ ... on ProjectV2SingleSelectField { ++ id ++ options { id name } ++ } ++ } ++ } ++ } ++ } ++ "#; ++ let field_resp = execute_github_graphql( ++ &self.client, ++ &token, ++ &graphql_url, ++ field_query, ++ serde_json::json!({ "projectId": project_node_id }), ++ ) ++ .await?; ++ ++ let field = &field_resp["data"]["node"]["field"]; ++ let field_id = field["id"] ++ .as_str() ++ .ok_or("Missing Status field id")? ++ .to_string(); ++ ++ let option_id = field["options"] ++ .as_array() ++ .and_then(|opts| { ++ opts.iter().find(|o| { ++ o["name"] ++ .as_str() ++ .is_some_and(|n| n.eq_ignore_ascii_case(state_name)) ++ }) ++ }) ++ .and_then(|o| o["id"].as_str()) ++ .ok_or_else(|| format!("Status option '{state_name}' not found in project"))? ++ .to_string(); ++ ++ // Step 2: Update the field value ++ let update_query = r#" ++ mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) { ++ updateProjectV2ItemFieldValue(input: { ++ projectId: $projectId ++ itemId: $itemId ++ fieldId: $fieldId ++ value: { singleSelectOptionId: $optionId } ++ }) { ++ projectV2Item { id } ++ } ++ } ++ "#; ++ execute_github_graphql( ++ &self.client, ++ &token, ++ &graphql_url, ++ update_query, ++ serde_json::json!({ ++ "projectId": project_node_id, ++ "itemId": project_item_id, ++ "fieldId": field_id, ++ "optionId": option_id, ++ }), ++ ) ++ .await?; ++ ++ Ok(()) ++ } ++ ++ async fn fetch_candidate_issues(&self, state_names: &[&str]) -> Result, String> { ++ tracing::debug!( ++ owner = %self.owner, ++ project_number = self.project_number, ++ ?state_names, ++ "Fetching candidate issues from GitHub project" ++ ); ++ ++ let token = self.fresh_token().await?; ++ let project_node_id = self.resolve_project_node_id(&token).await?; ++ let graphql_url = self.graphql_url(); ++ ++ let mut all_issues = Vec::new(); ++ let mut cursor: Option = None; ++ ++ loop { ++ let (nodes, has_next, end_cursor) = fetch_project_items_page( ++ &self.client, ++ &token, ++ &graphql_url, ++ project_node_id, ++ cursor.as_deref(), ++ ) ++ .await?; ++ ++ for node in &nodes { ++ if let Some(issue) = normalize_github_item(node) { ++ if state_names ++ .iter() ++ .any(|s| s.eq_ignore_ascii_case(&issue.state)) ++ { ++ all_issues.push(issue); ++ } ++ } ++ } ++ ++ if has_next { ++ cursor = end_cursor; ++ } else { ++ break; ++ } ++ } ++ ++ Ok(all_issues) ++ } ++ ++ async fn fetch_issues_by_ids(&self, ids: &[&str]) -> Result, String> { ++ if ids.is_empty() { ++ return Ok(Vec::new()); ++ } ++ ++ tracing::debug!( ++ count = ids.len(), ++ "Fetching GitHub issues by ID from project" ++ ); ++ ++ let token = self.fresh_token().await?; ++ let project_node_id = self.resolve_project_node_id(&token).await?; ++ let graphql_url = self.graphql_url(); ++ ++ let id_set: std::collections::HashSet<&str> = ids.iter().copied().collect(); ++ let mut issue_map: std::collections::HashMap = ++ std::collections::HashMap::new(); ++ let mut cursor: Option = None; ++ ++ loop { ++ let (nodes, has_next, end_cursor) = fetch_project_items_page( ++ &self.client, ++ &token, ++ &graphql_url, ++ project_node_id, ++ cursor.as_deref(), ++ ) ++ .await?; ++ ++ for node in &nodes { ++ if let Some(issue) = normalize_github_item(node) { ++ if id_set.contains(issue.id.as_str()) { ++ issue_map.insert(issue.id.clone(), issue); ++ } ++ } ++ } ++ ++ if has_next { ++ cursor = end_cursor; ++ } else { ++ break; ++ } ++ } ++ ++ // Return in the same order as the input IDs ++ Ok(ids.iter().filter_map(|id| issue_map.remove(*id)).collect()) ++ } ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ use crate::Issue; ++ use fabro_github::GitHubAppCredentials; ++ ++ fn test_rsa_key() -> String { ++ use std::process::Command; ++ let output = Command::new("openssl") ++ .args([ ++ "genpkey", ++ "-algorithm", ++ "RSA", ++ "-pkeyopt", ++ "rsa_keygen_bits:2048", ++ ]) ++ .output() ++ .expect("openssl should be available"); ++ assert!(output.status.success(), "openssl keygen failed"); ++ String::from_utf8(output.stdout).unwrap() ++ } ++ ++ // ----------------------------------------------------------------------- ++ // execute_github_graphql ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn execute_github_graphql_success() { ++ let mut server = mockito::Server::new_async().await; ++ ++ let mock = server ++ .mock("POST", "/graphql") ++ .match_header("Authorization", "Bearer test-token") ++ .match_header("Content-Type", "application/json") ++ .match_header("User-Agent", "fabro") ++ .with_status(200) ++ .with_body(r#"{"data": {"viewer": {"id": "U_abc"}}}"#) ++ .create_async() ++ .await; ++ ++ let client = reqwest::Client::new(); ++ let result = execute_github_graphql( ++ &client, ++ "test-token", ++ &format!("{}/graphql", server.url()), ++ "query { viewer { id } }", ++ serde_json::json!({}), ++ ) ++ .await ++ .unwrap(); ++ ++ assert_eq!(result["data"]["viewer"]["id"], "U_abc"); ++ mock.assert_async().await; ++ } ++ ++ #[tokio::test] ++ async fn execute_github_graphql_http_error() { ++ let mut server = mockito::Server::new_async().await; ++ ++ server ++ .mock("POST", "/graphql") ++ .with_status(401) ++ .with_body("Unauthorized") ++ .create_async() ++ .await; ++ ++ let client = reqwest::Client::new(); ++ let err = execute_github_graphql( ++ &client, ++ "bad-token", ++ &format!("{}/graphql", server.url()), ++ "query { viewer { id } }", ++ serde_json::json!({}), ++ ) ++ .await ++ .unwrap_err(); ++ ++ assert!(err.contains("401"), "got: {err}"); ++ } ++ ++ #[tokio::test] ++ async fn execute_github_graphql_errors_array() { ++ let mut server = mockito::Server::new_async().await; ++ ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": null, "errors": [{"message": "Not found"}]}"#) ++ .create_async() ++ .await; ++ ++ let client = reqwest::Client::new(); ++ let err = execute_github_graphql( ++ &client, ++ "token", ++ &format!("{}/graphql", server.url()), ++ "query { bad }", ++ serde_json::json!({}), ++ ) ++ .await ++ .unwrap_err(); ++ ++ assert!(err.contains("Not found"), "got: {err}"); ++ } ++ ++ #[tokio::test] ++ async fn execute_github_graphql_correct_headers() { ++ let mut server = mockito::Server::new_async().await; ++ ++ let mock = server ++ .mock("POST", "/graphql") ++ .match_header("Authorization", "Bearer my-token") ++ .match_header("Content-Type", "application/json") ++ .match_header("User-Agent", "fabro") ++ .with_status(200) ++ .with_body(r#"{"data": {}}"#) ++ .create_async() ++ .await; ++ ++ let client = reqwest::Client::new(); ++ execute_github_graphql( ++ &client, ++ "my-token", ++ &format!("{}/graphql", server.url()), ++ "query { viewer { id } }", ++ serde_json::json!({}), ++ ) ++ .await ++ .unwrap(); ++ ++ mock.assert_async().await; ++ } ++ ++ // ----------------------------------------------------------------------- ++ // GitHubTracker helpers ++ // ----------------------------------------------------------------------- ++ ++ fn mock_github_tracker(server_url: &str, pem: String) -> GitHubTracker { ++ GitHubTracker::new( ++ GitHubAppCredentials { ++ app_id: "test-app".to_string(), ++ private_key_pem: pem, ++ }, ++ reqwest::Client::new(), ++ "owner".to_string(), ++ "repo".to_string(), ++ 1, ++ server_url.to_string(), ++ ) ++ } ++ ++ fn make_test_issue(state: &str) -> Issue { ++ Issue { ++ id: "I_issue1".to_string(), ++ project_item_id: Some("PVTI_item1".to_string()), ++ identifier: "#42".to_string(), ++ title: "Fix bug".to_string(), ++ description: None, ++ priority: None, ++ state: state.to_string(), ++ branch_name: None, ++ url: "https://github.com/owner/repo/issues/42".to_string(), ++ assignee_id: None, ++ labels: vec![], ++ blocked_by: vec![], ++ created_at: None, ++ updated_at: None, ++ } ++ } ++ ++ fn org_project_node_id_response() -> &'static str { ++ r#"{"data": {"organization": {"projectV2": {"id": "PVT_abc123"}}}}"# ++ } ++ ++ fn empty_items_response() -> &'static str { ++ r#"{"data": {"node": {"items": {"nodes": [], "pageInfo": {"hasNextPage": false, "endCursor": null}}}}}"# ++ } ++ ++ fn single_item_response(status: &str) -> String { ++ serde_json::json!({ ++ "data": { ++ "node": { ++ "items": { ++ "nodes": [ ++ { ++ "id": "PVTI_item1", ++ "fieldValueByName": {"name": status}, ++ "content": { ++ "id": "I_issue1", ++ "number": 42, ++ "title": "Fix bug", ++ "body": "Description", ++ "url": "https://github.com/owner/repo/issues/42", ++ "createdAt": "2026-01-01T00:00:00Z", ++ "updatedAt": "2026-01-02T00:00:00Z", ++ "assignees": {"nodes": []}, ++ "labels": {"nodes": [{"name": "bug"}]} ++ } ++ } ++ ], ++ "pageInfo": {"hasNextPage": false, "endCursor": null} ++ } ++ } ++ } ++ }) ++ .to_string() ++ } ++ ++ // ----------------------------------------------------------------------- ++ // project node ID resolution ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn project_node_id_resolved_via_org() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(empty_items_response()) ++ .create_async() ++ .await; ++ ++ let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); ++ assert!(issues.is_empty()); ++ } ++ ++ #[tokio::test] ++ async fn project_node_id_falls_back_to_user() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ // Org query returns null → fall back to user ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"organization": null}}"#) ++ .create_async() ++ .await; ++ // User query succeeds ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"user": {"projectV2": {"id": "PVT_user1"}}}}"#) ++ .create_async() ++ .await; ++ // Items page (empty) ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(empty_items_response()) ++ .create_async() ++ .await; ++ ++ let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); ++ assert!(issues.is_empty()); ++ } ++ ++ // ----------------------------------------------------------------------- ++ // fetch_viewer_id (GitHubTracker) ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_viewer_id_success() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"viewer": {"id": "U_xyz"}}}"#) ++ .create_async() ++ .await; ++ ++ let id = tracker.fetch_viewer_id().await.unwrap(); ++ assert_eq!(id, "U_xyz"); ++ } ++ ++ // ----------------------------------------------------------------------- ++ // create_comment (GitHubTracker) ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn github_tracker_create_comment_success() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"addComment": {"clientMutationId": null}}}"#) ++ .create_async() ++ .await; ++ ++ let issue = make_test_issue("In Progress"); ++ tracker.create_comment(&issue, "Great work!").await.unwrap(); ++ } ++ ++ // ----------------------------------------------------------------------- ++ // update_issue_state (GitHubTracker) ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn github_tracker_update_issue_state_success() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ // Resolve project node ID (org path) ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ // Field query ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"node": {"field": {"id": "FLD_1", "options": [{"id": "opt-done", "name": "Done"}, {"id": "opt-todo", "name": "Todo"}]}}}}"#) ++ .create_async() ++ .await; ++ // Update mutation ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"updateProjectV2ItemFieldValue": {"projectV2Item": {"id": "PVTI_item1"}}}}"#) ++ .create_async() ++ .await; ++ ++ let issue = make_test_issue("In Progress"); ++ tracker.update_issue_state(&issue, "Done").await.unwrap(); ++ } ++ ++ #[tokio::test] ++ async fn github_tracker_update_issue_state_status_not_found() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ // Resolve project node ID ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ // Field query — options don't include "Nonexistent" ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(r#"{"data": {"node": {"field": {"id": "FLD_1", "options": [{"id": "opt-done", "name": "Done"}]}}}}"#) ++ .create_async() ++ .await; ++ ++ let issue = make_test_issue("Todo"); ++ let err = tracker ++ .update_issue_state(&issue, "Nonexistent") ++ .await ++ .unwrap_err(); ++ assert!(err.contains("Nonexistent"), "got: {err}"); ++ assert!(err.contains("not found"), "got: {err}"); ++ } ++ ++ // ----------------------------------------------------------------------- ++ // fetch_candidate_issues (GitHubTracker) ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_candidate_issues_single_page() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(single_item_response("In Progress")) ++ .create_async() ++ .await; ++ ++ let issues = tracker ++ .fetch_candidate_issues(&["In Progress"]) ++ .await ++ .unwrap(); ++ ++ assert_eq!(issues.len(), 1); ++ assert_eq!(issues[0].identifier, "#42"); ++ assert_eq!(issues[0].state, "In Progress"); ++ assert_eq!(issues[0].id, "I_issue1"); ++ assert_eq!(issues[0].project_item_id.as_deref(), Some("PVTI_item1")); ++ assert_eq!(issues[0].labels, vec!["bug"]); ++ assert!(issues[0].branch_name.is_none()); ++ assert!(issues[0].priority.is_none()); ++ } ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_candidate_issues_empty() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(empty_items_response()) ++ .create_async() ++ .await; ++ ++ let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); ++ assert!(issues.is_empty()); ++ } ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_candidate_issues_status_filtering() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ let items_body = serde_json::json!({ ++ "data": { ++ "node": { ++ "items": { ++ "nodes": [ ++ { ++ "id": "PVTI_done", ++ "fieldValueByName": {"name": "Done"}, ++ "content": { ++ "id": "I_done1", "number": 10, "title": "Done issue", ++ "body": null, "url": "https://github.com/owner/repo/issues/10", ++ "createdAt": null, "updatedAt": null, ++ "assignees": {"nodes": []}, "labels": {"nodes": []} ++ } ++ }, ++ { ++ "id": "PVTI_inprog", ++ "fieldValueByName": {"name": "In Progress"}, ++ "content": { ++ "id": "I_inprog1", "number": 20, "title": "Active issue", ++ "body": null, "url": "https://github.com/owner/repo/issues/20", ++ "createdAt": null, "updatedAt": null, ++ "assignees": {"nodes": []}, "labels": {"nodes": []} ++ } ++ } ++ ], ++ "pageInfo": {"hasNextPage": false, "endCursor": null} ++ } ++ } ++ } ++ }) ++ .to_string(); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(items_body) ++ .create_async() ++ .await; ++ ++ let issues = tracker ++ .fetch_candidate_issues(&["In Progress"]) ++ .await ++ .unwrap(); ++ ++ assert_eq!(issues.len(), 1); ++ assert_eq!(issues[0].identifier, "#20"); ++ } ++ ++ // ----------------------------------------------------------------------- ++ // fetch_issues_by_ids (GitHubTracker) ++ // ----------------------------------------------------------------------- ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_issues_by_ids_ordering() { ++ let mut server = mockito::Server::new_async().await; ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker(&server.url(), pem); ++ ++ // Page returns issues in reverse order of what we request ++ let items_body = serde_json::json!({ ++ "data": { ++ "node": { ++ "items": { ++ "nodes": [ ++ { ++ "id": "PVTI_b", ++ "fieldValueByName": {"name": "Todo"}, ++ "content": { ++ "id": "I_b", "number": 2, "title": "B", ++ "body": null, "url": "https://github.com/owner/repo/issues/2", ++ "createdAt": null, "updatedAt": null, ++ "assignees": {"nodes": []}, "labels": {"nodes": []} ++ } ++ }, ++ { ++ "id": "PVTI_a", ++ "fieldValueByName": {"name": "Todo"}, ++ "content": { ++ "id": "I_a", "number": 1, "title": "A", ++ "body": null, "url": "https://github.com/owner/repo/issues/1", ++ "createdAt": null, "updatedAt": null, ++ "assignees": {"nodes": []}, "labels": {"nodes": []} ++ } ++ } ++ ], ++ "pageInfo": {"hasNextPage": false, "endCursor": null} ++ } ++ } ++ } ++ }) ++ .to_string(); ++ ++ server ++ .mock("GET", "/repos/owner/repo/installation") ++ .with_status(200) ++ .with_body(r#"{"id": 1}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/app/installations/1/access_tokens") ++ .with_status(201) ++ .with_body(r#"{"token": "ghs_test"}"#) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(org_project_node_id_response()) ++ .create_async() ++ .await; ++ server ++ .mock("POST", "/graphql") ++ .with_status(200) ++ .with_body(items_body) ++ .create_async() ++ .await; ++ ++ // Request in A, B order — should get back in A, B order despite page returning B, A ++ let issues = tracker.fetch_issues_by_ids(&["I_a", "I_b"]).await.unwrap(); ++ ++ assert_eq!(issues.len(), 2); ++ assert_eq!(issues[0].id, "I_a"); ++ assert_eq!(issues[1].id, "I_b"); ++ } ++ ++ #[tokio::test] ++ async fn github_tracker_fetch_issues_by_ids_empty() { ++ let pem = test_rsa_key(); ++ let tracker = mock_github_tracker("http://unused", pem); ++ ++ // Empty input → no HTTP calls at all ++ let issues = tracker.fetch_issues_by_ids(&[]).await.unwrap(); ++ assert!(issues.is_empty()); ++ } ++} +diff --git a/lib/crates/fabro-tracker/src/lib.rs b/lib/crates/fabro-tracker/src/lib.rs +index 1dc9554d..d2bc5677 100644 +--- a/lib/crates/fabro-tracker/src/lib.rs ++++ b/lib/crates/fabro-tracker/src/lib.rs +@@ -1,5 +1,11 @@ + use async_trait::async_trait; + ++pub mod github; ++pub mod linear; ++ ++pub use github::GitHubTracker; ++pub use linear::{LinearConfig, LinearTracker, LINEAR_API_ENDPOINT}; ++ + #[derive(Debug, Clone)] + pub struct BlockerRef { + pub id: String, +diff --git a/lib/crates/fabro-linear/src/lib.rs b/lib/crates/fabro-tracker/src/linear.rs +similarity index 71% +rename from lib/crates/fabro-linear/src/lib.rs +rename to lib/crates/fabro-tracker/src/linear.rs +index 02b4b666..2dc211b8 100644 +--- a/lib/crates/fabro-linear/src/lib.rs ++++ b/lib/crates/fabro-tracker/src/linear.rs +@@ -1,7 +1,10 @@ + use std::collections::HashMap; + ++use async_trait::async_trait; + use serde_json::Value; + ++use crate::{BlockerRef, Issue, Tracker}; ++ + pub const LINEAR_API_ENDPOINT: &str = "https://api.linear.app/graphql"; + + const BLOCKS_RELATION_TYPE: &str = "blocks"; +@@ -21,30 +24,6 @@ impl LinearConfig { + } + } + +-#[derive(Debug, Clone)] +-pub struct Issue { +- pub id: String, +- pub identifier: String, +- pub title: String, +- pub description: Option, +- pub priority: Option, +- pub state: String, +- pub branch_name: Option, +- pub url: String, +- pub assignee_id: Option, +- pub labels: Vec, +- pub blocked_by: Vec, +- pub created_at: Option, +- pub updated_at: Option, +-} +- +-#[derive(Debug, Clone)] +-pub struct BlockerRef { +- pub id: String, +- pub identifier: String, +- pub state: String, +-} +- + const ISSUE_FIELDS: &str = " + id + identifier +@@ -122,6 +101,7 @@ fn normalize_issue(node: &Value) -> Result { + + Ok(Issue { + id, ++ project_item_id: None, + identifier, + title, + description, +@@ -183,209 +163,210 @@ async fn execute_graphql( + Ok(response) + } + +-pub async fn fetch_viewer_id( +- client: &reqwest::Client, +- config: &LinearConfig, +-) -> Result { +- tracing::debug!("Fetching viewer ID from Linear"); +- let query = "query { viewer { id } }"; +- let response = execute_graphql(client, config, query, serde_json::json!({})).await?; ++fn extract_issues(response: &Value) -> Result, String> { ++ let nodes = response["data"]["issues"]["nodes"] ++ .as_array() ++ .ok_or("Missing issues nodes in response")?; + +- response["data"]["viewer"]["id"] +- .as_str() +- .map(|s| s.to_string()) +- .ok_or_else(|| "Missing viewer id in response".to_string()) ++ nodes.iter().map(normalize_issue).collect() + } + +-pub async fn create_comment( +- client: &reqwest::Client, +- config: &LinearConfig, +- issue_id: &str, +- body: &str, +-) -> Result<(), String> { +- tracing::debug!(issue_id, "Creating comment on Linear issue"); +- let query = r#" +- mutation($issueId: String!, $body: String!) { +- commentCreate(input: { issueId: $issueId, body: $body }) { +- success +- } +- } +- "#; +- +- let variables = serde_json::json!({ +- "issueId": issue_id, +- "body": body, +- }); +- +- let response = execute_graphql(client, config, query, variables).await?; ++/// A `Tracker` implementation backed by Linear. ++pub struct LinearTracker { ++ config: LinearConfig, ++ client: reqwest::Client, ++ project_slug: String, ++} + +- let success = response["data"]["commentCreate"]["success"] +- .as_bool() +- .unwrap_or(false); +- if !success { +- return Err("Linear commentCreate returned success: false".to_string()); ++impl LinearTracker { ++ pub fn new(config: LinearConfig, client: reqwest::Client, project_slug: String) -> Self { ++ Self { ++ config, ++ client, ++ project_slug, ++ } + } +- +- Ok(()) + } + +-pub async fn update_issue_state( +- client: &reqwest::Client, +- config: &LinearConfig, +- issue_id: &str, +- state_name: &str, +-) -> Result<(), String> { +- tracing::debug!(issue_id, state_name, "Updating Linear issue state"); +- // Step 1: Resolve state name to ID via the issue's team +- let resolve_query = r#" +- query($issueId: String!, $stateName: String!) { +- issue(id: $issueId) { +- team { +- states(filter: { name: { eq: $stateName } }) { +- nodes { id } +- } ++#[async_trait] ++impl Tracker for LinearTracker { ++ async fn fetch_viewer_id(&self) -> Result { ++ tracing::debug!("Fetching viewer ID from Linear"); ++ let query = "query { viewer { id } }"; ++ let response = ++ execute_graphql(&self.client, &self.config, query, serde_json::json!({})).await?; ++ ++ response["data"]["viewer"]["id"] ++ .as_str() ++ .map(|s| s.to_string()) ++ .ok_or_else(|| "Missing viewer id in response".to_string()) ++ } ++ ++ async fn create_comment(&self, issue: &Issue, body: &str) -> Result<(), String> { ++ tracing::debug!(issue_id = %issue.id, "Creating comment on Linear issue"); ++ let query = r#" ++ mutation($issueId: String!, $body: String!) { ++ commentCreate(input: { issueId: $issueId, body: $body }) { ++ success + } + } +- } +- "#; ++ "#; + +- let resolve_vars = serde_json::json!({ +- "issueId": issue_id, +- "stateName": state_name, +- }); ++ let variables = serde_json::json!({ ++ "issueId": issue.id, ++ "body": body, ++ }); + +- let resolve_resp = execute_graphql(client, config, resolve_query, resolve_vars).await?; ++ let response = execute_graphql(&self.client, &self.config, query, variables).await?; + +- let state_id = resolve_resp["data"]["issue"]["team"]["states"]["nodes"] +- .as_array() +- .and_then(|arr| arr.first()) +- .and_then(|node| node["id"].as_str()) +- .ok_or_else(|| format!("State '{state_name}' not found for issue {issue_id}"))? +- .to_string(); ++ let success = response["data"]["commentCreate"]["success"] ++ .as_bool() ++ .unwrap_or(false); ++ if !success { ++ return Err("Linear commentCreate returned success: false".to_string()); ++ } + +- // Step 2: Update the issue +- let update_query = r#" +- mutation($issueId: String!, $stateId: String!) { +- issueUpdate(id: $issueId, input: { stateId: $stateId }) { +- success ++ Ok(()) ++ } ++ ++ async fn update_issue_state(&self, issue: &Issue, state_name: &str) -> Result<(), String> { ++ tracing::debug!(issue_id = %issue.id, state_name, "Updating Linear issue state"); ++ // Step 1: Resolve state name to ID via the issue's team ++ let resolve_query = r#" ++ query($issueId: String!, $stateName: String!) { ++ issue(id: $issueId) { ++ team { ++ states(filter: { name: { eq: $stateName } }) { ++ nodes { id } ++ } ++ } ++ } + } +- } +- "#; ++ "#; + +- let update_vars = serde_json::json!({ +- "issueId": issue_id, +- "stateId": state_id, +- }); ++ let resolve_vars = serde_json::json!({ ++ "issueId": issue.id, ++ "stateName": state_name, ++ }); + +- let update_resp = execute_graphql(client, config, update_query, update_vars).await?; ++ let resolve_resp = ++ execute_graphql(&self.client, &self.config, resolve_query, resolve_vars).await?; ++ ++ let state_id = resolve_resp["data"]["issue"]["team"]["states"]["nodes"] ++ .as_array() ++ .and_then(|arr| arr.first()) ++ .and_then(|node| node["id"].as_str()) ++ .ok_or_else(|| format!("State '{state_name}' not found for issue {}", issue.id))? ++ .to_string(); ++ ++ // Step 2: Update the issue ++ let update_query = r#" ++ mutation($issueId: String!, $stateId: String!) { ++ issueUpdate(id: $issueId, input: { stateId: $stateId }) { ++ success ++ } ++ } ++ "#; + +- let success = update_resp["data"]["issueUpdate"]["success"] +- .as_bool() +- .unwrap_or(false); +- if !success { +- return Err("Linear issueUpdate returned success: false".to_string()); +- } ++ let update_vars = serde_json::json!({ ++ "issueId": issue.id, ++ "stateId": state_id, ++ }); + +- Ok(()) +-} ++ let update_resp = ++ execute_graphql(&self.client, &self.config, update_query, update_vars).await?; + +-fn extract_issues(response: &Value) -> Result, String> { +- let nodes = response["data"]["issues"]["nodes"] +- .as_array() +- .ok_or("Missing issues nodes in response")?; ++ let success = update_resp["data"]["issueUpdate"]["success"] ++ .as_bool() ++ .unwrap_or(false); ++ if !success { ++ return Err("Linear issueUpdate returned success: false".to_string()); ++ } + +- nodes.iter().map(normalize_issue).collect() +-} ++ Ok(()) ++ } + +-pub async fn fetch_candidate_issues( +- client: &reqwest::Client, +- config: &LinearConfig, +- project_slug: &str, +- state_names: &[&str], +-) -> Result, String> { +- tracing::debug!( +- project_slug, +- ?state_names, +- "Fetching candidate issues from Linear" +- ); +- +- let query = format!( +- r#" +- query($slug: String!, $states: [String!]!, $cursor: String) {{ +- issues( +- first: 50 +- after: $cursor +- filter: {{ +- project: {{ slugId: {{ eq: $slug }} }} +- state: {{ name: {{ in: $states }} }} ++ async fn fetch_candidate_issues(&self, state_names: &[&str]) -> Result, String> { ++ tracing::debug!( ++ project_slug = %self.project_slug, ++ ?state_names, ++ "Fetching candidate issues from Linear" ++ ); ++ ++ let query = format!( ++ r#" ++ query($slug: String!, $states: [String!]!, $cursor: String) {{ ++ issues( ++ first: 50 ++ after: $cursor ++ filter: {{ ++ project: {{ slugId: {{ eq: $slug }} }} ++ state: {{ name: {{ in: $states }} }} ++ }} ++ ) {{ ++ nodes {{ {ISSUE_FIELDS} }} ++ pageInfo {{ hasNextPage endCursor }} + }} +- ) {{ +- nodes {{ {ISSUE_FIELDS} }} +- pageInfo {{ hasNextPage endCursor }} + }} +- }} +- "# +- ); ++ "# ++ ); + +- let mut all_issues = Vec::new(); +- let mut cursor: Option = None; ++ let mut all_issues = Vec::new(); ++ let mut cursor: Option = None; + +- loop { +- let variables = serde_json::json!({ +- "slug": project_slug, +- "states": state_names, +- "cursor": cursor, +- }); ++ loop { ++ let variables = serde_json::json!({ ++ "slug": self.project_slug, ++ "states": state_names, ++ "cursor": cursor, ++ }); + +- let response = execute_graphql(client, config, &query, variables).await?; ++ let response = execute_graphql(&self.client, &self.config, &query, variables).await?; + +- all_issues.extend(extract_issues(&response)?); ++ all_issues.extend(extract_issues(&response)?); + +- let page_info = &response["data"]["issues"]["pageInfo"]; +- if page_info["hasNextPage"].as_bool() == Some(true) { +- cursor = page_info["endCursor"].as_str().map(|s| s.to_string()); +- } else { +- break; ++ let page_info = &response["data"]["issues"]["pageInfo"]; ++ if page_info["hasNextPage"].as_bool() == Some(true) { ++ cursor = page_info["endCursor"].as_str().map(|s| s.to_string()); ++ } else { ++ break; ++ } + } +- } +- +- Ok(all_issues) +-} + +-pub async fn fetch_issues_by_ids( +- client: &reqwest::Client, +- config: &LinearConfig, +- ids: &[&str], +-) -> Result, String> { +- if ids.is_empty() { +- return Ok(Vec::new()); ++ Ok(all_issues) + } + +- tracing::debug!(count = ids.len(), "Fetching issues by ID from Linear"); ++ async fn fetch_issues_by_ids(&self, ids: &[&str]) -> Result, String> { ++ if ids.is_empty() { ++ return Ok(Vec::new()); ++ } ++ ++ tracing::debug!(count = ids.len(), "Fetching issues by ID from Linear"); + +- let query = format!( +- r#" +- query($ids: [ID!]!) {{ +- issues(filter: {{ id: {{ in: $ids }} }}) {{ +- nodes {{ {ISSUE_FIELDS} }} ++ let query = format!( ++ r#" ++ query($ids: [ID!]!) {{ ++ issues(filter: {{ id: {{ in: $ids }} }}) {{ ++ nodes {{ {ISSUE_FIELDS} }} ++ }} + }} +- }} +- "# +- ); ++ "# ++ ); + +- let mut issue_map: HashMap = HashMap::with_capacity(ids.len()); ++ let mut issue_map: HashMap = HashMap::with_capacity(ids.len()); + +- for batch in ids.chunks(50) { +- let variables = serde_json::json!({ "ids": batch }); +- let response = execute_graphql(client, config, &query, variables).await?; ++ for batch in ids.chunks(50) { ++ let variables = serde_json::json!({ "ids": batch }); ++ let response = execute_graphql(&self.client, &self.config, &query, variables).await?; + +- for issue in extract_issues(&response)? { +- issue_map.insert(issue.id.clone(), issue); ++ for issue in extract_issues(&response)? { ++ issue_map.insert(issue.id.clone(), issue); ++ } + } +- } + +- // Return in the same order as the input IDs +- Ok(ids.iter().filter_map(|id| issue_map.remove(*id)).collect()) ++ // Return in the same order as the input IDs ++ Ok(ids.iter().filter_map(|id| issue_map.remove(*id)).collect()) ++ } + } + + #[cfg(test)] +@@ -438,6 +419,7 @@ mod tests { + let issue = normalize_issue(&node).unwrap(); + + assert_eq!(issue.id, "issue-1"); ++ assert!(issue.project_item_id.is_none()); + assert_eq!(issue.identifier, "ABC-123"); + assert_eq!(issue.title, "Fix the bug"); + assert_eq!(issue.description.as_deref(), Some("Detailed description")); +@@ -479,6 +461,7 @@ mod tests { + let issue = normalize_issue(&node).unwrap(); + + assert_eq!(issue.id, "issue-2"); ++ assert!(issue.project_item_id.is_none()); + assert!(issue.description.is_none()); + assert!(issue.priority.is_none()); + assert!(issue.branch_name.is_none()); +@@ -716,7 +699,7 @@ mod tests { + } + + // ----------------------------------------------------------------------- +- // fetch_viewer_id ++ // LinearTracker::fetch_viewer_id + // ----------------------------------------------------------------------- + + #[tokio::test] +@@ -731,8 +714,8 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let id = fetch_viewer_id(&client, &config).await.unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let id = tracker.fetch_viewer_id().await.unwrap(); + assert_eq!(id, "user-abc"); + } + +@@ -748,13 +731,13 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let err = fetch_viewer_id(&client, &config).await.unwrap_err(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let err = tracker.fetch_viewer_id().await.unwrap_err(); + assert!(err.contains("401"), "got: {err}"); + } + + // ----------------------------------------------------------------------- +- // create_comment ++ // LinearTracker::create_comment + // ----------------------------------------------------------------------- + + #[tokio::test] +@@ -769,10 +752,24 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- create_comment(&client, &config, "issue-1", "Hello world") +- .await +- .unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issue = Issue { ++ id: "issue-1".to_string(), ++ project_item_id: None, ++ identifier: "T-1".to_string(), ++ title: "Test".to_string(), ++ description: None, ++ priority: None, ++ state: "Todo".to_string(), ++ branch_name: None, ++ url: "https://linear.app/t".to_string(), ++ assignee_id: None, ++ labels: vec![], ++ blocked_by: vec![], ++ created_at: None, ++ updated_at: None, ++ }; ++ tracker.create_comment(&issue, "Hello world").await.unwrap(); + } + + #[tokio::test] +@@ -787,15 +784,29 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let err = create_comment(&client, &config, "issue-1", "Hello") +- .await +- .unwrap_err(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issue = Issue { ++ id: "issue-1".to_string(), ++ project_item_id: None, ++ identifier: "T-1".to_string(), ++ title: "Test".to_string(), ++ description: None, ++ priority: None, ++ state: "Todo".to_string(), ++ branch_name: None, ++ url: "https://linear.app/t".to_string(), ++ assignee_id: None, ++ labels: vec![], ++ blocked_by: vec![], ++ created_at: None, ++ updated_at: None, ++ }; ++ let err = tracker.create_comment(&issue, "Hello").await.unwrap_err(); + assert!(err.contains("success: false"), "got: {err}"); + } + + // ----------------------------------------------------------------------- +- // update_issue_state ++ // LinearTracker::update_issue_state + // ----------------------------------------------------------------------- + + #[tokio::test] +@@ -821,10 +832,24 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- update_issue_state(&client, &config, "issue-1", "Done") +- .await +- .unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issue = Issue { ++ id: "issue-1".to_string(), ++ project_item_id: None, ++ identifier: "T-1".to_string(), ++ title: "Test".to_string(), ++ description: None, ++ priority: None, ++ state: "Todo".to_string(), ++ branch_name: None, ++ url: "https://linear.app/t".to_string(), ++ assignee_id: None, ++ labels: vec![], ++ blocked_by: vec![], ++ created_at: None, ++ updated_at: None, ++ }; ++ tracker.update_issue_state(&issue, "Done").await.unwrap(); + + resolve_mock.assert_async().await; + update_mock.assert_async().await; +@@ -842,8 +867,25 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let err = update_issue_state(&client, &config, "issue-1", "Nonexistent") ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issue = Issue { ++ id: "issue-1".to_string(), ++ project_item_id: None, ++ identifier: "T-1".to_string(), ++ title: "Test".to_string(), ++ description: None, ++ priority: None, ++ state: "Todo".to_string(), ++ branch_name: None, ++ url: "https://linear.app/t".to_string(), ++ assignee_id: None, ++ labels: vec![], ++ blocked_by: vec![], ++ created_at: None, ++ updated_at: None, ++ }; ++ let err = tracker ++ .update_issue_state(&issue, "Nonexistent") + .await + .unwrap_err(); + assert!(err.contains("Nonexistent"), "got: {err}"); +@@ -851,7 +893,7 @@ mod tests { + } + + // ----------------------------------------------------------------------- +- // fetch_candidate_issues ++ // LinearTracker::fetch_candidate_issues + // ----------------------------------------------------------------------- + + #[tokio::test] +@@ -876,13 +918,15 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let issues = fetch_candidate_issues(&client, &config, "my-project", &["In Progress"]) ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "my-project".to_string()); ++ let issues = tracker ++ .fetch_candidate_issues(&["In Progress"]) + .await + .unwrap(); + + assert_eq!(issues.len(), 1); + assert_eq!(issues[0].identifier, "ABC-123"); ++ assert!(issues[0].project_item_id.is_none()); + } + + #[tokio::test] +@@ -937,10 +981,8 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let issues = fetch_candidate_issues(&client, &config, "proj", &["Todo"]) +- .await +- .unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); + + assert_eq!(issues.len(), 2); + assert_eq!(issues[0].identifier, "T-1"); +@@ -968,16 +1010,14 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let issues = fetch_candidate_issues(&client, &config, "proj", &["Todo"]) +- .await +- .unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issues = tracker.fetch_candidate_issues(&["Todo"]).await.unwrap(); + + assert!(issues.is_empty()); + } + + // ----------------------------------------------------------------------- +- // fetch_issues_by_ids ++ // LinearTracker::fetch_issues_by_ids + // ----------------------------------------------------------------------- + + #[tokio::test] +@@ -1012,8 +1052,9 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let issues = fetch_issues_by_ids(&client, &config, &["id-a", "id-b"]) ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issues = tracker ++ .fetch_issues_by_ids(&["id-a", "id-b"]) + .await + .unwrap(); + +@@ -1071,10 +1112,8 @@ mod tests { + .create_async() + .await; + +- let client = reqwest::Client::new(); +- let issues = fetch_issues_by_ids(&client, &config, &id_refs) +- .await +- .unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issues = tracker.fetch_issues_by_ids(&id_refs).await.unwrap(); + + assert_eq!(issues.len(), 51); + assert_eq!(issues[0].id, "id-0"); +@@ -1083,9 +1122,9 @@ mod tests { + + #[tokio::test] + async fn fetch_issues_by_ids_empty() { +- let client = reqwest::Client::new(); + let config = LinearConfig::new("unused".to_string()); +- let issues = fetch_issues_by_ids(&client, &config, &[]).await.unwrap(); ++ let tracker = LinearTracker::new(config, reqwest::Client::new(), "proj".to_string()); ++ let issues = tracker.fetch_issues_by_ids(&[]).await.unwrap(); + assert!(issues.is_empty()); + } + } diff --git a/nodes/simplify_opus/prompt.md b/nodes/simplify_opus/prompt.md new file mode 100644 index 000000000..cdc85bb17 --- /dev/null +++ b/nodes/simplify_opus/prompt.md @@ -0,0 +1,179 @@ +Goal: # Plan: Merge fabro-linear and GitHub tracker into fabro-tracker + +## Context + +The tracker ecosystem currently has three crates: +- **fabro-tracker** — trait-only (57 lines): `Tracker` trait, `Issue`, `BlockerRef` +- **fabro-linear** — standalone Linear functions that duplicate the `Issue`/`BlockerRef` types and don't implement the `Tracker` trait. Entirely unused. +- **fabro-github** — mixed crate: GitHub App auth/PRs/branches (~70%) + `GitHubTracker` implementing `Tracker` (~30%). The `GitHubTracker` is also unused by consumers. + +Goal: consolidate both tracker implementations into `fabro-tracker`, keeping non-tracker GitHub code in `fabro-github`, and deleting `fabro-linear`. + +## Dependency Direction Change + +**Current:** `fabro-github → fabro-tracker` (for trait re-export) +**After:** `fabro-tracker → fabro-github` (for auth primitives: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects`) + +`fabro-github` no longer depends on `fabro-tracker`. No circular dependency. + +## Steps + +### 1. Update `lib/crates/fabro-tracker/Cargo.toml` + +Add dependencies needed by both implementations: +```toml +[dependencies] +fabro-github = { path = "../fabro-github" } +async-trait.workspace = true +serde.workspace = true +serde_json.workspace = true +reqwest.workspace = true +tracing.workspace = true +tokio = { workspace = true } + +[dev-dependencies] +mockito = "1" +tokio = { workspace = true, features = ["test-util", "macros"] } +``` + +### 2. Update `lib/crates/fabro-github/Cargo.toml` + +Remove: +- `fabro-tracker = { path = "../fabro-tracker" }` +- `async-trait.workspace = true` + +### 3. Remove tracker code from `lib/crates/fabro-github/src/lib.rs` + +Remove these items (keep everything else): +- `use async_trait::async_trait;` (line 1) +- `use tokio::sync::OnceCell;` (line 3) +- `pub use fabro_tracker::{BlockerRef, Issue, Tracker};` (line 5) +- `execute_github_graphql()` fn (~line 796) +- `GitHubTracker` struct, `impl GitHubTracker`, `impl Tracker for GitHubTracker` (~line 866-1315) +- `normalize_github_item()` fn (~line 981) +- `fetch_project_items_page()` fn (~line 1035) +- All tracker-related tests (~line 2172-2841): `execute_github_graphql` tests, tracker helpers (`mock_github_tracker`, `make_test_issue`, etc.), and all `GitHubTracker` method tests + +**Keep** `create_installation_access_token_for_projects()` — it stays in fabro-github as a public function alongside the other `create_installation_access_token_*` variants. + +### 4. Create `lib/crates/fabro-tracker/src/linear.rs` + +Adapt `fabro-linear/src/lib.rs` code: +- **Remove** the duplicate `Issue` and `BlockerRef` struct definitions — use `crate::Issue` and `crate::BlockerRef` +- **Adapt** `normalize_issue()` to return `crate::Issue` with `project_item_id: None` +- **Create** `LinearTracker` struct wrapping `LinearConfig`, `reqwest::Client`, and `project_slug: String` +- **Implement** `Tracker for LinearTracker` by delegating to the existing functions +- **Keep** private: `execute_graphql`, `normalize_issue`, `extract_issues`, `ISSUE_FIELDS`, `BLOCKS_RELATION_TYPE` +- **Keep** public: `LinearConfig`, `LinearTracker`, `LINEAR_API_ENDPOINT` +- **Move** all tests, updating assertions for the added `project_item_id` field + +### 5. Create `lib/crates/fabro-tracker/src/github.rs` + +Move tracker code from fabro-github: +- Import from fabro-github: `GitHubAppCredentials`, `sign_app_jwt`, `create_installation_access_token_for_projects` +- Contains: `GitHubTracker` struct + impls, `execute_github_graphql`, `normalize_github_item`, `fetch_project_items_page` +- Uses `crate::Issue` and `crate::BlockerRef` (same types, just different import path) +- Move all GitHubTracker tests (duplicate `test_rsa_key()` helper since test code isn't importable across crates) + +### 6. Update `lib/crates/fabro-tracker/src/lib.rs` + +Add module declarations and re-exports: +```rust +pub mod github; +pub mod linear; + +pub use github::GitHubTracker; +pub use linear::{LinearConfig, LinearTracker, LINEAR_API_ENDPOINT}; +``` + +### 7. Delete `lib/crates/fabro-linear/` + +Remove entire directory. Workspace glob `members = ["lib/crates/*"]` handles the rest. + +## Verification + +```bash +cargo build --workspace +cargo test --workspace +cargo clippy --workspace -- -D warnings +cargo fmt --check --all +``` + +Key things to verify: +- No circular dependency (fabro-tracker → fabro-github, fabro-github has no fabro-tracker dep) +- Linear `normalize_issue` sets `project_item_id: None` +- All moved tests pass in their new home +- `test_rsa_key()` helper is duplicated in fabro-tracker's github test module + + +## Completed stages +- **toolchain**: success + - Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1` + - Stdout: + ``` + cargo 1.94.0 (85eff7c80 2026-01-15) + ``` + - Stderr: (empty) +- **preflight_compile**: success + - Script: `cargo check -q --workspace 2>&1` + - Stdout: (empty) + - Stderr: (empty) +- **preflight_lint**: success + - Script: `cargo clippy -q --workspace -- -D warnings 2>&1` + - Stdout: (empty) + - Stderr: (empty) +- **implement**: success + - Model: claude-opus-4-6, 113.7k tokens in / 38.3k out + - Files: /home/daytona/workspace/lib/crates/fabro-github/Cargo.toml, /home/daytona/workspace/lib/crates/fabro-github/src/lib.rs, /home/daytona/workspace/lib/crates/fabro-tracker/Cargo.toml, /home/daytona/workspace/lib/crates/fabro-tracker/src/github.rs, /home/daytona/workspace/lib/crates/fabro-tracker/src/lib.rs, /home/daytona/workspace/lib/crates/fabro-tracker/src/linear.rs + + +# Simplify: Code Review and Cleanup + +Review all changed files for reuse, quality, and efficiency. Fix any issues found. + +## Phase 1: Identify Changes + +Run git diff (or git diff HEAD if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation. + +## Phase 2: Launch Three Review Agents in Parallel + +Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context. + +### Agent 1: Code Reuse Review + +For each change: + +1. Search for existing utilities and helpers that could replace newly written code. Use Grep to find similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones. +2. Flag any new function that duplicates existing functionality. Suggest the existing function to use instead. +3. Flag any inline logic that could use an existing utility — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates. + +Note: This is a greenfield app, so focus on maximizing simplicity and don't worry about changing things to achieve it. + +### Agent 2: Code Quality Review + +Review the same changes for hacky patterns: + +1. Redundant state: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls +2. Parameter sprawl: adding new parameters to a function instead of generalizing or restructuring existing ones +3. Copy-paste with slight variation: near-duplicate code blocks that should be unified with a shared abstraction +4. Leaky abstractions: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries +5. Stringly-typed code: using raw strings where constants, enums (string unions), or branded types already exist in the codebase + +Note: This is a greenfield app, so be aggressive in optimizing quality. + +### Agent 3: Efficiency Review + +Review the same changes for efficiency: + +1. Unnecessary work: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns +2. Missed concurrency: independent operations run sequentially when they could run in parallel +3. Hot-path bloat: new blocking work added to startup or per-request/per-render hot paths +4. Unnecessary existence checks: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error +5. Memory: unbounded data structures, missing cleanup, event listener leaks +6. Overly broad operations: reading entire files when only a portion is needed, loading all items when filtering for one + +## Phase 3: Fix Issues + +Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it. + +When done, briefly summarize what was fixed (or confirm the code was already clean). \ No newline at end of file diff --git a/nodes/simplify_opus/provider_used.json b/nodes/simplify_opus/provider_used.json new file mode 100644 index 000000000..c1905ff10 --- /dev/null +++ b/nodes/simplify_opus/provider_used.json @@ -0,0 +1,5 @@ +{ + "mode": "agent", + "provider": "anthropic", + "model": "claude-opus-4-6" +} \ No newline at end of file diff --git a/nodes/simplify_opus/response.md b/nodes/simplify_opus/response.md new file mode 100644 index 000000000..d86ef729f --- /dev/null +++ b/nodes/simplify_opus/response.md @@ -0,0 +1,18 @@ +All clean. Here's a summary of what was fixed: + +## Summary + +**4 issues fixed, 2 skipped as expected/acceptable:** + +### Fixed +1. **Unified duplicate GraphQL execution functions** (HIGH) — Extracted `execute_graphql_request()` into `lib.rs` as a `pub(crate)` shared helper. Both `github.rs::execute_github_graphql()` and `linear.rs::execute_graphql()` now delegate to it, eliminating ~80 lines of duplicated request/error-handling logic while preserving provider-specific auth headers and error labels. + +2. **Added `make_test_issue()` helper to linear.rs tests** (MEDIUM) — Replaced 4 identical 14-field `Issue` struct constructions with a shared test helper, removing ~55 lines of boilerplate and matching the pattern already used in `github.rs` tests. + +3. **Removed unused `serde` dependency** (MEDIUM) — `fabro-tracker/Cargo.toml` listed `serde.workspace = true` but no file in the crate imports or derives from `serde` directly (only `serde_json` is used). Removed the phantom dependency. + +4. **Fixed missing trailing newline in `fabro-github/Cargo.toml`** (LOW) — The file was missing a POSIX trailing newline, causing `\ No newline at end of file` in diffs. + +### Skipped (acceptable) +- **`test_rsa_key()` duplication** between `fabro-github` and `fabro-tracker` — Expected; Rust `#[cfg(test)]` code can't be shared across crate boundaries without a test-utils crate. +- **`fetch_issues_by_ids` ordering pattern** in both modules — Idiomatic; the provider-specific fetch logic differs enough that extraction would be forced. \ No newline at end of file diff --git a/nodes/simplify_opus/status.json b/nodes/simplify_opus/status.json new file mode 100644 index 000000000..738383812 --- /dev/null +++ b/nodes/simplify_opus/status.json @@ -0,0 +1,6 @@ +{ + "status": "success", + "notes": "Stage completed: simplify_opus", + "failure_reason": null, + "timestamp": "2026-03-20T00:27:02.170332+00:00" +} \ No newline at end of file