diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json index 47f2b8d3ba..f57f8c0906 100644 --- a/.github/plugin/marketplace.json +++ b/.github/plugin/marketplace.json @@ -86,6 +86,12 @@ "description": "See a live map of the Copilot agents on your computer, their sub-agents, their commands, and where their data goes.", "version": "1.0.1" }, + { + "name": "agent-session-board", + "source": "plugins/agent-session-board", + "description": "Supervise several Copilot sessions working one GitHub repository: a decision queue, progress by label track, merge-gate status for every PR, hourly and daily merge flow, warnings, and an optional merge-lock lane.", + "version": "1.0.0" + }, { "name": "agentcouncil", "description": "Multi-model council for Copilot CLI: three subagents on different model families (Anthropic, OpenAI, Google) answer independently, then build on each other or attack the leading answer before an orchestrator writes the final result from anonymized inputs.", diff --git a/docs/README.plugins.md b/docs/README.plugins.md index 51e54af9bb..5e1600ca50 100644 --- a/docs/README.plugins.md +++ b/docs/README.plugins.md @@ -31,6 +31,7 @@ See [CONTRIBUTING.md](../CONTRIBUTING.md#adding-plugins) for guidelines on how t | [acreadiness-cockpit](../plugins/acreadiness-cockpit/README.md) | Drive Microsoft AgentRC from Copilot chat: assess AI readiness, generate Copilot instructions (flat or nested with applyTo globs for monorepos), and manage policies. Produces a self-contained static HTML dashboard at reports/index.html. | 4 items | agentrc, ai-readiness, copilot-instructions, readiness-report, monorepo, policy, dashboard | | [adobe-illustrator](../plugins/adobe-illustrator/README.md) | Adobe Illustrator scripting, extension and plug-in development, MCP and command-line automation, and Creative Cloud asset management, led by an expert technical artist agent for Adobe Creative Cloud. | 3 items | adobe-illustrator, illustrator, extendscript, cep, uxp, creative-cloud, graphic-design, automation, mcp | | [agent-radar](../plugins/agent-radar/README.md) | See a live map of the Copilot agents on your computer, their sub-agents, their commands, and where their data goes. | 1 items | agents, canvas, copilot-extension, data-flow, mcp, observability, subagents, token-usage | +| [agent-session-board](../plugins/agent-session-board/README.md) | Supervise several Copilot sessions working one GitHub repository: a decision queue, progress by label track, merge-gate status for every PR, hourly and daily merge flow, warnings, and an optional merge-lock lane. | 1 items | canvas, copilot-extension, dashboard, merge-queue, multi-agent, pull-requests, supervision | | [ai-credits-breakdown](../plugins/ai-credits-breakdown/README.md) | See exactly where your own GitHub Copilot AI credits go: dollars by day, repository, model, call type and prompt-cache state, built privately on your computer from your Copilot telemetry. | 1 items | ai-credits, canvas, copilot-extension, cost-tracking, token-usage, usage-analytics | | [ai-team-orchestration](../plugins/ai-team-orchestration/README.md) | Run a lightweight, role-separated AI development team with flexible tools, developer-selected models, proportionate planning, and optional QA. | 4 items | ai-team, multi-agent, sprint-planning, brainstorm, project-management, orchestration, developer-workflow | | [apng-studio](../plugins/apng-studio/README.md) | Interactive GitHub Copilot app canvas extension for building Animated PNG (APNG) files from frames. Draw or upload frames, tune per-frame timing and compositing, preview live, send the result to your phone by QR, and export an animated .png. | 1 items | animated-png, apng, copilot-canvas, frame-animation, image-export, interactive-canvas | diff --git a/extensions/agent-session-board/README.md b/extensions/agent-session-board/README.md new file mode 100644 index 0000000000..a088b41ca5 --- /dev/null +++ b/extensions/agent-session-board/README.md @@ -0,0 +1,103 @@ +# Agent Session Board + +A canvas for supervising several Copilot agent sessions that work on one GitHub repository through issues, pull requests, reviews and merges. One screen answers: what is waiting on me, how far along is each milestone, which PR is stuck at which gate, and how fast is work landing. + +![Agent Session Board showing demo data](assets/preview.png) + +## What it shows + +- **Waiting on you**: questions that agents put on the board (choice buttons or a free answer), plus open issues carrying a decision label. Agents read the answers back with `get_answers`. An answer is tied to the exact version of its question (title, detail, options and link), so a question revised under the same id starts unanswered and never receives, returns or is hidden by an answer meant for the old one. +- **Progress by track**: one row per configured label (milestone, area, phase, …) with checklist progress from issue bodies, closed/total issues, and merges in the last 24 hours and 7 days. A track with no open issues shows as ready; if a label has more issues than one refresh loads, its numbers are marked partial and it is never shown as ready. Optional epic bars use GitHub sub-issue progress. +- **Sessions**: one card per agent session with its open PRs. Each PR shows the first merge gate it has not passed: draft, conflict, CI failed, CI running, changes requested, unresolved threads, threads not fully loaded, awaiting review, no review on the latest commit, mergeability still being computed by GitHub, behind the base branch, blocked by branch rules, or mergeable. Sessions idle longer than `idleMinutes` are flagged. PRs that match no session appear under *Unassigned*. +- **Merge flow**: stacked bars for the last 24 clock hours (including the current hour) and the last 7 calendar days (including today), colored by track, plus a recent-merge list. The 24-hour and 7-day totals count exactly those bars. Times use your machine's time zone. Each chart has a data table for screen readers and keyboard users. +- **Warnings**: CI failures, conflicts, PRs idle for a day, idle sessions, an expired merge lock, a low GitHub API budget, data that was too large to load completely, and (optional) local memory, swap and heavy-process limits. +- **Local resources** (optional, off by default): with `localResources.enabled`, the header shows free memory, swap use and the number of running processes that match `heavyPattern`. +- **Merge lock** (optional): reads lock, reserve and release lines from comments on a coordination issue. + +The board is in English. Set `language: "ko"` with `configure_board` to show it in Korean. + +## Open it + +```text +open_canvas agent-session-board { "repo": "owner/name" } +open_canvas agent-session-board { "demo": true } +``` + +`demo: true` shows fictional sample data and needs no GitHub access. + +## Actions + +| Action | Purpose | +| --- | --- | +| `refresh` | Collect from GitHub now and return a compact summary. | +| `get_summary` | Return the summary, using a one-minute cache. | +| `configure_board` | Set `sessions`, `tracks`, `epics`, `decisionLabel`, `coordinationIssue`, `lockPrefixes`, `lockAuthors`, `localResources`, `idleMinutes`, `language`. Only the fields you pass change. | +| `set_decisions` | Replace (default) or append (`mode: "append"`) the questions waiting on the user. The queue holds up to 50 questions; an append that would exceed that is refused instead of dropping older questions. | +| `get_answers` | Answers given on the board that have not been marked seen, each with its `id` and `at`. | +| `mark_answers_seen` | Pass `answers: [{ id, at }]` from `get_answers`. If the user changed an answer since, it stays unseen and is returned in `changed`. | + +Example configuration: + +```json +{ + "sessions": [ + { "id": "api", "name": "API worker", "branchPatterns": ["^api/"] }, + { "id": "docs", "name": "Docs worker", "titlePatterns": ["^docs:"], "prs": [42] } + ], + "tracks": [ + { "label": "milestone: alpha", "name": "Alpha", "group": "Milestones" }, + { "label": "area: docs", "name": "Docs", "group": "Areas", "titlePattern": "^docs:" } + ], + "epics": [{ "number": 10, "name": "Alpha release" }], + "decisionLabel": "needs-decision", + "coordinationIssue": 1 +} +``` + +### How a merge is attributed to a track + +1. The PR's own labels. +2. The labels of issues the PR closes or references (`#123` in the title or body). +3. The labels of those issues' parent (epic) issues. + +If several tracks match at one step, the one listed first wins. Only when no label matches is each track's optional `titlePattern` tried against the PR, issue and parent titles. Anything left is *Untracked*. If an item has more labels than one refresh loads (20), or more body references exist than are resolved (320), the board warns that attribution is partial. + +### Session matching + +A PR belongs to the first session that lists its number in `prs`; otherwise the first whose `branchPatterns` match the head branch; otherwise the first whose `titlePatterns` match the title. + +Patterns are case-insensitive regular expressions matched against at most 256 characters. Because they run against titles and branch names that any contributor controls, patterns that can backtrack catastrophically are rejected: backreferences, and a repeated group that itself contains a quantifier or an alternation (for example `(a+)+`, `(a+){20}` or `(a|ab)*`). Every pattern also runs in a worker thread with a time limit; a pattern that takes too long is skipped and reported, so no pattern can stall the board. + +### Merge lock comments + +When `coordinationIssue` is set, the first line of each comment from the last 48 hours is read. With the default prefixes: + +```text +merge reserve: #138 +merge lock: #141 until 14:30Z +merge lock release: #141 +``` + +The expiry is optional and can be an ISO timestamp or `HH:MM` followed by `Z`, `UTC` or an offset such as `+09:00`. Change the prefixes with `lockPrefixes`. + +Only comments from authors whose repository permission is verified as write, maintain or admin change the lock lane, so passers-by on a public repository cannot take or release the lock. Verification needs push access to the repository and covers the 50 most recent lock-command authors; comments that could not be verified are ignored and a warning says the lane may be incomplete. To trust a fixed set of accounts instead (no permission lookups), set `lockAuthors` to their GitHub logins. + +## Requirements + +- GitHub Copilot app with canvas support. +- The [GitHub CLI](https://cli.github.com/) (`gh`), signed in with access to the repository. The board never reads or stores tokens; every GitHub call goes through `gh`. + +If `gh` is not installed or not signed in to github.com, the board shows the steps to set it up instead of loading data. `{ "demo": true }` works without `gh`. + +## Data and privacy + +- The extension starts processes in one place, `lib/exec.mjs`, and only from a fixed allowlist: `gh` for GitHub data, and `ps`, `sysctl` and `memory_pressure` for the optional local resource checks. Commands run without a shell, with arguments as an array, a timeout and an output cap. +- The board runs a local server on `127.0.0.1` with a random port. Every page and API route sits under a random per-panel key that only the canvas host receives, so other local users and web pages cannot read the board or post answers. The key opens only that local board and is not a GitHub credential. The server also requires its own `Host` header, accepts only same-origin JSON posts, and refuses to be framed. +- Board settings, questions and answers are stored per repository in `/extension-data/agent-session-board/` (`COPILOT_HOME`, or `~/.copilot` when unset). Files carry a format marker and version and are written atomically under a lock file, so several Copilot sessions can share one repository's board without losing updates; a file the extension did not write is left untouched. +- Local resource checks are off by default. + +## Development + +```bash +node --test test/*.test.mjs +``` diff --git a/extensions/agent-session-board/assets/preview.png b/extensions/agent-session-board/assets/preview.png new file mode 100644 index 0000000000..494f1c0012 Binary files /dev/null and b/extensions/agent-session-board/assets/preview.png differ diff --git a/extensions/agent-session-board/extension.mjs b/extensions/agent-session-board/extension.mjs new file mode 100644 index 0000000000..0de974142a --- /dev/null +++ b/extensions/agent-session-board/extension.mjs @@ -0,0 +1,410 @@ +// Extension: agent-session-board +// Supervise several Copilot sessions working one GitHub repository: decisions, track progress, PR merge gates, merge flow. +import { createCanvas, CanvasError, joinSession } from "@github/copilot-sdk/extension"; +import { CANVAS_ID, DEMO_KEY, StoreError, configPatch, getBoard, sanitizeDecisions, updateBoard, validAnswer } from "./lib/store.mjs"; +import { buildState, collectRaw, decisionRev, isValidRepo, prepareMatcher, summarize } from "./lib/collect.mjs"; +import { DEMO_REPO, demoBoard, demoRaw } from "./lib/demo.mjs"; +import { startServer } from "./lib/server.mjs"; + +const CACHE_MS = 60 * 1000; +const SEEN_TTL_MS = 30 * 24 * 3600 * 1000; +const instances = new Map(); +const opening = new Map(); +let session; + +function log(message, level = "warning") { + try { + session?.log?.(`[${CANVAS_ID}] ${message}`, { level, ephemeral: true })?.catch?.(() => {}); + } catch { + // Logging must never break the board. + } +} + +function asCanvasError(error) { + if (error instanceof CanvasError) return error; + if (error instanceof StoreError) return new CanvasError(error.code, error.message); + return new CanvasError("internal", error?.message || String(error)); +} + +function guarded(fn) { + return async (ctx) => { + try { + return await fn(ctx); + } catch (error) { + throw asCanvasError(error); + } + }; +} + +function requireInstance(instanceId) { + const instance = instances.get(instanceId); + if (!instance) throw new CanvasError("not_open", `Canvas instance ${instanceId} is not open; call open_canvas first.`); + return instance; +} + +// Every board change bumps the generation, so a GitHub fetch that started before it can neither be reused nor cached. +function invalidate(instance) { + instance.generation += 1; + instance.cache = null; +} + +async function stateFor(instance, force) { + const generation = instance.generation; + if (!force && instance.cache && instance.cache.generation === generation && Date.now() - instance.cache.at < CACHE_MS) return instance.cache.state; + if (instance.pending && instance.pending.generation === generation) return instance.pending.promise; + const promise = (async () => { + const now = Date.now(); + const board = await getBoard(instance.key); + const raw = instance.demo ? demoRaw(now) : await collectRaw(instance.repo, board, now); + if (instance.demo && !board.localResources.enabled) raw.local = null; + // Configured patterns run in a worker under a deadline; buildState only looks up their results. + const matcher = await prepareMatcher(raw, board); + raw.skippedPatterns = matcher.skipped; + const state = buildState(raw, board, now, matcher.test); + if (instance.generation === generation) instance.cache = { at: Date.now(), generation, state }; + return state; + })(); + const pending = { generation, promise }; + instance.pending = pending; + try { + return await promise; + } finally { + if (instance.pending === pending) instance.pending = null; + } +} + +async function saveAnswer(instance, body) { + const parsed = validAnswer(body); + if (!parsed) return { status: 400, body: { error: "id, rev and answer (1-1000 characters) are required" } }; + // Label-raised questions live on GitHub, so they are checked against a freshly collected board. + if (parsed.id.startsWith("gh-")) { + const current = (await stateFor(instance, true)).decisions.find((d) => d.id === parsed.id); + if (!current) return { status: 404, body: { error: "unknown decision" } }; + if (current.rev !== parsed.rev) return { status: 409, body: { error: "the question changed; reload and answer again" } }; + } + let outcome = null; + const board = await updateBoard(instance.key, (b) => { + // Board questions are checked inside the write lock against the stored board, so a question that another + // session replaced (same id, new content) cannot receive an answer meant for the old one. + if (!parsed.id.startsWith("gh-")) { + const current = b.decisions.find((d) => d.id === parsed.id); + if (!current) outcome = { status: 404, body: { error: "unknown decision" } }; + else if (decisionRev(current) !== parsed.rev) outcome = { status: 409, body: { error: "the question changed; reload and answer again" } }; + if (outcome) return b; + } + return { ...b, answers: { ...b.answers, [parsed.id]: { answer: parsed.answer, rev: parsed.rev, at: new Date().toISOString(), seen: false } } }; + }); + invalidate(instance); + return outcome || { status: 200, body: board.answers[parsed.id] }; +} + +function stopInstance(instanceId) { + const instance = instances.get(instanceId); + if (!instance) return; + instances.delete(instanceId); + instance.server?.close(); +} + +async function startInstance(target) { + try { + const board = await getBoard(target.key); + if (target.demo && !board.sessions.length && !board.tracks.length && !board.decisions.length && !Object.keys(board.answers).length) { + await updateBoard(target.key, (b) => ({ ...b, ...demoBoard() })); + } + } catch (error) { + throw asCanvasError(error); + } + const instance = { ...target, generation: 0, cache: null, pending: null, server: null, url: "" }; + try { + const started = await startServer({ + state: (force) => stateFor(instance, force), + answer: (body) => saveAnswer(instance, body), + log, + }); + instance.server = started.server; + instance.url = started.url; + } catch (error) { + throw new CanvasError("server_start", `Could not start the board server: ${error.message}`); + } + return instance; +} + +function parseOpenInput(input) { + const value = input && typeof input === "object" ? input : {}; + if (value.demo === true) return { key: DEMO_KEY, repo: DEMO_REPO, demo: true }; + if (!isValidRepo(value.repo)) throw new CanvasError("invalid_input", "input.repo must be an owner/name GitHub repository, or pass { demo: true }."); + return { key: value.repo.toLowerCase(), repo: value.repo, demo: false }; +} + +const titleFor = (instance) => `Agent Session Board · ${instance.repo}${instance.demo ? " (demo)" : ""}`; + +const sessionSchema = { + type: "object", + additionalProperties: false, + required: ["id"], + properties: { + id: { type: "string", description: "kebab-case id, unique on this board" }, + name: { type: "string", description: "Display name of the agent session" }, + note: { type: "string", description: "Short status line shown on the card" }, + link: { type: "string", description: "https://github.com/... link, e.g. the session's epic issue" }, + branchPatterns: { type: "array", items: { type: "string" }, description: "Regexes matched against PR head branch names" }, + titlePatterns: { type: "array", items: { type: "string" }, description: "Regexes matched against PR titles" }, + prs: { type: "array", items: { type: "integer" }, description: "Explicit PR numbers owned by this session (checked first)" }, + }, +}; + +const trackSchema = { + type: "object", + additionalProperties: false, + required: ["label"], + properties: { + label: { type: "string", description: "GitHub label that defines the track (milestone, area, phase, ...)" }, + name: { type: "string" }, + note: { type: "string" }, + group: { type: "string", description: "Optional heading grouping several tracks" }, + titlePattern: { type: "string", description: "Fallback regex matched against PR and issue titles when no label matches" }, + }, +}; + +const decisionSchema = { + type: "object", + additionalProperties: false, + required: ["title"], + properties: { + id: { type: "string", description: "Stable kebab-case id; answers are keyed by it" }, + title: { type: "string" }, + detail: { type: "string" }, + url: { type: "string", description: "Optional https://github.com/... link" }, + options: { type: "array", items: { type: "string" }, description: "Up to 8 choice buttons; the user can also type a free answer" }, + }, +}; + +const canvas = createCanvas({ + id: CANVAS_ID, + displayName: "Agent Session Board", + description: "Supervise several Copilot sessions working one GitHub repo: decision queue, label-track progress, per-PR merge gates, hourly and daily merge flow, warnings and an optional merge-lock lane.", + inputSchema: { + type: "object", + additionalProperties: false, + properties: { + repo: { type: "string", description: "GitHub owner/name to supervise (required unless demo is true)" }, + demo: { type: "boolean", description: "Show fictional sample data instead of a real repository" }, + }, + }, + actions: [ + { + name: "refresh", + description: "Re-collect data from GitHub now and return a compact summary.", + handler: guarded(async (ctx) => summarize(await stateFor(requireInstance(ctx.instanceId), true))), + }, + { + name: "get_summary", + description: "Return a compact summary of the board (open PRs by merge gate, merges by track, sessions, lock, decisions, warnings). Uses a one-minute cache.", + handler: guarded(async (ctx) => summarize(await stateFor(requireInstance(ctx.instanceId), false))), + }, + { + name: "configure_board", + description: "Configure this repository's board. Only the fields you pass change. Merges are attributed to tracks by PR label, then the labels of issues the PR closes or references, then those issues' parent epics.", + inputSchema: { + type: "object", + additionalProperties: false, + properties: { + sessions: { type: "array", items: sessionSchema, description: "Agent sessions; each PR goes to the first session whose prs, branchPatterns or titlePatterns match" }, + tracks: { type: "array", items: trackSchema, description: "Label tracks in priority order (earlier wins when several match)" }, + epics: { + type: "array", + description: "Epic issues whose sub-issue progress is shown as bars", + items: { + type: "object", + additionalProperties: false, + required: ["number"], + properties: { number: { type: "integer", minimum: 1 }, name: { type: "string" }, group: { type: "string" } }, + }, + }, + decisionLabel: { type: "string", description: "Open issues/PRs with this label join the decision queue (empty string disables)" }, + coordinationIssue: { type: "integer", minimum: 0, description: "Issue whose comments carry merge lock / reserve / release lines (0 disables the lock lane)" }, + lockAuthors: { + type: "array", + items: { type: "string" }, + description: "GitHub logins whose lock comments count. Empty (default) means anyone with write access (owner, member or collaborator)", + }, + lockPrefixes: { + type: "object", + additionalProperties: false, + description: "First-line prefixes of coordination comments, followed by #PR and optionally an expiry (ISO time or HH:MMZ)", + properties: { lock: { type: "string" }, reserve: { type: "string" }, release: { type: "string" } }, + }, + localResources: { + type: "object", + additionalProperties: false, + description: "Optional local machine checks (off by default): free memory, swap, and a cap on heavy processes", + properties: { + enabled: { type: "boolean" }, + heavyPattern: { type: "string", description: "Regex matched against process command lines" }, + maxHeavy: { type: "integer", minimum: 0 }, + }, + }, + idleMinutes: { type: "integer", minimum: 5, description: "Flag a session with open PRs after this many idle minutes (default 90)" }, + language: { type: "string", enum: ["en", "ko"], description: "Board language; English by default" }, + }, + }, + handler: guarded(async (ctx) => { + const instance = requireInstance(ctx.instanceId); + const board = await updateBoard(instance.key, (b) => ({ ...b, ...configPatch(ctx.input || {}, b) })); + invalidate(instance); + return { + repo: instance.repo, + sessions: board.sessions.map((s) => s.id), + tracks: board.tracks.map((t) => t.label), + epics: board.epics.map((e) => e.number), + decisionLabel: board.decisionLabel, + coordinationIssue: board.coordinationIssue, + lockPrefixes: board.lockPrefixes, + lockAuthors: board.lockAuthors, + localResources: board.localResources, + idleMinutes: board.idleMinutes, + language: board.language, + }; + }), + }, + { + name: "set_decisions", + description: "Put questions for the user on the board. mode 'replace' (default) swaps the whole queue; 'append' adds or updates items by id.", + inputSchema: { + type: "object", + additionalProperties: false, + required: ["items"], + properties: { + items: { type: "array", items: decisionSchema }, + mode: { type: "string", enum: ["replace", "append"] }, + }, + }, + handler: guarded(async (ctx) => { + const instance = requireInstance(ctx.instanceId); + const items = sanitizeDecisions(ctx.input?.items); + const mode = ctx.input?.mode === "append" ? "append" : "replace"; + const board = await updateBoard(instance.key, (b) => { + const kept = mode === "append" ? b.decisions.filter((d) => !items.some((i) => i.id === d.id)) : []; + const decisions = [...kept, ...items]; + // Several agents share this queue; refuse to grow it past 50 rather than evict someone else's question. + if (decisions.length > 50) { + throw new StoreError("queue_full", `The decision queue would hold ${decisions.length} questions; the limit is 50. Mark answered questions seen or replace the queue.`); + } + // An answer only carries over when the same question (id and title) is still open; anything else starts fresh. + const answers = { ...b.answers }; + for (const item of items) { + // Any content change (title, detail, options or link) changes the revision and drops the old answer. + if (Object.hasOwn(answers, item.id) && (answers[item.id].seen || answers[item.id].rev !== decisionRev(item))) delete answers[item.id]; + } + return { ...b, decisions, answers }; + }); + invalidate(instance); + return { repo: instance.repo, decisions: board.decisions.map((d) => d.id) }; + }), + }, + { + name: "get_answers", + description: "Return answers the user gave on the board that have not been marked seen. After acting on them, call mark_answers_seen with each answer's id and at.", + handler: guarded(async (ctx) => { + const instance = requireInstance(ctx.instanceId); + const board = await getBoard(instance.key); + // Board questions are checked against the stored board; label questions against a freshly collected one. + // Refresh from GitHub only when an unseen answer to a label-raised question could be returned. + const needsLabels = Object.entries(board.answers).some(([id, a]) => id.startsWith("gh-") && !a.seen); + const labelled = needsLabels ? (await stateFor(instance, true)).decisions.filter((d) => d.source === "label") : []; + const current = new Map([...board.decisions.map((d) => ({ ...d, rev: decisionRev(d) })), ...labelled].map((d) => [d.id, d])); + const titles = new Map([...current.values()].map((d) => [d.id, d.title])); + const answers = Object.entries(board.answers) + // Only answers to the current revision of a question that is still asked are returned. + .filter(([id, a]) => !a.seen && current.has(id) && current.get(id).rev === a.rev) + .map(([id, a]) => ({ id, title: titles.get(id) || id, answer: a.answer, at: a.at })) + .sort((a, b) => String(b.at).localeCompare(String(a.at))); + const answered = new Set(Object.keys(board.answers)); + return { answers, unanswered: board.decisions.filter((d) => !answered.has(d.id)).map((d) => d.id) }; + }), + }, + { + name: "mark_answers_seen", + description: "Mark answers as handled; their questions leave the queue. Pass the id and at from get_answers: if the user changed the answer since, it stays unseen and is listed in changed.", + inputSchema: { + type: "object", + additionalProperties: false, + required: ["answers"], + properties: { + answers: { + type: "array", + items: { + type: "object", + additionalProperties: false, + required: ["id", "at"], + properties: { id: { type: "string" }, at: { type: "string", description: "The at value returned by get_answers" } }, + }, + }, + }, + }, + handler: guarded(async (ctx) => { + const instance = requireInstance(ctx.instanceId); + const acks = new Map((Array.isArray(ctx.input?.answers) ? ctx.input.answers : []) + .filter((a) => a && typeof a.id === "string" && typeof a.at === "string") + .map((a) => [a.id, a.at])); + let marked = 0; + const changed = []; + await updateBoard(instance.key, (b) => { + const answers = {}; + const cutoff = Date.now() - SEEN_TTL_MS; + for (const [id, a] of Object.entries(b.answers)) { + // Only the exact answer the agent read is acknowledged; a newer one stays for the next get_answers. + const acknowledged = acks.has(id) && acks.get(id) === a.at; + if (acks.has(id) && !acknowledged && !a.seen) changed.push(id); + if (acknowledged && !a.seen) marked += 1; + const next = acknowledged ? { ...a, seen: true, seenAt: new Date().toISOString() } : a; + // Old handled answers are dropped so the file stays small. + if (!(next.seen && Date.parse(next.seenAt || next.at) < cutoff)) answers[id] = next; + } + return { ...b, answers, decisions: b.decisions.filter((d) => !(Object.hasOwn(answers, d.id) && answers[d.id].seen)) }; + }); + invalidate(instance); + return { marked, changed }; + }), + }, + ], + open: async (ctx) => { + const target = parseOpenInput(ctx.input); + const id = ctx.instanceId; + const existing = instances.get(id); + if (existing && existing.key === target.key && existing.server?.listening) { + return { url: existing.url, title: titleFor(existing) }; + } + const inflight = opening.get(id); + if (inflight && inflight.key === target.key) { + const instance = await inflight.promise; + return { url: instance.url, title: titleFor(instance) }; + } + if (inflight) inflight.cancelled = true; + if (existing) stopInstance(id); + const entry = { key: target.key, cancelled: false, promise: null }; + entry.promise = startInstance(target).then((instance) => { + // A close or a newer open for this panel arrived while starting; do not leave a server behind. + if (entry.cancelled) { + instance.server.close(); + throw new CanvasError("cancelled", "The canvas was closed or reopened while it was starting."); + } + instances.set(id, instance); + return instance; + }); + opening.set(id, entry); + try { + const instance = await entry.promise; + return { url: instance.url, title: titleFor(instance) }; + } finally { + if (opening.get(id) === entry) opening.delete(id); + } + }, + onClose: (ctx) => { + const inflight = opening.get(ctx.instanceId); + if (inflight) inflight.cancelled = true; + stopInstance(ctx.instanceId); + }, +}); + +session = await joinSession({ canvases: [canvas] }); diff --git a/extensions/agent-session-board/lib/collect.mjs b/extensions/agent-session-board/lib/collect.mjs new file mode 100644 index 0000000000..1b05900435 --- /dev/null +++ b/extensions/agent-session-board/lib/collect.mjs @@ -0,0 +1,961 @@ +import { createHash } from "node:crypto"; +import os from "node:os"; +import { MAX_SUBJECT, evaluatePatterns, safeRegex, testPattern } from "./pattern.mjs"; +import { run } from "./exec.mjs"; + +const HOUR = 3600 * 1000; +const DAY = 24 * HOUR; +const STALE_HOURS = 24; +const MAX_WARNINGS = 20; +const API_LOW = 500; + +// GitHub owners are alphanumeric with hyphens; repository names also allow "." and "_" but not "." or ".." alone. +const REPO_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/(?!\.{1,2}$)[A-Za-z0-9_.-]{1,100}$/; + +export const UNTRACKED = ""; + +export function isValidRepo(repo) { + return typeof repo === "string" && REPO_RE.test(repo); +} + +// --------------------------------------------------------------------------- +// Pure helpers (unit tested) +// --------------------------------------------------------------------------- + +/** A short fingerprint of a question's content; answers must name the revision they were given for. */ +export function decisionRev(decision) { + // `body` is the full text of a label-raised issue, where its options live; it is hashed but never sent to the page. + const content = JSON.stringify([decision.title || "", decision.detail || "", decision.options || [], decision.url || "", decision.body || ""]); + // The full digest: the hash binds answers to contributor-controlled content, so it is not truncated. + return createHash("sha256").update(content).digest("hex"); +} + +/** Explicit PR numbers win, then head-branch patterns, then title patterns. Returns a session id or null. */ +export function matchSession(pr, sessions, test = testPattern) { + const list = Array.isArray(sessions) ? sessions : []; + for (const s of list) if (Array.isArray(s.prs) && s.prs.includes(pr.number)) return s.id; + for (const s of list) if ((s.branchPatterns || []).some((p) => test(p, pr.headRefName))) return s.id; + for (const s of list) if ((s.titlePatterns || []).some((p) => test(p, pr.title))) return s.id; + return null; +} + +export function referencedNumbers(pr) { + const text = `${pr.title || ""}\n${pr.body || ""}`; + const out = new Set(); + for (const m of text.matchAll(/(?:^|[^\w/&])#(\d{1,7})\b/g)) { + const n = Number(m[1]); + if (n !== pr.number) out.add(n); + } + // Every reference is kept; the global resolution budget in addBodyRefs counts anything it cannot resolve. + return [...out]; +} + +/** The first configured track whose label appears in `labels`; configuration order is priority. */ +export function pickTrack(labels, tracks) { + const set = new Set(labels || []); + for (const t of tracks || []) if (set.has(t.label)) return t.label; + return null; +} + +function trackFromTitles(titles, tracks, test) { + for (const t of tracks || []) { + if (t.titlePattern && titles.some((title) => title && test(t.titlePattern, title))) return t.label; + } + return null; +} + +/** + * Attribute a merged PR to a track: + * 1. the PR's own labels, + * 2. the labels of the issues it closes or references, + * 3. the labels of those issues' parent (epic) issues, + * and, only when no label matched, each track's optional titlePattern against the same titles. + */ +export function attributeTrack(pr, tracks, test = testPattern) { + const refs = Array.isArray(pr.refs) ? pr.refs : []; + return pickTrack(pr.labels, tracks) + || pickTrack(refs.flatMap((r) => r.labels || []), tracks) + || pickTrack(refs.flatMap((r) => r.parent?.labels || []), tracks) + || trackFromTitles([pr.title, ...refs.map((r) => r.title), ...refs.map((r) => r.parent?.title)], tracks, test) + || UNTRACKED; +} + +/** Expiry written in a lock line: an ISO timestamp, or HH:MM with Z/UTC/±HH:MM (next occurrence after the comment). */ +export function lockExpiry(line, createdAt) { + const iso = line.match(/\b(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2}))/); + if (iso) { + const t = Date.parse(iso[1]); + return Number.isNaN(t) ? null : new Date(t).toISOString(); + } + const hm = line.match(/\b(\d{1,2}):(\d{2})\s*(Z|UTC|[+-]\d{2}:?\d{2})(?![\w:])/i); + if (!hm) return null; + const hours = Number(hm[1]); + const minutes = Number(hm[2]); + if (hours > 23 || minutes > 59) return null; + let offset = 0; + if (/^[+-]/.test(hm[3])) { + const z = hm[3].replace(":", ""); + offset = (z[0] === "-" ? -1 : 1) * (Number(z.slice(1, 3)) * 60 + Number(z.slice(3, 5))); + } + const base = Date.parse(createdAt); + if (Number.isNaN(base)) return null; + // Take the comment's calendar date in the offset the line was written in, not in UTC. + const local = new Date(base + offset * 60000); + let candidate = Date.UTC(local.getUTCFullYear(), local.getUTCMonth(), local.getUTCDate(), hours, minutes) - offset * 60000; + // A time up to an hour before the comment is an already-expired lock, not tomorrow's. + while (candidate < base - HOUR) candidate += DAY; + return new Date(candidate).toISOString(); +} + +/** Classify the first line of a coordination comment. Longest prefix first, so "merge lock release:" never reads as "merge lock:". */ +export function parseLockLine(line, prefixes) { + const text = String(line || "").replace(/^[*_>\s`]+/, "").trim(); + const lower = text.toLowerCase(); + const kinds = ["release", "reserve", "lock"] + .filter((k) => typeof prefixes?.[k] === "string" && prefixes[k].trim()) + .sort((a, b) => prefixes[b].length - prefixes[a].length); + for (const kind of kinds) { + if (!lower.startsWith(prefixes[kind].trim().toLowerCase())) continue; + const pr = Number((text.match(/#(\d{1,7})\b/) || [])[1]); + return pr ? { kind, pr, text } : null; + } + return null; +} + +/** + * Lock lines count only from the configured `lockAuthors`, or by default from authors whose repository + * permission was verified as write, maintain or admin. Unverified authors fail closed. + */ +export function isTrustedLockAuthor(comment, lockAuthors) { + const allow = (lockAuthors || []).map((a) => String(a).toLowerCase()); + if (allow.length) return allow.includes(String(comment.author || "").toLowerCase()); + return comment.writeAccess === true; +} + +/** + * Replay coordination comments into the current lock holder and reservation queue. + * `openNumbers` is the set of open PRs, or null when the open list is incomplete (then nothing is dropped as closed). + */ +export function parseLocks(comments, prefixes, openNumbers, now = Date.now(), lockAuthors = []) { + let holder = null; + const reservations = new Map(); + const events = []; + let ignored = 0; + let unverified = 0; + const isOpen = (pr) => openNumbers === null || openNumbers.has(pr); + const sorted = [...(comments || [])].sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt))); + for (const comment of sorted) { + const parsed = parseLockLine(comment.line, prefixes); + if (!parsed) continue; + if (!isTrustedLockAuthor(comment, lockAuthors)) { + // null means the author's permission was never checked: the lane is then uncertain, not just filtered. + if (comment.writeAccess === null && !(lockAuthors || []).length) unverified += 1; + else ignored += 1; + continue; + } + const { kind, pr, text } = parsed; + events.push({ kind, pr, at: comment.createdAt, author: comment.author || "", line: text.slice(0, 200), url: comment.url }); + if (kind === "release") { + if (holder && holder.pr === pr) holder = null; + reservations.delete(pr); + } else if (kind === "lock") { + holder = { pr, since: comment.createdAt, until: lockExpiry(text, comment.createdAt), line: text.slice(0, 200), url: comment.url }; + reservations.delete(pr); + } else { + reservations.set(pr, { pr, at: comment.createdAt, url: comment.url }); + } + } + if (holder) { + holder.expired = holder.until ? Date.parse(holder.until) < now : false; + if (!isOpen(holder.pr)) holder = null; + } + return { + holder, + reservations: [...reservations.values()].filter((r) => isOpen(r.pr)), + events: events.slice(-12), + ignored, + unverified, + }; +} + +export function ciFromRollup(state) { + switch (state) { + case "SUCCESS": return "passed"; + case "FAILURE": + case "ERROR": return "failed"; + case "PENDING": + case "EXPECTED": return "running"; + default: return "none"; + } +} + +/** The first gate a PR still has to pass, in the order a merge would hit them. */ +export function prGate(pr) { + if (pr.isDraft) return "draft"; + if (pr.mergeable === "CONFLICTING") return "conflict"; + if (pr.ci === "failed") return "ci-failed"; + if (pr.ci === "running") return "ci-running"; + if (pr.reviewDecision === "CHANGES_REQUESTED") return "changes-requested"; + if ((pr.unresolvedThreads || 0) > 0) return "unresolved-threads"; + if (pr.threadsComplete === false) return "threads-unknown"; + if (pr.reviewDecision === "REVIEW_REQUIRED") return "review-required"; + if (!pr.headReviewed) return "no-head-review"; + // GitHub reports UNKNOWN while it computes mergeability; never call that mergeable. + if (pr.mergeable !== "MERGEABLE") return "mergeability-unknown"; + // MERGEABLE only means conflict-free; mergeStateStatus says whether the repository's own rules allow the merge. + if (pr.mergeStateStatus === "BEHIND") return "behind"; + if (pr.mergeStateStatus === "BLOCKED") return "blocked"; + if (pr.mergeStateStatus === "UNKNOWN") return "mergeability-unknown"; + return "mergeable"; +} + +export function checklist(body) { + // [ \t]* keeps every match attempt on one line, so long bodies cannot trigger heavy backtracking. + const boxes = String(body || "").match(/^[ \t]*[-*] \[[ xX]\]/gm) || []; + const ticked = String(body || "").match(/^[ \t]*[-*] \[[xX]\]/gm) || []; + return { total: boxes.length, done: ticked.length }; +} + +function pad(n) { + return String(n).padStart(2, "0"); +} + +// Buckets follow the host's local time zone, which is the user's machine. +export function hourKey(ms) { + const d = new Date(ms); + return `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}`; +} + +export function dayKey(ms) { + const d = new Date(ms); + return `${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; +} + +/** + * Local-time buckets and the exact windows they cover: 24 clock hours ending with the current hour, + * and 7 calendar days ending today. Totals use the same windows, so every counted merge has a bar. + */ +export function mergeWindows(now) { + // Subtract the elapsed part of the local hour instead of setMinutes(0): during the repeated hour at the end of + // daylight saving time, setMinutes picks the earlier offset and would shift the window an hour back. + const at = new Date(now); + const hourStart = new Date(now - (at.getMinutes() * 60000 + at.getSeconds() * 1000 + at.getMilliseconds())); + const hours = []; + for (let i = 23; i >= 0; i -= 1) hours.push(hourStart.getTime() - i * HOUR); + const today = new Date(now); + today.setHours(0, 0, 0, 0); + const days = []; + for (let i = 6; i >= 0; i -= 1) { + const d = new Date(today); + d.setDate(today.getDate() - i); + days.push(d.getTime()); + } + return { hours, days, hourSince: hours[0], daySince: days[0] }; +} + +const own = (object, key) => object !== null && typeof object === "object" && Object.hasOwn(object, key); + +function trackProgress(track, issues, complete, merged24, merged7) { + const rows = (issues || []).map((issue) => { + const box = checklist(issue.body); + const open = issue.state === "OPEN"; + const tasks = Math.max(box.total, 1); + // A closed issue counts as fully done; an open one without a checklist counts as one unfinished task. + const done = open ? (box.total ? box.done : 0) : tasks; + return { number: issue.number, title: issue.title, url: issue.url, open, tasks, done }; + }).sort((a, b) => a.number - b.number); + const total = rows.length; + const closed = rows.filter((r) => !r.open).length; + const tasks = rows.reduce((a, r) => a + r.tasks, 0); + const tasksDone = rows.reduce((a, r) => a + r.done, 0); + return { + label: track.label, + name: track.name || track.label, + note: track.note || "", + group: track.group || "", + total, + closed, + open: total - closed, + tasks, + tasksDone, + pct: tasks ? Math.round((tasksDone / tasks) * 100) : 0, + // Totals from a truncated issue list are partial, so a track is never called ready on them. + complete, + ready: complete && total > 0 && closed === total, + openIssues: rows.filter((r) => r.open).map(({ number, title, url }) => ({ number, title, url })), + merged24: merged24.filter((m) => m.track === track.label).length, + merged7: merged7.filter((m) => m.track === track.label).length, + }; +} + +function capWarnings(list) { + if (list.length <= MAX_WARNINGS) return list; + return [...list.slice(0, MAX_WARNINGS - 1), { level: "info", code: "more_warnings", params: { count: list.length - MAX_WARNINGS + 1 } }]; +} + +/** + * Turn raw repository data (from GitHub or the demo) and the stored board into the view model. + * Pure: no I/O, `now` is injected. + */ +export function buildState(raw, board, now = Date.now(), test = testPattern) { + const sessions = board.sessions || []; + const tracks = board.tracks || []; + const incomplete = raw.incomplete || {}; + const openNumbers = incomplete.openPrs ? null : new Set((raw.openPrs || []).map((pr) => pr.number)); + const lock = parseLocks(raw.lockComments || [], board.lockPrefixes, openNumbers, now, board.lockAuthors); + + const prs = (raw.openPrs || []).map((pr) => { + const tags = []; + if (lock.holder && lock.holder.pr === pr.number) tags.push(lock.holder.expired ? "lock-expired" : "lock"); + if (lock.reservations.some((r) => r.pr === pr.number)) tags.push("reserved"); + return { + number: pr.number, + title: pr.title, + url: pr.url, + branch: pr.headRefName, + updatedAt: pr.updatedAt, + session: matchSession(pr, sessions, test), + gate: prGate(pr), + ci: pr.ci, + checks: pr.checks || 0, + unresolvedThreads: pr.unresolvedThreads || 0, + tags, + }; + }); + + const windows = mergeWindows(now); + const mergedWeek = (raw.merged || []) + .filter((pr) => pr.mergedAt && Date.parse(pr.mergedAt) >= windows.daySince && Date.parse(pr.mergedAt) <= now) + .map((pr) => ({ + number: pr.number, + title: pr.title, + url: pr.url, + mergedAt: pr.mergedAt, + session: matchSession(pr, sessions, test), + track: attributeTrack(pr, tracks, test), + })) + .sort((a, b) => a.mergedAt.localeCompare(b.mergedAt)); + const merged24 = mergedWeek.filter((pr) => Date.parse(pr.mergedAt) >= windows.hourSince); + + // Hours are indexed by absolute offset from the window start, so the repeated local hour at the end + // of daylight saving time stays two separate bars; the local label is for display only. + const hours = windows.hours.map((t) => ({ key: hourKey(t), start: new Date(t).toISOString(), counts: Object.create(null) })); + for (const pr of merged24) { + const bucket = hours[Math.floor((Date.parse(pr.mergedAt) - windows.hourSince) / HOUR)]; + if (bucket) bucket.counts[pr.track] = (bucket.counts[pr.track] || 0) + 1; + } + // Track labels are user text ("constructor", "__proto__"), so count maps have no prototype. + const days = windows.days.map((t) => ({ key: dayKey(t), counts: Object.create(null) })); + const dayIndex = new Map(days.map((d) => [d.key, d])); + for (const pr of mergedWeek) { + const bucket = dayIndex.get(dayKey(Date.parse(pr.mergedAt))); + if (bucket) bucket.counts[pr.track] = (bucket.counts[pr.track] || 0) + 1; + } + + const idleLimit = Number.isInteger(board.idleMinutes) && board.idleMinutes > 0 ? board.idleMinutes : 90; + const cards = [...sessions, { id: null, name: "" }].map((s) => { + const own = prs.filter((pr) => pr.session === s.id); + const ownMerged = merged24.filter((pr) => pr.session === s.id); + const times = [...own.map((pr) => pr.updatedAt), ...ownMerged.map((pr) => pr.mergedAt)].filter(Boolean).sort(); + const last = times.length ? times[times.length - 1] : ""; + const idleMinutes = last ? Math.max(0, Math.round((now - Date.parse(last)) / 60000)) : null; + return { + id: s.id, + name: s.name || s.id || "", + note: s.note || "", + link: s.link || "", + prs: own, + merged24: ownMerged.length, + lastActivity: last, + idleMinutes, + idle: s.id !== null && own.length > 0 && idleMinutes !== null && idleMinutes > idleLimit, + }; + }).filter((card) => card.id !== null || card.prs.length > 0 || card.merged24 > 0); + + const trackRows = tracks.map((t) => trackProgress(t, (raw.trackIssues && Object.hasOwn(raw.trackIssues, t.label) ? raw.trackIssues[t.label] : []), !(incomplete.tracks || []).includes(t.label), merged24, mergedWeek)); + const epics = (raw.epics || []).map((e) => { + const closed = e.state === "CLOSED"; + const pct = closed ? 100 : e.total ? Math.round((e.completed / e.total) * 100) : 0; + return { ...e, pct }; + }); + const epicTotal = epics.reduce((a, e) => a + (e.total || 0), 0); + const overall = epicTotal + ? Math.round((100 * epics.reduce((a, e) => a + (e.state === "CLOSED" ? e.total || 0 : e.completed || 0), 0)) / epicTotal) + : null; + + // With sessions configured, PR warnings focus on the configured sessions' own PRs instead of every contributor's. + const watched = sessions.length ? prs.filter((pr) => pr.session !== null) : prs; + const warnings = []; + if (raw.setup) warnings.push({ level: "error", code: raw.setup, params: {} }); + for (const err of raw.errors || []) warnings.push({ level: "error", code: "collect_error", params: err }); + if (incomplete.openPrs) warnings.push({ level: "warn", code: "open_prs_incomplete", params: { shown: prs.length, total: raw.openPrTotal } }); + if (incomplete.merged) warnings.push({ level: "warn", code: "merges_incomplete", params: { shown: mergedWeek.length } }); + for (const label of incomplete.tracks || []) warnings.push({ level: "warn", code: "track_incomplete", params: { track: (tracks.find((t) => t.label === label) || {}).name || label } }); + if (incomplete.decisions) warnings.push({ level: "warn", code: "decisions_incomplete", params: { shown: (raw.decisionIssues || []).length } }); + if (lock.ignored) warnings.push({ level: "info", code: "lock_ignored", params: { count: lock.ignored } }); + if (lock.unverified) warnings.push({ level: "warn", code: "lock_unverified", params: { count: lock.unverified } }); + const skippedPatterns = [...(raw.skippedPatterns || []), ...(raw.local?.patternSkipped ? [board.localResources?.heavyPattern] : [])]; + for (const pattern of skippedPatterns) warnings.push({ level: "warn", code: "pattern_skipped", params: { pattern } }); + const attribution = incomplete.attribution || {}; + if (attribution.truncatedLabels || attribution.skippedRefs) { + warnings.push({ level: "warn", code: "attribution_incomplete", params: { labels: attribution.truncatedLabels || 0, refs: attribution.skippedRefs || 0 } }); + } + if (raw.rate && raw.rate.remaining < API_LOW) { + warnings.push({ level: raw.rate.remaining < API_LOW / 5 ? "error" : "warn", code: "api_low", params: { remaining: raw.rate.remaining, limit: raw.rate.limit, resetAt: raw.rate.resetAt } }); + } + if (lock.holder && lock.holder.expired) warnings.push({ level: "warn", code: "lock_expired", params: { pr: lock.holder.pr, until: lock.holder.until } }); + for (const pr of watched) { + if (pr.gate === "ci-failed") warnings.push({ level: "warn", code: "ci_failed", params: { pr: pr.number, title: pr.title } }); + if (pr.gate === "conflict") warnings.push({ level: pr.tags.length ? "error" : "warn", code: pr.tags.length ? "lock_conflict" : "conflict", params: { pr: pr.number, title: pr.title } }); + } + for (const pr of watched) { + const hoursIdle = (now - Date.parse(pr.updatedAt)) / HOUR; + if (pr.gate !== "draft" && hoursIdle >= STALE_HOURS) warnings.push({ level: "info", code: "stale_pr", params: { pr: pr.number, title: pr.title, hours: Math.round(hoursIdle) } }); + } + for (const card of cards.filter((c) => c.idle)) warnings.push({ level: "info", code: "session_idle", params: { session: card.name, minutes: card.idleMinutes } }); + const local = raw.local || null; + if (local) { + const max = Number.isInteger(board.localResources?.maxHeavy) ? board.localResources.maxHeavy : 2; + if (local.freePct !== null && local.freePct < 20) warnings.push({ level: local.freePct < 10 ? "error" : "warn", code: "memory_low", params: { freePct: local.freePct } }); + if (local.swapTotalMb && local.swapUsedMb / local.swapTotalMb > 0.8 && (local.freePct === null || local.freePct < 35)) { + warnings.push({ level: "warn", code: "swap_high", params: { usedMb: local.swapUsedMb, totalMb: local.swapTotalMb } }); + } + if (local.heavy > max) warnings.push({ level: "warn", code: "heavy_jobs", params: { count: local.heavy, max } }); + } + + const answers = board.answers || {}; + // An answer belongs to the question revision it was given for; a revised question starts unanswered. + const answerFor = (d) => (own(answers, d.id) && answers[d.id].rev === d.rev ? answers[d.id] : null); + const queued = new Set((board.decisions || []).map((d) => d.id)); + const decisions = [ + ...(board.decisions || []).map((d) => ({ ...d, source: "board" })), + ...(raw.decisionIssues || []) + .filter((issue) => !queued.has(`gh-${issue.number}`)) + .map((issue) => ({ id: `gh-${issue.number}`, title: `#${issue.number} ${issue.title}`, url: issue.url, detail: "", options: [], body: issue.body || "", source: "label" })), + ].map(({ body, ...d }) => ({ ...d, rev: decisionRev({ ...d, body }) })) + .map((d) => ({ ...d, answer: answerFor(d) })) + .filter((d) => !(d.answer && d.answer.seen)); + + return { + repo: raw.repo, + demo: !!raw.demo, + setup: raw.setup || null, + language: board.language === "ko" ? "ko" : "en", + generatedAt: new Date(now).toISOString(), + openPrTotal: raw.openPrTotal ?? prs.length, + incomplete, + prs, + sessions: cards, + tracks: trackRows, + trackOrder: [...tracks.map((t) => ({ label: t.label, name: t.name || t.label })), { label: UNTRACKED, name: "" }], + epics, + overall, + merged24, + mergedWeek, + hours, + days, + lock: { enabled: Number(board.coordinationIssue) > 0, issue: Number(board.coordinationIssue) || 0, ...lock }, + decisionLabel: board.decisionLabel || "", + decisions, + rate: raw.rate || null, + local, + warnings: capWarnings(warnings), + }; +} + +const WARNING_TEXT = { + collect_error: (p) => `Could not load ${p.source}: ${p.message}`, + api_low: (p) => `GitHub API budget low: ${p.remaining}/${p.limit} left until ${p.resetAt}`, + lock_expired: (p) => `Merge lock on #${p.pr} passed its expiry without a release`, + lock_conflict: (p) => `Locked or reserved PR #${p.pr} has merge conflicts`, + conflict: (p) => `#${p.pr} has merge conflicts`, + ci_failed: (p) => `#${p.pr} CI failed`, + stale_pr: (p) => `#${p.pr} has had no activity for ${p.hours}h`, + session_idle: (p) => `${p.session}: no PR activity for ${p.minutes < 120 ? `${p.minutes} min` : `${Math.round(p.minutes / 60)}h`}`, + memory_low: (p) => `Free memory ${p.freePct}%`, + swap_high: (p) => `Swap ${(p.usedMb / 1024).toFixed(1)} of ${(p.totalMb / 1024).toFixed(1)} GB in use`, + heavy_jobs: (p) => `${p.count} heavy local jobs running (limit ${p.max})`, + more_warnings: (p) => `${p.count} more warnings`, + open_prs_incomplete: (p) => `Showing ${p.shown} of ${p.total} open PRs; the rest were not loaded`, + merges_incomplete: (p) => `Merge history is partial (${p.shown} loaded); totals are lower bounds`, + track_incomplete: (p) => `${p.track}: too many issues to load; progress is partial`, + decisions_incomplete: (p) => `More labeled decision issues exist than the ${p.shown} loaded`, + lock_ignored: (p) => `Ignored ${p.count} lock comments from authors without verified write access`, + lock_unverified: (p) => `Could not verify the authors of ${p.count} lock comments; the lock lane may be incomplete`, + gh_missing: () => "The GitHub CLI (gh) is not installed. Install it from https://cli.github.com, run gh auth login, then refresh", + gh_signed_out: () => "The GitHub CLI is not signed in to github.com. Run gh auth login, then refresh", + pattern_skipped: (p) => `Pattern ${p.pattern} took too long and was skipped; simplify it`, + attribution_incomplete: (p) => `Track attribution is partial: ${p.labels} items had more labels than loaded, ${p.refs} referenced issues were not resolved`, +}; + +export function warningText(w) { + const fn = WARNING_TEXT[w.code]; + return fn ? fn(w.params || {}) : w.code; +} + +export function summarize(state) { + const byGate = {}; + for (const pr of state.prs) byGate[pr.gate] = (byGate[pr.gate] || 0) + 1; + const trackName = (label) => (label === UNTRACKED ? "Untracked" : (state.trackOrder.find((t) => t.label === label) || { name: label }).name); + const countBy = (list) => { + const out = Object.create(null); + for (const pr of list) out[trackName(pr.track)] = (out[trackName(pr.track)] || 0) + 1; + return out; + }; + return { + repo: state.repo, + demo: state.demo, + generatedAt: state.generatedAt, + openPrs: state.openPrTotal, + prsByGate: byGate, + merged24h: state.merged24.length, + merged7d: state.mergedWeek.length, + mergedByTrack24h: countBy(state.merged24), + mergedByTrack7d: countBy(state.mergedWeek), + tracks: state.tracks.map((t) => ({ label: t.label, pct: t.pct, issuesClosed: t.closed, issues: t.total, ready: t.ready, merged24h: t.merged24, merged7d: t.merged7, open: t.openIssues.map((i) => i.number) })), + epics: state.epics.map((e) => ({ number: e.number, pct: e.pct, completed: e.completed, total: e.total, state: e.state })), + overall: state.overall, + sessions: state.sessions.map((s) => ({ id: s.id ?? "unassigned", open: s.prs.map((p) => `#${p.number}:${p.gate}`), merged24h: s.merged24, idleMinutes: s.idleMinutes, idle: s.idle })), + lock: state.lock.enabled + ? { holder: state.lock.holder ? { pr: state.lock.holder.pr, until: state.lock.holder.until, expired: state.lock.holder.expired } : null, reservations: state.lock.reservations.map((r) => r.pr) } + : null, + pendingDecisions: state.decisions.filter((d) => !d.answer).length, + newAnswers: state.decisions.filter((d) => d.answer && !d.answer.seen).map((d) => ({ id: d.id, answer: d.answer.answer, at: d.answer.at })), + rate: state.rate, + local: state.local, + setup: state.setup, + incomplete: state.incomplete, + warnings: state.warnings.map((w) => `${w.level}: ${warningText(w)}`), + }; +} + +// --------------------------------------------------------------------------- +// GitHub collection through the gh CLI (the user's own authentication) +// --------------------------------------------------------------------------- + + +// Page caps keep one refresh bounded; anything beyond them is reported as incomplete instead of silently dropped. +const OPEN_PR_PAGES = 20; +const THREAD_PAGES = 10; +const MERGED_PAGES = 10; +const SEARCH_PAGES = 5; + +/** Run a GraphQL query. Partial errors next to usable data go to `onError` instead of being dropped. */ +async function graphql(query, vars, onError) { + const args = ["api", "graphql", "-f", `query=${query}`]; + for (const [k, v] of Object.entries(vars)) { + if (v === null || v === undefined) continue; + args.push(typeof v === "number" ? "-F" : "-f", `${k}=${v}`); + } + // gh exits non-zero when a response carries errors, even alongside usable partial data (e.g. one missing epic). + const out = JSON.parse(await run("gh", args, 45000, { keepOutputOnError: true })); + if (!out.data) throw new Error(out.errors?.[0]?.message || out.message || "GitHub returned no data"); + for (const e of out.errors || []) onError(e.message || "GraphQL error", e.type); + return out.data; +} + +function requireRepository(data) { + if (!data.repository) throw new Error("repository not found or not accessible with the current gh login"); + return data.repository; +} + +const LABELS = "labels(first: 20) { totalCount nodes { name } }"; +const PAGE = "pageInfo { hasNextPage endCursor }"; + +const OPEN_PRS_QUERY = `query($owner: String!, $name: String!, $after: String) { + rateLimit { limit remaining resetAt } + repository(owner: $owner, name: $name) { + pullRequests(states: OPEN, first: 25, after: $after, orderBy: { field: UPDATED_AT, direction: DESC }) { + totalCount + ${PAGE} + nodes { + number title url isDraft headRefName headRefOid updatedAt mergeable mergeStateStatus reviewDecision + reviewThreads(first: 100) { ${PAGE} nodes { isResolved } } + reviews(last: 30) { nodes { state commit { oid } } } + commits(last: 1) { nodes { commit { statusCheckRollup { state contexts(first: 1) { totalCount } } } } } + } + } + } +}`; + +const THREADS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $after: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { reviewThreads(first: 100, after: $after) { ${PAGE} nodes { isResolved } } } + } +}`; + +const MERGED_QUERY = `query($q: String!, $after: String) { + search(query: $q, type: ISSUE, first: 100, after: $after) { + ${PAGE} + nodes { + ... on PullRequest { + number title url mergedAt headRefName body ${LABELS} + closingIssuesReferences(first: 5) { totalCount nodes { number title ${LABELS} parent { title ${LABELS} } } } + } + } + } +}`; + +const ISSUE_FIELDS = "... on Issue { number title url state body }"; +const DECISION_FIELDS = "... on Issue { number title url body } ... on PullRequest { number title url body }"; +const searchPageQuery = (fields) => `query($q: String!, $after: String) { + search(query: $q, type: ISSUE, first: 100, after: $after) { ${PAGE} nodes { ${fields} } } +}`; + +function mapOpenPr(node, threads) { + const rollup = node.commits?.nodes?.[0]?.commit?.statusCheckRollup; + const reviews = node.reviews?.nodes || []; + return { + number: node.number, + title: node.title, + url: node.url, + isDraft: node.isDraft, + headRefName: node.headRefName, + updatedAt: node.updatedAt, + mergeable: node.mergeable, + mergeStateStatus: node.mergeStateStatus, + reviewDecision: node.reviewDecision, + ci: ciFromRollup(rollup?.state), + checks: rollup?.contexts?.totalCount || 0, + unresolvedThreads: threads.unresolved, + threadsComplete: threads.complete, + headReviewed: reviews.some((r) => r.state !== "PENDING" && r.commit?.oid === node.headRefOid), + }; +} + +// More labels than loaded means a configured track label may be missing from attribution. +function labelsTruncated(labels) { + return (labels?.totalCount || 0) > (labels?.nodes || []).length; +} + +function names(labels) { + return (labels?.nodes || []).map((l) => l.name); +} + +async function fetchOpenPrs(repo, onError) { + const [owner, name] = repo.split("/"); + const nodes = []; + let rate = null; + let total = 0; + let after = null; + let more = false; + for (let page = 0; page < OPEN_PR_PAGES; page += 1) { + const data = await graphql(OPEN_PRS_QUERY, { owner, name, after }, onError); + rate ||= data.rateLimit; + const conn = requireRepository(data).pullRequests; + total = conn?.totalCount ?? 0; + nodes.push(...(conn?.nodes || []).filter((n) => n?.number)); + more = !!conn?.pageInfo?.hasNextPage; + if (!more) break; + after = conn.pageInfo.endCursor; + } + const prs = []; + for (const node of nodes) { + let unresolved = (node.reviewThreads?.nodes || []).filter((t) => !t.isResolved).length; + let info = node.reviewThreads?.pageInfo; + for (let page = 0; info?.hasNextPage && page < THREAD_PAGES; page += 1) { + const data = await graphql(THREADS_QUERY, { owner, name, number: node.number, after: info.endCursor }, onError); + const conn = requireRepository(data).pullRequest?.reviewThreads; + unresolved += (conn?.nodes || []).filter((t) => !t.isResolved).length; + info = conn?.pageInfo; + } + prs.push(mapOpenPr(node, { unresolved, complete: !info?.hasNextPage })); + } + return { prs, total, incomplete: more, rate }; +} + +async function searchAll(q, fields, first, onError) { + const query = searchPageQuery(fields); + const nodes = [...(first?.nodes || [])]; + let info = first?.pageInfo; + for (let page = 0; info?.hasNextPage && page < SEARCH_PAGES; page += 1) { + const data = await graphql(query, { q, after: info.endCursor }, onError); + nodes.push(...(data.search?.nodes || [])); + info = data.search?.pageInfo; + } + return { nodes: nodes.filter((n) => n?.number), complete: !info?.hasNextPage }; +} + +async function fetchMerged(repo, now, onError) { + // Search exactly the window the charts cover (local midnight six days ago), so no page is spent on older merges. + const since = new Date(mergeWindows(now).daySince).toISOString().replace(/\.\d{3}Z$/, "Z"); + const q = `repo:${repo} is:pr is:merged merged:>=${since}`; + const out = []; + let after = null; + let more = false; + for (let page = 0; page < MERGED_PAGES; page += 1) { + const data = await graphql(MERGED_QUERY, { q, after }, onError); + for (const node of data.search?.nodes || []) { + if (!node?.number) continue; + out.push({ + number: node.number, + title: node.title, + url: node.url, + mergedAt: node.mergedAt, + headRefName: node.headRefName, + body: node.body || "", + labels: names(node.labels), + // Closing references beyond the first five are counted, not loaded, and reported as partial attribution. + closingRefsMissed: Math.max(0, (node.closingIssuesReferences?.totalCount || 0) - (node.closingIssuesReferences?.nodes || []).length), + labelsTruncated: labelsTruncated(node.labels) + || (node.closingIssuesReferences?.nodes || []).some((r) => r && (labelsTruncated(r.labels) || labelsTruncated(r.parent?.labels))), + refs: (node.closingIssuesReferences?.nodes || []).filter((r) => r?.number).map((r) => ({ + number: r.number, + title: r.title, + labels: names(r.labels), + parent: r.parent ? { title: r.parent.title, labels: names(r.parent.labels) } : null, + })), + }); + } + more = !!data.search?.pageInfo?.hasNextPage; + if (!more) break; + after = data.search.pageInfo.endCursor; + } + return { items: out, incomplete: more }; +} + +// Body references that are not closing references ("part of #12") still say which issue a PR served. +const REF_BATCH = 80; +const REF_BATCHES = 4; + +/** Resolve body references in bounded batches. Returns how many referenced numbers were left unresolved. */ +async function addBodyRefs(repo, merged, onError) { + const wanted = new Map(); + for (const pr of merged) { + const known = new Set(pr.refs.map((r) => r.number)); + for (const n of referencedNumbers(pr)) if (!known.has(n)) wanted.set(n, true); + } + const all = [...wanted.keys()]; + const numbers = all.slice(0, REF_BATCH * REF_BATCHES); + if (!numbers.length) return { skipped: 0, truncated: 0 }; + const [owner, name] = repo.split("/"); + // "#123" in a body is only a guess at a reference, so numbers that do not exist are skipped quietly. + const quietMissing = (message, type) => { if (type !== "NOT_FOUND") onError(message, type); }; + const found = new Map(); + let truncated = 0; + for (let i = 0; i < numbers.length; i += REF_BATCH) { + const batch = numbers.slice(i, i + REF_BATCH); + const fields = batch.map((n) => `n${n}: issueOrPullRequest(number: ${n}) { ... on Issue { number title ${LABELS} parent { title ${LABELS} } } }`).join("\n"); + const data = await graphql(`query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`, { owner, name }, quietMissing); + const repoData = requireRepository(data); + for (const n of batch) { + const node = repoData[`n${n}`]; + if (!node?.number) continue; + if (labelsTruncated(node.labels) || labelsTruncated(node.parent?.labels)) truncated += 1; + found.set(n, { number: n, title: node.title, labels: names(node.labels), parent: node.parent ? { title: node.parent.title, labels: names(node.parent.labels) } : null }); + } + } + for (const pr of merged) { + const known = new Set(pr.refs.map((r) => r.number)); + for (const n of referencedNumbers(pr)) if (!known.has(n) && found.has(n)) pr.refs.push(found.get(n)); + } + return { skipped: all.length - numbers.length, truncated }; +} + +async function fetchBoardData(repo, board, onError) { + const tracks = board.tracks || []; + const epics = board.epics || []; + const empty = { trackIssues: {}, epics: [], decisionIssues: [], incompleteTracks: [], decisionsIncomplete: false }; + if (!tracks.length && !epics.length && !board.decisionLabel) return empty; + const [owner, name] = repo.split("/"); + const vars = { owner, name }; + const fields = []; + tracks.forEach((t, i) => { + vars[`t${i}`] = `repo:${repo} is:issue label:"${t.label}"`; + fields.push(`t${i}: search(query: $t${i}, type: ISSUE, first: 100) { ${PAGE} nodes { ${ISSUE_FIELDS} } }`); + }); + if (board.decisionLabel) { + vars.dq = `repo:${repo} is:open label:"${board.decisionLabel}"`; + fields.push(`dq: search(query: $dq, type: ISSUE, first: 100) { ${PAGE} nodes { ${DECISION_FIELDS} } }`); + } + const repoFields = epics.map((e) => `e${e.number}: issue(number: ${Number(e.number)}) { number title url state subIssuesSummary { total completed } }`).join("\n"); + const declared = Object.keys(vars).map((k) => `$${k}: String!`).join(", "); + const query = `query(${declared}) { ${fields.join("\n")} repository(owner: $owner, name: $name) { id ${repoFields} } }`; + const data = await graphql(query, vars, onError); + const repoData = requireRepository(data); + const trackIssues = Object.create(null); + const incompleteTracks = []; + for (const [i, t] of tracks.entries()) { + const result = await searchAll(vars[`t${i}`], ISSUE_FIELDS, data[`t${i}`], onError); + trackIssues[t.label] = result.nodes; + if (!result.complete) incompleteTracks.push(t.label); + } + const decisions = board.decisionLabel ? await searchAll(vars.dq, DECISION_FIELDS, data.dq, onError) : { nodes: [], complete: true }; + return { + trackIssues, + incompleteTracks, + decisionIssues: decisions.nodes, + decisionsIncomplete: !decisions.complete, + epics: epics.map((e) => { + const issue = repoData[`e${e.number}`]; + if (!issue) return { number: e.number, name: e.name || `#${e.number}`, group: e.group || "", missing: true, total: 0, completed: 0, state: "" }; + return { + number: issue.number, + name: e.name || issue.title, + group: e.group || "", + url: issue.url, + state: issue.state, + total: issue.subIssuesSummary?.total || 0, + completed: issue.subIssuesSummary?.completed || 0, + }; + }), + }; +} + +const WRITE_ROLES = new Set(["admin", "write"]); + +const MAX_AUTHOR_CHECKS = 50; + +async function fetchLockComments(repo, issue, now, board, onError) { + const since = new Date(now - 48 * HOUR).toISOString(); + const out = await run("gh", ["api", "--paginate", `repos/${repo}/issues/${Number(issue)}/comments?per_page=100&since=${since}`, + "--jq", ".[] | {createdAt: .created_at, url: .html_url, author: (.user.login // \"\"), line: (.body | split(\"\\n\")[0] | .[0:300])}"]); + // Only lock, reserve and release lines matter; other discussion on the issue is dropped before any lookups. + const comments = out.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l)) + .filter((c) => parseLockLine(c.line, board.lockPrefixes)); + if ((board.lockAuthors || []).length) return comments; + // Without an allowlist, look up each lock author's actual repository permission (needs push access to the repo). + // Authors of the newest lock lines are checked first; anyone left unchecked stays null (unverified). + const authors = [...new Set([...comments].reverse().map((c) => c.author).filter(Boolean))]; + const access = new Map(); + for (const author of authors.slice(0, MAX_AUTHOR_CHECKS)) { + try { + // `.permission` is the base access level (admin, write, read, none); `.role_name` can be a custom role name. + const role = (await run("gh", ["api", `repos/${repo}/collaborators/${encodeURIComponent(author)}/permission`, "--jq", ".permission"], 15000)).trim(); + access.set(author, WRITE_ROLES.has(role)); + } catch (error) { + access.set(author, null); + onError(`could not verify ${author}'s permission (${error.message}); set lockAuthors to trust specific accounts`); + } + } + return comments.map((c) => ({ ...c, writeAccess: access.has(c.author) ? access.get(c.author) : null })); +} + +async function fetchLocal(settings) { + const out = { freePct: null, swapUsedMb: null, swapTotalMb: null, heavy: 0 }; + if (process.platform === "darwin") { + try { + const m = (await run("memory_pressure", [], 8000)).match(/free percentage: (\d+)%/); + if (m) out.freePct = Number(m[1]); + } catch { + // memory_pressure is optional. + } + try { + const swap = await run("sysctl", ["-n", "vm.swapusage"], 5000); + const used = swap.match(/used = ([\d.]+)M/); + const total = swap.match(/total = ([\d.]+)M/); + if (used) out.swapUsedMb = Math.round(Number(used[1])); + if (total) out.swapTotalMb = Math.round(Number(total[1])); + } catch { + // vm.swapusage is optional. + } + } + if (out.freePct === null) out.freePct = Math.round((os.freemem() / os.totalmem()) * 100); + if (settings.heavyPattern && safeRegex(settings.heavyPattern) && process.platform !== "win32") { + try { + // Command lines go through the same length cap and deadline-bound worker as titles and branches. + const lines = (await run("ps", ["-axo", "command="], 5000)).split("\n").map((l) => l.trim()).filter(Boolean).map((l) => l.slice(0, MAX_SUBJECT)); + const matcher = await evaluatePatterns([settings.heavyPattern], lines); + out.heavy = lines.filter((line) => matcher.test(settings.heavyPattern, line)).length; + if (matcher.skipped.length) out.patternSkipped = true; + } catch { + // ps failure leaves heavy at 0. + } + } + return out; +} + +/** + * Evaluate every configured session and track pattern against the PRs in `raw` in a worker under a deadline, + * so buildState never runs a configured regex on the main thread. Patterns that time out are reported. + */ +export async function prepareMatcher(raw, board) { + const sessions = board.sessions || []; + const patterns = [ + ...sessions.flatMap((s) => [...(s.branchPatterns || []), ...(s.titlePatterns || [])]), + ...(board.tracks || []).map((t) => t.titlePattern).filter(Boolean), + ]; + const prs = [...(raw.openPrs || []), ...(raw.merged || [])]; + const subjects = prs.flatMap((pr) => [pr.headRefName, pr.title, ...(pr.refs || []).flatMap((r) => [r.title, r.parent?.title])]).filter(Boolean); + return evaluatePatterns(patterns, subjects); +} + +/** Fetch everything the board shows. Each source fails independently and is reported as a warning. */ +// Remembered once gh is found and signed in, so a working setup costs no extra calls per refresh. +let ghReady = false; + +/** Why gh cannot be used ("gh_missing" or "gh_signed_out"), or null when it is ready. */ +export async function checkGh() { + if (ghReady) return null; + try { + await run("gh", ["--version"], 10000); + } catch { + return "gh_missing"; + } + try { + await run("gh", ["auth", "status", "--active", "--hostname", "github.com"], 15000); + } catch { + return "gh_signed_out"; + } + ghReady = true; + return null; +} + +export async function collectRaw(repo, board, now = Date.now()) { + // Without a usable gh, show one setup message instead of the same failure from every data source. + const setup = await checkGh(); + if (setup) { + return { repo, setup, openPrs: [], openPrTotal: 0, merged: [], lockComments: [], rate: null, local: null, errors: [], trackIssues: {}, epics: [], decisionIssues: [], incomplete: {} }; + } + const errors = []; + const seen = new Set(); + const report = (source) => (message) => { + const key = `${source}\n${message}`; + if (seen.has(key) || errors.length >= 10) return; + seen.add(key); + errors.push({ source, message: String(message).slice(0, 240) }); + }; + const safe = async (source, fn, fallback) => { + try { + return await fn(report(source)); + } catch (error) { + // The GraphQL error that caused the failure is usually reported already; add the failure only if not. + if (!errors.some((e) => e.source === source)) report(source)(error.message); + return fallback; + } + }; + const emptyBoard = { trackIssues: {}, epics: [], decisionIssues: [], incompleteTracks: [], decisionsIncomplete: false }; + const [open, merged, boardData, lockComments, local] = await Promise.all([ + safe("open pull requests", (onError) => fetchOpenPrs(repo, onError), null), + safe("merged pull requests", (onError) => fetchMerged(repo, now, onError), { items: [], incomplete: false }), + safe("tracks, epics and decisions", (onError) => fetchBoardData(repo, board, onError), emptyBoard), + board.coordinationIssue > 0 ? safe("merge lock comments", (onError) => fetchLockComments(repo, board.coordinationIssue, now, board, onError), []) : Promise.resolve([]), + board.localResources?.enabled ? fetchLocal(board.localResources) : Promise.resolve(null), + ]); + const refs = (board.tracks || []).length && merged.items.length + ? await safe("referenced issues", (onError) => addBodyRefs(repo, merged.items, onError), { skipped: 0, truncated: 0 }) + : { skipped: 0, truncated: 0 }; + return { + repo, + openPrs: open?.prs || [], + openPrTotal: open?.total ?? 0, + merged: merged.items, + lockComments, + rate: open?.rate ? { remaining: open.rate.remaining, limit: open.rate.limit, resetAt: open.rate.resetAt } : null, + local, + errors, + trackIssues: boardData.trackIssues, + epics: boardData.epics, + decisionIssues: boardData.decisionIssues, + incomplete: { + // A failed open-PR fetch is also incomplete: nothing may be treated as closed on its account. + openPrs: !open || open.incomplete, + merged: merged.incomplete, + tracks: boardData.incompleteTracks, + decisions: boardData.decisionsIncomplete, + attribution: (board.tracks || []).length + ? { truncatedLabels: merged.items.filter((m) => m.labelsTruncated).length + (refs?.truncated || 0), skippedRefs: (refs?.skipped || 0) + merged.items.reduce((a, m) => a + (m.closingRefsMissed || 0), 0) } + : {}, + }, + }; +} diff --git a/extensions/agent-session-board/lib/demo.mjs b/extensions/agent-session-board/lib/demo.mjs new file mode 100644 index 0000000000..214ec76066 --- /dev/null +++ b/extensions/agent-session-board/lib/demo.mjs @@ -0,0 +1,148 @@ +// Fictional data for demos and the preview image. Nothing here refers to a real repository or account. +const HOUR = 3600 * 1000; +const MIN = 60 * 1000; + +export const DEMO_REPO = "example-org/demo-app"; + +export function demoBoard() { + return { + sessions: [ + { id: "api", name: "API worker", note: "Pagination and rate-limit handling", branchPatterns: ["^api/"], titlePatterns: [], prs: [] }, + { id: "web", name: "Web UI worker", note: "Settings page redesign", branchPatterns: ["^web/"], titlePatterns: [], prs: [] }, + { id: "docs", name: "Docs worker", note: "", branchPatterns: ["^docs/"], titlePatterns: ["^docs:"], prs: [] }, + { id: "infra", name: "Infra worker", note: "CI cache migration", branchPatterns: ["^infra/"], titlePatterns: [], prs: [] }, + ], + tracks: [ + { label: "milestone: alpha", name: "Alpha", note: "Core API and login", group: "Milestones" }, + { label: "milestone: beta", name: "Beta", note: "Settings and billing", group: "Milestones" }, + { label: "area: docs", name: "Docs", note: "", group: "Areas", titlePattern: "^docs:" }, + ], + epics: [ + { number: 10, name: "Alpha release", group: "" }, + { number: 11, name: "Beta release", group: "" }, + ], + decisionLabel: "needs-decision", + coordinationIssue: 1, + localResources: { enabled: true, heavyPattern: "test-runner", maxHeavy: 3 }, + decisions: [ + { + id: "cache-strategy", + title: "Which cache should the API worker use for session tokens?", + detail: "Both pass the load test; in-memory is simpler, the shared cache survives restarts.", + url: "", + options: ["In-memory", "Shared cache"], + }, + { + id: "beta-scope", + title: "Ship billing in Beta or move it to the next milestone?", + detail: "Billing has 3 open issues and one failing integration test.", + url: "", + options: ["Keep in Beta", "Move to next milestone"], + }, + ], + }; +} + +// Demo items carry no links so nothing points at a real page. +function url() { + return ""; +} + +function iso(ms) { + return new Date(ms).toISOString(); +} + +export function demoRaw(now = Date.now()) { + const at = (minutesAgo) => iso(now - minutesAgo * MIN); + const open = (number, title, headRefName, minutesAgo, extra) => ({ + number, title, url: url("pull", number), headRefName, updatedAt: at(minutesAgo), + isDraft: false, mergeable: "MERGEABLE", mergeStateStatus: "CLEAN", reviewDecision: null, ci: "passed", checks: 6, + unresolvedThreads: 0, headReviewed: true, ...extra, + }); + const openPrs = [ + open(141, "Add cursor pagination to list endpoints", "api/pagination", 12, { reviewDecision: "APPROVED" }), + open(143, "Retry on secondary rate limits", "api/rate-limit", 25, { ci: "running", checks: 6 }), + open(138, "Settings page layout", "web/settings-layout", 40, { unresolvedThreads: 2 }), + open(144, "Billing form validation", "web/billing-form", 18, { headReviewed: false }), + open(139, "Theme tokens for dark mode", "web/theme-tokens", 200, { mergeable: "CONFLICTING" }), + open(145, "docs: getting started rewrite", "docs/getting-started", 130, { isDraft: true, ci: "none", checks: 0, headReviewed: false }), + open(142, "Move CI cache to new storage", "infra/ci-cache", 15, { ci: "failed" }), + open(146, "Fix flaky login test", "fix/login-flake", 1600, { reviewDecision: "REVIEW_REQUIRED", headReviewed: false }), + ]; + + const alpha = { labels: ["milestone: alpha"] }; + const beta = { labels: ["milestone: beta"] }; + const plan = [ + // [number, title, branch, minutesAgo, own labels, refs] + [120, "Login endpoint", "api/login", 6 * 24 * 60 + 200, ["milestone: alpha"], []], + [121, "Session tokens", "api/tokens", 5 * 24 * 60 + 400, [], [{ number: 30, title: "Token storage", ...alpha, parent: null }]], + [122, "Password reset email", "api/reset", 5 * 24 * 60 + 90, [], [{ number: 31, title: "Reset flow", labels: [], parent: { title: "Alpha release", ...alpha } }]], + [123, "docs: API reference", "docs/api-ref", 4 * 24 * 60 + 300, [], []], + [124, "Settings skeleton", "web/settings", 4 * 24 * 60 + 100, ["milestone: beta"], []], + [125, "Health check endpoint", "api/health", 3 * 24 * 60 + 500, [], [{ number: 32, title: "Health checks", ...alpha, parent: null }]], + [126, "Profile form", "web/profile", 3 * 24 * 60 + 200, [], [{ number: 40, title: "Profile settings", ...beta, parent: null }]], + [127, "Bump runner image", "infra/runner", 3 * 24 * 60 + 60, [], []], + [128, "Billing plan picker", "web/plans", 2 * 24 * 60 + 400, [], [{ number: 41, title: "Plans", labels: [], parent: { title: "Beta release", ...beta } }]], + [129, "docs: auth guide", "docs/auth", 2 * 24 * 60 + 100, ["area: docs"], []], + [130, "Audit log endpoint", "api/audit", 30 * 60, ["milestone: alpha"], []], + [131, "Invoice download", "web/invoice", 28 * 60, ["milestone: beta"], []], + [132, "Error envelope", "api/errors", 22 * 60, ["milestone: alpha"], []], + [133, "Notification settings", "web/notify", 19 * 60, [], [{ number: 42, title: "Notifications", ...beta, parent: null }]], + [134, "docs: rate limits", "docs/rate-limits", 15 * 60, [], []], + [135, "Request IDs in logs", "api/request-id", 11 * 60, [], [{ number: 33, title: "Observability", labels: [], parent: { title: "Alpha release", ...alpha } }]], + [136, "Cache Docker layers", "infra/docker-cache", 8 * 60, [], []], + [137, "Billing address form", "web/address", 5 * 60, ["milestone: beta"], []], + [140, "Token refresh", "api/refresh", 3 * 60, ["milestone: alpha"], []], + [147, "Dark mode toggle", "web/dark-toggle", 70, ["milestone: beta"], []], + [148, "docs: changelog", "docs/changelog", 150, [], []], + ]; + const merged = plan.map(([number, title, headRefName, minutesAgo, labels, refs]) => ({ + number, title, url: url("pull", number), headRefName, mergedAt: at(minutesAgo), body: "", labels, refs, + })); + + const issue = (number, title, state, body = "") => ({ number, title, url: url("issues", number), state, body }); + const trackIssues = { + "milestone: alpha": [ + issue(30, "Token storage", "CLOSED"), + issue(31, "Reset flow", "CLOSED"), + issue(32, "Health checks", "CLOSED"), + issue(33, "Observability", "OPEN", "- [x] request ids\n- [x] structured logs\n- [ ] trace export"), + issue(34, "Pagination", "OPEN", "- [x] cursor\n- [ ] page size limits"), + ], + "milestone: beta": [ + issue(40, "Profile settings", "CLOSED"), + issue(41, "Plans", "OPEN", "- [x] picker\n- [ ] proration\n- [ ] downgrade"), + issue(42, "Notifications", "CLOSED"), + issue(43, "Billing form", "OPEN", "- [ ] validation\n- [ ] address"), + issue(44, "Dark mode", "OPEN"), + ], + "area: docs": [ + issue(50, "API reference", "CLOSED"), + issue(51, "Auth guide", "CLOSED"), + issue(52, "Changelog", "CLOSED"), + ], + }; + + return { + repo: DEMO_REPO, + demo: true, + openPrs, + openPrTotal: openPrs.length, + merged, + lockComments: [ + { createdAt: at(90), url: url(), author: "web-worker", writeAccess: true, line: "merge reserve: #138" }, + { createdAt: at(50), url: url(), author: "web-worker", writeAccess: true, line: "merge lock release: #137" }, + { createdAt: at(20), url: url(), author: "api-worker", writeAccess: true, line: `merge lock: #141 until ${iso(now + 25 * MIN)}` }, + { createdAt: at(10), url: url(), author: "web-worker", writeAccess: true, line: "merge reserve: #144" }, + ], + trackIssues, + epics: [ + { number: 10, name: "Alpha release", group: "", url: url("issues", 10), state: "OPEN", total: 9, completed: 7 }, + { number: 11, name: "Beta release", group: "", url: url("issues", 11), state: "OPEN", total: 12, completed: 5 }, + ], + decisionIssues: [{ number: 150, title: "Pick the default page size for list endpoints", url: url("issues", 150) }], + rate: { remaining: 4210, limit: 5000, resetAt: iso(now + 40 * MIN) }, + local: { freePct: 41, swapUsedMb: 2150, swapTotalMb: 4096, heavy: 2 }, + errors: [], + }; +} diff --git a/extensions/agent-session-board/lib/exec.mjs b/extensions/agent-session-board/lib/exec.mjs new file mode 100644 index 0000000000..9b3d48ff28 --- /dev/null +++ b/extensions/agent-session-board/lib/exec.mjs @@ -0,0 +1,43 @@ +// The only place this extension starts processes. Commands are a fixed allowlist, run without a shell, +// with arguments passed as an array, a timeout and an output cap. Nothing else can be executed. +import { execFile } from "node:child_process"; + +// gh reads GitHub through the user's own login; the rest are optional local-resource checks. +const ALLOWED = new Set(["gh", "ps", "sysctl", "memory_pressure"]); +const MAX_OUTPUT = 64 * 1024 * 1024; + +export class ExecError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +/** + * Run an allowlisted command and resolve with its stdout. + * `keepOutputOnError` resolves with stdout when a failing command still printed JSON (gh does this for partial + * GraphQL results). Rejects with ExecError code "not_allowed", "not_installed" or "failed". + */ +export function run(cmd, args, timeoutMs = 45000, { keepOutputOnError = false } = {}) { + if (!ALLOWED.has(cmd)) return Promise.reject(new ExecError("not_allowed", `${cmd} is not an allowed command`)); + if (!Array.isArray(args) || args.some((a) => typeof a !== "string")) { + return Promise.reject(new ExecError("not_allowed", "arguments must be an array of strings")); + } + return new Promise((resolve, reject) => { + execFile(cmd, args, { timeout: timeoutMs, maxBuffer: MAX_OUTPUT, windowsHide: true, shell: false }, (error, stdout, stderr) => { + if (error && keepOutputOnError && stdout && stdout.trim().startsWith("{")) { + resolve(stdout); + return; + } + if (error) { + if (error.code === "ENOENT") { + reject(new ExecError("not_installed", `${cmd} is not installed or not on PATH`)); + return; + } + reject(new ExecError("failed", (stderr || error.message).trim().split("\n")[0].slice(0, 240))); + return; + } + resolve(stdout); + }); + }); +} diff --git a/extensions/agent-session-board/lib/match-worker.mjs b/extensions/agent-session-board/lib/match-worker.mjs new file mode 100644 index 0000000000..cc3e8d306b --- /dev/null +++ b/extensions/agent-session-board/lib/match-worker.mjs @@ -0,0 +1,18 @@ +// Runs configured patterns against subjects off the main thread, one pattern at a time, reporting progress +// so the parent can terminate this worker if a single pattern runs past its deadline. +import { parentPort, workerData } from "node:worker_threads"; + +const { patterns, subjects, start } = workerData; +for (let pi = start; pi < patterns.length; pi += 1) { + parentPort.postMessage({ type: "start", pi }); + const hits = []; + let re = null; + try { + re = new RegExp(patterns[pi], "i"); + } catch { + re = null; + } + if (re) for (let si = 0; si < subjects.length; si += 1) if (re.test(subjects[si])) hits.push(si); + parentPort.postMessage({ type: "done", pi, hits }); +} +parentPort.postMessage({ type: "end" }); diff --git a/extensions/agent-session-board/lib/page.mjs b/extensions/agent-session-board/lib/page.mjs new file mode 100644 index 0000000000..7b026e9bb6 --- /dev/null +++ b/extensions/agent-session-board/lib/page.mjs @@ -0,0 +1,616 @@ +// The board page. Values are inserted with textContent / DOM APIs only, never as HTML. +export const PAGE_HTML = String.raw` + + + + +Agent Session Board + + + + +
+

Agent Session Board

+ +
+ + +
+

+
+ +
+
+

Waiting on you

+
    +
    +

    Progress by track

    +
    +
    +

    Warnings

      +

      Merge lock

      +

      Merges, last 7 days (daily)

      Data table
      +
      +

      Sessions

      +

      Merges, last 24 hours (hourly)

      Data table
      +

      Recent merges (7 days)

        +
        + + +`; diff --git a/extensions/agent-session-board/lib/pattern.mjs b/extensions/agent-session-board/lib/pattern.mjs new file mode 100644 index 0000000000..1297326119 --- /dev/null +++ b/extensions/agent-session-board/lib/pattern.mjs @@ -0,0 +1,155 @@ +// Configured patterns run against contributor-controlled PR titles and branch names, so they must not be +// able to block the extension. Two layers: patterns with the constructs that cause exponential matching are +// rejected up front, and every pattern actually runs in a worker thread under a per-pattern deadline +// (evaluatePatterns), so even polynomial backtracking such as \d*\d*\d*x cannot stall the board. +import { Worker } from "node:worker_threads"; + +export const MAX_SUBJECT = 256; + +/** + * Why a pattern may backtrack exponentially, or null if it is safe: + * - backreferences; + * - a repeating quantifier (`*`, `+`, `{n}` with n > 1, `{n,}`, `{n,m}` with m > 1) applied to a group + * that itself contains a quantifier or an alternation, such as `(a+)+`, `(a+){20}` or `(a|aa)*`. + */ +export function unsafePatternReason(source) { + const stack = [{ inner: false }]; + let closed = null; + for (let i = 0; i < source.length; i += 1) { + const c = source[i]; + if (c === "\\") { + const next = source[i + 1] || ""; + if (/[1-9]/.test(next) || next === "k") return "backreferences are not allowed"; + i += 1; + closed = null; + continue; + } + if (c === "[") { + i += 1; + // In JavaScript (without the u/v flags) a "]" right after "[" or "[^" closes the class, so it is not skipped. + if (source[i] === "^") i += 1; + while (i < source.length && source[i] !== "]") i += source[i] === "\\" ? 2 : 1; + closed = null; + continue; + } + if (c === "(") { + stack.push({ inner: false }); + if (source[i + 1] === "?") { + // Skip group modifiers: (?: (?= (?! (?<= (? + i += 2; + if (source[i] === "<" && source[i + 1] !== "=" && source[i + 1] !== "!") { + while (i < source.length && source[i] !== ">") i += 1; + } else if (source[i] === "<") { + i += 1; + } + } + closed = null; + continue; + } + if (c === ")") { + const group = stack.length > 1 ? stack.pop() : { inner: false }; + // Whatever is inside this group is also inside its parent. + if (group.inner) stack[stack.length - 1].inner = true; + closed = group; + continue; + } + if (c === "|") { + stack[stack.length - 1].inner = true; + closed = null; + continue; + } + const brace = c === "{" ? source.slice(i).match(/^\{(\d+)(,(\d*))?\}/) : null; + if (c === "*" || c === "+" || c === "?" || brace) { + // {n} with n > 1 repeats too: (a+){20} backtracks as badly as (a+)+. + const repeats = c === "*" || c === "+" + || (brace && (brace[2] === undefined ? Number(brace[1]) > 1 : brace[3] === "" || Number(brace[3]) > 1)); + if (repeats && closed && closed.inner) return "a repeated group must not contain another quantifier or an alternation"; + stack[stack.length - 1].inner = true; + if (brace) i += brace[0].length - 1; + if (source[i + 1] === "?") i += 1; + closed = null; + continue; + } + closed = null; + } + return null; +} + +const cache = new Map(); + +/** Compile a configured pattern case-insensitively; invalid or unsafe patterns compile to null and never match. */ +export function safeRegex(source) { + if (!cache.has(source)) { + let compiled = null; + if (typeof source === "string" && source.length <= 200 && !unsafePatternReason(source)) { + try { + compiled = new RegExp(source, "i"); + } catch { + compiled = null; + } + } + cache.set(source, compiled); + } + return cache.get(source); +} + +export function testPattern(source, subject) { + const re = safeRegex(source); + return !!re && re.test(String(subject || "").slice(0, MAX_SUBJECT)); +} + +const PATTERN_DEADLINE_MS = 500; + +/** + * Test every pattern against every subject in a worker thread. A pattern that runs past its deadline is + * skipped (and reported) and the worker restarts with the next pattern. + * Returns { test(pattern, subject) => boolean, skipped: [pattern] }. + */ +export async function evaluatePatterns(patternList, subjectList, deadlineMs = PATTERN_DEADLINE_MS) { + const patterns = [...new Set(patternList)].filter((p) => safeRegex(p)); + const subjects = [...new Set(subjectList.map((x) => String(x || "").slice(0, MAX_SUBJECT)))]; + const hits = new Set(); + const skipped = []; + const subjectIndex = new Map(subjects.map((x, i) => [x, i])); + const key = (pi, si) => `${pi}:${si}`; + let start = 0; + while (patterns.length && subjects.length && start < patterns.length) { + start = await new Promise((resolve, reject) => { + const worker = new Worker(new URL("./match-worker.mjs", import.meta.url), { workerData: { patterns, subjects, start } }); + let current = start; + let timer = null; + const arm = () => { + clearTimeout(timer); + timer = setTimeout(() => { + skipped.push(patterns[current]); + worker.terminate().finally(() => resolve(current + 1)); + }, deadlineMs); + }; + arm(); + worker.on("message", (m) => { + if (m.type === "start") { + current = m.pi; + arm(); + } else if (m.type === "done") { + for (const si of m.hits) hits.add(key(m.pi, si)); + } else if (m.type === "end") { + clearTimeout(timer); + worker.terminate().finally(() => resolve(patterns.length)); + } + }); + worker.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + }); + } + const patternIndex = new Map(patterns.map((p, i) => [p, i])); + return { + skipped, + test(pattern, subject) { + const pi = patternIndex.get(pattern); + const si = subjectIndex.get(String(subject || "").slice(0, MAX_SUBJECT)); + return pi !== undefined && si !== undefined && hits.has(key(pi, si)); + }, + }; +} diff --git a/extensions/agent-session-board/lib/server.mjs b/extensions/agent-session-board/lib/server.mjs new file mode 100644 index 0000000000..f48b5b7c34 --- /dev/null +++ b/extensions/agent-session-board/lib/server.mjs @@ -0,0 +1,98 @@ +import http from "node:http"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { PAGE_HTML } from "./page.mjs"; + +const SECURITY_HEADERS = { + "cache-control": "no-store", + "x-content-type-options": "nosniff", + "referrer-policy": "no-referrer", + // The Copilot host loads canvases as a top-level webview, so framing is never legitimate. + "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", + "x-frame-options": "DENY", +}; + +function send(res, status, type, body) { + res.writeHead(status, { "content-type": type, ...SECURITY_HEADERS }); + res.end(body); +} + +function readJsonBody(req, limit = 8192) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on("data", (chunk) => { + size += chunk.length; + if (size > limit) { + reject(new Error("body too large")); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on("end", () => { + try { + resolve(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + } catch { + reject(new Error("invalid JSON")); + } + }); + req.on("error", reject); + }); +} + +/** + * Serve one board on 127.0.0.1 with an ephemeral port. + * Every route sits under a random per-panel key that only the canvas host receives (from open()), + * so other local users and web pages cannot read the board or post answers. The key unlocks this + * one local board only; it is not a GitHub credential. The Host header must also name this server + * (blocks DNS rebinding) and answers must be same-origin JSON. + * `handlers.state(force)` returns the view model, `handlers.answer(body)` stores an answer. + */ +export function startServer(handlers) { + const key = randomBytes(24).toString("base64url"); + const prefix = Buffer.from(`/${key}/`); + const authorized = (pathname) => { + const got = Buffer.from(pathname.slice(0, prefix.length)); + return got.length === prefix.length && timingSafeEqual(got, prefix); + }; + return new Promise((resolve, reject) => { + let port = 0; + const server = http.createServer(async (req, res) => { + try { + const allowedHosts = [`127.0.0.1:${port}`, `localhost:${port}`]; + if (!allowedHosts.includes(req.headers.host || "")) return send(res, 403, "text/plain; charset=utf-8", "Forbidden"); + const url = new URL(req.url, `http://127.0.0.1:${port}`); + if (!authorized(url.pathname)) return send(res, 404, "text/plain; charset=utf-8", "Not found"); + const route = url.pathname.slice(prefix.length - 1); + if (req.method === "GET" && (route === "/" || route === "/index.html")) { + return send(res, 200, "text/html; charset=utf-8", PAGE_HTML); + } + if (req.method === "GET" && route === "/api/state") { + const state = await handlers.state(url.searchParams.get("force") === "1"); + return send(res, 200, "application/json; charset=utf-8", JSON.stringify(state)); + } + if (req.method === "POST" && route === "/api/answer") { + const origin = req.headers.origin; + const site = req.headers["sec-fetch-site"]; + if ((origin && !allowedHosts.some((h) => origin === `http://${h}`)) || (site && site !== "same-origin")) { + return send(res, 403, "text/plain; charset=utf-8", "Cross-origin request refused"); + } + if (!String(req.headers["content-type"] || "").startsWith("application/json")) { + return send(res, 415, "text/plain; charset=utf-8", "application/json required"); + } + const result = await handlers.answer(await readJsonBody(req)); + return send(res, result.status, "application/json; charset=utf-8", JSON.stringify(result.body)); + } + return send(res, 404, "text/plain; charset=utf-8", "Not found"); + } catch (error) { + handlers.log?.(`request failed: ${error.message}`); + return send(res, 500, "text/plain; charset=utf-8", error.message); + } + }); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + port = server.address().port; + resolve({ server, url: `http://127.0.0.1:${port}/${key}/` }); + }); + }); +} diff --git a/extensions/agent-session-board/lib/store.mjs b/extensions/agent-session-board/lib/store.mjs new file mode 100644 index 0000000000..d4e62383bf --- /dev/null +++ b/extensions/agent-session-board/lib/store.mjs @@ -0,0 +1,414 @@ +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { unsafePatternReason } from "./pattern.mjs"; + +export const CANVAS_ID = "agent-session-board"; +export const FORMAT = "agent-session-board/board"; +export const VERSION = 1; +export const DEMO_KEY = "demo"; + +export class StoreError extends Error { + constructor(code, message) { + super(message); + this.code = code; + } +} + +function copilotHome() { + const env = process.env.COPILOT_HOME; + return env && env.length > 0 ? env : path.join(os.homedir(), ".copilot"); +} + +export function dataDir() { + return path.join(copilotHome(), "extension-data", CANVAS_ID); +} + +// One file per repository keeps boards independent; "owner__name" cannot collide with the demo key. +export function boardFileName(key) { + if (key === DEMO_KEY) return "demo.json"; + const [owner, name, extra] = String(key).toLowerCase().split("/"); + if (extra !== undefined || !owner || !name || !/^[a-z0-9-]+$/.test(owner) || !/^[a-z0-9_.-]+$/.test(name) || /^\.+$/.test(name)) { + throw new StoreError("invalid_repo", `Cannot derive a board file name from ${JSON.stringify(key)}.`); + } + return `${owner}__${name}.json`; +} + +export function defaultBoard() { + return { + sessions: [], + tracks: [], + epics: [], + decisionLabel: "", + coordinationIssue: 0, + lockPrefixes: { lock: "merge lock:", reserve: "merge reserve:", release: "merge lock release:" }, + lockAuthors: [], + localResources: { enabled: false, heavyPattern: "", maxHeavy: 2 }, + idleMinutes: 90, + language: "en", + decisions: [], + answers: {}, + }; +} + +function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +// Refuses anything this extension did not write, so a foreign or newer file is never overwritten. +export function validateDocument(data, where = "board file") { + if (!isObject(data) || data.format !== FORMAT) { + throw new StoreError("store_unrecognized", `Unrecognized data in ${where}; leaving it untouched.`); + } + if (data.version !== VERSION) { + throw new StoreError("store_version", `Unsupported version ${JSON.stringify(data.version)} in ${where}.`); + } + const board = data.board; + if (!isObject(board)) throw new StoreError("store_corrupt", `${where} has no board object.`); + for (const key of ["sessions", "tracks", "epics", "decisions", "lockAuthors"]) { + if (board[key] !== undefined && !Array.isArray(board[key])) { + throw new StoreError("store_corrupt", `${where}: board.${key} must be an array.`); + } + } + for (const key of ["answers", "lockPrefixes", "localResources"]) { + if (board[key] !== undefined && !isObject(board[key])) { + throw new StoreError("store_corrupt", `${where}: board.${key} must be an object.`); + } + } + return data; +} + +export function parseDocument(raw, where) { + let data; + try { + data = JSON.parse(raw); + } catch { + throw new StoreError("store_corrupt", `${where} is not valid JSON; leaving it untouched.`); + } + return validateDocument(data, where); +} + +function mergeBoard(stored) { + const base = defaultBoard(); + return { + ...base, + ...stored, + lockPrefixes: { ...base.lockPrefixes, ...(stored?.lockPrefixes || {}) }, + localResources: { ...base.localResources, ...(stored?.localResources || {}) }, + }; +} + +export async function getBoard(key) { + const file = path.join(dataDir(), boardFileName(key)); + const where = path.basename(file); + let raw; + try { + raw = await fs.readFile(file, "utf8"); + } catch (error) { + if (error.code === "ENOENT") return defaultBoard(); + throw new StoreError("store_read", `Could not read ${where}: ${error.message}`); + } + return mergeBoard(parseDocument(raw, where).board); +} + +async function writeBoard(key, board) { + const dir = dataDir(); + const file = path.join(dir, boardFileName(key)); + const doc = validateDocument({ format: FORMAT, version: VERSION, key, updatedAt: new Date().toISOString(), board }, path.basename(file)); + await fs.mkdir(dir, { recursive: true }); + const tmp = `${file}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`; + try { + await fs.writeFile(tmp, JSON.stringify(doc, null, 2), { encoding: "utf8", mode: 0o600 }); + await fs.rename(tmp, file); + } catch (error) { + await fs.rm(tmp, { force: true }).catch(() => {}); + throw new StoreError("store_write", `Could not write ${path.basename(file)}: ${error.message}`); + } +} + +const LOCK_STALE_MS = 5 * 60 * 1000; +const LOCK_WAIT_MS = 10 * 1000; +const TAKEOVER_STALE_MS = 30 * 1000; + +async function readLock(lockPath) { + try { + const [text, stat] = await Promise.all([fs.readFile(lockPath, "utf8"), fs.stat(lockPath)]); + const [pid, token] = text.trim().split(" "); + return { pid: Number(pid), token: token || "", mtimeMs: stat.mtimeMs }; + } catch { + return null; + } +} + +function processAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error.code === "EPERM"; + } +} + +// A lock is abandoned when its writer process is gone, or when it is far older than any write takes. +// A lock without a token (written by an interrupted writer) has no owner to ask, so it gets a grace period. +function abandoned(lock) { + if (!lock.token) return Date.now() - lock.mtimeMs > TAKEOVER_STALE_MS; + return !processAlive(lock.pid) || Date.now() - lock.mtimeMs > LOCK_STALE_MS; +} + +/** + * Remove an abandoned lock. Takeovers are serialized through `.takeover`, and the lock is removed only + * if it still carries the token that was judged abandoned, so a live replacement lock is never deleted. + */ +async function takeOver(lockPath, judged) { + const takeoverPath = `${lockPath}.takeover`; + let handle; + try { + handle = await fs.open(takeoverPath, "wx", 0o600); + } catch (error) { + if (error.code !== "EEXIST") return false; + const stat = await fs.stat(takeoverPath).catch(() => null); + if (stat && Date.now() - stat.mtimeMs > TAKEOVER_STALE_MS) await fs.rm(takeoverPath, { force: true }); + return false; + } + try { + const current = await readLock(lockPath); + if (current && current.token === judged.token && current.mtimeMs === judged.mtimeMs) { + await fs.rm(lockPath, { force: true }); + return true; + } + return false; + } finally { + await handle.close().catch(() => {}); + await fs.rm(takeoverPath, { force: true }).catch(() => {}); + } +} + +/** + * Hold `.lock` for the whole read-modify-write. Several Copilot sessions (separate processes) + * may supervise the same repository, and an atomic rename alone would still let one overwrite another. + */ +async function withFileLock(key, fn) { + const dir = dataDir(); + await fs.mkdir(dir, { recursive: true }); + const lockPath = path.join(dir, `${boardFileName(key)}.lock`); + const token = crypto.randomBytes(12).toString("hex"); + const deadline = Date.now() + LOCK_WAIT_MS; + // The lock content is written to a private file first and then hard-linked into place. link() fails if the + // lock exists, so acquiring is atomic and a lock file is never visible empty. + const draft = `${lockPath}.${token}.tmp`; + await fs.writeFile(draft, `${process.pid} ${token}\n`, { mode: 0o600 }); + try { + for (;;) { + try { + await fs.link(draft, lockPath); + break; + } catch (error) { + if (error.code !== "EEXIST") throw new StoreError("store_lock", `Could not lock ${path.basename(lockPath)}: ${error.message}`); + const lock = await readLock(lockPath); + // Retry at once only after actually removing an abandoned lock; otherwise fall through to the deadline and backoff. + if (lock && abandoned(lock) && (await takeOver(lockPath, lock))) continue; + if (Date.now() > deadline) throw new StoreError("store_busy", `${path.basename(lockPath)} is held by another session; try again.`); + await new Promise((resolve) => setTimeout(resolve, 40 + Math.floor(Math.random() * 60))); + } + } + } finally { + await fs.rm(draft, { force: true }).catch(() => {}); + } + try { + return await fn(); + } finally { + // Release only our own lock, never one that replaced it. + const current = await readLock(lockPath); + if (current && current.token === token) await fs.rm(lockPath, { force: true }).catch(() => {}); + } +} + +// Within one process, updates also queue per board so they do not spin on each other's lock file. +const queues = new Map(); + +export function updateBoard(key, mutate) { + const previous = queues.get(key) || Promise.resolve(); + const next = previous.catch(() => {}).then(() => withFileLock(key, async () => { + const board = await getBoard(key); + const updated = mergeBoard(await mutate(board)); + await writeBoard(key, updated); + return updated; + })); + queues.set(key, next); + return next.finally(() => { + if (queues.get(key) === next) queues.delete(key); + }); +} + +// --------------------------------------------------------------------------- +// Input validation for configure_board, set_decisions and answers +// --------------------------------------------------------------------------- + +const ID_RE = /^[a-z0-9][a-z0-9-]{0,60}$/; + +function invalid(message) { + return new StoreError("invalid_input", message); +} + +function text(value, max) { + return typeof value === "string" ? value.trim().slice(0, max) : ""; +} + +function httpsUrl(value) { + return typeof value === "string" && /^https:\/\/github\.com\//.test(value) ? value.slice(0, 300) : ""; +} + +function pattern(value, where) { + if (value === undefined || value === "") return ""; + if (typeof value !== "string" || value.length > 200) throw invalid(`${where} must be a regular expression of at most 200 characters.`); + try { + new RegExp(value, "i"); + } catch { + throw invalid(`${where} is not a valid regular expression.`); + } + const unsafe = unsafePatternReason(value); + if (unsafe) throw invalid(`${where} could backtrack catastrophically: ${unsafe}.`); + return value; +} + +function labelName(value, where) { + if (typeof value !== "string" || !value.trim() || value.length > 50 || /["\n\r]/.test(value)) { + throw invalid(`${where} must be a single label name (1-50 characters, no quotes).`); + } + return value.trim(); +} + +function list(value, where, max) { + if (!Array.isArray(value)) throw invalid(`${where} must be an array.`); + if (value.length > max) throw invalid(`${where} accepts at most ${max} entries.`); + return value; +} + +function sanitizeSessions(value) { + const ids = new Set(); + return list(value, "sessions", 30).map((s, i) => { + if (!isObject(s) || typeof s.id !== "string" || !ID_RE.test(s.id)) throw invalid(`sessions[${i}].id must be a kebab-case id.`); + if (ids.has(s.id)) throw invalid(`Duplicate session id ${s.id}.`); + ids.add(s.id); + const patterns = (key) => list(s[key] ?? [], `sessions[${i}].${key}`, 20).map((p, j) => pattern(p, `sessions[${i}].${key}[${j}]`)).filter(Boolean); + return { + id: s.id, + name: text(s.name, 80) || s.id, + note: text(s.note, 200), + link: httpsUrl(s.link), + branchPatterns: patterns("branchPatterns"), + titlePatterns: patterns("titlePatterns"), + prs: list(s.prs ?? [], `sessions[${i}].prs`, 100).filter((n) => Number.isInteger(n) && n > 0), + }; + }); +} + +function sanitizeTracks(value) { + const labels = new Set(); + return list(value, "tracks", 30).map((t, i) => { + if (!isObject(t)) throw invalid(`tracks[${i}] must be an object.`); + const label = labelName(t.label, `tracks[${i}].label`); + if (labels.has(label)) throw invalid(`Duplicate track label ${label}.`); + labels.add(label); + return { label, name: text(t.name, 60), note: text(t.note, 160), group: text(t.group, 40), titlePattern: pattern(t.titlePattern, `tracks[${i}].titlePattern`) }; + }); +} + +function sanitizeEpics(value) { + return list(value, "epics", 40).map((e, i) => { + if (!isObject(e) || !Number.isInteger(e.number) || e.number < 1) throw invalid(`epics[${i}].number must be a positive integer.`); + return { number: e.number, name: text(e.name, 80), group: text(e.group, 40) }; + }); +} + +function sanitizeLockPrefixes(value, current) { + if (!isObject(value)) throw invalid("lockPrefixes must be an object."); + const next = { ...current }; + for (const key of ["lock", "reserve", "release"]) { + if (value[key] === undefined) continue; + if (typeof value[key] !== "string" || !value[key].trim() || value[key].length > 40 || /[\n\r]/.test(value[key])) { + throw invalid(`lockPrefixes.${key} must be 1-40 characters on one line.`); + } + next[key] = value[key].trim(); + } + const lowered = Object.values(next).map((p) => p.toLowerCase()); + if (new Set(lowered).size !== lowered.length) throw invalid("lockPrefixes must be distinct."); + return next; +} + +function sanitizeLocalResources(value, current) { + if (!isObject(value)) throw invalid("localResources must be an object."); + const next = { ...current }; + if (value.enabled !== undefined) { + if (typeof value.enabled !== "boolean") throw invalid("localResources.enabled must be a boolean."); + next.enabled = value.enabled; + } + if (value.heavyPattern !== undefined) next.heavyPattern = pattern(value.heavyPattern, "localResources.heavyPattern"); + if (value.maxHeavy !== undefined) { + if (!Number.isInteger(value.maxHeavy) || value.maxHeavy < 0 || value.maxHeavy > 64) throw invalid("localResources.maxHeavy must be an integer from 0 to 64."); + next.maxHeavy = value.maxHeavy; + } + return next; +} + +/** Validate a configure_board input against the current board and return the fields to change. */ +export function configPatch(input, board) { + if (!isObject(input)) throw invalid("Input must be an object."); + const patch = {}; + if (input.sessions !== undefined) patch.sessions = sanitizeSessions(input.sessions); + if (input.tracks !== undefined) patch.tracks = sanitizeTracks(input.tracks); + if (input.epics !== undefined) patch.epics = sanitizeEpics(input.epics); + if (input.decisionLabel !== undefined) patch.decisionLabel = input.decisionLabel === "" ? "" : labelName(input.decisionLabel, "decisionLabel"); + if (input.coordinationIssue !== undefined) { + if (!Number.isInteger(input.coordinationIssue) || input.coordinationIssue < 0) throw invalid("coordinationIssue must be a non-negative integer (0 disables the lock lane)."); + patch.coordinationIssue = input.coordinationIssue; + } + if (input.lockPrefixes !== undefined) patch.lockPrefixes = sanitizeLockPrefixes(input.lockPrefixes, board.lockPrefixes); + if (input.lockAuthors !== undefined) { + patch.lockAuthors = list(input.lockAuthors, "lockAuthors", 50).map((a, i) => { + if (typeof a !== "string" || !/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?$/.test(a)) throw invalid(`lockAuthors[${i}] must be a GitHub login.`); + return a; + }); + } + if (input.localResources !== undefined) patch.localResources = sanitizeLocalResources(input.localResources, board.localResources); + if (input.language !== undefined) { + if (input.language !== "en" && input.language !== "ko") throw invalid('language must be "en" or "ko".'); + patch.language = input.language; + } + if (input.idleMinutes !== undefined) { + if (!Number.isInteger(input.idleMinutes) || input.idleMinutes < 5 || input.idleMinutes > 1440) throw invalid("idleMinutes must be an integer from 5 to 1440."); + patch.idleMinutes = input.idleMinutes; + } + return patch; +} + +export function sanitizeDecisions(value) { + const ids = new Set(); + return list(value, "items", 50).map((item, i) => { + if (!isObject(item) || typeof item.title !== "string" || !item.title.trim()) throw invalid(`items[${i}].title is required.`); + // Without an id, derive one from the title so separate calls never reuse the same id for different questions. + const id = item.id === undefined ? `q-${crypto.createHash("sha256").update(item.title.trim()).digest("hex").slice(0, 10)}` : item.id; + if (typeof id !== "string" || !ID_RE.test(id) || id.startsWith("gh-")) throw invalid(`items[${i}].id must be kebab-case and must not start with "gh-".`); + if (ids.has(id)) throw invalid(`Duplicate item id ${id}.`); + ids.add(id); + return { + id, + title: text(item.title, 200), + detail: text(item.detail, 600), + url: httpsUrl(item.url), + options: list(item.options ?? [], `items[${i}].options`, 8).map((o) => text(String(o), 120)).filter(Boolean), + }; + }); +} + +/** An answer from the board page: a known id shape, the question revision it answers, and 1-1000 characters. */ +export function validAnswer(body) { + const id = typeof body?.id === "string" ? body.id : ""; + const rev = typeof body?.rev === "string" ? body.rev : ""; + const answer = typeof body?.answer === "string" ? body.answer.trim() : ""; + if (!(ID_RE.test(id) || /^gh-\d{1,7}$/.test(id)) || !/^[0-9a-f]{64}$/.test(rev) || !answer || answer.length > 1000) return null; + return { id, rev, answer }; +} diff --git a/extensions/agent-session-board/package.json b/extensions/agent-session-board/package.json new file mode 100644 index 0000000000..8df479d065 --- /dev/null +++ b/extensions/agent-session-board/package.json @@ -0,0 +1,17 @@ +{ + "name": "agent-session-board", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "extension.mjs", + "description": "Supervise several Copilot sessions working one GitHub repository: decision queue, label-track progress, per-PR merge gates, merge flow, warnings and an optional merge-lock lane.", + "scripts": { + "test": "node --test test/*.test.mjs" + }, + "keywords": [ + "canvas", + "multi-agent", + "pull-requests", + "supervision" + ] +} diff --git a/extensions/agent-session-board/test/collect.test.mjs b/extensions/agent-session-board/test/collect.test.mjs new file mode 100644 index 0000000000..9f4f750d4d --- /dev/null +++ b/extensions/agent-session-board/test/collect.test.mjs @@ -0,0 +1,286 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { attributeTrack, buildState, checklist, decisionRev, isValidRepo, referencedNumbers, lockExpiry, matchSession, mergeWindows, parseLockLine, parseLocks, prGate, UNTRACKED } from "../lib/collect.mjs"; +import { demoBoard, demoRaw } from "../lib/demo.mjs"; + +const tracks = [ + { label: "milestone: alpha", titlePattern: "" }, + { label: "milestone: beta", titlePattern: "" }, + { label: "area: docs", titlePattern: "^docs:" }, +]; + +test("attributeTrack prefers the PR's own labels", () => { + const pr = { title: "x", labels: ["milestone: beta"], refs: [{ title: "i", labels: ["milestone: alpha"], parent: null }] }; + assert.equal(attributeTrack(pr, tracks), "milestone: beta"); +}); + +test("attributeTrack falls back to referenced issue labels", () => { + const pr = { title: "x", labels: ["bug"], refs: [{ title: "i", labels: ["milestone: alpha"], parent: { title: "e", labels: ["milestone: beta"] } }] }; + assert.equal(attributeTrack(pr, tracks), "milestone: alpha"); +}); + +test("attributeTrack falls back to the parent epic's labels", () => { + const pr = { title: "x", labels: [], refs: [{ title: "i", labels: [], parent: { title: "e", labels: ["milestone: beta"] } }] }; + assert.equal(attributeTrack(pr, tracks), "milestone: beta"); +}); + +test("attributeTrack uses title patterns only after labels, and reports untracked otherwise", () => { + assert.equal(attributeTrack({ title: "docs: guide", labels: [], refs: [] }, tracks), "area: docs"); + assert.equal(attributeTrack({ title: "docs: guide", labels: ["milestone: alpha"], refs: [] }, tracks), "milestone: alpha"); + assert.equal(attributeTrack({ title: "chore", labels: ["bug"], refs: [] }, tracks), UNTRACKED); +}); + +test("attributeTrack resolves several matching labels by configured order", () => { + assert.equal(attributeTrack({ title: "x", labels: ["area: docs", "milestone: beta"], refs: [] }, tracks), "milestone: beta"); +}); + +const prefixes = { lock: "merge lock:", reserve: "merge reserve:", release: "merge lock release:" }; + +test("parseLockLine reads the longest matching prefix first", () => { + assert.deepEqual(parseLockLine("merge lock release: #12", prefixes), { kind: "release", pr: 12, text: "merge lock release: #12" }); + assert.equal(parseLockLine("**Merge Lock:** #7 until 10:30Z", prefixes)?.kind, "lock"); + assert.equal(parseLockLine("merge reserve: #8", prefixes)?.pr, 8); + assert.equal(parseLockLine("merge lock: no number", prefixes), null); + assert.equal(parseLockLine("unrelated #5", prefixes), null); +}); + +test("lockExpiry reads ISO times and HH:MM with an offset", () => { + assert.equal(lockExpiry("merge lock: #1 until 2026-01-02T03:04:00Z", "2026-01-02T02:00:00Z"), "2026-01-02T03:04:00.000Z"); + assert.equal(lockExpiry("merge lock: #1 until 03:30Z", "2026-01-02T02:00:00Z"), "2026-01-02T03:30:00.000Z"); + assert.equal(lockExpiry("merge lock: #1 until 12:00+09:00", "2026-01-02T02:00:00Z"), "2026-01-02T03:00:00.000Z"); + // An expiry earlier in the day than the comment means the next day. + assert.equal(lockExpiry("merge lock: #1 until 01:00Z", "2026-01-02T23:00:00Z"), "2026-01-03T01:00:00.000Z"); + assert.equal(lockExpiry("merge lock: #1", "2026-01-02T02:00:00Z"), null); + // The calendar date comes from the written offset: 01:00Z on Jan 2 is still Jan 1 at -07:00. + assert.equal(lockExpiry("merge lock: #1 until 20:00-07:00", "2026-01-02T01:00:00Z"), "2026-01-02T03:00:00.000Z"); +}); + +test("parseLocks tracks holder, release, reservations and expiry", () => { + const now = Date.parse("2026-01-02T05:00:00Z"); + const c = (createdAt, line) => ({ createdAt, url: "", author: "dev", writeAccess: true, line }); + const comments = [ + c("2026-01-02T01:00:00Z", "merge lock: #10 until 02:00Z"), + c("2026-01-02T01:10:00Z", "merge reserve: #11"), + c("2026-01-02T01:20:00Z", "merge reserve: #12"), + c("2026-01-02T01:30:00Z", "merge lock release: #10"), + c("2026-01-02T01:40:00Z", "merge lock: #11 until 03:00Z"), + ]; + const lock = parseLocks(comments, prefixes, new Set([10, 11, 12]), now); + assert.equal(lock.holder.pr, 11); + assert.equal(lock.holder.expired, true); + assert.deepEqual(lock.reservations.map((r) => r.pr), [12]); + assert.equal(lock.events.length, 5); + assert.equal(parseLocks(comments, prefixes, new Set([12]), now).holder, null, "a closed PR cannot hold the lock"); + assert.equal(parseLocks(comments, prefixes, null, now).holder.pr, 11, "an incomplete open list drops nothing as closed"); +}); + +test("parseLocks ignores lock lines from authors without verified write access", () => { + const comments = [ + { createdAt: "2026-01-02T01:00:00Z", url: "", author: "dev", writeAccess: true, line: "merge lock: #10" }, + { createdAt: "2026-01-02T01:05:00Z", url: "", author: "drive-by", writeAccess: false, line: "merge lock release: #10" }, + { createdAt: "2026-01-02T01:06:00Z", url: "", author: "drive-by", line: "merge reserve: #11" }, + ]; + const lock = parseLocks(comments, prefixes, new Set([10, 11]), Date.parse("2026-01-02T02:00:00Z")); + assert.equal(lock.holder.pr, 10); + assert.deepEqual(lock.reservations, []); + assert.equal(lock.ignored, 2); + const allow = parseLocks(comments, prefixes, new Set([10, 11]), Date.parse("2026-01-02T02:00:00Z"), ["Drive-By"]); + assert.equal(allow.holder, null, "an explicit allowlist replaces the association rule"); + assert.deepEqual(allow.reservations.map((r) => r.pr), [11]); +}); + +test("prGate reports the first unmet merge gate", () => { + const ok = { isDraft: false, mergeable: "MERGEABLE", ci: "passed", reviewDecision: "APPROVED", unresolvedThreads: 0, headReviewed: true }; + assert.equal(prGate(ok), "mergeable"); + assert.equal(prGate({ ...ok, isDraft: true, mergeable: "CONFLICTING" }), "draft"); + assert.equal(prGate({ ...ok, mergeable: "CONFLICTING", ci: "failed" }), "conflict"); + assert.equal(prGate({ ...ok, ci: "failed" }), "ci-failed"); + assert.equal(prGate({ ...ok, ci: "running" }), "ci-running"); + assert.equal(prGate({ ...ok, reviewDecision: "CHANGES_REQUESTED", unresolvedThreads: 1 }), "changes-requested"); + assert.equal(prGate({ ...ok, unresolvedThreads: 2 }), "unresolved-threads"); + assert.equal(prGate({ ...ok, reviewDecision: "REVIEW_REQUIRED" }), "review-required"); + assert.equal(prGate({ ...ok, headReviewed: false }), "no-head-review"); + assert.equal(prGate({ ...ok, ci: "none", reviewDecision: null }), "mergeable"); + assert.equal(prGate({ ...ok, mergeable: "UNKNOWN" }), "mergeability-unknown", "unknown mergeability is never green"); + assert.equal(prGate({ ...ok, mergeStateStatus: "BEHIND" }), "behind", "conflict-free is not enough when the branch must be up to date"); + assert.equal(prGate({ ...ok, mergeStateStatus: "BLOCKED" }), "blocked"); + assert.equal(prGate({ ...ok, mergeStateStatus: "UNKNOWN" }), "mergeability-unknown"); + assert.equal(prGate({ ...ok, mergeStateStatus: "CLEAN" }), "mergeable"); + assert.equal(prGate({ ...ok, threadsComplete: false }), "threads-unknown"); + assert.equal(prGate({ ...ok, threadsComplete: false, unresolvedThreads: 1 }), "unresolved-threads"); +}); + +test("matchSession checks explicit PRs, then branches, then titles", () => { + const sessions = [ + { id: "a", prs: [], branchPatterns: ["^api/"], titlePatterns: [] }, + { id: "b", prs: [7], branchPatterns: [], titlePatterns: ["^docs:"] }, + { id: "c", prs: [], branchPatterns: ["(invalid"], titlePatterns: [] }, + ]; + assert.equal(matchSession({ number: 7, headRefName: "api/x", title: "" }, sessions), "b"); + assert.equal(matchSession({ number: 1, headRefName: "API/x", title: "docs: y" }, sessions), "a"); + assert.equal(matchSession({ number: 2, headRefName: "web/x", title: "docs: y" }, sessions), "b"); + assert.equal(matchSession({ number: 3, headRefName: "web/x", title: "feat" }, sessions), null); + // A pattern that could backtrack catastrophically never runs against contributor titles. + const risky = [{ id: "r", prs: [], branchPatterns: [], titlePatterns: ["(a+)+$"] }]; + const started = Date.now(); + assert.equal(matchSession({ number: 4, headRefName: "", title: `${"a".repeat(40)}!` }, risky), null); + assert.ok(Date.now() - started < 100); +}); + +test("isValidRepo accepts owner/name slugs only", () => { + assert.equal(isValidRepo("octo-org/my.repo_1"), true); + assert.equal(isValidRepo("octo/.."), false); + assert.equal(isValidRepo("../etc"), false); + assert.equal(isValidRepo("a/b/c"), false); + assert.equal(isValidRepo("-bad/x"), false); +}); + +test("buildState on demo data fills every panel", () => { + const now = Date.parse("2026-03-04T12:00:00Z"); + const betaRev = decisionRev(demoBoard().decisions.find((d) => d.id === "beta-scope")); + const state = buildState(demoRaw(now), { ...demoBoard(), lockPrefixes: prefixes, answers: { "beta-scope": { answer: "Keep in Beta", rev: betaRev, at: "2026-03-04T11:00:00Z", seen: true } } }, now); + assert.equal(state.hours.length, 24); + assert.equal(state.days.length, 7); + assert.ok(state.mergedWeek.length > state.merged24.length); + assert.ok(state.mergedWeek.every((pr) => pr.track !== undefined)); + assert.equal(state.lock.holder.pr, 141); + assert.deepEqual(state.decisions.map((d) => d.id), ["cache-strategy", "gh-150"], "seen answers leave the queue"); + assert.ok(state.sessions.some((s) => s.id === null), "unmatched PRs get an Unassigned card"); + assert.ok(state.warnings.some((w) => w.code === "ci_failed")); +}); + +test("checklist counts boxes per line and stays fast on whitespace-heavy bodies", () => { + assert.deepEqual(checklist("- [x] a\n - [ ] b\n\t* [X] c\ntext - [ ] d"), { total: 3, done: 2 }); + const started = Date.now(); + checklist(`${" \n".repeat(200000)}x`); + assert.ok(Date.now() - started < 1000); +}); + +test("merge totals cover exactly the charted buckets", () => { + const now = new Date(2026, 2, 4, 12, 30).getTime(); + const windows = mergeWindows(now); + assert.equal(windows.hourSince, new Date(2026, 2, 3, 13, 0).getTime()); + assert.equal(windows.daySince, new Date(2026, 1, 26, 0, 0).getTime()); + const merged = [ + new Date(2026, 2, 3, 12, 45), // before the first hourly bar: in the 7-day total only + new Date(2026, 2, 3, 13, 5), + new Date(2026, 1, 26, 0, 10), // first minutes of the oldest day + new Date(2026, 1, 25, 23, 50), // outside both windows + ].map((d, i) => ({ number: i + 1, title: "t", url: "", mergedAt: d.toISOString(), labels: [], refs: [] })); + const state = buildState({ repo: "o/r", openPrs: [], merged }, { sessions: [], tracks: [], answers: {} }, now); + const sum = (buckets) => buckets.reduce((a, b) => a + Object.values(b.counts).reduce((x, y) => x + y, 0), 0); + assert.equal(state.merged24.length, 1); + assert.equal(sum(state.hours), state.merged24.length); + assert.equal(state.mergedWeek.length, 3); + assert.equal(sum(state.days), state.mergedWeek.length); +}); + +test("buildState only attaches answers the board actually stored", () => { + const board = { sessions: [], tracks: [], answers: {}, decisions: [{ id: "constructor", title: "Q", options: [] }] }; + const state = buildState({ repo: "o/r", openPrs: [], merged: [] }, board, Date.now()); + assert.equal(state.decisions[0].answer, null); +}); + +test("incomplete collection is reported and never yields a ready track", () => { + const raw = { + repo: "o/r", openPrs: [], openPrTotal: 600, merged: [], + trackIssues: { a: [{ number: 1, title: "x", url: "", state: "CLOSED", body: "" }] }, + incomplete: { openPrs: true, merged: true, tracks: ["a"], decisions: true }, + }; + const state = buildState(raw, { sessions: [], tracks: [{ label: "a" }], answers: {} }, Date.now()); + assert.equal(state.tracks[0].ready, false); + const codes = state.warnings.map((w) => w.code); + for (const code of ["open_prs_incomplete", "merges_incomplete", "track_incomplete", "decisions_incomplete"]) assert.ok(codes.includes(code), code); +}); + +test("the repeated hour at the end of daylight saving time keeps two separate bars", () => { + const previous = process.env.TZ; + process.env.TZ = "America/New_York"; + try { + // 01:00-02:00 local happens twice on 2026-11-01 (05:00-06:00Z as EDT, 06:00-07:00Z as EST). + const now = Date.parse("2026-11-01T07:30:00Z"); + const merged = ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"].map((mergedAt, i) => ({ number: i + 1, title: "t", url: "", mergedAt, labels: [], refs: [] })); + const state = buildState({ repo: "o/r", openPrs: [], merged }, { sessions: [], tracks: [], answers: {} }, now); + const totals = state.hours.map((h) => Object.values(h.counts).reduce((a, x) => a + x, 0)); + assert.equal(totals.reduce((a, x) => a + x, 0), 2); + assert.equal(Math.max(...totals), 1); + } finally { + if (previous === undefined) delete process.env.TZ; + else process.env.TZ = previous; + } +}); + +test("decisionRev changes when a question is replaced under the same id", () => { + const a = { id: "q", title: "Ship it?", detail: "", options: ["yes", "no"] }; + assert.equal(decisionRev(a), decisionRev({ ...a })); + assert.notEqual(decisionRev(a), decisionRev({ ...a, title: "Ship the other thing?" })); + assert.notEqual(decisionRev(a), decisionRev({ ...a, options: ["yes"] })); + const state = buildState({ repo: "o/r", openPrs: [], merged: [] }, { sessions: [], tracks: [], answers: {}, decisions: [a] }, Date.now()); + assert.equal(state.decisions[0].rev, decisionRev(a)); +}); + +test("answers attach to and hide only the question revision they were given for", () => { + const q = { id: "q", title: "Ship it?", detail: "", options: ["yes", "no"], url: "" }; + const rev = decisionRev(q); + const answers = { q: { answer: "yes", rev, at: "2026-01-01T00:00:00Z", seen: false }, "gh-7": { answer: "ok", rev: "000000000000", at: "2026-01-01T00:00:00Z", seen: true } }; + const raw = { repo: "o/r", openPrs: [], merged: [], decisionIssues: [{ number: 7, title: "Retitled question", url: "" }] }; + const same = buildState(raw, { sessions: [], tracks: [], answers, decisions: [q] }, Date.now()); + assert.equal(same.decisions.find((d) => d.id === "q").answer.answer, "yes"); + assert.ok(same.decisions.some((d) => d.id === "gh-7" && d.answer === null), "a seen answer to an older revision does not hide the revised question"); + const revised = buildState(raw, { sessions: [], tracks: [], answers, decisions: [{ ...q, options: ["yes", "no", "later"] }] }, Date.now()); + assert.equal(revised.decisions.find((d) => d.id === "q").answer, null); +}); + +test("the hourly window keeps the current offset during the repeated hour", () => { + const previous = process.env.TZ; + process.env.TZ = "America/New_York"; + try { + const now = Date.parse("2026-11-01T06:30:00Z"); // 01:30 EST, the second 01:00 hour + assert.equal(new Date(mergeWindows(now).hourSince).toISOString(), "2026-10-31T07:00:00.000Z"); + const merged = [{ number: 1, title: "t", url: "", mergedAt: "2026-11-01T06:15:00Z", labels: [], refs: [] }]; + const state = buildState({ repo: "o/r", openPrs: [], merged }, { sessions: [], tracks: [], answers: {} }, now); + const charted = state.hours.reduce((a, h) => a + Object.values(h.counts).reduce((x, y) => x + y, 0), 0); + assert.equal(state.merged24.length, 1); + assert.equal(charted, 1); + } finally { + if (previous === undefined) delete process.env.TZ; + else process.env.TZ = previous; + } +}); + +test("unverified lock authors and partial attribution are reported", () => { + const comments = [{ createdAt: "2026-01-02T01:00:00Z", url: "", author: "someone", writeAccess: null, line: "merge lock: #10" }]; + const lock = parseLocks(comments, prefixes, new Set([10]), Date.parse("2026-01-02T02:00:00Z")); + assert.equal(lock.holder, null); + assert.equal(lock.unverified, 1); + const state = buildState( + { repo: "o/r", openPrs: [], merged: [], lockComments: comments, incomplete: { attribution: { truncatedLabels: 2, skippedRefs: 3 } } }, + { sessions: [], tracks: [], answers: {}, coordinationIssue: 1, lockPrefixes: prefixes }, Date.parse("2026-01-02T02:00:00Z")); + const codes = state.warnings.map((w) => w.code); + assert.ok(codes.includes("lock_unverified")); + assert.ok(codes.includes("attribution_incomplete")); +}); + +test("referencedNumbers keeps every reference for the global budget to account for", () => { + const body = Array.from({ length: 20 }, (_, i) => `see #${i + 100}`).join("\n"); + assert.equal(referencedNumbers({ number: 1, title: "", body }).length, 20); +}); + +test("track labels that look like object keys keep exact counts", () => { + const tracks = [{ label: "constructor" }, { label: "__proto__" }]; + const now = Date.now(); + const merged = ["constructor", "__proto__", "__proto__"].map((label, i) => ({ number: i + 1, title: "t", url: "", mergedAt: new Date(now - 60000).toISOString(), labels: [label], refs: [] })); + const state = buildState({ repo: "o/r", openPrs: [], merged, trackIssues: {} }, { sessions: [], tracks, answers: {} }, now); + const bucket = state.hours[state.hours.length - 1].counts; + assert.equal(bucket.constructor, 1); + assert.equal(Object.getOwnPropertyDescriptor(bucket, "__proto__").value, 2); + assert.deepEqual(state.tracks.map((t) => t.merged24), [1, 2]); +}); + +test("a label-raised question's body is part of its revision but is not sent to the page", () => { + const issue = { number: 7, title: "Pick one", url: "", body: "- option A\n- option B" }; + const one = buildState({ repo: "o/r", openPrs: [], merged: [], decisionIssues: [issue] }, { sessions: [], tracks: [], answers: {} }, Date.now()).decisions[0]; + const two = buildState({ repo: "o/r", openPrs: [], merged: [], decisionIssues: [{ ...issue, body: "- option C" }] }, { sessions: [], tracks: [], answers: {} }, Date.now()).decisions[0]; + assert.notEqual(one.rev, two.rev); + assert.equal(one.body, undefined); +}); diff --git a/extensions/agent-session-board/test/exec.test.mjs b/extensions/agent-session-board/test/exec.test.mjs new file mode 100644 index 0000000000..39f4a5ca13 --- /dev/null +++ b/extensions/agent-session-board/test/exec.test.mjs @@ -0,0 +1,10 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { run } from "../lib/exec.mjs"; + +test("run refuses commands outside the allowlist and non-string arguments", async () => { + await assert.rejects(run("rm", ["-rf", "/tmp/x"]), { code: "not_allowed" }); + await assert.rejects(run("sh", ["-c", "echo hi"]), { code: "not_allowed" }); + await assert.rejects(run("gh", "--version"), { code: "not_allowed" }); + await assert.rejects(run("gh", [{ toString: () => "--version" }]), { code: "not_allowed" }); +}); diff --git a/extensions/agent-session-board/test/fixtures/board-writer.mjs b/extensions/agent-session-board/test/fixtures/board-writer.mjs new file mode 100644 index 0000000000..20ec80a24e --- /dev/null +++ b/extensions/agent-session-board/test/fixtures/board-writer.mjs @@ -0,0 +1,8 @@ +// Test fixture: one independent writer. Each worker thread loads its own copy of store.mjs, so the in-process +// queue is not shared between writers and only the lock file keeps their updates from overwriting each other. +import { workerData } from "node:worker_threads"; +import { updateBoard } from "../../lib/store.mjs"; + +for (let i = 0; i < workerData.count; i += 1) { + await updateBoard("octo/app", (b) => ({ ...b, decisions: [...b.decisions, { id: `${workerData.name}-${i}`, title: "t", detail: "", url: "", options: [] }] })); +} diff --git a/extensions/agent-session-board/test/pattern.test.mjs b/extensions/agent-session-board/test/pattern.test.mjs new file mode 100644 index 0000000000..dbbdf20756 --- /dev/null +++ b/extensions/agent-session-board/test/pattern.test.mjs @@ -0,0 +1,15 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { evaluatePatterns } from "../lib/pattern.mjs"; + +test("evaluatePatterns skips a pattern that runs past its deadline and still evaluates the rest", async () => { + const slow = "\\d*\\d*\\d*\\d*\\d*x"; + const started = Date.now(); + const matcher = await evaluatePatterns(["^api/", slow, "^docs:"], ["api/x", "docs: y", "1".repeat(250)], 200); + assert.deepEqual(matcher.skipped, [slow]); + assert.equal(matcher.test("^api/", "api/x"), true); + assert.equal(matcher.test("^docs:", "docs: y"), true); + assert.equal(matcher.test("^docs:", "api/x"), false); + assert.equal(matcher.test(slow, "1".repeat(250)), false); + assert.ok(Date.now() - started < 3000); +}); diff --git a/extensions/agent-session-board/test/store.test.mjs b/extensions/agent-session-board/test/store.test.mjs new file mode 100644 index 0000000000..920e163599 --- /dev/null +++ b/extensions/agent-session-board/test/store.test.mjs @@ -0,0 +1,160 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile, mkdir, utimes } from "node:fs/promises"; +import { Worker } from "node:worker_threads"; +import os from "node:os"; +import path from "node:path"; +import { FORMAT, VERSION, boardFileName, configPatch, defaultBoard, getBoard, parseDocument, sanitizeDecisions, updateBoard, validAnswer } from "../lib/store.mjs"; + +test("parseDocument rejects foreign, newer, malformed and non-JSON files", () => { + assert.throws(() => parseDocument("{nope", "f"), { code: "store_corrupt" }); + assert.throws(() => parseDocument(JSON.stringify({ format: "something-else", version: 1, board: {} }), "f"), { code: "store_unrecognized" }); + assert.throws(() => parseDocument(JSON.stringify({ format: FORMAT, version: VERSION + 1, board: {} }), "f"), { code: "store_version" }); + assert.throws(() => parseDocument(JSON.stringify({ format: FORMAT, version: VERSION, board: { sessions: {} } }), "f"), { code: "store_corrupt" }); + assert.throws(() => parseDocument(JSON.stringify({ format: FORMAT, version: VERSION }), "f"), { code: "store_corrupt" }); + assert.equal(parseDocument(JSON.stringify({ format: FORMAT, version: VERSION, board: {} }), "f").version, VERSION); +}); + +test("boardFileName keys boards per repository and refuses unsafe names", () => { + assert.equal(boardFileName("Octo-Org/My.Repo"), "octo-org__my.repo.json"); + assert.equal(boardFileName("demo"), "demo.json"); + assert.throws(() => boardFileName("octo/.."), { code: "invalid_repo" }); + assert.throws(() => boardFileName("a/b/c"), { code: "invalid_repo" }); +}); + +test("updateBoard writes atomically under COPILOT_HOME and leaves a foreign file untouched", async (t) => { + const home = await mkdtemp(path.join(os.tmpdir(), "fcb-")); + const previous = process.env.COPILOT_HOME; + process.env.COPILOT_HOME = home; + t.after(async () => { + if (previous === undefined) delete process.env.COPILOT_HOME; + else process.env.COPILOT_HOME = previous; + await rm(home, { recursive: true, force: true }); + }); + const dir = path.join(home, "extension-data", "agent-session-board"); + await Promise.all([ + updateBoard("octo/app", (b) => ({ ...b, idleMinutes: 30 })), + updateBoard("octo/app", (b) => ({ ...b, decisionLabel: "needs-decision" })), + ]); + const saved = JSON.parse(await readFile(path.join(dir, "octo__app.json"), "utf8")); + assert.equal(saved.format, FORMAT); + assert.equal(saved.board.idleMinutes, 30, "concurrent updates are serialized"); + assert.equal(saved.board.decisionLabel, "needs-decision"); + assert.deepEqual((await getBoard("octo/other")).sessions, defaultBoard().sessions); + + await mkdir(dir, { recursive: true }); + const foreign = JSON.stringify({ hello: "world" }); + await writeFile(path.join(dir, "octo__foreign.json"), foreign); + await assert.rejects(updateBoard("octo/foreign", (b) => b), { code: "store_unrecognized" }); + assert.equal(await readFile(path.join(dir, "octo__foreign.json"), "utf8"), foreign); +}); + +test("configPatch validates labels, regexes and lock prefixes", () => { + const board = defaultBoard(); + assert.deepEqual(configPatch({ tracks: [{ label: "area: api", titlePattern: "^api" }] }, board).tracks[0].label, "area: api"); + assert.throws(() => configPatch({ tracks: [{ label: 'bad "label"' }] }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ sessions: [{ id: "a", branchPatterns: ["("] }] }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ sessions: [{ id: "a", titlePatterns: ["(a+)+$"] }] }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ tracks: [{ label: "x", titlePattern: "(a|aa)*" }] }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ sessions: [{ id: "a", titlePatterns: ["(a+){20}$"] }] }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ sessions: [{ id: "a", titlePatterns: ["[](a+)+$"] }] }, board), { code: "invalid_input" }, "[] closes at once in JavaScript"); + assert.throws(() => configPatch({ localResources: { heavyPattern: "(\\w+\\s?)+$" } }, board), { code: "invalid_input" }); + assert.throws(() => configPatch({ lockPrefixes: { lock: "merge reserve:" } }, board), { code: "invalid_input" }); + assert.equal(configPatch({ lockPrefixes: { lock: "lock:" } }, board).lockPrefixes.release, "merge lock release:"); + assert.deepEqual(configPatch({ lockAuthors: ["octo-cat", "ci[bot]"] }, board).lockAuthors, ["octo-cat", "ci[bot]"]); + assert.throws(() => configPatch({ lockAuthors: ["not a login"] }, board), { code: "invalid_input" }); + assert.equal(defaultBoard().language, "en", "the board is English unless configured"); + assert.equal(configPatch({ language: "ko" }, board).language, "ko"); + assert.throws(() => configPatch({ language: "fr" }, board), { code: "invalid_input" }); +}); + +test("sanitizeDecisions and validAnswer keep ids well-formed", () => { + const [first] = sanitizeDecisions([{ title: "Pick one", options: ["a", "b"] }]); + const [other] = sanitizeDecisions([{ title: "Pick another" }]); + assert.match(first.id, /^q-[0-9a-f]{10}$/); + assert.notEqual(first.id, other.id, "default ids differ for different questions"); + assert.throws(() => sanitizeDecisions([{ title: "Same" }, { title: "Same" }]), { code: "invalid_input" }); + assert.throws(() => sanitizeDecisions([{ id: "gh-1", title: "x" }]), { code: "invalid_input" }); + assert.equal(sanitizeDecisions([{ id: "x", title: "t", url: "javascript:alert(1)" }])[0].url, ""); + const rev = "a".repeat(64); + assert.deepEqual(validAnswer({ id: "gh-12", rev, answer: " yes " }), { id: "gh-12", rev, answer: "yes" }); + assert.equal(validAnswer({ id: "x", answer: "yes" }), null, "an answer must name the question revision"); + assert.equal(validAnswer({ id: "x", rev: "a".repeat(12), answer: "yes" }), null, "a truncated revision is not accepted"); + assert.equal(validAnswer({ id: "../x", rev, answer: "y" }), null); + assert.equal(validAnswer({ id: "x", rev, answer: "" }), null); +}); + +test("updateBoard keeps every update when independent writers share the same board", async (t) => { + const home = await mkdtemp(path.join(os.tmpdir(), "asb-mw-")); + t.after(() => rm(home, { recursive: true, force: true })); + const writer = (name) => new Promise((resolve, reject) => { + const worker = new Worker(new URL("./fixtures/board-writer.mjs", import.meta.url), { workerData: { name, count: 15 }, env: { ...process.env, COPILOT_HOME: home } }); + worker.once("error", reject); + worker.once("exit", (code) => (code === 0 ? resolve() : reject(new Error(`writer ${name} exited with ${code}`)))); + }); + await Promise.all([writer("a"), writer("b"), writer("c")]); + const saved = JSON.parse(await readFile(path.join(home, "extension-data", "agent-session-board", "octo__app.json"), "utf8")); + assert.equal(saved.board.decisions.length, 45); +}); + +test("a lock left by a dead process is taken over, and the board stays writable", async (t) => { + const home = await mkdtemp(path.join(os.tmpdir(), "fcb-stale-")); + const previous = process.env.COPILOT_HOME; + process.env.COPILOT_HOME = home; + t.after(async () => { + if (previous === undefined) delete process.env.COPILOT_HOME; + else process.env.COPILOT_HOME = previous; + await rm(home, { recursive: true, force: true }); + }); + const dir = path.join(home, "extension-data", "agent-session-board"); + await mkdir(dir, { recursive: true }); + // PID 2^22+1 is above the default pid_max on Linux and macOS, so no live process owns it. + await writeFile(path.join(dir, "octo__app.json.lock"), "4194305 deadbeefdeadbeefdeadbeef\n"); + const started = Date.now(); + const board = await updateBoard("octo/app", (b) => ({ ...b, idleMinutes: 42 })); + assert.equal(board.idleMinutes, 42); + assert.ok(Date.now() - started < 5000); + await assert.rejects(readFile(path.join(dir, "octo__app.json.lock")), { code: "ENOENT" }, "the writer released its own lock"); +}); + +test("an empty lock left by an interrupted writer is recovered after its grace period", async (t) => { + const home = await mkdtemp(path.join(os.tmpdir(), "fcb-empty-")); + const previous = process.env.COPILOT_HOME; + process.env.COPILOT_HOME = home; + t.after(async () => { + if (previous === undefined) delete process.env.COPILOT_HOME; + else process.env.COPILOT_HOME = previous; + await rm(home, { recursive: true, force: true }); + }); + const dir = path.join(home, "extension-data", "agent-session-board"); + await mkdir(dir, { recursive: true }); + const lock = path.join(dir, "octo__app.json.lock"); + await writeFile(lock, ""); + const old = new Date(Date.now() - 60 * 1000); + await utimes(lock, old, old); + const board = await updateBoard("octo/app", (b) => ({ ...b, idleMinutes: 7 })); + assert.equal(board.idleMinutes, 7); +}); + +test("a fresh takeover marker makes writers back off to the deadline instead of spinning", async (t) => { + const home = await mkdtemp(path.join(os.tmpdir(), "asb-takeover-")); + const previous = process.env.COPILOT_HOME; + process.env.COPILOT_HOME = home; + t.after(async () => { + if (previous === undefined) delete process.env.COPILOT_HOME; + else process.env.COPILOT_HOME = previous; + await rm(home, { recursive: true, force: true }); + }); + const dir = path.join(home, "extension-data", "agent-session-board"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "octo__app.json.lock"), "4194305 deadbeefdeadbeefdeadbeef\n"); + await writeFile(path.join(dir, "octo__app.json.lock.takeover"), ""); + const started = Date.now(); + let reads = 0; + const timer = setInterval(() => { reads += 1; }, 50); + await assert.rejects(updateBoard("octo/app", (b) => b), { code: "store_busy" }); + clearInterval(timer); + const elapsed = Date.now() - started; + assert.ok(elapsed >= 9500 && elapsed < 13000, `gave up after ${elapsed} ms`); + assert.ok(reads > 100, "the event loop stayed free while waiting"); +}); diff --git a/plugins/agent-session-board/README.md b/plugins/agent-session-board/README.md new file mode 100644 index 0000000000..0271f331ac --- /dev/null +++ b/plugins/agent-session-board/README.md @@ -0,0 +1,33 @@ +# Agent Session Board Plugin + +Supervise several Copilot sessions working one GitHub repository: a decision queue, progress by label track, merge-gate status for every PR, hourly and daily merge flow, warnings, and an optional merge-lock lane. + +## Requirements + +- GitHub Copilot app with canvas support +- [GitHub CLI](https://cli.github.com/) (`gh`) signed in with access to the repository you supervise + +## Installation + +```bash +copilot plugin install agent-session-board@awesome-copilot +``` + +## Usage + +Open the canvas for a repository, or with sample data: + +```text +open_canvas agent-session-board { "repo": "owner/name" } +open_canvas agent-session-board { "demo": true } +``` + +See the [extension README](../../extensions/agent-session-board/README.md) for configuration and actions. + +## Source + +This plugin is part of [Awesome Copilot](https://github.com/github/awesome-copilot). + +## License + +MIT diff --git a/plugins/agent-session-board/plugin.json b/plugins/agent-session-board/plugin.json new file mode 100644 index 0000000000..7a878b95a0 --- /dev/null +++ b/plugins/agent-session-board/plugin.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "agent-session-board", + "description": "Supervise several Copilot sessions working one GitHub repository: a decision queue, progress by label track, merge-gate status for every PR, hourly and daily merge flow, warnings, and an optional merge-lock lane.", + "version": "1.0.0", + "author": { + "name": "hellices", + "url": "https://github.com/hellices" + }, + "repository": "https://github.com/github/awesome-copilot", + "license": "MIT", + "keywords": [ + "canvas", + "copilot-extension", + "dashboard", + "merge-queue", + "multi-agent", + "pull-requests", + "supervision" + ], + "extensions": { + "com.github.copilot": { + "logo": "assets/preview.png" + }, + "com.github.awesome-copilot": { + "extensions": [ + "./extensions/agent-session-board" + ] + } + } +}