agentops

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 22, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

CI Release License Go Version

Languages: English | 中文

AgentCLI - GO logo

Framework modules for building Go CLI projects with an agent-first workflow.

agentcli-go is an agent-first CLI scaffold and runtime framework: it provides logging, argument parsing, command execution, filesystem helpers, lifecycle flow, and verification primitives so AI agents can build reliable CLI tools consistently.


AgentCLI - GO

2-minute value

  • Generate a standards-compliant Go CLI in under a minute.
  • Keep it deterministic with task ci and docs-aware checks.
  • Onboard another AI agent with one documented sequence.

30-second demo

go install github.com/gh-xj/agentcli-go/cmd/agentcli@v0.2.5
agentcli new --module github.com/me/my-tool my-tool
cd my-tool
agentcli doctor
agentcli loop doctor --repo-root .            # optional verification trace

Expected result: a runnable scaffold (main.go, cmd/, Taskfile.yml, test/) plus a first quality check in less than 2 minutes. agentcli new now runs go mod tidy automatically for standalone projects, so go.sum is generated on scaffold.

Why

  • Skip framework boilerplate for AI-assisted CLI creation.
  • Standardized CLI patterns across generated agents/tools.
  • Scaffold a compliant project in under a minute.
  • Machine-readable output (--json) built into the scaffold from day one.
Harness Engineering value proposition
  • Deterministic project scaffolding with opinionated defaults for reproducible setup.
  • Built-in quality gates designed for AI-assisted workflows and CI-safe project hygiene.
  • Contract-first outputs (schemas + tooling) to make generated CLIs easier to maintain over time.
  • Standardized lifecycle/error semantics so teams can onboard agents and scripts faster with fewer “first-run” surprises.
  • A practical base for scalable agent/tooling workflows, while keeping the runtime surface small and reviewable.

Who should use agentcli-go

  • You want AI agents to generate, evolve, and maintain Go CLIs with predictable behavior.
  • You ship internal tooling and want deterministic templates, predictable outputs, and CI-friendly checks.
  • You want fewer run/retry loops from inconsistent setup and missing onboarding context.
  • You value a small, reviewable runtime API over large generator-heavy ecosystems.

This project is primarily a foundation for agent-built CLIs, and also useful for human users who want that same rigor and consistency.

Common use cases

  • Internal ops scripts (cron, migration helpers, maintenance assistants).
  • Data/IO helpers (sync, fetch, transform, report).
  • Multi-step agent workflows that need deterministic command/task orchestration.
  • Reusable CLI kits for internal teams needing the same scaffolding and quality gates.

How this project fits

agentcli-go is the foundation layer for CLI scripts in this repo:

  • As a library, it provides reusable CLI primitives.
  • As a scaffold CLI, it generates a compliant project skeleton.
  • As harness infrastructure, it helps AI agents produce, verify, and iterate safely.
User request
   │
   ▼
AI Agent (Codex/Claude/ClawHub)
   │
   ├─ reads onboarding + skill docs
   │
   ▼
agentcli-go (library + scaffold CLI)
   │
   ├─ generates standard CLI layout
   ├─ standardized flags, logging, errors, config flow
   └─ adds harness entrypoints and docs/checks
           │
           ▼
Generated project (task/verify, schemas, docs:check, loop/quality)
           │
   ▼
Lower agent cognitive load + safer iteration

How this helps discoverability

  • Stable, predictable output format (--json) and task gates help people trust what they see.
  • Strong documentation structure (README + agents.md + skill docs) reduces setup confusion.
  • Ready-to-use agent entrypoint on ClawHub:

Copy-paste onboarding prompt (for agents)

Use this short pointer at session start:

I am onboarding to use this repository as an agent skill.
Project URL: https://github.com/gh-xj/agentcli-go
Please follow the sequence in agents.md, including canonical onboarding commands, doc-routing rules, and memory/update actions.

Quick adoption path (5 minutes)

  1. Install the CLI:
go install github.com/gh-xj/agentcli-go/cmd/agentcli@v0.2.5
  1. Generate a standard project:
agentcli new --module github.com/me/my-tool my-tool
cd my-tool
  1. Run the first health checks:
go test ./...
agentcli doctor
  1. Add a command and verify quickly:
agentcli add command --name sync --preset file-sync
go run . --help

If this works, your team gets a scaffolded CLI with harness-friendly structure without manual setup.

Migrate Existing scripts/*.sh (10-minute path)

Start from help:

agentcli --help

Then run migration in safe mode:

agentcli migrate --source ./scripts --mode safe --dry-run
agentcli migrate --source ./scripts --mode safe --apply

Output artifacts are generated under agentcli-migrated/docs/migration/ by default:

  • plan.json (machine-readable migration plan)
  • report.md and report.json (human + machine report)
  • compatibility.md (shell feature compatibility)

KPI fields for onboarding conversion tracking are documented in docs/migration/README.md.

If this project saves your agent setup time, give it a star on GitHub to improve discovery for other teams: https://github.com/gh-xj/agentcli-go

FAQ (1-minute)

  • agentcli loop command fails in docs?
    • Check agents.md and skills/verification-loop/SKILL.md for current command signatures.
  • My generated project is missing expected files?
    • Re-run agentcli new with a clean directory name and check template version compatibility.
  • What should I do before opening PR?
    • Run task verify and include output of key checks in your PR notes.

Contributing

  • Contributions are welcome. See CONTRIBUTING.md for review expectations, local checks, and PR workflow.

Installation

Library (import into your project)
go get github.com/gh-xj/agentcli-go@v0.2.5
Scaffold CLI (optional, for generating new projects)
go install github.com/gh-xj/agentcli-go/cmd/agentcli@v0.2.5

Naming note: repository/module name is agentcli-go, installed binary name is agentcli.

Or with Homebrew:

brew tap gh-xj/tap
brew install agentcli

Or download a prebuilt binary (macOS/Linux amd64+arm64):

Claude Code Skill

For guidance on using this library effectively in Codex/Claude workflows, see skills/agentcli-go/SKILL.md. For agent-specific onboarding and harness entrypoints, see agents.md. For a project-level quick-start skill example, see skill.md.

Published on ClawHub

This repo is published as an agent skill at: https://clawhub.ai/gh-xj/agentcli-go

HN drafts

  • English: docs/hn/2026-02-22-show-hn-agentcli-go.md
  • 中文: docs/hn/2026-02-23-show-hn-agentcli-go-zh.md

Quick Start: Agent-oriented CLI example

package main

import (
    "fmt"
    "os"
    "slices"

    "github.com/gh-xj/agentcli-go/dal"
    "github.com/gh-xj/agentcli-go/operator"
    "github.com/rs/zerolog/log"
)

func main() {
    verbose := slices.Contains(os.Args, "-v") || slices.Contains(os.Args, "--verbose")
    dal.NewLogger().Init(verbose, os.Stderr)

    argsOp := operator.NewArgsOperator()
    args := argsOp.Parse(os.Args[1:])
    src, err := argsOp.Require(args, "src", "--src path")
    if err != nil {
        log.Fatal().Err(err).Msg("missing required flag")
    }
    dst := argsOp.Get(args, "dst", "/tmp/out")

    fs := dal.NewFileSystem()
    if !fs.Exists(src) {
        log.Fatal().Str("src", src).Msg("source not found")
    }
    fs.EnsureDir(dst)

    exec := dal.NewExecutor()
    out, err := exec.Run("rsync", "-av", src, dst)
    if err != nil {
        log.Fatal().Err(err).Msg("sync failed")
    }
    fmt.Print(out)
}

Run with: go run . --src ./data --dst /backup


API Reference

Root Package (Model Layer)
Type Description
AppContext Shared runtime context (Logger, IO, Meta, Values)
Hook Preflight/Postflight interface
CLIError Typed error with exit code
ResolveExitCode(err) Map error to exit code
DoctorReport Scaffold compliance check results
DAL Layer (dal/)
Type Description
FileSystem / NewFileSystem() Exists, EnsureDir, ReadFile, WriteFile, ReadDir, BaseName
Executor / NewExecutor() Run, RunInDir, RunOsascript, Which
Logger / NewLogger() Init(verbose, writer) — zerolog setup
Operator Layer (operator/)
Type Description
ArgsOperator / NewArgsOperator() Parse, Require, Get, HasFlag
TemplateOperator / NewTemplateOperator(fs) RenderTemplate, KebabToCamel, ResolveParentModule
ComplianceOperator / NewComplianceOperator(fs) CheckFileExists, CheckFileContains, ValidateCommandName
Service Layer (service/)
Type Description
service.Get() Wire DI container singleton
ScaffoldService New (scaffold project), AddCommand
DoctorService Run (compliance checks + DAG validation)
LifecycleService Run (preflight/run/postflight)
Adapters
  • cobrax — Cobra adapter with standardized persistent flags (--verbose, --config, --json, --no-color) and deterministic exit code mapping
  • configx — Config loading with deterministic precedence: Defaults < File < Env < Flags

Quick Start: Scaffold a New Project

Use agentcli new to generate a fully-wired DAG project with Taskfile, smoke tests, Wire DI, and schema contracts:

agentcli new --module github.com/me/my-tool my-tool
cd my-tool
agentcli add command --preset file-sync sync-data
agentcli doctor --json        # verify compliance
task verify                   # run full local gate

Recommended default for monorepos: generate without nested go.mod:

# run inside an existing Go module
agentcli new --dir ./tools --in-existing-module replay-cli
cd tools/replay-cli
task verify

Minimal mode (tiny scaffold surface):

agentcli new --minimal --module github.com/me/my-mini my-mini

Generated layout:

my-tool/
├── main.go
├── cmd/root.go
├── service/{container,wire}.go
├── operator/{interfaces,example_op}.go
├── dal/{interfaces,filesystem}.go
├── internal/app/{bootstrap,lifecycle,errors}.go
├── internal/config/{schema,load}.go
├── internal/io/output.go
├── internal/tools/smokecheck/main.go
├── pkg/version/version.go
├── test/e2e/cli_test.go
├── test/smoke/version.schema.json
└── Taskfile.yml

Command presets: file-sync, http-client, deploy-helper, task-replay-orchestrator

Cross-repo orchestration pattern

Common pattern: run task in an external repo with env injection.

agentcli add command --preset task-replay-orchestrator replay-orchestrate
go run . replay-orchestrate \
  --repo ../external-repo \
  --task replay:emit \
  --env IOC_ID=123 \
  --env MODE=baseline \
  --timeout 90s \
  --timeout-hook 'echo timeout for $AGENTCLI_TIMEOUT_TASK'

Generated wrapper contract:

  • required: --repo <path>
  • optional: --task <name> (default replay:emit)
  • optional repeat: --env KEY=VALUE
  • optional: --timeout <duration>
  • optional: --timeout-hook <shell command>

Examples

Runnable examples:

Examples index: examples/README.md


Project Health

Documentation Conventions

For Agent-Installed Workflows

If this project is used as an agent skill, start with agents.md, then follow links from there.

Optional: Advanced verification profiles

agentcli loop supports configurable verification profiles (for automation workflows).

Canonical shape:

  • agentcli loop [global flags] <action> [action flags]
  • Global flags must appear before <action>.
  • Global flags: --format text|json|ndjson, --summary <path>, --no-color, --dry-run, --explain

Discovery:

  • agentcli loop --format json capabilities

Behavior-only regression gate:

  • agentcli loop regression --repo-root .
  • baseline update: agentcli loop regression --repo-root . --write-baseline

Loop API contract:

  • loop-server endpoint POST /v1/loop/run returns the same harness summary envelope used by CLI output (schema_version, command, status, checks, failures, artifacts, data).
  • Client helper internal/loopapi.RunSummary returns the summary envelope directly.

Core-only compile fallback:

  • If optional loop/harness packages drift and you only need scaffold/doctor flows, build with agentcli_core tag:
    • go build -tags agentcli_core ./cmd/agentcli
  • In agentcli_core builds, loop and loop-server commands are intentionally disabled.

Documentation

Index

Constants

View Source
const (
	ExitSuccess             = 0
	ExitFailure             = 1
	ExitUsage               = 2
	ExitPreflightDependency = 3
	ExitRuntimeExternal     = 4

	ExitStrategyMissing  = 10 // no .agentops/ found
	ExitTransitionDenied = 11 // invalid state transition
	ExitWorkerFailed     = 12 // worker returned error
	ExitValidationFailed = 13 // case/strategy validation failed
)

Variables

This section is empty.

Functions

func ResolveExitCode

func ResolveExitCode(err error) int

ResolveExitCode maps an error to a deterministic exit code.

Types

type AppContext

type AppContext struct {
	Context context.Context
	Logger  zerolog.Logger
	Config  any
	IO      IOStreams
	Meta    AppMeta
	Values  map[string]any
}

AppContext is the shared runtime context for CLI command execution.

func NewAppContext

func NewAppContext(ctx context.Context) *AppContext

NewAppContext returns a context with safe defaults for CLI apps.

type AppMeta

type AppMeta struct {
	Name    string
	Version string
	Commit  string
	Date    string
}

AppMeta carries optional build/runtime metadata.

type CLIError

type CLIError struct {
	Code    int
	Kind    string
	Message string
	Cause   error
}

CLIError is a typed error with a deterministic exit code.

func NewCLIError

func NewCLIError(code int, kind, message string, cause error) *CLIError

NewCLIError builds a typed CLI error with an optional cause.

func (*CLIError) Error

func (e *CLIError) Error() string

func (*CLIError) ExitCode

func (e *CLIError) ExitCode() int

func (*CLIError) Unwrap

func (e *CLIError) Unwrap() error

type DoctorFinding

type DoctorFinding struct {
	Code    string `json:"code"`
	Path    string `json:"path"`
	Message string `json:"message"`
}

DoctorFinding describes a single compliance issue in a scaffolded project.

type DoctorReport

type DoctorReport struct {
	SchemaVersion string          `json:"schema_version"`
	OK            bool            `json:"ok"`
	Findings      []DoctorFinding `json:"findings"`
}

DoctorReport summarizes scaffold compliance checks.

func (DoctorReport) JSON

func (r DoctorReport) JSON() (string, error)

JSON returns the report as indented JSON.

type ExitCoder

type ExitCoder interface {
	error
	ExitCode() int
}

ExitCoder describes errors that can provide a process exit code.

type Hook

type Hook interface {
	Preflight(*AppContext) error
	Postflight(*AppContext) error
}

Hook allows commands to run standardized pre/post execution steps.

type IOStreams

type IOStreams struct {
	Stdout io.Writer
	Stderr io.Writer
}

IOStreams defines where command output should be written.

Directories

Path Synopsis
cmd
agentops command
internal
tools/doccheck command
tools/loopbench command
tools/loopclean command
tools/roleagent command
tools

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL