Skip to main content

sqlite_graphrag/commands/enrich/
args.rs

1//! CLI argument types for the `enrich` subcommand.
2//! Extracted from mod.rs (Wave C1).
3
4use serde::{Deserialize, Serialize};
5use std::path::PathBuf;
6
7use super::DEFAULT_BODY_ENRICH_MAX_CHARS;
8use super::DEFAULT_BODY_ENRICH_MIN_CHARS;
9
10// ---------------------------------------------------------------------------
11// CLI args
12// ---------------------------------------------------------------------------
13
14/// Operation to perform in the `enrich` command.
15#[derive(Debug, Clone, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
16#[serde(rename_all = "kebab-case")]
17pub enum EnrichOperation {
18    /// Add missing entity/relationship bindings to memories (fully implemented).
19    /// memory-bindings LINKS each memory to the EXISTING entities extracted from
20    /// its body — it does not invent a new graph, it only connects what is missing. Scans
21    /// only UNBOUND memories (those with zero `memory_entities`).
22    MemoryBindings,
23    /// GAP-SG-24/26: additive augmentation — re-run binding extraction over
24    /// memories that are ALREADY bound, filtered by `--names`/`--names-file`, to
25    /// merge newly-discovered entities/relationships WITHOUT removing existing
26    /// links. Requires a name filter (refuses to re-scan the whole namespace).
27    AugmentBindings,
28    /// Fill NULL/empty entity descriptions with LLM-generated summaries (fully implemented).
29    EntityDescriptions,
30    /// Expand short memory bodies into richer content (fully implemented, GAP-18).
31    BodyEnrich,
32    /// Rebuild missing memory embeddings without rewriting the memory body.
33    ReEmbed,
34    /// Calibrate relationship weights using LLM analysis (fully implemented; persists weight).
35    WeightCalibrate,
36    /// Reclassify relationship types using LLM judgment (fully implemented; persists relation).
37    RelationReclassify,
38    /// Connect isolated entities by suggesting and persisting new relationships (fully implemented).
39    EntityConnect,
40    /// Validate entity type assignments using LLM judgment (fully implemented; persists type).
41    EntityTypeValidate,
42    /// Enrich memory descriptions that are generic/auto-generated (fully implemented; persists description).
43    DescriptionEnrich,
44    /// Identify cross-domain bridges between disconnected subgraphs.
45    /// Shares the O(k) pair scan + `entity_connect_seen` drain path with
46    /// `entity-connect` (v1.1.04+ / v1.1.06); status backlog proxy remains 0.
47    CrossDomainBridges,
48    /// Classify memories into domain categories (fully implemented; persists metadata).
49    DomainClassify,
50    /// Audit the graph for quality issues (scan/report; does not mutate graph structure).
51    GraphAudit,
52    /// Synthesize deep-research findings into graph memories (fully implemented when bindings persist).
53    DeepResearchSynth,
54    /// Extract structured body from unstructured text (fully implemented; persists body).
55    BodyExtract,
56}
57
58/// v1.1.1 (P2): which embedding table the `re-embed` operation backfills.
59///
60/// `memories` is the historical behaviour (and the default, so existing
61/// invocations are unchanged); `entities` and `chunks` close the retroactive
62/// coverage gap for `entity_embeddings` / `chunk_embeddings`; `all` runs the
63/// three scans in one invocation.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Serialize, Deserialize)]
65#[serde(rename_all = "kebab-case")]
66pub enum ReEmbedTarget {
67    /// Memories without a live vector in `memory_embeddings` (default).
68    Memories,
69    /// Entities without a live vector in `entity_embeddings`.
70    Entities,
71    /// Chunks without a live vector in `chunk_embeddings`.
72    Chunks,
73    /// All three targets in a single run.
74    All,
75}
76
77/// LLM provider for enrichment.
78#[derive(Debug, Clone, PartialEq, Eq, clap::ValueEnum)]
79pub enum EnrichMode {
80    /// Use locally installed Claude Code CLI (OAuth-first).
81    ClaudeCode,
82    /// Use locally installed OpenAI Codex CLI.
83    Codex,
84    /// Use locally installed OpenCode CLI.
85    #[value(name = "opencode")]
86    Opencode,
87    /// Use the OpenRouter chat-completions REST API (no local CLI; v1.0.95).
88    #[value(name = "openrouter")]
89    OpenRouter,
90}
91
92impl std::fmt::Display for EnrichMode {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        match self {
95            EnrichMode::ClaudeCode => write!(f, "claude-code"),
96            EnrichMode::Codex => write!(f, "codex"),
97            EnrichMode::Opencode => write!(f, "opencode"),
98            EnrichMode::OpenRouter => write!(f, "openrouter"),
99        }
100    }
101}
102
103/// Arguments for the `enrich` subcommand.
104#[derive(clap::Args)]
105#[command(
106    about = "Enrich graph memories and entities using an LLM provider",
107    after_long_help = "EXAMPLES:\n  \
108    # Add missing entity bindings to all unbound memories\n  \
109    sqlite-graphrag enrich --operation memory-bindings --mode codex --codex-model gpt-5.4-mini\n\n  \
110    # Fill entity descriptions (dry-run preview, no tokens spent)\n  \
111    sqlite-graphrag enrich --operation entity-descriptions --dry-run --json\n\n  \
112    # Expand short memory bodies (GAP-18)\n  \
113    sqlite-graphrag enrich --operation body-enrich --min-output-chars 600\n\n  \
114    # Rebuild only missing memory embeddings without rewriting bodies\n  \
115    sqlite-graphrag enrich --operation re-embed --limit 100\n\n  \
116    # Resume an interrupted body-enrich run\n  \
117    sqlite-graphrag enrich --operation body-enrich --resume --json\n\n  \
118    # Retry only failed items from a previous run\n  \
119    sqlite-graphrag enrich --operation memory-bindings --retry-failed --json\n\n  \
120    # Converge the whole backlog (internal scan+drain loop, no bash wrapper)\n  \
121    sqlite-graphrag enrich --operation memory-bindings --mode openrouter \\\n    \
122      --openrouter-model deepseek/deepseek-v4-flash:nitro --until-empty --max-runtime 600\n\n  \
123    # Inspect / resurrect dead-letter items\n  \
124    sqlite-graphrag enrich --operation memory-bindings --list-dead\n  \
125    sqlite-graphrag enrich --operation memory-bindings --requeue-dead\n\n  \
126    # Read-only status (no LLM, no singleton)\n  \
127    sqlite-graphrag enrich --operation memory-bindings --status\n\n\
128    OPERATIONS NOTE:\n  \
129    memory-bindings LINKS each memory to the EXISTING entities extracted from its\n  \
130    body — it does not invent a new graph, it connects what is missing. It scans\n  \
131    only UNBOUND memories. To re-run extraction over ALREADY-bound memories and\n  \
132    MERGE newly-found entities/relationships additively (without removing links),\n  \
133    use --operation augment-bindings with --names/--names-file.\n\n\
134    DEAD-LETTER SIDECAR (.enrich-queue.sqlite):\n  \
135    A SQLite sidecar tracks each work item across runs. Schema (table `queue`):\n  \
136    item_key (UNIQUE name/id), item_type (memory|entity), operation, memory_id,\n  \
137    status (pending|processing|done|skipped|dead), attempt, error, error_class,\n  \
138    next_retry_at (backoff cooldown). --until-empty loops scan→drain internally\n  \
139    until eligible items are exhausted; transient failures (incl. malformed/non-\n  \
140    JSON LLM output, GAP-SG-09) reschedule with backoff until --max-attempts, then\n  \
141    land in status='dead'. Use --status to see the queue, --list-dead to inspect\n  \
142    the sink, --requeue-dead to retry it, and --ignore-backoff to skip cooldowns.\n  \
143    --names/--names-file also remedy a cooldown by targeting a specific subset.\n\n\
144    EXIT CODES:\n  \
145    0  success\n  \
146    1  validation error (bad args, binary not found)\n  \
147    14 I/O error"
148)]
149#[derive(Clone)]
150pub struct EnrichArgs {
151    /// Enrichment operation to run. Required for write operations; optional for
152    /// the read-only queue inspectors (`--status` / `--list-dead` /
153    /// `--requeue-dead`), where it defaults to `memory-bindings` when omitted
154    /// (GAP-SG-31).
155    #[arg(
156        long,
157        short = 'o',
158        value_enum,
159        value_name = "OPERATION",
160        // GAP-CLI-DRY-01: dry-run is read-only (no LLM); still needs --operation.
161        required_unless_present_any = ["status", "list_dead", "requeue_dead", "prune_dead_orphans", "prune_dead_entity_orphans"]
162    )]
163    pub operation: Option<EnrichOperation>,
164
165    /// LLM provider to use. Required for write operations; not needed for the
166    /// read-only queue inspectors (`--status` / `--list-dead` /
167    /// `--requeue-dead`), which never call the LLM (GAP-SG-31).
168    ///
169    /// GAP-CLI-DRY-01 (v1.1.8): also optional for `--dry-run` (preview only).
170    #[arg(
171        long,
172        value_enum,
173        required_unless_present_any = ["status", "list_dead", "requeue_dead", "prune_dead_orphans", "prune_dead_entity_orphans", "dry_run"]
174    )]
175    pub mode: Option<EnrichMode>,
176
177    /// Maximum number of items to process in this run. Omit for all.
178    #[arg(long, value_name = "N")]
179    pub limit: Option<usize>,
180
181    /// v1.1.1 (P2): embedding table backfilled by `--operation re-embed`.
182    /// `memories` (default) preserves the historical behaviour; `entities`
183    /// and `chunks` rebuild `entity_embeddings` / `chunk_embeddings`; `all`
184    /// covers the three tables in one run. The scan also selects rows whose
185    /// stored `dim` diverges from the configured `--embedding-dim` (P10),
186    /// so legacy-dimension vectors are regenerated, not only missing ones.
187    /// Ignored (rejected) for every other operation.
188    #[arg(long, value_enum, value_name = "TARGET", default_value_t = ReEmbedTarget::Memories)]
189    pub target: ReEmbedTarget,
190
191    /// Preview items without calling the LLM (zero tokens consumed).
192    #[arg(long)]
193    pub dry_run: bool,
194
195    /// Namespace to operate on. Default: global.
196    #[arg(long)]
197    pub namespace: Option<String>,
198
199    // -- Provider flags (Claude) --
200    /// Path to the Claude Code binary. Default: auto-detect from PATH.
201    #[arg(long, value_name = "PATH")]
202    pub claude_binary: Option<PathBuf>,
203
204    /// Claude model to use (e.g. claude-sonnet-4-6).
205    #[arg(long, value_name = "MODEL")]
206    pub claude_model: Option<String>,
207
208    /// Timeout per item in seconds when using Claude Code. Default: 300.
209    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
210    pub claude_timeout: u64,
211
212    // -- Provider flags (Codex) --
213    /// Path to the Codex CLI binary. Default: auto-detect from PATH.
214    #[arg(long, value_name = "PATH")]
215    pub codex_binary: Option<PathBuf>,
216
217    /// Codex model to use (e.g. o4-mini).
218    #[arg(long, value_name = "MODEL")]
219    pub codex_model: Option<String>,
220
221    /// Timeout per item in seconds when using Codex. Default: 300.
222    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
223    pub codex_timeout: u64,
224
225    // -- Provider flags (OpenCode) --
226    /// Path to the OpenCode binary. Default: auto-detect from PATH.
227    #[arg(long, value_name = "PATH")]
228    pub opencode_binary: Option<PathBuf>,
229
230    /// OpenCode model to use.
231    #[arg(long, value_name = "MODEL")]
232    pub opencode_model: Option<String>,
233
234    /// Timeout per item in seconds when using OpenCode. Default: 300.
235    #[arg(
236        long,
237        value_name = "SECONDS",
238                default_value_t = 300
239    )]
240    pub opencode_timeout: u64,
241
242    // -- Provider flags (OpenRouter, v1.0.95) --
243    /// OpenRouter text model to use (REQUIRED with --mode openrouter; no default).
244    #[arg(long, value_name = "MODEL")]
245    pub openrouter_model: Option<String>,
246
247    /// OpenRouter API key. Falls back to OPENROUTER_API_KEY env or stored config.
248    #[arg(
249        long,
250        value_name = "KEY",
251                hide_env_values = true
252    )]
253    pub openrouter_api_key: Option<String>,
254
255    /// Timeout per item in seconds when using OpenRouter. Default: 600.
256    ///
257    /// GAP-SG-17: raised from 300 to 600 because dense bodies (close to the
258    /// ~32K-token context ceiling of the configured model) routinely take
259    /// longer than five minutes to generate via `deepseek-v4-flash:nitro`.
260    /// Raise it further for very large corpora; lower it for short snippets.
261    #[arg(long, value_name = "SECONDS", default_value_t = 600)]
262    pub openrouter_timeout: u64,
263
264    /// Optional OpenRouter base URL override (reserved; defaults to the public API).
265    #[arg(long, value_name = "URL")]
266    pub openrouter_base_url: Option<String>,
267
268    // -- Cost controls --
269    /// Abort when cumulative cost exceeds this USD budget (API key only; ignored for OAuth).
270    #[arg(long, value_name = "USD")]
271    pub max_cost_usd: Option<f64>,
272
273    // -- Queue controls --
274    /// Resume a previously interrupted run (skip already-done items).
275    #[arg(long)]
276    pub resume: bool,
277
278    /// Retry only items that failed in a previous run.
279    #[arg(long)]
280    pub retry_failed: bool,
281
282    /// v1.1.2 (Bug 4): reset `processing` rows whose `claimed_at` is older than
283    /// `--stale-claim-secs` (default 1800s = 30 min) back to `pending`, then exit.
284    /// Recover rows orphaned by a kill -9 mid-enrich without a full re-scan.
285    #[arg(long)]
286    pub reset_stale_claims: bool,
287
288    /// v1.1.2 (Bug 4): age threshold (seconds) for `--reset-stale-claims` and
289    /// the run-startup stale sweep. Default 1800 (30 min).
290    #[arg(long, value_name = "SECONDS", default_value_t = 1800)]
291    pub stale_claim_secs: u64,
292
293    /// GAP-ENRICH-BACKLOG-CONVERGE: loop scan→drain internally until the queue
294    /// empties of eligible items or --max-runtime elapses; removes the need for
295    /// an external bash retry loop.
296    #[arg(long)]
297    pub until_empty: bool,
298
299    /// GAP-ENRICH-BACKLOG-CONVERGE: wall-clock ceiling in seconds for
300    /// --until-empty. Defaults to 3600 when omitted.
301    #[arg(long, value_name = "SECONDS")]
302    pub max_runtime: Option<u64>,
303
304    /// GAP-ENRICH-BACKLOG-CONVERGE: attempts per item before it becomes a
305    /// dead-letter (status='dead'). Range 1..=20. Default 8.
306    ///
307    /// GAP-SG-21: the default was raised from 5 to 8 because GAP-SG-09 now
308    /// reclassifies malformed / non-JSON LLM output as TRANSIENT (retryable)
309    /// rather than a permanent HardFailure. A flaky structured-output model
310    /// (e.g. deepseek-v4-flash:nitro) may emit several bad generations in a row
311    /// even after JSON repair (GAP-SG-10) recovers most of them; the extra
312    /// attempts give the backlog room to converge before an item is parked in
313    /// the dead-letter sink. Permanent faults (ProviderError, NotFound) still
314    /// dead-letter on the first attempt regardless of this value.
315    #[arg(long, value_name = "N", default_value_t = 8, value_parser = clap::value_parser!(u32).range(1..=20))]
316    pub max_attempts: u32,
317
318    /// GAP-ENRICH-BACKLOG-CONVERGE: read-only mode — report queue and backlog
319    /// counts without calling the LLM or acquiring the singleton.
320    ///
321    /// Field semantics (v1.1.03 clarification):
322    /// - `scan_backlog` = candidates a fresh scan WOULD select from the database
323    ///   (REAL pending work, same WHERE predicate as the scanners).
324    /// - `queue_pending` = a COMPUTED COUNT over the sidecar queue, NOT a physical
325    ///   queue of rows to process — it stays non-zero even after a clean drain.
326    /// - `eligible_now == 0` WITH `queue_pending > 0` means COOLDOWN (rate-limit
327    ///   backoff), NOT a deadlock: items are parked on `next_retry_at`.
328    /// - `eligible_now > 0` stuck against `state: "draining"` IS a deadlock —
329    ///   stale `processing` claims hold the state. Run `--reset-stale-claims`
330    ///   to clear processing claims older than the threshold.
331    #[arg(long)]
332    pub status: bool,
333
334    /// GAP-SG-23: list every dead-letter item (status='dead') for the current
335    /// operation with its error_class, attempt count and last error message.
336    /// Read-only — no LLM, no singleton. Use it to inspect what `--requeue-dead`
337    /// would resurrect before running it.
338    #[arg(long)]
339    pub list_dead: bool,
340
341    /// GAP-SG-11/14: resurrect dead-letter items — move every `status='dead'`
342    /// row back to `pending`, zeroing `attempt`, `next_retry_at`, `error` and
343    /// `error_class`. Distinct from `--retry-failed`, which only resets the
344    /// legacy `status='failed'` rows; dead-letter rows are the terminal sink of
345    /// the v1.0.96 converge loop and are never re-selected without this flag.
346    /// No LLM call or singleton is taken — it only rewrites queue statuses.
347    #[arg(long)]
348    pub requeue_dead: bool,
349
350    /// GAP-SG-66: prune ORPHAN dead-letter rows — remove every `status='dead'`
351    /// memory row whose `item_key` (the memory name) no longer exists in the
352    /// main DB for this namespace. These are terminal "not found" failures that
353    /// `--requeue-dead` can never recover (re-processing re-fails the same way),
354    /// so they inflate `queue_dead` forever. Read-only on the main DB; deletes
355    /// only confirmed-orphan rows from the queue sidecar. Entity-keyed dead rows
356    /// are left untouched. No LLM, no singleton — like `--list-dead`.
357    #[arg(long)]
358    pub prune_dead_orphans: bool,
359
360    /// v1.1.2: prune dead ENTITY orphan rows — remove every `status='dead'`
361    /// `item_type='entity'` row from the queue sidecar. Distinct from
362    /// `--prune-dead-orphans` (memory-keyed, consults the main DB): entity dead
363    /// rows are terminal artifacts of re-extraction and have no recovery path,
364    /// so no main-DB check is needed. Required because the v1.1.1 re-embed bug
365    /// left 14680 entity-keyed dead-letter rows that the memory-scoped pruner
366    /// cannot reach. No LLM, no singleton — like `--list-dead`.
367    #[arg(long, conflicts_with = "prune_dead_orphans")]
368    pub prune_dead_entity_orphans: bool,
369
370    /// GAP-SG-16: ignore the per-item backoff cooldown (`next_retry_at`) when
371    /// selecting candidates, so items waiting on exponential backoff are
372    /// processed immediately. Use to drain a backlog whose cooldown windows are
373    /// long but the provider has recovered. Without it, `--status` reports such
374    /// items under `waiting` and they are skipped until their `next_retry_at`.
375    #[arg(long)]
376    pub ignore_backoff: bool,
377
378    /// GAP-SG-28: read-only `body-extract` — extract entities/relationships into
379    /// the graph WITHOUT rewriting (or truncating) the memory body. The default
380    /// `body-extract` restructures the stored body in place; with this flag the
381    /// body is left untouched and only graph bindings are persisted (additive,
382    /// via the same upsert path as `memory-bindings`). Ignored for every other
383    /// operation.
384    #[arg(long)]
385    pub body_extract_graph_only: bool,
386
387    /// GAP-ENRICH-BACKLOG-CONVERGE: REST concurrency for --mode openrouter
388    /// (clamp 1..=16, default 8). Distinct from the legacy --llm-parallelism.
389    #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=16))]
390    pub rest_concurrency: Option<u32>,
391
392    // -- body-enrich specific flags (GAP-18) --
393    /// Minimum output character count for body-enrich. Default: 500.
394    #[arg(long, value_name = "CHARS", default_value_t = DEFAULT_BODY_ENRICH_MIN_CHARS)]
395    pub min_output_chars: usize,
396
397    /// Maximum output character count for body-enrich. Default: 2000.
398    #[arg(long, value_name = "CHARS", default_value_t = DEFAULT_BODY_ENRICH_MAX_CHARS)]
399    pub max_output_chars: usize,
400
401    /// Check that enriched body preserves all facts from the original (LLM judge). Default: true.
402    #[arg(long, default_value_t = true)]
403    pub preserve_check: bool,
404
405    /// Path to a custom prompt template file for body-enrich.
406    #[arg(long, value_name = "PATH")]
407    pub prompt_template: Option<PathBuf>,
408
409    /// Number of parallel LLM workers (default 1 = serial).
410    /// Each worker claims items atomically from the queue DB via UPDATE...RETURNING.
411    /// Range: 1–32. For 2321 entities, --llm-parallelism 4 reduces wall time ~4×.
412    #[arg(long, default_value_t = 1, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=32))]
413    pub llm_parallelism: u32,
414
415    // -- Output / infra --
416    /// Emit NDJSON output. Always true; flag accepted for compatibility.
417    #[arg(long)]
418    pub json: bool,
419
420    /// Database path override.
421    #[arg(long)]
422    pub db: Option<String>,
423
424    /// G30: poll for the job singleton every second for up to N seconds
425    /// when another invocation holds the lock. Default: 0 (fail fast).
426    #[arg(long, value_name = "SECONDS")]
427    pub wait_job_singleton: Option<u64>,
428
429    /// G30: force acquisition of the singleton lock by removing a stale
430    /// lock file from a previously crashed invocation. Use only when you
431    /// are certain no other `enrich`/`ingest` is running.
432    #[arg(long, default_value_t = false)]
433    pub force_job_singleton: bool,
434
435    /// Select a subset of names to enrich instead of the full candidate set.
436    /// Comma-separated, e.g. `--names a,b,c`. Semantics depend on the
437    /// operation (GAP-CLI-NAMES-01): entity-keyed ops (`entity-descriptions`,
438    /// `entity-connect`, …) treat values as **entity** names; memory-keyed
439    /// ops (`memory-bindings`, `body-enrich`, …) treat values as **memory**
440    /// names. Prefer `--entity-names` / `--memory-names` for an explicit
441    /// namespace. Empty when omitted (processes all candidates).
442    ///
443    /// GAP-SG-18: also a cooldown remedy — when `--status` shows items under
444    /// `waiting` (parked on `next_retry_at` backoff), pass the exact names here
445    /// to re-enqueue and process just that subset on the next run instead of
446    /// waiting for every cooldown to elapse. REQUIRED for `--operation
447    /// augment-bindings`, which refuses to re-scan the whole namespace.
448    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
449    pub names: Vec<String>,
450
451    /// G37: read the subset of memory names from a file (one per line).
452    /// Lines starting with `#` and empty lines are ignored. Combined with
453    /// `--names` (union) when both are set.
454    #[arg(long, value_name = "PATH")]
455    pub names_file: Option<PathBuf>,
456
457    /// G35: probe the LLM provider with a 1-turn ping before processing
458    /// the batch. Aborts with a clear error if the rate-limit window is
459    /// closed (avoids burning N turns only to fail on item 1).
460    #[arg(long, default_value_t = false)]
461    pub preflight_check: bool,
462
463    /// G35: if a preflight probe or in-flight call hits the Claude rate
464    /// limit, fall back to `--fallback-mode` (typically `codex`) instead
465    /// of failing the batch. Ignored when `--mode` is already `codex`.
466    #[arg(long, value_enum)]
467    pub fallback_mode: Option<EnrichMode>,
468
469    /// G35: number of seconds before the OAuth rate-limit reset at which
470    /// the preflight probe should refuse to start. Default 300 (5 min).
471    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
472    pub rate_limit_buffer: u64,
473
474    /// G28-D: refuse to start when the 1-minute load average exceeds
475    /// `2 × ncpus` (or XDG `enrich.max_load_per_ncpu` if set).
476    /// Set to false to skip the check on contended CI runners.
477    #[arg(long, default_value_t = true)]
478    pub max_load_check: bool,
479
480    /// G28-D: when the system is saturated, abort the job after this
481    /// many consecutive HardFailure outcomes. Default 5.
482    #[arg(long, value_name = "N", default_value_t = 5)]
483    pub circuit_breaker_threshold: u32,
484
485    /// G29 Step 4: minimum trigram-Jaccard similarity between the
486    /// original body and the LLM-rewritten body for the rewrite to be
487    /// accepted. Scores below the threshold are rejected and emitted as
488    /// `EnrichItemResult::PreservationFailed`. Default 0.7 (per the G29
489    /// gap specification). Ignored when `--operation` is not
490    /// `body-enrich`.
491    #[arg(long, value_name = "FLOAT", default_value_t = 0.7)]
492    pub preserve_threshold: f64,
493
494    /// GAP-CLI-ED-03: minimum grounding coverage of an entity description
495    /// against linked memory bodies. Uses trigram coverage (`|A∩B|/|A|`),
496    /// not symmetric Jaccard, because descriptions are short. Default 0.12.
497    /// Set to 0 to use the compiled default. Only applies to
498    /// `entity-descriptions`.
499    #[arg(long, value_name = "FLOAT", default_value_t = 0.12)]
500    pub entity_description_grounding_threshold: f64,
501
502    /// GAP-CLI-ED-06: re-scan entities whose description is empty OR matches
503    /// low-quality patterns (e.g. generic "configuration file" / software
504    /// jargon). Default false (write-once for non-empty descriptions).
505    #[arg(long, default_value_t = false)]
506    pub force_redescribe: bool,
507
508    /// Wave 2 / GAP-CLI-OBS-04: sample N entities with descriptions and report
509    /// `quality_pct` / `scan_backlog_low_grounding_est` on `--status`.
510    /// Precedence: this flag > XDG `enrich.entity_description.quality_sample`
511    /// > default 50. Set 0 to disable sampling.
512    #[arg(long, value_name = "N")]
513    pub quality_sample: Option<usize>,
514
515    /// GAP-CLI-NAMES-02: explicit entity name filter (entity-descriptions,
516    /// entity-connect, …). Alias of `--names` for entity-keyed ops.
517    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
518    pub entity_names: Vec<String>,
519
520    /// GAP-CLI-NAMES-02: explicit memory name filter (memory-bindings,
521    /// body-enrich, …). Alias of `--names` for memory-keyed ops.
522    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
523    pub memory_names: Vec<String>,
524
525    /// GAP-CLI-EC-03: limit entity-connect pair scan to the subgraph of
526    /// entities linked to this memory name.
527    #[arg(long, value_name = "NAME")]
528    pub anchor_memory: Option<String>,
529
530    /// GAP-CLI-ED-05: optional domain label for entity-descriptions
531    /// (`auto` = no hint, `none` = force neutral, or free-form e.g. `fiscal`).
532    /// Precedence: this flag > XDG `enrich.entity_description.domain` > `auto`.
533    #[arg(long, value_name = "LABEL", default_value = "auto")]
534    pub entity_description_domain: String,
535
536    /// GAP-CLI-PRIO-05: cooperative yield every N processed items so hot-set
537    /// entity-descriptions can preempt long entity-connect drains. 0 disables.
538    /// XDG key: `enrich.yield_every_n_items` (default 10).
539    #[arg(long, value_name = "N")]
540    pub yield_every_n_items: Option<usize>,
541
542    /// GAP-CLI-OBS-02 / PRIO-04: run gate ops in order
543    /// memory-bindings → entity-descriptions (before entity-connect).
544    #[arg(long, default_value_t = false)]
545    pub ops_gate: bool,
546
547    /// G33 Step 3: when set, validate `--codex-model` against the
548    /// ChatGPT Pro OAuth accepted-model list and abort with a
549    /// suggestion when the value is unknown. Default true (fail fast
550    /// to avoid burning OAuth turns). Set to false to opt out.
551    #[arg(long, default_value_t = true)]
552    pub codex_model_validate: bool,
553
554    /// G33 Step 3: when set together with an invalid `--codex-model`,
555    /// automatically substitute the supplied default (e.g. `gpt-5.5`)
556    /// instead of aborting. The substitution is recorded in the NDJSON
557    /// stream as `provider_substituted: true` for traceability.
558    #[arg(long, value_name = "MODEL")]
559    pub codex_model_fallback: Option<String>,
560}
561
562impl EnrichArgs {
563    /// GAP-SG-31: resolved enrichment operation.
564    ///
565    /// `operation` is `Option` so the read-only queue inspectors
566    /// (`--status` / `--list-dead` / `--requeue-dead`) can run without it.
567    /// Write paths always carry a value (enforced by
568    /// `required_unless_present_any` at parse time); the read-only paths fall
569    /// back to `memory-bindings`, the most common queue, when it is omitted.
570    pub(crate) fn operation(&self) -> EnrichOperation {
571        self.operation
572            .clone()
573            .unwrap_or(EnrichOperation::MemoryBindings)
574    }
575
576    /// GAP-SG-31: resolved LLM provider. `mode` is `Option` for the read-only
577    /// inspectors that never call the LLM; write paths always carry a value
578    /// (enforced by `required_unless_present_any`). The fallback is only ever
579    /// observed by read-only code that does not actually invoke the provider.
580    pub(crate) fn mode(&self) -> EnrichMode {
581        self.mode.clone().unwrap_or(EnrichMode::OpenRouter)
582    }
583}