Files
kandev/apps/web/lib/state/slices/github/github-slice.test.ts
T
João Salavisa fd79d6170f feat(tasks): multi-branch tasks — N (repo, branch) pairs per task (#1226)
* feat(tasks): multi-branch tasks — N (repo, branch) pairs per task

Extends multi-repo into multi-branch so a single task can hold multiple
worktrees on the same repo (one per branch). Sibling worktrees layout at
<task>/<repo>/ + <task>/<repo>-<slug>/, dedicated PRWatch per branch,
live agentctl tracker rescan + frontend store updates so the UI splits
PRs / files / commits per branch without a session restart. MCP
add_branch_to_task_kandev tool is shielded to the worktree executor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): unify multi-branch repo label as <repo> · <branch> across panels

PR Changes and Commits panels rendered repo labels differently for multi-branch
tasks — Commits showed "kandev · feature/x" while PR Changes leaked the raw
"kandev-feature-x" agentctl tracker tag. Reformat tracker-tagged repo names via
formatRepoLabel using the longest known-repo prefix so kandev-cli-* doesn't
collapse to kandev · cli-*.

* fix(tasks): address multi-branch PR review — data races, slug collisions, MCP error codes

Backend
- agentctl process.Manager: add repoTrackersMu RWMutex guarding repoTrackers
  + workspaceTracker. Reads snapshot under RLock; RescanRepositories builds
  trackers first, takes Lock for swap/append. Validates newWorkDir via
  os.Stat before publishing cfg.WorkDir.
- worktree.Manager: reject invalid explicit BranchSlug up-front; cache key
  uses sanitized wt.BranchSlug so read/write paths are symmetric.
- worktree.store: narrow isDuplicateColumnError to "duplicate column name".
- task service AddBranchToTask: slug-collision guard rejects feat/a vs feat-a.
- orchestrator resolvePushRepo: two-pass exact-name match before subdir
  prefix fallback so "backend" doesn't swallow pushes for "backend-admin".
- executor buildRepoSpecs: duplicate repos always get a non-empty BranchSlug
  (falls back to branch-N when both branch fields sanitize to empty).
- MCP handler: classifyAddBranchError maps service errors to NOT_FOUND /
  CONFLICT / VALIDATION_ERROR; add ErrorCodeConflict constant.
- MCP server: extract registerAddBranchToTaskTool, register in task mode
  only (external mode contract: config tools + create_task_kandev).
- workspace_rescan handler: reject malformed JSON with 400 instead of
  silently rescanning the current root.
- branch_materializer: split MaterializeBranch into prepare + finalize
  helpers to satisfy the 80-line cap.

Frontend
- existingPrUrl returns undefined when a task has >1 PR so per-repo View PR
  buttons take over (no silent linking to a sibling).
- formatRepoLabel checks exact known-repo match before prefix splitting so
  "kandev-cli" isn't mislabeled as "kandev · cli".
- Repo chip key now includes base_branch so siblings differing only on
  base render as distinct chips.

Docs
- multi-branch spec uniqueness wording aligned with the canonical 4-column
  key (task_id, repository_id, base_branch, checkout_branch).
- worktree.CreateRequest.BranchSlug doc describes the sibling layout
  (<repo>-<slug>) instead of the obsolete nested form.

* fix(tasks): scope slug-collision check to repo only + use errors.Is for ErrTaskNotFound

- service_branches: drop base_branch from the slug-collision check. Worktree
  path is (repo, slug); two rows on the same repo cut from different bases
  still collide on disk.
- service_branches: prepareBranchAdd wraps taskrepo.ErrTaskNotFound via
  fmt.Errorf with %w so classifiers don't have to substring-match the
  formatted task UUID.
- mcp handlers: classifyAddBranchError uses errors.Is(err, ErrTaskNotFound).

* fix(agentctl): sanitize rescan work_dir before os.Stat to clear CodeQL path-injection

CodeQL flagged the rescan endpoint as a path-injection sink (the
HTTP-supplied work_dir flowed straight into os.Stat and downstream
scanRepositorySubdirs). Add validateRescanPath which:
- requires the input to be a clean absolute path with no ".." segments
- rejects anything that isn't equal to or an ancestor of the current
  cfg.WorkDir — the only legitimate use case is the branch materializer
  promoting <task>/<repo>/ to <task>/

Defense in depth: agentctl binds to localhost, but any colocated process
could otherwise direct it at /etc or the user's home by POSTing
/api/v1/workspace/rescan.

* fix(agentctl): tighten validateRescanPath, close TOCTOU on existingTrackers, add tests

- Drop the strings.Contains(clean, "..") guard. filepath.Clean already
  resolves traversal; the substring check rejects legitimate names like
  /home/u/..hidden without adding defense (the ancestor check via
  filepath.Rel is the real boundary).
- Drop the rel == "." branch in the ancestor check — early return for
  clean == currentClean already covers identity.
- Read existingTrackers inside the write-lock section (not under RLock
  then re-Lock) so two concurrent rescans can't both see 0 trackers and
  double-bootstrap the multi-repo set.
- Add table-driven TestValidateRescanPath covering rejection paths
  (relative, descendant, sibling, traversal-cleaned, empty input),
  legitimate ancestor promotion, exact match, no-anchor first-launch,
  and a /home/u/..hidden dotted-segment case.

* fix(agentctl): break taint flow into os.Stat — derive rescan path from cfg, not HTTP body

CodeQL's go/path-injection trace still flagged manager_rescan.go after the
prior sanitizer because the user-supplied newWorkDir flowed (after
validation) into os.Stat and then into cfg.WorkDir → tracker paths →
workspace_monitor os.Stat sinks.

Replace validateRescanPath with resolveRescanPath: it returns a path
DERIVED from currentWorkDir (no-op = currentClean, promotion =
filepath.Dir(currentClean)) and uses newPath only for comparison, never
as a source for the returned string. os.Stat now receives a path whose
provenance is trusted manager config.

Functionally the legitimate caller (branch materializer promoting
<task>/<repo>/ to <task>/) is unchanged.

* test(agentctl): make TestResolveRescanPath windows-portable

The Linux Backend Tests job passed but the Backend (windows) job rejected
every "absolute" case because filepath.IsAbs("/task/repo") is false on
Windows (no volume letter).

Build inputs via filepath.Join against absRoot() (filepath.Abs of "/" /
"\\") so the same table covers POSIX (`/...`) and Windows (`C:\...`)
without per-OS branches. Keep the traversal-after-Clean case POSIX-only
since filepath.Clean is the shared primitive and that input form needs a
volume to be considered absolute on Windows anyway.

* fix(agentctl): serialize RescanRepositories + re-check trackers under write lock

Two concurrent RescanRepositories calls could both observe an empty
tracker set (between the snapshot read and the bootstrap branch) and both
enter transitionToMultiRepoMode, leaking a duplicate bare-root tracker
and duplicate per-repo trackers. Same race in appendNewRepoTrackers would
double-append the same new child across both callers.

Fix:
- Add rescanMu sync.Mutex on Manager. Acquired for the full body of
  RescanRepositories so the snapshot → branch → mutate sequence is
  serialized. repoTrackersMu still guards individual field reads from
  unrelated goroutines (subscribe/unsubscribe/poll-mode).
- appendNewRepoTrackers re-checks membership inside the write-lock
  before appending and drops already-present trackers (Stop + detach
  outside the lock). Defense in depth.
- Test: add `dotted segment is legal as promotion` case so the
  ..hidden-segment promotion path stays exercised.

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 19:36:20 +01:00

233 lines
7.2 KiB
TypeScript

import { describe, it, expect } from "vitest";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createGitHubSlice } from "./github-slice";
import type { GitHubSlice } from "./types";
import type { GitHubStatus, TaskPR } from "@/lib/types/github";
function makePR(overrides: Partial<TaskPR> = {}): TaskPR {
return {
id: "id",
task_id: "task-1",
owner: "o",
repo: "r",
pr_number: 1,
pr_url: "",
pr_title: "Test PR",
head_branch: "feat",
base_branch: "main",
author_login: "alice",
state: "open",
review_state: "",
checks_state: "",
mergeable_state: "",
review_count: 0,
pending_review_count: 0,
comment_count: 0,
unresolved_review_threads: 0,
checks_total: 0,
checks_passing: 0,
additions: 0,
deletions: 0,
created_at: "",
merged_at: null,
closed_at: null,
last_synced_at: null,
updated_at: "",
...overrides,
};
}
function makeStore() {
return create<GitHubSlice>()(immer((...a) => createGitHubSlice(...a)));
}
const FUTURE_RESET = "2030-01-01T00:00:00Z";
const NOW = "2026-05-04T12:00:00Z";
const baseStatus: GitHubStatus = {
authenticated: true,
username: "octocat",
auth_method: "pat",
token_configured: true,
required_scopes: ["repo"],
};
describe("applyGitHubRateLimitUpdate", () => {
it("merges incoming snapshots into the existing status", () => {
const store = makeStore();
store.getState().setGitHubStatus({ ...baseStatus });
store.getState().applyGitHubRateLimitUpdate({
trigger: "graphql",
snapshots: [
{
resource: "graphql",
remaining: 0,
limit: 5000,
reset_at: FUTURE_RESET,
updated_at: NOW,
},
{
resource: "core",
remaining: 4500,
limit: 5000,
reset_at: FUTURE_RESET,
updated_at: NOW,
},
],
});
const status = store.getState().githubStatus.status;
expect(status?.rate_limit?.graphql?.remaining).toBe(0);
expect(status?.rate_limit?.graphql?.limit).toBe(5000);
expect(status?.rate_limit?.core?.remaining).toBe(4500);
});
it("overwrites only the resources present in the update", () => {
const store = makeStore();
store.getState().setGitHubStatus({
...baseStatus,
rate_limit: {
core: {
resource: "core",
remaining: 4500,
limit: 5000,
reset_at: FUTURE_RESET,
updated_at: NOW,
},
},
});
store.getState().applyGitHubRateLimitUpdate({
trigger: "graphql",
snapshots: [
{
resource: "graphql",
remaining: 100,
limit: 5000,
reset_at: FUTURE_RESET,
updated_at: NOW,
},
],
});
const rl = store.getState().githubStatus.status?.rate_limit;
expect(rl?.core?.remaining).toBe(4500); // untouched
expect(rl?.graphql?.remaining).toBe(100);
});
it("is a no-op when status has not been hydrated yet", () => {
const store = makeStore();
expect(store.getState().githubStatus.status).toBeNull();
store.getState().applyGitHubRateLimitUpdate({
trigger: "core",
snapshots: [
{
resource: "core",
remaining: 0,
limit: 5000,
reset_at: FUTURE_RESET,
updated_at: NOW,
},
],
});
expect(store.getState().githubStatus.status).toBeNull();
});
});
describe("setTaskPR", () => {
it("appends a PR when the task has no rows yet", () => {
const store = makeStore();
const pr = makePR({ repository_id: "repo-a" });
store.getState().setTaskPR("task-1", pr);
expect(store.getState().taskPRs.byTaskId["task-1"]).toEqual([pr]);
});
it("upserts by repository_id so multi-repo PRs coexist", () => {
const store = makeStore();
const prA = makePR({ id: "a", repository_id: "repo-a", pr_number: 1 });
const prB = makePR({ id: "b", repository_id: "repo-b", pr_number: 2 });
const prAUpdated = makePR({ id: "a", repository_id: "repo-a", pr_number: 1, additions: 10 });
store.getState().setTaskPR("task-1", prA);
store.getState().setTaskPR("task-1", prB);
store.getState().setTaskPR("task-1", prAUpdated);
const list = store.getState().taskPRs.byTaskId["task-1"];
expect(list).toHaveLength(2);
expect(list.find((p) => p.repository_id === "repo-a")?.additions).toBe(10);
expect(list.find((p) => p.repository_id === "repo-b")?.id).toBe("b");
});
it("keeps multi-branch PRs as siblings (same repo, different pr_number)", () => {
const store = makeStore();
const pr1 = makePR({ id: "p1", repository_id: "repo-a", pr_number: 1221 });
const pr2 = makePR({ id: "p2", repository_id: "repo-a", pr_number: 1222 });
const pr1Updated = makePR({
id: "p1",
repository_id: "repo-a",
pr_number: 1221,
additions: 99,
});
store.getState().setTaskPR("task-1", pr1);
store.getState().setTaskPR("task-1", pr2);
store.getState().setTaskPR("task-1", pr1Updated);
const list = store.getState().taskPRs.byTaskId["task-1"];
expect(list).toHaveLength(2);
expect(list.find((p) => p.pr_number === 1221)?.additions).toBe(99);
expect(list.find((p) => p.pr_number === 1222)?.id).toBe("p2");
});
it("heals a corrupted non-array entry instead of throwing", () => {
// Simulates a stray payload landing in byTaskId[taskId] as something other
// than an array (e.g. a partial hydration). The next setTaskPR call must
// recover rather than propagate the bad shape, otherwise downstream
// renderers crash with `prs is not iterable`.
const store = makeStore();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
store.getState().setTaskPRs({ "task-1": {} as any });
const pr = makePR({ repository_id: "repo-a" });
expect(() => store.getState().setTaskPR("task-1", pr)).not.toThrow();
expect(Array.isArray(store.getState().taskPRs.byTaskId["task-1"])).toBe(true);
expect(store.getState().taskPRs.byTaskId["task-1"]).toEqual([pr]);
});
});
describe("setPendingPrUrlForTask", () => {
it("stores a pending PR URL until TaskPR sync clears it", () => {
const store = makeStore();
store
.getState()
.setPendingPrUrlForTask("task-1", "", "https://dev.azure.com/o/p/_git/r/pullrequest/1");
expect(store.getState().pendingPrUrlByTaskId.byTaskId["task-1"]?.[""]).toBe(
"https://dev.azure.com/o/p/_git/r/pullrequest/1",
);
store.getState().setTaskPR("task-1", makePR());
expect(store.getState().pendingPrUrlByTaskId.byTaskId["task-1"]).toBeUndefined();
});
it("clears only the synced repo pending URL in multi-repo tasks", () => {
const store = makeStore();
const urlA = "https://dev.azure.com/o/p/_git/a/pullrequest/1";
const urlB = "https://dev.azure.com/o/p/_git/b/pullrequest/2";
store.getState().setPendingPrUrlForTask("task-1", "repo-a", urlA);
store.getState().setPendingPrUrlForTask("task-1", "repo-b", urlB);
store.getState().setTaskPR("task-1", makePR({ repository_id: "repo-a", pr_url: urlA }));
expect(store.getState().pendingPrUrlByTaskId.byTaskId["task-1"]?.["repo-b"]).toBe(urlB);
expect(store.getState().pendingPrUrlByTaskId.byTaskId["task-1"]?.["repo-a"]).toBeUndefined();
});
});