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 --preview      # inspect the most recent operation
581  heddle undo --hard         # roll it back and rewind the worktree
582  heddle undo -n 3 --hard    # roll back the last three operations
583  heddle undo --recover      # restore the state preserved by the last undo
584  heddle undo --list         # preview undoable operations on this thread
585  heddle undo --dry-run      # show what would change without applying
586
587Undoable operations:
588  - heddle capture           (restores HEAD to the pre-capture parent)
589  - heddle land (non-FF)     (restores HEAD + both thread refs)
590  - heddle land (FF)         (restores HEAD + the landed-into thread ref to
591                              the pre-merge tip; the merged-in thread is
592                              untouched.)
593  - heddle thread switch     (restores HEAD to the previous thread state)
594  - heddle thread create/drop/rename
595  - heddle thread marker create/drop
596  - heddle redact apply               (with --allow-redact-undo; removes the
597                                       redaction record so future materializes
598                                       restore the original blob bytes. Refused
599                                       when a Purge has destroyed the bytes.)
600  - heddle undo --redo                re-apply the most recently undone operation
601
602Not undoable (file a follow-up if you need one):
603  - heddle push / pull                (remote-affecting; out of scope)
604  - heddle redact purge apply         (destructive by design; irreversible)
605  - heddle start <name> --path <dir>  (refused while the materialized worktree
606                                       still exists — run `heddle thread drop
607                                       <name> --delete-thread` first, then
608                                       re-run `heddle undo`)
609  - cross-worktree shared-backend undo (no worktree registry yet; single-
610                                        worktree usage is the supported
611                                        configuration for 0.3)
612")]
613pub struct UndoArgs {
614    /// Undo N operations.
615    #[arg(short = 'n', long, default_value = "1")]
616    pub steps: usize,
617
618    /// List recent operations without undoing.
619    #[arg(long)]
620    pub list: bool,
621
622    /// Number of batches to list.
623    #[arg(long, default_value = "20")]
624    pub depth: usize,
625
626    /// Preview operations without undoing. `--dry-run` is an accepted
627    /// alias kept for muscle memory from git/other VCS tooling.
628    #[arg(long, visible_alias = "dry-run")]
629    pub preview: bool,
630
631    /// Permit undo to rewind worktree files to the selected operation's prior
632    /// state. Without this explicit opt-in, an undo that would rewrite the
633    /// worktree refuses before changing repository state or files.
634    #[arg(long, conflicts_with_all = ["list", "preview", "redo", "recover"])]
635    pub hard: bool,
636
637    /// Re-apply operations that a prior `undo` rewound.
638    #[arg(long, conflicts_with = "list")]
639    pub redo: bool,
640
641    /// Restore the checkout-local state preserved by the most recent undo as
642    /// worktree changes. HEAD and the current thread remain unchanged.
643    #[arg(
644        long,
645        conflicts_with_all = ["steps", "list", "preview", "hard", "redo", "allow_redact_undo"]
646    )]
647    pub recover: bool,
648
649    /// Explicit opt-in for undoing a `heddle redact apply`. The inverse
650    /// removes the redaction record so subsequent materializes restore
651    /// the original blob bytes — i.e. previously-hidden content
652    /// becomes readable again. Without this flag, a `heddle undo`
653    /// chain that crosses a Redact refuses loudly rather than silently
654    /// re-exposing the content. Refused regardless of the flag when
655    /// a Purge has destroyed the bytes: Purge is irreversible.
656    #[arg(long)]
657    pub allow_redact_undo: bool,
658}
659
660/// User-facing `--workspace` flag values. Vocabulary is the same as
661/// [`repo::ThreadMode`] (and the on-wire
662/// `thread.mode` JSON field) so a single name carries through the
663/// CLI, the daemon, and the thread record on disk. See
664/// `docs/design/clonefile-threads.md` for the rationale.
665#[derive(Clone, Copy, Debug, clap::ValueEnum, PartialEq, Eq)]
666pub enum WorkspaceModeArg {
667    /// Let Heddle choose the right checkout mode.
668    Auto,
669    /// Create a disk checkout with shared extents when the filesystem supports it.
670    Materialized,
671    /// Use a virtual filesystem checkout when the mount feature is available.
672    Virtualized,
673    /// Copy full files into an isolated checkout.
674    Solid,
675}
676
677/// Arguments for the `thread start` and top-level `start` commands.
678#[derive(Clone, Debug, clap::Args)]
679#[command(after_help = "\
680Examples:
681  heddle start feature/auth --path ../feature-auth  # create an isolated checkout
682  heddle start scratch --path ../scratch            # place the checkout explicitly
683  heddle start fix-flake --task 'fix CI flake'      # attach a task description
684
685Isolated 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.
686
687`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.
688
689Advanced (hidden) flags:
690  --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.
691")]
692pub struct ThreadStartArgs {
693    /// Thread name to create or resume.
694    pub name: String,
695
696    /// Base state for the thread (default: HEAD).
697    #[arg(long)]
698    pub from: Option<String>,
699
700    /// Filesystem path for the isolated checkout.
701    #[arg(long)]
702    pub path: Option<std::path::PathBuf>,
703
704    /// Workspace mode for the thread.
705    #[arg(long, value_enum, default_value_t = WorkspaceModeArg::Auto)]
706    pub workspace: WorkspaceModeArg,
707
708    /// AI provider name for the registered agent thread.
709    #[arg(long, hide = true)]
710    pub agent_provider: Option<String>,
711
712    /// AI model name for the registered agent thread.
713    #[arg(long, hide = true)]
714    pub agent_model: Option<String>,
715
716    /// First-class task/goal metadata for the thread.
717    #[arg(long)]
718    pub task: Option<String>,
719
720    /// Parent thread identifier for delegated child work.
721    #[arg(long, hide = true)]
722    pub parent_thread: Option<String>,
723
724    /// Internal hint that this thread was started by automation rather than a direct CLI flow.
725    #[arg(long, hide = true)]
726    pub automated: bool,
727
728    /// Print only the new thread's absolute checkout path to stdout and exit.
729    ///
730    /// Designed for shell wrappers that want to cd into the new checkout:
731    ///   dir=$(heddle start foo --print-cd-path) && cd "$dir"
732    /// Skips all other output (no JSON, no styling, no extra lines) so the
733    /// stdout is a clean path. Mutually exclusive with `--watch`-style flows.
734    #[arg(long, hide = true, conflicts_with_all = ["agent_provider", "agent_model"])]
735    pub print_cd_path: bool,
736
737    /// For `--workspace virtualized`: hand the filesystem mount off to the
738    /// long-lived `heddled` daemon (default). The daemon owns the
739    /// mount across CLI invocations, so the mount survives `heddle
740    /// thread start` exiting. Linux-only; no-op for heavy
741    /// workspaces. Pass `--no-daemon` to keep the mount in-process
742    /// instead.
743    #[arg(
744        long,
745        overrides_with = "no_daemon",
746        action = clap::ArgAction::SetTrue,
747        default_value_t = true,
748        hide = true,
749    )]
750    pub daemon: bool,
751
752    /// For `--workspace virtualized`: keep the filesystem mount in this CLI
753    /// process instead of handing it to the `heddled` daemon. The
754    /// mount unmounts when this `heddle thread start` exits — useful
755    /// for one-shot inspections, debugging the in-process mount path,
756    /// or environments where the daemon can't run.
757    #[arg(
758        long,
759        overrides_with = "daemon",
760        action = clap::ArgAction::SetTrue,
761        hide = true,
762    )]
763    pub no_daemon: bool,
764
765    /// Allow this invocation to open System Settings and wait briefly for
766    /// FSKit approval. Requires an interactive terminal; otherwise setup
767    /// fails before opening a GUI.
768    #[arg(long)]
769    pub interactive_setup: bool,
770
771    /// Redirect cargo's `target/` directory to a workspace-wide shared
772    /// path (`.heddle/targets/<workspace-fingerprint>/`) instead of
773    /// letting cargo create a per-thread `target/`. Saves multiples of
774    /// gigabytes when several materialized threads coexist in a Rust
775    /// workspace. Implemented by writing `.cargo/config.toml` inside
776    /// the new thread checkout — transparent to any `cargo` invocation
777    /// in that directory.
778    ///
779    /// Default: on for solid/materialized threads when the repository
780    /// root has a `Cargo.toml`. Pass `--no-shared-target` to opt out.
781    /// Explicit `--shared-target` forces the attempt on (still a no-op
782    /// without a top-level `Cargo.toml`). Has no effect on virtualized
783    /// (mounted) threads.
784    #[arg(
785        long,
786        overrides_with = "no_shared_target",
787        action = clap::ArgAction::SetTrue,
788        hide = true,
789    )]
790    pub shared_target: bool,
791
792    /// Opt out of the default shared cargo `target/` redirect for
793    /// solid/materialized threads in Rust workspaces. See
794    /// `--shared-target`.
795    #[arg(
796        long,
797        overrides_with = "shared_target",
798        action = clap::ArgAction::SetTrue,
799        hide = true,
800    )]
801    pub no_shared_target: bool,
802
803    /// Symlink the origin checkout's top-level ignored dependency
804    /// directories (`node_modules`, `.venv`, `target`, …) into this
805    /// isolated checkout so it's immediately buildable — run
806    /// `tsc`/`eslint`/tests without reinstalling deps from scratch.
807    ///
808    /// The links point back at the origin's directories and stay
809    /// ignored, so the deps are never captured into heddle. Admin dirs
810    /// (`.git`, `.heddle`) are excluded; only top-level ignored
811    /// directories are linked. Has no effect on virtualized (mounted)
812    /// threads.
813    #[arg(long)]
814    pub hydrate: bool,
815}
816
817/// Arguments for the `try` command — atomic-ephemeral-thread sugar.
818///
819/// Implements item 3.1 from the heddle 6→8 plan: spin up an ephemeral
820/// thread, run `<cmd>` inside that thread's checkout, capture on
821/// success and drop on failure. The parent's working tree is never
822/// touched, regardless of whether the command succeeds or fails — the
823/// ephemeral thread is a sandbox.
824#[derive(Clone, Debug, clap::Args)]
825pub struct TryArgs {
826    /// Optional thread name. When omitted, defaults to
827    /// `try-<short-hash>` derived from the command and a timestamp.
828    #[arg(long)]
829    pub name: Option<String>,
830
831    /// Workspace mode for the ephemeral thread. Defaults to `materialized`
832    /// (a real isolated checkout) so `<cmd>` runs against a proper
833    /// filesystem. Pass `auto`, `virtualized`, or `solid` to use a different
834    /// workspace strategy.
835    #[arg(long, value_enum, default_value_t = WorkspaceModeArg::Materialized)]
836    pub workspace: WorkspaceModeArg,
837    /// On zero exit, automatically land the resulting thread into
838    /// the current thread. Default: off.
839    #[arg(long = "auto-merge")]
840    pub auto_merge: bool,
841
842    /// Keep the ephemeral thread on success even if `--auto-merge`
843    /// would otherwise drop it after merging. Has no effect on the
844    /// failure path (failed attempts are always dropped).
845    #[arg(long = "keep-on-success")]
846    pub keep_on_success: bool,
847
848    /// The command to run. Everything after `--` lands here. The
849    /// first token is the program; the rest are its arguments.
850    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
851    pub command: Vec<String>,
852}
853
854/// Arguments for the `run` command.
855#[derive(Clone, Debug, clap::Args)]
856pub struct RunArgs {
857    /// Thread to execute within.
858    #[arg(long = "thread")]
859    pub thread: Option<String>,
860
861    /// Command to run inside the thread execution root.
862    #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
863    pub command: Vec<String>,
864}
865
866/// Arguments for the `ready` command.
867#[derive(Clone, Debug, clap::Args)]
868pub struct ReadyArgs {
869    /// Thread to evaluate for integration readiness.
870    #[arg(long = "thread")]
871    pub thread: Option<String>,
872
873    /// Intent/message to use if `ready` needs to capture outstanding work first.
874    #[arg(short = 'm', long)]
875    pub message: Option<String>,
876
877    /// Honest confidence estimate (0.0-1.0) if `ready` captures outstanding work.
878    #[arg(long, value_parser = parse_confidence)]
879    pub confidence: Option<f32>,
880
881    /// Preview the readiness decision (integration target, conflicts, verify
882    /// verdicts, would-be thread transition) without capturing work or moving
883    /// the thread to Ready/Blocked. No mutation occurs.
884    #[arg(long)]
885    pub dry_run: bool,
886}
887
888/// Arguments for the `sync` command.
889#[derive(Clone, Debug, clap::Args)]
890pub struct SyncArgs {
891    /// Optional sync target. Omit for operator/thread sync.
892    #[cfg(feature = "git-overlay")]
893    #[command(subcommand)]
894    pub command: Option<SyncCommands>,
895
896    /// Thread to refresh (default: current thread).
897    #[arg(long = "thread")]
898    pub thread: Option<String>,
899}
900
901/// Arguments for the `land` command.
902#[derive(Clone, Debug, clap::Args)]
903pub struct LandArgs {
904    /// Thread to capture and integrate (default: current thread).
905    #[arg(long = "thread")]
906    pub thread: Option<String>,
907
908    /// Peer threads to land in order. When `--thread` is also supplied, that
909    /// thread is landed first. Comma-separated, e.g.
910    /// `--threads alpha,beta,gamma`. Each peer is refreshed and landed against
911    /// the live target tip.
912    #[arg(long = "threads", value_delimiter = ',')]
913    pub threads: Vec<String>,
914
915    /// Intent/message to use if land needs to capture outstanding work first.
916    #[arg(short = 'm', long)]
917    pub message: Option<String>,
918
919    /// Preserve per-State Git export instead of squashing the landed thread.
920    #[arg(long)]
921    pub no_squash: bool,
922
923    /// Preview the integration (thread -> target, merge relation, conflicts,
924    /// verify verdicts) without capturing work, syncing, or merging. No
925    /// mutation occurs and no server round-trip is made.
926    #[arg(long)]
927    pub dry_run: bool,
928}
929
930/// Arguments for `thread show`.
931#[derive(Clone, Debug, clap::Args)]
932pub struct ThreadShowArgs {
933    /// Thread identifier. Defaults to the current thread when omitted.
934    pub thread: Option<String>,
935
936    /// Continuously refresh thread status.
937    #[arg(long)]
938    pub watch: bool,
939
940    /// Internal helper for tests: stop after N watch updates.
941    #[arg(long, hide = true)]
942    pub watch_iterations: Option<usize>,
943
944    /// Internal helper for tests: polling interval in milliseconds.
945    #[arg(long, hide = true)]
946    pub watch_interval_ms: Option<u64>,
947}
948
949/// Arguments for `thread captures`.
950#[derive(Clone, Debug, clap::Args)]
951pub struct ThreadCapturesArgs {
952    /// Thread identifier. Defaults to the current thread when omitted.
953    pub thread: Option<String>,
954
955    /// Maximum captures to show.
956    #[arg(long, default_value_t = 20)]
957    pub limit: usize,
958}
959
960/// Arguments for commands that take a thread identifier. Omitting the
961/// positional resolves to the current thread when one can be inferred
962/// from the working checkout.
963#[derive(Clone, Debug, clap::Args)]
964pub struct ThreadNameArgs {
965    /// Thread identifier. Defaults to the current thread when omitted.
966    pub thread: Option<String>,
967}
968
969/// Arguments for `thread rename`.
970#[derive(Clone, Debug, clap::Args)]
971pub struct ThreadRenameArgs {
972    /// Existing thread identifier.
973    pub old: String,
974
975    /// New thread identifier.
976    pub new: String,
977}
978
979/// Arguments for `thread promote`.
980#[derive(Clone, Debug, clap::Args)]
981pub struct ThreadPromoteArgs {
982    /// Thread identifier.
983    pub thread: String,
984
985    /// Materialized checkout path.
986    #[arg(long)]
987    pub path: Option<std::path::PathBuf>,
988
989    /// Discard dirty work in the source checkout while promoting.
990    #[arg(long)]
991    pub force: bool,
992}
993
994/// Arguments for `thread move`.
995#[derive(Clone, Debug, clap::Args)]
996pub struct ThreadMoveArgs {
997    /// Source thread identifier.
998    pub from: String,
999
1000    /// Destination thread identifier.
1001    pub to: String,
1002
1003    /// Repository-relative path prefix to move.
1004    #[arg(long = "path", required = true, value_name = "PATH")]
1005    pub paths: Vec<String>,
1006
1007    /// Intent/message for the snapshots created by the move.
1008    #[arg(short = 'm', long)]
1009    pub message: Option<String>,
1010}
1011
1012/// Arguments for `thread absorb`.
1013#[derive(Clone, Debug, clap::Args)]
1014pub struct ThreadAbsorbArgs {
1015    /// Child thread to absorb.
1016    pub thread: String,
1017
1018    /// Parent thread to absorb into (default: the thread's recorded parent).
1019    #[arg(long)]
1020    pub into: Option<String>,
1021
1022    /// Commit message for the absorb merge.
1023    #[arg(short = 'm', long)]
1024    pub message: Option<String>,
1025
1026    /// Show the absorb preview without applying it.
1027    #[arg(long)]
1028    pub preview: bool,
1029}
1030
1031/// Arguments for `thread resolve`.
1032#[derive(Clone, Debug, clap::Args)]
1033pub struct ThreadResolveArgs {
1034    /// Thread identifier.
1035    pub thread: String,
1036}
1037
1038/// Arguments for `thread drop`.
1039#[derive(Clone, Debug, clap::Args)]
1040pub struct ThreadDropArgs {
1041    /// Thread identifier.
1042    pub thread: String,
1043
1044    /// Also delete the attached thread ref.
1045    #[arg(long)]
1046    pub delete_thread: bool,
1047
1048    /// Discard uncommitted changes in the thread checkout before dropping it.
1049    #[arg(short, long)]
1050    pub force: bool,
1051}
1052
1053/// Arguments for `thread approve` — record an approval for a
1054/// `<source> -> <target>` merge against the source thread's
1055/// current state.
1056#[derive(Clone, Debug, clap::Args)]
1057pub struct ThreadApproveArgs {
1058    /// Source thread identifier (the change set being merged).
1059    pub source: String,
1060
1061    /// Target thread identifier (where the merge would land).
1062    pub target: String,
1063
1064    /// Optional human note attached to the approval.
1065    #[arg(long)]
1066    pub note: Option<String>,
1067
1068    /// Hosted remote name (default: `origin`).
1069    #[arg(long, default_value = "origin")]
1070    pub remote: String,
1071}
1072
1073/// Arguments for `thread approvals` — list every approval recorded
1074/// for `<source> -> <target>`.
1075#[derive(Clone, Debug, clap::Args)]
1076pub struct ThreadApprovalsArgs {
1077    pub source: String,
1078    pub target: String,
1079    #[arg(long, default_value = "origin")]
1080    pub remote: String,
1081}
1082
1083/// Arguments for `thread revoke-approval` — remove a recorded
1084/// approval by id.
1085#[derive(Clone, Debug, clap::Args)]
1086pub struct ThreadRevokeApprovalArgs {
1087    /// UUID of the approval row to revoke.
1088    pub id: String,
1089    #[arg(long, default_value = "origin")]
1090    pub remote: String,
1091}
1092
1093/// Arguments for `thread check-merge` — query the merge gate
1094/// without recording anything. Returns the unmet requirements.
1095#[derive(Clone, Debug, clap::Args)]
1096pub struct ThreadCheckMergeArgs {
1097    pub source: String,
1098    pub target: String,
1099
1100    /// 'merge' (default), 'force_push', or 'complete'.
1101    #[arg(long, default_value = "merge")]
1102    pub gated_action: String,
1103
1104    /// File paths the diff touches, repeat or comma-separate. Empty =
1105    /// "we don't know" (every path-conditional policy fires).
1106    #[arg(long = "path", value_delimiter = ',')]
1107    pub changed_paths: Vec<String>,
1108
1109    #[arg(long, default_value = "origin")]
1110    pub remote: String,
1111}
1112
1113/// Arguments for the `collapse` command.
1114#[derive(Clone, Debug, clap::Args)]
1115pub struct CollapseArgs {
1116    /// States to collapse.
1117    #[arg(required = true)]
1118    pub states: Vec<String>,
1119
1120    /// Intent/name for the resulting state.
1121    #[arg(long)]
1122    pub into: String,
1123
1124    /// Confidence for the resulting state (0.0-1.0).
1125    #[arg(long)]
1126    pub confidence: Option<f32>,
1127}
1128
1129/// Arguments for the `expand` command.
1130#[derive(Clone, Debug, clap::Args)]
1131pub struct ExpandArgs {
1132    /// Git OID, state spec, or thread name for the squashed land.
1133    pub reference: String,
1134}
1135
1136/// Arguments for the `resolve` command.
1137#[derive(Clone, Debug, clap::Args)]
1138pub struct ResolveArgs {
1139    /// File to resolve.
1140    pub path: Option<String>,
1141
1142    /// Resolve all conflicts.
1143    #[arg(long)]
1144    pub all: bool,
1145
1146    /// List unresolved conflicts.
1147    #[arg(long)]
1148    pub list: bool,
1149
1150    /// Use our version (current thread).
1151    #[arg(long, conflicts_with = "theirs")]
1152    pub ours: bool,
1153
1154    /// Use their version (merged thread).
1155    #[arg(long, conflicts_with = "ours")]
1156    pub theirs: bool,
1157
1158    /// Mark the path resolved even if conflict markers are still present.
1159    #[arg(long)]
1160    pub force: bool,
1161
1162    /// Abort the merge.
1163    #[arg(long)]
1164    pub abort: bool,
1165}
1166
1167/// The `(remote, thread)` pair shared by remote commands that use an
1168/// option-only thread selector.
1169#[derive(Clone, Debug, clap::Args)]
1170pub struct RemoteOperationArgs {
1171    /// Heddle remote name, native repository path, or hosted address.
1172    pub remote: Option<String>,
1173
1174    /// Thread to act on.
1175    #[arg(short, long)]
1176    pub thread: Option<String>,
1177
1178    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1179    /// Prefer enabling TLS; use this only for intentional lab/VPN testing.
1180    #[arg(long)]
1181    pub insecure: bool,
1182}
1183
1184/// Arguments for the `push` command.
1185#[derive(Clone, Debug, clap::Args)]
1186#[command(after_help = "\
1187Git Overlay refs:
1188  A normal push writes refs/heads/<thread> and refs/notes/heddle.
1189  --all-threads writes every refs/heads/<thread> and refs/tags/<tag>, plus refs/notes/heddle.
1190  JSON output lists changed refs in refs_written; verify with git ls-remote <remote>.
1191")]
1192pub struct PushArgs {
1193    /// Heddle remote name, native repository path, or hosted address.
1194    pub remote: Option<String>,
1195
1196    /// Thread to push.
1197    #[arg(short, long, conflicts_with = "thread_arg")]
1198    pub thread: Option<String>,
1199
1200    /// Thread to push; alias for `--thread`.
1201    #[arg(value_name = "THREAD")]
1202    pub thread_arg: Option<String>,
1203
1204    /// State to push (default: HEAD).
1205    #[arg(short, long)]
1206    pub state: Option<String>,
1207
1208    /// Force push.
1209    #[arg(short, long)]
1210    pub force: bool,
1211
1212    /// Push every thread. In Git Overlay, also include every local Git tag.
1213    #[arg(long)]
1214    pub all_threads: bool,
1215
1216    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1217    /// Prefer enabling TLS; use this only for intentional lab/VPN testing.
1218    #[arg(long)]
1219    pub insecure: bool,
1220
1221    /// Preview the push plan (target, thread/track ref, state that would be
1222    /// published, force status) without pushing, moving refs, capturing work,
1223    /// running hooks, or contacting the server for anything beyond read/plan.
1224    #[arg(long)]
1225    pub dry_run: bool,
1226}
1227
1228impl PushArgs {
1229    pub fn thread_name(&self) -> Option<String> {
1230        self.thread.clone().or_else(|| self.thread_arg.clone())
1231    }
1232}
1233
1234/// Arguments for the `pull` command.
1235#[derive(Clone, Debug, clap::Args)]
1236#[command(after_help = "\
1237Advanced (hidden) flags:
1238  --lazy leaves blob content absent by design and hydrates it explicitly later. Hosted/network Heddle remotes only.
1239")]
1240pub struct PullArgs {
1241    #[command(flatten)]
1242    pub remote_op: RemoteOperationArgs,
1243
1244    /// Local thread to update.
1245    #[arg(short, long)]
1246    pub local_thread: Option<String>,
1247
1248    /// Leave blob content absent by design and hydrate it explicitly later.
1249    #[arg(long, hide = true)]
1250    pub lazy: bool,
1251}
1252
1253/// Arguments for the `clone` command.
1254///
1255/// Help style budget (heddle#652): `--help` carries the signature, flags,
1256/// a one-screen Behavior summary, and the hidden-flag breadcrumb
1257/// (heddle#646). The full default-thread fallback chain and --depth
1258/// exposition moved to `heddle help clone` (help.rs CLONE_TOPIC); keep
1259/// flag docs single-line so clap renders the compact help layout.
1260#[derive(Clone, Debug, clap::Args)]
1261#[command(after_help = "\
1262Behavior:
1263  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`.
1264
1265Advanced/planned flags: see `heddle help clone`.
1266
1267Examples:
1268  heddle clone ../native-repo ./clone                # local native Heddle repository
1269  heddle clone heddle://host/repo ./clone --depth 1   # shallow Heddle clone: tip plus immediate parents
1270")]
1271pub struct CloneArgs {
1272    /// Remote repository path.
1273    pub remote: String,
1274
1275    /// Local directory to clone into.
1276    pub local: String,
1277
1278    /// Thread to check out after cloning.
1279    #[arg(long)]
1280    pub thread: Option<String>,
1281
1282    /// Create a shallow clone with the specified depth. `0` means full history.
1283    #[arg(long)]
1284    pub depth: Option<u32>,
1285
1286    // Hosted/network remotes only. The user-facing exposition lives in the
1287    // after-help breadcrumb above and `heddle help clone`.
1288    /// Leave blob content absent by design and hydrate it explicitly later.
1289    #[arg(long, hide = true)]
1290    pub lazy: bool,
1291
1292    /// Allow cleartext (non-TLS) connections to non-loopback hosts.
1293    #[arg(long)]
1294    pub insecure: bool,
1295
1296    // Only `blob:none` is accepted (a synonym for --lazy on hosted
1297    // remotes); git-style filters such as `tree:0` or `blob:limit=…` are
1298    // rejected at parse time. See the after-help breadcrumb and `heddle help
1299    // clone`.
1300    /// Partial-clone filter spec (`blob:none` only).
1301    #[arg(long, hide = true, value_name = "SPEC", value_parser = parse_clone_filter_spec)]
1302    pub filter: Option<String>,
1303
1304    /// Clone a whole hosted monorepo: resolve the root spool's child tree and
1305    /// clone every child spool at its anchored state into its mount path.
1306    /// Hosted/network remotes only. (Alias: --monorepo.)
1307    #[arg(long, visible_alias = "monorepo")]
1308    pub recursive: bool,
1309}
1310
1311fn parse_clone_filter_spec(s: &str) -> Result<String, String> {
1312    match s {
1313        "blob:none" => Ok(s.to_string()),
1314        other => Err(format!(
1315            "unsupported --filter spec `{other}`; only `blob:none` is supported today"
1316        )),
1317    }
1318}
1319
1320/// Arguments for `agent provenance begin`.
1321#[derive(Clone, Debug, clap::Args)]
1322pub struct AgentProvenanceBeginArgs {
1323    /// Provider name (e.g., "anthropic", "openai").
1324    #[arg(long)]
1325    pub provider: String,
1326
1327    /// Model identifier (e.g., "claude-opus-4").
1328    #[arg(long)]
1329    pub model: String,
1330
1331    /// Policy or prompt template ID.
1332    #[arg(long)]
1333    pub policy: Option<String>,
1334}
1335
1336/// Arguments for `agent provenance segment`.
1337#[derive(Clone, Debug, clap::Args)]
1338pub struct AgentProvenanceSegmentArgs {
1339    /// Provider name (e.g., "anthropic", "openai").
1340    #[arg(long)]
1341    pub provider: String,
1342
1343    /// Model identifier (e.g., "claude-opus-4").
1344    #[arg(long)]
1345    pub model: String,
1346
1347    /// Policy or prompt template ID.
1348    #[arg(long)]
1349    pub policy: Option<String>,
1350}
1351
1352/// Arguments for `agent provenance end`.
1353#[derive(Clone, Debug, clap::Args)]
1354pub struct AgentProvenanceEndArgs {
1355    /// Session ID to end (default: current session).
1356    pub session_id: Option<String>,
1357}
1358
1359/// Arguments for `agent provenance show`.
1360#[derive(Clone, Debug, clap::Args)]
1361pub struct AgentProvenanceShowArgs {
1362    /// Session ID to show (default: current session).
1363    pub session_id: Option<String>,
1364}
1365
1366/// Arguments for `agent provenance list`.
1367#[derive(Clone, Debug, clap::Args)]
1368pub struct AgentProvenanceListArgs {
1369    /// Show only active sessions.
1370    #[arg(long)]
1371    pub active: bool,
1372}
1373
1374/// Arguments for the `worktree add` command.
1375#[derive(Clone, Debug, clap::Args)]
1376pub struct WorktreeAddArgs {
1377    /// Path to the new agent checkout directory.
1378    pub path: std::path::PathBuf,
1379
1380    /// Thread name for the agent (created if absent, default: HEAD thread).
1381    #[arg(long)]
1382    pub thread: Option<String>,
1383
1384    /// Base state to materialize (default: HEAD).
1385    #[arg(long)]
1386    pub from: Option<String>,
1387}
1388
1389/// Arguments for the `worktree remove` command.
1390#[derive(Clone, Debug, clap::Args)]
1391pub struct WorktreeRemoveArgs {
1392    /// Path to the isolated checkout directory to remove.
1393    pub path: std::path::PathBuf,
1394
1395    /// Also delete the associated thread ref, if this checkout is attached.
1396    #[arg(long)]
1397    pub delete_thread: bool,
1398}
1399
1400/// Arguments for `agent presence list`.
1401#[derive(Clone, Debug, clap::Args)]
1402pub struct AgentPresenceListArgs {
1403    /// Show only active actors.
1404    #[arg(long)]
1405    pub active: bool,
1406}
1407
1408/// Arguments for `agent presence show`.
1409#[derive(Clone, Debug, clap::Args)]
1410pub struct AgentPresenceShowArgs {
1411    /// Session ID to show (default: current thread actor).
1412    pub session: Option<String>,
1413}
1414
1415/// Arguments for `agent presence explain`.
1416#[derive(Clone, Debug, clap::Args)]
1417pub struct AgentPresenceExplainArgs {
1418    /// Session ID to explain (default: current thread actor).
1419    pub session: Option<String>,
1420}
1421
1422/// Arguments for `agent presence complete`.
1423#[derive(Clone, Debug, clap::Args)]
1424pub struct AgentPresenceCompleteArgs {
1425    /// Session ID to mark as complete (default: current thread actor).
1426    #[arg(long)]
1427    pub session: Option<String>,
1428}
1429
1430/// Arguments for `agent reserve`.
1431#[derive(Clone, Debug, clap::Args)]
1432pub struct AgentReserveArgs {
1433    /// Thread to reserve.
1434    #[arg(long)]
1435    pub thread: String,
1436
1437    /// Anchor state spec (default: current HEAD).
1438    #[arg(long)]
1439    pub anchor: Option<String>,
1440
1441    /// Optional task description.
1442    #[arg(long)]
1443    pub task: Option<String>,
1444
1445    /// Local agent task assignment id to attach to this reservation.
1446    #[arg(long)]
1447    pub task_id: Option<String>,
1448
1449    /// Reap the lease early when this long-lived owner process exits.
1450    #[arg(long, value_name = "PID")]
1451    pub hold_for_pid: Option<u32>,
1452}
1453
1454/// Arguments for `agent heartbeat`.
1455#[derive(Clone, Debug, clap::Args)]
1456pub struct AgentHeartbeatArgs {
1457    /// Writer lease id returned by `agent reserve`.
1458    #[arg(long)]
1459    pub lease: String,
1460
1461    /// Bearer token returned by `agent reserve`.
1462    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1463    pub token: String,
1464}
1465
1466/// Arguments for `agent release`.
1467#[derive(Clone, Debug, clap::Args)]
1468pub struct AgentReleaseArgs {
1469    /// Writer lease id returned by `agent reserve`.
1470    #[arg(long)]
1471    pub lease: String,
1472
1473    /// Bearer token returned by `agent reserve`.
1474    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1475    pub token: String,
1476
1477    /// Terminal status to record.
1478    #[arg(long, default_value = "complete")]
1479    pub status: AgentReleaseStatusArg,
1480}
1481
1482#[derive(Clone, Debug, clap::ValueEnum)]
1483pub enum AgentReleaseStatusArg {
1484    Complete,
1485    Abandoned,
1486}
1487
1488/// Arguments for `agent list`.
1489#[derive(Clone, Debug, clap::Args)]
1490pub struct AgentApiListArgs {
1491    /// Filter by thread.
1492    #[arg(long)]
1493    pub thread: Option<String>,
1494
1495    /// Show only active reservations.
1496    #[arg(long)]
1497    pub alive_only: bool,
1498}
1499
1500#[derive(Clone, Debug, clap::ValueEnum)]
1501pub enum AgentTaskStatusArg {
1502    Open,
1503    InProgress,
1504    Blocked,
1505    Complete,
1506    Abandoned,
1507}
1508
1509/// Arguments for `agent task create`.
1510#[derive(Clone, Debug, clap::Args)]
1511pub struct AgentTaskCreateArgs {
1512    /// Optional caller-provided task id (default: generated task UUIDv7 id).
1513    #[arg(long)]
1514    pub task_id: Option<String>,
1515
1516    /// Human-readable task title.
1517    #[arg(long)]
1518    pub title: String,
1519
1520    /// Detailed task body.
1521    #[arg(long)]
1522    pub body: Option<String>,
1523
1524    /// Thread this task targets.
1525    #[arg(long)]
1526    pub thread: String,
1527
1528    /// Optional base state id this task was delegated from.
1529    #[arg(long)]
1530    pub base_state: Option<String>,
1531
1532    /// Optional base root id this task was delegated from.
1533    #[arg(long)]
1534    pub base_root: Option<String>,
1535
1536    /// Optional parent task id.
1537    #[arg(long)]
1538    pub parent_task_id: Option<String>,
1539
1540    /// Optional coordination discussion id.
1541    #[arg(long)]
1542    pub coordination_discussion_id: Option<String>,
1543
1544    /// Allow this task to continue without hosted connectivity.
1545    #[arg(long)]
1546    pub allow_offline: bool,
1547
1548    /// Principal or agent that delegated this task.
1549    #[arg(long)]
1550    pub delegated_by: Option<String>,
1551}
1552
1553/// Arguments for `agent task list`.
1554#[derive(Clone, Debug, clap::Args)]
1555pub struct AgentTaskListArgs {
1556    /// Filter by target thread.
1557    #[arg(long)]
1558    pub thread: Option<String>,
1559
1560    /// Filter by task status.
1561    #[arg(long)]
1562    pub status: Option<AgentTaskStatusArg>,
1563}
1564
1565/// Arguments for `agent task show`.
1566#[derive(Clone, Debug, clap::Args)]
1567pub struct AgentTaskShowArgs {
1568    /// Task id to show.
1569    pub task_id: String,
1570}
1571
1572/// Arguments for `agent task update`.
1573#[derive(Clone, Debug, clap::Args)]
1574pub struct AgentTaskUpdateArgs {
1575    /// Task id to update.
1576    pub task_id: String,
1577
1578    /// Replace the task title.
1579    #[arg(long)]
1580    pub title: Option<String>,
1581
1582    /// Replace the task body.
1583    #[arg(long)]
1584    pub body: Option<String>,
1585
1586    /// Replace the task status.
1587    #[arg(long)]
1588    pub status: Option<AgentTaskStatusArg>,
1589
1590    /// Replace the target thread.
1591    #[arg(long)]
1592    pub thread: Option<String>,
1593
1594    /// Replace the base state id.
1595    #[arg(long)]
1596    pub base_state: Option<String>,
1597
1598    /// Replace the base root id.
1599    #[arg(long)]
1600    pub base_root: Option<String>,
1601
1602    /// Replace the parent task id.
1603    #[arg(long)]
1604    pub parent_task_id: Option<String>,
1605
1606    /// Replace the coordination discussion id.
1607    #[arg(long)]
1608    pub coordination_discussion_id: Option<String>,
1609
1610    /// Allow this task to continue without hosted connectivity.
1611    #[arg(long, conflicts_with = "no_allow_offline")]
1612    pub allow_offline: bool,
1613
1614    /// Disallow offline continuation for this task.
1615    #[arg(long, conflicts_with = "allow_offline")]
1616    pub no_allow_offline: bool,
1617
1618    /// Replace the delegating principal or agent label.
1619    #[arg(long)]
1620    pub delegated_by: Option<String>,
1621}
1622
1623/// Arguments shared by `agent fanout plan` and `agent fanout start`.
1624#[derive(Clone, Debug, clap::Args)]
1625pub struct AgentFanoutPlanArgs {
1626    /// Parent coordination task title.
1627    #[arg(long)]
1628    pub title: String,
1629
1630    /// Lane spec: `<thread>=<path>:<title>`. Repeat once per child lane.
1631    #[arg(long, value_name = "THREAD=PATH:TITLE")]
1632    pub lane: Vec<String>,
1633
1634    /// Optional collaboration discussion id to store on task assignments.
1635    #[arg(long)]
1636    pub coordination_discussion_id: Option<String>,
1637}
1638
1639/// Arguments for `agent fanout start`.
1640#[derive(Clone, Debug, clap::Args)]
1641pub struct AgentFanoutStartArgs {
1642    /// Parent coordination task title.
1643    #[arg(long)]
1644    pub title: String,
1645
1646    /// Lane spec: `<thread>=<path>:<title>`. Repeat once per child lane.
1647    #[arg(long, value_name = "THREAD=PATH:TITLE")]
1648    pub lane: Vec<String>,
1649
1650    /// Optional collaboration discussion id to store on task assignments.
1651    #[arg(long)]
1652    pub coordination_discussion_id: Option<String>,
1653}
1654
1655/// Arguments for `agent capture` under a current reservation lease.
1656#[derive(Clone, Debug, clap::Args)]
1657pub struct AgentCaptureArgs {
1658    /// Writer lease id returned by `agent reserve`.
1659    #[arg(long)]
1660    pub lease: String,
1661
1662    /// Bearer token returned by `agent reserve`.
1663    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1664    pub token: String,
1665
1666    /// Capture intent / commit message.
1667    #[arg(long, short = 'm', alias = "intent")]
1668    pub message: Option<String>,
1669
1670    /// Honest confidence estimate (0.0–1.0).
1671    #[arg(long, value_parser = parse_confidence)]
1672    pub confidence: Option<f32>,
1673}
1674
1675/// Arguments for `agent ready` under a writer lease.
1676#[derive(Clone, Debug, clap::Args)]
1677pub struct AgentReadyArgs {
1678    /// Writer lease id returned by `agent reserve`.
1679    #[arg(long)]
1680    pub lease: String,
1681
1682    /// Bearer token returned by `agent reserve`.
1683    #[arg(long, env = "HEDDLE_RESERVATION_TOKEN", hide_env_values = true)]
1684    pub token: String,
1685
1686    /// Optional summary message.
1687    #[arg(long, short = 'm')]
1688    pub message: Option<String>,
1689
1690    /// Honest confidence estimate (0.0-1.0) if `agent ready` captures outstanding work.
1691    #[arg(long, value_parser = parse_confidence)]
1692    pub confidence: Option<f32>,
1693}
1694
1695/// Arguments for the `watch` command.
1696///
1697/// Streams live oplog activity (snapshots, merges, thread create/update,
1698/// markers, etc.) as it happens. Default behavior tails forever and exits
1699/// on Ctrl-C. `--since 5m` replays the last N before tailing live;
1700/// `--filter` restricts output to the named kinds; `--output json` emits one
1701/// JSON object per line for piping to `jq`.
1702#[derive(Clone, Debug, clap::Args)]
1703pub struct WatchArgs {
1704    /// Replay events from this duration ago (e.g. `30s`, `5m`, `1h`,
1705    /// `2d`) before tailing live. When unset, only new events are
1706    /// emitted.
1707    #[arg(long, value_name = "DURATION")]
1708    pub since: Option<String>,
1709
1710    /// Comma-separated event kinds to include
1711    /// (`snapshot,merge,thread_create,thread_update,thread_delete,
1712    /// collapse,thread_marker_create,thread_marker_delete`).
1713    #[arg(long, value_name = "KINDS")]
1714    pub filter: Option<String>,
1715
1716    /// Internal helper for tests: stop after the oplog file produces
1717    /// this many modify events (still drains pending entries first).
1718    #[arg(long, hide = true)]
1719    pub max_iterations: Option<usize>,
1720
1721    /// Internal helper for tests: poll interval in milliseconds for
1722    /// the `notify` watcher's debounce check (default 200ms).
1723    #[arg(long, hide = true)]
1724    pub poll_interval_ms: Option<u64>,
1725}
1726
1727// `AgentCaptureArgs` and `AgentReadyArgs` defined earlier in this
1728// file. A second copy was left here by the rebase (the workstreams
1729// commit added them twice when the cherry-pick had lost the
1730// originals and we re-added them mid-rebase). Removed.
1731
1732#[cfg(test)]
1733mod capture_message_alias_tests {
1734    use clap::Parser;
1735
1736    use crate::cli::{Cli, Commands, SnapshotArgs};
1737
1738    fn parse_capture(extra: &[&str]) -> Result<SnapshotArgs, clap::Error> {
1739        let mut argv: Vec<&str> = vec!["heddle", "capture"];
1740        argv.extend_from_slice(extra);
1741        let cli = Cli::try_parse_from(argv)?;
1742        match cli.command {
1743            Commands::Capture(args) => Ok(args),
1744            _ => panic!("expected Commands::Capture"),
1745        }
1746    }
1747
1748    #[test]
1749    fn capture_accepts_message_alias() {
1750        let args = parse_capture(&["--message", "my change"]).expect("--message should parse");
1751        assert_eq!(args.intent.as_deref(), Some("my change"));
1752    }
1753
1754    #[test]
1755    fn capture_accepts_intent_long_form() {
1756        let args = parse_capture(&["--intent", "my change"]).expect("--intent should parse");
1757        assert_eq!(args.intent.as_deref(), Some("my change"));
1758    }
1759
1760    #[test]
1761    fn capture_accepts_short_m() {
1762        let args = parse_capture(&["-m", "my change"]).expect("-m should parse");
1763        assert_eq!(args.intent.as_deref(), Some("my change"));
1764    }
1765
1766    #[test]
1767    fn capture_rejects_non_finite_or_out_of_range_confidence() {
1768        for value in ["NaN", "inf", "-0.1", "1.7"] {
1769            let confidence_arg = format!("--confidence={value}");
1770            let err = parse_capture(&["-m", "bad confidence", &confidence_arg])
1771                .expect_err("invalid confidence should fail to parse");
1772            assert!(
1773                err.to_string()
1774                    .contains("confidence must be a finite number from 0.0 to 1.0"),
1775                "unexpected parse error for {value}: {err}"
1776            );
1777        }
1778    }
1779}
1780
1781#[cfg(test)]
1782mod clone_filter_tests {
1783    use clap::Parser;
1784
1785    use crate::cli::{Cli, CloneArgs, Commands};
1786
1787    fn parse_clone(extra: &[&str]) -> Result<CloneArgs, clap::Error> {
1788        let mut argv: Vec<&str> = vec!["heddle", "clone", "remote", "local"];
1789        argv.extend_from_slice(extra);
1790        let cli = Cli::try_parse_from(argv)?;
1791        match cli.command {
1792            Commands::Clone(args) => Ok(args),
1793            _ => panic!("expected Commands::Clone"),
1794        }
1795    }
1796
1797    #[test]
1798    fn parses_clone_filter_blob_none() {
1799        let args = parse_clone(&["--filter", "blob:none"]).expect("parse --filter blob:none");
1800        assert_eq!(args.filter.as_deref(), Some("blob:none"));
1801        assert!(!args.lazy);
1802    }
1803
1804    #[test]
1805    fn rejects_unknown_filter_spec() {
1806        let err = parse_clone(&["--filter", "tree:0"])
1807            .expect_err("unknown --filter spec should fail to parse");
1808        let msg = err.to_string();
1809        assert!(
1810            msg.contains("tree:0") && msg.contains("blob:none"),
1811            "error should name the bad spec and the supported one: {msg}"
1812        );
1813    }
1814}