@muwi/herdr-app 0.0.0-stage → 0.7.0

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.
package/src/layout.js ADDED
@@ -0,0 +1,171 @@
1
+ // 그래프 배치. 카드와 연결선이 겹치지 않는 좌표를 계산한다.
2
+ // 계산은 ELK(Eclipse Layout Kernel, elkjs)의 layered 알고리즘이 한다. 왼쪽에서 오른쪽으로 흐르고 선은 직각으로 꺾인다.
3
+ // 세로로 긴 칸(터미널 오른쪽에 둔 그래프)에서는 위에서 아래로 흐르게 할 수 있다 (down).
4
+ // 칸 크기를 알면 두 방향을 다 ELK로 계산해 보고, 칸에 훨씬 크게 들어가는 방향을 쓴다 (layoutFor). 배치 자체는 ELK가 계산한 그대로다.
5
+ // 계획이 바뀌면 전체를 다시 계산한다. 그리는 쪽(Herdr 앱 칸)은 받은 좌표를 그대로 그린다.
6
+ import { createRequire } from 'node:module';
7
+
8
+ const require = createRequire(import.meta.url);
9
+
10
+
11
+
12
+
13
+
14
+                   
15
+ /** 그래프를 그릴 칸의 크기 (그래프 칸이 알려 준다) */
16
+
17
+
18
+ /** 흐름의 방향: 왼쪽→오른쪽(right) 또는 위→아래(down) */
19
+
20
+
21
+ /** 카드 크기 (px, 확대 1 기준). 그리는 쪽과 같아야 한다 */
22
+ export const SIZE = { cardW: 224, cardH: 62 };
23
+
24
+ const OPTIONS = {
25
+ 'elk.algorithm': 'layered',
26
+ 'elk.direction': 'RIGHT',
27
+ 'elk.edgeRouting': 'ORTHOGONAL',
28
+ // 계획에 적은 순서를 따른다. 같은 계획이면 같은 그림이 나온다
29
+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
30
+ 'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
31
+ 'elk.layered.nodePlacement.bk.fixedAlignment': 'NONE',
32
+ 'elk.layered.nodePlacement.favorStraightEdges': 'true',
33
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '56',
34
+ 'elk.spacing.nodeNode': '22',
35
+ 'elk.spacing.edgeNode': '14',
36
+ 'elk.spacing.edgeEdge': '10',
37
+ 'elk.layered.spacing.edgeNodeBetweenLayers': '16',
38
+ 'elk.layered.spacing.edgeEdgeBetweenLayers': '10',
39
+ 'elk.padding': '[top=28,left=28,bottom=28,right=28]',
40
+ };
41
+
42
+ const r1 = (n ) => Math.round(n * 10) / 10;
43
+
44
+ /**
45
+ * 한 줄로 그리면 칸에 이 배율보다 작게 들어갈 때만 여러 줄로 접는다. 그보다 크면 글자가 읽히므로 한 줄 그대로 둔다.
46
+ * 그래프 칸이 글자가 읽히는 크기로 보는 배율(터미널 아래 칸에서 0.7배까지 줄여 담는다)과 같다
47
+ */
48
+ const WRAP_BELOW = 0.7;
49
+
50
+ /**
51
+ * 계획을 그래프로 배치한다. fit(그릴 칸의 크기)을 주면, 한 줄로는 칸에 너무 작게 들어가는 긴 그래프를
52
+ * 칸 비율에 맞춰 여러 줄로 접는다 (ELK의 graph wrapping). 접어도 더 크게 보이지 않으면 한 줄 그대로 둔다
53
+ */
54
+ export async function layoutGraph(g , size = SIZE, flow = 'right', fit ) {
55
+ const flat = await place(g, size, flow);
56
+ if (!fit || fit.w <= 0 || fit.h <= 0 || !flat.nodes.length) return flat;
57
+ const zoom = (l ) => fitZoom(l, fit);
58
+ if (zoom(flat) >= WRAP_BELOW) return flat;
59
+ // 선이 한 가닥만 지나는 곳에서만 자른다 (SINGLE_EDGE). 갈래 한가운데를 자르지 않아서 줄과 줄 사이로는 선이 늘 한 가닥만 지나간다.
60
+ // 그런 곳이 없는 계획은 ELK가 접지 못하므로 한 줄 그대로 둔다 (MULTI_EDGE는 갈래 한가운데도 잘라 선 여러 가닥이 줄 사이를 길게 돌아갔다)
61
+ const wrapped = await place(g, size, flow, { 'elk.layered.wrapping.strategy': 'SINGLE_EDGE', 'elk.aspectRatio': String(fit.w / fit.h) });
62
+ return zoom(wrapped) > zoom(flat) + 0.05 ? { ...wrapped, wrapped: true } : flat;
63
+ }
64
+
65
+ async function place(g , size , flow , extra = {}) {
66
+ if (!g.nodes.length) return { width: 0, height: 0, nodes: [], edges: [] };
67
+ // elkjs의 한 파일짜리 판 (워커 없이 이 프로세스에서 계산한다)
68
+ const ELK = require('elkjs/lib/elk.bundled.js');
69
+ const ids = new Set(g.nodes.map(n => n.id));
70
+ const lines = g.edges.filter(e => ids.has(e.from) && ids.has(e.to)).map(e => ({ key: `${e.from}|${e.to}`, from: e.from, to: e.to }));
71
+ const out = await new ELK().layout({
72
+ id: 'plan',
73
+ layoutOptions: { ...(flow === 'down' ? { ...OPTIONS, 'elk.direction': 'DOWN', 'elk.layered.spacing.nodeNodeBetweenLayers': '40' } : OPTIONS), ...extra },
74
+ children: g.nodes.map(n => ({ id: n.id, width: size.cardW, height: size.cardH })),
75
+ edges: lines.map(l => ({ id: l.key, sources: [l.from], targets: [l.to] })),
76
+ });
77
+ const nodes = out.children.map((c ) => ({ id: c.id, x: r1(c.x), y: r1(c.y), w: c.width, h: c.height }));
78
+ const edges = out.edges.map((e , i ) => {
79
+ const s = e.sections?.[0];
80
+ if (!s) throw new Error(`선을 잇지 못했어요: ${lines[i].key}`);
81
+ const points = [s.startPoint, ...(s.bendPoints ?? []), s.endPoint].map((p ) => [r1(p.x), r1(p.y)]);
82
+ return { ...lines[i], points };
83
+ });
84
+ return { width: Math.ceil(out.width), height: Math.ceil(out.height), nodes, edges };
85
+ }
86
+
87
+ /** 그래프가 칸에 다 들어가는 배율. 칸보다 작은 그래프를 키우지는 않는다 (1까지) */
88
+ export const fitZoom = (l , fit ) => (l.width && l.height ? Math.min(1, fit.w / l.width, fit.h / l.height) : 1);
89
+
90
+ /** 반대 방향이 칸에 이만큼 넘게 크게 들어가야 칸 모양으로 정한 방향을 버린다 (비슷하면 칸 모양을 따른다) */
91
+ const SWITCH = 1.25;
92
+
93
+ /**
94
+ * 칸에 맞는 흐름 방향으로 배치한다. 칸 모양으로 정한 방향(prefer)을 쓰되, 반대 방향이 칸에 훨씬 크게 들어가면 반대 방향을 쓴다.
95
+ * 두 방향 모두 ELK가 계산한 배치(필요하면 여러 줄로 접은 것)를 그대로 쓰고, 어느 쪽을 쓸지만 고른다.
96
+ * 예: 나란히 하는 일이 여덟인 계획을 좁고 긴 칸에서 위→아래로 그리면 여덟 카드가 옆으로 늘어서 칸보다 몇 배 넓어진다.
97
+ * 왼쪽→오른쪽으로 그리면 여덟 카드가 세로로 쌓여 칸에 들어간다
98
+ */
99
+ export async function layoutFor(g , prefer , fit , size = SIZE) {
100
+ const layout = await layoutGraph(g, size, prefer, fit);
101
+ // 칸에 거의 다 들어가면 반대 방향이 더 나을 수 없다 (1배보다 키우지 않는다)
102
+ if (!fit || fit.w <= 0 || fit.h <= 0 || !layout.nodes.length || fitZoom(layout, fit) * SWITCH >= 1) return { layout, flow: prefer };
103
+ const other = prefer === 'down' ? 'right' : 'down';
104
+ const alt = await layoutGraph(g, size, other, fit);
105
+ return fitZoom(alt, fit) > fitZoom(layout, fit) * SWITCH ? { layout: alt, flow: other } : { layout, flow: prefer };
106
+ }
107
+
108
+ // ── 겹침 검사 ──────────────────────────────────────────────────────────
109
+ // 배치가 지켜야 할 것: 카드끼리 겹치지 않는다, 선은 직각으로 꺾인다,
110
+ // 선은 출발 카드 오른쪽 변에서 나가 도착 카드 왼쪽 변으로 들어간다 (위→아래면 아래 변에서 나가 위 변으로), 선이 카드를 지나지 않는다,
111
+ // 두 선이 같은 줄 위에 포개지지 않는다.
112
+
113
+
114
+
115
+ const segsOf = (e ) => e.points.slice(1).map((p, i) => ({ a: e.points[i], b: p, edge: e.key }));
116
+ const inset = (b , d ) => ({ x: b.x + d, y: b.y + d, w: b.w - 2 * d, h: b.h - 2 * d });
117
+ const boxesMeet = (p , q ) => p.x < q.x + q.w && q.x < p.x + p.w && p.y < q.y + q.h && q.y < p.y + p.h;
118
+
119
+ function segCrosses(s , b ) {
120
+ const [x1, x2] = [Math.min(s.a[0], s.b[0]), Math.max(s.a[0], s.b[0])];
121
+ const [y1, y2] = [Math.min(s.a[1], s.b[1]), Math.max(s.a[1], s.b[1])];
122
+ return x1 < b.x + b.w && x2 > b.x && y1 < b.y + b.h && y2 > b.y;
123
+ }
124
+
125
+ /** 배치의 문제 목록. 비어 있으면 겹침 없이 그릴 수 있다 */
126
+ export function layoutProblems(l , flow = 'right') {
127
+ const out = [];
128
+ const at = new Map(l.nodes.map(n => [n.id, n]));
129
+ const segs = l.edges.flatMap(segsOf);
130
+
131
+ for (let i = 0; i < l.nodes.length; i++) {
132
+ for (let j = i + 1; j < l.nodes.length; j++) {
133
+ if (boxesMeet(l.nodes[i], l.nodes[j])) out.push(`카드 겹침: ${l.nodes[i].id} ↔ ${l.nodes[j].id}`);
134
+ }
135
+ }
136
+ for (const e of l.edges) {
137
+ const src = at.get(e.from), dst = at.get(e.to);
138
+ if (!src || !dst) {
139
+ out.push(`없는 카드에 이은 선: ${e.key}`);
140
+ continue;
141
+ }
142
+ const [p0, pn] = [e.points[0], e.points[e.points.length - 1]];
143
+ if (flow === 'down') {
144
+ if (Math.abs(p0[1] - (src.y + src.h)) > 0.6 || p0[0] < src.x || p0[0] > src.x + src.w) out.push(`선이 출발 카드 아래 변에서 나가지 않음: ${e.key}`);
145
+ if (Math.abs(pn[1] - dst.y) > 0.6 || pn[0] < dst.x || pn[0] > dst.x + dst.w) out.push(`선이 도착 카드 위 변으로 들어가지 않음: ${e.key}`);
146
+ } else {
147
+ if (Math.abs(p0[0] - (src.x + src.w)) > 0.6 || p0[1] < src.y || p0[1] > src.y + src.h) out.push(`선이 출발 카드 오른쪽 변에서 나가지 않음: ${e.key}`);
148
+ if (Math.abs(pn[0] - dst.x) > 0.6 || pn[1] < dst.y || pn[1] > dst.y + dst.h) out.push(`선이 도착 카드 왼쪽 변으로 들어가지 않음: ${e.key}`);
149
+ }
150
+ for (const s of segsOf(e)) {
151
+ if (Math.abs(s.a[0] - s.b[0]) > 0.6 && Math.abs(s.a[1] - s.b[1]) > 0.6) out.push(`비스듬한 선: ${e.key}`);
152
+ }
153
+ }
154
+ for (const s of segs) {
155
+ for (const n of l.nodes) if (segCrosses(s, inset(n, 1))) out.push(`선이 카드를 지남: ${s.edge} → ${n.id}`);
156
+ }
157
+ for (let i = 0; i < segs.length; i++) {
158
+ for (let j = i + 1; j < segs.length; j++) {
159
+ const [s, t] = [segs[i], segs[j]];
160
+ if (s.edge === t.edge) continue;
161
+ const sh = Math.abs(s.a[1] - s.b[1]) < 0.6, th = Math.abs(t.a[1] - t.b[1]) < 0.6;
162
+ if (sh !== th) continue;
163
+ const k = sh ? 1 : 0, m = sh ? 0 : 1;
164
+ if (Math.abs(s.a[k] - t.a[k]) > 0.6) continue;
165
+ const lo = Math.max(Math.min(s.a[m], s.b[m]), Math.min(t.a[m], t.b[m]));
166
+ const hi = Math.min(Math.max(s.a[m], s.b[m]), Math.max(t.a[m], t.b[m]));
167
+ if (hi - lo > 2) out.push(`선 포개짐: ${s.edge} ↔ ${t.edge}`);
168
+ }
169
+ }
170
+ return [...new Set(out)];
171
+ }
package/src/live.js ADDED
@@ -0,0 +1,71 @@
1
+ // 노드를 하던 세션이 아직 살아 있는지 Herdr에 물어본다.
2
+ // muwi는 AI가 적어 준 것만 안다. 세션을 닫아 버리면 "끝"을 적을 쪽이 없어서 노드가 계속 작업 중으로 남는다.
3
+ // 그래서 보여 줄 때 Herdr에 그 터미널이 살아 있는지 확인하고, 없으면 "세션이 닫힘"으로 보여 준다.
4
+ // 상태를 바꾸지는 않는다. 일이 끝났는지는 알 수 없다. 하다가 멈췄다는 것만 보여 준다.
5
+ import { LABEL_SESSION, hc } from './hc.js';
6
+
7
+
8
+
9
+ /**
10
+ * 닫힌 세션과, 그 세션을 마지막으로 본 시각(ms).
11
+ * 판단할 수 없으면 닫혔다고 하지 않는다: Herdr 밖이거나(hc가 없음), 그 세션의 터미널을 모를 때.
12
+ *
13
+ * 닫혔다고 보는 경우
14
+ * - 터미널이 없어졌다 (닫았거나 프로그램이 끝났다)
15
+ * - 터미널은 있는데 에이전트가 돌고 있지 않다 (Claude를 끝내고 셸만 남았다)
16
+ * - 그 터미널에서 다른 대화가 돌고 있다 (/clear, 새로 띄움). 세션이 시작될 때 터미널에 세션 이름을 라벨로 붙여 둔다
17
+ */
18
+ export function closedSessions(sessions , keys , env = process.env) {
19
+ return sessionStates(sessions, keys, env).closed;
20
+ }
21
+
22
+
23
+                        
24
+
25
+                                           
26
+
27
+
28
+
29
+ /** 세션마다 닫혔는지, 살아 있으면 지금 무얼 하는지 (closedSessions와 같은 기준) */
30
+ export function sessionStates(sessions , keys , env = process.env) {
31
+ const closed = new Map ();
32
+ const status = new Map ();
33
+ const none = { closed, status };
34
+ const wanted = [...new Set(keys)].filter(k => sessions[k]?.terminal);
35
+ if (!wanted.length) return none;
36
+ const ls = hc(['ls', '--json'], env, 3000);
37
+ if (!ls.ok) return none;
38
+ let terminals ;
39
+ try {
40
+ terminals = JSON.parse(ls.out)?.terminals ?? [];
41
+ } catch {
42
+ return none;
43
+ }
44
+ const live = new Map (terminals.map(t => [String(t.address), t]));
45
+ const owner = new Map ();
46
+ /** 그 터미널에서 지금 도는 세션. 라벨이 없으면 null (옛 판에서 시작했거나 훅이 없는 도구) */
47
+ const ownerOf = (terminal ) => {
48
+ if (!owner.has(terminal)) {
49
+ let label = null;
50
+ const got = hc(['get', terminal, '--json'], env, 3000);
51
+ try {
52
+ const v = JSON.parse(got.out)?.labels?.[LABEL_SESSION];
53
+ if (typeof v === 'string' && v) label = v;
54
+ } catch {
55
+ // 읽지 못하면 모르는 것으로 둔다
56
+ }
57
+ owner.set(terminal, label);
58
+ }
59
+ return owner.get(terminal) ?? null;
60
+ };
61
+ for (const key of wanted) {
62
+ const terminal = sessions[key].terminal ;
63
+ const t = live.get(terminal);
64
+ // 상태를 알리는 프로그램(에이전트)이 돌고 있어야 살아 있는 것이다. 셸만 남은 터미널은 상태가 없다
65
+ const running = Boolean(t && t.state === 'live' && t.status != null);
66
+ const mine = running ? ownerOf(terminal) : null;
67
+ if (!running || (mine !== null && mine !== key)) closed.set(key, Date.parse(sessions[key].seenAt ?? '') || 0);
68
+ else status.set(key, String(t.status));
69
+ }
70
+ return { closed, status };
71
+ }
package/src/preview.js ADDED
@@ -0,0 +1,106 @@
1
+ // Herdr 설정 화면(Look > Layout)에 보일 muwi 레이아웃 그림. 레이아웃 파일의 "preview"가 이 그림을 가리킨다.
2
+ // 그림이 없으면 설정 화면은 빈 틀만 그린다. 320×200이고 설정 화면에서는 96×62쯤으로 줄어 보이므로 간단하게 그린다:
3
+ // 왼쪽 작업 목록(상태 색 점), 오른쪽 터미널과 그래프 칸. 그래프 칸은 그 레이아웃의 자리(위·아래·오른쪽)대로 그린다.
4
+ // 그림 파일은 테마를 따라가지 못해 어두운 색 하나로 그린다 (Herdr의 Terminals·Herdr 98 그림도 그렇다)
5
+
6
+
7
+ const C = {
8
+ bg: '#1a1c21', side: '#202329', divider: '#2a2e36', canvas: '#1f2228', term: '#16181c',
9
+ text: '#5b6270', faint: '#383d47',
10
+ node: '#272b33', nodeEdge: '#363b45', doingFill: '#2e2a20',
11
+ blue: '#61afef', yellow: '#e5c07b', purple: '#c678dd', green: '#98c379',
12
+ };
13
+
14
+
15
+
16
+
17
+ export function layoutPreview(where = 'bottom') {
18
+ const out = [];
19
+ const rect = (b , fill , rx = 0, extra = '') =>
20
+ out.push(`<rect x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}"${rx ? ` rx="${rx}"` : ''} fill="${fill}"${extra}/>`);
21
+ const bar = (x , y , w , fill , h = 5) => rect({ x, y: y - h / 2, w, h }, fill, h / 2);
22
+ const dot = (x , y , r , fill ) => out.push(`<circle cx="${x}" cy="${y}" r="${r}" fill="${fill}"/>`);
23
+ const ring = (x , y , r , color ) => out.push(`<circle cx="${x}" cy="${y}" r="${r}" fill="none" stroke="${color}" stroke-width="1.6"/>`);
24
+
25
+ rect({ x: 0, y: 0, w: 320, h: 200 }, C.bg);
26
+
27
+ // 작업 목록: 응답 대기 · 작업 중 · 새 결과 · 끝 · 끝
28
+ rect({ x: 0, y: 0, w: 80, h: 200 }, C.side);
29
+ rect({ x: 80, y: 0, w: 1.5, h: 200 }, C.divider);
30
+ const rows = [[C.purple, 38, C.text], [C.yellow, 30, C.text], [C.blue, 42, C.text], [C.faint, 34, C.faint], [C.faint, 26, C.faint]];
31
+ rows.forEach(([color, w, line], i) => {
32
+ const y = 52 + i * 24;
33
+ dot(18, y, 4, color);
34
+ bar(30, y, w, line);
35
+ });
36
+
37
+ // 터미널과 그래프 칸의 자리
38
+ let graph , term ;
39
+ if (where === 'top') {
40
+ graph = { x: 81.5, y: 0, w: 238.5, h: 112 };
41
+ term = { x: 81.5, y: 113.5, w: 238.5, h: 86.5 };
42
+ } else if (where === 'right') {
43
+ term = { x: 81.5, y: 0, w: 118.5, h: 200 };
44
+ graph = { x: 201.5, y: 0, w: 118.5, h: 200 };
45
+ } else {
46
+ term = { x: 81.5, y: 0, w: 238.5, h: 86.5 };
47
+ graph = { x: 81.5, y: 88, w: 238.5, h: 112 };
48
+ }
49
+ if (where === 'top') rect({ x: 81.5, y: 112, w: 238.5, h: 1.5 }, C.divider);
50
+ if (where === 'bottom') rect({ x: 81.5, y: 86.5, w: 238.5, h: 1.5 }, C.divider);
51
+ if (where === 'right') rect({ x: 200, y: 0, w: 1.5, h: 200 }, C.divider);
52
+
53
+ // 터미널: 세 줄만
54
+ rect(term, C.term);
55
+ const tx = term.x + 16, ty = term.y + Math.min(26, term.h / 4);
56
+ dot(tx, ty, 2.6, C.green);
57
+ bar(tx + 8, ty, Math.min(84, term.w - 40), C.text, 4.5);
58
+ bar(tx - 2.6, ty + 18, Math.min(136, term.w - 32), C.faint, 4.5);
59
+ bar(tx - 2.6, ty + 36, Math.min(100, term.w - 50), C.faint, 4.5);
60
+
61
+ // 그래프: 끝난 노드 → 끝난 노드·작업 중인 노드 → 아직
62
+ rect(graph, C.canvas);
63
+ const down = where === 'right';
64
+ const W = down ? 40 : 54, H = down ? 18 : 20;
65
+ const at = (x , y , s ) => ({ b: { x, y, w: W, h: H }, s });
66
+ let nodes ;
67
+ if (!down) {
68
+ const gap = 22, x0 = graph.x + (graph.w - (3 * W + 2 * gap)) / 2, cy = graph.y + graph.h / 2 - H / 2;
69
+ nodes = [at(x0, cy, 'done'), at(x0 + W + gap, cy - 17, 'done'), at(x0 + W + gap, cy + 17, 'doing'), at(x0 + 2 * (W + gap), cy, 'todo')];
70
+ } else {
71
+ const gap = 10, cx = graph.x + (graph.w - W) / 2, x0 = graph.x + (graph.w - (2 * W + gap)) / 2;
72
+ nodes = [at(cx, 44, 'done'), at(x0, 91, 'done'), at(x0 + W + gap, 91, 'doing'), at(cx, 138, 'todo')];
73
+ }
74
+ const [a, b1, b2, c] = nodes;
75
+
76
+ // 선: 끝난 노드에서 나가는 선은 파랑, 나머지는 흐리게. 꺾이는 곳은 둥글게
77
+ const edge = (from , to ) => {
78
+ const color = from.s === 'done' ? C.blue : C.faint;
79
+ const f = from.b, t = to.b, r = 5;
80
+ let d ;
81
+ if (!down) {
82
+ const x1 = f.x + f.w, y1 = f.y + f.h / 2, x2 = t.x, y2 = t.y + t.h / 2, mx = (x1 + x2) / 2;
83
+ const s = Math.sign(y2 - y1), k = Math.min(r, Math.abs(y2 - y1) / 2);
84
+ d = s === 0 ? `M${x1} ${y1} H${x2}` : `M${x1} ${y1} H${mx - k} Q${mx} ${y1} ${mx} ${y1 + s * k} V${y2 - s * k} Q${mx} ${y2} ${mx + k} ${y2} H${x2}`;
85
+ } else {
86
+ const x1 = f.x + f.w / 2, y1 = f.y + f.h, x2 = t.x + t.w / 2, y2 = t.y, my = (y1 + y2) / 2;
87
+ const s = Math.sign(x2 - x1), k = Math.min(r, Math.abs(x2 - x1) / 2);
88
+ d = s === 0 ? `M${x1} ${y1} V${y2}` : `M${x1} ${y1} V${my - k} Q${x1} ${my} ${x1 + s * k} ${my} H${x2 - s * k} Q${x2} ${my} ${x2} ${my + k} V${y2}`;
89
+ }
90
+ out.push(`<path d="${d}" fill="none" stroke="${color}" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>`);
91
+ };
92
+ edge(a, b1); edge(a, b2); edge(b1, c); edge(b2, c);
93
+
94
+ // 노드: 상태 점 하나와 제목 한 줄. 작업 중인 노드는 노랗게 빛난다
95
+ for (const { b, s } of nodes) {
96
+ if (s === 'doing') rect({ x: b.x - 4, y: b.y - 4, w: b.w + 8, h: b.h + 8 }, C.yellow, 9, ' opacity="0.14"');
97
+ rect(b, s === 'doing' ? C.doingFill : C.node, 6, ` stroke="${s === 'doing' ? C.yellow : C.nodeEdge}" stroke-width="${s === 'doing' ? 1.6 : 1.2}"`);
98
+ const cy = b.y + b.h / 2, ix = b.x + 10;
99
+ if (s === 'done') dot(ix, cy, 3.4, C.blue);
100
+ if (s === 'doing') dot(ix, cy, 3.4, C.yellow);
101
+ if (s === 'todo') ring(ix, cy, 3, C.text);
102
+ bar(b.x + 19, cy, b.w - (down ? 27 : 29), s === 'todo' ? C.faint : C.text, 4);
103
+ }
104
+
105
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 200">\n ${out.join('\n ')}\n</svg>\n`;
106
+ }
package/src/resume.js ADDED
@@ -0,0 +1,68 @@
1
+ // 닫힌 세션을 이어 하는 버튼(그래프 칸의 "이어서 하려면")에 쓸 사실을 모은다.
2
+ // 그래프 칸(Herdr 앱 mod)은 파일을 볼 수 없어서 muwi board가 알려 준다:
3
+ // 그 폴더가 아직 있는가 (worktree를 지웠으면 그 폴더에서는 터미널을 열 수 없다)
4
+ // Claude 대화를 다시 열 수 있는가 (대화 파일이 없으면 claude --resume이 "No conversation found"로 끝난다)
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { launchCommand, resumeCommand, toolById } from '@muwi/core/connectors/tools';
9
+
10
+
11
+ /** Claude Code 세션 id 모양. muwi는 Claude 세션의 id를 세션 이름으로 쓴다 */
12
+ const CLAUDE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+
14
+
15
+                                                   
16
+
17
+                                
18
+
19
+                                                  
20
+
21
+                                                            
22
+
23
+                                      
24
+
25
+                                
26
+
27
+
28
+
29
+ /** 터미널로 대신한 세션 이름 (세션 id를 주지 않는 도구). 이 이름으로는 대화를 다시 열 수 없다 */
30
+ const STAND_IN = /^(hc|herdr)-/;
31
+
32
+ /** Claude Code는 대화를 <설정 폴더>/projects/<폴더 경로의 글자 아닌 것을 -로 바꾼 이름>/<세션 id>.jsonl에 남긴다 */
33
+ export function resumeFacts(v , env = process.env) {
34
+ const folders = new Set ();
35
+ if (v.cwd) folders.add(v.cwd);
36
+ for (const s of Object.values(v.sessions)) if (s.cwd) folders.add(s.cwd);
37
+ for (const n of v.nodes) for (const sp of n.spawns ?? []) if (sp.cwd) folders.add(sp.cwd);
38
+ const exists = Object.fromEntries([...folders].map(f => [f, fs.existsSync(f)]));
39
+
40
+ const projects = path.join(env.CLAUDE_CONFIG_DIR || path.join(env.HOME || env.USERPROFILE || os.homedir(), '.claude'), 'projects');
41
+ let dirs = null;
42
+ const saved = (key , cwd ) => {
43
+ // 보통은 그 폴더 이름으로 된 곳에 있다. 못 찾으면 모든 프로젝트 폴더를 본다 (이름 짓는 법이 바뀌어도 찾게)
44
+ if (cwd && fs.existsSync(path.join(projects, cwd.replace(/[^A-Za-z0-9]/g, '-'), `${key}.jsonl`))) return true;
45
+ dirs ??= (() => {
46
+ try {
47
+ return fs.readdirSync(projects);
48
+ } catch {
49
+ return [];
50
+ }
51
+ })();
52
+ return dirs.some(d => fs.existsSync(path.join(projects, d, `${key}.jsonl`)));
53
+ };
54
+ const resume = {};
55
+ const launch = {};
56
+ for (const [key, s] of Object.entries(v.sessions)) {
57
+ if (toolById(s.tool)) launch[key] = launchCommand(s.tool);
58
+ // Claude Code는 대화 파일이 남아 있어야 열린다. 다른 도구는 그 도구의 대화 id가 있으면 이어 가기 명령을 쓴다.
59
+ // 터미널을 세션으로 본 도구는 훅이 적어 둔 대화 id(native)를 쓴다
60
+ const id = s.native ?? (STAND_IN.test(key) ? null : key);
61
+ const can = s.tool === 'claude' ? CLAUDE_ID.test(key) && saved(key, s.cwd) : Boolean(id);
62
+ const command = can && id ? resumeCommand(s.tool, id) : null;
63
+ if (command) resume[key] = command;
64
+ }
65
+ const launcher = (v.lead && launch[v.lead]) || launchCommand('claude');
66
+ const toolNames = Object.fromEntries(Object.values(v.sessions).map(s => toolById(s.tool)).filter(t => t !== null).map(t => [t .id, t .name]));
67
+ return { exists, resumable: Object.keys(resume), resume, launch, launcher, toolNames };
68
+ }