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): item-level board ops on canvas:mut, with deterministic default columns

reviewf86c0debcfed
diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.ts
index e49fafa46..1f1d35ad0 100644
--- a/src/core/canvas-sync.test.ts
+++ b/src/core/canvas-sync.test.ts
@@ -6,6 +6,7 @@ import { initPlatform, resetPlatformForTests, type CorePlatform } from './platfo
import { fakePlatform } from './platform-fake'
import {
initCanvasSync,
+ publishCanvasMutation,
reflectTargets,
stampMutation,
isCanvasMutation,
@@ -257,3 +258,53 @@ describe('initCanvasSync (reflector)', () => {
expect(t.registrations).toEqual([IPC.canvasMut])
})
})
+
+// Kanban ops ride the same reflector (@shared/kanban-ops): the same ingest verdict, the same stamp —
+// 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', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: 'a\u0007b', color: 'red' }, src: 'cv-a' })
+ expect(t.sent).toEqual([])
+ })
+
+ 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 }
+ t.cast(1, 'p1', m)
+ const stamped = { ...m, seq: 1 }
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', stamped] },
+ { to: 2, channel: IPC.canvasMut, args: ['p1', stamped] }
+ ])
+ })
+
+ it('reflects the REPAIRED op: a label colour off the palette becomes default, src/seen kept', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'kb-label', label: { id: 'l1', name: ' Bug ', color: 'neon', junk: 'x' }, src: 'cv-a', seen: 0 })
+ const repaired = { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'default' }, src: 'cv-a', seen: 0, seq: 1 }
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', repaired] },
+ { to: 2, channel: IPC.canvasMut, args: ['p1', repaired] }
+ ])
+ })
+
+ it('the core\'s own publish path reflects the repaired op too', () => {
+ t.setClients([1])
+ const ok = publishCanvasMutation('p1', {
+ op: 'kb-card',
+ assignment: { nodeId: 'n1', columnId: 'c1', rank: '!!' }
+ } as CanvasMutation)
+ expect(ok).toBe(true)
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' }, seq: 1 }] }
+ ])
+ })
+
+ it('the core\'s own publish path refuses what the reflector refuses', () => {
+ t.setClients([1])
+ expect(publishCanvasMutation('p1', { op: 'kb-card-remove', nodeId: '' } as CanvasMutation)).toBe(false)
+ expect(t.sent).toEqual([])
+ })
+})
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
index 445f8e492..c8757ea82 100644
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@ -1,7 +1,8 @@
// Canvas sync — the reflector.
//
-// Every attached client (an Electron renderer, a Server-Edition browser tab) casts its LOCAL node
-// mutations on `canvas:mut`. This service stamps each one with a monotone `seq` and sends it back
+// Every attached client (an Electron renderer, a Server-Edition browser tab) casts its LOCAL canvas
+// mutations — nodes, edges and board items (@shared/kanban-ops) — on `canvas:mut`. This service
+// stamps each one with a monotone `seq` and sends it back
// out on the same channel to EVERY attached client, so all clients converge on the same node set —
// a teammate's cursor never hovers over stale geometry, and a client whose canvas still held a node
// someone else deleted can no longer write it back on the next whole-file workspace.save.
@@ -38,8 +39,12 @@
import { platform, type CorePlatform } from './platform'
import { IPC } from '../shared/ipc'
-import { isCanvasMutation, isRefId, MUTATION_MAX_BYTES } from '../shared/canvas-mutations'
-import { sanitizeInboundMutation } from '../shared/node-exec'
+import {
+ isCanvasMutation,
+ isRefId,
+ MUTATION_MAX_BYTES,
+ sanitizeCanvasMutation
+} from '../shared/canvas-mutations'
import { type ClientId } from '../shared/presence'
import type { CanvasMutation } from '../shared/types'
@@ -108,8 +113,10 @@ let seq = 0
*/
export function publishCanvasMutation(projectId: string, mutation: CanvasMutation): boolean {
if (!isRefId(projectId) || !isCanvasMutation(mutation)) return false
+ const clean = sanitizeCanvasMutation(mutation)
+ if (!clean) return false
const p = platform()
- const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
+ const stamped = stampMutation(clean, ++seq)
for (const id of p.clientIds()) p.sendTo(id, IPC.canvasMut, projectId, stamped)
return true
}
@@ -126,11 +133,19 @@ export function initCanvasSync(): void {
if (!isCanvasMutation(mutation)) return
// Stamped ONCE, here: the order every client will agree on. The sender is in the target list —
// its copy is the ack that tells it where its own edit landed (see the header).
- // The exec-enabling node fields (`shell`, `ssh.extraArgs`) are stripped HERE too, so they are
- // not even reflected to the other clients: a peer must not be able to put a program name or an
- // `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips them
- // again on apply — this is the cheap upstream half.
- const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
+ // What is stamped is the CLEAN op (`sanitizeCanvasMutation`), so every client receives the same
+ // bytes rather than each repairing the raw cast on its own:
+ // - the exec-enabling node fields (`shell`, `ssh.extraArgs`) are stripped HERE too, so they are
+ // not even reflected to the other clients: a peer must not be able to put a program name or
+ // an `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips
+ // them again on apply — this is the cheap upstream half;
+ // - a kanban op is rebuilt by `sanitizeKanbanOp` (unknown fields dropped, a label colour off the
+ // palette → `default`, an invalid rank / priority / dueAt / category dropped), keeping its
+ // `src` / `seen` so the order can still judge it. Kanban fields land in a git-shared
+ // project.json, and the authority sanitizes again before it writes (the two-seam rule).
+ const clean = sanitizeCanvasMutation(mutation)
+ if (!clean) return
+ const stamped = stampMutation(clean, ++seq)
for (const id of reflectTargets(p.clientIds(), senderId)) {
p.sendTo(id, IPC.canvasMut, projectId, stamped)
}
diff --git a/src/core/project-kanban-write.ts b/src/core/project-kanban-write.ts
index d7069f070..b33e0c271 100644
--- a/src/core/project-kanban-write.ts
+++ b/src/core/project-kanban-write.ts
@@ -217,8 +217,8 @@ export function parseCardLabelEdit(raw: unknown): CardLabelEdit | null {
* meta round-trip untouched (the same raw-object discipline as the rest of this file).
*
* A project with no board gets the default one seeded first, exactly as the desktop's first
- * "+ Label" does (`NodeLabels` edits `kanban ?? defaultKanban()`) — but only when the edit actually
- * changes something, so a no-op never writes a board nobody asked for.
+ * "+ Label" does (`NodeLabels` edits `kanban ?? defaultKanban(projectId)`) — but only when the
+ * edit actually changes something, so a no-op never writes a board nobody asked for.
*
* Returns null (nothing written) for a file of the wrong shape, an unusable `kanban` block, an
* `add` naming a label this palette does not have (the phone's copy is stale — applying a dangling
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index fc8a76da0..6171adae7 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -1943,8 +1943,8 @@ export class WorkspaceStore {
* when this project cannot have a board written at all.
*
* **Why the phone needs a verb for this at all.** The desktop's board is a LAZY default: the
- * canvas renders `kanban ?? defaultKanban()` and the `kanban` block is not written to the file
- * until the user's first board edit. So on a fresh project the columns exist only in the
+ * canvas renders `kanban ?? defaultKanban(projectId)` and the `kanban` block is not written to
+ * the file until the user's first board edit. So on a fresh project the columns exist only in the
* renderer's memory — and the phone, which knows a project solely by its `.nodeterm/project.json`,
* saw a project with no board and could not offer one. (Measured on the author's own machine:
* 1 of 13 project files had a `kanban` block.) Seeding the SAME three columns from the SAME
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 6339e0f1c..62941a865 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -3088,13 +3088,12 @@ export function Canvas() {
const globalKanbanOpen = rawGlobalKanban && omniEnabled
const kanbanOpen = globalKanbanOpen || perProjectKanbanOpen
const projectKanban = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.kanban)
- // Fresh default per project — ids must not be shared across projects; NOT persisted
- // until the first edit writes it (spec lazy-default rule).
- const seedBoard = useMemo(
- () => defaultKanban(),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [activeProjectId]
- )
+ // The active project's lazy default board — deterministic per project (the same ids on every
+ // client, different across projects); NOT persisted until the first edit writes it (spec
+ // lazy-default rule). Callbacks that know WHICH project they write read `defaultKanban(thatId)`
+ // themselves rather than this render-time value, which can name the previous project for a
+ // render during a switch.
+ const seedBoard = useMemo(() => defaultKanban(activeProjectId ?? ''), [activeProjectId])
const onKanbanChange = useCallback(
(next: ProjectKanban) => {
const id = useProjects.getState().activeProjectId
@@ -3103,7 +3102,7 @@ export function Canvas() {
if (isHostedReadOnly(sessionForProject(id).id)) return
// The board BEFORE this change — read fresh at callback entry (a stale closed-over value
// would misattribute the diff). Same lazy-default as the KanbanView render.
- const prev = useProjects.getState().getProject(id)?.kanban ?? seedBoard
+ const prev = useProjects.getState().getProject(id)?.kanban ?? defaultKanban(id)
useProjects.getState().setProjectKanban(id, next)
markDirty() // rides the existing debounced persist (commitActiveToStore + workspace.save)
// cardTitle must return '' for — and ONLY for — nodes that no longer exist (the diff reads
@@ -3120,7 +3119,7 @@ export function Canvas() {
useBoardLog.getState().append(api, id, { kind: 'event', nodeId, event })
}
},
- [markDirty, api, seedBoard]
+ [markDirty, api]
)
// The board moving a session card by itself because every pull request linked to it merged
@@ -10468,7 +10467,7 @@ export function Canvas() {
targetProjectId
)
setNodes((ns) => [...ns, node])
- const board = project?.kanban ?? seedBoard
+ const board = project?.kanban ?? defaultKanban(targetProjectId)
if (columnId) {
useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, node.id, columnId, null))
}
@@ -10496,7 +10495,7 @@ export function Canvas() {
event: { type: 'card-created', to: toName, title }
})
},
- [emptyNodePos, setNodes, markDirty, seedBoard, api]
+ [emptyNodePos, setNodes, markDirty, api]
)
// ---- GitHub issue → agent session ("Start with agent ▸") ----
@@ -10518,7 +10517,7 @@ export function Canvas() {
const { node, projectId: targetProjectId } = created
const nodeId = node.id
// The project addAgentNode charged the node to (its guarded, live read) — not a second read.
- const board = useProjects.getState().getProject(targetProjectId)?.kanban ?? seedBoard
+ const board = useProjects.getState().getProject(targetProjectId)?.kanban ?? defaultKanban(targetProjectId)
const column = issue.columnId ? board.columns.find((c) => c.id === issue.columnId) : undefined
if (column) {
useProjects.getState().setProjectKanban(targetProjectId, assignNode(board, nodeId, column.id, null))
@@ -10545,7 +10544,7 @@ export function Canvas() {
})
if (started) useBoardLog.getState().append(api, targetProjectId, started)
},
- [seedBoard, markDirty, api]
+ [markDirty, api]
)
/** The reference + first prompt of an issue start, or a notice saying why nothing started. The
@@ -14216,7 +14215,7 @@ export function Canvas() {
// Read prev fresh so the board-log diff below has the SAME base the write mutates —
// a lazy-default board is materialized here (as the first UI edit would) so the
// resolved column ids are stable across the write and the diff.
- const prev = store.getProject(pid)?.kanban ?? defaultKanban()
+ const prev = store.getProject(pid)?.kanban ?? defaultKanban(pid)
// Resolve --column by id or (case-insensitive) title; empty / "ungrouped" → null
// (unassign). `undefined` = no such column, so report what IS available.
const rawCol = (args.column ?? '').trim()
diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsx
index d60c436f5..c2fc822ad 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@ -334,7 +334,7 @@ export const GlobalKanbanView = memo(function GlobalKanbanView() {
}, [jumpTo])
const onChangeBoard = useCallback((projectId: string, next: ProjectKanban) => {
- const prev = useProjects.getState().getProject(projectId)?.kanban ?? defaultKanban()
+ const prev = useProjects.getState().getProject(projectId)?.kanban ?? defaultKanban(projectId)
useProjects.getState().setProjectKanban(projectId, next)
markWorkspaceDirty()
const cardTitle = (nodeId: string) => {
@@ -412,7 +412,7 @@ export const GlobalKanbanView = memo(function GlobalKanbanView() {
</div>
<div className="global-kanban__scroll">
{projects.map((p, idx) => {
- const board = p.kanban ?? defaultKanban()
+ const board = p.kanban ?? defaultKanban(p.id)
const sessions = p.nodes.map(n => toKanbanSessionState(n as never)).filter((s): s is KanbanSession => s !== null)
return (
<Swimlane
diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
index 34c823034..67c5ebab9 100644
--- a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
@@ -56,7 +56,7 @@ function render(accountMenuItems?: (id: string) => MenuItem[]): void {
act(() =>
root.render(
<KanbanView
- board={defaultKanban()}
+ board={defaultKanban('p')}
sessions={[session]}
onChange={noop}
onOpenNode={noop}
diff --git a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
index 122aa79e8..75f1f22ea 100644
--- a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
@@ -96,7 +96,7 @@ async function render(opts: {
await act(async () => {
root.render(
<KanbanView
- board={opts.board ?? { ...defaultKanban(), github: { columnMappings: [] } }}
+ board={opts.board ?? { ...defaultKanban('p'), github: { columnMappings: [] } }}
sessions={opts.sessions ?? [bound]}
onChange={opts.onChange ?? noop}
onOpenNode={noop}
@@ -211,7 +211,7 @@ describe('KanbanView — GitHub issue ↔ session binding', () => {
})
it('an issue the board cannot show opens on GitHub instead of doing nothing', async () => {
- await render({ board: defaultKanban() })
+ await render({ board: defaultKanban('p') })
await act(async () => {
useViewMode.getState().requestIssue({ owner: 'other', repo: 'repo', number: 7 })
})
diff --git a/src/renderer/components/kanban/NodeLabels.tsx b/src/renderer/components/kanban/NodeLabels.tsx
index ccb9f0148..86278bee4 100644
--- a/src/renderer/components/kanban/NodeLabels.tsx
+++ b/src/renderer/components/kanban/NodeLabels.tsx
@@ -21,9 +21,11 @@ import { LabelPicker } from './LabelPicker'
export function NodeLabels({ nodeId, trailing }: { nodeId: string; trailing?: ReactNode }): React.JSX.Element {
const [open, setOpen] = useState(false)
const kanban = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.kanban)
+ const activeProjectId = useProjects((s) => s.activeProjectId)
// Adding the first label seeds the default board (To Do / In Progress / Done), exactly like the
// board's own lazy default — so a node-side label add never leaves an empty column-less board.
- const board = useMemo(() => kanban ?? defaultKanban(), [kanban])
+ // The SAME board, ids included: the lazy default is deterministic per project.
+ const board = useMemo(() => kanban ?? defaultKanban(activeProjectId ?? ''), [kanban, activeProjectId])
const labels = labelsForCard(board, nodeId)
const commit = (next: ProjectKanban): void => {
diff --git a/src/renderer/lib/kanban.test.ts b/src/renderer/lib/kanban.test.ts
index eb54aed11..80fe94fc5 100644
--- a/src/renderer/lib/kanban.test.ts
+++ b/src/renderer/lib/kanban.test.ts
@@ -25,12 +25,18 @@ const board = (): ProjectKanban => ({
describe('defaultKanban', () => {
it('makes To Do / In Progress / Done with unique ids and no assignments', () => {
- const k = defaultKanban()
+ const k = defaultKanban('p')
expect(k.columns.map((c) => c.title)).toEqual(['To Do', 'In Progress', 'Done'])
expect(k.columns.map((c) => c.category)).toEqual(['unstarted', 'started', 'done'])
expect(new Set(k.columns.map((c) => c.id)).size).toBe(3)
expect(k.assignments).toEqual([])
})
+ // Every client renders this board until the first edit; two clients' concurrent first edits must
+ // land on the same three columns (spec §11 amendment 5).
+ it('is the same board, ids included, for one project — and a different one for another', () => {
+ expect(defaultKanban('p1')).toEqual(defaultKanban('p1'))
+ expect(defaultKanban('p1').columns.map((c) => c.id)).not.toEqual(defaultKanban('p2').columns.map((c) => c.id))
+ })
})
describe('columns', () => {
@@ -394,8 +400,10 @@ describe('tag → label migration', () => {
// no kanban → a default board (3 columns) is seeded so the board is never column-less
const m = migrateProjectTags(proj([{ id: 'n1', tags: ['x'] }]))
expect(m.kanban!.columns).toHaveLength(3)
+ // …and it is THIS project's lazy default, so the ids match what every other client shows
+ expect(m.kanban!.columns.map((c) => c.id)).toEqual(defaultKanban('p').columns.map((c) => c.id))
// an existing label of the same name is reused, not duplicated
- const existing = createLabel(defaultKanban(), 'x', 'red').k
+ const existing = createLabel(defaultKanban('p'), 'x', 'red').k
const m2 = migrateProjectTags(proj([{ id: 'n1', tags: ['x'] }], existing))
expect(boardLabels(m2.kanban!)).toHaveLength(1)
expect(labelsForCard(m2.kanban!, 'n1')[0]).toMatchObject({ name: 'x', color: 'red' })
diff --git a/src/renderer/lib/kanban.ts b/src/renderer/lib/kanban.ts
index acc98c91a..ce8465e89 100644
--- a/src/renderer/lib/kanban.ts
+++ b/src/renderer/lib/kanban.ts
@@ -4,7 +4,7 @@ import type {
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 { defaultKanbanFor } from '@shared/kanban-default-board'
import { autoLabelColor, boardLabels, cardMeta, createLabel, metaList, setCardLabels } from '@shared/kanban-labels'
import { prunePullLinks } from '@shared/kanban-pull-links'
@@ -23,12 +23,14 @@ const kid = (prefix: string): string => `${prefix}-${Math.random().toString(36).
/** Default board for a project whose file has no `kanban` yet. NOT written to disk
* until the first user edit (the spec's lazy-default rule) — EXCEPT when the phone asks for one
* outright (relay `projects.ensureBoard`), which seeds the same three columns from the same
- * shared definition so a board born on either surface is the same board. */
-export function defaultKanban(): ProjectKanban {
- return {
- columns: defaultBoardColumns(),
- assignments: []
- }
+ * shared definition so a board born on either surface is the same board.
+ *
+ * Its column ids are DETERMINISTIC per project (`defaultKanbanFor`): every client renders this
+ * board until someone edits it, and with boards syncing live two clients' first edits must land on
+ * the same three columns, not six. So it takes the project it is the default OF — never pass the
+ * active project's default for another project's board. */
+export function defaultKanban(projectId: string): ProjectKanban {
+ return defaultKanbanFor(projectId)
}
/** Color for the next added column — cycles the node palette. */
@@ -262,7 +264,7 @@ export function migrateProjectTags(project: Project): Project {
const nodeTags = tagged
.map((n) => ({ nodeId: n.id, tags: (n.tags as string[]).filter((t) => t !== 'claude') }))
.filter((x) => x.tags.length > 0)
- const kanban = migrateTagsToLabels(project.kanban ?? defaultKanban(), nodeTags)
+ const kanban = migrateTagsToLabels(project.kanban ?? defaultKanban(project.id), nodeTags)
const nodes: CanvasNodeState[] = project.nodes.map((n) => {
if (!Array.isArray(n.tags) || !n.tags.length) return n
const hadClaude = n.tags.includes('claude')
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index e0a4b2242..ec471c12e 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -2117,6 +2117,8 @@ export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): Can
if (!nodes.some((n) => n.id === m.id)) return nodes // already gone — keep identity, skip render
return nodes.filter((n) => n.id !== m.id)
}
+ // A kanban op addresses the project's board, not the node list — same no-op, same reference.
+ if (m.op !== 'upsert') return nodes
// A peer's node never brings the exec-enabling fields with it (@shared/node-exec): they are
// per-machine settings, and letting one into the live array is exactly how it ends up harvested
// into this machine's "trusted" workspace.json on the next save.
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index 461fedc97..f50fffcde 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -6,9 +6,10 @@ import {
createMutationGuard,
diffToMutations,
isCanvasMutation,
- MUTATION_MAX_BYTES
+ MUTATION_MAX_BYTES,
+ sanitizeCanvasMutation
} from './canvas-mutations'
-import type { BridgeLink, CanvasNodeState } from './types'
+import type { BridgeLink, CanvasMutation, CanvasNodeState } from './types'
const n = (id: string, x = 0, title = 't'): CanvasNodeState =>
({
@@ -333,3 +334,74 @@ describe('diffToMutations — scenes', () => {
])
})
})
+
+// Kanban ops ride canvas:mut too (@shared/kanban-ops). The guard is `sanitizeKanbanOp`'s verdict —
+// one set of shape rules, not a second copy here — plus the same byte cap every mutation has.
+describe('isCanvasMutation — kanban ops', () => {
+ it('accepts a well-formed kanban op of every kind', () => {
+ const ok: unknown[] = [
+ { op: 'kb-column', column: { id: 'c1', title: 'To Do', color: '#fff' } },
+ { op: 'kb-column-remove', id: 'c1' },
+ { op: 'kb-column-order', ids: ['c1', 'c2'] },
+ { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' } },
+ { op: 'kb-card-remove', nodeId: 'n1' },
+ { 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' }
+ ]
+ 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', () => {
+ 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)
+ })
+
+ 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)
+ })
+
+ it('bounds a kanban op by the same byte cap', () => {
+ const big = { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' }, pad: 'x'.repeat(MUTATION_MAX_BYTES) }
+ expect(isCanvasMutation(big)).toBe(false)
+ })
+})
+
+describe('sanitizeCanvasMutation', () => {
+ it('repairs a kanban op and keeps its stamp fields', () => {
+ const raw = { op: 'kb-label', label: { id: 'l1', name: ' Bug ', color: 'neon', junk: 1 }, src: 'cv-a', seq: 4, seen: 3 } as unknown as CanvasMutation
+ expect(sanitizeCanvasMutation(raw)).toEqual({
+ op: 'kb-label',
+ label: { id: 'l1', name: 'Bug', color: 'default' },
+ src: 'cv-a',
+ seq: 4,
+ seen: 3
+ })
+ })
+
+ it('refuses (null) a kanban op sanitizeKanbanOp refuses', () => {
+ expect(sanitizeCanvasMutation({ op: 'kb-card-remove', nodeId: '' })).toBeNull()
+ })
+
+ it('strips the exec-enabling fields off a node upsert, and passes other ops through', () => {
+ const withShell = { op: 'upsert', node: { ...n('1'), shell: '/bin/evil' } } as CanvasMutation
+ const out = sanitizeCanvasMutation(withShell) as Extract<CanvasMutation, { op: 'upsert' }>
+ expect(out.node.shell).toBeUndefined()
+ const rm: CanvasMutation = { op: 'remove', id: '1', src: 'a' }
+ expect(sanitizeCanvasMutation(rm)).toBe(rm)
+ })
+})
+
+describe('applyCanvasMutation with a kanban op', () => {
+ it('leaves the node list untouched, by reference (a kanban op addresses the board, not a node)', () => {
+ const a = [n('1')]
+ expect(applyCanvasMutation(a, { op: 'kb-card', assignment: { nodeId: '1', columnId: 'c' } })).toBe(a)
+ expect(applyCanvasMutation(a, { op: 'kb-card-remove', nodeId: '1' })).toBe(a)
+ })
+})
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index 1d785a7d4..b8426aad5 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -2,7 +2,8 @@
// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector
// (src/core). Pure: no electron, no sockets, no disk.
-import { carryLocalNodeExec, sanitizeInboundNode } from './node-exec'
+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'
@@ -66,10 +67,16 @@ export function isRefId(value: unknown): value is string {
* whole-file save would resurrect the node they deleted). The publisher therefore asks THIS function
* first and, on a refusal, casts nothing, records nothing, and keeps the node in its baseline so the
* next edit retries it. One predicate, one verdict, both ends.
+ *
+ * A kanban op (`kb-*`) is accepted iff `sanitizeKanbanOp` would keep it — its shape rules live in
+ * ONE place (@shared/kanban-ops) — and it fits the same byte cap. Accepted is not the same as
+ * clean: a repairable field (a label colour off the palette, an invalid rank) passes here and is
+ * repaired by `sanitizeCanvasMutation` before anyone applies or reflects it.
*/
export function isCanvasMutation(value: unknown): value is CanvasMutation {
if (!value || typeof value !== 'object') return false
const m = value as { op?: unknown; id?: unknown; node?: unknown; kind?: unknown; edge?: unknown }
+ if (isKanbanOp(m)) return sanitizeKanbanOp(value) !== null && withinSizeLimit(value)
if (m.op === 'remove') return isRefId(m.id)
if (m.op === 'edge-remove') return isEdgeKind(m.kind) && isRefId(m.id)
if (m.op === 'edge-upsert') {
@@ -91,6 +98,30 @@ export function isCanvasMutation(value: unknown): value is CanvasMutation {
return withinSizeLimit(m)
}
+/**
+ * The CLEAN form of an accepted mutation — what a reflector reflects and an authority applies, so
+ * every peer receives the repaired op rather than each repairing the raw one on its own:
+ * - a node `upsert` loses the exec-enabling fields (`sanitizeInboundMutation`, @shared/node-exec);
+ * - a kanban op is rebuilt by `sanitizeKanbanOp` (unknown fields dropped, colour / rank / priority /
+ * dueAt / category repaired or dropped), KEEPING the stamp fields `src` / `seq` / `seen` — the
+ * order still has to judge it;
+ * - everything else passes through unchanged.
+ * `null` = refused (a kanban op `sanitizeKanbanOp` refuses). The caller still runs
+ * `isCanvasMutation` first for the size cap; this adds no size check of its own.
+ */
+export function sanitizeCanvasMutation(m: CanvasMutation): CanvasMutation | null {
+ if (isKanbanOp(m)) {
+ const clean = sanitizeKanbanOp(m)
+ if (!clean) return null
+ const out: CanvasMutation = { ...clean }
+ if (m.src !== undefined) out.src = m.src
+ if (m.seq !== undefined) out.seq = m.seq
+ if (m.seen !== undefined) out.seen = m.seen
+ return out
+ }
+ return sanitizeInboundMutation(m)
+}
+
function withinSizeLimit(m: unknown): boolean {
try {
// The wire form is JSON on the server and a structured clone on the desktop; either way this
@@ -200,6 +231,8 @@ export function applyCanvasMutation(
// safe reading of "this list is not what that mutation is about".
if (isEdgeMutation(m)) return states
if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
+ // A kanban op addresses the board, not the node list (its `nodeId` names a CARD) — same no-op.
+ if (m.op !== 'upsert') return states
const node = sanitizeInboundNode(m.node)
const idx = states.findIndex((n) => n.id === node.id)
if (idx === -1) return [...states, node]
diff --git a/src/shared/canvas-order.test.ts b/src/shared/canvas-order.test.ts
index 546bf1035..68873f30d 100644
--- a/src/shared/canvas-order.test.ts
+++ b/src/shared/canvas-order.test.ts
@@ -85,6 +85,111 @@ describe('mutationKey', () => {
})
})
+// Kanban ops (@shared/kanban-ops) share the ONE order: a `k:` key space, highest seq wins per key,
+// and rule 4 for the three removals that mean "this board item is gone". A card / meta removal is a
+// 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 card = (nodeId: string, columnId: string, src: string, seq: number, seen?: number): CanvasMutation => ({
+ op: 'kb-card',
+ assignment: { nodeId, columnId },
+ src,
+ seq,
+ ...(seen === undefined ? {} : { seen })
+ })
+
+ 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')
+ // …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)))
+ })
+
+ it('addresses no node (mutationNodeId is null for every kanban op)', () => {
+ expect(mutationNodeId(card('n1', 'c', 'a', 1))).toBeNull()
+ expect(mutationNodeId({ op: 'kb-card-remove', nodeId: 'n1' })).toBeNull()
+ expect(mutationNodeId({ op: 'kb-meta', meta: { nodeId: 'n1' } })).toBeNull()
+ })
+
+ 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)
+ })
+
+ 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)
+ 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)
+ // a deliberate re-creation — cast knowing the removal — is applied
+ expect(o.accept({ ...stale, seq: 7, seen: 6 })).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)
+ })
+
+ 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)
+ })
+
+ 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)
+ })
+
+ it('the rule-4 deletion classification is exactly the five removals', () => {
+ const removes: CanvasMutation[] = [
+ { op: 'remove', id: 'x' },
+ { op: 'edge-remove', kind: 'bridge', id: 'x' },
+ { op: 'kb-column-remove', id: 'x' },
+ { op: 'kb-label-remove', id: 'x' },
+ { op: 'kb-view-remove', id: 'x' }
+ ]
+ const values: CanvasMutation[] = [
+ up('x', 0, 'a', 1),
+ { op: 'edge-upsert', kind: 'rope', edge: { id: 'x', source: 'a', target: 'b' } },
+ { op: 'kb-card-remove', nodeId: 'x' },
+ { op: 'kb-meta-remove', nodeId: 'x' },
+ { op: 'kb-column-order', ids: [] },
+ { op: 'kb-label-order', ids: [] },
+ card('x', 'c', 'a', 1)
+ ]
+ for (const m of removes) expect(isRemoveOp(m), m.op).toBe(true)
+ for (const m of values) expect(isRemoveOp(m), m.op).toBe(false)
+ })
+
+ 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
+ })
+
+ 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' }))
+ expect(o.hasPendingRemove('k:col:c1')).toBe(true)
+ o.onLocal(o.stamp({ op: 'kb-card-remove', nodeId: 'n1' }))
+ expect(o.hasPendingRemove('k:card:n1')).toBe(false)
+ })
+})
+
describe('createCanvasOrder', () => {
it('applies a peer mutation', () => {
const o = createCanvasOrder('me')
diff --git a/src/shared/canvas-order.ts b/src/shared/canvas-order.ts
index 81a017942..b2a8611de 100644
--- a/src/shared/canvas-order.ts
+++ b/src/shared/canvas-order.ts
@@ -69,7 +69,8 @@
//
// Pure: no React, no DOM, no timers (the pending TTL below is a lazy clock read, not a timer).
-import type { CanvasMutation } from './types'
+import { isKanbanDeletion, isKanbanOp, kanbanOpKey } from './kanban-ops'
+import type { CanvasMutation, KanbanOp } from './types'
/**
* How long an unacked local mutation keeps suppressing peers' mutations for that node.
@@ -109,28 +110,48 @@ export const REMOVED_MAX = 512
* bridge and a rope claiming the same id must fight in the total order and be resolved to one
* thing, not held as two independent entities on different clients. The apply side enforces the
* 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.
*/
export function mutationKey(m: CanvasMutation): string {
+ if (isKanbanOp(m)) return kanbanOpKey(m as KanbanOp)
if (m.op === 'edge-remove') return `e:${m.id}`
if (m.op === 'edge-upsert') return `e:${m.edge.id}`
- return `n:${m.op === 'remove' ? m.id : m.node.id}`
+ if (m.op === 'remove') return `n:${m.id}`
+ if (m.op === 'upsert') return `n:${m.node.id}`
+ // Unreachable for a typed mutation; an op this build does not know keys on its own name, so it
+ // can never be confused with (or tombstone) a real node, edge or board item.
+ return `?:${(m as { op: string }).op}`
}
-/** The node a mutation addresses. Node ops only — an edge mutation addresses no node. */
+/** The node a mutation addresses. Node ops only — an edge mutation addresses no node, and neither
+ * does a kanban op (a card's `nodeId` names the card, not a node this op creates or deletes). */
export function mutationNodeId(m: CanvasMutation): string | null {
if (m.op === 'remove') return m.id
if (m.op === 'upsert') return m.node.id
return null
}
-/** Does this mutation ADD-OR-REPLACE its subject (as opposed to dropping it)? Nodes and edges are
- * ordered by the same rules, so every rule below asks this rather than `op === 'upsert'`. */
+/** Does this mutation ADD-OR-REPLACE its subject (as opposed to dropping it)? Nodes, edges and
+ * board items are ordered by the same rules, so every rule below asks this rather than
+ * `op === 'upsert'`. Every kanban op that is not a rule-4 deletion is a value here — including
+ * `kb-card-remove` / `kb-meta-remove`, which set a card's placement / meta to "none" (an ordinary
+ * last-writer-wins value, never a tombstone), and the two order ops. */
function isUpsert(m: CanvasMutation): boolean {
+ if (isKanbanOp(m)) return !isKanbanDeletion(m as KanbanOp)
return m.op === 'upsert' || m.op === 'edge-upsert'
}
-/** Does this mutation DROP its subject? The mirror of `isUpsert`. */
+/** Does this mutation DROP its subject — a rule-4 deletion? The mirror of `isUpsert`: `remove`,
+ * `edge-remove`, and the three board removals that mean "this item is gone" (`kb-column-remove`,
+ * `kb-label-remove`, `kb-view-remove`). NOT `kb-card-remove` / `kb-meta-remove`: a card moved back
+ * to Ungrouped and then filed again is not a resurrection, and tombstoning it would drop a
+ * teammate's concurrent move as a "stale frame". */
function isRemove(m: CanvasMutation): boolean {
+ if (isKanbanOp(m)) return isKanbanDeletion(m as KanbanOp)
return m.op === 'remove' || m.op === 'edge-remove'
}
diff --git a/src/shared/kanban-default-board.test.ts b/src/shared/kanban-default-board.test.ts
index c95680897..2110c233d 100644
--- a/src/shared/kanban-default-board.test.ts
+++ b/src/shared/kanban-default-board.test.ts
@@ -4,7 +4,7 @@
// test is the pin on the desktop half — change it and the iOS twin (KanbanDefaultsTests) must move
// in the same PR.
import { describe, expect, it } from 'vitest'
-import { DEFAULT_BOARD_COLUMNS, makeColumnId } from './kanban-default-board'
+import { DEFAULT_BOARD_COLUMNS, defaultKanbanFor, makeColumnId, seededColumnId } from './kanban-default-board'
import { SYSTEM_NODE_COLORS } from './node-colors'
describe('DEFAULT_BOARD_COLUMNS', () => {
@@ -38,3 +38,25 @@ describe('makeColumnId', () => {
expect(new Set(ids).size).toBeGreaterThan(45)
})
})
+
+// The LAZY default board (a project whose file has no `kanban` yet) is what every client renders
+// until the first edit. Its column ids must be the same on every client for one project, or two
+// people's first-ever board edits land on six columns instead of three (spec §11 amendment 5).
+describe('deterministic default board', () => {
+ it('same project → same ids on every client; different projects → different ids', () => {
+ expect(defaultKanbanFor('project-1')).toEqual(defaultKanbanFor('project-1'))
+ expect(defaultKanbanFor('project-1').columns[0].id).not.toBe(defaultKanbanFor('project-2').columns[0].id)
+ })
+ it('keeps the desktop id shape kcol-<8 base36>', () => {
+ for (let i = 0; i < 3; i++) expect(seededColumnId('project-1', i)).toMatch(/^kcol-[0-9a-z]{8}$/)
+ })
+ it('titles, order, colours and categories are the shared defaults', () => {
+ const b = defaultKanbanFor('p')
+ expect(b.columns.map((c) => [c.title, c.color, c.category])).toEqual(
+ DEFAULT_BOARD_COLUMNS.map((c) => [c.title, c.color, c.category]))
+ expect(b.assignments).toEqual([])
+ })
+ it('the three columns of one board have three distinct ids', () => {
+ expect(new Set(defaultKanbanFor('project-1').columns.map((c) => c.id)).size).toBe(3)
+ })
+})
diff --git a/src/shared/kanban-default-board.ts b/src/shared/kanban-default-board.ts
index 3eb30f8cd..3e3f217fd 100644
--- a/src/shared/kanban-default-board.ts
+++ b/src/shared/kanban-default-board.ts
@@ -2,21 +2,30 @@
* The starting board every project gets when it first grows one: To Do / In Progress / Done.
*
* It lives in `shared` because THREE writers must mint the same board and none of them may own the
- * definition: the renderer's `defaultKanban()` (the desktop's lazy default, seeded on the user's
- * first board edit), the core's `ensureProjectBoard` (the host side of the relay
+ * definition: the renderer's `defaultKanban(projectId)` (the desktop's lazy default, seeded on the
+ * user's first board edit), the core's `ensureProjectBoard` (the host side of the relay
* `projects.ensureBoard` verb — the phone creating a board on a project that has never had one),
* and, across the repo boundary, nodeterm-ios `KanbanDefaults` (which cannot import this file and
* therefore copies it verbatim under a pinning test).
*
* Only the TITLES, their ORDER, their COLORS and their lifecycle CATEGORY are shared (the category
* is additive: a surface whose copy lacks it seeds uncategorized columns, which every reader
- * tolerates — see @shared/kanban-category). Column ids are minted per board and are
- * deliberately random: a board is created exactly once, by whichever surface got there first, and
- * every later reader addresses columns by the ids that board carries — so two surfaces agreeing on
- * an id would buy nothing and a fixed id would collide across projects.
+ * tolerates — see @shared/kanban-category).
+ *
+ * Column ids come in two kinds, and which one a board gets depends on how it was born:
+ * - the LAZY default (the renderer's `defaultKanban(projectId)` → `defaultKanbanFor`): what every
+ * client renders for a project whose file has no `kanban` yet. It is not written until the first
+ * edit, and with the board syncing live between clients, TWO people can make that first edit at
+ * once. Random ids per client turned that into six columns; so the lazy default seeds ids that
+ * are a pure function of the project id and the column's index (`seededColumnId`) — the same on
+ * every client for one project, different across projects.
+ * - an EXPLICITLY created board (the core's `ensureProjectBoard`, the phone's first board): minted
+ * once, by one writer, and then read by id — so its ids stay random (`makeColumnId`).
+ * Both kinds have the same `kcol-<8 base36>` shape, so every reader of existing files is unaffected
+ * and existing boards keep the ids they carry.
*/
import { SYSTEM_NODE_COLORS } from './node-colors'
-import type { KanbanColumn, KanbanColumnCategory } from './types'
+import type { KanbanColumn, KanbanColumnCategory, ProjectKanban } from './types'
export interface DefaultBoardColumn {
title: string
@@ -53,3 +62,29 @@ export function defaultBoardColumns(mintId: () => string = makeColumnId): Kanban
export function makeColumnId(): string {
return `kcol-${Math.random().toString(36).slice(2, 10)}`
}
+
+/** FNV-1a 32-bit — a stable, dependency-free hash (no crypto: this is identity, not security). */
+function fnv1a32(s: string): number {
+ let h = 0x811c9dc5
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i)
+ h = Math.imul(h, 0x01000193) >>> 0
+ }
+ return h >>> 0
+}
+
+/**
+ * The id of the i-th default column of `projectId`'s lazy board: the same on every client that
+ * renders that project, so two people's first-ever board edits land on the SAME three columns
+ * (random ids per client made that six). Different across projects. Same `kcol-` + 8 base36 shape
+ * `makeColumnId` has always produced, so every reader of existing files is unaffected.
+ */
+export function seededColumnId(projectId: string, index: number): string {
+ return `kcol-${fnv1a32(`${projectId}:${index}`).toString(36).padStart(8, '0').slice(-8)}`
+}
+
+/** The lazy default board of one project (the renderer's `kanban ?? defaultKanban(id)`). */
+export function defaultKanbanFor(projectId: string): ProjectKanban {
+ let i = 0
+ return { columns: defaultBoardColumns(() => seededColumnId(projectId, i++)), assignments: [] }
+}
diff --git a/src/shared/kanban-ops.test.ts b/src/shared/kanban-ops.test.ts
new file mode 100644
index 000000000..bcd1393b7
--- /dev/null
+++ b/src/shared/kanban-ops.test.ts
@@ -0,0 +1,125 @@
+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'
+
+const P = 'project-1'
+const base = (): ProjectKanban => defaultKanbanFor(P)
+const [todo, doing] = base().columns.map((c) => c.id)
+const live = (...ids: string[]) => new Set(ids)
+
+describe('sanitizeKanbanOp', () => {
+ it('refuses a bad id and an unknown op', () => {
+ expect(sanitizeKanbanOp({ op: 'kb-card-remove', nodeId: '' })).toBeNull()
+ expect(sanitizeKanbanOp({ op: 'kb-nope' })).toBeNull()
+ })
+ it('repairs label colour, drops bad priority / dueAt / category, keeps good fields', () => {
+ expect(sanitizeKanbanOp({ op: 'kb-label', label: { id: 'l1', name: ' Bug ', color: 'neon' } }))
+ .toEqual({ op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'default' } })
+ expect(sanitizeKanbanOp({ op: 'kb-meta', meta: { nodeId: 'n1', priority: 'extreme', dueAt: Number.NaN } }))
+ .toEqual({ op: 'kb-meta', meta: { nodeId: 'n1' } })
+ 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()
+ })
+ it('drops an invalid rank rather than the whole op', () => {
+ expect(sanitizeKanbanOp({ op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1', rank: '!!' } }))
+ .toEqual({ op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c1' } })
+ })
+})
+
+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')
+ })
+ 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)
+ expect(isKanbanDeletion({ op: 'kb-card-remove', nodeId: 'n' })).toBe(false)
+ expect(isKanbanDeletion({ op: 'kb-meta-remove', nodeId: 'n' })).toBe(false)
+ })
+})
+
+describe('applyKanbanOp', () => {
+ it('seeds the deterministic default board when the project has none', () => {
+ const b = applyKanbanOp(undefined, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ expect(b.columns.map((c) => c.id)).toEqual(base().columns.map((c) => c.id))
+ expect(b.assignments).toEqual([{ nodeId: 'n1', columnId: todo }])
+ })
+ it('a card op replaces the card and keeps its column in rank order', () => {
+ let b = base()
+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo, rank: 'm' } }, P)
+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'n2', columnId: todo, rank: 'c' } }, P)
+ b = applyKanbanOp(b, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: doing, rank: 'm' } }, P)
+ 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'])
+ })
+ 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)
+ expect(b.columns.some((c) => c.id === todo)).toBe(false)
+ expect(b.assignments).toEqual([])
+ })
+ it('a label removal strips it from every card', () => {
+ let b = applyKanbanOp(base(), { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'red' } }, P)
+ b = applyKanbanOp(b, { op: 'kb-meta', meta: { nodeId: 'n1', labels: ['l1'] } }, P)
+ b = applyKanbanOp(b, { op: 'kb-label-remove', id: 'l1' }, P)
+ expect(b.labels).toEqual([])
+ expect(b.meta ?? []).toEqual([])
+ })
+ it('column order: listed ids first, unlisted kept after, unknown ignored', () => {
+ const ids = base().columns.map((c) => c.id)
+ const b = applyKanbanOp(base(), { op: 'kb-column-order', ids: [ids[2], 'ghost', ids[0]] }, P)
+ expect(b.columns.map((c) => c.id)).toEqual([ids[2], ids[0], ids[1]])
+ })
+})
+
+describe('diffKanbanOps', () => {
+ it('one move of one card is one kb-card op', () => {
+ const prev = applyKanbanOp(base(), { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ const next = applyKanbanOp(prev, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: doing } }, P)
+ expect(diffKanbanOps(prev, next, P, live('n1'))).toEqual([
+ { op: 'kb-card', assignment: { nodeId: 'n1', columnId: doing } }
+ ])
+ })
+ it('an absent prev board diffs against the deterministic default (no column ops for the seed)', () => {
+ const next = applyKanbanOp(undefined, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ expect(diffKanbanOps(undefined, next, P, live('n1'))).toEqual([
+ { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }
+ ])
+ })
+ it('prune removals of dead cards are never cast', () => {
+ const prev = applyKanbanOp(base(), { op: 'kb-card', assignment: { nodeId: 'dead', columnId: todo } }, P)
+ expect(diffKanbanOps(prev, base(), P, live())).toEqual([])
+ })
+ it('prune removals of a dead card\'s meta are never cast; a live card\'s cleared meta is', () => {
+ const prev = applyKanbanOp(base(), { op: 'kb-meta', meta: { nodeId: 'dead', priority: 'high' } }, P)
+ expect(diffKanbanOps(prev, base(), P, live())).toEqual([])
+ expect(diffKanbanOps(prev, base(), P, live('dead'))).toEqual([{ op: 'kb-meta-remove', nodeId: 'dead' }])
+ })
+ it('a live card moved to Ungrouped is a kb-card-remove', () => {
+ const prev = applyKanbanOp(base(), { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ expect(diffKanbanOps(prev, base(), P, live('n1'))).toEqual([{ op: 'kb-card-remove', nodeId: 'n1' }])
+ })
+ it('batch order: upserts before removals; a removed column covers its own cards', () => {
+ const prev = applyKanbanOp(base(), { op: 'kb-card', assignment: { nodeId: 'n1', columnId: todo } }, P)
+ 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'])
+ })
+ it('never diffs github or pullLinks', () => {
+ const prev = base()
+ const next: ProjectKanban = {
+ ...prev,
+ github: { repository: 'a/b', columnMappings: [{ columnId: todo, label: 'status:todo' }] },
+ pullLinks: { unlinked: [{ nodeId: 'n1', pull: 7 }], noAutoMove: ['n1'] }
+ }
+ expect(diffKanbanOps(prev, next, P, live('n1'))).toEqual([])
+ })
+})
diff --git a/src/shared/kanban-ops.ts b/src/shared/kanban-ops.ts
new file mode 100644
index 000000000..bcd2bdef9
--- /dev/null
+++ b/src/shared/kanban-ops.ts
@@ -0,0 +1,267 @@
+// Item-level kanban mutations — the board half of the canvas:mut vocabulary. Pure: no DOM, no fs.
+// Every surface that applies a board change from someone else (a peer client, the Server Edition
+// canvas authority) goes through `applyKanbanOp`; every surface that publishes one builds it with
+// `diffKanbanOps`. One implementation of each, so a board converges to the same bytes everywhere.
+// See docs/team-presence.md for the ordering rules (seq, rule 4) these ops share with nodes/edges.
+
+import { isRefId } from './canvas-mutations'
+import { defaultKanbanFor } from './kanban-default-board'
+import { KANBAN_LABEL_COLORS } from './kanban-labels'
+import { isValidRank } from './kanban-rank'
+import { sanitizeViews } from './kanban-views'
+import type {
+ KanbanAssignment, KanbanCardMeta, KanbanColumn, KanbanColumnCategory, KanbanLabel,
+ KanbanLabelColor, KanbanOp, KanbanPriority, KanbanSavedView, ProjectKanban
+} from './types'
+
+const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
+const TITLE_MAX = 200
+const COLOR_MAX = 64
+const NAME_MAX = 100
+const LABEL_NAME_MAX = 60 // same bound as core/project-kanban-write.ts LABEL_NAME_MAX
+const LIST_MAX = 500
+const PRIORITIES: readonly KanbanPriority[] = ['low', 'medium', 'high', 'urgent']
+const CATEGORIES: readonly KanbanColumnCategory[] = ['unstarted', 'started', 'done', 'closed']
+/** 1970 … 3000: a real due date, not a sentinel. */
+const DUE_MIN = 0
+const DUE_MAX = 32_503_680_000_000
+
+const 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
+const idList = (x: unknown): string[] | null => {
+ if (!Array.isArray(x) || x.length > LIST_MAX || !x.every(isRefId)) return null
+ return [...new Set(x as string[])]
+}
+
+function column(x: unknown): KanbanColumn | null {
+ if (!isObj(x) || !isRefId(x.id)) return null
+ const title = text(x.title, TITLE_MAX)
+ const color = text(x.color, COLOR_MAX)
+ if (title === null || color === null) return null
+ const out: KanbanColumn = { id: x.id, title, color }
+ if (CATEGORIES.includes(x.category as KanbanColumnCategory)) out.category = x.category as KanbanColumnCategory
+ return out
+}
+
+function assignment(x: unknown): KanbanAssignment | null {
+ if (!isObj(x) || !isRefId(x.nodeId) || !isRefId(x.columnId)) return null
+ const out: KanbanAssignment = { nodeId: x.nodeId, columnId: x.columnId }
+ if (isValidRank(x.rank)) out.rank = x.rank
+ return out
+}
+
+function meta(x: unknown): KanbanCardMeta | null {
+ if (!isObj(x) || !isRefId(x.nodeId)) return null
+ const out: KanbanCardMeta = { nodeId: x.nodeId }
+ 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) }))
+ .filter((p): p is { name: string; color: string } => !!p.name && p.color !== null)
+ .slice(0, 50)
+ if (a.length) out.assignees = a
+ }
+ if (typeof x.dueAt === 'number' && Number.isFinite(x.dueAt) && x.dueAt >= DUE_MIN && x.dueAt <= DUE_MAX)
+ out.dueAt = x.dueAt
+ if (PRIORITIES.includes(x.priority as KanbanPriority)) out.priority = x.priority as KanbanPriority
+ const labels = x.labels === undefined ? null : idList(x.labels)
+ if (labels && labels.length) out.labels = labels
+ return out
+}
+
+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
+ const color: KanbanLabelColor = KANBAN_LABEL_COLORS.includes(x.color as KanbanLabelColor)
+ ? (x.color as KanbanLabelColor)
+ : 'default'
+ return { id: x.id, name, color }
+}
+
+function view(x: unknown): KanbanSavedView | null {
+ const v = sanitizeViews([x])
+ return v && v.length === 1 ? v[0] : null
+}
+
+/** Is this an op name this module owns? (Shape is `sanitizeKanbanOp`'s job.) */
+export function isKanbanOp(m: { op?: unknown }): boolean {
+ return typeof m.op === 'string' && m.op.startsWith('kb-')
+}
+
+/** 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. */
+export function sanitizeKanbanOp(m: unknown): KanbanOp | null {
+ if (!isObj(m)) return null
+ switch (m.op) {
+ case 'kb-column': { const c = column(m.column); return c && { op: 'kb-column', column: c } }
+ case 'kb-column-remove': return isRefId(m.id) ? { op: 'kb-column-remove', id: m.id } : null
+ case 'kb-column-order': { const ids = idList(m.ids); return ids && { op: 'kb-column-order', ids } }
+ case 'kb-card': { const a = assignment(m.assignment); return a && { op: 'kb-card', assignment: a } }
+ case 'kb-card-remove': return isRefId(m.nodeId) ? { op: 'kb-card-remove', nodeId: m.nodeId } : null
+ case 'kb-meta': { const x = meta(m.meta); return x && { op: 'kb-meta', meta: x } }
+ case 'kb-meta-remove': return isRefId(m.nodeId) ? { op: 'kb-meta-remove', nodeId: m.nodeId } : null
+ case 'kb-label': { const l = label(m.label); return l && { op: 'kb-label', label: l } }
+ case 'kb-label-remove': return isRefId(m.id) ? { op: 'kb-label-remove', id: m.id } : null
+ case 'kb-label-order': { const ids = idList(m.ids); return ids && { op: 'kb-label-order', ids } }
+ case 'kb-view': { const v = view(m.view); return v && { op: 'kb-view', view: v } }
+ case 'kb-view-remove': return isRefId(m.id) ? { op: 'kb-view-remove', id: m.id } : null
+ default: return null
+ }
+}
+
+/** The ordering key (canvas-order): one `k:` space with a sub-prefix per item kind. */
+export function kanbanOpKey(m: KanbanOp): 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-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-view': return `k:view:${m.view.id}`
+ case 'kb-view-remove': return `k:view:${m.id}`
+ }
+}
+
+/** Rule-4 deletions: the thing is gone. A card/meta removal is a VALUE ("no placement", "no meta")
+ * and orders like any other write. */
+export function isKanbanDeletion(m: KanbanOp): boolean {
+ return m.op === 'kb-column-remove' || m.op === 'kb-label-remove' || m.op === 'kb-view-remove'
+}
+
+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)
+ const listed = new Set(head.map((x) => x.id))
+ return [...head, ...list.filter((x) => !listed.has(x.id))]
+}
+
+function upsertById<T extends { id: string }>(list: T[] | undefined, item: T): T[] {
+ const cur = list ?? []
+ const i = cur.findIndex((x) => x.id === item.id)
+ if (i === -1) return [...cur, item]
+ const next = cur.slice()
+ next[i] = item
+ return next
+}
+
+/** Insert a placement so its column stays in rank order in the ARRAY (a build that ignores `rank`
+ * reads array order, see ProjectKanban.assignments). */
+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 at = before ?? sameCol[sameCol.length - 1] + 1
+ return [...rest.slice(0, at), a, ...rest.slice(at)]
+}
+
+/** Apply one (already sanitized) op. Pure; returns a new board. An absent board is the project's
+ * deterministic lazy default — exactly what every client was showing. */
+export 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-remove':
+ return {
+ ...b,
+ columns: b.columns.filter((c) => c.id !== m.id),
+ assignments: b.assignments.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-meta': {
+ const cur = b.meta ?? []
+ 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)
+ return { ...b, meta: next }
+ }
+ case 'kb-label': return { ...b, labels: upsertById(b.labels, 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))
+ .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 }
+ }
+ 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) }
+ }
+}
+
+function stable(v: unknown): string {
+ return JSON.stringify(v, (_k, val) =>
+ isObj(val) ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, val[k]])) : val)
+}
+const same = (a: unknown, b: unknown): boolean => stable(a) === stable(b)
+
+/**
+ * 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).
+ */
+export function diffKanbanOps(
+ prev: ProjectKanban | undefined,
+ next: ProjectKanban | undefined,
+ projectId: string,
+ liveNodeIds: ReadonlySet<string>
+): KanbanOp[] {
+ if (!next) return []
+ const p = prev ?? defaultKanbanFor(projectId)
+ 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 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 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 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 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 nColSet = new Set(nColIds)
+ for (const a of p.assignments) {
+ // 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 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 })
+
+ return [...up, ...down]
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 0a3df5f52..214b051ce 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -639,7 +639,9 @@ export interface CanvasState {
}
/**
- * A minimal change to a canvas node list: replace-or-append a node by id, or drop one by id.
+ * A minimal change to a canvas: replace-or-append a node by id, or drop one by id — and, on the team
+ * canvas-sync path, the same for one persisted edge (`edge-*`) or one board item (`kb-*`, see
+ * `KanbanOp` below and @shared/kanban-ops).
* Used for the client's optimistic edits and host-side diffing (see `applyMutation`/`diffToMutations`).
*
* `src` and `seq` exist ONLY on the team canvas-sync path (`canvas:mut`), and they are what makes
@@ -669,6 +671,37 @@ export type CanvasMutation =
seen?: number
}
| { op: 'edge-remove'; kind: CanvasEdgeKind; id: string; src?: string; seq?: number; seen?: number }
+ | (KanbanOp & MutationStamp)
+
+/** 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 {
+ src?: string
+ seq?: number
+ seen?: number
+}
+
+/**
+ * The board half of the `canvas:mut` vocabulary (@shared/kanban-ops): one op per board ITEM, so two
+ * people editing one board converge item by item instead of last-writer-wins on the whole `kanban`
+ * block. Keys live in one `k:` space (`kanbanOpKey`); only a column / label / view REMOVAL is a
+ * rule-4 deletion — `kb-card-remove` and `kb-meta-remove` set a card's placement / metadata to
+ * "none", an ordinary last-writer-wins value (`isKanbanDeletion`). `github` and `pullLinks` are
+ * outside the vocabulary and never cast.
+ */
+export type KanbanOp =
+ | { op: 'kb-column'; column: KanbanColumn }
+ | { op: 'kb-column-remove'; id: string }
+ | { op: 'kb-column-order'; ids: string[] }
+ | { op: 'kb-card'; assignment: KanbanAssignment }
+ | { op: 'kb-card-remove'; nodeId: string }
+ | { op: 'kb-meta'; meta: KanbanCardMeta }
+ | { op: 'kb-meta-remove'; nodeId: string }
+ | { op: 'kb-label'; label: KanbanLabel }
+ | { op: 'kb-label-remove'; id: string }
+ | { op: 'kb-label-order'; ids: string[] }
+ | { op: 'kb-view'; view: KanbanSavedView }
+ | { op: 'kb-view-remove'; id: string }
/**
* Which persisted edge list a mutation addresses — `bridges` (context links, which an agent can