CLI Auto-Remedy Recipe Generation & Help Menu Golden Parity Guide

Comprehensive architectural manual, invariants specification, and operational guide for System Check Auto-Remedy Recipe Generation, Flag Sanitization, and CLI Help Menu Golden Parity Enforcement (pkg/system, cmd/zqk).


1. Executive Summary & Architectural Invariant Floor

The stability and predictability of autonomous agent swarms and human operators rely upon two foundational pillars in the ZQK CLI plane:

  1. Deterministic Auto-Remedy Recipes: When workspace or kernel anomalies occur (e.g. stale lock files, unseeded preconditions, corrupted object state), the diagnostic subsystem synthesizes clean, actionable recovery commands that adhere strictly to canonical CLI syntax.
  2. Help Menu Golden Parity: The CLI's interactive and machine-readable surfaces must maintain bit-for-bit parity against validated golden specifications, preventing flag drift, missing examples, or syntax ambiguities from polluting agent prompts or causing execution failures.

Under POL-DOC-001 and criteria CRIT-001, CRIT-001, and CRIT-001, this guide defines the invariants, sanitization algorithms, validation gates, and test suites governing auto-remedy recipe generation and CLI golden menu parity.

+-------------------------------------------------------------------------+
|                  Agent Swarm / CLI Command Plane                        |
|                     (zqk system check / whats-next)                     |
+-------------------------------------------------------------------------+
                                    │
                                    ▼
+-------------------------------------------------------------------------+
|                 DiagnosticsRemedyEngine (pkg/system)                    |
|                                                                         |
|  [ Anomaly Detection ]  ──► Stale Locks, Orphan PIDs, Scratch Buffers   |
|  [ Precondition Probes] ──► Policy / Persona Seeding Verification       |
|  [ Check Issue Intake ] ──► System Check Validation Issue Translation   |
|  [ Command Sanitizer  ] ──► SanitizeRecipeCommand (Positional ID Norm)  |
|  [ Syntax Validator   ] ──► ValidateRecipeCommand (Fail-Closed Safety)  |
+-------------------------------------------------------------------------+
                                    │
                                    ▼
+-------------------------------------------------------------------------+
|                  Validated Execution / Golden Surface                   |
|  • Deterministic Recipes: zqk <verb> <id> [flags] (No invalid --ids)    |
|  • Golden Menu Parity:    TestHelpMenuParity (cmd/zqk/testdata/)        |
+-------------------------------------------------------------------------+

Static Floor Invariants

  • Positional ID Invariant: Single-object CLI mutations and inspection verbs (system check, object delete, object update, object promote, object demote, object park, object get, object inspect, workflow gen-trace-pipeline) require positional argument IDs. Auto-remedy recipes must NEVER emit --ids <ID> or --ids=<ID> flags for these verbs.
  • Fail-Closed Command Validation Invariant: All recipe command strings passed to or generated by DiagnosticsRemedyEngine must satisfy ValidateRecipeCommand. Malformed flag prefixes (---), bare flags (--), empty value assignments (--field=), and unsanitized --ids flags fail closed with explicit descriptive errors.
  • Help Menu Parity Invariant: Every CLI subcommand registered in the Cobra command hierarchy must adhere to standardized formatting, contain mandatory usage examples, declare standard categorization groups, and match its committed golden representation in cmd/zqk/testdata/help_golden/.
  • Zero Ambiguity Invariant: Auto-remedy commands presented to agents or operators in console tables (zqk system check or zqk workflow whats-next) must be immediately copy-paste executable without manual correction of flag names or syntax.

2. Auto-Remedy Recipe Generation Subsystem

The auto-remedy recipe generation subsystem (pkg/system/auto_remedy.go) is responsible for converting environmental diagnostics and validation errors into structured, deterministic recovery plans (RemedyPlan).

2.1 Remedy Action Types

Each RemedyPlan encapsulates an atomic action with an assigned ActionType:

ActionType Description Execution Safety / AutoApply
ActionRemoveFile Removes stale locks or abandoned temporary scratch files within .zqk/ Safe for auto-apply (AutoApply: true), confined strictly to .zqk/
ActionTouchFile Updates timestamp or initializes required placeholder files Safe for auto-apply (AutoApply: true), confined strictly to .zqk/
ActionSeed Executes registered in-process seeders for policies and personas Safe for auto-apply when seeders are registered (AutoApply: true)
ActionKillProcess Reaps detached zombie processes under PID 1 matching project workspace Safe for auto-apply (AutoApply: true)
ActionRunCommand Formulates an actionable CLI command string for manual or runner execution Safe for auto-apply when matching whitelisted internal auto-fix commands (AutoApply: true); requires runner or callback execution

2.2 Diagnostic Generation Pipeline

When DiagnosticsRemedyEngine.Diagnose(ctx, checkResults) runs:

  1. I/O Resource Inspection: Scans .zqk/state/ and .zqk/lock/ for stale file locks (older than 15 minutes), abandoned temp files (.tmp older than 30 minutes), and orphaned worker processes detached under PID 1.
  2. Precondition Probing: Verifies that default policy objects exist in .zqk/process/policies and persona objects exist in .zqk/process/personas. If unseeded, plans are generated with commands zqk system init --force and zqk system agent-onboard.
  3. Check Issue Intake & Sanitization: Inspects systemcheck.CheckResult objects. If an issue provides a FixCommand, or if an issue is AutoFixable (such as a CAS hash mismatch), a recipe command is generated: - For issues with FixCommand: Command: SanitizeRecipeCommand(issue.FixCommand) - For AutoFixable issues: Command: SanitizeRecipeCommand("zqk system check --auto-fix " + cr.ObjectID)

3. Command Sanitization & Flag Syntax Normalization

3.1 The --ids Flag Anti-Pattern

In legacy iterations of ZQK CLI command builders (GH-947, GH-940, GH-937), certain bulk commands accepted --ids <ID1,ID2>, while single-object mutation commands expected positional arguments zqk <noun> <verb> <ID>. When validation rules or legacy templates emitted suggestions like zqk system check --auto-fix --ids OBJ-123, execution failed immediately:

Error: unknown flag: --ids
Usage:
  zqk system check [kind] [id...] [flags]

system check does not possess an --ids flag (it only supports --ids-from-file and --write-failing-ids for bulk batch re-validation). Similarly, object update, object delete, and object promote expect positional object IDs as the primary arguments.

3.2 SanitizeRecipeCommand Specification

SanitizeRecipeCommand normalizes any generated or suggested CLI command across all subcommands (system check, object delete, object update, object promote, object demote, object park, object get, object inspect, workflow gen-trace-pipeline, etc.):

func SanitizeRecipeCommand(cmd string) string {
    if cmd == "" {
        return ""
    }

    // 1. Remove empty or trailing --ids flags
    cmd = reEmptyIDsEqualed.ReplaceAllString(cmd, "")
    cmd = reEmptyIDsSpaced.ReplaceAllString(cmd, "")

    // 2. Replace '--ids <arg>' or '--ids=<arg>' with ' <arg>'
    cmd = reIDsFlagArg.ReplaceAllString(cmd, " ")

    // 3. Handle leading '--ids ' or '--ids=' if at start of string
    cmd = reLeadingIDs.ReplaceAllString(cmd, "")

    return strings.TrimSpace(cmd)
}

Transformation Invariants

Input Command Sanitized Output Command Invariant Enforced
zqk system check --auto-fix --ids OBJ-123 zqk system check --auto-fix OBJ-123 Positional ID preserved; unknown flag eliminated
zqk system check --ids OBJ-123 zqk system check OBJ-123 Direct check syntax aligned
zqk object delete --ids OBJ-456 --unlink-references zqk object delete OBJ-456 --unlink-references Positional ID preserved; subsequent flags intact
zqk object update --ids=OBJ-789 --field title=New zqk object update OBJ-789 --field title=New = syntax normalized to positional ID
zqk object promote --ids OBJ-101 zqk object promote OBJ-101 Promotion recipe standardized
zqk object demote --ids=OBJ-202 zqk object demote OBJ-202 Demotion recipe standardized
zqk object park --ids OBJ-303 zqk object park OBJ-303 Park recipe standardized
zqk system check --ids OBJ-707 zqk system check OBJ-707 Whitespace collapsed cleanly
zqk object delete --ids OBJ-1 --ids OBJ-2 zqk object delete OBJ-1 OBJ-2 Multi-ID positional arguments preserved
zqk object update OBJ-1 --field "title=A B" zqk object update OBJ-1 --field "title=A B" Quoted flag values containing spaces untouched

4. Negative Adversarial Boundary & Fail-Closed Validation

To satisfy CRIT-001, recipe commands must not only be sanitized upon generation, but also rigorously validated before execution or presentation.

4.1 ValidateRecipeCommand Enforcement

ValidateRecipeCommand parses command tokens using shell-aware quoting rules and asserts:

  1. Non-Empty Clause: Empty or whitespace-only recipe commands fail closed: recipe command cannot be empty

  2. Bare Flag Rejection: A bare double-dash (--) without a flag name is rejected: invalid bare flag '--' in recipe command "<cmd>"

  3. Malformed Flag Prefix: Flags starting with --- (e.g. ---auto-fix) are rejected: malformed flag prefix "---auto-fix" in recipe command

  4. Malformed Flag Assignment: Flags starting with --= are rejected: malformed flag argument "--=auto-fix" in recipe command

  5. Dangling Argument Guard: Flags with empty equal assignments (e.g. --field=) are rejected: flag "--field" requires a non-empty argument

  6. Unsanitized --ids Rejection: Any command retaining --ids or --ids= fails validation: recipe command contains invalid flag '--ids': positional ID arguments must be used

4.2 Safe Command Whitelist & Adversarial Boundary Verification

Under POL-DOC-001 and CRIT-001, ValidateSafeCommand(cmd, projectRoot) enforces strict negative adversarial boundaries to guarantee that only safe internal commands are auto-applied, rejecting any foreign, dangerous, or boundary-violating operations:

  1. Strict Executable Whitelist: Only invocations of the canonical product executable (zqk, paths.CLIName(), paths.CLICommandNameDefault) are permitted. Invocations of external shell interpreters (sh, bash, python), system utilities (rm, curl, wget, sudo), or unknown binaries fail closed: executable "<bin>" is not whitelisted; only zqk commands are permitted

  2. Subcommand & Operation Whitelist: - zqk system check (specifically safe internal auto-fix recipes: zqk system check --auto-fix <id>) - zqk system init (e.g. zqk system init --force) - zqk system agent-onboard - zqk system cleanup-duplicates - zqk object update (controlled metadata field corrections)

  3. Destructive Command Rejection: Mutation commands that delete or destroy objects (object delete, object destroy, object purge, rm) are explicitly rejected from automatic application: destructive command 'object delete' cannot be auto-applied

  4. Shell Injection & Metacharacter Prevention: Recipe command strings must not contain command-chaining or shell-injection metacharacters (;, &, |, >, <, `, $, \n, \r): command contains unsafe shell metacharacter "<char>"

  5. Path Traversal & Project Boundary Confinement: - Commands containing relative directory navigation (..) are rejected: argument "<arg>" contains path traversal '..' outside project boundary

  • Absolute paths targeting outside ProjectRoot are rejected: argument "<arg>" references path outside project boundary

4.3 Application Phase Execution & Runner Abstraction

In DiagnosticsRemedyEngine.Apply(ctx, plans), ActionRunCommand plans undergo rigorous gate verification before dispatch:

func (e *DiagnosticsRemedyEngine) applyRunCommand(ctx context.Context, plan RemedyPlan) RemedyOutcome {
    if plan.Command == "" {
        return RemedyOutcome{Plan: plan, Applied: false, Error: msgCommandRequires}
    }
    if err := ValidateRecipeCommand(plan.Command); err != nil {
        return RemedyOutcome{Plan: plan, Applied: false, Error: fmt.Sprintf("invalid remedy command: %v", err)}
    }
    if err := e.ValidateSafeCommand(plan.Command); err != nil {
        return RemedyOutcome{Plan: plan, Applied: false, Error: fmt.Sprintf("unsafe command rejected: %v", err)}
    }

    runner := e.CommandRunner
    if runner == nil {
        runner = e.defaultRunner()
    }

    out, err := runner(ctx, plan.Command)
    if err != nil {
        return RemedyOutcome{Plan: plan, Applied: false, Error: fmt.Sprintf("command execution failed: %v", err)}
    }

    detail := strings.TrimSpace(out)
    if detail == "" {
        detail = fmt.Sprintf("executed remedy command: %s", plan.Command)
    }
    return RemedyOutcome{
        Plan:    plan,
        Applied: true,
        Detail:  detail,
    }
}
  • Pluggable CommandRunner: Callers (such as test harnesses or orchestration environments) may inject a custom CommandRunner func(ctx context.Context, cmd string) (string, error) callback.
  • Default In-Process Fallback: When no custom runner is provided, defaultRunner() resolves bin/zqk or os.Executable(), executing the command under cmd.Dir = e.ProjectRoot.
  • Automatic Execution in system check --auto-remedy: When zqk system check --auto-remedy is invoked, diagnosed recoverable auto-fix issues (REMEDY-AUTOFIX-<id>) are automatically promoted to execution and safely applied, resolving recoverable issues end-to-end without leaving them unapplied.

5. CLI Help Menu Golden Parity Enforcement

The second pillar of CLI reliability is help menu golden parity (cmd/zqk/help_parity_test.go). CLI help outputs serve as the system contract for human operators and LLM agent prompts.

5.1 The Four Verification Pillars

When go test ./cmd/zqk -run TestHelpMenuParity executes, it builds the entire command tree and runs four comprehensive test suites:

TestHelpMenuParity
├── FormattingQuality      (Checks indentation, spacing, capitalization, line wraps)
├── HelpTextRequirements   (Enforces usage descriptions, examples, and syntax clarity)
├── GoldenFileComparison   (Bit-for-bit diff against cmd/zqk/testdata/help_golden/*.txt)
└── CommandGrouping        (Validates proper classification into Core, Workflow, System)
  1. Formatting Quality: - Ensures flags have descriptions. - Enforces consistent flag indentation and no trailing whitespace. - Verifies commands have concise Short and detailed Long documentation.
  2. Help Text Requirements: - Every subcommand must declare at least one realistic usage example matching %s <noun> <verb> .... - Examples must use valid flag names and positional argument patterns.
  3. Golden File Comparison: - Each command path (e.g. zqk_system_check__kind___id____.txt, zqk_object_delete__id___id____.txt) is compared against the pre-recorded baseline in cmd/zqk/testdata/help_golden/. - If a flag description, flag name, or example changes, the test fails closed with a diff highlighting the divergence.
  4. Command Grouping: - Root and parent commands verify that all subcommands are classified into logical groups (Core Commands, Workflow Commands, Process & Governance, System Operations).

5.2 Golden File Regeneration Runbook

When a new CLI flag is intentionally added or a command description is refined, the golden files must be updated deliberately:

# 1. Run help menu parity check to review diffs
ZQK_ALLOW_FOREGROUND_GO_TEST=1 go test -v ./cmd/zqk -run TestHelpMenuParity/GoldenFileComparison

# 2. If changes are verified and intentional, regenerate golden baselines:
ZQK_ALLOW_FOREGROUND_GO_TEST=1 UPDATE_HELP_GOLDEN=1 go test ./cmd/zqk -run TestHelpMenuParity/GoldenFileComparison

# 3. Verify git diff to inspect exact documentation updates:
git diff cmd/zqk/testdata/help_golden/

# 4. Re-run complete suite to confirm zero regressions:
ZQK_ALLOW_FOREGROUND_GO_TEST=1 go test ./cmd/zqk -run TestHelpMenuParity

6. Operational Recipes & Runbook

6.1 Inspecting Diagnosed Auto-Remedies

Run zqk system check in audit mode. If anomalies exist, recipes are displayed with copy-paste executable commands:

$ zqk system check all
...
⚡ Deterministic Remedy Recipes (Run with --auto-remedy to apply safe fixes):
  • Fix validation issue for BLI-101: Precondition missing estimated_effort
    Command: zqk object update BLI-101 --field estimated_effort=1d
  • Apply autofix for REQ-202: Integrity hash mismatch
    Command: zqk system check --auto-fix REQ-202

6.2 Applying Safe Precondition & Hygiene Remedies

Execute system check with --auto-remedy to automatically execute safe cleanup actions (stale locks, orphaned tmp files, unseeded policies/personas):

$ zqk system check all --auto-remedy
✓ Auto-Remedy applied 3 of 3 fixes:
  • Clean Stale Lock File (session.lock): removed session.lock
  • Clean Orphaned Temp File (scratch.tmp): removed scratch.tmp
  • Seed Default Policy Pack: seeded 14 policies

6.3 Verifying Implementation & Invariants in CI

Run the unit and parity verification suites:

# Verify Auto-Remedy engine and recipe sanitization
ZQK_ALLOW_FOREGROUND_GO_TEST=1 go test -v ./pkg/system -run "TestSanitizeRecipeCommand|TestValidateRecipeCommand|TestAutoRemedy"

# Verify complete pkg/system package
ZQK_ALLOW_FOREGROUND_GO_TEST=1 go test ./pkg/system/...

# Verify CLI Help Menu Golden Parity
ZQK_ALLOW_FOREGROUND_GO_TEST=1 go test ./cmd/zqk -run TestHelpMenuParity

7. Traceability Matrix

Subsystem Track: Auto-Remedy Execution & Flag Parity Subsystem

Artifact / Contract Identifier Verification Proof
Backlog Item BLI-001 Auto-Remedy Execution and Positional Flag Parity
Priority Plan PRI-001 Core Execution Work Plan
Requirement REQ-001 Automated System Check Remedy Execution and Flag Parity
Test Case TST-001 Unified Auto-Remedy Test Suite (pkg/system/auto_remedy_test.go)
Static Floor Criteria CRIT-001 TestAutoRemedy_StaticFloor_SafeCommandRecognitionAndFlagParity
Dynamic Operational Criteria CRIT-001 TestAutoRemedy_OperationalProof_AutoFixCommandExecution
Negative Boundary Criteria CRIT-001 TestAutoRemedy_NegativeBoundary_UnsafeRecipeRejection
Compliance Criteria CRIT-001 docs/guides/CLI_AUTO_REMEDY_AND_PARITY.md specification per POL-DOC-001

Subsystem Track: Recipe Generation & Help Golden Parity Baseline

Artifact / Contract Identifier Verification Proof
Backlog Item BLI-001 Lane 3: System Check Auto-Remedy Flag Alignment & CLI Menu Parity
Priority Plan PRI-001 Core Execution Work Plan
Requirement REQ-001 CLI System Check Auto-Remedy Flag Parity & Golden Menu Alignment
Static Floor Criteria CRIT-001 docs/guides/CLI_AUTO_REMEDY_AND_PARITY.md specification
Dynamic Operational Criteria CRIT-001 TestSanitizeRecipeCommand_RemovesIDsAcrossAllVerbsAndPreservesPositionalIDs, TestAutoRemedy_GeneratedRecipes_OperationalDynamicProof
Negative Boundary Criteria CRIT-001 TestValidateRecipeCommand_NegativeAdversarialBoundary
Help Parity Suite Golden Parity Gate cmd/zqk/help_parity_test.go:TestHelpMenuParity