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        // R-AN-01: --print-schema exits before any work.
162        required_unless_present_any = ["status", "list_dead", "requeue_dead", "list_skipped", "requeue_skipped", "prune_dead_orphans", "prune_dead_entity_orphans", "print_schema"]
163    )]
164    pub operation: Option<EnrichOperation>,
165
166    /// LLM provider to use. Required for write operations; not needed for the
167    /// read-only queue inspectors (`--status` / `--list-dead` /
168    /// `--requeue-dead` / `--list-skipped` / `--requeue-skipped`), which never
169    /// call the LLM (GAP-SG-31).
170    ///
171    /// GAP-CLI-DRY-01 (v1.1.8): also optional for `--dry-run` (preview only).
172    #[arg(
173        long,
174        value_enum,
175        required_unless_present_any = ["status", "list_dead", "requeue_dead", "list_skipped", "requeue_skipped", "prune_dead_orphans", "prune_dead_entity_orphans", "dry_run", "print_schema"]
176    )]
177    pub mode: Option<EnrichMode>,
178
179    /// Maximum number of items to process in this run. Omit for all.
180    #[arg(long, value_name = "N")]
181    pub limit: Option<usize>,
182
183    /// v1.1.1 (P2): embedding table backfilled by `--operation re-embed`.
184    /// `memories` (default) preserves the historical behaviour; `entities`
185    /// and `chunks` rebuild `entity_embeddings` / `chunk_embeddings`; `all`
186    /// covers the three tables in one run. The scan also selects rows whose
187    /// stored `dim` diverges from the configured `--embedding-dim` (P10),
188    /// so legacy-dimension vectors are regenerated, not only missing ones.
189    /// Ignored (rejected) for every other operation.
190    #[arg(long, value_enum, value_name = "TARGET", default_value_t = ReEmbedTarget::Memories)]
191    pub target: ReEmbedTarget,
192
193    /// Preview items without calling the LLM (zero tokens consumed).
194    #[arg(long)]
195    pub dry_run: bool,
196
197    /// Namespace to operate on. Default: global.
198    #[arg(long)]
199    pub namespace: Option<String>,
200
201    // -- Provider flags (Claude) --
202    /// Path to the Claude Code binary. Default: auto-detect from PATH.
203    #[arg(long, value_name = "PATH")]
204    pub claude_binary: Option<PathBuf>,
205
206    /// Claude model to use (e.g. claude-sonnet-4-6).
207    #[arg(long, value_name = "MODEL")]
208    pub claude_model: Option<String>,
209
210    /// Timeout per item in seconds when using Claude Code. Default: 300.
211    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
212    pub claude_timeout: u64,
213
214    // -- Provider flags (Codex) --
215    /// Path to the Codex CLI binary. Default: auto-detect from PATH.
216    #[arg(long, value_name = "PATH")]
217    pub codex_binary: Option<PathBuf>,
218
219    /// Codex model to use (e.g. o4-mini).
220    #[arg(long, value_name = "MODEL")]
221    pub codex_model: Option<String>,
222
223    /// Timeout per item in seconds when using Codex. Default: 300.
224    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
225    pub codex_timeout: u64,
226
227    // -- Provider flags (OpenCode) --
228    /// Path to the OpenCode binary. Default: auto-detect from PATH.
229    #[arg(long, value_name = "PATH")]
230    pub opencode_binary: Option<PathBuf>,
231
232    /// OpenCode model to use.
233    #[arg(long, value_name = "MODEL")]
234    pub opencode_model: Option<String>,
235
236    /// Timeout per item in seconds when using OpenCode. Default: 300.
237    #[arg(
238        long,
239        value_name = "SECONDS",
240                default_value_t = 300
241    )]
242    pub opencode_timeout: u64,
243
244    // -- Provider flags (OpenRouter, v1.0.95) --
245    /// OpenRouter text model to use (REQUIRED with --mode openrouter; no default).
246    #[arg(long, value_name = "MODEL")]
247    pub openrouter_model: Option<String>,
248
249    /// OpenRouter API key. Falls back to OPENROUTER_API_KEY env or stored config.
250    #[arg(
251        long,
252        value_name = "KEY",
253                hide_env_values = true
254    )]
255    pub openrouter_api_key: Option<String>,
256
257    /// Timeout per item in seconds when using OpenRouter. Default: 600.
258    ///
259    /// GAP-SG-17: raised from 300 to 600 because dense bodies (close to the
260    /// ~32K-token context ceiling of the configured model) routinely take
261    /// longer than five minutes to generate via `deepseek-v4-flash:nitro`.
262    /// Raise it further for very large corpora; lower it for short snippets.
263    #[arg(long, value_name = "SECONDS", default_value_t = 600)]
264    pub openrouter_timeout: u64,
265
266    /// Optional OpenRouter base URL override (reserved; defaults to the public API).
267    #[arg(long, value_name = "URL")]
268    pub openrouter_base_url: Option<String>,
269
270    // -- Cost controls --
271    /// Abort when cumulative cost exceeds this USD budget (API key only; ignored for OAuth).
272    #[arg(long, value_name = "USD")]
273    pub max_cost_usd: Option<f64>,
274
275    // -- Queue controls --
276    /// Resume a previously interrupted run (skip already-done items).
277    #[arg(long)]
278    pub resume: bool,
279
280    /// Retry only items that failed in a previous run.
281    #[arg(long)]
282    pub retry_failed: bool,
283
284    /// v1.1.2 (Bug 4): reset `processing` rows whose `claimed_at` is older than
285    /// `--stale-claim-secs` (default 1800s = 30 min) back to `pending`, then exit.
286    /// Recover rows orphaned by a kill -9 mid-enrich without a full re-scan.
287    #[arg(long)]
288    pub reset_stale_claims: bool,
289
290    /// v1.1.2 (Bug 4): age threshold (seconds) for `--reset-stale-claims` and
291    /// the run-startup stale sweep. Default 1800 (30 min).
292    #[arg(long, value_name = "SECONDS", default_value_t = 1800)]
293    pub stale_claim_secs: u64,
294
295    /// GAP-ENRICH-BACKLOG-CONVERGE: loop scan→drain internally until the queue
296    /// empties of eligible items or --max-runtime elapses; removes the need for
297    /// an external bash retry loop.
298    #[arg(long)]
299    pub until_empty: bool,
300
301    /// GAP-ENRICH-BACKLOG-CONVERGE: wall-clock ceiling in seconds for
302    /// --until-empty. Defaults to 3600 when omitted.
303    #[arg(long, value_name = "SECONDS")]
304    pub max_runtime: Option<u64>,
305
306    /// GAP-ENRICH-BACKLOG-CONVERGE: attempts per item before it becomes a
307    /// dead-letter (status='dead'). Range 1..=20. Default 8.
308    ///
309    /// GAP-SG-21: the default was raised from 5 to 8 because GAP-SG-09 now
310    /// reclassifies malformed / non-JSON LLM output as TRANSIENT (retryable)
311    /// rather than a permanent HardFailure. A flaky structured-output model
312    /// (e.g. deepseek-v4-flash:nitro) may emit several bad generations in a row
313    /// even after JSON repair (GAP-SG-10) recovers most of them; the extra
314    /// attempts give the backlog room to converge before an item is parked in
315    /// the dead-letter sink. Permanent faults (ProviderError, NotFound) still
316    /// dead-letter on the first attempt regardless of this value.
317    #[arg(long, value_name = "N", default_value_t = 8, value_parser = clap::value_parser!(u32).range(1..=20))]
318    pub max_attempts: u32,
319
320    /// GAP-ENRICH-BACKLOG-CONVERGE: read-only mode — report queue and backlog
321    /// counts without calling the LLM or acquiring the singleton.
322    ///
323    /// Field semantics (v1.1.03 clarification):
324    /// - `scan_backlog` = candidates a fresh scan WOULD select from the database
325    ///   (REAL pending work, same WHERE predicate as the scanners).
326    /// - `queue_pending` = a COMPUTED COUNT over the sidecar queue, NOT a physical
327    ///   queue of rows to process — it stays non-zero even after a clean drain.
328    /// - `eligible_now == 0` WITH `queue_pending > 0` means COOLDOWN (rate-limit
329    ///   backoff), NOT a deadlock: items are parked on `next_retry_at`.
330    /// - `eligible_now > 0` stuck against `state: "draining"` IS a deadlock —
331    ///   stale `processing` claims hold the state. Run `--reset-stale-claims`
332    ///   to clear processing claims older than the threshold.
333    #[arg(long)]
334    pub status: bool,
335
336    /// GAP-SG-23: list every dead-letter item (status='dead') for the current
337    /// operation with its error_class, attempt count and last error message.
338    /// Read-only — no LLM, no singleton. Use it to inspect what `--requeue-dead`
339    /// would resurrect before running it.
340    #[arg(long)]
341    pub list_dead: bool,
342
343    /// GAP-SG-11/14: resurrect dead-letter items — move every `status='dead'`
344    /// row back to `pending`, zeroing `attempt`, `next_retry_at`, `error` and
345    /// `error_class`. Distinct from `--retry-failed`, which only resets the
346    /// legacy `status='failed'` rows; dead-letter rows are the terminal sink of
347    /// the v1.0.96 converge loop and are never re-selected without this flag.
348    /// No LLM call or singleton is taken — it only rewrites queue statuses.
349    #[arg(long)]
350    pub requeue_dead: bool,
351
352    /// GAP-SG-96 / G-PR-4: list every `status='skipped'` row for the operation
353    /// (preservation_failed / veto sink). Read-only — no LLM, no singleton.
354    #[arg(long)]
355    pub list_skipped: bool,
356
357    /// GAP-SG-96 / G-PR-3/4: resurrect skipped items — move every
358    /// `status='skipped'` row back to `pending`, zeroing attempt/backoff so a
359    /// lower grounding threshold or corpus fix can re-process them without SQL.
360    #[arg(long)]
361    pub requeue_skipped: bool,
362
363    /// GAP-SG-66: prune ORPHAN dead-letter rows — remove every `status='dead'`
364    /// memory row whose `item_key` (the memory name) no longer exists in the
365    /// main DB for this namespace. These are terminal "not found" failures that
366    /// `--requeue-dead` can never recover (re-processing re-fails the same way),
367    /// so they inflate `queue_dead` forever. Read-only on the main DB; deletes
368    /// only confirmed-orphan rows from the queue sidecar. Entity-keyed dead rows
369    /// are left untouched. No LLM, no singleton — like `--list-dead`.
370    #[arg(long)]
371    pub prune_dead_orphans: bool,
372
373    /// v1.1.2: prune dead ENTITY orphan rows — remove every `status='dead'`
374    /// `item_type='entity'` row from the queue sidecar. Distinct from
375    /// `--prune-dead-orphans` (memory-keyed, consults the main DB): entity dead
376    /// rows are terminal artifacts of re-extraction and have no recovery path,
377    /// so no main-DB check is needed. Required because the v1.1.1 re-embed bug
378    /// left 14680 entity-keyed dead-letter rows that the memory-scoped pruner
379    /// cannot reach. No LLM, no singleton — like `--list-dead`.
380    #[arg(long, conflicts_with = "prune_dead_orphans")]
381    pub prune_dead_entity_orphans: bool,
382
383    /// GAP-SG-16: ignore the per-item backoff cooldown (`next_retry_at`) when
384    /// selecting candidates, so items waiting on exponential backoff are
385    /// processed immediately. Use to drain a backlog whose cooldown windows are
386    /// long but the provider has recovered. Without it, `--status` reports such
387    /// items under `waiting` and they are skipped until their `next_retry_at`.
388    #[arg(long)]
389    pub ignore_backoff: bool,
390
391    /// GAP-SG-28: read-only `body-extract` — extract entities/relationships into
392    /// the graph WITHOUT rewriting (or truncating) the memory body. The default
393    /// `body-extract` restructures the stored body in place; with this flag the
394    /// body is left untouched and only graph bindings are persisted (additive,
395    /// via the same upsert path as `memory-bindings`). Ignored for every other
396    /// operation.
397    #[arg(long)]
398    pub body_extract_graph_only: bool,
399
400    /// GAP-ENRICH-BACKLOG-CONVERGE: REST concurrency for --mode openrouter
401    /// (clamp 1..=16, default 8). Distinct from the legacy --llm-parallelism.
402    #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=16))]
403    pub rest_concurrency: Option<u32>,
404
405    // -- body-enrich specific flags (GAP-18) --
406    /// Minimum output character count for body-enrich. Default: 500.
407    #[arg(long, value_name = "CHARS", default_value_t = DEFAULT_BODY_ENRICH_MIN_CHARS)]
408    pub min_output_chars: usize,
409
410    /// Maximum output character count for body-enrich. Default: 2000.
411    #[arg(long, value_name = "CHARS", default_value_t = DEFAULT_BODY_ENRICH_MAX_CHARS)]
412    pub max_output_chars: usize,
413
414    /// Check that enriched body preserves all facts from the original (LLM judge). Default: true.
415    #[arg(long, default_value_t = true)]
416    pub preserve_check: bool,
417
418    /// Path to a custom prompt template file for body-enrich.
419    #[arg(long, value_name = "PATH")]
420    pub prompt_template: Option<PathBuf>,
421
422    /// Number of parallel LLM workers (default 1 = serial).
423    /// Each worker claims items atomically from the queue DB via UPDATE...RETURNING.
424    /// Range: 1–32. For 2321 entities, --llm-parallelism 4 reduces wall time ~4×.
425    #[arg(long, default_value_t = 1, value_name = "N", value_parser = clap::value_parser!(u32).range(1..=32))]
426    pub llm_parallelism: u32,
427
428    // -- Output / infra --
429    /// Emit NDJSON output. Always true; flag accepted for compatibility.
430    #[arg(long)]
431    pub json: bool,
432
433    /// Database path override.
434    #[arg(long)]
435    pub db: Option<String>,
436
437    /// G30: poll for the job singleton every second for up to N seconds
438    /// when another invocation holds the lock. Default: 0 (fail fast).
439    #[arg(long, value_name = "SECONDS")]
440    pub wait_job_singleton: Option<u64>,
441
442    /// G30: force acquisition of the singleton lock by removing a stale
443    /// lock file from a previously crashed invocation. Use only when you
444    /// are certain no other `enrich`/`ingest` is running.
445    #[arg(long, default_value_t = false)]
446    pub force_job_singleton: bool,
447
448    /// Select a subset of names to enrich instead of the full candidate set.
449    /// Comma-separated, e.g. `--names a,b,c`. Semantics depend on the
450    /// operation (GAP-CLI-NAMES-01): entity-keyed ops (`entity-descriptions`,
451    /// `entity-connect`, …) treat values as **entity** names; memory-keyed
452    /// ops (`memory-bindings`, `body-enrich`, …) treat values as **memory**
453    /// names. Prefer `--entity-names` / `--memory-names` for an explicit
454    /// namespace. Empty when omitted (processes all candidates).
455    ///
456    /// GAP-SG-18: also a cooldown remedy — when `--status` shows items under
457    /// `waiting` (parked on `next_retry_at` backoff), pass the exact names here
458    /// to re-enqueue and process just that subset on the next run instead of
459    /// waiting for every cooldown to elapse. REQUIRED for `--operation
460    /// augment-bindings`, which refuses to re-scan the whole namespace.
461    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
462    pub names: Vec<String>,
463
464    /// G37: read the subset of memory names from a file (one per line).
465    /// Lines starting with `#` and empty lines are ignored. Combined with
466    /// `--names` (union) when both are set.
467    #[arg(long, value_name = "PATH")]
468    pub names_file: Option<PathBuf>,
469
470    /// G35: probe the LLM provider with a 1-turn ping before processing
471    /// the batch. Aborts with a clear error if the rate-limit window is
472    /// closed (avoids burning N turns only to fail on item 1).
473    #[arg(long, default_value_t = false)]
474    pub preflight_check: bool,
475
476    /// G35: if a preflight probe or in-flight call hits the Claude rate
477    /// limit, fall back to `--fallback-mode` (typically `codex`) instead
478    /// of failing the batch. Ignored when `--mode` is already `codex`.
479    #[arg(long, value_enum)]
480    pub fallback_mode: Option<EnrichMode>,
481
482    /// G35: number of seconds before the OAuth rate-limit reset at which
483    /// the preflight probe should refuse to start. Default 300 (5 min).
484    #[arg(long, value_name = "SECONDS", default_value_t = 300)]
485    pub rate_limit_buffer: u64,
486
487    /// G28-D: refuse to start when the 1-minute load average exceeds
488    /// `2 × ncpus` (or XDG `enrich.max_load_per_ncpu` if set).
489    /// Set to false to skip the check on contended CI runners.
490    #[arg(long, default_value_t = true)]
491    pub max_load_check: bool,
492
493    /// G28-D: when the system is saturated, abort the job after this
494    /// many consecutive HardFailure outcomes. Default 5.
495    #[arg(long, value_name = "N", default_value_t = 5)]
496    pub circuit_breaker_threshold: u32,
497
498    /// G29 Step 4: minimum trigram-Jaccard similarity between the
499    /// original body and the LLM-rewritten body for the rewrite to be
500    /// accepted. Scores below the threshold are rejected and emitted as
501    /// `EnrichItemResult::PreservationFailed`. Default 0.7 (per the G29
502    /// gap specification). Ignored when `--operation` is not
503    /// `body-enrich`.
504    #[arg(long, value_name = "FLOAT", default_value_t = 0.7)]
505    pub preserve_threshold: f64,
506
507    /// GAP-CLI-ED-03: minimum grounding coverage of an entity description
508    /// against linked memory bodies. Uses trigram coverage (`|A∩B|/|A|`),
509    /// not symmetric Jaccard, because descriptions are short. Default 0.12.
510    /// Set to 0 to use the compiled default. Only applies to
511    /// `entity-descriptions`.
512    #[arg(long, value_name = "FLOAT", default_value_t = 0.12)]
513    pub entity_description_grounding_threshold: f64,
514
515    /// GAP-CLI-ED-06: re-scan entities whose description is empty OR matches
516    /// low-quality patterns (e.g. generic "configuration file" / software
517    /// jargon). Default false (write-once for non-empty descriptions).
518    #[arg(long, default_value_t = false)]
519    pub force_redescribe: bool,
520
521    /// Wave 2 / GAP-CLI-OBS-04: sample N entities with descriptions and report
522    /// `quality_pct` / `scan_backlog_low_grounding_est` on `--status`.
523    /// Precedence: this flag > XDG `enrich.entity_description.quality_sample`
524    /// > default 50. Set 0 to disable sampling.
525    #[arg(long, value_name = "N")]
526    pub quality_sample: Option<usize>,
527
528    /// GAP-CLI-NAMES-02: explicit entity name filter (entity-descriptions,
529    /// entity-connect, …). Alias of `--names` for entity-keyed ops.
530    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
531    pub entity_names: Vec<String>,
532
533    /// GAP-CLI-NAMES-02: explicit memory name filter (memory-bindings,
534    /// body-enrich, …). Alias of `--names` for memory-keyed ops.
535    #[arg(long, value_name = "NAMES", value_delimiter = ',')]
536    pub memory_names: Vec<String>,
537
538    /// GAP-CLI-EC-03: limit entity-connect pair scan to the subgraph of
539    /// entities linked to this memory name.
540    #[arg(long, value_name = "NAME")]
541    pub anchor_memory: Option<String>,
542
543    /// GAP-CLI-ED-05: optional domain label for entity-descriptions
544    /// (`auto` = no hint, `none` = force neutral, or free-form e.g. `fiscal`).
545    /// Precedence: this flag > XDG `enrich.entity_description.domain` > `auto`.
546    #[arg(long, value_name = "LABEL", default_value = "auto")]
547    pub entity_description_domain: String,
548
549    /// GAP-CLI-PRIO-05: cooperative yield every N processed items so hot-set
550    /// entity-descriptions can preempt long entity-connect drains. 0 disables.
551    /// XDG key: `enrich.yield_every_n_items` (default 10).
552    #[arg(long, value_name = "N")]
553    pub yield_every_n_items: Option<usize>,
554
555    /// GAP-CLI-OBS-02 / PRIO-04: run gate ops in order
556    /// memory-bindings → entity-descriptions (before entity-connect).
557    #[arg(long, default_value_t = false)]
558    pub ops_gate: bool,
559
560    /// G33 Step 3: when set, validate `--codex-model` against the
561    /// ChatGPT Pro OAuth accepted-model list and abort with a
562    /// suggestion when the value is unknown. Default true (fail fast
563    /// to avoid burning OAuth turns). Set to false to opt out.
564    #[arg(long, default_value_t = true)]
565    pub codex_model_validate: bool,
566
567    /// G33 Step 3: when set together with an invalid `--codex-model`,
568    /// automatically substitute the supplied default (e.g. `gpt-5.5`)
569    /// instead of aborting. The substitution is recorded in the NDJSON
570    /// stream as `provider_substituted: true` for traceability.
571    #[arg(long, value_name = "MODEL")]
572    pub codex_model_fallback: Option<String>,
573
574    /// Emit the JSON Schema for `enrich --status` stdout and exit 0 without
575    /// opening the database or calling the LLM (agent-native R-AN-01).
576    #[arg(
577        long,
578        default_value_t = false,
579        help = "Print JSON Schema for enrich --status output and exit"
580    )]
581    pub print_schema: bool,
582}
583
584impl EnrichArgs {
585    /// GAP-SG-31: resolved enrichment operation.
586    ///
587    /// `operation` is `Option` so the read-only queue inspectors
588    /// (`--status` / `--list-dead` / `--requeue-dead`) can run without it.
589    /// Write paths always carry a value (enforced by
590    /// `required_unless_present_any` at parse time); the read-only paths fall
591    /// back to `memory-bindings`, the most common queue, when it is omitted.
592    pub(crate) fn operation(&self) -> EnrichOperation {
593        self.operation
594            .clone()
595            .unwrap_or(EnrichOperation::MemoryBindings)
596    }
597
598    /// GAP-SG-31: resolved LLM provider. `mode` is `Option` for the read-only
599    /// inspectors that never call the LLM; write paths always carry a value
600    /// (enforced by `required_unless_present_any`). The fallback is only ever
601    /// observed by read-only code that does not actually invoke the provider.
602    pub(crate) fn mode(&self) -> EnrichMode {
603        self.mode.clone().unwrap_or(EnrichMode::OpenRouter)
604    }
605}