@XAMTO_AI: 让AI替你熬夜改代码,你只管睡觉 这个工具叫 gnhf,是“Good Night, Have Fun”的缩写——大白话就是:你去休息,剩下的交给AI。 操作流程相当简单: ① 写好一条指令,就能自动调用 Claude Code 或 Cod…
摘要
gnhf 是一个开源工具,让你在睡觉时让AI代理自动循环修改代码、生成Git提交、处理错误并记录进展,支持多种AI模型(如Claude Code、Codex)和多代理并行工作。
查看缓存全文
缓存时间: 2026/05/22 19:58
让AI替你熬夜改代码,你只管睡觉
这个工具叫 gnhf,是“Good Night, Have Fun”的缩写——大白话就是:你去休息,剩下的交给AI。
操作流程相当简单:
① 写好一条指令,就能自动调用 Claude Code 或 Codex ② 进入全自动编码循环,每改一版都会自动生成 Git 提交记录 ③ 遇到报错会自动回滚并重试,全程不需要人工盯着 ④ 具备跨轮次记忆,每次结果会写入笔记,AI 清楚自己之前做过什么 ⑤ 连续失败时会启动指数退避策略,不会白白烧掉太多 token 费用 ⑥ 支持 worktree 模式,可以同时跑多个智能体,彼此不干扰
等一觉醒来,代码已经被反复打磨了好几轮。
有兴趣的可以亲自试试看。
https://github.com/kunchenguid/gnhf…
kunchenguid/gnhf
Source: https://github.com/kunchenguid/gnhf
Before I go to bed, I tell my agents:
good night, have fun
Never wake up empty-handed.
gnhf is a ralph, autoresearch-style orchestrator that keeps your agents running while you sleep — each iteration makes one small, committed, documented change towards an objective. You wake up to a branch full of clean work and a log of everything that happened.
- Dead simple — one command starts an autonomous loop that runs until you request stop or a configured runtime cap is reached
- Long running — each iteration is committed on success, rolled back on failure except commit failures preserved for repair, with sensible retries; retryable hard agent errors back off exponentially while agent-reported failures continue immediately
- Live terminal title — interactive runs keep your terminal title updated with live status, token totals, and commit count, then clear or restore it on exit depending on terminal support; token totals prefixed with
~are estimates - Exit summary: every run ends with a permanent summary covering elapsed time, branch, iterations, tokens, branch diff stats, local notes/log paths, and review commands
- Agent-agnostic: works with Claude Code, Codex, Rovo Dev, OpenCode, GitHub Copilot CLI, Pi, or ACP targets out of the box
Quick Start
$ gnhf "reduce complexity of the codebase without changing functionality"
# have a good sleep
$ gnhf "reduce complexity of the codebase without changing functionality" \
--max-iterations 10 \
--max-tokens 5000000
# have a good nap
# Run multiple agents on the same repo simultaneously using worktrees
$ gnhf --worktree "implement feature X" &
$ gnhf --worktree "add tests for module Y" &
$ gnhf --worktree "refactor the API layer" &
# Commit directly on the current branch and push after each successful iteration
$ gnhf --current-branch --push "keep improving this app"
Run gnhf from inside a Git repository with a clean working tree. If you are starting from a plain directory, run git init first.
gnhf supports macOS, Linux, and Windows.
Install
npm
npm install -g gnhf
From source
git clone https://github.com/kunchenguid/gnhf.git
cd gnhf
corepack enable
pnpm install
pnpm run build
pnpm link --global
Agent Skill
The npm package includes an agent-facing skill at skills/gnhf/SKILL.md. Agents that support local skills can copy or reference this file to learn how to run GNHF in Hands-Off mode for bounded overnight work, or Companion mode when the outer agent should steer and review a long-running GNHF run.
After installing from npm, the skill is available under the installed package directory. From a source checkout, use skills/gnhf/SKILL.md directly.
How It Works
┌─────────────┐
│ gnhf start │
└──────┬──────┘
▼
┌──────────────────────┐
│ validate clean git │
│ create or use branch │
│ write prompt.md │
└──────────┬───────────┘
▼
┌────────────────────────────┐
│ build iteration prompt │◄──────────────┐
│ (inject notes.md context) │ │
└────────────┬───────────────┘ │
▼ │
┌────────────────────────────┐ │
│ invoke your agent │ │
│ (non-interactive mode) │ │
└────────────┬───────────────┘ │
▼ │
┌─────────────┐ │
│ success? │ │
└──┬──────┬───┘ │
yes │ │ no │
▼ ▼ │
┌──────────┐ ┌───────────┐ │
│ commit │ │ reset or │ │
│ append │ │ repair │ │
│ notes.md │ │ maybe wait│ │
└────┬─────┘ └─────┬─────┘ │
│ │ │
│ ┌──────────┘ │
▼ ▼ │
┌────────────┐ yes ┌──────────┐ │
│ 3 consec. ├─────────►│ abort │ │
│ failures │ └────▲─────┘ │
│ or perm. ├───────────────┘ │
│ error? │ │
└─────┬──────┘ │
no │ │
└──────────────────────────────────────┘
- Incremental commits - each successful iteration is a separate unsigned git commit, so you can cherry-pick or revert individual changes without GPG or SSH signing prompts blocking the run; if
git commitfails, gnhf preserves the uncommitted work and asks the next agent iteration to repair it - Failure handling - failed iterations are rolled back with
git reset --hardexcept commit failures, which preserve uncommitted work for repair; agent-reported failures proceed to the next iteration immediately, retryable hard agent errors use exponential backoff, and permanent agent errors such as Claude low credit balance abort immediately and print the run log path. Complete no-op iterations are reported as failures and count toward the consecutive-failure abort limit. If the run exits with a pending commit failure, the exit summary warns that uncommitted changes were left for repair. - Runtime caps -
--max-iterationsstops before the next iteration begins,--max-tokenscan abort mid-iteration once reported usage reaches the cap, and--stop-whenends the loop after an iteration whose agent output reports the natural-language condition is met unless a commit failure needs repair first; resumed runs reuse the saved stop condition unless you pass a new value, or--stop-when ""to clear it; pending commit-failure repair work is preserved and other uncommitted work is rolled back, and in the interactive TUI the final state remains visible until you press Ctrl+C to exit - Iteration finalization - agents are expected to finish validation, stop any background processes they started, and only then emit the final JSON result for the iteration
- Graceful interrupts - in the interactive TUI, the first Ctrl+C requests a graceful stop and lets the current iteration finish (or ends backoff early), the second Ctrl+C force-stops immediately, and
SIGTERMalso force-stops immediately - Exit summary - after shutdown cleanup, gnhf prints a permanent stdout summary with the final branch, elapsed time, iteration and token totals, branch diff stats, notes/debug-log paths, and review commands
- Shared memory — the agent reads
notes.md(built up from prior iterations) to communicate across iterations - Local run metadata — gnhf stores prompt, notes, stop conditions, and commit-message convention metadata under
.gnhf/runs/and ignores it locally, so your branch only contains intentional work - Resume support — run
gnhfwhile on an existinggnhf/branch to pick up where a previous run left off; if you provide a different prompt, gnhf asks whether to update the saved prompt and continue with the existing history, start a new branch, or quit. New runs whose generated branch already exists use a numeric suffix such asgnhf/<slug>-1.
Live Branch Mode
Pass --current-branch to run on the branch you are already on instead of creating a gnhf/ branch.
Pass --push to push the current branch after each successful iteration.
Together, --current-branch --push is useful for loose projects where you want a deployed or locally watched branch to update throughout the run.
- Re-running the same prompt with
--current-branchresumes the existing.gnhf/runs/<runId>/history on a clean working tree and continues iteration numbering. - Push failures abort the run after preserving the successful local commit.
- gnhf never force-pushes or auto-pulls for this mode.
--pushalso works with the defaultgnhf/branch mode and setsoriginas the upstream when needed.- Do not combine
--current-branchwith--worktree; gnhf exits with an error because those modes choose different working directories.
Worktree Mode
Pass --worktree to run each agent in an isolated git worktree. This lets you launch multiple agents on the same repo simultaneously — each gets its own working directory and branch without interfering with the others or your main checkout.
<repo>/ ← your repo (unchanged)
<repo>-gnhf-worktrees/
├── <run-slug-1>/ ← worktree for agent 1
└── <run-slug-2>/ ← worktree for agent 2
- Worktrees with commits are preserved after the run so you can review, merge, or cherry-pick the work. gnhf prints the path and cleanup command.
- Re-running the same prompt with
--worktreeresumes a preserved matching worktree when possible; otherwise gnhf creates a suffixed worktree such as<run-slug>-1if the original name is unavailable. - Worktrees with no commits are automatically removed on exit unless a pending commit failure left uncommitted work to inspect or repair.
--worktreemust be run from a non-gnhf branch (typicallymain).
CLI Reference
| Command | Description |
|---|---|
gnhf "<prompt>" | Start a new run with the given objective |
gnhf | Resume a run (when on an existing gnhf/ branch) |
echo "<prompt>" | gnhf | Pipe prompt via stdin |
cat prd.md | gnhf | Pipe a large spec or PRD via stdin |
If you run gnhf on an existing gnhf/ branch with a different prompt, gnhf asks whether to update prompt.md and continue the existing run history, start a new branch, or quit. When the prompt came from stdin, that confirmation is read from the controlling terminal, so it must be available.
Flags
| Flag | Description | Default |
|---|---|---|
--agent <agent> | Agent to use (claude, codex, rovodev, opencode, copilot, pi, or acp:<target-or-command>) | config file (claude) |
--max-iterations <n> | Abort after n total iterations | unlimited |
--max-tokens <n> | Abort after n total input+output tokens | unlimited |
--stop-when <cond> | End when the agent reports this condition, after any commit-failure repair; persists across resume | unlimited |
--prevent-sleep <mode> | Prevent system sleep during the run (on/off or true/false) | config file (on) |
--worktree | Run in a separate git worktree (enables multiple agents concurrently) | false |
--current-branch | Run on the current branch instead of creating a gnhf/ branch | false |
--push | Push the current branch after each successful iteration | false |
--meteor-frequency <n> | Set TUI meteor frequency from 0 to 5 (0 disables meteors) | 3 |
--version | Show version |
Configuration
Config lives at ~/.gnhf/config.yml:
# Agent to use by default (claude, codex, rovodev, opencode, copilot, pi, or acp:<target-or-command>)
agent: claude
# Custom paths to native agent binaries (optional)
# agentPathOverride:
# claude: /path/to/custom-claude
# codex: /path/to/custom-codex
# copilot: /path/to/custom-copilot
# pi: /path/to/custom-pi
# Native agent CLI arg overrides (optional)
# agentArgsOverride:
# codex:
# - -m
# - gpt-5.4
# - -c
# - model_reasoning_effort="high"
# - --full-auto
# copilot:
# - --model
# - gpt-5.4
# pi:
# - --provider
# - openai-codex
# - --model
# - gpt-5.5
# - --thinking
# - high
# Custom ACP target commands (optional)
# acpRegistryOverrides:
# my-fork: "/usr/local/bin/my-claude-code-fork --acp"
# staging: "node /opt/staging/agent.mjs"
# Commit message convention (optional)
# Defaults to: gnhf <iteration>: <summary>
# Use the conventional preset for semantic-release compatible headers:
# commitMessage:
# preset: conventional
# Abort after this many consecutive failures
maxConsecutiveFailures: 3
# Prevent the machine from sleeping during a run
preventSleep: true
If the file does not exist yet, gnhf creates it on first run using the resolved defaults.
CLI flags override config file values. --prevent-sleep accepts on/off as well as true/false; the config file always uses a boolean.
The iteration and token caps are runtime-only flags and are not persisted in config.yml; --stop-when is persisted per run for resume, but not in config.
agentArgsOverride.<name> lets you pass through extra CLI flags for native agents (claude, codex, rovodev, opencode, copilot, or pi).
ACP targets do not support path or arg overrides in this version.
Use acpRegistryOverrides to map acp:<target> names to custom spawn commands for local, forked, or beta ACP agents.
You can also pass a raw custom ACP server command directly as a quoted acp: spec, for example gnhf --agent 'acp:./bin/dev-acp --profile ci' "fix the tests".
- Use it for agent-specific options like models, profiles, or reasoning settings without adding a dedicated
gnhfconfig field for each one. - For
codex,claude, andcopilot,gnhfadds its usual non-interactive permission default only when you do not provide your own permission or execution-mode flag. If you set one explicitly,gnhftreats that as user-managed and does not add its default on top. - Flags that
gnhfmanages itself for a given agent, such as output-shaping or local-server startup flags, are rejected during config loading so you get a clear error instead of duplicate-argument ambiguity. Forpispecifically,--api-keyis also blocked; configure the Pi API key via Pi’s own config or the environment variable it reads, not viaagentArgsOverride.
commitMessage controls the subject line that gnhf uses for each successful iteration commit.
- Omit it to keep the default
gnhf <iteration>: <summary>format. - Set
preset: conventionalto ask the agent fortypeand optionalscope, then commit astype(scope): summaryfor semantic-release style workflows. Valid types arebuild,ci,docs,feat,fix,perf,refactor,test, andchore; invalid or missing types fall back tochore, and empty scopes are omitted. - The resolved commit-message convention is saved per run, so resuming keeps the original subject format even if
config.ymlchanges later.
Custom Agent Paths
Use agentPathOverride to point any native agent at a custom binary - useful for wrappers like Claude Code Switch or custom Codex builds that accept the same flags and arguments as the original:
agentPathOverride:
claude: ~/bin/claude-code-switch
codex: /usr/local/bin/my-codex-wrapper
copilot: ~/bin/copilot-wrapper
pi: ~/bin/pi-wrapper
Paths may be absolute, bare executable names already on your PATH, ~-prefixed, or relative to the config directory (~/.gnhf/). The override replaces only the binary name; all standard arguments are preserved, so the replacement must be CLI-compatible with the original agent. On Windows, .cmd and .bat wrappers are supported, including bare names resolved from PATH. For rovodev, the override must point to an acli-compatible binary since gnhf invokes it as <bin> rovodev serve ....
When sleep prevention is enabled, gnhf uses the native mechanism for your OS: caffeinate on macOS, systemd-inhibit on Linux, and a small PowerShell helper backed by SetThreadExecutionState on Windows.
Debug Logs
Every run writes a JSONL debug log to .gnhf/runs/<runId>/gnhf.log alongside notes.md. Lifecycle events for the orchestrator, agent, and HTTP requests are captured with elapsed timings and (for failures) the full error.cause chain, which is what you need to tell a bare TypeError: fetch failed apart from an undici UND_ERR_HEADERS_TIMEOUT. The agent’s own streaming output still goes to the per-iteration iteration-<n>.jsonl file next to it.
Raw ACP command specs are redacted as acp:custom/custom in debug logs and related errors, so local paths or secrets in custom commands are not written to gnhf.log.
Including a snippet of gnhf.log is the single most useful thing you can attach when filing an issue.
Telemetry
gnhf sends anonymous usage telemetry to my self-hosted analytics so I can see what’s actually getting used.
No prompts, repo paths, or branch names are sent.
Set GNHF_TELEMETRY=0 to turn it off.
Agents
gnhf supports six native agents plus ACP targets. ACP support is powered by acpx, which is bundled with gnhf and provides the runtime and agent registry for acp:<target-or-command> specs.
| Agent | Flag | Requirements | Notes |
|---|---|---|---|
| Claude Code | --agent claude | Install Anthropic’s claude CLI and sign in first. | gnhf invokes claude directly in non-interactive mode. After Claude emits a successful structured result, gnhf treats that result as final and shuts down any lingering Claude process tree after a short grace period. |
| Codex | --agent codex | Install OpenAI’s codex CLI and sign in first. | gnhf invokes codex exec directly in non-interactive mode. |
| GitHub Copilot CLI | --agent copilot | Install GitHub Copilot CLI and sign in first. | gnhf invokes copilot directly in non-interactive JSONL mode. Copilot currently exposes assistant output tokens, but not full input/cache token totals; see https://github.com/github/copilot-cli/issues/1152. |
| Pi | --agent pi | Install the pi CLI and configure a usable provider/model first. | gnhf invokes pi directly in JSON mode, appends the final output schema to the prompt, and disables Pi session persistence with --no-session. |
| Rovo Dev | --agent rovodev | Install Atlassian’s acli and authenticate it with Rovo Dev first. | gnhf starts a local acli rovodev serve --disable-session-token <port> process automatically in the repo workspace. |
| OpenCode | --agent opencode | Install opencode and configure at least one usable model provider first. | gnhf starts a local opencode serve --hostname 127.0.0.1 --port <port> --print-logs process automatically, creates a per-run session, and applies a blanket allow rule so tool calls do not block on prompts. |
| ACP target | --agent acp:<target-or-command> | Install and authenticate the target supported by the bundled acpx registry, such as acp:gemini, or pass a quoted custom ACP server command. | gnhf runs the target through ACP with a persistent per-run session under .gnhf/runs/<runId>/acp-sessions; token usage and --max-tokens use ACP used deltas when available, with prompt-length plus tool-call estimates as a fallback, and agentPathOverride and agentArgsOverride do not apply. |
Development
If you want to contribute changes back to this repo, see CONTRIBUTING.md. Human-authored PRs targeting main must be opened via git push no-mistakes so the required Require no-mistakes check passes.
pnpm run build # Build with tsdown
pnpm run dev # Watch mode
pnpm test # Build, then run all tests (vitest)
pnpm run test:e2e # Build, then run end-to-end tests against the mock opencode executable
pnpm run lint # ESLint
pnpm run format # Prettier
Star History
Amto (@XAMTO_AI): 用工程化的方式写推文,这个开源项目重新定义了内容创作流程
tweet-skills 将推文创作拆解为8个独立模块:采集、调研、观点生成、正文撰写、去AI痕迹、标题拟定、结尾处理、内容串联。每个环节职责明确,可单独运行、单独调优。
相似文章
@Xudong07452910: ARIS:让 AI 在你睡觉时继续搞科研的神器! 一个极致轻量的自动科研工具,可以让 Claude Code / Codex / Cursor / Trae / 国产模型自动进入科研工作流: 读论文,找 weakness 生成 idea,…
ARIS 是一个基于 Markdown 的轻量级自动科研工具,支持多种 AI 模型(如 Claude Code、Cursor、Trae)自动完成读论文、生成 idea、设计实验、写论文等全流程科研工作,让 AI 在用户睡眠时持续探索。
@XAMTO_AI: 之前用AI写代码,我一直是"人盯着工具干"的模式,一个任务跑完再丢下一个,像流水线工人一样等着。multica 刷新了这个协作方式。 它不只是一个需要你时刻唤醒的代码生成器,而是被设计成一个能自主接单、主动汇报的虚拟同事。你只需要在看板上…
Multica 是一个开源工作空间,旨在将AI编码代理转变为能自主接单和主动汇报的虚拟同事,从而改变开发者与AI工具的协作方式。
@Ryrenz: 大部分人用编程 AI 只会说「帮我改一下这个 bug」,然后花半小时跟它拉扯。换个说法,一次就对。 1. 让它先看再动 「先别写代码。把相关文件读一遍,告诉我这个功能现在是怎么走的,我确认完你再改。」 2. 卡住的 bug 「不要猜。加日…
一条关于如何更有效地使用编程 AI 的实用提示,列出了 12 条具体指令范例,如让 AI 先读代码再修改、只改必要部分、写进 AGENTS.md 等,以减少来回拉扯并让规则长期生效。
@ai_super_niko: AI 编程工具在拼命执行,方向偏了只能眼睁睁看它跑完?上一条提问写错了,只能在后面补十条解释? 我把最近重度使用 Codex 的过程,总结成了 4 个动作: 1. 打断:双击 Esc 现场叫停,拒绝无效等待; 2. 编辑:直接编辑最近消息…
总结使用AI编程工具Codex的四个关键动作:打断、编辑、引导排队、分叉,帮助用户从被动等待结果转变为主动管理过程。
@Saccc_c: 小白如何快速入门 AI 的几个建议: 1、停止使用ChatGPT等对话式AI ,开始使用Claude Code、Codex、Manus 这类能自主执行任务的 Agent 工具。 2、写好一个自己的 Skill,比如 把你的工作习惯、偏好、…
给AI新手的建议:使用能自主执行任务的Agent工具(如Claude Code、Codex、Manus),编写个人Skill结构化说明,并持续积累上下文提炼有效Prompt。