8000 Worktree-aware roadmap view by rore · Pull Request #32 · rore/minimap · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ The roadmap mode is a repo-local view over a small file convention:

The UI never holds a second copy. Editing through the UI writes the markdown back; agents update the same files directly through the [`minimap-roadmap`](package/minimap/skills/minimap-roadmap/SKILL.md) skill.

When the repository has linked Git worktrees, the board's checkout picker can show **This checkout** or **Across worktrees**. Across is a read-only combined view: it identifies shared features from Git ancestry, keeps divergent checkout versions and their exact values visible, and marks unavailable sources as partial coverage. Choose a version in the item panel before editing; Save changes only that selected checkout and refuses a changed checkout or stale file. Across never synchronizes roadmap files or reorders multiple worktrees. The selected checkout version is retained in the URL on reload.

Default layout:

```text
Expand Down
18 changes: 18 additions & 0 deletions fixtures/pause-source-read.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import fs from "node:fs/promises";

const readFile = fs.readFile.bind(fs);
let paused = false;
fs.readFile = async function (file, ...args) {
if (!paused && String(file) === process.env.MINIMAP_TEST_PAUSE_FILE) {
try {
await fs.access(process.env.MINIMAP_TEST_ARM);
paused = true;
await fs.writeFile(process.env.MINIMAP_TEST_REACHED, "ready");
for (let attempt = 0; attempt < 600; attempt++) {
try { await fs.access(process.env.MINIMAP_TEST_RELEASE); break; }
catch { await new Promise((resolve) => setTimeout(resolve, 50)); }
}
} catch { /* The test has not armed the read yet. */ }
}
return readFile(file, ...args);
};
8 changes: 8 additions & 0 deletions package/minimap/CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ Example config:
}
```

## Linked worktree view

The board can show **This checkout** or a read-only **Across worktrees** projection. Discovery considers at most 16 registered linked Git worktrees in the opened repository's common Git directory. A separate clone is not a sibling. A source with an incompatible roadmap location, unreadable workspace, or uncertain identity is excluded or marked as partial coverage; it is never silently represented as empty. A checkout whose branch or HEAD changes during the read invalidates the combined snapshot and requires Refresh. Same item ID and path alone do not prove one logical feature: the shared ancestor must contain that identity, and a delete/re-add breaks it. Conflicting values stay source-specific. Different board-group memberships are disclosed on the cards; missing-file board references remain visible in coverage details even under metadata lenses. Line-ending-only differences do not produce a visual conflict, although raw file revisions remain exact for stale-write checks. Search, filters, In play, and metadata grouping evaluate each checkout version, not a fabricated merged item.

Across does not edit board order or synchronize files. Opening an item exposes its checkout versions; switching version changes only the selected document. Edit/Raw requires explicit one-checkout confirmation. The selected version is pinned in the URL, and a missing or changed source must not silently fall back to another. Unsaved drafts cannot be silently discarded by Refresh or checkout navigation. Source-bound UI requests carry a source context checked against the live Git worktree and roadmap location; item, board, and scope writes additionally require an exact expected revision. Spec file paths in a source-bound request must stay inside that checkout. The ordinary agent CLI and unbound routes remain unchanged.

Across participant counts use one bounded feature-wide read for at most 200 unambiguous logical features. An association is not checkout-specific; ambiguous same-ID features cannot inherit one another's count or detail. Errors and overflow remain visibly incomplete, not zero.

## Canonical File Ownership

Within the resolved roadmap root:
Expand Down
4 changes: 3 additions & 1 deletion package/minimap/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ A single running minimap server can serve roadmap for any number of repos. The a
http://localhost:4312/#repo=/abs/path/to/repo&view=board
```

Each request carries its own repo identity via the `X-Minimap-Repo` header — the server itself is repo-agnostic.
Each roadmap request carries its own repo identity via `X-Minimap-Repo` (or `X-Minimap-Repo-Encoded` for non-ASCII paths) — the server itself is repo-agnostic.

For linked Git worktrees, the board picker offers **Across worktrees**. It combines compatible checkouts without copying or changing their roadmap files, displays checkout-specific conflicts and incomplete coverage, and keeps one selected checkout version in the item URL. Edit/Raw and Save target that version only; the server rechecks the checkout identity and file revision before writing. Board ordering remains disabled in the combined view.

### Optional Pallium participants

Expand Down
142 changes: 136 additions & 6 deletions package/minimap/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import {
saveItemById,
saveScopeText,
} from "./src/roadmap.js";
import { loadWorktreeAggregate } from "./src/worktree-aggregate.js";
import { selectWorktreeParticipantCandidates } from "./src/worktree-presence.js";
import { requirePathInSource, requireRoadmapInSource, verifySourceContext } from "./src/source-bound.js";
import { withSourceWriteGuard } from "./src/source-write-guard.js";
import {
addFileSessionSuggestion,
addFileSessionSuggestionReply,
Expand Down Expand Up @@ -158,7 +162,35 @@ function requireQueryParam(requestUrl, name) {

async function withJsonBody(request) {
const raw = await readRequestBody(request);
return parseJsonBody(raw);
if (request.boundRepoRoot) await validateBoundRequest(request);
const body = parseJsonBody(raw);
if (request.boundSpecRepo) {
request.boundBodyPaths = ["file", "from", "to"].filter((key) => Object.hasOwn(body, key)).map((key) => body[key]);
for (const candidate of request.boundBodyPaths) await requirePathInSource(request.boundSpecRepo, candidate);
}
return body;
}

async function validateBoundRequest(request) {
await verifySourceContext(request.boundRepoRoot, request.boundExpected);
if (request.boundSpecRepo) {
if (request.boundUrl.searchParams.has("path")) {
await requirePathInSource(request.boundRepoRoot, request.boundUrl.searchParams.get("path"));
}
for (const candidate of request.boundBodyPaths || []) await requirePathInSource(request.boundRepoRoot, candidate);
return;
}
const roadmap = await requireRoadmapInSource(request.boundRepoRoot);
const expectedPath = request.boundExpected.roadmapBinding?.resolvedPath;
const actualPath = roadmap.resolvedPath;
const samePath = typeof expectedPath === "string" && path.isAbsolute(expectedPath)
&& (process.platform === "win32"
? path.normalize(expectedPath).toLowerCase() === path.normalize(actualPath).toLowerCase()
: path.normalize(expectedPath) === path.normalize(actualPath));
if (request.boundExpected.roadmapBinding?.roadmapPath !== roadmap.roadmapPath
|| !samePath) {
throw new AppError("Roadmap location changed. Reload this source before continuing.", 409, "source_changed");
}
}

function requireFileFromBody(body, message) {
Expand All @@ -169,7 +201,16 @@ function requireFileFromBody(body, message) {
}

async function resolveRoadmapRepo(request) {
const headerRepo = request.headers["x-minimap-repo"];
if (request.boundRepoRoot) return request.boundRepoRoot;
const encodedRepo = request.headers["x-minimap-repo-encoded"];
let headerRepo = request.headers["x-minimap-repo"];
if (encodedRepo !== undefined) {
if (typeof encodedRepo !== "string" || headerRepo !== undefined) {
throw new AppError("Invalid repo path headers.", 400, "bad_request");
}
try { headerRepo = decodeURIComponent(encodedRepo); }
catch { throw new AppError("Invalid encoded repo path.", 400, "bad_request"); }
}
const candidate = (typeof headerRepo === "string" && headerRepo.trim()) || cwdFallback;
const resolved = path.resolve(candidate);
try {
Expand Down Expand Up @@ -273,7 +314,14 @@ async function handleSpecAttach(request, response) {
}

async function handleListSpecSessions(request, response) {
const sessions = await listFileSessions();
let sessions = await listFileSessions();
if (request.boundSpecRepo) {
const scoped = await Promise.all(sessions.map(async (session) => {
try { await requirePathInSource(request.boundSpecRepo, session.targetFile); return session; }
catch { return null; }
}));
sessions = scoped.filter(Boolean);
}
sendJson(response, 200, { sessions });
}

Expand Down Expand Up @@ -384,6 +432,54 @@ async function handleWorkspace(request, response) {
sendJson(response, 200, workspace);
}

async function handleWorktreeWorkspace(request, response) {
const repoRoot = await resolveRoadmapRepo(request);
const aggregate = await loadWorktreeAggregate(repoRoot);
aggregate.participantCounts = await lookupWorktreeParticipantCounts(request, response, repoRoot, aggregate);
if (!response.destroyed) sendJson(response, 200, aggregate);
}

async function lookupWorktreeParticipantCounts(request, response, repoRoot, aggregate) {
if (!palliumConfig.configured) {
return { status: "disabled", counts: [], partial: Boolean(aggregate.partial), includeCompleted: true };
}
if (!aggregate.workspace) {
return { status: "identity-unavailable", counts: [], partial: true, includeCompleted: true };
}
const candidates = selectWorktreeParticipantCandidates(aggregate, { includeCompleted: true });
const partial = candidates.partial || candidates.ambiguous.length > 0;
if (!candidates.features.length) {
return { status: "ok", counts: [], partial, includeCompleted: true };
}
const references = await resolveRoadmapItemReferences(repoRoot, aggregate.workspace.roadmapPath, candidates.features.map((feature) => feature.id));
if (!references) {
return { status: "identity-unavailable", counts: [], partial: true, includeCompleted: true };
}
const controller = new AbortController();
const abort = () => controller.abort();
request.once("aborted", abort);
response.once("close", abort);
try {
const result = await lookupPalliumParticipantCounts(palliumConfig, references, { signal: controller.signal });
return {
status: result.status,
counts: result.status === "ok" ? result.counts.map((row, index) => ({
featureKey: candidates.features[index].key, participantCount: row.participant_count,
recentParticipantCount: row.recent_participant_count, dormantParticipantCount: row.dormant_participant_count,
})) : [],
partial,
...(result.status === "ok" ? { asOf: result.asOf, recentSeconds: result.recentSeconds } : {}),
includeCompleted: true,
};
} catch (error) {
if (!controller.signal.aborted) throw error;
return { status: "unavailable", counts: [], partial: true, includeCompleted: true };
} finally {
request.off("aborted", abort);
response.off("close", abort);
}
}

async function handleInitialize(request, response) {
const repoRoot = await resolveRoadmapRepo(request);
const workspace = await initializeWorkspace(repoRoot);
Expand All @@ -393,6 +489,9 @@ async function handleInitialize(request, response) {
async function handleBoard(request, response) {
const repoRoot = await resolveRoadmapRepo(request);
const body = await withJsonBody(request);
if (request.boundRepoRoot && typeof body.expectedRevision !== "string") {
throw new AppError("Bound board update requires expectedRevision.", 400, "revision_required");
}
const workspace = await saveBoardByGroups(repoRoot, body.groups, body.expectedRevision);
sendJson(response, 200, workspace);
}
Expand All @@ -417,8 +516,11 @@ async function handleScope(request, response) {
if (typeof body.scopeText !== "string") {
throw new AppError("Scope update must provide scopeText.", 400, "bad_request");
}
if (request.boundRepoRoot && typeof body.expectedRevision !== "string") {
throw new AppError("Bound scope update requires expectedRevision.", 400, "revision_required");
}

const workspace = await saveScopeText(repoRoot, body.scopeText);
const workspace = await saveScopeText(repoRoot, body.scopeText, body.expectedRevision ?? null);
sendJson(response, 200, workspace);
}

Expand Down Expand Up @@ -524,6 +626,9 @@ async function handleSaveItem(request, response, ctx) {
const repoRoot = await resolveRoadmapRepo(request);
const id = decodeURIComponent(ctx.params[0]);
const body = await withJsonBody(request);
if (request.boundRepoRoot && typeof body.expectedRevision !== "string") {
throw new AppError("Bound item update requires expectedRevision.", 400, "revision_required");
}

if (body.id && body.id !== id) {
throw new AppError("Item id in request body must match the URL.", 400, "bad_request");
Expand All @@ -539,6 +644,7 @@ async function handleSaveItem(request, response, ctx) {
const routes = [
{ method: "GET", pattern: /^\/health$/, handler: handleHealth },
{ method: "POST", pattern: /^\/api\/shutdown$/, handler: handleShutdown },
{ method: "GET", pattern: /^\/api\/worktree-workspace$/, handler: handleWorktreeWorkspace },
{ method: "POST", pattern: /^\/api\/spec-sessions\/attach$/, handler: handleSpecAttach },
{ method: "GET", pattern: /^\/api\/spec-sessions$/, handler: handleListSpecSessions },
{ method: "GET", pattern: /^\/api\/spec-sessions\/by-file$/, handler: handleGetSpecSession },
Expand Down Expand Up @@ -567,12 +673,36 @@ const routes = [
];

async function handleApi(request, response, requestUrl) {
const match = matchRoute(routes, request.method, requestUrl.pathname);
const bound = requestUrl.pathname.startsWith("/api/source/");
const routedUrl = bound ? new URL(requestUrl) : requestUrl;
if (bound) routedUrl.pathname = requestUrl.pathname.replace(/^\/api\/source\//, "/api/");
const match = matchRoute(routes, request.method, routedUrl.pathname);
if (!match) return false;
if (!isTrustedLocalRequest(request)) {
throw new AppError("Minimap API is available only from this local origin.", 403, "forbidden");
}
await match.handler(request, response, { url: requestUrl, params: match.params });
if (bound) {
if (["/api/shutdown", "/api/worktree-workspace", "/api/setup/initialize"].includes(routedUrl.pathname)) {
throw new AppError("Route cannot be source-bound.", 400, "bad_request");
}
const rawContext = request.headers["x-minimap-source-context"];
if (typeof rawContext !== "string" || !rawContext) {
throw new AppError("Source context is required.", 400, "source_context_required");
}
let expected;
try { expected = JSON.parse(rawContext); }
catch { throw new AppError("Invalid source context.", 400, "bad_request"); }
const repoRoot = await resolveRoadmapRepo(request);
request.boundRepoRoot = repoRoot;
request.boundExpected = expected;
request.boundSpecRepo = routedUrl.pathname.startsWith("/api/spec-sessions") ? repoRoot : null;
request.boundUrl = routedUrl;
await validateBoundRequest(request);
}
if (bound) await withSourceWriteGuard(() => validateBoundRequest(request),
() => match.handler(request, response, { url: routedUrl, params: match.params }),
(candidate) => requirePathInSource(request.boundRepoRoot, candidate));
else await match.handler(request, response, { url: routedUrl, params: match.params });
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@ Use existing linked Pallium session controls for explicit association cleanup; M
- If the tools are missing or unavailable, proceed without Pallium. Do not use a shell or HTTP substitute and do not install anything.

The optional Minimap participant panel is read-only. With a validated loopback `MINIMAP_PALLIUM_ENDPOINT`, each visible roadmap board uses one bounded count request per refresh for up to 200 board items: Minimap `GET /api/board/participant-counts` calls Pallium `POST /relay/work-refs/participant-counts`. Done, shipped, superseded, cancelled, and canceled items are omitted by default. In play adds completed candidates only when its status filter permits them, using `?includeCompleted=1`; absent or `0` keeps the default, and invalid or repeated values are rejected. Successful completed-inclusive responses echo `includeCompleted: true`; a server ignoring the flag leaves results incomplete and needs an update. Completed-item board badges appear only in In play; session detail remains available on demand in the existing item panel. In play means status `in-progress` OR any confirmed attached, nonclosed session, including dormant sessions—not working right now. Overflow and error/unknown outcomes remain visibly incomplete, never zero; in-progress matches still appear. When the endpoint is disabled, Minimap makes no Pallium HTTP requests. Exact-session links separately require an explicitly configured, reviewed compatible `MINIMAP_PALLIUM_DASHBOARD_ENDPOINT`; without it, names remain plain text. These panel settings do not control whether an agent may use already-available Pallium MCP tools.

Across worktrees is a separate read-only board projection. Its `GET /api/worktree-workspace` snapshot includes one bounded participant-count batch for at most 200 unambiguous logical features across versions, including completed versions so In play can be evaluated without a second board scan. The UI still shows badges only where the current view permits them. Associations are feature-wide, never evidence that a particular checkout version is active. Independent features sharing an NFC-equivalent item ID receive no inferred count or participant detail; a partial/unknown result is not zero.
4 changes: 3 additions & 1 deletion package/minimap/skills/minimap-roadmap/references/server.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ Restart checks every registered/requested target before any shutdown, does not s

## Multi-repo

The server is repo-agnostic. Every roadmap request carries its own repo identity via the `X-Minimap-Repo` header (set by the UI from the `#repo=...` URL hash). One server can serve any number of repos at once.
The server is repo-agnostic. Roadmap requests carry the repo chosen by the UI's `#repo=...` URL hash in `X-Minimap-Repo`, or in `X-Minimap-Repo-Encoded` for paths that cannot be sent as an ASCII HTTP header. One server can serve any number of repos at once.

The browser's **Across worktrees** board reads `GET /api/worktree-workspace` for the opened repo. Its source-specific requests use `/api/source/...` plus the returned `X-Minimap-Source-Context`; the server rechecks the live Git checkout and roadmap location, and source-bound item/board/scope writes require `expectedRevision`. Source-bound spec paths cannot escape the checkout. The UI uses `X-Minimap-Repo-Encoded` for non-ASCII paths when needed. Do not construct or reuse a source context from a guessed path, stale response, or another repo. This is a UI safety boundary, not a new agent roadmap-editing workflow: agents continue to edit only their assigned checkout's canonical files and do not automatically copy changes across worktrees.

## Optional Pallium participants

Expand Down
Loading
Loading
0