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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(kanban): tolerant board reads, order ops that converge, project-scoped order keys
review785ac6f9a311
diff --git a/src/core/canvas-sync.convergence.test.ts b/src/core/canvas-sync.convergence.test.tsindex 2b32be093..bfcc3ca12 100644--- a/src/core/canvas-sync.convergence.test.ts+++ b/src/core/canvas-sync.convergence.test.ts@@ -187,12 +187,14 @@ class Client {const stamped = this.order.stamp(m)// The re-creation gate, as Canvas has it: a re-creation of a key whose remove of ours is// still unacked would carry a `seen` below that remove — held (owed) until the echo lands.- if (!isRemoveOp(stamped) && this.order.hasPendingRemove(mutationKey(stamped))) return false+ // The project rides every key the order builds (ruling R4: a board's order ops are+ // per-project singletons) — the same PROJECT the cast goes out on.+ if (!isRemoveOp(stamped) && this.order.hasPendingRemove(mutationKey(stamped, PROJECT))) return falseif (!isCanvasMutation(stamped)) {this.refused++return false}- this.order.onLocal(stamped)+ this.order.onLocal(stamped, PROJECT)bus.cast(id, PROJECT, stamped)return true},@@ -202,9 +204,9 @@ class Client {if (projectId !== PROJECT) return// Mirrors Canvas: our own remove coming back RELEASES a re-creation the gate held — cast it now,// after this mutation is handled (a repaired remove is applied first), or it waits for an edit.- const key = mutationKey(m)+ const key = mutationKey(m, projectId)const held = this.order.hasPendingRemove(key)- const apply = this.order.accept(m)+ const apply = this.order.accept(m, projectId)const released = held && !this.order.hasPendingRemove(key)if (apply) {this.applied++diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.tsindex 1f1d35ad0..63bb730a9 100644--- a/src/core/canvas-sync.test.ts+++ b/src/core/canvas-sync.test.ts@@ -263,12 +263,24 @@ describe('initCanvasSync (reflector)', () => {// and, because every peer and the authority must receive the SAME repaired op rather than each// repairing the raw one, the reflector reflects the SANITIZED op (stamp fields kept).describe('initCanvasSync (reflector) — kanban ops', () => {- it('refuses a kb-label whose name carries a control character', () => {+ // Ruling R5: a name is REPAIRED (control and bidi characters stripped), never refused — the UI+ // has no length cap, so a refused rename would silently never sync. A name with nothing left once+ // repaired is still refused, and so is a bad id.+ it('refuses a kb-label whose name is empty once repaired, and one with a bad id', () => {t.setClients([1, 2])- t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' }, src: 'cv-a' })+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: '\u0007\u202e ', color: 'red' }, src: 'cv-a' })+ t.cast(1, 'p1', { op: 'kb-label', label: { id: '', name: 'Bug', color: 'red' }, src: 'cv-a' })expect(t.sent).toEqual([])})+ it('reflects a kb-label whose name carried control / bidi characters with them stripped', () => {+ t.setClients([1])+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: 'a\u0007b\u202e', color: 'red' }, src: 'cv-a' })+ expect(t.sent).toEqual([+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'kb-label', label: { id: 'l1', name: 'ab', color: 'red' }, src: 'cv-a', seq: 1 }] }+ ])+ })+it('reflects a valid kb-label to every client, stamped with the total order', () => {t.setClients([1, 2])const m = { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' }, src: 'cv-a', seen: 0 }diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.tsindex c8757ea82..bd5ca5057 100644--- a/src/core/canvas-sync.ts+++ b/src/core/canvas-sync.ts@@ -46,7 +46,7 @@ import {sanitizeCanvasMutation} from '../shared/canvas-mutations'import { type ClientId } from '../shared/presence'-import type { CanvasMutation } from '../shared/types'+import type { CanvasMutation, MutationStamp } from '../shared/types'// The ingest guard (`isCanvasMutation`) and its size cap live in `shared`, because the PUBLISHER// must reach the same verdict BEFORE it casts: a mutation this reflector refuses is dropped@@ -81,8 +81,8 @@ export function reflectTargets(all: ClientId[], _sender: ClientId): ClientId[] {* beyond the moment it actually cast. A non-integer / negative value is dropped, which degrades to* "unstamped" (judged exactly as before rule 4 existed), never to a value that outranks a delete.*/-export function stampMutation(m: CanvasMutation, seq: number): CanvasMutation {- const stamped: CanvasMutation = { ...m, seq }+export function stampMutation<M extends CanvasMutation>(m: M, seq: number): M & MutationStamp {+ const stamped: M & MutationStamp = { ...m, seq }if (!isRefId(stamped.src)) delete stamped.srcconst seen = stamped.seenif (typeof seen !== 'number' || !Number.isInteger(seen) || seen < 0) delete stamped.seendiff --git a/src/core/workspace-files.kanban-ops.test.ts b/src/core/workspace-files.kanban-ops.test.tsnew file mode 100644index 000000000..eb0ad3a61--- /dev/null+++ b/src/core/workspace-files.kanban-ops.test.ts@@ -0,0 +1,95 @@+// The board reducer and diff (@shared/kanban-ops) run on whatever board a project holds, and a+// board reaches a project through the load seam, `sanitizeKanban`. That seam deliberately admits a+// malformed `meta` and `labels` (types.ts: "tolerated as absent/malformed by every reader") — so the+// reducer and the diff are readers too, and neither may throw on anything the seam lets through.+// A throw here is not a refused op: it is a dead board sync for that project, on every edit.++import { describe, expect, it } from 'vitest'+import { sanitizeKanban } from './workspace-files'+import { applyKanbanOp, diffKanbanOps } from '../shared/kanban-ops'+import { createLabel, setCardLabels, setCardPriority } from '../shared/kanban-labels'+import type { KanbanOp, ProjectKanban } from '../shared/types'++const P = 'project-1'+const col = { id: 'c1', title: 'A', color: '#fff' }++/** Raw file shapes the load seam ADMITS (each is asserted to pass `sanitizeKanban` below). */+const SHAPES: Record<string, unknown> = {+ 'meta: {}': { columns: [col], assignments: [], meta: {} },+ 'meta: [null]': { columns: [col], assignments: [], meta: [null] },+ 'meta: [7, "x", { no nodeId }]': { columns: [col], assignments: [], meta: [7, 'x', { priority: 'high' }] },+ 'meta entry with labels: {}': { columns: [col], assignments: [], meta: [{ nodeId: 'n1', labels: { a: 1 } }] },+ 'labels: [null]': { columns: [col], assignments: [], labels: [null] },+ 'labels: {}': { columns: [col], assignments: [], labels: { a: 1 } },+ 'labels: [7, { no id }]': { columns: [col], assignments: [], labels: [7, { name: 'x', color: 'red' }] },+ 'views: 5': { columns: [col], assignments: [], views: 5 }+}++const OPS: KanbanOp[] = [+ { op: 'kb-meta', meta: { nodeId: 'n1', priority: 'high' } },+ { op: 'kb-meta-remove', nodeId: 'n1' },+ { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' } },+ { op: 'kb-label-remove', id: 'l1' },+ { op: 'kb-label-order', ids: ['l1'] },+ { op: 'kb-view', view: { id: 'v1', name: 'Mine', query: {} } },+ { op: 'kb-view-remove', id: 'v1' },+ { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' } },+ { op: 'kb-card-remove', nodeId: 'n1' },+ { op: 'kb-column', column: { id: 'c2', title: 'B', color: '#000' } },+ { op: 'kb-column-order', ids: ['c2', 'c1'] },+ { op: 'kb-column-remove', id: 'c1' }+]++const admitted = (raw: unknown): ProjectKanban => {+ const b = sanitizeKanban(JSON.parse(JSON.stringify(raw)))+ expect(b, 'the load seam admits this shape').toBeDefined()+ return b as ProjectKanban+}++describe('applyKanbanOp / diffKanbanOps on boards the load seam admits', () => {+ for (const [name, raw] of Object.entries(SHAPES)) {+ it(`${name}: every op applies without throwing`, () => {+ const b = admitted(raw)+ for (const op of OPS) expect(() => applyKanbanOp(b, op, P), op.op).not.toThrow()+ })++ it(`${name}: the diff after any edit does not throw`, () => {+ const b = admitted(raw)+ const created = createLabel(b, 'Bug', 'red')+ const edits: ProjectKanban[] = [+ ...OPS.map((op) => applyKanbanOp(b, op, P)),+ setCardPriority(b, 'n1', 'high'),+ created.k,+ // setCardLabels, not toggleCardLabel: the latter reads a card's `labels` raw and throws on+ // the malformed shape itself (pre-existing, reported) — this suite is about the reducer/diff.+ setCardLabels(created.k, 'n1', [created.id])+ ]+ for (const next of edits) {+ expect(() => diffKanbanOps(b, next, P, new Set(['n1']))).not.toThrow()+ expect(() => diffKanbanOps(next, b, P, new Set(['n1']))).not.toThrow()+ }+ })+ }++ it('a malformed meta is read as the valid entries it holds (none), and a write repairs it', () => {+ const b = admitted(SHAPES['meta: {}'])+ const next = applyKanbanOp(b, { op: 'kb-meta', meta: { nodeId: 'n1', priority: 'high' } }, P)+ expect(next.meta).toEqual([{ nodeId: 'n1', priority: 'high' }])+ const nulls = admitted(SHAPES['meta: [null]'])+ expect(applyKanbanOp(nulls, { op: 'kb-meta-remove', nodeId: 'n1' }, P).meta).toEqual([])+ })++ it('a malformed labels list is read as its valid entries, and a label op writes a clean list', () => {+ const b = admitted(SHAPES['labels: [null]'])+ expect(applyKanbanOp(b, { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' } }, P).labels)+ .toEqual([{ id: 'l1', name: 'Bug', color: 'red' }])+ expect(applyKanbanOp(b, { op: 'kb-label-remove', id: 'l1' }, P).labels).toEqual([])+ })++ it('an edit to a malformed board diffs to the ops for what actually changed', () => {+ const b = admitted(SHAPES['meta: {}'])+ expect(diffKanbanOps(b, setCardPriority(b, 'n1', 'high'), P, new Set(['n1']))).toEqual([+ { op: 'kb-meta', meta: { nodeId: 'n1', priority: 'high' } }+ ])+ })+})diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 62941a865..8fa02b554 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -3730,7 +3730,9 @@ export function Canvas() {// ⌘Z'd, within one round trip) would be dropped by every peer as a stale frame while we keep// showing it. Held = owed: the publisher keeps it, and the receive handler's release casts it// the moment the remove's echo lands. Never a remove itself (a remove is never stale).- if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped))) return false+ // The key carries the project it is cast into: a board's two order ops are per-project+ // singletons in the ONE order this Canvas keeps for every loaded project (ruling R4).+ if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped, projectId))) return false// The reflector REFUSES an oversized / malformed mutation at ingest, silently: no peer ever// sees it and there is no negative ack. Ask the same predicate FIRST, so a refusal costs us// neither a pending entry (which would deafen this node to its peers for the whole TTL — a@@ -3748,7 +3750,7 @@ export function Canvas() {else console.warn('[canvas-sync] refused an unsendable mutation', stamped.op)return false}- order.onLocal(stamped)+ order.onLocal(stamped, projectId)// Cast to the ACTIVE session's core — a relay tab publishes to the relay HOST, not to B's// own local core (the bug this fixes). Byte-identical on a local tab (`activeSession.api`// IS `window.nodeTerminal`). `canvasSyncTarget` decides the GATE (hasPeers) at bind time;@@ -3837,9 +3839,9 @@ export function Canvas() {hasPeersRef.current = true // proof of a peer, whatever the presence table saysconst order = orderRef.currentif (!order) return- const key = mutationKey(mutation)+ const key = mutationKey(mutation, projectId)const held = order.hasPendingRemove(key)- const apply = order.accept(mutation)+ const apply = order.accept(mutation, projectId)const released = held && !order.hasPendingRemove(key)if (released) queueMicrotask(releaseHeld)if (!apply) returndiff --git a/src/renderer/canvas/canvas-sync-ordering.source.test.ts b/src/renderer/canvas/canvas-sync-ordering.source.test.tsindex 2e442e2b3..6a1744350 100644--- a/src/renderer/canvas/canvas-sync-ordering.source.test.ts+++ b/src/renderer/canvas/canvas-sync-ordering.source.test.ts@@ -23,10 +23,10 @@ describe('the re-creation gate (canvas-order hasPendingRemove)', () => {// peer drops it as a stale frame (rule 4) while we keep showing it.it('the send callback holds a non-remove op whose key has our remove in flight', () => {const body = sendCallback()- const gate = body.indexOf('if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped))) return false')+ const gate = body.indexOf('if (!isRemoveOp(stamped) && order.hasPendingRemove(mutationKey(stamped, projectId))) return false')expect(gate).toBeGreaterThan(-1)// …before anything records or casts it: a held op must not leave a pending entry behind.- expect(gate).toBeLessThan(body.indexOf('order.onLocal(stamped)'))+ expect(gate).toBeLessThan(body.indexOf('order.onLocal(stamped, projectId)'))})// Held = owed, but nothing re-publishes on its own: our echo is an ack, it changes no React state,@@ -34,13 +34,27 @@ describe('the re-creation gate (canvas-order hasPendingRemove)', () => {it('our own remove coming back releases what the gate held', () => {const body = receiveHandler()const held = body.indexOf('const held = order.hasPendingRemove(key)')- const accept = body.indexOf('order.accept(mutation)')+ const accept = body.indexOf('order.accept(mutation, projectId)')expect(held).toBeGreaterThan(-1)expect(held).toBeLessThan(accept) // asked BEFORE the ack draws the count downexpect(body).toMatch(/const released = held && !order\.hasPendingRemove\(key\)/)expect(body).toMatch(/if \(released\) queueMicrotask\(releaseHeld\)/)})+ // RULING R4: one order serves every loaded project, and a board's two order ops are per-project+ // singletons — so both paths key, record and judge with the project the op belongs to. Dropping+ // the project from any one of these made our unacked reorder in A deafen a peer's reorder in B.+ it('both paths thread the project id into the order (key, onLocal, accept)', () => {+ const send = sendCallback()+ expect(send).toContain('mutationKey(stamped, projectId)')+ expect(send).toContain('order.onLocal(stamped, projectId)')+ expect(send).not.toMatch(/order\.onLocal\(stamped\)/)+ const recv = receiveHandler()+ expect(recv).toContain('const key = mutationKey(mutation, projectId)')+ expect(recv).toContain('order.accept(mutation, projectId)')+ expect(recv).not.toMatch(/order\.accept\(mutation\)/)+ })+it('the release publishes only when something is owed, and never during a load', () => {const start = src.indexOf('const releaseHeld = (): void => {')expect(start).toBeGreaterThan(-1)diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.tsindex f50fffcde..d93ffbe0d 100644--- a/src/shared/canvas-mutations.test.ts+++ b/src/shared/canvas-mutations.test.ts@@ -356,15 +356,17 @@ describe('isCanvasMutation — kanban ops', () => {for (const m of ok) expect(isCanvasMutation(m), JSON.stringify(m)).toBe(true)})- it('refuses what sanitizeKanbanOp refuses — an unknown kb- op, a bad id, a control character', () => {+ it('refuses what sanitizeKanbanOp refuses — an unknown kb- op, a bad id, a name empty once repaired', () => {expect(isCanvasMutation({ op: 'kb-nope' })).toBe(false)expect(isCanvasMutation({ op: 'kb-card-remove', nodeId: '' })).toBe(false)expect(isCanvasMutation({ op: 'kb-column-remove', id: 'x'.repeat(129) })).toBe(false)- expect(isCanvasMutation({ op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' } })).toBe(false)+ expect(isCanvasMutation({ op: 'kb-label', label: { id: 'l1', name: ' \u0007\u202e ', color: 'red' } })).toBe(false)})it('accepts a repairable op (the repair is sanitizeCanvasMutation\'s job, not a refusal)', () => {expect(isCanvasMutation({ op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'neon' } })).toBe(true)+ // ruling R5: a control character in a NAME is stripped, never a refusal (an id's still is)+ expect(isCanvasMutation({ op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' } })).toBe(true)})it('bounds a kanban op by the same byte cap', () => {diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.tsindex b8426aad5..6e710d071 100644--- a/src/shared/canvas-mutations.ts+++ b/src/shared/canvas-mutations.ts@@ -5,7 +5,7 @@import { isKanbanOp, sanitizeKanbanOp } from './kanban-ops'import { carryLocalNodeExec, sanitizeInboundMutation, sanitizeInboundNode } from './node-exec'import { REF_MAX_LEN } from './presence'-import type { BridgeLink, CanvasEdgeKind, CanvasMutation, CanvasNodeState } from './types'+import type { BridgeLink, CanvasEdgeKind, CanvasMutation, CanvasNodeState, SceneMutation } from './types'/*** A canvas as the publisher sees it: the nodes React Flow manages, plus the two PERSISTED edge@@ -328,8 +328,8 @@ function diffEdges(next: BridgeLink[],kind: CanvasEdgeKind,liveIds: ReadonlySet<string>,- upserts: CanvasMutation[],- removes: CanvasMutation[]+ upserts: SceneMutation[],+ removes: SceneMutation[]): void {const prevById = new Map(prev.map((e) => [e.id, e]))for (const edge of next) {@@ -360,11 +360,11 @@ function diffEdges(export function diffToMutations(prev: CanvasScene | CanvasNodeState[],next: CanvasScene | CanvasNodeState[]-): CanvasMutation[] {+): SceneMutation[] {const a = asScene(prev)const b = asScene(next)- const upserts: CanvasMutation[] = []- const removes: CanvasMutation[] = []+ const upserts: SceneMutation[] = []+ const removes: SceneMutation[] = []const prevById = new Map(a.nodes.map((node) => [node.id, node]))const nextIds = new Set(b.nodes.map((node) => node.id))@@ -380,8 +380,8 @@ export function diffToMutations(if (!nextIds.has(node.id)) removes.push({ op: 'remove', id: node.id })}- const edgeUpserts: CanvasMutation[] = []- const edgeRemoves: CanvasMutation[] = []+ const edgeUpserts: SceneMutation[] = []+ const edgeRemoves: SceneMutation[] = []const liveEdgeIds = new Set([...b.bridges, ...b.ropes].map((e) => e.id))diffEdges(a.bridges, b.bridges, 'bridge', liveEdgeIds, edgeUpserts, edgeRemoves)diffEdges(a.ropes, b.ropes, 'rope', liveEdgeIds, edgeUpserts, edgeRemoves)diff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.tsindex 68873f30d..107b72336 100644--- a/src/shared/canvas-order.test.ts+++ b/src/shared/canvas-order.test.ts@@ -12,7 +12,7 @@ import {PENDING_TTL_MS,REMOVED_MAX} from './canvas-order'-import type { CanvasMutation, CanvasNodeState } from './types'+import type { CanvasMutation, CanvasNodeState, SceneMutation } from './types'const node = (id: string, x = 0): CanvasNodeState =>({@@ -25,13 +25,13 @@ const node = (id: string, x = 0): CanvasNodeState =>size: { width: 10, height: 10 }}) as CanvasNodeState-const up = (id: string, x: number, src: string | undefined, seq: number): CanvasMutation => ({+const up = (id: string, x: number, src: string | undefined, seq: number): SceneMutation => ({op: 'upsert',node: node(id, x),...(src ? { src } : {}),seq})-const rm = (id: string, src: string | undefined, seq: number): CanvasMutation => ({+const rm = (id: string, src: string | undefined, seq: number): SceneMutation => ({op: 'remove',id,...(src ? { src } : {}),@@ -53,7 +53,7 @@ describe('mutationNodeId', () => {// One key space for nodes and edges, with a prefix: a node id and an edge id are generated// independently and could be equal. The kind is NOT in the key — one id is one edge.describe('mutationKey', () => {- const edgeUp = (id: string, kind: 'bridge' | 'rope'): CanvasMutation => ({+ const edgeUp = (id: string, kind: 'bridge' | 'rope'): SceneMutation => ({op: 'edge-upsert',kind,edge: { id, source: 'a', target: 'b' }@@ -90,6 +90,7 @@ describe('mutationKey', () => {// VALUE — "no placement", "no meta" — and must never tombstone, or a teammate filing a card a moment// after someone moved it to Ungrouped would be dropped everywhere as a stale frame.describe('kanban ops in the order', () => {+ const P = 'project-1'const card = (nodeId: string, columnId: string, src: string, seq: number, seen?: number): CanvasMutation => ({op: 'kb-card',assignment: { nodeId, columnId },@@ -99,15 +100,15 @@ describe('kanban ops in the order', () => {})it('keys every kanban op in the k: space, apart from the node its card names', () => {- expect(mutationKey(card('x', 'c', 'a', 1))).toBe('k:card:x')- expect(mutationKey({ op: 'kb-card-remove', nodeId: 'x' })).toBe('k:card:x')- expect(mutationKey({ op: 'kb-column', column: { id: 'x', title: 'T', color: '#fff' } })).toBe('k:col:x')- expect(mutationKey({ op: 'kb-column-remove', id: 'x' })).toBe('k:col:x')- expect(mutationKey({ op: 'kb-meta-remove', nodeId: 'x' })).toBe('k:meta:x')- expect(mutationKey({ op: 'kb-label-order', ids: [] })).toBe('k:labelorder')- expect(mutationKey({ op: 'kb-view-remove', id: 'x' })).toBe('k:view:x')+ expect(mutationKey(card('x', 'c', 'a', 1), P)).toBe('k:card:x')+ expect(mutationKey({ op: 'kb-card-remove', nodeId: 'x' }, P)).toBe('k:card:x')+ expect(mutationKey({ op: 'kb-column', column: { id: 'x', title: 'T', color: '#fff' } }, P)).toBe('k:col:x')+ expect(mutationKey({ op: 'kb-column-remove', id: 'x' }, P)).toBe('k:col:x')+ expect(mutationKey({ op: 'kb-meta-remove', nodeId: 'x' }, P)).toBe('k:meta:x')+ expect(mutationKey({ op: 'kb-label-order', ids: [] }, P)).toBe(`k:labelorder:${P}`)+ expect(mutationKey({ op: 'kb-view-remove', id: 'x' }, P)).toBe('k:view:x')// …never the node's key: a card move is not a node edit, a node delete does not tombstone its card- expect(mutationKey(card('x', 'c', 'a', 1))).not.toBe(mutationKey(up('x', 0, 'a', 1)))+ expect(mutationKey(card('x', 'c', 'a', 1), P)).not.toBe(mutationKey(up('x', 0, 'a', 1)))})it('addresses no node (mutationNodeId is null for every kanban op)', () => {@@ -118,38 +119,38 @@ describe('kanban ops in the order', () => {it('two kb-card ops for the same card: the higher seq wins, the straggler is dropped', () => {const o = createCanvasOrder('me')- expect(o.accept(card('n1', 'doing', 'a', 5))).toBe(true)- expect(o.accept(card('n1', 'todo', 'b', 4))).toBe(false) // superseded by seq 5- expect(o.accept(card('n1', 'done', 'b', 6))).toBe(true)+ expect(o.accept(card('n1', 'doing', 'a', 5), P)).toBe(true)+ expect(o.accept(card('n1', 'todo', 'b', 4), P)).toBe(false) // superseded by seq 5+ expect(o.accept(card('n1', 'done', 'b', 6), P)).toBe(true)})it('a kb-column-remove at seq 5 beats a kb-column cast before its sender saw it (seen 3, seq 6)', () => {const o = createCanvasOrder('me')- expect(o.accept({ op: 'kb-column-remove', id: 'c1', src: 'a', seq: 5 })).toBe(true)+ expect(o.accept({ op: 'kb-column-remove', id: 'c1', src: 'a', seq: 5 }, P)).toBe(true)const stale: CanvasMutation = { op: 'kb-column', column: { id: 'c1', title: 'T', color: '#fff' }, src: 'b', seq: 6, seen: 3 }- expect(o.accept(stale)).toBe(false)+ expect(o.accept(stale, P)).toBe(false)// a deliberate re-creation — cast knowing the removal — is applied- expect(o.accept({ ...stale, seq: 7, seen: 6 })).toBe(true)+ expect(o.accept({ ...stale, seq: 7, seen: 6 }, P)).toBe(true)})it('label and view removals tombstone their keys the same way', () => {const o = createCanvasOrder('me')- expect(o.accept({ op: 'kb-label-remove', id: 'l1', src: 'a', seq: 5 })).toBe(true)- expect(o.accept({ op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' }, src: 'b', seq: 6, seen: 3 })).toBe(false)- expect(o.accept({ op: 'kb-view-remove', id: 'v1', src: 'a', seq: 7 })).toBe(true)- expect(o.accept({ op: 'kb-view', view: { id: 'v1', name: 'Mine', query: {} }, src: 'b', seq: 8, seen: 3 })).toBe(false)+ expect(o.accept({ op: 'kb-label-remove', id: 'l1', src: 'a', seq: 5 }, P)).toBe(true)+ expect(o.accept({ op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' }, src: 'b', seq: 6, seen: 3 }, P)).toBe(false)+ expect(o.accept({ op: 'kb-view-remove', id: 'v1', src: 'a', seq: 7 }, P)).toBe(true)+ expect(o.accept({ op: 'kb-view', view: { id: 'v1', name: 'Mine', query: {} }, src: 'b', seq: 8, seen: 3 }, P)).toBe(false)})it('a kb-card-remove does NOT tombstone: a kb-card with seen 3 at seq 6 after it (seq 5) is accepted', () => {const o = createCanvasOrder('me')- expect(o.accept({ op: 'kb-card-remove', nodeId: 'n1', src: 'a', seq: 5 })).toBe(true)- expect(o.accept(card('n1', 'todo', 'b', 6, 3))).toBe(true)+ expect(o.accept({ op: 'kb-card-remove', nodeId: 'n1', src: 'a', seq: 5 }, P)).toBe(true)+ expect(o.accept(card('n1', 'todo', 'b', 6, 3), P)).toBe(true)})it('a kb-meta-remove does NOT tombstone either', () => {const o = createCanvasOrder('me')- expect(o.accept({ op: 'kb-meta-remove', nodeId: 'n1', src: 'a', seq: 5 })).toBe(true)- expect(o.accept({ op: 'kb-meta', meta: { nodeId: 'n1', priority: 'high' }, src: 'b', seq: 6, seen: 3 })).toBe(true)+ expect(o.accept({ op: 'kb-meta-remove', nodeId: 'n1', src: 'a', seq: 5 }, P)).toBe(true)+ expect(o.accept({ op: 'kb-meta', meta: { nodeId: 'n1', priority: 'high' }, src: 'b', seq: 6, seen: 3 }, P)).toBe(true)})it('the rule-4 deletion classification is exactly the five removals', () => {@@ -175,19 +176,47 @@ describe('kanban ops in the order', () => {it('a rule-2 hold applies to a kb-card-remove (a value) but not to a kb-column-remove (a deletion)', () => {const o = createCanvasOrder('me')- o.onLocal(o.stamp(card('n1', 'todo', 'me', 0))) // our own card move is unacked- expect(o.accept({ op: 'kb-card-remove', nodeId: 'n1', src: 'peer', seq: 7 })).toBe(false) // held off- o.onLocal(o.stamp({ op: 'kb-column', column: { id: 'c1', title: 'T', color: '#fff' } }))- expect(o.accept({ op: 'kb-column-remove', id: 'c1', src: 'peer', seq: 8 })).toBe(true) // never held off+ o.onLocal(o.stamp(card('n1', 'todo', 'me', 0)), P) // our own card move is unacked+ expect(o.accept({ op: 'kb-card-remove', nodeId: 'n1', src: 'peer', seq: 7 }, P)).toBe(false) // held off+ o.onLocal(o.stamp({ op: 'kb-column', column: { id: 'c1', title: 'T', color: '#fff' } }), P)+ expect(o.accept({ op: 'kb-column-remove', id: 'c1', src: 'peer', seq: 8 }, P)).toBe(true) // never held off})it('the re-creation gate covers a kanban deletion key, and ignores a card removal', () => {const o = createCanvasOrder('me')- o.onLocal(o.stamp({ op: 'kb-column-remove', id: 'c1' }))+ o.onLocal(o.stamp({ op: 'kb-column-remove', id: 'c1' }), P)expect(o.hasPendingRemove('k:col:c1')).toBe(true)- o.onLocal(o.stamp({ op: 'kb-card-remove', nodeId: 'n1' }))+ o.onLocal(o.stamp({ op: 'kb-card-remove', nodeId: 'n1' }), P)expect(o.hasPendingRemove('k:card:n1')).toBe(false)})++ // RULING R4 — one CanvasOrder orders EVERY loaded project (Canvas keeps loaded-but-inactive+ // projects in step), so a board's two singleton keys must carry the project: otherwise our own+ // unacked reorder in project A holds off (rule 2) a peer's reorder in project B, and B diverges.+ it('a project-A pending order op does not suppress a peer\'s project-B order op', () => {+ const o = createCanvasOrder('me')+ o.onLocal(o.stamp({ op: 'kb-column-order', ids: ['a2', 'a1'] }), 'A') // ours, unacked+ expect(o.accept({ op: 'kb-column-order', ids: ['b3', 'b1'], src: 'peer', seq: 7, seen: 6 }, 'B')).toBe(true)+ o.onLocal(o.stamp({ op: 'kb-label-order', ids: ['la'] }), 'A')+ expect(o.accept({ op: 'kb-label-order', ids: ['lb'], src: 'peer', seq: 8 }, 'B')).toBe(true)+ // …while in project A itself rule 2 still holds+ expect(o.accept({ op: 'kb-column-order', ids: ['a1', 'a2'], src: 'peer', seq: 9 }, 'A')).toBe(false)+ })++ it('scopes only the two singleton keys: per-item kanban, node and edge keys ignore the project', () => {+ expect(mutationKey({ op: 'kb-column-order', ids: [] }, 'A')).toBe('k:colorder:A')+ expect(mutationKey({ op: 'kb-label-order', ids: [] }, 'B')).toBe('k:labelorder:B')+ expect(mutationKey(card('n1', 'c', 'a', 1), 'A')).toBe(mutationKey(card('n1', 'c', 'a', 1), 'B'))+ expect(mutationKey(up('n1', 0, 'a', 1), 'A')).toBe('n:n1')+ expect(mutationKey({ op: 'edge-remove', kind: 'rope', id: 'e1' }, 'A')).toBe('e:e1')+ })++ it('a straggler order op in one project is still a straggler; another project has its own order', () => {+ const o = createCanvasOrder('me')+ expect(o.accept({ op: 'kb-column-order', ids: ['x'], src: 'a', seq: 5 }, 'A')).toBe(true)+ expect(o.accept({ op: 'kb-column-order', ids: ['y'], src: 'b', seq: 4 }, 'A')).toBe(false)+ expect(o.accept({ op: 'kb-column-order', ids: ['z'], src: 'b', seq: 4 }, 'B')).toBe(true)+ })})describe('createCanvasOrder', () => {@@ -315,7 +344,7 @@ describe('createCanvasOrder', () => {it('an unstamped mutation (no reflector in the path) is never treated as stale', () => {const o = createCanvasOrder('me')- const unstamped: CanvasMutation = { op: 'upsert', node: node('n1', 1) }+ const unstamped: SceneMutation = { op: 'upsert', node: node('n1', 1) }expect(o.accept(unstamped)).toBe(true)expect(o.accept(unstamped)).toBe(true)})@@ -434,7 +463,7 @@ describe('createCanvasOrder', () => {describe('a pending local remove (the re-creation gate)', () => {it('reports a pending local remove until its echo returns', () => {const o = createCanvasOrder('a')- const rm: CanvasMutation = { op: 'edge-remove', kind: 'bridge', id: 'b1', src: 'a' }+ const rm: SceneMutation = { op: 'edge-remove', kind: 'bridge', id: 'b1', src: 'a' }o.onLocal(rm)expect(o.hasPendingRemove('e:b1')).toBe(true)o.accept({ ...rm, seq: 7 })diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.tsindex b2a8611de..dbe265386 100644--- a/src/shared/canvas-order.ts+++ b/src/shared/canvas-order.ts@@ -70,7 +70,7 @@// Pure: no React, no DOM, no timers (the pending TTL below is a lazy clock read, not a timer).import { isKanbanDeletion, isKanbanOp, kanbanOpKey } from './kanban-ops'-import type { CanvasMutation, KanbanOp } from './types'+import type { CanvasMutation, KanbanOp, MutationStamp, SceneMutation } from './types'/*** How long an unacked local mutation keeps suppressing peers' mutations for that node.@@ -112,12 +112,23 @@ export const REMOVED_MAX = 512* same identity (`applyEdgeMutationToScene` in canvas-mutations).** Kanban ops take the third prefix, `k:`, with a sub-prefix per board item (`k:col:<id>`,- * `k:card:<nodeId>`, `k:colorder`, … — `kanbanOpKey`). A card's placement and meta are keyed by- * the node id they describe, under their own sub-prefixes, so they never share an order with the- * node itself: deleting a node does not tombstone its card, and a card move is not a node edit.+ * `k:card:<nodeId>`, `k:colorder:<projectId>`, … — `kanbanOpKey`). A card's placement and meta are+ * keyed by the node id they describe, under their own sub-prefixes, so they never share an order+ * with the node itself: deleting a node does not tombstone its card, and a card move is not a node+ * edit.+ *+ * THE PROJECT. One `CanvasOrder` orders every loaded project (Canvas applies mutations for+ * loaded-but-inactive projects too), and a board's two order ops are per-project SINGLETONS — so+ * their keys carry the project (ruling R4), and every caller that may hold a board op must pass it.+ * The overloads make that a type error rather than a convention: a SceneMutation (node / edge) keys+ * the same in every project and may omit it; anything typed `CanvasMutation` may not.*/-export function mutationKey(m: CanvasMutation): string {- if (isKanbanOp(m)) return kanbanOpKey(m as KanbanOp)+export function mutationKey(m: SceneMutation, projectId?: string): string+export function mutationKey(m: CanvasMutation, projectId: string): string+export function mutationKey(m: CanvasMutation, projectId?: string): string {+ // `?? ''` is unreachable through the types (a board op has no overload without a project); it+ // keeps an untyped caller keying on the empty scope rather than throwing on the order's hot path.+ if (isKanbanOp(m)) return kanbanOpKey(m as KanbanOp, projectId ?? '')if (m.op === 'edge-remove') return `e:${m.id}`if (m.op === 'edge-upsert') return `e:${m.edge.id}`if (m.op === 'remove') return `n:${m.id}`@@ -170,16 +181,20 @@ export interface CanvasOrder {* bytes smaller than the one that actually goes on the wire — the one difference that can put a* borderline mutation on the wrong side of the cap.*/- stamp(m: CanvasMutation): CanvasMutation- /** Record a mutation WE are casting (it becomes pending until its echo comes back). */- onLocal(m: CanvasMutation): void+ stamp<M extends CanvasMutation>(m: M): M & MutationStamp+ /** Record a mutation WE are casting (it becomes pending until its echo comes back). `projectId`+ * is the canvas it is cast into — it scopes a board's singleton order keys (see `mutationKey`),+ * and is required for anything that may be a board op. */+ onLocal(m: SceneMutation, projectId?: string): void+ onLocal(m: CanvasMutation, projectId: string): void/**- * Decide an incoming mutation (a peer's, or our own echoed back).+ * Decide an incoming mutation (a peer's, or our own echoed back) for the canvas `projectId`.* `true` → apply it to the canvas.* `false` → drop it: our own echo (already applied), a straggler the total order has superseded,* or a peer's edit to a node whose newer local edit of ours is still in flight.*/- accept(m: CanvasMutation): boolean+ accept(m: SceneMutation, projectId?: string): boolean+ accept(m: CanvasMutation, projectId: string): boolean/*** True while one of OUR remove-class casts (`remove` / `edge-remove`) for `key` (a `mutationKey`)* is unacked — THE RE-CREATION GATE.@@ -195,6 +210,10 @@ export interface CanvasOrder {* Counted per key, not a flag: two removes in flight (delete, undo, delete) release on the second* ack. Not TTL-bound, unlike rule 2's suppression: a late ack is exactly when the gate matters, and* a lost one comes with a reconnect, whose `reset` clears it.+ *+ * The PROJECT rides in the key: callers build it with `mutationKey(m, projectId)` — the same+ * function `onLocal` keys with — so the gate is project-scoped wherever a key is. (Only a+ * remove-class op can open the gate, and none of those has a project-scoped key today.)*/hasPendingRemove(key: string): boolean/** Forget the per-connection order state on a genuine reconnect (see `createReconnectWatch`) —@@ -297,15 +316,15 @@ export function createCanvasOrder(}return {- stamp(m) {+ stamp<M extends CanvasMutation>(m: M): M & MutationStamp {// `lastSeq` 0 = we have applied nothing from the reflector yet, which is also the value an// unstamped mutation would carry. Stamp it anyway: 0 is a truthful causal position (we know// about nothing), and it is what makes a first-frame drag lose to a delete that precedes it.return { ...m, seen: lastSeq }},- onLocal(m) {- const id = mutationKey(m)+ onLocal(m: CanvasMutation, projectId?: string) {+ const id = mutationKey(m, projectId ?? '')const p = pending.get(id)if (p) {p.count++@@ -321,8 +340,8 @@ export function createCanvasOrder(superseded.delete(id)},- accept(m) {- const id = mutationKey(m)+ accept(m: CanvasMutation, projectId?: string) {+ const id = mutationKey(m, projectId ?? '')const seq = m.seq ?? 0const highest = seen.get(id) ?? 0// `seq` 0 means an unstamped mutation (no reflector in the path) — never treat it as stale.diff --git a/src/shared/kanban-ops.convergence.test.ts b/src/shared/kanban-ops.convergence.test.tsnew file mode 100644index 000000000..dd8e59ef7--- /dev/null+++ b/src/shared/kanban-ops.convergence.test.ts@@ -0,0 +1,101 @@+// Board convergence under concurrency: two clients and the authority, each applying the reflector's+// stream through the SAME order (`createCanvasOrder`) and the SAME reducer (`applyKanbanOp`), with+// every client publishing through `diffKanbanOps`. A column list is a LIST, and an item op+// (`kb-column`) only says the column exists — its place comes from the order op (ruling R3). Two+// people adding a column at once used to leave A at …,X,Y and B at …,Y,X for good.++import { describe, expect, it } from 'vitest'+import { applyKanbanOp, diffKanbanOps } from './kanban-ops'+import { createCanvasOrder } from './canvas-order'+import { defaultKanbanFor } from './kanban-default-board'+import type { CanvasMutation, KanbanOp, ProjectKanban } from './types'++const P = 'project-1'++interface Replica {+ name: string+ order: ReturnType<typeof createCanvasOrder>+ board: ProjectKanban+}++/** A bus with the reflector's contract: one total order (`seq`), delivered to every replica — the+ * sender included (its copy is its ack) — and to the authority, in that order. */+function world(names: string[]) {+ let seq = 0+ let authority: ProjectKanban = defaultKanbanFor(P)+ const wire: CanvasMutation[] = []+ const replicas: Replica[] = names.map((name) => ({+ name,+ order: createCanvasOrder(name),+ board: defaultKanbanFor(P)+ }))+ const byName = new Map(replicas.map((r) => [r.name, r]))+ return {+ replicas,+ authority: () => authority,+ /** A local edit on one replica: take the new board, cast its diff (what the publisher does). */+ edit(name: string, next: (b: ProjectKanban) => ProjectKanban) {+ const r = byName.get(name)!+ const after = next(r.board)+ for (const op of diffKanbanOps(r.board, after, P, new Set())) {+ const m = r.order.stamp({ ...op, src: r.name } as CanvasMutation)+ r.order.onLocal(m, P)+ wire.push(m)+ }+ r.board = after+ },+ /** The reflector stamps what arrived, in arrival order, and fans it out. */+ reflect() {+ for (const m of wire.splice(0).map((x) => ({ ...x, seq: ++seq }))) {+ authority = applyKanbanOp(authority, m as unknown as KanbanOp, P)+ for (const r of replicas) {+ if (r.order.accept(m, P)) r.board = applyKanbanOp(r.board, m as unknown as KanbanOp, P)+ }+ }+ }+ }+}++const ids = (k: ProjectKanban) => k.columns.map((c) => c.id)+const add = (id: string, title: string) => (b: ProjectKanban): ProjectKanban => ({+ ...b,+ columns: [...b.columns, { id, title, color: '#123456' }]+})++describe('board convergence (ruling R3)', () => {+ it('two clients adding a column at once converge on every replica and the authority', () => {+ const w = world(['A', 'B'])+ w.edit('A', add('kcol-X', 'X'))+ w.edit('B', add('kcol-Y', 'Y'))+ w.reflect()+ const [a, b] = w.replicas+ expect(ids(a.board)).toEqual(ids(b.board))+ expect(ids(a.board)).toEqual(ids(w.authority()))+ // …on the LATER order op's list: B cast after A, so B's order (…, Y) leads and X follows+ expect(ids(a.board).slice(-2)).toEqual(['kcol-Y', 'kcol-X'])+ })++ it('a column inserted mid-list lands mid-list on the peer (add + move in one edit)', () => {+ const w = world(['A', 'B'])+ w.edit('A', (b) => {+ const [c0, ...rest] = b.columns+ return { ...b, columns: [c0, { id: 'kcol-new', title: 'New', color: '#123456' }, ...rest] }+ })+ w.reflect()+ const [a, b] = w.replicas+ expect(ids(b.board)).toEqual(ids(a.board))+ expect(ids(b.board)[1]).toBe('kcol-new')+ expect(ids(w.authority())).toEqual(ids(a.board))+ })++ it('two clients adding a label at once converge too (kb-label-order)', () => {+ const w = world(['A', 'B'])+ w.edit('A', (b) => ({ ...b, labels: [...(b.labels ?? []), { id: 'l-x', name: 'x', color: 'red' }] }))+ w.edit('B', (b) => ({ ...b, labels: [...(b.labels ?? []), { id: 'l-y', name: 'y', color: 'blue' }] }))+ w.reflect()+ const [a, b] = w.replicas+ const labels = (k: ProjectKanban) => (k.labels ?? []).map((l) => l.id)+ expect(labels(a.board)).toEqual(labels(b.board))+ expect(labels(a.board)).toEqual(labels(w.authority()))+ })+})diff --git a/src/shared/kanban-ops.test.ts b/src/shared/kanban-ops.test.tsindex bcd1393b7..cc6fc8c3d 100644--- a/src/shared/kanban-ops.test.ts+++ b/src/shared/kanban-ops.test.ts@@ -1,7 +1,9 @@import { describe, it, expect } from 'vitest'import { applyKanbanOp, diffKanbanOps, sanitizeKanbanOp, kanbanOpKey, isKanbanDeletion } from './kanban-ops'import { defaultKanbanFor } from './kanban-default-board'-import type { ProjectKanban } from './types'+import { columnOrder } from './kanban-order'+import { isValidRank, rankBetween } from './kanban-rank'+import type { KanbanOp, ProjectKanban } from './types'const P = 'project-1'const base = (): ProjectKanban => defaultKanbanFor(P)@@ -21,9 +23,38 @@ describe('sanitizeKanbanOp', () => {expect(sanitizeKanbanOp({ op: 'kb-column', column: { id: 'c1', title: 'X', color: '#fff', category: 'weird' } })).toEqual({ op: 'kb-column', column: { id: 'c1', title: 'X', color: '#fff' } })})- it('refuses a label name with control characters and an over-long one', () => {- expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' } })).toBeNull()- expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: 'x'.repeat(61), color: 'red' } })).toBeNull()+ // Names and titles are REPAIRED, never refused (ruling R5): the UI has no maxLength, so a refused+ // rename would silently never sync. Only a name that is empty after the repair is refused.+ it('strips control characters and bidi overrides from a label name, and truncates it to 60 code points', () => {+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' } }))+ .toEqual({ op: 'kb-label', label: { id: 'l1', name: 'ab', color: 'red' } })+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: '\u202eevil\u2066\u2069 ', color: 'red' } }))+ .toEqual({ op: 'kb-label', label: { id: 'l1', name: 'evil', color: 'red' } })+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: 'x'.repeat(61), color: 'red' } }))+ .toEqual({ op: 'kb-label', label: { id: 'l1', name: 'x'.repeat(60), color: 'red' } })+ // 60 CODE POINTS: an astral character is one, and is never split in half+ const astral = sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: '😀'.repeat(61), color: 'red' } }) as Extract<KanbanOp, { op: 'kb-label' }>+ expect([...astral.label.name]).toHaveLength(60)+ expect(astral.label.name).toBe('😀'.repeat(60))+ })+ it('refuses a label name that is empty once repaired', () => {+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: ' \u0007\u202e ', color: 'red' } })).toBeNull()+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: '', color: 'red' } })).toBeNull()+ })+ it('repairs a column title the same way (200 code points), and refuses an empty one', () => {+ expect(sanitizeKanbanOp({ op: 'kb-column', column: { id: 'c1', title: ' In\nProgress\u202d ', color: '#fff' } }))+ .toEqual({ op: 'kb-column', column: { id: 'c1', title: 'InProgress', color: '#fff' } })+ expect(sanitizeKanbanOp({ op: 'kb-column', column: { id: 'c1', title: 'y'.repeat(250), color: '#fff' } }))+ .toEqual({ op: 'kb-column', column: { id: 'c1', title: 'y'.repeat(200), color: '#fff' } })+ expect(sanitizeKanbanOp({ op: 'kb-column', column: { id: 'c1', title: '\u0000 ', color: '#fff' } })).toBeNull()+ })+ it('strips control characters and bidi overrides from an assignee name', () => {+ expect(sanitizeKanbanOp({ op: 'kb-meta', meta: { nodeId: 'n1', assignees: [{ name: 'Ada\u202egnihsihp', color: '#f00' }, { name: '\u0007', color: '#0f0' }] } }))+ .toEqual({ op: 'kb-meta', meta: { nodeId: 'n1', assignees: [{ name: 'Adagnihsihp', color: '#f00' }] } })+ })+ it('ids stay refuse-only: a control character in an id is not repaired', () => {+ expect(sanitizeKanbanOp({ op: 'kb-column-remove', id: 'x'.repeat(129) })).toBeNull()+ expect(sanitizeKanbanOp({ op: 'kb-card', assignment: { nodeId: '', columnId: 'c1' } })).toBeNull()})it('drops an invalid rank rather than the whole op', () => {expect(sanitizeKanbanOp({ op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1', rank: '!!' } }))@@ -33,9 +64,17 @@ describe('sanitizeKanbanOp', () => {describe('keys and deletions', () => {it('uses one k: key space', () => {- expect(kanbanOpKey({ op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c' } })).toBe('k:card:n1')- expect(kanbanOpKey({ op: 'kb-card-remove', nodeId: 'n1' })).toBe('k:card:n1')- expect(kanbanOpKey({ op: 'kb-column-order', ids: [] })).toBe('k:colorder')+ expect(kanbanOpKey({ op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c' } }, P)).toBe('k:card:n1')+ expect(kanbanOpKey({ op: 'kb-card-remove', nodeId: 'n1' }, P)).toBe('k:card:n1')+ })+ // One CanvasOrder orders every loaded project, so a board's two SINGLETON keys must carry the+ // project (ruling R4) — else our unacked reorder in A holds off a peer's reorder in B (rule 2).+ // Per-item keys need no scope: node ids are global, column ids are per-project seeded or random.+ it('scopes the two singleton order keys by project, and only those', () => {+ expect(kanbanOpKey({ op: 'kb-column-order', ids: [] }, 'A')).toBe('k:colorder:A')+ expect(kanbanOpKey({ op: 'kb-label-order', ids: [] }, 'A')).toBe('k:labelorder:A')+ expect(kanbanOpKey({ op: 'kb-column-order', ids: [] }, 'B')).not.toBe(kanbanOpKey({ op: 'kb-column-order', ids: [] }, 'A'))+ expect(kanbanOpKey({ op: 'kb-column-remove', id: 'c' }, 'A')).toBe(kanbanOpKey({ op: 'kb-column-remove', id: 'c' }, 'B'))})it('only column/label/view removals are deletions (rule 4); card and meta removals are values', () => {expect(isKanbanDeletion({ op: 'kb-column-remove', id: 'c' })).toBe(true)@@ -58,6 +97,47 @@ describe('applyKanbanOp', () => {expect(b.assignments.filter((a) => a.columnId === todo).map((a) => a.nodeId)).toEqual(['n2'])expect(b.assignments.filter((a) => a.columnId === doing).map((a) => a.nodeId)).toEqual(['n1'])})+ // With REAL ranks and several cards: the array keeps each column in rank order (the reader an+ // older build uses), and it agrees with `columnOrder` (the reader this build uses).+ it('places cards with valid ranks in rank order, several per column', () => {+ const r = ['a0', 'a1', 'a2', 'a3']+ expect(r.every(isValidRank)).toBe(true)+ let b = base()+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'c', columnId: todo, rank: r[2] } }, P)+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'x', columnId: doing, rank: r[0] } }, P)+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'a', columnId: todo, rank: r[0] } }, P)+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'd', columnId: todo, rank: r[3] } }, P)+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'b', columnId: todo, rank: r[1] } }, P)+ const between = rankBetween(r[1], r[2])+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'bc', columnId: todo, rank: between } }, P)+ const inArray = b.assignments.filter((a) => a.columnId === todo).map((a) => a.nodeId)+ expect(inArray).toEqual(['a', 'b', 'bc', 'c', 'd'])+ expect(columnOrder(b.assignments, todo).map((a) => a.nodeId)).toEqual(inArray)+ // moving the top card to the bottom of the same column+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'a', columnId: todo, rank: rankBetween(r[3], null) } }, P)+ expect(b.assignments.filter((a) => a.columnId === todo).map((a) => a.nodeId)).toEqual(['b', 'bc', 'c', 'd', 'a'])+ })+ it('an invalid rank is treated as absent — incoming (goes to the end) and already placed (reads as its predecessor)', () => {+ let b = base()+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo, rank: 'a0' } }, P)+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'n3', columnId: todo, rank: 'a2' } }, P)+ // incoming invalid rank: not compared as a string (`'!!'` sorts before every real rank)+ const incoming = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'z', columnId: todo, rank: '!!' } }, P)+ expect(incoming.assignments.filter((a) => a.columnId === todo).map((a) => a.nodeId)).toEqual(['n1', 'n3', 'z'])+ // an already-placed entry with an invalid rank ('zz') sits with its predecessor (a0), so a card+ // ranked a1 lands AFTER it — not before, which a plain string compare ('zz' > 'a1') would do+ const legacy: ProjectKanban = {+ ...base(),+ assignments: [+ { nodeId: 'n1', columnId: todo, rank: 'a0' },+ { nodeId: 'n2', columnId: todo, rank: 'zz' },+ { nodeId: 'n3', columnId: todo, rank: 'a2' }+ ]+ }+ const placed = applyKanbanOp(legacy, { op: 'kb-card', assignment: { nodeId: 'x', columnId: todo, rank: 'a1' } }, P)+ expect(columnOrder(placed.assignments, todo).map((a) => a.nodeId)).toEqual(['n1', 'n2', 'x', 'n3'])+ expect(placed.assignments.map((a) => a.nodeId)).toEqual(['n1', 'n2', 'x', 'n3'])+ })it('a column removal also drops the column’s placements', () => {let b = applyKanbanOp(base(), { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)b = applyKanbanOp(b, { op: 'kb-column-remove', id: todo }, P)@@ -110,8 +190,54 @@ describe('diffKanbanOps', () => {let next = applyKanbanOp(prev, { op: 'kb-column-remove', id: todo }, P)next = applyKanbanOp(next, { op: 'kb-label', label: { id: 'l1', name: 'x', color: 'red' } }, P)const ops = diffKanbanOps(prev, next, P, live('n1')).map((o) => o.op)- // No separate kb-card-remove: applyKanbanOp drops the column's placements with the column.- expect(ops).toEqual(['kb-label', 'kb-column-remove'])+ // No separate kb-card-remove: applyKanbanOp drops the column's placements with the column. The+ // label set grew, so its order op rides along (R3), after the label it orders.+ expect(ops).toEqual(['kb-label', 'kb-label-order', 'kb-column-remove'])+ })+ // RULING R3 — an order op rides whenever the id set GAINED an id, or the relative order of the ids+ // both sides share changed. `kb-column` alone appends on a peer, so without it a column inserted+ // mid-list (the UI's add-then-move, a git pull) lands last everywhere else.+ const replay = (prev: ProjectKanban, ops: KanbanOp[]): ProjectKanban =>+ ops.reduce((b, o) => applyKanbanOp(b, o, P), prev)+ it('a new column NOT at the end emits the order op, and a peer replaying the ops gets the same order', () => {+ const prev = base()+ const [a, b2, c] = prev.columns+ const next: ProjectKanban = { ...prev, columns: [a, { id: 'kcol-new', title: 'New', color: '#123456' }, b2, c] }+ const ops = diffKanbanOps(prev, next, P, live())+ expect(ops).toEqual([+ { op: 'kb-column', column: { id: 'kcol-new', title: 'New', color: '#123456' } },+ { op: 'kb-column-order', ids: next.columns.map((x) => x.id) }+ ])+ expect(replay(prev, ops).columns.map((x) => x.id)).toEqual(next.columns.map((x) => x.id))+ })+ it('a new column at the end still emits the order op (the id set grew)', () => {+ const prev = base()+ const next: ProjectKanban = { ...prev, columns: [...prev.columns, { id: 'kcol-new', title: 'New', color: '#123456' }] }+ expect(diffKanbanOps(prev, next, P, live()).map((o) => o.op)).toEqual(['kb-column', 'kb-column-order'])+ })+ it('moving a column emits exactly one kb-column-order with the whole next order', () => {+ const prev = base()+ const [a, b2, c] = prev.columns+ const next: ProjectKanban = { ...prev, columns: [c, a, b2] }+ expect(diffKanbanOps(prev, next, P, live())).toEqual([{ op: 'kb-column-order', ids: [c.id, a.id, b2.id] }])+ })+ it('renaming a column or removing one emits no order op', () => {+ const prev = base()+ const renamed: ProjectKanban = { ...prev, columns: prev.columns.map((x, i) => (i === 1 ? { ...x, title: 'Doing' } : x)) }+ expect(diffKanbanOps(prev, renamed, P, live()).map((o) => o.op)).toEqual(['kb-column'])+ const removed: ProjectKanban = { ...prev, columns: prev.columns.slice(1) }+ expect(diffKanbanOps(prev, removed, P, live()).map((o) => o.op)).toEqual(['kb-column-remove'])+ })+ it('adding a label emits kb-label-order; reordering labels emits exactly the order op', () => {+ const l1 = { id: 'l1', name: 'Bug', color: 'red' as const }+ const l2 = { id: 'l2', name: 'Feat', color: 'blue' as const }+ const prev: ProjectKanban = { ...base(), labels: [l1] }+ expect(diffKanbanOps(prev, { ...prev, labels: [l2, l1] }, P, live())).toEqual([+ { op: 'kb-label', label: l2 },+ { op: 'kb-label-order', ids: ['l2', 'l1'] }+ ])+ const two: ProjectKanban = { ...base(), labels: [l1, l2] }+ expect(diffKanbanOps(two, { ...two, labels: [l2, l1] }, P, live())).toEqual([{ op: 'kb-label-order', ids: ['l2', 'l1'] }])})it('never diffs github or pullLinks', () => {const prev = base()diff --git a/src/shared/kanban-ops.ts b/src/shared/kanban-ops.tsindex bcd2bdef9..f3e70f163 100644--- a/src/shared/kanban-ops.ts+++ b/src/shared/kanban-ops.ts@@ -6,15 +6,19 @@import { isRefId } from './canvas-mutations'import { defaultKanbanFor } from './kanban-default-board'-import { KANBAN_LABEL_COLORS } from './kanban-labels'+import { boardLabels, KANBAN_LABEL_COLORS, metaList } from './kanban-labels'import { isValidRank } from './kanban-rank'import { sanitizeViews } from './kanban-views'+import { capCodePoints } from './presence'import type {KanbanAssignment, KanbanCardMeta, KanbanColumn, KanbanColumnCategory, KanbanLabel,KanbanLabelColor, KanbanOp, KanbanPriority, KanbanSavedView, ProjectKanban} from './types'const CONTROL = /[\u0000-\u001f\u007f-\u009f]/+/** What a display name must never carry: C0/C1 controls (they break a name out of its one-line chip)+ * and the bidi overrides / isolates (they make a name DISPLAY as something it is not). */+const UNSAFE_DISPLAY = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/gconst TITLE_MAX = 200const COLOR_MAX = 64const NAME_MAX = 100@@ -29,6 +33,18 @@ const DUE_MAX = 32_503_680_000_000const isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x)const text = (x: unknown, max: number): string | null =>typeof x === 'string' && x.length <= max && !CONTROL.test(x) ? x : null+/**+ * A label name, column title or assignee name, REPAIRED rather than refused (ruling R5): the UI puts+ * no length cap on them, so refusing an over-long rename would make it silently never sync. Unsafe+ * characters are removed, the rest trimmed, then cut to `max` CODE POINTS (never splitting an astral+ * character in half) and trimmed again. Only what is empty once repaired is refused (`null`). Ids+ * are never passed through here — an id is an address, and a repaired one addresses the wrong thing.+ */+function displayText(x: unknown, max: number): string | null {+ if (typeof x !== 'string') return null+ const out = capCodePoints(x.replace(UNSAFE_DISPLAY, '').trim(), max).trim()+ return out ? out : null+}const idList = (x: unknown): string[] | null => {if (!Array.isArray(x) || x.length > LIST_MAX || !x.every(isRefId)) return nullreturn [...new Set(x as string[])]@@ -36,7 +52,7 @@ const idList = (x: unknown): string[] | null => {function column(x: unknown): KanbanColumn | null {if (!isObj(x) || !isRefId(x.id)) return null- const title = text(x.title, TITLE_MAX)+ const title = displayText(x.title, TITLE_MAX)const color = text(x.color, COLOR_MAX)if (title === null || color === null) return nullconst out: KanbanColumn = { id: x.id, title, color }@@ -57,7 +73,7 @@ function meta(x: unknown): KanbanCardMeta | null {if (Array.isArray(x.assignees)) {const a = x.assignees.filter(isObj)- .map((p) => ({ name: text(p.name, NAME_MAX), color: text(p.color, COLOR_MAX) }))+ .map((p) => ({ name: displayText(p.name, NAME_MAX), color: text(p.color, COLOR_MAX) })).filter((p): p is { name: string; color: string } => !!p.name && p.color !== null).slice(0, 50)if (a.length) out.assignees = a@@ -71,9 +87,9 @@ function meta(x: unknown): KanbanCardMeta | null {}function label(x: unknown): KanbanLabel | null {- if (!isObj(x) || !isRefId(x.id) || typeof x.name !== 'string') return null- const name = x.name.trim()- if (!name || [...name].length > LABEL_NAME_MAX || CONTROL.test(name)) return null+ if (!isObj(x) || !isRefId(x.id)) return null+ const name = displayText(x.name, LABEL_NAME_MAX)+ if (name === null) return nullconst color: KanbanLabelColor = KANBAN_LABEL_COLORS.includes(x.color as KanbanLabelColor)? (x.color as KanbanLabelColor): 'default'@@ -91,7 +107,8 @@ export function isKanbanOp(m: { op?: unknown }): boolean {}/** The sanitized op, or null to REFUSE it. Refusals are whole-op (a bad id addresses the wrong- * thing); repairable fields (colour, rank, priority, dueAt, category) are repaired or dropped. */+ * thing); repairable fields are repaired or dropped — colour, rank, priority, dueAt, category, and+ * the display text (label name, column title, assignee name: see `displayText`). */export function sanitizeKanbanOp(m: unknown): KanbanOp | null {if (!isObj(m)) return nullswitch (m.op) {@@ -111,19 +128,27 @@ export function sanitizeKanbanOp(m: unknown): KanbanOp | null {}}-/** The ordering key (canvas-order): one `k:` space with a sub-prefix per item kind. */-export function kanbanOpKey(m: KanbanOp): string {+/**+ * The ordering key (canvas-order): one `k:` space with a sub-prefix per item kind.+ *+ * The two ORDER ops are per-project SINGLETONS, so their key carries the project (ruling R4): one+ * `CanvasOrder` orders every loaded project, and an unscoped `k:colorder` let our unacked reorder in+ * project A hold off (rule 2) a peer's reorder in project B. Every other key names an item whose id+ * is already unique across projects — a card/meta by its node id (global), a column by a+ * per-project seeded or random id, a label or view by a random id — so it needs no scope.+ */+export function kanbanOpKey(m: KanbanOp, projectId: string): string {switch (m.op) {case 'kb-column': return `k:col:${m.column.id}`case 'kb-column-remove': return `k:col:${m.id}`- case 'kb-column-order': return 'k:colorder'+ case 'kb-column-order': return `k:colorder:${projectId}`case 'kb-card': return `k:card:${m.assignment.nodeId}`case 'kb-card-remove': return `k:card:${m.nodeId}`case 'kb-meta': return `k:meta:${m.meta.nodeId}`case 'kb-meta-remove': return `k:meta:${m.nodeId}`case 'kb-label': return `k:label:${m.label.id}`case 'kb-label-remove': return `k:label:${m.id}`- case 'kb-label-order': return 'k:labelorder'+ case 'kb-label-order': return `k:labelorder:${projectId}`case 'kb-view': return `k:view:${m.view.id}`case 'kb-view-remove': return `k:view:${m.id}`}@@ -135,6 +160,28 @@ export function isKanbanDeletion(m: KanbanOp): boolean {return m.op === 'kb-column-remove' || m.op === 'kb-label-remove' || m.op === 'kb-view-remove'}+// The board's lists, read TOLERANTLY. A board reaches a project through the load seam+// (`sanitizeKanban`), which admits a non-list `meta` / `labels` / `views` and non-record entries in+// them (types.ts: "tolerated as absent/malformed by every reader") — and the reducer and the diff+// are readers. A throw here is not a refused op, it is a dead board sync for that project on every+// edit. Malformed entries are invisible to both: the diff never casts them, and the one op that+// writes a list back writes it clean.+const isEntry = <K extends string>(key: K) => (x: unknown): x is Record<K, string> =>+ isObj(x) && typeof x[key] === 'string'+const columnsOf = (b: ProjectKanban): KanbanColumn[] =>+ Array.isArray(b.columns) ? b.columns.filter(isEntry('id')) as KanbanColumn[] : []+const assignmentsOf = (b: ProjectKanban): KanbanAssignment[] =>+ Array.isArray(b.assignments)+ ? (b.assignments.filter((a) => isEntry('nodeId')(a) && typeof (a as { columnId?: unknown }).columnId === 'string') as KanbanAssignment[])+ : []+const metaOf = (b: ProjectKanban): KanbanCardMeta[] => metaList(b).filter(isEntry('nodeId')) as KanbanCardMeta[]+const labelsOf = (b: ProjectKanban): KanbanLabel[] => boardLabels(b)+const viewsOf = (b: ProjectKanban): KanbanSavedView[] =>+ Array.isArray(b.views) ? b.views.filter(isEntry('id')) as KanbanSavedView[] : []+/** A card's label ids, whatever a malformed file put there. */+const cardLabelIds = (x: KanbanCardMeta): string[] =>+ Array.isArray(x.labels) ? x.labels.filter((l): l is string => typeof l === 'string') : []+function reorder<T extends { id: string }>(list: T[], ids: string[]): T[] {const byId = new Map(list.map((x) => [x.id, x]))const head = ids.map((id) => byId.get(id)).filter((x): x is T => !!x)@@ -152,15 +199,19 @@ function upsertById<T extends { id: string }>(list: T[] | undefined, item: T): T}/** Insert a placement so its column stays in rank order in the ARRAY (a build that ignores `rank`- * reads array order, see ProjectKanban.assignments). */+ * reads array order, see ProjectKanban.assignments). An INVALID rank is treated exactly as an absent+ * one, on both sides — the rule `columnOrder` reads by: the incoming card goes to the end of its+ * column, and an entry already placed with an invalid rank sits with its array predecessor, so it+ * is never the one a valid rank is compared against (`'zz' > 'a1'` as strings, but `zz` is no rank). */function placeCard(assignments: KanbanAssignment[], a: KanbanAssignment): KanbanAssignment[] {const rest = assignments.filter((x) => x.nodeId !== a.nodeId)const sameCol: number[] = []rest.forEach((x, i) => { if (x.columnId === a.columnId) sameCol.push(i) })if (!sameCol.length) return [...rest, a]- const before = a.rank === undefined- ? undefined- : sameCol.find((i) => { const r = rest[i].rank; return r !== undefined && r > (a.rank as string) })+ const rank = a.rank+ const before = isValidRank(rank)+ ? sameCol.find((i) => { const r = rest[i].rank; return isValidRank(r) && r > rank })+ : undefinedconst at = before ?? sameCol[sameCol.length - 1] + 1return [...rest.slice(0, at), a, ...rest.slice(at)]}@@ -170,37 +221,39 @@ function placeCard(assignments: KanbanAssignment[], a: KanbanAssignment): Kanbanexport function applyKanbanOp(board: ProjectKanban | undefined, m: KanbanOp, projectId: string): ProjectKanban {const b: ProjectKanban = board ?? defaultKanbanFor(projectId)switch (m.op) {- case 'kb-column': return { ...b, columns: upsertById(b.columns, m.column) }+ case 'kb-column': return { ...b, columns: upsertById(columnsOf(b), m.column) }case 'kb-column-remove':return {...b,- columns: b.columns.filter((c) => c.id !== m.id),- assignments: b.assignments.filter((a) => a.columnId !== m.id)+ columns: columnsOf(b).filter((c) => c.id !== m.id),+ assignments: assignmentsOf(b).filter((a) => a.columnId !== m.id)}- case 'kb-column-order': return { ...b, columns: reorder(b.columns, m.ids) }- case 'kb-card': return { ...b, assignments: placeCard(b.assignments, m.assignment) }- case 'kb-card-remove': return { ...b, assignments: b.assignments.filter((a) => a.nodeId !== m.nodeId) }+ case 'kb-column-order': return { ...b, columns: reorder(columnsOf(b), m.ids) }+ case 'kb-card': return { ...b, assignments: placeCard(assignmentsOf(b), m.assignment) }+ case 'kb-card-remove': return { ...b, assignments: assignmentsOf(b).filter((a) => a.nodeId !== m.nodeId) }case 'kb-meta': {- const cur = b.meta ?? []+ const cur = metaOf(b)const i = cur.findIndex((x) => x.nodeId === m.meta.nodeId)const next = i === -1 ? [...cur, m.meta] : cur.map((x, j) => (j === i ? m.meta : x))return { ...b, meta: next }}case 'kb-meta-remove': {- const next = (b.meta ?? []).filter((x) => x.nodeId !== m.nodeId)+ const next = metaOf(b).filter((x) => x.nodeId !== m.nodeId)return { ...b, meta: next }}- case 'kb-label': return { ...b, labels: upsertById(b.labels, m.label) }+ case 'kb-label': return { ...b, labels: upsertById(labelsOf(b), m.label) }case 'kb-label-remove': {- const meta = (b.meta ?? [])- .map((x) => (x.labels?.includes(m.id) ? { ...x, labels: x.labels.filter((l) => l !== m.id) } : x))+ const meta = metaOf(b)+ // Any `labels` field is rewritten from its valid ids minus the removed one, which also+ // repairs a malformed list; a card with no field is left exactly as it was.+ .map((x) => (x.labels === undefined ? x : { ...x, labels: cardLabelIds(x).filter((l) => l !== m.id) })).map((x) => (x.labels && x.labels.length === 0 ? (({ labels: _l, ...rest }) => rest)(x) : x)).filter((x) => Object.keys(x).length > 1) // an entry with only nodeId is "no metadata"- return { ...b, labels: (b.labels ?? []).filter((l) => l.id !== m.id), meta }+ return { ...b, labels: labelsOf(b).filter((l) => l.id !== m.id), meta }}- case 'kb-label-order': return { ...b, labels: reorder(b.labels ?? [], m.ids) }- case 'kb-view': return { ...b, views: upsertById(b.views, m.view) }- case 'kb-view-remove': return { ...b, views: (b.views ?? []).filter((v) => v.id !== m.id) }+ case 'kb-label-order': return { ...b, labels: reorder(labelsOf(b), m.ids) }+ case 'kb-view': return { ...b, views: upsertById(viewsOf(b), m.view) }+ case 'kb-view-remove': return { ...b, views: viewsOf(b).filter((v) => v.id !== m.id) }}}@@ -210,12 +263,34 @@ function stable(v: unknown): string {}const same = (a: unknown, b: unknown): boolean => stable(a) === stable(b)+/**+ * Does a list need its order op? When it GAINED an id, or the relative order of the ids both sides+ * share changed (ruling R3). The first half is what makes a list converge: an item op only says the+ * item exists, and a peer that applies it alone appends it — so a column inserted mid-list (the+ * UI's add-then-move, a git pull) landed last everywhere else, and two people adding a column at+ * once ended A at …,X,Y and B at …,Y,X. With the order op every replica lands on the LATER order+ * op's list. A pure removal needs none: dropping an id never reorders the rest.+ * Residual, stated: an order op lists the ids its sender knew. An id added concurrently by ANOTHER+ * client that the op does not list keeps its place after the listed ones in each replica's local+ * order — one such id converges (it is last everywhere), two from two different clients in the same+ * window can still sit in different relative orders until the next order op.+ */+function orderChanged(prevIds: string[], nextIds: string[]): boolean {+ const had = new Set(prevIds)+ if (nextIds.some((id) => !had.has(id))) return true+ const kept = new Set(nextIds)+ const common = prevIds.filter((id) => kept.has(id))+ const commonSet = new Set(common)+ return !same(common, nextIds.filter((id) => commonSet.has(id)))+}+/*** The item-level ops that turn `prev` into `next`. Never casts `github` / `pullLinks` (outside the* vocabulary). Never casts the removal of a DEAD card's placement or meta: pruning is a local, lazy* cleanup, and a peer whose node op has not arrived yet would otherwise delete a fresh card.* Batch order: upserts (columns, column order, labels, label order, views, cards, meta), then- * removals (meta, cards, views, labels, columns).+ * removals (meta, cards, views, labels, columns). Reads both boards tolerantly (see `metaOf`), so a+ * malformed list on either side is never a throw — its junk entries are simply not ops.*/export function diffKanbanOps(prev: ProjectKanban | undefined,@@ -228,40 +303,47 @@ export function diffKanbanOps(const up: KanbanOp[] = []const down: KanbanOp[] = []- const pCols = new Map(p.columns.map((c) => [c.id, c]))- for (const c of next.columns) if (!same(pCols.get(c.id), c)) up.push({ op: 'kb-column', column: c })- const nColIds = next.columns.map((c) => c.id)- const common = p.columns.map((c) => c.id).filter((id) => nColIds.includes(id))- if (!same(common, nColIds.filter((id) => common.includes(id)))) up.push({ op: 'kb-column-order', ids: nColIds })+ const pColumns = columnsOf(p)+ const nColumns = columnsOf(next)+ const pCols = new Map(pColumns.map((c) => [c.id, c]))+ for (const c of nColumns) if (!same(pCols.get(c.id), c)) up.push({ op: 'kb-column', column: c })+ const nColIds = nColumns.map((c) => c.id)+ if (orderChanged(pColumns.map((c) => c.id), nColIds)) up.push({ op: 'kb-column-order', ids: nColIds })- const pLabels = new Map((p.labels ?? []).map((l) => [l.id, l]))- for (const l of next.labels ?? []) if (!same(pLabels.get(l.id), l)) up.push({ op: 'kb-label', label: l })- const nLabelIds = (next.labels ?? []).map((l) => l.id)- const commonL = (p.labels ?? []).map((l) => l.id).filter((id) => nLabelIds.includes(id))- if (!same(commonL, nLabelIds.filter((id) => commonL.includes(id)))) up.push({ op: 'kb-label-order', ids: nLabelIds })+ const pLabelList = labelsOf(p)+ const nLabelList = labelsOf(next)+ const pLabels = new Map(pLabelList.map((l) => [l.id, l]))+ for (const l of nLabelList) if (!same(pLabels.get(l.id), l)) up.push({ op: 'kb-label', label: l })+ const nLabelIds = nLabelList.map((l) => l.id)+ if (orderChanged(pLabelList.map((l) => l.id), nLabelIds)) up.push({ op: 'kb-label-order', ids: nLabelIds })- const pViews = new Map((p.views ?? []).map((v) => [v.id, v]))- for (const v of next.views ?? []) if (!same(pViews.get(v.id), v)) up.push({ op: 'kb-view', view: v })+ const pViewList = viewsOf(p)+ const pViews = new Map(pViewList.map((v) => [v.id, v]))+ for (const v of viewsOf(next)) if (!same(pViews.get(v.id), v)) up.push({ op: 'kb-view', view: v })- const pCards = new Map(p.assignments.map((a) => [a.nodeId, a]))- for (const a of next.assignments) if (!same(pCards.get(a.nodeId), a)) up.push({ op: 'kb-card', assignment: a })- const pMeta = new Map((p.meta ?? []).map((x) => [x.nodeId, x]))- for (const x of next.meta ?? []) if (!same(pMeta.get(x.nodeId), x)) up.push({ op: 'kb-meta', meta: x })+ const pAssignments = assignmentsOf(p)+ const nAssignments = assignmentsOf(next)+ const pCards = new Map(pAssignments.map((a) => [a.nodeId, a]))+ for (const a of nAssignments) if (!same(pCards.get(a.nodeId), a)) up.push({ op: 'kb-card', assignment: a })+ const pMetaList = metaOf(p)+ const nMetaList = metaOf(next)+ const pMeta = new Map(pMetaList.map((x) => [x.nodeId, x]))+ for (const x of nMetaList) if (!same(pMeta.get(x.nodeId), x)) up.push({ op: 'kb-meta', meta: x })- const nMeta = new Set((next.meta ?? []).map((x) => x.nodeId))- for (const x of p.meta ?? []) if (!nMeta.has(x.nodeId) && liveNodeIds.has(x.nodeId)) down.push({ op: 'kb-meta-remove', nodeId: x.nodeId })- const nCards = new Set(next.assignments.map((a) => a.nodeId))+ const nMeta = new Set(nMetaList.map((x) => x.nodeId))+ for (const x of pMetaList) if (!nMeta.has(x.nodeId) && liveNodeIds.has(x.nodeId)) down.push({ op: 'kb-meta-remove', nodeId: x.nodeId })+ const nCards = new Set(nAssignments.map((a) => a.nodeId))const nColSet = new Set(nColIds)- for (const a of p.assignments) {+ for (const a of pAssignments) {// A placement that vanished because its COLUMN was removed is covered by kb-column-remove.if (!nCards.has(a.nodeId) && liveNodeIds.has(a.nodeId) && nColSet.has(a.columnId))down.push({ op: 'kb-card-remove', nodeId: a.nodeId })}- const nViews = new Set((next.views ?? []).map((v) => v.id))- for (const v of p.views ?? []) if (!nViews.has(v.id)) down.push({ op: 'kb-view-remove', id: v.id })+ const nViews = new Set(viewsOf(next).map((v) => v.id))+ for (const v of pViewList) if (!nViews.has(v.id)) down.push({ op: 'kb-view-remove', id: v.id })const nLabels = new Set(nLabelIds)- for (const l of p.labels ?? []) if (!nLabels.has(l.id)) down.push({ op: 'kb-label-remove', id: l.id })- for (const c of p.columns) if (!nColSet.has(c.id)) down.push({ op: 'kb-column-remove', id: c.id })+ for (const l of pLabelList) if (!nLabels.has(l.id)) down.push({ op: 'kb-label-remove', id: l.id })+ for (const c of pColumns) if (!nColSet.has(c.id)) down.push({ op: 'kb-column-remove', id: c.id })return [...up, ...down]}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 214b051ce..74bd5d923 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -673,6 +673,12 @@ export type CanvasMutation =| { op: 'edge-remove'; kind: CanvasEdgeKind; id: string; src?: string; seq?: number; seen?: number }| (KanbanOp & MutationStamp)+/** The node and edge half of `CanvasMutation` — all a canvas SCENE diff (`diffToMutations`) ever+ * produces. Their order keys are project-independent (node and edge ids are globally unique), so+ * the ordering API accepts them without a project id; any value that MAY be a board op must name+ * its project (see `mutationKey`). */+export type SceneMutation = Exclude<CanvasMutation, { op: `kb-${string}` }>+/** Stamp fields every canvas mutation may carry (see canvas-order): the sender tag, the reflector's* total order, and the sender's causal position. Documented on `CanvasMutation` above. */export interface MutationStamp {