@xiaobuyu/nodesign 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/package.json +1 -1
  2. package/server/api/assets/helpers.js +20 -0
  3. package/server/api/assets/notes.js +50 -0
  4. package/server/api/assets.js +6 -11
  5. package/server/api/board.js +78 -1
  6. package/server/engine/agent/events.js +1 -0
  7. package/server/engine/agent/hooks/user-prompt-submit.js +43 -0
  8. package/server/engine/agent/prompts/nodesign-prelude.md +53 -1
  9. package/server/engine/agent/session-loop.js +11 -0
  10. package/server/engine/mcp/index.js +12 -0
  11. package/server/engine/mcp/tools/arrange-on-board.js +4 -4
  12. package/server/engine/mcp/tools/create-on-board.js +9 -12
  13. package/server/engine/mcp/tools/edit-sketch.js +167 -0
  14. package/server/engine/mcp/tools/look-at-board.js +124 -0
  15. package/server/engine/mcp/tools/read-board.js +121 -34
  16. package/server/engine/mcp/tools/read-user-view.js +59 -0
  17. package/server/engine/mcp/tools/relate-on-board.js +5 -3
  18. package/server/engine/mcp/tools/sketch-on-board.js +337 -0
  19. package/server/engine/mcp/tools/write-on-board.js +130 -0
  20. package/server/engine/plugins/nodesign/skills/deskskill-engine-mini/SKILL.md +7 -0
  21. package/server/engine/plugins/nodesign/skills/docx-craft/SKILL.md +7 -0
  22. package/server/engine/plugins/nodesign/skills/rp-craft/SKILL.md +7 -0
  23. package/server/engine/plugins/nodesign/skills/site-craft/SKILL.md +7 -0
  24. package/server/engine/runs/board-tasklist.js +130 -0
  25. package/server/index.js +3 -0
  26. package/server/lib/binding-types.js +12 -0
  27. package/server/lib/board-graph-export.js +191 -0
  28. package/server/lib/board-groups.js +167 -0
  29. package/server/lib/board-hero.js +76 -0
  30. package/server/lib/board-kind-sizes.js +23 -0
  31. package/server/lib/board-relations.js +1 -1
  32. package/server/lib/chalk.js +121 -0
  33. package/server/lib/sketch-layout.js +277 -0
  34. package/server/projects/board-limits.js +12 -0
  35. package/server/projects/board-sanitize.js +252 -0
  36. package/server/projects/board-store.js +72 -205
  37. package/server/projects/ui-config.js +6 -0
  38. package/server/projects/viewpoint-store.js +78 -0
  39. package/server/ws/broker.js +3 -0
  40. package/web/dist/assets/{BrowserWindow-BYCgizHw.js → BrowserWindow-P_vIdh-G.js} +2 -2
  41. package/web/dist/assets/{DeckWindow-pNydEM4L.js → DeckWindow-BpLv5082.js} +3 -3
  42. package/web/dist/assets/{DocxWindow-PPgzh3Gq.js → DocxWindow-DSAU1-tD.js} +4 -4
  43. package/web/dist/assets/MermaidBlock-DR1GikCv.js +313 -0
  44. package/web/dist/assets/SiteWindow-92uBuRRR.js +18 -0
  45. package/web/dist/assets/abnfDiagram-VCTEODGH-uA8Esix4.js +1 -0
  46. package/web/dist/assets/arc-D_khH_xN.js +1 -0
  47. package/web/dist/assets/architectureDiagram-5GKGNRK7-DydJHqOt.js +36 -0
  48. package/web/dist/assets/blockDiagram-NRAW4CY4-B7wBbKiW.js +129 -0
  49. package/web/dist/assets/c4Diagram-UCG6FXSJ-6mrH0x7Y.js +38 -0
  50. package/web/dist/assets/channel-DGkccMO1.js +1 -0
  51. package/web/dist/assets/chunk-2Q5K7J3B-Cuikho5Q.js +1 -0
  52. package/web/dist/assets/chunk-5VM5RSS4-3-KZ5AUz.js +15 -0
  53. package/web/dist/assets/chunk-F27PBJKO-Bkwq2gGU.js +1 -0
  54. package/web/dist/assets/chunk-G27WJ6UU-BLyQzdGE.js +231 -0
  55. package/web/dist/assets/chunk-JWPE2WC7-B7HxxQds.js +1 -0
  56. package/web/dist/assets/chunk-LCL6LL3I-CtXrnUwF.js +206 -0
  57. package/web/dist/assets/chunk-POPQ4Y6H-dxddZlXt.js +1 -0
  58. package/web/dist/assets/chunk-SVP7TREG-DpkmrgHn.js +88 -0
  59. package/web/dist/assets/chunk-XXDRQBXY-BwZ7RbpQ.js +1 -0
  60. package/web/dist/assets/classDiagram-DTDB5LWJ-BGscw3OD.js +1 -0
  61. package/web/dist/assets/classDiagram-v2-JRS7N3AN-BGscw3OD.js +1 -0
  62. package/web/dist/assets/cose-bilkent-JH36ORCC-DGFOsMUt.js +1 -0
  63. package/web/dist/assets/cynefin-OW5HDTMX-DUwn3ehS.js +178 -0
  64. package/web/dist/assets/cynefinDiagram-5FMLGOSQ-DlLAOZ9x.js +62 -0
  65. package/web/dist/assets/cytoscape.esm-BjAbmLdb.js +331 -0
  66. package/web/dist/assets/dagre-3AP2YEHR-CyourLfz.js +4 -0
  67. package/web/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  68. package/web/dist/assets/diagram-S7CK7UJ4-BTMbx2np.js +30 -0
  69. package/web/dist/assets/diagram-UQ7AKVKN-UK94_1-P.js +41 -0
  70. package/web/dist/assets/diagram-VSXAHHWV-C7zS-v9v.js +3 -0
  71. package/web/dist/assets/diagram-VX7I27RA-DKJRa6CK.js +24 -0
  72. package/web/dist/assets/diagram-Z3DM3KII-kUbAfGAp.js +24 -0
  73. package/web/dist/assets/ebnfDiagram-PWID7BFC-CVW16_vb.js +1 -0
  74. package/web/dist/assets/erDiagram-SSCWMZ5O-BRQMFQ5y.js +99 -0
  75. package/web/dist/assets/flowDiagram-A5DVABFB-S34LpLtK.js +168 -0
  76. package/web/dist/assets/ganttDiagram-EL5Y4UJY-BFiqk1-G.js +292 -0
  77. package/web/dist/assets/gitGraphDiagram-WWUBYQGX-LZsrdyyv.js +106 -0
  78. package/web/dist/assets/index-GAamh1p4.js +2152 -0
  79. package/web/dist/assets/infoDiagram-RXCK75RN-0DvN6KIp.js +2 -0
  80. package/web/dist/assets/init-Gi6I4Gst.js +1 -0
  81. package/web/dist/assets/ishikawaDiagram-5VMMS53U-CaY3A-Bx.js +70 -0
  82. package/web/dist/assets/journeyDiagram-EYS64GPL-BBeiaCrj.js +139 -0
  83. package/web/dist/assets/kanban-definition-3QL26DDD-ux42DRXQ.js +89 -0
  84. package/web/dist/assets/layout-CnXiF_NB.js +1 -0
  85. package/web/dist/assets/linear-BMW0u6G6.js +1 -0
  86. package/web/dist/assets/mindmap-definition-FBJOCRG2-hUxSpdKn.js +96 -0
  87. package/web/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  88. package/web/dist/assets/pegDiagram-XKGWAZYB-aCaQPH0w.js +1 -0
  89. package/web/dist/assets/{pending-edit-apply-C0I13CbD.js → pending-edit-apply-AcdOQ9Ij.js} +6 -6
  90. package/web/dist/assets/pieDiagram-E7YTZNPT-CmOEZ8zg.js +39 -0
  91. package/web/dist/assets/quadrantDiagram-AXDQQJYC-VW6fAhsV.js +7 -0
  92. package/web/dist/assets/railroadDiagram-O6MQD6OU-CKJ7Ba5K.js +1 -0
  93. package/web/dist/assets/requirementDiagram-EFPCY7ZU-pNGkq9Vw.js +84 -0
  94. package/web/dist/assets/{rotate-cw-B1UQ8Hld.js → rotate-cw-KAfChbGV.js} +1 -1
  95. package/web/dist/assets/sankeyDiagram-P5KCCOFB-BIMmDTfZ.js +40 -0
  96. package/web/dist/assets/sequenceDiagram-WJ2MYXX4-BBW7wzKY.js +162 -0
  97. package/web/dist/assets/sizeCapture-X5ZJPWSS-DdkXmLYR.js +1 -0
  98. package/web/dist/assets/{square-dashed-mouse-pointer-8lrgqmfv.js → square-dashed-mouse-pointer-CDUlhUP7.js} +1 -1
  99. package/web/dist/assets/stateDiagram-HBIQ2CUA-W313Uz16.js +1 -0
  100. package/web/dist/assets/stateDiagram-v2-4QOOHH4V-DDhJBZzf.js +1 -0
  101. package/web/dist/assets/swimlanes-XN3QIQJK-C29TL26K.js +1 -0
  102. package/web/dist/assets/swimlanesDiagram-VK2B7HYN-BfN-Xdmu.js +8 -0
  103. package/web/dist/assets/timeline-definition-24CTP7MA-CF0JMObX.js +120 -0
  104. package/web/dist/assets/vennDiagram-4TSXK5OY-DrDFsaH3.js +34 -0
  105. package/web/dist/assets/wardleyDiagram-VM6X3IG4-CVrnRIS_.js +78 -0
  106. package/web/dist/assets/xychartDiagram-S5SC5T6Z-BvkN1zsT.js +7 -0
  107. package/web/dist/index.html +1 -1
  108. package/web/dist/assets/SiteWindow-DM0LQPCO.js +0 -18
  109. package/web/dist/assets/index-BHTBJlpY.js +0 -2125
@@ -0,0 +1,337 @@
1
+ /**
2
+ * mcp/tools/sketch-on-board.js —— sketch_on_board / finish_sketch(2026-08-23 黑板)
3
+ *
4
+ * 让 agent 把画布当黑板:一次调用落一整张示意图(节点 + 形状 + 线),而不是
5
+ * 像 create_on_board 那样一条条写。设计要点(跟用户商定的形状):
6
+ * - **没有几何容器**:一张图 = 一批带同一 #tag 的普通物件和线。read_board 按
7
+ * 连通分量 + tag 分段读,用户可以整组选/整组擦,入座算法照旧绕着走
8
+ * - **两阶段**:落下来的默认是 staging(半透明,"正在画"),finish_sketch 或
9
+ * 回合结束自动落定;落定只清 staging 位,tag 留着当逻辑分组
10
+ * - **结构不是像素**:agent 给模板 + 网格坐标(1 格 = 24px),服务端算像素与落位
11
+ * - **形状是涂鸦**:rect/ellipse/arrow… 在服务端生成带手绘抖动的路径,落成
12
+ * 普通 scribble 对象,前端零改动;自由路径(path)也收,同一白名单
13
+ * - 线的材质缺省 pencil(手绘)—— 草图上的线是人顺手拉的;要丝线/墨线自己说
14
+ *
15
+ * 护栏:每回合 3 张图;每张 ≤ 40 节点 / 30 形状 / 60 线。
16
+ */
17
+
18
+ import { tool } from '@anthropic-ai/claude-agent-sdk';
19
+ import { z } from 'zod';
20
+ import { readBoard, patchBoard, commitStaging, removeByTag, TEXT_FONTS } from '../../../projects/board-store.js';
21
+ import { estimateSizeOn } from '../../../lib/board-kind-sizes.js';
22
+ import { layerOf, normalizeCanvasId } from '../../../lib/canvas-id.js';
23
+ import { BINDING_TYPE_IDS, BINDING_MATERIALS } from '../../../lib/binding-types.js';
24
+ import { UNIT, SKETCH_FIT, SKETCH_MAX, textBox, shapePath, layoutNodes, bboxOf, findSpot, fitFor } from '../../../lib/sketch-layout.js';
25
+ import { getViewpoint } from '../../../projects/viewpoint-store.js';
26
+
27
+ const MAX_NODES = 40;
28
+ const MAX_SHAPES = 30;
29
+ const MAX_EDGES = 60;
30
+
31
+ let seq = 0;
32
+ const stamp = () => `${Date.now().toString(36)}${(seq++ % 1000).toString(36)}`;
33
+ const COLORS = ['ink', 'red', 'pencil', 'brass'];
34
+
35
+ const LOCAL_ID = z.string().regex(/^[A-Za-z0-9_-]{1,24}$/, 'local id: letters/digits/_/-');
36
+ const GRID_PT = z.object({ x: z.number().min(-400).max(400), y: z.number().min(-400).max(400) });
37
+
38
+ export function makeSketchOnBoardTool({ projectId, ctx }) {
39
+ const turnStamp = { turn: -1, count: 0 }; // 只记数(返回里不再报余额)
40
+ return tool(
41
+ 'sketch_on_board',
42
+ `Draw a whole sketch on the canvas in ONE call — notes, shapes and lines, laid out
43
+ together: a comparison table, a flow, a mind map, a detective board linking real
44
+ artifacts. The canvas is the blackboard; use it when thinking out loud with the user
45
+ would be clearer as a picture than as prose.
46
+
47
+ How it works
48
+ - You describe STRUCTURE; the server does pixels. Pick a layout template (column /
49
+ row / grid / mindmap) or place nodes yourself on a grid (1 cell = ${UNIT}px, layout
50
+ 'free', at:{x,y}). Whole sketch lands beside \`near\` (a canvas id from read_board)
51
+ or under the desktop's current content.
52
+ - nodes: plain handwriting or format:'md' (Markdown + KaTeX $…$ + \`\`\`mermaid fences).
53
+ Use md for lists/tables/formulas; mermaid only for dense formal diagrams
54
+ (sequence/state) — anything that should connect to real artifacts must be nodes+edges.
55
+ - shapes: rect / ellipse / circle / line / arrow / underline (hand-drawn look is
56
+ applied for you) or path (raw SVG M/L/Q in local px) — all in grid units.
57
+ - edges: between local node ids and/or real canvas ids. type = the relation
58
+ vocabulary (link/annotates/flow/contrast/derives-from/ref); material = ink (quiet
59
+ archive line) / pencil (hand-drawn, default here) / yarn (detective red string + pins
60
+ for hypotheses and evidence).
61
+ - Everything carries one #tag (a group): read_board {tag} reads just it, the user can
62
+ select/erase it as a whole, finish_sketch commits or erases it.
63
+ - Items land as STAGING (half-transparent = you are still drawing). Call finish_sketch
64
+ when done, or they commit automatically when the turn ends. Look at the result with
65
+ look_at_board before you call it done — agent scribbles only make sense with eyes.
66
+ - Readability rule: the user reads the board at 80–100% zoom. Body text stays md/lg
67
+ (sm only for captions ≤40 chars); one sketch ≤ ${SKETCH_FIT.w}x${SKETCH_FIT.h} world px (one screen at 80%),
68
+ hard limit ${SKETCH_MAX.w}x${SKETCH_MAX.h} — split into two tagged sketches instead of one huge one.
69
+ - To change an existing sketch use edit_sketch (move/retext/add/remove by id) — do NOT
70
+ erase and redraw the whole thing for a small change.
71
+ Per sketch: ≤${MAX_NODES} nodes, ${MAX_SHAPES} shapes, ${MAX_EDGES} edges (split big ones).`,
72
+ {
73
+ title: z.string().max(60).optional().describe('Optional heading written at the top of the sketch'),
74
+ tag: z.string().regex(/^[\w一-鿿぀-ヿ-]{1,40}$/).optional()
75
+ .describe('Group tag (letters/digits/_/-/CJK, ≤40). Default: auto "sk-<stamp>"'),
76
+ near: z.string().max(300).optional().describe('Canvas id to place the sketch beside (right side; falls back to below)'),
77
+ layout: z.enum(['auto', 'free', 'column', 'row', 'grid', 'mindmap']).optional()
78
+ .describe('auto = free if any node has at, else column (≤4) / grid'),
79
+ cols: z.number().int().min(1).max(8).optional().describe('grid columns'),
80
+ staging: z.boolean().optional().describe('Default true. false = land committed (solid) immediately'),
81
+ nodes: z.array(z.object({
82
+ id: LOCAL_ID.describe('Local id to reference from edges/shapes'),
83
+ text: z.string().min(1).max(4000),
84
+ format: z.enum(['plain', 'md']).optional(),
85
+ size: z.enum(['sm', 'md', 'lg', 'xl']).optional(),
86
+ font: z.enum(['pen', 'kai', 'sans', 'serif', 'mono']).optional(),
87
+ color: z.enum(['ink', 'red', 'pencil', 'brass']).optional(),
88
+ at: GRID_PT.optional().describe('Grid position (layout free); top-left of the node'),
89
+ w: z.number().min(3).max(22).optional().describe('Width in grid units (md nodes; default by content; ≤22 = 528px — paragraphs grow down, not wide)'),
90
+ })).max(MAX_NODES).optional(),
91
+ shapes: z.array(z.object({
92
+ id: LOCAL_ID.optional(),
93
+ kind: z.enum(['rect', 'ellipse', 'circle', 'line', 'arrow', 'underline', 'path']),
94
+ at: GRID_PT.optional().describe('Grid position (top-left for rect/ellipse; start point for line/arrow). Or use around:'),
95
+ around: LOCAL_ID.optional().describe('rect/ellipse/circle/underline: wrap this node (pad applied) instead of at/w/h'),
96
+ w: z.number().min(0).max(200).optional().describe('grid units'),
97
+ h: z.number().min(0).max(200).optional().describe('grid units'),
98
+ to: GRID_PT.optional().describe('line/arrow end point (grid)'),
99
+ toNode: LOCAL_ID.optional().describe('line/arrow: aim at this node\'s center instead of to'),
100
+ d: z.string().max(8000).optional().describe('path kind: SVG path (M/L/Q/Z only) in local px'),
101
+ color: z.enum(['ink', 'red', 'pencil', 'brass']).optional(),
102
+ width: z.number().min(1).max(12).optional(),
103
+ })).max(MAX_SHAPES).optional(),
104
+ edges: z.array(z.object({
105
+ from: z.string().min(1).max(300).describe('local node id or canvas id'),
106
+ to: z.string().min(1).max(300).describe('local node id or canvas id'),
107
+ type: z.enum(BINDING_TYPE_IDS).optional().describe('default link'),
108
+ material: z.enum(BINDING_MATERIALS).optional().describe('default pencil'),
109
+ label: z.string().max(60).optional(),
110
+ })).max(MAX_EDGES).optional(),
111
+ },
112
+ async (args) => {
113
+ if (!projectId) return { content: [{ type: 'text', text: 'No project bound.' }], isError: true };
114
+ const err = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
115
+ // 回合闸 08-23 用户拍板先不设(「别设置限制吧先」):只记数不拦
116
+ const turn = ctx?.runId ?? -1;
117
+ if (turnStamp.turn !== turn) { turnStamp.turn = turn; turnStamp.count = 0; }
118
+
119
+ const nodesIn = args.nodes || [];
120
+ const shapesIn = args.shapes || [];
121
+ const edgesIn = args.edges || [];
122
+ if (!nodesIn.length && !shapesIn.length) return err('空图不落板:至少给一个节点或形状。');
123
+ const tag = args.tag || `sk-${stamp()}`;
124
+ const staging = args.staging !== false;
125
+
126
+ // ── 节点身位 ──
127
+ const localIds = new Set();
128
+ const nodes = [];
129
+ if (args.title) {
130
+ nodes.push({ key: '__title', text: `## ${args.title}`, format: 'md', size: 'md', font: 'kai', color: 'ink', at: null, w: null });
131
+ }
132
+ for (const n of nodesIn) {
133
+ if (localIds.has(n.id)) return err(`节点 id 重复:${n.id}`);
134
+ localIds.add(n.id);
135
+ // 可读性规范:正文不低于 md(0.8 倍下 12.8 屏幕像素是底线);sm 只给 ≤40 字的题注
136
+ const size = (n.size === 'sm' && n.text.length > 40) ? 'md' : (n.size || 'md');
137
+ nodes.push({ key: n.id, text: n.text, format: n.format || 'plain', size, font: n.font || 'pen', color: n.color || 'ink', at: n.at || null, w: n.w || null });
138
+ }
139
+ for (const n of nodes) {
140
+ const box = textBox(n.text, n.size, { md: n.format === 'md', wUnits: n.w });
141
+ n.w = box.w; n.h = box.h;
142
+ }
143
+ // 标题永远在最上面:free 模式给它 (0,-2),模板模式它就是第一个
144
+ const titleNode = nodes.find(n => n.key === '__title');
145
+ let tpl = args.layout || 'auto';
146
+ if (tpl === 'auto') tpl = nodes.some(n => n.at) ? 'free' : (nodes.length - (titleNode ? 1 : 0) <= 4 ? 'column' : 'grid');
147
+ const layoutInput = titleNode && tpl === 'mindmap' ? nodes.filter(n => n !== titleNode) : nodes;
148
+ const pos = layoutNodes(layoutInput, { template: tpl, cols: args.cols });
149
+ if (titleNode && !pos.has('__title')) {
150
+ const bb = bboxOf([...pos.entries()].map(([k, p]) => ({ x: p.x, y: p.y, ...nodes.find(n => n.key === k) })));
151
+ pos.set('__title', { x: bb.x, y: bb.y - titleNode.h - 12 });
152
+ } else if (titleNode && tpl === 'free' && !titleNode.at) {
153
+ const bb = bboxOf([...pos.entries()].filter(([k]) => k !== '__title').map(([k, p]) => ({ x: p.x, y: p.y, ...nodes.find(n => n.key === k) })));
154
+ pos.set('__title', { x: bb.x, y: bb.y - titleNode.h - 12 });
155
+ }
156
+ const rectOfNode = (key) => { const n = nodes.find(x => x.key === key); const p = pos.get(key); return n && p ? { x: p.x, y: p.y, w: n.w, h: n.h } : null; };
157
+
158
+ // ── 形状(局部像素)──
159
+ const shapes = [];
160
+ for (let i = 0; i < shapesIn.length; i += 1) {
161
+ const s = shapesIn[i];
162
+ const sid = s.id || `s${i + 1}`;
163
+ if (localIds.has(sid) || shapes.some(x => x.key === sid)) return err(`形状 id「${sid}」跟节点/别的形状重名(形状缺省叫 s1,s2…,节点别用这类名)`);
164
+ const seed = `${tag}:${sid}`;
165
+ const color = COLORS.includes(s.color) ? s.color : (s.kind === 'arrow' || s.kind === 'line' ? 'ink2' : 'ink');
166
+ const width = s.width || 2;
167
+ let rect; let d;
168
+ if (s.kind === 'path') {
169
+ if (!s.d || !/^[\dMLQCZ ,.\-eE]+$/.test(s.d)) return err(`形状 ${sid}:path 只收 M/L/Q/Z 与数字`);
170
+ // 自由路径:算它的包围盒,平移到 (at 或 0,0)
171
+ const nums = s.d.match(/-?\d*\.?\d+(?:[eE][-+]?\d+)?/g)?.map(Number) || [];
172
+ const xs = nums.filter((_, k) => k % 2 === 0); const ys = nums.filter((_, k) => k % 2 === 1);
173
+ const w = Math.max(4, Math.max(...xs) - Math.min(0, Math.min(...xs))); const h = Math.max(4, Math.max(...ys) - Math.min(0, Math.min(...ys)));
174
+ rect = { x: (s.at?.x || 0) * UNIT, y: (s.at?.y || 0) * UNIT, w: w + 6, h: h + 6 };
175
+ d = s.d;
176
+ } else if (s.kind === 'line' || s.kind === 'arrow' || s.kind === 'underline') {
177
+ let a; let b;
178
+ if (s.kind === 'underline' && s.around) {
179
+ const r = rectOfNode(s.around); if (!r) return err(`形状 ${sid}:around 指向不存在的节点 ${s.around}`);
180
+ a = { x: r.x + 2, y: r.y + r.h - 2 }; b = { x: r.x + r.w - 2, y: r.y + r.h - 2 };
181
+ } else {
182
+ if (!s.at) return err(`形状 ${sid}:${s.kind} 要 at 起点`);
183
+ a = { x: s.at.x * UNIT, y: s.at.y * UNIT };
184
+ if (s.toNode) {
185
+ const r = rectOfNode(s.toNode); if (!r) return err(`形状 ${sid}:toNode 指向不存在的节点 ${s.toNode}`);
186
+ b = { x: r.x + r.w / 2, y: r.y + r.h / 2 };
187
+ } else if (s.to) b = { x: s.to.x * UNIT, y: s.to.y * UNIT };
188
+ else if (s.kind === 'underline') b = { x: a.x + (s.w || 4) * UNIT, y: a.y };
189
+ else return err(`形状 ${sid}:${s.kind} 要 to 或 toNode`);
190
+ }
191
+ const sp = shapePath(s.kind, { to: { x: b.x - a.x, y: b.y - a.y } }, seed);
192
+ rect = { x: Math.min(a.x, b.x) - 6, y: Math.min(a.y, b.y) - 6, w: sp.w, h: sp.h };
193
+ d = sp.d;
194
+ } else {
195
+ let box;
196
+ if (s.around) {
197
+ const r = rectOfNode(s.around); if (!r) return err(`形状 ${sid}:around 指向不存在的节点 ${s.around}`);
198
+ const pad = s.kind === 'rect' ? 8 : 14;
199
+ box = { x: r.x - pad, y: r.y - pad, w: r.w + pad * 2, h: r.h + pad * 2 };
200
+ if (s.kind === 'circle') { const dmax = Math.max(box.w, box.h); box = { x: box.x + (box.w - dmax) / 2, y: box.y + (box.h - dmax) / 2, w: dmax, h: dmax }; }
201
+ } else {
202
+ if (!s.at || !s.w) return err(`形状 ${sid}:${s.kind} 要 at + w(+h)或 around`);
203
+ box = { x: s.at.x * UNIT, y: s.at.y * UNIT, w: s.w * UNIT, h: (s.h || s.w) * UNIT };
204
+ }
205
+ const sp = shapePath(s.kind, { w: box.w, h: box.h }, seed);
206
+ rect = { x: box.x - 6, y: box.y - 6, w: sp.w, h: sp.h };
207
+ d = sp.d;
208
+ }
209
+ shapes.push({ key: sid, rect, d, color: COLORS.includes(color) ? color : 'ink', width });
210
+ }
211
+
212
+ // ── 先分配 id、解析线 ──
213
+ // 线要先于落位算:一条连到真实产物卡的线会改变**主角判断**(手画线 +0.5 焦点分),
214
+ // 那张卡可能因此放大 1.5 倍 —— 落位必须按"线画上去之后"的尺寸避让
215
+ // (08-23 首跑真踩:草图连了一条丝线到纸本站,纸本当场成主角,身体盖住半张图)。
216
+ const board = await readBoard(projectId);
217
+ const known = new Set(Object.keys(board.zones || {}));
218
+ const idOf = new Map(); // local → canvas id
219
+ for (const n of nodes) idOf.set(n.key, `text:a${stamp()}`);
220
+ for (const sh of shapes) idOf.set(sh.key, `scribble:a${stamp()}`);
221
+ const resolveEnd = (raw) => {
222
+ if (idOf.has(raw)) return idOf.get(raw);
223
+ const cid = normalizeCanvasId(raw);
224
+ if (cid && board.objects?.[cid]) return cid;
225
+ if (cid && board.zones?.[cid] !== undefined) return cid;
226
+ return null;
227
+ };
228
+ const bindings = {};
229
+ const badEdges = [];
230
+ for (const e of edgesIn) {
231
+ const from = resolveEnd(e.from); const to = resolveEnd(e.to);
232
+ if (!from || !to || from === to) { badEdges.push(`${e.from}→${e.to}`); continue; }
233
+ bindings[`b:a${stamp()}`] = {
234
+ type: e.type || 'link', from, to, by: 'agent', material: e.material || 'pencil', tag,
235
+ ...(staging ? { staging: true } : {}), ...(e.label ? { label: e.label } : {}),
236
+ };
237
+ }
238
+ // 落位用"线画上之后"的板来估尺寸(主角可能换人)
239
+ const after = { ...board, bindings: { ...(board.bindings || {}), ...bindings } };
240
+
241
+ // ── 宏观落位 ──
242
+ const local = bboxOf([
243
+ ...nodes.map(n => ({ ...pos.get(n.key), w: n.w, h: n.h })),
244
+ ...shapes.map(sh => sh.rect),
245
+ ]);
246
+ let zone = '';
247
+ let anchor = null;
248
+ if (args.near) {
249
+ const nid = normalizeCanvasId(args.near);
250
+ const e = nid ? board.objects?.[nid] : null;
251
+ if (!e || !Number.isFinite(e.x)) return err(`锚点 ${args.near} 还没有座位(read_board 里看不到就锚不上)。`);
252
+ zone = layerOf(nid, e, known);
253
+ anchor = { x: e.x, y: e.y, ...estimateSizeOn(after, nid, e) };
254
+ }
255
+ const obstacles = [];
256
+ let contentBottom = 0;
257
+ for (const [id, e] of Object.entries(board.objects || {})) {
258
+ if (!Number.isFinite(e?.x) || layerOf(id, e, known) !== zone) continue;
259
+ const r = { x: e.x, y: e.y, ...estimateSizeOn(after, id, e) };
260
+ obstacles.push(r); contentBottom = Math.max(contentBottom, r.y + r.h);
261
+ }
262
+ if (!zone) for (const zz of Object.values(board.zones || {})) if (Number.isFinite(zz?.y)) contentBottom = Math.max(contentBottom, zz.y + 240);
263
+ // 尺寸规范:硬上限直接拒(一张图说一件事),推荐上限以上给提醒
264
+ if (local.w > SKETCH_MAX.w || local.h > SKETCH_MAX.h) {
265
+ return err(`这张图太大了(${Math.round(local.w)}x${Math.round(local.h)} 世界像素,上限 ${SKETCH_MAX.w}x${SKETCH_MAX.h}):用户在 80%~100% 缩放下看不全。拆成两张(各自一个 tag,之间用线连),或减节点/缩 w。`);
266
+ }
267
+ // 用户视口(同一层才算;黑板是主窗口时画在他眼前)+ 按他的屏幕算"一屏"
268
+ const vp = getViewpoint(projectId);
269
+ const vpRect = (vp && (vp.layer || '') === zone && vp.camera) ? vp.camera : null;
270
+ const fit = fitFor(vp);
271
+ const spot = findSpot({ w: local.w + 24, h: local.h + 24, near: anchor, obstacles, contentBottom, viewport: vpRect });
272
+ const ox = spot.x - local.x + 12; const oy = spot.y - local.y + 12;
273
+
274
+ // ── 落盘 ──
275
+ const objects = {};
276
+ const common = { z: 1, zone, by: 'agent', tag, ...(staging ? { staging: true } : {}) };
277
+ for (const n of nodes) {
278
+ const p = pos.get(n.key);
279
+ objects[idOf.get(n.key)] = {
280
+ x: Math.round(p.x + ox), y: Math.round(p.y + oy), w: n.w, h: n.h, kind: 'text',
281
+ data: { t: n.text, ...(n.format === 'md' ? { format: 'md' } : {}), font: TEXT_FONTS.includes(n.font) ? n.font : 'pen', size: n.size, color: n.color },
282
+ ...common,
283
+ };
284
+ }
285
+ for (const sh of shapes) {
286
+ objects[idOf.get(sh.key)] = { x: Math.round(sh.rect.x + ox), y: Math.round(sh.rect.y + oy), w: Math.round(sh.rect.w), h: Math.round(sh.rect.h), kind: 'scribble', data: { d: sh.d, color: sh.color, width: sh.width }, ...common };
287
+ }
288
+ const saved = await patchBoard(projectId, { objects, bindings });
289
+ const landed = Object.keys(objects).filter(id => saved.objects?.[id]).length;
290
+ if (!landed) return err('草图被 board 拒了(内容或字段不合法)。');
291
+ turnStamp.count += 1;
292
+ const world = { x: Math.round(local.x + ox), y: Math.round(local.y + oy), w: Math.round(local.w), h: Math.round(local.h) };
293
+ try {
294
+ ctx?.emit?.({ type: 'board.updated', sessionId: null, summary: `画了一张草图 #${tag}` });
295
+ // 镜头提示(前端只在黑板模式跟随;不是劫持,是"黑板是主窗口"的约定)
296
+ ctx?.emit?.({ type: 'board.focus', sessionId: null, tag, rect: world, layer: zone });
297
+ } catch { /* fail-soft */ }
298
+ const lines = [
299
+ `Sketch #${tag} landed${staging ? ' as STAGING (半透明)' : ''}: ${Object.keys(objects).length - shapes.length} nodes, ${shapes.length} shapes, ${Object.keys(bindings).length} lines; layout ${tpl}; at world (${world.x},${world.y}) ${world.w}x${world.h}${anchor ? ` (${spot.side} of ${args.near})` : ' (below current content)'}.`,
300
+ `ids: ${[...idOf].map(([k, v]) => `${k}=${v}`).join(', ')}`,
301
+ ];
302
+ if (badEdges.length) lines.push(`Skipped ${badEdges.length} edge(s) with unknown endpoints: ${badEdges.slice(0, 6).join(', ')}`);
303
+ if (world.w > fit.w || world.h > fit.h) lines.push(`⚠ Bigger than one screen at 80% zoom${fit.screen ? ` (user's screen ${fit.screen.w}x${fit.screen.h}px → ${fit.w}x${fit.h} world px fits)` : ` (${fit.w}x${fit.h} fits)`} — the user will have to pan. Split into two tagged sketches (side by side or stacked) next time.`);
304
+ if (vp?.zoom && vp.zoom < 0.8) lines.push(`User's zoom is ${vp.zoom} (<0.8): text this size is small on their screen. Keep nodes md/lg and say in one line that there is a sketch on the board.`);
305
+ lines.push(spot.side === 'viewport' ? 'Placed inside the user\'s current viewport.' : `Placed ${spot.side === 'bottom' ? 'below current content' : spot.side + ' of the anchor'}${vpRect ? ' (no room in the user\'s viewport)' : ''}.`);
306
+ lines.push(staging
307
+ ? 'Next: look_at_board {tag} to check it, then finish_sketch {tag} (or it commits at turn end). Mention the sketch to the user in one line.'
308
+ : 'Next: look_at_board {tag} to check it.');
309
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
310
+ },
311
+ );
312
+ }
313
+
314
+ export function makeFinishSketchTool({ projectId, ctx }) {
315
+ return tool(
316
+ 'finish_sketch',
317
+ `Commit a staging sketch (make it solid) — or erase it. Pass the #tag from
318
+ sketch_on_board; omit tag to commit everything still staging. erase:true deletes the
319
+ whole group (its notes/shapes/lines; real artifact cards only lose the tag).`,
320
+ {
321
+ tag: z.string().max(40).optional(),
322
+ erase: z.boolean().optional(),
323
+ },
324
+ async ({ tag, erase }) => {
325
+ if (!projectId) return { content: [{ type: 'text', text: 'No project bound.' }], isError: true };
326
+ if (erase) {
327
+ if (!tag) return { content: [{ type: 'text', text: 'erase needs a tag.' }], isError: true };
328
+ const { removed } = await removeByTag(projectId, tag);
329
+ try { ctx?.emit?.({ type: 'board.updated', sessionId: null, summary: `擦掉了草图 #${tag}` }); } catch { /* */ }
330
+ return { content: [{ type: 'text', text: `Erased #${tag}: ${removed} item(s)/line(s) removed.` }] };
331
+ }
332
+ const { committed } = await commitStaging(projectId, { tag: tag || null });
333
+ if (committed) { try { ctx?.emit?.({ type: 'board.updated', sessionId: null, summary: `草图落定${tag ? ` #${tag}` : ''}` }); } catch { /* */ } }
334
+ return { content: [{ type: 'text', text: committed ? `Committed ${committed} item(s)${tag ? ` of #${tag}` : ''}.` : 'Nothing was staging.' }] };
335
+ },
336
+ );
337
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * mcp/tools/write-on-board.js —— write_on_board(2026-08-23 黑板三期)
3
+ *
4
+ * agent 在画布上**说话**的主通道:一段 md 板书,贴着它说的那件东西(`near`),或者
5
+ * 接在用户/自己的某条板书下面(`reply_to` = 线程)。本体是文件
6
+ * (notes/板书/<stamp>-<slug>.md,见 lib/chalk.js),board.json 只存位置和线。
7
+ *
8
+ * 落位纪律(gutter):
9
+ * - reply_to:落在被回应那条的**正下方**(同列、间距 12),自动连 flow 线(读序)
10
+ * - near:落在锚点右侧、顶对齐,撞了往下让;自动连 annotates 线(这段话关于它)
11
+ * - 都没有:用户视口里的空地 > 桌面内容底下
12
+ * 跟 create_on_board 的分工:那是"记号"(手写一句、画布原生、给人看),这是"话"
13
+ * (md、文件本体、agent 要能读回来、有线程)。黑板模式下回复的主体走这里。
14
+ */
15
+
16
+ import { tool } from '@anthropic-ai/claude-agent-sdk';
17
+ import { z } from 'zod';
18
+ import { readBoard, patchBoard } from '../../../projects/board-store.js';
19
+ import { estimateSizeOn } from '../../../lib/board-kind-sizes.js';
20
+ import { layerOf, normalizeCanvasId } from '../../../lib/canvas-id.js';
21
+ import { textBox, findSpot, SKETCH_FIT } from '../../../lib/sketch-layout.js';
22
+ import { getViewpoint } from '../../../projects/viewpoint-store.js';
23
+ import { renderChalk, chalkFileName, writeChalkFile, CHALK_DIR } from '../../../lib/chalk.js';
24
+
25
+ let seq = 0;
26
+ const stamp = () => `${Date.now().toString(36)}${(seq++ % 1000).toString(36)}`;
27
+
28
+ export function makeWriteOnBoardTool({ projectId, sharedRoot, sessionId, ctx }) {
29
+ const turnStamp = { turn: -1, count: 0 };
30
+ return tool(
31
+ 'write_on_board',
32
+ `Say it ON THE BOARD: write a short Markdown note on the canvas, beside the thing it is
33
+ about (near) or right under a note you are replying to (reply_to). This is your main way
34
+ to talk to the user when they work on the canvas — the sidebar is the log, the board is
35
+ the conversation. The note is a real file (${CHALK_DIR}/…md) you can Read/Grep/Edit later.
36
+
37
+ - near: canvas id the note is about (an artifact card, an image, another note) → lands to
38
+ its right, top-aligned, with an annotates line. Use it right after you finish something:
39
+ "what this is / why this way / what to look at".
40
+ - reply_to: path of a board note (yours or the user's) → lands right under it with a
41
+ flow line (a thread). When the user annotates one of your notes, answer with reply_to.
42
+ - neither → lands in the user's viewport (or below current content).
43
+ - text: Markdown (+KaTeX, lists, tables; ≤1500 chars, keep it one thought — long
44
+ analysis belongs in a .md the user opens). size 'md' default, 'lg' for headlines.
45
+ Keep the chat reply short — a line pointing at the board is enough.`,
46
+ {
47
+ text: z.string().min(1).max(1500),
48
+ near: z.string().max(300).optional(),
49
+ reply_to: z.string().max(300).optional().describe(`path like ${CHALK_DIR}/20260823-070809-xxx.md`),
50
+ tag: z.string().regex(/^[\w一-鿿぀-ヿ-]{1,40}$/).optional(),
51
+ size: z.enum(['md', 'lg']).optional(),
52
+ width: z.number().min(8).max(30).optional().describe('grid units (24px); default by content, max 30'),
53
+ },
54
+ async ({ text, near, reply_to: replyTo, tag, size, width }) => {
55
+ const err = (t) => ({ content: [{ type: 'text', text: t }], isError: true });
56
+ if (!projectId || !sharedRoot) return err('No project bound.');
57
+ // 回合闸 08-23 用户拍板先不设:只记数不拦
58
+ const turn = ctx?.runId ?? -1;
59
+ if (turnStamp.turn !== turn) { turnStamp.turn = turn; turnStamp.count = 0; }
60
+ const body = String(text).trim();
61
+ if (!body) return err('空话不上板。');
62
+
63
+ const board = await readBoard(projectId);
64
+ const known = new Set(Object.keys(board.zones || {}));
65
+ // 默认宽度:散文按 14 格(336px)排,短句按内容;太窄会把一句话折成三行
66
+ const em = (l) => [...l].reduce((n, c) => n + (/[\u3000-\u9fff\uff00-\uffef]/.test(c) ? 1 : 0.62), 0);
67
+ const longest = Math.max(...body.split('\n').map(em));
68
+ const wUnits = width || (longest <= 12 ? null : Math.max(12, Math.min(18, Math.ceil(longest * 16 / 24) + 1)));
69
+ const box = textBox(body, size || 'md', { md: true, wUnits });
70
+ let zone = '';
71
+ let pos = null;
72
+ let anchorId = null; let parentId = null;
73
+ const obstaclesOf = (z) => Object.entries(board.objects || {})
74
+ .filter(([id, e]) => Number.isFinite(e?.x) && layerOf(id, e, known) === z)
75
+ .map(([id, e]) => ({ id, x: e.x, y: e.y, ...estimateSizeOn(board, id, e) }));
76
+ const avoid = (p, obstacles, w, h) => {
77
+ for (let g = 0; g < 40; g += 1) {
78
+ const b = obstacles.find(o => !(p.x + w <= o.x || o.x + o.w <= p.x || p.y + h <= o.y || o.y + o.h <= p.y));
79
+ if (!b) break;
80
+ p.y = b.y + b.h + 12;
81
+ }
82
+ return p;
83
+ };
84
+ if (replyTo) {
85
+ const pid = normalizeCanvasId(replyTo);
86
+ const e = pid ? board.objects?.[pid] : null;
87
+ if (!e || !Number.isFinite(e.x)) return err(`reply_to ${replyTo} 不在板上(read_board 里看不到就接不上)。`);
88
+ parentId = pid; zone = layerOf(pid, e, known);
89
+ const ps = estimateSizeOn(board, pid, e);
90
+ pos = avoid({ x: e.x, y: e.y + ps.h + 12 }, obstaclesOf(zone), box.w, box.h);
91
+ } else if (near) {
92
+ const nid = normalizeCanvasId(near);
93
+ const e = nid ? board.objects?.[nid] : null;
94
+ if (!e || !Number.isFinite(e.x)) return err(`锚点 ${near} 还没有座位(read_board 里看不到就锚不上)。`);
95
+ anchorId = nid; zone = layerOf(nid, e, known);
96
+ const as = estimateSizeOn(board, nid, e);
97
+ pos = avoid({ x: e.x + as.w + 24, y: e.y }, obstaclesOf(zone), box.w, box.h);
98
+ } else {
99
+ const obstacles = obstaclesOf('');
100
+ let bottom = 0; for (const o of obstacles) bottom = Math.max(bottom, o.y + o.h);
101
+ for (const zz of Object.values(board.zones || {})) if (Number.isFinite(zz?.y)) bottom = Math.max(bottom, zz.y + 240);
102
+ const vp = getViewpoint(projectId);
103
+ const vpRect = (vp && !(vp.layer) && vp.camera) ? vp.camera : null;
104
+ const spot = findSpot({ w: box.w + 24, h: box.h + 24, obstacles, contentBottom: bottom, viewport: vpRect });
105
+ pos = { x: spot.x + 12, y: spot.y + 12 };
106
+ }
107
+
108
+ const fileName = chalkFileName(body);
109
+ const content = renderChalk({ body, by: 'agent', anchor: anchorId, replyTo: parentId, tag: tag || null, sessionId: sessionId || null });
110
+ const rel = await writeChalkFile(sharedRoot, fileName, content);
111
+
112
+ const objects = { [rel]: { x: Math.round(pos.x), y: Math.round(pos.y), z: 1, w: box.w, h: box.h, zone, by: 'agent', ...(tag ? { tag } : {}) } };
113
+ const bindings = {};
114
+ if (anchorId) bindings[`b:a${stamp()}`] = { type: 'annotates', from: rel, to: anchorId, by: 'agent', ...(tag ? { tag } : {}) };
115
+ if (parentId) bindings[`b:a${stamp()}`] = { type: 'flow', from: parentId, to: rel, by: 'agent', material: 'pencil', ...(tag ? { tag } : {}) };
116
+ await patchBoard(projectId, { objects, bindings });
117
+ turnStamp.count += 1;
118
+ const rect = { x: Math.round(pos.x), y: Math.round(pos.y), w: box.w, h: box.h };
119
+ try {
120
+ ctx?.emit?.({ type: 'board.updated', sessionId: null, summary: parentId ? '回了一条板书' : '写了一条板书' });
121
+ ctx?.emit?.({ type: 'board.focus', sessionId: null, tag: tag || null, rect, layer: zone, soft: true, chalk: rel });
122
+ } catch { /* */ }
123
+ const big = box.h > SKETCH_FIT.h * 0.6;
124
+ return { content: [{ type: 'text', text:
125
+ `Wrote board note ${rel} at (${rect.x},${rect.y}) ${rect.w}x${rect.h}`
126
+ + (anchorId ? ` beside ${anchorId} (annotates line)` : parentId ? ` under ${parentId} (thread)` : ' in the user\'s view')
127
+ + `.${big ? ' ⚠ It is tall — next time split or shorten.' : ''} Mention it in one line in chat; the user can annotate it to reply.` }] };
128
+ },
129
+ );
130
+ }
@@ -190,3 +190,10 @@ IP、角色、真人、某个具体产品型号、小众品牌 —— 那种情
190
190
  > 工具用法、路径、标记规约、比例硬规则在 prelude;生图 cookbook / tweaks 语法 /
191
191
  > vision-checker 派发模板由 PreToolUse hook 首次调用时注入。
192
192
  > layout 骨架参考按需 Read `<plugin>/patterns/<role>.md`。
193
+
194
+ ## 板书(交稿纪律)
195
+ 做完这一轮的东西,在它旁边写一条板书(`write_on_board near=那张卡`):这版是什么 / 为什么这么做 /
196
+ 看哪里。改了几处就写几条要点,一条说一件事。同一件东西出了新版本,画一条「改自」线
197
+ (`relate_on_board` derives-from);有参考来源画「取材」。用户在你的板书上标注了,用
198
+ `write_on_board reply_to=` 接在那条下面回。多步任务先 TodoWrite 列步骤 —— 步骤清单会自动上板、
199
+ 每步的产物自动连过去。
@@ -160,3 +160,10 @@ screenshot_canvas → 看版式
160
160
  `raw` 就是那个 .docx 本身 —— **它就是交付物**,不是"导出的副产品",这跟 deck /
161
161
  站点反过来。`pdf` 走 LibreOffice,是快速预览用的;要发出去的正式 PDF 让用户在
162
162
  Word 里导(域和字体都对)。
163
+
164
+ ## 板书(交稿纪律)
165
+ 做完这一轮的东西,在它旁边写一条板书(`write_on_board near=那张卡`):这版是什么 / 为什么这么做 /
166
+ 看哪里。改了几处就写几条要点,一条说一件事。同一件东西出了新版本,画一条「改自」线
167
+ (`relate_on_board` derives-from);有参考来源画「取材」。用户在你的板书上标注了,用
168
+ `write_on_board reply_to=` 接在那条下面回。多步任务先 TodoWrite 列步骤 —— 步骤清单会自动上板、
169
+ 每步的产物自动连过去。
@@ -226,3 +226,10 @@ gemini-3.7-flash:$0.75/M 入、$3.75/M 出(促销价,思考 token 计入
226
226
  - 页面里永远不出现任何密钥(不需要:端点靠 cookie)。
227
227
  - 页面不做定时轮询、自动重发 —— 限频闸会拦,但根上就别写。
228
228
  - 演出内容平台不审(chatai 无工具无副作用),尺度是用户和角色设定之间的事。
229
+
230
+ ## 板书(交稿纪律)
231
+ 做完这一轮的东西,在它旁边写一条板书(`write_on_board near=那张卡`):这版是什么 / 为什么这么做 /
232
+ 看哪里。改了几处就写几条要点,一条说一件事。同一件东西出了新版本,画一条「改自」线
233
+ (`relate_on_board` derives-from);有参考来源画「取材」。用户在你的板书上标注了,用
234
+ `write_on_board reply_to=` 接在那条下面回。多步任务先 TodoWrite 列步骤 —— 步骤清单会自动上板、
235
+ 每步的产物自动连过去。
@@ -321,3 +321,10 @@ Read `patterns/page-transitions.md` —— **动手写第一个转场之前先
321
321
  > 目录约定、产物根、`_drafts/`、导出交付在站点技术参考(首次写站点 html 时注入)。
322
322
  > 抠图叠层配方按需 Read 本 skill 目录下的 `patterns/cutout-collage.md`。
323
323
  > 构建道(React / vite / Tailwind / 组件库)配方 Read `patterns/build-lane.md`。
324
+
325
+ ## 板书(交稿纪律)
326
+ 做完这一轮的东西,在它旁边写一条板书(`write_on_board near=那张卡`):这版是什么 / 为什么这么做 /
327
+ 看哪里。改了几处就写几条要点,一条说一件事。同一件东西出了新版本,画一条「改自」线
328
+ (`relate_on_board` derives-from);有参考来源画「取材」。用户在你的板书上标注了,用
329
+ `write_on_board reply_to=` 接在那条下面回。多步任务先 TodoWrite 列步骤 —— 步骤清单会自动上板、
330
+ 每步的产物自动连过去。
@@ -0,0 +1,130 @@
1
+ /**
2
+ * server/engine/runs/board-tasklist.js —— 把 agent 的步骤清单镜像成板书(2026-08-23)
3
+ *
4
+ * 用户定的文化:板书是基础设施。agent 开工时用 TodoWrite 列的步骤不该只活在侧栏的计划
5
+ * 面板里 —— 它是这一轮的骨架,该写在画布上、每一步产出的东西连到对应步骤。
6
+ * 这件事**由 harness 做,不靠 agent 记得**:
7
+ * - run.todo.updated → 一条板书 `notes/板书/<stamp>-步骤.md`(一轮一条、原地更新),
8
+ * Markdown 任务列表:✓ 已做 / → 正在(加粗)/ 待做;落定不走 staging
9
+ * - run.file_changed(有"正在"的步骤时)→ 这条板书到那件产物的 annotates 线,label「第 N 步」,
10
+ * by:'auto'(不算进主角焦点分;同一轮同一件只连一次)
11
+ * - run.done/cancelled/error → 忘掉这一轮的状态(板书留着,它是过程记录)
12
+ * 挂在 project bus 上(broker.getProjectBus 建 bus 时调一次),与 live-turn 折叠器同级。
13
+ * 失败一律吞掉只 warn:镜像挂了不能影响 run。
14
+ */
15
+ import path from 'node:path';
16
+ import { readBoard, patchBoard } from '../../projects/board-store.js';
17
+ import { getSharedDir } from '../../projects/workspace.js';
18
+ import { estimateSizeOn } from '../../lib/board-kind-sizes.js';
19
+ import { layerOf, normalizeCanvasId } from '../../lib/canvas-id.js';
20
+ import { textBox, findSpot } from '../../lib/sketch-layout.js';
21
+ import { getViewpoint } from '../../projects/viewpoint-store.js';
22
+ import { renderChalk, writeChalkFile, CHALK_DIR } from '../../lib/chalk.js';
23
+
24
+ const byRun = new Map(); // runId → { projectId, rel, fileName, items, linked:Set, session }
25
+ const MAX_LINKS_PER_RUN = 24;
26
+
27
+ function renderList(items) {
28
+ const lines = ['### 这一轮的步骤', ''];
29
+ items.forEach((it, i) => {
30
+ const text = String(it.content || it.activeForm || '').trim() || `步骤 ${i + 1}`;
31
+ if (it.status === 'completed') lines.push(`- [x] ${text}`);
32
+ else if (it.status === 'in_progress') lines.push(`- [ ] **→ ${it.activeForm || text}**`);
33
+ else lines.push(`- [ ] ${text}`);
34
+ });
35
+ return lines.join('\n');
36
+ }
37
+
38
+ /** 工作区相对路径 → 画布 id(产物卡的地址):精确 > deck: > 站点/word 根 > 原样 */
39
+ export function canvasIdForRel(board, rel) {
40
+ const r = String(rel || '').replace(/\\/g, '/').replace(/^\.\//, '');
41
+ if (!r) return null;
42
+ const objs = board.objects || {};
43
+ if (objs[r]) return r;
44
+ const norm = normalizeCanvasId(r);
45
+ if (norm && objs[norm]) return norm;
46
+ for (const id of Object.keys(objs)) {
47
+ const m = /^(site|docx):(.+)$/.exec(id);
48
+ if (!m) continue;
49
+ const root = m[2];
50
+ if (r === root || r.startsWith(`${root}/`)) return id;
51
+ }
52
+ // 还没上墙:按形态猜(seated 之后线自然画出来)
53
+ return norm || r;
54
+ }
55
+
56
+ async function upsert(st, items) {
57
+ st.items = items;
58
+ const body = renderList(items);
59
+ const content = renderChalk({ body, by: 'agent', tag: st.tag, sessionId: st.session || null });
60
+ const sharedRoot = getSharedDir(st.projectId);
61
+ if (!st.fileName) st.fileName = `${new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, '').replace('T', '-')}-步骤.md`;
62
+ st.rel = await writeChalkFile(sharedRoot, st.fileName, content, { overwrite: !!st.rel });
63
+ st.fileName = st.rel.split('/').pop(); // 首写可能被加了防撞序号,之后原地覆盖同一个文件
64
+ const board = await readBoard(st.projectId);
65
+ const box = textBox(body, 'md', { md: true, wUnits: 14 });
66
+ const prev = board.objects?.[st.rel];
67
+ if (prev && Number.isFinite(prev.x)) {
68
+ // 已有座位:只改高(行数变了)不碰宽 —— 宽由前端量过真值,回写会跟它来回抖(fable P2)
69
+ await patchBoard(st.projectId, { objects: { [st.rel]: { ...prev, h: box.h } } });
70
+ return;
71
+ }
72
+ // 首次落位:用户视口的空地 > 内容底下(跟 write_on_board 同口径)
73
+ const known = new Set(Object.keys(board.zones || {}));
74
+ const obstacles = Object.entries(board.objects || {})
75
+ .filter(([id, e]) => Number.isFinite(e?.x) && layerOf(id, e, known) === '')
76
+ .map(([id, e]) => ({ x: e.x, y: e.y, ...estimateSizeOn(board, id, e) }));
77
+ let bottom = 0; for (const o of obstacles) bottom = Math.max(bottom, o.y + o.h);
78
+ for (const zz of Object.values(board.zones || {})) if (Number.isFinite(zz?.y)) bottom = Math.max(bottom, zz.y + 240);
79
+ const vp = getViewpoint(st.projectId);
80
+ const vpRect = (vp && !vp.layer && vp.camera) ? vp.camera : null;
81
+ const spot = findSpot({ w: box.w + 24, h: box.h + 24, obstacles, contentBottom: bottom, viewport: vpRect });
82
+ await patchBoard(st.projectId, { objects: { [st.rel]: { x: spot.x + 12, y: spot.y + 12, z: 1, w: box.w, h: box.h, by: 'agent', tag: st.tag } } });
83
+ }
84
+
85
+ export function attachBoardTasklist(bus, projectId) {
86
+ const handle = async (evt) => {
87
+ if (!evt?.runId) return;
88
+ if (evt.type === 'run.todo.updated') {
89
+ const items = Array.isArray(evt.todos) ? evt.todos.filter(t => t && typeof t === 'object') : [];
90
+ if (!items.length) return;
91
+ let st = byRun.get(evt.runId);
92
+ if (!st) {
93
+ st = { projectId, rel: null, fileName: null, items: [], linked: new Set(), session: evt.sessionId || null, tag: `步骤-${String(evt.runId).slice(-6)}` };
94
+ byRun.set(evt.runId, st);
95
+ }
96
+ await upsert(st, items);
97
+ bus.publish({ type: 'board.updated', sessionId: null, runId: evt.runId, summary: '步骤清单上板' });
98
+ return;
99
+ }
100
+ if (evt.type === 'run.file_changed') {
101
+ const st = byRun.get(evt.runId);
102
+ if (!st?.rel || !evt.filePath) return;
103
+ const idx = st.items.findIndex(t => t.status === 'in_progress');
104
+ if (idx < 0) return;
105
+ // 只连工作区内、非隐藏目录的真产物;每轮封顶(否则 /tmp、.nd、.claude 里的写入会灌一堆
106
+ // 指向虚空的 auto 线,MAX_BINDINGS 一到用户自己的线都不收 —— fable 08-23 P2)
107
+ const rel = String(evt.filePath).replace(/\\/g, '/');
108
+ if (rel.startsWith('/') || rel.split('/').some(seg => seg === '..' || seg.startsWith('.') || seg === 'node_modules')) return;
109
+ if (rel.startsWith(`${CHALK_DIR}/`) || rel.startsWith('notes/')) return;
110
+ if (st.linked.size >= MAX_LINKS_PER_RUN) return;
111
+ const board = await readBoard(st.projectId);
112
+ const target = canvasIdForRel(board, evt.filePath);
113
+ if (!target || target === st.rel || target.startsWith(`${CHALK_DIR}/`)) return;
114
+ if (st.linked.has(target)) return;
115
+ st.linked.add(target);
116
+ const id = `b:auto:step:${String(evt.runId).slice(-6)}:${st.linked.size}`;
117
+ await patchBoard(st.projectId, { bindings: { [id]: { type: 'annotates', from: st.rel, to: target, by: 'auto', label: `第 ${idx + 1} 步`, tag: st.tag } } });
118
+ bus.publish({ type: 'board.updated', sessionId: null, runId: evt.runId, summary: `第 ${idx + 1} 步 → ${path.basename(target)}` });
119
+ return;
120
+ }
121
+ if (evt.type === 'run.done' || evt.type === 'run.cancelled' || evt.type === 'run.error') {
122
+ byRun.delete(evt.runId);
123
+ }
124
+ };
125
+ bus.subscribe('*', (evt) => {
126
+ handle(evt).catch(err => console.warn('[board-tasklist]', err?.message || err));
127
+ });
128
+ }
129
+
130
+ export function _resetBoardTasklist() { byRun.clear(); }