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/CHANGELOG.md b/CHANGELOG.md index 242a3b11..afb5407c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ 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, 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, preserve live legacy locks during rolling upgrades, and prevent terminal MCP activity sessions from being reused. + +### 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. +- Added paginated sensor-run history alongside sharded, byte-capped latest-sensor summaries, plus small replay/dataset retention sidecars. + +### 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. +- 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. +- 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, 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. +- 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 ### Fixed 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/README.md b/README.md index 73e31c73..e862fcdf 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 @@ -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. @@ -522,6 +522,12 @@ 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. + +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/concepts/harness-runtime.md b/docs/src/content/docs/en/concepts/harness-runtime.md index 0ed921d4..162b4016 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": {} } ``` @@ -120,7 +123,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. 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. @@ -157,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 **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 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/concepts/replay-and-datasets.md b/docs/src/content/docs/en/concepts/replay-and-datasets.md index 5d9de528..cfbf55a4 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 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 { @@ -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 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/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/en/reference/context-layout.md b/docs/src/content/docs/en/reference/context-layout.md index c4802641..11c75814 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 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 @@ -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/en/reference/mcp-tools.md b/docs/src/content/docs/en/reference/mcp-tools.md index c940b036..ac59fca9 100644 --- a/docs/src/content/docs/en/reference/mcp-tools.md +++ b/docs/src/content/docs/en/reference/mcp-tools.md @@ -55,9 +55,15 @@ 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, search | Opaque continuation cursor from `page.nextCursor` | **Returns:** file contents, matched files, symbol analysis, search results, or a directory tree. +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. 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 Context scaffolding and semantic context — the entry point for creating and filling `.context/`. @@ -218,6 +224,16 @@ 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. + +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. @@ -321,6 +337,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/concepts/harness-runtime.md b/docs/src/content/docs/pt-br/concepts/harness-runtime.md index 16409af2..75a96c9d 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": {} } ``` @@ -120,7 +123,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. 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. @@ -157,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 **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, 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/concepts/replay-and-datasets.md b/docs/src/content/docs/pt-br/concepts/replay-and-datasets.md index 388b7006..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 @@ -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: +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 { @@ -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 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/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/docs/src/content/docs/pt-br/reference/context-layout.md b/docs/src/content/docs/pt-br/reference/context-layout.md index 6c20226c..36f388f2 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 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 @@ -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/docs/src/content/docs/pt-br/reference/mcp-tools.md b/docs/src/content/docs/pt-br/reference/mcp-tools.md index c3bcf410..885546de 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,15 @@ 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, 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` 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. 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 Scaffolding de contexto e contexto semântico — o ponto de entrada para criar e preencher o `.context/`. @@ -218,6 +224,16 @@ 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. + +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. @@ -321,6 +337,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/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/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..dcf4e3ae 100644 --- a/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts +++ b/src/harness/adapters/out/runtimeState/__tests__/runtimeStateService.test.ts @@ -1,8 +1,14 @@ 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, + MAX_SENSOR_SUMMARY_ENTRIES, + MAX_SENSOR_SUMMARY_ENTRY_BYTES, + MAX_STREAMED_TRACE_LINE_BYTES, } from '../runtimeStateService'; describe('HarnessRuntimeStateService', () => { @@ -49,13 +55,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'); @@ -78,6 +86,92 @@ 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(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 () => { + 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, 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 () => { @@ -95,4 +189,536 @@ 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); + 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); + }); + + 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('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); + 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: { + 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); + }); + 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.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', + }); + }); + + 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('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' } } }); + 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'))).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); + }, 15_000); }); diff --git a/src/harness/adapters/out/runtimeState/runtimeStateService.ts b/src/harness/adapters/out/runtimeState/runtimeStateService.ts index a23622e2..8e8da574 100644 --- a/src/harness/adapters/out/runtimeState/runtimeStateService.ts +++ b/src/harness/adapters/out/runtimeState/runtimeStateService.ts @@ -8,8 +8,400 @@ 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'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; +import { + boundGenericTraceRecord, + loadGenericTraceEventMaxBytes, + loadHookTracePolicy, +} from '../../../application/hooks/hookTracePolicy'; +import { + boundedPageBytes, + boundedLimit, + RUNTIME_HISTORY_LIMITS, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + serializedHistoryItemBytes, + RuntimeHistoryCursorError, + type RuntimeHistoryDirection, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../../../application/history/runtimeHistory'; + +const traceWriteQueues = new Map>(); +const TRACE_LOCK_STALE_MS = 60_000; +const ROTATION_EVENT_RESERVE_BYTES = 2 * 1024; + +interface TraceLockIdentity { + pid: number; + token: string; + createdAt?: string; +} + +interface TraceFileLock extends TraceLockIdentity { + lockFile: string; + handle: FileHandle; + inode: bigint | number; + 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 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)); +} + +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'; + } +} + +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 : '', + createdAt: typeof parsed.createdAt === 'string' ? parsed.createdAt : undefined, + }; + } 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; + pid?: number; + createdAt?: 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 + && (expected.pid === undefined || identity.pid === expected.pid) + && (expected.createdAt === undefined || identity.createdAt === expected.createdAt); + } finally { + await handle.close(); + } + } catch { + return false; + } +} + +async function readTraceLockSnapshot(lockFile: string): Promise { + try { + 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 { + const [stat, contents] = await Promise.all([ + handle.stat({ bigint: true }), + handle.readFile('utf8'), + ]); + const document = parseTraceTakeoverDocument(contents); + if (document) { + if (document.inode !== String(stat.ino) || document.device !== String(stat.dev)) return undefined; + return { + ...document, + format: 'current', + actualInode: stat.ino, + actualDevice: stat.dev, + mtimeMs: Number(stat.mtimeMs), + }; + } + const legacy = parseTraceLockIdentity(contents); + if (!Number.isInteger(legacy.pid) || !legacy.token || !legacy.createdAt) return undefined; + return { + ...legacy, + format: 'legacy', + createdAt: legacy.createdAt, + actualInode: stat.ino, + actualDevice: stat.dev, + mtimeMs: Number(stat.mtimeMs), + }; + } finally { + await handle.close(); + } + } catch { + return undefined; + } +} + +async function sameTakeoverIdentity(file: string, expected: TraceTakeoverSnapshot): Promise { + const current = await readTraceTakeoverSnapshot(file); + return current !== undefined + && current.format === expected.format + && current.actualInode === expected.actualInode + && current.actualDevice === expected.actualDevice + && current.pid === expected.pid + && current.token === expected.token + && current.createdAt === expected.createdAt; +} + +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; + } + const published = await readTraceTakeoverSnapshot(takeoverFile); + return published?.format === 'current' ? published : undefined; + } finally { + 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; + + if (takeover.format === 'legacy') { + const lockFile = takeoverFile.slice(0, -'.takeover'.length); + const target = await readTraceLockSnapshot(lockFile); + if ( + !target + || target.inode !== takeover.actualInode + || target.device !== takeover.actualDevice + || target.pid !== takeover.pid + || target.token !== takeover.token + || target.createdAt !== takeover.createdAt + ) return false; + // Legacy elections from the previous branch head were hard links to the + // target lock. Re-open both names immediately before unlinking only the + // election name, so a replacement identity survives the race. + if (!(await sameLockIdentity(lockFile, target))) return false; + if (!(await sameTakeoverIdentity(takeoverFile, takeover))) return false; + await nodeFs.unlink(takeoverFile).catch(() => undefined); + return true; + } + + 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); + } + } +} + +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 (await recoverOrphanedTraceTakeover(takeoverFile)) continue; + 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'); + 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, device: stat.dev, pid: process.pid, token }; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code !== 'EEXIST') throw error; + + if (await tryTakeOverStaleTraceLock(lockFile)) { + 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); + if (await sameLockIdentity(lock.lockFile, lock)) { + 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; + 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 withCrossProcessTraceLock(key, 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'; @@ -27,6 +419,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; @@ -39,6 +443,7 @@ export interface HarnessSessionRecord { failedAt?: string; lastTraceAt?: string; lastCheckpointAt?: string; + lastCheckpointId?: string; traceCount: number; artifactCount: number; checkpointCount: number; @@ -75,7 +480,181 @@ 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; + 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; + 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 { + file: string; + offset: number; + fingerprint: string; +} + +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(TRACE_READ_CHUNK_BYTES); + let position = startOffset; + let carry = Buffer.alloc(0); + let discardingOversized = false; + let unreportedBytes = 0; + try { + while (true) { + const { bytesRead } = await handle.read(chunk, 0, chunk.length, position); + if (bytesRead === 0) break; + 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); + } + } + position += bytesRead; + } + if (discardingOversized || carry.length > 0) { + yield { + line: discardingOversized ? '' : carry.toString('utf8').replace(/\r$/, ''), + nextOffset: position, + bytesRead: unreportedBytes, + oversized: discardingOversized, + }; + } + } 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); + let discardingOversized = false; + let unreportedBytes = 0; + try { + while (position > 0) { + 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); + unreportedBytes += bytesRead; + const newlines: number[] = []; + 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 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(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, + }; + } + } finally { + await handle.close(); + } } export interface CreateSessionInput { @@ -109,6 +688,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; @@ -149,10 +741,35 @@ 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); } + private checkpointFile(sessionId: string, checkpointId: string): string { + return this.layout.sessionCheckpointFile(sessionId, checkpointId); + } + + private sensorSummaryFile(sessionId: string): string { + 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)); } @@ -167,7 +784,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,28 +793,284 @@ 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); } } - 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)).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 { + 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); + 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 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({ + 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.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 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, 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 { + 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') 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, runCount }; await this.ensureSessionDir(sessionId); - await fs.appendFile(this.traceFile(sessionId), `${JSON.stringify(trace)}\n`, 'utf8'); + 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 { - const session = await this.readSession(sessionId); - await this.appendTraceLine(sessionId, trace); + // 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 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 += 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 { @@ -227,30 +1101,99 @@ export class HarnessRuntimeStateService { data: input.metadata ? { metadata: input.metadata } : undefined, }); - return this.readSession(session.id); + return this.getSession(session.id); } 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, RUNTIME_HISTORY_LIMITS.sessions.default, RUNTIME_HISTORY_LIMITS.sessions.maximum, '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: 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 file = this.sessionFile(entry.name); - sessions.push((await fs.readJson(file)) as HarnessSessionRecord); - } catch { - // Skip sessions with missing or unparseable session.json. - continue; + 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; + 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 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; } - - return sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + 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 || oversizedRecordsSkipped > 0, + durationMs: Date.now() - started, + }; } async getSession(sessionId: string): Promise { + // 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); } @@ -306,54 +1249,295 @@ export class HarnessRuntimeStateService { return artifact; } - async listCheckpoints(sessionId: string): Promise { + async listCheckpointsPage( + sessionId: string, + options: ListCheckpointsOptions = {}, + ): Promise { const session = await this.readSession(sessionId); - return [...session.checkpoints].sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + 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 (!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.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)); } async listArtifacts(sessionId: string): Promise { + const artifacts: HarnessArtifactRecord[] = []; + 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, RUNTIME_HISTORY_LIMITS.artifacts.default, RUNTIME_HISTORY_LIMITS.artifacts.maximum, '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); - if (!(await fs.pathExists(dir))) { - return []; + 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 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; + 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)); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt legacy records */ } + } } - - 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; + 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; } - - return artifacts.sort((a, b) => a.createdAt.localeCompare(b.createdAt)); + 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 || oversizedRecordsSkipped > 0, + durationMs: Date.now() - started, + }; } async listTraces(sessionId: string): Promise { - const file = this.traceFile(sessionId); - if (!(await fs.pathExists(file))) { - 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.oversized || !item.line.trim()) continue; + try { yield JSON.parse(item.line) as HarnessTraceRecord; } catch { /* bounded malformed diagnostic in pages */ } + } } + } - const content = await fs.readFile(file, 'utf8'); - return content - .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, RUNTIME_HISTORY_LIMITS.traces.default, RUNTIME_HISTORY_LIMITS.traces.maximum, '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); + 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 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) { + 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.oversized) { malformedCount += 1; continue; } + 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; } + 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 }; + } + return { + items, + nextCursor: hasMore && nextPosition ? encodeHistoryCursor('traces', binding, nextPosition) : undefined, + hasMore, + recordsReturned: items.length, + recordsScanned, + scannedBytes, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, + malformedCount, + cursorVersion: 1, + partial: hasMore || oversizedRecordsSkipped > 0, + durationMs: Date.now() - started, + }; } async checkpointSession(sessionId: string, input: CheckpointInput = {}): Promise { const session = await this.readSession(sessionId); + const { config } = await loadRuntimeRetentionConfig(this.repoPath); + 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(), @@ -362,10 +1546,30 @@ 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`); + } - 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.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; session.updatedAt = createdAt; session.status = input.pause ? 'paused' : session.status; @@ -380,7 +1584,7 @@ export class HarnessRuntimeStateService { data: { checkpointId: checkpoint.id, artifactIds: checkpoint.artifactIds, - payload: input.data, + payloadBytes: serializedBytes, }, }); 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..6d13cbb1 --- /dev/null +++ b/src/harness/adapters/out/semantic/__tests__/boundedFileDiscovery.test.ts @@ -0,0 +1,108 @@ +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); + await expect(isBoundedSnapshotFresh(result.snapshot)).resolves.toMatchObject({ + fresh: false, + signalsChecked: 0, + }); + }); + + 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: 3, + 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: 11, + 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'); + 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 new file mode 100644 index 00000000..647f92f2 --- /dev/null +++ b/src/harness/adapters/out/semantic/__tests__/cacheRetention.test.ts @@ -0,0 +1,136 @@ +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 = { + 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(); + }); + + 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); + }); + + 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};`); + } + 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(2); + expect(builder.freshnessMetrics(repo)).toMatchObject({ + discoveries: 2, + filesSelected: 10, + partialDiscoveries: 2, + }); + expect(builder.freshnessMetrics(repo)!.entriesScanned).toBeLessThan(40); + 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(); + }); + + 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 e1a01ec2..96b9733f 100644 --- a/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/codebaseAnalyzer.test.ts @@ -2,9 +2,11 @@ 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'; +jest.mock('glob', () => ({ glob: jest.fn() })); + // Mock TreeSitterLayer jest.mock('../treeSitter/treeSitterLayer', () => ({ TreeSitterLayer: jest.fn().mockImplementation(() => ({ @@ -59,22 +61,6 @@ jest.mock('../lsp/lspLayer', () => ({ })), })); -// Mock glob -jest.mock('glob', () => ({ - glob: jest.fn().mockImplementation(async (pattern: string, options: { cwd: string }) => { - // Return mock files based on the pattern - if (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'), - ]; - } - return []; - }), -})); - function createTempOutput(prefix: string): Promise { return fs.mkdtemp(path.join(os.tmpdir(), prefix)); } @@ -84,6 +70,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(); }); @@ -121,6 +119,164 @@ 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); + 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, + 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('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`) + ); + 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 () => { const analyzer = new CodebaseAnalyzer({ useLSP: false }); @@ -193,19 +349,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 (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); @@ -389,15 +532,35 @@ 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 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 () => { @@ -425,25 +588,15 @@ 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, - 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/__tests__/contextCache.test.ts b/src/harness/adapters/out/semantic/__tests__/contextCache.test.ts index cf878769..4b8b31b0 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 }); @@ -97,6 +104,113 @@ 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(); + }); + + 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 }); + 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(); + }); + + 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('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({ + 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', () => { @@ -143,6 +257,50 @@ 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'); + 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/__tests__/semanticSnapshotService.test.ts b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts index 35d56457..e4da9916 100644 --- a/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts +++ b/src/harness/adapters/out/semantic/__tests__/semanticSnapshotService.test.ts @@ -1,9 +1,14 @@ import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; import * as os from 'os'; import * as path from 'path'; import { FileMapper } from '../../../../../utils/fileMapper'; -import { SemanticSnapshotService } from '../semanticSnapshotService'; +import { + RepositoryChangingError, + SemanticFingerprintCache, + SemanticSnapshotService, +} from '../semanticSnapshotService'; describe('SemanticSnapshotService', () => { let tempDir: string; @@ -27,6 +32,7 @@ describe('SemanticSnapshotService', () => { }); afterEach(async () => { + jest.restoreAllMocks(); await fs.remove(tempDir); }); @@ -71,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); @@ -108,6 +172,180 @@ 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('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('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); + 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); + + 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 +439,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 05b12438..46d45e4f 100644 --- a/src/harness/adapters/out/semantic/codebaseAnalyzer.ts +++ b/src/harness/adapters/out/semantic/codebaseAnalyzer.ts @@ -5,9 +5,14 @@ * for deeper semantic understanding. */ -import { glob } from 'glob'; import * as path from 'path'; import * as fs from 'fs/promises'; +import type { FileInfo, RepoDiscoveryMetrics, RepoStructure } from '../../../../types'; +import { + ABSOLUTE_FILE_MAPPING_SCAN_LIMITS, + FileMapper, +} from '../../../../utils/fileMapper'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; import { TreeSitterLayer } from './treeSitter/treeSitterLayer'; import { LSPLayer } from './lsp/lspLayer'; import { @@ -35,17 +40,112 @@ const DEFAULT_OPTIONS: Required = { exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, + concurrency: 16, cacheEnabled: true, + fileAnalysisCacheMaxEntries: 5_000, + fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, }; +/** 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; + maxFileBytes: number; + maxDirectoriesScanned: number; + maxEntriesScanned: number; + concurrency: number; +} + +export type AnalysisSkipReason = + | 'file-limit' + | 'total-byte-limit' + | 'file-too-large' + | 'directory-limit' + | 'entry-limit' + | 'stat-failed'; + +export interface SkippedAnalysisFile { + file: string; + reason: AnalysisSkipReason; + size?: number; +} + +export interface AnalysisMetrics { + directoriesScanned: number; + entriesScanned: number; + 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; +} + +type DiscoveredAnalysisFile = string | Pick; +type SemanticDiscoveryInput = DiscoveredAnalysisFile[] | RepoStructure; + export class CodebaseAnalyzer { private treeSitter: TreeSitterLayer; private lspLayer?: LSPLayer; private options: Required; + private readonly fileCacheEntriesExplicit: boolean; + private readonly fileCacheBytesExplicit: boolean; + private readonly maxEntriesScannedExplicit: boolean; + private lastDiscovery?: import('./discovery').BoundedDiscoveryMetrics; constructor(options: AnalyzerOptions = {}) { - this.treeSitter = new TreeSitterLayer(); + this.fileCacheEntriesExplicit = options.fileAnalysisCacheMaxEntries !== undefined; + this.fileCacheBytesExplicit = options.fileAnalysisCacheMaxBytes !== undefined; + this.maxEntriesScannedExplicit = options.maxEntriesScanned !== undefined; 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.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)) + ); + 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) + ); + 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) { @@ -54,13 +154,103 @@ export class CodebaseAnalyzer { } async analyze(projectPath: string): Promise { + return (await this.analyzeProject(projectPath)).context; + } + + async analyzeBundle( + projectPath: string, + discoveryInput?: SemanticDiscoveryInput + ): Promise { + const result = await this.analyzeProject(projectPath, discoveryInput); + 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: 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, discoveryInput?: SemanticDiscoveryInput): Promise<{ + context: SemanticContext; + files: string[]; + fileAnalyses: Map; + skipped: SkippedAnalysisFile[]; + metrics: AnalysisMetrics; + startedAt: number; + }> { const startTime = Date.now(); + const { config } = await loadRuntimeRetentionConfig(projectPath); + if (this.options.cacheEnabled) { + 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), + }); + } + const metrics: AnalysisMetrics = { + directoriesScanned: 0, + entriesScanned: 0, + 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 discovery = discoveryInput + ? this.discoveryFromInput(projectPath, discoveryInput) + : await this.findCodeFiles( + projectPath, + this.maxEntriesScannedExplicit + ? this.options.maxEntriesScanned + : Math.min(this.options.maxEntriesScanned, config.caches.semantic.maxEntriesScanned) + ); + 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; + const skipped = [...discovery.skipped, ...selected.skipped]; + const bytes = selected.bytes; + 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); + this.treeSitter.retainOnly?.(files); + metrics.filesParsed = fileAnalyses.size; + metrics.durationsMs.parsing = Date.now() - parsingStartedAt; // 3. Build base context const context = this.buildBaseContext(fileAnalyses, projectPath); @@ -71,63 +261,212 @@ 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; - return context; - } - - private async findCodeFiles(projectPath: string): Promise { - const extensions = Object.keys(LANGUAGE_EXTENSIONS); - const patterns = extensions.map((ext) => `**/*${ext}`); + if (!this.options.cacheEnabled) { + this.treeSitter.clearCache(); + } - const ignorePatterns = this.options.exclude.map((p) => `**/${p}/**`); + return { + context, + files, + fileAnalyses, + skipped, + metrics, + startedAt: startTime, + }; + } - const allFiles: string[] = []; + private analysisLimits(): AnalysisLimits { + return { + maxFiles: this.options.maxFiles, + maxTotalBytes: this.options.maxTotalBytes, + maxFileBytes: this.options.maxFileBytes, + maxDirectoriesScanned: this.options.maxDirectoriesScanned, + maxEntriesScanned: this.options.maxEntriesScanned, + concurrency: this.options.concurrency, + }; + } - 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 + private async findCodeFiles( + projectPath: string, + maxEntriesScanned = this.options.maxEntriesScanned + ): Promise<{ + files: Array<{ path: string; size?: number }>; + skipped: SkippedAnalysisFile[]; + metrics?: RepoDiscoveryMetrics; + }> { + const startedAt = Date.now(); + 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, + }).mapRepository(projectPath); + const discoveryMetrics = structure.discoveryMetrics; + const limitSkip = structure.skipped?.find((item) => + item.reason === 'file-limit' || item.reason === 'directory-limit' || item.reason === 'entry-limit' + ); + if (discoveryMetrics) { + this.lastDiscovery = { + filesSelected: structure.files.length, + directoriesVisited: discoveryMetrics.directoriesScanned, + entriesScanned: discoveryMetrics.entriesScanned, + statsAttempted: discoveryMetrics.statCalls, + partial: Boolean(structure.partial || discoveryMetrics.stoppedEarly), + stopReason: limitSkip?.reason === 'file-limit' + ? 'maxFiles' + : limitSkip?.reason === 'directory-limit' + ? 'maxDirectories' + : limitSkip?.reason === 'entry-limit' + ? 'maxEntriesScanned' + : undefined, + durationMs: Date.now() - startedAt, + }; } + return { + files: this.filterCodeFiles(projectPath, structure.files), + skipped: (structure.skipped ?? []).map((skip) => ({ + file: skip.file, + reason: skip.reason, + size: skip.size, + })), + metrics: structure.discoveryMetrics, + }; + } catch { + return { files: [], skipped: [] }; } + } - // 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)) - ); + 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: [] }; } - - // Limit number of files - return filteredFiles.slice(0, this.options.maxFiles); + 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 async analyzeFiles(files: string[]): Promise> { - const analyses = new Map(); - const batchSize = 50; + private filterCodeFiles( + projectPath: string, + discoveredFiles: DiscoveredAnalysisFile[] + ): Array<{ path: string; size?: number }> { + const supported = new Set(Object.keys(LANGUAGE_EXTENSIONS)); + 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.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.path.includes(pattern))) + .sort((left, right) => left.path.localeCompare(right.path)); + } - 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( + candidates: Array<{ path: string; size?: number }> + ): Promise<{ + files: string[]; + skipped: SkippedAnalysisFile[]; + bytes: number; + }> { + const selected: string[] = []; + const skipped: SkippedAnalysisFile[] = []; + let bytes = 0; + + 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; + } + } - for (const analysis of results) { - analyses.set(analysis.filePath, analysis); + 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; } @@ -592,10 +931,23 @@ export class CodebaseAnalyzer { this.treeSitter.clearCache(); } + fileAnalysisCacheMetrics() { + return this.treeSitter.cacheMetrics(); + } + + discoveryMetrics(): import('./discovery').BoundedDiscoveryMetrics | undefined { + return this.lastDiscovery ? { ...this.lastDiscovery } : undefined; + } + /** * Shutdown LSP servers gracefully */ async shutdown(): Promise { + if (this.options.cacheEnabled) { + this.treeSitter.dispose?.(); + } else { + this.treeSitter.clearCache(); + } if (this.lspLayer) { await this.lspLayer.shutdown(); } @@ -671,9 +1023,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 analyses = await this.analyzeFiles(files); + return (await this.analyzeBundle(projectPath)).functionalPatterns; + } + 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/adapters/out/semantic/contextBuilder.ts b/src/harness/adapters/out/semantic/contextBuilder.ts index d07e2ab3..5848e6c8 100644 --- a/src/harness/adapters/out/semantic/contextBuilder.ts +++ b/src/harness/adapters/out/semantic/contextBuilder.ts @@ -15,6 +15,14 @@ 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'; +import { + discoverBoundedFiles, + isBoundedSnapshotFresh, + type BoundedDiscoveryMetrics, + type BoundedFreshnessSnapshot, +} from './discovery'; export interface ContextBuilderOptions extends AnalyzerOptions { /** Maximum symbols to include per category */ @@ -25,45 +33,136 @@ 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'; +export interface SemanticFreshnessMetrics { + discoveries: number; + filesSelected: number; + directoriesVisited: number; + entriesScanned: number; + partialDiscoveries: number; + entryLimitDiscoveries: number; + signalsChecked: number; + invalidations: number; +} + const DEFAULT_OPTIONS: Required = { useLSP: false, languages: ['typescript', 'javascript', 'python', 'go'], exclude: DEFAULT_EXCLUDE_PATTERNS, include: [], maxFiles: 5000, + maxTotalBytes: 256 * 1024 * 1024, + maxFileBytes: 2 * 1024 * 1024, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, + concurrency: 16, cacheEnabled: true, + fileAnalysisCacheMaxEntries: 5_000, + fileAnalysisCacheMaxBytes: 128 * 1024 * 1024, maxSymbolsPerCategory: 50, includeDocumentation: true, includeSignatures: true, maxContextLength: 32000, + semanticCacheMaxBytes: 64 * 1024 * 1024, }; export class SemanticContextBuilder { private analyzer: CodebaseAnalyzer; private options: Required; - private cachedContext: SemanticContext | null = null; - private cachedProjectPath: string | null = null; + private readonly semanticCacheBytesExplicit: boolean; + private readonly maxEntriesScannedExplicit: boolean; + private readonly semanticCaches = new Map; + signature: string; + fingerprint?: string; + 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, + }); } /** * Analyze the codebase and cache the result */ async analyze(projectPath: string): Promise { - if (this.cachedContext && this.cachedProjectPath === projectPath) { - return this.cachedContext; + const normalizedProjectPath = path.resolve(projectPath); + const owner = this.options.cacheEnabled + ? await this.semanticCacheForRepo(normalizedProjectPath) + : undefined; + 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; + if (freshness.fresh) { + const cached = owner.cache.get(owner.fingerprint); + if (cached) return cached; + } else { + discovered = await this.computeProjectFingerprint(normalizedProjectPath, owner.maxEntriesScanned); + 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); + if (cached) return cached; + } else { + owner.cache.clear(); + owner.freshness.invalidations += 1; + } + } } - this.cachedContext = await this.analyzer.analyze(projectPath); - this.cachedProjectPath = projectPath; - return this.cachedContext; + if (!discovered) { + discovered = await this.computeProjectFingerprint(normalizedProjectPath, owner.maxEntriesScanned); + 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); + 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; } /** @@ -805,8 +904,7 @@ export class SemanticContextBuilder { * Clear cached analysis */ clearCache(): void { - this.cachedContext = null; - this.cachedProjectPath = null; + for (const owner of this.semanticCaches.values()) owner.cache.clear(); this.analyzer.clearCache(); } @@ -814,6 +912,123 @@ export class SemanticContextBuilder { * Shutdown analyzer (cleanup LSP servers if enabled) */ 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 ?? [])]; + } + + 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) { + 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, + maxEntriesScanned: this.maxEntriesScannedExplicit ? this.options.maxEntriesScanned : configured.maxEntriesScanned, + }; + 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({ + maxEntries: limits.maxEntries, + maxBytes: limits.maxBytes, + ttlMs: 24 * 60 * 60 * 1000, + estimateBytes: context => this.estimateSemanticContextBytes(context), + }); + 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, + entryLimitDiscoveries: 0, + signalsChecked: 0, + invalidations: 0, + }, + }; + 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, 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, + }); + } + + 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; + if (metrics.stopReason === 'maxEntriesScanned') target.entryLimitDiscoveries += 1; + } + + 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..f80eceb7 100644 --- a/src/harness/adapters/out/semantic/contextCache.ts +++ b/src/harness/adapters/out/semantic/contextCache.ts @@ -11,8 +11,15 @@ * Thread safety: Node.js is single-threaded, so no mutex needed. */ -import * as fs from 'fs-extra'; import * as path from 'path'; +import { BoundedLruCache, type BoundedLruCacheMetrics } from '../../../domain/retention/boundedLruCache'; +import { loadRuntimeRetentionConfig } from '../../../application/retention/runtimeRetentionConfig'; +import { + discoverBoundedFiles, + isBoundedSnapshotFresh, + type BoundedFreshnessSnapshot, +} from './discovery'; +import { SemanticSnapshotService } from './semanticSnapshotService'; /** * A cached context entry with metadata for invalidation. @@ -20,10 +27,10 @@ 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; + freshnessFingerprint?: string; + freshnessSnapshot?: BoundedFreshnessSnapshot; + /** Content-aware identity that catches same-size writes with restored mtimes. */ + contentFingerprint?: string; } export interface ContextCacheOptions { @@ -31,18 +38,66 @@ 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; + /** Maximum relevant files selected while establishing freshness (default: 128). */ + 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; } 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; + entriesScanned: number; + partialDiscoveries: number; + entryLimitDiscoveries: number; + signalsChecked: number; + invalidations: number; +} export class ContextCache { - private readonly cache = new Map(); - private readonly ttlMs: number; + private readonly caches = new Map; + signature: string; + diagnostics: string[]; + maxEntriesScanned: number; + }>(); private readonly watchDirs: string[]; + private readonly options: ContextCacheOptions; + private readonly fingerprintService = new SemanticSnapshotService(true); + private readonly freshness: ContextCacheFreshnessMetrics = { + discoveries: 0, + filesSelected: 0, + directoriesVisited: 0, + entriesScanned: 0, + partialDiscoveries: 0, + entryLimitDiscoveries: 0, + signalsChecked: 0, + invalidations: 0, + }; constructor(options: ContextCacheOptions = {}) { - this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; + this.options = options; this.watchDirs = options.watchDirs ?? DEFAULT_WATCH_DIRS; } @@ -53,24 +108,19 @@ 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); - const entry = this.cache.get(key); + async get(repoPath: string, contextType: string, keyOptions?: unknown): Promise { + const cache = await this.cacheForRepo(repoPath); + const key = this.buildKey(repoPath, contextType, keyOptions); + const entry = 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) { - this.cache.delete(key); + const fresh = await this.isFresh(repoPath, entry); + if (!fresh) { + cache.delete(key); + this.freshness.invalidations += 1; return null; } @@ -84,14 +134,30 @@ 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); - const mtimeHash = await this.computeMtimeHash(repoPath); + 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 freshness = await this.captureFreshness(repoPath); - this.cache.set(key, { + // 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, - createdAt: Date.now(), - mtimeHash, + ...freshness, + contentFingerprint: this.options.fingerprintProvider + ? undefined + : await this.fingerprintService.captureRepoFingerprint(repoPath), + }); + 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, }); } @@ -99,61 +165,169 @@ export class ContextCache { * 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 { + for (const owner of this.caches.values()) owner.cache.dispose(); + this.caches.clear(); + } + + metrics(): BoundedLruCacheMetrics { + 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 ?? [])]; + } + + freshnessMetrics(): ContextCacheFreshnessMetrics { + return { ...this.freshness }; } /** * 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 `${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; } - /** - * 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 mtimes: number[] = []; - - 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)); - } catch { - // Directory doesn't exist — that's fine, skip it - mtimes.push(0); + 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, + maxEntriesScanned: this.options.freshnessMaxEntriesScanned ?? configured.maxEntriesScanned, + }; + 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({ + 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 ?? '')) + + Buffer.byteLength(entry.contentFingerprint ?? ''), + }); + this.caches.set(normalized, { + cache, + signature, + diagnostics: loaded.diagnostics, + maxEntriesScanned: limits.maxEntriesScanned, + }); + return cache; + } - return mtimes.join('-'); + 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); + } + } + } + + 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, + 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 }; + } + + 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; + if (entry.freshnessSnapshot.partial) return false; + const result = await isBoundedSnapshotFresh(entry.freshnessSnapshot); + this.freshness.signalsChecked += result.signalsChecked; + if (result.fresh) { + return entry.contentFingerprint === undefined + || await this.fingerprintService.captureRepoFingerprint(repoPath) === entry.contentFingerprint; + } + 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; + } + 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..a62f4f3c --- /dev/null +++ b/src/harness/adapters/out/semantic/discovery/boundedFileDiscovery.ts @@ -0,0 +1,260 @@ +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; +} + +/** + * 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; +} + +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; + snapshot: BoundedFreshnessSnapshot; + metrics: BoundedDiscoveryMetrics; +} + +export interface BoundedFileDiscoveryOptions { + roots?: string[]; + maxFiles: number; + maxDirectories?: number; + maxEntriesScanned?: 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__', +]); + +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('/'); +} + +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`); + } + 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 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 ?? [])] + .map(value => value.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '')); + 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 partial = false; + let stopReason: BoundedDiscoveryStopReason | undefined; + const stopPartial = (reason: BoundedDiscoveryStopReason) => { + partial = true; + stopReason ??= reason; + }; + + 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); + for await (const entry of directory) { + entriesScanned += 1; + const absolute = path.join(directoryPath, entry.name); + const relative = normalizedRelative(root, absolute); + if (entry.isDirectory()) { + 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); + } + } 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 (files.length >= maxFiles) { + stopPartial('maxFiles'); + break; + } + } + } catch { /* missing or unreadable roots are represented by their absence */ } + } + 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, roots: rootSignals, 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, + statsAttempted, + partial, + stopReason, + 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(); + // 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 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)); + 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'; 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..4973b8e4 --- /dev/null +++ b/src/harness/adapters/out/semantic/lsp/__tests__/fixtures/fake-lsp-server.js @@ -0,0 +1,109 @@ +'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.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) { + const content = JSON.stringify(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') { + 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' } }); + } 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: {} } }); + } + return; + } + + if (message.method === 'shutdown') { + if (!mode.startsWith('ignore-shutdown')) { + send({ jsonrpc: '2.0', id: message.id, result: null }); + } + return; + } + + if (message.method === 'exit') { + if (!mode.startsWith('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..c73a8870 --- /dev/null +++ b/src/harness/adapters/out/semantic/lsp/__tests__/lspLayer.lifecycle.test.ts @@ -0,0 +1,322 @@ +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, + MAX_LSP_BODY_BYTES, +} 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, attackSize?: number): LSPServerConfig { + const args = [FIXTURE, mode, pidFile]; + if (attackSize !== undefined) args.push(String(attackSize)); + return { command: process.execPath, args }; +} + +interface InspectableHandle { + process: ChildProcess; + pendingRequests: Map; + timers: Set; + receiver: { bufferedByteLength: number }; +} + +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 (await 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.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.receiver.bufferedByteLength).toBe(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) }); + + 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(); + }); + + 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) }); + + 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.receiver.bufferedByteLength).toBe(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/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..814ab230 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 { spawn, execFile, ChildProcess } from 'child_process'; +import { createHash } from 'crypto'; import * as path from 'path'; import { TypeInfo, @@ -30,6 +31,179 @@ 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; + timers: Set; + receiver: LSPFrameAccumulator; + startedAt: number; + terminationReason?: string; + forcedKill: boolean; + exited: boolean; + closed: boolean; + 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; + requestTimeoutMs?: number; + shutdownTimeoutMs?: number; + terminationGraceMs?: number; + maxHeaderBytes?: number; + maxBodyBytes?: number; + maxReceiveBufferBytes?: number; + onLifecycleEvent?: (event: LSPLifecycleEvent) => void; +} + const LSP_SERVER_CONFIGS: Record = { typescript: { command: 'typescript-language-server', @@ -48,85 +222,164 @@ 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 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 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 maxHeaderBytes: number; + private readonly maxBodyBytes: number; + private readonly maxReceiveBufferBytes: 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.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; + } 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; + + const existing = this.handles.get(key); + if (existing?.state === 'ready') return true; + if (existing?.state === 'starting') return existing.initialization; + if (existing) return false; + + const config = this.serverConfigs[language]; + if (!config) return false; + + 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, + }); - 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); - }); - - // 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); - }); - - this.servers.set(language, serverProcess); - this.buffers.set(language, ''); - - // 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(), + timers: new Set(), + receiver: new LSPFrameAccumulator( + this.maxHeaderBytes, + this.maxBodyBytes, + this.maxReceiveBufferBytes + ), + startedAt: Date.now(), + forcedKill: false, + exited: false, + closed: false, + }; - 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`)); + // 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; + }); + } - serverProcess.on('exit', () => { - this.cleanup(language); - }); + private markClosed(handle: ServerHandle): void { + if (handle.closed) return; + handle.closed = true; + } - // 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 +390,333 @@ 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) { + 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'; + 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; - - if (buffer.length < headerEnd + contentLength) break; - - const content = buffer.slice(headerEnd, headerEnd + contentLength); - buffer = buffer.slice(headerEnd + contentLength); + 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); + }); + } + private handleServerData(handle: ServerHandle, data: Buffer): void { + if (handle.state === 'stopping' || handle.state === 'stopped') return; + const error = handle.receiver.accept(data, (body) => { 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. } - } + }); + if (error) this.failProtocol(handle, error); + } - this.buffers.set(language, buffer); + private failProtocol(handle: ServerHandle, detail: string): void { + if ( + handle.state === 'failed' || + handle.state === 'stopping' || + handle.state === 'stopped' + ) return; + + const reason = `protocol overflow: ${detail}`; + handle.receiver.reset(); + 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(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); + this.clearHandleTimeout(handle, 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); + const timeout = this.setHandleTimeout(handle, () => { + 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 })) { + this.clearHandleTimeout(handle, 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()) { + this.clearHandleTimeout(handle, 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 (this.processTreeIsAlive(handle)) { + const exitedNaturally = + waitForNaturalExit && + (await this.waitForProcessTreeExit(handle, this.terminationGraceMs)); + if (!exitedNaturally) { + await this.signalProcessTree(handle, 'SIGTERM'); + if (!(await this.waitForProcessTreeExit(handle, this.terminationGraceMs))) { + handle.forcedKill = true; + 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); + } + } + } + + handle.state = 'stopped'; + this.emitHandleLifecycle(handle, 'stopped', { + reason, + exitCode: handle.exitCode, + exitSignal: handle.exitSignal, + forcedKill: handle.forcedKill, + }); + this.releaseHandle(handle); + })(); + return handle.stopping; + } + + 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 { - server.stdin.write(header + content); + handle.process.kill(signal); } catch { - // Silently ignore send failures + // A concurrent process exit is equivalent to successful termination. + } + } + + private taskkill(pid: number, force: boolean): Promise { + return new Promise((resolve) => { + 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 cleanup(language: string): void { - this.servers.delete(language); - this.initialized.delete(language); - this.buffers.delete(language); + 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, + 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.receiver.reset(); + handle.process.stdin?.removeAllListeners(); + handle.process.stdout?.removeAllListeners(); + handle.process.stderr?.removeAllListeners(); + handle.process.removeAllListeners(); + } + + private emitHandleLifecycle( + handle: ServerHandle, + state: LSPServerState, + details: Partial = {} + ): void { + this.emitLifecycle( + handle.language, + handle.projectPath, + state, + handle.pendingRequests.size, + { pid: handle.process.pid, ...details } + ); + } - // 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 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 +725,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 +750,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 +767,8 @@ export class LSPLayer { })); } } catch { - // LSP request failed - return empty array + // Fall back to an empty result. } - return []; } @@ -315,16 +780,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 +797,8 @@ export class LSPLayer { }; } } catch { - // LSP request failed - return null + // Fall back to the non-LSP analysis. } - return null; } @@ -348,16 +810,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 +826,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 +842,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 +852,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); } } diff --git a/src/harness/adapters/out/semantic/semanticSnapshotService.ts b/src/harness/adapters/out/semantic/semanticSnapshotService.ts index f4260f92..46a04669 100644 --- a/src/harness/adapters/out/semantic/semanticSnapshotService.ts +++ b/src/harness/adapters/out/semantic/semanticSnapshotService.ts @@ -1,15 +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'; @@ -48,6 +52,11 @@ export interface SemanticSnapshotWriteResult { manifest: SemanticSnapshotManifest; snapshotDir: string; publishedSummaryPath: string; + metrics: { + generationMs: number; + publicationMs: number; + stabilizationAttempts: number; + }; } export interface SemanticSnapshotReadOptions { @@ -91,8 +100,10 @@ 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 DEFAULT_FINGERPRINT_CACHE_TTL_MS = 5 * 60_000; const SECTION_FILENAMES: Record = { stack: 'stack.json', @@ -107,62 +118,161 @@ 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; + 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; + partial: boolean; + skipped: RepoDiscoverySkip[]; + 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>(); - async captureRepoFingerprint(repoPath: string): Promise { - return this.computeRepoFingerprint(repoPath); + constructor( + private readonly cacheEnabled = true, + 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) + ) + ), + 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 + ) + ) + ), + }; + } + + private readonly fingerprintLimits: FileMappingLimits; + + async captureRepoFingerprint(repoPath: string, discovery?: RepoStructure): Promise { + return (await this.computeRepoFingerprint(repoPath, discovery)).fingerprint; + } + + async captureRepoFingerprintWithMetrics( + repoPath: string, + discovery?: RepoStructure + ): Promise { + return this.computeRepoFingerprint(repoPath, discovery); } async writeSnapshot( @@ -172,27 +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); - - const artifacts = await this.buildSnapshotArtifacts(repoStructure, { - ...options, - repoFingerprint, - }); - const manifest = await this.publishSnapshotArtifacts({ - outputDir, - snapshotDir, - publishedSummaryPath, - artifacts, - }); + 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, - }; + throw new RepositoryChangingError(repoStructure.rootPath, MAX_REFRESH_ATTEMPTS); } async ensureFreshSummary( @@ -301,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 repoFingerprint = await this.computeRepoFingerprint(repoPath); - const repoStructure = await fileMapper.mapRepository(repoPath); - const artifacts = await this.buildSnapshotArtifacts(repoStructure, { - outputDir, - repoFingerprint, - }); - const currentFingerprint = await this.computeRepoFingerprint(repoPath); - - if (currentFingerprint !== repoFingerprint) { - continue; - } - - const manifest = await this.publishSnapshotArtifacts({ - outputDir, - snapshotDir, - publishedSummaryPath, - artifacts, - }); - const publishedFingerprint = await this.computeRepoFingerprint(repoPath); - - if (publishedFingerprint !== repoFingerprint) { - continue; - } - - return { - summary: artifacts.summary, - manifest, - snapshotDir, - publishedSummaryPath, - }; - } - - throw new Error( - `Semantic snapshot refresh could not stabilize for ${repoPath}; repository changed during refresh.` - ); + const repoStructure = await fileMapper.mapRepository(repoPath); + return this.writeSnapshot(repoStructure, { outputDir }); })(); SemanticSnapshotService.inFlightRefreshes.set(refreshKey, refreshPromise); @@ -424,14 +524,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 + ); + semantics ??= bundle.context; + functionalPatterns ??= bundle.functionalPatterns; } if (!stackInfo) { @@ -448,7 +546,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,46 +824,174 @@ 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('**/*', { - cwd: repoPath, - nodir: true, - dot: true, - ignore: FINGERPRINT_IGNORE_PATTERNS, - }); - - const relevantFiles = files - .filter((filePath) => this.isFingerprintRelevant(filePath)) - .sort(); - - const hash = createHash('sha1'); - for (const relativePath of relevantFiles) { - const absolutePath = path.join(repoPath, relativePath); + private async computeRepoFingerprint( + repoPath: string, + discovery?: RepoStructure + ): Promise { + const startedAt = Date.now(); + const boundedDiscovery = discovery ?? await new FileMapper([], this.fingerprintLimits) + .mapRepository(repoPath); + const discoveries = discovery ? 0 : 1; + 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 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}`; try { - hash.update(`${relativePath}\0`); - hash.update(await fs.readFile(absolutePath)); - hash.update('\0'); + 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 + ? this.fingerprintCache.get(cacheKey, metadata) + : undefined; + if (cachedHash) { + contentHash = cachedHash; + cacheHits += 1; + } else { + const boundedHash = await this.hashFileContentBounded( + absolutePath, + Math.min( + this.fingerprintLimits.maxFileBytes, + this.fingerprintLimits.maxTotalBytes - selectedBytes + ) + ); + bytesRead += boundedHash.bytesRead; + contentReads += 1; + 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' }); } } - return hash.digest('hex'); - } + 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`); + } - private isFingerprintRelevant(relativePath: string): boolean { - if (FINGERPRINT_ROOT_FILES.has(relativePath)) { - return true; + // 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. } - const topLevel = relativePath.split('/')[0]; - if (['src', 'lib', 'bin', 'app', 'packages', 'scripts'].includes(topLevel)) { - return true; + if (this.cacheEnabled) { + this.fingerprintCache.reconcileRepo(repoPrefix, liveCacheKeys); } - return FINGERPRINT_CODE_EXTENSIONS.has(path.extname(relativePath).toLowerCase()); + return { + fingerprint: hash.digest('hex'), + files: filesHashed, + bytesRead, + contentReads, + cacheHits, + discoveries, + partial, + skipped, + durationMs: Date.now() - startedAt, + }; + } + + private recordFingerprintSkip( + skipped: RepoDiscoverySkip[], + skip: RepoDiscoverySkip + ): void { + if (skipped.length < 1_000) skipped.push(skip); + } + + 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; + } + 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(); + } } + } diff --git a/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts b/src/harness/adapters/out/semantic/treeSitter/treeSitterLayer.ts index 121dc2db..b6c16660 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,15 +23,38 @@ interface CacheEntry { } export class TreeSitterLayer { - private cache: Map = new Map(); + private cache: BoundedLruCache; + private readonly cacheEnabled: boolean; + private cacheSignature: string; 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; + 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)), + }); + } + + 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 { try { // Try to load tree-sitter dynamically @@ -70,7 +94,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 +108,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 +585,25 @@ 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; + } + + cacheMetrics() { + return this.cache.metrics(); + } + + dispose(): void { + this.cache.dispose(); + } + async isTreeSitterAvailable(): Promise { await this.ready; return this.treeSitterAvailable; diff --git a/src/harness/adapters/out/semantic/types.ts b/src/harness/adapters/out/semantic/types.ts index 2b38577d..eaf74b79 100644 --- a/src/harness/adapters/out/semantic/types.ts +++ b/src/harness/adapters/out/semantic/types.ts @@ -190,7 +190,19 @@ 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; + /** Maximum directories opened while discovering repository files. */ + maxDirectoriesScanned?: number; + /** Maximum raw directory entries inspected before returning a partial analysis. */ + maxEntriesScanned?: number; cacheEnabled?: boolean; + fileAnalysisCacheMaxEntries?: number; + fileAnalysisCacheMaxBytes?: number; } export interface LSPServerConfig { diff --git a/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts b/src/harness/adapters/out/sensors/__tests__/testsPassing.test.ts index f613a95b..e6e49fb9 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; @@ -18,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, @@ -35,6 +49,55 @@ 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' }, + }); + 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 +150,140 @@ 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('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', + 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('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', + 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' }); + }); + + 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/__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/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 a3e53e7d..ac9f983c 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 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 * runners. @@ -16,16 +17,31 @@ */ import { spawn } from 'child_process'; +import { closeSync, openSync, promises as fs, writeSync } 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, + resolveSubprocessOutputLimits, + subprocessSpawnOptions, + terminateProcessTree, + type SubprocessOutputLimitsInput, +} from '../../../domain/execution'; +import { projectJestResultFile, type ProjectedJestResultRead } from './jestResultProjector'; export interface TestsPassingOptions { kind?: 'jest' | 'exit-code'; testCommand?: string[]; timeoutMs?: number; + tailBytes?: number; + hardOutputLimitBytes?: number; } export interface TestsPassingReport { @@ -37,9 +53,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 +69,72 @@ 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 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, + 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 = {}, + 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, { @@ -79,64 +142,123 @@ export function runShell( shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: process.env, + ...subprocessSpawnOptions(), }); } catch (err) { - resolve({ - exitCode: null, - stdout: '', - stderr: '', - timedOut: false, - spawnError: err instanceof Error ? err.message : String(err), - }); + if (structuredStdoutFd !== undefined) closeSync(structuredStdoutFd); + 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 exitCodeSeen: number | null = null; + let termination: Promise | undefined; - child.stdout?.on('data', (c: Buffer) => stdoutChunks.push(c)); - child.stderr?.on('data', (c: Buffer) => stderrChunks.push(c)); + 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; + requestTermination(); + } + }; - 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'); + requestTermination(); }, timeoutMs); - const finish = (exitCode: number | null, spawnError?: Error) => { + 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, - 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)); - child.on('close', (code) => finish(code)); + // Wait for close after error/kill so the child is always reaped before the + // promise resolves. + child.on('error', (err) => { spawnError = err; }); + 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 = ProjectedJestResultRead; + +export async function readJestResultFile(resultPath: string): Promise { + return projectJestResultFile(resultPath); +} + +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( @@ -144,102 +266,118 @@ export async function executeTestsPassing( input: HarnessSensorExecutionInput ): Promise { const opts = readOptions(input); + let resultDirectory: string | undefined; + let resultPath: string | undefined; + let command = opts.testCommand; + let structuredStdoutPath: string | undefined; + if (opts.kind === 'jest') { + resultDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-jest-')); + resultPath = path.join(resultDirectory, 'result.json'); + if (opts.usesDefaultCommand) command = [...DEFAULT_JEST_COMMAND, '--outputFile', resultPath]; + else structuredStdoutPath = 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, + }, structuredStdoutPath); - 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 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 { + status: 'failed', + summary: 'tests-passing: resultFileTooLarge', + evidence: [`command: ${command.join(' ')}`], + details, + }; + } + if (fileRead?.status !== 'ok') { + 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 report: TestsPassingReport = fileRead.value; + const { numPassedTests, numFailedTests, numTotalTestSuites, failures } = report; + + 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/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/actionService.ts b/src/harness/application/actions/actionService.ts index c24cc28b..2ff1b849 100644 --- a/src/harness/application/actions/actionService.ts +++ b/src/harness/application/actions/actionService.ts @@ -84,9 +84,18 @@ export interface HarnessActionInput { replayId?: string; includePayloads?: boolean; maxEvents?: number; + maxBytes?: number; datasetId?: string; sessionIds?: string[]; includeSuccessfulSessions?: boolean; + limit?: number; + cursor?: string; + direction?: 'oldest' | 'newest'; + createdAfter?: string; + 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'; @@ -195,9 +204,12 @@ export class HarnessActionService { }), }; case 'listSessions': + 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, - sessions: await this.executionService.listSessions(), + sessions, + page: sessionPagination, }; case 'getSession': return { @@ -215,9 +227,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, maxBytes: params.maxBytes }); + const { items: traces, ...tracePagination } = tracePage; return { success: true, - traces: await this.executionService.listTraces(params.sessionId!), + traces, + page: tracePagination, }; case 'addArtifact': return { @@ -231,9 +246,12 @@ export class HarnessActionService { }), }; case 'listArtifacts': + 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, - artifacts: await this.executionService.listArtifacts(params.sessionId!), + artifacts, + page: artifactPagination, }; case 'checkpoint': return { @@ -312,9 +330,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 { @@ -338,9 +359,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 { @@ -348,12 +372,17 @@ export class HarnessActionService { replay: await this.executionService.replaySession(params.sessionId!, { includePayloads: params.includePayloads, maxEvents: params.maxEvents, + maxBytes: params.maxBytes, + cursor: params.cursor, }), }; case 'listReplays': + 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, - replays: await this.executionService.listReplays(params.sessionId), + replays, + page: replayPagination, }; case 'getReplay': return { @@ -366,12 +395,19 @@ export class HarnessActionService { dataset: await this.executionService.buildFailureDataset({ sessionIds: params.sessionIds, includeSuccessfulSessions: params.includeSuccessfulSessions, + concurrency: params.concurrency, + maxFailures: params.maxFailures, + maxFailureBytes: params.maxFailureBytes, + maxBytes: params.maxBytes, }), }; case 'listDatasets': + const datasetPage = await this.executionService.listDatasetPage({ limit: params.limit, cursor: params.cursor, maxBytes: params.maxBytes }); + 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/actions/exploreActionService.ts b/src/harness/application/actions/exploreActionService.ts index 7f9e5cd1..a5805136 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({ @@ -56,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..d48b8b89 --- /dev/null +++ b/src/harness/application/context/__tests__/boundedExplore.load.test.ts @@ -0,0 +1,62 @@ +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); + } + }); + + 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 new file mode 100644 index 00000000..d85d919c --- /dev/null +++ b/src/harness/application/context/__tests__/boundedExplore.test.ts @@ -0,0 +1,214 @@ +import * as fsExtra from 'fs-extra'; +import { promises as fs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { + listBoundedExploreFiles, + 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('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)); + 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); + }); + + 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/__tests__/contextTools.test.ts b/src/harness/application/context/__tests__/contextTools.test.ts index 40e76dec..cb95f58d 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'; @@ -9,6 +10,11 @@ import { listFilesToFillTool, } 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'; +import { FileMapper } from '../../../../utils/fileMapper'; describe('contextTools sensors scaffolding', () => { let tempDir: string; @@ -29,9 +35,111 @@ 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'); + const docs = jest.spyOn(DocumentationGenerator.prototype, 'generateDocumentation'); + const agents = jest.spyOn(AgentGenerator.prototype, 'generateAgentPrompts'); + const snapshot = jest.spyOn(SemanticSnapshotService.prototype, 'writeSnapshot'); + + await initializeContextTool.execute!( + { + repoPath: tempDir, + type: 'both', + semantic: true, + generateQA: false, + skipContentGeneration: true, + }, + toolExecutionContext + ); + + expect(analyzeBundle).toHaveBeenCalledTimes(1); + const analyzed = await analyzeBundle.mock.results[0].value; + 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(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, + functionalPatterns: analyzed.functionalPatterns, + })); + }); + + it('performs one bundle discovery plus publication verification per operation', async () => { + const repositoryDiscovery = jest.spyOn(FileMapper.prototype, 'mapRepository'); + + 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(4); + 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('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/analysisBundle.ts b/src/harness/application/context/analysisBundle.ts new file mode 100644 index 00000000..34f6e784 --- /dev/null +++ b/src/harness/application/context/analysisBundle.ts @@ -0,0 +1,48 @@ +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, + maxDirectoriesScanned: 10_000, + maxEntriesScanned: 100_000, + concurrency: 16, +}); + +export interface AnalysisMetrics extends SemanticAnalysisMetrics { + fingerprint: { + files: number; + bytesRead: number; + contentReads: number; + cacheHits: number; + discoveries: 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/boundedExplore.ts b/src/harness/application/context/boundedExplore.ts new file mode 100644 index 00000000..dcf4183b --- /dev/null +++ b/src/harness/application/context/boundedExplore.ts @@ -0,0 +1,672 @@ +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 { + 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 const DEFAULT_EXPLORE_REGEX_TIMEOUT_MS = 100; + +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; + 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 { + 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 ListCursor { + fileOffset: number; +} + +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}'; + +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) { + 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 }; + } + } +} + +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, + 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 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 matcher = await BoundedRegexMatcher.create(input.pattern, regexTimeoutMs); + 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 regexTimedOut = false; + let nextCursor: string | undefined; + let returnedBytes = 2; + + 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; + } + 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; + 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; + } + 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 || regexTimedOut; + return { + 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, + 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, + regexTimedOut, + regexTimeoutMs, + 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 26e946ef..019c0b66 100644 --- a/src/harness/application/context/contextTools.ts +++ b/src/harness/application/context/contextTools.ts @@ -8,7 +8,12 @@ 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, + SemanticFingerprintCache, + 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'; @@ -28,6 +33,25 @@ 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'; +import { + boundedLimit, + RUNTIME_HISTORY_LIMITS, +} from '../history/runtimeHistory'; +import { + listBoundedExploreFiles, + readBoundedExploreFile, + searchBoundedCode, + type BoundedExploreListResult, +} from './boundedExplore'; + +// 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; @@ -316,20 +340,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, @@ -341,24 +368,35 @@ 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?: BoundedExploreListResult['page']; + 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('/')); - return { - success: true, - files, - count: files.length, - pattern - }; + 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' + ); + return await listBoundedExploreFiles({ + pattern, + cwd: resolvedCwd, + ignore: resolvedIgnore, + limit, + cursor: input.cursor, + }); } catch (error) { return { success: false, @@ -425,7 +463,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; @@ -458,52 +501,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, @@ -581,6 +592,7 @@ export const initializeContextTool = createInternalTool< skipContentGeneration?: boolean; generateQA?: boolean; generateSkills?: boolean; + cacheEnabled?: boolean; }, Record >( @@ -599,6 +611,7 @@ export const initializeContextTool = createInternalTool< skipContentGeneration = true, generateQA = false, generateSkills = true, + cacheEnabled = true, } = input; const resolvedRepoPath = path.resolve(repoPath); @@ -642,12 +655,72 @@ export const initializeContextTool = createInternalTool< const fileMapper = new FileMapper(exclude); const repoStructure = await fileMapper.mapRepository(resolvedRepoPath, include); + let semanticBundle: SemanticAnalysisBundle | undefined; + 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 { + fingerprintMetrics = await snapshotService!.captureRepoFingerprintWithMetrics( + resolvedRepoPath, + repoStructure + ); + semanticFingerprint = fingerprintMetrics.fingerprint; + semanticBundle = await analyzer.analyzeBundle( + resolvedRepoPath, + repoStructure + ); + } 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 (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, + contentReads: fingerprintMetrics.contentReads, + cacheHits: fingerprintMetrics.cacheHits, + discoveries: fingerprintMetrics.discoveries, + durationMs: fingerprintMetrics.durationMs, + }, + }, + }; + } + + if (!disableFiltering) { if (overrideProjectType) { projectType = overrideProjectType; classification = { @@ -657,7 +730,7 @@ export const initializeContextTool = createInternalTool< reasoning: ['Project type manually specified'], }; } else { - classification = classifyProject(stackInfo); + classification = classifyProject(detectedStackInfo!); projectType = classification.primaryType; } } @@ -672,7 +745,23 @@ export const initializeContextTool = createInternalTool< docsGenerated = await docGenerator.generateDocumentation( repoStructure, outputDir, - { semantic, filteredDocs }, + { + semantic, + filteredDocs, + semanticContext: semanticBundle?.context, + functionalPatterns: semanticBundle?.functionalPatterns, + stackInfo: detectedStackInfo, + repoFingerprint: semanticFingerprint, + cacheEnabled, + analysisBundle, + snapshotService, + onSnapshotMetrics: (metrics) => { + if (analysisBundle) { + analysisBundle.metrics.durationsMs.generation = metrics.generationMs; + analysisBundle.metrics.durationsMs.publication = metrics.publicationMs; + } + }, + }, false ); } @@ -716,7 +805,15 @@ export const initializeContextTool = createInternalTool< agentsGenerated = await agentGenerator.generateAgentPrompts( repoStructure, outputDir, - { semantic, filteredAgents, availableSkills }, + { + semantic, + filteredAgents, + availableSkills, + semanticContext: semanticBundle?.context, + stackInfo: detectedStackInfo, + cacheEnabled, + analysisBundle, + }, false ); } @@ -861,6 +958,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 ? { @@ -1158,7 +1263,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/index.ts b/src/harness/application/context/index.ts index e1c71169..0b490c7d 100644 --- a/src/harness/application/context/index.ts +++ b/src/harness/application/context/index.ts @@ -1,4 +1,6 @@ export * from './contextService'; export * from './contextTools'; +export * from './analysisBundle'; +export * from './boundedExplore'; 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 9a88fde8..6650557d 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[]; @@ -40,6 +41,12 @@ interface AgentGenerationConfig { autoFill?: boolean; /** Available skills that agents can reference */ availableSkills?: AvailableSkill[]; + /** Operation-scoped data supplied by context init. */ + semanticContext?: SemanticContext; + stackInfo?: StackInfo; + cacheEnabled?: boolean; + /** Preferred operation-scoped input from context init. */ + analysisBundle?: AnalysisBundle; } /** @@ -116,24 +123,31 @@ 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.analysisBundle?.semanticContext ?? 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 + )).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; } } // Detect stack info for autoFill - let stackInfo: StackInfo | undefined; - if (normalizedConfig.autoFill) { + let stackInfo = normalizedConfig.analysisBundle?.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..ca202cf0 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, @@ -17,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. @@ -57,6 +63,21 @@ 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; + cacheEnabled?: boolean; + onSnapshotMetrics?: (metrics: { + generationMs: number; + publicationMs: number; + stabilizationAttempts: number; + }) => void; + /** Preferred operation-scoped input from context init. */ + analysisBundle?: AnalysisBundle; + /** Operation-owned service; avoids rebuilding fingerprint cache ownership. */ + snapshotService?: SemanticSnapshotService; } export class DocumentationGenerator { @@ -72,29 +93,44 @@ 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) + ? config.snapshotService ?? new SemanticSnapshotService(config.cacheEnabled ?? true) + : null; // Perform semantic analysis if enabled - let semantics: SemanticContext | undefined; - let snapshotFingerprint: string | undefined; - if (config.semantic) { + 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); - 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); + snapshotFingerprint = await snapshotService!.captureRepoFingerprint( + repoStructure.rootPath, + repoStructure + ); + const bundle = await this.analyzer.analyzeBundle( + repoStructure.rootPath, + repoStructure + ); + 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; } } // Detect stack info for codebase map and autoFill - let stackInfo; - if (semantics || config.autoFill) { + let stackInfo = config.analysisBundle?.stackInfo ?? config.stackInfo; + if (!stackInfo && (semantics || config.autoFill)) { try { const stackDetector = new StackDetector(); stackInfo = await stackDetector.detect(repoStructure.rootPath); @@ -111,8 +147,10 @@ export class DocumentationGenerator { outputDir, semantics, stackInfo, + functionalPatterns, repoFingerprint: snapshotFingerprint, }); + config.onSnapshotMetrics?.(snapshot.metrics); GeneratorUtils.logProgress( `Created semantic snapshot summary at ${path.relative(outputDir, snapshot.publishedSummaryPath)}`, 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 b9bde628..e682cce3 100644 --- a/src/harness/application/contracts/taskContractsService.ts +++ b/src/harness/application/contracts/taskContractsService.ts @@ -14,9 +14,20 @@ import { resolveRuntimeLayoutFromRepo, type RuntimeLayout } from '../../../share import type { HarnessArtifactRecord, HarnessRuntimeStatePort, - HarnessTraceRecord, } from '../../adapters/out/runtimeState/runtimeStateService'; import type { HarnessSensorRun } from '../sensors/sensorsService'; +import { + boundedLimit, + boundedPageBytes, + decodeHistoryCursor, + encodeHistoryCursor, + MAX_RUNTIME_HISTORY_PAGE_BYTES, + queryBinding, + RUNTIME_HISTORY_LIMITS, + serializedHistoryItemBytes, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../history/runtimeHistory'; /** * Structured artifact requirement. @@ -187,6 +198,17 @@ export interface HarnessHandoffContract { metadata?: Record; } +export interface BoundedSessionContracts { + items: T[]; + total: number; + nextCursor?: string; + hasMore: boolean; + returnedBytes: number; + byteBudget: number; + byteLimited: boolean; + oversizedRecordsSkipped: number; +} + export interface HarnessTaskCompletionResult { taskId: string; sessionId?: string; @@ -296,6 +318,100 @@ 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 byteBudget = boundedPageBytes(query.maxBytes, '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: Array<{ contract: HarnessTaskContract; bytes: number }> = []; + let recordsScanned = 0; + let oversizedRecordsSkipped = 0; + const directory = await fs.opendir(this.tasksPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const file = path.join(this.tasksPath, entry.name); + if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { + oversizedRecordsSkipped += 1; + continue; + } + const contract = await fs.readJson(file) 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; + const bytes = serializedHistoryItemBytes(contract); + if (bytes + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + selected.push({ contract, bytes }); + selected.sort((left, right) => { + const comparison = left.contract.updatedAt.localeCompare(right.contract.updatedAt) + || left.contract.id.localeCompare(right.contract.id); + return direction === 'newest' ? -comparison : comparison; + }); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const items: HarnessTaskContract[] = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected.slice(0, limit + 1)) { + if (items.length === limit) break; + const candidateTotal = returnedBytes + candidate.bytes + (items.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + byteLimited = true; + break; + } + items.push(candidate.contract); + returnedBytes = candidateTotal; + } + const hasMore = selected.length > items.length; + 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, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, + cursorVersion: 1, + partial: hasMore || oversizedRecordsSkipped > 0, + durationMs: Date.now() - started, + }; + } + + async listSessionTaskContracts( + sessionId: string, + limit = 100, + maxBytes?: number, + cursor?: string + ): Promise> { + return this.listBoundedSessionContracts( + this.tasksPath, + sessionId, + boundedLimit(limit, 100, 1000, 'session task contracts'), + boundedPageBytes(maxBytes, 'session task contracts'), + cursor, + 'session-task-contracts' + ); + } + async getTaskContract(taskId: string): Promise { const filePath = await this.taskFile(taskId); if (!(await fs.pathExists(filePath))) { @@ -371,16 +487,180 @@ 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 byteBudget = boundedPageBytes(query.maxBytes, '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: Array<{ contract: HarnessHandoffContract; bytes: number }> = []; + let recordsScanned = 0; + let oversizedRecordsSkipped = 0; + const directory = await fs.opendir(this.handoffsPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + const file = path.join(this.handoffsPath, entry.name); + if ((await fs.stat(file)).size > MAX_RUNTIME_HISTORY_PAGE_BYTES) { + oversizedRecordsSkipped += 1; + continue; + } + const contract = await fs.readJson(file) 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; + const bytes = serializedHistoryItemBytes(contract); + if (bytes + 2 > byteBudget) { + oversizedRecordsSkipped += 1; + continue; + } + selected.push({ contract, bytes }); + selected.sort((left, right) => { + const comparison = left.contract.createdAt.localeCompare(right.contract.createdAt) + || left.contract.id.localeCompare(right.contract.id); + return direction === 'newest' ? -comparison : comparison; + }); + if (selected.length > limit + 1) selected.pop(); + } catch { /* skip corrupt records */ } + } + const items: HarnessHandoffContract[] = []; + let returnedBytes = 2; + let byteLimited = false; + for (const candidate of selected.slice(0, limit + 1)) { + if (items.length === limit) break; + const candidateTotal = returnedBytes + candidate.bytes + (items.length > 0 ? 1 : 0); + if (candidateTotal > byteBudget) { + byteLimited = true; + break; + } + items.push(candidate.contract); + returnedBytes = candidateTotal; + } + const hasMore = selected.length > items.length; + 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, + returnedBytes, + byteBudget, + byteLimited, + oversizedRecordsSkipped, + cursorVersion: 1, + partial: hasMore || oversizedRecordsSkipped > 0, + durationMs: Date.now() - started, + }; + } + + async listSessionHandoffContracts( + sessionId: string, + limit = 100, + maxBytes?: number, + cursor?: string + ): Promise> { + return this.listBoundedSessionContracts( + this.handoffsPath, + sessionId, + boundedLimit(limit, 100, 1000, 'session handoff contracts'), + boundedPageBytes(maxBytes, 'session handoff contracts'), + cursor, + 'session-handoff-contracts' + ); + } + + private async listBoundedSessionContracts( + directoryPath: string, + sessionId: string, + limit: 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; + const directory = await fs.opendir(directoryPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json')) continue; + try { + 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; + if (boundary && `${contract.createdAt}\0${contract.id}` <= `${boundary.createdAt}\0${boundary.id}`) continue; + 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) + ); + if (selected.length > limit + 1) selected.pop(); + } catch { + // A malformed unrelated contract must not make replay unavailable. + } + } + const chosen: typeof selected = []; + let returnedBytes = 2; + let byteLimited = false; + 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) { + 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); + 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, + oversizedRecordsSkipped, + }; + } + async evaluateTaskCompletion(taskId: string, sessionId?: string): Promise { const contract = await this.getTaskContract(taskId); if (!contract) { 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 +668,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..e1eaf73d 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,161 @@ 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); + }); + + 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); + }); + + 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); + }); + + 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 96263359..b16e4d23 100644 --- a/src/harness/application/datasets/datasetService.ts +++ b/src/harness/application/datasets/datasetService.ts @@ -1,12 +1,17 @@ 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 { 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'; +import { boundedPageBytes, boundedLimit, decodeHistoryCursor, encodeHistoryCursor, MAX_RUNTIME_HISTORY_PAGE_BYTES, queryBinding, RUNTIME_HISTORY_LIMITS, serializedHistoryItemBytes, type RuntimeHistoryPage, type RuntimeHistoryQuery } from '../history/runtimeHistory'; export type HarnessFailureKind = 'sensor' | 'task' | 'session' | 'trace'; @@ -41,6 +46,8 @@ export interface HarnessFailureDataset { clusterCount: number; failures: HarnessFailureRecord[]; clusters: HarnessFailureCluster[]; + partial: boolean; + omittedFailureCount: number; } export interface HarnessDatasetServiceOptions { @@ -51,6 +58,24 @@ export interface HarnessDatasetServiceOptions { export interface BuildHarnessDatasetOptions { sessionIds?: string[]; 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; + sessionCount: number; + failureCount: number; + clusterCount: number; + partial: boolean; } export interface HarnessDatasetDependencies { @@ -64,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) 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(), @@ -97,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; @@ -129,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 [{ @@ -149,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 => ({ @@ -178,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, }); @@ -186,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; @@ -246,57 +283,191 @@ 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); } 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 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 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[]) => { + 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: true, + maxEvents: 1000, + maxBytes: Math.min(maxDatasetBytes, MAX_RUNTIME_HISTORY_PAGE_BYTES), + }); + 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 (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 }); + await processBatch(page.items, async (session) => session); + cursor = page.nextCursor; + } while (cursor); } - const sessionFailures = replays.flatMap(replay => buildSessionFailure(replay)); - const traceFailures = replays.flatMap(replay => buildTraceFailures(replay)); - const failures = [...sensorFailures, ...taskFailures, ...sessionFailures, ...traceFailures]; const clusters = clusterFailures(failures); const dataset: HarnessFailureDataset = { id: randomUUID(), createdAt: nowIso(), repoPath: this.repoPath, - sessionCount: selectedSessions.length, - replayCount: replays.length, + sessionCount, + replayCount, failureCount: failures.length, clusterCount: clusters.length, failures, clusters, + partial: omittedFailureCount > 0, + 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; } 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, RUNTIME_HISTORY_LIMITS.datasets.default, RUNTIME_HISTORY_LIMITS.datasets.maximum, '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 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; + let oversizedRecordsSkipped = 0; + const directory = await fs.opendir(this.datasetsPath); + for await (const entry of directory) { + if (!entry.isFile() || !entry.name.endsWith('.json') || entry.name.endsWith('.meta.json')) continue; + try { + const file = path.join(this.datasetsPath, entry.name); + 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; + 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 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, 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/execution/executionService.ts b/src/harness/application/execution/executionService.ts index 8b30a154..e899d033 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', @@ -180,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', @@ -194,6 +210,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); } @@ -212,6 +232,10 @@ export class HarnessExecutionService { return this.contracts.listHandoffContracts(); } + listHandoffContractPage(query: Parameters[0] = {}) { + return this.contracts.listHandoffContractPage(query); + } + listPolicies(): Promise { return this.policy.listRules(); } @@ -276,6 +300,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 +323,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); } @@ -312,7 +344,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 new file mode 100644 index 00000000..ad7877a4 --- /dev/null +++ b/src/harness/application/history/__tests__/runtimeHistory.load.test.ts @@ -0,0 +1,77 @@ +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; + +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); + + 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 () => { + 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); + }); + + 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/__tests__/runtimeRetentionService.test.ts b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts new file mode 100644 index 00000000..36f9eb22 --- /dev/null +++ b/src/harness/application/history/__tests__/runtimeRetentionService.test.ts @@ -0,0 +1,67 @@ +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); + }); + + 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/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..840771b0 --- /dev/null +++ b/src/harness/application/history/runtimeHistory.ts @@ -0,0 +1,107 @@ +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 }, + exploreFiles: { default: 100, maximum: 1000 }, + replayEvents: { default: 100, maximum: 1000 }, +} as const; + +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 { + items: T[]; + nextCursor?: string; + hasMore: boolean; + recordsReturned: number; + recordsScanned: number; + scannedBytes?: number; + returnedBytes: number; + byteBudget: number; + byteLimited: boolean; + oversizedRecordsSkipped: 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; +} + +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/history/runtimeRetentionService.ts b/src/harness/application/history/runtimeRetentionService.ts new file mode 100644 index 00000000..e2070342 --- /dev/null +++ b/src/harness/application/history/runtimeRetentionService.ts @@ -0,0 +1,178 @@ +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'; + +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; +} + +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) {} + + 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'] = []; + const quotaEligibleSessions: Array<{ path: string; kind: 'session'; bytes: number; mtime: number }> = []; + + 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 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, 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') || entry.name.endsWith('.meta.json')) continue; + const target = path.join(dir, entry.name); + try { + 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)); + 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 }> = 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') || name.endsWith('.meta.json')) continue; + const stat = await fs.stat(target); + 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); + 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); + 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/hooks/__tests__/hookReadiness.test.ts b/src/harness/application/hooks/__tests__/hookReadiness.test.ts index f8dbfb64..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, @@ -185,6 +186,18 @@ 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' } }); + + 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 new file mode 100644 index 00000000..1d08866f --- /dev/null +++ b/src/harness/application/hooks/__tests__/hookTracePolicy.test.ts @@ -0,0 +1,267 @@ +import { + DEFAULT_HOOK_STDIN_MAX_BYTES, + 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', { + 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.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', { + [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); + 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); + }); + + 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/bashClassification.ts b/src/harness/application/hooks/bashClassification.ts index 03fc3aa8..a71f65f7 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,16 +98,19 @@ export function classifyBashCommand(command: string | undefined): HookBashClassi return undefined; } -export function buildHookTraceData(toolName: string | undefined, toolInput: unknown): Record { - const data: Record = { tool_input: toolInput }; - if (toolName?.trim().toLowerCase() !== 'bash') { - return data; - } - - const classification = classifyBashCommand(extractBashCommand(toolInput)); - if (classification) { - data.classification = classification; - } - - return data; +export function buildHookTraceData( + toolName: string | undefined, + toolInput: unknown, + options: { policy?: HookTracePolicy; repoPath?: string } = {} +): Record { + const policy = options.policy ?? loadHookTracePolicy(options.repoPath); + 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 new file mode 100644 index 00000000..9211582f --- /dev/null +++ b/src/harness/application/hooks/hookTracePolicy.ts @@ -0,0 +1,573 @@ +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 : {}; + 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'), + 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 + ), + // 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, + }; +} + +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; + } +} + +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 }; + + 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: encoded.subarray(0, end).toString('utf8'), 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; +} + +const COMMAND_SECRET_KEY = /(? 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 { + 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; +} + +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, + state: SanitizeState, + depth = 0 +): unknown { + if (value === null || typeof value === 'number' || typeof value === 'boolean') { + return value; + } + if (typeof value === 'string') { + const result = truncateUtf8Prefix(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: 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 [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[outputKey] = summarizeUnknown(child, policy, state, depth + 1); + } + } + return result; +} + +function boundedMetadataString(value: string | undefined, policy: HookTracePolicy, state: SanitizeState): string | undefined { + if (value === undefined) return undefined; + const bounded = truncateUtf8Prefix(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 { + ...(filePath ? { filePath } : {}), + ...(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, 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 { + ...(filePath ? { filePath } : {}), + ...(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 = truncateUtf8Prefix(redactedCommand.value, policy.maxStringBytes); + if (preview.truncated) state.truncatedFieldCount += 1; + const basename = boundedMetadataString(commandBasename(command), policy, state); + return { + ...(basename ? { commandBasename: basename } : {}), + 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, + additionalData: Record = {} +): 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, policy, state); + } else if (normalizedTool === 'edit') { + state.redactedFieldCount = countSensitiveFields(input, policy); + summary = summarizeEdit(input, policy, state); + } 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 = { + ...additionalData, + tool_input: summary, + capture: { + inputBytes: byteLength(toolInput), + persistedBytes: 0, + redactedFieldCount: state.redactedFieldCount, + truncatedFieldCount: state.truncatedFieldCount, + quotaStatus: 'within_limit', + }, + }; + 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 = { + 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 < 8; 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 = truncateUtf8Prefix(trace.message, 512); + const bounded = { + ...trace, + ...(typeof trace.event === 'string' ? { event: truncateUtf8Prefix(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/application/index.ts b/src/harness/application/index.ts index 721c0d0f..2ac80d94 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'; @@ -10,6 +11,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..ca71e923 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); }); @@ -58,5 +60,93 @@ 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 () => { + 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); + 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 () => { + 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: 30 }); + + expect(listTasks).not.toHaveBeenCalled(); + expect(listHandoffs).not.toHaveBeenCalled(); + 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'])); + }); + + 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 b110bca7..affb24e8 100644 --- a/src/harness/application/replay/replayService.ts +++ b/src/harness/application/replay/replayService.ts @@ -17,6 +17,18 @@ import { type HarnessHandoffContract, type HarnessTaskContract, } from '../contracts/taskContractsService'; +import { + boundedPageBytes, + boundedLimit, + decodeHistoryCursor, + encodeHistoryCursor, + queryBinding, + RUNTIME_HISTORY_LIMITS, + serializedHistoryItemBytes, + MAX_RUNTIME_HISTORY_PAGE_BYTES, + type RuntimeHistoryPage, + type RuntimeHistoryQuery, +} from '../history/runtimeHistory'; export type HarnessReplayEventSource = | 'session' @@ -34,6 +46,7 @@ export interface HarnessReplayEvent { source: HarnessReplayEventSource; label: string; payload?: Record; + record?: HarnessArtifactRecord | HarnessSessionCheckpoint | HarnessTraceRecord | HarnessSensorRun | HarnessTaskContract | HarnessHandoffContract; } export interface HarnessReplayRecord { @@ -44,15 +57,12 @@ export interface HarnessReplayRecord { replayedAt: string; fidelity: 'complete' | 'partial'; eventCount: number; + sourceCounts: Record; + omittedCounts: Record; + nextCursor?: string; summary: string; events: HarnessReplayEvent[]; - session: HarnessSessionRecord; - artifacts: HarnessArtifactRecord[]; - checkpoints: HarnessSessionCheckpoint[]; - traces: HarnessTraceRecord[]; - sensorRuns: HarnessSensorRun[]; - tasks: HarnessTaskContract[]; - handoffs: HarnessHandoffContract[]; + session: Omit & { checkpoints?: never }; } export interface HarnessReplayServiceOptions { @@ -63,20 +73,48 @@ export interface HarnessReplayServiceOptions { export interface ReplaySessionOptions { includePayloads?: boolean; maxEvents?: number; + maxBytes?: number; + cursor?: string; +} + +export interface HarnessReplaySummary { + id: string; + sessionId: string; + createdAt: string; + fidelity: 'complete' | 'partial'; + eventCount: number; + summary: string; } export interface HarnessReplayDependencies { stateService: HarnessRuntimeStatePort; - sensorsService: Pick; - contractsService: Pick; + sensorsService: Pick; + contractsService: Pick< + HarnessTaskContractsService, + 'listSessionTaskContracts' | 'listSessionHandoffContracts' + >; } function nowIso(): string { return new Date().toISOString(); } -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 { @@ -112,6 +150,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); } @@ -119,6 +161,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 { @@ -134,138 +185,156 @@ export class HarnessReplayService { sessionId: string, options: ReplaySessionOptions = {} ): Promise { + const maxEvents = boundedLimit(options.maxEvents, RUNTIME_HISTORY_LIMITS.replayEvents.default, RUNTIME_HISTORY_LIMITS.replayEvents.maximum, 'replay events'); + const byteBudget = boundedPageBytes(options.maxBytes, '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), - this.sensorsService.getSessionSensorRuns(sessionId), - this.contractsService.listTaskContracts(), - this.contractsService.listHandoffContracts(), - ]); - - const sessionTasks = tasks.filter((task) => task.sessionId === sessionId); - const sessionHandoffs = handoffs.filter((handoff) => handoff.sessionId === sessionId); - - 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, - }, + 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; + const pageSize = Math.min(32, maxEvents); + const sourceTotals: Record = { + session: 1, + trace: session.traceCount, + artifact: session.artifactCount, + checkpoint: session.checkpointCount, + sensor: sensorRunCount, + 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 = paged( + async cursor => { + // Checkpoint records are externalized by the retention layer, so the + // summary returned by getSession() intentionally does not embed them. + // Keep each prefetched page below the default replay byte budget using + // the checkpoint record's absolute 64 KiB ceiling. + const page = await this.stateService.listCheckpointsPage(sessionId, { + cursor, + limit: Math.min(pageSize, 16), + }); + return { items: page.records, nextCursor: page.nextCursor }; }, - ...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(), + checkpoint => ({ + id: checkpoint.id, sessionId, createdAt: checkpoint.createdAt, - source: 'checkpoint' as const, + source: 'checkpoint', 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, options.maxEvents ?? Number.MAX_SAFE_INTEGER); + record: recordFor(checkpoint), + }) + ); + const sensorSource = paged( + cursor => this.sensorsService.getSessionSensorRunPage(sessionId, { limit: pageSize, cursor, direction: 'oldest', maxBytes: byteBudget }), + run => ({ 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 }; + 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 = hasMore || byteLimited || 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: 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, - artifacts, - checkpoints, - traces, - sensorRuns, - tasks: sessionTasks, - handoffs: sessionHandoffs, + session: boundedSession, }; return replay; @@ -281,19 +350,66 @@ 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, RUNTIME_HISTORY_LIMITS.replays.default, RUNTIME_HISTORY_LIMITS.replays.maximum, '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') || entry.name.endsWith('.meta.json')) continue; + try { + const file = path.join(this.replaysPath, entry.name); + 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}`; + 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 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, returnedBytes, byteBudget, byteLimited, oversizedRecordsSkipped, cursorVersion: 1, partial: hasMore || oversizedRecordsSkipped > 0, durationMs: Date.now() - started }; } async getReplay(replayId: string): Promise { 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..58a6f6ab --- /dev/null +++ b/src/harness/application/retention/__tests__/runtimeRetentionConfig.test.ts @@ -0,0 +1,62 @@ +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 }, + 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); + }); + + 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/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..1fe3a0ca --- /dev/null +++ b/src/harness/application/retention/runtimeRetentionConfig.ts @@ -0,0 +1,238 @@ +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; + maxSerializedBytes: number; + maxNoteBytes: number; + maxArtifactIds: number; + maxArtifactIdBytes: number; + }; + bindings: { maxEntries: number; maxAgeMs: number }; + caches: { + 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 }; + }; +} + +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 = { + version: 1, + traces: { maxBytes: 64 * 1024 * 1024 }, + sessions: { maxEntries: 1_000 }, + replays: { maxEntries: 100 }, + datasets: { maxEntries: 100 }, + 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 }, + 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 }, + }, +}; + +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', 'maxSerializedBytes', 'maxNoteBytes', 'maxArtifactIds', 'maxArtifactIdBytes'], + bindings: ['maxEntries', 'maxAgeMs'], + caches: ['context', 'semantic', 'mcpSessions', 'fileAnalysis'], + 'caches.context': ['maxEntries', 'maxBytes', 'ttlMs', 'maxEntriesScanned'], + 'caches.semantic': ['maxEntries', 'maxBytes', 'maxEntriesScanned'], + '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, + fallback: number, + minimum: number, + absoluteMaximum: number, + name: string, + diagnostics: string[], + metrics: RuntimeRetentionConfigMetrics, +): number { + if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum) { + if (value !== undefined) { + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, `${name} was invalid; safe default applied`); + } + return fallback; + } + if (value > absoluteMaximum) { + metrics.clampedValues += 1; + addDiagnostic(diagnostics, metrics, `${name} was clamped to the absolute safety ceiling ${absoluteMaximum}`); + return absoluteMaximum; + } + return Math.floor(value); +} + +/** 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 fileExists = false; + if (await fs.pathExists(file)) { + fileExists = true; + try { + 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 { + metrics.invalidValues += 1; + addDiagnostic(diagnostics, metrics, 'runtime.json could not be parsed; defaults applied'); + } + } + + 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, metrics); + const config: RuntimeRetentionConfig = { + version: 1, + 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(checkpoints.maxDataBytes, d.checkpoints.maxDataBytes, 1_024, 1024 ** 2, 'checkpoints.maxDataBytes'), + maxSerializedBytes: number(checkpoints.maxSerializedBytes, d.checkpoints.maxSerializedBytes, 1_024, 2 * 1024 ** 2, 'checkpoints.maxSerializedBytes'), + maxNoteBytes: number(checkpoints.maxNoteBytes, d.checkpoints.maxNoteBytes, 1, 64 * 1024, 'checkpoints.maxNoteBytes'), + maxArtifactIds: number(checkpoints.maxArtifactIds, d.checkpoints.maxArtifactIds, 1, 1_000, 'checkpoints.maxArtifactIds'), + maxArtifactIdBytes: number(checkpoints.maxArtifactIdBytes, d.checkpoints.maxArtifactIdBytes, 1, 16 * 1024, 'checkpoints.maxArtifactIdBytes'), + }, + bindings: { + 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(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'), + maxEntriesScanned: number(context.maxEntriesScanned, d.caches.context.maxEntriesScanned, 1, 1_000_000, 'caches.context.maxEntriesScanned'), + }, + semantic: { + 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'), + maxEntriesScanned: number(semantic.maxEntriesScanned, d.caches.semantic.maxEntriesScanned, 1, 1_000_000, 'caches.semantic.maxEntriesScanned'), + }, + mcpSessions: { + 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(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: metrics.invalidValues + metrics.clampedValues, metrics }; +} 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 4e47adb4..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,48 @@ export class HarnessSensorsService { return run; } + 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 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 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( 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/harness/domain/execution/__tests__/boundedByteCollector.test.ts b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts new file mode 100644 index 00000000..dc8f0a87 --- /dev/null +++ b/src/harness/domain/execution/__tests__/boundedByteCollector.test.ts @@ -0,0 +1,87 @@ +import { + BoundedByteCollector, + DEFAULT_SUBPROCESS_TAIL_BYTES, + MAX_SAFE_SUBPROCESS_HARD_OUTPUT_BYTES, + MAX_SUBPROCESS_TAIL_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 })); + }); + + 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 new file mode 100644 index 00000000..28d9edcd --- /dev/null +++ b/src/harness/domain/execution/boundedByteCollector.ts @@ -0,0 +1,150 @@ +/** + * 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; +/** + * 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; +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 = Math.min( + positiveInteger(input.tailBytes, DEFAULT_SUBPROCESS_TAIL_BYTES, 0), + MAX_SUBPROCESS_TAIL_BYTES + ); + 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 { + readonly tailBytes: number; + private readonly buffer: Buffer; + private retainedLength = 0; + private writeOffset = 0; + private observedBytes = 0; + + constructor(tailBytes: number = DEFAULT_SUBPROCESS_TAIL_BYTES) { + if (!Number.isSafeInteger(tailBytes) || tailBytes < 0) { + throw new Error('tailBytes must be a non-negative safe integer'); + } + // 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 { + 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..a271f343 --- /dev/null +++ b/src/harness/domain/execution/index.ts @@ -0,0 +1,20 @@ +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, + MAX_JEST_RESULT_FILE_BYTES, + resolveSubprocessOutputLimits, + type BoundedByteCollectorSnapshot, + 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/index.ts b/src/harness/domain/index.ts index 2d1af512..fad53334 100644 --- a/src/harness/domain/index.ts +++ b/src/harness/domain/index.ts @@ -4,3 +4,5 @@ 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'; +export * as execution from './execution'; 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..dd2e1320 --- /dev/null +++ b/src/harness/domain/retention/boundedLruCache.ts @@ -0,0 +1,147 @@ +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'); + } + + 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(); + } + + 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/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts b/src/harness/domain/workflow/plans/__tests__/acceptanceRunner.test.ts index 91829dea..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)'] }, @@ -55,6 +67,92 @@ 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('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( + { + 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('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 a4fa8c94..db959c02 100644 --- a/src/harness/domain/workflow/plans/acceptanceRunner.ts +++ b/src/harness/domain/workflow/plans/acceptanceRunner.ts @@ -7,9 +7,18 @@ */ import { spawn } from 'child_process'; +import * as path from 'path'; +import { + BoundedByteCollector, + DEFAULT_SUBPROCESS_HARD_OUTPUT_BYTES, + DEFAULT_SUBPROCESS_TAIL_BYTES, + resolveSubprocessOutputLimits, + subprocessSpawnOptions, + terminateProcessTree, +} 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 +43,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 +64,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; @@ -71,6 +82,7 @@ export async function runAcceptance( shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: process.env, + ...subprocessSpawnOptions(), }); } catch (err) { resolve({ @@ -81,42 +93,94 @@ 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; + 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 ( + !outputLimitExceeded && + stdout.totalBytes + stderr.totalBytes > limits.hardCombinedOutputBytes + ) { + outputLimitExceeded = true; + requestTermination(); + } + }; - 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'); + requestTermination(); }, timeoutMs); - const finish = (exitCode: number | null, spawnError?: Error) => { + const finish = async (exitCode: number | null) => { + if (settled) return; + if (termination) await termination; 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)); - child.on('close', (code) => finish(code)); + // 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('exit', (code) => { exitCodeSeen = code; }); + child.on('close', (code) => { void 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 } ); diff --git a/src/harness/index.ts b/src/harness/index.ts index fa1b6cd9..d274fce3 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, @@ -115,6 +129,7 @@ export { type HarnessArtifactKind, type HarnessSessionRecord, type HarnessSessionCheckpoint, + type HarnessCheckpointPage, type HarnessTraceRecord, type HarnessArtifactRecord, type HarnessRuntimeStatePort, @@ -122,6 +137,9 @@ export { type AppendTraceInput, type AddArtifactInput, type CheckpointInput, + type ListCheckpointsOptions, + type HarnessTracePageQuery, + type HarnessSensorSummary, HarnessSensorsService, HarnessSensorCatalogService, type HarnessSensorsServiceOptions, @@ -152,6 +170,7 @@ export { type HarnessReplayEvent, type HarnessReplayEventSource, type HarnessReplayRecord, + type HarnessReplaySummary, type ReplaySessionOptions, HarnessDatasetService, type HarnessDatasetServiceOptions, @@ -161,6 +180,17 @@ export { type HarnessFailureRecord, type HarnessFailureCluster, type HarnessFailureDataset, + type HarnessDatasetSummary, + HarnessRuntimeRetentionService, + DEFAULT_RUNTIME_HISTORY_PAGE_BYTES, + MAX_RUNTIME_HISTORY_PAGE_BYTES, + RuntimeHistoryCursorError, + RUNTIME_HISTORY_LIMITS, + type RuntimeHistoryDirection, + type RuntimeHistoryQuery, + type RuntimeHistoryPage, + type RuntimePruneReport, + type RuntimePruneOptions, HarnessPolicyService, HarnessPolicyBlockedError, type HarnessPolicyServiceOptions, diff --git a/src/harness/ports/out/index.ts b/src/harness/ports/out/index.ts index a2415056..ab5a934f 100644 --- a/src/harness/ports/out/index.ts +++ b/src/harness/ports/out/index.ts @@ -4,6 +4,8 @@ export { type AppendTraceInput, type AddArtifactInput, type CheckpointInput, + type HarnessCheckpointPage, + type ListCheckpointsOptions, } from '../../adapters/out/runtimeState/runtimeStateService'; export { type HarnessWorkflowRecord, 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/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 795881b7..e4cdda4a 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -1,6 +1,8 @@ import * as fs from 'fs-extra'; import * as os from 'os'; import * as path from 'path'; +import { promises as nativeFs } from 'fs'; +import { spawn } from 'child_process'; import { createHarnessHookAdapter } from '../../../harness'; import { @@ -10,6 +12,8 @@ import { import { ensureHookHarnessSession, getHookHarnessSessionId, + pruneHookSessionBindings, + saveHookHarnessSession, } from '../hookSessionStore'; describe('hookDispatchCommands', () => { @@ -57,4 +61,245 @@ 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(); + }); + + 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); + }); + + 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('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: {} }); + 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 = { + pid: process.pid, + 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 739ba127..9cb5a320 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -1,8 +1,11 @@ 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'; +import { loadRuntimeRetentionConfig } from '../../harness/application/retention/runtimeRetentionConfig'; import { extractHarnessSessionId } from './extractHarnessSessionId'; @@ -21,6 +24,42 @@ interface HookSessionStoreDocument { bindings: Record>; } +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; +} + +/** Lock shape written before owner tokens were introduced. */ +interface LegacyHookSessionLockOwner { + pid: number; + createdAt: number; +} + +type AnyHookSessionLockOwner = HookSessionLockOwner | LegacyHookSessionLockOwner; + +interface HookSessionLockSnapshot { + owner?: AnyHookSessionLockOwner; + device: number; + inode: number; + mtimeMs: number; + content: string; +} + +export interface HookSessionPruneResult { + removedExpired: number; + removedMissing: number; + removedOverLimit: number; + remaining: number; + durationMs: number; +} + export interface HookSessionAdapter { handle(event: { tool: 'harness'; @@ -62,7 +101,203 @@ 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); + } +} + +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 + || typeof candidate.token !== 'string' + || !/^[0-9a-f-]{36}$/i.test(candidate.token) + ) 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, + content, + }; + } finally { + await handle.close().catch(() => undefined); + } +} + +function sameLock(left: HookSessionLockSnapshot, right: HookSessionLockSnapshot): boolean { + return left.device === right.device + && left.inode === right.inode + && left.content === right.content + && 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. 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); + } 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)}`); + } + await new Promise(resolve => setTimeout(resolve, LOCK_RETRY_MS)); + } + } + + const owner: HookSessionLockOwner = { + version: 1, + pid: process.pid, + token, + createdAt: Date.now(), + }; + const serializedOwner = JSON.stringify(owner); + try { + await handle.writeFile(serializedOwner, 'utf8'); + await handle.sync(); + } catch (error) { + const stat = await handle.stat().catch(() => undefined); + await handle.close().catch(() => undefined); + if (stat) { + await releaseOwnedLock(lockPath, { + owner, + device: stat.dev, + inode: stat.ino, + mtimeMs: stat.mtimeMs, + content: serializedOwner, + }); + } + throw error; + } + + const stat = await handle.stat(); + const owned: HookSessionLockSnapshot = { + owner, + device: stat.dev, + inode: stat.ino, + mtimeMs: stat.mtimeMs, + content: serializedOwner, + }; + + try { + return await operation(); + } finally { + await handle.close().catch(() => undefined); + await releaseOwnedLock(lockPath, owned); + } +} + +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: { @@ -76,11 +311,69 @@ export async function getHookHarnessSessionId(options: { } export async function saveHookHarnessSession(binding: HookSessionBinding): Promise { - const document = await readStore(binding.repoPath); - const sourceBindings = document.bindings[binding.source] ?? {}; - sourceBindings[binding.hostSessionId] = binding; - document.bindings[binding.source] = sourceBindings; - await writeStore(binding.repoPath, document); + const normalizedRepoPath = path.resolve(binding.repoPath); + 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 }> { + 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); + return mutateStore(normalizedRepoPath, async () => { + 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 +384,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/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 }), }, }; } diff --git a/src/mcp/README.md b/src/mcp/README.md index 600088e8..71fbd806 100644 --- a/src/mcp/README.md +++ b/src/mcp/README.md @@ -26,6 +26,19 @@ 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 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. 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. 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) 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/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/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..a17edb7f 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; +} + +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; + } + 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 = resolveMcpPayloadBudget(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 = resolveMcpPayloadBudget(); + 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/logging/__tests__/actionLogger.test.ts b/src/mcp/logging/__tests__/actionLogger.test.ts index f66e80af..ca30c261 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, getMcpActionSessionCacheMetrics, 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 () => { @@ -86,4 +88,47 @@ 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); + }); + + 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 d4907036..13915ac9 100644 --- a/src/mcp/logging/actionLogger.ts +++ b/src/mcp/logging/actionLogger.ts @@ -6,8 +6,11 @@ */ import * as fs from 'fs-extra'; +import * as path from 'path'; import { HarnessRuntimeStateService } from '../../harness/adapters/out/runtimeState/runtimeStateService'; +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'; @@ -39,7 +42,67 @@ const MAX_ARRAY = 20; const MAX_STRING = 200; const MCP_ACTIVITY_NAME = 'mcp-activity'; -const sessionCache = new Map(); +const sessionCaches = new Map; + signature: string; + diagnostics: string[]; +}>(); + +function normalizeRepoPath(repoPath: string): string { + 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 { + for (const owner of sessionCaches.values()) owner.cache.dispose(); + sessionCaches.clear(); +} + +export function getMcpActionSessionCacheSize(): number { + 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 { const resolution = await resolveContextRoot({ @@ -108,23 +171,33 @@ async function resolveMcpActivitySessionId( repoPath: string, state: HarnessRuntimeStateService ): Promise { - const cached = sessionCache.get(repoPath); + const cacheKey = 'mcp-activity'; + const sessionCache = await sessionCacheForRepo(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); } } - 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' && + (session.status === 'active' || session.status === 'paused') + ); + cursor = existing ? undefined : page.nextCursor; + } while (!existing && cursor); if (existing) { - sessionCache.set(repoPath, existing.id); + sessionCache.set(cacheKey, existing.id); return existing.id; } @@ -135,7 +208,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/__tests__/mcpServer.test.ts b/src/mcp/server/__tests__/mcpServer.test.ts index 79be42f4..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 } 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 @@ -45,6 +50,72 @@ 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.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 () => { + 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/__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 0e0bf5d8..39c4878c 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 { clearMcpActionSessionCache, logMcpAction } from '../logging/actionLogger'; +import { + createBoundedResourceJson, + createBoundedResourceText, + readBoundedFileResource, +} from './resourceResponse'; import { PREVC_ROLES, getScaleName, @@ -53,6 +57,9 @@ import { type WorkflowAdvanceParams, type WorkflowManageParams, type MCPToolResponse, + createErrorResponse, + validateMcpInput, + MCP_INPUT_LIMITS, } from '../gateway'; export interface MCPServerOptions { @@ -66,6 +73,41 @@ 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 MCP_MAX_BYTES_SCHEMA = z.number().int().min(1024).max(64 * 1024 * 1024); +const MCP_MAX_FAILURE_BYTES_SCHEMA = z.number().int().min(1024).max(1024 * 1024); +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); +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; @@ -115,35 +157,39 @@ 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?) -- list: List files matching pattern (params: pattern, cwd?, ignore?) +- 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']) .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() + limit: MCP_LIST_LIMIT_SCHEMA.optional() + .describe('(list) Maximum files per page'), + cursor: mcpString().max(MCP_INPUT_LIMITS.cursorLength).optional() + .describe('(list, search) Opaque continuation cursor'), + 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 +222,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 +244,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 +255,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 +264,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 +310,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 +369,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 +392,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 +419,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 +495,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 +527,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 +554,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 +598,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 +608,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 +629,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'), @@ -623,11 +669,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?) @@ -670,71 +716,80 @@ 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), + maxBytes: MCP_MAX_BYTES_SCHEMA.optional(), + 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(), + concurrency: z.number().int().min(1).max(4).optional(), + maxFailures: z.number().int().min(1).max(10_000).optional(), + maxFailureBytes: MCP_MAX_FAILURE_BYTES_SCHEMA.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 => { @@ -790,13 +845,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); } ); @@ -810,22 +859,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); } ); @@ -855,43 +889,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), + }); } } ); @@ -995,21 +1013,31 @@ 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 { + if (toolName === 'harness') { + MCP_HARNESS_ACTION_LIMIT_SCHEMA.parse(params); + } + 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 +1078,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 +1087,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 +1111,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 */ @@ -1136,6 +1125,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/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(); + } +} 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`), }; } diff --git a/src/types.ts b/src/types.ts index e0968847..bae254b2 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'; } @@ -13,6 +16,33 @@ export interface TopLevelDirectoryStats { totalSize: number; } +export type RepoDiscoverySkipReason = + | 'file-limit' + | 'total-byte-limit' + | 'file-too-large' + | 'directory-limit' + | 'entry-limit' + | 'stat-failed'; + +export interface RepoDiscoverySkip { + file: string; + reason: RepoDiscoverySkipReason; + size?: number; + mtimeMs?: number; + ctimeMs?: number; +} + +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; +} + export interface RepoStructure { rootPath: string; files: FileInfo[]; @@ -20,6 +50,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..0cf093a0 --- /dev/null +++ b/src/utils/__tests__/fileMapper.test.ts @@ -0,0 +1,212 @@ +import * as fs from 'fs-extra'; +import { promises as nativeFs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { FileMapper } from '../fileMapper'; + +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 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 { + 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(); + 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`)) + ); + 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, + }); + expect(stat).toHaveBeenCalledTimes(5_000); + expect(result.skipped).toEqual(expect.arrayContaining([ + expect.objectContaining({ reason: 'file-limit' }), + ])); + }); + + it('stops metadata work as soon as the aggregate byte budget is reached', async () => { + 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([], { + maxFiles: 5_000, + maxFileBytes: 100, + maxTotalBytes: 10, + }).mapRepository(repoPath); + + 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, 'b.ts'), reason: 'total-byte-limit' }), + ])); + }); + + 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); + + 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, '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 8e6edd99..ec07a1c4 100644 --- a/src/utils/fileMapper.ts +++ b/src/utils/fileMapper.ts @@ -1,17 +1,76 @@ 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 { minimatch } from 'minimatch'; +import { + FileInfo, + RepoStructure, + TopLevelDirectoryStats, + type RepoDiscoverySkip, +} from '../types'; import { GitIgnoreManager } from './gitignoreManager'; +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 = [ + '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; + +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'; + } + return (REPOSITORY_RELEVANT_EXTENSIONS as readonly string[]).includes(extension); +} + +const MAX_RECORDED_SKIPS = 1_000; + export class FileMapper { private excludePatterns: string[] = [ 'node_modules', '**/node_modules', '**/node_modules/**', '.git/**', + '.git', 'dist/**', 'build/**', + '.context/**', + '.context', '*.log', '.env*', '*.tmp', @@ -20,21 +79,41 @@ export class FileMapper { private readonly gitIgnoreManager: GitIgnoreManager; - constructor(customExcludes: string[] = []) { - this.excludePatterns = [...this.excludePatterns, ...customExcludes]; - this.gitIgnoreManager = new GitIgnoreManager({ extraPatterns: customExcludes }); - } + private readonly limits: FileMappingLimits; - 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('#')); + constructor( + customExcludes: string[] = [], + limits: Partial = {} + ) { + this.excludePatterns = [...this.excludePatterns, ...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( + 0, + Math.floor(limits.maxTotalBytes ?? DEFAULT_FILE_MAPPING_LIMITS.maxTotalBytes) + ), + maxFileBytes: Math.max( + 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) + ) + ), + }; } async mapRepository(repoPath: string, includePatterns?: string[]): Promise { @@ -44,67 +123,140 @@ 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 = includePatterns ?? []; + const fileInfos: FileInfo[] = []; + const skipped: RepoDiscoverySkip[] = []; + let totalSize = 0; + let entriesScanned = 0; + let directoriesScanned = 0; + let entriesVisited = 0; + let statCalls = 0; + let stoppedEarly = false; + const topLevelStats = new Map(); + const directoryQueue = ['']; + let nextDirectory = 0; - const patterns = includePatterns || ['**/*']; - const allFiles: string[] = []; + 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; + break; + } + nextDirectory += 1; + directoriesScanned += 1; - for (const pattern of patterns) { - const files = await glob(pattern, { - cwd: absolutePath, - ignore: ignorePatterns, - dot: false, - absolute: false - }); - allFiles.push(...files); - } + let directory; + try { + directory = await nativeFs.opendir(path.join(absolutePath, relativeDirectory)); + } catch { + this.recordSkip(skipped, { + file: path.join(absolutePath, relativeDirectory), + reason: 'stat-failed', + }); + continue; + } - // Apply .gitignore filtering on top of glob excludes - const filteredFiles = this.gitIgnoreManager.filterPaths(allFiles); + 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 uniqueFiles = [...new Set(filteredFiles)]; - const fileInfos: FileInfo[] = []; - const directories: FileInfo[] = []; - let totalSize = 0; - const topLevelStats = new Map(); - const concurrency = 32; + const relativePath = path.posix.join( + relativeDirectory.split(path.sep).join('/'), + entry.name + ); + if (this.isIgnored(relativePath, entry.isDirectory())) continue; + + if (entry.isDirectory()) { + 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; + } - 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 = { + 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, - type: stats.isDirectory() ? 'directory' : 'file' - }; + 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 }; - if (!stats.isDirectory()) { - current.fileCount += 1; - current.totalSize += stats.size; - } + current.fileCount += 1; + current.totalSize += stats.size; topLevelStats.set(topLevelSegment, current); } - - if (stats.isDirectory()) { - directories.push(info); - } else { - fileInfos.push(info); - totalSize += stats.size; - } - - }) - ); + } + } finally { + await directory.close().catch(() => undefined); + } } + 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)); @@ -115,10 +267,48 @@ export class FileMapper { directories, totalFiles: fileInfos.length, totalSize, - topLevelDirectoryStats + topLevelDirectoryStats, + partial: skipped.length > 0 || stoppedEarly, + skipped, + discoveryMetrics: { + entriesScanned, + directoriesScanned, + entriesVisited, + statCalls, + stoppedEarly, + }, }; } + private isIgnored(relativePath: string, isDirectory: boolean): boolean { + return this.gitIgnoreManager.shouldIgnore(relativePath) || + (isDirectory && this.gitIgnoreManager.shouldIgnore(`${relativePath}/`)); + } + + 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');