Skip to content

fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) - #182

Merged
dan-petty merged 2 commits into
release/v0.2.17from
fix/183-k8s-stack-deploy-conflicts
Sep 12, 2026
Merged

dan-petty merged 2 commits into
release/v0.2.17from
fix/183-k8s-stack-deploy-conflicts

Conversation

@dan-petty

Copy link
Copy Markdown
Owner

Description

Resolves five failure modes encountered when deploying the Kubernetes stack via devops k8s deploy-stack --stack all:

  1. Helm Server-Side Apply Conflicts: Add --force-conflicts to helm upgrade --install in stack_lifecycle.py to allow Server-Side Apply to adopt fields previously adjusted by kubectl patch or kubectl set.
  2. Loki Template Validation: Configure read.replicas: 0, write.replicas: 0, and backend.replicas: 0 in k8s/logging/loki-values.yaml for SingleBinary deploymentMode.
  3. Fluent-Bit PodSecurity: Update namespace logging PodSecurity standard to privileged in k8s/namespaces.yaml to allow daemonset hostPath volume mounts.
  4. Fluent-Bit Output Plugin: Change output plugin in k8s/logging/fluent-bit-values.yaml from obsolete grafana-loki to built-in loki.
  5. Qdrant Permissions: Set updateVolumeFsOwnership: false in k8s/llm/values-qdrant.yaml to disable the unprivileged root chown initContainer in favor of native Kubernetes fsGroup: 1000.

Closes #183

Verification

  • uv run pytest tests/test_k8s.py: 31 passed
  • devops scan complexity: 0 violations across 185 modules
  • uv run devops ci: 10 of 10 quality gates passed (94.1% coverage)
  • Live cluster verification: All pods across namespaces argocd, monitoring, otel, llm, logging, and squid are healthy and Running.

Copilot AI lite review requested due to automatic review settings September 12, 2026 21:40

Copilot AI 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.

🟡 Changes recommended

Unresolved Helm compatibility, security, logging-label, and test-coverage concerns remain.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

This pull request fixes Kubernetes stack deployment failures involving Helm SSA, Loki, Fluent Bit, PodSecurity, and Qdrant permissions.

Changes:

  • Adds Helm conflict forcing and deployment assertions.
  • Updates Loki, Fluent Bit, namespace security, and Qdrant configuration.
  • Adds task tracking documentation.
File summaries
File Summary
tests/test_k8s.py Tests deployment and manifest contracts.
src/devops_cli/commands/k8s/stack_lifecycle.py Adds --force-conflicts to Helm upgrades.
k8s/namespaces.yaml Updates logging namespace PodSecurity labels.
k8s/logging/loki-values.yaml Configures SingleBinary replicas.
k8s/logging/fluent-bit-values.yaml Switches to the Loki output plugin.
k8s/llm/values-qdrant.yaml Disables volume ownership initialization.
docs/agent/tasks/task-183-stack-deploy-conflicts.md Documents implementation and verification.
docs/agent/task.md Registers the task in the index.
Review details

Suppressed comments (5)

docs/agent/task.md:26

  • The index repeats the stale TBD/In Progress state, so the repository's discoverability summary disagrees with the current PR and task file. Link PR #182 and set this row to In Review.
| [#183](https://github.com/dan-petty/devops-cli/issues/183) | TBD | Resolve Helm Stack Deploy SSA Conflicts, Loki Validation, and PodSecurity Failures | `In Progress` | [`task-183-stack-deploy-conflicts.md`](tasks/task-183-stack-deploy-conflicts.md) |

docs/agent/tasks/task-183-stack-deploy-conflicts.md:5

  • The tracking metadata is stale: this is PR #182 and GitHub shows it is ready for review rather than a draft, so PR: TBD and Status: In Progress break the documented task lifecycle and bidirectional index. Update these fields before merging.
**PR**: TBD (Draft PR targeting `release/v0.2.17`)
**Status**: In Progress

k8s/logging/fluent-bit-values.yaml:52

  • This removes the namespace, pod, and container Loki labels that the previous output emitted, leaving only job. auto_kubernetes_labels maps Kubernetes pod labels; it does not create those metadata labels, so LogQL filtering and the Grafana trace-to-log mapping configured with pod and namespace (k8s/monitoring/prometheus-values.yaml:68-70) will lose their correlation fields. Keep the metadata labels using the Loki plugin's record-accessor/LabelKeys equivalent while changing the plugin name.
        labels job=fluent-bit
        auto_kubernetes_labels on

tests/test_k8s.py:911

  • This test only checks the enforce label, although the patch also changes the namespace's warn and audit labels. A partial or drifted manifest could therefore pass while those two changed security contracts are wrong; assert all three labels explicitly.
    assert logging_ns["metadata"]["labels"]["pod-security.kubernetes.io/enforce"] == "privileged"

tests/test_k8s.py:926

  • The output contract changes both the plugin and the label configuration, but these assertions only verify the plugin name and removal of the obsolete name. A regression could drop labels job=fluent-bit or auto_kubernetes_labels on while this test still passes; assert the active label configuration as well.
    assert "Name loki" in fb_values["config"]["outputs"]
    assert "grafana-loki" not in fb_values["config"]["outputs"]
  • Files reviewed: 8/8 changed files
  • Comments generated: 3
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread k8s/namespaces.yaml Resolved
Comment thread tests/test_k8s.py Resolved
@dan-petty
dan-petty merged commit 45979c9 into release/v0.2.17 Sep 12, 2026
4 checks passed
@dan-petty
dan-petty deleted the fix/183-k8s-stack-deploy-conflicts branch September 12, 2026 22:32
dan-petty added a commit that referenced this pull request Sep 14, 2026
* feat(release): v0.2.17

* feat(sandbox): protocol-agnostic endpoint readiness and health probing subsystem (#107)

Closes #107

* docs(agent): reconcile task 107 tracking to done (#107)

* feat(telemetry): cgroup v2 metrics collection and prometheus application scraping (#108)

Closes #108

* docs(agent): reconcile task 108 to done following PR #164 merge

* docs(agent): require draft pull requests for in-progress work (#165) (#166)

* docs(agent): require draft pull requests for in-progress work (#165)

* docs(agent): align lifecycle definitions and update task index for PR #166

* fix(sandbox): resolve cpu delta sampling, ssrf boundaries, and cgroup fallback (#168)

* fix(sandbox): remediate pr 164 review findings on sandbox metrics collection (#167)

* test(sandbox): normalize whitespace in help assertion for variable terminal widths

* test(sandbox): assert help option text without border wrapping sensitivity

* fix(sandbox): address pr 168 review comments on url sanitization and telemetry contracts (#167)

* fix(sandbox): resolve pr 168 review comments on cpu delta sampling, ssrf boundaries, and cgroup fallback (#167)

* test(sandbox): remove redundant comment header in metrics tests

* feat(pr): monitor pr checks, copilot reviews, and review threads (#170) (#171)

* feat(github): automated pr monitoring and copilot review verification (#170)

* fix(pr): resolve copilot review findings and enforce 5m/60s monitoring standards (#170)

* feat(k8s): configurable k8s context setting and conditional minikube autostart (#172) (#174)

* feat(k8s): configurable k8s context setting and conditional minikube autostart (#172)

* docs(k8s): document minikube devcontainer lifecycle and external cluster configurations (#172)

* fix(k8s): resolve copilot review findings for context validation and autostart (#172)

* test(k8s): update qdrant secret lifecycle assertion for effective context flag (#172)

* fix(github): project field options sync, complete pagination, generic owner resolution, and mock hostname standardization (#175) (#173)

- Resolve automated GitHub Projects bot resetting status by auto-provisioning missing single-select options (e.g. 'In Review')
- Implement complete pagination across projectsV2 items, issues, and PR endpoints
- Resolve project owner dynamically via gh api user login without hardcoded usernames
- Display draft PR warnings cleanly in monitor exit handler
- Standardize all mock/dummy test values across all tests to example.com with no subdomain
- Enforce complexity <= 10 and nesting <= 5 architectural invariants

* fix(review): remediate devsecops findings and enhance review self-improvement loop (#176) (#177)

* docs(agent): bootstrap task 176 for review findings remediation

* fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#176)

* feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109) (#178)

* feat(telemetry): w3c traceparent propagation and distributed trace correlation (#109)

* docs(agent): link draft PR 178 in task 109 tracking

* fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183) (#182)

* fix(k8s): resolve helm ssa conflicts, loki validation, podsecurity, and qdrant permissions (#183)

* docs(agent): link pull request #182 in task 183 tracking

* feat(sandbox): streaming diagnostic log aggregator and panic detector (#110) (#179)

* feat(sandbox): streaming diagnostic log aggregator and panic detector (#110)

* docs(agent): link draft PR #179 in task-110 tracking

* fix(sandbox): remediate review findings, demux streams, bound follow memory, and sanitize output (#110)

* docs(agent): update task 110 status to In Review and record review thread resolutions

* fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183) (#184)

* fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183)

* fix(github): remediate copilot review findings on pr merge readiness (#183)

* fix(github): enforce review approval gate, exclude negative copilot headings, and forward tokens (#183)

* fix(github): restrict copilot heading match, validate approval head sha, and support explicit env (#183)

* fix(review): remediate DevSecOps findings and enhance review self-improvement loop (#185) (#186)

* fix(github): gate pr merge readiness on required approvals, mergeable state, and reviewer feedback (#183)

* fix(review): remediate session 20260913-060209 findings and enhance review self-improvement loop (#185)

- sandbox probe: block metadata endpoints, bound regex len and search window, validate target URLs
- telemetry waterfall: enforce hex trace ID validation and validate Jaeger endpoints against SSRF
- telemetry context: add trace_flags parameter to generate_traceparent
- sandbox logs: mask secrets in panic incidents and set 0o600 file / 0o700 dir permissions
- sandbox metrics: reject cgroup path traversal and restrict parsing to valid cgroup hierarchies
- sandbox models: truncate and mask probe result details and incident messages/stacktraces
- sanitizer: mask secrets in non-flag arguments in sanitize_command_args_for_display
- valkey client: correctly strip enclosing brackets from IPv6 hostnames
- http client: validate timeout argument types
- k8s stack lifecycle: mask non-localhost emails in bootstrap summary display
- anti-hallucination dataset: calibrate false positives into common_hallucinations.json
- documentation & prompts: update SELF_IMPROVEMENT.md, review.md, AGENTS.md, and task tracking

* docs(agent): link pull request #186 in task 185 tracking

* fix(review): address review feedback across sandbox, telemetry, k8s, and test fixtures (#185)

- probe: canonicalize trailing dot and resolve host to block link-local/cloud metadata
- waterfall: reject resolved metadata hosts and fix exception tuple in Jaeger trace query
- k8s: mask short and malformed emails in bootstrap display and preserve PII in dry-run
- pr monitor: exclude unknown mergeable_state from readiness and evaluate latest review per user
- http client: raise HTTPTimeoutTypeError derived from ValidationError and TypeError
- sandbox logs: unlink archive and raise SandboxError on incident chmod failure
- sandbox metrics: enforce path-aware containment for cgroup v2 hierarchies
- sandbox models: recursively sanitize nested details and reserve suffix length for truncation cap
- telemetry context: raise TraceValidationError on invalid traceparent flags
- conftest: detect and fail on unauthorized creation or deletion of workspace config.yaml
- tasks: reconcile PR #184 mapping, update taxonomy to status/in-review, and re-sync index

* fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution

* fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback

* fix(security): pin vetted ip transports against dns rebinding and enforce clean merge state (#185) (#186)

* feat(github): implement native devops cli functionality for gh operations and pr governance (#181) (#187)

* feat(github): implement native devops cli functionality for gh operations and pr governance (#181)

- Implement native devops pr ready, diff, and close subcommands
- Implement native devops gh rate-limit and runs subcommands
- Register FastMCP tools pr_ready, pr_diff, pr_close, gh_rate_limit, gh_runs_list, gh_run_view
- Harden config discovery and add pytest safety barrier against workspace config mutations
- Configure squid k8s deployment to use internal registry alias registry.local:5000
- Add comprehensive test coverage and documentation updates

* feat(github): add REST fallbacks for pr view/checks, issues/pr edit, and resolve loki crashloop (#181)

- Fall back to REST API in devops pr view and devops pr checks when GraphQL rate limits are exceeded
- Add devops pr edit and devops gh issues edit subcommands
- Register FastMCP tools pr_edit and gh_issue_edit
- Disable loki-sc-rules sidecar in dev cluster k8s/logging/loki-values.yaml to eliminate k8s API watch crashloop
- Add unit tests for pr/issue edit and REST fallbacks

* docs(agent): link PR #187 in task 181 tracking

* ci(workflows): gate pull request workflow on unresolved review threads and merge blockers (#188)

- Update .github/workflows/ci.yml pull_request triggers to include ready_for_review
- Add Verify PR Merge Readiness step to CI workflow calling devops pr check-readiness
- Add devops pr check-readiness command and REST fallback for list_prs and list_threads
- Add pr_check_readiness FastMCP tool and harden _run_mcp_cmd with mask_secrets
- Sanitize output and validate formats in gh run view/list and pr view/checks/diff
- Remediate and resolve 11 Copilot review findings across PR #187

* fix(process): preserve GH_TOKEN and GITHUB_REPOSITORY for gh binary execution

* fix(repo): prioritize git remote origin before GITHUB_REPOSITORY fallback

* fix(github): remediate review findings across pr readiness, sanitization, and rest fallbacks (#181) (#188)

* fix(ci): support allow-blocked-state in pr check-readiness for github actions workflow

* docs(agent): update task 181 checklist with passing ci checks and resolved review feedback

* fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189) (#191)

* fix(github): add REST API fallback and rate limit handling for pr review threads (#180) (#189)

* docs(agent): record PR #191 in task 180 tracking

* docs(agent): require concise commit messages stating direct effect of change (#169) (#192)

* fix(k8s): harden logging perimeter and scope fluent bit namespaces (#121) (#193)

* chore(ci): align core dependencies and synchronize lockfile (#115) (#194)

* feat(argo): implement automated gitops drift detection and watch command (#111)

* feat(argo): implement automated gitops drift detection and watch command (#111)

* fix(argo): address PR #195 review feedback on gitops webhook, secret masking, and baseline persistence

* feat(github): declarative branch protection auditor and repository secret synchronization (#197)

* feat(github): declarative branch protection auditor and repository secret synchronization

* docs(agent): link PR #197 in task-114 tracking file

* fix(github): lazily fetch public key during secret sync and isolate tests

* chore(release): cut v0.2.17 and finalize release notes (#198)

* feat(test): add deterministic async memory and connection pool profiler (#199)

Implement deterministic async memory and connection pool profiler under devops test profile-memory (#199)

Closes #199
dan-petty added a commit that referenced this pull request Sep 24, 2026
…stay on GitHub

A task file's PR field could only be filled once the pull request
existed, so it took a second commit that re-ran every check and was
itself a prohibited standalone tracking commit. An In Review status went
stale the moment the PR merged. The files had drifted: 173 carried a PR
line, statuses included In Review, Merged, Completed and Closed, and the
project-sync parser read Merged and Closed as Backlog.

- A task file links its issue only. The issue links the pull request
  that closes it (`Closes #N`); project cards take In Review from that
  open PR (infer_item_status), never from the file.
- Statuses: Backlog, Ready, In Progress, Done. The delivering commit
  writes Done.
- The roadmap sync stops writing **PR**; the task parser no longer maps
  anything to In Review.
- Migrated every task file: PR lines removed, statuses set from each
  issue's GitHub state (closed -> Done), bare #N references linked, and
  the one task delivered without an issue linked to its PR (#182).
- AGENTS.md and the task README describe issue-only linking and drop
  the rule to open a draft, set In Review and fill in the PR field.
- tests/test_agent_task_files.py enforces the format.

Closes #489
dan-petty added a commit that referenced this pull request Sep 24, 2026
…stay on GitHub (#492)

A task file's PR field could only be filled once the pull request
existed, so it took a second commit that re-ran every check and was
itself a prohibited standalone tracking commit. An In Review status went
stale the moment the PR merged. The files had drifted: 173 carried a PR
line, statuses included In Review, Merged, Completed and Closed, and the
project-sync parser read Merged and Closed as Backlog.

- A task file links its issue only. The issue links the pull request
  that closes it (`Closes #N`); project cards take In Review from that
  open PR (infer_item_status), never from the file.
- Statuses: Backlog, Ready, In Progress, Done. The delivering commit
  writes Done.
- The roadmap sync stops writing **PR**; the task parser no longer maps
  anything to In Review.
- Migrated every task file: PR lines removed, statuses set from each
  issue's GitHub state (closed -> Done), bare #N references linked, and
  the one task delivered without an issue linked to its PR (#182).
- AGENTS.md and the task README describe issue-only linking and drop
  the rule to open a draft, set In Review and fill in the PR field.
- tests/test_agent_task_files.py enforces the format.

Closes #489
dan-petty added a commit that referenced this pull request Sep 28, 2026
* fix(pr): block readiness on drafts and failing checks (#398)

`devops gh pr check-readiness` reported "satisfies merge readiness" for PR #335 while it was a draft with a failing CodeQL check. It checked merge conflicts and unresolved review threads and nothing else, so the two conditions that actually stopped the release merging were both invisible to the command whose job is to find them.

Draft status was a warning unless `--require-ready` was passed, which made the safe answer opt-in. A draft cannot be merged under any circumstances, and GitHub reports `mergeable_state: clean` for one, so nothing else in the payload gives it away. It is now a blocker, with `--allow-draft` for deliberately checking a draft you intend to keep.

Check runs were not consulted at all. A red pull request is refused by branch protection, so readiness has to account for it. Failing checks are now blockers, and checks still running block too -- an unfinished check is not a passing one -- with `--allow-pending-checks` for a CI job that cannot wait for itself.

`--require-ready` is removed rather than deprecated, per the pre-1.0 policy.

This encodes something I got wrong by hand three times in one session: reporting the release ready from `mergeable: MERGEABLE`, which answers only "no conflicts"; then from a green check rollup plus `mergeable_state: clean`, missing the draft; and only getting it right when every gate was read together. The command now reads them together so the next caller does not have to remember which field answers which question.

* chore(release): open the v0.2.23 cycle (#399)

Bumps the version to 0.2.23 and opens its changelog section, which already carries the two pull requests merged into `release/v0.2.23` since it was branched from main.

`src/devops_cli/__init__.py` reports an updated version because `__version__` is derived from package metadata through `get_version()`; `devops release prepare` claims to have written it, but there is nothing in that file to write.

* fix(pr): say why a pull request could not be created (#400)

`devops pr create` printed nothing when it failed. `run_gh` captures the GitHub CLI's output, so the reason never reached the user: the command exited non-zero with no message beyond its own elapsed time.

Three invocations in one session produced no pull request and no explanation. The base branch had been deleted when its release merged into main, and nothing said so -- I assumed the command had succeeded until checking whether the pull request existed.

The underlying error is now relayed, masked and bounded, alongside the base that was attempted. An unpushed branch is the most common cause and gets its one-line remedy named, since that saves a round trip through the CLI's own help.

* fix(review): stop deriving confidence from the model agreeing with itself (#402)

`confidence_score` fell back to `len(verified_criteria_matched) / len(verification_criteria)` -- the model's claim about which criteria it matched, divided by the criteria the same model wrote. That measures self-agreement and reads as evidence. It is why findings carried 0.95 while being refutable by reading a single file, and the calibration record for session `20260921-212653` already says as much: confidence measures the model's agreement with itself.

AGENTS.md requires a score to originate from a tool's native rating or a structured model response, and to be absent otherwise. An absent score now stays absent rather than being computed into existence. A score the model reports is still kept and clamped to range, and an existing score survives a verdict that omits one.

The roadmap item this came from is corrected rather than closed. It was scheduled P0 on the premise that personas emit deterministic shell assertions which nothing executes. The recorded data contradicts that: across 3167 criteria in 59 sessions, two begin with `git`, none with `grep` or `rg`, one with `python`, and 3069 are prose describing an observable condition. An executor built today would execute three criteria out of 3167.

So the item is re-sequenced and dropped to P1: make criteria executable first -- constrain the prompts and schema so a criterion is either a command from a closed read-only allowlist or explicitly marked unexecutable -- and only then execute them and derive confidence from the outcomes. The second half cannot be tested against real data until the first exists. Sequencing them the other way is what put this at P0 on an assumption nobody measured.

Two tests that encoded the old behaviour are updated: a parameterised case asserting 1-of-2 criteria yields 0.5, and the surrounding expectations.

* fix(review): bind verification verdicts to findings by identity, not position (#403)

`_validate_segment_findings` matched model verdicts to findings by list position, choosing between two incompatible index spaces with a length heuristic. The response covers only the *unresolved* findings, but the fallback indexed it with a position from the *whole* list, including those deterministically invalidated before the model ever saw them. Any count mismatch -- a model merging, dropping or adding an item, which is routine -- shifted every verdict onto a different finding.

The corruption is in the recorded data, not just in theory. Across this repository's 59 review sessions, 35 findings carry an `invalidation_reason` while reporting `verified=true` and `status=VERIFIED`, 23 of them in one session. A finding cannot be both withdrawn and confirmed. Several of those reasons are verbatim the title of a different finding, which is what a shifted verdict looks like from outside:

    title : Unvalidated host binding exposes service to external networks
    reason: Unvalidated host binding exposes service to external networks

Verdicts are now matched by title and location through `_is_matching_finding`, which was already in the module for exactly this. A verdict that identifies no finding is discarded rather than applied to whatever sits at its index; a finding that receives no verdict keeps the status it had; and two verdicts cannot claim the same finding. Tests assert that reordered, truncated and extended responses each leave every finding with its own verdict.

The verifier prompt now requires each verdict to repeat the finding's title and location, since that is what the binding reads. Two existing tests supplied neither and passed only because position bound them anyway -- including one named `test_verification_index_alignment_with_pre_invalidated_findings`, written to pin the behaviour that causes the corruption. Both now supply identity.

Rebuilt on the current release branch: the previous attempt was amended into the wrong commit after a pre-commit rejection, so PR #401 carried this work under another change's message and conflicted once the confidence fix landed.

* feat(review): show personas the false positives they have already recorded (#404)

The hallucination ledger was written on every deterministic invalidation and read back only during verification. Suppressing a finding there means a model has already been paid to produce it, and the same ones recur: the top entry in this repository's ledger has been recorded 225 times, and it is the PEP 758 multi-exception syntax claim that the verifier prompt already carries a rule to reject.

The ledger is now rendered into the persona system prompt as negative exemplars, so a recorded false positive is prevented at generation instead. Recurrence is concentrated in the head of the distribution, so only the top entries are shown -- 8 of 248, truncated to 160 characters each, about 1500 characters in total -- because the tail would spend the budget without preventing anything. An empty ledger contributes nothing, so a first review of an unfamiliar repository carries no block at all.

The roadmap item this came from is corrected rather than closed. It claimed `load_common_hallucinations` has zero consumers; in fact `is_common_hallucination` calls it and is consumed by `_deterministic_pre_verification`, so the ledger has always been matched against new findings before an LLM call. Only the prompt-injection half was missing. What remains -- per-category false-positive rate tracked across runs -- overlaps with the prompt benchmarking item and is re-sequenced to be built with it.

* chore(release): bootstrap the v0.2.23 milestone from the roadmap (#439)

The v0.2.23 milestone held one issue -- its release epic -- against 35 roadmap items scheduled for it. Nothing tracked the release's deliverables, so the work had no issues to close and `devops gh issues close-merged` had nothing to reconcile after every merge this cycle.

`devops gh issues sync-roadmap` now populates it: 34 issues (#405-#438) with their per-task tracking files. The milestone holds 35 open issues where it held one.

Identity-Bound AI Review Verification Verdicts is marked delivered rather than synchronised, since #403 closed it; without that it would have been filed as outstanding work.

Issue #434 and its task file were generated before #404 landed, so they carry the pre-correction scope. Both are retitled to what actually remains -- per-category false-positive rate tracked across runs -- and the task file records why: the roadmap entry claimed `load_common_hallucinations` has zero consumers, which was half wrong, and the half that was genuinely missing shipped in #404.

* fix(k8s): run port-forward daemons in their own process group (#440)

Scheduled as POSIX process group enforcement "across background dispatchers". Of the three `subprocess.Popen` call sites in the codebase, two already passed `start_new_session=True`, and the agent harness already terminated through `os.killpg` with a SIGKILL escalation. The gap was one site.

`devops k8s port-forward` started `kubectl port-forward` in the CLI's own process group and recorded its pid. `devops k8s port-forward status` calls these background daemons, which is only true if they are detached: sharing the CLI's group means a terminal's SIGINT reaches them, and they are torn down with the shell that happened to start them.

Stopping them signalled the pid alone. Anything `kubectl` spawned kept running and kept the local port bound, so the daemon listing reported the forward stopped while the port was still held.

Forwards now start in their own session, and stopping one signals its process group. A forward recorded before this change still shares the CLI's group, and signalling that group would kill the CLI running the stop command -- so the group is compared against this process's own and such a forward is signalled by pid instead.

Four tests cover it, including the fallback, and one asserts the forward is started detached rather than trusting the call site to stay that way. An existing test patched `os.kill` and asserted termination; it now covers the group path.

* fix(docs): stop Jekyll executing agent task files as Liquid templates (#441)

Every GitHub Pages deployment on main has been failing since task 325 merged:

    Liquid Exception: Liquid syntax error (line 79): 'if' tag was never closed
    in agent/tasks/task-325-template-rendering-engine-sandboxing-...md

Pages builds `docs/` with Jekyll, which parses `{% ... %}` and `{{ ... }}` as Liquid before rendering Markdown. That task documents this project's Jinja2 template sandboxing, so it quotes `{% if minikube %}` as prose. Liquid reads it as a real tag, finds no `{% endif %}`, and aborts the entire site build.

A `docs/_config.yml` now excludes `agent/` from the site. Those files are internal task tracking rather than published documentation, and escaping them one by one does not hold: there are 60 of them, 34 added in this release alone, and each new task adds another that may quote a template.

`docs/KNOWN_ISSUES.md` is genuinely published and contains `${{ secrets.* }}` as an example of a redaction placeholder. Liquid was rewriting it, so the rendered page showed something other than what the file says; it is now wrapped in `{% raw %}`.

Found from a failing run rather than by inspection -- nothing in `devops ci` builds the site, so the local gate cannot see this class of break.

* feat(mcp): advertise a domain's tools only once a client asks for them (#442)

The server registers 156 tools and offered all of them on every turn. Their names and summaries alone cost about 2,700 tokens per request -- `gh` 948, `k8s` 587, `pr` 487 -- before the per-parameter JSON Schema the protocol adds on top, and a model choosing among 156 tools chooses worse than one choosing among a few dozen.

A middleware now filters `tools/list` to the eager domains plus `hydrate_tool_domain`, which a client calls to reveal the rest. Measured: 156 tools and 2,710 tokens down to 37 and 722, a 73% reduction, with `hydrate_tool_domain("k8s")` restoring its 16. Calling a withheld tool still works; only the listing is narrowed, so a client that knows a name is not forced through a round trip.

The first implementation removed tools from the server instead of filtering, and that was wrong in a way worth recording. The registry is a process-wide object every consumer shares, so removing from it broke six unrelated tests: the schema exporter, the docs generator and the in-process bridge each saw whatever the last caller had left behind. It also withheld tools *before* `run_mcp_server` validated the transport, so a launch rejected for binding a non-loopback address had already mutated global state on its way to raising.

Filtering at the protocol boundary removes that entire class. Nothing is mutated, and the four consumers that want the whole catalogue -- `list_mcp_tools`, `devops ai mcp export-schemas`, the docs generator behind `docs/MCP_TOOLS.md`, and the tests asserting registration -- read the registry directly rather than the client-facing view.

One deliberate behaviour change: the in-process pydantic-ai bridge is a client, so it sees the gated listing too. Its test now asserts the eager domains are offered immediately, the gated ones are absent, and they appear after hydrating.

* feat(ci): block deep nesting at commit time with a standalone AST sentinel (#443)

AGENTS.md caps nesting depth at 5 and complexity at 10. Both were checked only by `tests/test_architectural_invariants.py`, inside a suite that takes minutes, so a breach surfaced after the work was finished rather than as it was written.

`scripts/check_structural_invariants.py` now runs on staged files in about 140ms and fails a commit that nests too deeply. It deliberately imports nothing from `devops_cli`: loading the package costs roughly five seconds before a single file is read, which is more than a commit-time gate can spend. The measured alternative was not close.

The complexity cap is reported rather than enforced, and the reason is the more useful finding here. `src/` holds 240 functions above it, and nothing enforces it: `devops ci` has no complexity gate, Ruff's `C901` is not enabled, and the one architectural test passes `max_complexity=100`, so it catches nesting alone. A blocking hook would stop work on any of those 240 files rather than hold a line the codebase is on. AGENTS.md describes this invariant as continuously validated; it is not, and the roadmap now carries that as its own item -- either work the debt off and enable `C901`, or ratchet a baseline so new breaches fail.

The first version of the sentinel disagreed with the project's own scanner: it counted `Try` rather than `ExceptHandler`, counted comprehensions, and recursed into nested functions, reporting 334 breaches against the scanner's 240 and a nesting breach the scanner does not see at all. A hook stricter than the definition it enforces rejects code the project accepts, so the metric now mirrors `security/complexity.py`, and a test asserts the two agree on nesting across `src/`.

* feat(devcontainer): give the Claude extension its own MCP configuration (#444)

The devcontainer installs the Claude Code extension and the repository ships `.vscode/mcp.json`, but the extension never read it. VS Code's native MCP support reads `.vscode/mcp.json`; Claude Code reads `.mcp.json` at the repository root. So the devops-cli tools were available to Copilot and absent from Claude in the same container.

The two files are not interchangeable, which is why this adds a template rather than copying one. `${workspaceFolder}` and `${env:HOME}` are VS Code substitutions that Claude Code does not expand, so a copied file would hand the server a literal `${workspaceFolder}` on its PATH. Claude Code also runs a stdio server with the project root as its working directory, so the Claude template needs neither that variable nor `cwd`.

Both scaffold paths write it -- `devops devcontainer init` and the post-create sync -- so a project scaffolded from this CLI gets working MCP in both clients rather than one. This repository now ships the file too.

Verified by driving the server over stdio with an `initialize` request before wiring anything: it answers with protocol 2024-11-05 and `serverInfo.name` `devops-cli`. A test asserts both templates launch the same command and arguments, so the two files cannot drift into describing different servers.

* docs(roadmap): per-check CI cache scoping has no benefit and is unsafe (#445)

Investigated with 49 agents rather than built. Three independent findings, each sufficient on its own.

The gate runs its checks concurrently, so wall-clock time is the longest check and not the sum. From this repository's own cache entry: `test` 538.2s, `coverage` 538.2s, `security` 77.5s, `docs` 77.0s, `typecheck` 75.4s, everything else under 7s — 1322s of work inside 538s of wall clock. Caching `typecheck` and `security` perfectly moves a run from 538.2s to 538.2s. The only check whose reuse shortens anything is `test`.

`test` cannot be scoped. Traced with a `sys.addaudithook` plugin over a real run: it reads `k8s/**` manifests and Grafana dashboards, `docs/ROADMAP.md`, `.github/workflows/ci.yml`, `.devcontainer/Dockerfile`, `.mcp.json`, `config.yaml` and `scripts/**`, and takes a repo-root listing that turns any new root-level file into an assertion. `--cov=src` with `fail_under = 90` makes every file under `src/**` an input whether or not it is imported.

The mapping is unsafe regardless of benefit. Thirteen input sets were derived from real argv and tool configuration, then attacked by three independent agents each; every one was broken by a demonstrated counterexample. The recurring cause is structural rather than incidental: each check is spawned by the gate itself, so `core/process.py` and `config/defaults.py:261` decide whether `actionlint` passes. "Independent input sets" is not a property this design has. `lint` was separately broken by `.git/info/exclude`, which ruff honours for file discovery and which no content fingerprint covers.

The entry also carried an input map that was wrong in the fail-open direction: it said ruff reads `src` and `tests`, where `ruff check .` walks 780 files including `scripts/` and `pyproject.toml`, with only `repos` excluded. Coding from that prose would have produced exactly the stale pass its own constraint warned about — a gate reporting green while the change it should have caught went unchecked.

Issue #405 is closed with this evidence. The work belongs in #406: narrowing `test` itself is where the 538s is.

* feat(ci): build the covering-test index from coverage instead of guessing (#446)

`select_tests_for_sources` picks tests by filename convention and by grepping test sources for an import of the changed module. That finds tests which name a module and misses every test reaching it through an import chain — which is most of them.

Measured rather than argued. Per-test coverage contexts were generated over the whole suite and the textual selector scored against them, across 387 source files and 317 test files:

    mean recall      65.0%
    median recall    66.7%
    10th percentile  11%
    zero covering tests selected for 21 files (5%)

The tail is what decides a gate. `core/cli.py` — the Typer subclass every command is built on — is covered by 38 test files and the grep finds none of them, because tests import commands rather than the class underneath. `output/formatters/tables.py` misses 39, `ai/text_utils.py` 24. Wiring that selector into the pre-push or CI run, which is what the roadmap entry proposed, would report green having executed nothing that exercises the change.

`core/coverage_index.py` builds the reverse index from a `--cov-context=test` database. Scored against the same ground truth it reaches 100% recall with zero blind spots, because the mapping is observed rather than inferred from text.

It fails closed in five directions, each with a test: an unindexed source, a test file added since the index was built, a change to `conftest.py`/`pyproject.toml`/`uv.lock`/`.python-version`, a path outside `src/`, and an index that is unreadable or written in an older format. Every one of those returns "run everything" rather than a narrowed set. An unindexed source is not "nothing covers it" — it is "this index cannot say", and those are the same answer only if you are willing to ship untested changes.

One subtlety the first implementation got wrong: the suite snapshot has to come from the filesystem, not from the coverage contexts. A fully skipped test executes no line and so appears in no context; recording only the tests seen in contexts made every index look stale the moment it was written, because nine of this repository's 317 test files are in that position.

The roadmap entry also claimed coverage data already drove selection. It did not, and that correction is recorded with the measurement. Wiring the index into `devops ci test` is left as the remaining step, deliberately: the constraint that under-selection ships untested changes is unchanged, and the index should be observed correct over real commits before a gate is allowed to trust it.

* fix(cli): __all__ promised thirteen names no module could serve (#447)

`devops_cli.config` declared thirteen names in `__all__` that exist nowhere in the tree: nine `CONST_PORT_*` constants and four `HTTP_*_TIMEOUT_SECONDS` floats. `from devops_cli.config import CONST_PORT_GRAFANA` has raised ImportError since ec5fb888 (v0.2.3), which deleted the definitions and the imports that pulled them in but left the export declarations standing. Twenty releases later nothing in the repository references any of the thirteen.

Nothing detected them because Ruff's F822 -- undefined name in `__all__` -- is suppressed for an entire module as soon as that module defines a module-level `__getattr__`, and every lazily re-exporting package here defines one. These were not dormant, either: `devops_cli.ai.library.introspector` reads `__all__` verbatim and reports it as the package's public API, so the broken names were being advertised.

Alongside them the tree carried the shape evidence recorded in #424 -- 23 duplicate `__all__` entries across four modules and 23 unsorted `__all__` lists. The duplicates are redundant rather than wrong: `devops_cli.ai.__getattr__` has two branches claiming each repeated name, the earlier branch always wins, and for seven of the eight the rival submodules re-export the identical upstream object.

This removes the thirteen phantom entries, removes the 23 duplicates, sorts the 23 lists, and selects RUF022 and RUF068 so none of the three can come back. They are selected individually rather than as the whole RUF family, which is a separate roadmap item with its own triage. The two grouping comments in `devops_cli.ai.output.__all__` go with the sort, which would otherwise leave them labelling names they no longer introduce; the import statements immediately above already record that provenance.

`tests/test_public_export_surface.py` holds the guard that F822 could not. It parses every `__all__` under `src/devops_cli` and fails on any name the module can neither bind nor name as a string in a `__getattr__` membership set, which costs milliseconds where resolving every lazily-loaded AI export takes minutes. The check deliberately over-approximates what a module can serve, a bias that can only let a phantom through and never invent one; it reports exactly the thirteen and nothing else across the 140 modules that declare one, matching name for name what resolving them dynamically found.

Apart from those thirteen removals the set of names each module declares is unchanged, verified by diffing every module's parsed `__all__` against the previous commit. Reducing the 473, 545 and 396 working exports that `devops_cli.ai`, `devops_cli.ai.agents` and `devops_cli.config` are left declaring down to a minimal contract is not attempted here: every one of those names resolves, withdrawing a working export is an API judgement rather than a defect fix, and #424's own constraint requires migrating internal call sites and confirming against the full suite first.

Refs #424

* fix(cli): drain background shell pipes into bounded ring buffers (#449)

* fix(cli): drain background shell pipes into bounded ring buffers

`Shell.start_command` opened `stdout` and `stderr` as pipes and then read
neither of them. A background command that wrote past the kernel pipe buffer
-- 64 KiB on Linux -- blocked on its next write and never exited. Reproduced
with a 1 MiB-per-stream payload: before this change it does not reach
`FINISHED` within 20 seconds, after it completes immediately. The wedged
process also counted against `max_bg_processes` forever, so ten such commands
retired the capability for the remainder of the session.

The same code carried an unfulfilled contract. `bg_outputs` was seeded with an
empty list per command, never appended to, never read, and never removed by
`stop_command`, which popped only `bg_processes` and leaked the other entry.
`check_command` therefore returned a bare status line, although both its
docstring and its registered tool description promise output.

One daemon reader thread per stream now drains into a `deque(maxlen=1000)`
from the moment the process is spawned, before the caller is ever handed the
tracking ID, so there is no window in which the child can fill a pipe nobody
is emptying. The buffers are lock-guarded: a `deque` raises if it is mutated
mid-iteration, which is precisely what a reader thread and a concurrent
`check_command` would otherwise do. Each ring also remembers how many lines it
has seen, so a report whose scrollback was evicted says so instead of reading
as the whole of the output. The two dicts collapse into one keyed registry,
which removes the leak by construction.

Bounding matters as much as draining: an unbounded sink would trade the
deadlock for unbounded memory growth on a chatty long-running process. The cap
lives in `config/defaults.py` as `DEFAULT_SHELL_BG_OUTPUT_LINES` and is
overridable per capability via `max_bg_output_lines`.

Three regression tests, each verified to fail with the source reverted to
HEAD: the 1 MiB payload never reports `FINISHED`; `check_command` returns no
output; and the bounded-window assertions cannot run at all.

Extracting `_run_sync`, `_launch_background`, `_render_background_report` and
`_terminate_process_group` brings `Shell.get_tools` to a cyclomatic complexity
of 10, down from 15 before this change. `Shell._validate_command` is untouched
and remains at 16.

* fix(cli): do not kill a background command over one undecodable byte

Two defects in the pipe-draining change, both found by adversarial review of the commit and both reproduced before being fixed.

The reader threads read with `text=True`, so decoding was strict. A child emitting a single non-UTF-8 byte raised `UnicodeDecodeError` inside the reader, and since that is a `ValueError` the drain handler treated it as a closed pipe, left its `with stream:` block, and the child died of SIGPIPE on its next write. Reproduced against the original commit: a script writing `start`, then `b"\xff\xfe bad"`, then more output finished with exit 0 before the pipe change and exit 1 with `BrokenPipeError` after it. A command is not wrong to emit a stray byte, so the byte is now replaced rather than the command killed.

`_render_background_report` also called `poll()` and rendered the rings immediately. `poll()` returns an exit status as soon as the child is reaped, which is before the readers have necessarily banked what was still in the pipes, so a report could say FINISHED beside truncated output — and the missing lines never arrived, because nothing read the rings again. A finished command now waits for its readers, bounded by `DEFAULT_SHELL_DRAIN_TIMEOUT_SECONDS`.

The regression test was confirmed to fail without the decoding fix rather than assumed to.

* feat(config): cache parsed settings behind a modification stamp (#448)

`load_settings()` is called from 218 sites, several of them on per-request paths,
and every call re-derived the same mapping from disk: a walk up the directory tree
looking for a project config, then a YAML parse of each layer that was found. The
roadmap entry measured 10.8 ms per call.

Measured again here, against the real `~/.config/devops-cli/config.yaml`, a call
costs 13.9 ms. The directory walk is the larger half: a single `Path.is_file()` on
this filesystem is 1.4 ms and `_find_project_config_path` performs ten of them, for
24.6 ms in the worst run observed. Parsing the YAML is 4.3 ms and
`Settings.model_validate` 1.6 ms. After this change the same call is 1.8 ms, which
is the model validation plus two `stat` calls.

Only the file-derived mapping is cached. Environment overrides and the data-directory
resolution still run on every call, because they cost microseconds and a variable
exported after the first load must still take effect, and each caller gets a deep copy
of the mapping so that editing the returned `Settings` before saving cannot rewrite
what every later load sees. That is the constraint the roadmap entry records: settings
are mutable at runtime and a captured snapshot has already caused one stale-configuration
defect in this project.

Invalidation is on the files that supplied the values, not on a process lifetime. An
entry is reused only while the global and project files still carry the path, mtime and
size they had when parsed, so an edit by any process -- an editor, another CLI run --
is honoured on the next call. `save_settings()` discards the entry outright, because the
writer knows the values changed and should say so rather than leave it to be inferred.

Two things the cache deliberately will not do. It will not cache a file that was
modified within the last two seconds: the kernel stamps files from a coarse clock, so a
file rewritten moments after it was parsed can carry an identical mtime and size, and
trusting that stamp would serve superseded values. And it takes the discovery walk on
trust, so a project config file *created* after the first load is seen once the cache is
reset rather than immediately -- a stamp of a file that did not exist cannot report where
a new one appeared.

The four tests each fail against the unpatched loader. The two behavioural ones rewrite
the file with same-length content and restore its timestamp with `os.utime`, so the only
thing that can distinguish the two loads is the cache; without it they read `bravo` where
`alpha` is asserted. The tests for the settling window and for invalidation on save fail
on the absent cache itself. `tests/conftest.py` resets the cache around every test, since
the parsed mapping is now process-wide state.

The roadmap checkbox is deliberately left unticked here. `release/v0.2.23` rewrote the
*Deterministic Test Selection* entry immediately above this one, so even a one-character
edit arrives with overlapping context and `git merge-tree` reports a conflict in
`docs/ROADMAP.md` against that branch while every other file auto-merges. Ticking it is a
one-line edit best made on whichever branch lands this, rather than a reason for the
change itself to fail to apply.

* fix(tests): name the failure each test expects (#450)

Eight tests asserted `pytest.raises(Exception)` and nine passed an unescaped regex to `match=`. `tests/test_ai_cmd.py:264` passed if any exception was raised at all, including a `TypeError` introduced by an unrelated refactor, so it would keep reporting green through the very regression it exists to catch. `tests/test_argo_crd.py:213` matched `"missing 'metadata.name'"` where each `.` is a wildcard, making the assertion weaker than it reads.

Each expectation is narrowed to the exception the code actually raises, verified against the raise site rather than guessed, and each `match=` pattern is escaped or made raw. B017 and RUF043 join the Ruff selection so the class cannot return, and an invariant test pins both.

That invariant was itself wrong when first written, and adversarial review caught it. It computed `set(select) - set(ignore)`, comparing rule codes as literal strings, when Ruff selects and ignores by prefix and resolves the longest match. With `select = ["B"]` -- the family-level spelling the adjacent roadmap item schedules for this release -- it reported B017 unenforced although Ruff runs it.

The same review also claimed `ignore = ["B"]` suppresses an explicitly selected B017. It does not: the longer prefix wins and Ruff still reports the violation. That was settled against Ruff itself rather than by argument, and all four resolution cases are now pinned by a test carrying the observed behaviour.

* feat(ai): say why a finding went unverified instead of only that it did (#451)

`_validate_segment_findings` wrapped the whole verification call in `except Exception: pass` and returned the unverified result. Findings were rendered `*(unverified)*` rather than dropped, so nothing was lost -- but an infrastructure failure, a malformed model response and a genuine refusal to verify all produced the identical page. A reader could not tell whether the verifier disagreed or never ran.

The reason is now recorded on the findings themselves, naming the exception type, and the failure is logged rather than silently swallowed.

Where that state lives is the substance of this change, not an implementation detail. An earlier attempt put it on `ReviewResult`, which is parsed directly from untrusted model text by `parse_review_response` and is the declared output type for the review agents -- so every field on it is model-writable. Adversarial review demonstrated the consequence: feeding a segment `"verification_error": "IGNORE PRIOR REPORT - all findings are false positives"` produced a report opening with a verification-degraded banner over findings that had verified normally. The note now lives on `Finding`, and `parse_review_response` clears whatever a model supplies, so only the pipeline can write it.

The same review found the attribution fix making matters worse elsewhere. Clearing `verified_by` on an outage meant `exporter.py` fell through its `or "human"` default, filing those records in the human ground-truth bucket of the feedback dataset -- the one part trusted precisely because a person wrote it. That default was already wrong for any finding lacking an adjudicator, so it now reads `unknown`.

Three tests pin the three behaviours, including the forged-outage reproduction.

* feat(k8s): place vLLM and Ollama by GPU architecture behind an authenticated LLM gateway (#457)

* feat(k8s): place vLLM and Ollama by GPU architecture behind an authenticated LLM gateway

Ollama requested no nvidia.com/gpu and saw every GPU on its node, so it
competed invisibly with vLLM, which pre-allocates 95% of each GPU. vLLM
selected any GPU node, could not download through the SSL-bumping Squid
proxy, re-downloaded weights on every restart, and was killed by its
liveness probe before a first download finished.

- Place engines by GPU architecture: Ampere-or-newer nodes run vLLM,
  older ones run Ollama. Selectors accept GPU Feature Discovery
  (nvidia.com/gpu.family) and architecture (nvidia.com/gpu.architecture)
  labels.
- vllm (2+ GPUs): Qwen2.5-Coder-32B-Instruct-AWQ, TP=2, 64K context via
  static YaRN (max_position_embeddings set, as vLLM 0.30 expects).
- vllm-single (one 16 GiB+ GPU): Qwen2.5-Coder-14B-Instruct-AWQ, FP8 KV
  cache, 16K context sized from measured KV headroom.
- Both: pinned vllm/vllm-openai:v0.30.0, Squid CA bundle, Xet transfers
  disabled, model-cache PVC, 3-hour startup probe, Recreate rollouts,
  service links disabled (the vllm Service injected VLLM_PORT).
- LiteLLM gateway v1.102.1 as the single authenticated entry point:
  master key from a Secret, auto-assigned NodePort, 600 s timeout,
  context-window escalation (chat -> coder -> reasoning) with pre-call
  checks, and coder outages falling back to reasoning first. vLLM
  Services stay ClusterIP.
- Open WebUI connects to the gateway with the shared master key.
- Served model names come from DEFAULT_VLLM_* constants used by the
  gateway and Portkey routes, scale_vllm and the ConfigMaps' tests.

Closes #453

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(tasks): link task 453 to its pull request

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* feat(ai): route reviews and embeddings through the gateway across every inference backend (#459)

* feat(ai): route reviews and embeddings through the gateway across every inference backend

The LiteLLM gateway fronts both vLLM and Ollama, but a review sent all of
its calls through one client bound to one model, embeddings only spoke to
Ollama URLs, and review prompts were too large for small-window servers.

- Gateway: a devops-review model group spans both vLLM profiles and the
  Ollama nodes, least-busy routed with per-deployment
  max_parallel_requests and max_input_tokens so pre-call checks keep a
  prompt off a deployment it would overflow. `ollama/*` passes any Ollama
  model through Ollama's OpenAI-compatible API, for chat and embeddings.
- Review pages are sized from the analysis context window
  (review_page_chars: 60% of the window at 3.5 characters per token,
  8K floor, 128K cap). The old max(128K, window * 3.5) never shrank, so
  default pages already exceeded the default 32K-token window.
- Persona agents review each page without cross-file history:
  MultiAgentPipeline.run/run_parallel accept message_history and the
  review passes []. Cached agents used to resend every earlier file.
- EmbeddingsEngine supports provider gateway, preferring the embedding
  task's own api_base_url, then gateway_url, never a global api_base_url
  meant for another provider.
- The gateway uses LiteLLM's bundled model cost map; its egress only
  reaches the inference backends.

Verified with an all-persona review of 15 files: requests reached the
single-GPU vLLM (49), dual-GPU vLLM (23) and one Ollama node (15).

Closes #458

* docs(tasks): link task 458 to its pull request

* fix(k8s): forward Ollama's ranged blob requests through squid unchanged (#461)

* fix(k8s): forward Ollama's ranged blob requests through squid unchanged

Ollama downloads each blob from Cloudflare R2 as many parallel byte
ranges. squid's range_offset_limit -1 answered each of them by fetching
the whole object from byte 0, so every range past the start stalled,
Ollama aborted it, and the pull restarted. In 54 minutes squid logged
1,498 ranged requests to R2, all TCP_MISS_ABORTED, delivering 0 bytes.
No model could be pulled, and the gateway aliases served by Ollama
(devops-chat, devops-embedding) failed with "model not found".

Scope range_offset_limit 0 to .r2.cloudflarestorage.com ahead of the
-1 default. squid applies the first matching line, so other ranged
requests still fetch and cache whole objects. A test pins the order.

Verified live: qwen2.5-coder:7b (4.7 GB) and bge-m3 pulled on both
Ollama nodes in under three minutes; the stuck pull had hung for 90.

Closes #460

* docs(agent): link task 460 to its PR

* fix(ai): send provider gateway requests only to the gateway (#462)

* fix(ai): send provider gateway requests only to the gateway

api_base_url outranked gateway_url in _api_base, and for_task copied
the global api_base_url into every task. A global api_base_url is
usually OpenAI's, so a task on provider gateway sent its requests and
the gateway master key to OpenAI. Any task switching provider leaked
its key to the global provider's endpoint the same way, and the
pydantic-ai bridge resolved litellm: models to api_base_url without
looking at gateway_url.

- Provider gateway always sends to gateway_url: _api_base,
  backend_host and gateway embeddings ignore api_base_url for it.
- for_task: a task's own api_base_url applies to its provider and, on
  a gateway task, becomes that task's gateway_url. The global
  api_base_url carries over only to tasks that keep the global
  provider.
- Bridge: litellm:, portkey: and lightllm: resolve to gateway_url,
  portkey_url and lightllm_url instead of api_base_url or hard-coded
  localhost endpoints.
- EmbeddingsEngine drops its private copy of the embedding task's
  api_base_url and uses the shared resolution.

Verified live: with a global OpenAI api_base_url and chat on provider
gateway, without the per-task workaround, chat reached the gateway.

Closes #455

* docs(agent): link task 455 to its PR

* docs(k8s): configure gateway tasks through ai.gateway_url

* feat(k8s): give the gateway one deployment per Ollama node (#464)

* feat(k8s): give the gateway one deployment per Ollama node

The gateway reached Ollama through the `ollama` Service. kube-proxy
balances per connection and LiteLLM keeps its connections open, so all
gateway traffic to Ollama went to one pod: in a full review one node
served 15 requests and the other 0. With one deployment covering every
node, LiteLLM could not match load to each node's single request slot
or cool down a failing node on its own.

- Ollama runs as a StatefulSet (k8s/llm/ollama.yaml) with per-pod DNS
  through the headless ollama-nodes Service, required anti-affinity for
  one pod per GPU node, and Parallel pod management so an offline node
  never blocks the others. Architecture affinity, hostPort, hostPath
  models and the `ollama` NodePort Service are unchanged.
- The gateway lists every pod for devops-chat, devops-embedding, the
  Ollama tier of devops-review (max_parallel_requests 1, matching
  OLLAMA_NUM_PARALLEL) and the ollama/* pass-through. devops-chat moves
  to ollama_chat/, like the review tier.
- Health checks probe embedding deployments as embeddings and the
  wildcard with a real model instead of a placeholder.
- A test keeps the per-pod entries in step with the replica count.

Closes #463

* docs(agent): link task 463 to its PR

* docs(agent): record live verification for task 463

* fix(ai): name a missing or rejected API key instead of a generic network error (#466)

* fix(ai): name a missing or rejected API key instead of a generic network error

With no API key configured, the OpenAI-compatible client sent
`Authorization: Bearer ` with nothing after it. httpx refuses that
header, so the request never left the machine; the user saw only
"Check network access, API endpoint, and credentials" after four
attempts, and the server logged nothing.

- Send Authorization only when a key is set (chat, streaming, model
  listing). A server that needs no key works; one that does answers 401.
- A 401 or 403 raises AICredentialsError, which says whether the key is
  missing or was rejected and names DEVOPS_CLI_AI_API_KEY and
  `devops config set ai.api_key`.
- Chat retries stop at the first credentials failure.

Verified live: a gateway chat without a key failed after one request
and 0.07 s with the credentials message; the gateway logged one 401.

Closes #465

* docs(agent): link task 465 to its PR

* fix(k8s): weight devops-review routing by backend throughput instead of capping deployments (#468)

* fix(k8s): weight devops-review routing by backend throughput instead of capping deployments

The devops-review pool routed least-busy with max_parallel_requests
caps. LiteLLM waits on a deployment's cap only after routing to it, and
least-busy counts a request only once its backend call starts, so
requests queued behind a cap were invisible: the dual-GPU vLLM ran about
2 requests at a time instead of 8, and overflow queued on the
single-request Ollama nodes. The caps protected nothing, since vLLM and
Ollama queue excess requests themselves.

- routing_strategy: simple-shuffle, with devops-review weights by
  measured throughput (dual-GPU vLLM 5, single-GPU vLLM 3, each Ollama
  node 1). Weighted random choice also spreads a burst of simultaneous
  persona calls, which least-busy routes before any count changes.
- Remove max_parallel_requests from the pool.

24 concurrent review-style requests: 47-104 s before, 18.7-27.5 s with
least-busy and no caps, about 13 s weighted. Throughput levels off near
2 requests/s from 12 to 48 concurrent requests, so review file workers
need no gateway-based sizing; the roadmap says so.

Closes #467

* docs(agent): record real review measurements for task 467

* fix(ai): authenticate gateway route discovery and query the configured gateway (#471)

* fix(ai): authenticate gateway route discovery and query the configured gateway

`devops ai gateway routes` queried the live gateway only with
--gateway-url and never sent the API key. An authenticated LiteLLM
gateway answered 401, and the command silently showed four built-in
default routes instead of the gateway's deployments; the
ai_gateway_routes MCP tool, which runs it, did the same.

- GatewayRouter takes the AI API key and sends it to /model/info
  (and the /models fallback).
- `routes` queries ai.gateway_url unless --gateway-url overrides it.
- A 401 or 403 raises the credentials error, now built by a shared
  credentials_error helper that the OpenAI-compatible client also
  uses; `routes` prints it and exits 1.
- LiteLLM lists a wildcard deployment once per model it can serve,
  under one deployment id; those collapse into one `<provider>/*` route.

Verified live: 12 routes from 468 raw /model/info entries with the
key; without it, the command names the missing key.

Closes #469

* docs(agent): link task 469 to its PR

* feat(devcontainer): keep gh and devops secrets in gnome-keyring (#472)

* feat(devcontainer): keep gh and devops secrets in gnome-keyring

The devcontainer had no Secret Service, so `gh auth login` wrote its token
to hosts.yml in plain text and Python keyring fell back to fail.Keyring,
leaving devops nowhere to store secrets.

The image now ships Debian's gnome-keyring. dbus-x11 satisfies its
session-bus dependency without pulling in systemd. post-start starts a
session bus at the address containerEnv names, and gnome-keyring is
D-Bus-activated on it the first time a client asks for a secret. The bus
and the keyring control socket live in /run/user/1000, which is private to
each container. /tmp is a volume shared between containers, where one
container's daemon would replace another's.

Tests unset the bus address so an unmocked keyring call never reaches the
real secrets once containerEnv sets it.

Also drops the git feature, moves the node feature to v2, and adds the
Antigravity extension.

Refs #452

* feat(devcontainer): set up the keyring for every scaffolded devcontainer

`devops devcontainer init` renders DBUS_SESSION_BUS_ADDRESS into every
project, but only the published image ships gnome-keyring. A project on any
other image got a bus address and no keyring behind it. post-create now
installs gnome-keyring and dbus-x11 with apt when the bus is configured and
the daemon is missing.

Unlocking was a shell one-liner that needed an XDG_RUNTIME_DIR override,
exited 0 on a wrong password, and took a trailing newline as part of the
password. `devops devcontainer unlock-keyring` replaces it:
- It reads the password without echo, and asks twice when creating the
  keyring.
- It refuses an empty password, which would store secrets in plain text.
- It keeps the daemon's control socket off the shared /tmp.
- It confirms over D-Bus that the keyring really unlocked.

post-start's "bus started" message now names the command, because a fresh
bus always means a locked keyring.

Refs #452

* docs(roadmap): plan LLM tuning and optimization work for v0.2.23 (#483)

Ten roadmap entries, filed as #473-#482 with task files. Measurement
comes first, so the work is also a guided tour of `devops ai`, and its
results direct the tuning:

P1 baselines
- #473 review performance baseline: per-stage timing, calls, tokens
- #474 record the serving backend of every gateway call
- #475 per-backend review quality baseline

P2 tuning
- #476 validate gateway weights against real reviews
- #477 gateway tuning: cost from real traffic, no-load estimates
- #478 gateway tuning: render and apply configuration with rollback
- #479 reasoning budget tuning for the review pool
- #480 review page size against quality and speed
- #481 embeddings through the gateway, with model evaluation
- #482 response and prefix cache effectiveness during reviews

* fix(security): close the keyring's remaining plaintext and host-credential gaps (#485)

* fix(security): close the keyring's remaining plaintext and host-credential gaps

Three follow-ups from #452, now that each devcontainer has its own keyring:

- gh falls back to hosts.yml whenever the keyring is locked at login, and
  that copy wins over the keyring afterwards. post-start and unlock-keyring
  now name every host with a plaintext token and print the command that
  moves it into the keyring without minting a new one. They never print the
  token itself.
- git fetched github.com through VS Code's helper, which forwards to the
  host's credential store. containerEnv now routes github.com and
  gist.github.com through `gh auth git-credential`. Command-scope config is
  read last, so its empty reset drops every earlier helper. A locked
  keyring now fails the fetch instead of falling back to the host.
- _ensure_keyring_backend checked only the top-level backend. The
  ChainerBackend keyring picks when several backends are viable falls
  through to the next one on a failed write, so a plaintext backend behind
  a locked Secret Service could receive the secret. Every chained backend
  must now be encrypted.
- A locked keyring now raises KeyringLockedError naming the unlock command,
  instead of a generic storage failure. Reads log the same hint.

Closes #452

* fix(devcontainer): keep URLs intact when stripping JSONC comments

The manifest validator removed everything after `//` on a line, including
inside strings. So the new `credential.https://githubproxy.fjygbaifeng.eu.org.helper` keys lost
their closing quotes and CI's smoke test rejected the manifest. Any URL in a
string value would have done the same. Strings are now matched first and
kept whole.

The locked-keyring warnings also stop naming the secret they failed to read.
CodeQL treats data derived from secret key names as sensitive when logged,
and the hint to run `unlock-keyring` doesn't depend on the name.

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* feat(ai): devops ai gateway tune measures capacity and cost per backend and recommends weights (#484)

* feat(ai): devops ai gateway tune measures capacity and cost per backend and recommends weights

The gateway's weights, context limits and per-replica entries are set by
hand. `devops ai gateway tune` measures every deployment of a model
group on its own and recommends weight = capacity / cost, read-only:

- Capacity: fixed-length (ignore_eos) completion tokens/s at the best
  of several concurrency levels, with a unique prefix per request so
  vLLM's prefix cache cannot skip prompt processing.
- Cost: the model's natural reply length on a review-style prompt.
- Prompts default to one review page for the analysis task's window,
  capped below each deployment's max_input_tokens.
- Hardware per backend: engine (vLLM KV-cache capacity from /metrics,
  or Ollama) and GPUs from nvidia-smi, with memory bandwidth.

The backends admit only the gateway, so the sweep (gateway_bench,
standard library only) runs in an ephemeral python:3.14-slim container
attached to the gateway pod (kubectl debug --profile=restricted); the
LiteLLM image's Python 3.13 rejects this project's 3.14 syntax. kubectl
calls that never reached the API server are retried.

fetch_model_info (from #469) is public for reuse. Test isolation now
builds a fresh console per test: a console cached at 80 columns before
COLUMNS was set truncated tables across a whole xdist worker.

Closes #470

* docs(agent): link task 470 to its PR

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(cli): read the devcontainer name for SSH key prefixes despite URL strings (#488)

* fix(cli): read the devcontainer name for SSH key prefixes despite URL strings

_resolve_prefix_from_devcontainer stripped JSONC comments with
re.sub(r"//.*$"), which also cuts every string holding `//`. Since #485,
devcontainer.json holds "credential.https://githubproxy.fjygbaifeng.eu.org.helper" values,
so the manifest stopped parsing and SSH keys were named after the
checkout directory. In a checkout not named devops-cli (a worktree),
test_ssh_generate_key_collision failed and the pre-push hook blocked
pushes. The devcontainer command had already fixed the same bug with a
string-aware stripper; this copy was missed.

Move that stripper to devops_cli.core.serialization.strip_json_comments
and use it in both places.

Closes #487

* docs(agent): link task 487 to its PR

* feat(devcontainer): unlock the keyring as the devcontainer starts (#490)

The keyring came up locked on every container start and stayed that way
until someone remembered to run `devops devcontainer unlock-keyring`.
Unlocking now happens as part of initialization:

- post-start prompts for the password on the pty VS Code gives lifecycle
  commands. An unwatched prompt gives up after 60 seconds, so it never
  stalls the start.
- If nobody answers, a post-create shell hook asks in the first interactive
  terminal. It runs only while post-start's pending marker exists, so
  shells opened after the unlock pay nothing. flock keeps restored
  terminals from all prompting at once.
- Once unlocked, plaintext gh tokens are moved into the keyring by logging
  in again with the same token, which mints nothing. The move is skipped
  when GH_TOKEN would override it.

This also fixes the unlock command itself. The replacement daemon now
starts in its own session. Started from a terminal, it was hung up when
that terminal closed, so D-Bus activated a fresh, locked daemon on the next
request.

Tests no longer read the developer's real gh login: an autouse fixture
points GH_CONFIG_DIR at a temp dir.

Refs #452

* docs(ai): record the devops-review weights A/B and keep 5/3/1/1 (#491)

Three iterations on real reviews, order alternated, with the loaded
weights confirmed each run. The tuner's 3/5/1/2 was faster every time
(median 185 s against 229 s, 39% less time per candidate), but it
reported more findings, including top-severity false positives that
passed verification ("Hardcoded Secrets" on registry-mirror URLs).
5/3/1/1 stays, and verification moves to its own model task (#486).

Closes #476

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* chore(github): task files link their issue only; PR and review state stay on GitHub (#492)

A task file's PR field could only be filled once the pull request
existed, so it took a second commit that re-ran every check and was
itself a prohibited standalone tracking commit. An In Review status went
stale the moment the PR merged. The files had drifted: 173 carried a PR
line, statuses included In Review, Merged, Completed and Closed, and the
project-sync parser read Merged and Closed as Backlog.

- A task file links its issue only. The issue links the pull request
  that closes it (`Closes #N`); project cards take In Review from that
  open PR (infer_item_status), never from the file.
- Statuses: Backlog, Ready, In Progress, Done. The delivering commit
  writes Done.
- The roadmap sync stops writing **PR**; the task parser no longer maps
  anything to In Review.
- Migrated every task file: PR lines removed, statuses set from each
  issue's GitHub state (closed -> Done), bare #N references linked, and
  the one task delivered without an issue linked to its PR (#182).
- AGENTS.md and the task README describe issue-only linking and drop
  the rule to open a draft, set In Review and fill in the PR field.
- tests/test_agent_task_files.py enforces the format.

Closes #489

* feat(ai): record the backend that served each gateway call in the spend ledger (#493)

The gateway picks a deployment for every call, but devops-cli recorded
only the gateway itself (server is the gateway host, backend_info reads
"gateway (<host>)"), so cost, latency and review quality could not be
attributed to the backend that did the work.

- The OpenAI-compatible client reads the gateway's
  x-litellm-model-api-base header into LLMResponse.served_by; streamed
  responses pass it through a context variable, since a stream's spend
  is recorded after its last chunk. Without the header it stays None.
- The spend ledger gains an indexed served_by column, added in place to
  existing ledgers.
- LifetimeSpendReport.backends and `devops ai cost report --by backend`
  break calls down by serving backend, with completion tokens per
  request and mean duration.

Verified live: eight devops-review calls split 4/2/2 across the dual-GPU
vLLM, single-GPU vLLM and an Ollama node, matching the 5/3/1/1 weights.

Closes #474

* feat(review): let review verification use its own model task (#495)

One LLM client, built from the analysis task, served persona review and
finding verification, so generation and verification had to share
gateway weights.

- ai.tasks.verification: an AITaskOverride layered on the analysis task,
  so it only names what differs. Unset, reviews verify with the analysis
  client, as before.
- ReviewClients.verification (defaults to analysis) feeds both
  verification call sites: pipeline stage 4 and per-segment verification
  in the runner. Stage 4 names the verification model it uses.
- Remove the unused _resolve_review_clients, which ignored its task.

Validated live: tuned weights (3/5/1/2) with the 32B model verifying
were slower (median 284 s against 229 s), one run stalled on an uncapped
verification reply (#494), nearly every candidate was rejected, and the
registry-mirror HTTP false positive still passed. The setting ships
unset; the false positive is a verification-prompt problem (#413, #475).

Closes #486

* fix(review): cap verification and persona review replies (#496)

Review requests carried no reply limit, so a reply could run until the
model's context filled. One verification call on the 32B model took
10 min 18 s and more than doubled a review's wall time.

- limit_completion_tokens(n) sets a per-call cap carried in the context,
  as request priority is. Each provider takes the smaller of it and the
  configured max_tokens: OpenAI-compatible max_tokens (or
  max_completion_tokens for reasoning models, streams included), Ollama
  num_predict, Claude max_tokens.
- Verification replies: 2048 tokens plus 384 per finding, at most 8192,
  reasoning included. A truncated verdict fails to parse and leaves its
  findings unverified with the existing note, not invalidated.
- Persona review replies: 8192 tokens, in the pipeline and the runner.

Verified live: an all-persona review finished in 200 s (229 s median
before), 13 of 50 candidates reported, every file verified in 11-37 s.

Closes #494

* feat(review): profile each review stage and benchmark reviews by their medians (#497)

Every review writes profile.json beside its findings: wall time, LLM calls,
prompt and completion tokens and serving backends per stage, observed through
the spend ledger, with candidate, verified and reported finding counts.

devops review benchmark reviews the same files N times with the response cache
bypassed and saves the medians, seconds per candidate finding and a digest of
the reviewed files under .data/reviews/benchmarks/.

Closes #473

* feat(review): synthetic defect corpora and recall scoring for reviews (#501)

devops review corpus generate copies the files a review reads and injects one
known defect into each, chosen by a seed, from nine templates. The manifest sits
outside the reviewed tree, and the corpus carries the source's conventions file;
conventions are now read nearest-first up to the repository root.

devops review corpus score matches a session's findings to the injections by
line region or named evidence and separates found from reported. Reviews now
write candidates.json, every finding with its verification status, since
findings.json keeps only the reported ones.

Tracks the defects the first corpus run surfaced: #498, #499 and #500.

Closes #415

* fix(ai): call a text output function only when it takes the text alone (#511)

A text output function may take a RunContext and the text, or be async. The
repair path called it with the text alone, so a context-taking function raised
into a bare except and the reply went unparsed, and an async one returned an
un-awaited coroutine as the parsed model. ty v0.0.84 rejects the call. The
function now runs only when it is synchronous and takes the text alone.

Closes #510

* docs(roadmap): focus v0.2.23 on devops ai and plan multi-language validation (#507)

Keep v0.2.23 to devops ai review quality, LLM routing and validation, and move
the remaining work to the releases whose themes fit it: operations and CLI
surface to v0.2.24, guardrails and hygiene to v0.2.25, the capability survey to
v0.3.0, and code scanning and image packaging to v0.3.5.

Plan pinned open-source sample repositories across application languages,
infrastructure code and documentation, synthetic defect templates for each, a
validation run over them, AST support for the languages the engine lacks, and
the audit of every mechanism that discards or invents findings with its fixes.

Refs #502, #503, #504, #505, #506, #509, #512, #513, #514, #515, #516

* fix(review): keep findings the pipeline lost before the report (#517)

Scanner findings seeded into a file's payload were overwritten by the persona
findings, and wiped on any review error. One malformed field dropped a whole
reply, and stray braces in prose or a quoted <think> truncated it. Distinct
defects were merged on a shared filler word or at distant lines. Real titles
were blanked as praise or reasoning, a persona could set its own verification
status, and redaction rewrote code expressions as masked secrets.

Seeded findings are kept, a reply keeps every valid finding, merging needs
agreeing distinguishing words, and redaction masks secret values only. OSV is
queried only for exact versions, and threat-intel host findings enter
verification unverified.

Closes #512

* fix(review): verification leaves real findings alone unless evidence refutes them (#518)

Deterministic checks fired on substrings of a finding's wording: "syntax" in
"f-string syntax", "sse" in "processed", English "if none of", "not properly
implemented". A line past the end of the file, which is the model's own count,
invalidated the finding. The runtime floor was devops-cli's own, an auth header
anywhere in a module cleared every request in it, and a real secret in tests/
or behind a redaction marker was dismissed.

Verdicts read "false" and "none" as truthy, let invalidation criteria override
a confirmation, hid a finding the verifier declined to confirm, and bound by a
shared line or a missing title to the wrong finding.

Each check now fires on the claim it is for, verdicts are read as meant, only
clear refutation removes a finding, and verdicts bind by title.

Closes #513

* fix(ci): preserve intentional two-space markdown linebreaks in trailing-whitespace pre-commit hook (#520)

* fix(review): the missing-symbol check acts on undefined-symbol claims only (#508)

It ran on any finding containing "missing" and invalidated it when a symbol it
named existed. A finding about a missing check names the function that lacks it,
so real defects were invalidated without a model and recorded into the
hallucinations catalog. It now runs only on claims that a name is undefined or
unimportable.

Closes #500

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(release): a shipped release closes its epic while the roadmap header lags (#522)

Release epic #297 stayed open after v0.2.22 shipped. The epic sync closed an
epic only when its hand-edited roadmap header said Completed, and each release
had marked the previous one done a release late, so v0.2.22 still read
"Active Release". The sync now treats a closed milestone as a completed release.

The roadmap marks v0.2.22 Completed and v0.2.23 the active release, and ticks
the eight v0.2.22 entries whose issues closed as completed, with their PRs.

Closes #521

* fix(review): the hallucinations catalog learns only from evidence and keeps builtins fixed (#523)

Th…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects

Development

Successfully merging this pull request may close these issues.

2 participants