nightshift

repository·main·Indexed 21 days ago

https://github.com/marcus/nightshift

An automated codebase maintenance tool that identifies dead code, documentation drift, test gaps, and security issues. It operates by creating branches or PRs to ensure a zero-risk workflow. Nightshift includes a budget-aware scheduler for AI providers (Claude, Codex, GitHub Copilot), a background daemon for scheduled tasks, and a busfactor command to analyze code ownership concentration and project continuity risk.

Tokens
40.3K
Snippets
145
Records
208
Agent score
71%

What's inside nightshift

  1. Understand budget modes: Daily vs Weekly

    main

    Nightshift supports two primary usage models via budget.mode:

    • Daily Mode (recommended): Each night uses up to max_percent of your daily budget (calculated as weekly / 7). This provides consistent and predictable usage.
    • Weekly Mode: Uses max_percent of the remaining weekly budget. If aggressive_end_of_week: true is set, the system will spend more near the end of the week to avoid wasting tokens.
  2. Security best practices for Nightshift

    main

    To keep your environment secure when using Nightshift:

    • No Credentials in Config: Never store API keys in .yaml files. Use environment variables like ANTHROPIC_API_KEY or OPENAI_API_KEY.
    • Write Permissions: By default, Nightshift runs in read-only mode. You must explicitly use the --enable-writes flag for the first run to allow file modifications.
    • Budget Safety: The system defaults to a max 75% budget usage to prevent runaway costs.
    • No Auto-Push: Nightshift does not automatically push changes to remote repositories.
  3. Interpret provider calibration output and multipliers

    main

    The calibration report provides two types of medians:

    1. Per-session medians: Useful for coarse workload shape checks, but sensitive to session length artifacts.
    2. Per-user-turn medians: Preferred for multiplier discussions as they provide better normalization when one provider has longer sessions.

    Suggested Multiplier Calculation

    The tool suggests a multiplier using the following logic: codex_primary_per_user_turn / claude_alt_per_user_turn

    Note: Claude alt tokens are used because they include cache-related fields (input + output + cache_read + cache_creation), which more closely aligns with subscription-accounting behavior.

  4. Manage task cooldowns and intervals

    main

    Tasks have default cooldown periods per project to prevent excessive resource usage. For example, after running lint-fix, it won't run again on that project for 24 hours.

    Default Category Intervals

    • pr: 7 days
    • analysis: 3 days
    • options: 7 days
    • safe: 14 days
    • map: 7 days
    • emergency: 30 days

    Overriding and Inspecting

    • Override: Use tasks.intervals in your config to change a task's cooldown.
    • Inspect: Use nightshift preview --explain to see which tasks are currently on cooldown and when they will become eligible again.
  5. Core concepts of Nightshift

    main

    Nightshift is a Go-based CLI tool designed to run AI-powered maintenance tasks (like finding dead code, doc drift, or security issues) on your codebase overnight. It operates based on several key principles:

    • Everything is a PR: Nightshift never writes directly to your primary branch. All changes are submitted as Pull Requests, which you can review or close.
    • Budget-aware: It uses your remaining daily token allotment from Claude Code or Codex subscriptions and will never exceed your configured maximum (which defaults to 75%).
    • Multi-project: It can be pointed at multiple repositories simultaneously.
    • Zero config defaults: It is designed to work out of the box with sensible defaults, though it is fully customizable.
  6. How the Budget Inference system works

    main

    The Budget Inference system replaces hardcoded token guesses with a calibration mechanism that estimates a user's actual subscription budget. It correlates local token usage counts with scraped usage percentages from provider interfaces (like Claude's /usage or Codex's /status).

    Core Formula (Subscription Users): total_budget = local_tokens / (scraped_pct / 100)

    Example: If local files show 315K tokens used and the scraped usage reports 45%, the inferred total budget is 315K / 0.45 = 700K tokens/week.

    API Token Users: Users on pay-per-token plans (billing_mode: api) do not use calibration. Their budget is treated as deterministic based on the weekly_tokens configuration or a dollar cap. The system tracks actual spend from local session data without needing tmux scraping.

  7. Understand the Nightshift run lifecycle

    main

    A Nightshift run follows a specific sequence from trigger to completion. The process begins when a scheduler (like cron, launchd, or systemd) executes nightshift run or the internal daemon calls runScheduledTasks.

    The execution flow is:

    1. Trigger: Scheduler starts the process.
    2. Initialization: Nightshift loads configuration and initializes logging.
    3. Resource Allocation: The system calculates budgets and selects an appropriate provider based on preferences and budget constraints.
    4. Task Selection: Relevant tasks are identified for execution.
    5. Execution Loop: The Orchestrator enters a Plan → Implement → Review loop for each task.
    6. Finalization: A run record, summary, and report are generated and saved.
  8. Integrate external task lists (td and GitHub)

    main

    Nightshift can pull tasks from external sources.

    Using td (task management): Use td list --format json to provide tasks to Nightshift. Nightshift expects to be able to use td assign TASK_ID and td complete TASK_ID to manage task state.

    Using GitHub Issues: Nightshift can monitor issues with specific labels (e.g., nightshift) using the GitHub CLI (gh).

    # Example GitHub integration command used by Nightshift
    gh issue list --label "nightshift" --json number,title,body
  9. Conceptual overview of Nightshift

    main

    Nightshift is a Go-based CLI tool designed to perform automated maintenance and development tasks on codebases during off-hours (e.g., overnight). It is specifically designed for developers using AI coding agent plans with weekly credit/budget allotments.

    Core Value Proposition: Nightshift manages your remaining AI budget by automatically executing tasks like code reviews, documentation updates, and security checks, ensuring your subscription credits are utilized effectively without exceeding your limits.

    Key Workflow:

    1. Trigger: A system like cron wakes up the Nightshift process.
    2. Planning: Nightwatch builds a prompt for an orchestrator based on your configuration and remaining budget.
    3. Execution: The orchestrator selects a task, assigns it to prevent duplicate processing, and spawns sub-agents to plan, implement, and review the work.
    4. Budget Check: The system periodically checks the token budget. If within the allowed threshold, it repeats the process. If the budget is exhausted or the interval is reached, it stops.
    5. Output: Every task concludes by answering: "What would you like to do next?" (e.g., "Pick A or B", "Here is the context you were missing", or "Nothing - merged").
  10. Configure Nightshift project hierarchy

    main

    Nightshift uses a hierarchical configuration model:

    1. Global config: Located at ~/.config/nightshift/config.yaml. Defines default settings and a list of managed projects.
    2. Per-project override: A .nightshift.yaml file in the project root. Overrides global settings and can enable/disable specific tasks for that project.

    Projects can be defined explicitly by path or via glob patterns in the global config.

    # Example global config snippet
    projects:
      - path: ~/code/project1
      - path: ~/code/project2
      - pattern: ~/code/oss/*
        exclude:
          - ~/code/oss/archived
  11. Provide project context via CLAUDE.md or AGENTS.md

    main
    Nightshift reads project-level instruction files to understand context during task execution. By placing a CLAUDE.md or AGENTS.md file in your repository root, you can provide project-specific guidance. Note that tasks explicitly mentioned in these files receive a priority bonus of +2.