@tienne/gestalt 0.136.1 → 0.137.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 (37) 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 +7 -3
  4. package/dist/src/cli/commands/conductor.d.ts +7 -0
  5. package/dist/src/cli/commands/conductor.d.ts.map +1 -1
  6. package/dist/src/cli/commands/conductor.js +91 -21
  7. package/dist/src/cli/commands/conductor.js.map +1 -1
  8. package/dist/src/cli/index.d.ts.map +1 -1
  9. package/dist/src/cli/index.js +10 -1
  10. package/dist/src/cli/index.js.map +1 -1
  11. package/dist/src/conductor/engine.d.ts +26 -1
  12. package/dist/src/conductor/engine.d.ts.map +1 -1
  13. package/dist/src/conductor/engine.js +82 -8
  14. package/dist/src/conductor/engine.js.map +1 -1
  15. package/dist/src/conductor/intake.d.ts +10 -2
  16. package/dist/src/conductor/intake.d.ts.map +1 -1
  17. package/dist/src/conductor/intake.js +11 -8
  18. package/dist/src/conductor/intake.js.map +1 -1
  19. package/dist/src/conductor/launcher.d.ts +107 -8
  20. package/dist/src/conductor/launcher.d.ts.map +1 -1
  21. package/dist/src/conductor/launcher.js +574 -51
  22. package/dist/src/conductor/launcher.js.map +1 -1
  23. package/dist/src/conductor/parent-worktree.d.ts +1 -1
  24. package/dist/src/conductor/parent-worktree.d.ts.map +1 -1
  25. package/dist/src/conductor/parent-worktree.js.map +1 -1
  26. package/dist/src/conductor/store.d.ts +7 -0
  27. package/dist/src/conductor/store.d.ts.map +1 -1
  28. package/dist/src/conductor/store.js +96 -2
  29. package/dist/src/conductor/store.js.map +1 -1
  30. package/dist/src/conductor/types.d.ts +32 -0
  31. package/dist/src/conductor/types.d.ts.map +1 -1
  32. package/dist/src/conductor/types.js.map +1 -1
  33. package/package.json +1 -1
  34. package/plugin/.codex-plugin/plugin.json +1 -1
  35. package/plugin/.mcp.json +1 -1
  36. package/plugin/mcp.json +1 -1
  37. package/plugin/skills/conductor/SKILL.md +7 -3
@@ -3,9 +3,10 @@ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
3
  import { basename, delimiter, isAbsolute, join, relative, sep } from 'node:path';
4
4
  import { isAccountName } from './account-name.js';
5
5
  import { handleNeed, openOrReuse } from './gates.js';
6
- import { oneLine } from './intake.js';
6
+ import { ISSUE_KEY_RE, isRefName, oneLine } from './intake.js';
7
7
  import { RESUME_MARKER } from './metrics.js';
8
8
  import { real, worktreeField } from './parent-worktree.js';
9
+ import { normalizePrRef } from './pr-ref.js';
9
10
  import { ACTIVE_WORKER_STATUSES, } from './types.js';
10
11
  import { TEXT_TAIL_CHARS, tailOfStrings, usageLimitIn, usageLimitInText, } from './usage-limit.js';
11
12
  /**
@@ -54,7 +55,8 @@ export function workerAt(cwd, workers) {
54
55
  return false;
55
56
  });
56
57
  }
57
- function orcaWorktreeName(w) {
58
+ /** 오르카 워커의 워크트리 디렉토리 이름. worker-start의 `--name`으로 넘긴 값이 그대로 디렉토리 이름이 된다 */
59
+ export function orcaWorktreeName(w) {
58
60
  return `${w.orderId}-${w.attempt}`;
59
61
  }
60
62
  /** 멈춘 호출 하나가 tick 잠금을 쥔 채 남지 않게 끊는 기본 시간 */
@@ -207,6 +209,243 @@ function tidyBlock(text) {
207
209
  }
208
210
  return out.replace(/\n{3,}/g, '\n\n').trim();
209
211
  }
212
+ /** 버그 주문은 fix, 나머지는 이슈 타입이 없을 때까지 포함해 feat 브랜치로 띄운다 */
213
+ export function branchPrefixFor(issueType) {
214
+ return issueType === 'bug' || issueType === 'sub-bug' ? 'fix' : 'feat';
215
+ }
216
+ /**
217
+ * 지라 주문이 새로 만들 브랜치 이름. 지라 키가 없으면 undefined라 런처 기본 이름을 쓴다.
218
+ * PR이 붙은 주문은 그 PR 브랜치에서 일하므로 새 브랜치를 만들지 않는다
219
+ */
220
+ export function issueBranchName(order) {
221
+ if (!order.issueKey || order.prRef || !ISSUE_KEY_RE.test(order.issueKey))
222
+ return undefined;
223
+ return `${branchPrefixFor(order.issueType)}/${order.issueKey}`;
224
+ }
225
+ /** 오르카 워크트리에 붙일 참조. 지라 키가 있을 때만 붙이고 PR이 있으면 PR 주소도 같이 붙인다 */
226
+ export function worktreeReferences(order) {
227
+ if (!order.issueKey || !ISSUE_KEY_RE.test(order.issueKey))
228
+ return [];
229
+ const pr = order.prRef ? prUrlOf(order.prRef) : undefined;
230
+ return [order.issueKey, ...(pr ? [pr] : [])];
231
+ }
232
+ /** `owner/name#번호`를 GitHub PR 주소로 바꾼다 */
233
+ export function prUrlOf(prRef) {
234
+ const n = normalizePrRef(prRef);
235
+ if (!n)
236
+ return undefined;
237
+ const at = n.indexOf('#');
238
+ return `https://github.com/${n.slice(0, at)}/pull/${n.slice(at + 1)}`;
239
+ }
240
+ const MAX_BRANCH_SUFFIX = 20;
241
+ // ls-remote는 네트워크를 기다리고 나머지 git 명령은 로컬만 읽어서 따로 조정할 수 있게 나눠 둔다.
242
+ // ssh 연결 자체는 lsRemoteEnv의 ConnectTimeout=10이 먼저 끊는다
243
+ const LS_REMOTE_TIMEOUT_MS = 30_000;
244
+ const GIT_TIMEOUT_MS = 30_000;
245
+ /** `refs/heads/<이름>` 줄을 브랜치 이름 집합으로 읽는다. ls-remote 줄은 앞의 커밋 해시를 버린다 */
246
+ function headsOf(out) {
247
+ const names = new Set();
248
+ for (const line of out.split('\n')) {
249
+ const ref = line.trim().split(/\s+/).at(-1) ?? '';
250
+ if (ref.startsWith('refs/heads/'))
251
+ names.add(ref.slice('refs/heads/'.length));
252
+ }
253
+ return names;
254
+ }
255
+ /**
256
+ * base와 base-N 꼴의 로컬 브랜치를 한 번에 읽는다. 패턴은 base 뒤에 다른 글자가 붙은 이름도 걸리므로
257
+ * 쓰는 쪽에서 이름을 정확히 비교한다
258
+ */
259
+ async function localHeads(runner, gitDir, base) {
260
+ const r = await runner('git', [
261
+ '-C',
262
+ gitDir,
263
+ 'for-each-ref',
264
+ '--format=%(refname)',
265
+ `refs/heads/${base}`,
266
+ `refs/heads/${base}-*`,
267
+ ], { timeoutMs: GIT_TIMEOUT_MS });
268
+ if (r.code !== 0)
269
+ throw new Error(`${gitDir}의 로컬 브랜치를 못 읽었어요: ${outputHead(r)}`);
270
+ return headsOf(r.stdout);
271
+ }
272
+ /**
273
+ * ls-remote에 붙일 환경 변수. 사용자가 ssh 명령을 따로 정해 두지 않았을 때만 BatchMode를 건다.
274
+ * 호스트 키 확인이나 암호 입력을 기다리다 시간 제한까지 멈추지 않게 하려는 것이다.
275
+ * GIT_SSH_COMMAND는 core.sshCommand보다 우선해서 사용자가 정해 둔 ssh 명령(회사용 키 등)을 덮지 않으려고
276
+ * 설정부터 읽는다. remoteHeads 캐시 덕에 레포당 tick 한 번만 돈다
277
+ */
278
+ async function lsRemoteEnv(runner, gitDir) {
279
+ const env = { GIT_TERMINAL_PROMPT: '0' };
280
+ if (process.env['GIT_SSH_COMMAND'])
281
+ return env;
282
+ const configured = await runner('git', ['-C', gitDir, 'config', '--get', 'core.sshCommand'], {
283
+ timeoutMs: GIT_TIMEOUT_MS,
284
+ }).catch(() => undefined);
285
+ if (configured?.code === 0 && configured.stdout.trim())
286
+ return env;
287
+ return { ...env, GIT_SSH_COMMAND: 'ssh -o BatchMode=yes -o ConnectTimeout=10' };
288
+ }
289
+ /**
290
+ * origin의 브랜치 목록. origin이 없는 레포는 빈 목록이고 경고도 없다. 원격을 못 읽으면 경고를 돌려준다.
291
+ * 성공이든 실패든 tick 캐시에 담는다
292
+ */
293
+ async function remoteHeads(runner, gitDir, cache) {
294
+ const seen = cache?.get(gitDir);
295
+ if (seen)
296
+ return seen;
297
+ const key = cache ? await repoKey(runner, gitDir) : gitDir;
298
+ const hit = cache?.get(key);
299
+ if (hit) {
300
+ cache.set(gitDir, hit);
301
+ return hit;
302
+ }
303
+ const remotes = await runner('git', ['-C', gitDir, 'remote'], { timeoutMs: GIT_TIMEOUT_MS });
304
+ if (remotes.code !== 0)
305
+ throw new Error(`${gitDir}의 원격 목록을 못 읽었어요: ${outputHead(remotes)}`);
306
+ let result = { names: new Set() };
307
+ if (remotes.stdout.split('\n').some((l) => l.trim() === 'origin')) {
308
+ // 패턴 없이 전체를 받는다. 한 tick 안에서 base가 다른 주문끼리 이 결과를 같이 쓴다
309
+ const r = await runner('git', ['-C', gitDir, 'ls-remote', '--heads', 'origin'], {
310
+ env: await lsRemoteEnv(runner, gitDir),
311
+ timeoutMs: LS_REMOTE_TIMEOUT_MS,
312
+ });
313
+ result =
314
+ r.code === 0
315
+ ? { names: headsOf(r.stdout) }
316
+ : { names: new Set(), warning: outputHead(r) };
317
+ }
318
+ cache?.set(key, result);
319
+ cache?.set(gitDir, result);
320
+ return result;
321
+ }
322
+ /** 같은 레포의 워크트리끼리 같은 값을 내는 캐시 키. git common dir을 못 읽으면 gitDir를 그대로 쓴다 */
323
+ async function repoKey(runner, gitDir) {
324
+ const r = await runner('git', ['-C', gitDir, 'rev-parse', '--path-format=absolute', '--git-common-dir'], { timeoutMs: GIT_TIMEOUT_MS }).catch(() => undefined);
325
+ const dir = r?.code === 0 ? r.stdout.trim() : '';
326
+ return dir ? real(dir) : gitDir;
327
+ }
328
+ /**
329
+ * 워커 기록에서 온 앞 브랜치를 git과 오르카 인자로 넘기기 전에 이름 꼴을 본다. 꼴이 틀리면 새 브랜치로
330
+ * 넘어가지 않고 멈춘다. 새로 갈라 띄우면 앞 워커 커밋을 말없이 두고 가게 된다
331
+ */
332
+ function assertResumableBranch(branch) {
333
+ if (!isRefName(branch))
334
+ throw new Error(`앞 워커가 기록한 브랜치 값이 브랜치 이름으로 쓸 수 없는 꼴이라 이어받지 못했어요: ${oneLine(branch, 120)}`);
335
+ }
336
+ /** 워크트리가 체크아웃한 브랜치. detach됐거나 못 읽으면 undefined */
337
+ async function currentBranch(runner, path) {
338
+ const r = await runner('git', ['-C', path, 'branch', '--show-current'], {
339
+ timeoutMs: GIT_TIMEOUT_MS,
340
+ }).catch(() => undefined);
341
+ const name = r?.code === 0 ? r.stdout.trim() : '';
342
+ return name && isRefName(name) ? name : undefined;
343
+ }
344
+ /** 로컬에 그 이름의 브랜치가 정확히 있는지 본다 */
345
+ export async function hasLocalBranch(runner, gitDir, branch) {
346
+ return (await localHeads(runner, gitDir, branch)).has(branch);
347
+ }
348
+ /**
349
+ * 브랜치 기록이 없는 옛 워커를 재개할 때 기본 이름이 로컬에 있으면 경고를 남기고 그 이름을 돌려준다.
350
+ * 사람이 같은 이름으로 만든 브랜치일 수도 있어서 확인을 부탁한다. 없으면 읽어 둔 로컬 목록을 돌려줘
351
+ * pickFreeBranch가 다시 읽지 않게 한다
352
+ */
353
+ async function adoptPlannedIfPresent(runner, gitDir, planned, orderId, warnings) {
354
+ const local = await localHeads(runner, gitDir, planned);
355
+ if (!local.has(planned))
356
+ return { local };
357
+ warnings.push(`${orderId}: 브랜치 기록이 없는 옛 워커라 기본 이름 ${planned}를 이어받았어요. 앞 워커가 만든 브랜치가 아닐 수 있으니 확인해 주세요`);
358
+ return { name: planned, local };
359
+ }
360
+ /**
361
+ * 옛 워커의 앞 워크트리가 체크아웃한 브랜치가 이 주문 몫인지 본다. 기본 이름과 그 접미사, 예전 이름
362
+ * `conductor/<주문 id>`, 오르카가 워크트리 이름으로 지은 브랜치(`<사용자>/<주문 id>-<시도>`)만 인정한다
363
+ */
364
+ function isOwnBranch(held, planned, orderId, worktreeName) {
365
+ if (held === planned || held === `conductor/${orderId}`)
366
+ return true;
367
+ const suffix = held.startsWith(`${planned}-`) ? held.slice(planned.length + 1) : '';
368
+ if (/^[1-9]\d*$/.test(suffix) && Number(suffix) >= 2 && Number(suffix) <= MAX_BRANCH_SUFFIX)
369
+ return true;
370
+ return held.split('/').at(-1) === worktreeName;
371
+ }
372
+ /** origin의 기본 브랜치. `origin/HEAD`가 없으면 main과 master를 기본으로 본다 */
373
+ async function defaultBranches(runner, dir) {
374
+ const r = await runner('git', ['-C', dir, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {
375
+ timeoutMs: GIT_TIMEOUT_MS,
376
+ }).catch(() => undefined);
377
+ const ref = r?.code === 0 ? r.stdout.trim() : '';
378
+ return ref.startsWith('origin/') ? [ref.slice('origin/'.length)] : ['main', 'master'];
379
+ }
380
+ /** 기준 브랜치나 레포 기본 브랜치인지 본다. 워커가 이런 브랜치를 이어받아 커밋하면 안 된다 */
381
+ async function isProtectedBranch(runner, dir, branch, order) {
382
+ return branch === order.baseBranch || (await defaultBranches(runner, dir)).includes(branch);
383
+ }
384
+ /** 기록된 앞 브랜치가 기준 브랜치나 기본 브랜치면 이어받지 않고 멈춘다 */
385
+ async function assertNotProtected(runner, dir, branch, order) {
386
+ if (await isProtectedBranch(runner, dir, branch, order))
387
+ throw new Error(`앞 워커가 기록한 브랜치 ${branch}가 기준 브랜치나 레포 기본 브랜치라 이어받지 않았어요. 워커 기록을 확인해 주세요`);
388
+ }
389
+ /** 실패를 예외 대신 code 1 결과로 받는다. 실패해도 경고만 남기고 이어 가는 자리에서 쓴다 */
390
+ function runSoft(runner, cmd, args, opts) {
391
+ return runner(cmd, args, opts).catch((err) => ({
392
+ code: 1,
393
+ stdout: '',
394
+ stderr: err.message,
395
+ }));
396
+ }
397
+ /**
398
+ * 처음 띄울 때 쓸 브랜치 이름을 고른다. 로컬이나 origin에 이미 있으면 `-2`, `-3`을 붙여 빈 이름을 찾는다.
399
+ * 사람이 손으로 만든 브랜치나 예전 주문이 남긴 브랜치 위에 얹지 않으려는 것이다.
400
+ * origin을 못 읽으면 로컬만 보고 고른 뒤 경고를 남긴다. 이미 읽은 base 패턴의 로컬 목록이 있으면 넘겨받는다
401
+ */
402
+ export async function pickFreeBranch(runner, gitDir, base, cache, knownLocal) {
403
+ const [local, remote] = await Promise.all([
404
+ knownLocal ?? localHeads(runner, gitDir, base),
405
+ remoteHeads(runner, gitDir, cache),
406
+ ]);
407
+ for (let n = 1; n <= MAX_BRANCH_SUFFIX; n++) {
408
+ const branch = n === 1 ? base : `${base}-${n}`;
409
+ if (local.has(branch) || remote.names.has(branch))
410
+ continue;
411
+ const warnings = remote.warning
412
+ ? [`origin을 못 읽어 ${branch}가 원격에 있는지 확인 못 하고 띄웠어요: ${remote.warning}`]
413
+ : [];
414
+ return { branch, warnings };
415
+ }
416
+ throw new Error(`${base}부터 ${base}-${MAX_BRANCH_SUFFIX}까지 브랜치가 다 있어요. 남은 브랜치를 정리해 주세요`);
417
+ }
418
+ /**
419
+ * `git worktree list --porcelain`에서 그 브랜치를 체크아웃한 워크트리를 찾는다. prunable은 디렉토리가
420
+ * 지워져 git 등록만 남은 워크트리다
421
+ */
422
+ function worktreeHolding(porcelain, branch) {
423
+ for (const block of porcelain.split(/\n\s*\n/)) {
424
+ const lines = block.split('\n');
425
+ const path = lines.find((l) => l.startsWith('worktree '))?.slice('worktree '.length);
426
+ if (path && lines.includes(`branch refs/heads/${branch}`))
427
+ return { path, prunable: lines.some((l) => l.startsWith('prunable')) };
428
+ }
429
+ return undefined;
430
+ }
431
+ /** 안내 문장에 넣는 명령 인자. 셸에 그대로 붙여 넣어도 안전한 글자만 있으면 그대로 두고 아니면 작은따옴표로 감싼다 */
432
+ function shellArg(value) {
433
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
434
+ }
435
+ /** 남은 워크트리를 지울 명령. 앞 워커가 쓰던 브랜치에 있는 워크트리는 브랜치를 남겨야 해서 deleteBranch를 끈다 */
436
+ function rmCommand(selector, deleteBranch) {
437
+ return `\`orca worktree rm --worktree ${shellArg(selector)}${deleteBranch ? ' --delete-branch' : ''}\``;
438
+ }
439
+ function leftoverHint(selector, deleteBranch) {
440
+ return `남은 워크트리는 ${rmCommand(selector, deleteBranch)}로 지워 주세요`;
441
+ }
442
+ /**
443
+ * 바깥 출처가 고른 기준 브랜치의 셋업 스크립트를 이 호스트에서 돌리지 않는다. 재개는 앞 워커가 커밋한
444
+ * 브랜치에서 만들어서 기준 브랜치가 없어도 같은 이유로 건너뛴다
445
+ */
446
+ function setupFlags(order, resume = false) {
447
+ return (order.baseBranch || resume) && order.source !== 'spoken' ? ['--setup', 'skip'] : [];
448
+ }
210
449
  function writePrompt(promptDir, workerId, prompt) {
211
450
  mkdirSync(promptDir, { recursive: true });
212
451
  const file = join(promptDir, `${workerId}.md`);
@@ -217,6 +456,11 @@ export class OrcaLauncher {
217
456
  opts;
218
457
  kind = 'orca-worktree';
219
458
  runner;
459
+ remoteHeads = new Map();
460
+ /** 레포 선택자별 로컬 경로. `orca repo show`를 주문마다 다시 묻지 않는다 */
461
+ repoDirs = new Map();
462
+ /** 오르카 워크트리 이름별 경로. 못 찾은 답도 담는다 */
463
+ worktreePaths = new Map();
220
464
  constructor(opts) {
221
465
  this.opts = opts;
222
466
  this.runner = opts.runner ?? execRunner;
@@ -226,15 +470,49 @@ export class OrcaLauncher {
226
470
  const name = orcaWorktreeName(spec.worker);
227
471
  const displayName = oneLine(spec.order.title, 60);
228
472
  const agent = spec.worker.agent ?? 'claude';
229
- return spec.order.parentWorktree
230
- ? this.startInChild(spec.order, file, name, displayName, agent)
231
- : this.startTopLevel(spec.order, file, name, displayName, agent);
473
+ const planned = issueBranchName(spec.order);
474
+ const refs = worktreeReferences(spec.order);
475
+ const warnings = [];
476
+ // PR이 붙은 주문은 PR 브랜치에서 일하므로 앞 브랜치를 이어받을 일이 없어 경고하지 않는다
477
+ if (!planned && spec.previousBranch !== undefined && !spec.order.prRef)
478
+ warnings.push(`${spec.order.id}: 지라 키가 없는 주문이라 앞 워커가 쓰던 브랜치 ${oneLine(spec.previousBranch, 120)}를 이어받지 않고 새 워크트리로 띄웠어요`);
479
+ // 부모 워크트리도 없고 브랜치 이름이나 참조를 붙일 일도 없으면 한 번에 띄우던 길을 그대로 둔다.
480
+ // 지라 키가 없는 PR 감시 주문이 여기로 온다
481
+ if (!spec.order.parentWorktree && !planned && refs.length === 0) {
482
+ const handle = await this.startTopLevel(spec.order, file, name, displayName, agent);
483
+ return { handle, ...(warnings.length ? { warnings } : {}) };
484
+ }
485
+ const branch = planned ? await this.planBranch(spec, planned, warnings) : undefined;
486
+ const created = await this.createWorktree(spec.order, name, displayName, branch);
487
+ const resume = branch?.resume === true;
488
+ let used = created.branch ?? branch?.name;
489
+ let detached;
490
+ if (resume) {
491
+ detached = await this.adoptBranch(spec, created, branch.name);
492
+ used = branch.name;
493
+ const warning = await this.dropTempBranch(spec, created, branch.name);
494
+ if (warning)
495
+ warnings.push(warning);
496
+ }
497
+ else if (branch && !created.branch) {
498
+ warnings.push(`${spec.order.id}: 오르카가 실제 브랜치를 안 알려 줘 계획한 이름 ${branch.name}를 기록했어요`);
499
+ }
500
+ // 같은 워크트리 메타데이터에 오르카가 동시에 쓰지 않도록 하나씩 붙인다. 참조는 많아야 두 개다
501
+ for (const ref of refs) {
502
+ const warning = await this.attachReference(spec.order, created.selector, ref);
503
+ if (warning)
504
+ warnings.push(warning);
505
+ }
506
+ // 재개면 새 워크트리가 앞 브랜치에 있다. 브랜치째 지우면 앞 워커가 쌓은 커밋을 잃는다.
507
+ // 새 워크트리를 지웠으면 브랜치가 풀리니 detach해 둔 앞 워크트리를 다시 그 브랜치로 돌린다
508
+ const handle = await this.startInWorktree(created.selector, file, agent, !resume, detached && branch ? () => this.restoreHolder(detached, branch.name) : undefined);
509
+ return {
510
+ handle,
511
+ ...(used ? { branch: used } : {}),
512
+ ...(warnings.length ? { warnings } : {}),
513
+ };
232
514
  }
233
515
  async startTopLevel(order, file, name, displayName, agent) {
234
- const path = this.opts.repoPaths?.[order.repo];
235
- const repo = path ? `path:${path}` : `name:${order.repo.split('/')[1]}`;
236
- // 바깥 출처가 고른 기준 브랜치의 셋업 스크립트를 이 호스트에서 돌리지 않는다
237
- const setup = order.baseBranch && order.source !== 'spoken' ? ['--setup', 'skip'] : [];
238
516
  const out = await mustRun(this.runner, this.opts.orcaCommand, [
239
517
  'orchestration',
240
518
  'worker-start',
@@ -245,25 +523,95 @@ export class OrcaLauncher {
245
523
  '--agent',
246
524
  agent,
247
525
  '--repo',
248
- repo,
526
+ this.repoSelector(order),
249
527
  ...(order.baseBranch ? ['--base-branch', order.baseBranch] : []),
250
- ...setup,
528
+ ...setupFlags(order),
251
529
  '--name',
252
530
  name,
253
531
  '--display-name',
254
532
  displayName,
255
533
  '--json',
256
534
  ], { timeoutMs: ORCA_TIMEOUT_MS });
257
- return { handle: parseDispatchId(out) };
535
+ return parseDispatchId(out);
536
+ }
537
+ repoSelector(order) {
538
+ const path = this.opts.repoPaths?.[order.repo];
539
+ return path ? `path:${path}` : `name:${order.repo.split('/')[1]}`;
258
540
  }
259
541
  /**
260
- * 하위 워크트리를 만들고 거기에 워커를 띄운다.
542
+ * 지라 주문의 브랜치를 정한다. 재개면 앞 워커가 기록한 브랜치를 이어받는다. 브랜치 기록이 없는 옛 워커는
543
+ * 앞 워크트리가 체크아웃한 브랜치가 이 주문 몫이면 그걸 이어받고, 아니면 기본 이름(`feat/<키>`, `fix/<키>`)이
544
+ * 로컬에 있을 때 그걸 이어받으며 경고를 남긴다. 처음이면 로컬과 origin에서 비어 있는 이름을 고른다
545
+ */
546
+ async planBranch(spec, planned, warnings) {
547
+ if (spec.previousBranch !== undefined) {
548
+ assertResumableBranch(spec.previousBranch);
549
+ await assertNotProtected(this.runner, await this.gitDirOf(spec.order), spec.previousBranch, spec.order);
550
+ return { name: spec.previousBranch, resume: true };
551
+ }
552
+ let local;
553
+ if (spec.previousWorker) {
554
+ const held = await this.previousCheckout(spec.order, spec.previousWorker, planned, warnings);
555
+ if (held)
556
+ return { name: held, resume: true };
557
+ }
558
+ const gitDir = await this.gitDirOf(spec.order);
559
+ if (spec.previousWorker) {
560
+ const found = await adoptPlannedIfPresent(this.runner, gitDir, planned, spec.order.id, warnings);
561
+ if (found.name)
562
+ return { name: found.name, resume: true };
563
+ local = found.local;
564
+ }
565
+ const picked = await pickFreeBranch(this.runner, gitDir, planned, this.remoteHeads, local);
566
+ warnings.push(...picked.warnings.map((w) => `${spec.order.id}: ${w}`));
567
+ return { name: picked.branch, resume: false };
568
+ }
569
+ /**
570
+ * 옛 워커의 앞 워크트리가 체크아웃한 브랜치. 이 주문 몫이 아니면 이어받지 않는다. 기준 브랜치나 레포 기본
571
+ * 브랜치면 조용히 넘어가고 그 밖의 이름이면 경고를 남긴다. 워커가 남의 브랜치에 커밋하지 않게 하려는 것이다
572
+ */
573
+ async previousCheckout(order, previous, planned, warnings) {
574
+ const worktreeName = orcaWorktreeName(previous);
575
+ const path = await this.worktreePathOf(worktreeName);
576
+ const held = path ? await currentBranch(this.runner, path) : undefined;
577
+ if (!path || !held)
578
+ return undefined;
579
+ if (isOwnBranch(held, planned, order.id, worktreeName))
580
+ return held;
581
+ if (held === order.baseBranch || (await defaultBranches(this.runner, path)).includes(held))
582
+ return undefined;
583
+ warnings.push(`${order.id}: 앞 워크트리가 이 주문 몫이 아닌 브랜치 ${held}에 있어 이어받지 않았어요`);
584
+ return undefined;
585
+ }
586
+ /** 브랜치가 겹치는지 볼 로컬 git 디렉토리. 부모 워크트리나 repoPaths, 오르카에 등록된 레포 경로 순으로 본다 */
587
+ async gitDirOf(order) {
588
+ if (order.parentWorktree)
589
+ return order.parentWorktree;
590
+ const path = this.opts.repoPaths?.[order.repo];
591
+ if (path)
592
+ return path;
593
+ const selector = this.repoSelector(order);
594
+ const cached = this.repoDirs.get(selector);
595
+ if (cached)
596
+ return cached;
597
+ const out = await mustRun(this.runner, this.opts.orcaCommand, ['repo', 'show', '--repo', selector, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS });
598
+ const repo = resultOf(out)?.['repo'];
599
+ const found = typeof repo === 'object' && repo !== null
600
+ ? stringField(repo, 'path')
601
+ : undefined;
602
+ if (!found)
603
+ throw new Error(`오르카에서 ${order.repo}의 로컬 경로를 못 찾아 브랜치 이름을 못 골랐어요`);
604
+ this.repoDirs.set(selector, found);
605
+ return found;
606
+ }
607
+ /**
608
+ * 만든 워크트리에 워커를 띄운다.
261
609
  *
262
610
  * 띄우기가 실패하면 워커가 저장되지 않아 회차가 안 오르고 다음 시도가 같은 이름으로 다시 만든다.
263
611
  * 그래서 워커가 확실히 안 떴을 때만 만든 워크트리를 지운다. 떴는지 모르면 지우지 않고 남은 자리를 알린다
264
612
  */
265
- async startInChild(order, file, name, displayName, agent) {
266
- const worktree = await this.createChild(order, name, displayName);
613
+ async startInWorktree(worktree, file, agent, deleteBranch, afterRemove) {
614
+ const leftover = leftoverHint(worktree, deleteBranch);
267
615
  const r = await this.runner(this.opts.orcaCommand, [
268
616
  'orchestration',
269
617
  'worker-start',
@@ -275,10 +623,9 @@ export class OrcaLauncher {
275
623
  agent,
276
624
  '--json',
277
625
  ], { timeoutMs: ORCA_TIMEOUT_MS });
278
- const leftover = `남은 워크트리는 \`orca worktree rm --worktree ${worktree} --delete-branch\`로 지워 주세요`;
279
626
  if (r.code === 0) {
280
627
  try {
281
- return { handle: parseDispatchId(r.stdout) };
628
+ return parseDispatchId(r.stdout);
282
629
  }
283
630
  catch (err) {
284
631
  throw new Error(`${err.message}. 워커가 떴을 수 있어 워크트리를 그대로 뒀어요. ${leftover}`, { cause: err });
@@ -288,37 +635,48 @@ export class OrcaLauncher {
288
635
  const failure = `${this.opts.orcaCommand} orchestration worker-start 실패(${r.code}): ${head}`;
289
636
  if (!surelyNotStarted(r.stdout))
290
637
  throw new Error(`${failure}. 워커가 떴는지 몰라 워크트리를 그대로 뒀어요. ${leftover}`);
291
- const rm = await this.runner(this.opts.orcaCommand, ['worktree', 'rm', '--worktree', worktree, '--delete-branch', '--json'], { timeoutMs: ORCA_TIMEOUT_MS }).catch(() => undefined);
292
- if (rm?.code !== 0)
293
- throw new Error(`${failure}. 워크트리를 못 지웠어요. ${leftover}`);
294
- throw new Error(failure);
638
+ const rm = await runSoft(this.runner, this.opts.orcaCommand, [
639
+ 'worktree',
640
+ 'rm',
641
+ '--worktree',
642
+ worktree,
643
+ ...(deleteBranch ? ['--delete-branch'] : []),
644
+ '--json',
645
+ ], { timeoutMs: ORCA_TIMEOUT_MS });
646
+ if (rm.code !== 0)
647
+ throw new Error(`${failure}. 워크트리를 못 지웠어요(${outputHead(rm)}). ${leftover}`);
648
+ throw new Error(`${failure}${afterRemove ? await afterRemove() : ''}`);
295
649
  }
296
650
  /**
297
- * 부모 워크트리 아래 하위 워크트리를 만들고 오르카 워크트리 선택자를 돌려준다.
651
+ * 워커 워크트리를 만들고 오르카 워크트리 선택자를 돌려준다.
652
+ *
653
+ * 부모가 있으면 그 아래 하위 워크트리로 만든다. worker-start의 new-child는 호출한 쪽(컨덕터)
654
+ * 워크스페이스 아래에 붙어 임의 부모를 못 고른다. 그래서 `worktree create --parent-worktree`로 먼저
655
+ * 만들고 worker-start는 그 워크트리를 고른다. 레포는 부모 워크트리에서 읽는다. `path:` 레포 선택자는
656
+ * 메인 체크아웃만 받아서다.
298
657
  *
299
- * worker-start의 new-child는 호출한 쪽(컨덕터) 워크스페이스 아래에 붙어 임의 부모를 못 고른다.
300
- * 그래서 `worktree create --parent-worktree`로 먼저 만들고 worker-start는 그 워크트리를 고른다.
301
- * 레포는 부모 워크트리에서 읽는다. `path:` 레포 선택자는 메인 체크아웃만 받아서다
658
+ * 부모가 없으면 `--no-parent`를 붙인다. 안 붙이면 오르카가 컨덕터 워크트리를 부모로 잡는다
302
659
  */
303
- async createChild(order, name, displayName) {
304
- const parent = `path:${order.parentWorktree}`;
305
- const shown = await mustRun(this.runner, this.opts.orcaCommand, ['worktree', 'show', '--worktree', parent, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS });
306
- const repoId = worktreeField(shown, 'repoId');
307
- if (!repoId)
308
- throw new Error(`오르카에서 부모 워크트리 ${order.parentWorktree}를 못 찾았어요`);
309
- const leftover = `${order.parentWorktree} 아래 ${name} 워크트리가 생겼을 수 있어요. \`orca worktree show --worktree name:${name}\`로 확인하고 있으면 \`orca worktree rm --worktree name:${name} --delete-branch\`로 지워 주세요`;
660
+ async createWorktree(order, name, displayName, branch) {
661
+ const placement = order.parentWorktree
662
+ ? await this.childPlacement(order)
663
+ : ['--repo', this.repoSelector(order), '--no-parent'];
664
+ // 부모 없는 워크트리의 셋업 정책은 한 번에 띄우던 길과 같게 둔다. worker-start의 새 워크트리 기본값이 run이다
665
+ const skip = order.parentWorktree ? [] : setupFlags(order, branch?.resume === true);
666
+ const setup = skip.length ? skip : ['--setup', 'run'];
667
+ const where = order.parentWorktree ? `${order.parentWorktree} 아래 ` : '';
668
+ const leftover = `${where}${name} 워크트리가 생겼을 수 있어요. \`orca worktree show --worktree ${shellArg(`name:${name}`)}\`로 확인하고 있으면 ${rmCommand(`name:${name}`, true)}로 지워 주세요`;
669
+ // 재개는 앞 브랜치에서 갈라 만든 뒤 그 브랜치로 바꾼다. --branch는 이미 있는 이름이면 숫자를 붙여 새로 만든다
670
+ const base = branch?.resume ? branch.name : order.baseBranch;
310
671
  const created = await mustRun(this.runner, this.opts.orcaCommand, [
311
672
  'worktree',
312
673
  'create',
313
674
  '--name',
314
675
  name,
315
- '--repo',
316
- `id:${repoId}`,
317
- '--parent-worktree',
318
- parent,
319
- ...(order.baseBranch ? ['--base-branch', order.baseBranch] : []),
320
- '--setup',
321
- 'run',
676
+ ...placement,
677
+ ...(base ? ['--base-branch', base] : []),
678
+ ...(branch && !branch.resume ? ['--branch', branch.name] : []),
679
+ ...setup,
322
680
  '--json',
323
681
  ], { timeoutMs: ORCA_TIMEOUT_MS }).catch((err) => {
324
682
  // 실패하면 회차가 안 올라 다음 시도가 같은 이름으로 다시 만들다 부딪힌다
@@ -326,12 +684,132 @@ export class OrcaLauncher {
326
684
  });
327
685
  const id = worktreeField(created, 'id');
328
686
  const path = worktreeField(created, 'path');
329
- const worktree = id ? `id:${id}` : path ? `path:${path}` : undefined;
330
- if (!worktree)
687
+ const selector = id ? `id:${id}` : path ? `path:${path}` : undefined;
688
+ if (!selector)
331
689
  throw new Error(`오르카 worktree create 응답에 워크트리 id와 경로가 없어요. ${leftover}`);
690
+ // 응답에 브랜치가 없으면 계획한 이름 대신 실제 체크아웃을 읽는다. --branch는 이름이 겹치면 숫자를 붙인다
691
+ const reported = worktreeField(created, 'branch')?.replace(/^refs\/heads\//, '');
692
+ const createdBranch = reported && isRefName(reported)
693
+ ? reported
694
+ : path
695
+ ? await currentBranch(this.runner, path)
696
+ : undefined;
332
697
  // 표시 이름은 보기 좋으라고 붙이는 것이라 실패해도 워커는 띄운다
333
- await this.runner(this.opts.orcaCommand, ['worktree', 'set', '--worktree', worktree, '--display-name', displayName, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS }).catch(() => undefined);
334
- return worktree;
698
+ await this.runner(this.opts.orcaCommand, ['worktree', 'set', '--worktree', selector, '--display-name', displayName, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS }).catch(() => undefined);
699
+ return {
700
+ selector,
701
+ ...(path ? { path } : {}),
702
+ ...(createdBranch ? { branch: createdBranch } : {}),
703
+ };
704
+ }
705
+ async childPlacement(order) {
706
+ const parent = `path:${order.parentWorktree}`;
707
+ const shown = await mustRun(this.runner, this.opts.orcaCommand, ['worktree', 'show', '--worktree', parent, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS });
708
+ const repoId = worktreeField(shown, 'repoId');
709
+ if (!repoId)
710
+ throw new Error(`오르카에서 부모 워크트리 ${order.parentWorktree}를 못 찾았어요`);
711
+ return ['--repo', `id:${repoId}`, '--parent-worktree', parent];
712
+ }
713
+ /**
714
+ * 재개로 만든 워크트리를 앞 워커의 브랜치로 바꾼다. detach한 앞 워크트리 경로를 돌려준다.
715
+ *
716
+ * 앞 워크트리는 재개해도 지우지 않아 그 브랜치를 체크아웃한 채로 남아 있다. git은 한 브랜치를 두
717
+ * 워크트리에 체크아웃하지 못하게 막으니 앞 워크트리를 그 자리 커밋에서 detach해 브랜치 체크아웃을
718
+ * 해제한다. detach는 커밋 안 한 변경을 그대로 두고 커밋은 브랜치에 남는다. 새 워크트리는 그 브랜치에서
719
+ * 갈라 만들어 같은 커밋이라 바로 바꿀 수 있다. 바꾸다 실패하면 detach한 앞 워크트리를 다시 그 브랜치로
720
+ * 돌려 둔다
721
+ */
722
+ async adoptBranch(spec, created, branch) {
723
+ // 여기서 실패하면 새 워크트리는 아직 오르카 임시 브랜치에 있다. 그 브랜치를 알 때만 브랜치째 지우게 안내한다
724
+ const leftover = leftoverHint(created.selector, created.branch !== undefined && created.branch !== branch);
725
+ const fail = (why, cause) => new Error(`앞 워커가 쓰던 브랜치 ${branch}를 새 워크트리에 못 붙였어요: ${why}. ${leftover}`, {
726
+ cause,
727
+ });
728
+ if (!created.path)
729
+ throw fail('오르카 응답에 새 워크트리 경로가 없어요');
730
+ let detached;
731
+ try {
732
+ detached = await this.releaseBranchFromPrevious(spec, created.path, branch);
733
+ await mustRun(this.runner, 'git', ['-C', created.path, 'switch', branch], {
734
+ timeoutMs: GIT_TIMEOUT_MS,
735
+ });
736
+ }
737
+ catch (err) {
738
+ const restored = detached ? await this.restoreHolder(detached, branch) : '';
739
+ throw fail(`${err.message}${restored}`, err);
740
+ }
741
+ return detached;
742
+ }
743
+ /**
744
+ * 앞 브랜치를 체크아웃한 워크트리에서 브랜치를 풀어 준다. detach했으면 그 경로를 돌려준다.
745
+ *
746
+ * 그 워크트리가 앞 워커의 워크트리가 아니면(사람이 쓰는 메인 체크아웃 등) 건드리지 않고 멈춘다.
747
+ * 디렉토리만 지워진 앞 워크트리는 등록만 지운다. 레포 전체 prune은 다른 워크트리 등록까지 지워서 쓰지 않는다
748
+ */
749
+ async releaseBranchFromPrevious(spec, path, branch) {
750
+ const listed = await mustRun(this.runner, 'git', ['-C', path, 'worktree', 'list', '--porcelain'], { timeoutMs: GIT_TIMEOUT_MS });
751
+ const holder = worktreeHolding(listed, branch);
752
+ if (!holder || real(holder.path) === real(path))
753
+ return undefined;
754
+ const previous = spec.previousWorker
755
+ ? await this.worktreePathOf(orcaWorktreeName(spec.previousWorker))
756
+ : undefined;
757
+ if (!previous || real(previous) !== real(holder.path))
758
+ throw new Error(`앞 브랜치를 앞 워커가 아닌 워크트리(${holder.path})가 체크아웃하고 있어요`);
759
+ if (holder.prunable) {
760
+ // prunable은 git이 디렉토리를 못 찾았다는 뜻이다. 그사이 디렉토리가 다시 보이면 --force가 안의 변경까지 지운다
761
+ if (existsSync(holder.path))
762
+ throw new Error(`앞 워크트리 ${holder.path}가 git에는 prunable로 나오는데 디렉토리가 남아 있어 지우지 않았어요. 안의 변경을 확인하고 정리해 주세요`);
763
+ await mustRun(this.runner, 'git', ['-C', path, 'worktree', 'remove', '--force', holder.path], {
764
+ timeoutMs: GIT_TIMEOUT_MS,
765
+ });
766
+ return undefined;
767
+ }
768
+ await mustRun(this.runner, 'git', ['-C', holder.path, 'switch', '--detach'], {
769
+ timeoutMs: GIT_TIMEOUT_MS,
770
+ });
771
+ return holder.path;
772
+ }
773
+ /** 오르카가 재개 워크트리를 만들며 붙인 임시 브랜치를 지운다. 못 지우면 경고만 돌려준다 */
774
+ async dropTempBranch(spec, created, branch) {
775
+ if (created.branch === branch)
776
+ return undefined;
777
+ if (!created.branch)
778
+ return `${spec.order.id}: 오르카가 만든 임시 브랜치를 못 읽어 지우지 못했어요. ${created.path ?? created.selector}에서 git branch로 확인해 주세요`;
779
+ const r = await runSoft(this.runner, 'git', ['-C', created.path, 'branch', '-d', created.branch], {
780
+ timeoutMs: GIT_TIMEOUT_MS,
781
+ });
782
+ if (r.code === 0)
783
+ return undefined;
784
+ return `${spec.order.id}: 오르카가 만든 임시 브랜치 ${created.branch}를 못 지웠어요: ${outputHead(r)}`;
785
+ }
786
+ /** 오르카 워크트리 이름으로 경로를 찾는다. 못 찾으면 undefined. 브랜치 계획과 이어받기가 같은 답을 쓴다 */
787
+ async worktreePathOf(name) {
788
+ if (this.worktreePaths.has(name))
789
+ return this.worktreePaths.get(name);
790
+ const r = await this.runner(this.opts.orcaCommand, ['worktree', 'show', '--worktree', `name:${name}`, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS }).catch(() => undefined);
791
+ const path = r?.code === 0 ? worktreeField(r.stdout, 'path') : undefined;
792
+ this.worktreePaths.set(name, path);
793
+ return path;
794
+ }
795
+ /** detach한 앞 워크트리를 다시 그 브랜치로 돌린다. 결과를 실패 사유 뒤에 붙일 문장으로 돌려준다 */
796
+ async restoreHolder(holder, branch) {
797
+ const r = await this.runner('git', ['-C', holder, 'switch', branch], {
798
+ timeoutMs: GIT_TIMEOUT_MS,
799
+ }).catch(() => undefined);
800
+ return r?.code === 0
801
+ ? `. 앞 워크트리 ${holder}는 다시 ${branch}로 돌려 뒀어요`
802
+ : `. 앞 워크트리 ${holder}가 detach된 채로 남았어요. \`git -C ${shellArg(holder)} switch ${shellArg(branch)}\`로 되돌려 주세요`;
803
+ }
804
+ /**
805
+ * 워크트리에 참조를 붙인다. 붙이기는 워커 띄우기와 별개라 실패해도 띄우고 경고만 돌려준다.
806
+ * `worktree create --reference`는 지라 키를 못 풀면 워크트리 만들기까지 실패하므로 만든 뒤 붙인다
807
+ */
808
+ async attachReference(order, worktree, ref) {
809
+ const r = await runSoft(this.runner, this.opts.orcaCommand, ['reference', 'add', ref, '--worktree', worktree, '--json'], { timeoutMs: DEFAULT_COMMAND_TIMEOUT_MS });
810
+ if (r.code === 0)
811
+ return undefined;
812
+ return `${order.id}: 워크트리에 참조 ${oneLine(ref, 120)}를 못 붙였어요: ${outputHead(r)}`;
335
813
  }
336
814
  async send(worker, message) {
337
815
  if (!worker.handle)
@@ -496,7 +974,7 @@ export class OrcaLauncher {
496
974
  const r = await this.runner(this.opts.orcaCommand, ['worktree', 'rm', '--worktree', workspace.selector, '--delete-branch', '--json'], { timeoutMs: ORCA_TIMEOUT_MS });
497
975
  if (r.code === 0 || errorCode(r.stdout) === 'selector_not_found')
498
976
  return;
499
- throw new Error(`${this.opts.orcaCommand} worktree rm 실패(${r.code}): ${outputHead(r)}. 커밋 안 한 변경이 있는지 확인하고 \`orca worktree rm --worktree ${workspace.selector} --delete-branch\`로 지워 주세요`);
977
+ throw new Error(`${this.opts.orcaCommand} worktree rm 실패(${r.code}): ${outputHead(r)}. 커밋 안 한 변경이 있는지 확인하고 ${rmCommand(workspace.selector, true)}로 지워 주세요`);
500
978
  }
501
979
  }
502
980
  /**
@@ -641,6 +1119,7 @@ export class GitWorktreeLauncher {
641
1119
  opts;
642
1120
  kind = 'git-worktree';
643
1121
  runner;
1122
+ remoteHeads = new Map();
644
1123
  constructor(opts) {
645
1124
  this.opts = opts;
646
1125
  this.runner = opts.runner ?? execRunner;
@@ -652,18 +1131,30 @@ export class GitWorktreeLauncher {
652
1131
  const cwd = spec.previousHandle && existsSync(spec.previousHandle)
653
1132
  ? spec.previousHandle
654
1133
  : join(this.opts.worktreeRoot, spec.order.id);
655
- if (!existsSync(cwd))
656
- await this.addWorktree(repoPath, `conductor/${spec.order.id}`, cwd, spec.order.baseBranch);
1134
+ const warnings = [];
1135
+ let branch;
1136
+ if (existsSync(cwd)) {
1137
+ // 앞 워크트리를 다시 쓴다. 기록은 이름 규칙이 아니라 그 워크트리가 실제로 체크아웃한 브랜치를 따른다
1138
+ branch = await currentBranch(this.runner, cwd);
1139
+ if (!branch)
1140
+ warnings.push(`${spec.order.id}: ${cwd}가 detach 상태이거나 브랜치를 못 읽어 워커 브랜치를 기록하지 않았어요`);
1141
+ else if (await isProtectedBranch(this.runner, cwd, branch, spec.order)) {
1142
+ warnings.push(`${spec.order.id}: ${cwd}가 기준 브랜치나 기본 브랜치 ${branch}를 체크아웃하고 있어 워커 브랜치로 기록하지 않았어요`);
1143
+ branch = undefined;
1144
+ }
1145
+ }
1146
+ else {
1147
+ branch = await this.branchFor(spec, repoPath, warnings);
1148
+ await this.addWorktree(repoPath, branch, cwd, spec.order.baseBranch);
1149
+ }
657
1150
  const promptFile = writePrompt(this.opts.promptDir, spec.worker.id, spec.prompt);
658
1151
  // git 워크트리에는 부모 자식 관계가 없다. 주문은 그대로 띄우고 부모를 못 따랐다고 알린다
659
- const warnings = spec.order.parentWorktree
660
- ? [
661
- `${spec.order.id}: git 워크트리 워커라 부모 워크트리(${spec.order.parentWorktree})를 무시하고 ${cwd}에 띄웠어요`,
662
- ]
663
- : [];
1152
+ if (spec.order.parentWorktree)
1153
+ warnings.push(`${spec.order.id}: git 워크트리 워커라 부모 워크트리(${spec.order.parentWorktree})를 무시하고 ${cwd}에 띄웠어요`);
664
1154
  return {
665
1155
  ...(warnings.length ? { warnings } : {}),
666
1156
  handle: cwd,
1157
+ ...(branch ? { branch } : {}),
667
1158
  hostAction: {
668
1159
  type: 'open-session',
669
1160
  workerId: spec.worker.id,
@@ -673,6 +1164,38 @@ export class GitWorktreeLauncher {
673
1164
  },
674
1165
  };
675
1166
  }
1167
+ /**
1168
+ * 지라 주문은 재개면 앞 워커가 기록한 브랜치를, 처음이면 비어 있는 `fix/`나 `feat/` 이름을 쓴다.
1169
+ * 기록한 브랜치가 로컬에 없으면 새로 갈라 띄우지 않고 멈춘다. 브랜치 기록이 없는 옛 워커는 예전 이름
1170
+ * `conductor/<주문 id>`가 남아 있으면 그걸, 없고 기본 이름이 로컬에 있으면 경고와 함께 그걸 이어받는다.
1171
+ * 그 밖의 주문은 지금처럼 `conductor/<주문 id>`를 쓰고 남아 있으면 이어 붙인다
1172
+ */
1173
+ async branchFor(spec, repoPath, warnings) {
1174
+ const planned = issueBranchName(spec.order);
1175
+ const legacy = `conductor/${spec.order.id}`;
1176
+ if (!planned)
1177
+ return legacy;
1178
+ const previous = spec.previousBranch;
1179
+ if (previous !== undefined) {
1180
+ assertResumableBranch(previous);
1181
+ await assertNotProtected(this.runner, repoPath, previous, spec.order);
1182
+ if (!(await hasLocalBranch(this.runner, repoPath, previous)))
1183
+ throw new Error(`앞 워커가 쓰던 브랜치 ${previous}가 로컬에 없어 이어받지 못했어요. origin에만 있으면 \`git -C ${shellArg(repoPath)} branch ${shellArg(previous)} ${shellArg(`origin/${previous}`)}\`로 가져온 뒤 다시 돌려 주세요`);
1184
+ return previous;
1185
+ }
1186
+ let local;
1187
+ if (spec.previousWorker) {
1188
+ if (await hasLocalBranch(this.runner, repoPath, legacy))
1189
+ return legacy;
1190
+ const found = await adoptPlannedIfPresent(this.runner, repoPath, planned, spec.order.id, warnings);
1191
+ if (found.name)
1192
+ return found.name;
1193
+ local = found.local;
1194
+ }
1195
+ const picked = await pickFreeBranch(this.runner, repoPath, planned, this.remoteHeads, local);
1196
+ warnings.push(...picked.warnings.map((w) => `${spec.order.id}: ${w}`));
1197
+ return picked.branch;
1198
+ }
676
1199
  /**
677
1200
  * 재개 때 디렉토리만 지워지고 브랜치가 남았으면 그 브랜치로 다시 붙인다. 지워진 워크트리가
678
1201
  * git에 등록된 채로 남아 있으면 같은 브랜치를 못 붙이니 먼저 prune한다.