@wjarka/cezarion 0.17.0 → 0.18.0-dev.5793
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin.js +2 -0
- package/cez.js +2 -0
- package/cezarion.js +2 -0
- package/dist/cez.js +2 -0
- package/dist/cezarion.js +2 -0
- package/dist/hsq.js +2 -0
- package/dist/index.js +1 -835
- package/dist/server/app-type.d.ts +1 -6
- package/dist/server/app-type.js +1 -2
- package/hsq.js +2 -0
- package/package.json +20 -59
- package/web/dist/assets/activity-motion-0wHCeUs7.css +1 -0
- package/web/dist/assets/activity-motion-2nE59DAT.js +2 -0
- package/web/dist/assets/activity-route-R9lPc2jy.js +1 -0
- package/web/dist/assets/agent-accounts-f1cxwgfz.js +18 -0
- package/web/dist/assets/alert-dialog-Dj464rjk.js +1 -0
- package/web/dist/assets/arrow-right-Dh_Lx3um.js +1 -0
- package/web/dist/assets/button-CHUAMTHK.js +3 -0
- package/web/dist/assets/centered-state-DGyy0SuA.js +1 -0
- package/web/dist/assets/cez-idle-EVoUsgU3.js +1 -0
- package/web/dist/assets/commit-diff-panel-BJyNYmCY.js +1 -0
- package/web/dist/assets/control-locations-C9II3kPz.js +1 -0
- package/web/dist/assets/design-icons-DmYTv2r1.js +1 -0
- package/web/dist/assets/diff-D_9MtICR.js +3 -0
- package/web/dist/assets/diff-controls-BR2uqhwG.js +1 -0
- package/web/dist/assets/diff-view-xRPxXHXl.js +11 -0
- package/web/dist/assets/dropdown-menu-DhrBcVgr.js +1 -0
- package/web/dist/assets/es2015-D345RR4o.js +41 -0
- package/web/dist/assets/file-preview-D08Kq15E.js +2 -0
- package/web/dist/assets/git-toolbar-D9taioU5.js +1 -0
- package/web/dist/assets/github-bv_pBGc5.js +1 -0
- package/web/dist/assets/github-sidebar-model-B0Ufci5S.js +1 -0
- package/web/dist/assets/global-activity-route-QxTPDyx-.js +1 -0
- package/web/dist/assets/hourglass-B0lPAJvT.js +1 -0
- package/web/dist/assets/{image-preview-C_t9q45f.js → image-preview-Cq1vDiEo.js} +1 -1
- package/web/dist/assets/index-B18AqW0Z.css +1 -0
- package/web/dist/assets/index-DgU3yYUl.js +14 -0
- package/web/dist/assets/index.global-D3Ga_D3Y.js +1 -0
- package/web/dist/assets/live-protocol-BVn0UA_g.js +64 -0
- package/web/dist/assets/live-refetch-BdnmTJ_8.js +1 -0
- package/web/dist/assets/{live-worker-BizfZSoh.ts → live-worker-BWdeGzQX.ts} +2 -1
- package/web/dist/assets/loader-circle-CZkGEdoI.js +1 -0
- package/web/dist/assets/markdown-D7DUNWcJ.js +6 -0
- package/web/dist/assets/mermaid.min-3O9YjB2l.js +1 -0
- package/web/dist/assets/message-square-B-MD-8rD.js +1 -0
- package/web/dist/assets/{nav-row-styles-AoIhhIwf.js → nav-row-styles-BZUUavOF.js} +1 -1
- package/web/dist/assets/popover-DRcRI46x.js +1 -0
- package/web/dist/assets/preview-pane-connected-cD-MTiVN.js +3 -0
- package/web/dist/assets/project-router-MMOk9VbW.js +1 -0
- package/web/dist/assets/project-scope-context-B3M-u8R0.js +4 -0
- package/web/dist/assets/queries-DORTKwyN.js +1 -0
- package/web/dist/assets/repo-git-E_4Ighvg.js +1 -0
- package/web/dist/assets/report-reader-XVNQsXB4.js +1 -0
- package/web/dist/assets/report-title-D4Mbu2Er.js +1 -0
- package/web/dist/assets/reports-B7QAzibP.css +1 -0
- package/web/dist/assets/reports-B_PVTBzP.js +1 -0
- package/web/dist/assets/run-header-wm0gSs6X.js +2 -0
- package/web/dist/assets/skill-empty-hint-YDmkqgo-.js +1 -0
- package/web/dist/assets/skills-D2RLxUIc.js +1 -0
- package/web/dist/assets/skills-DFBiAuJG.js +1 -0
- package/web/dist/assets/skills-workflows-C21NystW.css +1 -0
- package/web/dist/assets/sortable.esm-zp_qkYGV.js +5 -0
- package/web/dist/assets/tab-link-BvoGfK8S.js +1 -0
- package/web/dist/assets/task-changes-DNtkfFzQ.js +1 -0
- package/web/dist/assets/task-commits-CivO-OrN.js +1 -0
- package/web/dist/assets/task-files-dczkxV_G.js +1 -0
- package/web/dist/assets/task-github-item-DKV4yrcf.js +1 -0
- package/web/dist/assets/task-thread-DIaTTGEF.js +9 -0
- package/web/dist/assets/textarea-DlVUfdWG.js +1 -0
- package/web/dist/assets/thread-state-DIozHuHb.js +4 -0
- package/web/dist/assets/toaster-B1MyeHiE.js +1 -0
- package/web/dist/assets/use-hand-to-agent-state-D58ayxI4.js +1 -0
- package/web/dist/assets/useInfiniteQuery-BbYMWe23.js +1 -0
- package/web/dist/assets/useQuery-CqqnAJvu.js +1 -0
- package/web/dist/assets/workflows-YMEsGXeB.js +7 -0
- package/web/dist/assets/ws-BtSVmivO.js +1 -0
- package/web/dist/assets/zoomable-image-5pOUaPEg.js +1 -0
- package/web/dist/index.html +31 -15
- package/web/dist/live-worker.js +2 -2
- package/LICENSE +0 -22
- package/README.md +0 -1725
- package/dist/agent-config/account-identity.d.ts +0 -28
- package/dist/agent-config/account-identity.js +0 -131
- package/dist/agent-config/account-identity.js.map +0 -1
- package/dist/agent-config/catalog.d.ts +0 -70
- package/dist/agent-config/catalog.js +0 -383
- package/dist/agent-config/catalog.js.map +0 -1
- package/dist/agent-config/files.d.ts +0 -42
- package/dist/agent-config/files.js +0 -115
- package/dist/agent-config/files.js.map +0 -1
- package/dist/agent-config/model-settings/claude.d.ts +0 -2
- package/dist/agent-config/model-settings/claude.js +0 -11
- package/dist/agent-config/model-settings/claude.js.map +0 -1
- package/dist/agent-config/model-settings/codex.d.ts +0 -2
- package/dist/agent-config/model-settings/codex.js +0 -16
- package/dist/agent-config/model-settings/codex.js.map +0 -1
- package/dist/agent-config/model-settings/opencode.d.ts +0 -2
- package/dist/agent-config/model-settings/opencode.js +0 -8
- package/dist/agent-config/model-settings/opencode.js.map +0 -1
- package/dist/agent-config/model-settings/pi.d.ts +0 -2
- package/dist/agent-config/model-settings/pi.js +0 -38
- package/dist/agent-config/model-settings/pi.js.map +0 -1
- package/dist/agent-config/model-settings/shared.d.ts +0 -12
- package/dist/agent-config/model-settings/shared.js +0 -100
- package/dist/agent-config/model-settings/shared.js.map +0 -1
- package/dist/agent-config/model-settings/types.d.ts +0 -9
- package/dist/agent-config/model-settings/types.js +0 -2
- package/dist/agent-config/model-settings/types.js.map +0 -1
- package/dist/agent-config/models.d.ts +0 -9
- package/dist/agent-config/models.js +0 -40
- package/dist/agent-config/models.js.map +0 -1
- package/dist/agent-config/seed.d.ts +0 -15
- package/dist/agent-config/seed.js +0 -94
- package/dist/agent-config/seed.js.map +0 -1
- package/dist/agent-config/service.d.ts +0 -44
- package/dist/agent-config/service.js +0 -72
- package/dist/agent-config/service.js.map +0 -1
- package/dist/agent-config/validate.d.ts +0 -18
- package/dist/agent-config/validate.js +0 -82
- package/dist/agent-config/validate.js.map +0 -1
- package/dist/application-update/bin-recovery.d.ts +0 -5
- package/dist/application-update/bin-recovery.js +0 -96
- package/dist/application-update/bin-recovery.js.map +0 -1
- package/dist/application-update/discovery.d.ts +0 -22
- package/dist/application-update/discovery.js +0 -91
- package/dist/application-update/discovery.js.map +0 -1
- package/dist/application-update/helper.d.ts +0 -57
- package/dist/application-update/helper.js +0 -369
- package/dist/application-update/helper.js.map +0 -1
- package/dist/application-update/launcher.d.ts +0 -12
- package/dist/application-update/launcher.js +0 -59
- package/dist/application-update/launcher.js.map +0 -1
- package/dist/application-update/lock.d.ts +0 -4
- package/dist/application-update/lock.js +0 -70
- package/dist/application-update/lock.js.map +0 -1
- package/dist/application-update/npm-process.d.ts +0 -17
- package/dist/application-update/npm-process.js +0 -133
- package/dist/application-update/npm-process.js.map +0 -1
- package/dist/application-update/service.d.ts +0 -69
- package/dist/application-update/service.js +0 -456
- package/dist/application-update/service.js.map +0 -1
- package/dist/archive-on-merge-setting.d.ts +0 -15
- package/dist/archive-on-merge-setting.js +0 -14
- package/dist/archive-on-merge-setting.js.map +0 -1
- package/dist/artifacts/cli.d.ts +0 -9
- package/dist/artifacts/cli.js +0 -59
- package/dist/artifacts/cli.js.map +0 -1
- package/dist/artifacts/lifecycle.d.ts +0 -4
- package/dist/artifacts/lifecycle.js +0 -42
- package/dist/artifacts/lifecycle.js.map +0 -1
- package/dist/artifacts/resolve.d.ts +0 -18
- package/dist/artifacts/resolve.js +0 -103
- package/dist/artifacts/resolve.js.map +0 -1
- package/dist/artifacts/store.d.ts +0 -8
- package/dist/artifacts/store.js +0 -323
- package/dist/artifacts/store.js.map +0 -1
- package/dist/automations/automation-cli.d.ts +0 -59
- package/dist/automations/automation-cli.js +0 -509
- package/dist/automations/automation-cli.js.map +0 -1
- package/dist/automations/builtin-skill.d.ts +0 -7
- package/dist/automations/builtin-skill.js +0 -14
- package/dist/automations/builtin-skill.js.map +0 -1
- package/dist/automations/coordinator.d.ts +0 -33
- package/dist/automations/coordinator.js +0 -86
- package/dist/automations/coordinator.js.map +0 -1
- package/dist/automations/github-baseline.d.ts +0 -3
- package/dist/automations/github-baseline.js +0 -17
- package/dist/automations/github-baseline.js.map +0 -1
- package/dist/automations/github-poller.d.ts +0 -93
- package/dist/automations/github-poller.js +0 -303
- package/dist/automations/github-poller.js.map +0 -1
- package/dist/automations/prompts.d.ts +0 -12
- package/dist/automations/prompts.js +0 -160
- package/dist/automations/prompts.js.map +0 -1
- package/dist/automations/schedule-runner.d.ts +0 -149
- package/dist/automations/schedule-runner.js +0 -513
- package/dist/automations/schedule-runner.js.map +0 -1
- package/dist/automations/scheduler.d.ts +0 -87
- package/dist/automations/scheduler.js +0 -434
- package/dist/automations/scheduler.js.map +0 -1
- package/dist/automations/service.d.ts +0 -777
- package/dist/automations/service.js +0 -444
- package/dist/automations/service.js.map +0 -1
- package/dist/automations/store.d.ts +0 -160
- package/dist/automations/store.js +0 -738
- package/dist/automations/store.js.map +0 -1
- package/dist/automations/task-template.d.ts +0 -59
- package/dist/automations/task-template.js +0 -273
- package/dist/automations/task-template.js.map +0 -1
- package/dist/automations/tool-adapter.d.ts +0 -6
- package/dist/automations/tool-adapter.js +0 -108
- package/dist/automations/tool-adapter.js.map +0 -1
- package/dist/automations/types.d.ts +0 -1
- package/dist/automations/types.js +0 -2
- package/dist/automations/types.js.map +0 -1
- package/dist/autosave-cleanup.d.ts +0 -26
- package/dist/autosave-cleanup.js +0 -87
- package/dist/autosave-cleanup.js.map +0 -1
- package/dist/autosave-git.d.ts +0 -21
- package/dist/autosave-git.js +0 -204
- package/dist/autosave-git.js.map +0 -1
- package/dist/autosave-group.d.ts +0 -8
- package/dist/autosave-group.js +0 -61
- package/dist/autosave-group.js.map +0 -1
- package/dist/autosave-holders.d.ts +0 -34
- package/dist/autosave-holders.js +0 -204
- package/dist/autosave-holders.js.map +0 -1
- package/dist/autosave-windows.d.ts +0 -25
- package/dist/autosave-windows.js +0 -156
- package/dist/autosave-windows.js.map +0 -1
- package/dist/ci-wait/client.d.ts +0 -28
- package/dist/ci-wait/client.js +0 -105
- package/dist/ci-wait/client.js.map +0 -1
- package/dist/ci-wait/controller.d.ts +0 -756
- package/dist/ci-wait/controller.js +0 -334
- package/dist/ci-wait/controller.js.map +0 -1
- package/dist/ci-wait/errors.d.ts +0 -27
- package/dist/ci-wait/errors.js +0 -252
- package/dist/ci-wait/errors.js.map +0 -1
- package/dist/ci-wait/github.d.ts +0 -87
- package/dist/ci-wait/github.js +0 -278
- package/dist/ci-wait/github.js.map +0 -1
- package/dist/ci-wait/injection.d.ts +0 -3
- package/dist/ci-wait/injection.js +0 -26
- package/dist/ci-wait/injection.js.map +0 -1
- package/dist/ci-wait/mcp.d.ts +0 -3
- package/dist/ci-wait/mcp.js +0 -30
- package/dist/ci-wait/mcp.js.map +0 -1
- package/dist/ci-wait/resources.d.ts +0 -7
- package/dist/ci-wait/resources.js +0 -32
- package/dist/ci-wait/resources.js.map +0 -1
- package/dist/ci-wait/supervisor.d.ts +0 -29
- package/dist/ci-wait/supervisor.js +0 -260
- package/dist/ci-wait/supervisor.js.map +0 -1
- package/dist/ci-wait/tools.d.ts +0 -827
- package/dist/ci-wait/tools.js +0 -208
- package/dist/ci-wait/tools.js.map +0 -1
- package/dist/config.d.ts +0 -68
- package/dist/config.js +0 -209
- package/dist/config.js.map +0 -1
- package/dist/contract/active-provider.d.ts +0 -12
- package/dist/contract/agent-config.d.ts +0 -160
- package/dist/contract/agent-profiles.d.ts +0 -369
- package/dist/contract/application-update.d.ts +0 -32
- package/dist/contract/artifacts.d.ts +0 -83
- package/dist/contract/ask-schema.d.ts +0 -50
- package/dist/contract/ask.d.ts +0 -9
- package/dist/contract/attachments.d.ts +0 -35
- package/dist/contract/attention.d.ts +0 -90
- package/dist/contract/automation-requests.d.ts +0 -308
- package/dist/contract/automation-schedule.d.ts +0 -89
- package/dist/contract/automation-storage.d.ts +0 -512
- package/dist/contract/automations.d.ts +0 -1542
- package/dist/contract/ci-wait.d.ts +0 -222
- package/dist/contract/config-requests.d.ts +0 -36
- package/dist/contract/conversations.d.ts +0 -351
- package/dist/contract/defined.d.ts +0 -8
- package/dist/contract/delegation.d.ts +0 -1882
- package/dist/contract/discovery.d.ts +0 -141
- package/dist/contract/effort.d.ts +0 -18
- package/dist/contract/events.d.ts +0 -292
- package/dist/contract/github-requests.d.ts +0 -26
- package/dist/contract/github.d.ts +0 -732
- package/dist/contract/handoff.d.ts +0 -43
- package/dist/contract/health.d.ts +0 -124
- package/dist/contract/image-path.d.ts +0 -6
- package/dist/contract/index.d.ts +0 -59
- package/dist/contract/index.js +0 -5887
- package/dist/contract/live-coordination.d.ts +0 -158
- package/dist/contract/live-limits.d.ts +0 -8
- package/dist/contract/live.d.ts +0 -123
- package/dist/contract/pending-ask.d.ts +0 -58
- package/dist/contract/permissions.d.ts +0 -54
- package/dist/contract/preview.d.ts +0 -541
- package/dist/contract/project-limits.d.ts +0 -33
- package/dist/contract/projects.d.ts +0 -716
- package/dist/contract/provider-requests.d.ts +0 -77
- package/dist/contract/query-requests.d.ts +0 -52
- package/dist/contract/repo-requests.d.ts +0 -12
- package/dist/contract/repo.d.ts +0 -496
- package/dist/contract/run-labels.d.ts +0 -8
- package/dist/contract/run-limits.d.ts +0 -8
- package/dist/contract/run-predicates.d.ts +0 -32
- package/dist/contract/run-requests.d.ts +0 -33
- package/dist/contract/run-search.d.ts +0 -193
- package/dist/contract/runs.d.ts +0 -5340
- package/dist/contract/scheduled-tasks.d.ts +0 -187
- package/dist/contract/skills.d.ts +0 -56
- package/dist/contract/team-skill-ref.d.ts +0 -10
- package/dist/contract/tool-display.d.ts +0 -25
- package/dist/contract/ui-state-requests.d.ts +0 -60
- package/dist/contract/version.d.ts +0 -3
- package/dist/contract/voice.d.ts +0 -213
- package/dist/contract/waits.d.ts +0 -1204
- package/dist/contract/workflow-file.d.ts +0 -37
- package/dist/contract/workflow-requests.d.ts +0 -7
- package/dist/contract/workflows.d.ts +0 -250
- package/dist/contract/workspace.d.ts +0 -631
- package/dist/contract/zoned-time.d.ts +0 -26
- package/dist/core/agent-env.d.ts +0 -30
- package/dist/core/agent-env.js +0 -400
- package/dist/core/agent-env.js.map +0 -1
- package/dist/core/agent-model-policy.d.ts +0 -10
- package/dist/core/agent-model-policy.js +0 -36
- package/dist/core/agent-model-policy.js.map +0 -1
- package/dist/core/agent-profiles.d.ts +0 -50
- package/dist/core/agent-profiles.js +0 -105
- package/dist/core/agent-profiles.js.map +0 -1
- package/dist/core/agent-runner.d.ts +0 -394
- package/dist/core/agent-runner.js +0 -96
- package/dist/core/agent-runner.js.map +0 -1
- package/dist/core/ask.d.ts +0 -79
- package/dist/core/ask.js +0 -232
- package/dist/core/ask.js.map +0 -1
- package/dist/core/backend-detect.d.ts +0 -17
- package/dist/core/backend-detect.js +0 -209
- package/dist/core/backend-detect.js.map +0 -1
- package/dist/core/claude-cli-runner.d.ts +0 -72
- package/dist/core/claude-cli-runner.js +0 -910
- package/dist/core/claude-cli-runner.js.map +0 -1
- package/dist/core/claude-model-catalog.d.ts +0 -16
- package/dist/core/claude-model-catalog.js +0 -198
- package/dist/core/claude-model-catalog.js.map +0 -1
- package/dist/core/claude-ui-mapper.d.ts +0 -80
- package/dist/core/claude-ui-mapper.js +0 -696
- package/dist/core/claude-ui-mapper.js.map +0 -1
- package/dist/core/codex-app-server-runner.d.ts +0 -61
- package/dist/core/codex-app-server-runner.js +0 -1278
- package/dist/core/codex-app-server-runner.js.map +0 -1
- package/dist/core/codex-app-server-transport.d.ts +0 -52
- package/dist/core/codex-app-server-transport.js +0 -199
- package/dist/core/codex-app-server-transport.js.map +0 -1
- package/dist/core/codex-approvals.d.ts +0 -12
- package/dist/core/codex-approvals.js +0 -161
- package/dist/core/codex-approvals.js.map +0 -1
- package/dist/core/codex-model-catalog.d.ts +0 -10
- package/dist/core/codex-model-catalog.js +0 -110
- package/dist/core/codex-model-catalog.js.map +0 -1
- package/dist/core/codex-permissions.d.ts +0 -6
- package/dist/core/codex-permissions.js +0 -27
- package/dist/core/codex-permissions.js.map +0 -1
- package/dist/core/codex-stream-error.d.ts +0 -2
- package/dist/core/codex-stream-error.js +0 -12
- package/dist/core/codex-stream-error.js.map +0 -1
- package/dist/core/codex-turn-outcome.d.ts +0 -8
- package/dist/core/codex-turn-outcome.js +0 -30
- package/dist/core/codex-turn-outcome.js.map +0 -1
- package/dist/core/codex-ui-mapper.d.ts +0 -112
- package/dist/core/codex-ui-mapper.js +0 -808
- package/dist/core/codex-ui-mapper.js.map +0 -1
- package/dist/core/cursor-acp-runner.d.ts +0 -34
- package/dist/core/cursor-acp-runner.js +0 -777
- package/dist/core/cursor-acp-runner.js.map +0 -1
- package/dist/core/cursor-cli-flags.d.ts +0 -19
- package/dist/core/cursor-cli-flags.js +0 -47
- package/dist/core/cursor-cli-flags.js.map +0 -1
- package/dist/core/cursor-config-options.d.ts +0 -18
- package/dist/core/cursor-config-options.js +0 -31
- package/dist/core/cursor-config-options.js.map +0 -1
- package/dist/core/cursor-model-catalog.d.ts +0 -45
- package/dist/core/cursor-model-catalog.js +0 -300
- package/dist/core/cursor-model-catalog.js.map +0 -1
- package/dist/core/cursor-print-capabilities.d.ts +0 -16
- package/dist/core/cursor-print-capabilities.js +0 -141
- package/dist/core/cursor-print-capabilities.js.map +0 -1
- package/dist/core/cursor-print-process.d.ts +0 -31
- package/dist/core/cursor-print-process.js +0 -117
- package/dist/core/cursor-print-process.js.map +0 -1
- package/dist/core/cursor-print-runner.d.ts +0 -31
- package/dist/core/cursor-print-runner.js +0 -555
- package/dist/core/cursor-print-runner.js.map +0 -1
- package/dist/core/cursor-print-tool-catalog.d.ts +0 -10
- package/dist/core/cursor-print-tool-catalog.js +0 -91
- package/dist/core/cursor-print-tool-catalog.js.map +0 -1
- package/dist/core/cursor-print-ui-mapper.d.ts +0 -47
- package/dist/core/cursor-print-ui-mapper.js +0 -553
- package/dist/core/cursor-print-ui-mapper.js.map +0 -1
- package/dist/core/cursor-provider-error.d.ts +0 -33
- package/dist/core/cursor-provider-error.js +0 -68
- package/dist/core/cursor-provider-error.js.map +0 -1
- package/dist/core/cursor-runner.d.ts +0 -24
- package/dist/core/cursor-runner.js +0 -149
- package/dist/core/cursor-runner.js.map +0 -1
- package/dist/core/cursor-ui-mapper.d.ts +0 -29
- package/dist/core/cursor-ui-mapper.js +0 -275
- package/dist/core/cursor-ui-mapper.js.map +0 -1
- package/dist/core/defined.d.ts +0 -1
- package/dist/core/defined.js +0 -2
- package/dist/core/defined.js.map +0 -1
- package/dist/core/hook-items.d.ts +0 -14
- package/dist/core/hook-items.js +0 -13
- package/dist/core/hook-items.js.map +0 -1
- package/dist/core/host-model-catalog.d.ts +0 -7
- package/dist/core/host-model-catalog.js +0 -21
- package/dist/core/host-model-catalog.js.map +0 -1
- package/dist/core/input-submissions.d.ts +0 -14
- package/dist/core/input-submissions.js +0 -26
- package/dist/core/input-submissions.js.map +0 -1
- package/dist/core/managed-session.d.ts +0 -6
- package/dist/core/managed-session.js +0 -116
- package/dist/core/managed-session.js.map +0 -1
- package/dist/core/model-identity.d.ts +0 -108
- package/dist/core/model-identity.js +0 -137
- package/dist/core/model-identity.js.map +0 -1
- package/dist/core/model-presets.d.ts +0 -10
- package/dist/core/model-presets.js +0 -77
- package/dist/core/model-presets.js.map +0 -1
- package/dist/core/ndjson.d.ts +0 -6
- package/dist/core/ndjson.js +0 -23
- package/dist/core/ndjson.js.map +0 -1
- package/dist/core/omp-model-catalog.d.ts +0 -43
- package/dist/core/omp-model-catalog.js +0 -205
- package/dist/core/omp-model-catalog.js.map +0 -1
- package/dist/core/omp-runner.d.ts +0 -72
- package/dist/core/omp-runner.js +0 -1049
- package/dist/core/omp-runner.js.map +0 -1
- package/dist/core/omp-ui-mapper.d.ts +0 -106
- package/dist/core/omp-ui-mapper.js +0 -882
- package/dist/core/omp-ui-mapper.js.map +0 -1
- package/dist/core/opencode-model-catalog.d.ts +0 -32
- package/dist/core/opencode-model-catalog.js +0 -215
- package/dist/core/opencode-model-catalog.js.map +0 -1
- package/dist/core/opencode-permissions.d.ts +0 -52
- package/dist/core/opencode-permissions.js +0 -101
- package/dist/core/opencode-permissions.js.map +0 -1
- package/dist/core/opencode-server-runner.d.ts +0 -61
- package/dist/core/opencode-server-runner.js +0 -1692
- package/dist/core/opencode-server-runner.js.map +0 -1
- package/dist/core/opencode-session-error.d.ts +0 -19
- package/dist/core/opencode-session-error.js +0 -42
- package/dist/core/opencode-session-error.js.map +0 -1
- package/dist/core/opencode-ui-mapper.d.ts +0 -137
- package/dist/core/opencode-ui-mapper.js +0 -768
- package/dist/core/opencode-ui-mapper.js.map +0 -1
- package/dist/core/pi-model-catalog.d.ts +0 -38
- package/dist/core/pi-model-catalog.js +0 -249
- package/dist/core/pi-model-catalog.js.map +0 -1
- package/dist/core/pi-runner.d.ts +0 -43
- package/dist/core/pi-runner.js +0 -827
- package/dist/core/pi-runner.js.map +0 -1
- package/dist/core/pi-ui-mapper.d.ts +0 -52
- package/dist/core/pi-ui-mapper.js +0 -395
- package/dist/core/pi-ui-mapper.js.map +0 -1
- package/dist/core/process-usage.d.ts +0 -74
- package/dist/core/process-usage.js +0 -218
- package/dist/core/process-usage.js.map +0 -1
- package/dist/core/provider-auth.d.ts +0 -168
- package/dist/core/provider-auth.js +0 -660
- package/dist/core/provider-auth.js.map +0 -1
- package/dist/core/provider-availability.d.ts +0 -3
- package/dist/core/provider-availability.js +0 -14
- package/dist/core/provider-availability.js.map +0 -1
- package/dist/core/runner-factory.d.ts +0 -11
- package/dist/core/runner-factory.js +0 -31
- package/dist/core/runner-factory.js.map +0 -1
- package/dist/core/runner-model-catalog.d.ts +0 -34
- package/dist/core/runner-model-catalog.js +0 -109
- package/dist/core/runner-model-catalog.js.map +0 -1
- package/dist/core/runner-runtime.d.ts +0 -40
- package/dist/core/runner-runtime.js +0 -88
- package/dist/core/runner-runtime.js.map +0 -1
- package/dist/core/runner-stderr.d.ts +0 -2
- package/dist/core/runner-stderr.js +0 -20
- package/dist/core/runner-stderr.js.map +0 -1
- package/dist/core/runner-tool-grants.d.ts +0 -21
- package/dist/core/runner-tool-grants.js +0 -64
- package/dist/core/runner-tool-grants.js.map +0 -1
- package/dist/core/secret-redaction.d.ts +0 -20
- package/dist/core/secret-redaction.js +0 -98
- package/dist/core/secret-redaction.js.map +0 -1
- package/dist/core/session-process.d.ts +0 -42
- package/dist/core/session-process.js +0 -360
- package/dist/core/session-process.js.map +0 -1
- package/dist/core/shell-env.d.ts +0 -17
- package/dist/core/shell-env.js +0 -51
- package/dist/core/shell-env.js.map +0 -1
- package/dist/core/ui-events.d.ts +0 -348
- package/dist/core/ui-events.js +0 -2
- package/dist/core/ui-events.js.map +0 -1
- package/dist/core/usage-limit.d.ts +0 -42
- package/dist/core/usage-limit.js +0 -152
- package/dist/core/usage-limit.js.map +0 -1
- package/dist/core/usage.d.ts +0 -11
- package/dist/core/usage.js +0 -15
- package/dist/core/usage.js.map +0 -1
- package/dist/core/v1-text-coalescer.d.ts +0 -36
- package/dist/core/v1-text-coalescer.js +0 -72
- package/dist/core/v1-text-coalescer.js.map +0 -1
- package/dist/data-gitignore.d.ts +0 -6
- package/dist/data-gitignore.js +0 -59
- package/dist/data-gitignore.js.map +0 -1
- package/dist/delegation/capacity.d.ts +0 -15
- package/dist/delegation/capacity.js +0 -30
- package/dist/delegation/capacity.js.map +0 -1
- package/dist/delegation/cli.d.ts +0 -4
- package/dist/delegation/cli.js +0 -481
- package/dist/delegation/cli.js.map +0 -1
- package/dist/delegation/context.d.ts +0 -40
- package/dist/delegation/context.js +0 -378
- package/dist/delegation/context.js.map +0 -1
- package/dist/delegation/conversations.d.ts +0 -9
- package/dist/delegation/conversations.js +0 -66
- package/dist/delegation/conversations.js.map +0 -1
- package/dist/delegation/credentials.d.ts +0 -21
- package/dist/delegation/credentials.js +0 -66
- package/dist/delegation/credentials.js.map +0 -1
- package/dist/delegation/destroy-observation.d.ts +0 -42
- package/dist/delegation/destroy-observation.js +0 -115
- package/dist/delegation/destroy-observation.js.map +0 -1
- package/dist/delegation/effort.d.ts +0 -1
- package/dist/delegation/effort.js +0 -11
- package/dist/delegation/effort.js.map +0 -1
- package/dist/delegation/execution-identity.d.ts +0 -180
- package/dist/delegation/execution-identity.js +0 -154
- package/dist/delegation/execution-identity.js.map +0 -1
- package/dist/delegation/idle-test-app.d.ts +0 -4
- package/dist/delegation/idle-test-app.js +0 -174
- package/dist/delegation/idle-test-app.js.map +0 -1
- package/dist/delegation/input.d.ts +0 -12
- package/dist/delegation/input.js +0 -50
- package/dist/delegation/input.js.map +0 -1
- package/dist/delegation/park-notice.d.ts +0 -42
- package/dist/delegation/park-notice.js +0 -71
- package/dist/delegation/park-notice.js.map +0 -1
- package/dist/delegation/policy.d.ts +0 -22
- package/dist/delegation/policy.js +0 -95
- package/dist/delegation/policy.js.map +0 -1
- package/dist/delegation/process-liveness.d.ts +0 -98
- package/dist/delegation/process-liveness.js +0 -213
- package/dist/delegation/process-liveness.js.map +0 -1
- package/dist/delegation/provision.d.ts +0 -32
- package/dist/delegation/provision.js +0 -177
- package/dist/delegation/provision.js.map +0 -1
- package/dist/delegation/questions.d.ts +0 -21
- package/dist/delegation/questions.js +0 -50
- package/dist/delegation/questions.js.map +0 -1
- package/dist/delegation/readiness.d.ts +0 -13
- package/dist/delegation/readiness.js +0 -19
- package/dist/delegation/readiness.js.map +0 -1
- package/dist/delegation/results.d.ts +0 -13
- package/dist/delegation/results.js +0 -154
- package/dist/delegation/results.js.map +0 -1
- package/dist/delegation/retry-backoff.d.ts +0 -31
- package/dist/delegation/retry-backoff.js +0 -26
- package/dist/delegation/retry-backoff.js.map +0 -1
- package/dist/delegation/routes.d.ts +0 -953
- package/dist/delegation/routes.js +0 -74
- package/dist/delegation/routes.js.map +0 -1
- package/dist/delegation/scratch-cleanup.d.ts +0 -28
- package/dist/delegation/scratch-cleanup.js +0 -145
- package/dist/delegation/scratch-cleanup.js.map +0 -1
- package/dist/delegation/service.d.ts +0 -211
- package/dist/delegation/service.js +0 -946
- package/dist/delegation/service.js.map +0 -1
- package/dist/delegation/transport.d.ts +0 -931
- package/dist/delegation/transport.js +0 -22
- package/dist/delegation/transport.js.map +0 -1
- package/dist/delegation/wait.d.ts +0 -14
- package/dist/delegation/wait.js +0 -72
- package/dist/delegation/wait.js.map +0 -1
- package/dist/delegation/windows-test-app.d.ts +0 -5
- package/dist/delegation/windows-test-app.js +0 -63
- package/dist/delegation/windows-test-app.js.map +0 -1
- package/dist/delegation/windows-workspace-identity.d.ts +0 -3
- package/dist/delegation/windows-workspace-identity.js +0 -22
- package/dist/delegation/windows-workspace-identity.js.map +0 -1
- package/dist/delegation/workspace.d.ts +0 -33
- package/dist/delegation/workspace.js +0 -556
- package/dist/delegation/workspace.js.map +0 -1
- package/dist/detached-process.d.ts +0 -103
- package/dist/detached-process.js +0 -301
- package/dist/detached-process.js.map +0 -1
- package/dist/discovery/catalog.d.ts +0 -15
- package/dist/discovery/catalog.js +0 -31
- package/dist/discovery/catalog.js.map +0 -1
- package/dist/discovery/cli.d.ts +0 -8
- package/dist/discovery/cli.js +0 -106
- package/dist/discovery/cli.js.map +0 -1
- package/dist/git-diff-base.d.ts +0 -41
- package/dist/git-diff-base.js +0 -116
- package/dist/git-diff-base.js.map +0 -1
- package/dist/git-index-copy.d.ts +0 -4
- package/dist/git-index-copy.js +0 -10
- package/dist/git-index-copy.js.map +0 -1
- package/dist/git-refs.d.ts +0 -11
- package/dist/git-refs.js +0 -14
- package/dist/git-refs.js.map +0 -1
- package/dist/git-worktree-lock-helper.d.ts +0 -7
- package/dist/git-worktree-lock-helper.js +0 -158
- package/dist/git-worktree-lock-helper.js.map +0 -1
- package/dist/git-worktree-lock.d.ts +0 -17
- package/dist/git-worktree-lock.js +0 -90
- package/dist/git-worktree-lock.js.map +0 -1
- package/dist/git-worktree-release.d.ts +0 -20
- package/dist/git-worktree-release.js +0 -27
- package/dist/git-worktree-release.js.map +0 -1
- package/dist/git-worktree.d.ts +0 -154
- package/dist/git-worktree.js +0 -858
- package/dist/git-worktree.js.map +0 -1
- package/dist/handoff.d.ts +0 -72
- package/dist/handoff.js +0 -206
- package/dist/handoff.js.map +0 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.js.map +0 -1
- package/dist/install-as-command.d.ts +0 -40
- package/dist/install-as-command.js +0 -52
- package/dist/install-as-command.js.map +0 -1
- package/dist/merge-observations.d.ts +0 -13
- package/dist/merge-observations.js +0 -55
- package/dist/merge-observations.js.map +0 -1
- package/dist/open-url.d.ts +0 -2
- package/dist/open-url.js +0 -10
- package/dist/open-url.js.map +0 -1
- package/dist/pack-check.d.ts +0 -17
- package/dist/pack-check.js +0 -27
- package/dist/pack-check.js.map +0 -1
- package/dist/paths.d.ts +0 -138
- package/dist/paths.js +0 -220
- package/dist/paths.js.map +0 -1
- package/dist/planner.d.ts +0 -28
- package/dist/planner.js +0 -271
- package/dist/planner.js.map +0 -1
- package/dist/preview/agent-address.d.ts +0 -34
- package/dist/preview/agent-address.js +0 -51
- package/dist/preview/agent-address.js.map +0 -1
- package/dist/preview/agent-marker.d.ts +0 -17
- package/dist/preview/agent-marker.js +0 -71
- package/dist/preview/agent-marker.js.map +0 -1
- package/dist/preview/cdp-proxy.d.ts +0 -54
- package/dist/preview/cdp-proxy.js +0 -151
- package/dist/preview/cdp-proxy.js.map +0 -1
- package/dist/preview/cdp.d.ts +0 -49
- package/dist/preview/cdp.js +0 -167
- package/dist/preview/cdp.js.map +0 -1
- package/dist/preview/chromium.d.ts +0 -87
- package/dist/preview/chromium.js +0 -481
- package/dist/preview/chromium.js.map +0 -1
- package/dist/preview/dev-server.d.ts +0 -68
- package/dist/preview/dev-server.js +0 -317
- package/dist/preview/dev-server.js.map +0 -1
- package/dist/preview/host.d.ts +0 -221
- package/dist/preview/host.js +0 -967
- package/dist/preview/host.js.map +0 -1
- package/dist/preview/registration.d.ts +0 -68
- package/dist/preview/registration.js +0 -111
- package/dist/preview/registration.js.map +0 -1
- package/dist/preview/session.d.ts +0 -75
- package/dist/preview/session.js +0 -357
- package/dist/preview/session.js.map +0 -1
- package/dist/preview/url.d.ts +0 -6
- package/dist/preview/url.js +0 -17
- package/dist/preview/url.js.map +0 -1
- package/dist/process-wait/exit-file.d.ts +0 -29
- package/dist/process-wait/exit-file.js +0 -67
- package/dist/process-wait/exit-file.js.map +0 -1
- package/dist/process-wait/supervisor.d.ts +0 -30
- package/dist/process-wait/supervisor.js +0 -71
- package/dist/process-wait/supervisor.js.map +0 -1
- package/dist/release/manifests.d.ts +0 -103
- package/dist/release/manifests.js +0 -90
- package/dist/release/manifests.js.map +0 -1
- package/dist/release/snapshot.d.ts +0 -67
- package/dist/release/snapshot.js +0 -97
- package/dist/release/snapshot.js.map +0 -1
- package/dist/release/stable.d.ts +0 -38
- package/dist/release/stable.js +0 -55
- package/dist/release/stable.js.map +0 -1
- package/dist/runs/agent-tmpdir-removal.d.ts +0 -15
- package/dist/runs/agent-tmpdir-removal.js +0 -60
- package/dist/runs/agent-tmpdir-removal.js.map +0 -1
- package/dist/runs/agent-tmpdir.d.ts +0 -119
- package/dist/runs/agent-tmpdir.js +0 -829
- package/dist/runs/agent-tmpdir.js.map +0 -1
- package/dist/runs/arm-repo-handle.d.ts +0 -9
- package/dist/runs/arm-repo-handle.js +0 -45
- package/dist/runs/arm-repo-handle.js.map +0 -1
- package/dist/runs/auto-name.d.ts +0 -75
- package/dist/runs/auto-name.js +0 -179
- package/dist/runs/auto-name.js.map +0 -1
- package/dist/runs/client-request.d.ts +0 -11
- package/dist/runs/client-request.js +0 -26
- package/dist/runs/client-request.js.map +0 -1
- package/dist/runs/delegation-state.d.ts +0 -400
- package/dist/runs/delegation-state.js +0 -22
- package/dist/runs/delegation-state.js.map +0 -1
- package/dist/runs/event-history-agent-context.d.ts +0 -14
- package/dist/runs/event-history-agent-context.js +0 -105
- package/dist/runs/event-history-agent-context.js.map +0 -1
- package/dist/runs/event-history-context.d.ts +0 -15
- package/dist/runs/event-history-context.js +0 -109
- package/dist/runs/event-history-context.js.map +0 -1
- package/dist/runs/event-history.d.ts +0 -53
- package/dist/runs/event-history.js +0 -535
- package/dist/runs/event-history.js.map +0 -1
- package/dist/runs/history-compressor.d.ts +0 -29
- package/dist/runs/history-compressor.js +0 -116
- package/dist/runs/history-compressor.js.map +0 -1
- package/dist/runs/history-file.d.ts +0 -36
- package/dist/runs/history-file.js +0 -463
- package/dist/runs/history-file.js.map +0 -1
- package/dist/runs/history-stream.d.ts +0 -2
- package/dist/runs/history-stream.js +0 -62
- package/dist/runs/history-stream.js.map +0 -1
- package/dist/runs/legacy-index.d.ts +0 -49
- package/dist/runs/legacy-index.js +0 -155
- package/dist/runs/legacy-index.js.map +0 -1
- package/dist/runs/live-item-snapshots.d.ts +0 -13
- package/dist/runs/live-item-snapshots.js +0 -79
- package/dist/runs/live-item-snapshots.js.map +0 -1
- package/dist/runs/loaded-run-healing.d.ts +0 -3
- package/dist/runs/loaded-run-healing.js +0 -17
- package/dist/runs/loaded-run-healing.js.map +0 -1
- package/dist/runs/outcome-commit.d.ts +0 -98
- package/dist/runs/outcome-commit.js +0 -132
- package/dist/runs/outcome-commit.js.map +0 -1
- package/dist/runs/pull-requests.d.ts +0 -14
- package/dist/runs/pull-requests.js +0 -96
- package/dist/runs/pull-requests.js.map +0 -1
- package/dist/runs/raw-record.d.ts +0 -40
- package/dist/runs/raw-record.js +0 -133
- package/dist/runs/raw-record.js.map +0 -1
- package/dist/runs/retention.d.ts +0 -91
- package/dist/runs/retention.js +0 -182
- package/dist/runs/retention.js.map +0 -1
- package/dist/runs/review-gate.d.ts +0 -18
- package/dist/runs/review-gate.js +0 -21
- package/dist/runs/review-gate.js.map +0 -1
- package/dist/runs/run-claims.d.ts +0 -16
- package/dist/runs/run-claims.js +0 -24
- package/dist/runs/run-claims.js.map +0 -1
- package/dist/runs/run-database.d.ts +0 -380
- package/dist/runs/run-database.js +0 -1008
- package/dist/runs/run-database.js.map +0 -1
- package/dist/runs/run-index.d.ts +0 -26
- package/dist/runs/run-index.js +0 -212
- package/dist/runs/run-index.js.map +0 -1
- package/dist/runs/run-row.d.ts +0 -15
- package/dist/runs/run-row.js +0 -59
- package/dist/runs/run-row.js.map +0 -1
- package/dist/runs/store-open-error.d.ts +0 -24
- package/dist/runs/store-open-error.js +0 -61
- package/dist/runs/store-open-error.js.map +0 -1
- package/dist/runs/store.d.ts +0 -3090
- package/dist/runs/store.js +0 -4693
- package/dist/runs/store.js.map +0 -1
- package/dist/runs/task-markers.d.ts +0 -29
- package/dist/runs/task-markers.js +0 -78
- package/dist/runs/task-markers.js.map +0 -1
- package/dist/runs/task-refs.d.ts +0 -25
- package/dist/runs/task-refs.js +0 -74
- package/dist/runs/task-refs.js.map +0 -1
- package/dist/runs/transcript-facts-fold.d.ts +0 -64
- package/dist/runs/transcript-facts-fold.js +0 -109
- package/dist/runs/transcript-facts-fold.js.map +0 -1
- package/dist/runs/transcript-facts-load.d.ts +0 -11
- package/dist/runs/transcript-facts-load.js +0 -66
- package/dist/runs/transcript-facts-load.js.map +0 -1
- package/dist/runs/transcript-facts-queue.d.ts +0 -30
- package/dist/runs/transcript-facts-queue.js +0 -227
- package/dist/runs/transcript-facts-queue.js.map +0 -1
- package/dist/runs/transcript-facts-worker.d.ts +0 -15
- package/dist/runs/transcript-facts-worker.js +0 -26
- package/dist/runs/transcript-facts-worker.js.map +0 -1
- package/dist/runs/transcript-facts.d.ts +0 -39
- package/dist/runs/transcript-facts.js +0 -186
- package/dist/runs/transcript-facts.js.map +0 -1
- package/dist/runs/ui-event-sink.d.ts +0 -56
- package/dist/runs/ui-event-sink.js +0 -188
- package/dist/runs/ui-event-sink.js.map +0 -1
- package/dist/runs/webhook.d.ts +0 -191
- package/dist/runs/webhook.js +0 -360
- package/dist/runs/webhook.js.map +0 -1
- package/dist/runs/worker-execution.d.ts +0 -22
- package/dist/runs/worker-execution.js +0 -30
- package/dist/runs/worker-execution.js.map +0 -1
- package/dist/server/app-type.js.map +0 -1
- package/dist/server/archive-on-merge.d.ts +0 -35
- package/dist/server/archive-on-merge.js +0 -202
- package/dist/server/archive-on-merge.js.map +0 -1
- package/dist/server/capabilities.d.ts +0 -59
- package/dist/server/capabilities.js +0 -141
- package/dist/server/capabilities.js.map +0 -1
- package/dist/server/checkout-progress.d.ts +0 -10
- package/dist/server/checkout-progress.js +0 -27
- package/dist/server/checkout-progress.js.map +0 -1
- package/dist/server/checkout.d.ts +0 -129
- package/dist/server/checkout.js +0 -304
- package/dist/server/checkout.js.map +0 -1
- package/dist/server/cockpit-ownership.d.ts +0 -31
- package/dist/server/cockpit-ownership.js +0 -191
- package/dist/server/cockpit-ownership.js.map +0 -1
- package/dist/server/cold-repo-handles.d.ts +0 -14
- package/dist/server/cold-repo-handles.js +0 -78
- package/dist/server/cold-repo-handles.js.map +0 -1
- package/dist/server/completion-actions.d.ts +0 -30
- package/dist/server/completion-actions.js +0 -204
- package/dist/server/completion-actions.js.map +0 -1
- package/dist/server/create-project.d.ts +0 -71
- package/dist/server/create-project.js +0 -448
- package/dist/server/create-project.js.map +0 -1
- package/dist/server/forge/github-filters.d.ts +0 -22
- package/dist/server/forge/github-filters.js +0 -127
- package/dist/server/forge/github-filters.js.map +0 -1
- package/dist/server/forge/github-merge-requirements.d.ts +0 -18
- package/dist/server/forge/github-merge-requirements.js +0 -137
- package/dist/server/forge/github-merge-requirements.js.map +0 -1
- package/dist/server/forge/github.d.ts +0 -535
- package/dist/server/forge/github.js +0 -3200
- package/dist/server/forge/github.js.map +0 -1
- package/dist/server/forge/index.d.ts +0 -40
- package/dist/server/forge/index.js +0 -72
- package/dist/server/forge/index.js.map +0 -1
- package/dist/server/forge/types.d.ts +0 -244
- package/dist/server/forge/types.js +0 -2
- package/dist/server/forge/types.js.map +0 -1
- package/dist/server/fs-browse.d.ts +0 -80
- package/dist/server/fs-browse.js +0 -182
- package/dist/server/fs-browse.js.map +0 -1
- package/dist/server/git-changes.d.ts +0 -203
- package/dist/server/git-changes.js +0 -508
- package/dist/server/git-changes.js.map +0 -1
- package/dist/server/git.d.ts +0 -52
- package/dist/server/git.js +0 -170
- package/dist/server/git.js.map +0 -1
- package/dist/server/github.d.ts +0 -9
- package/dist/server/github.js +0 -8
- package/dist/server/github.js.map +0 -1
- package/dist/server/launch-key.d.ts +0 -5
- package/dist/server/launch-key.js +0 -31
- package/dist/server/launch-key.js.map +0 -1
- package/dist/server/live-routes.d.ts +0 -68
- package/dist/server/live-routes.js +0 -147
- package/dist/server/live-routes.js.map +0 -1
- package/dist/server/open-in-app.d.ts +0 -57
- package/dist/server/open-in-app.js +0 -177
- package/dist/server/open-in-app.js.map +0 -1
- package/dist/server/open-in-targets.d.ts +0 -42
- package/dist/server/open-in-targets.js +0 -110
- package/dist/server/open-in-targets.js.map +0 -1
- package/dist/server/open-in-terminal.d.ts +0 -73
- package/dist/server/open-in-terminal.js +0 -159
- package/dist/server/open-in-terminal.js.map +0 -1
- package/dist/server/pr.d.ts +0 -7
- package/dist/server/pr.js +0 -7
- package/dist/server/pr.js.map +0 -1
- package/dist/server/preview-cdp-socket.d.ts +0 -21
- package/dist/server/preview-cdp-socket.js +0 -112
- package/dist/server/preview-cdp-socket.js.map +0 -1
- package/dist/server/preview-socket.d.ts +0 -36
- package/dist/server/preview-socket.js +0 -126
- package/dist/server/preview-socket.js.map +0 -1
- package/dist/server/preview-sockets.d.ts +0 -14
- package/dist/server/preview-sockets.js +0 -18
- package/dist/server/preview-sockets.js.map +0 -1
- package/dist/server/project-context.d.ts +0 -192
- package/dist/server/project-context.js +0 -444
- package/dist/server/project-context.js.map +0 -1
- package/dist/server/provider-action-gate.d.ts +0 -5
- package/dist/server/provider-action-gate.js +0 -27
- package/dist/server/provider-action-gate.js.map +0 -1
- package/dist/server/provider-auth-runtime.d.ts +0 -32
- package/dist/server/provider-auth-runtime.js +0 -116
- package/dist/server/provider-auth-runtime.js.map +0 -1
- package/dist/server/repo-branches.d.ts +0 -99
- package/dist/server/repo-branches.js +0 -620
- package/dist/server/repo-branches.js.map +0 -1
- package/dist/server/repo-pull.d.ts +0 -18
- package/dist/server/repo-pull.js +0 -96
- package/dist/server/repo-pull.js.map +0 -1
- package/dist/server/run-event-feed.d.ts +0 -20
- package/dist/server/run-event-feed.js +0 -190
- package/dist/server/run-event-feed.js.map +0 -1
- package/dist/server/server-deps.d.ts +0 -37
- package/dist/server/server-deps.js +0 -114
- package/dist/server/server-deps.js.map +0 -1
- package/dist/server/server.d.ts +0 -28587
- package/dist/server/server.js +0 -5466
- package/dist/server/server.js.map +0 -1
- package/dist/server/start-run-options.d.ts +0 -82
- package/dist/server/start-run-options.js +0 -111
- package/dist/server/start-run-options.js.map +0 -1
- package/dist/server/static-ui.d.ts +0 -49
- package/dist/server/static-ui.js +0 -98
- package/dist/server/static-ui.js.map +0 -1
- package/dist/server/upgrade-router.d.ts +0 -23
- package/dist/server/upgrade-router.js +0 -53
- package/dist/server/upgrade-router.js.map +0 -1
- package/dist/server/validators.d.ts +0 -80
- package/dist/server/validators.js +0 -85
- package/dist/server/validators.js.map +0 -1
- package/dist/server/ws.d.ts +0 -65
- package/dist/server/ws.js +0 -200
- package/dist/server/ws.js.map +0 -1
- package/dist/server/wsl.d.ts +0 -25
- package/dist/server/wsl.js +0 -92
- package/dist/server/wsl.js.map +0 -1
- package/dist/server-install/engine.d.ts +0 -47
- package/dist/server-install/engine.js +0 -317
- package/dist/server-install/engine.js.map +0 -1
- package/dist/server-install/npx-cache.d.ts +0 -36
- package/dist/server-install/npx-cache.js +0 -104
- package/dist/server-install/npx-cache.js.map +0 -1
- package/dist/server-install/platforms/macosx-ngrok.d.ts +0 -6
- package/dist/server-install/platforms/macosx-ngrok.js +0 -371
- package/dist/server-install/platforms/macosx-ngrok.js.map +0 -1
- package/dist/server-install/platforms/ubuntu-vps.d.ts +0 -54
- package/dist/server-install/platforms/ubuntu-vps.js +0 -1066
- package/dist/server-install/platforms/ubuntu-vps.js.map +0 -1
- package/dist/server-install/state.d.ts +0 -50
- package/dist/server-install/state.js +0 -180
- package/dist/server-install/state.js.map +0 -1
- package/dist/server-install/steps.d.ts +0 -108
- package/dist/server-install/steps.js +0 -332
- package/dist/server-install/steps.js.map +0 -1
- package/dist/server-install/strategies.d.ts +0 -4
- package/dist/server-install/strategies.js +0 -20
- package/dist/server-install/strategies.js.map +0 -1
- package/dist/server-install/types.d.ts +0 -284
- package/dist/server-install/types.js +0 -118
- package/dist/server-install/types.js.map +0 -1
- package/dist/server-install/ui.d.ts +0 -36
- package/dist/server-install/ui.js +0 -130
- package/dist/server-install/ui.js.map +0 -1
- package/dist/session-context.d.ts +0 -64
- package/dist/session-context.js +0 -264
- package/dist/session-context.js.map +0 -1
- package/dist/skills-provision.d.ts +0 -62
- package/dist/skills-provision.js +0 -325
- package/dist/skills-provision.js.map +0 -1
- package/dist/skills-remote.d.ts +0 -129
- package/dist/skills-remote.js +0 -782
- package/dist/skills-remote.js.map +0 -1
- package/dist/skills.d.ts +0 -71
- package/dist/skills.js +0 -249
- package/dist/skills.js.map +0 -1
- package/dist/subcommands.d.ts +0 -11
- package/dist/subcommands.js +0 -24
- package/dist/subcommands.js.map +0 -1
- package/dist/task-cli/cli.d.ts +0 -38
- package/dist/task-cli/cli.js +0 -710
- package/dist/task-cli/cli.js.map +0 -1
- package/dist/task-cli/discovery.d.ts +0 -25
- package/dist/task-cli/discovery.js +0 -98
- package/dist/task-cli/discovery.js.map +0 -1
- package/dist/task-cli/hint.d.ts +0 -20
- package/dist/task-cli/hint.js +0 -14
- package/dist/task-cli/hint.js.map +0 -1
- package/dist/task-cli/http.d.ts +0 -49
- package/dist/task-cli/http.js +0 -109
- package/dist/task-cli/http.js.map +0 -1
- package/dist/task-cli/projections.d.ts +0 -68
- package/dist/task-cli/projections.js +0 -76
- package/dist/task-cli/projections.js.map +0 -1
- package/dist/task-cli/watch.d.ts +0 -119
- package/dist/task-cli/watch.js +0 -475
- package/dist/task-cli/watch.js.map +0 -1
- package/dist/ui-state.d.ts +0 -41
- package/dist/ui-state.js +0 -90
- package/dist/ui-state.js.map +0 -1
- package/dist/update-check.d.ts +0 -2
- package/dist/update-check.js +0 -26
- package/dist/update-check.js.map +0 -1
- package/dist/voice/decide.d.ts +0 -32
- package/dist/voice/decide.js +0 -297
- package/dist/voice/decide.js.map +0 -1
- package/dist/voice/decision-log.d.ts +0 -52
- package/dist/voice/decision-log.js +0 -107
- package/dist/voice/decision-log.js.map +0 -1
- package/dist/voice/engine.d.ts +0 -119
- package/dist/voice/engine.js +0 -60
- package/dist/voice/engine.js.map +0 -1
- package/dist/voice/fake-engine.d.ts +0 -10
- package/dist/voice/fake-engine.js +0 -192
- package/dist/voice/fake-engine.js.map +0 -1
- package/dist/voice/jev-engine.d.ts +0 -17
- package/dist/voice/jev-engine.js +0 -110
- package/dist/voice/jev-engine.js.map +0 -1
- package/dist/voice/pending-ask.d.ts +0 -17
- package/dist/voice/pending-ask.js +0 -50
- package/dist/voice/pending-ask.js.map +0 -1
- package/dist/voice/routes.d.ts +0 -115
- package/dist/voice/routes.js +0 -91
- package/dist/voice/routes.js.map +0 -1
- package/dist/voice/sentence.d.ts +0 -21
- package/dist/voice/sentence.js +0 -61
- package/dist/voice/sentence.js.map +0 -1
- package/dist/voice/thresholds.d.ts +0 -28
- package/dist/voice/thresholds.js +0 -29
- package/dist/voice/thresholds.js.map +0 -1
- package/dist/webhooks/cli.d.ts +0 -18
- package/dist/webhooks/cli.js +0 -145
- package/dist/webhooks/cli.js.map +0 -1
- package/dist/webhooks/prompt.d.ts +0 -5
- package/dist/webhooks/prompt.js +0 -26
- package/dist/webhooks/prompt.js.map +0 -1
- package/dist/workflows/active-run.d.ts +0 -167
- package/dist/workflows/active-run.js +0 -21
- package/dist/workflows/active-run.js.map +0 -1
- package/dist/workflows/attachment-path.d.ts +0 -6
- package/dist/workflows/attachment-path.js +0 -40
- package/dist/workflows/attachment-path.js.map +0 -1
- package/dist/workflows/continuation-admission.d.ts +0 -913
- package/dist/workflows/continuation-admission.js +0 -265
- package/dist/workflows/continuation-admission.js.map +0 -1
- package/dist/workflows/execution-account.d.ts +0 -13
- package/dist/workflows/execution-account.js +0 -18
- package/dist/workflows/execution-account.js.map +0 -1
- package/dist/workflows/grouped-command.d.ts +0 -31
- package/dist/workflows/grouped-command.js +0 -143
- package/dist/workflows/grouped-command.js.map +0 -1
- package/dist/workflows/input-acknowledgement.d.ts +0 -152
- package/dist/workflows/input-acknowledgement.js +0 -38
- package/dist/workflows/input-acknowledgement.js.map +0 -1
- package/dist/workflows/line-order.d.ts +0 -5
- package/dist/workflows/line-order.js +0 -25
- package/dist/workflows/line-order.js.map +0 -1
- package/dist/workflows/load.d.ts +0 -17
- package/dist/workflows/load.js +0 -61
- package/dist/workflows/load.js.map +0 -1
- package/dist/workflows/outcome-batches.d.ts +0 -20
- package/dist/workflows/outcome-batches.js +0 -25
- package/dist/workflows/outcome-batches.js.map +0 -1
- package/dist/workflows/question-routing.d.ts +0 -8
- package/dist/workflows/question-routing.js +0 -18
- package/dist/workflows/question-routing.js.map +0 -1
- package/dist/workflows/run-scheduling.d.ts +0 -35
- package/dist/workflows/run-scheduling.js +0 -61
- package/dist/workflows/run-scheduling.js.map +0 -1
- package/dist/workflows/run-states.d.ts +0 -190
- package/dist/workflows/run-states.js +0 -295
- package/dist/workflows/run-states.js.map +0 -1
- package/dist/workflows/run.d.ts +0 -2405
- package/dist/workflows/run.js +0 -10745
- package/dist/workflows/run.js.map +0 -1
- package/dist/workflows/turn-end.d.ts +0 -116
- package/dist/workflows/turn-end.js +0 -68
- package/dist/workflows/turn-end.js.map +0 -1
- package/dist/workflows/types.d.ts +0 -83
- package/dist/workflows/types.js +0 -192
- package/dist/workflows/types.js.map +0 -1
- package/dist/workflows/waits.d.ts +0 -74
- package/dist/workflows/waits.js +0 -197
- package/dist/workflows/waits.js.map +0 -1
- package/dist/workspace/agent-accounts.d.ts +0 -128
- package/dist/workspace/agent-accounts.js +0 -280
- package/dist/workspace/agent-accounts.js.map +0 -1
- package/dist/workspace/agent-profiles.d.ts +0 -124
- package/dist/workspace/agent-profiles.js +0 -190
- package/dist/workspace/agent-profiles.js.map +0 -1
- package/dist/workspace/config.d.ts +0 -181
- package/dist/workspace/config.js +0 -389
- package/dist/workspace/config.js.map +0 -1
- package/dist/workspace/migrations.d.ts +0 -35
- package/dist/workspace/migrations.js +0 -147
- package/dist/workspace/migrations.js.map +0 -1
- package/dist/workspace/projects-cli.d.ts +0 -25
- package/dist/workspace/projects-cli.js +0 -172
- package/dist/workspace/projects-cli.js.map +0 -1
- package/dist/workspace/projects.d.ts +0 -129
- package/dist/workspace/projects.js +0 -267
- package/dist/workspace/projects.js.map +0 -1
- package/dist/workspace/semaphore.d.ts +0 -145
- package/dist/workspace/semaphore.js +0 -196
- package/dist/workspace/semaphore.js.map +0 -1
- package/dist/workspace/ui-state.d.ts +0 -36
- package/dist/workspace/ui-state.js +0 -55
- package/dist/workspace/ui-state.js.map +0 -1
- package/dist/workspace/webhooks.d.ts +0 -40
- package/dist/workspace/webhooks.js +0 -146
- package/dist/workspace/webhooks.js.map +0 -1
- package/dist/worktree-manifest.d.ts +0 -165
- package/dist/worktree-manifest.js +0 -530
- package/dist/worktree-manifest.js.map +0 -1
- package/dist/worktree-setup.d.ts +0 -85
- package/dist/worktree-setup.js +0 -164
- package/dist/worktree-setup.js.map +0 -1
- package/scripts/benchmark-run-store-fixture.ts +0 -432
- package/scripts/benchmark-run-store.ts +0 -743
- package/scripts/benchmark-stuck-destroys.ts +0 -143
- package/scripts/check-pack.mjs +0 -48
- package/scripts/inline-contract.mjs +0 -165
- package/scripts/install-as-command.mjs +0 -122
- package/scripts/measure-transcript-facts-health.mjs +0 -87
- package/scripts/measure-transcript-facts-lag.mjs +0 -68
- package/scripts/mock-autonomous.mjs +0 -11
- package/scripts/mock-ci-tool.mjs +0 -111
- package/scripts/mock-claude-model-refusal.mjs +0 -42
- package/scripts/mock-claude.mjs +0 -1065
- package/scripts/mock-codex-app-server.mjs +0 -905
- package/scripts/mock-codex-coalesce-steer.mjs +0 -59
- package/scripts/mock-codex-reverse-steer.mjs +0 -130
- package/scripts/mock-cursor-acp.mjs +0 -423
- package/scripts/mock-cursor-hang-stdin-late.mjs +0 -35
- package/scripts/mock-cursor-hang-stdin.mjs +0 -30
- package/scripts/mock-cursor-print.mjs +0 -256
- package/scripts/mock-deferred-turn-start.mjs +0 -16
- package/scripts/mock-delivery-control.d.mts +0 -23
- package/scripts/mock-delivery-control.mjs +0 -80
- package/scripts/mock-env-record.mjs +0 -11
- package/scripts/mock-failure-control.d.mts +0 -13
- package/scripts/mock-failure-control.mjs +0 -68
- package/scripts/mock-multi-pr.mjs +0 -7
- package/scripts/mock-nudge.mjs +0 -45
- package/scripts/mock-omp-rpc.mjs +0 -779
- package/scripts/mock-opencode-serve.mjs +0 -1230
- package/scripts/mock-pi-rpc.mjs +0 -698
- package/scripts/mock-runner-crash.mjs +0 -58
- package/scripts/mock-session-context.d.mts +0 -5
- package/scripts/mock-session-context.mjs +0 -56
- package/scripts/mock-silent-tail.mjs +0 -85
- package/scripts/mock-turn-messages.mjs +0 -5
- package/scripts/omp-ci-wait.mjs +0 -29
- package/scripts/omp-restrict-delegation.yml +0 -4
- package/scripts/pi-ci-wait.mjs +0 -17
- package/scripts/pi-default-tools.mjs +0 -22
- package/scripts/pi-project-skills.mjs +0 -59
- package/scripts/pi-retry-degraded-service.mjs +0 -16
- package/scripts/probe-cursor-print.mjs +0 -627
- package/scripts/seed-archive-profile.ts +0 -53
- package/scripts/sync-readme.mjs +0 -20
- package/scripts/test-process-usage.mjs +0 -47
- package/scripts/transcript-facts-fixture.mjs +0 -53
- package/scripts/voice-replay.ts +0 -50
- package/scripts/windows-workspace-identity.cs +0 -208
- package/scripts/windows-workspace-identity.ps1 +0 -10
- package/web/dist/assets/alert-dialog-DfctKUMw.js +0 -1
- package/web/dist/assets/button-CeupvoKG.js +0 -41
- package/web/dist/assets/centered-state-hDsyXrnH.js +0 -1
- package/web/dist/assets/cez-idle-D3aj_9lp.js +0 -1
- package/web/dist/assets/diff-BnIXZK3i2.js +0 -3
- package/web/dist/assets/diff-controls-GewpW9aF.js +0 -1
- package/web/dist/assets/diff-view-Byo7gpvW.js +0 -11
- package/web/dist/assets/dropdown-menu-COj_J5wd.js +0 -6
- package/web/dist/assets/git-toolbar-DY0z0n4S.js +0 -1
- package/web/dist/assets/github-DwU6ALRK.js +0 -1
- package/web/dist/assets/index-BOfE8pyD.js +0 -34
- package/web/dist/assets/index-D9HpsmdW.css +0 -1
- package/web/dist/assets/lib-BQXq3kEf.js +0 -1
- package/web/dist/assets/live-protocol-Uce2NwEX.js +0 -64
- package/web/dist/assets/play-CmVAj_fu.js +0 -1
- package/web/dist/assets/popover-D56fhiXj.js +0 -1
- package/web/dist/assets/preview-pane-connected-BmVqfSU5.js +0 -3
- package/web/dist/assets/reference-chip-gQNk-4jc.js +0 -1
- package/web/dist/assets/repo-git-B5ECDUuv.js +0 -1
- package/web/dist/assets/run-header-C0Y1NvEM.js +0 -2
- package/web/dist/assets/skill-empty-hint-oOtzR3v0.js +0 -1
- package/web/dist/assets/skills-DUeTkZ9z.js +0 -1
- package/web/dist/assets/status-dot-1PR0i69P.js +0 -1
- package/web/dist/assets/tab-link-DmWk4l5O.js +0 -1
- package/web/dist/assets/task-changes-DKZXuW89.js +0 -1
- package/web/dist/assets/task-commits-BZ6KxWdF.js +0 -1
- package/web/dist/assets/task-files-DlF7Apcn.js +0 -2
- package/web/dist/assets/task-github-item-CVPo3geZ.js +0 -1
- package/web/dist/assets/task-thread-mm4-ECyo.js +0 -9
- package/web/dist/assets/thread-state-CIw2BlhT.js +0 -4
- package/web/dist/assets/use-hand-to-agent-state-BCDjzHnG.js +0 -1
- package/web/dist/assets/workflows-D8vYD-ql.js +0 -7
- package/web/dist/assets/zoomable-image-CxQSsfcn.js +0 -1
|
@@ -1,3200 +0,0 @@
|
|
|
1
|
-
import { defined } from '../../core/defined.js';
|
|
2
|
-
import { activeWorkflowRunsArgs, parseActiveWorkflowRuns } from '../../ci-wait/github.js';
|
|
3
|
-
import { exactLineIndex, nextLineIndex } from '../../contract/index.js';
|
|
4
|
-
import { pullRequestKey } from '../../runs/pull-requests.js';
|
|
5
|
-
import { matchesGithubPullRequest, mergedPullRequestObservations } from '../../merge-observations.js';
|
|
6
|
-
import { randomUUID } from 'node:crypto';
|
|
7
|
-
import { execFile } from 'node:child_process';
|
|
8
|
-
import { promisify } from 'node:util';
|
|
9
|
-
import { z } from 'zod';
|
|
10
|
-
import { GITHUB_COMMENT_COUNTS_MAX, GITHUB_SEARCH_MAX, REFERENCE_STATUS_MAX } from '../../contract/index.js';
|
|
11
|
-
import { fetchIssueProjects, fetchRepositoryProjects, fetchViewerLogin } from './github-filters.js';
|
|
12
|
-
import { fetchGithubMergeRequirements } from './github-merge-requirements.js';
|
|
13
|
-
import { autosaveCommit } from '../../git-worktree.js';
|
|
14
|
-
/**
|
|
15
|
-
* The GitHub forge driver — all `gh`-CLI logic in one place, moved here from
|
|
16
|
-
* `src/server/github.ts` (tab listing) and `src/server/pr.ts` (draft PRs)
|
|
17
|
-
* behind the `ForgeDriver` seam. Those modules remain as thin delegates.
|
|
18
|
-
* `/api/github`'s response shape is this driver's serialization and is
|
|
19
|
-
* protected by BACKWARD_COMPATIBILITY.md — additive changes only.
|
|
20
|
-
*/
|
|
21
|
-
const exec = promisify(execFile);
|
|
22
|
-
export const GH_PR_DIFF_FILE_CAP = 300;
|
|
23
|
-
export const GH_PR_PATCH_CAP = 512 * 1024;
|
|
24
|
-
export const GH_PR_DIFF_JSON_CAP = 4 * 1024 * 1024;
|
|
25
|
-
const ghPrFileSchema = z.object({
|
|
26
|
-
filename: z.string().min(1),
|
|
27
|
-
previous_filename: z.string().optional(),
|
|
28
|
-
status: z.enum(['added', 'modified', 'removed', 'renamed', 'copied', 'changed']),
|
|
29
|
-
additions: z.number().int().nonnegative(),
|
|
30
|
-
deletions: z.number().int().nonnegative(),
|
|
31
|
-
patch: z.string().optional(),
|
|
32
|
-
});
|
|
33
|
-
const ghPrHeadSchema = z.object({ headRefOid: z.string().regex(/^[0-9a-f]{40}$/i) });
|
|
34
|
-
export class GithubPrNotFoundError extends Error {
|
|
35
|
-
}
|
|
36
|
-
const prDiffCache = new Map();
|
|
37
|
-
/** Fetch no more than the three GitHub pages represented by the public 300-file response cap. */
|
|
38
|
-
export async function fetchPrFilePages(runPage) {
|
|
39
|
-
const rows = [];
|
|
40
|
-
for (let page = 1; page <= GH_PR_DIFF_FILE_CAP / 100; page++) {
|
|
41
|
-
const next = z.array(z.unknown()).parse(JSON.parse(await runPage(page)));
|
|
42
|
-
rows.push(...next);
|
|
43
|
-
if (next.length < 100)
|
|
44
|
-
break;
|
|
45
|
-
}
|
|
46
|
-
return rows;
|
|
47
|
-
}
|
|
48
|
-
export async function fetchGithubPrDiff(repoRoot, number, refresh = false) {
|
|
49
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
50
|
-
return mockGithubPrDiff(number);
|
|
51
|
-
try {
|
|
52
|
-
const head = ghPrHeadSchema.parse(JSON.parse(await gh(repoRoot, ['pr', 'view', String(number), '--json', 'headRefOid']))).headRefOid;
|
|
53
|
-
const key = `${repoRoot}\0${number}\0${head}`;
|
|
54
|
-
const hit = prDiffCache.get(key);
|
|
55
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
56
|
-
return hit.data;
|
|
57
|
-
const rows = z.array(ghPrFileSchema).parse(await fetchPrFilePages((page) => gh(repoRoot, ['api', `repos/{owner}/{repo}/pulls/${number}/files?per_page=100&page=${page}`], 30_000)));
|
|
58
|
-
const limited = rows.slice(0, GH_PR_DIFF_FILE_CAP);
|
|
59
|
-
// A full third page may have a successor. Without fetching a 301st file, conservatively call
|
|
60
|
-
// the response partial rather than claiming completeness we cannot prove.
|
|
61
|
-
let responseTruncated = rows.length >= GH_PR_DIFF_FILE_CAP;
|
|
62
|
-
const reasons = responseTruncated ? [`Only the first ${GH_PR_DIFF_FILE_CAP} files are shown.`] : [];
|
|
63
|
-
const files = limited.map((row) => {
|
|
64
|
-
let patch = row.patch;
|
|
65
|
-
let truncated = false;
|
|
66
|
-
let patchUnavailableReason;
|
|
67
|
-
if (patch !== undefined && Buffer.byteLength(patch, 'utf8') > GH_PR_PATCH_CAP) {
|
|
68
|
-
patch = undefined;
|
|
69
|
-
truncated = true;
|
|
70
|
-
patchUnavailableReason = 'too-large';
|
|
71
|
-
responseTruncated = true;
|
|
72
|
-
}
|
|
73
|
-
else if (patch === undefined) {
|
|
74
|
-
patchUnavailableReason = row.additions === 0 && row.deletions === 0 ? 'binary' : 'not-provided';
|
|
75
|
-
}
|
|
76
|
-
return {
|
|
77
|
-
path: row.filename,
|
|
78
|
-
...(row.previous_filename ? { previousPath: row.previous_filename } : {}),
|
|
79
|
-
status: row.status,
|
|
80
|
-
additions: row.additions,
|
|
81
|
-
deletions: row.deletions,
|
|
82
|
-
...(patch !== undefined ? { patch } : {}),
|
|
83
|
-
...(patchUnavailableReason ? { patchUnavailableReason } : {}),
|
|
84
|
-
...(truncated ? { truncated: true } : {}),
|
|
85
|
-
};
|
|
86
|
-
});
|
|
87
|
-
let kept = files;
|
|
88
|
-
while (kept.length > 0 &&
|
|
89
|
-
Buffer.byteLength(JSON.stringify({ available: true, number, headSha: head, files: kept }), 'utf8') >
|
|
90
|
-
GH_PR_DIFF_JSON_CAP) {
|
|
91
|
-
kept = kept.slice(0, -1);
|
|
92
|
-
responseTruncated = true;
|
|
93
|
-
}
|
|
94
|
-
if (kept.length < files.length)
|
|
95
|
-
reasons.push('The response size limit omitted some files.');
|
|
96
|
-
if (files.some((file) => file.truncated))
|
|
97
|
-
reasons.push('One or more patches exceeded the per-file limit.');
|
|
98
|
-
const data = {
|
|
99
|
-
available: true,
|
|
100
|
-
number,
|
|
101
|
-
headSha: head,
|
|
102
|
-
files: kept,
|
|
103
|
-
additions: rows.reduce((sum, row) => sum + row.additions, 0),
|
|
104
|
-
deletions: rows.reduce((sum, row) => sum + row.deletions, 0),
|
|
105
|
-
truncated: responseTruncated,
|
|
106
|
-
...(reasons.length ? { reason: reasons.join(' ') } : {}),
|
|
107
|
-
};
|
|
108
|
-
prDiffCache.set(key, { at: Date.now(), data });
|
|
109
|
-
while (prDiffCache.size > 50)
|
|
110
|
-
prDiffCache.delete(prDiffCache.keys().next().value);
|
|
111
|
-
return data;
|
|
112
|
-
}
|
|
113
|
-
catch (err) {
|
|
114
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
115
|
-
if (/HTTP 404|Could not resolve to a PullRequest|no pull requests found/i.test(message)) {
|
|
116
|
-
throw new GithubPrNotFoundError(`Pull request #${number} was not found`);
|
|
117
|
-
}
|
|
118
|
-
return {
|
|
119
|
-
available: false,
|
|
120
|
-
reason: /ENOENT/.test(message)
|
|
121
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
122
|
-
: firstLine(message),
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
function mockGithubPrDiff(number) {
|
|
127
|
-
return {
|
|
128
|
-
available: true,
|
|
129
|
-
number,
|
|
130
|
-
headSha: '0123456789abcdef0123456789abcdef01234567',
|
|
131
|
-
additions: 15,
|
|
132
|
-
deletions: 4,
|
|
133
|
-
truncated: true,
|
|
134
|
-
reason: 'One or more patches were not provided by GitHub.',
|
|
135
|
-
files: [
|
|
136
|
-
{ path: 'src/session.ts', status: 'modified', additions: 8, deletions: 3, patch: '@@ -1,3 +1,4 @@\n-old\n+new\n context' },
|
|
137
|
-
{ path: 'src/new-name.ts', previousPath: 'src/old-name.ts', status: 'renamed', additions: 7, deletions: 1, patch: '@@ -1 +1 @@\n-old name\n+new name' },
|
|
138
|
-
{ path: 'assets/logo.png', status: 'modified', additions: 0, deletions: 0, patchUnavailableReason: 'binary' },
|
|
139
|
-
{ path: 'generated/output.txt', status: 'modified', additions: 0, deletions: 0, patchUnavailableReason: 'too-large', truncated: true },
|
|
140
|
-
],
|
|
141
|
-
};
|
|
142
|
-
}
|
|
143
|
-
// `gh … --json` output — validated at the boundary, extras stripped.
|
|
144
|
-
const ghAuthor = z.object({ login: z.string() }).nullish();
|
|
145
|
-
// `color` is the 6-hex GitHub label color (no `#`), '' when gh omits it.
|
|
146
|
-
const ghLabel = z.object({ name: z.string(), color: z.string().default('') });
|
|
147
|
-
const ghIssueSchema = z.object({
|
|
148
|
-
number: z.number(),
|
|
149
|
-
title: z.string(),
|
|
150
|
-
author: ghAuthor,
|
|
151
|
-
createdAt: z.string(),
|
|
152
|
-
labels: z.array(ghLabel).default([]),
|
|
153
|
-
assignees: z.array(z.object({ login: z.string() })).default([]),
|
|
154
|
-
body: z.string().nullish(),
|
|
155
|
-
url: z.string(),
|
|
156
|
-
});
|
|
157
|
-
// One check run's `gh --json statusCheckRollup` entry — every field optional/nullish because
|
|
158
|
-
// gh's shape varies by check provider (exported so #400's unit tests can build fixtures).
|
|
159
|
-
export const ghCheckRunSchema = z.object({
|
|
160
|
-
state: z.string().nullish(),
|
|
161
|
-
status: z.string().nullish(),
|
|
162
|
-
conclusion: z.string().nullish(),
|
|
163
|
-
});
|
|
164
|
-
const ghStatusCheckRollup = z.array(ghCheckRunSchema).nullish();
|
|
165
|
-
// The list tier no longer requests `statusCheckRollup` (#664) — it is hydrated lazily per
|
|
166
|
-
// on-screen PR row (`fetchGithubChecks`). `checks` is set to `null` on list rows; the schema
|
|
167
|
-
// keeps no rollup field because the list call never asks for it.
|
|
168
|
-
const ghPrSchema = ghIssueSchema.extend({
|
|
169
|
-
isDraft: z.boolean().default(false),
|
|
170
|
-
additions: z.number().default(0),
|
|
171
|
-
deletions: z.number().default(0),
|
|
172
|
-
});
|
|
173
|
-
const ghPrViewSchema = z.object({
|
|
174
|
-
number: z.number(),
|
|
175
|
-
url: z.string(),
|
|
176
|
-
state: z.string().default('OPEN'),
|
|
177
|
-
mergedAt: z.unknown().optional(),
|
|
178
|
-
isDraft: z.boolean().default(false),
|
|
179
|
-
statusCheckRollup: ghStatusCheckRollup,
|
|
180
|
-
});
|
|
181
|
-
const mergeCheckSchema = z.object({
|
|
182
|
-
name: z.string().optional(),
|
|
183
|
-
context: z.string().optional(),
|
|
184
|
-
targetUrl: z.string().nullish(),
|
|
185
|
-
state: z.string().nullish(),
|
|
186
|
-
status: z.string().nullish(),
|
|
187
|
-
conclusion: z.string().nullish(),
|
|
188
|
-
detailsUrl: z.string().nullish(),
|
|
189
|
-
});
|
|
190
|
-
const mergePrSchema = z.object({
|
|
191
|
-
number: z.number(),
|
|
192
|
-
title: z.string(),
|
|
193
|
-
url: z.string(),
|
|
194
|
-
state: z.string(),
|
|
195
|
-
mergedAt: z.unknown().optional(),
|
|
196
|
-
isDraft: z.boolean().default(false),
|
|
197
|
-
headRefName: z.string(),
|
|
198
|
-
baseRefName: z.string(),
|
|
199
|
-
headRefOid: z.string().regex(/^[0-9a-f]{40}$/),
|
|
200
|
-
mergeable: z.string().nullish(),
|
|
201
|
-
mergeStateStatus: z.string().nullish(),
|
|
202
|
-
reviewDecision: z.string().nullish(),
|
|
203
|
-
statusCheckRollup: z.array(mergeCheckSchema).nullish(),
|
|
204
|
-
});
|
|
205
|
-
const repoMergePolicySchema = z.object({
|
|
206
|
-
allow_merge_commit: z.boolean().default(false),
|
|
207
|
-
allow_squash_merge: z.boolean().default(false),
|
|
208
|
-
allow_rebase_merge: z.boolean().default(false),
|
|
209
|
-
merge_commit_title: z.string().nullish(),
|
|
210
|
-
squash_merge_commit_title: z.string().nullish(),
|
|
211
|
-
});
|
|
212
|
-
const ghMergeResultSchema = z.object({
|
|
213
|
-
merged: z.boolean(),
|
|
214
|
-
message: z.string().nullish(),
|
|
215
|
-
sha: z.string().nullish(),
|
|
216
|
-
});
|
|
217
|
-
/** Exported for unit tests (#400) — collapses a zod-validated `statusCheckRollup` array down to
|
|
218
|
-
* the single enum the GitHub tab (list rows + detail badge) renders. */
|
|
219
|
-
export function rollupToChecks(rollup) {
|
|
220
|
-
if (!rollup || rollup.length === 0)
|
|
221
|
-
return null;
|
|
222
|
-
const states = rollup.map((r) => (r.conclusion || r.state || r.status || '').toUpperCase());
|
|
223
|
-
if (states.some((s) => ['FAILURE', 'ERROR', 'TIMED_OUT', 'ACTION_REQUIRED'].includes(s)))
|
|
224
|
-
return 'failing';
|
|
225
|
-
if (states.some((s) => ['PENDING', 'IN_PROGRESS', 'QUEUED', 'EXPECTED', ''].includes(s)))
|
|
226
|
-
return 'pending';
|
|
227
|
-
return 'passing';
|
|
228
|
-
}
|
|
229
|
-
// Keep account-directory and host selection attached to shared work. Never key by owner/name:
|
|
230
|
-
// separate local roots (including different remotes/accounts) must not share results.
|
|
231
|
-
function githubContext(repoRoot) {
|
|
232
|
-
const env = { GH_HOST: process.env.GH_HOST, GH_CONFIG_DIR: process.env.GH_CONFIG_DIR };
|
|
233
|
-
return { key: JSON.stringify([repoRoot, env.GH_HOST, env.GH_CONFIG_DIR]), env };
|
|
234
|
-
}
|
|
235
|
-
async function gh(repoRoot, args, timeout = 15_000, signal, context) {
|
|
236
|
-
const { stdout } = await exec('gh', args, {
|
|
237
|
-
cwd: repoRoot,
|
|
238
|
-
...(context ? { env: { ...process.env, ...context.env } } : {}),
|
|
239
|
-
timeout,
|
|
240
|
-
maxBuffer: 50 * 1024 * 1024,
|
|
241
|
-
...(signal ? { signal } : {}),
|
|
242
|
-
});
|
|
243
|
-
return stdout;
|
|
244
|
-
}
|
|
245
|
-
/** `gh api graphql` argv. `-f` sends every value as a String, and GitHub rejects a String where
|
|
246
|
-
* the query declares `Int!` ("Could not coerce value to Int", open-mercato/cezar#1366), so a
|
|
247
|
-
* number goes through `-F`. A string never does: `-F` would read `@file` and coerce
|
|
248
|
-
* `true`/numerals, which is not what an opaque cursor or a login means. */
|
|
249
|
-
export function ghGraphqlArgs(query, variables = {}) {
|
|
250
|
-
const args = ['api', 'graphql', '-f', `query=${query}`];
|
|
251
|
-
for (const [key, value] of Object.entries(variables)) {
|
|
252
|
-
args.push(typeof value === 'number' ? '-F' : '-f', `${key}=${value}`);
|
|
253
|
-
}
|
|
254
|
-
return args;
|
|
255
|
-
}
|
|
256
|
-
/** `owner/name` → `{ owner, name }`, or null when the handle isn't a clean two-part slug. */
|
|
257
|
-
export function parseOwnerName(nameWithOwner) {
|
|
258
|
-
const [owner, name, ...rest] = nameWithOwner.trim().split('/');
|
|
259
|
-
return owner && name && rest.length === 0 ? { owner, name } : null;
|
|
260
|
-
}
|
|
261
|
-
// Paged open lists defer comment counts; hydrate them through the counts route after paint.
|
|
262
|
-
/** GitHub GraphQL rejects `first` above 100 (EXCESSIVE_PAGINATION); larger limits walk pages. */
|
|
263
|
-
export const GH_GRAPHQL_PAGE_MAX = 100;
|
|
264
|
-
// Labels up to 100, which is what `gh issue list --json labels` read before the GraphQL page.
|
|
265
|
-
const LIST_NODE_FIELDS = 'number title author { login } createdAt url body labels(first: 100) { nodes { name color } }';
|
|
266
|
-
const listQuery = (side) => `
|
|
267
|
-
query ($owner: String!, $name: String!, $first: Int!, $after: String) {
|
|
268
|
-
repository(owner: $owner, name: $name) {
|
|
269
|
-
${side}(first: $first, after: $after, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) {
|
|
270
|
-
totalCount
|
|
271
|
-
pageInfo { hasNextPage endCursor }
|
|
272
|
-
nodes { ${LIST_NODE_FIELDS} ${side === 'issues' ? 'assignees(first: 20) { nodes { login } }' : 'isDraft additions deletions'} }
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}`;
|
|
276
|
-
/** A GraphQL connection (`{ nodes }`) read as the flat array `gh … --json` used to return. */
|
|
277
|
-
const connectionOf = (item) => z.object({ nodes: z.array(item.nullable()).default([]) }).nullish()
|
|
278
|
-
.transform((connection) => (connection?.nodes ?? []).filter((node) => node != null));
|
|
279
|
-
const ghListNodeSchema = z.object({
|
|
280
|
-
number: z.number(),
|
|
281
|
-
title: z.string(),
|
|
282
|
-
author: ghAuthor,
|
|
283
|
-
createdAt: z.string(),
|
|
284
|
-
url: z.string(),
|
|
285
|
-
body: z.string().nullish(),
|
|
286
|
-
labels: connectionOf(ghLabel),
|
|
287
|
-
assignees: connectionOf(z.object({ login: z.string() })),
|
|
288
|
-
isDraft: z.boolean().nullish(),
|
|
289
|
-
additions: z.number().nullish(),
|
|
290
|
-
deletions: z.number().nullish(),
|
|
291
|
-
});
|
|
292
|
-
const ghListConnectionSchema = z.object({
|
|
293
|
-
totalCount: z.number().int().nonnegative(),
|
|
294
|
-
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullish() }),
|
|
295
|
-
nodes: z.array(ghListNodeSchema.nullable()),
|
|
296
|
-
});
|
|
297
|
-
function parseListConnection(out, side) {
|
|
298
|
-
const parsed = JSON.parse(out);
|
|
299
|
-
const message = parsed.errors?.map((e) => e.message).filter(Boolean).join(' ');
|
|
300
|
-
if (message)
|
|
301
|
-
throw new Error(message);
|
|
302
|
-
if (!parsed.data?.repository)
|
|
303
|
-
throw new Error('GitHub did not resolve this repository');
|
|
304
|
-
return ghListConnectionSchema.parse(parsed.data.repository[side]);
|
|
305
|
-
}
|
|
306
|
-
/**
|
|
307
|
-
* One side of the open list: up to `limit` rows from `cursor`, in requests of at most
|
|
308
|
-
* `GH_GRAPHQL_PAGE_MAX`. `nextCursor` is where the rows stop, or `null` once the side is
|
|
309
|
-
* exhausted. `done` asks for `first: 0`, which still answers `totalCount`, so an exhausted side
|
|
310
|
-
* keeps a fresh total without ever restarting from its first page (open-mercato/cezar#1366
|
|
311
|
-
* restarted it while the other side paged).
|
|
312
|
-
*/
|
|
313
|
-
export async function fetchListConnection(run, owner, name, side, limit, cursor, done = false) {
|
|
314
|
-
const query = listQuery(side);
|
|
315
|
-
if (done) {
|
|
316
|
-
const page = parseListConnection(await run(query, { owner, name, first: 0 }), side);
|
|
317
|
-
return { totalCount: page.totalCount, nodes: [], nextCursor: null };
|
|
318
|
-
}
|
|
319
|
-
const nodes = [];
|
|
320
|
-
let after = cursor;
|
|
321
|
-
for (;;) {
|
|
322
|
-
const first = Math.min(GH_GRAPHQL_PAGE_MAX, limit - nodes.length);
|
|
323
|
-
const page = parseListConnection(await run(query, { owner, name, first, ...(after ? { after } : {}) }), side);
|
|
324
|
-
const rows = page.nodes.filter((node) => node !== null);
|
|
325
|
-
nodes.push(...rows);
|
|
326
|
-
const next = page.pageInfo.hasNextPage ? page.pageInfo.endCursor ?? null : null;
|
|
327
|
-
// An empty page that claims more would loop forever; read it as the end of the side.
|
|
328
|
-
if (next === null || rows.length === 0)
|
|
329
|
-
return { totalCount: page.totalCount, nodes, nextCursor: null };
|
|
330
|
-
if (next === after)
|
|
331
|
-
throw new Error('GitHub list cursor did not advance');
|
|
332
|
-
// A short page with more behind it still ends this request: the cursor resumes it exactly.
|
|
333
|
-
if (nodes.length >= limit || rows.length < first)
|
|
334
|
-
return { totalCount: page.totalCount, nodes, nextCursor: next };
|
|
335
|
-
after = next;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
/* Reads degrade to `available: false` with a hint — never an error (plan rule
|
|
339
|
-
7): no `gh`, no remote, offline all land on the same quiet path. A short
|
|
340
|
-
cache keeps tab switches from hammering the GitHub API; a cached fetch with
|
|
341
|
-
a bigger limit than asked serves fine (it's a superset). Keyed by repository/host/account context
|
|
342
|
-
(multi-project workspace, step 2.6) plus the page asked for: one project's — possibly private —
|
|
343
|
-
issues/PRs must never be served under another project's scope, and page 2 is never page 1.
|
|
344
|
-
Bounded like `commentsCache` so an unbounded workspace can't grow it without limit. */
|
|
345
|
-
let listRequestOrder = 0;
|
|
346
|
-
/** Per context, the order of the newest page-1 refresh. A refresh drops the context's later
|
|
347
|
-
* pages (their cursors were cut from the old first page), and a later page that started before
|
|
348
|
-
* it may answer its caller but never re-enters the cache. Bounded with `listCache`. */
|
|
349
|
-
const listRefreshOrder = new Map();
|
|
350
|
-
const listCache = new Map();
|
|
351
|
-
const LIST_CACHE_MAX = 50;
|
|
352
|
-
const CACHE_MS = 60_000;
|
|
353
|
-
/** Which page key holds a projects generation, so `fetchGithubProjects` never scans the cache.
|
|
354
|
-
* Installed and evicted in step with `listCache`, so it shares its bound. */
|
|
355
|
-
const projectGenerations = new Map();
|
|
356
|
-
/** Board discovery (the `projectsV2` walk) per context: page 2 pays for membership only. A
|
|
357
|
-
* failed discovery is dropped, so the next page or refresh asks again. */
|
|
358
|
-
const repositoryProjectsCache = new Map();
|
|
359
|
-
function dropListEntry(key) {
|
|
360
|
-
const generation = listCache.get(key)?.data.projectsGeneration;
|
|
361
|
-
if (generation && projectGenerations.get(generation) === key)
|
|
362
|
-
projectGenerations.delete(generation);
|
|
363
|
-
listCache.delete(key);
|
|
364
|
-
}
|
|
365
|
-
function discoverRepositoryProjects(contextKey, refresh, start) {
|
|
366
|
-
const hit = repositoryProjectsCache.get(contextKey);
|
|
367
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
368
|
-
return hit.projects;
|
|
369
|
-
const projects = start();
|
|
370
|
-
const entry = { at: Date.now(), projects };
|
|
371
|
-
repositoryProjectsCache.delete(contextKey);
|
|
372
|
-
repositoryProjectsCache.set(contextKey, entry);
|
|
373
|
-
projects.catch(() => {
|
|
374
|
-
if (repositoryProjectsCache.get(contextKey) === entry)
|
|
375
|
-
repositoryProjectsCache.delete(contextKey);
|
|
376
|
-
});
|
|
377
|
-
while (repositoryProjectsCache.size > LIST_CACHE_MAX) {
|
|
378
|
-
const oldest = repositoryProjectsCache.keys().next().value;
|
|
379
|
-
if (oldest === undefined)
|
|
380
|
-
break;
|
|
381
|
-
repositoryProjectsCache.delete(oldest);
|
|
382
|
-
}
|
|
383
|
-
return projects;
|
|
384
|
-
}
|
|
385
|
-
export const GH_MAX_LIMIT = 1000;
|
|
386
|
-
function listPageKey(contextKey, page) {
|
|
387
|
-
return JSON.stringify([contextKey, page.issuesCursor ?? null, page.prsCursor ?? null, !!page.issuesDone, !!page.prsDone]);
|
|
388
|
-
}
|
|
389
|
-
export async function fetchGithub(repoRoot, refresh = false, limit = 30, page = {}) {
|
|
390
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
391
|
-
return mockGithubPage(limit, page);
|
|
392
|
-
const context = githubContext(repoRoot);
|
|
393
|
-
const capped = Math.min(Math.max(limit, 1), GH_MAX_LIMIT);
|
|
394
|
-
const key = listPageKey(context.key, page);
|
|
395
|
-
const hit = listCache.get(key);
|
|
396
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS && hit.limit >= capped) {
|
|
397
|
-
return hit.data;
|
|
398
|
-
}
|
|
399
|
-
const order = ++listRequestOrder;
|
|
400
|
-
if (refresh && !page.issuesCursor && !page.prsCursor && !page.issuesDone && !page.prsDone) {
|
|
401
|
-
listRefreshOrder.delete(context.key);
|
|
402
|
-
listRefreshOrder.set(context.key, order);
|
|
403
|
-
while (listRefreshOrder.size > LIST_CACHE_MAX) {
|
|
404
|
-
const oldest = listRefreshOrder.keys().next().value;
|
|
405
|
-
if (oldest === undefined)
|
|
406
|
-
break;
|
|
407
|
-
listRefreshOrder.delete(oldest);
|
|
408
|
-
}
|
|
409
|
-
for (const [cached, entry] of [...listCache]) {
|
|
410
|
-
if (entry.contextKey === context.key && cached !== key)
|
|
411
|
-
dropListEntry(cached);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
try {
|
|
415
|
-
// No `statusCheckRollup` (#664): it is hydrated lazily per on-screen PR row via
|
|
416
|
-
// `fetchGithubChecks`. A big aggregate list still gets a little more wall clock.
|
|
417
|
-
const timeout = capped > 100 ? 30_000 : 15_000;
|
|
418
|
-
const ownerName = await resolveRepoHandleStrict(repoRoot, context);
|
|
419
|
-
if (!ownerName)
|
|
420
|
-
return { available: false, reason: 'Could not resolve this repository on GitHub.', issues: [], prs: [] };
|
|
421
|
-
const runGraphql = (query, variables) => gh(repoRoot, ghGraphqlArgs(query, variables), timeout, undefined, context);
|
|
422
|
-
// Optional project queries have one shared wall-clock budget. A missing scope, a cap,
|
|
423
|
-
// or malformed metadata must never turn an otherwise working list into unavailable.
|
|
424
|
-
const deadline = Date.now() + 15_000;
|
|
425
|
-
const projectGraphql = (query, variables) => {
|
|
426
|
-
const remaining = deadline - Date.now();
|
|
427
|
-
if (remaining <= 0)
|
|
428
|
-
return Promise.reject(new Error('Project lookup timed out'));
|
|
429
|
-
return gh(repoRoot, ghGraphqlArgs(query, variables), Math.min(remaining, 8_000), undefined, context);
|
|
430
|
-
};
|
|
431
|
-
const firstPage = !page.issuesCursor && !page.prsCursor && !page.issuesDone && !page.prsDone;
|
|
432
|
-
const issueSide = fetchListConnection(runGraphql, ownerName.owner, ownerName.name, 'issues', capped, page.issuesCursor, page.issuesDone);
|
|
433
|
-
const projectLookup = fetchIssueProjects(projectGraphql, ownerName.owner, ownerName.name, async () => (await issueSide).nodes.map((node) => node.number), () => discoverRepositoryProjects(context.key, refresh, () => fetchRepositoryProjects(projectGraphql, ownerName.owner, ownerName.name)));
|
|
434
|
-
const [issuesPage, prsPage, viewerLogin] = await Promise.all([
|
|
435
|
-
issueSide,
|
|
436
|
-
fetchListConnection(runGraphql, ownerName.owner, ownerName.name, 'pullRequests', capped, page.prsCursor, page.prsDone),
|
|
437
|
-
// The viewer is the same on every page; only the first one asks.
|
|
438
|
-
firstPage
|
|
439
|
-
? fetchViewerLogin((query) => gh(repoRoot, ghGraphqlArgs(query), 8_000, undefined, context))
|
|
440
|
-
: Promise.resolve(undefined),
|
|
441
|
-
]);
|
|
442
|
-
// One repo-wide label→color map, filled as we flatten each item's labels.
|
|
443
|
-
const labelColors = {};
|
|
444
|
-
const recordColor = (l) => {
|
|
445
|
-
if (l.color && !labelColors[l.name])
|
|
446
|
-
labelColors[l.name] = l.color;
|
|
447
|
-
};
|
|
448
|
-
const issues = issuesPage.nodes.map((i) => {
|
|
449
|
-
i.labels.forEach(recordColor);
|
|
450
|
-
return {
|
|
451
|
-
kind: 'issue',
|
|
452
|
-
number: i.number,
|
|
453
|
-
title: i.title,
|
|
454
|
-
author: i.author?.login ?? '?',
|
|
455
|
-
createdAt: i.createdAt,
|
|
456
|
-
labels: i.labels.map((l) => l.name),
|
|
457
|
-
body: (i.body ?? '').slice(0, 8_000),
|
|
458
|
-
url: i.url,
|
|
459
|
-
comments: 0,
|
|
460
|
-
assignees: i.assignees.map(a => a.login),
|
|
461
|
-
};
|
|
462
|
-
});
|
|
463
|
-
const prs = prsPage.nodes.map((p) => {
|
|
464
|
-
p.labels.forEach(recordColor);
|
|
465
|
-
const isDraft = p.isDraft ?? false;
|
|
466
|
-
return {
|
|
467
|
-
kind: 'pr',
|
|
468
|
-
number: p.number,
|
|
469
|
-
title: p.title,
|
|
470
|
-
author: p.author?.login ?? '?',
|
|
471
|
-
createdAt: p.createdAt,
|
|
472
|
-
labels: [...p.labels.map((l) => l.name), ...(isDraft ? ['draft'] : [])],
|
|
473
|
-
body: (p.body ?? '').slice(0, 8_000),
|
|
474
|
-
url: p.url,
|
|
475
|
-
comments: 0,
|
|
476
|
-
isDraft,
|
|
477
|
-
additions: p.additions ?? 0,
|
|
478
|
-
deletions: p.deletions ?? 0,
|
|
479
|
-
// Hydrated lazily by `fetchGithubChecks` for on-screen rows (#664) — the list no
|
|
480
|
-
// longer pays for the CI rollup of every open PR.
|
|
481
|
-
checks: null,
|
|
482
|
-
};
|
|
483
|
-
});
|
|
484
|
-
// Only verified values from the same repository may survive a refresh.
|
|
485
|
-
const previous = hit?.data.repo === `${ownerName.owner}/${ownerName.name}` ? hit.data : undefined;
|
|
486
|
-
for (const issue of issues) {
|
|
487
|
-
const known = previous?.issues.find(row => row.number === issue.number)?.projectIds;
|
|
488
|
-
if (known !== undefined)
|
|
489
|
-
issue.projectIds = known;
|
|
490
|
-
}
|
|
491
|
-
const generation = randomUUID();
|
|
492
|
-
const data = {
|
|
493
|
-
available: true,
|
|
494
|
-
repo: `${ownerName.owner}/${ownerName.name}`,
|
|
495
|
-
syncedAt: new Date().toISOString(),
|
|
496
|
-
issues,
|
|
497
|
-
prs,
|
|
498
|
-
labelColors,
|
|
499
|
-
...(viewerLogin ? { viewerLogin } : {}),
|
|
500
|
-
projectsState: 'refreshing',
|
|
501
|
-
projectsGeneration: generation,
|
|
502
|
-
...(previous?.projects ? { projects: previous.projects } : {}),
|
|
503
|
-
issuesTotal: issuesPage.totalCount,
|
|
504
|
-
prsTotal: prsPage.totalCount,
|
|
505
|
-
issuesNextCursor: issuesPage.nextCursor,
|
|
506
|
-
prsNextCursor: prsPage.nextCursor,
|
|
507
|
-
commentsDeferred: true,
|
|
508
|
-
};
|
|
509
|
-
const projects = projectLookup.then((result) => {
|
|
510
|
-
const metadata = 'membership' in result
|
|
511
|
-
? { generation, state: 'ready', projects: result.projects, membership: result.membership }
|
|
512
|
-
: { generation, state: 'unavailable', reason: result.projectsReason };
|
|
513
|
-
const current = listCache.get(key);
|
|
514
|
-
if (current?.data.projectsGeneration === generation) {
|
|
515
|
-
current.data = {
|
|
516
|
-
...current.data,
|
|
517
|
-
projectsState: metadata.state,
|
|
518
|
-
...(metadata.state === 'ready' ? {
|
|
519
|
-
projects: metadata.projects,
|
|
520
|
-
issues: current.data.issues.map(issue => ({ ...issue, projectIds: metadata.membership?.[issue.number] ?? [] })),
|
|
521
|
-
} : { projectsReason: metadata.reason }),
|
|
522
|
-
};
|
|
523
|
-
}
|
|
524
|
-
return metadata;
|
|
525
|
-
});
|
|
526
|
-
// Concurrent refreshes may finish in reverse order. An older list must not evict
|
|
527
|
-
// the newer generation (and invalidate the newer client's metadata follow-up).
|
|
528
|
-
if ((listCache.get(key)?.order ?? -1) < order && order >= (listRefreshOrder.get(context.key) ?? 0)) {
|
|
529
|
-
dropListEntry(key); // re-insert so this key becomes the newest
|
|
530
|
-
listCache.set(key, { contextKey: context.key, order, at: Date.now(), limit: capped, data, projects });
|
|
531
|
-
projectGenerations.set(generation, key);
|
|
532
|
-
}
|
|
533
|
-
while (listCache.size > LIST_CACHE_MAX) {
|
|
534
|
-
const oldest = listCache.keys().next().value;
|
|
535
|
-
if (oldest === undefined)
|
|
536
|
-
break;
|
|
537
|
-
dropListEntry(oldest);
|
|
538
|
-
}
|
|
539
|
-
return data;
|
|
540
|
-
}
|
|
541
|
-
catch (err) {
|
|
542
|
-
return { available: false, reason: ghFailureReason(err), issues: [], prs: [] };
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
/** A `gh` failure as one readable line. GitHub's own words come on stderr; the Node message
|
|
546
|
-
* starts with the whole argv, and a GraphQL argv is a multi-line query, so its first line is
|
|
547
|
-
* a fragment of that query rather than the reason (open-mercato/cezar#1366). */
|
|
548
|
-
export function ghFailureReason(err) {
|
|
549
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
550
|
-
if (/ENOENT/.test(message))
|
|
551
|
-
return 'gh CLI not found — install it and run `gh auth login`';
|
|
552
|
-
const failure = (err ?? {});
|
|
553
|
-
const stderr = typeof failure.stderr === 'string' ? failure.stderr : '';
|
|
554
|
-
if (stderr.trim()) {
|
|
555
|
-
const lines = stderr.split('\n').map((line) => line.trim()).filter(Boolean);
|
|
556
|
-
return lines.find((line) => !/^Command failed:/i.test(line)) ?? lines[0];
|
|
557
|
-
}
|
|
558
|
-
if (failure.killed === true || typeof failure.signal === 'string')
|
|
559
|
-
return 'GitHub did not answer in time. Refresh to try again.';
|
|
560
|
-
// Without stderr, everything after "Command failed:" is the argv, which is query text.
|
|
561
|
-
if (/^Command failed:/i.test(message))
|
|
562
|
-
return 'GitHub request failed. Refresh to try again.';
|
|
563
|
-
return message.split('\n').map((line) => line.trim()).find(Boolean) ?? 'gh failed';
|
|
564
|
-
}
|
|
565
|
-
/** Bounded lookup already started by the list. Never launch work for an expired generation. */
|
|
566
|
-
export async function fetchGithubProjects(repoRoot, generation) {
|
|
567
|
-
const key = projectGenerations.get(generation);
|
|
568
|
-
const entry = key === undefined ? undefined : listCache.get(key);
|
|
569
|
-
// A generation from another repository, host or account never resolves here, even when
|
|
570
|
-
// its UUID is known: the context is part of what the generation was issued for.
|
|
571
|
-
if (!entry || entry.contextKey !== githubContext(repoRoot).key || entry.data.projectsGeneration !== generation) {
|
|
572
|
-
return { generation, state: 'unavailable', reason: 'Project metadata expired. Refresh to try again.' };
|
|
573
|
-
}
|
|
574
|
-
return entry.projects;
|
|
575
|
-
}
|
|
576
|
-
function firstLine(s) {
|
|
577
|
-
return s.split('\n').find((l) => l.trim().length > 0)?.trim() ?? 'gh failed';
|
|
578
|
-
}
|
|
579
|
-
// On-demand cross-state search stays separate from the hot open list.
|
|
580
|
-
/** Hits per search. `gh search`'s own default is 30; 50 matches the page size the incremental-
|
|
581
|
-
* loading spec settled on and keeps one search to a single `gh` round-trip. */
|
|
582
|
-
export const GH_SEARCH_MAX = GITHUB_SEARCH_MAX;
|
|
583
|
-
/** The `--json` field set each search path requests. Neither path asks for `additions`/`deletions`
|
|
584
|
-
* or `statusCheckRollup` — the same reason the list tier stopped (#664), those are the expensive
|
|
585
|
-
* per-PR lookups.
|
|
586
|
-
*
|
|
587
|
-
* `isDraft` is added for PRs only, and that is a hard requirement rather than a nicety: `gh search
|
|
588
|
-
* issues` does not define the field at all and rejects the whole call with `Unknown JSON field:
|
|
589
|
-
* "isDraft"`, which would turn every text query on the Issues tab into the "could not be searched"
|
|
590
|
-
* degrade. `gh {issue,pr} view` is the opposite — it tolerates the field for both kinds — so only
|
|
591
|
-
* the search path needs to discriminate. */
|
|
592
|
-
const SEARCH_FIELDS = 'number,title,author,createdAt,labels,body,url';
|
|
593
|
-
/** `gh search {prs,issues} --json` field list for `kind`. See `SEARCH_FIELDS` on why `isDraft`
|
|
594
|
-
* cannot be sent to the issues search. */
|
|
595
|
-
function searchJsonFields(kind) {
|
|
596
|
-
return kind === 'pr'
|
|
597
|
-
? `${SEARCH_FIELDS},isDraft,commentsCount`
|
|
598
|
-
: `${SEARCH_FIELDS},assignees,commentsCount`;
|
|
599
|
-
}
|
|
600
|
-
/** `gh search issues|prs` returns `commentsCount` where the list tier gets its counts from a
|
|
601
|
-
* separate GraphQL walk. Same value, different spelling — normalized into `ForgeItem.comments`. */
|
|
602
|
-
const ghSearchHitSchema = ghIssueSchema.extend({
|
|
603
|
-
assignees: z.array(z.object({ login: z.string() })).optional(),
|
|
604
|
-
isDraft: z.boolean().default(false),
|
|
605
|
-
commentsCount: z.number().default(0),
|
|
606
|
-
});
|
|
607
|
-
/** `gh {issue,pr} view <n> --json …` — the exact-number path. Shares `ghIssueSchema`'s core;
|
|
608
|
-
* `isDraft`/`additions`/`deletions` are PR-only and default harmlessly for issues. */
|
|
609
|
-
const ghViewHitSchema = ghIssueSchema.extend({
|
|
610
|
-
state: z.string().optional(),
|
|
611
|
-
mergedAt: z.unknown().optional(),
|
|
612
|
-
assignees: z.array(z.object({ login: z.string() })).optional(),
|
|
613
|
-
isDraft: z.boolean().default(false),
|
|
614
|
-
additions: z.number().default(0),
|
|
615
|
-
deletions: z.number().default(0),
|
|
616
|
-
});
|
|
617
|
-
/** Flatten one validated hit into the `ForgeItem` the tab's rows already render. `checks: null`
|
|
618
|
-
* is what the list tier ships too since #664 — the glyph hydrates lazily via `/api/github/checks`
|
|
619
|
-
* — so a searched row and a listed row are indistinguishable to the UI. */
|
|
620
|
-
function toSearchItem(kind, hit, labelColors) {
|
|
621
|
-
for (const label of hit.labels) {
|
|
622
|
-
if (label.color && !labelColors[label.name])
|
|
623
|
-
labelColors[label.name] = label.color;
|
|
624
|
-
}
|
|
625
|
-
const item = {
|
|
626
|
-
kind,
|
|
627
|
-
number: hit.number,
|
|
628
|
-
title: hit.title,
|
|
629
|
-
author: hit.author?.login ?? '?',
|
|
630
|
-
createdAt: hit.createdAt,
|
|
631
|
-
labels: hit.labels.map((l) => l.name),
|
|
632
|
-
body: (hit.body ?? '').slice(0, 8_000),
|
|
633
|
-
url: hit.url,
|
|
634
|
-
comments: hit.commentsCount,
|
|
635
|
-
...(kind === 'issue' && hit.assignees ? { assignees: hit.assignees.map(a => a.login) } : {}),
|
|
636
|
-
};
|
|
637
|
-
if (kind === 'pr') {
|
|
638
|
-
item.isDraft = hit.isDraft;
|
|
639
|
-
// Draft is a label on list rows as well as a flag — keep the parity so filtering by the
|
|
640
|
-
// `draft` chip behaves the same on a searched row.
|
|
641
|
-
if (hit.isDraft)
|
|
642
|
-
item.labels = [...item.labels, 'draft'];
|
|
643
|
-
if ('additions' in hit)
|
|
644
|
-
item.additions = hit.additions;
|
|
645
|
-
if ('deletions' in hit)
|
|
646
|
-
item.deletions = hit.deletions;
|
|
647
|
-
item.checks = null;
|
|
648
|
-
}
|
|
649
|
-
return item;
|
|
650
|
-
}
|
|
651
|
-
/** `gh {pr,issue} view <n>` diagnostics that name the REQUESTED item as absent. A bare
|
|
652
|
-
* "not found" / 404 or "Could not resolve to a Repository" also fails a view, but says the
|
|
653
|
-
* repository (or auth) is the problem, not that the number does not exist. */
|
|
654
|
-
const MISSING_ITEM_RE = /could not resolve to an? (?:pullrequest|issue|issueorpullrequest|pull request|issue or pull request)\b|no (?:pull requests|issues) found/i;
|
|
655
|
-
/** The exact `gh view` call plus its parse. `null` only for a confirmed-missing item; anything
|
|
656
|
-
* else (transport, auth, repository, unparseable output) throws. */
|
|
657
|
-
async function viewGithubHit(repoRoot, kind, number) {
|
|
658
|
-
try {
|
|
659
|
-
const out = await gh(repoRoot, [
|
|
660
|
-
kind === 'pr' ? 'pr' : 'issue',
|
|
661
|
-
'view',
|
|
662
|
-
String(number),
|
|
663
|
-
'--json',
|
|
664
|
-
kind === 'pr' ? `${SEARCH_FIELDS},isDraft,additions,deletions,state,mergedAt` : `${SEARCH_FIELDS},assignees`,
|
|
665
|
-
]);
|
|
666
|
-
const hit = ghViewHitSchema.parse(JSON.parse(out));
|
|
667
|
-
if (kind === 'pr' && hit.state === 'MERGED') {
|
|
668
|
-
const handle = await resolveRepoHandle(repoRoot);
|
|
669
|
-
if (handle)
|
|
670
|
-
mergedPullRequestObservations.observe({ owner: handle.owner, repo: handle.name, number }, hit);
|
|
671
|
-
}
|
|
672
|
-
return hit;
|
|
673
|
-
}
|
|
674
|
-
catch (err) {
|
|
675
|
-
if (MISSING_ITEM_RE.test(err instanceof Error ? err.message : String(err)))
|
|
676
|
-
return null;
|
|
677
|
-
throw err;
|
|
678
|
-
}
|
|
679
|
-
}
|
|
680
|
-
/** `view` exposes comment bodies rather than a count. Read the single issue resource
|
|
681
|
-
* (PRs share this endpoint) instead of paginating a potentially enormous thread.
|
|
682
|
-
* gh resolves placeholders in repoRoot, just as it resolves the preceding view call. */
|
|
683
|
-
async function finishViewHit(repoRoot, kind, number, hit, labelColors) {
|
|
684
|
-
const commentsCount = z.number().int().nonnegative().parse(JSON.parse(await gh(repoRoot, ['api', `repos/{owner}/{repo}/issues/${number}`, '--jq', '.comments'], 8_000)));
|
|
685
|
-
return toSearchItem(kind, { ...hit, commentsCount }, labelColors);
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
* One issue or PR by number, in any state (#692). `null` when `gh` confirms the item is absent;
|
|
689
|
-
* throws on every other failure. `labelColors` is an optional out-param.
|
|
690
|
-
*/
|
|
691
|
-
export async function viewGithubItem(repoRoot, kind, number, labelColors = {}) {
|
|
692
|
-
const hit = await viewGithubHit(repoRoot, kind, number);
|
|
693
|
-
return hit ? finishViewHit(repoRoot, kind, number, hit, labelColors) : null;
|
|
694
|
-
}
|
|
695
|
-
/**
|
|
696
|
-
* Search any state: exact numbers try a direct lookup, then text fallback; text search omits
|
|
697
|
-
* state restriction. Return availability and a reason on failure instead of throwing.
|
|
698
|
-
*/
|
|
699
|
-
export async function searchGithubItems(repoRoot, kind, query, limit = GH_SEARCH_MAX) {
|
|
700
|
-
const trimmed = query.trim();
|
|
701
|
-
if (trimmed === '')
|
|
702
|
-
return { available: true, items: [] };
|
|
703
|
-
const capped = Math.min(Math.max(limit, 1), GH_SEARCH_MAX);
|
|
704
|
-
if (process.env.CEZ_DRY_RUN === '1') {
|
|
705
|
-
const mock = mockGithub();
|
|
706
|
-
const pool = kind === 'issue' ? mock.issues : mock.prs;
|
|
707
|
-
const queryText = trimmed.toLowerCase();
|
|
708
|
-
const numeric = queryText.replace(/^#/, '');
|
|
709
|
-
const idOnly = /^\d+$/.test(numeric);
|
|
710
|
-
// The fixture obeys `limit` and flags `truncated` on the live path's own rule (#838). The
|
|
711
|
-
// catalog is a handful of rows, so the cap never bites in the demo itself — but offline mode
|
|
712
|
-
// is the only place anyone developing without `gh` exercises cap-and-truncate at all, and a
|
|
713
|
-
// dry-run that returned the whole pool unflagged would hide a regression in it.
|
|
714
|
-
const items = pool
|
|
715
|
-
.filter((item) => idOnly
|
|
716
|
-
? String(item.number).includes(numeric)
|
|
717
|
-
: `#${item.number} ${item.title} ${item.author} ${item.body}`.toLowerCase().includes(queryText))
|
|
718
|
-
.slice(0, capped)
|
|
719
|
-
// Search rows defer checks to the same hydration endpoint as live results. Copy rather
|
|
720
|
-
// than mutate: the mock checks endpoint still reads the fixture's passing/failing values.
|
|
721
|
-
.map(item => item.kind === 'pr' ? { ...item, checks: null } : item);
|
|
722
|
-
return { available: true, items, truncated: items.length >= capped };
|
|
723
|
-
}
|
|
724
|
-
const labelColors = {};
|
|
725
|
-
const numeric = trimmed.replace(/^#/, '');
|
|
726
|
-
try {
|
|
727
|
-
if (/^\d+$/.test(numeric)) {
|
|
728
|
-
// `Number()` before interpolation: the regex already guarantees digits, but the number is
|
|
729
|
-
// user input reaching an argv, so it is normalized rather than passed through verbatim.
|
|
730
|
-
const number = Number(numeric);
|
|
731
|
-
// Any failure of the exact view call or its parse (and a missing number) falls through to
|
|
732
|
-
// the text search below. The comment count is outside that guard: its failure reports
|
|
733
|
-
// unavailable rather than an invented zero.
|
|
734
|
-
let hit = null;
|
|
735
|
-
try {
|
|
736
|
-
hit = await viewGithubHit(repoRoot, kind, number);
|
|
737
|
-
}
|
|
738
|
-
catch {
|
|
739
|
-
// fall through
|
|
740
|
-
}
|
|
741
|
-
if (hit) {
|
|
742
|
-
const item = await finishViewHit(repoRoot, kind, number, hit, labelColors);
|
|
743
|
-
return await hydrateSearchProjects(repoRoot, kind, { available: true, items: [item], labelColors });
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
// The memoized handle first (usually a hit). Its `null` is deliberately ambiguous — it swallows
|
|
747
|
-
// "gh is missing" and "no remote" alike — so on a miss, ask once more directly and let the real
|
|
748
|
-
// failure reach the catch below, where it becomes the same honest hint the list tier gives.
|
|
749
|
-
// Only a genuinely unparseable slug reaches the "no remote" reason.
|
|
750
|
-
const handle = (await resolveRepoHandle(repoRoot)) ??
|
|
751
|
-
parseOwnerName(await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']));
|
|
752
|
-
if (!handle) {
|
|
753
|
-
return { available: false, reason: 'no GitHub remote to search', items: [] };
|
|
754
|
-
}
|
|
755
|
-
const out = await gh(repoRoot, [
|
|
756
|
-
'search',
|
|
757
|
-
kind === 'pr' ? 'prs' : 'issues',
|
|
758
|
-
'--repo',
|
|
759
|
-
`${handle.owner}/${handle.name}`,
|
|
760
|
-
'--limit',
|
|
761
|
-
String(capped),
|
|
762
|
-
'--json',
|
|
763
|
-
searchJsonFields(kind),
|
|
764
|
-
// End-of-flags, then the query: `gh` parses a leading `-`/`--` as a flag otherwise, so a
|
|
765
|
-
// flag-shaped query would degrade the tab to "GitHub could not be searched: unknown flag",
|
|
766
|
-
// and the exact text `--web` would match `gh search`'s own `-w, --web` and open a browser
|
|
767
|
-
// on the cockpit's host. Behind `--` it is search text, which is all the box ever means.
|
|
768
|
-
'--',
|
|
769
|
-
trimmed,
|
|
770
|
-
]);
|
|
771
|
-
const hits = z.array(ghSearchHitSchema).parse(JSON.parse(out));
|
|
772
|
-
// Older gh/GHES search treats repeated repo qualifiers as OR. Never hydrate a foreign
|
|
773
|
-
// hit's number with this repository's memberships or expose it as a local detail row.
|
|
774
|
-
const prefix = `/${handle.owner}/${handle.name}/${kind === 'pr' ? 'pull' : 'issues'}/`.toLowerCase();
|
|
775
|
-
if (hits.some(hit => {
|
|
776
|
-
try {
|
|
777
|
-
return new URL(hit.url).pathname.toLowerCase() !== `${prefix}${hit.number}`;
|
|
778
|
-
}
|
|
779
|
-
catch {
|
|
780
|
-
return true;
|
|
781
|
-
}
|
|
782
|
-
}))
|
|
783
|
-
return { available: false, reason: 'GitHub returned results outside this repository. Remove repository qualifiers and try again.', items: [] };
|
|
784
|
-
return await hydrateSearchProjects(repoRoot, kind, {
|
|
785
|
-
available: true,
|
|
786
|
-
items: hits.map((hit) => toSearchItem(kind, hit, labelColors)),
|
|
787
|
-
truncated: hits.length >= capped,
|
|
788
|
-
labelColors,
|
|
789
|
-
});
|
|
790
|
-
}
|
|
791
|
-
catch (err) {
|
|
792
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
793
|
-
const reason = /ENOENT/.test(message)
|
|
794
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
795
|
-
: firstLine(message);
|
|
796
|
-
return { available: false, reason, items: [] };
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
/** The list's metadata window contains only open issues. Search must look up its own window,
|
|
800
|
-
* including closed issues, with the same bounds and unknown-on-failure semantics (#90). */
|
|
801
|
-
async function hydrateSearchProjects(repoRoot, kind, data) {
|
|
802
|
-
if (kind !== 'issue' || data.items.length === 0)
|
|
803
|
-
return data;
|
|
804
|
-
const handle = await resolveRepoHandle(repoRoot);
|
|
805
|
-
if (!handle)
|
|
806
|
-
return { ...data, projectsReason: 'Project boards unavailable for this repository.' };
|
|
807
|
-
const deadline = Date.now() + 15_000;
|
|
808
|
-
const run = (query, variables) => {
|
|
809
|
-
const remaining = deadline - Date.now();
|
|
810
|
-
if (remaining <= 0)
|
|
811
|
-
return Promise.reject(new Error('Project lookup timed out'));
|
|
812
|
-
const args = ghGraphqlArgs(query, variables);
|
|
813
|
-
return gh(repoRoot, args, Math.min(remaining, 8_000));
|
|
814
|
-
};
|
|
815
|
-
const projects = await fetchIssueProjects(run, handle.owner, handle.name, data.items.map(item => item.number));
|
|
816
|
-
if ('projectsReason' in projects)
|
|
817
|
-
return { ...data, projectsReason: projects.projectsReason };
|
|
818
|
-
return { ...data, items: data.items.map(item => ({ ...item, projectIds: projects.membership[item.number] ?? [] })) };
|
|
819
|
-
}
|
|
820
|
-
/** The dry-run catalog, paged like the real list: numeric offset cursors per side, done flags
|
|
821
|
-
* honored, exact totals, and counts deferred to the counts route (hearsay-tools/cezarion#1183). */
|
|
822
|
-
function mockGithubPage(limit, page) {
|
|
823
|
-
const full = mockGithub();
|
|
824
|
-
const side = (rows, cursor, done) => {
|
|
825
|
-
const start = done ? rows.length : Number(cursor ?? 0);
|
|
826
|
-
const slice = rows.slice(start, start + Math.max(limit, 1));
|
|
827
|
-
const end = start + slice.length;
|
|
828
|
-
return { rows: slice.map((row) => ({ ...row, comments: 0 })), next: end < rows.length ? String(end) : null };
|
|
829
|
-
};
|
|
830
|
-
const issues = side(full.issues, page.issuesCursor, page.issuesDone);
|
|
831
|
-
const prs = side(full.prs, page.prsCursor, page.prsDone);
|
|
832
|
-
const firstPage = !page.issuesCursor && !page.prsCursor && !page.issuesDone && !page.prsDone;
|
|
833
|
-
const { viewerLogin, ...rest } = full;
|
|
834
|
-
return {
|
|
835
|
-
...rest,
|
|
836
|
-
...(firstPage && viewerLogin ? { viewerLogin } : {}),
|
|
837
|
-
issues: issues.rows,
|
|
838
|
-
prs: prs.rows,
|
|
839
|
-
issuesTotal: full.issues.length,
|
|
840
|
-
prsTotal: full.prs.length,
|
|
841
|
-
issuesNextCursor: issues.next,
|
|
842
|
-
prsNextCursor: prs.next,
|
|
843
|
-
commentsDeferred: true,
|
|
844
|
-
};
|
|
845
|
-
}
|
|
846
|
-
/** CEZ_DRY_RUN=1 — a small fixed catalog so the GitHub tab is demoable offline. */
|
|
847
|
-
function mockGithub() {
|
|
848
|
-
const mk = (over) => ({
|
|
849
|
-
author: 'mock',
|
|
850
|
-
createdAt: new Date(Date.now() - over.number * 3_600_000).toISOString(),
|
|
851
|
-
labels: [],
|
|
852
|
-
url: `https://github.com/mock/repo/${over.kind === 'pr' ? 'pull' : 'issues'}/${over.number}`,
|
|
853
|
-
comments: 0,
|
|
854
|
-
...over,
|
|
855
|
-
});
|
|
856
|
-
return {
|
|
857
|
-
available: true,
|
|
858
|
-
repo: 'mock/repo',
|
|
859
|
-
viewerLogin: 'octocat',
|
|
860
|
-
projects: [{ id: 'mock-delivery', title: 'Delivery', url: 'https://github.com/users/mock/projects/1' }],
|
|
861
|
-
syncedAt: new Date().toISOString(),
|
|
862
|
-
issues: [
|
|
863
|
-
mk({ kind: 'issue', assignees: ['octocat'], projectIds: ['mock-delivery'], number: 142, title: 'Login form drops session on refresh', labels: ['bug', 'auth'], comments: 3, body: 'Repro: log in, hit reload — you land back on /login. The session cookie is set correctly, but the client store rehydrates before the cookie check resolves, so the auth guard redirects.' }),
|
|
864
|
-
mk({ kind: 'issue', assignees: ['ada'], projectIds: [], number: 139, title: 'Add --json flag to cez CLI output', labels: ['enhancement', 'cli'], comments: 1, body: 'For scripting it would help if `cez list` and `cez status` could emit machine-readable JSON instead of the table view.' }),
|
|
865
|
-
mk({ kind: 'issue', assignees: [], projectIds: ['mock-delivery'], number: 135, title: 'Flaky e2e: worktree cleanup race on cancel', labels: ['bug', 'flaky-test'], comments: 6, body: 'Cancelling a run while the agent holds a file lock leaves a dangling worktree. The next run on the same branch then fails with "worktree already exists".' }),
|
|
866
|
-
],
|
|
867
|
-
prs: [
|
|
868
|
-
mk({ kind: 'pr', number: 128, title: 'Fix flaky auth test in CI', labels: ['tests'], checks: 'passing', additions: 6, deletions: 3, body: 'Loosens the timing assertion in refresh.test.ts to a realistic budget.' }),
|
|
869
|
-
mk({ kind: 'pr', number: 124, title: 'Rate limit /api/runs', labels: ['server', 'draft'], isDraft: true, checks: 'failing', additions: 118, deletions: 7, comments: 4, body: 'Draft: token-bucket middleware on the runs router. Still needs the config surface and README docs before review.' }),
|
|
870
|
-
],
|
|
871
|
-
labelColors: {
|
|
872
|
-
bug: 'd73a4a',
|
|
873
|
-
auth: '5319e7',
|
|
874
|
-
enhancement: 'a2eeef',
|
|
875
|
-
cli: '0e8a16',
|
|
876
|
-
'flaky-test': 'fbca04',
|
|
877
|
-
tests: 'c5def5',
|
|
878
|
-
server: '1d76db',
|
|
879
|
-
draft: '6a737d',
|
|
880
|
-
},
|
|
881
|
-
};
|
|
882
|
-
}
|
|
883
|
-
// ---- comment threads (#499 Phase 2) ----------------------------------------
|
|
884
|
-
// A lazy per-thread fetch behind `GET /api/github/comments/:kind/:number`: the
|
|
885
|
-
// conversation comments (issues endpoint — GitHub serves PR conversation
|
|
886
|
-
// comments there too), plus submitted reviews for PRs, normalized into one
|
|
887
|
-
// chronological `ForgeComment[]`. Its own bounded 60 s cache keeps an open
|
|
888
|
-
// detail view from re-fetching on every focus. Degrades to `available: false`
|
|
889
|
-
// exactly like the list fetch — never a 5xx.
|
|
890
|
-
const ghCommentUser = z.object({ login: z.string(), avatar_url: z.string().nullish() }).nullish();
|
|
891
|
-
const ghIssueCommentSchema = z.object({
|
|
892
|
-
id: z.number(),
|
|
893
|
-
user: ghCommentUser,
|
|
894
|
-
created_at: z.string(),
|
|
895
|
-
body: z.string().nullish(),
|
|
896
|
-
html_url: z.string(),
|
|
897
|
-
});
|
|
898
|
-
const ghReviewSchema = z.object({
|
|
899
|
-
id: z.number(),
|
|
900
|
-
user: ghCommentUser,
|
|
901
|
-
body: z.string().nullish(),
|
|
902
|
-
state: z.string(),
|
|
903
|
-
submitted_at: z.string().nullish(),
|
|
904
|
-
html_url: z.string(),
|
|
905
|
-
});
|
|
906
|
-
// ---- timeline events (#525) -------------------------------------------------
|
|
907
|
-
// The thread's non-comment history — commits, label changes, assignments, merges, force-pushes,
|
|
908
|
-
// cross-references. Sourced from `/issues/{n}/timeline`, which returns comments AND events in one
|
|
909
|
-
// chronological stream, so the `commented` rows keep flowing through `normalizeComments` unchanged
|
|
910
|
-
// and `comments[]` stays exactly what BACKWARD_COMPATIBILITY.md §2 promises.
|
|
911
|
-
/** The event kinds rendered in v1 — an allowlist, so a new GitHub event type is dropped rather
|
|
912
|
-
* than rendered and can never crash or clutter the thread. Real timelines carry plenty that
|
|
913
|
-
* github.com itself doesn't surface (`subscribed`, `mentioned`, `review_requested`).
|
|
914
|
-
*
|
|
915
|
-
* `reviewed` is deliberately absent: timeline `reviewed` rows DO carry a body and would work,
|
|
916
|
-
* but `/pulls/{n}/reviews` is already normalized, chipped and empty-body-filtered, so sourcing
|
|
917
|
-
* both would render every review twice. */
|
|
918
|
-
export const TIMELINE_EVENT_KINDS = new Set([
|
|
919
|
-
'committed',
|
|
920
|
-
'labeled',
|
|
921
|
-
'unlabeled',
|
|
922
|
-
'assigned',
|
|
923
|
-
'unassigned',
|
|
924
|
-
'merged',
|
|
925
|
-
'closed',
|
|
926
|
-
'reopened',
|
|
927
|
-
'head_ref_force_pushed',
|
|
928
|
-
'cross-referenced',
|
|
929
|
-
'renamed',
|
|
930
|
-
]);
|
|
931
|
-
/** Events get their OWN cap, independent of `THREAD_ENTRY_CAP`. A combined cap would mean a
|
|
932
|
-
* thread with 150 comments and 100 events returns ~120 comments — silently removing contents
|
|
933
|
-
* from a §2-protected response. */
|
|
934
|
-
export const TIMELINE_EVENT_CAP = 200;
|
|
935
|
-
/** `gh api --paginate` has no page limit, so the timeline fetch hand-rolls a bounded loop. */
|
|
936
|
-
export const TIMELINE_MAX_PAGES = 10;
|
|
937
|
-
/** ONE budget shared by every page. `gh()`'s timeout is per invocation, so ten pages at the 15 s
|
|
938
|
-
* default would put the ceiling at 150 s — an order of magnitude worse than the single
|
|
939
|
-
* `--paginate` spawn this replaces. The loop tracks a deadline and passes what's left. */
|
|
940
|
-
export const TIMELINE_BUDGET_MS = 15_000;
|
|
941
|
-
/** Never spawn a page that cannot finish. A bare `remaining <= 0` guard catches only the exact
|
|
942
|
-
* boundary; the realistic case is 300 ms left, which spawns `gh` with a 300 ms timeout, throws,
|
|
943
|
-
* and is indistinguishable from a real endpoint failure. */
|
|
944
|
-
export const TIMELINE_MIN_PAGE_MS = 2_000;
|
|
945
|
-
/** `committed` messages are trimmed to their first line, then this. */
|
|
946
|
-
const COMMIT_MESSAGE_CAP = 120;
|
|
947
|
-
/** One timeline row. `event` stays a loose `z.string()` so unknown kinds parse and are dropped by
|
|
948
|
-
* the allowlist rather than throwing the whole page. Extras are stripped by default — notably
|
|
949
|
-
* `author.email`, which is read for nothing and must not reach the wire type. */
|
|
950
|
-
export const ghTimelineEventSchema = z.object({
|
|
951
|
-
event: z.string(),
|
|
952
|
-
id: z.number().nullish(),
|
|
953
|
-
node_id: z.string().nullish(),
|
|
954
|
-
created_at: z.string().nullish(),
|
|
955
|
-
actor: z.object({ login: z.string(), avatar_url: z.string().nullish() }).nullish(),
|
|
956
|
-
url: z.string().nullish(),
|
|
957
|
-
html_url: z.string().nullish(),
|
|
958
|
-
// `committed`
|
|
959
|
-
sha: z.string().nullish(),
|
|
960
|
-
message: z.string().nullish(),
|
|
961
|
-
author: z.object({ name: z.string().nullish(), date: z.string().nullish() }).nullish(),
|
|
962
|
-
// `labeled` / `unlabeled`
|
|
963
|
-
label: z.object({ name: z.string(), color: z.string().nullish() }).nullish(),
|
|
964
|
-
// `assigned` / `unassigned`
|
|
965
|
-
assignee: z.object({ login: z.string() }).nullish(),
|
|
966
|
-
// `renamed`
|
|
967
|
-
rename: z.object({ from: z.string().nullish(), to: z.string().nullish() }).nullish(),
|
|
968
|
-
// `cross-referenced`
|
|
969
|
-
source: z
|
|
970
|
-
.object({
|
|
971
|
-
issue: z
|
|
972
|
-
.object({
|
|
973
|
-
number: z.number().nullish(),
|
|
974
|
-
title: z.string().nullish(),
|
|
975
|
-
html_url: z.string().nullish(),
|
|
976
|
-
pull_request: z.unknown().nullish(),
|
|
977
|
-
})
|
|
978
|
-
.nullish(),
|
|
979
|
-
})
|
|
980
|
-
.nullish(),
|
|
981
|
-
});
|
|
982
|
-
const REVIEW_STATE = {
|
|
983
|
-
APPROVED: 'approved',
|
|
984
|
-
CHANGES_REQUESTED: 'changes_requested',
|
|
985
|
-
COMMENTED: 'commented',
|
|
986
|
-
DISMISSED: 'dismissed',
|
|
987
|
-
};
|
|
988
|
-
/** First 200 thread entries, then `truncated`; each body sliced to 8 000 chars (same cap as
|
|
989
|
-
* item bodies). */
|
|
990
|
-
export const THREAD_ENTRY_CAP = 200;
|
|
991
|
-
const COMMENT_BODY_CAP = 8_000;
|
|
992
|
-
/** `gh api …/issues/{n}/comments` JSON → `ForgeComment[]`. Exported for unit tests. */
|
|
993
|
-
export function normalizeComments(raw) {
|
|
994
|
-
return z.array(ghIssueCommentSchema).parse(raw).map((c) => defined({
|
|
995
|
-
id: c.id,
|
|
996
|
-
author: c.user?.login ?? '?',
|
|
997
|
-
avatarUrl: c.user?.avatar_url ?? undefined,
|
|
998
|
-
createdAt: c.created_at,
|
|
999
|
-
body: (c.body ?? '').slice(0, COMMENT_BODY_CAP),
|
|
1000
|
-
kind: 'comment',
|
|
1001
|
-
url: c.html_url,
|
|
1002
|
-
}));
|
|
1003
|
-
}
|
|
1004
|
-
/** `gh api …/pulls/{n}/reviews` JSON → `ForgeComment[]`. Reviews with an empty body AND state
|
|
1005
|
-
* COMMENTED/PENDING carry no signal in a flat thread and are dropped; the rest map to
|
|
1006
|
-
* `kind: 'review'` (Q4). Exported for unit tests. */
|
|
1007
|
-
export function normalizeReviews(raw) {
|
|
1008
|
-
return z
|
|
1009
|
-
.array(ghReviewSchema)
|
|
1010
|
-
.parse(raw)
|
|
1011
|
-
.filter((r) => {
|
|
1012
|
-
const state = r.state.toUpperCase();
|
|
1013
|
-
const emptyBody = (r.body ?? '').trim().length === 0;
|
|
1014
|
-
return !(emptyBody && (state === 'COMMENTED' || state === 'PENDING'));
|
|
1015
|
-
})
|
|
1016
|
-
.map((r) => defined({
|
|
1017
|
-
id: r.id,
|
|
1018
|
-
author: r.user?.login ?? '?',
|
|
1019
|
-
avatarUrl: r.user?.avatar_url ?? undefined,
|
|
1020
|
-
createdAt: r.submitted_at ?? '',
|
|
1021
|
-
body: (r.body ?? '').slice(0, COMMENT_BODY_CAP),
|
|
1022
|
-
kind: 'review',
|
|
1023
|
-
reviewState: REVIEW_STATE[r.state.toUpperCase()],
|
|
1024
|
-
url: r.html_url,
|
|
1025
|
-
}));
|
|
1026
|
-
}
|
|
1027
|
-
/**
|
|
1028
|
-
* `gh api …/issues/{n}/timeline` JSON → `ForgeTimelineEvent[]`, plus whether the cap fired.
|
|
1029
|
-
*
|
|
1030
|
-
* Returns `truncated` rather than just the array because the caller has no other way to learn it:
|
|
1031
|
-
* `events.length === TIMELINE_EVENT_CAP` is ambiguous on a thread with exactly that many.
|
|
1032
|
-
*
|
|
1033
|
-
* Three details here are load-bearing and were verified against a real timeline, not assumed:
|
|
1034
|
-
*
|
|
1035
|
-
* 1. **`committed` rows return `created_at: null`** — the real timestamp is at `author.date`.
|
|
1036
|
-
* Mapping `created_at` naively yields `createdAt: null` on every commit, which string-sorts to
|
|
1037
|
-
* the top and silently reorders the entire thread.
|
|
1038
|
-
* 2. **`committed` carries a git author, not a GitHub actor** — a name, no login, no avatar.
|
|
1039
|
-
* 3. **The cap keeps the NEWEST events — `slice(-cap)`**, the opposite of the neighbouring
|
|
1040
|
-
* `mergeThread`, which head-slices. The timeline arrives oldest-first, so `slice(0, cap)` would
|
|
1041
|
-
* retain 200 stale day-one `labeled` rows and discard the merge and the recent commits — the
|
|
1042
|
-
* exact rows #525 asks for.
|
|
1043
|
-
*
|
|
1044
|
-
* Exported for unit tests.
|
|
1045
|
-
*/
|
|
1046
|
-
export function normalizeEvents(raw, cap = TIMELINE_EVENT_CAP) {
|
|
1047
|
-
const rows = z.array(ghTimelineEventSchema).parse(raw);
|
|
1048
|
-
const mapped = [];
|
|
1049
|
-
rows.forEach((row, index) => {
|
|
1050
|
-
const kind = row.event;
|
|
1051
|
-
if (!TIMELINE_EVENT_KINDS.has(kind))
|
|
1052
|
-
return; // unknown//noise → dropped, never rendered
|
|
1053
|
-
// Per-kind timestamp resolution — see (1) above.
|
|
1054
|
-
const rawAt = kind === 'committed' ? row.author?.date : row.created_at;
|
|
1055
|
-
if (!rawAt)
|
|
1056
|
-
return; // no resolvable timestamp → drop, rather than merge at an arbitrary spot
|
|
1057
|
-
// `author.date` arrives with a numeric offset (`+02:00`); normalize so the string compare the
|
|
1058
|
-
// thread sorts by stays correct across zones.
|
|
1059
|
-
const parsedAt = new Date(rawAt);
|
|
1060
|
-
if (Number.isNaN(parsedAt.getTime()))
|
|
1061
|
-
return;
|
|
1062
|
-
const createdAt = parsedAt.toISOString();
|
|
1063
|
-
// Per-kind actor resolution — see (2) above.
|
|
1064
|
-
const actor = (kind === 'committed' ? row.author?.name : row.actor?.login) ?? '?';
|
|
1065
|
-
// Identity: `sha` sits ahead of `node_id` deliberately. `committed` rows carry both, and a
|
|
1066
|
-
// node_id-first order would key commits by an opaque `C_kwDO…` blob instead of the SHA, which
|
|
1067
|
-
// is the natural, debuggable identifier and is already the rollup key. The bare-index fallback
|
|
1068
|
-
// reaches only `cross-referenced`, the one kind with no identity at all — as a general scheme
|
|
1069
|
-
// it would be wrong, since the id becomes the React key and an index over the post-sort array
|
|
1070
|
-
// shifts for every row below an insertion, remounting them on each 60 s refetch.
|
|
1071
|
-
const identity = row.id ?? row.sha ?? row.node_id ?? index;
|
|
1072
|
-
const event = {
|
|
1073
|
-
id: `evt-${identity}`,
|
|
1074
|
-
kind,
|
|
1075
|
-
actor,
|
|
1076
|
-
createdAt,
|
|
1077
|
-
};
|
|
1078
|
-
// A git author has no avatar, so `committed` deliberately carries none.
|
|
1079
|
-
if (kind !== 'committed' && row.actor?.avatar_url)
|
|
1080
|
-
event.avatarUrl = row.actor.avatar_url;
|
|
1081
|
-
switch (kind) {
|
|
1082
|
-
case 'committed': {
|
|
1083
|
-
// Enforce the full-40-hex invariant the rollup query depends on rather than assuming it:
|
|
1084
|
-
// `oid` rejects anything else, and a malformed value embedded in the batched query would
|
|
1085
|
-
// cost the whole chunk its glyphs instead of just this commit.
|
|
1086
|
-
if (row.sha && /^[0-9a-f]{40}$/i.test(row.sha))
|
|
1087
|
-
event.sha = row.sha;
|
|
1088
|
-
if (row.message)
|
|
1089
|
-
event.message = (row.message.split('\n')[0] ?? '').slice(0, COMMIT_MESSAGE_CAP);
|
|
1090
|
-
if (row.html_url)
|
|
1091
|
-
event.url = row.html_url;
|
|
1092
|
-
break;
|
|
1093
|
-
}
|
|
1094
|
-
case 'labeled':
|
|
1095
|
-
case 'unlabeled': {
|
|
1096
|
-
if (row.label) {
|
|
1097
|
-
event.label = { name: row.label.name };
|
|
1098
|
-
if (row.label.color)
|
|
1099
|
-
event.label.color = row.label.color;
|
|
1100
|
-
}
|
|
1101
|
-
break;
|
|
1102
|
-
}
|
|
1103
|
-
case 'assigned':
|
|
1104
|
-
case 'unassigned': {
|
|
1105
|
-
if (row.assignee?.login)
|
|
1106
|
-
event.subject = row.assignee.login;
|
|
1107
|
-
break;
|
|
1108
|
-
}
|
|
1109
|
-
case 'renamed': {
|
|
1110
|
-
if (row.rename?.to)
|
|
1111
|
-
event.subject = row.rename.to;
|
|
1112
|
-
break;
|
|
1113
|
-
}
|
|
1114
|
-
case 'cross-referenced': {
|
|
1115
|
-
const issue = row.source?.issue;
|
|
1116
|
-
if (issue?.number != null)
|
|
1117
|
-
event.refNumber = issue.number;
|
|
1118
|
-
if (issue?.title)
|
|
1119
|
-
event.refTitle = issue.title;
|
|
1120
|
-
if (issue)
|
|
1121
|
-
event.refIsPr = Boolean(issue.pull_request);
|
|
1122
|
-
if (issue?.html_url)
|
|
1123
|
-
event.url = issue.html_url;
|
|
1124
|
-
break;
|
|
1125
|
-
}
|
|
1126
|
-
default:
|
|
1127
|
-
break;
|
|
1128
|
-
}
|
|
1129
|
-
mapped.push(event);
|
|
1130
|
-
});
|
|
1131
|
-
const truncated = mapped.length > cap;
|
|
1132
|
-
// slice(-cap), NOT slice(0, cap) — see (3) above.
|
|
1133
|
-
return { events: truncated ? mapped.slice(-cap) : mapped, truncated };
|
|
1134
|
-
}
|
|
1135
|
-
/** Merge comment/review lists chronologically (oldest first) and apply the entry cap. Exported
|
|
1136
|
-
* for unit tests. */
|
|
1137
|
-
export function mergeThread(parts, cap = THREAD_ENTRY_CAP) {
|
|
1138
|
-
const all = parts.flat().sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
1139
|
-
const truncated = all.length > cap;
|
|
1140
|
-
return { comments: truncated ? all.slice(0, cap) : all, truncated };
|
|
1141
|
-
}
|
|
1142
|
-
// Per-thread cache: keyed `repoRoot␀kind#number` (the root scopes the key — two projects each
|
|
1143
|
-
// having a PR #42 must not collide; step 2.6), same 60 s TTL as the list cache but BOUNDED — a
|
|
1144
|
-
// long browsing session can't grow it without limit (Map preserves insertion order → oldest
|
|
1145
|
-
// first).
|
|
1146
|
-
const commentsCache = new Map();
|
|
1147
|
-
const COMMENTS_CACHE_MAX = 50;
|
|
1148
|
-
function cacheComments(key, data) {
|
|
1149
|
-
commentsCache.delete(key); // re-insert so this key becomes the newest
|
|
1150
|
-
commentsCache.set(key, { at: Date.now(), data });
|
|
1151
|
-
while (commentsCache.size > COMMENTS_CACHE_MAX) {
|
|
1152
|
-
const oldest = commentsCache.keys().next().value;
|
|
1153
|
-
if (oldest === undefined)
|
|
1154
|
-
break;
|
|
1155
|
-
commentsCache.delete(oldest);
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
/** Test-only: drop the per-thread cache so cases don't leak state into each other. */
|
|
1159
|
-
export function __clearCommentsCacheForTests() {
|
|
1160
|
-
commentsCache.clear();
|
|
1161
|
-
}
|
|
1162
|
-
// Single-item cache (#692): same key shape, TTL and LRU bound as `commentsCache`. Only a real
|
|
1163
|
-
// answer (an item or a confirmed absence) is cached, never an unavailable one.
|
|
1164
|
-
const itemCache = new Map();
|
|
1165
|
-
function itemCacheKey(repoRoot, kind, number) {
|
|
1166
|
-
return `${repoRoot}\0${kind}#${number}`;
|
|
1167
|
-
}
|
|
1168
|
-
export function forgetGithubItem(repoRoot, kind, number) {
|
|
1169
|
-
itemCache.delete(itemCacheKey(repoRoot, kind, number));
|
|
1170
|
-
}
|
|
1171
|
-
/** Test-only: drop the single-item cache. */
|
|
1172
|
-
export function __clearGithubItemCacheForTests() {
|
|
1173
|
-
itemCache.clear();
|
|
1174
|
-
}
|
|
1175
|
-
export async function fetchGithubItem(repoRoot, kind, number, refresh = false) {
|
|
1176
|
-
if (process.env.CEZ_DRY_RUN === '1') {
|
|
1177
|
-
const mock = mockGithub();
|
|
1178
|
-
const item = (kind === 'issue' ? mock.issues : mock.prs).find((i) => i.number === number);
|
|
1179
|
-
return item
|
|
1180
|
-
? { available: true, item, labelColors: mock.labelColors ?? {} }
|
|
1181
|
-
: { available: true, item: null };
|
|
1182
|
-
}
|
|
1183
|
-
const key = itemCacheKey(repoRoot, kind, number);
|
|
1184
|
-
const hit = itemCache.get(key);
|
|
1185
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
1186
|
-
return hit.data;
|
|
1187
|
-
try {
|
|
1188
|
-
const forge = await detectGithub(repoRoot);
|
|
1189
|
-
if (!forge.available)
|
|
1190
|
-
return { available: false, reason: forge.reason ?? 'GitHub is unavailable' };
|
|
1191
|
-
const labelColors = {};
|
|
1192
|
-
const item = await viewGithubItem(repoRoot, kind, number, labelColors);
|
|
1193
|
-
const data = {
|
|
1194
|
-
available: true, item, ...(item ? { labelColors } : {}),
|
|
1195
|
-
};
|
|
1196
|
-
itemCache.delete(key); // re-insert so this key becomes the newest
|
|
1197
|
-
itemCache.set(key, { at: Date.now(), data });
|
|
1198
|
-
while (itemCache.size > COMMENTS_CACHE_MAX) {
|
|
1199
|
-
const oldest = itemCache.keys().next().value;
|
|
1200
|
-
if (oldest === undefined)
|
|
1201
|
-
break;
|
|
1202
|
-
itemCache.delete(oldest);
|
|
1203
|
-
}
|
|
1204
|
-
return data;
|
|
1205
|
-
}
|
|
1206
|
-
catch (err) {
|
|
1207
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1208
|
-
return {
|
|
1209
|
-
available: false,
|
|
1210
|
-
reason: /ENOENT/.test(message)
|
|
1211
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
1212
|
-
: firstLine(message),
|
|
1213
|
-
};
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
const TIMELINE_PER_PAGE = 100;
|
|
1217
|
-
const repoHandleCache = new Map();
|
|
1218
|
-
const repoDiscoveryFlights = new Map();
|
|
1219
|
-
/** Each subscriber owns a lease, not the subprocess. Only the last cancellation aborts it.
|
|
1220
|
-
* Keep the rejecting promise intact so strict callers retain gh's diagnostic. */
|
|
1221
|
-
function sharedRepoHandle(repoRoot, signal, context = githubContext(repoRoot)) {
|
|
1222
|
-
if (signal?.aborted)
|
|
1223
|
-
return Promise.reject(signal.reason);
|
|
1224
|
-
const memo = repoHandleCache.get(context.key);
|
|
1225
|
-
if (memo !== undefined)
|
|
1226
|
-
return Promise.resolve(memo);
|
|
1227
|
-
let flight = repoDiscoveryFlights.get(context.key);
|
|
1228
|
-
if (!flight) {
|
|
1229
|
-
const controller = new AbortController();
|
|
1230
|
-
const created = {
|
|
1231
|
-
controller, owners: 0,
|
|
1232
|
-
promise: gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], 15_000, controller.signal, context)
|
|
1233
|
-
.then(parseOwnerName),
|
|
1234
|
-
};
|
|
1235
|
-
created.promise = created.promise.then(handle => {
|
|
1236
|
-
// A disposed owner may complete late; it must not overwrite a replacement discovery.
|
|
1237
|
-
if (!controller.signal.aborted && repoDiscoveryFlights.get(context.key) === created) {
|
|
1238
|
-
repoHandleCache.set(context.key, handle);
|
|
1239
|
-
}
|
|
1240
|
-
return handle;
|
|
1241
|
-
}).finally(() => {
|
|
1242
|
-
if (repoDiscoveryFlights.get(context.key) === created)
|
|
1243
|
-
repoDiscoveryFlights.delete(context.key);
|
|
1244
|
-
});
|
|
1245
|
-
flight = created;
|
|
1246
|
-
repoDiscoveryFlights.set(context.key, flight);
|
|
1247
|
-
}
|
|
1248
|
-
const owned = flight;
|
|
1249
|
-
owned.owners++;
|
|
1250
|
-
return new Promise((resolve, reject) => {
|
|
1251
|
-
let released = false;
|
|
1252
|
-
const release = () => {
|
|
1253
|
-
if (released)
|
|
1254
|
-
return false;
|
|
1255
|
-
released = true;
|
|
1256
|
-
signal?.removeEventListener('abort', cancel);
|
|
1257
|
-
if (--owned.owners === 0 && repoDiscoveryFlights.get(context.key) === owned) {
|
|
1258
|
-
repoDiscoveryFlights.delete(context.key);
|
|
1259
|
-
owned.controller.abort();
|
|
1260
|
-
}
|
|
1261
|
-
return true;
|
|
1262
|
-
};
|
|
1263
|
-
const cancel = () => { if (release())
|
|
1264
|
-
reject(signal?.reason); };
|
|
1265
|
-
signal?.addEventListener('abort', cancel, { once: true });
|
|
1266
|
-
owned.promise.then(handle => { if (release())
|
|
1267
|
-
resolve(handle); }, error => { if (release())
|
|
1268
|
-
reject(error); });
|
|
1269
|
-
});
|
|
1270
|
-
}
|
|
1271
|
-
/** Test-only: drop the memoized repo handles. */
|
|
1272
|
-
export function __clearRepoHandleCacheForTests() {
|
|
1273
|
-
repoHandleCache.clear();
|
|
1274
|
-
for (const flight of repoDiscoveryFlights.values())
|
|
1275
|
-
flight.controller.abort();
|
|
1276
|
-
repoDiscoveryFlights.clear();
|
|
1277
|
-
}
|
|
1278
|
-
/** Local absence cannot improve through network retries. Authentication, timeouts and remote
|
|
1279
|
-
* errors deliberately stay retryable, including 404s for temporarily inaccessible repositories. */
|
|
1280
|
-
function isPermanentRepoFailure(error) {
|
|
1281
|
-
if (!(error instanceof Error))
|
|
1282
|
-
return false;
|
|
1283
|
-
if ('code' in error && error.code === 'ENOENT')
|
|
1284
|
-
return true;
|
|
1285
|
-
const stderr = 'stderr' in error && typeof error.stderr === 'string' ? error.stderr : '';
|
|
1286
|
-
return /not a git repository|no git remotes found|none of the git remotes configured for this repository point to a known GitHub host/i.test(`${error.message}\n${stderr}`);
|
|
1287
|
-
}
|
|
1288
|
-
/** Share the existing memo with ordinary discovery, but retain failure classification (#102).
|
|
1289
|
-
* An aborted owner must never publish its late result into this shared cache. */
|
|
1290
|
-
export async function discoverRepoHandle(repoRoot, signal) {
|
|
1291
|
-
const context = githubContext(repoRoot);
|
|
1292
|
-
if (signal?.aborted)
|
|
1293
|
-
return { status: 'cancelled' };
|
|
1294
|
-
try {
|
|
1295
|
-
const handle = await sharedRepoHandle(repoRoot, signal, context);
|
|
1296
|
-
if (signal?.aborted)
|
|
1297
|
-
return { status: 'cancelled' };
|
|
1298
|
-
return handle ? { status: 'resolved', handle } : { status: 'unknown' };
|
|
1299
|
-
}
|
|
1300
|
-
catch (error) {
|
|
1301
|
-
if (signal?.aborted)
|
|
1302
|
-
return { status: 'cancelled' };
|
|
1303
|
-
if (isPermanentRepoFailure(error)) {
|
|
1304
|
-
// Do not replace a successful discovery another caller completed while this one failed.
|
|
1305
|
-
const recovered = repoHandleCache.get(context.key);
|
|
1306
|
-
if (recovered)
|
|
1307
|
-
return { status: 'resolved', handle: recovered };
|
|
1308
|
-
// The live arming loop stops on unknown. Do not memoize local failures here: later cold
|
|
1309
|
-
// index/status requests must still discover an installed gh or a newly added remote.
|
|
1310
|
-
return { status: 'unknown' };
|
|
1311
|
-
}
|
|
1312
|
-
return { status: 'retryable' };
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
/** Compatible fail-open lookup for existing API and cold-index callers. */
|
|
1316
|
-
export async function resolveRepoHandle(repoRoot, signal) {
|
|
1317
|
-
const result = await discoverRepoHandle(repoRoot, signal);
|
|
1318
|
-
return result.status === 'resolved' ? result.handle : null;
|
|
1319
|
-
}
|
|
1320
|
-
/**
|
|
1321
|
-
* Walk `/issues/{n}/timeline` under ONE shared time budget.
|
|
1322
|
-
*
|
|
1323
|
-
* `gh api --paginate` is not used here: it pages *"until there are no more pages of results"* and
|
|
1324
|
-
* exposes no page-limit flag, so the only way to bound the walk is to hand-roll it. The cap that
|
|
1325
|
-
* `paginateCounts` gets comes from being a JS cursor loop, not from a `gh` flag.
|
|
1326
|
-
*
|
|
1327
|
-
* The budget is a **total**, not a per-page allowance. `gh()` takes its timeout per invocation, so
|
|
1328
|
-
* ten sequential spawns at the 15 s default would put the ceiling at 150 s — an order of magnitude
|
|
1329
|
-
* worse than the single `--paginate` spawn this replaces. The loop tracks a deadline and passes
|
|
1330
|
-
* each page whatever remains.
|
|
1331
|
-
*
|
|
1332
|
-
* Exported for unit tests; `run` is injected so the loop is testable without shelling out.
|
|
1333
|
-
*/
|
|
1334
|
-
export async function fetchTimelinePages(run, opts = {}) {
|
|
1335
|
-
const maxPages = opts.maxPages ?? TIMELINE_MAX_PAGES;
|
|
1336
|
-
const budgetMs = opts.budgetMs ?? TIMELINE_BUDGET_MS;
|
|
1337
|
-
const minPageMs = opts.minPageMs ?? TIMELINE_MIN_PAGE_MS;
|
|
1338
|
-
const now = opts.now ?? Date.now;
|
|
1339
|
-
const deadline = now() + budgetMs;
|
|
1340
|
-
const rows = [];
|
|
1341
|
-
let stoppedShort = false;
|
|
1342
|
-
let page = 1;
|
|
1343
|
-
for (; page <= maxPages; page++) {
|
|
1344
|
-
const remaining = deadline - now();
|
|
1345
|
-
// Never spawn a page that cannot finish. A bare `remaining <= 0` guard catches only the exact
|
|
1346
|
-
// boundary; the realistic case is 300 ms left, which spawns gh with a 300 ms timeout, throws,
|
|
1347
|
-
// and looks indistinguishable from a real endpoint failure.
|
|
1348
|
-
if (remaining < minPageMs) {
|
|
1349
|
-
stoppedShort = true;
|
|
1350
|
-
break;
|
|
1351
|
-
}
|
|
1352
|
-
let parsed;
|
|
1353
|
-
try {
|
|
1354
|
-
parsed = z.array(z.unknown()).parse(JSON.parse(await run(page, remaining)));
|
|
1355
|
-
}
|
|
1356
|
-
catch (err) {
|
|
1357
|
-
// Page 1 rethrows so the caller's inner catch can decide whether substitution helps —
|
|
1358
|
-
// nothing was fetched, so there is nothing to lose. A failure on any later page keeps the
|
|
1359
|
-
// pages already in hand: discarding nine good pages to re-fetch comments-only is strictly
|
|
1360
|
-
// worse than what the loop already holds.
|
|
1361
|
-
if (page === 1)
|
|
1362
|
-
throw err;
|
|
1363
|
-
stoppedShort = true;
|
|
1364
|
-
break;
|
|
1365
|
-
}
|
|
1366
|
-
rows.push(...parsed);
|
|
1367
|
-
if (parsed.length < TIMELINE_PER_PAGE)
|
|
1368
|
-
break; // short page — the real end of the timeline
|
|
1369
|
-
}
|
|
1370
|
-
if (page > maxPages)
|
|
1371
|
-
stoppedShort = true; // fell out on the page cap
|
|
1372
|
-
return { rows, stoppedShort };
|
|
1373
|
-
}
|
|
1374
|
-
/** SHAs per rollup query. Aliases resolve independently, so a chunk that fails costs only its own
|
|
1375
|
-
* glyphs — but an unbounded alias list would eventually blow the query size limit. */
|
|
1376
|
-
export const COMMIT_CHECKS_CHUNK = 50;
|
|
1377
|
-
/** One aliased `object(oid:)` per SHA. `oid` requires a FULL 40-char SHA in both literal and
|
|
1378
|
-
* variable form (`Could not coerce value "babda63" to GitObjectID`), which constrains fixtures
|
|
1379
|
-
* rather than production data — the timeline always supplies full SHAs. */
|
|
1380
|
-
function commitChecksQuery(shas) {
|
|
1381
|
-
const aliases = shas
|
|
1382
|
-
.map((sha, i) => ` c${i}: object(oid: "${sha}") { ... on Commit { statusCheckRollup { state } } }`)
|
|
1383
|
-
.join('\n');
|
|
1384
|
-
return `query ($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n${aliases}\n }\n}`;
|
|
1385
|
-
}
|
|
1386
|
-
const ghCommitChecksSchema = z.record(z.string(), z.object({ statusCheckRollup: z.object({ state: z.string().nullish() }).nullish() }).nullish());
|
|
1387
|
-
/**
|
|
1388
|
-
* Rolled-up CI state per commit SHA, as a `sha → checks` map.
|
|
1389
|
-
*
|
|
1390
|
-
* Batched and aliased so a 40-commit PR costs one subprocess, not forty. Verified against the live
|
|
1391
|
-
* API: each alias resolves independently and an unknown SHA comes back `null` rather than erroring
|
|
1392
|
-
* the batch, so partial results degrade cleanly.
|
|
1393
|
-
*
|
|
1394
|
-
* Degrades to an empty map on any failure — exactly as `fetchCommentCounts` does for counts. The
|
|
1395
|
-
* caller then leaves `checks` **absent**, which the UI renders as no glyph. Exported for tests;
|
|
1396
|
-
* `runGraphql` is injected so this is testable without shelling out.
|
|
1397
|
-
*/
|
|
1398
|
-
export async function fetchCommitChecks(runGraphql, owner, name, shas, chunkSize = COMMIT_CHECKS_CHUNK) {
|
|
1399
|
-
const out = {};
|
|
1400
|
-
if (shas.length === 0)
|
|
1401
|
-
return out;
|
|
1402
|
-
for (let i = 0; i < shas.length; i += chunkSize) {
|
|
1403
|
-
const chunk = shas.slice(i, i + chunkSize);
|
|
1404
|
-
try {
|
|
1405
|
-
const raw = JSON.parse(await runGraphql(commitChecksQuery(chunk), { owner, name }));
|
|
1406
|
-
const repository = ghCommitChecksSchema.parse(raw?.data?.repository ?? {});
|
|
1407
|
-
chunk.forEach((sha, index) => {
|
|
1408
|
-
const node = repository[`c${index}`];
|
|
1409
|
-
if (!node)
|
|
1410
|
-
return; // unknown SHA → alias resolved null; leave `checks` absent
|
|
1411
|
-
// Adapt the single rollup state into the array shape `rollupToChecks` expects, so the
|
|
1412
|
-
// existing FAILURE/PENDING/SUCCESS vocabulary is reused rather than duplicated.
|
|
1413
|
-
out[sha] = node.statusCheckRollup
|
|
1414
|
-
? rollupToChecks([{ state: node.statusCheckRollup.state, status: null, conclusion: null }])
|
|
1415
|
-
: null; // no CI configured — distinct from absent
|
|
1416
|
-
});
|
|
1417
|
-
}
|
|
1418
|
-
catch {
|
|
1419
|
-
// A failed chunk costs only its own glyphs; the rest still resolve.
|
|
1420
|
-
}
|
|
1421
|
-
}
|
|
1422
|
-
return out;
|
|
1423
|
-
}
|
|
1424
|
-
/** PR numbers per checks query. Aliases resolve independently (a failed chunk costs only its own
|
|
1425
|
-
* glyphs); bounded so an unbounded number list can't blow the query size limit. Also the route's
|
|
1426
|
-
* hard cap on how many PRs one request may ask about. */
|
|
1427
|
-
export const GH_CHECKS_MAX = 100;
|
|
1428
|
-
/** One aliased `pullRequest(number:)` per PR; the rolled-up CI state lives on the head commit. */
|
|
1429
|
-
function prChecksQuery(numbers) {
|
|
1430
|
-
const aliases = numbers
|
|
1431
|
-
.map((n, i) => ` p${i}: pullRequest(number: ${n}) { commits(last: 1) { nodes { commit { statusCheckRollup { state } } } } }`)
|
|
1432
|
-
.join('\n');
|
|
1433
|
-
return `query ($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\n${aliases}\n }\n}`;
|
|
1434
|
-
}
|
|
1435
|
-
const ghPrChecksSchema = z.record(z.string(), z
|
|
1436
|
-
.object({
|
|
1437
|
-
commits: z.object({
|
|
1438
|
-
nodes: z.array(z.object({
|
|
1439
|
-
commit: z.object({
|
|
1440
|
-
statusCheckRollup: z.object({ state: z.string().nullish() }).nullish(),
|
|
1441
|
-
}),
|
|
1442
|
-
})),
|
|
1443
|
-
}),
|
|
1444
|
-
})
|
|
1445
|
-
.nullish());
|
|
1446
|
-
/**
|
|
1447
|
-
* Rolled-up CI state per PR number, as a `number → glyph` map.
|
|
1448
|
-
*
|
|
1449
|
-
* Batched and aliased so a 100-PR window costs one subprocess, not a hundred. Each alias resolves
|
|
1450
|
-
* independently and an unknown number comes back `null` (alias resolved null → left absent), so
|
|
1451
|
-
* partial results degrade cleanly. Degrades to an empty map on any failure — exactly as
|
|
1452
|
-
* `fetchCommitChecks` does. Exported for tests; `runGraphql` is injected so this is testable
|
|
1453
|
-
* without shelling out.
|
|
1454
|
-
*/
|
|
1455
|
-
export async function fetchPrChecks(runGraphql, owner, name, numbers, chunkSize = GH_CHECKS_MAX) {
|
|
1456
|
-
const out = {};
|
|
1457
|
-
if (numbers.length === 0)
|
|
1458
|
-
return out;
|
|
1459
|
-
for (let i = 0; i < numbers.length; i += chunkSize) {
|
|
1460
|
-
const chunk = numbers.slice(i, i + chunkSize);
|
|
1461
|
-
try {
|
|
1462
|
-
const raw = JSON.parse(await runGraphql(prChecksQuery(chunk), { owner, name }));
|
|
1463
|
-
const repository = ghPrChecksSchema.parse(raw?.data?.repository ?? {});
|
|
1464
|
-
chunk.forEach((number, index) => {
|
|
1465
|
-
const node = repository[`p${index}`];
|
|
1466
|
-
if (!node)
|
|
1467
|
-
return; // unknown PR → alias resolved null; leave the glyph absent
|
|
1468
|
-
const rollup = node.commits.nodes[0]?.commit.statusCheckRollup;
|
|
1469
|
-
// Adapt the single rollup state into the array shape `rollupToChecks` expects, reusing the
|
|
1470
|
-
// FAILURE/PENDING/SUCCESS vocabulary rather than duplicating it.
|
|
1471
|
-
out[number] = rollup
|
|
1472
|
-
? rollupToChecks([{ state: rollup.state, status: null, conclusion: null }]) ?? null
|
|
1473
|
-
: null; // no CI configured — distinct from absent
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
1476
|
-
catch {
|
|
1477
|
-
// A failed chunk costs only its own glyphs; the rest still resolve.
|
|
1478
|
-
}
|
|
1479
|
-
}
|
|
1480
|
-
return out;
|
|
1481
|
-
}
|
|
1482
|
-
const itemDetailSchema = z.object({
|
|
1483
|
-
body: z.string().nullish(),
|
|
1484
|
-
additions: z.number().int().nonnegative().optional(),
|
|
1485
|
-
deletions: z.number().int().nonnegative().optional(),
|
|
1486
|
-
});
|
|
1487
|
-
/** One item's body (and a PR's diffstat), or `undefined` on any failure. */
|
|
1488
|
-
async function fetchItemDetail(repoRoot, kind, number) {
|
|
1489
|
-
try {
|
|
1490
|
-
const out = await gh(repoRoot, [kind, 'view', String(number), '--json', kind === 'pr' ? 'body,additions,deletions' : 'body']);
|
|
1491
|
-
const parsed = itemDetailSchema.parse(JSON.parse(out));
|
|
1492
|
-
return {
|
|
1493
|
-
body: (parsed.body ?? '').slice(0, COMMENT_BODY_CAP),
|
|
1494
|
-
...(kind === 'pr' && parsed.additions !== undefined ? { additions: parsed.additions } : {}),
|
|
1495
|
-
...(kind === 'pr' && parsed.deletions !== undefined ? { deletions: parsed.deletions } : {}),
|
|
1496
|
-
};
|
|
1497
|
-
}
|
|
1498
|
-
catch {
|
|
1499
|
-
return undefined;
|
|
1500
|
-
}
|
|
1501
|
-
}
|
|
1502
|
-
// Per-item comment counts (hearsay-tools/cezarion#1183): the list defers them, and the cockpit
|
|
1503
|
-
// asks for its loaded rows after paint. Keyed `context␀kind␀number`, same TTL and bound as checks.
|
|
1504
|
-
const commentCountsCache = new Map();
|
|
1505
|
-
const commentCountsSchema = z.object({
|
|
1506
|
-
data: z.object({
|
|
1507
|
-
repository: z.record(z.string(), z.object({ comments: z.object({ totalCount: z.number().int().nonnegative() }) }).nullable()),
|
|
1508
|
-
}),
|
|
1509
|
-
});
|
|
1510
|
-
/**
|
|
1511
|
-
* Comment counts for the given issue or PR numbers, in one aliased GraphQL query. A number GitHub
|
|
1512
|
-
* does not know is absent (unknown), never 0. Degrades to `{ available: false, reason }` — never a
|
|
1513
|
-
* throw. Numbers are de-duplicated, validated and capped at `GITHUB_COMMENT_COUNTS_MAX`.
|
|
1514
|
-
*/
|
|
1515
|
-
export async function fetchGithubCommentCounts(repoRoot, kind, numbers, refresh = false) {
|
|
1516
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
1517
|
-
return mockGithubCommentCounts(kind, numbers);
|
|
1518
|
-
const context = githubContext(repoRoot);
|
|
1519
|
-
const wanted = [...new Set(numbers)].filter((n) => Number.isSafeInteger(n) && n > 0).slice(0, GITHUB_COMMENT_COUNTS_MAX);
|
|
1520
|
-
const counts = {};
|
|
1521
|
-
const misses = [];
|
|
1522
|
-
const now = Date.now();
|
|
1523
|
-
const keyOf = (n) => `${context.key}\0${kind}\0${n}`;
|
|
1524
|
-
for (const n of wanted) {
|
|
1525
|
-
const hit = commentCountsCache.get(keyOf(n));
|
|
1526
|
-
if (!refresh && hit && now - hit.at < CACHE_MS)
|
|
1527
|
-
counts[n] = hit.count;
|
|
1528
|
-
else
|
|
1529
|
-
misses.push(n);
|
|
1530
|
-
}
|
|
1531
|
-
if (misses.length === 0)
|
|
1532
|
-
return { available: true, counts };
|
|
1533
|
-
try {
|
|
1534
|
-
const handle = await resolveRepoHandleStrict(repoRoot, context);
|
|
1535
|
-
if (!handle)
|
|
1536
|
-
return { available: false, reason: 'Could not resolve this repository on GitHub.' };
|
|
1537
|
-
// Integers only in the aliases; owner and name travel as variables.
|
|
1538
|
-
const fields = misses.map((n) => `n${n}: issueOrPullRequest(number: ${n}) {
|
|
1539
|
-
... on Issue { comments { totalCount } }
|
|
1540
|
-
... on PullRequest { comments { totalCount } }
|
|
1541
|
-
}`).join('\n');
|
|
1542
|
-
// A number GitHub does not know comes back NOT_FOUND and makes `gh` exit 1 with the rest of
|
|
1543
|
-
// the batch on stdout; `refStatusGraphql` keeps that partial answer.
|
|
1544
|
-
const raw = await refStatusGraphql(repoRoot, context)(`query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`, { owner: handle.owner, name: handle.name });
|
|
1545
|
-
const rows = commentCountsSchema.parse(JSON.parse(raw)).data.repository;
|
|
1546
|
-
for (const n of misses) {
|
|
1547
|
-
const count = rows[`n${n}`]?.comments.totalCount;
|
|
1548
|
-
if (count === undefined)
|
|
1549
|
-
continue; // unknown number: absent, and asked again next time
|
|
1550
|
-
counts[n] = count;
|
|
1551
|
-
commentCountsCache.delete(keyOf(n));
|
|
1552
|
-
commentCountsCache.set(keyOf(n), { at: now, count });
|
|
1553
|
-
}
|
|
1554
|
-
while (commentCountsCache.size > CHECKS_CACHE_MAX) {
|
|
1555
|
-
const oldest = commentCountsCache.keys().next().value;
|
|
1556
|
-
if (oldest === undefined)
|
|
1557
|
-
break;
|
|
1558
|
-
commentCountsCache.delete(oldest);
|
|
1559
|
-
}
|
|
1560
|
-
return { available: true, counts };
|
|
1561
|
-
}
|
|
1562
|
-
catch (err) {
|
|
1563
|
-
return { available: false, reason: ghFailureReason(err) };
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
/** CEZ_DRY_RUN=1 — the catalog's own counts, so the offline list shows its badges. */
|
|
1567
|
-
function mockGithubCommentCounts(kind, numbers) {
|
|
1568
|
-
const rows = kind === 'pr' ? mockGithub().prs : mockGithub().issues;
|
|
1569
|
-
const counts = {};
|
|
1570
|
-
for (const n of numbers) {
|
|
1571
|
-
const row = rows.find((item) => item.number === n);
|
|
1572
|
-
if (row)
|
|
1573
|
-
counts[n] = row.comments;
|
|
1574
|
-
}
|
|
1575
|
-
return { available: true, counts };
|
|
1576
|
-
}
|
|
1577
|
-
// Per-PR checks cache: keyed `repoRoot␀number`, same 60 s TTL as the list cache but BOUNDED. Lets
|
|
1578
|
-
// a repeated visible-window hydration within a minute serve cached glyphs instead of re-querying.
|
|
1579
|
-
const checksCache = new Map();
|
|
1580
|
-
const CHECKS_CACHE_MAX = 500;
|
|
1581
|
-
/** Test hook — the per-PR checks cache would otherwise leak state across cases in one process. */
|
|
1582
|
-
export function __clearChecksCacheForTests() {
|
|
1583
|
-
checksCache.clear();
|
|
1584
|
-
}
|
|
1585
|
-
/**
|
|
1586
|
-
* Lazy checks glyphs for the given PR numbers (route-facing). Resolves the repo handle once,
|
|
1587
|
-
* serves fresh cache entries, queries only the misses, and degrades to `{ available: false,
|
|
1588
|
-
* reason }` when `gh` or the handle is unavailable — never a throw, never a 5xx (plan rule 7).
|
|
1589
|
-
* Numbers are de-duplicated, validated, and capped at `GH_CHECKS_MAX`.
|
|
1590
|
-
*/
|
|
1591
|
-
export async function fetchGithubChecks(repoRoot, numbers) {
|
|
1592
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
1593
|
-
return mockGithubChecks(numbers);
|
|
1594
|
-
const wanted = [...new Set(numbers)].filter((n) => Number.isInteger(n) && n > 0).slice(0, GH_CHECKS_MAX);
|
|
1595
|
-
const checks = {};
|
|
1596
|
-
const misses = [];
|
|
1597
|
-
const now = Date.now();
|
|
1598
|
-
for (const n of wanted) {
|
|
1599
|
-
const hit = checksCache.get(`${repoRoot}\0${n}`);
|
|
1600
|
-
if (hit && now - hit.at < CACHE_MS)
|
|
1601
|
-
checks[n] = hit.glyph;
|
|
1602
|
-
else
|
|
1603
|
-
misses.push(n);
|
|
1604
|
-
}
|
|
1605
|
-
if (misses.length === 0)
|
|
1606
|
-
return { available: true, checks };
|
|
1607
|
-
try {
|
|
1608
|
-
const repoOut = await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']);
|
|
1609
|
-
const ownerName = parseOwnerName(repoOut);
|
|
1610
|
-
if (!ownerName)
|
|
1611
|
-
return { available: false, reason: 'repository handle unavailable' };
|
|
1612
|
-
const runGraphql = (query, variables) => {
|
|
1613
|
-
const args = ghGraphqlArgs(query, variables);
|
|
1614
|
-
return gh(repoRoot, args);
|
|
1615
|
-
};
|
|
1616
|
-
const fetched = await fetchPrChecks(runGraphql, ownerName.owner, ownerName.name, misses);
|
|
1617
|
-
for (const n of misses) {
|
|
1618
|
-
// Absent (unknown/closed PR) caches as `null` so a nonexistent number isn't re-queried.
|
|
1619
|
-
const glyph = n in fetched ? fetched[n] : null;
|
|
1620
|
-
checks[n] = glyph;
|
|
1621
|
-
checksCache.set(`${repoRoot}\0${n}`, { at: now, glyph });
|
|
1622
|
-
}
|
|
1623
|
-
while (checksCache.size > CHECKS_CACHE_MAX) {
|
|
1624
|
-
const oldest = checksCache.keys().next().value;
|
|
1625
|
-
if (oldest === undefined)
|
|
1626
|
-
break;
|
|
1627
|
-
checksCache.delete(oldest);
|
|
1628
|
-
}
|
|
1629
|
-
return { available: true, checks };
|
|
1630
|
-
}
|
|
1631
|
-
catch (err) {
|
|
1632
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1633
|
-
return {
|
|
1634
|
-
available: false,
|
|
1635
|
-
reason: /ENOENT/.test(message)
|
|
1636
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
1637
|
-
: firstLine(message),
|
|
1638
|
-
};
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
/** CEZ_DRY_RUN=1 — glyphs straight from the mock catalog so the offline demo shows checks. */
|
|
1642
|
-
function mockGithubChecks(numbers) {
|
|
1643
|
-
const byNumber = new Map(mockGithub().prs.map((p) => [p.number, (p.checks ?? null)]));
|
|
1644
|
-
const checks = {};
|
|
1645
|
-
for (const n of numbers)
|
|
1646
|
-
checks[n] = byNumber.get(n) ?? null;
|
|
1647
|
-
return { available: true, checks };
|
|
1648
|
-
}
|
|
1649
|
-
/** Numbers per kind in one ref-status query — the same bound, and for the same reasons, as
|
|
1650
|
-
* `GH_CHECKS_MAX`: aliases resolve independently, and the query size stays finite. Taken from the
|
|
1651
|
-
* contract rather than restated, because the cockpit caps its batches by the same number and a
|
|
1652
|
-
* client that guessed high would have every chip in a batch 400 instead of losing its tail. */
|
|
1653
|
-
export const GH_REF_STATUS_MAX = REFERENCE_STATUS_MAX;
|
|
1654
|
-
/** A requested reviewer, as either connection spells them. `login` covers `User` and `Bot`, `slug`
|
|
1655
|
-
* covers `Team`; `reviewerKey` folds them into one comparable string. */
|
|
1656
|
-
const reviewerRefSchema = z
|
|
1657
|
-
.object({
|
|
1658
|
-
__typename: z.string().nullish(),
|
|
1659
|
-
login: z.string().nullish(),
|
|
1660
|
-
slug: z.string().nullish(),
|
|
1661
|
-
})
|
|
1662
|
-
.nullish();
|
|
1663
|
-
/** One reviewer as a comparable key, or `null` when GitHub named nobody we can match on — which
|
|
1664
|
-
* must never compare equal to another unnamed reviewer, hence `null` rather than a shared "". */
|
|
1665
|
-
function reviewerKey(ref) {
|
|
1666
|
-
const name = ref?.login ?? ref?.slug;
|
|
1667
|
-
return name ? `${ref?.__typename ?? '?'}:${name}` : null;
|
|
1668
|
-
}
|
|
1669
|
-
const ghRefStatusPrSchema = z
|
|
1670
|
-
.object({
|
|
1671
|
-
state: z.string(),
|
|
1672
|
-
url: z.unknown().optional(),
|
|
1673
|
-
mergedAt: z.unknown().optional(),
|
|
1674
|
-
isDraft: z.boolean().nullish(),
|
|
1675
|
-
reviewDecision: z.string().nullish(),
|
|
1676
|
-
/** `MERGEABLE` | `CONFLICTING` | `UNKNOWN` — GitHub computes it in the background, so
|
|
1677
|
-
* `UNKNOWN` is normal on a PR that was just pushed and must never read as "clean". */
|
|
1678
|
-
mergeable: z.string().nullish(),
|
|
1679
|
-
commits: z
|
|
1680
|
-
.object({
|
|
1681
|
-
nodes: z.array(z.object({
|
|
1682
|
-
commit: z.object({
|
|
1683
|
-
committedDate: z.string().nullish(),
|
|
1684
|
-
/** `totalCount` says whether the head is a merge; the first parent is the branch's
|
|
1685
|
-
* previous tip, which is the newest commit that is actual WORK when it is. */
|
|
1686
|
-
parents: z
|
|
1687
|
-
.object({
|
|
1688
|
-
totalCount: z.number(),
|
|
1689
|
-
nodes: z.array(z.object({ committedDate: z.string().nullish() }).nullish()).nullish(),
|
|
1690
|
-
})
|
|
1691
|
-
.nullish(),
|
|
1692
|
-
statusCheckRollup: z.object({ state: z.string().nullish() }).nullish(),
|
|
1693
|
-
}),
|
|
1694
|
-
})),
|
|
1695
|
-
})
|
|
1696
|
-
.nullish(),
|
|
1697
|
-
reviews: z.object({ nodes: z.array(z.object({ submittedAt: z.string().nullish() })) }).nullish(),
|
|
1698
|
-
/** Who is on the hook RIGHT NOW. The reviewers are carried, not just the count, because a
|
|
1699
|
-
* request's date has to be matched to a request that still stands — see `reviewRequestedAt`. */
|
|
1700
|
-
reviewRequests: z
|
|
1701
|
-
.object({
|
|
1702
|
-
totalCount: z.number(),
|
|
1703
|
-
nodes: z.array(z.object({ requestedReviewer: reviewerRefSchema }).nullish()).nullish(),
|
|
1704
|
-
})
|
|
1705
|
-
.nullish(),
|
|
1706
|
-
timelineItems: z
|
|
1707
|
-
.object({
|
|
1708
|
-
nodes: z
|
|
1709
|
-
.array(z.object({ createdAt: z.string().nullish(), requestedReviewer: reviewerRefSchema }).nullish())
|
|
1710
|
-
.nullish(),
|
|
1711
|
-
})
|
|
1712
|
-
.nullish(),
|
|
1713
|
-
})
|
|
1714
|
-
.nullish();
|
|
1715
|
-
/**
|
|
1716
|
-
* When was the newest STILL-STANDING review request made?
|
|
1717
|
-
*
|
|
1718
|
-
* The two connections answer different halves and neither answers both: `reviewRequests` says who
|
|
1719
|
-
* is on the hook right now but carries no date, while a `ReviewRequestedEvent` carries the date and
|
|
1720
|
-
* survives the request being withdrawn. Reading the newest event on its own therefore dates a
|
|
1721
|
-
* request that may no longer exist — and a request added after a review and then removed would make
|
|
1722
|
-
* a live rejection read as answered, which is the exact bug the precedence above exists to fix.
|
|
1723
|
-
* Matching the two by reviewer is what keeps the date attached to a request that is really there.
|
|
1724
|
-
*
|
|
1725
|
-
* `null` when nothing matches, which the precedence reads as an undated request and treats
|
|
1726
|
-
* conservatively: the review stands rather than being dismissed on a guess.
|
|
1727
|
-
*/
|
|
1728
|
-
function standingReviewRequestedAt(requests, timeline) {
|
|
1729
|
-
const standing = new Set();
|
|
1730
|
-
for (const node of requests?.nodes ?? []) {
|
|
1731
|
-
const key = reviewerKey(node?.requestedReviewer);
|
|
1732
|
-
if (key)
|
|
1733
|
-
standing.add(key);
|
|
1734
|
-
}
|
|
1735
|
-
if (standing.size === 0)
|
|
1736
|
-
return null;
|
|
1737
|
-
let newest = null;
|
|
1738
|
-
for (const node of timeline?.nodes ?? []) {
|
|
1739
|
-
if (!node?.createdAt)
|
|
1740
|
-
continue;
|
|
1741
|
-
const key = reviewerKey(node.requestedReviewer);
|
|
1742
|
-
if (!key || !standing.has(key))
|
|
1743
|
-
continue;
|
|
1744
|
-
if (!newest || isAfter(node.createdAt, newest))
|
|
1745
|
-
newest = node.createdAt;
|
|
1746
|
-
}
|
|
1747
|
-
return newest;
|
|
1748
|
-
}
|
|
1749
|
-
const ghRefStatusIssueSchema = z.object({ state: z.string(), stateReason: z.string().nullish() }).nullish();
|
|
1750
|
-
// The aliases hold two DIFFERENT shapes, so the record stays unvalidated here and each alias is
|
|
1751
|
-
// parsed by its own schema below. A union at this level would be wrong, not merely loose: zod
|
|
1752
|
-
// strips unknown keys, so a PR node matched by the issue arm would come back with `isDraft` and
|
|
1753
|
-
// `commits` silently removed.
|
|
1754
|
-
const ghRefStatusSchema = z.record(z.string(), z.unknown());
|
|
1755
|
-
/**
|
|
1756
|
-
* Query issueOrPullRequest once per number and use __typename for the actual kind. Include
|
|
1757
|
-
* branch-work and review timestamps for freshness decisions.
|
|
1758
|
-
*/
|
|
1759
|
-
function refStatusQuery(numbers) {
|
|
1760
|
-
const aliases = numbers
|
|
1761
|
-
.map((n, i) => ` r${i}: issueOrPullRequest(number: ${n}) { __typename ... on PullRequest { url mergedAt state isDraft reviewDecision mergeable commits(last: 1) { nodes { commit { committedDate parents(first: 1) { totalCount nodes { committedDate } } statusCheckRollup { state } } } } reviews(last: 1, states: CHANGES_REQUESTED) { nodes { submittedAt } } reviewRequests(first: 20) { totalCount nodes { requestedReviewer { __typename ... on User { login } ... on Bot { login } ... on Team { slug } } } } timelineItems(last: 20, itemTypes: [REVIEW_REQUESTED_EVENT]) { nodes { ... on ReviewRequestedEvent { createdAt requestedReviewer { __typename ... on User { login } ... on Bot { login } ... on Team { slug } } } } } } ... on Issue { state stateReason } }`)
|
|
1762
|
-
.join('\n');
|
|
1763
|
-
return `query ($owner: String!, $name: String!) {\n repository(owner: $owner, name: $name) {\nnameWithOwner\n${aliases}\n }\n}`;
|
|
1764
|
-
}
|
|
1765
|
-
/**
|
|
1766
|
-
* Derive whose action is pending: terminal, draft, pending checks, current requested changes,
|
|
1767
|
-
* failing checks, review, then ready. Use dated review/work evidence; mergeability remains a
|
|
1768
|
-
* separate axis.
|
|
1769
|
-
*/
|
|
1770
|
-
export function derivePrReferenceStatus(pr) {
|
|
1771
|
-
const state = pr.state.toUpperCase();
|
|
1772
|
-
if (state === 'MERGED')
|
|
1773
|
-
return 'merged';
|
|
1774
|
-
if (state === 'CLOSED')
|
|
1775
|
-
return 'closed';
|
|
1776
|
-
if (pr.isDraft)
|
|
1777
|
-
return 'draft';
|
|
1778
|
-
if (pr.checks === 'pending')
|
|
1779
|
-
return 'checks-pending';
|
|
1780
|
-
const decision = (pr.reviewDecision ?? '').toUpperCase();
|
|
1781
|
-
const changesRequested = decision === 'CHANGES_REQUESTED';
|
|
1782
|
-
// Has the author already answered the review — by asking for another look, or by pushing?
|
|
1783
|
-
// A standing request counts as the ask only if it POSTDATES the review; one made before it is a
|
|
1784
|
-
// reviewer who has not got to the PR yet, and on a PR where someone else rejected it that
|
|
1785
|
-
// request would otherwise mask the rejection indefinitely. With no review date at all it still
|
|
1786
|
-
// counts — that is the empty-`reviews` case above, where it is the only signal there is.
|
|
1787
|
-
const reRequested = pr.reviewRequested === true && (!pr.changesRequestedAt || isAfter(pr.reviewRequestedAt, pr.changesRequestedAt));
|
|
1788
|
-
// A push counts as the answer, judged by the newest commit that is actual WORK. GitHub's "Update
|
|
1789
|
-
// branch" button (and this cockpit's own "Resolve conflicts") writes `Merge branch 'main' into
|
|
1790
|
-
// <branch>` dated NOW, newer than any review while addressing none of it: the click people make
|
|
1791
|
-
// reflexively on a stale PR must not wipe a rejection off the chip. Two parents is what tells
|
|
1792
|
-
// that commit apart from work.
|
|
1793
|
-
//
|
|
1794
|
-
// Which is why a merge is not simply DISQUALIFYING: it is transparent. Reading only the head
|
|
1795
|
-
// would let a merge landing on top of a genuine fix erase that fix's answer and flip the chip
|
|
1796
|
-
// back to red, blaming an author who already responded — the same misattribution this whole
|
|
1797
|
-
// function exists to prevent, just pointed the other way. The merge's FIRST parent is the
|
|
1798
|
-
// branch's previous tip, so it carries the date of the work the merge sat on top of.
|
|
1799
|
-
const workCommittedAt = (pr.headParentCount ?? 1) < 2 ? pr.headCommittedAt : pr.headFirstParentCommittedAt;
|
|
1800
|
-
const pushed = isAfter(workCommittedAt, pr.changesRequestedAt);
|
|
1801
|
-
const answered = reRequested || pushed;
|
|
1802
|
-
if (changesRequested && !answered)
|
|
1803
|
-
return 'changes-requested';
|
|
1804
|
-
if (pr.checks === 'failing')
|
|
1805
|
-
return 'checks-failing';
|
|
1806
|
-
// `APPROVED` is the forge saying the review requirement IS MET, and it outranks a pending
|
|
1807
|
-
// request: a reviewer left on the list after someone else approved is a courtesy ask, not an
|
|
1808
|
-
// unmet gate. (A repo needing two approvals reports `REVIEW_REQUIRED` until it has both, so
|
|
1809
|
-
// `APPROVED` never arrives early.) Without this, an approved, green, mergeable pull request
|
|
1810
|
-
// reads "waiting for review" for as long as anyone stays listed — which is indefinitely.
|
|
1811
|
-
if (decision === 'APPROVED')
|
|
1812
|
-
return 'ready';
|
|
1813
|
-
if (changesRequested || decision === 'REVIEW_REQUIRED' || pr.reviewRequested === true) {
|
|
1814
|
-
return 'review-required';
|
|
1815
|
-
}
|
|
1816
|
-
return 'ready';
|
|
1817
|
-
}
|
|
1818
|
-
export function mergeabilityOf(state, mergeable) {
|
|
1819
|
-
if (state.toUpperCase() !== 'OPEN')
|
|
1820
|
-
return undefined;
|
|
1821
|
-
switch (mergeable?.toUpperCase()) {
|
|
1822
|
-
case 'MERGEABLE':
|
|
1823
|
-
return 'mergeable';
|
|
1824
|
-
case 'CONFLICTING':
|
|
1825
|
-
return 'conflicting';
|
|
1826
|
-
default:
|
|
1827
|
-
// Includes a field GitHub omitted entirely: not being told is not being told.
|
|
1828
|
-
return 'unknown';
|
|
1829
|
-
}
|
|
1830
|
-
}
|
|
1831
|
-
/** Did `later` happen AFTER `earlier` — a commit, or a re-request, landing past the review?
|
|
1832
|
-
* Unparseable or missing dates answer `false`, which is the conservative direction for both
|
|
1833
|
-
* callers: they only ever use a `true` to demote a review, so no answer must keep the review
|
|
1834
|
-
* current rather than silently dismiss one. */
|
|
1835
|
-
function isAfter(later, earlier) {
|
|
1836
|
-
const a = later ? Date.parse(later) : NaN;
|
|
1837
|
-
const b = earlier ? Date.parse(earlier) : NaN;
|
|
1838
|
-
return Number.isFinite(a) && Number.isFinite(b) && a > b;
|
|
1839
|
-
}
|
|
1840
|
-
/**
|
|
1841
|
-
* An issue's two signals as one word. `NOT_PLANNED` is kept apart from `completed` because they
|
|
1842
|
-
* are opposite outcomes — "we did it" vs "we won't" — and a task whose issue was declined must
|
|
1843
|
-
* not read as a task that landed.
|
|
1844
|
-
*/
|
|
1845
|
-
export function deriveIssueReferenceStatus(issue) {
|
|
1846
|
-
if (issue.state.toUpperCase() !== 'CLOSED')
|
|
1847
|
-
return 'open';
|
|
1848
|
-
return (issue.stateReason ?? '').toUpperCase() === 'NOT_PLANNED' ? 'not-planned' : 'completed';
|
|
1849
|
-
}
|
|
1850
|
-
/**
|
|
1851
|
-
* Status per NUMBER, resolved to whatever that number actually is.
|
|
1852
|
-
*
|
|
1853
|
-
* Batched and aliased like `fetchPrChecks`: one subprocess per chunk, each alias resolving
|
|
1854
|
-
* independently, and a number the forge does not have simply staying absent from `resolved` (its
|
|
1855
|
-
* chip then renders neutral, as it did before this seam existed). A failed chunk costs only its
|
|
1856
|
-
* own numbers, and says so rather than letting them look absent. Exported for tests; `runGraphql`
|
|
1857
|
-
* is injected so this is testable without shelling out.
|
|
1858
|
-
*/
|
|
1859
|
-
export async function fetchRefStatuses(runGraphql, owner, name, numbers, chunkSize = GH_REF_STATUS_MAX) {
|
|
1860
|
-
const out = { resolved: {}, failed: [] };
|
|
1861
|
-
if (numbers.length === 0)
|
|
1862
|
-
return out;
|
|
1863
|
-
for (let i = 0; i < numbers.length; i += chunkSize) {
|
|
1864
|
-
const chunk = numbers.slice(i, i + chunkSize);
|
|
1865
|
-
try {
|
|
1866
|
-
const raw = JSON.parse(await runGraphql(refStatusQuery(chunk), { owner, name }));
|
|
1867
|
-
const repository = ghRefStatusSchema.parse(raw?.data?.repository ?? {});
|
|
1868
|
-
chunk.forEach((number, index) => {
|
|
1869
|
-
const node = repository[`r${index}`];
|
|
1870
|
-
// Absent alias → the number is not in this repository at all. Left out of the map, which
|
|
1871
|
-
// is what the route reports as "not found" and the chip paints as neutral.
|
|
1872
|
-
if (!node)
|
|
1873
|
-
return;
|
|
1874
|
-
if (node.__typename === 'PullRequest') {
|
|
1875
|
-
const pr = ghRefStatusPrSchema.parse(node);
|
|
1876
|
-
if (!pr)
|
|
1877
|
-
return;
|
|
1878
|
-
if ((!raw.errors || (Array.isArray(raw.errors) && raw.errors.length === 0)) &&
|
|
1879
|
-
typeof repository.nameWithOwner === 'string' && repository.nameWithOwner.toLowerCase() === `${owner}/${name}`.toLowerCase()) {
|
|
1880
|
-
mergedPullRequestObservations.observe({ owner, repo: name, number }, { ...pr, number });
|
|
1881
|
-
}
|
|
1882
|
-
const head = pr.commits?.nodes[0]?.commit;
|
|
1883
|
-
const rollup = head?.statusCheckRollup;
|
|
1884
|
-
const mergeability = mergeabilityOf(pr.state, pr.mergeable);
|
|
1885
|
-
out.resolved[number] = {
|
|
1886
|
-
kind: 'pr',
|
|
1887
|
-
status: derivePrReferenceStatus({
|
|
1888
|
-
state: pr.state,
|
|
1889
|
-
isDraft: pr.isDraft,
|
|
1890
|
-
reviewDecision: pr.reviewDecision,
|
|
1891
|
-
// Adapt the single rollup state into the array shape `rollupToChecks` expects,
|
|
1892
|
-
// reusing the FAILURE/PENDING/SUCCESS vocabulary rather than duplicating it.
|
|
1893
|
-
checks: rollup ? rollupToChecks([{ state: rollup.state, status: null, conclusion: null }]) ?? null : null,
|
|
1894
|
-
headCommittedAt: head?.committedDate,
|
|
1895
|
-
// Two parents = "Update branch", which is dated now and answers nothing on its own —
|
|
1896
|
-
// so the first parent's date, the work it sat on top of, is carried with it.
|
|
1897
|
-
headParentCount: head?.parents?.totalCount,
|
|
1898
|
-
headFirstParentCommittedAt: head?.parents?.nodes?.[0]?.committedDate,
|
|
1899
|
-
// `reviews(last: 1, states: CHANGES_REQUESTED)` — the timestamp only. WHETHER changes
|
|
1900
|
-
// are requested stays `reviewDecision`'s answer, which is the one that accounts for
|
|
1901
|
-
// dismissed and superseded reviews.
|
|
1902
|
-
changesRequestedAt: pr.reviews?.nodes[0]?.submittedAt,
|
|
1903
|
-
reviewRequested: (pr.reviewRequests?.totalCount ?? 0) > 0,
|
|
1904
|
-
// WHEN that standing request was made. `reviewRequests` carries no date of its own,
|
|
1905
|
-
// and without one an old request looks exactly like a re-request.
|
|
1906
|
-
reviewRequestedAt: standingReviewRequestedAt(pr.reviewRequests, pr.timelineItems),
|
|
1907
|
-
}),
|
|
1908
|
-
// The tri-state, not a boolean: `unknown` has to survive as far as the cache, which
|
|
1909
|
-
// is what decides to ask again in seconds rather than in a minute.
|
|
1910
|
-
...(mergeability ? { mergeable: mergeability } : {}),
|
|
1911
|
-
};
|
|
1912
|
-
}
|
|
1913
|
-
else if (node.__typename === 'Issue') {
|
|
1914
|
-
const issue = ghRefStatusIssueSchema.parse(node);
|
|
1915
|
-
if (!issue)
|
|
1916
|
-
return;
|
|
1917
|
-
out.resolved[number] = { kind: 'issue', status: deriveIssueReferenceStatus(issue) };
|
|
1918
|
-
}
|
|
1919
|
-
});
|
|
1920
|
-
}
|
|
1921
|
-
catch (err) {
|
|
1922
|
-
// A failed chunk costs only its own numbers; the rest still resolve. They are recorded as
|
|
1923
|
-
// FAILED rather than left absent, so nothing downstream mistakes them for "no such number".
|
|
1924
|
-
out.failed.push(...chunk);
|
|
1925
|
-
out.reason ??= firstLine(err instanceof Error ? err.message : String(err));
|
|
1926
|
-
}
|
|
1927
|
-
}
|
|
1928
|
-
return out;
|
|
1929
|
-
}
|
|
1930
|
-
// Per-reference cache: keyed `repoRoot␀number` — by NUMBER, not by kind, because the kind is now
|
|
1931
|
-
// something the forge answers rather than something the caller asserts. Same 60 s TTL and bounded
|
|
1932
|
-
// shape as the checks cache; `null` is a cached "this repository has no such number", so a
|
|
1933
|
-
// transcript-scraped number from another repo is not re-queried on every table repaint.
|
|
1934
|
-
//
|
|
1935
|
-
// `unknownSince` is when this reference FIRST came back with its mergeability still being
|
|
1936
|
-
// computed, carried across refreshes so the fast recheck below is bounded to that first window
|
|
1937
|
-
// rather than restarting on every answer that is still `unknown`.
|
|
1938
|
-
const refStatusCache = new Map();
|
|
1939
|
-
const REF_STATUS_CACHE_MAX = 500;
|
|
1940
|
-
/** Test-only: drop the per-reference cache so cases don't leak state into each other. */
|
|
1941
|
-
export function __clearRefStatusCacheForTests() {
|
|
1942
|
-
refStatusCache.clear();
|
|
1943
|
-
refStatusFlights.clear();
|
|
1944
|
-
}
|
|
1945
|
-
/** Test-only: warm the cache the way the lazy route would have, so a reader can be tested
|
|
1946
|
-
* without a forge behind it. */
|
|
1947
|
-
export function __seedRefStatusCacheForTests(repoRoot, entries) {
|
|
1948
|
-
for (const [number, resolved] of entries) {
|
|
1949
|
-
refStatusCache.set(refStatusKey(repoRoot, number), { at: Date.now(), resolved });
|
|
1950
|
-
}
|
|
1951
|
-
}
|
|
1952
|
-
/**
|
|
1953
|
-
* Invalidate one reference after a known mutation. Let the next forge read establish status
|
|
1954
|
-
* rather than caching a guessed result.
|
|
1955
|
-
*/
|
|
1956
|
-
export function forgetRefStatus(repoRoot, number) {
|
|
1957
|
-
refStatusCache.delete(refStatusKey(repoRoot, number));
|
|
1958
|
-
refStatusFlights.delete(refStatusKey(repoRoot, number));
|
|
1959
|
-
}
|
|
1960
|
-
/**
|
|
1961
|
-
* Everything the cache ALREADY knows about these numbers. Never spawns `gh`, never awaits.
|
|
1962
|
-
*
|
|
1963
|
-
* This is what lets a status ride along with the rows that carry the references, instead of the
|
|
1964
|
-
* cockpit fetching it separately a moment later: the run index reads whatever is warm and ships
|
|
1965
|
-
* it, and a cold entry is simply absent — the lazy `/github/ref-status` route stays the thing that
|
|
1966
|
-
* actually goes and asks.
|
|
1967
|
-
*
|
|
1968
|
-
* Because it cannot cost anything, the caller may pass a SUPERSET of the numbers it will really
|
|
1969
|
-
* display. That matters: deciding which of a run's references a chip shows is the cockpit's rule
|
|
1970
|
-
* (#407, #526), deliberately not duplicated server-side, and a cache read does not need to know —
|
|
1971
|
-
* it can look up every number a run mentions and let the client pick.
|
|
1972
|
-
*/
|
|
1973
|
-
export function readCachedRefStatuses(repoRoot, numbers) {
|
|
1974
|
-
const out = { prs: {}, issues: {} };
|
|
1975
|
-
const now = Date.now();
|
|
1976
|
-
for (const number of new Set(numbers)) {
|
|
1977
|
-
const hit = refStatusCache.get(refStatusKey(repoRoot, number));
|
|
1978
|
-
if (!hit || !hit.resolved || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
|
|
1979
|
-
continue;
|
|
1980
|
-
out[hit.resolved.kind === 'pr' ? 'prs' : 'issues'][number] = hit.resolved.status;
|
|
1981
|
-
}
|
|
1982
|
-
return out;
|
|
1983
|
-
}
|
|
1984
|
-
// The `#N` in a forge URL. Defined beside the run search matcher, which reads it too (#864).
|
|
1985
|
-
export { refNumberFromUrl } from '../../contract/index.js';
|
|
1986
|
-
/** A closed issue or an abandoned PR can be REOPENED, so this is long rather than forever — but
|
|
1987
|
-
* it is the rare event, and re-asking a hundred settled references every minute to catch it is
|
|
1988
|
-
* the wrong trade. */
|
|
1989
|
-
const REF_STATUS_CLOSED_TTL = 10 * 60_000;
|
|
1990
|
-
/** A merged pull request is merged forever: GitHub has no un-merge. Capped at a day only so a
|
|
1991
|
-
* long-lived server eventually re-reads rather than trusting a value from another era. */
|
|
1992
|
-
const REF_STATUS_MERGED_TTL = 24 * 60 * 60_000;
|
|
1993
|
-
/**
|
|
1994
|
-
* How long a cached answer stays fresh — by how changeable that answer IS.
|
|
1995
|
-
*
|
|
1996
|
-
* One TTL for everything gets both ends wrong: it re-asks about a merged PR (which cannot change)
|
|
1997
|
-
* every minute, and it is the only thing standing between a running CI job and a stale chip. What
|
|
1998
|
-
* a reader wants rechecked is precisely what is still moving.
|
|
1999
|
-
*
|
|
2000
|
-
* A number the repository does not have keeps the short TTL: it is usually a wrong number, but it
|
|
2001
|
-
* is also what a reference to a not-yet-created PR looks like, and re-asking is cheap.
|
|
2002
|
-
*/
|
|
2003
|
-
function refStatusTtl(entry, unknownSince, now = Date.now()) {
|
|
2004
|
-
if (!entry)
|
|
2005
|
-
return CACHE_MS;
|
|
2006
|
-
// Mergeability GitHub has not finished computing is not an answer to cache for a minute. It is
|
|
2007
|
-
// the normal reply for the first seconds after a push, and holding it that long is what let a
|
|
2008
|
-
// conflicting pull request read "Ready to merge" until the page was reloaded. Ask again in
|
|
2009
|
-
// seconds instead — and only while it is still plausibly being computed, so a repository that
|
|
2010
|
-
// answers `UNKNOWN` indefinitely settles back to the ordinary cadence rather than spawning `gh`
|
|
2011
|
-
// every few seconds forever.
|
|
2012
|
-
if (entry.mergeable === 'unknown' &&
|
|
2013
|
-
unknownSince !== undefined &&
|
|
2014
|
-
now - unknownSince < MERGEABILITY_UNKNOWN_WINDOW_MS) {
|
|
2015
|
-
return MERGEABILITY_UNKNOWN_TTL_MS;
|
|
2016
|
-
}
|
|
2017
|
-
switch (entry.status) {
|
|
2018
|
-
case 'merged':
|
|
2019
|
-
return REF_STATUS_MERGED_TTL;
|
|
2020
|
-
case 'closed':
|
|
2021
|
-
case 'completed':
|
|
2022
|
-
case 'not-planned':
|
|
2023
|
-
return REF_STATUS_CLOSED_TTL;
|
|
2024
|
-
default:
|
|
2025
|
-
return CACHE_MS;
|
|
2026
|
-
}
|
|
2027
|
-
}
|
|
2028
|
-
/** How long a status can be trusted to stay put — `null` when it can never change again. The
|
|
2029
|
-
* cadence half of `refStatusTtl`, and deliberately the same function: a value the cache would
|
|
2030
|
-
* still be serving is a value there is no point asking for, and a value it would NOT serve —
|
|
2031
|
-
* mergeability still being computed — is one the cockpit should come back for just as soon. */
|
|
2032
|
-
function refStatusRecheckAfter(entry, unknownSince, now = Date.now()) {
|
|
2033
|
-
if (entry?.status === 'merged')
|
|
2034
|
-
return null; // GitHub has no un-merge
|
|
2035
|
-
return refStatusTtl(entry, unknownSince, now);
|
|
2036
|
-
}
|
|
2037
|
-
/** How long the WHOLE answer holds — the soonest any single reference in it could differ. `null`
|
|
2038
|
-
* only when every one of them is immutable, which is what tells the cockpit to stop scheduling.
|
|
2039
|
-
* Taking the per-reference values rather than the entries, because one of them may be on the fast
|
|
2040
|
-
* mergeability cadence and the batch has to travel at the speed of its most impatient member. */
|
|
2041
|
-
function batchRecheckAfter(rechecks) {
|
|
2042
|
-
let soonest = null;
|
|
2043
|
-
for (const after of rechecks) {
|
|
2044
|
-
if (after === null)
|
|
2045
|
-
continue;
|
|
2046
|
-
soonest = soonest === null ? after : Math.min(soonest, after);
|
|
2047
|
-
}
|
|
2048
|
-
return soonest;
|
|
2049
|
-
}
|
|
2050
|
-
/**
|
|
2051
|
-
* How long a still-computing mergeability holds, and for how long that fast cadence applies.
|
|
2052
|
-
*
|
|
2053
|
-
* Five seconds because that is the shape of the thing being waited for: GitHub kicks off the
|
|
2054
|
-
* merge-base computation when asked and usually has it by the next request. Bounded to a minute
|
|
2055
|
-
* because a value that is STILL unknown after that is not a computation in flight any more — it is
|
|
2056
|
-
* a repository that will not answer, and re-asking it every five seconds forever costs a `gh`
|
|
2057
|
-
* subprocess a second for nothing.
|
|
2058
|
-
*/
|
|
2059
|
-
const MERGEABILITY_UNKNOWN_TTL_MS = 5_000;
|
|
2060
|
-
const MERGEABILITY_UNKNOWN_WINDOW_MS = 60_000;
|
|
2061
|
-
/** A forge that could not be reached is worth retrying, and worth not hammering: a workspace with
|
|
2062
|
-
* no `gh` installed would otherwise spawn a subprocess a minute, forever, to be told the same
|
|
2063
|
-
* thing. Five minutes is the same order as the cockpit's own reconnect cadence. */
|
|
2064
|
-
const REF_STATUS_RETRY_MS = 5 * 60_000;
|
|
2065
|
-
/**
|
|
2066
|
-
* Use failed gh GraphQL stdout only when it contains usable data.repository. Preserve successful
|
|
2067
|
-
* aliases in partial responses; rethrow malformed or unresolved-repository failures.
|
|
2068
|
-
*/
|
|
2069
|
-
function refStatusGraphql(repoRoot, context = githubContext(repoRoot)) {
|
|
2070
|
-
return async (query, variables) => {
|
|
2071
|
-
const args = ghGraphqlArgs(query, variables);
|
|
2072
|
-
try {
|
|
2073
|
-
return await gh(repoRoot, args, 15_000, undefined, context);
|
|
2074
|
-
}
|
|
2075
|
-
catch (err) {
|
|
2076
|
-
const stdout = err.stdout;
|
|
2077
|
-
if (typeof stdout === 'string' && hasResolvedRepository(stdout))
|
|
2078
|
-
return stdout;
|
|
2079
|
-
throw err;
|
|
2080
|
-
}
|
|
2081
|
-
};
|
|
2082
|
-
}
|
|
2083
|
-
/**
|
|
2084
|
-
* The repo handle, memoized in the same map `resolveRepoHandle` uses — but rethrowing instead of
|
|
2085
|
-
* answering `null`.
|
|
2086
|
-
*
|
|
2087
|
-
* The memo is the point: without it every recheck tick spawned a second subprocess to re-learn an
|
|
2088
|
-
* `owner/name` that changes approximately never, doubling the cost of the one query that actually
|
|
2089
|
-
* carries information. The difference from `resolveRepoHandle` is the failure: this route turns a
|
|
2090
|
-
* `gh` error into the payload's `reason` — "gh CLI not found — install it and run `gh auth login`"
|
|
2091
|
-
* is what the chip's tooltip now shows a user — and a `null` would erase which failure it was.
|
|
2092
|
-
*/
|
|
2093
|
-
async function resolveRepoHandleStrict(repoRoot, context = githubContext(repoRoot)) {
|
|
2094
|
-
return sharedRepoHandle(repoRoot, undefined, context);
|
|
2095
|
-
}
|
|
2096
|
-
/** Is this a reply we can still read aliases out of? `repository: null` says the handle did not
|
|
2097
|
-
* resolve, which is a real failure and must not be read as "the numbers are all missing". */
|
|
2098
|
-
function hasResolvedRepository(stdout) {
|
|
2099
|
-
try {
|
|
2100
|
-
const parsed = JSON.parse(stdout);
|
|
2101
|
-
const repository = parsed?.data?.repository;
|
|
2102
|
-
return typeof repository === 'object' && repository !== null;
|
|
2103
|
-
}
|
|
2104
|
-
catch {
|
|
2105
|
-
return false;
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
// Ownership is per reference, before discovery starts. Overlapping requests join just the
|
|
2109
|
-
// numbers they need; extra numbers form their own batch without a batching timer or new delay.
|
|
2110
|
-
// At capacity, untracked work answers its callers without caching: it has no ownership token
|
|
2111
|
-
// to protect publication against invalidation or newer requests. Retained ownership is at most 500.
|
|
2112
|
-
const refStatusFlights = new Map();
|
|
2113
|
-
async function sharedRefStatusMisses(repoRoot, numbers, context) {
|
|
2114
|
-
const pending = new Map();
|
|
2115
|
-
const owned = [];
|
|
2116
|
-
for (const n of numbers) {
|
|
2117
|
-
const flight = refStatusFlights.get(refStatusKey(repoRoot, n, context));
|
|
2118
|
-
if (flight)
|
|
2119
|
-
pending.set(n, flight);
|
|
2120
|
-
else
|
|
2121
|
-
owned.push(n);
|
|
2122
|
-
}
|
|
2123
|
-
if (owned.length) {
|
|
2124
|
-
const batch = (async () => {
|
|
2125
|
-
const handle = await resolveRepoHandleStrict(repoRoot, context);
|
|
2126
|
-
if (!handle)
|
|
2127
|
-
throw new Error('repository handle unavailable');
|
|
2128
|
-
return fetchRefStatuses(refStatusGraphql(repoRoot, context), handle.owner, handle.name, owned);
|
|
2129
|
-
})();
|
|
2130
|
-
for (const n of owned) {
|
|
2131
|
-
const key = refStatusKey(repoRoot, n, context);
|
|
2132
|
-
const tracked = refStatusFlights.size < REF_STATUS_CACHE_MAX;
|
|
2133
|
-
const promise = batch.then(result => {
|
|
2134
|
-
if (result.failed.includes(n))
|
|
2135
|
-
return { reason: result.reason ?? 'GitHub could not be reached' };
|
|
2136
|
-
// Date fresh results at arrival; keep the original unknown-mergeability retry window.
|
|
2137
|
-
const storedAt = Date.now();
|
|
2138
|
-
const entry = result.resolved[n] ?? null;
|
|
2139
|
-
const unknownSince = entry?.mergeable === 'unknown'
|
|
2140
|
-
? (refStatusCache.get(key)?.unknownSince ?? storedAt) : undefined;
|
|
2141
|
-
const value = { resolved: entry, ...(unknownSince === undefined ? {} : { unknownSince }) };
|
|
2142
|
-
if (tracked && refStatusFlights.get(key) === promise) {
|
|
2143
|
-
refStatusCache.set(key, { at: storedAt, ...value });
|
|
2144
|
-
while (refStatusCache.size > REF_STATUS_CACHE_MAX)
|
|
2145
|
-
refStatusCache.delete(refStatusCache.keys().next().value);
|
|
2146
|
-
}
|
|
2147
|
-
return value;
|
|
2148
|
-
}).finally(() => {
|
|
2149
|
-
if (refStatusFlights.get(key) === promise)
|
|
2150
|
-
refStatusFlights.delete(key);
|
|
2151
|
-
});
|
|
2152
|
-
if (tracked)
|
|
2153
|
-
refStatusFlights.set(key, promise);
|
|
2154
|
-
pending.set(n, promise);
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
return Promise.all(numbers.map(async (n) => [n, await pending.get(n)]));
|
|
2158
|
-
}
|
|
2159
|
-
/**
|
|
2160
|
-
* Route-facing reference status. Resolves the repo handle once, serves fresh cache entries,
|
|
2161
|
-
* queries only the misses, and degrades to `{ available: false, reason }` when `gh` or the handle
|
|
2162
|
-
* is unavailable — never a throw, never a 5xx.
|
|
2163
|
-
*
|
|
2164
|
-
* The two request lists are merged into ONE set of numbers: issues and pull requests share a
|
|
2165
|
-
* repository's numbering space, so a number is one thing and asking about it twice would be asking
|
|
2166
|
-
* the same question twice. What comes back is filed by what each number turned out to BE, which is
|
|
2167
|
-
* why a chip whose kind the cockpit guessed wrong still gets the right status.
|
|
2168
|
-
*/
|
|
2169
|
-
export async function fetchGithubRefStatus(repoRoot, input) {
|
|
2170
|
-
const context = githubContext(repoRoot);
|
|
2171
|
-
const asPrs = sanitizeRefNumbers(input.prs);
|
|
2172
|
-
const asIssues = sanitizeRefNumbers(input.issues);
|
|
2173
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
2174
|
-
return mockGithubRefStatus(asPrs, asIssues);
|
|
2175
|
-
const wanted = [...new Set([...asPrs, ...asIssues])];
|
|
2176
|
-
const resolved = { prs: {}, issues: {} };
|
|
2177
|
-
// How soon each reference in the answer could differ — what the batch's cadence is the minimum
|
|
2178
|
-
// of. Per reference rather than per batch because mergeability still being computed is worth
|
|
2179
|
-
// coming back for in seconds while everything else holds for a minute.
|
|
2180
|
-
const rechecks = [];
|
|
2181
|
-
// The second axis, and a list rather than a map because it is nearly always empty: only the
|
|
2182
|
-
// pull requests the forge actively called CONFLICTING are named (see `mergeabilityOf`).
|
|
2183
|
-
const conflicts = [];
|
|
2184
|
-
const file = (number, entry, unknownSince) => {
|
|
2185
|
-
rechecks.push(refStatusRecheckAfter(entry, unknownSince));
|
|
2186
|
-
if (!entry)
|
|
2187
|
-
return;
|
|
2188
|
-
resolved[entry.kind === 'pr' ? 'prs' : 'issues'][number] = entry.status;
|
|
2189
|
-
if (entry.mergeable === 'conflicting')
|
|
2190
|
-
conflicts.push(number);
|
|
2191
|
-
};
|
|
2192
|
-
const misses = [];
|
|
2193
|
-
const now = Date.now();
|
|
2194
|
-
for (const n of wanted) {
|
|
2195
|
-
const hit = refStatusCache.get(refStatusKey(repoRoot, n, context));
|
|
2196
|
-
if (!hit || now - hit.at >= refStatusTtl(hit.resolved, hit.unknownSince, now))
|
|
2197
|
-
misses.push(n);
|
|
2198
|
-
else
|
|
2199
|
-
file(n, hit.resolved, hit.unknownSince);
|
|
2200
|
-
}
|
|
2201
|
-
if (misses.length === 0) {
|
|
2202
|
-
return {
|
|
2203
|
-
available: true,
|
|
2204
|
-
prs: resolved.prs,
|
|
2205
|
-
issues: resolved.issues,
|
|
2206
|
-
conflicts,
|
|
2207
|
-
recheckAfterMs: batchRecheckAfter(rechecks),
|
|
2208
|
-
};
|
|
2209
|
-
}
|
|
2210
|
-
try {
|
|
2211
|
-
const entries = await sharedRefStatusMisses(repoRoot, misses, context);
|
|
2212
|
-
let failure;
|
|
2213
|
-
for (const [n, result] of entries) {
|
|
2214
|
-
if ('reason' in result)
|
|
2215
|
-
failure ??= result.reason;
|
|
2216
|
-
else
|
|
2217
|
-
file(n, result.resolved, result.unknownSince);
|
|
2218
|
-
}
|
|
2219
|
-
// Anything unasked makes the whole answer `unavailable`, deliberately. The alternative is a
|
|
2220
|
-
// payload where a number we could not reach is indistinguishable from one that does not exist,
|
|
2221
|
-
// and the cockpit would paint "not found on this repository" over a perfectly good PR — the
|
|
2222
|
-
// exact defect this route was reported for. The successes are cached either way, so the next
|
|
2223
|
-
// request costs only the numbers that failed and usually answers in full.
|
|
2224
|
-
if (failure !== undefined) {
|
|
2225
|
-
return {
|
|
2226
|
-
available: false,
|
|
2227
|
-
reason: failure,
|
|
2228
|
-
recheckAfterMs: REF_STATUS_RETRY_MS,
|
|
2229
|
-
};
|
|
2230
|
-
}
|
|
2231
|
-
return {
|
|
2232
|
-
available: true,
|
|
2233
|
-
prs: resolved.prs,
|
|
2234
|
-
issues: resolved.issues,
|
|
2235
|
-
conflicts,
|
|
2236
|
-
recheckAfterMs: batchRecheckAfter(rechecks),
|
|
2237
|
-
};
|
|
2238
|
-
}
|
|
2239
|
-
catch (err) {
|
|
2240
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
2241
|
-
return {
|
|
2242
|
-
available: false,
|
|
2243
|
-
reason: /ENOENT/.test(message)
|
|
2244
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
2245
|
-
: firstLine(message),
|
|
2246
|
-
recheckAfterMs: REF_STATUS_RETRY_MS,
|
|
2247
|
-
};
|
|
2248
|
-
}
|
|
2249
|
-
}
|
|
2250
|
-
/** NUL separator, as everywhere else here: two projects each having a #42 must not collide. */
|
|
2251
|
-
function refStatusKey(repoRoot, number, context = githubContext(repoRoot)) {
|
|
2252
|
-
return `${context.key}\0#${number}`;
|
|
2253
|
-
}
|
|
2254
|
-
function sanitizeRefNumbers(numbers) {
|
|
2255
|
-
return [...new Set(numbers ?? [])].filter((n) => Number.isInteger(n) && n > 0).slice(0, GH_REF_STATUS_MAX);
|
|
2256
|
-
}
|
|
2257
|
-
/** CEZ_DRY_RUN=1 — statuses derived from the mock catalog so the offline demo paints real chips. */
|
|
2258
|
-
function mockGithubRefStatus(prs, issues) {
|
|
2259
|
-
const catalog = mockGithub();
|
|
2260
|
-
const byPr = new Map(catalog.prs.map((p) => [p.number, p]));
|
|
2261
|
-
const byIssue = new Set(catalog.issues.map((i) => i.number));
|
|
2262
|
-
const out = { available: true, prs: {}, issues: {}, recheckAfterMs: CACHE_MS };
|
|
2263
|
-
for (const n of prs) {
|
|
2264
|
-
const pr = byPr.get(n);
|
|
2265
|
-
if (pr) {
|
|
2266
|
-
out.prs[n] = derivePrReferenceStatus({
|
|
2267
|
-
state: 'OPEN',
|
|
2268
|
-
isDraft: pr.isDraft,
|
|
2269
|
-
reviewDecision: null,
|
|
2270
|
-
checks: (pr.checks ?? null),
|
|
2271
|
-
});
|
|
2272
|
-
}
|
|
2273
|
-
}
|
|
2274
|
-
for (const n of issues)
|
|
2275
|
-
if (byIssue.has(n))
|
|
2276
|
-
out.issues[n] = 'open';
|
|
2277
|
-
return out;
|
|
2278
|
-
}
|
|
2279
|
-
/**
|
|
2280
|
-
* The conversation thread for one issue/PR, lazily. `{owner}`/`{repo}` in the gh api paths are
|
|
2281
|
-
* filled from the worktree's remote by gh itself, so no extra handle lookup. Everything degrades:
|
|
2282
|
-
* gh missing/offline → `{ available: false, reason }`, a 404 → a "not found" hint — never a throw.
|
|
2283
|
-
*
|
|
2284
|
-
* Since #525 the thread is sourced from `/issues/{n}/timeline`, which returns comments AND events
|
|
2285
|
-
* in one stream: `commented` rows go through the unchanged `normalizeComments`, the rest through
|
|
2286
|
-
* `normalizeEvents`. `comments[]` therefore keeps its exact pre-#525 shape, contents and cap
|
|
2287
|
-
* (BACKWARD_COMPATIBILITY.md §2) — see the top-up below for the one case that needed defending.
|
|
2288
|
-
*/
|
|
2289
|
-
export async function fetchGithubComments(repoRoot, kind, number, refresh = false) {
|
|
2290
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
2291
|
-
return mockGithubComments(kind, number);
|
|
2292
|
-
// NUL separator: cannot appear in a filesystem path, so roots can never alias.
|
|
2293
|
-
const key = `${repoRoot}\0${kind}#${number}`;
|
|
2294
|
-
const hit = commentsCache.get(key);
|
|
2295
|
-
if (!refresh && hit && Date.now() - hit.at < CACHE_MS)
|
|
2296
|
-
return hit.data;
|
|
2297
|
-
// PR conversation comments live on the issues endpoint too — always use it for the body thread.
|
|
2298
|
-
const legacyComments = () => gh(repoRoot, ['api', `repos/{owner}/{repo}/issues/${number}/comments`, '--paginate']);
|
|
2299
|
-
// The detail tier (hearsay-tools/cezarion#1183): the list no longer has to carry a body, so
|
|
2300
|
-
// the pane asks for it here, in parallel with the thread. It is attached only to a thread
|
|
2301
|
-
// that loaded, and a failed view never costs the thread.
|
|
2302
|
-
const detail = fetchItemDetail(repoRoot, kind, number);
|
|
2303
|
-
try {
|
|
2304
|
-
let commentRows = [];
|
|
2305
|
-
let events;
|
|
2306
|
-
let eventsTruncated = false;
|
|
2307
|
-
let stoppedShort = false;
|
|
2308
|
-
try {
|
|
2309
|
-
const pages = await fetchTimelinePages((page, timeoutMs) => gh(repoRoot, [
|
|
2310
|
-
'api',
|
|
2311
|
-
'-H',
|
|
2312
|
-
'Accept: application/vnd.github+json',
|
|
2313
|
-
`repos/{owner}/{repo}/issues/${number}/timeline?per_page=${TIMELINE_PER_PAGE}&page=${page}`,
|
|
2314
|
-
], timeoutMs));
|
|
2315
|
-
stoppedShort = pages.stoppedShort;
|
|
2316
|
-
commentRows = pages.rows.filter((r) => r?.event === 'commented');
|
|
2317
|
-
const normalized = normalizeEvents(pages.rows);
|
|
2318
|
-
events = normalized.events;
|
|
2319
|
-
eventsTruncated = normalized.truncated;
|
|
2320
|
-
// Comments top-up. The two ENTRY caps are independent, but the FETCH budget is not: today's
|
|
2321
|
-
// call is an unbounded --paginate over a comments-only endpoint, so every comment is fetched
|
|
2322
|
-
// and mergeThread picks the oldest 200 from the complete set. Under the timeline those same
|
|
2323
|
-
// 200 slots are filled from at most 1000 rows in which events compete with comments — so on
|
|
2324
|
-
// a 1500-row thread with 250 interleaved comments, comments[] would return ~167 where today
|
|
2325
|
-
// it returns 200. Same §2 defect class as a combined entry cap, arriving via the source set.
|
|
2326
|
-
//
|
|
2327
|
-
// The trigger deliberately over-fires: it cannot distinguish "comments were cut off" from
|
|
2328
|
-
// "this thread just has few comments", because the second is only knowable by fetching them.
|
|
2329
|
-
// So on an event-heavy thread with 30 comments it re-fetches 30 complete comments. Accepted
|
|
2330
|
-
// — it fires only past ~1000 timeline rows, behind the 60 s LRU, and the alternative is a §2
|
|
2331
|
-
// regression. In the other direction the threshold is provably sound: with ≥200 commented
|
|
2332
|
-
// rows already in the oldest-first prefix, mergeThread's oldest-200 cut lies inside it.
|
|
2333
|
-
if (stoppedShort && commentRows.length < THREAD_ENTRY_CAP) {
|
|
2334
|
-
// Its OWN nested catch. The inner handler's remedy is the fallback — which is this very
|
|
2335
|
-
// call — and the outer handler returns { available: false, comments: [] }, emptying a
|
|
2336
|
-
// thread that was about to render. So a thrown top-up is swallowed: keep the commented
|
|
2337
|
-
// rows the timeline already returned and carry on. That is at worst the short list the
|
|
2338
|
-
// safeguard existed to avoid, never worse than not having attempted it.
|
|
2339
|
-
try {
|
|
2340
|
-
commentRows = z.array(z.unknown()).parse(JSON.parse(await legacyComments()));
|
|
2341
|
-
}
|
|
2342
|
-
catch {
|
|
2343
|
-
// keep the timeline's own commented rows
|
|
2344
|
-
}
|
|
2345
|
-
}
|
|
2346
|
-
}
|
|
2347
|
-
catch (timelineErr) {
|
|
2348
|
-
// Scoped INSIDE the existing outer catch on purpose: the outer handler's /404|not found/i
|
|
2349
|
-
// branch would otherwise turn a timeline 404 into an empty thread. ENOENT is the one failure
|
|
2350
|
-
// the fallback cannot rescue — nothing will work, and a second spawn fails identically.
|
|
2351
|
-
const message = timelineErr instanceof Error ? timelineErr.message : String(timelineErr);
|
|
2352
|
-
if (/ENOENT/.test(message))
|
|
2353
|
-
throw timelineErr;
|
|
2354
|
-
// Every other endpoint-level failure substitutes the legacy comments call. It is a
|
|
2355
|
-
// substitution, not a retry — a different endpoint, which typically still answers. (A 403
|
|
2356
|
-
// attaches to the token rather than the endpoint, so it cannot succeed either; not
|
|
2357
|
-
// special-cased, since rate-limit replies are immediate and it costs one fast spawn.)
|
|
2358
|
-
commentRows = z.array(z.unknown()).parse(JSON.parse(await legacyComments()));
|
|
2359
|
-
events = undefined;
|
|
2360
|
-
}
|
|
2361
|
-
// Per-commit CI (#525 Phase 2). One extra subprocess per opened thread that contains commits,
|
|
2362
|
-
// behind the same 60 s LRU — a per-thread-open cost, not per-render. Every failure path here
|
|
2363
|
-
// leaves `checks` ABSENT rather than null, so commits simply render unglyphed: the fetch
|
|
2364
|
-
// degrades to "no data" and the render decides what absence looks like.
|
|
2365
|
-
const commitShas = (events ?? []).flatMap((e) => (e.kind === 'committed' && e.sha ? [e.sha] : []));
|
|
2366
|
-
if (commitShas.length > 0) {
|
|
2367
|
-
const handle = await resolveRepoHandle(repoRoot);
|
|
2368
|
-
if (handle) {
|
|
2369
|
-
const runGraphql = (query, variables) => {
|
|
2370
|
-
const args = ghGraphqlArgs(query, variables);
|
|
2371
|
-
return gh(repoRoot, args);
|
|
2372
|
-
};
|
|
2373
|
-
const checks = await fetchCommitChecks(runGraphql, handle.owner, handle.name, commitShas);
|
|
2374
|
-
for (const event of events ?? []) {
|
|
2375
|
-
if (event.kind !== 'committed' || !event.sha)
|
|
2376
|
-
continue;
|
|
2377
|
-
if (event.sha in checks) {
|
|
2378
|
-
delete event.checks;
|
|
2379
|
-
Object.assign(event, defined({ checks: checks[event.sha] }));
|
|
2380
|
-
}
|
|
2381
|
-
}
|
|
2382
|
-
}
|
|
2383
|
-
}
|
|
2384
|
-
const parts = [normalizeComments(commentRows)];
|
|
2385
|
-
if (kind === 'pr') {
|
|
2386
|
-
const reviewsOut = await gh(repoRoot, ['api', `repos/{owner}/{repo}/pulls/${number}/reviews`, '--paginate']);
|
|
2387
|
-
parts.push(normalizeReviews(JSON.parse(reviewsOut)));
|
|
2388
|
-
}
|
|
2389
|
-
const { comments, truncated } = mergeThread(parts);
|
|
2390
|
-
const data = defined({
|
|
2391
|
-
available: true,
|
|
2392
|
-
comments,
|
|
2393
|
-
// OR-folded exactly as before, so the pre-existing >200-comments trigger is preserved
|
|
2394
|
-
// rather than replaced.
|
|
2395
|
-
truncated: truncated || eventsTruncated || stoppedShort || undefined,
|
|
2396
|
-
});
|
|
2397
|
-
if (events)
|
|
2398
|
-
data.events = events;
|
|
2399
|
-
const itemDetail = await detail;
|
|
2400
|
-
if (itemDetail)
|
|
2401
|
-
data.detail = itemDetail;
|
|
2402
|
-
cacheComments(key, data);
|
|
2403
|
-
return data;
|
|
2404
|
-
}
|
|
2405
|
-
catch (err) {
|
|
2406
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
2407
|
-
const reason = /ENOENT/.test(message)
|
|
2408
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
2409
|
-
: /404|not found/i.test(message)
|
|
2410
|
-
? 'not found on GitHub — it may be closed or deleted'
|
|
2411
|
-
: firstLine(message);
|
|
2412
|
-
return { available: false, reason, comments: [] };
|
|
2413
|
-
}
|
|
2414
|
-
}
|
|
2415
|
-
/** CEZ_DRY_RUN=1 — a small fixed thread (one image-bearing comment, plus a review for PRs) so
|
|
2416
|
-
* the whole feature is demoable and e2e-testable offline. */
|
|
2417
|
-
function mockGithubComments(kind, number) {
|
|
2418
|
-
const base = Date.now() - 3_600_000;
|
|
2419
|
-
const at = (offset) => new Date(base + offset).toISOString();
|
|
2420
|
-
const comments = [
|
|
2421
|
-
{
|
|
2422
|
-
id: 1,
|
|
2423
|
-
author: 'ada',
|
|
2424
|
-
avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',
|
|
2425
|
-
createdAt: at(0),
|
|
2426
|
-
body: 'Thanks for the report — I can reproduce. Which browser were you on?\n\n```\nchrome 126, macOS\n```',
|
|
2427
|
-
kind: 'comment',
|
|
2428
|
-
url: 'https://github.com/mock/repo/issues/1#issuecomment-1',
|
|
2429
|
-
},
|
|
2430
|
-
{
|
|
2431
|
-
id: 2,
|
|
2432
|
-
author: 'lin',
|
|
2433
|
-
createdAt: at(600_000),
|
|
2434
|
-
body: 'Here is the failing screen:\n\n',
|
|
2435
|
-
kind: 'comment',
|
|
2436
|
-
url: 'https://github.com/mock/repo/issues/1#issuecomment-2',
|
|
2437
|
-
},
|
|
2438
|
-
];
|
|
2439
|
-
if (kind === 'pr') {
|
|
2440
|
-
comments.push({
|
|
2441
|
-
id: 3,
|
|
2442
|
-
author: 'grace',
|
|
2443
|
-
avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
|
|
2444
|
-
createdAt: at(1_200_000),
|
|
2445
|
-
body: 'Looks good overall — please add a regression test before this lands.',
|
|
2446
|
-
kind: 'review',
|
|
2447
|
-
reviewState: 'changes_requested',
|
|
2448
|
-
url: 'https://github.com/mock/repo/pull/1#pullrequestreview-3',
|
|
2449
|
-
});
|
|
2450
|
-
}
|
|
2451
|
-
// Timeline events (#525) so the whole feature is demoable and e2e-testable offline. Deliberately
|
|
2452
|
-
// covers the cases that are easy to get wrong rather than one of each: a multi-commit run by ONE
|
|
2453
|
-
// author (exercises the client-side grouping) with MIXED check states (passing/failing/pending
|
|
2454
|
-
// plus one `null` = no CI configured), a label change, a cross-reference, and — for PRs — a
|
|
2455
|
-
// merge. SHAs are full 40-char because the rollup query's `oid` rejects abbreviated ones, and a
|
|
2456
|
-
// fixture that cheated there would not survive being pasted into a real query.
|
|
2457
|
-
const sha = (seed) => seed.repeat(40).slice(0, 40);
|
|
2458
|
-
const events = [
|
|
2459
|
-
{
|
|
2460
|
-
id: 'evt-100',
|
|
2461
|
-
kind: 'labeled',
|
|
2462
|
-
actor: 'ada',
|
|
2463
|
-
avatarUrl: 'https://avatars.githubusercontent.com/u/1?v=4',
|
|
2464
|
-
createdAt: at(300_000),
|
|
2465
|
-
label: { name: 'bug', color: 'd73a4a' },
|
|
2466
|
-
},
|
|
2467
|
-
{
|
|
2468
|
-
id: `evt-${sha('a')}`,
|
|
2469
|
-
kind: 'committed',
|
|
2470
|
-
actor: 'Lin Zhao',
|
|
2471
|
-
createdAt: at(900_000),
|
|
2472
|
-
sha: sha('a'),
|
|
2473
|
-
message: 'fix(session): keep the refresh token on reload',
|
|
2474
|
-
checks: 'passing',
|
|
2475
|
-
},
|
|
2476
|
-
{
|
|
2477
|
-
id: `evt-${sha('b')}`,
|
|
2478
|
-
kind: 'committed',
|
|
2479
|
-
actor: 'Lin Zhao',
|
|
2480
|
-
createdAt: at(960_000),
|
|
2481
|
-
sha: sha('b'),
|
|
2482
|
-
message: 'test(session): cover the reload path',
|
|
2483
|
-
checks: 'failing',
|
|
2484
|
-
},
|
|
2485
|
-
{
|
|
2486
|
-
id: `evt-${sha('c')}`,
|
|
2487
|
-
kind: 'committed',
|
|
2488
|
-
actor: 'Lin Zhao',
|
|
2489
|
-
createdAt: at(1_020_000),
|
|
2490
|
-
sha: sha('c'),
|
|
2491
|
-
message: 'chore: appease the linter',
|
|
2492
|
-
checks: 'pending',
|
|
2493
|
-
},
|
|
2494
|
-
{
|
|
2495
|
-
id: `evt-${sha('d')}`,
|
|
2496
|
-
kind: 'committed',
|
|
2497
|
-
actor: 'Lin Zhao',
|
|
2498
|
-
createdAt: at(1_080_000),
|
|
2499
|
-
sha: sha('d'),
|
|
2500
|
-
message: 'docs: note the new behavior',
|
|
2501
|
-
checks: null, // no CI configured — renders no glyph, distinct from absent
|
|
2502
|
-
},
|
|
2503
|
-
{
|
|
2504
|
-
id: 'evt-101',
|
|
2505
|
-
kind: 'cross-referenced',
|
|
2506
|
-
actor: 'grace',
|
|
2507
|
-
avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
|
|
2508
|
-
createdAt: at(1_500_000),
|
|
2509
|
-
refNumber: 42,
|
|
2510
|
-
refTitle: 'Session handling rewrite',
|
|
2511
|
-
refIsPr: true,
|
|
2512
|
-
url: 'https://github.com/mock/repo/pull/42',
|
|
2513
|
-
},
|
|
2514
|
-
];
|
|
2515
|
-
if (kind === 'pr') {
|
|
2516
|
-
events.push({
|
|
2517
|
-
id: 'evt-102',
|
|
2518
|
-
kind: 'merged',
|
|
2519
|
-
actor: 'grace',
|
|
2520
|
-
avatarUrl: 'https://avatars.githubusercontent.com/u/3?v=4',
|
|
2521
|
-
createdAt: at(1_800_000),
|
|
2522
|
-
});
|
|
2523
|
-
}
|
|
2524
|
-
// The detail tier (hearsay-tools/cezarion#1183): the catalog row's own body and diffstat.
|
|
2525
|
-
const row = number === undefined ? undefined
|
|
2526
|
-
: (kind === 'pr' ? mockGithub().prs : mockGithub().issues).find((item) => item.number === number);
|
|
2527
|
-
const detail = row ? {
|
|
2528
|
-
body: row.body ?? '',
|
|
2529
|
-
...(kind === 'pr' ? { additions: row.additions ?? 0, deletions: row.deletions ?? 0 } : {}),
|
|
2530
|
-
} : undefined;
|
|
2531
|
-
return { available: true, comments, events, ...(detail ? { detail } : {}) };
|
|
2532
|
-
}
|
|
2533
|
-
// ---- draft-PR creation (review gate, spec 009) ------------------------------
|
|
2534
|
-
// Final autosave-commit → `git push -u origin cez/<id8>` → `gh pr create
|
|
2535
|
-
// --draft`, all executed in the task worktree (gh picks the repo up from the
|
|
2536
|
-
// worktree's remote). Every failure maps to a one-line human error — the GUI
|
|
2537
|
-
// shows it as a toast plus the manual `git merge <branch>` fallback. Never throws.
|
|
2538
|
-
const PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/;
|
|
2539
|
-
const PUSH_TIMEOUT_MS = 60_000;
|
|
2540
|
-
const PROGRESS_LINES_MAX = 10;
|
|
2541
|
-
export async function createDraftPr(input) {
|
|
2542
|
-
const { run } = input;
|
|
2543
|
-
const worktree = run.worktreePath;
|
|
2544
|
-
const branch = run.branch;
|
|
2545
|
-
if (!worktree || !branch) {
|
|
2546
|
-
return { ok: false, error: 'this task has no worktree/branch to publish' };
|
|
2547
|
-
}
|
|
2548
|
-
// Final autosave: the branch must hold everything before it leaves the box.
|
|
2549
|
-
// This is the LAST flush — unlike the turn-end and run-finalize ones there is
|
|
2550
|
-
// no later autosave to pick the work up, so a refusal (conflicted tree) or a
|
|
2551
|
-
// failed commit has to stop the publish instead of silently opening a PR from
|
|
2552
|
-
// a branch that is missing the run's final state.
|
|
2553
|
-
const saved = await autosaveCommit(worktree, 'pre-PR');
|
|
2554
|
-
if (saved === 'refused') {
|
|
2555
|
-
return {
|
|
2556
|
-
ok: false,
|
|
2557
|
-
error: 'worktree has unresolved merge conflicts — resolve them, then publish again',
|
|
2558
|
-
};
|
|
2559
|
-
}
|
|
2560
|
-
if (saved === 'failed') {
|
|
2561
|
-
return { ok: false, error: 'could not commit the final changes — check git status in the worktree' };
|
|
2562
|
-
}
|
|
2563
|
-
// DRY-RUN (CEZ_DRY_RUN=1): no push, no gh — simulate success with a fake PR
|
|
2564
|
-
// URL so the whole review → PR flow is testable without GitHub.
|
|
2565
|
-
if (process.env.CEZ_DRY_RUN === '1') {
|
|
2566
|
-
return { ok: true, url: 'https://github.com/open-mercato/demo/pull/777', dryRun: true };
|
|
2567
|
-
}
|
|
2568
|
-
const remote = await execTool(['remote', 'get-url', 'origin'], worktree, 'git');
|
|
2569
|
-
if (!remote.ok || !remote.stdout.trim()) {
|
|
2570
|
-
return { ok: false, error: 'no git remote — add one (git remote add origin <url>) or merge the branch locally' };
|
|
2571
|
-
}
|
|
2572
|
-
const push = await execTool(['push', '-u', 'origin', branch], worktree, 'git', PUSH_TIMEOUT_MS);
|
|
2573
|
-
if (!push.ok) {
|
|
2574
|
-
return { ok: false, error: `git push failed — ${tail(push.stderr) || 'unknown error'}` };
|
|
2575
|
-
}
|
|
2576
|
-
const body = buildPrBody(input.handoffText, run.task);
|
|
2577
|
-
// Target the branch the worktree forked from (config `baseBranch`) — without
|
|
2578
|
-
// --base, gh aims at the repo default (main) even when work started on
|
|
2579
|
-
// develop. `origin/x` normalizes to `x`; a raw sha (detached-HEAD fork
|
|
2580
|
-
// point) can't be a PR base, so gh falls back to the default branch.
|
|
2581
|
-
const prBase = run.baseBranch?.replace(/^origin\//, '');
|
|
2582
|
-
const baseArgs = prBase && !/^[0-9a-f]{7,40}$/i.test(prBase) ? ['--base', prBase] : [];
|
|
2583
|
-
const pr = await execTool(['pr', 'create', '--draft', '--head', branch, ...baseArgs, '--title', run.title, '--body', body], worktree, 'gh', PUSH_TIMEOUT_MS);
|
|
2584
|
-
if (!pr.ok) {
|
|
2585
|
-
if (pr.notFound) {
|
|
2586
|
-
return { ok: false, error: 'gh not found — install the GitHub CLI and run `gh auth login`, or merge the branch locally' };
|
|
2587
|
-
}
|
|
2588
|
-
const hint = /auth|log ?in|credential/i.test(pr.stderr) ? ' (try `gh auth login`)' : '';
|
|
2589
|
-
return { ok: false, error: `gh pr create failed — ${tail(pr.stderr) || 'unknown error'}${hint}` };
|
|
2590
|
-
}
|
|
2591
|
-
// gh prints the PR URL on stdout; some versions echo it to stderr instead.
|
|
2592
|
-
const match = PR_URL_RE.exec(`${pr.stdout}\n${pr.stderr}`);
|
|
2593
|
-
if (!match) {
|
|
2594
|
-
return { ok: false, error: 'gh pr create returned no PR URL — check `gh pr list` manually' };
|
|
2595
|
-
}
|
|
2596
|
-
return { ok: true, url: match[0], dryRun: false };
|
|
2597
|
-
}
|
|
2598
|
-
/**
|
|
2599
|
-
* PR body from the handoff journal: the "## Goal" section (task text as
|
|
2600
|
-
* fallback) + the first ~10 lines of "## Progress log" (newest first) +
|
|
2601
|
-
* the cezar footer.
|
|
2602
|
-
*/
|
|
2603
|
-
export function buildPrBody(handoffText, task) {
|
|
2604
|
-
const goal = section(handoffText, '## Goal') || task.trim();
|
|
2605
|
-
const progress = section(handoffText, '## Progress log').split('\n').filter((l) => l.trim()).slice(0, PROGRESS_LINES_MAX).join('\n');
|
|
2606
|
-
const parts = ['## Goal', '', goal];
|
|
2607
|
-
if (progress)
|
|
2608
|
-
parts.push('', '## Progress log', '', progress);
|
|
2609
|
-
parts.push('', '---', '', '🤖 made with cezar');
|
|
2610
|
-
return parts.join('\n');
|
|
2611
|
-
}
|
|
2612
|
-
/** Text of one `## Header` section, up to the next `## ` header, with LF line endings. The header
|
|
2613
|
-
* is a whole line (hearsay-tools/cezarion#1147), so a Goal that quotes one is never taken for it. */
|
|
2614
|
-
function section(text, header) {
|
|
2615
|
-
const start = exactLineIndex(text, header);
|
|
2616
|
-
if (start < 0)
|
|
2617
|
-
return '';
|
|
2618
|
-
const rest = text.slice(nextLineIndex(text, start)).replaceAll('\r\n', '\n');
|
|
2619
|
-
const next = rest.indexOf('\n## ');
|
|
2620
|
-
return (next >= 0 ? rest.slice(0, next) : rest).trim();
|
|
2621
|
-
}
|
|
2622
|
-
/** Last 3 stderr lines, pipe-joined — enough context, toast-sized. */
|
|
2623
|
-
function tail(stderr) {
|
|
2624
|
-
return stderr.trim().split('\n').slice(-3).join(' | ').slice(0, 300);
|
|
2625
|
-
}
|
|
2626
|
-
function execTool(args, cwd, bin, timeoutMs = 30_000) {
|
|
2627
|
-
return new Promise((resolve) => {
|
|
2628
|
-
execFile(bin, args, {
|
|
2629
|
-
cwd,
|
|
2630
|
-
timeout: timeoutMs,
|
|
2631
|
-
maxBuffer: 4 * 1024 * 1024,
|
|
2632
|
-
encoding: 'utf8',
|
|
2633
|
-
// Nobody can answer a prompt here: git opens /dev/tty directly, so
|
|
2634
|
-
// piped stdio is not enough to stop it. Without this a `git push` that
|
|
2635
|
-
// cannot authenticate hangs for the whole timeout and surfaces as a
|
|
2636
|
-
// blank one-minute stall instead of git's own "could not read Username".
|
|
2637
|
-
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
2638
|
-
}, (err, stdout, stderr) => resolve({
|
|
2639
|
-
ok: !err,
|
|
2640
|
-
stdout: stdout ?? '',
|
|
2641
|
-
stderr: stderr ?? '',
|
|
2642
|
-
notFound: err?.code === 'ENOENT',
|
|
2643
|
-
}));
|
|
2644
|
-
});
|
|
2645
|
-
}
|
|
2646
|
-
// ---- the driver -------------------------------------------------------------
|
|
2647
|
-
/**
|
|
2648
|
-
* Cached availability probe so `GET /api/health` never pays a full listing. Keyed by repo root:
|
|
2649
|
-
* every registered project reads its own slot, so the boot project's constant health refresh can't
|
|
2650
|
-
* evict another project's answer (a single slot made `GET /automations` flap between "still being
|
|
2651
|
-
* checked" and available). One in-flight probe per root dedupes a burst of reads.
|
|
2652
|
-
*/
|
|
2653
|
-
const DETECT_CACHE_MAX = 64;
|
|
2654
|
-
const detectCache = new Map();
|
|
2655
|
-
const detectInflight = new Map();
|
|
2656
|
-
async function probeGithub(repoRoot) {
|
|
2657
|
-
let result;
|
|
2658
|
-
try {
|
|
2659
|
-
await gh(repoRoot, ['repo', 'view', '--json', 'nameWithOwner'], 5_000);
|
|
2660
|
-
result = { available: true };
|
|
2661
|
-
}
|
|
2662
|
-
catch (err) {
|
|
2663
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
2664
|
-
result = {
|
|
2665
|
-
available: false,
|
|
2666
|
-
reason: /ENOENT/.test(message)
|
|
2667
|
-
? 'gh CLI not found — install it and run `gh auth login`'
|
|
2668
|
-
: firstLine(message),
|
|
2669
|
-
};
|
|
2670
|
-
}
|
|
2671
|
-
detectCache.delete(repoRoot); // re-insert so Map order tracks recency
|
|
2672
|
-
detectCache.set(repoRoot, { at: Date.now(), result });
|
|
2673
|
-
while (detectCache.size > DETECT_CACHE_MAX) {
|
|
2674
|
-
const oldest = detectCache.keys().next().value;
|
|
2675
|
-
if (oldest === undefined)
|
|
2676
|
-
break;
|
|
2677
|
-
detectCache.delete(oldest);
|
|
2678
|
-
}
|
|
2679
|
-
return result;
|
|
2680
|
-
}
|
|
2681
|
-
async function detectGithub(repoRoot) {
|
|
2682
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
2683
|
-
return { available: true };
|
|
2684
|
-
const hit = detectCache.get(repoRoot);
|
|
2685
|
-
if (hit && Date.now() - hit.at < CACHE_MS)
|
|
2686
|
-
return hit.result;
|
|
2687
|
-
const pending = detectInflight.get(repoRoot);
|
|
2688
|
-
if (pending)
|
|
2689
|
-
return pending;
|
|
2690
|
-
const probe = probeGithub(repoRoot).finally(() => detectInflight.delete(repoRoot));
|
|
2691
|
-
detectInflight.set(repoRoot, probe);
|
|
2692
|
-
return probe;
|
|
2693
|
-
}
|
|
2694
|
-
/**
|
|
2695
|
-
* Non-blocking availability for `GET /api/health` (#major-health-latency): serves the last-known
|
|
2696
|
-
* probe immediately (stale-while-revalidate) and only returns `null` on a cold start, before the
|
|
2697
|
-
* first probe has ever warmed the cache. It NEVER shells out to `gh` on the request that reads it,
|
|
2698
|
-
* so health stays under the bookmarklet's 800 ms port budget (a `gh repo view` round-trip is
|
|
2699
|
-
* ~500–650 ms on its own). `null` is contract-safe — the whole `forge` field is additive, so
|
|
2700
|
-
* "unknown until warm" is a valid answer.
|
|
2701
|
-
*
|
|
2702
|
-
* Serving the stale value while revalidating is what keeps the GitHub nav item from flickering:
|
|
2703
|
-
* without it, every time the 60 s cache expired this returned `null` for one 5 s health poll,
|
|
2704
|
-
* dropping `forge.available` and blinking the sidebar item out until the background probe warmed.
|
|
2705
|
-
*/
|
|
2706
|
-
export function detectGithubCached(repoRoot) {
|
|
2707
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
2708
|
-
return { available: true };
|
|
2709
|
-
const hit = detectCache.get(repoRoot);
|
|
2710
|
-
const cached = hit?.result ?? null;
|
|
2711
|
-
const fresh = hit !== undefined && Date.now() - hit.at < CACHE_MS;
|
|
2712
|
-
if (!fresh) {
|
|
2713
|
-
void detectGithub(repoRoot).catch(() => { }); // revalidate off the request path
|
|
2714
|
-
}
|
|
2715
|
-
return cached; // last-known value while revalidating; null only until the first probe warms
|
|
2716
|
-
}
|
|
2717
|
-
const mergeStateCache = new Map();
|
|
2718
|
-
const mergeInflight = new Set();
|
|
2719
|
-
const MERGE_CACHE_MS = 15_000;
|
|
2720
|
-
function mergeCheckState(check) {
|
|
2721
|
-
const value = (check.conclusion || check.state || check.status || '').toUpperCase();
|
|
2722
|
-
if (['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(value))
|
|
2723
|
-
return 'passing';
|
|
2724
|
-
if (['FAILURE', 'ERROR', 'TIMED_OUT', 'ACTION_REQUIRED', 'CANCELLED'].includes(value))
|
|
2725
|
-
return 'failing';
|
|
2726
|
-
if (['PENDING', 'IN_PROGRESS', 'QUEUED', 'EXPECTED', 'WAITING', 'REQUESTED'].includes(value))
|
|
2727
|
-
return 'pending';
|
|
2728
|
-
return 'unknown';
|
|
2729
|
-
}
|
|
2730
|
-
export function normalizeMergeState(raw, policyRaw, requirements = {
|
|
2731
|
-
readable: false,
|
|
2732
|
-
requiredChecks: [],
|
|
2733
|
-
}) {
|
|
2734
|
-
const pr = mergePrSchema.parse(raw);
|
|
2735
|
-
const policy = repoMergePolicySchema.parse(policyRaw);
|
|
2736
|
-
const state = pr.state.toUpperCase() === 'MERGED' ? 'merged' : pr.state.toUpperCase() === 'CLOSED' ? 'closed' : 'open';
|
|
2737
|
-
const mergeable = pr.mergeable?.toUpperCase() === 'MERGEABLE'
|
|
2738
|
-
? 'mergeable'
|
|
2739
|
-
: pr.mergeable?.toUpperCase() === 'CONFLICTING'
|
|
2740
|
-
? 'conflicting'
|
|
2741
|
-
: 'unknown';
|
|
2742
|
-
const reviewDecision = pr.reviewDecision?.toUpperCase() === 'APPROVED'
|
|
2743
|
-
? 'approved'
|
|
2744
|
-
: pr.reviewDecision?.toUpperCase() === 'CHANGES_REQUESTED'
|
|
2745
|
-
? 'changes-requested'
|
|
2746
|
-
: pr.reviewDecision?.toUpperCase() === 'REVIEW_REQUIRED'
|
|
2747
|
-
? 'review-required'
|
|
2748
|
-
: !pr.reviewDecision?.trim() && requirements.readable && requirements.requiredApprovingReviews === 0
|
|
2749
|
-
? 'not-required'
|
|
2750
|
-
: 'unknown';
|
|
2751
|
-
const checks = (pr.statusCheckRollup ?? []).map((check) => {
|
|
2752
|
-
const name = check.name ?? check.context ?? 'Check';
|
|
2753
|
-
const url = check.detailsUrl ?? check.targetUrl;
|
|
2754
|
-
return {
|
|
2755
|
-
name,
|
|
2756
|
-
state: mergeCheckState(check),
|
|
2757
|
-
required: requirements.readable ? requirements.requiredChecks.includes(name) : null,
|
|
2758
|
-
...(url?.startsWith('https://') || url?.startsWith('http://') ? { url } : {}),
|
|
2759
|
-
};
|
|
2760
|
-
});
|
|
2761
|
-
if (requirements.readable) {
|
|
2762
|
-
for (const name of requirements.requiredChecks) {
|
|
2763
|
-
if (!checks.some((check) => check.name === name))
|
|
2764
|
-
checks.push({ name, state: 'pending', required: true });
|
|
2765
|
-
}
|
|
2766
|
-
}
|
|
2767
|
-
const methods = [];
|
|
2768
|
-
const methodAllowed = (method) => requirements.allowedMergeMethods?.includes(method) ?? true;
|
|
2769
|
-
if (policy.allow_squash_merge && methodAllowed('squash'))
|
|
2770
|
-
methods.push('squash');
|
|
2771
|
-
if (policy.allow_merge_commit && methodAllowed('merge'))
|
|
2772
|
-
methods.push('merge');
|
|
2773
|
-
if (policy.allow_rebase_merge && methodAllowed('rebase'))
|
|
2774
|
-
methods.push('rebase');
|
|
2775
|
-
const defaultMethod = policy.squash_merge_commit_title && methods.includes('squash')
|
|
2776
|
-
? 'squash'
|
|
2777
|
-
: policy.merge_commit_title && methods.includes('merge')
|
|
2778
|
-
? 'merge'
|
|
2779
|
-
: methods[0] ?? null;
|
|
2780
|
-
const blockers = [];
|
|
2781
|
-
let eligibility = 'ready';
|
|
2782
|
-
if (state !== 'open') {
|
|
2783
|
-
eligibility = 'terminal';
|
|
2784
|
-
blockers.push({ code: 'terminal', message: state === 'merged' ? 'This pull request is merged.' : 'This pull request is closed.' });
|
|
2785
|
-
}
|
|
2786
|
-
else if (pr.isDraft) {
|
|
2787
|
-
eligibility = 'blocked';
|
|
2788
|
-
blockers.push({ code: 'draft', message: 'Mark the pull request ready for review before merging.' });
|
|
2789
|
-
}
|
|
2790
|
-
else if (mergeable === 'conflicting') {
|
|
2791
|
-
eligibility = 'blocked';
|
|
2792
|
-
blockers.push({ code: 'conflicts', message: 'Conflicts must be resolved before merging.' });
|
|
2793
|
-
}
|
|
2794
|
-
else if (checks.some((check) => check.state === 'failing')) {
|
|
2795
|
-
eligibility = 'blocked';
|
|
2796
|
-
blockers.push({ code: 'checks-failing', message: 'One or more checks are failing.' });
|
|
2797
|
-
}
|
|
2798
|
-
else if (reviewDecision === 'changes-requested' || reviewDecision === 'review-required') {
|
|
2799
|
-
eligibility = 'blocked';
|
|
2800
|
-
blockers.push({ code: 'reviews', message: reviewDecision === 'changes-requested' ? 'Changes were requested.' : 'A required review is missing.' });
|
|
2801
|
-
}
|
|
2802
|
-
else if ((requirements.unresolvedThreads ?? 0) > 0) {
|
|
2803
|
-
eligibility = 'blocked';
|
|
2804
|
-
blockers.push({ code: 'review-threads', message: 'Required review threads must be resolved before merging.' });
|
|
2805
|
-
}
|
|
2806
|
-
else if (reviewDecision === 'unknown' || !requirements.readable ||
|
|
2807
|
-
(requirements.requiresThreadResolution && requirements.unresolvedThreads == null) ||
|
|
2808
|
-
checks.some((check) => check.required === true && check.state === 'unknown')) {
|
|
2809
|
-
eligibility = 'unknown';
|
|
2810
|
-
blockers.push({
|
|
2811
|
-
code: 'rules-unknown',
|
|
2812
|
-
message: 'GitHub could not confirm review and branch-protection requirements.',
|
|
2813
|
-
});
|
|
2814
|
-
}
|
|
2815
|
-
else if (checks.some((check) => check.state === 'pending') || pr.mergeStateStatus?.toUpperCase() === 'UNSTABLE') {
|
|
2816
|
-
eligibility = 'pending';
|
|
2817
|
-
blockers.push({ code: 'pending', message: 'Checks or GitHub mergeability are still pending.' });
|
|
2818
|
-
// GitHub's aggregate still enforces other rules and required check provider identities.
|
|
2819
|
-
}
|
|
2820
|
-
else if (mergeable !== 'mergeable' ||
|
|
2821
|
-
!['CLEAN', 'HAS_HOOKS'].includes(pr.mergeStateStatus?.toUpperCase() ?? '') ||
|
|
2822
|
-
methods.length === 0) {
|
|
2823
|
-
eligibility = 'unknown';
|
|
2824
|
-
blockers.push({ code: 'unknown', message: 'GitHub could not confirm every merge requirement.' });
|
|
2825
|
-
}
|
|
2826
|
-
const canMerge = eligibility === 'ready';
|
|
2827
|
-
const canOverride = !canMerge &&
|
|
2828
|
-
state === 'open' &&
|
|
2829
|
-
!pr.isDraft &&
|
|
2830
|
-
mergeable !== 'conflicting' &&
|
|
2831
|
-
methods.length > 0;
|
|
2832
|
-
return {
|
|
2833
|
-
number: pr.number,
|
|
2834
|
-
title: pr.title,
|
|
2835
|
-
url: pr.url,
|
|
2836
|
-
state,
|
|
2837
|
-
isDraft: pr.isDraft,
|
|
2838
|
-
headRef: pr.headRefName,
|
|
2839
|
-
baseRef: pr.baseRefName,
|
|
2840
|
-
headSha: pr.headRefOid,
|
|
2841
|
-
mergeable,
|
|
2842
|
-
reviewDecision,
|
|
2843
|
-
checks,
|
|
2844
|
-
methods,
|
|
2845
|
-
defaultMethod,
|
|
2846
|
-
eligibility,
|
|
2847
|
-
blockers,
|
|
2848
|
-
canMerge,
|
|
2849
|
-
canOverride,
|
|
2850
|
-
};
|
|
2851
|
-
}
|
|
2852
|
-
async function fetchPrMergeState(repoRoot, repoRef, number, refresh = false) {
|
|
2853
|
-
if (process.env.CEZ_DRY_RUN === '1') {
|
|
2854
|
-
return {
|
|
2855
|
-
available: true,
|
|
2856
|
-
mergeState: normalizeMergeState({
|
|
2857
|
-
number,
|
|
2858
|
-
title: 'Dry-run pull request',
|
|
2859
|
-
url: `https://github.com/mock/repo/pull/${number}`,
|
|
2860
|
-
state: 'OPEN',
|
|
2861
|
-
isDraft: false,
|
|
2862
|
-
headRefName: 'feat/dry-run',
|
|
2863
|
-
baseRefName: 'main',
|
|
2864
|
-
headRefOid: '0123456789abcdef0123456789abcdef01234567',
|
|
2865
|
-
mergeable: 'MERGEABLE',
|
|
2866
|
-
mergeStateStatus: 'CLEAN',
|
|
2867
|
-
reviewDecision: 'APPROVED',
|
|
2868
|
-
statusCheckRollup: [{ name: 'test', conclusion: 'SUCCESS', detailsUrl: 'https://github.com/mock/repo/actions' }],
|
|
2869
|
-
}, { allow_merge_commit: true, allow_squash_merge: true, allow_rebase_merge: true }, { readable: true, requiredChecks: ['test'] }),
|
|
2870
|
-
};
|
|
2871
|
-
}
|
|
2872
|
-
if (!repoRef)
|
|
2873
|
-
return { available: false, reason: 'GitHub remote could not be resolved' };
|
|
2874
|
-
const key = `${repoRoot}:${number}`;
|
|
2875
|
-
const hit = mergeStateCache.get(key);
|
|
2876
|
-
if (!refresh && hit && Date.now() - hit.at < MERGE_CACHE_MS)
|
|
2877
|
-
return hit.value;
|
|
2878
|
-
try {
|
|
2879
|
-
const prOut = await gh(repoRoot, [
|
|
2880
|
-
'pr', 'view', String(number), '--json',
|
|
2881
|
-
'number,title,url,state,isDraft,headRefName,baseRefName,headRefOid,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,mergedAt',
|
|
2882
|
-
]);
|
|
2883
|
-
const parsedPr = mergePrSchema.parse(JSON.parse(prOut));
|
|
2884
|
-
if (!matchesGithubPullRequest({ ...repoRef, number }, parsedPr))
|
|
2885
|
-
return { available: false, reason: 'GitHub returned a different pull request.' };
|
|
2886
|
-
mergedPullRequestObservations.observe({ ...repoRef, number }, parsedPr);
|
|
2887
|
-
const [policyOut, requirements] = await Promise.all([
|
|
2888
|
-
gh(repoRoot, ['api', `repos/${repoRef.owner}/${repoRef.repo}`]),
|
|
2889
|
-
fetchGithubMergeRequirements((args) => gh(repoRoot, args), repoRef.owner, repoRef.repo, parsedPr.baseRefName, number),
|
|
2890
|
-
]);
|
|
2891
|
-
const value = {
|
|
2892
|
-
available: true,
|
|
2893
|
-
mergeState: normalizeMergeState(parsedPr, JSON.parse(policyOut), requirements),
|
|
2894
|
-
};
|
|
2895
|
-
mergeStateCache.set(key, { at: Date.now(), value });
|
|
2896
|
-
return value;
|
|
2897
|
-
}
|
|
2898
|
-
catch (error) {
|
|
2899
|
-
return { available: false, reason: firstLine(error instanceof Error ? error.message : String(error)) };
|
|
2900
|
-
}
|
|
2901
|
-
}
|
|
2902
|
-
export function evictGithubProjectCaches(repoRoot) {
|
|
2903
|
-
const contextKey = githubContext(repoRoot).key;
|
|
2904
|
-
listCache.forEach((entry, key) => {
|
|
2905
|
-
if (entry.contextKey === contextKey)
|
|
2906
|
-
dropListEntry(key);
|
|
2907
|
-
});
|
|
2908
|
-
repositoryProjectsCache.delete(contextKey);
|
|
2909
|
-
commentCountsCache.forEach((_value, key) => {
|
|
2910
|
-
if (key.startsWith(`${contextKey}\0`))
|
|
2911
|
-
commentCountsCache.delete(key);
|
|
2912
|
-
});
|
|
2913
|
-
mergeStateCache.forEach((_value, key) => {
|
|
2914
|
-
if (key.startsWith(`${repoRoot}:`))
|
|
2915
|
-
mergeStateCache.delete(key);
|
|
2916
|
-
});
|
|
2917
|
-
commentsCache.forEach((_value, key) => {
|
|
2918
|
-
if (key.startsWith(`${repoRoot}\0`))
|
|
2919
|
-
commentsCache.delete(key);
|
|
2920
|
-
});
|
|
2921
|
-
itemCache.forEach((_value, key) => {
|
|
2922
|
-
if (key.startsWith(`${repoRoot}\0`))
|
|
2923
|
-
itemCache.delete(key);
|
|
2924
|
-
});
|
|
2925
|
-
}
|
|
2926
|
-
async function mergePullRequest(repoRoot, repoRef, number, input) {
|
|
2927
|
-
const key = `${repoRoot}:${number}`;
|
|
2928
|
-
if (mergeInflight.has(key))
|
|
2929
|
-
return { merged: false, status: 409, error: 'A merge is already in progress.', code: 'concurrent' };
|
|
2930
|
-
mergeInflight.add(key);
|
|
2931
|
-
try {
|
|
2932
|
-
if (input.canProceed?.() === false)
|
|
2933
|
-
return { merged: false, status: 409, error: 'Automatic merging was cancelled.', code: 'cancelled' };
|
|
2934
|
-
const fresh = await fetchPrMergeState(repoRoot, repoRef, number, true);
|
|
2935
|
-
if (input.canProceed?.() === false)
|
|
2936
|
-
return { merged: false, status: 409, error: 'Automatic merging was cancelled.', code: 'cancelled' };
|
|
2937
|
-
if (!fresh.available)
|
|
2938
|
-
return { merged: false, status: 502, error: fresh.reason };
|
|
2939
|
-
const current = fresh.mergeState;
|
|
2940
|
-
if (current.headSha !== input.expectedHeadSha) {
|
|
2941
|
-
return { merged: false, status: 409, error: 'The pull request head changed. Review the new commits before merging.', code: 'stale-head', current };
|
|
2942
|
-
}
|
|
2943
|
-
if (input.expectedHeadRef !== undefined && current.headRef !== input.expectedHeadRef) {
|
|
2944
|
-
return { merged: false, status: 409, error: 'The pull request branch changed.', code: 'stale-branch', current };
|
|
2945
|
-
}
|
|
2946
|
-
if (input.requirePassingChecks && (current.checks.length === 0 || current.checks.some(check => check.state !== 'passing'))) {
|
|
2947
|
-
return { merged: false, status: 409, error: 'Automatic merging requires at least one check and every current-head check passing.', code: 'checks-not-passing', current };
|
|
2948
|
-
}
|
|
2949
|
-
if (!current.methods.includes(input.method)) {
|
|
2950
|
-
return { merged: false, status: 409, error: 'That merge method is no longer enabled.', code: 'disabled-method', current };
|
|
2951
|
-
}
|
|
2952
|
-
if (!mergePreflightAllowed(current, !input.requirePassingChecks && input.overrideRules)) {
|
|
2953
|
-
return { merged: false, status: 409, error: current.blockers[0]?.message ?? 'The pull request is not eligible to merge.', code: current.eligibility, current };
|
|
2954
|
-
}
|
|
2955
|
-
if (input.requirePassingChecks && process.env.CEZ_DRY_RUN !== '1') {
|
|
2956
|
-
if (!repoRef)
|
|
2957
|
-
return { merged: false, status: 404, error: 'GitHub repository not found.' };
|
|
2958
|
-
const active = parseActiveWorkflowRuns(await gh(repoRoot, activeWorkflowRunsArgs({
|
|
2959
|
-
repository: `${repoRef.owner}/${repoRef.repo}`, headSha: current.headSha,
|
|
2960
|
-
})));
|
|
2961
|
-
if (input.canProceed?.() === false)
|
|
2962
|
-
return { merged: false, status: 409, error: 'Automatic merging was cancelled.', code: 'cancelled' };
|
|
2963
|
-
if (active)
|
|
2964
|
-
return { merged: false, status: 409, error: 'Waiting for active CI workflows on the current PR head.', code: 'checks-active', current };
|
|
2965
|
-
}
|
|
2966
|
-
if (process.env.CEZ_DRY_RUN === '1') {
|
|
2967
|
-
evictGithubProjectCaches(repoRoot);
|
|
2968
|
-
return { merged: true, number, url: current.url, method: input.method, mergeCommitSha: 'abcdef0123456789abcdef0123456789abcdef01' };
|
|
2969
|
-
}
|
|
2970
|
-
if (!repoRef)
|
|
2971
|
-
return { merged: false, status: 404, error: 'GitHub repository not found.' };
|
|
2972
|
-
if (input.canProceed?.() === false)
|
|
2973
|
-
return { merged: false, status: 409, error: 'Automatic merging was cancelled.', code: 'cancelled' };
|
|
2974
|
-
const out = await gh(repoRoot, [
|
|
2975
|
-
'api', '--method', 'PUT', `repos/${repoRef.owner}/${repoRef.repo}/pulls/${number}/merge`,
|
|
2976
|
-
'-f', `merge_method=${input.method}`, '-f', `sha=${input.expectedHeadSha}`,
|
|
2977
|
-
]);
|
|
2978
|
-
// Once GitHub accepted the mutation, report its real outcome even if intent changed in flight.
|
|
2979
|
-
const result = ghMergeResultSchema.parse(JSON.parse(out));
|
|
2980
|
-
if (!result.merged)
|
|
2981
|
-
return { merged: false, status: 409, error: result.message ?? 'GitHub refused the merge.', code: 'github-blocked', current };
|
|
2982
|
-
evictGithubProjectCaches(repoRoot);
|
|
2983
|
-
return { merged: true, number, url: current.url, method: input.method, ...(result.sha ? { mergeCommitSha: result.sha } : {}) };
|
|
2984
|
-
}
|
|
2985
|
-
catch (error) {
|
|
2986
|
-
const message = firstLine(error instanceof Error ? error.message : String(error));
|
|
2987
|
-
const status = /403|permission|forbidden/i.test(message) ? 403 : /404|not found/i.test(message) ? 404 : 502;
|
|
2988
|
-
return { merged: false, status, error: status === 403 ? 'GitHub permission denied.' : status === 404 ? 'Pull request or repository not found.' : 'GitHub could not complete the merge.' };
|
|
2989
|
-
}
|
|
2990
|
-
finally {
|
|
2991
|
-
mergeInflight.delete(key);
|
|
2992
|
-
}
|
|
2993
|
-
}
|
|
2994
|
-
export function mergePreflightAllowed(current, overrideRules = false) {
|
|
2995
|
-
return current.canMerge || (overrideRules && current.canOverride);
|
|
2996
|
-
}
|
|
2997
|
-
/** gh has no compare-and-swap ready operation. Check ownership immediately before marking ready,
|
|
2998
|
-
* then refresh again; the later merge has its own head guard and GitHub's atomic SHA check. */
|
|
2999
|
-
async function readyPullRequest(repoRoot, repoRef, number, input) {
|
|
3000
|
-
if (!Number.isSafeInteger(number) || number < 1 || !/^[0-9a-f]{40}$/.test(input.expectedHeadSha) || !input.expectedHeadRef) {
|
|
3001
|
-
return { available: false, reason: 'A valid pull request, head SHA and task branch are required.' };
|
|
3002
|
-
}
|
|
3003
|
-
const key = `${repoRoot}:${number}`;
|
|
3004
|
-
if (mergeInflight.has(key))
|
|
3005
|
-
return { available: false, reason: 'A pull request mutation is already in progress.' };
|
|
3006
|
-
mergeInflight.add(key);
|
|
3007
|
-
try {
|
|
3008
|
-
if (input.canProceed?.() === false)
|
|
3009
|
-
return { available: false, reason: 'Marking the pull request ready was cancelled.' };
|
|
3010
|
-
const dryRun = process.env.CEZ_DRY_RUN === '1';
|
|
3011
|
-
if (!dryRun) {
|
|
3012
|
-
if (!repoRef)
|
|
3013
|
-
return { available: false, reason: 'GitHub remote could not be resolved' };
|
|
3014
|
-
const pr = mergePrSchema.pick({ number: true, url: true, state: true, isDraft: true, headRefName: true, headRefOid: true }).parse(JSON.parse(await gh(repoRoot, [
|
|
3015
|
-
'pr', 'view', String(number), '--json', 'number,url,state,isDraft,headRefName,headRefOid',
|
|
3016
|
-
])));
|
|
3017
|
-
if (input.canProceed?.() === false)
|
|
3018
|
-
return { available: false, reason: 'Marking the pull request ready was cancelled.' };
|
|
3019
|
-
if (!matchesGithubPullRequest({ ...repoRef, number }, pr))
|
|
3020
|
-
return { available: false, reason: 'GitHub returned a different pull request.' };
|
|
3021
|
-
if (pr.headRefOid !== input.expectedHeadSha)
|
|
3022
|
-
return { available: false, reason: 'The pull request head changed.' };
|
|
3023
|
-
if (pr.headRefName !== input.expectedHeadRef)
|
|
3024
|
-
return { available: false, reason: 'The pull request branch changed.' };
|
|
3025
|
-
if (pr.state !== 'OPEN')
|
|
3026
|
-
return { available: false, reason: 'The pull request is no longer open.' };
|
|
3027
|
-
if (pr.isDraft) {
|
|
3028
|
-
if (input.canProceed?.() === false)
|
|
3029
|
-
return { available: false, reason: 'Marking the pull request ready was cancelled.' };
|
|
3030
|
-
await gh(repoRoot, ['pr', 'ready', String(number), '--repo', `github.com/${repoRef.owner}/${repoRef.repo}`]);
|
|
3031
|
-
evictGithubProjectCaches(repoRoot);
|
|
3032
|
-
if (input.canProceed?.() === false)
|
|
3033
|
-
return { available: false, reason: 'Marking the pull request ready was cancelled.' };
|
|
3034
|
-
}
|
|
3035
|
-
}
|
|
3036
|
-
const fresh = await fetchPrMergeState(repoRoot, repoRef, number, true);
|
|
3037
|
-
if (input.canProceed?.() === false)
|
|
3038
|
-
return { available: false, reason: 'Marking the pull request ready was cancelled.' };
|
|
3039
|
-
if (fresh.available && fresh.mergeState.headSha !== input.expectedHeadSha)
|
|
3040
|
-
return { available: false, reason: 'The pull request head changed.' };
|
|
3041
|
-
if (fresh.available && fresh.mergeState.headRef !== input.expectedHeadRef)
|
|
3042
|
-
return { available: false, reason: 'The pull request branch changed.' };
|
|
3043
|
-
return fresh;
|
|
3044
|
-
}
|
|
3045
|
-
catch {
|
|
3046
|
-
return { available: false, reason: 'GitHub could not mark the pull request ready for review.' };
|
|
3047
|
-
}
|
|
3048
|
-
finally {
|
|
3049
|
-
mergeInflight.delete(key);
|
|
3050
|
-
}
|
|
3051
|
-
}
|
|
3052
|
-
const GH_PR_STATES = {
|
|
3053
|
-
MERGED: 'merged',
|
|
3054
|
-
CLOSED: 'closed',
|
|
3055
|
-
};
|
|
3056
|
-
export function createGithubDriver(repoRoot, repoRef) {
|
|
3057
|
-
return {
|
|
3058
|
-
kind: 'github',
|
|
3059
|
-
detect: () => detectGithub(repoRoot),
|
|
3060
|
-
detectCached: () => detectGithubCached(repoRoot),
|
|
3061
|
-
listIssues: async (opts) => (await fetchGithub(repoRoot, opts?.refresh, opts?.limit, opts)).issues,
|
|
3062
|
-
listPRs: async (opts) => (await fetchGithub(repoRoot, opts?.refresh, opts?.limit, opts)).prs,
|
|
3063
|
-
// The open-only list tier's escape hatch (#730) — this is the only path that can reach a
|
|
3064
|
-
// closed or merged item.
|
|
3065
|
-
searchItems: (kind, query, opts) => searchGithubItems(repoRoot, kind, query, opts?.limit),
|
|
3066
|
-
viewItem: (kind, number) => viewGithubItem(repoRoot, kind, number),
|
|
3067
|
-
prDiff: (number, opts) => fetchGithubPrDiff(repoRoot, number, opts?.refresh),
|
|
3068
|
-
createPR: (input) => createDraftPr(input),
|
|
3069
|
-
// Null covers everything from "no PR yet" to "gh missing" — the callers
|
|
3070
|
-
// (Create PR → View PR flip) treat all of it as "nothing to link".
|
|
3071
|
-
prStatus: async (branch) => {
|
|
3072
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
3073
|
-
return null;
|
|
3074
|
-
try {
|
|
3075
|
-
const out = await gh(repoRoot, ['pr', 'view', branch, '--json', 'number,url,state,isDraft,statusCheckRollup,mergedAt']);
|
|
3076
|
-
const pr = ghPrViewSchema.parse(JSON.parse(out));
|
|
3077
|
-
if (repoRef)
|
|
3078
|
-
mergedPullRequestObservations.observe({ ...repoRef, number: pr.number }, pr);
|
|
3079
|
-
return {
|
|
3080
|
-
number: pr.number,
|
|
3081
|
-
url: pr.url,
|
|
3082
|
-
state: GH_PR_STATES[pr.state.toUpperCase()] ?? 'open',
|
|
3083
|
-
isDraft: pr.isDraft,
|
|
3084
|
-
checks: rollupToChecks(pr.statusCheckRollup) ?? null,
|
|
3085
|
-
};
|
|
3086
|
-
}
|
|
3087
|
-
catch {
|
|
3088
|
-
return null;
|
|
3089
|
-
}
|
|
3090
|
-
},
|
|
3091
|
-
prMergeState: (number, opts) => fetchPrMergeState(repoRoot, repoRef, number, opts?.refresh),
|
|
3092
|
-
readyPR: (number, input) => readyPullRequest(repoRoot, repoRef, number, input),
|
|
3093
|
-
mergePR: (number, input) => mergePullRequest(repoRoot, repoRef, number, input),
|
|
3094
|
-
viewUrl: (kind, ref) => {
|
|
3095
|
-
if (!repoRef)
|
|
3096
|
-
return null;
|
|
3097
|
-
const base = `https://github.com/${repoRef.owner}/${repoRef.repo}`;
|
|
3098
|
-
// Branch names may contain '/' — encode per segment, keep the slashes.
|
|
3099
|
-
const path = String(ref).split('/').map(encodeURIComponent).join('/');
|
|
3100
|
-
switch (kind) {
|
|
3101
|
-
case 'repo':
|
|
3102
|
-
return base;
|
|
3103
|
-
case 'issue':
|
|
3104
|
-
return `${base}/issues/${path}`;
|
|
3105
|
-
case 'pr':
|
|
3106
|
-
return `${base}/pull/${path}`;
|
|
3107
|
-
case 'branch':
|
|
3108
|
-
return `${base}/tree/${path}`;
|
|
3109
|
-
case 'commit':
|
|
3110
|
-
return `${base}/commit/${path}`;
|
|
3111
|
-
}
|
|
3112
|
-
},
|
|
3113
|
-
};
|
|
3114
|
-
}
|
|
3115
|
-
/** A missing alias must not poison unrelated families. Discard partial data and requery only
|
|
3116
|
-
* unaffected aliases once; archive authority still comes from an error-free response. */
|
|
3117
|
-
async function mergedPullRequestChunk(runGraphql, initial) {
|
|
3118
|
-
let chunk = initial;
|
|
3119
|
-
for (let attempt = 0; attempt < 2 && chunk.length; attempt++) {
|
|
3120
|
-
const query = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { nameWithOwner ${chunk.map(pr => `pr${pr.number}: pullRequest(number: ${pr.number}) { number url state mergedAt }`).join(' ')} } }`;
|
|
3121
|
-
let response;
|
|
3122
|
-
let failure;
|
|
3123
|
-
try {
|
|
3124
|
-
response = JSON.parse(await runGraphql(query, { owner: chunk[0].owner, name: chunk[0].repo }));
|
|
3125
|
-
}
|
|
3126
|
-
catch (error) {
|
|
3127
|
-
// gh exits 1 on GraphQL errors, with the structured envelope on stdout. Neither stderr
|
|
3128
|
-
// nor timeout/abort output is evidence that one particular alias was missing.
|
|
3129
|
-
const rejected = z.object({ code: z.literal(1), stdout: z.string() }).safeParse(error);
|
|
3130
|
-
if (!rejected.success)
|
|
3131
|
-
throw error;
|
|
3132
|
-
try {
|
|
3133
|
-
response = JSON.parse(rejected.data.stdout);
|
|
3134
|
-
}
|
|
3135
|
-
catch {
|
|
3136
|
-
throw error;
|
|
3137
|
-
}
|
|
3138
|
-
failure = error;
|
|
3139
|
-
}
|
|
3140
|
-
const partial = z.object({
|
|
3141
|
-
errors: z.array(z.object({ type: z.literal('NOT_FOUND'), path: z.tuple([z.literal('repository'), z.string()]) })).nonempty(),
|
|
3142
|
-
data: z.object({ repository: z.object({ nameWithOwner: z.string() }) }),
|
|
3143
|
-
}).safeParse(response);
|
|
3144
|
-
const aliases = new Set(chunk.map(pr => `pr${pr.number}`));
|
|
3145
|
-
if (attempt === 0 && partial.success &&
|
|
3146
|
-
partial.data.data.repository.nameWithOwner.toLowerCase() === `${chunk[0].owner}/${chunk[0].repo}`.toLowerCase() &&
|
|
3147
|
-
partial.data.errors.every(error => aliases.has(error.path[1]))) {
|
|
3148
|
-
const missing = new Set(partial.data.errors.map(error => error.path[1]));
|
|
3149
|
-
chunk = chunk.filter(pr => !missing.has(`pr${pr.number}`));
|
|
3150
|
-
continue;
|
|
3151
|
-
}
|
|
3152
|
-
if (failure)
|
|
3153
|
-
throw failure;
|
|
3154
|
-
return response;
|
|
3155
|
-
}
|
|
3156
|
-
return undefined;
|
|
3157
|
-
}
|
|
3158
|
-
/** Strict archive authority: no partial GraphQL success, redirects, guessed identity or date. */
|
|
3159
|
-
export async function fetchMergedPullRequests(runGraphql, identities) {
|
|
3160
|
-
const repositories = new Map();
|
|
3161
|
-
for (const identity of new Map(identities.map(pr => [pullRequestKey(pr), pr])).values()) {
|
|
3162
|
-
const key = `${identity.owner}/${identity.repo}`;
|
|
3163
|
-
repositories.set(key, [...(repositories.get(key) ?? []), identity]);
|
|
3164
|
-
}
|
|
3165
|
-
const merged = [];
|
|
3166
|
-
for (const [repository, prs] of repositories) {
|
|
3167
|
-
for (let offset = 0; offset < prs.length; offset += 25) {
|
|
3168
|
-
const chunk = prs.slice(offset, offset + 25);
|
|
3169
|
-
const response = await mergedPullRequestChunk(runGraphql, chunk);
|
|
3170
|
-
const parsed = z.object({ errors: z.array(z.unknown()).optional(), data: z.object({ repository: z.object({ nameWithOwner: z.string() }).passthrough().nullable() }) }).safeParse(response);
|
|
3171
|
-
if (!parsed.success || parsed.data.errors?.length || parsed.data.data.repository?.nameWithOwner.toLowerCase() !== repository.toLowerCase())
|
|
3172
|
-
continue;
|
|
3173
|
-
for (const pr of chunk) {
|
|
3174
|
-
const fact = mergedPullRequestObservations.observe(pr, parsed.data.data.repository[`pr${pr.number}`]);
|
|
3175
|
-
if (fact)
|
|
3176
|
-
merged.push(fact);
|
|
3177
|
-
}
|
|
3178
|
-
}
|
|
3179
|
-
}
|
|
3180
|
-
return merged;
|
|
3181
|
-
}
|
|
3182
|
-
export async function lookupMergedPullRequests(repoRoot, identities, signal) {
|
|
3183
|
-
signal.throwIfAborted();
|
|
3184
|
-
if (process.env.CEZ_DRY_RUN === '1')
|
|
3185
|
-
return [];
|
|
3186
|
-
const unique = [...new Map(identities.map(pr => [pullRequestKey(pr), pr])).values()];
|
|
3187
|
-
const known = unique.flatMap(pr => mergedPullRequestObservations.get(pr) ?? []);
|
|
3188
|
-
const missing = unique.filter(pr => !mergedPullRequestObservations.get(pr));
|
|
3189
|
-
if (missing.length === 0)
|
|
3190
|
-
return known;
|
|
3191
|
-
const context = githubContext(repoRoot);
|
|
3192
|
-
const fetched = await fetchMergedPullRequests(async (query, variables) => {
|
|
3193
|
-
const args = ['api', 'graphql', '--hostname', 'github.com', '-f', `query=${query}`];
|
|
3194
|
-
for (const [key, value] of Object.entries(variables))
|
|
3195
|
-
args.push('-f', `${key}=${value}`);
|
|
3196
|
-
return gh(repoRoot, args, 15_000, signal, context);
|
|
3197
|
-
}, missing);
|
|
3198
|
-
return [...known, ...fetched];
|
|
3199
|
-
}
|
|
3200
|
-
//# sourceMappingURL=github.js.map
|