Skip to main content

heddle_cli_args/cli/cli_args/
commands_args.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Named argument structs for top-level CLI commands.
3
4#[cfg(feature = "git-overlay")]
5use super::commands_git_projection::SyncCommands;
6
7/// Arguments for the `init` command.
8#[derive(Clone, Debug, clap::Args)]
9#[command(after_help = "\
10Examples:
11  heddle init                                                    # initialize here; existing Git becomes Git Overlay
12  heddle init my-project                                         # initialize a native Heddle subdirectory
13  heddle init --principal-name 'Ada Lovelace' --principal-email ada@example.com
14")]
15pub struct InitArgs {
16    /// Directory to initialize (default: current directory).
17    pub path: Option<std::path::PathBuf>,
18
19    /// Principal name for attribution.
20    #[arg(long)]
21    pub principal_name: Option<String>,
22
23    /// Principal email for attribution.
24    #[arg(long)]
25    pub principal_email: Option<String>,
26
27    /// Install harness integrations after init.
28    #[arg(long)]
29    pub install_harnesses: Option<String>,
30
31    /// Skip harness integration installation during init.
32    #[arg(long)]
33    pub no_harness_install: bool,
34
35    /// Preferred install scope (`repo` or `user`).
36    #[arg(long, visible_alias = "scope", default_value = "repo")]
37    pub harness_install_scope: String,
38
39    /// Overwrite Heddle-managed integration entries when needed.
40    #[arg(long)]
41    pub harness_install_force: bool,
42}
43
44/// Arguments for the `adopt` command.
45#[derive(Clone, Debug, clap::Args)]
46#[command(after_help = "\
47Examples:
48  heddle adopt                                # adopt all local Git refs into native Heddle storage
49  heddle adopt --ref main                     # adopt one branch or tag
50  heddle adopt ../repo --ref main --ref v1.0  # adopt selected refs in another repo
51
52Adoption imports Git refs, makes Heddle the source authority, and retains `.git` for explicit Git Projection. Normal Git Overlay setup uses `heddle init` instead.
53")]
54pub struct AdoptArgs {
55    /// Git repository to adopt into native Heddle storage (default: current directory).
56    pub path: Option<std::path::PathBuf>,
57
58    /// Git branch or tag to adopt. Repeat for selected refs; omit to adopt all refs.
59    #[arg(long = "ref", value_name = "REF")]
60    pub refs: Vec<String>,
61}
62
63/// Arguments for the `doctor` command (and its subcommands).
64///
65/// `heddle doctor` with no subcommand reports repository, thread, actor,
66/// and workspace health. `heddle doctor docs`
67/// runs the documentation truthfulness checker — see [`DoctorDocsArgs`]
68/// for that surface.
69#[derive(Clone, Debug, clap::Args)]
70pub struct DoctorArgs {
71    /// Include local timing for the diagnosis read path.
72    ///
73    /// Only honoured when no subcommand is given. Subcommands like
74    /// `heddle doctor docs` ignore it.
75    #[arg(long, global = false)]
76    pub profile: bool,
77
78    #[command(subcommand)]
79    pub command: Option<DoctorCommands>,
80}
81
82/// `heddle doctor <subcommand>` surface.
83#[derive(Clone, Debug, clap::Subcommand)]
84pub enum DoctorCommands {
85    /// Diff-check markdown documentation against the actual CLI surface.
86    ///
87    /// Walks every `heddle <verb> [<subverb>] [flags]` invocation in
88    /// the requested markdown files and reports any drift: missing
89    /// verbs, unknown long flags, or invalid literal values for flags
90    /// like `--workspace`, `--scope`, and `--kind`.
91    ///
92    /// Exits non-zero when any drift is found, so it's safe to run in
93    /// CI. Pair with `--output json` for structured output. Run on every PR
94    /// to prevent the docs from drifting from the CLI again.
95    Docs(DoctorDocsArgs),
96
97    /// Drift-check `docs/json-schemas.md` against the registered
98    /// schemas.
99    ///
100    /// Generates the canonical schema for every verb in the schemas
101    /// registry, parses every `## heddle <verb> --output json` sample in
102    /// `docs/json-schemas.md`, and verifies that every key in the
103    /// sample is declared in the schema. Exits non-zero on drift.
104    /// Pair with `--output json` for CI. Run alongside `heddle doctor docs`
105    /// on every PR.
106    Schemas(DoctorSchemasArgs),
107}
108
109/// Arguments for `heddle doctor docs`.
110#[derive(Clone, Debug, clap::Args)]
111pub struct DoctorDocsArgs {
112    /// Markdown file(s) to scan. Repeatable.
113    ///
114    /// When neither `--path` nor `--all` is given, defaults to
115    /// `--all`.
116    #[arg(long, value_name = "PATH")]
117    pub path: Vec<std::path::PathBuf>,
118
119    /// Scan every tracked `.md` file in the repository.
120    #[arg(long)]
121    pub all: bool,
122}
123
124/// Arguments for `heddle doctor schemas`.
125#[derive(Clone, Debug, clap::Args)]
126pub struct DoctorSchemasArgs {
127    /// Refresh the generated command-contract coverage sample in
128    /// `docs/json-schemas.md`, then run the normal schema drift check.
129    #[arg(long)]
130    pub update_docs: bool,
131}
132
133fn parse_confidence(s: &str) -> Result<f32, String> {
134    let value = s
135        .parse::<f32>()
136        .map_err(|_| format!("confidence must be a finite number from 0.0 to 1.0, got `{s}`"))?;
137    if !value.is_finite() || !(0.0..=1.0).contains(&value) {
138        return Err(format!(
139            "confidence must be a finite number from 0.0 to 1.0, got `{s}`"
140        ));
141    }
142    Ok(value)
143}
144
145/// Arguments for the `capture` command.
146#[derive(Clone, Debug, clap::Args)]
147#[command(after_help = "\
148Examples:
149  heddle capture -m 'add login route'           # capture the worktree with intent
150  heddle capture -m 'wip' --confidence 0.6      # honest confidence on a draft step
151
152Agent automation flags (provider/model/session/policy/split) are hidden here.
153Run `heddle help agent-flags`, or `heddle capture --help-agent` to list them inline.
154")]
155pub struct SnapshotArgs {
156    /// Reveal the hidden agent-automation flags inline instead of capturing.
157    /// A first-class clap flag so the whole command line (including global
158    /// options in any spelling clap accepts) is parsed by clap; the dispatch
159    /// arm inspects the parsed result rather than scanning raw tokens.
160    /// `hide`d to keep everyday `capture --help` terse (the after-help
161    /// pointer is the discovery route). It is still a registered clap arg,
162    /// so `doctor docs` recognizes `heddle capture --help-agent` via the
163    /// registered-but-hidden flag seam — the machine contract stays in sync
164    /// without cluttering human help.
165    #[arg(long, hide = true)]
166    pub help_agent: bool,
167
168    /// Natural language intent for this recoverable step.
169    #[arg(short = 'm', long, visible_alias = "message")]
170    pub intent: Option<String>,
171
172    /// Confidence level (0.0-1.0).
173    #[arg(long, value_parser = parse_confidence)]
174    pub confidence: Option<f32>,
175
176    /// Allow a large or deletion-heavy capture without the safety preflight.
177    #[arg(short, long)]
178    pub force: bool,
179
180    /// Override HEDDLE_AGENT_PROVIDER.
181    #[arg(long, hide = true)]
182    pub agent_provider: Option<String>,
183
184    /// Override HEDDLE_AGENT_MODEL.
185    #[arg(long, hide = true)]
186    pub agent_model: Option<String>,
187
188    /// Override active agent session id.
189    #[arg(long, hide = true)]
190    pub agent_session: Option<String>,
191
192    /// Override active agent session segment.
193    #[arg(long, hide = true)]
194    pub agent_segment: Option<String>,
195
196    /// Override HEDDLE_AGENT_POLICY.
197    #[arg(long, hide = true)]
198    pub policy: Option<String>,
199
200    /// Omit policy attribution.
201    #[arg(long, hide = true)]
202    pub no_policy: bool,
203
204    /// Omit agent attribution.
205    #[arg(long, hide = true)]
206    pub no_agent: bool,
207
208    /// Split selected paths into another thread instead of capturing the whole worktree.
209    #[arg(long, hide = true)]
210    pub split: bool,
211
212    /// Target thread when using `--split`.
213    #[arg(long, hide = true, requires = "split")]
214    pub into: Option<String>,
215
216    /// Repository-relative path prefix to include when using `--split`.
217    #[arg(long = "path", hide = true, requires = "split", value_name = "PATH")]
218    pub paths: Vec<String>,
219}
220
221/// Arguments for the Git-overlay `commit` command.
222#[derive(Clone, Debug, clap::Args)]
223#[command(after_help = "\
224Examples:
225  heddle capture -m 'add login route'
226  heddle commit
227  heddle commit -m 'add login route'
228
229Behavior:
230  Commits the complete captured tree and replaces the Git index with that tree.
231  Git pre-commit and commit-msg hooks are not run.
232")]
233pub struct CommitArgs {
234    /// Git commit message. Defaults to the current capture intent.
235    #[arg(short = 'm', long = "message")]
236    pub message: Option<String>,
237}
238
239/// Arguments for the `log` command.
240#[derive(Clone, Debug, clap::Args)]
241#[command(after_help = "\
242Examples:
243  heddle log                          # walk the current thread
244  heddle log --oneline -n 20          # 20 most recent states in compact form
245  heddle log --timeline               # show agent timeline tool-call cursor
246  heddle log --reflog                 # include re-attributed history
247  heddle log --path src/auth.rs       # restrict to states touching a path
248")]
249pub struct LogArgs {
250    /// Starting state (default: HEAD).
251    pub state: Option<String>,
252
253    /// Maximum states to show.
254    #[arg(short = 'n', long, default_value = "20")]
255    pub limit: usize,
256
257    /// Show all states, not just ancestors.
258    #[arg(long)]
259    pub all: bool,
260
261    /// Show ASCII DAG graph.
262    #[arg(long)]
263    pub graph: bool,
264
265    /// One state per line.
266    #[arg(long)]
267    pub oneline: bool,
268
269    /// Show Git-overlay reflog entries instead of Heddle capture history.
270    #[arg(long)]
271    pub reflog: bool,
272
273    /// Show agent timeline tool-call navigation instead of capture history.
274    #[arg(long)]
275    pub timeline: bool,
276
277    /// Timeline thread to render with `--timeline`.
278    #[arg(long, default_value = "main")]
279    pub thread: String,
280
281    /// Filter by agent model.
282    #[arg(long)]
283    pub agent: Option<String>,
284
285    /// Show only states that changed the given repository-relative path.
286    #[arg(long = "path", value_name = "PATH")]
287    pub paths: Vec<String>,
288
289    /// Lower bound: walk back until reaching this state or marker
290    /// (exclusive of the bound itself). Accepts a marker name, a
291    /// state ID (short or full), or any spec the state resolver
292    /// understands. When combined with `--limit`, the bound is
293    /// applied first, then the result is trimmed to `--limit`.
294    #[arg(long, value_name = "STATE")]
295    pub since: Option<String>,
296}
297
298/// Arguments for `heddle timeline`.
299#[derive(Clone, Debug, clap::Args)]
300pub struct TimelineArgs {
301    #[command(subcommand)]
302    pub command: TimelineCommands,
303}
304
305/// Timeline navigation action commands.
306#[derive(Clone, Debug, clap::Subcommand)]
307pub enum TimelineCommands {
308    /// Show the current timeline cursor, counts, and recovery status.
309    Status(TimelineStatusArgs),
310
311    /// Record the start of a native tool timeline step.
312    #[command(name = "record-start")]
313    RecordStart(TimelineRecordStartArgs),
314
315    /// Record the finish of a native tool timeline step.
316    #[command(name = "record-finish")]
317    RecordFinish(TimelineRecordFinishArgs),
318
319    /// Fork a timeline branch from a step or native harness tool call.
320    #[command(after_help = "\
321Examples:
322  heddle timeline fork --step tls-abc --branch tlb-experiment
323  heddle timeline fork --tool-call call_123 --session ses_456 --branch tlb-alt
324")]
325    Fork(TimelineForkArgs),
326
327    /// Reset the logical timeline cursor, optionally materializing checkout files.
328    #[command(after_help = "\
329Examples:
330  heddle timeline reset --step tls-abc
331  heddle timeline reset --tool-call call_123 --materialize
332")]
333    Reset(TimelineResetArgs),
334
335    /// Recover a pending timeline materialization after an interrupted reset/seek.
336    Recover(TimelineRecoverArgs),
337}
338
339/// Shared selector arguments for timeline action commands.
340#[derive(Clone, Debug, clap::Args)]
341pub struct TimelineTargetArgs {
342    /// Timeline thread to target.
343    #[arg(long, default_value = "main")]
344    pub thread: String,
345
346    /// Constrain the target to this branch when selecting by step/current cursor.
347    #[arg(long = "from-branch", value_name = "BRANCH")]
348    pub from_branch: Option<String>,
349
350    /// Target a timeline step id.
351    #[arg(long, conflicts_with_all = ["tool_call", "undo", "redo", "current"])]
352    pub step: Option<String>,
353
354    /// Target a native harness tool call id, such as an OpenCode tool call id.
355    #[arg(long = "tool-call", conflicts_with_all = ["step", "undo", "redo", "current"])]
356    pub tool_call: Option<String>,
357
358    /// Native harness name for `--tool-call`.
359    #[arg(long, default_value = "opencode")]
360    pub harness: String,
361
362    /// Native harness session id for `--tool-call`.
363    #[arg(long)]
364    pub session: Option<String>,
365
366    /// Native harness message id for `--tool-call`.
367    #[arg(long)]
368    pub message: Option<String>,
369
370    /// Target the previous step from the current cursor.
371    #[arg(long, conflicts_with_all = ["step", "tool_call", "redo", "current"])]
372    pub undo: bool,
373
374    /// Target the next step from the current cursor.
375    #[arg(long, conflicts_with_all = ["step", "tool_call", "undo", "current"])]
376    pub redo: bool,
377
378    /// Target the current logical cursor.
379    #[arg(long, conflicts_with_all = ["step", "tool_call", "undo", "redo"])]
380    pub current: bool,
381}
382
383/// Arguments for `heddle timeline fork`.
384#[derive(Clone, Debug, clap::Args)]
385pub struct TimelineForkArgs {
386    #[command(flatten)]
387    pub target: TimelineTargetArgs,
388
389    /// New timeline branch id. Generated when omitted.
390    #[arg(long, value_name = "BRANCH")]
391    pub branch: Option<String>,
392
393    /// Branch reason: explicit-fork, edit-from-rewound-cursor, retry, fan-out.
394    #[arg(long, default_value = "explicit-fork")]
395    pub reason: String,
396}
397
398/// Arguments for `heddle timeline reset`.
399#[derive(Clone, Debug, clap::Args)]
400pub struct TimelineResetArgs {
401    #[command(flatten)]
402    pub target: TimelineTargetArgs,
403
404    /// Materialize checkout files to the target state after moving the cursor.
405    #[arg(long)]
406    pub materialize: bool,
407
408    /// Materialization mode: fail-if-dirty or capture-current-then-seek.
409    #[arg(long, default_value = "fail-if-dirty")]
410    pub mode: String,
411}
412
413/// Arguments for `heddle timeline recover`.
414#[derive(Clone, Debug, clap::Args)]
415pub struct TimelineRecoverArgs {
416    /// Timeline thread to recover.
417    #[arg(long, default_value = "main")]
418    pub thread: String,
419}
420
421/// Arguments for `heddle timeline status`.
422#[derive(Clone, Debug, clap::Args)]
423pub struct TimelineStatusArgs {
424    /// Timeline thread to inspect.
425    #[arg(long, default_value = "main")]
426    pub thread: String,
427}
428
429/// Shared scrubbed native tool-call identity for timeline recording commands.
430#[derive(Clone, Debug, clap::Args)]
431pub struct TimelineRecordToolArgs {
432    /// Timeline thread to record into.
433    #[arg(long, default_value = "main")]
434    pub thread: String,
435
436    /// Native harness name.
437    #[arg(long, default_value = "opencode")]
438    pub harness: String,
439
440    /// Native harness session id.
441    #[arg(long)]
442    pub session: Option<String>,
443
444    /// Native harness message id.
445    #[arg(long)]
446    pub message: Option<String>,
447
448    /// Native harness tool-call id.
449    #[arg(long = "tool-call")]
450    pub tool_call: String,
451
452    /// Explicit timeline step id. When omitted, Heddle derives one from the native identity.
453    #[arg(long = "step-id")]
454    pub step_id: Option<String>,
455
456    /// Explicit timeline branch id. Defaults to the current timeline branch or `tlb-main`.
457    #[arg(long = "branch")]
458    pub branch: Option<String>,
459
460    /// Scrubbed human summary for the native payload.
461    #[arg(long = "summary")]
462    pub summary: Option<String>,
463
464    /// Hash of the native payload, never the raw payload bytes.
465    #[arg(long = "payload-hash")]
466    pub payload_hash: Option<String>,
467}
468
469/// Arguments for `heddle timeline record-start`.
470#[derive(Clone, Debug, clap::Args)]
471pub struct TimelineRecordStartArgs {
472    #[command(flatten)]
473    pub tool: TimelineRecordToolArgs,
474
475    /// Stable tool name such as `bash`, `edit`, or `read`.
476    #[arg(long = "tool-name", default_value = "tool")]
477    pub tool_name: String,
478}
479
480/// Arguments for `heddle timeline record-finish`.
481#[derive(Clone, Debug, clap::Args)]
482pub struct TimelineRecordFinishArgs {
483    #[command(flatten)]
484    pub tool: TimelineRecordToolArgs,
485
486    /// Tool result status: succeeded, failed, or cancelled.
487    #[arg(long, default_value = "succeeded")]
488    pub status: String,
489}
490
491/// Arguments for the `retro` command.
492///
493/// `heddle retro --since <marker-or-state>` summarizes a working
494/// session by combining oplog, agent registry, marker, and context
495/// annotation reads into one structured payload. Replaces the
496/// reconstruct-from-`heddle log` boilerplate agents wrote before.
497#[derive(Clone, Debug, clap::Args)]
498pub struct RetroArgs {
499    /// Lower bound: marker name or state id (short or full). When
500    /// omitted, the verb walks back to the most recent `Claude Code
501    /// turn`-shaped intent or to one hour ago, whichever is more
502    /// recent.
503    #[arg(long)]
504    pub since: Option<String>,
505
506    /// Include merge entries in the output payload (off by default
507    /// because merges are noisy in agent retros).
508    #[arg(long)]
509    pub include_merges: bool,
510
511    /// Include undo entries in the output payload (off by default
512    /// because undos are noisy in agent retros).
513    #[arg(long)]
514    pub include_undos: bool,
515
516    /// Render full annotation/intent content rather than excerpts.
517    /// Aliased as `--full` because the global `-v/--verbose` flag is
518    /// already wired as a u8 verbosity counter on `Cli`.
519    #[arg(long = "full", alias = "expand")]
520    pub full: bool,
521}
522
523/// Arguments for the `diff` command.
524#[derive(Clone, Debug, clap::Args)]
525#[command(after_help = "\
526Patch compatibility:
527  --patch output uses Git-compatible unified diff, including extended headers for type and mode changes.
528")]
529pub struct DiffArgs {
530    /// Base state (default: HEAD).
531    pub from: Option<String>,
532
533    /// Target state (default: worktree).
534    pub to: Option<String>,
535
536    /// Show semantic changes.
537    #[arg(long)]
538    pub semantic: bool,
539
540    /// Show diffstat summary only.
541    #[arg(long)]
542    pub stat: bool,
543
544    /// Show only changed file names.
545    #[arg(long)]
546    pub name_only: bool,
547
548    /// Number of surrounding context lines to include in each hunk.
549    #[arg(short = 'U', long = "unified", default_value_t = 3)]
550    pub unified: usize,
551
552    /// Show concise applicable context alongside diff output.
553    #[arg(long)]
554    pub context: bool,
555
556    /// Output a Git-compatible unified diff.
557    #[arg(short = 'p', long = "patch")]
558    pub patch: bool,
559}
560
561/// Arguments for the `revert` command.
562#[derive(Clone, Debug, clap::Args)]
563pub struct RevertArgs {
564    /// State to revert.
565    pub state: String,
566
567    /// Commit message for the revert.
568    #[arg(short = 'm', long)]
569    pub message: Option<String>,
570
571    /// Apply changes to worktree without committing.
572    #[arg(long)]
573    pub no_commit: bool,
574}
575
576/// Arguments for the `undo` command.
577#[derive(Clone, Debug, clap::Args)]
578#[command(after_help = "\
579Examples:
580  heddle undo                # roll back the most recent operation
581  heddle undo -n 3           # roll back the last three operations
582  heddle undo --recover      # restore the state preserved by the last undo
583  heddle undo --list         # preview undoable operations on this thread
584  heddle undo --dry-run      # show what would change without applying
585
586Undoable operations:
587  - heddle capture           (restores HEAD to the pre-capture parent)
588  - heddle land (non-FF)     (restores HEAD + both thread refs)
589  - heddle land (FF)         (restores HEAD + the landed-into thread ref to
590                              the pre-merge tip; the merged-in thread is
591                              untouched.)
592  - heddle thread switch     (restores HEAD to the previous thread state)
593  - heddle thread create/drop/rename
594  - heddle thread marker create/drop
595  - heddle redact apply               (with --allow-redact-undo; removes the
596                                       redaction record so future materializes
597                                       restore the original blob bytes. Refused
598                                       when a Purge has destroyed the bytes.)
599  - heddle undo --redo                re-apply the most recently undone operation
600
601Not undoable (file a follow-up if you need one):
602  - heddle push / pull                (remote-affecting; out of scope)
603  - heddle redact purge apply         (destructive by design; irreversible)
604  - heddle start <name> --path <dir>  (refused while the materialized worktree
605                                       still exists — run `heddle thread drop
606                                       <name> --delete-thread` first, then
607                                       re-run `heddle undo`)
608  - cross-worktree shared-backend undo (no worktree registry yet; single-
609                                        worktree usage is the supported
610                                        configuration for 0.3)
611")]
612pub struct UndoArgs {
613    /// Undo N operations.
614    #[arg(short = 'n', long, default_value = "1")]
615    pub steps: usize,
616
617    /// List recent operations without undoing.
618    #[arg(long)]
619    pub list: bool,
620
621    /// Number of batches to list.
622    #[arg(long, default_value = "20")]
623    pub depth: usize,
624
625    /// Preview operations without undoing. `--dry-run` is an accepted
626    /// alias kept for muscle memory from git/other VCS tooling.
627    #[arg(long, visible_alias = "dry-run")]
628    pub preview: bool,
629
630    /// Re-apply operations that a prior `undo` rewound.
631    #[arg(long, conflicts_with = "list")]
632    pub redo: bool,
633
634    /// Restore the checkout-local state preserved by the most recent undo as
635    /// worktree changes. HEAD and the current thread remain unchanged.
636    #[arg(
637        long,
638        conflicts_with_all = ["steps", "list", "preview", "redo", "allow_redact_undo"]
639    )]
640    pub recover: bool,
641
642    /// Explicit opt-in for undoing a `heddle redact apply`. The inverse
643    /// removes the redaction record so subsequent materializes restore
644    /// the original blob bytes — i.e. previously-hidden content
645    /// becomes readable again. Without this flag, a `heddle undo`
646    /// chain that crosses a Redact refuses loudly rather than silently
647    /// re-exposing the content. Refused regardless of the flag when
648    /// a Purge has destroyed the bytes: Purge is irreversible.
649    #[arg(long)]
650    pub allow_redact_undo: bool,
651}
652
653/// User-facing `--workspace` flag values. Vocabulary is the same as
654/// [`repo::ThreadMode`] (and the on-wire
655/// `thread.mode` JSON field) so a single name carries through the
656/// CLI, the daemon, and the thread record on disk. See
657/// `docs/design/clonefile-threads.md` for the rationale.
658#[derive(Clone, Copy, Debug, clap::ValueEnum, PartialEq, Eq)]
659pub enum WorkspaceModeArg {
660    /// Let Heddle choose the right checkout mode.
661    Auto,
662    /// Create a disk checkout with shared extents when the filesystem supports it.
663    Materialized,
664    /// Use a virtual filesystem checkout when the mount feature is available.
665    Virtualized,
666    /// Copy full files into an isolated checkout.
667    Solid,
668}
669
670/// Arguments for the `thread start` and top-level `start` commands.
671#[derive(Clone, Debug, clap::Args)]
672#[command(after_help = "\
673Examples:
674  heddle start feature/auth --path ../feature-auth  # create an isolated checkout
675  heddle start scratch --path ../scratch            # place the checkout explicitly
676  heddle start fix-flake --task 'fix CI flake'      # attach a task description
677
678Isolated checkouts are Heddle-managed working directories. They do not contain a .git directory; use Heddle commands inside them, and run Git-authority operations through Heddle from the parent Git-overlay repository.
679
680`heddle start <name> --path <dir>` is the one-step form of the advanced split flow: `heddle thread create <name>` creates the ref now, and `heddle thread promote <name> --path <dir>` materializes it later. Use the split form only when you intentionally need ref-first, checkout-later staging.
681
682Advanced (hidden) flags:
683  --agent-provider/--agent-model (agent attribution for the registered thread), --parent-thread (delegated child work), --print-cd-path (print only the checkout path for shell wrappers), --daemon/--no-daemon (virtualized-mount ownership), --shared-target/--no-shared-target (workspace-shared cargo target dir; default on for Rust solid/materialized). All are accepted here; they stay out of the flag list to keep everyday help terse.
684")]
685pub struct ThreadStartArgs {
686    /// Thread name to create or resume.
687    pub name: String,
688
689    /// Base state for the thread (default: HEAD).
690    #[arg(long)]
691    pub from: Option<String>,
692
693    /// Filesystem path for the isolated checkout.
694    #[arg(long)]
695    pub path: Option<std::path::PathBuf>,
696
697    /// Workspace mode for the thread.
698    #[arg(long, value_enum, default_value_t = WorkspaceModeArg::Auto)]
699    pub workspace: WorkspaceModeArg,
700
701    /// AI provider name for the registered agent thread.
702    #[arg(long, hide = true)]
703    pub agent_provider: Option<String>,
704
705    /// AI model name for the registered agent thread.
706    #[arg(long, hide = true)]
707    pub agent_model: Option<String>,
708
709    /// First-class task/goal metadata for the thread.
710    #[arg(long)]
711    pub task: Option<String>,
712
713    /// Parent thread identifier for delegated child work.
714    #[arg(long, hide = true)]
715    pub parent_thread: Option<String>,
716
717    /// Internal hint that this thread was started by automation rather than a direct CLI flow.
718    #[arg(long, hide = true)]
719    pub automated: bool,
720
721    /// Print only the new thread's absolute checkout path to stdout and exit.
722    ///
723    /// Designed for shell wrappers that want to cd into the new checkout:
724    ///   dir=$(heddle start foo --print-cd-path) && cd "$dir"
725    /// Skips all other output (no JSON, no styling, no extra lines) so the
726    /// stdout is a clean path. Mutually exclusive with `--watch`-style flows.
727    #[arg(long, hide = true, conflicts_with_all = ["agent_provider", "agent_model"])]
728    pub print_cd_path: bool,
729
730    /// For `--workspace virtualized`: hand the filesystem mount off to the
731    /// long-lived `heddled` daemon (default). The daemon owns the
732    /// mount across CLI invocations, so the mount survives `heddle
733    /// thread start` exiting. Linux-only; no-op for heavy
734    /// workspaces. Pass `--no-daemon` to keep the mount in-process
735    /// instead.
736    #[arg(
737        long,
738        overrides_with = "no_daemon",
739        action = clap::ArgAction::SetTrue,
740        default_value_t = true,
741        hide = true,
742    )]
743    pub daemon: bool,
744
745    /// For `--workspace virtualized`: keep the filesystem mount in this CLI
746    /// process instead of handing it to the `heddled` daemon. The
747    /// mount unmounts when this `heddle thread start` exits — useful
748    /// for one-shot inspections, debugging the in-process mount path,
749    /// or environments where the daemon can't run.
750    #[arg(
751        long,
752        overrides_with = "daemon",
753        action = clap::ArgAction::SetTrue,
754        hide = true,
755    )]
756    pub no_daemon: bool,
757
758    /// Allow this invocation to open System Settings and wait briefly for
759    /// FSKit approval. Requires an interactive terminal; otherwise setup
760    /// fails before opening a GUI.
761    #[arg(long)]
762    pub interactive_setup: bool,
763
764    /// Redirect cargo's `target/` directory to a workspace-wide shared
765    /// path (`.heddle/targets/<workspace-fingerprint>/`) instead of
766    /// letting cargo create a per-thread `target/`. Saves multiples of
767    /// gigabytes when several materialized threads coexist in a Rust
768    /// workspace. Implemented by writing `.cargo/config.toml` inside
769    /// the new thread checkout — transparent to any `cargo` invocation
770    /// in that directory.
771    ///
772    /// Default: on for solid/materialized threads when the repository
773    /// root has a `Cargo.toml`. Pass `--no-shared-target` to opt out.
774    /// Explicit `--shared-target` forces the attempt on (still a no-op
775    /// without a top-level `Cargo.toml`). Has no effect on virtualized
776    /// (mounted) threads.
777    #[arg(
778        long,
779        overrides_with = "no_shared_target",
780        action = clap::ArgAction::SetTrue,
781        hide = true,
782    )]
783    pub shared_target: bool,
784
785    /// Opt out of the default shared cargo `target/` redirect for
786    /// solid/materialized threads in Rust workspaces. See
787    /// `--shared-target`.
788    #[arg(
789        long,
790        overrides_with = "shared_target",
791        action = clap::ArgAction::SetTrue,
792        hide = true,
793    )]
794    pub no_shared_target: bool,
795
796    /// Symlink the origin checkout's top-level ignored dependency
797    /// directories (`node_modules`, `.venv`, `target`, …) into this
798    /// isolated checkout so it's immediately buildable — run
799    /// `tsc`/`eslint`/tests without reinstalling deps from scratch.
800    ///
801    /// The links point back at the origin's directories and stay
802    /// ignored, so the deps are never captured into heddle. Admin dirs
803    /// (`.git`, `.heddle`) are excluded; only top-level ignored
804    /// directories are linked. Has no effect on virtualized (mounted)
805    /// threads.
806    #[arg(long)]
807    pub hydrate: bool,
808}
809
810/// Arguments for the `try` command — atomic-ephemeral-thread sugar.
811///
812/// Implements item 3.1 from the heddle 6→8 plan: spin up an ephemeral
813/// thread, run `<cmd>` inside that thread's checkout, capture on
814/// success and drop on failure. The parent's working tree is never
815/// touched, regardless of whether the command succeeds or fails — the
816/// ephemeral thread is a sandbox.
817#[derive(Clone, Debug, clap::Args)]
818pub struct TryArgs {
819    /// Optional thread name. When omitted, defaults to
820    /// `try-<short-hash>` derived from the command and a timestamp.
821    #[arg(long)]
822    pub name: Option<String>,
823
824    /// Workspace mode for the ephemeral thread. Defaults to `materialized`
825    /// (a real isolated checkout) so `<cmd>` runs against a proper
826    /// filesystem. Pass `auto`, `virtualized`, or `solid` to use a different
827    /// workspace strategy.
828    #[arg(long, value_enum, default_value_t = WorkspaceModeArg::Materialized)]
829    pub workspace: WorkspaceModeArg,
830    /// On zero exit, automatically land the resulting thread into
831    /// the current thread. Default: off.
832    #[arg(long = "auto-merge")]
833    pub auto_merge: bool,
834
835    /// Keep the ephemeral thread on success even if `--auto-merge`
836    /// would otherwise drop it after merging. Has no effect on the
837    /// failure path (failed attempts are always dropped).
838    #[arg(long = "keep-on-success")]
839    pub keep_on_success: bool,
840
841    /// The command to run. Everything after `--` lands here. The
842    /// first token is the program; the rest are its arguments.
843    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
844    pub command: Vec<String>,
845}
846
847/// Arguments for the `run` command.
848#[derive(Clone, Debug, clap::Args)]
849pub struct RunArgs {
850    /// Thread to execute within.
851    #[arg(long = "thread")]
852    pub thread: Option<String>,
853
854    /// Command to run inside the thread execution root.
855    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
856    pub command: Vec<String>,
857}
858
859/// Arguments for the `ready` command.
860#[derive(Clone, Debug, clap::Args)]
861pub struct ReadyArgs {
862    /// Thread to evaluate for integration readiness.
863    #[arg(long = "thread")]
864    pub thread: Option<String>,
865
866    /// Intent/message to use if `ready` needs to capture outstanding work first.
867    #[arg(short = 'm', long)]
868    pub message: Option<String>,
869
870    /// Honest confidence estimate (0.0-1.0) if `ready` captures outstanding work.
871    #[arg(long, value_parser = parse_confidence)]
872    pub confidence: Option<f32>,
873
874    /// Preview the readiness decision (integration target, conflicts, verify
875    /// verdicts, would-be thread transition) without capturing work or moving
876    /// the thread to Ready/Blocked. No mutation occurs.
877    #[arg(long)]
878    pub dry_run: bool,
879}
880
881/// Arguments for the `sync` command.
882#[derive(Clone, Debug, clap::Args)]
883pub struct SyncArgs {
884    /// Optional sync target. Omit for operator/thread sync.
885    #[cfg(feature = "git-overlay")]
886    #[command(subcommand)]
887    pub command: Option<SyncCommands>,
888
889    /// Thread to refresh (default: current thread).
890    #[arg(long = "thread")]
891    pub thread: Option<String>,
892}
893
894/// Arguments for the `land` command.
895#[derive(Clone, Debug, clap::Args)]
896pub struct LandArgs {
897    /// Thread to capture and integrate (default: current thread).
898    #[arg(long = "thread")]
899    pub thread: Option<String>,
900
901    /// Peer threads to land in order. When `--thread` is also supplied, that
902    /// thread is landed first. Comma-separated, e.g.
903    /// `--threads alpha,beta,gamma`. Each peer is refreshed and landed against
904    /// the live target tip.
905    #[arg(long = "threads", value_delimiter = ',')]
906    pub threads: Vec<String>,
907
908    /// Intent/message to use if land needs to capture outstanding work first.
909    #[arg(short = 'm', long)]
910    pub message: Option<String>,
911
912    /// Preserve per-State Git export instead of squashing the landed thread.
913    #[arg(long)]
914    pub no_squash: bool,
915
916    /// Preview the integration (thread -> target, merge relation, conflicts,
917    /// verify verdicts) without capturing work, syncing, or merging. No
918    /// mutation occurs and no server round-trip is made.
919    #[arg(long)]
920    pub dry_run: bool,
921}
922
923/// Arguments for `thread show`.
924#[derive(Clone, Debug, clap::Args)]
925pub struct ThreadShowArgs {
926    /// Thread identifier. Defaults to the current thread when omitted.
927    pub thread: Option<String>,
928
929    /// Continuously refresh thread status.
930    #[arg(long)]
931    pub watch: bool,
932
933    /// Internal helper for tests: stop after N watch updates.
934    #[arg(long, hide = true)]
935    pub watch_iterations: Option<usize>,
936
937    /// Internal helper for tests: polling interval in milliseconds.
938    #[arg(long, hide = true)]
939    pub watch_interval_ms: Option<u64>,
940}
941
942/// Arguments for `thread captures`.
943#[derive(Clone, Debug, clap::Args)]
944pub struct ThreadCapturesArgs {
945    /// Thread identifier. Defaults to the current thread when omitted.
946    pub thread: Option<String>,
947
948    /// Maximum captures to show.
949    #[arg(long, default_value_t = 20)]
950    pub limit: usize,
951}
952
953/// Arguments for commands that take a thread identifier. Omitting the
954/// positional resolves to the current thread when one can be inferred
955/// from the working checkout.
956#[derive(Clone, Debug, clap::Args)]
957pub struct ThreadNameArgs {
958    /// Thread identifier. Defaults to the current thread when omitted.
959    pub thread: Option<String>,
960}
961
962/// Arguments for `thread rename`.
963#[derive(Clone, Debug, clap::Args)]
964pub struct ThreadRenameArgs {
965    /// Existing thread identifier.
966    pub old: String,
967
968    /// New thread identifier.
969    pub new: String,
970}
971
972/// Arguments for `thread promote`.
973#[derive(Clone, Debug, clap::Args)]
974pub struct ThreadPromoteArgs {
975    /// Thread identifier.
976    pub thread: String,
977
978    /// Materialized checkout path.
979    #[arg(long)]
980    pub path: Option<std::path::PathBuf>,
981
982    /// Discard dirty work in the source checkout while promoting.
983    #[arg(long)]
984    pub force: bool,
985}
986
987/// Arguments for `thread move`.
988#[derive(Clone, Debug, clap::Args)]
989pub struct ThreadMoveArgs {
990    /// Source thread identifier.
991    pub from: String,
992
993    /// Destination thread identifier.
994    pub to: String,
995
996    /// Repository-relative path prefix to move.
997    #[arg(long = "path", required = true, value_name = "PATH")]
998    pub paths: Vec<String>,
999
1000    /// Intent/message for the snapshots created by the move.
1001    #[arg(short = 'm', long)]
1002    pub message: Option<String>,
1003}
1004
1005/// Arguments for `thread absorb`.
1006#[derive(Clone, Debug, clap::Args)]
1007pub struct ThreadAbsorbArgs {
1008    /// Child thread to absorb.
1009    pub thread: String,
1010
1011    /// Parent thread to absorb into (default: the thread's recorded parent).
1012    #[arg(long)]
1013    pub into: Option<String>,
1014
1015    /// Commit message for the absorb merge.
1016    #[arg(short = 'm', long)]
1017    pub message: Option<String>,
1018
1019    /// Show the absorb preview without applying it.
1020    #[arg(long)]
1021    pub preview: bool,
1022}
1023
1024/// Arguments for `thread resolve`.
1025#[derive(Clone, Debug, clap::Args)]
1026pub struct ThreadResolveArgs {
1027    /// Thread identifier.
1028    pub thread: String,
1029}
1030
1031/// Arguments for `thread drop`.
1032#[derive(Clone, Debug, clap::Args)]
1033pub struct ThreadDropArgs {
1034    /// Thread identifier.
1035    pub thread: String,
1036
1037    /// Also delete the attached thread ref.
1038    #[arg(long)]
1039    pub delete_thread: bool,
1040
1041    /// Discard uncommitted changes in the thread checkout before dropping it.
1042    #[arg(short, long)]
1043    pub force: bool,
1044}
1045
1046/// Arguments for `thread approve` — record an approval for a
1047/// `<source> -> <target>` merge against the source thread's
1048/// current state.
1049#[derive(Clone, Debug, clap::Args)]
1050pub struct ThreadApproveArgs {
1051    /// Source thread identifier (the change set being merged).
1052    pub source: String,
1053
1054    /// Target thread identifier (where the merge would land).
1055    pub target: String,
1056
1057    /// Optional human note attached to the approval.
1058    #[arg(long)]
1059    pub note: Option<String>,
1060
1061    /// Hosted remote name (default: `origin`).
1062    #[arg(long, default_value = "origin")]
1063    pub remote: String,
1064}
1065
1066/// Arguments for `thread approvals` — list every approval recorded
1067/// for `<source> -> <target>`.
1068#[derive(Clone, Debug, clap::Args)]
1069pub struct ThreadApprovalsArgs {
1070    pub source: String,
1071    pub target: String,
1072    #[arg(long, default_value = "origin")]
1073    pub remote: String,
1074}
1075
1076/// Arguments for `thread revoke-approval` — remove a recorded
1077/// approval by id.
1078#[derive(Clone, Debug, clap::Args)]
1079pub struct ThreadRevokeApprovalArgs {
1080    /// UUID of the approval row to revoke.
1081    pub id: String,
1082    #[arg(long, default_value = "origin")]
1083    pub remote: String,
1084}
1085
1086/// Arguments for `thread check-merge` — query the merge gate
1087/// without recording anything. Returns the unmet requirements.
1088#[derive(Clone, Debug, clap::Args)]
1089pub struct ThreadCheckMergeArgs {
1090    pub source: String,
1091    pub target: String,
1092
1093    /// 'merge' (default), 'force_push', or 'complete'.
1094    #[arg(long, default_value = "merge")]
1095    pub gated_action: String,
1096
1097    /// File paths the diff touches, repeat or comma-separate. Empty =
1098    /// "we don't know" (every path-conditional policy fires).
1099    #[arg(long = "path", value_delimiter = ',')]
1100    pub changed_paths: Vec<String>,
1101
1102    #[arg(long, default_value = "origin")]
1103    pub remote: String,
1104}
1105
1106/// Arguments for the `collapse` command.
1107#[derive(Clone, Debug, clap::Args)]
1108pub struct CollapseArgs {
1109    /// States to collapse.
1110    #[arg(required = true)]
1111    pub states: Vec<String>,
1112
1113    /// Intent/name for the resulting state.
1114    #[arg(long)]
1115    pub into: String,
1116
1117    /// Confidence for the resulting state (0.0-1.0).
1118    #[arg(long)]
1119    pub confidence: Option<f32>,
1120}
1121
1122/// Arguments for the `expand` command.
1123#[derive(Clone, Debug, clap::Args)]
1124pub struct ExpandArgs {
1125    /// Git OID, state spec, or thread name for the squashed land.
1126    pub reference: String,
1127}
1128
1129/// Arguments for the `resolve` command.
1130#[derive(Clone, Debug, clap::Args)]
1131pub struct ResolveArgs {
1132    /// File to resolve.
1133    pub path: Option<String>,
1134
1135    /// Resolve all conflicts.
1136    #[arg(long)]
1137    pub all: bool,
1138
1139    /// List unresolved conflicts.
1140    #[arg(long)]
1141    pub list: bool,
1142
1143    /// Use our version (current thread).
1144    #[arg(long, conflicts_with = "theirs")]
1145    pub ours: bool,
1146
1147    /// Use their version (merged thread).
1148    #[arg(long, conflicts_with = "ours")]
1149    pub theirs: bool,
1150
1151    /// Mark the path resolved even if conflict markers are still present.
1152    #[arg(long)]
1153    pub force: bool,
1154
1155    /// Abort the merge.
1156    #[arg(long)]
1157    pub abort: bool,
1158}
1159
1160/// The `(remote, thread)` pair shared by remote commands that use an
1161/// option-only thread selector.
1162#[derive(Clone, Debug, clap::Args)]
1163pub struct RemoteOperationArgs {
1164    /// Heddle remote name, native repository path, or hosted address.
1165    pub remote: Option<String>,
1166
1167    /// Thread to act on.
1168    #[arg(short, long)]
1169    pub thread: Option<String>,
1170
1171    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1172    /// Prefer enabling TLS; use this only for intentional lab/VPN testing.
1173    #[arg(long)]
1174    pub insecure: bool,
1175}
1176
1177/// Arguments for the `push` command.
1178#[derive(Clone, Debug, clap::Args)]
1179#[command(after_help = "\
1180Git Overlay refs:
1181  A normal push writes refs/heads/<thread> and refs/notes/heddle.
1182  --all-threads writes every refs/heads/<thread> and refs/tags/<tag>, plus refs/notes/heddle.
1183  JSON output lists changed refs in refs_written; verify with git ls-remote <remote>.
1184")]
1185pub struct PushArgs {
1186    /// Heddle remote name, native repository path, or hosted address.
1187    pub remote: Option<String>,
1188
1189    /// Thread to push.
1190    #[arg(short, long, conflicts_with = "thread_arg")]
1191    pub thread: Option<String>,
1192
1193    /// Thread to push; alias for `--thread`.
1194    #[arg(value_name = "THREAD")]
1195    pub thread_arg: Option<String>,
1196
1197    /// State to push (default: HEAD).
1198    #[arg(short, long)]
1199    pub state: Option<String>,
1200
1201    /// Force push.
1202    #[arg(short, long)]
1203    pub force: bool,
1204
1205    /// Push every thread. In Git Overlay, also include every local Git tag.
1206    #[arg(long)]
1207    pub all_threads: bool,
1208
1209    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1210    /// Prefer enabling TLS; use this only for intentional lab/VPN testing.
1211    #[arg(long)]
1212    pub insecure: bool,
1213
1214    /// Preview the push plan (target, thread/track ref, state that would be
1215    /// published, force status) without pushing, moving refs, capturing work,
1216    /// running hooks, or contacting the server for anything beyond read/plan.
1217    #[arg(long)]
1218    pub dry_run: bool,
1219}
1220
1221impl PushArgs {
1222    pub fn thread_name(&self) -> Option<String> {
1223        self.thread.clone().or_else(|| self.thread_arg.clone())
1224    }
1225}
1226
1227/// Arguments for the `pull` command.
1228#[derive(Clone, Debug, clap::Args)]
1229#[command(after_help = "\
1230Advanced (hidden) flags:
1231  --lazy leaves blob content absent by design and hydrates it explicitly later. Hosted/network Heddle remotes only.
1232")]
1233pub struct PullArgs {
1234    #[command(flatten)]
1235    pub remote_op: RemoteOperationArgs,
1236
1237    /// Local thread to update.
1238    #[arg(short, long)]
1239    pub local_thread: Option<String>,
1240
1241    /// Leave blob content absent by design and hydrate it explicitly later.
1242    #[arg(long, hide = true)]
1243    pub lazy: bool,
1244}
1245
1246/// Arguments for the `clone` command.
1247///
1248/// Help style budget (heddle#652): `--help` carries the signature, flags,
1249/// a one-screen Behavior summary, and the hidden-flag breadcrumb
1250/// (heddle#646). The full default-thread fallback chain and --depth
1251/// exposition moved to `heddle help clone` (help.rs CLONE_TOPIC); keep
1252/// flag docs single-line so clap renders the compact help layout.
1253#[derive(Clone, Debug, clap::Args)]
1254#[command(after_help = "\
1255Behavior:
1256  Clones native Heddle or Git repositories and checks out the selected default branch. Git transport runs through Sley and does not require a Git executable. Never prompts. Full details: `heddle help clone`.
1257
1258Advanced/planned flags: see `heddle help clone`.
1259
1260Examples:
1261  heddle clone ../native-repo ./clone                # local native Heddle repository
1262  heddle clone heddle://host/repo ./clone --depth 1   # shallow Heddle clone: tip plus immediate parents
1263")]
1264pub struct CloneArgs {
1265    /// Remote repository path.
1266    pub remote: String,
1267
1268    /// Local directory to clone into.
1269    pub local: String,
1270
1271    /// Thread to check out after cloning.
1272    #[arg(long)]
1273    pub thread: Option<String>,
1274
1275    /// Create a shallow clone with the specified depth. `0` means full history.
1276    #[arg(long)]
1277    pub depth: Option<u32>,
1278
1279    // Hosted/network remotes only. The user-facing exposition lives in the
1280    // after-help breadcrumb above and `heddle help clone`.
1281    /// Leave blob content absent by design and hydrate it explicitly later.
1282    #[arg(long, hide = true)]
1283    pub lazy: bool,
1284
1285    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1286    #[arg(long)]
1287    pub insecure: bool,
1288
1289    // Only `blob:none` is accepted (a synonym for --lazy on hosted
1290    // remotes); git-style filters such as `tree:0` or `blob:limit=…` are
1291    // rejected at parse time. See the after-help breadcrumb and `heddle help
1292    // clone`.
1293    /// Partial-clone filter spec (`blob:none` only).
1294    #[arg(long, hide = true, value_name = "SPEC", value_parser = parse_clone_filter_spec)]
1295    pub filter: Option<String>,
1296
1297    /// Clone a whole hosted monorepo: resolve the root spool's child tree and
1298    /// clone every child spool at its anchored state into its mount path.
1299    /// Hosted/network remotes only. (Alias: --monorepo.)
1300    #[arg(long, visible_alias = "monorepo")]
1301    pub recursive: bool,
1302}
1303
1304fn parse_clone_filter_spec(s: &str) -> Result<String, String> {
1305    match s {
1306        "blob:none" => Ok(s.to_string()),
1307        other => Err(format!(
1308            "unsupported --filter spec `{other}`; only `blob:none` is supported today"
1309        )),
1310    }
1311}
1312
1313/// Arguments for `agent provenance begin`.
1314#[derive(Clone, Debug, clap::Args)]
1315pub struct AgentProvenanceBeginArgs {
1316    /// Provider name (e.g., "anthropic", "openai").
1317    #[arg(long)]
1318    pub provider: String,
1319
1320    /// Model identifier (e.g., "claude-opus-4").
1321    #[arg(long)]
1322    pub model: String,
1323
1324    /// Policy or prompt template ID.
1325    #[arg(long)]
1326    pub policy: Option<String>,
1327}
1328
1329/// Arguments for `agent provenance segment`.
1330#[derive(Clone, Debug, clap::Args)]
1331pub struct AgentProvenanceSegmentArgs {
1332    /// Provider name (e.g., "anthropic", "openai").
1333    #[arg(long)]
1334    pub provider: String,
1335
1336    /// Model identifier (e.g., "claude-opus-4").
1337    #[arg(long)]
1338    pub model: String,
1339
1340    /// Policy or prompt template ID.
1341    #[arg(long)]
1342    pub policy: Option<String>,
1343}
1344
1345/// Arguments for `agent provenance end`.
1346#[derive(Clone, Debug, clap::Args)]
1347pub struct AgentProvenanceEndArgs {
1348    /// Session ID to end (default: current session).
1349    pub session_id: Option<String>,
1350}
1351
1352/// Arguments for `agent provenance show`.
1353#[derive(Clone, Debug, clap::Args)]
1354pub struct AgentProvenanceShowArgs {
1355    /// Session ID to show (default: current session).
1356    pub session_id: Option<String>,
1357}
1358
1359/// Arguments for `agent provenance list`.
1360#[derive(Clone, Debug, clap::Args)]
1361pub struct AgentProvenanceListArgs {
1362    /// Show only active sessions.
1363    #[arg(long)]
1364    pub active: bool,
1365}
1366
1367/// Arguments for the `worktree add` command.
1368#[derive(Clone, Debug, clap::Args)]
1369pub struct WorktreeAddArgs {
1370    /// Path to the new agent checkout directory.
1371    pub path: std::path::PathBuf,
1372
1373    /// Thread name for the agent (created if absent, default: HEAD thread).
1374    #[arg(long)]
1375    pub thread: Option<String>,
1376
1377    /// Base state to materialize (default: HEAD).
1378    #[arg(long)]
1379    pub from: Option<String>,
1380}
1381
1382/// Arguments for the `worktree remove` command.
1383#[derive(Clone, Debug, clap::Args)]
1384pub struct WorktreeRemoveArgs {
1385    /// Path to the isolated checkout directory to remove.
1386    pub path: std::path::PathBuf,
1387
1388    /// Also delete the associated thread ref, if this checkout is attached.
1389    #[arg(long)]
1390    pub delete_thread: bool,
1391}
1392
1393/// Arguments for `agent presence list`.
1394#[derive(Clone, Debug, clap::Args)]
1395pub struct AgentPresenceListArgs {
1396    /// Show only active actors.
1397    #[arg(long)]
1398    pub active: bool,
1399}
1400
1401/// Arguments for `agent presence show`.
1402#[derive(Clone, Debug, clap::Args)]
1403pub struct AgentPresenceShowArgs {
1404    /// Session ID to show (default: current thread actor).
1405    pub session: Option<String>,
1406}
1407
1408/// Arguments for `agent presence explain`.
1409#[derive(Clone, Debug, clap::Args)]
1410pub struct AgentPresenceExplainArgs {
1411    /// Session ID to explain (default: current thread actor).
1412    pub session: Option<String>,
1413}
1414
1415/// Arguments for `agent presence complete`.
1416#[derive(Clone, Debug, clap::Args)]
1417pub struct AgentPresenceCompleteArgs {
1418    /// Session ID to mark as complete (default: current thread actor).
1419    #[arg(long)]
1420    pub session: Option<String>,
1421}
1422
1423/// Arguments for `agent reserve`.
1424#[derive(Clone, Debug, clap::Args)]
1425pub struct AgentReserveArgs {
1426    /// Thread to reserve.
1427    #[arg(long)]
1428    pub thread: String,
1429
1430    /// Anchor state spec (default: current HEAD).
1431    #[arg(long)]
1432    pub anchor: Option<String>,
1433
1434    /// Optional task description.
1435    #[arg(long)]
1436    pub task: Option<String>,
1437
1438    /// Local agent task assignment id to attach to this reservation.
1439    #[arg(long)]
1440    pub task_id: Option<String>,
1441
1442    /// Reap the lease early when this long-lived owner process exits.
1443    #[arg(long, value_name = "PID")]
1444    pub hold_for_pid: Option<u32>,
1445}
1446
1447/// Arguments for `agent heartbeat`.
1448#[derive(Clone, Debug, clap::Args)]
1449pub struct AgentHeartbeatArgs {
1450    /// Writer lease id returned by `agent reserve`.
1451    #[arg(long)]
1452    pub lease: String,
1453
1454    /// Bearer token returned by `agent reserve`.
1455    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1456    pub token: String,
1457}
1458
1459/// Arguments for `agent release`.
1460#[derive(Clone, Debug, clap::Args)]
1461pub struct AgentReleaseArgs {
1462    /// Writer lease id returned by `agent reserve`.
1463    #[arg(long)]
1464    pub lease: String,
1465
1466    /// Bearer token returned by `agent reserve`.
1467    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1468    pub token: String,
1469
1470    /// Terminal status to record.
1471    #[arg(long, default_value = "complete")]
1472    pub status: AgentReleaseStatusArg,
1473}
1474
1475#[derive(Clone, Debug, clap::ValueEnum)]
1476pub enum AgentReleaseStatusArg {
1477    Complete,
1478    Abandoned,
1479}
1480
1481/// Arguments for `agent list`.
1482#[derive(Clone, Debug, clap::Args)]
1483pub struct AgentApiListArgs {
1484    /// Filter by thread.
1485    #[arg(long)]
1486    pub thread: Option<String>,
1487
1488    /// Show only active reservations.
1489    #[arg(long)]
1490    pub alive_only: bool,
1491}
1492
1493#[derive(Clone, Debug, clap::ValueEnum)]
1494pub enum AgentTaskStatusArg {
1495    Open,
1496    InProgress,
1497    Blocked,
1498    Complete,
1499    Abandoned,
1500}
1501
1502/// Arguments for `agent task create`.
1503#[derive(Clone, Debug, clap::Args)]
1504pub struct AgentTaskCreateArgs {
1505    /// Optional caller-provided task id (default: generated task UUIDv7 id).
1506    #[arg(long)]
1507    pub task_id: Option<String>,
1508
1509    /// Human-readable task title.
1510    #[arg(long)]
1511    pub title: String,
1512
1513    /// Detailed task body.
1514    #[arg(long)]
1515    pub body: Option<String>,
1516
1517    /// Thread this task targets.
1518    #[arg(long)]
1519    pub thread: String,
1520
1521    /// Optional base state id this task was delegated from.
1522    #[arg(long)]
1523    pub base_state: Option<String>,
1524
1525    /// Optional base root id this task was delegated from.
1526    #[arg(long)]
1527    pub base_root: Option<String>,
1528
1529    /// Optional parent task id.
1530    #[arg(long)]
1531    pub parent_task_id: Option<String>,
1532
1533    /// Optional coordination discussion id.
1534    #[arg(long)]
1535    pub coordination_discussion_id: Option<String>,
1536
1537    /// Allow this task to continue without hosted connectivity.
1538    #[arg(long)]
1539    pub allow_offline: bool,
1540
1541    /// Principal or agent that delegated this task.
1542    #[arg(long)]
1543    pub delegated_by: Option<String>,
1544}
1545
1546/// Arguments for `agent task list`.
1547#[derive(Clone, Debug, clap::Args)]
1548pub struct AgentTaskListArgs {
1549    /// Filter by target thread.
1550    #[arg(long)]
1551    pub thread: Option<String>,
1552
1553    /// Filter by task status.
1554    #[arg(long)]
1555    pub status: Option<AgentTaskStatusArg>,
1556}
1557
1558/// Arguments for `agent task show`.
1559#[derive(Clone, Debug, clap::Args)]
1560pub struct AgentTaskShowArgs {
1561    /// Task id to show.
1562    pub task_id: String,
1563}
1564
1565/// Arguments for `agent task update`.
1566#[derive(Clone, Debug, clap::Args)]
1567pub struct AgentTaskUpdateArgs {
1568    /// Task id to update.
1569    pub task_id: String,
1570
1571    /// Replace the task title.
1572    #[arg(long)]
1573    pub title: Option<String>,
1574
1575    /// Replace the task body.
1576    #[arg(long)]
1577    pub body: Option<String>,
1578
1579    /// Replace the task status.
1580    #[arg(long)]
1581    pub status: Option<AgentTaskStatusArg>,
1582
1583    /// Replace the target thread.
1584    #[arg(long)]
1585    pub thread: Option<String>,
1586
1587    /// Replace the base state id.
1588    #[arg(long)]
1589    pub base_state: Option<String>,
1590
1591    /// Replace the base root id.
1592    #[arg(long)]
1593    pub base_root: Option<String>,
1594
1595    /// Replace the parent task id.
1596    #[arg(long)]
1597    pub parent_task_id: Option<String>,
1598
1599    /// Replace the coordination discussion id.
1600    #[arg(long)]
1601    pub coordination_discussion_id: Option<String>,
1602
1603    /// Allow this task to continue without hosted connectivity.
1604    #[arg(long, conflicts_with = "no_allow_offline")]
1605    pub allow_offline: bool,
1606
1607    /// Disallow offline continuation for this task.
1608    #[arg(long, conflicts_with = "allow_offline")]
1609    pub no_allow_offline: bool,
1610
1611    /// Replace the delegating principal or agent label.
1612    #[arg(long)]
1613    pub delegated_by: Option<String>,
1614}
1615
1616/// Arguments shared by `agent fanout plan` and `agent fanout start`.
1617#[derive(Clone, Debug, clap::Args)]
1618pub struct AgentFanoutPlanArgs {
1619    /// Parent coordination task title.
1620    #[arg(long)]
1621    pub title: String,
1622
1623    /// Lane spec: `<thread>=<path>:<title>`. Repeat once per child lane.
1624    #[arg(long, value_name = "THREAD=PATH:TITLE")]
1625    pub lane: Vec<String>,
1626
1627    /// Optional collaboration discussion id to store on task assignments.
1628    #[arg(long)]
1629    pub coordination_discussion_id: Option<String>,
1630}
1631
1632/// Arguments for `agent fanout start`.
1633#[derive(Clone, Debug, clap::Args)]
1634pub struct AgentFanoutStartArgs {
1635    /// Parent coordination task title.
1636    #[arg(long)]
1637    pub title: String,
1638
1639    /// Lane spec: `<thread>=<path>:<title>`. Repeat once per child lane.
1640    #[arg(long, value_name = "THREAD=PATH:TITLE")]
1641    pub lane: Vec<String>,
1642
1643    /// Optional collaboration discussion id to store on task assignments.
1644    #[arg(long)]
1645    pub coordination_discussion_id: Option<String>,
1646}
1647
1648/// Arguments for `agent capture` under a current reservation lease.
1649#[derive(Clone, Debug, clap::Args)]
1650pub struct AgentCaptureArgs {
1651    /// Writer lease id returned by `agent reserve`.
1652    #[arg(long)]
1653    pub lease: String,
1654
1655    /// Bearer token returned by `agent reserve`.
1656    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1657    pub token: String,
1658
1659    /// Capture intent / commit message.
1660    #[arg(long, short = 'm', alias = "intent")]
1661    pub message: Option<String>,
1662
1663    /// Honest confidence estimate (0.0–1.0).
1664    #[arg(long, value_parser = parse_confidence)]
1665    pub confidence: Option<f32>,
1666}
1667
1668/// Arguments for `agent ready` under a writer lease.
1669#[derive(Clone, Debug, clap::Args)]
1670pub struct AgentReadyArgs {
1671    /// Writer lease id returned by `agent reserve`.
1672    #[arg(long)]
1673    pub lease: String,
1674
1675    /// Bearer token returned by `agent reserve`.
1676    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1677    pub token: String,
1678
1679    /// Optional summary message.
1680    #[arg(long, short = 'm')]
1681    pub message: Option<String>,
1682
1683    /// Honest confidence estimate (0.0-1.0) if `agent ready` captures outstanding work.
1684    #[arg(long, value_parser = parse_confidence)]
1685    pub confidence: Option<f32>,
1686}
1687
1688/// Arguments for the `watch` command.
1689///
1690/// Streams live oplog activity (snapshots, merges, thread create/update,
1691/// markers, etc.) as it happens. Default behavior tails forever and exits
1692/// on Ctrl-C. `--since 5m` replays the last N before tailing live;
1693/// `--filter` restricts output to the named kinds; `--output json` emits one
1694/// JSON object per line for piping to `jq`.
1695#[derive(Clone, Debug, clap::Args)]
1696pub struct WatchArgs {
1697    /// Replay events from this duration ago (e.g. `30s`, `5m`, `1h`,
1698    /// `2d`) before tailing live. When unset, only new events are
1699    /// emitted.
1700    #[arg(long, value_name = "DURATION")]
1701    pub since: Option<String>,
1702
1703    /// Comma-separated event kinds to include
1704    /// (`snapshot,merge,thread_create,thread_update,thread_delete,
1705    /// collapse,thread_marker_create,thread_marker_delete`).
1706    #[arg(long, value_name = "KINDS")]
1707    pub filter: Option<String>,
1708
1709    /// Internal helper for tests: stop after the oplog file produces
1710    /// this many modify events (still drains pending entries first).
1711    #[arg(long, hide = true)]
1712    pub max_iterations: Option<usize>,
1713
1714    /// Internal helper for tests: poll interval in milliseconds for
1715    /// the `notify` watcher's debounce check (default 200ms).
1716    #[arg(long, hide = true)]
1717    pub poll_interval_ms: Option<u64>,
1718}
1719
1720// `AgentCaptureArgs` and `AgentReadyArgs` defined earlier in this
1721// file. A second copy was left here by the rebase (the workstreams
1722// commit added them twice when the cherry-pick had lost the
1723// originals and we re-added them mid-rebase). Removed.
1724
1725#[cfg(test)]
1726mod capture_message_alias_tests {
1727    use clap::Parser;
1728
1729    use crate::cli::{Cli, Commands, SnapshotArgs};
1730
1731    fn parse_capture(extra: &[&str]) -> Result<SnapshotArgs, clap::Error> {
1732        let mut argv: Vec<&str> = vec!["heddle", "capture"];
1733        argv.extend_from_slice(extra);
1734        let cli = Cli::try_parse_from(argv)?;
1735        match cli.command {
1736            Commands::Capture(args) => Ok(args),
1737            _ => panic!("expected Commands::Capture"),
1738        }
1739    }
1740
1741    #[test]
1742    fn capture_accepts_message_alias() {
1743        let args = parse_capture(&["--message", "my change"]).expect("--message should parse");
1744        assert_eq!(args.intent.as_deref(), Some("my change"));
1745    }
1746
1747    #[test]
1748    fn capture_accepts_intent_long_form() {
1749        let args = parse_capture(&["--intent", "my change"]).expect("--intent should parse");
1750        assert_eq!(args.intent.as_deref(), Some("my change"));
1751    }
1752
1753    #[test]
1754    fn capture_accepts_short_m() {
1755        let args = parse_capture(&["-m", "my change"]).expect("-m should parse");
1756        assert_eq!(args.intent.as_deref(), Some("my change"));
1757    }
1758
1759    #[test]
1760    fn capture_rejects_non_finite_or_out_of_range_confidence() {
1761        for value in ["NaN", "inf", "-0.1", "1.7"] {
1762            let confidence_arg = format!("--confidence={value}");
1763            let err = parse_capture(&["-m", "bad confidence", &confidence_arg])
1764                .expect_err("invalid confidence should fail to parse");
1765            assert!(
1766                err.to_string()
1767                    .contains("confidence must be a finite number from 0.0 to 1.0"),
1768                "unexpected parse error for {value}: {err}"
1769            );
1770        }
1771    }
1772}
1773
1774#[cfg(test)]
1775mod clone_filter_tests {
1776    use clap::Parser;
1777
1778    use crate::cli::{Cli, CloneArgs, Commands};
1779
1780    fn parse_clone(extra: &[&str]) -> Result<CloneArgs, clap::Error> {
1781        let mut argv: Vec<&str> = vec!["heddle", "clone", "remote", "local"];
1782        argv.extend_from_slice(extra);
1783        let cli = Cli::try_parse_from(argv)?;
1784        match cli.command {
1785            Commands::Clone(args) => Ok(args),
1786            _ => panic!("expected Commands::Clone"),
1787        }
1788    }
1789
1790    #[test]
1791    fn parses_clone_filter_blob_none() {
1792        let args = parse_clone(&["--filter", "blob:none"]).expect("parse --filter blob:none");
1793        assert_eq!(args.filter.as_deref(), Some("blob:none"));
1794        assert!(!args.lazy);
1795    }
1796
1797    #[test]
1798    fn rejects_unknown_filter_spec() {
1799        let err = parse_clone(&["--filter", "tree:0"])
1800            .expect_err("unknown --filter spec should fail to parse");
1801        let msg = err.to_string();
1802        assert!(
1803            msg.contains("tree:0") && msg.contains("blob:none"),
1804            "error should name the bad spec and the supported one: {msg}"
1805        );
1806    }
1807}