@tienne/gestalt 0.162.1 → 0.163.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 (87) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  3. package/dist/plugin/skills/_shared/before-screenshot.md +41 -15
  4. package/dist/plugin/skills/_shared/screen-change.md +154 -0
  5. package/dist/plugin/skills/conductor/SKILL.md +3 -1
  6. package/dist/plugin/skills/execute/SKILL.md +1 -1
  7. package/dist/plugin/skills/handoff/SKILL.md +1 -1
  8. package/dist/plugin/skills/pr/SKILL.md +32 -17
  9. package/dist/plugin/skills/ship/SKILL.md +16 -8
  10. package/dist/schemas/gestalt.schema.json +12 -2
  11. package/dist/src/cli/commands/conductor.d.ts +12 -76
  12. package/dist/src/cli/commands/conductor.d.ts.map +1 -1
  13. package/dist/src/cli/commands/conductor.js +312 -99
  14. package/dist/src/cli/commands/conductor.js.map +1 -1
  15. package/dist/src/cli/index.d.ts.map +1 -1
  16. package/dist/src/cli/index.js +21 -26
  17. package/dist/src/cli/index.js.map +1 -1
  18. package/dist/src/conductor/activity.d.ts +15 -1
  19. package/dist/src/conductor/activity.d.ts.map +1 -1
  20. package/dist/src/conductor/activity.js +15 -0
  21. package/dist/src/conductor/activity.js.map +1 -1
  22. package/dist/src/conductor/bot-approval.d.ts +1 -0
  23. package/dist/src/conductor/bot-approval.d.ts.map +1 -1
  24. package/dist/src/conductor/bot-approval.js +14 -26
  25. package/dist/src/conductor/bot-approval.js.map +1 -1
  26. package/dist/src/conductor/engine.d.ts +2 -0
  27. package/dist/src/conductor/engine.d.ts.map +1 -1
  28. package/dist/src/conductor/engine.js +12 -5
  29. package/dist/src/conductor/engine.js.map +1 -1
  30. package/dist/src/conductor/intake.d.ts +5 -2
  31. package/dist/src/conductor/intake.d.ts.map +1 -1
  32. package/dist/src/conductor/intake.js +13 -3
  33. package/dist/src/conductor/intake.js.map +1 -1
  34. package/dist/src/conductor/launcher.d.ts +8 -0
  35. package/dist/src/conductor/launcher.d.ts.map +1 -1
  36. package/dist/src/conductor/launcher.js +12 -4
  37. package/dist/src/conductor/launcher.js.map +1 -1
  38. package/dist/src/conductor/scheduler.d.ts +18 -7
  39. package/dist/src/conductor/scheduler.d.ts.map +1 -1
  40. package/dist/src/conductor/scheduler.js +33 -8
  41. package/dist/src/conductor/scheduler.js.map +1 -1
  42. package/dist/src/conductor/store.d.ts.map +1 -1
  43. package/dist/src/conductor/store.js +10 -1
  44. package/dist/src/conductor/store.js.map +1 -1
  45. package/dist/src/conductor/transcript.d.ts +29 -0
  46. package/dist/src/conductor/transcript.d.ts.map +1 -1
  47. package/dist/src/conductor/transcript.js +82 -8
  48. package/dist/src/conductor/transcript.js.map +1 -1
  49. package/dist/src/conductor/trusted-chat-approval.d.ts +20 -0
  50. package/dist/src/conductor/trusted-chat-approval.d.ts.map +1 -0
  51. package/dist/src/conductor/trusted-chat-approval.js +73 -0
  52. package/dist/src/conductor/trusted-chat-approval.js.map +1 -0
  53. package/dist/src/conductor/types.d.ts +36 -3
  54. package/dist/src/conductor/types.d.ts.map +1 -1
  55. package/dist/src/conductor/types.js.map +1 -1
  56. package/dist/src/conductor/work-class.d.ts +36 -0
  57. package/dist/src/conductor/work-class.d.ts.map +1 -0
  58. package/dist/src/conductor/work-class.js +72 -0
  59. package/dist/src/conductor/work-class.js.map +1 -0
  60. package/dist/src/core/config.d.ts +44 -4
  61. package/dist/src/core/config.d.ts.map +1 -1
  62. package/dist/src/core/config.js +17 -2
  63. package/dist/src/core/config.js.map +1 -1
  64. package/package.json +1 -1
  65. package/plugin/.codex-plugin/plugin.json +1 -1
  66. package/plugin/.mcp.json +1 -1
  67. package/plugin/mcp.json +1 -1
  68. package/plugin/skills/_shared/before-screenshot.md +41 -15
  69. package/plugin/skills/_shared/screen-change.md +154 -0
  70. package/plugin/skills/conductor/SKILL.md +3 -1
  71. package/plugin/skills/execute/SKILL.md +1 -1
  72. package/plugin/skills/handoff/SKILL.md +1 -1
  73. package/plugin/skills/pr/SKILL.md +32 -17
  74. package/plugin/skills/ship/SKILL.md +16 -8
  75. package/schemas/gestalt.schema.json +12 -2
  76. package/dist/src/cli/commands/conductor-approval.d.ts +0 -32
  77. package/dist/src/cli/commands/conductor-approval.d.ts.map +0 -1
  78. package/dist/src/cli/commands/conductor-approval.js +0 -207
  79. package/dist/src/cli/commands/conductor-approval.js.map +0 -1
  80. package/dist/src/conductor/approval-server.d.ts +0 -69
  81. package/dist/src/conductor/approval-server.d.ts.map +0 -1
  82. package/dist/src/conductor/approval-server.js +0 -279
  83. package/dist/src/conductor/approval-server.js.map +0 -1
  84. package/dist/src/conductor/webauthn-approval.d.ts +0 -81
  85. package/dist/src/conductor/webauthn-approval.d.ts.map +0 -1
  86. package/dist/src/conductor/webauthn-approval.js +0 -181
  87. package/dist/src/conductor/webauthn-approval.js.map +0 -1
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { chatApprovalCandidates, chatApprovalId, chatDecisionId, chatOfferProblem, mergeApprovalPolicy, requireTrustedChat, TRUSTED_CHAT_OFF, verifyChatOffer, } from '../../conductor/trusted-chat-approval.js';
2
3
  import { mkdirSync, readFileSync, realpathSync, rmSync, statSync } from 'node:fs';
3
4
  import { homedir } from 'node:os';
4
5
  import { dirname, join, resolve } from 'node:path';
@@ -7,7 +8,7 @@ import { handleGithubOrder, readGithubOrder } from '../../conductor/bot-github.j
7
8
  import { handoffBot } from '../../conductor/bot-handoff.js';
8
9
  import { automationCoordinationDir, automationCoordinationRoot, handoffCancellationPending, } from '../../conductor/bot-handoff-coordination.js';
9
10
  import { readEditReceipt } from '../../conductor/bot-handoff-edit.js';
10
- import { decisionId, decisionReceipt, decisionTarget, gateApprovalMessage, matchBotGate, readBotPolicy, loadBotPolicy, approverStatus, approverGuidance, assertApproverReady, terminalResolveCommand, approverRegistry, peekBotPolicy, readMergeEvidence, verifyGateApproval, } from '../../conductor/bot-approval.js';
11
+ import { decisionId, BOT_POLICY_FILE, decisionReceipt, decisionTarget, gateApprovalMessage, matchBotGate, readBotPolicy, loadBotPolicy, approverStatus, approverGuidance, assertApproverReady, terminalResolveCommand, approverRegistry, peekBotPolicy, readMergeEvidence, verifyGateApproval, } from '../../conductor/bot-approval.js';
11
12
  import { officialOrcaApprovalIssuer, ORCA_APPROVAL_UNAVAILABLE, orcaApprovalTargetHash, verifyOrcaApproval, } from '../../conductor/orca-approval-attestation.js';
12
13
  import { itemBinding, OrcaContractError, readItemDecision, readOrcaItem, } from '../../conductor/orca-item-approval.js';
13
14
  import { assertBotOwner, changeBotOwner, currentBotOwner, targetBotOwner, readBotOwnership, } from '../../conductor/bot-owner.js';
@@ -39,11 +40,12 @@ import { normalizePrRef } from '../../conductor/pr-ref.js';
39
40
  import { saveSkillCheckpoint } from '../../conductor/resume.js';
40
41
  import { currentSessionTab, nameConductorTab, renameHandoffTabs, } from '../../conductor/tab-title.js';
41
42
  import { clearCloseClaim, closeHandedOffTabs, handoffCloseLine, } from '../../conductor/handoff-close.js';
43
+ import { planSlots } from '../../conductor/scheduler.js';
44
+ import { mapClasses, orderWorkClass, totalLimit, WORK_CLASS_LABEL, WORK_CLASSES, workerWorkClass, } from '../../conductor/work-class.js';
42
45
  import { confirmSlackDelivery, draftSlack, pendingSlackDelivery } from '../../conductor/slack.js';
43
46
  import { isSlackChannelId } from '../../conductor/slack-state.js';
44
47
  import { claimWaitOwner, consumeWaitCarry, hasWaitCarry, mergeWaitCarry, readSeen, saveWaitCarry, shownLines, WAIT_REPORT_FILE, waitForAttention, withWaitOwnerLock, writeSeen, } from '../../conductor/wait.js';
45
48
  import { ConductorStore } from '../../conductor/store.js';
46
- import { APPROVAL_PORT, assertionSchema, verifyWebAuthnAssertion, webAuthnApprovers, webAuthnChallenge, } from '../../conductor/webauthn-approval.js';
47
49
  import { InputError } from '../../conductor/input-error.js';
48
50
  import { resolveStateDir } from '../../conductor/state-dir.js';
49
51
  import { INTAKE_KINDS, ISSUE_TYPES, JIRA_STATUSES, ORDER_SCOPES, WORKER_KINDS, TERMINAL_ORDER_STATUSES, } from '../../conductor/types.js';
@@ -126,6 +128,9 @@ export function conductorOrderAddCommand(opts) {
126
128
  ...(opts.workerKind
127
129
  ? { workerKind: oneOf(opts.workerKind, WORKER_KINDS, '--worker-kind') }
128
130
  : {}),
131
+ ...(opts.workClass
132
+ ? { workClass: oneOf(opts.workClass, WORK_CLASSES, '--work-class') }
133
+ : {}),
129
134
  ...(parentWorktree ? { parentWorktree } : {}),
130
135
  ...(opts.baseBranch !== undefined ? { baseBranch: opts.baseBranch } : {}),
131
136
  ...(opts.issueKey ? { issueKey: issueKey(opts.issueKey) } : {}),
@@ -159,7 +164,7 @@ export function conductorOrderAddCommand(opts) {
159
164
  }
160
165
  if (opts.json)
161
166
  return print({ created: out.created, order: out.order });
162
- console.log(`${out.created ? '주문을 받았어요' : '이미 받은 주문이에요'}: ${out.order.id} (${out.order.scope})`);
167
+ console.log(`${out.created ? '주문을 받았어요' : '이미 받은 주문이에요'}: ${out.order.id} (${out.order.scope}, ${WORK_CLASS_LABEL[orderWorkClass(out.order)]})`);
163
168
  });
164
169
  }
165
170
  /**
@@ -468,6 +473,8 @@ export function conductorStatusCommand(opts) {
468
473
  ...(o.workerId ? { worker: o.workerId } : {}),
469
474
  // 오르카 플러그인 같은 바깥 도구가 워커 워크트리를 찾아 열 때 쓴다
470
475
  ...(w ? { workerKind: w.kind, workerStatus: w.status } : {}),
476
+ // 동시 실행 슬롯 유형. 워커 종류와는 다른 칸이다
477
+ workClass: w ? workerWorkClass(w, o) : orderWorkClass(o),
471
478
  ...(w?.handle ? { workerHandle: w.handle } : {}),
472
479
  ...(w?.kind === 'orca-worktree' ? { worktreeName: orcaWorktreeName(w) } : {}),
473
480
  // 바깥 도구가 주문 위계를 그릴 때 쓴다. 하위 주문과 부모 워크트리 둘 다 비면 뿌리 주문이다
@@ -511,6 +518,10 @@ export function conductorStatusCommand(opts) {
511
518
  });
512
519
  }
513
520
  console.log(`마지막 tick: ${store.snapshot.lastTickAt ?? '없음'}`);
521
+ console.log(`슬롯: ${slotLine(store, config)}`);
522
+ const legacy = legacyLimitWarning(config);
523
+ if (legacy)
524
+ console.log(`경고: ${legacy}`);
514
525
  const staleWarning = staleTickWarning(store.snapshot.lastTickAt, new Date().toISOString(), config.staleAfterSec * 1000);
515
526
  if (staleWarning)
516
527
  console.log(`경고: ${staleWarning}`);
@@ -518,7 +529,7 @@ export function conductorStatusCommand(opts) {
518
529
  const summary = opts.all && TERMINAL_ORDER_STATUSES.has(o.status)
519
530
  ? store.snapshot.reports[o.id]?.at(-1)?.summary
520
531
  : undefined;
521
- console.log(`${o.id} ${o.status} ${o.scope} ${o.repo} ${o.title}${summary ? ` ${oneLine(summary, 100)}` : ''}`);
532
+ console.log(`${o.id} ${o.status} ${o.scope} ${o.repo} ${o.title} [${WORK_CLASS_LABEL[orderWorkClass(o)]}]${summary ? ` ${oneLine(summary, 100)}` : ''}`);
522
533
  const limit = limited.get(o.id);
523
534
  if (limit)
524
535
  console.log(` ${rateLimitLine(limit)}`);
@@ -534,7 +545,7 @@ export function conductorStatusCommand(opts) {
534
545
  console.log(`승인자: 봇 정책 파일이 ${approvers.policy === 'missing' ? '없어요' : '깨져서 못 읽어요'}. 봇 채팅에서는 게이트를 못 닫아요`);
535
546
  else
536
547
  for (const a of approvers.repos)
537
- console.log(`승인자 ${a.repo} 머지 ${a.merge ? `${a.merge}명` : '미등록'} 게이트 ${a.gate ? `${a.gate}명` : '미등록'}`);
548
+ console.log(`승인자 ${a.repo} 머지 ${a.mergeApprovalPolicy === 'trusted-chat' ? `채팅 문구 승인${a.merge ? `, 서명 ${a.merge}명` : ''}` : a.merge ? `${a.merge}명` : '미등록'} 게이트 ${a.gate ? `${a.gate}명` : '미등록'}`);
538
549
  for (const g of gates)
539
550
  console.log(`게이트 ${g.id} ${g.type} ${g.reason}`);
540
551
  });
@@ -562,6 +573,17 @@ function statusApprovers(store, config, orders) {
562
573
  ...Object.keys(config.repoPaths ?? {}),
563
574
  ]);
564
575
  }
576
+ /** 예전 전체 상한이 설정에 남아 있으면 안 쓴다고 알린다. 두 번째 상한으로 쓰지 않는다 */
577
+ function legacyLimitWarning(config) {
578
+ if (config.maxConcurrentWorkers === undefined)
579
+ return undefined;
580
+ return `conductor.maxConcurrentWorkers(${config.maxConcurrentWorkers})는 이제 안 써요. 전체 한도는 workerLimits의 합(${totalLimit(config.workerLimits)})이에요. 설정에서 workerLimits로 옮겨 주세요`;
581
+ }
582
+ /** `조회 2/5 · 리뷰 3/5 · 작업 4/10` */
583
+ function slotLine(store, config) {
584
+ const plan = planSlots(store, config.workerLimits);
585
+ return WORK_CLASSES.map((c) => `${WORK_CLASS_LABEL[c]} ${plan.byClass[c].active}/${plan.byClass[c].limit}`).join(' · ');
586
+ }
565
587
  /**
566
588
  * 컨덕터 자체의 값. 저장소와 설정에서 이미 아는 것만 싣는다.
567
589
  * 컴팩트 횟수와 세션 id, 작업 디렉토리는 살아 있는 컨덕터 세션을 찾았을 때만 싣는다.
@@ -582,9 +604,17 @@ function conductorSummary(ctx) {
582
604
  const session = botOwner
583
605
  ? undefined
584
606
  : findActiveConductor(store.dir, '', Date.now(), activeConductorWindowMs(config));
607
+ const slots = planSlots(store, config.workerLimits);
608
+ const legacy = legacyLimitWarning(config);
585
609
  return {
586
610
  pollIntervalSec: config.pollIntervalSec,
587
- maxWorkers: config.maxConcurrentWorkers,
611
+ // 이전 CLI를 읽는 화면을 위해 이름은 그대로 두고 값은 유형별 한도의 합을 싣는다
612
+ maxWorkers: slots.limit,
613
+ workerSlots: mapClasses((c) => ({
614
+ active: slots.byClass[c].active,
615
+ limit: slots.byClass[c].limit,
616
+ })),
617
+ ...(legacy ? { warnings: [legacy] } : {}),
588
618
  activeWorkers: store.activeWorkers().length,
589
619
  queuedOrders: store.queuedOrders().length,
590
620
  prWatchRepos: config.prWatchRepos,
@@ -779,6 +809,10 @@ async function runConductorTick(ctx, opts, sessionId, caller, onClose = () => {
779
809
  ],
780
810
  });
781
811
  report.hostActions.push(...deferred);
812
+ // status를 안 보는 동안에도 옛 상한이 무시되고 있다는 걸 tick 출력으로 알린다
813
+ const legacy = legacyLimitWarning(ctx.config);
814
+ if (legacy)
815
+ report.warnings.push(legacy);
782
816
  const handoff = sessionId ? sessionHandoff(ctx, sessionId) : undefined;
783
817
  return { report, ...(handoff ? { handoff } : {}), handoffClose };
784
818
  }
@@ -1694,12 +1728,17 @@ function botDecisionStatus(gate) {
1694
1728
  : 'pending';
1695
1729
  const source = gate.decisionSource;
1696
1730
  const decided = gate.decision === 'approved' ? '승인' : gate.decision === 'rejected' ? '거절' : gate.decision;
1697
- const approvalLabel = source?.attestation ? 'Orca 증빙' : '서명';
1731
+ const approvalLabel = gate.decisionVia?.kind === 'trusted-chat'
1732
+ ? '채팅 문구 승인'
1733
+ : source?.attestation
1734
+ ? 'Orca 증빙'
1735
+ : '서명';
1698
1736
  return {
1699
1737
  gateId: gate.id,
1700
1738
  decision: gate.decision ?? 'open',
1701
1739
  ...(gate.decisionBy ? { signer: gate.decisionBy } : {}),
1702
1740
  ...(source ? { source } : {}),
1741
+ ...(gate.decisionVia ? { via: gate.decisionVia } : {}),
1703
1742
  delivery,
1704
1743
  ...(receipt
1705
1744
  ? {
@@ -1774,13 +1813,6 @@ async function botGateEvidence(ctx, target) {
1774
1813
  ? readMergeEvidence(target.ref, new GhAccounts(ctx.config.accounts))
1775
1814
  : undefined;
1776
1815
  }
1777
- /** 서명 문자열에 PR과 HEAD가 들어가는 게이트는 그 값을 못 읽으면 승인 페이지에 원인을 400으로 돌려준다 */
1778
- async function touchIdGateEvidence(ctx, target) {
1779
- const evidence = await botGateEvidence(ctx, target);
1780
- if (!evidence && (target.gate.type === 'merge' || target.gate.type === 'review-manual-switch'))
1781
- throw new InputError('이 게이트는 PR과 HEAD를 읽어야 서명을 확인할 수 있어요');
1782
- return evidence;
1783
- }
1784
1816
  export async function conductorBotGateCommand(gateId, opts) {
1785
1817
  try {
1786
1818
  const ctx = open(opts);
@@ -1815,6 +1847,16 @@ export async function conductorBotGateCommand(gateId, opts) {
1815
1847
  // 승인자가 없으면 서명을 요구할 이유가 없다. 봇이 터미널 안내로 바로 가게 서명 재료를 싣지 않는다
1816
1848
  const read = peekBotPolicy(ctx.store.dir);
1817
1849
  const policy = 'policy' in read ? read.policy : undefined;
1850
+ const trusted = gate.type === 'merge' && mergeApprovalPolicy(policy, target.repo) === 'trusted-chat'
1851
+ ? {
1852
+ mergeApprovalPolicy: 'trusted-chat',
1853
+ chatApproval: gate.chatApprovalOffer,
1854
+ guidance: `chat-offer ${gate.id}로 PR과 HEAD를 안내하고 <ID> 승인해줘 요청을 chat-decide로 처리해 주세요`,
1855
+ }
1856
+ : undefined;
1857
+ // trusted-chat 레포에서 approverReady는 서명 경로를 함께 쓸 수 있는지만 뜻한다. 없어도 터미널로 보내지 않는다
1858
+ if (trusted && !approverStatus(policy, gate.type, target.repo).ready)
1859
+ return print({ ...base, approverReady: false, ...trusted });
1818
1860
  const gap = 'unreadable' in read ? 'unreadable' : approverStatus(policy, gate.type, target.repo).gap;
1819
1861
  if (gap)
1820
1862
  return print({
@@ -1829,11 +1871,10 @@ export async function conductorBotGateCommand(gateId, opts) {
1829
1871
  });
1830
1872
  const evidence = await botGateEvidence(ctx, target);
1831
1873
  const issuer = await officialOrcaApprovalIssuer(caller);
1832
- const touchId = touchIdLinks(ctx, gate.id, webAuthnApprovers(policy, gate.type, target.repo));
1833
1874
  print({
1834
1875
  ...base,
1835
1876
  approverReady: true,
1836
- ...touchId,
1877
+ ...trusted,
1837
1878
  ...(evidence ? { evidence } : {}),
1838
1879
  messages: {
1839
1880
  approved: gateApprovalMessage(target, evidence?.head, 'approved', evidence?.base),
@@ -1856,46 +1897,29 @@ export async function conductorBotGateCommand(gateId, opts) {
1856
1897
  exitWithError(error);
1857
1898
  }
1858
1899
  }
1859
- /**
1860
- * 승인자가 Touch ID 키를 등록할 때의 주소로 승인 페이지 링크를 만든다. --port로 등록했으면 그 포트로 띄워야
1861
- * origin이 맞는다. 승인자마다 포트가 다르면 첫 승인자의 주소를 쓴다
1862
- */
1863
- function touchIdLinks(ctx, gateId, approvers) {
1864
- const first = approvers[0];
1865
- if (!first)
1866
- return {};
1867
- const origin = first.credential.origin;
1868
- const port = Number(new URL(origin).port) || APPROVAL_PORT;
1869
- const link = (decision) => `${origin}/gate/${encodeURIComponent(gateId)}?decision=${decision}`;
1870
- return {
1871
- touchId: {
1872
- links: { approved: link('approved'), rejected: link('rejected') },
1873
- start: `gestalt conductor approval serve --detach --state-dir ${JSON.stringify(ctx.store.dir)}${port === APPROVAL_PORT ? '' : ` --port ${port}`}`,
1874
- },
1875
- };
1876
- }
1877
1900
  function verifyBotDecision(policy, target, receiptTarget, evidence, request) {
1878
- if ('webauthn' in request) {
1879
- const { webauthn, decision, nonce, origin } = request;
1880
- const approver = webAuthnApprovers(policy, target.gate.type, target.repo).find((a) => a.credential.credentialId === webauthn.credentialId);
1881
- if (!approver)
1882
- throw new InputError(`이 레포의 ${target.gate.type === 'merge' ? '머지' : '게이트'} 승인자로 등록된 Touch ID 키가 아니에요`);
1883
- const { signCount } = verifyWebAuthnAssertion(approver.credential, {
1884
- challenge: webAuthnChallenge(gateApprovalMessage(target, evidence?.head, decision, evidence?.base), nonce),
1885
- origin,
1886
- }, webauthn);
1901
+ if ('chatOffer' in request) {
1902
+ requireTrustedChat(policy, target.repo);
1903
+ if (target.gate.type !== 'merge' || request.decision !== 'approved')
1904
+ throw new InputError('운영 채팅 문구를 신뢰하는 경로는 머지 승인만 처리해요');
1905
+ const offer = verifyChatOffer(target.gate.chatApprovalOffer, request.owner, receiptTarget);
1906
+ if (offer.id !== request.chatOffer.id ||
1907
+ offer.head !== evidence?.head ||
1908
+ offer.base !== evidence?.base)
1909
+ throw new InputError('승인 안내가 바뀌었어요. 새 안내를 확인한 뒤 승인해 주세요');
1887
1910
  return {
1888
- id: decisionId(approver.id, Buffer.from(webauthn.signature, 'base64url').toString('base64')),
1889
- signer: approver.id,
1890
- via: { kind: 'webauthn', credentialId: webauthn.credentialId, signCount },
1911
+ id: chatDecisionId(offer),
1912
+ signer: `trusted-chat:${offer.botId}:${offer.chatId}`,
1913
+ via: { kind: 'trusted-chat', offerId: offer.id, botId: offer.botId, chatId: offer.chatId },
1891
1914
  };
1892
1915
  }
1916
+ const ready = assertApproverReady(policy, target.gate, target.repo);
1893
1917
  if ('issuer' in request) {
1894
1918
  const { issuer, proof, decision, source } = request;
1895
1919
  const targetHash = orcaApprovalTargetHash(receiptTarget, evidence);
1896
- return verifyOrcaApproval(issuer, proof, { source, decision, target, targetHash }, policy);
1920
+ return verifyOrcaApproval(issuer, proof, { source, decision, target, targetHash }, ready);
1897
1921
  }
1898
- verifyGateApproval(policy, target.gate.type, target.repo, request.signer, gateApprovalMessage(target, evidence?.head, request.decision, evidence?.base), request.signature);
1922
+ verifyGateApproval(ready, target.gate.type, target.repo, request.signer, gateApprovalMessage(target, evidence?.head, request.decision, evidence?.base), request.signature);
1899
1923
  return { ...request, id: decisionId(request.signer, request.signature) };
1900
1924
  }
1901
1925
  /**
@@ -1904,10 +1928,13 @@ function verifyBotDecision(policy, target, receiptTarget, evidence, request) {
1904
1928
  async function applyBotDecision(ctx, { caller, request }, gateId, beforeTarget, evidence, sameSource) {
1905
1929
  const lock = await waitForDecisionLock(ctx);
1906
1930
  try {
1907
- // Touch ID 승인은 운영 봇이 아니라 승인자 본인이 연 페이지에서 온다. 승인 근거는 서명이라 봇 운영권을 묻지 않는다
1908
- if (caller || !('webauthn' in request))
1909
- assertBotOwner(ctx.store.dir, caller);
1931
+ assertBotOwner(ctx.store.dir, caller);
1910
1932
  ctx.store.reload();
1933
+ if ('chatOffer' in request) {
1934
+ const matches = chatApprovalCandidates(Object.values(ctx.store.snapshot.gates), request.inputId, caller);
1935
+ if (matches.length !== 1 || matches[0]?.id !== gateId)
1936
+ throw new InputError('승인 ID의 대상이 바뀌었어요. 어느 PR인지 다시 확인해 주세요');
1937
+ }
1911
1938
  const existing = ctx.store.snapshot.gates[gateId];
1912
1939
  if (existing?.status === 'resolved')
1913
1940
  return {
@@ -1927,7 +1954,7 @@ async function applyBotDecision(ctx, { caller, request }, gateId, beforeTarget,
1927
1954
  throw new InputError('게이트나 PR이 바뀌었어요. 다시 확인해 주세요');
1928
1955
  const head = evidence?.head;
1929
1956
  const { decision } = request;
1930
- const approval = verifyBotDecision(assertApproverReady(loadBotPolicy(ctx.store.dir), current.gate, current.repo), current, receiptTarget, evidence, request);
1957
+ const approval = verifyBotDecision(loadBotPolicy(ctx.store.dir), current, receiptTarget, evidence, request);
1931
1958
  let checked;
1932
1959
  if (current.ref) {
1933
1960
  const now = await botGateEvidence(ctx, current);
@@ -1959,59 +1986,245 @@ async function applyBotDecision(ctx, { caller, request }, gateId, beforeTarget,
1959
1986
  lock.release();
1960
1987
  }
1961
1988
  }
1962
- /** 승인 페이지는 승인자가 보는 자리라 깨진 정책 파일도 경로 대신 안내 문구로 돌려준다 */
1963
- function touchIdPolicy(dir, gate, repo) {
1964
- const read = peekBotPolicy(dir);
1965
- if ('unreadable' in read)
1966
- throw new InputError(approverGuidance(gate, repo, 'unreadable'));
1967
- return assertApproverReady(read.policy, gate, repo);
1989
+ export async function conductorBotMergePolicyCommand(repo, opts) {
1990
+ try {
1991
+ const ctx = open(opts);
1992
+ const caller = await requireBotOperator(ctx);
1993
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo))
1994
+ throw new InputError('레포는 owner/name 형식이어야 해요');
1995
+ repo = repo.toLowerCase();
1996
+ const mode = oneOf(opts.mode, ['signed', 'trusted-chat'], '--mode');
1997
+ const lock = await waitForDecisionLock(ctx);
1998
+ try {
1999
+ assertBotOwner(ctx.store.dir, caller);
2000
+ const policy = loadBotPolicy(ctx.store.dir) ?? {};
2001
+ const previous = mergeApprovalPolicy(policy, repo);
2002
+ const table = policy['mergeApprovalPolicy'];
2003
+ writeJsonAtomic(join(ctx.store.dir, BOT_POLICY_FILE), {
2004
+ ...policy,
2005
+ mergeApprovalPolicy: { ...table, [repo]: mode },
2006
+ }, { mode: 0o600 });
2007
+ print({
2008
+ repo,
2009
+ previous,
2010
+ mode,
2011
+ changedBy: `${caller.botId}:${caller.chatId}`,
2012
+ trust: '운영 채팅 에이전트가 전달한 문구를 신뢰하고, 사람의 신원은 확인하지 않아요',
2013
+ });
2014
+ }
2015
+ finally {
2016
+ lock.release();
2017
+ }
2018
+ }
2019
+ catch (error) {
2020
+ exitWithError(error);
2021
+ }
2022
+ }
2023
+ function chatOfferPr(offer) {
2024
+ return `https://github.com/${offer.prRef.replace('#', '/pull/')}`;
2025
+ }
2026
+ /** 이 게이트 하나로만 좁혀지는 ID만 안내한다. 게이트 ID는 늘 남는다. */
2027
+ function chatOfferView(ctx, gate, offer) {
2028
+ const gates = Object.values(ctx.store.snapshot.gates);
2029
+ const owner = { botId: offer.botId, chatId: offer.chatId };
2030
+ const ids = [
2031
+ gate.id,
2032
+ ...[gate.orderId, offer.item ? String(offer.item.number) : undefined].filter((id) => {
2033
+ if (!id)
2034
+ return false;
2035
+ const matches = chatApprovalCandidates(gates, id, owner);
2036
+ return matches.length === 1 && matches[0].id === gate.id;
2037
+ }),
2038
+ ];
2039
+ return {
2040
+ gateId: gate.id,
2041
+ orderId: gate.orderId,
2042
+ ids,
2043
+ pr: chatOfferPr(offer),
2044
+ head: offer.head,
2045
+ base: offer.base,
2046
+ offerId: offer.id,
2047
+ offeredAt: offer.offeredAt,
2048
+ commands: ids.map((id) => `${id} 승인해줘`),
2049
+ };
2050
+ }
2051
+ function assertOrcaItemInChat(show, caller, number, mismatch, uid) {
2052
+ if (show.item.number !== number ||
2053
+ show.item.botId !== caller.botId ||
2054
+ show.item.chatId !== caller.chatId)
2055
+ throw new InputError(mismatch);
2056
+ if (uid && show.item.uid !== uid.expected)
2057
+ throw new InputError(uid.message ?? mismatch);
2058
+ }
2059
+ function openTrustedMergeGate(ctx, gateId) {
2060
+ const target = matchBotGate(ctx.store, gateId);
2061
+ if (target.gate.type !== 'merge' || !target.ref || target.gate.status !== 'open')
2062
+ throw new InputError('열린 머지 게이트의 PR만 안내할 수 있어요');
2063
+ requireTrustedChat(loadBotPolicy(ctx.store.dir), target.repo);
2064
+ return { target, ref: target.ref, decision: decisionTarget(ctx.store, target) };
2065
+ }
2066
+ export async function conductorBotChatOfferCommand(gateId, opts) {
2067
+ try {
2068
+ const ctx = open(opts);
2069
+ const caller = await requireBotOperator(ctx);
2070
+ assertBotOwner(ctx.store.dir, caller);
2071
+ const before = openTrustedMergeGate(ctx, gateId);
2072
+ const existing = before.target.gate.chatApprovalOffer;
2073
+ if (existing && !opts.refresh) {
2074
+ verifyChatOffer(existing, caller, before.decision);
2075
+ if (opts.item !== undefined && String(existing.item?.number) !== opts.item)
2076
+ throw new InputError('항목 연결을 바꾸려면 --refresh로 다시 안내해 주세요');
2077
+ return print({ ...chatOfferView(ctx, before.target.gate, existing), reused: true });
2078
+ }
2079
+ // 인계 전 채팅의 항목은 새 채팅 소유가 아니라서 같은 채팅의 안내일 때만 연결을 이어받는다
2080
+ const inherited = existing?.item && existing.botId === caller.botId && existing.chatId === caller.chatId
2081
+ ? existing.item
2082
+ : undefined;
2083
+ const itemNumber = opts.item ?? (inherited ? String(inherited.number) : undefined);
2084
+ let number;
2085
+ if (itemNumber !== undefined) {
2086
+ number = Number(itemNumber);
2087
+ if (!Number.isSafeInteger(number) || number <= 0 || String(number) !== itemNumber)
2088
+ throw new InputError('--item은 Orca 항목 번호예요');
2089
+ }
2090
+ // 외부 CLI와 gh 호출은 서로 기다릴 이유가 없고 결정 잠금을 쥔 채 기다리지 않는다
2091
+ const [show, evidence] = await Promise.all([
2092
+ number === undefined ? undefined : readOrcaItem(number),
2093
+ botGateEvidence(ctx, before.target),
2094
+ ]);
2095
+ let item;
2096
+ if (show && number !== undefined) {
2097
+ assertOrcaItemInChat(show, caller, number, '현재 운영 봇 채팅의 Orca 항목이 아니에요', inherited?.number === number
2098
+ ? {
2099
+ expected: inherited.uid,
2100
+ message: '연결한 Orca 항목의 UID가 바뀌었어요. 다른 항목을 확인해 연결해 주세요',
2101
+ }
2102
+ : undefined);
2103
+ item = { number, uid: show.item.uid };
2104
+ }
2105
+ if (!evidence || evidence.state !== 'OPEN' || evidence.draft)
2106
+ throw new InputError('리뷰 준비가 끝난 열린 PR만 머지 승인 안내를 할 수 있어요');
2107
+ const lock = await waitForDecisionLock(ctx);
2108
+ try {
2109
+ assertBotOwner(ctx.store.dir, caller);
2110
+ ctx.store.reload();
2111
+ const now = openTrustedMergeGate(ctx, gateId);
2112
+ if (now.decision !== before.decision ||
2113
+ now.target.gate.chatApprovalOffer?.id !== existing?.id)
2114
+ throw new InputError('안내 대상이 바뀌었어요. 다시 안내해 주세요');
2115
+ const offer = {
2116
+ id: randomUUID(),
2117
+ botId: caller.botId,
2118
+ chatId: caller.chatId,
2119
+ target: now.decision,
2120
+ prRef: now.ref,
2121
+ head: evidence.head,
2122
+ base: evidence.base,
2123
+ offeredAt: ctx.store.timestamp(),
2124
+ ...(item ? { item } : {}),
2125
+ };
2126
+ ctx.store.append({ type: 'gate-chat-offered', gateId, at: offer.offeredAt, offer });
2127
+ print(chatOfferView(ctx, now.target.gate, offer));
2128
+ }
2129
+ finally {
2130
+ lock.release();
2131
+ }
2132
+ }
2133
+ catch (error) {
2134
+ exitWithError(error);
2135
+ }
1968
2136
  }
1969
2137
  /**
1970
- * Touch ID 승인 페이지가 서명 전에 보여 줄 게이트 내용과 challenge. 봇 운영권 없이 승인자 본인이 연다.
1971
- * nonce는 승인 서버가 발급해 메모리에 둔 값이다
2138
+ * 이 채팅에서 안내한 열린 게이트이고 안내 뒤 대상이 그대로일 때만 바로 승인할 수 있다.
2139
+ * matchBotGate의 InputError(대상 레포의 PR이 연결된 머지 게이트가 아님)는 unavailable로 돌리고
2140
+ * 정책 파일 오류는 단일 후보 경로처럼 그대로 던진다.
1972
2141
  */
1973
- export async function touchIdGateOptions(opts, gateId, decision, nonce) {
1974
- const ctx = open(opts);
1975
- if (!ctx.store.snapshot.gates[gateId])
1976
- throw new InputError('게이트를 찾을 수 없어요');
1977
- const target = matchBotGate(ctx.store, gateId);
1978
- if (target.gate.status !== 'open')
1979
- throw new InputError('이미 닫힌 게이트예요');
1980
- const policy = touchIdPolicy(ctx.store.dir, target.gate, target.repo);
1981
- const approvers = webAuthnApprovers(policy, target.gate.type, target.repo);
1982
- if (!approvers.length)
1983
- throw new InputError(`${target.repo} 레포에는 이 게이트를 닫을 Touch ID 승인자가 없어요. gestalt conductor approver enroll로 먼저 등록해 주세요`);
1984
- const evidence = await touchIdGateEvidence(ctx, target);
2142
+ function chatOfferStatus(ctx, gate, caller) {
2143
+ if (gate.status !== 'open')
2144
+ return { ready: false, reason: 'closed', message: '이미 결정한 머지 게이트예요' };
2145
+ let target;
2146
+ try {
2147
+ target = matchBotGate(ctx.store, gate.id);
2148
+ }
2149
+ catch (error) {
2150
+ if (error instanceof InputError)
2151
+ return { ready: false, reason: 'unavailable', message: error.message };
2152
+ throw error;
2153
+ }
2154
+ if (mergeApprovalPolicy(loadBotPolicy(ctx.store.dir), target.repo) !== 'trusted-chat')
2155
+ return { ready: false, reason: 'policy-off', message: TRUSTED_CHAT_OFF, target };
2156
+ const offer = gate.chatApprovalOffer;
2157
+ const problem = chatOfferProblem(offer, caller, decisionTarget(ctx.store, target));
2158
+ if (problem)
2159
+ return { ready: false, ...problem, target };
2160
+ return { ready: true, offer: offer, target };
2161
+ }
2162
+ const REFRESH_GUIDANCE = '안내 뒤 대상이 바뀌었거나 다른 채팅에서 안내한 머지 게이트예요. 변경을 확인하고 chat-offer --refresh로 다시 안내해 주세요';
2163
+ const AMBIGUOUS_GUIDANCE = {
2164
+ closed: '이미 닫힌 머지 게이트만 남았어요. 후보마다 결정 상태를 확인해 주세요',
2165
+ unavailable: '주문이 없거나 PR이 연결되지 않았거나 PR이 주문 레포와 다른 머지 게이트예요. 주문의 레포와 PR 연결을 확인해 주세요',
2166
+ 'policy-off': '이 레포는 채팅 문구 승인이 꺼져 있어요. bot gate로 서명 승인 경로를 안내해 주세요',
2167
+ 'no-offer': '열린 머지 게이트가 있지만 이 채팅에서 안내하지 않았어요. 먼저 chat-offer로 안내해 주세요',
2168
+ 'other-chat': REFRESH_GUIDANCE,
2169
+ stale: REFRESH_GUIDANCE,
2170
+ };
2171
+ function ambiguousGuidance(statuses) {
2172
+ if (!statuses.length)
2173
+ return '해당 ID의 머지 게이트가 없어요';
2174
+ if (statuses.some((status) => status.ready))
2175
+ return '여러 머지 대상이 있어요. 어느 PR인지 확인하고 command 문구로 다시 요청해 주세요';
2176
+ const reasons = new Set(statuses.flatMap((status) => (status.ready ? [] : [status.reason])));
2177
+ const open = [...reasons].filter((reason) => reason !== 'closed');
2178
+ if (!open.length)
2179
+ return AMBIGUOUS_GUIDANCE.closed;
2180
+ const guidance = new Set(open.map((reason) => AMBIGUOUS_GUIDANCE[reason]));
2181
+ if (guidance.size === 1)
2182
+ return [...guidance][0];
2183
+ return '후보마다 막힌 이유가 달라요. 후보의 reason을 보고 확인할 게이트를 하나 골라 주세요';
2184
+ }
2185
+ function ambiguousCandidate(gate, status, caller) {
2186
+ const offer = gate.chatApprovalOffer;
2187
+ const ownOffer = offer?.botId === caller.botId && offer.chatId === caller.chatId;
2188
+ const offeredPr = offer && ownOffer ? chatOfferPr(offer) : undefined;
2189
+ const pr = status.target?.url;
1985
2190
  return {
1986
- gate: {
1987
- id: target.gate.id,
1988
- type: target.gate.type,
1989
- repo: target.repo,
1990
- reason: target.gate.reason,
1991
- refs: target.gate.refs ?? [],
1992
- ...(target.url ? { pr: target.url } : {}),
1993
- },
1994
- ...(evidence ? { head: evidence.head } : {}),
1995
- decision,
1996
- challenge: webAuthnChallenge(gateApprovalMessage(target, evidence?.head, decision, evidence?.base), nonce),
1997
- nonce,
1998
- credentialIds: approvers.map((a) => a.credential.credentialId),
2191
+ gateId: gate.id,
2192
+ orderId: gate.orderId,
2193
+ status: gate.status,
2194
+ ...(pr ? { pr } : {}),
2195
+ ...(offeredPr && offeredPr !== pr ? { offeredPr } : {}),
2196
+ ...(status.ready ? { command: `${gate.id} 승인해줘` } : { reason: status.reason }),
1999
2197
  };
2000
2198
  }
2001
- /** Touch ID 서명으로 게이트를 닫는다. 서명 확인과 잠금, 기록은 봇 결정과 같은 경로를 탄다 */
2002
- export async function touchIdGateDecide(opts, gateId, decision, raw, server) {
2003
- const parsed = assertionSchema.safeParse(raw);
2004
- if (!parsed.success)
2005
- throw new InputError('WebAuthn 응답 형식을 확인하지 못했어요');
2006
- const ctx = open(opts);
2007
- const target = ctx.store.snapshot.gates[gateId]?.receipt
2008
- ? undefined
2009
- : matchBotGate(ctx.store, gateId);
2010
- const beforeTarget = target ? decisionTarget(ctx.store, target) : undefined;
2011
- if (target?.gate.status === 'open')
2012
- touchIdPolicy(ctx.store.dir, target.gate, target.repo);
2013
- const evidence = target?.gate.status === 'open' ? await touchIdGateEvidence(ctx, target) : undefined;
2014
- return applyBotDecision(ctx, { request: { decision, webauthn: parsed.data, ...server } }, gateId, beforeTarget, evidence);
2199
+ export async function conductorBotChatDecideCommand(opts) {
2200
+ try {
2201
+ const ctx = open(opts);
2202
+ const caller = await requireBotOperator(ctx);
2203
+ const id = chatApprovalId(opts.message);
2204
+ const candidates = chatApprovalCandidates(Object.values(ctx.store.snapshot.gates), id, caller);
2205
+ if (candidates.length !== 1) {
2206
+ const statuses = candidates.map((gate) => chatOfferStatus(ctx, gate, caller));
2207
+ return print({
2208
+ status: candidates.length ? 'ambiguous' : 'not-found',
2209
+ guidance: ambiguousGuidance(statuses),
2210
+ candidates: candidates.map((gate, i) => ambiguousCandidate(gate, statuses[i], caller)),
2211
+ });
2212
+ }
2213
+ const gate = candidates[0];
2214
+ if (gate.status === 'resolved')
2215
+ return print({ ...botDecisionStatus(gate), alreadyResolved: true });
2216
+ const status = chatOfferStatus(ctx, gate, caller);
2217
+ if (!status.ready)
2218
+ throw new InputError(status.message);
2219
+ const { offer } = status;
2220
+ if (offer.item && id === String(offer.item.number)) {
2221
+ assertOrcaItemInChat(await readOrcaItem(offer.item.number), caller, offer.item.number, '안내한 Orca 항목이 바뀌었어요. 다시 확인해 주세요', { expected: offer.item.uid });
2222
+ }
2223
+ print(await applyBotDecision(ctx, { caller, request: { decision: 'approved', chatOffer: offer, owner: caller, inputId: id } }, gate.id, offer.target, { head: offer.head, base: offer.base }));
2224
+ }
2225
+ catch (error) {
2226
+ exitWithError(error);
2227
+ }
2015
2228
  }
2016
2229
  export async function conductorBotDecideCommand(gateId, opts) {
2017
2230
  try {