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.

feat(kanban): rank strings for card order within a column

reviewc050f72988e2
diff --git a/src/core/kanban-rank-merge.test.ts b/src/core/kanban-rank-merge.test.ts
new file mode 100644
index 000000000..bef070017
--- /dev/null
+++ b/src/core/kanban-rank-merge.test.ts
@@ -0,0 +1,134 @@
+// Ranks exist so two machines moving cards on the same git-shared board produce edits git can merge.
+// This runs the real three-way merge (`git merge-file`) over the board block as it is written to
+// `.nodeterm/project.json` (pretty-printed, 2-space JSON) rather than asserting a diff shape by hand.
+//
+// Scope, stated honestly: the FILE's own header also changes on every save (`rev`, `savedAt`), and
+// two concurrent saves still disagree on `savedAt` — a pre-existing property of project.json that
+// ranks do not touch. What is measured here is the board block the move itself writes.
+import { execFileSync } from 'child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+import { afterAll, describe, expect, it } from 'vitest'
+import type { ProjectKanban } from '../shared/types'
+import { columnOrder, placeAssignment } from '../shared/kanban-order'
+
+const hasGit = (() => {
+ try {
+ execFileSync('git', ['--version'], { stdio: 'ignore' })
+ return true
+ } catch {
+ return false
+ }
+})()
+
+const dir = mkdtempSync(path.join(tmpdir(), 'kanban-merge-'))
+afterAll(() => rmSync(dir, { recursive: true, force: true }))
+
+const text = (k: ProjectKanban): string => `${JSON.stringify(k, null, 2)}\n`
+
+/** Three-way merge; returns the merged board, or null when git reports a conflict. */
+function merge(base: ProjectKanban, ours: ProjectKanban, theirs: ProjectKanban): ProjectKanban | null {
+ const [b, o, t] = ['base', 'ours', 'theirs'].map((n) => path.join(dir, `${n}.json`))
+ writeFileSync(b, text(base))
+ writeFileSync(o, text(ours))
+ writeFileSync(t, text(theirs))
+ try {
+ return JSON.parse(execFileSync('git', ['merge-file', '-p', o, b, t], { encoding: 'utf8' })) as ProjectKanban
+ } catch {
+ return null // non-zero exit = conflicts
+ }
+}
+
+const changedLines = (a: ProjectKanban, b: ProjectKanban): number => {
+ const x = text(a).split('\n')
+ const y = text(b).split('\n')
+ if (x.length !== y.length) return Number.POSITIVE_INFINITY
+ return x.filter((line, i) => line !== y[i]).length
+}
+
+const move = (k: ProjectKanban, nodeId: string, columnId: string, anchor: Parameters<typeof placeAssignment>[3]): ProjectKanban => ({
+ ...k,
+ assignments: placeAssignment(k.assignments, nodeId, columnId, anchor)
+})
+
+/** A board as the field has it after a while: cards filed across three columns, all ranked
+ * (the first write into each column ranks it). */
+function fieldBoard(): ProjectKanban {
+ let k: ProjectKanban = {
+ columns: [
+ { id: 'todo', title: 'To Do', color: '#0a84ff' },
+ { id: 'doing', title: 'In Progress', color: '#ffd60a' },
+ { id: 'done', title: 'Done', color: '#32d74b' }
+ ],
+ assignments: []
+ }
+ for (const [id, col] of [
+ ['t1', 'todo'], ['t2', 'todo'], ['t3', 'todo'], ['t4', 'todo'],
+ ['p1', 'doing'], ['p2', 'doing'],
+ ['d1', 'done'], ['d2', 'done'], ['d3', 'done']
+ ] as const) {
+ k = move(k, id, col, 'end')
+ }
+ return k
+}
+
+describe.skipIf(!hasGit)('rank strings under a real three-way merge', () => {
+ it('a card filed at the top of Done, from before Done in the file, is a two-line change', () => {
+ const base = fieldBoard()
+ const moved = move(base, 'p1', 'done', 'top')
+ expect(changedLines(base, moved)).toBe(2) // "columnId" and "rank" of the one entry
+ })
+
+ it('two machines filing DIFFERENT cards into Done merge cleanly, and both moves survive', () => {
+ const base = fieldBoard()
+ const ours = move(base, 't1', 'done', 'top')
+ const theirs = move(base, 'p2', 'done', 'top')
+ const merged = merge(base, ours, theirs)
+ expect(merged).not.toBeNull()
+ const done = columnOrder(merged!.assignments, 'done').map((a) => a.nodeId)
+ expect(done).toContain('t1')
+ expect(done).toContain('p2')
+ expect(done.slice(2)).toEqual(['d1', 'd2', 'd3'])
+ expect(merged!.assignments).toHaveLength(base.assignments.length)
+ })
+
+ // The contrast that is the reason for ranks. MEASURED, not assumed: filing two NON-adjacent cards
+ // into one column merges cleanly even without ranks (git pairs the similar JSON blocks), but two
+ // ADJACENT cards filed concurrently — the ordinary case of two agents finishing neighbouring
+ // stations — make array-only placement edit the same stretch of the file on both sides, and git
+ // stops at a conflict. With ranks each card changes in place, two lines apiece, and it merges.
+ // (Both sides mint the same key there — the tie keeps array order, and the next write into the
+ // column re-keys it; see @shared/kanban-order.)
+ it('two ADJACENT cards filed concurrently: conflict without ranks, clean with them', () => {
+ const arrayOnly = (k: ProjectKanban, nodeId: string, columnId: string): ProjectKanban => {
+ const without = k.assignments
+ .filter((a) => a.nodeId !== nodeId)
+ .map(({ nodeId: n, columnId: c }) => ({ nodeId: n, columnId: c }))
+ const at = without.findIndex((a) => a.columnId === columnId)
+ const i = at === -1 ? without.length : at
+ return { ...k, assignments: [...without.slice(0, i), { nodeId, columnId }, ...without.slice(i)] }
+ }
+ const unranked = (k: ProjectKanban): ProjectKanban => ({
+ ...k,
+ assignments: k.assignments.map(({ nodeId, columnId }) => ({ nodeId, columnId }))
+ })
+ const plain = unranked(fieldBoard())
+ expect(merge(plain, arrayOnly(plain, 't1', 'done'), arrayOnly(plain, 't2', 'done'))).toBeNull()
+
+ const base = fieldBoard()
+ const merged = merge(base, move(base, 't1', 'done', 'top'), move(base, 't2', 'done', 'top'))
+ expect(merged).not.toBeNull()
+ expect(columnOrder(merged!.assignments, 'done').map((a) => a.nodeId)).toEqual(['t1', 't2', 'd1', 'd2', 'd3'])
+ })
+
+ it('a reorder in one column and a move in another merge cleanly', () => {
+ const base = fieldBoard()
+ const ours = move(base, 't4', 'todo', 'top') // reorder within To Do (moves a block)
+ const theirs = move(base, 'd3', 'done', 'top') // reorder within Done
+ const merged = merge(base, ours, theirs)
+ expect(merged).not.toBeNull()
+ expect(columnOrder(merged!.assignments, 'todo').map((a) => a.nodeId)).toEqual(['t4', 't1', 't2', 't3'])
+ expect(columnOrder(merged!.assignments, 'done').map((a) => a.nodeId)).toEqual(['d3', 'd1', 'd2'])
+ })
+})
diff --git a/src/core/project-kanban-write.test.ts b/src/core/project-kanban-write.test.ts
index e233c470e..d3d49a40f 100644
--- a/src/core/project-kanban-write.test.ts
+++ b/src/core/project-kanban-write.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { ensureProjectBoard, setProjectCardColumn } from './project-kanban-write'
import { DEFAULT_BOARD_COLUMNS } from '../shared/kanban-default-board'
+import { isValidRank } from '../shared/kanban-rank'
const NOW = new Date('2026-09-10T12:00:00.000Z')
@@ -99,7 +100,8 @@ describe('setProjectCardColumn', () => {
it('assigns an unassigned card and bumps rev', () => {
const out = parse(setProjectCardColumn(board(), 'term-a-1', 'kcol-a', NOW))
- expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-a' }])
+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-a', rank: expect.any(String) }])
+ expect(isValidRank(out.kanban.assignments[0].rank)).toBe(true)
expect(out.rev).toBe(8)
})
@@ -107,7 +109,7 @@ describe('setProjectCardColumn', () => {
const out = parse(
setProjectCardColumn(board([{ nodeId: 'term-a-1', columnId: 'kcol-a' }]), 'term-a-1', 'kcol-b', NOW)
)
- expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-b' }])
+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-b', rank: expect.any(String) }])
})
it('columnId null drops the assignment (the virtual Ungrouped column)', () => {
@@ -123,7 +125,7 @@ describe('setProjectCardColumn', () => {
)
expect(out.kanban.assignments).toEqual([
{ nodeId: 'term-z-9', columnId: 'kcol-b' },
- { nodeId: 'term-a-1', columnId: 'kcol-a' }
+ { nodeId: 'term-a-1', columnId: 'kcol-a', rank: expect.any(String) }
])
expect(out.kanban.meta).toEqual([{ nodeId: 'term-a-1', priority: 'high' }])
})
@@ -163,7 +165,7 @@ describe('setProjectCardColumn', () => {
it('accepts a node id the canvas does not list yet (it may have just been registered)', () => {
const out = parse(setProjectCardColumn(board(), 'term-new-1', 'kcol-a', NOW))
- expect(out.kanban.assignments).toEqual([{ nodeId: 'term-new-1', columnId: 'kcol-a' }])
+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-new-1', columnId: 'kcol-a', rank: expect.any(String) }])
})
it('refuses a project with no board at all — the caller seeds one first', () => {
diff --git a/src/core/project-kanban-write.ts b/src/core/project-kanban-write.ts
index 680fa63d6..d7069f070 100644
--- a/src/core/project-kanban-write.ts
+++ b/src/core/project-kanban-write.ts
@@ -22,6 +22,7 @@ import {
setCardLabels
} from '../shared/kanban-labels'
import type { KanbanLabelColor, ProjectKanban } from '../shared/types'
+import { placeAssignment, type RankedEntry } from '../shared/kanban-order'
/** Parse `raw` as the `{version:1, rev, nodes}` project file, or null. */
function parseProjectFile(raw: string): Record<string, unknown> | null {
@@ -120,16 +121,13 @@ export function setProjectCardColumn(
// Already there — including "already Ungrouped", which is what an ABSENT assignment means.
if ((current ?? null) === columnId) return null
- const kept = before.filter((a) => a?.nodeId !== nodeId)
if (columnId === null) {
- board.assignments = kept
+ board.assignments = before.filter((a) => a?.nodeId !== nodeId)
} else {
- // Unanchored ⇒ the TOP of the destination, the desktop's rule (`assignNode`): array order is
- // column order, so that is just before the column's first assignment; an empty column's first
- // card joins the end of the array.
- const first = kept.findIndex((a) => a?.columnId === columnId)
- const at = first === -1 ? kept.length : first
- board.assignments = [...kept.slice(0, at), { nodeId, columnId }, ...kept.slice(at)]
+ // Unanchored ⇒ the TOP of the destination, through the SAME placement the desktop's
+ // `assignNode` uses: one new rank, the array kept in rank order for builds that ignore it,
+ // every other entry (and every field this surface does not know) untouched.
+ board.assignments = placeAssignment(before as unknown as RankedEntry[], nodeId, columnId, 'top')
}
if (!Array.isArray(board.columns)) board.columns = columns
root.kanban = board
diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.ts
index 6b5c86a72..5cf318bce 100644
--- a/src/core/workspace-files.test.ts
+++ b/src/core/workspace-files.test.ts
@@ -621,6 +621,24 @@ describe('sanitizeKanban — the board is hostile, git-shared input', () => {
expect(sanitizeKanban(k)?.assignments).toEqual([{ nodeId: 'n', columnId: 'kcol-a' }])
})
+ it('keeps a valid rank and drops one that is not (the card then derives from array order)', () => {
+ const k = {
+ ...clean(),
+ assignments: [
+ { nodeId: 'ok', columnId: 'kcol-a', rank: 'a0' },
+ { nodeId: 'num', columnId: 'kcol-a', rank: 5 },
+ { nodeId: 'junk', columnId: 'kcol-a', rank: 'not a rank!' },
+ { nodeId: 'huge', columnId: 'kcol-a', rank: 'a'.repeat(1000) }
+ ]
+ }
+ expect(sanitizeKanban(k)?.assignments).toEqual([
+ { nodeId: 'ok', columnId: 'kcol-a', rank: 'a0' },
+ { nodeId: 'num', columnId: 'kcol-a' },
+ { nodeId: 'junk', columnId: 'kcol-a' },
+ { nodeId: 'huge', columnId: 'kcol-a' }
+ ])
+ })
+
it('keeps fields it does not know (a newer build\'s board data round-trips)', () => {
const k = { ...clean(), futureThing: [1, 2], columns: [{ ...clean().columns[0], wip: 3 }] }
const out = sanitizeKanban(k) as unknown as Record<string, unknown>
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index eda8992a5..5a67126dc 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -8,6 +8,7 @@ import {
stripSharedNodeExec,
type LocalNodeExecMap
} from '../shared/node-exec'
+import { isValidRank } from '../shared/kanban-rank'
import { CLOSED_SESSIONS_CAP } from '../shared/types'
import type { BridgeLink, CanvasNodeState, ClosedSessionEntry, NavStop, Project, ProjectKanban, Viewport, Workspace } from '../shared/types'
import { projectCapabilityFields, readProjectCapabilities } from '../shared/project-capabilities'
@@ -415,7 +416,9 @@ const isRecord = (x: unknown): x is Record<string, unknown> =>
* - a column's `category` that is not a STRING is dropped. An unknown string is KEPT: it may be a
* category a newer build added, and dropping it here would erase that build's data from the
* shared file on our next save. Readers treat it as absent (`columnCategory`);
- * - an assignment that is not an object with string `nodeId` and `columnId` is dropped.
+ * - an assignment that is not an object with string `nodeId` and `columnId` is dropped, and a
+ * `rank` that `isValidRank` refuses is dropped from it (the card then derives its position from
+ * array order — see @shared/kanban-order).
* Every other field — known or not — round-trips untouched.
*
* Returns the SAME object when nothing needed repair, so a clean file is never rewritten, and
@@ -439,11 +442,22 @@ export function sanitizeKanban(k: unknown): ProjectKanban | undefined {
}
columns.push(c as unknown as ProjectKanban['columns'][number])
}
- const assignments = (k.assignments as unknown[]).filter(
- (a): a is ProjectKanban['assignments'][number] =>
- isRecord(a) && typeof a.nodeId === 'string' && typeof a.columnId === 'string'
- )
- if (assignments.length !== k.assignments.length) changed = true
+ const assignments: ProjectKanban['assignments'] = []
+ for (const a of k.assignments as unknown[]) {
+ if (!isRecord(a) || typeof a.nodeId !== 'string' || typeof a.columnId !== 'string') {
+ changed = true
+ continue
+ }
+ // A rank we could not have minted is not a position: drop it and the card derives its place
+ // from array order, which every write keeps in rank order anyway (@shared/kanban-order).
+ if ('rank' in a && !isValidRank(a.rank)) {
+ const { rank: _drop, ...rest } = a
+ assignments.push(rest as unknown as ProjectKanban['assignments'][number])
+ changed = true
+ continue
+ }
+ assignments.push(a as unknown as ProjectKanban['assignments'][number])
+ }
return changed ? { ...k, columns, assignments } : k
}
diff --git a/src/core/workspace-store.kanban.test.ts b/src/core/workspace-store.kanban.test.ts
index 203bb3b3c..1f115a78a 100644
--- a/src/core/workspace-store.kanban.test.ts
+++ b/src/core/workspace-store.kanban.test.ts
@@ -128,9 +128,9 @@ describe('setRemoteCardColumn (the phone moving a card)', () => {
fake.sent.length = 0
expect(await store.setRemoteCardColumn('p1', 'term-1', 'kcol-b')).toBe(true)
- expect((await readFile()).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b' }])
+ expect((await readFile()).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b', rank: expect.any(String) }])
expect(externalChanges()).toHaveLength(1)
- expect(externalChanges()[0].kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b' }])
+ expect(externalChanges()[0].kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b', rank: expect.any(String) }])
})
it('null moves the card to Ungrouped', async () => {
@@ -174,7 +174,7 @@ describe('setRemoteCardColumn (the phone moving a card)', () => {
expect(await moving).toBe(true)
await saving
const file = await readFile()
- expect(file.kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])
+ expect(file.kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a', rank: expect.any(String) }])
expect(file.name).toBe('renamed')
})
})
@@ -212,10 +212,10 @@ describe('an SSH project (the case the phone can never write itself)', () => {
})]))
expect(await store.setRemoteCardColumn('ssh1', 'term-1', 'kcol-a')).toBe(true)
- expect(JSON.parse(io.content!).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])
+ expect(JSON.parse(io.content!).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a', rank: expect.any(String) }])
const reloaded = await new WorkspaceStore(io).load()
expect(reloaded.projects.find((p) => p.id === 'ssh1')?.kanban?.assignments)
- .toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])
+ .toEqual([{ nodeId: 'term-1', columnId: 'kcol-a', rank: expect.any(String) }])
})
// Every refusal reason stays a refusal on this path too — a cache write that cannot be described
diff --git a/src/renderer/lib/kanban.ts b/src/renderer/lib/kanban.ts
index b11d6d704..61e31271a 100644
--- a/src/renderer/lib/kanban.ts
+++ b/src/renderer/lib/kanban.ts
@@ -1,7 +1,8 @@
import type {
- CanvasNodeState, KanbanAssignment, KanbanColumn, KanbanColumnCategory, Project, ProjectKanban
+ CanvasNodeState, KanbanColumn, KanbanColumnCategory, Project, ProjectKanban
} from '@shared/types'
import { columnCategory } from '@shared/kanban-category'
+import { columnOrder, placeAssignment, type CardAnchor } from '@shared/kanban-order'
import { SYSTEM_NODE_COLORS } from '../state/workspace'
import { defaultBoardColumns } from '@shared/kanban-default-board'
import { autoLabelColor, boardLabels, cardMeta, createLabel, metaList, setCardLabels } from '@shared/kanban-labels'
@@ -117,9 +118,10 @@ export function deleteColumn(k: ProjectKanban, columnId: string): ProjectKanban
}
}
-/** Node ids assigned to `columnId`, in board order. */
+/** Node ids assigned to `columnId`, in board order — rank first, array order for entries without
+ * one (@shared/kanban-order). Every board reader goes through this. */
export function assignedTo(k: ProjectKanban, columnId: string): string[] {
- return k.assignments.filter((a) => a.columnId === columnId).map((a) => a.nodeId)
+ return columnOrder(k.assignments, columnId).map((a) => a.nodeId)
}
/**
@@ -164,7 +166,9 @@ export const AT_COLUMN_END: unique symbol = Symbol('kanban.atColumnEnd')
* card created from a column): appended at the bottom of a long "Done" column, the card an
* agent just finished read as having disappeared.
*
- * Unknown target column is a no-op. */
+ * The move writes one `rank` and keeps the array in rank order (`placeAssignment`, which the
+ * relay's move verb shares). Unknown target column, or a card already exactly there, returns the
+ * SAME board. */
export function assignNode(
k: ProjectKanban,
nodeId: string,
@@ -177,20 +181,10 @@ export function assignNode(
return { ...k, assignments: k.assignments.filter((a) => a.nodeId !== nodeId) }
}
if (!k.columns.some((c) => c.id === columnId)) return k
- const moved: KanbanAssignment = { nodeId, columnId }
- const without = k.assignments.filter((a) => a.nodeId !== nodeId)
- const anchor =
- typeof beforeNodeId === 'string'
- ? without.find((a) => a.nodeId === beforeNodeId && a.columnId === columnId)
- : undefined
- // Array order is the column order, so "top" = before the column's first assignment, and an empty
- // column's first card simply joins the end of the array.
- const target =
- anchor ??
- (beforeNodeId === AT_COLUMN_END ? undefined : without.find((a) => a.columnId === columnId))
- const idx = target ? without.indexOf(target) : -1
- const at = idx === -1 ? without.length : idx
- return { ...k, assignments: [...without.slice(0, at), moved, ...without.slice(at)] }
+ const anchor: CardAnchor =
+ beforeNodeId === AT_COLUMN_END ? 'end' : typeof beforeNodeId === 'string' ? { before: beforeNodeId } : 'top'
+ const assignments = placeAssignment(k.assignments, nodeId, columnId, anchor)
+ return assignments === k.assignments ? k : { ...k, assignments }
}
/** Drops assignments of nodes that no longer exist. Returns the SAME object when nothing
diff --git a/src/shared/kanban-order.test.ts b/src/shared/kanban-order.test.ts
new file mode 100644
index 000000000..cd5df59a1
--- /dev/null
+++ b/src/shared/kanban-order.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it } from 'vitest'
+import type { KanbanAssignment } from './types'
+import { columnOrder, placeAssignment } from './kanban-order'
+import { isValidRank, rankBetween } from './kanban-rank'
+
+type A = KanbanAssignment
+const a = (nodeId: string, columnId: string, rank?: string): A => (rank === undefined ? { nodeId, columnId } : { nodeId, columnId, rank })
+const ids = (list: readonly A[]): string[] => list.map((x) => x.nodeId)
+const order = (list: readonly A[], col: string): string[] => ids(columnOrder(list, col))
+/** What a build that ignores `rank` shows: the column's entries in ARRAY order. */
+const arrayOrder = (list: readonly A[], col: string): string[] => ids(list.filter((x) => x.columnId === col))
+
+const r1 = rankBetween(null, null)
+const r2 = rankBetween(r1, null)
+const r3 = rankBetween(r2, null)
+
+describe('columnOrder — rank first, array order for what has none', () => {
+ it('sorts ranked entries by rank whatever their array order', () => {
+ expect(order([a('c', 'x', r3), a('a', 'x', r1), a('b', 'x', r2)], 'x')).toEqual(['a', 'b', 'c'])
+ })
+
+ it('an unranked board (every pre-rank file) is array order', () => {
+ expect(order([a('b', 'x'), a('y1', 'y'), a('a', 'x')], 'x')).toEqual(['b', 'a'])
+ })
+
+ it('an unranked entry sits right after the entry before it in the array (an old build’s move)', () => {
+ // An old build moved `u` to just above `c`: it sits after `b` in the array, with no rank.
+ expect(order([a('a', 'x', r1), a('b', 'x', r2), a('u', 'x'), a('c', 'x', r3)], 'x')).toEqual(['a', 'b', 'u', 'c'])
+ // At the very front of the column it stays first.
+ expect(order([a('u', 'x'), a('a', 'x', r1)], 'x')).toEqual(['u', 'a'])
+ })
+
+ it('an invalid rank reads as absent', () => {
+ expect(order([a('a', 'x', r1), a('bad', 'x', 'not a rank!'), a('b', 'x', r2)], 'x')).toEqual(['a', 'bad', 'b'])
+ })
+
+ it('equal ranks (two machines minted the same key) keep array order, deterministically', () => {
+ expect(order([a('q', 'x', r1), a('p', 'x', r1)], 'x')).toEqual(['q', 'p'])
+ })
+})
+
+describe('placeAssignment', () => {
+ it('top / end / before, each with a valid rank', () => {
+ const base = [a('a', 'x', r1), a('b', 'x', r2)]
+ const top = placeAssignment(base, 'n', 'x', 'top')
+ expect(order(top, 'x')).toEqual(['n', 'a', 'b'])
+ const end = placeAssignment(base, 'n', 'x', 'end')
+ expect(order(end, 'x')).toEqual(['a', 'b', 'n'])
+ const mid = placeAssignment(base, 'n', 'x', { before: 'b' })
+ expect(order(mid, 'x')).toEqual(['a', 'n', 'b'])
+ for (const list of [top, end, mid]) expect(list.every((e) => isValidRank(e.rank))).toBe(true)
+ })
+
+ it('a `before` outside the column is no anchor: top', () => {
+ const base = [a('a', 'x', r1), a('z', 'y', r1)]
+ expect(order(placeAssignment(base, 'n', 'x', { before: 'z' }), 'x')).toEqual(['n', 'a'])
+ })
+
+ it('WRITES the array in rank order — a build that ignores rank shows the same column', () => {
+ const base = [a('a', 'x', r1), a('b', 'x', r2), a('c', 'x', r3)]
+ for (const anchor of ['top', 'end', { before: 'b' }, { before: 'a' }] as const) {
+ for (const moving of ['a', 'b', 'c', 'new']) {
+ const out = placeAssignment(base, moving, 'x', anchor)
+ expect(arrayOrder(out, 'x'), `${moving} → ${JSON.stringify(anchor)}`).toEqual(order(out, 'x'))
+ }
+ }
+ })
+
+ it('a cross-column move whose slot already fits changes ONE entry, in place (a two-line diff)', () => {
+ // The card sits BEFORE the destination's first card in the array, so the top of that column
+ // needs no array move — only its columnId and rank change.
+ // An entry of a THIRD column sits between the card and the destination's first card, so the
+ // naive "insert before the successor" would move the card's block past it.
+ const base = [a('m', 'x', r1), a('o', 'z', r1), a('d1', 'y', r1), a('d2', 'y', r2), a('k', 'x', r2)]
+ const out = placeAssignment(base, 'm', 'y', 'top')
+ expect(out).toHaveLength(5)
+ expect(out[0]).toMatchObject({ nodeId: 'm', columnId: 'y' })
+ for (const i of [1, 2, 3, 4]) expect(out[i]).toBe(base[i])
+ expect(order(out, 'y')).toEqual(['m', 'd1', 'd2'])
+ })
+
+ it('touches no entry of another column', () => {
+ const base = [a('o1', 'z'), a('a', 'x', r1), a('o2', 'z'), a('b', 'x', r2)]
+ const out = placeAssignment(base, 'b', 'x', 'top')
+ expect(out.filter((e) => e.columnId === 'z')).toEqual([base[0], base[2]])
+ expect(out.find((e) => e.nodeId === 'o1')).toBe(base[0])
+ })
+
+ it('a move that lands where the card already is returns the SAME array (nothing to write)', () => {
+ const base = [a('a', 'x', r1), a('b', 'x', r2)]
+ expect(placeAssignment(base, 'a', 'x', 'top')).toBe(base)
+ expect(placeAssignment(base, 'b', 'x', 'end')).toBe(base)
+ expect(placeAssignment(base, 'a', 'x', { before: 'b' })).toBe(base)
+ })
+
+ it('ranks an UNRANKED column on its first write, in the order it was already showing', () => {
+ const base = [a('a', 'x'), a('b', 'x'), a('c', 'x')]
+ const out = placeAssignment(base, 'n', 'x', 'top')
+ expect(order(out, 'x')).toEqual(['n', 'a', 'b', 'c'])
+ expect(arrayOrder(out, 'x')).toEqual(['n', 'a', 'b', 'c'])
+ expect(out.every((e) => isValidRank(e.rank))).toBe(true)
+ })
+
+ it('re-keys only the colliding entries after two machines minted the same rank', () => {
+ const base = [a('p', 'x', r1), a('q', 'x', r1), a('s', 'x', r3)]
+ const out = placeAssignment(base, 'n', 'x', { before: 'q' })
+ expect(order(out, 'x')).toEqual(['p', 'n', 'q', 's'])
+ expect(out.find((e) => e.nodeId === 'p')).toBe(base[0])
+ expect(out.find((e) => e.nodeId === 's')).toBe(base[2])
+ const ranks = columnOrder(out, 'x').map((e) => e.rank!)
+ for (let i = 1; i < ranks.length; i++) expect(ranks[i - 1] < ranks[i]).toBe(true)
+ })
+
+ it('repairs a column whose array disagrees with its ranks (after a textual merge)', () => {
+ const base = [a('c', 'x', r3), a('a', 'x', r1), a('b', 'x', r2)]
+ const out = placeAssignment(base, 'n', 'x', 'end')
+ expect(order(out, 'x')).toEqual(['a', 'b', 'c', 'n'])
+ expect(arrayOrder(out, 'x')).toEqual(['a', 'b', 'c', 'n'])
+ })
+
+ it('an old build’s rank-less move is respected, then ranked by our next write', () => {
+ // Ours: a, b, c ranked. An old build moved `c` to the top: it dropped c's rank and spliced it
+ // before `a` in the array (its assignNode rebuilds the moved entry without the field).
+ const afterOld = [a('c', 'x'), a('a', 'x', r1), a('b', 'x', r2)]
+ expect(order(afterOld, 'x')).toEqual(['c', 'a', 'b'])
+ const out = placeAssignment(afterOld, 'n', 'x', 'end')
+ expect(order(out, 'x')).toEqual(['c', 'a', 'b', 'n'])
+ expect(arrayOrder(out, 'x')).toEqual(order(out, 'x'))
+ expect(out.every((e) => isValidRank(e.rank))).toBe(true)
+ })
+
+ it('keeps fields it does not know on the moved entry', () => {
+ const base = [{ ...a('a', 'x', r1), future: 1 } as A, a('b', 'y', r1)]
+ const out = placeAssignment(base, 'a', 'y', 'end')
+ expect(out.find((e) => e.nodeId === 'a')).toMatchObject({ future: 1, columnId: 'y' })
+ })
+
+ // The contract across ANY sequence of writes: array order == rank order in every column (so a
+ // build that ignores rank shows the same board), and every column written to is fully ranked.
+ it('holds the old-build contract across a seeded random walk of moves', () => {
+ let seed = 7
+ const rand = (n: number): number => {
+ seed = (seed * 1103515245 + 12345) % 2147483648
+ return Math.floor((seed / 2147483648) * n)
+ }
+ const cols = ['x', 'y', 'z']
+ const nodes = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7']
+ // Start from a MIXED board: some ranked, some not, one duplicate — what the field will hold.
+ let list: A[] = [a('n0', 'x'), a('n1', 'y', r1), a('n2', 'x', r2), a('n3', 'y', r1), a('n4', 'z')]
+ for (let i = 0; i < 400; i++) {
+ const node = nodes[rand(nodes.length)]
+ const col = cols[rand(cols.length)]
+ const pick = rand(3)
+ const colIds = order(list, col)
+ const anchor = pick === 0 ? 'top' : pick === 1 ? 'end' : { before: colIds[rand(colIds.length + 1)] ?? 'nobody' }
+ list = placeAssignment(list, node, col, anchor as Parameters<typeof placeAssignment>[3])
+ for (const c of cols) expect(arrayOrder(list, c), `step ${i} col ${c}`).toEqual(order(list, c))
+ const dest = columnOrder(list, col).map((e) => e.rank)
+ expect(dest.every(isValidRank), `step ${i}`).toBe(true)
+ for (let j = 1; j < dest.length; j++) expect(dest[j - 1]! < dest[j]!).toBe(true)
+ expect(new Set(ids(list)).size).toBe(list.length)
+ }
+ })
+})
diff --git a/src/shared/kanban-order.ts b/src/shared/kanban-order.ts
new file mode 100644
index 000000000..0c2627815
--- /dev/null
+++ b/src/shared/kanban-order.ts
@@ -0,0 +1,126 @@
+/**
+ * Card order within a board column, and the one placement every writer uses.
+ *
+ * ORDER (`columnOrder`): an entry with a valid `rank` sorts by it; an entry without one (every
+ * pre-rank board, an older build's move, a hand edit) sits right after the entry before it in the
+ * ARRAY, so a board no build has ranked reads exactly as it always did. Ties keep array order, so
+ * two machines that minted the same key still agree on the result.
+ *
+ * WRITE (`placeAssignment`): the moved card gets one new rank between its neighbours, and the
+ * ARRAY is kept in rank order too — a build that ignores `rank` reads array order, and must show
+ * the same column. The two goals pull against each other, and the resolution is to move as little
+ * as the second one allows:
+ * - the moved entry stays at its array index when that index already sits between its new
+ * neighbours — a cross-column move whose slot fits is then a two-line diff (columnId + rank);
+ * - otherwise it moves next to its successor (else its predecessor), i.e. one block moves;
+ * - the destination column is repaired first when it must be — ranks that are missing, invalid or
+ * collide get fresh keys IN THE ORDER THE COLUMN WAS ALREADY SHOWING (only those entries change),
+ * and an array that disagrees with the ranks (a textual merge) is re-slotted within the column's
+ * own array positions. A board's first write into an unranked column therefore ranks it once.
+ * A reorder WITHIN a column always moves a block: the array must change for an old build to see it.
+ *
+ * Generic over the entry type and spread-preserving, so the host core can run it on the raw
+ * project-file objects (the relay's move verb) and every unknown field round-trips.
+ */
+import { isValidRank, rankBetween, ranksBetween } from './kanban-rank'
+
+export interface RankedEntry {
+ nodeId: string
+ columnId: string
+ rank?: string
+}
+
+/** Where a moved card goes: the top, the bottom, or just above a card of that column. */
+export type CardAnchor = 'top' | 'end' | { before: string }
+
+/** One column's entries in board order (see the module note). Never throws. */
+export function columnOrder<A extends RankedEntry>(list: readonly A[], columnId: string): A[] {
+ const entries: Array<{ a: A; idx: number; key: string }> = []
+ let prev = ''
+ list.forEach((a, idx) => {
+ if (!a || a.columnId !== columnId) return
+ const key = isValidRank(a.rank) ? a.rank : prev
+ entries.push({ a, idx, key })
+ prev = key
+ })
+ entries.sort((p, q) => (p.key < q.key ? -1 : p.key > q.key ? 1 : p.idx - q.idx))
+ return entries.map((e) => e.a)
+}
+
+/** New ranks for the entries of an ordered column that lack a strictly increasing valid one
+ * (missing, invalid, or colliding with the one before). Kept entries are untouched. */
+function repairRanks<A extends RankedEntry>(order: readonly A[]): Map<A, string> {
+ const fixes = new Map<A, string>()
+ let last: string | null = null
+ const keep = order.map((e) => {
+ if (isValidRank(e.rank) && (last === null || e.rank > last)) {
+ last = e.rank
+ return true
+ }
+ return false
+ })
+ for (let i = 0; i < order.length; ) {
+ if (keep[i]) {
+ i++
+ continue
+ }
+ let j = i
+ while (j < order.length && !keep[j]) j++
+ const lo = i > 0 ? (order[i - 1].rank as string) : null
+ const hi = j < order.length ? (order[j].rank as string) : null
+ ranksBetween(lo, hi, j - i).forEach((k, t) => fixes.set(order[i + t], k))
+ i = j
+ }
+ return fixes
+}
+
+/**
+ * Move (or add) `nodeId` into `columnId` at `anchor`, returning the new assignments array — or the
+ * SAME array when the card is already exactly there (nothing to write). A `before` that names no
+ * card of that column is no anchor: the top. Ungrouped (removal) is the caller's, not this.
+ */
+export function placeAssignment<A extends RankedEntry>(
+ list: readonly A[],
+ nodeId: string,
+ columnId: string,
+ anchor: CardAnchor
+): A[] {
+ const i0 = list.findIndex((e) => e?.nodeId === nodeId)
+ const old = i0 === -1 ? undefined : list[i0]
+ const without = i0 === -1 ? [...list] : [...list.slice(0, i0), ...list.slice(i0 + 1)]
+ let col = columnOrder(without, columnId)
+ const anchorIdx = typeof anchor === 'object' ? col.findIndex((e) => e.nodeId === anchor.before) : -1
+ const at = anchor === 'end' ? col.length : anchorIdx !== -1 ? anchorIdx : 0
+ if (old && old.columnId === columnId && columnOrder(list, columnId).indexOf(old) === at) {
+ return list as A[]
+ }
+
+ // Repair the destination column, then make its array slots agree with its order.
+ let arr = without
+ const fixes = repairRanks(col)
+ if (fixes.size) {
+ arr = arr.map((e) => (fixes.has(e) ? { ...e, rank: fixes.get(e)! } : e))
+ col = columnOrder(arr, columnId)
+ }
+ const slots: number[] = []
+ arr.forEach((e, i) => {
+ if (e?.columnId === columnId) slots.push(i)
+ })
+ if (slots.some((s, k) => arr[s] !== col[k])) {
+ arr = [...arr]
+ slots.forEach((s, k) => {
+ arr[s] = col[k]
+ })
+ }
+
+ const prev = at > 0 ? col[at - 1] : undefined
+ const next = at < col.length ? col[at] : undefined
+ const rank = rankBetween(prev?.rank ?? null, next?.rank ?? null)
+ const moved = (old ? { ...old, columnId, rank } : { nodeId, columnId, rank }) as A
+
+ const pIdx = prev ? arr.indexOf(prev) : -1
+ const sIdx = next ? arr.indexOf(next) : -1
+ const fits = i0 !== -1 && (pIdx === -1 || pIdx < i0) && (sIdx === -1 || i0 <= sIdx)
+ const pos = fits ? i0 : sIdx !== -1 ? sIdx : pIdx !== -1 ? pIdx + 1 : i0 !== -1 ? i0 : arr.length
+ return [...arr.slice(0, pos), moved, ...arr.slice(pos)]
+}
diff --git a/src/shared/kanban-rank.test.ts b/src/shared/kanban-rank.test.ts
new file mode 100644
index 000000000..b5ad4fef0
--- /dev/null
+++ b/src/shared/kanban-rank.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest'
+import { RANK_MAX_LENGTH, isValidRank, rankBetween, ranksBetween } from './kanban-rank'
+
+describe('rankBetween — fractional-index strings', () => {
+ it('mints a first key, then keys before and after it', () => {
+ const first = rankBetween(null, null)
+ expect(isValidRank(first)).toBe(true)
+ const before = rankBetween(null, first)
+ const after = rankBetween(first, null)
+ expect(before < first).toBe(true)
+ expect(after > first).toBe(true)
+ })
+
+ it('always finds a key strictly between two distinct keys (no gap exhaustion)', () => {
+ let lo = rankBetween(null, null)
+ let hi = rankBetween(lo, null)
+ for (let i = 0; i < 500; i++) {
+ const mid = rankBetween(lo, hi)
+ expect(mid > lo && mid < hi, `${lo} < ${mid} < ${hi}`).toBe(true)
+ expect(isValidRank(mid)).toBe(true)
+ // Alternate sides so the gap keeps shrinking from both ends.
+ if (i % 2) lo = mid
+ else hi = mid
+ }
+ })
+
+ it('stays SHORT under the board’s default: a thousand inserts at the top of one column', () => {
+ let top = rankBetween(null, null)
+ for (let i = 0; i < 1000; i++) {
+ const next = rankBetween(null, top)
+ expect(next < top).toBe(true)
+ top = next
+ }
+ expect(top.length).toBeLessThanOrEqual(4)
+ })
+
+ it('stays short for a thousand appends too', () => {
+ let last = rankBetween(null, null)
+ for (let i = 0; i < 1000; i++) last = rankBetween(last, null)
+ expect(last.length).toBeLessThanOrEqual(4)
+ })
+
+ it('refuses an inverted or equal pair and an invalid key, rather than inventing an order', () => {
+ const a = rankBetween(null, null)
+ const b = rankBetween(a, null)
+ expect(() => rankBetween(b, a)).toThrow()
+ expect(() => rankBetween(a, a)).toThrow()
+ expect(() => rankBetween('not a key!', null)).toThrow()
+ })
+
+ it('compares with plain string order (code units) — what every reader, on every surface, uses', () => {
+ const keys: string[] = []
+ let k = rankBetween(null, null)
+ for (let i = 0; i < 50; i++) {
+ keys.push(k)
+ k = rankBetween(k, null)
+ }
+ expect([...keys].sort()).toEqual(keys)
+ })
+})
+
+describe('ranksBetween', () => {
+ it('mints n ascending keys inside the gap', () => {
+ const lo = rankBetween(null, null)
+ const hi = rankBetween(lo, null)
+ const keys = ranksBetween(lo, hi, 7)
+ expect(keys).toHaveLength(7)
+ expect([lo, ...keys, hi]).toEqual([lo, ...keys, hi].slice().sort())
+ expect(new Set(keys).size).toBe(7)
+ })
+
+ it('works open-ended on either side', () => {
+ expect(ranksBetween(null, null, 3)).toEqual([...ranksBetween(null, null, 3)].sort())
+ const hi = rankBetween(null, null)
+ const below = ranksBetween(null, hi, 4)
+ expect(below.every((k) => k < hi)).toBe(true)
+ expect(ranksBetween(null, null, 0)).toEqual([])
+ })
+})
+
+describe('isValidRank', () => {
+ it('accepts what rankBetween mints', () => {
+ expect(isValidRank(rankBetween(null, null))).toBe(true)
+ })
+
+ it('rejects garbage a hand edit could put in the file', () => {
+ for (const bad of ['', 'a', 'a0 ', 'a00', '!!', 'Aaaa', 7, null, {}, 'a0é', 'x'.repeat(300)]) {
+ expect(isValidRank(bad), String(bad)).toBe(false)
+ }
+ })
+})
+
+describe('rankBetween — randomized insert positions', () => {
+ it('keeps any sequence of inserts strictly ordered and valid (seeded)', () => {
+ let seed = 42
+ const rand = (): number => {
+ seed = (seed * 1103515245 + 12345) % 2147483648
+ return seed / 2147483648
+ }
+ const keys: string[] = []
+ for (let i = 0; i < 2000; i++) {
+ const at = Math.floor(rand() * (keys.length + 1))
+ const k = rankBetween(keys[at - 1] ?? null, keys[at] ?? null)
+ expect(isValidRank(k)).toBe(true)
+ keys.splice(at, 0, k)
+ }
+ for (let i = 1; i < keys.length; i++) expect(keys[i - 1] < keys[i]).toBe(true)
+ expect(Math.max(...keys.map((k) => k.length))).toBeLessThan(RANK_MAX_LENGTH)
+ })
+})
diff --git a/src/shared/kanban-rank.ts b/src/shared/kanban-rank.ts
new file mode 100644
index 000000000..1bcc8ba3e
--- /dev/null
+++ b/src/shared/kanban-rank.ts
@@ -0,0 +1,155 @@
+/**
+ * Rank strings for board order — fractional indexing over base-62 digits.
+ *
+ * A card's position in a column is a string key compared with PLAIN string order (UTF-16 code
+ * units; every key is ASCII, so byte order on every other surface agrees). Between any two distinct
+ * keys there is always another, so moving one card writes one card's key: no neighbour renumbering,
+ * no gap exhaustion, no rebalancing — which is what lets a move be a small diff that git merges
+ * across machines (the board is git-shared).
+ *
+ * Key shape: an INTEGER part followed by an optional FRACTION.
+ * - The integer part is a head letter plus digits; the head says how many digits follow
+ * (`a`..`z` → 1..26 digits, ascending; `A`..`Z` → 26..1 digits, the negative range). Stepping the
+ * integer is what a "before the first" / "after the last" insert does, so the board's default —
+ * an unanchored move lands at the TOP — costs a decrement, not a longer key: a thousand
+ * consecutive top inserts stay four characters long. A plain digit-string scheme grows by one
+ * character every few top inserts instead.
+ * - The fraction is the midpoint between two keys that share an integer part; it never ends in
+ * the zero digit, so there is always room before it.
+ *
+ * `isValidRank` is the gate for anything read from a file: a key a hand edit mangled is treated as
+ * ABSENT by the readers (the card's position then derives from array order), never fed to the
+ * generator, which refuses it.
+ */
+
+const DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
+const ZERO = DIGITS[0]
+const LAST = DIGITS[DIGITS.length - 1]
+/** The smallest integer part. Reserved: nothing may sort before it, so nothing may be it. */
+const SMALLEST_INTEGER = `A${ZERO.repeat(26)}`
+/** Longer than any key a board will ever mint; beyond it a "rank" is garbage, not a position. */
+export const RANK_MAX_LENGTH = 256
+
+const digitValue = (c: string): number => DIGITS.indexOf(c)
+
+/** Digits after the head letter, or -1 for a character that is not a head. */
+function integerDigits(head: string): number {
+ if (head >= 'a' && head <= 'z') return head.charCodeAt(0) - 'a'.charCodeAt(0) + 1
+ if (head >= 'A' && head <= 'Z') return 'Z'.charCodeAt(0) - head.charCodeAt(0) + 1
+ return -1
+}
+
+function integerPart(key: string): string {
+ const n = integerDigits(key[0] ?? '')
+ if (n < 0 || key.length < n + 1) throw new Error(`invalid rank: ${key}`)
+ return key.slice(0, n + 1)
+}
+
+/** Is `x` a rank this module could have minted (and can therefore extend)? Never throws. */
+export function isValidRank(x: unknown): x is string {
+ if (typeof x !== 'string' || x.length === 0 || x.length > RANK_MAX_LENGTH) return false
+ for (const c of x) if (digitValue(c) === -1) return false
+ const n = integerDigits(x[0])
+ if (n < 0 || x.length < n + 1) return false
+ if (x.slice(0, n + 1) === SMALLEST_INTEGER) return false
+ return !x.slice(n + 1).endsWith(ZERO)
+}
+
+/** A fraction strictly between `a` and `b` (`b` null = open-ended). Neither ends in ZERO. */
+function midpoint(a: string, b: string | null): string {
+ if (b !== null) {
+ // Skip the common prefix (a is right-padded with zeros for the comparison).
+ let n = 0
+ while ((a[n] ?? ZERO) === b[n]) n++
+ if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n))
+ }
+ const da = a ? digitValue(a[0]) : 0
+ const db = b !== null ? digitValue(b[0]) : DIGITS.length
+ if (db - da > 1) return DIGITS[Math.round((da + db) / 2)]
+ // Adjacent digits: take a's first digit and recurse into the tail.
+ if (b !== null && b.length > 1) return b.slice(0, 1)
+ return DIGITS[da] + midpoint(a.slice(1), null)
+}
+
+function stepInteger(x: string, dir: 1 | -1): string | null {
+ const head = x[0]
+ const digits = x.slice(1).split('')
+ let carry = true
+ for (let i = digits.length - 1; carry && i >= 0; i--) {
+ const d = digitValue(digits[i]) + dir
+ if (d === DIGITS.length) digits[i] = ZERO
+ else if (d === -1) digits[i] = LAST
+ else {
+ digits[i] = DIGITS[d]
+ carry = false
+ }
+ }
+ if (!carry) return head + digits.join('')
+ if (dir === 1) {
+ if (head === 'Z') return `a${ZERO}`
+ if (head === 'z') return null
+ const next = String.fromCharCode(head.charCodeAt(0) + 1)
+ if (next > 'a') digits.push(ZERO)
+ else digits.pop()
+ return next + digits.join('')
+ }
+ if (head === 'a') return `Z${LAST}`
+ if (head === 'A') return null
+ const next = String.fromCharCode(head.charCodeAt(0) - 1)
+ if (next < 'Z') digits.push(LAST)
+ else digits.pop()
+ return next + digits.join('')
+}
+
+/**
+ * A key strictly between `a` and `b`; `null` means open on that side (`rankBetween(null, null)` is
+ * a first key). Throws for an invalid key or `a >= b` — the caller is expected to have normalized
+ * its neighbours first, and inventing an order here would hide a bug.
+ */
+export function rankBetween(a: string | null, b: string | null): string {
+ if (a !== null && !isValidRank(a)) throw new Error(`invalid rank: ${a}`)
+ if (b !== null && !isValidRank(b)) throw new Error(`invalid rank: ${b}`)
+ if (a !== null && b !== null && a >= b) throw new Error(`rank ${a} is not before ${b}`)
+ if (a === null) {
+ if (b === null) return `a${ZERO}`
+ const ib = integerPart(b)
+ const fb = b.slice(ib.length)
+ if (ib === SMALLEST_INTEGER) return ib + midpoint('', fb)
+ if (ib < b) return ib
+ const down = stepInteger(ib, -1)
+ if (down === null) throw new Error('rank space exhausted below')
+ return down
+ }
+ if (b === null) {
+ const ia = integerPart(a)
+ const up = stepInteger(ia, 1)
+ return up === null ? ia + midpoint(a.slice(ia.length), null) : up
+ }
+ const ia = integerPart(a)
+ const ib = integerPart(b)
+ if (ia === ib) return ia + midpoint(a.slice(ia.length), b.slice(ib.length))
+ const up = stepInteger(ia, 1)
+ if (up === null) throw new Error('rank space exhausted above')
+ return up < b ? up : ia + midpoint(a.slice(ia.length), null)
+}
+
+/** `n` ascending keys strictly between `a` and `b` (same open-ended rules as `rankBetween`). */
+export function ranksBetween(a: string | null, b: string | null, n: number): string[] {
+ if (n <= 0) return []
+ if (n === 1) return [rankBetween(a, b)]
+ if (b === null) {
+ const out: string[] = []
+ let k = a
+ for (let i = 0; i < n; i++) out.push((k = rankBetween(k, null)))
+ return out
+ }
+ if (a === null) {
+ const out: string[] = []
+ let k: string | null = b
+ for (let i = 0; i < n; i++) out.push((k = rankBetween(null, k)))
+ return out.reverse()
+ }
+ const half = Math.floor(n / 2)
+ const mid = rankBetween(a, b)
+ return [...ranksBetween(a, mid, half), mid, ...ranksBetween(mid, b, n - half - 1)]
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 31639314c..a2f49911b 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -632,11 +632,15 @@ export interface KanbanColumn {
}
/** Assignment of one session node to a board column. A session with no assignment sits
- * in the virtual Ungrouped column (never persisted). Order within a column = relative
- * order in ProjectKanban.assignments. */
+ * in the virtual Ungrouped column (never persisted). Order within a column = `rank` (a
+ * fractional-index string, @shared/kanban-rank), and for an entry without a valid one, its
+ * position in ProjectKanban.assignments (@shared/kanban-order `columnOrder`). Every write keeps
+ * the ARRAY in rank order too, so a build that ignores `rank` shows the same column. */
export interface KanbanAssignment {
nodeId: string
columnId: string
+ /** Optional position key within the column. Absent / invalid ⇒ derived from array order. */
+ rank?: string
}
/** Per-project kanban board (docs/superpowers/specs/2026-07-18-kanban-view-design.md).