Skip to content

refactor: package code organization wave 12 - #2362

Merged
gsxdsm merged 7 commits into
mainfrom
feature/code-organization-wave12
Jul 22, 2026
Merged

refactor: package code organization wave 12#2362
gsxdsm merged 7 commits into
mainfrom
feature/code-organization-wave12

Conversation

@gsxdsm

@gsxdsm gsxdsm commented Jul 20, 2026

Copy link
Copy Markdown
Collaborator

Summary

Behavior-preserving package code organization (wave 12), continuing after wave 11 (#2333).

  • Dashboard client API peels from app/api/legacy.ts into focused modules with stable re-exports:
    • git.ts — remotes, PR management, terminal sessions, git management (withRepoPath preserved)
    • workspace-files.ts — file browser + workspace file ops
    • provider-status.ts — auth/CLI and runtime provider status
    • github-import.ts / gitlab-import.ts — issue/PR import clients
    • run-audit.ts — run-audit, timeline, org tree, task review
    • task-diff.ts — task diffs and commit associations
    • agent-import-generation.ts — agent import catalog + generation
  • Core types peels from types.ts:
    • types/run-audit.ts
    • types/planner-intervention.ts
  • Domain rename: task-store/remaining-ops-5.tstask-store/task-id-integrity.ts (call sites updated)
  • Line-count ratchet: legacy.ts ceiling ~5665 → ~3339; baseline refreshed

No intentional behavior changes; public import paths via app/api / @fusion/core remain stable.

Test plan

  • @fusion/core typecheck
  • Dashboard tsconfig.app typecheck (wave12-related errors cleared; pre-existing playwright/plugin env noise unchanged vs main)
  • ESLint on peeled API modules
  • pnpm check:line-count (baseline updated)
  • CI: Lint / Typecheck / Build / Gate

Summary by CodeRabbit

  • New Features
    • Added dashboard client support for Git remotes/PR workflows, GitHub/GitLab importing, terminals (HTTP/SSE) and PTY sessions, workspace file browsing/editing/search, and task diff viewing with file/ZIP download helpers.
    • Added new dashboard APIs for planning/onboarding streaming, mission interview flows, provider/auth status, dev server sessions, run-audit/timelines & task review, agent import/generation, and AI title summarization.
    • Added backup and settings export/import helpers, plus model discovery/usage reporting and task steering actions.
  • Refactor
    • Modularized dashboard API clients into focused modules while preserving the existing integration style.
  • Tests
    • Updated a backend-mode SQLite guidance regression test to exercise the intended implementations.
  • Chores
    • Refreshed internal line-count baselines.

…, task-id-integrity

Behavior-preserving package organization after wave 11:
- app/api: git, workspace-files, provider-status, github/gitlab-import,
  run-audit, task-diff, agent-import-generation (legacy re-exports kept)
- types/run-audit.ts + types/planner-intervention.ts peels from types.ts
- rename remaining-ops-5 → task-store/task-id-integrity.ts
- Ratchet legacy.ts line-count ceiling (~5665 → ~3339)
@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR modularizes core audit and intervention types, reroutes task-store helper wiring, and extracts dashboard API clients for providers, imports, Git operations, terminals, workspaces, planning, run audits, reviews, and task diffs while preserving legacy re-exports.

Changes

Core task-store and type organization

Layer / File(s) Summary
Task-store wiring and audit contracts
packages/core/src/{store.ts,archive-db.ts,types.ts}, packages/core/src/types/*, packages/core/src/task-store/*, packages/core/src/__tests__/*
Task-store references are rerouted to renamed modules, and run-audit and planner-intervention contracts are moved into dedicated modules while remaining available through the core types barrel.

Dashboard API modularization

Layer / File(s) Summary
Legacy barrel extraction
packages/dashboard/app/api/legacy.ts, scripts/line-count-baseline.json
The legacy API barrel re-exports focused clients and the line-count baselines are updated.
Provider, workspace, and task-support clients
packages/dashboard/app/api/{provider-status,workspace-files,task-steer,models-usage,ai-summarize,task-diff}.ts
Typed clients are added for provider/auth management, workspace files, task steering, model usage, title summarization, and task diffs.
Import and generation clients
packages/dashboard/app/api/{agent-import-generation,github-import,gitlab-import}.ts
Typed wrappers support agent generation, backups, settings transfer, GitHub imports, and GitLab imports.
Git and terminal client
packages/dashboard/app/api/git.ts
Typed endpoints cover Git remotes, pull requests, terminals, repository state, branches, stashes, diffs, staging, commits, and discard operations.
Workflow and streaming clients
packages/dashboard/app/api/{run-audit,planning,mission-interview,dev-server}.ts
Clients support run audits, timelines, task review workflows, planning and interview SSE sessions, and legacy/session dev-server operations.

Sequence Diagram(s)

sequenceDiagram
  participant Dashboard
  participant ApiClient
  participant Backend
  participant EventSource
  Dashboard->>ApiClient: Start planning or interview session
  ApiClient->>Backend: POST session request
  Backend-->>ApiClient: Return sessionId
  Dashboard->>EventSource: Connect to session stream
  EventSource-->>Dashboard: Deliver questions, summaries, and terminal events
Loading

Estimated code review effort: 5 (Critical) | ~90 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the refactor but is too vague to convey the main changes in the codebase. Make the title more specific, e.g. mention splitting dashboard APIs and extracting core types while preserving public import paths.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/code-organization-wave12

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR reorganizes dashboard API and core code without intentional behavior changes. The main changes are:

  • Moves dashboard API clients from legacy.ts into focused modules with compatibility re-exports.
  • Extracts run-audit and planner-intervention types into dedicated core modules.
  • Renames two internal task-store modules and updates their import paths.
  • Refreshes the line-count baseline and related test imports.

Confidence Score: 5/5

This looks safe to merge.

  • The extracted core types preserve their existing public exports.
  • Known imports use the renamed task-store module paths.
  • No qualifying blocking issue remains in the updated code.

Important Files Changed

Filename Overview
packages/dashboard/app/api/legacy.ts Replaces extracted client implementations with compatibility re-exports from focused API modules.
packages/core/src/types.ts Re-exports run-audit and planner-intervention definitions from their new modules.
packages/core/src/types/run-audit.ts Contains the extracted run-audit type definitions.
packages/core/src/types/planner-intervention.ts Contains the extracted planner-intervention types and mutation constant.
packages/core/src/store.ts Updates imports for the renamed internal task-store modules.
packages/core/src/task-store/task-id-integrity.ts Renames the internal task-ID integrity and persistence helper module.
packages/core/src/task-store/task-artifacts-ops.ts Renames the internal artifact, document, archive, and merge-queue helper module.

Reviews (7): Last reviewed commit: "refactor: package code organization wave..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/dashboard/app/api/provider-status.ts`:
- Around line 332-404: Update fetchPaperclipStatus, fetchPaperclipCompanies, and
fetchPaperclipAgents to stop putting apiKey in URLSearchParams or request paths.
Pass apiKey through the API client’s supported request-body or header mechanism
instead, while retaining apiUrl and companyId as needed query parameters so
failed requests cannot expose the secret in originalUrl logs.

In `@packages/dashboard/app/api/run-audit.ts`:
- Around line 210-214: Update the error handler in the agent children request to
detect HTTP 404s via err.status === 404, while retaining a case-insensitive
message fallback for “not found”; continue returning an empty array for either
case and rethrow all other errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 4dbde5b7-ffc9-44cb-acc8-705693e79edb

📥 Commits

Reviewing files that changed from the base of the PR and between f221d2b and d20dc7d.

📒 Files selected for processing (17)
  • packages/core/src/__tests__/agent-logs-backend-mode.test.ts
  • packages/core/src/archive-db.ts
  • packages/core/src/store.ts
  • packages/core/src/task-store/task-id-integrity.ts
  • packages/core/src/types.ts
  • packages/core/src/types/planner-intervention.ts
  • packages/core/src/types/run-audit.ts
  • packages/dashboard/app/api/agent-import-generation.ts
  • packages/dashboard/app/api/git.ts
  • packages/dashboard/app/api/github-import.ts
  • packages/dashboard/app/api/gitlab-import.ts
  • packages/dashboard/app/api/legacy.ts
  • packages/dashboard/app/api/provider-status.ts
  • packages/dashboard/app/api/run-audit.ts
  • packages/dashboard/app/api/task-diff.ts
  • packages/dashboard/app/api/workspace-files.ts
  • scripts/line-count-baseline.json

Comment thread packages/dashboard/app/api/provider-status.ts
Comment thread packages/dashboard/app/api/run-audit.ts Outdated
Prefer ApiRequestError.status === 404 over case-sensitive message matching
when agent children are missing, with a case-insensitive not-found fallback.
gsxdsm added 4 commits July 21, 2026 00:01
## Summary

Wave 13 of package code organization (stacks on #2362 / wave 12).

### Peels

| New module | Parent |
|---|---|
| `app/api/planning.ts` | planning mode + agent onboarding streams |
| `app/api/dev-server.ts` | dev-server detect/session/log/preview client
|
| `app/api/mission-interview.ts` | mission / milestone / slice interview
streams |
| `app/api/models-usage.ts` | models registry + usage |
| `app/api/task-steer.ts` | steer / spec revise / rebuild / refine |
| `app/api/ai-summarize.ts` | AI title summarization |
| `task-store/task-artifacts-ops.ts` | rename of `remaining-ops-7` |

Public paths stay stable via `legacy.ts` re-exports (`app/api.ts` →
`legacy`).

### LOC

- `legacy.ts` ~3342 → **~1408** (under the 2000-line hard cap; removed
from grandfather baseline)

### Shims

- `legacy.ts` → peels above (delete-when: dashboard imports domain
modules)
- `remaining-ops-7` → `task-artifacts-ops` (rename complete)

## Test plan

- [x] eslint on peeled API modules + legacy
- [x] dashboard app typecheck (wave13-related errors cleared)
- [x] core typecheck
- [x] `pnpm check:line-count` (baseline updated)
- [ ] CI merge gate

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/dashboard/app/api/dev-server.ts (2)

78-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate DevServerConfig declaration.

DevServerConfig is already declared identically at Lines 51-58. TypeScript merges the two, so it compiles, but this is a copy/paste artifact from the peel and should be removed to avoid drift.

♻️ Remove the duplicate
-export interface DevServerConfig {
-  selectedScript: string | null;
-  selectedSource: string | null;
-  selectedCommand: string | null;
-  previewUrlOverride: string | null;
-  detectedPreviewUrl: string | null;
-  selectedAt: string | null;
-}
-
 interface BackendDevServerCandidate {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/dashboard/app/api/dev-server.ts` around lines 78 - 85, Remove the
duplicate DevServerConfig interface declaration near the later declaration,
keeping the original DevServerConfig definition unchanged and preserving all
existing references to it.

873-873: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove orphaned JSDoc leftover from the peel.

This trailing /** Get the SSE stream URL for a planning session */ has no following declaration — the planning stream helper moved to planning.ts. Dead comment; drop it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/dashboard/app/api/dev-server.ts` at line 873, Remove the orphaned
trailing JSDoc comment for the planning session SSE stream URL from the
dev-server module, leaving the surrounding code unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/dashboard/app/api/ai-summarize.ts`:
- Around line 46-61: Update the response parsing in the AI summarization request
to use the shared api() helper from client.ts, or otherwise wrap JSON.parse in
try/catch and validate that the result is a non-null object with string-valued
error/title fields before accessing them. Preserve the existing status-specific
errors and ensure only a string title is returned to satisfy the Promise<string>
contract.

---

Nitpick comments:
In `@packages/dashboard/app/api/dev-server.ts`:
- Around line 78-85: Remove the duplicate DevServerConfig interface declaration
near the later declaration, keeping the original DevServerConfig definition
unchanged and preserving all existing references to it.
- Line 873: Remove the orphaned trailing JSDoc comment for the planning session
SSE stream URL from the dev-server module, leaving the surrounding code
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d0a7a2c8-548b-4d56-8d79-cfcf3c37defa

📥 Commits

Reviewing files that changed from the base of the PR and between c12ebf3 and 0681d47.

📒 Files selected for processing (11)
  • packages/core/src/__tests__/agent-logs-backend-mode.test.ts
  • packages/core/src/store.ts
  • packages/core/src/task-store/task-artifacts-ops.ts
  • packages/dashboard/app/api/ai-summarize.ts
  • packages/dashboard/app/api/dev-server.ts
  • packages/dashboard/app/api/legacy.ts
  • packages/dashboard/app/api/mission-interview.ts
  • packages/dashboard/app/api/models-usage.ts
  • packages/dashboard/app/api/planning.ts
  • packages/dashboard/app/api/task-steer.ts
  • scripts/line-count-baseline.json
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/core/src/tests/agent-logs-backend-mode.test.ts
  • packages/core/src/store.ts
  • scripts/line-count-baseline.json
  • packages/dashboard/app/api/legacy.ts

Comment on lines +46 to +61
const data = JSON.parse(bodyText) as { title?: string; error?: string };

if (!res.ok) {
const errorMessage = data.error || "Request failed";
if (res.status === 400) {
throw new Error(`Invalid request: ${errorMessage}`);
} else if (res.status === 429) {
throw new Error(`Rate limit exceeded: ${errorMessage}`);
} else if (res.status === 503) {
throw new Error(`AI service temporarily unavailable: ${errorMessage}`);
} else {
throw new Error(errorMessage);
}
}

if (!data.title) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Validate parsed API responses before accessing fields.

The cast on Line [46] provides no runtime validation: malformed JSON throws a raw SyntaxError, while valid null or non-object JSON can crash at Lines [49] or [61]. A non-string title can also violate the declared Promise<string> contract. Parse inside try/catch and validate the response shape before reading error or returning title.

Proposed fix
-  const data = JSON.parse(bodyText) as { title?: string; error?: string };
+  let parsed: unknown;
+  try {
+    parsed = JSON.parse(bodyText);
+  } catch {
+    throw new Error("API returned invalid JSON response");
+  }
+  if (typeof parsed !== "object" || parsed === null) {
+    throw new Error("API returned invalid JSON response");
+  }
+  const data = parsed as { title?: unknown; error?: unknown };
...
-    const errorMessage = data.error || "Request failed";
+    const errorMessage = typeof data.error === "string" ? data.error : "Request failed";
...
-  if (!data.title) {
+  const title = data.title;
+  if (typeof title !== "string" || title.length === 0) {
     throw new Error("API returned empty title");
   }
 
-  return data.title;
+  return title;

The shared api() helper in packages/dashboard/app/api/client.ts already handles invalid JSON explicitly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const data = JSON.parse(bodyText) as { title?: string; error?: string };
if (!res.ok) {
const errorMessage = data.error || "Request failed";
if (res.status === 400) {
throw new Error(`Invalid request: ${errorMessage}`);
} else if (res.status === 429) {
throw new Error(`Rate limit exceeded: ${errorMessage}`);
} else if (res.status === 503) {
throw new Error(`AI service temporarily unavailable: ${errorMessage}`);
} else {
throw new Error(errorMessage);
}
}
if (!data.title) {
let parsed: unknown;
try {
parsed = JSON.parse(bodyText);
} catch {
throw new Error("API returned invalid JSON response");
}
if (typeof parsed !== "object" || parsed === null) {
throw new Error("API returned invalid JSON response");
}
const data = parsed as { title?: unknown; error?: unknown };
if (!res.ok) {
const errorMessage = typeof data.error === "string" ? data.error : "Request failed";
if (res.status === 400) {
throw new Error(`Invalid request: ${errorMessage}`);
} else if (res.status === 429) {
throw new Error(`Rate limit exceeded: ${errorMessage}`);
} else if (res.status === 503) {
throw new Error(`AI service temporarily unavailable: ${errorMessage}`);
} else {
throw new Error(errorMessage);
}
}
const title = data.title;
if (typeof title !== "string" || title.length === 0) {
throw new Error("API returned empty title");
}
return title;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/dashboard/app/api/ai-summarize.ts` around lines 46 - 61, Update the
response parsing in the AI summarization request to use the shared api() helper
from client.ts, or otherwise wrap JSON.parse in try/catch and validate that the
result is a non-null object with string-valued error/title fields before
accessing them. Preserve the existing status-specific errors and ensure only a
string title is returned to satisfy the Promise<string> contract.

@gsxdsm
gsxdsm merged commit 3a7684b into main Jul 22, 2026
7 checks passed
@gsxdsm
gsxdsm deleted the feature/code-organization-wave12 branch July 22, 2026 06:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant