Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(kanban): keep pull observations on the host; claim each merge move once

review5b3599c17c44
diff --git a/CLAUDE.md b/CLAUDE.md
index 631f58c36..fcf09192a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5354,21 +5354,37 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
next member/due/label edit. SSH projects show the worktree reason instead (no worktree groups
there). The open seam: joining PR → issue → node through the `issueRef` an agent started from an
issue card will carry (not on main yet) — `pullsForCard` is where that second link source plugs in.
- **Merge-driven move — session cards only, OFF by default.** The switch and the target column are
- MACHINE-LOCAL (`settings.kanbanPullAutoMove.projects[projectId]`): it makes this machine write the
- shared board on its own, so a switch in the project file would make every clone move and commit
- cards nobody on that machine asked for. Per-card opt-out is board content (`pullLinks.noAutoMove`).
- Guards in order (`decidePullAutoMove`): opted out → never; any linked PR open/draft → wait; any
- closed unmerged → blocked until the user unlinks it; already in target → nothing; all merged but
- this machine never SAW one open (`seen`, same settings entry) → no move. The move is a
- compare-and-set on the column the decision saw (`applyPullAutoMove`, run by Canvas against the
- store's latest board) and writes ONE `card-moved` board-log line whose `title` names the PRs. It
- runs only while the board is open (that is when pull status is fresh) and never on a stale
- snapshot. **GitHub issue cards are never auto-moved** — GitHub already closes them when a
- `Closes #N` PR merges, and a second writer would race it and could clobber `state_reason`.
+ **What this machine observed lives on the HOST** (`core/github/pull-memory.ts`, persisted beside
+ the issue cache per identity + repository, deleted with it): every PR it has seen, its head, its
+ lifecycle, whether it was seen open, and `mergedSeenAt` — the first time it was seen merged AFTER
+ being seen open (an OBSERVED merge). The read lists only 50 open + 30 recent PRs, so without it a
+ closed-unmerged PR's block would expire once 30 newer PRs closed; remembered PRs stay on the pull
+ board (closed ones until unlinked, merges for 30 days) and an unlisted one takes its lifecycle
+ from the REST harvest. The first version kept a per-card "seen" map in settings.json instead, and
+ review found three failures in that shape: the planner's output exceeded the sanitizer's bounds so
+ the hook rewrote settings in a loop until React threw; the block expired; and two Server Edition
+ tabs both moved the card while a background tab's settings write reverted another tab's changes.
+ **Merge-driven move — session cards only, OFF by default.** The switch, the target column and
+ `armedAt` are MACHINE-LOCAL (`settings.kanbanPullAutoMove.projects[projectId]`, written ONLY by
+ the user's own Settings action): it makes this machine write the shared board on its own, so a
+ switch in the project file would make every clone move and commit cards nobody on that machine
+ asked for. Per-card opt-out is board content (`pullLinks.noAutoMove`). Guards in order
+ (`decidePullAutoMove`): opted out → never; any linked PR open/draft → wait; any closed unmerged →
+ blocked until the user unlinks it; already in target → nothing; no linked merge with
+ `mergedSeenAt >= armedAt` → no move (arming never sweeps old merges). Each planned move must then
+ win the host's one-time CLAIM (`githubIssues:claim-pull-auto-move`, persisted in the same memory,
+ keyed by project + card + PR set) — the first ask across every window wins, and a card dragged
+ back is not moved again for the same merges — and is applied as a compare-and-set on the column
+ the decision saw (`applyPullAutoMove`, run by Canvas against the store's latest board), writing
+ ONE `card-moved` board-log line whose `title` names the PRs. The planner writes nothing; it runs
+ only while the board is open and never on a stale snapshot. **GitHub issue cards are never
+ auto-moved** — GitHub already closes them when a `Closes #N` PR merges, and a second writer would
+ race it and could clobber `state_reason`.
Surfaces: Desktop + Server Edition identical (core + renderer; `githubIssues:pull-status`,
- `:chase-pulls`, `:pull-checks` are registered by the shared core handlers and served to relay
- tabs through the project-scope table). **Mobile: follow-up** — the phone board carries session
+ `:chase-pulls`, `:pull-checks`, `:claim-pull-auto-move` are registered by the shared core handlers
+ and served to relay tabs through the project-scope table; a relay tab never auto-moves — the
+ board belongs to the other machine). Check detail is bounded for relay guests: one read per PR per
+ 15 s, ten per project per minute, both decided before a credential is resolved. **Mobile: follow-up** — the phone board carries session
cards only; showing PR CI there means carrying `GitHubPullBoard` over the relay dialect.
**Where a card comes from is a registry, not a branch per call site** (`renderer/lib/kanbanSources.ts`,
2026-08-30 — the same membership-plus-one-leaf discipline `AGENT_CONFIG` uses): each entry declares
diff --git a/src/core/github/cache.ts b/src/core/github/cache.ts
index 64a9f52ef..5f23c20c8 100644
--- a/src/core/github/cache.ts
+++ b/src/core/github/cache.ts
@@ -4,8 +4,12 @@ import path from 'node:path'
import type { GitHubIssue } from '../../shared/github-issues'
import { renameAtomic, tempNameFor } from '../fs-atomic'
import { parseGitHubRepository } from './config'
+import { emptyPullMemory, validPullMemory, type PullMemory } from './pull-memory'
const DIRECTORY = 'github-issues-cache'
+/** What this machine observed about the repository's pull requests (pull-memory.ts). Beside the
+ * issue cache, same key, and deleted with it. */
+const PULL_MEMORY_DIRECTORY = 'github-pull-memory'
const BINDING_DIRECTORY = 'github-issues-bindings'
const DEFAULT_MAXIMUM = 64 * 1024 * 1024
@@ -165,6 +169,25 @@ export class GitHubIssueCache {
async clear(userId: string, repository: string): Promise<void> {
await fs.rm(this.file(userId, repository), { force: true })
+ await fs.rm(this.file(userId, repository, PULL_MEMORY_DIRECTORY), { force: true })
+ }
+
+ /** Never throws: an unreadable or malformed file is an empty memory (nothing observed yet), which
+ * can only make the merge-driven move WAIT, never fire. */
+ async loadPullMemory(userId: string, repository: string): Promise<PullMemory> {
+ try {
+ const raw = await fs.readFile(this.file(userId, repository, PULL_MEMORY_DIRECTORY), 'utf-8')
+ if (Buffer.byteLength(raw, 'utf-8') > 4 * 1024 * 1024) return emptyPullMemory()
+ const parsed: unknown = JSON.parse(raw)
+ return validPullMemory(parsed) ? structuredClone(parsed) : emptyPullMemory()
+ } catch {
+ return emptyPullMemory()
+ }
+ }
+
+ async savePullMemory(userId: string, repository: string, memory: PullMemory): Promise<void> {
+ if (!validPullMemory(memory)) throw new GitHubCacheError('cache-too-large')
+ await this.writePrivate(this.file(userId, repository, PULL_MEMORY_DIRECTORY), JSON.stringify(memory))
}
async bind(
@@ -200,12 +223,12 @@ export class GitHubIssueCache {
await fs.rm(binding, { force: true })
}
- private file(userId: string, repository: string): string {
+ private file(userId: string, repository: string, directory = DIRECTORY): string {
if (!userId || userId.length > 256 || parseGitHubRepository(repository) !== repository) {
throw new GitHubCacheError('invalid-cache-key')
}
const digest = createHash('sha256').update(`${userId}\0${repository}`).digest('hex')
- return path.join(this.userDataDir, DIRECTORY, `${digest}.json`)
+ return path.join(this.userDataDir, directory, `${digest}.json`)
}
private bindingFile(localApprovalId: string, projectId: string, repository: string): string {
diff --git a/src/core/github/graphql-pulls.test.ts b/src/core/github/graphql-pulls.test.ts
index f6793cd64..f7269df13 100644
--- a/src/core/github/graphql-pulls.test.ts
+++ b/src/core/github/graphql-pulls.test.ts
@@ -93,6 +93,20 @@ describe('parsePullStatusResponse', () => {
expect(read.open[0].closes).toEqual([4])
})
+ it('a closing reference the token may not see drops that reference, not the whole read', () => {
+ const read = parsePullStatusResponse(body([node(1, {
+ closingIssuesReferences: { nodes: [null, { number: 4, repository: { nameWithOwner: 'eneskirca/nodeterm' } }] }
+ })], {
+ errors: [{ type: 'FORBIDDEN', path: ['repository', 'open', 'nodes', 0, 'closingIssuesReferences', 'nodes', 0] }]
+ }), REPO)
+ expect(read.open[0].closes).toEqual([4])
+ expect(read.access).toEqual({ ci: true, merge: true })
+ // Without a permission error explaining it, a null reference is still a malformed answer.
+ expect(() => parsePullStatusResponse(body([node(1, {
+ closingIssuesReferences: { nodes: [null] }
+ })]), REPO)).toThrow(GraphQLShapeError)
+ })
+
it('reports a truncated list', () => {
expect(parsePullStatusResponse(body([node(1)], { totalCount: 60 }), REPO).truncated).toBe(true)
})
diff --git a/src/core/github/graphql-pulls.ts b/src/core/github/graphql-pulls.ts
index d3b9179af..70a2c4577 100644
--- a/src/core/github/graphql-pulls.ts
+++ b/src/core/github/graphql-pulls.ts
@@ -173,6 +173,9 @@ export function parsePullStatusResponse(body: unknown, repository: string): Pull
ci: !permission.some((error) => !error.path || touches(error, ['commits', 'statusCheckRollup'])),
merge: !permission.some((error) => !error.path || touches(error, ['mergeable', 'mergeStateStatus']))
}
+ // A closing reference the token may not see (an issue in a private repository elsewhere) comes back
+ // as a null node plus a FORBIDDEN error. That hides ONE reference — it is not a failed read.
+ const closingHidden = permission.some((error) => touches(error, ['closingIssuesReferences']))
const openConnection = object(repositoryValue.open)
if (!openConnection || !nonNegative(openConnection.totalCount)) throw new GraphQLShapeError()
const repositoryFolded = repository.toLocaleLowerCase('en-US')
@@ -213,6 +216,7 @@ export function parsePullStatusResponse(body: unknown, repository: string): Pull
const closes = node.closingIssuesReferences === null
? []
: list(node.closingIssuesReferences, MAX_CLOSING_ISSUES).flatMap((reference) => {
+ if (reference === null && closingHidden) return []
const issue = object(reference)
const nameWithOwner = object(issue?.repository)?.nameWithOwner
if (!issue || !positive(issue.number) || typeof nameWithOwner !== 'string') {
diff --git a/src/core/github/handlers.test.ts b/src/core/github/handlers.test.ts
index 9d43527c9..d301abc20 100644
--- a/src/core/github/handlers.test.ts
+++ b/src/core/github/handlers.test.ts
@@ -26,7 +26,8 @@ describe('registerGitHubIssueHandlers', () => {
chasePulls: async (...args: unknown[]) => { calls.push(['chase', ...args]); return false },
pullChecks: async (...args: unknown[]) => {
calls.push(['checks', ...args]); return { status: 'no-checks' as const }
- }
+ },
+ claimPullAutoMove: async (...args: unknown[]) => { calls.push(['claim', ...args]); return true }
}
const platform = fakePlatform()
registerGitHubIssueHandlers(platform, service)
@@ -37,13 +38,15 @@ describe('registerGitHubIssueHandlers', () => {
await platform.handlers[IPC.githubIssuesPullStatus]('p1')
await platform.handlers[IPC.githubIssuesChasePulls]('p1')
await platform.handlers[IPC.githubIssuesPullChecks]('p1', 12)
+ await platform.handlers[IPC.githubIssuesClaimPullAutoMove]({ projectId: 'p1', cardId: 'n', pulls: [3] })
expect(calls).toEqual([
['subscribe', 7, { projectId: 'p1' }],
['unsubscribe', 7, 'p1'],
['query', { projectId: 'p1', columnId: null, pageSize: 50 }],
['pullStatus', { projectId: 'p1' }],
['chase', { projectId: 'p1' }],
- ['checks', { projectId: 'p1', pullNumber: 12 }]
+ ['checks', { projectId: 'p1', pullNumber: 12 }],
+ ['claim', { projectId: 'p1', cardId: 'n', pulls: [3] }]
])
expect(Object.keys(platform.handlers).some((channel) => channel.startsWith('githubControl:'))).toBe(false)
})
diff --git a/src/core/github/handlers.ts b/src/core/github/handlers.ts
index fb0204d10..338a67942 100644
--- a/src/core/github/handlers.ts
+++ b/src/core/github/handlers.ts
@@ -26,6 +26,7 @@ export interface GitHubIssueHandlerService {
pullStatus(request: { projectId: string }): Promise<GitHubPullBoard>
chasePulls(request: { projectId: string }): Promise<boolean>
pullChecks(request: { projectId: string; pullNumber: number }): Promise<GitHubPullChecksResult>
+ claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean>
}
export function registerGitHubIssueHandlers(
@@ -50,4 +51,6 @@ export function registerGitHubIssueHandlers(
service.chasePulls({ projectId }))
platform.handle(IPC.githubIssuesPullChecks, (projectId: string, pullNumber: number) =>
service.pullChecks({ projectId, pullNumber }))
+ platform.handle(IPC.githubIssuesClaimPullAutoMove,
+ (request: { projectId: string; cardId: string; pulls: number[] }) => service.claimPullAutoMove(request))
}
diff --git a/src/core/github/pull-memory.test.ts b/src/core/github/pull-memory.test.ts
new file mode 100644
index 000000000..2a4805a61
--- /dev/null
+++ b/src/core/github/pull-memory.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest'
+import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
+import {
+ PULL_MEMORY_MAX,
+ REMEMBERED_MERGE_VISIBLE_MS,
+ claimInMemory,
+ emptyPullMemory,
+ rememberPulls,
+ rememberedForBoard,
+ validPullMemory
+} from './pull-memory'
+
+const status = (number: number, lifecycle: PullLifecycle, over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle, headRefName: `feat/${number}`, closes: [], ...over })
+const none = new Map<number, PullLifecycle>()
+
+describe('rememberPulls', () => {
+ it('a merge counts as observed only after the PR was seen open', () => {
+ const seenOpen = rememberPulls([], [status(1, 'open')], none, 10)
+ expect(seenOpen).toEqual([{ number: 1, headRefName: 'feat/1', lifecycle: 'open', openSeen: true }])
+ const merged = rememberPulls(seenOpen, [status(1, 'merged')], none, 20)
+ expect(merged[0]).toMatchObject({ lifecycle: 'merged', openSeen: true, mergedSeenAt: 20 })
+ // The time is the FIRST observation; seeing it merged again does not move it.
+ expect(rememberPulls(merged, [status(1, 'merged')], none, 30)[0].mergedSeenAt).toBe(20)
+ })
+
+ it('a PR first seen already merged is remembered without an observed merge', () => {
+ expect(rememberPulls([], [status(1, 'merged')], none, 10)[0]).toEqual(
+ { number: 1, headRefName: 'feat/1', lifecycle: 'merged' })
+ })
+
+ it('keeps a PR the read no longer lists — a closed one stays closed', () => {
+ const closed = rememberPulls([], [status(1, 'closed')], none, 10)
+ expect(rememberPulls(closed, [], none, 20)).toEqual(closed)
+ })
+
+ it('refreshes an unlisted PR from the REST harvest, observing its merge', () => {
+ const open = rememberPulls([], [status(1, 'open')], none, 10)
+ const merged = rememberPulls(open, [], new Map([[1, 'merged']]), 50)
+ expect(merged[0]).toMatchObject({ lifecycle: 'merged', mergedSeenAt: 50, headRefName: 'feat/1' })
+ })
+
+ it('is bounded, and keeps unfinished PRs over old finished ones', () => {
+ const many = Array.from({ length: PULL_MEMORY_MAX + 20 }, (_, index) => status(index + 1, 'merged'))
+ const kept = rememberPulls([], [...many, status(1, 'open')], none, 1)
+ expect(kept).toHaveLength(PULL_MEMORY_MAX)
+ expect(kept.some((pull) => pull.number === 1 && pull.lifecycle === 'open')).toBe(true)
+ expect(validPullMemory({ version: 1, pulls: kept, claims: [] })).toBe(true)
+ })
+})
+
+describe('rememberedForBoard', () => {
+ it('shows unlisted open and closed PRs, and merges observed within the window', () => {
+ const memory = [
+ { number: 1, headRefName: 'a', lifecycle: 'closed' as const },
+ { number: 2, headRefName: 'b', lifecycle: 'open' as const, openSeen: true as const },
+ { number: 3, headRefName: 'c', lifecycle: 'merged' as const, openSeen: true as const, mergedSeenAt: 100 },
+ { number: 4, headRefName: 'd', lifecycle: 'merged' as const },
+ { number: 5, headRefName: 'e', lifecycle: 'open' as const }
+ ]
+ expect(rememberedForBoard(memory, new Set([5]), 200).map((pull) => pull.number)).toEqual([1, 2, 3])
+ expect(rememberedForBoard(memory, new Set(), 100 + REMEMBERED_MERGE_VISIBLE_MS).map((pull) => pull.number))
+ .toEqual([1, 2, 5])
+ })
+})
+
+describe('claims', () => {
+ it('the first claim for a key wins', () => {
+ const first = claimInMemory(emptyPullMemory(), 'p|n|1')
+ expect(first.claimed).toBe(true)
+ expect(claimInMemory(first.memory, 'p|n|1').claimed).toBe(false)
+ expect(claimInMemory(first.memory, 'p|n|1,2').claimed).toBe(true)
+ })
+
+ it('rejects a malformed memory file', () => {
+ expect(validPullMemory({ version: 1, pulls: [{ number: -1, headRefName: 'x', lifecycle: 'open' }], claims: [] }))
+ .toBe(false)
+ expect(validPullMemory({ version: 2, pulls: [], claims: [] })).toBe(false)
+ expect(validPullMemory({ version: 1, pulls: [], claims: [3] })).toBe(false)
+ })
+})
diff --git a/src/core/github/pull-memory.ts b/src/core/github/pull-memory.ts
new file mode 100644
index 000000000..dd070786c
--- /dev/null
+++ b/src/core/github/pull-memory.ts
@@ -0,0 +1,148 @@
+// What this machine has OBSERVED about a repository's pull requests, kept across reads and restarts
+// (persisted per identity + repository beside the issue cache, see cache.ts). The GraphQL read only
+// lists the 50 most recently updated open PRs and the 30 most recently finished ones, so without a
+// memory two facts the merge-driven column move depends on would silently expire:
+//
+// - "PR #12 closed without merging" — the card linked to it must stay blocked until the user
+// unlinks it, not until 30 other PRs close and #12 drops out of the `recent` list;
+// - "this machine saw PR #15 open, and later saw it merged" — the only thing that counts as an
+// observed transition. A merge first seen already-merged never moves a card.
+//
+// A remembered PR that neither list covers any more gets its lifecycle from the REST issues harvest
+// (which carries every PR's state), so an old merge is still noticed; one the harvest does not have
+// keeps its last known lifecycle, which for an open PR means "wait" — the safe answer.
+//
+// It also holds CLAIMS: one per (project, card, set of PRs) that has been moved. Every board in every
+// window asks the host before it moves a card, and only the first ask wins — so two Server Edition
+// tabs cannot both move the card, and a card the user dragged back is not moved again for the same
+// merges.
+import type { GitHubPullStatus, PullLifecycle } from '../../shared/github-pull-status'
+
+export interface RememberedPull {
+ number: number
+ headRefName: string
+ crossRepository?: true
+ lifecycle: PullLifecycle
+ openSeen?: true
+ mergedSeenAt?: number
+}
+
+export interface PullMemory {
+ version: 1
+ pulls: RememberedPull[]
+ claims: string[]
+}
+
+export const PULL_MEMORY_MAX = 500
+export const PULL_CLAIMS_MAX = 2_000
+/** A merged PR stays on the board this long after its merge was observed — long enough for a board
+ * opened days later to see the merge and move the card. Older merges are kept only as memory. */
+export const REMEMBERED_MERGE_VISIBLE_MS = 30 * 24 * 60 * 60_000
+
+export function emptyPullMemory(): PullMemory {
+ return { version: 1, pulls: [], claims: [] }
+}
+
+const LIFECYCLES = new Set<PullLifecycle>(['open', 'draft', 'merged', 'closed'])
+
+function validRemembered(value: unknown): value is RememberedPull {
+ if (!value || typeof value !== 'object') return false
+ const pull = value as RememberedPull
+ return Number.isSafeInteger(pull.number) && pull.number > 0 &&
+ typeof pull.headRefName === 'string' && pull.headRefName.length > 0 && pull.headRefName.length <= 255 &&
+ (pull.crossRepository === undefined || pull.crossRepository === true) &&
+ LIFECYCLES.has(pull.lifecycle) &&
+ (pull.openSeen === undefined || pull.openSeen === true) &&
+ (pull.mergedSeenAt === undefined || (Number.isSafeInteger(pull.mergedSeenAt) && pull.mergedSeenAt >= 0))
+}
+
+export function validPullMemory(value: unknown): value is PullMemory {
+ if (!value || typeof value !== 'object') return false
+ const memory = value as PullMemory
+ return memory.version === 1 &&
+ Array.isArray(memory.pulls) && memory.pulls.length <= PULL_MEMORY_MAX && memory.pulls.every(validRemembered) &&
+ Array.isArray(memory.claims) && memory.claims.length <= PULL_CLAIMS_MAX &&
+ memory.claims.every((claim) => typeof claim === 'string' && claim.length <= 1_024)
+}
+
+const UNFINISHED = new Set<PullLifecycle>(['open', 'draft'])
+
+/**
+ * Folds one read into the memory. `listed` is what the GraphQL read returned (open + recent);
+ * remembered PRs it does not list take their lifecycle from `harvest` (the REST snapshot) when it
+ * has them. A merge counts as observed only when this machine had seen the PR open before.
+ */
+export function rememberPulls(
+ previous: RememberedPull[],
+ listed: GitHubPullStatus[],
+ harvest: ReadonlyMap<number, PullLifecycle>,
+ now: number
+): RememberedPull[] {
+ const byNumber = new Map(previous.map((pull) => [pull.number, pull]))
+ const next = new Map<number, RememberedPull>()
+ const apply = (number: number, headRefName: string, crossRepository: boolean, lifecycle: PullLifecycle): void => {
+ const before = byNumber.get(number)
+ const openSeen = !!before?.openSeen || UNFINISHED.has(lifecycle)
+ const mergedSeenAt = before?.mergedSeenAt ??
+ (lifecycle === 'merged' && before?.openSeen ? now : undefined)
+ next.set(number, {
+ number,
+ headRefName,
+ ...(crossRepository ? { crossRepository: true as const } : {}),
+ lifecycle,
+ ...(openSeen ? { openSeen: true as const } : {}),
+ ...(mergedSeenAt !== undefined ? { mergedSeenAt } : {})
+ })
+ }
+ for (const pull of listed) apply(pull.number, pull.headRefName, !!pull.crossRepository, pull.lifecycle)
+ for (const pull of previous) {
+ if (next.has(pull.number)) continue
+ const lifecycle = harvest.get(pull.number) ?? pull.lifecycle
+ apply(pull.number, pull.headRefName, !!pull.crossRepository, lifecycle)
+ }
+ // Bound: unfinished PRs are kept first (dropping one would turn "wait" into "not linked"), then the
+ // newest. An evicted merged PR only loses its place on a board long after it mattered.
+ return [...next.values()]
+ .sort((a, b) => Number(UNFINISHED.has(b.lifecycle)) - Number(UNFINISHED.has(a.lifecycle)) ||
+ b.number - a.number)
+ .slice(0, PULL_MEMORY_MAX)
+}
+
+/** The remembered PRs the board still needs that the read did not list: every unfinished or
+ * closed-unmerged one (a closed PR keeps blocking its card until unlinked), and merges observed
+ * within `REMEMBERED_MERGE_VISIBLE_MS`. */
+export function rememberedForBoard(
+ memory: RememberedPull[],
+ listed: ReadonlySet<number>,
+ now: number
+): GitHubPullStatus[] {
+ return memory
+ .filter((pull) => !listed.has(pull.number))
+ .filter((pull) => pull.lifecycle !== 'merged' ||
+ (pull.mergedSeenAt !== undefined && now - pull.mergedSeenAt < REMEMBERED_MERGE_VISIBLE_MS))
+ .map((pull): GitHubPullStatus => ({
+ number: pull.number,
+ lifecycle: pull.lifecycle,
+ headRefName: pull.headRefName,
+ ...(pull.crossRepository ? { crossRepository: true as const } : {}),
+ closes: [],
+ ...(pull.openSeen ? { openSeen: true as const } : {}),
+ ...(pull.mergedSeenAt !== undefined ? { mergedSeenAt: pull.mergedSeenAt } : {})
+ }))
+}
+
+/** A listed status with what the memory knows about it. */
+export function withObservations(status: GitHubPullStatus, remembered: RememberedPull | undefined): GitHubPullStatus {
+ if (!remembered) return status
+ return {
+ ...status,
+ ...(remembered.openSeen ? { openSeen: true as const } : {}),
+ ...(remembered.mergedSeenAt !== undefined ? { mergedSeenAt: remembered.mergedSeenAt } : {})
+ }
+}
+
+/** Records a claim; `claimed` is false when it was already there. */
+export function claimInMemory(memory: PullMemory, key: string): { memory: PullMemory; claimed: boolean } {
+ if (memory.claims.includes(key)) return { memory, claimed: false }
+ return { memory: { ...memory, claims: [...memory.claims, key].slice(-PULL_CLAIMS_MAX) }, claimed: true }
+}
diff --git a/src/core/github/pull-status-tracker.test.ts b/src/core/github/pull-status-tracker.test.ts
index 6a7b81c12..b17029070 100644
--- a/src/core/github/pull-status-tracker.test.ts
+++ b/src/core/github/pull-status-tracker.test.ts
@@ -4,6 +4,7 @@ import { GitHubRequestCoordinator } from './request-coordinator'
import type { PullStatusRead } from './graphql-pulls'
import { PULL_CHASE_MAX } from '../../shared/github-pull-status'
import type { PullStatusFacts } from '../../shared/github-pull-status'
+import { emptyPullMemory, type PullMemory } from './pull-memory'
const HEAD = 'a'.repeat(40)
const KEY = 'user-1\0o/r'
@@ -19,14 +20,34 @@ function read(open: PullStatusFacts[], over: Partial<PullStatusRead> = {}): Pull
return { open, recent: [], access: { ci: true, merge: true }, truncated: false, ...over }
}
-function tracker(start = 0) {
+/** An on-disk memory stand-in shared across tracker instances (an app restart = a new tracker). */
+function memoryStore() {
+ const files = new Map<string, PullMemory>()
+ const saves: PullMemory[] = []
+ return {
+ files,
+ saves,
+ load: async (userId: string, repository: string) =>
+ structuredClone(files.get(`${userId}\0${repository}`) ?? emptyPullMemory()),
+ save: async (userId: string, repository: string, memory: PullMemory) => {
+ saves.push(structuredClone(memory))
+ files.set(`${userId}\0${repository}`, structuredClone(memory))
+ }
+ }
+}
+
+function tracker(start = 0, store = memoryStore()) {
let now = start
const changes: number[][] = []
const coordinator = new GitHubRequestCoordinator({ now: () => now })
const subject = new GitHubPullStatusTracker({
- coordinator, now: () => now, onChanged: (_key, numbers) => changes.push(numbers)
+ coordinator, now: () => now, onChanged: (_key, numbers) => changes.push(numbers), memory: store
})
- return { subject, coordinator, changes, advance: (ms: number) => { now += ms }, at: () => now }
+ return { subject, coordinator, changes, store, advance: (ms: number) => { now += ms }, at: () => now }
+}
+
+async function settleSaves(): Promise<void> {
+ for (let index = 0; index < 10; index++) await Promise.resolve()
}
describe('GitHubPullStatusTracker', () => {
@@ -156,4 +177,96 @@ describe('GitHubPullStatusTracker', () => {
read([facts(1, { headRefOid: pushed, rollup: 'SUCCESS', rollupOid: HEAD })]))
expect(subject.board(KEY).pulls[0]).toMatchObject({ headRefOid: pushed, ci: 'pending' })
})
+
+ describe('memory', () => {
+ it('a PR closed without merging stays on the board after it leaves the recent list', async () => {
+ const { subject } = tracker()
+ await subject.read(KEY, 'user-1', 'heartbeat', async () => read([], {
+ recent: [{ number: 12, headRefName: 'feat/x', crossRepository: false, lifecycle: 'closed' }]
+ }))
+ // Thirty newer PRs closed: #12 is no longer in the read at all.
+ await subject.read(KEY, 'user-1', 'foreground', async () => read([]))
+ expect(subject.board(KEY).pulls).toEqual([
+ { number: 12, lifecycle: 'closed', headRefName: 'feat/x', closes: [] }
+ ])
+ })
+
+ it('marks a merge as observed only when it had seen the PR open, and remembers it across a restart', async () => {
+ const store = memoryStore()
+ const first = tracker(100, store)
+ await first.subject.read(KEY, 'user-1', 'heartbeat', async () => read([facts(1, { headRefName: 'feat/x' })]))
+ await settleSaves()
+ // An app restart: a new tracker over the same stored memory, and #1 has merged meanwhile.
+ const second = tracker(500, store)
+ await second.subject.read(KEY, 'user-1', 'heartbeat', async () => read([], {
+ recent: [{ number: 1, headRefName: 'feat/x', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ expect(second.subject.board(KEY).pulls[0]).toMatchObject({ number: 1, lifecycle: 'merged', openSeen: true, mergedSeenAt: 500 })
+ // A merge this machine never saw open carries no observation.
+ await second.subject.read(KEY, 'user-1', 'foreground', async () => read([], {
+ recent: [{ number: 2, headRefName: 'feat/y', crossRepository: false, lifecycle: 'merged' }]
+ }))
+ expect(second.subject.board(KEY).pulls.find((pull) => pull.number === 2)).not.toHaveProperty('mergedSeenAt')
+ })
+
+ it('a claim is won once, across concurrent asks and across a restart', async () => {
+ const store = memoryStore()
+ const { subject } = tracker(0, store)
+ const answers = await Promise.all([subject.claim(KEY, 'p\u0000n\u00001'), subject.claim(KEY, 'p\u0000n\u00001')])
+ expect(answers.sort()).toEqual([false, true])
+ await settleSaves()
+ const restarted = tracker(0, store)
+ expect(await restarted.subject.claim(KEY, 'p\u0000n\u00001')).toBe(false)
+ expect(await restarted.subject.claim(KEY, 'p\u0000n\u00002')).toBe(true)
+ })
+
+ it('a save queued behind a slow one is dropped once the repository is forgotten', async () => {
+ const store = memoryStore()
+ let releaseFirst!: () => void
+ const firstSave = new Promise<void>((resolve) => { releaseFirst = resolve })
+ const save = store.save
+ let calls = 0
+ store.save = async (...args) => {
+ calls += 1
+ if (calls === 1) await firstSave
+ return save(...args)
+ }
+ const { subject } = tracker(0, store)
+ expect(await subject.claim(KEY, 'one')).toBe(true)
+ expect(await subject.claim(KEY, 'two')).toBe(true)
+ const forgotten = subject.forgetRepository('o/r')
+ releaseFirst()
+ await forgotten
+ expect(calls).toBe(1)
+ expect(store.saves).toHaveLength(1)
+ })
+
+ it('nothing started before a cache clear writes the memory back', async () => {
+ const store = memoryStore()
+ const { subject } = tracker(0, store)
+ let release!: (value: PullStatusRead) => void
+ const pending = subject.read(KEY, 'user-1', 'heartbeat', () => new Promise((resolve) => { release = resolve }))
+ await subject.forgetRepository('o/r')
+ release(read([facts(1)]))
+ await pending
+ await settleSaves()
+ expect(store.saves).toEqual([])
+ })
+ })
+
+ it('the chase read that spends the last attempt tells the boards at once', async () => {
+ const { subject, advance, changes } = tracker()
+ const undecided = async () => read([facts(1, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })])
+ await subject.read(KEY, 'user-1', 'heartbeat', undecided)
+ for (let attempt = 0; attempt < PULL_CHASE_MAX - 1; attempt++) {
+ advance(300_000)
+ expect(subject.claimChase(KEY)).toBe(true)
+ await subject.read(KEY, 'user-1', 'chase', undecided)
+ }
+ changes.length = 0
+ advance(300_000)
+ expect(subject.claimChase(KEY)).toBe(true)
+ expect(changes).toEqual([[]])
+ expect(subject.board(KEY).undecided).toBe(false)
+ })
})
diff --git a/src/core/github/pull-status-tracker.ts b/src/core/github/pull-status-tracker.ts
index c7bd0a9c0..676fba8d3 100644
--- a/src/core/github/pull-status-tracker.ts
+++ b/src/core/github/pull-status-tracker.ts
@@ -3,8 +3,8 @@
// owns only the decisions, so each rule can be pressed by a test without a network.
//
// WHEN a read happens — nothing else triggers one:
-// 1. The issues heartbeat (Wave 1) reported a change. A push, a merge, a label, a comment all move
-// the repository's most recently updated item; a finished check run does NOT, which is why:
+// 1. The issues heartbeat reported a change. A push, a merge, a label, a comment all move the
+// repository's most recently updated item; a finished check run does NOT, which is why:
// 2. An undecided PR (mergeability UNKNOWN, or a rollup still PENDING) is CHASED — 30 s, 1 min,
// 2 min, then 5 min, at most 12 reads per episode — and only while a board is VISIBLE. The
// renderer asserts visibility by asking (`claimChase`); a hidden or closed board stops asking.
@@ -13,6 +13,9 @@
//
// A read the budget holds is skipped, never queued, and remembered as owed; a failed read keeps the
// last snapshot and marks it stale. Neither blanks what the board shows.
+//
+// Every read is also folded into the repository's persisted MEMORY (pull-memory.ts): what this
+// machine has observed about each PR, and the one-time claims the merge-driven column move takes.
import {
EMPTY_PULL_BOARD,
PULL_CHASE_MAX,
@@ -21,9 +24,18 @@ import {
pullStatusFrom,
type GitHubPullBoard,
type GitHubPullStatus,
- type PullChaseState
+ type PullChaseState,
+ type PullLifecycle
} from '../../shared/github-pull-status'
import type { PullStatusRead } from './graphql-pulls'
+import {
+ claimInMemory,
+ emptyPullMemory,
+ rememberPulls,
+ rememberedForBoard,
+ withObservations,
+ type PullMemory
+} from './pull-memory'
import type { GitHubRequestCoordinator } from './request-coordinator'
export type PullReadReason = 'heartbeat' | 'foreground' | 'chase'
@@ -38,8 +50,12 @@ type PullRepositoryState = {
/** A read was skipped by the rate budget; the next opportunity reads even if nothing changed. */
owed: boolean
inFlight?: Promise<void>
- /** Bumped by `forget` so a read in flight when the cache was cleared cannot publish. */
+ /** Bumped by `forgetRepository` so nothing started before a cache clear can publish or persist. */
generation: number
+ memory?: PullMemory
+ memoryLoad?: Promise<PullMemory>
+ /** Saves run one after another, so the file always ends at the latest memory. */
+ saving: Promise<void>
}
type TrackerOptions = {
@@ -47,16 +63,28 @@ type TrackerOptions = {
now?: () => number
/** Something the board shows changed for this repository key. */
onChanged: (key: string, changedPullNumbers: number[]) => void
+ /** Persistence for the memory; absent = memory lives for this process only. */
+ memory?: {
+ load(userId: string, repository: string): Promise<PullMemory>
+ save(userId: string, repository: string, memory: PullMemory): Promise<void>
+ }
+ /** Every PR's lifecycle from the REST issues harvest, for remembered PRs the GraphQL read no
+ * longer lists. */
+ harvest?: (key: string) => ReadonlyMap<number, PullLifecycle>
}
-/** Why a read did not produce a snapshot. `hidden` is an ANSWER (the token may not read these
- * fields), not a failure. */
function errorCode(error: unknown): string | undefined {
return error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'
? (error as { code: string }).code
: undefined
}
+/** Repository keys are `${userId}\0${repository}` — the issue service's own key. */
+function splitKey(key: string): [string, string] {
+ const at = key.indexOf('\0')
+ return [key.slice(0, at), key.slice(at + 1)]
+}
+
export class GitHubPullStatusTracker {
private readonly states = new Map<string, PullRepositoryState>()
private readonly now: () => number
@@ -88,22 +116,48 @@ export class GitHubPullStatusTracker {
/**
* Claims one chase read, synchronously, so two boards asking at once cannot both spend it. True
* means the caller must now `read(…, 'chase')`. The attempt is counted HERE, before the read: a
- * chase read that fails still spends one of the twelve.
+ * chase read that fails still spends one of the twelve. The claim that spends the last one tells
+ * the boards at once, so they stop asking.
*/
claimChase(key: string): boolean {
const state = this.states.get(key)
if (!state || state.inFlight || !pullChaseDue(state.chase, this.now())) return false
state.chase = { ...state.chase!, attempts: state.chase!.attempts + 1, lastReadAt: this.now() }
+ if (state.chase.attempts >= PULL_CHASE_MAX) this.options.onChanged(key, [])
+ return true
+ }
+
+ /**
+ * The one-time permission to move a card for a set of merged PRs. The first caller for a key wins,
+ * whichever window it comes from, and the claim is persisted — a card the user dragged back is not
+ * moved again for the same merges.
+ */
+ async claim(key: string, claimKey: string): Promise<boolean> {
+ const state = this.stateFor(key)
+ const generation = state.generation
+ const memory = await this.memoryFor(key, state)
+ if (generation !== state.generation) return false
+ const { memory: next, claimed } = claimInMemory(state.memory ?? memory, claimKey)
+ if (!claimed) return false
+ state.memory = next
+ this.persist(key, state)
return true
}
- /** Drops every repository state for `repository` (a cache clear or revoke). */
- forgetRepository(repository: string): void {
+ /**
+ * Drops every repository state for `repository` (a cache clear or revoke). Resolves once any save
+ * already under way has finished, so a caller deleting the file afterwards cannot have it written
+ * back by a save that started before.
+ */
+ forgetRepository(repository: string): Promise<void> {
+ const pending: Promise<void>[] = []
for (const [key, state] of this.states) {
if (!key.endsWith(`\0${repository}`)) continue
state.generation += 1
+ pending.push(state.saving)
this.states.delete(key)
}
+ return Promise.all(pending).then(() => undefined)
}
/**
@@ -119,8 +173,8 @@ export class GitHubPullStatusTracker {
): Promise<void> {
const state = this.stateFor(key)
if (state.inFlight) return state.inFlight
- // Background reads (heartbeat, chase) respect the whole budget, including the floor Wave 1 keeps
- // for the user's own tools. A read the user asked for respects only a hard limit.
+ // Background reads (heartbeat, chase) respect the whole budget, including the floor kept for
+ // the user's own tools. A read the user asked for respects only a hard limit.
const throttle = this.options.coordinator.throttle(userId, this.now(), 'graphql')
if (throttle && (reason !== 'foreground' || throttle.kind === 'rate-limited')) {
state.owed = true
@@ -153,7 +207,7 @@ export class GitHubPullStatusTracker {
return
}
if (code === 'insufficient-permission') {
- this.publish(key, state, {
+ await this.publish(key, state, generation, {
open: [], recent: [], access: { ci: false, merge: false }, truncated: false
}, userId)
return
@@ -166,10 +220,18 @@ export class GitHubPullStatusTracker {
return
}
if (generation !== state.generation) return
- this.publish(key, state, result, userId)
+ await this.publish(key, state, generation, result, userId)
}
- private publish(key: string, state: PullRepositoryState, result: PullStatusRead, userId: string): void {
+ private async publish(
+ key: string,
+ state: PullRepositoryState,
+ generation: number,
+ result: PullStatusRead,
+ userId: string
+ ): Promise<void> {
+ const memory = await this.memoryFor(key, state)
+ if (generation !== state.generation) return
const now = this.now()
if (result.rateLimit) {
// The body's own reading, in case a proxy stripped the headers the client already fed in.
@@ -192,7 +254,17 @@ export class GitHubPullStatusTracker {
...(pull.crossRepository ? { crossRepository: true as const } : {}),
closes: []
}))
- const pulls = [...open, ...finished]
+ const listed = [...open, ...finished]
+ const remembered = rememberPulls(memory.pulls, listed, this.options.harvest?.(key) ?? new Map(), now)
+ if (JSON.stringify(remembered) !== JSON.stringify(memory.pulls)) {
+ state.memory = { ...(state.memory ?? memory), pulls: remembered }
+ this.persist(key, state)
+ }
+ const rememberedByNumber = new Map(remembered.map((pull) => [pull.number, pull]))
+ const pulls = [
+ ...listed.map((pull) => withObservations(pull, rememberedByNumber.get(pull.number))),
+ ...rememberedForBoard(remembered, new Set(listed.map((pull) => pull.number)), now)
+ ]
const nextNumbers = new Set(pulls.map((pull) => pull.number))
const changed = [
...pulls.filter((pull) => JSON.stringify(pull) !== JSON.stringify(previous.get(pull.number)))
@@ -213,12 +285,38 @@ export class GitHubPullStatusTracker {
if (changed.length || accessChanged || wasStale || chaseChanged) this.options.onChanged(key, changed)
}
+ private memoryFor(key: string, state: PullRepositoryState): Promise<PullMemory> {
+ if (state.memory) return Promise.resolve(state.memory)
+ if (!state.memoryLoad) {
+ const [userId, repository] = splitKey(key)
+ state.memoryLoad = (this.options.memory
+ ? this.options.memory.load(userId, repository)
+ : Promise.resolve(emptyPullMemory())).catch(() => emptyPullMemory())
+ }
+ return state.memoryLoad.then((loaded) => {
+ if (!state.memory) state.memory = loaded
+ return state.memory
+ })
+ }
+
+ private persist(key: string, state: PullRepositoryState): void {
+ const save = this.options.memory?.save
+ if (!save) return
+ const [userId, repository] = splitKey(key)
+ const generation = state.generation
+ state.saving = state.saving.then(async () => {
+ // Written at its turn with the LATEST memory, and never after the repository was forgotten.
+ if (generation !== state.generation || !state.memory) return
+ await save(userId, repository, state.memory)
+ }).catch(() => undefined)
+ }
+
private stateFor(key: string): PullRepositoryState {
let state = this.states.get(key)
if (!state) {
state = {
pulls: [], stale: false, access: { ci: true, merge: true }, truncated: false,
- chase: null, owed: false, generation: 0
+ chase: null, owed: false, generation: 0, saving: Promise.resolve()
}
this.states.set(key, state)
}
diff --git a/src/core/github/service.pulls.test.ts b/src/core/github/service.pulls.test.ts
index 750978890..a146e2afe 100644
--- a/src/core/github/service.pulls.test.ts
+++ b/src/core/github/service.pulls.test.ts
@@ -37,8 +37,12 @@ class PullClient implements GitHubIssuesClientLike {
failChecks?: Error
async listIssues() { return { items: [] as GitHubIssue[] } }
+ /** Runs inside the heartbeat — lets a test change the configuration between the heartbeat and the
+ * pull status read that follows it. */
+ onHeartbeat?: () => void
async issuesHeartbeat(_repository: string, etag?: string): Promise<IssueHeartbeatResult> {
this.heartbeats += 1
+ this.onHeartbeat?.()
if (this.changed || !etag) { this.changed = false; return { notModified: false, etag: `W/"${Math.random()}"` } }
return { notModified: true, etag }
}
@@ -59,9 +63,10 @@ class PullClient implements GitHubIssuesClientLike {
}
}
-function context(client: PullClient): GitHubIssueServiceContext {
+function context(client: PullClient, revision = config.revision): GitHubIssueServiceContext {
return {
- localApprovalId: 'local-1', projectId: 'project-1', repository: 'o/r', config, controlRevision: 1,
+ localApprovalId: 'local-1', projectId: 'project-1', repository: 'o/r', config: { ...config, revision },
+ controlRevision: 1,
credentialGeneration: 1, userId: 'user-1', client, columnColors: {}, mappingApproved: true
}
}
@@ -76,10 +81,11 @@ function harness(client = new PullClient()) {
let now = 1_000_000
let poll: (() => void) | undefined
let contexts = 0
+ let revision = config.revision
const service = new GitHubIssueService({
cache: new GitHubIssueCache(userDataDir),
coordinator: new GitHubRequestCoordinator({ now: () => now }),
- contextForProject: async () => { contexts += 1; return context(client) },
+ contextForProject: async () => { contexts += 1; return context(client, revision) },
now: () => now,
setInterval: (fn) => { poll = fn; return 1 },
clearInterval: () => { poll = undefined }
@@ -88,7 +94,8 @@ function harness(client = new PullClient()) {
client, service,
advance: (ms: number) => { now += ms },
poll: async () => { poll?.(); await flush() },
- contexts: () => contexts
+ contexts: () => contexts,
+ setRevision: (next: string) => { revision = next }
}
}
@@ -179,11 +186,53 @@ describe('GitHubIssueService pull status', () => {
expect(h.client.checkReads).toBe(0)
})
- it('clearing the cache forgets pull status', async () => {
+ it('clearing the cache forgets pull status and deletes its memory file', async () => {
const h = harness()
await h.service.subscribe(7, { projectId: 'project-1' })
- await flush()
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ const memoryDir = path.join(userDataDir, 'github-pull-memory')
+ await vi.waitFor(async () => expect(await fs.readdir(memoryDir).catch(() => [])).toHaveLength(1))
await h.service.clearCache({ projectId: 'project-1' })
+ expect(await fs.readdir(memoryDir).catch(() => [])).toEqual([])
+ // Bind the same identity again with a read that never answers: nothing from before the clear may
+ // come back under that key.
+ h.client.pullRequestStatuses = () => new Promise(() => undefined)
+ h.advance(120_000)
+ await h.service.refresh({ projectId: 'project-1' })
+ await flush()
expect((await h.service.pullStatus({ projectId: 'project-1' })).pulls).toEqual([])
})
+
+ it('a configuration change between the heartbeat and the read is not a failed read', async () => {
+ const h = harness()
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ h.client.changed = true
+ h.client.onHeartbeat = () => h.setRevision('mapping-2')
+ h.advance(120_000)
+ await h.service.refresh({ projectId: 'project-1' })
+ await flush()
+ expect(h.client.statusReads).toBe(1)
+ expect((await h.service.pullStatus({ projectId: 'project-1' })).stale).toBe(false)
+ })
+
+ it('a move claim is won once, and malformed asks are refused', async () => {
+ const h = harness()
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [1] })).toBe(false)
+ await h.service.subscribe(7, { projectId: 'project-1' })
+ await vi.waitFor(() => expect(h.client.statusReads).toBe(1))
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [2, 1] })).toBe(true)
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'n', pulls: [1, 2] })).toBe(false)
+ expect(await h.service.claimPullAutoMove({ projectId: 'project-1', cardId: 'other', pulls: [1, 2] })).toBe(true)
+ for (const bad of [
+ { projectId: 'project-1', cardId: '', pulls: [1] },
+ { projectId: 'project-1', cardId: 'x'.repeat(300), pulls: [1] },
+ { projectId: 'project-1', cardId: 'n\u0001', pulls: [1] },
+ { projectId: 'project-1', cardId: 'n', pulls: [] },
+ { projectId: 'project-1', cardId: 'n', pulls: [0] },
+ null
+ ]) {
+ expect(await h.service.claimPullAutoMove(bad as never)).toBe(false)
+ }
+ })
})
diff --git a/src/core/github/service.ts b/src/core/github/service.ts
index 665f396f4..2392301e7 100644
--- a/src/core/github/service.ts
+++ b/src/core/github/service.ts
@@ -26,7 +26,7 @@ import { classifyGitHubFailure } from './failure'
import type { GitHubRequestCoordinator } from './request-coordinator'
import type { PullStatusRead } from './graphql-pulls'
import { GitHubPullStatusTracker } from './pull-status-tracker'
-import type { GitHubPullBoard, GitHubPullChecksResult } from '../../shared/github-pull-status'
+import type { GitHubPullBoard, GitHubPullChecksResult, PullLifecycle } from '../../shared/github-pull-status'
const MAX_ISSUES = 10_000
const MAX_CACHE_BYTES = 64 * 1024 * 1024
@@ -237,6 +237,20 @@ export class GitHubIssueService {
onChanged: (key, changed) => {
const state = this.repositories.get(key)
if (state) this.emitDelta(state, changed, true)
+ },
+ memory: {
+ load: (userId, repository) => options.cache.loadPullMemory(userId, repository),
+ save: (userId, repository, memory) => options.cache.savePullMemory(userId, repository, memory)
+ },
+ harvest: (key) => {
+ const lifecycles = new Map<number, PullLifecycle>()
+ for (const item of this.repositories.get(key)?.snapshot?.issues ?? []) {
+ if (!item.pull) continue
+ lifecycles.set(item.number, item.state === 'closed'
+ ? item.pull.mergedAt ? 'merged' : 'closed'
+ : item.pull.draft ? 'draft' : 'open')
+ }
+ return lifecycles
}
})
}
@@ -670,10 +684,12 @@ export class GitHubIssueService {
await Promise.allSettled([
...this.statePreparations.get(context.repository) ?? [],
...affected.flatMap((state) => state.refresh ? [state.refresh] : []),
- ...mutations
+ ...mutations,
+ // Forgotten BEFORE the files go, and waited for: a memory save already under way would
+ // otherwise write the pull memory back after clearBound deleted it.
+ this.pulls.forgetRepository(context.repository)
])
await this.options.cache.clearBound(context.localApprovalId, context.projectId, context.repository)
- this.pulls.forgetRepository(context.repository)
for (const state of this.repositoryStates(context.localApprovalId, context.repository)) {
state.cacheGeneration += 1
state.snapshot = undefined
@@ -715,6 +731,24 @@ export class GitHubIssueService {
return true
}
+ /**
+ * The one-time permission for the board to move `cardId` because every PR in `pulls` merged. The
+ * first ask wins across every window (two Server Edition tabs cannot both move it), and it is
+ * remembered, so a card the user dragged back is not moved again for the same merges. It sends no
+ * request and resolves no credential.
+ */
+ async claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean> {
+ const { projectId, cardId, pulls } = request ?? {}
+ if (typeof projectId !== 'string' || typeof cardId !== 'string' || !cardId || cardId.length > 256 ||
+ /[\u0000-\u001f]/.test(cardId) || !Array.isArray(pulls) || pulls.length === 0 || pulls.length > 100 ||
+ pulls.some((pull) => !Number.isSafeInteger(pull) || pull < 1)) return false
+ const key = this.projectKeys.get(projectId)
+ if (!key || key.startsWith('unbound:')) return false
+ if (this.repositoryControl(key.slice(key.indexOf('\0') + 1)).deletion) return false
+ const numbers = [...new Set(pulls)].sort((a, b) => a - b).join(',')
+ return this.pulls.claim(key, `${projectId}\0${cardId}\0${numbers}`)
+ }
+
/** Per-check detail for one PR, read when its modal opens. Never throws: every failure is one of
* the result's own statuses, so a modal can always say what it knows. */
async pullChecks(request: { projectId: string; pullNumber: number }): Promise<GitHubPullChecksResult> {
@@ -1197,5 +1231,9 @@ export class GitHubIssueService {
}
}
-class ConfigurationChangedError extends Error {}
+/** Carries a `code` like every other error the pull status tracker reads: a context that changed
+ * mid-read is not a failed read, and must not mark the board stale. */
+class ConfigurationChangedError extends Error {
+ readonly code = 'configuration-changed'
+}
class RepositoryClearedError extends Error {}
diff --git a/src/main/remote/relay-project-scope.ts b/src/main/remote/relay-project-scope.ts
index 517372b63..e54828e99 100644
--- a/src/main/remote/relay-project-scope.ts
+++ b/src/main/remote/relay-project-scope.ts
@@ -48,6 +48,7 @@ const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {
[IPC.githubIssuesPullStatus]: fromFirstArg,
[IPC.githubIssuesChasePulls]: fromFirstArg,
[IPC.githubIssuesPullChecks]: fromFirstArg,
+ [IPC.githubIssuesClaimPullAutoMove]: fromFirstArgField,
[IPC.boardLogAppend]: fromFirstArg,
[IPC.boardLogRead]: fromFirstArg,
[IPC.boardLogSubscribe]: fromFirstArg,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index c17aad03f..53d00f0a9 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -232,6 +232,7 @@ const api: NodeTerminalApi = {
chasePulls: (projectId) => ipcRenderer.invoke(IPC.githubIssuesChasePulls, projectId),
pullChecks: (projectId, pullNumber) =>
ipcRenderer.invoke(IPC.githubIssuesPullChecks, projectId, pullNumber),
+ claimPullAutoMove: (request) => ipcRenderer.invoke(IPC.githubIssuesClaimPullAutoMove, request),
projectAvatar: (projectId) => ipcRenderer.invoke(IPC.githubProjectAvatar, projectId),
onChanged: (projectId, listener) => {
const channel = IPC.githubIssuesChanged(projectId)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 79536e886..7e08c53bf 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -462,6 +462,8 @@ export function buildGitHubApi(
client.request(IPC.githubIssuesPullChecks, projectId, pullNumber) as ReturnType<
GitHubIssuesApi['pullChecks']
>,
+ claimPullAutoMove: (request) =>
+ client.request(IPC.githubIssuesClaimPullAutoMove, request) as Promise<boolean>,
projectAvatar: (projectId) =>
client.request(IPC.githubProjectAvatar, projectId) as ReturnType<
GitHubIssuesApi['projectAvatar']
diff --git a/src/renderer/components/kanban/CardPullRequests.test.tsx b/src/renderer/components/kanban/CardPullRequests.test.tsx
index 834e768f6..d7c7a8d66 100644
--- a/src/renderer/components/kanban/CardPullRequests.test.tsx
+++ b/src/renderer/components/kanban/CardPullRequests.test.tsx
@@ -40,9 +40,9 @@ function setup(ssh = false): void {
}]
} as never)
useGitHubIssues.setState({ projects: { p1: { pullBoard } as never } })
- useSettings.setState((state) => ({
- settings: { ...state.settings, kanbanPullAutoMove: { projects: { p1: { columnId: 'done' } } } }
- }))
+ useSettings.setState({
+ settings: { ...useSettings.getState().settings, kanbanPullAutoMove: { projects: { p1: { columnId: 'done', armedAt: 1 } } } }
+ })
}
function render(k: ProjectKanban, card = session()): { host: HTMLElement; onChange: ReturnType<typeof vi.fn> } {
diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
index 48b4eec34..f3088ffe1 100644
--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
@@ -132,7 +132,13 @@ export function GitHubIssueSummaryModal({
{closingPulls.map((pull) => <PullRefChip key={pull.number} status={pull} freshness={pullFreshness} />)}
</div>
)}
- {isPull && pullOpen && <PullChecks result={checks} onOpen={(url) => void api.shell.openExternal(url)} />}
+ {isPull && pullOpen && (
+ <PullChecks
+ result={checks}
+ expectedHead={pullStatus?.headRefOid}
+ onOpen={(url) => void api.shell.openExternal(url)}
+ />
+ )}
<div className="github-issue-modal__body">
{issue.body.trim() || 'No description provided.'}
</div>
@@ -168,17 +174,21 @@ const CHECK_GLYPH = { passed: '✓', failed: '✗', pending: '●', skipped: '
/** The checks list. A token that may not read checks (`hidden`) shows NOTHING, and a commit with no
* checks says so in words — never a green tick for checks that do not exist. */
-function PullChecks({
+export function PullChecks({
result,
+ expectedHead,
onOpen
}: {
result: GitHubPullChecksResult | 'loading' | null
+ /** The head the status line above describes. Checks read at another commit are not shown under
+ * it (the host may answer from a read taken a few seconds before a push). */
+ expectedHead?: string
onOpen: (url: string) => void
}): React.JSX.Element | null {
if (result === null || (result !== 'loading' && result.status === 'hidden')) return null
if (result === 'loading') return <p className="pull-checks__note">Loading checks…</p>
if (result.status === 'no-checks') return <p className="pull-checks__note">No checks on the head commit.</p>
- if (result.status === 'moved') return <p className="pull-checks__note">The branch moved while reading its checks. Reopen to see the new commit's.</p>
+ if (result.status === 'moved' || (result.status === 'ok' && expectedHead && result.headRefOid !== expectedHead)) return <p className="pull-checks__note">The branch moved while reading its checks. Reopen to see the new commit's.</p>
if (result.status === 'unavailable') return <p className="pull-checks__note">Checks could not be read from GitHub.</p>
return (
<ul className="pull-checks" aria-label="Checks">
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index 348e8bea8..fc104adfc 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -392,6 +392,7 @@ export const KanbanView = memo(function KanbanView({
[onAutoMoveFromPulls, projectId]
)
usePullAutoMove({
+ api: api.githubIssues,
projectId,
cards: sessions,
board,
diff --git a/src/renderer/components/kanban/PullChecks.test.tsx b/src/renderer/components/kanban/PullChecks.test.tsx
new file mode 100644
index 000000000..b3e7c1b8c
--- /dev/null
+++ b/src/renderer/components/kanban/PullChecks.test.tsx
@@ -0,0 +1,40 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { describe, expect, it, vi } from 'vitest'
+import type { GitHubPullChecksResult } from '@shared/github-pull-status'
+import { PullChecks } from './GitHubIssueSummaryModal'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const HEAD = 'a'.repeat(40)
+const ok: GitHubPullChecksResult = {
+ status: 'ok', headRefOid: HEAD, truncated: false,
+ checks: [{ name: 'quality', state: 'passed', url: 'https://github.com/x/1' }, { name: 'windows', state: 'failed' }]
+}
+
+function render(result: GitHubPullChecksResult | 'loading' | null, expectedHead?: string): HTMLElement {
+ const host = document.createElement('div')
+ act(() => createRoot(host).render(<PullChecks result={result} expectedHead={expectedHead} onOpen={vi.fn()} />))
+ return host
+}
+
+describe('PullChecks', () => {
+ it('lists the checks read at the head the status line shows', () => {
+ const host = render(ok, HEAD)
+ expect(host.textContent).toContain('quality')
+ expect(host.textContent).toContain('windows')
+ })
+
+ it('never shows checks from another commit under the current head', () => {
+ const host = render(ok, 'b'.repeat(40))
+ expect(host.textContent).not.toContain('quality')
+ expect(host.textContent).toContain('branch moved')
+ })
+
+ it('shows nothing when the token may not read checks, and says so in words when there are none', () => {
+ expect(render({ status: 'hidden' }, HEAD).textContent).toBe('')
+ expect(render({ status: 'no-checks' }, HEAD).textContent).toContain('No checks')
+ expect(render({ status: 'no-checks' }, HEAD).textContent).not.toContain('✓')
+ })
+})
diff --git a/src/renderer/components/kanban/usePullAutoMove.test.tsx b/src/renderer/components/kanban/usePullAutoMove.test.tsx
index 42bacf079..38c123c5a 100644
--- a/src/renderer/components/kanban/usePullAutoMove.test.tsx
+++ b/src/renderer/components/kanban/usePullAutoMove.test.tsx
@@ -17,12 +17,29 @@ const board: ProjectKanban = {
}
const cards = [{ id: 'card-1', kind: 'terminal', worktreeBranch: 'feat/x' }]
const merged: GitHubPullBoard = {
- pulls: [{ number: 12, lifecycle: 'merged', headRefName: 'feat/x', closes: [] }],
+ pulls: [{ number: 12, lifecycle: 'merged', headRefName: 'feat/x', closes: [], openSeen: true, mergedSeenAt: 2_000 }],
observedAt: 1, stale: false, access: { ci: true, merge: true }, undecided: false, truncated: false
}
-function Probe(props: { pullBoard: GitHubPullBoard; onAutoMove: (...args: unknown[]) => void }): null {
- usePullAutoMove({ projectId: 'p1', cards, board, pullBoard: props.pullBoard, onAutoMove: props.onAutoMove })
+/** The host's claim: the first ask for a key wins, like GitHubPullStatusTracker.claim. */
+function hostClaims() {
+ const claimed = new Set<string>()
+ return {
+ claimPullAutoMove: vi.fn(async (request: { projectId: string; cardId: string; pulls: number[] }) => {
+ const key = `${request.projectId}:${request.cardId}:${request.pulls.join(',')}`
+ if (claimed.has(key)) return false
+ claimed.add(key)
+ return true
+ })
+ }
+}
+
+function Probe(props: {
+ api: ReturnType<typeof hostClaims>
+ pullBoard: GitHubPullBoard
+ onAutoMove: (...args: unknown[]) => void
+}): null {
+ usePullAutoMove({ api: props.api, projectId: 'p1', cards, board, pullBoard: props.pullBoard, onAutoMove: props.onAutoMove })
return null
}
@@ -31,33 +48,49 @@ function arm(remote = false): void {
activeProjectId: 'p1',
projects: [{ id: 'p1', name: 'P', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [], ...(remote ? { remote: true } : {}) }]
} as never)
- useSettings.setState((state) => ({
- settings: {
- ...state.settings,
- kanbanPullAutoMove: { projects: { p1: { columnId: 'done', seen: { 'card-1': { '12': 'open' } } } } }
- }
- }))
+ useSettings.setState({
+ settings: { ...useSettings.getState().settings, kanbanPullAutoMove: { projects: { p1: { columnId: 'done', armedAt: 1_000 } } } }
+ })
+}
+
+async function settle(): Promise<void> {
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) })
}
beforeEach(() => arm())
describe('usePullAutoMove', () => {
- it('moves once on the observed merge and records it, so a re-run does not move again', () => {
+ it('moves once after winning the host claim, and never writes settings', async () => {
+ const api = hostClaims()
const onAutoMove = vi.fn()
- const host = document.createElement('div')
- const root = createRoot(host)
- act(() => root.render(<Probe pullBoard={merged} onAutoMove={onAutoMove} />))
- act(() => root.render(<Probe pullBoard={{ ...merged }} onAutoMove={onAutoMove} />))
+ const before = useSettings.getState().settings
+ const root = createRoot(document.createElement('div'))
+ act(() => root.render(<Probe api={api} pullBoard={merged} onAutoMove={onAutoMove} />))
+ act(() => root.render(<Probe api={api} pullBoard={{ ...merged }} onAutoMove={onAutoMove} />))
+ await settle()
expect(onAutoMove).toHaveBeenCalledTimes(1)
expect(onAutoMove).toHaveBeenCalledWith('card-1', 'doing', 'done', 'PR #12 merged')
- expect(useSettings.getState().settings.kanbanPullAutoMove?.projects.p1.seen)
- .toEqual({ 'card-1': { '12': 'merged' } })
+ expect(api.claimPullAutoMove).toHaveBeenCalledWith({ projectId: 'p1', cardId: 'card-1', pulls: [12] })
+ expect(useSettings.getState().settings).toBe(before)
+ })
+
+ it('two windows on one host: only the one that wins the claim moves the card', async () => {
+ const api = hostClaims()
+ const first = vi.fn()
+ const second = vi.fn()
+ act(() => createRoot(document.createElement('div')).render(<Probe api={api} pullBoard={merged} onAutoMove={first} />))
+ act(() => createRoot(document.createElement('div')).render(<Probe api={api} pullBoard={merged} onAutoMove={second} />))
+ await settle()
+ expect(first.mock.calls.length + second.mock.calls.length).toBe(1)
})
- it('never moves a card on a relay tab — that board belongs to the other machine', () => {
+ it('never moves a card on a relay tab — that board belongs to the other machine', async () => {
arm(true)
+ const api = hostClaims()
const onAutoMove = vi.fn()
- act(() => createRoot(document.createElement('div')).render(<Probe pullBoard={merged} onAutoMove={onAutoMove} />))
+ act(() => createRoot(document.createElement('div')).render(<Probe api={api} pullBoard={merged} onAutoMove={onAutoMove} />))
+ await settle()
expect(onAutoMove).not.toHaveBeenCalled()
+ expect(api.claimPullAutoMove).not.toHaveBeenCalled()
})
})
diff --git a/src/renderer/components/kanban/usePullAutoMove.ts b/src/renderer/components/kanban/usePullAutoMove.ts
index f408b3441..a9b3f47d9 100644
--- a/src/renderer/components/kanban/usePullAutoMove.ts
+++ b/src/renderer/components/kanban/usePullAutoMove.ts
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from 'react'
+import { useEffect, useMemo, useRef } from 'react'
import type { ProjectKanban } from '@shared/types'
import type { GitHubIssuesApi } from '@shared/github-issues'
import type { GitHubPullBoard } from '@shared/github-pull-status'
@@ -10,11 +10,14 @@ import { documentChaseDeps, startPullChase } from '../../lib/pullChase'
/**
* Runs the merge-driven move for SESSION cards while the board is open (the pull status it reads is
- * only fresh while a board is subscribed). All decisions are `planPullAutoMoves`; this glue only
- * applies them: each move goes to `onAutoMove`, which compare-and-sets against the latest board and
- * writes the board-log line, and the last-seen map goes to this machine's settings.
+ * only fresh while a board is subscribed). All decisions are `planPullAutoMoves`, which writes
+ * nothing; this glue asks the host for each move's one-time claim and applies only the moves it wins,
+ * through `onAutoMove` (a compare-and-set against the latest board + the board-log line). It never
+ * writes settings: a background settings write from one Server Edition tab would overwrite whatever
+ * the user just changed in another.
*/
export function usePullAutoMove(input: {
+ api: Pick<GitHubIssuesApi, 'claimPullAutoMove'>
projectId: string
cards: Array<{ id: string; kind: string; worktreeBranch?: string }>
board: ProjectKanban
@@ -29,32 +32,32 @@ export function usePullAutoMove(input: {
() => relay ? undefined : sanitizeKanbanPullAutoMove(raw).projects[input.projectId],
[raw, input.projectId, relay]
)
- const { projectId, cards, board, pullBoard, onAutoMove } = input
+ const { api, projectId, cards, board, pullBoard, onAutoMove } = input
+ // The BOARD's lifetime, not one effect run: the pull board is re-read every minute, and a re-render
+ // landing between a won claim and its answer must not throw the move away — the claim is spent
+ // either way, so dropping it would lose the move for good.
+ const mounted = useRef(true)
+ useEffect(() => {
+ mounted.current = true
+ return () => { mounted.current = false }
+ }, [])
+ const latest = useRef(onAutoMove)
+ latest.current = onAutoMove
useEffect(() => {
if (!entry || !onAutoMove) return
- const plan = planPullAutoMoves({ cards, board, pullBoard, entry })
- if (plan.seen !== null) {
- // Recorded BEFORE the moves: a re-run triggered by the move then sees the transition as
- // consumed. A move whose compare-and-set fails (the user moved the card meanwhile) is not
- // retried — the user's placement wins.
- const current = sanitizeKanbanPullAutoMove(useSettings.getState().settings.kanbanPullAutoMove)
- const own = current.projects[projectId]
- if (own) {
- const { seen: _old, ...rest } = own
- useSettings.getState().update({
- kanbanPullAutoMove: {
- projects: {
- ...current.projects,
- [projectId]: Object.keys(plan.seen).length ? { ...rest, seen: plan.seen } : rest
- }
+ for (const move of planPullAutoMoves({ cards, board, pullBoard, entry }).moves) {
+ void api.claimPullAutoMove({ projectId, cardId: move.cardId, pulls: move.pulls })
+ .then((claimed) => {
+ // A claim that lands after this board closed is spent, not applied: the card stays where it
+ // is, which is the safe side of a lost move. The move itself is a compare-and-set against
+ // the latest board, so a late answer cannot undo a drag made meanwhile.
+ if (claimed && mounted.current) {
+ latest.current?.(move.cardId, move.fromColumnId, entry.columnId, autoMoveNote(move.pulls))
}
})
- }
- }
- for (const move of plan.moves) {
- onAutoMove(move.cardId, move.fromColumnId, entry.columnId, autoMoveNote(move.pulls))
+ .catch(() => undefined)
}
- }, [entry, cards, board, pullBoard, projectId, onAutoMove])
+ }, [api, entry, cards, board, pullBoard, projectId, onAutoMove])
}
/** While some PR is undecided, ask the host (only while the page is visible) whether a chase read
diff --git a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
index f81d82bc2..e53ac5184 100644
--- a/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
+++ b/src/renderer/components/settings/sections/GitHubIssuesSection.tsx
@@ -133,9 +133,12 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
if (!projectId) return
const live = new Set(useProjects.getState().projects.map((item) => item.id))
const current = prunePullAutoMove(sanitizeKanbanPullAutoMove(autoMoveRaw), live)
- const { [projectId]: _previous, ...others } = current.projects
+ const { [projectId]: previous, ...others } = current.projects
+ // Switching it ON starts the clock: only merges observed from now on move a card. Changing only
+ // the target column keeps the original time — the switch never went off.
+ const armedAt = previous?.armedAt ?? Date.now()
updateSettings({
- kanbanPullAutoMove: { projects: columnId ? { ...others, [projectId]: { columnId } } : others }
+ kanbanPullAutoMove: { projects: columnId ? { ...others, [projectId]: { columnId, armedAt } } : others }
})
}
@@ -617,7 +620,7 @@ export function GitHubIssuesSection({ isActive }: { isActive: boolean }): React.
<FieldRow
label={ROWS.pullAutoMove.title}
htmlFor="github-pull-auto-move"
- description={`${ROWS.pullAutoMove.description} Only session cards in a worktree group move — GitHub closes linked issues itself. A card moves only after this machine saw one of its pull requests open, and never if one closed without merging. This setting is for this machine only.`}
+ description={`${ROWS.pullAutoMove.description} Only session cards in a worktree group move — GitHub closes linked issues itself. Only merges this machine sees after you turn this on count (it must have seen the pull request open first), and a card never moves while one of its pull requests closed without merging. This setting is for this machine only.`}
control={
<Select
id="github-pull-auto-move"
diff --git a/src/renderer/lib/pullAutoMove.test.ts b/src/renderer/lib/pullAutoMove.test.ts
index 40ad1aa4c..58fcfd4fa 100644
--- a/src/renderer/lib/pullAutoMove.test.ts
+++ b/src/renderer/lib/pullAutoMove.test.ts
@@ -4,13 +4,9 @@ import { describe, expect, it } from 'vitest'
import type { ProjectKanban } from '@shared/types'
import type { GitHubPullBoard, GitHubPullStatus } from '@shared/github-pull-status'
import { setNoAutoMove, unlinkPull } from '@shared/kanban-pull-links'
-import {
- applyPullAutoMove,
- autoMoveNote,
- decidePullAutoMove,
- nextSeen,
- planPullAutoMoves
-} from './pullAutoMove'
+import { applyPullAutoMove, autoMoveNote, decidePullAutoMove, planPullAutoMoves } from './pullAutoMove'
+
+const ARMED = 1_000
const board = (over: Partial<ProjectKanban> = {}): ProjectKanban => ({
columns: [
@@ -21,6 +17,9 @@ const board = (over: Partial<ProjectKanban> = {}): ProjectKanban => ({
...over
})
+/** A PR this machine saw open and then saw merge after the switch went on. */
+const observedMerge = (number: number, over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
+ ({ number, lifecycle: 'merged', headRefName: 'feat/x', closes: [], openSeen: true, mergedSeenAt: ARMED + 5, ...over })
const pull = (number: number, lifecycle: GitHubPullStatus['lifecycle'], over: Partial<GitHubPullStatus> = {}): GitHubPullStatus =>
({ number, lifecycle, headRefName: 'feat/x', closes: [], ...over })
@@ -30,40 +29,37 @@ const pulls = (items: GitHubPullStatus[], over: Partial<GitHubPullBoard> = {}):
})
const card = { id: 'card-1', kind: 'terminal', worktreeBranch: 'feat/x' }
-const entry = (seen?: Record<string, Record<string, 'open' | 'draft' | 'merged' | 'closed'>>) =>
- ({ columnId: 'done', ...(seen ? { seen } : {}) })
+const entry = { columnId: 'done', armedAt: ARMED }
describe('decidePullAutoMove — the guard order', () => {
- const base = { optedOut: false, seen: { '1': 'open' as const }, columnId: 'doing', targetColumnId: 'done' }
+ const base = { optedOut: false, columnId: 'doing', targetColumnId: 'done', armedAt: ARMED }
+ const merged = { number: 1, lifecycle: 'merged' as const, mergedSeenAt: ARMED + 1 }
it('an opted-out card never moves, even when everything merged', () => {
- expect(decidePullAutoMove({ ...base, optedOut: true, linked: [{ number: 1, lifecycle: 'merged' }] }))
+ expect(decidePullAutoMove({ ...base, optedOut: true, linked: [merged] }))
.toEqual({ kind: 'none', reason: 'opted-out' })
})
it('waits while any linked PR is open or a draft', () => {
- expect(decidePullAutoMove({ ...base, linked: [
- { number: 1, lifecycle: 'merged' }, { number: 2, lifecycle: 'draft' }
- ] })).toEqual({ kind: 'none', reason: 'waiting' })
+ expect(decidePullAutoMove({ ...base, linked: [merged, { number: 2, lifecycle: 'draft' }] }))
+ .toEqual({ kind: 'none', reason: 'waiting' })
})
it('a PR closed without merging blocks the move', () => {
- expect(decidePullAutoMove({ ...base, linked: [
- { number: 1, lifecycle: 'merged' }, { number: 2, lifecycle: 'closed' }
- ] })).toEqual({ kind: 'none', reason: 'blocked' })
+ expect(decidePullAutoMove({ ...base, linked: [merged, { number: 2, lifecycle: 'closed' }] }))
+ .toEqual({ kind: 'none', reason: 'blocked' })
})
- it('moves only on a transition this machine observed', () => {
- const linked = [{ number: 1, lifecycle: 'merged' as const }]
- expect(decidePullAutoMove({ ...base, linked })).toEqual({ kind: 'move', pulls: [1] })
- expect(decidePullAutoMove({ ...base, linked, seen: undefined }))
+ it('moves only on a merge this machine observed after the switch went on', () => {
+ expect(decidePullAutoMove({ ...base, linked: [merged] })).toEqual({ kind: 'move', pulls: [1] })
+ expect(decidePullAutoMove({ ...base, linked: [{ number: 1, lifecycle: 'merged' }] }))
.toEqual({ kind: 'none', reason: 'no-transition' })
- expect(decidePullAutoMove({ ...base, linked, seen: { '1': 'merged' } }))
+ expect(decidePullAutoMove({ ...base, linked: [{ ...merged, mergedSeenAt: ARMED - 1 }] }))
.toEqual({ kind: 'none', reason: 'no-transition' })
})
it('does nothing for a card already in the target column', () => {
- expect(decidePullAutoMove({ ...base, columnId: 'done', linked: [{ number: 1, lifecycle: 'merged' }] }))
+ expect(decidePullAutoMove({ ...base, columnId: 'done', linked: [merged] }))
.toEqual({ kind: 'none', reason: 'in-target' })
})
})
@@ -84,54 +80,45 @@ describe('applyPullAutoMove — compare-and-set', () => {
})
describe('planPullAutoMoves', () => {
- it('moves a card whose only PR went from open to merged, and records what it saw', () => {
- const plan = planPullAutoMoves({
- cards: [card], board: board(), pullBoard: pulls([pull(1, 'merged')]), entry: entry({ 'card-1': { '1': 'open' } })
- })
- expect(plan.moves).toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [1] }])
- expect(plan.seen).toEqual({ 'card-1': { '1': 'merged' } })
+ it('plans the move for a card whose only PR was seen open and then merged', () => {
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: pulls([observedMerge(1)]), entry }).moves)
+ .toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [1] }])
})
- it('arming the switch over PRs that merged long ago moves nothing, it only records them', () => {
- const plan = planPullAutoMoves({
- cards: [card], board: board(), pullBoard: pulls([pull(1, 'merged')]), entry: entry()
- })
- expect(plan.moves).toEqual([])
- expect(plan.seen).toEqual({ 'card-1': { '1': 'merged' } })
+ it('a merge first seen already-merged, or seen before arming, moves nothing', () => {
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: pulls([pull(1, 'merged')]), entry }).moves)
+ .toEqual([])
+ expect(planPullAutoMoves({
+ cards: [card], board: board(), pullBoard: pulls([observedMerge(1, { mergedSeenAt: ARMED - 1 })]), entry
+ }).moves).toEqual([])
})
it('does nothing at all while the switch is off, the status is stale, or unknown', () => {
- const seenOpen = entry({ 'card-1': { '1': 'open' } })
- const merged = pulls([pull(1, 'merged')])
- expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: merged, entry: undefined }))
- .toEqual({ moves: [], seen: null })
- expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: { ...merged, stale: true }, entry: seenOpen }))
- .toEqual({ moves: [], seen: null })
- expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: undefined, entry: seenOpen }))
- .toEqual({ moves: [], seen: null })
+ const merged = pulls([observedMerge(1)])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: merged, entry: undefined }).moves).toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: { ...merged, stale: true }, entry }).moves)
+ .toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: undefined, entry }).moves).toEqual([])
})
it('an unlinked PR does not count, and an opted-out card stays put', () => {
- const seenOpen = entry({ 'card-1': { '1': 'open' } })
- const merged = pulls([pull(1, 'merged')])
- expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 1), pullBoard: merged, entry: seenOpen }).moves)
+ const merged = pulls([observedMerge(1)])
+ expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 1), pullBoard: merged, entry }).moves)
.toEqual([])
- expect(planPullAutoMoves({ cards: [card], board: setNoAutoMove(board(), 'card-1', true), pullBoard: merged, entry: seenOpen }).moves)
+ expect(planPullAutoMoves({ cards: [card], board: setNoAutoMove(board(), 'card-1', true), pullBoard: merged, entry }).moves)
.toEqual([])
})
it('a closed-unmerged sibling blocks until the user removes that link', () => {
- const seenOpen = entry({ 'card-1': { '1': 'open', '2': 'open' } })
- const both = pulls([pull(1, 'merged'), pull(2, 'closed')])
- expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: both, entry: seenOpen }).moves).toEqual([])
- expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 2), pullBoard: both, entry: seenOpen }).moves)
+ const both = pulls([observedMerge(1), pull(2, 'closed')])
+ expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: both, entry }).moves).toEqual([])
+ expect(planPullAutoMoves({ cards: [card], board: unlinkPull(board(), 'card-1', 2), pullBoard: both, entry }).moves)
.toEqual([{ cardId: 'card-1', fromColumnId: 'doing', pulls: [1] }])
})
- it('a fork PR on a same-named branch is not this card\'s work', () => {
+ it("a fork PR on a same-named branch is not this card's work", () => {
const plan = planPullAutoMoves({
- cards: [card], board: board(), pullBoard: pulls([pull(1, 'merged', { crossRepository: true })]),
- entry: entry({ 'card-1': { '1': 'open' } })
+ cards: [card], board: board(), pullBoard: pulls([observedMerge(1, { crossRepository: true })]), entry
})
expect(plan.moves).toEqual([])
})
@@ -140,34 +127,27 @@ describe('planPullAutoMoves', () => {
const plan = planPullAutoMoves({
cards: [{ id: 'github:12', kind: 'github', worktreeBranch: 'feat/x' }],
board: board({ assignments: [{ nodeId: 'github:12', columnId: 'doing' }] }),
- pullBoard: pulls([pull(1, 'merged', { closes: [12] })]),
- entry: entry({ 'github:12': { '1': 'open' } })
+ pullBoard: pulls([observedMerge(1, { closes: [12] })]),
+ entry
})
expect(plan.moves).toEqual([])
})
- it('the planner and its hook never reach the GitHub issue write path', () => {
+ it('the planner and its hook never reach the GitHub issue write path, and never write settings', () => {
for (const file of ['pullAutoMove.ts', '../components/kanban/usePullAutoMove.ts']) {
const source = readFileSync(path.join(__dirname, file), 'utf8').replace(/\r\n/g, '\n')
expect(source).not.toMatch(/moveIssue|githubIssues\s*\.\s*move|updateIssue/)
+ expect(source).not.toMatch(/\.update\(|settings\.save/)
}
})
- it('writes nothing when nothing changed', () => {
- const seen = { 'card-1': { '1': 'open' as const } }
- expect(planPullAutoMoves({ cards: [card], board: board(), pullBoard: pulls([pull(1, 'open')]), entry: entry(seen) }).seen)
- .toBeNull()
+ it('is stable: the same inputs plan the same moves (no hidden state to converge)', () => {
+ const input = { cards: [card], board: board(), pullBoard: pulls([observedMerge(1)]), entry }
+ expect(planPullAutoMoves(input)).toEqual(planPullAutoMoves(input))
})
})
describe('helpers', () => {
- it('nextSeen keeps identity when unchanged', () => {
- const previous = { '1': 'open' as const }
- expect(nextSeen(previous, [{ number: 1, lifecycle: 'open' }])).toBe(previous)
- expect(nextSeen(previous, [{ number: 1, lifecycle: 'merged' }])).toEqual({ '1': 'merged' })
- expect(nextSeen(previous, [])).toBeUndefined()
- })
-
it('names the PRs in the board-log line', () => {
expect(autoMoveNote([12])).toBe('PR #12 merged')
expect(autoMoveNote([12, 15])).toBe('PRs #12, #15 merged')
diff --git a/src/renderer/lib/pullAutoMove.ts b/src/renderer/lib/pullAutoMove.ts
index c8b5196e4..0af5f6f5f 100644
--- a/src/renderer/lib/pullAutoMove.ts
+++ b/src/renderer/lib/pullAutoMove.ts
@@ -11,9 +11,17 @@
// 4. any linked PR closed WITHOUT merging → blocked until the user removes that link; an
// abandoned PR is not finished work
// 5. already in the target column → nothing to do
-// 6. all merged, but this machine never saw one of them open → no move: it only acts on a
-// transition it observed, so arming the switch (or cloning a repo whose PRs merged long ago)
+// 6. all merged, but none of the merges was OBSERVED by this machine since the switch went on →
+// no move. The host remembers each PR it saw open and when it then saw it merge
+// (core/github/pull-memory.ts); arming the switch, or cloning a repo whose PRs merged long ago,
// never sweeps old cards across the board.
+//
+// Remembered PRs keep a card blocked: a PR that closed unmerged stays on the host's pull board (and
+// so stays linked) until the user unlinks it — it does not expire when 30 newer PRs close.
+//
+// Nothing here writes. Each planned move must still win the host's one-time claim
+// (`githubIssues.claimPullAutoMove`) — so two windows cannot both move a card, and a card the user
+// dragged back is not moved again for the same merges — and is then applied as a compare-and-set.
import type { ProjectKanban } from '@shared/types'
import type { GitHubPullBoard, PullLifecycle } from '@shared/github-pull-status'
import { readPullLinks, type KanbanPullAutoMoveEntry } from '@shared/kanban-pull-links'
@@ -29,11 +37,11 @@ export type PullAutoMoveDecision =
export function decidePullAutoMove(input: {
optedOut: boolean
- linked: Array<{ number: number; lifecycle: PullLifecycle }>
- /** What this machine last saw for this card, by PR number. */
- seen: Record<string, PullLifecycle> | undefined
+ linked: Array<{ number: number; lifecycle: PullLifecycle; mergedSeenAt?: number }>
columnId: string | null
targetColumnId: string
+ /** When this machine switched the move on; only merges it OBSERVED since then count. */
+ armedAt: number
}): PullAutoMoveDecision {
if (input.optedOut) return { kind: 'none', reason: 'opted-out' }
if (input.linked.length === 0) return { kind: 'none', reason: 'no-links' }
@@ -42,27 +50,14 @@ export function decidePullAutoMove(input: {
}
if (input.linked.some((pull) => pull.lifecycle === 'closed')) return { kind: 'none', reason: 'blocked' }
if (input.columnId === input.targetColumnId) return { kind: 'none', reason: 'in-target' }
- const observed = input.linked.some((pull) => {
- const before = input.seen?.[String(pull.number)]
- return before === 'open' || before === 'draft'
- })
+ // The host records `mergedSeenAt` only for a PR it had seen open before — a merge first seen
+ // already-merged has none, and never counts.
+ const observed = input.linked.some((pull) =>
+ pull.mergedSeenAt !== undefined && pull.mergedSeenAt >= input.armedAt)
if (!observed) return { kind: 'none', reason: 'no-transition' }
return { kind: 'move', pulls: input.linked.map((pull) => pull.number).sort((a, b) => a - b) }
}
-/** The card's next "last seen" record: exactly its linked PRs, as they are now. Returns the SAME
- * object when nothing changed, so an unchanged observation writes nothing to settings. */
-export function nextSeen(
- previous: Record<string, PullLifecycle> | undefined,
- linked: Array<{ number: number; lifecycle: PullLifecycle }>
-): Record<string, PullLifecycle> | undefined {
- if (!linked.length) return undefined
- const next = Object.fromEntries(linked.map((pull) => [String(pull.number), pull.lifecycle]))
- if (previous && Object.keys(previous).length === linked.length &&
- linked.every((pull) => previous[String(pull.number)] === pull.lifecycle)) return previous
- return next
-}
-
/**
* The move itself, as a compare-and-set: it applies only if the card is still in the column the
* decision saw (a teammate's pull, a drag a moment ago, or another window's move all make it a
@@ -92,14 +87,13 @@ const SESSION_CARD_KINDS = new Set(['terminal', 'sticky', 'browser'])
export interface PullAutoMovePlan {
moves: Array<{ cardId: string; fromColumnId: string | null; pulls: number[] }>
- /** This project's next last-seen map, or null when nothing changed (write nothing). */
- seen: NonNullable<KanbanPullAutoMoveEntry['seen']> | null
}
/**
- * One pass over the board: what to move, and what this machine has now seen. Nothing happens while
- * the switch is off, while the pull status is unknown or STALE (a decision on a snapshot GitHub
- * could not confirm is a guess), or while the target column does not exist.
+ * One pass over the board: which cards to move. Nothing moves while the switch is off, while the pull
+ * status is unknown or STALE (a decision on a snapshot GitHub could not confirm is a guess), or while
+ * the target column does not exist. Write-free by design — an earlier version kept "last seen" in
+ * settings.json and could loop against the sanitizer's bounds; observation now lives on the host.
*/
export function planPullAutoMoves(input: {
cards: Array<{ id: string; kind: string; worktreeBranch?: string }>
@@ -107,31 +101,22 @@ export function planPullAutoMoves(input: {
pullBoard: GitHubPullBoard | undefined
entry: KanbanPullAutoMoveEntry | undefined
}): PullAutoMovePlan {
- const idle: PullAutoMovePlan = { moves: [], seen: null }
const { entry, pullBoard, board } = input
- if (!entry || !pullBoard || pullBoard.observedAt === undefined || pullBoard.stale) return idle
- if (!board.columns.some((column) => column.id === entry.columnId)) return idle
+ if (!entry || !pullBoard || pullBoard.observedAt === undefined || pullBoard.stale) return { moves: [] }
+ if (!board.columns.some((column) => column.id === entry.columnId)) return { moves: [] }
const optedOut = new Set(readPullLinks(board).noAutoMove)
- const previous = entry.seen ?? {}
- const seen: NonNullable<KanbanPullAutoMoveEntry['seen']> = {}
const moves: PullAutoMovePlan['moves'] = []
for (const card of input.cards) {
if (!SESSION_CARD_KINDS.has(card.kind)) continue
- const linked = pullsForCard(card, pullBoard, board).linked
- .map((pull) => ({ number: pull.number, lifecycle: pull.lifecycle }))
const fromColumnId = columnForNode(board, card.id)?.id ?? null
const decision = decidePullAutoMove({
optedOut: optedOut.has(card.id),
- linked,
- seen: previous[card.id],
+ linked: pullsForCard(card, pullBoard, board).linked,
columnId: fromColumnId,
- targetColumnId: entry.columnId
+ targetColumnId: entry.columnId,
+ armedAt: entry.armedAt
})
if (decision.kind === 'move') moves.push({ cardId: card.id, fromColumnId, pulls: decision.pulls })
- const next = nextSeen(previous[card.id], linked)
- if (next) seen[card.id] = next
}
- const changed = Object.keys(seen).length !== Object.keys(previous).length ||
- Object.entries(seen).some(([cardId, value]) => previous[cardId] !== value)
- return { moves, seen: changed ? seen : null }
+ return { moves }
}
diff --git a/src/renderer/lib/pullLinks.test.ts b/src/renderer/lib/pullLinks.test.ts
index 58050e943..e40da7625 100644
--- a/src/renderer/lib/pullLinks.test.ts
+++ b/src/renderer/lib/pullLinks.test.ts
@@ -67,6 +67,15 @@ describe('board pull links (git-shared, hostile input)', () => {
.toEqual({ unlinked: [], noAutoMove: [] })
})
+ it('a write keeps keys a newer build stored in the block', () => {
+ const newer = { ...empty, pullLinks: { issueLinks: [{ nodeId: 'n', issue: 4 }] } } as unknown as ProjectKanban
+ const next = unlinkPull(newer, 'n', 5)
+ expect((next.pullLinks as unknown as Record<string, unknown>).issueLinks).toEqual([{ nodeId: 'n', issue: 4 }])
+ expect(readPullLinks(next).unlinked).toEqual([{ nodeId: 'n', pull: 5 }])
+ const cleared = relinkPull(next, 'n', 5)
+ expect(cleared.pullLinks).toEqual({ issueLinks: [{ nodeId: 'n', issue: 4 }] })
+ })
+
it('an emptied block leaves no key in the file', () => {
const on = setNoAutoMove(empty, 'n', true)
expect(on.pullLinks).toEqual({ noAutoMove: ['n'] })
@@ -90,12 +99,14 @@ describe('board pull links (git-shared, hostile input)', () => {
})
describe('the machine-local switch', () => {
- it('reads hand-edited settings defensively', () => {
+ it('reads hand-edited settings defensively; an entry without a valid arming time is off', () => {
expect(sanitizeKanbanPullAutoMove({ projects: {
- p1: { columnId: 'done', seen: { n: { '5': 'open', '6': 'weird', x: 'open' }, bad: 3 } },
- p2: { columnId: 4 },
- p3: 'no'
- } })).toEqual({ projects: { p1: { columnId: 'done', seen: { n: { '5': 'open' } } } } })
+ p1: { columnId: 'done', armedAt: 5, seen: { n: { '5': 'open' } } },
+ p2: { columnId: 4, armedAt: 1 },
+ p3: 'no',
+ p4: { columnId: 'done' },
+ p5: { columnId: 'done', armedAt: -1 }
+ } })).toEqual({ projects: { p1: { columnId: 'done', armedAt: 5 } } })
expect(sanitizeKanbanPullAutoMove(undefined)).toEqual({ projects: {} })
})
})
diff --git a/src/renderer/state/githubIssues.test.ts b/src/renderer/state/githubIssues.test.ts
index 8589957a8..2ffd3912a 100644
--- a/src/renderer/state/githubIssues.test.ts
+++ b/src/renderer/state/githubIssues.test.ts
@@ -37,6 +37,7 @@ function api(): GitHubIssuesApi {
})),
chasePulls: vi.fn(async () => false),
pullChecks: vi.fn(async () => ({ status: 'no-checks' as const })),
+ claimPullAutoMove: vi.fn(async () => false),
projectAvatar: vi.fn(async () => null),
onChanged: vi.fn(() => () => {})
}
diff --git a/src/shared/github-issues.ts b/src/shared/github-issues.ts
index 226775d89..d1d35ad8a 100644
--- a/src/shared/github-issues.ts
+++ b/src/shared/github-issues.ts
@@ -287,6 +287,9 @@ export interface GitHubIssuesApi {
chasePulls(projectId: string): Promise<boolean>
/** Per-check detail for one PR — read only when its modal opens. */
pullChecks(projectId: string, pullNumber: number): Promise<GitHubPullChecksResult>
+ /** The one-time permission to move a session card because its linked PRs merged. The first ask
+ * across every window wins; the host remembers it. */
+ claimPullAutoMove(request: { projectId: string; cardId: string; pulls: number[] }): Promise<boolean>
onChanged(projectId: string, listener: (changedIssueNumbers: number[]) => void): () => void
/** Resolve the project's GitHub org/user avatar (owner derived host-side from the project's own
* origin — never a caller-supplied slug). Null when the project has no GitHub origin or the
diff --git a/src/shared/github-pull-status.ts b/src/shared/github-pull-status.ts
index 1dd44e11b..fa85af400 100644
--- a/src/shared/github-pull-status.ts
+++ b/src/shared/github-pull-status.ts
@@ -65,6 +65,11 @@ export interface GitHubPullStatus {
merge?: PullMergeState
/** Open PRs only. */
closes: number[]
+ /** This machine has seen the PR open or as a draft (remembered across restarts, per repository). */
+ openSeen?: true
+ /** Epoch ms when this machine first saw the PR merged AFTER having seen it open — an OBSERVED
+ * merge. Absent for a PR that was already merged when this machine first saw it. */
+ mergedSeenAt?: number
}
/** Everything the board knows about a repository's pull requests beyond the issues harvest. */
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index e8936655e..5e31991af 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -415,6 +415,7 @@ export const IPC = {
githubIssuesPullStatus: 'githubIssues:pull-status',
githubIssuesChasePulls: 'githubIssues:chase-pulls',
githubIssuesPullChecks: 'githubIssues:pull-checks',
+ githubIssuesClaimPullAutoMove: 'githubIssues:claim-pull-auto-move',
githubIssuesChanged: (projectId: string) => `githubIssues:changed:${projectId}`,
githubProjectAvatar: 'github:projectAvatar',
githubControlStatus: 'githubControl:status',
diff --git a/src/shared/kanban-pull-links.ts b/src/shared/kanban-pull-links.ts
index 96f28d47c..7f49b37c6 100644
--- a/src/shared/kanban-pull-links.ts
+++ b/src/shared/kanban-pull-links.ts
@@ -18,11 +18,11 @@
// the auto-move on makes THIS machine write the shared board on its own, whenever a merge is
// observed. If the switch lived in the project file, cloning or pulling a repository would make
// every teammate's app start moving cards (and committing those moves) without anyone on that
-// machine having asked for it — so it is off unless this machine turns it on. The same entry
-// holds the last PR state this machine saw per card, so a move fires only on a transition it
-// observed, never merely because a merged PR was found on first sight.
+// machine having asked for it — so it is off unless this machine turns it on. It is written
+// ONLY by the user's own Settings action: what this machine has observed about each PR lives in
+// core (core/github/pull-memory.ts), because a background settings write from a second Server
+// Edition tab would overwrite whatever the user just changed in the first.
import type { ProjectKanban } from './types'
-import type { PullLifecycle } from './github-pull-status'
export interface KanbanPullLinks {
/** Card ↔ PR links the user removed. A branch auto-link never re-adds one. */
@@ -64,15 +64,23 @@ export function readPullLinks(board: ProjectKanban | undefined): {
return { unlinked, noAutoMove }
}
+/** Writes the two lists back. Any OTHER key already in the block — one a newer build added — rides
+ * along untouched: the file is shared with builds this one cannot know about, and a write here
+ * must not erase what they stored. */
function withPullLinks(
board: ProjectKanban,
next: { unlinked: Array<{ nodeId: string; pull: number }>; noAutoMove: string[] }
): ProjectKanban {
- const { pullLinks: _previous, ...bare } = board
- const links: KanbanPullLinks = {
+ const { pullLinks: previous, ...bare } = board
+ const others = previous && typeof previous === 'object' && !Array.isArray(previous)
+ ? Object.fromEntries(Object.entries(previous as Record<string, unknown>)
+ .filter(([key]) => key !== 'unlinked' && key !== 'noAutoMove'))
+ : {}
+ const links = {
+ ...others,
...(next.unlinked.length ? { unlinked: next.unlinked } : {}),
...(next.noAutoMove.length ? { noAutoMove: next.noAutoMove } : {})
- }
+ } as KanbanPullLinks
return Object.keys(links).length ? { ...bare, pullLinks: links } : bare
}
@@ -114,24 +122,22 @@ export function prunePullLinks(board: ProjectKanban, live: ReadonlySet<string>):
return withPullLinks(board, { unlinked, noAutoMove })
}
-// ── Machine-local switch + last-seen memory ─────────────────────────────────────────────────────
+// ── Machine-local switch ────────────────────────────────────────────────────────────────────────
export interface KanbanPullAutoMoveEntry {
/** The column cards move to. A column deleted since then means no move, not a guess. */
columnId: string
- /** Last PR state this machine saw, per card id then PR number. */
- seen?: Record<string, Record<string, PullLifecycle>>
+ /** When this machine switched it on (epoch ms). Only merges observed AFTER this count, so turning
+ * the switch on never sweeps cards whose PRs merged earlier. */
+ armedAt: number
}
export interface KanbanPullAutoMove {
projects: Record<string, KanbanPullAutoMoveEntry>
}
-const LIFECYCLES = new Set<PullLifecycle>(['open', 'draft', 'merged', 'closed'])
-const MAX_SEEN_CARDS = 500
-const MAX_SEEN_PULLS = 20
-
-/** settings.json is hand-editable: read it through this, never directly. */
+/** settings.json is hand-editable: read it through this, never directly. An entry without a valid
+ * `armedAt` is OFF — a guessed arming time would decide which past merges count. */
export function sanitizeKanbanPullAutoMove(raw: unknown): KanbanPullAutoMove {
const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {}
const projects = value.projects && typeof value.projects === 'object' && !Array.isArray(value.projects)
@@ -141,20 +147,9 @@ export function sanitizeKanbanPullAutoMove(raw: unknown): KanbanPullAutoMove {
for (const [projectId, entryRaw] of Object.entries(projects).slice(0, 500)) {
const entry = entryRaw && typeof entryRaw === 'object' ? entryRaw as Record<string, unknown> : null
if (!nodeId(projectId) || !entry || !nodeId(entry.columnId)) continue
- const seen: Record<string, Record<string, PullLifecycle>> = {}
- const seenRaw = entry.seen && typeof entry.seen === 'object' && !Array.isArray(entry.seen)
- ? entry.seen as Record<string, unknown>
- : {}
- for (const [cardId, pullsRaw] of Object.entries(seenRaw).slice(0, MAX_SEEN_CARDS)) {
- if (!nodeId(cardId) || !pullsRaw || typeof pullsRaw !== 'object' || Array.isArray(pullsRaw)) continue
- const pulls: Record<string, PullLifecycle> = {}
- for (const [number, lifecycle] of Object.entries(pullsRaw as Record<string, unknown>).slice(0, MAX_SEEN_PULLS)) {
- if (pullNumber(Number(number)) && String(Number(number)) === number &&
- LIFECYCLES.has(lifecycle as PullLifecycle)) pulls[number] = lifecycle as PullLifecycle
- }
- if (Object.keys(pulls).length) seen[cardId] = pulls
- }
- out[projectId] = { columnId: entry.columnId, ...(Object.keys(seen).length ? { seen } : {}) }
+ const armedAt = entry.armedAt
+ if (typeof armedAt !== 'number' || !Number.isSafeInteger(armedAt) || armedAt < 0) continue
+ out[projectId] = { columnId: entry.columnId, armedAt }
}
return { projects: out }
}