Skip to content

Add agent-context output to cargo-orthohelp (6.2.1)#342

Merged
leynos merged 28 commits into
mainfrom
6-2-1-cargo-orthohelp-agent-context-format
Jun 11, 2026
Merged

Add agent-context output to cargo-orthohelp (6.2.1)#342
leynos merged 28 commits into
mainfrom
6-2-1-cargo-orthohelp-agent-context-format

Conversation

@lodyai

@lodyai lodyai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Summary

This pull request delivers the full implementation of roadmap item 6.2.1: "Add --format agent-context to cargo-orthohelp".

The branch contains the execution plan, production code, tests, and documentation updates.

The implementation extends cargo-orthohelp with a new --format agent-context output that emits a compact, machine-oriented JSON manifest of the CLI command tree for LLM agents. The bridge IR, existing --format ir|man|ps|all outputs, and the OrthoConfigDocs derive contract remain unchanged.

Roadmap task: 6.2.1

What ships

  • ortho_config::agent_context::AgentCommand gains summary: Option<String> (additive, serde-safe).
  • cargo_orthohelp::agent_context::bridge_ir_to_agent_context(meta: &DocMetadata, package: &str, localizer: Option<&dyn Localizer>) -> AgentContext
  • cargo_orthohelp::output::write_agent_context(out_dir: &Utf8Path, payload: &AgentContext) -> Result<Utf8PathBuf, OrthohelpError> — atomic write via PID+counter temp file and rename.
  • OutputFormat::AgentContext variant; --format agent-context accepted by clap.
  • Golden snapshot, BDD scenario, property tests (uniqueness, sort order, hidden-field omission), unit tests (concurrency, collision hard-failure).

Key design decisions

  • Positional inputs detected from existing CliMetadata; no AgentInput.kind extension.
  • --format all remains ir + man + ps; agent-context excluded until 6.2.2 locks the schema version.
  • Single non-localised <out_dir>/agent-context.json; no per-locale layout.
  • interaction_mode, mutation_effect, policy.agent_native left at schema defaults for v1.
  • Commands sorted by path, inputs by name, for snapshot stability.
  • create_new(true) + AtomicU64 counter enforces collision hard-failure and concurrent-write safety.
  • Non-Unix sync_parent_dir stub carries #[expect(clippy::unnecessary_wraps)] to preserve signature parity.

Validation

make lint && cargo test --workspace

References

  • Lody session: d8f3be20-9be8-4473-8437-c652e745cc11

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 548da25b-e2d2-4ceb-9eec-06f579842e55

📥 Commits

Reviewing files that changed from the base of the PR and between 12c19c9 and 6ce92ad.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • cargo-orthohelp/Cargo.toml
  • cargo-orthohelp/tests/compile_time.rs
  • cargo-orthohelp/tests/ui/must_use_bridge_ir.rs
  • cargo-orthohelp/tests/ui/must_use_bridge_ir.stderr
  • docs/developers-guide.md
👮 Files not reviewed due to content moderation or server errors (5)
  • docs/developers-guide.md
  • cargo-orthohelp/Cargo.toml
  • cargo-orthohelp/tests/compile_time.rs
  • cargo-orthohelp/tests/ui/must_use_bridge_ir.rs
  • cargo-orthohelp/tests/ui/must_use_bridge_ir.stderr

Summary

This pull request implements roadmap item 6.2.1 by adding a new --format agent-context output to cargo-orthohelp, enabling machine-oriented JSON manifest generation for LLM agent consumption. The implementation is captured in the new execplan document docs/execplans/6-2-1-cargo-orthohelp-agent-context-format.md, which marks the feature as complete and defines scope boundaries, invariants, and validation gates.

Key Changes

Core Implementation:

  • New public function cargo_orthohelp::agent_context::bridge_ir_to_agent_context(meta, package, localizer) -> AgentContext converts bridge documentation IR into agent-context JSON
  • New public function cargo_orthohelp::output::write_agent_context(out_dir, payload) performs atomic writes via unique PID+AtomicU64 temp filenames with create_new(true) for collision safety
  • OutputFormat::AgentContext variant added to CLI with clap acceptance for --format agent-context
  • ortho_config::agent_context::AgentCommand extended with optional summary: Option<String> field

Design Decisions:

  • Positional inputs detected from existing CLI metadata without extending IR schema
  • Agent-context excluded from --format all (awaiting schema versioning lock in 6.2.2)
  • Single non-localised output file at <out_dir>/agent-context.json
  • Commands sorted by path, inputs sorted by name for snapshot stability
  • Non-Unix platforms use const fn sync_parent_dir stub with #[expect(clippy::unnecessary_wraps)]

Testing Coverage:

  • Golden snapshot test matching expected JSON output
  • BDD scenario validating end-to-end generation
  • Property tests for uniqueness, deterministic sorting, and hidden-field omission
  • Unit tests for concurrent writes and collision hard-failure semantics
  • Compile-time tests using trybuild to verify #[must_use] enforcement

Observability & Safety:

  • Structured tracing::debug! logging at transformation and write boundaries
  • Atomic writes with hard-fail on temp-file collisions
  • JSON serialisation error mapping to OrthohelpError::IrJson

Documentation Updates

Related design documents were updated to reflect the new capability:

Review Outcomes

The extensive iterative review addressed:

  • Test helper hygiene: Introduced typed pub(super) enum JsonField with as_str() and Display to replace string-heavy function arguments
  • Deterministic testing: Added property tests for command sorting (by path) and input sorting (by name), plus hidden-field omission validation
  • Concurrency safety: Fixed temp-file creation from .create(true).truncate(true) to unique PID+counter filenames with create_new(true) hard-fail semantics
  • Observability: Added structured debug traces at IR transformation and JSON write boundaries
  • Documentation: Added API signatures to developers-guide and compile-time tests for #[must_use] verification

Validation

Passing: make lint && cargo test --workspace

Walkthrough

Implement --format agent-context end-to-end: add optional command summaries to the schema, implement an IR→AgentContext transformer producing deterministic flattened command paths and inputs, wire CLI and EN‑US localiser gating, atomically write pretty JSON to /agent-context.json with concurrency safety, and validate via unit, proptest, golden and BDD tests plus documentation.

Changes

Agent-context generation feature

Layer / File(s) Summary
Schema extension and transform core
ortho_config/src/agent_context/mod.rs, cargo-orthohelp/src/agent_context/mod.rs
Add optional summary to AgentCommand. Implement bridge_ir_to_agent_context to traverse DocMetadata, build hierarchical path (root uses bin_name fallback app_name), resolve optional trimmed en‑US summaries (suppress missing/blank/template), set canonical_verb from allowlist, map visible CLI fields into AgentInput including value-type mapping and enum recovery, and enforce deterministic sorting of commands and inputs.
Transformer validation
cargo-orthohelp/src/agent_context/proptests.rs, cargo-orthohelp/src/agent_context/tests.rs
Add proptest strategies and property tests for unique/ordered command paths, input ordering, and hidden-field omission. Add unit tests for command flattening, canonical verbs, summary rules, input mapping (flags, positional encoding via absent long, defaults, requiredness), and enum-value reconstruction. Include deterministic builders and StaticLocalizer.
CLI format support and module exports
cargo-orthohelp/src/cli.rs, cargo-orthohelp/src/lib.rs, cargo-orthohelp/src/main.rs
Add AgentContext variant to OutputFormat, update parser tests to accept --format agent-context, export agent_context module from crate root and binary, and import localiser types for EN‑US resolution and gating. Replace unconditional localisation with format-gated calls.
Output writer with concurrent file I/O
cargo-orthohelp/src/output.rs
Add write_agent_context to serialise pretty JSON to <out>/agent-context.json using PID+counter temp filenames, create_new(true) to detect collisions, write+flush+sync_all(), atomic rename and Unix parent-dir sync. Add unit tests for concurrent writes, collision hard-fail behaviour, and temp-name uniqueness.
Main pipeline integration
cargo-orthohelp/src/main.rs
Invoke generate_agent_context_if_requested(...) when --format agent-context selected; attempt EN‑US localiser (warn and skip if build fails), bridge IR to agent-context, and call write_agent_context. Gate localisation resolution to requested outputs.
End-to-end validation
tests/fixtures/orthohelp_fixture/src/lib.rs, cargo-orthohelp/tests/features/orthohelp_agent_context.feature, cargo-orthohelp/tests/golden/agent_context_tests.rs, cargo-orthohelp/tests/rstest_bdd/behaviour/
Extend fixture annotations to include enum value constraints. Add Cucumber scenario, rstest-bdd steps to run the binary and parse agent-context.json, a golden snapshot test comparing generated JSON to baseline, and scenario registration. Provide helpers to extract and assert typed JSON fields.
Design documentation and README
docs/execplans/6-2-1-cargo-orthohelp-agent-context-format.md, docs/cargo-orthohelp-design.md, docs/developers-guide.md, docs/users-guide.md, docs/roadmap.md, docs/agent-native-cli-design.md, cargo-orthohelp/README.md
Add living execplan for 6.2.1 with invariants and milestones; document --format agent-context contract, output path and JSON shape; mark roadmap item complete; update developer and user guides and README examples.

Possibly related issues

Possibly related PRs

Poem

Walk the IR, make paths align and neat,
Trim the summary so each command can speak,
Map flags and enums, order inputs true,
Write JSON atomically where builds can view,
Run tests and snapshots — ship the compact suite.

🚥 Pre-merge checks | ✅ 20
✅ Passed checks (20 passed)
Check name Status Explanation
Title check ✅ Passed The PR title directly corresponds to the main implementation: adding agent-context output to cargo-orthohelp, and includes the required roadmap reference (6.2.1).
Description check ✅ Passed The description comprehensively explains the roadmap item implementation, deliverables, key design decisions, and validation approach, directly aligned with the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Testing (Overall) ✅ Passed Tests are substantive and would catch incorrect implementations: property tests verify uniqueness/sorting/hidden-field omission across generated trees; unit tests verify command flattening, field f...
User-Facing Documentation ✅ Passed New --format agent-context functionality documented comprehensively: users-guide explains output format and use cases; README signposts features with examples; developers-guide documents public A...
Developer Documentation ✅ Passed Developer documentation fully satisfies all requirements: the developer's guide documents new APIs (bridge_ir_to_agent_context, write_agent_context, OutputFormat::AgentContext) with signatures and...
Module-Level Documentation ✅ Passed All substantive modules added carry docstrings explaining purpose and function: agent_context/mod.rs, proptests.rs, tests.rs, golden/agent_context_tests.rs, and steps_agent_context.rs all have modu...
Testing (Unit And Behavioural) ✅ Passed The PR provides comprehensive test coverage across unit, property-based, behavioural, and end-to-end tests. Unit tests verify bridge_ir_to_agent_context() edge cases (summaries, sorting, enum recov...
Testing (Property / Proof) ✅ Passed PR implements substantive property-based tests (4 invariants via proptest) and unit tests (concurrency, collision safety) that are rigorous, well-founded, and non-axiomatic. No proof-level work req...
Testing (Compile-Time / Ui) ✅ Passed Compile-time testing via trybuild is present with proper compile_fail test and expected stderr fixture. Snapshot testing via insta encodes meaningful expectations: full JSON structure with schema_v...
Unit Architecture ✅ Passed Clear separation between query (bridge_ir_to_agent_context: pure, deterministic, no I/O) and command (write_agent_context: Result-returning, explicit file I/O) paths; Localizer injected as Option;...
Domain Architecture ✅ Passed Domain transformation properly segregated: bridge_ir_to_agent_context() depends only on domain concepts (DocMetadata, package selection, localization interface) and outputs domain objects; infrastr...
Observability ✅ Passed The PR provides comprehensive observability via structured debug logging at all major operational boundaries. Logging includes contextual fields (package, path, command_count, bytes) at transformat...
Security And Privacy ✅ Passed The PR introduces no secrets, credentials, unsafe deserialization, injection risks, or sensitive data exposure. The bridge_ir_to_agent_context transformation emits only CLI metadata from DocMetadat...
Performance And Resource Use ✅ Passed PR avoids algorithmic regressions: tree walk with sorting is O(N log N) for N commands, bounded by typical CLI depth (3-5); no quadratic loops or unbounded recursion. Memory is bounded by input siz...
Concurrency And State ✅ Passed Concurrency model is explicit: process-wide AtomicU64 counter with Relaxed ordering (filesystem ops provide synchronisation), unique PID+counter temp filenames, hard-fail collision detection via cr...
Architectural Complexity And Maintainability ✅ Passed The PR introduces a focused agent-context transformation module with no unnecessary abstractions. It reuses existing Localizer trait and ortho_config types, adds no new traits/frameworks/registries...
Rust Compiler Lint Integrity ✅ Passed PR preserves compiler lint integrity: only 1 narrowly-scoped #[expect(clippy::unnecessary_wraps)] justified for non-Unix stub signature parity; no broad allow/unused suppressions; all test helpers...

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 6-2-1-cargo-orthohelp-agent-context-format

Comment @coderabbitai help to get the list of available commands and usage tips.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@sourcery-ai

sourcery-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

ExecPlan-only PR that adds a detailed execution plan document for roadmap item 6.2.1, specifying how a new --format agent-context output for cargo-orthohelp will be implemented, tested, validated, and integrated, without changing any production code yet.

Sequence diagram for cargo-orthohelp --format agent-context execution

sequenceDiagram
    actor User
    participant CLI as cargo_orthohelp::cli
    participant Main as main::run
    participant Bridge as bridge::load_or_build_ir
    participant Xform as agent_context::bridge_ir_to_agent_context
    participant Output as output::write_agent_context

    User->>CLI: parse --format agent-context
    CLI->>Main: OutputFormat::AgentContext
    Main->>Bridge: load_or_build_ir()
    Bridge-->>Main: DocMetadata
    Main->>Xform: bridge_ir_to_agent_context(DocMetadata, package, localizer)
    Xform-->>Main: AgentContext
    Main->>Output: write_agent_context(out_dir, AgentContext)
    Output-->>User: agent-context.json path
Loading

File-Level Changes

Change Details Files
Add an execution plan for implementing --format agent-context in cargo-orthohelp, defining design, constraints, milestones, and interfaces while deferring actual code changes.
  • Introduce a new ExecPlan markdown document describing the purpose and scope of adding an agent-context JSON output format for cargo-orthohelp.
  • Define hard constraints, tolerances, risks, and validation gates governing the future implementation work and its autonomy boundaries.
  • Specify the bridge-IR-to-AgentContext transform, including canonical verb mapping, positional detection rules, sorting, and value-type mapping.
  • Lay out milestones for schema updates, CLI flag addition, transform and emitter wiring, unit/property/BDD tests, documentation updates, and final gating commands.
  • Record design decisions (e.g., only additive AgentCommand.summary field, no AgentInput.kind, exclusion from --format all, single agent-context.json output) and reference related design docs and ADRs.
docs/execplans/6-2-1-cargo-orthohelp-agent-context-format.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@leynos leynos marked this pull request as ready for review June 5, 2026 23:39

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @leynos, you have reached your weekly rate limit of 2500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai coderabbitai Bot added the Roadmap label Jun 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b02c0c17e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/execplans/6-2-1-cargo-orthohelp-agent-context-format.md
Comment thread docs/execplans/6-2-1-cargo-orthohelp-agent-context-format.md
@leynos

leynos commented Jun 6, 2026

Copy link
Copy Markdown
Owner

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews paused.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Jun 6, 2026

Copy link
Copy Markdown
Owner

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response.

cargo-orthohelp/tests/rstest_bdd/behaviour/steps_agent_context.rs

Comment on file

//! Agent-context JSON step definitions for `cargo-orthohelp` behavioural tests.

❌ New issue: String Heavy Function Arguments
In this module, 46.7% of all arguments to its 8 functions are strings. The threshold for string arguments is 39.0%

@coderabbitai

This comment was marked as resolved.

@lodyai lodyai Bot force-pushed the 6-2-1-cargo-orthohelp-agent-context-format branch from 25baf04 to 5e67bc9 Compare June 6, 2026 00:30
codescene-delta-analysis[bot]

This comment was marked as outdated.

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Jun 6, 2026

Copy link
Copy Markdown
Owner

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

leynos added 11 commits June 6, 2026 19:19
Add the execution plan for roadmap item 6.2.1, "Add `--format
agent-context` to `cargo-orthohelp`". The plan covers the bridge-IR-to-
agent-context transform, the new CLI variant, the single-file emitter at
`<out_dir>/agent-context.json`, and the documentation updates.

The plan incorporates the Logisphere community-of-experts review:

- Scope the schema change to a single additive `summary: Option<String>`
  field on `AgentCommand`. Do not introduce an `AgentInput.kind` field;
  detect positional inputs from existing `CliMetadata` data instead.
- Exclude `agent-context` from `--format all` until later items lock the
  schema version and populate the semantic fields that currently default
  to `unknown`.
- Sort commands by path and inputs by name inside the transform so the
  golden snapshot stays stable without redactions.
- Narrow `proptest` coverage to a single uniqueness invariant on command
  paths.
- Document explicitly that `interaction_mode`, `mutation_effect`, and
  `policy.agent_native` are placeholders pending later roadmap items.

Plan status: DRAFT. Implementation is gated on maintainer approval.
Add the optional `AgentCommand.summary` field to the reusable agent-context schema and cover its omission, preservation, and legacy defaulting behaviour.

Record the cargo-orthohelp transform expectation for concise en-US summaries and update the active ExecPlan with Milestone 1 validation evidence.
Add `agent-context` to the supported `--format` values and cover the parser surface with a positive test, preserved invalid-value coverage, and the existing property strategy.

Update the active ExecPlan with Milestone 2 validation and CodeRabbit review evidence.
Add the bridge from documentation metadata into the compact
`AgentContext` schema, including deterministic command and input ordering.
Wire `--format agent-context` through the CLI runner and output writer so it
writes `agent-context.json` without requiring localized IR generation.

Record the Milestone 3 validation, CodeRabbit review findings, rate-limit
retries, and final clean review in the execplan.
Add focused unit coverage for command flattening, summaries, canonical verbs,
visible CLI inputs, positional inputs, and summary omission cases.
Add a proptest invariant that generated metadata trees produce unique command
paths without relying on rejection filtering.

Record the Milestone 4 gates, CodeRabbit finding, rate-limit retries, and
clean follow-up review in the execplan.
Add an rstest-bdd scenario that exercises cargo-orthohelp with
`--format agent-context` against the fixture and verifies the generated
`agent-context.json` shape.

Add a focused golden snapshot test for the fixture output so the exact
agent-context JSON remains stable across future transformer changes.

Record the Milestone 5 gate results, CodeRabbit follow-up, and snapshot
test layout decision in the execplan.
Update the user and developer guides for the implemented
`cargo orthohelp --format agent-context` flow, including the generated
`agent-context.json` path, non-localized summary rule, and positional
input convention.

Refresh the cargo-orthohelp and agent-native design notes so compact
agent-context output is no longer described as missing, while still
leaving JSON status, policy reporting, and agent-native linting as
future work.

Record the Milestone 6 validation and clean CodeRabbit review in the
execplan.
Mark roadmap item 6.2.1 and its sub-items complete now that
`cargo-orthohelp --format agent-context` is implemented, documented,
and covered by behavioural and golden tests.

Close the execplan with final outcomes, full gate results, and the clean
CodeRabbit review.
Update the completed execplan constraint so it matches the implemented
adapter boundary: an en-US Localizer may be passed only for the short
command summary used by agent command selection.

Keep the non-localized agent-context rule intact for Fluent identifiers,
long help, and any other locale-specific behaviour.
Remove an extra blank line introduced while resolving the rebase so
the Markdown gate remains clean after replaying the branch on main.
Replace stringly JSON field identifiers in the agent-context BDD
assertion helpers with a local `JsonField` enum.

Keep assertion values and step text unchanged while reducing the helper
argument string ratio that CodeScene reports.
@lodyai lodyai Bot force-pushed the 6-2-1-cargo-orthohelp-agent-context-format branch from f8a0722 to cd55ba5 Compare June 6, 2026 17:21
codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Jun 9, 2026

Copy link
Copy Markdown
Owner

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

Tighten `temp_file_open_fails_when_file_already_exists` to assert the
returned `OrthohelpError::Io` wraps a `std::io::Error` whose kind is
`ErrorKind::AlreadyExists`, matching its sibling
`temp_file_collision_fails_hard`. The previous `result.is_err()` check
would have passed on an unrelated failure (a `NotFound` or permission
error), so it did not actually prove the `create_new(true)` collision
path.
codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cargo-orthohelp/src/output.rs`:
- Around line 328-331: The test currently only checks that
open_agent_context_temp_file(...) returns Err but doesn't verify the error kind;
update the assertion in this test to mirror temp_file_collision_fails_hard by
checking that the returned io::Error kind is io::ErrorKind::AlreadyExists (e.g.,
unwrap the Err and assert the error.kind() == io::ErrorKind::AlreadyExists or
use matches!) so permission or other I/O errors won't be treated as a passing
collision case; reference open_agent_context_temp_file and the test name
temp_file_collision_fails_hard when locating the failing assertion to change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 28d7e0ac-619a-476b-adab-5fe7bfaa5b4e

📥 Commits

Reviewing files that changed from the base of the PR and between 7f92862 and f13469a.

📒 Files selected for processing (1)
  • cargo-orthohelp/src/output.rs

Comment thread cargo-orthohelp/src/output.rs Outdated
Repository owner deleted a comment from coderabbitai Bot Jun 10, 2026
@leynos

leynos commented Jun 10, 2026

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 10, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos

leynos commented Jun 11, 2026

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== cargo-orthohelp/src/output.rs ==="
cat cargo-orthohelp/src/output.rs

echo ""
echo "=== Key markers ==="
rg -n "create_new|create(true)|truncate|debug!|tracing::|collision|temp_file_open_fails|AlreadyExists|ambient_authority" cargo-orthohelp/src/output.rs

Length of output: 13858



@leynos — all eight checks are resolved.

Check Status Evidence
Unit Architecture ❌ ✅ Resolved Line 136: OpenOptions::new().write(true).create_new(true) in open_agent_context_temp_file
Security And Privacy ❌ ✅ Resolved Same
Rust Compiler Lint Integrity ❌ ✅ Resolved Same
Domain Architecture ⚠️ ✅ Resolved create_new(true) enforces hard failure on collision
Observability ⚠️ ✅ Resolved Lines 59–62: tracing::debug!(out_dir = %out_dir, "starting agent-context write") at the very first statement in write_agent_context
Testing (Unit And Behavioural) ⚠️ ✅ Resolved temp_file_collision_fails_hard (line 290) and temp_file_open_fails_when_file_already_exists (line 316) both assert ErrorKind::AlreadyExists
Testing (Property / Proof) ⚠️ ✅ Resolved Same two collision tests
Concurrency And State ⚠️ ✅ Resolved create_new(true) in place; concurrent_writes_do_not_corrupt_output and concurrent_writes_produce_unique_temp_names both present

Note: Line 37 (create(true).truncate(true)) is in write_localized_ir, the IR writer — outside the scope of all eight checks, which concern only the agent-context path.

@leynos

leynos commented Jun 11, 2026

Copy link
Copy Markdown
Owner

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

Document `agent-context` in the cargo-orthohelp README, add debug traces for
skipped generation and package-aware writer diagnostics, and record the temp
counter invariants that keep concurrent manifest writes collision-resistant.
codescene-delta-analysis[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
cargo-orthohelp/README.md (1)

19-25: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Vary sentence structure to improve readability.

Four consecutive sentences begin with "It," reducing flow. Rework the numbered list to vary structure whilst preserving clarity.

♻️ Proposed rewrite
 ## How it works
 
-1. It discovers your package and root config type from Cargo metadata or CLI
-   flags.
-2. It builds a tiny bridge binary that calls
-   `OrthoConfigDocs::get_doc_metadata()`.
-3. It resolves Fluent message IDs for each requested locale.
-4. It emits localized IR JSON, roff man pages, PowerShell external help,
-   compact agent-context JSON, or all formats.
+1. Discovers your package and root config type from Cargo metadata or CLI
+   flags.
+2. Builds a tiny bridge binary that calls
+   `OrthoConfigDocs::get_doc_metadata()`.
+3. Resolves Fluent message IDs for each requested locale.
+4. Emits localised IR JSON, roff man pages, PowerShell external help,
+   compact agent-context JSON, or all formats.

Triage: [type:docstyle]

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cargo-orthohelp/README.md` around lines 19 - 25, Rewrite the four-item
numbered list so each line varies its sentence structure while keeping the same
meaning: e.g., start items with verbs or descriptive phrases instead of
repeating "It" — reference the existing concepts like discovering package/root
config via Cargo metadata or CLI flags, building a tiny bridge binary that calls
OrthoConfigDocs::get_doc_metadata(), resolving Fluent message IDs for each
requested locale, and emitting localized IR JSON, roff man pages, PowerShell
external help, compact agent-context JSON, or all formats; keep the numbered
sequence and concise wording but vary the openings (e.g., "Discovers...",
"Builds...", "Resolves...", "Emits..." or use gerunds/clauses) to improve flow
and readability.
cargo-orthohelp/src/main.rs (1)

88-90: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Gate locale resolution behind the human-output formats.

Line 90 still resolves locales before the format gate, so any locale parsing or
selection failure aborts --format agent-context even though that artefact is
explicitly non-localized. Move locale::resolve_locales(...) behind the
Ir | Man | Ps path, or resolve it inside localize_docs_if_requested.

Patch
-    let locales = locale::resolve_locales(&args, &selection)?;
-
     let out_dir = resolve_out_dir(args.out_dir.clone(), &selection);
@@
     let should_generate_ir = matches!(args.format, OutputFormat::Ir | OutputFormat::All);
     let should_generate_man = matches!(args.format, OutputFormat::Man | OutputFormat::All);
     let should_generate_ps = matches!(args.format, OutputFormat::Ps | OutputFormat::All);
+    let should_generate_localized_docs =
+        should_generate_ir || should_generate_man || should_generate_ps;
+    let locales = if should_generate_localized_docs {
+        locale::resolve_locales(&args, &selection)?
+    } else {
+        Vec::new()
+    };
 
     generate_agent_context_if_requested(&args, &selection, &doc_metadata, &out_dir)?;
 
     let localized_docs = localize_docs_if_requested(
-        should_generate_ir || should_generate_man || should_generate_ps,
+        should_generate_localized_docs,
         &selection,
         &doc_metadata,
         &locales,
     )?;

Based on learnings: "The agent-context output must ... be non-localized" and
the PR objective to gate localisation on requested formats.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cargo-orthohelp/src/main.rs` around lines 88 - 90, Move locale resolution out
from the top-level flow so locale::resolve_locales(&args, &selection) is only
called when we will actually generate localized artifacts: compute
should_generate_ir/man/ps using matches!(args.format, OutputFormat::Ir |
OutputFormat::All) etc., combine into should_generate_localized_docs =
should_generate_ir || should_generate_man || should_generate_ps, then call
locale::resolve_locales(...) only if should_generate_localized_docs (otherwise
use an empty Vec); update the call to localize_docs_if_requested to take
should_generate_localized_docs (instead of recomputing the expression) and leave
generate_agent_context_if_requested(...) before any locale work so agent-context
remains non-localized — adjust variables around metadata::load_metadata(),
metadata::select_package(), resolve_out_dir(), doc_metadata, and
localize_docs_if_requested accordingly.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cargo-orthohelp/README.md`:
- Around line 32-33: Reword the README line that lists "PowerShell help (`ps`),
compact agent-context JSON (`agent-context`), or all formats (`all`)" to make
explicit that `--format all` does NOT include `agent-context`; update the
phrasing to something like "PowerShell help (`ps`), compact agent-context JSON
(`agent-context`), or all output formats (`all`) — note: `--format all`
currently excludes `agent-context` until schema versioning is locked" so readers
know `agent-context` is intentionally excluded from `--format all`.

---

Outside diff comments:
In `@cargo-orthohelp/README.md`:
- Around line 19-25: Rewrite the four-item numbered list so each line varies its
sentence structure while keeping the same meaning: e.g., start items with verbs
or descriptive phrases instead of repeating "It" — reference the existing
concepts like discovering package/root config via Cargo metadata or CLI flags,
building a tiny bridge binary that calls OrthoConfigDocs::get_doc_metadata(),
resolving Fluent message IDs for each requested locale, and emitting localized
IR JSON, roff man pages, PowerShell external help, compact agent-context JSON,
or all formats; keep the numbered sequence and concise wording but vary the
openings (e.g., "Discovers...", "Builds...", "Resolves...", "Emits..." or use
gerunds/clauses) to improve flow and readability.

In `@cargo-orthohelp/src/main.rs`:
- Around line 88-90: Move locale resolution out from the top-level flow so
locale::resolve_locales(&args, &selection) is only called when we will actually
generate localized artifacts: compute should_generate_ir/man/ps using
matches!(args.format, OutputFormat::Ir | OutputFormat::All) etc., combine into
should_generate_localized_docs = should_generate_ir || should_generate_man ||
should_generate_ps, then call locale::resolve_locales(...) only if
should_generate_localized_docs (otherwise use an empty Vec); update the call to
localize_docs_if_requested to take should_generate_localized_docs (instead of
recomputing the expression) and leave generate_agent_context_if_requested(...)
before any locale work so agent-context remains non-localized — adjust variables
around metadata::load_metadata(), metadata::select_package(), resolve_out_dir(),
doc_metadata, and localize_docs_if_requested accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6fa68212-1663-4caa-8646-7f4dcfc1bd96

📥 Commits

Reviewing files that changed from the base of the PR and between f13469a and 092e1b8.

📒 Files selected for processing (3)
  • cargo-orthohelp/README.md
  • cargo-orthohelp/src/main.rs
  • cargo-orthohelp/src/output.rs

Comment thread cargo-orthohelp/README.md Outdated
Document that `--format all` excludes `agent-context` while the schema is
still being locked. Defer locale resolution until a localized output format is
actually requested so agent-context-only generation remains non-localized.
codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Jun 11, 2026

Copy link
Copy Markdown
Owner

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews resumed.

@leynos

This comment was marked as resolved.

@coderabbitai

This comment was marked as resolved.

Add the 6.2.1 public API signatures to the developer guide so the stable
agent-context surface is discoverable from the documentation. Add a trybuild
compile-fail test that records the compiler enforcement path for ignored
`#[must_use]` return values.
@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== docs/developers-guide.md (agent-context section) ==="
grep -n "bridge_ir_to_agent_context\|write_agent_context\|OutputFormat::AgentContext\|Public API\|### Public API" docs/developers-guide.md | head -40

echo ""
echo "=== docs/developers-guide.md lines around agent-context section ==="
grep -n "agent.context\|Generating agent" docs/developers-guide.md | head -20

echo ""
echo "=== cargo-orthohelp/Cargo.toml dev-dependencies ==="
grep -n "trybuild" cargo-orthohelp/Cargo.toml || echo "trybuild absent"

echo ""
echo "=== trybuild tests ==="
fd -e rs . cargo-orthohelp/tests/ 2>/dev/null | sort | head -30

echo ""
echo "=== cargo-orthohelp/tests/compile_time.rs ==="
cat cargo-orthohelp/tests/compile_time.rs 2>/dev/null || echo "FILE NOT FOUND"

echo ""
echo "=== cargo-orthohelp/tests/ui/ ==="
ls cargo-orthohelp/tests/ui/ 2>/dev/null || echo "DIR NOT FOUND"

echo ""
echo "=== PR description ==="
gh pr view 342 --json title,body --jq '.body' | head -40

Length of output: 6035



@leynos — all three checks are resolved.

Check Status Evidence
Developer Documentation ⚠️ ✅ Resolved docs/developers-guide.md line 128: ### Public API subsection present with explicit signatures for bridge_ir_to_agent_context, write_agent_context, and OutputFormat::AgentContext
Testing (Compile-Time / UI) ⚠️ ✅ Resolved trybuild = "1" in cargo-orthohelp/Cargo.toml line 42; tests/compile_time.rs contains must_use_compile_tests(); tests/ui/must_use_bridge_ir.rs and tests/ui/must_use_bridge_ir.stderr both present
Architectural Complexity ⚠️ ✅ Resolved PR description updated to accurately reflect the full implementation scope; AgentContextWriteTarget is correctly retained as it underpins the concurrency and collision-failure tests resolved in earlier cycles

No further work is required on this PR.

@leynos leynos merged commit fc420c7 into main Jun 11, 2026
6 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 15, 2026
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant