kranz_cli/cli.rs
1//! clap derive surface of the `kranz` binary (plan §5 Phase 1-2).
2
3use clap::{Parser, Subcommand};
4use kranz_engine::event_log::LockForce;
5use std::path::PathBuf;
6
7/// Long help for `kranz msg` (plan §4.5): the queue/interrupt semantics must
8/// be documented verbatim in `--help`.
9pub const MSG_LONG_ABOUT: &str = "Queue a message for the mission's orchestrator.\n\n\
10 Messages queue and are processed between worker runs by default; the \
11 orchestrator reads them at its next decision point and records a \
12 decision. Passing --interrupt additionally aborts the current worker \
13 run (recorded as partial) before injecting the message — use it when \
14 the current work is headed the wrong way.";
15
16/// kranz — a local mission-control harness: an orchestrator plans, fresh
17/// headless-agent sessions implement features, validators judge milestones,
18/// and git is the source of truth.
19#[derive(Parser, Debug)]
20#[command(name = "kranz", version, about, author = None)]
21pub struct Cli {
22 /// Target repository root (defaults to the current directory)
23 #[arg(long, global = true, value_name = "PATH")]
24 pub repo: Option<PathBuf>,
25
26 /// Mission id (defaults to the repo's only mission; with several, the
27 /// one whose event log was updated most recently)
28 #[arg(long, global = true, value_name = "ID")]
29 pub mission: Option<String>,
30
31 /// Steal the engine lock unless its holder is provably ALIVE (a lock
32 /// whose holder is provably dead is stolen automatically, without this
33 /// flag; a live holder additionally needs --dangerously-steal-live-lock)
34 #[arg(long, global = true)]
35 pub force_lock: bool,
36
37 /// DANGEROUS: steal the engine lock even from a provably LIVE holder
38 /// (implies --force-lock). Only for a holder you have verified — e.g. via
39 /// `ps -p <pid>` — to be a zombie or foreign process: stealing from a
40 /// running kranz engine lets two engines corrupt one event log.
41 #[arg(long, global = true, hide_short_help = true)]
42 pub dangerously_steal_live_lock: bool,
43
44 /// DANGEROUS: bypass all permission gating for every agent session
45 /// (bypassPermissions). Loud, never the default.
46 #[arg(long, global = true)]
47 pub dangerously_allow_all: bool,
48
49 #[command(subcommand)]
50 pub command: Command,
51}
52
53impl Cli {
54 /// Map the two lock flags onto the engine's [`LockForce`] tier. Passing
55 /// both is fine — the strongest wins (--dangerously-steal-live-lock
56 /// implies --force-lock).
57 pub fn lock_force(&self) -> LockForce {
58 if self.dangerously_steal_live_lock {
59 LockForce::EvenIfLive
60 } else if self.force_lock {
61 LockForce::IfNotLive
62 } else {
63 LockForce::No
64 }
65 }
66}
67
68#[derive(Subcommand, Debug)]
69pub enum Command {
70 /// Print Kranz, Rust dependency and embedded-dashboard license notices
71 Licenses,
72
73 /// Prepare an existing Git worktree for its first Kranz mission.
74 ///
75 /// Scaffolds an additive runtime-ignore block, a tracked merge-gate
76 /// suite, and the tickets directory. Common Rust, Node, and Python gates
77 /// are detected; unfamiliar toolchains must supply --gate. Re-running is
78 /// safe: existing gates are validated and never replaced.
79 Init {
80 /// Unconditional validation command (repeat for multiple gates).
81 /// Overrides toolchain detection when creating a new gate suite.
82 #[arg(long = "gate", value_name = "COMMAND")]
83 gates: Vec<String>,
84
85 /// Register this canonical root in the global multi-repo host catalog.
86 #[arg(long)]
87 register: bool,
88
89 /// Host-catalog repository id (defaults to a slug of the directory).
90 #[arg(long, value_name = "ID", requires = "register")]
91 id: Option<String>,
92
93 /// Friendly name shown in the dashboard project picker.
94 #[arg(long, value_name = "NAME", requires = "register")]
95 display_name: Option<String>,
96 },
97
98 /// Create a mission and shape its plan in an interactive conversation.
99 ///
100 /// With no goal, resumes the most recent mission still in planning
101 /// (e.g. after a Claude usage-limit interruption) — the orchestrator
102 /// session is resumed with its full conversation context.
103 Plan {
104 /// The mission goal, in plain language (omit to resume planning)
105 goal: Option<String>,
106 },
107
108 /// Execute the mission loop (also crash-resumes an interrupted mission)
109 Run,
110
111 /// Show the mission tree, totals and recent decisions (read-only, no lock)
112 Status {
113 /// Dump the full MissionState as JSON instead of the tree
114 #[arg(long)]
115 json: bool,
116 },
117
118 /// Probe the native Windows AppContainer candidate without launching it.
119 ///
120 /// Loads processmodel.dll from System32 only, checks for Microsoft's
121 /// experimental process-sandbox export, and records the Windows build.
122 /// API presence never enables production enforcement by itself.
123 SandboxProbe {
124 /// Print the stable probe report as JSON.
125 #[arg(long)]
126 json: bool,
127 },
128
129 /// Prepare the Windows host for AppContainer enforcement.
130 ///
131 /// Adds only the two persistent, non-inheriting metadata ACEs required by
132 /// Windows tools on each drive root and reapplies the documented null-device
133 /// descriptor that resets at boot. Run from an elevated PowerShell;
134 /// ordinary Kranz launches verify both prerequisites read-only.
135 SandboxPrepare {
136 /// Literal local drive root to prepare (repeat for multiple drives).
137 #[arg(long = "target", value_name = "DRIVE-ROOT", required = true)]
138 targets: Vec<PathBuf>,
139 },
140
141 /// Show the flight-surgeon outcomes fold: autonomy ratio, grant-latency
142 /// distribution, per-task-class rows, context reuse, the rubber-stamp
143 /// flag, and the escalation ledger (read-only, no lock)
144 Outcomes {
145 /// Dump the full Outcomes struct as JSON instead of the text report
146 #[arg(long)]
147 json: bool,
148
149 /// Cost per merged change grouped by repo across the host catalog
150 /// (~/.kranz/config.json), beside the autonomy ratio (KRZ-329)
151 #[arg(long)]
152 all: bool,
153
154 /// Window in days for the merged-change denominator (only with
155 /// --all; default 30, inclusive at both ends)
156 #[arg(long, default_value_t = kranz_engine::outcomes::DEFAULT_MERGED_CHANGE_WINDOW_DAYS)]
157 window_days: u64,
158 },
159
160 /// Show the flight-surgeon console: autonomy ratio split by outcome,
161 /// the rubber-stamp signal (park→grant p50/p90 + sub-10s count), false
162 /// greens (completed missions with traced defect tickets), and the
163 /// escalation ledger (read-only, no lock)
164 EscalationMetrics {
165 /// Dump the full EscalationMetrics struct as JSON instead of the text
166 /// report
167 #[arg(long)]
168 json: bool,
169 },
170
171 /// Replay why a mission's unit passed from its event log alone: the gate
172 /// ladder in order (verdicts + artefact resolution against the mission
173 /// dir), each session's backend/model and prompt identity, every human
174 /// decision with its event seq, and the terminal outcome (read-only, no
175 /// lock). A cleaned runs/ degrades artefact refs to "unresolved", never
176 /// to an error.
177 Provenance {
178 /// The mission id (defaults to the global --mission / auto-selection)
179 mission_id: Option<String>,
180
181 /// Dump the full ProvenanceChain struct as JSON instead of the text
182 /// report
183 #[arg(long)]
184 json: bool,
185 },
186
187 /// Show the recorded evaluation series for one gate identity across all
188 /// missions: every gate.result with that gate name, in log order —
189 /// verdict, and the gate-supplied score + threshold where the gate
190 /// reported them (read-only, no lock). kranz records what gates report,
191 /// never normalizes it, and never derives the verdict from the score;
192 /// a boolean-only gate's series shows verdicts with no score column
193 /// (absence is the normal case, never a zero).
194 GateScores {
195 /// The gate identity (the `gate` field on gate.result events — a
196 /// defect-class name like `vacuous-filter`, a pack gate name,
197 /// `merge-gate-suite`)
198 gate: String,
199
200 /// Dump the GateScoreSeries struct as JSON instead of the text table
201 #[arg(long)]
202 json: bool,
203 },
204
205 /// Pause the mission (takes effect between worker runs)
206 Pause,
207
208 /// Resume a paused mission (takes effect between worker runs)
209 Resume,
210
211 /// Queue a message for the orchestrator
212 #[command(long_about = MSG_LONG_ABOUT)]
213 Msg {
214 /// The message text
215 text: String,
216
217 /// Abort the current worker run (recorded as partial) before
218 /// injecting the message
219 #[arg(long)]
220 interrupt: bool,
221 },
222
223 /// Request a revised plan for an active mission
224 Revise {
225 /// Mission id to revise
226 id: String,
227
228 /// Operator instructions for the revision
229 #[arg(required = true, num_args = 1.., trailing_var_arg = true)]
230 instructions: Vec<String>,
231 },
232
233 /// Approve or reject a pending plan revision
234 Revision {
235 #[command(subcommand)]
236 command: RevisionCommand,
237 },
238
239 /// Approve or deny a parked capability-grant request
240 Grant {
241 #[command(subcommand)]
242 command: GrantCommand,
243 },
244
245 /// Answer an open structured human question (the pending-decision
246 /// projection the dashboard and Slack also render)
247 Question {
248 #[command(subcommand)]
249 command: QuestionCommand,
250 },
251
252 /// List this repo's missions
253 Missions,
254
255 /// Retire a mission: mark it ABANDONED (a terminal state, not a failure).
256 ///
257 /// Appends `mission.abandoned` to the event log and stops here — git
258 /// branches, tags, and the deliverable are left untouched. A mission that
259 /// is already terminal (Complete/Failed/Abandoned) is rejected. If a live
260 /// engine still holds the mission lock, stop it first; --force-lock
261 /// steals only a lock whose holder is not provably alive, and
262 /// --dangerously-steal-live-lock steals even a live one.
263 Abandon {
264 /// The mission id (defaults to the global --mission / auto-selection)
265 id: Option<String>,
266
267 /// Why the mission is being retired (recorded on the event)
268 #[arg(long, value_name = "TEXT")]
269 reason: Option<String>,
270 },
271
272 /// Remove stale mission directories under .kranz/missions/.
273 ///
274 /// Cleans Failed, Abandoned, and abandoned-in-planning husks (Planning
275 /// with no plan.json) by default; --all additionally removes Complete
276 /// missions. A mission whose lock is held by a live engine is never
277 /// cleaned. Only mission directories are removed — git branches/tags and
278 /// the missions index.md are left intact.
279 Clean {
280 /// Skip the confirmation prompt (assume yes)
281 #[arg(long)]
282 yes: bool,
283
284 /// Also remove Complete missions (kept by default for review)
285 #[arg(long)]
286 all: bool,
287 },
288
289 /// Work with mission tickets (the backlog): list, show, new, queue
290 Ticket {
291 #[command(subcommand)]
292 command: TicketCommand,
293 },
294
295 /// Draft a plan for a ticket non-interactively (orchestrator only).
296 ///
297 /// Seeds the orchestrator with the whole ticket, requests the plan, and
298 /// either parks a committed plan.md for review (default) or, with --yes,
299 /// approves and queues it immediately. If the orchestrator needs more
300 /// context, its questions are appended to the ticket and the ticket is
301 /// flagged NEEDS-CONTEXT. Spend is bounded by the orchestrator budget cap.
302 Draft {
303 /// The ticket slug (file stem under .kranz/tickets/)
304 slug: String,
305
306 /// Approve and enqueue the plan immediately instead of parking it for
307 /// review
308 #[arg(long)]
309 yes: bool,
310
311 /// Seed the ticket's `traced-from-mission` frontmatter with this
312 /// mission id (drafting a defect ticket traced back to the mission
313 /// that shipped the defect — the flight-surgeon false-green join)
314 #[arg(long = "from-mission", value_name = "MISSION_ID")]
315 from_mission: Option<String>,
316 },
317
318 /// Decompose a complex goal into a ticket DAG (blocked-by edges).
319 ///
320 /// One planner turn proposes 1..=8 tickets as JSON; the proposed DAG
321 /// (slugs, titles, priorities, edges) is printed for review. Without
322 /// --yes nothing is written (dry-run preview). With --yes all tickets are
323 /// written at once: slug rules, unknown blockers, a missing root, or a
324 /// blocked-by cycle each refuse the whole write loudly — no partial
325 /// writes. Every emitted ticket is an ordinary ticket: draft it with
326 /// `kranz draft <slug>`, queue it with `kranz ticket queue <slug>`; deps
327 /// gating keeps a node from running before its blockers Complete.
328 Decompose {
329 /// The complex goal, in plain language
330 goal: String,
331
332 /// Write the proposed tickets (without this flag it is a dry-run preview)
333 #[arg(long, short = 'y')]
334 yes: bool,
335 },
336
337 /// Run a mission fully headlessly from a plan file (CI: plan in, exit code out).
338 ///
339 /// The file is a ticket-shaped markdown (`## Goal`, `## Context`, `##
340 /// Scoping answers`, `## Acceptance hints`). exec seeds the orchestrator
341 /// with the whole file, auto-approves the returned plan (no human), and
342 /// runs the mission to a terminal state. Events stream to stderr; the only
343 /// line on stdout is `kranz exec <id> <STATUS> cost=$X.XX branch=<b>`.
344 ///
345 /// Exit codes: 0 complete, 1 failed, 2 blocked, 3 underspecified (the
346 /// orchestrator wanted clarification a headless run cannot provide — make
347 /// the plan file self-sufficient and re-run). stdin is never read.
348 Exec {
349 /// The mission plan file (ticket-shaped markdown)
350 #[arg(short = 'f', long = "file", value_name = "MISSION.md")]
351 file: std::path::PathBuf,
352
353 /// Accepted for symmetry; headless runs always auto-approve (no-op)
354 #[arg(long)]
355 yes: bool,
356
357 /// Override maxFixCyclesPerMilestone for this run (bounds CI spend)
358 #[arg(long, value_name = "N")]
359 max_cycles: Option<u32>,
360
361 /// Create, plan, approve, and enqueue the mission without running it.
362 /// A later `kranz work` drain owns execution. This is the native-queue
363 /// handoff for headless producers such as the Gas City pack.
364 #[arg(long, conflicts_with = "push")]
365 enqueue: bool,
366
367 /// Stable producer name recorded beside an enqueued mission so its
368 /// terminal state can be returned even if another dispatcher drains
369 /// the shared queue. Must be paired with --enqueue-external-ref.
370 #[arg(
371 long,
372 value_name = "PRODUCER",
373 requires_all = ["enqueue", "enqueue_external_ref"]
374 )]
375 enqueue_source: Option<String>,
376
377 /// Producer-owned identifier recorded with --enqueue-source.
378 #[arg(
379 long,
380 value_name = "REF",
381 requires_all = ["enqueue", "enqueue_source"]
382 )]
383 enqueue_external_ref: Option<String>,
384
385 /// After a COMPLETE run, push the mission's `kranz/*` branch to this
386 /// git remote (the cloud-mission handoff: a human reviews the branch
387 /// and opens the PR). Refuses to push anything but a kranz/* ref.
388 #[arg(long, value_name = "REMOTE")]
389 push: Option<String>,
390
391 /// Override the unattended scrutiny floor: without this, exec refuses
392 /// to run a mission whose config has skipScrutiny set, since a headless
393 /// run with the scrutiny validator disabled has no adversarial reader
394 /// and can pass its own tautological acceptance (see docs/gascity.md
395 /// lesson 3). The `KRANZ_ALLOW_UNVALIDATED=1` env var is equivalent.
396 #[arg(long)]
397 allow_unvalidated: bool,
398 },
399
400 /// Show or remove an entry from the per-repo execution queue
401 Queue {
402 /// Remove the queued entry for this mission without running it. The
403 /// mission itself is retained for audit; abandon it separately when
404 /// the producer is cancelling the work rather than re-enqueueing it.
405 #[arg(long, value_name = "MISSION_ID")]
406 remove: Option<String>,
407 },
408
409 /// Report docs/knowledge notes whose verified_against paths drifted.
410 KnowledgeRefresh {
411 /// Print the report as JSON instead of text
412 #[arg(long)]
413 json: bool,
414 },
415
416 /// Scan a git diff for unwaived secret findings.
417 Scan {
418 /// Scan staged changes (`git diff --cached`)
419 #[arg(long)]
420 staged: bool,
421
422 /// Scan a git range such as `main..HEAD`
423 #[arg(long, value_name = "A..B")]
424 range: Option<String>,
425 },
426
427 /// Lint the scoped tree for banned domain vocabulary (the KRZ-314
428 /// clean-room boundary: kranz core stays domain-free, domain knowledge
429 /// ships in private packs). Policy is the committed hashed denylist
430 /// (.kranz/domain-denylist.json) plus reviewed waivers
431 /// (.kranz/domain-allowlist); see docs/domain-lint.md. Exit 0 clean, 1
432 /// on unwaived hits — each named by fingerprint + file:line, never
433 /// quoting the matched term.
434 DomainLint {
435 /// Regenerate the hashed denylist from a plaintext terms file (one
436 /// term per line, `#` comments) instead of linting. The terms file
437 /// IS the protected vocabulary: keep it out of the repo —
438 /// .kranz/domain-terms.local is gitignored for exactly this.
439 #[arg(long, value_name = "TERMS_FILE")]
440 seed_config: Option<PathBuf>,
441
442 /// Print the report as JSON instead of text
443 #[arg(long)]
444 json: bool,
445 },
446
447 /// INTERNAL: the Claude Code lifecycle-hook command the engine installs
448 /// into worker sessions (KRZ-302). Never invoked by operators — the
449 /// session's CLI pipes a PreToolUse hook payload to stdin; the guard
450 /// judges it against the engine-written spec file, records the outcome,
451 /// and exits 0 (allow) / 2 (block, stderr fed to the model) / 1 (guard
452 /// error, failing open — the engine-side sweep remains authoritative).
453 HookGuard {
454 /// The per-session hook-gate spec file the engine wrote
455 #[arg(long, value_name = "PATH")]
456 config: PathBuf,
457 },
458
459 /// INTERNAL: the cursor CLI lifecycle-hook relay the backend installs
460 /// into agent sessions (ticket `agent-hooks-status-signals`). Never
461 /// invoked by operators — the session's CLI pipes a lifecycle hook
462 /// payload to stdin; the relay maps it to a coarse signal and POSTs it
463 /// to the loopback endpoint in the engine-written spec file. Purely
464 /// observational: every failure exits 0.
465 HookStatus {
466 /// The per-session hook-status spec file the engine wrote
467 #[arg(long, value_name = "PATH")]
468 config: PathBuf,
469 },
470
471 /// Score how ready this repo is for autonomous kranz missions.
472 Ready {
473 /// Print the serializable scorecard JSON.
474 #[arg(long)]
475 json: bool,
476 /// Score every repo in the host catalog (~/.kranz/config.json) and
477 /// report the N-of-M-at-L3+ org headline.
478 #[arg(long)]
479 all: bool,
480 },
481
482 /// Drain the execution queue: run queued missions one at a time per repo
483 Work {
484 /// Process exactly one front entry (exit 0 if the repo is busy)
485 /// instead of draining until the queue is empty
486 #[arg(long)]
487 once: bool,
488
489 /// With --once, run only when this exact mission is still at the
490 /// front. A changed front is released without execution.
491 #[arg(long, value_name = "MISSION_ID", requires = "once")]
492 expect: Option<String>,
493 },
494
495 /// Serve the REST/WebSocket API (and the dashboard, if built)
496 Serve {
497 /// TCP port to bind
498 #[arg(long, default_value_t = 4560)]
499 port: u16,
500
501 /// Bind address. Default loopback; set e.g. 0.0.0.0 (LAN) or a
502 /// tailnet IP to reach the API from other devices (glasses app,
503 /// phones). Non-loopback binds require `--insecure-lan` — every
504 /// `/api` GET/POST/WS then requires a token. Reads accept the
505 /// read-only token; POSTs require the mutation token.
506 #[arg(long, default_value = "127.0.0.1")]
507 host: String,
508
509 /// Acknowledge that a non-loopback bind exposes the API on the
510 /// network. Required when `--host` is not a loopback address;
511 /// off-loopback, GETs and WS upgrades require either the read-only or
512 /// mutation token; POSTs require the mutation token. Ignored for
513 /// loopback addresses (127.0.0.0/8, ::1).
514 #[arg(long)]
515 insecure_lan: bool,
516
517 /// Require either the read-only or mutation token on `/api` GETs and
518 /// the WS upgrade on ANY bind class, including loopback. POSTs still
519 /// require the mutation token. Off-loopback binds already gate reads;
520 /// this flag forces that posture on loopback too. Still requires
521 /// `--insecure-lan` for a non-loopback bind (unchanged).
522 #[arg(long)]
523 read_auth: bool,
524
525 /// Open the dashboard in the default browser
526 #[arg(long)]
527 open: bool,
528
529 /// Directory holding the built dashboard (index.html + assets).
530 /// Default search order: `$KRANZ_DASHBOARD_DIST`, `<repo>/apps/dashboard/dist`,
531 /// installed asset dirs, the kranz source checkout used to build the
532 /// binary, then the embedded dashboard bundled into the CLI.
533 #[arg(long, value_name = "DIR")]
534 dashboard: Option<std::path::PathBuf>,
535
536 /// Pin the mutation token instead of generating one (scripting).
537 /// Every POST /api/... must carry it in the x-kranz-token header.
538 /// Falls back to $KRANZ_TOKEN when unset.
539 #[arg(long, value_name = "TOKEN")]
540 token: Option<String>,
541
542 /// Pin the read-only token instead of generating one (falls back to
543 /// $KRANZ_READ_TOKEN). Authenticates /api GETs and the WS upgrade
544 /// only — never mutations — so it is the token safe to hand to
545 /// dashboards and agents. Stored next to serve.token at
546 /// .kranz/serve.read.token (operator catalog:
547 /// `~/.kranz/serve/<endpoint>.read.token`). Must be non-empty visible
548 /// ASCII without whitespace and differ from the mutation token.
549 #[arg(long, value_name = "TOKEN")]
550 read_token: Option<String>,
551
552 /// Also run the Slack bridge (Socket Mode). Requires bot/app tokens +
553 /// channel in ~/.kranz/config.json or KRANZ_SLACK_* env vars; a no-op
554 /// with a log line when unconfigured. See docs/backlog-and-slack.md.
555 #[arg(long)]
556 slack: bool,
557 },
558
559 /// Free the mission's single-writer lock held by a running `kranz serve`.
560 ///
561 /// Resolves the selected root against the running serve's live catalog,
562 /// then POSTs to its repository-scoped release endpoint. The CLI runs in
563 /// a different process and cannot reach serve's in-memory registry
564 /// directly. The mission id comes from the global --mission /
565 /// auto-selection, same as `kranz abandon`.
566 Release {
567 /// Base URL of the running `kranz serve` instance
568 #[arg(long, default_value = "http://127.0.0.1:4560")]
569 url: String,
570
571 /// Mutation token printed by `kranz serve` (falls back to $KRANZ_TOKEN)
572 #[arg(long, value_name = "TOKEN")]
573 token: Option<String>,
574 },
575
576 /// Tail mission event logs and export OpenTelemetry spans over OTLP HTTP.
577 ///
578 /// Entirely read-side: polls each in-scope mission's events.jsonl (like
579 /// `kranz run`'s tail and the Slack bridge), folds spans from the event
580 /// timestamps, and exports one span per closed run/milestone/mission.
581 /// Runs until Ctrl-C. Honors the global --repo/--mission.
582 Otel {
583 /// OTLP HTTP traces endpoint, e.g. http://localhost:4318/v1/traces
584 #[arg(long, value_name = "URL")]
585 endpoint: String,
586
587 /// Replay each mission's full log (spans built from event
588 /// timestamps) before following live. Without this, each mission's
589 /// cursor is seeded at its current head — only spans whose opening
590 /// AND closing events arrive during the tail are exported.
591 #[arg(long)]
592 from_start: bool,
593 },
594
595 /// Export a mission's portable audit bundle (KRZ-326): a self-contained
596 /// directory an auditor can open without repo access — manifest.json
597 /// (every entry with its sha256 + source ref), a human summary.md, the
598 /// provenance chain.json, the escalation ledger and cost fold, the raw
599 /// scrubbed event log, and every resolvable artefact's bytes under
600 /// artefacts/. Missing artefact bytes are listed as unresolved manifest
601 /// entries, never omitted. The same log always yields the same bundle.
602 EvidenceBundle {
603 /// The mission id (defaults to the global --mission / auto-selection)
604 mission_id: Option<String>,
605
606 /// Directory to write the bundle into (created; must be empty).
607 /// Defaults to `./evidence-bundle-<mission-id>`
608 #[arg(long, value_name = "DIR")]
609 out: Option<PathBuf>,
610 },
611
612 /// Export validation-PASSED worker traces as fine-tuning-ready JSONL.
613 ///
614 /// Derived and regenerable: loads and folds the target mission's event
615 /// log on demand (like `status`) and prints one instruction-pair JSON
616 /// object per line to stdout — there is no persisted dataset file, so
617 /// re-running this command over an unchanged event log always yields
618 /// byte-identical output.
619 ExportTraces {
620 /// The mission id (defaults to the global --mission / auto-selection;
621 /// ignored with --all)
622 mission_id: Option<String>,
623
624 /// Aggregate passed traces across every mission under
625 /// .kranz/missions. A mission whose event log is missing or
626 /// unreadable is skipped, not fatal.
627 #[arg(long)]
628 all: bool,
629
630 /// Write the JSONL output to this path instead of stdout.
631 #[arg(long, value_name = "PATH")]
632 out: Option<PathBuf>,
633 },
634
635 /// Export the provenance-tagged training corpus as JSONL (KRZ-332).
636 ///
637 /// One tagged record per line (`source`: worker-trace / divergence /
638 /// escalation): validation-PASSED worker traces, divergence
639 /// comparison+resolution pairs, and escalation-ledger human judgments —
640 /// every record carrying the provenance refs (mission, backend/model,
641 /// run id, gate-chain seqs) that resolve it through `kranz provenance`.
642 /// Derived and regenerable like export-traces (which stays a
643 /// traces-only contract): same logs in, byte-identical JSONL out.
644 ExportCorpus {
645 /// The mission id (defaults to the global --mission / auto-selection;
646 /// ignored with --all)
647 mission_id: Option<String>,
648
649 /// Aggregate the corpus across every mission under .kranz/missions
650 /// (ids sorted). A mission whose event log is missing, unreadable,
651 /// or corrupt is skipped, not fatal.
652 #[arg(long)]
653 all: bool,
654
655 /// Write the JSONL output to this path instead of stdout.
656 #[arg(long, value_name = "PATH")]
657 out: Option<PathBuf>,
658 },
659
660 /// Inspect and edit kranz configuration (files + mid-mission changes).
661 ///
662 /// Config resolves from three layers, later winning: compiled-in defaults
663 /// <- `~/.kranz/config.json` (`--global`) <- `<repo>/.kranz/config.json` (the
664 /// default target). `show` prints the effective merge; `set`/`unset` edit
665 /// one layer file (validated before writing, other keys preserved);
666 /// `role` is the MID-MISSION path — it enqueues a config-change control
667 /// command on a running mission (the CLI twin of Slack's /kranz config),
668 /// while file edits only shape future missions.
669 Config {
670 #[command(subcommand)]
671 command: crate::config_cmd::ConfigCommand,
672 },
673
674 /// Work with kranz packs (the pack contract: deterministic gates, role
675 /// prompts, checklists, artefact stores — docs/pack-contract.md)
676 Pack {
677 #[command(subcommand)]
678 command: PackCommand,
679 },
680
681 /// Work with Flight Rules standards (KRZ-341): the schema-4 pack
682 /// standards corpus — RFCs, rules, the normalized manifest + content
683 /// digest, and the lifecycle transition lint
684 /// (docs/scoping/flight-rules-engineering-standards.md)
685 Standards {
686 #[command(subcommand)]
687 command: StandardsCommand,
688 },
689}
690
691/// Subcommands under `kranz pack` — the pack contract surface (ticket
692/// `.kranz/tickets/pack-contract-gates-prompts.md`).
693#[derive(Subcommand, Debug)]
694pub enum PackCommand {
695 /// Load and validate a pack directory fully locally, printing what it
696 /// registers (gates, prompts, checklists, artefact stores).
697 ///
698 /// A directory without a pack.toml is not a pack — the command says so
699 /// plainly and exits 0. An invalid pack fails closed: nonzero exit
700 /// naming the offending field (unknown field, wrong type, missing
701 /// required key, empty gate command, duplicate name, model-judged gate
702 /// kind, engine-reserved gate name).
703 Lint {
704 /// The pack directory containing pack.toml
705 dir: PathBuf,
706 },
707}
708
709/// Subcommands under `kranz standards` — the Flight Rules surface (ticket
710/// `.kranz/tickets/flight-rules-pack-contract.md`, KRZ-341).
711#[derive(Subcommand, Debug)]
712pub enum StandardsCommand {
713 /// Fold Flight Rules effectiveness across mission event logs and traced
714 /// defect tickets. Raw denominators are always shown; interpretive smells
715 /// remain suppressed below the documented minimum sample count.
716 Metrics {
717 /// Emit the deterministic machine-readable report
718 #[arg(long)]
719 json: bool,
720 },
721
722 /// Load a pack's `[standards]` corpus and print the normalized manifest:
723 /// every RFC and rule with its effective lifecycle status, checker
724 /// binding, and scopes, plus the sha256 content digest and the trust
725 /// posture (an external/untracked pack is advisory-only — enforced rules
726 /// are refused at load naming the remedy).
727 ///
728 /// With `--against <ref>`, the base pack is read from TRACKED BLOBS at
729 /// that git ref (never the worktree) and lifecycle transition violations
730 /// are refused: absent/draft → enforced, a semantic rule change without
731 /// a revision increment, a disappeared known rule ID, tombstone
732 /// reactivation. Exit 0 clean, 1 on load errors or refused transitions.
733 Lint {
734 /// The pack directory containing pack.toml
735 dir: PathBuf,
736
737 /// Base git ref (branch or sha) whose tracked pack bytes define the
738 /// approved lifecycle state for the transition check
739 #[arg(long, value_name = "REF")]
740 against: Option<String>,
741 },
742
743 /// Record an authorized human waiver for ONE standards failure (ticket
744 /// flight-rules-waiver-decisions, KRZ-344; design D-I) — the only
745 /// approval surface. Displays the finding, the pinned rule, the
746 /// affected paths, and the diff digest the waiver binds, then appends
747 /// `standards.waiver.approved` to the mission log. Refuses: a rule with
748 /// `waivable: false`, a rule absent from the approved pin (an expired/
749 /// retired rule or RFC is never pinned), a mismatched revision, an
750 /// absent finding, an already-waived finding, or a past expiry. The
751 /// approver is recorded honestly as `local-operator` plus this surface
752 /// — a model may request a waiver but can never approve one.
753 Waive {
754 /// The pinned rule id to except (e.g. ENG-RUST-014)
755 #[arg(long)]
756 rule: String,
757
758 /// The revision you believe you are waiving (defaults to the pinned
759 /// revision; a mismatch refuses rather than silently rebinding)
760 #[arg(long)]
761 revision: Option<u64>,
762
763 /// Waive only the latest finding with this subject (disambiguates
764 /// when several findings cite the rule)
765 #[arg(long)]
766 finding: Option<String>,
767
768 /// Why the exception is granted (recorded verbatim)
769 #[arg(long)]
770 reason: String,
771
772 /// Expiry instant, RFC 3339 (e.g. 2026-09-01T00:00:00Z) — must be
773 /// in the future; waivers are never permanent
774 #[arg(long, value_name = "RFC3339")]
775 expires: String,
776 },
777
778 /// Record the authorized human verdict for one approval-pinned
779 /// `manual-attestation` rule. The attestation binds to the current
780 /// affected paths and diff digest, so any relevant change invalidates
781 /// it. The approver is always the local operator using this CLI surface.
782 Attest {
783 /// The pinned manual-attestation rule id
784 #[arg(long)]
785 rule: String,
786
787 /// Why the operator judges the current change compliant
788 #[arg(long)]
789 reason: String,
790 },
791}
792
793#[derive(Subcommand, Debug)]
794pub enum RevisionCommand {
795 /// Approve a proposed plan revision
796 Approve {
797 /// Mission id whose pending revision should be approved
798 id: String,
799
800 /// Revision number to approve
801 revision: u32,
802 },
803
804 /// Reject a proposed plan revision
805 Reject {
806 /// Mission id whose pending revision should be rejected
807 id: String,
808
809 /// Revision number to reject
810 revision: u32,
811 },
812}
813
814#[derive(Subcommand, Debug)]
815pub enum GrantCommand {
816 /// Approve the parked grant request (extend command_grants + re-validate)
817 Approve {
818 /// Mission id whose pending grant should be approved
819 id: String,
820
821 /// The exact command to grant, quoted (must match the parked request)
822 command: String,
823 },
824
825 /// Deny the parked grant request (block the milestone, fail closed)
826 Deny {
827 /// Mission id whose pending grant should be denied
828 id: String,
829
830 /// The exact command being denied, quoted (must match the parked request)
831 command: String,
832
833 /// Reason recorded on the denial
834 #[arg(long, default_value = "denied by operator")]
835 reason: String,
836 },
837}
838
839/// Subcommands under `kranz question` — the structured human-question
840/// pending-decision projection (ticket structured-human-question-events).
841#[derive(Subcommand, Debug)]
842pub enum QuestionCommand {
843 /// List the mission's open questions (id, text, options)
844 List {
845 /// Mission id whose open questions should be listed
846 id: String,
847 },
848
849 /// Answer an open question (lands as question.answered; the answer
850 /// reaches the running mission via the user-message consult)
851 Answer {
852 /// Mission id whose open question should be answered
853 id: String,
854
855 /// The engine-minted question id (`q-<n>`, from `kranz question list`)
856 question_id: String,
857
858 /// The answer: an offered option's text verbatim, or free text
859 answer: String,
860
861 /// 0-based index of the offered option picked (omit for free text)
862 #[arg(long)]
863 option: Option<u32>,
864 },
865}
866
867/// Subcommands under `kranz ticket` — the backlog surface.
868#[derive(Subcommand, Debug)]
869pub enum TicketCommand {
870 /// List tickets with slug, priority, pipeline state, and title
871 List,
872
873 /// List tickets ready to pick up now: actionable states whose
874 /// `defer-until` (if any) has passed — deferred tickets stay hidden until
875 /// their time (D-BW-3; the clock decides at listing time, no scheduler)
876 Ready {
877 /// Also list the not-yet-ready deferred tickets, with their defer
878 /// times (operator visibility; the default listing stays clean)
879 #[arg(long)]
880 include_deferred: bool,
881 },
882
883 /// Show one ticket: parsed fields, its state, and any needs-context block
884 Show {
885 /// The ticket slug (file stem under .kranz/tickets/)
886 slug: String,
887 },
888
889 /// Scaffold a new ticket at `.kranz/tickets/<slug>.md` (refuses to overwrite)
890 New {
891 /// The ticket slug (used as the file stem)
892 slug: String,
893
894 /// The ticket title (frontmatter `title`)
895 #[arg(long)]
896 title: String,
897
898 /// An optional one-paragraph goal to pre-fill the `## Goal` section
899 #[arg(long)]
900 goal: Option<String>,
901 },
902
903 /// Import an OpenSpec change folder (`openspec/changes/<name>/`) as a
904 /// ticket. Carries the proposal and its requirements; deliberately drops
905 /// `tasks.md`, and never passes SHALL scenarios off as acceptance
906 /// criteria. One way only — the approved plan stays authoritative
907 ImportOpenspec {
908 /// Path to the OpenSpec change directory (must hold proposal.md)
909 path: PathBuf,
910
911 /// Ticket slug (defaults to the change directory's name)
912 #[arg(long)]
913 slug: Option<String>,
914 },
915
916 /// Append a note to a ticket's discussion
917 /// (`.kranz/tickets/<slug>.notes.jsonl` — append-only, committed with the
918 /// ticket; D-BW-3). Author is $KRANZ_NOTE_AUTHOR, else "operator"
919 Note {
920 /// The ticket slug
921 slug: String,
922
923 /// The note text (multiple words are joined with spaces)
924 #[arg(required = true)]
925 text: Vec<String>,
926 },
927
928 /// Print a ticket's discussion notes chronologically (append-only — there
929 /// is no edit or delete, mirroring the event log's honesty posture)
930 Notes {
931 /// The ticket slug
932 slug: String,
933 },
934
935 /// Queue a drafted (REVIEW) ticket: enqueue its mission and mark it QUEUED
936 Queue {
937 /// The ticket slug
938 slug: String,
939
940 /// The drafted mission id (auto-detected from the ticket goal if omitted)
941 #[arg(long, value_name = "ID")]
942 mission: Option<String>,
943
944 /// Queue despite unsatisfied `blocked-by` dependencies (a
945 /// blocked-by cycle is never overridable)
946 #[arg(long)]
947 force: bool,
948 },
949
950 /// Deprecated alias for `ticket queue` (kept for one release; prints a
951 /// deprecation note to stderr). Do not confuse with plan approval — see
952 /// docs/scoping/pipeline-view.md decision D-A.
953 Approve {
954 /// The ticket slug
955 slug: String,
956
957 /// The drafted mission id (auto-detected from the ticket goal if omitted)
958 #[arg(long, value_name = "ID")]
959 mission: Option<String>,
960
961 /// Approve despite unsatisfied `blocked-by` dependencies (a
962 /// blocked-by cycle is never overridable)
963 #[arg(long)]
964 force: bool,
965 },
966
967 /// Fold terminal `.status` sidecar states into committed frontmatter
968 /// `state:` keys — the one-time migration from the ticket-state-
969 /// frontmatter design, so done verdicts survive a fresh clone. Dry-run
970 /// by default; tickets with uncommitted .md edits are skipped by name
971 /// (never rewrite a file an in-flight editor or agent has open)
972 MigrateState {
973 /// Apply the fold (without this flag it only reports what it would do)
974 #[arg(long)]
975 yes: bool,
976 },
977}
978
979#[cfg(test)]
980mod tests {
981 use super::*;
982
983 #[test]
984 fn serve_parses_read_auth_flag() {
985 let cli = Cli::try_parse_from(["kranz", "serve", "--read-auth"]).unwrap();
986 match cli.command {
987 Command::Serve { read_auth, .. } => assert!(read_auth),
988 other => panic!("expected Serve, got {other:?}"),
989 }
990 }
991
992 #[test]
993 fn serve_parses_read_token_flag() {
994 let cli = Cli::try_parse_from(["kranz", "serve", "--read-token", "ro-123"]).unwrap();
995 match cli.command {
996 Command::Serve { read_token, .. } => {
997 assert_eq!(read_token.as_deref(), Some("ro-123"))
998 }
999 other => panic!("expected Serve, got {other:?}"),
1000 }
1001 }
1002
1003 #[test]
1004 fn pack_contract_pack_lint_parses_dir() {
1005 let cli = Cli::try_parse_from(["kranz", "pack", "lint", "some/dir"]).unwrap();
1006 match cli.command {
1007 Command::Pack { command } => match command {
1008 PackCommand::Lint { dir } => assert_eq!(dir, PathBuf::from("some/dir")),
1009 },
1010 other => panic!("expected Pack, got {other:?}"),
1011 }
1012 }
1013
1014 #[test]
1015 fn flight_rules_contract_standards_lint_parses_dir_and_against() {
1016 let cli = Cli::try_parse_from(["kranz", "standards", "lint", "some/dir"]).unwrap();
1017 match cli.command {
1018 Command::Standards { command } => match command {
1019 StandardsCommand::Lint { dir, against } => {
1020 assert_eq!(dir, PathBuf::from("some/dir"));
1021 assert_eq!(against, None);
1022 }
1023 other => panic!("expected Lint, got {other:?}"),
1024 },
1025 other => panic!("expected Standards, got {other:?}"),
1026 }
1027 let cli = Cli::try_parse_from([
1028 "kranz",
1029 "standards",
1030 "lint",
1031 "some/dir",
1032 "--against",
1033 "main",
1034 ])
1035 .unwrap();
1036 match cli.command {
1037 Command::Standards { command } => match command {
1038 StandardsCommand::Lint { dir, against } => {
1039 assert_eq!(dir, PathBuf::from("some/dir"));
1040 assert_eq!(against.as_deref(), Some("main"));
1041 }
1042 other => panic!("expected Lint, got {other:?}"),
1043 },
1044 other => panic!("expected Standards, got {other:?}"),
1045 }
1046 }
1047
1048 /// KRZ-344 (D-I): the waiver surface parses its full flag set; the
1049 /// approver is never a flag — the record honestly names
1050 /// `local-operator` plus the `cli` surface.
1051 #[test]
1052 fn flight_rules_waiver_standards_waive_parses_flags() {
1053 let cli = Cli::try_parse_from([
1054 "kranz",
1055 "standards",
1056 "waive",
1057 "--rule",
1058 "ZZ-FAIL-001",
1059 "--reason",
1060 "accepted risk",
1061 "--expires",
1062 "2026-09-01T00:00:00Z",
1063 ])
1064 .unwrap();
1065 match cli.command {
1066 Command::Standards { command } => match command {
1067 StandardsCommand::Waive {
1068 rule,
1069 revision,
1070 finding,
1071 reason,
1072 expires,
1073 } => {
1074 assert_eq!(rule, "ZZ-FAIL-001");
1075 assert_eq!(revision, None);
1076 assert_eq!(finding, None);
1077 assert_eq!(reason, "accepted risk");
1078 assert_eq!(expires, "2026-09-01T00:00:00Z");
1079 }
1080 other => panic!("expected Waive, got {other:?}"),
1081 },
1082 other => panic!("expected Standards, got {other:?}"),
1083 }
1084 let cli = Cli::try_parse_from([
1085 "kranz",
1086 "standards",
1087 "waive",
1088 "--rule",
1089 "ZZ-FAIL-001",
1090 "--revision",
1091 "2",
1092 "--finding",
1093 "a-1",
1094 "--reason",
1095 "accepted risk",
1096 "--expires",
1097 "2026-09-01T00:00:00Z",
1098 ])
1099 .unwrap();
1100 match cli.command {
1101 Command::Standards { command } => match command {
1102 StandardsCommand::Waive {
1103 revision, finding, ..
1104 } => {
1105 assert_eq!(revision, Some(2));
1106 assert_eq!(finding.as_deref(), Some("a-1"));
1107 }
1108 other => panic!("expected Waive, got {other:?}"),
1109 },
1110 other => panic!("expected Standards, got {other:?}"),
1111 }
1112 // --reason and --expires are required: no silent permanent or
1113 // reason-less waiver exists.
1114 assert!(
1115 Cli::try_parse_from(["kranz", "standards", "waive", "--rule", "ZZ-FAIL-001"]).is_err()
1116 );
1117 }
1118
1119 #[test]
1120 fn flight_rules_enforcement_standards_attest_parses_flags() {
1121 let cli = Cli::try_parse_from([
1122 "kranz",
1123 "standards",
1124 "attest",
1125 "--rule",
1126 "ZZ-MANUAL-001",
1127 "--reason",
1128 "reviewed the deployment evidence",
1129 ])
1130 .unwrap();
1131 match cli.command {
1132 Command::Standards { command } => match command {
1133 StandardsCommand::Attest { rule, reason } => {
1134 assert_eq!(rule, "ZZ-MANUAL-001");
1135 assert_eq!(reason, "reviewed the deployment evidence");
1136 }
1137 other => panic!("expected Attest, got {other:?}"),
1138 },
1139 other => panic!("expected Standards, got {other:?}"),
1140 }
1141 assert!(
1142 Cli::try_parse_from(["kranz", "standards", "attest", "--rule", "ZZ-MANUAL-001"])
1143 .is_err()
1144 );
1145 }
1146
1147 #[test]
1148 fn flight_rules_metrics_standards_metrics_parses_json() {
1149 let cli = Cli::try_parse_from(["kranz", "standards", "metrics", "--json"]).unwrap();
1150 match cli.command {
1151 Command::Standards {
1152 command: StandardsCommand::Metrics { json },
1153 } => assert!(json),
1154 other => panic!("expected standards metrics, got {other:?}"),
1155 }
1156 }
1157
1158 #[test]
1159 fn evidence_bundle_parses_mission_and_out() {
1160 let cli =
1161 Cli::try_parse_from(["kranz", "evidence-bundle", "m-1", "--out", "some/dir"]).unwrap();
1162 match cli.command {
1163 Command::EvidenceBundle { mission_id, out } => {
1164 assert_eq!(mission_id.as_deref(), Some("m-1"));
1165 assert_eq!(out.as_deref(), Some(PathBuf::from("some/dir").as_path()));
1166 }
1167 other => panic!("expected EvidenceBundle, got {other:?}"),
1168 }
1169
1170 // Both optional: the mission falls back to auto-selection, the output
1171 // dir to ./evidence-bundle-<mission-id>.
1172 let cli = Cli::try_parse_from(["kranz", "evidence-bundle"]).unwrap();
1173 match cli.command {
1174 Command::EvidenceBundle { mission_id, out } => {
1175 assert_eq!(mission_id, None);
1176 assert_eq!(out, None);
1177 }
1178 other => panic!("expected EvidenceBundle, got {other:?}"),
1179 }
1180 }
1181
1182 #[test]
1183 fn decompose_parses_goal_and_yes_flag() {
1184 let cli = Cli::try_parse_from(["kranz", "decompose", "build the thing", "--yes"]).unwrap();
1185 match cli.command {
1186 Command::Decompose { goal, yes } => {
1187 assert_eq!(goal, "build the thing");
1188 assert!(yes);
1189 }
1190 other => panic!("expected Decompose, got {other:?}"),
1191 }
1192
1193 let cli = Cli::try_parse_from(["kranz", "decompose", "g", "-y"]).unwrap();
1194 match cli.command {
1195 Command::Decompose { yes, .. } => assert!(yes),
1196 other => panic!("expected Decompose, got {other:?}"),
1197 }
1198
1199 // Dry-run is the default: no flag, no write.
1200 let cli = Cli::try_parse_from(["kranz", "decompose", "g"]).unwrap();
1201 match cli.command {
1202 Command::Decompose { yes, .. } => assert!(!yes),
1203 other => panic!("expected Decompose, got {other:?}"),
1204 }
1205 }
1206
1207 #[test]
1208 fn knowledge_refresh_parses_json_flag() {
1209 let cli = Cli::try_parse_from(["kranz", "knowledge-refresh"]).unwrap();
1210 match cli.command {
1211 Command::KnowledgeRefresh { json } => assert!(!json),
1212 other => panic!("expected KnowledgeRefresh, got {other:?}"),
1213 }
1214 let cli = Cli::try_parse_from(["kranz", "knowledge-refresh", "--json"]).unwrap();
1215 match cli.command {
1216 Command::KnowledgeRefresh { json } => assert!(json),
1217 other => panic!("expected KnowledgeRefresh, got {other:?}"),
1218 }
1219 }
1220
1221 #[test]
1222 fn domain_lint_command_parses_seed_config_and_json_flags() {
1223 // Bare form: lint mode, text output.
1224 let cli = Cli::try_parse_from(["kranz", "domain-lint"]).unwrap();
1225 match cli.command {
1226 Command::DomainLint { seed_config, json } => {
1227 assert_eq!(seed_config, None);
1228 assert!(!json);
1229 }
1230 other => panic!("expected DomainLint, got {other:?}"),
1231 }
1232
1233 let cli = Cli::try_parse_from(["kranz", "domain-lint", "--seed-config", "terms", "--json"])
1234 .unwrap();
1235 match cli.command {
1236 Command::DomainLint { seed_config, json } => {
1237 assert_eq!(seed_config, Some(PathBuf::from("terms")));
1238 assert!(json);
1239 }
1240 other => panic!("expected DomainLint, got {other:?}"),
1241 }
1242 }
1243
1244 /// Composition audit (ticket `config-fail-open-audit`): every CLI flag
1245 /// whose name signals a guard-weakening override must either carry the
1246 /// `dangerously-` prefix or be one of the enumerated, justified
1247 /// exceptions. A future flag that short-circuits a guard without the
1248 /// prefix trips this test until its justification is recorded — the
1249 /// naming rule's tripwire. The per-flag rationales live in
1250 /// docs/config-composition.md.
1251 #[test]
1252 fn composition_audit_guard_weakening_flags_are_dangerously_prefixed_or_enumerated() {
1253 use clap::CommandFactory;
1254
1255 fn collect_long_flags(cmd: &clap::Command, out: &mut Vec<String>) {
1256 for arg in cmd.get_arguments() {
1257 if let Some(long) = arg.get_long() {
1258 out.push(long.to_string());
1259 }
1260 }
1261 for sub in cmd.get_subcommands() {
1262 collect_long_flags(sub, out);
1263 }
1264 }
1265
1266 let mut flags = Vec::new();
1267 collect_long_flags(&Cli::command(), &mut flags);
1268 // The heuristic: names that read like they weaken a guard. Wide on
1269 // purpose — a false positive only costs a recorded justification.
1270 let suspicious = [
1271 "force",
1272 "steal",
1273 "bypass",
1274 "unvalidated",
1275 "insecure",
1276 "skip",
1277 "unsafe",
1278 "dangerous",
1279 "override",
1280 ];
1281 let mut hits: Vec<String> = flags
1282 .into_iter()
1283 .filter(|flag| suspicious.iter().any(|s| flag.contains(s)))
1284 .collect();
1285 hits.sort();
1286 hits.dedup();
1287
1288 // The documented set. `dangerously-*` members are the naming rule's
1289 // escape valve; the rest are the accepted exceptions of
1290 // docs/config-composition.md:
1291 // - force-lock: steals only from a holder PROVABLY dead (the
1292 // liveness probe is fail-closed); the live-holder bypass is the
1293 // dangerously-named flag.
1294 // - allow-unvalidated (exec): lifts only the unattended scrutiny
1295 // FLOOR — a refuse-to-run gate, not a deny list; self-describing.
1296 // - insecure-lan (serve): an acknowledgment that ADDS token
1297 // requirements on non-loopback binds; it removes nothing.
1298 // - force (ticket queue/approve): skips blocked-by READINESS only;
1299 // dependency cycles are never overridable.
1300 let expected = [
1301 "allow-unvalidated",
1302 "dangerously-allow-all",
1303 "dangerously-steal-live-lock",
1304 "force",
1305 "force-lock",
1306 "insecure-lan",
1307 ];
1308 assert_eq!(
1309 hits,
1310 expected.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
1311 "a guard-weakening flag changed: every bypass of a deny list must carry \
1312 the dangerously- prefix or a recorded exception (docs/config-composition.md)"
1313 );
1314 }
1315}