From 693c5125c72127f2279a38a10b8b88d374da683c Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Sun, 8 Nov 2026 08:00:03 +0000
Subject: [PATCH 1/6] Move sync, list, shell, and dash under jobs
These four commands now live only under cronitor jobs. Root
invocations fail as unknown commands. discover stays as an alias
of jobs sync, and the auto-discover crontab line targets that
subcommand even when inherited flags sit between the two words.
Co-authored-by: August Flanagan
---
README.md | 39 +++---
cmd/configure.go | 2 +-
cmd/dash.go | 6 +-
cmd/discover.go | 26 ++--
cmd/jobs.go | 33 +++++
cmd/jobs_test.go | 65 ++++++++++
cmd/list.go | 10 +-
cmd/shell.go | 6 +-
cmd/shell_shim_sync_test.go | 4 +-
cmd/sync_rerun_test.go | 6 +-
dockerfile | 2 +-
docs/IP-ACCESS-RESTRICTIONS.md | 2 +-
docs/MCP_INTEGRATION.md | 36 +++---
docs/MCP_PROMPTS.md | 8 +-
fixtures/shim/crontab.expected | 2 +-
fixtures/shim/crontab.format-exec.expected | 2 +-
fixtures/shim/crontab.format-short.expected | 2 +-
fixtures/shim/crontab.input | 2 +-
lib/crontab.go | 126 +++++++++++++++++++-
lib/crontab_test.go | 50 ++++++++
lib/crontab_wrap_test.go | 5 +-
tests/cleanup-ci-monitors.sh | 2 +-
tests/real-cron.sh | 2 +-
tests/test-discover.bats | 28 ++---
tests/test-list.bats | 4 +-
web/src/components/Docs.js | 16 +--
26 files changed, 378 insertions(+), 108 deletions(-)
create mode 100644 cmd/jobs.go
create mode 100644 cmd/jobs_test.go
diff --git a/README.md b/README.md
index 2103e51a..50fe01f2 100644
--- a/README.md
+++ b/README.md
@@ -63,17 +63,20 @@ Logout revokes this installation's credential and removes it locally. **Schedule
### Cron Management
| Command | Description |
|---------|-------------|
-| `cronitor sync` | Sync cron jobs to Cronitor |
-| `cronitor sync --format=short` | Also convert `cronitor exec` lines to `CRONITOR=` lines |
-| `cronitor sync --format=exec` | Write all lines as `cronitor exec` and restore your `SHELL` |
-| `cronitor sync --with-monitored` | Also ask about jobs that are already monitored, for example to rename them |
-| `cronitor sync --dry-run` | Show what Linux/macOS crontab sync would change, without sending or writing. Does not apply to `--file` or Windows scheduled tasks |
+| `cronitor jobs sync` | Sync cron jobs to Cronitor |
+| `cronitor jobs sync --format=short` | Also convert `cronitor exec` lines to `CRONITOR=` lines |
+| `cronitor jobs sync --format=exec` | Write all lines as `cronitor exec` and restore your `SHELL` |
+| `cronitor jobs sync --with-monitored` | Also ask about jobs that are already monitored, for example to rename them |
+| `cronitor jobs sync --dry-run` | Show what Linux/macOS crontab sync would change, without sending or writing. Does not apply to `--file` or Windows scheduled tasks |
| `cronitor exec ` | Run a command with monitoring |
-| `cronitor list` | List all cron jobs |
+| `cronitor jobs list` | List all cron jobs |
+| `cronitor jobs shell` | Run a command the way cron would |
| `cronitor status` | View monitor status |
-| `cronitor dash` | Start the web dashboard |
+| `cronitor jobs dash` | Start the web dashboard |
-#### How `cronitor sync` changes a crontab
+`cronitor jobs discover` is an alias of `cronitor jobs sync`. `ping`, `exec`, and the other commands stay at the top level.
+
+#### How `cronitor jobs sync` changes a crontab
On Linux and macOS, sync puts the monitor key in front of each job you monitor, and adds one line to the top of the crontab:
@@ -93,21 +96,21 @@ SHELL=/etc/cronitor/shell
0 1 * * * CRONITOR=abc123 CRONITOR_ENV=staging CRONITOR_NO_STDOUT=1 /usr/local/bin/backup.sh
```
- A `CRONITOR=` line works only in a crontab that sync has changed. To add monitoring by hand to any other crontab, script or task, use `cronitor exec `.
-- To go back, run `cronitor sync --format=exec`.
+- To go back, run `cronitor jobs sync --format=exec`.
- Windows scheduled tasks always use `cronitor exec`.
-#### Running `cronitor sync` again
+#### Running `cronitor jobs sync` again
There are three ways to run sync:
| Command | Asks about | Picks up schedule and timezone changes | Monitors new jobs |
| --- | --- | --- | --- |
-| `cronitor sync` | new jobs only | yes | the ones you choose |
-| `cronitor sync --with-monitored` | every job (to rename one) | yes | the ones you choose |
-| `cronitor sync --auto` | nothing | yes | **all of them** |
+| `cronitor jobs sync` | new jobs only | yes | the ones you choose |
+| `cronitor jobs sync --with-monitored` | every job (to rename one) | yes | the ones you choose |
+| `cronitor jobs sync --auto` | nothing | yes | **all of them** |
-- Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing.
-- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. It also monitors every new job, so it is not the way to pick up one schedule change.
+- Run plain `cronitor jobs sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing.
+- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor jobs sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. It also monitors every new job, so it is not the way to pick up one schedule change.
- If any crontab fails to apply, in any mode, sync exits 1.
- For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor.
- If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it.
@@ -279,7 +282,7 @@ The Cronitor CLI bundles the [Crontab Guru Dashboard](https://crontab.guru/dashb
Start locally
```
-cronitor dash
+cronitor jobs dash
# then visit http://localhost:9000
```
@@ -378,12 +381,12 @@ You can also pass `--ping-api-host eu.cronitor.link`, or save it with `cronitor
The Cronitor CLI includes a built-in [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for managing cron jobs with natural language through AI-powered tools like Claude Code, Cursor, Cline, and Windsurf.
-**Quick start:** Run `cronitor dash` on your server, then configure your MCP client to spawn `cronitor dash --mcp-instance default`.
+**Quick start:** Run `cronitor jobs dash` on your server, then configure your MCP client to spawn `cronitor jobs dash --mcp-instance default`.
For setup instructions, available tools, and configuration options, see the [MCP Integration Guide](docs/MCP_INTEGRATION.md).
## Uninstall CronitorCLI
-First, run `cronitor sync --format=exec` for each crontab that sync changed. This removes the `SHELL=.../cronitor/shell` line (and `CRONITOR_SHELL=`, if any), restores your previous `SHELL`, and writes monitored jobs as `cronitor exec MONITOR_KEY ...`.
+First, run `cronitor jobs sync --format=exec` for each crontab that sync changed. This removes the `SHELL=.../cronitor/shell` line (and `CRONITOR_SHELL=`, if any), restores your previous `SHELL`, and writes monitored jobs as `cronitor exec MONITOR_KEY ...`.
**Do not delete `/etc/cronitor/shell` while a crontab still has `SHELL=/etc/cronitor/shell`. If you do, no job in that crontab runs, including jobs without monitoring.**
diff --git a/cmd/configure.go b/cmd/configure.go
index 13b04fba..08a27681 100644
--- a/cmd/configure.go
+++ b/cmd/configure.go
@@ -78,7 +78,7 @@ Example setting your API key (preferred):
$ export CRONITOR_API_KEY
$ cronitor configure
-Example setting common exclude text for use with 'cronitor discover':
+Example setting common exclude text for use with 'cronitor jobs sync':
$ cronitor configure -e "/var/app/code/path/" -e "/var/app/bin/" -e "> /dev/null"`,
Run: func(cmd *cobra.Command, args []string) {
clearManagedAuthMetadataIfReplacingKey(cmd)
diff --git a/cmd/dash.go b/cmd/dash.go
index a6e2b989..23cdc577 100644
--- a/cmd/dash.go
+++ b/cmd/dash.go
@@ -710,7 +710,7 @@ not start a web server but instead communicates via stdio protocol.`,
}
fmt.Printf("\nCredentials saved to: %s\n", configPath)
- fmt.Println("Please run 'cronitor dash' again to start the dashboard.")
+ fmt.Println("Please run 'cronitor jobs dash' again to start the dashboard.")
os.Exit(0)
}
@@ -1077,7 +1077,7 @@ func addLineToCrontab(file string, line string) error {
}
func init() {
- RootCmd.AddCommand(dashCmd)
+ jobsCmd.AddCommand(dashCmd)
dashCmd.Flags().Int("port", 9000, "Port to run the dashboard on")
dashCmd.Flags().Bool("safe-mode", false, "Limit the ability to edit jobs, crontabs, and settings")
dashCmd.Flags().Bool("mcp", false, "Enable MCP server mode for Cursor integration (deprecated: use --mcp-instance instead)")
@@ -3063,7 +3063,7 @@ func requestSystemdRestart() error {
// Type=simple
// Restart=always
// RestartSec=5
- // ExecStart=/usr/local/bin/cronitor dash
+ // ExecStart=/usr/local/bin/cronitor jobs dash
// Try to determine the service name for logging purposes
serviceName := getSystemdServiceName()
diff --git a/cmd/discover.go b/cmd/discover.go
index 6bea780c..619b462b 100644
--- a/cmd/discover.go
+++ b/cmd/discover.go
@@ -112,7 +112,7 @@ var existingMonitors = ExistingMonitors{}
var processingMultipleCrontabs = false
var userAbortedSync = false // Set to true when user presses Ctrl+D to abort sync entirely
-// stdoutIsCrontab is true while `cronitor sync --auto` handles one crontab
+// stdoutIsCrontab is true while `cronitor jobs sync --auto` handles one crontab
// file and will print it on stdout. Verbose logs go to stderr so the pipe
// cannot install log text or a partial crontab.
var stdoutIsCrontab bool
@@ -257,22 +257,22 @@ Note: You must supply your Cronitor API key. This can be passed as a flag, envir
There are three ways to run sync:
- $ cronitor sync
+ $ cronitor jobs sync
> Asks about each job that is not monitored yet
> Checks every monitored job against Cronitor and picks up schedule and timezone changes
> Shows one summary with each change, then asks once before it sends or writes anything
> Run it again whenever you add jobs or change a schedule. If nothing changed, it asks nothing.
- $ cronitor sync --with-monitored
+ $ cronitor jobs sync --with-monitored
> The same, but also asks about jobs that are already monitored, for example to rename them
- $ cronitor sync --auto
+ $ cronitor jobs sync --auto
> Asks nothing. Monitors every new job, sends schedule and timezone changes, and writes the crontab
> Prints the crontab to stdout even when nothing changed. Once sync has read the file,
a failure prints the original crontab and exits 1. A direct "| crontab -" pipe can
still install an empty crontab if sync fails before it can read the file, for example
when the file is missing or a flag is invalid. Capture the output first:
- out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -
+ out=$(cronitor jobs sync --auto file) && printf '%s\n' "$out" | crontab -
Do not add --silent to that command: --auto --silent prints no crontab,
so the pipe would install an empty one.
> Use it to automate sync, not to pick up one schedule change: it also monitors every new job
@@ -285,11 +285,11 @@ There are three ways to run sync:
sync shows the summary and asks whether to save. "Skip this job, don't ask again" adds
"# cronitor: ignore" above the line; a monitored job keeps reporting to Cronitor.
- $ cronitor sync /path/to/crontab
+ $ cronitor jobs sync /path/to/crontab
> Instead of the user crontab, provide a crontab file (or directory of crontabs) to use
Example excluding secrets or common text from monitor names:
- $ cronitor sync /path/to/crontab -e "secret-token" -e "/var/common/app/path/"
+ $ cronitor jobs sync /path/to/crontab -e "secret-token" -e "/var/common/app/path/"
> Creates new monitors, excluding the provided snippets from the generated name.
> Existing monitored names are kept. Use --with-monitored to rename them.
> Adds Cronitor integration to your crontab and outputs to stdout
@@ -297,7 +297,7 @@ Example excluding secrets or common text from monitor names:
You can run the command as many times as you need, accumulating exclusion params until the job names on your Cronitor dashboard are clear and readable.
Example where you perform a dry-run without any crontab modifications:
- $ cronitor sync /path/to/crontab --dry-run
+ $ cronitor jobs sync /path/to/crontab --dry-run
> Asks about new jobs and shows what would change
> On Linux and macOS crontab sync, sends nothing to Cronitor and does not write the crontab
> Does not apply to --file imports or Windows scheduled-task sync
@@ -432,8 +432,8 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read
if importedCrontabs > 0 {
msg := "Reminder: This is a DRY-RUN. Integration is not complete."
next := "To complete integration, run:"
- // Same command without --dry-run. That is `cronitor sync`
- // after an interactive dry run, or `cronitor sync --auto`
+ // Same command without --dry-run. That is `cronitor jobs sync`
+ // after an interactive dry run, or `cronitor jobs sync --auto`
// when --auto was already set. --auto --silent is neither:
// --auto would monitor every new job, and with --silent it
// also skips printing the crontab.
@@ -1243,7 +1243,7 @@ func applyPlan(plan *crontabPlan) bool {
sent, err := getCronitorApi().PutMonitors(monitors)
if err != nil {
// os.Exit here skips finishSync's deferred print, so
- // `cronitor sync --auto file | crontab -` installs an empty
+ // `cronitor jobs sync --auto file | crontab -` installs an empty
// crontab. Same as a shim or save failure: stdout gets the
// original crontab (not the planned rewrite) and the process
// exits 1.
@@ -1678,11 +1678,11 @@ const (
)
func init() {
- RootCmd.AddCommand(discoverCmd)
+ jobsCmd.AddCommand(discoverCmd)
discoverCmd.Flags().BoolVar(&saveCrontabFile, "save", saveCrontabFile, "Save the updated crontab file")
discoverCmd.Flags().BoolVar(&dryRun, "dry-run", dryRun, "Show what Linux/macOS crontab sync would change. Sends nothing to Cronitor and does not write the crontab. Does not apply to --file or Windows scheduled-task sync.")
- discoverCmd.Flags().StringArrayVarP(&excludeFromName, "exclude-from-name", "e", excludeFromName, "Substring to exclude from auto-generated monitor name e.g. $ cronitor sync -e '> /dev/null' -e '/path/to/app'")
+ discoverCmd.Flags().StringArrayVarP(&excludeFromName, "exclude-from-name", "e", excludeFromName, "Substring to exclude from auto-generated monitor name e.g. $ cronitor jobs sync -e '> /dev/null' -e '/path/to/app'")
discoverCmd.Flags().BoolVar(&noAutoDiscover, "no-auto-discover", noAutoDiscover, "Do not attach an automatic discover job to this crontab, or remove if already attached.")
discoverCmd.Flags().BoolVar(&noStdoutPassthru, "no-stdout", noStdoutPassthru, "Do not send cron job output to Cronitor when your job completes.")
discoverCmd.Flags().StringVar(¬ificationList, "notification-list", notificationList, "Set this alert list on new and existing monitors. Without it, sync sends no alert list: new monitors get Cronitor's default list and existing monitors keep theirs.")
diff --git a/cmd/jobs.go b/cmd/jobs.go
new file mode 100644
index 00000000..e6e8b44a
--- /dev/null
+++ b/cmd/jobs.go
@@ -0,0 +1,33 @@
+package cmd
+
+import (
+ "github.com/spf13/cobra"
+)
+
+// jobsCmd groups the commands that read or change cron jobs on this machine.
+// sync, list, shell, and dash are only available here. The root command does
+// not keep those names as aliases or hidden forwarders.
+var jobsCmd = &cobra.Command{
+ Use: "jobs",
+ Short: "Sync, list, and run the cron jobs on this machine",
+ Long: `Commands for the cron jobs on this machine.
+
+ $ cronitor jobs sync
+ > Add monitoring to new cron jobs and sync changes
+
+ $ cronitor jobs list
+ > List cron jobs
+
+ $ cronitor jobs shell
+ > Run commands from a cron-like shell
+
+ $ cronitor jobs dash
+ > Start the web dashboard
+
+sync accepts the alias discover:
+ $ cronitor jobs discover`,
+}
+
+func init() {
+ RootCmd.AddCommand(jobsCmd)
+}
diff --git a/cmd/jobs_test.go b/cmd/jobs_test.go
new file mode 100644
index 00000000..a5cb1b8b
--- /dev/null
+++ b/cmd/jobs_test.go
@@ -0,0 +1,65 @@
+package cmd
+
+import (
+ "strings"
+ "testing"
+)
+
+// TestJobsCommandLayout locks the clean break: sync, list, shell, and dash
+// live only under jobs, and discover is only an alias of jobs sync.
+func TestJobsCommandLayout(t *testing.T) {
+ got := map[string]bool{}
+ for _, c := range jobsCmd.Commands() {
+ if c.Name() == "help" {
+ continue
+ }
+ got[c.Name()] = true
+ if c.Parent() != jobsCmd {
+ t.Errorf("%s parent = %v", c.Name(), c.Parent())
+ }
+ }
+ for _, name := range []string{"sync", "list", "shell", "dash"} {
+ if !got[name] {
+ t.Errorf("jobs is missing %s", name)
+ }
+ }
+ if len(got) != 4 {
+ t.Errorf("jobs subcommands = %v", got)
+ }
+
+ aliasOK := false
+ for _, alias := range discoverCmd.Aliases {
+ if alias == "discover" {
+ aliasOK = true
+ }
+ }
+ if !aliasOK {
+ t.Fatalf("sync aliases = %v", discoverCmd.Aliases)
+ }
+ viaAlias, _, err := RootCmd.Find([]string{"jobs", "discover"})
+ if err != nil || viaAlias != discoverCmd {
+ t.Fatalf("jobs discover resolved to %v (%v)", viaAlias, err)
+ }
+ for _, flag := range []string{"auto", "dry-run", "format", "with-monitored", "silent"} {
+ if discoverCmd.Flags().Lookup(flag) == nil {
+ t.Errorf("sync is missing --%s", flag)
+ }
+ }
+ if dashCmd.Flags().Lookup("mcp-instance") == nil || dashCmd.Flags().Lookup("mcp") == nil {
+ t.Fatal("dash is missing --mcp-instance or --mcp")
+ }
+ if listCmd.Flags().Lookup("json") == nil {
+ t.Fatal("list is missing --json")
+ }
+
+ for _, name := range []string{"sync", "discover", "list", "shell", "dash"} {
+ found, _, findErr := RootCmd.Find([]string{name})
+ if findErr == nil || !strings.Contains(findErr.Error(), "unknown command") || !strings.Contains(findErr.Error(), `"`+name+`"`) {
+ path := ""
+ if found != nil {
+ path = found.CommandPath()
+ }
+ t.Errorf("root %s: %v (%s)", name, findErr, path)
+ }
+ }
+}
diff --git a/cmd/list.go b/cmd/list.go
index 2873bdf3..89a29ea3 100644
--- a/cmd/list.go
+++ b/cmd/list.go
@@ -18,16 +18,16 @@ var listCmd = &cobra.Command{
Use: "list ",
Short: "Search for and list all cron jobs",
Long: `
-Cronitor list scans for cron jobs and displays them in an easy to read format.
+cronitor jobs list scans for cron jobs and displays them in an easy to read format.
Example:
- $ cronitor list
+ $ cronitor jobs list
> List all cron jobs in your user crontab and system directory
- $ cronitor list /path/to/crontab
+ $ cronitor jobs list /path/to/crontab
> Instead of the user crontab, list the jobs in a provided a crontab file (or directory of crontabs)
- $ cronitor list --json
+ $ cronitor jobs list --json
> Output all discovered cron jobs as JSON
`,
Args: func(cmd *cobra.Command, args []string) error {
@@ -53,7 +53,7 @@ Example:
}
func init() {
- RootCmd.AddCommand(listCmd)
+ jobsCmd.AddCommand(listCmd)
listCmd.Flags().BoolVarP(&printJSON, "json", "j", false, "Output as JSON")
}
diff --git a/cmd/shell.go b/cmd/shell.go
index f65df079..29bb7080 100644
--- a/cmd/shell.go
+++ b/cmd/shell.go
@@ -12,10 +12,10 @@ var shellCmd = &cobra.Command{
Use: "shell",
Short: "Run commands from a cron-like shell",
Long: `
-Cronitor shell allows you to run commands like cron does. Commands run from the prompt start from your home directory, with reduced shell functionality and no shared environment variables.
+cronitor jobs shell runs commands like cron does. Commands run from the prompt start from your home directory, with reduced shell functionality and no shared environment variables.
Example:
- $ cronitor shell
+ $ cronitor jobs shell
~ $
`,
@@ -72,5 +72,5 @@ Example:
}
func init() {
- RootCmd.AddCommand(shellCmd)
+ jobsCmd.AddCommand(shellCmd)
}
diff --git a/cmd/shell_shim_sync_test.go b/cmd/shell_shim_sync_test.go
index b9894abd..415b4b72 100644
--- a/cmd/shell_shim_sync_test.go
+++ b/cmd/shell_shim_sync_test.go
@@ -18,7 +18,7 @@ import (
"github.com/spf13/viper"
)
-// runSync drives `cronitor sync` itself. Tests must not assign line.Code and
+// runSync drives `cronitor jobs sync` itself. Tests must not assign line.Code and
// call Write; that skips the flag handling and the API round trip.
func runSync(t *testing.T, serverURL, path string, extra ...string) string {
t.Helper()
@@ -71,7 +71,7 @@ func runSyncArgs(t *testing.T, serverURL, path string, extra ...string) string {
}
// Execute on the subcommand is ignored: cobra always runs from the root.
- args := []string{"--config", cfg, "sync"}
+ args := []string{"--config", cfg, "jobs", "sync"}
args = append(args, extra...)
args = append(args, path)
RootCmd.SetArgs(args)
diff --git a/cmd/sync_rerun_test.go b/cmd/sync_rerun_test.go
index a113b7d7..d909ee4d 100644
--- a/cmd/sync_rerun_test.go
+++ b/cmd/sync_rerun_test.go
@@ -546,7 +546,7 @@ func TestSyncRerunTimezoneChangeSendsTimezone(t *testing.T) {
}
}
-// Pipelines such as "cronitor sync --auto file | crontab -" read stdout, so
+// Pipelines such as "cronitor jobs sync --auto file | crontab -" read stdout, so
// --auto prints the crontab even when nothing changed, including --dry-run.
func TestSyncAutoPrintsCrontabWhenNothingChanged(t *testing.T) {
for _, extra := range [][]string{{"--auto"}, {"--auto", "--dry-run"}} {
@@ -604,7 +604,7 @@ func TestSyncAutoPrintsOriginalWhenShimInstallFails(t *testing.T) {
}
// An API failure used to os.Exit inside applyPlan, skipping the deferred
-// print. `cronitor sync --auto file | crontab -` then installed an empty crontab.
+// print. `cronitor jobs sync --auto file | crontab -` then installed an empty crontab.
func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) {
withSyncFixture(t)
withNotificationList(t, "")
@@ -656,7 +656,7 @@ func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) {
}
// A missing or unwritable file used to print nothing and exit 0, so
-// `cronitor sync --auto file | crontab -` installed an empty crontab.
+// `cronitor jobs sync --auto file | crontab -` installed an empty crontab.
func TestSyncAutoExitsWhenCrontabMissingOrUnwritable(t *testing.T) {
withSyncFixture(t)
withNotificationList(t, "")
diff --git a/dockerfile b/dockerfile
index 741206e4..d9aa1343 100644
--- a/dockerfile
+++ b/dockerfile
@@ -22,4 +22,4 @@ RUN case "${TARGETARCH}" in amd64|arm64|arm) ;; \
EXPOSE 9000
-CMD ["cronitor", "dash", "--port", "9000"]
+CMD ["cronitor", "jobs", "dash", "--port", "9000"]
diff --git a/docs/IP-ACCESS-RESTRICTIONS.md b/docs/IP-ACCESS-RESTRICTIONS.md
index 2b57035f..92e2c99e 100644
--- a/docs/IP-ACCESS-RESTRICTIONS.md
+++ b/docs/IP-ACCESS-RESTRICTIONS.md
@@ -17,7 +17,7 @@ Set the `CRONITOR_ALLOWED_IPS` environment variable with a comma-separated list
export CRONITOR_ALLOWED_IPS="192.168.1.0/24,10.0.0.1,2001:db8::/32"
# Start the dashboard
-cronitor dash
+cronitor jobs dash
```
### Command Line Configuration
diff --git a/docs/MCP_INTEGRATION.md b/docs/MCP_INTEGRATION.md
index eed828a8..4cbffbf2 100644
--- a/docs/MCP_INTEGRATION.md
+++ b/docs/MCP_INTEGRATION.md
@@ -17,17 +17,17 @@ Cronitor CLI includes built-in support for the [Model Context Protocol (MCP)](ht
The MCP integration has two components:
-1. **Dashboard** (`cronitor dash`) - The web UI that manages cron jobs. This **must be running on the server where your cron jobs live**.
+1. **Dashboard** (`cronitor jobs dash`) - The web UI that manages cron jobs. This **must be running on the server where your cron jobs live**.
-2. **MCP Server** (`cronitor dash --mcp-instance`) - A bridge process that your AI tool spawns locally. It communicates with your AI tool via stdio and connects to the dashboard over HTTP.
+2. **MCP Server** (`cronitor jobs dash --mcp-instance`) - A bridge process that your AI tool spawns locally. It communicates with your AI tool via stdio and connects to the dashboard over HTTP.
```
-┌─────────────────────┐ stdio ┌─────────────────────┐ HTTP ┌─────────────────────┐
-│ AI Tool │ ◄─────────────► │ MCP Server │ ◄─────────────► │ Dashboard │
-│ (Claude Code, │ │ (cronitor dash │ │ (cronitor dash) │
-│ Cursor, etc.) │ │ --mcp-instance) │ │ on your server │
-└─────────────────────┘ └─────────────────────┘ └─────────────────────┘
- Your machine Your machine Your server
+┌─────────────────────┐ stdio ┌──────────────────────────┐ HTTP ┌──────────────────────────┐
+│ AI Tool │ ◄─────────────► │ MCP Server │ ◄─────────────► │ Dashboard │
+│ (Claude Code, │ │ (cronitor jobs dash │ │ (cronitor jobs dash) │
+│ Cursor, etc.) │ │ --mcp-instance) │ │ on your server │
+└─────────────────────┘ └──────────────────────────┘ └──────────────────────────┘
+ Your machine Your machine Your server
```
## Quick Start
@@ -44,7 +44,7 @@ export CRONITOR_DASH_PASS=PASS
cronitor configure
# Start the dashboard (runs on port 9000 by default)
-cronitor dash
+cronitor jobs dash
```
**Important:** The dashboard must be running and accessible for the MCP server to work. For production use, consider running it as a systemd service or in Docker.
@@ -59,7 +59,7 @@ Configure your AI tool to spawn the Cronitor MCP server. Most MCP-compatible too
"mcpServers": {
"cronitor": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"]
+ "args": ["jobs", "dash", "--mcp-instance", "default"]
}
}
}
@@ -116,15 +116,15 @@ To connect to multiple dashboards, configure each as a separate MCP server:
"mcpServers": {
"cronitor": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"]
+ "args": ["jobs", "dash", "--mcp-instance", "default"]
},
"cronitor-prod": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "production"]
+ "args": ["jobs", "dash", "--mcp-instance", "production"]
},
"cronitor-staging": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "staging"]
+ "args": ["jobs", "dash", "--mcp-instance", "staging"]
}
}
}
@@ -139,7 +139,7 @@ You can override the config file path per-project using an environment variable:
"mcpServers": {
"cronitor-project": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"],
+ "args": ["jobs", "dash", "--mcp-instance", "default"],
"env": {
"CRONITOR_CONFIG": "/path/to/project/cronitor.json"
}
@@ -278,7 +278,7 @@ Some MCP clients support running commands over SSH directly:
"command": "ssh",
"args": [
"user@your-server",
- "cronitor dash --mcp-instance default"
+ "cronitor jobs dash --mcp-instance default"
]
}
}
@@ -304,10 +304,10 @@ The MCP server respects these environment variables:
```bash
# Test MCP server startup with default instance
-cronitor dash --mcp-instance default
+cronitor jobs dash --mcp-instance default
# Test with specific instance
-cronitor dash --mcp-instance production
+cronitor jobs dash --mcp-instance production
```
### Check Configuration
@@ -330,7 +330,7 @@ cronitor configure
**"Connection refused"**
- Check that the dashboard URL is correct
-- Verify the dashboard is running: `cronitor dash` in another terminal
+- Verify the dashboard is running: `cronitor jobs dash` in another terminal
- Check network connectivity and any firewalls
- For remote dashboards, ensure your SSH tunnel is active
diff --git a/docs/MCP_PROMPTS.md b/docs/MCP_PROMPTS.md
index d0d25efa..f622a8c9 100644
--- a/docs/MCP_PROMPTS.md
+++ b/docs/MCP_PROMPTS.md
@@ -65,12 +65,12 @@ You can add per-server instructions in your MCP configuration file. This is usef
"mcpServers": {
"cronitor": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"],
+ "args": ["jobs", "dash", "--mcp-instance", "default"],
"description": "Local Cronitor dashboard - Use for development cron jobs"
},
"cronitor-production": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "production"],
+ "args": ["jobs", "dash", "--mcp-instance", "production"],
"description": "Production Cronitor - CAUTION: Changes affect live system!"
}
}
@@ -84,11 +84,11 @@ Some tools also support an `instructions` field for more detailed guidance:
"mcpServers": {
"cronitor": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"]
+ "args": ["jobs", "dash", "--mcp-instance", "default"]
},
"cronitor-production": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "production"]
+ "args": ["jobs", "dash", "--mcp-instance", "production"]
}
},
"instructions": {
diff --git a/fixtures/shim/crontab.expected b/fixtures/shim/crontab.expected
index 81ffd21d..413a872d 100644
--- a/fixtures/shim/crontab.expected
+++ b/fixtures/shim/crontab.expected
@@ -1,5 +1,5 @@
SHELL=/etc/cronitor/shell
-# Fixture for `cronitor sync` with the shell shim.
+# Fixture for `cronitor jobs sync` with the shell shim.
# lib/shell_shim_golden_test.go writes this with every job monitored and
# compares the result to crontab.expected (run with -update to regenerate).
# cmd/shell_shim_fixture_test.go runs each job line, before and after, and
diff --git a/fixtures/shim/crontab.format-exec.expected b/fixtures/shim/crontab.format-exec.expected
index beac8a45..79168cce 100644
--- a/fixtures/shim/crontab.format-exec.expected
+++ b/fixtures/shim/crontab.format-exec.expected
@@ -1,4 +1,4 @@
-# Fixture for `cronitor sync` with the shell shim.
+# Fixture for `cronitor jobs sync` with the shell shim.
# lib/shell_shim_golden_test.go writes this with every job monitored and
# compares the result to crontab.expected (run with -update to regenerate).
# cmd/shell_shim_fixture_test.go runs each job line, before and after, and
diff --git a/fixtures/shim/crontab.format-short.expected b/fixtures/shim/crontab.format-short.expected
index 48821f3f..81f4fed2 100644
--- a/fixtures/shim/crontab.format-short.expected
+++ b/fixtures/shim/crontab.format-short.expected
@@ -1,5 +1,5 @@
SHELL=/etc/cronitor/shell
-# Fixture for `cronitor sync` with the shell shim.
+# Fixture for `cronitor jobs sync` with the shell shim.
# lib/shell_shim_golden_test.go writes this with every job monitored and
# compares the result to crontab.expected (run with -update to regenerate).
# cmd/shell_shim_fixture_test.go runs each job line, before and after, and
diff --git a/fixtures/shim/crontab.input b/fixtures/shim/crontab.input
index 4c5f24b5..80bf24ea 100644
--- a/fixtures/shim/crontab.input
+++ b/fixtures/shim/crontab.input
@@ -1,4 +1,4 @@
-# Fixture for `cronitor sync` with the shell shim.
+# Fixture for `cronitor jobs sync` with the shell shim.
# lib/shell_shim_golden_test.go writes this with every job monitored and
# compares the result to crontab.expected (run with -update to regenerate).
# cmd/shell_shim_fixture_test.go runs each job line, before and after, and
diff --git a/lib/crontab.go b/lib/crontab.go
index b8a7e252..687f1849 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -914,6 +914,124 @@ func (l Line) GetEnvVarValue() string {
return ""
}
+// ensureAutoOnJobsSubcommand inserts --auto after `jobs sync` or
+// `jobs discover`, including when inherited flags sit between the two words
+// (`jobs --hostname box sync`). sync is written as discover so
+// IsAutoDiscoverCommand still matches. Flag values are not rewritten.
+func ensureAutoOnJobsSubcommand(args []string) []string {
+ cleaned := make([]string, 0, len(args)+1)
+ for _, arg := range args {
+ if arg == "--auto" || strings.HasPrefix(arg, "--auto=") {
+ continue
+ }
+ cleaned = append(cleaned, arg)
+ }
+ args = cleaned
+
+ if idx := jobsSubcommandIndex(args); idx >= 0 {
+ args = append([]string{}, args...)
+ args[idx] = "discover"
+ return insertArgAfter(args, idx, "--auto")
+ }
+ for _, arg := range args {
+ if arg == "jobs" {
+ return args
+ }
+ }
+ for i, arg := range args {
+ if arg == "discover" {
+ return insertArgAfter(args, i, "--auto")
+ }
+ }
+ return args
+}
+
+func jobsSubcommandIndex(args []string) int {
+ for i := 0; i < len(args); i++ {
+ if args[i] != "jobs" {
+ continue
+ }
+ j := i + 1
+ for j < len(args) {
+ tok := args[j]
+ if tok == "sync" || tok == "discover" {
+ return j
+ }
+ if !strings.HasPrefix(tok, "-") || tok == "-" || tok == "--" {
+ break
+ }
+ step := inheritedFlagWidth(tok)
+ if step < 1 || j+step > len(args) {
+ break
+ }
+ j += step
+ }
+ }
+ return -1
+}
+
+func inheritedFlagWidth(tok string) int {
+ if strings.HasPrefix(tok, "--") {
+ name, _, hasEq := strings.Cut(strings.TrimPrefix(tok, "--"), "=")
+ if hasEq || inheritedBoolFlag(name) {
+ return 1
+ }
+ return 2
+ }
+ body := strings.TrimPrefix(tok, "-")
+ if strings.Contains(body, "=") {
+ return 1
+ }
+ takesNext := false
+ for i := 0; i < len(body); i++ {
+ letter := body[i : i+1]
+ if inheritedBoolFlag(letter) {
+ continue
+ }
+ if inheritedValueFlag(letter) {
+ if i < len(body)-1 {
+ return 1
+ }
+ takesNext = true
+ break
+ }
+ if len(body) == 1 {
+ return 2
+ }
+ return 1
+ }
+ if takesNext {
+ return 2
+ }
+ return 1
+}
+
+func inheritedBoolFlag(name string) bool {
+ switch name {
+ case "verbose", "v", "use-dev", "help", "h":
+ return true
+ default:
+ return false
+ }
+}
+
+func inheritedValueFlag(name string) bool {
+ switch name {
+ case "config", "c", "env", "api-key", "k", "ping-api-key", "p", "ping-api-host", "hostname", "n", "log", "l", "users", "u", "api-version":
+ return true
+ default:
+ return false
+ }
+}
+
+func insertArgAfter(args []string, i int, tok string) []string {
+ out := make([]string, 0, len(args)+1)
+ out = append(out, args[:i+1]...)
+ out = append(out, tok)
+ out = append(out, args[i+1:]...)
+ return out
+}
+
func createAutoDiscoverLine(crontab *Crontab) *Line {
cronExpression := fmt.Sprintf("%d * * * *", randomMinute())
if crontab.UsesSixFieldExpressions {
@@ -921,7 +1039,9 @@ func createAutoDiscoverLine(crontab *Crontab) *Line {
}
// Normalize the command so it can be run reliably from crontab.
- commandToRun := strings.Join(os.Args, " ")
+ // Place --auto on the jobs subcommand before the legacy string cleanups,
+ // which remove `-v` inside longer tokens such as `--verbose`.
+ commandToRun := strings.Join(ensureAutoOnJobsSubcommand(os.Args), " ")
commandToRun = strings.Replace(commandToRun, "--save", "", -1)
commandToRun = strings.Replace(commandToRun, "--verbose", "", -1)
commandToRun = strings.Replace(commandToRun, "-v", "", -1)
@@ -931,10 +1051,6 @@ func createAutoDiscoverLine(crontab *Crontab) *Line {
commandToRun = strings.Replace(commandToRun, crontab.Filename, crontab.CanonicalName(), -1)
}
- // Remove existing --auto flag before adding a new one to prevent doubling up
- commandToRun = strings.Replace(commandToRun, "--auto", "", -1)
- commandToRun = strings.Replace(commandToRun, " discover", " discover --auto ", -1)
-
line := Line{}
line.CronExpression = cronExpression
line.CommandToRun = commandToRun
diff --git a/lib/crontab_test.go b/lib/crontab_test.go
index 4b07343f..4421712c 100644
--- a/lib/crontab_test.go
+++ b/lib/crontab_test.go
@@ -1,6 +1,7 @@
package lib
import (
+ "os"
"regexp"
"strings"
"testing"
@@ -251,3 +252,52 @@ func TestLineWriteWithNoStdoutAndEnv(t *testing.T) {
t.Errorf("Expected 'cronitor --env testing exec --no-stdout test123' in output but got: %s", output)
}
}
+
+func TestCreateAutoDiscoverLineTargetsJobsSubcommand(t *testing.T) {
+ old := os.Args
+ t.Cleanup(func() { os.Args = old })
+ ct := &Crontab{}
+
+ os.Args = []string{"cronitor", "jobs", "sync", "--auto", "--exclude-from-name", "my discover job", "/tmp/crontab"}
+ line := createAutoDiscoverLine(ct)
+ if !strings.Contains(line.CommandToRun, "jobs discover --auto") {
+ t.Fatalf("sync invocation = %q", line.CommandToRun)
+ }
+ if strings.Contains(line.CommandToRun, "discover --auto job") {
+ t.Fatalf("exclude text was rewritten: %q", line.CommandToRun)
+ }
+ if !line.IsAutoDiscoverCommand() {
+ t.Fatalf("plumbing line not recognized: %q", line.CommandToRun)
+ }
+
+ os.Args = []string{"cronitor", "--hostname", "sync", "jobs", "sync", "--auto", "/tmp/crontab"}
+ line = createAutoDiscoverLine(ct)
+ if !strings.Contains(line.CommandToRun, "--hostname sync jobs discover --auto") {
+ t.Fatalf("hostname value rewritten: %q", line.CommandToRun)
+ }
+
+ os.Args = []string{"cronitor", "jobs", "--hostname", "box", "sync", "--auto", "/tmp/crontab"}
+ line = createAutoDiscoverLine(ct)
+ if !strings.Contains(line.CommandToRun, "jobs --hostname box discover --auto") {
+ t.Fatalf("flag between jobs and sync = %q", line.CommandToRun)
+ }
+
+ os.Args = []string{"cronitor", "jobs", "--verbose", "sync", "--auto", "/tmp/crontab"}
+ line = createAutoDiscoverLine(ct)
+ if !strings.Contains(line.CommandToRun, "discover --auto") || strings.Contains(line.CommandToRun, " sync") {
+ t.Fatalf("bool flag between jobs and sync = %q", line.CommandToRun)
+ }
+
+ os.Args = []string{"cronitor", "jobs", "discover", "--auto", "/tmp/crontab"}
+ line = createAutoDiscoverLine(ct)
+ if !strings.Contains(line.CommandToRun, "jobs discover --auto") || strings.Contains(line.CommandToRun, "--auto --auto") {
+ t.Fatalf("discover alias = %q", line.CommandToRun)
+ }
+
+ if (&Line{CommandToRun: "cronitor jobs sync --auto /etc/crontab"}).IsAutoDiscoverCommand() {
+ t.Fatal("jobs sync --auto must stay a normal job")
+ }
+ if !(&Line{CommandToRun: "cronitor discover --auto /etc/crontab"}).IsAutoDiscoverCommand() {
+ t.Fatal("historical discover --auto line must still be plumbing")
+ }
+}
diff --git a/lib/crontab_wrap_test.go b/lib/crontab_wrap_test.go
index 3c463105..0d035c89 100644
--- a/lib/crontab_wrap_test.go
+++ b/lib/crontab_wrap_test.go
@@ -47,7 +47,10 @@ func TestWrapDetection(t *testing.T) {
{"suffix is not the binary", `0 * * * * notcronitor exec abc /bin/true`, "", "notcronitor exec abc /bin/true", false},
{"cronitor-helper", `0 * * * * cronitor-helper exec abc /bin/true`, "", "cronitor-helper exec abc /bin/true", false},
{"unknown flag takes no value", `0 * * * * cronitor --bogus v exec k1 /bin/true`, "", "cronitor --bogus v exec k1 /bin/true", false},
- {"discover subcommand", `30 * * * * cronitor discover /etc/crontab`, "", "cronitor discover /etc/crontab", false},
+ {"historical discover line", `30 * * * * cronitor discover /etc/crontab`, "", "cronitor discover /etc/crontab", false},
+ {"jobs discover", `30 * * * * cronitor jobs discover /etc/crontab`, "", "cronitor jobs discover /etc/crontab", false},
+ {"jobs sync", `30 * * * * cronitor jobs sync /etc/crontab`, "", "cronitor jobs sync /etc/crontab", false},
+ {"jobs dash", `30 * * * * cronitor jobs dash`, "", "cronitor jobs dash", false},
{"simple quotes kept", `0 * * * * cronitor exec abc echo "hi there"`, "abc", `echo "hi there"`, true},
{"quoted simple word kept", `0 * * * * cronitor exec k1 'my script.sh'`, "k1", `'my script.sh'`, true},
{"escaped word kept", `0 * * * * cronitor exec k1 \%`, "k1", `\%`, true},
diff --git a/tests/cleanup-ci-monitors.sh b/tests/cleanup-ci-monitors.sh
index 3d11edf6..ee2ea03b 100755
--- a/tests/cleanup-ci-monitors.sh
+++ b/tests/cleanup-ci-monitors.sh
@@ -2,7 +2,7 @@
#
# Delete the monitors that the CI test suite creates in the Cronitor account.
#
-# `cronitor discover` names each monitor after the machine it runs on:
+# `cronitor jobs sync` names each monitor after the machine it runs on:
# Linux: "[] "
# Windows: "/"
# Hosted runner images reuse hostnames across runs, so the workflow renames
diff --git a/tests/real-cron.sh b/tests/real-cron.sh
index 9997efc3..1d97cced 100755
--- a/tests/real-cron.sh
+++ b/tests/real-cron.sh
@@ -87,7 +87,7 @@ EOF
python3 -I "$repo/tests/real-cron-fixture.py" lines "$repo/fixtures/shim/crontab.input" >> "$work/crontab"
echo '{"CRONITOR_API_KEY":"real-cron-test-key-0000"}' > "$work/cronitor.json"
echo '{}' > "$work/other.json"
-"$work/bin/cronitor" --config "$work/cronitor.json" sync --auto --silent --format=short "$work/crontab"
+"$work/bin/cronitor" --config "$work/cronitor.json" jobs sync --auto --silent --format=short "$work/crontab"
# A line added after sync has no marker. It must survive a broken binary.
echo "* * * * * echo raw >> $out/raw.log" >> "$work/crontab"
echo "--- synced crontab"
diff --git a/tests/test-discover.bats b/tests/test-discover.bats
index b445b96d..fb5ef82c 100755
--- a/tests/test-discover.bats
+++ b/tests/test-discover.bats
@@ -21,78 +21,78 @@ teardown() {
#################
@test "Discover reads file and sends PUT" {
- ../cronitor $CRONITOR_ARGS discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY" --log $CLI_LOGFILE > /dev/null
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY" --log $CLI_LOGFILE > /dev/null
grep -q "Request" $CLI_LOGFILE
}
@test "Discover parses response and rewrites crontab" {
skip_if_windows "no crontabs on Windows"
- run ../cronitor $CRONITOR_ARGS discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY"
+ run ../cronitor $CRONITOR_ARGS jobs discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY"
echo "$output" | grep "slave_status.sh" | grep -q "cronitor exec"
}
@test "Discover is silent when being run under exec" {
- [[ $(../cronitor $CRONITOR_ARGS exec d3x0c1 ../cronitor $CRONITOR_ARGS discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY" | wc -c) -eq 0 ]]
+ [[ $(../cronitor $CRONITOR_ARGS exec d3x0c1 ../cronitor $CRONITOR_ARGS jobs discover --auto $FIXTURES_DIR/crontab.txt -k "$API_KEY" | wc -c) -eq 0 ]]
}
@test "Discover correctly parses crontab with username" {
skip_if_windows "no crontabs on Windows"
echo "* * * * * $CLI_USERNAME echo 'username parse'" | cat - $FIXTURES_DIR/crontab.txt > $CLI_CRONTAB_TEMP
- ../cronitor $CRONITOR_ARGS discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "$CLI_USERNAME cronitor exec"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "$CLI_USERNAME cronitor exec"
}
@test "Discover correctly parses crontab with 6 digits" {
skip_if_windows "no crontabs on Windows"
echo "* * * * * 0 echo 'six dig parse'" | cat - $FIXTURES_DIR/crontab.txt > $CLI_CRONTAB_TEMP
- ../cronitor $CRONITOR_ARGS discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY"| grep "echo '" | grep -q "0 cronitor exec"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY"| grep "echo '" | grep -q "0 cronitor exec"
}
@test "Discover correctly parses crontab with 6th digit DoW string range" {
skip_if_windows "no crontabs on Windows"
echo "* * * * * Mon-Fri echo 'DoW string parse'" | cat - $FIXTURES_DIR/crontab.txt > $CLI_CRONTAB_TEMP
- ../cronitor $CRONITOR_ARGS discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon-Fri cronitor exec"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon-Fri cronitor exec"
}
@test "Discover correctly parses crontab with 6th digit DoW string list" {
skip_if_windows "no crontabs on Windows"
echo "* * * * * Mon,Wed,Fri echo 'DoW string list parse'" | cat - $FIXTURES_DIR/crontab.txt > $CLI_CRONTAB_TEMP
- ../cronitor $CRONITOR_ARGS discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon,Wed,Fri cronitor exec"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon,Wed,Fri cronitor exec"
}
@test "Discover correctly parses crontab with 6th digit DoW string name" {
skip_if_windows "no crontabs on Windows"
echo "* * * * * Mon echo 'DoW string name parse'" | cat - $FIXTURES_DIR/crontab.txt > $CLI_CRONTAB_TEMP
- ../cronitor $CRONITOR_ARGS discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon cronitor exec"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $CLI_CRONTAB_TEMP -k "$API_KEY" | grep "echo '" | grep -q "Mon cronitor exec"
}
@test "Discover rewrites crontab in place" {
skip_if_windows "no crontabs on Windows"
cp $FIXTURES_DIR/crontab.txt $TMPFILE
- ../cronitor $CRONITOR_ARGS discover --auto $TMPFILE -k "$API_KEY" > /dev/null
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $TMPFILE -k "$API_KEY" > /dev/null
grep "slave_status.sh" $TMPFILE | grep -q "cronitor exec"
}
@test "Discover ignores meta crontab entries" {
cp $FIXTURES_DIR/metacrontab.txt $TMPFILE
- ../cronitor $CRONITOR_ARGS discover --auto $TMPFILE -k "$API_KEY" > /dev/null
+ ../cronitor $CRONITOR_ARGS jobs discover --auto $TMPFILE -k "$API_KEY" > /dev/null
run -1 bash -c 'grep "cron.hourly" $TMPFILE | grep -q "cronitor exec"'
}
@test "Discover adds no-stdout flag when supplied" {
- run -1 bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --no-stdout | grep "cronitor exec" | grep -q "no-stdout"'
+ run -1 bash -c '../cronitor $CRONITOR_ARGS jobs discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --no-stdout | grep "cronitor exec" | grep -q "no-stdout"'
}
-# discover --auto on one file prints the crontab on stdout and --verbose
+# jobs discover --auto on one file prints the crontab on stdout and --verbose
# request logs on stderr. Windows does not reserve stdout, so those logs
# stay there. Read both streams: the needles are not in the crontab.
# bash -c does not see this test's variables unless they are passed in.
@test "Discover omits 'notifications' if notification-list not specificed" {
run -1 env API_KEY="$API_KEY" FIXTURES_DIR="$FIXTURES_DIR" CRONITOR_ARGS="$CRONITOR_ARGS" \
- bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"'
+ bash -c '../cronitor $CRONITOR_ARGS jobs discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"'
}
@test "Discover includes custom notification-list" {
- ../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name 2>&1 | grep -q "test-list-name"
+ ../cronitor $CRONITOR_ARGS jobs discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name 2>&1 | grep -q "test-list-name"
}
@test "Discover reads all of the crontabs in a directory" {
diff --git a/tests/test-list.bats b/tests/test-list.bats
index 9c927cc1..90494b02 100755
--- a/tests/test-list.bats
+++ b/tests/test-list.bats
@@ -15,7 +15,7 @@ setup() {
@test "List reads crontab and writes table" {
skip_if_linux "We can't figure out why this isn't working"
- run ../cronitor $CRONITOR_ARGS list $FIXTURES_DIR/crontab.txt
+ run ../cronitor $CRONITOR_ARGS jobs list $FIXTURES_DIR/crontab.txt
# echo "Real file\n" >&3
# cat $FIXTURES_DIR/crontab.txt >&3
# echo "Processed file" >&3
@@ -24,5 +24,5 @@ setup() {
}
@test "List reads crontab and formats table correctly" {
- ../cronitor $CRONITOR_ARGS list $FIXTURES_DIR/crontab.txt | grep -q "\-----"
+ ../cronitor $CRONITOR_ARGS jobs list $FIXTURES_DIR/crontab.txt | grep -q "\-----"
}
\ No newline at end of file
diff --git a/web/src/components/Docs.js b/web/src/components/Docs.js
index 54359f7e..881f1dfe 100644
--- a/web/src/components/Docs.js
+++ b/web/src/components/Docs.js
@@ -382,7 +382,7 @@ export default function Docs() {
Understanding the CLI Connection
- When the dashboard is running and monitoring is enabled, job names and schedules are synced automatically with Cronitor. There is no need to run "cronitor sync" manually if you also use the dashboard. For job names, this is a 2-way sync: Names changed on Cronitor will show up on this dashboard, and names changed here will be synced with Cronitor. Schedules are only synced one-way: Changes made on Cronitor do not impact your actual job schedule.
+ When the dashboard is running and monitoring is enabled, job names and schedules are synced automatically with Cronitor. There is no need to run "cronitor jobs sync" manually if you also use the dashboard. For job names, this is a 2-way sync: Names changed on Cronitor will show up on this dashboard, and names changed here will be synced with Cronitor. Schedules are only synced one-way: Changes made on Cronitor do not impact your actual job schedule.
Version Management
@@ -432,13 +432,13 @@ cronitor update
{`# Connect to default instance
-cronitor dash --mcp-instance default
+cronitor jobs dash --mcp-instance default
# Connect to production instance
-cronitor dash --mcp-instance production
+cronitor jobs dash --mcp-instance production
# Connect to staging instance
-cronitor dash --mcp-instance staging`}
+cronitor jobs dash --mcp-instance staging`}
Configuring MCP Instances
@@ -487,15 +487,15 @@ cronitor dash --mcp-instance staging`}
"mcpServers": {
"cronitor": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "default"]
+ "args": ["jobs", "dash", "--mcp-instance", "default"]
},
"cronitor-production": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "production"]
+ "args": ["jobs", "dash", "--mcp-instance", "production"]
},
"cronitor-staging": {
"command": "cronitor",
- "args": ["dash", "--mcp-instance", "staging"]
+ "args": ["jobs", "dash", "--mcp-instance", "staging"]
}
}
}`}
@@ -691,7 +691,7 @@ connect = remote-cron-server:9000`}
{`# Start dashboard in safe mode
-cronitor dash --safe-mode`}
+cronitor jobs dash --safe-mode`}
- Prevents cron command modifications
From c36328d3d9c8fb7d3cbf3e2443c8054423bf66cc Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Sun, 8 Nov 2026 08:21:53 +0000
Subject: [PATCH 2/6] Fix jobs unknown-command exit and shrink auto-discover
writer
cronitor jobs with an unknown subcommand now returns an
unknown-command error. The hidden auto-discover line writer only
rewrites the jobs subcommand to discover --auto, and the opt-in
path writes an old discover --auto line in that form.
Co-authored-by: August Flanagan
---
cmd/jobs.go | 8 +++
cmd/jobs_test.go | 18 +++---
lib/crontab.go | 150 +++++++++-----------------------------------
lib/crontab_test.go | 44 +------------
4 files changed, 47 insertions(+), 173 deletions(-)
diff --git a/cmd/jobs.go b/cmd/jobs.go
index e6e8b44a..9b5302b6 100644
--- a/cmd/jobs.go
+++ b/cmd/jobs.go
@@ -26,6 +26,14 @@ var jobsCmd = &cobra.Command{
sync accepts the alias discover:
$ cronitor jobs discover`,
+ // Cobra 1.2 only reports an unknown command for the root. A parent with
+ // subcommands and no Run prints help and exits 0. NoArgs runs once Run
+ // makes the command runnable, so `jobs ` fails the way a root typo does.
+ // Bare `jobs` still prints help.
+ Args: cobra.NoArgs,
+ Run: func(cmd *cobra.Command, args []string) {
+ cmd.Help()
+ },
}
func init() {
diff --git a/cmd/jobs_test.go b/cmd/jobs_test.go
index a5cb1b8b..993f1a29 100644
--- a/cmd/jobs_test.go
+++ b/cmd/jobs_test.go
@@ -40,17 +40,6 @@ func TestJobsCommandLayout(t *testing.T) {
if err != nil || viaAlias != discoverCmd {
t.Fatalf("jobs discover resolved to %v (%v)", viaAlias, err)
}
- for _, flag := range []string{"auto", "dry-run", "format", "with-monitored", "silent"} {
- if discoverCmd.Flags().Lookup(flag) == nil {
- t.Errorf("sync is missing --%s", flag)
- }
- }
- if dashCmd.Flags().Lookup("mcp-instance") == nil || dashCmd.Flags().Lookup("mcp") == nil {
- t.Fatal("dash is missing --mcp-instance or --mcp")
- }
- if listCmd.Flags().Lookup("json") == nil {
- t.Fatal("list is missing --json")
- }
for _, name := range []string{"sync", "discover", "list", "shell", "dash"} {
found, _, findErr := RootCmd.Find([]string{name})
@@ -62,4 +51,11 @@ func TestJobsCommandLayout(t *testing.T) {
t.Errorf("root %s: %v (%s)", name, findErr, path)
}
}
+
+ RootCmd.SetArgs([]string{"jobs", "not-a-command"})
+ t.Cleanup(func() { RootCmd.SetArgs(nil) })
+ execErr := RootCmd.Execute()
+ if execErr == nil || !strings.Contains(execErr.Error(), "unknown command") || !strings.Contains(execErr.Error(), `"not-a-command"`) {
+ t.Fatalf("jobs typo: %v", execErr)
+ }
}
diff --git a/lib/crontab.go b/lib/crontab.go
index 687f1849..8df66ed5 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -284,6 +284,11 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
if noAutoDiscover {
continue // remove the auto-discover line from the crontab if --no-auto-discover flag is passed
}
+ // Opt-in only (--no-auto-discover=false). The default removes this
+ // line and does not add one. The monitor key ignores command text.
+ if !strings.Contains(line.CommandToRun, "jobs discover --auto") {
+ line.CommandToRun = autoDiscoverCommand(c)
+ }
}
// Reset the name and ignored for the next line after we've found its command line
@@ -914,134 +919,29 @@ func (l Line) GetEnvVarValue() string {
return ""
}
-// ensureAutoOnJobsSubcommand inserts --auto after `jobs sync` or
-// `jobs discover`, including when inherited flags sit between the two words
-// (`jobs --hostname box sync`). sync is written as discover so
-// IsAutoDiscoverCommand still matches. Flag values are not rewritten.
-func ensureAutoOnJobsSubcommand(args []string) []string {
- cleaned := make([]string, 0, len(args)+1)
- for _, arg := range args {
+// autoDiscoverCommand is the hidden opt-in plumbing command. sync is written
+// as discover so IsAutoDiscoverCommand still matches. The first sync or
+// discover token after jobs is the subcommand.
+func autoDiscoverCommand(crontab *Crontab) string {
+ args := make([]string, 0, len(os.Args)+1)
+ seenJobs := false
+ replaced := false
+ for _, arg := range os.Args {
if arg == "--auto" || strings.HasPrefix(arg, "--auto=") {
continue
}
- cleaned = append(cleaned, arg)
- }
- args = cleaned
-
- if idx := jobsSubcommandIndex(args); idx >= 0 {
- args = append([]string{}, args...)
- args[idx] = "discover"
- return insertArgAfter(args, idx, "--auto")
- }
- for _, arg := range args {
- if arg == "jobs" {
- return args
- }
- }
- for i, arg := range args {
- if arg == "discover" {
- return insertArgAfter(args, i, "--auto")
- }
- }
- return args
-}
-
-func jobsSubcommandIndex(args []string) int {
- for i := 0; i < len(args); i++ {
- if args[i] != "jobs" {
+ if seenJobs && !replaced && (arg == "sync" || arg == "discover") {
+ args = append(args, "discover", "--auto")
+ replaced = true
continue
}
- j := i + 1
- for j < len(args) {
- tok := args[j]
- if tok == "sync" || tok == "discover" {
- return j
- }
- if !strings.HasPrefix(tok, "-") || tok == "-" || tok == "--" {
- break
- }
- step := inheritedFlagWidth(tok)
- if step < 1 || j+step > len(args) {
- break
- }
- j += step
+ if arg == "jobs" {
+ seenJobs = true
}
+ args = append(args, arg)
}
- return -1
-}
-func inheritedFlagWidth(tok string) int {
- if strings.HasPrefix(tok, "--") {
- name, _, hasEq := strings.Cut(strings.TrimPrefix(tok, "--"), "=")
- if hasEq || inheritedBoolFlag(name) {
- return 1
- }
- return 2
- }
- body := strings.TrimPrefix(tok, "-")
- if strings.Contains(body, "=") {
- return 1
- }
- takesNext := false
- for i := 0; i < len(body); i++ {
- letter := body[i : i+1]
- if inheritedBoolFlag(letter) {
- continue
- }
- if inheritedValueFlag(letter) {
- if i < len(body)-1 {
- return 1
- }
- takesNext = true
- break
- }
- if len(body) == 1 {
- return 2
- }
- return 1
- }
- if takesNext {
- return 2
- }
- return 1
-}
-
-func inheritedBoolFlag(name string) bool {
- switch name {
- case "verbose", "v", "use-dev", "help", "h":
- return true
- default:
- return false
- }
-}
-
-func inheritedValueFlag(name string) bool {
- switch name {
- case "config", "c", "env", "api-key", "k", "ping-api-key", "p", "ping-api-host", "hostname", "n", "log", "l", "users", "u", "api-version":
- return true
- default:
- return false
- }
-}
-
-func insertArgAfter(args []string, i int, tok string) []string {
- out := make([]string, 0, len(args)+1)
- out = append(out, args[:i+1]...)
- out = append(out, tok)
- out = append(out, args[i+1:]...)
- return out
-}
-
-func createAutoDiscoverLine(crontab *Crontab) *Line {
- cronExpression := fmt.Sprintf("%d * * * *", randomMinute())
- if crontab.UsesSixFieldExpressions {
- cronExpression = fmt.Sprintf("* %s", cronExpression)
- }
-
- // Normalize the command so it can be run reliably from crontab.
- // Place --auto on the jobs subcommand before the legacy string cleanups,
- // which remove `-v` inside longer tokens such as `--verbose`.
- commandToRun := strings.Join(ensureAutoOnJobsSubcommand(os.Args), " ")
+ commandToRun := strings.Join(args, " ")
commandToRun = strings.Replace(commandToRun, "--save", "", -1)
commandToRun = strings.Replace(commandToRun, "--verbose", "", -1)
commandToRun = strings.Replace(commandToRun, "-v", "", -1)
@@ -1050,10 +950,18 @@ func createAutoDiscoverLine(crontab *Crontab) *Line {
if len(crontab.Filename) > 0 {
commandToRun = strings.Replace(commandToRun, crontab.Filename, crontab.CanonicalName(), -1)
}
+ return commandToRun
+}
+
+func createAutoDiscoverLine(crontab *Crontab) *Line {
+ cronExpression := fmt.Sprintf("%d * * * *", randomMinute())
+ if crontab.UsesSixFieldExpressions {
+ cronExpression = fmt.Sprintf("* %s", cronExpression)
+ }
line := Line{}
line.CronExpression = cronExpression
- line.CommandToRun = commandToRun
+ line.CommandToRun = autoDiscoverCommand(crontab)
line.FullLine = fmt.Sprintf("%s %s", line.CronExpression, line.CommandToRun)
return &line
}
diff --git a/lib/crontab_test.go b/lib/crontab_test.go
index 4421712c..8e70dac7 100644
--- a/lib/crontab_test.go
+++ b/lib/crontab_test.go
@@ -256,48 +256,10 @@ func TestLineWriteWithNoStdoutAndEnv(t *testing.T) {
func TestCreateAutoDiscoverLineTargetsJobsSubcommand(t *testing.T) {
old := os.Args
t.Cleanup(func() { os.Args = old })
- ct := &Crontab{}
- os.Args = []string{"cronitor", "jobs", "sync", "--auto", "--exclude-from-name", "my discover job", "/tmp/crontab"}
- line := createAutoDiscoverLine(ct)
- if !strings.Contains(line.CommandToRun, "jobs discover --auto") {
+ os.Args = []string{"cronitor", "jobs", "sync", "--auto", "/tmp/crontab"}
+ line := createAutoDiscoverLine(&Crontab{})
+ if !strings.Contains(line.CommandToRun, "jobs discover --auto") || strings.Contains(line.CommandToRun, " sync") {
t.Fatalf("sync invocation = %q", line.CommandToRun)
}
- if strings.Contains(line.CommandToRun, "discover --auto job") {
- t.Fatalf("exclude text was rewritten: %q", line.CommandToRun)
- }
- if !line.IsAutoDiscoverCommand() {
- t.Fatalf("plumbing line not recognized: %q", line.CommandToRun)
- }
-
- os.Args = []string{"cronitor", "--hostname", "sync", "jobs", "sync", "--auto", "/tmp/crontab"}
- line = createAutoDiscoverLine(ct)
- if !strings.Contains(line.CommandToRun, "--hostname sync jobs discover --auto") {
- t.Fatalf("hostname value rewritten: %q", line.CommandToRun)
- }
-
- os.Args = []string{"cronitor", "jobs", "--hostname", "box", "sync", "--auto", "/tmp/crontab"}
- line = createAutoDiscoverLine(ct)
- if !strings.Contains(line.CommandToRun, "jobs --hostname box discover --auto") {
- t.Fatalf("flag between jobs and sync = %q", line.CommandToRun)
- }
-
- os.Args = []string{"cronitor", "jobs", "--verbose", "sync", "--auto", "/tmp/crontab"}
- line = createAutoDiscoverLine(ct)
- if !strings.Contains(line.CommandToRun, "discover --auto") || strings.Contains(line.CommandToRun, " sync") {
- t.Fatalf("bool flag between jobs and sync = %q", line.CommandToRun)
- }
-
- os.Args = []string{"cronitor", "jobs", "discover", "--auto", "/tmp/crontab"}
- line = createAutoDiscoverLine(ct)
- if !strings.Contains(line.CommandToRun, "jobs discover --auto") || strings.Contains(line.CommandToRun, "--auto --auto") {
- t.Fatalf("discover alias = %q", line.CommandToRun)
- }
-
- if (&Line{CommandToRun: "cronitor jobs sync --auto /etc/crontab"}).IsAutoDiscoverCommand() {
- t.Fatal("jobs sync --auto must stay a normal job")
- }
- if !(&Line{CommandToRun: "cronitor discover --auto /etc/crontab"}).IsAutoDiscoverCommand() {
- t.Fatal("historical discover --auto line must still be plumbing")
- }
}
From 85996ac64cfcc1ef001a06a747ac08559da1e860 Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Thu, 12 Nov 2026 16:36:50 +0000
Subject: [PATCH 3/6] Keep the opt-in discover rewrite when the line is not
monitorable
Write() saved the original discover --auto line when the rewritten
command looked like meta-cron or a cronitor.link host. The jobs
subcommand scan also treated a flag value of sync or discover as
the subcommand.
Co-authored-by: August Flanagan
---
lib/crontab.go | 45 +++++++++++++++++++++++++++++++++++++++++++--
lib/crontab_test.go | 25 +++++++++++++++++++++++++
2 files changed, 68 insertions(+), 2 deletions(-)
diff --git a/lib/crontab.go b/lib/crontab.go
index 8df66ed5..5f0f7f9a 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -286,8 +286,16 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
}
// Opt-in only (--no-auto-discover=false). The default removes this
// line and does not add one. The monitor key ignores command text.
+ // Write() emits FullLine when the command is not monitorable
+ // (meta-cron fragments, cronitor.link), so the rewrite has to land there.
if !strings.Contains(line.CommandToRun, "jobs discover --auto") {
line.CommandToRun = autoDiscoverCommand(c)
+ parts := []string{line.CronExpression}
+ if !c.IsUserCrontab && line.RunAs != "" {
+ parts = append(parts, line.RunAs)
+ }
+ parts = append(parts, line.CommandToRun)
+ line.FullLine = strings.Join(parts, " ")
}
}
@@ -920,13 +928,19 @@ func (l Line) GetEnvVarValue() string {
}
// autoDiscoverCommand is the hidden opt-in plumbing command. sync is written
-// as discover so IsAutoDiscoverCommand still matches. The first sync or
-// discover token after jobs is the subcommand.
+// as discover so IsAutoDiscoverCommand still matches. The subcommand is the
+// sync or discover token after jobs; a flag value in that position is not it.
func autoDiscoverCommand(crontab *Crontab) string {
args := make([]string, 0, len(os.Args)+1)
seenJobs := false
replaced := false
+ skipValue := false
for _, arg := range os.Args {
+ if skipValue {
+ args = append(args, arg)
+ skipValue = false
+ continue
+ }
if arg == "--auto" || strings.HasPrefix(arg, "--auto=") {
continue
}
@@ -939,6 +953,9 @@ func autoDiscoverCommand(crontab *Crontab) string {
seenJobs = true
}
args = append(args, arg)
+ if seenJobs && !replaced && flagTakesValue(arg) {
+ skipValue = true
+ }
}
commandToRun := strings.Join(args, " ")
@@ -953,6 +970,30 @@ func autoDiscoverCommand(crontab *Crontab) string {
return commandToRun
}
+// flagTakesValue reports whether this argv token is a flag whose next token is
+// its value. Bool flags and --flag=value do not consume the next token.
+func flagTakesValue(arg string) bool {
+ if len(arg) < 2 || arg[0] != '-' || strings.Contains(arg, "=") {
+ return false
+ }
+ name := arg
+ if strings.HasPrefix(arg, "--") {
+ name = arg[2:]
+ } else if len(arg) == 2 {
+ name = arg[1:]
+ } else {
+ return false
+ }
+ switch name {
+ case "config", "c", "env", "api-key", "k", "ping-api-key", "p", "ping-api-host",
+ "hostname", "n", "log", "l", "users", "u", "api-version",
+ "exclude-from-name", "e", "notification-list", "format", "file":
+ return true
+ default:
+ return false
+ }
+}
+
func createAutoDiscoverLine(crontab *Crontab) *Line {
cronExpression := fmt.Sprintf("%d * * * *", randomMinute())
if crontab.UsesSixFieldExpressions {
diff --git a/lib/crontab_test.go b/lib/crontab_test.go
index 8e70dac7..9d1b35a4 100644
--- a/lib/crontab_test.go
+++ b/lib/crontab_test.go
@@ -2,6 +2,7 @@ package lib
import (
"os"
+ "path/filepath"
"regexp"
"strings"
"testing"
@@ -262,4 +263,28 @@ func TestCreateAutoDiscoverLineTargetsJobsSubcommand(t *testing.T) {
if !strings.Contains(line.CommandToRun, "jobs discover --auto") || strings.Contains(line.CommandToRun, " sync") {
t.Fatalf("sync invocation = %q", line.CommandToRun)
}
+
+ // The rewritten command is not monitorable (cron.daily and cronitor.link),
+ // and the hostname value sync sits where a naive scan would see the subcommand.
+ dir := t.TempDir()
+ path := filepath.Join(dir, "cron.daily")
+ body := "15 * * * * cronitor discover --auto /etc/crontab\n0 * * * * echo hello\n"
+ if err := os.WriteFile(path, []byte(body), 0644); err != nil {
+ t.Fatal(err)
+ }
+ os.Args = []string{
+ "cronitor", "jobs", "--hostname", "sync", "sync", "--auto",
+ "--no-auto-discover=false", "--ping-api-host", "eu.cronitor.link", path,
+ }
+ ct := CrontabFactory("rewrite", path)
+ if err, code := ct.Parse(false); err != nil {
+ t.Fatalf("parse: %v (%d)", err, code)
+ }
+ written := ct.Write()
+ if strings.Contains(written, "cronitor discover --auto") || !strings.Contains(written, "jobs --hostname sync discover --auto") || !strings.Contains(written, "echo hello") {
+ t.Fatalf("rewrite = %q", written)
+ }
+ if strings.Contains(written, "--hostname discover") || strings.Contains(written, "discover --auto sync") {
+ t.Fatalf("flag value consumed as the subcommand: %q", written)
+ }
}
From f436533851be081185474891ea8e253f2cca75a5 Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Thu, 12 Nov 2026 17:22:32 +0000
Subject: [PATCH 4/6] Write one fresh opt-in discover line instead of rewriting
argv
The hidden --no-auto-discover=false path was scanning the old line's tokens.
Short clusters, flag values named sync, and a crontab path named job, jobs,
or auto each broke that scan. Remove the recognized line and emit one
shell-quoted jobs discover --auto line from the resolved path and flags
this sync already parsed.
Co-authored-by: August Flanagan
---
cmd/discover.go | 34 ++++++++++-
cmd/discover_test.go | 51 ++++++++++++++++
lib/crontab.go | 135 ++++++++++++++-----------------------------
lib/crontab_test.go | 37 ------------
4 files changed, 128 insertions(+), 129 deletions(-)
diff --git a/cmd/discover.go b/cmd/discover.go
index 619b462b..a3d9c742 100644
--- a/cmd/discover.go
+++ b/cmd/discover.go
@@ -955,6 +955,38 @@ var askAboutJob = func(line *lib.Line, name string, monitored bool) promptResult
return promptResult{choice: choiceMonitor, name: finalModel.textInput.Value()}
}
+func autoDiscoverFlagArgs() []string {
+ args := []string{"--no-auto-discover=false"}
+ for _, pair := range [][2]string{
+ {"config", cfgFile}, {"env", environment}, {"api-key", apiKey}, {"ping-api-key", pingApiKey},
+ {"ping-api-host", pingApiHostFlag}, {"hostname", hostname}, {"log", debugLog}, {"users", users},
+ {"notification-list", notificationList}, {"format", syncFormat},
+ } {
+ if pair[1] != "" {
+ args = append(args, "--"+pair[0], pair[1])
+ }
+ }
+ if f := RootCmd.PersistentFlags().Lookup("api-version"); f != nil && f.Changed && f.Value.String() != "" {
+ args = append(args, "--api-version", f.Value.String())
+ }
+ if verbose {
+ args = append(args, "--verbose")
+ }
+ if noStdoutPassthru {
+ args = append(args, "--no-stdout")
+ }
+ if dev {
+ args = append(args, "--use-dev")
+ }
+ if isSilent {
+ args = append(args, "--silent")
+ }
+ for _, text := range excludeFromName {
+ args = append(args, "--exclude-from-name", text)
+ }
+ return args
+}
+
// planCrontab reads a crontab and decides what to do with each job. It
// returns nil when a crontab is skipped. One named file that does not exist
// or is not writable is an unusable plan: sync prints the original crontab
@@ -972,7 +1004,7 @@ func planCrontab(crontab *lib.Crontab) *crontabPlan {
}
// This will mostly happen when the crontab is empty
- if err, _ := crontab.Parse(noAutoDiscover); err != nil {
+ if err, _ := crontab.Parse(noAutoDiscover, autoDiscoverFlagArgs()...); err != nil {
// A named file that cannot be read is a failure. There is nothing
// to print. An empty crontab is still a skip: installing it changes
// nothing. Scanning many crontabs keeps the old skip.
diff --git a/cmd/discover_test.go b/cmd/discover_test.go
index 71658247..72e94705 100644
--- a/cmd/discover_test.go
+++ b/cmd/discover_test.go
@@ -1,10 +1,13 @@
package cmd
import (
+ "os"
+ "path/filepath"
"strings"
"testing"
"github.com/cronitorio/cronitor-cli/lib"
+ "github.com/kballard/go-shellquote"
)
func TestCreateDefaultNameHasAddCandidateSideEffect(t *testing.T) {
@@ -258,3 +261,51 @@ func TestHasMonitorByNameSkipsCurrent(t *testing.T) {
t.Fatal("HasMonitorByName missed a different monitor's name")
}
}
+
+func TestOptInAutoDiscoverLine(t *testing.T) {
+ t.Cleanup(resetSyncFlags)
+ legacy := "15 * * * * cronitor discover --auto /etc/crontab\n"
+ for _, tc := range []struct {
+ name, file, extra, host, ping string
+ argv []string
+ rel bool
+ }{
+ {"meta-link", "cron.daily", "0 * * * * echo hello\n", "", "eu.cronitor.link", []string{"jobs", "sync", "--no-auto-discover=false", "--ping-api-host", "eu.cronitor.link"}, false},
+ {"hostname-sync", "crontab", "", "sync", "", []string{"jobs", "--hostname", "sync", "sync", "--no-auto-discover=false"}, false},
+ {"vn-sync", "crontab", "", "sync", "", []string{"jobs", "-vn", "sync", "sync", "--no-auto-discover=false"}, false},
+ {"relative-jobs", "jobs", "", "", "", []string{"jobs", "sync", "--no-auto-discover=false"}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, tc.file), []byte(legacy+tc.extra), 0644); err != nil {
+ t.Fatal(err)
+ }
+ filename := filepath.Join(dir, tc.file)
+ if tc.rel {
+ t.Chdir(dir)
+ filename = tc.file
+ }
+ resetSyncFlags()
+ cmd, rest, err := RootCmd.Find(append(append([]string{}, tc.argv...), filename))
+ if err != nil || cmd != discoverCmd || cmd.ParseFlags(rest) != nil {
+ t.Fatal(err)
+ }
+ ct := lib.CrontabFactory("rewrite", filename)
+ if err, code := ct.Parse(false, autoDiscoverFlagArgs()...); err != nil {
+ t.Fatalf("%v %d", err, code)
+ }
+ got := ct.Write()
+ words, err := shellquote.Split(strings.TrimPrefix(strings.Split(got, "\n")[0], "15 * * * * "))
+ abs, _ := filepath.Abs(filename)
+ if err != nil || len(words) < 4 || words[1] != "jobs" || words[2] != "discover" || words[3] != "--auto" || words[len(words)-1] != abs || strings.Contains(got, "/etc/crontab") || strings.Count(got, "discover --auto") != 1 || tc.host != "" && !strings.Contains(got, "--hostname "+tc.host) || tc.ping != "" && !strings.Contains(got, tc.ping) || tc.extra != "" && !strings.Contains(got, "echo hello") {
+ t.Fatal(got)
+ }
+ })
+ }
+}
+
+func resetSyncFlags() {
+ hostname, pingApiHostFlag, environment, users, apiKey, pingApiKey, debugLog, cfgFile = "", "", "", "", "", "", "", ""
+ notificationList, syncFormat, excludeFromName = "", "", nil
+ verbose, noStdoutPassthru, noAutoDiscover, dev, isSilent = false, false, true, false, false
+}
diff --git a/lib/crontab.go b/lib/crontab.go
index 5f0f7f9a..38e76976 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -15,6 +15,7 @@ import (
"strconv"
"strings"
+ "github.com/kballard/go-shellquote"
"github.com/spf13/viper"
)
@@ -113,7 +114,7 @@ func isValidCronExpression(line string) bool {
return true
}
-func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
+func (c *Crontab) Parse(noAutoDiscover bool, discoverFlags ...string) (error, int) {
lines, errCode, err := c.load()
if err != nil {
return err, errCode
@@ -124,9 +125,10 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
}
c.original = strings.Join(lines, "\n")
- var autoDiscoverLine *Line
var name string
var ignored bool
+ var keptSchedule, keptRunAs string
+ emitted := false
for lineIndex, fullLine := range lines {
lineNumber := lineIndex + 1 // Convert to 1-indexed
@@ -279,24 +281,21 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
line.rawCommand = rawCommand
line.parsedCommand = line.CommandToRun
+ // Drop a discover --auto line. Opt-in emits one fresh line from flags already parsed.
if line.IsAutoDiscoverCommand() {
- autoDiscoverLine = &line
- if noAutoDiscover {
- continue // remove the auto-discover line from the crontab if --no-auto-discover flag is passed
+ if keptSchedule == "" {
+ keptSchedule = line.CronExpression
+ keptRunAs = line.RunAs
}
- // Opt-in only (--no-auto-discover=false). The default removes this
- // line and does not add one. The monitor key ignores command text.
- // Write() emits FullLine when the command is not monitorable
- // (meta-cron fragments, cronitor.link), so the rewrite has to land there.
- if !strings.Contains(line.CommandToRun, "jobs discover --auto") {
- line.CommandToRun = autoDiscoverCommand(c)
- parts := []string{line.CronExpression}
- if !c.IsUserCrontab && line.RunAs != "" {
- parts = append(parts, line.RunAs)
- }
- parts = append(parts, line.CommandToRun)
- line.FullLine = strings.Join(parts, " ")
+ if !noAutoDiscover && !emitted {
+ c.Lines = append(c.Lines, createAutoDiscoverLine(c, keptSchedule, keptRunAs, discoverFlags))
+ emitted = true
+ }
+ if !noAutoDiscover && line.CronExpression != "" {
+ name = ""
+ ignored = false
}
+ continue
}
// Reset the name and ignored for the next line after we've found its command line
@@ -308,9 +307,8 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
c.Lines = append(c.Lines, &line)
}
- // If we do not have an auto-discover line but we should, add one now
- if autoDiscoverLine == nil && !noAutoDiscover {
- c.Lines = append(c.Lines, createAutoDiscoverLine(c))
+ if !noAutoDiscover && !emitted {
+ c.Lines = append(c.Lines, createAutoDiscoverLine(c, "", "", discoverFlags))
}
if IsShimShellPath(c.Shell) {
@@ -927,86 +925,41 @@ func (l Line) GetEnvVarValue() string {
return ""
}
-// autoDiscoverCommand is the hidden opt-in plumbing command. sync is written
-// as discover so IsAutoDiscoverCommand still matches. The subcommand is the
-// sync or discover token after jobs; a flag value in that position is not it.
-func autoDiscoverCommand(crontab *Crontab) string {
- args := make([]string, 0, len(os.Args)+1)
- seenJobs := false
- replaced := false
- skipValue := false
- for _, arg := range os.Args {
- if skipValue {
- args = append(args, arg)
- skipValue = false
- continue
- }
- if arg == "--auto" || strings.HasPrefix(arg, "--auto=") {
- continue
- }
- if seenJobs && !replaced && (arg == "sync" || arg == "discover") {
- args = append(args, "discover", "--auto")
- replaced = true
- continue
- }
- if arg == "jobs" {
- seenJobs = true
- }
- args = append(args, arg)
- if seenJobs && !replaced && flagTakesValue(arg) {
- skipValue = true
- }
+func autoDiscoverCommand(crontab *Crontab, flags []string) string {
+ bin := "cronitor"
+ if len(os.Args) > 0 && os.Args[0] != "" {
+ bin = os.Args[0]
}
-
- commandToRun := strings.Join(args, " ")
- commandToRun = strings.Replace(commandToRun, "--save", "", -1)
- commandToRun = strings.Replace(commandToRun, "--verbose", "", -1)
- commandToRun = strings.Replace(commandToRun, "-v", "", -1)
- commandToRun = strings.Replace(commandToRun, "--interactive", "", -1)
- commandToRun = strings.Replace(commandToRun, "-i", "", -1)
- if len(crontab.Filename) > 0 {
- commandToRun = strings.Replace(commandToRun, crontab.Filename, crontab.CanonicalName(), -1)
+ args := append([]string{bin, "jobs", "discover", "--auto"}, flags...)
+ if !crontab.IsUserCrontab && crontab.Filename != "" {
+ args = append(args, crontab.CanonicalName())
}
- return commandToRun
+ return shellquote.Join(args...)
}
-// flagTakesValue reports whether this argv token is a flag whose next token is
-// its value. Bool flags and --flag=value do not consume the next token.
-func flagTakesValue(arg string) bool {
- if len(arg) < 2 || arg[0] != '-' || strings.Contains(arg, "=") {
- return false
+func createAutoDiscoverLine(crontab *Crontab, schedule, runAs string, flags []string) *Line {
+ if schedule == "" {
+ schedule = fmt.Sprintf("%d * * * *", randomMinute())
+ if crontab.UsesSixFieldExpressions {
+ schedule = "* " + schedule
+ }
}
- name := arg
- if strings.HasPrefix(arg, "--") {
- name = arg[2:]
- } else if len(arg) == 2 {
- name = arg[1:]
- } else {
- return false
+ cmd := autoDiscoverCommand(crontab, flags)
+ parts := []string{schedule}
+ if !crontab.IsUserCrontab && runAs != "" {
+ parts = append(parts, runAs)
}
- switch name {
- case "config", "c", "env", "api-key", "k", "ping-api-key", "p", "ping-api-host",
- "hostname", "n", "log", "l", "users", "u", "api-version",
- "exclude-from-name", "e", "notification-list", "format", "file":
- return true
- default:
- return false
+ parts = append(parts, cmd)
+ return &Line{
+ IsJob: true,
+ CronExpression: schedule,
+ CommandToRun: cmd,
+ RunAs: runAs,
+ FullLine: strings.Join(parts, " "),
+ Crontab: crontab.lightweightCopy(),
}
}
-func createAutoDiscoverLine(crontab *Crontab) *Line {
- cronExpression := fmt.Sprintf("%d * * * *", randomMinute())
- if crontab.UsesSixFieldExpressions {
- cronExpression = fmt.Sprintf("* %s", cronExpression)
- }
-
- line := Line{}
- line.CronExpression = cronExpression
- line.CommandToRun = autoDiscoverCommand(crontab)
- line.FullLine = fmt.Sprintf("%s %s", line.CronExpression, line.CommandToRun)
- return &line
-}
-
func isSixFieldCronExpression(splitLine []string) bool {
matchDigitOrWildcard, _ := regexp.MatchString("^[-,?*/0-9]+$", splitLine[5])
matchDayOfWeekStringRange, _ := regexp.MatchString("^(Mon|Tue|Wed|Thr|Fri|Sat|Sun)(-(Mon|Tue|Wed|Thr|Fri|Sat|Sun))?$", splitLine[5])
diff --git a/lib/crontab_test.go b/lib/crontab_test.go
index 9d1b35a4..4b07343f 100644
--- a/lib/crontab_test.go
+++ b/lib/crontab_test.go
@@ -1,8 +1,6 @@
package lib
import (
- "os"
- "path/filepath"
"regexp"
"strings"
"testing"
@@ -253,38 +251,3 @@ func TestLineWriteWithNoStdoutAndEnv(t *testing.T) {
t.Errorf("Expected 'cronitor --env testing exec --no-stdout test123' in output but got: %s", output)
}
}
-
-func TestCreateAutoDiscoverLineTargetsJobsSubcommand(t *testing.T) {
- old := os.Args
- t.Cleanup(func() { os.Args = old })
-
- os.Args = []string{"cronitor", "jobs", "sync", "--auto", "/tmp/crontab"}
- line := createAutoDiscoverLine(&Crontab{})
- if !strings.Contains(line.CommandToRun, "jobs discover --auto") || strings.Contains(line.CommandToRun, " sync") {
- t.Fatalf("sync invocation = %q", line.CommandToRun)
- }
-
- // The rewritten command is not monitorable (cron.daily and cronitor.link),
- // and the hostname value sync sits where a naive scan would see the subcommand.
- dir := t.TempDir()
- path := filepath.Join(dir, "cron.daily")
- body := "15 * * * * cronitor discover --auto /etc/crontab\n0 * * * * echo hello\n"
- if err := os.WriteFile(path, []byte(body), 0644); err != nil {
- t.Fatal(err)
- }
- os.Args = []string{
- "cronitor", "jobs", "--hostname", "sync", "sync", "--auto",
- "--no-auto-discover=false", "--ping-api-host", "eu.cronitor.link", path,
- }
- ct := CrontabFactory("rewrite", path)
- if err, code := ct.Parse(false); err != nil {
- t.Fatalf("parse: %v (%d)", err, code)
- }
- written := ct.Write()
- if strings.Contains(written, "cronitor discover --auto") || !strings.Contains(written, "jobs --hostname sync discover --auto") || !strings.Contains(written, "echo hello") {
- t.Fatalf("rewrite = %q", written)
- }
- if strings.Contains(written, "--hostname discover") || strings.Contains(written, "discover --auto sync") {
- t.Fatalf("flag value consumed as the subcommand: %q", written)
- }
-}
From 760790eddedcf85f840e749fbef1cc60c7f06d5d Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Thu, 12 Nov 2026 18:09:53 +0000
Subject: [PATCH 5/6] Remove the hidden auto-discover opt-in
Auto-discover has been off since 2020, and rewriting that legacy line
kept breaking. jobs sync still drops an active discover --auto line,
leaves a commented-out one unchanged, and says so once on stderr.
Co-authored-by: August Flanagan
---
cmd/discover.go | 45 ++--------------------
cmd/discover_test.go | 51 ------------------------
lib/crontab.go | 83 ++++++++++++++--------------------------
lib/crontab_wrap_test.go | 13 +++++++
4 files changed, 46 insertions(+), 146 deletions(-)
diff --git a/cmd/discover.go b/cmd/discover.go
index a3d9c742..fa1975e0 100644
--- a/cmd/discover.go
+++ b/cmd/discover.go
@@ -233,9 +233,6 @@ var syncFile string // Path to YAML/JSON file for bulk monitor import
var syncFormat string // --format: "", "short" or "exec"
var withMonitored bool // --with-monitored: also ask about jobs that are already monitored
-// To deprecate this feature we are hijacking this flag that will trigger removal of auto-discover lines from existing user's crontabs.
-var noAutoDiscover = true
-
func discoverMissingAPIKeyGuidance() string {
return fmt.Sprintf("\n%s\n\n%s Run %s to sign in with device authorization (%s is an alias).\n\n%s Copy an SDK key from https://cronitor.io/app/settings/api and save it with %s\n\n",
color.New(color.FgRed, color.Bold).Sprint("Add your API key before running sync."),
@@ -955,38 +952,6 @@ var askAboutJob = func(line *lib.Line, name string, monitored bool) promptResult
return promptResult{choice: choiceMonitor, name: finalModel.textInput.Value()}
}
-func autoDiscoverFlagArgs() []string {
- args := []string{"--no-auto-discover=false"}
- for _, pair := range [][2]string{
- {"config", cfgFile}, {"env", environment}, {"api-key", apiKey}, {"ping-api-key", pingApiKey},
- {"ping-api-host", pingApiHostFlag}, {"hostname", hostname}, {"log", debugLog}, {"users", users},
- {"notification-list", notificationList}, {"format", syncFormat},
- } {
- if pair[1] != "" {
- args = append(args, "--"+pair[0], pair[1])
- }
- }
- if f := RootCmd.PersistentFlags().Lookup("api-version"); f != nil && f.Changed && f.Value.String() != "" {
- args = append(args, "--api-version", f.Value.String())
- }
- if verbose {
- args = append(args, "--verbose")
- }
- if noStdoutPassthru {
- args = append(args, "--no-stdout")
- }
- if dev {
- args = append(args, "--use-dev")
- }
- if isSilent {
- args = append(args, "--silent")
- }
- for _, text := range excludeFromName {
- args = append(args, "--exclude-from-name", text)
- }
- return args
-}
-
// planCrontab reads a crontab and decides what to do with each job. It
// returns nil when a crontab is skipped. One named file that does not exist
// or is not writable is an unusable plan: sync prints the original crontab
@@ -1004,7 +969,7 @@ func planCrontab(crontab *lib.Crontab) *crontabPlan {
}
// This will mostly happen when the crontab is empty
- if err, _ := crontab.Parse(noAutoDiscover, autoDiscoverFlagArgs()...); err != nil {
+ if err, _ := crontab.Parse(true); err != nil {
// A named file that cannot be read is a failure. There is nothing
// to print. An empty crontab is still a skip: installing it changes
// nothing. Scanning many crontabs keeps the old skip.
@@ -1316,6 +1281,9 @@ func applyPlan(plan *crontabPlan) bool {
if !dryRun && changed {
if err := crontab.Save(updatedCrontabLines); err == nil {
plan.output = updatedCrontabLines
+ if crontab.RemovedAutoDiscoverLine() {
+ fmt.Fprintln(os.Stderr, "Removed the old auto-discover line. Auto-discover is no longer supported.")
+ }
if !isSilent {
printDoneText("Integration complete", true)
}
@@ -1715,7 +1683,6 @@ func init() {
discoverCmd.Flags().BoolVar(&saveCrontabFile, "save", saveCrontabFile, "Save the updated crontab file")
discoverCmd.Flags().BoolVar(&dryRun, "dry-run", dryRun, "Show what Linux/macOS crontab sync would change. Sends nothing to Cronitor and does not write the crontab. Does not apply to --file or Windows scheduled-task sync.")
discoverCmd.Flags().StringArrayVarP(&excludeFromName, "exclude-from-name", "e", excludeFromName, "Substring to exclude from auto-generated monitor name e.g. $ cronitor jobs sync -e '> /dev/null' -e '/path/to/app'")
- discoverCmd.Flags().BoolVar(&noAutoDiscover, "no-auto-discover", noAutoDiscover, "Do not attach an automatic discover job to this crontab, or remove if already attached.")
discoverCmd.Flags().BoolVar(&noStdoutPassthru, "no-stdout", noStdoutPassthru, "Do not send cron job output to Cronitor when your job completes.")
discoverCmd.Flags().StringVar(¬ificationList, "notification-list", notificationList, "Set this alert list on new and existing monitors. Without it, sync sends no alert list: new monitors get Cronitor's default list and existing monitors keep theirs.")
discoverCmd.Flags().BoolVar(&isAutoDiscover, "auto", isAutoDiscover, "Ask nothing: monitor every new job, send schedule and timezone changes, write the crontab, and print it to stdout even when nothing changed.")
@@ -1730,8 +1697,4 @@ func init() {
discoverCmd.Flags().MarkDeprecated("save", "save will now happen automatically when the --dry-run flag is not used")
discoverCmd.Flags().MarkHidden("save")
- // Since 24.0 no auto discover is deprecated
- discoverCmd.Flags().MarkDeprecated("no-auto-discover", "the auto-discover feature has been removed")
- discoverCmd.Flags().MarkHidden("no-auto-discover")
-
}
diff --git a/cmd/discover_test.go b/cmd/discover_test.go
index 72e94705..71658247 100644
--- a/cmd/discover_test.go
+++ b/cmd/discover_test.go
@@ -1,13 +1,10 @@
package cmd
import (
- "os"
- "path/filepath"
"strings"
"testing"
"github.com/cronitorio/cronitor-cli/lib"
- "github.com/kballard/go-shellquote"
)
func TestCreateDefaultNameHasAddCandidateSideEffect(t *testing.T) {
@@ -261,51 +258,3 @@ func TestHasMonitorByNameSkipsCurrent(t *testing.T) {
t.Fatal("HasMonitorByName missed a different monitor's name")
}
}
-
-func TestOptInAutoDiscoverLine(t *testing.T) {
- t.Cleanup(resetSyncFlags)
- legacy := "15 * * * * cronitor discover --auto /etc/crontab\n"
- for _, tc := range []struct {
- name, file, extra, host, ping string
- argv []string
- rel bool
- }{
- {"meta-link", "cron.daily", "0 * * * * echo hello\n", "", "eu.cronitor.link", []string{"jobs", "sync", "--no-auto-discover=false", "--ping-api-host", "eu.cronitor.link"}, false},
- {"hostname-sync", "crontab", "", "sync", "", []string{"jobs", "--hostname", "sync", "sync", "--no-auto-discover=false"}, false},
- {"vn-sync", "crontab", "", "sync", "", []string{"jobs", "-vn", "sync", "sync", "--no-auto-discover=false"}, false},
- {"relative-jobs", "jobs", "", "", "", []string{"jobs", "sync", "--no-auto-discover=false"}, true},
- } {
- t.Run(tc.name, func(t *testing.T) {
- dir := t.TempDir()
- if err := os.WriteFile(filepath.Join(dir, tc.file), []byte(legacy+tc.extra), 0644); err != nil {
- t.Fatal(err)
- }
- filename := filepath.Join(dir, tc.file)
- if tc.rel {
- t.Chdir(dir)
- filename = tc.file
- }
- resetSyncFlags()
- cmd, rest, err := RootCmd.Find(append(append([]string{}, tc.argv...), filename))
- if err != nil || cmd != discoverCmd || cmd.ParseFlags(rest) != nil {
- t.Fatal(err)
- }
- ct := lib.CrontabFactory("rewrite", filename)
- if err, code := ct.Parse(false, autoDiscoverFlagArgs()...); err != nil {
- t.Fatalf("%v %d", err, code)
- }
- got := ct.Write()
- words, err := shellquote.Split(strings.TrimPrefix(strings.Split(got, "\n")[0], "15 * * * * "))
- abs, _ := filepath.Abs(filename)
- if err != nil || len(words) < 4 || words[1] != "jobs" || words[2] != "discover" || words[3] != "--auto" || words[len(words)-1] != abs || strings.Contains(got, "/etc/crontab") || strings.Count(got, "discover --auto") != 1 || tc.host != "" && !strings.Contains(got, "--hostname "+tc.host) || tc.ping != "" && !strings.Contains(got, tc.ping) || tc.extra != "" && !strings.Contains(got, "echo hello") {
- t.Fatal(got)
- }
- })
- }
-}
-
-func resetSyncFlags() {
- hostname, pingApiHostFlag, environment, users, apiKey, pingApiKey, debugLog, cfgFile = "", "", "", "", "", "", "", ""
- notificationList, syncFormat, excludeFromName = "", "", nil
- verbose, noStdoutPassthru, noAutoDiscover, dev, isSilent = false, false, true, false, false
-}
diff --git a/lib/crontab.go b/lib/crontab.go
index 38e76976..058918b7 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -15,7 +15,6 @@ import (
"strconv"
"strings"
- "github.com/kballard/go-shellquote"
"github.com/spf13/viper"
)
@@ -41,6 +40,7 @@ type Crontab struct {
RewriteShimToExec bool `json:"-"`
ConvertExec bool `json:"-"` // sync --format=short
original string // the text Parse read
+ removedAutoDiscover bool // Parse dropped an active legacy discover --auto line
}
// Original returns the crontab text as Parse read it.
@@ -48,6 +48,9 @@ func (c Crontab) Original() string {
return c.original
}
+// RemovedAutoDiscoverLine reports that Parse dropped an active legacy auto-discover line.
+func (c Crontab) RemovedAutoDiscoverLine() bool { return c.removedAutoDiscover }
+
// isExampleCronLine checks if a line contains obvious placeholder/example text
func isExampleCronLine(line string) bool {
line = strings.ToLower(line)
@@ -114,7 +117,7 @@ func isValidCronExpression(line string) bool {
return true
}
-func (c *Crontab) Parse(noAutoDiscover bool, discoverFlags ...string) (error, int) {
+func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
lines, errCode, err := c.load()
if err != nil {
return err, errCode
@@ -127,8 +130,6 @@ func (c *Crontab) Parse(noAutoDiscover bool, discoverFlags ...string) (error, in
var name string
var ignored bool
- var keptSchedule, keptRunAs string
- emitted := false
for lineIndex, fullLine := range lines {
lineNumber := lineIndex + 1 // Convert to 1-indexed
@@ -281,21 +282,28 @@ func (c *Crontab) Parse(noAutoDiscover bool, discoverFlags ...string) (error, in
line.rawCommand = rawCommand
line.parsedCommand = line.CommandToRun
- // Drop a discover --auto line. Opt-in emits one fresh line from flags already parsed.
+ // Active discover --auto lines are the old auto-discover plumbing. Sync
+ // removes them and does not install a replacement. A commented-out
+ // line is left byte-for-byte, including its leading #.
if line.IsAutoDiscoverCommand() {
- if keptSchedule == "" {
- keptSchedule = line.CronExpression
- keptRunAs = line.RunAs
- }
- if !noAutoDiscover && !emitted {
- c.Lines = append(c.Lines, createAutoDiscoverLine(c, keptSchedule, keptRunAs, discoverFlags))
- emitted = true
- }
- if !noAutoDiscover && line.CronExpression != "" {
+ if isComment {
+ c.Lines = append(c.Lines, &Line{
+ IsComment: true,
+ Name: name,
+ FullLine: lines[lineIndex],
+ LineNumber: lineNumber,
+ Ignored: ignored,
+ verbatim: true,
+ Crontab: c.lightweightCopy(),
+ })
name = ""
ignored = false
+ continue
+ }
+ if noAutoDiscover {
+ c.removedAutoDiscover = true
+ continue
}
- continue
}
// Reset the name and ignored for the next line after we've found its command line
@@ -307,10 +315,6 @@ func (c *Crontab) Parse(noAutoDiscover bool, discoverFlags ...string) (error, in
c.Lines = append(c.Lines, &line)
}
- if !noAutoDiscover && !emitted {
- c.Lines = append(c.Lines, createAutoDiscoverLine(c, "", "", discoverFlags))
- }
-
if IsShimShellPath(c.Shell) {
c.Shell = c.RealShell // "" when the crontab had no SHELL line before sync
}
@@ -489,6 +493,7 @@ type Line struct {
marker string // shim: CRONITOR= or MONITORIO=, as parsed
shimSettings []string // shim: CRONITOR_ENV=... words after the key
Integration string `json:"-"`
+ verbatim bool // write FullLine unchanged; a commented-out auto-discover line
}
func (l Line) IsMonitorable() bool {
@@ -540,6 +545,11 @@ func (l Line) writeUsing(c Crontab) string {
outputLines = append(outputLines, fmt.Sprintf("# Name: %s", l.Name))
}
+ if l.verbatim {
+ outputLines = append(outputLines, l.FullLine)
+ return strings.Join(outputLines, "\n")
+ }
+
if !l.IsMonitorable() {
// If this is a comment line, ensure it starts with #
if l.IsComment && !strings.HasPrefix(l.FullLine, "#") {
@@ -925,41 +935,6 @@ func (l Line) GetEnvVarValue() string {
return ""
}
-func autoDiscoverCommand(crontab *Crontab, flags []string) string {
- bin := "cronitor"
- if len(os.Args) > 0 && os.Args[0] != "" {
- bin = os.Args[0]
- }
- args := append([]string{bin, "jobs", "discover", "--auto"}, flags...)
- if !crontab.IsUserCrontab && crontab.Filename != "" {
- args = append(args, crontab.CanonicalName())
- }
- return shellquote.Join(args...)
-}
-
-func createAutoDiscoverLine(crontab *Crontab, schedule, runAs string, flags []string) *Line {
- if schedule == "" {
- schedule = fmt.Sprintf("%d * * * *", randomMinute())
- if crontab.UsesSixFieldExpressions {
- schedule = "* " + schedule
- }
- }
- cmd := autoDiscoverCommand(crontab, flags)
- parts := []string{schedule}
- if !crontab.IsUserCrontab && runAs != "" {
- parts = append(parts, runAs)
- }
- parts = append(parts, cmd)
- return &Line{
- IsJob: true,
- CronExpression: schedule,
- CommandToRun: cmd,
- RunAs: runAs,
- FullLine: strings.Join(parts, " "),
- Crontab: crontab.lightweightCopy(),
- }
-}
-
func isSixFieldCronExpression(splitLine []string) bool {
matchDigitOrWildcard, _ := regexp.MatchString("^[-,?*/0-9]+$", splitLine[5])
matchDayOfWeekStringRange, _ := regexp.MatchString("^(Mon|Tue|Wed|Thr|Fri|Sat|Sun)(-(Mon|Tue|Wed|Thr|Fri|Sat|Sun))?$", splitLine[5])
diff --git a/lib/crontab_wrap_test.go b/lib/crontab_wrap_test.go
index 0d035c89..590197e1 100644
--- a/lib/crontab_wrap_test.go
+++ b/lib/crontab_wrap_test.go
@@ -382,6 +382,19 @@ func commandFieldOf(crontabLine string) string {
return skipWSFields(line, fields)
}
+func TestLegacyAutoDiscoverLine(t *testing.T) {
+ commented := " #15 * * * * batchjob cronitor discover --auto /etc/crontab"
+ got := parseContent(t, strings.Join([]string{
+ "15 * * * * cronitor discover --auto /etc/crontab",
+ commented,
+ "0 1 * * * root echo hello",
+ }, "\n")).Write()
+ want := commented + "\n0 1 * * * root echo hello\n"
+ if got != want {
+ t.Fatalf("got:\n%s\nwant:\n%s", got, want)
+ }
+}
+
func requireShSyntax(t *testing.T, commandField string) {
t.Helper()
if _, err := exec.LookPath("sh"); err != nil {
From 65ace4b7c94539a003989a324558ca3a02b7046c Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Thu, 12 Nov 2026 19:14:25 +0000
Subject: [PATCH 6/6] Match only the installed auto-discover line
The substring check deleted user jobs that merely mentioned
discover and --auto. Recognize the old CLI line by tokens:
an optional cronitor exec wrapper, a cronitor binary, optional
global flags, an optional jobs, then discover and the word --auto.
A pending name or ignore comment is cleared when that line is removed.
Co-authored-by: August Flanagan
---
cmd/discover_test.go | 4 +-
lib/crontab.go | 17 ++++++++-
lib/crontab_wrap.go | 79 ++++++++++++++++++++++++++++++++++++++++
lib/crontab_wrap_test.go | 55 ++++++++++++++++++++++++----
4 files changed, 144 insertions(+), 11 deletions(-)
diff --git a/cmd/discover_test.go b/cmd/discover_test.go
index 71658247..f041a5c5 100644
--- a/cmd/discover_test.go
+++ b/cmd/discover_test.go
@@ -139,7 +139,7 @@ func TestCreateDefaultName(t *testing.T) {
"/var/some/command arg1 arg2"},
{"auto discover name is created",
- "cronitor d3x0c1 cronitor discover --auto /discover/test",
+ "cronitor exec d3x0c1 cronitor discover --auto /discover/test",
"",
11,
"localhost",
@@ -205,7 +205,7 @@ func TestCreateDefaultName(t *testing.T) {
func TestCreateDefaultNameAutoDiscover(t *testing.T) {
line := &lib.Line{
- CommandToRun: "cronitor d3x0c1 cronitor discover --auto /discover/test",
+ CommandToRun: "cronitor exec d3x0c1 cronitor discover --auto /discover/test",
LineNumber: 11,
RunAs: "",
}
diff --git a/lib/crontab.go b/lib/crontab.go
index 058918b7..5903045f 100644
--- a/lib/crontab.go
+++ b/lib/crontab.go
@@ -302,6 +302,7 @@ func (c *Crontab) Parse(noAutoDiscover bool) (error, int) {
}
if noAutoDiscover {
c.removedAutoDiscover = true
+ name, ignored = "", false
continue
}
}
@@ -501,9 +502,21 @@ func (l Line) IsMonitorable() bool {
return l.IsJob && !l.IsMetaCronJob() && !l.HasLegacyIntegration()
}
+// IsAutoDiscoverCommand reports the auto-discover line the old CLI installed.
+// After an optional run-as user and an optional "cronitor exec " wrapper,
+// the command is a cronitor binary, optional global flags, an optional jobs,
+// the word discover, and the word --auto.
func (l Line) IsAutoDiscoverCommand() bool {
- matched, _ := regexp.MatchString(".+discover[[:space:]]+--auto.*", strings.ToLower(l.CommandToRun))
- return matched
+ cmd := l.rawCommand
+ if cmd == "" {
+ cmd = l.CommandToRun
+ }
+ if isLegacyAutoDiscoverCommand(cmd) {
+ return true
+ }
+ // A passwd account named cronitor is taken as the run-as user, which
+ // hides the binary. Put that word back and test the same shape.
+ return l.RunAs != "" && isLegacyAutoDiscoverCommand(l.RunAs+" "+cmd)
}
func (l Line) HasLegacyIntegration() bool {
diff --git a/lib/crontab_wrap.go b/lib/crontab_wrap.go
index 76266c35..f72bc5cd 100644
--- a/lib/crontab_wrap.go
+++ b/lib/crontab_wrap.go
@@ -84,6 +84,85 @@ var cronitorBoolFlags = map[string]bool{
"help": true, "h": true,
}
+// isLegacyAutoDiscoverCommand reports the plumbing line the old CLI wrote.
+// Tokens, not a substring: [cronitor exec ]
+// [global flags] [jobs] discover --auto. --auto-scale is not --auto.
+func isLegacyAutoDiscoverCommand(command string) bool {
+ return legacyAutoDiscoverAt(strings.Fields(command), 0)
+}
+
+func legacyAutoDiscoverAt(words []string, i int) bool {
+ if i >= len(words) || !cronitorBasename(words[i]) {
+ return false
+ }
+ j := skipCronitorFlags(words, i+1)
+ if j < len(words) && words[j] == "exec" {
+ j++
+ j = skipCronitorFlags(words, j)
+ if j >= len(words) || strings.HasPrefix(words[j], "-") {
+ return false
+ }
+ return legacyDiscoverCommand(words, j+1)
+ }
+ return legacyDiscoverCommand(words, i)
+}
+
+func legacyDiscoverCommand(words []string, i int) bool {
+ if i >= len(words) || !cronitorBasename(words[i]) {
+ return false
+ }
+ i = skipCronitorFlags(words, i+1)
+ if i < len(words) && words[i] == "jobs" {
+ i = skipCronitorFlags(words, i+1)
+ }
+ if i >= len(words) || words[i] != "discover" {
+ return false
+ }
+ return i+1 < len(words) && words[i+1] == "--auto"
+}
+
+func cronitorBasename(token string) bool {
+ return path.Base(token) == "cronitor"
+}
+
+func knownCronitorGlobalFlag(tok string) bool {
+ if !strings.HasPrefix(tok, "-") || tok == "-" || tok == "--" {
+ return false
+ }
+ name, _, _ := strings.Cut(tok, "=")
+ if strings.HasPrefix(name, "--") {
+ name = strings.TrimPrefix(name, "--")
+ return cronitorValueFlags[name] || cronitorBoolFlags[name]
+ }
+ name = strings.TrimPrefix(name, "-")
+ if name == "" {
+ return false
+ }
+ if cronitorValueFlags[name] || cronitorBoolFlags[name] {
+ return true
+ }
+ return len(name) > 1 && cronitorValueFlags[name[:1]]
+}
+
+// skipCronitorFlags advances past global flags. A value flag consumes the
+// next word unless the value is attached with "=" or a short cluster.
+func skipCronitorFlags(words []string, i int) int {
+ for i < len(words) && knownCronitorGlobalFlag(words[i]) {
+ tok := words[i]
+ name := tok
+ if eq := strings.IndexByte(name, '='); eq >= 0 {
+ name = name[:eq]
+ }
+ attached := strings.Contains(tok, "=") || (!strings.HasPrefix(tok, "--") && len(tok) > 2)
+ if !attached && cronitorValueFlags[strings.TrimLeft(name, "-")] && i+1 < len(words) {
+ i += 2
+ continue
+ }
+ i++
+ }
+ return i
+}
+
// unwrapCronitorExec parses `cronitor [flags] exec [flags] [command]`.
// prefix is the original text through the key so Write can emit it unchanged.
func unwrapCronitorExec(raw string) (code, command, prefix string, noStdout, ok bool) {
diff --git a/lib/crontab_wrap_test.go b/lib/crontab_wrap_test.go
index 590197e1..892e10dd 100644
--- a/lib/crontab_wrap_test.go
+++ b/lib/crontab_wrap_test.go
@@ -383,15 +383,56 @@ func commandFieldOf(crontabLine string) string {
}
func TestLegacyAutoDiscoverLine(t *testing.T) {
- commented := " #15 * * * * batchjob cronitor discover --auto /etc/crontab"
- got := parseContent(t, strings.Join([]string{
+ kept := []string{
+ "0 * * * * echo discover --auto",
+ "0 * * * * rediscover --auto",
+ "0 * * * * discover --auto-prune",
+ "0 * * * * /opt/acme/bin/discover --auto-scale",
+ "0 * * * * ./rediscover --automatic --x",
+ "0 * * * * echo 'run discover --auto later' >> /tmp/log",
+ }
+ removed := []string{
"15 * * * * cronitor discover --auto /etc/crontab",
- commented,
+ "15 * * * * /usr/local/bin/cronitor discover --auto /etc/crontab",
+ "15 * * * * root cronitor discover --auto /etc/crontab",
+ "15 * * * * cronitor jobs discover --auto /etc/crontab",
+ "15 * * * * cronitor exec abc123 cronitor discover --auto /etc/crontab",
+ "15 * * * * cronitor --hostname db1 discover --auto /etc/crontab",
"0 1 * * * root echo hello",
- }, "\n")).Write()
- want := commented + "\n0 1 * * * root echo hello\n"
- if got != want {
- t.Fatalf("got:\n%s\nwant:\n%s", got, want)
+ }
+ tests := []struct {
+ name string
+ in []string
+ want string
+ }{
+ {
+ name: "legacy lines removed",
+ in: removed,
+ want: "0 1 * * * root echo hello\n",
+ },
+ {
+ name: "similar user jobs kept",
+ in: kept,
+ want: strings.Join(kept, "\n") + "\n",
+ },
+ {
+ name: "name and ignore do not carry to the next job",
+ in: []string{
+ "# Name: Auto discover",
+ "# cronitor: ignore",
+ "15 * * * * cronitor discover --auto /etc/crontab",
+ "0 1 * * * echo next",
+ },
+ want: "0 1 * * * echo next\n",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseContent(t, strings.Join(tc.in, "\n")).Write()
+ if got != tc.want {
+ t.Fatalf("got:\n%s\nwant:\n%s", got, tc.want)
+ }
+ })
}
}