Repository navigation
feat(docs): implement document compaction engine and enhance review self-improvement loop - #138
Conversation
…elf-improvement loop - Author DocCompactor engine supporting roadmap, release notes, and log compaction - Integrate devops docs compact subcommand with check, dry-run, and series filtering - Expose docs_compact tool on FastMCP server and synchronize MCP JSON schemas - Harden reference extractor to exclude glob patterns, examples, and stdlib prefixes - Resolve executive summary reporting error handling for skipped and errored files - Enhance review prompts and system instructions for closed-loop self-improvement - Constrain Loki logging NetworkPolicy ingress to ingress-nginx controller - Add comprehensive test suites for compaction engine and MCP tools Closes #137
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings remain in compaction, error handling, CLI state management, and secret sanitization.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This pull request adds automated documentation compaction through the CLI and FastMCP, while improving review reporting, security sanitization, documentation, and network policy.
Changes:
- Added
DocCompactor,devops docs compact, thedocs_compactMCP tool, and tests. - Enhanced review reporting, reference extraction, context packing, and secret handling.
- Updated documentation, knowledge-base content, configuration examples, and Loki ingress policy.
File summaries
| File | Description |
|---|---|
tests/test_review_report_summary.py |
Tests errored-file summaries. |
tests/test_reference_extractor.py |
Tests reference filtering. |
tests/test_mcp.py |
Tests MCP delegation. |
tests/test_github_issues.py |
Tests bounded issue-title details. |
tests/test_fastmcp_contracts.py |
Verifies tool registration. |
tests/test_docs_compactor.py |
Tests compaction behavior and CLI. |
tests/test_context_packer.py |
Tests linear pruning. |
tests/test_consolidation_security_sanitizer.py |
Tests secret masking paths. |
src/devops_cli/security/sanitizer.py |
Hardens token regex boundaries. |
src/devops_cli/security/reference_extractor.py |
Filters code and template references. |
src/devops_cli/lang/en/messages.py |
Adds compaction messages. |
src/devops_cli/lang/en/help.py |
Adds compaction help text. |
src/devops_cli/github/issues.py |
Bounds issue-title error details. |
src/devops_cli/exceptions/docs.py |
Defines the compaction exception. |
src/devops_cli/exceptions/__init__.py |
Exports the exception. |
src/devops_cli/docs/compactor.py |
Implements documentation compaction. |
src/devops_cli/docs/__init__.py |
Exports compaction models. |
src/devops_cli/config/env.py |
Updates endpoint configuration. |
src/devops_cli/config/constants.py |
Adds the compaction error code. |
src/devops_cli/commands/docs.py |
Adds the docs compact command. |
src/devops_cli/ai/tasks/verify_finding_system.md |
Extends verification guidance. |
src/devops_cli/ai/tasks/review.md |
Extends review guidance. |
src/devops_cli/ai/review/stages/reporting.py |
Supports errored-file summaries. |
src/devops_cli/ai/review/pipeline.py |
Records review errors. |
src/devops_cli/ai/mcp/server.py |
Adds the docs_compact tool. |
src/devops_cli/ai/mcp/__init__.py |
Exports the MCP tool. |
src/devops_cli/ai/knowledge_base/it_domains/topics/agentic_ai_and_code_reviews.md |
Updates review guidance. |
src/devops_cli/ai/knowledge_base/it_domains/tools/ollama.md |
Updates endpoint examples. |
src/devops_cli/ai/knowledge_base/devops_cli/tasks/ai_code_review.md |
Updates review safeguards. |
src/devops_cli/ai/knowledge_base/devops_cli/configuration_and_settings.md |
Updates configuration examples. |
src/devops_cli/ai/context_packer.py |
Optimizes AST pruning. |
README.md |
Documents the new command. |
k8s/logging/networkpolicy.yaml |
Restricts Loki ingress. |
docs/MCP_TOOLS.md |
Documents the MCP tool. |
docs/LOG.md |
Records remediation work. |
docs/ERRORS.md |
Documents the new error code. |
docs/ENV_VARS.md |
Updates endpoint documentation. |
docs/commands/docs.md |
Documents CLI options. |
docs/CLI_REFERENCE.md |
Updates the CLI reference. |
docs/agent/tasks/task-137-docs-compaction-engine.md |
Tracks the implementation task. |
AGENTS.md |
Adds security and feedback-loop requirements. |
Review details
Suppressed comments (11)
docs/agent/tasks/task-137-docs-compaction-engine.md:5
- The task-file template requires a
**PR**field between the issue and status entries (docs/agent/tasks/README.md:40-45), but this new task file omits it. Add the current PR number so project/task synchronization can link the deliverable to this review.
**Issue**: [#137](https://github.com/dan-petty/devops-cli/issues/137)
**Status**: In Review
**Milestone**: `v0.2.16`
src/devops_cli/commands/docs.py:255
- When callers pass more than one
--*-onlyflag, this precedence silently chooses roadmap-only and ignores the other requested targets. That makes a seemingly successful command fail to honor its arguments; reject conflicting flags (or explicitly support a multi-target mode) instead of silently prioritizing the first one.
if roadmap_only:
return True, False, False
if release_notes_only:
return False, True, False
if log_only:
src/devops_cli/commands/docs.py:280
- This new subcommand performs multiple file reads, transformations, and writes without an OpenTelemetry span or
GLOBAL_METRICSinstrumentation, contrary to the repository requirement for new subcommands (AGENTS.md:229). Compaction latency and failures will therefore be invisible to the command telemetry; wrap the operation in the standard span/metric instrumentation.
@app.command(name="compact")
def compact_cmd(
src/devops_cli/docs/compactor.py:181
- These matches are based only on the version prefix, so default
v0.2compaction includes the current/scheduled roadmap blocks (v0.2.15,v0.2.16, andv0.2.17indocs/ROADMAP.md) and replaces them with aCompletedsummary; the matrix rows are similarly collapsed as✅ Completed. Restrict candidates to explicitly completed headers/rows so the command cannot erase active roadmap state.
matching_blocks = [
b for b in blocks if _version_matches_series(b.group(2), normalized_series)
]
src/devops_cli/docs/compactor.py:141
- After the first compaction, the generated header
(... v0.2.0 – v0.2.17 - Completed)still matches_extract_roadmap_versions, but onlyv0.2.0is captured, so a second run rewrites the range tov0.2.0 – v0.2.0. Consequently--checknever becomes clean after compaction; detect an already consolidated block or preserve its full range before rebuilding.
def _extract_roadmap_versions(self, text: str, series: str) -> list[str]:
"""Extract all version numbers matching series in Section 2."""
pattern = r"###\s+.*?\((v\d+\.\d+\.\d+).*?\)"
matches = re.findall(pattern, text)
return [v for v in matches if _version_matches_series(v, series)]
src/devops_cli/docs/compactor.py:306
archive_entryis inserted whenever the description line is encountered, without checking for an existing archive link or whether new blocks were archived. On the second run this adds another identicalHistorical Sprint Archivessection and marksLOG.mdmodified, so--checkkeeps failing after the first compaction. Make log compaction idempotent.
archive_entry = (
f"### Historical Sprint Archives\n"
f"- [{normalized_series}.x Series Log](agent/archive/historical-phases-{normalized_series}.x.md): "
f"Consolidated sprint logs for {normalized_series}.x development phases.\n\n---\n"
)
src/devops_cli/docs/compactor.py:375
- The two writes are not coordinated:
LOG.mdis replaced before the archive file is written. If the archive write fails (permissions, disk-full, or an invalid destination), the log already points to a missing/incomplete archive, and earlier roadmap/release-note writes may also have succeeded. Prepare/validate all outputs first and commit them with rollback or write the archive before publishing the pointer.
if not dry_run and not check:
write_text_file(log_path, compacted_log)
write_text_file(archive_file, archive_content)
src/devops_cli/docs/compactor.py:128
- The matrix predicate also treats any target-series row as completed. That will replace the current roadmap's scheduled v0.2.15–v0.2.17 rows with
_SERIES_MATRIX_SUMMARIES, whose status is✅ Completed, losing planned work. Require a completed status before including a row in the compacted summary.
return len(row_cells) >= 6 and _version_matches_series(row_cells[5], normalized_series)
src/devops_cli/docs/compactor.py:340
- Although this PR introduces
DocCompactionError,compact_allperforms rawPath.read_text/write_text_fileoperations without translating failures into that domain exception. Permission, decoding, or race errors can therefore escape as built-in exceptions and the new canonical error code is never used. Wrap the filesystem boundaries and raiseDocCompactionErrorwith bounded series/path details.
orig_text = roadmap_path.read_text(encoding="utf-8")
src/devops_cli/docs/compactor.py:372
- The archive is only considered when
compacted_log != orig_text. IfLOG.mdis already compacted buthistorical-phases-<series>.x.mdwas deleted or is missing, this path reports up-to-date and never recreates or flags the required archive. Check archive existence (and, if needed, its content) as part of the compacted state.
if compacted_log != orig_text:
result.log_compacted = True
archive_file = archive_dir / f"historical-phases-{normalized_series}.x.md"
result.archive_file_path = str(archive_file)
modified_files.append(str(log_path))
src/devops_cli/exceptions/docs.py:15
- Although
DocCompactionErroris introduced and exported, no compactor or CLI path raises it.read_textandwrite_text_filefailures incompact_alltherefore still escape as raw I/O exceptions/tracebacks instead of the advertisedDOC_COMPACTION_ERRORdomain error; wrap compaction I/O and convert failures to this exception.
class DocCompactionError(DevOpsCLIError):
"""Exception raised when documentation compaction fails."""
- Files reviewed: 41/41 changed files
- Comments generated: 9
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
…nment, and syntax boundaries - Sanitize and bound error strings in pipeline errored_files registry to <= 256 chars - Enforce strict regex validation and archive directory containment for release series - Use negative lookbehind boundaries for secret tokens to support underscore identifiers - Restore process dry-run state via try/finally in docs compact CLI command - Refine log header version extraction and eliminate hardcoded series strings - Populate roadmap and release notes section counters in DocCompactionResult - Truncate caller-provided details in DocCompactionError to 256 characters - Replace hardcoded package prefixes with dynamic importlib package introspection
* docs(changelog): document v0.2.15 release highlights and features (#105) * docs(changelog): document v0.2.15 release highlights and features * docs(changelog): clarify k8s logs invocation and list all 11 security scanners * docs(agents): update agent instructions to honor API rate limits and quotas (#130) * docs(agents): update agent instructions to honor API rate limits and quotas - Add API rate limiting, complexity budgeting, and quota guidelines to AGENTS.md across core engineering, GitHub integration, and AI inference. - Synchronize DEVOPS_CLI_AGENTS_METADATA_TEMPLATE in instruction_generator.py with rate-limiting rules. - Add regression test assertions to test_instruction_generator.py. - Track deliverable in task-129-agent-instructions-rate-limits.md. Closes #129 * docs(agents): include AI inference rate limits and expand generator test assertions * docs(agents): make semaphore example executable and link PR in task tracking * feat(ai): render chat persona title in orange styling (#133) * feat(ai): render chat persona title in orange styling - Render persona title in bold dark_orange in chat section header rule - Output persona reply prompt in bold dark_orange using Rich console - Preserve bold cyan styling for 'You:' user prompt - Update unit tests in test_ai_cmd.py asserting persona and user prompt colors Closes #132 * test(ai): assert dark_orange section header styling and update task status to In Review * fix(k8s): review pod restarts, eliminate cgroup oom kills, and optimize workload resource limits (#136) * fix(k8s): review pod restarts, eliminate cgroup oom kills, and optimize workload resource limits - Remove hard memory limits on Ollama DaemonSet (leaving requests at 3000m CPU and 8Gi RAM), allowing dynamic memory bursting into available node RAM without cgroup OOM kills - Add startupProbe to Ollama DaemonSet with 5-minute failure threshold for cold starts and large model weight loading - Relax Ollama livenessProbe (10s timeout, 15s period, 6 failure threshold) to prevent premature kubelet SIGKILL terminations during heavy inference - Raise memory and CPU limits across core workloads (ArgoCD controller, repoServer, server, and Redis; Valkey; Jaeger; Registry; Fluent Bit; and Loki) - Add comprehensive regression tests in tests/test_k8s.py verifying resource limit invariants and probe resilience - Create task tracking document docs/agent/tasks/task-135-k8s-pod-restarts-resource-limits.md Closes #135 * fix(k8s): bound Ollama memory limit, enforce probe contracts, and assert all resource changes * feat(k8s): deploy squid caching proxy with ssl bump, observability, and failover handling (#134) * feat(k8s): deploy squid caching proxy with ssl bump, observability, and failover handling - Deploy high-capacity Squid caching proxy configured for 100GB single objects - Enable SSL-Bump TLS interception with dynamic cert generation for Ollama 70B layers - Add Prometheus observability via squid-exporter sidecar on port 9301 - Enable structured JSON access logging to stdout and Cache Manager API - Implement LFUDA dynamic aging eviction with proactive high/low watermarks (92%/85%) - Integrate Squid proxy env vars and CA certificate mount in ollama-daemonset - Document failover architecture across node crash, WAN outage, and storage domains - Add comprehensive unit test suite in test_k8s_squid.py Closes #131 * fix(docker): format and sort imports in _client helper * refactor(k8s): relocate squid docker assets to k8s/squid/docker to prevent SDK namespace shadowing * feat(k8s): add condor node affinity for high-capacity 1.8TB NVMe storage allocation * fix(docker): format import order in client builder * fix(k8s): resolve review feedback on squid probes, egress policy, ca sync, and chown * feat(docs): implement document compaction engine and enhance review self-improvement loop (#138) * feat(docs): implement document compaction engine and enhance review self-improvement loop - Author DocCompactor engine supporting roadmap, release notes, and log compaction - Integrate devops docs compact subcommand with check, dry-run, and series filtering - Expose docs_compact tool on FastMCP server and synchronize MCP JSON schemas - Harden reference extractor to exclude glob patterns, examples, and stdlib prefixes - Resolve executive summary reporting error handling for skipped and errored files - Enhance review prompts and system instructions for closed-loop self-improvement - Constrain Loki logging NetworkPolicy ingress to ingress-nginx controller - Add comprehensive test suites for compaction engine and MCP tools Closes #137 * fix(docs): resolve review feedback on error sanitization, path containment, and syntax boundaries - Sanitize and bound error strings in pipeline errored_files registry to <= 256 chars - Enforce strict regex validation and archive directory containment for release series - Use negative lookbehind boundaries for secret tokens to support underscore identifiers - Restore process dry-run state via try/finally in docs compact CLI command - Refine log header version extraction and eliminate hardcoded series strings - Populate roadmap and release notes section counters in DocCompactionResult - Truncate caller-provided details in DocCompactionError to 256 characters - Replace hardcoded package prefixes with dynamic importlib package introspection * feat(ai): format chat responses as rich markdown and failover ollama models * docs(roadmap): add agentic sandbox iteration architecture tasks * feat(k8s): enable squid caching forward proxy cluster-wide and resolve root ca (#143) * feat(k8s): enable squid caching forward proxy cluster-wide and resolve root ca * feat(ai): support chat model cli overrides and map llm gateway to roadmap * fix(k8s): address copilot review on squid proxy security and ca rotation * feat(k8s): enable in-cluster squid proxying, store-id caching, and loopback rewriting * fix(k8s): resolve pod restarts on gpu-feature-discovery and prometheus stack with burstable qos * docs(agent): reconcile task lifecycles for v0.2.16 milestone release merge * docs(devcontainer): align devcontainer usage guide with modern best practices (#145) * docs(devcontainer): align devcontainer usage guide with modern best practices * docs(devcontainer): address peer review feedback and improve configuration examples * docs: remove obsolete development log and redundant pending features docs (#146) (#147) * docs: remove obsolete development log and redundant pending features docs (#146) * docs(agent): update task 146 status to in review with PR #147 * docs(routine): distinguish docs compaction from manual task archival * refactor(core): decouple circular module imports and streamline convoluted import patterns (#148) (#149) * refactor(core): decouple circular module imports and streamline convoluted import patterns (#148) * fix(test): resolve child module import edges in invariant check and decouple config settings (#148) * fix(k8s): route stack lifecycle run_subprocess and forward patches to _stack_lifecycle (#148) * docs(architecture): document pre-1.0 alpha status, zero legacy remnants, and post-1.0 semver policy (#150) (#151) * docs(architecture): document pre-1.0 alpha status, zero legacy remnants, and post-1.0 semver policy (#150) * docs(security): sanitize homelab configurations and align release manuals with pre-1.0 alpha policy - Fix Copilot review feedback on RELEASE_CYCLE.md: use generic SemVer placeholders X.Y.0 and X.Y.Z - Fix Copilot review feedback on knowledge base: qualify release_management.md and release_engineering_and_semver_governance.md with pre-1.0 alpha zero backwards compatibility policy vs post-1.0 SemVer 2.0.0 governance - Sanitize internal hostnames, RFC 1918 IPs, and hardware mount paths across k8s/squid/deployment.yaml, tests/test_k8s_squid.py, docs/ROADMAP.md, docs/squid-failover-and-observability.md, and docs/agent/tasks/ - Update AGENTS.md and instruction_generator.py with comprehensive prohibitions against recording internal infrastructure details - Ground changes in Issue #152 and docs/agent/tasks/task-152-sanitize-internal-systems-and-strengthen-instructions.md * docs(security): gate pre-1.0 alpha notice on devops-cli and sanitize cluster network docs (#152) (#153) * docs(security): gate pre-1.0 alpha notice on devops-cli and sanitize cluster network docs (#152) - Gate pre-1.0 alpha notice on meta.is_devops_cli across generate_pointer_stub, generate_instruction_content, and generate_agents_md so external scaffolded projects do not receive DevOps CLI-specific alpha notices - Update test_instruction_generator.py to verify is_devops_cli gating behavior on pointer stubs and AGENTS.md - Sanitize LAN speed reference in docs/squid-failover-and-observability.md to local cluster network speed - Update task tracking in docs/agent/tasks/task-152-sanitize-internal-systems-and-strengthen-instructions.md * docs(agent): update task-152 PR reference to #153 * test(ai): assert absence of pre-1.0 alpha lifecycle block for generic external projects * fix(security): remediate devsecops findings and consolidate embedding configuration (#154) (#155) * fix(security): remediate devsecops findings and consolidate embedding configuration (#154) - Remediate review session findings for credential leakage, injection, and resource exhaustion - Consolidate embedding configuration under ai.tasks.embedding and remove duplicate keys from rag - Add offline fallback to tldextract and test-wide network egress guard - Protect local user runtime config.yaml from automated sanitization rewrites - Enhance review falsification rules, feedback export, and common hallucinations catalog * fix(security): remediate pr 155 review comments and exclude documented example network references (#154) * docs(roadmap): add milestones v0.2.19, v0.2.20, and v0.2.21, and mark task 154 complete * chore(release): bump version to v0.2.16 and finalize changelog * feat(sandbox): implement long-running workload sandbox lifecycle engine (#157) * feat(sandbox): implement long-running workload sandbox lifecycle engine * docs(agent): update task 106 tracking to In Review with PR 157 * feat(sandbox): remediate pr review findings, update agent instructions, and resolve threads * fix(sandbox): address bandit b108 tmpfs mount false positive and format * docs(roadmap): reprioritize roadmap and redistribute features across v0.2.17-v0.2.19 * feat(ci): automatically apply formatting and linting across CLI and CI commands (#159) * feat(ci): automatically apply formatting and linting across CLI and CI commands (#158) - Default --fix to True on devops ci, devops ci format, and devops ci lint - Support --check flag for non-mutating validation - Introduce top-level devops format and devops lint CLI commands with clean usage - Move _layouts/ and assets/ to docs/ for Jekyll GitHub Pages compliance - Prevent event loop deadlock in introspect_mcp_tools and offload check_docs - Update test suites, architectural invariants, and documentation * fix(docs): address PR 159 review comments on executor cleanup, alias docs, and jekyll layout - Introspect leaf command aliases directly so devops format and devops lint generate clean leaf command usage rather than inheriting all ci subcommands - Implement non-blocking thread pool executor cleanup with wait=False, cancel_futures=True and asyncio.wait_for in introspect_mcp_tools - Remove /docs/ prefix in docs/_layouts/default.html navigation and footer links to prevent 404s on GitHub Pages - Configure default layout in docs/github-pages.config.yaml for Jekyll markdown pages - Synchronize task tracking and regenerate documentation * chore(tasks): mark task-158 as done upon PR #159 merge * fix(release): add release notes extraction fallback and enforce changelog version check (#140, #160) Resolves release orchestration failures where release notes extraction fails due to missing version headers or changelog discrepancies: - Strictly enforce matching version in CHANGELOG.md during devops release check (fatal Exit 1) - Implement layered fallback extraction across CHANGELOG.md -> docs/RELEASE_NOTES.md -> git commit log - Defensive fallback to git commit log in .github/workflows/release.yml - Decompose release_check to maintain cyclomatic complexity <= 10 - Comprehensive unit tests in tests/test_release.py * chore(tasks): mark task-140 as done upon PR #160 merge * docs(release): update v0.2.16 changelog and release notes highlights * fix(review): address PR 161 comments on sandbox port allocation, secret lookbehind, and gfd image * fix(sandbox): align requested_ports type annotation in SandboxRegistry with allocate_ports
Summary
This pull request implements the automated documentation compaction engine (
devops docs compactandDocCompactor) fulfilling the SDLC requirements defined inAGENTS.md(Section 3: Mandatory Historical Documentation Compaction on Major & Minor Releases) anddocs/ROUTINE_TASKS.md(Cadence C, Step 8). It also hardens the review loop, reporting, reference extraction, and network policies.Key Changes
src/devops_cli/docs/compactor.py):DocCompactorclass providing roadmap, release notes, and sprint log compaction for completed release series (v0.2.x).--check,--dry-run,--series,--roadmap-only,--release-notes-only, and--log-only.devops docs compactintegrated intosrc/devops_cli/commands/docs.pywith localized help messages and dry-run decorators.docs_compacttool insrc/devops_cli/ai/mcp/server.pyand re-exported insrc/devops_cli/ai/mcp/__init__.py.devops mcp export-schemas.errored_filessupport tosynthesize_report_executive_summaryinreporting.pyandpipeline.py.reference_extractor.pyagainst glob wildcards, example template configs, and stdlib modules.ingress-nginxnamespace selector.DocCompactorintests/test_docs_compactor.py(10 passed).tests/test_mcp.pyand contract assertions intests/test_fastmcp_contracts.py.Closes #137