@tienne/gestalt 0.152.0 → 0.153.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.
Files changed (54) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  3. package/dist/plugin/skills/conductor/SKILL.md +2 -0
  4. package/dist/src/cli/commands/conductor-results.d.ts +34 -0
  5. package/dist/src/cli/commands/conductor-results.d.ts.map +1 -0
  6. package/dist/src/cli/commands/conductor-results.js +301 -0
  7. package/dist/src/cli/commands/conductor-results.js.map +1 -0
  8. package/dist/src/cli/commands/conductor.d.ts.map +1 -1
  9. package/dist/src/cli/commands/conductor.js +14 -21
  10. package/dist/src/cli/commands/conductor.js.map +1 -1
  11. package/dist/src/cli/index.d.ts.map +1 -1
  12. package/dist/src/cli/index.js +42 -0
  13. package/dist/src/cli/index.js.map +1 -1
  14. package/dist/src/conductor/fold.d.ts +32 -0
  15. package/dist/src/conductor/fold.d.ts.map +1 -0
  16. package/dist/src/conductor/fold.js +168 -0
  17. package/dist/src/conductor/fold.js.map +1 -0
  18. package/dist/src/conductor/recent-events.d.ts +8 -2
  19. package/dist/src/conductor/recent-events.d.ts.map +1 -1
  20. package/dist/src/conductor/recent-events.js +40 -8
  21. package/dist/src/conductor/recent-events.js.map +1 -1
  22. package/dist/src/conductor/results-markdown.d.ts +6 -0
  23. package/dist/src/conductor/results-markdown.d.ts.map +1 -0
  24. package/dist/src/conductor/results-markdown.js +377 -0
  25. package/dist/src/conductor/results-markdown.js.map +1 -0
  26. package/dist/src/conductor/results.d.ts +238 -0
  27. package/dist/src/conductor/results.d.ts.map +1 -0
  28. package/dist/src/conductor/results.js +703 -0
  29. package/dist/src/conductor/results.js.map +1 -0
  30. package/dist/src/conductor/state-dir.d.ts +8 -0
  31. package/dist/src/conductor/state-dir.d.ts.map +1 -0
  32. package/dist/src/conductor/state-dir.js +10 -0
  33. package/dist/src/conductor/state-dir.js.map +1 -0
  34. package/dist/src/conductor/store.d.ts +55 -3
  35. package/dist/src/conductor/store.d.ts.map +1 -1
  36. package/dist/src/conductor/store.js +157 -11
  37. package/dist/src/conductor/store.js.map +1 -1
  38. package/dist/src/conductor/terminal-text.d.ts +8 -0
  39. package/dist/src/conductor/terminal-text.d.ts.map +1 -0
  40. package/dist/src/conductor/terminal-text.js +18 -0
  41. package/dist/src/conductor/terminal-text.js.map +1 -0
  42. package/dist/src/conductor-web/html.d.ts +9 -0
  43. package/dist/src/conductor-web/html.d.ts.map +1 -0
  44. package/dist/src/conductor-web/html.js +475 -0
  45. package/dist/src/conductor-web/html.js.map +1 -0
  46. package/dist/src/conductor-web/server.d.ts +48 -0
  47. package/dist/src/conductor-web/server.d.ts.map +1 -0
  48. package/dist/src/conductor-web/server.js +369 -0
  49. package/dist/src/conductor-web/server.js.map +1 -0
  50. package/package.json +1 -1
  51. package/plugin/.codex-plugin/plugin.json +1 -1
  52. package/plugin/.mcp.json +1 -1
  53. package/plugin/mcp.json +1 -1
  54. package/plugin/skills/conductor/SKILL.md +2 -0
@@ -0,0 +1,703 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readdirSync, readSync, realpathSync, statSync, } from 'node:fs';
3
+ import { basename, extname, isAbsolute, join, relative, sep } from 'node:path';
4
+ import { isControlChar } from './intake.js';
5
+ import { orcaWorktreeName } from './launcher.js';
6
+ import { BASE_FILE, EVENTS_FILE, listSegments, replayStore } from './store.js';
7
+ /**
8
+ * 컨덕터 결과 뷰어의 데이터 계층. 터미널 명령과 웹 뷰어가 같이 쓴다.
9
+ *
10
+ * 저장소에는 아무것도 쓰지 않는다. `ConductorStore.open()`은 디렉토리를 만들고
11
+ * tick과 같은 파일을 만지므로 쓰지 않고 이벤트 로그를 직접 재생한다.
12
+ * 워커 보고의 refs와 그 파일 본문은 워커가 적은 값이라 신뢰하지 않는다. 읽을 수 있는 자리를
13
+ * 허용 루트 아래로 묶고 확장자와 크기도 제한한다.
14
+ */
15
+ /** 본문을 읽어도 되는 확장자. 그 밖은 경로만 보여준다 */
16
+ export const READABLE_EXTENSIONS = new Set([
17
+ '.md',
18
+ '.markdown',
19
+ '.txt',
20
+ '.log',
21
+ '.json',
22
+ '.diff',
23
+ '.patch',
24
+ ]);
25
+ /** 이보다 큰 파일은 앞부분만 읽는다 */
26
+ export const MAX_FULL_READ_BYTES = 1024 * 1024;
27
+ export const TRUNCATED_READ_BYTES = 256 * 1024;
28
+ /** 디렉토리 ref 하나에서 보여줄 파일 수 상한 */
29
+ export const MAX_DIR_ENTRIES = 50;
30
+ /** 본문 캐시 상한. 서버가 오래 떠 있어도 읽은 본문이 메모리에 끝없이 쌓이지 않게 한다 */
31
+ export const BODY_CACHE_MAX_ENTRIES = 256;
32
+ export const BODY_CACHE_MAX_CHARS = 32 * 1024 * 1024;
33
+ /** "주문 없음" 묶음을 모으는 저장소 하위 디렉토리. 프롬프트나 인계 파일 같은 운영 파일 자리는 뺀다 */
34
+ export const UNLINKED_DIRS = [
35
+ 'reports',
36
+ 'refs',
37
+ 'results',
38
+ 'artifacts',
39
+ 'notes',
40
+ 'drafts',
41
+ ];
42
+ /** 저장소 최상위에서 이 이름으로 시작하는 디렉토리도 "주문 없음" 수집 대상이다 */
43
+ export const UNLINKED_DIR_PREFIX_RE = /^(?:ord|wrk)-/;
44
+ const ORDER_ID_RE = /ord-[0-9a-f]{8}/g;
45
+ const URL_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;
46
+ /**
47
+ * 읽은 본문 캐시. 키는 경로와 mtime, 크기라 파일이 바뀌면 다음 읽기에서 새로 읽는다.
48
+ * 개수와 글자 수 상한을 넘으면 가장 오래 안 쓴 것부터 버린다
49
+ */
50
+ export class BodyCache {
51
+ maxEntries;
52
+ maxChars;
53
+ map = new Map();
54
+ chars = 0;
55
+ constructor(maxEntries = BODY_CACHE_MAX_ENTRIES, maxChars = BODY_CACHE_MAX_CHARS) {
56
+ this.maxEntries = maxEntries;
57
+ this.maxChars = maxChars;
58
+ }
59
+ get size() {
60
+ return this.map.size;
61
+ }
62
+ get(key) {
63
+ const v = this.map.get(key);
64
+ if (v) {
65
+ this.map.delete(key);
66
+ this.map.set(key, v);
67
+ }
68
+ return v;
69
+ }
70
+ set(key, body) {
71
+ const old = this.map.get(key);
72
+ if (old) {
73
+ this.chars -= old.text.length;
74
+ this.map.delete(key);
75
+ }
76
+ this.map.set(key, body);
77
+ this.chars += body.text.length;
78
+ for (const [k, v] of this.map) {
79
+ if (this.map.size <= this.maxEntries && this.chars <= this.maxChars)
80
+ break;
81
+ if (k === key)
82
+ break;
83
+ this.map.delete(k);
84
+ this.chars -= v.text.length;
85
+ }
86
+ }
87
+ }
88
+ export function loadResults(opts) {
89
+ if (!existsSync(opts.stateDir) || !statSync(opts.stateDir).isDirectory()) {
90
+ throw new Error(`상태 저장소가 없어요: ${opts.stateDir}`);
91
+ }
92
+ const eventsPath = join(opts.stateDir, EVENTS_FILE);
93
+ if (!existsSync(eventsPath) &&
94
+ !existsSync(join(opts.stateDir, BASE_FILE)) &&
95
+ listSegments(opts.stateDir).length === 0) {
96
+ throw new Error(`${eventsPath}가 없어요. 받은 주문이 아직 없어요`);
97
+ }
98
+ const stateDir = realpathSync(opts.stateDir);
99
+ const snapshot = replayStore(stateDir);
100
+ const repoRoots = realRoots(Object.values(opts.repoPaths ?? {}));
101
+ const orderRefs = new Map();
102
+ for (const id of Object.keys(snapshot.orders)) {
103
+ const ctx = refContext(snapshot, id, stateDir, repoRoots);
104
+ const seen = new Map();
105
+ const firstReport = [];
106
+ const refs = [];
107
+ (snapshot.reports[id] ?? []).forEach((r, i) => {
108
+ for (const ref of r.refs) {
109
+ if (seen.has(ref))
110
+ continue;
111
+ seen.set(ref, refs.length);
112
+ refs.push(classifyRef(ref, ctx));
113
+ firstReport.push(i + 1);
114
+ }
115
+ });
116
+ orderRefs.set(id, { refs, firstReport });
117
+ }
118
+ const linked = new Set();
119
+ const linkedDirs = [];
120
+ for (const { refs } of orderRefs.values()) {
121
+ for (const r of refs) {
122
+ if (r.kind === 'file' && r.path)
123
+ linked.add(r.path);
124
+ if (r.kind === 'dir' && r.path)
125
+ linkedDirs.push(r.path);
126
+ }
127
+ }
128
+ const files = collectUnlinkedFiles(stateDir, linked, linkedDirs, new Set(Object.keys(snapshot.orders)));
129
+ const filesByOrder = new Map();
130
+ for (const f of files) {
131
+ if (!f.orderId)
132
+ continue;
133
+ const list = filesByOrder.get(f.orderId);
134
+ if (list)
135
+ list.push(f);
136
+ else
137
+ filesByOrder.set(f.orderId, [f]);
138
+ }
139
+ return {
140
+ stateDir,
141
+ snapshot,
142
+ repoRoots,
143
+ orderRefs,
144
+ files,
145
+ fileByKey: new Map(files.map((f) => [f.key, f])),
146
+ filesByOrder,
147
+ bodies: opts.bodies ?? new BodyCache(),
148
+ };
149
+ }
150
+ function realRoots(paths) {
151
+ const out = [];
152
+ for (const p of paths) {
153
+ if (!isAbsolute(p))
154
+ continue;
155
+ try {
156
+ out.push(realpathSync(p));
157
+ }
158
+ catch {
159
+ // 지금 없는 레포 경로는 허용 루트에서 뺀다
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ export function refContext(snapshot, orderId, stateDir, repoRoots) {
165
+ const workers = Object.values(snapshot.workers).filter((w) => w.orderId === orderId);
166
+ const worktrees = realRoots(workers.filter((w) => w.kind === 'git-worktree' && w.handle).map((w) => w.handle));
167
+ return {
168
+ roots: [stateDir, ...repoRoots, ...worktrees],
169
+ worktreeNames: workers.filter((w) => w.kind === 'orca-worktree').map(orcaWorktreeName),
170
+ };
171
+ }
172
+ function within(path, root) {
173
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
174
+ }
175
+ function allowed(real, ctx) {
176
+ if (ctx.roots.some((r) => within(real, r)))
177
+ return true;
178
+ // 오르카 워커의 워크트리 경로는 저장소에 안 남는다. 워크트리 디렉토리 이름이 주문 id와 회차라 그 이름으로 가린다
179
+ const parts = real.split(sep);
180
+ return ctx.worktreeNames.some((n) => parts.slice(0, -1).includes(n));
181
+ }
182
+ /**
183
+ * refs 항목 하나를 분류한다. 본문은 읽지 않는다.
184
+ * 파일 후보는 절대 경로뿐이다. 심링크와 `..`는 실제 경로로 푼 뒤 허용 루트와 비교해 막는다.
185
+ */
186
+ export function classifyRef(ref, ctx) {
187
+ const value = ref.trim();
188
+ const base = { ref, display: value };
189
+ if (URL_SCHEME_RE.test(value) && !isAbsolute(value)) {
190
+ try {
191
+ const url = new URL(value);
192
+ if (url.protocol === 'http:' || url.protocol === 'https:') {
193
+ return { ...base, kind: 'url', display: url.href };
194
+ }
195
+ }
196
+ catch {
197
+ // 주소 꼴이 아니면 글자로 보여준다
198
+ }
199
+ return { ...base, kind: 'reference' };
200
+ }
201
+ if (!isAbsolute(value) || value.includes('\0'))
202
+ return { ...base, kind: 'reference' };
203
+ let real;
204
+ try {
205
+ real = realpathSync(value);
206
+ }
207
+ catch {
208
+ return { ...base, kind: 'missing' };
209
+ }
210
+ if (!allowed(real, ctx))
211
+ return { ...base, kind: 'outside' };
212
+ let st;
213
+ try {
214
+ st = statSync(real);
215
+ }
216
+ catch {
217
+ return { ...base, kind: 'missing' };
218
+ }
219
+ if (st.isDirectory()) {
220
+ const { entries, total } = dirEntries(real);
221
+ return { ...base, kind: 'dir', path: real, entries, entriesTotal: total };
222
+ }
223
+ if (!st.isFile() || !READABLE_EXTENSIONS.has(extname(real).toLowerCase())) {
224
+ return { ...base, kind: 'unsupported' };
225
+ }
226
+ return { ...base, kind: 'file', path: real, size: st.size };
227
+ }
228
+ /** 디렉토리 바로 아래 읽을 수 있는 파일. 심링크는 Dirent가 파일로 안 쳐서 빠진다 */
229
+ function dirEntries(dir) {
230
+ let names;
231
+ try {
232
+ names = readdirSync(dir, { withFileTypes: true })
233
+ .filter((d) => d.isFile() && READABLE_EXTENSIONS.has(extname(d.name).toLowerCase()))
234
+ .map((d) => d.name)
235
+ .sort();
236
+ }
237
+ catch {
238
+ return { entries: [], total: 0 };
239
+ }
240
+ const out = [];
241
+ for (const name of names.slice(0, MAX_DIR_ENTRIES)) {
242
+ const path = join(dir, name);
243
+ try {
244
+ out.push({ name, path, size: statSync(path).size });
245
+ }
246
+ catch {
247
+ // 목록을 읽은 사이 지워진 파일은 뺀다
248
+ }
249
+ }
250
+ return { entries: out, total: names.length };
251
+ }
252
+ /**
253
+ * 허용 루트 아래 텍스트 파일을 읽는다. 분류한 뒤에 파일이 심링크로 바뀌었을 수 있어 읽기 직전에 다시 확인한다.
254
+ * 확인한 뒤 여는 사이의 교체는 두 경우만 막는다. 마지막 경로 요소가 심링크로 바뀌면 O_NOFOLLOW로 열기가 실패한다.
255
+ * 다른 파일로 바뀌면 연 fd의 dev, ino가 확인한 파일과 달라 버린다. 중간 디렉토리가 바뀌는 경우는 막지 않는다.
256
+ * 조건에 안 맞거나 읽다 실패하면 null.
257
+ */
258
+ export function readTextFile(path, roots) {
259
+ let real;
260
+ try {
261
+ if (lstatSync(path).isSymbolicLink())
262
+ return null;
263
+ real = realpathSync(path);
264
+ }
265
+ catch {
266
+ return null;
267
+ }
268
+ if (!roots.some((r) => within(real, r)))
269
+ return null;
270
+ if (!READABLE_EXTENSIONS.has(extname(real).toLowerCase()))
271
+ return null;
272
+ let fd;
273
+ let checked;
274
+ try {
275
+ checked = statSync(real);
276
+ // FIFO를 열면 쓰는 쪽이 올 때까지 멈춘다. 열기 전에 일반 파일만 남기고 O_NONBLOCK도 건다
277
+ if (!checked.isFile())
278
+ return null;
279
+ fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
280
+ }
281
+ catch {
282
+ return null;
283
+ }
284
+ try {
285
+ const st = fstatSync(fd);
286
+ if (!st.isFile() || st.dev !== checked.dev || st.ino !== checked.ino)
287
+ return null;
288
+ const truncated = st.size > MAX_FULL_READ_BYTES;
289
+ const want = truncated ? TRUNCATED_READ_BYTES : st.size;
290
+ const buf = Buffer.alloc(want);
291
+ let read = 0;
292
+ while (read < want) {
293
+ const n = readSync(fd, buf, read, want - read, read);
294
+ if (n === 0)
295
+ break;
296
+ read += n;
297
+ }
298
+ return { text: buf.subarray(0, read).toString('utf-8'), truncated, size: st.size };
299
+ }
300
+ catch {
301
+ return null;
302
+ }
303
+ finally {
304
+ closeSync(fd);
305
+ }
306
+ }
307
+ /** 분류된 ref의 본문. file이 아니면 null. 디렉토리 항목은 `entry`(0부터)로 고른다 */
308
+ export function readRefBody(results, orderId, ref, entry) {
309
+ const ctx = refContext(results.snapshot, orderId, results.stateDir, results.repoRoots);
310
+ const fresh = classifyRef(ref.ref, ctx);
311
+ if (entry !== undefined) {
312
+ if (fresh.kind !== 'dir' || !fresh.path)
313
+ return null;
314
+ const e = fresh.entries?.[entry];
315
+ return e ? cachedBody(results, e.path, [fresh.path], { store: true }) : null;
316
+ }
317
+ if (fresh.kind !== 'file' || !fresh.path)
318
+ return null;
319
+ return cachedBody(results, fresh.path, [dirOf(fresh.path)], { store: true });
320
+ }
321
+ /**
322
+ * 검색용. 로드 때 분류한 경로를 다시 분류하지 않고 읽는다. 바뀐 파일은 readTextFile이 읽기 직전에 다시 막는다
323
+ */
324
+ function loadedRefBody(results, ref, entry) {
325
+ if (!ref.path)
326
+ return null;
327
+ if (entry !== undefined) {
328
+ const e = ref.kind === 'dir' ? ref.entries?.[entry] : undefined;
329
+ return e ? cachedBody(results, e.path, [ref.path], NO_STORE) : null;
330
+ }
331
+ return ref.kind === 'file' ? cachedBody(results, ref.path, [dirOf(ref.path)], NO_STORE) : null;
332
+ }
333
+ /** 저장소 파일 본문. 키로만 고른다. 검색은 `cache: false`로 불러 캐시를 채우지 않는다 */
334
+ export function readResultFile(results, key, opts = {}) {
335
+ const file = results.fileByKey.get(key);
336
+ if (!file)
337
+ return null;
338
+ return cachedBody(results, file.path, [results.stateDir], { store: opts.cache !== false });
339
+ }
340
+ function dirOf(path) {
341
+ const i = path.lastIndexOf(sep);
342
+ return i <= 0 ? sep : path.slice(0, i);
343
+ }
344
+ const NO_STORE = { store: false };
345
+ /**
346
+ * 못 읽은 결과는 캐시하지 않는다. 잠깐 난 권한 오류가 파일이 바뀔 때까지 남지 않게 한다.
347
+ * 검색은 파일을 한 번씩 훑기만 해서 `store`를 끈다. 켜 두면 검색 한 번이 상세 화면에서 연 본문을 밀어낸다.
348
+ * 심링크는 캐시 키가 같아 보여도 가리키는 대상이 바뀔 수 있어서 캐시를 보기 전에 막는다
349
+ */
350
+ function cachedBody(results, path, roots, { store }) {
351
+ let st;
352
+ try {
353
+ st = lstatSync(path, { throwIfNoEntry: false });
354
+ }
355
+ catch {
356
+ // 파일 아래를 가리키는 경로는 throwIfNoEntry를 꺼도 ENOTDIR로 던진다
357
+ return null;
358
+ }
359
+ if (!st || st.isSymbolicLink())
360
+ return null;
361
+ const key = `${path}\0${st.mtimeMs}\0${st.size}`;
362
+ const hit = results.bodies.get(key);
363
+ if (hit)
364
+ return hit;
365
+ const body = readTextFile(path, roots);
366
+ if (body && store)
367
+ results.bodies.set(key, body);
368
+ return body;
369
+ }
370
+ /**
371
+ * 어느 주문 refs에도 안 걸린 저장소 파일을 모은다.
372
+ * 파일 이름이나 상위 디렉토리 이름에 있는 주문 id로 그 주문의 관련 파일로 붙인다. 못 붙이면 주문 없음이다.
373
+ */
374
+ export function collectUnlinkedFiles(stateDir, linked, linkedDirs, orderIds) {
375
+ const paths = [];
376
+ const top = readdirSync(stateDir, { withFileTypes: true });
377
+ const dirs = [...UNLINKED_DIRS];
378
+ // 워커가 저장소 최상위에 주문이나 워커 id로 만든 결과 디렉토리도 모은다. Dirent가 심링크는 디렉토리로 안 친다
379
+ for (const d of top)
380
+ if (d.isDirectory() && UNLINKED_DIR_PREFIX_RE.test(d.name))
381
+ dirs.push(d.name);
382
+ for (const name of dirs) {
383
+ const dir = join(stateDir, name);
384
+ if (!existsSync(dir) || lstatSync(dir).isSymbolicLink())
385
+ continue;
386
+ for (const d of readdirSync(dir, { withFileTypes: true, recursive: true })) {
387
+ if (d.isFile())
388
+ paths.push(join(d.parentPath, d.name));
389
+ }
390
+ }
391
+ for (const d of top) {
392
+ const ext = extname(d.name).toLowerCase();
393
+ if (d.isFile() && (ext === '.md' || ext === '.markdown'))
394
+ paths.push(join(stateDir, d.name));
395
+ }
396
+ const out = [];
397
+ for (const path of paths) {
398
+ if (!READABLE_EXTENSIONS.has(extname(path).toLowerCase()))
399
+ continue;
400
+ if (linked.has(path) || linkedDirs.some((dir) => within(path, dir)))
401
+ continue;
402
+ const rel = relative(stateDir, path);
403
+ const st = statSync(path);
404
+ const orderId = [...rel.matchAll(ORDER_ID_RE)].map((m) => m[0]).find((id) => orderIds.has(id));
405
+ out.push({
406
+ key: fileKey(rel),
407
+ path,
408
+ rel,
409
+ size: st.size,
410
+ mtime: st.mtime.toISOString(),
411
+ ...(orderId ? { orderId } : {}),
412
+ });
413
+ }
414
+ return out.sort((a, b) => b.mtime.localeCompare(a.mtime) || a.rel.localeCompare(b.rel));
415
+ }
416
+ function fileKey(rel) {
417
+ return createHash('sha256').update(rel).digest('hex').slice(0, 16);
418
+ }
419
+ /** `--since` 값. 날짜만 적으면 화면의 날짜와 맞게 로컬 자정으로 읽는다. 날짜로 못 읽으면 던진다 */
420
+ export function parseSince(v) {
421
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v.trim());
422
+ if (day) {
423
+ const [y, m, d] = [Number(day[1]), Number(day[2]), Number(day[3])];
424
+ const local = new Date(y, m - 1, d);
425
+ if (local.getFullYear() === y && local.getMonth() === m - 1 && local.getDate() === d) {
426
+ return local.getTime();
427
+ }
428
+ throw new Error(`--since는 2026-11-01 같은 날짜여야 해요: ${v}`);
429
+ }
430
+ const t = Date.parse(v);
431
+ if (Number.isNaN(t))
432
+ throw new Error(`--since는 2026-11-01 같은 날짜여야 해요: ${v}`);
433
+ return t;
434
+ }
435
+ function matchesFilters(o, f, since) {
436
+ if (f.repo && o.repo !== f.repo)
437
+ return false;
438
+ if (f.status && o.status !== f.status)
439
+ return false;
440
+ if (f.issueKey && o.issueKey !== f.issueKey)
441
+ return false;
442
+ if (since !== undefined && Date.parse(o.updatedAt) < since)
443
+ return false;
444
+ return true;
445
+ }
446
+ function filteredOrders(results, f) {
447
+ const since = f.since ? parseSince(f.since) : undefined;
448
+ return Object.values(results.snapshot.orders)
449
+ .filter((o) => matchesFilters(o, f, since))
450
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id));
451
+ }
452
+ function relatedFiles(results, orderId) {
453
+ return results.filesByOrder.get(orderId) ?? [];
454
+ }
455
+ export function summarize(results, o) {
456
+ const reports = results.snapshot.reports[o.id] ?? [];
457
+ const last = reports[reports.length - 1];
458
+ return {
459
+ id: o.id,
460
+ title: o.title,
461
+ repo: o.repo,
462
+ status: o.status,
463
+ ...(o.issueKey ? { issueKey: o.issueKey } : {}),
464
+ ...(o.prRef ? { prRef: o.prRef } : {}),
465
+ createdAt: o.createdAt,
466
+ updatedAt: o.updatedAt,
467
+ reportCount: reports.length,
468
+ refCount: results.orderRefs.get(o.id)?.refs.length ?? 0,
469
+ relatedCount: relatedFiles(results, o.id).length,
470
+ ...(last ? { lastReportAt: last.at } : {}),
471
+ };
472
+ }
473
+ export function listOrders(results, filters = {}) {
474
+ const orders = filteredOrders(results, filters);
475
+ return { total: orders.length, orders: orders.map((o) => summarize(results, o)) };
476
+ }
477
+ /** 주문 id. 앞부분만 적어도 하나로 정해지면 받는다 */
478
+ export function resolveOrderId(results, input) {
479
+ const { orders, removedOrders } = results.snapshot;
480
+ if (Object.hasOwn(orders, input))
481
+ return { ok: true, id: input };
482
+ if (Object.hasOwn(removedOrders, input))
483
+ return { ok: false, reason: 'removed', candidates: [] };
484
+ const hits = input ? Object.keys(orders).filter((id) => id.startsWith(input)) : [];
485
+ if (hits.length === 1)
486
+ return { ok: true, id: hits[0] };
487
+ return { ok: false, reason: hits.length > 1 ? 'ambiguous' : 'unknown', candidates: hits.sort() };
488
+ }
489
+ export function getOrderDetail(results, id) {
490
+ const s = results.snapshot;
491
+ const order = s.orders[id];
492
+ if (!order)
493
+ return undefined;
494
+ const { refs, firstReport } = results.orderRefs.get(id) ?? { refs: [], firstReport: [] };
495
+ return {
496
+ order,
497
+ workers: Object.values(s.workers).filter((w) => w.orderId === id),
498
+ reports: (s.reports[id] ?? []).map((r, i) => ({ ...r, index: i + 1 })),
499
+ gates: Object.values(s.gates)
500
+ .filter((g) => g.orderId === id)
501
+ .sort((a, b) => a.openedAt.localeCompare(b.openedAt)),
502
+ bypasses: s.bypasses.filter((b) => b.orderId === id),
503
+ refs: refs.map((r, i) => ({ ...r, index: i + 1, firstReport: firstReport[i] ?? 0 })),
504
+ related: relatedFiles(results, id),
505
+ };
506
+ }
507
+ const EXCERPT_RADIUS = 80;
508
+ /** 파일 하나에서 내는 결과 수 상한. 한 파일이 결과를 다 차지하지 않게 한다 */
509
+ const MAX_HITS_PER_FILE = 3;
510
+ function escapeRegExp(s) {
511
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
512
+ }
513
+ /**
514
+ * 맞은 자리 앞뒤로 잘라 한 줄로 만든다. 개행과 제어 문자는 공백으로 바꾼다.
515
+ * 대소문자를 무시하는 정규식으로 원문 위치를 그대로 잡는다. toLowerCase는 길이가 바뀌는 글자가 있어 위치가 어긋난다.
516
+ */
517
+ export function excerpt(text, re, radius = EXCERPT_RADIUS) {
518
+ re.lastIndex = 0;
519
+ const m = re.exec(text);
520
+ if (!m)
521
+ return null;
522
+ return excerptAt(text, m.index, m[0].length, radius);
523
+ }
524
+ function excerptAt(text, index, length, radius) {
525
+ const start = Math.max(0, index - radius);
526
+ const end = Math.min(text.length, index + length + radius);
527
+ const head = start > 0 ? '…' : '';
528
+ const tail = end < text.length ? '…' : '';
529
+ const before = head + flat(text.slice(start, index));
530
+ return {
531
+ excerpt: before +
532
+ flat(text.slice(index, index + length)) +
533
+ flat(text.slice(index + length, end)) +
534
+ tail,
535
+ matchStart: before.length,
536
+ matchLength: length,
537
+ };
538
+ }
539
+ function flat(s) {
540
+ let out = '';
541
+ for (const ch of s)
542
+ out += isControlChar(ch.codePointAt(0)) ? ' ' : ch;
543
+ return out;
544
+ }
545
+ function addHit(sink, make) {
546
+ sink.total++;
547
+ if (sink.hits.length >= sink.limit)
548
+ return undefined;
549
+ const hit = make();
550
+ sink.hits.push(hit);
551
+ return hit;
552
+ }
553
+ /** 읽은 범위 안에서 맞은 줄을 다 센다. 결과는 파일당 앞 MAX_HITS_PER_FILE건만 만든다 */
554
+ function bodyHits(sink, path, body, re, base) {
555
+ // 0건이어도 뒷부분에 있을 수 있다고 알려야 해서 맞았는지와 무관하게 센다
556
+ if (body.truncated)
557
+ sink.partialPaths.add(path);
558
+ // 본문 전체에서 안 맞으면 어느 줄에서도 안 맞는다. 큰 본문을 줄로 쪼개지 않고 끝낸다
559
+ // re는 g, y 플래그 없이 만들어 lastIndex가 test 결과에 영향을 주지 않는다
560
+ if (!re.test(body.text))
561
+ return 0;
562
+ const lines = body.text.split('\n');
563
+ const extra = body.truncated ? { partial: true } : {};
564
+ let matched = 0;
565
+ let last;
566
+ let made = 0;
567
+ for (let i = 0; i < lines.length; i++) {
568
+ const line = lines[i];
569
+ re.lastIndex = 0;
570
+ const m = re.exec(line);
571
+ if (!m)
572
+ continue;
573
+ matched++;
574
+ if (matched > MAX_HITS_PER_FILE) {
575
+ sink.total++;
576
+ continue;
577
+ }
578
+ const hit = addHit(sink, () => ({
579
+ ...base,
580
+ ...extra,
581
+ line: i + 1,
582
+ ...excerptAt(line, m.index, m[0].length, EXCERPT_RADIUS),
583
+ }));
584
+ if (hit) {
585
+ last = hit;
586
+ made++;
587
+ }
588
+ }
589
+ if (last && matched > made)
590
+ last.moreInFile = matched - made;
591
+ return matched;
592
+ }
593
+ /**
594
+ * 제목과 보고 요약, 읽을 수 있는 refs 본문, 저장소 파일에서 찾는다. 대소문자는 무시한다.
595
+ * 결과는 주문 갱신순이고 한 주문 안에서는 제목, 요약(최근 보고 먼저), refs, 관련 파일 순이다. 주문 없음 파일은 끝에 온다.
596
+ * total은 맞은 건수 전부다. 파일당 상한과 limit에 걸려 결과로 안 만든 것도 센다.
597
+ */
598
+ export function searchResults(results, query, opts = {}) {
599
+ const q = query.trim();
600
+ if (!q)
601
+ return { query: q, total: 0, hits: [] };
602
+ const re = new RegExp(escapeRegExp(q), 'iu');
603
+ // 줄 단위로 찾으니 개행이 든 검색어는 본문에서 맞을 수 없다. 제목과 요약만 찾는다
604
+ const body = opts.body !== false && !q.includes('\n');
605
+ const sink = {
606
+ hits: [],
607
+ total: 0,
608
+ limit: opts.limit ?? Infinity,
609
+ partialPaths: new Set(),
610
+ };
611
+ for (const o of filteredOrders(results, opts)) {
612
+ const head = { orderId: o.id, title: o.title, repo: o.repo };
613
+ const t = excerpt(o.title, re);
614
+ if (t)
615
+ addHit(sink, () => ({ ...head, at: o.updatedAt, source: 'title', where: 'title', ...t }));
616
+ const reports = results.snapshot.reports[o.id] ?? [];
617
+ for (let i = reports.length - 1; i >= 0; i--) {
618
+ const r = reports[i];
619
+ re.lastIndex = 0;
620
+ if (!re.test(r.summary))
621
+ continue;
622
+ addHit(sink, () => ({
623
+ ...head,
624
+ at: r.at,
625
+ source: 'summary',
626
+ where: 'summary',
627
+ reportIndex: i + 1,
628
+ ...excerpt(r.summary, re),
629
+ }));
630
+ }
631
+ if (!body)
632
+ continue;
633
+ const { refs, firstReport } = results.orderRefs.get(o.id) ?? { refs: [], firstReport: [] };
634
+ refs.forEach((ref, i) => {
635
+ const at = reports[(firstReport[i] ?? 1) - 1]?.at ?? o.updatedAt;
636
+ if (ref.kind === 'file') {
637
+ const b = loadedRefBody(results, ref);
638
+ if (b) {
639
+ bodyHits(sink, ref.path, b, re, {
640
+ ...head,
641
+ at,
642
+ source: 'ref',
643
+ where: ref.display,
644
+ refIndex: i + 1,
645
+ });
646
+ }
647
+ }
648
+ else if (ref.kind === 'dir') {
649
+ (ref.entries ?? []).forEach((entry, j) => {
650
+ const b = loadedRefBody(results, ref, j);
651
+ if (!b)
652
+ return;
653
+ bodyHits(sink, entry.path, b, re, {
654
+ ...head,
655
+ at,
656
+ source: 'ref',
657
+ where: `${ref.display.replace(/\/+$/, '')}/${entry.name}`,
658
+ refIndex: i + 1,
659
+ entryIndex: j,
660
+ });
661
+ });
662
+ }
663
+ });
664
+ for (const f of relatedFiles(results, o.id))
665
+ fileHits(sink, results, f, re, head);
666
+ }
667
+ // 주문 없는 파일에는 레포나 상태, 지라 키가 없다. 그중 하나라도 필터를 걸었으면 뺀다
668
+ if (body && !opts.repo && !opts.status && !opts.issueKey) {
669
+ const since = opts.since ? parseSince(opts.since) : undefined;
670
+ for (const f of results.files) {
671
+ if (f.orderId)
672
+ continue;
673
+ if (since !== undefined && Date.parse(f.mtime) < since)
674
+ continue;
675
+ fileHits(sink, results, f, re, { orderId: null, title: f.rel, repo: null });
676
+ }
677
+ }
678
+ return {
679
+ query: q,
680
+ total: sink.total,
681
+ hits: sink.hits,
682
+ ...(sink.partialPaths.size > 0 ? { partialFiles: sink.partialPaths.size } : {}),
683
+ };
684
+ }
685
+ function fileHits(sink, results, f, re, head) {
686
+ const b = readResultFile(results, f.key, { cache: false });
687
+ const base = {
688
+ ...head,
689
+ at: f.mtime,
690
+ source: 'file',
691
+ where: f.rel,
692
+ fileKey: f.key,
693
+ absPath: f.path,
694
+ };
695
+ const matched = b ? bodyHits(sink, f.path, b, re, base) : 0;
696
+ if (matched > 0)
697
+ return;
698
+ // 본문에 없고 이름에만 있으면 이름으로 한 건 낸다
699
+ const name = excerpt(basename(f.rel), re);
700
+ if (name)
701
+ addHit(sink, () => ({ ...base, ...name }));
702
+ }
703
+ //# sourceMappingURL=results.js.map