Skip to main content

heddle_cli_args/cli/cli_args/
commands_main.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Top-level CLI commands.
3
4use clap::{Args, Subcommand};
5
6#[cfg(feature = "git-overlay")]
7use super::BridgeCommands;
8#[cfg(feature = "semantic")]
9use super::SemanticCommands;
10use super::{
11    AgentCommands, CompletionSubject, ContextCommands, DiscussCommands, EnvCommands, HookCommands,
12    IntegrationCommands, OplogCommands, QueryArgs, RedactCommands, RemoteCommands, ReviewCommands,
13    ShellCommands, ThreadCommands, VisibilityCommands,
14    commands_args::{
15        AdoptArgs, CloneArgs, CommitArgs, DiffArgs, DoctorArgs, INIT_VERB, InitArgs, LandArgs,
16        LogArgs, PullArgs, PushArgs, ReadyArgs, ResolveArgs, RevertArgs, SnapshotArgs, SyncArgs,
17        ThreadStartArgs, UndoArgs, WatchArgs,
18    },
19};
20#[cfg(feature = "client")]
21use super::{AuthCommands, ClaimArgs};
22
23#[derive(Clone, Debug, Args)]
24pub struct FsckArgs {
25    /// Full check (includes content verification).
26    #[arg(long)]
27    pub full: bool,
28
29    /// Run slower graph and signature integrity checks.
30    #[arg(long)]
31    pub thorough: bool,
32
33    /// Verify offline authorship identity and review-signature chains.
34    #[arg(long, requires = "thorough")]
35    pub provenance: bool,
36
37    /// Include Git projection, mapping, notes, and checkout checks.
38    #[arg(long)]
39    pub git: bool,
40
41    #[command(subcommand)]
42    pub command: Option<FsckCommands>,
43}
44
45#[derive(Clone, Debug, Subcommand)]
46pub enum FsckCommands {
47    /// Repair an integrity surface, then verify it.
48    Repair {
49        #[command(subcommand)]
50        target: FsckRepairCommands,
51    },
52}
53
54#[derive(Clone, Debug, Subcommand)]
55pub enum FsckRepairCommands {
56    /// Reconcile Git projection metadata or one projected ref.
57    Git(FsckRepairGitArgs),
58}
59
60#[derive(Clone, Debug, Args)]
61pub struct FsckRepairGitArgs {
62    /// Git ref to reconcile. Required for native repositories.
63    #[arg(long = "ref", value_name = "BRANCH")]
64    pub ref_name: Option<String>,
65
66    /// Assert the intended authority direction.
67    #[arg(long, value_parser = ["git", "heddle"])]
68    pub prefer: Option<String>,
69
70    /// Show the authority-valid repair without changing refs.
71    #[arg(long)]
72    pub preview: bool,
73}
74
75#[derive(Subcommand)]
76pub enum Commands {
77    /// Initialize Heddle in a directory or existing Git checkout.
78    #[command(name = INIT_VERB)]
79    Init(InitArgs),
80
81    /// Adopt Git history into Heddle-native source authority.
82    ///
83    /// Git Overlay is the normal existing-Git mode: Git keeps source objects,
84    /// refs, index, and worktree state while Heddle stores metadata in
85    /// `.heddle`. `adopt` imports history and moves source authority to Heddle.
86    Adopt(AdoptArgs),
87
88    /// Curated, progressive-disclosure help.
89    ///
90    /// `heddle help` prints the locked everyday verbs. `heddle help
91    /// <topic>` prints the topic page (e.g. `model`, `daemon`,
92    /// `signals`, `git-concepts`). `heddle help <command path>` falls
93    /// through to that command's `--help` so the printer never
94    /// duplicates clap's per-verb derivation.
95    Help {
96        /// Topic name (`model`, `daemon`, `signals`, …) or command
97        /// path. When omitted, prints the curated default.
98        #[arg(value_name = "TOPIC_OR_COMMAND")]
99        topics: Vec<String>,
100    },
101
102    /// Show what needs attention and the next safe Heddle action.
103    #[command(after_help = "\
104Examples:
105  heddle status               # current thread, dirty paths, recommended next step
106  heddle status --short       # one-line summary for shell prompts
107  heddle status --watch       # live dashboard that refreshes in place
108")]
109    Status {
110        /// Short format.
111        #[arg(short, long)]
112        short: bool,
113
114        /// Continuously refresh status.
115        #[arg(long)]
116        watch: bool,
117
118        /// Internal helper for tests: stop after N watch updates.
119        #[arg(long, hide = true)]
120        watch_iterations: Option<usize>,
121
122        /// Internal helper for tests: polling interval in milliseconds.
123        #[arg(long, hide = true)]
124        watch_interval_ms: Option<u64>,
125    },
126
127    /// Stream live oplog activity.
128    ///
129    /// Tails the repository's append-only oplog file like `tail -f`,
130    /// emitting snapshots, merges, and thread events as they happen.
131    /// Exits on Ctrl-C.
132    Watch(WatchArgs),
133
134    /// Verify this workspace; exits nonzero until every check is clean.
135    #[command(after_help = "\
136Checks: Git mapping, worktree, remote, operation, clone verification, machine contract.
137
138Examples:
139  heddle verify                # strict verification gate and next recovery step
140  heddle verify --verbose      # full proof rows and machine-contract details
141  heddle verify --output json  # proof JSON when clean; error envelope when blocked
142")]
143    Verify {
144        /// Verify each state's offline authorship and review-signature chain.
145        #[arg(long)]
146        provenance: bool,
147    },
148
149    /// Explain repository health, or run targeted doctor checks.
150    ///
151    /// `heddle doctor` (no subcommand) reports repository health and
152    /// the next recovery step. `heddle doctor docs` diff-checks markdown
153    /// documentation against
154    /// the actual CLI surface and exits non-zero on drift — wire it
155    /// into CI to stop docs from going stale.
156    Doctor(DoctorArgs),
157
158    /// Create or resume an isolated thread for focused work.
159    Start(ThreadStartArgs),
160
161    /// Run Heddle CI checks. Finds `ci.ts` / `ci.rs` / `ci.go`, compiles if needed, then runs.
162    #[cfg(feature = "ci")]
163    Ci {
164        #[command(subcommand)]
165        command: super::CiCommands,
166    },
167
168    /// Automation/workflow command: refresh the current thread onto its target when safe.
169    Sync(SyncArgs),
170
171    /// Continue the active operation without remembering the specific subcommand.
172    Continue,
173
174    /// Abort the active operation without remembering the specific subcommand.
175    Abort,
176
177    /// Integrate a ready thread into its local target.
178    ///
179    /// `land` is the local integration verb: capture outstanding work if needed,
180    /// refresh against the target when safe, and land the thread. It fails
181    /// closed when conflicts or other blockers exist. Pair it with `ready`
182    /// when you want the verdict and next action before landing anything.
183    Land(LandArgs),
184
185    /// Prepare this thread for review or merge.
186    ///
187    /// `ready` captures outstanding work if needed, checks conflicts,
188    /// blockers, freshness, and semantic risk, then marks the thread
189    /// ready or blocked and prints the next action. It never lands,
190    /// checkpoints, or pushes; use it when you want Heddle's verdict
191    /// before integrating the work.
192    Ready(ReadyArgs),
193
194    /// Capture a recoverable Heddle step for undo, provenance, and review.
195    Capture(SnapshotArgs),
196
197    /// Write captured source history to `.git` in Git Overlay.
198    Commit(CommitArgs),
199
200    /// Show state history.
201    ///
202    /// By default, when a thread name is given (e.g. `heddle log master`),
203    /// the walk is *first-parent only* — equivalent to `git log
204    /// --first-parent <branch>`. To see every ancestor reachable through
205    /// merge commits, pass `--graph` (which renders the full DAG) or
206    /// `--all` (which lists every state regardless of ancestry).
207    #[command(visible_alias = "history")]
208    Log(LogArgs),
209
210    /// Show state details.
211    Show {
212        /// State by physical state ID, logical change ID, or unambiguous prefix.
213        /// Defaults to HEAD.
214        state: Option<String>,
215    },
216
217    /// Show what changed in the worktree, a thread, or two states.
218    Diff(DiffArgs),
219
220    /// Open or resolve discussions anchored to symbols.
221    ///
222    /// Open a discussion against a symbol; append turns;
223    /// resolve by edit or dismiss. Anchors
224    /// travel across renames and cross-file moves on subsequent
225    /// state mutations.
226    ///
227    /// Native Heddle only. Discussions live in `.heddle` and travel
228    /// over `heddle push` / `heddle pull` to a Heddle remote. They are
229    /// not projected into Git, so `git clone` does not carry them; in
230    /// Git Overlay mode they are local to that working copy.
231    #[command(after_help = "\
232Scope:
233  Native Heddle only. Discussions are stored in `.heddle` and move over
234  `heddle push` / `heddle pull`. Git does not carry them: a `git clone` of a
235  Git Overlay repository arrives with no discussions and no Heddle store.
236
237Examples:
238  heddle discuss open src/auth.rs verify 'Should this reject expired tokens?'  # anchor a discussion
239  heddle discuss append <id> 'switched to argon2'          # add a turn
240  heddle discuss resolve <id> --mode by-edit --state HEAD
241")]
242    Discuss {
243        #[command(subcommand)]
244        command: DiscussCommands,
245    },
246
247    /// Structured query over the operation log. Filter by
248    /// actor, time window, signal kind, symbol, thread, verbs. Returns
249    /// structured results consumable by agents.
250    Query(QueryArgs),
251
252    /// Review a state — render the payload, sign, see signal health.
253    ///
254    /// `heddle review show` renders the review payload (summary,
255    /// agent narrative, in-budget signals, anchored discussions).
256    /// `heddle review sign` submits a `read` / `agent_preview` /
257    /// `agent_co_review` signature on the state. `heddle review
258    /// health` reports per-module signal fire rates over a rolling
259    /// window.
260    #[command(after_help = "\
261Examples:
262  heddle review show HEAD                                # render the review payload for HEAD
263  heddle review show HEAD --base last-turn               # review this agent peer's turn
264  heddle review sign HEAD --kind read --public-key <hex> --signature <hex> --signed-at-unix <ts>
265  heddle review health --window 7                       # signal fire-rates over recent states
266")]
267    Review {
268        #[command(subcommand)]
269        command: ReviewCommands,
270    },
271
272    /// Redact a sensitive blob in a state so reads return a stub
273    /// instead of the content.
274    ///
275    /// `heddle redact apply` declares a redaction; the blob bytes stay
276    /// on disk and reads return the operator-supplied stub. `heddle
277    /// redact purge` afterward physically removes the bytes. Both are signed,
278    /// attributed, oplog-audited operations. See
279    /// `docs/PRINCIPLES.md` (the honesty principle) for context.
280    Redact {
281        #[command(subcommand)]
282        command: RedactCommands,
283    },
284
285    /// Declare and inspect a state's audience visibility tier.
286    ///
287    /// `heddle visibility set` binds a tier to a state; `promote` lifts it to
288    /// a less-restrictive tier via a superseding record; `show` reports the
289    /// effective tier; `list` enumerates non-public states. Capture binds the
290    /// inherited `[review.discussion] default_visibility` automatically
291    /// (Invariant A) — these verbs are the explicit operator overrides.
292    Visibility {
293        #[command(subcommand)]
294        command: VisibilityCommands,
295    },
296
297    /// Run a child with a confidential runtime profile.
298    ///
299    /// `heddle env run --profile <name> -- <cmd>` asks the local policy
300    /// broker to unwrap named slots and injects them into the child
301    /// environment only. Values never land in the worktree, the store, or
302    /// command JSON. Same-UID callers are cooperative; OS isolation is later.
303    #[command(after_help = "\
304Examples:
305  heddle env list
306  heddle env create --name local --from-env DATABASE_URL
307  heddle env run --profile local -- printenv DATABASE_URL
308")]
309    Env {
310        #[command(subcommand)]
311        command: EnvCommands,
312    },
313
314    /// Revert changes from a state.
315    Revert(RevertArgs),
316
317    /// Undo the last Heddle operation.
318    Undo(UndoArgs),
319
320    /// Manage threads.
321    Thread {
322        #[command(subcommand)]
323        command: ThreadCommands,
324    },
325
326    /// Shell integration helpers (auto-cd on thread start/switch/cd).
327    Shell {
328        #[command(subcommand)]
329        command: ShellCommands,
330    },
331
332    /// Print a tab-completion script for bash, zsh, or fish.
333    ///
334    /// With no shell, prints install lines. With `bash`, `zsh`, or `fish`,
335    /// emits the same script as `heddle shell completion`.
336    Completions {
337        /// Shell to generate completion for: bash, zsh, or fish.
338        #[arg(value_name = "SHELL")]
339        shell: Option<String>,
340    },
341
342    /// Internal shell-completion candidate helper.
343    #[command(name = "complete", alias = "__complete", hide = true)]
344    Complete {
345        /// Candidate set to print, one candidate per line.
346        #[arg(value_enum)]
347        subject: CompletionSubject,
348    },
349
350    /// Resolve merge conflicts.
351    Resolve(ResolveArgs),
352
353    /// Explicit interoperability with other version-control formats.
354    #[cfg(feature = "git-overlay")]
355    Bridge {
356        #[command(subcommand)]
357        command: BridgeCommands,
358    },
359
360    /// Push the source-authoritative history to a remote.
361    Push(PushArgs),
362
363    /// Pull source-authoritative history from a remote.
364    Pull(PullArgs),
365
366    /// Manage remote repositories.
367    Remote {
368        #[command(subcommand)]
369        command: RemoteCommands,
370    },
371
372    /// Authenticate with a Heddle server.
373    #[cfg(feature = "client")]
374    Auth {
375        #[command(subcommand)]
376        command: AuthCommands,
377    },
378
379    /// Offer this agent account for a human to claim.
380    ///
381    /// Prints a short-lived bearer link, then keeps the agent's Iroh endpoint
382    /// online until the human finishes, the offer expires, or Ctrl-C stops it.
383    #[cfg(feature = "client")]
384    #[command(after_help = "\
385Examples:
386  heddle claim
387  heddle claim --timeout 30m
388  heddle claim --server weft.example --web-origin https://heddle.example
389")]
390    Claim(ClaimArgs),
391
392    /// Report the capture actor, then hosted auth.
393    ///
394    /// The capture actor is who the next capture is attributed to
395    /// (`user_config`, `init --principal-*`, or `HEDDLE_PRINCIPAL_*`).
396    /// Hosted auth is whether this machine has a server credential.
397    /// These are different objects. `heddle auth login` does not set the
398    /// local actor. `whoami` only reads; it never attaches a credential.
399    #[cfg(feature = "client")]
400    #[command(after_help = "\
401The capture actor and hosted auth are different objects:
402  capture actor  who the next capture is attributed to
403                 (user_config, init --principal-*, or HEDDLE_PRINCIPAL_*)
404  hosted auth    whether this machine has a credential for the server
405                 (heddle auth login). whoami never attaches a credential.
406
407Examples:
408  heddle whoami                       # capture actor first, then hosted auth
409  heddle whoami --output json         # machine-readable, stable output_kind shape
410  heddle whoami --server api.heddle.sh")]
411    Whoami {
412        /// Heddle server address (defaults to the configured server).
413        #[arg(long)]
414        server: Option<String>,
415    },
416
417    /// Manage code context annotations.
418    ///
419    /// Native Heddle only. Annotations live in `.heddle`, and travel
420    /// over `heddle push` / `heddle pull` to a Heddle remote. They are
421    /// deliberately not projected into Git — not into `refs/notes/*`,
422    /// not into a tracked file — so `git push` and `git clone` do not
423    /// carry them. In Git Overlay mode annotations still work and are
424    /// still useful; they are simply local to that working copy.
425    #[command(after_help = "\
426Scope:
427  Native Heddle only. Annotations are stored in `.heddle` and move over
428  `heddle push` / `heddle pull`. Git does not carry them: a `git clone` of a
429  Git Overlay repository arrives with no annotations and no Heddle store.
430
431Examples:
432  heddle context set --path src/auth.rs --scope symbol:verify --kind invariant -m 'returns false on timing mismatch'
433  heddle context get --path src/auth.rs --scope symbol:verify
434  heddle context list --prefix src/auth          # everything attached under a path
435  heddle context check --path src/auth.rs        # surface annotations for editor tooling
436")]
437    Context {
438        #[command(subcommand)]
439        command: ContextCommands,
440    },
441
442    /// Manage ambient harness integrations.
443    Integration {
444        #[command(subcommand)]
445        command: IntegrationCommands,
446    },
447
448    /// Semantic analysis queries (call-graph hot-spots, churn,
449    /// signature-stability surfaces).
450    #[cfg(feature = "semantic")]
451    Semantic {
452        #[command(subcommand)]
453        command: SemanticCommands,
454    },
455
456    /// FUSE mount-daemon control plane — distinct from `agent`.
457    ///
458    /// `heddle daemon serve` runs a foreground mount daemon that
459    /// owns FUSE sessions for `--workspace virtualized --daemon`
460    /// threads. It is normally spawned on demand by the per-thread
461    /// CLI; running it interactively is for debugging.
462    /// `status` reports liveness/uptime/mount count without spawning;
463    /// `stop` asks a running daemon to drain mounts and exit.
464    Daemon {
465        #[command(subcommand)]
466        command: DaemonCommands,
467    },
468
469    /// Box-scoped network daemon control plane — distinct from
470    /// `daemon` (FUSE mounts).
471    ///
472    /// `heddle netd serve` runs a long-lived async daemon that binds
473    /// the machine's single persistent Iroh endpoint on the persisted
474    /// device node id and keeps it relay-reachable, so outstanding
475    /// claim links keep resolving across restarts. Unlike `daemon`, it
476    /// is not gated on Linux/FUSE and never idle-exits. `status`
477    /// reports liveness and the advertised node id; `stop` asks a
478    /// running daemon to close its endpoint and exit.
479    Netd {
480        #[command(subcommand)]
481        command: NetdCommands,
482    },
483
484    /// Agent reservation and one-shot orchestration API.
485    ///
486    /// `heddle agent reserve|capture|ready|release|list|heartbeat` is the stable
487    /// JSON contract orchestrators use to coordinate parallel
488    /// writers. `heddle daemon` remains the distinct FUSE mount control plane.
489    Agent {
490        #[command(subcommand)]
491        command: AgentCommands,
492    },
493
494    /// Inspect and refresh rebuildable performance sidecars.
495    Maintenance {
496        #[command(subcommand)]
497        command: MaintenanceCommands,
498    },
499
500    /// Clone from remote.
501    Clone(CloneArgs),
502
503    /// Manage repository hooks.
504    Hook {
505        #[command(subcommand)]
506        command: HookCommands,
507    },
508}
509
510/// Maintenance subcommands.
511#[derive(Clone, Debug, clap::Subcommand)]
512pub enum MaintenanceCommands {
513    /// Verify repository integrity or explicitly repair one surface.
514    Fsck(FsckArgs),
515
516    /// Inspect repository performance sidecars and repo shape.
517    Inspect,
518
519    /// Refresh repository performance sidecars without changing repository meaning.
520    Refresh,
521
522    /// Repack native objects now through the resource-controlled scheduler.
523    Repack,
524
525    /// Garbage collect unreachable objects.
526    Gc {
527        /// Prune unreachable objects.
528        #[arg(long)]
529        prune: bool,
530
531        /// Aggressive garbage collection.
532        #[arg(long)]
533        aggressive: bool,
534
535        /// Show what would be removed without removing.
536        #[arg(long)]
537        dry_run: bool,
538    },
539
540    /// Inspect and repair the operation log.
541    ///
542    /// `heddle maintenance oplog recover` explicitly salvages a truncated or
543    /// torn oplog, reporting what was recovered — the operator-facing
544    /// entrypoint over the same recovery the everyday read path runs
545    /// automatically.
546    Oplog {
547        #[command(subcommand)]
548        command: OplogCommands,
549    },
550}
551
552/// Daemon control plane subcommands. See `Commands::Daemon`.
553#[derive(Clone, Debug, clap::Subcommand)]
554pub enum DaemonCommands {
555    /// Run a foreground mount daemon for this repository.
556    ///
557    /// Normally spawned on demand by the per-thread CLI when
558    /// `--daemon` is passed. Running interactively is for
559    /// debugging the daemon protocol.
560    Serve,
561
562    /// Report daemon liveness, version, uptime, and active mount
563    /// count. No-op success when the daemon isn't running.
564    Status,
565
566    /// Ask the running daemon to drain its mounts and exit. Sweeps
567    /// any leftover registry entries with `fusermount -u` as a
568    /// safety net before returning.
569    Stop,
570}
571
572/// Box-scoped network daemon subcommands. See `Commands::Netd`.
573#[derive(Clone, Debug, clap::Subcommand)]
574pub enum NetdCommands {
575    /// Run the foreground network daemon: bind the persistent device
576    /// endpoint, keep relays online, and serve same-uid control RPCs.
577    /// Never idle-exits.
578    Serve,
579
580    /// Report network-daemon liveness and the advertised device node
581    /// id. No-op success when the daemon isn't running.
582    Status,
583
584    /// Ask the running network daemon to close its endpoint and exit.
585    Stop,
586}