From b7eb969274a95b26f620a3a45591bca74c9881a8 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 12:53:37 -0300 Subject: [PATCH 01/39] docs: add performance remediation specs --- .context/skills/README.md | 28 +- .context/skills/bound-mcp-payloads/SKILL.md | 52 ++ .../bound-mcp-payloads/agents/openai.yaml | 4 + .../skills/bound-subprocess-output/SKILL.md | 52 ++ .../agents/openai.yaml | 4 + .../skills/govern-cache-retention/SKILL.md | 61 +++ .../govern-cache-retention/agents/openai.yaml | 4 + .../manage-lsp-process-lifecycle/SKILL.md | 50 ++ .../agents/openai.yaml | 4 + .../skills/sanitize-hook-payloads/SKILL.md | 50 ++ .../sanitize-hook-payloads/agents/openai.yaml | 4 + .../skills/share-semantic-analysis/SKILL.md | 44 ++ .../agents/openai.yaml | 4 + .../skills/stream-runtime-history/SKILL.md | 45 ++ .../stream-runtime-history/agents/openai.yaml | 4 + MEMORY_PERFORMANCE_AUDIT.md | 486 ++++++++++++++++++ specs/performance/README.md | 62 +++ .../f-01-bound-subprocess-output.md | 116 +++++ .../f-02-sanitize-hook-payloads.md | 119 +++++ .../f-03-stream-runtime-history.md | 135 +++++ .../performance/f-04-lsp-process-lifecycle.md | 111 ++++ .../f-05-shared-semantic-analysis.md | 121 +++++ specs/performance/f-06-bound-mcp-payloads.md | 121 +++++ specs/performance/f-07-cache-retention.md | 123 +++++ 24 files changed, 1794 insertions(+), 10 deletions(-) create mode 100644 .context/skills/bound-mcp-payloads/SKILL.md create mode 100644 .context/skills/bound-mcp-payloads/agents/openai.yaml create mode 100644 .context/skills/bound-subprocess-output/SKILL.md create mode 100644 .context/skills/bound-subprocess-output/agents/openai.yaml create mode 100644 .context/skills/govern-cache-retention/SKILL.md create mode 100644 .context/skills/govern-cache-retention/agents/openai.yaml create mode 100644 .context/skills/manage-lsp-process-lifecycle/SKILL.md create mode 100644 .context/skills/manage-lsp-process-lifecycle/agents/openai.yaml create mode 100644 .context/skills/sanitize-hook-payloads/SKILL.md create mode 100644 .context/skills/sanitize-hook-payloads/agents/openai.yaml create mode 100644 .context/skills/share-semantic-analysis/SKILL.md create mode 100644 .context/skills/share-semantic-analysis/agents/openai.yaml create mode 100644 .context/skills/stream-runtime-history/SKILL.md create mode 100644 .context/skills/stream-runtime-history/agents/openai.yaml create mode 100644 MEMORY_PERFORMANCE_AUDIT.md create mode 100644 specs/performance/README.md create mode 100644 specs/performance/f-01-bound-subprocess-output.md create mode 100644 specs/performance/f-02-sanitize-hook-payloads.md create mode 100644 specs/performance/f-03-stream-runtime-history.md create mode 100644 specs/performance/f-04-lsp-process-lifecycle.md create mode 100644 specs/performance/f-05-shared-semantic-analysis.md create mode 100644 specs/performance/f-06-bound-mcp-payloads.md create mode 100644 specs/performance/f-07-cache-retention.md diff --git a/.context/skills/README.md b/.context/skills/README.md index 96a4e528..db775bec 100644 --- a/.context/skills/README.md +++ b/.context/skills/README.md @@ -27,6 +27,18 @@ On-demand expertise for AI agents. Skills are task-specific procedures that get | [Security Audit](./security-audit/SKILL.md) | Security review checklist for code and infrastructure | R, V | filled | | [Test Generation](./test-generation/SKILL.md) | Generate comprehensive test cases for code | E, V | filled | +### Performance Safety Skills + +| Skill | Description | Related Spec | +|-------|-------------|--------------| +| [Bound Subprocess Output](./bound-subprocess-output/SKILL.md) | Prevent unbounded stdout and stderr retention | [F-01](../../specs/performance/f-01-bound-subprocess-output.md) | +| [Sanitize Hook Payloads](./sanitize-hook-payloads/SKILL.md) | Keep hook inputs and traces bounded and redacted | [F-02](../../specs/performance/f-02-sanitize-hook-payloads.md) | +| [Stream Runtime History](./stream-runtime-history/SKILL.md) | Paginate traces, replay, datasets, and retention | [F-03](../../specs/performance/f-03-stream-runtime-history.md) | +| [Manage LSP Process Lifecycle](./manage-lsp-process-lifecycle/SKILL.md) | Prevent orphan language-server processes | [F-04](../../specs/performance/f-04-lsp-process-lifecycle.md) | +| [Share Semantic Analysis](./share-semantic-analysis/SKILL.md) | Reuse repository scans and semantic analysis | [F-05](../../specs/performance/f-05-shared-semantic-analysis.md) | +| [Bound MCP Payloads](./bound-mcp-payloads/SKILL.md) | Bound inputs, responses, serialization, and logging | [F-06](../../specs/performance/f-06-bound-mcp-payloads.md) | +| [Govern Cache Retention](./govern-cache-retention/SKILL.md) | Add cache budgets, TTL, invalidation, and cleanup | [F-07](../../specs/performance/f-07-cache-retention.md) | + ## Creating Custom Skills Create a new skill by adding a directory with a `SKILL.md` file: @@ -43,21 +55,12 @@ Create a new skill by adding a directory with a `SKILL.md` file: ```yaml --- -type: skill name: my-skill -description: When to use this skill -skillSlug: my-skill -phases: [P, E, V] # Optional: PREVC phases -mode: false # Optional: mode command? -status: filled -scaffoldVersion: "2.0.0" +description: What the skill does and the concrete tasks that should trigger it --- # My Skill -## When to Use -[Description of when this skill applies] - ## Instructions 1. Step one 2. Step two @@ -66,6 +69,11 @@ scaffoldVersion: "2.0.0" [Usage examples] ``` +Keep only `name` and `description` in frontmatter. Put all trigger conditions in +`description`, because discovery reads metadata before loading the skill body. The +folder name is the stable skill slug. Add `agents/openai.yaml` when UI metadata is +needed. + ## PREVC Phase Mapping | Phase | Name | Skills | diff --git a/.context/skills/bound-mcp-payloads/SKILL.md b/.context/skills/bound-mcp-payloads/SKILL.md new file mode 100644 index 00000000..9cc5c1ae --- /dev/null +++ b/.context/skills/bound-mcp-payloads/SKILL.md @@ -0,0 +1,52 @@ +--- +name: bound-mcp-payloads +description: Implement or review bounded MCP inputs and responses. Use for gateway response helpers, MCP Zod schemas, list actions, cursor pagination, maxEvents, JSON serialization, audit logging, response metadata, artifact exports, or payload-size and client-compatibility changes. +--- + +# Bound MCP Payloads + +Serialize once, paginate at the source, and keep transport metadata small. + +## Workflow + +1. Identify the harness result cardinality before shaping the MCP response. +2. Reuse harness cursor pagination; never paginate only after serialization. +3. Set Zod defaults and maxima for counts, string lengths, array lengths, and patterns. +4. Add serialized-byte validation for nested unknown objects. +5. Derive bounded audit metadata before serialization. +6. Serialize response content once and measure UTF-8 bytes. +7. Return a smaller-page hint or artifact reference when the response exceeds budget. +8. Test boundary values and existing client behavior. + +## Required invariants + +- Never JSON.parse response text for logging. +- Never truncate JSON at an arbitrary byte position. +- Never pretty-print large machine payloads. +- Never expose an unlimited list action. +- Never put content, prompts, messages, or secrets in audit metadata. +- Keep MCP adaptation thin; pagination belongs to harness. +- Preserve content text for clients that ignore _meta. + +## Response choices + +Use, in order: + +1. a normal bounded page; +2. a smaller suggested page after pageTooLarge; +3. an artifact/export reference for intentionally large output; +4. a typed rejection for oversized input. + +Do not increase the payload budget to accommodate an unbounded API. + +## Dotcontext routing + +- Keep reusable data limits in harness. +- Keep schema and response shaping in src/mcp/gateway or src/mcp/server. +- Update MCP docs and package smoke tests for public contract changes. +- Follow [F-06](../../../specs/performance/f-06-bound-mcp-payloads.md). + +## Review gate + +Require evidence that normal responses serialize once, list defaults are bounded, limit+1 is rejected, audit metadata stays content-free, and no successful response silently exceeds budget. + diff --git a/.context/skills/bound-mcp-payloads/agents/openai.yaml b/.context/skills/bound-mcp-payloads/agents/openai.yaml new file mode 100644 index 00000000..ce8416ab --- /dev/null +++ b/.context/skills/bound-mcp-payloads/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Bound MCP Payloads" + short_description: "Keep MCP responses paginated and bounded" + default_prompt: "Use $bound-mcp-payloads to review MCP response size, pagination, serialization, and logging." diff --git a/.context/skills/bound-subprocess-output/SKILL.md b/.context/skills/bound-subprocess-output/SKILL.md new file mode 100644 index 00000000..7f9e4cd0 --- /dev/null +++ b/.context/skills/bound-subprocess-output/SKILL.md @@ -0,0 +1,52 @@ +--- +name: bound-subprocess-output +description: Implement or review child-process execution with bounded stdout and stderr memory. Use for Node spawn wrappers, sensors, test runners, acceptance commands, timeout handling, output tails, truncation, or any change that captures subprocess output in the dotcontext harness. +--- + +# Bound Subprocess Output + +Keep memory proportional to configured diagnostics, never to total child output. + +## Workflow + +1. Identify what the caller actually needs: exit code, a tail, structured output, or a durable export. +2. Define separate byte limits for stdout, stderr, structured result files, and combined output before editing code. +3. Retain data online with a ring/tail buffer. Do not collect all chunks and trim at process exit. +4. Track total, retained, and dropped bytes without logging content. +5. Define explicit behavior for timeout, output ceiling, spawn error, non-zero exit, and malformed structured output. +6. Preserve shell:false and argv-array execution. +7. Add volume tests that exceed every limit. + +## Required invariants + +- Never let an array of chunks scale with total output. +- Never call Buffer.concat over the full historical stream. +- Measure limits in UTF-8 bytes, not JavaScript string length. +- Bound stdout and stderr independently. +- Apply hard ceilings while the process is running. +- Kill and reap the child when a hard ceiling or timeout fires. +- Expose truncated, droppedBytes, and termination reason. +- Persist only bounded tails in traces and plan tracking. + +## Structured test output + +Write large machine-readable results to a temporary file when a parser needs more than a tail. Check file size before reading, parse only required fields, and remove the file in finally. Keep console streams bounded even when using a result file. + +## Dotcontext routing + +- Put pure bounding rules in src/harness/domain. +- Keep subprocess orchestration in the existing harness execution or adapter boundary. +- Apply the same collector to sensors and plan acceptance. +- Follow [F-01](../../../specs/performance/f-01-bound-subprocess-output.md). + +## Review gate + +Reject the change if any answer is no: + +- Is there a documented default and absolute maximum? +- Does memory stay bounded before process exit? +- Does every failure path reap the child? +- Are truncation counters visible? +- Does a 100 MiB-output regression test pass without retaining 100 MiB? +- Do npm run build and npm test -- --runInBand pass? + diff --git a/.context/skills/bound-subprocess-output/agents/openai.yaml b/.context/skills/bound-subprocess-output/agents/openai.yaml new file mode 100644 index 00000000..0e62297f --- /dev/null +++ b/.context/skills/bound-subprocess-output/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Bound Subprocess Output" + short_description: "Prevent unbounded child-process output" + default_prompt: "Use $bound-subprocess-output to implement or review bounded stdout and stderr capture." diff --git a/.context/skills/govern-cache-retention/SKILL.md b/.context/skills/govern-cache-retention/SKILL.md new file mode 100644 index 00000000..bc667966 --- /dev/null +++ b/.context/skills/govern-cache-retention/SKILL.md @@ -0,0 +1,61 @@ +--- +name: govern-cache-retention +description: Design, implement, or review bounded cache and persistent-index lifecycle. Use for ContextCache, SemanticContextBuilder, tree-sitter analysis cache, MCP session cache, hook host-session bindings, checkpoints, TTL, LRU, byte budgets, invalidation, cleanup timers, disposal, migration, or runtime retention configuration. +--- + +# Govern Cache Retention + +Require every cache and persistent index to declare how it stops growing and becomes fresh again. + +## Workflow + +1. Inventory keys, values, entry count, estimated bytes, and ownership lifetime. +2. Define maximum entries, maximum estimated bytes, TTL, and single-entry behavior. +3. Choose a freshness signal tied to the source, not only elapsed time. +4. Use LRU within TTL and evict proactively on set and lifecycle cleanup. +5. Make timers unref, bounded, and disposable. +6. Clear process-local caches on server stop. +7. Add lazy, dual-read migration for persistent shape changes. +8. Protect active sessions and preserve rollback readability. + +## Required cache contract + +Document: + +- normalized key; +- entry and byte limits; +- TTL; +- freshness signal; +- eviction order; +- sweep trigger; +- dispose behavior; +- metrics; +- behavior when one entry exceeds budget. + +Reject a cache implementation that omits any item. + +## Persistent indexes + +Avoid one ever-growing JSON document on a hot path. Partition bindings or records when lookup and rewrite cost scale with total history. Keep summaries in session.json and move growing checkpoint payloads to append-only or individual records. + +## Required invariants + +- Never expire only when the exact stale key is read again. +- Never leave a referenced interval after stop. +- Never retain stale semantic context after source identity changes. +- Never ignore cacheEnabled. +- Never prune active workflow state. +- Never require destructive migration to roll back. +- Clamp unsafe configuration values. + +## Dotcontext routing + +- Put generic LRU/retention rules in harness domain/application. +- Keep MCP and integration caches owned and disposed by their surfaces. +- Coordinate repository pruning with runtime history. +- Follow [F-07](../../../specs/performance/f-07-cache-retention.md). + +## Review gate + +Test entry eviction, byte eviction, TTL sweep, freshness invalidation, stop cleanup, stale binding removal, checkpoint migration, unsafe config clamps, and legacy reads. + diff --git a/.context/skills/govern-cache-retention/agents/openai.yaml b/.context/skills/govern-cache-retention/agents/openai.yaml new file mode 100644 index 00000000..0e3d3055 --- /dev/null +++ b/.context/skills/govern-cache-retention/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Govern Cache Retention" + short_description: "Add cache limits, TTLs, and cleanup" + default_prompt: "Use $govern-cache-retention to design bounded caches and lifecycle-aware persistent indexes." diff --git a/.context/skills/manage-lsp-process-lifecycle/SKILL.md b/.context/skills/manage-lsp-process-lifecycle/SKILL.md new file mode 100644 index 00000000..341a8b72 --- /dev/null +++ b/.context/skills/manage-lsp-process-lifecycle/SKILL.md @@ -0,0 +1,50 @@ +--- +name: manage-lsp-process-lifecycle +description: Implement or review language-server child-process ownership and cleanup. Use for LSPLayer, optional semantic LSP mode, spawn initialization, request timeouts, buffers, pending requests, retries, circuit breakers, graceful shutdown, SIGTERM/SIGKILL escalation, or orphan-process regressions. +--- + +# Manage LSP Process Lifecycle + +Give every process one owner and a terminal state. + +## Workflow + +1. Model one handle containing process, state, buffer, pending requests, timers, and project identity. +2. Deduplicate initialization with one Promise per language/project. +3. Treat initialize rejection, timeout, spawn error, and early exit as terminal failures. +4. Terminate the child on every failed initialization path. +5. Suppress retries for the current analysis after failure. +6. Make shutdown idempotent during starting, ready, failed, and stopping states. +7. Escalate from protocol shutdown to exit, SIGTERM, and bounded SIGKILL. +8. Wait for close and remove listeners/timers before releasing ownership. + +## Required invariants + +- Never overwrite a tracked process handle with a new child. +- Never let cleanup mean only deleting Maps. +- Never reject requests owned by another server handle. +- Never retry initialization once per symbol. +- Never resolve shutdown while a managed child remains alive. +- Preserve the useLSP=false fallback and non-LSP semantic behavior. + +## Testing + +Use executable fake servers that: + +- reject initialize; +- never answer initialize; +- crash after spawn; +- ignore protocol shutdown; +- answer normally; +- run concurrently for different languages. + +Assert OS child exit, spawn count, pending request cleanup, timer cleanup, and forced-kill metadata. Checking Map size alone is insufficient. + +## Dotcontext routing + +Keep ownership in src/harness/adapters/out/semantic/lsp and keep CodebaseAnalyzer responsible only for choosing whether to use LSP. Follow [F-04](../../../specs/performance/f-04-lsp-process-lifecycle.md). + +## Review gate + +Reject any change that lacks a zero-child assertion for failure and shutdown, or that introduces an unbounded retry path. + diff --git a/.context/skills/manage-lsp-process-lifecycle/agents/openai.yaml b/.context/skills/manage-lsp-process-lifecycle/agents/openai.yaml new file mode 100644 index 00000000..4721d92b --- /dev/null +++ b/.context/skills/manage-lsp-process-lifecycle/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Manage LSP Process Lifecycle" + short_description: "Prevent orphan language-server processes" + default_prompt: "Use $manage-lsp-process-lifecycle to implement or review safe LSP startup, failure, and shutdown paths." diff --git a/.context/skills/sanitize-hook-payloads/SKILL.md b/.context/skills/sanitize-hook-payloads/SKILL.md new file mode 100644 index 00000000..41389ba1 --- /dev/null +++ b/.context/skills/sanitize-hook-payloads/SKILL.md @@ -0,0 +1,50 @@ +--- +name: sanitize-hook-payloads +description: Design, implement, or review safe lifecycle-hook payload capture and trace persistence. Use for Claude Code, Codex, or Pi hook dispatch; PostToolUse Write/Edit/Bash mapping; stdin parsing; trace redaction; trace quotas; rotation; or hook privacy and performance changes. +--- + +# Sanitize Hook Payloads + +Treat host hook envelopes as untrusted, potentially huge, and potentially secret-bearing. + +## Workflow + +1. Trace the envelope from host stdin through normalization, mapping, and appendTrace. +2. Set an input byte ceiling before parsing JSON. +3. Reduce tool input to an allowlisted metadata summary before it reaches runtime state. +4. Apply recursive redaction and serialized-size limits as defense in depth. +5. Rotate traces by bytes and preserve atomic append behavior. +6. Keep host hooks non-blocking while recording a bounded failure reason. +7. Test equivalent envelopes for Claude Code, Codex, and Pi. + +## Tool summaries + +- Write: keep path, byte length, hash, and contentOmitted. +- Edit: keep path, old/new lengths, hashes, and range metadata. +- Bash: keep classification, basename, and a bounded preview. +- Unknown: keep scalar metadata and key names only. + +Redact content, old_string, new_string, patch, prompt, messages, authorization, tokens, passwords, secrets, and API keys case-insensitively. + +## Required invariants + +- Never persist raw Write or Edit bodies. +- Never echo rejected stdin. +- Never rely only on host-provided sizes. +- Measure the serialized trace before writing. +- Keep trace rotation compatible with legacy trace.jsonl. +- Never delete the active segment. +- Keep safety ceilings effective even when configuration is malformed. + +## Dotcontext routing + +- Keep host field mapping in src/integrations. +- Keep stdin limits in src/cli. +- Keep reusable sanitization and trace policy in src/harness. +- Update hook installer tests and public hook docs when observable behavior changes. +- Follow [F-02](../../../specs/performance/f-02-sanitize-hook-payloads.md). + +## Review gate + +Verify a multi-megabyte Write produces a small trace, sensitive fixtures never appear on disk, oversized stdin stays non-blocking, rotation survives concurrent appends, and package smoke tests pass. + diff --git a/.context/skills/sanitize-hook-payloads/agents/openai.yaml b/.context/skills/sanitize-hook-payloads/agents/openai.yaml new file mode 100644 index 00000000..3a113398 --- /dev/null +++ b/.context/skills/sanitize-hook-payloads/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Sanitize Hook Payloads" + short_description: "Keep hook traces small and safe" + default_prompt: "Use $sanitize-hook-payloads to review hook input capture, redaction, and trace size limits." diff --git a/.context/skills/share-semantic-analysis/SKILL.md b/.context/skills/share-semantic-analysis/SKILL.md new file mode 100644 index 00000000..5672e927 --- /dev/null +++ b/.context/skills/share-semantic-analysis/SKILL.md @@ -0,0 +1,44 @@ +--- +name: share-semantic-analysis +description: Consolidate or review repository discovery, semantic parsing, functional-pattern detection, codebase fingerprints, and snapshot generation. Use for context init, DocumentationGenerator, AgentGenerator, SemanticSnapshotService, CodebaseAnalyzer, FileMapper, analysis caching, or large-monorepo performance work. +--- + +# Share Semantic Analysis + +Compute one bounded analysis bundle per operation and reuse it. + +## Workflow + +1. Map every repository scan, glob, file read, parse, fingerprint, and derived output in the operation. +2. Define one AnalysisBundle owner at the harness application boundary. +3. Discover relevant files once with shared ignores. +4. Parse each selected file once and derive symbols, architecture, and functional patterns from the same analyses. +5. Pass the same bundle to documentation, agent, plan, and snapshot consumers. +6. Apply file-count, per-file byte, total-byte, and concurrency limits. +7. Mark partial analysis and skipped reasons explicitly. +8. Release operation-scoped caches in finally. + +## Fingerprinting + +Enumerate only relevant files. Reuse content hashes when path, size, and mtime are unchanged. Include dirty files when using git identity. Limit stabilization retries and keep the previous snapshot readable until publication succeeds. + +## Required invariants + +- Never perform a second semantic read only to derive functional patterns. +- Never let generators silently create independent analyzers in the main context-init path. +- Never glob the entire repository and filter relevance only afterward. +- Never call an analysis complete after a configured limit was hit. +- Honor cacheEnabled. +- Keep snapshot publication atomic. + +## Dotcontext routing + +- Own AnalysisBundle in src/harness/application/context. +- Keep parsing in semantic adapters. +- Inject data into generators instead of importing transport state. +- Follow [F-05](../../../specs/performance/f-05-shared-semantic-analysis.md). + +## Review gate + +Instrument tests to count discovery calls, file reads, parse calls, maximum concurrency, bytes read, and fingerprint attempts. Require one parse per selected file in default type=both context init. + diff --git a/.context/skills/share-semantic-analysis/agents/openai.yaml b/.context/skills/share-semantic-analysis/agents/openai.yaml new file mode 100644 index 00000000..af2acfd5 --- /dev/null +++ b/.context/skills/share-semantic-analysis/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Share Semantic Analysis" + short_description: "Avoid duplicate repository analysis work" + default_prompt: "Use $share-semantic-analysis to consolidate codebase scans, fingerprints, and semantic analysis." diff --git a/.context/skills/stream-runtime-history/SKILL.md b/.context/skills/stream-runtime-history/SKILL.md new file mode 100644 index 00000000..83f7407e --- /dev/null +++ b/.context/skills/stream-runtime-history/SKILL.md @@ -0,0 +1,45 @@ +--- +name: stream-runtime-history +description: Implement or review bounded runtime-history storage and retrieval. Use for traces, sessions, artifacts, sensor summaries, replays, datasets, cursor pagination, JSONL streaming, pruning, retention, or any harness API whose cost can grow with historical records. +--- + +# Stream Runtime History + +Make memory and response size proportional to a requested page. + +## Workflow + +1. Identify the cardinality and byte growth of every source collection. +2. Define default and maximum page sizes before changing an API. +3. Read JSONL incrementally and stop as soon as the page is complete. +4. Return an opaque, versioned cursor and explicit partial metadata. +5. Replace hot-path historical scans with bounded summary indexes. +6. Limit replay materialization at the source, transformation, response, and persistence layers. +7. Process multi-session work with bounded concurrency. +8. Add retention with dry-run, active-session protection, and crash-safe writes. + +## Required invariants + +- Never implement pagination by loading everything and slicing afterward. +- Never return complete source arrays inside a partial replay. +- Never use Promise.all over an unbounded set of sessions or files. +- Keep point reads by ID available. +- Read legacy runtime files without destructive migration. +- Keep active workflow evidence immune from age-based pruning. +- Treat malformed final JSONL lines as bounded diagnostics. + +## Cursor rules + +Keep cursors opaque to callers, include a version, bind them to the query direction and filters, and return a typed error for invalid or stale values. Do not promise raw byte offsets as a stable public contract. + +## Dotcontext routing + +- Define pagination and retention in harness ports/application. +- Keep MCP cursor adaptation thin. +- Coordinate trace segments with the hook payload skill. +- Follow [F-03](../../../specs/performance/f-03-stream-runtime-history.md). + +## Review gate + +Require load evidence for a large trace and many sessions. Verify page-size memory, maxEvents semantics, dataset concurrency, legacy reads, prune safety, and cursor boundary cases. + diff --git a/.context/skills/stream-runtime-history/agents/openai.yaml b/.context/skills/stream-runtime-history/agents/openai.yaml new file mode 100644 index 00000000..36170026 --- /dev/null +++ b/.context/skills/stream-runtime-history/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Stream Runtime History" + short_description: "Bound runtime history reads and replays" + default_prompt: "Use $stream-runtime-history to design paginated traces, replays, datasets, and retention." diff --git a/MEMORY_PERFORMANCE_AUDIT.md b/MEMORY_PERFORMANCE_AUDIT.md new file mode 100644 index 00000000..00d5d77a --- /dev/null +++ b/MEMORY_PERFORMANCE_AUDIT.md @@ -0,0 +1,486 @@ +# Auditoria de memória e performance do dotcontext + +Data da investigação: 2026-07-11 +Revisão analisada: b9e2981 +Branch: fix/performance-issues +Ambiente de medição: Node.js v22.20.0, npm 10.9.3, Linux + +## Resumo executivo + +A investigação confirmou falhas capazes de explicar tanto crescimento progressivo de memória e disco quanto picos abruptos de RSS e degradação de performance. + +O principal problema é um encadeamento entre hooks, persistência e leitura do runtime: + +1. Hooks de Write e Edit recebem o conteúdo integral da operação. +2. O dispatcher materializa todo o stdin em memória. +3. O conteúdo integral de tool_input é persistido em trace.jsonl. +4. Não há rotação, retenção, paginação ou limite de tamanho para traces. +5. Operações de qualidade, replay e dataset relêem e parseiam o histórico inteiro. +6. Replay preserva todos os traces mesmo quando maxEvents é pequeno. +7. A camada MCP serializa respostas grandes e depois faz JSON.parse do texto completo apenas para logging. + +Há ainda dois problemas independentes com alto potencial de impacto: + +- sensores e acceptance runners acumulam stdout e stderr completos em memória; +- falhas de inicialização ou shutdown do LSP deixam processos filhos vivos. + +Conclusão: os relatos de usuários são tecnicamente plausíveis e foram reproduzidos em cenários isolados. A prioridade deve ser introduzir limites rígidos e streaming antes de otimizações menores. + +## Classificação dos achados + +| ID | Severidade | Confiança | Área | Resumo | +| --- | --- | --- | --- | --- | +| F-01 | Crítica | Confirmado por medição | Harness / sensores | stdout e stderr de subprocessos crescem sem limite | +| F-02 | Crítica | Confirmado por medição | Hooks / runtime state | hooks persistem payloads completos e traces não têm retenção | +| F-03 | Crítica | Confirmado por medição | Runtime / replay / dataset | históricos são materializados integralmente; maxEvents não limita o payload do replay | +| F-04 | Crítica quando useLSP=true | Confirmado por reprodução | Semantic / LSP | processos LSP ficam órfãos após falha de inicialização ou shutdown | +| F-05 | Alta | Confirmado por inspeção | Context init / semantic | inicialização semântica repete scans e análises completas | +| F-06 | Alta | Confirmado por inspeção | MCP / listagens | respostas e coleções grandes são duplicadas e não paginadas | +| F-07 | Média | Confirmado por inspeção | Caches / lifecycle | caches e índices não têm limite global ou invalidação completa | + +## Escopo e método + +Foram auditadas as quatro superfícies da arquitetura: + +- CLI e hook dispatch; +- harness, incluindo runtime state, sensores, replay, datasets e context; +- gateway e servidor MCP; +- integrações Claude Code, Codex e Pi. + +O método combinou: + +- busca estática por buffers, arrays, Maps, subprocessos, listeners, leituras integrais e Promise.all; +- rastreamento dos fluxos de hooks e runtime; +- medições isoladas de RSS com Node.js; +- reprodução controlada de falha LSP; +- inspeção agregada do runtime local, sem expor conteúdo; +- build e suíte completa de testes. + +Os benchmarks abaixo são sintéticos e servem para demonstrar a forma de crescimento. Os números absolutos variam por sistema, versão do Node e formato dos dados. + +## Evidência quantitativa + +| Cenário | Entrada | Resultado observado | +| --- | ---: | --- | +| Sensor runShell | 80 MiB em stdout | RSS de aproximadamente 45 MiB para 293 MiB; 80 MiB permaneceram na string retornada | +| Acceptance runner | 80 MiB em stdout | RSS de aproximadamente 45 MiB para 133 MiB, embora apenas 8 KiB sejam retornados | +| listTraces | JSONL de 50,3 MB, 100 mil eventos | RSS após leitura de aproximadamente 231 MiB; heap usado de 113 MiB | +| buildReplay com maxEvents=10 | mesmos 100 mil traces | 10 events, mas 100 mil traces no resultado; RSS de aproximadamente 304 MiB | +| Hook Write | content de 5 MiB | trace.jsonl cresceu para 5.243.340 bytes e reteve o conteúdo | +| LSP com initialize rejeitado | duas tentativas | dois processos filhos vivos; shutdown deixou os dois vivos | + +O runtime deste checkout também confirma o comportamento em uso normal: + +- 33 arquivos de trace; +- 1.387 eventos; +- 1.065.603 bytes de traces; +- 1.245 eventos tool.use; +- 77 eventos com tool_input.content; +- 361.957 bytes de conteúdo de Write/Edit duplicados nos traces; +- 29 bindings em host-sessions.json. + +Esse volume local ainda é pequeno, mas demonstra que o caminho de retenção está ativo. + +## F-01 — Captura ilimitada de stdout e stderr + +### Evidência + +O helper de sensores mantém cada chunk em arrays e, ao final, concatena tudo e converte para string: + +- [testsPassing.ts](src/harness/adapters/out/sensors/testsPassing.ts), linhas 94–115. + +O helper é reutilizado por tests-passing e typecheck-clean. Em modo Jest, o stdout completo é adicionalmente parseado como JSON. + +O acceptance runner tem uma constante de tail de 8 KiB, mas só aplica o corte depois de acumular e concatenar a saída completa: + +- [acceptanceRunner.ts](src/harness/domain/workflow/plans/acceptanceRunner.ts), linhas 88–104. + +### Impacto + +- pico de memória proporcional à saída total do filho; +- múltiplas cópias simultâneas: chunks, Buffer concatenado e string UTF-16; +- OOM em testes verbosos, typecheck com muitos erros ou comandos que imprimem artefatos; +- timeout não limita memória produzida antes do encerramento. + +### Correção recomendada + +1. Implementar um ring buffer de bytes para stderr e para modos que só precisam de tail. +2. Definir limite absoluto de captura, por exemplo 8–16 MiB, e matar o filho ou truncar explicitamente ao excedê-lo. +3. Para Jest, usar arquivo temporário via --outputFile ou parser incremental; não manter JSON e chunks duplicados. +4. Aplicar backpressure ou descartar chunks antigos durante a execução, não apenas no finish. +5. Incluir bytesCaptured, bytesDropped e outputTruncated no resultado. + +## F-02 — Hooks persistem payload completo e traces crescem indefinidamente + +### Evidência + +O dispatcher lê stdin inteiro em chunks, concatena e cria uma string antes do JSON.parse: + +- [hookDispatchService.ts](src/cli/services/hookDispatchService.ts), linhas 280–287. + +O mapper inclui tool_input sem sanitização ou limite: + +- [bashClassification.ts](src/harness/application/hooks/bashClassification.ts), linhas 95–106. + +O trace é serializado integralmente e anexado ao JSONL: + +- [runtimeStateService.ts](src/harness/adapters/out/runtimeState/runtimeStateService.ts), linhas 185–197. + +Os templates ativam PostToolUse para Write, Edit e Bash. Write pode carregar o arquivo inteiro em content; Edit pode carregar blocos extensos. + +Não foi encontrado mecanismo de: + +- limite do stdin do hook; +- limite por campo ou evento; +- redaction do conteúdo de Write/Edit; +- rotação de trace.jsonl; +- quota por sessão ou repositório; +- expiração ou remoção de sessões. + +### Impacto + +- cópias transitórias grandes no processo curto do hook; +- crescimento linear de disco por edição; +- dados de código e possíveis segredos ficam duplicados em .context/runtime; +- cada leitura posterior do trace amplifica o custo; +- hooks frequentes adicionam I/O síncrono percebido pelo host. + +### Correção recomendada + +1. Persistir apenas metadados de Write/Edit: caminho, tamanho, hash, faixa alterada e classificação. +2. Remover content, old_string, new_string e campos equivalentes, ou truncá-los para uma amostra pequena configurável. +3. Rejeitar ou truncar stdin acima de um limite explícito antes de Buffer.concat. +4. Introduzir rotação por bytes e idade, com retenção total por repositório. +5. Adicionar comando de prune e execução automática segura no início/fim de sessão. +6. Tornar a política de captura documentada e configurável, com default seguro. + +## F-03 — listTraces, replay e dataset materializam todo o histórico + +### Evidência + +listTraces executa readFile do JSONL completo, split, trim e JSON.parse de todas as linhas: + +- [runtimeStateService.ts](src/harness/adapters/out/runtimeState/runtimeStateService.ts), linhas 334–352. + +O mesmo padrão de coleção integral existe em listSessions e listArtifacts: + +- [runtimeStateService.ts](src/harness/adapters/out/runtimeState/runtimeStateService.ts), linhas 233–250 e 314–331. + +Leituras integrais de traces também acontecem em rotas frequentes: + +- avaliação de task em [taskContractsService.ts](src/harness/application/contracts/taskContractsService.ts), linhas 380–391; +- consulta de sensor runs em [sensorsService.ts](src/harness/application/sensors/sensorsService.ts), linhas 125–129. + +Replay carrega traces, artefatos, checkpoints, sensores, tasks e handoffs em paralelo, cria uma segunda coleção de events e só então aplica maxEvents: + +- [replayService.ts](src/harness/application/replay/replayService.ts), linhas 133–251. + +Depois do corte, o objeto retornado ainda inclui traces, artifacts, checkpoints, sensorRuns, tasks e handoffs completos: + +- [replayService.ts](src/harness/application/replay/replayService.ts), linhas 252–269. + +listReplays carrega todos os arquivos JSON em Promise.all: + +- [replayService.ts](src/harness/application/replay/replayService.ts), linhas 283–296. + +Dataset seleciona todas as sessões não concluídas por default e constrói todos os replays em Promise.all: + +- [datasetService.ts](src/harness/application/datasets/datasetService.ts), linhas 253–286. + +listDatasets também carrega todos os datasets em Promise.all: + +- [datasetService.ts](src/harness/application/datasets/datasetService.ts), linhas 290–299. + +### Impacto + +- crescimento de memória muito maior que o tamanho do arquivo em disco; +- maxEvents transmite uma falsa sensação de proteção; +- replay duplica o histórico em memória e novamente em disco; +- buildDataset multiplica o pico pelo número de sessões concorrentes; +- avaliações simples ficam progressivamente mais lentas conforme a sessão cresce. + +### Correção recomendada + +1. Substituir listTraces por leitura streaming de JSONL com cursor, limit, direction e filtros por event/level/time. +2. Manter um índice resumido dos últimos sensor runs por sensor, evitando scan completo na avaliação. +3. Fazer maxEvents limitar leitura, transformação e payload final. +4. No replay parcial, não incluir coleções completas; retornar summaries e cursores. +5. Processar datasets com concorrência limitada, idealmente uma sessão por vez. +6. Paginar listSessions, listArtifacts, listReplays e listDatasets; listar metadados sem carregar payloads. +7. Definir tamanho máximo para artefato, checkpoint.data, trace.data e arquivos de replay/dataset. + +## F-04 — Processos LSP órfãos + +### Evidência + +ensureServer registra o processo no Map e aguarda initialize: + +- [lspLayer.ts](src/harness/adapters/out/semantic/lsp/lspLayer.ts), linhas 69–143. + +Se initialize falha ou expira, o catch apenas retorna false: + +- [lspLayer.ts](src/harness/adapters/out/semantic/lsp/lspLayer.ts), linhas 144–147. + +O processo não é morto. Uma nova tentativa cria outro processo e sobrescreve a entrada do Map. O processo anterior fica vivo e deixa de ser alcançável pelo gerenciador. + +cleanup remove Maps e rejeita requests, mas não encerra o processo: + +- [lspLayer.ts](src/harness/adapters/out/semantic/lsp/lspLayer.ts), linhas 236–246. + +shutdown envia shutdown/exit, porém, se houver erro ou timeout, apenas chama cleanup: + +- [lspLayer.ts](src/harness/adapters/out/semantic/lsp/lspLayer.ts), linhas 399–416. + +A reprodução com um servidor que rejeita initialize deixou um filho por tentativa e nenhum foi eliminado por shutdown. + +### Impacto + +- múltiplos language servers acumulam memória e CPU; +- processos órfãos podem sobreviver ao fluxo semântico; +- enhanceWithLSP pode repetir ensureServer para até 100 símbolos; +- falha silenciosa torna o diagnóstico difícil. + +### Correção recomendada + +1. Guardar uma Promise de inicialização por linguagem para deduplicar tentativas. +2. Em qualquer falha de initialize, fechar stdin, enviar SIGTERM e aplicar SIGKILL após grace period. +3. Em shutdown, sempre garantir término do processo e aguardar exit. +4. Associar pendingRequests à linguagem; hoje cleanup de uma linguagem rejeita todos os requests globais. +5. Adicionar circuit breaker após uma falha por linguagem/projeto durante a análise atual. +6. Criar testes que verificam contagem de filhos após initialize rejeitado, timeout e shutdown. + +## F-05 — Context init repete scans e análises semânticas + +### Evidência + +context init usa por default type=both e semantic=true: + +- [contextTools.ts](src/harness/application/context/contextTools.ts), linhas 589–601. + +Primeiro, FileMapper globba e mantém a estrutura inteira do repositório: + +- [fileMapper.ts](src/utils/fileMapper.ts), linhas 47–119. + +Depois: + +- DocumentationGenerator cria um CodebaseAnalyzer, calcula fingerprint e analisa o repositório: [documentationGenerator.ts](src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts), linhas 75–85. +- A escrita do snapshot cria outro analyzer se functionalPatterns não foi fornecido: [semanticSnapshotService.ts](src/harness/adapters/out/semantic/semanticSnapshotService.ts), linhas 415–435. +- AgentGenerator cria outro CodebaseAnalyzer e analisa novamente: [agentGenerator.ts](src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts), linhas 118–125. + +O orquestrador chama docs e agents separadamente com semantic habilitado: + +- [contextTools.ts](src/harness/application/context/contextTools.ts), linhas 669–721. + +Uma análise aceita até 5.000 arquivos e guarda FileAnalysis, símbolos e grafos: + +- [codebaseAnalyzer.ts](src/harness/adapters/out/semantic/codebaseAnalyzer.ts), linhas 32–38 e 56–131. + +O refresh de snapshot calcula fingerprint até três vezes por tentativa e pode repetir a tentativa três vezes: + +- [semanticSnapshotService.ts](src/harness/adapters/out/semantic/semanticSnapshotService.ts), linhas 307–338. + +Cada fingerprint começa com glob de todo o repositório e lê o conteúdo integral de cada arquivo relevante: + +- [semanticSnapshotService.ts](src/harness/adapters/out/semantic/semanticSnapshotService.ts), linhas 732–756. + +### Impacto + +- context init faz aproximadamente três análises semânticas completas no caminho default; +- grandes monorepos sofrem alta latência, I/O e pressão de GC; +- fingerprint pode ler o codebase várias vezes; +- o glob inicial coleta caminhos que só são filtrados depois. + +### Correção recomendada + +1. Criar um único AnalysisBundle por operação contendo RepoStructure, SemanticContext, functionalPatterns, stackInfo e fingerprint. +2. Injetar o bundle em DocumentationGenerator, AgentGenerator e SemanticSnapshotService. +3. Fazer fingerprint incremental com stat/mtime/size e hash de conteúdo apenas quando necessário, ou usar git tree/index quando disponível. +4. Usar um único glob por conjunto de extensões, deduplicado e com ignores centralizados. +5. Permitir maxFiles e limites de bytes configuráveis no init; avisar quando a análise for parcial. +6. Instrumentar duração, arquivos e bytes lidos por estágio. + +## F-06 — Respostas MCP e listagens sem paginação amplificam o pico + +### Evidência + +createJsonResponse serializa o objeto inteiro para uma string formatada: + +- [response.ts](src/mcp/gateway/response.ts), linhas 27–33. + +Após a serialização, logToolResponse faz JSON.parse do texto completo para extrair poucas chaves: + +- [mcpServer.ts](src/mcp/server/mcpServer.ts), linhas 1046–1058 e 1090–1098. + +Assim, respostas como listTraces, replay, listReplays e datasets mantêm simultaneamente: + +- estruturas do harness; +- string JSON formatada; +- objeto parseado novamente pelo logger. + +O schema MCP aceita content, data, output e maxEvents sem limites de tamanho e expõe listagens sem cursor: + +- [mcpServer.ts](src/mcp/server/mcpServer.ts), linhas 680–715. + +### Impacto + +- picos adicionais de heap em respostas grandes; +- maior tempo de CPU em stringify/parse redundante; +- payloads MCP podem exceder limites do cliente antes de o servidor se recuperar; +- pretty-print adiciona custo sem benefício operacional para payloads grandes. + +### Correção recomendada + +1. Propagar success/error/resultSummary como metadados estruturados antes da serialização. +2. Remover parseResponsePayload do caminho de logging. +3. Paginar todas as listagens e estabelecer um limite default conservador. +4. Rejeitar parâmetros acima do máximo no schema Zod. +5. Não usar pretty-print em respostas grandes. +6. Retornar referências a artefatos/arquivos em vez de conteúdo integral quando apropriado. + +## F-07 — Caches e índices sem lifecycle completo + +### Evidência + +O cache global de sessões MCP é um Map sem máximo ou TTL: + +- [actionLogger.ts](src/mcp/logging/actionLogger.ts), linha 42 e linhas 107–139. + +O ContextCache só remove entradas expiradas quando a mesma chave é consultada. Entradas nunca revisitadas permanecem: + +- [contextCache.ts](src/harness/adapters/out/semantic/contextCache.ts), linhas 39–95. + +SemanticContextBuilder mantém o SemanticContext completo indefinidamente para o mesmo path e não invalida por mudança de arquivos: + +- [contextBuilder.ts](src/harness/adapters/out/semantic/contextBuilder.ts), linhas 45–66. + +Existe cacheEnabled nas opções do analyzer, mas não há uso dessa flag no código de cache. + +host-sessions.json guarda bindings sem expiração e é lido integralmente em cada lookup: + +- [hookSessionStore.ts](src/integrations/shared/hookSessionStore.ts), linhas 45–83. + +checkpoints ficam embutidos em session.json, crescem sem limite e o arquivo completo é reescrito a cada trace: + +- [runtimeStateService.ts](src/harness/adapters/out/runtimeState/runtimeStateService.ts), linhas 190–197 e 355–373. + +### Impacto + +- degradação gradual em servidores MCP usados com muitos repositórios; +- contexto semântico pode ficar obsoleto enquanto continua retido; +- host-sessions.json e session.json tornam-se documentos cada vez mais caros; +- o custo de appendTrace cresce com o tamanho de session.json quando há muitos checkpoints. + +### Correção recomendada + +1. Aplicar LRU com limites por quantidade e bytes. +2. Limpar caches no stop e invalidá-los por fingerprint/mtime. +3. Honrar cacheEnabled. +4. Expirar bindings encerrados e particionar o store por host/session ou usar arquivos individuais. +5. Mover checkpoints para JSONL ou arquivos individuais e manter apenas resumo no session.json. + +## Plano de correção priorizado + +### P0 — Contenção imediata + +1. Limitar captura de stdout/stderr durante a execução. +2. Redigir/truncar payloads de Write/Edit antes de appendTrace. +3. Implementar leitura paginada/streaming de traces. +4. Corrigir maxEvents para limitar o replay inteiro. +5. Encerrar processos LSP em todos os caminhos de falha. +6. Aplicar limites de schema para content, data, output, maxEvents e listagens. + +Essas mudanças atacam diretamente os caminhos capazes de causar OOM. + +### P1 — Evitar crescimento progressivo + +1. Rotação e retenção de runtime state. +2. Paginação de sessions, artifacts, replays e datasets. +3. Dataset com concorrência limitada. +4. Remoção do JSON.parse redundante no logging MCP. +5. Índice incremental de sensores e eventos recentes. +6. Prune de host session bindings e checkpoints. + +### P2 — Reduzir custo semântico + +1. Compartilhar um AnalysisBundle no context init. +2. Tornar fingerprint incremental. +3. LRU e invalidação correta dos caches. +4. Unificar globs e ignores. +5. Expor telemetria de duração, bytes e contagem de arquivos. + +## Testes de regressão necessários + +Adicionar testes que falhem antes da correção: + +1. subprocesso produz 100 MiB; RSS e bytes retidos permanecem abaixo de um teto; +2. hook Write com content grande persiste apenas metadados/truncamento; +3. stdin do hook acima do limite é truncado ou rejeitado sem crash; +4. listTraces retorna no máximo limit e fornece cursor; +5. replay maxEvents=10 não contém arrays completos fora dos 10 eventos; +6. buildDataset respeita limite de concorrência; +7. listReplays/listDatasets não lê payload de todos os arquivos; +8. LSP initialize rejeitado ou expirado deixa zero filhos; +9. shutdown LSP deixa zero filhos mesmo quando o protocolo não responde; +10. context init analisa cada arquivo uma única vez por operação; +11. caches respeitam máximo, TTL e cacheEnabled; +12. retenção remove traces, sessions e bindings antigos sem quebrar sessões ativas. + +Os testes de memória devem rodar em uma faixa tolerante e medir invariantes de bytes retidos, não apenas um RSS absoluto frágil. + +## Observabilidade recomendada + +Sem logs de conteúdo, registrar: + +- process.memoryUsage antes/depois de operações pesadas; +- bytes lidos, parseados, serializados e descartados; +- tamanho por trace e tamanho acumulado da sessão; +- número de sessions, replays, datasets e bindings; +- subprocess output bytes e truncation; +- PIDs LSP, estado de inicialização, tentativas e motivo de término; +- duração por estágio do context init; +- cache entries e bytes estimados. + +Criar alertas locais quando: + +- um evento de trace ultrapassar 256 KiB; +- uma sessão ultrapassar a quota configurada; +- um subprocesso truncar saída; +- um replay/dataset precisar ser parcial; +- um LSP exigir SIGKILL. + +## Workaround operacional até a correção + +Para usuários afetados: + +1. desabilitar temporariamente PostToolUse de Write/Edit, mantendo SessionStart e Stop se necessários; +2. evitar replaySession, listTraces, listReplays, buildDataset e listDatasets em sessões grandes; +3. iniciar sessões novas com maior frequência; +4. remover ou arquivar manualmente .context/runtime antigo somente com backup e fora de uma sessão ativa; +5. evitar useLSP=true; +6. configurar testes e typecheck para reduzir output. + +Não é recomendado apenas aumentar --max-old-space-size: isso adia o OOM, mas não corrige crescimento de disco, processos órfãos nem complexidade das leituras. + +## Validação da baseline + +Nenhuma alteração de runtime foi feita nesta investigação. + +Validações executadas: + +- npm run build: aprovado; +- npm test -- --runInBand: 92 suítes aprovadas, 564 testes aprovados, 0 falhas. + +Isso indica que a suíte funcional atual não cobre os limites e cenários de carga descritos. Os achados são problemas de comportamento sob volume e lifecycle, não falhas detectadas pelos testes existentes. + +## Especificações de correção + +As propostas implementáveis, critérios de aceitação e skills preventivas estão indexados em [specs/performance/README.md](specs/performance/README.md). + +## Limitações + +- Não foram coletados heap snapshots ou perfis de produção de usuários. +- As medições foram isoladas no checkout local e não representam um workload específico de cliente. +- A auditoria não alterou o código nem validou uma implementação de correção. +- Dependências externas, especialmente o SDK MCP e implementações reais de language server, podem adicionar overhead além do observado. + +Mesmo com essas limitações, F-01 a F-04 têm reprodução direta e suficiente para justificar correção imediata. diff --git a/specs/performance/README.md b/specs/performance/README.md new file mode 100644 index 00000000..2b89a893 --- /dev/null +++ b/specs/performance/README.md @@ -0,0 +1,62 @@ +# Memory and Performance Remediation Specifications + +Status: Proposed +Source audit: [MEMORY_PERFORMANCE_AUDIT.md](../../MEMORY_PERFORMANCE_AUDIT.md) + +## Objective + +Turn every confirmed audit finding into an independently deliverable change with explicit resource bounds, compatibility rules, observability, rollback, and regression tests. + +## Specification map + +| Finding | Specification | Preventive skill | Priority | +| --- | --- | --- | --- | +| F-01 | [Bound subprocess output](./f-01-bound-subprocess-output.md) | [bound-subprocess-output](../../.context/skills/bound-subprocess-output/SKILL.md) | P0 | +| F-02 | [Sanitize hook payloads and rotate traces](./f-02-sanitize-hook-payloads.md) | [sanitize-hook-payloads](../../.context/skills/sanitize-hook-payloads/SKILL.md) | P0 | +| F-03 | [Stream runtime history](./f-03-stream-runtime-history.md) | [stream-runtime-history](../../.context/skills/stream-runtime-history/SKILL.md) | P0 | +| F-04 | [Own the LSP process lifecycle](./f-04-lsp-process-lifecycle.md) | [manage-lsp-process-lifecycle](../../.context/skills/manage-lsp-process-lifecycle/SKILL.md) | P0 | +| F-05 | [Share semantic analysis work](./f-05-shared-semantic-analysis.md) | [share-semantic-analysis](../../.context/skills/share-semantic-analysis/SKILL.md) | P1 | +| F-06 | [Bound MCP payloads](./f-06-bound-mcp-payloads.md) | [bound-mcp-payloads](../../.context/skills/bound-mcp-payloads/SKILL.md) | P0/P1 | +| F-07 | [Govern cache and persistent retention](./f-07-cache-retention.md) | [govern-cache-retention](../../.context/skills/govern-cache-retention/SKILL.md) | P1 | + +## Delivery order + +1. F-01 and F-04 can proceed independently. +2. F-02 establishes safe trace writes. +3. F-03 establishes bounded reads, replay, dataset, and runtime retention. +4. F-06 consumes the pagination contracts from F-03. +5. F-05 consolidates semantic work without coupling to runtime history. +6. F-07 finishes lifecycle policy across caches, bindings, checkpoints, and indexes. + +F-02, F-03, and F-06 must agree on cursor and truncation metadata before implementation. Do not ship a response limit that merely rejects the current unpaginated runtime APIs. + +## Global engineering constraints + +- Preserve the cli -> harness <- mcp and integrations boundary. +- Put reusable execution behavior in src/harness/application or reusable rules in src/harness/domain. +- Keep transport validation and response shaping in src/mcp/gateway or src/mcp/server. +- Keep host event mapping and hook templates in src/integrations. +- Do not add code under src/services. +- Keep default behavior safe without requiring configuration. +- Never use a larger Node heap as the primary mitigation. + +## Global quality gates + +Every implementation must: + +1. add a failing regression test before the fix; +2. define the bound in bytes, entries, concurrency, or time; +3. expose truncation or partial-result metadata; +4. keep active workflows and existing runtime files readable; +5. avoid logging captured content; +6. run npm run build and npm test -- --runInBand; +7. run package build and smoke tests if a public package contract changes. + +## Shared terminology + +- Hard limit: input above the threshold is rejected or terminated. +- Soft limit: older data is evicted or output is truncated while the operation continues. +- Cursor: opaque continuation token; callers must not infer file offsets from it. +- Summary record: bounded metadata without the original payload. +- Partial result: a successful, explicitly incomplete response with a continuation path. + diff --git a/specs/performance/f-01-bound-subprocess-output.md b/specs/performance/f-01-bound-subprocess-output.md new file mode 100644 index 00000000..e0bb13c9 --- /dev/null +++ b/specs/performance/f-01-bound-subprocess-output.md @@ -0,0 +1,116 @@ +# F-01 — Bound subprocess output + +Status: Proposed +Priority: P0 +Boundary owner: harness +Preventive skill: [bound-subprocess-output](../../.context/skills/bound-subprocess-output/SKILL.md) + +## Problem + +Sensor and acceptance subprocesses retain every stdout and stderr chunk. Tail limits are applied only after Buffer.concat, and Jest output is converted into another full string before parsing. Memory therefore scales with child output instead of the configured diagnostic tail. + +Affected code: + +- [testsPassing.ts](../../src/harness/adapters/out/sensors/testsPassing.ts) +- [typecheckClean.ts](../../src/harness/adapters/out/sensors/typecheckClean.ts) +- [acceptanceRunner.ts](../../src/harness/domain/workflow/plans/acceptanceRunner.ts) + +## Goals + +- Bound in-memory child output independently for stdout and stderr. +- Preserve an 8 KiB diagnostic tail by default. +- Support Jest summary extraction without retaining terminal output. +- Make truncation visible to callers and traces. +- Terminate commands that exceed a configurable hard output ceiling when requested. + +## Non-goals + +- Replace Node child_process. +- Stream live output to the MCP client. +- Store complete test output in runtime traces. + +## Proposed design + +### Bounded collector + +Add a pure bounded byte collector under src/harness/domain/execution. It must: + +- accept Buffer chunks; +- retain only the newest tailBytes; +- track totalBytes and droppedBytes; +- expose truncated; +- avoid Buffer.concat over all historical chunks; +- cap the number of retained segments or compact incrementally. + +Default limits: + +| Setting | Default | +| --- | ---: | +| tailBytes per stream | 8 KiB | +| soft capture limit per stream | 1 MiB | +| hard combined output limit | 16 MiB | +| hard-limit behavior | terminate child and return outputLimitExceeded | + +The caller may lower limits. Raising a hard limit above 64 MiB must require an explicit unsafe override in application code, not only user input. + +### Sensor execution + +Replace runShell raw strings with a result containing bounded tails and counters: + +- stdoutTail; +- stderrTail; +- stdoutBytes; +- stderrBytes; +- stdoutDroppedBytes; +- stderrDroppedBytes; +- outputTruncated; +- outputLimitExceeded. + +For default Jest execution: + +1. write JSON results to a temporary file using Jest outputFile; +2. keep console stdout/stderr bounded; +3. reject a JSON result file above 32 MiB before reading; +4. parse only fields required for TestsPassingReport; +5. remove the temporary file in finally. + +Custom exit-code sensors never need complete output. + +### Acceptance execution + +Use the same collector. A plan acceptance run persists only tails and counters. Exceeding the hard limit fails the acceptance predicate with a stable reason. + +## Compatibility + +- Keep existing tailStdout and tailStderr fields. +- Add optional counters so older persisted plan tracking remains readable. +- Preserve timeout and exit-code semantics. +- Keep testCommand arrays and shell:false behavior. + +## Work breakdown + +1. Implement and unit-test the bounded collector. +2. Refactor acceptance runner. +3. Refactor shared sensor runner. +4. Move Jest JSON to a temporary result file. +5. Add output-limit configuration with clamped values. +6. Add observability fields to sensor and acceptance traces. + +## Acceptance criteria + +- A child that emits 100 MiB does not retain more than configured tails plus 8 MiB process overhead attributable to capture. +- No array grows with the total number of output chunks. +- Acceptance returns at most tailBytes per stream. +- Typecheck and exit-code sensor paths never materialize full output strings. +- Jest result files above 32 MiB fail with resultFileTooLarge. +- Timeout, spawn error, non-zero exit, malformed Jest JSON, and output-limit paths have regression tests. +- npm run build and the complete Jest suite pass. + +## Rollout and rollback + +Ship behind internal defaults, not a user-facing feature flag. Preserve legacy result fields. Roll back by restoring the old runner only if bounded capture breaks command completion; never roll back the hard ceiling without an incident-specific patch. + +## Observability + +Record byte counters, truncation, termination reason, duration, and command basename. Never record full command output. + diff --git a/specs/performance/f-02-sanitize-hook-payloads.md b/specs/performance/f-02-sanitize-hook-payloads.md new file mode 100644 index 00000000..96a15b6b --- /dev/null +++ b/specs/performance/f-02-sanitize-hook-payloads.md @@ -0,0 +1,119 @@ +# F-02 — Sanitize hook payloads and rotate traces + +Status: Proposed +Priority: P0 +Boundary owners: integrations, cli, harness +Preventive skill: [sanitize-hook-payloads](../../.context/skills/sanitize-hook-payloads/SKILL.md) + +## Problem + +Shell hook dispatch reads all stdin into memory and PostToolUse persists tool_input unchanged. Write and Edit can therefore duplicate complete source content into trace.jsonl. Traces have no event limit, byte quota, rotation, or automatic retention. + +Affected code: + +- [hookDispatchService.ts](../../src/cli/services/hookDispatchService.ts) +- [bashClassification.ts](../../src/harness/application/hooks/bashClassification.ts) +- [resolveHarnessHookFromHostEvent.ts](../../src/integrations/shared/resolveHarnessHookFromHostEvent.ts) +- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) + +## Goals + +- Bound hook stdin before concatenation and JSON parsing. +- Persist useful tool metadata without source bodies or secrets. +- Enforce a defense-in-depth maximum serialized trace event size. +- Rotate and retain trace segments without breaking active sessions. +- Make redaction and truncation observable. + +## Non-goals + +- Persist diffs for later reconstruction. +- Rewrite historical traces during the first release. +- Change host hook configuration shapes. + +## Proposed design + +### Bounded stdin + +Implement incremental byte counting in CLI hook dispatch: + +- default maximum: 8 MiB; +- stop reading and return a non-blocking diagnostic when exceeded; +- do not Buffer.concat after the limit; +- never echo the rejected input. + +The dispatcher must remain non-blocking for host operations, but must record a bounded trace-failure diagnostic. + +### Hook trace policy + +Add a reusable policy in src/harness/application/hooks. Normalize known tools: + +| Tool | Persist | +| --- | --- | +| Write | file path, declared byte length, content hash, contentOmitted=true | +| Edit | file path, old/new byte lengths, hashes, range metadata when present | +| Bash | classification, command basename, bounded command preview | +| Unknown | keys, scalar metadata, bounded structural summary | + +Always redact keys matching content, old_string, new_string, patch, apiKey, token, secret, password, authorization, messages, and prompt, case-insensitively. + +Defaults: + +- maximum string field: 512 bytes; +- maximum array items: 20; +- maximum object depth: 4; +- maximum serialized hook trace data: 16 KiB; +- maximum serialized generic trace event: 256 KiB. + +### Trace write quota and rotation + +Store trace segments under the existing session directory: + +- active trace.jsonl remains the write target; +- rotate at 8 MiB; +- retain 4 closed segments per active session; +- retain at most 32 MiB per session by default; +- never delete the active segment; +- write a bounded trace.rotated event after rotation. + +F-03 defines streaming reads across segments and repository-wide retention. + +## Configuration + +Use .context/config/hooks.json for hook-specific limits and .context/config/runtime.json for generic trace limits. Clamp all configured values to safe global maxima. + +## Compatibility and migration + +- Existing unsegmented trace.jsonl remains readable. +- New readers must merge legacy and rotated segments in chronological order. +- Existing hook installation docs and templates remain unchanged. +- No historical source payload is rewritten automatically. + +## Work breakdown + +1. Add tool-input sanitizer and tests for every host envelope. +2. Add bounded stdin reader. +3. Add serialized event size guard to runtime state. +4. Add atomic trace rotation. +5. Add config parsing and clamping. +6. Update README, dotcontext.dev hook guide, and CHANGELOG because hook behavior changes. + +## Acceptance criteria + +- A 5 MiB Write content produces a trace event below 16 KiB. +- No raw Write/Edit content appears in persisted traces. +- Sensitive keys are redacted regardless of case. +- Hook stdin above 8 MiB does not cause Buffer.concat or process failure. +- A trace rotates after the configured threshold and active writes continue. +- Concurrent appends do not corrupt or misorder a segment. +- Old trace.jsonl files remain readable. +- Hook round-trip tests cover Claude Code, Codex, and Pi. +- Build, full tests, package build, and package smoke pass. + +## Rollout and rollback + +Enable sanitization immediately. Roll out rotation after F-03 readers understand segments. Rollback may disable rotation, but must never restore raw content capture. + +## Observability + +Record inputBytes, persistedBytes, redactedFieldCount, truncatedFieldCount, rotationCount, and quota status. Never log redacted values or hashes of known secrets. + diff --git a/specs/performance/f-03-stream-runtime-history.md b/specs/performance/f-03-stream-runtime-history.md new file mode 100644 index 00000000..9f93de92 --- /dev/null +++ b/specs/performance/f-03-stream-runtime-history.md @@ -0,0 +1,135 @@ +# F-03 — Stream runtime history + +Status: Proposed +Priority: P0 +Boundary owner: harness, with MCP adaptation in F-06 +Preventive skill: [stream-runtime-history](../../.context/skills/stream-runtime-history/SKILL.md) + +## Problem + +Runtime APIs load complete traces, artifacts, sessions, replays, and datasets. Replay creates a second full event graph and applies maxEvents only after materialization, while still returning complete source arrays. Dataset builds every selected replay concurrently. + +Affected code: + +- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) +- [replayService.ts](../../src/harness/application/replay/replayService.ts) +- [datasetService.ts](../../src/harness/application/datasets/datasetService.ts) +- [taskContractsService.ts](../../src/harness/application/contracts/taskContractsService.ts) +- [sensorsService.ts](../../src/harness/application/sensors/sensorsService.ts) + +## Goals + +- Make memory proportional to page size, not history size. +- Give every list operation a bounded default and maximum. +- Make replay limits constrain reads, transformations, response, and persistence. +- Build datasets with bounded concurrency. +- Add retention without deleting active workflow evidence. + +## Non-goals + +- Introduce a database dependency. +- Preserve unlimited list behavior. +- Reconstruct source content removed by F-02. + +## Query contracts + +Introduce opaque cursor-based queries: + +| Resource | Default | Maximum | +| --- | ---: | ---: | +| traces | 100 | 1,000 | +| sessions | 50 | 200 | +| artifacts | 50 | 200 | +| replay summaries | 25 | 100 | +| dataset summaries | 25 | 100 | + +Every page returns items, nextCursor, hasMore, and scannedBytes where applicable. Support trace filters for event, level, createdAfter, and createdBefore. + +Cursor payloads must be versioned and encoded; invalid or stale cursors return a typed error. Do not expose raw file offsets as a public guarantee. + +## Streaming trace reader + +Add a runtime-state port that iterates JSONL records across legacy and rotated segments: + +- read line-by-line; +- stop after the requested page; +- skip malformed terminal lines and report malformedCount; +- support newest-first without reading the entire file into a string; +- expose an internal async iterator for consumers that need full scans. + +Task evaluation and sensor quality must not scan every trace. Maintain a bounded session summary with the latest run per sensor and update it during appendTrace. + +## Replay contract + +Replace the current mixed full/partial record with: + +- bounded events; +- source counts by type; +- omitted counts; +- nextCursor for additional events; +- fidelity; +- bounded session summary. + +When maxEvents is 10, no source array may contain more than those 10 materialized events. Full export, if retained, must stream to a file artifact and return its path/metadata rather than the payload. + +## Dataset execution + +- default concurrency: 1 session; +- configurable maximum: 4; +- process replay summaries incrementally; +- retain only failure records required for clustering; +- cap failures per dataset at 10,000 by default; +- return partial=true and omittedFailureCount when capped. + +## Runtime retention + +Default policy: + +- active sessions: never age-delete; +- completed/failed sessions: retain 30 days; +- replays: retain 10 per session and 30 days; +- datasets: retain 20 and 30 days; +- repository runtime quota: 256 MiB; +- prune oldest eligible data first; +- dry-run prune report required. + +F-07 owns configuration lifecycle and binding/checkpoint retention. + +## Compatibility + +- Keep point reads by ID. +- Read legacy trace.jsonl and existing replay/dataset JSON. +- Add summary-only list APIs before changing MCP defaults. +- Mark unlimited methods deprecated for one minor release, but make internal hot paths use paginated APIs immediately. + +## Work breakdown + +1. Define page and cursor types in harness. +2. Implement streaming trace reader and segment merge. +3. Add paginated state ports. +4. Add sensor summary index and migration-on-read. +5. Redesign replay result and persistence. +6. Bound dataset concurrency and records. +7. Add prune service with dry-run. +8. Adapt CLI and MCP consumers. + +## Acceptance criteria + +- Reading 100 records from a 1 GiB trace stays within 32 MiB incremental RSS in a dedicated benchmark. +- maxEvents=10 returns and persists at most 10 event payloads. +- Task evaluation reads the sensor summary rather than listTraces. +- Dataset processing never exceeds configured concurrency. +- List APIs reject limits above their maximum. +- Legacy runtime fixtures remain readable. +- Prune never deletes active sessions or the active workflow binding. +- Crash during rotation/prune leaves a readable previous state. +- Load tests cover one million trace lines and 1,000 sessions. + +## Rollout and rollback + +Ship readers before writers and summary indexes before hot-path migration. Keep legacy fallback for one release. Roll back consumers independently while preserving new files; never require destructive downgrade migration. + +## Observability + +Expose recordsReturned, recordsScanned, bytesRead, cursorVersion, malformedCount, partial, pruneBytes, and per-operation duration. + diff --git a/specs/performance/f-04-lsp-process-lifecycle.md b/specs/performance/f-04-lsp-process-lifecycle.md new file mode 100644 index 00000000..9e68c96d --- /dev/null +++ b/specs/performance/f-04-lsp-process-lifecycle.md @@ -0,0 +1,111 @@ +# F-04 — Own the LSP process lifecycle + +Status: Proposed +Priority: P0 when useLSP is enabled +Boundary owner: harness semantic adapter +Preventive skill: [manage-lsp-process-lifecycle](../../.context/skills/manage-lsp-process-lifecycle/SKILL.md) + +## Problem + +LSPLayer returns false after initialize failure without terminating the spawned process. A later request spawns another process and overwrites the tracked Map entry. cleanup removes bookkeeping but never kills the child, and shutdown has the same leak when the protocol request fails or times out. + +Affected code: + +- [lspLayer.ts](../../src/harness/adapters/out/semantic/lsp/lspLayer.ts) +- [codebaseAnalyzer.ts](../../src/harness/adapters/out/semantic/codebaseAnalyzer.ts) + +## Goals + +- Give every spawned process exactly one tracked owner. +- Deduplicate concurrent initialization per language and project. +- Guarantee termination after initialization failure and shutdown. +- Scope requests, buffers, and cleanup to a concrete server instance. +- Avoid retry storms while preserving regex/tree-sitter fallback. + +## Non-goals + +- Implement a general LSP client framework. +- Automatically install language servers. +- Keep a failed server alive for debugging. + +## Proposed state model + +Track a ServerHandle per language and project: + +- process; +- state: starting, ready, stopping, stopped, failed; +- initialization Promise; +- pending request IDs; +- receive buffer; +- projectPath; +- startedAt; +- termination reason. + +Do not store process, buffer, and initialized state in separate Maps. + +### Initialization + +1. Return the ready handle when available. +2. Return the existing initialization Promise while starting. +3. After a failure, open a circuit for the current analysis. +4. On failure, reject only requests owned by that handle. +5. Close stdin, send SIGTERM, wait up to 2 seconds, then SIGKILL. +6. Wait for close before deleting the handle. + +Use a spawn confirmation based on spawn/error events rather than a 100 ms timer. + +### Shutdown + +For each handle: + +1. request protocol shutdown with a 2-second timeout; +2. send exit when shutdown succeeds; +3. close stdin; +4. wait for process exit; +5. send SIGTERM, then SIGKILL after 2 seconds if necessary; +6. clear timers, listeners, buffers, and pending requests. + +shutdown must be idempotent and safe during initialization. + +### Retry policy + +- one initialization attempt per language/project per CodebaseAnalyzer; +- no per-symbol retries after failure; +- a new analyzer may retry; +- optional explicit retry method for diagnostics only. + +## Compatibility + +- Keep public LSPLayer semantic methods and fallback return values. +- Preserve useLSP=false behavior. +- Do not expose ChildProcess through public harness APIs. + +## Work breakdown + +1. Introduce ServerHandle and typed state transitions. +2. Replace Maps with handle ownership. +3. Add spawn and initialization deduplication. +4. Implement terminateProcess with grace and kill escalation. +5. Scope pending requests by handle. +6. Add circuit breaker to semantic enhancement. +7. Add fake-server fixtures for rejection, timeout, crash, and ignored shutdown. + +## Acceptance criteria + +- Initialize rejection leaves zero child processes. +- Initialize timeout leaves zero child processes. +- Two concurrent ensureServer calls spawn exactly one child. +- Repeated symbol enhancement after failure performs no new spawn. +- shutdown leaves zero children when the server ignores protocol shutdown. +- cleanup of one language does not reject another language's requests. +- All timers and listeners are removed after shutdown. +- Tests assert child exit, not only empty Maps. + +## Rollout and rollback + +Ship without a flag because the current behavior leaks processes. If an LSP implementation needs more shutdown time, adjust the bounded grace period by config; do not revert process ownership. + +## Observability + +Record language, project hash, PID, state transition, initialize duration, exit code/signal, forcedKill, pending request count, and retry suppression. Do not log source payloads returned by LSP. + diff --git a/specs/performance/f-05-shared-semantic-analysis.md b/specs/performance/f-05-shared-semantic-analysis.md new file mode 100644 index 00000000..97a5a9ff --- /dev/null +++ b/specs/performance/f-05-shared-semantic-analysis.md @@ -0,0 +1,121 @@ +# F-05 — Share semantic analysis work + +Status: Proposed +Priority: P1 +Boundary owner: harness context application +Preventive skill: [share-semantic-analysis](../../.context/skills/share-semantic-analysis/SKILL.md) + +## Problem + +The default context init maps the repository, analyzes documentation semantics, analyzes functional patterns with another analyzer, and analyzes agents with a third analyzer. Snapshot refresh can hash repository contents three times per attempt and retry three times. + +Affected code: + +- [contextTools.ts](../../src/harness/application/context/contextTools.ts) +- [documentationGenerator.ts](../../src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts) +- [agentGenerator.ts](../../src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts) +- [semanticSnapshotService.ts](../../src/harness/adapters/out/semantic/semanticSnapshotService.ts) +- [codebaseAnalyzer.ts](../../src/harness/adapters/out/semantic/codebaseAnalyzer.ts) +- [fileMapper.ts](../../src/utils/fileMapper.ts) + +## Goals + +- Perform one bounded repository discovery per context operation. +- Parse each selected source file at most once per analysis bundle. +- Reuse semantics, functional patterns, stack info, and fingerprint. +- Avoid content rehash when the repository has not changed. +- Make partial analysis explicit when limits apply. + +## Non-goals + +- Persist full symbol graphs as a public format. +- Guarantee a perfectly fresh snapshot during continuous writes. +- Analyze more than the configured file and byte budget. + +## Analysis bundle + +Add an operation-scoped AnalysisBundle in src/harness/application/context: + +- repoPath; +- discovered files and RepoStructure; +- SemanticContext; +- DetectedFunctionalPatterns; +- StackInfo; +- repo fingerprint; +- limits and partial metadata; +- metrics: filesDiscovered, filesParsed, bytesRead, duration by stage. + +Create the bundle once in HarnessContextService and inject it into generators and snapshot publication. + +CodebaseAnalyzer must expose one analyzeBundle pass that derives architecture and functional patterns from the same FileAnalysis Map. + +## Limits + +Defaults: + +| Limit | Default | +| --- | ---: | +| code files parsed | 5,000 | +| total source bytes parsed | 256 MiB | +| single source file | 2 MiB | +| file analysis concurrency | 16 | +| fingerprint attempts | 2 | + +Skip oversized files with a reason and mark partial=true. + +## Fingerprinting + +Use a staged fingerprint: + +1. enumerate only relevant paths with shared ignores; +2. hash path, size, and mtime for a fast candidate; +3. reuse cached content hashes for unchanged metadata; +4. hash content only for new or changed candidates; +5. use git index/tree identity as an additional fast signal when safe, never as the sole signal for dirty files. + +Do not glob every file and filter relevance afterward. + +Snapshot stabilization computes the initial fingerprint and one verification fingerprint. A second attempt is allowed; further instability returns a typed repositoryChanging error with the previous snapshot left readable. + +## Cache behavior + +- AnalysisBundle is operation-scoped and released after completion. +- Persistent cache stores bounded summary sections, not full FileAnalysis objects. +- Honor cacheEnabled. +- Invalidate by fingerprint, not only repository path. + +## Compatibility + +- Preserve current context init output and generated files. +- Keep SemanticContextBuilder public methods. +- Allow generators to construct their own bundle only for direct legacy calls; log a deprecation metric. + +## Work breakdown + +1. Define AnalysisLimits, AnalysisMetrics, and AnalysisBundle. +2. Unify file discovery and ignore rules. +3. Derive functional patterns from existing analyses. +4. Inject the bundle into docs and agent generators. +5. Refactor snapshot publication to consume the bundle. +6. Add incremental fingerprint cache. +7. Honor cacheEnabled and clear operation state in finally. + +## Acceptance criteria + +- Default type=both semantic init calls file parsing once per selected file. +- Functional pattern detection performs no second file read. +- Documentation and agent generators receive the same SemanticContext identity. +- A 3,000-file fixture remains within configured concurrency and byte limits. +- Oversized files are skipped and reported without crashing. +- Snapshot refresh performs no more than two stabilization attempts. +- Previous snapshots remain readable during refresh failure. +- Tests count analyzer calls, file reads, and maximum in-flight analysis. + +## Rollout and rollback + +Introduce AnalysisBundle behind the existing context service while legacy direct generator calls remain supported. Roll back individual consumers without changing the snapshot format. + +## Observability + +Record discovery, parsing, fingerprint, generation and publication durations; file and byte counts; cache hits; skipped file reasons; partial status; and stabilization attempts. + diff --git a/specs/performance/f-06-bound-mcp-payloads.md b/specs/performance/f-06-bound-mcp-payloads.md new file mode 100644 index 00000000..fee8f623 --- /dev/null +++ b/specs/performance/f-06-bound-mcp-payloads.md @@ -0,0 +1,121 @@ +# F-06 — Bound MCP payloads + +Status: Proposed +Priority: P0 for redundant parsing, P1 for complete pagination migration +Boundary owner: MCP gateway and server +Preventive skill: [bound-mcp-payloads](../../.context/skills/bound-mcp-payloads/SKILL.md) + +## Problem + +Gateway helpers serialize complete result objects into pretty JSON. The server then parses the same text to derive a small audit summary. Runtime list actions have no cursor and schema fields that can carry large content have no explicit size constraints. + +Affected code: + +- [response.ts](../../src/mcp/gateway/response.ts) +- [mcpServer.ts](../../src/mcp/server/mcpServer.ts) +- [actionLogger.ts](../../src/mcp/logging/actionLogger.ts) +- [actionService.ts](../../src/harness/application/actions/actionService.ts) + +## Goals + +- Eliminate response stringify/parse duplication. +- Bound every MCP list response. +- Validate caller-provided sizes and limits. +- Return actionable partial or too-large responses. +- Preserve transport-neutral behavior in harness. + +## Non-goals + +- Stream arbitrary MCP tool responses over a custom transport. +- Move pagination logic into MCP when it belongs in harness. +- Return raw runtime files as text. + +## Structured audit metadata + +Use the MCP result _meta field for bounded dotcontext audit metadata: + +- success; +- errorCode when present; +- scalar summary keys; +- itemCount; +- partial. + +Gateway response helpers construct content and audit metadata from the original result. logToolResponse reads _meta and response.isError; it must never JSON.parse response text. + +The dotcontext metadata object must remain below 2 KiB and contain no caller content. + +## Pagination + +Expose the F-03 cursor contracts for: + +- listSessions; +- listTraces; +- listArtifacts; +- listReplays; +- listDatasets; +- listTasks and listHandoffs if their counts can grow without bound. + +Defaults and maxima come from harness. MCP Zod schemas enforce integer, positive, bounded limit values. maxEvents defaults to 100 and is capped at 1,000. + +## Payload budget + +Set a default MCP text payload budget of 1 MiB and an absolute maximum of 4 MiB. + +Before final response: + +1. serialize compact JSON once; +2. measure UTF-8 bytes; +3. if over budget and pagination is available, return a typed pageTooLarge error with a smaller suggested limit; +4. if content is an export, persist it as a harness artifact and return metadata; +5. never truncate JSON text at an arbitrary byte boundary. + +Do not pretty-print responses above 64 KiB. Compact JSON is the default for machine transport. + +## Input bounds + +Apply schema maxima to: + +- content and scalar strings; +- data/output/details object depth and serialized bytes; +- arrays such as evidence, artifacts, sessionIds, and requiredArtifacts; +- regex and glob pattern length; +- maxResults, limit, and maxEvents. + +Validate serialized object bytes in application code because Zod shape limits alone are insufficient. + +## Compatibility + +- Preserve content text for MCP clients. +- Add _meta without requiring clients to consume it. +- Keep existing actions but change unlimited lists to bounded defaults. +- Document how to continue with nextCursor. + +## Work breakdown + +1. Add audit metadata to response helpers. +2. Remove parseResponsePayload. +3. Add shared input-size validation. +4. Wire F-03 pagination into schemas and gateways. +5. Add single-serialization payload guard. +6. Update MCP README, public docs, and CHANGELOG. + +## Acceptance criteria + +- logToolResponse performs zero JSON.parse calls on response content. +- A listTraces request without limit returns no more than 100 items. +- Limits above maximum fail schema validation. +- No successful MCP text response exceeds the configured budget without an explicit export reference. +- JSON is serialized exactly once in the normal response path. +- Audit metadata remains below 2 KiB and contains no content fields. +- Existing clients can read success/error content. +- Gateway and server tests cover boundaries at limit-1, limit, and limit+1. +- Package build and smoke tests pass. + +## Rollout and rollback + +Remove redundant parsing immediately. Ship pagination after F-03. If a client depends on unlimited lists, provide a temporary compatibility option capped by the absolute payload budget; do not restore unlimited defaults. + +## Observability + +Record responseBytes, serializationMs, itemCount, partial, requestedLimit, appliedLimit, and pageTooLarge. Do not log response bodies. + diff --git a/specs/performance/f-07-cache-retention.md b/specs/performance/f-07-cache-retention.md new file mode 100644 index 00000000..ad0fcc61 --- /dev/null +++ b/specs/performance/f-07-cache-retention.md @@ -0,0 +1,123 @@ +# F-07 — Govern cache and persistent retention + +Status: Proposed +Priority: P1 +Boundary owners: harness, MCP logging, integrations +Preventive skill: [govern-cache-retention](../../.context/skills/govern-cache-retention/SKILL.md) + +## Problem + +Several caches and persistent indexes have no maximum size, complete invalidation, or cleanup lifecycle. ContextCache expires only on access, SemanticContextBuilder retains a full graph without file invalidation, MCP sessionCache has no TTL, host session bindings never expire, and checkpoints grow inside session.json that is rewritten on every trace. + +Affected code: + +- [contextCache.ts](../../src/harness/adapters/out/semantic/contextCache.ts) +- [contextBuilder.ts](../../src/harness/adapters/out/semantic/contextBuilder.ts) +- [actionLogger.ts](../../src/mcp/logging/actionLogger.ts) +- [hookSessionStore.ts](../../src/integrations/shared/hookSessionStore.ts) +- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) + +## Goals + +- Give every in-memory cache entry, byte, and age limits. +- Make expiration proactive at safe lifecycle points. +- Keep cache freshness tied to source identity. +- Bound host bindings and checkpoint persistence. +- Centralize runtime retention configuration with safe defaults. + +## Non-goals + +- Share caches between OS processes. +- Guarantee exact memory accounting. +- Delete active workflow data. + +## Cache contract + +Every cache must declare: + +- key normalization; +- maximum entries; +- estimated maximum bytes; +- TTL; +- freshness signal; +- eviction order; +- cleanup trigger; +- stop/dispose behavior; +- metrics. + +Defaults: + +| Cache | Entries | Estimated bytes | TTL | +| --- | ---: | ---: | ---: | +| ContextCache | 16 | 32 MiB | 5 minutes | +| SemanticContextBuilder | 1 | 64 MiB | fingerprint-bound | +| MCP session cache | 64 | negligible | 30 minutes idle | +| Tree-sitter FileAnalysis | 5,000 | 128 MiB | analysis lifecycle | + +Use LRU within TTL. Reject a single entry larger than its cache byte budget. + +### Context cache + +- sweep expired entries on set and at a bounded interval; +- unref the sweep timer; +- clear on MCP stop; +- include target file and relevant options in the key; +- use fingerprint/mtime for freshness. + +### Semantic builder and tree-sitter + +- honor cacheEnabled; +- invalidate full SemanticContext when repository fingerprint changes; +- evict removed file paths; +- release analysis cache after operation-scoped use from F-05. + +### Session cache and host bindings + +- normalize repoPath before using it as a key; +- LRU/idle-expire MCP session entries; +- remove cache entry when the session completes or disappears; +- expire host bindings after 30 days or when the bound harness session is missing; +- cap bindings at 1,000 per repository; +- prune during SessionStart and explicit maintenance, not every PostToolUse. + +### Checkpoints + +Move checkpoints from the growing session.json array to append-only checkpoint records or individual files. Keep only checkpointCount, lastCheckpointAt, and lastCheckpointId in session.json. + +Read legacy embedded checkpoints and migrate lazily on the next checkpoint write. Cap checkpoint data at 64 KiB and artifactIds at 200. + +## Runtime configuration + +Create .context/config/runtime.json with versioned sections for traces, sessions, replays, datasets, checkpoints, bindings, and caches. Defaults apply when absent. Unknown keys are ignored with a diagnostic; invalid unsafe values are clamped. + +## Work breakdown + +1. Define reusable LRU byte-budget utility. +2. Apply it to ContextCache and MCP session cache. +3. Honor semantic cacheEnabled and fingerprint freshness. +4. Add host binding prune and cap. +5. Externalize checkpoints with legacy migration. +6. Add runtime config schema and maintenance service. +7. Connect repository retention to F-03 prune. + +## Acceptance criteria + +- Inserting more than maxEntries evicts the least recently used entry. +- Expired entries disappear without being accessed individually. +- MCP stop leaves cache size zero and no referenced sweep timer. +- cacheEnabled=false stores no FileAnalysis or SemanticContext. +- Changing a source fingerprint invalidates semantic context. +- host-sessions.json never exceeds the configured binding cap. +- Missing harness sessions cause stale binding removal. +- Adding a checkpoint does not grow session.json with checkpoint payload history. +- Legacy embedded checkpoints remain readable and migrate without loss. +- Runtime config invalid values cannot disable absolute safety ceilings. + +## Rollout and rollback + +Land cache bounds independently. Migrate checkpoints with dual-read/new-write behavior. Keep legacy fields readable for at least one minor release. Rollback must not discard new checkpoint files. + +## Observability + +Expose entries, estimatedBytes, hit, miss, eviction reason, oldest age, stale binding count, checkpoint migration count, config clamps, and cleanup duration. + From 16eac4f37f76d5081d5975295feb6ed0e104c3a8 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 12:58:02 -0300 Subject: [PATCH 02/39] perf: share semantic analysis during context init --- .../__tests__/codebaseAnalyzer.test.ts | 20 ++++++++ .../adapters/out/semantic/codebaseAnalyzer.ts | 40 +++++++++++++-- .../context/__tests__/contextTools.test.ts | 19 +++++++ .../application/context/contextTools.ts | 51 ++++++++++++++++--- .../generators/agents/agentGenerator.ts | 11 ++-- .../documentation/documentationGenerator.ts | 29 ++++++++--- 6 files changed, 149 insertions(+), 21 deletions(-) diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index e1a01ec2..2d354a2a 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -121,6 +121,26 @@ describe('CodebaseAnalyzer', () => { }); describe('analyze', () => { + it('builds semantic context and functional patterns from one file-analysis pass', async () => { + const analyzer = new CodebaseAnalyzer({ useLSP: false }); + const internal = analyzer as unknown as { + findCodeFiles(projectPath: string): Promise; + analyzeFiles(files: string[]): Promise>; + }; + const findSpy = jest.spyOn(internal, 'findCodeFiles'); + const analyzeSpy = jest.spyOn(internal, 'analyzeFiles'); + + const bundle = await analyzer.analyzeBundle(tempDir); + + expect(findSpy).toHaveBeenCalledTimes(1); + expect(analyzeSpy).toHaveBeenCalledTimes(1); + expect(bundle.context.stats.totalFiles).toBeGreaterThan(0); + expect(bundle.functionalPatterns).toEqual(expect.objectContaining({ + patterns: expect.any(Array), + })); + expect(bundle.files).toHaveLength(bundle.context.stats.totalFiles); + }); + it('should analyze files with Tree-sitter by default', async () => { const analyzer = new CodebaseAnalyzer({ useLSP: false }); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 05b12438..fab49a9a 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -38,6 +38,12 @@ const DEFAULT_OPTIONS: Required = { cacheEnabled: true, }; +export interface SemanticAnalysisBundle { + context: SemanticContext; + functionalPatterns: DetectedFunctionalPatterns; + files: string[]; +} + export class CodebaseAnalyzer { private treeSitter: TreeSitterLayer; private lspLayer?: LSPLayer; @@ -54,6 +60,23 @@ export class CodebaseAnalyzer { } async analyze(projectPath: string): Promise { + return (await this.analyzeProject(projectPath)).context; + } + + async analyzeBundle(projectPath: string): Promise { + const { context, files, fileAnalyses } = await this.analyzeProject(projectPath); + return { + context, + functionalPatterns: this.detectFunctionalPatternsFromAnalyses(files, fileAnalyses), + files, + }; + } + + private async analyzeProject(projectPath: string): Promise<{ + context: SemanticContext; + files: string[]; + fileAnalyses: Map; + }> { const startTime = Date.now(); // 1. Find all code files @@ -76,7 +99,11 @@ export class CodebaseAnalyzer { // 6. Calculate stats context.stats.analysisTimeMs = Date.now() - startTime; - return context; + return { + context, + files, + fileAnalyses, + }; } private async findCodeFiles(projectPath: string): Promise { @@ -102,9 +129,9 @@ export class CodebaseAnalyzer { } // Apply include filter if specified - let filteredFiles = allFiles; + let filteredFiles = [...new Set(allFiles)]; if (this.options.include.length > 0) { - filteredFiles = allFiles.filter((file) => + filteredFiles = filteredFiles.filter((file) => this.options.include.some((pattern) => file.includes(pattern)) ); } @@ -674,6 +701,13 @@ export class CodebaseAnalyzer { const files = await this.findCodeFiles(projectPath); const analyses = await this.analyzeFiles(files); + return this.detectFunctionalPatternsFromAnalyses(files, analyses); + } + + private detectFunctionalPatternsFromAnalyses( + files: string[], + analyses: Map + ): DetectedFunctionalPatterns { const patterns: FunctionalPattern[] = []; const allSymbols = [...analyses.values()].flatMap((a) => a.symbols); const allImports = [...analyses.values()].flatMap((a) => diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index 40e76dec..d0497653 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -9,6 +9,7 @@ import { listFilesToFillTool, } from '../contextTools'; import { toolExecutionContext } from '../../../../shared'; +import { CodebaseAnalyzer } from '../../../adapters/out/semantic'; describe('contextTools sensors scaffolding', () => { let tempDir: string; @@ -29,9 +30,27 @@ describe('contextTools sensors scaffolding', () => { }); afterEach(async () => { + jest.restoreAllMocks(); await fs.remove(tempDir); }); + it('shares one semantic analysis bundle across docs, snapshot, and agents', async () => { + const analyzeBundle = jest.spyOn(CodebaseAnalyzer.prototype, 'analyzeBundle'); + + await initializeContextTool.execute!( + { + repoPath: tempDir, + type: 'both', + semantic: true, + generateQA: false, + skipContentGeneration: true, + }, + toolExecutionContext + ); + + expect(analyzeBundle).toHaveBeenCalledTimes(1); + }); + it('includes bootstrap sensors.json in pending writes and listToFill', async () => { const result = await initializeContextTool.execute!( { diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 26e946ef..14a6b8a6 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -8,7 +8,11 @@ import { FileMapper } from '../../../utils/fileMapper'; import { needsFill } from '../../../utils/frontMatter'; import { getScaffoldStructure, serializeStructureForAI } from './scaffolding/generators/shared/structures'; import { DocumentationGenerator } from './scaffolding/generators/documentation/documentationGenerator'; -import { SemanticSnapshotService } from '../../adapters/out/semantic'; +import { + CodebaseAnalyzer, + SemanticSnapshotService, + type SemanticAnalysisBundle, +} from '../../adapters/out/semantic'; import { AgentGenerator } from './scaffolding/generators/agents/agentGenerator'; import { SkillGenerator } from './scaffolding/generators/skills/skillGenerator'; import { PlanGenerator } from './scaffolding/generators/plans/planGenerator'; @@ -642,12 +646,34 @@ export const initializeContextTool = createInternalTool< const fileMapper = new FileMapper(exclude); const repoStructure = await fileMapper.mapRepository(resolvedRepoPath, include); + let semanticBundle: SemanticAnalysisBundle | undefined; + let semanticFingerprint: string | undefined; + if (semantic) { + const analyzer = new CodebaseAnalyzer({ + exclude: [...new Set([...DEFAULT_EXCLUDE_PATTERNS, ...exclude])], + }); + try { + const snapshotService = new SemanticSnapshotService(); + semanticFingerprint = await snapshotService.captureRepoFingerprint(resolvedRepoPath); + semanticBundle = await analyzer.analyzeBundle(resolvedRepoPath); + } catch { + semanticBundle = undefined; + semanticFingerprint = undefined; + } finally { + await analyzer.shutdown(); + } + } + let classification: ProjectClassification | undefined; let projectType: ProjectType = 'unknown'; + let detectedStackInfo: Awaited> | undefined; - if (!disableFiltering) { + if (!disableFiltering || semantic) { const stackDetector = new StackDetector(); - const stackInfo = await stackDetector.detect(resolvedRepoPath); + detectedStackInfo = await stackDetector.detect(resolvedRepoPath); + } + + if (!disableFiltering) { if (overrideProjectType) { projectType = overrideProjectType; classification = { @@ -657,7 +683,7 @@ export const initializeContextTool = createInternalTool< reasoning: ['Project type manually specified'], }; } else { - classification = classifyProject(stackInfo); + classification = classifyProject(detectedStackInfo!); projectType = classification.primaryType; } } @@ -672,7 +698,14 @@ export const initializeContextTool = createInternalTool< docsGenerated = await docGenerator.generateDocumentation( repoStructure, outputDir, - { semantic, filteredDocs }, + { + semantic, + filteredDocs, + semanticContext: semanticBundle?.context, + functionalPatterns: semanticBundle?.functionalPatterns, + stackInfo: detectedStackInfo, + repoFingerprint: semanticFingerprint, + }, false ); } @@ -716,7 +749,13 @@ export const initializeContextTool = createInternalTool< agentsGenerated = await agentGenerator.generateAgentPrompts( repoStructure, outputDir, - { semantic, filteredAgents, availableSkills }, + { + semantic, + filteredAgents, + availableSkills, + semanticContext: semanticBundle?.context, + stackInfo: detectedStackInfo, + }, false ); } diff --git a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts index 9a88fde8..ea61702d 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts @@ -40,6 +40,9 @@ interface AgentGenerationConfig { autoFill?: boolean; /** Available skills that agents can reference */ availableSkills?: AvailableSkill[]; + /** Operation-scoped data supplied by context init. */ + semanticContext?: SemanticContext; + stackInfo?: StackInfo; } /** @@ -116,8 +119,8 @@ export class AgentGenerator { await GeneratorUtils.ensureDirectoryAndLog(agentsDir, verbose, 'Generating agent scaffold in'); // Perform semantic analysis if enabled - let semantics: SemanticContext | undefined; - if (normalizedConfig.semantic) { + let semantics = normalizedConfig.semanticContext; + if (normalizedConfig.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis for agents...', verbose); this.analyzer = new CodebaseAnalyzer(); try { @@ -132,8 +135,8 @@ export class AgentGenerator { } // Detect stack info for autoFill - let stackInfo: StackInfo | undefined; - if (normalizedConfig.autoFill) { + let stackInfo = normalizedConfig.stackInfo; + if (!stackInfo && normalizedConfig.autoFill) { try { const stackDetector = new StackDetector(); stackInfo = await stackDetector.detect(repoStructure.rootPath); diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index 2b07c375..49d31130 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -8,8 +8,13 @@ import { renderIndex, } from './templates'; import { getGuidesByKeys, DOCUMENT_GUIDES } from './guideRegistry'; -import { CodebaseAnalyzer, SemanticContext, SemanticSnapshotService } from '../../../../../adapters/out/semantic'; -import { StackDetector } from '../../../intelligence/stack'; +import { + CodebaseAnalyzer, + SemanticContext, + SemanticSnapshotService, + type DetectedFunctionalPatterns, +} from '../../../../../adapters/out/semantic'; +import { StackDetector, type StackInfo } from '../../../intelligence/stack'; import { createDocFrontmatter, serializeFrontmatter, @@ -57,6 +62,11 @@ interface DocumentationGenerationConfig { includeContentStubs?: boolean; /** Fill scaffolds with semantic data (no LLM required) */ autoFill?: boolean; + /** Operation-scoped semantic data supplied by context init. */ + semanticContext?: SemanticContext; + functionalPatterns?: DetectedFunctionalPatterns; + stackInfo?: StackInfo; + repoFingerprint?: string; } export class DocumentationGenerator { @@ -72,12 +82,14 @@ export class DocumentationGenerator { ): Promise { const docsDir = path.join(outputDir, 'docs'); await GeneratorUtils.ensureDirectoryAndLog(docsDir, verbose, 'Generating documentation scaffold in'); - const snapshotService = config.semantic ? new SemanticSnapshotService() : null; + const snapshotService = (config.semantic || config.semanticContext) + ? new SemanticSnapshotService() + : null; // Perform semantic analysis if enabled - let semantics: SemanticContext | undefined; - let snapshotFingerprint: string | undefined; - if (config.semantic) { + let semantics = config.semanticContext; + let snapshotFingerprint = config.repoFingerprint; + if (config.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis...', verbose); this.analyzer = new CodebaseAnalyzer(); try { @@ -93,8 +105,8 @@ export class DocumentationGenerator { } // Detect stack info for codebase map and autoFill - let stackInfo; - if (semantics || config.autoFill) { + let stackInfo = config.stackInfo; + if (!stackInfo && (semantics || config.autoFill)) { try { const stackDetector = new StackDetector(); stackInfo = await stackDetector.detect(repoStructure.rootPath); @@ -111,6 +123,7 @@ export class DocumentationGenerator { outputDir, semantics, stackInfo, + functionalPatterns: config.functionalPatterns, repoFingerprint: snapshotFingerprint, }); From aca5641b12a879dcf60abc6579dfffa074f02192 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:00:37 -0300 Subject: [PATCH 03/39] fix: bound subprocess output capture --- .../sensors/__tests__/testsPassing.test.ts | 100 ++++- .../adapters/out/sensors/testsPassing.ts | 369 +++++++++++++----- .../adapters/out/sensors/typecheckClean.ts | 39 +- .../__tests__/boundedByteCollector.test.ts | 51 +++ .../domain/execution/boundedByteCollector.ts | 136 +++++++ src/harness/domain/execution/index.ts | 12 + src/harness/domain/index.ts | 1 + .../plans/__tests__/acceptanceRunner.test.ts | 42 ++ .../domain/workflow/plans/acceptanceRunner.ts | 95 +++-- .../domain/workflow/plans/executionTypes.ts | 9 + .../workflow/plans/planUpdateOrchestrator.ts | 6 +- 11 files changed, 723 insertions(+), 137 deletions(-) create mode 100644 src/harness/domain/execution/__tests__/boundedByteCollector.test.ts create mode 100644 src/harness/domain/execution/boundedByteCollector.ts create mode 100644 src/harness/domain/execution/index.ts diff --git a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts index f613a95b..b8077718 100644 --- a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts +++ b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts @@ -1,7 +1,12 @@ import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { executeTestsPassing } from '../testsPassing'; +import { + executeTestsPassing, + readJestResultFile, + runShell, +} from '../testsPassing'; describe('tests-passing sensor', () => { let tempDir: string; @@ -35,6 +40,30 @@ describe('tests-passing sensor', () => { expect(out.numFailedTests).toBe(0); }); + it('uses a temporary output file for the default Jest command', async () => { + await fs.writeJson(path.join(tempDir, 'package.json'), { + scripts: { test: 'node fake-jest.js' }, + }); + await fs.writeFile( + path.join(tempDir, 'fake-jest.js'), + [ + "const fs = require('fs');", + "const outputFlag = process.argv.indexOf('--outputFile');", + "const resultPath = process.argv[outputFlag + 1];", + 'fs.writeFileSync(resultPath, JSON.stringify({', + ' numPassedTests: 3, numFailedTests: 0, numTotalTestSuites: 1, testResults: []', + '}));', + "process.stdout.write('bounded console output');", + ].join('\n') + ); + + const result = await executeTestsPassing(tempDir, { sessionId: 's' }); + + expect(result.status).toBe('passed'); + expect(result.output).toEqual(expect.objectContaining({ numPassedTests: 3 })); + expect(result.details).toEqual(expect.objectContaining({ command: 'npm' })); + }); + it('fails when jest JSON reports failed tests and captures failure names', async () => { const json = JSON.stringify({ numPassedTests: 1, @@ -87,4 +116,73 @@ describe('tests-passing sensor', () => { expect(bad.status).toBe('failed'); expect(bad.summary).toContain('exit 2'); }); + + it('bounds both console streams while retaining counters', async () => { + const result = await runShell( + nodeScript('process.stdout.write("a".repeat(1000)); process.stderr.write("b".repeat(800))'), + tempDir, + 5_000, + { tailBytes: 32 } + ); + + expect(Buffer.byteLength(result.stdoutTail)).toBe(32); + expect(Buffer.byteLength(result.stderrTail)).toBe(32); + expect(result.stdoutBytes).toBe(1000); + expect(result.stderrBytes).toBe(800); + expect(result.outputTruncated).toBe(true); + }); + + it('fails with a stable reason when output exceeds the hard limit', async () => { + const result = await executeTestsPassing(tempDir, { + sessionId: 's', + context: { + kind: 'exit-code', + testCommand: nodeScript( + 'const c="x".repeat(4096); for(let i=0;i<10000;i++) process.stdout.write(c)' + ), + tailBytes: 128, + hardOutputLimitBytes: 32 * 1024, + }, + }); + + expect(result.status).toBe('failed'); + expect(result.summary).toContain('outputLimitExceeded'); + expect(result.details).toEqual(expect.objectContaining({ + outputLimitExceeded: true, + terminationReason: 'outputLimit', + outputTruncated: true, + })); + }); + + it('reports timeout and spawn error termination paths', async () => { + const timedOut = await executeTestsPassing(tempDir, { + sessionId: 's', + context: { + kind: 'exit-code', + testCommand: nodeScript('setTimeout(() => {}, 5000)'), + timeoutMs: 50, + }, + }); + expect(timedOut.summary).toMatch(/timed out/); + expect(timedOut.details).toEqual(expect.objectContaining({ terminationReason: 'timeout' })); + + const spawnError = await executeTestsPassing(tempDir, { + sessionId: 's', + context: { kind: 'exit-code', testCommand: ['definitely-not-a-real-command-dotcontext'] }, + }); + expect(spawnError.summary).toMatch(/spawn error/); + expect(spawnError.details).toEqual(expect.objectContaining({ terminationReason: 'spawnError' })); + }); + + it('rejects oversized and malformed Jest result files before parsing', async () => { + const oversized = path.join(tempDir, 'oversized.json'); + const handle = await nativeFs.open(oversized, 'w'); + await handle.truncate(32 * 1024 * 1024 + 1); + await handle.close(); + await expect(readJestResultFile(oversized)).resolves.toEqual({ status: 'resultFileTooLarge' }); + + const malformed = path.join(tempDir, 'malformed.json'); + await fs.writeFile(malformed, '{not-json'); + await expect(readJestResultFile(malformed)).resolves.toEqual({ status: 'malformed' }); + }); }); diff --git a/src/harness/adapters/out/sensors/testsPassing.ts b/src/harness/adapters/out/sensors/testsPassing.ts index a3e53e7d..194bbe8c 100644 --- a/src/harness/adapters/out/sensors/testsPassing.ts +++ b/src/harness/adapters/out/sensors/testsPassing.ts @@ -2,9 +2,10 @@ * Built-in `tests-passing` sensor. * * Two modes: - * - `kind: 'jest'` (default): runs `npm test -- --runInBand --json` (or a - * configured `testCommand` argv array) and parses the JSON result on - * stdout. Passes iff exit code 0 AND `numFailedTests === 0`. + * - `kind: 'jest'` (default): runs `npm test -- --runInBand --json`, writes + * structured results to a size-checked temporary file, and keeps console + * output bounded. Configured commands retain legacy JSON-on-stdout parsing. + * Passes iff exit code 0 AND `numFailedTests === 0`. * - `kind: 'exit-code'`: runs the configured `testCommand` argv array and * passes iff the process exits with code 0. Use this for non-jest test * runners. @@ -16,16 +17,29 @@ */ import { spawn } from 'child_process'; +import { promises as fs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; import type { HarnessSensorDefinition, HarnessSensorExecutionInput, HarnessSensorExecutionResult, } from '../../../application/sensors/sensorsService'; +import { + BoundedByteCollector, + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + DEFAULT_SUBPROCESS_TAIL_BYTES, + MAX_JEST_RESULT_FILE_BYTES, + resolveSubprocessOutputLimits, + type SubprocessOutputLimitsInput, +} from '../../../domain/execution'; export interface TestsPassingOptions { kind?: 'jest' | 'exit-code'; testCommand?: string[]; timeoutMs?: number; + tailBytes?: number; + hardOutputLimitBytes?: number; } export interface TestsPassingReport { @@ -37,9 +51,12 @@ export interface TestsPassingReport { const DEFAULT_TIMEOUT_MS = 300_000; const DEFAULT_JEST_COMMAND: string[] = ['npm', 'test', '--', '--runInBand', '--json']; -const TAIL_LIMIT_BYTES = 8 * 1024; -function readOptions(input: HarnessSensorExecutionInput): Required { +interface ResolvedTestsPassingOptions extends Required { + usesDefaultCommand: boolean; +} + +function readOptions(input: HarnessSensorExecutionInput): ResolvedTestsPassingOptions { const ctx = (input.context && typeof input.context === 'object' ? input.context : {}) as TestsPassingOptions; const meta = (input.metadata && typeof input.metadata === 'object' ? (input.metadata as Record) @@ -50,28 +67,57 @@ function readOptions(input: HarnessSensorExecutionInput): Required 0 ? cmd : DEFAULT_JEST_COMMAND, timeoutMs: ctx.timeoutMs ?? meta.timeoutMs ?? DEFAULT_TIMEOUT_MS, + tailBytes: ctx.tailBytes ?? meta.tailBytes ?? DEFAULT_SUBPROCESS_TAIL_BYTES, + hardOutputLimitBytes: + ctx.hardOutputLimitBytes ?? meta.hardOutputLimitBytes ?? DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + usesDefaultCommand: !Array.isArray(cmd) || cmd.length === 0, }; } -interface SpawnResult { +export interface SpawnResult { exitCode: number | null; - stdout: string; - stderr: string; + stdoutTail: string; + stderrTail: string; + stdoutBytes: number; + stderrBytes: number; + stdoutDroppedBytes: number; + stderrDroppedBytes: number; + outputTruncated: boolean; + outputLimitExceeded: boolean; timedOut: boolean; + durationMs: number; spawnError?: string; + terminationReason?: 'timeout' | 'outputLimit' | 'spawnError'; } -function tail(s: string, limit: number): string { - return s.length <= limit ? s : s.slice(s.length - limit); +function emptySpawnResult(startedAt: number, spawnError: string): SpawnResult { + return { + exitCode: null, + stdoutTail: '', + stderrTail: '', + stdoutBytes: 0, + stderrBytes: 0, + stdoutDroppedBytes: 0, + stderrDroppedBytes: 0, + outputTruncated: false, + outputLimitExceeded: false, + timedOut: false, + durationMs: Date.now() - startedAt, + spawnError, + terminationReason: 'spawnError', + }; } export function runShell( argv: string[], cwd: string, - timeoutMs: number + timeoutMs: number, + outputLimits: SubprocessOutputLimitsInput = {} ): Promise { return new Promise((resolve) => { + const startedAt = Date.now(); const [executable, ...args] = argv; + const limits = resolveSubprocessOutputLimits(outputLimits); let child: ReturnType; try { child = spawn(executable, args, { @@ -81,43 +127,69 @@ export function runShell( env: process.env, }); } catch (err) { - resolve({ - exitCode: null, - stdout: '', - stderr: '', - timedOut: false, - spawnError: err instanceof Error ? err.message : String(err), - }); + resolve(emptySpawnResult(startedAt, err instanceof Error ? err.message : String(err))); return; } - const stdoutChunks: Buffer[] = []; - const stderrChunks: Buffer[] = []; + const stdout = new BoundedByteCollector(limits.tailBytes); + const stderr = new BoundedByteCollector(limits.tailBytes); let timedOut = false; + let outputLimitExceeded = false; let settled = false; + let spawnError: Error | undefined; + + let timer: NodeJS.Timeout; + const capture = (collector: BoundedByteCollector, chunk: Buffer) => { + collector.append(chunk); + if ( + !outputLimitExceeded && + stdout.totalBytes + stderr.totalBytes > limits.hardCombinedOutputBytes + ) { + outputLimitExceeded = true; + clearTimeout(timer); + child.kill('SIGKILL'); + } + }; - child.stdout?.on('data', (c: Buffer) => stdoutChunks.push(c)); - child.stderr?.on('data', (c: Buffer) => stderrChunks.push(c)); + child.stdout?.on('data', (chunk: Buffer) => capture(stdout, chunk)); + child.stderr?.on('data', (chunk: Buffer) => capture(stderr, chunk)); - const timer = setTimeout(() => { + timer = setTimeout(() => { + if (outputLimitExceeded) return; timedOut = true; child.kill('SIGKILL'); }, timeoutMs); - const finish = (exitCode: number | null, spawnError?: Error) => { + const finish = (exitCode: number | null) => { if (settled) return; settled = true; clearTimeout(timer); resolve({ exitCode, - stdout: Buffer.concat(stdoutChunks).toString('utf-8'), - stderr: Buffer.concat(stderrChunks).toString('utf-8'), + stdoutTail: stdout.toString(), + stderrTail: stderr.toString(), + stdoutBytes: stdout.totalBytes, + stderrBytes: stderr.totalBytes, + stdoutDroppedBytes: stdout.droppedBytes, + stderrDroppedBytes: stderr.droppedBytes, + outputTruncated: stdout.truncated || stderr.truncated, + outputLimitExceeded, timedOut, + durationMs: Date.now() - startedAt, spawnError: spawnError?.message, + terminationReason: outputLimitExceeded + ? 'outputLimit' + : timedOut + ? 'timeout' + : spawnError + ? 'spawnError' + : undefined, }); }; - child.on('error', (err) => finish(null, err)); + // Wait for close after error/kill so the child is always reaped before the + // promise resolves. + child.on('error', (err) => { spawnError = err; }); child.on('close', (code) => finish(code)); }); } @@ -139,107 +211,192 @@ function extractJsonFromStdout(stdout: string): unknown | null { } } +export type JestResultFileRead = + | { status: 'ok'; value: unknown } + | { status: 'resultFileTooLarge' } + | { status: 'malformed' }; + +export async function readJestResultFile(resultPath: string): Promise { + try { + const stat = await fs.stat(resultPath); + if (stat.size > MAX_JEST_RESULT_FILE_BYTES) { + return { status: 'resultFileTooLarge' }; + } + const contents = await fs.readFile(resultPath, 'utf-8'); + return { status: 'ok', value: JSON.parse(contents) }; + } catch { + return { status: 'malformed' }; + } +} + +export function subprocessDetails(result: SpawnResult, argv: string[]): Record { + return { + command: path.basename(argv[0] ?? ''), + durationMs: result.durationMs, + stdoutBytes: result.stdoutBytes, + stderrBytes: result.stderrBytes, + stdoutDroppedBytes: result.stdoutDroppedBytes, + stderrDroppedBytes: result.stderrDroppedBytes, + outputTruncated: result.outputTruncated, + outputLimitExceeded: result.outputLimitExceeded, + terminationReason: result.terminationReason, + }; +} + export async function executeTestsPassing( repoPath: string, input: HarnessSensorExecutionInput ): Promise { const opts = readOptions(input); + let resultDirectory: string | undefined; + let resultPath: string | undefined; + let command = opts.testCommand; + if (opts.kind === 'jest' && opts.usesDefaultCommand) { + resultDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-jest-')); + resultPath = path.join(resultDirectory, 'result.json'); + command = [...DEFAULT_JEST_COMMAND, '--outputFile', resultPath]; + } - const result = await runShell(opts.testCommand, repoPath, opts.timeoutMs); + try { + const result = await runShell(command, repoPath, opts.timeoutMs, { + tailBytes: opts.tailBytes, + hardCombinedOutputBytes: opts.hardOutputLimitBytes, + }); - if (result.spawnError) { - return { - status: 'failed', - summary: `tests-passing: spawn error: ${result.spawnError}`, - evidence: [`command: ${opts.testCommand.join(' ')}`], - }; - } + const details = subprocessDetails(result, command); - if (result.timedOut) { - return { - status: 'failed', - summary: `tests-passing: timed out after ${opts.timeoutMs}ms`, - evidence: [`command: ${opts.testCommand.join(' ')}`, tail(result.stderr, TAIL_LIMIT_BYTES)], - }; - } + if (result.spawnError) { + return { + status: 'failed', + summary: `tests-passing: spawn error: ${result.spawnError}`, + evidence: [`command: ${command.join(' ')}`], + details, + }; + } - if (opts.kind === 'exit-code') { - if (result.exitCode === 0) { + if (result.outputLimitExceeded) { return { - status: 'passed', - summary: 'tests-passing: exit 0', - evidence: [`command: ${opts.testCommand.join(' ')}`], + status: 'failed', + summary: 'tests-passing: outputLimitExceeded', + evidence: [`command: ${command.join(' ')}`, result.stderrTail].filter(Boolean), + details, }; } - return { - status: 'failed', - summary: `tests-passing: exit ${result.exitCode}`, - evidence: [`command: ${opts.testCommand.join(' ')}`, tail(result.stderr, TAIL_LIMIT_BYTES)], - }; - } - // jest mode - const parsed = extractJsonFromStdout(result.stdout); - if (!parsed || typeof parsed !== 'object') { - return { - status: 'failed', - summary: 'tests-passing: could not parse jest --json output', - evidence: [ - `command: ${opts.testCommand.join(' ')}`, - `exitCode: ${result.exitCode}`, - tail(result.stdout, TAIL_LIMIT_BYTES), - tail(result.stderr, TAIL_LIMIT_BYTES), - ].filter(Boolean), - }; - } + if (result.timedOut) { + return { + status: 'failed', + summary: `tests-passing: timed out after ${opts.timeoutMs}ms`, + evidence: [`command: ${command.join(' ')}`, result.stderrTail].filter(Boolean), + details, + }; + } - const j = parsed as Record; - const numPassedTests = typeof j.numPassedTests === 'number' ? j.numPassedTests : 0; - const numFailedTests = typeof j.numFailedTests === 'number' ? j.numFailedTests : 0; - const numTotalTestSuites = typeof j.numTotalTestSuites === 'number' ? j.numTotalTestSuites : 0; - - const failures: Array<{ name: string; message: string }> = []; - const testResults = Array.isArray(j.testResults) ? j.testResults : []; - for (const suite of testResults) { - if (!suite || typeof suite !== 'object') continue; - const s = suite as Record; - const assertionResults = Array.isArray(s.assertionResults) ? s.assertionResults : []; - for (const a of assertionResults) { - if (!a || typeof a !== 'object') continue; - const ar = a as Record; - if (ar.status === 'failed') { - const messages = Array.isArray(ar.failureMessages) ? ar.failureMessages : []; - failures.push({ - name: typeof ar.fullName === 'string' ? ar.fullName : (typeof ar.title === 'string' ? ar.title : 'unknown'), - message: messages.map((m) => String(m)).join('\n').slice(0, 2000), - }); + if (opts.kind === 'exit-code') { + if (result.exitCode === 0) { + return { + status: 'passed', + summary: 'tests-passing: exit 0', + evidence: [`command: ${command.join(' ')}`], + details, + }; } + return { + status: 'failed', + summary: `tests-passing: exit ${result.exitCode}`, + evidence: [`command: ${command.join(' ')}`, result.stderrTail].filter(Boolean), + details, + }; } - } - const report: TestsPassingReport = { - numPassedTests, - numFailedTests, - numTotalTestSuites, - failures, - }; + // Default Jest runs write structured output to a bounded temporary file. + // Configured commands retain legacy stdout parsing, but stdout itself is + // now always a bounded tail. + const fileRead = resultPath ? await readJestResultFile(resultPath) : undefined; + if (fileRead?.status === 'resultFileTooLarge') { + return { + status: 'failed', + summary: 'tests-passing: resultFileTooLarge', + evidence: [`command: ${command.join(' ')}`], + details, + }; + } + const parsed = fileRead?.status === 'ok' + ? fileRead.value + : extractJsonFromStdout(result.stdoutTail); + if (!parsed || typeof parsed !== 'object') { + return { + status: 'failed', + summary: 'tests-passing: could not parse jest --json output', + evidence: [ + `command: ${command.join(' ')}`, + `exitCode: ${result.exitCode}`, + result.stdoutTail, + result.stderrTail, + ].filter(Boolean), + details, + }; + } + + const j = parsed as Record; + const numPassedTests = typeof j.numPassedTests === 'number' ? j.numPassedTests : 0; + const numFailedTests = typeof j.numFailedTests === 'number' ? j.numFailedTests : 0; + const numTotalTestSuites = typeof j.numTotalTestSuites === 'number' ? j.numTotalTestSuites : 0; + + const failures: Array<{ name: string; message: string }> = []; + const testResults = Array.isArray(j.testResults) ? j.testResults : []; + for (const suite of testResults) { + if (!suite || typeof suite !== 'object') continue; + const s = suite as Record; + const assertionResults = Array.isArray(s.assertionResults) ? s.assertionResults : []; + for (const a of assertionResults) { + if (!a || typeof a !== 'object') continue; + const ar = a as Record; + if (ar.status === 'failed') { + const messages = Array.isArray(ar.failureMessages) ? ar.failureMessages : []; + if (failures.length >= 100) continue; + failures.push({ + name: typeof ar.fullName === 'string' + ? ar.fullName + : (typeof ar.title === 'string' ? ar.title : 'unknown'), + message: messages + .slice(0, 10) + .map((m) => String(m).slice(0, 2000)) + .join('\n') + .slice(0, 2000), + }); + } + } + } + + const report: TestsPassingReport = { + numPassedTests, + numFailedTests, + numTotalTestSuites, + failures, + }; + + const passed = result.exitCode === 0 && numFailedTests === 0; + if (passed) { + return { + status: 'passed', + summary: `tests-passing: ${numPassedTests} passed across ${numTotalTestSuites} suites`, + evidence: [`command: ${command.join(' ')}`], + output: report, + details, + }; + } - const passed = result.exitCode === 0 && numFailedTests === 0; - if (passed) { return { - status: 'passed', - summary: `tests-passing: ${numPassedTests} passed across ${numTotalTestSuites} suites`, - evidence: [`command: ${opts.testCommand.join(' ')}`], + status: 'failed', + summary: `tests-passing: ${numFailedTests} failed (exit ${result.exitCode})`, + evidence: failures.slice(0, 10).map((f) => `${f.name}: ${f.message.split('\n')[0]}`), output: report, + details, }; + } finally { + if (resultDirectory) await fs.rm(resultDirectory, { recursive: true, force: true }); } - - return { - status: 'failed', - summary: `tests-passing: ${numFailedTests} failed (exit ${result.exitCode})`, - evidence: failures.slice(0, 10).map((f) => `${f.name}: ${f.message.split('\n')[0]}`), - output: report, - }; } export function createTestsPassingSensor(repoPath: string): HarnessSensorDefinition { diff --git a/src/harness/adapters/out/sensors/typecheckClean.ts b/src/harness/adapters/out/sensors/typecheckClean.ts index c924548e..53d6bf67 100644 --- a/src/harness/adapters/out/sensors/typecheckClean.ts +++ b/src/harness/adapters/out/sensors/typecheckClean.ts @@ -16,12 +16,18 @@ import type { HarnessSensorExecutionInput, HarnessSensorExecutionResult, } from '../../../application/sensors/sensorsService'; -import { runShell } from './testsPassing'; +import { + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + DEFAULT_SUBPROCESS_TAIL_BYTES, +} from '../../../domain/execution'; +import { runShell, subprocessDetails } from './testsPassing'; export interface TypecheckCleanOptions { command?: string[]; timeoutMs?: number; tailLines?: number; + tailBytes?: number; + hardOutputLimitBytes?: number; } const DEFAULT_COMMAND: string[] = ['npx', 'tsc', '--noEmit']; @@ -38,6 +44,9 @@ function readOptions(input: HarnessSensorExecutionInput): Required 0 ? cmd : DEFAULT_COMMAND, timeoutMs: ctx.timeoutMs ?? meta.timeoutMs ?? DEFAULT_TIMEOUT_MS, tailLines: ctx.tailLines ?? meta.tailLines ?? DEFAULT_TAIL_LINES, + tailBytes: ctx.tailBytes ?? meta.tailBytes ?? DEFAULT_SUBPROCESS_TAIL_BYTES, + hardOutputLimitBytes: + ctx.hardOutputLimitBytes ?? meta.hardOutputLimitBytes ?? DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, }; } @@ -53,13 +62,27 @@ export async function executeTypecheckClean( ): Promise { const opts = readOptions(input); - const result = await runShell(opts.command, repoPath, opts.timeoutMs); + const result = await runShell(opts.command, repoPath, opts.timeoutMs, { + tailBytes: opts.tailBytes, + hardCombinedOutputBytes: opts.hardOutputLimitBytes, + }); + const details = subprocessDetails(result, opts.command); if (result.spawnError) { return { status: 'failed', summary: `typecheck-clean: spawn error: ${result.spawnError}`, evidence: [`command: ${opts.command.join(' ')}`], + details, + }; + } + + if (result.outputLimitExceeded) { + return { + status: 'failed', + summary: 'typecheck-clean: outputLimitExceeded', + evidence: [`command: ${opts.command.join(' ')}`, result.stderrTail].filter(Boolean), + details, }; } @@ -67,7 +90,11 @@ export async function executeTypecheckClean( return { status: 'failed', summary: `typecheck-clean: timed out after ${opts.timeoutMs}ms`, - evidence: [`command: ${opts.command.join(' ')}`, tailLines(result.stderr, opts.tailLines)], + evidence: [ + `command: ${opts.command.join(' ')}`, + tailLines(result.stderrTail, opts.tailLines), + ].filter(Boolean), + details, }; } @@ -76,14 +103,15 @@ export async function executeTypecheckClean( status: 'passed', summary: 'typecheck-clean: tsc reported no errors', evidence: [`command: ${opts.command.join(' ')}`], + details, }; } // tsc writes diagnostics to stdout, errors are typically there. Capture // both tails so the operator sees what went wrong regardless of where // they landed. - const stderrTail = tailLines(result.stderr, opts.tailLines); - const stdoutTail = tailLines(result.stdout, opts.tailLines); + const stderrTail = tailLines(result.stderrTail, opts.tailLines); + const stdoutTail = tailLines(result.stdoutTail, opts.tailLines); const combinedTail = [stdoutTail, stderrTail].filter(Boolean).join('\n'); return { @@ -91,6 +119,7 @@ export async function executeTypecheckClean( summary: `typecheck-clean: tsc exit ${result.exitCode}`, evidence: [`command: ${opts.command.join(' ')}`, combinedTail].filter(Boolean) as string[], output: { exitCode: result.exitCode, tail: combinedTail }, + details, }; } diff --git a/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts new file mode 100644 index 00000000..21f1ba43 --- /dev/null +++ b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts @@ -0,0 +1,51 @@ +import { + BoundedByteCollector, + MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, + resolveSubprocessOutputLimits, +} from '../boundedByteCollector'; + +describe('BoundedByteCollector', () => { + it('retains only the newest bytes without growing with input volume', () => { + const collector = new BoundedByteCollector(8); + const chunk = Buffer.alloc(1024, 'x'); + for (let i = 0; i < 100 * 1024; i += 1) { + collector.append(chunk); + } + + expect(collector.totalBytes).toBe(100 * 1024 * 1024); + expect(collector.retainedBytes).toBe(8); + expect(collector.droppedBytes).toBe(100 * 1024 * 1024 - 8); + expect(collector.truncated).toBe(true); + expect(collector.toString()).toBe('xxxxxxxx'); + }); + + it('preserves byte ordering when writes wrap the ring', () => { + const collector = new BoundedByteCollector(5); + collector.append(Buffer.from('abc')); + collector.append(Buffer.from('def')); + collector.append(Buffer.from('gh')); + + expect(collector.toString()).toBe('defgh'); + }); + + it('measures UTF-8 bytes rather than JavaScript characters', () => { + const collector = new BoundedByteCollector(4); + collector.append(Buffer.from('ééé', 'utf-8')); + + expect(collector.totalBytes).toBe(6); + expect(collector.retainedBytes).toBe(4); + expect(collector.toString()).toBe('éé'); + }); + + it('clamps untrusted hard limits to 64 MiB', () => { + const requested = MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES * 2; + expect(resolveSubprocessOutputLimits({ hardCombinedOutputBytes: requested })) + .toEqual(expect.objectContaining({ + hardCombinedOutputBytes: MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, + })); + expect(resolveSubprocessOutputLimits({ + hardCombinedOutputBytes: requested, + unsafeAllowAboveMaximum: true, + })).toEqual(expect.objectContaining({ hardCombinedOutputBytes: requested })); + }); +}); diff --git a/src/harness/domain/execution/boundedByteCollector.ts b/src/harness/domain/execution/boundedByteCollector.ts new file mode 100644 index 00000000..860269ce --- /dev/null +++ b/src/harness/domain/execution/boundedByteCollector.ts @@ -0,0 +1,136 @@ +/** + * Memory-safe byte tail used by subprocess capture paths. + * + * The collector owns one fixed-size ring buffer. Its memory usage therefore + * depends only on `tailBytes`, not on how much data the child writes. + */ + +export const DEFAULT_SUBPROCESS_TAIL_BYTES = 8 * 1024; +export const DEFAULT_SUBPROCESS_SOFT_OUTPUT_BYTES = 1024 * 1024; +export const DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES = 16 * 1024 * 1024; +export const MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES = 64 * 1024 * 1024; +export const MAX_JEST_RESULT_FILE_BYTES = 32 * 1024 * 1024; + +export interface SubprocessOutputLimitsInput { + tailBytes?: number; + hardCombinedOutputBytes?: number; + /** Only trusted application code may opt into a ceiling above 64 MiB. */ + unsafeAllowAboveMaximum?: boolean; +} + +export interface SubprocessOutputLimits { + tailBytes: number; + hardCombinedOutputBytes: number; +} + +function positiveInteger(value: number | undefined, fallback: number, minimum: number): number { + if (value === undefined || !Number.isFinite(value)) return fallback; + return Math.max(minimum, Math.floor(value)); +} + +export function resolveSubprocessOutputLimits( + input: SubprocessOutputLimitsInput = {} +): SubprocessOutputLimits { + const tailBytes = positiveInteger(input.tailBytes, DEFAULT_SUBPROCESS_TAIL_BYTES, 0); + const requestedHardLimit = positiveInteger( + input.hardCombinedOutputBytes, + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + 1 + ); + const hardCombinedOutputBytes = input.unsafeAllowAboveMaximum + ? requestedHardLimit + : Math.min(requestedHardLimit, MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES); + + return { tailBytes, hardCombinedOutputBytes }; +} + +export interface BoundedByteCollectorSnapshot { + tail: Buffer; + totalBytes: number; + retainedBytes: number; + droppedBytes: number; + truncated: boolean; +} + +export class BoundedByteCollector { + private readonly buffer: Buffer; + private retainedLength = 0; + private writeOffset = 0; + private observedBytes = 0; + + constructor(readonly tailBytes: number = DEFAULT_SUBPROCESS_TAIL_BYTES) { + if (!Number.isSafeInteger(tailBytes) || tailBytes < 0) { + throw new Error('tailBytes must be a non-negative safe integer'); + } + this.buffer = Buffer.allocUnsafe(tailBytes); + } + + append(chunk: Buffer): void { + if (!Buffer.isBuffer(chunk)) { + throw new Error('BoundedByteCollector accepts Buffer chunks only'); + } + + this.observedBytes += chunk.length; + if (this.tailBytes === 0 || chunk.length === 0) return; + + if (chunk.length >= this.tailBytes) { + chunk.copy(this.buffer, 0, chunk.length - this.tailBytes); + this.retainedLength = this.tailBytes; + this.writeOffset = 0; + return; + } + + const beforeWrap = Math.min(chunk.length, this.tailBytes - this.writeOffset); + chunk.copy(this.buffer, this.writeOffset, 0, beforeWrap); + if (beforeWrap < chunk.length) { + chunk.copy(this.buffer, 0, beforeWrap); + } + + this.writeOffset = (this.writeOffset + chunk.length) % this.tailBytes; + this.retainedLength = Math.min(this.tailBytes, this.retainedLength + chunk.length); + } + + get totalBytes(): number { + return this.observedBytes; + } + + get retainedBytes(): number { + return this.retainedLength; + } + + get droppedBytes(): number { + return this.observedBytes - this.retainedLength; + } + + get truncated(): boolean { + return this.droppedBytes > 0; + } + + tail(): Buffer { + if (this.retainedLength === 0) return Buffer.alloc(0); + if (this.retainedLength < this.tailBytes) { + return Buffer.from(this.buffer.subarray(0, this.retainedLength)); + } + if (this.writeOffset === 0) return Buffer.from(this.buffer); + + const result = Buffer.allocUnsafe(this.retainedLength); + const newerLength = this.tailBytes - this.writeOffset; + this.buffer.copy(result, 0, this.writeOffset); + this.buffer.copy(result, newerLength, 0, this.writeOffset); + return result; + } + + toString(encoding: BufferEncoding = 'utf-8'): string { + return this.tail().toString(encoding); + } + + snapshot(): BoundedByteCollectorSnapshot { + return { + tail: this.tail(), + totalBytes: this.totalBytes, + retainedBytes: this.retainedBytes, + droppedBytes: this.droppedBytes, + truncated: this.truncated, + }; + } +} diff --git a/src/harness/domain/execution/index.ts b/src/harness/domain/execution/index.ts new file mode 100644 index 00000000..f0143a6f --- /dev/null +++ b/src/harness/domain/execution/index.ts @@ -0,0 +1,12 @@ +export { + BoundedByteCollector, + DEFAULT_SUBPROCESS_TAIL_BYTES, + DEFAULT_SUBPROCESS_SOFT_OUTPUT_BYTES, + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, + MAX_JEST_RESULT_FILE_BYTES, + resolveSubprocessOutputLimits, + type BoundedByteCollectorSnapshot, + type SubprocessOutputLimits, + type SubprocessOutputLimitsInput, +} from './boundedByteCollector'; diff --git a/src/harness/domain/index.ts b/src/harness/domain/index.ts index 2d1af512..4bcf918a 100644 --- a/src/harness/domain/index.ts +++ b/src/harness/domain/index.ts @@ -4,3 +4,4 @@ export * as policies from './policies'; export * as sensors from './sensors'; export * as collaboration from './collaboration'; export * as context from './context'; +export * as execution from './execution'; diff --git a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts index 91829dea..6f63658f 100644 --- a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts +++ b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts @@ -55,6 +55,48 @@ describe('runAcceptance', () => { expect(result.tailStdout).toContain('hello-tail'); }); + it('bounds stdout and stderr independently and exposes byte counters', async () => { + const result = await runAcceptance( + { + kind: 'shell', + command: [ + 'node', + '-e', + 'process.stdout.write("a".repeat(1000)); process.stderr.write("b".repeat(700))', + ], + }, + { ...ctx, outputLimits: { tailBytes: 64 } } + ); + + expect(Buffer.byteLength(result.tailStdout)).toBe(64); + expect(Buffer.byteLength(result.tailStderr)).toBe(64); + expect(result.stdoutBytes).toBe(1000); + expect(result.stderrBytes).toBe(700); + expect(result.stdoutDroppedBytes).toBe(936); + expect(result.stderrDroppedBytes).toBe(636); + expect(result.outputTruncated).toBe(true); + }); + + it('kills and reaps a child that exceeds the combined hard output limit', async () => { + const result = await runAcceptance( + { + kind: 'shell', + command: [ + 'node', + '-e', + 'const c="x".repeat(4096); for(let i=0;i<10000;i++) process.stdout.write(c)', + ], + }, + { ...ctx, outputLimits: { tailBytes: 128, hardCombinedOutputBytes: 32 * 1024 } } + ); + + expect(result.passed).toBe(false); + expect(result.outputLimitExceeded).toBe(true); + expect(result.terminationReason).toBe('outputLimit'); + expect(result.stdoutBytes).toBeGreaterThan(32 * 1024); + expect(Buffer.byteLength(result.tailStdout)).toBeLessThanOrEqual(128); + }); + it('rejects an empty command array', async () => { await expect( runAcceptance({ kind: 'shell', command: [] }, ctx) diff --git a/src/harness/domain/workflow/plans/acceptanceRunner.ts b/src/harness/domain/workflow/plans/acceptanceRunner.ts index a4fa8c94..2bfe6210 100644 --- a/src/harness/domain/workflow/plans/acceptanceRunner.ts +++ b/src/harness/domain/workflow/plans/acceptanceRunner.ts @@ -7,9 +7,16 @@ */ import { spawn } from 'child_process'; +import * as path from 'path'; +import { + BoundedByteCollector, + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + DEFAULT_SUBPROCESS_TAIL_BYTES, + resolveSubprocessOutputLimits, +} from '../../execution'; import type { StepAcceptanceRun, StepAcceptanceSpec } from './executionTypes'; -export const ACCEPTANCE_TAIL_LIMIT_BYTES = 8 * 1024; +export const ACCEPTANCE_TAIL_LIMIT_BYTES = DEFAULT_SUBPROCESS_TAIL_BYTES; export const ACCEPTANCE_DEFAULT_TIMEOUT_MS = 60_000; export class AcceptanceFailedError extends Error { @@ -34,14 +41,10 @@ export class AcceptanceFailedError extends Error { export interface AcceptanceContext { repoPath: string; -} - -function tailBuffer(chunks: Buffer[], limit: number): string { - const joined = Buffer.concat(chunks); - if (joined.length <= limit) { - return joined.toString('utf-8'); - } - return joined.subarray(joined.length - limit).toString('utf-8'); + outputLimits?: { + tailBytes?: number; + hardCombinedOutputBytes?: number; + }; } export async function runAcceptance( @@ -59,6 +62,12 @@ export async function runAcceptance( const timeoutMs = spec.timeoutMs ?? ACCEPTANCE_DEFAULT_TIMEOUT_MS; const cwd = spec.workingDir ?? ctx.repoPath; const startedAt = Date.now(); + const limits = resolveSubprocessOutputLimits({ + tailBytes: ctx.outputLimits?.tailBytes ?? ACCEPTANCE_TAIL_LIMIT_BYTES, + hardCombinedOutputBytes: + ctx.outputLimits?.hardCombinedOutputBytes ?? DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + }); + const commandBasename = path.basename(executable); return new Promise((resolve) => { let settled = false; @@ -81,42 +90,80 @@ export async function runAcceptance( tailStderr: `spawn error: ${err instanceof Error ? err.message : String(err)}`, durationMs: Date.now() - startedAt, timedOut: false, + stdoutBytes: 0, + stderrBytes: 0, + stdoutDroppedBytes: 0, + stderrDroppedBytes: 0, + outputTruncated: false, + outputLimitExceeded: false, + terminationReason: 'spawnError', + commandBasename, }); return; } - const stdoutChunks: Buffer[] = []; - const stderrChunks: Buffer[] = []; + const stdout = new BoundedByteCollector(limits.tailBytes); + const stderr = new BoundedByteCollector(limits.tailBytes); + let outputLimitExceeded = false; + let spawnError: Error | undefined; - child.stdout?.on('data', (c: Buffer) => stdoutChunks.push(c)); - child.stderr?.on('data', (c: Buffer) => stderrChunks.push(c)); + let timer: NodeJS.Timeout; + const capture = (collector: BoundedByteCollector, chunk: Buffer) => { + collector.append(chunk); + if ( + !outputLimitExceeded && + stdout.totalBytes + stderr.totalBytes > limits.hardCombinedOutputBytes + ) { + outputLimitExceeded = true; + clearTimeout(timer); + child.kill('SIGKILL'); + } + }; - const timer = setTimeout(() => { + child.stdout?.on('data', (chunk: Buffer) => capture(stdout, chunk)); + child.stderr?.on('data', (chunk: Buffer) => capture(stderr, chunk)); + + timer = setTimeout(() => { + if (outputLimitExceeded) return; timedOut = true; child.kill('SIGKILL'); }, timeoutMs); - const finish = (exitCode: number | null, spawnError?: Error) => { + const finish = (exitCode: number | null) => { if (settled) return; settled = true; clearTimeout(timer); - const tailStdout = tailBuffer(stdoutChunks, ACCEPTANCE_TAIL_LIMIT_BYTES); - let tailStderr = tailBuffer(stderrChunks, ACCEPTANCE_TAIL_LIMIT_BYTES); - if (spawnError) { - tailStderr = `${tailStderr}${tailStderr ? '\n' : ''}spawn error: ${spawnError.message}`; - } resolve({ ran_at: startedAt, - passed: !timedOut && !spawnError && exitCode === 0, + passed: !timedOut && !outputLimitExceeded && !spawnError && exitCode === 0, exitCode, - tailStdout, - tailStderr, + tailStdout: stdout.toString(), + tailStderr: stderr.toString(), durationMs: Date.now() - startedAt, timedOut, + stdoutBytes: stdout.totalBytes, + stderrBytes: stderr.totalBytes, + stdoutDroppedBytes: stdout.droppedBytes, + stderrDroppedBytes: stderr.droppedBytes, + outputTruncated: stdout.truncated || stderr.truncated, + outputLimitExceeded, + terminationReason: outputLimitExceeded + ? 'outputLimit' + : timedOut + ? 'timeout' + : spawnError + ? 'spawnError' + : undefined, + commandBasename, }); }; - child.on('error', (err) => finish(null, err)); + // Keep the error diagnostic inside the same bounded stderr collector and + // wait for close so failed and killed children are reaped. + child.on('error', (err) => { + spawnError = err; + stderr.append(Buffer.from(`spawn error: ${err.message}`)); + }); child.on('close', (code) => finish(code)); }); } diff --git a/src/harness/domain/workflow/plans/executionTypes.ts b/src/harness/domain/workflow/plans/executionTypes.ts index 3d3e2c2c..d2c3f887 100644 --- a/src/harness/domain/workflow/plans/executionTypes.ts +++ b/src/harness/domain/workflow/plans/executionTypes.ts @@ -36,6 +36,15 @@ export interface StepAcceptanceRun { tailStderr: string; durationMs: number; timedOut: boolean; + /** Optional for compatibility with acceptance runs persisted before F-01. */ + stdoutBytes?: number; + stderrBytes?: number; + stdoutDroppedBytes?: number; + stderrDroppedBytes?: number; + outputTruncated?: boolean; + outputLimitExceeded?: boolean; + terminationReason?: 'timeout' | 'outputLimit' | 'spawnError'; + commandBasename?: string; } /** Individual step execution tracking */ diff --git a/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts b/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts index 53676e13..47d652a4 100644 --- a/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts +++ b/src/harness/domain/workflow/plans/planUpdateOrchestrator.ts @@ -134,7 +134,11 @@ export class PlanUpdateOrchestrator { this.indexProjector.invalidateCache(); throw new AcceptanceFailedError( `Acceptance predicate failed for step ${stepIndex} in ${phaseId} of ${planSlug}` + - (run.timedOut ? ' (timed out)' : ` (exit ${run.exitCode ?? 'null'})`), + (run.outputLimitExceeded + ? ' (outputLimitExceeded)' + : run.timedOut + ? ' (timed out)' + : ` (exit ${run.exitCode ?? 'null'})`), run, { planSlug, phaseId, stepIndex } ); From 095cefa8cf026aad1ca13fb071230184bfae3a23 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:02:19 -0300 Subject: [PATCH 04/39] fix: bound and sanitize hook traces --- CHANGELOG.md | 10 + README.md | 2 +- .../docs/en/guides/using-with-hooks.md | 8 +- .../content/docs/en/guides/using-with-pi.md | 4 +- .../docs/pt-br/guides/hook-session-flow.md | 13 +- .../docs/pt-br/guides/using-with-hooks.md | 8 +- .../docs/pt-br/guides/using-with-pi.md | 2 +- .../__tests__/hookDispatchService.test.ts | 37 +- src/cli/services/hookDispatchService.ts | 57 ++- .../__tests__/runtimeStateService.test.ts | 50 +++ .../out/runtimeState/runtimeStateService.ts | 125 +++++- .../hooks/__tests__/hookReadiness.test.ts | 2 +- .../hooks/__tests__/hookTracePolicy.test.ts | 101 +++++ .../application/hooks/bashClassification.ts | 15 +- .../application/hooks/hookTracePolicy.ts | 405 ++++++++++++++++++ src/harness/application/hooks/index.ts | 1 + src/harness/index.ts | 14 + .../__tests__/hookRoundTrip.test.ts | 51 ++- src/integrations/pi-dev/hooks/mapPiEvent.ts | 2 +- .../shared/resolveHarnessHookFromHostEvent.ts | 2 +- 20 files changed, 872 insertions(+), 37 deletions(-) create mode 100644 src/harness/application/hooks/__tests__/hookTracePolicy.test.ts create mode 100644 src/harness/application/hooks/hookTracePolicy.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 242a3b11..e0e42212 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Added configurable, globally clamped hook stdin, field, event, rotation, segment-retention, and per-session trace limits. + +### Fixed + +- Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. +- Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. +- Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. + ## [1.1.1] - 2026-06-27 ### Fixed diff --git a/README.md b/README.md index 73e31c73..e718d799 100644 --- a/README.md +++ b/README.md @@ -417,7 +417,7 @@ Hook install writes project-level configuration by default. Use `--global` only `SessionStart` resolves the project root first (`--repo-path`, then the nearest parent with `.context/`, then `cwd`) and checks readiness. If the repository is not initialized yet, the hook returns a short JSON-safe hint and does not create `.context/runtime`. Partial context lists up to three missing areas. Ready context gets compact navigation, a daily no-workflow reminder, or active PREVC preflight when a workflow is running. -`PostToolUse` appends durable `tool.use` traces for `Write`, `Edit`, and `Bash`. Bash traces include best-effort classification such as `test`, `build`, `lint`, or `inspection` without running extra commands. Repeated trace append failures are counted under `.context/runtime/hooks/trace-failures.json` and stay non-blocking. +`PostToolUse` appends durable `tool.use` traces for `Write`, `Edit`, and `Bash` without retaining source bodies. Write/Edit traces keep paths, byte counts, and content hashes; Bash keeps a bounded preview and best-effort classification such as `test`, `build`, `lint`, or `inspection`. Hook stdin is capped at 8 MiB and oversized input remains non-blocking. Trace events are size-bounded, `trace.jsonl` rotates at 8 MiB, and up to four closed segments are retained by default. Repeated trace append or input failures are counted under `.context/runtime/hooks/trace-failures.json`. `Stop` and session-end hooks stay quiet unless there is an active PREVC workflow. Missing, inactive, malformed, or reentrant workflow state returns a successful no-op so end-of-turn feedback does not become noise. diff --git a/docs/src/content/docs/en/guides/using-with-hooks.md b/docs/src/content/docs/en/guides/using-with-hooks.md index 70b5fde9..89f567bb 100644 --- a/docs/src/content/docs/en/guides/using-with-hooks.md +++ b/docs/src/content/docs/en/guides/using-with-hooks.md @@ -77,7 +77,7 @@ All supported hosts run the same harness actions; only the event envelope differ | Session start (no `.context/`) | `context` → `check` | Return a short JSON-safe hint to configure MCP and run `context init`; does not create `.context/runtime` | | Session start (`.context/` partial) | `context` → `check` | List up to three missing setup areas, such as `workflow` or `plans` | | Session start (`.context/` ready) | `context` → `check`, then harness session binding and `context` → `getMap` | Inject compact context/navigation, daily no-workflow reminder, or active PREVC preflight | -| Post tool use (Write / Edit / Bash) | `harness` → `appendTrace` | Append durable trace under `.context/runtime/`; Bash traces get best-effort classification | +| Post tool use (Write / Edit / Bash) | `harness` → `appendTrace` | Append a bounded, source-body-free trace under `.context/runtime/`; Bash traces get best-effort classification | | Stop / session end | `workflow-guide` | Inject compact PREVC next steps, skills, and gate hints only when an active PREVC workflow exists | Hooks are **non-blocking by default**. Harness errors do not stop your agent session. Stop/session-end hooks also stay silent when no PREVC workflow is active, when workflow state is missing or malformed, and during host reentry. Those cases return successful no-ops so hook feedback cannot create end-of-turn noise. @@ -88,6 +88,12 @@ Bash classification is best-effort and only reads the command already supplied b Repeated trace append failures are recorded under `.context/runtime/hooks/trace-failures.json` and are surfaced by `hook doctor`; the first failure remains silent to the host. +### Trace privacy and limits + +Hook envelopes are treated as untrusted input. Shell dispatch accepts at most 8 MiB by default and rejects larger stdin without echoing it or blocking the host operation. Write and Edit source bodies, patches, prompts, messages, authorization values, API keys, tokens, secrets, and passwords are never copied into hook traces. Write/Edit metadata includes the file path, byte counts, omission flags, and SHA-256 hashes of source bodies; Bash stores a command basename and a preview capped at 512 bytes. + +Hook trace data is capped at 16 KiB and all runtime trace events have a 256 KiB defense-in-depth ceiling. The active `trace.jsonl` rotates at 8 MiB; readers include chronological `trace.*.jsonl` segments, with four closed segments and 32 MiB per session retained by default. Limits can be lowered in `.context/config/hooks.json` (`stdin.maxBytes` and `trace.*`) and `.context/config/runtime.json` (`trace.maxSerializedBytes`). Values above global safety ceilings are clamped. + ## Claude Code The installer writes `hooks` entries to Claude Code settings. Each entry runs: diff --git a/docs/src/content/docs/en/guides/using-with-pi.md b/docs/src/content/docs/en/guides/using-with-pi.md index e976a5f7..e30108c8 100644 --- a/docs/src/content/docs/en/guides/using-with-pi.md +++ b/docs/src/content/docs/en/guides/using-with-pi.md @@ -49,7 +49,7 @@ The default export registers handlers through Pi's `ExtensionAPI`: | Pi event | Harness call | Effect | | --- | --- | --- | | `session_start` | `context` → `check` (+ optional navigation excerpt) | Inject bootstrap message or resource when `.context/` exists | -| `tool_execution_end` | `harness` → `appendTrace` for write/edit/bash tools | Silent durable trace under `.context/runtime/` | +| `tool_execution_end` | `harness` → `appendTrace` for write/edit/bash tools | Silent, size-bounded trace without Write/Edit source bodies | | `agent_end` | `workflow-guide` | Optional UI notification with PREVC next steps, skills, and gate hints | When `.context/` is missing, `session_start` injects a one-line hint to initialize context through MCP. @@ -87,7 +87,7 @@ Global MCP config path: `~/.config/mcp/mcp.json`. Local: `.mcp.json` in the proj 2. **Bootstrap injection** — in a repo with `.context/` initialized, start a session. You should see dotcontext bootstrap content on `session_start`. -3. **Traces** — edit a file through Pi, then check `.context/runtime/sessions/*/trace.jsonl` for `tool.use` entries. +3. **Traces** — edit a file through Pi, then check `.context/runtime/sessions/*/trace*.jsonl` for `tool.use` entries. Write/Edit bodies are omitted; paths, byte counts, and hashes remain available. 4. **MCP tools** — with `pi-mcp-adapter` connected, ask Pi to run the context check tool against your repository. diff --git a/docs/src/content/docs/pt-br/guides/hook-session-flow.md b/docs/src/content/docs/pt-br/guides/hook-session-flow.md index 4598da13..6d4053e7 100644 --- a/docs/src/content/docs/pt-br/guides/hook-session-flow.md +++ b/docs/src/content/docs/pt-br/guides/hook-session-flow.md @@ -138,7 +138,10 @@ O dispatch procura a sessão do harness vinculada a `codex-session-123` e anexa "message": "Write", "data": { "tool_input": { - "file_path": "src/feature.ts" + "filePath": "src/feature.ts", + "contentBytes": 1840, + "contentHash": "sha256:...", + "contentOmitted": true } } } @@ -170,7 +173,7 @@ Um `Bash` também vira trace: } ``` -O `trace.jsonl` passa a ter uma linha `tool.use` com `message: "Bash"`, o comando em `data.tool_input` e uma classificação best-effort: +O `trace.jsonl` passa a ter uma linha `tool.use` com `message: "Bash"`, um preview limitado do comando em `data.tool_input` e uma classificação best-effort: ```json { @@ -179,7 +182,9 @@ O `trace.jsonl` passa a ter uma linha `tool.use` com `message: "Bash"`, o comand "data": { "classification": "test", "tool_input": { - "command": "npm test -- --runInBand" + "commandBasename": "npm", + "commandBytes": 23, + "commandPreview": "npm test -- --runInBand" } } } @@ -187,6 +192,8 @@ O `trace.jsonl` passa a ter uma linha `tool.use` com `message: "Bash"`, o comand Essa classificação só lê o payload recebido do host; hooks não executam comandos extras. +Corpos de Write/Edit e campos sensíveis nunca entram no trace. O stdin do dispatch, os campos e os eventos serializados têm limites seguros. Quando o `trace.jsonl` ativo chega a 8 MiB, ele é movido para um segmento `trace.*.jsonl` e a escrita continua em um novo arquivo ativo. + ### 4. A sessão termina sem workflow ativo Se não existe workflow PREVC ativo, `Stop` é intencionalmente silencioso: diff --git a/docs/src/content/docs/pt-br/guides/using-with-hooks.md b/docs/src/content/docs/pt-br/guides/using-with-hooks.md index 0f12c02f..56297f42 100644 --- a/docs/src/content/docs/pt-br/guides/using-with-hooks.md +++ b/docs/src/content/docs/pt-br/guides/using-with-hooks.md @@ -64,7 +64,7 @@ npx -y @dotcontext/cli@latest mcp:install codex --no-hooks | Início sem `.context/` | `context` → `check` | Retorna uma dica curta e JSON-safe para configurar MCP e rodar `context init`; não cria `.context/runtime` | | Início com `.context/` parcial | `context` → `check` | Lista até três partes faltantes do setup, como `workflow` ou `plans` | | Início com `.context/` pronto | `context` → `check`, vínculo de sessão e `context` → `getMap` | Injeta contexto/navegação compactos, lembrete diário de workflow ausente ou preflight PREVC ativo | -| Pós ferramenta (Write/Edit/Bash) | `harness` → `appendTrace` | Trace em `.context/runtime/`; Bash recebe classificação best-effort | +| Pós ferramenta (Write/Edit/Bash) | `harness` → `appendTrace` | Trace limitado e sem corpo de código em `.context/runtime/`; Bash recebe classificação best-effort | | Stop / fim | `workflow-guide` | Próximos passos, skills e dicas de gate PREVC somente quando existe um workflow PREVC ativo | Hooks são **não bloqueantes** por padrão. Erros do harness não encerram a sessão do agente. Stop/fim também fica silencioso quando não há workflow PREVC ativo, quando o estado de workflow está ausente ou malformado, e durante reentrada do host. Nesses casos, o hook retorna um no-op bem-sucedido para não criar ruído no encerramento. @@ -75,6 +75,12 @@ A classificação de Bash só lê o comando que o host já enviou; ela não exec Falhas repetidas de append trace são registradas em `.context/runtime/hooks/trace-failures.json` e aparecem no `hook doctor`; a primeira falha continua silenciosa para o host. +### Privacidade e limites dos traces + +Envelopes de hook são tratados como entrada não confiável. O dispatch via shell aceita no máximo 8 MiB por padrão e rejeita stdin maior sem ecoar seu conteúdo nem bloquear a operação do host. Corpos de Write/Edit, patches, prompts, mensagens, authorization, chaves de API, tokens, secrets e senhas não são copiados para os traces. Write/Edit mantêm caminho, contagens de bytes, flags de omissão e hashes SHA-256; Bash mantém o nome-base do comando e um preview de até 512 bytes. + +Os dados de hook ficam limitados a 16 KiB e todo evento de runtime tem um segundo teto de 256 KiB. O `trace.jsonl` ativo rotaciona em 8 MiB; a leitura inclui segmentos cronológicos `trace.*.jsonl`, com retenção padrão de quatro segmentos fechados e 32 MiB por sessão. Limites podem ser reduzidos em `.context/config/hooks.json` (`stdin.maxBytes` e `trace.*`) e `.context/config/runtime.json` (`trace.maxSerializedBytes`). Valores acima dos tetos globais são limitados automaticamente. + ## Claude Code O instalador grava entradas `hooks` em `.claude/settings.json` por padrão. Cada entrada chama: diff --git a/docs/src/content/docs/pt-br/guides/using-with-pi.md b/docs/src/content/docs/pt-br/guides/using-with-pi.md index a33170b3..df23201e 100644 --- a/docs/src/content/docs/pt-br/guides/using-with-pi.md +++ b/docs/src/content/docs/pt-br/guides/using-with-pi.md @@ -30,7 +30,7 @@ npx -y @dotcontext/cli@latest hook install pi | Evento Pi | Chamada harness | Efeito | | --- | --- | --- | | `session_start` | `context` → `check` | Injeta bootstrap ou dica | -| `tool_execution_end` | `harness` → `appendTrace` | Trace silencioso | +| `tool_execution_end` | `harness` → `appendTrace` | Trace silencioso e limitado, sem corpos de Write/Edit | | `agent_end` | `workflow-guide` | Notificação com próximos passos, skills e dicas de gate PREVC | `agent_end` fica silencioso sem workflow PREVC ativo, e chamadas marcadas como reentrantes são ignoradas para evitar loops de notificação. diff --git a/src/cli/services/__tests__/hookDispatchService.test.ts b/src/cli/services/__tests__/hookDispatchService.test.ts index 44525835..7f74cf38 100644 --- a/src/cli/services/__tests__/hookDispatchService.test.ts +++ b/src/cli/services/__tests__/hookDispatchService.test.ts @@ -96,6 +96,38 @@ describe('HookDispatchService session lifecycle', () => { expect(traceContent).toContain('tool.use'); }); + it.each(['claude-code', 'codex'] as const)( + 'rejects oversized %s stdin without echoing input or blocking the host', + async (source) => { + const marker = 'must-not-be-echoed'; + const stdoutChunks: Buffer[] = []; + const stdout = new PassThrough(); + stdout.on('data', (chunk) => stdoutChunks.push(Buffer.from(chunk))); + const input = JSON.stringify({ + cwd: tempDir, + hook_event_name: 'PostToolUse', + content: `${marker}${'x'.repeat(2048)}`, + }); + + const result = await runHookDispatch({ + source, + repoPath: tempDir, + stdin: PassThrough.from([input.slice(0, 900), input.slice(900)]), + stdout, + maxInputBytes: 1024, + }); + + expect(result).toEqual({ exitCode: 0, output: { continue: true } }); + expect(Buffer.concat(stdoutChunks).toString('utf8')).not.toContain(marker); + const diagnostic = await fs.readFile( + path.join(tempDir, '.context', 'runtime', 'hooks', 'trace-failures.json'), + 'utf8' + ); + expect(diagnostic).toContain('hook_stdin_too_large'); + expect(diagnostic).not.toContain(marker); + } + ); + it('runs context check before binding SessionStart sessions in uninitialized repos', async () => { await fs.remove(path.join(tempDir, '.context')); @@ -537,7 +569,10 @@ describe('HookDispatchService session lifecycle', () => { const toolTrace = records.find((record) => record.event === 'tool.use'); expect(toolTrace?.data).toMatchObject({ classification: 'test', - tool_input: { command: 'npm test -- --runInBand' }, + tool_input: { + commandBasename: 'npm', + commandPreview: 'npm test -- --runInBand', + }, }); }); diff --git a/src/cli/services/hookDispatchService.ts b/src/cli/services/hookDispatchService.ts index 9b65fc6c..f396d72a 100644 --- a/src/cli/services/hookDispatchService.ts +++ b/src/cli/services/hookDispatchService.ts @@ -5,8 +5,11 @@ * and writes host-specific JSON to stdout. */ +import * as path from 'path'; + import { createHarnessHookAdapter, + loadHookTracePolicy, recordHookTraceFailure, type HarnessHookResponse, WorkflowService, @@ -36,6 +39,8 @@ export interface HookDispatchOptions { repoPath?: string; stdin?: NodeJS.ReadableStream; stdout?: NodeJS.WritableStream; + /** Test/embedding override. Values remain clamped by the hook policy ceiling. */ + maxInputBytes?: number; } export interface HookDispatchResult { @@ -277,11 +282,32 @@ async function recordTraceAppendFailure(options: { } } -async function readStdin(stdin: NodeJS.ReadableStream = process.stdin): Promise { +class HookInputTooLargeError extends Error { + constructor( + readonly inputBytes: number, + readonly maxInputBytes: number + ) { + super(`Hook dispatch input exceeded the ${maxInputBytes} byte limit`); + this.name = 'HookInputTooLargeError'; + } +} + +async function readStdin( + stdin: NodeJS.ReadableStream = process.stdin, + maxInputBytes: number +): Promise { const chunks: Buffer[] = []; + let inputBytes = 0; for await (const chunk of stdin) { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))); + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)); + inputBytes += buffer.byteLength; + if (inputBytes > maxInputBytes) { + // Do not retain or concatenate rejected input. Hook failures must not block the host. + chunks.length = 0; + throw new HookInputTooLargeError(inputBytes, maxInputBytes); + } + chunks.push(buffer); } return Buffer.concat(chunks).toString('utf-8').trim(); @@ -499,7 +525,32 @@ export async function runHookDispatch( ): Promise { const stdin = options.stdin ?? process.stdin; const stdout = options.stdout ?? process.stdout; - const rawInput = await readStdin(stdin); + const configuredPolicy = loadHookTracePolicy(options.repoPath ?? process.cwd()); + const maxInputBytes = Math.min( + configuredPolicy.maxInputBytes, + typeof options.maxInputBytes === 'number' && Number.isFinite(options.maxInputBytes) + ? Math.max(1024, Math.floor(options.maxInputBytes)) + : configuredPolicy.maxInputBytes + ); + let rawInput: string; + try { + rawInput = await readStdin(stdin, maxInputBytes); + } catch (error) { + if (!(error instanceof HookInputTooLargeError)) { + throw error; + } + + const repoPath = path.resolve(options.repoPath ?? process.cwd()); + await recordTraceAppendFailure({ + repoPath, + source: options.source, + reason: 'hook_stdin_too_large', + message: `Rejected ${error.inputBytes} bytes (limit ${error.maxInputBytes})`, + }); + const output = finalizeHostHookOutput(options.source, { continue: true }); + stdout.write(`${JSON.stringify(output)}\n`); + return { exitCode: 0, output }; + } if (!rawInput) { throw new Error('Hook dispatch requires JSON input on stdin'); diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 1ace38ce..50060b19 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -95,4 +95,54 @@ describe('HarnessRuntimeStateService', () => { await expect(service.resumeSession(session.id)).rejects.toThrow('Cannot resume a completed session'); }); + + it('bounds oversized generic trace events before writing them', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + trace: { maxSerializedBytes: 1024 }, + }); + const session = await service.createSession({ name: 'bounded-traces' }); + const secretMarker = `large-marker-${'x'.repeat(10 * 1024)}`; + + const trace = await service.appendTrace(session.id, { + level: 'info', + event: 'large.event', + message: 'large trace', + data: { body: secretMarker }, + }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const persisted = await fs.readFile(traceFile, 'utf8'); + + expect(trace.data).toMatchObject({ traceDataOmitted: true, quota: 'max_serialized_trace_bytes' }); + expect(persisted).not.toContain(secretMarker); + expect(persisted.trim().split('\n').every((line) => Buffer.byteLength(line) <= 1024)).toBe(true); + }); + + it('rotates traces atomically and reads retained segments in chronological order', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'hooks.json'), { + trace: { + rotationBytes: 64 * 1024, + retainedSegments: 4, + maxSessionBytes: 512 * 1024, + }, + }); + const session = await service.createSession({ name: 'rotating-traces' }); + await Promise.all(Array.from({ length: 12 }, (_, index) => service.appendTrace(session.id, { + level: 'info', + event: 'concurrent.event', + message: `event-${index}`, + data: { index, payload: 'x'.repeat(10 * 1024) }, + }))); + + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const files = (await fs.readdir(sessionDir)).filter((entry) => entry.endsWith('.jsonl')); + expect(files).toContain('trace.jsonl'); + expect(files.some((entry) => /^trace\..+\.jsonl$/.test(entry))).toBe(true); + + const traces = await service.listTraces(session.id); + expect(traces.filter((trace) => trace.event === 'concurrent.event')).toHaveLength(12); + expect(traces.some((trace) => trace.event === 'trace.rotated')).toBe(true); + expect(traces.filter((trace) => trace.event === 'concurrent.event').map((trace) => trace.data?.index)) + .toEqual(Array.from({ length: 12 }, (_, index) => index)); + expect((await service.getSession(session.id)).traceCount).toBe(traces.length); + }); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index a23622e2..b80d2338 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -10,6 +10,30 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import { randomUUID } from 'crypto'; import { resolveRuntimeLayout, type RuntimeLayout } from '../../../../shared/fs/pathHelpers'; +import { + boundGenericTraceRecord, + loadGenericTraceEventMaxBytes, + loadHookTracePolicy, +} from '../../../application/hooks/hookTracePolicy'; + +const traceWriteQueues = new Map>(); + +async function withTraceWriteLock(key: string, operation: () => Promise): Promise { + const previous = traceWriteQueues.get(key) ?? Promise.resolve(); + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const tail = previous.catch(() => undefined).then(() => gate); + traceWriteQueues.set(key, tail); + await previous.catch(() => undefined); + try { + return await operation(); + } finally { + release(); + if (traceWriteQueues.get(key) === tail) { + traceWriteQueues.delete(key); + } + } +} export type HarnessSessionStatus = 'active' | 'paused' | 'completed' | 'failed'; export type HarnessTraceLevel = 'debug' | 'info' | 'warn' | 'error'; @@ -149,6 +173,10 @@ export class HarnessRuntimeStateService { return this.layout.sessionTraceFile(sessionId); } + private traceSegmentPrefix(sessionId: string): string { + return path.join(this.layout.sessionDir(sessionId), 'trace.'); + } + private artifactFile(sessionId: string, artifactId: string): string { return this.layout.sessionArtifactFile(sessionId, artifactId); } @@ -182,21 +210,88 @@ export class HarnessRuntimeStateService { } } - private async appendTraceLine(sessionId: string, trace: HarnessTraceRecord): Promise { + private async listTraceSegmentFiles(sessionId: string): Promise { + const sessionDir = this.layout.sessionDir(sessionId); + if (!(await fs.pathExists(sessionDir))) { + return []; + } + const entries = await fs.readdir(sessionDir); + return entries + .filter((entry) => /^trace\..+\.jsonl$/.test(entry)) + .sort() + .map((entry) => path.join(sessionDir, entry)); + } + + private async pruneTraceSegments(sessionId: string): Promise { + const policy = loadHookTracePolicy(this.repoPath); + const activeFile = this.traceFile(sessionId); + const activeBytes = await fs.stat(activeFile).then((stat) => stat.size).catch(() => 0); + const segments = await this.listTraceSegmentFiles(sessionId); + const segmentStats = await Promise.all(segments.map(async (file) => ({ + file, + bytes: await fs.stat(file).then((stat) => stat.size).catch(() => 0), + }))); + let totalBytes = activeBytes + segmentStats.reduce((sum, item) => sum + item.bytes, 0); + let retained = segmentStats.length; + for (const segment of segmentStats) { + if (retained <= policy.retainedTraceSegments && totalBytes <= policy.maxSessionTraceBytes) { + break; + } + await fs.remove(segment.file); + retained -= 1; + totalBytes -= segment.bytes; + } + } + + private async appendTraceLine( + sessionId: string, + trace: HarnessTraceRecord + ): Promise { await this.ensureSessionDir(sessionId); - await fs.appendFile(this.traceFile(sessionId), `${JSON.stringify(trace)}\n`, 'utf8'); + const activeFile = this.traceFile(sessionId); + const serialized = `${JSON.stringify(trace)}\n`; + const activeBytes = await fs.stat(activeFile).then((stat) => stat.size).catch(() => 0); + const policy = loadHookTracePolicy(this.repoPath); + let rotationTrace: HarnessTraceRecord | undefined; + + if (activeBytes > 0 && activeBytes + Buffer.byteLength(serialized, 'utf8') > policy.traceRotationBytes) { + const rotationId = `${new Date().toISOString().replace(/[:.]/g, '-')}.${randomUUID()}`; + const segmentFile = `${this.traceSegmentPrefix(sessionId)}${rotationId}.jsonl`; + await fs.rename(activeFile, segmentFile); + rotationTrace = boundGenericTraceRecord({ + id: randomUUID(), + sessionId, + level: 'info', + event: 'trace.rotated', + message: 'Trace segment rotated', + createdAt: nowIso(), + data: { + segment: path.basename(segmentFile), + rotationCount: (await this.listTraceSegmentFiles(sessionId)).length, + quotaStatus: 'within_limit', + }, + }, loadGenericTraceEventMaxBytes(this.repoPath)); + await fs.appendFile(activeFile, `${JSON.stringify(rotationTrace)}\n`, 'utf8'); + } + + await fs.appendFile(activeFile, serialized, 'utf8'); + await this.pruneTraceSegments(sessionId); + return rotationTrace; } private async recordTrace(sessionId: string, trace: HarnessTraceRecord): Promise { - const session = await this.readSession(sessionId); - await this.appendTraceLine(sessionId, trace); + return withTraceWriteLock(this.traceFile(sessionId), async () => { + const session = await this.readSession(sessionId); + const boundedTrace = boundGenericTraceRecord(trace, loadGenericTraceEventMaxBytes(this.repoPath)); + const rotationTrace = await this.appendTraceLine(sessionId, boundedTrace); - session.traceCount += 1; - session.lastTraceAt = trace.createdAt; - session.updatedAt = trace.createdAt; - await this.saveSession(session); + session.traceCount += rotationTrace ? 2 : 1; + session.lastTraceAt = boundedTrace.createdAt; + session.updatedAt = boundedTrace.createdAt; + await this.saveSession(session); - return trace; + return boundedTrace; + }); } async createSession(input: CreateSessionInput): Promise { @@ -332,13 +427,17 @@ export class HarnessRuntimeStateService { } async listTraces(sessionId: string): Promise { - const file = this.traceFile(sessionId); - if (!(await fs.pathExists(file))) { + const activeFile = this.traceFile(sessionId); + const files = [ + ...(await this.listTraceSegmentFiles(sessionId)), + ...(await fs.pathExists(activeFile) ? [activeFile] : []), + ]; + if (files.length === 0) { return []; } - const content = await fs.readFile(file, 'utf8'); - return content + const contents = await Promise.all(files.map((file) => fs.readFile(file, 'utf8'))); + return contents.join('') .split('\n') .map((line) => line.trim()) .filter(Boolean) diff --git a/src/harness/application/hooks/__tests__/hookReadiness.test.ts b/src/harness/application/hooks/__tests__/hookReadiness.test.ts index f8dbfb64..4700d5b6 100644 --- a/src/harness/application/hooks/__tests__/hookReadiness.test.ts +++ b/src/harness/application/hooks/__tests__/hookReadiness.test.ts @@ -185,6 +185,6 @@ describe('hook readiness runtime helpers', () => { expect(buildHookTraceData('Bash', { command: 'git diff -- src' })) .toMatchObject({ classification: 'inspection' }); expect(buildHookTraceData('Write', { file_path: 'README.md' })) - .toEqual({ tool_input: { file_path: 'README.md' } }); + .toMatchObject({ tool_input: { filePath: 'README.md' } }); }); }); diff --git a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts new file mode 100644 index 00000000..ea471baf --- /dev/null +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -0,0 +1,101 @@ +import { + DEFAULT_HOOK_STDIN_MAX_BYTES, + DEFAULT_HOOK_TRACE_POLICY, + parseHookTracePolicy, + sanitizeHookTraceData, +} from '../hookTracePolicy'; + +describe('hook trace policy', () => { + it('summarizes a multi-megabyte Write without persisting its source body', () => { + const content = `private-${'x'.repeat(5 * 1024 * 1024)}`; + const data = sanitizeHookTraceData('Write', { + file_path: 'src/large.ts', + content, + Authorization: 'Bearer secret-value', + }); + const serialized = JSON.stringify(data); + + expect(Buffer.byteLength(serialized)).toBeLessThan(16 * 1024); + expect(serialized).not.toContain('private-'); + expect(serialized).not.toContain('secret-value'); + expect(data).toMatchObject({ + tool_input: { + filePath: 'src/large.ts', + contentBytes: Buffer.byteLength(content), + contentHash: expect.stringMatching(/^sha256:/), + contentOmitted: true, + }, + capture: { + redactedFieldCount: 2, + truncatedFieldCount: 0, + }, + }); + }); + + it('summarizes Edit bodies and redacts sensitive keys case-insensitively', () => { + const data = sanitizeHookTraceData('Edit', { + filePath: 'src/index.ts', + old_string: 'old secret source', + newString: 'new secret source', + start_line: 4, + end_line: 8, + apiKEY: 'should-never-appear', + }); + const serialized = JSON.stringify(data); + + expect(serialized).not.toContain('old secret source'); + expect(serialized).not.toContain('new secret source'); + expect(serialized).not.toContain('should-never-appear'); + expect(data).toMatchObject({ + tool_input: { + filePath: 'src/index.ts', + oldStringBytes: 17, + oldStringOmitted: true, + newStringBytes: 17, + newStringOmitted: true, + range: { start_line: 4, end_line: 8 }, + }, + capture: { redactedFieldCount: 3 }, + }); + }); + + it('bounds Bash previews and unknown nested structures', () => { + const bash = sanitizeHookTraceData('Bash', { + command: `API_TOKEN=top-secret npm test --password hunter2 ${'x'.repeat(2000)}`, + }); + expect(bash).toMatchObject({ + tool_input: { commandBasename: 'npm' }, + capture: { truncatedFieldCount: 1 }, + }); + expect(Buffer.byteLength(String(bash.tool_input.commandPreview))).toBeLessThan(540); + expect(JSON.stringify(bash)).not.toContain('top-secret'); + expect(JSON.stringify(bash)).not.toContain('hunter2'); + + const unknown = sanitizeHookTraceData('CustomTool', { + Prompt: 'do not retain', + metadata: { token: 'secret', ok: true }, + values: Array.from({ length: 50 }, (_, index) => index), + }); + const serialized = JSON.stringify(unknown); + expect(serialized).not.toContain('do not retain'); + expect(serialized).not.toContain('secret'); + expect(unknown.capture.redactedFieldCount).toBe(2); + expect(unknown.capture.truncatedFieldCount).toBe(1); + }); + + it('falls back to defaults and clamps malformed or unsafe configuration', () => { + expect(parseHookTracePolicy({ maxInputBytes: 'huge' }).maxInputBytes) + .toBe(DEFAULT_HOOK_STDIN_MAX_BYTES); + const policy = parseHookTracePolicy({ + maxInputBytes: Number.MAX_SAFE_INTEGER, + maxStringBytes: Number.MAX_SAFE_INTEGER, + maxObjectDepth: -10, + trace: { retainedSegments: Number.MAX_SAFE_INTEGER }, + }); + expect(policy.maxInputBytes).toBe(16 * 1024 * 1024); + expect(policy.maxStringBytes).toBe(4096); + expect(policy.maxObjectDepth).toBe(1); + expect(policy.retainedTraceSegments).toBe(16); + expect(DEFAULT_HOOK_TRACE_POLICY.maxSerializedTraceBytes).toBe(16 * 1024); + }); +}); diff --git a/src/harness/application/hooks/bashClassification.ts b/src/harness/application/hooks/bashClassification.ts index 03fc3aa8..6391197e 100644 --- a/src/harness/application/hooks/bashClassification.ts +++ b/src/harness/application/hooks/bashClassification.ts @@ -6,6 +6,12 @@ export type HookBashClassification = | 'migration' | 'destructive'; +import { + loadHookTracePolicy, + sanitizeHookTraceData, + type HookTracePolicy, +} from './hookTracePolicy'; + function normalizeCommand(command: string): string { return command.trim().replace(/\s+/g, ' ').toLowerCase(); } @@ -92,8 +98,13 @@ export function classifyBashCommand(command: string | undefined): HookBashClassi return undefined; } -export function buildHookTraceData(toolName: string | undefined, toolInput: unknown): Record { - const data: Record = { tool_input: toolInput }; +export function buildHookTraceData( + toolName: string | undefined, + toolInput: unknown, + options: { policy?: HookTracePolicy; repoPath?: string } = {} +): Record { + const policy = options.policy ?? loadHookTracePolicy(options.repoPath); + const data: Record = sanitizeHookTraceData(toolName, toolInput, policy); if (toolName?.trim().toLowerCase() !== 'bash') { return data; } diff --git a/src/harness/application/hooks/hookTracePolicy.ts b/src/harness/application/hooks/hookTracePolicy.ts new file mode 100644 index 00000000..ad603b1b --- /dev/null +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -0,0 +1,405 @@ +import { createHash } from 'crypto'; +import * as fs from 'fs-extra'; +import * as path from 'path'; + +export const DEFAULT_HOOK_STDIN_MAX_BYTES = 8 * 1024 * 1024; +export const DEFAULT_HOOK_TRACE_MAX_BYTES = 16 * 1024; +export const DEFAULT_TRACE_EVENT_MAX_BYTES = 256 * 1024; +export const DEFAULT_TRACE_ROTATION_BYTES = 8 * 1024 * 1024; +export const DEFAULT_TRACE_RETAINED_SEGMENTS = 4; +export const DEFAULT_SESSION_TRACE_MAX_BYTES = 32 * 1024 * 1024; + +const GLOBAL_HOOK_STDIN_MAX_BYTES = 16 * 1024 * 1024; +const GLOBAL_HOOK_TRACE_MAX_BYTES = 64 * 1024; +const GLOBAL_TRACE_EVENT_MAX_BYTES = 1024 * 1024; +const GLOBAL_TRACE_ROTATION_MAX_BYTES = 64 * 1024 * 1024; +const GLOBAL_TRACE_RETAINED_SEGMENTS = 16; +const GLOBAL_SESSION_TRACE_MAX_BYTES = 256 * 1024 * 1024; + +export interface HookTracePolicy { + maxInputBytes: number; + maxStringBytes: number; + maxArrayItems: number; + maxObjectDepth: number; + maxSerializedTraceBytes: number; + traceRotationBytes: number; + retainedTraceSegments: number; + maxSessionTraceBytes: number; +} + +export interface HookTraceMetrics { + inputBytes: number; + persistedBytes: number; + redactedFieldCount: number; + truncatedFieldCount: number; + quotaStatus: 'within_limit' | 'truncated'; +} + +export interface SanitizedHookTraceData extends Record { + tool_input: Record; + capture: HookTraceMetrics; +} + +export const DEFAULT_HOOK_TRACE_POLICY: HookTracePolicy = { + maxInputBytes: DEFAULT_HOOK_STDIN_MAX_BYTES, + maxStringBytes: 512, + maxArrayItems: 20, + maxObjectDepth: 4, + maxSerializedTraceBytes: DEFAULT_HOOK_TRACE_MAX_BYTES, + traceRotationBytes: DEFAULT_TRACE_ROTATION_BYTES, + retainedTraceSegments: DEFAULT_TRACE_RETAINED_SEGMENTS, + maxSessionTraceBytes: DEFAULT_SESSION_TRACE_MAX_BYTES, +}; + +const SENSITIVE_KEY = /(?:content|old[_-]?string|new[_-]?string|patch|api[_-]?key|token|secret|password|authorization|messages|prompt)/i; +const PATH_KEYS = ['file_path', 'filePath', 'path']; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function finiteInteger(value: unknown, fallback: number, minimum: number, maximum: number): number { + return typeof value === 'number' && Number.isFinite(value) + ? Math.min(maximum, Math.max(minimum, Math.floor(value))) + : fallback; +} + +function nestedValue(config: Record, section: string, key: string): unknown { + const nested = config[section]; + return isRecord(nested) ? nested[key] : undefined; +} + +function configuredValue(config: Record, key: string, section: string, nestedKey: string): unknown { + return config[key] ?? nestedValue(config, section, nestedKey); +} + +export function parseHookTracePolicy(value: unknown): HookTracePolicy { + const config = isRecord(value) ? value : {}; + return { + maxInputBytes: finiteInteger( + configuredValue(config, 'maxInputBytes', 'stdin', 'maxBytes'), + DEFAULT_HOOK_TRACE_POLICY.maxInputBytes, + 1024, + GLOBAL_HOOK_STDIN_MAX_BYTES + ), + maxStringBytes: finiteInteger( + configuredValue(config, 'maxStringBytes', 'trace', 'maxStringBytes'), + DEFAULT_HOOK_TRACE_POLICY.maxStringBytes, + 32, + 4096 + ), + maxArrayItems: finiteInteger( + configuredValue(config, 'maxArrayItems', 'trace', 'maxArrayItems'), + DEFAULT_HOOK_TRACE_POLICY.maxArrayItems, + 1, + 100 + ), + maxObjectDepth: finiteInteger( + configuredValue(config, 'maxObjectDepth', 'trace', 'maxObjectDepth'), + DEFAULT_HOOK_TRACE_POLICY.maxObjectDepth, + 1, + 8 + ), + maxSerializedTraceBytes: finiteInteger( + configuredValue(config, 'maxSerializedTraceBytes', 'trace', 'maxSerializedBytes'), + DEFAULT_HOOK_TRACE_POLICY.maxSerializedTraceBytes, + 1024, + GLOBAL_HOOK_TRACE_MAX_BYTES + ), + traceRotationBytes: finiteInteger( + configuredValue(config, 'traceRotationBytes', 'trace', 'rotationBytes'), + DEFAULT_HOOK_TRACE_POLICY.traceRotationBytes, + 64 * 1024, + GLOBAL_TRACE_ROTATION_MAX_BYTES + ), + retainedTraceSegments: finiteInteger( + configuredValue(config, 'retainedTraceSegments', 'trace', 'retainedSegments'), + DEFAULT_HOOK_TRACE_POLICY.retainedTraceSegments, + 0, + GLOBAL_TRACE_RETAINED_SEGMENTS + ), + maxSessionTraceBytes: finiteInteger( + configuredValue(config, 'maxSessionTraceBytes', 'trace', 'maxSessionBytes'), + DEFAULT_HOOK_TRACE_POLICY.maxSessionTraceBytes, + 64 * 1024, + GLOBAL_SESSION_TRACE_MAX_BYTES + ), + }; +} + +export function loadHookTracePolicy(repoPath?: string): HookTracePolicy { + if (!repoPath) { + return { ...DEFAULT_HOOK_TRACE_POLICY }; + } + + try { + const configPath = path.join(path.resolve(repoPath), '.context', 'config', 'hooks.json'); + return parseHookTracePolicy(fs.readJsonSync(configPath)); + } catch { + return { ...DEFAULT_HOOK_TRACE_POLICY }; + } +} + +export function loadGenericTraceEventMaxBytes(repoPath: string): number { + try { + const configPath = path.join(path.resolve(repoPath), '.context', 'config', 'runtime.json'); + const value = fs.readJsonSync(configPath) as unknown; + const config = isRecord(value) ? value : {}; + const configured = config.maxSerializedTraceBytes ?? nestedValue(config, 'trace', 'maxSerializedBytes'); + return finiteInteger(configured, DEFAULT_TRACE_EVENT_MAX_BYTES, 1024, GLOBAL_TRACE_EVENT_MAX_BYTES); + } catch { + return DEFAULT_TRACE_EVENT_MAX_BYTES; + } +} + +function byteLength(value: unknown): number { + try { + return Buffer.byteLength(JSON.stringify(value) ?? '', 'utf8'); + } catch { + return 0; + } +} + +function truncateUtf8(value: string, maximumBytes: number): { value: string; truncated: boolean } { + if (Buffer.byteLength(value, 'utf8') <= maximumBytes) { + return { value, truncated: false }; + } + + const characters = Array.from(value); + let low = 0; + let high = characters.length; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + if (Buffer.byteLength(characters.slice(0, middle).join(''), 'utf8') <= maximumBytes) { + low = middle; + } else { + high = middle - 1; + } + } + return { value: characters.slice(0, low).join(''), truncated: true }; +} + +function hashText(value: string): string { + return `sha256:${createHash('sha256').update(value, 'utf8').digest('hex')}`; +} + +function firstString(input: Record, keys: string[]): string | undefined { + for (const key of keys) { + if (typeof input[key] === 'string') { + return input[key] as string; + } + } + return undefined; +} + +function commandBasename(command: string): string | undefined { + const match = command.trim().match(/^(?:env\s+)?(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*([^\s;&|]+)/); + return match?.[1] ? path.basename(match[1]) : undefined; +} + +function redactCommandSecrets(command: string): { value: string; redacted: number } { + let redacted = 0; + const replace = (pattern: RegExp, replacement: string): void => { + command = command.replace(pattern, (...args: unknown[]) => { + redacted += 1; + const key = typeof args[1] === 'string' ? args[1] : ''; + return replacement.replace('$KEY', key); + }); + }; + replace(/['"](authorization)\s*:\s*(?:bearer\s+)?[^'"]+['"]/gi, '$KEY=[REDACTED]'); + replace(/\b(authorization)\s*[:=]\s*(?:bearer\s+)?[^\s;&|]+/gi, '$KEY=[REDACTED]'); + replace(/--?(api[-_]?key|token|password|secret)(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, '--$KEY=[REDACTED]'); + replace(/\b(api[-_]?key|token|password|secret)=(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, '$KEY=[REDACTED]'); + return { value: command, redacted }; +} + +function countSensitiveFields(value: unknown, policy: HookTracePolicy, depth = 0): number { + if (depth > policy.maxObjectDepth) return 0; + if (Array.isArray(value)) { + return value.slice(0, policy.maxArrayItems) + .reduce((sum, item) => sum + countSensitiveFields(item, policy, depth + 1), 0); + } + if (!isRecord(value)) return 0; + return Object.entries(value).slice(0, policy.maxArrayItems).reduce( + (sum, [key, child]) => sum + (SENSITIVE_KEY.test(key) ? 1 : countSensitiveFields(child, policy, depth + 1)), + 0 + ); +} + +interface SanitizeState { + redactedFieldCount: number; + truncatedFieldCount: number; +} + +function summarizeUnknown( + value: unknown, + policy: HookTracePolicy, + state: SanitizeState, + depth = 0 +): unknown { + if (value === null || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + if (typeof value === 'string') { + const result = truncateUtf8(value, policy.maxStringBytes); + if (result.truncated) state.truncatedFieldCount += 1; + return result.truncated ? `${result.value}…[truncated]` : result.value; + } + if (Array.isArray(value)) { + const values = value.slice(0, policy.maxArrayItems); + if (values.length < value.length) state.truncatedFieldCount += 1; + if (depth >= policy.maxObjectDepth) { + state.truncatedFieldCount += 1; + return { itemCount: value.length, valuesOmitted: true }; + } + return values.map((item) => summarizeUnknown(item, policy, state, depth + 1)); + } + if (!isRecord(value)) { + return typeof value; + } + if (depth >= policy.maxObjectDepth) { + state.truncatedFieldCount += 1; + return { keys: Object.keys(value).slice(0, policy.maxArrayItems), valuesOmitted: true }; + } + + const result: Record = {}; + const entries = Object.entries(value).slice(0, policy.maxArrayItems); + if (entries.length < Object.keys(value).length) state.truncatedFieldCount += 1; + for (const [key, child] of entries) { + if (SENSITIVE_KEY.test(key)) { + result[key] = '[REDACTED]'; + state.redactedFieldCount += 1; + } else { + result[key] = summarizeUnknown(child, policy, state, depth + 1); + } + } + return result; +} + +function summarizeWrite(input: Record): Record { + const content = typeof input.content === 'string' ? input.content : undefined; + return { + ...(firstString(input, PATH_KEYS) ? { filePath: firstString(input, PATH_KEYS) } : {}), + ...(typeof input.byte_length === 'number' ? { declaredByteLength: input.byte_length } : {}), + ...(content !== undefined ? { + contentBytes: Buffer.byteLength(content, 'utf8'), + contentHash: hashText(content), + contentOmitted: true, + } : {}), + }; +} + +function summarizeEdit(input: Record): Record { + const oldString = firstString(input, ['old_string', 'oldString']); + const newString = firstString(input, ['new_string', 'newString']); + const rangeKeys = ['start_line', 'end_line', 'startLine', 'endLine', 'line', 'column']; + const range = Object.fromEntries(rangeKeys + .filter((key) => typeof input[key] === 'number') + .map((key) => [key, input[key]])); + return { + ...(firstString(input, PATH_KEYS) ? { filePath: firstString(input, PATH_KEYS) } : {}), + ...(oldString !== undefined ? { + oldStringBytes: Buffer.byteLength(oldString, 'utf8'), + oldStringHash: hashText(oldString), + oldStringOmitted: true, + } : {}), + ...(newString !== undefined ? { + newStringBytes: Buffer.byteLength(newString, 'utf8'), + newStringHash: hashText(newString), + newStringOmitted: true, + } : {}), + ...(Object.keys(range).length > 0 ? { range } : {}), + }; +} + +function summarizeBash(input: Record, policy: HookTracePolicy, state: SanitizeState): Record { + const command = typeof input.command === 'string' ? input.command : undefined; + if (!command) return {}; + const redactedCommand = redactCommandSecrets(command); + state.redactedFieldCount += redactedCommand.redacted; + const preview = truncateUtf8(redactedCommand.value, policy.maxStringBytes); + if (preview.truncated) state.truncatedFieldCount += 1; + return { + commandBasename: commandBasename(command), + commandBytes: Buffer.byteLength(command, 'utf8'), + commandPreview: preview.truncated ? `${preview.value}…[truncated]` : preview.value, + }; +} + +export function sanitizeHookTraceData( + toolName: string | undefined, + toolInput: unknown, + policy: HookTracePolicy = DEFAULT_HOOK_TRACE_POLICY +): SanitizedHookTraceData { + const state: SanitizeState = { redactedFieldCount: 0, truncatedFieldCount: 0 }; + const normalizedTool = toolName?.trim().toLowerCase(); + const input = isRecord(toolInput) ? toolInput : {}; + let summary: Record; + if (normalizedTool === 'write') { + state.redactedFieldCount = countSensitiveFields(input, policy); + summary = summarizeWrite(input); + } else if (normalizedTool === 'edit') { + state.redactedFieldCount = countSensitiveFields(input, policy); + summary = summarizeEdit(input); + } else if (normalizedTool === 'bash') { + state.redactedFieldCount = countSensitiveFields(input, policy); + summary = summarizeBash(input, policy, state); + } else { + summary = summarizeUnknown(input, policy, state) as Record; + } + + const result: SanitizedHookTraceData = { + tool_input: summary, + capture: { + inputBytes: byteLength(toolInput), + persistedBytes: 0, + redactedFieldCount: state.redactedFieldCount, + truncatedFieldCount: state.truncatedFieldCount, + quotaStatus: 'within_limit', + }, + }; + for (let iteration = 0; iteration < 4; iteration += 1) { + const persistedBytes = byteLength(result); + if (result.capture.persistedBytes === persistedBytes) break; + result.capture.persistedBytes = persistedBytes; + } + + if (byteLength(result) > policy.maxSerializedTraceBytes) { + result.tool_input = { + keys: Object.keys(input).slice(0, policy.maxArrayItems), + valuesOmitted: true, + }; + result.capture.truncatedFieldCount += 1; + result.capture.quotaStatus = 'truncated'; + for (let iteration = 0; iteration < 4; iteration += 1) { + const persistedBytes = byteLength(result); + if (result.capture.persistedBytes === persistedBytes) break; + result.capture.persistedBytes = persistedBytes; + } + } + + return result; +} + +export function boundGenericTraceRecord }>( + trace: T, + maximumBytes: number +): T { + if (byteLength(trace) <= maximumBytes) { + return trace; + } + + const originalBytes = byteLength(trace); + const boundedMessage = truncateUtf8(trace.message, 512); + const bounded = { + ...trace, + ...(typeof trace.event === 'string' ? { event: truncateUtf8(trace.event, 256).value } : {}), + message: boundedMessage.truncated ? `${boundedMessage.value}…[truncated]` : boundedMessage.value, + data: { + traceDataOmitted: true, + originalSerializedBytes: originalBytes, + quota: 'max_serialized_trace_bytes', + }, + }; + return bounded as T; +} diff --git a/src/harness/application/hooks/index.ts b/src/harness/application/hooks/index.ts index d349b35c..fc47d1c4 100644 --- a/src/harness/application/hooks/index.ts +++ b/src/harness/application/hooks/index.ts @@ -2,3 +2,4 @@ export * from './hookAdapter'; export * from './bashClassification'; export * from './hookReadiness'; export * from './hookRuntimeState'; +export * from './hookTracePolicy'; diff --git a/src/harness/index.ts b/src/harness/index.ts index fa1b6cd9..b6536732 100644 --- a/src/harness/index.ts +++ b/src/harness/index.ts @@ -20,6 +20,17 @@ export { HarnessHookAdapter, createHarnessHookAdapter, buildHookTraceData, + sanitizeHookTraceData, + parseHookTracePolicy, + loadHookTracePolicy, + loadGenericTraceEventMaxBytes, + boundGenericTraceRecord, + DEFAULT_HOOK_STDIN_MAX_BYTES, + DEFAULT_HOOK_TRACE_MAX_BYTES, + DEFAULT_TRACE_EVENT_MAX_BYTES, + DEFAULT_TRACE_ROTATION_BYTES, + DEFAULT_TRACE_RETAINED_SEGMENTS, + DEFAULT_SESSION_TRACE_MAX_BYTES, classifyBashCommand, extractBashCommand, buildHookReadinessSummary, @@ -41,6 +52,9 @@ export { type HarnessHookResponse, type HarnessHookAdapterOptions, type HookBashClassification, + type HookTracePolicy, + type HookTraceMetrics, + type SanitizedHookTraceData, type HookContextReadiness, type HookWorkflowReadiness, type HookWorkflowPreflightSummary, diff --git a/src/integrations/__tests__/hookRoundTrip.test.ts b/src/integrations/__tests__/hookRoundTrip.test.ts index 26207037..0520d53e 100644 --- a/src/integrations/__tests__/hookRoundTrip.test.ts +++ b/src/integrations/__tests__/hookRoundTrip.test.ts @@ -38,9 +38,10 @@ describe('hook mapper unit tests', () => { }); it('maps PostToolUse to harness appendTrace when harness session is bound', () => { - expect(mapClaudeCodeEvent(postToolUseWriteFixture, { + const mapped = mapClaudeCodeEvent(postToolUseWriteFixture, { harnessSessionId: 'harness-session-1', - })).toEqual({ + }); + expect(mapped).toMatchObject({ tool: 'harness', params: { action: 'appendTrace', @@ -48,9 +49,17 @@ describe('hook mapper unit tests', () => { level: 'info', event: 'tool.use', message: 'Write', - data: { tool_input: postToolUseWriteFixture.tool_input }, + data: { + tool_input: { + filePath: postToolUseWriteFixture.tool_input.file_path, + contentBytes: Buffer.byteLength(postToolUseWriteFixture.tool_input.content), + contentOmitted: true, + }, + capture: { redactedFieldCount: 1 }, + }, }, }); + expect(JSON.stringify(mapped)).not.toContain(postToolUseWriteFixture.tool_input.content); }); it('returns null for PostToolUse without harness session binding', () => { @@ -82,9 +91,10 @@ describe('hook mapper unit tests', () => { }); it('maps PostToolUse to harness appendTrace when harness session is bound', () => { - expect(mapCodexEvent(codexPostToolUseFixture, { + const mapped = mapCodexEvent(codexPostToolUseFixture, { harnessSessionId: 'harness-session-2', - })).toEqual({ + }); + expect(mapped).toMatchObject({ tool: 'harness', params: { action: 'appendTrace', @@ -92,9 +102,13 @@ describe('hook mapper unit tests', () => { level: 'info', event: 'tool.use', message: 'Edit', - data: { tool_input: codexPostToolUseFixture.tool_input }, + data: { + tool_input: { filePath: codexPostToolUseFixture.tool_input.file_path }, + capture: { redactedFieldCount: 1 }, + }, }, }); + expect(JSON.stringify(mapped)).not.toContain(codexPostToolUseFixture.tool_input.content); }); it('maps Stop to workflow-guide', () => { @@ -383,6 +397,31 @@ describe('hook mapper unit tests', () => { }, }); }); + + it('sanitizes Pi Write payloads before mapping them to appendTrace', () => { + const source = 'pi-secret-source-body'; + const mapped = mapPiEvent({ + type: 'tool_execution_end', + toolName: 'Write', + toolInput: { file_path: 'src/pi.ts', content: source, password: 'hidden' }, + sessionId: 'pi-harness-1', + cwd: '/tmp/repo', + }); + + expect(mapped).toMatchObject({ + tool: 'harness', + params: { + action: 'appendTrace', + data: { + host: 'pi-dev', + tool_input: { filePath: 'src/pi.ts', contentOmitted: true }, + capture: { redactedFieldCount: 2 }, + }, + }, + }); + expect(JSON.stringify(mapped)).not.toContain(source); + expect(JSON.stringify(mapped)).not.toContain('hidden'); + }); }); describe('mapPiResponse', () => { diff --git a/src/integrations/pi-dev/hooks/mapPiEvent.ts b/src/integrations/pi-dev/hooks/mapPiEvent.ts index 3b539dd5..5b70edef 100644 --- a/src/integrations/pi-dev/hooks/mapPiEvent.ts +++ b/src/integrations/pi-dev/hooks/mapPiEvent.ts @@ -107,7 +107,7 @@ export function mapPiEvent( event: 'tool.use', message: event.toolName, data: { - ...buildHookTraceData(event.toolName, event.toolInput), + ...buildHookTraceData(event.toolName, event.toolInput, { repoPath }), host: 'pi-dev', }, }, diff --git a/src/integrations/shared/resolveHarnessHookFromHostEvent.ts b/src/integrations/shared/resolveHarnessHookFromHostEvent.ts index 07c43129..f1526bf0 100644 --- a/src/integrations/shared/resolveHarnessHookFromHostEvent.ts +++ b/src/integrations/shared/resolveHarnessHookFromHostEvent.ts @@ -97,7 +97,7 @@ export function resolveHarnessHookFromHostEvent( level: 'info', event: 'tool.use', message: event.toolName ?? 'tool.use', - data: buildHookTraceData(event.toolName, event.toolInput), + data: buildHookTraceData(event.toolName, event.toolInput, { repoPath }), }, }; } From 850bfdd31e12501deaccbe8d87101a482d8ecadf Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:00:59 -0300 Subject: [PATCH 05/39] fix LSP process lifecycle --- .../lsp/__tests__/fixtures/fake-lsp-server.js | 71 +++ .../lsp/__tests__/lspLayer.lifecycle.test.ts | 163 +++++ .../adapters/out/semantic/lsp/index.ts | 5 + .../adapters/out/semantic/lsp/lspLayer.ts | 590 ++++++++++++------ 4 files changed, 647 insertions(+), 182 deletions(-) create mode 100644 src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js create mode 100644 src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js new file mode 100644 index 00000000..fc7ea1d5 --- /dev/null +++ b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js @@ -0,0 +1,71 @@ +'use strict'; + +const fs = require('fs'); + +const mode = process.argv[2] || 'normal'; +const pidFile = process.argv[3]; +if (pidFile) fs.appendFileSync(pidFile, `${process.pid}\n`); + +if (mode === 'ignore-shutdown') { + process.on('SIGTERM', () => {}); +} + +let input = Buffer.alloc(0); + +function send(message) { + const content = JSON.stringify(message); + process.stdout.write(`Content-Length: ${Buffer.byteLength(content)}\r\n\r\n${content}`); +} + +function respond(message) { + if (message.method === 'initialize') { + if (mode === 'crash-after-spawn') { + process.exit(19); + } else if (mode === 'reject-initialize') { + send({ jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'initialize rejected' } }); + } else if (mode !== 'timeout-initialize') { + send({ jsonrpc: '2.0', id: message.id, result: { capabilities: {} } }); + } + return; + } + + if (message.method === 'shutdown') { + if (mode !== 'ignore-shutdown') { + send({ jsonrpc: '2.0', id: message.id, result: null }); + } + return; + } + + if (message.method === 'exit') { + if (mode !== 'ignore-shutdown') process.exit(0); + return; + } + + if (message.method === 'textDocument/hover') { + if (mode === 'crash-on-hover') process.exit(23); + send({ jsonrpc: '2.0', id: message.id, result: { contents: '```ts\nFakeType\n```' } }); + return; + } + + if (message.id !== undefined) send({ jsonrpc: '2.0', id: message.id, result: [] }); +} + +process.stdin.on('data', (data) => { + input = Buffer.concat([input, data]); + while (true) { + const headerEnd = input.indexOf('\r\n\r\n'); + if (headerEnd < 0) return; + const header = input.subarray(0, headerEnd).toString('ascii'); + const match = /Content-Length:\s*(\d+)/i.exec(header); + if (!match) process.exit(2); + const length = Number(match[1]); + const bodyStart = headerEnd + 4; + if (input.length < bodyStart + length) return; + const message = JSON.parse(input.subarray(bodyStart, bodyStart + length).toString('utf8')); + input = input.subarray(bodyStart + length); + respond(message); + } +}); + +// Keep the fixture alive after stdin closes so tests prove signal escalation. +setInterval(() => {}, 1000); diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts new file mode 100644 index 00000000..aca8c164 --- /dev/null +++ b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts @@ -0,0 +1,163 @@ +import * as fs from 'fs/promises'; +import * as os from 'os'; +import * as path from 'path'; +import { LSPLayer, LSPLayerOptions, LSPLifecycleEvent } from '../lspLayer'; +import type { LSPServerConfig } from '../../types'; + +const FIXTURE = path.join(__dirname, 'fixtures', 'fake-lsp-server.js'); +const TIMEOUT_MS = 150; + +function server(mode: string, pidFile: string): LSPServerConfig { + return { command: process.execPath, args: [FIXTURE, mode, pidFile] }; +} + +async function waitUntil(predicate: () => boolean, timeoutMs = 2_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error('condition did not become true before timeout'); +} + +function processIsAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function readPids(pidFile: string): Promise { + try { + return (await fs.readFile(pidFile, 'utf8')) + .trim() + .split('\n') + .filter(Boolean) + .map(Number); + } catch { + return []; + } +} + +describe('LSPLayer process lifecycle', () => { + let projectPath: string; + let pidFile: string; + let layer: LSPLayer | undefined; + + beforeEach(async () => { + projectPath = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-lsp-')); + pidFile = path.join(projectPath, 'pids'); + }); + + afterEach(async () => { + await layer?.shutdown(); + const pids = await readPids(pidFile); + await Promise.all(pids.map((pid) => waitUntil(() => !processIsAlive(pid)))); + await fs.rm(projectPath, { recursive: true, force: true }); + }); + + function createLayer( + configs: Record, + overrides: LSPLayerOptions = {} + ): LSPLayer { + layer = new LSPLayer({ + serverConfigs: configs, + requestTimeoutMs: TIMEOUT_MS, + shutdownTimeoutMs: TIMEOUT_MS, + terminationGraceMs: TIMEOUT_MS, + ...overrides, + }); + return layer; + } + + it('terminates the child after initialize rejection and suppresses retries', async () => { + const subject = createLayer({ typescript: server('reject-initialize', pidFile) }); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); + const [pid] = await readPids(pidFile); + expect(pid).toBeDefined(); + await waitUntil(() => !processIsAlive(pid)); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); + await expect(subject.getTypeInfo(path.join(projectPath, 'a.ts'), 1, 0, projectPath)).resolves.toBeNull(); + expect(await readPids(pidFile)).toEqual([pid]); + }); + + it('terminates the child after initialize timeout', async () => { + const subject = createLayer({ typescript: server('timeout-initialize', pidFile) }); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); + const [pid] = await readPids(pidFile); + expect(pid).toBeDefined(); + await waitUntil(() => !processIsAlive(pid)); + }); + + it('cleans up when the child crashes during initialization', async () => { + const subject = createLayer({ typescript: server('crash-after-spawn', pidFile) }); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); + const [pid] = await readPids(pidFile); + expect(pid).toBeDefined(); + await waitUntil(() => !processIsAlive(pid)); + }); + + it('deduplicates concurrent initialization for the same language and project', async () => { + const subject = createLayer({ typescript: server('normal', pidFile) }); + + await expect( + Promise.all([ + subject.ensureServer('typescript', projectPath), + subject.ensureServer('typescript', projectPath), + subject.ensureServer('typescript', projectPath), + ]) + ).resolves.toEqual([true, true, true]); + expect(await readPids(pidFile)).toHaveLength(1); + }); + + it('does not reject another language request when one server crashes', async () => { + const subject = createLayer({ + typescript: server('crash-on-hover', pidFile), + javascript: server('normal', pidFile), + }); + await Promise.all([ + subject.ensureServer('typescript', projectPath), + subject.ensureServer('javascript', projectPath), + ]); + + const [failedResult, healthyResult] = await Promise.all([ + subject.getTypeInfo(path.join(projectPath, 'a.ts'), 1, 0, projectPath), + subject.getTypeInfo(path.join(projectPath, 'a.js'), 1, 0, projectPath), + ]); + + expect(failedResult).toBeNull(); + expect(healthyResult?.name).toBe('FakeType'); + }); + + it('forces termination and waits for child exit when shutdown is ignored', async () => { + const events: LSPLifecycleEvent[] = []; + const subject = createLayer( + { typescript: server('ignore-shutdown', pidFile) }, + { onLifecycleEvent: (event) => events.push(event) } + ); + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(true); + const [pid] = await readPids(pidFile); + expect(processIsAlive(pid)).toBe(true); + + await subject.shutdown(); + + expect(processIsAlive(pid)).toBe(false); + expect(events).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + language: 'typescript', + state: 'stopped', + forcedKill: true, + exitSignal: 'SIGKILL', + }), + ]) + ); + await expect(subject.shutdown()).resolves.toBeUndefined(); + }); +}); diff --git a/src/harness/adapters/out/semantic/lsp/index.ts b/src/harness/adapters/out/semantic/lsp/index.ts index 19425507..56b9b494 100644 --- a/src/harness/adapters/out/semantic/lsp/index.ts +++ b/src/harness/adapters/out/semantic/lsp/index.ts @@ -1 +1,6 @@ export { LSPLayer } from './lspLayer'; +export type { + LSPLayerOptions, + LSPLifecycleEvent, + LSPServerState, +} from './lspLayer'; diff --git a/src/harness/adapters/out/semantic/lsp/lspLayer.ts b/src/harness/adapters/out/semantic/lsp/lspLayer.ts index 9b45f6ba..a7f33990 100644 --- a/src/harness/adapters/out/semantic/lsp/lspLayer.ts +++ b/src/harness/adapters/out/semantic/lsp/lspLayer.ts @@ -1,11 +1,12 @@ /** - * LSP Layer - Language Server Protocol integration for semantic analysis + * LSP Layer - Language Server Protocol integration for semantic analysis. * - * Provides deeper semantic understanding through LSP servers. - * This layer is lazily initialized and optional. + * Every child process is owned by one ServerHandle. Buffers, pending requests, + * initialization and shutdown state therefore cannot leak across servers. */ import { spawn, ChildProcess } from 'child_process'; +import { createHash } from 'crypto'; import * as path from 'path'; import { TypeInfo, @@ -30,6 +31,52 @@ interface PendingRequest { timeout: NodeJS.Timeout; } +export type LSPServerState = 'starting' | 'ready' | 'stopping' | 'stopped' | 'failed'; + +export interface LSPLifecycleEvent { + language: string; + projectHash: string; + pid?: number; + state: LSPServerState; + timestamp: number; + pendingRequestCount: number; + reason?: string; + initializeDurationMs?: number; + exitCode?: number | null; + exitSignal?: NodeJS.Signals | null; + forcedKill?: boolean; + retrySuppressed?: boolean; +} + +interface ServerHandle { + key: string; + language: string; + projectPath: string; + process: ChildProcess; + state: LSPServerState; + initialization: Promise; + stopping?: Promise; + pendingRequests: Map; + buffer: Buffer; + startedAt: number; + terminationReason?: string; + forcedKill: boolean; + closed: boolean; + closePromise: Promise; + resolveClose: () => void; + exitCode?: number | null; + exitSignal?: NodeJS.Signals | null; +} + +export interface LSPLayerOptions { + /** Primarily useful to provide explicitly installed or test language servers. */ + serverConfigs?: Record; + requestTimeoutMs?: number; + shutdownTimeoutMs?: number; + terminationGraceMs?: number; + onLifecycleEvent?: (event: LSPLifecycleEvent) => void; +} + const LSP_SERVER_CONFIGS: Record = { typescript: { command: 'typescript-language-server', @@ -48,85 +95,136 @@ const LSP_SERVER_CONFIGS: Record = { }, }; -const REQUEST_TIMEOUT_MS = 10000; +const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; +const DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000; +const DEFAULT_TERMINATION_GRACE_MS = 2_000; export class LSPLayer { - private servers: Map = new Map(); - private messageId: number = 0; - private pendingRequests: Map = new Map(); - private initialized: Map = new Map(); - private buffers: Map = new Map(); + private readonly handles = new Map(); + private readonly failedCircuits = new Set(); + private readonly serverConfigs: Record; + private readonly requestTimeoutMs: number; + private readonly shutdownTimeoutMs: number; + private readonly terminationGraceMs: number; + private readonly onLifecycleEvent?: (event: LSPLifecycleEvent) => void; + private messageId = 0; + private shuttingDown?: Promise; + + constructor(options: LSPLayerOptions = {}) { + this.serverConfigs = options.serverConfigs || LSP_SERVER_CONFIGS; + this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; + this.shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS; + this.terminationGraceMs = options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS; + this.onLifecycleEvent = options.onLifecycleEvent; + } private detectLanguage(filePath: string): SupportedLanguage | null { const ext = path.extname(filePath); return LANGUAGE_EXTENSIONS[ext] || null; } - private getServerConfig(language: string): LSPServerConfig | null { - return LSP_SERVER_CONFIGS[language] || null; + private serverKey(language: string, projectPath: string): string { + return `${language}:${path.resolve(projectPath)}`; } async ensureServer(language: string, projectPath: string): Promise { - if (this.initialized.get(language)) { - return true; - } - - const config = this.getServerConfig(language); - if (!config) { + const key = this.serverKey(language, projectPath); + if (this.failedCircuits.has(key)) { + this.emitLifecycle(language, projectPath, 'failed', 0, { retrySuppressed: true }); return false; } + if (this.shuttingDown) return false; - try { - // Wrap spawn in a promise to properly handle ENOENT and other spawn errors - const serverProcess = await new Promise((resolve, reject) => { - const proc = spawn(config.command, config.args, { - cwd: projectPath, - stdio: ['pipe', 'pipe', 'pipe'], - env: { ...process.env }, - }); - - // Handle spawn errors (e.g., command not found) - proc.on('error', (error) => { - reject(error); - }); + const existing = this.handles.get(key); + if (existing?.state === 'ready') return true; + if (existing?.state === 'starting') return existing.initialization; + if (existing) return false; - // Give spawn a moment to fail or succeed - // If no error within a short time, assume spawn succeeded - setTimeout(() => { - if (proc.pid) { - resolve(proc); - } else { - reject(new Error(`Failed to spawn ${config.command}`)); - } - }, 100); - }); + const config = this.serverConfigs[language]; + if (!config) return false; - this.servers.set(language, serverProcess); - this.buffers.set(language, ''); + let resolveClose!: () => void; + const closePromise = new Promise((resolve) => { + resolveClose = resolve; + }); + const child = spawn(config.command, config.args, { + cwd: projectPath, + stdio: ['pipe', 'pipe', 'pipe'], + env: { ...process.env }, + }); - // Setup message handling - serverProcess.stdout?.on('data', (data: Buffer) => { - this.handleServerData(language, data); - }); + const handle: ServerHandle = { + key, + language, + projectPath: path.resolve(projectPath), + process: child, + state: 'starting', + initialization: Promise.resolve(false), + pendingRequests: new Map(), + buffer: Buffer.alloc(0), + startedAt: Date.now(), + forcedKill: false, + closed: false, + closePromise, + resolveClose, + }; - serverProcess.stderr?.on('data', () => { - // Silently ignore stderr - LSP servers may output diagnostics - }); + // Publish the owner before any asynchronous event can act on the process. + this.handles.set(key, handle); + this.emitHandleLifecycle(handle, 'starting'); + this.attachProcessListeners(handle); + handle.initialization = this.initializeHandle(handle); + return handle.initialization; + } - // Re-attach error handler for runtime errors (after spawn) - serverProcess.on('error', () => { - // Silently cleanup on error - this.cleanup(language); - }); + private attachProcessListeners(handle: ServerHandle): void { + handle.process.stdout?.on('data', (data: Buffer) => this.handleServerData(handle, data)); + // Drain stderr without retaining diagnostics in memory. + handle.process.stderr?.on('data', () => undefined); + handle.process.stdin?.on('error', () => undefined); + handle.process.once('error', (error) => { + if (handle.state !== 'stopping' && handle.state !== 'stopped') { + const reason = `process error: ${error.message}`; + handle.terminationReason = reason; + handle.state = 'failed'; + this.failedCircuits.add(handle.key); + this.emitHandleLifecycle(handle, 'failed', { reason }); + this.rejectPending(handle, new Error(`LSP server ${handle.language} failed`)); + if (!handle.process.pid) this.markClosed(handle); + void this.terminateHandle(handle, reason); + } + }); + handle.process.once('close', (code, signal) => { + handle.exitCode = code; + handle.exitSignal = signal; + this.markClosed(handle); + if (handle.state !== 'stopping' && handle.state !== 'stopped') { + handle.state = 'failed'; + handle.terminationReason ||= 'process closed unexpectedly'; + this.failedCircuits.add(handle.key); + this.emitHandleLifecycle(handle, 'failed', { + reason: handle.terminationReason, + exitCode: code, + exitSignal: signal, + }); + this.rejectPending(handle, new Error(`LSP server ${handle.language} disconnected`)); + this.releaseHandle(handle); + } + }); + } - serverProcess.on('exit', () => { - this.cleanup(language); - }); + private markClosed(handle: ServerHandle): void { + if (handle.closed) return; + handle.closed = true; + handle.resolveClose(); + } - // Initialize the server - await this.sendRequest(language, 'initialize', { + private async initializeHandle(handle: ServerHandle): Promise { + try { + await this.waitForSpawn(handle); + await this.sendRequest(handle, 'initialize', { processId: process.pid, - rootUri: `file://${projectPath}`, + rootUri: `file://${handle.projectPath}`, capabilities: { textDocument: { hover: { contentFormat: ['markdown', 'plaintext'] }, @@ -137,115 +235,255 @@ export class LSPLayer { }, }); - this.sendNotification(language, 'initialized', {}); - this.initialized.set(language, true); - + if (handle.state !== 'starting') throw new Error('LSP server stopped during initialize'); + this.sendNotification(handle, 'initialized', {}); + handle.state = 'ready'; + this.emitHandleLifecycle(handle, 'ready', { + initializeDurationMs: Date.now() - handle.startedAt, + }); return true; - } catch { - // LSP server not available - this is expected if the language server isn't installed - // Silently return false and fall back to non-LSP analysis + } catch (error) { + this.failedCircuits.add(handle.key); + const reason = + error instanceof Error ? `initialize failed: ${error.message}` : 'initialize failed'; + handle.state = 'failed'; + this.emitHandleLifecycle(handle, 'failed', { + reason, + initializeDurationMs: Date.now() - handle.startedAt, + }); + await this.terminateHandle( + handle, + reason + ); return false; } } - private handleServerData(language: string, data: Buffer): void { - let buffer = (this.buffers.get(language) || '') + data.toString(); - - while (true) { - const headerMatch = buffer.match(/Content-Length: (\d+)\r\n\r\n/); - if (!headerMatch) break; - - const contentLength = parseInt(headerMatch[1], 10); - const headerEnd = headerMatch.index! + headerMatch[0].length; + private waitForSpawn(handle: ServerHandle): Promise { + return new Promise((resolve, reject) => { + const onSpawn = (): void => { + cleanup(); + resolve(); + }; + const onError = (error: Error): void => { + cleanup(); + reject(error); + }; + const onClose = (): void => { + cleanup(); + reject(new Error('LSP server closed before spawn confirmation')); + }; + const cleanup = (): void => { + handle.process.off('spawn', onSpawn); + handle.process.off('error', onError); + handle.process.off('close', onClose); + }; + handle.process.once('spawn', onSpawn); + handle.process.once('error', onError); + handle.process.once('close', onClose); + }); + } - if (buffer.length < headerEnd + contentLength) break; + private handleServerData(handle: ServerHandle, data: Buffer): void { + handle.buffer = Buffer.concat([handle.buffer, data]); - const content = buffer.slice(headerEnd, headerEnd + contentLength); - buffer = buffer.slice(headerEnd + contentLength); + while (true) { + const headerEnd = handle.buffer.indexOf('\r\n\r\n'); + if (headerEnd < 0) return; + const header = handle.buffer.subarray(0, headerEnd).toString('ascii'); + const match = /(?:^|\r\n)Content-Length:\s*(\d+)/i.exec(header); + if (!match) { + handle.buffer = Buffer.alloc(0); + return; + } + const contentLength = Number(match[1]); + const bodyStart = headerEnd + 4; + if (handle.buffer.length < bodyStart + contentLength) return; + const body = handle.buffer.subarray(bodyStart, bodyStart + contentLength); + handle.buffer = handle.buffer.subarray(bodyStart + contentLength); try { - const message: LSPMessage = JSON.parse(content); - this.handleMessage(message); + this.handleMessage(handle, JSON.parse(body.toString('utf8')) as LSPMessage); } catch { - // Silently ignore malformed messages + // Malformed server messages are ignored without affecting another handle. } } - - this.buffers.set(language, buffer); } - private handleMessage(message: LSPMessage): void { - if (message.id !== undefined && this.pendingRequests.has(message.id)) { - const pending = this.pendingRequests.get(message.id)!; - this.pendingRequests.delete(message.id); - clearTimeout(pending.timeout); + private handleMessage(handle: ServerHandle, message: LSPMessage): void { + if (message.id === undefined) return; + const pending = handle.pendingRequests.get(message.id); + if (!pending) return; - if (message.error) { - pending.reject(new Error(message.error.message)); - } else { - pending.resolve(message.result); - } - } + handle.pendingRequests.delete(message.id); + clearTimeout(pending.timeout); + if (message.error) pending.reject(new Error(message.error.message)); + else pending.resolve(message.result); } - private sendRequest(language: string, method: string, params: unknown): Promise { + private sendRequest( + handle: ServerHandle, + method: string, + params: unknown, + timeoutMs = this.requestTimeoutMs + ): Promise { return new Promise((resolve, reject) => { const id = ++this.messageId; - const timeout = setTimeout(() => { - this.pendingRequests.delete(id); + handle.pendingRequests.delete(id); reject(new Error(`LSP request timeout: ${method}`)); - }, REQUEST_TIMEOUT_MS); - - this.pendingRequests.set(id, { resolve, reject, timeout }); - - const message: LSPMessage = { - jsonrpc: '2.0', - id, - method, - params, - }; + }, timeoutMs); + handle.pendingRequests.set(id, { resolve, reject, timeout }); - this.sendMessage(language, message); + if (!this.sendMessage(handle, { jsonrpc: '2.0', id, method, params })) { + clearTimeout(timeout); + handle.pendingRequests.delete(id); + reject(new Error(`LSP server ${handle.language} is not writable`)); + } }); } - private sendNotification(language: string, method: string, params: unknown): void { - const message: LSPMessage = { - jsonrpc: '2.0', - method, - params, - }; - this.sendMessage(language, message); + private sendNotification(handle: ServerHandle, method: string, params: unknown): boolean { + return this.sendMessage(handle, { jsonrpc: '2.0', method, params }); } - private sendMessage(language: string, message: LSPMessage): void { - const server = this.servers.get(language); - if (!server?.stdin?.writable) return; - + private sendMessage(handle: ServerHandle, message: LSPMessage): boolean { + const stdin = handle.process.stdin; + if (!stdin?.writable || stdin.destroyed) return false; const content = JSON.stringify(message); const header = `Content-Length: ${Buffer.byteLength(content)}\r\n\r\n`; + try { + stdin.write(header + content); + return true; + } catch { + return false; + } + } + + private rejectPending(handle: ServerHandle, error: Error): void { + for (const pending of handle.pendingRequests.values()) { + clearTimeout(pending.timeout); + pending.reject(error); + } + handle.pendingRequests.clear(); + } + private async terminateHandle( + handle: ServerHandle, + reason: string, + waitForNaturalExit = false + ): Promise { + if (handle.stopping) return handle.stopping; + if (handle.state === 'stopped' && handle.closed) return; + + handle.terminationReason = reason; + handle.state = 'stopping'; + this.emitHandleLifecycle(handle, 'stopping', { reason }); + handle.stopping = (async () => { + this.rejectPending(handle, new Error(`LSP server ${handle.language} terminated: ${reason}`)); + handle.process.stdin?.end(); + + if (!handle.closed) { + const exitedNaturally = + waitForNaturalExit && (await this.waitForClose(handle, this.terminationGraceMs)); + if (!exitedNaturally) { + this.signal(handle, 'SIGTERM'); + if (!(await this.waitForClose(handle, this.terminationGraceMs))) { + handle.forcedKill = true; + this.signal(handle, 'SIGKILL'); + await handle.closePromise; + } + } + } + + handle.state = 'stopped'; + this.emitHandleLifecycle(handle, 'stopped', { + reason, + exitCode: handle.exitCode, + exitSignal: handle.exitSignal, + forcedKill: handle.forcedKill, + }); + this.releaseHandle(handle); + })(); + return handle.stopping; + } + + private signal(handle: ServerHandle, signal: NodeJS.Signals): void { + if (handle.closed || !handle.process.pid) return; try { - server.stdin.write(header + content); + handle.process.kill(signal); } catch { - // Silently ignore send failures + // A concurrent process exit is equivalent to successful termination. } } - private cleanup(language: string): void { - this.servers.delete(language); - this.initialized.delete(language); - this.buffers.delete(language); + private waitForClose(handle: ServerHandle, timeoutMs: number): Promise { + if (handle.closed) return Promise.resolve(true); + return new Promise((resolve) => { + const timeout = setTimeout(() => resolve(false), timeoutMs); + handle.closePromise.then(() => { + clearTimeout(timeout); + resolve(true); + }); + }); + } + + private releaseHandle(handle: ServerHandle): void { + if (this.handles.get(handle.key) === handle) this.handles.delete(handle.key); + this.rejectPending(handle, new Error(`LSP server ${handle.language} released`)); + handle.buffer = Buffer.alloc(0); + handle.process.stdin?.removeAllListeners(); + handle.process.stdout?.removeAllListeners(); + handle.process.stderr?.removeAllListeners(); + handle.process.removeAllListeners(); + } - // Reject all pending requests for this language - for (const [id, pending] of this.pendingRequests) { - clearTimeout(pending.timeout); - pending.reject(new Error(`LSP server ${language} disconnected`)); - this.pendingRequests.delete(id); + private emitHandleLifecycle( + handle: ServerHandle, + state: LSPServerState, + details: Partial = {} + ): void { + this.emitLifecycle( + handle.language, + handle.projectPath, + state, + handle.pendingRequests.size, + { pid: handle.process.pid, ...details } + ); + } + + private emitLifecycle( + language: string, + projectPath: string, + state: LSPServerState, + pendingRequestCount: number, + details: Partial = {} + ): void { + if (!this.onLifecycleEvent) return; + const event: LSPLifecycleEvent = { + language, + projectHash: createHash('sha256').update(path.resolve(projectPath)).digest('hex').slice(0, 12), + state, + timestamp: Date.now(), + pendingRequestCount, + ...details, + }; + try { + this.onLifecycleEvent(event); + } catch { + // Observability must never change process ownership or fallback behavior. } } + private async readyHandle( + language: string, + projectPath: string + ): Promise { + if (!(await this.ensureServer(language, projectPath))) return undefined; + const handle = this.handles.get(this.serverKey(language, projectPath)); + return handle?.state === 'ready' ? handle : undefined; + } + async getTypeInfo( filePath: string, line: number, @@ -254,23 +492,20 @@ export class LSPLayer { ): Promise { const language = this.detectLanguage(filePath); if (!language) return null; - - const serverReady = await this.ensureServer(language, projectPath); - if (!serverReady) return null; + const handle = await this.readyHandle(language, projectPath); + if (!handle) return null; try { - const result = await this.sendRequest(language, 'textDocument/hover', { + const result = await this.sendRequest(handle, 'textDocument/hover', { textDocument: { uri: `file://${filePath}` }, position: { line: line - 1, character: column }, }); - if (result && typeof result === 'object' && 'contents' in result) { return this.parseHoverResult((result as { contents: unknown }).contents); } } catch { - // LSP request failed - return null to fall back to non-LSP analysis + // Fall back to the non-LSP analysis. } - return null; } @@ -282,17 +517,15 @@ export class LSPLayer { ): Promise { const language = this.detectLanguage(filePath); if (!language) return []; - - const serverReady = await this.ensureServer(language, projectPath); - if (!serverReady) return []; + const handle = await this.readyHandle(language, projectPath); + if (!handle) return []; try { - const result = await this.sendRequest(language, 'textDocument/references', { + const result = await this.sendRequest(handle, 'textDocument/references', { textDocument: { uri: `file://${filePath}` }, position: { line: line - 1, character: column }, context: { includeDeclaration: true }, }); - if (Array.isArray(result)) { return result.map((ref: { uri: string; range: { start: { line: number; character: number } } }) => ({ file: ref.uri.replace('file://', ''), @@ -301,9 +534,8 @@ export class LSPLayer { })); } } catch { - // LSP request failed - return empty array + // Fall back to an empty result. } - return []; } @@ -315,16 +547,14 @@ export class LSPLayer { ): Promise { const language = this.detectLanguage(filePath); if (!language) return null; - - const serverReady = await this.ensureServer(language, projectPath); - if (!serverReady) return null; + const handle = await this.readyHandle(language, projectPath); + if (!handle) return null; try { - const result = await this.sendRequest(language, 'textDocument/definition', { + const result = await this.sendRequest(handle, 'textDocument/definition', { textDocument: { uri: `file://${filePath}` }, position: { line: line - 1, character: column }, }); - if (Array.isArray(result) && result.length > 0) { const def = result[0] as { uri: string; range: { start: { line: number; character: number } } }; return { @@ -334,9 +564,8 @@ export class LSPLayer { }; } } catch { - // LSP request failed - return null + // Fall back to the non-LSP analysis. } - return null; } @@ -348,16 +577,14 @@ export class LSPLayer { ): Promise { const language = this.detectLanguage(filePath); if (!language) return []; - - const serverReady = await this.ensureServer(language, projectPath); - if (!serverReady) return []; + const handle = await this.readyHandle(language, projectPath); + if (!handle) return []; try { - const result = await this.sendRequest(language, 'textDocument/implementation', { + const result = await this.sendRequest(handle, 'textDocument/implementation', { textDocument: { uri: `file://${filePath}` }, position: { line: line - 1, character: column }, }); - if (Array.isArray(result)) { return result.map((impl: { uri: string; range: { start: { line: number; character: number } } }) => ({ file: impl.uri.replace('file://', ''), @@ -366,18 +593,15 @@ export class LSPLayer { })); } } catch { - // LSP request failed - return empty array + // Fall back to an empty result. } - return []; } private parseHoverResult(contents: unknown): TypeInfo { let text = ''; - - if (typeof contents === 'string') { - text = contents; - } else if (Array.isArray(contents)) { + if (typeof contents === 'string') text = contents; + else if (Array.isArray(contents)) { text = contents .map((c) => (typeof c === 'string' ? c : (c as { value?: string }).value || '')) .join('\n'); @@ -385,10 +609,8 @@ export class LSPLayer { text = (contents as { value?: string }).value || ''; } - // Extract type from markdown code blocks const codeMatch = text.match(/```\w*\n?([\s\S]*?)\n?```/); const typeText = codeMatch ? codeMatch[1] : text; - return { name: typeText.split('\n')[0] || 'unknown', fullType: typeText, @@ -397,30 +619,34 @@ export class LSPLayer { } async shutdown(): Promise { - const shutdownPromises: Promise[] = []; - - for (const [language] of this.servers) { - shutdownPromises.push( - (async () => { - try { - await this.sendRequest(language, 'shutdown', null); - this.sendNotification(language, 'exit', null); - } catch { - // Ignore shutdown errors - } - this.cleanup(language); - })() - ); - } + if (this.shuttingDown) return this.shuttingDown; + this.shuttingDown = (async () => { + const handles = [...this.handles.values()]; + await Promise.all(handles.map((handle) => this.shutdownHandle(handle))); + })(); + return this.shuttingDown; + } - await Promise.all(shutdownPromises); + private async shutdownHandle(handle: ServerHandle): Promise { + if (handle.stopping) return handle.stopping; + if (handle.state === 'ready') { + try { + await this.sendRequest(handle, 'shutdown', null, this.shutdownTimeoutMs); + this.sendNotification(handle, 'exit', null); + } catch { + // Process termination below is authoritative even if the protocol fails. + } + } + await this.terminateHandle(handle, 'layer shutdown', true); } isServerAvailable(language: string): boolean { - return this.initialized.get(language) === true; + return [...this.handles.values()].some( + (handle) => handle.language === language && handle.state === 'ready' + ); } getAvailableLanguages(): string[] { - return Object.keys(LSP_SERVER_CONFIGS); + return Object.keys(this.serverConfigs); } } From 328134f486692daa641fa0cf14f777ca5bbf86f6 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:06:18 -0300 Subject: [PATCH 06/39] fix: serialize trace writes across processes --- .../__tests__/runtimeStateService.test.ts | 23 ++++++ .../out/runtimeState/runtimeStateService.ts | 70 ++++++++++++++++++- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 50060b19..27a42cab 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -144,5 +144,28 @@ describe('HarnessRuntimeStateService', () => { expect(traces.filter((trace) => trace.event === 'concurrent.event').map((trace) => trace.data?.index)) .toEqual(Array.from({ length: 12 }, (_, index) => index)); expect((await service.getSession(session.id)).traceCount).toBe(traces.length); + expect(await fs.pathExists(path.join(sessionDir, 'trace.jsonl.lock'))).toBe(false); + }); + + it('recovers a stale cross-process trace lock', async () => { + const session = await service.createSession({ name: 'stale-lock' }); + const lockFile = path.join( + tempDir, + '.context', + 'runtime', + 'sessions', + session.id, + 'trace.jsonl.lock' + ); + await fs.writeFile(lockFile, '999999 2000-01-01T00:00:00.000Z\n', 'utf8'); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + await expect(service.appendTrace(session.id, { + level: 'info', + event: 'after.stale.lock', + message: 'continued', + })).resolves.toMatchObject({ event: 'after.stale.lock' }); + expect(await fs.pathExists(lockFile)).toBe(false); }); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index b80d2338..38ee6f97 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -9,6 +9,8 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import { randomUUID } from 'crypto'; +import { promises as nodeFs } from 'fs'; +import type { FileHandle } from 'fs/promises'; import { resolveRuntimeLayout, type RuntimeLayout } from '../../../../shared/fs/pathHelpers'; import { boundGenericTraceRecord, @@ -18,6 +20,68 @@ import { const traceWriteQueues = new Map>(); +function waitForLock(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +function isProcessAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +async function acquireTraceFileLock( + traceFile: string +): Promise<{ lockFile: string; handle: FileHandle; inode: bigint | number }> { + const lockFile = `${traceFile}.lock`; + const deadline = Date.now() + 10_000; + while (true) { + try { + const handle = await nodeFs.open(lockFile, 'wx'); + await handle.writeFile(`${process.pid} ${new Date().toISOString()}\n`, 'utf8'); + const stat = await handle.stat({ bigint: true }); + return { lockFile, handle, inode: stat.ino }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== 'EEXIST') throw error; + + const [age, ownerPid] = await Promise.all([ + nodeFs.stat(lockFile).then((stat) => Date.now() - stat.mtimeMs).catch(() => 0), + nodeFs.readFile(lockFile, 'utf8') + .then((value) => Number.parseInt(value.split(/\s/, 1)[0], 10)) + .catch(() => Number.NaN), + ]); + if (age > 60_000 && !isProcessAlive(ownerPid)) { + await nodeFs.unlink(lockFile).catch(() => undefined); + continue; + } + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for trace lock: ${path.basename(traceFile)}`); + } + await waitForLock(10 + Math.floor(Math.random() * 20)); + } + } +} + +async function withCrossProcessTraceLock(traceFile: string, operation: () => Promise): Promise { + const lock = await acquireTraceFileLock(traceFile); + try { + return await operation(); + } finally { + await lock.handle.close().catch(() => undefined); + const currentInode = await nodeFs.stat(lock.lockFile, { bigint: true }) + .then((stat) => stat.ino) + .catch(() => undefined); + if (currentInode === lock.inode) { + await nodeFs.unlink(lock.lockFile).catch(() => undefined); + } + } +} + async function withTraceWriteLock(key: string, operation: () => Promise): Promise { const previous = traceWriteQueues.get(key) ?? Promise.resolve(); let release!: () => void; @@ -26,7 +90,7 @@ async function withTraceWriteLock(key: string, operation: () => Promise): traceWriteQueues.set(key, tail); await previous.catch(() => undefined); try { - return await operation(); + return await withCrossProcessTraceLock(key, operation); } finally { release(); if (traceWriteQueues.get(key) === tail) { @@ -280,6 +344,10 @@ export class HarnessRuntimeStateService { } private async recordTrace(sessionId: string, trace: HarnessTraceRecord): Promise { + // Preserve the established missing/corrupt-session error contract before creating a lock file. + if (!fs.pathExistsSync(this.sessionFile(sessionId))) { + throw new Error(`Harness session not found: ${sessionId}`); + } return withTraceWriteLock(this.traceFile(sessionId), async () => { const session = await this.readSession(sessionId); const boundedTrace = boundGenericTraceRecord(trace, loadGenericTraceEventMaxBytes(this.repoPath)); From 209552d5c9cf862aa5d24aae3616afebbf69c22d Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:11:09 -0300 Subject: [PATCH 07/39] fix: bound cache and persistent retention --- CHANGELOG.md | 5 + README.md | 2 +- .../docs/en/concepts/harness-runtime.md | 13 +- .../docs/en/reference/context-layout.md | 7 +- .../docs/pt-br/concepts/harness-runtime.md | 13 +- .../docs/pt-br/reference/context-layout.md | 7 +- .../__tests__/runtimeStateService.test.ts | 40 +++++ .../out/runtimeState/runtimeStateService.ts | 67 +++++++-- .../semantic/__tests__/cacheRetention.test.ts | 52 +++++++ .../semantic/__tests__/contextCache.test.ts | 24 +++ .../adapters/out/semantic/codebaseAnalyzer.ts | 4 +- .../adapters/out/semantic/contextBuilder.ts | 63 +++++++- .../adapters/out/semantic/contextCache.ts | 71 ++++++--- .../semantic/treeSitter/treeSitterLayer.ts | 33 +++- src/harness/application/index.ts | 1 + .../__tests__/runtimeRetentionConfig.test.ts | 23 +++ src/harness/application/retention/index.ts | 1 + .../retention/runtimeRetentionConfig.ts | 118 +++++++++++++++ src/harness/domain/index.ts | 1 + .../__tests__/boundedLruCache.test.ts | 39 +++++ .../domain/retention/boundedLruCache.ts | 141 ++++++++++++++++++ src/harness/domain/retention/index.ts | 1 + .../shared/__tests__/hookSessionStore.test.ts | 47 ++++++ src/integrations/shared/hookSessionStore.ts | 70 ++++++++- src/integrations/shared/index.ts | 2 + .../logging/__tests__/actionLogger.test.ts | 4 +- src/mcp/logging/actionLogger.ts | 35 ++++- src/mcp/server/mcpServer.ts | 4 +- src/shared/fs/pathHelpers.ts | 7 + 29 files changed, 828 insertions(+), 67 deletions(-) create mode 100644 src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts create mode 100644 src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts create mode 100644 src/harness/application/retention/index.ts create mode 100644 src/harness/application/retention/runtimeRetentionConfig.ts create mode 100644 src/harness/domain/retention/__tests__/boundedLruCache.test.ts create mode 100644 src/harness/domain/retention/boundedLruCache.ts create mode 100644 src/harness/domain/retention/index.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 242a3b11..0c3faffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, and safe runtime configuration clamps. +- Moved checkpoint payload history from `session.json` into individual checkpoint records with legacy dual-read and lazy migration. + ## [1.1.1] - 2026-06-27 ### Fixed diff --git a/README.md b/README.md index 73e31c73..53ba4761 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ One `.context/` directory stores durable project knowledge and workflow state. ├── agents/ # Agent playbooks ├── skills/ # On-demand expertise guides ├── plans/ # Structured PREVC plans and execution tracking -├── config/ # Authored config: policy.json and sensors.json (version-controlled) +├── config/ # Authored config: policy.json, sensors.json, runtime.json (version-controlled) └── runtime/ # Generated state (gitignored): ├── sessions/ # one folder per session: session.json, trace.jsonl, artifacts/ ├── workflows/ # PREVC state (prevc.json), plan tracking, collaboration records diff --git a/docs/src/content/docs/en/concepts/harness-runtime.md b/docs/src/content/docs/en/concepts/harness-runtime.md index 0ed921d4..a424b095 100644 --- a/docs/src/content/docs/en/concepts/harness-runtime.md +++ b/docs/src/content/docs/en/concepts/harness-runtime.md @@ -41,15 +41,18 @@ Each session owns a folder under `.context/runtime/sessions//`: └── / ├── session.json # the session record ├── trace.jsonl # append-only event log (one JSON per line) - └── artifacts/ - └── .json + ├── artifacts/ + │ └── .json + └── checkpoints/ + └── .json ``` | Path | What it holds | | --- | --- | -| `.context/runtime/sessions//session.json` | The session record — status, timestamps, activity counters, and inline checkpoints | +| `.context/runtime/sessions//session.json` | The bounded session summary — status, timestamps, counters, and latest checkpoint identity | | `.context/runtime/sessions//trace.jsonl` | Append-only event log, one JSON object per line | | `.context/runtime/sessions//artifacts/.json` | One file per recorded artifact | +| `.context/runtime/sessions//checkpoints/.json` | One bounded record per checkpoint | ::: caution Everything under `.context/runtime/` is regenerated as needed and is gitignored. Don't hand-edit these files — go through the harness so counters and the trace stay consistent. @@ -77,7 +80,7 @@ The session record is stored at `.context/runtime/sessions//session.json`: "checkpointCount": 1, "lastTraceAt": "2026-06-05T...", "lastCheckpointAt": "2026-06-05T...", - "checkpoints": [], + "lastCheckpointId": "ckpt_...", "metadata": {} } ``` @@ -157,7 +160,7 @@ Add artifacts with the `harness` tool's `addArtifact` action and read them with A **checkpoint** is a named waypoint within a session. It bundles a set of artifacts and optional state so you have a meaningful, recoverable point to return to — useful between PREVC phases, before a risky step, or whenever you want a labeled snapshot. -Checkpoints are stored **inline** in the session record's `checkpoints` array (not as separate files): +Checkpoints are stored as individual records under `.context/runtime/sessions//checkpoints/`. `session.json` retains only the count and latest checkpoint identity, so checkpoint history does not make every session update progressively larger. Legacy inline checkpoints remain readable and migrate on the next checkpoint write. ```json { diff --git a/docs/src/content/docs/en/reference/context-layout.md b/docs/src/content/docs/en/reference/context-layout.md index c4802641..1488fad5 100644 --- a/docs/src/content/docs/en/reference/context-layout.md +++ b/docs/src/content/docs/en/reference/context-layout.md @@ -28,7 +28,8 @@ The rule of thumb: if a human wrote it, it is probably versioned and committed. ├── config.json # versioned — generation config ├── config/ │ ├── policy.json # versioned — policy rules -│ └── sensors.json # versioned — sensor catalog +│ ├── sensors.json # versioned — sensor catalog +│ └── runtime.json # versioned — retention safety limits ├── docs/ # versioned — documentation + semantic KB ├── agents/ # versioned — agent playbooks ├── skills/ # versioned — on-demand expertise @@ -51,6 +52,7 @@ These files govern how the harness behaves. You write them, you review them, and | `.context/config/` | versioned | Yes | The authored config directory. | | `.context/config/policy.json` | versioned | Yes | Harness [policy](/concepts/policies/) rules and approval constraints. | | `.context/config/sensors.json` | versioned | Yes | Project [sensor](/concepts/sensors/) catalog plus detected stack info. Generated at bootstrap, then customized by the team. | +| `.context/config/runtime.json` | versioned | Yes | Versioned retention limits for traces, sessions, replays, datasets, checkpoints, bindings, and caches. Unsafe values are clamped to absolute ceilings. | ## Durable project knowledge @@ -80,9 +82,10 @@ One folder per [harness session](/concepts/harness-runtime/), holding its record | Path | Classification | Git-tracked | Purpose | | --- | --- | --- | --- | | `.context/runtime/sessions/` | runtime | No | Root for all session state. | -| `.context/runtime/sessions//session.json` | runtime | No | The session record (status, counters, checkpoints). | +| `.context/runtime/sessions//session.json` | runtime | No | The bounded session summary (status, counters, latest checkpoint). | | `.context/runtime/sessions//trace.jsonl` | runtime | No | Append-only event log, one JSON object per line. | | `.context/runtime/sessions//artifacts/.json` | runtime | No | Individual artifact records produced during the session. | +| `.context/runtime/sessions//checkpoints/.json` | runtime | No | Individual checkpoint records produced during the session. | ### Workflows diff --git a/docs/src/content/docs/pt-br/concepts/harness-runtime.md b/docs/src/content/docs/pt-br/concepts/harness-runtime.md index 16409af2..2ecb3eef 100644 --- a/docs/src/content/docs/pt-br/concepts/harness-runtime.md +++ b/docs/src/content/docs/pt-br/concepts/harness-runtime.md @@ -41,15 +41,18 @@ Cada session é dona de uma pasta em `.context/runtime/sessions//`: └── / ├── session.json # o registro da session ├── trace.jsonl # log de eventos append-only (um JSON por linha) - └── artifacts/ - └── .json + ├── artifacts/ + │ └── .json + └── checkpoints/ + └── .json ``` | Caminho | O que contém | | --- | --- | -| `.context/runtime/sessions//session.json` | O registro da session — status, timestamps, contadores de atividade e checkpoints inline | +| `.context/runtime/sessions//session.json` | O resumo limitado da session — status, timestamps, contadores e identidade do checkpoint mais recente | | `.context/runtime/sessions//trace.jsonl` | Log de eventos append-only, um objeto JSON por linha | | `.context/runtime/sessions//artifacts/.json` | Um arquivo por artifact registrado | +| `.context/runtime/sessions//checkpoints/.json` | Um registro limitado por checkpoint | ::: caution Tudo em `.context/runtime/` é regenerado conforme necessário e está no gitignore. Não edite esses arquivos manualmente — passe pelo harness para que os contadores e o trace permaneçam consistentes. @@ -77,7 +80,7 @@ O registro da session é armazenado em `.context/runtime/sessions//session.j "checkpointCount": 1, "lastTraceAt": "2026-06-05T...", "lastCheckpointAt": "2026-06-05T...", - "checkpoints": [], + "lastCheckpointId": "ckpt_...", "metadata": {} } ``` @@ -157,7 +160,7 @@ Adicione artifacts com a action `addArtifact` da tool `harness` e leia-os com `l Um **checkpoint** é um marco nomeado dentro de uma session. Ele agrupa um conjunto de artifacts e estado opcional, dando a você um ponto significativo e recuperável para o qual voltar — útil entre fases PREVC, antes de um passo arriscado ou sempre que você quiser um snapshot rotulado. -Checkpoints são armazenados **inline** no array `checkpoints` do registro da session (não como arquivos separados): +Checkpoints são armazenados como registros individuais em `.context/runtime/sessions//checkpoints/`. O `session.json` mantém apenas o contador e a identidade do checkpoint mais recente, evitando que o histórico torne cada atualização da session progressivamente maior. Checkpoints legados inline continuam legíveis e são migrados na próxima gravação. ```json { diff --git a/docs/src/content/docs/pt-br/reference/context-layout.md b/docs/src/content/docs/pt-br/reference/context-layout.md index 6c20226c..ebe1abbb 100644 --- a/docs/src/content/docs/pt-br/reference/context-layout.md +++ b/docs/src/content/docs/pt-br/reference/context-layout.md @@ -28,7 +28,8 @@ A regra de bolso: se um humano escreveu, provavelmente é versioned e fica no co ├── config.json # versioned — config de geração ├── config/ │ ├── policy.json # versioned — regras de policy -│ └── sensors.json # versioned — catálogo de sensores +│ ├── sensors.json # versioned — catálogo de sensores +│ └── runtime.json # versioned — limites seguros de retenção ├── docs/ # versioned — documentação + KB semântica ├── agents/ # versioned — playbooks de agentes ├── skills/ # versioned — expertise sob demanda @@ -51,6 +52,7 @@ Esses arquivos governam como o harness se comporta. Você os escreve, os revisa | `.context/config/` | versioned | Sim | O diretório de config autorada. | | `.context/config/policy.json` | versioned | Sim | Regras de [policy](/pt-br/concepts/policies/) do harness e restrições de aprovação. | | `.context/config/sensors.json` | versioned | Sim | Catálogo de [sensores](/pt-br/concepts/sensors/) do projeto mais informações da stack detectada. Gerado no bootstrap e depois customizado pelo time. | +| `.context/config/runtime.json` | versioned | Sim | Limites versionados de retenção para traces, sessions, replays, datasets, checkpoints, bindings e caches. Valores inseguros são limitados por tetos absolutos. | ## Conhecimento durável do projeto @@ -80,9 +82,10 @@ Uma pasta por [session do harness](/pt-br/concepts/harness-runtime/), guardando | Caminho | Classificação | Rastreado | Propósito | | --- | --- | --- | --- | | `.context/runtime/sessions/` | runtime | Não | Raiz de todo o estado de sessions. | -| `.context/runtime/sessions//session.json` | runtime | Não | O registro da session (status, contadores, checkpoints). | +| `.context/runtime/sessions//session.json` | runtime | Não | O resumo limitado da session (status, contadores e checkpoint mais recente). | | `.context/runtime/sessions//trace.jsonl` | runtime | Não | Log de eventos append-only, um objeto JSON por linha. | | `.context/runtime/sessions//artifacts/.json` | runtime | Não | Registros de artefatos individuais produzidos durante a session. | +| `.context/runtime/sessions//checkpoints/.json` | runtime | Não | Registros individuais de checkpoints produzidos durante a session. | ### Workflows diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 1ace38ce..e96d9699 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -78,6 +78,46 @@ describe('HarnessRuntimeStateService', () => { expect(await fs.pathExists(sessionFile)).toBe(true); expect(await fs.pathExists(traceFile)).toBe(true); expect(await fs.pathExists(artifactFile)).toBe(true); + const sessionDocument = await fs.readJson(sessionFile); + expect(sessionDocument.checkpoints).toBeUndefined(); + expect(sessionDocument.lastCheckpointId).toBe(checkpointed.checkpoints[0].id); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'checkpoints', `${checkpointed.checkpoints[0].id}.json`))).toBe(true); + }); + + it('reads legacy inline checkpoints and migrates them losslessly on the next write', async () => { + const session = await service.createSession({ name: 'legacy' }); + const file = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'session.json'); + const document = await fs.readJson(file); + document.checkpoints = [{ + id: 'legacy-checkpoint', + note: 'legacy note', + data: { retained: true }, + artifactIds: ['artifact-1'], + createdAt: '2020-01-01T00:00:00.000Z', + }]; + document.checkpointCount = 1; + await fs.writeJson(file, document); + + const before = await service.listCheckpoints(session.id); + expect(before.map(item => item.id)).toEqual(['legacy-checkpoint']); + await service.checkpointSession(session.id, { note: 'new checkpoint' }); + const after = await service.listCheckpoints(session.id); + expect(after).toHaveLength(2); + expect(after.find(item => item.id === 'legacy-checkpoint')?.data).toEqual({ retained: true }); + expect((await fs.readJson(file)).checkpoints).toBeUndefined(); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'checkpoints', 'legacy-checkpoint.json'))).toBe(true); + }); + + it('enforces checkpoint payload and artifact limits from safe runtime config', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + version: 1, + checkpoints: { maxDataBytes: 1024, maxArtifactIds: 1 }, + }); + const session = await service.createSession({ name: 'bounded' }); + await expect(service.checkpointSession(session.id, { data: 'x'.repeat(2048) })) + .rejects.toThrow('Checkpoint data exceeds'); + await expect(service.checkpointSession(session.id, { artifactIds: ['a', 'b'] })) + .rejects.toThrow('Checkpoint artifactIds exceed'); }); it('lists sessions sorted by recency', async () => { diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index a23622e2..36b0edf2 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -10,6 +10,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import { randomUUID } from 'crypto'; import { resolveRuntimeLayout, type RuntimeLayout } from '../../../../shared/fs/pathHelpers'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; export type HarnessSessionStatus = 'active' | 'paused' | 'completed' | 'failed'; export type HarnessTraceLevel = 'debug' | 'info' | 'warn' | 'error'; @@ -39,6 +40,7 @@ export interface HarnessSessionRecord { failedAt?: string; lastTraceAt?: string; lastCheckpointAt?: string; + lastCheckpointId?: string; traceCount: number; artifactCount: number; checkpointCount: number; @@ -153,6 +155,10 @@ export class HarnessRuntimeStateService { return this.layout.sessionArtifactFile(sessionId, artifactId); } + private checkpointFile(sessionId: string, checkpointId: string): string { + return this.layout.sessionCheckpointFile(sessionId, checkpointId); + } + private async ensureSessionDir(sessionId: string): Promise { await fs.ensureDir(this.layout.sessionDir(sessionId)); } @@ -167,7 +173,8 @@ export class HarnessRuntimeStateService { throw new Error(`Harness session not found: ${sessionId}`); } - return fs.readJson(file) as Promise; + const session = await fs.readJson(file) as HarnessSessionRecord; + return { ...session, checkpoints: Array.isArray(session.checkpoints) ? session.checkpoints : [] }; } private async saveSession(session: HarnessSessionRecord): Promise { @@ -175,7 +182,14 @@ export class HarnessRuntimeStateService { const sessionFile = this.sessionFile(session.id); const tmpFile = `${sessionFile}.${process.pid}.${randomUUID()}.tmp`; try { - await fs.writeJson(tmpFile, session, { spaces: 2 }); + // Preserve legacy inline records until checkpointSession has copied them. + // New-format sessions carry an empty in-memory array and persist only the summary. + if (session.checkpoints.length > 0) { + await fs.writeJson(tmpFile, session, { spaces: 2 }); + } else { + const { checkpoints: _checkpointPayloads, ...document } = session; + await fs.writeJson(tmpFile, document, { spaces: 2 }); + } await fs.rename(tmpFile, sessionFile); } finally { await fs.remove(tmpFile).catch(() => undefined); @@ -227,7 +241,7 @@ export class HarnessRuntimeStateService { data: input.metadata ? { metadata: input.metadata } : undefined, }); - return this.readSession(session.id); + return this.getSession(session.id); } async listSessions(): Promise { @@ -251,7 +265,9 @@ export class HarnessRuntimeStateService { } async getSession(sessionId: string): Promise { - return this.readSession(sessionId); + const session = await this.readSession(sessionId); + session.checkpoints = await this.listCheckpoints(sessionId); + return session; } async appendTrace(sessionId: string, input: AppendTraceInput): Promise { @@ -308,7 +324,20 @@ export class HarnessRuntimeStateService { async listCheckpoints(sessionId: string): Promise { const session = await this.readSession(sessionId); - return [...session.checkpoints].sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + const checkpoints = new Map(); + for (const checkpoint of session.checkpoints ?? []) checkpoints.set(checkpoint.id, checkpoint); + const dir = this.layout.sessionCheckpointsDir(sessionId); + if (await fs.pathExists(dir)) { + for (const entry of (await fs.readdir(dir)).filter((name) => name.endsWith('.json'))) { + try { + const checkpoint = await fs.readJson(path.join(dir, entry)) as HarnessSessionCheckpoint; + checkpoints.set(checkpoint.id, checkpoint); + } catch { + // Preserve availability when one record is corrupt or partially written. + } + } + } + return [...checkpoints.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)); } async listArtifacts(sessionId: string): Promise { @@ -354,6 +383,14 @@ export class HarnessRuntimeStateService { async checkpointSession(sessionId: string, input: CheckpointInput = {}): Promise { const session = await this.readSession(sessionId); + const { config } = await loadRuntimeRetentionConfig(this.repoPath); + const dataBytes = input.data === undefined ? 0 : Buffer.byteLength(JSON.stringify(input.data)); + if (dataBytes > config.checkpoints.maxDataBytes) { + throw new Error(`Checkpoint data exceeds ${config.checkpoints.maxDataBytes} byte limit`); + } + if ((input.artifactIds?.length ?? 0) > config.checkpoints.maxArtifactIds) { + throw new Error(`Checkpoint artifactIds exceed ${config.checkpoints.maxArtifactIds} item limit`); + } const createdAt = nowIso(); const checkpoint: HarnessSessionCheckpoint = { id: randomUUID(), @@ -363,9 +400,21 @@ export class HarnessRuntimeStateService { createdAt, }; - session.checkpoints.push(checkpoint); - session.checkpointCount = session.checkpoints.length; + // Lazy, lossless migration: legacy inline records are copied before the + // next new-write strips the embedded array from session.json. + for (const legacy of session.checkpoints ?? []) { + const file = this.checkpointFile(sessionId, legacy.id); + if (!await fs.pathExists(file)) { + await fs.ensureDir(path.dirname(file)); + await fs.writeJson(file, legacy, { spaces: 2 }); + } + } + await fs.ensureDir(this.layout.sessionCheckpointsDir(sessionId)); + await fs.writeJson(this.checkpointFile(sessionId, checkpoint.id), checkpoint, { spaces: 2 }); + session.checkpointCount = (await this.listCheckpoints(sessionId)).length; + session.checkpoints = []; session.lastCheckpointAt = createdAt; + session.lastCheckpointId = checkpoint.id; session.updatedAt = createdAt; session.status = input.pause ? 'paused' : session.status; @@ -380,11 +429,11 @@ export class HarnessRuntimeStateService { data: { checkpointId: checkpoint.id, artifactIds: checkpoint.artifactIds, - payload: input.data, + payloadBytes: dataBytes, }, }); - return this.readSession(sessionId); + return this.getSession(sessionId); } async resumeSession(sessionId: string): Promise { diff --git a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts new file mode 100644 index 00000000..39947345 --- /dev/null +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -0,0 +1,52 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; +import { SemanticContextBuilder } from '../contextBuilder'; +import { TreeSitterLayer } from '../treeSitter/treeSitterLayer'; + +const emptyContext = { + symbols: { classes: [], interfaces: [], functions: [], types: [], enums: [] }, + dependencies: { graph: new Map(), reverseGraph: new Map() }, + architecture: { layers: [], patterns: [], entryPoints: [], publicAPI: [] }, + stats: { totalFiles: 0, totalSymbols: 0, languageBreakdown: {}, analysisTimeMs: 0 }, +}; + +describe('semantic cache retention', () => { + let repo: string; + beforeEach(async () => { + repo = await fs.mkdtemp(path.join(os.tmpdir(), 'semantic-retention-')); + await fs.outputFile(path.join(repo, 'src', 'index.ts'), 'export const value = 1;'); + }); + afterEach(async () => fs.remove(repo)); + + it('does not retain FileAnalysis when cacheEnabled is false', async () => { + const layer = new TreeSitterLayer({ cacheEnabled: false }); + await layer.analyzeFile(path.join(repo, 'src', 'index.ts')); + expect(layer.cacheSize).toBe(0); + layer.dispose(); + }); + + it('invalidates semantic context when the repository fingerprint changes', async () => { + const builder = new SemanticContextBuilder(); + const analyze = jest.fn().mockResolvedValue(emptyContext); + (builder as any).analyzer.analyze = analyze; + await builder.analyze(repo); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(1); + await new Promise(resolve => setTimeout(resolve, 10)); + await fs.writeFile(path.join(repo, 'src', 'index.ts'), 'export const value = 22;'); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(2); + await builder.shutdown(); + }); + + it('does not retain SemanticContext when cacheEnabled is false', async () => { + const builder = new SemanticContextBuilder({ cacheEnabled: false }); + const analyze = jest.fn().mockResolvedValue(emptyContext); + (builder as any).analyzer.analyze = analyze; + await builder.analyze(repo); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(2); + await builder.shutdown(); + }); +}); diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index cf878769..166a3805 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -58,6 +58,13 @@ describe('ContextCache', () => { }); describe('TTL expiration', () => { + it('proactively sweeps expired entries', async () => { + const cache = new ContextCache({ ttlMs: 20, sweepIntervalMs: 5 }); + await cache.set(tempDir, 'compact', 'content'); + await new Promise(resolve => setTimeout(resolve, 40)); + expect(cache.size).toBe(0); + cache.dispose(); + }); it('should expire entries after TTL', async () => { // Create cache with very short TTL const cache = new ContextCache({ ttlMs: 50 }); @@ -143,6 +150,23 @@ describe('ContextCache', () => { }); describe('overwrite behavior', () => { + it('evicts least recently used contexts over the entry limit', async () => { + const cache = new ContextCache({ maxEntries: 2 }); + await cache.set(tempDir, 'compact', 'a'); + await cache.set(tempDir, 'documentation', 'b'); + await cache.get(tempDir, 'compact'); + await cache.set(tempDir, 'plan', 'c'); + expect(await cache.get(tempDir, 'documentation')).toBeNull(); + expect(await cache.get(tempDir, 'compact')).toBe('a'); + cache.dispose(); + }); + + it('does not retain a single entry larger than the byte budget', async () => { + const cache = new ContextCache({ maxBytes: 32 }); + await cache.set(tempDir, 'compact', 'x'.repeat(100)); + expect(cache.size).toBe(0); + cache.dispose(); + }); it('should overwrite existing entries', async () => { const cache = new ContextCache(); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 05b12438..49be7e6c 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -44,8 +44,8 @@ export class CodebaseAnalyzer { private options: Required; constructor(options: AnalyzerOptions = {}) { - this.treeSitter = new TreeSitterLayer(); this.options = { ...DEFAULT_OPTIONS, ...options }; + this.treeSitter = new TreeSitterLayer({ cacheEnabled: this.options.cacheEnabled }); // Create LSPLayer if LSP mode is enabled if (this.options.useLSP) { @@ -61,6 +61,7 @@ export class CodebaseAnalyzer { // 2. Analyze with Tree-sitter const fileAnalyses = await this.analyzeFiles(files); + this.treeSitter.retainOnly?.(files); // 3. Build base context const context = this.buildBaseContext(fileAnalyses, projectPath); @@ -596,6 +597,7 @@ export class CodebaseAnalyzer { * Shutdown LSP servers gracefully */ async shutdown(): Promise { + this.treeSitter.dispose?.(); if (this.lspLayer) { await this.lspLayer.shutdown(); } diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index d07e2ab3..2a3011fd 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -6,6 +6,9 @@ */ import * as path from 'path'; +import * as fs from 'fs/promises'; +import { createHash } from 'crypto'; +import { glob } from 'glob'; import { CodebaseAnalyzer } from './codebaseAnalyzer'; import type { SemanticContext, @@ -25,6 +28,8 @@ export interface ContextBuilderOptions extends AnalyzerOptions { includeSignatures?: boolean; /** Maximum total context length (chars) */ maxContextLength?: number; + /** Maximum estimated bytes retained by the single semantic context cache */ + semanticCacheMaxBytes?: number; } export type ContextFormat = 'documentation' | 'playbook' | 'plan' | 'compact'; @@ -40,6 +45,7 @@ const DEFAULT_OPTIONS: Required = { includeDocumentation: true, includeSignatures: true, maxContextLength: 32000, + semanticCacheMaxBytes: 64 * 1024 * 1024, }; export class SemanticContextBuilder { @@ -47,6 +53,7 @@ export class SemanticContextBuilder { private options: Required; private cachedContext: SemanticContext | null = null; private cachedProjectPath: string | null = null; + private cachedFingerprint: string | null = null; constructor(options: ContextBuilderOptions = {}) { this.options = { ...DEFAULT_OPTIONS, ...options }; @@ -57,13 +64,24 @@ export class SemanticContextBuilder { * Analyze the codebase and cache the result */ async analyze(projectPath: string): Promise { - if (this.cachedContext && this.cachedProjectPath === projectPath) { + const normalizedProjectPath = path.resolve(projectPath); + const fingerprint = await this.computeProjectFingerprint(normalizedProjectPath); + if ( + this.options.cacheEnabled && + this.cachedContext && + this.cachedProjectPath === normalizedProjectPath && + this.cachedFingerprint === fingerprint + ) { return this.cachedContext; } - this.cachedContext = await this.analyzer.analyze(projectPath); - this.cachedProjectPath = projectPath; - return this.cachedContext; + const context = await this.analyzer.analyze(normalizedProjectPath); + if (this.options.cacheEnabled && this.estimateSemanticContextBytes(context) <= this.options.semanticCacheMaxBytes) { + this.cachedContext = context; + this.cachedProjectPath = normalizedProjectPath; + this.cachedFingerprint = fingerprint; + } + return context; } /** @@ -807,6 +825,7 @@ export class SemanticContextBuilder { clearCache(): void { this.cachedContext = null; this.cachedProjectPath = null; + this.cachedFingerprint = null; this.analyzer.clearCache(); } @@ -814,6 +833,42 @@ export class SemanticContextBuilder { * Shutdown analyzer (cleanup LSP servers if enabled) */ async shutdown(): Promise { + this.clearCache(); await this.analyzer.shutdown(); } + + private async computeProjectFingerprint(projectPath: string): Promise { + const extensions = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go']; + const files = await glob(`**/*.{${extensions.join(',')}}`, { + cwd: projectPath, + absolute: true, + nodir: true, + ignore: this.options.exclude.map((entry) => `**/${entry}/**`), + }); + const hash = createHash('sha256'); + for (const file of files.sort().slice(0, this.options.maxFiles)) { + try { + const stat = await fs.stat(file); + hash.update(`${path.relative(projectPath, file)}:${stat.size}:${stat.mtimeMs}\n`); + } catch { + hash.update(`${path.relative(projectPath, file)}:missing\n`); + } + } + return hash.digest('hex'); + } + + private estimateSemanticContextBytes(context: SemanticContext): number { + let bytes = Buffer.byteLength(JSON.stringify({ + symbols: context.symbols, + architecture: context.architecture, + stats: context.stats, + })); + for (const [file, dependencies] of context.dependencies.graph) { + bytes += Buffer.byteLength(file) + dependencies.reduce((sum, dependency) => sum + Buffer.byteLength(dependency), 0); + } + for (const [file, dependants] of context.dependencies.reverseGraph) { + bytes += Buffer.byteLength(file) + dependants.reduce((sum, dependant) => sum + Buffer.byteLength(dependant), 0); + } + return bytes; + } } diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index e69334ea..c44d0fbf 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -13,6 +13,9 @@ import * as fs from 'fs-extra'; import * as path from 'path'; +import { createHash } from 'crypto'; +import { glob } from 'glob'; +import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; /** * A cached context entry with metadata for invalidation. @@ -20,8 +23,6 @@ import * as path from 'path'; interface CacheEntry { /** The cached context string */ content: string; - /** Timestamp when this entry was created */ - createdAt: number; /** Modification time hash of source directories at cache time */ mtimeHash: string; } @@ -31,19 +32,34 @@ export interface ContextCacheOptions { ttlMs?: number; /** Directories to monitor for changes (relative to repo root) */ watchDirs?: string[]; + /** Maximum cached contexts (default: 16) */ + maxEntries?: number; + /** Estimated UTF-8 byte ceiling (default: 32 MiB) */ + maxBytes?: number; + /** Proactive expiration sweep interval */ + sweepIntervalMs?: number; } const DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes const DEFAULT_WATCH_DIRS = ['src', '.context', 'lib', 'packages']; +const DEFAULT_MAX_ENTRIES = 16; +const DEFAULT_MAX_BYTES = 32 * 1024 * 1024; export class ContextCache { - private readonly cache = new Map(); + private readonly cache: BoundedLruCache; private readonly ttlMs: number; private readonly watchDirs: string[]; constructor(options: ContextCacheOptions = {}) { this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; this.watchDirs = options.watchDirs ?? DEFAULT_WATCH_DIRS; + this.cache = new BoundedLruCache({ + maxEntries: options.maxEntries ?? DEFAULT_MAX_ENTRIES, + maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES, + ttlMs: this.ttlMs, + sweepIntervalMs: options.sweepIntervalMs, + estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + Buffer.byteLength(entry.mtimeHash), + }); } /** @@ -53,20 +69,14 @@ export class ContextCache { * @param contextType - Type of context (e.g., 'documentation', 'compact', 'full') * @returns Cached context string or null */ - async get(repoPath: string, contextType: string): Promise { - const key = this.buildKey(repoPath, contextType); + async get(repoPath: string, contextType: string, keyOptions?: unknown): Promise { + const key = this.buildKey(repoPath, contextType, keyOptions); const entry = this.cache.get(key); if (!entry) { return null; } - // Check TTL expiration - if (Date.now() - entry.createdAt > this.ttlMs) { - this.cache.delete(key); - return null; - } - // Check directory mtime invalidation const currentMtimeHash = await this.computeMtimeHash(repoPath); if (currentMtimeHash !== entry.mtimeHash) { @@ -84,13 +94,12 @@ export class ContextCache { * @param contextType - Type of context * @param content - The context string to cache */ - async set(repoPath: string, contextType: string, content: string): Promise { - const key = this.buildKey(repoPath, contextType); + async set(repoPath: string, contextType: string, content: string, keyOptions?: unknown): Promise { + const key = this.buildKey(repoPath, contextType, keyOptions); const mtimeHash = await this.computeMtimeHash(repoPath); this.cache.set(key, { content, - createdAt: Date.now(), mtimeHash, }); } @@ -114,6 +123,15 @@ export class ContextCache { this.cache.clear(); } + /** Stop proactive sweeping and release all entries. */ + dispose(): void { + this.cache.dispose(); + } + + metrics(): BoundedLruCacheMetrics { + return this.cache.metrics(); + } + /** * Get the number of cached entries (for monitoring/debugging). */ @@ -124,8 +142,9 @@ export class ContextCache { /** * Build a unique cache key from repo path and context type. */ - private buildKey(repoPath: string, contextType: string): string { - return `${this.normalizeRepoPath(repoPath)}:${contextType}`; + private buildKey(repoPath: string, contextType: string, keyOptions?: unknown): string { + const optionsKey = keyOptions === undefined ? '' : `:${JSON.stringify(keyOptions)}`; + return `${this.normalizeRepoPath(repoPath)}:${contextType}${optionsKey}`; } /** @@ -141,19 +160,27 @@ export class ContextCache { * of whether source files have changed. */ private async computeMtimeHash(repoPath: string): Promise { - const mtimes: number[] = []; + const hash = createHash('sha256'); for (const dir of this.watchDirs) { const dirPath = path.join(repoPath, dir); try { - const stat = await fs.stat(dirPath); - mtimes.push(Math.floor(stat.mtimeMs)); + const files = await glob('**/*', { + cwd: dirPath, + absolute: true, + nodir: true, + dot: true, + ignore: dir === '.context' ? ['runtime/**', 'cache/**'] : [], + }); + for (const file of files.sort()) { + const stat = await fs.stat(file); + hash.update(`${dir}/${path.relative(dirPath, file)}:${stat.size}:${stat.mtimeMs}\n`); + } } catch { - // Directory doesn't exist — that's fine, skip it - mtimes.push(0); + hash.update(`${dir}:missing\n`); } } - return mtimes.join('-'); + return hash.digest('hex'); } } diff --git a/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts b/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts index 121dc2db..6f2afed7 100644 --- a/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts +++ b/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts @@ -15,6 +15,7 @@ import { LANGUAGE_EXTENSIONS, SupportedLanguage, } from '../types'; +import { BoundedLruCache } from '../../../../domain/retention/boundedLruCache'; interface CacheEntry { mtime: number; @@ -22,12 +23,21 @@ interface CacheEntry { } export class TreeSitterLayer { - private cache: Map = new Map(); + private readonly cache: BoundedLruCache; + private readonly cacheEnabled: boolean; private treeSitterAvailable: boolean = false; private parsers: Map = new Map(); public readonly ready: Promise; - constructor() { + constructor(options: { cacheEnabled?: boolean; maxEntries?: number; maxBytes?: number } = {}) { + this.cacheEnabled = options.cacheEnabled ?? true; + this.cache = new BoundedLruCache({ + maxEntries: options.maxEntries ?? 5_000, + maxBytes: options.maxBytes ?? 128 * 1024 * 1024, + // File freshness is mtime-bound; this TTL bounds idle retention for long-lived processes. + ttlMs: 30 * 60 * 1000, + estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(JSON.stringify(entry.analysis)), + }); this.ready = this.initializeParsers(); } @@ -70,7 +80,7 @@ export class TreeSitterLayer { const mtime = stat.mtimeMs; // Check cache - const cached = this.cache.get(filePath); + const cached = this.cacheEnabled ? this.cache.get(path.resolve(filePath)) : undefined; if (cached && cached.mtime === mtime) { return cached.analysis; } @@ -84,7 +94,7 @@ export class TreeSitterLayer { analysis = this.analyzeWithRegex(filePath, content, language); } - this.cache.set(filePath, { mtime, analysis }); + if (this.cacheEnabled) this.cache.set(path.resolve(filePath), { mtime, analysis }); return analysis; } catch (error) { return this.emptyAnalysis(filePath, language); @@ -561,6 +571,21 @@ export class TreeSitterLayer { this.cache.clear(); } + retainOnly(filePaths: Iterable): void { + const retained = new Set([...filePaths].map(filePath => path.resolve(filePath))); + for (const cachedPath of [...this.cache.keys()]) { + if (!retained.has(cachedPath)) this.cache.delete(cachedPath); + } + } + + get cacheSize(): number { + return this.cache.size; + } + + dispose(): void { + this.cache.dispose(); + } + async isTreeSitterAvailable(): Promise { await this.ready; return this.treeSitterAvailable; diff --git a/src/harness/application/index.ts b/src/harness/application/index.ts index 721c0d0f..80fa2650 100644 --- a/src/harness/application/index.ts +++ b/src/harness/application/index.ts @@ -1,6 +1,7 @@ export * from './actions'; export * from './hooks'; export * from './workflow'; +export * from './retention'; export * from './context'; export * from './agents'; export * from './skills'; diff --git a/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts new file mode 100644 index 00000000..09288ea3 --- /dev/null +++ b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts @@ -0,0 +1,23 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; +import { loadRuntimeRetentionConfig } from '../runtimeRetentionConfig'; + +describe('loadRuntimeRetentionConfig', () => { + it('ignores unknown keys and clamps values that could disable safety ceilings', async () => { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), 'runtime-retention-')); + await fs.outputJson(path.join(repo, '.context', 'config', 'runtime.json'), { + version: 1, + unknown: true, + bindings: { maxEntries: Number.MAX_SAFE_INTEGER }, + checkpoints: { maxDataBytes: 0, maxArtifactIds: -1 }, + }); + const result = await loadRuntimeRetentionConfig(repo); + expect(result.config.bindings.maxEntries).toBe(10_000); + expect(result.config.checkpoints.maxDataBytes).toBe(64 * 1024); + expect(result.config.checkpoints.maxArtifactIds).toBe(200); + expect(result.diagnostics.some(item => item.includes('Unknown'))).toBe(true); + expect(result.clamps).toBeGreaterThan(0); + await fs.remove(repo); + }); +}); diff --git a/src/harness/application/retention/index.ts b/src/harness/application/retention/index.ts new file mode 100644 index 00000000..d7e050eb --- /dev/null +++ b/src/harness/application/retention/index.ts @@ -0,0 +1 @@ +export * from './runtimeRetentionConfig'; diff --git a/src/harness/application/retention/runtimeRetentionConfig.ts b/src/harness/application/retention/runtimeRetentionConfig.ts new file mode 100644 index 00000000..6aa402b0 --- /dev/null +++ b/src/harness/application/retention/runtimeRetentionConfig.ts @@ -0,0 +1,118 @@ +import * as fs from 'fs-extra'; +import * as path from 'path'; + +export interface RuntimeRetentionConfig { + version: 1; + traces: { maxBytes: number }; + sessions: { maxEntries: number }; + replays: { maxEntries: number }; + datasets: { maxEntries: number }; + checkpoints: { maxDataBytes: number; maxArtifactIds: number }; + bindings: { maxEntries: number; maxAgeMs: number }; + caches: { + context: { maxEntries: number; maxBytes: number; ttlMs: number }; + semantic: { maxEntries: number; maxBytes: number }; + mcpSessions: { maxEntries: number; ttlMs: number }; + fileAnalysis: { maxEntries: number; maxBytes: number }; + }; +} + +export interface RuntimeRetentionConfigResult { + config: RuntimeRetentionConfig; + diagnostics: string[]; + clamps: number; +} + +export const DEFAULT_RUNTIME_RETENTION_CONFIG: RuntimeRetentionConfig = { + version: 1, + traces: { maxBytes: 64 * 1024 * 1024 }, + sessions: { maxEntries: 1_000 }, + replays: { maxEntries: 100 }, + datasets: { maxEntries: 100 }, + checkpoints: { maxDataBytes: 64 * 1024, maxArtifactIds: 200 }, + bindings: { maxEntries: 1_000, maxAgeMs: 30 * 24 * 60 * 60 * 1000 }, + caches: { + context: { maxEntries: 16, maxBytes: 32 * 1024 * 1024, ttlMs: 5 * 60 * 1000 }, + semantic: { maxEntries: 1, maxBytes: 64 * 1024 * 1024 }, + mcpSessions: { maxEntries: 64, ttlMs: 30 * 60 * 1000 }, + fileAnalysis: { maxEntries: 5_000, maxBytes: 128 * 1024 * 1024 }, + }, +}; + +const KNOWN_TOP_LEVEL = new Set(['version', 'traces', 'sessions', 'replays', 'datasets', 'checkpoints', 'bindings', 'caches']); + +function boundedNumber( + value: unknown, + fallback: number, + minimum: number, + absoluteMaximum: number, + name: string, + diagnostics: string[], +): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum) { + if (value !== undefined) diagnostics.push(`${name} was invalid and reset to ${fallback}`); + return fallback; + } + if (value > absoluteMaximum) { + diagnostics.push(`${name} was clamped to the absolute safety ceiling ${absoluteMaximum}`); + return absoluteMaximum; + } + return Math.floor(value); +} + +/** Load `.context/config/runtime.json`, ignoring unknown keys and clamping unsafe limits. */ +export async function loadRuntimeRetentionConfig(repoPath: string): Promise { + const diagnostics: string[] = []; + const file = path.join(path.resolve(repoPath), '.context', 'config', 'runtime.json'); + let input: Record = {}; + if (await fs.pathExists(file)) { + try { + const parsed = await fs.readJson(file); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) input = parsed; + else diagnostics.push('runtime.json root must be an object; defaults applied'); + } catch { + diagnostics.push('runtime.json could not be parsed; defaults applied'); + } + } + for (const key of Object.keys(input)) { + if (!KNOWN_TOP_LEVEL.has(key)) diagnostics.push(`Unknown runtime configuration key ignored: ${key}`); + } + const d = DEFAULT_RUNTIME_RETENTION_CONFIG; + const number = (value: unknown, fallback: number, min: number, max: number, name: string) => + boundedNumber(value, fallback, min, max, name, diagnostics); + const config: RuntimeRetentionConfig = { + version: 1, + traces: { maxBytes: number(input.traces?.maxBytes, d.traces.maxBytes, 1_024, 1024 ** 3, 'traces.maxBytes') }, + sessions: { maxEntries: number(input.sessions?.maxEntries, d.sessions.maxEntries, 1, 100_000, 'sessions.maxEntries') }, + replays: { maxEntries: number(input.replays?.maxEntries, d.replays.maxEntries, 1, 10_000, 'replays.maxEntries') }, + datasets: { maxEntries: number(input.datasets?.maxEntries, d.datasets.maxEntries, 1, 10_000, 'datasets.maxEntries') }, + checkpoints: { + maxDataBytes: number(input.checkpoints?.maxDataBytes, d.checkpoints.maxDataBytes, 1_024, 1024 ** 2, 'checkpoints.maxDataBytes'), + maxArtifactIds: number(input.checkpoints?.maxArtifactIds, d.checkpoints.maxArtifactIds, 1, 1_000, 'checkpoints.maxArtifactIds'), + }, + bindings: { + maxEntries: number(input.bindings?.maxEntries, d.bindings.maxEntries, 1, 10_000, 'bindings.maxEntries'), + maxAgeMs: number(input.bindings?.maxAgeMs, d.bindings.maxAgeMs, 60_000, 365 * 24 * 60 * 60 * 1000, 'bindings.maxAgeMs'), + }, + caches: { + context: { + maxEntries: number(input.caches?.context?.maxEntries, d.caches.context.maxEntries, 1, 256, 'caches.context.maxEntries'), + maxBytes: number(input.caches?.context?.maxBytes, d.caches.context.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.context.maxBytes'), + ttlMs: number(input.caches?.context?.ttlMs, d.caches.context.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.context.ttlMs'), + }, + semantic: { + maxEntries: number(input.caches?.semantic?.maxEntries, d.caches.semantic.maxEntries, 1, 4, 'caches.semantic.maxEntries'), + maxBytes: number(input.caches?.semantic?.maxBytes, d.caches.semantic.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.semantic.maxBytes'), + }, + mcpSessions: { + maxEntries: number(input.caches?.mcpSessions?.maxEntries, d.caches.mcpSessions.maxEntries, 1, 1_000, 'caches.mcpSessions.maxEntries'), + ttlMs: number(input.caches?.mcpSessions?.ttlMs, d.caches.mcpSessions.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.mcpSessions.ttlMs'), + }, + fileAnalysis: { + maxEntries: number(input.caches?.fileAnalysis?.maxEntries, d.caches.fileAnalysis.maxEntries, 1, 20_000, 'caches.fileAnalysis.maxEntries'), + maxBytes: number(input.caches?.fileAnalysis?.maxBytes, d.caches.fileAnalysis.maxBytes, 1_024, 512 * 1024 * 1024, 'caches.fileAnalysis.maxBytes'), + }, + }, + }; + return { config, diagnostics, clamps: diagnostics.length }; +} diff --git a/src/harness/domain/index.ts b/src/harness/domain/index.ts index 2d1af512..69308224 100644 --- a/src/harness/domain/index.ts +++ b/src/harness/domain/index.ts @@ -4,3 +4,4 @@ export * as policies from './policies'; export * as sensors from './sensors'; export * as collaboration from './collaboration'; export * as context from './context'; +export * as retention from './retention'; diff --git a/src/harness/domain/retention/__tests__/boundedLruCache.test.ts b/src/harness/domain/retention/__tests__/boundedLruCache.test.ts new file mode 100644 index 00000000..5e7c3ed1 --- /dev/null +++ b/src/harness/domain/retention/__tests__/boundedLruCache.test.ts @@ -0,0 +1,39 @@ +import { BoundedLruCache } from '../boundedLruCache'; + +describe('BoundedLruCache', () => { + it('evicts least recently used entries and rejects an oversized entry', () => { + let now = 0; + const cache = new BoundedLruCache({ + maxEntries: 2, + maxBytes: 5, + ttlMs: 100, + sweepIntervalMs: 0, + now: () => now, + estimateBytes: value => value.length, + }); + cache.set('a', 'aa'); + cache.set('b', 'bb'); + expect(cache.get('a')).toBe('aa'); + cache.set('c', 'cc'); + expect(cache.get('b')).toBeUndefined(); + expect(cache.set('huge', '123456')).toBe(false); + expect(cache.metrics().estimatedBytes).toBe(4); + cache.dispose(); + }); + + it('sweeps expired entries without reading each key', () => { + let now = 0; + const cache = new BoundedLruCache({ + maxEntries: 2, + maxBytes: 10, + ttlMs: 10, + sweepIntervalMs: 0, + now: () => now, + estimateBytes: value => value.length, + }); + cache.set('a', 'a'); + now = 11; + expect(cache.sweepExpired()).toBe(1); + expect(cache.size).toBe(0); + }); +}); diff --git a/src/harness/domain/retention/boundedLruCache.ts b/src/harness/domain/retention/boundedLruCache.ts new file mode 100644 index 00000000..4fccc9d1 --- /dev/null +++ b/src/harness/domain/retention/boundedLruCache.ts @@ -0,0 +1,141 @@ +export type CacheEvictionReason = 'expired' | 'entries' | 'bytes' | 'replaced' | 'cleared'; + +export interface BoundedLruCacheOptions { + maxEntries: number; + maxBytes: number; + ttlMs: number; + estimateBytes(value: V, key: K): number; + sweepIntervalMs?: number; + now?: () => number; +} + +interface Entry { + value: V; + bytes: number; + createdAt: number; + lastAccessedAt: number; +} + +export interface BoundedLruCacheMetrics { + entries: number; + estimatedBytes: number; + hits: number; + misses: number; + evictions: Record; + oldestAgeMs: number; +} + +/** A process-local TTL/LRU cache with deterministic entry and byte ceilings. */ +export class BoundedLruCache { + private readonly entries = new Map>(); + private readonly now: () => number; + private readonly timer?: NodeJS.Timeout; + private estimatedBytes = 0; + private hits = 0; + private misses = 0; + private readonly evictions: Record = { + expired: 0, + entries: 0, + bytes: 0, + replaced: 0, + cleared: 0, + }; + + constructor(private readonly options: BoundedLruCacheOptions) { + if (options.maxEntries < 1 || options.maxBytes < 1 || options.ttlMs < 1) { + throw new Error('BoundedLruCache limits must be positive'); + } + this.now = options.now ?? Date.now; + const interval = options.sweepIntervalMs ?? Math.min(options.ttlMs, 60_000); + if (interval > 0) { + this.timer = setInterval(() => this.sweepExpired(), interval); + this.timer.unref(); + } + } + + get(key: K): V | undefined { + const entry = this.entries.get(key); + if (!entry) { + this.misses += 1; + return undefined; + } + if (this.now() - entry.lastAccessedAt >= this.options.ttlMs) { + this.remove(key, 'expired'); + this.misses += 1; + return undefined; + } + entry.lastAccessedAt = this.now(); + // Map insertion order is the LRU order. + this.entries.delete(key); + this.entries.set(key, entry); + this.hits += 1; + return entry.value; + } + + set(key: K, value: V): boolean { + this.sweepExpired(); + const bytes = Math.max(0, Math.ceil(this.options.estimateBytes(value, key))); + if (bytes > this.options.maxBytes) return false; + if (this.entries.has(key)) this.remove(key, 'replaced'); + const timestamp = this.now(); + this.entries.set(key, { value, bytes, createdAt: timestamp, lastAccessedAt: timestamp }); + this.estimatedBytes += bytes; + while (this.entries.size > this.options.maxEntries) this.evictOldest('entries'); + while (this.estimatedBytes > this.options.maxBytes) this.evictOldest('bytes'); + return this.entries.has(key); + } + + delete(key: K): boolean { + return this.remove(key, 'cleared'); + } + + sweepExpired(): number { + const startedWith = this.entries.size; + const now = this.now(); + for (const [key, entry] of this.entries) { + if (now - entry.lastAccessedAt >= this.options.ttlMs) this.remove(key, 'expired'); + } + return startedWith - this.entries.size; + } + + clear(): void { + for (const key of [...this.entries.keys()]) this.remove(key, 'cleared'); + } + + dispose(): void { + if (this.timer) clearInterval(this.timer); + this.clear(); + } + + keys(): IterableIterator { return this.entries.keys(); } + get size(): number { return this.entries.size; } + + metrics(): BoundedLruCacheMetrics { + const oldest = [...this.entries.values()].reduce( + (value, entry) => Math.min(value, entry.createdAt), + this.now(), + ); + return { + entries: this.entries.size, + estimatedBytes: this.estimatedBytes, + hits: this.hits, + misses: this.misses, + evictions: { ...this.evictions }, + oldestAgeMs: this.entries.size ? Math.max(0, this.now() - oldest) : 0, + }; + } + + private evictOldest(reason: CacheEvictionReason): void { + const key = this.entries.keys().next().value as K | undefined; + if (key !== undefined) this.remove(key, reason); + } + + private remove(key: K, reason: CacheEvictionReason): boolean { + const entry = this.entries.get(key); + if (!entry) return false; + this.entries.delete(key); + this.estimatedBytes -= entry.bytes; + this.evictions[reason] += 1; + return true; + } +} diff --git a/src/harness/domain/retention/index.ts b/src/harness/domain/retention/index.ts new file mode 100644 index 00000000..514af691 --- /dev/null +++ b/src/harness/domain/retention/index.ts @@ -0,0 +1 @@ +export * from './boundedLruCache'; diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 795881b7..f6c48690 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -10,6 +10,8 @@ import { import { ensureHookHarnessSession, getHookHarnessSessionId, + pruneHookSessionBindings, + saveHookHarnessSession, } from '../hookSessionStore'; describe('hookDispatchCommands', () => { @@ -57,4 +59,49 @@ describe('hookSessionStore', () => { expect(stored).toBe(first); }); + + it('prunes expired and missing harness-session bindings during explicit maintenance', async () => { + const old = '2020-01-01T00:00:00.000Z'; + await saveHookHarnessSession({ + repoPath: tempDir, + source: 'codex', + hostSessionId: 'expired', + harnessSessionId: 'missing-expired', + createdAt: old, + updatedAt: old, + }); + await saveHookHarnessSession({ + repoPath: tempDir, + source: 'codex', + hostSessionId: 'missing', + harnessSessionId: 'missing-current', + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + const result = await pruneHookSessionBindings(tempDir); + expect(result.removedExpired).toBe(1); + expect(result.removedMissing).toBe(1); + expect(result.remaining).toBe(0); + }); + + it('caps host-sessions.json at the configured repository limit', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + version: 1, + bindings: { maxEntries: 2 }, + }); + for (let index = 0; index < 3; index += 1) { + const timestamp = new Date(Date.now() + index * 1000).toISOString(); + await saveHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: `host-${index}`, + harnessSessionId: `harness-${index}`, + createdAt: timestamp, + updatedAt: timestamp, + }); + } + const store = await fs.readJson(path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json')); + expect(Object.keys(store.bindings['claude-code'])).toHaveLength(2); + expect(store.bindings['claude-code']['host-0']).toBeUndefined(); + }); }); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 739ba127..ba38784d 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -3,6 +3,7 @@ import * as path from 'path'; import { getContextRootPath } from '../../shared/context'; import type { HarnessHookResponse } from '../../harness'; +import { loadRuntimeRetentionConfig } from '../../harness/application/retention/runtimeRetentionConfig'; import { extractHarnessSessionId } from './extractHarnessSessionId'; @@ -21,6 +22,14 @@ interface HookSessionStoreDocument { bindings: Record>; } +export interface HookSessionPruneResult { + removedExpired: number; + removedMissing: number; + removedOverLimit: number; + remaining: number; + durationMs: number; +} + export interface HookSessionAdapter { handle(event: { tool: 'harness'; @@ -76,11 +85,65 @@ export async function getHookHarnessSessionId(options: { } export async function saveHookHarnessSession(binding: HookSessionBinding): Promise { - const document = await readStore(binding.repoPath); + const normalizedRepoPath = path.resolve(binding.repoPath); + const document = await readStore(normalizedRepoPath); const sourceBindings = document.bindings[binding.source] ?? {}; - sourceBindings[binding.hostSessionId] = binding; + sourceBindings[binding.hostSessionId] = { ...binding, repoPath: normalizedRepoPath }; document.bindings[binding.source] = sourceBindings; - await writeStore(binding.repoPath, document); + const { config } = await loadRuntimeRetentionConfig(normalizedRepoPath); + capBindings(document, config.bindings.maxEntries); + await writeStore(normalizedRepoPath, document); +} + +function allBindings(document: HookSessionStoreDocument): Array<{ source: string; hostSessionId: string; binding: HookSessionBinding }> { + return Object.entries(document.bindings).flatMap(([source, sourceBindings]) => + Object.entries(sourceBindings).map(([hostSessionId, binding]) => ({ source, hostSessionId, binding })), + ); +} + +function capBindings(document: HookSessionStoreDocument, maxEntries: number): number { + const bindings = allBindings(document).sort((a, b) => b.binding.updatedAt.localeCompare(a.binding.updatedAt)); + let removed = 0; + for (const entry of bindings.slice(maxEntries)) { + delete document.bindings[entry.source]?.[entry.hostSessionId]; + removed += 1; + } + return removed; +} + +/** Explicit maintenance used at SessionStart, never on each PostToolUse. */ +export async function pruneHookSessionBindings(repoPath: string): Promise { + const startedAt = Date.now(); + const normalizedRepoPath = path.resolve(repoPath); + const contextRoot = await getContextRootPath(normalizedRepoPath); + const document = await readStore(normalizedRepoPath); + const { config } = await loadRuntimeRetentionConfig(normalizedRepoPath); + const cutoff = Date.now() - config.bindings.maxAgeMs; + let removedExpired = 0; + let removedMissing = 0; + + for (const { source, hostSessionId, binding } of allBindings(document)) { + const updatedAt = Date.parse(binding.updatedAt); + if (!Number.isFinite(updatedAt) || updatedAt < cutoff) { + delete document.bindings[source]?.[hostSessionId]; + removedExpired += 1; + continue; + } + const sessionFile = path.join(contextRoot, 'runtime', 'sessions', binding.harnessSessionId, 'session.json'); + if (!await fs.pathExists(sessionFile)) { + delete document.bindings[source]?.[hostSessionId]; + removedMissing += 1; + } + } + const removedOverLimit = capBindings(document, config.bindings.maxEntries); + await writeStore(normalizedRepoPath, document); + return { + removedExpired, + removedMissing, + removedOverLimit, + remaining: allBindings(document).length, + durationMs: Date.now() - startedAt, + }; } export async function ensureHookHarnessSession( @@ -91,6 +154,7 @@ export async function ensureHookHarnessSession( hostSessionId: string; } ): Promise { + await pruneHookSessionBindings(options.repoPath); const existing = await getHookHarnessSessionId(options); if (existing) { return existing; diff --git a/src/integrations/shared/index.ts b/src/integrations/shared/index.ts index a9b9a458..62566ac0 100644 --- a/src/integrations/shared/index.ts +++ b/src/integrations/shared/index.ts @@ -46,8 +46,10 @@ export { ensureHookHarnessSession, getHookHarnessSessionId, saveHookHarnessSession, + pruneHookSessionBindings, type HookSessionAdapter, type HookSessionBinding, + type HookSessionPruneResult, type ShellHookSource, } from './hookSessionStore'; diff --git a/src/mcp/logging/__tests__/actionLogger.test.ts b/src/mcp/logging/__tests__/actionLogger.test.ts index f66e80af..230356a5 100644 --- a/src/mcp/logging/__tests__/actionLogger.test.ts +++ b/src/mcp/logging/__tests__/actionLogger.test.ts @@ -4,7 +4,7 @@ import * as path from 'path'; import { HarnessRuntimeStateService } from '../../../harness/adapters/out/runtimeState/runtimeStateService'; import { WorkflowService } from '../../../harness/application/workflow/workflowService'; -import { logMcpAction } from '../actionLogger'; +import { clearMcpActionSessionCache, getMcpActionSessionCacheSize, logMcpAction } from '../actionLogger'; describe('logMcpAction', () => { let tempDir: string; @@ -22,6 +22,7 @@ describe('logMcpAction', () => { }); afterEach(async () => { + clearMcpActionSessionCache(); await fs.remove(tempDir); }); @@ -53,6 +54,7 @@ describe('logMcpAction', () => { expect((mcpTrace?.data as any).details.nested.content).toBe('[redacted]'); expect(await fs.pathExists(path.join(tempDir, '.context', 'workflow', 'actions.jsonl'))).toBe(false); + expect(getMcpActionSessionCacheSize()).toBeLessThanOrEqual(64); }); it('reuses the workflow harness session when one is active', async () => { diff --git a/src/mcp/logging/actionLogger.ts b/src/mcp/logging/actionLogger.ts index d4907036..9bb58ba2 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -6,8 +6,10 @@ */ import * as fs from 'fs-extra'; +import * as path from 'path'; import { HarnessRuntimeStateService } from '../../harness/adapters/out/runtimeState/runtimeStateService'; +import { BoundedLruCache } from '../../harness/domain/retention/boundedLruCache'; import { HarnessWorkflowStateService } from '../../harness/adapters/out/workflowState/workflowStateService'; import { resolveContextRoot } from '../../shared/context/contextRootResolver'; @@ -39,7 +41,24 @@ const MAX_ARRAY = 20; const MAX_STRING = 200; const MCP_ACTIVITY_NAME = 'mcp-activity'; -const sessionCache = new Map(); +const sessionCache = new BoundedLruCache({ + maxEntries: 64, + maxBytes: 64 * 1024, + ttlMs: 30 * 60 * 1000, + estimateBytes: (sessionId, repoPath) => Buffer.byteLength(sessionId) + Buffer.byteLength(repoPath), +}); + +function normalizeRepoPath(repoPath: string): string { + return path.resolve(repoPath).toLowerCase(); +} + +export function clearMcpActionSessionCache(): void { + sessionCache.dispose(); +} + +export function getMcpActionSessionCacheSize(): number { + return sessionCache.size; +} async function resolveContextPath(repoPath: string): Promise { const resolution = await resolveContextRoot({ @@ -108,13 +127,15 @@ async function resolveMcpActivitySessionId( repoPath: string, state: HarnessRuntimeStateService ): Promise { - const cached = sessionCache.get(repoPath); + const cacheKey = normalizeRepoPath(repoPath); + const cached = sessionCache.get(cacheKey); if (cached) { try { - await state.getSession(cached); - return cached; + const session = await state.getSession(cached); + if (session.status === 'active' || session.status === 'paused') return cached; + sessionCache.delete(cacheKey); } catch { - sessionCache.delete(repoPath); + sessionCache.delete(cacheKey); } } @@ -124,7 +145,7 @@ async function resolveMcpActivitySessionId( ); if (existing) { - sessionCache.set(repoPath, existing.id); + sessionCache.set(cacheKey, existing.id); return existing.id; } @@ -135,7 +156,7 @@ async function resolveMcpActivitySessionId( purpose: 'tool-audit', }, }); - sessionCache.set(repoPath, created.id); + sessionCache.set(cacheKey, created.id); return created.id; } diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index 0e0bf5d8..9c20854a 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -19,7 +19,7 @@ import { SemanticContextBuilder, type ContextFormat } from '../../harness/adapte import { ContextCache } from '../../harness/adapters/out/semantic/contextCache'; import { VERSION } from '../../version'; import { WorkflowService } from '../../harness/application/workflow'; -import { logMcpAction } from '../logging/actionLogger'; +import { clearMcpActionSessionCache, logMcpAction } from '../logging/actionLogger'; import { PREVC_ROLES, getScaleName, @@ -1136,6 +1136,8 @@ Actions: */ async stop(): Promise { await this.server.close(); + this.contextCache.dispose(); + clearMcpActionSessionCache(); await this.contextBuilder.shutdown(); this.log('MCP Server stopped'); } diff --git a/src/shared/fs/pathHelpers.ts b/src/shared/fs/pathHelpers.ts index a8694956..1493aa0f 100644 --- a/src/shared/fs/pathHelpers.ts +++ b/src/shared/fs/pathHelpers.ts @@ -131,6 +131,10 @@ export interface RuntimeLayout { sessionArtifactsDir(sessionId: string): string; /** `.context/runtime/sessions//artifacts/.json` */ sessionArtifactFile(sessionId: string, artifactId: string): string; + /** `.context/runtime/sessions//checkpoints` */ + sessionCheckpointsDir(sessionId: string): string; + /** `.context/runtime/sessions//checkpoints/.json` */ + sessionCheckpointFile(sessionId: string, checkpointId: string): string; } /** @@ -169,6 +173,9 @@ export function resolveRuntimeLayout(contextPath: string): RuntimeLayout { sessionArtifactsDir: (sessionId: string) => path.join(sessionsDir, sessionId, 'artifacts'), sessionArtifactFile: (sessionId: string, artifactId: string) => path.join(sessionsDir, sessionId, 'artifacts', `${artifactId}.json`), + sessionCheckpointsDir: (sessionId: string) => path.join(sessionsDir, sessionId, 'checkpoints'), + sessionCheckpointFile: (sessionId: string, checkpointId: string) => + path.join(sessionsDir, sessionId, 'checkpoints', `${checkpointId}.json`), }; } From 327762866f51efa33c058e498867f6dd5debfb82 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:16:35 -0300 Subject: [PATCH 08/39] perf: stream and bound runtime history --- CHANGELOG.md | 3 + .../docs/en/concepts/harness-runtime.md | 2 +- .../docs/en/concepts/replay-and-datasets.md | 11 +- .../docs/pt-br/concepts/harness-runtime.md | 2 +- .../pt-br/concepts/replay-and-datasets.md | 11 +- .../__tests__/runtimeStateService.test.ts | 43 +++ .../out/runtimeState/runtimeStateService.ts | 345 +++++++++++++++--- .../application/actions/actionService.ts | 34 +- .../contracts/taskContractsService.ts | 17 +- .../datasets/__tests__/datasetService.test.ts | 32 ++ .../application/datasets/datasetService.ts | 102 ++++-- .../application/execution/executionService.ts | 20 + .../__tests__/runtimeHistory.load.test.ts | 41 +++ .../__tests__/runtimeRetentionService.test.ts | 38 ++ src/harness/application/history/index.ts | 2 + .../application/history/runtimeHistory.ts | 69 ++++ .../history/runtimeRetentionService.ts | 126 +++++++ src/harness/application/index.ts | 1 + .../replay/__tests__/replayService.test.ts | 17 + .../application/replay/replayService.ts | 117 ++++-- .../application/sensors/sensorsService.ts | 6 +- src/harness/index.ts | 11 + src/mcp/logging/actionLogger.ts | 13 +- 23 files changed, 940 insertions(+), 123 deletions(-) create mode 100644 src/harness/application/history/__tests__/runtimeHistory.load.test.ts create mode 100644 src/harness/application/history/__tests__/runtimeRetentionService.test.ts create mode 100644 src/harness/application/history/index.ts create mode 100644 src/harness/application/history/runtimeHistory.ts create mode 100644 src/harness/application/history/runtimeRetentionService.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e0e42212..e48777b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added configurable, globally clamped hook stdin, field, event, rotation, segment-retention, and per-session trace limits. +- Added opaque cursor pages for sessions, traces, artifacts, replay summaries, and dataset summaries, including bounded defaults, query-bound cursors, and scan metadata. +- Added latest-sensor summary indexes, bounded dataset concurrency/failure retention, and dry-run runtime pruning with active workflow protection. ### Fixed - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. +- Replaced whole-file trace reads and post-materialization replay limits with rotation-aware streaming and source-level event bounds. ## [1.1.1] - 2026-06-27 diff --git a/docs/src/content/docs/en/concepts/harness-runtime.md b/docs/src/content/docs/en/concepts/harness-runtime.md index 0ed921d4..3cb9585f 100644 --- a/docs/src/content/docs/en/concepts/harness-runtime.md +++ b/docs/src/content/docs/en/concepts/harness-runtime.md @@ -120,7 +120,7 @@ Each trace entry looks like this: | `message` | Human-readable description | | `data` | Optional structured payload (sensor results, context, etc.) | -Because the file is **append-only** (`.jsonl`, one JSON object per line), traces are cheap to write and never rewrite earlier entries. Use the `harness` tool's `appendTrace` action to add an event and `listTraces` to read the timeline. +Because the file is **append-only** (`.jsonl`, one JSON object per line), traces are cheap to write and never rewrite earlier entries. The harness reads legacy and rotated segments incrementally. `listTraces` returns a bounded page (100 records by default, 1,000 maximum) with an opaque `nextCursor`, `hasMore`, scan-byte, malformed-line, and duration metadata. Filters support `event`, `level`, `createdAfter`, and `createdBefore`; point reads remain available through their resource-specific actions. ::: note Trace `event` values like `sensor.run` are how the harness records [sensor](/concepts/sensors/) results into a session. That's what later lets task contracts check whether required sensors passed, and lets [failure datasets](/concepts/replay-and-datasets/) cluster error-level events. diff --git a/docs/src/content/docs/en/concepts/replay-and-datasets.md b/docs/src/content/docs/en/concepts/replay-and-datasets.md index 5d9de528..78c166de 100644 --- a/docs/src/content/docs/en/concepts/replay-and-datasets.md +++ b/docs/src/content/docs/en/concepts/replay-and-datasets.md @@ -23,7 +23,7 @@ Replay answers the first two by collapsing a session into one ordered event log. ## Replay: a durable, ordered event log -A **replay** reconstructs a session's complete timeline from everything the harness recorded: the session record itself, its traces, artifacts, checkpoints, sensor runs, tasks, and handoffs. The result is a single document with a flat, time-ordered list of events that you can play back in sequence. +A **replay** reconstructs a bounded page of a session timeline from its session summary, traces, artifacts, checkpoints, sensor runs, tasks, and handoffs. The result is a time-ordered event page that can be continued with an opaque cursor without first materializing the complete history. ### What a replay contains @@ -37,9 +37,11 @@ Each replay is a self-contained snapshot. Beyond the collected data, it carries | `createdAt` / `replayedAt` | When the replay was built | | `fidelity` | `complete` or `partial` (whether all source data was available) | | `eventCount` | Number of events in the ordered timeline | +| `sourceCounts` / `omittedCounts` | Available and omitted records by source | +| `nextCursor` | Opaque continuation cursor when the replay is partial | | `summary` | Human-readable description of the run | -The collected source data (`session`, `artifacts`, `checkpoints`, `traces`, `sensorRuns`, `tasks`, `handoffs`) is included in full, and the `events` array merges all of it into one timeline: +The collected source arrays and the merged `events` array are all constrained by `maxEvents` (100 by default, 1,000 maximum). A partial replay persists only that bounded materialization: ```json { @@ -87,6 +89,9 @@ Replay is an action on the `harness` MCP tool: // Re-run a session into a durable replay { "action": "replaySession", "sessionId": "session-..." } +// Bound the response and persisted replay to ten events +{ "action": "replaySession", "sessionId": "session-...", "maxEvents": 10 } + // List existing replays { "action": "listReplays" } @@ -100,7 +105,7 @@ Build a replay right after a session finishes — whether it completed or failed ## Failure datasets: clustering what keeps breaking -A single replay tells you about one run. A **failure dataset** scans across replays to build a failure corpus, then groups related failures into clusters so you can see which problems recur. +A single replay tells you about one run. A **failure dataset** processes sessions with one worker by default (configurable up to four), retains at most 10,000 failures by default, and reports `partial` plus `omittedFailureCount` when capped. ### How failures are collected diff --git a/docs/src/content/docs/pt-br/concepts/harness-runtime.md b/docs/src/content/docs/pt-br/concepts/harness-runtime.md index 16409af2..94b51cb2 100644 --- a/docs/src/content/docs/pt-br/concepts/harness-runtime.md +++ b/docs/src/content/docs/pt-br/concepts/harness-runtime.md @@ -120,7 +120,7 @@ Cada entrada de trace tem este formato: | `message` | Descrição legível por humanos | | `data` | Payload estruturado opcional (resultados de sensor, contexto, etc.) | -Como o arquivo é **append-only** (`.jsonl`, um objeto JSON por linha), traces são baratos de escrever e nunca reescrevem entradas anteriores. Use a action `appendTrace` da tool `harness` para adicionar um evento e `listTraces` para ler a linha do tempo. +Como o arquivo é **append-only** (`.jsonl`, um objeto JSON por linha), traces são baratos de escrever e nunca reescrevem entradas anteriores. O harness lê segmentos legados e rotacionados de forma incremental. `listTraces` retorna uma página limitada (100 registros por padrão, máximo de 1.000) com `nextCursor` opaco, `hasMore` e metadados de bytes lidos, linhas malformadas e duração. Os filtros aceitos são `event`, `level`, `createdAfter` e `createdBefore`; leituras pontuais continuam disponíveis nas actions específicas de cada recurso. ::: note Valores de `event` de trace como `sensor.run` são a forma como o harness registra resultados de [sensores](/pt-br/concepts/sensors/) em uma session. É isso que depois permite que task contracts verifiquem se os sensores requeridos passaram, e que [failure datasets](/pt-br/concepts/replay-and-datasets/) agrupem eventos de nível de erro. diff --git a/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md b/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md index 388b7006..092041d6 100644 --- a/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md +++ b/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md @@ -23,7 +23,7 @@ O replay responde as duas primeiras ao condensar uma sessão em um único log de ## Replay: um log de eventos durável e ordenado -Um **replay** reconstrói a timeline completa de uma sessão a partir de tudo que o harness registrou: o próprio registro da sessão, seus traces, artifacts, checkpoints, execuções de sensor, tasks e handoffs. O resultado é um único documento com uma lista plana de eventos ordenada no tempo, que você pode reproduzir em sequência. +Um **replay** reconstrói uma página limitada da timeline de uma sessão a partir do resumo da sessão, traces, artifacts, checkpoints, execuções de sensor, tasks e handoffs. O resultado é uma página de eventos ordenada no tempo que pode continuar por cursor opaco sem materializar primeiro todo o histórico. ### O que um replay contém @@ -37,9 +37,11 @@ Cada replay é um snapshot autocontido. Além dos dados coletados, ele carrega u | `createdAt` / `replayedAt` | Quando o replay foi construído | | `fidelity` | `complete` ou `partial` (se todos os dados de origem estavam disponíveis) | | `eventCount` | Número de eventos na timeline ordenada | +| `sourceCounts` / `omittedCounts` | Registros disponíveis e omitidos por origem | +| `nextCursor` | Cursor opaco de continuação quando o replay é parcial | | `summary` | Descrição legível da execução | -Os dados de origem coletados (`session`, `artifacts`, `checkpoints`, `traces`, `sensorRuns`, `tasks`, `handoffs`) são incluídos por completo, e o array `events` mescla tudo em uma única timeline: +Os arrays de origem coletados e o array mesclado `events` são limitados por `maxEvents` (100 por padrão, máximo de 1.000). Um replay parcial persiste somente essa materialização limitada: ```json { @@ -87,6 +89,9 @@ O replay é uma action da ferramenta MCP `harness`: // Re-executa uma sessão em um replay durável { "action": "replaySession", "sessionId": "session-..." } +// Limita a resposta e o replay persistido a dez eventos +{ "action": "replaySession", "sessionId": "session-...", "maxEvents": 10 } + // Lista os replays existentes { "action": "listReplays" } @@ -100,7 +105,7 @@ Construa um replay logo após a sessão terminar — tendo ela completado ou fal ## Datasets de falha: agrupando o que continua quebrando -Um único replay conta sobre uma execução. Um **dataset de falha** varre vários replays para montar um corpus de falhas e então agrupa falhas relacionadas em clusters, para você ver quais problemas se repetem. +Um único replay conta sobre uma execução. Um **dataset de falha** processa sessões com um worker por padrão (configurável até quatro), retém no máximo 10.000 falhas por padrão e informa `partial` e `omittedFailureCount` quando o limite é atingido. ### Como as falhas são coletadas diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 27a42cab..308bb8c6 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -168,4 +168,47 @@ describe('HarnessRuntimeStateService', () => { })).resolves.toMatchObject({ event: 'after.stale.lock' }); expect(await fs.pathExists(lockFile)).toBe(false); }); + + it('streams bounded newest-first trace pages across rotated segments', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'hooks.json'), { + trace: { rotationBytes: 64 * 1024, retainedSegments: 8, maxSessionBytes: 1024 * 1024 }, + }); + const session = await service.createSession({ name: 'paged' }); + for (let index = 0; index < 18; index += 1) { + await service.appendTrace(session.id, { level: 'info', event: 'page.event', message: `event-${index}`, data: { index, payload: 'x'.repeat(8 * 1024) } }); + } + + const first = await service.listTracePage(session.id, { limit: 5, event: 'page.event' }); + const second = await service.listTracePage(session.id, { limit: 5, event: 'page.event', cursor: first.nextCursor }); + + expect(first.items.map(item => item.data?.index)).toEqual([17, 16, 15, 14, 13]); + expect(second.items.map(item => item.data?.index)).toEqual([12, 11, 10, 9, 8]); + expect(first).toMatchObject({ hasMore: true, recordsReturned: 5, cursorVersion: 1, malformedCount: 0 }); + expect(first.scannedBytes).toBeLessThan(256 * 1024); + }); + + it('skips malformed terminal trace lines and rejects oversized pages', async () => { + const session = await service.createSession({ name: 'malformed' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + await fs.appendFile(traceFile, '{"partial":', 'utf8'); + + const page = await service.listTracePage(session.id, { limit: 1 }); + expect(page.items).toHaveLength(1); + expect(page.malformedCount).toBe(1); + await expect(service.listTracePage(session.id, { limit: 1001 })).rejects.toThrow('between 1 and 1000'); + await expect(service.listSessionPage({ limit: 201 })).rejects.toThrow('between 1 and 200'); + await expect(service.listTracePage(session.id, { cursor: 'not-a-cursor' })).rejects.toMatchObject({ + code: 'INVALID_RUNTIME_HISTORY_CURSOR', + }); + }); + + it('maintains a latest sensor summary without scanning trace history', async () => { + const session = await service.createSession({ name: 'sensor-summary' }); + await service.appendTrace(session.id, { level: 'error', event: 'sensor.run', message: 'first', data: { run: { sensorId: 'tests', status: 'failed', createdAt: '2025-01-01' } } }); + await service.appendTrace(session.id, { level: 'info', event: 'sensor.run', message: 'second', data: { run: { sensorId: 'tests', status: 'passed', createdAt: '2025-01-02' } } }); + + const summary = await service.getSensorSummary(session.id); + expect(summary.latestBySensor.tests).toMatchObject({ status: 'passed' }); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'sensor-summary.json'))).toBe(true); + }); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 38ee6f97..fe4a27b8 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -17,6 +17,16 @@ import { loadGenericTraceEventMaxBytes, loadHookTracePolicy, } from '../../../application/hooks/hookTracePolicy'; +import { + boundedLimit, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + RuntimeHistoryCursorError, + type RuntimeHistoryDirection, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../../../application/history/runtimeHistory'; const traceWriteQueues = new Map>(); @@ -164,6 +174,92 @@ export interface HarnessRuntimeStatePort { listArtifacts(sessionId: string): Promise; checkpointSession(sessionId: string, input?: CheckpointInput): Promise; listCheckpoints(sessionId: string): Promise; + listTracePage(sessionId: string, query?: HarnessTracePageQuery): Promise>; + listSessionPage(query?: RuntimeHistoryQuery): Promise>; + listArtifactPage(sessionId: string, query?: RuntimeHistoryQuery): Promise>; + getSensorSummary(sessionId: string): Promise; +} + +export interface HarnessTracePageQuery extends RuntimeHistoryQuery { + event?: string; + level?: HarnessTraceLevel; + createdAfter?: string; + createdBefore?: string; +} + +export interface HarnessSensorSummary { + version: 1; + updatedAt: string; + latestBySensor: Record; +} + +interface TraceCursorPosition { + file: string; + offset: number; + fingerprint: string; +} + +interface TraceLine { + line: string; + nextOffset: number; + bytesRead: number; +} + +async function* readLinesForward(file: string, startOffset = 0): AsyncGenerator { + const handle = await nodeFs.open(file, 'r'); + const chunk = Buffer.allocUnsafe(64 * 1024); + let position = startOffset; + let carry = Buffer.alloc(0); + let carryStart = startOffset; + try { + while (true) { + const { bytesRead } = await handle.read(chunk, 0, chunk.length, position); + if (bytesRead === 0) break; + const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : Buffer.from(chunk.subarray(0, bytesRead)); + let lineStart = 0; + for (let index = 0; index < data.length; index += 1) { + if (data[index] !== 0x0a) continue; + const nextOffset = carryStart + index + 1; + yield { line: data.subarray(lineStart, index).toString('utf8').replace(/\r$/, ''), nextOffset, bytesRead }; + lineStart = index + 1; + } + carry = Buffer.from(data.subarray(lineStart)); + carryStart += lineStart; + position += bytesRead; + } + if (carry.length > 0) yield { line: carry.toString('utf8').replace(/\r$/, ''), nextOffset: position, bytesRead: 0 }; + } finally { + await handle.close(); + } +} + +async function* readLinesReverse(file: string, startOffset?: number): AsyncGenerator { + const handle = await nodeFs.open(file, 'r'); + const size = (await handle.stat()).size; + let position = Math.min(startOffset ?? size, size); + let carry = Buffer.alloc(0); + try { + while (position > 0) { + const length = Math.min(64 * 1024, position); + position -= length; + const chunk = Buffer.allocUnsafe(length); + const { bytesRead } = await handle.read(chunk, 0, length, position); + const data = carry.length ? Buffer.concat([chunk.subarray(0, bytesRead), carry]) : Buffer.from(chunk.subarray(0, bytesRead)); + const newlines: number[] = []; + for (let index = 0; index < data.length; index += 1) if (data[index] === 0x0a) newlines.push(index); + if (newlines.length === 0) { carry = data; continue; } + for (let index = newlines.length - 1; index >= 0; index -= 1) { + const lineStart = newlines[index] + 1; + const lineEnd = index + 1 < newlines.length ? newlines[index + 1] : data.length; + const line = data.subarray(lineStart, lineEnd).toString('utf8').replace(/\r?\n$/, '').replace(/\r$/, ''); + if (line.length > 0) yield { line, nextOffset: position + lineStart, bytesRead: index === newlines.length - 1 ? bytesRead : 0 }; + } + carry = Buffer.from(data.subarray(0, newlines[0])); + } + if (carry.length > 0) yield { line: carry.toString('utf8').replace(/\r$/, ''), nextOffset: 0, bytesRead: 0 }; + } finally { + await handle.close(); + } } export interface CreateSessionInput { @@ -245,6 +341,10 @@ export class HarnessRuntimeStateService { return this.layout.sessionArtifactFile(sessionId, artifactId); } + private sensorSummaryFile(sessionId: string): string { + return path.join(this.layout.sessionDir(sessionId), 'sensor-summary.json'); + } + private async ensureSessionDir(sessionId: string): Promise { await fs.ensureDir(this.layout.sessionDir(sessionId)); } @@ -339,10 +439,40 @@ export class HarnessRuntimeStateService { } await fs.appendFile(activeFile, serialized, 'utf8'); + await this.updateSensorSummary(sessionId, trace); await this.pruneTraceSegments(sessionId); return rotationTrace; } + private async updateSensorSummary(sessionId: string, trace: HarnessTraceRecord): Promise { + if (trace.event !== 'sensor.run' || !trace.data?.run || typeof trace.data.run !== 'object') return; + const run = trace.data.run as Record; + if (typeof run.sensorId !== 'string') return; + const current = await this.getSensorSummary(sessionId); + current.latestBySensor[run.sensorId] = run; + current.updatedAt = trace.createdAt; + const target = this.sensorSummaryFile(sessionId); + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`; + await fs.writeJson(temporary, current, { spaces: 2 }); + await fs.rename(temporary, target); + } + + async getSensorSummary(sessionId: string): Promise { + const target = this.sensorSummaryFile(sessionId); + if (await fs.pathExists(target)) { + try { return await fs.readJson(target) as HarnessSensorSummary; } catch { /* migrate below */ } + } + const latestBySensor: Record = {}; + for await (const trace of this.iterateTraces(sessionId)) { + const run = trace.data?.run as Record | undefined; + if (trace.event === 'sensor.run' && typeof run?.sensorId === 'string') latestBySensor[run.sensorId] = run; + } + const summary: HarnessSensorSummary = { version: 1, updatedAt: nowIso(), latestBySensor }; + await this.ensureSessionDir(sessionId); + await fs.writeJson(target, summary, { spaces: 2 }); + return summary; + } + private async recordTrace(sessionId: string, trace: HarnessTraceRecord): Promise { // Preserve the established missing/corrupt-session error contract before creating a lock file. if (!fs.pathExistsSync(this.sessionFile(sessionId))) { @@ -394,23 +524,54 @@ export class HarnessRuntimeStateService { } async listSessions(): Promise { - await this.ensureLayout(); - const entries = await fs.readdir(this.sessionsPath, { withFileTypes: true }); const sessions: HarnessSessionRecord[] = []; - for (const entry of entries) { - if (!entry.isDirectory()) { - continue; - } + let cursor: string | undefined; + do { + const page = await this.listSessionPage({ limit: 200, cursor }); + sessions.push(...page.items); + cursor = page.nextCursor; + } while (cursor); + return sessions; + } + + async listSessionPage(query: RuntimeHistoryQuery = {}): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, 50, 200, 'sessions'); + const direction = query.direction ?? 'newest'; + const binding = queryBinding({ direction }); + const boundary = decodeHistoryCursor<{ updatedAt: string; id: string }>(query.cursor, 'sessions', binding); + await this.ensureLayout(); + const selected: HarnessSessionRecord[] = []; + let recordsScanned = 0; + const directory = await nodeFs.opendir(this.sessionsPath); + for await (const entry of directory) { + if (!entry.isDirectory()) continue; try { - const file = this.sessionFile(entry.name); - sessions.push((await fs.readJson(file)) as HarnessSessionRecord); - } catch { - // Skip sessions with missing or unparseable session.json. - continue; - } + const session = await fs.readJson(this.sessionFile(entry.name)) as HarnessSessionRecord; + recordsScanned += 1; + const key = `${session.updatedAt}\0${session.id}`; + const boundaryKey = boundary ? `${boundary.updatedAt}\0${boundary.id}` : undefined; + if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; + selected.push(session); + selected.sort((a, b) => direction === 'newest' + ? b.updatedAt.localeCompare(a.updatedAt) || b.id.localeCompare(a.id) + : a.updatedAt.localeCompare(b.updatedAt) || a.id.localeCompare(b.id)); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt legacy records */ } } - - return sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { + items, + nextCursor: hasMore && last ? encodeHistoryCursor('sessions', binding, { updatedAt: last.updatedAt, id: last.id }) : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - started, + }; } async getSession(sessionId: string): Promise { @@ -475,48 +636,136 @@ export class HarnessRuntimeStateService { } async listArtifacts(sessionId: string): Promise { - const dir = this.layout.sessionArtifactsDir(sessionId); - if (!(await fs.pathExists(dir))) { - return []; - } - - const entries = await fs.readdir(dir); const artifacts: HarnessArtifactRecord[] = []; - for (const entry of entries.filter((entry) => entry.endsWith('.json'))) { - try { - artifacts.push((await fs.readJson(path.join(dir, entry))) as HarnessArtifactRecord); - } catch { - // Skip missing or unparseable artifact files. - continue; + let cursor: string | undefined; + do { + const page = await this.listArtifactPage(sessionId, { limit: 200, cursor, direction: 'oldest' }); + artifacts.push(...page.items); + cursor = page.nextCursor; + } while (cursor); + return artifacts; + } + + async listArtifactPage(sessionId: string, query: RuntimeHistoryQuery = {}): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, 50, 200, 'artifacts'); + const direction = query.direction ?? 'newest'; + const binding = queryBinding({ sessionId, direction }); + const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'artifacts', binding); + const dir = this.layout.sessionArtifactsDir(sessionId); + const selected: HarnessArtifactRecord[] = []; + let recordsScanned = 0; + if (await fs.pathExists(dir)) { + const directory = await nodeFs.opendir(dir); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const artifact = await fs.readJson(path.join(dir, entry.name)) as HarnessArtifactRecord; + recordsScanned += 1; + const key = `${artifact.createdAt}\0${artifact.id}`; + const boundaryKey = boundary ? `${boundary.createdAt}\0${boundary.id}` : undefined; + if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; + selected.push(artifact); + selected.sort((a, b) => direction === 'newest' + ? b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id) + : a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt legacy records */ } } } - - return artifacts.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { + items, + nextCursor: hasMore && last ? encodeHistoryCursor('artifacts', binding, { createdAt: last.createdAt, id: last.id }) : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - started, + }; } async listTraces(sessionId: string): Promise { - const activeFile = this.traceFile(sessionId); - const files = [ - ...(await this.listTraceSegmentFiles(sessionId)), - ...(await fs.pathExists(activeFile) ? [activeFile] : []), - ]; - if (files.length === 0) { - return []; + const traces: HarnessTraceRecord[] = []; + for await (const trace of this.iterateTraces(sessionId)) traces.push(trace); + return traces; + } + + async *iterateTraces(sessionId: string): AsyncGenerator { + const files = [...await this.listTraceSegmentFiles(sessionId)]; + const active = this.traceFile(sessionId); + if (await fs.pathExists(active)) files.push(active); + for (const file of files) { + for await (const item of readLinesForward(file)) { + if (!item.line.trim()) continue; + try { yield JSON.parse(item.line) as HarnessTraceRecord; } catch { /* bounded malformed diagnostic in pages */ } + } } + } - const contents = await Promise.all(files.map((file) => fs.readFile(file, 'utf8'))); - return contents.join('') - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) - .flatMap((line) => { - try { - return [JSON.parse(line) as HarnessTraceRecord]; - } catch { - // Drop malformed/partially-written trace lines. - return []; - } - }); + async listTracePage(sessionId: string, query: HarnessTracePageQuery = {}): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, 100, 1000, 'traces'); + const direction: RuntimeHistoryDirection = query.direction ?? 'newest'; + const filters = { sessionId, direction, event: query.event, level: query.level, createdAfter: query.createdAfter, createdBefore: query.createdBefore }; + const binding = queryBinding(filters); + const cursor = decodeHistoryCursor(query.cursor, 'traces', binding); + const active = this.traceFile(sessionId); + const chronological = [...await this.listTraceSegmentFiles(sessionId), ...(await fs.pathExists(active) ? [active] : [])]; + const stats = await Promise.all(chronological.map(async file => { + const stat = await nodeFs.stat(file); + return { file, size: stat.size, mtime: stat.mtimeMs }; + })); + const fingerprint = queryBinding(stats.map(item => [path.basename(item.file), item.size, item.mtime])); + if (cursor && cursor.fingerprint !== fingerprint) { + throw new RuntimeHistoryCursorError('Invalid or stale runtime history cursor: trace segments changed'); + } + const files = direction === 'newest' ? [...chronological].reverse() : chronological; + let startIndex = cursor ? files.findIndex(file => path.basename(file) === cursor.file) : 0; + if (cursor && startIndex < 0) { + throw new RuntimeHistoryCursorError('Invalid or stale runtime history cursor: segment no longer exists'); + } + const items: HarnessTraceRecord[] = []; + let recordsScanned = 0; + let scannedBytes = 0; + let malformedCount = 0; + let hasMore = false; + let nextPosition: TraceCursorPosition | undefined; + outer: for (let index = startIndex; index < files.length; index += 1) { + const file = files[index]; + const initialOffset = index === startIndex ? cursor?.offset : undefined; + const iterator = direction === 'newest' ? readLinesReverse(file, initialOffset) : readLinesForward(file, initialOffset ?? 0); + for await (const line of iterator) { + scannedBytes += line.bytesRead; + if (!line.line.trim()) continue; + let trace: HarnessTraceRecord; + try { trace = JSON.parse(line.line) as HarnessTraceRecord; } catch { malformedCount += 1; continue; } + recordsScanned += 1; + if (query.event && trace.event !== query.event) continue; + if (query.level && trace.level !== query.level) continue; + if (query.createdAfter && trace.createdAt <= query.createdAfter) continue; + if (query.createdBefore && trace.createdAt >= query.createdBefore) continue; + if (items.length === limit) { hasMore = true; break outer; } + items.push(trace); + nextPosition = { file: path.basename(file), offset: line.nextOffset, fingerprint }; + } + if (items.length > 0) nextPosition = { file: path.basename(files[index + 1] ?? file), offset: direction === 'newest' ? Number.MAX_SAFE_INTEGER : 0, fingerprint }; + } + return { + items, + nextCursor: hasMore && nextPosition ? encodeHistoryCursor('traces', binding, nextPosition) : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + scannedBytes, + malformedCount, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - started, + }; } async checkpointSession(sessionId: string, input: CheckpointInput = {}): Promise { diff --git a/src/harness/application/actions/actionService.ts b/src/harness/application/actions/actionService.ts index c24cc28b..70b27c45 100644 --- a/src/harness/application/actions/actionService.ts +++ b/src/harness/application/actions/actionService.ts @@ -87,6 +87,13 @@ export interface HarnessActionInput { datasetId?: string; sessionIds?: string[]; includeSuccessfulSessions?: boolean; + limit?: number; + cursor?: string; + direction?: 'oldest' | 'newest'; + createdAfter?: string; + createdBefore?: string; + concurrency?: number; + maxFailures?: number; scope?: 'sensor' | 'artifact' | 'handoff' | 'workflow' | 'task' | 'risk'; effect?: 'allow' | 'deny' | 'require_approval'; target?: 'tool' | 'action' | 'path' | 'risk'; @@ -195,9 +202,12 @@ export class HarnessActionService { }), }; case 'listSessions': + const sessionPage = await this.executionService.listSessionPage({ limit: params.limit, cursor: params.cursor, direction: params.direction }); + const { items: sessions, ...sessionPagination } = sessionPage; return { success: true, - sessions: await this.executionService.listSessions(), + sessions, + page: sessionPagination, }; case 'getSession': return { @@ -215,9 +225,12 @@ export class HarnessActionService { }), }; case 'listTraces': + const tracePage = await this.executionService.listTracePage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction, event: params.event, level: params.level, createdAfter: params.createdAfter, createdBefore: params.createdBefore }); + const { items: traces, ...tracePagination } = tracePage; return { success: true, - traces: await this.executionService.listTraces(params.sessionId!), + traces, + page: tracePagination, }; case 'addArtifact': return { @@ -231,9 +244,12 @@ export class HarnessActionService { }), }; case 'listArtifacts': + const artifactPage = await this.executionService.listArtifactPage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction }); + const { items: artifacts, ...artifactPagination } = artifactPage; return { success: true, - artifacts: await this.executionService.listArtifacts(params.sessionId!), + artifacts, + page: artifactPagination, }; case 'checkpoint': return { @@ -351,9 +367,12 @@ export class HarnessActionService { }), }; case 'listReplays': + const replayPage = await this.executionService.listReplayPage({ limit: params.limit, cursor: params.cursor, sessionId: params.sessionId }); + const { items: replays, ...replayPagination } = replayPage; return { success: true, - replays: await this.executionService.listReplays(params.sessionId), + replays, + page: replayPagination, }; case 'getReplay': return { @@ -366,12 +385,17 @@ export class HarnessActionService { dataset: await this.executionService.buildFailureDataset({ sessionIds: params.sessionIds, includeSuccessfulSessions: params.includeSuccessfulSessions, + concurrency: params.concurrency, + maxFailures: params.maxFailures, }), }; case 'listDatasets': + const datasetPage = await this.executionService.listDatasetPage({ limit: params.limit, cursor: params.cursor }); + const { items: datasets, ...datasetPagination } = datasetPage; return { success: true, - datasets: await this.executionService.listDatasets(), + datasets, + page: datasetPagination, }; case 'getDataset': return { diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index b9bde628..4aec8c9d 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -14,7 +14,6 @@ import { resolveRuntimeLayoutFromRepo, type RuntimeLayout } from '../../../share import type { HarnessArtifactRecord, HarnessRuntimeStatePort, - HarnessTraceRecord, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { HarnessSensorRun } from '../sensors/sensorsService'; @@ -377,10 +376,8 @@ export class HarnessTaskContractsService { throw new Error(`Task contract not found: ${taskId}`); } - const traces: HarnessTraceRecord[] = sessionId ? await this.options.stateService.listTraces(sessionId) : []; - const sensorRuns = traces - .filter((trace) => trace.event === 'sensor.run' && trace.data?.run) - .map((trace) => trace.data!.run as HarnessSensorRun); + const sensorSummary = sessionId ? await this.options.stateService.getSensorSummary(sessionId) : undefined; + const sensorRuns = sensorSummary ? Object.values(sensorSummary.latestBySensor) as HarnessSensorRun[] : []; const latestRunsBySensor = new Map(); for (const run of sensorRuns) { const current = latestRunsBySensor.get(run.sensorId); @@ -388,7 +385,15 @@ export class HarnessTaskContractsService { latestRunsBySensor.set(run.sensorId, run); } } - const artifacts = sessionId ? await this.options.stateService.listArtifacts(sessionId) : []; + const artifacts: HarnessArtifactRecord[] = []; + if (sessionId) { + let cursor: string | undefined; + do { + const page = await this.options.stateService.listArtifactPage(sessionId, { limit: 200, cursor, direction: 'oldest' }); + artifacts.push(...page.items); + cursor = page.nextCursor; + } while (cursor); + } const matchedSensorRuns = contract.requiredSensors .map((sensorId) => latestRunsBySensor.get(sensorId)) diff --git a/src/harness/application/datasets/__tests__/datasetService.test.ts b/src/harness/application/datasets/__tests__/datasetService.test.ts index a5505d1d..851d8fb2 100644 --- a/src/harness/application/datasets/__tests__/datasetService.test.ts +++ b/src/harness/application/datasets/__tests__/datasetService.test.ts @@ -4,6 +4,7 @@ import * as path from 'path'; import { HarnessExecutionService } from '../../execution/executionService'; import { HarnessDatasetService } from '../datasetService'; +import { HarnessReplayService } from '../../replay/replayService'; describe('HarnessDatasetService', () => { let tempDir: string; @@ -61,4 +62,35 @@ describe('HarnessDatasetService', () => { expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays'))).toBe(false); expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'evaluations', 'datasets', `${dataset.id}.json`))).toBe(true); }); + + it('bounds session concurrency and caps retained failure records', async () => { + const sessions = []; + for (let index = 0; index < 6; index += 1) { + const session = await execution.createSession({ name: `failure-${index}` }); + await execution.appendTrace(session.id, { level: 'error', event: 'task.failed', message: `failed-${index}` }); + sessions.push(session); + } + const replay = new HarnessReplayService({ repoPath: tempDir }); + let active = 0; + let peak = 0; + const bounded = new HarnessDatasetService({ + repoPath: tempDir, + dependencies: { + replayService: { + buildReplay: async (...args) => { + active += 1; + peak = Math.max(peak, active); + await new Promise(resolve => setTimeout(resolve, 5)); + try { return await replay.buildReplay(...args); } finally { active -= 1; } + }, + }, + }, + }); + + const dataset = await bounded.buildFailureDataset({ sessionIds: sessions.map(item => item.id), includeSuccessfulSessions: true, concurrency: 2, maxFailures: 2 }); + expect(peak).toBeLessThanOrEqual(2); + expect(dataset.failures).toHaveLength(2); + expect(dataset.partial).toBe(true); + expect(dataset.omittedFailureCount).toBe(4); + }); }); diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index 96263359..b989a4c3 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -7,6 +7,7 @@ import { HarnessRuntimeStateService, type HarnessRuntimeStatePort } from '../../ import { HarnessReplayService, type HarnessReplayRecord } from '../replay/replayService'; import { HarnessSensorsService } from '../sensors/sensorsService'; import { HarnessTaskContractsService } from '../contracts/taskContractsService'; +import { boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; export type HarnessFailureKind = 'sensor' | 'task' | 'session' | 'trace'; @@ -41,6 +42,8 @@ export interface HarnessFailureDataset { clusterCount: number; failures: HarnessFailureRecord[]; clusters: HarnessFailureCluster[]; + partial: boolean; + omittedFailureCount: number; } export interface HarnessDatasetServiceOptions { @@ -51,6 +54,17 @@ export interface HarnessDatasetServiceOptions { export interface BuildHarnessDatasetOptions { sessionIds?: string[]; includeSuccessfulSessions?: boolean; + concurrency?: number; + maxFailures?: number; +} + +export interface HarnessDatasetSummary { + id: string; + createdAt: string; + sessionCount: number; + failureCount: number; + clusterCount: number; + partial: boolean; } export interface HarnessDatasetDependencies { @@ -251,35 +265,57 @@ export class HarnessDatasetService { } async buildFailureDataset(options: BuildHarnessDatasetOptions = {}): Promise { - const sessions = options.sessionIds?.length - ? await Promise.all(options.sessionIds.map(sessionId => this.stateService.getSession(sessionId))) - : await this.stateService.listSessions(); + const concurrency = boundedLimit(options.concurrency, 1, 4, 'dataset concurrency'); + const maxFailures = boundedLimit(options.maxFailures, 10_000, 10_000, 'dataset failures'); + const sessions = []; + if (options.sessionIds?.length) { + for (const sessionId of options.sessionIds) sessions.push(await this.stateService.getSession(sessionId)); + } else { + let cursor: string | undefined; + do { + const page = await this.stateService.listSessionPage({ limit: 200, cursor }); + sessions.push(...page.items); + cursor = page.nextCursor; + } while (cursor); + } const selectedSessions = options.includeSuccessfulSessions ? sessions : sessions.filter(session => session.status !== 'completed'); - const replays = await Promise.all(selectedSessions.map(session => this.replayService.buildReplay(session.id, { includePayloads: false }))); - const sensorFailures = replays.flatMap(replay => buildSensorFailures(replay)); - const taskFailures: HarnessFailureRecord[] = []; - for (const replay of replays) { - taskFailures.push(...await buildTaskFailures(replay, this.taskContractsService)); - } - const sessionFailures = replays.flatMap(replay => buildSessionFailure(replay)); - const traceFailures = replays.flatMap(replay => buildTraceFailures(replay)); - - const failures = [...sensorFailures, ...taskFailures, ...sessionFailures, ...traceFailures]; + const failures: HarnessFailureRecord[] = []; + let omittedFailureCount = 0; + let nextIndex = 0; + const retain = (records: HarnessFailureRecord[]) => { + const available = Math.max(0, maxFailures - failures.length); + failures.push(...records.slice(0, available)); + omittedFailureCount += Math.max(0, records.length - available); + }; + const worker = async () => { + while (true) { + const index = nextIndex++; + if (index >= selectedSessions.length) return; + const replay = await this.replayService.buildReplay(selectedSessions[index].id, { includePayloads: false, maxEvents: 1000 }); + retain(buildSensorFailures(replay)); + retain(await buildTaskFailures(replay, this.taskContractsService)); + retain(buildSessionFailure(replay)); + retain(buildTraceFailures(replay)); + } + }; + await Promise.all(Array.from({ length: Math.min(concurrency, selectedSessions.length) }, () => worker())); const clusters = clusterFailures(failures); const dataset: HarnessFailureDataset = { id: randomUUID(), createdAt: nowIso(), repoPath: this.repoPath, sessionCount: selectedSessions.length, - replayCount: replays.length, + replayCount: selectedSessions.length, failureCount: failures.length, clusterCount: clusters.length, failures, clusters, + partial: omittedFailureCount > 0, + omittedFailureCount, }; await this.ensureLayout(); @@ -288,15 +324,37 @@ export class HarnessDatasetService { } async listDatasets(): Promise { + const page = await this.listDatasetPage(); + const datasets: HarnessFailureDataset[] = []; + for (const summary of page.items) datasets.push(await this.getDataset(summary.id)); + return datasets; + } + + async listDatasetPage(query: RuntimeHistoryQuery = {}): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, 25, 100, 'dataset summaries'); + const binding = queryBinding({ resource: 'datasets' }); + const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'datasets', binding); await this.ensureLayout(); - const entries = await fs.readdir(this.datasetsPath); - const datasets = await Promise.all( - entries - .filter(entry => entry.endsWith('.json')) - .map(async entry => fs.readJson(path.join(this.datasetsPath, entry)) as Promise) - ); - - return datasets.sort((left, right) => right.createdAt.localeCompare(left.createdAt)); + const selected: HarnessDatasetSummary[] = []; + let recordsScanned = 0; + const directory = await fs.opendir(this.datasetsPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const dataset = await fs.readJson(path.join(this.datasetsPath, entry.name)) as HarnessFailureDataset; + recordsScanned += 1; + const key = `${dataset.createdAt}\0${dataset.id}`; + if (boundary && key >= `${boundary.createdAt}\0${boundary.id}`) continue; + selected.push({ id: dataset.id, createdAt: dataset.createdAt, sessionCount: dataset.sessionCount, failureCount: dataset.failureCount, clusterCount: dataset.clusterCount, partial: dataset.partial ?? false }); + selected.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { items, nextCursor: hasMore && last ? encodeHistoryCursor('datasets', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, cursorVersion: 1, partial: hasMore, durationMs: Date.now() - started }; } async getDataset(datasetId: string): Promise { diff --git a/src/harness/application/execution/executionService.ts b/src/harness/application/execution/executionService.ts index 8b30a154..1b7f66cf 100644 --- a/src/harness/application/execution/executionService.ts +++ b/src/harness/application/execution/executionService.ts @@ -95,6 +95,10 @@ export class HarnessExecutionService { return this.state.listSessions(); } + listSessionPage(query: Parameters[0] = {}) { + return this.state.listSessionPage(query); + } + getSession(sessionId: string) { return this.state.getSession(sessionId); } @@ -107,6 +111,10 @@ export class HarnessExecutionService { return this.state.listTraces(sessionId); } + listTracePage(sessionId: string, query: Parameters[1] = {}) { + return this.state.listTracePage(sessionId, query); + } + async addArtifact(sessionId: string, input: AddArtifactInput) { await this.policy.authorize({ tool: 'harness', @@ -122,6 +130,10 @@ export class HarnessExecutionService { return this.state.listArtifacts(sessionId); } + listArtifactPage(sessionId: string, query: Parameters[1] = {}) { + return this.state.listArtifactPage(sessionId, query); + } + async checkpointSession(sessionId: string, input: CheckpointInput = {}) { await this.policy.authorize({ tool: 'harness', @@ -276,6 +288,10 @@ export class HarnessExecutionService { return this.replay.listReplays(sessionId ? { sessionId } : undefined); } + listReplayPage(query: Parameters[0] = {}) { + return this.replay.listReplayPage(query); + } + getReplay(replayId: string): Promise { return this.replay.getReplay(replayId); } @@ -295,6 +311,10 @@ export class HarnessExecutionService { return this.datasets.listDatasets(); } + listDatasetPage(query: Parameters[0] = {}) { + return this.datasets.listDatasetPage(query); + } + getDataset(datasetId: string): Promise { return this.datasets.getDataset(datasetId); } diff --git a/src/harness/application/history/__tests__/runtimeHistory.load.test.ts b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts new file mode 100644 index 00000000..500dcc97 --- /dev/null +++ b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts @@ -0,0 +1,41 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; +import { HarnessRuntimeStateService } from '../../../adapters/out/runtimeState/runtimeStateService'; + +const loadDescribe = process.env.DOTCONTEXT_RUNTIME_LOAD_TESTS === '1' ? describe : describe.skip; + +loadDescribe('runtime history load acceptance', () => { + jest.setTimeout(120_000); + let tempDir: string; + beforeEach(async () => { tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'runtime-history-load-')); }); + afterEach(async () => { await fs.remove(tempDir); }); + + it('returns 100 records from one million JSONL lines with bounded incremental RSS', async () => { + const state = new HarnessRuntimeStateService({ repoPath: tempDir }); + const session = await state.createSession({ name: 'million-lines' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const line = `${JSON.stringify({ id: 'load', sessionId: session.id, level: 'info', event: 'load', message: 'bounded', createdAt: '2026-01-01T00:00:00.000Z', data: { payload: 'x'.repeat(900) } })}\n`; + const block = line.repeat(10_000); + const handle = await fs.open(traceFile, 'w'); + try { for (let index = 0; index < 100; index += 1) await fs.write(handle, block); } finally { await fs.close(handle); } + global.gc?.(); + const before = process.memoryUsage().rss; + const page = await state.listTracePage(session.id, { limit: 100 }); + global.gc?.(); + expect(page.items).toHaveLength(100); + expect(process.memoryUsage().rss - before).toBeLessThan(32 * 1024 * 1024); + }); + + it('keeps a 1,000-session page bounded', async () => { + const sessionsDir = path.join(tempDir, '.context', 'runtime', 'sessions'); + for (let index = 0; index < 1000; index += 1) { + const id = `session-${index.toString().padStart(4, '0')}`; + await fs.outputJson(path.join(sessionsDir, id, 'session.json'), { id, name: id, status: 'completed', repoPath: tempDir, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: new Date(1_700_000_000_000 + index).toISOString(), startedAt: '2026-01-01T00:00:00.000Z', traceCount: 0, artifactCount: 0, checkpointCount: 0, checkpoints: [] }); + } + const page = await new HarnessRuntimeStateService({ repoPath: tempDir }).listSessionPage(); + expect(page.items).toHaveLength(50); + expect(page.hasMore).toBe(true); + expect(page.recordsScanned).toBe(1000); + }); +}); diff --git a/src/harness/application/history/__tests__/runtimeRetentionService.test.ts b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts new file mode 100644 index 00000000..05cfa7c3 --- /dev/null +++ b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts @@ -0,0 +1,38 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; +import { HarnessRuntimeStateService } from '../../../adapters/out/runtimeState/runtimeStateService'; +import { HarnessRuntimeRetentionService } from '../runtimeRetentionService'; + +describe('HarnessRuntimeRetentionService', () => { + let tempDir: string; + beforeEach(async () => { tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'runtime-retention-')); }); + afterEach(async () => { await fs.remove(tempDir); }); + + it('reports dry-run bytes and never prunes active or workflow-bound sessions', async () => { + const state = new HarnessRuntimeStateService({ repoPath: tempDir }); + const active = await state.createSession({ name: 'active' }); + const bound = await state.createSession({ name: 'bound' }); + await state.completeSession(bound.id); + const old = '2020-01-01T00:00:00.000Z'; + const boundFile = path.join(tempDir, '.context', 'runtime', 'sessions', bound.id, 'session.json'); + await fs.writeJson(boundFile, { ...await fs.readJson(boundFile), updatedAt: old }); + await fs.outputJson(path.join(tempDir, '.context', 'runtime', 'workflows', 'prevc.json'), { binding: { sessionId: bound.id } }); + const expired = await state.createSession({ name: 'expired' }); + await state.completeSession(expired.id); + const expiredFile = path.join(tempDir, '.context', 'runtime', 'sessions', expired.id, 'session.json'); + await fs.writeJson(expiredFile, { ...await fs.readJson(expiredFile), updatedAt: old }); + + const retention = new HarnessRuntimeRetentionService(tempDir); + const report = await retention.prune({ dryRun: true, now: new Date('2026-01-01T00:00:00.000Z') }); + expect(report.candidates.map(item => item.path)).toContain(path.dirname(expiredFile)); + expect(report.candidates.map(item => item.path)).not.toContain(path.dirname(boundFile)); + expect(report.protectedSessionIds).toEqual(expect.arrayContaining([active.id, bound.id])); + expect(report.pruneBytes).toBeGreaterThan(0); + expect(await fs.pathExists(expiredFile)).toBe(true); + + await retention.prune({ dryRun: false, now: new Date('2026-01-01T00:00:00.000Z') }); + expect(await fs.pathExists(expiredFile)).toBe(false); + expect(await fs.pathExists(boundFile)).toBe(true); + }); +}); diff --git a/src/harness/application/history/index.ts b/src/harness/application/history/index.ts new file mode 100644 index 00000000..16b833ec --- /dev/null +++ b/src/harness/application/history/index.ts @@ -0,0 +1,2 @@ +export * from './runtimeHistory'; +export * from './runtimeRetentionService'; diff --git a/src/harness/application/history/runtimeHistory.ts b/src/harness/application/history/runtimeHistory.ts new file mode 100644 index 00000000..dd2170fe --- /dev/null +++ b/src/harness/application/history/runtimeHistory.ts @@ -0,0 +1,69 @@ +import { createHash } from 'crypto'; + +export type RuntimeHistoryDirection = 'oldest' | 'newest'; + +export interface RuntimeHistoryQuery { + limit?: number; + cursor?: string; + direction?: RuntimeHistoryDirection; +} + +export interface RuntimeHistoryPage { + items: T[]; + nextCursor?: string; + hasMore: boolean; + recordsReturned: number; + recordsScanned: number; + scannedBytes?: number; + malformedCount?: number; + cursorVersion: 1; + partial: boolean; + durationMs: number; +} + +export class RuntimeHistoryCursorError extends Error { + readonly code = 'INVALID_RUNTIME_HISTORY_CURSOR'; + + constructor(message: string) { + super(message); + this.name = 'RuntimeHistoryCursorError'; + } +} + +interface CursorEnvelope { + v: 1; + scope: string; + binding: string; + position: T; +} + +export function queryBinding(value: unknown): string { + return createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 20); +} + +export function encodeHistoryCursor(scope: string, binding: string, position: T): string { + return Buffer.from(JSON.stringify({ v: 1, scope, binding, position } satisfies CursorEnvelope)) + .toString('base64url'); +} + +export function decodeHistoryCursor(cursor: string | undefined, scope: string, binding: string): T | undefined { + if (!cursor) return undefined; + try { + const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as CursorEnvelope; + if (parsed.v !== 1 || parsed.scope !== scope || parsed.binding !== binding || parsed.position === undefined) { + throw new Error('cursor does not match this query'); + } + return parsed.position; + } catch (error) { + if (error instanceof RuntimeHistoryCursorError) throw error; + throw new RuntimeHistoryCursorError(`Invalid or stale runtime history cursor: ${(error as Error).message}`); + } +} + +export function boundedLimit(value: number | undefined, defaultLimit: number, maximum: number, resource: string): number { + const limit = value ?? defaultLimit; + if (!Number.isInteger(limit) || limit < 1 || limit > maximum) { + throw new RangeError(`${resource} limit must be an integer between 1 and ${maximum}`); + } + return limit; +} diff --git a/src/harness/application/history/runtimeRetentionService.ts b/src/harness/application/history/runtimeRetentionService.ts new file mode 100644 index 00000000..14de558d --- /dev/null +++ b/src/harness/application/history/runtimeRetentionService.ts @@ -0,0 +1,126 @@ +import * as fs from 'fs-extra'; +import * as path from 'path'; +import { randomUUID } from 'crypto'; +import { resolveRuntimeLayoutFromRepo } from '../../../shared/fs/pathHelpers'; +import type { HarnessSessionRecord } from '../../adapters/out/runtimeState/runtimeStateService'; + +export interface RuntimePruneReport { + dryRun: boolean; + candidates: Array<{ path: string; kind: 'session' | 'replay' | 'dataset'; bytes: number; reason: string }>; + protectedSessionIds: string[]; + pruneBytes: number; + runtimeBytes: number; + durationMs: number; +} + +export interface RuntimePruneOptions { + dryRun?: boolean; + now?: Date; + sessionRetentionDays?: number; + replayRetentionDays?: number; + datasetRetentionDays?: number; + replayLimitPerSession?: number; + datasetLimit?: number; + quotaBytes?: number; +} + +async function fileBytes(target: string): Promise { + const stat = await fs.stat(target); + if (stat.isFile()) return stat.size; + let total = 0; + const directory = await fs.opendir(target); + for await (const entry of directory) total += await fileBytes(path.join(target, entry.name)); + return total; +} + +export class HarnessRuntimeRetentionService { + constructor(private readonly repoPath: string) {} + + async prune(options: RuntimePruneOptions = {}): Promise { + const started = Date.now(); + const layout = resolveRuntimeLayoutFromRepo(this.repoPath); + const now = (options.now ?? new Date()).getTime(); + const activeBinding = await fs.readJson(layout.prevcFile) + .then(value => typeof value?.binding?.sessionId === 'string' ? value.binding.sessionId as string : undefined) + .catch(() => undefined); + const protectedSessionIds = new Set(activeBinding ? [activeBinding] : []); + const candidates: RuntimePruneReport['candidates'] = []; + + if (await fs.pathExists(layout.sessionsDir)) { + const directory = await fs.opendir(layout.sessionsDir); + for await (const entry of directory) { + if (!entry.isDirectory() || entry.name.startsWith('.prune-')) continue; + const target = layout.sessionDir(entry.name); + try { + const session = await fs.readJson(layout.sessionFile(entry.name)) as HarnessSessionRecord; + if (session.status === 'active' || session.status === 'paused' || protectedSessionIds.has(session.id)) { + protectedSessionIds.add(session.id); + continue; + } + const cutoff = (options.sessionRetentionDays ?? 30) * 86_400_000; + if (now - new Date(session.updatedAt).getTime() > cutoff) { + candidates.push({ path: target, kind: 'session', bytes: await fileBytes(target), reason: 'age' }); + } + } catch { /* corrupt state is retained for manual recovery */ } + } + } + + const collectEvaluations = async (dir: string, kind: 'replay' | 'dataset', days: number, keep: number) => { + if (!(await fs.pathExists(dir))) return; + const records: Array<{ path: string; createdAt: string; sessionId?: string; bytes: number }> = []; + const directory = await fs.opendir(dir); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + const target = path.join(dir, entry.name); + try { + const value = await fs.readJson(target) as { createdAt: string; sessionId?: string }; + records.push({ path: target, createdAt: value.createdAt, sessionId: value.sessionId, bytes: (await fs.stat(target)).size }); + } catch { /* retain malformed files */ } + } + records.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + const counts = new Map(); + for (const record of records) { + const group = kind === 'replay' ? record.sessionId ?? 'unknown' : 'datasets'; + const position = (counts.get(group) ?? 0) + 1; + counts.set(group, position); + const expired = now - new Date(record.createdAt).getTime() > days * 86_400_000; + if (expired || position > keep) candidates.push({ path: record.path, kind, bytes: record.bytes, reason: expired ? 'age' : 'count' }); + } + }; + await collectEvaluations(layout.replaysDir, 'replay', options.replayRetentionDays ?? 30, options.replayLimitPerSession ?? 10); + await collectEvaluations(layout.datasetsDir, 'dataset', options.datasetRetentionDays ?? 30, options.datasetLimit ?? 20); + + const runtimeBytes = await fs.pathExists(layout.runtimeDir) ? await fileBytes(layout.runtimeDir) : 0; + const quota = options.quotaBytes ?? 256 * 1024 * 1024; + if (runtimeBytes > quota) { + const already = new Set(candidates.map(item => item.path)); + const eligible: Array<{ path: string; kind: 'session' | 'replay' | 'dataset'; bytes: number; mtime: number }> = []; + for (const dir of [layout.replaysDir, layout.datasetsDir]) { + if (!(await fs.pathExists(dir))) continue; + for (const name of await fs.readdir(dir)) { + const target = path.join(dir, name); + if (already.has(target) || !name.endsWith('.json')) continue; + const stat = await fs.stat(target); + eligible.push({ path: target, kind: dir === layout.replaysDir ? 'replay' : 'dataset', bytes: stat.size, mtime: stat.mtimeMs }); + } + } + eligible.sort((a, b) => a.mtime - b.mtime); + let projected = runtimeBytes - candidates.reduce((sum, item) => sum + item.bytes, 0); + for (const item of eligible) { + if (projected <= quota) break; + candidates.push({ path: item.path, kind: item.kind, bytes: item.bytes, reason: 'quota' }); + projected -= item.bytes; + } + } + + if (options.dryRun === false) { + for (const candidate of candidates) { + if (!(await fs.pathExists(candidate.path))) continue; + const tombstone = path.join(path.dirname(candidate.path), `.prune-${randomUUID()}-${path.basename(candidate.path)}`); + await fs.rename(candidate.path, tombstone); + await fs.remove(tombstone); + } + } + return { dryRun: options.dryRun !== false, candidates, protectedSessionIds: [...protectedSessionIds], pruneBytes: candidates.reduce((sum, item) => sum + item.bytes, 0), runtimeBytes, durationMs: Date.now() - started }; + } +} diff --git a/src/harness/application/index.ts b/src/harness/application/index.ts index 721c0d0f..b299e08b 100644 --- a/src/harness/application/index.ts +++ b/src/harness/application/index.ts @@ -10,6 +10,7 @@ export * from './execution'; export * from './policies'; export * from './replay'; export * from './datasets'; +export * from './history'; export * from '../adapters/out/runtimeState'; export * from '../adapters/out/workflowState'; export * from '../adapters/out/sensors'; diff --git a/src/harness/application/replay/__tests__/replayService.test.ts b/src/harness/application/replay/__tests__/replayService.test.ts index 3ec82077..56921c8a 100644 --- a/src/harness/application/replay/__tests__/replayService.test.ts +++ b/src/harness/application/replay/__tests__/replayService.test.ts @@ -59,4 +59,21 @@ describe('HarnessReplayService', () => { expect(list[0].sessionId).toBe(session.id); expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays', `${replay.id}.json`))).toBe(true); }); + + it('applies maxEvents to materialization, response, and persistence', async () => { + const session = await execution.createSession({ name: 'bounded-replay' }); + for (let index = 0; index < 20; index += 1) { + await execution.appendTrace(session.id, { level: 'info', event: 'step', message: `step-${index}` }); + } + + const replay = await service.replaySession(session.id, { maxEvents: 10 }); + const persisted = await fs.readJson(path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays', `${replay.id}.json`)); + expect(replay.events).toHaveLength(10); + expect(replay.fidelity).toBe('partial'); + expect(replay.omittedCounts.trace).toBeGreaterThan(0); + for (const source of ['artifacts', 'checkpoints', 'traces', 'sensorRuns', 'tasks', 'handoffs']) { + expect((replay[source as keyof typeof replay] as unknown[]).length).toBeLessThanOrEqual(10); + expect((persisted[source] as unknown[]).length).toBeLessThanOrEqual(10); + } + }); }); diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index b110bca7..75d2b239 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -17,6 +17,14 @@ import { type HarnessHandoffContract, type HarnessTaskContract, } from '../contracts/taskContractsService'; +import { + boundedLimit, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../history/runtimeHistory'; export type HarnessReplayEventSource = | 'session' @@ -44,9 +52,12 @@ export interface HarnessReplayRecord { replayedAt: string; fidelity: 'complete' | 'partial'; eventCount: number; + sourceCounts: Record; + omittedCounts: Record; + nextCursor?: string; summary: string; events: HarnessReplayEvent[]; - session: HarnessSessionRecord; + session: Omit & { checkpoints?: never }; artifacts: HarnessArtifactRecord[]; checkpoints: HarnessSessionCheckpoint[]; traces: HarnessTraceRecord[]; @@ -65,6 +76,15 @@ export interface ReplaySessionOptions { maxEvents?: number; } +export interface HarnessReplaySummary { + id: string; + sessionId: string; + createdAt: string; + fidelity: 'complete' | 'partial'; + eventCount: number; + summary: string; +} + export interface HarnessReplayDependencies { stateService: HarnessRuntimeStatePort; sensorsService: Pick; @@ -134,16 +154,20 @@ export class HarnessReplayService { sessionId: string, options: ReplaySessionOptions = {} ): Promise { + const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); const session = await this.stateService.getSession(sessionId); - const [traces, artifacts, checkpoints, sensorRuns, tasks, handoffs] = await Promise.all([ - this.stateService.listTraces(sessionId), - this.stateService.listArtifacts(sessionId), - this.stateService.listCheckpoints(sessionId), + const [tracePage, artifactPage, sensorRuns, tasks, handoffs] = await Promise.all([ + this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest' }), + this.stateService.listArtifactPage(sessionId, { limit: Math.min(maxEvents, 200), direction: 'oldest' }), this.sensorsService.getSessionSensorRuns(sessionId), this.contractsService.listTaskContracts(), this.contractsService.listHandoffContracts(), ]); + const traces = tracePage.items; + const artifacts = artifactPage.items; + const checkpoints = session.checkpoints.slice(0, maxEvents); + const sessionTasks = tasks.filter((task) => task.sessionId === sessionId); const sessionHandoffs = handoffs.filter((handoff) => handoff.sessionId === sessionId); @@ -248,24 +272,46 @@ export class HarnessReplayService { })), ]; - const orderedEvents = sortByCreatedAt(events).slice(0, options.maxEvents ?? Number.MAX_SAFE_INTEGER); + const orderedEvents = sortByCreatedAt(events).slice(0, maxEvents); + const sourceCounts: Record = { + session: 1, + trace: session.traceCount, + artifact: session.artifactCount, + checkpoint: session.checkpointCount, + sensor: sensorRuns.length, + task: sessionTasks.length, + handoff: sessionHandoffs.length, + }; + const includedCounts = orderedEvents.reduce((counts, event) => { + counts[event.source] += 1; + return counts; + }, { session: 0, trace: 0, artifact: 0, checkpoint: 0, sensor: 0, task: 0, handoff: 0 } as Record); + const omittedCounts = Object.fromEntries(Object.entries(sourceCounts).map(([source, count]) => [ + source, + Math.max(0, count - includedCounts[source as HarnessReplayEventSource]), + ])) as Record; + const { checkpoints: _embeddedCheckpoints, ...boundedSession } = session; + const partial = Object.values(omittedCounts).some(count => count > 0); const replay: HarnessReplayRecord = { id: randomUUID(), sessionId, repoPath: this.repoPath, createdAt: nowIso(), replayedAt: nowIso(), - fidelity: orderedEvents.length >= events.length ? 'complete' : 'partial', + fidelity: partial ? 'partial' : 'complete', eventCount: orderedEvents.length, + sourceCounts, + omittedCounts, + nextCursor: tracePage.nextCursor, summary: `Replayed ${orderedEvents.length} events for session ${session.name}`, events: orderedEvents, - session, - artifacts, - checkpoints, - traces, - sensorRuns, - tasks: sessionTasks, - handoffs: sessionHandoffs, + session: boundedSession, + artifacts: artifacts.slice(0, maxEvents), + checkpoints: checkpoints.slice(0, maxEvents), + traces: traces.slice(0, maxEvents), + sensorRuns: sensorRuns.slice(0, maxEvents), + tasks: sessionTasks.slice(0, maxEvents), + handoffs: sessionHandoffs.slice(0, maxEvents), }; return replay; @@ -281,19 +327,38 @@ export class HarnessReplayService { } async listReplays(filter?: { sessionId?: string }): Promise { - await this.ensureLayout(); - const entries = await fs.readdir(this.replaysPath); - const replays = await Promise.all( - entries - .filter((entry) => entry.endsWith('.json')) - .map(async (entry) => fs.readJson(path.join(this.replaysPath, entry)) as Promise) - ); - - const filtered = filter?.sessionId - ? replays.filter((replay) => replay.sessionId === filter.sessionId) - : replays; + const page = await this.listReplayPage({ limit: 25, sessionId: filter?.sessionId }); + const records: HarnessReplayRecord[] = []; + for (const summary of page.items) records.push(await this.readReplay(summary.id)); + return records; + } - return filtered.sort((left, right) => right.createdAt.localeCompare(left.createdAt)); + async listReplayPage(query: RuntimeHistoryQuery & { sessionId?: string } = {}): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, 25, 100, 'replay summaries'); + const binding = queryBinding({ sessionId: query.sessionId }); + const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'replays', binding); + await this.ensureLayout(); + const selected: HarnessReplaySummary[] = []; + let recordsScanned = 0; + const directory = await fs.opendir(this.replaysPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const replay = await fs.readJson(path.join(this.replaysPath, entry.name)) as HarnessReplayRecord; + recordsScanned += 1; + if (query.sessionId && replay.sessionId !== query.sessionId) continue; + const key = `${replay.createdAt}\0${replay.id}`; + if (boundary && key >= `${boundary.createdAt}\0${boundary.id}`) continue; + selected.push({ id: replay.id, sessionId: replay.sessionId, createdAt: replay.createdAt, fidelity: replay.fidelity, eventCount: replay.eventCount, summary: replay.summary }); + selected.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id)); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { items, nextCursor: hasMore && last ? encodeHistoryCursor('replays', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, cursorVersion: 1, partial: hasMore, durationMs: Date.now() - started }; } async getReplay(replayId: string): Promise { diff --git a/src/harness/application/sensors/sensorsService.ts b/src/harness/application/sensors/sensorsService.ts index 4e47adb4..7e151db1 100644 --- a/src/harness/application/sensors/sensorsService.ts +++ b/src/harness/application/sensors/sensorsService.ts @@ -123,10 +123,8 @@ export class HarnessSensorsService { } async getSessionSensorRuns(sessionId: string): Promise { - const traces = await this.options.stateService.listTraces(sessionId); - return traces - .filter((trace) => trace.event === 'sensor.run' && trace.data?.run) - .map((trace) => trace.data!.run as HarnessSensorRun); + const summary = await this.options.stateService.getSensorSummary(sessionId); + return Object.values(summary.latestBySensor) as HarnessSensorRun[]; } evaluateBackpressure( diff --git a/src/harness/index.ts b/src/harness/index.ts index b6536732..2b61d1aa 100644 --- a/src/harness/index.ts +++ b/src/harness/index.ts @@ -136,6 +136,8 @@ export { type AppendTraceInput, type AddArtifactInput, type CheckpointInput, + type HarnessTracePageQuery, + type HarnessSensorSummary, HarnessSensorsService, HarnessSensorCatalogService, type HarnessSensorsServiceOptions, @@ -166,6 +168,7 @@ export { type HarnessReplayEvent, type HarnessReplayEventSource, type HarnessReplayRecord, + type HarnessReplaySummary, type ReplaySessionOptions, HarnessDatasetService, type HarnessDatasetServiceOptions, @@ -175,6 +178,14 @@ export { type HarnessFailureRecord, type HarnessFailureCluster, type HarnessFailureDataset, + type HarnessDatasetSummary, + HarnessRuntimeRetentionService, + RuntimeHistoryCursorError, + type RuntimeHistoryDirection, + type RuntimeHistoryQuery, + type RuntimeHistoryPage, + type RuntimePruneReport, + type RuntimePruneOptions, HarnessPolicyService, HarnessPolicyBlockedError, type HarnessPolicyServiceOptions, diff --git a/src/mcp/logging/actionLogger.ts b/src/mcp/logging/actionLogger.ts index d4907036..f9331c77 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -118,10 +118,15 @@ async function resolveMcpActivitySessionId( } } - const existing = (await state.listSessions()).find((session) => - session.name === MCP_ACTIVITY_NAME && - session.metadata?.transport === 'mcp' - ); + let existing; + let cursor: string | undefined; + do { + const page = await state.listSessionPage({ limit: 50, cursor }); + existing = page.items.find((session) => + session.name === MCP_ACTIVITY_NAME && session.metadata?.transport === 'mcp' + ); + cursor = existing ? undefined : page.nextCursor; + } while (!existing && cursor); if (existing) { sessionCache.set(repoPath, existing.id); From c905257b79bbd4867fc16ede25ffc8bbbc3959ea Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:19:02 -0300 Subject: [PATCH 09/39] perf: complete bounded semantic analysis --- .../__tests__/codebaseAnalyzer.test.ts | 117 ++++++++ .../semantic/__tests__/contextCache.test.ts | 13 + .../__tests__/semanticSnapshotService.test.ts | 55 +++- .../adapters/out/semantic/codebaseAnalyzer.ts | 263 +++++++++++++++--- .../adapters/out/semantic/contextBuilder.ts | 14 +- .../adapters/out/semantic/contextCache.ts | 9 +- .../out/semantic/semanticSnapshotService.ts | 167 +++++++++-- src/harness/adapters/out/semantic/types.ts | 6 + .../context/__tests__/contextTools.test.ts | 18 ++ .../application/context/analysisBundle.ts | 44 +++ .../application/context/contextTools.ts | 56 +++- src/harness/application/context/index.ts | 1 + .../generators/agents/agentGenerator.ts | 12 +- .../documentation/documentationGenerator.ts | 25 +- 14 files changed, 713 insertions(+), 87 deletions(-) create mode 100644 src/harness/application/context/analysisBundle.ts diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index 2d354a2a..0d030309 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -84,6 +84,18 @@ describe('CodebaseAnalyzer', () => { beforeEach(async () => { tempDir = await createTempOutput('dotcontext-analyzer-'); + await Promise.all([ + 'src/services/userService.ts', + 'src/controllers/userController.ts', + 'src/models/user.ts', + 'src/utils/helper.ts', + 'src/index.ts', + 'src/main.ts', + ].map(async (relativePath) => { + const filePath = path.join(tempDir, relativePath); + await fs.ensureDir(path.dirname(filePath)); + await fs.writeFile(filePath, 'export const fixture = true;\n'); + })); jest.clearAllMocks(); }); @@ -139,6 +151,111 @@ describe('CodebaseAnalyzer', () => { patterns: expect.any(Array), })); expect(bundle.files).toHaveLength(bundle.context.stats.totalFiles); + expect(bundle.metrics.filesParsed).toBe(bundle.files.length); + expect(bundle.metrics.bytesRead).toBeGreaterThan(0); + expect(bundle.partial).toBe(false); + }); + + it('uses the documented default analysis limits', async () => { + const bundle = await new CodebaseAnalyzer().analyzeBundle(tempDir); + + expect(bundle.limits).toEqual({ + maxFiles: 5000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + concurrency: 16, + }); + }); + + it('bounds a 3000-file-equivalent analysis and reports maximum in-flight work', async () => { + const files = Array.from({ length: 3000 }, (_, index) => + path.join(tempDir, 'scale', `file-${index}.ts`) + ); + await fs.ensureDir(path.join(tempDir, 'scale')); + for (let index = 0; index < files.length; index += 100) { + await Promise.all(files.slice(index, index + 100).map((file) => + fs.writeFile(file, 'export const value = true;\n') + )); + } + + const { TreeSitterLayer } = require('../treeSitter/treeSitterLayer'); + let inFlight = 0; + let maxInFlight = 0; + const analyzeFile = jest.fn().mockImplementation(async (filePath: string): Promise => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + await Promise.resolve(); + inFlight -= 1; + return { filePath, language: 'typescript', symbols: [], imports: [], exports: [] }; + }); + TreeSitterLayer.mockImplementationOnce(() => ({ analyzeFile, clearCache: jest.fn() })); + + const bundle = await new CodebaseAnalyzer({ concurrency: 16 }).analyzeBundle(tempDir, files); + + expect(bundle.metrics.filesDiscovered).toBe(3000); + expect(bundle.metrics.filesParsed).toBe(3000); + expect(bundle.metrics.fileReads).toBe(3000); + expect(analyzeFile).toHaveBeenCalledTimes(3000); + expect(bundle.metrics.maxInFlight).toBeLessThanOrEqual(16); + expect(maxInFlight).toBeLessThanOrEqual(16); + expect(bundle.metrics.bytesRead).toBeLessThanOrEqual(bundle.limits.maxTotalBytes); + }, 20_000); + + it('skips oversized files and reports partial analysis without parsing them', async () => { + const small = path.join(tempDir, 'small.ts'); + const oversized = path.join(tempDir, 'oversized.ts'); + await fs.writeFile(small, 'ok'); + await fs.writeFile(oversized, '0123456789'); + const { TreeSitterLayer } = require('../treeSitter/treeSitterLayer'); + const analyzeFile = jest.fn().mockImplementation(async (filePath: string): Promise => + ({ filePath, language: 'typescript', symbols: [], imports: [], exports: [] })); + TreeSitterLayer.mockImplementationOnce(() => ({ analyzeFile, clearCache: jest.fn() })); + + const bundle = await new CodebaseAnalyzer({ maxFileBytes: 5 }).analyzeBundle( + tempDir, + [small, oversized] + ); + + expect(bundle.partial).toBe(true); + expect(bundle.skipped).toContainEqual({ + file: oversized, + reason: 'file-too-large', + size: 10, + }); + expect(analyzeFile).toHaveBeenCalledTimes(1); + expect(analyzeFile).toHaveBeenCalledWith(small); + }); + + it('honors aggregate byte and file budgets', async () => { + const files = await Promise.all([0, 1, 2].map(async (index) => { + const file = path.join(tempDir, `budget-${index}.ts`); + await fs.writeFile(file, '1234'); + return file; + })); + + const bundle = await new CodebaseAnalyzer({ + maxFiles: 2, + maxTotalBytes: 6, + }).analyzeBundle(tempDir, files); + + expect(bundle.metrics.filesParsed).toBe(1); + expect(bundle.metrics.bytesRead).toBe(4); + expect(bundle.partial).toBe(true); + expect(bundle.skipped.map((item) => item.reason)).toEqual([ + 'total-byte-limit', + 'total-byte-limit', + ]); + }); + + it('does not retain parser cache state when cacheEnabled is false', async () => { + const { TreeSitterLayer } = require('../treeSitter/treeSitterLayer'); + const analyzer = new CodebaseAnalyzer({ cacheEnabled: false }); + const layer = TreeSitterLayer.mock.results.at(-1).value; + + await analyzer.analyzeBundle(tempDir); + await analyzer.shutdown(); + + expect(layer.clearCache).toHaveBeenCalledTimes(3); }); it('should analyze files with Tree-sitter by default', async () => { diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index cf878769..45cad9e9 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -97,6 +97,19 @@ describe('ContextCache', () => { expect(await cache.get(tempDir, 'compact')).toBeNull(); }); + + it('invalidates by content fingerprint when directory mtime is unchanged', async () => { + const cache = new ContextCache({ watchDirs: ['src'] }); + const filePath = path.join(tempDir, 'src', 'stable.ts'); + await fs.writeFile(filePath, 'export const value = 1;\n'); + await cache.set(tempDir, 'compact', 'old-content'); + const original = await fs.stat(filePath); + + await fs.writeFile(filePath, 'export const value = 2;\n'); + await fs.utimes(filePath, original.atime, original.mtime); + + expect(await cache.get(tempDir, 'compact')).toBeNull(); + }); }); describe('invalidation and clearing', () => { diff --git a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts index 35d56457..897b1bc8 100644 --- a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts @@ -3,7 +3,7 @@ import * as os from 'os'; import * as path from 'path'; import { FileMapper } from '../../../../../utils/fileMapper'; -import { SemanticSnapshotService } from '../semanticSnapshotService'; +import { RepositoryChangingError, SemanticSnapshotService } from '../semanticSnapshotService'; describe('SemanticSnapshotService', () => { let tempDir: string; @@ -108,6 +108,29 @@ describe('SemanticSnapshotService', () => { expect(stale).toBeNull(); }); + it('reuses cached content hashes when file metadata is unchanged', async () => { + const service = new SemanticSnapshotService(true); + + const initial = await service.captureRepoFingerprintWithMetrics(repoPath); + const repeated = await service.captureRepoFingerprintWithMetrics(repoPath); + + expect(repeated.fingerprint).toBe(initial.fingerprint); + expect(initial.bytesRead).toBeGreaterThan(0); + expect(repeated.bytesRead).toBe(0); + expect(repeated.cacheHits).toBe(repeated.files); + }); + + it('honors disabled fingerprint caching', async () => { + const service = new SemanticSnapshotService(false); + + const initial = await service.captureRepoFingerprintWithMetrics(repoPath); + const repeated = await service.captureRepoFingerprintWithMetrics(repoPath); + + expect(repeated.fingerprint).toBe(initial.fingerprint); + expect(repeated.bytesRead).toBeGreaterThan(0); + expect(repeated.cacheHits).toBe(0); + }); + it('auto-refreshes a stale snapshot on demand', async () => { const mapper = new FileMapper(); const repoStructure = await mapper.mapRepository(repoPath); @@ -201,6 +224,36 @@ describe('SemanticSnapshotService', () => { expect(observedGeneratedAt).toBe(initial.manifest.generatedAt); }); + it('stops after two unstable attempts with a typed error and retains the previous snapshot', async () => { + const mapper = new FileMapper(); + const repoStructure = await mapper.mapRepository(repoPath); + const service = new SemanticSnapshotService(); + const initial = await service.writeSnapshot(repoStructure, { outputDir }); + await fs.writeFile(path.join(repoPath, 'src', 'index.ts'), 'export const run = () => false;\n'); + + let mutation = 0; + const originalBuild = (service as any).buildSnapshotArtifacts.bind(service); + const buildSpy = jest.spyOn(service as any, 'buildSnapshotArtifacts').mockImplementation(async (...args) => { + const artifacts = await originalBuild(...args); + mutation += 1; + await fs.writeFile( + path.join(repoPath, 'src', 'auth.ts'), + `export const login = () => ${mutation};\n` + ); + return artifacts; + }); + + await expect(service.ensureFreshSummary(repoPath, { outputDir })) + .rejects.toBeInstanceOf(RepositoryChangingError); + expect(buildSpy).toHaveBeenCalledTimes(2); + + const retained = await new SemanticSnapshotService().readSummary(repoPath, { + outputDir, + allowStale: true, + }); + expect(retained?.manifest?.generatedAt).toBe(initial.manifest.generatedAt); + }); + it('does not load a legacy docs/codebase-map.json without a snapshot manifest', async () => { const service = new SemanticSnapshotService(); await fs.ensureDir(path.join(outputDir, 'docs')); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index fab49a9a..38945e1b 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -35,13 +35,57 @@ const DEFAULT_OPTIONS: Required = { exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + concurrency: 16, cacheEnabled: true, }; +export interface AnalysisLimits { + maxFiles: number; + maxTotalBytes: number; + maxFileBytes: number; + concurrency: number; +} + +export type AnalysisSkipReason = + | 'file-limit' + | 'total-byte-limit' + | 'file-too-large' + | 'stat-failed'; + +export interface SkippedAnalysisFile { + file: string; + reason: AnalysisSkipReason; + size?: number; +} + +export interface AnalysisMetrics { + filesDiscovered: number; + filesParsed: number; + fileReads: number; + bytesRead: number; + maxInFlight: number; + cacheHits: number; + durationsMs: { + discovery: number; + parsing: number; + architecture: number; + functionalPatterns: number; + generation: number; + publication: number; + total: number; + }; +} + export interface SemanticAnalysisBundle { context: SemanticContext; functionalPatterns: DetectedFunctionalPatterns; files: string[]; + limits: AnalysisLimits; + partial: boolean; + skipped: SkippedAnalysisFile[]; + metrics: AnalysisMetrics; } export class CodebaseAnalyzer { @@ -52,6 +96,10 @@ export class CodebaseAnalyzer { constructor(options: AnalyzerOptions = {}) { this.treeSitter = new TreeSitterLayer(); this.options = { ...DEFAULT_OPTIONS, ...options }; + this.options.maxFiles = Math.max(0, this.options.maxFiles); + this.options.maxTotalBytes = Math.max(0, this.options.maxTotalBytes); + this.options.maxFileBytes = Math.max(0, this.options.maxFileBytes); + this.options.concurrency = Math.max(1, this.options.concurrency); // Create LSPLayer if LSP mode is enabled if (this.options.useLSP) { @@ -63,27 +111,71 @@ export class CodebaseAnalyzer { return (await this.analyzeProject(projectPath)).context; } - async analyzeBundle(projectPath: string): Promise { - const { context, files, fileAnalyses } = await this.analyzeProject(projectPath); + async analyzeBundle(projectPath: string, discoveredFiles?: string[]): Promise { + const result = await this.analyzeProject(projectPath, discoveredFiles); + const functionalStartedAt = Date.now(); + const functionalPatterns = this.detectFunctionalPatternsFromAnalyses( + result.files, + result.fileAnalyses + ); + result.metrics.durationsMs.functionalPatterns = Date.now() - functionalStartedAt; + result.metrics.durationsMs.total = Date.now() - result.startedAt; return { - context, - functionalPatterns: this.detectFunctionalPatternsFromAnalyses(files, fileAnalyses), - files, + context: result.context, + functionalPatterns, + files: result.files, + limits: this.analysisLimits(), + partial: result.skipped.length > 0, + skipped: result.skipped, + metrics: result.metrics, }; } - private async analyzeProject(projectPath: string): Promise<{ + private async analyzeProject(projectPath: string, discoveredFiles?: string[]): Promise<{ context: SemanticContext; files: string[]; fileAnalyses: Map; + skipped: SkippedAnalysisFile[]; + metrics: AnalysisMetrics; + startedAt: number; }> { const startTime = Date.now(); + const metrics: AnalysisMetrics = { + filesDiscovered: 0, + filesParsed: 0, + fileReads: 0, + bytesRead: 0, + maxInFlight: 0, + cacheHits: 0, + durationsMs: { + discovery: 0, + parsing: 0, + architecture: 0, + functionalPatterns: 0, + generation: 0, + publication: 0, + total: 0, + }, + }; - // 1. Find all code files - const files = await this.findCodeFiles(projectPath); + // 1. Select source files once, applying byte and count budgets before parsing. + const discoveryStartedAt = Date.now(); + const candidates = discoveredFiles + ? this.filterCodeFiles(projectPath, discoveredFiles) + : await this.findCodeFiles(projectPath); + metrics.filesDiscovered = candidates.length; + const { files, skipped, bytes } = await this.selectFilesWithinLimits(candidates); + metrics.bytesRead = bytes; + metrics.durationsMs.discovery = Date.now() - discoveryStartedAt; // 2. Analyze with Tree-sitter - const fileAnalyses = await this.analyzeFiles(files); + if (!this.options.cacheEnabled) { + this.treeSitter.clearCache(); + } + const parsingStartedAt = Date.now(); + const fileAnalyses = await this.analyzeFiles(files, metrics); + metrics.filesParsed = fileAnalyses.size; + metrics.durationsMs.parsing = Date.now() - parsingStartedAt; // 3. Build base context const context = this.buildBaseContext(fileAnalyses, projectPath); @@ -94,67 +186,156 @@ export class CodebaseAnalyzer { } // 5. Detect architecture and patterns + const architectureStartedAt = Date.now(); context.architecture = this.detectArchitecture(fileAnalyses, projectPath); + metrics.durationsMs.architecture = Date.now() - architectureStartedAt; // 6. Calculate stats context.stats.analysisTimeMs = Date.now() - startTime; + metrics.durationsMs.total = context.stats.analysisTimeMs; + + if (!this.options.cacheEnabled) { + this.treeSitter.clearCache(); + } return { context, files, fileAnalyses, + skipped, + metrics, + startedAt: startTime, + }; + } + + private analysisLimits(): AnalysisLimits { + return { + maxFiles: this.options.maxFiles, + maxTotalBytes: this.options.maxTotalBytes, + maxFileBytes: this.options.maxFileBytes, + concurrency: this.options.concurrency, }; } private async findCodeFiles(projectPath: string): Promise { - const extensions = Object.keys(LANGUAGE_EXTENSIONS); - const patterns = extensions.map((ext) => `**/*${ext}`); + const enabledLanguages = new Set(this.options.languages); + const extensions = Object.entries(LANGUAGE_EXTENSIONS) + .filter(([, language]) => enabledLanguages.has(language)) + .map(([extension]) => extension); + if (extensions.length === 0) { + return []; + } + const pattern = `**/*{${extensions.join(',')}}`; const ignorePatterns = this.options.exclude.map((p) => `**/${p}/**`); - const allFiles: string[] = []; - - for (const pattern of patterns) { - try { - const matches = await glob(pattern, { - cwd: projectPath, - ignore: ignorePatterns, - absolute: true, - nodir: true, - }); - allFiles.push(...matches); - } catch { - // Ignore glob errors for individual patterns - } + let allFiles: string[] = []; + try { + allFiles = await glob(pattern, { + cwd: projectPath, + ignore: ignorePatterns, + absolute: true, + nodir: true, + }); + } catch { + // A repository that cannot be enumerated produces an empty, valid bundle. } // Apply include filter if specified - let filteredFiles = [...new Set(allFiles)]; + let filteredFiles = [...new Set(allFiles)].sort(); if (this.options.include.length > 0) { filteredFiles = filteredFiles.filter((file) => this.options.include.some((pattern) => file.includes(pattern)) ); } - // Limit number of files - return filteredFiles.slice(0, this.options.maxFiles); + return filteredFiles; } - private async analyzeFiles(files: string[]): Promise> { - const analyses = new Map(); - const batchSize = 50; + private filterCodeFiles(projectPath: string, discoveredFiles: string[]): string[] { + const supported = new Set(Object.keys(LANGUAGE_EXTENSIONS)); + return [...new Set(discoveredFiles.map((file) => + path.isAbsolute(file) ? file : path.resolve(projectPath, file) + ))] + .filter((file) => { + const extension = path.extname(file).toLowerCase(); + return supported.has(extension) && + this.options.languages.includes(LANGUAGE_EXTENSIONS[extension]); + }) + .filter((file) => this.options.include.length === 0 || + this.options.include.some((pattern) => file.includes(pattern))) + .sort(); + } - for (let i = 0; i < files.length; i += batchSize) { - const batch = files.slice(i, i + batchSize); - const results = await Promise.all( - batch.map((file) => this.treeSitter.analyzeFile(file)) - ); + private async selectFilesWithinLimits(files: string[]): Promise<{ + files: string[]; + skipped: SkippedAnalysisFile[]; + bytes: number; + }> { + const selected: string[] = []; + const skipped: SkippedAnalysisFile[] = []; + let bytes = 0; - for (const analysis of results) { - analyses.set(analysis.filePath, analysis); + for (const file of files) { + let size: number; + try { + size = (await fs.stat(file)).size; + } catch { + skipped.push({ file, reason: 'stat-failed' }); + continue; + } + + if (size > this.options.maxFileBytes) { + skipped.push({ file, reason: 'file-too-large', size }); + continue; } + if (selected.length >= this.options.maxFiles) { + skipped.push({ file, reason: 'file-limit', size }); + continue; + } + if (bytes + size > this.options.maxTotalBytes) { + skipped.push({ file, reason: 'total-byte-limit', size }); + continue; + } + + selected.push(file); + bytes += size; } + return { files: selected, skipped, bytes }; + } + + private async analyzeFiles( + files: string[], + metrics?: AnalysisMetrics + ): Promise> { + const analyses = new Map(); + let cursor = 0; + let inFlight = 0; + const workerCount = Math.min(this.options.concurrency, files.length); + + const worker = async (): Promise => { + while (cursor < files.length) { + const index = cursor; + cursor += 1; + inFlight += 1; + if (metrics) { + metrics.maxInFlight = Math.max(metrics.maxInFlight, inFlight); + } + try { + if (metrics) { + metrics.fileReads += 1; + } + const analysis = await this.treeSitter.analyzeFile(files[index]); + analyses.set(analysis.filePath, analysis); + } finally { + inFlight -= 1; + } + } + }; + + await Promise.all(Array.from({ length: workerCount }, () => worker())); + return analyses; } @@ -623,6 +804,7 @@ export class CodebaseAnalyzer { * Shutdown LSP servers gracefully */ async shutdown(): Promise { + this.treeSitter.clearCache(); if (this.lspLayer) { await this.lspLayer.shutdown(); } @@ -698,10 +880,7 @@ export class CodebaseAnalyzer { * These patterns indicate functional capabilities like auth, database, API, etc. */ async detectFunctionalPatterns(projectPath: string): Promise { - const files = await this.findCodeFiles(projectPath); - const analyses = await this.analyzeFiles(files); - - return this.detectFunctionalPatternsFromAnalyses(files, analyses); + return (await this.analyzeBundle(projectPath)).functionalPatterns; } private detectFunctionalPatternsFromAnalyses( diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index d07e2ab3..5b872759 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -35,6 +35,9 @@ const DEFAULT_OPTIONS: Required = { exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + concurrency: 16, cacheEnabled: true, maxSymbolsPerCategory: 50, includeDocumentation: true, @@ -57,13 +60,16 @@ export class SemanticContextBuilder { * Analyze the codebase and cache the result */ async analyze(projectPath: string): Promise { - if (this.cachedContext && this.cachedProjectPath === projectPath) { + if (this.options.cacheEnabled && this.cachedContext && this.cachedProjectPath === projectPath) { return this.cachedContext; } - this.cachedContext = await this.analyzer.analyze(projectPath); - this.cachedProjectPath = projectPath; - return this.cachedContext; + const context = await this.analyzer.analyze(projectPath); + if (this.options.cacheEnabled) { + this.cachedContext = context; + this.cachedProjectPath = projectPath; + } + return context; } /** diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index e69334ea..f0fa5472 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -13,6 +13,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; +import { SemanticSnapshotService } from './semanticSnapshotService'; /** * A cached context entry with metadata for invalidation. @@ -24,6 +25,8 @@ interface CacheEntry { createdAt: number; /** Modification time hash of source directories at cache time */ mtimeHash: string; + /** Content-aware identity; prevents path/TTL-only reuse. */ + repoFingerprint: string; } export interface ContextCacheOptions { @@ -40,6 +43,7 @@ export class ContextCache { private readonly cache = new Map(); private readonly ttlMs: number; private readonly watchDirs: string[]; + private readonly fingerprintService = new SemanticSnapshotService(true); constructor(options: ContextCacheOptions = {}) { this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; @@ -69,7 +73,8 @@ export class ContextCache { // Check directory mtime invalidation const currentMtimeHash = await this.computeMtimeHash(repoPath); - if (currentMtimeHash !== entry.mtimeHash) { + const currentFingerprint = await this.fingerprintService.captureRepoFingerprint(repoPath); + if (currentMtimeHash !== entry.mtimeHash || currentFingerprint !== entry.repoFingerprint) { this.cache.delete(key); return null; } @@ -87,11 +92,13 @@ export class ContextCache { async set(repoPath: string, contextType: string, content: string): Promise { const key = this.buildKey(repoPath, contextType); const mtimeHash = await this.computeMtimeHash(repoPath); + const repoFingerprint = await this.fingerprintService.captureRepoFingerprint(repoPath); this.cache.set(key, { content, createdAt: Date.now(), mtimeHash, + repoFingerprint, }); } diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index f4260f92..e9a10523 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -48,6 +48,11 @@ export interface SemanticSnapshotWriteResult { manifest: SemanticSnapshotManifest; snapshotDir: string; publishedSummaryPath: string; + metrics: { + generationMs: number; + publicationMs: number; + stabilizationAttempts: number; + }; } export interface SemanticSnapshotReadOptions { @@ -91,8 +96,9 @@ const SNAPSHOT_DIRNAME = path.join('cache', 'semantic'); const MANIFEST_FILENAME = 'manifest.json'; const SUMMARY_FILENAME = 'summary.json'; const VERSIONS_DIRNAME = 'versions'; -const MAX_REFRESH_ATTEMPTS = 3; +const MAX_REFRESH_ATTEMPTS = 2; const MAX_VERSION_HISTORY = 3; +const MAX_FINGERPRINT_CACHE_ENTRIES = 10_000; const SECTION_FILENAMES: Record = { stack: 'stack.json', @@ -158,10 +164,43 @@ const FINGERPRINT_CODE_EXTENSIONS = new Set([ '.toml', ]); +interface FingerprintCacheEntry { + metadata: string; + contentHash: string; + lastUsedAt: number; +} + +export interface RepoFingerprintResult { + fingerprint: string; + files: number; + bytesRead: number; + cacheHits: number; + durationMs: number; +} + +export class RepositoryChangingError extends Error { + readonly code = 'repositoryChanging'; + + constructor(readonly repoPath: string, readonly attempts: number) { + super( + `Semantic snapshot refresh could not stabilize for ${repoPath}; ` + + `repository changed during ${attempts} refresh attempts.` + ); + this.name = 'RepositoryChangingError'; + } +} + export class SemanticSnapshotService { private static readonly inFlightRefreshes = new Map>(); + private readonly fingerprintCache = new Map(); + + constructor(private readonly cacheEnabled = true) {} async captureRepoFingerprint(repoPath: string): Promise { + return (await this.computeRepoFingerprint(repoPath)).fingerprint; + } + + async captureRepoFingerprintWithMetrics(repoPath: string): Promise { return this.computeRepoFingerprint(repoPath); } @@ -174,24 +213,29 @@ export class SemanticSnapshotService { const publishedSummaryPath = path.join(snapshotDir, SUMMARY_FILENAME); const repoFingerprint = - options.repoFingerprint ?? await this.computeRepoFingerprint(repoStructure.rootPath); + options.repoFingerprint ?? (await this.computeRepoFingerprint(repoStructure.rootPath)).fingerprint; + const generationStartedAt = Date.now(); const artifacts = await this.buildSnapshotArtifacts(repoStructure, { ...options, repoFingerprint, }); + const generationMs = Date.now() - generationStartedAt; + const publicationStartedAt = Date.now(); const manifest = await this.publishSnapshotArtifacts({ outputDir, snapshotDir, publishedSummaryPath, artifacts, }); + const publicationMs = Date.now() - publicationStartedAt; return { summary: artifacts.summary, manifest, snapshotDir, publishedSummaryPath, + metrics: { generationMs, publicationMs, stabilizationAttempts: 1 }, }; } @@ -305,41 +349,38 @@ export class SemanticSnapshotService { const publishedSummaryPath = path.join(snapshotDir, SUMMARY_FILENAME); for (let attempt = 1; attempt <= MAX_REFRESH_ATTEMPTS; attempt += 1) { - const repoFingerprint = await this.computeRepoFingerprint(repoPath); + const repoFingerprint = (await this.computeRepoFingerprint(repoPath)).fingerprint; const repoStructure = await fileMapper.mapRepository(repoPath); + const generationStartedAt = Date.now(); const artifacts = await this.buildSnapshotArtifacts(repoStructure, { outputDir, repoFingerprint, }); - const currentFingerprint = await this.computeRepoFingerprint(repoPath); + const generationMs = Date.now() - generationStartedAt; + const currentFingerprint = (await this.computeRepoFingerprint(repoPath)).fingerprint; if (currentFingerprint !== repoFingerprint) { continue; } + const publicationStartedAt = Date.now(); const manifest = await this.publishSnapshotArtifacts({ outputDir, snapshotDir, publishedSummaryPath, artifacts, }); - const publishedFingerprint = await this.computeRepoFingerprint(repoPath); - - if (publishedFingerprint !== repoFingerprint) { - continue; - } - + const publicationMs = Date.now() - publicationStartedAt; return { summary: artifacts.summary, manifest, snapshotDir, publishedSummaryPath, + metrics: { generationMs, publicationMs, stabilizationAttempts: attempt }, }; } - throw new Error( - `Semantic snapshot refresh could not stabilize for ${repoPath}; repository changed during refresh.` - ); + throw new RepositoryChangingError(repoPath, MAX_REFRESH_ATTEMPTS); })(); SemanticSnapshotService.inFlightRefreshes.set(refreshKey, refreshPromise); @@ -424,14 +465,12 @@ export class SemanticSnapshotService { try { if (!semantics || !functionalPatterns) { analyzer = new CodebaseAnalyzer(options.analyzerOptions); - } - - if (!semantics) { - semantics = await analyzer!.analyze(repoStructure.rootPath); - } - - if (!functionalPatterns) { - functionalPatterns = await analyzer!.detectFunctionalPatterns(repoStructure.rootPath); + const bundle = await analyzer.analyzeBundle( + repoStructure.rootPath, + repoStructure.files.map((file) => file.path) + ); + semantics ??= bundle.context; + functionalPatterns ??= bundle.functionalPatterns; } if (!stackInfo) { @@ -448,7 +487,7 @@ export class SemanticSnapshotService { schemaVersion: SNAPSHOT_SCHEMA_VERSION, generatedAt: new Date().toISOString(), repoFingerprint: - options.repoFingerprint ?? await this.computeRepoFingerprint(repoStructure.rootPath), + options.repoFingerprint ?? (await this.computeRepoFingerprint(repoStructure.rootPath)).fingerprint, analyzer: { useLSP: !!options.analyzerOptions?.useLSP, includesSymbolPayload: false, @@ -726,11 +765,20 @@ export class SemanticSnapshotService { } private async isFresh(repoPath: string, expectedFingerprint: string): Promise { - return expectedFingerprint === await this.computeRepoFingerprint(repoPath); + return expectedFingerprint === (await this.computeRepoFingerprint(repoPath)).fingerprint; } - private async computeRepoFingerprint(repoPath: string): Promise { - const files = await glob('**/*', { + private async computeRepoFingerprint(repoPath: string): Promise { + const startedAt = Date.now(); + const extensionPattern = `**/*.{${[...FINGERPRINT_CODE_EXTENSIONS] + .map((extension) => extension.slice(1)) + .join(',')}}`; + const files = await glob([ + extensionPattern, + '{src,lib,bin,app,packages,scripts}/**/*', + ...FINGERPRINT_ROOT_FILES, + '.github/workflows/**/*.{yml,yaml}', + ], { cwd: repoPath, nodir: true, dot: true, @@ -741,19 +789,78 @@ export class SemanticSnapshotService { .filter((filePath) => this.isFingerprintRelevant(filePath)) .sort(); - const hash = createHash('sha1'); + const hash = createHash('sha256'); + let bytesRead = 0; + let cacheHits = 0; + const liveCacheKeys = new Set(); for (const relativePath of relevantFiles) { const absolutePath = path.join(repoPath, relativePath); + const cacheKey = `${path.resolve(repoPath).toLowerCase()}\0${relativePath}`; + liveCacheKeys.add(cacheKey); try { - hash.update(`${relativePath}\0`); - hash.update(await fs.readFile(absolutePath)); - hash.update('\0'); + const stats = await fs.stat(absolutePath); + const metadata = `${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`; + let contentHash: string; + const cached = this.cacheEnabled ? this.fingerprintCache.get(cacheKey) : undefined; + if (cached?.metadata === metadata) { + contentHash = cached.contentHash; + cached.lastUsedAt = Date.now(); + cacheHits += 1; + } else { + const content = await fs.readFile(absolutePath); + bytesRead += content.byteLength; + contentHash = createHash('sha256').update(content).digest('hex'); + if (this.cacheEnabled) { + this.fingerprintCache.set(cacheKey, { + metadata, + contentHash, + lastUsedAt: Date.now(), + }); + } + } + hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeMs}\0${contentHash}\n`); } catch { hash.update(`${relativePath}:missing\n`); } } - return hash.digest('hex'); + // Git index identity is an additional signal only; dirty files are still + // represented by their independently hashed metadata/content above. + try { + const gitIndex = await fs.stat(path.join(repoPath, '.git', 'index')); + hash.update(`git-index:${gitIndex.size}:${gitIndex.mtimeMs}\n`); + } catch { + // Non-git repositories are fully supported. + } + + if (this.cacheEnabled) { + for (const key of this.fingerprintCache.keys()) { + if (key.startsWith(`${path.resolve(repoPath).toLowerCase()}\0`) && !liveCacheKeys.has(key)) { + this.fingerprintCache.delete(key); + } + } + this.pruneFingerprintCache(); + } + + return { + fingerprint: hash.digest('hex'), + files: relevantFiles.length, + bytesRead, + cacheHits, + durationMs: Date.now() - startedAt, + }; + } + + private pruneFingerprintCache(): void { + if (this.fingerprintCache.size <= MAX_FINGERPRINT_CACHE_ENTRIES) { + return; + } + const stale = [...this.fingerprintCache.entries()] + .sort((left, right) => left[1].lastUsedAt - right[1].lastUsedAt) + .slice(0, this.fingerprintCache.size - MAX_FINGERPRINT_CACHE_ENTRIES); + for (const [key] of stale) { + this.fingerprintCache.delete(key); + } } private isFingerprintRelevant(relativePath: string): boolean { diff --git a/src/harness/adapters/out/semantic/types.ts b/src/harness/adapters/out/semantic/types.ts index 2b38577d..3f7ad44e 100644 --- a/src/harness/adapters/out/semantic/types.ts +++ b/src/harness/adapters/out/semantic/types.ts @@ -190,6 +190,12 @@ export interface AnalyzerOptions { exclude?: string[]; include?: string[]; maxFiles?: number; + /** Maximum aggregate bytes selected for semantic parsing. */ + maxTotalBytes?: number; + /** Maximum size of one source file selected for semantic parsing. */ + maxFileBytes?: number; + /** Maximum number of file analyses running concurrently. */ + concurrency?: number; cacheEnabled?: boolean; } diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index d0497653..87a9f129 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -10,6 +10,9 @@ import { } from '../contextTools'; import { toolExecutionContext } from '../../../../shared'; import { CodebaseAnalyzer } from '../../../adapters/out/semantic'; +import { DocumentationGenerator } from '../scaffolding/generators/documentation/documentationGenerator'; +import { AgentGenerator } from '../scaffolding/generators/agents/agentGenerator'; +import { SemanticSnapshotService } from '../../../adapters/out/semantic'; describe('contextTools sensors scaffolding', () => { let tempDir: string; @@ -36,6 +39,9 @@ describe('contextTools sensors scaffolding', () => { it('shares one semantic analysis bundle across docs, snapshot, and agents', async () => { const analyzeBundle = jest.spyOn(CodebaseAnalyzer.prototype, 'analyzeBundle'); + const docs = jest.spyOn(DocumentationGenerator.prototype, 'generateDocumentation'); + const agents = jest.spyOn(AgentGenerator.prototype, 'generateAgentPrompts'); + const snapshot = jest.spyOn(SemanticSnapshotService.prototype, 'writeSnapshot'); await initializeContextTool.execute!( { @@ -49,6 +55,18 @@ describe('contextTools sensors scaffolding', () => { ); expect(analyzeBundle).toHaveBeenCalledTimes(1); + const analyzed = await analyzeBundle.mock.results[0].value; + expect(docs.mock.calls[0][2]).toEqual(expect.objectContaining({ + semanticContext: analyzed.context, + functionalPatterns: analyzed.functionalPatterns, + })); + expect(agents.mock.calls[0][2]).toEqual(expect.objectContaining({ + semanticContext: analyzed.context, + })); + expect(snapshot.mock.calls[0][1]).toEqual(expect.objectContaining({ + semantics: analyzed.context, + functionalPatterns: analyzed.functionalPatterns, + })); }); it('includes bootstrap sensors.json in pending writes and listToFill', async () => { diff --git a/src/harness/application/context/analysisBundle.ts b/src/harness/application/context/analysisBundle.ts new file mode 100644 index 00000000..9b9d9876 --- /dev/null +++ b/src/harness/application/context/analysisBundle.ts @@ -0,0 +1,44 @@ +import type { RepoStructure } from '../../../types'; +import type { + AnalysisLimits, + AnalysisMetrics as SemanticAnalysisMetrics, + DetectedFunctionalPatterns, + SemanticContext, + SkippedAnalysisFile, +} from '../../adapters/out/semantic'; +import type { StackInfo } from './intelligence/stack'; + +/** Default safety budgets for one context operation. */ +export const DEFAULT_ANALYSIS_LIMITS: AnalysisLimits = Object.freeze({ + maxFiles: 5_000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + concurrency: 16, +}); + +export interface AnalysisMetrics extends SemanticAnalysisMetrics { + fingerprint: { + files: number; + bytesRead: number; + cacheHits: number; + durationMs: number; + }; +} + +/** + * Operation-scoped repository view shared by all context-init consumers. + * It deliberately contains summaries, never the parser's full FileAnalysis map. + */ +export interface AnalysisBundle { + repoPath: string; + discoveredFiles: string[]; + repoStructure: RepoStructure; + semanticContext: SemanticContext; + functionalPatterns: DetectedFunctionalPatterns; + stackInfo?: StackInfo; + repoFingerprint: string; + limits: AnalysisLimits; + partial: boolean; + skipped: SkippedAnalysisFile[]; + metrics: AnalysisMetrics; +} diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 14a6b8a6..ac99df2d 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -32,6 +32,7 @@ import { getUntrackedContextLayoutEntries } from '../../../shared'; import { resolveRuntimeLayout } from '../../../shared/fs/pathHelpers'; import { createSkillRegistry } from '../../domain/workflow/skills'; import { ensureGitignorePatterns } from '../../../utils/gitignoreManager'; +import type { AnalysisBundle } from './analysisBundle'; type ToolContext = unknown; @@ -585,6 +586,7 @@ export const initializeContextTool = createInternalTool< skipContentGeneration?: boolean; generateQA?: boolean; generateSkills?: boolean; + cacheEnabled?: boolean; }, Record >( @@ -603,6 +605,7 @@ export const initializeContextTool = createInternalTool< skipContentGeneration = true, generateQA = false, generateSkills = true, + cacheEnabled = true, } = input; const resolvedRepoPath = path.resolve(repoPath); @@ -647,15 +650,22 @@ export const initializeContextTool = createInternalTool< const repoStructure = await fileMapper.mapRepository(resolvedRepoPath, include); let semanticBundle: SemanticAnalysisBundle | undefined; + let analysisBundle: AnalysisBundle | undefined; let semanticFingerprint: string | undefined; + let fingerprintMetrics: Awaited> | undefined; if (semantic) { const analyzer = new CodebaseAnalyzer({ exclude: [...new Set([...DEFAULT_EXCLUDE_PATTERNS, ...exclude])], + cacheEnabled, }); try { - const snapshotService = new SemanticSnapshotService(); - semanticFingerprint = await snapshotService.captureRepoFingerprint(resolvedRepoPath); - semanticBundle = await analyzer.analyzeBundle(resolvedRepoPath); + const snapshotService = new SemanticSnapshotService(cacheEnabled); + fingerprintMetrics = await snapshotService.captureRepoFingerprintWithMetrics(resolvedRepoPath); + semanticFingerprint = fingerprintMetrics.fingerprint; + semanticBundle = await analyzer.analyzeBundle( + resolvedRepoPath, + repoStructure.files.map((file) => file.path) + ); } catch { semanticBundle = undefined; semanticFingerprint = undefined; @@ -673,6 +683,30 @@ export const initializeContextTool = createInternalTool< detectedStackInfo = await stackDetector.detect(resolvedRepoPath); } + if (semanticBundle && semanticFingerprint && fingerprintMetrics) { + analysisBundle = { + repoPath: resolvedRepoPath, + discoveredFiles: semanticBundle.files, + repoStructure, + semanticContext: semanticBundle.context, + functionalPatterns: semanticBundle.functionalPatterns, + stackInfo: detectedStackInfo, + repoFingerprint: semanticFingerprint, + limits: semanticBundle.limits, + partial: semanticBundle.partial, + skipped: semanticBundle.skipped, + metrics: { + ...semanticBundle.metrics, + fingerprint: { + files: fingerprintMetrics.files, + bytesRead: fingerprintMetrics.bytesRead, + cacheHits: fingerprintMetrics.cacheHits, + durationMs: fingerprintMetrics.durationMs, + }, + }, + }; + } + if (!disableFiltering) { if (overrideProjectType) { projectType = overrideProjectType; @@ -705,6 +739,13 @@ export const initializeContextTool = createInternalTool< functionalPatterns: semanticBundle?.functionalPatterns, stackInfo: detectedStackInfo, repoFingerprint: semanticFingerprint, + cacheEnabled, + onSnapshotMetrics: (metrics) => { + if (analysisBundle) { + analysisBundle.metrics.durationsMs.generation = metrics.generationMs; + analysisBundle.metrics.durationsMs.publication = metrics.publicationMs; + } + }, }, false ); @@ -755,6 +796,7 @@ export const initializeContextTool = createInternalTool< availableSkills, semanticContext: semanticBundle?.context, stackInfo: detectedStackInfo, + cacheEnabled, }, false ); @@ -900,6 +942,14 @@ export const initializeContextTool = createInternalTool< reasoning: classification.reasoning, } : undefined, + analysis: analysisBundle + ? { + limits: analysisBundle.limits, + partial: analysisBundle.partial, + skipped: analysisBundle.skipped, + metrics: analysisBundle.metrics, + } + : undefined, }, nextStep: pendingWrites.length > 0 ? { diff --git a/src/harness/application/context/index.ts b/src/harness/application/context/index.ts index e1c71169..02d4209d 100644 --- a/src/harness/application/context/index.ts +++ b/src/harness/application/context/index.ts @@ -1,4 +1,5 @@ export * from './contextService'; export * from './contextTools'; +export * from './analysisBundle'; export * as intelligence from './intelligence'; export * as scaffolding from './scaffolding'; diff --git a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts index ea61702d..bfbc644e 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts @@ -43,6 +43,7 @@ interface AgentGenerationConfig { /** Operation-scoped data supplied by context init. */ semanticContext?: SemanticContext; stackInfo?: StackInfo; + cacheEnabled?: boolean; } /** @@ -122,15 +123,22 @@ export class AgentGenerator { let semantics = normalizedConfig.semanticContext; if (normalizedConfig.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis for agents...', verbose); - this.analyzer = new CodebaseAnalyzer(); + GeneratorUtils.logProgress('[metric] semantic.legacy_bundle_build=1', verbose); + this.analyzer = new CodebaseAnalyzer({ cacheEnabled: normalizedConfig.cacheEnabled ?? true }); try { - semantics = await this.analyzer.analyze(repoStructure.rootPath); + semantics = (await this.analyzer.analyzeBundle( + repoStructure.rootPath, + repoStructure.files.map((file) => file.path) + )).context; GeneratorUtils.logProgress( `Analyzed ${semantics.stats.totalFiles} files, found ${semantics.stats.totalSymbols} symbols`, verbose ); } catch (error) { GeneratorUtils.logError('Semantic analysis failed, continuing without it', error, verbose); + } finally { + await this.analyzer.shutdown(); + this.analyzer = undefined; } } diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index 49d31130..565b0269 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -67,6 +67,12 @@ interface DocumentationGenerationConfig { functionalPatterns?: DetectedFunctionalPatterns; stackInfo?: StackInfo; repoFingerprint?: string; + cacheEnabled?: boolean; + onSnapshotMetrics?: (metrics: { + generationMs: number; + publicationMs: number; + stabilizationAttempts: number; + }) => void; } export class DocumentationGenerator { @@ -83,24 +89,34 @@ export class DocumentationGenerator { const docsDir = path.join(outputDir, 'docs'); await GeneratorUtils.ensureDirectoryAndLog(docsDir, verbose, 'Generating documentation scaffold in'); const snapshotService = (config.semantic || config.semanticContext) - ? new SemanticSnapshotService() + ? new SemanticSnapshotService(config.cacheEnabled ?? true) : null; // Perform semantic analysis if enabled let semantics = config.semanticContext; + let functionalPatterns = config.functionalPatterns; let snapshotFingerprint = config.repoFingerprint; if (config.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis...', verbose); - this.analyzer = new CodebaseAnalyzer(); + GeneratorUtils.logProgress('[metric] semantic.legacy_bundle_build=1', verbose); + this.analyzer = new CodebaseAnalyzer({ cacheEnabled: config.cacheEnabled ?? true }); try { snapshotFingerprint = await snapshotService!.captureRepoFingerprint(repoStructure.rootPath); - semantics = await this.analyzer.analyze(repoStructure.rootPath); + const bundle = await this.analyzer.analyzeBundle( + repoStructure.rootPath, + repoStructure.files.map((file) => file.path) + ); + semantics = bundle.context; + functionalPatterns = bundle.functionalPatterns; GeneratorUtils.logProgress( `Analyzed ${semantics.stats.totalFiles} files, found ${semantics.stats.totalSymbols} symbols in ${semantics.stats.analysisTimeMs}ms`, verbose ); } catch (error) { GeneratorUtils.logError('Semantic analysis failed, continuing without it', error, verbose); + } finally { + await this.analyzer.shutdown(); + this.analyzer = undefined; } } @@ -123,9 +139,10 @@ export class DocumentationGenerator { outputDir, semantics, stackInfo, - functionalPatterns: config.functionalPatterns, + functionalPatterns, repoFingerprint: snapshotFingerprint, }); + config.onSnapshotMetrics?.(snapshot.metrics); GeneratorUtils.logProgress( `Created semantic snapshot summary at ${path.relative(outputDir, snapshot.publishedSummaryPath)}`, From 892c94bf3fb10e1683dac40b0a584a6a991b7cf1 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:21:07 -0300 Subject: [PATCH 10/39] refactor: inject analysis bundle into generators --- .../context/__tests__/contextTools.test.ts | 10 ++++++++-- src/harness/application/context/contextTools.ts | 2 ++ .../scaffolding/generators/agents/agentGenerator.ts | 7 +++++-- .../documentation/documentationGenerator.ts | 11 +++++++---- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index 87a9f129..00baa06a 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -56,12 +56,18 @@ describe('contextTools sensors scaffolding', () => { expect(analyzeBundle).toHaveBeenCalledTimes(1); const analyzed = await analyzeBundle.mock.results[0].value; - expect(docs.mock.calls[0][2]).toEqual(expect.objectContaining({ + const docsConfig = docs.mock.calls[0][2]!; + const agentsConfig = agents.mock.calls[0][2]!; + expect(docsConfig).toEqual(expect.objectContaining({ semanticContext: analyzed.context, functionalPatterns: analyzed.functionalPatterns, })); - expect(agents.mock.calls[0][2]).toEqual(expect.objectContaining({ + expect(docsConfig).toEqual(expect.objectContaining({ + analysisBundle: expect.objectContaining({ semanticContext: analyzed.context }), + })); + expect(agentsConfig).toEqual(expect.objectContaining({ semanticContext: analyzed.context, + analysisBundle: docsConfig.analysisBundle, })); expect(snapshot.mock.calls[0][1]).toEqual(expect.objectContaining({ semantics: analyzed.context, diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index ac99df2d..accc012a 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -740,6 +740,7 @@ export const initializeContextTool = createInternalTool< stackInfo: detectedStackInfo, repoFingerprint: semanticFingerprint, cacheEnabled, + analysisBundle, onSnapshotMetrics: (metrics) => { if (analysisBundle) { analysisBundle.metrics.durationsMs.generation = metrics.generationMs; @@ -797,6 +798,7 @@ export const initializeContextTool = createInternalTool< semanticContext: semanticBundle?.context, stackInfo: detectedStackInfo, cacheEnabled, + analysisBundle, }, false ); diff --git a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts index bfbc644e..53f89e67 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts @@ -15,6 +15,7 @@ import { PrevcPhase } from '../../../../../domain/workflow/types'; import { getScaffoldStructure, serializeStructureAsMarkdown } from '../shared/structures'; import { AutoFillService, AutoFillContext } from '../../../intelligence/autoFill'; import { StackDetector, StackInfo } from '../../../intelligence/stack'; +import type { AnalysisBundle } from '../../../analysisBundle'; interface AgentContext { topLevelDirectories: string[]; @@ -44,6 +45,8 @@ interface AgentGenerationConfig { semanticContext?: SemanticContext; stackInfo?: StackInfo; cacheEnabled?: boolean; + /** Preferred operation-scoped input from context init. */ + analysisBundle?: AnalysisBundle; } /** @@ -120,7 +123,7 @@ export class AgentGenerator { await GeneratorUtils.ensureDirectoryAndLog(agentsDir, verbose, 'Generating agent scaffold in'); // Perform semantic analysis if enabled - let semantics = normalizedConfig.semanticContext; + let semantics = normalizedConfig.analysisBundle?.semanticContext ?? normalizedConfig.semanticContext; if (normalizedConfig.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis for agents...', verbose); GeneratorUtils.logProgress('[metric] semantic.legacy_bundle_build=1', verbose); @@ -143,7 +146,7 @@ export class AgentGenerator { } // Detect stack info for autoFill - let stackInfo = normalizedConfig.stackInfo; + let stackInfo = normalizedConfig.analysisBundle?.stackInfo ?? normalizedConfig.stackInfo; if (!stackInfo && normalizedConfig.autoFill) { try { const stackDetector = new StackDetector(); diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index 565b0269..16bc2d9a 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -22,6 +22,7 @@ import { } from '../../../../../../types/scaffoldFrontmatter'; import { getScaffoldStructure, ScaffoldStructure, serializeStructureAsMarkdown } from '../shared/structures'; import { AutoFillService, AutoFillContext } from '../../../intelligence/autoFill'; +import type { AnalysisBundle } from '../../../analysisBundle'; /** * Category mapping from document name to frontmatter category. @@ -73,6 +74,8 @@ interface DocumentationGenerationConfig { publicationMs: number; stabilizationAttempts: number; }) => void; + /** Preferred operation-scoped input from context init. */ + analysisBundle?: AnalysisBundle; } export class DocumentationGenerator { @@ -93,9 +96,9 @@ export class DocumentationGenerator { : null; // Perform semantic analysis if enabled - let semantics = config.semanticContext; - let functionalPatterns = config.functionalPatterns; - let snapshotFingerprint = config.repoFingerprint; + let semantics = config.analysisBundle?.semanticContext ?? config.semanticContext; + let functionalPatterns = config.analysisBundle?.functionalPatterns ?? config.functionalPatterns; + let snapshotFingerprint = config.analysisBundle?.repoFingerprint ?? config.repoFingerprint; if (config.semantic && !semantics) { GeneratorUtils.logProgress('Running semantic analysis...', verbose); GeneratorUtils.logProgress('[metric] semantic.legacy_bundle_build=1', verbose); @@ -121,7 +124,7 @@ export class DocumentationGenerator { } // Detect stack info for codebase map and autoFill - let stackInfo = config.stackInfo; + let stackInfo = config.analysisBundle?.stackInfo ?? config.stackInfo; if (!stackInfo && (semantics || config.autoFill)) { try { const stackDetector = new StackDetector(); From 4a7d75c6d3fa0137b0308ab3f97007308c872f9e Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:27:53 -0300 Subject: [PATCH 11/39] fix: clamp subprocess diagnostic tails --- .../sensors/__tests__/testsPassing.test.ts | 18 ++++++++++ .../sensors/__tests__/typecheckClean.test.ts | 19 ++++++++++ .../__tests__/boundedByteCollector.test.ts | 36 +++++++++++++++++++ .../domain/execution/boundedByteCollector.ts | 20 +++++++++-- src/harness/domain/execution/index.ts | 1 + .../plans/__tests__/acceptanceRunner.test.ts | 16 +++++++++ 6 files changed, 107 insertions(+), 3 deletions(-) diff --git a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts index b8077718..e2984e2e 100644 --- a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts +++ b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts @@ -132,6 +132,24 @@ describe('tests-passing sensor', () => { expect(result.outputTruncated).toBe(true); }); + it('clamps an enormous caller-controlled context tail to the safe default', async () => { + const result = await executeTestsPassing(tempDir, { + sessionId: 's', + context: { + kind: 'exit-code', + testCommand: nodeScript('process.stdout.write("x".repeat(12 * 1024))'), + tailBytes: Number.MAX_SAFE_INTEGER, + }, + }); + + expect(result.status).toBe('passed'); + expect(result.details).toEqual(expect.objectContaining({ + stdoutBytes: 12 * 1024, + stdoutDroppedBytes: 4 * 1024, + outputTruncated: true, + })); + }); + it('fails with a stable reason when output exceeds the hard limit', async () => { const result = await executeTestsPassing(tempDir, { sessionId: 's', diff --git a/src/harness/adapters/out/sensors/__tests__/typecheckClean.test.ts b/src/harness/adapters/out/sensors/__tests__/typecheckClean.test.ts index ac10fa39..c81d2cab 100644 --- a/src/harness/adapters/out/sensors/__tests__/typecheckClean.test.ts +++ b/src/harness/adapters/out/sensors/__tests__/typecheckClean.test.ts @@ -40,4 +40,23 @@ describe('typecheck-clean sensor', () => { expect(out.tail).not.toContain('line 0'); expect(out.tail).toContain('line 59'); }); + + it('clamps an enormous metadata tail and exposes stable truncation counters', async () => { + const result = await executeTypecheckClean(tempDir, { + sessionId: 's', + metadata: { + command: ['node', '-e', 'process.stdout.write("x".repeat(12 * 1024)); process.exit(2)'], + tailBytes: Number.MAX_SAFE_INTEGER, + }, + }); + + expect(result.status).toBe('failed'); + expect(result.details).toEqual(expect.objectContaining({ + stdoutBytes: 12 * 1024, + stdoutDroppedBytes: 4 * 1024, + outputTruncated: true, + })); + const output = result.output as { tail: string }; + expect(Buffer.byteLength(output.tail)).toBe(8 * 1024); + }); }); diff --git a/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts index 21f1ba43..dc8f0a87 100644 --- a/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts +++ b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts @@ -1,6 +1,8 @@ import { BoundedByteCollector, + DEFAULT_SUBPROCESS_TAIL_BYTES, MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, + MAX_SUBPROCESS_TAIL_BYTES, resolveSubprocessOutputLimits, } from '../boundedByteCollector'; @@ -48,4 +50,38 @@ describe('BoundedByteCollector', () => { unsafeAllowAboveMaximum: true, })).toEqual(expect.objectContaining({ hardCombinedOutputBytes: requested })); }); + + it('allows callers to lower the tail but never increase it', () => { + expect(resolveSubprocessOutputLimits({ tailBytes: 128 }).tailBytes).toBe(128); + expect(resolveSubprocessOutputLimits({ tailBytes: Number.MAX_SAFE_INTEGER }).tailBytes) + .toBe(MAX_SUBPROCESS_TAIL_BYTES); + expect(resolveSubprocessOutputLimits({ tailBytes: Number.MAX_VALUE }).tailBytes) + .toBe(MAX_SUBPROCESS_TAIL_BYTES); + expect(resolveSubprocessOutputLimits({ tailBytes: Number.POSITIVE_INFINITY }).tailBytes) + .toBe(DEFAULT_SUBPROCESS_TAIL_BYTES); + expect(resolveSubprocessOutputLimits({ tailBytes: Number.NaN }).tailBytes) + .toBe(DEFAULT_SUBPROCESS_TAIL_BYTES); + expect(resolveSubprocessOutputLimits({ tailBytes: -100 }).tailBytes).toBe(0); + }); + + it('guards its allocation boundary when constructed directly with an enormous tail', () => { + const collector = new BoundedByteCollector(Number.MAX_SAFE_INTEGER); + collector.append(Buffer.alloc(DEFAULT_SUBPROCESS_TAIL_BYTES * 2, 'z')); + + expect(collector.tailBytes).toBe(MAX_SUBPROCESS_TAIL_BYTES); + expect(collector.totalBytes).toBe(DEFAULT_SUBPROCESS_TAIL_BYTES * 2); + expect(collector.retainedBytes).toBe(MAX_SUBPROCESS_TAIL_BYTES); + expect(collector.droppedBytes).toBe(DEFAULT_SUBPROCESS_TAIL_BYTES); + expect(collector.truncated).toBe(true); + expect(collector.tail()).toHaveLength(MAX_SUBPROCESS_TAIL_BYTES); + }); + + it.each([Number.NaN, Number.POSITIVE_INFINITY, -1])( + 'rejects invalid direct-constructor tail value %p before allocation', + (tailBytes) => { + expect(() => new BoundedByteCollector(tailBytes)).toThrow( + 'tailBytes must be a non-negative safe integer' + ); + } + ); }); diff --git a/src/harness/domain/execution/boundedByteCollector.ts b/src/harness/domain/execution/boundedByteCollector.ts index 860269ce..28d9edcd 100644 --- a/src/harness/domain/execution/boundedByteCollector.ts +++ b/src/harness/domain/execution/boundedByteCollector.ts @@ -6,6 +6,12 @@ */ export const DEFAULT_SUBPROCESS_TAIL_BYTES = 8 * 1024; +/** + * Absolute per-stream capture ceiling. Diagnostic callers may request a + * smaller tail, but increasing it would make user-controlled configuration a + * memory-allocation primitive. + */ +export const MAX_SUBPROCESS_TAIL_BYTES = DEFAULT_SUBPROCESS_TAIL_BYTES; export const DEFAULT_SUBPROCESS_SOFT_OUTPUT_BYTES = 1024 * 1024; export const DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES = 16 * 1024 * 1024; export const MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES = 64 * 1024 * 1024; @@ -31,7 +37,10 @@ function positiveInteger(value: number | undefined, fallback: number, minimum: n export function resolveSubprocessOutputLimits( input: SubprocessOutputLimitsInput = {} ): SubprocessOutputLimits { - const tailBytes = positiveInteger(input.tailBytes, DEFAULT_SUBPROCESS_TAIL_BYTES, 0); + const tailBytes = Math.min( + positiveInteger(input.tailBytes, DEFAULT_SUBPROCESS_TAIL_BYTES, 0), + MAX_SUBPROCESS_TAIL_BYTES + ); const requestedHardLimit = positiveInteger( input.hardCombinedOutputBytes, DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, @@ -53,16 +62,21 @@ export interface BoundedByteCollectorSnapshot { } export class BoundedByteCollector { + readonly tailBytes: number; private readonly buffer: Buffer; private retainedLength = 0; private writeOffset = 0; private observedBytes = 0; - constructor(readonly tailBytes: number = DEFAULT_SUBPROCESS_TAIL_BYTES) { + constructor(tailBytes: number = DEFAULT_SUBPROCESS_TAIL_BYTES) { if (!Number.isSafeInteger(tailBytes) || tailBytes < 0) { throw new Error('tailBytes must be a non-negative safe integer'); } - this.buffer = Buffer.allocUnsafe(tailBytes); + // Enforce the invariant at the allocation boundary as defense in depth. + // Callers should resolve limits first, but direct construction must never + // turn an oversized value into a large allocation. + this.tailBytes = Math.min(tailBytes, MAX_SUBPROCESS_TAIL_BYTES); + this.buffer = Buffer.allocUnsafe(this.tailBytes); } append(chunk: Buffer): void { diff --git a/src/harness/domain/execution/index.ts b/src/harness/domain/execution/index.ts index f0143a6f..563530f0 100644 --- a/src/harness/domain/execution/index.ts +++ b/src/harness/domain/execution/index.ts @@ -1,6 +1,7 @@ export { BoundedByteCollector, DEFAULT_SUBPROCESS_TAIL_BYTES, + MAX_SUBPROCESS_TAIL_BYTES, DEFAULT_SUBPROCESS_SOFT_OUTPUT_BYTES, DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, diff --git a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts index 6f63658f..69742067 100644 --- a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts +++ b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts @@ -77,6 +77,22 @@ describe('runAcceptance', () => { expect(result.outputTruncated).toBe(true); }); + it('clamps an enormous acceptance tail at the domain configuration boundary', async () => { + const result = await runAcceptance( + { + kind: 'shell', + command: ['node', '-e', 'process.stdout.write("x".repeat(12 * 1024))'], + }, + { ...ctx, outputLimits: { tailBytes: Number.MAX_SAFE_INTEGER } } + ); + + expect(result.passed).toBe(true); + expect(Buffer.byteLength(result.tailStdout)).toBe(8 * 1024); + expect(result.stdoutBytes).toBe(12 * 1024); + expect(result.stdoutDroppedBytes).toBe(4 * 1024); + expect(result.outputTruncated).toBe(true); + }); + it('kills and reaps a child that exceeds the combined hard output limit', async () => { const result = await runAcceptance( { From 3a43801b19cc08197f74bf96329cf7161c3585f8 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:28:10 -0300 Subject: [PATCH 12/39] fix: bound MCP payloads --- CHANGELOG.md | 2 + README.md | 2 + .../content/docs/en/reference/mcp-tools.md | 8 + .../content/docs/pt-br/reference/mcp-tools.md | 8 + .../out/runtimeState/runtimeStateService.ts | 7 +- .../application/actions/actionService.ts | 10 +- .../__tests__/taskContractsService.test.ts | 20 +- .../contracts/taskContractsService.ts | 107 +++++++ .../application/datasets/datasetService.ts | 4 +- .../application/execution/executionService.ts | 8 + .../application/history/runtimeHistory.ts | 12 + .../application/replay/replayService.ts | 5 +- src/harness/index.ts | 1 + src/mcp/README.md | 7 + src/mcp/gateway/__tests__/harness.test.ts | 28 ++ src/mcp/gateway/__tests__/inputLimits.test.ts | 23 ++ src/mcp/gateway/__tests__/response.test.ts | 74 +++++ src/mcp/gateway/harness.ts | 17 +- src/mcp/gateway/index.ts | 9 + src/mcp/gateway/inputLimits.ts | 82 +++++ src/mcp/gateway/response.ts | 267 ++++++++++++---- src/mcp/server/__tests__/mcpServer.test.ts | 41 ++- src/mcp/server/mcpServer.ts | 301 +++++++++--------- 23 files changed, 818 insertions(+), 225 deletions(-) create mode 100644 src/mcp/gateway/__tests__/inputLimits.test.ts create mode 100644 src/mcp/gateway/__tests__/response.test.ts create mode 100644 src/mcp/gateway/inputLimits.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e48777b6..3afefdaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,12 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Added bounded MCP input schemas, cursor pagination for every growing harness list, compact payload budgets, and content-free `_meta.dotcontext` response metrics. - Added configurable, globally clamped hook stdin, field, event, rotation, segment-retention, and per-session trace limits. - Added opaque cursor pages for sessions, traces, artifacts, replay summaries, and dataset summaries, including bounded defaults, query-bound cursors, and scan metadata. - Added latest-sensor summary indexes, bounded dataset concurrency/failure retention, and dry-run runtime pruning with active workflow protection. ### Fixed +- Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses. - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. diff --git a/README.md b/README.md index e718d799..6823f99d 100644 --- a/README.md +++ b/README.md @@ -522,6 +522,8 @@ The MCP adapter currently exposes 12 tools: 7 action-based gateways plus 5 dedic For AI-agent use, provide `repoPath` on the first context-heavy MCP call so dotcontext can cache the working repository. +MCP JSON responses are compact and bounded to 1 MiB by default (4 MiB absolute). Growing `harness` lists return `page.nextCursor`; pass it back with a bounded `limit` to continue. If a selected page cannot fit, the tool returns `MCP_PAGE_TOO_LARGE` and a `suggestedLimit` instead of truncating JSON. The optional `_meta.dotcontext` envelope contains only bounded audit metrics, so existing clients can continue reading `content` unchanged. + ## CLI Reference ### Requirements diff --git a/docs/src/content/docs/en/reference/mcp-tools.md b/docs/src/content/docs/en/reference/mcp-tools.md index c940b036..df9ba286 100644 --- a/docs/src/content/docs/en/reference/mcp-tools.md +++ b/docs/src/content/docs/en/reference/mcp-tools.md @@ -218,6 +218,14 @@ Explicit harness runtime operations — sessions, traces, artifacts, checkpoints | `summary` / `evidence` | string / array | Sensor result summary | | `from` / `to` / `artifacts` | — | Handoff fields | | `scope` / `effect` / `target` / `pattern` | — | Policy fields | +| `limit` | integer, 1–1,000 | Maximum records requested from a list action | +| `cursor` | string | Opaque continuation cursor from `page.nextCursor` | +| `direction` | `oldest` \| `newest` | Page traversal direction where supported | +| `maxEvents` | integer, 1–1,000 | Replay event budget; defaults to 100 | + +`listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays`, and `listDatasets` are bounded. Continue a partial result by sending the returned `page.nextCursor` unchanged in the next call. Cursors are bound to their query and become invalid when their underlying trace segments rotate. + +MCP JSON text is compact-serialized once and has a 1 MiB default budget (4 MiB absolute maximum). A page that does not fit returns the typed `MCP_PAGE_TOO_LARGE` error with `suggestedLimit`; JSON is never cut at an arbitrary byte. Tool results also include a content-free `_meta.dotcontext` audit envelope with response size and page metrics. Clients may ignore `_meta` and continue reading `content`. **Returns:** session timelines, artifact inventories, task evaluations, sensor telemetry, replay records, failure clusters, or policy enforcement results. diff --git a/docs/src/content/docs/pt-br/reference/mcp-tools.md b/docs/src/content/docs/pt-br/reference/mcp-tools.md index c3bcf410..57c3b9e0 100644 --- a/docs/src/content/docs/pt-br/reference/mcp-tools.md +++ b/docs/src/content/docs/pt-br/reference/mcp-tools.md @@ -218,6 +218,14 @@ Operações explícitas do runtime do harness — sessions, traces, artefatos, c | `summary` / `evidence` | string / array | Resumo do resultado do sensor | | `from` / `to` / `artifacts` | — | Campos de handoff | | `scope` / `effect` / `target` / `pattern` | — | Campos de policy | +| `limit` | inteiro, 1–1.000 | Máximo de registros solicitado em uma action de listagem | +| `cursor` | string | Cursor opaco de continuação retornado em `page.nextCursor` | +| `direction` | `oldest` \| `newest` | Direção da paginação quando suportada | +| `maxEvents` | inteiro, 1–1.000 | Orçamento de eventos do replay; padrão 100 | + +`listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays` e `listDatasets` são limitadas. Para continuar um resultado parcial, envie o `page.nextCursor` retornado, sem alterá-lo, na próxima chamada. Os cursors são vinculados à query e ficam inválidos quando os segmentos de trace subjacentes rotacionam. + +O texto JSON MCP é serializado uma vez em formato compacto e tem orçamento padrão de 1 MiB (máximo absoluto de 4 MiB). Uma página que não cabe retorna o erro tipado `MCP_PAGE_TOO_LARGE` com `suggestedLimit`; o JSON nunca é cortado em um byte arbitrário. Os resultados também incluem um envelope de auditoria `_meta.dotcontext`, sem conteúdo do usuário, com tamanho da resposta e métricas de paginação. Clientes podem ignorar `_meta` e continuar lendo `content`. **Retorna:** linhas do tempo de session, inventários de artefatos, avaliações de tasks, telemetria de sensors, registros de replay, clusters de falhas ou resultados de aplicação de policy. diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index fe4a27b8..a1bdff8b 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -19,6 +19,7 @@ import { } from '../../../application/hooks/hookTracePolicy'; import { boundedLimit, + RUNTIME_HISTORY_LIMITS, decodeHistoryCursor, encodeHistoryCursor, queryBinding, @@ -536,7 +537,7 @@ export class HarnessRuntimeStateService { async listSessionPage(query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); - const limit = boundedLimit(query.limit, 50, 200, 'sessions'); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.sessions.default, RUNTIME_HISTORY_LIMITS.sessions.maximum, 'sessions'); const direction = query.direction ?? 'newest'; const binding = queryBinding({ direction }); const boundary = decodeHistoryCursor<{ updatedAt: string; id: string }>(query.cursor, 'sessions', binding); @@ -648,7 +649,7 @@ export class HarnessRuntimeStateService { async listArtifactPage(sessionId: string, query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); - const limit = boundedLimit(query.limit, 50, 200, 'artifacts'); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.artifacts.default, RUNTIME_HISTORY_LIMITS.artifacts.maximum, 'artifacts'); const direction = query.direction ?? 'newest'; const binding = queryBinding({ sessionId, direction }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'artifacts', binding); @@ -708,7 +709,7 @@ export class HarnessRuntimeStateService { async listTracePage(sessionId: string, query: HarnessTracePageQuery = {}): Promise> { const started = Date.now(); - const limit = boundedLimit(query.limit, 100, 1000, 'traces'); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.traces.default, RUNTIME_HISTORY_LIMITS.traces.maximum, 'traces'); const direction: RuntimeHistoryDirection = query.direction ?? 'newest'; const filters = { sessionId, direction, event: query.event, level: query.level, createdAfter: query.createdAfter, createdBefore: query.createdBefore }; const binding = queryBinding(filters); diff --git a/src/harness/application/actions/actionService.ts b/src/harness/application/actions/actionService.ts index 70b27c45..74bf44bc 100644 --- a/src/harness/application/actions/actionService.ts +++ b/src/harness/application/actions/actionService.ts @@ -328,9 +328,12 @@ export class HarnessActionService { }), }; case 'listTasks': + const taskPage = await this.executionService.listTaskContractPage({ limit: params.limit, cursor: params.cursor, direction: params.direction }); + const { items: tasks, ...taskPagination } = taskPage; return { success: true, - tasks: await this.executionService.listTaskContracts(), + tasks, + page: taskPagination, }; case 'evaluateTask': return { @@ -354,9 +357,12 @@ export class HarnessActionService { }), }; case 'listHandoffs': + const handoffPage = await this.executionService.listHandoffContractPage({ limit: params.limit, cursor: params.cursor, direction: params.direction }); + const { items: handoffs, ...handoffPagination } = handoffPage; return { success: true, - handoffs: await this.executionService.listHandoffContracts(), + handoffs, + page: handoffPagination, }; case 'replaySession': return { diff --git a/src/harness/application/contracts/__tests__/taskContractsService.test.ts b/src/harness/application/contracts/__tests__/taskContractsService.test.ts index d26359c1..60eaac80 100644 --- a/src/harness/application/contracts/__tests__/taskContractsService.test.ts +++ b/src/harness/application/contracts/__tests__/taskContractsService.test.ts @@ -73,6 +73,25 @@ describe('HarnessTaskContractsService', () => { expect(await fs.pathExists(contractPath)).toBe(true); }); + it('paginates growing task and handoff contract collections with opaque cursors', async () => { + for (let index = 0; index < 3; index += 1) { + await service.createTaskContract({ title: `Task ${index}` }); + await service.createHandoffContract({ from: `agent-${index}`, to: 'reviewer' }); + } + + const tasksFirst = await service.listTaskContractPage({ limit: 2 }); + const tasksSecond = await service.listTaskContractPage({ limit: 2, cursor: tasksFirst.nextCursor }); + const handoffsFirst = await service.listHandoffContractPage({ limit: 2 }); + const handoffsSecond = await service.listHandoffContractPage({ limit: 2, cursor: handoffsFirst.nextCursor }); + + expect(tasksFirst).toMatchObject({ recordsReturned: 2, hasMore: true, partial: true }); + expect(tasksSecond).toMatchObject({ recordsReturned: 1, hasMore: false, partial: false }); + expect(new Set([...tasksFirst.items, ...tasksSecond.items].map((item) => item.id)).size).toBe(3); + expect(handoffsFirst).toMatchObject({ recordsReturned: 2, hasMore: true, partial: true }); + expect(handoffsSecond).toMatchObject({ recordsReturned: 1, hasMore: false, partial: false }); + expect(new Set([...handoffsFirst.items, ...handoffsSecond.items].map((item) => item.id)).size).toBe(3); + }); + describe('structured artifact specs', () => { it('glob spec with minMatches blocks when fewer artifacts match', async () => { const session = await stateService.createSession({ name: 'glob-min' }); @@ -250,4 +269,3 @@ describe('HarnessTaskContractsService', () => { }); }); }); - diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index 4aec8c9d..53ef163d 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -16,6 +16,15 @@ import type { HarnessRuntimeStatePort, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { HarnessSensorRun } from '../sensors/sensorsService'; +import { + boundedLimit, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + RUNTIME_HISTORY_LIMITS, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../history/runtimeHistory'; /** * Structured artifact requirement. @@ -295,6 +304,55 @@ export class HarnessTaskContractsService { return contracts.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); } + async listTaskContractPage( + query: RuntimeHistoryQuery = {} + ): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.tasks.default, RUNTIME_HISTORY_LIMITS.tasks.maximum, 'task contracts'); + const direction = query.direction ?? 'newest'; + const binding = queryBinding({ resource: 'task-contracts', direction }); + const boundary = decodeHistoryCursor<{ updatedAt: string; id: string }>( + query.cursor, + 'task-contracts', + binding + ); + await this.ensureLayout(); + const selected: HarnessTaskContract[] = []; + let recordsScanned = 0; + const directory = await fs.opendir(this.tasksPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const contract = await fs.readJson(path.join(this.tasksPath, entry.name)) as HarnessTaskContract; + recordsScanned += 1; + const key = `${contract.updatedAt}\0${contract.id}`; + const boundaryKey = boundary ? `${boundary.updatedAt}\0${boundary.id}` : undefined; + if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; + selected.push(contract); + selected.sort((left, right) => { + const comparison = left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id); + return direction === 'newest' ? -comparison : comparison; + }); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { + items, + nextCursor: hasMore && last + ? encodeHistoryCursor('task-contracts', binding, { updatedAt: last.updatedAt, id: last.id }) + : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - started, + }; + } + async getTaskContract(taskId: string): Promise { const filePath = await this.taskFile(taskId); if (!(await fs.pathExists(filePath))) { @@ -370,6 +428,55 @@ export class HarnessTaskContractsService { return contracts.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); } + async listHandoffContractPage( + query: RuntimeHistoryQuery = {} + ): Promise> { + const started = Date.now(); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.handoffs.default, RUNTIME_HISTORY_LIMITS.handoffs.maximum, 'handoff contracts'); + const direction = query.direction ?? 'newest'; + const binding = queryBinding({ resource: 'handoff-contracts', direction }); + const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>( + query.cursor, + 'handoff-contracts', + binding + ); + await this.ensureLayout(); + const selected: HarnessHandoffContract[] = []; + let recordsScanned = 0; + const directory = await fs.opendir(this.handoffsPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const contract = await fs.readJson(path.join(this.handoffsPath, entry.name)) as HarnessHandoffContract; + recordsScanned += 1; + const key = `${contract.createdAt}\0${contract.id}`; + const boundaryKey = boundary ? `${boundary.createdAt}\0${boundary.id}` : undefined; + if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; + selected.push(contract); + selected.sort((left, right) => { + const comparison = left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); + return direction === 'newest' ? -comparison : comparison; + }); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const hasMore = selected.length > limit; + const items = selected.slice(0, limit); + const last = items.at(-1); + return { + items, + nextCursor: hasMore && last + ? encodeHistoryCursor('handoff-contracts', binding, { createdAt: last.createdAt, id: last.id }) + : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - started, + }; + } + async evaluateTaskCompletion(taskId: string, sessionId?: string): Promise { const contract = await this.getTaskContract(taskId); if (!contract) { diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index b989a4c3..beadd33f 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -7,7 +7,7 @@ import { HarnessRuntimeStateService, type HarnessRuntimeStatePort } from '../../ import { HarnessReplayService, type HarnessReplayRecord } from '../replay/replayService'; import { HarnessSensorsService } from '../sensors/sensorsService'; import { HarnessTaskContractsService } from '../contracts/taskContractsService'; -import { boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; +import { boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, RUNTIME_HISTORY_LIMITS, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; export type HarnessFailureKind = 'sensor' | 'task' | 'session' | 'trace'; @@ -332,7 +332,7 @@ export class HarnessDatasetService { async listDatasetPage(query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); - const limit = boundedLimit(query.limit, 25, 100, 'dataset summaries'); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.datasets.default, RUNTIME_HISTORY_LIMITS.datasets.maximum, 'dataset summaries'); const binding = queryBinding({ resource: 'datasets' }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'datasets', binding); await this.ensureLayout(); diff --git a/src/harness/application/execution/executionService.ts b/src/harness/application/execution/executionService.ts index 1b7f66cf..c6e6958a 100644 --- a/src/harness/application/execution/executionService.ts +++ b/src/harness/application/execution/executionService.ts @@ -206,6 +206,10 @@ export class HarnessExecutionService { return this.contracts.listTaskContracts(); } + listTaskContractPage(query: Parameters[0] = {}) { + return this.contracts.listTaskContractPage(query); + } + evaluateTaskCompletion(taskId: string, sessionId?: string): Promise { return this.contracts.evaluateTaskCompletion(taskId, sessionId); } @@ -224,6 +228,10 @@ export class HarnessExecutionService { return this.contracts.listHandoffContracts(); } + listHandoffContractPage(query: Parameters[0] = {}) { + return this.contracts.listHandoffContractPage(query); + } + listPolicies(): Promise { return this.policy.listRules(); } diff --git a/src/harness/application/history/runtimeHistory.ts b/src/harness/application/history/runtimeHistory.ts index dd2170fe..29cf93be 100644 --- a/src/harness/application/history/runtimeHistory.ts +++ b/src/harness/application/history/runtimeHistory.ts @@ -2,6 +2,18 @@ import { createHash } from 'crypto'; export type RuntimeHistoryDirection = 'oldest' | 'newest'; +/** Source-of-truth limits shared by harness callers and transport adapters. */ +export const RUNTIME_HISTORY_LIMITS = { + sessions: { default: 50, maximum: 200 }, + artifacts: { default: 50, maximum: 200 }, + traces: { default: 100, maximum: 1000 }, + tasks: { default: 100, maximum: 1000 }, + handoffs: { default: 100, maximum: 1000 }, + replays: { default: 25, maximum: 100 }, + datasets: { default: 25, maximum: 100 }, + replayEvents: { default: 100, maximum: 1000 }, +} as const; + export interface RuntimeHistoryQuery { limit?: number; cursor?: string; diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index 75d2b239..9efc295c 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -22,6 +22,7 @@ import { decodeHistoryCursor, encodeHistoryCursor, queryBinding, + RUNTIME_HISTORY_LIMITS, type RuntimeHistoryPage, type RuntimeHistoryQuery, } from '../history/runtimeHistory'; @@ -154,7 +155,7 @@ export class HarnessReplayService { sessionId: string, options: ReplaySessionOptions = {} ): Promise { - const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); + const maxEvents = boundedLimit(options.maxEvents, RUNTIME_HISTORY_LIMITS.replayEvents.default, RUNTIME_HISTORY_LIMITS.replayEvents.maximum, 'replay events'); const session = await this.stateService.getSession(sessionId); const [tracePage, artifactPage, sensorRuns, tasks, handoffs] = await Promise.all([ this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest' }), @@ -335,7 +336,7 @@ export class HarnessReplayService { async listReplayPage(query: RuntimeHistoryQuery & { sessionId?: string } = {}): Promise> { const started = Date.now(); - const limit = boundedLimit(query.limit, 25, 100, 'replay summaries'); + const limit = boundedLimit(query.limit, RUNTIME_HISTORY_LIMITS.replays.default, RUNTIME_HISTORY_LIMITS.replays.maximum, 'replay summaries'); const binding = queryBinding({ sessionId: query.sessionId }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'replays', binding); await this.ensureLayout(); diff --git a/src/harness/index.ts b/src/harness/index.ts index 2b61d1aa..b7f956b1 100644 --- a/src/harness/index.ts +++ b/src/harness/index.ts @@ -181,6 +181,7 @@ export { type HarnessDatasetSummary, HarnessRuntimeRetentionService, RuntimeHistoryCursorError, + RUNTIME_HISTORY_LIMITS, type RuntimeHistoryDirection, type RuntimeHistoryQuery, type RuntimeHistoryPage, diff --git a/src/mcp/README.md b/src/mcp/README.md index 600088e8..78b6e47c 100644 --- a/src/mcp/README.md +++ b/src/mcp/README.md @@ -26,6 +26,13 @@ The MCP tools follow a simple, explicit pattern: | `plan` | Plan management and execution tracking | | `agent` | Agent orchestration and discovery | | `skill` | Skill management for on-demand expertise | +| `harness` | Bounded runtime operations for sessions, traces, artifacts, contracts, replay, datasets, sensors, and policies | + +## Bounded responses + +Machine JSON is compact-serialized once and limited to 1 MiB by default (4 MiB absolute maximum). Every tool response includes a content-free `_meta.dotcontext` audit summary with response bytes, serialization time, item count, and partial-page state. Clients that ignore `_meta` continue to read the same JSON text from `content`. + +The growing harness lists (`listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays`, and `listDatasets`) return bounded pages. Pass `limit` and the opaque `cursor` returned as `page.nextCursor` to continue; do not inspect or modify cursors. `replaySession.maxEvents` defaults to 100 and cannot exceed 1,000. An oversized page returns `MCP_PAGE_TOO_LARGE` with `suggestedLimit`, never truncated JSON. ### Dedicated Workflow Tools (5) diff --git a/src/mcp/gateway/__tests__/harness.test.ts b/src/mcp/gateway/__tests__/harness.test.ts index db637e7e..e7975cf8 100644 --- a/src/mcp/gateway/__tests__/harness.test.ts +++ b/src/mcp/gateway/__tests__/harness.test.ts @@ -193,4 +193,32 @@ describe('handleHarness', () => { expect(datasetPayload.dataset.failureCount).toBeGreaterThan(0); expect(datasetPayload.dataset.clusterCount).toBeGreaterThan(0); }); + + it('bounds listTraces to the harness default and exposes nextCursor', async () => { + const created = await handleHarness( + { action: 'createSession', name: 'bounded-traces' }, + { repoPath: tempDir } + ); + const session = JSON.parse(created.content[0].text).session; + for (let index = 0; index < 105; index += 1) { + await handleHarness({ + action: 'appendTrace', + sessionId: session.id, + level: 'info', + event: 'bounded.trace', + message: `trace ${index}`, + }, { repoPath: tempDir }); + } + + const first = await handleHarness( + { action: 'listTraces', sessionId: session.id }, + { repoPath: tempDir } + ); + const payload = JSON.parse(first.content[0].text); + + expect(payload.traces).toHaveLength(100); + expect(payload.page).toMatchObject({ recordsReturned: 100, hasMore: true, partial: true }); + expect(payload.page.nextCursor).toEqual(expect.any(String)); + expect(first._meta?.dotcontext).toMatchObject({ itemCount: 100, partial: true, appliedLimit: 100 }); + }); }); diff --git a/src/mcp/gateway/__tests__/inputLimits.test.ts b/src/mcp/gateway/__tests__/inputLimits.test.ts new file mode 100644 index 00000000..11fa1c42 --- /dev/null +++ b/src/mcp/gateway/__tests__/inputLimits.test.ts @@ -0,0 +1,23 @@ +import { MCP_INPUT_LIMITS, MCPInputLimitError, validateMcpInput } from '../inputLimits'; + +describe('MCP input limits', () => { + it('accepts arrays at the limit and rejects limit + 1', () => { + expect(() => validateMcpInput({ evidence: Array(MCP_INPUT_LIMITS.arrayItems).fill('ok') })).not.toThrow(); + expect(() => validateMcpInput({ evidence: Array(MCP_INPUT_LIMITS.arrayItems + 1).fill('ok') })) + .toThrow(MCPInputLimitError); + }); + + it('bounds patterns and nested serialized objects', () => { + expect(() => validateMcpInput({ pattern: 'x'.repeat(MCP_INPUT_LIMITS.patternLength) })).not.toThrow(); + expect(() => validateMcpInput({ pattern: 'x'.repeat(MCP_INPUT_LIMITS.patternLength + 1) })) + .toThrow(/exceeds/); + expect(() => validateMcpInput({ data: { value: 'x'.repeat(MCP_INPUT_LIMITS.nestedObjectBytes) } })) + .toThrow(/serialized bytes/); + }); + + it('rejects excessive object depth', () => { + let nested: Record = {}; + for (let index = 0; index <= MCP_INPUT_LIMITS.depth; index += 1) nested = { child: nested }; + expect(() => validateMcpInput(nested)).toThrow(/depth/); + }); +}); diff --git a/src/mcp/gateway/__tests__/response.test.ts b/src/mcp/gateway/__tests__/response.test.ts new file mode 100644 index 00000000..cf84fa6f --- /dev/null +++ b/src/mcp/gateway/__tests__/response.test.ts @@ -0,0 +1,74 @@ +import { + MAX_MCP_AUDIT_META_BYTES, + createErrorResponse, + createJsonResponse, +} from '../response'; + +describe('bounded MCP responses', () => { + it('compact-serializes the caller result exactly once on the normal path', () => { + const payload = { success: true, sessions: [{ id: 'one' }], page: { partial: false, recordsReturned: 1 } }; + const stringify = jest.spyOn(JSON, 'stringify'); + + const response = createJsonResponse(payload); + + expect(stringify.mock.calls.filter(([value]) => value === payload)).toHaveLength(1); + expect(response.content[0].text).toBe(JSON.stringify(payload)); + stringify.mockRestore(); + }); + + it('keeps audit metadata below 2 KiB and excludes caller content', () => { + const secret = 'caller-secret-body'; + const response = createJsonResponse({ + success: true, + content: secret, + message: secret, + sessions: [{ content: secret }], + page: { partial: true, recordsReturned: 1 }, + }); + const serializedMeta = JSON.stringify(response._meta); + + expect(Buffer.byteLength(serializedMeta, 'utf8')).toBeLessThan(MAX_MCP_AUDIT_META_BYTES); + expect(serializedMeta).not.toContain(secret); + expect(response._meta?.dotcontext).toMatchObject({ success: true, itemCount: 1, partial: true }); + }); + + it('accepts payloads at the byte budget and rejects the next byte without truncation', () => { + const payload = { success: true, value: 'é'.repeat(64) }; + const bytes = Buffer.byteLength(JSON.stringify(payload), 'utf8'); + + const below = createJsonResponse(payload, { payloadBudgetBytes: bytes - 1 }); + const at = createJsonResponse(payload, { payloadBudgetBytes: bytes }); + const above = createJsonResponse(payload, { payloadBudgetBytes: bytes + 1 }); + + expect(below.isError).toBe(true); + expect(JSON.parse(below.content[0].text)).toMatchObject({ errorCode: 'MCP_PAGE_TOO_LARGE' }); + expect(at.isError).toBeUndefined(); + expect(at.content[0].text).toBe(JSON.stringify(payload)); + expect(above.isError).toBeUndefined(); + }); + + it('returns an existing artifact reference instead of its oversized body', () => { + const response = createJsonResponse({ + success: true, + artifact: { id: 'artifact-1', name: 'export.json', kind: 'json', content: 'x'.repeat(5000) }, + }, { payloadBudgetBytes: 100 }); + const payload = JSON.parse(response.content[0].text); + + expect(response.isError).toBeUndefined(); + expect(payload).toMatchObject({ + success: true, + exported: true, + artifact: { id: 'artifact-1', name: 'export.json', kind: 'json' }, + }); + expect(response.content[0].text).not.toContain('x'.repeat(100)); + }); + + it('exposes typed error metadata without embedding the message in audit data', () => { + const error = Object.assign(new Error('private failure detail'), { code: 'BOUNDED_FAILURE' }); + const response = createErrorResponse(error); + + expect(response.isError).toBe(true); + expect(response._meta?.dotcontext).toMatchObject({ success: false, errorCode: 'BOUNDED_FAILURE' }); + expect(JSON.stringify(response._meta)).not.toContain('private failure detail'); + }); +}); diff --git a/src/mcp/gateway/harness.ts b/src/mcp/gateway/harness.ts index 61f70af1..251bfa4a 100644 --- a/src/mcp/gateway/harness.ts +++ b/src/mcp/gateway/harness.ts @@ -1,4 +1,4 @@ -import { HarnessActionService } from '../../harness'; +import { HarnessActionService, RUNTIME_HISTORY_LIMITS } from '../../harness'; import type { HarnessParams } from './types'; import type { MCPToolResponse } from './response'; @@ -8,6 +8,16 @@ export interface HarnessOptions { repoPath: string; } +const LIST_DEFAULTS: Partial> = { + listSessions: RUNTIME_HISTORY_LIMITS.sessions.default, + listTraces: RUNTIME_HISTORY_LIMITS.traces.default, + listArtifacts: RUNTIME_HISTORY_LIMITS.artifacts.default, + listTasks: RUNTIME_HISTORY_LIMITS.tasks.default, + listHandoffs: RUNTIME_HISTORY_LIMITS.handoffs.default, + listReplays: RUNTIME_HISTORY_LIMITS.replays.default, + listDatasets: RUNTIME_HISTORY_LIMITS.datasets.default, +}; + export async function handleHarness( params: HarnessParams, options: HarnessOptions @@ -15,7 +25,10 @@ export async function handleHarness( const service = new HarnessActionService({ repoPath: options.repoPath }); try { - return createJsonResponse(await service.execute(params)); + return createJsonResponse(await service.execute(params), { + requestedLimit: params.limit, + appliedLimit: params.limit ?? LIST_DEFAULTS[params.action], + }); } catch (error) { return createErrorResponse(error); } diff --git a/src/mcp/gateway/index.ts b/src/mcp/gateway/index.ts index a7e86d9f..22b4a218 100644 --- a/src/mcp/gateway/index.ts +++ b/src/mcp/gateway/index.ts @@ -14,8 +14,17 @@ export { createJsonResponse, createErrorResponse, createTextResponse, + type DotcontextAuditMetadata, + DEFAULT_MCP_TEXT_PAYLOAD_BYTES, + ABSOLUTE_MCP_TEXT_PAYLOAD_BYTES, } from './response'; +export { + MCP_INPUT_LIMITS, + MCPInputLimitError, + validateMcpInput, +} from './inputLimits'; + // Shared utilities export { minimalUI, mockTranslate, toolContext } from './shared'; diff --git a/src/mcp/gateway/inputLimits.ts b/src/mcp/gateway/inputLimits.ts new file mode 100644 index 00000000..b6aa063c --- /dev/null +++ b/src/mcp/gateway/inputLimits.ts @@ -0,0 +1,82 @@ +export const MCP_INPUT_LIMITS = { + scalarString: 64 * 1024, + contentString: 1024 * 1024, + nestedObjectBytes: 512 * 1024, + totalBytes: 4 * 1024 * 1024, + depth: 12, + arrayItems: 1000, + patternLength: 2048, + cursorLength: 4096, + listDefault: 100, + listMaximum: 1000, + maxEventsDefault: 100, + maxEventsMaximum: 1000, +} as const; + +export class MCPInputLimitError extends Error { + readonly code = 'MCP_INPUT_LIMIT_EXCEEDED'; + + constructor(message: string) { + super(message); + this.name = 'MCPInputLimitError'; + } +} + +const NESTED_OBJECT_KEYS = new Set(['content', 'data', 'output', 'details', 'metadata', 'policy', 'options']); +const PATTERN_KEYS = new Set(['pattern', 'pathPattern', 'fileGlob']); + +function serializedBytes(value: unknown, path: string): number { + try { + return Buffer.byteLength(JSON.stringify(value), 'utf8'); + } catch { + throw new MCPInputLimitError(`${path} must be JSON serializable`); + } +} + +function inspect(value: unknown, path: string, key: string | undefined, depth: number): void { + if (depth > MCP_INPUT_LIMITS.depth) { + throw new MCPInputLimitError(`${path} exceeds maximum depth ${MCP_INPUT_LIMITS.depth}`); + } + if (typeof value === 'string') { + const maximum = key === 'content' + ? MCP_INPUT_LIMITS.contentString + : PATTERN_KEYS.has(key ?? '') ? MCP_INPUT_LIMITS.patternLength : MCP_INPUT_LIMITS.scalarString; + if (Buffer.byteLength(value, 'utf8') > maximum) { + throw new MCPInputLimitError(`${path} exceeds ${maximum} UTF-8 bytes`); + } + return; + } + if (typeof value === 'number' && ['limit', 'maxResults', 'maxEvents'].includes(key ?? '')) { + if (!Number.isInteger(value) || value < 1 || value > MCP_INPUT_LIMITS.listMaximum) { + throw new MCPInputLimitError(`${path} must be an integer between 1 and ${MCP_INPUT_LIMITS.listMaximum}`); + } + return; + } + if (Array.isArray(value)) { + if (value.length > MCP_INPUT_LIMITS.arrayItems) { + throw new MCPInputLimitError(`${path} exceeds ${MCP_INPUT_LIMITS.arrayItems} items`); + } + value.forEach((entry, index) => inspect(entry, `${path}[${index}]`, undefined, depth + 1)); + return; + } + if (value !== null && typeof value === 'object') { + if (key && NESTED_OBJECT_KEYS.has(key)) { + const bytes = serializedBytes(value, path); + if (bytes > MCP_INPUT_LIMITS.nestedObjectBytes) { + throw new MCPInputLimitError(`${path} exceeds ${MCP_INPUT_LIMITS.nestedObjectBytes} serialized bytes`); + } + } + for (const [childKey, child] of Object.entries(value)) { + inspect(child, `${path}.${childKey}`, childKey, depth + 1); + } + } +} + +/** Validate protocol-wide bounds that cannot be expressed reliably with Zod shapes. */ +export function validateMcpInput(value: unknown): void { + const totalBytes = serializedBytes(value, 'input'); + if (totalBytes > MCP_INPUT_LIMITS.totalBytes) { + throw new MCPInputLimitError(`input exceeds ${MCP_INPUT_LIMITS.totalBytes} serialized bytes`); + } + inspect(value, 'input', undefined, 0); +} diff --git a/src/mcp/gateway/response.ts b/src/mcp/gateway/response.ts index db3e4688..3b4dfb21 100644 --- a/src/mcp/gateway/response.ts +++ b/src/mcp/gateway/response.ts @@ -1,13 +1,39 @@ /** - * MCP Response Helpers + * MCP response helpers. * - * Standardized response creation for MCP tool handlers. + * JSON responses are compact-serialized exactly once on the successful path. + * The small `_meta.dotcontext` envelope is derived from the original value, so + * transports never need to parse the response body for logging. */ -/** - * MCP Tool Response type that matches the MCP SDK CallToolResult interface. - * Uses index signature for forward compatibility with SDK extensions. - */ +export const DEFAULT_MCP_TEXT_PAYLOAD_BYTES = 1024 * 1024; +export const ABSOLUTE_MCP_TEXT_PAYLOAD_BYTES = 4 * 1024 * 1024; +export const MAX_MCP_AUDIT_META_BYTES = 2 * 1024; + +const AUDIT_SCALAR_KEYS = [ + 'success', + 'currentPhase', + 'nextPhase', + 'phase', + 'scale', + 'count', + 'total', + 'status', +] as const; + +export interface DotcontextAuditMetadata { + success: boolean; + errorCode?: string; + summary?: Record; + itemCount?: number; + partial?: boolean; + responseBytes: number; + serializationMs: number; + requestedLimit?: number; + appliedLimit?: number; + pageTooLarge?: boolean; +} + export interface MCPToolResponse { [x: string]: unknown; content: Array<{ @@ -19,45 +45,197 @@ export interface MCPToolResponse { }; }>; isError?: boolean; + _meta?: { + dotcontext: DotcontextAuditMetadata; + }; } -/** - * Creates a successful JSON response for MCP tool handlers. - */ -export function createJsonResponse(data: unknown): MCPToolResponse { +export interface JsonResponseOptions { + payloadBudgetBytes?: number; + requestedLimit?: number; + appliedLimit?: number; +} + +function asRecord(value: unknown): Record | undefined { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : undefined; +} + +function boundedPayloadBudget(requested?: number): number { + const configured = requested ?? Number(process.env.DOTCONTEXT_MCP_PAYLOAD_BYTES); + if (!Number.isFinite(configured) || configured <= 0) { + return DEFAULT_MCP_TEXT_PAYLOAD_BYTES; + } + return Math.min(Math.floor(configured), ABSOLUTE_MCP_TEXT_PAYLOAD_BYTES); +} + +function findItemCount(record: Record | undefined): number | undefined { + if (!record) return undefined; + const page = asRecord(record.page); + if (typeof page?.recordsReturned === 'number') return page.recordsReturned; + for (const value of Object.values(record)) { + if (Array.isArray(value)) return value.length; + } + return undefined; +} + +function artifactReference(record: Record | undefined): Record | undefined { + const artifact = asRecord(record?.artifact); + if (!artifact || typeof artifact.id !== 'string') return undefined; return { - content: [{ - type: 'text' as const, - text: JSON.stringify(data, null, 2) - }] + id: artifact.id, + ...(typeof artifact.name === 'string' ? { name: artifact.name } : {}), + ...(typeof artifact.kind === 'string' ? { kind: artifact.kind } : {}), + ...(typeof artifact.path === 'string' ? { path: artifact.path } : {}), }; } -/** - * Creates an error response for MCP tool handlers. - */ -export function createErrorResponse(error: unknown): MCPToolResponse { +function buildAuditMetadata( + value: unknown, + responseBytes: number, + serializationMs: number, + options: JsonResponseOptions = {}, + forceError = false +): DotcontextAuditMetadata { + const record = asRecord(value); + const page = asRecord(record?.page); + const summary: Record = {}; + for (const key of AUDIT_SCALAR_KEYS) { + const scalar = record?.[key]; + if (scalar === null || typeof scalar === 'boolean' || typeof scalar === 'number') { + summary[key] = scalar; + } else if ( + typeof scalar === 'string' + && scalar.length <= 64 + && ['currentPhase', 'nextPhase', 'phase', 'scale', 'status'].includes(key) + ) { + summary[key] = scalar; + } + } + + const errorCode = typeof record?.errorCode === 'string' && record.errorCode.length <= 80 + ? record.errorCode + : undefined; + const requestedLimit = options.requestedLimit; + const appliedLimit = options.appliedLimit + ?? (typeof page?.recordsReturned === 'number' ? page.recordsReturned : undefined); + const meta: DotcontextAuditMetadata = { + success: forceError ? false : typeof record?.success === 'boolean' ? record.success : true, + ...(errorCode ? { errorCode } : {}), + ...(Object.keys(summary).length > 0 ? { summary } : {}), + ...(findItemCount(record) !== undefined ? { itemCount: findItemCount(record) } : {}), + ...(typeof page?.partial === 'boolean' + ? { partial: page.partial } + : typeof record?.partial === 'boolean' ? { partial: record.partial } : {}), + responseBytes, + serializationMs, + ...(requestedLimit !== undefined ? { requestedLimit } : {}), + ...(appliedLimit !== undefined ? { appliedLimit } : {}), + ...(record?.pageTooLarge === true ? { pageTooLarge: true } : {}), + }; + + // This is a programming invariant, not a fallback that silently truncates + // metadata. Keep additions to this object scalar and content-free. + if (Buffer.byteLength(JSON.stringify(meta), 'utf8') >= MAX_MCP_AUDIT_META_BYTES) { + throw new Error('dotcontext MCP audit metadata exceeded 2 KiB'); + } + return meta; +} + +function jsonEnvelope( + value: unknown, + options: JsonResponseOptions = {}, + forceError = false +): MCPToolResponse { + const started = performance.now(); + const text = JSON.stringify(value); + const serializationMs = Math.max(0, performance.now() - started); + const responseBytes = Buffer.byteLength(text, 'utf8'); + const budgetBytes = boundedPayloadBudget(options.payloadBudgetBytes); + + if (!forceError && responseBytes > budgetBytes) { + const reference = artifactReference(asRecord(value)); + if (reference) { + return jsonEnvelope({ + success: true, + exported: true, + artifact: reference, + originalResponseBytes: responseBytes, + budgetBytes, + }, { + ...options, + payloadBudgetBytes: ABSOLUTE_MCP_TEXT_PAYLOAD_BYTES, + }); + } + const itemCount = findItemCount(asRecord(value)); + const currentLimit = options.appliedLimit ?? itemCount; + const suggestedLimit = currentLimit && currentLimit > 1 + ? Math.max(1, Math.floor(currentLimit * budgetBytes / responseBytes * 0.8)) + : 1; + const tooLarge = { + success: false, + errorCode: 'MCP_PAGE_TOO_LARGE', + error: 'The MCP response exceeds the configured payload budget. Request a smaller page.', + pageTooLarge: true, + responseBytes, + budgetBytes, + suggestedLimit, + }; + return jsonEnvelope(tooLarge, { + ...options, + payloadBudgetBytes: ABSOLUTE_MCP_TEXT_PAYLOAD_BYTES, + appliedLimit: currentLimit, + }, true); + } + return { - content: [{ - type: 'text' as const, - text: JSON.stringify({ - success: false, - error: error instanceof Error ? error.message : String(error) - }, null, 2) - }], - isError: true + content: [{ type: 'text', text }], + ...(forceError ? { isError: true } : {}), + _meta: { + dotcontext: buildAuditMetadata(value, responseBytes, serializationMs, options, forceError), + }, }; } -/** - * Creates a plain text response for MCP tool handlers. - */ +/** Creates a successful compact JSON response. */ +export function createJsonResponse(data: unknown, options: JsonResponseOptions = {}): MCPToolResponse { + return jsonEnvelope(data, options); +} + +/** Creates a typed error response while preserving the existing text content contract. */ +export function createErrorResponse(error: unknown): MCPToolResponse { + const code = asRecord(error)?.code; + return jsonEnvelope({ + success: false, + ...(typeof code === 'string' ? { errorCode: code } : {}), + error: error instanceof Error ? error.message : String(error), + }, {}, true); +} + +/** Creates a bounded plain text response. */ export function createTextResponse(text: string): MCPToolResponse { + const responseBytes = Buffer.byteLength(text, 'utf8'); + const budgetBytes = boundedPayloadBudget(); + if (responseBytes > budgetBytes) { + return jsonEnvelope({ + success: false, + errorCode: 'MCP_PAYLOAD_TOO_LARGE', + error: 'The MCP text response exceeds the configured payload budget.', + pageTooLarge: true, + responseBytes, + budgetBytes, + }, {}, true); + } return { - content: [{ - type: 'text' as const, - text - }] + content: [{ type: 'text', text }], + _meta: { + dotcontext: { + success: true, + responseBytes, + serializationMs: 0, + }, + }, }; } @@ -78,52 +256,31 @@ export function createScaffoldResponse( const { filesGenerated = 0, pendingFiles = [], repoPath, enhancementPrompt: customPrompt, nextSteps: customNextSteps } = options; const hasFilesToEnhance = filesGenerated > 0 || pendingFiles.length > 0; const hasCustomPrompt = customPrompt || customNextSteps; - - // Build enhanced response with clear action signals const enhancedData = { - // Original data ...data, - - // Action signals (appear first for visibility) ...(hasFilesToEnhance || hasCustomPrompt) && { _actionRequired: true, _status: hasCustomPrompt && !hasFilesToEnhance ? 'ready' : 'incomplete', _warning: hasCustomPrompt && !hasFilesToEnhance ? 'ACTION SUGGESTED' : 'SCAFFOLDING REQUIRES ENHANCEMENT', - - // Enhancement instructions enhancementPrompt: customPrompt || buildEnhancementPrompt(pendingFiles, repoPath), - - // Clear next steps nextSteps: customNextSteps || [ 'Call context({ action: "listToFill" }) to get files needing content', 'For each file, call context({ action: "fillSingle", filePath: "..." })', 'Generate content based on the semantic context returned', 'Write enhanced content using the Write tool', ], - - // Files needing enhancement ...(pendingFiles.length > 0 && { pendingEnhancement: pendingFiles, pendingCount: pendingFiles.length, }), }, }; - - return { - content: [{ - type: 'text' as const, - text: JSON.stringify(enhancedData, null, 2) - }] - }; + return createJsonResponse(enhancedData); } -/** - * Build enhancement prompt for scaffold files. - */ function buildEnhancementPrompt(pendingFiles: string[], repoPath?: string): string { const filesList = pendingFiles.slice(0, 5).map((f, i) => `${i + 1}. ${f}`).join('\n'); const moreFiles = pendingFiles.length > 5 ? `\n... and ${pendingFiles.length - 5} more files` : ''; - return `IMPORTANT ENHANCEMENT REQUIRED Scaffolding has been created but files need codebase-specific content. diff --git a/src/mcp/server/__tests__/mcpServer.test.ts b/src/mcp/server/__tests__/mcpServer.test.ts index 79be42f4..adabafb7 100644 --- a/src/mcp/server/__tests__/mcpServer.test.ts +++ b/src/mcp/server/__tests__/mcpServer.test.ts @@ -1,7 +1,7 @@ import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs-extra'; -import { AIContextMCPServer } from '../mcpServer'; +import { AIContextMCPServer, MCP_LIST_LIMIT_SCHEMA, MCP_MAX_EVENTS_SCHEMA } from '../mcpServer'; // We can't fully test the MCP server without a transport, // but we can test instantiation and configuration @@ -45,6 +45,45 @@ describe('AIContextMCPServer', () => { }); }); + describe('bounded numeric schemas', () => { + it.each([ + [999, true], + [1000, true], + [1001, false], + ])('validates list limit boundary %s', (value, success) => { + expect(MCP_LIST_LIMIT_SCHEMA.safeParse(value).success).toBe(success); + }); + + it.each([ + [999, true], + [1000, true], + [1001, false], + ])('validates maxEvents boundary %s', (value, success) => { + expect(MCP_MAX_EVENTS_SCHEMA.safeParse(value).success).toBe(success); + }); + }); + + it('logs response metadata without parsing response content', async () => { + const server = new AIContextMCPServer({ repoPath: tempDir }); + const parse = jest.spyOn(JSON, 'parse'); + + await (server as any).logToolResponse(tempDir, 'harness', 'listSessions', {}, { + content: [{ type: 'text', text: '{not-json' }], + _meta: { + dotcontext: { + success: true, + responseBytes: 9, + serializationMs: 0, + itemCount: 0, + partial: false, + }, + }, + }); + + expect(parse).not.toHaveBeenCalled(); + parse.mockRestore(); + }); + describe('resource registration', () => { it('should register resource templates', () => { // The server registers resources in constructor diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index 0e0bf5d8..f5440d01 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -53,6 +53,9 @@ import { type WorkflowAdvanceParams, type WorkflowManageParams, type MCPToolResponse, + createErrorResponse, + validateMcpInput, + MCP_INPUT_LIMITS, } from '../gateway'; export interface MCPServerOptions { @@ -66,6 +69,17 @@ export interface MCPServerOptions { contextBuilder?: SemanticContextBuilder; } +export const MCP_LIST_LIMIT_SCHEMA = z.number().int().min(1).max(MCP_INPUT_LIMITS.listMaximum); +export const MCP_MAX_EVENTS_SCHEMA = z.number().int().min(1).max(MCP_INPUT_LIMITS.maxEventsMaximum); +const mcpString = () => z.string().max(MCP_INPUT_LIMITS.scalarString); +const mcpPattern = () => mcpString().max(MCP_INPUT_LIMITS.patternLength); +const mcpArray = (schema: T) => z.array(schema).max(MCP_INPUT_LIMITS.arrayItems); +const mcpContent = () => z.unknown().superRefine((value, context) => { + if (typeof value === 'string' && Buffer.byteLength(value, 'utf8') > MCP_INPUT_LIMITS.contentString) { + context.addIssue({ code: z.ZodIssueCode.custom, message: `content exceeds ${MCP_INPUT_LIMITS.contentString} UTF-8 bytes` }); + } +}); + export class AIContextMCPServer { private server: McpServer; private contextBuilder: SemanticContextBuilder; @@ -123,27 +137,27 @@ export class AIContextMCPServer { inputSchema: { action: z.enum(['read', 'list', 'analyze', 'search', 'getStructure']) .describe('Action to perform'), - filePath: z.string().optional() + filePath: mcpString().optional() .describe('(read, analyze) File path to read or analyze'), - pattern: z.string().optional() + pattern: mcpPattern().optional() .describe('(list, search) Glob pattern for list, regex pattern for search'), - cwd: z.string().optional() + cwd: mcpString().optional() .describe('(list, search) Working directory'), encoding: z.enum(['utf-8', 'ascii', 'binary']).optional() .describe('(read) File encoding'), - ignore: z.array(z.string()).optional() + ignore: mcpArray(mcpPattern()).optional() .describe('(list) Patterns to ignore'), - symbolTypes: z.array(z.enum(['class', 'interface', 'function', 'type', 'enum'])).optional() + symbolTypes: mcpArray(z.enum(['class', 'interface', 'function', 'type', 'enum'])).optional() .describe('(analyze) Types of symbols to extract'), - fileGlob: z.string().optional() + fileGlob: mcpPattern().optional() .describe('(search) Glob pattern to filter files'), - maxResults: z.number().optional() + maxResults: z.number().int().min(1).max(MCP_INPUT_LIMITS.listMaximum).optional() .describe('(search) Maximum results to return'), - rootPath: z.string().optional() + rootPath: mcpString().optional() .describe('(getStructure) Root path for structure'), maxDepth: z.number().optional() .describe('(getStructure) Maximum directory depth'), - includePatterns: z.array(z.string()).optional() + includePatterns: mcpArray(mcpPattern()).optional() .describe('(getStructure) Include patterns'), } }, wrap('explore', async (params): Promise => { @@ -176,17 +190,17 @@ export class AIContextMCPServer { inputSchema: { action: z.enum(['check', 'bootstrapStatus', 'init', 'fill', 'fillSingle', 'listToFill', 'getMap', 'buildSemantic', 'scaffoldPlan', 'searchQA', 'generateQA', 'getFlow', 'detectPatterns']) .describe('Action to perform'), - repoPath: z.string().optional() + repoPath: mcpString().optional() .describe('Repository path (defaults to cwd)'), - outputDir: z.string().optional() + outputDir: mcpString().optional() .describe('Output directory (default: ./.context)'), type: z.enum(['docs', 'agents', 'both']).optional() .describe('(init) Type of scaffolding to create'), semantic: z.boolean().optional() .describe('(init, scaffoldPlan) Enable semantic analysis'), - include: z.array(z.string()).optional() + include: mcpArray(mcpString()).optional() .describe('(init) Include patterns'), - exclude: z.array(z.string()).optional() + exclude: mcpArray(mcpString()).optional() .describe('(init) Exclude patterns'), autoFill: z.boolean().optional() .describe('(init, scaffoldPlan) Auto-fill with codebase content'), @@ -198,9 +212,9 @@ export class AIContextMCPServer { .describe('(fill, listToFill) Which scaffolding to target, including nested skills and harness sensors'), offset: z.number().optional() .describe('(fill) Skip first N files'), - limit: z.number().optional() + limit: MCP_LIST_LIMIT_SCHEMA.optional() .describe('(fill) Max files to return'), - filePath: z.string().optional() + filePath: mcpString().optional() .describe('(fillSingle) Absolute path to scaffold file'), section: z.enum([ 'all', 'meta', 'stack', 'structure', 'architecture', @@ -209,7 +223,7 @@ export class AIContextMCPServer { .describe('(getMap) Section to retrieve; the snapshot auto-refreshes on read'), contextType: z.enum(['documentation', 'playbook', 'plan', 'compact']).optional() .describe('(buildSemantic) Type of context to build'), - targetFile: z.string().optional() + targetFile: mcpString().optional() .describe('(buildSemantic) Target file for focused context'), options: z.object({ useLSP: z.boolean().optional(), @@ -218,17 +232,17 @@ export class AIContextMCPServer { includeSignatures: z.boolean().optional() }).optional() .describe('(buildSemantic, generateQA, searchQA, getFlow, detectPatterns) Builder/analyzer options'), - planName: z.string().optional() + planName: mcpString().optional() .describe('(scaffoldPlan) Name of the plan'), - title: z.string().optional() + title: mcpString().optional() .describe('(scaffoldPlan) Plan title'), - summary: z.string().optional() + summary: mcpString().optional() .describe('(scaffoldPlan) Plan summary/goal'), - query: z.string().optional() + query: mcpString().optional() .describe('(searchQA) Query string used to rank generated Q&A helper docs'), - entryFile: z.string().optional() + entryFile: mcpString().optional() .describe('(getFlow) Entry file path for flow tracing'), - entryFunction: z.string().optional() + entryFunction: mcpString().optional() .describe('(getFlow) Optional entry function for flow tracing'), } }, wrap('context', async (params): Promise => { @@ -264,8 +278,8 @@ This is the harness-backed entry point for planned work. If the user asked to cr - Just exploring/researching code - User explicitly wants to skip workflow`, inputSchema: { - name: z.string().describe('Workflow/feature name (required)'), - description: z.string().optional() + name: mcpString().describe('Workflow/feature name (required)'), + description: mcpString().optional() .describe('Task description for scale detection'), scale: z.enum(['QUICK', 'SMALL', 'MEDIUM', 'LARGE']).optional() .describe(`Project scale - AI should evaluate based on task characteristics: @@ -323,7 +337,7 @@ Returns: Current phase, all phase statuses, gate settings, linked plans, agent a Use this for session orientation: current workflow state, next steps, relevant skills, and portable gate decision hints. Adapters should render this response instead of reimplementing workflow direction.`, inputSchema: { - repoPath: z.string().optional() + repoPath: mcpString().optional() .describe('Repository path'), phaseHint: z.enum(['P', 'R', 'E', 'V', 'C']).optional() .describe('Optional PREVC phase hint derived from the caller event'), @@ -346,7 +360,7 @@ Enforces gates: Use force=true to bypass gates, or use workflow-manage({ action: 'setAutonomous' }).`, inputSchema: { - outputs: z.array(z.string()).optional() + outputs: mcpArray(mcpString()).optional() .describe('Artifact paths produced in current phase'), force: z.boolean().optional() .describe('Force advancement even if gates block'), @@ -373,59 +387,59 @@ Actions: inputSchema: { action: z.enum(['handoff', 'collaborate', 'createDoc', 'getGates', 'approvePlan', 'setAutonomous', 'checkpoint', 'recordArtifact', 'defineTask', 'runSensors']) .describe('Action to perform'), - from: z.string().optional() + from: mcpString().optional() .describe('(handoff) Agent handing off (e.g., feature-developer)'), - to: z.string().optional() + to: mcpString().optional() .describe('(handoff) Agent receiving (e.g., code-reviewer)'), - artifacts: z.array(z.string()).optional() + artifacts: mcpArray(mcpString()).optional() .describe('(handoff) Artifacts to hand off'), - topic: z.string().optional() + topic: mcpString().optional() .describe('(collaborate) Collaboration topic'), - participants: z.array(z.enum(PREVC_ROLES as unknown as [string, ...string[]])).optional() + participants: mcpArray(z.enum(PREVC_ROLES as unknown as [string, ...string[]])).optional() .describe('(collaborate) Participating roles'), type: z.enum(['prd', 'tech-spec', 'architecture', 'adr', 'test-plan', 'changelog']).optional() .describe('(createDoc) Document type'), - docName: z.string().optional() + docName: mcpString().optional() .describe('(createDoc) Document name'), - planSlug: z.string().optional() + planSlug: mcpString().optional() .describe('(approvePlan) Plan to approve'), approver: z.enum(PREVC_ROLES as unknown as [string, ...string[]]).optional() .describe('(approvePlan) Approving role'), - notes: z.string().optional() + notes: mcpString().optional() .describe('(approvePlan) Approval notes'), enabled: z.boolean().optional() .describe('(setAutonomous) Enable/disable'), - reason: z.string().optional() + reason: mcpString().optional() .describe('(setAutonomous) Reason for change'), - name: z.string().optional() + name: mcpString().optional() .describe('(recordArtifact) Artifact name'), kind: z.enum(['text', 'json', 'file']).optional() .describe('(recordArtifact) Artifact kind'), - content: z.any().optional() + content: mcpContent().optional() .describe('(recordArtifact, checkpoint) Structured content or payload'), - filePath: z.string().optional() + filePath: mcpString().optional() .describe('(recordArtifact) Artifact file path'), - taskTitle: z.string().optional() + taskTitle: mcpString().optional() .describe('(defineTask) Task title'), - taskDescription: z.string().optional() + taskDescription: mcpString().optional() .describe('(defineTask) Task description'), - owner: z.string().optional() + owner: mcpString().optional() .describe('(defineTask) Task owner'), - inputs: z.array(z.string()).optional() + inputs: mcpArray(mcpString()).optional() .describe('(defineTask) Required inputs'), - expectedOutputs: z.array(z.string()).optional() + expectedOutputs: mcpArray(mcpString()).optional() .describe('(defineTask) Expected outputs'), - acceptanceCriteria: z.array(z.string()).optional() + acceptanceCriteria: mcpArray(mcpString()).optional() .describe('(defineTask) Acceptance criteria'), - requiredSensors: z.array(z.string()).optional() + requiredSensors: mcpArray(mcpString()).optional() .describe('(defineTask) Required sensors'), - requiredArtifacts: z.array(z.union([z.string(), z.record(z.string(), z.any())])).optional() + requiredArtifacts: mcpArray(z.union([mcpString(), z.record(mcpString(), z.any())])).optional() .describe('(defineTask) Required artifacts (string for exact name, or { kind: glob, glob, minMatches? } / { kind: file-count, glob, min } / { kind: name|path, ... })'), - sensors: z.array(z.string()).optional() + sensors: mcpArray(mcpString()).optional() .describe('(runSensors) Sensors to execute'), data: z.any().optional() .describe('(checkpoint) Optional checkpoint payload'), - artifactIds: z.array(z.string()).optional() + artifactIds: mcpArray(mcpString()).optional() .describe('(checkpoint) Artifact IDs associated with the checkpoint'), pause: z.boolean().optional() .describe('(checkpoint) Pause the active harness session after checkpoint'), @@ -449,7 +463,7 @@ Actions: inputSchema: { action: z.enum(['exportRules', 'exportDocs', 'exportAgents', 'exportContext', 'exportSkills', 'reverseSync', 'importDocs', 'importAgents', 'importSkills']) .describe('Action to perform'), - preset: z.string().optional() + preset: mcpString().optional() .describe('Target AI tool preset'), force: z.boolean().optional() .describe('Overwrite existing files'), @@ -481,7 +495,7 @@ Actions: .describe('(import*) Auto-detect files'), addMetadata: z.boolean().optional() .describe('(reverseSync) Add frontmatter metadata'), - repoPath: z.string().optional() + repoPath: mcpString().optional() .describe('Repository path'), } }, wrap('sync', async (params): Promise => { @@ -508,29 +522,29 @@ Actions: inputSchema: { action: z.enum(['link', 'getLinked', 'getDetails', 'getForPhase', 'updatePhase', 'recordDecision', 'updateStep', 'getStatus', 'syncMarkdown', 'commitPhase']) .describe('Action to perform'), - planSlug: z.string().optional() + planSlug: mcpString().optional() .describe('Plan slug/identifier'), - phaseId: z.string().optional() + phaseId: mcpString().optional() .describe('(updatePhase, updateStep, commitPhase) Phase ID'), status: z.enum(['pending', 'in_progress', 'completed', 'skipped']).optional() .describe('(updatePhase, updateStep) New status'), phase: z.enum(['P', 'R', 'E', 'V', 'C']).optional() .describe('(getForPhase, recordDecision) PREVC phase'), - title: z.string().optional() + title: mcpString().optional() .describe('(recordDecision) Decision title'), - description: z.string().optional() + description: mcpString().optional() .describe('(recordDecision) Decision description'), - alternatives: z.array(z.string()).optional() + alternatives: mcpArray(mcpString()).optional() .describe('(recordDecision) Considered alternatives'), stepIndex: z.number().optional() .describe('(updateStep) Step number (1-based)'), - output: z.string().optional() + output: mcpString().optional() .describe('(updateStep) Step output artifact'), - notes: z.string().optional() + notes: mcpString().optional() .describe('(updateStep) Execution notes'), - coAuthor: z.string().optional() + coAuthor: mcpString().optional() .describe('(commitPhase) Agent name for Co-Authored-By footer'), - stagePatterns: z.array(z.string()).optional() + stagePatterns: mcpArray(mcpString()).optional() .describe('(commitPhase) Patterns for files to stage (default: [".context/**"])'), dryRun: z.boolean().optional() .describe('(commitPhase) Preview without committing'), @@ -552,9 +566,9 @@ Actions: inputSchema: { action: z.enum(['discover', 'getInfo', 'orchestrate', 'getSequence', 'getDocs', 'getPhaseDocs', 'listTypes']) .describe('Action to perform'), - agentType: z.string().optional() + agentType: mcpString().optional() .describe('(getInfo) Agent type identifier'), - task: z.string().optional() + task: mcpString().optional() .describe('(orchestrate, getSequence) Task description'), phase: z.enum(['P', 'R', 'E', 'V', 'C']).optional() .describe('(orchestrate, getPhaseDocs) PREVC phase'), @@ -562,7 +576,7 @@ Actions: .describe('(orchestrate) PREVC role'), includeReview: z.boolean().optional() .describe('(getSequence) Include code review'), - phases: z.array(z.enum(['P', 'R', 'E', 'V', 'C'])).optional() + phases: mcpArray(z.enum(['P', 'R', 'E', 'V', 'C'])).optional() .describe('(getSequence) Phases to include'), agent: z.enum(AGENT_TYPES as unknown as [string, ...string[]]).optional() .describe('(getDocs) Agent type for docs'), @@ -583,17 +597,17 @@ Actions: inputSchema: { action: z.enum(['list', 'getContent', 'getForPhase', 'scaffold', 'export', 'fill']) .describe('Action to perform'), - skillSlug: z.string().optional() + skillSlug: mcpString().optional() .describe('(getContent) Skill identifier'), phase: z.enum(['P', 'R', 'E', 'V', 'C']).optional() .describe('(getForPhase) PREVC phase'), - skills: z.array(z.string()).optional() + skills: mcpArray(mcpString()).optional() .describe('(scaffold, fill) Specific skills to process'), includeContent: z.boolean().optional() .describe('(list) Include full content'), includeBuiltIn: z.boolean().optional() .describe('(export, fill) Include built-in skills'), - preset: z.string().optional() + preset: mcpString().optional() .describe('(export) Target AI tool preset'), force: z.boolean().optional() .describe('(scaffold, export) Overwrite existing'), @@ -670,71 +684,76 @@ Actions: 'resetPolicy', 'evaluatePolicy', ]).describe('Action to perform'), - sessionId: z.string().optional(), - taskId: z.string().optional(), - name: z.string().optional(), - title: z.string().optional(), - description: z.string().optional(), - owner: z.string().optional(), + sessionId: mcpString().optional(), + taskId: mcpString().optional(), + name: mcpString().optional(), + title: mcpString().optional(), + description: mcpString().optional(), + owner: mcpString().optional(), status: z.enum(['draft', 'ready', 'in_progress', 'blocked', 'completed', 'failed']).optional(), - metadata: z.record(z.string(), z.unknown()).optional(), + metadata: z.record(mcpString(), z.unknown()).optional(), level: z.enum(['debug', 'info', 'warn', 'error']).optional(), - event: z.string().optional(), - message: z.string().optional(), - data: z.record(z.string(), z.unknown()).optional(), + event: mcpString().optional(), + message: mcpString().optional(), + data: z.record(mcpString(), z.unknown()).optional(), kind: z.enum(['text', 'json', 'file']).optional(), - content: z.unknown().optional(), - path: z.string().optional(), - note: z.string().optional(), - artifactIds: z.array(z.string()).optional(), + content: mcpContent().optional(), + path: mcpString().optional(), + note: mcpString().optional(), + artifactIds: mcpArray(mcpString()).optional(), pause: z.boolean().optional(), - sensorId: z.string().optional(), - sensorName: z.string().optional(), + sensorId: mcpString().optional(), + sensorName: mcpString().optional(), sensorSeverity: z.enum(['info', 'warning', 'critical']).optional(), sensorBlocking: z.boolean().optional(), sensorStatus: z.enum(['passed', 'failed', 'skipped', 'blocked']).optional(), - summary: z.string().optional(), - evidence: z.array(z.string()).optional(), + summary: mcpString().optional(), + evidence: mcpArray(mcpString()).optional(), output: z.unknown().optional(), - details: z.record(z.string(), z.unknown()).optional(), + details: z.record(mcpString(), z.unknown()).optional(), blockOnWarnings: z.boolean().optional(), requireEvidence: z.boolean().optional(), - inputs: z.array(z.string()).optional(), - expectedOutputs: z.array(z.string()).optional(), - acceptanceCriteria: z.array(z.string()).optional(), - requiredSensors: z.array(z.string()).optional(), - requiredArtifacts: z.array(z.union([z.string(), z.record(z.string(), z.any())])).optional(), - from: z.string().optional(), - to: z.string().optional(), - artifacts: z.array(z.string()).optional(), - replayId: z.string().optional(), + inputs: mcpArray(mcpString()).optional(), + expectedOutputs: mcpArray(mcpString()).optional(), + acceptanceCriteria: mcpArray(mcpString()).optional(), + requiredSensors: mcpArray(mcpString()).optional(), + requiredArtifacts: mcpArray(z.union([mcpString(), z.record(mcpString(), z.any())])).optional(), + from: mcpString().optional(), + to: mcpString().optional(), + artifacts: mcpArray(mcpString()).optional(), + replayId: mcpString().optional(), includePayloads: z.boolean().optional(), - maxEvents: z.number().optional(), - datasetId: z.string().optional(), - sessionIds: z.array(z.string()).optional(), + maxEvents: MCP_MAX_EVENTS_SCHEMA.optional().default(MCP_INPUT_LIMITS.maxEventsDefault), + datasetId: mcpString().optional(), + sessionIds: mcpArray(mcpString()).optional(), includeSuccessfulSessions: z.boolean().optional(), + limit: MCP_LIST_LIMIT_SCHEMA.optional(), + cursor: mcpString().max(MCP_INPUT_LIMITS.cursorLength).optional(), + direction: z.enum(['oldest', 'newest']).optional(), + createdAfter: mcpString().optional(), + createdBefore: mcpString().optional(), scope: z.enum(['sensor', 'artifact', 'handoff', 'workflow', 'task', 'risk']).optional(), effect: z.enum(['allow', 'deny', 'require_approval']).optional(), target: z.enum(['tool', 'action', 'path', 'risk']).optional(), - pattern: z.string().optional(), - pathPattern: z.string().optional(), - approvalRole: z.string().optional(), - approvedBy: z.string().optional(), - approvalNote: z.string().optional(), + pattern: mcpPattern().optional(), + pathPattern: mcpPattern().optional(), + approvalRole: mcpString().optional(), + approvedBy: mcpString().optional(), + approvalNote: mcpString().optional(), risk: z.enum(['low', 'medium', 'high', 'critical']).optional(), policy: z.object({ defaultEffect: z.enum(['allow', 'deny']).optional(), - rules: z.array(z.object({ - id: z.string().optional(), + rules: mcpArray(z.object({ + id: mcpString().optional(), effect: z.enum(['allow', 'deny', 'require_approval']), target: z.enum(['tool', 'action', 'path', 'risk']).optional(), - pattern: z.string().optional(), - pathPattern: z.string().optional(), - approvalRole: z.string().optional(), - reason: z.string().optional(), - description: z.string().optional(), + pattern: mcpPattern().optional(), + pathPattern: mcpPattern().optional(), + approvalRole: mcpString().optional(), + reason: mcpString().optional(), + description: mcpString().optional(), scope: z.enum(['sensor', 'artifact', 'handoff', 'workflow', 'task', 'risk']).optional(), - })).optional(), + })).max(MCP_INPUT_LIMITS.arrayItems).optional(), }).optional(), } }, wrap('harness', async (params): Promise => { @@ -995,21 +1014,28 @@ Actions: handler: (params: TParams) => Promise ): (params: TParams) => Promise { return async (params: TParams) => { - const resolvedRepoPath = this.getRepoPath((params as { repoPath?: string })?.repoPath); const action = typeof (params as { action?: string })?.action === 'string' ? (params as { action?: string }).action! : toolName; + try { + validateMcpInput(params); + } catch (error) { + const resolvedRepoPath = this.getRepoPath(); + const response = createErrorResponse(error); + await this.logToolError(resolvedRepoPath, toolName, action, {} as TParams, error); + return response; + } + + const resolvedRepoPath = this.getRepoPath((params as { repoPath?: string })?.repoPath); + // Validate file paths to prevent path traversal attacks try { this.validatePathParams(params, resolvedRepoPath); } catch (error) { if (error instanceof SecurityError) { this.log(`[SECURITY] Path traversal blocked: ${error.message} (tool: ${toolName}, path: ${error.attemptedPath})`); - const errorResponse: MCPToolResponse = { - content: [{ type: 'text', text: JSON.stringify({ success: false, error: `Security: ${error.message}` }) }], - isError: true, - }; + const errorResponse = createErrorResponse(`Security: ${error.message}`); await this.logToolError(resolvedRepoPath, toolName, action, params, error); return errorResponse; } @@ -1050,12 +1076,8 @@ Actions: params: TParams, response: MCPToolResponse ): Promise { - const payload = this.parseResponsePayload(response); - const success = typeof payload?.success === 'boolean' - ? payload.success - : !response.isError; - const errorMessage = typeof payload?.error === 'string' ? payload.error : undefined; - const resultSummary = payload ? this.buildResultSummary(payload) : undefined; + const audit = response._meta?.dotcontext; + const success = audit?.success ?? !response.isError; await logMcpAction(repoPath, { tool: toolName, @@ -1063,9 +1085,9 @@ Actions: status: success ? 'success' : 'error', details: { params, - ...(resultSummary ? { result: resultSummary } : {}), + ...(audit ? { response: audit } : {}), }, - ...(success ? {} : { error: errorMessage || 'Tool reported failure' }), + ...(success ? {} : { error: audit?.errorCode || 'Tool reported failure' }), }); } @@ -1087,41 +1109,6 @@ Actions: }); } - private parseResponsePayload(response: MCPToolResponse): Record | null { - const text = response.content?.[0]?.text; - if (!text) return null; - try { - const parsed = JSON.parse(text); - return parsed && typeof parsed === 'object' ? parsed as Record : null; - } catch { - return null; - } - } - - private buildResultSummary(payload: Record): Record | null { - const summaryKeys = [ - 'success', - 'message', - 'currentPhase', - 'nextPhase', - 'phase', - 'scale', - 'planSlug', - 'count', - 'total', - 'status', - ]; - const summary: Record = {}; - - for (const key of summaryKeys) { - if (key in payload) { - summary[key] = payload[key]; - } - } - - return Object.keys(summary).length > 0 ? summary : null; - } - /** * Start the MCP server with stdio transport */ From ac985bd0c987ce0dc49f2daee938e1dcedeb364e Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:32:29 -0300 Subject: [PATCH 13/39] fix: bound LSP protocol framing --- .../lsp/__tests__/fixtures/fake-lsp-server.js | 11 +- .../lsp/__tests__/lspLayer.lifecycle.test.ts | 122 ++++++++++++++++- .../adapters/out/semantic/lsp/lspLayer.ts | 126 ++++++++++++++++-- 3 files changed, 242 insertions(+), 17 deletions(-) diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js index fc7ea1d5..9a2cd90b 100644 --- a/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js +++ b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js @@ -4,6 +4,7 @@ const fs = require('fs'); const mode = process.argv[2] || 'normal'; const pidFile = process.argv[3]; +const attackSize = Number(process.argv[4]) || 4096; if (pidFile) fs.appendFileSync(pidFile, `${process.pid}\n`); if (mode === 'ignore-shutdown') { @@ -19,7 +20,15 @@ function send(message) { function respond(message) { if (message.method === 'initialize') { - if (mode === 'crash-after-spawn') { + if (mode === 'incomplete-huge-header') { + process.stdout.write('X'.repeat(attackSize)); + } else if (mode === 'incomplete-huge-body') { + process.stdout.write( + `Content-Length: ${attackSize * 2}\r\n\r\n${'X'.repeat(attackSize)}` + ); + } else if (mode === 'abusive-content-length') { + process.stdout.write('Content-Length: 999999999999999999999999\r\n\r\n'); + } else if (mode === 'crash-after-spawn') { process.exit(19); } else if (mode === 'reject-initialize') { send({ jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'initialize rejected' } }); diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts index aca8c164..ad867cbd 100644 --- a/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts +++ b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts @@ -1,20 +1,40 @@ import * as fs from 'fs/promises'; import * as os from 'os'; import * as path from 'path'; +import type { ChildProcess } from 'child_process'; import { LSPLayer, LSPLayerOptions, LSPLifecycleEvent } from '../lspLayer'; import type { LSPServerConfig } from '../../types'; const FIXTURE = path.join(__dirname, 'fixtures', 'fake-lsp-server.js'); const TIMEOUT_MS = 150; -function server(mode: string, pidFile: string): LSPServerConfig { - return { command: process.execPath, args: [FIXTURE, mode, pidFile] }; +function server(mode: string, pidFile: string, attackSize?: number): LSPServerConfig { + const args = [FIXTURE, mode, pidFile]; + if (attackSize !== undefined) args.push(String(attackSize)); + return { command: process.execPath, args }; } -async function waitUntil(predicate: () => boolean, timeoutMs = 2_000): Promise { +interface InspectableHandle { + process: ChildProcess; + pendingRequests: Map; + timers: Set; + buffer: Buffer; +} + +function currentHandle(subject: LSPLayer): InspectableHandle { + const handles = (subject as unknown as { handles: Map }).handles; + const [handle] = [...handles.values()]; + if (!handle) throw new Error('expected an active LSP handle'); + return handle; +} + +async function waitUntil( + predicate: () => boolean | Promise, + timeoutMs = 2_000 +): Promise { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - if (predicate()) return; + if (await predicate()) return; await new Promise((resolve) => setTimeout(resolve, 10)); } throw new Error('condition did not become true before timeout'); @@ -103,6 +123,65 @@ describe('LSPLayer process lifecycle', () => { await waitUntil(() => !processIsAlive(pid)); }); + it.each([ + { + name: 'incomplete huge header', + mode: 'incomplete-huge-header', + attackSize: 4096, + overrides: { maxHeaderBytes: 1024, maxReceiveBufferBytes: 8192 }, + reason: /header limit exceeded/, + }, + { + name: 'incomplete huge body', + mode: 'incomplete-huge-body', + attackSize: 4096, + overrides: { maxBodyBytes: 8192, maxReceiveBufferBytes: 2048 }, + reason: /receive buffer limit exceeded|frame exceeds receive buffer limit/, + }, + { + name: 'abusive Content-Length', + mode: 'abusive-content-length', + attackSize: 4096, + overrides: { maxBodyBytes: 8192 }, + reason: /Content-Length exceeds body limit/, + }, + { + name: 'caller attempt to raise the absolute header maximum', + mode: 'incomplete-huge-header', + attackSize: 32 * 1024, + overrides: { maxHeaderBytes: Number.MAX_SAFE_INTEGER }, + reason: /header limit exceeded/, + }, + ])('terminates and opens the circuit for $name', async ({ + mode, + attackSize, + overrides, + reason, + }) => { + const events: LSPLifecycleEvent[] = []; + const subject = createLayer( + { typescript: server(mode, pidFile, attackSize) }, + { ...overrides, onLifecycleEvent: (event) => events.push(event) } + ); + + const initialization = subject.ensureServer('typescript', projectPath); + const handle = currentHandle(subject); + await expect(initialization).resolves.toBe(false); + const [pid] = await readPids(pidFile); + expect(pid).toBeDefined(); + await waitUntil(() => !processIsAlive(pid)); + expect(events).toEqual(expect.arrayContaining([ + expect.objectContaining({ state: 'failed', reason: expect.stringMatching(reason) }), + expect.objectContaining({ state: 'stopped', pendingRequestCount: 0 }), + ])); + expect(handle.pendingRequests.size).toBe(0); + expect(handle.timers.size).toBe(0); + expect(handle.buffer).toHaveLength(0); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); + expect(await readPids(pidFile)).toEqual([pid]); + }); + it('deduplicates concurrent initialization for the same language and project', async () => { const subject = createLayer({ typescript: server('normal', pidFile) }); @@ -160,4 +239,39 @@ describe('LSPLayer process lifecycle', () => { ); await expect(subject.shutdown()).resolves.toBeUndefined(); }); + + it('is safe when shutdown races with initialization', async () => { + const subject = createLayer({ typescript: server('timeout-initialize', pidFile) }); + + const initialization = subject.ensureServer('typescript', projectPath); + await waitUntil(async () => (await readPids(pidFile)).length === 1); + const [pid] = await readPids(pidFile); + const handle = currentHandle(subject); + + await expect(Promise.all([initialization, subject.shutdown()])).resolves.toEqual([ + false, + undefined, + ]); + expect(processIsAlive(pid)).toBe(false); + expect(handle.pendingRequests.size).toBe(0); + expect(handle.timers.size).toBe(0); + }); + + it('removes final listeners, timers, buffers, and process handles after shutdown', async () => { + const subject = createLayer({ typescript: server('normal', pidFile) }); + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(true); + const [pid] = await readPids(pidFile); + const handle = currentHandle(subject); + + await subject.shutdown(); + + expect(processIsAlive(pid)).toBe(false); + expect(handle.pendingRequests.size).toBe(0); + expect(handle.timers.size).toBe(0); + expect(handle.buffer).toHaveLength(0); + expect(handle.process.eventNames()).toEqual([]); + expect(handle.process.stdin?.eventNames()).toEqual([]); + expect(handle.process.stdout?.eventNames()).toEqual([]); + expect(handle.process.stderr?.eventNames()).toEqual([]); + }); }); diff --git a/src/harness/adapters/out/semantic/lsp/lspLayer.ts b/src/harness/adapters/out/semantic/lsp/lspLayer.ts index a7f33990..036322f1 100644 --- a/src/harness/adapters/out/semantic/lsp/lspLayer.ts +++ b/src/harness/adapters/out/semantic/lsp/lspLayer.ts @@ -57,6 +57,7 @@ interface ServerHandle { initialization: Promise; stopping?: Promise; pendingRequests: Map; + timers: Set; buffer: Buffer; startedAt: number; terminationReason?: string; @@ -74,6 +75,9 @@ export interface LSPLayerOptions { requestTimeoutMs?: number; shutdownTimeoutMs?: number; terminationGraceMs?: number; + maxHeaderBytes?: number; + maxBodyBytes?: number; + maxReceiveBufferBytes?: number; onLifecycleEvent?: (event: LSPLifecycleEvent) => void; } @@ -98,6 +102,15 @@ const LSP_SERVER_CONFIGS: Record = { const DEFAULT_REQUEST_TIMEOUT_MS = 10_000; const DEFAULT_SHUTDOWN_TIMEOUT_MS = 2_000; const DEFAULT_TERMINATION_GRACE_MS = 2_000; +export const MAX_LSP_HEADER_BYTES = 16 * 1024; +export const MAX_LSP_BODY_BYTES = 8 * 1024 * 1024; +export const MAX_LSP_RECEIVE_BUFFER_BYTES = + MAX_LSP_HEADER_BYTES + 4 + MAX_LSP_BODY_BYTES; + +function boundedProtocolLimit(value: number | undefined, maximum: number): number { + if (value === undefined || !Number.isSafeInteger(value) || value <= 0) return maximum; + return Math.min(value, maximum); +} export class LSPLayer { private readonly handles = new Map(); @@ -106,6 +119,9 @@ export class LSPLayer { private readonly requestTimeoutMs: number; private readonly shutdownTimeoutMs: number; private readonly terminationGraceMs: number; + private readonly maxHeaderBytes: number; + private readonly maxBodyBytes: number; + private readonly maxReceiveBufferBytes: number; private readonly onLifecycleEvent?: (event: LSPLifecycleEvent) => void; private messageId = 0; private shuttingDown?: Promise; @@ -115,6 +131,12 @@ export class LSPLayer { this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; this.shutdownTimeoutMs = options.shutdownTimeoutMs ?? DEFAULT_SHUTDOWN_TIMEOUT_MS; this.terminationGraceMs = options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS; + this.maxHeaderBytes = boundedProtocolLimit(options.maxHeaderBytes, MAX_LSP_HEADER_BYTES); + this.maxBodyBytes = boundedProtocolLimit(options.maxBodyBytes, MAX_LSP_BODY_BYTES); + this.maxReceiveBufferBytes = boundedProtocolLimit( + options.maxReceiveBufferBytes, + MAX_LSP_RECEIVE_BUFFER_BYTES + ); this.onLifecycleEvent = options.onLifecycleEvent; } @@ -161,6 +183,7 @@ export class LSPLayer { state: 'starting', initialization: Promise.resolve(false), pendingRequests: new Map(), + timers: new Set(), buffer: Buffer.alloc(0), startedAt: Date.now(), forcedKill: false, @@ -243,6 +266,10 @@ export class LSPLayer { }); return true; } catch (error) { + if (handle.state === 'stopping' || handle.state === 'stopped') { + await handle.stopping; + return false; + } this.failedCircuits.add(handle.key); const reason = error instanceof Error ? `initialize failed: ${error.message}` : 'initialize failed'; @@ -285,23 +312,61 @@ export class LSPLayer { } private handleServerData(handle: ServerHandle, data: Buffer): void { + if (handle.state === 'stopping' || handle.state === 'stopped') return; + if (data.length > this.maxReceiveBufferBytes - handle.buffer.length) { + this.failProtocol(handle, 'receive buffer limit exceeded'); + return; + } handle.buffer = Buffer.concat([handle.buffer, data]); while (true) { const headerEnd = handle.buffer.indexOf('\r\n\r\n'); - if (headerEnd < 0) return; + if (headerEnd < 0) { + if (handle.buffer.length > this.maxHeaderBytes) { + this.failProtocol(handle, 'incomplete header limit exceeded'); + } + return; + } + if (headerEnd > this.maxHeaderBytes) { + this.failProtocol(handle, 'header limit exceeded'); + return; + } const header = handle.buffer.subarray(0, headerEnd).toString('ascii'); - const match = /(?:^|\r\n)Content-Length:\s*(\d+)/i.exec(header); - if (!match) { - handle.buffer = Buffer.alloc(0); + const contentLengthHeaders = header + .split('\r\n') + .filter((line) => /^Content-Length:/i.test(line)); + if (contentLengthHeaders.length !== 1) { + this.failProtocol(handle, 'expected exactly one Content-Length header'); + return; + } + const rawContentLength = contentLengthHeaders[0].slice( + contentLengthHeaders[0].indexOf(':') + 1 + ).trim(); + if (!/^[0-9]+$/.test(rawContentLength)) { + this.failProtocol(handle, 'invalid Content-Length'); + return; + } + const contentLength = Number(rawContentLength); + if ( + !Number.isSafeInteger(contentLength) || + contentLength <= 0 || + contentLength > this.maxBodyBytes + ) { + this.failProtocol(handle, 'Content-Length exceeds body limit'); return; } - const contentLength = Number(match[1]); const bodyStart = headerEnd + 4; + if (bodyStart + contentLength > this.maxReceiveBufferBytes) { + this.failProtocol(handle, 'frame exceeds receive buffer limit'); + return; + } if (handle.buffer.length < bodyStart + contentLength) return; const body = handle.buffer.subarray(bodyStart, bodyStart + contentLength); - handle.buffer = handle.buffer.subarray(bodyStart + contentLength); + const remainingStart = bodyStart + contentLength; + handle.buffer = remainingStart === handle.buffer.length + ? Buffer.alloc(0) + : Buffer.from(handle.buffer.subarray(remainingStart)); try { this.handleMessage(handle, JSON.parse(body.toString('utf8')) as LSPMessage); } catch { @@ -310,13 +375,30 @@ export class LSPLayer { } } + private failProtocol(handle: ServerHandle, detail: string): void { + if ( + handle.state === 'failed' || + handle.state === 'stopping' || + handle.state === 'stopped' + ) return; + + const reason = `protocol overflow: ${detail}`; + handle.buffer = Buffer.alloc(0); + handle.terminationReason = reason; + handle.state = 'failed'; + this.failedCircuits.add(handle.key); + this.emitHandleLifecycle(handle, 'failed', { reason }); + this.rejectPending(handle, new Error(`LSP server ${handle.language} ${reason}`)); + void this.terminateHandle(handle, reason); + } + private handleMessage(handle: ServerHandle, message: LSPMessage): void { if (message.id === undefined) return; const pending = handle.pendingRequests.get(message.id); if (!pending) return; handle.pendingRequests.delete(message.id); - clearTimeout(pending.timeout); + this.clearHandleTimeout(handle, pending.timeout); if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result); } @@ -329,14 +411,14 @@ export class LSPLayer { ): Promise { return new Promise((resolve, reject) => { const id = ++this.messageId; - const timeout = setTimeout(() => { + const timeout = this.setHandleTimeout(handle, () => { handle.pendingRequests.delete(id); reject(new Error(`LSP request timeout: ${method}`)); }, timeoutMs); handle.pendingRequests.set(id, { resolve, reject, timeout }); if (!this.sendMessage(handle, { jsonrpc: '2.0', id, method, params })) { - clearTimeout(timeout); + this.clearHandleTimeout(handle, timeout); handle.pendingRequests.delete(id); reject(new Error(`LSP server ${handle.language} is not writable`)); } @@ -362,7 +444,7 @@ export class LSPLayer { private rejectPending(handle: ServerHandle, error: Error): void { for (const pending of handle.pendingRequests.values()) { - clearTimeout(pending.timeout); + this.clearHandleTimeout(handle, pending.timeout); pending.reject(error); } handle.pendingRequests.clear(); @@ -420,17 +502,37 @@ export class LSPLayer { private waitForClose(handle: ServerHandle, timeoutMs: number): Promise { if (handle.closed) return Promise.resolve(true); return new Promise((resolve) => { - const timeout = setTimeout(() => resolve(false), timeoutMs); + const timeout = this.setHandleTimeout(handle, () => resolve(false), timeoutMs); handle.closePromise.then(() => { - clearTimeout(timeout); + this.clearHandleTimeout(handle, timeout); resolve(true); }); }); } + private setHandleTimeout( + handle: ServerHandle, + callback: () => void, + timeoutMs: number + ): NodeJS.Timeout { + const timeout = setTimeout(() => { + handle.timers.delete(timeout); + callback(); + }, timeoutMs); + handle.timers.add(timeout); + return timeout; + } + + private clearHandleTimeout(handle: ServerHandle, timeout: NodeJS.Timeout): void { + clearTimeout(timeout); + handle.timers.delete(timeout); + } + private releaseHandle(handle: ServerHandle): void { if (this.handles.get(handle.key) === handle) this.handles.delete(handle.key); this.rejectPending(handle, new Error(`LSP server ${handle.language} released`)); + for (const timer of handle.timers) clearTimeout(timer); + handle.timers.clear(); handle.buffer = Buffer.alloc(0); handle.process.stdin?.removeAllListeners(); handle.process.stdout?.removeAllListeners(); From 39f90fc769ac4006644dc93f8911e26e7c834919 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:32:54 -0300 Subject: [PATCH 14/39] fix: enforce sanitized hook quota --- .../hooks/__tests__/hookReadiness.test.ts | 13 ++ .../hooks/__tests__/hookTracePolicy.test.ts | 70 +++++++++++ .../application/hooks/bashClassification.ts | 20 ++- .../application/hooks/hookTracePolicy.ts | 117 +++++++++++++++--- 4 files changed, 193 insertions(+), 27 deletions(-) diff --git a/src/harness/application/hooks/__tests__/hookReadiness.test.ts b/src/harness/application/hooks/__tests__/hookReadiness.test.ts index 4700d5b6..e492931b 100644 --- a/src/harness/application/hooks/__tests__/hookReadiness.test.ts +++ b/src/harness/application/hooks/__tests__/hookReadiness.test.ts @@ -6,6 +6,7 @@ import { WorkflowService } from '../../workflow'; import { buildHookReadinessSummary, buildHookTraceData, + DEFAULT_HOOK_TRACE_POLICY, consumeWorkflowMissingReminder, formatHookReadinessAdditionalContext, getHookReadinessSummary, @@ -186,5 +187,17 @@ describe('hook readiness runtime helpers', () => { .toMatchObject({ classification: 'inspection' }); expect(buildHookTraceData('Write', { file_path: 'README.md' })) .toMatchObject({ tool_input: { filePath: 'README.md' } }); + + const bounded = buildHookTraceData('Bash', { + command: `npm test ${'large-argument '.repeat(10_000)}`, + }, { + policy: { + ...DEFAULT_HOOK_TRACE_POLICY, + maxStringBytes: 4096, + maxSerializedTraceBytes: 1024, + }, + }); + expect(bounded).toMatchObject({ classification: 'test' }); + expect(Buffer.byteLength(JSON.stringify(bounded), 'utf8')).toBeLessThanOrEqual(1024); }); }); diff --git a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts index ea471baf..9bea8744 100644 --- a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -83,6 +83,76 @@ describe('hook trace policy', () => { expect(unknown.capture.truncatedFieldCount).toBe(1); }); + it('omits pathological unknown key names and enforces the hook quota before persistence', () => { + const secretInKey = `secret-key-material-${'private-key-fragment-'.repeat(20_000)}`; + const data = sanitizeHookTraceData('CustomTool', { + [secretInKey]: 'private-value-that-must-not-survive', + stable: true, + }); + const serialized = JSON.stringify(data); + + expect(Buffer.byteLength(serialized, 'utf8')).toBeLessThanOrEqual(DEFAULT_HOOK_TRACE_POLICY.maxSerializedTraceBytes); + expect(serialized).not.toContain('private-key-fragment'); + expect(serialized).not.toContain('private-value-that-must-not-survive'); + expect(serialized).not.toContain('secret-key-material'); + expect(data.tool_input).toMatchObject({ __redactedKey1: '[REDACTED]', stable: true }); + expect(data.capture).toMatchObject({ + persistedBytes: Buffer.byteLength(serialized, 'utf8'), + redactedFieldCount: 1, + quotaStatus: 'within_limit', + }); + }); + + it('collapses deep and wide unknown payloads to stable quota metadata', () => { + const policy = { + ...DEFAULT_HOOK_TRACE_POLICY, + maxStringBytes: 4096, + maxArrayItems: 100, + maxObjectDepth: 8, + maxSerializedTraceBytes: 1024, + }; + let deep: Record = { leaf: 'do-not-persist-'.repeat(500) }; + for (let depth = 0; depth < 20; depth += 1) deep = { nested: deep }; + const wide = Object.fromEntries(Array.from( + { length: 200 }, + (_, index) => [`field-${index}`, { deep, value: 'sensitive-body-'.repeat(500) }] + )); + + const first = sanitizeHookTraceData('UnknownTool', wide, policy); + const second = sanitizeHookTraceData('UnknownTool', wide, policy); + const serialized = JSON.stringify(first); + + expect(Buffer.byteLength(serialized, 'utf8')).toBeLessThanOrEqual(policy.maxSerializedTraceBytes); + expect(serialized).not.toContain('do-not-persist'); + expect(serialized).not.toContain('sensitive-body'); + expect(first.tool_input).toEqual({ + valuesOmitted: true, + inputKeyCount: 200, + quota: 'max_serialized_hook_trace_bytes', + }); + expect(first.capture).toEqual(second.capture); + expect(first.capture.persistedBytes).toBe(Buffer.byteLength(serialized, 'utf8')); + expect(first.capture.quotaStatus).toBe('truncated'); + expect(first.capture.truncatedFieldCount).toBeGreaterThan(0); + }); + + it.each(['Write', 'Edit', 'Bash'])('bounds allowlisted metadata for known %s tools', (toolName) => { + const marker = `must-not-survive-${'x'.repeat(100_000)}`; + const input = toolName === 'Write' + ? { file_path: marker, content: 'source body' } + : toolName === 'Edit' + ? { file_path: marker, old_string: 'old body', new_string: 'new body' } + : { command: marker }; + + const data = sanitizeHookTraceData(toolName, input); + const serialized = JSON.stringify(data); + + expect(Buffer.byteLength(serialized, 'utf8')).toBeLessThanOrEqual(DEFAULT_HOOK_TRACE_POLICY.maxSerializedTraceBytes); + expect(serialized).not.toContain('x'.repeat(1000)); + expect(data.capture.persistedBytes).toBe(Buffer.byteLength(serialized, 'utf8')); + expect(data.capture.truncatedFieldCount).toBeGreaterThan(0); + }); + it('falls back to defaults and clamps malformed or unsafe configuration', () => { expect(parseHookTracePolicy({ maxInputBytes: 'huge' }).maxInputBytes) .toBe(DEFAULT_HOOK_STDIN_MAX_BYTES); diff --git a/src/harness/application/hooks/bashClassification.ts b/src/harness/application/hooks/bashClassification.ts index 6391197e..a71f65f7 100644 --- a/src/harness/application/hooks/bashClassification.ts +++ b/src/harness/application/hooks/bashClassification.ts @@ -104,15 +104,13 @@ export function buildHookTraceData( options: { policy?: HookTracePolicy; repoPath?: string } = {} ): Record { const policy = options.policy ?? loadHookTracePolicy(options.repoPath); - const data: Record = sanitizeHookTraceData(toolName, toolInput, policy); - if (toolName?.trim().toLowerCase() !== 'bash') { - return data; - } - - const classification = classifyBashCommand(extractBashCommand(toolInput)); - if (classification) { - data.classification = classification; - } - - return data; + const classification = toolName?.trim().toLowerCase() === 'bash' + ? classifyBashCommand(extractBashCommand(toolInput)) + : undefined; + return sanitizeHookTraceData( + toolName, + toolInput, + policy, + classification ? { classification } : {} + ); } diff --git a/src/harness/application/hooks/hookTracePolicy.ts b/src/harness/application/hooks/hookTracePolicy.ts index ad603b1b..504b5d60 100644 --- a/src/harness/application/hooks/hookTracePolicy.ts +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -231,6 +231,54 @@ interface SanitizeState { truncatedFieldCount: number; } +interface SafeKeyName { + key: string; + keyBytes: number; + redacted: boolean; + truncated: boolean; +} + +function safeKeyName(key: string, index: number, policy: HookTracePolicy): SafeKeyName { + const keyBytes = Buffer.byteLength(key, 'utf8'); + if (SENSITIVE_KEY.test(key)) { + return { key: `__redactedKey${index + 1}`, keyBytes, redacted: true, truncated: false }; + } + if (keyBytes > policy.maxStringBytes) { + return { key: `__omittedKey${index + 1}`, keyBytes, redacted: false, truncated: true }; + } + return { key, keyBytes, redacted: false, truncated: false }; +} + +function uniqueSafeKey(result: Record, preferred: string, index: number): string { + if (!(preferred in result)) return preferred; + let suffix = index + 1; + while (`__field${suffix}` in result) suffix += 1; + return `__field${suffix}`; +} + +function summarizeKeyList( + value: Record, + policy: HookTracePolicy, + state: SanitizeState, + recordMetrics = true +): Array { + const keys = Object.keys(value); + const selected = keys.slice(0, policy.maxArrayItems); + if (selected.length < keys.length) state.truncatedFieldCount += 1; + return selected.map((key, index) => { + const safe = safeKeyName(key, index, policy); + if (safe.redacted) { + if (recordMetrics) state.redactedFieldCount += 1; + return '[REDACTED_KEY]'; + } + if (safe.truncated) { + if (recordMetrics) state.truncatedFieldCount += 1; + return { keyOmitted: true, keyBytes: safe.keyBytes }; + } + return safe.key; + }); +} + function summarizeUnknown( value: unknown, policy: HookTracePolicy, @@ -259,27 +307,44 @@ function summarizeUnknown( } if (depth >= policy.maxObjectDepth) { state.truncatedFieldCount += 1; - return { keys: Object.keys(value).slice(0, policy.maxArrayItems), valuesOmitted: true }; + return { keys: summarizeKeyList(value, policy, state), valuesOmitted: true }; } const result: Record = {}; const entries = Object.entries(value).slice(0, policy.maxArrayItems); if (entries.length < Object.keys(value).length) state.truncatedFieldCount += 1; - for (const [key, child] of entries) { - if (SENSITIVE_KEY.test(key)) { - result[key] = '[REDACTED]'; + for (const [index, [key, child]] of entries.entries()) { + const safe = safeKeyName(key, index, policy); + const outputKey = uniqueSafeKey(result, safe.key, index); + if (safe.redacted) { + result[outputKey] = '[REDACTED]'; state.redactedFieldCount += 1; + } else if (safe.truncated) { + result[outputKey] = { + keyOmitted: true, + keyBytes: safe.keyBytes, + value: summarizeUnknown(child, policy, state, depth + 1), + }; + state.truncatedFieldCount += 1; } else { - result[key] = summarizeUnknown(child, policy, state, depth + 1); + result[outputKey] = summarizeUnknown(child, policy, state, depth + 1); } } return result; } -function summarizeWrite(input: Record): Record { +function boundedMetadataString(value: string | undefined, policy: HookTracePolicy, state: SanitizeState): string | undefined { + if (value === undefined) return undefined; + const bounded = truncateUtf8(value, policy.maxStringBytes); + if (bounded.truncated) state.truncatedFieldCount += 1; + return bounded.truncated ? `${bounded.value}…[truncated]` : bounded.value; +} + +function summarizeWrite(input: Record, policy: HookTracePolicy, state: SanitizeState): Record { const content = typeof input.content === 'string' ? input.content : undefined; + const filePath = boundedMetadataString(firstString(input, PATH_KEYS), policy, state); return { - ...(firstString(input, PATH_KEYS) ? { filePath: firstString(input, PATH_KEYS) } : {}), + ...(filePath ? { filePath } : {}), ...(typeof input.byte_length === 'number' ? { declaredByteLength: input.byte_length } : {}), ...(content !== undefined ? { contentBytes: Buffer.byteLength(content, 'utf8'), @@ -289,15 +354,16 @@ function summarizeWrite(input: Record): Record }; } -function summarizeEdit(input: Record): Record { +function summarizeEdit(input: Record, policy: HookTracePolicy, state: SanitizeState): Record { const oldString = firstString(input, ['old_string', 'oldString']); const newString = firstString(input, ['new_string', 'newString']); const rangeKeys = ['start_line', 'end_line', 'startLine', 'endLine', 'line', 'column']; const range = Object.fromEntries(rangeKeys .filter((key) => typeof input[key] === 'number') .map((key) => [key, input[key]])); + const filePath = boundedMetadataString(firstString(input, PATH_KEYS), policy, state); return { - ...(firstString(input, PATH_KEYS) ? { filePath: firstString(input, PATH_KEYS) } : {}), + ...(filePath ? { filePath } : {}), ...(oldString !== undefined ? { oldStringBytes: Buffer.byteLength(oldString, 'utf8'), oldStringHash: hashText(oldString), @@ -319,8 +385,9 @@ function summarizeBash(input: Record, policy: HookTracePolicy, state.redactedFieldCount += redactedCommand.redacted; const preview = truncateUtf8(redactedCommand.value, policy.maxStringBytes); if (preview.truncated) state.truncatedFieldCount += 1; + const basename = boundedMetadataString(commandBasename(command), policy, state); return { - commandBasename: commandBasename(command), + ...(basename ? { commandBasename: basename } : {}), commandBytes: Buffer.byteLength(command, 'utf8'), commandPreview: preview.truncated ? `${preview.value}…[truncated]` : preview.value, }; @@ -329,7 +396,8 @@ function summarizeBash(input: Record, policy: HookTracePolicy, export function sanitizeHookTraceData( toolName: string | undefined, toolInput: unknown, - policy: HookTracePolicy = DEFAULT_HOOK_TRACE_POLICY + policy: HookTracePolicy = DEFAULT_HOOK_TRACE_POLICY, + additionalData: Record = {} ): SanitizedHookTraceData { const state: SanitizeState = { redactedFieldCount: 0, truncatedFieldCount: 0 }; const normalizedTool = toolName?.trim().toLowerCase(); @@ -337,10 +405,10 @@ export function sanitizeHookTraceData( let summary: Record; if (normalizedTool === 'write') { state.redactedFieldCount = countSensitiveFields(input, policy); - summary = summarizeWrite(input); + summary = summarizeWrite(input, policy, state); } else if (normalizedTool === 'edit') { state.redactedFieldCount = countSensitiveFields(input, policy); - summary = summarizeEdit(input); + summary = summarizeEdit(input, policy, state); } else if (normalizedTool === 'bash') { state.redactedFieldCount = countSensitiveFields(input, policy); summary = summarizeBash(input, policy, state); @@ -349,6 +417,7 @@ export function sanitizeHookTraceData( } const result: SanitizedHookTraceData = { + ...additionalData, tool_input: summary, capture: { inputBytes: byteLength(toolInput), @@ -358,7 +427,7 @@ export function sanitizeHookTraceData( quotaStatus: 'within_limit', }, }; - for (let iteration = 0; iteration < 4; iteration += 1) { + for (let iteration = 0; iteration < 8; iteration += 1) { const persistedBytes = byteLength(result); if (result.capture.persistedBytes === persistedBytes) break; result.capture.persistedBytes = persistedBytes; @@ -366,12 +435,28 @@ export function sanitizeHookTraceData( if (byteLength(result) > policy.maxSerializedTraceBytes) { result.tool_input = { - keys: Object.keys(input).slice(0, policy.maxArrayItems), + keys: summarizeKeyList(input, policy, state, false), + valuesOmitted: true, + }; + result.capture.redactedFieldCount = state.redactedFieldCount; + result.capture.truncatedFieldCount = state.truncatedFieldCount + 1; + result.capture.quotaStatus = 'truncated'; + for (let iteration = 0; iteration < 8; iteration += 1) { + const persistedBytes = byteLength(result); + if (result.capture.persistedBytes === persistedBytes) break; + result.capture.persistedBytes = persistedBytes; + } + } + + if (byteLength(result) > policy.maxSerializedTraceBytes) { + result.tool_input = { valuesOmitted: true, + inputKeyCount: Object.keys(input).length, + quota: 'max_serialized_hook_trace_bytes', }; result.capture.truncatedFieldCount += 1; result.capture.quotaStatus = 'truncated'; - for (let iteration = 0; iteration < 4; iteration += 1) { + for (let iteration = 0; iteration < 8; iteration += 1) { const persistedBytes = byteLength(result); if (result.capture.persistedBytes === persistedBytes) break; result.capture.persistedBytes = persistedBytes; From a082f8239e0d5a71637fb8220c4dd3826a7d48eb Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:33:07 -0300 Subject: [PATCH 15/39] fix: close runtime history memory gaps --- .../__tests__/runtimeStateService.test.ts | 27 ++++ .../out/runtimeState/runtimeStateService.ts | 120 ++++++++++++++---- .../contracts/taskContractsService.ts | 55 ++++++++ .../datasets/__tests__/datasetService.test.ts | 54 ++++++++ .../application/datasets/datasetService.ts | 86 ++++++++----- .../replay/__tests__/replayService.test.ts | 28 ++++ .../application/replay/replayService.ts | 23 ++-- 7 files changed, 331 insertions(+), 62 deletions(-) diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 308bb8c6..a081203f 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -3,6 +3,7 @@ import * as os from 'os'; import * as path from 'path'; import { HarnessRuntimeStateService, + MAX_STREAMED_TRACE_LINE_BYTES, } from '../runtimeStateService'; describe('HarnessRuntimeStateService', () => { @@ -202,6 +203,32 @@ describe('HarnessRuntimeStateService', () => { }); }); + it('discards oversized JSONL frames with bounded memory in both directions', async () => { + const session = await service.createSession({ name: 'oversized-lines' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const oldest = { + id: 'oldest', sessionId: session.id, level: 'info', event: 'valid', + message: 'oldest', createdAt: '2026-01-01T00:00:00.000Z', + }; + const newest = { + id: 'newest', sessionId: session.id, level: 'info', event: 'valid', + message: 'newest', createdAt: '2026-01-02T00:00:00.000Z', + }; + const oversized = `{"payload":"${'x'.repeat(MAX_STREAMED_TRACE_LINE_BYTES + 1)}"}`; + const contents = `${JSON.stringify(oldest)}\n${oversized}\n${JSON.stringify(newest)}\n`; + await fs.writeFile(traceFile, contents, 'utf8'); + + const forward = await service.listTracePage(session.id, { limit: 10, direction: 'oldest' }); + const reverse = await service.listTracePage(session.id, { limit: 10, direction: 'newest' }); + + expect(forward.items.map(item => item.id)).toEqual(['oldest', 'newest']); + expect(reverse.items.map(item => item.id)).toEqual(['newest', 'oldest']); + expect(forward.malformedCount).toBe(1); + expect(reverse.malformedCount).toBe(1); + expect(forward.scannedBytes).toBe(Buffer.byteLength(contents)); + expect(reverse.scannedBytes).toBe(Buffer.byteLength(contents)); + }); + it('maintains a latest sensor summary without scanning trace history', async () => { const session = await service.createSession({ name: 'sensor-summary' }); await service.appendTrace(session.id, { level: 'error', event: 'sensor.run', message: 'first', data: { run: { sensorId: 'tests', status: 'failed', createdAt: '2025-01-01' } } }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index fe4a27b8..9886df23 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -203,31 +203,65 @@ interface TraceLine { line: string; nextOffset: number; bytesRead: number; + oversized: boolean; } +const TRACE_READ_CHUNK_BYTES = 64 * 1024; +export const MAX_STREAMED_TRACE_LINE_BYTES = 1024 * 1024; + async function* readLinesForward(file: string, startOffset = 0): AsyncGenerator { const handle = await nodeFs.open(file, 'r'); - const chunk = Buffer.allocUnsafe(64 * 1024); + const chunk = Buffer.allocUnsafe(TRACE_READ_CHUNK_BYTES); let position = startOffset; let carry = Buffer.alloc(0); - let carryStart = startOffset; + let discardingOversized = false; + let unreportedBytes = 0; try { while (true) { const { bytesRead } = await handle.read(chunk, 0, chunk.length, position); if (bytesRead === 0) break; - const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, bytesRead)]) : Buffer.from(chunk.subarray(0, bytesRead)); - let lineStart = 0; - for (let index = 0; index < data.length; index += 1) { - if (data[index] !== 0x0a) continue; - const nextOffset = carryStart + index + 1; - yield { line: data.subarray(lineStart, index).toString('utf8').replace(/\r$/, ''), nextOffset, bytesRead }; - lineStart = index + 1; + unreportedBytes += bytesRead; + let segmentStart = 0; + for (let index = 0; index < bytesRead; index += 1) { + if (chunk[index] !== 0x0a) continue; + const segment = chunk.subarray(segmentStart, index); + const oversized = discardingOversized || carry.length + segment.length > MAX_STREAMED_TRACE_LINE_BYTES; + const line = oversized + ? '' + : (carry.length ? Buffer.concat([carry, segment]) : Buffer.from(segment)) + .toString('utf8') + .replace(/\r$/, ''); + yield { + line, + nextOffset: position + index + 1, + bytesRead: unreportedBytes, + oversized, + }; + unreportedBytes = 0; + carry = Buffer.alloc(0); + discardingOversized = false; + segmentStart = index + 1; + } + + const trailing = chunk.subarray(segmentStart, bytesRead); + if (!discardingOversized) { + if (carry.length + trailing.length > MAX_STREAMED_TRACE_LINE_BYTES) { + carry = Buffer.alloc(0); + discardingOversized = true; + } else if (trailing.length > 0) { + carry = carry.length ? Buffer.concat([carry, trailing]) : Buffer.from(trailing); + } } - carry = Buffer.from(data.subarray(lineStart)); - carryStart += lineStart; position += bytesRead; } - if (carry.length > 0) yield { line: carry.toString('utf8').replace(/\r$/, ''), nextOffset: position, bytesRead: 0 }; + if (discardingOversized || carry.length > 0) { + yield { + line: discardingOversized ? '' : carry.toString('utf8').replace(/\r$/, ''), + nextOffset: position, + bytesRead: unreportedBytes, + oversized: discardingOversized, + }; + } } finally { await handle.close(); } @@ -238,25 +272,66 @@ async function* readLinesReverse(file: string, startOffset?: number): AsyncGener const size = (await handle.stat()).size; let position = Math.min(startOffset ?? size, size); let carry = Buffer.alloc(0); + let discardingOversized = false; + let unreportedBytes = 0; try { while (position > 0) { - const length = Math.min(64 * 1024, position); + const length = Math.min(TRACE_READ_CHUNK_BYTES, position); position -= length; const chunk = Buffer.allocUnsafe(length); const { bytesRead } = await handle.read(chunk, 0, length, position); - const data = carry.length ? Buffer.concat([chunk.subarray(0, bytesRead), carry]) : Buffer.from(chunk.subarray(0, bytesRead)); + unreportedBytes += bytesRead; const newlines: number[] = []; - for (let index = 0; index < data.length; index += 1) if (data[index] === 0x0a) newlines.push(index); - if (newlines.length === 0) { carry = data; continue; } + for (let index = 0; index < bytesRead; index += 1) { + if (chunk[index] === 0x0a) newlines.push(index); + } + if (newlines.length === 0) { + if (!discardingOversized) { + if (bytesRead + carry.length > MAX_STREAMED_TRACE_LINE_BYTES) { + carry = Buffer.alloc(0); + discardingOversized = true; + } else { + carry = carry.length + ? Buffer.concat([chunk.subarray(0, bytesRead), carry]) + : Buffer.from(chunk.subarray(0, bytesRead)); + } + } + continue; + } + + let lineEnd = bytesRead; for (let index = newlines.length - 1; index >= 0; index -= 1) { const lineStart = newlines[index] + 1; - const lineEnd = index + 1 < newlines.length ? newlines[index + 1] : data.length; - const line = data.subarray(lineStart, lineEnd).toString('utf8').replace(/\r?\n$/, '').replace(/\r$/, ''); - if (line.length > 0) yield { line, nextOffset: position + lineStart, bytesRead: index === newlines.length - 1 ? bytesRead : 0 }; + const segment = chunk.subarray(lineStart, lineEnd); + const usesCarry = index === newlines.length - 1; + const oversized = usesCarry + ? discardingOversized || segment.length + carry.length > MAX_STREAMED_TRACE_LINE_BYTES + : segment.length > MAX_STREAMED_TRACE_LINE_BYTES; + const framed = oversized + ? Buffer.alloc(0) + : usesCarry && carry.length + ? Buffer.concat([segment, carry]) + : Buffer.from(segment); + yield { + line: oversized ? '' : framed.toString('utf8').replace(/\r$/, ''), + nextOffset: position + lineStart, + bytesRead: unreportedBytes, + oversized, + }; + unreportedBytes = 0; + lineEnd = newlines[index]; } - carry = Buffer.from(data.subarray(0, newlines[0])); + carry = Buffer.from(chunk.subarray(0, newlines[0])); + discardingOversized = false; + } + if (discardingOversized || carry.length > 0) { + yield { + line: discardingOversized ? '' : carry.toString('utf8').replace(/\r$/, ''), + nextOffset: 0, + bytesRead: unreportedBytes, + oversized: discardingOversized, + }; } - if (carry.length > 0) yield { line: carry.toString('utf8').replace(/\r$/, ''), nextOffset: 0, bytesRead: 0 }; } finally { await handle.close(); } @@ -700,7 +775,7 @@ export class HarnessRuntimeStateService { if (await fs.pathExists(active)) files.push(active); for (const file of files) { for await (const item of readLinesForward(file)) { - if (!item.line.trim()) continue; + if (item.oversized || !item.line.trim()) continue; try { yield JSON.parse(item.line) as HarnessTraceRecord; } catch { /* bounded malformed diagnostic in pages */ } } } @@ -740,6 +815,7 @@ export class HarnessRuntimeStateService { const iterator = direction === 'newest' ? readLinesReverse(file, initialOffset) : readLinesForward(file, initialOffset ?? 0); for await (const line of iterator) { scannedBytes += line.bytesRead; + if (line.oversized) { malformedCount += 1; continue; } if (!line.line.trim()) continue; let trace: HarnessTraceRecord; try { trace = JSON.parse(line.line) as HarnessTraceRecord; } catch { malformedCount += 1; continue; } diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index 4aec8c9d..2029e1c5 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -16,6 +16,7 @@ import type { HarnessRuntimeStatePort, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { HarnessSensorRun } from '../sensors/sensorsService'; +import { boundedLimit } from '../history/runtimeHistory'; /** * Structured artifact requirement. @@ -186,6 +187,11 @@ export interface HarnessHandoffContract { metadata?: Record; } +export interface BoundedSessionContracts { + items: T[]; + total: number; +} + export interface HarnessTaskCompletionResult { taskId: string; sessionId?: string; @@ -295,6 +301,17 @@ export class HarnessTaskContractsService { return contracts.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); } + async listSessionTaskContracts( + sessionId: string, + limit = 100 + ): Promise> { + return this.listBoundedSessionContracts( + this.tasksPath, + sessionId, + boundedLimit(limit, 100, 1000, 'session task contracts') + ); + } + async getTaskContract(taskId: string): Promise { const filePath = await this.taskFile(taskId); if (!(await fs.pathExists(filePath))) { @@ -370,6 +387,44 @@ export class HarnessTaskContractsService { return contracts.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); } + async listSessionHandoffContracts( + sessionId: string, + limit = 100 + ): Promise> { + return this.listBoundedSessionContracts( + this.handoffsPath, + sessionId, + boundedLimit(limit, 100, 1000, 'session handoff contracts') + ); + } + + private async listBoundedSessionContracts( + directoryPath: string, + sessionId: string, + limit: number + ): Promise> { + await this.ensureLayout(); + const selected: T[] = []; + let total = 0; + const directory = await fs.opendir(directoryPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const contract = await fs.readJson(path.join(directoryPath, entry.name)) as T; + if (contract.sessionId !== sessionId) continue; + total += 1; + selected.push(contract); + selected.sort((left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id) + ); + if (selected.length > limit) selected.pop(); + } catch { + // A malformed unrelated contract must not make replay unavailable. + } + } + return { items: selected, total }; + } + async evaluateTaskCompletion(taskId: string, sessionId?: string): Promise { const contract = await this.getTaskContract(taskId); if (!contract) { diff --git a/src/harness/application/datasets/__tests__/datasetService.test.ts b/src/harness/application/datasets/__tests__/datasetService.test.ts index 851d8fb2..2d06b2b4 100644 --- a/src/harness/application/datasets/__tests__/datasetService.test.ts +++ b/src/harness/application/datasets/__tests__/datasetService.test.ts @@ -93,4 +93,58 @@ describe('HarnessDatasetService', () => { expect(dataset.partial).toBe(true); expect(dataset.omittedFailureCount).toBe(4); }); + + it('processes one bounded session page before requesting the next page', async () => { + const sessions = ['one', 'two', 'three'].map((id) => ({ + id, + name: id, + status: 'failed', + repoPath: tempDir, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + startedAt: '2026-01-01T00:00:00.000Z', + traceCount: 0, + artifactCount: 0, + checkpointCount: 0, + checkpoints: [], + })); + const processed = new Set(); + const listSessionPage = jest.fn(async ({ cursor }: { cursor?: string }) => { + if (!cursor) { + return { items: sessions.slice(0, 2), nextCursor: 'page-2', hasMore: true }; + } + expect(processed).toEqual(new Set(['one', 'two'])); + return { items: sessions.slice(2), hasMore: false }; + }); + const buildReplay = jest.fn(async (sessionId: string) => { + processed.add(sessionId); + const session = sessions.find(item => item.id === sessionId)!; + return { + id: `replay-${sessionId}`, + sessionId, + session, + sensorRuns: [], + tasks: [], + traces: [], + } as any; + }); + const paged = new HarnessDatasetService({ + repoPath: tempDir, + dependencies: { + stateService: { listSessionPage } as any, + replayService: { buildReplay }, + taskContractsService: { evaluateTaskCompletion: jest.fn() }, + }, + }); + + const dataset = await paged.buildFailureDataset({ + includeSuccessfulSessions: true, + concurrency: 1, + }); + + expect(listSessionPage).toHaveBeenCalledTimes(2); + expect(buildReplay).toHaveBeenCalledTimes(3); + expect(dataset.sessionCount).toBe(3); + expect(dataset.replayCount).toBe(3); + }); }); diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index b989a4c3..5f3b32e1 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -3,7 +3,11 @@ import * as path from 'path'; import { randomUUID } from 'crypto'; import { resolveRuntimeLayoutFromRepo } from '../../../shared/fs/pathHelpers'; -import { HarnessRuntimeStateService, type HarnessRuntimeStatePort } from '../../adapters/out/runtimeState/runtimeStateService'; +import { + HarnessRuntimeStateService, + type HarnessRuntimeStatePort, + type HarnessSessionRecord, +} from '../../adapters/out/runtimeState/runtimeStateService'; import { HarnessReplayService, type HarnessReplayRecord } from '../replay/replayService'; import { HarnessSensorsService } from '../sensors/sensorsService'; import { HarnessTaskContractsService } from '../contracts/taskContractsService'; @@ -267,49 +271,71 @@ export class HarnessDatasetService { async buildFailureDataset(options: BuildHarnessDatasetOptions = {}): Promise { const concurrency = boundedLimit(options.concurrency, 1, 4, 'dataset concurrency'); const maxFailures = boundedLimit(options.maxFailures, 10_000, 10_000, 'dataset failures'); - const sessions = []; + const failures: HarnessFailureRecord[] = []; + let omittedFailureCount = 0; + let sessionCount = 0; + let replayCount = 0; + const retain = (records: HarnessFailureRecord[]) => { + const available = Math.max(0, maxFailures - failures.length); + failures.push(...records.slice(0, available)); + omittedFailureCount += Math.max(0, records.length - available); + }; + + const processSession = async (session: HarnessSessionRecord): Promise => { + if (!options.includeSuccessfulSessions && session.status === 'completed') return; + sessionCount += 1; + const replay = await this.replayService.buildReplay(session.id, { + includePayloads: false, + maxEvents: 1000, + }); + replayCount += 1; + retain(buildSensorFailures(replay)); + retain(await buildTaskFailures(replay, this.taskContractsService)); + retain(buildSessionFailure(replay)); + retain(buildTraceFailures(replay)); + }; + + const processBatch = async ( + batch: T[], + resolveSession: (item: T) => Promise + ): Promise => { + let nextIndex = 0; + const worker = async () => { + while (true) { + const index = nextIndex++; + if (index >= batch.length) return; + await processSession(await resolveSession(batch[index])); + } + }; + await Promise.all(Array.from( + { length: Math.min(concurrency, batch.length) }, + () => worker() + )); + }; + if (options.sessionIds?.length) { - for (const sessionId of options.sessionIds) sessions.push(await this.stateService.getSession(sessionId)); + for (let start = 0; start < options.sessionIds.length; start += 200) { + await processBatch( + options.sessionIds.slice(start, start + 200), + (sessionId) => this.stateService.getSession(sessionId) + ); + } } else { let cursor: string | undefined; do { const page = await this.stateService.listSessionPage({ limit: 200, cursor }); - sessions.push(...page.items); + await processBatch(page.items, async (session) => session); cursor = page.nextCursor; } while (cursor); } - const selectedSessions = options.includeSuccessfulSessions - ? sessions - : sessions.filter(session => session.status !== 'completed'); - - const failures: HarnessFailureRecord[] = []; - let omittedFailureCount = 0; - let nextIndex = 0; - const retain = (records: HarnessFailureRecord[]) => { - const available = Math.max(0, maxFailures - failures.length); - failures.push(...records.slice(0, available)); - omittedFailureCount += Math.max(0, records.length - available); - }; - const worker = async () => { - while (true) { - const index = nextIndex++; - if (index >= selectedSessions.length) return; - const replay = await this.replayService.buildReplay(selectedSessions[index].id, { includePayloads: false, maxEvents: 1000 }); - retain(buildSensorFailures(replay)); - retain(await buildTaskFailures(replay, this.taskContractsService)); - retain(buildSessionFailure(replay)); - retain(buildTraceFailures(replay)); - } - }; - await Promise.all(Array.from({ length: Math.min(concurrency, selectedSessions.length) }, () => worker())); const clusters = clusterFailures(failures); const dataset: HarnessFailureDataset = { id: randomUUID(), createdAt: nowIso(), repoPath: this.repoPath, - sessionCount: selectedSessions.length, - replayCount: selectedSessions.length, + sessionCount, + replayCount, failureCount: failures.length, clusterCount: clusters.length, failures, diff --git a/src/harness/application/replay/__tests__/replayService.test.ts b/src/harness/application/replay/__tests__/replayService.test.ts index 56921c8a..9433f644 100644 --- a/src/harness/application/replay/__tests__/replayService.test.ts +++ b/src/harness/application/replay/__tests__/replayService.test.ts @@ -3,6 +3,7 @@ import * as os from 'os'; import * as path from 'path'; import { HarnessExecutionService } from '../../execution/executionService'; +import { HarnessTaskContractsService } from '../../contracts/taskContractsService'; import { HarnessReplayService } from '../replayService'; describe('HarnessReplayService', () => { @@ -17,6 +18,7 @@ describe('HarnessReplayService', () => { }); afterEach(async () => { + jest.restoreAllMocks(); await fs.remove(tempDir); }); @@ -76,4 +78,30 @@ describe('HarnessReplayService', () => { expect((persisted[source] as unknown[]).length).toBeLessThanOrEqual(10); } }); + + it('reads bounded session-scoped contracts without global materialization', async () => { + const target = await execution.createSession({ name: 'bounded-contracts' }); + const other = await execution.createSession({ name: 'unrelated-contracts' }); + for (let index = 0; index < 5; index += 1) { + await execution.createTaskContract({ title: `target-${index}`, sessionId: target.id }); + await execution.createTaskContract({ title: `other-${index}`, sessionId: other.id }); + await execution.createHandoffContract({ from: 'a', to: `target-${index}`, sessionId: target.id }); + await execution.createHandoffContract({ from: 'a', to: `other-${index}`, sessionId: other.id }); + } + const listTasks = jest.spyOn(HarnessTaskContractsService.prototype, 'listTaskContracts'); + const listHandoffs = jest.spyOn(HarnessTaskContractsService.prototype, 'listHandoffContracts'); + const scopedTasks = jest.spyOn(HarnessTaskContractsService.prototype, 'listSessionTaskContracts'); + const scopedHandoffs = jest.spyOn(HarnessTaskContractsService.prototype, 'listSessionHandoffContracts'); + + const replay = await service.buildReplay(target.id, { maxEvents: 2 }); + + expect(listTasks).not.toHaveBeenCalled(); + expect(listHandoffs).not.toHaveBeenCalled(); + expect(scopedTasks).toHaveBeenCalledWith(target.id, 2); + expect(scopedHandoffs).toHaveBeenCalledWith(target.id, 2); + expect(replay.tasks).toHaveLength(2); + expect(replay.handoffs).toHaveLength(2); + expect(replay.sourceCounts.task).toBe(5); + expect(replay.sourceCounts.handoff).toBe(5); + }); }); diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index 75d2b239..3f427d39 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -88,7 +88,10 @@ export interface HarnessReplaySummary { export interface HarnessReplayDependencies { stateService: HarnessRuntimeStatePort; sensorsService: Pick; - contractsService: Pick; + contractsService: Pick< + HarnessTaskContractsService, + 'listSessionTaskContracts' | 'listSessionHandoffContracts' + >; } function nowIso(): string { @@ -156,20 +159,20 @@ export class HarnessReplayService { ): Promise { const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); const session = await this.stateService.getSession(sessionId); - const [tracePage, artifactPage, sensorRuns, tasks, handoffs] = await Promise.all([ + const [tracePage, artifactPage, allSensorRuns, taskScan, handoffScan] = await Promise.all([ this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest' }), this.stateService.listArtifactPage(sessionId, { limit: Math.min(maxEvents, 200), direction: 'oldest' }), this.sensorsService.getSessionSensorRuns(sessionId), - this.contractsService.listTaskContracts(), - this.contractsService.listHandoffContracts(), + this.contractsService.listSessionTaskContracts(sessionId, maxEvents), + this.contractsService.listSessionHandoffContracts(sessionId, maxEvents), ]); const traces = tracePage.items; const artifacts = artifactPage.items; const checkpoints = session.checkpoints.slice(0, maxEvents); - - const sessionTasks = tasks.filter((task) => task.sessionId === sessionId); - const sessionHandoffs = handoffs.filter((handoff) => handoff.sessionId === sessionId); + const sensorRuns = sortByCreatedAt(allSensorRuns).slice(0, maxEvents); + const sessionTasks = taskScan.items; + const sessionHandoffs = handoffScan.items; const events: HarnessReplayEvent[] = [ { @@ -278,9 +281,9 @@ export class HarnessReplayService { trace: session.traceCount, artifact: session.artifactCount, checkpoint: session.checkpointCount, - sensor: sensorRuns.length, - task: sessionTasks.length, - handoff: sessionHandoffs.length, + sensor: allSensorRuns.length, + task: taskScan.total, + handoff: handoffScan.total, }; const includedCounts = orderedEvents.reduce((counts, event) => { counts[event.source] += 1; From a50599435b8ac0f2d048c5e82890e45cba2d4bfd Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:41:18 -0300 Subject: [PATCH 16/39] perf: reuse semantic fingerprint discovery --- .../__tests__/semanticSnapshotService.test.ts | 104 ++++++- .../out/semantic/semanticSnapshotService.ts | 253 ++++++++++++++---- .../context/__tests__/contextTools.test.ts | 43 +++ .../application/context/analysisBundle.ts | 2 + .../application/context/contextTools.ts | 23 +- .../documentation/documentationGenerator.ts | 4 +- src/types.ts | 3 + src/utils/fileMapper.ts | 7 +- 8 files changed, 379 insertions(+), 60 deletions(-) diff --git a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts index 897b1bc8..ea174b2c 100644 --- a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts @@ -3,7 +3,11 @@ import * as os from 'os'; import * as path from 'path'; import { FileMapper } from '../../../../../utils/fileMapper'; -import { RepositoryChangingError, SemanticSnapshotService } from '../semanticSnapshotService'; +import { + RepositoryChangingError, + SemanticFingerprintCache, + SemanticSnapshotService, +} from '../semanticSnapshotService'; describe('SemanticSnapshotService', () => { let tempDir: string; @@ -120,6 +124,104 @@ describe('SemanticSnapshotService', () => { expect(repeated.cacheHits).toBe(repeated.files); }); + it('reuses bounded content hashes across short-lived service operations', async () => { + const cache = new SemanticFingerprintCache(100, 60_000); + const mapper = new FileMapper(); + const firstDiscovery = await mapper.mapRepository(repoPath); + const initial = await new SemanticSnapshotService(true, cache) + .captureRepoFingerprintWithMetrics(repoPath, firstDiscovery); + + const secondDiscovery = await mapper.mapRepository(repoPath); + const repeated = await new SemanticSnapshotService(true, cache) + .captureRepoFingerprintWithMetrics(repoPath, secondDiscovery); + + expect(initial.discoveries).toBe(0); + expect(initial.contentReads).toBe(initial.files); + expect(repeated.fingerprint).toBe(initial.fingerprint); + expect(repeated.discoveries).toBe(0); + expect(repeated.contentReads).toBe(0); + expect(repeated.bytesRead).toBe(0); + expect(repeated.cacheHits).toBe(repeated.files); + expect(cache.size).toBe(repeated.files); + }); + + it('produces the same fingerprint from shared discovery and fallback discovery', async () => { + const mapper = new FileMapper(); + const discovery = await mapper.mapRepository(repoPath); + const service = new SemanticSnapshotService(); + + const shared = await service.captureRepoFingerprintWithMetrics(repoPath, discovery); + const fallback = await service.captureRepoFingerprintWithMetrics(repoPath); + + expect(shared.discoveries).toBe(0); + expect(fallback.discoveries).toBe(1); + expect(fallback.fingerprint).toBe(shared.fingerprint); + }); + + it('keeps shared hashes correct for dirty, new, and deleted files', async () => { + const cache = new SemanticFingerprintCache(100, 60_000); + const mapper = new FileMapper(); + const capture = async () => new SemanticSnapshotService(true, cache) + .captureRepoFingerprintWithMetrics(repoPath, await mapper.mapRepository(repoPath)); + + const initial = await capture(); + const targetPath = path.join(repoPath, 'src', 'index.ts'); + const targetStats = await fs.stat(targetPath); + await new Promise((resolve) => setTimeout(resolve, 20)); + await fs.writeFile(targetPath, 'export const run = () => fals;\n', 'utf-8'); + await fs.utimes(targetPath, targetStats.atime, targetStats.mtime); + const dirty = await capture(); + expect(dirty.fingerprint).not.toBe(initial.fingerprint); + expect(dirty.contentReads).toBe(1); + + await fs.writeFile(path.join(repoPath, 'src', 'new.ts'), 'export const added = true;\n'); + const withNewFile = await capture(); + expect(withNewFile.fingerprint).not.toBe(dirty.fingerprint); + expect(withNewFile.contentReads).toBe(1); + + await fs.remove(path.join(repoPath, 'src', 'auth.ts')); + const withDeletedFile = await capture(); + expect(withDeletedFile.fingerprint).not.toBe(withNewFile.fingerprint); + expect(withDeletedFile.contentReads).toBe(0); + expect(withDeletedFile.cacheHits).toBe(withDeletedFile.files); + expect(cache.size).toBe(withDeletedFile.files); + }); + + it('does not use or populate an injected cache when caching is disabled', async () => { + const cache = new SemanticFingerprintCache(100, 60_000); + const mapper = new FileMapper(); + const discovery = await mapper.mapRepository(repoPath); + const first = await new SemanticSnapshotService(false, cache) + .captureRepoFingerprintWithMetrics(repoPath, discovery); + const repeated = await new SemanticSnapshotService(false, cache) + .captureRepoFingerprintWithMetrics(repoPath, discovery); + + expect(first.contentReads).toBe(first.files); + expect(repeated.contentReads).toBe(repeated.files); + expect(repeated.cacheHits).toBe(0); + expect(cache.size).toBe(0); + }); + + it('bounds shared cache entries, expires them, and supports explicit disposal', () => { + let now = 1_000; + const nowSpy = jest.spyOn(Date, 'now').mockImplementation(() => now); + const cache = new SemanticFingerprintCache(2, 10); + const cachePrefix = path.resolve(repoPath).toLowerCase(); + try { + cache.set(`${cachePrefix}\0a.ts`, 'm1', 'h1'); + cache.set(`${cachePrefix}\0b.ts`, 'm2', 'h2'); + cache.set(`${cachePrefix}\0c.ts`, 'm3', 'h3'); + expect(cache.size).toBe(2); + + now += 11; + expect(cache.get(`${cachePrefix}\0c.ts`, 'm3')).toBeUndefined(); + cache.dispose(repoPath); + expect(cache.size).toBe(0); + } finally { + nowSpy.mockRestore(); + } + }); + it('honors disabled fingerprint caching', async () => { const service = new SemanticSnapshotService(false); diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index e9a10523..81f49baf 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -1,4 +1,5 @@ import { createHash } from 'crypto'; +import { promises as nativeFs } from 'fs'; import * as fs from 'fs-extra'; import { glob } from 'glob'; import * as path from 'path'; @@ -99,6 +100,7 @@ const VERSIONS_DIRNAME = 'versions'; const MAX_REFRESH_ATTEMPTS = 2; const MAX_VERSION_HISTORY = 3; const MAX_FINGERPRINT_CACHE_ENTRIES = 10_000; +const DEFAULT_FINGERPRINT_CACHE_TTL_MS = 5 * 60_000; const SECTION_FILENAMES: Record = { stack: 'stack.json', @@ -170,11 +172,78 @@ interface FingerprintCacheEntry { lastUsedAt: number; } +/** + * Bounded metadata/content-hash cache that may be injected into short-lived + * snapshot services. It never stores file contents or semantic analyses. + */ +export class SemanticFingerprintCache { + private readonly entries = new Map(); + + constructor( + private readonly maxEntries = MAX_FINGERPRINT_CACHE_ENTRIES, + private readonly ttlMs = DEFAULT_FINGERPRINT_CACHE_TTL_MS + ) {} + + get(cacheKey: string, metadata: string): string | undefined { + const entry = this.entries.get(cacheKey); + if (!entry) return undefined; + const now = Date.now(); + if (now - entry.lastUsedAt > this.ttlMs) { + this.entries.delete(cacheKey); + return undefined; + } + if (entry.metadata !== metadata) return undefined; + entry.lastUsedAt = now; + return entry.contentHash; + } + + set(cacheKey: string, metadata: string, contentHash: string): void { + this.entries.set(cacheKey, { metadata, contentHash, lastUsedAt: Date.now() }); + this.prune(); + } + + reconcileRepo(repoPrefix: string, liveCacheKeys: Set): void { + for (const key of this.entries.keys()) { + if (key.startsWith(repoPrefix) && !liveCacheKeys.has(key)) this.entries.delete(key); + } + this.prune(); + } + + dispose(repoPath?: string): void { + if (!repoPath) { + this.entries.clear(); + return; + } + const prefix = `${path.resolve(repoPath).toLowerCase()}\0`; + for (const key of this.entries.keys()) { + if (key.startsWith(prefix)) this.entries.delete(key); + } + } + + get size(): number { + return this.entries.size; + } + + private prune(): void { + const now = Date.now(); + for (const [key, entry] of this.entries) { + if (now - entry.lastUsedAt > this.ttlMs) this.entries.delete(key); + } + if (this.entries.size <= this.maxEntries) return; + const stale = [...this.entries.entries()] + .sort((left, right) => left[1].lastUsedAt - right[1].lastUsedAt) + .slice(0, this.entries.size - this.maxEntries); + for (const [key] of stale) this.entries.delete(key); + } +} + export interface RepoFingerprintResult { fingerprint: string; files: number; bytesRead: number; + contentReads: number; cacheHits: number; + discoveries: number; durationMs: number; } @@ -192,16 +261,21 @@ export class RepositoryChangingError extends Error { export class SemanticSnapshotService { private static readonly inFlightRefreshes = new Map>(); - private readonly fingerprintCache = new Map(); - constructor(private readonly cacheEnabled = true) {} + constructor( + private readonly cacheEnabled = true, + private readonly fingerprintCache = new SemanticFingerprintCache() + ) {} - async captureRepoFingerprint(repoPath: string): Promise { - return (await this.computeRepoFingerprint(repoPath)).fingerprint; + async captureRepoFingerprint(repoPath: string, discovery?: RepoStructure): Promise { + return (await this.computeRepoFingerprint(repoPath, discovery)).fingerprint; } - async captureRepoFingerprintWithMetrics(repoPath: string): Promise { - return this.computeRepoFingerprint(repoPath); + async captureRepoFingerprintWithMetrics( + repoPath: string, + discovery?: RepoStructure + ): Promise { + return this.computeRepoFingerprint(repoPath, discovery); } async writeSnapshot( @@ -349,15 +423,15 @@ export class SemanticSnapshotService { const publishedSummaryPath = path.join(snapshotDir, SUMMARY_FILENAME); for (let attempt = 1; attempt <= MAX_REFRESH_ATTEMPTS; attempt += 1) { - const repoFingerprint = (await this.computeRepoFingerprint(repoPath)).fingerprint; const repoStructure = await fileMapper.mapRepository(repoPath); + const repoFingerprint = (await this.computeRepoFingerprint(repoPath, repoStructure)).fingerprint; const generationStartedAt = Date.now(); const artifacts = await this.buildSnapshotArtifacts(repoStructure, { outputDir, repoFingerprint, }); const generationMs = Date.now() - generationStartedAt; - const currentFingerprint = (await this.computeRepoFingerprint(repoPath)).fingerprint; + const currentFingerprint = (await this.computeRepoFingerprint(repoPath, repoStructure)).fingerprint; if (currentFingerprint !== repoFingerprint) { continue; @@ -768,62 +842,78 @@ export class SemanticSnapshotService { return expectedFingerprint === (await this.computeRepoFingerprint(repoPath)).fingerprint; } - private async computeRepoFingerprint(repoPath: string): Promise { + private async computeRepoFingerprint( + repoPath: string, + discovery?: RepoStructure + ): Promise { const startedAt = Date.now(); - const extensionPattern = `**/*.{${[...FINGERPRINT_CODE_EXTENSIONS] - .map((extension) => extension.slice(1)) - .join(',')}}`; - const files = await glob([ - extensionPattern, - '{src,lib,bin,app,packages,scripts}/**/*', - ...FINGERPRINT_ROOT_FILES, - '.github/workflows/**/*.{yml,yaml}', - ], { - cwd: repoPath, - nodir: true, - dot: true, - ignore: FINGERPRINT_IGNORE_PATTERNS, - }); - - const relevantFiles = files + const files = discovery + ? discovery.files.map((file) => file.relativePath) + : await this.discoverFingerprintFiles(repoPath); + const discoveries = discovery ? 0 : 1; + const relevantFiles = [...new Set(files.map((file) => file.split(path.sep).join('/')))] .filter((filePath) => this.isFingerprintRelevant(filePath)) .sort(); + const relevantDirectories = this.fingerprintDirectoriesForFiles(relevantFiles); const hash = createHash('sha256'); let bytesRead = 0; + let contentReads = 0; let cacheHits = 0; const liveCacheKeys = new Set(); + const repoPrefix = `${path.resolve(repoPath).toLowerCase()}\0`; for (const relativePath of relevantFiles) { const absolutePath = path.join(repoPath, relativePath); - const cacheKey = `${path.resolve(repoPath).toLowerCase()}\0${relativePath}`; + const cacheKey = `${repoPrefix}${relativePath}`; liveCacheKeys.add(cacheKey); try { - const stats = await fs.stat(absolutePath); - const metadata = `${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}`; + const stats = await nativeFs.stat(absolutePath, { bigint: true }); + const metadata = `${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`; let contentHash: string; - const cached = this.cacheEnabled ? this.fingerprintCache.get(cacheKey) : undefined; - if (cached?.metadata === metadata) { - contentHash = cached.contentHash; - cached.lastUsedAt = Date.now(); + const cachedHash = this.cacheEnabled + ? this.fingerprintCache.get(cacheKey, metadata) + : undefined; + if (cachedHash) { + contentHash = cachedHash; cacheHits += 1; } else { const content = await fs.readFile(absolutePath); bytesRead += content.byteLength; + contentReads += 1; contentHash = createHash('sha256').update(content).digest('hex'); if (this.cacheEnabled) { - this.fingerprintCache.set(cacheKey, { - metadata, - contentHash, - lastUsedAt: Date.now(), - }); + this.fingerprintCache.set(cacheKey, metadata, contentHash); } } - hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeMs}\0${contentHash}\n`); + hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeNs}\0${contentHash}\n`); } catch { hash.update(`${relativePath}:missing\n`); } } + // Directory metadata detects files created during stabilization without a + // second enumeration. A retry remaps the repository and includes them. + for (const relativePath of relevantDirectories) { + try { + const absoluteDirectory = relativePath === '.' + ? repoPath + : path.join(repoPath, relativePath); + const entriesHash = await this.hashRelevantDirectoryEntries(repoPath, relativePath); + if (relativePath === '.') { + // Root metadata also changes for ignored entries such as .context; + // its filtered entry signature is the stable relevant signal. + hash.update(`dir:.\0${entriesHash}\n`); + } else { + const stats = await nativeFs.stat(absoluteDirectory, { bigint: true }); + hash.update( + `dir:${relativePath}\0${stats.size}\0${stats.mtimeNs}\0${stats.ctimeNs}\0${entriesHash}\n` + ); + } + } catch { + hash.update(`dir:${relativePath}:missing\n`); + } + } + // Git index identity is an additional signal only; dirty files are still // represented by their independently hashed metadata/content above. try { @@ -834,33 +924,35 @@ export class SemanticSnapshotService { } if (this.cacheEnabled) { - for (const key of this.fingerprintCache.keys()) { - if (key.startsWith(`${path.resolve(repoPath).toLowerCase()}\0`) && !liveCacheKeys.has(key)) { - this.fingerprintCache.delete(key); - } - } - this.pruneFingerprintCache(); + this.fingerprintCache.reconcileRepo(repoPrefix, liveCacheKeys); } return { fingerprint: hash.digest('hex'), files: relevantFiles.length, bytesRead, + contentReads, cacheHits, + discoveries, durationMs: Date.now() - startedAt, }; } - private pruneFingerprintCache(): void { - if (this.fingerprintCache.size <= MAX_FINGERPRINT_CACHE_ENTRIES) { - return; - } - const stale = [...this.fingerprintCache.entries()] - .sort((left, right) => left[1].lastUsedAt - right[1].lastUsedAt) - .slice(0, this.fingerprintCache.size - MAX_FINGERPRINT_CACHE_ENTRIES); - for (const [key] of stale) { - this.fingerprintCache.delete(key); - } + private async discoverFingerprintFiles(repoPath: string): Promise { + const extensionPattern = `**/*.{${[...FINGERPRINT_CODE_EXTENSIONS] + .map((extension) => extension.slice(1)) + .join(',')}}`; + return glob([ + extensionPattern, + '{src,lib,bin,app,packages,scripts}/**/*', + ...FINGERPRINT_ROOT_FILES, + '.github/workflows/**/*.{yml,yaml}', + ], { + cwd: repoPath, + nodir: true, + dot: true, + ignore: FINGERPRINT_IGNORE_PATTERNS, + }); } private isFingerprintRelevant(relativePath: string): boolean { @@ -875,4 +967,57 @@ export class SemanticSnapshotService { return FINGERPRINT_CODE_EXTENSIONS.has(path.extname(relativePath).toLowerCase()); } + + private fingerprintDirectoriesForFiles(relevantFiles: string[]): string[] { + const directories = new Set(['.']); + for (const file of relevantFiles) { + let directory = path.posix.dirname(file); + while (directory !== '.') { + directories.add(directory); + directory = path.posix.dirname(directory); + } + } + return [...directories].sort(); + } + + private async hashRelevantDirectoryEntries( + repoPath: string, + relativeDirectory: string + ): Promise { + const absoluteDirectory = relativeDirectory === '.' + ? repoPath + : path.join(repoPath, relativeDirectory); + const aggregate = Buffer.alloc(32); + let count = 0; + const directory = await nativeFs.opendir(absoluteDirectory); + for await (const entry of directory) { + const relativePath = relativeDirectory === '.' + ? entry.name + : path.posix.join(relativeDirectory, entry.name); + if (!this.isFingerprintDirectoryEntryRelevant(relativePath, entry.isDirectory())) continue; + const entryHash = createHash('sha256') + .update(`${entry.isDirectory() ? 'd' : 'f'}:${entry.name}`) + .digest(); + for (let index = 0; index < aggregate.length; index += 1) { + aggregate[index] ^= entryHash[index]; + } + count += 1; + } + return `${count}:${aggregate.toString('hex')}`; + } + + private isFingerprintDirectoryEntryRelevant( + relativePath: string, + isDirectory: boolean + ): boolean { + const normalized = relativePath.split(path.sep).join('/'); + const segments = normalized.split('/'); + if (segments.some((segment) => [ + 'node_modules', '.git', 'dist', 'build', 'coverage', '.context', + 'vendor', '__pycache__', + ].includes(segment))) return false; + if (!isDirectory) return this.isFingerprintRelevant(normalized); + if (segments.length > 1) return true; + return ['src', 'lib', 'bin', 'app', 'packages', 'scripts', '.github'].includes(segments[0]); + } } diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index 00baa06a..73307d72 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -13,6 +13,7 @@ import { CodebaseAnalyzer } from '../../../adapters/out/semantic'; import { DocumentationGenerator } from '../scaffolding/generators/documentation/documentationGenerator'; import { AgentGenerator } from '../scaffolding/generators/agents/agentGenerator'; import { SemanticSnapshotService } from '../../../adapters/out/semantic'; +import { FileMapper } from '../../../../utils/fileMapper'; describe('contextTools sensors scaffolding', () => { let tempDir: string; @@ -75,6 +76,48 @@ describe('contextTools sensors scaffolding', () => { })); }); + it('performs one discovery per operation and reuses fingerprint reads across operations', async () => { + const repositoryDiscovery = jest.spyOn(FileMapper.prototype, 'mapRepository'); + const fingerprintDiscovery = jest.spyOn( + SemanticSnapshotService.prototype as any, + 'discoverFingerprintFiles' + ); + + const first = await initializeContextTool.execute!( + { + repoPath: tempDir, + type: 'both', + semantic: true, + generateQA: false, + generateSkills: false, + skipContentGeneration: true, + }, + toolExecutionContext + ) as Record; + const second = await initializeContextTool.execute!( + { + repoPath: tempDir, + type: 'both', + semantic: true, + generateQA: false, + generateSkills: false, + skipContentGeneration: true, + }, + toolExecutionContext + ) as Record; + + const firstFingerprint = first._metadata.analysis.metrics.fingerprint; + const secondFingerprint = second._metadata.analysis.metrics.fingerprint; + expect(repositoryDiscovery).toHaveBeenCalledTimes(2); + expect(fingerprintDiscovery).not.toHaveBeenCalled(); + expect(firstFingerprint.discoveries).toBe(0); + expect(firstFingerprint.contentReads).toBe(firstFingerprint.files); + expect(secondFingerprint.discoveries).toBe(0); + expect(secondFingerprint.contentReads).toBe(0); + expect(secondFingerprint.bytesRead).toBe(0); + expect(secondFingerprint.cacheHits).toBe(secondFingerprint.files); + }); + it('includes bootstrap sensors.json in pending writes and listToFill', async () => { const result = await initializeContextTool.execute!( { diff --git a/src/harness/application/context/analysisBundle.ts b/src/harness/application/context/analysisBundle.ts index 9b9d9876..f08d3ee4 100644 --- a/src/harness/application/context/analysisBundle.ts +++ b/src/harness/application/context/analysisBundle.ts @@ -20,7 +20,9 @@ export interface AnalysisMetrics extends SemanticAnalysisMetrics { fingerprint: { files: number; bytesRead: number; + contentReads: number; cacheHits: number; + discoveries: number; durationMs: number; }; } diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index accc012a..6fa5a3a8 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -10,6 +10,7 @@ import { getScaffoldStructure, serializeStructureForAI } from './scaffolding/gen import { DocumentationGenerator } from './scaffolding/generators/documentation/documentationGenerator'; import { CodebaseAnalyzer, + SemanticFingerprintCache, SemanticSnapshotService, type SemanticAnalysisBundle, } from '../../adapters/out/semantic'; @@ -34,6 +35,14 @@ import { createSkillRegistry } from '../../domain/workflow/skills'; import { ensureGitignorePatterns } from '../../../utils/gitignoreManager'; import type { AnalysisBundle } from './analysisBundle'; +// Context tools are long-lived while each operation remains short-lived. Only +// bounded fingerprint metadata/content hashes cross operation boundaries. +const contextFingerprintCache = new SemanticFingerprintCache(); + +function createContextSnapshotService(cacheEnabled = true): SemanticSnapshotService { + return new SemanticSnapshotService(cacheEnabled, contextFingerprintCache); +} + type ToolContext = unknown; interface InternalTool { @@ -653,14 +662,19 @@ export const initializeContextTool = createInternalTool< let analysisBundle: AnalysisBundle | undefined; let semanticFingerprint: string | undefined; let fingerprintMetrics: Awaited> | undefined; + const snapshotService = semantic + ? createContextSnapshotService(cacheEnabled) + : undefined; if (semantic) { const analyzer = new CodebaseAnalyzer({ exclude: [...new Set([...DEFAULT_EXCLUDE_PATTERNS, ...exclude])], cacheEnabled, }); try { - const snapshotService = new SemanticSnapshotService(cacheEnabled); - fingerprintMetrics = await snapshotService.captureRepoFingerprintWithMetrics(resolvedRepoPath); + fingerprintMetrics = await snapshotService!.captureRepoFingerprintWithMetrics( + resolvedRepoPath, + repoStructure + ); semanticFingerprint = fingerprintMetrics.fingerprint; semanticBundle = await analyzer.analyzeBundle( resolvedRepoPath, @@ -700,7 +714,9 @@ export const initializeContextTool = createInternalTool< fingerprint: { files: fingerprintMetrics.files, bytesRead: fingerprintMetrics.bytesRead, + contentReads: fingerprintMetrics.contentReads, cacheHits: fingerprintMetrics.cacheHits, + discoveries: fingerprintMetrics.discoveries, durationMs: fingerprintMetrics.durationMs, }, }, @@ -741,6 +757,7 @@ export const initializeContextTool = createInternalTool< repoFingerprint: semanticFingerprint, cacheEnabled, analysisBundle, + snapshotService, onSnapshotMetrics: (metrics) => { if (analysisBundle) { analysisBundle.metrics.durationsMs.generation = metrics.generationMs; @@ -1249,7 +1266,7 @@ export const getCodebaseMapTool = createInternalTool< const section = input.section || 'all'; try { - const snapshotService = new SemanticSnapshotService(); + const snapshotService = createContextSnapshotService(); const result = await snapshotService.ensureFreshSection(input.repoPath, section as any); return { success: true, diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index 16bc2d9a..c2df1c86 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -76,6 +76,8 @@ interface DocumentationGenerationConfig { }) => void; /** Preferred operation-scoped input from context init. */ analysisBundle?: AnalysisBundle; + /** Operation-owned service; avoids rebuilding fingerprint cache ownership. */ + snapshotService?: SemanticSnapshotService; } export class DocumentationGenerator { @@ -92,7 +94,7 @@ export class DocumentationGenerator { const docsDir = path.join(outputDir, 'docs'); await GeneratorUtils.ensureDirectoryAndLog(docsDir, verbose, 'Generating documentation scaffold in'); const snapshotService = (config.semantic || config.semanticContext) - ? new SemanticSnapshotService(config.cacheEnabled ?? true) + ? config.snapshotService ?? new SemanticSnapshotService(config.cacheEnabled ?? true) : null; // Perform semantic analysis if enabled diff --git a/src/types.ts b/src/types.ts index e0968847..200af4c4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -3,6 +3,9 @@ export interface FileInfo { relativePath: string; extension: string; size: number; + /** Filesystem metadata captured during bounded repository discovery. */ + mtimeMs?: number; + ctimeMs?: number; content?: string; type: 'file' | 'directory'; } diff --git a/src/utils/fileMapper.ts b/src/utils/fileMapper.ts index 8e6edd99..efea47af 100644 --- a/src/utils/fileMapper.ts +++ b/src/utils/fileMapper.ts @@ -10,8 +10,11 @@ export class FileMapper { '**/node_modules', '**/node_modules/**', '.git/**', + '.git', 'dist/**', 'build/**', + '.context/**', + '.context', '*.log', '.env*', '*.tmp', @@ -54,7 +57,7 @@ export class FileMapper { const files = await glob(pattern, { cwd: absolutePath, ignore: ignorePatterns, - dot: false, + dot: true, absolute: false }); allFiles.push(...files); @@ -81,6 +84,8 @@ export class FileMapper { relativePath, extension: path.extname(relativePath), size: stats.size, + mtimeMs: stats.mtimeMs, + ctimeMs: stats.ctimeMs, type: stats.isDirectory() ? 'directory' : 'file' }; From 2a457fff29eac63b087e55d9de9c162ecf35244f Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:44:02 -0300 Subject: [PATCH 17/39] fix: close MCP payload boundary gaps --- CHANGELOG.md | 1 + README.md | 2 + .../content/docs/en/reference/mcp-tools.md | 8 ++ .../content/docs/pt-br/reference/mcp-tools.md | 8 ++ .../__tests__/exploreActionService.test.ts | 33 ++++++ .../actions/exploreActionService.ts | 4 + .../application/context/contextTools.ts | 77 +++++++++++-- .../application/history/runtimeHistory.ts | 1 + src/mcp/README.md | 4 + src/mcp/gateway/explore.ts | 9 +- src/mcp/gateway/response.ts | 6 +- src/mcp/server/__tests__/mcpServer.test.ts | 34 +++++- .../server/__tests__/resourceResponse.test.ts | 75 ++++++++++++ src/mcp/server/mcpServer.ts | 108 +++++++++--------- src/mcp/server/resourceResponse.ts | 104 +++++++++++++++++ 15 files changed, 403 insertions(+), 71 deletions(-) create mode 100644 src/mcp/server/__tests__/resourceResponse.test.ts create mode 100644 src/mcp/server/resourceResponse.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3afefdaf..d44ca3ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses. +- Applied the same bounded UTF-8 budget to every MCP resource, rejected oversized files before reading their bodies, enforced action-specific list maxima, and paginated `explore` file listings. - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. diff --git a/README.md b/README.md index 6823f99d..bf83d68b 100644 --- a/README.md +++ b/README.md @@ -524,6 +524,8 @@ For AI-agent use, provide `repoPath` on the first context-heavy MCP call so dotc MCP JSON responses are compact and bounded to 1 MiB by default (4 MiB absolute). Growing `harness` lists return `page.nextCursor`; pass it back with a bounded `limit` to continue. If a selected page cannot fit, the tool returns `MCP_PAGE_TOO_LARGE` and a `suggestedLimit` instead of truncating JSON. The optional `_meta.dotcontext` envelope contains only bounded audit metrics, so existing clients can continue reading `content` unchanged. +The same UTF-8 budget covers MCP resources (`context://`, `file://`, and `workflow://`). Oversized file resources return `MCP_RESOURCE_TOO_LARGE` before the file body is read. `explore` action `list` returns bounded pages (100 files by default, 1,000 maximum); continue with its opaque `page.nextCursor`. + ## CLI Reference ### Requirements diff --git a/docs/src/content/docs/en/reference/mcp-tools.md b/docs/src/content/docs/en/reference/mcp-tools.md index df9ba286..91a7f335 100644 --- a/docs/src/content/docs/en/reference/mcp-tools.md +++ b/docs/src/content/docs/en/reference/mcp-tools.md @@ -55,9 +55,13 @@ File and code exploration — read files, list paths, search content, and extrac | `encoding` | enum: `utf-8` \| `ascii` \| `binary` | read | File encoding | | `symbolTypes` | array | analyze | Extract `class` \| `interface` \| `function` \| `type` \| `enum` | | `ignore` | array | list, search, getStructure | Patterns to exclude | +| `limit` | integer, 1–1,000 | list | Files per page; defaults to 100 | +| `cursor` | string | list | Opaque continuation cursor from `page.nextCursor` | **Returns:** file contents, matched files, symbol analysis, search results, or a directory tree. +The `list` action streams matches into bounded pages instead of materializing the entire glob. Pass the returned `page.nextCursor` unchanged to continue. + ### context Context scaffolding and semantic context — the entry point for creating and filling `.context/`. @@ -225,6 +229,8 @@ Explicit harness runtime operations — sessions, traces, artifacts, checkpoints `listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays`, and `listDatasets` are bounded. Continue a partial result by sending the returned `page.nextCursor` unchanged in the next call. Cursors are bound to their query and become invalid when their underlying trace segments rotate. +Action-specific maximums are enforced at the MCP boundary: 200 for sessions and artifacts, 100 for replays and datasets, and 1,000 for traces, tasks, and handoffs. + MCP JSON text is compact-serialized once and has a 1 MiB default budget (4 MiB absolute maximum). A page that does not fit returns the typed `MCP_PAGE_TOO_LARGE` error with `suggestedLimit`; JSON is never cut at an arbitrary byte. Tool results also include a content-free `_meta.dotcontext` audit envelope with response size and page metrics. Clients may ignore `_meta` and continue reading `content`. **Returns:** session timelines, artifact inventories, task evaluations, sensor telemetry, replay records, failure clusters, or policy enforcement results. @@ -329,6 +335,8 @@ In addition to tools, the server exposes read-only resources your client can fet | `file://{path}` | `text/plain` | Reads file contents; paths are validated against the workspace boundary. | | `workflow://status` | `application/json` | Current PREVC workflow status — phases, roles, and a progress snapshot. | +All resource text shares the MCP UTF-8 response budget: 1 MiB by default and 4 MiB at most. An oversized `file://` resource returns the typed `MCP_RESOURCE_TOO_LARGE` response before its body is read. Resource text is never arbitrarily truncated. + ## Recommended call flows **Standard initialization:** diff --git a/docs/src/content/docs/pt-br/reference/mcp-tools.md b/docs/src/content/docs/pt-br/reference/mcp-tools.md index 57c3b9e0..856f89f2 100644 --- a/docs/src/content/docs/pt-br/reference/mcp-tools.md +++ b/docs/src/content/docs/pt-br/reference/mcp-tools.md @@ -55,9 +55,13 @@ Exploração de arquivos e código — ler arquivos, listar caminhos, buscar con | `encoding` | enum: `utf-8` \| `ascii` \| `binary` | read | Codificação do arquivo | | `symbolTypes` | array | analyze | Extrai `class` \| `interface` \| `function` \| `type` \| `enum` | | `ignore` | array | list, search, getStructure | Padrões a excluir | +| `limit` | inteiro, 1–1.000 | list | Arquivos por página; padrão 100 | +| `cursor` | string | list | Cursor opaco de continuação retornado em `page.nextCursor` | **Retorna:** conteúdo de arquivos, arquivos correspondentes, análise de símbolos, resultados de busca ou uma árvore de diretórios. +A action `list` transmite os matches em páginas limitadas, sem materializar todo o glob. Envie o `page.nextCursor` retornado, sem alterá-lo, para continuar. + ### context Scaffolding de contexto e contexto semântico — o ponto de entrada para criar e preencher o `.context/`. @@ -225,6 +229,8 @@ Operações explícitas do runtime do harness — sessions, traces, artefatos, c `listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays` e `listDatasets` são limitadas. Para continuar um resultado parcial, envie o `page.nextCursor` retornado, sem alterá-lo, na próxima chamada. Os cursors são vinculados à query e ficam inválidos quando os segmentos de trace subjacentes rotacionam. +Os máximos específicos por action são validados na fronteira MCP: 200 para sessions e artifacts, 100 para replays e datasets e 1.000 para traces, tasks e handoffs. + O texto JSON MCP é serializado uma vez em formato compacto e tem orçamento padrão de 1 MiB (máximo absoluto de 4 MiB). Uma página que não cabe retorna o erro tipado `MCP_PAGE_TOO_LARGE` com `suggestedLimit`; o JSON nunca é cortado em um byte arbitrário. Os resultados também incluem um envelope de auditoria `_meta.dotcontext`, sem conteúdo do usuário, com tamanho da resposta e métricas de paginação. Clientes podem ignorar `_meta` e continuar lendo `content`. **Retorna:** linhas do tempo de session, inventários de artefatos, avaliações de tasks, telemetria de sensors, registros de replay, clusters de falhas ou resultados de aplicação de policy. @@ -329,6 +335,8 @@ Além das tools, o servidor expõe recursos somente leitura que seu cliente pode | `file://{path}` | `text/plain` | Lê o conteúdo de arquivos; os caminhos são validados contra o limite do workspace. | | `workflow://status` | `application/json` | Status atual do workflow PREVC — fases, papéis e um snapshot de progresso. | +Todo texto de recurso compartilha o orçamento UTF-8 de resposta MCP: 1 MiB por padrão e no máximo 4 MiB. Um recurso `file://` grande demais retorna a resposta tipada `MCP_RESOURCE_TOO_LARGE` antes da leitura do corpo. O texto nunca é truncado em um byte arbitrário. + ## Fluxos de chamada recomendados **Inicialização padrão:** diff --git a/src/harness/application/actions/__tests__/exploreActionService.test.ts b/src/harness/application/actions/__tests__/exploreActionService.test.ts index de987d83..82effa65 100644 --- a/src/harness/application/actions/__tests__/exploreActionService.test.ts +++ b/src/harness/application/actions/__tests__/exploreActionService.test.ts @@ -38,4 +38,37 @@ describe('HarnessExploreActionService', () => { expect(result.success).toBe(true); expect(result.files).toEqual(['src/example.ts']); }); + + it('returns bounded file pages with opaque continuation cursors', async () => { + for (let index = 0; index < 205; index += 1) { + await fs.outputFile( + path.join(tempDir, 'many', `file-${index.toString().padStart(3, '0')}.ts`), + 'export {};\n' + ); + } + + const first = await service.execute({ action: 'list', pattern: 'many/*.ts', limit: 100 }); + const second = await service.execute({ + action: 'list', + pattern: 'many/*.ts', + limit: 100, + cursor: (first.page as any).nextCursor, + }); + const third = await service.execute({ + action: 'list', + pattern: 'many/*.ts', + limit: 100, + cursor: (second.page as any).nextCursor, + }); + const files = [ + ...(first.files as string[]), + ...(second.files as string[]), + ...(third.files as string[]), + ]; + + expect(first.page).toMatchObject({ recordsReturned: 100, hasMore: true, partial: true }); + expect(second.page).toMatchObject({ recordsReturned: 100, hasMore: true, partial: true }); + expect(third.page).toMatchObject({ recordsReturned: 5, hasMore: false, partial: false }); + expect(new Set(files).size).toBe(205); + }); }); diff --git a/src/harness/application/actions/exploreActionService.ts b/src/harness/application/actions/exploreActionService.ts index 7f9e5cd1..ca3e8a93 100644 --- a/src/harness/application/actions/exploreActionService.ts +++ b/src/harness/application/actions/exploreActionService.ts @@ -15,6 +15,8 @@ export interface HarnessExploreActionInput { cwd?: string; encoding?: 'utf-8' | 'ascii' | 'binary'; ignore?: string[]; + limit?: number; + cursor?: string; symbolTypes?: Array<'class' | 'interface' | 'function' | 'type' | 'enum'>; fileGlob?: string; maxResults?: number; @@ -44,6 +46,8 @@ export class HarnessExploreActionService { pattern: params.pattern!, cwd: params.cwd || this.options.repoPath, ignore: params.ignore, + limit: params.limit, + cursor: params.cursor, }); case 'analyze': return analyzeSymbolsTool.execute({ diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 26e946ef..f125f084 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -1,5 +1,5 @@ import * as fs from 'fs-extra'; -import { glob } from 'glob'; +import { glob, globIterate } from 'glob'; import * as path from 'path'; import { TreeSitterLayer } from '../../adapters/out/semantic/treeSitter/treeSitterLayer'; import { SemanticContextBuilder } from '../../adapters/out/semantic/contextBuilder'; @@ -28,6 +28,14 @@ import { getUntrackedContextLayoutEntries } from '../../../shared'; import { resolveRuntimeLayout } from '../../../shared/fs/pathHelpers'; import { createSkillRegistry } from '../../domain/workflow/skills'; import { ensureGitignorePatterns } from '../../../utils/gitignoreManager'; +import { + boundedLimit, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + RUNTIME_HISTORY_LIMITS, + type RuntimeHistoryPage, +} from '../history/runtimeHistory'; type ToolContext = unknown; @@ -341,23 +349,74 @@ export const readFileTool = createInternalTool< ); export const listFilesTool = createInternalTool< - { pattern: string; cwd?: string; ignore?: string[] }, - { success: boolean; files?: string[]; count?: number; pattern: string; error?: string } + { pattern: string; cwd?: string; ignore?: string[]; limit?: number; cursor?: string }, + { + success: boolean; + files?: string[]; + count?: number; + pattern: string; + page?: Omit, 'items'>; + error?: string; + } >( 'List files matching a glob pattern in the repository', async (input) => { const { pattern, cwd, ignore } = input; try { - const files = (await glob(pattern, { - cwd: cwd || process.cwd(), - ignore: ignore || ['node_modules/**', '.git/**', 'dist/**'], - absolute: false - })).map((file) => file.split(path.sep).join('/')); + const resolvedCwd = path.resolve(cwd || process.cwd()); + const resolvedIgnore = ignore || ['node_modules/**', '.git/**', 'dist/**']; + const limit = boundedLimit( + input.limit, + RUNTIME_HISTORY_LIMITS.exploreFiles.default, + RUNTIME_HISTORY_LIMITS.exploreFiles.maximum, + 'explore files' + ); + const binding = queryBinding({ pattern, cwd: resolvedCwd, ignore: resolvedIgnore }); + const boundary = decodeHistoryCursor<{ offset: number }>( + input.cursor, + 'explore-files', + binding + ); + const offset = boundary?.offset ?? 0; + const files: string[] = []; + let matched = 0; + let recordsScanned = 0; + let hasMore = false; + const startedAt = Date.now(); + for await (const file of globIterate(pattern, { + cwd: resolvedCwd, + ignore: resolvedIgnore, + absolute: false, + nodir: true, + })) { + recordsScanned += 1; + if (matched < offset) { + matched += 1; + continue; + } + if (files.length === limit) { + hasMore = true; + break; + } + files.push(file.split(path.sep).join('/')); + matched += 1; + } return { success: true, files, count: files.length, - pattern + pattern, + page: { + nextCursor: hasMore + ? encodeHistoryCursor('explore-files', binding, { offset: offset + files.length }) + : undefined, + hasMore, + recordsReturned: files.length, + recordsScanned, + cursorVersion: 1, + partial: hasMore, + durationMs: Date.now() - startedAt, + }, }; } catch (error) { return { diff --git a/src/harness/application/history/runtimeHistory.ts b/src/harness/application/history/runtimeHistory.ts index 29cf93be..fe480873 100644 --- a/src/harness/application/history/runtimeHistory.ts +++ b/src/harness/application/history/runtimeHistory.ts @@ -11,6 +11,7 @@ export const RUNTIME_HISTORY_LIMITS = { handoffs: { default: 100, maximum: 1000 }, replays: { default: 25, maximum: 100 }, datasets: { default: 25, maximum: 100 }, + exploreFiles: { default: 100, maximum: 1000 }, replayEvents: { default: 100, maximum: 1000 }, } as const; diff --git a/src/mcp/README.md b/src/mcp/README.md index 78b6e47c..ead73f22 100644 --- a/src/mcp/README.md +++ b/src/mcp/README.md @@ -32,8 +32,12 @@ The MCP tools follow a simple, explicit pattern: Machine JSON is compact-serialized once and limited to 1 MiB by default (4 MiB absolute maximum). Every tool response includes a content-free `_meta.dotcontext` audit summary with response bytes, serialization time, item count, and partial-page state. Clients that ignore `_meta` continue to read the same JSON text from `content`. +The same UTF-8 budget applies to `context://`, `file://`, and `workflow://` resources. Oversized files are rejected from metadata, before their body is read, with the typed `MCP_RESOURCE_TOO_LARGE` response; resource text is never arbitrarily truncated. + The growing harness lists (`listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays`, and `listDatasets`) return bounded pages. Pass `limit` and the opaque `cursor` returned as `page.nextCursor` to continue; do not inspect or modify cursors. `replaySession.maxEvents` defaults to 100 and cannot exceed 1,000. An oversized page returns `MCP_PAGE_TOO_LARGE` with `suggestedLimit`, never truncated JSON. +`explore` action `list` is also paginated: it defaults to 100 files, accepts at most 1,000, and returns an opaque `page.nextCursor` when more matches exist. + ### Dedicated Workflow Tools (5) | Tool | Description | diff --git a/src/mcp/gateway/explore.ts b/src/mcp/gateway/explore.ts index 9350b20c..b8219e8e 100644 --- a/src/mcp/gateway/explore.ts +++ b/src/mcp/gateway/explore.ts @@ -1,4 +1,4 @@ -import { HarnessExploreActionService } from '../../harness'; +import { HarnessExploreActionService, RUNTIME_HISTORY_LIMITS } from '../../harness'; import type { ExploreParams } from './types'; import type { MCPToolResponse } from './response'; @@ -18,7 +18,12 @@ export async function handleExplore( const service = new HarnessExploreActionService({ repoPath: options.repoPath }); try { - return createJsonResponse(await service.execute(params)); + return createJsonResponse(await service.execute(params), { + requestedLimit: params.limit, + appliedLimit: params.action === 'list' + ? params.limit ?? RUNTIME_HISTORY_LIMITS.exploreFiles.default + : undefined, + }); } catch (error) { return createErrorResponse(error); } diff --git a/src/mcp/gateway/response.ts b/src/mcp/gateway/response.ts index 3b4dfb21..a17edb7f 100644 --- a/src/mcp/gateway/response.ts +++ b/src/mcp/gateway/response.ts @@ -62,7 +62,7 @@ function asRecord(value: unknown): Record | undefined { : undefined; } -function boundedPayloadBudget(requested?: number): number { +export function resolveMcpPayloadBudget(requested?: number): number { const configured = requested ?? Number(process.env.DOTCONTEXT_MCP_PAYLOAD_BYTES); if (!Number.isFinite(configured) || configured <= 0) { return DEFAULT_MCP_TEXT_PAYLOAD_BYTES; @@ -152,7 +152,7 @@ function jsonEnvelope( const text = JSON.stringify(value); const serializationMs = Math.max(0, performance.now() - started); const responseBytes = Buffer.byteLength(text, 'utf8'); - const budgetBytes = boundedPayloadBudget(options.payloadBudgetBytes); + const budgetBytes = resolveMcpPayloadBudget(options.payloadBudgetBytes); if (!forceError && responseBytes > budgetBytes) { const reference = artifactReference(asRecord(value)); @@ -216,7 +216,7 @@ export function createErrorResponse(error: unknown): MCPToolResponse { /** Creates a bounded plain text response. */ export function createTextResponse(text: string): MCPToolResponse { const responseBytes = Buffer.byteLength(text, 'utf8'); - const budgetBytes = boundedPayloadBudget(); + const budgetBytes = resolveMcpPayloadBudget(); if (responseBytes > budgetBytes) { return jsonEnvelope({ success: false, diff --git a/src/mcp/server/__tests__/mcpServer.test.ts b/src/mcp/server/__tests__/mcpServer.test.ts index adabafb7..f0cd1e42 100644 --- a/src/mcp/server/__tests__/mcpServer.test.ts +++ b/src/mcp/server/__tests__/mcpServer.test.ts @@ -1,7 +1,12 @@ import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs-extra'; -import { AIContextMCPServer, MCP_LIST_LIMIT_SCHEMA, MCP_MAX_EVENTS_SCHEMA } from '../mcpServer'; +import { + AIContextMCPServer, + MCP_HARNESS_ACTION_LIMIT_SCHEMA, + MCP_LIST_LIMIT_SCHEMA, + MCP_MAX_EVENTS_SCHEMA, +} from '../mcpServer'; // We can't fully test the MCP server without a transport, // but we can test instantiation and configuration @@ -61,6 +66,33 @@ describe('AIContextMCPServer', () => { ])('validates maxEvents boundary %s', (value, success) => { expect(MCP_MAX_EVENTS_SCHEMA.safeParse(value).success).toBe(success); }); + + it.each([ + ['listSessions', 200], + ['listTraces', 1000], + ['listArtifacts', 200], + ['listTasks', 1000], + ['listHandoffs', 1000], + ['listReplays', 100], + ['listDatasets', 100], + ])('enforces the %s action-specific maximum', (action, maximum) => { + expect(MCP_HARNESS_ACTION_LIMIT_SCHEMA.safeParse({ action, limit: maximum }).success) + .toBe(true); + expect(MCP_HARNESS_ACTION_LIMIT_SCHEMA.safeParse({ action, limit: maximum + 1 }).success) + .toBe(false); + }); + + it('rejects an action-specific limit before invoking the harness handler', async () => { + const server = new AIContextMCPServer({ repoPath: tempDir }); + const handler = jest.fn(); + const wrapped = (server as any).wrapWithActionLogging('harness', handler); + + const response = await wrapped({ action: 'listSessions', limit: 201 }); + + expect(handler).not.toHaveBeenCalled(); + expect(response.isError).toBe(true); + expect(JSON.parse(response.content[0].text)).toMatchObject({ success: false }); + }); }); it('logs response metadata without parsing response content', async () => { diff --git a/src/mcp/server/__tests__/resourceResponse.test.ts b/src/mcp/server/__tests__/resourceResponse.test.ts new file mode 100644 index 00000000..b9f589f0 --- /dev/null +++ b/src/mcp/server/__tests__/resourceResponse.test.ts @@ -0,0 +1,75 @@ +import * as fs from 'fs-extra'; +import { promises as nodeFs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { + createBoundedResourceJson, + createBoundedResourceText, + readBoundedFileResource, +} from '../resourceResponse'; + +describe('bounded MCP resources', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mcp-resource-')); + }); + + afterEach(async () => { + jest.restoreAllMocks(); + await fs.remove(tempDir); + }); + + it('returns resource text at the UTF-8 budget and rejects budget + 1', () => { + const at = createBoundedResourceText('context://codebase/compact', 'text/plain', 'é'.repeat(64), { + payloadBudgetBytes: 128, + }); + const above = createBoundedResourceText('context://codebase/compact', 'text/plain', `${'é'.repeat(64)}x`, { + payloadBudgetBytes: 128, + }); + + expect(at.contents[0].text).toBe('é'.repeat(64)); + expect(JSON.parse(above.contents[0].text)).toMatchObject({ + success: false, + errorCode: 'MCP_RESOURCE_TOO_LARGE', + resourceBytes: 129, + budgetBytes: 128, + }); + }); + + it('serializes JSON resources compactly through the same budget', () => { + const response = createBoundedResourceJson('workflow://status', { + name: 'workflow', + phases: ['P', 'R', 'E', 'V', 'C'], + }); + expect(response.contents[0].mimeType).toBe('application/json'); + expect(response.contents[0].text).not.toContain('\n'); + }); + + it('rejects a large file from stat without opening or materializing it', async () => { + const file = path.join(tempDir, 'large.txt'); + await fs.writeFile(file, 'secret-marker-'.repeat(10_000)); + const open = jest.spyOn(nodeFs, 'open'); + + const response = await readBoundedFileResource('file://large.txt', file, 'text/plain', { + payloadBudgetBytes: 1024, + }); + + expect(open).not.toHaveBeenCalled(); + expect(response.contents[0].text).not.toContain('secret-marker'); + expect(JSON.parse(response.contents[0].text)).toMatchObject({ + errorCode: 'MCP_RESOURCE_TOO_LARGE', + budgetBytes: 1024, + }); + }); + + it('reads at most budget + 1 bytes when the file fits the initial stat', async () => { + const file = path.join(tempDir, 'exact.txt'); + await fs.writeFile(file, 'x'.repeat(1024)); + const response = await readBoundedFileResource('file://exact.txt', file, 'text/plain', { + payloadBudgetBytes: 1024, + }); + expect(response.contents[0].text).toHaveLength(1024); + }); +}); diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index f5440d01..b4150381 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -13,13 +13,17 @@ import { z } from 'zod'; import * as path from 'path'; import * as fs from 'fs-extra'; -import { readFileTool } from '../../harness/application/context/contextTools'; import { PathValidator, SecurityError } from '../../utils/pathSecurity'; import { SemanticContextBuilder, type ContextFormat } from '../../harness/adapters/out/semantic/contextBuilder'; import { ContextCache } from '../../harness/adapters/out/semantic/contextCache'; import { VERSION } from '../../version'; import { WorkflowService } from '../../harness/application/workflow'; import { logMcpAction } from '../logging/actionLogger'; +import { + createBoundedResourceJson, + createBoundedResourceText, + readBoundedFileResource, +} from './resourceResponse'; import { PREVC_ROLES, getScaleName, @@ -71,6 +75,28 @@ export interface MCPServerOptions { export const MCP_LIST_LIMIT_SCHEMA = z.number().int().min(1).max(MCP_INPUT_LIMITS.listMaximum); export const MCP_MAX_EVENTS_SCHEMA = z.number().int().min(1).max(MCP_INPUT_LIMITS.maxEventsMaximum); +const MCP_HARNESS_LIST_MAXIMUMS: Record = { + listSessions: 200, + listTraces: 1000, + listArtifacts: 200, + listTasks: 1000, + listHandoffs: 1000, + listReplays: 100, + listDatasets: 100, +}; +export const MCP_HARNESS_ACTION_LIMIT_SCHEMA = z.object({ + action: z.string(), + limit: MCP_LIST_LIMIT_SCHEMA.optional(), +}).passthrough().superRefine((value, context) => { + const maximum = MCP_HARNESS_LIST_MAXIMUMS[value.action]; + if (maximum !== undefined && value.limit !== undefined && value.limit > maximum) { + context.addIssue({ + code: z.ZodIssueCode.custom, + path: ['limit'], + message: `${value.action} limit must be between 1 and ${maximum}`, + }); + } +}); const mcpString = () => z.string().max(MCP_INPUT_LIMITS.scalarString); const mcpPattern = () => mcpString().max(MCP_INPUT_LIMITS.patternLength); const mcpArray = (schema: T) => z.array(schema).max(MCP_INPUT_LIMITS.arrayItems); @@ -130,7 +156,7 @@ export class AIContextMCPServer { this.server.registerTool('explore', { description: `File and code exploration. Actions: - read: Read file contents (params: filePath, encoding?) -- list: List files matching pattern (params: pattern, cwd?, ignore?) +- list: List files matching pattern (params: pattern, cwd?, ignore?, limit?, cursor?) - analyze: Analyze symbols in a file (params: filePath, symbolTypes?) - search: Search code with regex (params: pattern, fileGlob?, maxResults?, cwd?) - getStructure: Get directory structure (params: rootPath?, maxDepth?, includePatterns?)`, @@ -147,6 +173,10 @@ export class AIContextMCPServer { .describe('(read) File encoding'), ignore: mcpArray(mcpPattern()).optional() .describe('(list) Patterns to ignore'), + limit: MCP_LIST_LIMIT_SCHEMA.optional() + .describe('(list) Maximum files per page'), + cursor: mcpString().max(MCP_INPUT_LIMITS.cursorLength).optional() + .describe('(list) Opaque continuation cursor'), symbolTypes: mcpArray(z.enum(['class', 'interface', 'function', 'type', 'enum'])).optional() .describe('(analyze) Types of symbols to extract'), fileGlob: mcpPattern().optional() @@ -809,13 +839,7 @@ Actions: await this.contextCache.set(repoPath, contextType, context); } - return { - contents: [{ - uri: uri.href, - mimeType: 'text/markdown', - text: context - }] - }; + return createBoundedResourceText(uri.href, 'text/markdown', context); } ); @@ -829,22 +853,7 @@ Actions: }, async (uri) => { const filePath = uri.pathname; - const result = await readFileTool.execute!( - { filePath }, - { toolCallId: '', messages: [] } - ) as { success: boolean; content?: string; error?: string }; - - if (!result.success) { - throw new Error(result.error || 'Failed to read file'); - } - - return { - contents: [{ - uri: uri.href, - mimeType: 'text/plain', - text: result.content || '' - }] - }; + return readBoundedFileResource(uri.href, filePath); } ); @@ -874,43 +883,27 @@ Actions: const service = new WorkflowService(repoPath); if (!(await service.hasWorkflow())) { - return { - contents: [{ - uri: 'workflow://status', - mimeType: 'application/json', - text: JSON.stringify({ error: 'No workflow found' }, null, 2) - }] - }; + return createBoundedResourceJson('workflow://status', { + error: 'No workflow found', + }); } const summary = await service.getSummary(); const status = await service.getStatus(); - return { - contents: [{ - uri: 'workflow://status', - mimeType: 'application/json', - text: JSON.stringify({ - name: summary.name, - scale: getScaleName(summary.scale as ProjectScale), - currentPhase: summary.currentPhase, - progress: summary.progress, - isComplete: summary.isComplete, - phases: status.phases, - roles: status.roles, - }, null, 2) - }] - }; + return createBoundedResourceJson('workflow://status', { + name: summary.name, + scale: getScaleName(summary.scale as ProjectScale), + currentPhase: summary.currentPhase, + progress: summary.progress, + isComplete: summary.isComplete, + phases: status.phases, + roles: status.roles, + }); } catch (error) { - return { - contents: [{ - uri: 'workflow://status', - mimeType: 'application/json', - text: JSON.stringify({ - error: error instanceof Error ? error.message : String(error) - }, null, 2) - }] - }; + return createBoundedResourceJson('workflow://status', { + error: error instanceof Error ? error.message : String(error), + }); } } ); @@ -1019,6 +1012,9 @@ Actions: : toolName; try { + if (toolName === 'harness') { + MCP_HARNESS_ACTION_LIMIT_SCHEMA.parse(params); + } validateMcpInput(params); } catch (error) { const resolvedRepoPath = this.getRepoPath(); diff --git a/src/mcp/server/resourceResponse.ts b/src/mcp/server/resourceResponse.ts new file mode 100644 index 00000000..baef7faa --- /dev/null +++ b/src/mcp/server/resourceResponse.ts @@ -0,0 +1,104 @@ +import { promises as fs } from 'fs'; + +import { resolveMcpPayloadBudget } from '../gateway/response'; + +export interface MCPResourceResponse { + [key: string]: unknown; + contents: Array<{ + uri: string; + mimeType: string; + text: string; + }>; +} + +export interface MCPResourceBudgetOptions { + payloadBudgetBytes?: number; +} + +function resourceTooLarge( + uri: string, + resourceBytes: number, + budgetBytes: number +): MCPResourceResponse { + return { + contents: [{ + uri, + mimeType: 'application/json', + text: JSON.stringify({ + success: false, + errorCode: 'MCP_RESOURCE_TOO_LARGE', + error: 'The MCP resource exceeds the configured payload budget.', + resourceBytes, + budgetBytes, + }), + }], + }; +} + +export function createBoundedResourceText( + uri: string, + mimeType: string, + text: string, + options: MCPResourceBudgetOptions = {} +): MCPResourceResponse { + const budgetBytes = resolveMcpPayloadBudget(options.payloadBudgetBytes); + const responseBytes = Buffer.byteLength(text, 'utf8'); + if (responseBytes > budgetBytes) { + return resourceTooLarge(uri, responseBytes, budgetBytes); + } + return { contents: [{ uri, mimeType, text }] }; +} + +export function createBoundedResourceJson( + uri: string, + value: unknown, + options: MCPResourceBudgetOptions = {} +): MCPResourceResponse { + return createBoundedResourceText( + uri, + 'application/json', + JSON.stringify(value), + options + ); +} + +/** Read at most budget + 1 bytes so a growing file cannot bypass the stat check. */ +export async function readBoundedFileResource( + uri: string, + filePath: string, + mimeType = 'text/plain', + options: MCPResourceBudgetOptions = {} +): Promise { + const budgetBytes = resolveMcpPayloadBudget(options.payloadBudgetBytes); + const stat = await fs.stat(filePath); + if (stat.size > budgetBytes) { + return resourceTooLarge(uri, stat.size, budgetBytes); + } + + const handle = await fs.open(filePath, 'r'); + try { + const buffer = Buffer.allocUnsafe(budgetBytes + 1); + let totalBytes = 0; + while (totalBytes < buffer.length) { + const { bytesRead } = await handle.read( + buffer, + totalBytes, + buffer.length - totalBytes, + totalBytes + ); + if (bytesRead === 0) break; + totalBytes += bytesRead; + } + if (totalBytes > budgetBytes) { + return resourceTooLarge(uri, Math.max(stat.size, totalBytes), budgetBytes); + } + return createBoundedResourceText( + uri, + mimeType, + buffer.subarray(0, totalBytes).toString('utf8'), + { payloadBudgetBytes: budgetBytes } + ); + } finally { + await handle.close(); + } +} From 1b98d6a8c1c96fa6426d3c6d0de5a1d5b44fa9c5 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:44:52 -0300 Subject: [PATCH 18/39] fix: apply repository cache policies --- .../semantic/__tests__/cacheRetention.test.ts | 33 ++++ .../semantic/__tests__/contextCache.test.ts | 27 +++ .../adapters/out/semantic/codebaseAnalyzer.ts | 25 ++- .../adapters/out/semantic/contextBuilder.ts | 103 +++++++++-- .../adapters/out/semantic/contextCache.ts | 119 ++++++++++--- .../semantic/treeSitter/treeSitterLayer.ts | 28 ++- src/harness/adapters/out/semantic/types.ts | 2 + .../__tests__/runtimeRetentionConfig.test.ts | 29 ++++ .../retention/runtimeRetentionConfig.ts | 163 ++++++++++++++---- .../domain/retention/boundedLruCache.ts | 6 + .../logging/__tests__/actionLogger.test.ts | 21 ++- src/mcp/logging/actionLogger.ts | 67 +++++-- 12 files changed, 533 insertions(+), 90 deletions(-) diff --git a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts index 39947345..fa5fa41d 100644 --- a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -2,6 +2,7 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { SemanticContextBuilder } from '../contextBuilder'; +import { CodebaseAnalyzer } from '../codebaseAnalyzer'; import { TreeSitterLayer } from '../treeSitter/treeSitterLayer'; const emptyContext = { @@ -49,4 +50,36 @@ describe('semantic cache retention', () => { expect(analyze).toHaveBeenCalledTimes(2); await builder.shutdown(); }); + + it('applies semantic byte and FileAnalysis entry overrides from this repository only', async () => { + await fs.outputJson(path.join(repo, '.context', 'config', 'runtime.json'), { + version: 1, + caches: { + semantic: { maxEntries: 1, maxBytes: 1024 }, + fileAnalysis: { maxEntries: 10, maxBytes: 1024 }, + }, + }); + const oversizedContext = { + ...emptyContext, + architecture: { ...emptyContext.architecture, entryPoints: ['x'.repeat(4_000)] }, + }; + const builder = new SemanticContextBuilder(); + const analyze = jest.fn().mockResolvedValue(oversizedContext); + (builder as any).analyzer.analyze = analyze; + await builder.analyze(repo); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(2); + expect(builder.semanticCacheMetrics(repo)).toMatchObject({ entries: 0 }); + await builder.shutdown(); + expect(builder.semanticCacheMetrics(repo)).toBeUndefined(); + + const largeSource = Array.from({ length: 200 }, (_, index) => `export function fn${index}() { return ${index}; }`).join('\n'); + await fs.outputFile(path.join(repo, 'src', 'index.ts'), largeSource); + await fs.outputFile(path.join(repo, 'src', 'second.ts'), largeSource); + const analyzer = new CodebaseAnalyzer({ useLSP: false }); + await analyzer.analyze(repo); + expect(analyzer.fileAnalysisCacheMetrics()).toMatchObject({ entries: 0, estimatedBytes: 0 }); + await analyzer.shutdown(); + expect(analyzer.fileAnalysisCacheMetrics().entries).toBe(0); + }); }); diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index 166a3805..8351bd47 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -150,6 +150,33 @@ describe('ContextCache', () => { }); describe('overwrite behavior', () => { + it('applies repository runtime overrides without leaking limits across repositories', async () => { + const otherDir = await fs.mkdtemp(path.join(os.tmpdir(), 'context-cache-other-')); + await fs.ensureDir(path.join(otherDir, 'src')); + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + version: 1, + caches: { context: { maxEntries: 1, maxBytes: 1024, ttlMs: 1000 } }, + }); + const now = jest.spyOn(Date, 'now').mockReturnValue(10_000); + const cache = new ContextCache({ sweepIntervalMs: 0 }); + await cache.set(tempDir, 'compact', 'first'); + await cache.set(tempDir, 'documentation', 'second'); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + expect(await cache.get(tempDir, 'documentation')).toBe('second'); + await cache.set(tempDir, 'plan', 'x'.repeat(2_000)); + expect(await cache.get(tempDir, 'plan')).toBeNull(); + + await cache.set(otherDir, 'compact', 'y'.repeat(2_000)); + expect(await cache.get(otherDir, 'compact')).toBe('y'.repeat(2_000)); + now.mockReturnValue(11_001); + expect(await cache.get(tempDir, 'documentation')).toBeNull(); + expect(cache.metrics().evictions.expired).toBeGreaterThan(0); + now.mockRestore(); + cache.dispose(); + expect(cache.size).toBe(0); + await fs.remove(otherDir); + }); + it('evicts least recently used contexts over the entry limit', async () => { const cache = new ContextCache({ maxEntries: 2 }); await cache.set(tempDir, 'compact', 'a'); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 49be7e6c..06b95266 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -8,6 +8,7 @@ import { glob } from 'glob'; import * as path from 'path'; import * as fs from 'fs/promises'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; import { TreeSitterLayer } from './treeSitter/treeSitterLayer'; import { LSPLayer } from './lsp/lspLayer'; import { @@ -36,16 +37,26 @@ const DEFAULT_OPTIONS: Required = { include: [], maxFiles: 5000, cacheEnabled: true, + fileAnalysisCacheMaxEntries: 5_000, + fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, }; export class CodebaseAnalyzer { private treeSitter: TreeSitterLayer; private lspLayer?: LSPLayer; private options: Required; + private readonly fileCacheEntriesExplicit: boolean; + private readonly fileCacheBytesExplicit: boolean; constructor(options: AnalyzerOptions = {}) { + this.fileCacheEntriesExplicit = options.fileAnalysisCacheMaxEntries !== undefined; + this.fileCacheBytesExplicit = options.fileAnalysisCacheMaxBytes !== undefined; this.options = { ...DEFAULT_OPTIONS, ...options }; - this.treeSitter = new TreeSitterLayer({ cacheEnabled: this.options.cacheEnabled }); + this.treeSitter = new TreeSitterLayer({ + cacheEnabled: this.options.cacheEnabled, + maxEntries: this.options.fileAnalysisCacheMaxEntries, + maxBytes: this.options.fileAnalysisCacheMaxBytes, + }); // Create LSPLayer if LSP mode is enabled if (this.options.useLSP) { @@ -55,6 +66,14 @@ export class CodebaseAnalyzer { async analyze(projectPath: string): Promise { const startTime = Date.now(); + if (this.options.cacheEnabled) { + const { config } = await loadRuntimeRetentionConfig(projectPath); + this.treeSitter.configureCache?.({ + maxEntries: this.fileCacheEntriesExplicit ? this.options.fileAnalysisCacheMaxEntries : config.caches.fileAnalysis.maxEntries, + maxBytes: this.fileCacheBytesExplicit ? this.options.fileAnalysisCacheMaxBytes : config.caches.fileAnalysis.maxBytes, + scope: path.resolve(projectPath), + }); + } // 1. Find all code files const files = await this.findCodeFiles(projectPath); @@ -593,6 +612,10 @@ export class CodebaseAnalyzer { this.treeSitter.clearCache(); } + fileAnalysisCacheMetrics() { + return this.treeSitter.cacheMetrics(); + } + /** * Shutdown LSP servers gracefully */ diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index 2a3011fd..5703d597 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -18,6 +18,8 @@ import type { AnalyzerOptions, } from './types'; import { DEFAULT_EXCLUDE_PATTERNS } from './types'; +import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; export interface ContextBuilderOptions extends AnalyzerOptions { /** Maximum symbols to include per category */ @@ -41,6 +43,8 @@ const DEFAULT_OPTIONS: Required = { include: [], maxFiles: 5000, cacheEnabled: true, + fileAnalysisCacheMaxEntries: 5_000, + fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, maxSymbolsPerCategory: 50, includeDocumentation: true, includeSignatures: true, @@ -51,11 +55,18 @@ const DEFAULT_OPTIONS: Required = { export class SemanticContextBuilder { private analyzer: CodebaseAnalyzer; private options: Required; - private cachedContext: SemanticContext | null = null; - private cachedProjectPath: string | null = null; - private cachedFingerprint: string | null = null; + private readonly semanticCacheBytesExplicit: boolean; + private readonly semanticCaches = new Map; + signature: string; + fingerprint?: string; + diagnostics: string[]; + maxEntries: number; + maxBytes: number; + }>(); constructor(options: ContextBuilderOptions = {}) { + this.semanticCacheBytesExplicit = options.semanticCacheMaxBytes !== undefined; this.options = { ...DEFAULT_OPTIONS, ...options }; this.analyzer = new CodebaseAnalyzer(this.options); } @@ -66,20 +77,23 @@ export class SemanticContextBuilder { async analyze(projectPath: string): Promise { const normalizedProjectPath = path.resolve(projectPath); const fingerprint = await this.computeProjectFingerprint(normalizedProjectPath); - if ( - this.options.cacheEnabled && - this.cachedContext && - this.cachedProjectPath === normalizedProjectPath && - this.cachedFingerprint === fingerprint - ) { - return this.cachedContext; + const owner = this.options.cacheEnabled + ? await this.semanticCacheForRepo(normalizedProjectPath) + : undefined; + if (owner?.fingerprint && owner.fingerprint !== fingerprint) { + owner.cache.clear(); + } + const cached = owner?.cache.get(fingerprint); + if (cached) { + owner!.fingerprint = fingerprint; + return cached; } const context = await this.analyzer.analyze(normalizedProjectPath); - if (this.options.cacheEnabled && this.estimateSemanticContextBytes(context) <= this.options.semanticCacheMaxBytes) { - this.cachedContext = context; - this.cachedProjectPath = normalizedProjectPath; - this.cachedFingerprint = fingerprint; + if (owner) { + owner.cache.set(fingerprint, context); + owner.fingerprint = fingerprint; + this.enforceSemanticLimits(owner.maxEntries, owner.maxBytes); } return context; } @@ -823,9 +837,7 @@ export class SemanticContextBuilder { * Clear cached analysis */ clearCache(): void { - this.cachedContext = null; - this.cachedProjectPath = null; - this.cachedFingerprint = null; + for (const owner of this.semanticCaches.values()) owner.cache.clear(); this.analyzer.clearCache(); } @@ -834,9 +846,66 @@ export class SemanticContextBuilder { */ async shutdown(): Promise { this.clearCache(); + for (const owner of this.semanticCaches.values()) owner.cache.dispose(); + this.semanticCaches.clear(); await this.analyzer.shutdown(); } + semanticCacheMetrics(projectPath: string): BoundedLruCacheMetrics | undefined { + return this.semanticCaches.get(path.resolve(projectPath))?.cache.metrics(); + } + + configDiagnostics(projectPath: string): string[] { + return [...(this.semanticCaches.get(path.resolve(projectPath))?.diagnostics ?? [])]; + } + + private async semanticCacheForRepo(projectPath: string) { + for (const [ownerPath, owner] of this.semanticCaches) { + if (ownerPath !== projectPath && owner.cache.size === 0) { + owner.cache.dispose(); + this.semanticCaches.delete(ownerPath); + } + } + const loaded = await loadRuntimeRetentionConfig(projectPath); + const configured = loaded.config.caches.semantic; + const limits = { + maxEntries: configured.maxEntries, + maxBytes: this.semanticCacheBytesExplicit ? this.options.semanticCacheMaxBytes : configured.maxBytes, + }; + const signature = JSON.stringify(limits); + const current = this.semanticCaches.get(projectPath); + if (current?.signature === signature) { + this.semanticCaches.delete(projectPath); + this.semanticCaches.set(projectPath, current); + return current; + } + current?.cache.dispose(); + const cache = new BoundedLruCache({ + ...limits, + ttlMs: 24 * 60 * 60 * 1000, + estimateBytes: context => this.estimateSemanticContextBytes(context), + }); + const owner = { cache, signature, diagnostics: loaded.diagnostics, ...limits, fingerprint: undefined as string | undefined }; + this.semanticCaches.set(projectPath, owner); + return owner; + } + + private enforceSemanticLimits(maxEntries: number, maxBytes: number): void { + const totalEntries = () => [...this.semanticCaches.values()].reduce((sum, owner) => sum + owner.cache.size, 0); + const totalBytes = () => [...this.semanticCaches.values()].reduce((sum, owner) => sum + owner.cache.metrics().estimatedBytes, 0); + while (totalEntries() > maxEntries || totalBytes() > maxBytes) { + const oldestOwnerPath = this.semanticCaches.keys().next().value as string | undefined; + if (!oldestOwnerPath) break; + const owner = this.semanticCaches.get(oldestOwnerPath)!; + const reason = totalEntries() > maxEntries ? 'entries' : 'bytes'; + owner.cache.evictLeastRecentlyUsed(reason); + if (owner.cache.size === 0) { + owner.cache.dispose(); + this.semanticCaches.delete(oldestOwnerPath); + } + } + } + private async computeProjectFingerprint(projectPath: string): Promise { const extensions = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go']; const files = await glob(`**/*.{${extensions.join(',')}}`, { diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index c44d0fbf..c4758445 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -16,6 +16,7 @@ import * as path from 'path'; import { createHash } from 'crypto'; import { glob } from 'glob'; import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; /** * A cached context entry with metadata for invalidation. @@ -46,20 +47,17 @@ const DEFAULT_MAX_ENTRIES = 16; const DEFAULT_MAX_BYTES = 32 * 1024 * 1024; export class ContextCache { - private readonly cache: BoundedLruCache; - private readonly ttlMs: number; + private readonly caches = new Map; + signature: string; + diagnostics: string[]; + }>(); private readonly watchDirs: string[]; + private readonly options: ContextCacheOptions; constructor(options: ContextCacheOptions = {}) { - this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; + this.options = options; this.watchDirs = options.watchDirs ?? DEFAULT_WATCH_DIRS; - this.cache = new BoundedLruCache({ - maxEntries: options.maxEntries ?? DEFAULT_MAX_ENTRIES, - maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES, - ttlMs: this.ttlMs, - sweepIntervalMs: options.sweepIntervalMs, - estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + Buffer.byteLength(entry.mtimeHash), - }); } /** @@ -70,8 +68,9 @@ export class ContextCache { * @returns Cached context string or null */ async get(repoPath: string, contextType: string, keyOptions?: unknown): Promise { + const cache = await this.cacheForRepo(repoPath); const key = this.buildKey(repoPath, contextType, keyOptions); - const entry = this.cache.get(key); + const entry = cache.get(key); if (!entry) { return null; @@ -80,7 +79,7 @@ export class ContextCache { // Check directory mtime invalidation const currentMtimeHash = await this.computeMtimeHash(repoPath); if (currentMtimeHash !== entry.mtimeHash) { - this.cache.delete(key); + cache.delete(key); return null; } @@ -95,48 +94,69 @@ export class ContextCache { * @param content - The context string to cache */ async set(repoPath: string, contextType: string, content: string, keyOptions?: unknown): Promise { + const cache = await this.cacheForRepo(repoPath); const key = this.buildKey(repoPath, contextType, keyOptions); const mtimeHash = await this.computeMtimeHash(repoPath); - this.cache.set(key, { + cache.set(key, { content, mtimeHash, }); + const loaded = await loadRuntimeRetentionConfig(repoPath); + this.enforceGlobalLimits({ + maxEntries: this.options.maxEntries ?? loaded.config.caches.context.maxEntries, + maxBytes: this.options.maxBytes ?? loaded.config.caches.context.maxBytes, + }); } /** * Invalidate all entries for a given repository. */ invalidateRepo(repoPath: string): void { - const prefix = this.normalizeRepoPath(repoPath) + ':'; - for (const key of this.cache.keys()) { - if (key.startsWith(prefix)) { - this.cache.delete(key); - } - } + const normalized = this.normalizeRepoPath(repoPath); + this.caches.get(normalized)?.cache.clear(); } /** * Clear all cached entries. */ clear(): void { - this.cache.clear(); + for (const owner of this.caches.values()) owner.cache.clear(); } /** Stop proactive sweeping and release all entries. */ dispose(): void { - this.cache.dispose(); + for (const owner of this.caches.values()) owner.cache.dispose(); + this.caches.clear(); } metrics(): BoundedLruCacheMetrics { - return this.cache.metrics(); + const all = [...this.caches.values()].map(owner => owner.cache.metrics()); + return all.reduce((total, metric) => ({ + entries: total.entries + metric.entries, + estimatedBytes: total.estimatedBytes + metric.estimatedBytes, + hits: total.hits + metric.hits, + misses: total.misses + metric.misses, + evictions: { + expired: total.evictions.expired + metric.evictions.expired, + entries: total.evictions.entries + metric.evictions.entries, + bytes: total.evictions.bytes + metric.evictions.bytes, + replaced: total.evictions.replaced + metric.evictions.replaced, + cleared: total.evictions.cleared + metric.evictions.cleared, + }, + oldestAgeMs: Math.max(total.oldestAgeMs, metric.oldestAgeMs), + }), { entries: 0, estimatedBytes: 0, hits: 0, misses: 0, evictions: { expired: 0, entries: 0, bytes: 0, replaced: 0, cleared: 0 }, oldestAgeMs: 0 }); } /** * Get the number of cached entries (for monitoring/debugging). */ get size(): number { - return this.cache.size; + return [...this.caches.values()].reduce((total, owner) => total + owner.cache.size, 0); + } + + configDiagnostics(repoPath: string): string[] { + return [...(this.caches.get(this.normalizeRepoPath(repoPath))?.diagnostics ?? [])]; } /** @@ -144,14 +164,63 @@ export class ContextCache { */ private buildKey(repoPath: string, contextType: string, keyOptions?: unknown): string { const optionsKey = keyOptions === undefined ? '' : `:${JSON.stringify(keyOptions)}`; - return `${this.normalizeRepoPath(repoPath)}:${contextType}${optionsKey}`; + return `${contextType}${optionsKey}`; } /** * Normalize repo path for consistent cache keys. */ private normalizeRepoPath(repoPath: string): string { - return path.resolve(repoPath).toLowerCase(); + const resolved = path.resolve(repoPath); + return process.platform === 'win32' ? resolved.toLowerCase() : resolved; + } + + private async cacheForRepo(repoPath: string): Promise> { + const normalized = this.normalizeRepoPath(repoPath); + for (const [ownerPath, owner] of this.caches) { + if (ownerPath !== normalized && owner.cache.size === 0) { + owner.cache.dispose(); + this.caches.delete(ownerPath); + } + } + const loaded = await loadRuntimeRetentionConfig(normalized); + const configured = loaded.config.caches.context; + const limits = { + maxEntries: this.options.maxEntries ?? configured.maxEntries ?? DEFAULT_MAX_ENTRIES, + maxBytes: this.options.maxBytes ?? configured.maxBytes ?? DEFAULT_MAX_BYTES, + ttlMs: this.options.ttlMs ?? configured.ttlMs ?? DEFAULT_TTL_MS, + }; + const signature = JSON.stringify(limits); + const current = this.caches.get(normalized); + if (current?.signature === signature) { + this.caches.delete(normalized); + this.caches.set(normalized, current); + return current.cache; + } + current?.cache.dispose(); + const cache = new BoundedLruCache({ + ...limits, + sweepIntervalMs: this.options.sweepIntervalMs, + estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + Buffer.byteLength(entry.mtimeHash), + }); + this.caches.set(normalized, { cache, signature, diagnostics: loaded.diagnostics }); + return cache; + } + + private enforceGlobalLimits(limits: { maxEntries: number; maxBytes: number }): void { + const totalEntries = () => [...this.caches.values()].reduce((sum, owner) => sum + owner.cache.size, 0); + const totalBytes = () => [...this.caches.values()].reduce((sum, owner) => sum + owner.cache.metrics().estimatedBytes, 0); + while (totalEntries() > limits.maxEntries || totalBytes() > limits.maxBytes) { + const oldestOwnerKey = this.caches.keys().next().value as string | undefined; + if (!oldestOwnerKey) break; + const owner = this.caches.get(oldestOwnerKey)!; + const reason = totalEntries() > limits.maxEntries ? 'entries' : 'bytes'; + owner.cache.evictLeastRecentlyUsed(reason); + if (owner.cache.size === 0) { + owner.cache.dispose(); + this.caches.delete(oldestOwnerKey); + } + } } /** diff --git a/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts b/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts index 6f2afed7..b6c16660 100644 --- a/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts +++ b/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts @@ -23,22 +23,36 @@ interface CacheEntry { } export class TreeSitterLayer { - private readonly cache: BoundedLruCache; + private cache: BoundedLruCache; private readonly cacheEnabled: boolean; + private cacheSignature: string; private treeSitterAvailable: boolean = false; private parsers: Map = new Map(); public readonly ready: Promise; constructor(options: { cacheEnabled?: boolean; maxEntries?: number; maxBytes?: number } = {}) { this.cacheEnabled = options.cacheEnabled ?? true; - this.cache = new BoundedLruCache({ - maxEntries: options.maxEntries ?? 5_000, - maxBytes: options.maxBytes ?? 128 * 1024 * 1024, + const limits = { maxEntries: options.maxEntries ?? 5_000, maxBytes: options.maxBytes ?? 128 * 1024 * 1024 }; + this.cacheSignature = JSON.stringify(limits); + this.cache = this.createCache(limits); + this.ready = this.initializeParsers(); + } + + private createCache(limits: { maxEntries: number; maxBytes: number }): BoundedLruCache { + return new BoundedLruCache({ + ...limits, // File freshness is mtime-bound; this TTL bounds idle retention for long-lived processes. ttlMs: 30 * 60 * 1000, estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(JSON.stringify(entry.analysis)), }); - this.ready = this.initializeParsers(); + } + + configureCache(options: { maxEntries: number; maxBytes: number; scope: string }): void { + const signature = JSON.stringify(options); + if (signature === this.cacheSignature) return; + this.cache.dispose(); + this.cache = this.createCache(options); + this.cacheSignature = signature; } private async initializeParsers(): Promise { @@ -582,6 +596,10 @@ export class TreeSitterLayer { return this.cache.size; } + cacheMetrics() { + return this.cache.metrics(); + } + dispose(): void { this.cache.dispose(); } diff --git a/src/harness/adapters/out/semantic/types.ts b/src/harness/adapters/out/semantic/types.ts index 2b38577d..9577628c 100644 --- a/src/harness/adapters/out/semantic/types.ts +++ b/src/harness/adapters/out/semantic/types.ts @@ -191,6 +191,8 @@ export interface AnalyzerOptions { include?: string[]; maxFiles?: number; cacheEnabled?: boolean; + fileAnalysisCacheMaxEntries?: number; + fileAnalysisCacheMaxBytes?: number; } export interface LSPServerConfig { diff --git a/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts index 09288ea3..3760c245 100644 --- a/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts +++ b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts @@ -20,4 +20,33 @@ describe('loadRuntimeRetentionConfig', () => { expect(result.clamps).toBeGreaterThan(0); await fs.remove(repo); }); + + it('diagnoses invalid versions and nested unknown keys without exposing key content', async () => { + const repo = await fs.mkdtemp(path.join(os.tmpdir(), 'runtime-retention-version-')); + const secretKey = `secret-config-${'private'.repeat(100)}`; + await fs.outputJson(path.join(repo, '.context', 'config', 'runtime.json'), { + version: 1, + caches: { + context: { maxEntries: 2, unknownNested: true, [secretKey]: 'never-log-this-value' }, + unknownCache: { body: 'never-log-this-value' }, + }, + }); + const nested = await loadRuntimeRetentionConfig(repo); + expect(nested.config.caches.context.maxEntries).toBe(2); + expect(nested.metrics.unknownKeys).toBe(3); + expect(nested.diagnostics.join('\n')).toContain('caches.context.unknownNested'); + expect(nested.diagnostics.join('\n')).not.toContain('privateprivate'); + expect(nested.diagnostics.join('\n')).not.toContain('never-log-this-value'); + expect(nested.diagnostics.every(item => item.length <= 200)).toBe(true); + + await fs.outputJson(path.join(repo, '.context', 'config', 'runtime.json'), { + version: 999, + caches: { context: { maxEntries: 1 } }, + }); + const invalidVersion = await loadRuntimeRetentionConfig(repo); + expect(invalidVersion.metrics.invalidVersion).toBe(1); + expect(invalidVersion.config.caches.context.maxEntries).toBe(16); + expect(invalidVersion.diagnostics).toContain('runtime.json version is unsupported; safe defaults applied'); + await fs.remove(repo); + }); }); diff --git a/src/harness/application/retention/runtimeRetentionConfig.ts b/src/harness/application/retention/runtimeRetentionConfig.ts index 6aa402b0..10396578 100644 --- a/src/harness/application/retention/runtimeRetentionConfig.ts +++ b/src/harness/application/retention/runtimeRetentionConfig.ts @@ -17,10 +17,19 @@ export interface RuntimeRetentionConfig { }; } +export interface RuntimeRetentionConfigMetrics { + invalidVersion: number; + unknownKeys: number; + invalidValues: number; + clampedValues: number; + diagnosticsDropped: number; +} + export interface RuntimeRetentionConfigResult { config: RuntimeRetentionConfig; diagnostics: string[]; clamps: number; + metrics: RuntimeRetentionConfigMetrics; } export const DEFAULT_RUNTIME_RETENTION_CONFIG: RuntimeRetentionConfig = { @@ -39,7 +48,62 @@ export const DEFAULT_RUNTIME_RETENTION_CONFIG: RuntimeRetentionConfig = { }, }; -const KNOWN_TOP_LEVEL = new Set(['version', 'traces', 'sessions', 'replays', 'datasets', 'checkpoints', 'bindings', 'caches']); +const MAX_DIAGNOSTICS = 32; +const KNOWN_KEYS: Record = { + root: ['version', 'traces', 'sessions', 'replays', 'datasets', 'checkpoints', 'bindings', 'caches'], + traces: ['maxBytes'], + sessions: ['maxEntries'], + replays: ['maxEntries'], + datasets: ['maxEntries'], + checkpoints: ['maxDataBytes', 'maxArtifactIds'], + bindings: ['maxEntries', 'maxAgeMs'], + caches: ['context', 'semantic', 'mcpSessions', 'fileAnalysis'], + 'caches.context': ['maxEntries', 'maxBytes', 'ttlMs'], + 'caches.semantic': ['maxEntries', 'maxBytes'], + 'caches.mcpSessions': ['maxEntries', 'ttlMs'], + 'caches.fileAnalysis': ['maxEntries', 'maxBytes'], +}; + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function safeKey(key: string): string { + return /^[A-Za-z0-9_-]{1,64}$/.test(key) + ? key + : ``; +} + +function addDiagnostic( + diagnostics: string[], + metrics: RuntimeRetentionConfigMetrics, + message: string, +): void { + if (diagnostics.length < MAX_DIAGNOSTICS) diagnostics.push(message.slice(0, 200)); + else metrics.diagnosticsDropped += 1; +} + +function diagnoseShape( + value: unknown, + section: string, + diagnostics: string[], + metrics: RuntimeRetentionConfigMetrics, +): Record { + if (value === undefined) return {}; + if (!isRecord(value)) { + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, `${section} must be an object; defaults applied`); + return {}; + } + const known = new Set(KNOWN_KEYS[section] ?? []); + for (const key of Object.keys(value)) { + if (!known.has(key)) { + metrics.unknownKeys += 1; + addDiagnostic(diagnostics, metrics, `Unknown runtime configuration key ignored: ${section}.${safeKey(key)}`); + } + } + return value; +} function boundedNumber( value: unknown, @@ -48,71 +112,110 @@ function boundedNumber( absoluteMaximum: number, name: string, diagnostics: string[], + metrics: RuntimeRetentionConfigMetrics, ): number { if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum) { - if (value !== undefined) diagnostics.push(`${name} was invalid and reset to ${fallback}`); + if (value !== undefined) { + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, `${name} was invalid; safe default applied`); + } return fallback; } if (value > absoluteMaximum) { - diagnostics.push(`${name} was clamped to the absolute safety ceiling ${absoluteMaximum}`); + metrics.clampedValues += 1; + addDiagnostic(diagnostics, metrics, `${name} was clamped to the absolute safety ceiling ${absoluteMaximum}`); return absoluteMaximum; } return Math.floor(value); } -/** Load `.context/config/runtime.json`, ignoring unknown keys and clamping unsafe limits. */ +/** Load a repository-scoped, versioned runtime policy without logging caller content. */ export async function loadRuntimeRetentionConfig(repoPath: string): Promise { const diagnostics: string[] = []; + const metrics: RuntimeRetentionConfigMetrics = { + invalidVersion: 0, + unknownKeys: 0, + invalidValues: 0, + clampedValues: 0, + diagnosticsDropped: 0, + }; const file = path.join(path.resolve(repoPath), '.context', 'config', 'runtime.json'); - let input: Record = {}; + let input: Record = {}; + let fileExists = false; if (await fs.pathExists(file)) { + fileExists = true; try { - const parsed = await fs.readJson(file); - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) input = parsed; - else diagnostics.push('runtime.json root must be an object; defaults applied'); + const parsed = await fs.readJson(file) as unknown; + if (isRecord(parsed)) input = parsed; + else { + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, 'runtime.json root must be an object; defaults applied'); + } } catch { - diagnostics.push('runtime.json could not be parsed; defaults applied'); + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, 'runtime.json could not be parsed; defaults applied'); } } - for (const key of Object.keys(input)) { - if (!KNOWN_TOP_LEVEL.has(key)) diagnostics.push(`Unknown runtime configuration key ignored: ${key}`); + + diagnoseShape(input, 'root', diagnostics, metrics); + if (fileExists && input.version !== 1) { + metrics.invalidVersion += 1; + addDiagnostic(diagnostics, metrics, 'runtime.json version is unsupported; safe defaults applied'); + return { + config: structuredClone(DEFAULT_RUNTIME_RETENTION_CONFIG), + diagnostics, + clamps: metrics.invalidValues + metrics.clampedValues, + metrics, + }; } + + const traces = diagnoseShape(input.traces, 'traces', diagnostics, metrics); + const sessions = diagnoseShape(input.sessions, 'sessions', diagnostics, metrics); + const replays = diagnoseShape(input.replays, 'replays', diagnostics, metrics); + const datasets = diagnoseShape(input.datasets, 'datasets', diagnostics, metrics); + const checkpoints = diagnoseShape(input.checkpoints, 'checkpoints', diagnostics, metrics); + const bindings = diagnoseShape(input.bindings, 'bindings', diagnostics, metrics); + const caches = diagnoseShape(input.caches, 'caches', diagnostics, metrics); + const context = diagnoseShape(caches.context, 'caches.context', diagnostics, metrics); + const semantic = diagnoseShape(caches.semantic, 'caches.semantic', diagnostics, metrics); + const mcpSessions = diagnoseShape(caches.mcpSessions, 'caches.mcpSessions', diagnostics, metrics); + const fileAnalysis = diagnoseShape(caches.fileAnalysis, 'caches.fileAnalysis', diagnostics, metrics); const d = DEFAULT_RUNTIME_RETENTION_CONFIG; const number = (value: unknown, fallback: number, min: number, max: number, name: string) => - boundedNumber(value, fallback, min, max, name, diagnostics); + boundedNumber(value, fallback, min, max, name, diagnostics, metrics); const config: RuntimeRetentionConfig = { version: 1, - traces: { maxBytes: number(input.traces?.maxBytes, d.traces.maxBytes, 1_024, 1024 ** 3, 'traces.maxBytes') }, - sessions: { maxEntries: number(input.sessions?.maxEntries, d.sessions.maxEntries, 1, 100_000, 'sessions.maxEntries') }, - replays: { maxEntries: number(input.replays?.maxEntries, d.replays.maxEntries, 1, 10_000, 'replays.maxEntries') }, - datasets: { maxEntries: number(input.datasets?.maxEntries, d.datasets.maxEntries, 1, 10_000, 'datasets.maxEntries') }, + traces: { maxBytes: number(traces.maxBytes, d.traces.maxBytes, 1_024, 1024 ** 3, 'traces.maxBytes') }, + sessions: { maxEntries: number(sessions.maxEntries, d.sessions.maxEntries, 1, 100_000, 'sessions.maxEntries') }, + replays: { maxEntries: number(replays.maxEntries, d.replays.maxEntries, 1, 10_000, 'replays.maxEntries') }, + datasets: { maxEntries: number(datasets.maxEntries, d.datasets.maxEntries, 1, 10_000, 'datasets.maxEntries') }, checkpoints: { - maxDataBytes: number(input.checkpoints?.maxDataBytes, d.checkpoints.maxDataBytes, 1_024, 1024 ** 2, 'checkpoints.maxDataBytes'), - maxArtifactIds: number(input.checkpoints?.maxArtifactIds, d.checkpoints.maxArtifactIds, 1, 1_000, 'checkpoints.maxArtifactIds'), + maxDataBytes: number(checkpoints.maxDataBytes, d.checkpoints.maxDataBytes, 1_024, 1024 ** 2, 'checkpoints.maxDataBytes'), + maxArtifactIds: number(checkpoints.maxArtifactIds, d.checkpoints.maxArtifactIds, 1, 1_000, 'checkpoints.maxArtifactIds'), }, bindings: { - maxEntries: number(input.bindings?.maxEntries, d.bindings.maxEntries, 1, 10_000, 'bindings.maxEntries'), - maxAgeMs: number(input.bindings?.maxAgeMs, d.bindings.maxAgeMs, 60_000, 365 * 24 * 60 * 60 * 1000, 'bindings.maxAgeMs'), + maxEntries: number(bindings.maxEntries, d.bindings.maxEntries, 1, 10_000, 'bindings.maxEntries'), + maxAgeMs: number(bindings.maxAgeMs, d.bindings.maxAgeMs, 60_000, 365 * 24 * 60 * 60 * 1000, 'bindings.maxAgeMs'), }, caches: { context: { - maxEntries: number(input.caches?.context?.maxEntries, d.caches.context.maxEntries, 1, 256, 'caches.context.maxEntries'), - maxBytes: number(input.caches?.context?.maxBytes, d.caches.context.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.context.maxBytes'), - ttlMs: number(input.caches?.context?.ttlMs, d.caches.context.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.context.ttlMs'), + maxEntries: number(context.maxEntries, d.caches.context.maxEntries, 1, 256, 'caches.context.maxEntries'), + maxBytes: number(context.maxBytes, d.caches.context.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.context.maxBytes'), + ttlMs: number(context.ttlMs, d.caches.context.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.context.ttlMs'), }, semantic: { - maxEntries: number(input.caches?.semantic?.maxEntries, d.caches.semantic.maxEntries, 1, 4, 'caches.semantic.maxEntries'), - maxBytes: number(input.caches?.semantic?.maxBytes, d.caches.semantic.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.semantic.maxBytes'), + maxEntries: number(semantic.maxEntries, d.caches.semantic.maxEntries, 1, 4, 'caches.semantic.maxEntries'), + maxBytes: number(semantic.maxBytes, d.caches.semantic.maxBytes, 1_024, 256 * 1024 * 1024, 'caches.semantic.maxBytes'), }, mcpSessions: { - maxEntries: number(input.caches?.mcpSessions?.maxEntries, d.caches.mcpSessions.maxEntries, 1, 1_000, 'caches.mcpSessions.maxEntries'), - ttlMs: number(input.caches?.mcpSessions?.ttlMs, d.caches.mcpSessions.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.mcpSessions.ttlMs'), + maxEntries: number(mcpSessions.maxEntries, d.caches.mcpSessions.maxEntries, 1, 1_000, 'caches.mcpSessions.maxEntries'), + ttlMs: number(mcpSessions.ttlMs, d.caches.mcpSessions.ttlMs, 1_000, 24 * 60 * 60 * 1000, 'caches.mcpSessions.ttlMs'), }, fileAnalysis: { - maxEntries: number(input.caches?.fileAnalysis?.maxEntries, d.caches.fileAnalysis.maxEntries, 1, 20_000, 'caches.fileAnalysis.maxEntries'), - maxBytes: number(input.caches?.fileAnalysis?.maxBytes, d.caches.fileAnalysis.maxBytes, 1_024, 512 * 1024 * 1024, 'caches.fileAnalysis.maxBytes'), + maxEntries: number(fileAnalysis.maxEntries, d.caches.fileAnalysis.maxEntries, 1, 20_000, 'caches.fileAnalysis.maxEntries'), + maxBytes: number(fileAnalysis.maxBytes, d.caches.fileAnalysis.maxBytes, 1_024, 512 * 1024 * 1024, 'caches.fileAnalysis.maxBytes'), }, }, }; - return { config, diagnostics, clamps: diagnostics.length }; + return { config, diagnostics, clamps: metrics.invalidValues + metrics.clampedValues, metrics }; } diff --git a/src/harness/domain/retention/boundedLruCache.ts b/src/harness/domain/retention/boundedLruCache.ts index 4fccc9d1..dd2e1320 100644 --- a/src/harness/domain/retention/boundedLruCache.ts +++ b/src/harness/domain/retention/boundedLruCache.ts @@ -102,6 +102,12 @@ export class BoundedLruCache { for (const key of [...this.entries.keys()]) this.remove(key, 'cleared'); } + evictLeastRecentlyUsed(reason: 'entries' | 'bytes'): boolean { + const before = this.entries.size; + this.evictOldest(reason); + return this.entries.size < before; + } + dispose(): void { if (this.timer) clearInterval(this.timer); this.clear(); diff --git a/src/mcp/logging/__tests__/actionLogger.test.ts b/src/mcp/logging/__tests__/actionLogger.test.ts index 230356a5..a642694a 100644 --- a/src/mcp/logging/__tests__/actionLogger.test.ts +++ b/src/mcp/logging/__tests__/actionLogger.test.ts @@ -4,7 +4,7 @@ import * as path from 'path'; import { HarnessRuntimeStateService } from '../../../harness/adapters/out/runtimeState/runtimeStateService'; import { WorkflowService } from '../../../harness/application/workflow/workflowService'; -import { clearMcpActionSessionCache, getMcpActionSessionCacheSize, logMcpAction } from '../actionLogger'; +import { clearMcpActionSessionCache, getMcpActionSessionCacheMetrics, getMcpActionSessionCacheSize, logMcpAction } from '../actionLogger'; describe('logMcpAction', () => { let tempDir: string; @@ -88,4 +88,23 @@ describe('logMcpAction', () => { expect(traces.some((trace) => trace.event === 'mcp.tool.succeeded')).toBe(true); expect(await fs.pathExists(path.join(tempDir, '.context', 'workflow', 'actions.jsonl'))).toBe(false); }); + + it('applies the repository MCP session TTL and expires without cross-repo cache keys', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + version: 1, + caches: { mcpSessions: { maxEntries: 1, ttlMs: 1000 } }, + }); + const now = jest.spyOn(Date, 'now').mockReturnValue(1_000); + const entry = { tool: 'context', action: 'check', status: 'success' as const }; + await logMcpAction(tempDir, entry); + await logMcpAction(tempDir, entry); + expect(getMcpActionSessionCacheMetrics(tempDir)?.hits).toBe(1); + now.mockReturnValue(2_001); + await logMcpAction(tempDir, entry); + expect(getMcpActionSessionCacheMetrics(tempDir)?.evictions.expired).toBe(1); + expect(getMcpActionSessionCacheSize()).toBe(1); + now.mockRestore(); + clearMcpActionSessionCache(); + expect(getMcpActionSessionCacheSize()).toBe(0); + }); }); diff --git a/src/mcp/logging/actionLogger.ts b/src/mcp/logging/actionLogger.ts index 9bb58ba2..2843e505 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -9,7 +9,8 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import { HarnessRuntimeStateService } from '../../harness/adapters/out/runtimeState/runtimeStateService'; -import { BoundedLruCache } from '../../harness/domain/retention/boundedLruCache'; +import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../harness/domain/retention/boundedLruCache'; +import { loadRuntimeRetentionConfig } from '../../harness/application/retention/runtimeRetentionConfig'; import { HarnessWorkflowStateService } from '../../harness/adapters/out/workflowState/workflowStateService'; import { resolveContextRoot } from '../../shared/context/contextRootResolver'; @@ -41,23 +42,66 @@ const MAX_ARRAY = 20; const MAX_STRING = 200; const MCP_ACTIVITY_NAME = 'mcp-activity'; -const sessionCache = new BoundedLruCache({ - maxEntries: 64, - maxBytes: 64 * 1024, - ttlMs: 30 * 60 * 1000, - estimateBytes: (sessionId, repoPath) => Buffer.byteLength(sessionId) + Buffer.byteLength(repoPath), -}); +const sessionCaches = new Map; + signature: string; + diagnostics: string[]; +}>(); function normalizeRepoPath(repoPath: string): string { - return path.resolve(repoPath).toLowerCase(); + const resolved = path.resolve(repoPath); + return process.platform === 'win32' ? resolved.toLowerCase() : resolved; +} + +async function sessionCacheForRepo(repoPath: string): Promise> { + const normalized = normalizeRepoPath(repoPath); + for (const [ownerPath, owner] of sessionCaches) { + if (owner.cache.size === 0) { + owner.cache.dispose(); + sessionCaches.delete(ownerPath); + } + } + const loaded = await loadRuntimeRetentionConfig(normalized); + const limits = loaded.config.caches.mcpSessions; + const signature = JSON.stringify(limits); + const current = sessionCaches.get(normalized); + if (current?.signature === signature) { + sessionCaches.delete(normalized); + sessionCaches.set(normalized, current); + return current.cache; + } + current?.cache.dispose(); + const cache = new BoundedLruCache({ + maxEntries: limits.maxEntries, + maxBytes: 64 * 1024, + ttlMs: limits.ttlMs, + estimateBytes: (sessionId, key) => Buffer.byteLength(sessionId) + Buffer.byteLength(key), + }); + sessionCaches.set(normalized, { cache, signature, diagnostics: loaded.diagnostics }); + while (sessionCaches.size > limits.maxEntries) { + const oldest = sessionCaches.keys().next().value as string | undefined; + if (!oldest) break; + sessionCaches.get(oldest)?.cache.dispose(); + sessionCaches.delete(oldest); + } + return cache; } export function clearMcpActionSessionCache(): void { - sessionCache.dispose(); + for (const owner of sessionCaches.values()) owner.cache.dispose(); + sessionCaches.clear(); } export function getMcpActionSessionCacheSize(): number { - return sessionCache.size; + return [...sessionCaches.values()].reduce((total, owner) => total + owner.cache.size, 0); +} + +export function getMcpActionSessionCacheDiagnostics(repoPath: string): string[] { + return [...(sessionCaches.get(normalizeRepoPath(repoPath))?.diagnostics ?? [])]; +} + +export function getMcpActionSessionCacheMetrics(repoPath: string): BoundedLruCacheMetrics | undefined { + return sessionCaches.get(normalizeRepoPath(repoPath))?.cache.metrics(); } async function resolveContextPath(repoPath: string): Promise { @@ -127,7 +171,8 @@ async function resolveMcpActivitySessionId( repoPath: string, state: HarnessRuntimeStateService ): Promise { - const cacheKey = normalizeRepoPath(repoPath); + const cacheKey = 'mcp-activity'; + const sessionCache = await sessionCacheForRepo(repoPath); const cached = sessionCache.get(cacheKey); if (cached) { try { From fa4f6e993ff1774aa74a6115acb9435cea240c74 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:54:41 -0300 Subject: [PATCH 19/39] perf: bound semantic freshness discovery --- .../__tests__/boundedFileDiscovery.test.ts | 56 ++++++ .../semantic/__tests__/cacheRetention.test.ts | 21 +++ .../__tests__/codebaseAnalyzer.test.ts | 40 ++-- .../semantic/__tests__/contextCache.test.ts | 20 ++ .../adapters/out/semantic/codebaseAnalyzer.ts | 47 ++--- .../adapters/out/semantic/contextBuilder.ts | 114 ++++++++---- .../adapters/out/semantic/contextCache.ts | 113 ++++++++---- .../discovery/boundedFileDiscovery.ts | 173 ++++++++++++++++++ .../adapters/out/semantic/discovery/index.ts | 1 + src/harness/adapters/out/semantic/index.ts | 1 + 10 files changed, 459 insertions(+), 127 deletions(-) create mode 100644 src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts create mode 100644 src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts create mode 100644 src/harness/adapters/out/semantic/discovery/index.ts diff --git a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts new file mode 100644 index 00000000..7ef49a8b --- /dev/null +++ b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts @@ -0,0 +1,56 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; + +import { discoverBoundedFiles, isBoundedSnapshotFresh } from '../discovery'; + +describe('bounded semantic file discovery', () => { + let repo: string; + + beforeEach(async () => { + repo = await fs.mkdtemp(path.join(os.tmpdir(), 'bounded-discovery-')); + }); + + afterEach(async () => fs.remove(repo)); + + it('stops streaming before materializing repositories larger than the file limit', async () => { + await fs.ensureDir(path.join(repo, 'src')); + for (let index = 0; index < 200; index += 1) { + await fs.writeFile(path.join(repo, 'src', `${String(index).padStart(3, '0')}.ts`), `export const v${index} = ${index};`); + } + const result = await discoverBoundedFiles(repo, { + maxFiles: 10, + maxDirectories: 4, + extensions: ['.ts'], + }); + + expect(result.files).toHaveLength(10); + expect(result.metrics).toMatchObject({ filesSelected: 10, partial: true }); + expect(result.metrics.entriesScanned).toBeLessThan(200); + expect(result.snapshot.files).toHaveLength(10); + }); + + it('ignores irrelevant trees and detects dirty, new, and deleted relevant files', async () => { + await fs.outputFile(path.join(repo, 'src', 'index.ts'), 'export const value = 1;'); + await fs.outputFile(path.join(repo, 'node_modules', 'large.ts'), 'ignored'); + await fs.outputFile(path.join(repo, '.context', 'runtime', 'trace.json'), '{}'); + const result = await discoverBoundedFiles(repo, { + maxFiles: 20, + extensions: ['.ts'], + excludeRelativePrefixes: ['.context/runtime'], + }); + expect(result.files.map(file => path.relative(repo, file))).toEqual(['src/index.ts']); + await expect(isBoundedSnapshotFresh(result.snapshot)).resolves.toMatchObject({ fresh: true }); + + await fs.writeFile(path.join(repo, 'src', 'index.ts'), 'export const value = 22;'); + await expect(isBoundedSnapshotFresh(result.snapshot)).resolves.toMatchObject({ fresh: false }); + + const refreshed = await discoverBoundedFiles(repo, { maxFiles: 20, extensions: ['.ts'] }); + await fs.outputFile(path.join(repo, 'src', 'new.ts'), 'export const added = true;'); + await expect(isBoundedSnapshotFresh(refreshed.snapshot)).resolves.toMatchObject({ fresh: false }); + + const withNew = await discoverBoundedFiles(repo, { maxFiles: 20, extensions: ['.ts'] }); + await fs.remove(path.join(repo, 'src', 'new.ts')); + await expect(isBoundedSnapshotFresh(withNew.snapshot)).resolves.toMatchObject({ fresh: false }); + }); +}); diff --git a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts index fa5fa41d..6e1da5a8 100644 --- a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -82,4 +82,25 @@ describe('semantic cache retention', () => { await analyzer.shutdown(); expect(analyzer.fileAnalysisCacheMetrics().entries).toBe(0); }); + + it('limits semantic fingerprint discovery before materialization and reuses bounded hit signals', async () => { + for (let index = 0; index < 40; index += 1) { + await fs.outputFile(path.join(repo, 'src', `${index}.ts`), `export const value${index} = ${index};`); + } + const builder = new SemanticContextBuilder({ maxFiles: 5 }); + const analyze = jest.fn().mockResolvedValue(emptyContext); + (builder as any).analyzer.analyze = analyze; + + await builder.analyze(repo); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(1); + expect(builder.freshnessMetrics(repo)).toMatchObject({ + discoveries: 1, + filesSelected: 5, + partialDiscoveries: 1, + }); + expect(builder.freshnessMetrics(repo)!.entriesScanned).toBeLessThan(40); + expect(builder.freshnessMetrics(repo)!.signalsChecked).toBeGreaterThan(0); + await builder.shutdown(); + }); }); diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index e1a01ec2..3bf902c1 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -84,6 +84,14 @@ describe('CodebaseAnalyzer', () => { beforeEach(async () => { tempDir = await createTempOutput('dotcontext-analyzer-'); + for (const relative of [ + 'src/services/userService.ts', + 'src/controllers/userController.ts', + 'src/models/user.ts', + 'src/utils/helper.ts', + ]) { + await fs.outputFile(path.join(tempDir, relative), 'export const value = 1;'); + } jest.clearAllMocks(); }); @@ -193,18 +201,8 @@ describe('CodebaseAnalyzer', () => { }); it('should find entry points based on file names', async () => { - // Override glob to return an entry point file - const { glob } = require('glob'); - glob.mockImplementationOnce(async (pattern: string, options: { cwd: string }) => { - if (pattern.includes('.ts')) { - return [ - path.join(options.cwd, 'src', 'index.ts'), - path.join(options.cwd, 'src', 'main.ts'), - path.join(options.cwd, 'src', 'services', 'userService.ts'), - ]; - } - return []; - }); + await fs.outputFile(path.join(tempDir, 'src', 'index.ts'), 'export const entry = true;'); + await fs.outputFile(path.join(tempDir, 'src', 'main.ts'), 'export const main = true;'); const analyzer = new CodebaseAnalyzer({ useLSP: false }); const context = await analyzer.analyze(tempDir); @@ -389,15 +387,16 @@ describe('CodebaseAnalyzer', () => { describe('options handling', () => { it('should respect maxFiles option', async () => { const { glob } = require('glob'); - const manyFiles = Array.from({ length: 100 }, (_, i) => - path.join(tempDir, `file${i}.ts`) - ); - glob.mockImplementationOnce(async () => manyFiles); + for (let index = 0; index < 30; index += 1) { + await fs.outputFile(path.join(tempDir, 'many', `file${index}.ts`), `export const v${index} = ${index};`); + } const analyzer = new CodebaseAnalyzer({ useLSP: false, maxFiles: 10 }); const context = await analyzer.analyze(tempDir); expect(context.stats.totalFiles).toBeLessThanOrEqual(10); + expect(analyzer.discoveryMetrics()).toMatchObject({ filesSelected: 10, partial: true }); + expect(glob).not.toHaveBeenCalled(); }); it('should respect languages option', async () => { @@ -425,14 +424,7 @@ describe('CodebaseAnalyzer', () => { }); it('should respect include patterns', async () => { - const { glob } = require('glob'); - glob.mockImplementationOnce(async (pattern: string, options: { cwd: string }) => { - return [ - path.join(options.cwd, 'src', 'services', 'userService.ts'), - path.join(options.cwd, 'src', 'controllers', 'userController.ts'), - path.join(options.cwd, 'tests', 'testFile.ts'), - ]; - }); + await fs.outputFile(path.join(tempDir, 'tests', 'testFile.ts'), 'export const testOnly = true;'); const analyzer = new CodebaseAnalyzer({ useLSP: false, diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index 8351bd47..adb9e675 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -104,6 +104,26 @@ describe('ContextCache', () => { expect(await cache.get(tempDir, 'compact')).toBeNull(); }); + + it('validates cache hits from bounded signals and ignores irrelevant runtime files', async () => { + await fs.writeFile(path.join(tempDir, 'src', 'index.ts'), 'export const value = 1;'); + const cache = new ContextCache({ watchDirs: ['src', '.context'], freshnessMaxFiles: 4 }); + await cache.set(tempDir, 'compact', 'content'); + const afterSet = cache.freshnessMetrics(); + expect(afterSet).toMatchObject({ discoveries: 1, filesSelected: 1, partialDiscoveries: 0 }); + + expect(await cache.get(tempDir, 'compact')).toBe('content'); + expect(await cache.get(tempDir, 'compact')).toBe('content'); + expect(cache.freshnessMetrics().discoveries).toBe(1); + expect(cache.freshnessMetrics().signalsChecked).toBeGreaterThan(0); + + await fs.outputFile(path.join(tempDir, '.context', 'runtime', 'ignored.json'), '{"ignored":true}'); + expect(await cache.get(tempDir, 'compact')).toBe('content'); + await fs.writeFile(path.join(tempDir, 'src', 'index.ts'), 'export const value = 222;'); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + expect(cache.freshnessMetrics().invalidations).toBe(1); + cache.dispose(); + }); }); describe('invalidation and clearing', () => { diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 06b95266..698ee312 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -5,7 +5,6 @@ * for deeper semantic understanding. */ -import { glob } from 'glob'; import * as path from 'path'; import * as fs from 'fs/promises'; import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; @@ -29,6 +28,7 @@ import { FlowEdge, ExecutionFlow, } from './types'; +import { discoverBoundedFiles, type BoundedDiscoveryMetrics } from './discovery'; const DEFAULT_OPTIONS: Required = { useLSP: false, @@ -47,6 +47,7 @@ export class CodebaseAnalyzer { private options: Required; private readonly fileCacheEntriesExplicit: boolean; private readonly fileCacheBytesExplicit: boolean; + private lastDiscovery?: BoundedDiscoveryMetrics; constructor(options: AnalyzerOptions = {}) { this.fileCacheEntriesExplicit = options.fileAnalysisCacheMaxEntries !== undefined; @@ -100,37 +101,15 @@ export class CodebaseAnalyzer { } private async findCodeFiles(projectPath: string): Promise { - const extensions = Object.keys(LANGUAGE_EXTENSIONS); - const patterns = extensions.map((ext) => `**/*${ext}`); - - const ignorePatterns = this.options.exclude.map((p) => `**/${p}/**`); - - const allFiles: string[] = []; - - for (const pattern of patterns) { - try { - const matches = await glob(pattern, { - cwd: projectPath, - ignore: ignorePatterns, - absolute: true, - nodir: true, - }); - allFiles.push(...matches); - } catch { - // Ignore glob errors for individual patterns - } - } - - // Apply include filter if specified - let filteredFiles = allFiles; - if (this.options.include.length > 0) { - filteredFiles = allFiles.filter((file) => - this.options.include.some((pattern) => file.includes(pattern)) - ); - } - - // Limit number of files - return filteredFiles.slice(0, this.options.maxFiles); + const discovery = await discoverBoundedFiles(projectPath, { + maxFiles: this.options.maxFiles, + maxDirectories: Math.min(10_000, this.options.maxFiles * 2 + 32), + extensions: Object.keys(LANGUAGE_EXTENSIONS), + include: this.options.include, + excludeDirectoryNames: this.options.exclude, + }); + this.lastDiscovery = discovery.metrics; + return discovery.files; } private async analyzeFiles(files: string[]): Promise> { @@ -616,6 +595,10 @@ export class CodebaseAnalyzer { return this.treeSitter.cacheMetrics(); } + discoveryMetrics(): BoundedDiscoveryMetrics | undefined { + return this.lastDiscovery ? { ...this.lastDiscovery } : undefined; + } + /** * Shutdown LSP servers gracefully */ diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index 5703d597..009f7276 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -6,9 +6,6 @@ */ import * as path from 'path'; -import * as fs from 'fs/promises'; -import { createHash } from 'crypto'; -import { glob } from 'glob'; import { CodebaseAnalyzer } from './codebaseAnalyzer'; import type { SemanticContext, @@ -20,6 +17,12 @@ import type { import { DEFAULT_EXCLUDE_PATTERNS } from './types'; import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; +import { + discoverBoundedFiles, + isBoundedSnapshotFresh, + type BoundedDiscoveryMetrics, + type BoundedFreshnessSnapshot, +} from './discovery'; export interface ContextBuilderOptions extends AnalyzerOptions { /** Maximum symbols to include per category */ @@ -36,6 +39,16 @@ export interface ContextBuilderOptions extends AnalyzerOptions { export type ContextFormat = 'documentation' | 'playbook' | 'plan' | 'compact'; +export interface SemanticFreshnessMetrics { + discoveries: number; + filesSelected: number; + directoriesVisited: number; + entriesScanned: number; + partialDiscoveries: number; + signalsChecked: number; + invalidations: number; +} + const DEFAULT_OPTIONS: Required = { useLSP: false, languages: ['typescript', 'javascript', 'python', 'go'], @@ -63,6 +76,8 @@ export class SemanticContextBuilder { diagnostics: string[]; maxEntries: number; maxBytes: number; + snapshot?: BoundedFreshnessSnapshot; + freshness: SemanticFreshnessMetrics; }>(); constructor(options: ContextBuilderOptions = {}) { @@ -76,25 +91,45 @@ export class SemanticContextBuilder { */ async analyze(projectPath: string): Promise { const normalizedProjectPath = path.resolve(projectPath); - const fingerprint = await this.computeProjectFingerprint(normalizedProjectPath); const owner = this.options.cacheEnabled ? await this.semanticCacheForRepo(normalizedProjectPath) : undefined; - if (owner?.fingerprint && owner.fingerprint !== fingerprint) { - owner.cache.clear(); - } - const cached = owner?.cache.get(fingerprint); - if (cached) { - owner!.fingerprint = fingerprint; - return cached; + if (!owner) return this.analyzer.analyze(normalizedProjectPath); + + let discovered: Awaited> | undefined; + if (owner.fingerprint && owner.snapshot) { + const freshness = await isBoundedSnapshotFresh(owner.snapshot); + owner.freshness.signalsChecked += freshness.signalsChecked; + if (freshness.fresh) { + const cached = owner.cache.get(owner.fingerprint); + if (cached) return cached; + } else { + discovered = await this.computeProjectFingerprint(normalizedProjectPath); + this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); + if (discovered.fingerprint === owner.fingerprint) { + owner.snapshot = discovered.snapshot; + const cached = owner.cache.get(owner.fingerprint); + if (cached) return cached; + } else { + owner.cache.clear(); + owner.freshness.invalidations += 1; + } + } } - const context = await this.analyzer.analyze(normalizedProjectPath); - if (owner) { - owner.cache.set(fingerprint, context); - owner.fingerprint = fingerprint; - this.enforceSemanticLimits(owner.maxEntries, owner.maxBytes); + if (!discovered) { + discovered = await this.computeProjectFingerprint(normalizedProjectPath); + this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); } + const fingerprint = discovered.fingerprint; + if (owner.fingerprint && owner.fingerprint !== fingerprint) owner.cache.clear(); + const cached = owner.cache.get(fingerprint); + if (cached) return cached; + const context = await this.analyzer.analyze(normalizedProjectPath); + owner.cache.set(fingerprint, context); + owner.fingerprint = fingerprint; + owner.snapshot = discovered.snapshot; + this.enforceSemanticLimits(owner.maxEntries, owner.maxBytes); return context; } @@ -859,6 +894,11 @@ export class SemanticContextBuilder { return [...(this.semanticCaches.get(path.resolve(projectPath))?.diagnostics ?? [])]; } + freshnessMetrics(projectPath: string): SemanticFreshnessMetrics | undefined { + const metrics = this.semanticCaches.get(path.resolve(projectPath))?.freshness; + return metrics ? { ...metrics } : undefined; + } + private async semanticCacheForRepo(projectPath: string) { for (const [ownerPath, owner] of this.semanticCaches) { if (ownerPath !== projectPath && owner.cache.size === 0) { @@ -885,7 +925,15 @@ export class SemanticContextBuilder { ttlMs: 24 * 60 * 60 * 1000, estimateBytes: context => this.estimateSemanticContextBytes(context), }); - const owner = { cache, signature, diagnostics: loaded.diagnostics, ...limits, fingerprint: undefined as string | undefined }; + const owner = { + cache, + signature, + diagnostics: loaded.diagnostics, + ...limits, + fingerprint: undefined as string | undefined, + snapshot: undefined as BoundedFreshnessSnapshot | undefined, + freshness: { discoveries: 0, filesSelected: 0, directoriesVisited: 0, entriesScanned: 0, partialDiscoveries: 0, signalsChecked: 0, invalidations: 0 }, + }; this.semanticCaches.set(projectPath, owner); return owner; } @@ -906,24 +954,22 @@ export class SemanticContextBuilder { } } - private async computeProjectFingerprint(projectPath: string): Promise { - const extensions = ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go']; - const files = await glob(`**/*.{${extensions.join(',')}}`, { - cwd: projectPath, - absolute: true, - nodir: true, - ignore: this.options.exclude.map((entry) => `**/${entry}/**`), + private async computeProjectFingerprint(projectPath: string) { + return discoverBoundedFiles(projectPath, { + maxFiles: this.options.maxFiles, + maxDirectories: Math.min(10_000, this.options.maxFiles * 2 + 32), + extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.pyw', '.pyi', '.go'], + include: this.options.include, + excludeDirectoryNames: this.options.exclude, }); - const hash = createHash('sha256'); - for (const file of files.sort().slice(0, this.options.maxFiles)) { - try { - const stat = await fs.stat(file); - hash.update(`${path.relative(projectPath, file)}:${stat.size}:${stat.mtimeMs}\n`); - } catch { - hash.update(`${path.relative(projectPath, file)}:missing\n`); - } - } - return hash.digest('hex'); + } + + private recordDiscoveryMetrics(target: SemanticFreshnessMetrics, metrics: BoundedDiscoveryMetrics): void { + target.discoveries += 1; + target.filesSelected += metrics.filesSelected; + target.directoriesVisited += metrics.directoriesVisited; + target.entriesScanned += metrics.entriesScanned; + if (metrics.partial) target.partialDiscoveries += 1; } private estimateSemanticContextBytes(context: SemanticContext): number { diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index c4758445..f392c29a 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -11,12 +11,14 @@ * Thread safety: Node.js is single-threaded, so no mutex needed. */ -import * as fs from 'fs-extra'; import * as path from 'path'; -import { createHash } from 'crypto'; -import { glob } from 'glob'; import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; +import { + discoverBoundedFiles, + isBoundedSnapshotFresh, + type BoundedFreshnessSnapshot, +} from './discovery'; /** * A cached context entry with metadata for invalidation. @@ -24,8 +26,8 @@ import { loadRuntimeRetentionConfig } from '../../../application/retention/runti interface CacheEntry { /** The cached context string */ content: string; - /** Modification time hash of source directories at cache time */ - mtimeHash: string; + freshnessFingerprint?: string; + freshnessSnapshot?: BoundedFreshnessSnapshot; } export interface ContextCacheOptions { @@ -39,12 +41,32 @@ export interface ContextCacheOptions { maxBytes?: number; /** Proactive expiration sweep interval */ sweepIntervalMs?: number; + /** Maximum relevant files selected while establishing freshness (default: 128). */ + freshnessMaxFiles?: number; + /** Maximum directories visited while establishing freshness (default: 256). */ + freshnessMaxDirectories?: number; + /** Optional operation-provided source fingerprint that avoids local discovery. */ + fingerprintProvider?: (repoPath: string) => Promise; } const DEFAULT_TTL_MS = 5 * 60 * 1000; // 5 minutes const DEFAULT_WATCH_DIRS = ['src', '.context', 'lib', 'packages']; const DEFAULT_MAX_ENTRIES = 16; const DEFAULT_MAX_BYTES = 32 * 1024 * 1024; +const CONTEXT_RELEVANT_EXTENSIONS = [ + '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.go', '.rs', '.java', '.kt', '.swift', '.cs', + '.php', '.rb', '.md', '.mdx', '.json', '.yaml', '.yml', '.toml', '.xml', '.graphql', '.gql', '.proto', + '.sql', '.sh', '.bash', '.zsh', '.css', '.scss', '.html', '.vue', '.svelte', +]; + +export interface ContextCacheFreshnessMetrics { + discoveries: number; + filesSelected: number; + directoriesVisited: number; + partialDiscoveries: number; + signalsChecked: number; + invalidations: number; +} export class ContextCache { private readonly caches = new Map(); private readonly watchDirs: string[]; private readonly options: ContextCacheOptions; + private readonly freshness: ContextCacheFreshnessMetrics = { + discoveries: 0, + filesSelected: 0, + directoriesVisited: 0, + partialDiscoveries: 0, + signalsChecked: 0, + invalidations: 0, + }; constructor(options: ContextCacheOptions = {}) { this.options = options; @@ -76,10 +106,10 @@ export class ContextCache { return null; } - // Check directory mtime invalidation - const currentMtimeHash = await this.computeMtimeHash(repoPath); - if (currentMtimeHash !== entry.mtimeHash) { + const fresh = await this.isFresh(repoPath, entry); + if (!fresh) { cache.delete(key); + this.freshness.invalidations += 1; return null; } @@ -96,11 +126,11 @@ export class ContextCache { async set(repoPath: string, contextType: string, content: string, keyOptions?: unknown): Promise { const cache = await this.cacheForRepo(repoPath); const key = this.buildKey(repoPath, contextType, keyOptions); - const mtimeHash = await this.computeMtimeHash(repoPath); + const freshness = await this.captureFreshness(repoPath); cache.set(key, { content, - mtimeHash, + ...freshness, }); const loaded = await loadRuntimeRetentionConfig(repoPath); this.enforceGlobalLimits({ @@ -159,6 +189,10 @@ export class ContextCache { return [...(this.caches.get(this.normalizeRepoPath(repoPath))?.diagnostics ?? [])]; } + freshnessMetrics(): ContextCacheFreshnessMetrics { + return { ...this.freshness }; + } + /** * Build a unique cache key from repo path and context type. */ @@ -201,7 +235,8 @@ export class ContextCache { const cache = new BoundedLruCache({ ...limits, sweepIntervalMs: this.options.sweepIntervalMs, - estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + Buffer.byteLength(entry.mtimeHash), + estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + + Buffer.byteLength(JSON.stringify(entry.freshnessSnapshot ?? entry.freshnessFingerprint ?? '')), }); this.caches.set(normalized, { cache, signature, diagnostics: loaded.diagnostics }); return cache; @@ -223,33 +258,37 @@ export class ContextCache { } } - /** - * Compute a lightweight hash based on directory modification times. - * Uses mtime of watched directories as a fast approximation - * of whether source files have changed. - */ - private async computeMtimeHash(repoPath: string): Promise { - const hash = createHash('sha256'); - - for (const dir of this.watchDirs) { - const dirPath = path.join(repoPath, dir); - try { - const files = await glob('**/*', { - cwd: dirPath, - absolute: true, - nodir: true, - dot: true, - ignore: dir === '.context' ? ['runtime/**', 'cache/**'] : [], - }); - for (const file of files.sort()) { - const stat = await fs.stat(file); - hash.update(`${dir}/${path.relative(dirPath, file)}:${stat.size}:${stat.mtimeMs}\n`); - } - } catch { - hash.update(`${dir}:missing\n`); - } + private async captureFreshness(repoPath: string): Promise> { + if (this.options.fingerprintProvider) { + return { freshnessFingerprint: await this.options.fingerprintProvider(repoPath) }; } + const discovery = await discoverBoundedFiles(repoPath, { + roots: this.watchDirs, + maxFiles: this.options.freshnessMaxFiles ?? 128, + maxDirectories: this.options.freshnessMaxDirectories ?? 256, + extensions: CONTEXT_RELEVANT_EXTENSIONS, + excludeRelativePrefixes: ['.context/runtime', '.context/cache'], + }); + this.freshness.discoveries += 1; + this.freshness.filesSelected += discovery.metrics.filesSelected; + this.freshness.directoriesVisited += discovery.metrics.directoriesVisited; + if (discovery.metrics.partial) this.freshness.partialDiscoveries += 1; + return { freshnessFingerprint: discovery.fingerprint, freshnessSnapshot: discovery.snapshot }; + } - return hash.digest('hex'); + private async isFresh(repoPath: string, entry: CacheEntry): Promise { + if (entry.freshnessFingerprint !== undefined && this.options.fingerprintProvider) { + return await this.options.fingerprintProvider(repoPath) === entry.freshnessFingerprint; + } + if (!entry.freshnessSnapshot) return false; + const result = await isBoundedSnapshotFresh(entry.freshnessSnapshot); + this.freshness.signalsChecked += result.signalsChecked; + if (result.fresh) return true; + const refreshed = await this.captureFreshness(repoPath); + if (refreshed.freshnessFingerprint === entry.freshnessFingerprint && refreshed.freshnessSnapshot) { + entry.freshnessSnapshot = refreshed.freshnessSnapshot; + return true; + } + return false; } } diff --git a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts new file mode 100644 index 00000000..6e8f08ae --- /dev/null +++ b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts @@ -0,0 +1,173 @@ +import { createHash } from 'crypto'; +import * as fs from 'fs/promises'; +import * as path from 'path'; + +export interface BoundedFileSignal { + path: string; + size: number; + mtimeMs: number; +} + +export interface BoundedDirectorySignal { + path: string; + mtimeMs: number; +} + +export interface BoundedFreshnessSnapshot { + rootPath: string; + files: BoundedFileSignal[]; + directories: BoundedDirectorySignal[]; + partial: boolean; +} + +export interface BoundedDiscoveryMetrics { + filesSelected: number; + directoriesVisited: number; + entriesScanned: number; + partial: boolean; + durationMs: number; +} + +export interface BoundedFileDiscoveryResult { + files: string[]; + fingerprint: string; + snapshot: BoundedFreshnessSnapshot; + metrics: BoundedDiscoveryMetrics; +} + +export interface BoundedFileDiscoveryOptions { + roots?: string[]; + maxFiles: number; + maxDirectories?: number; + extensions?: Iterable; + include?: string[]; + excludeDirectoryNames?: Iterable; + excludeRelativePrefixes?: Iterable; +} + +const DEFAULT_EXCLUDED_DIRECTORIES = new Set([ + '.git', 'node_modules', 'dist', 'build', 'coverage', '.next', '.nuxt', 'vendor', '__pycache__', +]); + +function normalizedRelative(root: string, target: string): string { + return path.relative(root, target).split(path.sep).join('/'); +} + +function fingerprintSnapshot(snapshot: BoundedFreshnessSnapshot): string { + const hash = createHash('sha256'); + for (const file of snapshot.files) { + hash.update(`f:${file.path}:${file.size}:${file.mtimeMs}\n`); + } + hash.update(`partial:${snapshot.partial}`); + return hash.digest('hex'); +} + +/** Stream directory entries and stop as soon as either discovery budget is reached. */ +export async function discoverBoundedFiles( + rootPath: string, + options: BoundedFileDiscoveryOptions, +): Promise { + const started = Date.now(); + const root = path.resolve(rootPath); + const maxFiles = Math.max(1, Math.floor(options.maxFiles)); + const maxDirectories = Math.max(1, Math.floor(options.maxDirectories ?? Math.min(10_000, maxFiles * 2 + 32))); + const extensions = options.extensions ? new Set([...options.extensions].map(value => value.toLowerCase())) : undefined; + const excludedNames = new Set([...DEFAULT_EXCLUDED_DIRECTORIES, ...(options.excludeDirectoryNames ?? [])]); + const excludedPrefixes = [...(options.excludeRelativePrefixes ?? [])] + .map(value => value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '')); + const queue = (options.roots?.length ? options.roots : ['.']) + .map(relative => path.resolve(root, relative)) + .filter(candidate => candidate === root || candidate.startsWith(`${root}${path.sep}`)); + const queued = new Set(queue); + const files: BoundedFileSignal[] = []; + const directories: BoundedDirectorySignal[] = []; + let entriesScanned = 0; + let partial = false; + + while (queue.length > 0 && files.length < maxFiles && directories.length < maxDirectories) { + const directoryPath = queue.shift()!; + const relativeDirectory = normalizedRelative(root, directoryPath); + if (excludedPrefixes.some(prefix => relativeDirectory === prefix || relativeDirectory.startsWith(`${prefix}/`))) continue; + try { + const directoryStat = await fs.stat(directoryPath); + directories.push({ path: relativeDirectory || '.', mtimeMs: directoryStat.mtimeMs }); + const directory = await fs.opendir(directoryPath); + for await (const entry of directory) { + entriesScanned += 1; + const absolute = path.join(directoryPath, entry.name); + const relative = normalizedRelative(root, absolute); + if (entry.isDirectory()) { + if (excludedNames.has(entry.name)) continue; + if (excludedPrefixes.some(prefix => relative === prefix || relative.startsWith(`${prefix}/`))) continue; + if (queued.size >= maxDirectories) { + partial = true; + continue; + } + if (!queued.has(absolute)) { + queued.add(absolute); + queue.push(absolute); + } + continue; + } + if (!entry.isFile()) continue; + if (extensions && !extensions.has(path.extname(entry.name).toLowerCase())) continue; + if (options.include?.length && !options.include.some(pattern => relative.includes(pattern))) continue; + try { + const stat = await fs.stat(absolute); + files.push({ path: relative, size: stat.size, mtimeMs: stat.mtimeMs }); + } catch { /* file changed during discovery */ } + if (files.length >= maxFiles) { + partial = true; + break; + } + } + } catch { /* missing or unreadable roots are represented by their absence */ } + } + if (queue.length > 0 || directories.length >= maxDirectories) partial = true; + files.sort((left, right) => left.path.localeCompare(right.path)); + directories.sort((left, right) => left.path.localeCompare(right.path)); + const snapshot: BoundedFreshnessSnapshot = { rootPath: root, files, directories, partial }; + return { + files: files.map(file => path.join(root, file.path)), + fingerprint: fingerprintSnapshot(snapshot), + snapshot, + metrics: { + filesSelected: files.length, + directoriesVisited: directories.length, + entriesScanned, + partial, + durationMs: Date.now() - started, + }, + }; +} + +/** Validate only previously selected signals; no glob, tree walk, or stat-all occurs on a hit. */ +export async function isBoundedSnapshotFresh(snapshot: BoundedFreshnessSnapshot): Promise<{ + fresh: boolean; + signalsChecked: number; + durationMs: number; +}> { + const started = Date.now(); + let signalsChecked = 0; + for (const directory of snapshot.directories) { + try { + const stat = await fs.stat(path.join(snapshot.rootPath, directory.path)); + signalsChecked += 1; + if (stat.mtimeMs !== directory.mtimeMs) return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } catch { + return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } + } + for (const file of snapshot.files) { + try { + const stat = await fs.stat(path.join(snapshot.rootPath, file.path)); + signalsChecked += 1; + if (stat.size !== file.size || stat.mtimeMs !== file.mtimeMs) { + return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } + } catch { + return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } + } + return { fresh: true, signalsChecked, durationMs: Date.now() - started }; +} diff --git a/src/harness/adapters/out/semantic/discovery/index.ts b/src/harness/adapters/out/semantic/discovery/index.ts new file mode 100644 index 00000000..ef85960f --- /dev/null +++ b/src/harness/adapters/out/semantic/discovery/index.ts @@ -0,0 +1 @@ +export * from './boundedFileDiscovery'; diff --git a/src/harness/adapters/out/semantic/index.ts b/src/harness/adapters/out/semantic/index.ts index 0da1e15d..90f9fe6d 100644 --- a/src/harness/adapters/out/semantic/index.ts +++ b/src/harness/adapters/out/semantic/index.ts @@ -5,3 +5,4 @@ export * from './codebaseAnalyzer'; export * from './semanticSnapshotService'; export * from './treeSitter'; export * from './lsp'; +export * from './discovery'; From 89bce54594c8b2721d62fee8f56be70194305f96 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:56:24 -0300 Subject: [PATCH 20/39] fix: bound runtime page bytes --- CHANGELOG.md | 1 + .../docs/en/concepts/harness-runtime.md | 2 +- .../docs/pt-br/concepts/harness-runtime.md | 2 +- .../__tests__/runtimeStateService.test.ts | 63 +++++++++ .../out/runtimeState/runtimeStateService.ts | 127 +++++++++++++++--- .../application/actions/actionService.ts | 12 +- .../contracts/taskContractsService.ts | 67 +++++++-- .../application/datasets/datasetService.ts | 35 ++++- .../__tests__/runtimeHistory.load.test.ts | 27 ++++ .../application/history/runtimeHistory.ts | 25 ++++ .../application/replay/replayService.ts | 49 +++++-- src/harness/index.ts | 2 + 12 files changed, 367 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e48777b6..4b2ab24c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. - Replaced whole-file trace reads and post-materialization replay limits with rotation-aware streaming and source-level event bounds. +- Added aggregate UTF-8 page budgets to runtime history so large valid records cannot multiply count limits into unbounded materialization. ## [1.1.1] - 2026-06-27 diff --git a/docs/src/content/docs/en/concepts/harness-runtime.md b/docs/src/content/docs/en/concepts/harness-runtime.md index 3cb9585f..2e10f656 100644 --- a/docs/src/content/docs/en/concepts/harness-runtime.md +++ b/docs/src/content/docs/en/concepts/harness-runtime.md @@ -120,7 +120,7 @@ Each trace entry looks like this: | `message` | Human-readable description | | `data` | Optional structured payload (sensor results, context, etc.) | -Because the file is **append-only** (`.jsonl`, one JSON object per line), traces are cheap to write and never rewrite earlier entries. The harness reads legacy and rotated segments incrementally. `listTraces` returns a bounded page (100 records by default, 1,000 maximum) with an opaque `nextCursor`, `hasMore`, scan-byte, malformed-line, and duration metadata. Filters support `event`, `level`, `createdAfter`, and `createdBefore`; point reads remain available through their resource-specific actions. +Because the file is **append-only** (`.jsonl`, one JSON object per line), traces are cheap to write and never rewrite earlier entries. The harness reads legacy and rotated segments incrementally. `listTraces` returns a bounded page (100 records by default, 1,000 maximum) with an opaque `nextCursor`, `hasMore`, scan-byte, malformed-line, and duration metadata. Pages also have a 1 MiB aggregate UTF-8 budget by default (16 MiB absolute maximum) and stop before materializing the next over-budget item. `returnedBytes`, `byteBudget`, `byteLimited`, and `oversizedRecordsSkipped` make that behavior explicit. A single valid record that cannot fit is skipped with metadata so cursor continuation cannot loop forever. Filters support `event`, `level`, `createdAfter`, and `createdBefore`; point reads remain available through their resource-specific actions. ::: note Trace `event` values like `sensor.run` are how the harness records [sensor](/concepts/sensors/) results into a session. That's what later lets task contracts check whether required sensors passed, and lets [failure datasets](/concepts/replay-and-datasets/) cluster error-level events. diff --git a/docs/src/content/docs/pt-br/concepts/harness-runtime.md b/docs/src/content/docs/pt-br/concepts/harness-runtime.md index 94b51cb2..5a784ec4 100644 --- a/docs/src/content/docs/pt-br/concepts/harness-runtime.md +++ b/docs/src/content/docs/pt-br/concepts/harness-runtime.md @@ -120,7 +120,7 @@ Cada entrada de trace tem este formato: | `message` | Descrição legível por humanos | | `data` | Payload estruturado opcional (resultados de sensor, contexto, etc.) | -Como o arquivo é **append-only** (`.jsonl`, um objeto JSON por linha), traces são baratos de escrever e nunca reescrevem entradas anteriores. O harness lê segmentos legados e rotacionados de forma incremental. `listTraces` retorna uma página limitada (100 registros por padrão, máximo de 1.000) com `nextCursor` opaco, `hasMore` e metadados de bytes lidos, linhas malformadas e duração. Os filtros aceitos são `event`, `level`, `createdAfter` e `createdBefore`; leituras pontuais continuam disponíveis nas actions específicas de cada recurso. +Como o arquivo é **append-only** (`.jsonl`, um objeto JSON por linha), traces são baratos de escrever e nunca reescrevem entradas anteriores. O harness lê segmentos legados e rotacionados de forma incremental. `listTraces` retorna uma página limitada (100 registros por padrão, máximo de 1.000) com `nextCursor` opaco, `hasMore` e metadados de bytes lidos, linhas malformadas e duração. As páginas também têm orçamento UTF-8 agregado de 1 MiB por padrão (máximo absoluto de 16 MiB) e param antes de materializar o próximo item que excederia o limite. `returnedBytes`, `byteBudget`, `byteLimited` e `oversizedRecordsSkipped` tornam esse comportamento explícito. Um registro válido que não cabe sozinho é ignorado com metadados para que a continuação por cursor nunca entre em loop. Os filtros aceitos são `event`, `level`, `createdAfter` e `createdBefore`; leituras pontuais continuam disponíveis nas actions específicas de cada recurso. ::: note Valores de `event` de trace como `sensor.run` são a forma como o harness registra resultados de [sensores](/pt-br/concepts/sensors/) em uma session. É isso que depois permite que task contracts verifiquem se os sensores requeridos passaram, e que [failure datasets](/pt-br/concepts/replay-and-datasets/) agrupem eventos de nível de erro. diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index a081203f..8ddbce4a 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -197,6 +197,9 @@ describe('HarnessRuntimeStateService', () => { expect(page.items).toHaveLength(1); expect(page.malformedCount).toBe(1); await expect(service.listTracePage(session.id, { limit: 1001 })).rejects.toThrow('between 1 and 1000'); + await expect(service.listTracePage(session.id, { maxBytes: 1023 })).rejects.toThrow('between 1024'); + await expect(service.listTracePage(session.id, { maxBytes: 16 * 1024 * 1024 + 1 })) + .rejects.toThrow('between 1024'); await expect(service.listSessionPage({ limit: 201 })).rejects.toThrow('between 1 and 200'); await expect(service.listTracePage(session.id, { cursor: 'not-a-cursor' })).rejects.toMatchObject({ code: 'INVALID_RUNTIME_HISTORY_CURSOR', @@ -229,6 +232,66 @@ describe('HarnessRuntimeStateService', () => { expect(reverse.scannedBytes).toBe(Buffer.byteLength(contents)); }); + it('limits aggregate trace page bytes and continues every record by cursor', async () => { + const session = await service.createSession({ name: 'byte-pages' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const records = Array.from({ length: 100 }, (_, index) => ({ + id: `large-${index}`, + sessionId: session.id, + level: 'info', + event: 'large.page', + message: `record-${index}`, + createdAt: new Date(1_700_000_000_000 + index).toISOString(), + data: { index, payload: 'x'.repeat(64 * 1024) }, + })); + await fs.writeFile(traceFile, `${records.map(record => JSON.stringify(record)).join('\n')}\n`); + + const seen: string[] = []; + let cursor: string | undefined; + do { + const page = await service.listTracePage(session.id, { + direction: 'oldest', + limit: 100, + maxBytes: 256 * 1024, + cursor, + }); + expect(page.returnedBytes).toBeLessThanOrEqual(256 * 1024); + expect(page.items.length).toBeLessThan(100); + seen.push(...page.items.map(record => record.id)); + cursor = page.nextCursor; + } while (cursor); + + expect(seen).toEqual(records.map(record => record.id)); + }); + + it('skips a single valid record larger than the byte budget without looping', async () => { + const session = await service.createSession({ name: 'single-oversize' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const oversized = { + id: 'oversized-valid', sessionId: session.id, level: 'info', event: 'valid', + message: 'x'.repeat(2048), createdAt: '2026-01-01T00:00:00.000Z', + }; + const small = { + id: 'small', sessionId: session.id, level: 'info', event: 'valid', + message: 'small', createdAt: '2026-01-02T00:00:00.000Z', + }; + await fs.writeFile(traceFile, `${JSON.stringify(oversized)}\n${JSON.stringify(small)}\n`); + + const page = await service.listTracePage(session.id, { + direction: 'oldest', + limit: 10, + maxBytes: 1024, + }); + + expect(page.items.map(record => record.id)).toEqual(['small']); + expect(page).toMatchObject({ + byteLimited: true, + oversizedRecordsSkipped: 1, + returnedBytes: expect.any(Number), + }); + expect(page.returnedBytes).toBeLessThanOrEqual(1024); + }); + it('maintains a latest sensor summary without scanning trace history', async () => { const session = await service.createSession({ name: 'sensor-summary' }); await service.appendTrace(session.id, { level: 'error', event: 'sensor.run', message: 'first', data: { run: { sensorId: 'tests', status: 'failed', createdAt: '2025-01-01' } } }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 9886df23..4a7d6e6e 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -18,10 +18,12 @@ import { loadHookTracePolicy, } from '../../../application/hooks/hookTracePolicy'; import { + boundedPageBytes, boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, + serializedHistoryItemBytes, RuntimeHistoryCursorError, type RuntimeHistoryDirection, type RuntimeHistoryPage, @@ -612,39 +614,74 @@ export class HarnessRuntimeStateService { async listSessionPage(query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); const limit = boundedLimit(query.limit, 50, 200, 'sessions'); + const byteBudget = boundedPageBytes(query.maxBytes, 'sessions'); const direction = query.direction ?? 'newest'; const binding = queryBinding({ direction }); const boundary = decodeHistoryCursor<{ updatedAt: string; id: string }>(query.cursor, 'sessions', binding); await this.ensureLayout(); - const selected: HarnessSessionRecord[] = []; + const selected: Array<{ file: string; updatedAt: string; id: string; bytes: number }> = []; let recordsScanned = 0; + let eligibleRecords = 0; + let oversizedRecordsSkipped = 0; const directory = await nodeFs.opendir(this.sessionsPath); for await (const entry of directory) { if (!entry.isDirectory()) continue; try { - const session = await fs.readJson(this.sessionFile(entry.name)) as HarnessSessionRecord; + const file = this.sessionFile(entry.name); + const stat = await nodeFs.stat(file); + if (stat.size + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + const session = JSON.parse(await nodeFs.readFile(file, 'utf8')) as HarnessSessionRecord; recordsScanned += 1; const key = `${session.updatedAt}\0${session.id}`; const boundaryKey = boundary ? `${boundary.updatedAt}\0${boundary.id}` : undefined; if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; - selected.push(session); + const bytes = serializedHistoryItemBytes(session); + if (bytes + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + eligibleRecords += 1; + selected.push({ file, updatedAt: session.updatedAt, id: session.id, bytes }); selected.sort((a, b) => direction === 'newest' ? b.updatedAt.localeCompare(a.updatedAt) || b.id.localeCompare(a.id) : a.updatedAt.localeCompare(b.updatedAt) || a.id.localeCompare(b.id)); if (selected.length > limit + 1) selected.pop(); } catch { /* skip corrupt legacy records */ } } - const hasMore = selected.length > limit; - const items = selected.slice(0, limit); - const last = items.at(-1); + const chosen: typeof selected = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected) { + if (chosen.length === limit) break; + const candidateTotal = returnedBytes + candidate.bytes + (chosen.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + byteLimited = true; + break; + } + chosen.push(candidate); + returnedBytes = candidateTotal; + } + const items: HarnessSessionRecord[] = []; + for (const candidate of chosen) { + items.push(JSON.parse(await nodeFs.readFile(candidate.file, 'utf8')) as HarnessSessionRecord); + } + const hasMore = eligibleRecords > chosen.length; + const last = chosen.at(-1); return { items, nextCursor: hasMore && last ? encodeHistoryCursor('sessions', binding, { updatedAt: last.updatedAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, cursorVersion: 1, - partial: hasMore, + partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started, }; } @@ -724,23 +761,38 @@ export class HarnessRuntimeStateService { async listArtifactPage(sessionId: string, query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); const limit = boundedLimit(query.limit, 50, 200, 'artifacts'); + const byteBudget = boundedPageBytes(query.maxBytes, 'artifacts'); const direction = query.direction ?? 'newest'; const binding = queryBinding({ sessionId, direction }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'artifacts', binding); const dir = this.layout.sessionArtifactsDir(sessionId); - const selected: HarnessArtifactRecord[] = []; + const selected: Array<{ file: string; createdAt: string; id: string; bytes: number }> = []; let recordsScanned = 0; + let eligibleRecords = 0; + let oversizedRecordsSkipped = 0; if (await fs.pathExists(dir)) { const directory = await nodeFs.opendir(dir); for await (const entry of directory) { if (!entry.isFile() || !entry.name.endsWith('.json')) continue; try { - const artifact = await fs.readJson(path.join(dir, entry.name)) as HarnessArtifactRecord; + const file = path.join(dir, entry.name); + const stat = await nodeFs.stat(file); + if (stat.size + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + const artifact = JSON.parse(await nodeFs.readFile(file, 'utf8')) as HarnessArtifactRecord; recordsScanned += 1; const key = `${artifact.createdAt}\0${artifact.id}`; const boundaryKey = boundary ? `${boundary.createdAt}\0${boundary.id}` : undefined; if (boundaryKey && (direction === 'newest' ? key >= boundaryKey : key <= boundaryKey)) continue; - selected.push(artifact); + const bytes = serializedHistoryItemBytes(artifact); + if (bytes + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + eligibleRecords += 1; + selected.push({ file, createdAt: artifact.createdAt, id: artifact.id, bytes }); selected.sort((a, b) => direction === 'newest' ? b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id) : a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)); @@ -748,17 +800,37 @@ export class HarnessRuntimeStateService { } catch { /* skip corrupt legacy records */ } } } - const hasMore = selected.length > limit; - const items = selected.slice(0, limit); - const last = items.at(-1); + const chosen: typeof selected = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected) { + if (chosen.length === limit) break; + const candidateTotal = returnedBytes + candidate.bytes + (chosen.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + byteLimited = true; + break; + } + chosen.push(candidate); + returnedBytes = candidateTotal; + } + const items: HarnessArtifactRecord[] = []; + for (const candidate of chosen) { + items.push(JSON.parse(await nodeFs.readFile(candidate.file, 'utf8')) as HarnessArtifactRecord); + } + const hasMore = eligibleRecords > chosen.length; + const last = chosen.at(-1); return { items, nextCursor: hasMore && last ? encodeHistoryCursor('artifacts', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, cursorVersion: 1, - partial: hasMore, + partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started, }; } @@ -784,6 +856,7 @@ export class HarnessRuntimeStateService { async listTracePage(sessionId: string, query: HarnessTracePageQuery = {}): Promise> { const started = Date.now(); const limit = boundedLimit(query.limit, 100, 1000, 'traces'); + const byteBudget = boundedPageBytes(query.maxBytes, 'traces'); const direction: RuntimeHistoryDirection = query.direction ?? 'newest'; const filters = { sessionId, direction, event: query.event, level: query.level, createdAfter: query.createdAfter, createdBefore: query.createdBefore }; const binding = queryBinding(filters); @@ -807,6 +880,9 @@ export class HarnessRuntimeStateService { let recordsScanned = 0; let scannedBytes = 0; let malformedCount = 0; + let returnedBytes = 2; + let oversizedRecordsSkipped = 0; + let byteLimited = false; let hasMore = false; let nextPosition: TraceCursorPosition | undefined; outer: for (let index = startIndex; index < files.length; index += 1) { @@ -825,7 +901,24 @@ export class HarnessRuntimeStateService { if (query.createdAfter && trace.createdAt <= query.createdAfter) continue; if (query.createdBefore && trace.createdAt >= query.createdBefore) continue; if (items.length === limit) { hasMore = true; break outer; } + const traceBytes = serializedHistoryItemBytes(trace); + const candidateBytes = returnedBytes + traceBytes + (items.length > 0 ? 1 : 0); + if (candidateBytes > byteBudget) { + if (items.length > 0) { + hasMore = true; + byteLimited = true; + break outer; + } + // A record larger than an otherwise empty page can never be returned + // under this budget. Consume it, report the typed skip, and continue + // so a cursor can never loop forever on the same valid line. + oversizedRecordsSkipped += 1; + byteLimited = true; + nextPosition = { file: path.basename(file), offset: line.nextOffset, fingerprint }; + continue; + } items.push(trace); + returnedBytes = candidateBytes; nextPosition = { file: path.basename(file), offset: line.nextOffset, fingerprint }; } if (items.length > 0) nextPosition = { file: path.basename(files[index + 1] ?? file), offset: direction === 'newest' ? Number.MAX_SAFE_INTEGER : 0, fingerprint }; @@ -837,9 +930,13 @@ export class HarnessRuntimeStateService { recordsReturned: items.length, recordsScanned, scannedBytes, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, malformedCount, cursorVersion: 1, - partial: hasMore, + partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started, }; } diff --git a/src/harness/application/actions/actionService.ts b/src/harness/application/actions/actionService.ts index 70b27c45..67507c47 100644 --- a/src/harness/application/actions/actionService.ts +++ b/src/harness/application/actions/actionService.ts @@ -84,6 +84,7 @@ export interface HarnessActionInput { replayId?: string; includePayloads?: boolean; maxEvents?: number; + maxBytes?: number; datasetId?: string; sessionIds?: string[]; includeSuccessfulSessions?: boolean; @@ -202,7 +203,7 @@ export class HarnessActionService { }), }; case 'listSessions': - const sessionPage = await this.executionService.listSessionPage({ limit: params.limit, cursor: params.cursor, direction: params.direction }); + const sessionPage = await this.executionService.listSessionPage({ limit: params.limit, cursor: params.cursor, direction: params.direction, maxBytes: params.maxBytes }); const { items: sessions, ...sessionPagination } = sessionPage; return { success: true, @@ -225,7 +226,7 @@ export class HarnessActionService { }), }; case 'listTraces': - const tracePage = await this.executionService.listTracePage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction, event: params.event, level: params.level, createdAfter: params.createdAfter, createdBefore: params.createdBefore }); + const tracePage = await this.executionService.listTracePage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction, event: params.event, level: params.level, createdAfter: params.createdAfter, createdBefore: params.createdBefore, maxBytes: params.maxBytes }); const { items: traces, ...tracePagination } = tracePage; return { success: true, @@ -244,7 +245,7 @@ export class HarnessActionService { }), }; case 'listArtifacts': - const artifactPage = await this.executionService.listArtifactPage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction }); + const artifactPage = await this.executionService.listArtifactPage(params.sessionId!, { limit: params.limit, cursor: params.cursor, direction: params.direction, maxBytes: params.maxBytes }); const { items: artifacts, ...artifactPagination } = artifactPage; return { success: true, @@ -364,10 +365,11 @@ export class HarnessActionService { replay: await this.executionService.replaySession(params.sessionId!, { includePayloads: params.includePayloads, maxEvents: params.maxEvents, + maxBytes: params.maxBytes, }), }; case 'listReplays': - const replayPage = await this.executionService.listReplayPage({ limit: params.limit, cursor: params.cursor, sessionId: params.sessionId }); + const replayPage = await this.executionService.listReplayPage({ limit: params.limit, cursor: params.cursor, sessionId: params.sessionId, maxBytes: params.maxBytes }); const { items: replays, ...replayPagination } = replayPage; return { success: true, @@ -390,7 +392,7 @@ export class HarnessActionService { }), }; case 'listDatasets': - const datasetPage = await this.executionService.listDatasetPage({ limit: params.limit, cursor: params.cursor }); + const datasetPage = await this.executionService.listDatasetPage({ limit: params.limit, cursor: params.cursor, maxBytes: params.maxBytes }); const { items: datasets, ...datasetPagination } = datasetPage; return { success: true, diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index 2029e1c5..cb318cd5 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -16,7 +16,12 @@ import type { HarnessRuntimeStatePort, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { HarnessSensorRun } from '../sensors/sensorsService'; -import { boundedLimit } from '../history/runtimeHistory'; +import { + boundedLimit, + boundedPageBytes, + MAX_RUNTIME_HISTORY_PAGE_BYTES, + serializedHistoryItemBytes, +} from '../history/runtimeHistory'; /** * Structured artifact requirement. @@ -190,6 +195,10 @@ export interface HarnessHandoffContract { export interface BoundedSessionContracts { items: T[]; total: number; + returnedBytes: number; + byteBudget: number; + byteLimited: boolean; + oversizedRecordsSkipped: number; } export interface HarnessTaskCompletionResult { @@ -303,12 +312,14 @@ export class HarnessTaskContractsService { async listSessionTaskContracts( sessionId: string, - limit = 100 + limit = 100, + maxBytes?: number ): Promise> { return this.listBoundedSessionContracts( this.tasksPath, sessionId, - boundedLimit(limit, 100, 1000, 'session task contracts') + boundedLimit(limit, 100, 1000, 'session task contracts'), + boundedPageBytes(maxBytes, 'session task contracts') ); } @@ -389,31 +400,45 @@ export class HarnessTaskContractsService { async listSessionHandoffContracts( sessionId: string, - limit = 100 + limit = 100, + maxBytes?: number ): Promise> { return this.listBoundedSessionContracts( this.handoffsPath, sessionId, - boundedLimit(limit, 100, 1000, 'session handoff contracts') + boundedLimit(limit, 100, 1000, 'session handoff contracts'), + boundedPageBytes(maxBytes, 'session handoff contracts') ); } private async listBoundedSessionContracts( directoryPath: string, sessionId: string, - limit: number + limit: number, + byteBudget: number ): Promise> { await this.ensureLayout(); - const selected: T[] = []; + const selected: Array<{ file: string; createdAt: string; id: string; bytes: number }> = []; let total = 0; + let oversizedRecordsSkipped = 0; const directory = await fs.opendir(directoryPath); for await (const entry of directory) { if (!entry.isFile() || !entry.name.endsWith('.json')) continue; try { - const contract = await fs.readJson(path.join(directoryPath, entry.name)) as T; + const file = path.join(directoryPath, entry.name); + if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { + oversizedRecordsSkipped += 1; + continue; + } + const contract = await fs.readJson(file) as T; if (contract.sessionId !== sessionId) continue; total += 1; - selected.push(contract); + const bytes = serializedHistoryItemBytes(contract); + if (bytes + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + selected.push({ file, createdAt: contract.createdAt, id: contract.id, bytes }); selected.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id) ); @@ -422,7 +447,29 @@ export class HarnessTaskContractsService { // A malformed unrelated contract must not make replay unavailable. } } - return { items: selected, total }; + const chosen: typeof selected = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected) { + if (chosen.length === limit) break; + const candidateTotal = returnedBytes + candidate.bytes + (chosen.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + byteLimited = true; + break; + } + chosen.push(candidate); + returnedBytes = candidateTotal; + } + const items: T[] = []; + for (const candidate of chosen) items.push(await fs.readJson(candidate.file) as T); + return { + items, + total, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, + }; } async evaluateTaskCompletion(taskId: string, sessionId?: string): Promise { diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index 5f3b32e1..77eabc3b 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -11,7 +11,7 @@ import { import { HarnessReplayService, type HarnessReplayRecord } from '../replay/replayService'; import { HarnessSensorsService } from '../sensors/sensorsService'; import { HarnessTaskContractsService } from '../contracts/taskContractsService'; -import { boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; +import { boundedPageBytes, boundedLimit, decodeHistoryCursor, encodeHistoryCursor, MAX_RUNTIME_HISTORY_PAGE_BYTES, queryBinding, serializedHistoryItemBytes, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; export type HarnessFailureKind = 'sensor' | 'task' | 'session' | 'trace'; @@ -359,16 +359,23 @@ export class HarnessDatasetService { async listDatasetPage(query: RuntimeHistoryQuery = {}): Promise> { const started = Date.now(); const limit = boundedLimit(query.limit, 25, 100, 'dataset summaries'); + const byteBudget = boundedPageBytes(query.maxBytes, 'dataset summaries'); const binding = queryBinding({ resource: 'datasets' }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'datasets', binding); await this.ensureLayout(); const selected: HarnessDatasetSummary[] = []; let recordsScanned = 0; + let oversizedRecordsSkipped = 0; const directory = await fs.opendir(this.datasetsPath); for await (const entry of directory) { if (!entry.isFile() || !entry.name.endsWith('.json')) continue; try { - const dataset = await fs.readJson(path.join(this.datasetsPath, entry.name)) as HarnessFailureDataset; + const file = path.join(this.datasetsPath, entry.name); + if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { + oversizedRecordsSkipped += 1; + continue; + } + const dataset = await fs.readJson(file) as HarnessFailureDataset; recordsScanned += 1; const key = `${dataset.createdAt}\0${dataset.id}`; if (boundary && key >= `${boundary.createdAt}\0${boundary.id}`) continue; @@ -377,10 +384,28 @@ export class HarnessDatasetService { if (selected.length > limit + 1) selected.pop(); } catch { /* skip corrupt records */ } } - const hasMore = selected.length > limit; - const items = selected.slice(0, limit); + const items: HarnessDatasetSummary[] = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected.slice(0, limit + 1)) { + if (items.length === limit) break; + const bytes = serializedHistoryItemBytes(candidate); + const candidateTotal = returnedBytes + bytes + (items.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + if (items.length > 0) { + byteLimited = true; + break; + } + oversizedRecordsSkipped += 1; + byteLimited = true; + continue; + } + items.push(candidate); + returnedBytes = candidateTotal; + } + const hasMore = selected.length > items.length; const last = items.at(-1); - return { items, nextCursor: hasMore && last ? encodeHistoryCursor('datasets', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, cursorVersion: 1, partial: hasMore, durationMs: Date.now() - started }; + return { items, nextCursor: hasMore && last ? encodeHistoryCursor('datasets', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, returnedBytes, byteBudget, byteLimited, oversizedRecordsSkipped, cursorVersion: 1, partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started }; } async getDataset(datasetId: string): Promise { diff --git a/src/harness/application/history/__tests__/runtimeHistory.load.test.ts b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts index 500dcc97..276ea1e1 100644 --- a/src/harness/application/history/__tests__/runtimeHistory.load.test.ts +++ b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts @@ -38,4 +38,31 @@ loadDescribe('runtime history load acceptance', () => { expect(page.hasMore).toBe(true); expect(page.recordsScanned).toBe(1000); }); + + it('keeps a page of 100 valid near-limit records within the byte and RSS budgets', async () => { + const state = new HarnessRuntimeStateService({ repoPath: tempDir }); + const session = await state.createSession({ name: 'large-records' }); + const traceFile = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'trace.jsonl'); + const records = Array.from({ length: 100 }, (_, index) => JSON.stringify({ + id: `large-${index}`, + sessionId: session.id, + level: 'info', + event: 'large', + message: `large-${index}`, + createdAt: new Date(1_700_000_000_000 + index).toISOString(), + data: { payload: 'x'.repeat(900 * 1024) }, + })); + await fs.writeFile(traceFile, `${records.join('\n')}\n`); + global.gc?.(); + const before = process.memoryUsage().rss; + + const page = await state.listTracePage(session.id, { limit: 100, direction: 'oldest' }); + + global.gc?.(); + expect(page.items).toHaveLength(1); + expect(page.returnedBytes).toBeLessThanOrEqual(page.byteBudget); + expect(page.byteLimited).toBe(true); + expect(page.nextCursor).toBeDefined(); + expect(process.memoryUsage().rss - before).toBeLessThan(32 * 1024 * 1024); + }); }); diff --git a/src/harness/application/history/runtimeHistory.ts b/src/harness/application/history/runtimeHistory.ts index dd2170fe..c1aa63c3 100644 --- a/src/harness/application/history/runtimeHistory.ts +++ b/src/harness/application/history/runtimeHistory.ts @@ -2,10 +2,14 @@ import { createHash } from 'crypto'; export type RuntimeHistoryDirection = 'oldest' | 'newest'; +export const DEFAULT_RUNTIME_HISTORY_PAGE_BYTES = 1024 * 1024; +export const MAX_RUNTIME_HISTORY_PAGE_BYTES = 16 * 1024 * 1024; + export interface RuntimeHistoryQuery { limit?: number; cursor?: string; direction?: RuntimeHistoryDirection; + maxBytes?: number; } export interface RuntimeHistoryPage { @@ -15,6 +19,10 @@ export interface RuntimeHistoryPage { recordsReturned: number; recordsScanned: number; scannedBytes?: number; + returnedBytes: number; + byteBudget: number; + byteLimited: boolean; + oversizedRecordsSkipped: number; malformedCount?: number; cursorVersion: 1; partial: boolean; @@ -67,3 +75,20 @@ export function boundedLimit(value: number | undefined, defaultLimit: number, ma } return limit; } + +export function boundedPageBytes( + value: number | undefined, + resource: string, + defaultBytes = DEFAULT_RUNTIME_HISTORY_PAGE_BYTES, + maximumBytes = MAX_RUNTIME_HISTORY_PAGE_BYTES +): number { + const bytes = value ?? defaultBytes; + if (!Number.isInteger(bytes) || bytes < 1024 || bytes > maximumBytes) { + throw new RangeError(`${resource} maxBytes must be an integer between 1024 and ${maximumBytes}`); + } + return bytes; +} + +export function serializedHistoryItemBytes(value: unknown): number { + return Buffer.byteLength(JSON.stringify(value), 'utf8'); +} diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index 3f427d39..0b690943 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -18,10 +18,13 @@ import { type HarnessTaskContract, } from '../contracts/taskContractsService'; import { + boundedPageBytes, boundedLimit, decodeHistoryCursor, encodeHistoryCursor, queryBinding, + serializedHistoryItemBytes, + MAX_RUNTIME_HISTORY_PAGE_BYTES, type RuntimeHistoryPage, type RuntimeHistoryQuery, } from '../history/runtimeHistory'; @@ -74,6 +77,7 @@ export interface HarnessReplayServiceOptions { export interface ReplaySessionOptions { includePayloads?: boolean; maxEvents?: number; + maxBytes?: number; } export interface HarnessReplaySummary { @@ -160,11 +164,15 @@ export class HarnessReplayService { const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); const session = await this.stateService.getSession(sessionId); const [tracePage, artifactPage, allSensorRuns, taskScan, handoffScan] = await Promise.all([ - this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest' }), - this.stateService.listArtifactPage(sessionId, { limit: Math.min(maxEvents, 200), direction: 'oldest' }), + this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest', maxBytes: options.maxBytes }), + this.stateService.listArtifactPage(sessionId, { limit: Math.min(maxEvents, 200), direction: 'oldest', maxBytes: options.maxBytes }), this.sensorsService.getSessionSensorRuns(sessionId), - this.contractsService.listSessionTaskContracts(sessionId, maxEvents), - this.contractsService.listSessionHandoffContracts(sessionId, maxEvents), + options.maxBytes === undefined + ? this.contractsService.listSessionTaskContracts(sessionId, maxEvents) + : this.contractsService.listSessionTaskContracts(sessionId, maxEvents, options.maxBytes), + options.maxBytes === undefined + ? this.contractsService.listSessionHandoffContracts(sessionId, maxEvents) + : this.contractsService.listSessionHandoffContracts(sessionId, maxEvents, options.maxBytes), ]); const traces = tracePage.items; @@ -339,16 +347,23 @@ export class HarnessReplayService { async listReplayPage(query: RuntimeHistoryQuery & { sessionId?: string } = {}): Promise> { const started = Date.now(); const limit = boundedLimit(query.limit, 25, 100, 'replay summaries'); + const byteBudget = boundedPageBytes(query.maxBytes, 'replay summaries'); const binding = queryBinding({ sessionId: query.sessionId }); const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(query.cursor, 'replays', binding); await this.ensureLayout(); const selected: HarnessReplaySummary[] = []; let recordsScanned = 0; + let oversizedRecordsSkipped = 0; const directory = await fs.opendir(this.replaysPath); for await (const entry of directory) { if (!entry.isFile() || !entry.name.endsWith('.json')) continue; try { - const replay = await fs.readJson(path.join(this.replaysPath, entry.name)) as HarnessReplayRecord; + const file = path.join(this.replaysPath, entry.name); + if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { + oversizedRecordsSkipped += 1; + continue; + } + const replay = await fs.readJson(file) as HarnessReplayRecord; recordsScanned += 1; if (query.sessionId && replay.sessionId !== query.sessionId) continue; const key = `${replay.createdAt}\0${replay.id}`; @@ -358,10 +373,28 @@ export class HarnessReplayService { if (selected.length > limit + 1) selected.pop(); } catch { /* skip corrupt records */ } } - const hasMore = selected.length > limit; - const items = selected.slice(0, limit); + const items: HarnessReplaySummary[] = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected.slice(0, limit + 1)) { + if (items.length === limit) break; + const bytes = serializedHistoryItemBytes(candidate); + const candidateTotal = returnedBytes + bytes + (items.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + if (items.length > 0) { + byteLimited = true; + break; + } + oversizedRecordsSkipped += 1; + byteLimited = true; + continue; + } + items.push(candidate); + returnedBytes = candidateTotal; + } + const hasMore = selected.length > items.length; const last = items.at(-1); - return { items, nextCursor: hasMore && last ? encodeHistoryCursor('replays', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, cursorVersion: 1, partial: hasMore, durationMs: Date.now() - started }; + return { items, nextCursor: hasMore && last ? encodeHistoryCursor('replays', binding, { createdAt: last.createdAt, id: last.id }) : undefined, hasMore, recordsReturned: items.length, recordsScanned, returnedBytes, byteBudget, byteLimited, oversizedRecordsSkipped, cursorVersion: 1, partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started }; } async getReplay(replayId: string): Promise { diff --git a/src/harness/index.ts b/src/harness/index.ts index 2b61d1aa..156e9bba 100644 --- a/src/harness/index.ts +++ b/src/harness/index.ts @@ -180,6 +180,8 @@ export { type HarnessFailureDataset, type HarnessDatasetSummary, HarnessRuntimeRetentionService, + DEFAULT_RUNTIME_HISTORY_PAGE_BYTES, + MAX_RUNTIME_HISTORY_PAGE_BYTES, RuntimeHistoryCursorError, type RuntimeHistoryDirection, type RuntimeHistoryQuery, From 5e245f0c914c0b8aaf19af21682dfc7b8ea5eae8 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:57:19 -0300 Subject: [PATCH 21/39] perf: bound semantic repository discovery --- .../__tests__/codebaseAnalyzer.test.ts | 22 +- .../__tests__/semanticSnapshotService.test.ts | 55 ++++ .../adapters/out/semantic/codebaseAnalyzer.ts | 115 ++++--- .../out/semantic/semanticSnapshotService.ts | 310 ++++++++---------- .../context/__tests__/contextTools.test.ts | 32 +- .../application/context/contextTools.ts | 14 +- .../documentation/documentationGenerator.ts | 2 +- src/types.ts | 23 ++ src/utils/__tests__/fileMapper.test.ts | 96 ++++++ src/utils/fileMapper.ts | 250 ++++++++++---- 10 files changed, 623 insertions(+), 296 deletions(-) create mode 100644 src/utils/__tests__/fileMapper.test.ts diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index 0d030309..ca4bfefd 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -60,20 +60,30 @@ jest.mock('../lsp/lspLayer', () => ({ })); // Mock glob -jest.mock('glob', () => ({ - glob: jest.fn().mockImplementation(async (pattern: string, options: { cwd: string }) => { +jest.mock('glob', () => { + const glob = jest.fn().mockImplementation(async (pattern: string, options: { cwd: string }) => { // Return mock files based on the pattern - if (pattern.includes('.ts')) { + if (String(pattern).includes('ts')) { return [ path.join(options.cwd, 'src', 'services', 'userService.ts'), path.join(options.cwd, 'src', 'controllers', 'userController.ts'), path.join(options.cwd, 'src', 'models', 'user.ts'), path.join(options.cwd, 'src', 'utils', 'helper.ts'), + path.join(options.cwd, 'src', 'index.ts'), + path.join(options.cwd, 'src', 'main.ts'), ]; } return []; - }), -})); + }); + const globStream = jest.fn((pattern: string, options: { cwd: string }) => { + const iterator = (async function* () { + for (const file of await glob(pattern, options)) yield file; + })() as any; + iterator.destroy = jest.fn(); + return iterator; + }); + return { glob, globStream }; +}); function createTempOutput(prefix: string): Promise { return fs.mkdtemp(path.join(os.tmpdir(), prefix)); @@ -333,7 +343,7 @@ describe('CodebaseAnalyzer', () => { // Override glob to return an entry point file const { glob } = require('glob'); glob.mockImplementationOnce(async (pattern: string, options: { cwd: string }) => { - if (pattern.includes('.ts')) { + if (String(pattern).includes('ts')) { return [ path.join(options.cwd, 'src', 'index.ts'), path.join(options.cwd, 'src', 'main.ts'), diff --git a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts index ea174b2c..512402c5 100644 --- a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts @@ -1,4 +1,5 @@ import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -31,6 +32,7 @@ describe('SemanticSnapshotService', () => { }); afterEach(async () => { + jest.restoreAllMocks(); await fs.remove(tempDir); }); @@ -202,6 +204,59 @@ describe('SemanticSnapshotService', () => { expect(cache.size).toBe(0); }); + it('stats but never opens an oversized sparse source file', async () => { + const hugePath = path.join(repoPath, 'src', 'huge.ts'); + const handle = await nativeFs.open(hugePath, 'w'); + await handle.truncate(3 * 1024 * 1024); + await handle.close(); + const discovery = await new FileMapper().mapRepository(repoPath); + expect(discovery.files.some((file) => file.path === hugePath)).toBe(false); + expect(discovery.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ file: hugePath, reason: 'file-too-large' }), + ])); + + // Defense in depth: even a caller-provided discovery containing the huge + // record is checked before the content stream is opened. + const stats = await fs.stat(hugePath); + discovery.files.push({ + path: hugePath, + relativePath: 'src/huge.ts', + extension: '.ts', + size: stats.size, + type: 'file', + }); + const open = jest.spyOn(nativeFs, 'open'); + const result = await new SemanticSnapshotService() + .captureRepoFingerprintWithMetrics(repoPath, discovery); + + expect(open.mock.calls.some(([file]) => file === hugePath)).toBe(false); + expect(result.partial).toBe(true); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ file: hugePath, reason: 'file-too-large' }), + ])); + }); + + it('stops fingerprint content reads at the aggregate byte budget', async () => { + await fs.remove(path.join(repoPath, 'package.json')); + await fs.remove(path.join(repoPath, 'src', 'auth.ts')); + await fs.writeFile(path.join(repoPath, 'src', 'a.ts'), '123456'); + await fs.writeFile(path.join(repoPath, 'src', 'b.ts'), '123456'); + await fs.remove(path.join(repoPath, 'src', 'index.ts')); + const discovery = await new FileMapper().mapRepository(repoPath); + const result = await new SemanticSnapshotService( + true, + new SemanticFingerprintCache(), + { maxTotalBytes: 10, maxFileBytes: 100 } + ).captureRepoFingerprintWithMetrics(repoPath, discovery); + + expect(result.contentReads).toBe(1); + expect(result.bytesRead).toBe(6); + expect(result.partial).toBe(true); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ reason: 'total-byte-limit' }), + ])); + }); + it('bounds shared cache entries, expires them, and supports explicit disposal', () => { let now = 1_000; const nowSpy = jest.spyOn(Date, 'now').mockImplementation(() => now); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 38945e1b..3219f939 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -5,9 +5,10 @@ * for deeper semantic understanding. */ -import { glob } from 'glob'; import * as path from 'path'; import * as fs from 'fs/promises'; +import type { FileInfo } from '../../../../types'; +import { FileMapper } from '../../../../utils/fileMapper'; import { TreeSitterLayer } from './treeSitter/treeSitterLayer'; import { LSPLayer } from './lsp/lspLayer'; import { @@ -88,6 +89,8 @@ export interface SemanticAnalysisBundle { metrics: AnalysisMetrics; } +type DiscoveredAnalysisFile = string | Pick; + export class CodebaseAnalyzer { private treeSitter: TreeSitterLayer; private lspLayer?: LSPLayer; @@ -111,7 +114,10 @@ export class CodebaseAnalyzer { return (await this.analyzeProject(projectPath)).context; } - async analyzeBundle(projectPath: string, discoveredFiles?: string[]): Promise { + async analyzeBundle( + projectPath: string, + discoveredFiles?: DiscoveredAnalysisFile[] + ): Promise { const result = await this.analyzeProject(projectPath, discoveredFiles); const functionalStartedAt = Date.now(); const functionalPatterns = this.detectFunctionalPatternsFromAnalyses( @@ -131,7 +137,7 @@ export class CodebaseAnalyzer { }; } - private async analyzeProject(projectPath: string, discoveredFiles?: string[]): Promise<{ + private async analyzeProject(projectPath: string, discoveredFiles?: DiscoveredAnalysisFile[]): Promise<{ context: SemanticContext; files: string[]; fileAnalyses: Map; @@ -160,11 +166,15 @@ export class CodebaseAnalyzer { // 1. Select source files once, applying byte and count budgets before parsing. const discoveryStartedAt = Date.now(); - const candidates = discoveredFiles - ? this.filterCodeFiles(projectPath, discoveredFiles) + const discovery = discoveredFiles + ? { files: this.filterCodeFiles(projectPath, discoveredFiles), skipped: [] } : await this.findCodeFiles(projectPath); + const candidates = discovery.files; metrics.filesDiscovered = candidates.length; - const { files, skipped, bytes } = await this.selectFilesWithinLimits(candidates); + const selected = await this.selectFilesWithinLimits(candidates); + const files = selected.files; + const skipped = [...discovery.skipped, ...selected.skipped]; + const bytes = selected.bytes; metrics.bytesRead = bytes; metrics.durationsMs.discovery = Date.now() - discoveryStartedAt; @@ -217,57 +227,57 @@ export class CodebaseAnalyzer { }; } - private async findCodeFiles(projectPath: string): Promise { - const enabledLanguages = new Set(this.options.languages); - const extensions = Object.entries(LANGUAGE_EXTENSIONS) - .filter(([, language]) => enabledLanguages.has(language)) - .map(([extension]) => extension); - if (extensions.length === 0) { - return []; - } - const pattern = `**/*{${extensions.join(',')}}`; - - const ignorePatterns = this.options.exclude.map((p) => `**/${p}/**`); - - let allFiles: string[] = []; + private async findCodeFiles(projectPath: string): Promise<{ + files: Array<{ path: string; size?: number }>; + skipped: SkippedAnalysisFile[]; + }> { try { - allFiles = await glob(pattern, { - cwd: projectPath, - ignore: ignorePatterns, - absolute: true, - nodir: true, - }); + const structure = await new FileMapper(this.options.exclude, { + maxFiles: this.options.maxFiles, + maxTotalBytes: this.options.maxTotalBytes, + maxFileBytes: this.options.maxFileBytes, + }).mapRepository(projectPath); + return { + files: this.filterCodeFiles(projectPath, structure.files), + skipped: (structure.skipped ?? []).map((skip) => ({ + file: skip.file, + reason: skip.reason, + size: skip.size, + })), + }; } catch { - // A repository that cannot be enumerated produces an empty, valid bundle. - } - - // Apply include filter if specified - let filteredFiles = [...new Set(allFiles)].sort(); - if (this.options.include.length > 0) { - filteredFiles = filteredFiles.filter((file) => - this.options.include.some((pattern) => file.includes(pattern)) - ); + return { files: [], skipped: [] }; } - - return filteredFiles; } - private filterCodeFiles(projectPath: string, discoveredFiles: string[]): string[] { + private filterCodeFiles( + projectPath: string, + discoveredFiles: DiscoveredAnalysisFile[] + ): Array<{ path: string; size?: number }> { const supported = new Set(Object.keys(LANGUAGE_EXTENSIONS)); - return [...new Set(discoveredFiles.map((file) => - path.isAbsolute(file) ? file : path.resolve(projectPath, file) - ))] + const unique = new Map(); + for (const discovered of discoveredFiles) { + const file = typeof discovered === 'string' ? discovered : discovered.path; + const absolutePath = path.isAbsolute(file) ? file : path.resolve(projectPath, file); + unique.set(absolutePath, { + path: absolutePath, + size: typeof discovered === 'string' ? undefined : discovered.size, + }); + } + return [...unique.values()] .filter((file) => { - const extension = path.extname(file).toLowerCase(); + const extension = path.extname(file.path).toLowerCase(); return supported.has(extension) && this.options.languages.includes(LANGUAGE_EXTENSIONS[extension]); }) .filter((file) => this.options.include.length === 0 || - this.options.include.some((pattern) => file.includes(pattern))) - .sort(); + this.options.include.some((pattern) => file.path.includes(pattern))) + .sort((left, right) => left.path.localeCompare(right.path)); } - private async selectFilesWithinLimits(files: string[]): Promise<{ + private async selectFilesWithinLimits( + candidates: Array<{ path: string; size?: number }> + ): Promise<{ files: string[]; skipped: SkippedAnalysisFile[]; bytes: number; @@ -276,13 +286,16 @@ export class CodebaseAnalyzer { const skipped: SkippedAnalysisFile[] = []; let bytes = 0; - for (const file of files) { - let size: number; - try { - size = (await fs.stat(file)).size; - } catch { - skipped.push({ file, reason: 'stat-failed' }); - continue; + for (const candidate of candidates) { + const file = candidate.path; + let size = candidate.size; + if (size === undefined) { + try { + size = (await fs.stat(file)).size; + } catch { + skipped.push({ file, reason: 'stat-failed' }); + continue; + } } if (size > this.options.maxFileBytes) { diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index 81f49baf..92032cba 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -1,16 +1,19 @@ import { createHash } from 'crypto'; import { promises as nativeFs } from 'fs'; import * as fs from 'fs-extra'; -import { glob } from 'glob'; import * as path from 'path'; -import { RepoStructure } from '../../../../types'; +import { RepoStructure, type RepoDiscoverySkip } from '../../../../types'; import { CodebaseMapGenerator } from '../../../application/context/scaffolding/generators/documentation/codebaseMapGenerator'; import type { CodebaseMap, SemanticSnapshotMetadata, } from '../../../application/context/scaffolding/generators/documentation/codebaseMapGenerator'; -import { FileMapper } from '../../../../utils/fileMapper'; +import { + DEFAULT_FILE_MAPPING_LIMITS, + FileMapper, + type FileMappingLimits, +} from '../../../../utils/fileMapper'; import { CodebaseAnalyzer } from './codebaseAnalyzer'; import type { AnalyzerOptions, DetectedFunctionalPatterns, SemanticContext } from './types'; import { StackDetector } from '../../../application/context/intelligence/stack/stackDetector'; @@ -115,57 +118,6 @@ const SECTION_FILENAMES: Record = { const LEGACY_CODEBASE_MAP_PATH = path.join('docs', 'codebase-map.json'); -const FINGERPRINT_IGNORE_PATTERNS = [ - 'node_modules/**', - '.git/**', - 'dist/**', - 'build/**', - 'coverage/**', - '.context/**', - 'vendor/**', - '__pycache__/**', -]; - -const FINGERPRINT_ROOT_FILES = new Set([ - 'package.json', - 'package-lock.json', - 'pnpm-lock.yaml', - 'yarn.lock', - 'bun.lockb', - 'tsconfig.json', - 'tsconfig.build.json', - 'jest.config.js', - 'jest.config.ts', - 'vitest.config.ts', - 'vite.config.ts', - 'webpack.config.js', - 'next.config.js', - 'next.config.ts', - 'nest-cli.json', - '.eslintrc', - '.eslintrc.js', - '.eslintrc.json', - '.prettierrc', - '.prettierrc.json', - '.nvmrc', - '.node-version', -]); - -const FINGERPRINT_CODE_EXTENSIONS = new Set([ - '.ts', - '.tsx', - '.js', - '.jsx', - '.mjs', - '.cjs', - '.py', - '.go', - '.json', - '.yaml', - '.yml', - '.toml', -]); - interface FingerprintCacheEntry { metadata: string; contentHash: string; @@ -244,6 +196,8 @@ export interface RepoFingerprintResult { contentReads: number; cacheHits: number; discoveries: number; + partial: boolean; + skipped: RepoDiscoverySkip[]; durationMs: number; } @@ -264,8 +218,32 @@ export class SemanticSnapshotService { constructor( private readonly cacheEnabled = true, - private readonly fingerprintCache = new SemanticFingerprintCache() - ) {} + private readonly fingerprintCache = new SemanticFingerprintCache(), + fingerprintLimits: Partial = {} + ) { + this.fingerprintLimits = { + maxFiles: Math.min( + DEFAULT_FILE_MAPPING_LIMITS.maxFiles, + Math.max(0, Math.floor(fingerprintLimits.maxFiles ?? DEFAULT_FILE_MAPPING_LIMITS.maxFiles)) + ), + maxTotalBytes: Math.min( + DEFAULT_FILE_MAPPING_LIMITS.maxTotalBytes, + Math.max( + 0, + Math.floor(fingerprintLimits.maxTotalBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxTotalBytes) + ) + ), + maxFileBytes: Math.min( + DEFAULT_FILE_MAPPING_LIMITS.maxFileBytes, + Math.max( + 0, + Math.floor(fingerprintLimits.maxFileBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxFileBytes) + ) + ), + }; + } + + private readonly fingerprintLimits: FileMappingLimits; async captureRepoFingerprint(repoPath: string, discovery?: RepoStructure): Promise { return (await this.computeRepoFingerprint(repoPath, discovery)).fingerprint; @@ -431,7 +409,10 @@ export class SemanticSnapshotService { repoFingerprint, }); const generationMs = Date.now() - generationStartedAt; - const currentFingerprint = (await this.computeRepoFingerprint(repoPath, repoStructure)).fingerprint; + const verificationStructure = await fileMapper.mapRepository(repoPath); + const currentFingerprint = ( + await this.computeRepoFingerprint(repoPath, verificationStructure) + ).fingerprint; if (currentFingerprint !== repoFingerprint) { continue; @@ -541,7 +522,7 @@ export class SemanticSnapshotService { analyzer = new CodebaseAnalyzer(options.analyzerOptions); const bundle = await analyzer.analyzeBundle( repoStructure.rootPath, - repoStructure.files.map((file) => file.path) + repoStructure.files ); semantics ??= bundle.context; functionalPatterns ??= bundle.functionalPatterns; @@ -847,27 +828,61 @@ export class SemanticSnapshotService { discovery?: RepoStructure ): Promise { const startedAt = Date.now(); - const files = discovery - ? discovery.files.map((file) => file.relativePath) - : await this.discoverFingerprintFiles(repoPath); + const boundedDiscovery = discovery ?? await new FileMapper([], this.fingerprintLimits) + .mapRepository(repoPath); const discoveries = discovery ? 0 : 1; - const relevantFiles = [...new Set(files.map((file) => file.split(path.sep).join('/')))] - .filter((filePath) => this.isFingerprintRelevant(filePath)) - .sort(); - const relevantDirectories = this.fingerprintDirectoriesForFiles(relevantFiles); - + const relevantFiles = [...boundedDiscovery.files] + .sort((left, right) => left.relativePath.localeCompare(right.relativePath)); + const skipped = [...(boundedDiscovery.skipped ?? [])]; + let partial = !!boundedDiscovery.partial; const hash = createHash('sha256'); let bytesRead = 0; let contentReads = 0; let cacheHits = 0; + let filesHashed = 0; + let selectedBytes = 0; const liveCacheKeys = new Set(); const repoPrefix = `${path.resolve(repoPath).toLowerCase()}\0`; - for (const relativePath of relevantFiles) { - const absolutePath = path.join(repoPath, relativePath); + for (const discoveredFile of relevantFiles) { + const relativePath = discoveredFile.relativePath.split(path.sep).join('/'); + if (filesHashed >= this.fingerprintLimits.maxFiles) { + partial = true; + this.recordFingerprintSkip(skipped, { + file: discoveredFile.path, + reason: 'file-limit', + size: discoveredFile.size, + }); + break; + } + const absolutePath = discoveredFile.path; const cacheKey = `${repoPrefix}${relativePath}`; - liveCacheKeys.add(cacheKey); try { const stats = await nativeFs.stat(absolutePath, { bigint: true }); + const size = Number(stats.size); + if (stats.size > BigInt(this.fingerprintLimits.maxFileBytes)) { + partial = true; + this.recordFingerprintSkip(skipped, { + file: absolutePath, + reason: 'file-too-large', + size, + mtimeMs: Number(stats.mtimeNs) / 1_000_000, + ctimeMs: Number(stats.ctimeNs) / 1_000_000, + }); + hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeNs}\0skipped:file-too-large\n`); + continue; + } + if (selectedBytes + size > this.fingerprintLimits.maxTotalBytes) { + partial = true; + this.recordFingerprintSkip(skipped, { + file: absolutePath, + reason: 'total-byte-limit', + size, + }); + hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeNs}\0skipped:total-byte-limit\n`); + break; + } + + liveCacheKeys.add(cacheKey); const metadata = `${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`; let contentHash: string; const cachedHash = this.cacheEnabled @@ -877,41 +892,42 @@ export class SemanticSnapshotService { contentHash = cachedHash; cacheHits += 1; } else { - const content = await fs.readFile(absolutePath); - bytesRead += content.byteLength; + const boundedHash = await this.hashFileContentBounded( + absolutePath, + Math.min( + this.fingerprintLimits.maxFileBytes, + this.fingerprintLimits.maxTotalBytes - selectedBytes + ) + ); + bytesRead += boundedHash.bytesRead; contentReads += 1; - contentHash = createHash('sha256').update(content).digest('hex'); + if (boundedHash.exceeded) { + partial = true; + const reason = selectedBytes + boundedHash.bytesRead > this.fingerprintLimits.maxTotalBytes + ? 'total-byte-limit' + : 'file-too-large'; + this.recordFingerprintSkip(skipped, { file: absolutePath, reason, size }); + hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeNs}\0skipped:${reason}\n`); + continue; + } + contentHash = boundedHash.contentHash!; if (this.cacheEnabled) { this.fingerprintCache.set(cacheKey, metadata, contentHash); } } hash.update(`${relativePath}\0${stats.size}\0${stats.mtimeNs}\0${contentHash}\n`); + filesHashed += 1; + selectedBytes += size; } catch { hash.update(`${relativePath}:missing\n`); + partial = true; + this.recordFingerprintSkip(skipped, { file: absolutePath, reason: 'stat-failed' }); } } - // Directory metadata detects files created during stabilization without a - // second enumeration. A retry remaps the repository and includes them. - for (const relativePath of relevantDirectories) { - try { - const absoluteDirectory = relativePath === '.' - ? repoPath - : path.join(repoPath, relativePath); - const entriesHash = await this.hashRelevantDirectoryEntries(repoPath, relativePath); - if (relativePath === '.') { - // Root metadata also changes for ignored entries such as .context; - // its filtered entry signature is the stable relevant signal. - hash.update(`dir:.\0${entriesHash}\n`); - } else { - const stats = await nativeFs.stat(absoluteDirectory, { bigint: true }); - hash.update( - `dir:${relativePath}\0${stats.size}\0${stats.mtimeNs}\0${stats.ctimeNs}\0${entriesHash}\n` - ); - } - } catch { - hash.update(`dir:${relativePath}:missing\n`); - } + for (const skip of skipped) { + const relativePath = path.relative(repoPath, skip.file).split(path.sep).join('/'); + hash.update(`discovery-skip:${relativePath}:${skip.reason}:${skip.size ?? 'unknown'}\n`); } // Git index identity is an additional signal only; dirty files are still @@ -929,95 +945,49 @@ export class SemanticSnapshotService { return { fingerprint: hash.digest('hex'), - files: relevantFiles.length, + files: filesHashed, bytesRead, contentReads, cacheHits, discoveries, + partial, + skipped, durationMs: Date.now() - startedAt, }; } - private async discoverFingerprintFiles(repoPath: string): Promise { - const extensionPattern = `**/*.{${[...FINGERPRINT_CODE_EXTENSIONS] - .map((extension) => extension.slice(1)) - .join(',')}}`; - return glob([ - extensionPattern, - '{src,lib,bin,app,packages,scripts}/**/*', - ...FINGERPRINT_ROOT_FILES, - '.github/workflows/**/*.{yml,yaml}', - ], { - cwd: repoPath, - nodir: true, - dot: true, - ignore: FINGERPRINT_IGNORE_PATTERNS, - }); - } - - private isFingerprintRelevant(relativePath: string): boolean { - if (FINGERPRINT_ROOT_FILES.has(relativePath)) { - return true; - } - - const topLevel = relativePath.split('/')[0]; - if (['src', 'lib', 'bin', 'app', 'packages', 'scripts'].includes(topLevel)) { - return true; - } - - return FINGERPRINT_CODE_EXTENSIONS.has(path.extname(relativePath).toLowerCase()); + private recordFingerprintSkip( + skipped: RepoDiscoverySkip[], + skip: RepoDiscoverySkip + ): void { + if (skipped.length < 1_000) skipped.push(skip); } - private fingerprintDirectoriesForFiles(relevantFiles: string[]): string[] { - const directories = new Set(['.']); - for (const file of relevantFiles) { - let directory = path.posix.dirname(file); - while (directory !== '.') { - directories.add(directory); - directory = path.posix.dirname(directory); - } - } - return [...directories].sort(); - } - - private async hashRelevantDirectoryEntries( - repoPath: string, - relativeDirectory: string - ): Promise { - const absoluteDirectory = relativeDirectory === '.' - ? repoPath - : path.join(repoPath, relativeDirectory); - const aggregate = Buffer.alloc(32); - let count = 0; - const directory = await nativeFs.opendir(absoluteDirectory); - for await (const entry of directory) { - const relativePath = relativeDirectory === '.' - ? entry.name - : path.posix.join(relativeDirectory, entry.name); - if (!this.isFingerprintDirectoryEntryRelevant(relativePath, entry.isDirectory())) continue; - const entryHash = createHash('sha256') - .update(`${entry.isDirectory() ? 'd' : 'f'}:${entry.name}`) - .digest(); - for (let index = 0; index < aggregate.length; index += 1) { - aggregate[index] ^= entryHash[index]; + private async hashFileContentBounded( + filePath: string, + maxBytes: number + ): Promise<{ contentHash?: string; bytesRead: number; exceeded: boolean }> { + const handle = await nativeFs.open(filePath, 'r'); + const contentHash = createHash('sha256'); + const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, Math.max(1, maxBytes))); + let bytesRead = 0; + try { + while (bytesRead < maxBytes) { + const length = Math.min(chunk.length, maxBytes - bytesRead); + const read = await handle.read(chunk, 0, length, null); + if (read.bytesRead === 0) { + return { contentHash: contentHash.digest('hex'), bytesRead, exceeded: false }; + } + contentHash.update(chunk.subarray(0, read.bytesRead)); + bytesRead += read.bytesRead; } - count += 1; + const probe = Buffer.allocUnsafe(1); + const extra = await handle.read(probe, 0, 1, null); + if (extra.bytesRead > 0) return { bytesRead: bytesRead + 1, exceeded: true }; + return { contentHash: contentHash.digest('hex'), bytesRead, exceeded: false }; + } finally { + await handle.close(); } - return `${count}:${aggregate.toString('hex')}`; } - private isFingerprintDirectoryEntryRelevant( - relativePath: string, - isDirectory: boolean - ): boolean { - const normalized = relativePath.split(path.sep).join('/'); - const segments = normalized.split('/'); - if (segments.some((segment) => [ - 'node_modules', '.git', 'dist', 'build', 'coverage', '.context', - 'vendor', '__pycache__', - ].includes(segment))) return false; - if (!isDirectory) return this.isFingerprintRelevant(normalized); - if (segments.length > 1) return true; - return ['src', 'lib', 'bin', 'app', 'packages', 'scripts', '.github'].includes(segments[0]); - } } diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index 73307d72..f44b93a1 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -1,4 +1,5 @@ import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; import * as os from 'os'; import * as path from 'path'; @@ -78,10 +79,6 @@ describe('contextTools sensors scaffolding', () => { it('performs one discovery per operation and reuses fingerprint reads across operations', async () => { const repositoryDiscovery = jest.spyOn(FileMapper.prototype, 'mapRepository'); - const fingerprintDiscovery = jest.spyOn( - SemanticSnapshotService.prototype as any, - 'discoverFingerprintFiles' - ); const first = await initializeContextTool.execute!( { @@ -109,7 +106,6 @@ describe('contextTools sensors scaffolding', () => { const firstFingerprint = first._metadata.analysis.metrics.fingerprint; const secondFingerprint = second._metadata.analysis.metrics.fingerprint; expect(repositoryDiscovery).toHaveBeenCalledTimes(2); - expect(fingerprintDiscovery).not.toHaveBeenCalled(); expect(firstFingerprint.discoveries).toBe(0); expect(firstFingerprint.contentReads).toBe(firstFingerprint.files); expect(secondFingerprint.discoveries).toBe(0); @@ -118,6 +114,32 @@ describe('contextTools sensors scaffolding', () => { expect(secondFingerprint.cacheHits).toBe(secondFingerprint.files); }); + it('propagates discovery skips and partial state without reading oversized source files', async () => { + const hugePath = path.join(tempDir, 'src', 'huge.ts'); + const handle = await nativeFs.open(hugePath, 'w'); + await handle.truncate(3 * 1024 * 1024); + await handle.close(); + + const result = await initializeContextTool.execute!( + { + repoPath: tempDir, + type: 'agents', + semantic: true, + generateQA: false, + generateSkills: false, + skipContentGeneration: true, + }, + toolExecutionContext + ) as Record; + + expect(result._metadata.analysis.partial).toBe(true); + expect(result._metadata.analysis.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ file: hugePath, reason: 'file-too-large' }), + ])); + expect(result._metadata.analysis.metrics.fingerprint.bytesRead) + .toBeLessThan(3 * 1024 * 1024); + }); + it('includes bootstrap sensors.json in pending writes and listToFill', async () => { const result = await initializeContextTool.execute!( { diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 6fa5a3a8..46cd9211 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -439,7 +439,12 @@ export const getFileStructureTool = createInternalTool< const { rootPath, maxDepth = 3, includePatterns } = input; try { const mapper = new FileMapper([]); - const structure = await mapper.mapRepository(rootPath, includePatterns || undefined); + // This explicit structure-inspection surface requests all paths, while + // context initialization uses the bounded relevant defaults. + const structure = await mapper.mapRepository( + rootPath, + includePatterns?.length ? includePatterns : ['**/*'] + ); const filterByDepth = (relativePath: string): boolean => relativePath.split('/').length <= maxDepth; @@ -678,7 +683,7 @@ export const initializeContextTool = createInternalTool< semanticFingerprint = fingerprintMetrics.fingerprint; semanticBundle = await analyzer.analyzeBundle( resolvedRepoPath, - repoStructure.files.map((file) => file.path) + repoStructure.files ); } catch { semanticBundle = undefined; @@ -698,6 +703,7 @@ export const initializeContextTool = createInternalTool< } if (semanticBundle && semanticFingerprint && fingerprintMetrics) { + const discoverySkipped = repoStructure.skipped ?? []; analysisBundle = { repoPath: resolvedRepoPath, discoveredFiles: semanticBundle.files, @@ -707,8 +713,8 @@ export const initializeContextTool = createInternalTool< stackInfo: detectedStackInfo, repoFingerprint: semanticFingerprint, limits: semanticBundle.limits, - partial: semanticBundle.partial, - skipped: semanticBundle.skipped, + partial: !!repoStructure.partial || semanticBundle.partial, + skipped: [...discoverySkipped, ...semanticBundle.skipped], metrics: { ...semanticBundle.metrics, fingerprint: { diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index c2df1c86..43b99b89 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -109,7 +109,7 @@ export class DocumentationGenerator { snapshotFingerprint = await snapshotService!.captureRepoFingerprint(repoStructure.rootPath); const bundle = await this.analyzer.analyzeBundle( repoStructure.rootPath, - repoStructure.files.map((file) => file.path) + repoStructure.files ); semantics = bundle.context; functionalPatterns = bundle.functionalPatterns; diff --git a/src/types.ts b/src/types.ts index 200af4c4..a2dbf5cf 100644 --- a/src/types.ts +++ b/src/types.ts @@ -16,6 +16,26 @@ export interface TopLevelDirectoryStats { totalSize: number; } +export type RepoDiscoverySkipReason = + | 'file-limit' + | 'total-byte-limit' + | 'file-too-large' + | 'stat-failed'; + +export interface RepoDiscoverySkip { + file: string; + reason: RepoDiscoverySkipReason; + size?: number; + mtimeMs?: number; + ctimeMs?: number; +} + +export interface RepoDiscoveryMetrics { + entriesVisited: number; + statCalls: number; + stoppedEarly: boolean; +} + export interface RepoStructure { rootPath: string; files: FileInfo[]; @@ -23,6 +43,9 @@ export interface RepoStructure { totalFiles: number; totalSize: number; topLevelDirectoryStats: TopLevelDirectoryStats[]; + partial?: boolean; + skipped?: RepoDiscoverySkip[]; + discoveryMetrics?: RepoDiscoveryMetrics; } export type AIProvider = 'openrouter' | 'openai' | 'anthropic' | 'google'; diff --git a/src/utils/__tests__/fileMapper.test.ts b/src/utils/__tests__/fileMapper.test.ts new file mode 100644 index 00000000..a67a1eb9 --- /dev/null +++ b/src/utils/__tests__/fileMapper.test.ts @@ -0,0 +1,96 @@ +import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { globStream } from 'glob'; +import { FileMapper } from '../fileMapper'; + +jest.mock('glob', () => ({ globStream: jest.fn() })); + +const mockedGlobStream = globStream as jest.MockedFunction; + +function entryStream(entries: string[]): AsyncIterable & { destroy: jest.Mock } { + const iterator = (async function* () { + for (const entry of entries) yield entry; + })() as unknown as AsyncIterable & { destroy: jest.Mock }; + iterator.destroy = jest.fn(); + return iterator; +} + +function mockFileStats(size: number): jest.Mock { + return jest.spyOn(nativeFs, 'stat').mockResolvedValue({ + isFile: () => true, + size, + mtimeMs: 1, + ctimeMs: 1, + } as any) as jest.Mock; +} + +describe('FileMapper bounded discovery', () => { + let repoPath: string; + + beforeEach(async () => { + repoPath = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-file-mapper-')); + }); + + afterEach(async () => { + jest.restoreAllMocks(); + mockedGlobStream.mockReset(); + await fs.remove(repoPath); + }); + + it('stops before statting or materializing entries beyond the file cap', async () => { + const stream = entryStream( + Array.from({ length: 5_100 }, (_, index) => `src/file-${index}.ts`) + ); + mockedGlobStream.mockReturnValue(stream as any); + const stat = mockFileStats(1); + + const result = await new FileMapper().mapRepository(repoPath); + + expect(result.files).toHaveLength(5_000); + expect(result.discoveryMetrics).toEqual({ + entriesVisited: 5_001, + statCalls: 5_000, + stoppedEarly: true, + }); + expect(stat).toHaveBeenCalledTimes(5_000); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ reason: 'file-limit' }), + ])); + expect(stream.destroy).toHaveBeenCalled(); + }); + + it('stops metadata work as soon as the aggregate byte budget is reached', async () => { + const stream = entryStream(['src/a.ts', 'src/b.ts', 'src/c.ts']); + mockedGlobStream.mockReturnValue(stream as any); + const stat = mockFileStats(6); + + const result = await new FileMapper([], { + maxFiles: 5_000, + maxFileBytes: 100, + maxTotalBytes: 10, + }).mapRepository(repoPath); + + expect(result.files.map((file) => file.relativePath)).toEqual(['src/a.ts']); + expect(stat).toHaveBeenCalledTimes(2); + expect(result.discoveryMetrics?.stoppedEarly).toBe(true); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ file: path.join(repoPath, 'src/b.ts'), reason: 'total-byte-limit' }), + ])); + }); + + it('uses targeted defaults and never stats irrelevant emitted paths', async () => { + const stream = entryStream(['assets/movie.bin', 'src/index.ts']); + mockedGlobStream.mockReturnValue(stream as any); + const stat = mockFileStats(1); + + const result = await new FileMapper().mapRepository(repoPath); + + const patterns = mockedGlobStream.mock.calls[0][0] as string[]; + expect(patterns).not.toContain('**/*'); + expect(result.files.map((file) => file.relativePath)).toEqual(['src/index.ts']); + expect(stat).toHaveBeenCalledTimes(1); + expect(stat).not.toHaveBeenCalledWith(path.join(repoPath, 'assets/movie.bin')); + }); +}); diff --git a/src/utils/fileMapper.ts b/src/utils/fileMapper.ts index efea47af..009674df 100644 --- a/src/utils/fileMapper.ts +++ b/src/utils/fileMapper.ts @@ -1,9 +1,71 @@ import * as fs from 'fs-extra'; +import { promises as nativeFs, type Stats } from 'fs'; import * as path from 'path'; -import { glob } from 'glob'; -import { FileInfo, RepoStructure, TopLevelDirectoryStats } from '../types'; +import { globStream } from 'glob'; +import { + FileInfo, + RepoStructure, + TopLevelDirectoryStats, + type RepoDiscoverySkip, +} from '../types'; import { GitIgnoreManager } from './gitignoreManager'; +export interface FileMappingLimits { + maxFiles: number; + maxTotalBytes: number; + maxFileBytes: number; +} + +export const DEFAULT_FILE_MAPPING_LIMITS: FileMappingLimits = Object.freeze({ + maxFiles: 5_000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, +}); + +export const REPOSITORY_RELEVANT_EXTENSIONS = [ + 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'pyw', 'pyi', + 'go', 'json', 'yaml', 'yml', 'toml', +] as const; + +export const REPOSITORY_ROOT_FILES = [ + 'package.json', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb', + 'tsconfig.json', 'tsconfig.build.json', 'jest.config.js', 'jest.config.ts', + 'vitest.config.ts', 'vite.config.ts', 'webpack.config.js', 'next.config.js', + 'next.config.ts', 'nest-cli.json', '.eslintrc', '.eslintrc.js', + '.eslintrc.json', '.prettierrc', '.prettierrc.json', '.nvmrc', '.node-version', +] as const; + +const DEFAULT_RELEVANT_PATTERNS = [ + `{src,lib,bin,app,packages,scripts}/**/*.{${REPOSITORY_RELEVANT_EXTENSIONS.join(',')}}`, + `*.{${REPOSITORY_RELEVANT_EXTENSIONS.join(',')}}`, + ...REPOSITORY_ROOT_FILES, + '.github/workflows/**/*.{yml,yaml}', + 'README*', + 'LICENSE*', + 'Dockerfile*', + 'Makefile', +]; + +const RELEVANT_SOURCE_ROOTS = new Set(['src', 'lib', 'bin', 'app', 'packages', 'scripts']); + +export function isRepositoryRelevantFile(relativePath: string): boolean { + const normalized = relativePath.split(path.sep).join('/'); + const basename = path.posix.basename(normalized); + const extension = path.posix.extname(normalized).slice(1).toLowerCase(); + const segments = normalized.split('/'); + if ((REPOSITORY_ROOT_FILES as readonly string[]).includes(normalized)) return true; + if (segments.length === 1 && /^(README|LICENSE|Dockerfile|Makefile)/i.test(basename)) return true; + if (segments[0] === '.github' && segments[1] === 'workflows') { + return extension === 'yml' || extension === 'yaml'; + } + if (segments.length === 1 || RELEVANT_SOURCE_ROOTS.has(segments[0])) { + return (REPOSITORY_RELEVANT_EXTENSIONS as readonly string[]).includes(extension); + } + return false; +} + +const MAX_RECORDED_SKIPS = 1_000; + export class FileMapper { private excludePatterns: string[] = [ 'node_modules', @@ -23,9 +85,25 @@ export class FileMapper { private readonly gitIgnoreManager: GitIgnoreManager; - constructor(customExcludes: string[] = []) { + private readonly limits: FileMappingLimits; + + constructor( + customExcludes: string[] = [], + limits: Partial = {} + ) { this.excludePatterns = [...this.excludePatterns, ...customExcludes]; this.gitIgnoreManager = new GitIgnoreManager({ extraPatterns: customExcludes }); + this.limits = { + maxFiles: Math.max(0, Math.floor(limits.maxFiles ?? DEFAULT_FILE_MAPPING_LIMITS.maxFiles)), + maxTotalBytes: Math.max( + 0, + Math.floor(limits.maxTotalBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxTotalBytes) + ), + maxFileBytes: Math.max( + 0, + Math.floor(limits.maxFileBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxFileBytes) + ), + }; } private async loadGitignorePatterns(repoPath: string): Promise { @@ -50,66 +128,93 @@ export class FileMapper { const gitignorePatterns = await this.loadGitignorePatterns(absolutePath); const ignorePatterns = [...this.excludePatterns, ...gitignorePatterns]; - const patterns = includePatterns || ['**/*']; - const allFiles: string[] = []; - - for (const pattern of patterns) { - const files = await glob(pattern, { - cwd: absolutePath, - ignore: ignorePatterns, - dot: true, - absolute: false - }); - allFiles.push(...files); - } - - // Apply .gitignore filtering on top of glob excludes - const filteredFiles = this.gitIgnoreManager.filterPaths(allFiles); - - const uniqueFiles = [...new Set(filteredFiles)]; + await this.gitIgnoreManager.loadFromRepo(absolutePath); + const usesDefaultPatterns = !includePatterns?.length; + const patterns = usesDefaultPatterns ? DEFAULT_RELEVANT_PATTERNS : includePatterns!; const fileInfos: FileInfo[] = []; - const directories: FileInfo[] = []; + const skipped: RepoDiscoverySkip[] = []; + const seen = new Set(); let totalSize = 0; + let entriesVisited = 0; + let statCalls = 0; + let stoppedEarly = false; const topLevelStats = new Map(); - const concurrency = 32; - - for (let index = 0; index < uniqueFiles.length; index += concurrency) { - const slice = uniqueFiles.slice(index, index + concurrency); - await Promise.all( - slice.map(async relativePath => { - const fullPath = path.join(absolutePath, relativePath); - const stats = await fs.stat(fullPath); - const info: FileInfo = { - path: fullPath, - relativePath, - extension: path.extname(relativePath), - size: stats.size, - mtimeMs: stats.mtimeMs, - ctimeMs: stats.ctimeMs, - type: stats.isDirectory() ? 'directory' : 'file' - }; - - const topLevelSegment = this.extractTopLevelSegment(relativePath); - if (topLevelSegment) { - const current = topLevelStats.get(topLevelSegment) ?? { fileCount: 0, totalSize: 0 }; - if (!stats.isDirectory()) { - current.fileCount += 1; - current.totalSize += stats.size; - } - topLevelStats.set(topLevelSegment, current); - } - - if (stats.isDirectory()) { - directories.push(info); - } else { - fileInfos.push(info); - totalSize += stats.size; - } - - }) - ); + const stream = globStream(patterns, { + cwd: absolutePath, + ignore: ignorePatterns, + dot: true, + absolute: false, + nodir: true, + }); + + for await (const entry of stream) { + const rawPath = String(entry); + const relativePath = (path.isAbsolute(rawPath) + ? path.relative(absolutePath, rawPath) + : rawPath).split(path.sep).join('/'); + if (seen.has(relativePath) || this.gitIgnoreManager.shouldIgnore(relativePath)) continue; + if (usesDefaultPatterns && !isRepositoryRelevantFile(relativePath)) continue; + seen.add(relativePath); + entriesVisited += 1; + + if (entriesVisited > this.limits.maxFiles) { + this.recordSkip(skipped, { file: relativePath, reason: 'file-limit' }); + stoppedEarly = true; + stream.destroy(); + break; + } + + const fullPath = path.join(absolutePath, relativePath); + let stats: Stats; + try { + statCalls += 1; + stats = await nativeFs.stat(fullPath); + } catch { + this.recordSkip(skipped, { file: relativePath, reason: 'stat-failed' }); + continue; + } + if (!stats.isFile()) continue; + + const skipMetadata = { + file: fullPath, + size: stats.size, + mtimeMs: stats.mtimeMs, + ctimeMs: stats.ctimeMs, + }; + if (stats.size > this.limits.maxFileBytes) { + this.recordSkip(skipped, { ...skipMetadata, reason: 'file-too-large' }); + continue; + } + if (totalSize + stats.size > this.limits.maxTotalBytes) { + this.recordSkip(skipped, { ...skipMetadata, reason: 'total-byte-limit' }); + stoppedEarly = true; + stream.destroy(); + break; + } + + fileInfos.push({ + path: fullPath, + relativePath, + extension: path.extname(relativePath), + size: stats.size, + mtimeMs: stats.mtimeMs, + ctimeMs: stats.ctimeMs, + type: 'file', + }); + totalSize += stats.size; + + const topLevelSegment = this.extractTopLevelSegment(relativePath); + if (topLevelSegment) { + const current = topLevelStats.get(topLevelSegment) ?? { fileCount: 0, totalSize: 0 }; + current.fileCount += 1; + current.totalSize += stats.size; + topLevelStats.set(topLevelSegment, current); + } } + fileInfos.sort((left, right) => left.relativePath.localeCompare(right.relativePath)); + const directories = this.deriveDirectories(absolutePath, fileInfos); + const topLevelDirectoryStats: TopLevelDirectoryStats[] = Array.from(topLevelStats.entries()) .map(([name, stats]) => ({ name, fileCount: stats.fileCount, totalSize: stats.totalSize })) .sort((a, b) => a.name.localeCompare(b.name)); @@ -120,10 +225,37 @@ export class FileMapper { directories, totalFiles: fileInfos.length, totalSize, - topLevelDirectoryStats + topLevelDirectoryStats, + partial: skipped.length > 0 || stoppedEarly, + skipped, + discoveryMetrics: { entriesVisited, statCalls, stoppedEarly }, }; } + private recordSkip(skipped: RepoDiscoverySkip[], skip: RepoDiscoverySkip): void { + if (skipped.length < MAX_RECORDED_SKIPS) skipped.push(skip); + } + + private deriveDirectories(repoPath: string, files: FileInfo[]): FileInfo[] { + const relativeDirectories = new Set(); + for (const file of files) { + let directory = path.posix.dirname(file.relativePath); + while (directory !== '.') { + relativeDirectories.add(directory); + directory = path.posix.dirname(directory); + } + } + return [...relativeDirectories] + .sort() + .map((relativePath) => ({ + path: path.join(repoPath, relativePath), + relativePath, + extension: '', + size: 0, + type: 'directory' as const, + })); + } + async readFileContent(filePath: string): Promise { try { return await fs.readFile(filePath, 'utf-8'); From d022944b215d238842211172d518f8d4efcc2d5d Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 13:58:41 -0300 Subject: [PATCH 22/39] perf: bound UTF-8 hook previews --- .../hooks/__tests__/hookTracePolicy.test.ts | 54 +++++++++++++++++++ .../application/hooks/hookTracePolicy.ts | 38 ++++++------- 2 files changed, 74 insertions(+), 18 deletions(-) diff --git a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts index 9bea8744..a7d1e1e8 100644 --- a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -3,9 +3,63 @@ import { DEFAULT_HOOK_TRACE_POLICY, parseHookTracePolicy, sanitizeHookTraceData, + truncateUtf8Prefix, } from '../hookTracePolicy'; describe('hook trace policy', () => { + describe('bounded UTF-8 prefixes', () => { + it('is byte-accurate for ASCII, multibyte, surrogate, and invalid-surrogate boundaries', () => { + expect(truncateUtf8Prefix('hello', 5)).toEqual({ value: 'hello', truncated: false }); + expect(truncateUtf8Prefix('hello!', 5)).toEqual({ value: 'hello', truncated: true }); + expect(truncateUtf8Prefix('ééé', 4)).toEqual({ value: 'éé', truncated: true }); + expect(truncateUtf8Prefix('😀x', 3)).toEqual({ value: '', truncated: true }); + expect(truncateUtf8Prefix('😀x', 4)).toEqual({ value: '😀', truncated: true }); + expect(truncateUtf8Prefix('\ud800A', 2)).toEqual({ value: '', truncated: true }); + expect(truncateUtf8Prefix('\ud800A', 3)).toEqual({ value: '�', truncated: true }); + expect(truncateUtf8Prefix('', 0)).toEqual({ value: '', truncated: false }); + expect(truncateUtf8Prefix('x', 0)).toEqual({ value: '', truncated: true }); + }); + + it.each([ + { + label: 'ASCII', + huge: 'x'.repeat(16 * 1024 * 1024 + 17), + maximumBytes: 512, + expected: 'x'.repeat(512), + maximumCodeUnitsCopied: 513, + }, + { + label: 'multibyte', + huge: '😀'.repeat(4 * 1024 * 1024 + 3), + maximumBytes: 512, + expected: '😀'.repeat(128), + maximumCodeUnitsCopied: 513, + }, + ])('copies only a bounded prefix from a 16 MiB+ $label input', ({ + huge, + maximumBytes, + expected, + maximumCodeUnitsCopied, + }) => { + const originalFrom = Buffer.from.bind(Buffer); + let largestStringInput = 0; + const from = jest.spyOn(Buffer, 'from').mockImplementation(((value: any, ...args: any[]) => { + if (typeof value === 'string') largestStringInput = Math.max(largestStringInput, value.length); + return (originalFrom as any)(value, ...args); + }) as any); + + const started = performance.now(); + const result = truncateUtf8Prefix(huge, maximumBytes); + const durationMs = performance.now() - started; + from.mockRestore(); + + expect(result).toEqual({ value: expected, truncated: true }); + expect(largestStringInput).toBeLessThanOrEqual(maximumCodeUnitsCopied); + expect(Buffer.byteLength(result.value, 'utf8')).toBe(maximumBytes); + expect(durationMs).toBeLessThan(500); + }); + }); + it('summarizes a multi-megabyte Write without persisting its source body', () => { const content = `private-${'x'.repeat(5 * 1024 * 1024)}`; const data = sanitizeHookTraceData('Write', { diff --git a/src/harness/application/hooks/hookTracePolicy.ts b/src/harness/application/hooks/hookTracePolicy.ts index 504b5d60..ccac0c73 100644 --- a/src/harness/application/hooks/hookTracePolicy.ts +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -160,23 +160,25 @@ function byteLength(value: unknown): number { } } -function truncateUtf8(value: string, maximumBytes: number): { value: string; truncated: boolean } { - if (Buffer.byteLength(value, 'utf8') <= maximumBytes) { +export function truncateUtf8Prefix(value: string, maximumBytes: number): { value: string; truncated: boolean } { + const limit = Math.max(0, Math.floor(maximumBytes)); + // UTF-8 uses at least one byte per UTF-16 code unit. Taking limit + 1 + // code units is therefore enough to decide truncation without scanning or + // copying the rest of an untrusted multi-megabyte string. + const prefix = value.slice(0, Math.min(value.length, limit + 1)); + const encoded = Buffer.from(prefix, 'utf8'); + if (value.length === prefix.length && encoded.length <= limit) { return { value, truncated: false }; } + if (limit === 0) return { value: '', truncated: value.length > 0 }; - const characters = Array.from(value); - let low = 0; - let high = characters.length; - while (low < high) { - const middle = Math.ceil((low + high) / 2); - if (Buffer.byteLength(characters.slice(0, middle).join(''), 'utf8') <= maximumBytes) { - low = middle; - } else { - high = middle - 1; - } + let end = Math.min(limit, encoded.length); + // If the first excluded byte is a continuation byte, the cut sits inside a + // code point. Rewind to that code point's leading byte and exclude it. + while (end > 0 && end < encoded.length && (encoded[end] & 0xc0) === 0x80) { + end -= 1; } - return { value: characters.slice(0, low).join(''), truncated: true }; + return { value: encoded.subarray(0, end).toString('utf8'), truncated: true }; } function hashText(value: string): string { @@ -289,7 +291,7 @@ function summarizeUnknown( return value; } if (typeof value === 'string') { - const result = truncateUtf8(value, policy.maxStringBytes); + const result = truncateUtf8Prefix(value, policy.maxStringBytes); if (result.truncated) state.truncatedFieldCount += 1; return result.truncated ? `${result.value}…[truncated]` : result.value; } @@ -335,7 +337,7 @@ function summarizeUnknown( function boundedMetadataString(value: string | undefined, policy: HookTracePolicy, state: SanitizeState): string | undefined { if (value === undefined) return undefined; - const bounded = truncateUtf8(value, policy.maxStringBytes); + const bounded = truncateUtf8Prefix(value, policy.maxStringBytes); if (bounded.truncated) state.truncatedFieldCount += 1; return bounded.truncated ? `${bounded.value}…[truncated]` : bounded.value; } @@ -383,7 +385,7 @@ function summarizeBash(input: Record, policy: HookTracePolicy, if (!command) return {}; const redactedCommand = redactCommandSecrets(command); state.redactedFieldCount += redactedCommand.redacted; - const preview = truncateUtf8(redactedCommand.value, policy.maxStringBytes); + const preview = truncateUtf8Prefix(redactedCommand.value, policy.maxStringBytes); if (preview.truncated) state.truncatedFieldCount += 1; const basename = boundedMetadataString(commandBasename(command), policy, state); return { @@ -475,10 +477,10 @@ export function boundGenericTraceRecord Date: Sat, 11 Jul 2026 14:00:04 -0300 Subject: [PATCH 23/39] fix: reject partial freshness cache hits --- .../__tests__/boundedFileDiscovery.test.ts | 4 ++ .../semantic/__tests__/cacheRetention.test.ts | 20 +++++++--- .../semantic/__tests__/contextCache.test.ts | 39 +++++++++++++++++++ .../adapters/out/semantic/contextBuilder.ts | 20 ++++++++++ .../adapters/out/semantic/contextCache.ts | 10 +++++ .../discovery/boundedFileDiscovery.ts | 5 +++ 6 files changed, 92 insertions(+), 6 deletions(-) diff --git a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts index 7ef49a8b..ab20f26b 100644 --- a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts @@ -28,6 +28,10 @@ describe('bounded semantic file discovery', () => { expect(result.metrics).toMatchObject({ filesSelected: 10, partial: true }); expect(result.metrics.entriesScanned).toBeLessThan(200); expect(result.snapshot.files).toHaveLength(10); + await expect(isBoundedSnapshotFresh(result.snapshot)).resolves.toMatchObject({ + fresh: false, + signalsChecked: 0, + }); }); it('ignores irrelevant trees and detects dirty, new, and deleted relevant files', async () => { diff --git a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts index 6e1da5a8..50579447 100644 --- a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -83,7 +83,7 @@ describe('semantic cache retention', () => { expect(analyzer.fileAnalysisCacheMetrics().entries).toBe(0); }); - it('limits semantic fingerprint discovery before materialization and reuses bounded hit signals', async () => { + it('never reuses semantic context from a partial bounded discovery', async () => { for (let index = 0; index < 40; index += 1) { await fs.outputFile(path.join(repo, 'src', `${index}.ts`), `export const value${index} = ${index};`); } @@ -93,14 +93,22 @@ describe('semantic cache retention', () => { await builder.analyze(repo); await builder.analyze(repo); - expect(analyze).toHaveBeenCalledTimes(1); + expect(analyze).toHaveBeenCalledTimes(2); expect(builder.freshnessMetrics(repo)).toMatchObject({ - discoveries: 1, - filesSelected: 5, - partialDiscoveries: 1, + discoveries: 2, + filesSelected: 10, + partialDiscoveries: 2, }); expect(builder.freshnessMetrics(repo)!.entriesScanned).toBeLessThan(40); - expect(builder.freshnessMetrics(repo)!.signalsChecked).toBeGreaterThan(0); + expect(builder.semanticCacheMetrics(repo)).toMatchObject({ entries: 0 }); + + await fs.writeFile(path.join(repo, 'src', '39.ts'), 'export const changedBeyondBudget = true;'); + await builder.analyze(repo); + await fs.outputFile(path.join(repo, 'src', 'added-beyond-budget.ts'), 'export const added = true;'); + await builder.analyze(repo); + await fs.remove(path.join(repo, 'src', '39.ts')); + await builder.analyze(repo); + expect(analyze).toHaveBeenCalledTimes(5); await builder.shutdown(); }); }); diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index adb9e675..8f73b83f 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -124,6 +124,45 @@ describe('ContextCache', () => { expect(cache.freshnessMetrics().invalidations).toBe(1); cache.dispose(); }); + + it('does not cache partial discoveries that cannot prove full freshness', async () => { + await fs.outputFile(path.join(tempDir, 'src', 'a.ts'), 'export const a = 1;'); + await fs.outputFile(path.join(tempDir, 'src', 'b.ts'), 'export const b = 1;'); + await fs.outputFile(path.join(tempDir, 'src', 'z.ts'), 'export const z = 1;'); + const cache = new ContextCache({ watchDirs: ['src'], freshnessMaxFiles: 2 }); + + await cache.set(tempDir, 'compact', 'stale-content'); + expect(cache.freshnessMetrics().partialDiscoveries).toBe(1); + expect(cache.size).toBe(0); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + + await fs.writeFile(path.join(tempDir, 'src', 'z.ts'), 'export const z = 222;'); + await cache.set(tempDir, 'compact', 'still-not-cacheable'); + await fs.outputFile(path.join(tempDir, 'src', 'zz-added.ts'), 'export const added = true;'); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + await fs.remove(path.join(tempDir, 'src', 'z.ts')); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + cache.dispose(); + }); + + it('allows cache hits when an injected strong fingerprint proves freshness', async () => { + let fingerprint = 'source-v1'; + const cache = new ContextCache({ + watchDirs: ['src'], + freshnessMaxFiles: 1, + fingerprintProvider: async () => fingerprint, + }); + await fs.outputFile(path.join(tempDir, 'src', 'a.ts'), 'export const a = 1;'); + await fs.outputFile(path.join(tempDir, 'src', 'b.ts'), 'export const b = 1;'); + await cache.set(tempDir, 'compact', 'strong-content'); + + expect(await cache.get(tempDir, 'compact')).toBe('strong-content'); + await fs.writeFile(path.join(tempDir, 'src', 'b.ts'), 'export const b = 222;'); + expect(await cache.get(tempDir, 'compact')).toBe('strong-content'); + fingerprint = 'source-v2'; + expect(await cache.get(tempDir, 'compact')).toBeNull(); + cache.dispose(); + }); }); describe('invalidation and clearing', () => { diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index 009f7276..dffa19d1 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -97,6 +97,13 @@ export class SemanticContextBuilder { if (!owner) return this.analyzer.analyze(normalizedProjectPath); let discovered: Awaited> | undefined; + if (owner.fingerprint && owner.snapshot) { + if (owner.snapshot.partial) { + owner.cache.clear(); + owner.fingerprint = undefined; + owner.snapshot = undefined; + } + } if (owner.fingerprint && owner.snapshot) { const freshness = await isBoundedSnapshotFresh(owner.snapshot); owner.freshness.signalsChecked += freshness.signalsChecked; @@ -106,6 +113,13 @@ export class SemanticContextBuilder { } else { discovered = await this.computeProjectFingerprint(normalizedProjectPath); this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); + if (discovered.snapshot.partial) { + owner.cache.clear(); + owner.fingerprint = undefined; + owner.snapshot = undefined; + owner.freshness.invalidations += 1; + return this.analyzer.analyze(normalizedProjectPath); + } if (discovered.fingerprint === owner.fingerprint) { owner.snapshot = discovered.snapshot; const cached = owner.cache.get(owner.fingerprint); @@ -121,6 +135,12 @@ export class SemanticContextBuilder { discovered = await this.computeProjectFingerprint(normalizedProjectPath); this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); } + if (discovered.snapshot.partial) { + owner.cache.clear(); + owner.fingerprint = undefined; + owner.snapshot = undefined; + return this.analyzer.analyze(normalizedProjectPath); + } const fingerprint = discovered.fingerprint; if (owner.fingerprint && owner.fingerprint !== fingerprint) owner.cache.clear(); const cached = owner.cache.get(fingerprint); diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index f392c29a..8a9c85c3 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -128,6 +128,14 @@ export class ContextCache { const key = this.buildKey(repoPath, contextType, keyOptions); const freshness = await this.captureFreshness(repoPath); + // Without an injected strong fingerprint, partial discovery cannot + // observe changes outside its selected prefix. Do not retain an entry + // that could later authorize a stale hit. + if (!this.options.fingerprintProvider && freshness.freshnessSnapshot?.partial) { + cache.delete(key); + return; + } + cache.set(key, { content, ...freshness, @@ -281,10 +289,12 @@ export class ContextCache { return await this.options.fingerprintProvider(repoPath) === entry.freshnessFingerprint; } if (!entry.freshnessSnapshot) return false; + if (entry.freshnessSnapshot.partial) return false; const result = await isBoundedSnapshotFresh(entry.freshnessSnapshot); this.freshness.signalsChecked += result.signalsChecked; if (result.fresh) return true; const refreshed = await this.captureFreshness(repoPath); + if (refreshed.freshnessSnapshot?.partial) return false; if (refreshed.freshnessFingerprint === entry.freshnessFingerprint && refreshed.freshnessSnapshot) { entry.freshnessSnapshot = refreshed.freshnessSnapshot; return true; diff --git a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts index 6e8f08ae..fcc2da6b 100644 --- a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts +++ b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts @@ -148,6 +148,11 @@ export async function isBoundedSnapshotFresh(snapshot: BoundedFreshnessSnapshot) durationMs: number; }> { const started = Date.now(); + // A partial snapshot has no signal for unvisited directories/files, so it + // can never prove that the complete source identity is still fresh. + if (snapshot.partial) { + return { fresh: false, signalsChecked: 0, durationMs: Date.now() - started }; + } let signalsChecked = 0; for (const directory of snapshot.directories) { try { From 036e7aaefb47a4b8fbca65fcd88e8a0ca96e383b Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 14:10:13 -0300 Subject: [PATCH 24/39] perf: cap semantic directory scans --- CHANGELOG.md | 2 +- .../docs/en/reference/context-layout.md | 2 +- .../docs/pt-br/reference/context-layout.md | 2 +- .../__tests__/boundedFileDiscovery.test.ts | 48 +++++++++++++ .../semantic/__tests__/cacheRetention.test.ts | 22 ++++++ .../__tests__/codebaseAnalyzer.test.ts | 19 +++++ .../semantic/__tests__/contextCache.test.ts | 24 +++++++ .../adapters/out/semantic/codebaseAnalyzer.ts | 23 ++++-- .../adapters/out/semantic/contextBuilder.ts | 33 +++++++-- .../adapters/out/semantic/contextCache.ts | 22 +++++- .../discovery/boundedFileDiscovery.ts | 70 ++++++++++++++----- src/harness/adapters/out/semantic/types.ts | 2 + .../__tests__/runtimeRetentionConfig.test.ts | 10 +++ .../retention/runtimeRetentionConfig.ts | 14 ++-- 14 files changed, 254 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c3faffc..ea8ee3bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, and safe runtime configuration clamps. +- Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, raw directory-entry scan budgets, and safe runtime configuration clamps. - Moved checkpoint payload history from `session.json` into individual checkpoint records with legacy dual-read and lazy migration. ## [1.1.1] - 2026-06-27 diff --git a/docs/src/content/docs/en/reference/context-layout.md b/docs/src/content/docs/en/reference/context-layout.md index 1488fad5..6523506e 100644 --- a/docs/src/content/docs/en/reference/context-layout.md +++ b/docs/src/content/docs/en/reference/context-layout.md @@ -52,7 +52,7 @@ These files govern how the harness behaves. You write them, you review them, and | `.context/config/` | versioned | Yes | The authored config directory. | | `.context/config/policy.json` | versioned | Yes | Harness [policy](/concepts/policies/) rules and approval constraints. | | `.context/config/sensors.json` | versioned | Yes | Project [sensor](/concepts/sensors/) catalog plus detected stack info. Generated at bootstrap, then customized by the team. | -| `.context/config/runtime.json` | versioned | Yes | Versioned retention limits for traces, sessions, replays, datasets, checkpoints, bindings, and caches. Unsafe values are clamped to absolute ceilings. | +| `.context/config/runtime.json` | versioned | Yes | Versioned retention and semantic-discovery limits for traces, sessions, replays, datasets, checkpoints, bindings, and caches. `caches.context.maxEntriesScanned` and `caches.semantic.maxEntriesScanned` cap raw directory entries before filtering; unsafe values are clamped to absolute ceilings. | ## Durable project knowledge diff --git a/docs/src/content/docs/pt-br/reference/context-layout.md b/docs/src/content/docs/pt-br/reference/context-layout.md index ebe1abbb..d4516c87 100644 --- a/docs/src/content/docs/pt-br/reference/context-layout.md +++ b/docs/src/content/docs/pt-br/reference/context-layout.md @@ -52,7 +52,7 @@ Esses arquivos governam como o harness se comporta. Você os escreve, os revisa | `.context/config/` | versioned | Sim | O diretório de config autorada. | | `.context/config/policy.json` | versioned | Sim | Regras de [policy](/pt-br/concepts/policies/) do harness e restrições de aprovação. | | `.context/config/sensors.json` | versioned | Sim | Catálogo de [sensores](/pt-br/concepts/sensors/) do projeto mais informações da stack detectada. Gerado no bootstrap e depois customizado pelo time. | -| `.context/config/runtime.json` | versioned | Sim | Limites versionados de retenção para traces, sessions, replays, datasets, checkpoints, bindings e caches. Valores inseguros são limitados por tetos absolutos. | +| `.context/config/runtime.json` | versioned | Sim | Limites versionados de retenção e descoberta semântica para traces, sessions, replays, datasets, checkpoints, bindings e caches. `caches.context.maxEntriesScanned` e `caches.semantic.maxEntriesScanned` limitam entradas brutas de diretório antes da filtragem; valores inseguros são limitados por tetos absolutos. | ## Conhecimento durável do projeto diff --git a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts index ab20f26b..627a119f 100644 --- a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts @@ -34,6 +34,54 @@ describe('bounded semantic file discovery', () => { }); }); + it('counts irrelevant dirents and stops a huge single directory before stat work beyond the entry cap', async () => { + const irrelevant = path.join(repo, 'irrelevant'); + await fs.ensureDir(irrelevant); + for (let index = 0; index < 500; index += 1) { + await fs.writeFile(path.join(irrelevant, `${String(index).padStart(3, '0')}.txt`), 'ignored'); + } + const result = await discoverBoundedFiles(repo, { + maxFiles: 100, + maxDirectories: 100, + maxEntriesScanned: 25, + extensions: ['.ts'], + }); + + expect(result.files).toEqual([]); + expect(result.metrics).toMatchObject({ + entriesScanned: 25, + statsAttempted: 2, + filesSelected: 0, + partial: true, + stopReason: 'maxEntriesScanned', + }); + }); + + it('does not visit or stat queued deep directories after the raw-entry budget is exhausted', async () => { + const tree = path.join(repo, 'tree'); + let cursor = tree; + for (let depth = 0; depth < 40; depth += 1) { + cursor = path.join(cursor, `d${depth}`); + await fs.ensureDir(cursor); + } + const result = await discoverBoundedFiles(repo, { + roots: ['tree'], + maxFiles: 100, + maxDirectories: 100, + maxEntriesScanned: 9, + extensions: ['.ts'], + }); + + expect(result.metrics).toMatchObject({ + entriesScanned: 9, + directoriesVisited: 9, + statsAttempted: 9, + partial: true, + stopReason: 'maxEntriesScanned', + }); + expect(result.snapshot.directories).not.toContainEqual(expect.objectContaining({ path: expect.stringContaining('d8') })); + }); + it('ignores irrelevant trees and detects dirty, new, and deleted relevant files', async () => { await fs.outputFile(path.join(repo, 'src', 'index.ts'), 'export const value = 1;'); await fs.outputFile(path.join(repo, 'node_modules', 'large.ts'), 'ignored'); diff --git a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts index 50579447..647f92f2 100644 --- a/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -111,4 +111,26 @@ describe('semantic cache retention', () => { expect(analyze).toHaveBeenCalledTimes(5); await builder.shutdown(); }); + + it('does not retain semantic context when irrelevant entries exhaust the scan policy', async () => { + for (let index = 0; index < 30; index += 1) { + await fs.outputFile(path.join(repo, 'src', `${index}.txt`), 'ignored'); + } + const builder = new SemanticContextBuilder({ maxEntriesScanned: 6 }); + const analyze = jest.fn().mockResolvedValue(emptyContext); + (builder as any).analyzer.analyze = analyze; + + await builder.analyze(repo); + await builder.analyze(repo); + + expect(analyze).toHaveBeenCalledTimes(2); + expect(builder.semanticCacheMetrics(repo)).toMatchObject({ entries: 0 }); + expect(builder.freshnessMetrics(repo)).toMatchObject({ + discoveries: 2, + entriesScanned: 12, + partialDiscoveries: 2, + entryLimitDiscoveries: 2, + }); + await builder.shutdown(); + }); }); diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index 3bf902c1..3be745ec 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -399,6 +399,25 @@ describe('CodebaseAnalyzer', () => { expect(glob).not.toHaveBeenCalled(); }); + it('should respect the raw directory-entry scan policy before analyzing files', async () => { + for (let index = 0; index < 40; index += 1) { + await fs.outputFile(path.join(tempDir, 'irrelevant', `${index}.txt`), 'ignored'); + } + const analyzer = new CodebaseAnalyzer({ + useLSP: false, + maxFiles: 100, + maxEntriesScanned: 6, + }); + + await analyzer.analyze(tempDir); + + expect(analyzer.discoveryMetrics()).toMatchObject({ + entriesScanned: 6, + partial: true, + stopReason: 'maxEntriesScanned', + }); + }); + it('should respect languages option', async () => { const analyzer = new CodebaseAnalyzer({ useLSP: false, diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index 8f73b83f..ccb3a16b 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -145,6 +145,30 @@ describe('ContextCache', () => { cache.dispose(); }); + it('does not cache when irrelevant raw entries exhaust the configured freshness budget', async () => { + for (let index = 0; index < 40; index += 1) { + await fs.writeFile(path.join(tempDir, 'src', `${index}.txt`), 'ignored'); + } + const cache = new ContextCache({ + watchDirs: ['src'], + freshnessMaxFiles: 20, + freshnessMaxEntriesScanned: 7, + }); + + await cache.set(tempDir, 'compact', 'must-not-be-reused'); + await cache.set(tempDir, 'compact', 'still-partial'); + + expect(cache.size).toBe(0); + expect(await cache.get(tempDir, 'compact')).toBeNull(); + expect(cache.freshnessMetrics()).toMatchObject({ + discoveries: 2, + entriesScanned: 14, + partialDiscoveries: 2, + entryLimitDiscoveries: 2, + }); + cache.dispose(); + }); + it('allows cache hits when an injected strong fingerprint proves freshness', async () => { let fingerprint = 'source-v1'; const cache = new ContextCache({ diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 698ee312..5d17e93c 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -36,6 +36,7 @@ const DEFAULT_OPTIONS: Required = { exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxEntriesScanned: 100_000, cacheEnabled: true, fileAnalysisCacheMaxEntries: 5_000, fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, @@ -47,11 +48,13 @@ export class CodebaseAnalyzer { private options: Required; private readonly fileCacheEntriesExplicit: boolean; private readonly fileCacheBytesExplicit: boolean; + private readonly maxEntriesScannedExplicit: boolean; private lastDiscovery?: BoundedDiscoveryMetrics; constructor(options: AnalyzerOptions = {}) { this.fileCacheEntriesExplicit = options.fileAnalysisCacheMaxEntries !== undefined; this.fileCacheBytesExplicit = options.fileAnalysisCacheMaxBytes !== undefined; + this.maxEntriesScannedExplicit = options.maxEntriesScanned !== undefined; this.options = { ...DEFAULT_OPTIONS, ...options }; this.treeSitter = new TreeSitterLayer({ cacheEnabled: this.options.cacheEnabled, @@ -67,8 +70,8 @@ export class CodebaseAnalyzer { async analyze(projectPath: string): Promise { const startTime = Date.now(); + const { config } = await loadRuntimeRetentionConfig(projectPath); if (this.options.cacheEnabled) { - const { config } = await loadRuntimeRetentionConfig(projectPath); this.treeSitter.configureCache?.({ maxEntries: this.fileCacheEntriesExplicit ? this.options.fileAnalysisCacheMaxEntries : config.caches.fileAnalysis.maxEntries, maxBytes: this.fileCacheBytesExplicit ? this.options.fileAnalysisCacheMaxBytes : config.caches.fileAnalysis.maxBytes, @@ -77,7 +80,12 @@ export class CodebaseAnalyzer { } // 1. Find all code files - const files = await this.findCodeFiles(projectPath); + const files = await this.findCodeFiles( + projectPath, + this.maxEntriesScannedExplicit + ? this.options.maxEntriesScanned + : config.caches.semantic.maxEntriesScanned, + ); // 2. Analyze with Tree-sitter const fileAnalyses = await this.analyzeFiles(files); @@ -100,10 +108,11 @@ export class CodebaseAnalyzer { return context; } - private async findCodeFiles(projectPath: string): Promise { + private async findCodeFiles(projectPath: string, maxEntriesScanned: number): Promise { const discovery = await discoverBoundedFiles(projectPath, { maxFiles: this.options.maxFiles, maxDirectories: Math.min(10_000, this.options.maxFiles * 2 + 32), + maxEntriesScanned, extensions: Object.keys(LANGUAGE_EXTENSIONS), include: this.options.include, excludeDirectoryNames: this.options.exclude, @@ -679,7 +688,13 @@ export class CodebaseAnalyzer { * These patterns indicate functional capabilities like auth, database, API, etc. */ async detectFunctionalPatterns(projectPath: string): Promise { - const files = await this.findCodeFiles(projectPath); + const { config } = await loadRuntimeRetentionConfig(projectPath); + const files = await this.findCodeFiles( + projectPath, + this.maxEntriesScannedExplicit + ? this.options.maxEntriesScanned + : config.caches.semantic.maxEntriesScanned, + ); const analyses = await this.analyzeFiles(files); const patterns: FunctionalPattern[] = []; diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index dffa19d1..16e5f6b6 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -45,6 +45,7 @@ export interface SemanticFreshnessMetrics { directoriesVisited: number; entriesScanned: number; partialDiscoveries: number; + entryLimitDiscoveries: number; signalsChecked: number; invalidations: number; } @@ -55,6 +56,7 @@ const DEFAULT_OPTIONS: Required = { exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxEntriesScanned: 100_000, cacheEnabled: true, fileAnalysisCacheMaxEntries: 5_000, fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, @@ -69,6 +71,7 @@ export class SemanticContextBuilder { private analyzer: CodebaseAnalyzer; private options: Required; private readonly semanticCacheBytesExplicit: boolean; + private readonly maxEntriesScannedExplicit: boolean; private readonly semanticCaches = new Map; signature: string; @@ -76,14 +79,19 @@ export class SemanticContextBuilder { diagnostics: string[]; maxEntries: number; maxBytes: number; + maxEntriesScanned: number; snapshot?: BoundedFreshnessSnapshot; freshness: SemanticFreshnessMetrics; }>(); constructor(options: ContextBuilderOptions = {}) { this.semanticCacheBytesExplicit = options.semanticCacheMaxBytes !== undefined; + this.maxEntriesScannedExplicit = options.maxEntriesScanned !== undefined; this.options = { ...DEFAULT_OPTIONS, ...options }; - this.analyzer = new CodebaseAnalyzer(this.options); + this.analyzer = new CodebaseAnalyzer({ + ...this.options, + maxEntriesScanned: options.maxEntriesScanned, + }); } /** @@ -111,7 +119,7 @@ export class SemanticContextBuilder { const cached = owner.cache.get(owner.fingerprint); if (cached) return cached; } else { - discovered = await this.computeProjectFingerprint(normalizedProjectPath); + discovered = await this.computeProjectFingerprint(normalizedProjectPath, owner.maxEntriesScanned); this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); if (discovered.snapshot.partial) { owner.cache.clear(); @@ -132,7 +140,7 @@ export class SemanticContextBuilder { } if (!discovered) { - discovered = await this.computeProjectFingerprint(normalizedProjectPath); + discovered = await this.computeProjectFingerprint(normalizedProjectPath, owner.maxEntriesScanned); this.recordDiscoveryMetrics(owner.freshness, discovered.metrics); } if (discovered.snapshot.partial) { @@ -931,6 +939,7 @@ export class SemanticContextBuilder { const limits = { maxEntries: configured.maxEntries, maxBytes: this.semanticCacheBytesExplicit ? this.options.semanticCacheMaxBytes : configured.maxBytes, + maxEntriesScanned: this.maxEntriesScannedExplicit ? this.options.maxEntriesScanned : configured.maxEntriesScanned, }; const signature = JSON.stringify(limits); const current = this.semanticCaches.get(projectPath); @@ -941,7 +950,8 @@ export class SemanticContextBuilder { } current?.cache.dispose(); const cache = new BoundedLruCache({ - ...limits, + maxEntries: limits.maxEntries, + maxBytes: limits.maxBytes, ttlMs: 24 * 60 * 60 * 1000, estimateBytes: context => this.estimateSemanticContextBytes(context), }); @@ -952,7 +962,16 @@ export class SemanticContextBuilder { ...limits, fingerprint: undefined as string | undefined, snapshot: undefined as BoundedFreshnessSnapshot | undefined, - freshness: { discoveries: 0, filesSelected: 0, directoriesVisited: 0, entriesScanned: 0, partialDiscoveries: 0, signalsChecked: 0, invalidations: 0 }, + freshness: { + discoveries: 0, + filesSelected: 0, + directoriesVisited: 0, + entriesScanned: 0, + partialDiscoveries: 0, + entryLimitDiscoveries: 0, + signalsChecked: 0, + invalidations: 0, + }, }; this.semanticCaches.set(projectPath, owner); return owner; @@ -974,10 +993,11 @@ export class SemanticContextBuilder { } } - private async computeProjectFingerprint(projectPath: string) { + private async computeProjectFingerprint(projectPath: string, maxEntriesScanned: number) { return discoverBoundedFiles(projectPath, { maxFiles: this.options.maxFiles, maxDirectories: Math.min(10_000, this.options.maxFiles * 2 + 32), + maxEntriesScanned, extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.pyw', '.pyi', '.go'], include: this.options.include, excludeDirectoryNames: this.options.exclude, @@ -990,6 +1010,7 @@ export class SemanticContextBuilder { target.directoriesVisited += metrics.directoriesVisited; target.entriesScanned += metrics.entriesScanned; if (metrics.partial) target.partialDiscoveries += 1; + if (metrics.stopReason === 'maxEntriesScanned') target.entryLimitDiscoveries += 1; } private estimateSemanticContextBytes(context: SemanticContext): number { diff --git a/src/harness/adapters/out/semantic/contextCache.ts b/src/harness/adapters/out/semantic/contextCache.ts index 8a9c85c3..3cc93491 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -45,6 +45,8 @@ export interface ContextCacheOptions { freshnessMaxFiles?: number; /** Maximum directories visited while establishing freshness (default: 256). */ freshnessMaxDirectories?: number; + /** Maximum raw directory entries inspected while establishing freshness. */ + freshnessMaxEntriesScanned?: number; /** Optional operation-provided source fingerprint that avoids local discovery. */ fingerprintProvider?: (repoPath: string) => Promise; } @@ -63,7 +65,9 @@ export interface ContextCacheFreshnessMetrics { discoveries: number; filesSelected: number; directoriesVisited: number; + entriesScanned: number; partialDiscoveries: number; + entryLimitDiscoveries: number; signalsChecked: number; invalidations: number; } @@ -73,6 +77,7 @@ export class ContextCache { cache: BoundedLruCache; signature: string; diagnostics: string[]; + maxEntriesScanned: number; }>(); private readonly watchDirs: string[]; private readonly options: ContextCacheOptions; @@ -80,7 +85,9 @@ export class ContextCache { discoveries: 0, filesSelected: 0, directoriesVisited: 0, + entriesScanned: 0, partialDiscoveries: 0, + entryLimitDiscoveries: 0, signalsChecked: 0, invalidations: 0, }; @@ -231,6 +238,7 @@ export class ContextCache { maxEntries: this.options.maxEntries ?? configured.maxEntries ?? DEFAULT_MAX_ENTRIES, maxBytes: this.options.maxBytes ?? configured.maxBytes ?? DEFAULT_MAX_BYTES, ttlMs: this.options.ttlMs ?? configured.ttlMs ?? DEFAULT_TTL_MS, + maxEntriesScanned: this.options.freshnessMaxEntriesScanned ?? configured.maxEntriesScanned, }; const signature = JSON.stringify(limits); const current = this.caches.get(normalized); @@ -241,12 +249,19 @@ export class ContextCache { } current?.cache.dispose(); const cache = new BoundedLruCache({ - ...limits, + maxEntries: limits.maxEntries, + maxBytes: limits.maxBytes, + ttlMs: limits.ttlMs, sweepIntervalMs: this.options.sweepIntervalMs, estimateBytes: (entry, key) => Buffer.byteLength(key) + Buffer.byteLength(entry.content) + Buffer.byteLength(JSON.stringify(entry.freshnessSnapshot ?? entry.freshnessFingerprint ?? '')), }); - this.caches.set(normalized, { cache, signature, diagnostics: loaded.diagnostics }); + this.caches.set(normalized, { + cache, + signature, + diagnostics: loaded.diagnostics, + maxEntriesScanned: limits.maxEntriesScanned, + }); return cache; } @@ -274,13 +289,16 @@ export class ContextCache { roots: this.watchDirs, maxFiles: this.options.freshnessMaxFiles ?? 128, maxDirectories: this.options.freshnessMaxDirectories ?? 256, + maxEntriesScanned: this.caches.get(this.normalizeRepoPath(repoPath))?.maxEntriesScanned, extensions: CONTEXT_RELEVANT_EXTENSIONS, excludeRelativePrefixes: ['.context/runtime', '.context/cache'], }); this.freshness.discoveries += 1; this.freshness.filesSelected += discovery.metrics.filesSelected; this.freshness.directoriesVisited += discovery.metrics.directoriesVisited; + this.freshness.entriesScanned += discovery.metrics.entriesScanned; if (discovery.metrics.partial) this.freshness.partialDiscoveries += 1; + if (discovery.metrics.stopReason === 'maxEntriesScanned') this.freshness.entryLimitDiscoveries += 1; return { freshnessFingerprint: discovery.fingerprint, freshnessSnapshot: discovery.snapshot }; } diff --git a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts index fcc2da6b..d2d1cf8f 100644 --- a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts +++ b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts @@ -24,10 +24,14 @@ export interface BoundedDiscoveryMetrics { filesSelected: number; directoriesVisited: number; entriesScanned: number; + statsAttempted: number; partial: boolean; + stopReason?: BoundedDiscoveryStopReason; durationMs: number; } +export type BoundedDiscoveryStopReason = 'maxFiles' | 'maxDirectories' | 'maxEntriesScanned'; + export interface BoundedFileDiscoveryResult { files: string[]; fingerprint: string; @@ -39,6 +43,7 @@ export interface BoundedFileDiscoveryOptions { roots?: string[]; maxFiles: number; maxDirectories?: number; + maxEntriesScanned?: number; extensions?: Iterable; include?: string[]; excludeDirectoryNames?: Iterable; @@ -49,6 +54,14 @@ const DEFAULT_EXCLUDED_DIRECTORIES = new Set([ '.git', 'node_modules', 'dist', 'build', 'coverage', '.next', '.nuxt', 'vendor', '__pycache__', ]); +export const DEFAULT_MAX_ENTRIES_SCANNED = 100_000; +export const ABSOLUTE_MAX_ENTRIES_SCANNED = 1_000_000; + +function boundedEntriesLimit(value: number | undefined): number { + if (value === undefined || !Number.isFinite(value)) return DEFAULT_MAX_ENTRIES_SCANNED; + return Math.min(ABSOLUTE_MAX_ENTRIES_SCANNED, Math.max(1, Math.floor(value))); +} + function normalizedRelative(root: string, target: string): string { return path.relative(root, target).split(path.sep).join('/'); } @@ -71,6 +84,7 @@ export async function discoverBoundedFiles( const root = path.resolve(rootPath); const maxFiles = Math.max(1, Math.floor(options.maxFiles)); const maxDirectories = Math.max(1, Math.floor(options.maxDirectories ?? Math.min(10_000, maxFiles * 2 + 32))); + const maxEntriesScanned = boundedEntriesLimit(options.maxEntriesScanned); const extensions = options.extensions ? new Set([...options.extensions].map(value => value.toLowerCase())) : undefined; const excludedNames = new Set([...DEFAULT_EXCLUDED_DIRECTORIES, ...(options.excludeDirectoryNames ?? [])]); const excludedPrefixes = [...(options.excludeRelativePrefixes ?? [])] @@ -82,13 +96,25 @@ export async function discoverBoundedFiles( const files: BoundedFileSignal[] = []; const directories: BoundedDirectorySignal[] = []; let entriesScanned = 0; + let statsAttempted = 0; let partial = false; + let stopReason: BoundedDiscoveryStopReason | undefined; + const stopPartial = (reason: BoundedDiscoveryStopReason) => { + partial = true; + stopReason ??= reason; + }; - while (queue.length > 0 && files.length < maxFiles && directories.length < maxDirectories) { + while ( + queue.length > 0 + && files.length < maxFiles + && directories.length < maxDirectories + && entriesScanned < maxEntriesScanned + ) { const directoryPath = queue.shift()!; const relativeDirectory = normalizedRelative(root, directoryPath); if (excludedPrefixes.some(prefix => relativeDirectory === prefix || relativeDirectory.startsWith(`${prefix}/`))) continue; try { + statsAttempted += 1; const directoryStat = await fs.stat(directoryPath); directories.push({ path: relativeDirectory || '.', mtimeMs: directoryStat.mtimeMs }); const directory = await fs.opendir(directoryPath); @@ -97,33 +123,39 @@ export async function discoverBoundedFiles( const absolute = path.join(directoryPath, entry.name); const relative = normalizedRelative(root, absolute); if (entry.isDirectory()) { - if (excludedNames.has(entry.name)) continue; - if (excludedPrefixes.some(prefix => relative === prefix || relative.startsWith(`${prefix}/`))) continue; - if (queued.size >= maxDirectories) { - partial = true; - continue; - } - if (!queued.has(absolute)) { + const excluded = excludedNames.has(entry.name) + || excludedPrefixes.some(prefix => relative === prefix || relative.startsWith(`${prefix}/`)); + if (!excluded && queued.size >= maxDirectories) { + stopPartial('maxDirectories'); + } else if (!excluded && !queued.has(absolute)) { queued.add(absolute); queue.push(absolute); } - continue; + } else if ( + entry.isFile() + && (!extensions || extensions.has(path.extname(entry.name).toLowerCase())) + && (!options.include?.length || options.include.some(pattern => relative.includes(pattern))) + ) { + try { + statsAttempted += 1; + const stat = await fs.stat(absolute); + files.push({ path: relative, size: stat.size, mtimeMs: stat.mtimeMs }); + } catch { /* file changed during discovery */ } + } + if (entriesScanned >= maxEntriesScanned) { + stopPartial('maxEntriesScanned'); + break; } - if (!entry.isFile()) continue; - if (extensions && !extensions.has(path.extname(entry.name).toLowerCase())) continue; - if (options.include?.length && !options.include.some(pattern => relative.includes(pattern))) continue; - try { - const stat = await fs.stat(absolute); - files.push({ path: relative, size: stat.size, mtimeMs: stat.mtimeMs }); - } catch { /* file changed during discovery */ } if (files.length >= maxFiles) { - partial = true; + stopPartial('maxFiles'); break; } } } catch { /* missing or unreadable roots are represented by their absence */ } } - if (queue.length > 0 || directories.length >= maxDirectories) partial = true; + if (entriesScanned >= maxEntriesScanned) stopPartial('maxEntriesScanned'); + else if (files.length >= maxFiles) stopPartial('maxFiles'); + else if (queue.length > 0 || directories.length >= maxDirectories) stopPartial('maxDirectories'); files.sort((left, right) => left.path.localeCompare(right.path)); directories.sort((left, right) => left.path.localeCompare(right.path)); const snapshot: BoundedFreshnessSnapshot = { rootPath: root, files, directories, partial }; @@ -135,7 +167,9 @@ export async function discoverBoundedFiles( filesSelected: files.length, directoriesVisited: directories.length, entriesScanned, + statsAttempted, partial, + stopReason, durationMs: Date.now() - started, }, }; diff --git a/src/harness/adapters/out/semantic/types.ts b/src/harness/adapters/out/semantic/types.ts index 9577628c..f5346e94 100644 --- a/src/harness/adapters/out/semantic/types.ts +++ b/src/harness/adapters/out/semantic/types.ts @@ -190,6 +190,8 @@ export interface AnalyzerOptions { exclude?: string[]; include?: string[]; maxFiles?: number; + /** Maximum raw directory entries inspected before returning a partial analysis. */ + maxEntriesScanned?: number; cacheEnabled?: boolean; fileAnalysisCacheMaxEntries?: number; fileAnalysisCacheMaxBytes?: number; diff --git a/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts index 3760c245..58a6f6ab 100644 --- a/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts +++ b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts @@ -11,11 +11,21 @@ describe('loadRuntimeRetentionConfig', () => { unknown: true, bindings: { maxEntries: Number.MAX_SAFE_INTEGER }, checkpoints: { maxDataBytes: 0, maxArtifactIds: -1 }, + caches: { + context: { maxEntriesScanned: Number.MAX_SAFE_INTEGER }, + semantic: { maxEntriesScanned: Number.MAX_SAFE_INTEGER }, + }, }); const result = await loadRuntimeRetentionConfig(repo); expect(result.config.bindings.maxEntries).toBe(10_000); expect(result.config.checkpoints.maxDataBytes).toBe(64 * 1024); expect(result.config.checkpoints.maxArtifactIds).toBe(200); + expect(result.config.caches.context.maxEntriesScanned).toBe(1_000_000); + expect(result.config.caches.semantic.maxEntriesScanned).toBe(1_000_000); + expect(result.diagnostics).toEqual(expect.arrayContaining([ + expect.stringContaining('caches.context.maxEntriesScanned was clamped'), + expect.stringContaining('caches.semantic.maxEntriesScanned was clamped'), + ])); expect(result.diagnostics.some(item => item.includes('Unknown'))).toBe(true); expect(result.clamps).toBeGreaterThan(0); await fs.remove(repo); diff --git a/src/harness/application/retention/runtimeRetentionConfig.ts b/src/harness/application/retention/runtimeRetentionConfig.ts index 10396578..4ef8ece1 100644 --- a/src/harness/application/retention/runtimeRetentionConfig.ts +++ b/src/harness/application/retention/runtimeRetentionConfig.ts @@ -10,8 +10,8 @@ export interface RuntimeRetentionConfig { checkpoints: { maxDataBytes: number; maxArtifactIds: number }; bindings: { maxEntries: number; maxAgeMs: number }; caches: { - context: { maxEntries: number; maxBytes: number; ttlMs: number }; - semantic: { maxEntries: number; maxBytes: number }; + context: { maxEntries: number; maxBytes: number; ttlMs: number; maxEntriesScanned: number }; + semantic: { maxEntries: number; maxBytes: number; maxEntriesScanned: number }; mcpSessions: { maxEntries: number; ttlMs: number }; fileAnalysis: { maxEntries: number; maxBytes: number }; }; @@ -41,8 +41,8 @@ export const DEFAULT_RUNTIME_RETENTION_CONFIG: RuntimeRetentionConfig = { checkpoints: { maxDataBytes: 64 * 1024, maxArtifactIds: 200 }, bindings: { maxEntries: 1_000, maxAgeMs: 30 * 24 * 60 * 60 * 1000 }, caches: { - context: { maxEntries: 16, maxBytes: 32 * 1024 * 1024, ttlMs: 5 * 60 * 1000 }, - semantic: { maxEntries: 1, maxBytes: 64 * 1024 * 1024 }, + context: { maxEntries: 16, maxBytes: 32 * 1024 * 1024, ttlMs: 5 * 60 * 1000, maxEntriesScanned: 20_000 }, + semantic: { maxEntries: 1, maxBytes: 64 * 1024 * 1024, maxEntriesScanned: 100_000 }, mcpSessions: { maxEntries: 64, ttlMs: 30 * 60 * 1000 }, fileAnalysis: { maxEntries: 5_000, maxBytes: 128 * 1024 * 1024 }, }, @@ -58,8 +58,8 @@ const KNOWN_KEYS: Record = { checkpoints: ['maxDataBytes', 'maxArtifactIds'], bindings: ['maxEntries', 'maxAgeMs'], caches: ['context', 'semantic', 'mcpSessions', 'fileAnalysis'], - 'caches.context': ['maxEntries', 'maxBytes', 'ttlMs'], - 'caches.semantic': ['maxEntries', 'maxBytes'], + 'caches.context': ['maxEntries', 'maxBytes', 'ttlMs', 'maxEntriesScanned'], + 'caches.semantic': ['maxEntries', 'maxBytes', 'maxEntriesScanned'], 'caches.mcpSessions': ['maxEntries', 'ttlMs'], 'caches.fileAnalysis': ['maxEntries', 'maxBytes'], }; @@ -202,10 +202,12 @@ export async function loadRuntimeRetentionConfig(repoPath: string): Promise Date: Sat, 11 Jul 2026 14:10:30 -0300 Subject: [PATCH 25/39] fix: bound MCP explore I/O --- CHANGELOG.md | 1 + README.md | 2 + .../content/docs/en/reference/mcp-tools.md | 4 +- .../content/docs/pt-br/reference/mcp-tools.md | 4 +- .../actions/exploreActionService.ts | 1 + .../__tests__/boundedExplore.load.test.ts | 35 ++ .../context/__tests__/boundedExplore.test.ts | 148 ++++++++ .../application/context/boundedExplore.ts | 339 ++++++++++++++++++ .../application/context/contextTools.ts | 71 ++-- src/harness/application/context/index.ts | 1 + src/mcp/README.md | 2 + src/mcp/server/mcpServer.ts | 6 +- 12 files changed, 561 insertions(+), 53 deletions(-) create mode 100644 src/harness/application/context/__tests__/boundedExplore.load.test.ts create mode 100644 src/harness/application/context/__tests__/boundedExplore.test.ts create mode 100644 src/harness/application/context/boundedExplore.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d44ca3ab..1fe4a127 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses. - Applied the same bounded UTF-8 budget to every MCP resource, rejected oversized files before reading their bodies, enforced action-specific list maxima, and paginated `explore` file listings. +- Bounded `explore` reads before file materialization and replaced whole-glob/whole-file code search with byte-capped streaming discovery, search, and cursor pages. - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. diff --git a/README.md b/README.md index bf83d68b..c7d5442b 100644 --- a/README.md +++ b/README.md @@ -526,6 +526,8 @@ MCP JSON responses are compact and bounded to 1 MiB by default (4 MiB absolute). The same UTF-8 budget covers MCP resources (`context://`, `file://`, and `workflow://`). Oversized file resources return `MCP_RESOURCE_TOO_LARGE` before the file body is read. `explore` action `list` returns bounded pages (100 files by default, 1,000 maximum); continue with its opaque `page.nextCursor`. +`explore` file reads use the same 1 MiB safety boundary and return `EXPLORE_FILE_TOO_LARGE` without opening an oversized body. Code search streams bounded discovery and files, reports partial/skip metrics, and supports continuation with `page.nextCursor`. + ## CLI Reference ### Requirements diff --git a/docs/src/content/docs/en/reference/mcp-tools.md b/docs/src/content/docs/en/reference/mcp-tools.md index 91a7f335..acc17d21 100644 --- a/docs/src/content/docs/en/reference/mcp-tools.md +++ b/docs/src/content/docs/en/reference/mcp-tools.md @@ -56,12 +56,14 @@ File and code exploration — read files, list paths, search content, and extrac | `symbolTypes` | array | analyze | Extract `class` \| `interface` \| `function` \| `type` \| `enum` | | `ignore` | array | list, search, getStructure | Patterns to exclude | | `limit` | integer, 1–1,000 | list | Files per page; defaults to 100 | -| `cursor` | string | list | Opaque continuation cursor from `page.nextCursor` | +| `cursor` | string | list, search | Opaque continuation cursor from `page.nextCursor` | **Returns:** file contents, matched files, symbol analysis, search results, or a directory tree. The `list` action streams matches into bounded pages instead of materializing the entire glob. Pass the returned `page.nextCursor` unchanged to continue. +The `read` action rejects files above 1 MiB with `EXPLORE_FILE_TOO_LARGE` before opening the body. `search` walks directories and reads matching files incrementally under file, raw-entry, directory, per-file, and result-byte ceilings. Its `page` reports partial discovery and oversized-file skips; pass `page.nextCursor` unchanged to continue result pagination. + ### context Context scaffolding and semantic context — the entry point for creating and filling `.context/`. diff --git a/docs/src/content/docs/pt-br/reference/mcp-tools.md b/docs/src/content/docs/pt-br/reference/mcp-tools.md index 856f89f2..eab7b3bb 100644 --- a/docs/src/content/docs/pt-br/reference/mcp-tools.md +++ b/docs/src/content/docs/pt-br/reference/mcp-tools.md @@ -56,12 +56,14 @@ Exploração de arquivos e código — ler arquivos, listar caminhos, buscar con | `symbolTypes` | array | analyze | Extrai `class` \| `interface` \| `function` \| `type` \| `enum` | | `ignore` | array | list, search, getStructure | Padrões a excluir | | `limit` | inteiro, 1–1.000 | list | Arquivos por página; padrão 100 | -| `cursor` | string | list | Cursor opaco de continuação retornado em `page.nextCursor` | +| `cursor` | string | list, search | Cursor opaco de continuação retornado em `page.nextCursor` | **Retorna:** conteúdo de arquivos, arquivos correspondentes, análise de símbolos, resultados de busca ou uma árvore de diretórios. A action `list` transmite os matches em páginas limitadas, sem materializar todo o glob. Envie o `page.nextCursor` retornado, sem alterá-lo, para continuar. +A action `read` rejeita arquivos acima de 1 MiB com `EXPLORE_FILE_TOO_LARGE` antes de abrir o corpo. `search` percorre diretórios e lê arquivos correspondentes incrementalmente, com limites de arquivos, entradas brutas, diretórios, bytes por arquivo e bytes de resultado. Seu `page` informa descoberta parcial e arquivos ignorados por tamanho; envie `page.nextCursor` sem alterações para continuar. + ### context Scaffolding de contexto e contexto semântico — o ponto de entrada para criar e preencher o `.context/`. diff --git a/src/harness/application/actions/exploreActionService.ts b/src/harness/application/actions/exploreActionService.ts index ca3e8a93..a5805136 100644 --- a/src/harness/application/actions/exploreActionService.ts +++ b/src/harness/application/actions/exploreActionService.ts @@ -60,6 +60,7 @@ export class HarnessExploreActionService { fileGlob: params.fileGlob, maxResults: params.maxResults || 50, cwd: params.cwd || this.options.repoPath, + cursor: params.cursor, }); case 'getStructure': return getFileStructureTool.execute({ diff --git a/src/harness/application/context/__tests__/boundedExplore.load.test.ts b/src/harness/application/context/__tests__/boundedExplore.load.test.ts new file mode 100644 index 00000000..6bb39263 --- /dev/null +++ b/src/harness/application/context/__tests__/boundedExplore.load.test.ts @@ -0,0 +1,35 @@ +import * as fsExtra from 'fs-extra'; +import { promises as fs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { readBoundedExploreFile, searchBoundedCode } from '../boundedExplore'; + +const loadDescribe = process.env.DOTCONTEXT_EXPLORE_LOAD_TESTS === '1' ? describe : describe.skip; + +loadDescribe('bounded explore load acceptance', () => { + jest.setTimeout(60_000); + + it('does not materialize a 256 MiB sparse read or matching search file', async () => { + const repo = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'bounded-explore-load-')); + try { + const file = path.join(repo, 'src', 'huge.ts'); + await fsExtra.ensureDir(path.dirname(file)); + const handle = await fs.open(file, 'w'); + await handle.truncate(256 * 1024 * 1024); + await handle.close(); + global.gc?.(); + const before = process.memoryUsage().rss; + + const read = await readBoundedExploreFile(file); + const search = await searchBoundedCode({ cwd: repo, pattern: 'needle' }); + + global.gc?.(); + expect(read).toMatchObject({ errorCode: 'EXPLORE_FILE_TOO_LARGE', contentOmitted: true }); + expect(search.page).toMatchObject({ oversizedFilesSkipped: 1, bytesScanned: 0 }); + expect(process.memoryUsage().rss - before).toBeLessThan(16 * 1024 * 1024); + } finally { + await fsExtra.remove(repo); + } + }); +}); diff --git a/src/harness/application/context/__tests__/boundedExplore.test.ts b/src/harness/application/context/__tests__/boundedExplore.test.ts new file mode 100644 index 00000000..ef8fb570 --- /dev/null +++ b/src/harness/application/context/__tests__/boundedExplore.test.ts @@ -0,0 +1,148 @@ +import * as fsExtra from 'fs-extra'; +import { promises as fs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { + readBoundedExploreFile, + searchBoundedCode, +} from '../boundedExplore'; + +describe('bounded explore I/O', () => { + let repo: string; + + beforeEach(async () => { + repo = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'bounded-explore-')); + }); + + afterEach(async () => { + jest.restoreAllMocks(); + await fsExtra.remove(repo); + }); + + it('preserves small-file read behavior', async () => { + const file = path.join(repo, 'small.ts'); + await fsExtra.writeFile(file, 'export const value = 1;\n'); + + await expect(readBoundedExploreFile(file)).resolves.toMatchObject({ + success: true, + path: file, + content: 'export const value = 1;\n', + size: 24, + }); + }); + + it('rejects a huge sparse file from stat without opening or allocating its body', async () => { + const file = path.join(repo, 'huge.ts'); + const handle = await fs.open(file, 'w'); + await handle.truncate(128 * 1024 * 1024); + await handle.close(); + const open = jest.spyOn(fs, 'open'); + + const result = await readBoundedExploreFile(file, 'utf-8', 1024 * 1024); + + expect(open).not.toHaveBeenCalled(); + expect(result).toMatchObject({ + success: false, + errorCode: 'EXPLORE_FILE_TOO_LARGE', + contentOmitted: true, + size: 128 * 1024 * 1024, + budgetBytes: 1024 * 1024, + }); + expect(result.content).toBeUndefined(); + }); + + it('streams small searches with legacy match/context fields and cursor continuation', async () => { + await fsExtra.outputFile( + path.join(repo, 'src', 'values.ts'), + ['before', 'needle one', 'middle', 'needle two', 'needle three', 'after'].join('\n') + ); + const first = await searchBoundedCode({ + cwd: repo, + pattern: 'needle', + maxResults: 2, + }); + const second = await searchBoundedCode({ + cwd: repo, + pattern: 'needle', + maxResults: 2, + cursor: (first.page as any).nextCursor, + }); + const matches = [...first.matches as any[], ...second.matches as any[]]; + + expect(matches.map(match => match.line)).toEqual([2, 4, 5]); + expect(matches[0]).toMatchObject({ + file: 'src/values.ts', + match: 'needle one', + context: 'before\nneedle one\nmiddle', + }); + expect(first.page).toMatchObject({ hasMore: true, recordsReturned: 2, partial: true }); + expect(second.page).toMatchObject({ hasMore: false, recordsReturned: 1 }); + }); + + it('stops at the raw-entry budget in a huge irrelevant tree', async () => { + for (let index = 0; index < 40; index += 1) { + await fsExtra.outputFile(path.join(repo, 'src', `asset-${index}.txt`), 'irrelevant'); + } + + const result = await searchBoundedCode({ + cwd: repo, + pattern: 'needle', + fileGlob: '**/*.ts', + }, { + maxEntries: 10, + maxDirectories: 4, + maxFiles: 4, + }); + + expect(result.matches).toEqual([]); + expect(result.page).toMatchObject({ + partial: true, + entriesScanned: 10, + discoveryLimitReason: 'entry-limit', + }); + }); + + it('skips a huge matching file without whole-file reads', async () => { + const file = path.join(repo, 'src', 'huge.ts'); + await fsExtra.ensureDir(path.dirname(file)); + const handle = await fs.open(file, 'w'); + await handle.truncate(8 * 1024 * 1024); + await handle.close(); + const readFile = jest.spyOn(fs, 'readFile'); + + const result = await searchBoundedCode({ cwd: repo, pattern: 'needle' }, { + maxFileBytes: 1024, + }); + + expect(readFile).not.toHaveBeenCalled(); + expect(result.matches).toEqual([]); + expect(result.page).toMatchObject({ + partial: true, + oversizedFilesSkipped: 1, + bytesScanned: 0, + }); + }); + + it('caps serialized result bytes and continues from the deferred match', async () => { + await fsExtra.outputFile( + path.join(repo, 'src', 'large-results.ts'), + Array.from({ length: 8 }, (_, index) => `needle-${index}-${'x'.repeat(400)}`).join('\n') + ); + const first = await searchBoundedCode({ cwd: repo, pattern: 'needle', maxResults: 100 }, { + maxResultBytes: 1024, + }); + const second = await searchBoundedCode({ + cwd: repo, + pattern: 'needle', + maxResults: 100, + cursor: (first.page as any).nextCursor, + }, { + maxResultBytes: 1024, + }); + + expect((first.page as any).resultBytes).toBeLessThanOrEqual(1024); + expect(first.page).toMatchObject({ hasMore: true, pageByteLimited: true }); + expect((second.matches as any[])[0].line).toBe((first.matches as any[]).length + 1); + }); +}); diff --git a/src/harness/application/context/boundedExplore.ts b/src/harness/application/context/boundedExplore.ts new file mode 100644 index 00000000..da88ca86 --- /dev/null +++ b/src/harness/application/context/boundedExplore.ts @@ -0,0 +1,339 @@ +import { createReadStream, promises as fs } from 'fs'; +import * as path from 'path'; +import * as readline from 'readline'; +import { minimatch } from 'minimatch'; + +import { + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, +} from '../history/runtimeHistory'; + +export const DEFAULT_EXPLORE_FILE_BYTES = 1024 * 1024; +export const MAX_EXPLORE_SEARCH_FILES = 5_000; +export const MAX_EXPLORE_SEARCH_ENTRIES = 20_000; +export const MAX_EXPLORE_SEARCH_DIRECTORIES = 2_000; +export const MAX_EXPLORE_SEARCH_RESULT_BYTES = 512 * 1024; + +export interface BoundedExploreReadResult extends Record { + success: boolean; + path: string; + content?: string; + size?: number; + errorCode?: 'EXPLORE_FILE_TOO_LARGE'; + error?: string; + budgetBytes?: number; + contentOmitted?: boolean; +} + +export interface BoundedExploreSearchOptions { + maxFiles?: number; + maxEntries?: number; + maxDirectories?: number; + maxFileBytes?: number; + maxResultBytes?: number; +} + +export interface BoundedExploreSearchInput { + pattern: string; + fileGlob?: string; + maxResults?: number; + cwd: string; + cursor?: string; +} + +interface SearchCursor { + fileOffset: number; + lineOffset: number; +} + +interface DiscoveryMetrics { + entriesScanned: number; + directoriesScanned: number; + matchingFiles: number; + partial: boolean; + limitReason?: 'entry-limit' | 'directory-limit' | 'file-limit'; +} + +interface SearchMatch { + file: string; + line: number; + match: string; + context: string; +} + +const IGNORED_DIRECTORY_NAMES = new Set(['node_modules', '.git', 'dist', 'build']); +const DEFAULT_SEARCH_GLOB = '**/*.{ts,tsx,js,jsx,py,go,rs,java}'; + +function positiveLimit(value: number | undefined, fallback: number, maximum: number): number { + if (value === undefined) return fallback; + if (!Number.isInteger(value) || value < 1 || value > maximum) { + throw new RangeError(`explore search limit must be between 1 and ${maximum}`); + } + return value; +} + +function typedFileTooLarge(filePath: string, size: number, budgetBytes: number): BoundedExploreReadResult { + return { + success: false, + path: filePath, + size, + budgetBytes, + contentOmitted: true, + errorCode: 'EXPLORE_FILE_TOO_LARGE', + error: 'The requested file exceeds the bounded explore read budget.', + }; +} + +/** Read at most budget + 1 bytes so a file growth race cannot bypass stat. */ +export async function readBoundedExploreFile( + filePath: string, + encoding: BufferEncoding = 'utf-8', + budgetBytes = DEFAULT_EXPLORE_FILE_BYTES +): Promise { + budgetBytes = positiveLimit( + budgetBytes, + DEFAULT_EXPLORE_FILE_BYTES, + DEFAULT_EXPLORE_FILE_BYTES + ); + const stat = await fs.stat(filePath); + if (stat.size > budgetBytes) return typedFileTooLarge(filePath, stat.size, budgetBytes); + + const handle = await fs.open(filePath, 'r'); + try { + const buffer = Buffer.allocUnsafe(budgetBytes + 1); + let totalBytes = 0; + while (totalBytes < buffer.length) { + const read = await handle.read(buffer, totalBytes, buffer.length - totalBytes, totalBytes); + if (read.bytesRead === 0) break; + totalBytes += read.bytesRead; + } + if (totalBytes > budgetBytes) { + return typedFileTooLarge(filePath, Math.max(stat.size, totalBytes), budgetBytes); + } + const content = buffer.subarray(0, totalBytes).toString(encoding); + if (Buffer.byteLength(content, 'utf8') > budgetBytes) { + return typedFileTooLarge(filePath, totalBytes, budgetBytes); + } + return { success: true, content, path: filePath, size: totalBytes }; + } finally { + await handle.close(); + } +} + +async function* discoverSearchFiles( + cwd: string, + fileGlob: string, + limits: Required>, + metrics: DiscoveryMetrics +): AsyncGenerator<{ absolutePath: string; relativePath: string; fileOffset: number }> { + const queue: string[] = [cwd]; + let directoriesQueued = 1; + + while (queue.length > 0) { + if (metrics.directoriesScanned >= limits.maxDirectories) { + metrics.partial = true; + metrics.limitReason = 'directory-limit'; + return; + } + const directoryPath = queue.shift()!; + metrics.directoriesScanned += 1; + let directory; + try { + directory = await fs.opendir(directoryPath); + } catch { + continue; + } + for await (const entry of directory) { + if (metrics.entriesScanned >= limits.maxEntries) { + metrics.partial = true; + metrics.limitReason = 'entry-limit'; + return; + } + metrics.entriesScanned += 1; + const absolutePath = path.join(directoryPath, entry.name); + if (entry.isDirectory()) { + if (IGNORED_DIRECTORY_NAMES.has(entry.name)) continue; + if (directoriesQueued >= limits.maxDirectories) { + metrics.partial = true; + metrics.limitReason = 'directory-limit'; + continue; + } + directoriesQueued += 1; + queue.push(absolutePath); + continue; + } + if (!entry.isFile()) continue; + const relativePath = path.relative(cwd, absolutePath).split(path.sep).join('/'); + if (!minimatch(relativePath, fileGlob, { dot: true })) continue; + if (metrics.matchingFiles >= limits.maxFiles) { + metrics.partial = true; + metrics.limitReason = 'file-limit'; + return; + } + const fileOffset = metrics.matchingFiles; + metrics.matchingFiles += 1; + yield { absolutePath, relativePath, fileOffset }; + } + } +} + +/** Search line-by-line over a bounded, streaming repository discovery. */ +export async function searchBoundedCode( + input: BoundedExploreSearchInput, + options: BoundedExploreSearchOptions = {} +): Promise> { + const startedAt = Date.now(); + const cwd = path.resolve(input.cwd); + const fileGlob = input.fileGlob || DEFAULT_SEARCH_GLOB; + const maxResults = positiveLimit(input.maxResults, 50, 1_000); + const limits = { + maxFiles: positiveLimit(options.maxFiles, MAX_EXPLORE_SEARCH_FILES, MAX_EXPLORE_SEARCH_FILES), + maxEntries: positiveLimit(options.maxEntries, MAX_EXPLORE_SEARCH_ENTRIES, MAX_EXPLORE_SEARCH_ENTRIES), + maxDirectories: positiveLimit( + options.maxDirectories, + MAX_EXPLORE_SEARCH_DIRECTORIES, + MAX_EXPLORE_SEARCH_DIRECTORIES + ), + }; + const maxFileBytes = positiveLimit( + options.maxFileBytes, + DEFAULT_EXPLORE_FILE_BYTES, + DEFAULT_EXPLORE_FILE_BYTES + ); + const maxResultBytes = positiveLimit( + options.maxResultBytes, + MAX_EXPLORE_SEARCH_RESULT_BYTES, + MAX_EXPLORE_SEARCH_RESULT_BYTES + ); + const binding = queryBinding({ cwd, fileGlob, pattern: input.pattern }); + const boundary = decodeHistoryCursor(input.cursor, 'explore-search', binding) + ?? { fileOffset: 0, lineOffset: 0 }; + const regex = new RegExp(input.pattern, 'gm'); + const matches: SearchMatch[] = []; + const metrics: DiscoveryMetrics = { + entriesScanned: 0, + directoriesScanned: 0, + matchingFiles: 0, + partial: false, + }; + let filesScanned = 0; + let linesScanned = 0; + let bytesScanned = 0; + let oversizedFilesSkipped = 0; + let hasMore = false; + let pageByteLimited = false; + let nextCursor: string | undefined; + let returnedBytes = 2; + + outer: for await (const file of discoverSearchFiles(cwd, fileGlob, limits, metrics)) { + if (file.fileOffset < boundary.fileOffset) continue; + let stat; + try { + stat = await fs.stat(file.absolutePath); + } catch { + continue; + } + if (stat.size > maxFileBytes) { + oversizedFilesSkipped += 1; + metrics.partial = true; + continue; + } + filesScanned += 1; + const startLine = file.fileOffset === boundary.fileOffset ? boundary.lineOffset : 0; + const stream = createReadStream(file.absolutePath, { + encoding: 'utf8', + highWaterMark: 64 * 1024, + // Guard a growth race after stat: the stream itself can never consume + // more than the per-file budget. + start: 0, + end: maxFileBytes - 1, + }); + const lines = readline.createInterface({ input: stream, crlfDelay: Infinity }); + let lineNumber = 0; + let previousLine: string | undefined; + let pending: { lineNumber: number; line: string; previousLine?: string } | undefined; + const appendPending = (nextLine?: string): boolean => { + if (!pending) return true; + const context = [pending.previousLine, pending.line, nextLine] + .filter((value): value is string => value !== undefined) + .join('\n') + .slice(0, 500); + const candidate: SearchMatch = { + file: file.relativePath, + line: pending.lineNumber, + match: pending.line.trim().slice(0, 200), + context, + }; + const candidateBytes = Buffer.byteLength(JSON.stringify(candidate), 'utf8'); + const candidateTotal = returnedBytes + candidateBytes + (matches.length > 0 ? 1 : 0); + if (matches.length === maxResults || candidateTotal > maxResultBytes) { + hasMore = true; + pageByteLimited = matches.length < maxResults; + nextCursor = encodeHistoryCursor('explore-search', binding, { + fileOffset: file.fileOffset, + lineOffset: pending.lineNumber - 1, + }); + return false; + } + matches.push(candidate); + returnedBytes = candidateTotal; + pending = undefined; + return true; + }; + try { + for await (const line of lines) { + lineNumber += 1; + bytesScanned += Buffer.byteLength(line, 'utf8') + 1; + if (lineNumber <= startLine) { + previousLine = line; + continue; + } + linesScanned += 1; + if (pending && !appendPending(line)) break outer; + regex.lastIndex = 0; + if (regex.test(line)) { + pending = { lineNumber, line, previousLine }; + } + previousLine = line; + } + if (pending && !appendPending()) break outer; + } finally { + lines.close(); + stream.destroy(); + } + const finalSize = await fs.stat(file.absolutePath).then(value => value.size).catch(() => stat.size); + if (finalSize > maxFileBytes) { + oversizedFilesSkipped += 1; + metrics.partial = true; + } + } + + const partial = hasMore || metrics.partial || oversizedFilesSkipped > 0; + return { + success: true, + pattern: input.pattern, + matches, + totalMatches: matches.length, + truncated: partial, + page: { + nextCursor, + hasMore, + recordsReturned: matches.length, + filesScanned, + linesScanned, + bytesScanned, + resultBytes: returnedBytes, + resultByteBudget: maxResultBytes, + pageByteLimited, + entriesScanned: metrics.entriesScanned, + directoriesScanned: metrics.directoriesScanned, + matchingFilesScanned: metrics.matchingFiles, + oversizedFilesSkipped, + discoveryLimitReason: metrics.limitReason, + partial, + cursorVersion: 1, + durationMs: Date.now() - startedAt, + }, + }; +} diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index f125f084..67b054bf 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -36,6 +36,10 @@ import { RUNTIME_HISTORY_LIMITS, type RuntimeHistoryPage, } from '../history/runtimeHistory'; +import { + readBoundedExploreFile, + searchBoundedCode, +} from './boundedExplore'; type ToolContext = unknown; @@ -324,20 +328,23 @@ export async function cleanupSharedContext(): Promise { } export const readFileTool = createInternalTool< - { filePath: string; encoding?: 'utf-8' | 'ascii' | 'binary' }, - { success: boolean; content?: string; path: string; size?: number; error?: string } + { filePath: string; encoding?: 'utf-8' | 'ascii' | 'binary'; maxBytes?: number }, + { + success: boolean; + content?: string; + path: string; + size?: number; + errorCode?: string; + error?: string; + budgetBytes?: number; + contentOmitted?: boolean; + } >( 'Read the contents of a file from the filesystem', async (input) => { const { filePath, encoding = 'utf-8' } = input; try { - const content = await fs.readFile(filePath, encoding as BufferEncoding); - return { - success: true, - content, - path: filePath, - size: content.length - }; + return await readBoundedExploreFile(filePath, encoding as BufferEncoding, input.maxBytes); } catch (error) { return { success: false, @@ -517,52 +524,20 @@ export const getFileStructureTool = createInternalTool< ); export const searchCodeTool = createInternalTool< - { pattern: string; fileGlob?: string; maxResults?: number; cwd?: string }, + { pattern: string; fileGlob?: string; maxResults?: number; cwd?: string; cursor?: string }, Record >( 'Search for code patterns across files using regex', async (input) => { - const { pattern, fileGlob, maxResults = 50, cwd } = input; + const { pattern, fileGlob, maxResults = 50, cwd, cursor } = input; try { - const files = await glob(fileGlob || '**/*.{ts,tsx,js,jsx,py,go,rs,java}', { + return await searchBoundedCode({ + pattern, + fileGlob, + maxResults, cwd: cwd || process.cwd(), - ignore: ['node_modules/**', '.git/**', 'dist/**', 'build/**'], - absolute: true + cursor, }); - - const regex = new RegExp(pattern, 'gm'); - const matches: Array<{ file: string; line: number; match: string; context: string }> = []; - - for (const file of files) { - if (matches.length >= maxResults) break; - - try { - const content = await fs.readFile(file, 'utf-8'); - const lines = content.split('\n'); - - for (let index = 0; index < lines.length && matches.length < maxResults; index++) { - if (regex.test(lines[index])) { - matches.push({ - file: path.relative(cwd || process.cwd(), file), - line: index + 1, - match: lines[index].trim().slice(0, 200), - context: lines.slice(Math.max(0, index - 1), index + 2).join('\n').slice(0, 500) - }); - } - regex.lastIndex = 0; - } - } catch { - // Skip unreadable files. - } - } - - return { - success: true, - pattern, - matches, - totalMatches: matches.length, - truncated: matches.length >= maxResults - }; } catch (error) { return { success: false, diff --git a/src/harness/application/context/index.ts b/src/harness/application/context/index.ts index e1c71169..a755a7b5 100644 --- a/src/harness/application/context/index.ts +++ b/src/harness/application/context/index.ts @@ -1,4 +1,5 @@ export * from './contextService'; export * from './contextTools'; +export * from './boundedExplore'; export * as intelligence from './intelligence'; export * as scaffolding from './scaffolding'; diff --git a/src/mcp/README.md b/src/mcp/README.md index ead73f22..770c0c9d 100644 --- a/src/mcp/README.md +++ b/src/mcp/README.md @@ -38,6 +38,8 @@ The growing harness lists (`listSessions`, `listTraces`, `listArtifacts`, `listT `explore` action `list` is also paginated: it defaults to 100 files, accepts at most 1,000, and returns an opaque `page.nextCursor` when more matches exist. +`explore` action `read` rejects files above 1 MiB from metadata before opening their bodies. Action `search` streams a bounded directory walk and bounded files line-by-line, caps result bytes, reports discovery/file skips in `page`, and returns `page.nextCursor` when another result page is available. + ### Dedicated Workflow Tools (5) | Tool | Description | diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index b4150381..b68bf8cf 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -155,10 +155,10 @@ export class AIContextMCPServer { // Gateway 1: explore - File and code exploration this.server.registerTool('explore', { description: `File and code exploration. Actions: -- read: Read file contents (params: filePath, encoding?) +- read: Read bounded file contents (params: filePath, encoding?) - list: List files matching pattern (params: pattern, cwd?, ignore?, limit?, cursor?) - analyze: Analyze symbols in a file (params: filePath, symbolTypes?) -- search: Search code with regex (params: pattern, fileGlob?, maxResults?, cwd?) +- search: Search code with bounded streaming (params: pattern, fileGlob?, maxResults?, cwd?, cursor?) - getStructure: Get directory structure (params: rootPath?, maxDepth?, includePatterns?)`, inputSchema: { action: z.enum(['read', 'list', 'analyze', 'search', 'getStructure']) @@ -176,7 +176,7 @@ export class AIContextMCPServer { limit: MCP_LIST_LIMIT_SCHEMA.optional() .describe('(list) Maximum files per page'), cursor: mcpString().max(MCP_INPUT_LIMITS.cursorLength).optional() - .describe('(list) Opaque continuation cursor'), + .describe('(list, search) Opaque continuation cursor'), symbolTypes: mcpArray(z.enum(['class', 'interface', 'function', 'type', 'enum'])).optional() .describe('(analyze) Types of symbols to extract'), fileGlob: mcpPattern().optional() From 08d1ccc7f60a03d57f059dc9d3d9aa11663273cd Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 14:10:47 -0300 Subject: [PATCH 26/39] perf: bound raw repository traversal --- package-lock.json | 1 + package.json | 1 + .../f-05-shared-semantic-analysis.md | 3 +- .../__tests__/codebaseAnalyzer.test.ts | 78 ++---- .../adapters/out/semantic/codebaseAnalyzer.ts | 66 ++++- .../adapters/out/semantic/contextBuilder.ts | 2 + .../out/semantic/semanticSnapshotService.ts | 21 +- src/harness/adapters/out/semantic/types.ts | 4 + .../application/context/analysisBundle.ts | 2 + .../application/context/contextTools.ts | 7 +- .../generators/agents/agentGenerator.ts | 2 +- .../documentation/documentationGenerator.ts | 7 +- src/types.ts | 7 + src/utils/__tests__/fileMapper.test.ts | 145 ++++++++-- src/utils/fileMapper.ts | 251 +++++++++++------- 15 files changed, 403 insertions(+), 194 deletions(-) diff --git a/package-lock.json b/package-lock.json index ad8e9dc7..421f1183 100644 --- a/package-lock.json +++ b/package-lock.json @@ -20,6 +20,7 @@ "glob": "^13.0.6", "ignore": "^7.0.5", "js-yaml": "^4.1.1", + "minimatch": "^10.2.5", "ora": "^5.4.1", "semver": "^7.6.3", "zod": "^4.3.5" diff --git a/package.json b/package.json index 21cada27..ca4c2838 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "glob": "^13.0.6", "ignore": "^7.0.5", "js-yaml": "^4.1.1", + "minimatch": "^10.2.5", "ora": "^5.4.1", "semver": "^7.6.3", "zod": "^4.3.5" diff --git a/specs/performance/f-05-shared-semantic-analysis.md b/specs/performance/f-05-shared-semantic-analysis.md index 97a5a9ff..a0da6673 100644 --- a/specs/performance/f-05-shared-semantic-analysis.md +++ b/specs/performance/f-05-shared-semantic-analysis.md @@ -58,6 +58,8 @@ Defaults: | code files parsed | 5,000 | | total source bytes parsed | 256 MiB | | single source file | 2 MiB | +| directories scanned | 10,000 (absolute maximum 50,000) | +| raw directory entries scanned | 100,000 (absolute maximum 500,000) | | file analysis concurrency | 16 | | fingerprint attempts | 2 | @@ -118,4 +120,3 @@ Introduce AnalysisBundle behind the existing context service while legacy direct ## Observability Record discovery, parsing, fingerprint, generation and publication durations; file and byte counts; cache hits; skipped file reasons; partial status; and stabilization attempts. - diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index ca4bfefd..0f8ea65b 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -59,32 +59,6 @@ jest.mock('../lsp/lspLayer', () => ({ })), })); -// Mock glob -jest.mock('glob', () => { - const glob = jest.fn().mockImplementation(async (pattern: string, options: { cwd: string }) => { - // Return mock files based on the pattern - if (String(pattern).includes('ts')) { - return [ - path.join(options.cwd, 'src', 'services', 'userService.ts'), - path.join(options.cwd, 'src', 'controllers', 'userController.ts'), - path.join(options.cwd, 'src', 'models', 'user.ts'), - path.join(options.cwd, 'src', 'utils', 'helper.ts'), - path.join(options.cwd, 'src', 'index.ts'), - path.join(options.cwd, 'src', 'main.ts'), - ]; - } - return []; - }); - const globStream = jest.fn((pattern: string, options: { cwd: string }) => { - const iterator = (async function* () { - for (const file of await glob(pattern, options)) yield file; - })() as any; - iterator.destroy = jest.fn(); - return iterator; - }); - return { glob, globStream }; -}); - function createTempOutput(prefix: string): Promise { return fs.mkdtemp(path.join(os.tmpdir(), prefix)); } @@ -173,10 +147,24 @@ describe('CodebaseAnalyzer', () => { maxFiles: 5000, maxTotalBytes: 256 * 1024 * 1024, maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, concurrency: 16, }); }); + it('absolute-clamps configurable repository scan limits', async () => { + const bundle = await new CodebaseAnalyzer({ + maxDirectoriesScanned: Number.MAX_SAFE_INTEGER, + maxEntriesScanned: Number.MAX_SAFE_INTEGER, + }).analyzeBundle(tempDir); + + expect(bundle.limits.maxDirectoriesScanned).toBe(50_000); + expect(bundle.limits.maxEntriesScanned).toBe(500_000); + expect(bundle.metrics.directoriesScanned).toBeGreaterThan(0); + expect(bundle.metrics.entriesScanned).toBeGreaterThan(0); + }); + it('bounds a 3000-file-equivalent analysis and reports maximum in-flight work', async () => { const files = Array.from({ length: 3000 }, (_, index) => path.join(tempDir, 'scale', `file-${index}.ts`) @@ -340,19 +328,6 @@ describe('CodebaseAnalyzer', () => { }); it('should find entry points based on file names', async () => { - // Override glob to return an entry point file - const { glob } = require('glob'); - glob.mockImplementationOnce(async (pattern: string, options: { cwd: string }) => { - if (String(pattern).includes('ts')) { - return [ - path.join(options.cwd, 'src', 'index.ts'), - path.join(options.cwd, 'src', 'main.ts'), - path.join(options.cwd, 'src', 'services', 'userService.ts'), - ]; - } - return []; - }); - const analyzer = new CodebaseAnalyzer({ useLSP: false }); const context = await analyzer.analyze(tempDir); @@ -535,16 +510,10 @@ describe('CodebaseAnalyzer', () => { describe('options handling', () => { it('should respect maxFiles option', async () => { - const { glob } = require('glob'); - const manyFiles = Array.from({ length: 100 }, (_, i) => - path.join(tempDir, `file${i}.ts`) - ); - glob.mockImplementationOnce(async () => manyFiles); - - const analyzer = new CodebaseAnalyzer({ useLSP: false, maxFiles: 10 }); + const analyzer = new CodebaseAnalyzer({ useLSP: false, maxFiles: 2 }); const context = await analyzer.analyze(tempDir); - expect(context.stats.totalFiles).toBeLessThanOrEqual(10); + expect(context.stats.totalFiles).toBe(2); }); it('should respect languages option', async () => { @@ -572,25 +541,14 @@ describe('CodebaseAnalyzer', () => { }); it('should respect include patterns', async () => { - const { glob } = require('glob'); - glob.mockImplementationOnce(async (pattern: string, options: { cwd: string }) => { - return [ - path.join(options.cwd, 'src', 'services', 'userService.ts'), - path.join(options.cwd, 'src', 'controllers', 'userController.ts'), - path.join(options.cwd, 'tests', 'testFile.ts'), - ]; - }); - const analyzer = new CodebaseAnalyzer({ useLSP: false, - include: ['src'], + include: ['services'], }); const context = await analyzer.analyze(tempDir); - // Files should be filtered to only include 'src' paths - // Due to mock implementation, we check it doesn't error - expect(context).toBeDefined(); + expect(context.stats.totalFiles).toBe(1); }); }); }); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 3219f939..86cdaba0 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -7,8 +7,11 @@ import * as path from 'path'; import * as fs from 'fs/promises'; -import type { FileInfo } from '../../../../types'; -import { FileMapper } from '../../../../utils/fileMapper'; +import type { FileInfo, RepoDiscoveryMetrics, RepoStructure } from '../../../../types'; +import { + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS, + FileMapper, +} from '../../../../utils/fileMapper'; import { TreeSitterLayer } from './treeSitter/treeSitterLayer'; import { LSPLayer } from './lsp/lspLayer'; import { @@ -38,6 +41,8 @@ const DEFAULT_OPTIONS: Required = { maxFiles: 5000, maxTotalBytes: 256 * 1024 * 1024, maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, concurrency: 16, cacheEnabled: true, }; @@ -46,6 +51,8 @@ export interface AnalysisLimits { maxFiles: number; maxTotalBytes: number; maxFileBytes: number; + maxDirectoriesScanned: number; + maxEntriesScanned: number; concurrency: number; } @@ -53,6 +60,8 @@ export type AnalysisSkipReason = | 'file-limit' | 'total-byte-limit' | 'file-too-large' + | 'directory-limit' + | 'entry-limit' | 'stat-failed'; export interface SkippedAnalysisFile { @@ -62,6 +71,8 @@ export interface SkippedAnalysisFile { } export interface AnalysisMetrics { + directoriesScanned: number; + entriesScanned: number; filesDiscovered: number; filesParsed: number; fileReads: number; @@ -90,6 +101,7 @@ export interface SemanticAnalysisBundle { } type DiscoveredAnalysisFile = string | Pick; +type SemanticDiscoveryInput = DiscoveredAnalysisFile[] | RepoStructure; export class CodebaseAnalyzer { private treeSitter: TreeSitterLayer; @@ -102,6 +114,14 @@ export class CodebaseAnalyzer { this.options.maxFiles = Math.max(0, this.options.maxFiles); this.options.maxTotalBytes = Math.max(0, this.options.maxTotalBytes); this.options.maxFileBytes = Math.max(0, this.options.maxFileBytes); + this.options.maxDirectoriesScanned = Math.min( + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS.maxDirectoriesScanned, + Math.max(0, Math.floor(this.options.maxDirectoriesScanned)) + ); + this.options.maxEntriesScanned = Math.min( + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS.maxEntriesScanned, + Math.max(0, Math.floor(this.options.maxEntriesScanned)) + ); this.options.concurrency = Math.max(1, this.options.concurrency); // Create LSPLayer if LSP mode is enabled @@ -116,9 +136,9 @@ export class CodebaseAnalyzer { async analyzeBundle( projectPath: string, - discoveredFiles?: DiscoveredAnalysisFile[] + discoveryInput?: SemanticDiscoveryInput ): Promise { - const result = await this.analyzeProject(projectPath, discoveredFiles); + const result = await this.analyzeProject(projectPath, discoveryInput); const functionalStartedAt = Date.now(); const functionalPatterns = this.detectFunctionalPatternsFromAnalyses( result.files, @@ -137,7 +157,7 @@ export class CodebaseAnalyzer { }; } - private async analyzeProject(projectPath: string, discoveredFiles?: DiscoveredAnalysisFile[]): Promise<{ + private async analyzeProject(projectPath: string, discoveryInput?: SemanticDiscoveryInput): Promise<{ context: SemanticContext; files: string[]; fileAnalyses: Map; @@ -147,6 +167,8 @@ export class CodebaseAnalyzer { }> { const startTime = Date.now(); const metrics: AnalysisMetrics = { + directoriesScanned: 0, + entriesScanned: 0, filesDiscovered: 0, filesParsed: 0, fileReads: 0, @@ -166,10 +188,12 @@ export class CodebaseAnalyzer { // 1. Select source files once, applying byte and count budgets before parsing. const discoveryStartedAt = Date.now(); - const discovery = discoveredFiles - ? { files: this.filterCodeFiles(projectPath, discoveredFiles), skipped: [] } + const discovery = discoveryInput + ? this.discoveryFromInput(projectPath, discoveryInput) : await this.findCodeFiles(projectPath); const candidates = discovery.files; + metrics.directoriesScanned = discovery.metrics?.directoriesScanned ?? 0; + metrics.entriesScanned = discovery.metrics?.entriesScanned ?? 0; metrics.filesDiscovered = candidates.length; const selected = await this.selectFilesWithinLimits(candidates); const files = selected.files; @@ -223,6 +247,8 @@ export class CodebaseAnalyzer { maxFiles: this.options.maxFiles, maxTotalBytes: this.options.maxTotalBytes, maxFileBytes: this.options.maxFileBytes, + maxDirectoriesScanned: this.options.maxDirectoriesScanned, + maxEntriesScanned: this.options.maxEntriesScanned, concurrency: this.options.concurrency, }; } @@ -230,12 +256,15 @@ export class CodebaseAnalyzer { private async findCodeFiles(projectPath: string): Promise<{ files: Array<{ path: string; size?: number }>; skipped: SkippedAnalysisFile[]; + metrics?: RepoDiscoveryMetrics; }> { try { const structure = await new FileMapper(this.options.exclude, { maxFiles: this.options.maxFiles, maxTotalBytes: this.options.maxTotalBytes, maxFileBytes: this.options.maxFileBytes, + maxDirectoriesScanned: this.options.maxDirectoriesScanned, + maxEntriesScanned: this.options.maxEntriesScanned, }).mapRepository(projectPath); return { files: this.filterCodeFiles(projectPath, structure.files), @@ -244,12 +273,35 @@ export class CodebaseAnalyzer { reason: skip.reason, size: skip.size, })), + metrics: structure.discoveryMetrics, }; } catch { return { files: [], skipped: [] }; } } + private discoveryFromInput( + projectPath: string, + input: SemanticDiscoveryInput + ): { + files: Array<{ path: string; size?: number }>; + skipped: SkippedAnalysisFile[]; + metrics?: RepoDiscoveryMetrics; + } { + if (Array.isArray(input)) { + return { files: this.filterCodeFiles(projectPath, input), skipped: [] }; + } + return { + files: this.filterCodeFiles(projectPath, input.files), + skipped: (input.skipped ?? []).map((skip) => ({ + file: skip.file, + reason: skip.reason, + size: skip.size, + })), + metrics: input.discoveryMetrics, + }; + } + private filterCodeFiles( projectPath: string, discoveredFiles: DiscoveredAnalysisFile[] diff --git a/src/harness/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index 5b872759..db8f9fb8 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -37,6 +37,8 @@ const DEFAULT_OPTIONS: Required = { maxFiles: 5000, maxTotalBytes: 256 * 1024 * 1024, maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, concurrency: 16, cacheEnabled: true, maxSymbolsPerCategory: 50, diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index 92032cba..2c5f8b94 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -240,6 +240,25 @@ export class SemanticSnapshotService { Math.floor(fingerprintLimits.maxFileBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxFileBytes) ) ), + maxDirectoriesScanned: Math.min( + DEFAULT_FILE_MAPPING_LIMITS.maxDirectoriesScanned, + Math.max( + 0, + Math.floor( + fingerprintLimits.maxDirectoriesScanned ?? + DEFAULT_FILE_MAPPING_LIMITS.maxDirectoriesScanned + ) + ) + ), + maxEntriesScanned: Math.min( + DEFAULT_FILE_MAPPING_LIMITS.maxEntriesScanned, + Math.max( + 0, + Math.floor( + fingerprintLimits.maxEntriesScanned ?? DEFAULT_FILE_MAPPING_LIMITS.maxEntriesScanned + ) + ) + ), }; } @@ -522,7 +541,7 @@ export class SemanticSnapshotService { analyzer = new CodebaseAnalyzer(options.analyzerOptions); const bundle = await analyzer.analyzeBundle( repoStructure.rootPath, - repoStructure.files + repoStructure ); semantics ??= bundle.context; functionalPatterns ??= bundle.functionalPatterns; diff --git a/src/harness/adapters/out/semantic/types.ts b/src/harness/adapters/out/semantic/types.ts index 3f7ad44e..e542b556 100644 --- a/src/harness/adapters/out/semantic/types.ts +++ b/src/harness/adapters/out/semantic/types.ts @@ -196,6 +196,10 @@ export interface AnalyzerOptions { maxFileBytes?: number; /** Maximum number of file analyses running concurrently. */ concurrency?: number; + /** Maximum directories opened while discovering repository files. */ + maxDirectoriesScanned?: number; + /** Maximum raw directory entries inspected during discovery. */ + maxEntriesScanned?: number; cacheEnabled?: boolean; } diff --git a/src/harness/application/context/analysisBundle.ts b/src/harness/application/context/analysisBundle.ts index f08d3ee4..34f6e784 100644 --- a/src/harness/application/context/analysisBundle.ts +++ b/src/harness/application/context/analysisBundle.ts @@ -13,6 +13,8 @@ export const DEFAULT_ANALYSIS_LIMITS: AnalysisLimits = Object.freeze({ maxFiles: 5_000, maxTotalBytes: 256 * 1024 * 1024, maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, concurrency: 16, }); diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 46cd9211..d171f198 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -683,7 +683,7 @@ export const initializeContextTool = createInternalTool< semanticFingerprint = fingerprintMetrics.fingerprint; semanticBundle = await analyzer.analyzeBundle( resolvedRepoPath, - repoStructure.files + repoStructure ); } catch { semanticBundle = undefined; @@ -703,7 +703,6 @@ export const initializeContextTool = createInternalTool< } if (semanticBundle && semanticFingerprint && fingerprintMetrics) { - const discoverySkipped = repoStructure.skipped ?? []; analysisBundle = { repoPath: resolvedRepoPath, discoveredFiles: semanticBundle.files, @@ -713,8 +712,8 @@ export const initializeContextTool = createInternalTool< stackInfo: detectedStackInfo, repoFingerprint: semanticFingerprint, limits: semanticBundle.limits, - partial: !!repoStructure.partial || semanticBundle.partial, - skipped: [...discoverySkipped, ...semanticBundle.skipped], + partial: semanticBundle.partial, + skipped: semanticBundle.skipped, metrics: { ...semanticBundle.metrics, fingerprint: { diff --git a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts index 53f89e67..6650557d 100644 --- a/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts @@ -131,7 +131,7 @@ export class AgentGenerator { try { semantics = (await this.analyzer.analyzeBundle( repoStructure.rootPath, - repoStructure.files.map((file) => file.path) + repoStructure )).context; GeneratorUtils.logProgress( `Analyzed ${semantics.stats.totalFiles} files, found ${semantics.stats.totalSymbols} symbols`, diff --git a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts index 43b99b89..ca202cf0 100644 --- a/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts +++ b/src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts @@ -106,10 +106,13 @@ export class DocumentationGenerator { GeneratorUtils.logProgress('[metric] semantic.legacy_bundle_build=1', verbose); this.analyzer = new CodebaseAnalyzer({ cacheEnabled: config.cacheEnabled ?? true }); try { - snapshotFingerprint = await snapshotService!.captureRepoFingerprint(repoStructure.rootPath); + snapshotFingerprint = await snapshotService!.captureRepoFingerprint( + repoStructure.rootPath, + repoStructure + ); const bundle = await this.analyzer.analyzeBundle( repoStructure.rootPath, - repoStructure.files + repoStructure ); semantics = bundle.context; functionalPatterns = bundle.functionalPatterns; diff --git a/src/types.ts b/src/types.ts index a2dbf5cf..bae254b2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -20,6 +20,8 @@ export type RepoDiscoverySkipReason = | 'file-limit' | 'total-byte-limit' | 'file-too-large' + | 'directory-limit' + | 'entry-limit' | 'stat-failed'; export interface RepoDiscoverySkip { @@ -31,6 +33,11 @@ export interface RepoDiscoverySkip { } export interface RepoDiscoveryMetrics { + /** Raw directory entries inspected, including irrelevant files. */ + entriesScanned: number; + /** Directories opened by the bounded repository walker. */ + directoriesScanned: number; + /** Relevant file candidates considered after path filtering. */ entriesVisited: number; statCalls: number; stoppedEarly: boolean; diff --git a/src/utils/__tests__/fileMapper.test.ts b/src/utils/__tests__/fileMapper.test.ts index a67a1eb9..9520f783 100644 --- a/src/utils/__tests__/fileMapper.test.ts +++ b/src/utils/__tests__/fileMapper.test.ts @@ -2,19 +2,32 @@ import * as fs from 'fs-extra'; import { promises as nativeFs } from 'fs'; import * as os from 'os'; import * as path from 'path'; -import { globStream } from 'glob'; -import { FileMapper } from '../fileMapper'; -jest.mock('glob', () => ({ globStream: jest.fn() })); +import { FileMapper } from '../fileMapper'; -const mockedGlobStream = globStream as jest.MockedFunction; +type FakeEntry = { + name: string; + isDirectory: () => boolean; + isFile: () => boolean; +}; + +function fakeEntry(name: string, type: 'file' | 'directory' = 'file'): FakeEntry { + return { + name, + isDirectory: () => type === 'directory', + isFile: () => type === 'file', + }; +} -function entryStream(entries: string[]): AsyncIterable & { destroy: jest.Mock } { - const iterator = (async function* () { - for (const entry of entries) yield entry; - })() as unknown as AsyncIterable & { destroy: jest.Mock }; - iterator.destroy = jest.fn(); - return iterator; +function fakeDirectory(entries: FakeEntry[]): { + read: jest.Mock; + close: jest.Mock; +} { + let index = 0; + return { + read: jest.fn(async () => entries[index++] ?? null), + close: jest.fn(async () => undefined), + }; } function mockFileStats(size: number): jest.Mock { @@ -35,21 +48,22 @@ describe('FileMapper bounded discovery', () => { afterEach(async () => { jest.restoreAllMocks(); - mockedGlobStream.mockReset(); await fs.remove(repoPath); }); - it('stops before statting or materializing entries beyond the file cap', async () => { - const stream = entryStream( - Array.from({ length: 5_100 }, (_, index) => `src/file-${index}.ts`) + it('stops before statting file candidates beyond the file cap', async () => { + const directory = fakeDirectory( + Array.from({ length: 5_100 }, (_, index) => fakeEntry(`file-${index}.ts`)) ); - mockedGlobStream.mockReturnValue(stream as any); + jest.spyOn(nativeFs, 'opendir').mockResolvedValue(directory as any); const stat = mockFileStats(1); const result = await new FileMapper().mapRepository(repoPath); expect(result.files).toHaveLength(5_000); expect(result.discoveryMetrics).toEqual({ + entriesScanned: 5_001, + directoriesScanned: 1, entriesVisited: 5_001, statCalls: 5_000, stoppedEarly: true, @@ -58,12 +72,15 @@ describe('FileMapper bounded discovery', () => { expect(result.skipped).toEqual(expect.arrayContaining([ expect.objectContaining({ reason: 'file-limit' }), ])); - expect(stream.destroy).toHaveBeenCalled(); }); it('stops metadata work as soon as the aggregate byte budget is reached', async () => { - const stream = entryStream(['src/a.ts', 'src/b.ts', 'src/c.ts']); - mockedGlobStream.mockReturnValue(stream as any); + const directory = fakeDirectory([ + fakeEntry('a.ts'), + fakeEntry('b.ts'), + fakeEntry('c.ts'), + ]); + jest.spyOn(nativeFs, 'opendir').mockResolvedValue(directory as any); const stat = mockFileStats(6); const result = await new FileMapper([], { @@ -72,25 +89,101 @@ describe('FileMapper bounded discovery', () => { maxTotalBytes: 10, }).mapRepository(repoPath); - expect(result.files.map((file) => file.relativePath)).toEqual(['src/a.ts']); + expect(result.files.map((file) => file.relativePath)).toEqual(['a.ts']); expect(stat).toHaveBeenCalledTimes(2); expect(result.discoveryMetrics?.stoppedEarly).toBe(true); expect(result.skipped).toEqual(expect.arrayContaining([ - expect.objectContaining({ file: path.join(repoPath, 'src/b.ts'), reason: 'total-byte-limit' }), + expect.objectContaining({ file: path.join(repoPath, 'b.ts'), reason: 'total-byte-limit' }), ])); }); - it('uses targeted defaults and never stats irrelevant emitted paths', async () => { - const stream = entryStream(['assets/movie.bin', 'src/index.ts']); - mockedGlobStream.mockReturnValue(stream as any); + it('uses targeted defaults and never stats irrelevant paths', async () => { + const root = fakeDirectory([ + fakeEntry('movie.bin'), + fakeEntry('src', 'directory'), + ]); + const src = fakeDirectory([ + fakeEntry('asset.bin'), + fakeEntry('index.ts'), + ]); + jest.spyOn(nativeFs, 'opendir').mockImplementation(async (directoryPath) => { + return (path.basename(String(directoryPath)) === 'src' ? src : root) as any; + }); const stat = mockFileStats(1); const result = await new FileMapper().mapRepository(repoPath); - const patterns = mockedGlobStream.mock.calls[0][0] as string[]; - expect(patterns).not.toContain('**/*'); expect(result.files.map((file) => file.relativePath)).toEqual(['src/index.ts']); + expect(result.discoveryMetrics).toEqual({ + entriesScanned: 4, + directoriesScanned: 2, + entriesVisited: 1, + statCalls: 1, + stoppedEarly: false, + }); expect(stat).toHaveBeenCalledTimes(1); - expect(stat).not.toHaveBeenCalledWith(path.join(repoPath, 'assets/movie.bin')); + expect(stat).not.toHaveBeenCalledWith(path.join(repoPath, 'movie.bin')); + expect(stat).not.toHaveBeenCalledWith(path.join(repoPath, 'src', 'asset.bin')); + }); + + it('caps raw scans inside one huge directory of irrelevant entries', async () => { + const root = fakeDirectory([fakeEntry('src', 'directory')]); + const src = fakeDirectory( + Array.from({ length: 100 }, (_, index) => fakeEntry(`asset-${index}.bin`)) + ); + jest.spyOn(nativeFs, 'opendir').mockImplementation(async (directoryPath) => { + return (path.basename(String(directoryPath)) === 'src' ? src : root) as any; + }); + const stat = jest.spyOn(nativeFs, 'stat'); + + const result = await new FileMapper([], { + maxEntriesScanned: 10, + maxDirectoriesScanned: 10, + }).mapRepository(repoPath); + + expect(result.files).toEqual([]); + expect(result.partial).toBe(true); + expect(result.discoveryMetrics).toEqual({ + entriesScanned: 10, + directoriesScanned: 2, + entriesVisited: 0, + statCalls: 0, + stoppedEarly: true, + }); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ reason: 'entry-limit' }), + ])); + expect(src.read).toHaveBeenCalledTimes(9); + expect(stat).not.toHaveBeenCalled(); + }); + + it('caps traversal of a deep irrelevant directory tree', async () => { + const opened: string[] = []; + jest.spyOn(nativeFs, 'opendir').mockImplementation(async (directoryPath) => { + const normalized = path.relative(repoPath, String(directoryPath)).split(path.sep).join('/'); + opened.push(normalized || '.'); + const name = normalized ? `level-${normalized.split('/').length}` : 'src'; + return fakeDirectory([fakeEntry(name, 'directory')]) as any; + }); + const stat = jest.spyOn(nativeFs, 'stat'); + + const result = await new FileMapper([], { + maxDirectoriesScanned: 3, + maxEntriesScanned: 100, + }).mapRepository(repoPath); + + expect(opened).toEqual(['.', 'src', 'src/level-1']); + expect(result.partial).toBe(true); + expect(result.discoveryMetrics).toEqual({ + entriesScanned: 3, + directoriesScanned: 3, + entriesVisited: 0, + statCalls: 0, + stoppedEarly: true, + }); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ reason: 'directory-limit' }), + ])); + expect(stat).not.toHaveBeenCalled(); }); }); diff --git a/src/utils/fileMapper.ts b/src/utils/fileMapper.ts index 009674df..56c737a6 100644 --- a/src/utils/fileMapper.ts +++ b/src/utils/fileMapper.ts @@ -1,7 +1,7 @@ import * as fs from 'fs-extra'; import { promises as nativeFs, type Stats } from 'fs'; import * as path from 'path'; -import { globStream } from 'glob'; +import { minimatch } from 'minimatch'; import { FileInfo, RepoStructure, @@ -14,12 +14,22 @@ export interface FileMappingLimits { maxFiles: number; maxTotalBytes: number; maxFileBytes: number; + maxDirectoriesScanned: number; + maxEntriesScanned: number; } export const DEFAULT_FILE_MAPPING_LIMITS: FileMappingLimits = Object.freeze({ maxFiles: 5_000, maxTotalBytes: 256 * 1024 * 1024, maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, +}); + +/** Hard ceilings that callers cannot raise through configuration. */ +export const ABSOLUTE_FILE_MAPPING_SCAN_LIMITS = Object.freeze({ + maxDirectoriesScanned: 50_000, + maxEntriesScanned: 500_000, }); export const REPOSITORY_RELEVANT_EXTENSIONS = [ @@ -35,17 +45,6 @@ export const REPOSITORY_ROOT_FILES = [ '.eslintrc.json', '.prettierrc', '.prettierrc.json', '.nvmrc', '.node-version', ] as const; -const DEFAULT_RELEVANT_PATTERNS = [ - `{src,lib,bin,app,packages,scripts}/**/*.{${REPOSITORY_RELEVANT_EXTENSIONS.join(',')}}`, - `*.{${REPOSITORY_RELEVANT_EXTENSIONS.join(',')}}`, - ...REPOSITORY_ROOT_FILES, - '.github/workflows/**/*.{yml,yaml}', - 'README*', - 'LICENSE*', - 'Dockerfile*', - 'Makefile', -]; - const RELEVANT_SOURCE_ROOTS = new Set(['src', 'lib', 'bin', 'app', 'packages', 'scripts']); export function isRepositoryRelevantFile(relativePath: string): boolean { @@ -92,7 +91,7 @@ export class FileMapper { limits: Partial = {} ) { this.excludePatterns = [...this.excludePatterns, ...customExcludes]; - this.gitIgnoreManager = new GitIgnoreManager({ extraPatterns: customExcludes }); + this.gitIgnoreManager = new GitIgnoreManager({ extraPatterns: this.excludePatterns }); this.limits = { maxFiles: Math.max(0, Math.floor(limits.maxFiles ?? DEFAULT_FILE_MAPPING_LIMITS.maxFiles)), maxTotalBytes: Math.max( @@ -103,21 +102,25 @@ export class FileMapper { 0, Math.floor(limits.maxFileBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxFileBytes) ), + maxDirectoriesScanned: Math.min( + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS.maxDirectoriesScanned, + Math.max( + 0, + Math.floor( + limits.maxDirectoriesScanned ?? DEFAULT_FILE_MAPPING_LIMITS.maxDirectoriesScanned + ) + ) + ), + maxEntriesScanned: Math.min( + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS.maxEntriesScanned, + Math.max( + 0, + Math.floor(limits.maxEntriesScanned ?? DEFAULT_FILE_MAPPING_LIMITS.maxEntriesScanned) + ) + ), }; } - private async loadGitignorePatterns(repoPath: string): Promise { - const gitignorePath = path.join(repoPath, '.gitignore'); - if (!await fs.pathExists(gitignorePath)) { - return []; - } - const content = await fs.readFile(gitignorePath, 'utf-8'); - return content - .split('\n') - .map(line => line.trim()) - .filter(line => line.length > 0 && !line.startsWith('#')); - } - async mapRepository(repoPath: string, includePatterns?: string[]): Promise { const absolutePath = path.resolve(repoPath); @@ -125,90 +128,136 @@ export class FileMapper { throw new Error(`Repository path does not exist: ${absolutePath}`); } - const gitignorePatterns = await this.loadGitignorePatterns(absolutePath); - const ignorePatterns = [...this.excludePatterns, ...gitignorePatterns]; - await this.gitIgnoreManager.loadFromRepo(absolutePath); const usesDefaultPatterns = !includePatterns?.length; - const patterns = usesDefaultPatterns ? DEFAULT_RELEVANT_PATTERNS : includePatterns!; + const patterns = includePatterns ?? []; const fileInfos: FileInfo[] = []; const skipped: RepoDiscoverySkip[] = []; - const seen = new Set(); let totalSize = 0; + let entriesScanned = 0; + let directoriesScanned = 0; let entriesVisited = 0; let statCalls = 0; let stoppedEarly = false; const topLevelStats = new Map(); - const stream = globStream(patterns, { - cwd: absolutePath, - ignore: ignorePatterns, - dot: true, - absolute: false, - nodir: true, - }); - - for await (const entry of stream) { - const rawPath = String(entry); - const relativePath = (path.isAbsolute(rawPath) - ? path.relative(absolutePath, rawPath) - : rawPath).split(path.sep).join('/'); - if (seen.has(relativePath) || this.gitIgnoreManager.shouldIgnore(relativePath)) continue; - if (usesDefaultPatterns && !isRepositoryRelevantFile(relativePath)) continue; - seen.add(relativePath); - entriesVisited += 1; - - if (entriesVisited > this.limits.maxFiles) { - this.recordSkip(skipped, { file: relativePath, reason: 'file-limit' }); + const directoryQueue = ['']; + let nextDirectory = 0; + + discovery: while (nextDirectory < directoryQueue.length) { + const relativeDirectory = directoryQueue[nextDirectory]; + if (directoriesScanned >= this.limits.maxDirectoriesScanned) { + this.recordSkip(skipped, { + file: path.join(absolutePath, relativeDirectory), + reason: 'directory-limit', + }); stoppedEarly = true; - stream.destroy(); break; } + nextDirectory += 1; + directoriesScanned += 1; - const fullPath = path.join(absolutePath, relativePath); - let stats: Stats; + let directory; try { - statCalls += 1; - stats = await nativeFs.stat(fullPath); + directory = await nativeFs.opendir(path.join(absolutePath, relativeDirectory)); } catch { - this.recordSkip(skipped, { file: relativePath, reason: 'stat-failed' }); - continue; - } - if (!stats.isFile()) continue; - - const skipMetadata = { - file: fullPath, - size: stats.size, - mtimeMs: stats.mtimeMs, - ctimeMs: stats.ctimeMs, - }; - if (stats.size > this.limits.maxFileBytes) { - this.recordSkip(skipped, { ...skipMetadata, reason: 'file-too-large' }); + this.recordSkip(skipped, { + file: path.join(absolutePath, relativeDirectory), + reason: 'stat-failed', + }); continue; } - if (totalSize + stats.size > this.limits.maxTotalBytes) { - this.recordSkip(skipped, { ...skipMetadata, reason: 'total-byte-limit' }); - stoppedEarly = true; - stream.destroy(); - break; - } - fileInfos.push({ - path: fullPath, - relativePath, - extension: path.extname(relativePath), - size: stats.size, - mtimeMs: stats.mtimeMs, - ctimeMs: stats.ctimeMs, - type: 'file', - }); - totalSize += stats.size; - - const topLevelSegment = this.extractTopLevelSegment(relativePath); - if (topLevelSegment) { - const current = topLevelStats.get(topLevelSegment) ?? { fileCount: 0, totalSize: 0 }; - current.fileCount += 1; - current.totalSize += stats.size; - topLevelStats.set(topLevelSegment, current); + try { + while (true) { + if (entriesScanned >= this.limits.maxEntriesScanned) { + this.recordSkip(skipped, { + file: path.join(absolutePath, relativeDirectory), + reason: 'entry-limit', + }); + stoppedEarly = true; + break discovery; + } + const entry = await directory.read(); + if (!entry) break; + entriesScanned += 1; + + const relativePath = path.posix.join( + relativeDirectory.split(path.sep).join('/'), + entry.name + ); + if (this.isIgnored(relativePath, entry.isDirectory())) continue; + + if (entry.isDirectory()) { + if (!usesDefaultPatterns || this.shouldTraverseDefaultDirectory(relativePath)) { + directoryQueue.push(relativePath); + } + continue; + } + if (!entry.isFile()) continue; + if (usesDefaultPatterns + ? !isRepositoryRelevantFile(relativePath) + : !patterns.some((pattern) => minimatch(relativePath, pattern, { dot: true }))) { + continue; + } + + entriesVisited += 1; + if (entriesVisited > this.limits.maxFiles) { + this.recordSkip(skipped, { + file: path.join(absolutePath, relativePath), + reason: 'file-limit', + }); + stoppedEarly = true; + break discovery; + } + + const fullPath = path.join(absolutePath, relativePath); + let stats: Stats; + try { + statCalls += 1; + stats = await nativeFs.stat(fullPath); + } catch { + this.recordSkip(skipped, { file: fullPath, reason: 'stat-failed' }); + continue; + } + if (!stats.isFile()) continue; + + const skipMetadata = { + file: fullPath, + size: stats.size, + mtimeMs: stats.mtimeMs, + ctimeMs: stats.ctimeMs, + }; + if (stats.size > this.limits.maxFileBytes) { + this.recordSkip(skipped, { ...skipMetadata, reason: 'file-too-large' }); + continue; + } + if (totalSize + stats.size > this.limits.maxTotalBytes) { + this.recordSkip(skipped, { ...skipMetadata, reason: 'total-byte-limit' }); + stoppedEarly = true; + break discovery; + } + + fileInfos.push({ + path: fullPath, + relativePath, + extension: path.extname(relativePath), + size: stats.size, + mtimeMs: stats.mtimeMs, + ctimeMs: stats.ctimeMs, + type: 'file', + }); + totalSize += stats.size; + + const topLevelSegment = this.extractTopLevelSegment(relativePath); + if (topLevelSegment) { + const current = topLevelStats.get(topLevelSegment) ?? { fileCount: 0, totalSize: 0 }; + current.fileCount += 1; + current.totalSize += stats.size; + topLevelStats.set(topLevelSegment, current); + } + } + } finally { + await directory.close().catch(() => undefined); } } @@ -228,10 +277,28 @@ export class FileMapper { topLevelDirectoryStats, partial: skipped.length > 0 || stoppedEarly, skipped, - discoveryMetrics: { entriesVisited, statCalls, stoppedEarly }, + discoveryMetrics: { + entriesScanned, + directoriesScanned, + entriesVisited, + statCalls, + stoppedEarly, + }, }; } + private isIgnored(relativePath: string, isDirectory: boolean): boolean { + return this.gitIgnoreManager.shouldIgnore(relativePath) || + (isDirectory && this.gitIgnoreManager.shouldIgnore(`${relativePath}/`)); + } + + private shouldTraverseDefaultDirectory(relativePath: string): boolean { + const segments = relativePath.split('/'); + if (RELEVANT_SOURCE_ROOTS.has(segments[0])) return true; + if (segments[0] !== '.github') return false; + return segments.length === 1 || segments[1] === 'workflows'; + } + private recordSkip(skipped: RepoDiscoverySkip[], skip: RepoDiscoverySkip): void { if (skipped.length < MAX_RECORDED_SKIPS) skipped.push(skip); } From 9e2ba4955c47ce22f14a62faec0398b12cd176a0 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 17:58:33 -0300 Subject: [PATCH 27/39] fix: address LSP lifecycle review findings --- .../lsp/__tests__/fixtures/fake-lsp-server.js | 35 +- .../lsp/__tests__/lspLayer.lifecycle.test.ts | 53 ++- .../adapters/out/semantic/lsp/lspLayer.ts | 301 +++++++++++++----- 3 files changed, 297 insertions(+), 92 deletions(-) diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js index 9a2cd90b..4973b8e4 100644 --- a/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js +++ b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js @@ -1,16 +1,24 @@ 'use strict'; const fs = require('fs'); +const { spawn } = require('child_process'); +const { once } = require('events'); const mode = process.argv[2] || 'normal'; const pidFile = process.argv[3]; const attackSize = Number(process.argv[4]) || 4096; if (pidFile) fs.appendFileSync(pidFile, `${process.pid}\n`); -if (mode === 'ignore-shutdown') { +if (mode.startsWith('ignore-shutdown') || mode === 'signal-ignoring-descendant') { process.on('SIGTERM', () => {}); } +if (mode === 'ignore-shutdown-with-descendant') { + spawn(process.execPath, [__filename, 'signal-ignoring-descendant', pidFile], { + stdio: ['ignore', 'inherit', 'inherit'], + }); +} + let input = Buffer.alloc(0); function send(message) { @@ -18,6 +26,21 @@ function send(message) { process.stdout.write(`Content-Length: ${Buffer.byteLength(content)}\r\n\r\n${content}`); } +async function sendFragmented(message, chunkSize = 1024) { + const content = JSON.stringify(message); + const frame = Buffer.from( + `Content-Length: ${Buffer.byteLength(content)}\r\n\r\n${content}` + ); + for (let offset = 0; offset < frame.length; offset += chunkSize) { + const chunk = frame.subarray(offset, Math.min(offset + chunkSize, frame.length)); + if (!process.stdout.write(chunk)) await once(process.stdout, 'drain'); + // Keep writes observably fragmented instead of filling the pipe in one turn. + if (offset > 0 && offset % (chunkSize * 64) === 0) { + await new Promise((resolve) => setImmediate(resolve)); + } + } +} + function respond(message) { if (message.method === 'initialize') { if (mode === 'incomplete-huge-header') { @@ -32,6 +55,12 @@ function respond(message) { process.exit(19); } else if (mode === 'reject-initialize') { send({ jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'initialize rejected' } }); + } else if (mode === 'fragmented-large-initialize') { + void sendFragmented({ + jsonrpc: '2.0', + id: message.id, + result: { capabilities: {}, padding: 'x'.repeat(attackSize) }, + }); } else if (mode !== 'timeout-initialize') { send({ jsonrpc: '2.0', id: message.id, result: { capabilities: {} } }); } @@ -39,14 +68,14 @@ function respond(message) { } if (message.method === 'shutdown') { - if (mode !== 'ignore-shutdown') { + if (!mode.startsWith('ignore-shutdown')) { send({ jsonrpc: '2.0', id: message.id, result: null }); } return; } if (message.method === 'exit') { - if (mode !== 'ignore-shutdown') process.exit(0); + if (!mode.startsWith('ignore-shutdown')) process.exit(0); return; } diff --git a/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts index ad867cbd..c73a8870 100644 --- a/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts +++ b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts @@ -2,7 +2,12 @@ import * as fs from 'fs/promises'; import * as os from 'os'; import * as path from 'path'; import type { ChildProcess } from 'child_process'; -import { LSPLayer, LSPLayerOptions, LSPLifecycleEvent } from '../lspLayer'; +import { + LSPLayer, + LSPLayerOptions, + LSPLifecycleEvent, + MAX_LSP_BODY_BYTES, +} from '../lspLayer'; import type { LSPServerConfig } from '../../types'; const FIXTURE = path.join(__dirname, 'fixtures', 'fake-lsp-server.js'); @@ -18,7 +23,7 @@ interface InspectableHandle { process: ChildProcess; pendingRequests: Map; timers: Set; - buffer: Buffer; + receiver: { bufferedByteLength: number }; } function currentHandle(subject: LSPLayer): InspectableHandle { @@ -176,7 +181,7 @@ describe('LSPLayer process lifecycle', () => { ])); expect(handle.pendingRequests.size).toBe(0); expect(handle.timers.size).toBe(0); - expect(handle.buffer).toHaveLength(0); + expect(handle.receiver.bufferedByteLength).toBe(0); await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(false); expect(await readPids(pidFile)).toEqual([pid]); @@ -240,6 +245,46 @@ describe('LSPLayer process lifecycle', () => { await expect(subject.shutdown()).resolves.toBeUndefined(); }); + it('kills a signal-ignoring descendant in the owned process group', async () => { + const events: LSPLifecycleEvent[] = []; + const subject = createLayer( + { typescript: server('ignore-shutdown-with-descendant', pidFile) }, + { onLifecycleEvent: (event) => events.push(event) } + ); + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(true); + await waitUntil(async () => (await readPids(pidFile)).length === 2); + const pids = await readPids(pidFile); + expect(pids).toHaveLength(2); + expect(pids.every(processIsAlive)).toBe(true); + + const startedAt = Date.now(); + await subject.shutdown(); + + expect(Date.now() - startedAt).toBeLessThan(2_000); + await Promise.all(pids.map((pid) => waitUntil(() => !processIsAlive(pid)))); + expect(events).toEqual( + expect.arrayContaining([ + expect.objectContaining({ state: 'stopped', forcedKill: true }), + ]) + ); + }); + + it('accepts a near-8MiB response fragmented into 1KiB writes', async () => { + const subject = createLayer( + { + typescript: server( + 'fragmented-large-initialize', + pidFile, + MAX_LSP_BODY_BYTES - 1024 + ), + }, + { requestTimeoutMs: 15_000 } + ); + + await expect(subject.ensureServer('typescript', projectPath)).resolves.toBe(true); + expect(currentHandle(subject).receiver.bufferedByteLength).toBe(0); + }, 20_000); + it('is safe when shutdown races with initialization', async () => { const subject = createLayer({ typescript: server('timeout-initialize', pidFile) }); @@ -268,7 +313,7 @@ describe('LSPLayer process lifecycle', () => { expect(processIsAlive(pid)).toBe(false); expect(handle.pendingRequests.size).toBe(0); expect(handle.timers.size).toBe(0); - expect(handle.buffer).toHaveLength(0); + expect(handle.receiver.bufferedByteLength).toBe(0); expect(handle.process.eventNames()).toEqual([]); expect(handle.process.stdin?.eventNames()).toEqual([]); expect(handle.process.stdout?.eventNames()).toEqual([]); diff --git a/src/harness/adapters/out/semantic/lsp/lspLayer.ts b/src/harness/adapters/out/semantic/lsp/lspLayer.ts index 036322f1..814ab230 100644 --- a/src/harness/adapters/out/semantic/lsp/lspLayer.ts +++ b/src/harness/adapters/out/semantic/lsp/lspLayer.ts @@ -5,7 +5,7 @@ * initialization and shutdown state therefore cannot leak across servers. */ -import { spawn, ChildProcess } from 'child_process'; +import { spawn, execFile, ChildProcess } from 'child_process'; import { createHash } from 'crypto'; import * as path from 'path'; import { @@ -58,17 +58,140 @@ interface ServerHandle { stopping?: Promise; pendingRequests: Map; timers: Set; - buffer: Buffer; + receiver: LSPFrameAccumulator; startedAt: number; terminationReason?: string; forcedKill: boolean; + exited: boolean; closed: boolean; - closePromise: Promise; - resolveClose: () => void; exitCode?: number | null; exitSignal?: NodeJS.Signals | null; } +/** + * Incrementally assembles one LSP frame without repeatedly copying all bytes + * received so far. Header segments are joined once after the delimiter and + * body bytes are copied directly into their final, bounded allocation. + */ +class LSPFrameAccumulator { + private readonly headerSegments: Buffer[] = []; + private headerLength = 0; + private headerDelimiterMatch = 0; + private body?: Buffer; + private bodyOffset = 0; + + constructor( + private readonly maxHeaderBytes: number, + private readonly maxBodyBytes: number, + private readonly maxReceiveBufferBytes: number + ) {} + + get bufferedByteLength(): number { + return this.headerLength + this.bodyOffset; + } + + accept(data: Buffer, onFrame: (body: Buffer) => void): string | undefined { + let offset = 0; + + while (offset < data.length) { + if (this.body) { + const copyLength = Math.min(data.length - offset, this.body.length - this.bodyOffset); + data.copy(this.body, this.bodyOffset, offset, offset + copyLength); + offset += copyLength; + this.bodyOffset += copyLength; + + if (this.bodyOffset === this.body.length) { + const completedBody = this.body; + this.body = undefined; + this.bodyOffset = 0; + onFrame(completedBody); + } + continue; + } + + const segmentStart = offset; + let foundHeader = false; + while (offset < data.length) { + const byte = data[offset++]; + this.headerLength += 1; + this.headerDelimiterMatch = this.nextDelimiterMatch( + this.headerDelimiterMatch, + byte + ); + + if (this.headerDelimiterMatch === 4) { + this.headerSegments.push(data.subarray(segmentStart, offset)); + foundHeader = true; + break; + } + + // Bytes matching the start of CRLFCRLF may still be the delimiter and + // therefore are not counted as header content until the match fails. + if (this.headerLength - this.headerDelimiterMatch > this.maxHeaderBytes) { + return 'incomplete header limit exceeded'; + } + if (this.headerLength > this.maxReceiveBufferBytes) { + return 'receive buffer limit exceeded'; + } + } + + if (!foundHeader) { + this.headerSegments.push(data.subarray(segmentStart, offset)); + return undefined; + } + + const headerEnd = this.headerLength - 4; + if (headerEnd > this.maxHeaderBytes) return 'header limit exceeded'; + const headerBuffer = Buffer.concat(this.headerSegments, this.headerLength); + const header = headerBuffer.subarray(0, headerEnd).toString('ascii'); + const contentLengthHeaders = header + .split('\r\n') + .filter((line) => /^Content-Length:/i.test(line)); + if (contentLengthHeaders.length !== 1) { + return 'expected exactly one Content-Length header'; + } + const rawContentLength = contentLengthHeaders[0] + .slice(contentLengthHeaders[0].indexOf(':') + 1) + .trim(); + if (!/^[0-9]+$/.test(rawContentLength)) return 'invalid Content-Length'; + + const contentLength = Number(rawContentLength); + if ( + !Number.isSafeInteger(contentLength) || + contentLength <= 0 || + contentLength > this.maxBodyBytes + ) { + return 'Content-Length exceeds body limit'; + } + if (this.headerLength + contentLength > this.maxReceiveBufferBytes) { + return 'frame exceeds receive buffer limit'; + } + + this.headerSegments.length = 0; + this.headerLength = 0; + this.headerDelimiterMatch = 0; + this.body = Buffer.allocUnsafe(contentLength); + this.bodyOffset = 0; + } + + return undefined; + } + + reset(): void { + this.headerSegments.length = 0; + this.headerLength = 0; + this.headerDelimiterMatch = 0; + this.body = undefined; + this.bodyOffset = 0; + } + + private nextDelimiterMatch(current: number, byte: number): number { + const delimiter = [13, 10, 13, 10]; + if (byte === delimiter[current]) return current + 1; + return byte === delimiter[0] ? 1 : 0; + } +} + export interface LSPLayerOptions { /** Primarily useful to provide explicitly installed or test language servers. */ serverConfigs?: Record; @@ -165,14 +288,14 @@ export class LSPLayer { const config = this.serverConfigs[language]; if (!config) return false; - let resolveClose!: () => void; - const closePromise = new Promise((resolve) => { - resolveClose = resolve; - }); const child = spawn(config.command, config.args, { cwd: projectPath, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env }, + // A dedicated POSIX process group lets the owner terminate launchers and + // every descendant they create. Windows uses taskkill /T below. + detached: process.platform !== 'win32', + windowsHide: true, }); const handle: ServerHandle = { @@ -184,12 +307,15 @@ export class LSPLayer { initialization: Promise.resolve(false), pendingRequests: new Map(), timers: new Set(), - buffer: Buffer.alloc(0), + receiver: new LSPFrameAccumulator( + this.maxHeaderBytes, + this.maxBodyBytes, + this.maxReceiveBufferBytes + ), startedAt: Date.now(), forcedKill: false, + exited: false, closed: false, - closePromise, - resolveClose, }; // Publish the owner before any asynchronous event can act on the process. @@ -231,15 +357,21 @@ export class LSPLayer { exitSignal: signal, }); this.rejectPending(handle, new Error(`LSP server ${handle.language} disconnected`)); - this.releaseHandle(handle); + // The direct launcher may have left descendants in its process group. + // Termination remains authoritative even after the launcher closes. + void this.terminateHandle(handle, handle.terminationReason); } }); + handle.process.once('exit', (code, signal) => { + handle.exited = true; + handle.exitCode = code; + handle.exitSignal = signal; + }); } private markClosed(handle: ServerHandle): void { if (handle.closed) return; handle.closed = true; - handle.resolveClose(); } private async initializeHandle(handle: ServerHandle): Promise { @@ -313,66 +445,14 @@ export class LSPLayer { private handleServerData(handle: ServerHandle, data: Buffer): void { if (handle.state === 'stopping' || handle.state === 'stopped') return; - if (data.length > this.maxReceiveBufferBytes - handle.buffer.length) { - this.failProtocol(handle, 'receive buffer limit exceeded'); - return; - } - handle.buffer = Buffer.concat([handle.buffer, data]); - - while (true) { - const headerEnd = handle.buffer.indexOf('\r\n\r\n'); - if (headerEnd < 0) { - if (handle.buffer.length > this.maxHeaderBytes) { - this.failProtocol(handle, 'incomplete header limit exceeded'); - } - return; - } - if (headerEnd > this.maxHeaderBytes) { - this.failProtocol(handle, 'header limit exceeded'); - return; - } - const header = handle.buffer.subarray(0, headerEnd).toString('ascii'); - const contentLengthHeaders = header - .split('\r\n') - .filter((line) => /^Content-Length:/i.test(line)); - if (contentLengthHeaders.length !== 1) { - this.failProtocol(handle, 'expected exactly one Content-Length header'); - return; - } - const rawContentLength = contentLengthHeaders[0].slice( - contentLengthHeaders[0].indexOf(':') + 1 - ).trim(); - if (!/^[0-9]+$/.test(rawContentLength)) { - this.failProtocol(handle, 'invalid Content-Length'); - return; - } - const contentLength = Number(rawContentLength); - if ( - !Number.isSafeInteger(contentLength) || - contentLength <= 0 || - contentLength > this.maxBodyBytes - ) { - this.failProtocol(handle, 'Content-Length exceeds body limit'); - return; - } - const bodyStart = headerEnd + 4; - if (bodyStart + contentLength > this.maxReceiveBufferBytes) { - this.failProtocol(handle, 'frame exceeds receive buffer limit'); - return; - } - if (handle.buffer.length < bodyStart + contentLength) return; - - const body = handle.buffer.subarray(bodyStart, bodyStart + contentLength); - const remainingStart = bodyStart + contentLength; - handle.buffer = remainingStart === handle.buffer.length - ? Buffer.alloc(0) - : Buffer.from(handle.buffer.subarray(remainingStart)); + const error = handle.receiver.accept(data, (body) => { try { this.handleMessage(handle, JSON.parse(body.toString('utf8')) as LSPMessage); } catch { // Malformed server messages are ignored without affecting another handle. } - } + }); + if (error) this.failProtocol(handle, error); } private failProtocol(handle: ServerHandle, detail: string): void { @@ -383,7 +463,7 @@ export class LSPLayer { ) return; const reason = `protocol overflow: ${detail}`; - handle.buffer = Buffer.alloc(0); + handle.receiver.reset(); handle.terminationReason = reason; handle.state = 'failed'; this.failedCircuits.add(handle.key); @@ -465,15 +545,18 @@ export class LSPLayer { this.rejectPending(handle, new Error(`LSP server ${handle.language} terminated: ${reason}`)); handle.process.stdin?.end(); - if (!handle.closed) { + if (this.processTreeIsAlive(handle)) { const exitedNaturally = - waitForNaturalExit && (await this.waitForClose(handle, this.terminationGraceMs)); + waitForNaturalExit && + (await this.waitForProcessTreeExit(handle, this.terminationGraceMs)); if (!exitedNaturally) { - this.signal(handle, 'SIGTERM'); - if (!(await this.waitForClose(handle, this.terminationGraceMs))) { + await this.signalProcessTree(handle, 'SIGTERM'); + if (!(await this.waitForProcessTreeExit(handle, this.terminationGraceMs))) { handle.forcedKill = true; - this.signal(handle, 'SIGKILL'); - await handle.closePromise; + await this.signalProcessTree(handle, 'SIGKILL'); + // Some descendants inherit the server's stdio and can prevent the + // ChildProcess `close` event. Never await it without a deadline. + await this.waitForProcessTreeExit(handle, this.terminationGraceMs); } } } @@ -490,8 +573,27 @@ export class LSPLayer { return handle.stopping; } - private signal(handle: ServerHandle, signal: NodeJS.Signals): void { - if (handle.closed || !handle.process.pid) return; + private async signalProcessTree( + handle: ServerHandle, + signal: 'SIGTERM' | 'SIGKILL' + ): Promise { + const pid = handle.process.pid; + if (!pid) return; + + if (process.platform === 'win32') { + await this.taskkill(pid, signal === 'SIGKILL'); + return; + } + + try { + // Negative PID targets the dedicated group created with detached=true. + process.kill(-pid, signal); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ESRCH') return; + } + + // Fall back to the direct child if group signalling is unavailable. try { handle.process.kill(signal); } catch { @@ -499,17 +601,46 @@ export class LSPLayer { } } - private waitForClose(handle: ServerHandle, timeoutMs: number): Promise { - if (handle.closed) return Promise.resolve(true); + private taskkill(pid: number, force: boolean): Promise { return new Promise((resolve) => { - const timeout = this.setHandleTimeout(handle, () => resolve(false), timeoutMs); - handle.closePromise.then(() => { - this.clearHandleTimeout(handle, timeout); - resolve(true); - }); + const args = ['/PID', String(pid), '/T']; + if (force) args.push('/F'); + execFile( + 'taskkill', + args, + { windowsHide: true, timeout: Math.max(100, this.terminationGraceMs) }, + () => resolve() + ); }); } + private processTreeIsAlive(handle: ServerHandle): boolean { + const pid = handle.process.pid; + if (!pid) return false; + if (process.platform === 'win32') return !handle.exited; + try { + process.kill(-pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } + } + + private async waitForProcessTreeExit( + handle: ServerHandle, + timeoutMs: number + ): Promise { + const deadline = Date.now() + timeoutMs; + while (this.processTreeIsAlive(handle)) { + const remaining = deadline - Date.now(); + if (remaining <= 0) return false; + await new Promise((resolve) => { + this.setHandleTimeout(handle, resolve, Math.min(25, remaining)); + }); + } + return true; + } + private setHandleTimeout( handle: ServerHandle, callback: () => void, @@ -533,7 +664,7 @@ export class LSPLayer { this.rejectPending(handle, new Error(`LSP server ${handle.language} released`)); for (const timer of handle.timers) clearTimeout(timer); handle.timers.clear(); - handle.buffer = Buffer.alloc(0); + handle.receiver.reset(); handle.process.stdin?.removeAllListeners(); handle.process.stdout?.removeAllListeners(); handle.process.stderr?.removeAllListeners(); From 041b87f0b467d931879f1c2d6f26b957ed24e808 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 17:59:52 -0300 Subject: [PATCH 28/39] fix: harden hook trace safety --- CHANGELOG.md | 3 + .../__tests__/runtimeStateService.test.ts | 118 ++++++++++++ .../out/runtimeState/runtimeStateService.ts | 170 +++++++++++++++--- .../hooks/__tests__/hookTracePolicy.test.ts | 42 +++++ .../application/hooks/hookTracePolicy.ts | 129 ++++++++++--- 5 files changed, 414 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0e42212..7221fdc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. +- Redacted Bash credentials across header, JSON, assignment, camel-case, and flag forms, omitting ambiguous command tails rather than risking secret disclosure. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. +- Made stale trace-lock takeover verify process ownership, token, device, and inode across competing processes; same-millisecond rotations now use a monotonic segment sequence. +- Kept the active rotation threshold and individual events within the configured per-session trace quota, including contradictory configurations and a single oversized event. ## [1.1.1] - 2026-06-27 diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 27a42cab..cff9e083 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -1,6 +1,8 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; +import { spawn } from 'child_process'; +import { pathToFileURL } from 'url'; import { HarnessRuntimeStateService, } from '../runtimeStateService'; @@ -168,4 +170,120 @@ describe('HarnessRuntimeStateService', () => { })).resolves.toMatchObject({ event: 'after.stale.lock' }); expect(await fs.pathExists(lockFile)).toBe(false); }); + + it('serializes multiprocess writers racing to take over the same stale lock', async () => { + const session = await service.createSession({ name: 'stale-lock-race' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const lockFile = path.join(sessionDir, 'trace.jsonl.lock'); + await fs.writeJson(lockFile, { + pid: 999999, + token: 'stale-owner-token', + createdAt: '2000-01-01T00:00:00.000Z', + }); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + const moduleUrl = pathToFileURL(path.resolve(__dirname, '../runtimeStateService.ts')).href; + const worker = ` + (async () => { + const loaded = await import(${JSON.stringify(moduleUrl)}); + const HarnessRuntimeStateService = loaded.HarnessRuntimeStateService ?? loaded.default?.HarnessRuntimeStateService; + const runtime = new HarnessRuntimeStateService({ repoPath: process.argv[1] }); + await runtime.appendTrace(process.argv[2], { + level: 'info', event: 'worker.event', message: 'worker-' + process.argv[3], + data: { worker: Number(process.argv[3]), payload: 'x'.repeat(8192) } + }); + })().catch((error) => { console.error(error); process.exitCode = 1; }); + `; + const runWorker = (index: number): Promise => new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['--import', 'tsx', '-e', worker, tempDir, session.id, String(index)], { + cwd: path.resolve(__dirname, '../../../../../..'), + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.once('error', reject); + child.once('exit', (code) => code === 0 ? resolve() : reject(new Error(`worker ${index} failed: ${stderr}`))); + }); + + await Promise.all(Array.from({ length: 8 }, (_, index) => runWorker(index))); + + const traceText = await fs.readFile(path.join(sessionDir, 'trace.jsonl'), 'utf8'); + const lines = traceText.trim().split('\n'); + expect(() => lines.forEach((line) => JSON.parse(line))).not.toThrow(); + const traces = await service.listTraces(session.id); + expect(traces.filter((trace) => trace.event === 'worker.event')).toHaveLength(8); + expect(new Set(traces.filter((trace) => trace.event === 'worker.event').map((trace) => trace.data?.worker)).size) + .toBe(8); + expect(await fs.pathExists(lockFile)).toBe(false); + expect(await fs.pathExists(`${lockFile}.takeover`)).toBe(false); + }, 30_000); + + it('uses monotonic segment sequences for same-millisecond rotation and pruning', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'hooks.json'), { + trace: { + rotationBytes: 64 * 1024, + retainedSegments: 2, + maxSessionBytes: 512 * 1024, + }, + }); + jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate', 'setTimeout'] }); + jest.setSystemTime(new Date('2026-07-11T20:00:00.123Z')); + try { + const session = await service.createSession({ name: 'same-ms-rotation' }); + for (let index = 0; index < 6; index += 1) { + await service.appendTrace(session.id, { + level: 'info', + event: 'same-ms.event', + message: `event-${index}`, + data: { index, payload: 'x'.repeat(60 * 1024) }, + }); + } + + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const segments = (await fs.readdir(sessionDir)) + .filter((entry) => /^trace\.\d{12}\..+\.jsonl$/.test(entry)) + .sort(); + expect(segments).toHaveLength(2); + const sequences = segments.map((entry) => Number(/^trace\.(\d{12})\./.exec(entry)?.[1])); + expect(sequences[1]).toBe(sequences[0] + 1); + + const traces = await service.listTraces(session.id); + const retainedIndexes = traces + .filter((trace) => trace.event === 'same-ms.event') + .map((trace) => trace.data?.index); + expect(retainedIndexes).toEqual([...retainedIndexes].sort((a, b) => Number(a) - Number(b))); + expect(retainedIndexes).toContain(5); + } finally { + jest.useRealTimers(); + } + }); + + it('keeps a single oversized event and active trace within a smaller session quota', async () => { + await fs.outputJson(path.join(tempDir, '.context', 'config', 'hooks.json'), { + trace: { + rotationBytes: 64 * 1024 * 1024, + retainedSegments: 16, + maxSessionBytes: 64 * 1024, + }, + }); + await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { + trace: { maxSerializedBytes: 1024 * 1024 }, + }); + const session = await service.createSession({ name: 'cross-limit-budget' }); + const marker = `must-not-persist-${'x'.repeat(512 * 1024)}`; + + const trace = await service.appendTrace(session.id, { + level: 'info', event: 'oversized.single', message: marker, data: { marker }, + }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const traceFiles = (await fs.readdir(sessionDir)).filter((entry) => entry.endsWith('.jsonl')); + const totalBytes = (await Promise.all(traceFiles.map((entry) => fs.stat(path.join(sessionDir, entry))))) + .reduce((sum, stat) => sum + stat.size, 0); + + expect(totalBytes).toBeLessThanOrEqual(64 * 1024); + expect(trace.data).toMatchObject({ traceDataOmitted: true }); + expect((await fs.readFile(path.join(sessionDir, 'trace.jsonl'), 'utf8'))).not.toContain(marker); + }); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 38ee6f97..f725b37e 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -19,6 +19,20 @@ import { } from '../../../application/hooks/hookTracePolicy'; const traceWriteQueues = new Map>(); +const TRACE_LOCK_STALE_MS = 60_000; +const ROTATION_EVENT_RESERVE_BYTES = 2 * 1024; + +interface TraceLockIdentity { + pid: number; + token: string; +} + +interface TraceFileLock extends TraceLockIdentity { + lockFile: string; + handle: FileHandle; + inode: bigint | number; + device: bigint | number; +} function waitForLock(milliseconds: number): Promise { return new Promise((resolve) => setTimeout(resolve, milliseconds)); @@ -34,29 +48,103 @@ function isProcessAlive(pid: number): boolean { } } -async function acquireTraceFileLock( - traceFile: string -): Promise<{ lockFile: string; handle: FileHandle; inode: bigint | number }> { +function parseTraceLockIdentity(value: string): TraceLockIdentity { + try { + const parsed = JSON.parse(value) as Partial; + return { + pid: typeof parsed.pid === 'number' ? parsed.pid : Number.NaN, + token: typeof parsed.token === 'string' ? parsed.token : '', + }; + } catch { + // Preserve takeover compatibility with locks written by the first F-02 + // implementation (`pid timestamp`). + return { pid: Number.parseInt(value.split(/\s/, 1)[0], 10), token: value.trim() }; + } +} + +async function sameLockIdentity( + file: string, + expected: { inode: bigint | number; device: bigint | number; token: string } +): Promise { + try { + const handle = await nodeFs.open(file, 'r'); + try { + const [stat, contents] = await Promise.all([ + handle.stat({ bigint: true }), + handle.readFile('utf8'), + ]); + const identity = parseTraceLockIdentity(contents); + return stat.ino === expected.inode && stat.dev === expected.device && identity.token === expected.token; + } finally { + await handle.close(); + } + } catch { + return false; + } +} + +async function tryTakeOverStaleTraceLock(lockFile: string): Promise { + const takeoverFile = `${lockFile}.takeover`; + try { + // link(2) is the atomic election: exactly one waiter creates the fixed + // takeover name, and the hard link pins the inode it inspected. + await nodeFs.link(lockFile, takeoverFile); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'EEXIST' || code === 'ENOENT') return false; + throw error; + } + + try { + const handle = await nodeFs.open(takeoverFile, 'r'); + try { + const [stat, contents] = await Promise.all([ + handle.stat({ bigint: true }), + handle.readFile('utf8'), + ]); + const identity = parseTraceLockIdentity(contents); + const age = Date.now() - Number(stat.mtimeMs); + const observed = { inode: stat.ino, device: stat.dev, token: identity.token }; + if (age <= TRACE_LOCK_STALE_MS || isProcessAlive(identity.pid)) return false; + if (!(await sameLockIdentity(lockFile, observed))) return false; + // No second reaper can race this unlink while the fixed takeover link + // exists, and a dead owner cannot replace its own inode/token. + await nodeFs.unlink(lockFile); + return true; + } finally { + await handle.close(); + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + return false; + } finally { + await nodeFs.unlink(takeoverFile).catch(() => undefined); + } +} + +async function acquireTraceFileLock(traceFile: string): Promise { const lockFile = `${traceFile}.lock`; + const takeoverFile = `${lockFile}.takeover`; const deadline = Date.now() + 10_000; while (true) { + if (await nodeFs.stat(takeoverFile).then(() => true).catch(() => false)) { + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for trace lock takeover: ${path.basename(traceFile)}`); + } + await waitForLock(10 + Math.floor(Math.random() * 20)); + continue; + } try { const handle = await nodeFs.open(lockFile, 'wx'); - await handle.writeFile(`${process.pid} ${new Date().toISOString()}\n`, 'utf8'); + const token = randomUUID(); + await handle.writeFile(JSON.stringify({ pid: process.pid, token, createdAt: new Date().toISOString() }), 'utf8'); const stat = await handle.stat({ bigint: true }); - return { lockFile, handle, inode: stat.ino }; + return { lockFile, handle, inode: stat.ino, device: stat.dev, pid: process.pid, token }; } catch (error) { const code = (error as NodeJS.ErrnoException).code; if (code !== 'EEXIST') throw error; - const [age, ownerPid] = await Promise.all([ - nodeFs.stat(lockFile).then((stat) => Date.now() - stat.mtimeMs).catch(() => 0), - nodeFs.readFile(lockFile, 'utf8') - .then((value) => Number.parseInt(value.split(/\s/, 1)[0], 10)) - .catch(() => Number.NaN), - ]); - if (age > 60_000 && !isProcessAlive(ownerPid)) { - await nodeFs.unlink(lockFile).catch(() => undefined); + if (await tryTakeOverStaleTraceLock(lockFile)) { continue; } if (Date.now() >= deadline) { @@ -73,10 +161,7 @@ async function withCrossProcessTraceLock(traceFile: string, operation: () => return await operation(); } finally { await lock.handle.close().catch(() => undefined); - const currentInode = await nodeFs.stat(lock.lockFile, { bigint: true }) - .then((stat) => stat.ino) - .catch(() => undefined); - if (currentInode === lock.inode) { + if (await sameLockIdentity(lock.lockFile, lock)) { await nodeFs.unlink(lock.lockFile).catch(() => undefined); } } @@ -279,11 +364,38 @@ export class HarnessRuntimeStateService { if (!(await fs.pathExists(sessionDir))) { return []; } - const entries = await fs.readdir(sessionDir); - return entries - .filter((entry) => /^trace\..+\.jsonl$/.test(entry)) - .sort() - .map((entry) => path.join(sessionDir, entry)); + const entries = (await fs.readdir(sessionDir)).filter((entry) => /^trace\..+\.jsonl$/.test(entry)); + const segments = await Promise.all(entries.map(async (entry) => { + const file = path.join(sessionDir, entry); + const stat = await fs.stat(file); + const sequence = /^trace\.(\d{12})\./.exec(entry)?.[1]; + return { file, entry, mtimeMs: stat.mtimeMs, sequence: sequence ? Number(sequence) : undefined }; + })); + return segments.sort((a, b) => { + if (a.sequence !== undefined && b.sequence !== undefined) return a.sequence - b.sequence; + return a.mtimeMs - b.mtimeMs || (a.sequence ?? 0) - (b.sequence ?? 0) || a.entry.localeCompare(b.entry); + }).map(({ file }) => file); + } + + private async nextTraceSegmentSequence(sessionId: string): Promise { + const sequenceFile = path.join(this.layout.sessionDir(sessionId), 'trace.sequence'); + const configured = await fs.readFile(sequenceFile, 'utf8') + .then((value) => Number.parseInt(value, 10)) + .catch(() => 0); + const existing = await this.listTraceSegmentFiles(sessionId); + const maximumExisting = existing.reduce((maximum, file) => { + const sequence = Number(/^trace\.(\d{12})\./.exec(path.basename(file))?.[1] ?? 0); + return Math.max(maximum, sequence); + }, 0); + const next = Math.max(Number.isSafeInteger(configured) ? configured : 0, maximumExisting) + 1; + const temporary = `${sequenceFile}.${process.pid}.${randomUUID()}.tmp`; + try { + await fs.writeFile(temporary, `${next}\n`, 'utf8'); + await fs.rename(temporary, sequenceFile); + } finally { + await fs.remove(temporary).catch(() => undefined); + } + return next; } private async pruneTraceSegments(sessionId: string): Promise { @@ -319,7 +431,8 @@ export class HarnessRuntimeStateService { let rotationTrace: HarnessTraceRecord | undefined; if (activeBytes > 0 && activeBytes + Buffer.byteLength(serialized, 'utf8') > policy.traceRotationBytes) { - const rotationId = `${new Date().toISOString().replace(/[:.]/g, '-')}.${randomUUID()}`; + const sequence = await this.nextTraceSegmentSequence(sessionId); + const rotationId = `${String(sequence).padStart(12, '0')}.${new Date().toISOString().replace(/[:.]/g, '-')}.${randomUUID()}`; const segmentFile = `${this.traceSegmentPrefix(sessionId)}${rotationId}.jsonl`; await fs.rename(activeFile, segmentFile); rotationTrace = boundGenericTraceRecord({ @@ -350,7 +463,16 @@ export class HarnessRuntimeStateService { } return withTraceWriteLock(this.traceFile(sessionId), async () => { const session = await this.readSession(sessionId); - const boundedTrace = boundGenericTraceRecord(trace, loadGenericTraceEventMaxBytes(this.repoPath)); + const policy = loadHookTracePolicy(this.repoPath); + const traceBudget = Math.max( + 1024, + Math.min( + loadGenericTraceEventMaxBytes(this.repoPath), + policy.traceRotationBytes - ROTATION_EVENT_RESERVE_BYTES, + policy.maxSessionTraceBytes - ROTATION_EVENT_RESERVE_BYTES + ) + ); + const boundedTrace = boundGenericTraceRecord(trace, traceBudget); const rotationTrace = await this.appendTraceLine(sessionId, boundedTrace); session.traceCount += rotationTrace ? 2 : 1; diff --git a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts index a7d1e1e8..1d08866f 100644 --- a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -137,6 +137,36 @@ describe('hook trace policy', () => { expect(unknown.capture.truncatedFieldCount).toBe(1); }); + it.each([ + ['header', `curl -H 'X-API-Key: header-supersecret' https://example.test`], + ['authorization header', `curl --header="Authorization: Bearer bearer-supersecret" https://example.test`], + ['JSON', `curl -d '{"token":"json-supersecret"}' https://example.test`], + ['escaped JSON', String.raw`curl -d "{\"apiKey\":\"escaped-supersecret\"}" https://example.test`], + ['colon', 'deploy password:colon-supersecret'], + ['equals', 'TOKEN=equals-supersecret npm test'], + ['camelCase flag', 'deploy --apiKey=camel-supersecret --safe true'], + ['space flag', 'deploy --secret flag-supersecret --safe true'], + ])('redacts case-insensitive Bash secrets in %s form', (_label, command) => { + const data = sanitizeHookTraceData('Bash', { command }); + const preview = String(data.tool_input.commandPreview); + + expect(preview).toContain('[REDACTED]'); + expect(preview.toLowerCase()).not.toContain('supersecret'); + expect(data.capture.redactedFieldCount).toBeGreaterThan(0); + }); + + it('omits the remaining Bash preview when a quoted secret has no reliable boundary', () => { + const data = sanitizeHookTraceData('Bash', { + command: `curl -H 'X-API-Key: never-persist --next also-sensitive`, + }); + const preview = String(data.tool_input.commandPreview); + + expect(preview).toContain('[REDACTED]'); + expect(preview).not.toContain('never-persist'); + expect(preview).not.toContain('--next'); + expect(preview).not.toContain('also-sensitive'); + }); + it('omits pathological unknown key names and enforces the hook quota before persistence', () => { const secretInKey = `secret-key-material-${'private-key-fragment-'.repeat(20_000)}`; const data = sanitizeHookTraceData('CustomTool', { @@ -222,4 +252,16 @@ describe('hook trace policy', () => { expect(policy.retainedTraceSegments).toBe(16); expect(DEFAULT_HOOK_TRACE_POLICY.maxSerializedTraceBytes).toBe(16 * 1024); }); + + it('caps the active rotation threshold at the total session quota', () => { + const policy = parseHookTracePolicy({ + trace: { + rotationBytes: 64 * 1024 * 1024, + maxSessionBytes: 64 * 1024, + }, + }); + + expect(policy.traceRotationBytes).toBe(64 * 1024); + expect(policy.maxSessionTraceBytes).toBe(64 * 1024); + }); }); diff --git a/src/harness/application/hooks/hookTracePolicy.ts b/src/harness/application/hooks/hookTracePolicy.ts index ccac0c73..9211582f 100644 --- a/src/harness/application/hooks/hookTracePolicy.ts +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -75,6 +75,18 @@ function configuredValue(config: Record, key: string, section: export function parseHookTracePolicy(value: unknown): HookTracePolicy { const config = isRecord(value) ? value : {}; + const maxSessionTraceBytes = finiteInteger( + configuredValue(config, 'maxSessionTraceBytes', 'trace', 'maxSessionBytes'), + DEFAULT_HOOK_TRACE_POLICY.maxSessionTraceBytes, + 64 * 1024, + GLOBAL_SESSION_TRACE_MAX_BYTES + ); + const traceRotationBytes = finiteInteger( + configuredValue(config, 'traceRotationBytes', 'trace', 'rotationBytes'), + DEFAULT_HOOK_TRACE_POLICY.traceRotationBytes, + 64 * 1024, + GLOBAL_TRACE_ROTATION_MAX_BYTES + ); return { maxInputBytes: finiteInteger( configuredValue(config, 'maxInputBytes', 'stdin', 'maxBytes'), @@ -106,24 +118,16 @@ export function parseHookTracePolicy(value: unknown): HookTracePolicy { 1024, GLOBAL_HOOK_TRACE_MAX_BYTES ), - traceRotationBytes: finiteInteger( - configuredValue(config, 'traceRotationBytes', 'trace', 'rotationBytes'), - DEFAULT_HOOK_TRACE_POLICY.traceRotationBytes, - 64 * 1024, - GLOBAL_TRACE_ROTATION_MAX_BYTES - ), + // The active segment is never pruned, so it must fit inside the total + // session budget even when configuration supplies contradictory limits. + traceRotationBytes: Math.min(traceRotationBytes, maxSessionTraceBytes), retainedTraceSegments: finiteInteger( configuredValue(config, 'retainedTraceSegments', 'trace', 'retainedSegments'), DEFAULT_HOOK_TRACE_POLICY.retainedTraceSegments, 0, GLOBAL_TRACE_RETAINED_SEGMENTS ), - maxSessionTraceBytes: finiteInteger( - configuredValue(config, 'maxSessionTraceBytes', 'trace', 'maxSessionBytes'), - DEFAULT_HOOK_TRACE_POLICY.maxSessionTraceBytes, - 64 * 1024, - GLOBAL_SESSION_TRACE_MAX_BYTES - ), + maxSessionTraceBytes, }; } @@ -199,20 +203,97 @@ function commandBasename(command: string): string | undefined { return match?.[1] ? path.basename(match[1]) : undefined; } +const COMMAND_SECRET_KEY = /(? { - command = command.replace(pattern, (...args: unknown[]) => { - redacted += 1; - const key = typeof args[1] === 'string' ? args[1] : ''; - return replacement.replace('$KEY', key); - }); - }; - replace(/['"](authorization)\s*:\s*(?:bearer\s+)?[^'"]+['"]/gi, '$KEY=[REDACTED]'); - replace(/\b(authorization)\s*[:=]\s*(?:bearer\s+)?[^\s;&|]+/gi, '$KEY=[REDACTED]'); - replace(/--?(api[-_]?key|token|password|secret)(?:=|\s+)(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, '--$KEY=[REDACTED]'); - replace(/\b(api[-_]?key|token|password|secret)=(?:"[^"]*"|'[^']*'|[^\s;&|]+)/gi, '$KEY=[REDACTED]'); - return { value: command, redacted }; + COMMAND_SECRET_KEY.lastIndex = 0; + for (let match = COMMAND_SECRET_KEY.exec(command); match; match = COMMAND_SECRET_KEY.exec(command)) { + if (match.index < sourceCursor) continue; + let cursor = skipJsonKeyQuote(command, match.index + match[0].length); + while (cursor < command.length && /\s/.test(command[cursor])) cursor += 1; + + if (command[cursor] === ':' || command[cursor] === '=') { + cursor += 1; + } else if (precedingFlag(command, match.index) && cursor > match.index + match[0].length) { + // A space-delimited --token value form. + } else { + continue; + } + while (cursor < command.length && /\s/.test(command[cursor])) cursor += 1; + + const quotedEnd = quotedValueEnd(command, cursor); + const end = quotedEnd ?? unquotedValueEnd(command, cursor, enclosingShellQuote(command, match.index)); + value += `${command.slice(sourceCursor, cursor)}[REDACTED]`; + sourceCursor = end; + redacted += 1; + COMMAND_SECRET_KEY.lastIndex = Math.max(COMMAND_SECRET_KEY.lastIndex, end); + } + return { value: value + command.slice(sourceCursor), redacted }; } function countSensitiveFields(value: unknown, policy: HookTracePolicy, depth = 0): number { From 01e87e0234bd5d10aacf1c5c96461da19dc6e4ad Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:00:05 -0300 Subject: [PATCH 29/39] fix: address subprocess lifecycle review --- .../sensors/__tests__/testsPassing.test.ts | 83 +++++ .../out/sensors/jestResultProjector.ts | 319 ++++++++++++++++++ .../adapters/out/sensors/testsPassing.ts | 155 ++++----- src/harness/domain/execution/index.ts | 7 + .../execution/processTreeTermination.ts | 88 +++++ .../plans/__tests__/acceptanceRunner.test.ts | 40 +++ .../domain/workflow/plans/acceptanceRunner.ts | 27 +- 7 files changed, 627 insertions(+), 92 deletions(-) create mode 100644 src/harness/adapters/out/sensors/jestResultProjector.ts create mode 100644 src/harness/domain/execution/processTreeTermination.ts diff --git a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts index e2984e2e..e6e49fb9 100644 --- a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts +++ b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts @@ -23,6 +23,15 @@ describe('tests-passing sensor', () => { return ['node', '-e', body]; } + function processExists(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + } + it('passes when jest-style JSON shows zero failures and exit 0', async () => { const json = JSON.stringify({ numPassedTests: 5, @@ -40,6 +49,31 @@ describe('tests-passing sensor', () => { expect(out.numFailedTests).toBe(0); }); + it('spools complete structured output for custom Jest commands larger than the tail', async () => { + const json = JSON.stringify({ + irrelevant: 'x'.repeat(30 * 1024), + numPassedTests: 7, + numFailedTests: 0, + numTotalTestSuites: 3, + testResults: [], + }); + const result = await executeTestsPassing(tempDir, { + sessionId: 's', + context: { + kind: 'jest', + testCommand: nodeScript(`process.stdout.write(${JSON.stringify(json)})`), + tailBytes: 8 * 1024, + }, + }); + + expect(result.status).toBe('passed'); + expect(result.output).toEqual(expect.objectContaining({ + numPassedTests: 7, + numTotalTestSuites: 3, + })); + expect(result.details).toEqual(expect.objectContaining({ outputTruncated: true })); + }); + it('uses a temporary output file for the default Jest command', async () => { await fs.writeJson(path.join(tempDir, 'package.json'), { scripts: { test: 'node fake-jest.js' }, @@ -172,6 +206,28 @@ describe('tests-passing sensor', () => { })); }); + it('terminates descendants that inherit pipes when the hard limit is exceeded', async () => { + const pidPath = path.join(tempDir, 'sensor-grandchild.pid'); + const script = [ + "const {spawn}=require('child_process');", + "const fs=require('fs');", + "const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});", + `fs.writeFileSync(${JSON.stringify(pidPath)},String(child.pid));`, + "const c='x'.repeat(4096); while(true) process.stdout.write(c);", + ].join(''); + + const startedAt = Date.now(); + const result = await runShell(nodeScript(script), tempDir, 10_000, { + tailBytes: 128, + hardCombinedOutputBytes: 32 * 1024, + }); + const grandchildPid = Number(await fs.readFile(pidPath, 'utf8')); + + expect(result.outputLimitExceeded).toBe(true); + expect(Date.now() - startedAt).toBeLessThan(3_000); + expect(processExists(grandchildPid)).toBe(false); + }); + it('reports timeout and spawn error termination paths', async () => { const timedOut = await executeTestsPassing(tempDir, { sessionId: 's', @@ -203,4 +259,31 @@ describe('tests-passing sensor', () => { await fs.writeFile(malformed, '{not-json'); await expect(readJestResultFile(malformed)).resolves.toEqual({ status: 'malformed' }); }); + + it('projects a near-limit Jest file without materializing irrelevant fields', async () => { + const nearLimit = path.join(tempDir, 'near-limit.json'); + const handle = await nativeFs.open(nearLimit, 'w'); + await handle.write('{"numPassedTests":11,"numFailedTests":0,"numTotalTestSuites":4,"irrelevant":"'); + const chunk = 'z'.repeat(64 * 1024); + for (let index = 0; index < 496; index += 1) await handle.write(chunk); + await handle.write('","testResults":[]}'); + await handle.close(); + + const before = process.memoryUsage().heapUsed; + const projected = await readJestResultFile(nearLimit); + const heapGrowth = process.memoryUsage().heapUsed - before; + + expect(projected).toEqual({ + status: 'ok', + value: { + numPassedTests: 11, + numFailedTests: 0, + numTotalTestSuites: 4, + failures: [], + }, + }); + // The file is ~31 MiB; projection should stay far below a full string plus + // parsed object. Leave headroom for Jest/GC noise while catching regressions. + expect(heapGrowth).toBeLessThan(16 * 1024 * 1024); + }, 30_000); }); diff --git a/src/harness/adapters/out/sensors/jestResultProjector.ts b/src/harness/adapters/out/sensors/jestResultProjector.ts new file mode 100644 index 00000000..4192e570 --- /dev/null +++ b/src/harness/adapters/out/sensors/jestResultProjector.ts @@ -0,0 +1,319 @@ +import { createReadStream, promises as fs } from 'fs'; +import { MAX_JEST_RESULT_FILE_BYTES } from '../../../domain/execution'; + +export interface ProjectedJestResult { + numPassedTests: number; + numFailedTests: number; + numTotalTestSuites: number; + failures: Array<{ name: string; message: string }>; +} + +export type ProjectedJestResultRead = + | { status: 'ok'; value: ProjectedJestResult } + | { status: 'resultFileTooLarge' } + | { status: 'malformed' }; + +type PathSegment = string | number; +type JsonPath = PathSegment[]; + +type ObjectState = 'keyOrEnd' | 'key' | 'colon' | 'value' | 'commaOrEnd'; +type ArrayState = 'valueOrEnd' | 'value' | 'commaOrEnd'; +type Frame = + | { kind: 'object'; path: JsonPath; state: ObjectState; key?: string } + | { kind: 'array'; path: JsonPath; state: ArrayState; index: number }; + +const MAX_TOKEN_STRING_CHARS = 4_096; + +function samePath(left: JsonPath, right: JsonPath): boolean { + return left.length === right.length && left.every((part, index) => part === right[index]); +} + +function assertionPath(path: JsonPath): boolean { + return path.length === 4 && path[0] === 'testResults' && typeof path[1] === 'number' + && path[2] === 'assertionResults' && typeof path[3] === 'number'; +} + +class JestProjection { + readonly result: ProjectedJestResult = { + numPassedTests: 0, + numFailedTests: 0, + numTotalTestSuites: 0, + failures: [], + }; + + private current?: { + path: JsonPath; + status?: string; + fullName?: string; + title?: string; + failureMessages: string[]; + }; + + startObject(path: JsonPath): void { + if (assertionPath(path)) { + this.current = { path, failureMessages: [] }; + } + } + + endObject(path: JsonPath): void { + if (!this.current || !samePath(this.current.path, path)) return; + if (this.current.status === 'failed' && this.result.failures.length < 100) { + this.result.failures.push({ + name: (this.current.fullName ?? this.current.title ?? 'unknown').slice(0, 2_000), + message: this.current.failureMessages.join('\n').slice(0, 2_000), + }); + } + this.current = undefined; + } + + primitive(path: JsonPath, value: string | number | boolean | null): void { + if (path.length === 1 && typeof value === 'number') { + if (path[0] === 'numPassedTests') this.result.numPassedTests = value; + if (path[0] === 'numFailedTests') this.result.numFailedTests = value; + if (path[0] === 'numTotalTestSuites') this.result.numTotalTestSuites = value; + return; + } + if (!this.current || path.length < 5) return; + const base = path.slice(0, 4); + if (!samePath(base, this.current.path)) return; + const field = path[4]; + if (field === 'status' && typeof value === 'string') this.current.status = value; + if (field === 'fullName' && typeof value === 'string') this.current.fullName = value; + if (field === 'title' && typeof value === 'string') this.current.title = value; + if ( + field === 'failureMessages' + && typeof path[5] === 'number' + && typeof value === 'string' + && this.current.failureMessages.length < 10 + ) { + this.current.failureMessages.push(value.slice(0, 2_000)); + } + } +} + +class StreamingJsonProjector { + private readonly frames: Frame[] = []; + private readonly projection = new JestProjection(); + private started = false; + private complete = false; + private failed = false; + private mode: 'normal' | 'string' | 'number' | 'literal' = 'normal'; + private stringValue = ''; + private escaped = false; + private unicodeDigits = ''; + private scalarValue = ''; + + write(chunk: string): void { + for (let index = 0; index < chunk.length && !this.failed; index += 1) { + const char = chunk[index]; + if (!this.started) { + if (char === '{') { + this.started = true; + this.consumePunctuation(char); + } + continue; + } + + if (this.complete) { + if (!/\s/.test(char)) this.failed = true; + continue; + } + + if (this.mode === 'string') { + this.consumeStringCharacter(char); + continue; + } + if (this.mode === 'number' || this.mode === 'literal') { + if (/\s|[\]},{:]/.test(char)) { + this.finishScalar(); + index -= 1; + } else { + if (this.scalarValue.length < 128) this.scalarValue += char; + else this.failed = true; + } + continue; + } + if (/\s/.test(char)) continue; + if (char === '"') { + this.mode = 'string'; + this.stringValue = ''; + this.escaped = false; + this.unicodeDigits = ''; + } else if (/[\[\]{},:]/.test(char)) { + this.consumePunctuation(char); + } else if (char === '-' || /[0-9]/.test(char)) { + this.mode = 'number'; + this.scalarValue = char; + } else if (/[tfn]/.test(char)) { + this.mode = 'literal'; + this.scalarValue = char; + } else { + this.failed = true; + } + } + } + + finish(): ProjectedJestResult | null { + if (this.mode === 'number' || this.mode === 'literal') this.finishScalar(); + if (this.mode !== 'normal' || this.failed || !this.started || !this.complete) return null; + return this.projection.result; + } + + private appendString(char: string): void { + if (this.stringValue.length < MAX_TOKEN_STRING_CHARS) this.stringValue += char; + } + + private consumeStringCharacter(char: string): void { + if (this.unicodeDigits) { + if (!/[0-9a-fA-F]/.test(char)) { + this.failed = true; + return; + } + this.unicodeDigits += char; + if (this.unicodeDigits.length === 5) { + this.appendString(String.fromCharCode(Number.parseInt(this.unicodeDigits.slice(1), 16))); + this.unicodeDigits = ''; + this.escaped = false; + } + return; + } + if (this.escaped) { + if (char === 'u') { + this.unicodeDigits = 'u'; + return; + } + const escapes: Record = { + '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t', + }; + if (!(char in escapes)) { + this.failed = true; + return; + } + this.appendString(escapes[char]); + this.escaped = false; + return; + } + if (char === '\\') { + this.escaped = true; + } else if (char === '"') { + this.mode = 'normal'; + this.consumePrimitive(this.stringValue); + } else if (char.charCodeAt(0) < 0x20) { + this.failed = true; + } else { + this.appendString(char); + } + } + + private finishScalar(): void { + const raw = this.scalarValue; + this.scalarValue = ''; + const mode = this.mode; + this.mode = 'normal'; + if (mode === 'literal') { + if (raw === 'true') this.consumePrimitive(true); + else if (raw === 'false') this.consumePrimitive(false); + else if (raw === 'null') this.consumePrimitive(null); + else this.failed = true; + return; + } + const validNumber = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(raw); + const value = Number(raw); + if (!validNumber || !Number.isFinite(value)) this.failed = true; + else this.consumePrimitive(value); + } + + private valuePath(): JsonPath | null { + if (this.frames.length === 0) return []; + const parent = this.frames[this.frames.length - 1]; + if (parent.kind === 'object') { + if (parent.state !== 'value' || parent.key === undefined) return null; + const path = [...parent.path, parent.key]; + parent.key = undefined; + parent.state = 'commaOrEnd'; + return path; + } + if (parent.state !== 'value' && parent.state !== 'valueOrEnd') return null; + const path = [...parent.path, parent.index]; + parent.index += 1; + parent.state = 'commaOrEnd'; + return path; + } + + private consumePrimitive(value: string | number | boolean | null): void { + const top = this.frames[this.frames.length - 1]; + if (typeof value === 'string' && top?.kind === 'object' + && (top.state === 'keyOrEnd' || top.state === 'key')) { + top.key = value; + top.state = 'colon'; + return; + } + const path = this.valuePath(); + if (!path) this.failed = true; + else this.projection.primitive(path, value); + } + + private consumePunctuation(char: string): void { + if (char === '{' || char === '[') { + const path = this.valuePath(); + if (!path) { + this.failed = true; + return; + } + if (char === '{') { + this.frames.push({ kind: 'object', path, state: 'keyOrEnd' }); + this.projection.startObject(path); + } else { + this.frames.push({ kind: 'array', path, state: 'valueOrEnd', index: 0 }); + } + return; + } + + const top = this.frames[this.frames.length - 1]; + if (!top) { + this.failed = true; + return; + } + if (char === ':') { + if (top.kind !== 'object' || top.state !== 'colon') this.failed = true; + else top.state = 'value'; + return; + } + if (char === ',') { + if (top.state !== 'commaOrEnd') this.failed = true; + else if (top.kind === 'object') top.state = 'key'; + else top.state = 'value'; + return; + } + if (char === '}') { + if (top.kind !== 'object' || (top.state !== 'keyOrEnd' && top.state !== 'commaOrEnd')) { + this.failed = true; + return; + } + this.frames.pop(); + this.projection.endObject(top.path); + } else if (char === ']') { + if (top.kind !== 'array' || (top.state !== 'valueOrEnd' && top.state !== 'commaOrEnd')) { + this.failed = true; + return; + } + this.frames.pop(); + } + if (this.frames.length === 0) this.complete = true; + } +} + +export async function projectJestResultFile(resultPath: string): Promise { + try { + const stat = await fs.stat(resultPath); + if (stat.size > MAX_JEST_RESULT_FILE_BYTES) return { status: 'resultFileTooLarge' }; + + const parser = new StreamingJsonProjector(); + const stream = createReadStream(resultPath, { encoding: 'utf-8', highWaterMark: 64 * 1024 }); + for await (const chunk of stream) parser.write(chunk); + const value = parser.finish(); + return value ? { status: 'ok', value } : { status: 'malformed' }; + } catch { + return { status: 'malformed' }; + } +} diff --git a/src/harness/adapters/out/sensors/testsPassing.ts b/src/harness/adapters/out/sensors/testsPassing.ts index 194bbe8c..ac9f983c 100644 --- a/src/harness/adapters/out/sensors/testsPassing.ts +++ b/src/harness/adapters/out/sensors/testsPassing.ts @@ -4,7 +4,7 @@ * Two modes: * - `kind: 'jest'` (default): runs `npm test -- --runInBand --json`, writes * structured results to a size-checked temporary file, and keeps console - * output bounded. Configured commands retain legacy JSON-on-stdout parsing. + * output bounded. Configured commands spool structured stdout to disk. * Passes iff exit code 0 AND `numFailedTests === 0`. * - `kind: 'exit-code'`: runs the configured `testCommand` argv array and * passes iff the process exits with code 0. Use this for non-jest test @@ -17,7 +17,7 @@ */ import { spawn } from 'child_process'; -import { promises as fs } from 'fs'; +import { closeSync, openSync, promises as fs, writeSync } from 'fs'; import * as os from 'os'; import * as path from 'path'; import type { @@ -29,10 +29,12 @@ import { BoundedByteCollector, DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, DEFAULT_SUBPROCESS_TAIL_BYTES, - MAX_JEST_RESULT_FILE_BYTES, resolveSubprocessOutputLimits, + subprocessSpawnOptions, + terminateProcessTree, type SubprocessOutputLimitsInput, } from '../../../domain/execution'; +import { projectJestResultFile, type ProjectedJestResultRead } from './jestResultProjector'; export interface TestsPassingOptions { kind?: 'jest' | 'exit-code'; @@ -90,6 +92,11 @@ export interface SpawnResult { terminationReason?: 'timeout' | 'outputLimit' | 'spawnError'; } +function writeComplete(fd: number, chunk: Buffer): void { + let offset = 0; + while (offset < chunk.length) offset += writeSync(fd, chunk, offset); +} + function emptySpawnResult(startedAt: number, spawnError: string): SpawnResult { return { exitCode: null, @@ -112,12 +119,22 @@ export function runShell( argv: string[], cwd: string, timeoutMs: number, - outputLimits: SubprocessOutputLimitsInput = {} + outputLimits: SubprocessOutputLimitsInput = {}, + structuredStdoutPath?: string ): Promise { return new Promise((resolve) => { const startedAt = Date.now(); const [executable, ...args] = argv; const limits = resolveSubprocessOutputLimits(outputLimits); + let structuredStdoutFd: number | undefined; + if (structuredStdoutPath) { + try { + structuredStdoutFd = openSync(structuredStdoutPath, 'w'); + } catch (err) { + resolve(emptySpawnResult(startedAt, err instanceof Error ? err.message : String(err))); + return; + } + } let child: ReturnType; try { child = spawn(executable, args, { @@ -125,8 +142,10 @@ export function runShell( shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: process.env, + ...subprocessSpawnOptions(), }); } catch (err) { + if (structuredStdoutFd !== undefined) closeSync(structuredStdoutFd); resolve(emptySpawnResult(startedAt, err instanceof Error ? err.message : String(err))); return; } @@ -137,17 +156,38 @@ export function runShell( let outputLimitExceeded = false; let settled = false; let spawnError: Error | undefined; + let exitCodeSeen: number | null = null; + let termination: Promise | undefined; let timer: NodeJS.Timeout; + const requestTermination = () => { + if (termination) return; + clearTimeout(timer); + termination = terminateProcessTree(child); + void termination.then(() => { + // A hostile descendant may keep inherited pipes open. Once the whole + // tree has received the forced signal, stop waiting on those streams. + child.stdout?.destroy(); + child.stderr?.destroy(); + void finish(exitCodeSeen); + }); + }; const capture = (collector: BoundedByteCollector, chunk: Buffer) => { collector.append(chunk); + if (collector === stdout && structuredStdoutFd !== undefined) { + try { + writeComplete(structuredStdoutFd, chunk); + } catch (err) { + spawnError = err instanceof Error ? err : new Error(String(err)); + requestTermination(); + } + } if ( !outputLimitExceeded && stdout.totalBytes + stderr.totalBytes > limits.hardCombinedOutputBytes ) { outputLimitExceeded = true; - clearTimeout(timer); - child.kill('SIGKILL'); + requestTermination(); } }; @@ -157,13 +197,19 @@ export function runShell( timer = setTimeout(() => { if (outputLimitExceeded) return; timedOut = true; - child.kill('SIGKILL'); + requestTermination(); }, timeoutMs); - const finish = (exitCode: number | null) => { + const finish = async (exitCode: number | null) => { + if (settled) return; + if (termination) await termination; if (settled) return; settled = true; clearTimeout(timer); + if (structuredStdoutFd !== undefined) { + closeSync(structuredStdoutFd); + structuredStdoutFd = undefined; + } resolve({ exitCode, stdoutTail: stdout.toString(), @@ -190,43 +236,15 @@ export function runShell( // Wait for close after error/kill so the child is always reaped before the // promise resolves. child.on('error', (err) => { spawnError = err; }); - child.on('close', (code) => finish(code)); + child.on('exit', (code) => { exitCodeSeen = code; }); + child.on('close', (code) => { void finish(code); }); }); } -function extractJsonFromStdout(stdout: string): unknown | null { - // Jest --json sometimes emits warnings on stdout before the JSON object. - // Find the first `{` and try to parse from there. - const trimmed = stdout.trim(); - if (!trimmed) return null; - if (trimmed.startsWith('{')) { - try { return JSON.parse(trimmed); } catch { /* fallthrough */ } - } - const idx = stdout.indexOf('{'); - if (idx === -1) return null; - try { - return JSON.parse(stdout.slice(idx)); - } catch { - return null; - } -} - -export type JestResultFileRead = - | { status: 'ok'; value: unknown } - | { status: 'resultFileTooLarge' } - | { status: 'malformed' }; +export type JestResultFileRead = ProjectedJestResultRead; export async function readJestResultFile(resultPath: string): Promise { - try { - const stat = await fs.stat(resultPath); - if (stat.size > MAX_JEST_RESULT_FILE_BYTES) { - return { status: 'resultFileTooLarge' }; - } - const contents = await fs.readFile(resultPath, 'utf-8'); - return { status: 'ok', value: JSON.parse(contents) }; - } catch { - return { status: 'malformed' }; - } + return projectJestResultFile(resultPath); } export function subprocessDetails(result: SpawnResult, argv: string[]): Record { @@ -251,17 +269,19 @@ export async function executeTestsPassing( let resultDirectory: string | undefined; let resultPath: string | undefined; let command = opts.testCommand; - if (opts.kind === 'jest' && opts.usesDefaultCommand) { + let structuredStdoutPath: string | undefined; + if (opts.kind === 'jest') { resultDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-jest-')); resultPath = path.join(resultDirectory, 'result.json'); - command = [...DEFAULT_JEST_COMMAND, '--outputFile', resultPath]; + if (opts.usesDefaultCommand) command = [...DEFAULT_JEST_COMMAND, '--outputFile', resultPath]; + else structuredStdoutPath = resultPath; } try { const result = await runShell(command, repoPath, opts.timeoutMs, { tailBytes: opts.tailBytes, hardCombinedOutputBytes: opts.hardOutputLimitBytes, - }); + }, structuredStdoutPath); const details = subprocessDetails(result, command); @@ -309,9 +329,8 @@ export async function executeTestsPassing( }; } - // Default Jest runs write structured output to a bounded temporary file. - // Configured commands retain legacy stdout parsing, but stdout itself is - // now always a bounded tail. + // Default Jest writes with --outputFile; custom Jest commands have stdout + // spooled directly to the same size-checked structured-output path. const fileRead = resultPath ? await readJestResultFile(resultPath) : undefined; if (fileRead?.status === 'resultFileTooLarge') { return { @@ -321,10 +340,7 @@ export async function executeTestsPassing( details, }; } - const parsed = fileRead?.status === 'ok' - ? fileRead.value - : extractJsonFromStdout(result.stdoutTail); - if (!parsed || typeof parsed !== 'object') { + if (fileRead?.status !== 'ok') { return { status: 'failed', summary: 'tests-passing: could not parse jest --json output', @@ -338,43 +354,8 @@ export async function executeTestsPassing( }; } - const j = parsed as Record; - const numPassedTests = typeof j.numPassedTests === 'number' ? j.numPassedTests : 0; - const numFailedTests = typeof j.numFailedTests === 'number' ? j.numFailedTests : 0; - const numTotalTestSuites = typeof j.numTotalTestSuites === 'number' ? j.numTotalTestSuites : 0; - - const failures: Array<{ name: string; message: string }> = []; - const testResults = Array.isArray(j.testResults) ? j.testResults : []; - for (const suite of testResults) { - if (!suite || typeof suite !== 'object') continue; - const s = suite as Record; - const assertionResults = Array.isArray(s.assertionResults) ? s.assertionResults : []; - for (const a of assertionResults) { - if (!a || typeof a !== 'object') continue; - const ar = a as Record; - if (ar.status === 'failed') { - const messages = Array.isArray(ar.failureMessages) ? ar.failureMessages : []; - if (failures.length >= 100) continue; - failures.push({ - name: typeof ar.fullName === 'string' - ? ar.fullName - : (typeof ar.title === 'string' ? ar.title : 'unknown'), - message: messages - .slice(0, 10) - .map((m) => String(m).slice(0, 2000)) - .join('\n') - .slice(0, 2000), - }); - } - } - } - - const report: TestsPassingReport = { - numPassedTests, - numFailedTests, - numTotalTestSuites, - failures, - }; + const report: TestsPassingReport = fileRead.value; + const { numPassedTests, numFailedTests, numTotalTestSuites, failures } = report; const passed = result.exitCode === 0 && numFailedTests === 0; if (passed) { diff --git a/src/harness/domain/execution/index.ts b/src/harness/domain/execution/index.ts index 563530f0..a271f343 100644 --- a/src/harness/domain/execution/index.ts +++ b/src/harness/domain/execution/index.ts @@ -11,3 +11,10 @@ export { type SubprocessOutputLimits, type SubprocessOutputLimitsInput, } from './boundedByteCollector'; +export { + PROCESS_TREE_TERMINATION_GRACE_MS, + PROCESS_TREE_TERMINATION_SETTLE_MS, + subprocessSpawnOptions, + terminateProcessTree, + type ProcessTreeTerminationOptions, +} from './processTreeTermination'; diff --git a/src/harness/domain/execution/processTreeTermination.ts b/src/harness/domain/execution/processTreeTermination.ts new file mode 100644 index 00000000..a542e736 --- /dev/null +++ b/src/harness/domain/execution/processTreeTermination.ts @@ -0,0 +1,88 @@ +import { spawn, type ChildProcess } from 'child_process'; + +export const PROCESS_TREE_TERMINATION_GRACE_MS = 200; +export const PROCESS_TREE_TERMINATION_SETTLE_MS = 50; + +export interface ProcessTreeTerminationOptions { + graceMs?: number; + settleMs?: number; +} + +/** + * Spawn children in their own process group on POSIX so timeouts and output + * ceilings can terminate descendants which inherited the child's stdio. + */ +export function subprocessSpawnOptions(): { detached: boolean } { + return { detached: process.platform !== 'win32' }; +} + +function signalPosixTree(child: ChildProcess, signal: NodeJS.Signals): void { + if (child.pid && child.pid > 0) { + try { + process.kill(-child.pid, signal); + return; + } catch { + // The process group may already be gone or the platform may not support + // negative pids. Fall through to the direct-child fallback. + } + } + try { child.kill(signal); } catch { /* already exited */ } +} + +function forceWindowsTree(child: ChildProcess, settleMs: number): Promise { + if (!child.pid || child.pid <= 0) { + try { child.kill('SIGKILL'); } catch { /* already exited */ } + return Promise.resolve(); + } + + return new Promise((resolve) => { + let settled = false; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(); + }; + const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { + stdio: 'ignore', + windowsHide: true, + shell: false, + }); + const timer = setTimeout(() => { + try { child.kill('SIGKILL'); } catch { /* already exited */ } + finish(); + }, Math.max(settleMs, 250)); + killer.once('error', () => { + try { child.kill('SIGKILL'); } catch { /* already exited */ } + finish(); + }); + killer.once('close', finish); + }); +} + +/** + * Terminate a child and every descendant with bounded escalation. + * + * POSIX children must be spawned with `subprocessSpawnOptions()` so the + * negative-pid signals target only their process group. Windows uses taskkill + * with `/T` because Node does not expose Job Objects through child_process. + */ +export async function terminateProcessTree( + child: ChildProcess, + options: ProcessTreeTerminationOptions = {} +): Promise { + const graceMs = Math.max(0, options.graceMs ?? PROCESS_TREE_TERMINATION_GRACE_MS); + const settleMs = Math.max(0, options.settleMs ?? PROCESS_TREE_TERMINATION_SETTLE_MS); + + if (process.platform === 'win32') { + await forceWindowsTree(child, settleMs); + return; + } + + signalPosixTree(child, 'SIGTERM'); + await new Promise((resolve) => setTimeout(resolve, graceMs)); + // Escalate even if the direct child has exited: an ignoring descendant can + // still own the process group and inherited pipes. + signalPosixTree(child, 'SIGKILL'); + if (settleMs > 0) await new Promise((resolve) => setTimeout(resolve, settleMs)); +} diff --git a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts index 69742067..2847c293 100644 --- a/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts +++ b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts @@ -1,8 +1,20 @@ import { runAcceptance } from '../acceptanceRunner'; +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; describe('runAcceptance', () => { const ctx = { repoPath: process.cwd() }; + function processExists(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + } + it('passes when command exits 0', async () => { const result = await runAcceptance( { kind: 'shell', command: ['node', '-e', 'process.exit(0)'] }, @@ -113,6 +125,34 @@ describe('runAcceptance', () => { expect(Buffer.byteLength(result.tailStdout)).toBeLessThanOrEqual(128); }); + it('terminates a long-lived descendant and completes within the timeout bound', async () => { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'acceptance-tree-')); + const pidPath = path.join(tempDir, 'grandchild.pid'); + const script = [ + "const {spawn}=require('child_process');", + "const fs=require('fs');", + "const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});", + `fs.writeFileSync(${JSON.stringify(pidPath)},String(child.pid));`, + 'setInterval(()=>{},1000);', + ].join(''); + + try { + const startedAt = Date.now(); + const result = await runAcceptance({ + kind: 'shell', + command: ['node', '-e', script], + timeoutMs: 100, + }, ctx); + const grandchildPid = Number(await fs.readFile(pidPath, 'utf8')); + + expect(result.timedOut).toBe(true); + expect(Date.now() - startedAt).toBeLessThan(3_000); + expect(processExists(grandchildPid)).toBe(false); + } finally { + await fs.remove(tempDir); + } + }); + it('rejects an empty command array', async () => { await expect( runAcceptance({ kind: 'shell', command: [] }, ctx) diff --git a/src/harness/domain/workflow/plans/acceptanceRunner.ts b/src/harness/domain/workflow/plans/acceptanceRunner.ts index 2bfe6210..db959c02 100644 --- a/src/harness/domain/workflow/plans/acceptanceRunner.ts +++ b/src/harness/domain/workflow/plans/acceptanceRunner.ts @@ -13,6 +13,8 @@ import { DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, DEFAULT_SUBPROCESS_TAIL_BYTES, resolveSubprocessOutputLimits, + subprocessSpawnOptions, + terminateProcessTree, } from '../../execution'; import type { StepAcceptanceRun, StepAcceptanceSpec } from './executionTypes'; @@ -80,6 +82,7 @@ export async function runAcceptance( shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: process.env, + ...subprocessSpawnOptions(), }); } catch (err) { resolve({ @@ -106,8 +109,20 @@ export async function runAcceptance( const stderr = new BoundedByteCollector(limits.tailBytes); let outputLimitExceeded = false; let spawnError: Error | undefined; + let exitCodeSeen: number | null = null; + let termination: Promise | undefined; let timer: NodeJS.Timeout; + const requestTermination = () => { + if (termination) return; + clearTimeout(timer); + termination = terminateProcessTree(child); + void termination.then(() => { + child.stdout?.destroy(); + child.stderr?.destroy(); + void finish(exitCodeSeen); + }); + }; const capture = (collector: BoundedByteCollector, chunk: Buffer) => { collector.append(chunk); if ( @@ -115,8 +130,7 @@ export async function runAcceptance( stdout.totalBytes + stderr.totalBytes > limits.hardCombinedOutputBytes ) { outputLimitExceeded = true; - clearTimeout(timer); - child.kill('SIGKILL'); + requestTermination(); } }; @@ -126,10 +140,12 @@ export async function runAcceptance( timer = setTimeout(() => { if (outputLimitExceeded) return; timedOut = true; - child.kill('SIGKILL'); + requestTermination(); }, timeoutMs); - const finish = (exitCode: number | null) => { + const finish = async (exitCode: number | null) => { + if (settled) return; + if (termination) await termination; if (settled) return; settled = true; clearTimeout(timer); @@ -164,6 +180,7 @@ export async function runAcceptance( spawnError = err; stderr.append(Buffer.from(`spawn error: ${err.message}`)); }); - child.on('close', (code) => finish(code)); + child.on('exit', (code) => { exitCodeSeen = code; }); + child.on('close', (code) => { void finish(code); }); }); } From 312229e18bee8f093fe4ccf30087886852fa2858 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:04:17 -0300 Subject: [PATCH 30/39] fix: address semantic analysis review findings --- .../f-05-shared-semantic-analysis.md | 2 +- .../__tests__/codebaseAnalyzer.test.ts | 21 +++- .../__tests__/semanticSnapshotService.test.ts | 58 +++++++++ .../adapters/out/semantic/codebaseAnalyzer.ts | 11 +- .../out/semantic/semanticSnapshotService.ts | 111 ++++++++---------- .../context/__tests__/contextTools.test.ts | 4 +- src/utils/__tests__/fileMapper.test.ts | 23 ++++ src/utils/fileMapper.ts | 18 +-- 8 files changed, 164 insertions(+), 84 deletions(-) diff --git a/specs/performance/f-05-shared-semantic-analysis.md b/specs/performance/f-05-shared-semantic-analysis.md index a0da6673..7da554ea 100644 --- a/specs/performance/f-05-shared-semantic-analysis.md +++ b/specs/performance/f-05-shared-semantic-analysis.md @@ -60,7 +60,7 @@ Defaults: | single source file | 2 MiB | | directories scanned | 10,000 (absolute maximum 50,000) | | raw directory entries scanned | 100,000 (absolute maximum 500,000) | -| file analysis concurrency | 16 | +| file analysis concurrency | 16 (absolute maximum 64) | | fingerprint attempts | 2 | Skip oversized files with a reason and mark partial=true. diff --git a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts index 0f8ea65b..ac373380 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -2,7 +2,7 @@ import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs-extra'; -import { CodebaseAnalyzer } from '../codebaseAnalyzer'; +import { CodebaseAnalyzer, MAX_FILE_ANALYSIS_CONCURRENCY } from '../codebaseAnalyzer'; import type { SemanticContext, FileAnalysis, ExtractedSymbol } from '../types'; // Mock TreeSitterLayer @@ -165,6 +165,25 @@ describe('CodebaseAnalyzer', () => { expect(bundle.metrics.entriesScanned).toBeGreaterThan(0); }); + it('normalizes invalid concurrency and absolute-clamps extreme direct API values', async () => { + const source = path.join(tempDir, 'src', 'index.ts'); + const cases: Array<{ concurrency: number; expected: number }> = [ + { concurrency: Number.NaN, expected: 16 }, + { concurrency: Number.POSITIVE_INFINITY, expected: 16 }, + { concurrency: 0, expected: 1 }, + { concurrency: 3.9, expected: 3 }, + { concurrency: Number.MAX_SAFE_INTEGER, expected: MAX_FILE_ANALYSIS_CONCURRENCY }, + ]; + + for (const testCase of cases) { + const bundle = await new CodebaseAnalyzer({ concurrency: testCase.concurrency }) + .analyzeBundle(tempDir, [source]); + expect(bundle.limits.concurrency).toBe(testCase.expected); + expect(bundle.metrics.filesParsed).toBe(1); + expect(bundle.metrics.maxInFlight).toBeLessThanOrEqual(testCase.expected); + } + }); + it('bounds a 3000-file-equivalent analysis and reports maximum in-flight work', async () => { const files = Array.from({ length: 3000 }, (_, index) => path.join(tempDir, 'scale', `file-${index}.ts`) diff --git a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts index 512402c5..e4da9916 100644 --- a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts @@ -77,6 +77,64 @@ describe('SemanticSnapshotService', () => { expect(await fs.pathExists(path.join(outputDir, 'cache', 'semantic', 'manifest.json'))).toBe(true); }); + it('verifies and retries an initial write when the repository changes during generation', async () => { + await fs.remove(path.join(repoPath, 'src', 'auth.ts')); + const repoStructure = await new FileMapper().mapRepository(repoPath); + const service = new SemanticSnapshotService(); + let mutationInjected = false; + const originalBuild = (service as any).buildSnapshotArtifacts.bind(service); + const buildSpy = jest.spyOn(service as any, 'buildSnapshotArtifacts').mockImplementation( + async (...args: unknown[]) => { + if (!mutationInjected) { + mutationInjected = true; + await fs.writeFile( + path.join(repoPath, 'src', 'auth.ts'), + 'export const login = () => "ok";\n' + ); + } + return originalBuild(...args); + } + ); + + const result = await service.writeSnapshot(repoStructure, { outputDir }); + + expect(buildSpy).toHaveBeenCalledTimes(2); + expect(result.metrics.stabilizationAttempts).toBe(2); + expect(result.summary.functionalPatterns.hasAuthPattern).toBe(true); + }); + + it('retains the previous manifest when a direct write cannot stabilize', async () => { + const mapper = new FileMapper(); + const service = new SemanticSnapshotService(); + const initialStructure = await mapper.mapRepository(repoPath); + const initial = await service.writeSnapshot(initialStructure, { outputDir }); + await fs.writeFile(path.join(repoPath, 'src', 'index.ts'), 'export const run = () => false;\n'); + const changedStructure = await mapper.mapRepository(repoPath); + let mutation = 0; + const originalBuild = (service as any).buildSnapshotArtifacts.bind(service); + const buildSpy = jest.spyOn(service as any, 'buildSnapshotArtifacts').mockImplementation( + async (...args: unknown[]) => { + const artifacts = await originalBuild(...args); + mutation += 1; + await fs.writeFile( + path.join(repoPath, 'src', 'auth.ts'), + `export const login = () => ${mutation};\n` + ); + return artifacts; + } + ); + + await expect(service.writeSnapshot(changedStructure, { outputDir })) + .rejects.toBeInstanceOf(RepositoryChangingError); + expect(buildSpy).toHaveBeenCalledTimes(2); + + const retained = await new SemanticSnapshotService().readSummary(repoPath, { + outputDir, + allowStale: true, + }); + expect(retained?.manifest?.generatedAt).toBe(initial.manifest.generatedAt); + }); + it('invalidates the snapshot when hidden config files change', async () => { const mapper = new FileMapper(); const repoStructure = await mapper.mapRepository(repoPath); diff --git a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts index 86cdaba0..b105913e 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -47,6 +47,9 @@ const DEFAULT_OPTIONS: Required = { cacheEnabled: true, }; +/** Absolute ceiling for direct API callers to avoid allocating excessive workers. */ +export const MAX_FILE_ANALYSIS_CONCURRENCY = 64; + export interface AnalysisLimits { maxFiles: number; maxTotalBytes: number; @@ -122,7 +125,13 @@ export class CodebaseAnalyzer { ABSOLUTE_FILE_MAPPING_SCAN_LIMITS.maxEntriesScanned, Math.max(0, Math.floor(this.options.maxEntriesScanned)) ); - this.options.concurrency = Math.max(1, this.options.concurrency); + const configuredConcurrency = Number.isFinite(this.options.concurrency) + ? Math.floor(this.options.concurrency) + : DEFAULT_OPTIONS.concurrency; + this.options.concurrency = Math.min( + MAX_FILE_ANALYSIS_CONCURRENCY, + Math.max(1, configuredConcurrency) + ); // Create LSPLayer if LSP mode is enabled if (this.options.useLSP) { diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index 2c5f8b94..46a04669 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -282,32 +282,54 @@ export class SemanticSnapshotService { const outputDir = this.resolveOutputDir(repoStructure.rootPath, options.outputDir); const snapshotDir = this.getSnapshotDir(outputDir); const publishedSummaryPath = path.join(snapshotDir, SUMMARY_FILENAME); + const fileMapper = new FileMapper([], this.fingerprintLimits); + let attemptStructure = repoStructure; + let attemptFingerprint = options.repoFingerprint; + let generationMs = 0; + + for (let attempt = 1; attempt <= MAX_REFRESH_ATTEMPTS; attempt += 1) { + const repoFingerprint = attemptFingerprint ?? ( + await this.computeRepoFingerprint(repoStructure.rootPath, attemptStructure) + ).fingerprint; + const attemptOptions: SemanticSnapshotWriteOptions = attempt === 1 + ? { ...options, repoFingerprint } + : { + outputDir: options.outputDir, + analyzerOptions: options.analyzerOptions, + repoFingerprint, + }; + const generationStartedAt = Date.now(); + const artifacts = await this.buildSnapshotArtifacts(attemptStructure, attemptOptions); + generationMs += Date.now() - generationStartedAt; + + const verificationStructure = await fileMapper.mapRepository(repoStructure.rootPath); + const verificationFingerprint = ( + await this.computeRepoFingerprint(repoStructure.rootPath, verificationStructure) + ).fingerprint; + if (verificationFingerprint !== repoFingerprint) { + attemptStructure = verificationStructure; + attemptFingerprint = verificationFingerprint; + continue; + } - const repoFingerprint = - options.repoFingerprint ?? (await this.computeRepoFingerprint(repoStructure.rootPath)).fingerprint; - - const generationStartedAt = Date.now(); - const artifacts = await this.buildSnapshotArtifacts(repoStructure, { - ...options, - repoFingerprint, - }); - const generationMs = Date.now() - generationStartedAt; - const publicationStartedAt = Date.now(); - const manifest = await this.publishSnapshotArtifacts({ - outputDir, - snapshotDir, - publishedSummaryPath, - artifacts, - }); - const publicationMs = Date.now() - publicationStartedAt; + const publicationStartedAt = Date.now(); + const manifest = await this.publishSnapshotArtifacts({ + outputDir, + snapshotDir, + publishedSummaryPath, + artifacts, + }); + const publicationMs = Date.now() - publicationStartedAt; + return { + summary: artifacts.summary, + manifest, + snapshotDir, + publishedSummaryPath, + metrics: { generationMs, publicationMs, stabilizationAttempts: attempt }, + }; + } - return { - summary: artifacts.summary, - manifest, - snapshotDir, - publishedSummaryPath, - metrics: { generationMs, publicationMs, stabilizationAttempts: 1 }, - }; + throw new RepositoryChangingError(repoStructure.rootPath, MAX_REFRESH_ATTEMPTS); } async ensureFreshSummary( @@ -416,45 +438,8 @@ export class SemanticSnapshotService { const refreshPromise = (async () => { const fileMapper = new FileMapper(); - const snapshotDir = this.getSnapshotDir(outputDir); - const publishedSummaryPath = path.join(snapshotDir, SUMMARY_FILENAME); - - for (let attempt = 1; attempt <= MAX_REFRESH_ATTEMPTS; attempt += 1) { - const repoStructure = await fileMapper.mapRepository(repoPath); - const repoFingerprint = (await this.computeRepoFingerprint(repoPath, repoStructure)).fingerprint; - const generationStartedAt = Date.now(); - const artifacts = await this.buildSnapshotArtifacts(repoStructure, { - outputDir, - repoFingerprint, - }); - const generationMs = Date.now() - generationStartedAt; - const verificationStructure = await fileMapper.mapRepository(repoPath); - const currentFingerprint = ( - await this.computeRepoFingerprint(repoPath, verificationStructure) - ).fingerprint; - - if (currentFingerprint !== repoFingerprint) { - continue; - } - - const publicationStartedAt = Date.now(); - const manifest = await this.publishSnapshotArtifacts({ - outputDir, - snapshotDir, - publishedSummaryPath, - artifacts, - }); - const publicationMs = Date.now() - publicationStartedAt; - return { - summary: artifacts.summary, - manifest, - snapshotDir, - publishedSummaryPath, - metrics: { generationMs, publicationMs, stabilizationAttempts: attempt }, - }; - } - - throw new RepositoryChangingError(repoPath, MAX_REFRESH_ATTEMPTS); + const repoStructure = await fileMapper.mapRepository(repoPath); + return this.writeSnapshot(repoStructure, { outputDir }); })(); SemanticSnapshotService.inFlightRefreshes.set(refreshKey, refreshPromise); diff --git a/src/harness/application/context/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index f44b93a1..cb95f58d 100644 --- a/src/harness/application/context/__tests__/contextTools.test.ts +++ b/src/harness/application/context/__tests__/contextTools.test.ts @@ -77,7 +77,7 @@ describe('contextTools sensors scaffolding', () => { })); }); - it('performs one discovery per operation and reuses fingerprint reads across operations', async () => { + it('performs one bundle discovery plus publication verification per operation', async () => { const repositoryDiscovery = jest.spyOn(FileMapper.prototype, 'mapRepository'); const first = await initializeContextTool.execute!( @@ -105,7 +105,7 @@ describe('contextTools sensors scaffolding', () => { const firstFingerprint = first._metadata.analysis.metrics.fingerprint; const secondFingerprint = second._metadata.analysis.metrics.fingerprint; - expect(repositoryDiscovery).toHaveBeenCalledTimes(2); + expect(repositoryDiscovery).toHaveBeenCalledTimes(4); expect(firstFingerprint.discoveries).toBe(0); expect(firstFingerprint.contentReads).toBe(firstFingerprint.files); expect(secondFingerprint.discoveries).toBe(0); diff --git a/src/utils/__tests__/fileMapper.test.ts b/src/utils/__tests__/fileMapper.test.ts index 9520f783..0cf093a0 100644 --- a/src/utils/__tests__/fileMapper.test.ts +++ b/src/utils/__tests__/fileMapper.test.ts @@ -51,6 +51,29 @@ describe('FileMapper bounded discovery', () => { await fs.remove(repoPath); }); + it('discovers source files under non-standard Python and Go roots', async () => { + const expected = [ + 'custompkg/main.py', + 'cmd/server/main.go', + 'internal/auth/service.go', + 'pkg/client/client.go', + ]; + await Promise.all(expected.map(async (relativePath) => { + const filePath = path.join(repoPath, relativePath); + await fs.ensureDir(path.dirname(filePath)); + await fs.writeFile(filePath, '# source\n'); + })); + await fs.ensureDir(path.join(repoPath, 'assets', 'nested')); + await fs.writeFile(path.join(repoPath, 'assets', 'nested', 'image.bin'), 'ignored'); + + const result = await new FileMapper().mapRepository(repoPath); + + expect(result.files.map((file) => file.relativePath)).toEqual([...expected].sort()); + expect(result.partial).toBe(false); + expect(result.discoveryMetrics?.directoriesScanned).toBe(10); + expect(result.discoveryMetrics?.statCalls).toBe(expected.length); + }); + it('stops before statting file candidates beyond the file cap', async () => { const directory = fakeDirectory( Array.from({ length: 5_100 }, (_, index) => fakeEntry(`file-${index}.ts`)) diff --git a/src/utils/fileMapper.ts b/src/utils/fileMapper.ts index 56c737a6..ec07a1c4 100644 --- a/src/utils/fileMapper.ts +++ b/src/utils/fileMapper.ts @@ -45,8 +45,6 @@ export const REPOSITORY_ROOT_FILES = [ '.eslintrc.json', '.prettierrc', '.prettierrc.json', '.nvmrc', '.node-version', ] as const; -const RELEVANT_SOURCE_ROOTS = new Set(['src', 'lib', 'bin', 'app', 'packages', 'scripts']); - export function isRepositoryRelevantFile(relativePath: string): boolean { const normalized = relativePath.split(path.sep).join('/'); const basename = path.posix.basename(normalized); @@ -57,10 +55,7 @@ export function isRepositoryRelevantFile(relativePath: string): boolean { if (segments[0] === '.github' && segments[1] === 'workflows') { return extension === 'yml' || extension === 'yaml'; } - if (segments.length === 1 || RELEVANT_SOURCE_ROOTS.has(segments[0])) { - return (REPOSITORY_RELEVANT_EXTENSIONS as readonly string[]).includes(extension); - } - return false; + return (REPOSITORY_RELEVANT_EXTENSIONS as readonly string[]).includes(extension); } const MAX_RECORDED_SKIPS = 1_000; @@ -188,9 +183,7 @@ export class FileMapper { if (this.isIgnored(relativePath, entry.isDirectory())) continue; if (entry.isDirectory()) { - if (!usesDefaultPatterns || this.shouldTraverseDefaultDirectory(relativePath)) { - directoryQueue.push(relativePath); - } + directoryQueue.push(relativePath); continue; } if (!entry.isFile()) continue; @@ -292,13 +285,6 @@ export class FileMapper { (isDirectory && this.gitIgnoreManager.shouldIgnore(`${relativePath}/`)); } - private shouldTraverseDefaultDirectory(relativePath: string): boolean { - const segments = relativePath.split('/'); - if (RELEVANT_SOURCE_ROOTS.has(segments[0])) return true; - if (segments[0] !== '.github') return false; - return segments.length === 1 || segments[1] === 'workflows'; - } - private recordSkip(skipped: RepoDiscoverySkip[], skip: RepoDiscoverySkip): void { if (skipped.length < MAX_RECORDED_SKIPS) skipped.push(skip); } From 4fcf64c9310dc6dead204910a15f14d8f3a7fb2f Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:08:16 -0300 Subject: [PATCH 31/39] fix: address cache retention review findings --- CHANGELOG.md | 3 +- .../docs/en/concepts/harness-runtime.md | 4 +- .../docs/en/reference/context-layout.md | 2 +- .../docs/pt-br/concepts/harness-runtime.md | 4 +- .../docs/pt-br/reference/context-layout.md | 2 +- .../__tests__/runtimeStateService.test.ts | 56 ++++++- .../out/runtimeState/runtimeStateService.ts | 132 +++++++++++++++-- .../__tests__/boundedFileDiscovery.test.ts | 4 +- .../semantic/__tests__/contextCache.test.ts | 11 ++ .../discovery/boundedFileDiscovery.ts | 54 ++++++- .../retention/runtimeRetentionConfig.ts | 21 ++- src/harness/index.ts | 2 + src/harness/ports/out/index.ts | 2 + .../shared/__tests__/hookSessionStore.test.ts | 33 +++++ src/integrations/shared/hookSessionStore.ts | 138 +++++++++++++----- .../logging/__tests__/actionLogger.test.ts | 24 +++ src/mcp/logging/actionLogger.ts | 5 +- 17 files changed, 429 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea8ee3bb..a06c91ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, raw directory-entry scan budgets, and safe runtime configuration clamps. -- Moved checkpoint payload history from `session.json` into individual checkpoint records with legacy dual-read and lazy migration. +- Moved checkpoint payload history from `session.json` into individually bounded, paginated checkpoint records with summary-only session reads, incremental counts, legacy dual-read, and lazy migration. +- Made host-session binding mutations atomic across concurrent hooks and prevented terminal MCP activity sessions from being reused. ## [1.1.1] - 2026-06-27 diff --git a/docs/src/content/docs/en/concepts/harness-runtime.md b/docs/src/content/docs/en/concepts/harness-runtime.md index a424b095..df228559 100644 --- a/docs/src/content/docs/en/concepts/harness-runtime.md +++ b/docs/src/content/docs/en/concepts/harness-runtime.md @@ -160,7 +160,9 @@ Add artifacts with the `harness` tool's `addArtifact` action and read them with A **checkpoint** is a named waypoint within a session. It bundles a set of artifacts and optional state so you have a meaningful, recoverable point to return to — useful between PREVC phases, before a risky step, or whenever you want a labeled snapshot. -Checkpoints are stored as individual records under `.context/runtime/sessions//checkpoints/`. `session.json` retains only the count and latest checkpoint identity, so checkpoint history does not make every session update progressively larger. Legacy inline checkpoints remain readable and migrate on the next checkpoint write. +Checkpoints are stored as individual records under `.context/runtime/sessions//checkpoints/`. `session.json` retains only the count and latest checkpoint identity, so normal session reads and writes never load the full checkpoint history. Runtime consumers can page through records with `listCheckpointsPage`; the complete `listCheckpoints` helper remains available for explicit replay-style operations. Legacy inline checkpoints remain readable and migrate on the next checkpoint write. + +Each new record is constrained by `checkpoints.maxSerializedBytes`; `data`, `note`, artifact count, and each artifact ID also have independent limits. This prevents a large label or identifier from bypassing the payload budget. ```json { diff --git a/docs/src/content/docs/en/reference/context-layout.md b/docs/src/content/docs/en/reference/context-layout.md index 6523506e..11c75814 100644 --- a/docs/src/content/docs/en/reference/context-layout.md +++ b/docs/src/content/docs/en/reference/context-layout.md @@ -52,7 +52,7 @@ These files govern how the harness behaves. You write them, you review them, and | `.context/config/` | versioned | Yes | The authored config directory. | | `.context/config/policy.json` | versioned | Yes | Harness [policy](/concepts/policies/) rules and approval constraints. | | `.context/config/sensors.json` | versioned | Yes | Project [sensor](/concepts/sensors/) catalog plus detected stack info. Generated at bootstrap, then customized by the team. | -| `.context/config/runtime.json` | versioned | Yes | Versioned retention and semantic-discovery limits for traces, sessions, replays, datasets, checkpoints, bindings, and caches. `caches.context.maxEntriesScanned` and `caches.semantic.maxEntriesScanned` cap raw directory entries before filtering; unsafe values are clamped to absolute ceilings. | +| `.context/config/runtime.json` | versioned | Yes | Versioned retention and semantic-discovery limits for traces, sessions, replays, datasets, checkpoints, bindings, and caches. Checkpoint records have total, data, note, artifact-count, and per-artifact-ID limits. `caches.context.maxEntriesScanned` and `caches.semantic.maxEntriesScanned` cap raw directory entries before filtering; unsafe values are clamped to absolute ceilings. | ## Durable project knowledge diff --git a/docs/src/content/docs/pt-br/concepts/harness-runtime.md b/docs/src/content/docs/pt-br/concepts/harness-runtime.md index 2ecb3eef..6ab87919 100644 --- a/docs/src/content/docs/pt-br/concepts/harness-runtime.md +++ b/docs/src/content/docs/pt-br/concepts/harness-runtime.md @@ -160,7 +160,9 @@ Adicione artifacts com a action `addArtifact` da tool `harness` e leia-os com `l Um **checkpoint** é um marco nomeado dentro de uma session. Ele agrupa um conjunto de artifacts e estado opcional, dando a você um ponto significativo e recuperável para o qual voltar — útil entre fases PREVC, antes de um passo arriscado ou sempre que você quiser um snapshot rotulado. -Checkpoints são armazenados como registros individuais em `.context/runtime/sessions//checkpoints/`. O `session.json` mantém apenas o contador e a identidade do checkpoint mais recente, evitando que o histórico torne cada atualização da session progressivamente maior. Checkpoints legados inline continuam legíveis e são migrados na próxima gravação. +Checkpoints são armazenados como registros individuais em `.context/runtime/sessions//checkpoints/`. O `session.json` mantém apenas o contador e a identidade do checkpoint mais recente, então leituras e gravações normais da session nunca carregam o histórico completo. Consumidores do runtime podem paginar os registros com `listCheckpointsPage`; o helper completo `listCheckpoints` continua disponível para operações explícitas, como replay. Checkpoints legados inline continuam legíveis e são migrados na próxima gravação. + +Cada novo registro é limitado por `checkpoints.maxSerializedBytes`; `data`, `note`, quantidade de artifacts e cada ID de artifact também têm limites independentes. Assim, um rótulo ou identificador grande não consegue contornar o budget do payload. ```json { diff --git a/docs/src/content/docs/pt-br/reference/context-layout.md b/docs/src/content/docs/pt-br/reference/context-layout.md index d4516c87..36f388f2 100644 --- a/docs/src/content/docs/pt-br/reference/context-layout.md +++ b/docs/src/content/docs/pt-br/reference/context-layout.md @@ -52,7 +52,7 @@ Esses arquivos governam como o harness se comporta. Você os escreve, os revisa | `.context/config/` | versioned | Sim | O diretório de config autorada. | | `.context/config/policy.json` | versioned | Sim | Regras de [policy](/pt-br/concepts/policies/) do harness e restrições de aprovação. | | `.context/config/sensors.json` | versioned | Sim | Catálogo de [sensores](/pt-br/concepts/sensors/) do projeto mais informações da stack detectada. Gerado no bootstrap e depois customizado pelo time. | -| `.context/config/runtime.json` | versioned | Sim | Limites versionados de retenção e descoberta semântica para traces, sessions, replays, datasets, checkpoints, bindings e caches. `caches.context.maxEntriesScanned` e `caches.semantic.maxEntriesScanned` limitam entradas brutas de diretório antes da filtragem; valores inseguros são limitados por tetos absolutos. | +| `.context/config/runtime.json` | versioned | Sim | Limites versionados de retenção e descoberta semântica para traces, sessions, replays, datasets, checkpoints, bindings e caches. Registros de checkpoint têm limites total, de data, note, quantidade de artifacts e por ID de artifact. `caches.context.maxEntriesScanned` e `caches.semantic.maxEntriesScanned` limitam entradas brutas de diretório antes da filtragem; valores inseguros são limitados por tetos absolutos. | ## Conhecimento durável do projeto diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index e96d9699..1304d0c1 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -49,13 +49,15 @@ describe('HarnessRuntimeStateService', () => { const completed = await service.completeSession(session.id, 'done'); const storedSession = await service.getSession(session.id); + const checkpointPage = await service.listCheckpointsPage(session.id, { limit: 10 }); const traces = await service.listTraces(session.id); const artifacts = await service.listArtifacts(session.id); expect(session.status).toBe('active'); expect(trace.event).toBe('task.started'); expect(artifact.name).toBe('design-note'); - expect(checkpointed.checkpoints).toHaveLength(1); + expect(checkpointed.checkpoints).toEqual([]); + expect(checkpointPage.records).toHaveLength(1); expect(resumed.status).toBe('active'); expect(completed.status).toBe('completed'); expect(storedSession.status).toBe('completed'); @@ -80,8 +82,8 @@ describe('HarnessRuntimeStateService', () => { expect(await fs.pathExists(artifactFile)).toBe(true); const sessionDocument = await fs.readJson(sessionFile); expect(sessionDocument.checkpoints).toBeUndefined(); - expect(sessionDocument.lastCheckpointId).toBe(checkpointed.checkpoints[0].id); - expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'checkpoints', `${checkpointed.checkpoints[0].id}.json`))).toBe(true); + expect(sessionDocument.lastCheckpointId).toBe(checkpointPage.records[0].id); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'checkpoints', `${checkpointPage.records[0].id}.json`))).toBe(true); }); it('reads legacy inline checkpoints and migrates them losslessly on the next write', async () => { @@ -111,13 +113,59 @@ describe('HarnessRuntimeStateService', () => { it('enforces checkpoint payload and artifact limits from safe runtime config', async () => { await fs.outputJson(path.join(tempDir, '.context', 'config', 'runtime.json'), { version: 1, - checkpoints: { maxDataBytes: 1024, maxArtifactIds: 1 }, + checkpoints: { maxDataBytes: 1024, maxSerializedBytes: 1024, maxArtifactIds: 1 }, }); const session = await service.createSession({ name: 'bounded' }); await expect(service.checkpointSession(session.id, { data: 'x'.repeat(2048) })) .rejects.toThrow('Checkpoint data exceeds'); await expect(service.checkpointSession(session.id, { artifactIds: ['a', 'b'] })) .rejects.toThrow('Checkpoint artifactIds exceed'); + await expect(service.checkpointSession(session.id, { data: 'x'.repeat(950) })) + .rejects.toThrow('Checkpoint record exceeds'); + await expect(service.checkpointSession(session.id, { note: 'n'.repeat(2 * 1024 * 1024) })) + .rejects.toThrow('Checkpoint note exceeds'); + await expect(service.checkpointSession(session.id, { artifactIds: ['a'.repeat(2 * 1024 * 1024)] })) + .rejects.toThrow('Checkpoint artifactId exceeds'); + }); + + it('keeps session lookup and checkpoint writes independent of total checkpoint history', async () => { + const session = await service.createSession({ name: 'many-checkpoints' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const checkpointDir = path.join(sessionDir, 'checkpoints'); + await fs.ensureDir(checkpointDir); + for (let index = 0; index < 250; index += 1) { + const checkpoint = { + id: `existing-${String(index).padStart(3, '0')}`, + note: `checkpoint ${index}`, + artifactIds: [], + createdAt: new Date(index * 1000).toISOString(), + }; + await fs.writeJson(path.join(checkpointDir, `${checkpoint.id}.json`), checkpoint); + } + const document = await fs.readJson(path.join(sessionDir, 'session.json')); + document.checkpointCount = 250; + document.lastCheckpointId = 'existing-249'; + await fs.writeJson(path.join(sessionDir, 'session.json'), document); + + const fullHistory = jest.spyOn(service, 'listCheckpoints'); + const summary = await service.getSession(session.id); + expect(summary.checkpointCount).toBe(250); + expect(summary.checkpoints).toEqual([]); + expect(fullHistory).not.toHaveBeenCalled(); + + const firstPage = await service.listCheckpointsPage(session.id, { limit: 25 }); + expect(firstPage.records).toHaveLength(25); + expect(firstPage.nextCursor).toBeDefined(); + const secondPage = await service.listCheckpointsPage(session.id, { + cursor: firstPage.nextCursor, + limit: 25, + }); + expect(secondPage.records).toHaveLength(25); + expect(new Set([...firstPage.records, ...secondPage.records].map(item => item.id)).size).toBe(50); + + await service.checkpointSession(session.id, { note: 'incremental' }); + expect((await service.getSession(session.id)).checkpointCount).toBe(251); + expect(fullHistory).not.toHaveBeenCalled(); }); it('lists sessions sorted by recency', async () => { diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 36b0edf2..04556c58 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -28,6 +28,18 @@ export interface HarnessSessionCheckpoint { createdAt: string; } +export interface ListCheckpointsOptions { + /** Opaque cursor returned by the preceding page. */ + cursor?: string; + /** Records per page. Clamped to 1..200 (default 100). */ + limit?: number; +} + +export interface HarnessCheckpointPage { + records: HarnessSessionCheckpoint[]; + nextCursor?: string; +} + export interface HarnessSessionRecord { id: string; name: string; @@ -77,6 +89,7 @@ export interface HarnessRuntimeStatePort { addArtifact(sessionId: string, input: AddArtifactInput): Promise; listArtifacts(sessionId: string): Promise; checkpointSession(sessionId: string, input?: CheckpointInput): Promise; + listCheckpointsPage(sessionId: string, options?: ListCheckpointsOptions): Promise; listCheckpoints(sessionId: string): Promise; } @@ -111,6 +124,19 @@ function nowIso(): string { return new Date().toISOString(); } +function encodeCheckpointCursor(offset: number): string { + return Buffer.from(String(offset), 'utf8').toString('base64url'); +} + +function decodeCheckpointCursor(cursor: string | undefined): number { + if (!cursor) return 0; + const decoded = Buffer.from(cursor, 'base64url').toString('utf8'); + if (!/^\d+$/.test(decoded)) throw new Error('Invalid checkpoint cursor'); + const offset = Number(decoded); + if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('Invalid checkpoint cursor'); + return offset; +} + function normalizeContent(content: unknown): unknown { if (content === undefined) { return undefined; @@ -265,9 +291,10 @@ export class HarnessRuntimeStateService { } async getSession(sessionId: string): Promise { - const session = await this.readSession(sessionId); - session.checkpoints = await this.listCheckpoints(sessionId); - return session; + // Session lookup is a hot path for trace logging. The record already + // carries checkpointCount/lastCheckpoint*, so never materialize payload + // history here. Call listCheckpointsPage() when records are required. + return this.readSession(sessionId); } async appendTrace(sessionId: string, input: AppendTraceInput): Promise { @@ -322,21 +349,68 @@ export class HarnessRuntimeStateService { return artifact; } - async listCheckpoints(sessionId: string): Promise { + async listCheckpointsPage( + sessionId: string, + options: ListCheckpointsOptions = {}, + ): Promise { const session = await this.readSession(sessionId); - const checkpoints = new Map(); - for (const checkpoint of session.checkpoints ?? []) checkpoints.set(checkpoint.id, checkpoint); + const limit = Math.min(200, Math.max(1, Math.floor(options.limit ?? 100))); + const offset = decodeCheckpointCursor(options.cursor); + const records: HarnessSessionCheckpoint[] = []; + let visited = 0; + let hasMore = false; + const legacyIds = new Set((session.checkpoints ?? []).map(checkpoint => checkpoint.id)); + + const consider = (checkpoint: HarnessSessionCheckpoint): boolean => { + if (visited < offset) { + visited += 1; + return true; + } + if (records.length >= limit) { + hasMore = true; + return false; + } + records.push(checkpoint); + visited += 1; + return true; + }; + + for (const checkpoint of session.checkpoints ?? []) { + if (!consider(checkpoint)) break; + } + const dir = this.layout.sessionCheckpointsDir(sessionId); - if (await fs.pathExists(dir)) { - for (const entry of (await fs.readdir(dir)).filter((name) => name.endsWith('.json'))) { + if (!hasMore && await fs.pathExists(dir)) { + const directory = await fs.opendir(dir); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; try { - const checkpoint = await fs.readJson(path.join(dir, entry)) as HarnessSessionCheckpoint; - checkpoints.set(checkpoint.id, checkpoint); + const checkpoint = await fs.readJson(path.join(dir, entry.name)) as HarnessSessionCheckpoint; + // An interrupted legacy migration can temporarily leave the same + // record inline and external. It still occupies one logical slot. + if (legacyIds.has(checkpoint.id)) continue; + if (!consider(checkpoint)) break; } catch { // Preserve availability when one record is corrupt or partially written. } } } + records.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + return { + records, + ...(hasMore ? { nextCursor: encodeCheckpointCursor(visited) } : {}), + }; + } + + /** Compatibility helper for explicit callers that need the complete history. */ + async listCheckpoints(sessionId: string): Promise { + const checkpoints = new Map(); + let cursor: string | undefined; + do { + const page = await this.listCheckpointsPage(sessionId, { cursor, limit: 200 }); + for (const checkpoint of page.records) checkpoints.set(checkpoint.id, checkpoint); + cursor = page.nextCursor; + } while (cursor); return [...checkpoints.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)); } @@ -384,13 +458,33 @@ export class HarnessRuntimeStateService { async checkpointSession(sessionId: string, input: CheckpointInput = {}): Promise { const session = await this.readSession(sessionId); const { config } = await loadRuntimeRetentionConfig(this.repoPath); - const dataBytes = input.data === undefined ? 0 : Buffer.byteLength(JSON.stringify(input.data)); + let serializedData = ''; + try { + if (input.data !== undefined) { + const encoded = JSON.stringify(input.data); + if (encoded === undefined) throw new Error('unsupported value'); + serializedData = encoded; + } + } catch { + throw new Error('Checkpoint data must be JSON serializable'); + } + const dataBytes = Buffer.byteLength(serializedData); if (dataBytes > config.checkpoints.maxDataBytes) { throw new Error(`Checkpoint data exceeds ${config.checkpoints.maxDataBytes} byte limit`); } + if (input.note !== undefined) { + if (typeof input.note !== 'string' || Buffer.byteLength(input.note) > config.checkpoints.maxNoteBytes) { + throw new Error(`Checkpoint note exceeds ${config.checkpoints.maxNoteBytes} byte limit`); + } + } if ((input.artifactIds?.length ?? 0) > config.checkpoints.maxArtifactIds) { throw new Error(`Checkpoint artifactIds exceed ${config.checkpoints.maxArtifactIds} item limit`); } + for (const artifactId of input.artifactIds ?? []) { + if (typeof artifactId !== 'string' || Buffer.byteLength(artifactId) > config.checkpoints.maxArtifactIdBytes) { + throw new Error(`Checkpoint artifactId exceeds ${config.checkpoints.maxArtifactIdBytes} byte limit`); + } + } const createdAt = nowIso(); const checkpoint: HarnessSessionCheckpoint = { id: randomUUID(), @@ -399,6 +493,11 @@ export class HarnessRuntimeStateService { artifactIds: input.artifactIds || [], createdAt, }; + const serializedCheckpoint = JSON.stringify(checkpoint); + const serializedBytes = Buffer.byteLength(serializedCheckpoint); + if (serializedBytes > config.checkpoints.maxSerializedBytes) { + throw new Error(`Checkpoint record exceeds ${config.checkpoints.maxSerializedBytes} byte limit`); + } // Lazy, lossless migration: legacy inline records are copied before the // next new-write strips the embedded array from session.json. @@ -410,8 +509,11 @@ export class HarnessRuntimeStateService { } } await fs.ensureDir(this.layout.sessionCheckpointsDir(sessionId)); - await fs.writeJson(this.checkpointFile(sessionId, checkpoint.id), checkpoint, { spaces: 2 }); - session.checkpointCount = (await this.listCheckpoints(sessionId)).length; + await fs.writeFile(this.checkpointFile(sessionId, checkpoint.id), serializedCheckpoint, 'utf8'); + const storedCount = Number.isSafeInteger(session.checkpointCount) && session.checkpointCount >= 0 + ? session.checkpointCount + : 0; + session.checkpointCount = Math.max(storedCount, session.checkpoints.length) + 1; session.checkpoints = []; session.lastCheckpointAt = createdAt; session.lastCheckpointId = checkpoint.id; @@ -429,11 +531,11 @@ export class HarnessRuntimeStateService { data: { checkpointId: checkpoint.id, artifactIds: checkpoint.artifactIds, - payloadBytes: dataBytes, + payloadBytes: serializedBytes, }, }); - return this.getSession(sessionId); + return this.readSession(sessionId); } async resumeSession(sessionId: string): Promise { diff --git a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts index 627a119f..6d13cbb1 100644 --- a/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts @@ -50,7 +50,7 @@ describe('bounded semantic file discovery', () => { expect(result.files).toEqual([]); expect(result.metrics).toMatchObject({ entriesScanned: 25, - statsAttempted: 2, + statsAttempted: 3, filesSelected: 0, partial: true, stopReason: 'maxEntriesScanned', @@ -75,7 +75,7 @@ describe('bounded semantic file discovery', () => { expect(result.metrics).toMatchObject({ entriesScanned: 9, directoriesVisited: 9, - statsAttempted: 9, + statsAttempted: 11, partial: true, stopReason: 'maxEntriesScanned', }); diff --git a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index ccb3a16b..b2c80251 100644 --- a/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts @@ -105,6 +105,17 @@ describe('ContextCache', () => { expect(await cache.get(tempDir, 'compact')).toBeNull(); }); + it('invalidates when a configured watch root is created after caching', async () => { + const cache = new ContextCache({ watchDirs: ['src', 'packages'] }); + await cache.set(tempDir, 'compact', 'before-packages'); + expect(await cache.get(tempDir, 'compact')).toBe('before-packages'); + + await fs.outputFile(path.join(tempDir, 'packages', 'new.ts'), 'export const created = true;'); + + expect(await cache.get(tempDir, 'compact')).toBeNull(); + cache.dispose(); + }); + it('validates cache hits from bounded signals and ignores irrelevant runtime files', async () => { await fs.writeFile(path.join(tempDir, 'src', 'index.ts'), 'export const value = 1;'); const cache = new ContextCache({ watchDirs: ['src', '.context'], freshnessMaxFiles: 4 }); diff --git a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts index d2d1cf8f..a62f4f3c 100644 --- a/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts +++ b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts @@ -13,8 +13,20 @@ export interface BoundedDirectorySignal { mtimeMs: number; } +/** + * A configured discovery root, including roots which did not exist when the + * snapshot was captured. Keeping absence as an explicit signal prevents a + * newly-created source root from authorizing a stale cache hit. + */ +export interface BoundedRootSignal { + path: string; + exists: boolean; + mtimeMs?: number; +} + export interface BoundedFreshnessSnapshot { rootPath: string; + roots: BoundedRootSignal[]; files: BoundedFileSignal[]; directories: BoundedDirectorySignal[]; partial: boolean; @@ -68,6 +80,11 @@ function normalizedRelative(root: string, target: string): string { function fingerprintSnapshot(snapshot: BoundedFreshnessSnapshot): string { const hash = createHash('sha256'); + for (const root of snapshot.roots) { + // Mtime is a cheap rescan sentinel, not source identity: excluded runtime + // churn may touch a watched parent without changing relevant source. + hash.update(`r:${root.path}:${root.exists}\n`); + } for (const file of snapshot.files) { hash.update(`f:${file.path}:${file.size}:${file.mtimeMs}\n`); } @@ -89,14 +106,33 @@ export async function discoverBoundedFiles( const excludedNames = new Set([...DEFAULT_EXCLUDED_DIRECTORIES, ...(options.excludeDirectoryNames ?? [])]); const excludedPrefixes = [...(options.excludeRelativePrefixes ?? [])] .map(value => value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '')); - const queue = (options.roots?.length ? options.roots : ['.']) + let statsAttempted = 0; + const configuredRoots = (options.roots?.length ? options.roots : ['.']) .map(relative => path.resolve(root, relative)) .filter(candidate => candidate === root || candidate.startsWith(`${root}${path.sep}`)); + // Always observe the repository root as well as every configured watch root. + // De-duplication keeps the default `.` case to one signal/stat. + const rootCandidates = [...new Set([root, ...configuredRoots])]; + const rootSignals: BoundedRootSignal[] = []; + for (const candidate of rootCandidates) { + statsAttempted += 1; + try { + const stat = await fs.stat(candidate); + rootSignals.push({ + path: normalizedRelative(root, candidate) || '.', + exists: true, + mtimeMs: stat.mtimeMs, + }); + } catch { + rootSignals.push({ path: normalizedRelative(root, candidate) || '.', exists: false }); + } + } + rootSignals.sort((left, right) => left.path.localeCompare(right.path)); + const queue = [...configuredRoots]; const queued = new Set(queue); const files: BoundedFileSignal[] = []; const directories: BoundedDirectorySignal[] = []; let entriesScanned = 0; - let statsAttempted = 0; let partial = false; let stopReason: BoundedDiscoveryStopReason | undefined; const stopPartial = (reason: BoundedDiscoveryStopReason) => { @@ -158,7 +194,7 @@ export async function discoverBoundedFiles( else if (queue.length > 0 || directories.length >= maxDirectories) stopPartial('maxDirectories'); files.sort((left, right) => left.path.localeCompare(right.path)); directories.sort((left, right) => left.path.localeCompare(right.path)); - const snapshot: BoundedFreshnessSnapshot = { rootPath: root, files, directories, partial }; + const snapshot: BoundedFreshnessSnapshot = { rootPath: root, roots: rootSignals, files, directories, partial }; return { files: files.map(file => path.join(root, file.path)), fingerprint: fingerprintSnapshot(snapshot), @@ -188,6 +224,18 @@ export async function isBoundedSnapshotFresh(snapshot: BoundedFreshnessSnapshot) return { fresh: false, signalsChecked: 0, durationMs: Date.now() - started }; } let signalsChecked = 0; + for (const root of snapshot.roots ?? []) { + try { + const stat = await fs.stat(path.join(snapshot.rootPath, root.path)); + signalsChecked += 1; + if (!root.exists || stat.mtimeMs !== root.mtimeMs) { + return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } + } catch { + signalsChecked += 1; + if (root.exists) return { fresh: false, signalsChecked, durationMs: Date.now() - started }; + } + } for (const directory of snapshot.directories) { try { const stat = await fs.stat(path.join(snapshot.rootPath, directory.path)); diff --git a/src/harness/application/retention/runtimeRetentionConfig.ts b/src/harness/application/retention/runtimeRetentionConfig.ts index 4ef8ece1..1fe3a0ca 100644 --- a/src/harness/application/retention/runtimeRetentionConfig.ts +++ b/src/harness/application/retention/runtimeRetentionConfig.ts @@ -7,7 +7,13 @@ export interface RuntimeRetentionConfig { sessions: { maxEntries: number }; replays: { maxEntries: number }; datasets: { maxEntries: number }; - checkpoints: { maxDataBytes: number; maxArtifactIds: number }; + checkpoints: { + maxDataBytes: number; + maxSerializedBytes: number; + maxNoteBytes: number; + maxArtifactIds: number; + maxArtifactIdBytes: number; + }; bindings: { maxEntries: number; maxAgeMs: number }; caches: { context: { maxEntries: number; maxBytes: number; ttlMs: number; maxEntriesScanned: number }; @@ -38,7 +44,13 @@ export const DEFAULT_RUNTIME_RETENTION_CONFIG: RuntimeRetentionConfig = { sessions: { maxEntries: 1_000 }, replays: { maxEntries: 100 }, datasets: { maxEntries: 100 }, - checkpoints: { maxDataBytes: 64 * 1024, maxArtifactIds: 200 }, + checkpoints: { + maxDataBytes: 64 * 1024, + maxSerializedBytes: 96 * 1024, + maxNoteBytes: 4 * 1024, + maxArtifactIds: 200, + maxArtifactIdBytes: 1_024, + }, bindings: { maxEntries: 1_000, maxAgeMs: 30 * 24 * 60 * 60 * 1000 }, caches: { context: { maxEntries: 16, maxBytes: 32 * 1024 * 1024, ttlMs: 5 * 60 * 1000, maxEntriesScanned: 20_000 }, @@ -55,7 +67,7 @@ const KNOWN_KEYS: Record = { sessions: ['maxEntries'], replays: ['maxEntries'], datasets: ['maxEntries'], - checkpoints: ['maxDataBytes', 'maxArtifactIds'], + checkpoints: ['maxDataBytes', 'maxSerializedBytes', 'maxNoteBytes', 'maxArtifactIds', 'maxArtifactIdBytes'], bindings: ['maxEntries', 'maxAgeMs'], caches: ['context', 'semantic', 'mcpSessions', 'fileAnalysis'], 'caches.context': ['maxEntries', 'maxBytes', 'ttlMs', 'maxEntriesScanned'], @@ -191,7 +203,10 @@ export async function loadRuntimeRetentionConfig(repoPath: string): Promise { expect(Object.keys(store.bindings['claude-code'])).toHaveLength(2); expect(store.bindings['claude-code']['host-0']).toBeUndefined(); }); + + it('serializes concurrent save and prune mutations without losing bindings', async () => { + const now = new Date().toISOString(); + const saves = Array.from({ length: 30 }, async (_, index) => { + const harnessSessionId = `concurrent-harness-${index}`; + await fs.outputJson( + path.join(tempDir, '.context', 'runtime', 'sessions', harnessSessionId, 'session.json'), + { id: harnessSessionId, status: 'active' }, + ); + await saveHookHarnessSession({ + repoPath: tempDir, + source: index % 2 === 0 ? 'claude-code' : 'codex', + hostSessionId: `concurrent-host-${index}`, + harnessSessionId, + createdAt: now, + updatedAt: now, + }); + }); + + await Promise.all([ + ...saves, + pruneHookSessionBindings(tempDir), + pruneHookSessionBindings(tempDir), + pruneHookSessionBindings(tempDir), + ]); + + const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); + const store = await fs.readJson(storePath); + const bindings = Object.values(store.bindings) + .flatMap(source => Object.values(source as Record)); + expect(bindings).toHaveLength(30); + expect(await fs.pathExists(`${storePath}.lock`)).toBe(false); + }); }); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index ba38784d..5a12ece4 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -1,5 +1,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; +import { promises as nativeFs } from 'fs'; +import { randomUUID } from 'crypto'; import { getContextRootPath } from '../../shared/context'; import type { HarnessHookResponse } from '../../harness'; @@ -22,6 +24,10 @@ interface HookSessionStoreDocument { bindings: Record>; } +const mutationTails = new Map>(); +const LOCK_WAIT_MS = 10_000; +const LOCK_RETRY_MS = 20; + export interface HookSessionPruneResult { removedExpired: number; removedMissing: number; @@ -71,7 +77,65 @@ async function readStore(repoPath: string): Promise { async function writeStore(repoPath: string, document: HookSessionStoreDocument): Promise { const storePath = await getStorePath(repoPath); await fs.ensureDir(path.dirname(storePath)); - await fs.writeJson(storePath, document, { spaces: 2 }); + const temporary = `${storePath}.${process.pid}.${randomUUID()}.tmp`; + try { + await fs.writeJson(temporary, document, { spaces: 2 }); + await fs.rename(temporary, storePath); + } finally { + await fs.remove(temporary).catch(() => undefined); + } +} + +async function withInterProcessLock(storePath: string, operation: () => Promise): Promise { + const lockPath = `${storePath}.lock`; + await fs.ensureDir(path.dirname(lockPath)); + const deadline = Date.now() + LOCK_WAIT_MS; + let handle: Awaited> | undefined; + + while (!handle) { + try { + handle = await nativeFs.open(lockPath, 'wx'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for hook session store lock: ${path.basename(storePath)}`); + } + await new Promise(resolve => setTimeout(resolve, LOCK_RETRY_MS)); + } + } + + try { + await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: Date.now() }), 'utf8'); + } catch (error) { + await handle.close().catch(() => undefined); + await nativeFs.unlink(lockPath).catch(() => undefined); + throw error; + } + + try { + return await operation(); + } finally { + await handle.close().catch(() => undefined); + await nativeFs.unlink(lockPath).catch(() => undefined); + } +} + +async function mutateStore(repoPath: string, operation: () => Promise): Promise { + const normalizedRepoPath = path.resolve(repoPath); + const storePath = await getStorePath(normalizedRepoPath); + const predecessor = mutationTails.get(storePath) ?? Promise.resolve(); + let release!: () => void; + const completed = new Promise(resolve => { release = resolve; }); + const tail = predecessor.catch(() => undefined).then(() => completed); + mutationTails.set(storePath, tail); + + await predecessor.catch(() => undefined); + try { + return await withInterProcessLock(storePath, () => operation()); + } finally { + release(); + if (mutationTails.get(storePath) === tail) mutationTails.delete(storePath); + } } export async function getHookHarnessSessionId(options: { @@ -86,13 +150,15 @@ export async function getHookHarnessSessionId(options: { export async function saveHookHarnessSession(binding: HookSessionBinding): Promise { const normalizedRepoPath = path.resolve(binding.repoPath); - const document = await readStore(normalizedRepoPath); - const sourceBindings = document.bindings[binding.source] ?? {}; - sourceBindings[binding.hostSessionId] = { ...binding, repoPath: normalizedRepoPath }; - document.bindings[binding.source] = sourceBindings; - const { config } = await loadRuntimeRetentionConfig(normalizedRepoPath); - capBindings(document, config.bindings.maxEntries); - await writeStore(normalizedRepoPath, document); + await mutateStore(normalizedRepoPath, async () => { + const document = await readStore(normalizedRepoPath); + const sourceBindings = document.bindings[binding.source] ?? {}; + sourceBindings[binding.hostSessionId] = { ...binding, repoPath: normalizedRepoPath }; + document.bindings[binding.source] = sourceBindings; + const { config } = await loadRuntimeRetentionConfig(normalizedRepoPath); + capBindings(document, config.bindings.maxEntries); + await writeStore(normalizedRepoPath, document); + }); } function allBindings(document: HookSessionStoreDocument): Array<{ source: string; hostSessionId: string; binding: HookSessionBinding }> { @@ -116,34 +182,36 @@ export async function pruneHookSessionBindings(repoPath: string): Promise { + const document = await readStore(normalizedRepoPath); + const { config } = await loadRuntimeRetentionConfig(normalizedRepoPath); + const cutoff = Date.now() - config.bindings.maxAgeMs; + let removedExpired = 0; + let removedMissing = 0; + + for (const { source, hostSessionId, binding } of allBindings(document)) { + const updatedAt = Date.parse(binding.updatedAt); + if (!Number.isFinite(updatedAt) || updatedAt < cutoff) { + delete document.bindings[source]?.[hostSessionId]; + removedExpired += 1; + continue; + } + const sessionFile = path.join(contextRoot, 'runtime', 'sessions', binding.harnessSessionId, 'session.json'); + if (!await fs.pathExists(sessionFile)) { + delete document.bindings[source]?.[hostSessionId]; + removedMissing += 1; + } } - } - const removedOverLimit = capBindings(document, config.bindings.maxEntries); - await writeStore(normalizedRepoPath, document); - return { - removedExpired, - removedMissing, - removedOverLimit, - remaining: allBindings(document).length, - durationMs: Date.now() - startedAt, - }; + const removedOverLimit = capBindings(document, config.bindings.maxEntries); + await writeStore(normalizedRepoPath, document); + return { + removedExpired, + removedMissing, + removedOverLimit, + remaining: allBindings(document).length, + durationMs: Date.now() - startedAt, + }; + }); } export async function ensureHookHarnessSession( diff --git a/src/mcp/logging/__tests__/actionLogger.test.ts b/src/mcp/logging/__tests__/actionLogger.test.ts index a642694a..ca30c261 100644 --- a/src/mcp/logging/__tests__/actionLogger.test.ts +++ b/src/mcp/logging/__tests__/actionLogger.test.ts @@ -107,4 +107,28 @@ describe('logMcpAction', () => { clearMcpActionSessionCache(); expect(getMcpActionSessionCacheSize()).toBe(0); }); + + it('never reuses a terminal MCP activity session', async () => { + const state = new HarnessRuntimeStateService({ repoPath: tempDir }); + const terminal = await state.createSession({ + name: 'mcp-activity', + metadata: { transport: 'mcp', purpose: 'tool-audit' }, + }); + await state.completeSession(terminal.id); + + await logMcpAction(tempDir, { + tool: 'context', + action: 'check', + status: 'success', + }); + + const sessions = await state.listSessions(); + const activity = sessions.filter(session => session.name === 'mcp-activity'); + expect(activity).toHaveLength(2); + expect(activity.find(session => session.id === terminal.id)?.status).toBe('completed'); + const replacement = activity.find(session => session.id !== terminal.id); + expect(replacement?.status).toBe('active'); + expect((await state.listTraces(terminal.id)).some(trace => trace.event === 'mcp.tool.succeeded')).toBe(false); + expect((await state.listTraces(replacement!.id)).some(trace => trace.event === 'mcp.tool.succeeded')).toBe(true); + }); }); diff --git a/src/mcp/logging/actionLogger.ts b/src/mcp/logging/actionLogger.ts index 2843e505..06a28a1d 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -184,9 +184,12 @@ async function resolveMcpActivitySessionId( } } + // listSessions() is newest-first. A terminal audit session is immutable for + // future activity: only an active/paused session may be reused. const existing = (await state.listSessions()).find((session) => session.name === MCP_ACTIVITY_NAME && - session.metadata?.transport === 'mcp' + session.metadata?.transport === 'mcp' && + (session.status === 'active' || session.status === 'paused') ); if (existing) { From b26ec23b749662fb49f3a7335537e9add207272b Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:12:19 -0300 Subject: [PATCH 32/39] fix: bound MCP exploration CPU and traversal --- CHANGELOG.md | 1 + .../content/docs/en/reference/mcp-tools.md | 4 +- .../content/docs/pt-br/reference/mcp-tools.md | 4 +- .../__tests__/boundedExplore.load.test.ts | 27 + .../context/__tests__/boundedExplore.test.ts | 66 +++ .../application/context/boundedExplore.ts | 491 +++++++++++++++--- .../application/context/contextTools.ts | 56 +- src/mcp/README.md | 4 +- 8 files changed, 519 insertions(+), 134 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fe4a127..96b3ce3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Removed MCP response-body reparsing from action logging and replaced oversized response truncation risk with typed smaller-page or artifact-reference responses. - Applied the same bounded UTF-8 budget to every MCP resource, rejected oversized files before reading their bodies, enforced action-specific list maxima, and paginated `explore` file listings. - Bounded `explore` reads before file materialization and replaced whole-glob/whole-file code search with byte-capped streaming discovery, search, and cursor pages. +- Bounded `explore.list` traversal even when callers disable default ignores, and isolated caller regex evaluation in a worker with a hard CPU deadline. - Prevented Claude Code, Codex, and Pi Write/Edit hooks from retaining source bodies or sensitive fields by persisting bounded metadata summaries instead. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. diff --git a/docs/src/content/docs/en/reference/mcp-tools.md b/docs/src/content/docs/en/reference/mcp-tools.md index acc17d21..ac59fca9 100644 --- a/docs/src/content/docs/en/reference/mcp-tools.md +++ b/docs/src/content/docs/en/reference/mcp-tools.md @@ -60,9 +60,9 @@ File and code exploration — read files, list paths, search content, and extrac **Returns:** file contents, matched files, symbol analysis, search results, or a directory tree. -The `list` action streams matches into bounded pages instead of materializing the entire glob. Pass the returned `page.nextCursor` unchanged to continue. +The `list` action uses a bounded directory walker instead of materializing the entire glob. File, raw-entry, and directory ceilings apply even with `ignore: []`. Pass `page.nextCursor` unchanged when continuation is available; otherwise partial discovery includes `discoveryLimitReason` and `continuationUnavailableReason`. -The `read` action rejects files above 1 MiB with `EXPLORE_FILE_TOO_LARGE` before opening the body. `search` walks directories and reads matching files incrementally under file, raw-entry, directory, per-file, and result-byte ceilings. Its `page` reports partial discovery and oversized-file skips; pass `page.nextCursor` unchanged to continue result pagination. +The `read` action rejects files above 1 MiB with `EXPLORE_FILE_TOO_LARGE` before opening the body. `search` walks directories and reads matching files incrementally under file, raw-entry, directory, per-file, and result-byte ceilings. Caller regexes execute outside the MCP event loop under a hard CPU deadline; `EXPLORE_REGEX_TIMEOUT` reports a timed-out partial search. Its `page` reports partial discovery and oversized-file skips; pass `page.nextCursor` unchanged to continue result pagination. ### context diff --git a/docs/src/content/docs/pt-br/reference/mcp-tools.md b/docs/src/content/docs/pt-br/reference/mcp-tools.md index eab7b3bb..885546de 100644 --- a/docs/src/content/docs/pt-br/reference/mcp-tools.md +++ b/docs/src/content/docs/pt-br/reference/mcp-tools.md @@ -60,9 +60,9 @@ Exploração de arquivos e código — ler arquivos, listar caminhos, buscar con **Retorna:** conteúdo de arquivos, arquivos correspondentes, análise de símbolos, resultados de busca ou uma árvore de diretórios. -A action `list` transmite os matches em páginas limitadas, sem materializar todo o glob. Envie o `page.nextCursor` retornado, sem alterá-lo, para continuar. +A action `list` usa um percurso limitado de diretórios, sem materializar todo o glob. Os limites de arquivos, entradas brutas e diretórios valem mesmo com `ignore: []`. Envie `page.nextCursor` sem alterações quando houver continuação; caso contrário, a descoberta parcial informa `discoveryLimitReason` e `continuationUnavailableReason`. -A action `read` rejeita arquivos acima de 1 MiB com `EXPLORE_FILE_TOO_LARGE` antes de abrir o corpo. `search` percorre diretórios e lê arquivos correspondentes incrementalmente, com limites de arquivos, entradas brutas, diretórios, bytes por arquivo e bytes de resultado. Seu `page` informa descoberta parcial e arquivos ignorados por tamanho; envie `page.nextCursor` sem alterações para continuar. +A action `read` rejeita arquivos acima de 1 MiB com `EXPLORE_FILE_TOO_LARGE` antes de abrir o corpo. `search` percorre diretórios e lê arquivos correspondentes incrementalmente, com limites de arquivos, entradas brutas, diretórios, bytes por arquivo e bytes de resultado. As regexes do cliente são executadas fora do event loop do MCP com prazo rígido de CPU; `EXPLORE_REGEX_TIMEOUT` informa uma busca parcial que excedeu o prazo. Seu `page` informa descoberta parcial e arquivos ignorados por tamanho; envie `page.nextCursor` sem alterações para continuar. ### context diff --git a/src/harness/application/context/__tests__/boundedExplore.load.test.ts b/src/harness/application/context/__tests__/boundedExplore.load.test.ts index 6bb39263..d48b8b89 100644 --- a/src/harness/application/context/__tests__/boundedExplore.load.test.ts +++ b/src/harness/application/context/__tests__/boundedExplore.load.test.ts @@ -32,4 +32,31 @@ loadDescribe('bounded explore load acceptance', () => { await fsExtra.remove(repo); } }); + + it('enforces the CPU deadline for catastrophic regex backtracking', async () => { + const repo = await fsExtra.mkdtemp(path.join(os.tmpdir(), 'bounded-regex-load-')); + try { + await fsExtra.outputFile( + path.join(repo, 'src', 'pathological.ts'), + `${'a'.repeat(128)}!\n` + ); + const startedAt = Date.now(); + + const search = await searchBoundedCode({ + cwd: repo, + pattern: '^(a+)+$', + }, { + regexTimeoutMs: 50, + }); + + expect(search).toMatchObject({ + success: false, + errorCode: 'EXPLORE_REGEX_TIMEOUT', + page: { regexTimedOut: true, partial: true }, + }); + expect(Date.now() - startedAt).toBeLessThan(1_000); + } finally { + await fsExtra.remove(repo); + } + }); }); diff --git a/src/harness/application/context/__tests__/boundedExplore.test.ts b/src/harness/application/context/__tests__/boundedExplore.test.ts index ef8fb570..d85d919c 100644 --- a/src/harness/application/context/__tests__/boundedExplore.test.ts +++ b/src/harness/application/context/__tests__/boundedExplore.test.ts @@ -4,6 +4,7 @@ import * as os from 'os'; import * as path from 'path'; import { + listBoundedExploreFiles, readBoundedExploreFile, searchBoundedCode, } from '../boundedExplore'; @@ -103,6 +104,36 @@ describe('bounded explore I/O', () => { }); }); + it('bounds list traversal and reports unavailable continuation when ignore is explicitly empty', async () => { + for (let index = 0; index < 40; index += 1) { + await fsExtra.outputFile( + path.join(repo, 'node_modules', `package-${index}`, 'README.md'), + 'irrelevant' + ); + } + + const result = await listBoundedExploreFiles({ + cwd: repo, + pattern: '**/*.ts', + ignore: [], + limit: 10, + }, { + maxEntries: 12, + maxDirectories: 8, + maxFiles: 8, + }); + + expect(result.files).toEqual([]); + expect(result.page).toMatchObject({ + partial: true, + recordsScanned: 12, + entriesScanned: 12, + discoveryLimitReason: 'entry-limit', + continuationAvailable: false, + continuationUnavailableReason: 'discovery-limit-reached', + }); + }); + it('skips a huge matching file without whole-file reads', async () => { const file = path.join(repo, 'src', 'huge.ts'); await fsExtra.ensureDir(path.dirname(file)); @@ -145,4 +176,39 @@ describe('bounded explore I/O', () => { expect(first.page).toMatchObject({ hasMore: true, pageByteLimited: true }); expect((second.matches as any[])[0].line).toBe((first.matches as any[]).length + 1); }); + + it('terminates pathological regexes without blocking the main event loop', async () => { + await fsExtra.outputFile( + path.join(repo, 'src', 'pathological.ts'), + `${'a'.repeat(64)}!\n` + ); + let eventLoopTicked = false; + const tick = new Promise((resolve) => { + setTimeout(() => { + eventLoopTicked = true; + resolve(); + }, 0); + }); + const startedAt = Date.now(); + + const result = await searchBoundedCode({ + cwd: repo, + pattern: '^(a+)+$', + }, { + regexTimeoutMs: 25, + }); + await tick; + + expect(eventLoopTicked).toBe(true); + expect(Date.now() - startedAt).toBeLessThan(1_000); + expect(result).toMatchObject({ + success: false, + errorCode: 'EXPLORE_REGEX_TIMEOUT', + page: { + partial: true, + regexTimedOut: true, + regexTimeoutMs: 25, + }, + }); + }); }); diff --git a/src/harness/application/context/boundedExplore.ts b/src/harness/application/context/boundedExplore.ts index da88ca86..dcf4183b 100644 --- a/src/harness/application/context/boundedExplore.ts +++ b/src/harness/application/context/boundedExplore.ts @@ -1,6 +1,7 @@ import { createReadStream, promises as fs } from 'fs'; import * as path from 'path'; import * as readline from 'readline'; +import { Worker } from 'worker_threads'; import { minimatch } from 'minimatch'; import { @@ -14,6 +15,7 @@ export const MAX_EXPLORE_SEARCH_FILES = 5_000; export const MAX_EXPLORE_SEARCH_ENTRIES = 20_000; export const MAX_EXPLORE_SEARCH_DIRECTORIES = 2_000; export const MAX_EXPLORE_SEARCH_RESULT_BYTES = 512 * 1024; +export const DEFAULT_EXPLORE_REGEX_TIMEOUT_MS = 100; export interface BoundedExploreReadResult extends Record { success: boolean; @@ -32,6 +34,43 @@ export interface BoundedExploreSearchOptions { maxDirectories?: number; maxFileBytes?: number; maxResultBytes?: number; + regexTimeoutMs?: number; +} + +export interface BoundedExploreListInput { + pattern: string; + cwd: string; + ignore?: string[]; + limit: number; + cursor?: string; +} + +export interface BoundedExploreListOptions { + maxFiles?: number; + maxEntries?: number; + maxDirectories?: number; +} + +export interface BoundedExploreListResult { + success: boolean; + files: string[]; + count: number; + pattern: string; + page: { + nextCursor?: string; + hasMore: boolean; + recordsReturned: number; + recordsScanned: number; + entriesScanned: number; + directoriesScanned: number; + matchingFilesScanned: number; + discoveryLimitReason?: DiscoveryMetrics['limitReason']; + continuationAvailable: boolean; + continuationUnavailableReason?: 'discovery-limit-reached'; + cursorVersion: 1; + partial: boolean; + durationMs: number; + }; } export interface BoundedExploreSearchInput { @@ -55,6 +94,10 @@ interface DiscoveryMetrics { limitReason?: 'entry-limit' | 'directory-limit' | 'file-limit'; } +interface ListCursor { + fileOffset: number; +} + interface SearchMatch { file: string; line: number; @@ -65,6 +108,146 @@ interface SearchMatch { const IGNORED_DIRECTORY_NAMES = new Set(['node_modules', '.git', 'dist', 'build']); const DEFAULT_SEARCH_GLOB = '**/*.{ts,tsx,js,jsx,py,go,rs,java}'; +const REGEX_WORKER_SOURCE = String.raw` + const { parentPort, workerData } = require('worker_threads'); + let regex; + try { + regex = new RegExp(workerData.pattern, 'gm'); + parentPort.postMessage({ type: 'ready' }); + } catch (error) { + parentPort.postMessage({ type: 'compile-error', message: error instanceof Error ? error.message : String(error) }); + } + parentPort.on('message', ({ id, line }) => { + regex.lastIndex = 0; + parentPort.postMessage({ type: 'result', id, matched: regex.test(line) }); + }); +`; + +class RegexDeadlineError extends Error { + constructor(readonly timeoutMs: number) { + super(`Regex evaluation exceeded the ${timeoutMs}ms CPU deadline.`); + this.name = 'RegexDeadlineError'; + } +} + +/** + * Runs caller-controlled regexes outside the main event loop. A pathological + * expression can consume at most one worker until the hard per-line deadline, + * after which the worker is terminated. + */ +class BoundedRegexMatcher { + private readonly worker: Worker; + private requestId = 0; + private pending: { + id: number; + resolve: (matched: boolean) => void; + reject: (error: Error) => void; + timer: NodeJS.Timeout; + } | undefined; + private closed = false; + private termination: Promise | undefined; + + private constructor( + pattern: string, + private readonly timeoutMs: number, + ready: { resolve: () => void; reject: (error: Error) => void } + ) { + this.worker = new Worker(REGEX_WORKER_SOURCE, { + eval: true, + workerData: { pattern }, + }); + this.worker.on('message', (message: { + type: 'ready' | 'compile-error' | 'result'; + id?: number; + matched?: boolean; + message?: string; + }) => { + if (message.type === 'ready') { + ready.resolve(); + return; + } + if (message.type === 'compile-error') { + ready.reject(new SyntaxError(message.message || 'Invalid regular expression')); + return; + } + if (message.type === 'result' && this.pending?.id === message.id) { + const pending = this.pending!; + this.pending = undefined; + clearTimeout(pending.timer); + pending.resolve(Boolean(message.matched)); + } + }); + this.worker.on('error', (error) => { + ready.reject(error); + this.rejectPending(error); + }); + this.worker.on('exit', (code) => { + if (!this.closed && code !== 0) { + this.rejectPending(new Error(`Regex worker exited with code ${code}`)); + } + }); + } + + static async create(pattern: string, timeoutMs: number): Promise { + let resolveReady!: () => void; + let rejectReady!: (error: Error) => void; + const readyPromise = new Promise((resolve, reject) => { + resolveReady = resolve; + rejectReady = reject; + }); + const matcher = new BoundedRegexMatcher(pattern, timeoutMs, { + resolve: resolveReady, + reject: rejectReady, + }); + const compileTimer = setTimeout(() => { + rejectReady(new RegexDeadlineError(Math.max(timeoutMs, 500))); + void matcher.close(); + }, Math.max(timeoutMs, 500)); + try { + await readyPromise; + return matcher; + } catch (error) { + await matcher.close(); + throw error; + } finally { + clearTimeout(compileTimer); + } + } + + async test(line: string): Promise { + if (this.closed) throw new Error('Regex worker is closed.'); + const id = ++this.requestId; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + if (this.pending?.id !== id) return; + this.pending = undefined; + const error = new RegexDeadlineError(this.timeoutMs); + reject(error); + void this.close(); + }, this.timeoutMs); + this.pending = { id, resolve, reject, timer }; + this.worker.postMessage({ id, line }); + }); + } + + async close(): Promise { + if (!this.termination) { + this.closed = true; + this.rejectPending(new Error('Regex worker was terminated.')); + this.termination = this.worker.terminate(); + } + await this.termination; + } + + private rejectPending(error: Error): void { + if (!this.pending) return; + const pending = this.pending; + this.pending = undefined; + clearTimeout(pending.timer); + pending.reject(error); + } +} + function positiveLimit(value: number | undefined, fallback: number, maximum: number): number { if (value === undefined) return fallback; if (!Number.isInteger(value) || value < 1 || value > maximum) { @@ -178,6 +361,132 @@ async function* discoverSearchFiles( } } +function matchesAnyIgnore(relativePath: string, isDirectory: boolean, ignore: string[]): boolean { + return ignore.some((pattern) => { + if (minimatch(relativePath, pattern, { dot: true })) return true; + return isDirectory && minimatch(`${relativePath}/`, pattern, { dot: true }); + }); +} + +/** + * List files through the same bounded opendir strategy used by search. Unlike + * globIterate, this walker caps work even when a caller explicitly disables + * the default node_modules/.git ignores. + */ +export async function listBoundedExploreFiles( + input: BoundedExploreListInput, + options: BoundedExploreListOptions = {} +): Promise { + const startedAt = Date.now(); + const cwd = path.resolve(input.cwd); + const ignore = input.ignore ?? []; + const pageLimit = positiveLimit(input.limit, 100, 1_000); + const limits = { + maxFiles: positiveLimit(options.maxFiles, MAX_EXPLORE_SEARCH_FILES, MAX_EXPLORE_SEARCH_FILES), + maxEntries: positiveLimit(options.maxEntries, MAX_EXPLORE_SEARCH_ENTRIES, MAX_EXPLORE_SEARCH_ENTRIES), + maxDirectories: positiveLimit( + options.maxDirectories, + MAX_EXPLORE_SEARCH_DIRECTORIES, + MAX_EXPLORE_SEARCH_DIRECTORIES + ), + }; + const binding = queryBinding({ pattern: input.pattern, cwd, ignore }); + const boundary = decodeHistoryCursor(input.cursor, 'explore-files', binding) + ?? { fileOffset: 0 }; + if (!Number.isInteger(boundary.fileOffset) || boundary.fileOffset < 0) { + throw new RangeError('explore files cursor offset must be a non-negative integer'); + } + + const files: string[] = []; + const queue: string[] = [cwd]; + let directoriesQueued = 1; + let directoriesScanned = 0; + let entriesScanned = 0; + let matchingFiles = 0; + let limitReason: DiscoveryMetrics['limitReason']; + let resultPageLimited = false; + + outer: while (queue.length > 0) { + if (directoriesScanned >= limits.maxDirectories) { + limitReason = 'directory-limit'; + break; + } + const directoryPath = queue.shift()!; + directoriesScanned += 1; + let directory; + try { + directory = await fs.opendir(directoryPath); + } catch { + continue; + } + for await (const entry of directory) { + if (entriesScanned >= limits.maxEntries) { + limitReason = 'entry-limit'; + break outer; + } + entriesScanned += 1; + const absolutePath = path.join(directoryPath, entry.name); + const relativePath = path.relative(cwd, absolutePath).split(path.sep).join('/'); + if (entry.isDirectory()) { + if (matchesAnyIgnore(relativePath, true, ignore)) continue; + if (directoriesQueued >= limits.maxDirectories) { + limitReason = 'directory-limit'; + continue; + } + directoriesQueued += 1; + queue.push(absolutePath); + continue; + } + if (!entry.isFile() || matchesAnyIgnore(relativePath, false, ignore)) continue; + if (!minimatch(relativePath, input.pattern, { dot: true })) continue; + if (matchingFiles >= limits.maxFiles) { + limitReason = 'file-limit'; + break outer; + } + const fileOffset = matchingFiles; + matchingFiles += 1; + if (fileOffset < boundary.fileOffset) continue; + if (files.length === pageLimit) { + resultPageLimited = true; + break outer; + } + files.push(relativePath); + } + } + + const discoveryPartial = limitReason !== undefined; + const hasMore = resultPageLimited; + const nextCursor = hasMore + ? encodeHistoryCursor('explore-files', binding, { + fileOffset: boundary.fileOffset + files.length, + }) + : undefined; + + return { + success: true, + files, + count: files.length, + pattern: input.pattern, + page: { + nextCursor, + hasMore, + recordsReturned: files.length, + recordsScanned: entriesScanned, + entriesScanned, + directoriesScanned, + matchingFilesScanned: matchingFiles, + discoveryLimitReason: limitReason, + continuationAvailable: Boolean(nextCursor), + continuationUnavailableReason: discoveryPartial && !nextCursor + ? 'discovery-limit-reached' + : undefined, + cursorVersion: 1, + partial: hasMore || discoveryPartial, + durationMs: Date.now() - startedAt, + }, + }; +} + /** Search line-by-line over a bounded, streaming repository discovery. */ export async function searchBoundedCode( input: BoundedExploreSearchInput, @@ -206,10 +515,15 @@ export async function searchBoundedCode( MAX_EXPLORE_SEARCH_RESULT_BYTES, MAX_EXPLORE_SEARCH_RESULT_BYTES ); + const regexTimeoutMs = positiveLimit( + options.regexTimeoutMs, + DEFAULT_EXPLORE_REGEX_TIMEOUT_MS, + 1_000 + ); const binding = queryBinding({ cwd, fileGlob, pattern: input.pattern }); const boundary = decodeHistoryCursor(input.cursor, 'explore-search', binding) ?? { fileOffset: 0, lineOffset: 0 }; - const regex = new RegExp(input.pattern, 'gm'); + const matcher = await BoundedRegexMatcher.create(input.pattern, regexTimeoutMs); const matches: SearchMatch[] = []; const metrics: DiscoveryMetrics = { entriesScanned: 0, @@ -223,95 +537,112 @@ export async function searchBoundedCode( let oversizedFilesSkipped = 0; let hasMore = false; let pageByteLimited = false; + let regexTimedOut = false; let nextCursor: string | undefined; let returnedBytes = 2; - outer: for await (const file of discoverSearchFiles(cwd, fileGlob, limits, metrics)) { - if (file.fileOffset < boundary.fileOffset) continue; - let stat; - try { - stat = await fs.stat(file.absolutePath); - } catch { - continue; - } - if (stat.size > maxFileBytes) { - oversizedFilesSkipped += 1; - metrics.partial = true; - continue; - } - filesScanned += 1; - const startLine = file.fileOffset === boundary.fileOffset ? boundary.lineOffset : 0; - const stream = createReadStream(file.absolutePath, { - encoding: 'utf8', - highWaterMark: 64 * 1024, - // Guard a growth race after stat: the stream itself can never consume - // more than the per-file budget. - start: 0, - end: maxFileBytes - 1, - }); - const lines = readline.createInterface({ input: stream, crlfDelay: Infinity }); - let lineNumber = 0; - let previousLine: string | undefined; - let pending: { lineNumber: number; line: string; previousLine?: string } | undefined; - const appendPending = (nextLine?: string): boolean => { - if (!pending) return true; - const context = [pending.previousLine, pending.line, nextLine] - .filter((value): value is string => value !== undefined) - .join('\n') - .slice(0, 500); - const candidate: SearchMatch = { - file: file.relativePath, - line: pending.lineNumber, - match: pending.line.trim().slice(0, 200), - context, - }; - const candidateBytes = Buffer.byteLength(JSON.stringify(candidate), 'utf8'); - const candidateTotal = returnedBytes + candidateBytes + (matches.length > 0 ? 1 : 0); - if (matches.length === maxResults || candidateTotal > maxResultBytes) { - hasMore = true; - pageByteLimited = matches.length < maxResults; - nextCursor = encodeHistoryCursor('explore-search', binding, { - fileOffset: file.fileOffset, - lineOffset: pending.lineNumber - 1, - }); - return false; + try { + outer: for await (const file of discoverSearchFiles(cwd, fileGlob, limits, metrics)) { + if (file.fileOffset < boundary.fileOffset) continue; + let stat; + try { + stat = await fs.stat(file.absolutePath); + } catch { + continue; } - matches.push(candidate); - returnedBytes = candidateTotal; - pending = undefined; - return true; - }; - try { - for await (const line of lines) { - lineNumber += 1; - bytesScanned += Buffer.byteLength(line, 'utf8') + 1; - if (lineNumber <= startLine) { - previousLine = line; - continue; + if (stat.size > maxFileBytes) { + oversizedFilesSkipped += 1; + metrics.partial = true; + continue; + } + filesScanned += 1; + const startLine = file.fileOffset === boundary.fileOffset ? boundary.lineOffset : 0; + const stream = createReadStream(file.absolutePath, { + encoding: 'utf8', + highWaterMark: 64 * 1024, + // Guard a growth race after stat: the stream itself can never consume + // more than the per-file budget. + start: 0, + end: maxFileBytes - 1, + }); + const lines = readline.createInterface({ input: stream, crlfDelay: Infinity }); + let lineNumber = 0; + let previousLine: string | undefined; + let pending: { lineNumber: number; line: string; previousLine?: string } | undefined; + const appendPending = (nextLine?: string): boolean => { + if (!pending) return true; + const context = [pending.previousLine, pending.line, nextLine] + .filter((value): value is string => value !== undefined) + .join('\n') + .slice(0, 500); + const candidate: SearchMatch = { + file: file.relativePath, + line: pending.lineNumber, + match: pending.line.trim().slice(0, 200), + context, + }; + const candidateBytes = Buffer.byteLength(JSON.stringify(candidate), 'utf8'); + const candidateTotal = returnedBytes + candidateBytes + (matches.length > 0 ? 1 : 0); + if (matches.length === maxResults || candidateTotal > maxResultBytes) { + hasMore = true; + pageByteLimited = matches.length < maxResults; + nextCursor = encodeHistoryCursor('explore-search', binding, { + fileOffset: file.fileOffset, + lineOffset: pending.lineNumber - 1, + }); + return false; } - linesScanned += 1; - if (pending && !appendPending(line)) break outer; - regex.lastIndex = 0; - if (regex.test(line)) { - pending = { lineNumber, line, previousLine }; + matches.push(candidate); + returnedBytes = candidateTotal; + pending = undefined; + return true; + }; + try { + for await (const line of lines) { + lineNumber += 1; + bytesScanned += Buffer.byteLength(line, 'utf8') + 1; + if (lineNumber <= startLine) { + previousLine = line; + continue; + } + linesScanned += 1; + if (pending && !appendPending(line)) break outer; + try { + if (await matcher.test(line)) { + pending = { lineNumber, line, previousLine }; + } + } catch (error) { + if (error instanceof RegexDeadlineError) { + regexTimedOut = true; + metrics.partial = true; + break outer; + } + throw error; + } + previousLine = line; } - previousLine = line; + if (pending && !appendPending()) break outer; + } finally { + lines.close(); + stream.destroy(); + } + const finalSize = await fs.stat(file.absolutePath).then(value => value.size).catch(() => stat.size); + if (finalSize > maxFileBytes) { + oversizedFilesSkipped += 1; + metrics.partial = true; } - if (pending && !appendPending()) break outer; - } finally { - lines.close(); - stream.destroy(); - } - const finalSize = await fs.stat(file.absolutePath).then(value => value.size).catch(() => stat.size); - if (finalSize > maxFileBytes) { - oversizedFilesSkipped += 1; - metrics.partial = true; } + } finally { + await matcher.close(); } - const partial = hasMore || metrics.partial || oversizedFilesSkipped > 0; + const partial = hasMore || metrics.partial || oversizedFilesSkipped > 0 || regexTimedOut; return { - success: true, + success: !regexTimedOut, + errorCode: regexTimedOut ? 'EXPLORE_REGEX_TIMEOUT' : undefined, + error: regexTimedOut + ? `Regex evaluation exceeded the ${regexTimeoutMs}ms CPU deadline.` + : undefined, pattern: input.pattern, matches, totalMatches: matches.length, @@ -330,6 +661,8 @@ export async function searchBoundedCode( directoriesScanned: metrics.directoriesScanned, matchingFilesScanned: metrics.matchingFiles, oversizedFilesSkipped, + regexTimedOut, + regexTimeoutMs, discoveryLimitReason: metrics.limitReason, partial, cursorVersion: 1, diff --git a/src/harness/application/context/contextTools.ts b/src/harness/application/context/contextTools.ts index 67b054bf..e7da3803 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -1,5 +1,5 @@ import * as fs from 'fs-extra'; -import { glob, globIterate } from 'glob'; +import { glob } from 'glob'; import * as path from 'path'; import { TreeSitterLayer } from '../../adapters/out/semantic/treeSitter/treeSitterLayer'; import { SemanticContextBuilder } from '../../adapters/out/semantic/contextBuilder'; @@ -30,13 +30,11 @@ import { createSkillRegistry } from '../../domain/workflow/skills'; import { ensureGitignorePatterns } from '../../../utils/gitignoreManager'; import { boundedLimit, - decodeHistoryCursor, - encodeHistoryCursor, - queryBinding, RUNTIME_HISTORY_LIMITS, type RuntimeHistoryPage, } from '../history/runtimeHistory'; import { + listBoundedExploreFiles, readBoundedExploreFile, searchBoundedCode, } from './boundedExplore'; @@ -378,53 +376,13 @@ export const listFilesTool = createInternalTool< RUNTIME_HISTORY_LIMITS.exploreFiles.maximum, 'explore files' ); - const binding = queryBinding({ pattern, cwd: resolvedCwd, ignore: resolvedIgnore }); - const boundary = decodeHistoryCursor<{ offset: number }>( - input.cursor, - 'explore-files', - binding - ); - const offset = boundary?.offset ?? 0; - const files: string[] = []; - let matched = 0; - let recordsScanned = 0; - let hasMore = false; - const startedAt = Date.now(); - for await (const file of globIterate(pattern, { + return await listBoundedExploreFiles({ + pattern, cwd: resolvedCwd, ignore: resolvedIgnore, - absolute: false, - nodir: true, - })) { - recordsScanned += 1; - if (matched < offset) { - matched += 1; - continue; - } - if (files.length === limit) { - hasMore = true; - break; - } - files.push(file.split(path.sep).join('/')); - matched += 1; - } - return { - success: true, - files, - count: files.length, - pattern, - page: { - nextCursor: hasMore - ? encodeHistoryCursor('explore-files', binding, { offset: offset + files.length }) - : undefined, - hasMore, - recordsReturned: files.length, - recordsScanned, - cursorVersion: 1, - partial: hasMore, - durationMs: Date.now() - startedAt, - }, - }; + limit, + cursor: input.cursor, + }); } catch (error) { return { success: false, diff --git a/src/mcp/README.md b/src/mcp/README.md index 770c0c9d..71fbd806 100644 --- a/src/mcp/README.md +++ b/src/mcp/README.md @@ -36,9 +36,9 @@ The same UTF-8 budget applies to `context://`, `file://`, and `workflow://` reso The growing harness lists (`listSessions`, `listTraces`, `listArtifacts`, `listTasks`, `listHandoffs`, `listReplays`, and `listDatasets`) return bounded pages. Pass `limit` and the opaque `cursor` returned as `page.nextCursor` to continue; do not inspect or modify cursors. `replaySession.maxEvents` defaults to 100 and cannot exceed 1,000. An oversized page returns `MCP_PAGE_TOO_LARGE` with `suggestedLimit`, never truncated JSON. -`explore` action `list` is also paginated: it defaults to 100 files, accepts at most 1,000, and returns an opaque `page.nextCursor` when more matches exist. +`explore` action `list` is also paginated: it defaults to 100 files, accepts at most 1,000, and returns an opaque `page.nextCursor` when more matches exist. Directory, raw-entry, and matching-file ceilings still apply when `ignore: []`; `page.partial` and `page.discoveryLimitReason` report an incomplete traversal. -`explore` action `read` rejects files above 1 MiB from metadata before opening their bodies. Action `search` streams a bounded directory walk and bounded files line-by-line, caps result bytes, reports discovery/file skips in `page`, and returns `page.nextCursor` when another result page is available. +`explore` action `read` rejects files above 1 MiB from metadata before opening their bodies. Action `search` streams a bounded directory walk and bounded files line-by-line, caps result bytes, reports discovery/file skips in `page`, and returns `page.nextCursor` when another result page is available. Caller-controlled regular expressions run outside the MCP event loop with a hard per-line CPU deadline; a timeout returns `EXPLORE_REGEX_TIMEOUT` and partial metadata. ### Dedicated Workflow Tools (5) From 92ee57e8158ad3048f5f0eb04df2247a2f0003bf Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:15:30 -0300 Subject: [PATCH 33/39] fix: close runtime history review gaps --- CHANGELOG.md | 3 + .../docs/en/concepts/replay-and-datasets.md | 4 +- .../pt-br/concepts/replay-and-datasets.md | 4 +- .../__tests__/runtimeStateService.test.ts | 19 +- .../out/runtimeState/runtimeStateService.ts | 158 ++++++++- .../application/actions/actionService.ts | 4 + .../contracts/taskContractsService.ts | 36 ++- .../datasets/__tests__/datasetService.test.ts | 35 ++ .../application/datasets/datasetService.ts | 102 ++++-- .../application/execution/executionService.ts | 6 +- .../__tests__/runtimeHistory.load.test.ts | 9 + .../__tests__/runtimeRetentionService.test.ts | 29 ++ .../history/runtimeRetentionService.ts | 68 +++- .../replay/__tests__/replayService.test.ts | 47 ++- .../application/replay/replayService.ts | 300 +++++++++--------- .../sensors/__tests__/sensorsService.test.ts | 17 +- .../application/sensors/sensorsService.ts | 42 ++- .../workflow/harnessSessionFacade.ts | 2 +- src/mcp/server/mcpServer.ts | 17 +- 19 files changed, 688 insertions(+), 214 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b2ab24c..7eb3ef84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added configurable, globally clamped hook stdin, field, event, rotation, segment-retention, and per-session trace limits. - Added opaque cursor pages for sessions, traces, artifacts, replay summaries, and dataset summaries, including bounded defaults, query-bound cursors, and scan metadata. - Added latest-sensor summary indexes, bounded dataset concurrency/failure retention, and dry-run runtime pruning with active workflow protection. +- Added paginated sensor-run history alongside sharded, byte-capped latest-sensor summaries, plus small replay/dataset retention sidecars. ### Fixed @@ -20,6 +21,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. - Replaced whole-file trace reads and post-materialization replay limits with rotation-aware streaming and source-level event bounds. - Added aggregate UTF-8 page budgets to runtime history so large valid records cannot multiply count limits into unbounded materialization. +- Made replay use one count/byte budget and one continuation cursor across every source, without persisting duplicate source arrays; datasets now enforce per-failure, aggregate, and on-disk byte limits. +- Made retention inspect bounded metadata prefixes and include young terminal sessions when enforcing the repository runtime quota. ## [1.1.1] - 2026-06-27 diff --git a/docs/src/content/docs/en/concepts/replay-and-datasets.md b/docs/src/content/docs/en/concepts/replay-and-datasets.md index 78c166de..cfbf55a4 100644 --- a/docs/src/content/docs/en/concepts/replay-and-datasets.md +++ b/docs/src/content/docs/en/concepts/replay-and-datasets.md @@ -41,7 +41,7 @@ Each replay is a self-contained snapshot. Beyond the collected data, it carries | `nextCursor` | Opaque continuation cursor when the replay is partial | | `summary` | Human-readable description of the run | -The collected source arrays and the merged `events` array are all constrained by `maxEvents` (100 by default, 1,000 maximum). A partial replay persists only that bounded materialization: +The merged `events` array is constrained by one shared `maxEvents` and byte budget (100 events by default, 1,000 maximum). Source records, when requested, live only under their event's `record` field; replay files no longer duplicate them in separate source arrays. A partial replay can continue every source through the same opaque cursor: ```json { @@ -105,7 +105,7 @@ Build a replay right after a session finishes — whether it completed or failed ## Failure datasets: clustering what keeps breaking -A single replay tells you about one run. A **failure dataset** processes sessions with one worker by default (configurable up to four), retains at most 10,000 failures by default, and reports `partial` plus `omittedFailureCount` when capped. +A single replay tells you about one run. A **failure dataset** processes sessions with one worker by default (configurable up to four), retains at most 10,000 failures by default, and also applies per-failure, aggregate, and persisted-file byte budgets. It reports `partial` plus `omittedFailureCount` when any limit is reached. ### How failures are collected diff --git a/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md b/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md index 092041d6..baa4b049 100644 --- a/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md +++ b/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md @@ -41,7 +41,7 @@ Cada replay é um snapshot autocontido. Além dos dados coletados, ele carrega u | `nextCursor` | Cursor opaco de continuação quando o replay é parcial | | `summary` | Descrição legível da execução | -Os arrays de origem coletados e o array mesclado `events` são limitados por `maxEvents` (100 por padrão, máximo de 1.000). Um replay parcial persiste somente essa materialização limitada: +O array mesclado `events` usa um único orçamento compartilhado de `maxEvents` e bytes (100 eventos por padrão, máximo de 1.000). Quando solicitados, os registros de origem ficam apenas no campo `record` do evento; o arquivo de replay não os duplica em arrays separados. Um replay parcial continua todas as fontes pelo mesmo cursor opaco: ```json { @@ -105,7 +105,7 @@ Construa um replay logo após a sessão terminar — tendo ela completado ou fal ## Datasets de falha: agrupando o que continua quebrando -Um único replay conta sobre uma execução. Um **dataset de falha** processa sessões com um worker por padrão (configurável até quatro), retém no máximo 10.000 falhas por padrão e informa `partial` e `omittedFailureCount` quando o limite é atingido. +Um único replay conta sobre uma execução. Um **dataset de falha** processa sessões com um worker por padrão (configurável até quatro), retém no máximo 10.000 falhas por padrão e também aplica limites de bytes por falha, agregados e no arquivo persistido. Ele informa `partial` e `omittedFailureCount` quando qualquer limite é atingido. ### Como as falhas são coletadas diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 8ddbce4a..87de456e 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -3,6 +3,8 @@ import * as os from 'os'; import * as path from 'path'; import { HarnessRuntimeStateService, + MAX_SENSOR_SUMMARY_ENTRIES, + MAX_SENSOR_SUMMARY_ENTRY_BYTES, MAX_STREAMED_TRACE_LINE_BYTES, } from '../runtimeStateService'; @@ -299,6 +301,21 @@ describe('HarnessRuntimeStateService', () => { const summary = await service.getSensorSummary(session.id); expect(summary.latestBySensor.tests).toMatchObject({ status: 'passed' }); - expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'sensor-summary.json'))).toBe(true); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'sensor-summary'))).toBe(true); + }); + + it('shards and caps sensor summaries by entry count and bytes', async () => { + const session = await service.createSession({ name: 'bounded-sensor-summary' }); + for (let index = 0; index < MAX_SENSOR_SUMMARY_ENTRIES + 4; index += 1) { + await service.appendTrace(session.id, { + level: 'error', event: 'sensor.run', message: `sensor-${index}`, + data: { run: { id: `run-${index}`, sensorId: `sensor-${index}`, sessionId: session.id, status: 'failed', createdAt: new Date(1_700_000_000_000 + index).toISOString(), output: 'x'.repeat(80 * 1024) } }, + }); + } + const summaryDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id, 'sensor-summary'); + const files = (await fs.readdir(summaryDir)).filter(file => file.endsWith('.json') && file !== 'meta.json'); + expect(files.length).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRIES); + for (const file of files) expect((await fs.stat(path.join(summaryDir, file))).size).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRY_BYTES); + expect(Object.keys((await service.getSensorSummary(session.id)).latestBySensor).length).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRIES); }); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index 4a7d6e6e..187e8133 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -8,7 +8,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; -import { randomUUID } from 'crypto'; +import { createHash, randomUUID } from 'crypto'; import { promises as nodeFs } from 'fs'; import type { FileHandle } from 'fs/promises'; import { resolveRuntimeLayout, type RuntimeLayout } from '../../../../shared/fs/pathHelpers'; @@ -193,6 +193,18 @@ export interface HarnessSensorSummary { version: 1; updatedAt: string; latestBySensor: Record; + runCount?: number; +} + +export const MAX_SENSOR_SUMMARY_ENTRIES = 256; +export const MAX_SENSOR_SUMMARY_BYTES = 1024 * 1024; +export const MAX_SENSOR_SUMMARY_ENTRY_BYTES = 64 * 1024; + +interface HarnessSensorSummaryShard { + version: 1; + sensorId: string; + updatedAt: string; + run: Record; } interface TraceCursorPosition { @@ -422,6 +434,19 @@ export class HarnessRuntimeStateService { return path.join(this.layout.sessionDir(sessionId), 'sensor-summary.json'); } + private sensorSummaryDir(sessionId: string): string { + return path.join(this.layout.sessionDir(sessionId), 'sensor-summary'); + } + + private sensorSummaryShardFile(sessionId: string, sensorId: string): string { + const key = createHash('sha256').update(sensorId).digest('hex'); + return path.join(this.sensorSummaryDir(sessionId), `${key}.json`); + } + + private sensorSummaryMetadataFile(sessionId: string): string { + return path.join(this.sensorSummaryDir(sessionId), 'meta.json'); + } + private async ensureSessionDir(sessionId: string): Promise { await fs.ensureDir(this.layout.sessionDir(sessionId)); } @@ -525,29 +550,140 @@ export class HarnessRuntimeStateService { if (trace.event !== 'sensor.run' || !trace.data?.run || typeof trace.data.run !== 'object') return; const run = trace.data.run as Record; if (typeof run.sensorId !== 'string') return; - const current = await this.getSensorSummary(sessionId); - current.latestBySensor[run.sensorId] = run; - current.updatedAt = trace.createdAt; - const target = this.sensorSummaryFile(sessionId); + const sensorId = run.sensorId; + let boundedRun = run; + if (Buffer.byteLength(JSON.stringify(run), 'utf8') > MAX_SENSOR_SUMMARY_ENTRY_BYTES) { + boundedRun = { + id: run.id, + sensorId, + sessionId: run.sessionId, + contractId: run.contractId, + severity: run.severity, + blocking: run.blocking, + createdAt: run.createdAt, + status: run.status, + summary: typeof run.summary === 'string' ? run.summary.slice(0, 8 * 1024) : String(run.summary ?? ''), + truncated: true, + }; + } + const shard: HarnessSensorSummaryShard = { + version: 1, + sensorId, + updatedAt: trace.createdAt, + run: boundedRun, + }; + await fs.ensureDir(this.sensorSummaryDir(sessionId)); + const target = this.sensorSummaryShardFile(sessionId, sensorId); const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`; - await fs.writeJson(temporary, current, { spaces: 2 }); + await fs.writeJson(temporary, shard); await fs.rename(temporary, target); + const metadataFile = this.sensorSummaryMetadataFile(sessionId); + const metadata = await nodeFs.stat(metadataFile).then(stat => stat.size <= 4096 ? fs.readJson(metadataFile) : undefined).catch(() => undefined) as { runCount?: number } | undefined; + const metadataTemporary = `${metadataFile}.${process.pid}.${randomUUID()}.tmp`; + await fs.writeJson(metadataTemporary, { version: 1, updatedAt: trace.createdAt, runCount: Math.max(0, metadata?.runCount ?? 0) + 1 }); + await fs.rename(metadataTemporary, metadataFile); + await this.pruneSensorSummaryShards(sessionId); + } + + private async pruneSensorSummaryShards(sessionId: string): Promise { + const directoryPath = this.sensorSummaryDir(sessionId); + if (!(await fs.pathExists(directoryPath))) return; + const entries: Array<{ file: string; bytes: number; mtime: number }> = []; + const directory = await nodeFs.opendir(directoryPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name === 'meta.json') continue; + const file = path.join(directoryPath, entry.name); + const stat = await nodeFs.stat(file); + entries.push({ file, bytes: stat.size, mtime: stat.mtimeMs }); + } + entries.sort((a, b) => b.mtime - a.mtime); + let retainedBytes = 0; + for (let index = 0; index < entries.length; index += 1) { + const entry = entries[index]; + if (index >= MAX_SENSOR_SUMMARY_ENTRIES || entry.bytes > MAX_SENSOR_SUMMARY_ENTRY_BYTES || retainedBytes + entry.bytes > MAX_SENSOR_SUMMARY_BYTES) { + await fs.remove(entry.file); + } else { + retainedBytes += entry.bytes; + } + } + } + + private async readShardedSensorSummary(sessionId: string): Promise { + const directoryPath = this.sensorSummaryDir(sessionId); + if (!(await fs.pathExists(directoryPath))) return undefined; + const entries: Array<{ file: string; bytes: number; mtime: number }> = []; + const directory = await nodeFs.opendir(directoryPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name === 'meta.json') continue; + const file = path.join(directoryPath, entry.name); + const stat = await nodeFs.stat(file); + if (stat.size <= MAX_SENSOR_SUMMARY_ENTRY_BYTES) entries.push({ file, bytes: stat.size, mtime: stat.mtimeMs }); + } + entries.sort((a, b) => b.mtime - a.mtime); + const latestBySensor: Record = {}; + let totalBytes = 0; + let updatedAt = ''; + for (const entry of entries.slice(0, MAX_SENSOR_SUMMARY_ENTRIES)) { + if (totalBytes + entry.bytes > MAX_SENSOR_SUMMARY_BYTES) break; + try { + const shard = await fs.readJson(entry.file) as HarnessSensorSummaryShard; + if (typeof shard.sensorId !== 'string' || !shard.run) continue; + latestBySensor[shard.sensorId] = shard.run; + updatedAt = updatedAt > shard.updatedAt ? updatedAt : shard.updatedAt; + totalBytes += entry.bytes; + } catch { /* skip a corrupt shard */ } + } + const metadataFile = this.sensorSummaryMetadataFile(sessionId); + const metadata = await nodeFs.stat(metadataFile).then(stat => stat.size <= 4096 ? fs.readJson(metadataFile) : undefined).catch(() => undefined) as { runCount?: number; updatedAt?: string } | undefined; + return { version: 1, updatedAt: metadata?.updatedAt ?? (updatedAt || nowIso()), latestBySensor, runCount: Math.max(Object.keys(latestBySensor).length, metadata?.runCount ?? 0) }; } async getSensorSummary(sessionId: string): Promise { + const sharded = await this.readShardedSensorSummary(sessionId); + if (sharded) return sharded; const target = this.sensorSummaryFile(sessionId); + let legacyFallback: HarnessSensorSummary | undefined; if (await fs.pathExists(target)) { - try { return await fs.readJson(target) as HarnessSensorSummary; } catch { /* migrate below */ } + try { + const stat = await nodeFs.stat(target); + if (stat.size <= MAX_SENSOR_SUMMARY_BYTES) { + legacyFallback = await fs.readJson(target) as HarnessSensorSummary; + await fs.remove(target); + } + } catch { /* migrate from bounded trace records below */ } } const latestBySensor: Record = {}; + let retainedBytes = 0; + let runCount = 0; for await (const trace of this.iterateTraces(sessionId)) { const run = trace.data?.run as Record | undefined; - if (trace.event === 'sensor.run' && typeof run?.sensorId === 'string') latestBySensor[run.sensorId] = run; + if (trace.event !== 'sensor.run' || typeof run?.sensorId !== 'string') continue; + runCount += 1; + const bytes = Buffer.byteLength(JSON.stringify(run), 'utf8'); + if (!(run.sensorId in latestBySensor) && Object.keys(latestBySensor).length >= MAX_SENSOR_SUMMARY_ENTRIES) continue; + if (bytes > MAX_SENSOR_SUMMARY_ENTRY_BYTES || retainedBytes + bytes > MAX_SENSOR_SUMMARY_BYTES) continue; + const previous = latestBySensor[run.sensorId]; + if (previous) retainedBytes -= Buffer.byteLength(JSON.stringify(previous), 'utf8'); + latestBySensor[run.sensorId] = run; + retainedBytes += bytes; + } + if (runCount === 0 && legacyFallback) { + for (const [sensorId, run] of Object.entries(legacyFallback.latestBySensor).slice(0, MAX_SENSOR_SUMMARY_ENTRIES)) { + latestBySensor[sensorId] = run; + } + runCount = Math.max(Object.keys(latestBySensor).length, legacyFallback.runCount ?? 0); } - const summary: HarnessSensorSummary = { version: 1, updatedAt: nowIso(), latestBySensor }; + const summary: HarnessSensorSummary = { version: 1, updatedAt: nowIso(), latestBySensor, runCount }; await this.ensureSessionDir(sessionId); - await fs.writeJson(target, summary, { spaces: 2 }); - return summary; + await fs.ensureDir(this.sensorSummaryDir(sessionId)); + for (const [sensorId, run] of Object.entries(latestBySensor)) { + await this.updateSensorSummary(sessionId, { + id: randomUUID(), sessionId, level: 'info', event: 'sensor.run', message: 'sensor summary migration', + createdAt: (run as Record).createdAt as string ?? summary.updatedAt, data: { run: run as Record }, + }); + } + await fs.writeJson(this.sensorSummaryMetadataFile(sessionId), { version: 1, updatedAt: summary.updatedAt, runCount }); + return (await this.readShardedSensorSummary(sessionId)) ?? summary; } private async recordTrace(sessionId: string, trace: HarnessTraceRecord): Promise { diff --git a/src/harness/application/actions/actionService.ts b/src/harness/application/actions/actionService.ts index 67507c47..09a82b9e 100644 --- a/src/harness/application/actions/actionService.ts +++ b/src/harness/application/actions/actionService.ts @@ -95,6 +95,7 @@ export interface HarnessActionInput { createdBefore?: string; concurrency?: number; maxFailures?: number; + maxFailureBytes?: number; scope?: 'sensor' | 'artifact' | 'handoff' | 'workflow' | 'task' | 'risk'; effect?: 'allow' | 'deny' | 'require_approval'; target?: 'tool' | 'action' | 'path' | 'risk'; @@ -366,6 +367,7 @@ export class HarnessActionService { includePayloads: params.includePayloads, maxEvents: params.maxEvents, maxBytes: params.maxBytes, + cursor: params.cursor, }), }; case 'listReplays': @@ -389,6 +391,8 @@ export class HarnessActionService { includeSuccessfulSessions: params.includeSuccessfulSessions, concurrency: params.concurrency, maxFailures: params.maxFailures, + maxFailureBytes: params.maxFailureBytes, + maxBytes: params.maxBytes, }), }; case 'listDatasets': diff --git a/src/harness/application/contracts/taskContractsService.ts b/src/harness/application/contracts/taskContractsService.ts index cb318cd5..44143b65 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -19,7 +19,10 @@ import type { HarnessSensorRun } from '../sensors/sensorsService'; import { boundedLimit, boundedPageBytes, + decodeHistoryCursor, + encodeHistoryCursor, MAX_RUNTIME_HISTORY_PAGE_BYTES, + queryBinding, serializedHistoryItemBytes, } from '../history/runtimeHistory'; @@ -195,6 +198,8 @@ export interface HarnessHandoffContract { export interface BoundedSessionContracts { items: T[]; total: number; + nextCursor?: string; + hasMore: boolean; returnedBytes: number; byteBudget: number; byteLimited: boolean; @@ -313,13 +318,16 @@ export class HarnessTaskContractsService { async listSessionTaskContracts( sessionId: string, limit = 100, - maxBytes?: number + maxBytes?: number, + cursor?: string ): Promise> { return this.listBoundedSessionContracts( this.tasksPath, sessionId, boundedLimit(limit, 100, 1000, 'session task contracts'), - boundedPageBytes(maxBytes, 'session task contracts') + boundedPageBytes(maxBytes, 'session task contracts'), + cursor, + 'session-task-contracts' ); } @@ -401,13 +409,16 @@ export class HarnessTaskContractsService { async listSessionHandoffContracts( sessionId: string, limit = 100, - maxBytes?: number + maxBytes?: number, + cursor?: string ): Promise> { return this.listBoundedSessionContracts( this.handoffsPath, sessionId, boundedLimit(limit, 100, 1000, 'session handoff contracts'), - boundedPageBytes(maxBytes, 'session handoff contracts') + boundedPageBytes(maxBytes, 'session handoff contracts'), + cursor, + 'session-handoff-contracts' ); } @@ -415,9 +426,13 @@ export class HarnessTaskContractsService { directoryPath: string, sessionId: string, limit: number, - byteBudget: number + byteBudget: number, + cursor: string | undefined, + scope: string ): Promise> { await this.ensureLayout(); + const binding = queryBinding({ sessionId, direction: 'oldest' }); + const boundary = decodeHistoryCursor<{ createdAt: string; id: string }>(cursor, scope, binding); const selected: Array<{ file: string; createdAt: string; id: string; bytes: number }> = []; let total = 0; let oversizedRecordsSkipped = 0; @@ -433,6 +448,7 @@ export class HarnessTaskContractsService { const contract = await fs.readJson(file) as T; if (contract.sessionId !== sessionId) continue; total += 1; + if (boundary && `${contract.createdAt}\0${contract.id}` <= `${boundary.createdAt}\0${boundary.id}`) continue; const bytes = serializedHistoryItemBytes(contract); if (bytes + 2 > byteBudget) { oversizedRecordsSkipped += 1; @@ -442,7 +458,7 @@ export class HarnessTaskContractsService { selected.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id) ); - if (selected.length > limit) selected.pop(); + if (selected.length > limit + 1) selected.pop(); } catch { // A malformed unrelated contract must not make replay unavailable. } @@ -450,7 +466,7 @@ export class HarnessTaskContractsService { const chosen: typeof selected = []; let returnedBytes = 2; let byteLimited = false; - for (const candidate of selected) { + for (const candidate of selected.slice(0, limit + 1)) { if (chosen.length === limit) break; const candidateTotal = returnedBytes + candidate.bytes + (chosen.length > 0 ? 1 : 0); if (candidateTotal > byteBudget) { @@ -462,9 +478,15 @@ export class HarnessTaskContractsService { } const items: T[] = []; for (const candidate of chosen) items.push(await fs.readJson(candidate.file) as T); + const hasMore = selected.length > chosen.length; + const last = chosen.at(-1); return { items, total, + nextCursor: hasMore && last + ? encodeHistoryCursor(scope, binding, { createdAt: last.createdAt, id: last.id }) + : undefined, + hasMore, returnedBytes, byteBudget, byteLimited, diff --git a/src/harness/application/datasets/__tests__/datasetService.test.ts b/src/harness/application/datasets/__tests__/datasetService.test.ts index 2d06b2b4..761b5d07 100644 --- a/src/harness/application/datasets/__tests__/datasetService.test.ts +++ b/src/harness/application/datasets/__tests__/datasetService.test.ts @@ -147,4 +147,39 @@ describe('HarnessDatasetService', () => { expect(dataset.sessionCount).toBe(3); expect(dataset.replayCount).toBe(3); }); + + it('stops on per-record and aggregate byte budgets and persists a bounded dataset', async () => { + const session = await execution.createSession({ name: 'byte-budget' }); + const replay = new HarnessReplayService({ repoPath: tempDir }); + const base = await replay.buildReplay(session.id); + const records = Array.from({ length: 12 }, (_, index) => ({ + id: `trace-${index}`, + sessionId: session.id, + level: 'error' as const, + event: 'task.failed', + message: `${index}:${'x'.repeat(index === 0 ? 4096 : 700)}`, + createdAt: new Date(1_700_000_000_000 + index).toISOString(), + })); + const bounded = new HarnessDatasetService({ + repoPath: tempDir, + dependencies: { + replayService: { + buildReplay: async () => ({ ...base, events: records.map(record => ({ id: record.id, sessionId: session.id, createdAt: record.createdAt, source: 'trace' as const, label: record.event, record })) }), + }, + }, + }); + + const dataset = await bounded.buildFailureDataset({ + sessionIds: [session.id], + includeSuccessfulSessions: true, + maxFailureBytes: 2048, + maxBytes: 4096, + }); + const file = path.join(tempDir, '.context', 'runtime', 'evaluations', 'datasets', `${dataset.id}.json`); + expect(dataset.partial).toBe(true); + expect(dataset.omittedFailureCount).toBeGreaterThan(0); + expect(dataset.failures.every(failure => Buffer.byteLength(JSON.stringify(failure)) <= 2048)).toBe(true); + expect((await fs.stat(file)).size).toBeLessThanOrEqual(4096); + expect(await fs.pathExists(file.replace(/\.json$/, '.meta.json'))).toBe(true); + }); }); diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index 77eabc3b..54d5ca68 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -1,6 +1,6 @@ import * as fs from 'fs-extra'; import * as path from 'path'; -import { randomUUID } from 'crypto'; +import { createHash, randomUUID } from 'crypto'; import { resolveRuntimeLayoutFromRepo } from '../../../shared/fs/pathHelpers'; import { @@ -60,8 +60,15 @@ export interface BuildHarnessDatasetOptions { includeSuccessfulSessions?: boolean; concurrency?: number; maxFailures?: number; + maxFailureBytes?: number; + maxBytes?: number; } +export const DEFAULT_DATASET_MAX_BYTES = 16 * 1024 * 1024; +export const MAX_DATASET_BYTES = 64 * 1024 * 1024; +export const DEFAULT_FAILURE_RECORD_MAX_BYTES = 64 * 1024; +export const MAX_FAILURE_RECORD_BYTES = 1024 * 1024; + export interface HarnessDatasetSummary { id: string; createdAt: string; @@ -82,15 +89,27 @@ function nowIso(): string { } function normalizeSignature(value: string): string { - return value + const normalized = value .toLowerCase() .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, ':uuid') .replace(/\s+/g, ' ') .trim(); + if (Buffer.byteLength(normalized, 'utf8') <= 512) return normalized; + return `${normalized.slice(0, 384)}:sha256:${createHash('sha256').update(normalized).digest('hex')}`; +} + +function replayRecords(replay: HarnessReplayRecord, source: HarnessReplayRecord['events'][number]['source']): T[] { + const events = replay.events ?? []; + const current = events + .filter(event => event.source === source && event.record) + .map(event => event.record as T); + if (current.length > 0 || events.length > 0) return current; + const legacyKey = ({ trace: 'traces', artifact: 'artifacts', checkpoint: 'checkpoints', sensor: 'sensorRuns', task: 'tasks', handoff: 'handoffs' } as const)[source as Exclude]; + return legacyKey ? (((replay as unknown as Record)[legacyKey] as T[] | undefined) ?? []) : []; } function buildSensorFailures(replay: HarnessReplayRecord): HarnessFailureRecord[] { - return replay.sensorRuns + return replayRecords(replay, 'sensor') .filter(run => run.status === 'failed' || run.status === 'blocked') .map(run => ({ id: randomUUID(), @@ -115,7 +134,7 @@ async function buildTaskFailures( ): Promise { const taskFailures: HarnessFailureRecord[] = []; - for (const task of replay.tasks.filter(item => item.sessionId === replay.sessionId)) { + for (const task of replayRecords(replay, 'task').filter(item => item.sessionId === replay.sessionId)) { const result = await taskContractsService.evaluateTaskCompletion(task.id, replay.sessionId); if (result.canComplete) { continue; @@ -147,7 +166,7 @@ function buildSessionFailure(replay: HarnessReplayRecord): HarnessFailureRecord[ return []; } - const lastErrorTrace = [...replay.traces].reverse().find(trace => trace.level === 'error' || trace.event.includes('failed')); + const lastErrorTrace = replayRecords(replay, 'trace').reverse().find(trace => trace.level === 'error' || trace.event.includes('failed')); const message = lastErrorTrace?.message || `Session failed: ${replay.session.name}`; return [{ @@ -167,7 +186,7 @@ function buildSessionFailure(replay: HarnessReplayRecord): HarnessFailureRecord[ } function buildTraceFailures(replay: HarnessReplayRecord): HarnessFailureRecord[] { - return replay.traces + return replayRecords(replay, 'trace') .filter(trace => trace.event !== 'sensor.run') .filter(trace => trace.level === 'error' || /failed|blocked/i.test(trace.event) || /failed|blocked/i.test(trace.message)) .map(trace => ({ @@ -196,7 +215,7 @@ function clusterFailures(failures: HarnessFailureRecord[]): HarnessFailureCluste signature: failure.signature, count: 1, sessionIds: [failure.sessionId], - exampleMessages: [failure.message], + exampleMessages: [failure.message.slice(0, 1024)], firstSeenAt: failure.createdAt, lastSeenAt: failure.createdAt, }); @@ -204,11 +223,11 @@ function clusterFailures(failures: HarnessFailureRecord[]): HarnessFailureCluste } existing.count += 1; - if (!existing.sessionIds.includes(failure.sessionId)) { + if (existing.sessionIds.length < 100 && !existing.sessionIds.includes(failure.sessionId)) { existing.sessionIds.push(failure.sessionId); } if (existing.exampleMessages.length < 3) { - existing.exampleMessages.push(failure.message); + existing.exampleMessages.push(failure.message.slice(0, 1024)); } if (failure.createdAt < existing.firstSeenAt) { existing.firstSeenAt = failure.createdAt; @@ -264,6 +283,10 @@ export class HarnessDatasetService { return path.join(this.datasetsPath, `${datasetId}.json`); } + private datasetMetadataFile(datasetId: string): string { + return path.join(this.datasetsPath, `${datasetId}.meta.json`); + } + private async ensureLayout(): Promise { await fs.ensureDir(this.datasetsPath); } @@ -271,22 +294,39 @@ export class HarnessDatasetService { async buildFailureDataset(options: BuildHarnessDatasetOptions = {}): Promise { const concurrency = boundedLimit(options.concurrency, 1, 4, 'dataset concurrency'); const maxFailures = boundedLimit(options.maxFailures, 10_000, 10_000, 'dataset failures'); + const maxDatasetBytes = boundedPageBytes(options.maxBytes, 'dataset persistence', DEFAULT_DATASET_MAX_BYTES, MAX_DATASET_BYTES); + const maxFailureBytes = boundedPageBytes(options.maxFailureBytes, 'dataset failure records', DEFAULT_FAILURE_RECORD_MAX_BYTES, MAX_FAILURE_RECORD_BYTES); + const aggregateFailureByteBudget = Math.floor(maxDatasetBytes / 2); const failures: HarnessFailureRecord[] = []; + let retainedFailureBytes = 2; + let failureByteLimited = false; let omittedFailureCount = 0; let sessionCount = 0; let replayCount = 0; const retain = (records: HarnessFailureRecord[]) => { - const available = Math.max(0, maxFailures - failures.length); - failures.push(...records.slice(0, available)); - omittedFailureCount += Math.max(0, records.length - available); + for (const record of records) { + if (failures.length >= maxFailures || failureByteLimited) { + omittedFailureCount += 1; + continue; + } + const bytes = serializedHistoryItemBytes(record); + if (bytes > maxFailureBytes || retainedFailureBytes + bytes + (failures.length > 0 ? 1 : 0) > aggregateFailureByteBudget) { + omittedFailureCount += 1; + failureByteLimited = true; + continue; + } + failures.push(record); + retainedFailureBytes += bytes + (failures.length > 1 ? 1 : 0); + } }; const processSession = async (session: HarnessSessionRecord): Promise => { if (!options.includeSuccessfulSessions && session.status === 'completed') return; sessionCount += 1; const replay = await this.replayService.buildReplay(session.id, { - includePayloads: false, + includePayloads: true, maxEvents: 1000, + maxBytes: Math.min(maxDatasetBytes, MAX_RUNTIME_HISTORY_PAGE_BYTES), }); replayCount += 1; retain(buildSensorFailures(replay)); @@ -344,8 +384,27 @@ export class HarnessDatasetService { omittedFailureCount, }; + let serialized = JSON.stringify(dataset); + while (Buffer.byteLength(serialized, 'utf8') > maxDatasetBytes && dataset.clusters.length > 0) { + dataset.clusters.pop(); + dataset.clusterCount = dataset.clusters.length; + dataset.partial = true; + serialized = JSON.stringify(dataset); + } + if (Buffer.byteLength(serialized, 'utf8') > maxDatasetBytes) { + throw new Error(`Dataset persistence budget exceeded after bounded compaction (${maxDatasetBytes} bytes)`); + } await this.ensureLayout(); - await fs.writeJson(this.datasetFile(dataset.id), dataset, { spaces: 2 }); + await fs.writeFile(this.datasetFile(dataset.id), serialized, 'utf8'); + await fs.writeJson(this.datasetMetadataFile(dataset.id), { + version: 1, + id: dataset.id, + createdAt: dataset.createdAt, + sessionCount: dataset.sessionCount, + failureCount: dataset.failureCount, + clusterCount: dataset.clusterCount, + partial: dataset.partial, + }); return dataset; } @@ -368,14 +427,17 @@ export class HarnessDatasetService { let oversizedRecordsSkipped = 0; const directory = await fs.opendir(this.datasetsPath); for await (const entry of directory) { - if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.endsWith('.meta.json')) continue; try { const file = path.join(this.datasetsPath, entry.name); - if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { - oversizedRecordsSkipped += 1; - continue; - } - const dataset = await fs.readJson(file) as HarnessFailureDataset; + const metadataFile = this.datasetMetadataFile(entry.name.slice(0, -'.json'.length)); + const metadataBytes = await fs.stat(metadataFile).then(stat => stat.size).catch(() => Number.POSITIVE_INFINITY); + const dataset = metadataBytes <= MAX_RUNTIME_HISTORY_PAGE_BYTES + ? await fs.readJson(metadataFile) as HarnessFailureDataset + : (await fs.stat(file)).size <= MAX_RUNTIME_HISTORY_PAGE_BYTES + ? await fs.readJson(file) as HarnessFailureDataset + : undefined; + if (!dataset) { oversizedRecordsSkipped += 1; continue; } recordsScanned += 1; const key = `${dataset.createdAt}\0${dataset.id}`; if (boundary && key >= `${boundary.createdAt}\0${boundary.id}`) continue; diff --git a/src/harness/application/execution/executionService.ts b/src/harness/application/execution/executionService.ts index 1b7f66cf..10641184 100644 --- a/src/harness/application/execution/executionService.ts +++ b/src/harness/application/execution/executionService.ts @@ -192,6 +192,10 @@ export class HarnessExecutionService { return this.sensors.getSessionSensorRuns(sessionId); } + getSessionSensorRunPage(sessionId: string, query: Parameters[1] = {}) { + return this.sensors.getSessionSensorRunPage(sessionId, query); + } + async createTaskContract(input: Parameters[0]) { await this.policy.authorize({ tool: 'harness', @@ -332,7 +336,7 @@ export class HarnessExecutionService { ): Promise { const [session, sensorRuns, taskEvaluation] = await Promise.all([ this.state.getSession(sessionId), - this.sensors.getSessionSensorRuns(sessionId), + this.sensors.getLatestSessionSensorRuns(sessionId), options.taskId ? this.contracts.evaluateTaskCompletion(options.taskId, sessionId) : Promise.resolve(null), diff --git a/src/harness/application/history/__tests__/runtimeHistory.load.test.ts b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts index 276ea1e1..ad7877a4 100644 --- a/src/harness/application/history/__tests__/runtimeHistory.load.test.ts +++ b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts @@ -2,6 +2,7 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { HarnessRuntimeStateService } from '../../../adapters/out/runtimeState/runtimeStateService'; +import { HarnessReplayService } from '../../replay/replayService'; const loadDescribe = process.env.DOTCONTEXT_RUNTIME_LOAD_TESTS === '1' ? describe : describe.skip; @@ -25,6 +26,14 @@ loadDescribe('runtime history load acceptance', () => { global.gc?.(); expect(page.items).toHaveLength(100); expect(process.memoryUsage().rss - before).toBeLessThan(32 * 1024 * 1024); + + global.gc?.(); + const replayBefore = process.memoryUsage().rss; + const replay = await new HarnessReplayService({ repoPath: tempDir }).buildReplay(session.id, { maxEvents: 100, includePayloads: false }); + global.gc?.(); + expect(replay.events).toHaveLength(100); + expect(replay.events.every(event => event.record === undefined)).toBe(true); + expect(process.memoryUsage().rss - replayBefore).toBeLessThan(32 * 1024 * 1024); }); it('keeps a 1,000-session page bounded', async () => { diff --git a/src/harness/application/history/__tests__/runtimeRetentionService.test.ts b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts index 05cfa7c3..36f9eb22 100644 --- a/src/harness/application/history/__tests__/runtimeRetentionService.test.ts +++ b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts @@ -35,4 +35,33 @@ describe('HarnessRuntimeRetentionService', () => { expect(await fs.pathExists(expiredFile)).toBe(false); expect(await fs.pathExists(boundFile)).toBe(true); }); + + it('reads only bounded metadata from oversized legacy evaluations', async () => { + const replayDir = path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays'); + const replayFile = path.join(replayDir, 'legacy.json'); + await fs.outputFile(replayFile, `{"id":"legacy","sessionId":"session-1","createdAt":"2020-01-01T00:00:00.000Z","events":["${'x'.repeat(12 * 1024 * 1024)}"]}`); + global.gc?.(); + const before = process.memoryUsage().rss; + const report = await new HarnessRuntimeRetentionService(tempDir).prune({ dryRun: true, now: new Date('2026-01-01T00:00:00.000Z') }); + global.gc?.(); + expect(report.candidates.map(item => item.path)).toContain(replayFile); + expect(process.memoryUsage().rss - before).toBeLessThan(16 * 1024 * 1024); + }); + + it('uses young terminal sessions as quota candidates while protecting active sessions', async () => { + const state = new HarnessRuntimeStateService({ repoPath: tempDir }); + const active = await state.createSession({ name: 'active' }); + const terminal = await state.createSession({ name: 'terminal' }); + await state.completeSession(terminal.id); + const report = await new HarnessRuntimeRetentionService(tempDir).prune({ + dryRun: true, + now: new Date(), + sessionRetentionDays: 30, + quotaBytes: 1, + }); + expect(report.candidates).toEqual(expect.arrayContaining([ + expect.objectContaining({ path: path.join(tempDir, '.context', 'runtime', 'sessions', terminal.id), kind: 'session', reason: 'quota' }), + ])); + expect(report.candidates.map(item => item.path)).not.toContain(path.join(tempDir, '.context', 'runtime', 'sessions', active.id)); + }); }); diff --git a/src/harness/application/history/runtimeRetentionService.ts b/src/harness/application/history/runtimeRetentionService.ts index 14de558d..e2070342 100644 --- a/src/harness/application/history/runtimeRetentionService.ts +++ b/src/harness/application/history/runtimeRetentionService.ts @@ -1,6 +1,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import { randomUUID } from 'crypto'; +import { promises as nodeFs } from 'fs'; import { resolveRuntimeLayoutFromRepo } from '../../../shared/fs/pathHelpers'; import type { HarnessSessionRecord } from '../../adapters/out/runtimeState/runtimeStateService'; @@ -33,6 +34,48 @@ async function fileBytes(target: string): Promise { return total; } +const LEGACY_METADATA_READ_BYTES = 64 * 1024; + +async function readBoundedJsonPrefix(target: string): Promise { + const handle = await nodeFs.open(target, 'r'); + try { + const buffer = Buffer.allocUnsafe(LEGACY_METADATA_READ_BYTES); + const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); + return buffer.subarray(0, bytesRead).toString('utf8'); + } finally { + await handle.close(); + } +} + +function jsonString(prefix: string, property: string): string | undefined { + const match = prefix.match(new RegExp(`"${property}"\\s*:\\s*"((?:\\\\.|[^"\\\\])*)"`)); + if (!match) return undefined; + try { return JSON.parse(`"${match[1]}"`) as string; } catch { return undefined; } +} + +async function readEvaluationMetadata(target: string): Promise<{ createdAt?: string; sessionId?: string }> { + const sidecar = target.replace(/\.json$/, '.meta.json'); + if (await fs.pathExists(sidecar)) { + const stat = await nodeFs.stat(sidecar); + if (stat.size <= LEGACY_METADATA_READ_BYTES) { + try { + const value = JSON.parse(await nodeFs.readFile(sidecar, 'utf8')) as { createdAt?: string; sessionId?: string }; + return { createdAt: value.createdAt, sessionId: value.sessionId }; + } catch { /* use bounded legacy prefix */ } + } + } + const prefix = await readBoundedJsonPrefix(target); + return { createdAt: jsonString(prefix, 'createdAt'), sessionId: jsonString(prefix, 'sessionId') }; +} + +async function readSessionMetadata(target: string): Promise | undefined> { + const prefix = await readBoundedJsonPrefix(target); + const id = jsonString(prefix, 'id'); + const status = jsonString(prefix, 'status') as HarnessSessionRecord['status'] | undefined; + const updatedAt = jsonString(prefix, 'updatedAt'); + return id && status && updatedAt ? { id, status, updatedAt } : undefined; +} + export class HarnessRuntimeRetentionService { constructor(private readonly repoPath: string) {} @@ -45,6 +88,7 @@ export class HarnessRuntimeRetentionService { .catch(() => undefined); const protectedSessionIds = new Set(activeBinding ? [activeBinding] : []); const candidates: RuntimePruneReport['candidates'] = []; + const quotaEligibleSessions: Array<{ path: string; kind: 'session'; bytes: number; mtime: number }> = []; if (await fs.pathExists(layout.sessionsDir)) { const directory = await fs.opendir(layout.sessionsDir); @@ -52,14 +96,17 @@ export class HarnessRuntimeRetentionService { if (!entry.isDirectory() || entry.name.startsWith('.prune-')) continue; const target = layout.sessionDir(entry.name); try { - const session = await fs.readJson(layout.sessionFile(entry.name)) as HarnessSessionRecord; + const session = await readSessionMetadata(layout.sessionFile(entry.name)); + if (!session) continue; if (session.status === 'active' || session.status === 'paused' || protectedSessionIds.has(session.id)) { protectedSessionIds.add(session.id); continue; } const cutoff = (options.sessionRetentionDays ?? 30) * 86_400_000; + const bytes = await fileBytes(target); + quotaEligibleSessions.push({ path: target, kind: 'session', bytes, mtime: new Date(session.updatedAt).getTime() }); if (now - new Date(session.updatedAt).getTime() > cutoff) { - candidates.push({ path: target, kind: 'session', bytes: await fileBytes(target), reason: 'age' }); + candidates.push({ path: target, kind: 'session', bytes, reason: 'age' }); } } catch { /* corrupt state is retained for manual recovery */ } } @@ -70,11 +117,14 @@ export class HarnessRuntimeRetentionService { const records: Array<{ path: string; createdAt: string; sessionId?: string; bytes: number }> = []; const directory = await fs.opendir(dir); for await (const entry of directory) { - if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.endsWith('.meta.json')) continue; const target = path.join(dir, entry.name); try { - const value = await fs.readJson(target) as { createdAt: string; sessionId?: string }; - records.push({ path: target, createdAt: value.createdAt, sessionId: value.sessionId, bytes: (await fs.stat(target)).size }); + const value = await readEvaluationMetadata(target); + if (!value.createdAt) continue; + const metadataFile = target.replace(/\.json$/, '.meta.json'); + const metadataBytes = await nodeFs.stat(metadataFile).then(stat => stat.size).catch(() => 0); + records.push({ path: target, createdAt: value.createdAt, sessionId: value.sessionId, bytes: (await fs.stat(target)).size + metadataBytes }); } catch { /* retain malformed files */ } } records.sort((a, b) => b.createdAt.localeCompare(a.createdAt)); @@ -94,14 +144,15 @@ export class HarnessRuntimeRetentionService { const quota = options.quotaBytes ?? 256 * 1024 * 1024; if (runtimeBytes > quota) { const already = new Set(candidates.map(item => item.path)); - const eligible: Array<{ path: string; kind: 'session' | 'replay' | 'dataset'; bytes: number; mtime: number }> = []; + const eligible: Array<{ path: string; kind: 'session' | 'replay' | 'dataset'; bytes: number; mtime: number }> = quotaEligibleSessions.filter(item => !already.has(item.path)); for (const dir of [layout.replaysDir, layout.datasetsDir]) { if (!(await fs.pathExists(dir))) continue; for (const name of await fs.readdir(dir)) { const target = path.join(dir, name); - if (already.has(target) || !name.endsWith('.json')) continue; + if (already.has(target) || !name.endsWith('.json') || name.endsWith('.meta.json')) continue; const stat = await fs.stat(target); - eligible.push({ path: target, kind: dir === layout.replaysDir ? 'replay' : 'dataset', bytes: stat.size, mtime: stat.mtimeMs }); + const metadataBytes = await nodeFs.stat(target.replace(/\.json$/, '.meta.json')).then(value => value.size).catch(() => 0); + eligible.push({ path: target, kind: dir === layout.replaysDir ? 'replay' : 'dataset', bytes: stat.size + metadataBytes, mtime: stat.mtimeMs }); } } eligible.sort((a, b) => a.mtime - b.mtime); @@ -119,6 +170,7 @@ export class HarnessRuntimeRetentionService { const tombstone = path.join(path.dirname(candidate.path), `.prune-${randomUUID()}-${path.basename(candidate.path)}`); await fs.rename(candidate.path, tombstone); await fs.remove(tombstone); + if (candidate.path.endsWith('.json')) await fs.remove(candidate.path.replace(/\.json$/, '.meta.json')); } } return { dryRun: options.dryRun !== false, candidates, protectedSessionIds: [...protectedSessionIds], pruneBytes: candidates.reduce((sum, item) => sum + item.bytes, 0), runtimeBytes, durationMs: Date.now() - started }; diff --git a/src/harness/application/replay/__tests__/replayService.test.ts b/src/harness/application/replay/__tests__/replayService.test.ts index 9433f644..35a9a02c 100644 --- a/src/harness/application/replay/__tests__/replayService.test.ts +++ b/src/harness/application/replay/__tests__/replayService.test.ts @@ -60,6 +60,7 @@ describe('HarnessReplayService', () => { expect(list).toHaveLength(1); expect(list[0].sessionId).toBe(session.id); expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays', `${replay.id}.json`))).toBe(true); + expect(await fs.pathExists(path.join(tempDir, '.context', 'runtime', 'evaluations', 'replays', `${replay.id}.meta.json`))).toBe(true); }); it('applies maxEvents to materialization, response, and persistence', async () => { @@ -73,10 +74,9 @@ describe('HarnessReplayService', () => { expect(replay.events).toHaveLength(10); expect(replay.fidelity).toBe('partial'); expect(replay.omittedCounts.trace).toBeGreaterThan(0); - for (const source of ['artifacts', 'checkpoints', 'traces', 'sensorRuns', 'tasks', 'handoffs']) { - expect((replay[source as keyof typeof replay] as unknown[]).length).toBeLessThanOrEqual(10); - expect((persisted[source] as unknown[]).length).toBeLessThanOrEqual(10); - } + expect(Object.keys(replay)).not.toEqual(expect.arrayContaining(['artifacts', 'checkpoints', 'traces', 'sensorRuns', 'tasks', 'handoffs'])); + expect(Object.keys(persisted)).not.toEqual(expect.arrayContaining(['artifacts', 'checkpoints', 'traces', 'sensorRuns', 'tasks', 'handoffs'])); + expect(Buffer.byteLength(JSON.stringify(persisted.events))).toBeLessThanOrEqual(1024 * 1024); }); it('reads bounded session-scoped contracts without global materialization', async () => { @@ -93,15 +93,44 @@ describe('HarnessReplayService', () => { const scopedTasks = jest.spyOn(HarnessTaskContractsService.prototype, 'listSessionTaskContracts'); const scopedHandoffs = jest.spyOn(HarnessTaskContractsService.prototype, 'listSessionHandoffContracts'); - const replay = await service.buildReplay(target.id, { maxEvents: 2 }); + const replay = await service.buildReplay(target.id, { maxEvents: 30 }); expect(listTasks).not.toHaveBeenCalled(); expect(listHandoffs).not.toHaveBeenCalled(); - expect(scopedTasks).toHaveBeenCalledWith(target.id, 2); - expect(scopedHandoffs).toHaveBeenCalledWith(target.id, 2); - expect(replay.tasks).toHaveLength(2); - expect(replay.handoffs).toHaveLength(2); + expect(scopedTasks).toHaveBeenCalledWith(target.id, 30, 1024 * 1024, undefined); + expect(scopedHandoffs).toHaveBeenCalledWith(target.id, 30, 1024 * 1024, undefined); + expect(replay.events.filter(event => event.source === 'task')).toHaveLength(5); + expect(replay.events.filter(event => event.source === 'handoff')).toHaveLength(5); expect(replay.sourceCounts.task).toBe(5); expect(replay.sourceCounts.handoff).toBe(5); }); + + it('continues every merged source with one global cursor and no duplicates', async () => { + const session = await execution.createSession({ name: 'merged-cursor' }); + await execution.addArtifact(session.id, { name: 'evidence', kind: 'text', content: 'ok' }); + await execution.checkpointSession(session.id, { note: 'checkpoint' }); + await execution.createTaskContract({ title: 'task', sessionId: session.id }); + await execution.createHandoffContract({ from: 'author', to: 'reviewer', sessionId: session.id }); + await execution.runSensor({ id: 'tests', name: 'Tests', execute: () => ({ status: 'passed', summary: 'ok' }) }, { sessionId: session.id }); + + const seen = new Set(); + const sources = new Set(); + let cursor: string | undefined; + let pageIndex = 0; + do { + const page = await service.buildReplay(session.id, { maxEvents: 3, cursor }); + expect(page.events.length).toBeLessThanOrEqual(3); + for (const event of page.events) { + const key = `${event.createdAt}:${event.source}:${event.id}`; + expect(seen.has(key)).toBe(false); + seen.add(key); + sources.add(event.source); + } + if (pageIndex === 0) expect(page.nextCursor).toBeDefined(); + cursor = page.nextCursor; + pageIndex += 1; + } while (cursor); + + expect([...sources]).toEqual(expect.arrayContaining(['session', 'trace', 'artifact', 'checkpoint', 'sensor', 'task', 'handoff'])); + }); }); diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index 0b690943..7cb43dd7 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -45,6 +45,7 @@ export interface HarnessReplayEvent { source: HarnessReplayEventSource; label: string; payload?: Record; + record?: HarnessArtifactRecord | HarnessSessionCheckpoint | HarnessTraceRecord | HarnessSensorRun | HarnessTaskContract | HarnessHandoffContract; } export interface HarnessReplayRecord { @@ -61,12 +62,6 @@ export interface HarnessReplayRecord { summary: string; events: HarnessReplayEvent[]; session: Omit & { checkpoints?: never }; - artifacts: HarnessArtifactRecord[]; - checkpoints: HarnessSessionCheckpoint[]; - traces: HarnessTraceRecord[]; - sensorRuns: HarnessSensorRun[]; - tasks: HarnessTaskContract[]; - handoffs: HarnessHandoffContract[]; } export interface HarnessReplayServiceOptions { @@ -78,6 +73,7 @@ export interface ReplaySessionOptions { includePayloads?: boolean; maxEvents?: number; maxBytes?: number; + cursor?: string; } export interface HarnessReplaySummary { @@ -91,7 +87,7 @@ export interface HarnessReplaySummary { export interface HarnessReplayDependencies { stateService: HarnessRuntimeStatePort; - sensorsService: Pick; + sensorsService: Pick; contractsService: Pick< HarnessTaskContractsService, 'listSessionTaskContracts' | 'listSessionHandoffContracts' @@ -106,6 +102,24 @@ function sortByCreatedAt(items: T[]): T[] { return [...items].sort((left, right) => left.createdAt.localeCompare(right.createdAt)); } +interface ReplayCursorPosition { + createdAt: string; + source: HarnessReplayEventSource; + id: string; +} + +const REPLAY_SOURCE_ORDER: Record = { + session: 0, trace: 1, artifact: 2, checkpoint: 3, sensor: 4, task: 5, handoff: 6, +}; + +function replayEventKey(event: Pick): string { + return `${event.createdAt}\0${String(REPLAY_SOURCE_ORDER[event.source]).padStart(2, '0')}\0${event.id}`; +} + +function replayCursorKey(position: ReplayCursorPosition): string { + return `${position.createdAt}\0${String(REPLAY_SOURCE_ORDER[position.source]).padStart(2, '0')}\0${position.id}`; +} + export class HarnessReplayService { private readonly stateService: HarnessReplayDependencies['stateService']; private readonly sensorsService: HarnessReplayDependencies['sensorsService']; @@ -139,6 +153,10 @@ export class HarnessReplayService { return path.join(this.replaysPath, `${replayId}.json`); } + private replayMetadataFile(replayId: string): string { + return path.join(this.replaysPath, `${replayId}.meta.json`); + } + private async ensureLayout(): Promise { await fs.ensureDir(this.replaysPath); } @@ -146,6 +164,15 @@ export class HarnessReplayService { private async saveReplay(replay: HarnessReplayRecord): Promise { await this.ensureLayout(); await fs.writeJson(this.replayFile(replay.id), replay, { spaces: 2 }); + await fs.writeJson(this.replayMetadataFile(replay.id), { + version: 1, + id: replay.id, + sessionId: replay.sessionId, + createdAt: replay.createdAt, + fidelity: replay.fidelity, + eventCount: replay.eventCount, + summary: replay.summary, + }); } private async readReplay(replayId: string): Promise { @@ -162,136 +189,118 @@ export class HarnessReplayService { options: ReplaySessionOptions = {} ): Promise { const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); + const byteBudget = boundedPageBytes(options.maxBytes, 'replay events'); const session = await this.stateService.getSession(sessionId); - const [tracePage, artifactPage, allSensorRuns, taskScan, handoffScan] = await Promise.all([ - this.stateService.listTracePage(sessionId, { limit: maxEvents, direction: 'oldest', maxBytes: options.maxBytes }), - this.stateService.listArtifactPage(sessionId, { limit: Math.min(maxEvents, 200), direction: 'oldest', maxBytes: options.maxBytes }), - this.sensorsService.getSessionSensorRuns(sessionId), - options.maxBytes === undefined - ? this.contractsService.listSessionTaskContracts(sessionId, maxEvents) - : this.contractsService.listSessionTaskContracts(sessionId, maxEvents, options.maxBytes), - options.maxBytes === undefined - ? this.contractsService.listSessionHandoffContracts(sessionId, maxEvents) - : this.contractsService.listSessionHandoffContracts(sessionId, maxEvents, options.maxBytes), - ]); - - const traces = tracePage.items; - const artifacts = artifactPage.items; - const checkpoints = session.checkpoints.slice(0, maxEvents); - const sensorRuns = sortByCreatedAt(allSensorRuns).slice(0, maxEvents); - const sessionTasks = taskScan.items; - const sessionHandoffs = handoffScan.items; - - const events: HarnessReplayEvent[] = [ - { - id: randomUUID(), - sessionId, - createdAt: session.createdAt, - source: 'session', - label: `session:${session.name}`, - payload: options.includePayloads === false - ? undefined - : { - id: session.id, - status: session.status, - metadata: session.metadata ?? null, - }, - }, - ...traces.map((trace) => ({ - id: randomUUID(), - sessionId, - createdAt: trace.createdAt, - source: 'trace' as const, - label: trace.event, - payload: options.includePayloads === false - ? undefined - : { - level: trace.level, - message: trace.message, - data: trace.data ?? null, - }, - })), - ...artifacts.map((artifact) => ({ - id: randomUUID(), - sessionId, - createdAt: artifact.createdAt, - source: 'artifact' as const, - label: artifact.name, - payload: options.includePayloads === false - ? undefined - : { - kind: artifact.kind, - path: artifact.path ?? null, - metadata: artifact.metadata ?? null, - }, - })), - ...checkpoints.map((checkpoint) => ({ - id: randomUUID(), - sessionId, - createdAt: checkpoint.createdAt, - source: 'checkpoint' as const, - label: checkpoint.note || checkpoint.id, - payload: options.includePayloads === false - ? undefined - : { - artifactIds: checkpoint.artifactIds, - data: checkpoint.data ?? null, - }, - })), - ...sensorRuns.map((run) => ({ - id: randomUUID(), - sessionId, - createdAt: run.createdAt, - source: 'sensor' as const, - label: run.sensorId, - payload: options.includePayloads === false - ? undefined - : { - status: run.status, - summary: run.summary, - severity: run.severity, - blocking: run.blocking, - }, - })), - ...sessionTasks.map((task) => ({ - id: randomUUID(), - sessionId, - createdAt: task.createdAt, - source: 'task' as const, - label: task.title, - payload: options.includePayloads === false - ? undefined - : { - status: task.status, - requiredSensors: task.requiredSensors, - requiredArtifacts: task.requiredArtifacts, - acceptanceCriteria: task.acceptanceCriteria, - }, - })), - ...sessionHandoffs.map((handoff) => ({ - id: randomUUID(), - sessionId, - createdAt: handoff.createdAt, - source: 'handoff' as const, - label: `${handoff.from} -> ${handoff.to}`, - payload: options.includePayloads === false - ? undefined - : { - artifacts: handoff.artifacts, - evidence: handoff.evidence, - }, - })), - ]; - - const orderedEvents = sortByCreatedAt(events).slice(0, maxEvents); - const sourceCounts: Record = { + const binding = queryBinding({ sessionId, direction: 'oldest', includePayloads: options.includePayloads !== false }); + const boundary = decodeHistoryCursor(options.cursor, 'replay-events', binding); + const boundaryKey = boundary ? replayCursorKey(boundary) : undefined; + const pageSize = Math.min(32, maxEvents); + const sourceTotals: Record = { session: 1, trace: session.traceCount, artifact: session.artifactCount, checkpoint: session.checkpointCount, - sensor: allSensorRuns.length, - task: taskScan.total, - handoff: handoffScan.total, + sensor: 0, + task: 0, + handoff: 0, + }; + + const afterBoundary = (event: HarnessReplayEvent) => !boundaryKey || replayEventKey(event) > boundaryKey; + const recordFor = >(record: T): T | undefined => + options.includePayloads === false ? undefined : record; + const paged = async function* ( + fetch: (cursor?: string) => Promise<{ items: T[]; nextCursor?: string }>, + map: (item: T) => HarnessReplayEvent + ): AsyncGenerator { + let cursor: string | undefined; + do { + const page = await fetch(cursor); + for (const item of page.items) { + const event = map(item); + if (afterBoundary(event)) yield event; + } + cursor = page.nextCursor; + } while (cursor); + }; + + const sessionSource = async function* (): AsyncGenerator { + const event: HarnessReplayEvent = { + id: `session:${session.id}`, sessionId, createdAt: session.createdAt, source: 'session', label: `session:${session.name}`, + payload: options.includePayloads === false ? undefined : { id: session.id, status: session.status, metadata: session.metadata ?? null }, + }; + if (afterBoundary(event)) yield event; + }; + const traceSource = paged( + cursor => this.stateService.listTracePage(sessionId, { limit: pageSize, cursor, direction: 'oldest', maxBytes: byteBudget }), + trace => ({ id: trace.id, sessionId, createdAt: trace.createdAt, source: 'trace', label: trace.event, record: recordFor(trace) }) + ); + const artifactSource = paged( + cursor => this.stateService.listArtifactPage(sessionId, { limit: pageSize, cursor, direction: 'oldest', maxBytes: byteBudget }), + artifact => ({ id: artifact.id, sessionId, createdAt: artifact.createdAt, source: 'artifact', label: artifact.name, record: recordFor(artifact) }) + ); + const checkpointSource = (async function* (): AsyncGenerator { + for (const checkpoint of sortByCreatedAt(session.checkpoints)) { + const event: HarnessReplayEvent = { id: checkpoint.id, sessionId, createdAt: checkpoint.createdAt, source: 'checkpoint', label: checkpoint.note || checkpoint.id, record: recordFor(checkpoint) }; + if (afterBoundary(event)) yield event; + } + })(); + const sensorSource = paged( + cursor => this.sensorsService.getSessionSensorRunPage(sessionId, { limit: pageSize, cursor, direction: 'oldest', maxBytes: byteBudget }), + run => { + sourceTotals.sensor += 1; + return { id: run.id, sessionId, createdAt: run.createdAt, source: 'sensor', label: run.sensorId, record: recordFor(run) }; + } + ); + const taskSource = paged( + async cursor => { + const page = await this.contractsService.listSessionTaskContracts(sessionId, pageSize, byteBudget, cursor); + sourceTotals.task = page.total; + return page; + }, + task => ({ id: task.id, sessionId, createdAt: task.createdAt, source: 'task', label: task.title, record: recordFor(task) }) + ); + const handoffSource = paged( + async cursor => { + const page = await this.contractsService.listSessionHandoffContracts(sessionId, pageSize, byteBudget, cursor); + sourceTotals.handoff = page.total; + return page; + }, + handoff => ({ id: handoff.id, sessionId, createdAt: handoff.createdAt, source: 'handoff', label: `${handoff.from} -> ${handoff.to}`, record: recordFor(handoff) }) + ); + + const iterators = [sessionSource(), traceSource, artifactSource, checkpointSource, sensorSource, taskSource, handoffSource]; + const heads = await Promise.all(iterators.map(iterator => iterator.next())); + const orderedEvents: HarnessReplayEvent[] = []; + let returnedBytes = 2; + let byteLimited = false; + let lastConsumed: HarnessReplayEvent | undefined; + while (orderedEvents.length < maxEvents) { + let selectedIndex = -1; + for (let index = 0; index < heads.length; index += 1) { + if (heads[index].done) continue; + if (selectedIndex < 0 || replayEventKey(heads[index].value) < replayEventKey(heads[selectedIndex].value)) selectedIndex = index; + } + if (selectedIndex < 0) break; + const candidate = heads[selectedIndex].value; + const bytes = serializedHistoryItemBytes(candidate); + const candidateTotal = returnedBytes + bytes + (orderedEvents.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget && orderedEvents.length > 0) { + byteLimited = true; + break; + } + lastConsumed = candidate; + heads[selectedIndex] = await iterators[selectedIndex].next(); + if (candidateTotal > byteBudget) { + byteLimited = true; + continue; + } + orderedEvents.push(candidate); + returnedBytes = candidateTotal; + } + const hasMore = heads.some(head => !head.done); + const sourceCounts: Record = { + ...sourceTotals, + sensor: sourceTotals.sensor, }; const includedCounts = orderedEvents.reduce((counts, event) => { counts[event.source] += 1; @@ -302,7 +311,7 @@ export class HarnessReplayService { Math.max(0, count - includedCounts[source as HarnessReplayEventSource]), ])) as Record; const { checkpoints: _embeddedCheckpoints, ...boundedSession } = session; - const partial = Object.values(omittedCounts).some(count => count > 0); + const partial = hasMore || byteLimited || Object.values(omittedCounts).some(count => count > 0); const replay: HarnessReplayRecord = { id: randomUUID(), sessionId, @@ -313,16 +322,12 @@ export class HarnessReplayService { eventCount: orderedEvents.length, sourceCounts, omittedCounts, - nextCursor: tracePage.nextCursor, + nextCursor: hasMore && lastConsumed + ? encodeHistoryCursor('replay-events', binding, { createdAt: lastConsumed.createdAt, source: lastConsumed.source, id: lastConsumed.id }) + : undefined, summary: `Replayed ${orderedEvents.length} events for session ${session.name}`, events: orderedEvents, session: boundedSession, - artifacts: artifacts.slice(0, maxEvents), - checkpoints: checkpoints.slice(0, maxEvents), - traces: traces.slice(0, maxEvents), - sensorRuns: sensorRuns.slice(0, maxEvents), - tasks: sessionTasks.slice(0, maxEvents), - handoffs: sessionHandoffs.slice(0, maxEvents), }; return replay; @@ -356,14 +361,17 @@ export class HarnessReplayService { let oversizedRecordsSkipped = 0; const directory = await fs.opendir(this.replaysPath); for await (const entry of directory) { - if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.endsWith('.meta.json')) continue; try { const file = path.join(this.replaysPath, entry.name); - if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { - oversizedRecordsSkipped += 1; - continue; - } - const replay = await fs.readJson(file) as HarnessReplayRecord; + const metadataFile = this.replayMetadataFile(entry.name.slice(0, -'.json'.length)); + const metadataBytes = await fs.stat(metadataFile).then(stat => stat.size).catch(() => Number.POSITIVE_INFINITY); + const replay = metadataBytes <= MAX_RUNTIME_HISTORY_PAGE_BYTES + ? await fs.readJson(metadataFile) as HarnessReplayRecord + : (await fs.stat(file)).size <= MAX_RUNTIME_HISTORY_PAGE_BYTES + ? await fs.readJson(file) as HarnessReplayRecord + : undefined; + if (!replay) { oversizedRecordsSkipped += 1; continue; } recordsScanned += 1; if (query.sessionId && replay.sessionId !== query.sessionId) continue; const key = `${replay.createdAt}\0${replay.id}`; diff --git a/src/harness/application/sensors/__tests__/sensorsService.test.ts b/src/harness/application/sensors/__tests__/sensorsService.test.ts index c97c6582..adfbc996 100644 --- a/src/harness/application/sensors/__tests__/sensorsService.test.ts +++ b/src/harness/application/sensors/__tests__/sensorsService.test.ts @@ -42,5 +42,20 @@ describe('HarnessSensorsService', () => { expect(storedRuns[0].sensorId).toBe('typecheck'); expect(service.evaluateBackpressure([run]).blocked).toBe(true); }); -}); + it('keeps paginated run history separate from the latest summary', async () => { + const session = await stateService.createSession({ name: 'sensor-history' }); + let index = 0; + service.registerSensor({ id: 'tests', name: 'Tests', execute: () => ({ status: index++ === 0 ? 'failed' : 'passed', summary: `run-${index}` }) }); + await service.runSensor('tests', { sessionId: session.id }); + await service.runSensor('tests', { sessionId: session.id }); + + const first = await service.getSessionSensorRunPage(session.id, { limit: 1, direction: 'oldest' }); + const second = await service.getSessionSensorRunPage(session.id, { limit: 1, direction: 'oldest', cursor: first.nextCursor }); + expect(first.items).toHaveLength(1); + expect(second.items).toHaveLength(1); + expect(await service.getSessionSensorRuns(session.id)).toHaveLength(2); + expect(await service.getLatestSessionSensorRuns(session.id)).toHaveLength(1); + expect(await service.getSessionSensorRunCount(session.id)).toBe(2); + }); +}); diff --git a/src/harness/application/sensors/sensorsService.ts b/src/harness/application/sensors/sensorsService.ts index 7e151db1..89305069 100644 --- a/src/harness/application/sensors/sensorsService.ts +++ b/src/harness/application/sensors/sensorsService.ts @@ -11,6 +11,7 @@ import type { HarnessRuntimeStatePort, HarnessTraceRecord, } from '../../adapters/out/runtimeState/runtimeStateService'; +import type { RuntimeHistoryPage, RuntimeHistoryQuery } from '../history/runtimeHistory'; export type HarnessSensorSeverity = 'info' | 'warning' | 'critical'; export type HarnessSensorStatus = 'passed' | 'failed' | 'skipped' | 'blocked'; @@ -122,11 +123,50 @@ export class HarnessSensorsService { return run; } - async getSessionSensorRuns(sessionId: string): Promise { + async getLatestSessionSensorRuns(sessionId: string): Promise { const summary = await this.options.stateService.getSensorSummary(sessionId); return Object.values(summary.latestBySensor) as HarnessSensorRun[]; } + async getSessionSensorRunCount(sessionId: string): Promise { + const summary = await this.options.stateService.getSensorSummary(sessionId); + return Math.max(Object.keys(summary.latestBySensor).length, summary.runCount ?? 0); + } + + async getSessionSensorRunPage( + sessionId: string, + query: RuntimeHistoryQuery = {} + ): Promise> { + const page = await this.options.stateService.listTracePage(sessionId, { + ...query, + event: 'sensor.run', + }); + const items = page.items + .map((trace) => trace.data?.run) + .filter((run): run is HarnessSensorRun => Boolean(run && typeof run === 'object')); + return { + ...page, + items, + recordsReturned: items.length, + }; + } + + /** @deprecated Use getSessionSensorRunPage for history or getLatestSessionSensorRuns for status. */ + async getSessionSensorRuns(sessionId: string): Promise { + const runs: HarnessSensorRun[] = []; + let cursor: string | undefined; + do { + const page = await this.getSessionSensorRunPage(sessionId, { + limit: 1000, + cursor, + direction: 'oldest', + }); + runs.push(...page.items); + cursor = page.nextCursor; + } while (cursor); + return runs; + } + evaluateBackpressure( runs: HarnessSensorRun[], policy: HarnessBackpressurePolicy = {} diff --git a/src/harness/application/workflow/harnessSessionFacade.ts b/src/harness/application/workflow/harnessSessionFacade.ts index 624e1a28..7f320b6d 100644 --- a/src/harness/application/workflow/harnessSessionFacade.ts +++ b/src/harness/application/workflow/harnessSessionFacade.ts @@ -144,7 +144,7 @@ export class HarnessSessionFacade { const binding = await this.ensureHarnessSession(workflowName); const session = await this.runtimeStateService.getSession(binding.sessionId); - const allSensorRuns = await this.sensorsService.getSessionSensorRuns(binding.sessionId); + const allSensorRuns = await this.sensorsService.getLatestSessionSensorRuns(binding.sessionId); const policyRules = await this.policyService.listRules(); const latestRuns = new Map(); for (const run of allSensorRuns) { diff --git a/src/mcp/server/mcpServer.ts b/src/mcp/server/mcpServer.ts index 0e0bf5d8..0fe415a8 100644 --- a/src/mcp/server/mcpServer.ts +++ b/src/mcp/server/mcpServer.ts @@ -623,11 +623,11 @@ Actions: - evaluateTask: Evaluate task completion (params: taskId, sessionId?) - createHandoff: Create handoff contract (params: from, to, sessionId?, taskId?, artifacts?, evidence?) - listHandoffs: List handoff contracts -- replaySession: Replay a durable session timeline (params: sessionId, includePayloads?, maxEvents?) -- listReplays: List generated replays (params: sessionId?) +- replaySession: Replay a durable session timeline (params: sessionId, includePayloads?, maxEvents?, maxBytes?, cursor?) +- listReplays: List generated replay summaries (params: sessionId?, limit?, maxBytes?, cursor?) - getReplay: Get replay by id (params: replayId) -- buildDataset: Build a failure dataset from sessions (params: sessionIds?, includeSuccessfulSessions?) -- listDatasets: List failure datasets +- buildDataset: Build a failure dataset from sessions (params: sessionIds?, includeSuccessfulSessions?, concurrency?, maxFailures?, maxFailureBytes?, maxBytes?) +- listDatasets: List failure dataset summaries (params: limit?, maxBytes?, cursor?) - getDataset: Get failure dataset by id (params: datasetId) - getFailureClusters: Get clusters for a dataset (params: datasetId) - registerPolicy: Register policy rule (params: scope, effect, target?, pattern?, pathPattern?, risk?, description?) @@ -710,9 +710,18 @@ Actions: replayId: z.string().optional(), includePayloads: z.boolean().optional(), maxEvents: z.number().optional(), + maxBytes: z.number().optional(), + cursor: z.string().optional(), + limit: z.number().optional(), + direction: z.enum(['oldest', 'newest']).optional(), + createdAfter: z.string().optional(), + createdBefore: z.string().optional(), datasetId: z.string().optional(), sessionIds: z.array(z.string()).optional(), includeSuccessfulSessions: z.boolean().optional(), + concurrency: z.number().optional(), + maxFailures: z.number().optional(), + maxFailureBytes: z.number().optional(), scope: z.enum(['sensor', 'artifact', 'handoff', 'workflow', 'task', 'risk']).optional(), effect: z.enum(['allow', 'deny', 'require_approval']).optional(), target: z.enum(['tool', 'action', 'path', 'risk']).optional(), From d3317bacfd4a54fbe676b8edc5b9bda5c6f79e62 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:19:20 -0300 Subject: [PATCH 34/39] fix: recover orphaned hook store locks --- CHANGELOG.md | 2 +- .../shared/__tests__/hookSessionStore.test.ts | 90 +++++++++++ src/integrations/shared/hookSessionStore.ts | 145 +++++++++++++++++- 3 files changed, 233 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a06c91ca..935e2d82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, raw directory-entry scan budgets, and safe runtime configuration clamps. - Moved checkpoint payload history from `session.json` into individually bounded, paginated checkpoint records with summary-only session reads, incremental counts, legacy dual-read, and lazy migration. -- Made host-session binding mutations atomic across concurrent hooks and prevented terminal MCP activity sessions from being reused. +- Made host-session binding mutations atomic across concurrent hooks, with owner-identified inter-process locks that safely recover after a crashed hook, and prevented terminal MCP activity sessions from being reused. ## [1.1.1] - 2026-06-27 diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 4a6348aa..de99091a 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -1,6 +1,9 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; +import { promises as nativeFs } from 'fs'; +import { randomUUID } from 'crypto'; +import { spawn } from 'child_process'; import { createHarnessHookAdapter } from '../../../harness'; import { @@ -137,4 +140,91 @@ describe('hookSessionStore', () => { expect(bindings).toHaveLength(30); expect(await fs.pathExists(`${storePath}.lock`)).toBe(false); }); + + it('reclaims an aged lock whose owner process crashed', async () => { + const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); + const lockPath = `${storePath}.lock`; + await fs.ensureDir(path.dirname(lockPath)); + const childScript = [ + "const fs = require('fs');", + "const { randomUUID } = require('crypto');", + 'const lockPath = process.argv[1];', + 'fs.writeFileSync(lockPath, JSON.stringify({', + ' version: 1,', + ' pid: process.pid,', + ' token: randomUUID(),', + ' createdAt: Date.now() - 60000', + '}));', + 'process.exit(73);', + ].join('\n'); + const child = spawn(process.execPath, ['-e', childScript, lockPath], { stdio: 'ignore' }); + await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('exit', () => resolve()); + }); + expect(await fs.pathExists(lockPath)).toBe(true); + + const now = new Date().toISOString(); + await saveHookHarnessSession({ + repoPath: tempDir, + source: 'codex', + hostSessionId: 'after-crash', + harnessSessionId: 'replacement-session', + createdAt: now, + updatedAt: now, + }); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'codex', + hostSessionId: 'after-crash', + })).toBe('replacement-session'); + expect(await fs.pathExists(lockPath)).toBe(false); + }); + + it('does not unlink a replacement lock with a different inode and token', async () => { + const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); + const lockPath = `${storePath}.lock`; + await fs.outputJson(storePath, { bindings: {} }); + let unblockRead!: () => void; + const readUnblocked = new Promise(resolve => { unblockRead = resolve; }); + let lockAcquired!: () => void; + const acquired = new Promise(resolve => { lockAcquired = resolve; }); + const fsExtraModule = require('fs-extra') as typeof fs; + const originalReadJson = fsExtraModule.readJson.bind(fsExtraModule); + let blocked = false; + const readSpy = jest.spyOn(fsExtraModule, 'readJson').mockImplementation(async (...args: Parameters) => { + if (!blocked && path.resolve(String(args[0])) === storePath) { + blocked = true; + lockAcquired(); + await readUnblocked; + } + return originalReadJson(...args); + }); + + const now = new Date().toISOString(); + const saving = saveHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'replacement-race', + harnessSessionId: 'replacement-race-session', + createdAt: now, + updatedAt: now, + }); + await acquired; + const replacement = { + version: 1, + pid: process.pid, + token: randomUUID(), + createdAt: Date.now(), + }; + await nativeFs.unlink(lockPath); + await nativeFs.writeFile(lockPath, JSON.stringify(replacement), 'utf8'); + unblockRead(); + await saving; + readSpy.mockRestore(); + + expect(await fs.readJson(lockPath)).toEqual(replacement); + await nativeFs.unlink(lockPath); + }); }); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 5a12ece4..1c95a79b 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -27,6 +27,21 @@ interface HookSessionStoreDocument { const mutationTails = new Map>(); const LOCK_WAIT_MS = 10_000; const LOCK_RETRY_MS = 20; +const LOCK_STALE_MS = 5_000; + +interface HookSessionLockOwner { + version: 1; + pid: number; + token: string; + createdAt: number; +} + +interface HookSessionLockSnapshot { + owner?: HookSessionLockOwner; + device: number; + inode: number; + mtimeMs: number; +} export interface HookSessionPruneResult { removedExpired: number; @@ -86,17 +101,118 @@ async function writeStore(repoPath: string, document: HookSessionStoreDocument): } } +function parseLockOwner(value: string): HookSessionLockOwner | undefined { + try { + const candidate = JSON.parse(value) as Partial; + if ( + candidate.version !== 1 + || !Number.isSafeInteger(candidate.pid) + || (candidate.pid ?? 0) <= 0 + || typeof candidate.token !== 'string' + || !/^[0-9a-f-]{36}$/i.test(candidate.token) + || !Number.isFinite(candidate.createdAt) + || (candidate.createdAt ?? 0) <= 0 + ) return undefined; + return candidate as HookSessionLockOwner; + } catch { + return undefined; + } +} + +async function readLockSnapshot(lockPath: string): Promise { + const handle = await nativeFs.open(lockPath, 'r'); + try { + const [stat, content] = await Promise.all([ + handle.stat(), + handle.readFile('utf8'), + ]); + return { + owner: parseLockOwner(content), + device: stat.dev, + inode: stat.ino, + mtimeMs: stat.mtimeMs, + }; + } finally { + await handle.close().catch(() => undefined); + } +} + +function sameLock(left: HookSessionLockSnapshot, right: HookSessionLockSnapshot): boolean { + return left.device === right.device + && left.inode === right.inode + && left.owner?.token === right.owner?.token + && left.owner?.pid === right.owner?.pid + && left.owner?.createdAt === right.owner?.createdAt; +} + +function processIsAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code !== 'ESRCH'; + } +} + +async function reclaimStaleLock(lockPath: string): Promise { + let observed: HookSessionLockSnapshot; + try { + observed = await readLockSnapshot(lockPath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true; + return false; + } + + const createdAt = observed.owner?.createdAt ?? observed.mtimeMs; + if (Date.now() - createdAt < LOCK_STALE_MS) return false; + if (observed.owner && processIsAlive(observed.owner.pid)) return false; + + // Re-open immediately before unlinking. Both inode and the unguessable + // owner token must still match, so a replacement lock is never removed on + // the basis of an earlier stale observation. + let current: HookSessionLockSnapshot; + try { + current = await readLockSnapshot(lockPath); + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'ENOENT'; + } + if (!sameLock(observed, current)) return false; + + try { + await nativeFs.unlink(lockPath); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'ENOENT'; + } +} + +async function releaseOwnedLock( + lockPath: string, + owned: HookSessionLockSnapshot, +): Promise { + let current: HookSessionLockSnapshot; + try { + current = await readLockSnapshot(lockPath); + } catch { + return; + } + if (!sameLock(owned, current)) return; + await nativeFs.unlink(lockPath).catch(() => undefined); +} + async function withInterProcessLock(storePath: string, operation: () => Promise): Promise { const lockPath = `${storePath}.lock`; await fs.ensureDir(path.dirname(lockPath)); const deadline = Date.now() + LOCK_WAIT_MS; let handle: Awaited> | undefined; + const token = randomUUID(); while (!handle) { try { handle = await nativeFs.open(lockPath, 'wx'); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + if (await reclaimStaleLock(lockPath)) continue; if (Date.now() >= deadline) { throw new Error(`Timed out waiting for hook session store lock: ${path.basename(storePath)}`); } @@ -104,19 +220,42 @@ async function withInterProcessLock(storePath: string, operation: () => Promi } } + const owner: HookSessionLockOwner = { + version: 1, + pid: process.pid, + token, + createdAt: Date.now(), + }; try { - await handle.writeFile(JSON.stringify({ pid: process.pid, createdAt: Date.now() }), 'utf8'); + await handle.writeFile(JSON.stringify(owner), 'utf8'); + await handle.sync(); } catch (error) { + const stat = await handle.stat().catch(() => undefined); await handle.close().catch(() => undefined); - await nativeFs.unlink(lockPath).catch(() => undefined); + if (stat) { + await releaseOwnedLock(lockPath, { + owner, + device: stat.dev, + inode: stat.ino, + mtimeMs: stat.mtimeMs, + }); + } throw error; } + const stat = await handle.stat(); + const owned: HookSessionLockSnapshot = { + owner, + device: stat.dev, + inode: stat.ino, + mtimeMs: stat.mtimeMs, + }; + try { return await operation(); } finally { await handle.close().catch(() => undefined); - await nativeFs.unlink(lockPath).catch(() => undefined); + await releaseOwnedLock(lockPath, owned); } } From 35a8f40a95afec61d56148a6cb3dec530179d38a Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:19:41 -0300 Subject: [PATCH 35/39] fix: recover orphaned trace takeovers --- CHANGELOG.md | 2 +- .../__tests__/runtimeStateService.test.ts | 102 ++++++++++ .../out/runtimeState/runtimeStateService.ts | 189 ++++++++++++++++-- 3 files changed, 270 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7221fdc9..d438368b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Redacted Bash credentials across header, JSON, assignment, camel-case, and flag forms, omitting ambiguous command tails rather than risking secret disclosure. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. -- Made stale trace-lock takeover verify process ownership, token, device, and inode across competing processes; same-millisecond rotations now use a monotonic segment sequence. +- Made stale trace-lock takeover verify process ownership, token, device, and inode across competing processes, and recover orphaned takeover elections after a reaper crash; same-millisecond rotations now use a monotonic segment sequence. - Kept the active rotation threshold and individual events within the configured per-session trace quota, including contradictory configurations and a single oversized event. ## [1.1.1] - 2026-06-27 diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index cff9e083..7aad2522 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -220,6 +220,108 @@ describe('HarnessRuntimeStateService', () => { expect(await fs.pathExists(`${lockFile}.takeover`)).toBe(false); }, 30_000); + it('recovers when a takeover owner crashes after publishing its election identity', async () => { + const session = await service.createSession({ name: 'orphaned-takeover-race' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const lockFile = path.join(sessionDir, 'trace.jsonl.lock'); + const takeoverFile = `${lockFile}.takeover`; + await fs.writeJson(lockFile, { + pid: 999999, + token: 'stale-target-token', + createdAt: '2000-01-01T00:00:00.000Z', + }); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + const moduleUrl = pathToFileURL(path.resolve(__dirname, '../runtimeStateService.ts')).href; + const holderScript = ` + const fs = require('fs'); + const originalLink = fs.promises.link.bind(fs.promises); + fs.promises.link = async (source, destination) => { + await originalLink(source, destination); + if (destination.endsWith('.takeover')) { + process.stdout.write('TAKEOVER_READY\\n'); + await new Promise(() => {}); + } + }; + (async () => { + const loaded = await import(${JSON.stringify(moduleUrl)}); + const Runtime = loaded.HarnessRuntimeStateService ?? loaded.default?.HarnessRuntimeStateService; + await new Runtime({ repoPath: process.argv[1] }).appendTrace(process.argv[2], { + level: 'info', event: 'holder.event', message: 'must-not-complete' + }); + })().catch((error) => { console.error(error); process.exitCode = 1; }); + `; + const holder = spawn(process.execPath, ['--import', 'tsx', '-e', holderScript, tempDir, session.id], { + cwd: path.resolve(__dirname, '../../../../../..'), + stdio: ['ignore', 'pipe', 'pipe'], + }); + await new Promise((resolve, reject) => { + let stdout = ''; + let stderr = ''; + holder.stdout.setEncoding('utf8'); + holder.stderr.setEncoding('utf8'); + holder.stdout.on('data', (chunk) => { + stdout += chunk; + if (stdout.includes('TAKEOVER_READY')) resolve(); + }); + holder.stderr.on('data', (chunk) => { stderr += chunk; }); + holder.once('error', reject); + holder.once('exit', (code) => reject(new Error(`takeover holder exited early (${code}): ${stderr}`))); + }); + const holderPid = holder.pid; + holder.kill('SIGKILL'); + await new Promise((resolve) => holder.once('exit', () => resolve())); + + const orphaned = await fs.readJson(takeoverFile) as Record; + expect(orphaned).toMatchObject({ + pid: holderPid, + token: expect.any(String), + createdAt: expect.any(String), + inode: expect.any(String), + device: expect.any(String), + target: { + token: 'stale-target-token', + inode: expect.any(String), + device: expect.any(String), + }, + }); + await fs.utimes(takeoverFile, old, old); + + const writerScript = ` + (async () => { + const loaded = await import(${JSON.stringify(moduleUrl)}); + const Runtime = loaded.HarnessRuntimeStateService ?? loaded.default?.HarnessRuntimeStateService; + await new Runtime({ repoPath: process.argv[1] }).appendTrace(process.argv[2], { + level: 'info', event: 'recovered.worker', message: 'worker-' + process.argv[3], + data: { worker: Number(process.argv[3]) } + }); + })().catch((error) => { console.error(error); process.exitCode = 1; }); + `; + const runWriter = (index: number): Promise => new Promise((resolve, reject) => { + const child = spawn(process.execPath, ['--import', 'tsx', '-e', writerScript, tempDir, session.id, String(index)], { + cwd: path.resolve(__dirname, '../../../../../..'), + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.once('error', reject); + child.once('exit', (code) => code === 0 ? resolve() : reject(new Error(`writer ${index} failed: ${stderr}`))); + }); + await Promise.all(Array.from({ length: 8 }, (_, index) => runWriter(index))); + + const traceText = await fs.readFile(path.join(sessionDir, 'trace.jsonl'), 'utf8'); + expect(() => traceText.trim().split('\n').forEach((line) => JSON.parse(line))).not.toThrow(); + const traces = await service.listTraces(session.id); + const recovered = traces.filter((trace) => trace.event === 'recovered.worker'); + expect(recovered).toHaveLength(8); + expect(new Set(recovered.map((trace) => trace.data?.worker)).size).toBe(8); + expect(traces.some((trace) => trace.event === 'holder.event')).toBe(false); + expect((await fs.readdir(sessionDir)).filter((entry) => entry.includes('.takeover'))).toEqual([]); + expect(await fs.pathExists(lockFile)).toBe(false); + }, 30_000); + it('uses monotonic segment sequences for same-millisecond rotation and pruning', async () => { await fs.outputJson(path.join(tempDir, '.context', 'config', 'hooks.json'), { trace: { diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index f725b37e..ebdd6c69 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -34,6 +34,29 @@ interface TraceFileLock extends TraceLockIdentity { device: bigint | number; } +interface TraceLockSnapshot extends TraceLockIdentity { + inode: bigint | number; + device: bigint | number; + mtimeMs: number; +} + +interface TraceTakeoverDocument extends TraceLockIdentity { + createdAt: string; + inode: string; + device: string; + target: { + inode: string; + device: string; + token: string; + }; +} + +interface TraceTakeoverSnapshot extends TraceTakeoverDocument { + actualInode: bigint | number; + actualDevice: bigint | number; + mtimeMs: number; +} + function waitForLock(milliseconds: number): Promise { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } @@ -83,18 +106,49 @@ async function sameLockIdentity( } } -async function tryTakeOverStaleTraceLock(lockFile: string): Promise { - const takeoverFile = `${lockFile}.takeover`; +async function readTraceLockSnapshot(lockFile: string): Promise { try { - // link(2) is the atomic election: exactly one waiter creates the fixed - // takeover name, and the hard link pins the inode it inspected. - await nodeFs.link(lockFile, takeoverFile); - } catch (error) { - const code = (error as NodeJS.ErrnoException).code; - if (code === 'EEXIST' || code === 'ENOENT') return false; - throw error; + const handle = await nodeFs.open(lockFile, 'r'); + try { + const [stat, contents] = await Promise.all([ + handle.stat({ bigint: true }), + handle.readFile('utf8'), + ]); + return { + ...parseTraceLockIdentity(contents), + inode: stat.ino, + device: stat.dev, + mtimeMs: Number(stat.mtimeMs), + }; + } finally { + await handle.close(); + } + } catch { + return undefined; } +} +function parseTraceTakeoverDocument(value: string): TraceTakeoverDocument | undefined { + try { + const parsed = JSON.parse(value) as Partial; + if ( + typeof parsed.pid !== 'number' + || typeof parsed.token !== 'string' + || typeof parsed.createdAt !== 'string' + || typeof parsed.inode !== 'string' + || typeof parsed.device !== 'string' + || !parsed.target + || typeof parsed.target.inode !== 'string' + || typeof parsed.target.device !== 'string' + || typeof parsed.target.token !== 'string' + ) return undefined; + return parsed as TraceTakeoverDocument; + } catch { + return undefined; + } +} + +async function readTraceTakeoverSnapshot(takeoverFile: string): Promise { try { const handle = await nodeFs.open(takeoverFile, 'r'); try { @@ -102,23 +156,113 @@ async function tryTakeOverStaleTraceLock(lockFile: string): Promise { handle.stat({ bigint: true }), handle.readFile('utf8'), ]); - const identity = parseTraceLockIdentity(contents); - const age = Date.now() - Number(stat.mtimeMs); - const observed = { inode: stat.ino, device: stat.dev, token: identity.token }; - if (age <= TRACE_LOCK_STALE_MS || isProcessAlive(identity.pid)) return false; - if (!(await sameLockIdentity(lockFile, observed))) return false; - // No second reaper can race this unlink while the fixed takeover link - // exists, and a dead owner cannot replace its own inode/token. - await nodeFs.unlink(lockFile); - return true; + const document = parseTraceTakeoverDocument(contents); + if (!document || document.inode !== String(stat.ino) || document.device !== String(stat.dev)) return undefined; + return { + ...document, + actualInode: stat.ino, + actualDevice: stat.dev, + mtimeMs: Number(stat.mtimeMs), + }; } finally { await handle.close(); } - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; - return false; + } catch { + return undefined; + } +} + +async function sameTakeoverIdentity(file: string, expected: TraceTakeoverSnapshot): Promise { + const current = await readTraceTakeoverSnapshot(file); + return current !== undefined + && current.actualInode === expected.actualInode + && current.actualDevice === expected.actualDevice + && current.token === expected.token; +} + +function takeoverCandidateFile(takeoverFile: string, pid: number, token: string): string { + return `${takeoverFile}.${pid}.${token}.candidate`; +} + +async function publishTraceTakeover( + takeoverFile: string, + target: TraceLockSnapshot +): Promise { + const token = randomUUID(); + const candidateFile = takeoverCandidateFile(takeoverFile, process.pid, token); + let handle: FileHandle | undefined; + try { + handle = await nodeFs.open(candidateFile, 'wx'); + const stat = await handle.stat({ bigint: true }); + const document: TraceTakeoverDocument = { + pid: process.pid, + token, + createdAt: new Date().toISOString(), + inode: String(stat.ino), + device: String(stat.dev), + target: { + inode: String(target.inode), + device: String(target.device), + token: target.token, + }, + }; + await handle.writeFile(JSON.stringify(document), 'utf8'); + await handle.sync(); + try { + // Publish a fully-written identity atomically. The candidate and fixed + // election name refer to the same inode, so a crash cannot expose a + // partially initialized takeover owner. + await nodeFs.link(candidateFile, takeoverFile); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'EEXIST' || code === 'ENOENT') return undefined; + throw error; + } + return readTraceTakeoverSnapshot(takeoverFile); } finally { - await nodeFs.unlink(takeoverFile).catch(() => undefined); + await handle?.close().catch(() => undefined); + await nodeFs.unlink(candidateFile).catch(() => undefined); + } +} + +async function recoverOrphanedTraceTakeover(takeoverFile: string): Promise { + const takeover = await readTraceTakeoverSnapshot(takeoverFile); + if (!takeover) return false; + const age = Date.now() - takeover.mtimeMs; + if (age <= TRACE_LOCK_STALE_MS || isProcessAlive(takeover.pid)) return false; + if (!(await sameTakeoverIdentity(takeoverFile, takeover))) return false; + + const candidateFile = takeoverCandidateFile(takeoverFile, takeover.pid, takeover.token); + if (await sameTakeoverIdentity(candidateFile, takeover)) { + await nodeFs.unlink(candidateFile).catch(() => undefined); + } + // Revalidate immediately before removal: a waiter that inspected an old + // election must not unlink a replacement published under the fixed name. + if (!(await sameTakeoverIdentity(takeoverFile, takeover))) return false; + await nodeFs.unlink(takeoverFile).catch(() => undefined); + return true; +} + +async function tryTakeOverStaleTraceLock(lockFile: string): Promise { + const takeoverFile = `${lockFile}.takeover`; + const target = await readTraceLockSnapshot(lockFile); + if (!target || Date.now() - target.mtimeMs <= TRACE_LOCK_STALE_MS || isProcessAlive(target.pid)) return false; + const takeover = await publishTraceTakeover(takeoverFile, target); + if (!takeover) return false; + + try { + if (!(await sameTakeoverIdentity(takeoverFile, takeover))) return false; + if (!(await sameLockIdentity(lockFile, { + inode: target.inode, + device: target.device, + token: target.token, + }))) return false; + await nodeFs.unlink(lockFile); + return true; + } finally { + if (await sameTakeoverIdentity(takeoverFile, takeover)) { + await nodeFs.unlink(takeoverFile).catch(() => undefined); + } } } @@ -128,6 +272,7 @@ async function acquireTraceFileLock(traceFile: string): Promise { const deadline = Date.now() + 10_000; while (true) { if (await nodeFs.stat(takeoverFile).then(() => true).catch(() => false)) { + if (await recoverOrphanedTraceTakeover(takeoverFile)) continue; if (Date.now() >= deadline) { throw new Error(`Timed out waiting for trace lock takeover: ${path.basename(traceFile)}`); } From 5806484b0699d45f18be8a6328a9263765444803 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sat, 11 Jul 2026 18:24:42 -0300 Subject: [PATCH 36/39] fix: recover legacy trace takeovers --- CHANGELOG.md | 2 +- .../__tests__/runtimeStateService.test.ts | 96 +++++++++++++++++++ .../out/runtimeState/runtimeStateService.ts | 76 +++++++++++++-- 3 files changed, 165 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d438368b..69c21a28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Redacted Bash credentials across header, JSON, assignment, camel-case, and flag forms, omitting ambiguous command tails rather than risking secret disclosure. - Kept oversized hook stdin non-blocking without concatenating or echoing rejected input, while recording a bounded failure diagnostic. - Added a generic serialized trace-event guard and atomic per-session trace rotation with chronological legacy-compatible reads. -- Made stale trace-lock takeover verify process ownership, token, device, and inode across competing processes, and recover orphaned takeover elections after a reaper crash; same-millisecond rotations now use a monotonic segment sequence. +- Made stale trace-lock takeover verify process ownership, token, device, and inode across competing processes, recover both current and legacy orphaned takeover elections after a reaper crash, and preserve live or replaced owners; same-millisecond rotations now use a monotonic segment sequence. - Kept the active rotation threshold and individual events within the configured per-session trace quota, including contradictory configurations and a single oversized event. ## [1.1.1] - 2026-06-27 diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 7aad2522..3d028a3a 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -2,6 +2,7 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { spawn } from 'child_process'; +import { promises as nodeFs } from 'fs'; import { pathToFileURL } from 'url'; import { HarnessRuntimeStateService, @@ -220,6 +221,101 @@ describe('HarnessRuntimeStateService', () => { expect(await fs.pathExists(`${lockFile}.takeover`)).toBe(false); }, 30_000); + it('recovers an aged legacy takeover hardlink owned by a dead process', async () => { + const session = await service.createSession({ name: 'legacy-takeover' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const lockFile = path.join(sessionDir, 'trace.jsonl.lock'); + const takeoverFile = `${lockFile}.takeover`; + await fs.writeJson(lockFile, { + pid: 999999, + token: 'legacy-dead-token', + createdAt: '2000-01-01T00:00:00.000Z', + }); + await fs.link(lockFile, takeoverFile); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + await expect(service.appendTrace(session.id, { + level: 'info', event: 'legacy.recovered', message: 'continued safely', + })).resolves.toMatchObject({ event: 'legacy.recovered' }); + expect(await fs.pathExists(lockFile)).toBe(false); + expect(await fs.pathExists(takeoverFile)).toBe(false); + }); + + it('does not steal an aged legacy takeover while its owner is alive', async () => { + const session = await service.createSession({ name: 'legacy-live-owner' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const lockFile = path.join(sessionDir, 'trace.jsonl.lock'); + const takeoverFile = `${lockFile}.takeover`; + const identity = { + pid: process.pid, + token: 'legacy-live-token', + createdAt: '2000-01-01T00:00:00.000Z', + }; + await fs.writeJson(lockFile, identity); + await fs.link(lockFile, takeoverFile); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + const pending = service.appendTrace(session.id, { + level: 'info', event: 'after.live.legacy', message: 'waited for owner', + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await fs.readJson(takeoverFile)).toEqual(identity); + + await fs.unlink(takeoverFile); + await fs.unlink(lockFile); + await expect(pending).resolves.toMatchObject({ event: 'after.live.legacy' }); + }); + + it('preserves a replacement takeover published during legacy recovery', async () => { + const session = await service.createSession({ name: 'legacy-replacement-race' }); + const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); + const lockFile = path.join(sessionDir, 'trace.jsonl.lock'); + const takeoverFile = `${lockFile}.takeover`; + await fs.writeJson(lockFile, { + pid: 999999, + token: 'legacy-replaced-token', + createdAt: '2000-01-01T00:00:00.000Z', + }); + await fs.link(lockFile, takeoverFile); + const old = new Date(Date.now() - 120_000); + await fs.utimes(lockFile, old, old); + + const replacement = { + pid: process.pid, + token: 'live-replacement-token', + createdAt: new Date().toISOString(), + }; + let takeoverOpens = 0; + let publishReplacement!: () => void; + const replacementPublished = new Promise((resolve) => { publishReplacement = resolve; }); + const originalOpen = nodeFs.open.bind(nodeFs); + const openSpy = jest.spyOn(nodeFs, 'open').mockImplementation(async (...args: Parameters) => { + if (String(args[0]) === takeoverFile && ++takeoverOpens === 2) { + const replacementFile = `${takeoverFile}.replacement`; + await fs.writeJson(replacementFile, replacement); + await fs.rename(replacementFile, takeoverFile); + publishReplacement(); + } + return originalOpen(...args); + }); + + const pending = service.appendTrace(session.id, { + level: 'info', event: 'after.replacement.race', message: 'replacement survived', + }); + try { + await replacementPublished; + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(await fs.readJson(takeoverFile)).toEqual(replacement); + } finally { + openSpy.mockRestore(); + await fs.unlink(takeoverFile).catch(() => undefined); + await fs.unlink(lockFile).catch(() => undefined); + } + await expect(pending).resolves.toMatchObject({ event: 'after.replacement.race' }); + }); + it('recovers when a takeover owner crashes after publishing its election identity', async () => { const session = await service.createSession({ name: 'orphaned-takeover-race' }); const sessionDir = path.join(tempDir, '.context', 'runtime', 'sessions', session.id); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index ebdd6c69..76ed1e1a 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -25,6 +25,7 @@ const ROTATION_EVENT_RESERVE_BYTES = 2 * 1024; interface TraceLockIdentity { pid: number; token: string; + createdAt?: string; } interface TraceFileLock extends TraceLockIdentity { @@ -51,12 +52,23 @@ interface TraceTakeoverDocument extends TraceLockIdentity { }; } -interface TraceTakeoverSnapshot extends TraceTakeoverDocument { +interface CurrentTraceTakeoverSnapshot extends TraceTakeoverDocument { + format: 'current'; actualInode: bigint | number; actualDevice: bigint | number; mtimeMs: number; } +interface LegacyTraceTakeoverSnapshot extends TraceLockIdentity { + format: 'legacy'; + createdAt: string; + actualInode: bigint | number; + actualDevice: bigint | number; + mtimeMs: number; +} + +type TraceTakeoverSnapshot = CurrentTraceTakeoverSnapshot | LegacyTraceTakeoverSnapshot; + function waitForLock(milliseconds: number): Promise { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } @@ -77,6 +89,7 @@ function parseTraceLockIdentity(value: string): TraceLockIdentity { return { pid: typeof parsed.pid === 'number' ? parsed.pid : Number.NaN, token: typeof parsed.token === 'string' ? parsed.token : '', + createdAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : undefined, }; } catch { // Preserve takeover compatibility with locks written by the first F-02 @@ -87,7 +100,13 @@ function parseTraceLockIdentity(value: string): TraceLockIdentity { async function sameLockIdentity( file: string, - expected: { inode: bigint | number; device: bigint | number; token: string } + expected: { + inode: bigint | number; + device: bigint | number; + token: string; + pid?: number; + createdAt?: string; + } ): Promise { try { const handle = await nodeFs.open(file, 'r'); @@ -97,7 +116,11 @@ async function sameLockIdentity( handle.readFile('utf8'), ]); const identity = parseTraceLockIdentity(contents); - return stat.ino === expected.inode && stat.dev === expected.device && identity.token === expected.token; + return stat.ino === expected.inode + && stat.dev === expected.device + && identity.token === expected.token + && (expected.pid === undefined || identity.pid === expected.pid) + && (expected.createdAt === undefined || identity.createdAt === expected.createdAt); } finally { await handle.close(); } @@ -157,9 +180,22 @@ async function readTraceTakeoverSnapshot(takeoverFile: string): Promise { const current = await readTraceTakeoverSnapshot(file); return current !== undefined + && current.format === expected.format && current.actualInode === expected.actualInode && current.actualDevice === expected.actualDevice - && current.token === expected.token; + && current.pid === expected.pid + && current.token === expected.token + && current.createdAt === expected.createdAt; } function takeoverCandidateFile(takeoverFile: string, pid: number, token: string): string { @@ -187,7 +226,7 @@ function takeoverCandidateFile(takeoverFile: string, pid: number, token: string) async function publishTraceTakeover( takeoverFile: string, target: TraceLockSnapshot -): Promise { +): Promise { const token = randomUUID(); const candidateFile = takeoverCandidateFile(takeoverFile, process.pid, token); let handle: FileHandle | undefined; @@ -218,7 +257,8 @@ async function publishTraceTakeover( if (code === 'EEXIST' || code === 'ENOENT') return undefined; throw error; } - return readTraceTakeoverSnapshot(takeoverFile); + const published = await readTraceTakeoverSnapshot(takeoverFile); + return published?.format === 'current' ? published : undefined; } finally { await handle?.close().catch(() => undefined); await nodeFs.unlink(candidateFile).catch(() => undefined); @@ -232,6 +272,26 @@ async function recoverOrphanedTraceTakeover(takeoverFile: string): Promise undefined); + return true; + } + const candidateFile = takeoverCandidateFile(takeoverFile, takeover.pid, takeover.token); if (await sameTakeoverIdentity(candidateFile, takeover)) { await nodeFs.unlink(candidateFile).catch(() => undefined); From 0209c7fef772bdc9064ab47c81bdf6c6b488eaa0 Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sun, 12 Jul 2026 10:15:44 -0300 Subject: [PATCH 37/39] fix: preserve live legacy hook locks --- CHANGELOG.md | 2 +- .../shared/__tests__/hookSessionStore.test.ts | 83 ++++++++++++++++++- src/integrations/shared/hookSessionStore.ts | 45 +++++++--- 3 files changed, 114 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 935e2d82..41b3b76f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Bounded semantic, file-analysis, MCP-session, and host-session retention with TTL/LRU limits, proactive cleanup, raw directory-entry scan budgets, and safe runtime configuration clamps. - Moved checkpoint payload history from `session.json` into individually bounded, paginated checkpoint records with summary-only session reads, incremental counts, legacy dual-read, and lazy migration. -- Made host-session binding mutations atomic across concurrent hooks, with owner-identified inter-process locks that safely recover after a crashed hook, and prevented terminal MCP activity sessions from being reused. +- Made host-session binding mutations atomic across concurrent hooks, with owner-identified inter-process locks that safely recover after a crashed hook, preserve live legacy locks during rolling upgrades, and prevent terminal MCP activity sessions from being reused. ## [1.1.1] - 2026-06-27 diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index de99091a..e4cdda4a 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -2,7 +2,6 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; import { promises as nativeFs } from 'fs'; -import { randomUUID } from 'crypto'; import { spawn } from 'child_process'; import { createHarnessHookAdapter } from '../../../harness'; @@ -182,7 +181,85 @@ describe('hookSessionStore', () => { expect(await fs.pathExists(lockPath)).toBe(false); }); - it('does not unlink a replacement lock with a different inode and token', async () => { + it('reads and recovers an aged legacy lock after its owner exits', async () => { + const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); + const lockPath = `${storePath}.lock`; + await fs.ensureDir(path.dirname(lockPath)); + const childScript = [ + "const fs = require('fs');", + 'const lockPath = process.argv[1];', + 'fs.writeFileSync(lockPath, JSON.stringify({', + ' pid: process.pid,', + ' createdAt: Date.now() - 60000', + '}));', + 'process.exit(74);', + ].join('\n'); + const child = spawn(process.execPath, ['-e', childScript, lockPath], { stdio: 'ignore' }); + await new Promise((resolve, reject) => { + child.once('error', reject); + child.once('exit', () => resolve()); + }); + + const now = new Date().toISOString(); + await saveHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'legacy-after-crash', + harnessSessionId: 'legacy-replacement-session', + createdAt: now, + updatedAt: now, + }); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'legacy-after-crash', + })).toBe('legacy-replacement-session'); + expect(await fs.pathExists(lockPath)).toBe(false); + }); + + it('does not steal an aged legacy lock from a live process and times out safely', async () => { + const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); + const lockPath = `${storePath}.lock`; + await fs.ensureDir(path.dirname(lockPath)); + const childScript = [ + "const fs = require('fs');", + 'const lockPath = process.argv[1];', + 'fs.writeFileSync(lockPath, JSON.stringify({', + ' pid: process.pid,', + ' createdAt: Date.now() - 60000', + '}));', + "process.stdout.write('ready\\n');", + 'setInterval(() => {}, 1000);', + ].join('\n'); + const child = spawn(process.execPath, ['-e', childScript, lockPath], { + stdio: ['ignore', 'pipe', 'ignore'], + }); + await new Promise((resolve, reject) => { + child.once('error', reject); + child.stdout!.once('data', () => resolve()); + }); + const originalLock = await fs.readFile(lockPath, 'utf8'); + + try { + const now = new Date().toISOString(); + await expect(saveHookHarnessSession({ + repoPath: tempDir, + source: 'codex', + hostSessionId: 'must-time-out', + harnessSessionId: 'must-not-be-saved', + createdAt: now, + updatedAt: now, + })).rejects.toThrow('Timed out waiting for hook session store lock'); + expect(await fs.readFile(lockPath, 'utf8')).toBe(originalLock); + } finally { + child.kill('SIGKILL'); + await new Promise(resolve => child.once('exit', () => resolve())); + await fs.remove(lockPath); + } + }, 15_000); + + it('does not unlink a replacement legacy lock with a different inode and owner content', async () => { const storePath = path.join(tempDir, '.context', 'runtime', 'hooks', 'host-sessions.json'); const lockPath = `${storePath}.lock`; await fs.outputJson(storePath, { bindings: {} }); @@ -213,9 +290,7 @@ describe('hookSessionStore', () => { }); await acquired; const replacement = { - version: 1, pid: process.pid, - token: randomUUID(), createdAt: Date.now(), }; await nativeFs.unlink(lockPath); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 1c95a79b..9cb5a320 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -36,11 +36,20 @@ interface HookSessionLockOwner { createdAt: number; } +/** Lock shape written before owner tokens were introduced. */ +interface LegacyHookSessionLockOwner { + pid: number; + createdAt: number; +} + +type AnyHookSessionLockOwner = HookSessionLockOwner | LegacyHookSessionLockOwner; + interface HookSessionLockSnapshot { - owner?: HookSessionLockOwner; + owner?: AnyHookSessionLockOwner; device: number; inode: number; mtimeMs: number; + content: string; } export interface HookSessionPruneResult { @@ -101,17 +110,27 @@ async function writeStore(repoPath: string, document: HookSessionStoreDocument): } } -function parseLockOwner(value: string): HookSessionLockOwner | undefined { +function validLockPidAndTimestamp(candidate: { pid?: unknown; createdAt?: unknown }): boolean { + return Number.isSafeInteger(candidate.pid) + && (candidate.pid as number) > 0 + && Number.isFinite(candidate.createdAt) + && (candidate.createdAt as number) > 0; +} + +function parseLockOwner(value: string): AnyHookSessionLockOwner | undefined { try { const candidate = JSON.parse(value) as Partial; + if (!validLockPidAndTimestamp(candidate)) return undefined; + // Rolling-upgrade compatibility: the original lock document had only + // pid/createdAt. Preserve that owner identity so a live legacy process is + // never mistaken for an orphan. + if (candidate.version === undefined && candidate.token === undefined) { + return { pid: candidate.pid!, createdAt: candidate.createdAt! }; + } if ( candidate.version !== 1 - || !Number.isSafeInteger(candidate.pid) - || (candidate.pid ?? 0) <= 0 || typeof candidate.token !== 'string' || !/^[0-9a-f-]{36}$/i.test(candidate.token) - || !Number.isFinite(candidate.createdAt) - || (candidate.createdAt ?? 0) <= 0 ) return undefined; return candidate as HookSessionLockOwner; } catch { @@ -131,6 +150,7 @@ async function readLockSnapshot(lockPath: string): Promise undefined); @@ -140,7 +160,7 @@ async function readLockSnapshot(lockPath: string): Promise { if (Date.now() - createdAt < LOCK_STALE_MS) return false; if (observed.owner && processIsAlive(observed.owner.pid)) return false; - // Re-open immediately before unlinking. Both inode and the unguessable - // owner token must still match, so a replacement lock is never removed on - // the basis of an earlier stale observation. + // Re-open immediately before unlinking. Inode and the complete owner + // document (including the token for current-format locks) must still match, + // so a replacement is never removed from an earlier stale observation. let current: HookSessionLockSnapshot; try { current = await readLockSnapshot(lockPath); @@ -226,8 +246,9 @@ async function withInterProcessLock(storePath: string, operation: () => Promi token, createdAt: Date.now(), }; + const serializedOwner = JSON.stringify(owner); try { - await handle.writeFile(JSON.stringify(owner), 'utf8'); + await handle.writeFile(serializedOwner, 'utf8'); await handle.sync(); } catch (error) { const stat = await handle.stat().catch(() => undefined); @@ -238,6 +259,7 @@ async function withInterProcessLock(storePath: string, operation: () => Promi device: stat.dev, inode: stat.ino, mtimeMs: stat.mtimeMs, + content: serializedOwner, }); } throw error; @@ -249,6 +271,7 @@ async function withInterProcessLock(storePath: string, operation: () => Promi device: stat.dev, inode: stat.ino, mtimeMs: stat.mtimeMs, + content: serializedOwner, }; try { From e61f43127ba4a8b8191ab7bba030ad48104315bd Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Sun, 12 Jul 2026 16:01:29 -0300 Subject: [PATCH 38/39] fix: address follow-up review feedback --- .../__tests__/runtimeStateService.test.ts | 2 +- .../datasets/__tests__/datasetService.test.ts | 37 +++++++++++++++++++ .../application/datasets/datasetService.ts | 2 +- .../hooks/__tests__/hookTracePolicy.test.ts | 30 +++++++++++++++ .../application/hooks/hookTracePolicy.ts | 34 ++++++++--------- .../replay/__tests__/replayService.test.ts | 16 ++++++++ .../application/replay/replayService.ts | 15 +++----- 7 files changed, 107 insertions(+), 29 deletions(-) diff --git a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts index 87de456e..8b8509fc 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -317,5 +317,5 @@ describe('HarnessRuntimeStateService', () => { expect(files.length).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRIES); for (const file of files) expect((await fs.stat(path.join(summaryDir, file))).size).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRY_BYTES); expect(Object.keys((await service.getSensorSummary(session.id)).latestBySensor).length).toBeLessThanOrEqual(MAX_SENSOR_SUMMARY_ENTRIES); - }); + }, 15_000); }); diff --git a/src/harness/application/datasets/__tests__/datasetService.test.ts b/src/harness/application/datasets/__tests__/datasetService.test.ts index 761b5d07..e1eaf73d 100644 --- a/src/harness/application/datasets/__tests__/datasetService.test.ts +++ b/src/harness/application/datasets/__tests__/datasetService.test.ts @@ -182,4 +182,41 @@ describe('HarnessDatasetService', () => { expect((await fs.stat(file)).size).toBeLessThanOrEqual(4096); expect(await fs.pathExists(file.replace(/\.json$/, '.meta.json'))).toBe(true); }); + + it('falls back to legacy arrays when events predate event.record', async () => { + const session = await execution.createSession({ name: 'legacy-replay-shape' }); + const replayService = new HarnessReplayService({ repoPath: tempDir }); + const base = await replayService.buildReplay(session.id); + const legacyTrace = { + id: 'legacy-trace', + sessionId: session.id, + level: 'error' as const, + event: 'task.failed', + message: 'legacy failure', + createdAt: new Date().toISOString(), + }; + const legacyReplay = { + ...base, + events: [{ + id: legacyTrace.id, + sessionId: session.id, + createdAt: legacyTrace.createdAt, + source: 'trace' as const, + label: legacyTrace.event, + }], + traces: [legacyTrace], + } as any; + const legacyDataset = new HarnessDatasetService({ + repoPath: tempDir, + dependencies: { replayService: { buildReplay: async () => legacyReplay } }, + }); + + const dataset = await legacyDataset.buildFailureDataset({ + sessionIds: [session.id], + includeSuccessfulSessions: true, + }); + + expect(dataset.failureCount).toBe(1); + expect(dataset.failures[0]).toMatchObject({ kind: 'trace', message: 'legacy failure' }); + }); }); diff --git a/src/harness/application/datasets/datasetService.ts b/src/harness/application/datasets/datasetService.ts index 54d5ca68..064b8402 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -103,7 +103,7 @@ function replayRecords(replay: HarnessReplayRecord, source: HarnessReplayReco const current = events .filter(event => event.source === source && event.record) .map(event => event.record as T); - if (current.length > 0 || events.length > 0) return current; + if (current.length > 0) return current; const legacyKey = ({ trace: 'traces', artifact: 'artifacts', checkpoint: 'checkpoints', sensor: 'sensorRuns', task: 'tasks', handoff: 'handoffs' } as const)[source as Exclude]; return legacyKey ? (((replay as unknown as Record)[legacyKey] as T[] | undefined) ?? []) : []; } diff --git a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts index ea471baf..b4fb01fb 100644 --- a/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -3,9 +3,39 @@ import { DEFAULT_HOOK_TRACE_POLICY, parseHookTracePolicy, sanitizeHookTraceData, + truncateUtf8Prefix, } from '../hookTracePolicy'; describe('hook trace policy', () => { + describe('bounded UTF-8 prefixes', () => { + it('is byte-accurate at multibyte and surrogate boundaries', () => { + expect(truncateUtf8Prefix('hello!', 5)).toEqual({ value: 'hello', truncated: true }); + expect(truncateUtf8Prefix('ééé', 4)).toEqual({ value: 'éé', truncated: true }); + expect(truncateUtf8Prefix('😀x', 3)).toEqual({ value: '', truncated: true }); + expect(truncateUtf8Prefix('😀x', 4)).toEqual({ value: '😀', truncated: true }); + expect(truncateUtf8Prefix('\ud800A', 2)).toEqual({ value: '', truncated: true }); + }); + + it.each([ + { label: 'ASCII', huge: 'x'.repeat(16 * 1024 * 1024 + 17), expected: 'x'.repeat(512) }, + { label: 'multibyte', huge: '😀'.repeat(4 * 1024 * 1024 + 3), expected: '😀'.repeat(128) }, + ])('copies only a bounded prefix from a 16 MiB+ $label input', ({ huge, expected }) => { + const originalFrom = Buffer.from.bind(Buffer); + let largestStringInput = 0; + const from = jest.spyOn(Buffer, 'from').mockImplementation(((value: any, ...args: any[]) => { + if (typeof value === 'string') largestStringInput = Math.max(largestStringInput, value.length); + return (originalFrom as any)(value, ...args); + }) as any); + + const result = truncateUtf8Prefix(huge, 512); + from.mockRestore(); + + expect(result).toEqual({ value: expected, truncated: true }); + expect(largestStringInput).toBeLessThanOrEqual(513); + expect(Buffer.byteLength(result.value, 'utf8')).toBe(512); + }); + }); + it('summarizes a multi-megabyte Write without persisting its source body', () => { const content = `private-${'x'.repeat(5 * 1024 * 1024)}`; const data = sanitizeHookTraceData('Write', { diff --git a/src/harness/application/hooks/hookTracePolicy.ts b/src/harness/application/hooks/hookTracePolicy.ts index ad603b1b..77ec51e5 100644 --- a/src/harness/application/hooks/hookTracePolicy.ts +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -160,23 +160,23 @@ function byteLength(value: unknown): number { } } -function truncateUtf8(value: string, maximumBytes: number): { value: string; truncated: boolean } { - if (Buffer.byteLength(value, 'utf8') <= maximumBytes) { +export function truncateUtf8Prefix(value: string, maximumBytes: number): { value: string; truncated: boolean } { + const limit = Math.max(0, Math.floor(maximumBytes)); + // UTF-8 uses at least one byte per UTF-16 code unit. Inspecting limit + 1 + // code units is enough to decide truncation without copying an untrusted + // multi-megabyte input into an Array of code points. + const prefix = value.slice(0, Math.min(value.length, limit + 1)); + const encoded = Buffer.from(prefix, 'utf8'); + if (value.length === prefix.length && encoded.length <= limit) { return { value, truncated: false }; } + if (limit === 0) return { value: '', truncated: value.length > 0 }; - const characters = Array.from(value); - let low = 0; - let high = characters.length; - while (low < high) { - const middle = Math.ceil((low + high) / 2); - if (Buffer.byteLength(characters.slice(0, middle).join(''), 'utf8') <= maximumBytes) { - low = middle; - } else { - high = middle - 1; - } + let end = Math.min(limit, encoded.length); + while (end > 0 && end < encoded.length && (encoded[end] & 0xc0) === 0x80) { + end -= 1; } - return { value: characters.slice(0, low).join(''), truncated: true }; + return { value: encoded.subarray(0, end).toString('utf8'), truncated: true }; } function hashText(value: string): string { @@ -241,7 +241,7 @@ function summarizeUnknown( return value; } if (typeof value === 'string') { - const result = truncateUtf8(value, policy.maxStringBytes); + const result = truncateUtf8Prefix(value, policy.maxStringBytes); if (result.truncated) state.truncatedFieldCount += 1; return result.truncated ? `${result.value}…[truncated]` : result.value; } @@ -317,7 +317,7 @@ function summarizeBash(input: Record, policy: HookTracePolicy, if (!command) return {}; const redactedCommand = redactCommandSecrets(command); state.redactedFieldCount += redactedCommand.redacted; - const preview = truncateUtf8(redactedCommand.value, policy.maxStringBytes); + const preview = truncateUtf8Prefix(redactedCommand.value, policy.maxStringBytes); if (preview.truncated) state.truncatedFieldCount += 1; return { commandBasename: commandBasename(command), @@ -390,10 +390,10 @@ export function boundGenericTraceRecord { expect([...sources]).toEqual(expect.arrayContaining(['session', 'trace', 'artifact', 'checkpoint', 'sensor', 'task', 'handoff'])); }); + + it('reports the complete sensor history count when the replay page stops early', async () => { + const session = await execution.createSession({ name: 'sensor-count' }); + for (let index = 0; index < 5; index += 1) { + await execution.runSensor({ + id: 'tests', + name: 'Tests', + execute: () => ({ status: 'passed', summary: `run-${index}` }), + }, { sessionId: session.id }); + } + + const replay = await service.buildReplay(session.id, { maxEvents: 1 }); + + expect(replay.sourceCounts.sensor).toBe(5); + expect(replay.omittedCounts.sensor).toBe(5); + }); }); diff --git a/src/harness/application/replay/replayService.ts b/src/harness/application/replay/replayService.ts index 7cb43dd7..33a93833 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -87,7 +87,7 @@ export interface HarnessReplaySummary { export interface HarnessReplayDependencies { stateService: HarnessRuntimeStatePort; - sensorsService: Pick; + sensorsService: Pick; contractsService: Pick< HarnessTaskContractsService, 'listSessionTaskContracts' | 'listSessionHandoffContracts' @@ -191,6 +191,7 @@ export class HarnessReplayService { const maxEvents = boundedLimit(options.maxEvents, 100, 1000, 'replay events'); const byteBudget = boundedPageBytes(options.maxBytes, 'replay events'); const session = await this.stateService.getSession(sessionId); + const sensorRunCount = await this.sensorsService.getSessionSensorRunCount(sessionId); const binding = queryBinding({ sessionId, direction: 'oldest', includePayloads: options.includePayloads !== false }); const boundary = decodeHistoryCursor(options.cursor, 'replay-events', binding); const boundaryKey = boundary ? replayCursorKey(boundary) : undefined; @@ -200,7 +201,7 @@ export class HarnessReplayService { trace: session.traceCount, artifact: session.artifactCount, checkpoint: session.checkpointCount, - sensor: 0, + sensor: sensorRunCount, task: 0, handoff: 0, }; @@ -246,10 +247,7 @@ export class HarnessReplayService { })(); const sensorSource = paged( cursor => this.sensorsService.getSessionSensorRunPage(sessionId, { limit: pageSize, cursor, direction: 'oldest', maxBytes: byteBudget }), - run => { - sourceTotals.sensor += 1; - return { id: run.id, sessionId, createdAt: run.createdAt, source: 'sensor', label: run.sensorId, record: recordFor(run) }; - } + run => ({ id: run.id, sessionId, createdAt: run.createdAt, source: 'sensor', label: run.sensorId, record: recordFor(run) }) ); const taskSource = paged( async cursor => { @@ -298,10 +296,7 @@ export class HarnessReplayService { returnedBytes = candidateTotal; } const hasMore = heads.some(head => !head.done); - const sourceCounts: Record = { - ...sourceTotals, - sensor: sourceTotals.sensor, - }; + const sourceCounts: Record = { ...sourceTotals }; const includedCounts = orderedEvents.reduce((counts, event) => { counts[event.source] += 1; return counts; From 92c2f1e0938e54eb81df597486bab054f2585bda Mon Sep 17 00:00:00 2001 From: Vinicius Lana Date: Mon, 13 Jul 2026 12:00:18 -0300 Subject: [PATCH 39/39] remove specs --- specs/performance/README.md | 62 -------- .../f-01-bound-subprocess-output.md | 116 --------------- .../f-02-sanitize-hook-payloads.md | 119 --------------- .../f-03-stream-runtime-history.md | 135 ------------------ .../performance/f-04-lsp-process-lifecycle.md | 111 -------------- .../f-05-shared-semantic-analysis.md | 122 ---------------- specs/performance/f-06-bound-mcp-payloads.md | 121 ---------------- specs/performance/f-07-cache-retention.md | 123 ---------------- 8 files changed, 909 deletions(-) delete mode 100644 specs/performance/README.md delete mode 100644 specs/performance/f-01-bound-subprocess-output.md delete mode 100644 specs/performance/f-02-sanitize-hook-payloads.md delete mode 100644 specs/performance/f-03-stream-runtime-history.md delete mode 100644 specs/performance/f-04-lsp-process-lifecycle.md delete mode 100644 specs/performance/f-05-shared-semantic-analysis.md delete mode 100644 specs/performance/f-06-bound-mcp-payloads.md delete mode 100644 specs/performance/f-07-cache-retention.md diff --git a/specs/performance/README.md b/specs/performance/README.md deleted file mode 100644 index 2b89a893..00000000 --- a/specs/performance/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Memory and Performance Remediation Specifications - -Status: Proposed -Source audit: [MEMORY_PERFORMANCE_AUDIT.md](../../MEMORY_PERFORMANCE_AUDIT.md) - -## Objective - -Turn every confirmed audit finding into an independently deliverable change with explicit resource bounds, compatibility rules, observability, rollback, and regression tests. - -## Specification map - -| Finding | Specification | Preventive skill | Priority | -| --- | --- | --- | --- | -| F-01 | [Bound subprocess output](./f-01-bound-subprocess-output.md) | [bound-subprocess-output](../../.context/skills/bound-subprocess-output/SKILL.md) | P0 | -| F-02 | [Sanitize hook payloads and rotate traces](./f-02-sanitize-hook-payloads.md) | [sanitize-hook-payloads](../../.context/skills/sanitize-hook-payloads/SKILL.md) | P0 | -| F-03 | [Stream runtime history](./f-03-stream-runtime-history.md) | [stream-runtime-history](../../.context/skills/stream-runtime-history/SKILL.md) | P0 | -| F-04 | [Own the LSP process lifecycle](./f-04-lsp-process-lifecycle.md) | [manage-lsp-process-lifecycle](../../.context/skills/manage-lsp-process-lifecycle/SKILL.md) | P0 | -| F-05 | [Share semantic analysis work](./f-05-shared-semantic-analysis.md) | [share-semantic-analysis](../../.context/skills/share-semantic-analysis/SKILL.md) | P1 | -| F-06 | [Bound MCP payloads](./f-06-bound-mcp-payloads.md) | [bound-mcp-payloads](../../.context/skills/bound-mcp-payloads/SKILL.md) | P0/P1 | -| F-07 | [Govern cache and persistent retention](./f-07-cache-retention.md) | [govern-cache-retention](../../.context/skills/govern-cache-retention/SKILL.md) | P1 | - -## Delivery order - -1. F-01 and F-04 can proceed independently. -2. F-02 establishes safe trace writes. -3. F-03 establishes bounded reads, replay, dataset, and runtime retention. -4. F-06 consumes the pagination contracts from F-03. -5. F-05 consolidates semantic work without coupling to runtime history. -6. F-07 finishes lifecycle policy across caches, bindings, checkpoints, and indexes. - -F-02, F-03, and F-06 must agree on cursor and truncation metadata before implementation. Do not ship a response limit that merely rejects the current unpaginated runtime APIs. - -## Global engineering constraints - -- Preserve the cli -> harness <- mcp and integrations boundary. -- Put reusable execution behavior in src/harness/application or reusable rules in src/harness/domain. -- Keep transport validation and response shaping in src/mcp/gateway or src/mcp/server. -- Keep host event mapping and hook templates in src/integrations. -- Do not add code under src/services. -- Keep default behavior safe without requiring configuration. -- Never use a larger Node heap as the primary mitigation. - -## Global quality gates - -Every implementation must: - -1. add a failing regression test before the fix; -2. define the bound in bytes, entries, concurrency, or time; -3. expose truncation or partial-result metadata; -4. keep active workflows and existing runtime files readable; -5. avoid logging captured content; -6. run npm run build and npm test -- --runInBand; -7. run package build and smoke tests if a public package contract changes. - -## Shared terminology - -- Hard limit: input above the threshold is rejected or terminated. -- Soft limit: older data is evicted or output is truncated while the operation continues. -- Cursor: opaque continuation token; callers must not infer file offsets from it. -- Summary record: bounded metadata without the original payload. -- Partial result: a successful, explicitly incomplete response with a continuation path. - diff --git a/specs/performance/f-01-bound-subprocess-output.md b/specs/performance/f-01-bound-subprocess-output.md deleted file mode 100644 index e0bb13c9..00000000 --- a/specs/performance/f-01-bound-subprocess-output.md +++ /dev/null @@ -1,116 +0,0 @@ -# F-01 — Bound subprocess output - -Status: Proposed -Priority: P0 -Boundary owner: harness -Preventive skill: [bound-subprocess-output](../../.context/skills/bound-subprocess-output/SKILL.md) - -## Problem - -Sensor and acceptance subprocesses retain every stdout and stderr chunk. Tail limits are applied only after Buffer.concat, and Jest output is converted into another full string before parsing. Memory therefore scales with child output instead of the configured diagnostic tail. - -Affected code: - -- [testsPassing.ts](../../src/harness/adapters/out/sensors/testsPassing.ts) -- [typecheckClean.ts](../../src/harness/adapters/out/sensors/typecheckClean.ts) -- [acceptanceRunner.ts](../../src/harness/domain/workflow/plans/acceptanceRunner.ts) - -## Goals - -- Bound in-memory child output independently for stdout and stderr. -- Preserve an 8 KiB diagnostic tail by default. -- Support Jest summary extraction without retaining terminal output. -- Make truncation visible to callers and traces. -- Terminate commands that exceed a configurable hard output ceiling when requested. - -## Non-goals - -- Replace Node child_process. -- Stream live output to the MCP client. -- Store complete test output in runtime traces. - -## Proposed design - -### Bounded collector - -Add a pure bounded byte collector under src/harness/domain/execution. It must: - -- accept Buffer chunks; -- retain only the newest tailBytes; -- track totalBytes and droppedBytes; -- expose truncated; -- avoid Buffer.concat over all historical chunks; -- cap the number of retained segments or compact incrementally. - -Default limits: - -| Setting | Default | -| --- | ---: | -| tailBytes per stream | 8 KiB | -| soft capture limit per stream | 1 MiB | -| hard combined output limit | 16 MiB | -| hard-limit behavior | terminate child and return outputLimitExceeded | - -The caller may lower limits. Raising a hard limit above 64 MiB must require an explicit unsafe override in application code, not only user input. - -### Sensor execution - -Replace runShell raw strings with a result containing bounded tails and counters: - -- stdoutTail; -- stderrTail; -- stdoutBytes; -- stderrBytes; -- stdoutDroppedBytes; -- stderrDroppedBytes; -- outputTruncated; -- outputLimitExceeded. - -For default Jest execution: - -1. write JSON results to a temporary file using Jest outputFile; -2. keep console stdout/stderr bounded; -3. reject a JSON result file above 32 MiB before reading; -4. parse only fields required for TestsPassingReport; -5. remove the temporary file in finally. - -Custom exit-code sensors never need complete output. - -### Acceptance execution - -Use the same collector. A plan acceptance run persists only tails and counters. Exceeding the hard limit fails the acceptance predicate with a stable reason. - -## Compatibility - -- Keep existing tailStdout and tailStderr fields. -- Add optional counters so older persisted plan tracking remains readable. -- Preserve timeout and exit-code semantics. -- Keep testCommand arrays and shell:false behavior. - -## Work breakdown - -1. Implement and unit-test the bounded collector. -2. Refactor acceptance runner. -3. Refactor shared sensor runner. -4. Move Jest JSON to a temporary result file. -5. Add output-limit configuration with clamped values. -6. Add observability fields to sensor and acceptance traces. - -## Acceptance criteria - -- A child that emits 100 MiB does not retain more than configured tails plus 8 MiB process overhead attributable to capture. -- No array grows with the total number of output chunks. -- Acceptance returns at most tailBytes per stream. -- Typecheck and exit-code sensor paths never materialize full output strings. -- Jest result files above 32 MiB fail with resultFileTooLarge. -- Timeout, spawn error, non-zero exit, malformed Jest JSON, and output-limit paths have regression tests. -- npm run build and the complete Jest suite pass. - -## Rollout and rollback - -Ship behind internal defaults, not a user-facing feature flag. Preserve legacy result fields. Roll back by restoring the old runner only if bounded capture breaks command completion; never roll back the hard ceiling without an incident-specific patch. - -## Observability - -Record byte counters, truncation, termination reason, duration, and command basename. Never record full command output. - diff --git a/specs/performance/f-02-sanitize-hook-payloads.md b/specs/performance/f-02-sanitize-hook-payloads.md deleted file mode 100644 index 96a15b6b..00000000 --- a/specs/performance/f-02-sanitize-hook-payloads.md +++ /dev/null @@ -1,119 +0,0 @@ -# F-02 — Sanitize hook payloads and rotate traces - -Status: Proposed -Priority: P0 -Boundary owners: integrations, cli, harness -Preventive skill: [sanitize-hook-payloads](../../.context/skills/sanitize-hook-payloads/SKILL.md) - -## Problem - -Shell hook dispatch reads all stdin into memory and PostToolUse persists tool_input unchanged. Write and Edit can therefore duplicate complete source content into trace.jsonl. Traces have no event limit, byte quota, rotation, or automatic retention. - -Affected code: - -- [hookDispatchService.ts](../../src/cli/services/hookDispatchService.ts) -- [bashClassification.ts](../../src/harness/application/hooks/bashClassification.ts) -- [resolveHarnessHookFromHostEvent.ts](../../src/integrations/shared/resolveHarnessHookFromHostEvent.ts) -- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) - -## Goals - -- Bound hook stdin before concatenation and JSON parsing. -- Persist useful tool metadata without source bodies or secrets. -- Enforce a defense-in-depth maximum serialized trace event size. -- Rotate and retain trace segments without breaking active sessions. -- Make redaction and truncation observable. - -## Non-goals - -- Persist diffs for later reconstruction. -- Rewrite historical traces during the first release. -- Change host hook configuration shapes. - -## Proposed design - -### Bounded stdin - -Implement incremental byte counting in CLI hook dispatch: - -- default maximum: 8 MiB; -- stop reading and return a non-blocking diagnostic when exceeded; -- do not Buffer.concat after the limit; -- never echo the rejected input. - -The dispatcher must remain non-blocking for host operations, but must record a bounded trace-failure diagnostic. - -### Hook trace policy - -Add a reusable policy in src/harness/application/hooks. Normalize known tools: - -| Tool | Persist | -| --- | --- | -| Write | file path, declared byte length, content hash, contentOmitted=true | -| Edit | file path, old/new byte lengths, hashes, range metadata when present | -| Bash | classification, command basename, bounded command preview | -| Unknown | keys, scalar metadata, bounded structural summary | - -Always redact keys matching content, old_string, new_string, patch, apiKey, token, secret, password, authorization, messages, and prompt, case-insensitively. - -Defaults: - -- maximum string field: 512 bytes; -- maximum array items: 20; -- maximum object depth: 4; -- maximum serialized hook trace data: 16 KiB; -- maximum serialized generic trace event: 256 KiB. - -### Trace write quota and rotation - -Store trace segments under the existing session directory: - -- active trace.jsonl remains the write target; -- rotate at 8 MiB; -- retain 4 closed segments per active session; -- retain at most 32 MiB per session by default; -- never delete the active segment; -- write a bounded trace.rotated event after rotation. - -F-03 defines streaming reads across segments and repository-wide retention. - -## Configuration - -Use .context/config/hooks.json for hook-specific limits and .context/config/runtime.json for generic trace limits. Clamp all configured values to safe global maxima. - -## Compatibility and migration - -- Existing unsegmented trace.jsonl remains readable. -- New readers must merge legacy and rotated segments in chronological order. -- Existing hook installation docs and templates remain unchanged. -- No historical source payload is rewritten automatically. - -## Work breakdown - -1. Add tool-input sanitizer and tests for every host envelope. -2. Add bounded stdin reader. -3. Add serialized event size guard to runtime state. -4. Add atomic trace rotation. -5. Add config parsing and clamping. -6. Update README, dotcontext.dev hook guide, and CHANGELOG because hook behavior changes. - -## Acceptance criteria - -- A 5 MiB Write content produces a trace event below 16 KiB. -- No raw Write/Edit content appears in persisted traces. -- Sensitive keys are redacted regardless of case. -- Hook stdin above 8 MiB does not cause Buffer.concat or process failure. -- A trace rotates after the configured threshold and active writes continue. -- Concurrent appends do not corrupt or misorder a segment. -- Old trace.jsonl files remain readable. -- Hook round-trip tests cover Claude Code, Codex, and Pi. -- Build, full tests, package build, and package smoke pass. - -## Rollout and rollback - -Enable sanitization immediately. Roll out rotation after F-03 readers understand segments. Rollback may disable rotation, but must never restore raw content capture. - -## Observability - -Record inputBytes, persistedBytes, redactedFieldCount, truncatedFieldCount, rotationCount, and quota status. Never log redacted values or hashes of known secrets. - diff --git a/specs/performance/f-03-stream-runtime-history.md b/specs/performance/f-03-stream-runtime-history.md deleted file mode 100644 index 9f93de92..00000000 --- a/specs/performance/f-03-stream-runtime-history.md +++ /dev/null @@ -1,135 +0,0 @@ -# F-03 — Stream runtime history - -Status: Proposed -Priority: P0 -Boundary owner: harness, with MCP adaptation in F-06 -Preventive skill: [stream-runtime-history](../../.context/skills/stream-runtime-history/SKILL.md) - -## Problem - -Runtime APIs load complete traces, artifacts, sessions, replays, and datasets. Replay creates a second full event graph and applies maxEvents only after materialization, while still returning complete source arrays. Dataset builds every selected replay concurrently. - -Affected code: - -- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) -- [replayService.ts](../../src/harness/application/replay/replayService.ts) -- [datasetService.ts](../../src/harness/application/datasets/datasetService.ts) -- [taskContractsService.ts](../../src/harness/application/contracts/taskContractsService.ts) -- [sensorsService.ts](../../src/harness/application/sensors/sensorsService.ts) - -## Goals - -- Make memory proportional to page size, not history size. -- Give every list operation a bounded default and maximum. -- Make replay limits constrain reads, transformations, response, and persistence. -- Build datasets with bounded concurrency. -- Add retention without deleting active workflow evidence. - -## Non-goals - -- Introduce a database dependency. -- Preserve unlimited list behavior. -- Reconstruct source content removed by F-02. - -## Query contracts - -Introduce opaque cursor-based queries: - -| Resource | Default | Maximum | -| --- | ---: | ---: | -| traces | 100 | 1,000 | -| sessions | 50 | 200 | -| artifacts | 50 | 200 | -| replay summaries | 25 | 100 | -| dataset summaries | 25 | 100 | - -Every page returns items, nextCursor, hasMore, and scannedBytes where applicable. Support trace filters for event, level, createdAfter, and createdBefore. - -Cursor payloads must be versioned and encoded; invalid or stale cursors return a typed error. Do not expose raw file offsets as a public guarantee. - -## Streaming trace reader - -Add a runtime-state port that iterates JSONL records across legacy and rotated segments: - -- read line-by-line; -- stop after the requested page; -- skip malformed terminal lines and report malformedCount; -- support newest-first without reading the entire file into a string; -- expose an internal async iterator for consumers that need full scans. - -Task evaluation and sensor quality must not scan every trace. Maintain a bounded session summary with the latest run per sensor and update it during appendTrace. - -## Replay contract - -Replace the current mixed full/partial record with: - -- bounded events; -- source counts by type; -- omitted counts; -- nextCursor for additional events; -- fidelity; -- bounded session summary. - -When maxEvents is 10, no source array may contain more than those 10 materialized events. Full export, if retained, must stream to a file artifact and return its path/metadata rather than the payload. - -## Dataset execution - -- default concurrency: 1 session; -- configurable maximum: 4; -- process replay summaries incrementally; -- retain only failure records required for clustering; -- cap failures per dataset at 10,000 by default; -- return partial=true and omittedFailureCount when capped. - -## Runtime retention - -Default policy: - -- active sessions: never age-delete; -- completed/failed sessions: retain 30 days; -- replays: retain 10 per session and 30 days; -- datasets: retain 20 and 30 days; -- repository runtime quota: 256 MiB; -- prune oldest eligible data first; -- dry-run prune report required. - -F-07 owns configuration lifecycle and binding/checkpoint retention. - -## Compatibility - -- Keep point reads by ID. -- Read legacy trace.jsonl and existing replay/dataset JSON. -- Add summary-only list APIs before changing MCP defaults. -- Mark unlimited methods deprecated for one minor release, but make internal hot paths use paginated APIs immediately. - -## Work breakdown - -1. Define page and cursor types in harness. -2. Implement streaming trace reader and segment merge. -3. Add paginated state ports. -4. Add sensor summary index and migration-on-read. -5. Redesign replay result and persistence. -6. Bound dataset concurrency and records. -7. Add prune service with dry-run. -8. Adapt CLI and MCP consumers. - -## Acceptance criteria - -- Reading 100 records from a 1 GiB trace stays within 32 MiB incremental RSS in a dedicated benchmark. -- maxEvents=10 returns and persists at most 10 event payloads. -- Task evaluation reads the sensor summary rather than listTraces. -- Dataset processing never exceeds configured concurrency. -- List APIs reject limits above their maximum. -- Legacy runtime fixtures remain readable. -- Prune never deletes active sessions or the active workflow binding. -- Crash during rotation/prune leaves a readable previous state. -- Load tests cover one million trace lines and 1,000 sessions. - -## Rollout and rollback - -Ship readers before writers and summary indexes before hot-path migration. Keep legacy fallback for one release. Roll back consumers independently while preserving new files; never require destructive downgrade migration. - -## Observability - -Expose recordsReturned, recordsScanned, bytesRead, cursorVersion, malformedCount, partial, pruneBytes, and per-operation duration. - diff --git a/specs/performance/f-04-lsp-process-lifecycle.md b/specs/performance/f-04-lsp-process-lifecycle.md deleted file mode 100644 index 9e68c96d..00000000 --- a/specs/performance/f-04-lsp-process-lifecycle.md +++ /dev/null @@ -1,111 +0,0 @@ -# F-04 — Own the LSP process lifecycle - -Status: Proposed -Priority: P0 when useLSP is enabled -Boundary owner: harness semantic adapter -Preventive skill: [manage-lsp-process-lifecycle](../../.context/skills/manage-lsp-process-lifecycle/SKILL.md) - -## Problem - -LSPLayer returns false after initialize failure without terminating the spawned process. A later request spawns another process and overwrites the tracked Map entry. cleanup removes bookkeeping but never kills the child, and shutdown has the same leak when the protocol request fails or times out. - -Affected code: - -- [lspLayer.ts](../../src/harness/adapters/out/semantic/lsp/lspLayer.ts) -- [codebaseAnalyzer.ts](../../src/harness/adapters/out/semantic/codebaseAnalyzer.ts) - -## Goals - -- Give every spawned process exactly one tracked owner. -- Deduplicate concurrent initialization per language and project. -- Guarantee termination after initialization failure and shutdown. -- Scope requests, buffers, and cleanup to a concrete server instance. -- Avoid retry storms while preserving regex/tree-sitter fallback. - -## Non-goals - -- Implement a general LSP client framework. -- Automatically install language servers. -- Keep a failed server alive for debugging. - -## Proposed state model - -Track a ServerHandle per language and project: - -- process; -- state: starting, ready, stopping, stopped, failed; -- initialization Promise; -- pending request IDs; -- receive buffer; -- projectPath; -- startedAt; -- termination reason. - -Do not store process, buffer, and initialized state in separate Maps. - -### Initialization - -1. Return the ready handle when available. -2. Return the existing initialization Promise while starting. -3. After a failure, open a circuit for the current analysis. -4. On failure, reject only requests owned by that handle. -5. Close stdin, send SIGTERM, wait up to 2 seconds, then SIGKILL. -6. Wait for close before deleting the handle. - -Use a spawn confirmation based on spawn/error events rather than a 100 ms timer. - -### Shutdown - -For each handle: - -1. request protocol shutdown with a 2-second timeout; -2. send exit when shutdown succeeds; -3. close stdin; -4. wait for process exit; -5. send SIGTERM, then SIGKILL after 2 seconds if necessary; -6. clear timers, listeners, buffers, and pending requests. - -shutdown must be idempotent and safe during initialization. - -### Retry policy - -- one initialization attempt per language/project per CodebaseAnalyzer; -- no per-symbol retries after failure; -- a new analyzer may retry; -- optional explicit retry method for diagnostics only. - -## Compatibility - -- Keep public LSPLayer semantic methods and fallback return values. -- Preserve useLSP=false behavior. -- Do not expose ChildProcess through public harness APIs. - -## Work breakdown - -1. Introduce ServerHandle and typed state transitions. -2. Replace Maps with handle ownership. -3. Add spawn and initialization deduplication. -4. Implement terminateProcess with grace and kill escalation. -5. Scope pending requests by handle. -6. Add circuit breaker to semantic enhancement. -7. Add fake-server fixtures for rejection, timeout, crash, and ignored shutdown. - -## Acceptance criteria - -- Initialize rejection leaves zero child processes. -- Initialize timeout leaves zero child processes. -- Two concurrent ensureServer calls spawn exactly one child. -- Repeated symbol enhancement after failure performs no new spawn. -- shutdown leaves zero children when the server ignores protocol shutdown. -- cleanup of one language does not reject another language's requests. -- All timers and listeners are removed after shutdown. -- Tests assert child exit, not only empty Maps. - -## Rollout and rollback - -Ship without a flag because the current behavior leaks processes. If an LSP implementation needs more shutdown time, adjust the bounded grace period by config; do not revert process ownership. - -## Observability - -Record language, project hash, PID, state transition, initialize duration, exit code/signal, forcedKill, pending request count, and retry suppression. Do not log source payloads returned by LSP. - diff --git a/specs/performance/f-05-shared-semantic-analysis.md b/specs/performance/f-05-shared-semantic-analysis.md deleted file mode 100644 index 7da554ea..00000000 --- a/specs/performance/f-05-shared-semantic-analysis.md +++ /dev/null @@ -1,122 +0,0 @@ -# F-05 — Share semantic analysis work - -Status: Proposed -Priority: P1 -Boundary owner: harness context application -Preventive skill: [share-semantic-analysis](../../.context/skills/share-semantic-analysis/SKILL.md) - -## Problem - -The default context init maps the repository, analyzes documentation semantics, analyzes functional patterns with another analyzer, and analyzes agents with a third analyzer. Snapshot refresh can hash repository contents three times per attempt and retry three times. - -Affected code: - -- [contextTools.ts](../../src/harness/application/context/contextTools.ts) -- [documentationGenerator.ts](../../src/harness/application/context/scaffolding/generators/documentation/documentationGenerator.ts) -- [agentGenerator.ts](../../src/harness/application/context/scaffolding/generators/agents/agentGenerator.ts) -- [semanticSnapshotService.ts](../../src/harness/adapters/out/semantic/semanticSnapshotService.ts) -- [codebaseAnalyzer.ts](../../src/harness/adapters/out/semantic/codebaseAnalyzer.ts) -- [fileMapper.ts](../../src/utils/fileMapper.ts) - -## Goals - -- Perform one bounded repository discovery per context operation. -- Parse each selected source file at most once per analysis bundle. -- Reuse semantics, functional patterns, stack info, and fingerprint. -- Avoid content rehash when the repository has not changed. -- Make partial analysis explicit when limits apply. - -## Non-goals - -- Persist full symbol graphs as a public format. -- Guarantee a perfectly fresh snapshot during continuous writes. -- Analyze more than the configured file and byte budget. - -## Analysis bundle - -Add an operation-scoped AnalysisBundle in src/harness/application/context: - -- repoPath; -- discovered files and RepoStructure; -- SemanticContext; -- DetectedFunctionalPatterns; -- StackInfo; -- repo fingerprint; -- limits and partial metadata; -- metrics: filesDiscovered, filesParsed, bytesRead, duration by stage. - -Create the bundle once in HarnessContextService and inject it into generators and snapshot publication. - -CodebaseAnalyzer must expose one analyzeBundle pass that derives architecture and functional patterns from the same FileAnalysis Map. - -## Limits - -Defaults: - -| Limit | Default | -| --- | ---: | -| code files parsed | 5,000 | -| total source bytes parsed | 256 MiB | -| single source file | 2 MiB | -| directories scanned | 10,000 (absolute maximum 50,000) | -| raw directory entries scanned | 100,000 (absolute maximum 500,000) | -| file analysis concurrency | 16 (absolute maximum 64) | -| fingerprint attempts | 2 | - -Skip oversized files with a reason and mark partial=true. - -## Fingerprinting - -Use a staged fingerprint: - -1. enumerate only relevant paths with shared ignores; -2. hash path, size, and mtime for a fast candidate; -3. reuse cached content hashes for unchanged metadata; -4. hash content only for new or changed candidates; -5. use git index/tree identity as an additional fast signal when safe, never as the sole signal for dirty files. - -Do not glob every file and filter relevance afterward. - -Snapshot stabilization computes the initial fingerprint and one verification fingerprint. A second attempt is allowed; further instability returns a typed repositoryChanging error with the previous snapshot left readable. - -## Cache behavior - -- AnalysisBundle is operation-scoped and released after completion. -- Persistent cache stores bounded summary sections, not full FileAnalysis objects. -- Honor cacheEnabled. -- Invalidate by fingerprint, not only repository path. - -## Compatibility - -- Preserve current context init output and generated files. -- Keep SemanticContextBuilder public methods. -- Allow generators to construct their own bundle only for direct legacy calls; log a deprecation metric. - -## Work breakdown - -1. Define AnalysisLimits, AnalysisMetrics, and AnalysisBundle. -2. Unify file discovery and ignore rules. -3. Derive functional patterns from existing analyses. -4. Inject the bundle into docs and agent generators. -5. Refactor snapshot publication to consume the bundle. -6. Add incremental fingerprint cache. -7. Honor cacheEnabled and clear operation state in finally. - -## Acceptance criteria - -- Default type=both semantic init calls file parsing once per selected file. -- Functional pattern detection performs no second file read. -- Documentation and agent generators receive the same SemanticContext identity. -- A 3,000-file fixture remains within configured concurrency and byte limits. -- Oversized files are skipped and reported without crashing. -- Snapshot refresh performs no more than two stabilization attempts. -- Previous snapshots remain readable during refresh failure. -- Tests count analyzer calls, file reads, and maximum in-flight analysis. - -## Rollout and rollback - -Introduce AnalysisBundle behind the existing context service while legacy direct generator calls remain supported. Roll back individual consumers without changing the snapshot format. - -## Observability - -Record discovery, parsing, fingerprint, generation and publication durations; file and byte counts; cache hits; skipped file reasons; partial status; and stabilization attempts. diff --git a/specs/performance/f-06-bound-mcp-payloads.md b/specs/performance/f-06-bound-mcp-payloads.md deleted file mode 100644 index fee8f623..00000000 --- a/specs/performance/f-06-bound-mcp-payloads.md +++ /dev/null @@ -1,121 +0,0 @@ -# F-06 — Bound MCP payloads - -Status: Proposed -Priority: P0 for redundant parsing, P1 for complete pagination migration -Boundary owner: MCP gateway and server -Preventive skill: [bound-mcp-payloads](../../.context/skills/bound-mcp-payloads/SKILL.md) - -## Problem - -Gateway helpers serialize complete result objects into pretty JSON. The server then parses the same text to derive a small audit summary. Runtime list actions have no cursor and schema fields that can carry large content have no explicit size constraints. - -Affected code: - -- [response.ts](../../src/mcp/gateway/response.ts) -- [mcpServer.ts](../../src/mcp/server/mcpServer.ts) -- [actionLogger.ts](../../src/mcp/logging/actionLogger.ts) -- [actionService.ts](../../src/harness/application/actions/actionService.ts) - -## Goals - -- Eliminate response stringify/parse duplication. -- Bound every MCP list response. -- Validate caller-provided sizes and limits. -- Return actionable partial or too-large responses. -- Preserve transport-neutral behavior in harness. - -## Non-goals - -- Stream arbitrary MCP tool responses over a custom transport. -- Move pagination logic into MCP when it belongs in harness. -- Return raw runtime files as text. - -## Structured audit metadata - -Use the MCP result _meta field for bounded dotcontext audit metadata: - -- success; -- errorCode when present; -- scalar summary keys; -- itemCount; -- partial. - -Gateway response helpers construct content and audit metadata from the original result. logToolResponse reads _meta and response.isError; it must never JSON.parse response text. - -The dotcontext metadata object must remain below 2 KiB and contain no caller content. - -## Pagination - -Expose the F-03 cursor contracts for: - -- listSessions; -- listTraces; -- listArtifacts; -- listReplays; -- listDatasets; -- listTasks and listHandoffs if their counts can grow without bound. - -Defaults and maxima come from harness. MCP Zod schemas enforce integer, positive, bounded limit values. maxEvents defaults to 100 and is capped at 1,000. - -## Payload budget - -Set a default MCP text payload budget of 1 MiB and an absolute maximum of 4 MiB. - -Before final response: - -1. serialize compact JSON once; -2. measure UTF-8 bytes; -3. if over budget and pagination is available, return a typed pageTooLarge error with a smaller suggested limit; -4. if content is an export, persist it as a harness artifact and return metadata; -5. never truncate JSON text at an arbitrary byte boundary. - -Do not pretty-print responses above 64 KiB. Compact JSON is the default for machine transport. - -## Input bounds - -Apply schema maxima to: - -- content and scalar strings; -- data/output/details object depth and serialized bytes; -- arrays such as evidence, artifacts, sessionIds, and requiredArtifacts; -- regex and glob pattern length; -- maxResults, limit, and maxEvents. - -Validate serialized object bytes in application code because Zod shape limits alone are insufficient. - -## Compatibility - -- Preserve content text for MCP clients. -- Add _meta without requiring clients to consume it. -- Keep existing actions but change unlimited lists to bounded defaults. -- Document how to continue with nextCursor. - -## Work breakdown - -1. Add audit metadata to response helpers. -2. Remove parseResponsePayload. -3. Add shared input-size validation. -4. Wire F-03 pagination into schemas and gateways. -5. Add single-serialization payload guard. -6. Update MCP README, public docs, and CHANGELOG. - -## Acceptance criteria - -- logToolResponse performs zero JSON.parse calls on response content. -- A listTraces request without limit returns no more than 100 items. -- Limits above maximum fail schema validation. -- No successful MCP text response exceeds the configured budget without an explicit export reference. -- JSON is serialized exactly once in the normal response path. -- Audit metadata remains below 2 KiB and contains no content fields. -- Existing clients can read success/error content. -- Gateway and server tests cover boundaries at limit-1, limit, and limit+1. -- Package build and smoke tests pass. - -## Rollout and rollback - -Remove redundant parsing immediately. Ship pagination after F-03. If a client depends on unlimited lists, provide a temporary compatibility option capped by the absolute payload budget; do not restore unlimited defaults. - -## Observability - -Record responseBytes, serializationMs, itemCount, partial, requestedLimit, appliedLimit, and pageTooLarge. Do not log response bodies. - diff --git a/specs/performance/f-07-cache-retention.md b/specs/performance/f-07-cache-retention.md deleted file mode 100644 index ad0fcc61..00000000 --- a/specs/performance/f-07-cache-retention.md +++ /dev/null @@ -1,123 +0,0 @@ -# F-07 — Govern cache and persistent retention - -Status: Proposed -Priority: P1 -Boundary owners: harness, MCP logging, integrations -Preventive skill: [govern-cache-retention](../../.context/skills/govern-cache-retention/SKILL.md) - -## Problem - -Several caches and persistent indexes have no maximum size, complete invalidation, or cleanup lifecycle. ContextCache expires only on access, SemanticContextBuilder retains a full graph without file invalidation, MCP sessionCache has no TTL, host session bindings never expire, and checkpoints grow inside session.json that is rewritten on every trace. - -Affected code: - -- [contextCache.ts](../../src/harness/adapters/out/semantic/contextCache.ts) -- [contextBuilder.ts](../../src/harness/adapters/out/semantic/contextBuilder.ts) -- [actionLogger.ts](../../src/mcp/logging/actionLogger.ts) -- [hookSessionStore.ts](../../src/integrations/shared/hookSessionStore.ts) -- [runtimeStateService.ts](../../src/harness/adapters/out/runtimeState/runtimeStateService.ts) - -## Goals - -- Give every in-memory cache entry, byte, and age limits. -- Make expiration proactive at safe lifecycle points. -- Keep cache freshness tied to source identity. -- Bound host bindings and checkpoint persistence. -- Centralize runtime retention configuration with safe defaults. - -## Non-goals - -- Share caches between OS processes. -- Guarantee exact memory accounting. -- Delete active workflow data. - -## Cache contract - -Every cache must declare: - -- key normalization; -- maximum entries; -- estimated maximum bytes; -- TTL; -- freshness signal; -- eviction order; -- cleanup trigger; -- stop/dispose behavior; -- metrics. - -Defaults: - -| Cache | Entries | Estimated bytes | TTL | -| --- | ---: | ---: | ---: | -| ContextCache | 16 | 32 MiB | 5 minutes | -| SemanticContextBuilder | 1 | 64 MiB | fingerprint-bound | -| MCP session cache | 64 | negligible | 30 minutes idle | -| Tree-sitter FileAnalysis | 5,000 | 128 MiB | analysis lifecycle | - -Use LRU within TTL. Reject a single entry larger than its cache byte budget. - -### Context cache - -- sweep expired entries on set and at a bounded interval; -- unref the sweep timer; -- clear on MCP stop; -- include target file and relevant options in the key; -- use fingerprint/mtime for freshness. - -### Semantic builder and tree-sitter - -- honor cacheEnabled; -- invalidate full SemanticContext when repository fingerprint changes; -- evict removed file paths; -- release analysis cache after operation-scoped use from F-05. - -### Session cache and host bindings - -- normalize repoPath before using it as a key; -- LRU/idle-expire MCP session entries; -- remove cache entry when the session completes or disappears; -- expire host bindings after 30 days or when the bound harness session is missing; -- cap bindings at 1,000 per repository; -- prune during SessionStart and explicit maintenance, not every PostToolUse. - -### Checkpoints - -Move checkpoints from the growing session.json array to append-only checkpoint records or individual files. Keep only checkpointCount, lastCheckpointAt, and lastCheckpointId in session.json. - -Read legacy embedded checkpoints and migrate lazily on the next checkpoint write. Cap checkpoint data at 64 KiB and artifactIds at 200. - -## Runtime configuration - -Create .context/config/runtime.json with versioned sections for traces, sessions, replays, datasets, checkpoints, bindings, and caches. Defaults apply when absent. Unknown keys are ignored with a diagnostic; invalid unsafe values are clamped. - -## Work breakdown - -1. Define reusable LRU byte-budget utility. -2. Apply it to ContextCache and MCP session cache. -3. Honor semantic cacheEnabled and fingerprint freshness. -4. Add host binding prune and cap. -5. Externalize checkpoints with legacy migration. -6. Add runtime config schema and maintenance service. -7. Connect repository retention to F-03 prune. - -## Acceptance criteria - -- Inserting more than maxEntries evicts the least recently used entry. -- Expired entries disappear without being accessed individually. -- MCP stop leaves cache size zero and no referenced sweep timer. -- cacheEnabled=false stores no FileAnalysis or SemanticContext. -- Changing a source fingerprint invalidates semantic context. -- host-sessions.json never exceeds the configured binding cap. -- Missing harness sessions cause stale binding removal. -- Adding a checkpoint does not grow session.json with checkpoint payload history. -- Legacy embedded checkpoints remain readable and migrate without loss. -- Runtime config invalid values cannot disable absolute safety ceilings. - -## Rollout and rollback - -Land cache bounds independently. Migrate checkpoints with dual-read/new-write behavior. Keep legacy fields readable for at least one minor release. Rollback must not discard new checkpoint files. - -## Observability - -Expose entries, estimatedBytes, hit, miss, eviction reason, oldest age, stale binding count, checkpoint migration count, config clamps, and cleanup duration. -