headlesscode 1.0.2
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/ATTRIBUTION.md +53 -0
- package/CODE_OF_CONDUCT.md +130 -0
- package/CONTRIBUTING.md +107 -0
- package/LICENSE +202 -0
- package/README.md +486 -0
- package/SECURITY.md +211 -0
- package/bin/headlesscode.mjs +83 -0
- package/package.json +63 -0
- package/shared/prompts/review-mode-prompt-short.md +93 -0
- package/shared/prompts/review-mode-prompt.md +281 -0
- package/shared/rules-code/rules.md +22 -0
- package/shared/stacks/cpp/rules.md +30 -0
- package/shared/stacks/fastapi/rules.md +30 -0
- package/shared/stacks/javascript/rules.md +37 -0
- package/shared/stacks/postgresql/rules.md +31 -0
- package/shared/stacks/python/rules.md +35 -0
- package/shared/stacks/react/rules.md +11 -0
- package/shared/stacks/typescript/rules.md +10 -0
- package/src/budget/budget.ts +221 -0
- package/src/budget/concurrency.ts +126 -0
- package/src/budget/cost.ts +309 -0
- package/src/budget/index.ts +8 -0
- package/src/checkpoints/cli.ts +256 -0
- package/src/checkpoints/service.ts +227 -0
- package/src/cli.ts +1535 -0
- package/src/cloud/docker-provider.ts +334 -0
- package/src/cloud/provider.ts +300 -0
- package/src/codeintel/call-graph.ts +78 -0
- package/src/codeintel/find-references.ts +123 -0
- package/src/codeintel/go-to-definition.ts +193 -0
- package/src/codeintel/handlers.ts +190 -0
- package/src/codeintel/import-graph.ts +173 -0
- package/src/codeintel/outline.ts +180 -0
- package/src/codeintel/position.ts +77 -0
- package/src/codeintel/program.ts +350 -0
- package/src/codeintel/rename-symbol.ts +213 -0
- package/src/codeintel/tools.ts +280 -0
- package/src/codemap/build.ts +135 -0
- package/src/codemap/cli.ts +190 -0
- package/src/codemap/extract.ts +339 -0
- package/src/codemap/files.ts +236 -0
- package/src/codemap/fingerprint.ts +65 -0
- package/src/codemap/flows.ts +62 -0
- package/src/codemap/html.ts +451 -0
- package/src/codemap/lock.ts +80 -0
- package/src/codemap/types.ts +101 -0
- package/src/codesearch/airunner-embedder.ts +185 -0
- package/src/codesearch/chunk.ts +339 -0
- package/src/codesearch/cli.ts +223 -0
- package/src/codesearch/embedder.ts +332 -0
- package/src/codesearch/files.ts +280 -0
- package/src/codesearch/index.ts +469 -0
- package/src/codesearch/ollama-embedder.ts +205 -0
- package/src/codesearch/search.ts +141 -0
- package/src/codesearch/types.ts +100 -0
- package/src/config/mode-models.ts +218 -0
- package/src/dashboard/aggregate.ts +364 -0
- package/src/dashboard/chat-thread.ts +141 -0
- package/src/dashboard/checkpoints.ts +124 -0
- package/src/dashboard/cli.ts +193 -0
- package/src/dashboard/codemap.ts +44 -0
- package/src/dashboard/files.ts +121 -0
- package/src/dashboard/page.ts +2803 -0
- package/src/dashboard/self-improvement-metrics.ts +282 -0
- package/src/dashboard/server.ts +1103 -0
- package/src/dashboard/session-launch.ts +310 -0
- package/src/dashboard/timeline.ts +273 -0
- package/src/dashboard/tool-exec.ts +107 -0
- package/src/dashboard/trend-cli.ts +141 -0
- package/src/dashboard/trend.ts +413 -0
- package/src/decision-proxy/cli.ts +261 -0
- package/src/decision-proxy/proxy.ts +569 -0
- package/src/deploy/gate-cli.ts +147 -0
- package/src/deploy/gate.ts +254 -0
- package/src/engine/condense.ts +512 -0
- package/src/engine/events.ts +428 -0
- package/src/engine/handoff.ts +71 -0
- package/src/engine/lazy-tools.ts +160 -0
- package/src/engine/local-explore.ts +653 -0
- package/src/engine/logger.ts +96 -0
- package/src/engine/loop.ts +5517 -0
- package/src/engine/parser.ts +347 -0
- package/src/engine/prompt.ts +860 -0
- package/src/engine/reports.ts +47 -0
- package/src/engine/stacks.ts +448 -0
- package/src/engine/types.ts +291 -0
- package/src/engine/usage.ts +186 -0
- package/src/github/app-auth.ts +161 -0
- package/src/github/cli.ts +448 -0
- package/src/github/installations.ts +133 -0
- package/src/github/pr.ts +321 -0
- package/src/github/provision.ts +118 -0
- package/src/github/push.ts +122 -0
- package/src/index-util.ts +50 -0
- package/src/index.ts +81 -0
- package/src/init/cli.ts +248 -0
- package/src/init/gitignore.ts +74 -0
- package/src/llm/ollama.ts +308 -0
- package/src/llm/openrouter.ts +868 -0
- package/src/llm/preflight.ts +367 -0
- package/src/llm/transcript-capture.ts +84 -0
- package/src/memory/embed.ts +110 -0
- package/src/memory/index.ts +22 -0
- package/src/memory/local.ts +259 -0
- package/src/memory/summarizer.ts +283 -0
- package/src/memory/types.ts +153 -0
- package/src/memory/uwuchat.ts +157 -0
- package/src/migrate/cli.ts +115 -0
- package/src/orchestrator/analyze-cli.ts +104 -0
- package/src/orchestrator/auto-split.ts +206 -0
- package/src/orchestrator/cleanup.ts +1003 -0
- package/src/orchestrator/cli.ts +3571 -0
- package/src/orchestrator/cost-estimate.ts +564 -0
- package/src/orchestrator/cost-history-cli.ts +242 -0
- package/src/orchestrator/cost-history.ts +397 -0
- package/src/orchestrator/git-sync.ts +250 -0
- package/src/orchestrator/index.ts +153 -0
- package/src/orchestrator/log-analysis.ts +0 -0
- package/src/orchestrator/merge-check.ts +108 -0
- package/src/orchestrator/pipeline.ts +411 -0
- package/src/orchestrator/resume.ts +1940 -0
- package/src/orchestrator/reviewer.ts +503 -0
- package/src/orchestrator/split.ts +296 -0
- package/src/orchestrator/state.ts +542 -0
- package/src/orchestrator/status.ts +697 -0
- package/src/orchestrator/verification-gate.ts +134 -0
- package/src/orchestrator/watch.ts +898 -0
- package/src/permissions/commands.ts +1083 -0
- package/src/permissions/config.ts +241 -0
- package/src/permissions/index.ts +12 -0
- package/src/permissions/protected-files.ts +96 -0
- package/src/permissions/store-protection.ts +272 -0
- package/src/project-store.ts +648 -0
- package/src/projects/cli.ts +382 -0
- package/src/qa/qa.ts +487 -0
- package/src/tools/browser/handler.ts +346 -0
- package/src/tools/browser/service.ts +406 -0
- package/src/tools/browser/smoke.ts +78 -0
- package/src/tools/browser/tool.ts +99 -0
- package/src/tools/executor.ts +2575 -0
- package/src/tools/language-detect.ts +183 -0
- package/src/tools/output-summarizer.ts +369 -0
- package/src/tools/run-tests.ts +302 -0
- package/src/tools/set-indentation-tool.ts +49 -0
- package/src/tools/test-selection.ts +160 -0
- package/src/vendor/tests/smoke.ts +103 -0
- package/src/vendor/zoo-code/VENDOR-NOTES.md +213 -0
- package/src/vendor/zoo-code/shim/anthropic.ts +71 -0
- package/src/vendor/zoo-code/shim/openai.d.ts +60 -0
- package/src/vendor/zoo-code/shim/os-name.ts +18 -0
- package/src/vendor/zoo-code/shim/strip-bom.ts +14 -0
- package/src/vendor/zoo-code/shim/vscode.ts +76 -0
- package/src/vendor/zoo-code/src/core/config/CustomModesManager.ts +1015 -0
- package/src/vendor/zoo-code/src/core/diff/strategies/multi-search-replace.ts +670 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/capabilities.ts +46 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/custom-instructions.ts +559 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/index.ts +10 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/markdown-formatting.ts +7 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/modes.ts +35 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/objective.ts +13 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/rules.ts +95 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/skills.ts +105 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/system-info.ts +30 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/tool-use-guidelines.ts +9 -0
- package/src/vendor/zoo-code/src/core/prompts/sections/tool-use.ts +7 -0
- package/src/vendor/zoo-code/src/core/prompts/system.ts +176 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/access_mcp_resource.ts +41 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/apply_diff.ts +40 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/apply_patch.ts +61 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/ask_followup_question.ts +62 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/attempt_completion.ts +33 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/codebase_search.ts +43 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/converters.ts +109 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/edit.ts +48 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/edit_file.ts +72 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/execute_command.ts +54 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/generate_image.ts +51 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/index.ts +75 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/list_files.ts +41 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/mcp_server.ts +75 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/new_task.ts +39 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/read_command_output.ts +81 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/read_file.ts +169 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/run_slash_command.ts +31 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/search_files.ts +50 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/search_replace.ts +51 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/skill.ts +33 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/switch_mode.ts +31 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/update_todo_list.ts +54 -0
- package/src/vendor/zoo-code/src/core/prompts/tools/native-tools/write_to_file.ts +40 -0
- package/src/vendor/zoo-code/src/core/prompts/types.ts +12 -0
- package/src/vendor/zoo-code/src/i18n/index.ts +19 -0
- package/src/vendor/zoo-code/src/integrations/misc/extract-text.ts +81 -0
- package/src/vendor/zoo-code/src/services/checkpoints/RepoPerTaskCheckpointService.ts +15 -0
- package/src/vendor/zoo-code/src/services/checkpoints/ShadowCheckpointService.ts +553 -0
- package/src/vendor/zoo-code/src/services/checkpoints/excludes.ts +212 -0
- package/src/vendor/zoo-code/src/services/checkpoints/index.ts +3 -0
- package/src/vendor/zoo-code/src/services/checkpoints/types.ts +35 -0
- package/src/vendor/zoo-code/src/services/code-index/manager.ts +19 -0
- package/src/vendor/zoo-code/src/services/mcp/McpHub.ts +36 -0
- package/src/vendor/zoo-code/src/services/roo-config/index.ts +441 -0
- package/src/vendor/zoo-code/src/services/search/file-search.ts +143 -0
- package/src/vendor/zoo-code/src/services/skills/SkillsManager.ts +20 -0
- package/src/vendor/zoo-code/src/shared/globalFileNames.ts +9 -0
- package/src/vendor/zoo-code/src/shared/language.ts +43 -0
- package/src/vendor/zoo-code/src/shared/modes.ts +257 -0
- package/src/vendor/zoo-code/src/shared/tools.ts +385 -0
- package/src/vendor/zoo-code/src/utils/fs.ts +39 -0
- package/src/vendor/zoo-code/src/utils/globalContext.ts +22 -0
- package/src/vendor/zoo-code/src/utils/json-schema.ts +16 -0
- package/src/vendor/zoo-code/src/utils/logging.ts +21 -0
- package/src/vendor/zoo-code/src/utils/mcp-name.ts +190 -0
- package/src/vendor/zoo-code/src/utils/object.ts +18 -0
- package/src/vendor/zoo-code/src/utils/path.ts +94 -0
- package/src/vendor/zoo-code/src/utils/shell.ts +376 -0
- package/src/vendor/zoo-code/src/utils/text-normalization.ts +99 -0
- package/src/vendor/zoo-code/types/global-settings.ts +19 -0
- package/src/vendor/zoo-code/types/index.ts +22 -0
- package/src/vendor/zoo-code/types/message.ts +375 -0
- package/src/vendor/zoo-code/types/mode.ts +241 -0
- package/src/vendor/zoo-code/types/todo.ts +19 -0
- package/src/vendor/zoo-code/types/tool-params.ts +116 -0
- package/src/vendor/zoo-code/types/tool.ts +67 -0
- package/src/vendor/zoo-code/types/vscode.ts +84 -0
- package/src/vision/describe.ts +242 -0
- package/src/vision/tool.ts +91 -0
- package/src/watcher/cli.ts +369 -0
- package/src/watcher/github.ts +304 -0
- package/src/watcher/index.ts +59 -0
- package/src/watcher/state.ts +254 -0
- package/src/watcher/watch.ts +562 -0
- package/tsconfig.json +18 -0
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `headlesscode watch` subcommand — Phase 5 GitHub issue watcher.
|
|
3
|
+
*
|
|
4
|
+
* npx tsx src/cli.ts watch --owner <o> --repo <local-clone-path> --label <target-label> \
|
|
5
|
+
* [--gh-repo <name>] [--poll-interval-ms <n>] [--run-once] [--max-per-sweep <n>] \
|
|
6
|
+
* [--state-file <path>] [--mode <slug>] [--qa] [--deploy] [--memory-dir <path>] \
|
|
7
|
+
* [--dry-run] [--retry-failed]
|
|
8
|
+
*
|
|
9
|
+
* Thin dispatch to src/watcher/watch.ts — no logic duplicated here. The
|
|
10
|
+
* GitHub repo name defaults to the basename of `--repo` (the local clone),
|
|
11
|
+
* which is the common case; override with `--gh-repo` when the directory
|
|
12
|
+
* name differs.
|
|
13
|
+
*
|
|
14
|
+
* `--dry-run` sweeps + reports what would be spawned (list issues + split
|
|
15
|
+
* plan per issue) WITHOUT spawning or writing state. It still needs a GitHub
|
|
16
|
+
* token for listIssues — a missing token is a clear error.
|
|
17
|
+
*
|
|
18
|
+
* `--run-once` performs one sweep and exits 0 (or 1 if any spawn failed) —
|
|
19
|
+
* the cron/CI-friendly form. Continuous mode (default) logs each sweep and
|
|
20
|
+
* runs until SIGINT/SIGTERM (clean shutdown via AbortSignal; state saved).
|
|
21
|
+
*
|
|
22
|
+
* Pass-through (recorded per batch / forwarded to the spawner): --mode and
|
|
23
|
+
* --memory-dir reach the spawner env (ORCHESTRATOR_MODE /
|
|
24
|
+
* HEADLESSCODE_MEMORY_DIR); --qa and --deploy are stored on the batch's
|
|
25
|
+
* state entry for the follow-up `orchestrate` completion run (see
|
|
26
|
+
* docs/phase5-issue-watcher.md — the watcher itself only spawns; completion
|
|
27
|
+
* watching / review / QA / deploy stays the orchestrator's job).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { execFileSync } from "node:child_process"
|
|
31
|
+
import * as path from "node:path"
|
|
32
|
+
|
|
33
|
+
import { Logger } from "../engine/logger.js"
|
|
34
|
+
import { watchIssues, type SweepResult } from "./watch.js"
|
|
35
|
+
|
|
36
|
+
const WATCH_USAGE = `headlesscode watch — Phase 5 GitHub issue watcher
|
|
37
|
+
|
|
38
|
+
Usage:
|
|
39
|
+
headlesscode watch --owner <o> --repo <path> --label <target-label> [options]
|
|
40
|
+
|
|
41
|
+
Options:
|
|
42
|
+
--owner <o> GitHub owner (required)
|
|
43
|
+
--repo <path> Local clone of the target repo (required; worktrees
|
|
44
|
+
are spawned under <path>/.worktrees/). The GitHub
|
|
45
|
+
repo name defaults to the directory basename.
|
|
46
|
+
--gh-repo <name> GitHub repo name override (default: basename of --repo)
|
|
47
|
+
--label <name> The label that triggers processing, e.g. needs-agent
|
|
48
|
+
--poll-interval-ms <n> Sweep interval in continuous mode (default: 60000)
|
|
49
|
+
--run-once One sweep then exit 0 (or 1 if any spawn failed);
|
|
50
|
+
the cron/CI form of the watcher
|
|
51
|
+
--max-per-sweep <n> Max NEW issues spawned per sweep (default: 5); the
|
|
52
|
+
rest stay in state as 'pending' and are picked up
|
|
53
|
+
next sweep (bounds label storms)
|
|
54
|
+
--max-concurrent-sessions <n> Phase 6 GLOBAL cap on concurrent sessions
|
|
55
|
+
across processes (default: $HEADLESSCODE_MAX_
|
|
56
|
+
CONCURRENT_SESSIONS or 3). Interplay: maxPerSweep
|
|
57
|
+
bounds one sweep's burst; this bounds the total
|
|
58
|
+
running/spawned fleet — issues beyond it stay
|
|
59
|
+
'pending' until slots free up
|
|
60
|
+
--state-file <path> Durable idempotency state (default:
|
|
61
|
+
<repo>/.worktrees/.watcher-state.json)
|
|
62
|
+
--mode <slug> Harness mode for workers (default: code; forwarded
|
|
63
|
+
to the spawner as ORCHESTRATOR_MODE)
|
|
64
|
+
--qa Pass-through: record that a QA round should follow
|
|
65
|
+
each batch (see docs/phase5-issue-watcher.md)
|
|
66
|
+
--deploy Pass-through: record that a deploy gate should follow
|
|
67
|
+
each batch (see docs/phase5-issue-watcher.md)
|
|
68
|
+
--memory-dir <path> Memory dir for workers (forwarded to the spawner as
|
|
69
|
+
HEADLESSCODE_MEMORY_DIR)
|
|
70
|
+
--dry-run Sweep + print the spawn plan per new issue, spawn
|
|
71
|
+
nothing, write no state (still needs a GH token)
|
|
72
|
+
--retry-failed Retry previously-failed spawns on the next sweep
|
|
73
|
+
(default: failed entries are NOT auto-retried)
|
|
74
|
+
--help Show this help and exit
|
|
75
|
+
|
|
76
|
+
Environment:
|
|
77
|
+
GH_TOKEN GitHub token (or GITHUB_TOKEN) — required; never logged
|
|
78
|
+
GITHUB_API_BASE_URL API base URL override (tests/mocks)
|
|
79
|
+
HEADLESSCODE_SPAWN_SCRIPT Override the spawner script path (e2e stubbing)
|
|
80
|
+
HEADLESSCODE_MAX_CONCURRENT_SESSIONS Global concurrency cap (default 3)
|
|
81
|
+
`
|
|
82
|
+
|
|
83
|
+
export interface WatchCliOptions {
|
|
84
|
+
owner: string
|
|
85
|
+
repo: string
|
|
86
|
+
ghRepo?: string
|
|
87
|
+
label: string
|
|
88
|
+
pollIntervalMs: number
|
|
89
|
+
runOnce: boolean
|
|
90
|
+
maxPerSweep: number
|
|
91
|
+
/** Phase 6: global concurrent-session cap (default env or 3). */
|
|
92
|
+
maxConcurrentSessions: number
|
|
93
|
+
stateFile?: string
|
|
94
|
+
mode: string
|
|
95
|
+
qa: boolean
|
|
96
|
+
deploy: boolean
|
|
97
|
+
memoryDir?: string
|
|
98
|
+
dryRun: boolean
|
|
99
|
+
retryFailed: boolean
|
|
100
|
+
help: boolean
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function parseWatchArgs(argv: string[]): { options: WatchCliOptions; error?: string } {
|
|
104
|
+
const options: WatchCliOptions = {
|
|
105
|
+
owner: "",
|
|
106
|
+
repo: "",
|
|
107
|
+
label: "",
|
|
108
|
+
pollIntervalMs: 60_000,
|
|
109
|
+
runOnce: false,
|
|
110
|
+
maxPerSweep: 5,
|
|
111
|
+
maxConcurrentSessions: 3,
|
|
112
|
+
mode: "code",
|
|
113
|
+
qa: false,
|
|
114
|
+
deploy: false,
|
|
115
|
+
dryRun: false,
|
|
116
|
+
retryFailed: false,
|
|
117
|
+
help: false,
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (let i = 0; i < argv.length; i++) {
|
|
121
|
+
const arg = argv[i]
|
|
122
|
+
const eq = arg.indexOf("=")
|
|
123
|
+
const flag = eq === -1 ? arg : arg.slice(0, eq)
|
|
124
|
+
const inlineValue = eq === -1 ? undefined : arg.slice(eq + 1)
|
|
125
|
+
const next = (): string | undefined => {
|
|
126
|
+
if (inlineValue !== undefined) {
|
|
127
|
+
return inlineValue
|
|
128
|
+
}
|
|
129
|
+
const v = argv[i + 1]
|
|
130
|
+
if (v === undefined || v.startsWith("--")) {
|
|
131
|
+
return undefined
|
|
132
|
+
}
|
|
133
|
+
i++
|
|
134
|
+
return v
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
switch (flag) {
|
|
138
|
+
case "--owner": {
|
|
139
|
+
const v = next()
|
|
140
|
+
if (v === undefined) {
|
|
141
|
+
return { options, error: "Missing value for --owner" }
|
|
142
|
+
}
|
|
143
|
+
options.owner = v
|
|
144
|
+
break
|
|
145
|
+
}
|
|
146
|
+
case "--repo": {
|
|
147
|
+
const v = next()
|
|
148
|
+
if (v === undefined) {
|
|
149
|
+
return { options, error: "Missing value for --repo" }
|
|
150
|
+
}
|
|
151
|
+
options.repo = v
|
|
152
|
+
break
|
|
153
|
+
}
|
|
154
|
+
case "--gh-repo": {
|
|
155
|
+
const v = next()
|
|
156
|
+
if (v === undefined) {
|
|
157
|
+
return { options, error: "Missing value for --gh-repo" }
|
|
158
|
+
}
|
|
159
|
+
options.ghRepo = v
|
|
160
|
+
break
|
|
161
|
+
}
|
|
162
|
+
case "--label": {
|
|
163
|
+
const v = next()
|
|
164
|
+
if (v === undefined) {
|
|
165
|
+
return { options, error: "Missing value for --label" }
|
|
166
|
+
}
|
|
167
|
+
options.label = v
|
|
168
|
+
break
|
|
169
|
+
}
|
|
170
|
+
case "--poll-interval-ms": {
|
|
171
|
+
const v = next()
|
|
172
|
+
const n = v === undefined ? Number.NaN : Number(v)
|
|
173
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
174
|
+
return { options, error: "--poll-interval-ms requires a positive integer" }
|
|
175
|
+
}
|
|
176
|
+
options.pollIntervalMs = n
|
|
177
|
+
break
|
|
178
|
+
}
|
|
179
|
+
case "--max-per-sweep": {
|
|
180
|
+
const v = next()
|
|
181
|
+
const n = v === undefined ? Number.NaN : Number(v)
|
|
182
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
183
|
+
return { options, error: "--max-per-sweep requires a positive integer" }
|
|
184
|
+
}
|
|
185
|
+
options.maxPerSweep = n
|
|
186
|
+
break
|
|
187
|
+
}
|
|
188
|
+
case "--max-concurrent-sessions": {
|
|
189
|
+
const v = next()
|
|
190
|
+
const n = v === undefined ? Number.NaN : Number(v)
|
|
191
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
192
|
+
return { options, error: "--max-concurrent-sessions requires a positive integer" }
|
|
193
|
+
}
|
|
194
|
+
options.maxConcurrentSessions = n
|
|
195
|
+
break
|
|
196
|
+
}
|
|
197
|
+
case "--state-file": {
|
|
198
|
+
const v = next()
|
|
199
|
+
if (v === undefined) {
|
|
200
|
+
return { options, error: "Missing value for --state-file" }
|
|
201
|
+
}
|
|
202
|
+
options.stateFile = v
|
|
203
|
+
break
|
|
204
|
+
}
|
|
205
|
+
case "--mode": {
|
|
206
|
+
const v = next()
|
|
207
|
+
if (v === undefined) {
|
|
208
|
+
return { options, error: "Missing value for --mode" }
|
|
209
|
+
}
|
|
210
|
+
options.mode = v
|
|
211
|
+
break
|
|
212
|
+
}
|
|
213
|
+
case "--memory-dir": {
|
|
214
|
+
const v = next()
|
|
215
|
+
if (v === undefined) {
|
|
216
|
+
return { options, error: "Missing value for --memory-dir" }
|
|
217
|
+
}
|
|
218
|
+
options.memoryDir = v
|
|
219
|
+
break
|
|
220
|
+
}
|
|
221
|
+
case "--run-once":
|
|
222
|
+
options.runOnce = true
|
|
223
|
+
break
|
|
224
|
+
case "--qa":
|
|
225
|
+
options.qa = true
|
|
226
|
+
break
|
|
227
|
+
case "--deploy":
|
|
228
|
+
options.deploy = true
|
|
229
|
+
break
|
|
230
|
+
case "--dry-run":
|
|
231
|
+
options.dryRun = true
|
|
232
|
+
break
|
|
233
|
+
case "--retry-failed":
|
|
234
|
+
options.retryFailed = true
|
|
235
|
+
break
|
|
236
|
+
case "--help":
|
|
237
|
+
case "-h":
|
|
238
|
+
options.help = true
|
|
239
|
+
break
|
|
240
|
+
default:
|
|
241
|
+
return { options, error: `Unknown watch argument: ${arg}` }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
return { options }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Print the dry-run spawn plan for the sweeps that were simulated. */
|
|
249
|
+
function printDryRunPlan(sweeps: SweepResult[]): void {
|
|
250
|
+
process.stdout.write("── Watch plan (dry run) ────────────────────────────────────\n")
|
|
251
|
+
for (const sweep of sweeps) {
|
|
252
|
+
for (const plan of sweep.dryRunPlan ?? []) {
|
|
253
|
+
const { issue, specs } = plan
|
|
254
|
+
process.stdout.write(` issue #${issue.number}: ${issue.title}\n`)
|
|
255
|
+
for (const spec of specs) {
|
|
256
|
+
process.stdout.write(
|
|
257
|
+
` -> ${spec.name} issues [${spec.issues.join(", ")}] plans/parallel-tasks/${spec.taskFile}\n`,
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if ((sweep.dryRunPlan ?? []).length === 0) {
|
|
262
|
+
process.stdout.write(" (no new issues to spawn)\n")
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export async function watchMain(argv: string[]): Promise<number> {
|
|
268
|
+
const { options, error } = parseWatchArgs(argv)
|
|
269
|
+
if (error) {
|
|
270
|
+
process.stderr.write(`headlesscode watch: ${error}\n\n${WATCH_USAGE}`)
|
|
271
|
+
return 2
|
|
272
|
+
}
|
|
273
|
+
if (options.help) {
|
|
274
|
+
process.stdout.write(WATCH_USAGE)
|
|
275
|
+
return 0
|
|
276
|
+
}
|
|
277
|
+
if (!options.owner || !options.repo || !options.label) {
|
|
278
|
+
process.stderr.write(
|
|
279
|
+
`headlesscode watch: --owner <o>, --repo <path> and --label <name> are required\n\n${WATCH_USAGE}`,
|
|
280
|
+
)
|
|
281
|
+
return 2
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN
|
|
285
|
+
if (!token) {
|
|
286
|
+
process.stderr.write(
|
|
287
|
+
"headlesscode watch: no GitHub token. Set GH_TOKEN (or GITHUB_TOKEN) — the watcher\n" +
|
|
288
|
+
" needs it for listIssues, even with --dry-run. The token is never logged.\n",
|
|
289
|
+
)
|
|
290
|
+
return 2
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const repoRoot = path.resolve(options.repo)
|
|
294
|
+
// Dry-run never touches the repo, so git validation only applies to real runs.
|
|
295
|
+
if (!options.dryRun) {
|
|
296
|
+
try {
|
|
297
|
+
execFileSync("git", ["-C", repoRoot, "rev-parse", "--git-dir"], { stdio: "ignore", timeout: 5000 })
|
|
298
|
+
} catch {
|
|
299
|
+
process.stderr.write(`headlesscode watch: not a git repo: ${repoRoot}\n`)
|
|
300
|
+
return 2
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const ghRepo = options.ghRepo ?? path.basename(repoRoot)
|
|
305
|
+
const logger = new Logger({ level: "info" })
|
|
306
|
+
|
|
307
|
+
// Continuous mode: clean shutdown on SIGINT/SIGTERM (state saved by
|
|
308
|
+
// watchIssues before returning).
|
|
309
|
+
const controller = new AbortController()
|
|
310
|
+
const onSignal = (): void => controller.abort()
|
|
311
|
+
process.on("SIGINT", onSignal)
|
|
312
|
+
process.on("SIGTERM", onSignal)
|
|
313
|
+
|
|
314
|
+
let result
|
|
315
|
+
try {
|
|
316
|
+
result = await watchIssues({
|
|
317
|
+
owner: options.owner,
|
|
318
|
+
repo: ghRepo,
|
|
319
|
+
targetLabel: options.label,
|
|
320
|
+
token,
|
|
321
|
+
ghBaseUrl: process.env.GITHUB_API_BASE_URL,
|
|
322
|
+
stateFile: options.stateFile,
|
|
323
|
+
repoRoot,
|
|
324
|
+
pollIntervalMs: options.pollIntervalMs,
|
|
325
|
+
runOnce: options.runOnce,
|
|
326
|
+
maxPerSweep: options.maxPerSweep,
|
|
327
|
+
maxConcurrentSessions: options.maxConcurrentSessions,
|
|
328
|
+
retryFailed: options.retryFailed,
|
|
329
|
+
dryRun: options.dryRun,
|
|
330
|
+
mode: options.mode,
|
|
331
|
+
memoryDir: options.memoryDir,
|
|
332
|
+
qa: options.qa,
|
|
333
|
+
deploy: options.deploy,
|
|
334
|
+
logger,
|
|
335
|
+
signal: controller.signal,
|
|
336
|
+
})
|
|
337
|
+
} finally {
|
|
338
|
+
process.off("SIGINT", onSignal)
|
|
339
|
+
process.off("SIGTERM", onSignal)
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
for (const sweep of result.sweeps) {
|
|
343
|
+
if (sweep.error) {
|
|
344
|
+
process.stderr.write(`[watch] ${sweep.error}\n`)
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (options.dryRun) {
|
|
348
|
+
printDryRunPlan(result.sweeps)
|
|
349
|
+
} else {
|
|
350
|
+
for (const sweep of result.sweeps) {
|
|
351
|
+
process.stdout.write(
|
|
352
|
+
`[watch] sweep: ${sweep.issuesFound} found, ${sweep.newIssues} new, ${sweep.skipped} skipped, ` +
|
|
353
|
+
`${sweep.spawned} spawned, ${sweep.deferred} deferred, ${sweep.failures} failed\n`,
|
|
354
|
+
)
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (options.dryRun) {
|
|
359
|
+
return 0
|
|
360
|
+
}
|
|
361
|
+
if (result.exitCode !== 0) {
|
|
362
|
+
process.stderr.write(
|
|
363
|
+
`headlesscode watch: ${result.spawned} batch(es) spawned, but one or more sweeps reported errors\n`,
|
|
364
|
+
)
|
|
365
|
+
return 1
|
|
366
|
+
}
|
|
367
|
+
process.stdout.write(`[watch] done: ${result.spawned} batch(es) spawned\n`)
|
|
368
|
+
return 0
|
|
369
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 5 — minimal authenticated GitHub REST client for the issue watcher.
|
|
3
|
+
*
|
|
4
|
+
* Native `fetch` only (Node >= 18), no new dependencies. GET-only for the
|
|
5
|
+
* watcher's needs (list issues by label, fetch a single issue) plus an
|
|
6
|
+
* optional `addLabel` POST used by the label-marking idempotency strategy
|
|
7
|
+
* (see docs/phase5-issue-watcher.md — the default watcher uses the state
|
|
8
|
+
* file, but the label-marking option is documented and this function exists
|
|
9
|
+
* for it).
|
|
10
|
+
*
|
|
11
|
+
* Auth: `Authorization: Bearer <token>` from `GH_TOKEN` or `GITHUB_TOKEN`
|
|
12
|
+
* (the caller passes the token in; this module never reads the environment
|
|
13
|
+
* itself so tests can inject a fake token). The token is NEVER logged and
|
|
14
|
+
* never written to the watcher state file.
|
|
15
|
+
*
|
|
16
|
+
* Base URL override: `GITHUB_API_BASE_URL` env (or the `baseUrl` option)
|
|
17
|
+
* points the client at a mock server for tests/e2e. Default api.github.com.
|
|
18
|
+
*
|
|
19
|
+
* Errors: non-2xx -> typed `GhApiError` with HTTP status + message; network
|
|
20
|
+
* failures are wrapped in a plain Error.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_GH_BASE_URL = "https://api.github.com"
|
|
24
|
+
/** GitHub REST API version header (see https://docs.github.com/en/rest). */
|
|
25
|
+
export const GH_API_VERSION = "2022-11-28"
|
|
26
|
+
/** Page size for list endpoints (GitHub max is 100). */
|
|
27
|
+
export const ISSUES_PAGE_SIZE = 100
|
|
28
|
+
/** Hard cap on total issues fetched per listIssues call (bounds runtime). */
|
|
29
|
+
export const DEFAULT_MAX_ISSUES = 1000
|
|
30
|
+
|
|
31
|
+
/** Typed error for non-2xx GitHub API responses. */
|
|
32
|
+
export class GhApiError extends Error {
|
|
33
|
+
readonly status: number
|
|
34
|
+
readonly url: string
|
|
35
|
+
|
|
36
|
+
constructor(status: number, message: string, url: string) {
|
|
37
|
+
super(message)
|
|
38
|
+
this.name = "GhApiError"
|
|
39
|
+
this.status = status
|
|
40
|
+
this.url = url
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A normalized GitHub issue (PRs are filtered out by listIssues/getIssue). */
|
|
45
|
+
export interface GitHubIssue {
|
|
46
|
+
number: number
|
|
47
|
+
title: string
|
|
48
|
+
body?: string
|
|
49
|
+
/** Label names, e.g. ["needs-agent"]. */
|
|
50
|
+
labels: string[]
|
|
51
|
+
updated_at?: string
|
|
52
|
+
html_url?: string
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface GhRequestOptions {
|
|
56
|
+
token: string
|
|
57
|
+
/** API base URL (default: $GITHUB_API_BASE_URL or https://api.github.com). */
|
|
58
|
+
baseUrl?: string
|
|
59
|
+
method?: string
|
|
60
|
+
body?: unknown
|
|
61
|
+
/** Injectable fetch for tests (default: global fetch). */
|
|
62
|
+
fetchImpl?: typeof fetch
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Build a GitHub API URL from a base URL + API path + query params.
|
|
67
|
+
* Exported so tests can assert URL construction without a network.
|
|
68
|
+
*/
|
|
69
|
+
export function buildGhUrl(
|
|
70
|
+
baseUrl: string,
|
|
71
|
+
apiPath: string,
|
|
72
|
+
params?: Record<string, string | number | undefined>,
|
|
73
|
+
): string {
|
|
74
|
+
const cleanBase = baseUrl.replace(/\/+$/, "")
|
|
75
|
+
const pathPart = apiPath.startsWith("/") ? apiPath : `/${apiPath}`
|
|
76
|
+
const url = new URL(`${cleanBase}${pathPart}`)
|
|
77
|
+
if (params) {
|
|
78
|
+
for (const [key, value] of Object.entries(params)) {
|
|
79
|
+
if (value !== undefined && value !== "") {
|
|
80
|
+
url.searchParams.set(key, String(value))
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return url.toString()
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* One authenticated GitHub REST call. GET by default (plus POST for
|
|
89
|
+
* addLabel). Non-2xx -> GhApiError; network errors are wrapped.
|
|
90
|
+
*/
|
|
91
|
+
export async function ghApi(apiPath: string, options: GhRequestOptions): Promise<unknown> {
|
|
92
|
+
const {
|
|
93
|
+
token,
|
|
94
|
+
baseUrl = process.env.GITHUB_API_BASE_URL || DEFAULT_GH_BASE_URL,
|
|
95
|
+
method = "GET",
|
|
96
|
+
body,
|
|
97
|
+
fetchImpl = fetch,
|
|
98
|
+
} = options
|
|
99
|
+
if (!token) {
|
|
100
|
+
throw new Error("ghApi: no GitHub token provided (set GH_TOKEN or GITHUB_TOKEN)")
|
|
101
|
+
}
|
|
102
|
+
// apiPath may be a relative API path ("/repos/o/r/issues") OR a fully
|
|
103
|
+
// built URL (listIssues constructs the paginated URL itself) — pass
|
|
104
|
+
// absolute URLs through unchanged.
|
|
105
|
+
const url = /^https?:\/\//i.test(apiPath) ? apiPath : buildGhUrl(baseUrl, apiPath)
|
|
106
|
+
|
|
107
|
+
const headers: Record<string, string> = {
|
|
108
|
+
Accept: "application/vnd.github+json",
|
|
109
|
+
"X-GitHub-Api-Version": GH_API_VERSION,
|
|
110
|
+
Authorization: `Bearer ${token}`,
|
|
111
|
+
"User-Agent": "headlesscode-watcher",
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
let response: Response
|
|
115
|
+
try {
|
|
116
|
+
response = await fetchImpl(url, {
|
|
117
|
+
method,
|
|
118
|
+
headers,
|
|
119
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
120
|
+
})
|
|
121
|
+
} catch (err) {
|
|
122
|
+
throw new Error(
|
|
123
|
+
`GitHub API network error (${method} ${url}): ${err instanceof Error ? err.message : String(err)}`,
|
|
124
|
+
{ cause: err },
|
|
125
|
+
)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (!response.ok) {
|
|
129
|
+
let message = `GitHub API HTTP ${response.status} for ${method} ${url}`
|
|
130
|
+
try {
|
|
131
|
+
const payload = (await response.json()) as { message?: unknown }
|
|
132
|
+
if (typeof payload?.message === "string" && payload.message !== "") {
|
|
133
|
+
message = `${payload.message} (HTTP ${response.status})`
|
|
134
|
+
}
|
|
135
|
+
} catch {
|
|
136
|
+
// body is not JSON — keep the generic message
|
|
137
|
+
}
|
|
138
|
+
throw new GhApiError(response.status, message, url)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 204/empty bodies (rare for GETs; addLabel returns 200 with a body).
|
|
142
|
+
const text = await response.text()
|
|
143
|
+
if (text.trim() === "") {
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
return JSON.parse(text)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface ListIssuesOptions {
|
|
150
|
+
owner: string
|
|
151
|
+
repo: string
|
|
152
|
+
/** Filter by label name (e.g. "needs-agent"). */
|
|
153
|
+
label?: string
|
|
154
|
+
/** Issue state filter (default "open"). */
|
|
155
|
+
state?: string
|
|
156
|
+
token: string
|
|
157
|
+
baseUrl?: string
|
|
158
|
+
fetchImpl?: typeof fetch
|
|
159
|
+
/** Hard cap on total issues (default 1000) to bound pagination runtime. */
|
|
160
|
+
maxTotal?: number
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Normalize one raw GitHub issue payload; undefined for PRs / garbage. */
|
|
164
|
+
export function toIssue(raw: unknown): GitHubIssue | undefined {
|
|
165
|
+
if (raw === null || typeof raw !== "object") {
|
|
166
|
+
return undefined
|
|
167
|
+
}
|
|
168
|
+
const r = raw as {
|
|
169
|
+
number?: unknown
|
|
170
|
+
title?: unknown
|
|
171
|
+
body?: unknown
|
|
172
|
+
labels?: unknown
|
|
173
|
+
updated_at?: unknown
|
|
174
|
+
html_url?: unknown
|
|
175
|
+
pull_request?: unknown
|
|
176
|
+
}
|
|
177
|
+
// The /issues endpoint returns pull requests too — filter them out.
|
|
178
|
+
if (r.pull_request !== undefined) {
|
|
179
|
+
return undefined
|
|
180
|
+
}
|
|
181
|
+
const number = Number(r.number)
|
|
182
|
+
if (!Number.isInteger(number) || number <= 0) {
|
|
183
|
+
return undefined
|
|
184
|
+
}
|
|
185
|
+
const labels = Array.isArray(r.labels)
|
|
186
|
+
? (r.labels as unknown[])
|
|
187
|
+
.filter(
|
|
188
|
+
(l): l is { name: string } =>
|
|
189
|
+
l !== null && typeof l === "object" && typeof (l as { name?: unknown }).name === "string",
|
|
190
|
+
)
|
|
191
|
+
.map((l) => l.name)
|
|
192
|
+
: []
|
|
193
|
+
return {
|
|
194
|
+
number,
|
|
195
|
+
title: typeof r.title === "string" ? r.title : String(r.title ?? ""),
|
|
196
|
+
...(typeof r.body === "string" ? { body: r.body } : {}),
|
|
197
|
+
labels,
|
|
198
|
+
...(typeof r.updated_at === "string" ? { updated_at: r.updated_at } : {}),
|
|
199
|
+
...(typeof r.html_url === "string" ? { html_url: r.html_url } : {}),
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* List issues filtered by label (plus state), PRs filtered out, paginated via
|
|
205
|
+
* a simple per_page/page loop (per_page=100 until a short page), capped at
|
|
206
|
+
* `maxTotal` to bound runtime.
|
|
207
|
+
*/
|
|
208
|
+
export async function listIssues(options: ListIssuesOptions): Promise<GitHubIssue[]> {
|
|
209
|
+
const { owner, repo, label, state = "open", token, baseUrl, fetchImpl, maxTotal = DEFAULT_MAX_ISSUES } = options
|
|
210
|
+
|
|
211
|
+
const issues: GitHubIssue[] = []
|
|
212
|
+
let page = 1
|
|
213
|
+
|
|
214
|
+
while (issues.length < maxTotal) {
|
|
215
|
+
const url = buildGhUrl(
|
|
216
|
+
baseUrl ?? process.env.GITHUB_API_BASE_URL ?? DEFAULT_GH_BASE_URL,
|
|
217
|
+
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues`,
|
|
218
|
+
{
|
|
219
|
+
per_page: ISSUES_PAGE_SIZE,
|
|
220
|
+
page,
|
|
221
|
+
state,
|
|
222
|
+
labels: label,
|
|
223
|
+
},
|
|
224
|
+
)
|
|
225
|
+
const raw = await ghApi(url, { token, baseUrl, fetchImpl })
|
|
226
|
+
const batch = Array.isArray(raw) ? raw : []
|
|
227
|
+
for (const entry of batch) {
|
|
228
|
+
const issue = toIssue(entry)
|
|
229
|
+
if (issue) {
|
|
230
|
+
issues.push(issue)
|
|
231
|
+
if (issues.length >= maxTotal) {
|
|
232
|
+
break
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
// A short page (or an empty one) means we've reached the end.
|
|
237
|
+
if (batch.length < ISSUES_PAGE_SIZE) {
|
|
238
|
+
break
|
|
239
|
+
}
|
|
240
|
+
page++
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return issues
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Fetch one issue by number. Used when an issue was only referenced by
|
|
248
|
+
* number (e.g. a webhook payload or a plain-number trigger).
|
|
249
|
+
*/
|
|
250
|
+
export async function getIssue(
|
|
251
|
+
owner: string,
|
|
252
|
+
repo: string,
|
|
253
|
+
number: number,
|
|
254
|
+
options: GhRequestOptions,
|
|
255
|
+
): Promise<GitHubIssue> {
|
|
256
|
+
const raw = await ghApi(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${number}`, options)
|
|
257
|
+
const issue = toIssue(raw)
|
|
258
|
+
if (!issue) {
|
|
259
|
+
throw new Error(`GitHub API: issue #${number} in ${owner}/${repo} is not a usable issue (or is a PR)`)
|
|
260
|
+
}
|
|
261
|
+
return issue
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Add a label to an issue (POST /repos/{o}/{r}/issues/{n}/labels). Used by
|
|
266
|
+
* the documented label-marking idempotency strategy — the default watcher
|
|
267
|
+
* relies on the state file and does not call this.
|
|
268
|
+
*/
|
|
269
|
+
export async function addLabel(
|
|
270
|
+
owner: string,
|
|
271
|
+
repo: string,
|
|
272
|
+
number: number,
|
|
273
|
+
label: string,
|
|
274
|
+
options: GhRequestOptions,
|
|
275
|
+
): Promise<void> {
|
|
276
|
+
await ghApi(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${number}/labels`, {
|
|
277
|
+
...options,
|
|
278
|
+
method: "POST",
|
|
279
|
+
body: { labels: [label] },
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface GhClientOptions {
|
|
284
|
+
token: string
|
|
285
|
+
baseUrl?: string
|
|
286
|
+
fetchImpl?: typeof fetch
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The client shape the watcher consumes (DI-friendly for tests). */
|
|
290
|
+
export interface GhClient {
|
|
291
|
+
listIssues(options: { owner: string; repo: string; label?: string; state?: string }): Promise<GitHubIssue[]>
|
|
292
|
+
getIssue(owner: string, repo: string, number: number): Promise<GitHubIssue>
|
|
293
|
+
addLabel(owner: string, repo: string, number: number, label: string): Promise<void>
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Build a GhClient bound to a token/base URL (or injectable fetch). */
|
|
297
|
+
export function createGhClient(options: GhClientOptions): GhClient {
|
|
298
|
+
const { token, baseUrl, fetchImpl } = options
|
|
299
|
+
return {
|
|
300
|
+
listIssues: (o) => listIssues({ ...o, token, baseUrl, fetchImpl }),
|
|
301
|
+
getIssue: (owner, repo, number) => getIssue(owner, repo, number, { token, baseUrl, fetchImpl }),
|
|
302
|
+
addLabel: (owner, repo, number, label) => addLabel(owner, repo, number, label, { token, baseUrl, fetchImpl }),
|
|
303
|
+
}
|
|
304
|
+
}
|