diff --git a/__reports__/workspace_discovery/00-architecture_v0.md b/__reports__/workspace_discovery/00-architecture_v0.md new file mode 100644 index 0000000..7948068 --- /dev/null +++ b/__reports__/workspace_discovery/00-architecture_v0.md @@ -0,0 +1,146 @@ +# Dynamic workspace discovery — Architecture Analysis (v0) + +Date: 2026-11-12 + +## Executive Summary + +- **Problem**: colgrep-mcp's default root resolution silently lands on the server + process's own cwd (the plugin install tree) whenever `COLGREP_MCP_ROOT` is unset + and the client sends no roots, so every path-less tool call searches the wrong + project and the model must repeat the path. Confirmed this session: + `doctor` reported `default_root: .../agentPlugins/.../1a1c9036c4d (source: cwd)` + and path-less `search` returned only plugin-tree hits. +- **Proposed change**: probe which dynamic per-call workspace signals each target + harness actually sends (request `_meta`, `initialize` context, `roots/list` + + successor channels per the 2026-07-28 MCP revision), then resolve the default + root per tool call from the strongest available signal. Survey + fleet evidence + feed a findings report; this document fixes the resolution contract. +- **Non-goals**: no behaviour change in this campaign beyond a probe facility that + is inert unless `COLGREP_MCP_PROBE` is set; no skill/schema guidance asking the + model to pass `paths` (rejected as a token-priced workaround); no hook-based + workspace plumbing (Agent Plugins hosts ignore `hooks/`). +- **Biggest risks**: (1) probe code accidentally altering resolution behaviour — + guarded by a verifier dispatch against a dump-only oracle; (2) no dynamic + channel exists in some harness — the contract turns that into fail+guidance, + not a silent wrong root; (3) harness probe runs are flaky/timeout-prone — + artifacts record raw evidence, gaps are reported, not filled. +- **Validation approach**: `pytest` + `ruff` green per leaf; verifier attack on the + dump-only invariant; harness probe artifacts JSON-checked for completeness by a + deterministic predicate, not read by eye. + +## Current State + +```mermaid +graph TD + T[tool call] --> R[paths.resolve_target_paths] + R --> A["explicit paths?"] + A -->|no| B{"COLGREP_MCP_ROOT"} + B -->|unset| C{"roots/list (deprecated, best-effort)"} + C -->|empty/absent| D["server cwd = plugin install dir"] + D --> W[wrong project searched silently] + B -->|set static pin| P[correct, but stale on workspace switch] +``` + +## Proposed State + +```mermaid +graph TD + T[tool call] --> R[resolve_default_root per call] + R --> R1[R1 request _meta / initialize workspace stamp] + R1 -.->|absent| R2[R2 roots: list_changed cache, lazy roots/list] + R2 -.->|absent| R3[R3 COLGREP_MCP_ROOT pin (env)] + R3 -.->|unset| R4[R4 guarded cwd] + R4 -->|cwd looks like install tree| E["ToolError ROOT_UNRESOLVED + guidance: pass an absolute paths entry"] + R1 --> OK[resolved root, root_source recorded] + R2 --> OK + R3 --> OK +``` + +## Key Flows + +```mermaid +sequenceDiagram + participant M as Model + participant T as tool handler + participant P as resolve_default_root + participant H as harness + M->>T: search(query=...) (no paths) + T->>P: per-call resolution + P->>H: read _meta / roots cache (no extra round-trip when cached) + H-->>P: workspace root or nothing + alt no dynamic signal, no pin + P-->>T: ROOT_UNRESOLVED(error + remedy) + T-->>M: error naming how to proceed (set paths to the project dir) + else signal present + P-->>T: [root], root_source label + T-->>M: results scoped to the workspace + end +``` + +## Contracts & Invariants + +- **Resolution ladder** (the only place this lives: `paths.py`): + `explicit paths > dynamic workspace signal (verbatim, per call) > COLGREP_MCP_ROOT pin > guarded cwd` + . Relative `paths` entries resolve against the chosen default root. Multiple dynamic roots select by + `paths` containment first, else `roots[0]`, surfaced in `root_source`. +- **Invariants**: probe facility changes nothing when `COLGREP_MCP_PROBE` is unset + (dump-only oracle: `Client.list_tools()/list_resources()` JSON diff vs base is + empty; resolved paths identical with probe on/off). `root_source` is recorded on + every result as it is today. Resolution errors name the remedy the model can act + on (`paths` with an absolute directory), fail+guidance — neither silence nor a + bare loud fail. +- **Probe dump schema** (JSONL, one record per tool call; file not stdout): + `{ts, server_pid, tool, raw_paths, env: {COLGREP_MCP_ROOT, ..., spawn_env_digest}, + init_capabilities, request_meta, roots_list: {static: "declared|empty|error", items}, + resolved: {root, source}, cwd}`. Raw values only — the record measures what the + harness sent, never what we wish it sent. +- **Error model**: `PATH_NOT_FOUND` keeps its current contract. New `ROOT_UNRESOLVED` + (advisory id, exact code settled at implementation) fires only when no rung can + produce a root, carrying the ghid: "no default workspace resolved; pass an + absolute paths entry" plus the ladder source that failed. +- **Per-harness measurement matrix** (columns fixed now, filled by the probe): + harness × {initialize capabilities, request `_meta` keys, `roots/list` verdict, + successor-of-roots per 2026-07-28 revision (via `protocol_survey`), spawn env}. + Harnesses: (1) VS Code/Copilot Agent Plugins load (this session), (2) `claude -p` + with the Claude Code plugin manifest (`${CLAUDE_PROJECT_DIR}` pin expected), + (3) `codex exec` per stacked `palette`/`codex/` extensions. + +## Alternatives Considered + +- **A. Prompt/schema guidance demanding `paths`** — rejected (user decision): still + costs model tokens and reasoning every call; compensates instead of fixes. +- **B. Recommended per-machine env pin** — accepted as lever #2 (precedence rung 3: + explicit pin outranks inference). Static per server lifetime; user refreshes on + switch, which is a documented limit of any default, not a bug. Complementary, not + sufficient alone. +- **C. Hook-written workspace state** — rejected as primary: Agent Plugins 1.0 + (`§6/§7`) ignores `hooks/`; Cursor needs manual `settings.json` porting (`D8`, + harness-wiring); `WorktreeRemove` is one-host. Retained only as future fallback. +- **D. Per-call protocol resolution (this campaign's target)** — wins because all + three ecosystems ship the same server over one wire; pack-time expansion is + frozen (spec 1.0 `§9.2`), so the protocol is the only portable dynamic headroom. + Tradeoff accepted: rung 1/2 may be empty in some harnesses — the matrix says so, + and rung 4 + fail+guidance keeps that honest. + +## Risks & Mitigations + +- Probe code perturbs resolution silently → verifier dispatch must sign a + dump-only oracle; probe path excluded from the resolve chain when env unset. +- Harness CLI prompts flaky → artifacts keep raw output; incomplete rows report `—` + and never synthesize. +- SDK already wraps the 2026-07-28 channel → `protocol_survey` pins the SDK version + tested and cites spec sections, so later re-probes are comparable. +- `dirtree-rdm` grammar rigidity → leaf consistency checks run `uv run ruff check`, + `uv run pytest -q`, and `test -s` probes as literally written; no check depends on + a not-yet-existing deliverable except where exempt. + +## Roadmap Recommendation + +Campaign `__roadmap__/workspace_discovery/` (Tier 2): root leaves +`probe_instrumentation` (server probe + tests, Agentic-Small) and `protocol_survey` +(MCP spec/SDK channel research, Reasoning-Medium) run in parallel; then +`evidence/collect_harness_evidence` (raw JSONL per harness, Agentic-Small) runs +depth-ordered after both. Findings report (batch 01) authored by the lead from +probe artifacts; architecture revised as `02-architecture_v1.md` if evidence +contradicts a rung. Adversarial-verifier dispatch is pledged for +`probe_instrumentation` (measurement semantics + silent-failure risk). diff --git a/__reports__/workspace_discovery/01-findings_harness_probe_v0.md b/__reports__/workspace_discovery/01-findings_harness_probe_v0.md new file mode 100644 index 0000000..f715c53 --- /dev/null +++ b/__reports__/workspace_discovery/01-findings_harness_probe_v0.md @@ -0,0 +1,109 @@ +# Harness probe — Findings (v0) + +Date: 2026-11-27 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-27 +version: v0 +prior-version: none +key-metric: dynamic_channels_work: 0 harnesses with a live dynamic rung (prior: N/A, delta: N/A) +decision-required: confirm +--- + +## Headline Result + +metric: dynamic_channels_work +value: 0 — all three fleet harness rows measured silent on every dynamic channel +unit: harnesses with a live dynamic rung measured (of 3 fleet rows; both across-run static cells also `—`) +prior: N/A +direction: new + +## Results Tables + +### Harness × workspace-signal matrix (fleet rows, condensed from the probe matrix) + +Every gap cell is `—` (silence — gap record, no R01-schema fields emitted), or a measured +row is absent from the raw store. No cell is inferred from R03b or any prior run. + +| harness | initialize capabilities | request `_meta` keys | `roots/list` verdict | successor (2026-07-28) | spawn env relevant vars | Resolution Picks | Notes | +|:--------|:------------------------|:---------------------|:----------------------|:------------------------|:-------------------------|:------------------|:------| +| `claude` | — | — | — | — | — | `fail+guidance` | gap record `claude_tool-20261127_141546.jsonl`:`{"error": "claude completed but no probe record written"}` — no R01-schema fields emitted | +| `codex` | — | — | — | — | — | `fail+guidance` | gap record `codex_tool-20261127_141606.jsonl`:`{"error": "codex completed but no probe record written"}` — no R01-schema fields emitted | +| `copilot-agent-plugins` | — | — | — | — | — | `fail+guidance` | no `copilot_tool-*.jsonl` present in raw store; reuse-by-filename-match absent, row recorded as `—` | + +### Channel map (R02 station ids, per R01 §Per-harness measurement matrix) + +| Channel | Station (R02) | Verdict (R02) | Fleet measurement | +|:--------|:--------------|:--------------|:------------------| +| initialize capabilities | Station 3 | static — once per spawn | `—` (no measured cell) | +| request `_meta` keys | Station 2 | dynamic if host stamps | `—` (no measured cell) | +| `roots/list` + successor | Station 1 | static (R02, superseded at the lab level by R03b) | `—` (no measured cell) | +| spawn env `COLGREP_MCP_ROOT` pin | env (launch pin) | static — process lifetime | `—` (no measured pin) | + +## Observations + +| Signal | Baseline / Expected (R01 ladder) | Observed [source] | Interpretation | +|:-------|:--------------------------------|:------------------|:---------------| +| `request _meta` vendor keys (rung 1: dynamic) | R01 proposed the server read a workspace stamp from per-call `_meta` (R02 Station 2: dynamic input) | `—` in all three fleet rows; gap records `claude_tool-20261127_141546.jsonl` / `codex_tool-20261127_141606.jsonl` hold only `{"error": "… completed but no probe record written"}`; the `copilot-agent-plugins` row has no record at all [source: `probe_data/harness/matrix.md`; `probe_data/harness/raw/claude_tool-20261127_141546.jsonl`; `probe_data/harness/raw/codex_tool-20261127_141606.jsonl`] | No fleet harness was measured stamping a per-call workspace value. The wire mechanism is proven cooperating-client-only (R03b); a real host stamping `_meta` is unmeasured, so the ladder's rung 1 is not exercised by any fleet row and the pick falls past it. | +| `roots/list` per call (rung 2: dynamic) | R01 proposed lazy per-call roots, awaiting the round-trip (rung 2 consumes the R03b race fix) | `—` in all three fleet rows — no `roots/list` verdict recorded for any harness [source: `probe_data/harness/matrix.md`] | The per-call roots channel R03b saw on a cooperating client was not reproduced by any fleet harness run. Rung 2 is unmeasured in the fleet; per-call roots remain a consumption-side capability awaiting a host that answers. | +| `initialize` capabilities (rung source, Station 3) | R01: once-per-spawn announcement, static (R02 Station 3) | `—` in all three fleet rows [source: `probe_data/harness/matrix.md`] | No fleet harness contributed an `initialize` capability probe either; the static rung is unmeasured at the fleet level, so no harness qualifies an initialize-stamped dynamic source. | +| `roots` successor post-2026-07-28 (rung 2 source) | R01 named the successor as a prerequisite before rung 2 promotes roots over the fallback | `—` in all three fleet rows [source: `probe_data/harness/matrix.md`] | No successor channel was observed on any fleet harness. R02's Station-1-open question (name the successor) stays open at the fleet level; the ladder keeps roots as at-best-static during this run. | +| spawn env `COLGREP_MCP_ROOT` pin (rung 3: pin) | R01 rung 3: a static explicit pin outranks inferred signals; only lever if server reads it | `—` in all three fleet rows — no launch env vars measured [source: `probe_data/harness/matrix.md`] | No fleet harness run supplied/measured a `COLGREP_MCP_ROOT` pin. The pin rung is a consumption-side, spawn-time lever; with none measured it is not the pick any harness earned this run. | +| Guarded-cwd fallback + fail+guidance (rung 4) | R01 rung 4: guarded cwd fires `ROOT_UNRESOLVED` + guidance (remedy names an absolute `paths` entry) only when no higher rung produced a root | All three fleet rows fell to the bottom of the ladder: no dynamic signal, no pin → guarded cwd → fail+guidance contract [source: `probe_data/harness/matrix.md`; consumption side already landed on this branch at `157b0a9` (ladder + guided failure)] | With both dynamic channels silent and no pin measured, the ladder's only honest landing for every fleet row is the guarded-cwd rung whose contract is `fail+guidance`: an error naming `paths` with an absolute directory, never a silent wrong root. This is what the measurement dictates, not an invented success. | + +### Slice counts (picks distribution) + +| R01 rung id | Harnesses it qualifies (measured) | +|:------------|:----------------------------------| +| `dynamic` | 0 | +| `pin` | 0 | +| `guarded-cwd` | 0 (as a *successful* resolution rung — no harness resolved a root) | +| `fail+guidance` | 3 (the bottom contract every silent row falls to) | + +## Charts & Visualizations + +```mermaid +graph TD + T[tool call, no explicit paths] --> D["dynamic workspace signal (rung 1, request _meta; rung 2, per-call roots)"] + D -.->|absent in all 3 fleet rows measured| P["COLGREP_MCP_ROOT pin (rung 3)"] + P -.->|no pin measured| C["guarded cwd (rung 4)"] + C -->|guard: cwd is install tree| F["ROOT_UNRESOLVED + guidance: pass an absolute paths entry"] + D --> RK[resolved root, root_source recorded] + P --> RK +``` + +Caption: measured fall of the fleet harnesses — every row landed past `dynamic` and `pin` (both `—`) onto the guarded-cwd rung's `fail+guidance` contract; no dynamic channel was measured live, so `dynamic_channels_work` counts 0. Units: fraction of the 3 fleet rows exercising each rung = 0/3 for rungs 1–3, 3/3 reaching the guarded-cwd fail+guidance. + +## Contradictions & Surprises + +- Mechanism vs fleet silence: R03b measured both per-call channels working on the wire (`request _meta` vendor keys and per-call `roots/list`, in `live_lab-a/b_tool-search.jsonl` and both wire transcripts), yet the fleet harness rows are uniformly `—`. The protocol carries the signal; no fleet harness emitted a probe record — the all-`—` matrix reflects sample availability, not a measured absence of the channels. +- R02's Station-1 "static, no successor" verdict was superseded at the lab level by R03b, but the fleet rows still record Station 1 as `—`: supersession happened on a cooperating client, not on any fleet harness — both statements coexist without contradiction once the layer (lab wire vs fleet harness) is named. +- Fleet census gap: two of the three harnesses were transport-auth-gated ("OAuth session expired" for `claude -p`, "401 Unauthorized" for `codex exec`) in the R03b run and reappear here as probe-record gaps; Copilot measured silent in R03b (fell to `cwd` = plugin install tree). A re-probe from authenticated sessions is the only path that can open `—` cells. + +## Steering Questions + +- [now] Confirm the next-campaign ship scope: obtain live dynamic signals by replaying the two auth-gated harnesses (Claude Code, Codex) against the instrumented server, and re-running the Copilot host probe — until then every fleet row stays `—` and ships nothing new. +- [now] Adopt `fail+guidance` as the production default for all three harnesses meanwhile: with no dynamic channel and no pin measured, the rung-4 contract (error names `paths` with an absolute directory — the pivot the sponsor specified over a bare loud failure) is the only safe resolution, already landed on this branch at `157b0a9`. +- [next run] Name the roots successor (R02 Station 1 opener): only then can rung 2 promote roots over the current fallback; the fleet `—` keeps it deactivated as a rung source for now. +- [next run] Measure the launch pin: the fleet recorded no `COLGREP_MCP_ROOT` value; a spawn-time pin probe would isolate whether rung 3 (pin) needs host support or is purely a server consumption-side lever. +- [later] Decide the serve-side `_meta`-consume and roots race-fix integration timing (lab-proven in R03b, landed in `6c1cb8a`/`30aad59`) against host-side stamping once a fleet harness actually stamps one of the channels. + +## Pointers + +- [matrix](../../__reports__/workspace_discovery/probe_data/harness/matrix.md) +- [claude gap record](../../__reports__/workspace_discovery/probe_data/harness/raw/claude_tool-20261127_141546.jsonl) +- [codex gap record](../../__reports__/workspace_discovery/probe_data/harness/raw/codex_tool-20261127_141606.jsonl) +- [live lab a](../../__reports__/workspace_discovery/probe_data/harness/raw/live_lab-a_tool-search.jsonl) +- [live lab b](../../__reports__/workspace_discovery/probe_data/harness/raw/live_lab-b_tool-search.jsonl) +- [wire 2026-07-28](../../__reports__/workspace_discovery/probe_data/harness/raw/wire-2026-07-28.log) +- [wire 2025-11-25](../../__reports__/workspace_discovery/probe_data/harness/raw/wire-2025-11-25.log) +- [R02 protocol survey](../../__reports__/workspace_discovery/01-findings_protocol_survey_v0.md) +- [R03b live probe](../../__reports__/workspace_discovery/03-findings_live_probe_v0.md) +- [dump-only signature](../../__reports__/workspace_discovery/04-findings_dump_only_signature_v0.md) +- [R01 architecture](../../__reports__/workspace_discovery/00-architecture_v0.md) + +## Decision + +**decision-required = confirm**: ship the next campaign from the fleet's measured silence. `dynamic_channels_work` counts 0 — every fleet harness row is `—` on request `_meta`, per-call roots, and the rest; the per-harness `Resolution Picks` are all `fail+guidance`, the rung R01's ladder falls to when both dynamic channels and any pin are silent. So the next campaign's per-call resolution ship scope is: wire `resolve_target_paths` to consume the lab-proven channels only where a fleet harness actually stamps one (the `request _meta` consume and per-call roots await/cache landed at `6c1cb8a`/`30aad59`; the ladder + `ROOT_UNRESOLVED` guided failure at `157b0a9`), and default every harness that still ships `—` to the fail+guidance contract — an error naming `paths` with an absolute directory as the remedy (the sponsor-specified pivot, never a bare loud failure and never a silent wrong root) — until a re-probed, authenticated fleet run yields live dynamic signals that promote a harness onto the `dynamic` rung. diff --git a/__reports__/workspace_discovery/01-findings_protocol_survey_v0.md b/__reports__/workspace_discovery/01-findings_protocol_survey_v0.md new file mode 100644 index 0000000..e37b839 --- /dev/null +++ b/__reports__/workspace_discovery/01-findings_protocol_survey_v0.md @@ -0,0 +1,79 @@ +# Workspace channels — Findings (v0) + +Date: 2026-11-13 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-13 +version: v0 +prior-version: none +key-metric: dynamic_channels_found: 2 of 3 stations can carry a per-call workspace value (prior: N/A, delta: N/A) +decision-required: confirm +--- + +## Headline Result + +metric: dynamic_channels_found +value: 2 +unit: stations of 3 capable of per-call (dynamic) resolution +prior: N/A +direction: new + +## Results Tables + +### Station verdicts (R01 R02 stations) + +| Station | Verdict | evidence_for | invoker | duration | invoker_coverage | +|:--------|:--------|:--------------|:--------|:---------|:-----------------| +| 1. client roots capability (roots/list + roots/list_changed + successor) | static | server/colgrep_mcp/paths.py S.client_roots docstring (in-fleet artifact, self-declared deprecated as of the 2026-07-28 protocol revision); lead-observed run warning on mcp SDK 2.2.0: MCPDeprecationWarning in mcp/server/mcpserver/context.py line 374 (The logging capability is deprecated as of 2026-07-28 (SEP-2577)) | host | once per spawn at best | partial: any value is a then-current snapshot; a roots successor could push it (the what-could-settle-it opener below) | +| 2. request _meta on tools/call | dynamic | mcp SDK 2.2.0 ServerRequestContext exposes meta: RequestParams.Meta (progress_token) per implementer report 6fd3edc inspection of server/.venv pins; cross-checked lead-side against that pin's context.py import | host | per call | full if the host stamps it; item under Contract (S01) records whichever par is there -- absence is recorded as None | +| 3. initialize handshake context | static | AGENTS.md report legend R05 M1 (client_roots measures the initialize result's declared capability, not a stale enumeration; agent-plugins Oslo absent implies no addressable dynamic source -- kept as claim of shape in R01 S01) | host | once per spawn | partial: one announcement per session; workspace switch mid-life needs a new source | + +### Channel mechanism boundary (formats and triggers) + +| Channel | Window | Trigger | Validation | Notes | +|:--------|:-------|:----------|:-----------|:------| +| MCP request meta (_meta on tools/call) | per call | every tool call | the probe dump schema keys init_capabilities / request_meta; recorded verbatim whether present or absent | terminal candidate for the 2026-07-28 clarification yes or no; the ZERO UNKNOWN from R01 stays frozen | +| MCP roots (list + list_changed) | session | handshake, push notification | deprecation recorded by being one-shot's self-announcement plus the SDK 2.2.0 deprecation string naming SEP-2577 (see query card below) | if a successor channel exists (dynamic roots / URI templates, plural-but-unknown), it too rides the SAME wire: needs a name before the ladder promotes rung 1 | +| Launch env (COLGREP_MCP_ROOT pin) | process lifetime | spawn (host or user recipe) | Settings.from_env flips a literal; pin outranks new dynamic sources by design (R01 S01) | this is the storyboard's static pin; accepted defect label -- stale on workspace switch, one-shot by nature | +| plugin-manifest placeholders | none | none | Agent Plugins 1.0 S9.2 expansion freeze: only ${PLUGIN_ROOT} / ${PLUGIN_DATA}; unconforming text stays literal | cannot carry a host workspace value in a spec-conformant client; a fourth manifests channel does not exist | + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:-------|:--------------------|:------------------|:----------------| +| Deprecation timestamp in the wild | R01 and paths.py both cite a 2026-07-28 protocol revision; no ground truth seen | mcp SDK 2.2.0 emits a real MCPDeprecationWarning naming 2026-07-28 SEP-2577 [source: lead-side re-gate of task/probe-instrumentation, 2026-11-13, .venv site-packages pin] | The 2026-07-28 revision exists AS A TIMESTAMP the ship-the-pin SCHEDULE references; whether it replaced roots/list wholesale is NOT established from this datum alone (SEP-2577 is the LOGGING deprecation, not a roots one). Verdict cell stays static + the opener below. | +| Station 2 (per-call meta) capability | R01 expected the launch-time hierarchy for 2 and 3 | ServerRequestContext carries a meta field (RequestParams.Meta with progress_token) [source: implementer 6fd3edc reading of mcp SDK 2.2.0 .venv source] | Structurally the channel a host could stamp per call; whether the three surveyed hosts DO stamp is a harness facts question (R03 probe fleet -- level-2 pre-condition). | +| Manifest channel scope | Two plugin-variable placeholders might cover a workspace ala Claude Code's ${CLAUDE_PROJECT_DIR} | Agent Plugins 1.0 S9.1-S9.2: clients MUST NOT perform any other expansion; env values are opaque strings not secrets [source: lead-verified fetch of agent-plugins.org/specification S9.1-S9.2] | Confirms prior analysis: within Agent Plugins, a pinned value is supplied at spawn (host or user), never read from the package. | +| Fleet gap safety | R01 requires every cell a raw measurement or an honest gap | Two protocol-survey dispatch rounds never ran (zero turns, session suspension) [source: task tool history, campaign lead] | This report itself surveys mechanism; behavioural cells are R03's target and remain unfilled by design -- gap stays visible rather than fabricated. | + +## Charts & Visualizations + +```mermaid +graph LR + meta["request _meta / (Station 2) - dynamic"] --> rung1["ladder rung 1: dynamic workspace signal"] + roots["roots capability / (Station 1) - static, deprecated"] --> rung2["ladder rung 2: root honour (tsould remain read lazily)"] + env["launch env pin / (Station: env) - static"] --> rung3["ladder rung 3: COLGREP_MCP_ROOT pin"] + man["manifest placeholders / (Station 4) - none"] -.->|expansion freeze N9.2| dead["no rung"] +``` + +Caption: rung provenance for each measured channel; only Station 2 is dynamic, and only if the host stamps it (the fleet probes decide per host). + +## Contradictions & Surprises + +- Name-of-revision real, subject-matter mismatch: SEP-2577 (the thing that names 2026-07-28 in the observed warning) is the LOGGING deprecation, not a roots one. The repo's own claim that roots is deprecated "as of the 2026-07-28 revision" may rest on a different SEP never pinned in-fleet (see Steering [later]). + +## Steering Questions + +- [now] Confirm one acceptance before R03: when every dynamic station is absent for a host, the failure is fail+guidance (error names an absolute `paths` entry as the remedy), per sponsor decisions -- no silent fallback to install-dir cwd (close the ladder there). +- [now] Name the roots successor (or confirm there is none): searches `roots/list` successor means promoting rung-1 roots over the current fallback instead of folding roots INTO the workspace signal. Until named the roots channel stays static at best, deactivated as a rung source. +- [next run] R03 fleet: measure whether hosts actually stamp request meta / a roots successor; the mechanism this survey establishes cannot answer the behavioural point. +- [later] Pin canon: which SEP replaced/expanded roots (SEP-2577 family). Requires context7-mcp (the user-specified third-party channel) -- beyond raw local pins; recorded so the next session starts this probe where this one ended. + +## Pointers + +- ../../__roadmap__/workspace_discovery/README.md (campaign gates, ownership) +- ../../__reports__/workspace_discovery/00-architecture_v0.md (R01 law and matrix contract) +- ../../server/colgrep_mcp/paths.py (in-fleet client_roots self-claim) +- ../../server/colgrep_mcp/probe.py (dump schema keys to be confirmed at R03; file withdrawn at c7c6377 pending the hardening fix, see 02-gap_analysis_calibrated_probe_v0.md) diff --git a/__reports__/workspace_discovery/02-findings_probe_verifier_v0.md b/__reports__/workspace_discovery/02-findings_probe_verifier_v0.md new file mode 100644 index 0000000..4c8d1c0 --- /dev/null +++ b/__reports__/workspace_discovery/02-findings_probe_verifier_v0.md @@ -0,0 +1,82 @@ +# Probe verifier — Findings (v0) + +Date: 2026-11-13 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-13 +version: v0 +prior-version: none +key-metric: dump_only_law: REFUSED (UNSOUND) (prior: N/A, delta: N/A) +decision-required: intervene +--- + +## Headline Result + +metric: dump_only_law +value: REFUSED (UNSOUND) +unit: adversarial signer verdict +prior: N/A +direction: new + +## Results Tables + +### Lever attack outcomes (verifier: probe-verifier-v3, dispatched at escalated tier) + +| Lever | Outcome | Proof | +|:------|:--------|:------| +| 1. Silent falsification (record fabrication) | exploitable | `probe.py` `_probe_tool_name()` frame scan always resolves to `record` itself, so every ledger line claims `"tool": "record"`; `probe.py:88-92` maps an exceptioning `client_roots` (per `paths.py:60-61` `except` call) to `{"static": "empty"}` — an emptiness the harness never sent | +| 1b. Doctor-stub impersonation | exploitable | `probe_workspace.py:51-70` stub synthesizes full R01 records with literals `"init_capabilities": None`, `"request_meta": None`, `"roots_list": {"static":"empty"}` on every invocation; `validate()` (`:158-183`) checks key presence only and passes them | +| 1c. getattr fallbacks (`init_caps`/`req_meta`) | inconclusive (execution-blocked) | statically: absent values recorded as `None`, never synthesized; live probe runs and `context7`-routed source inspection were both permission-denied at the dispatcher end | +| 2. Env-value escapes (`=""`, `=0`, `=/dev/null`, parent-is-file) | not exploitable (with debris) | `=""` inert at `probe.py:84`; `/dev/null` and parent-is-file raise `FileExistsError`/`NotADirectoryError` ⊂ `OSError`, caught (`:133-135` buffer) → `safe_log`, no debris; bare `=0` writes `./0/colgrep_probe.jsonl` in server cwd — documented-location debris, not a law break | +| 2b. Raise past the inertness law | exploitable (reachability inconclusive) | `capture_pure(record_obj)` (`probe.py:132`) sits outside the `try`/`except OSError`; a non-`model_dump`, non-serializable snapshot value raises `TypeError` through `_probe_record` → `paths.py:113`, breaking the tool call the module docstring promises never to break | +| 2c. Probe-on/off resolution difference | not exploitable | records write only under `$COLGREP_MCP_PROBE/` (`:133-135`), `default_root` is pure and inputs untouched — byte-identical outcomes except when 2b fires | +| 3. Regression honesty (`test_no_probe_side_effects`) | exploitable (blind oracle) | test deletes `COLGREP_MCP_PROBE` first (`test_probe.py:229`), so `record()` early-returns nothing observable; its sole post-call assertion re-reads the environment variable (`:247-251`), never a ledger; fs assertions check filenames the implementation never writes (`probe.jsonl`, `~/colgrep_probe.jsonl` vs the real `colgrep_probe.jsonl`) rather than content. A probe fabricating `init_capabilities` passes the whole test. | + +### Driver liveness audit + +| Surface | Outcome | Proof | +|:--------|:--------|:------| +| Real-colgrep leak | PASS (no violation) | the driver's only `subprocess.run` is `[harness_exe, "-p", TRIGGER_PROMPT]` (`probe_workspace.py:110`); `colgrep` is reached solely as the stub it writes (`:81-94`); no test writes `~/Library/Application Support/colgrep` or `~/.local/share/colgrep` (those strings are fixture text only) | + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:-------|:--------------------|:------------------|:----------------| +| Ledger can prove its own provenance beyond stub-written copies | R01 probe dump schema contract (report `00-architecture_v0.md`) | Stub-written records pass `validate()` unchanged [source: verifier lever 1b, repro static] | The evidence plan cannot trust any matrix cell whose `init_capabilities`/`roots_list` value equals the stub's hardcode | +| Always-non-raising claim in `probe.py` docstring | Leaf step 1 law ("best-effort" never raises) | `capture_pure` outside the try boundary, `TypeError` reachable through resolve path [source: verifier lever 2b] | Even one non-serializable snapshot breaks tool calls — the leaf's own headline invariant fail, not cosmetic | +| Root cell for a failed round-trip | The word `empty` should mean "genuinely nothing sent", distinct from "we couldn't ask" | Both collapse to `{"static": "empty"}` [source: verifier closed-workflow finding 6] | A matrix whose "race" column means "the call errored" cannot be scores for the campaign's Station 1 decision — this invisibly biases rung picks | +| Fleet validation path | `validate()` reports gap records as gaps, not crashes | Gap records crash `_validate_record` (key `snap["ts"]`) [source: verifier closed-workflow finding 5] | The driver literally cannot use its own gap signalling; needs tolerance before R03 uses it | + +## Charts & Visualizations + +```mermaid +graph TD + stub["_STUB_SCRIPT writes R01-shaped record"] --> doctor["doctor tool call"] + doctor -.->|"bypasses resolve_target_paths"| nonemissive["no server record written"] + nonemissive →|stub lines only| ledger["colgrep_probe.jsonl"] + validate["validate() checks keys only"] -->|passes| ledger + matrix["R03 matrix cells read ledger"] -->|believes| falsified["falsified init_capabilities / roots_list"] +``` + +Caption: verifier's exploitation chain (lever 1b + lever 3); every matrix cell values a record the harness never sent, and the gate designed to catch it never read the ledger. + +## Contradictions & Surprises + +- The probe module's *architecture doc* (R01 §Contracts & Invariants) already stated the dump-only invariant and the "raw values only" law — the defect is not a missing contract but a missing calibration witness (see the independent Gap Analysis `02-gap_analysis_calibrated_probe_v0.md` root cause). + +## Steering Questions + +- [now] Accept the gap analysis: probe must ship a truth-source oracle (`forge_record`/`diff_record`) and the stub must mark record provenance before any harness run is trusted. +- [now] Decide whether the driver's gap-record path or the provenance-marking change moves first (ordering for the fix leaf). +- [next run] A fresh verifier (protocol-adjusted ask of the same campaign-lead attack) must sign the repaired probe before `evidence/` dispatch opens. +- [later] Generalize: any collected evidence tool in this repo defaults to shipping its own calibration fixture ("tests can run is not tests can prove") — codify in `maintainer-policy` once (a future campaign). + +## Pointers + +- ../../__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md — gap analysis built on these findings +- ../../__roadmap__/workspace_discovery/README.md — campaign debt note this supersedes +- ../../server/colgrep_mcp/probe.py — defect region 1, 1c, 2b, 6 (file withdrawn at c7c6377; review against the tagged history at ca3cb40 for these fixes) +- ../../server/tests/test_probe.py — defect region 3 (withdrawn c7c6377) +- ../../server/tests/e2e/probe_workspace.py — defect regions 1b, 5 (withdrawn c7c6377) diff --git a/__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md b/__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md new file mode 100644 index 0000000..aef3601 --- /dev/null +++ b/__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md @@ -0,0 +1,123 @@ +# Gap Analysis: workspace_discovery - probe records cannot be trusted + +## Problem Statement + +The probe instrumentation shipped at `ca3cb40` cannot distinguish a +record the harness actually produced from a record the test harness's +`colgrep` stub fabricated. Every leg of the level-2 evidence plan (the +harness × signal matrix, the batch-01 findings rung picks) rests on +probe records *provably* being harness-sent. The adversarial verifier +finding at `02-findings_probe_verifier_v0.md` (this session, layered verdict +UNSOUND) proves they need not be, and one of the four levers actively breaks +the leaf's own law ("a probe must never break a tool call"). The structure +of the defect collection is what matters: three independent places where +the probe can lead the campaign astray exactly on the columns the campaign +exists to fill (`init_capabilities`, `request_meta`, `roots_list`). + +## Evidence + +Dumped severity leads (full verbose trace at `02-findings_probe_verifier_v0.md`, +not repeated here): + +1. **Stub impersonation (silent falsification, exploitable).** + `server/tests/e2e/probe_workspace.py`'s `_STUB_SCRIPT` (`:51-70`) writes fully + R01-shaped JSONL records hardcoded with `"init_capabilities": None`, + `"request_meta": None`, `"roots_list": {"static": "empty"}`. The + `doctor` tool resolves its root locally in `tools_index.py:331-339` (bypassing + `resolve_target_paths`), so **no server-side record is ever written** — the + stub's synthetic lines *are* the whole ledger, and `validate()` (`:158-183`) + passes them on key-presence alone. The repro, if executed, is a + single-stub run producing a complete-looking R01 record with no harness + having spoken. That directly falsifies the R03 matrix columns. + +2. **Tool-name fabrication (silent falsification, exploitable).** + `server/colgrep_mcp/probe.py`'s `_probe_tool_name()` frame scan resolves to + the `record` function itself every time, so each ledger line claims + `"tool": "record"` — a factually false value in the column that tells the + matrix which observation fired. + +3. **Non-`OSError` escape (law break, exploitable).** + `capture_pure(record_obj)` at `probe.py:132` sits *outside* the `try`/`except + OSError` that claims "never raises"; a non-`model_dump`, non-serializable + snapshot key turns into a `TypeError` that travels up through the + `resolve_target_paths` call site (`paths.py:113`) — a tool call corrupting + the very resolve path the module docstring promises never to touch. + +4. **Blind dump-only oracle (regression honesty, exploitable).** + `test_no_probe_side_effects` deletes `COLGREP_MCP_PROBE` first + (`test_probe.py:229`), so `record()` early-returns nothing observable; + its sole post-call assertion re-checks an environment variable + (`:247-251`), never reading a ledger or comparing a value. Its background + filesystem assertions probe filenames (`probe.jsonl`, `~/colgrep_probe.jsonl`) + that the implementation never writes (the real one is `colgrep_probe.jsonl`). + A probe that fabricates `init_capabilities` passes the whole test. + +5. **Gap-record crash (driver hygiene).** `_validate_record` (`:167-172`) keys + on `snap["ts"]`, so the driver's own `{"error": ...}` gap record + (`:112-118`) raises rather than reports — the driver cannot use its own + gap signalling. + +6. **Roots classification loses the `error` case (format assertion).** + `probe.record` maps "no pin and `client_roots` returned `None`" and "`client_roots` + dereferenced an exception" to the *same* `"empty"` value, so the matrix has + no way to tell "the harness sent nothing" from "the round-trip failed". + +## Root Cause + +The leaf was authored against a dump-only contract (`R01` §Contracts & Invariants) +but its implementation was given no truth-source oracle to prove the contract: +no fixture exists that fabricates a record from *known* ground truth and +checks an independent differ catches the issued-with-barrier. The first two verifier +dispatch rounds died before delivering any output, so the defect reached +merge approval on the implementer's self-report alone. Root cause is not "the code was written +sloppily" — it is "the campaign shipped an *accreditation-based* probe +implementer without a *commissioning* artefact to build trust. A gap analysis +whose success criteria are 'the ledger correctly separates known +fabrication' would have caught lever 1 at authoring time. + +## Impact Assessment + +- **In scope**: the full probe chain — `probe.py` truth-source columns, + the never-raise boundary, `test_probe.py`'s oracle fixture, `probe_workspace.py`'s + stub-vs-server provenance and gap-record tolerance. +- **Out of scope**: `paths.py` precedence behaviour (unchanged and separately + guarded by pre-existing resolve tests), the harness fleet run itself, any + report already published (`00-architecture_v0.md`, `01-findings_protocol_survey_v0.md`). +- **Risk if unaddressed**: every R03 matrix cell backed by a probe run is + unfalsifiable; a gap in the snapshot of the `_meta` station could be a stub + default carried all the way to the milestone `02-architecture_v1.md`'s + lowest-level decisions — the exact failure mode the earlier sponsor-called + loud-fail+guidance discussion existed to prevent. + +## Proposed Solution + +A hardening leaf, `probe_hardening`, at level 1 (sibling of `probe_instrumentation`, +before `evidence/`), composed of four steps: +1. Truth-source repair of the ledger columns (`tool`, `roots_list`'s `error` + class distinct from `empty`). +2. Non-raise hardening: make every code path in `record` total for arbitrary + inputs (no `TypeError` can escape past `resolve_target_paths`). +3. Calibration oracle fixture (`forge_record` / `diff_record`) — a ground-truth + record builder and an independent differ whose disagreement test must + whistle when given the stub's exact fabrication (a committed proof the + harness can catch a liar). +4. Provenance + gap-record hygiene in `probe_workspace.py` (stub-authored + records marked; `{"error": ...}` gaps reported, not crashed over). +Completion requires (a) the calibration test failing against the shipped +faulty state then passing after; (b) the rebuilt dump-only oracle reading the +real ledger record and asserting verbatim equality against constructed truth; +(c) a re-run of the existing suite green; (d) a fresh adversarial verifier +signature replacing the UNSOUND one before any evidence-level dispatch. + +## Recommendations + +1. **Hold level 2 (`evidence/`) until this leaf lands and is adversarially + re-verified.** A signature superseding the UNSOUND verdict is the + pre-condition recorded in the campaign's roadmap Gotchas. +2. **Each future leaf pair (implementer + adversary) must ship a calibration + or truth-source omelette-sized artefact alongside its feature** — briefs + and gates verify code can be *run*; only a fixture tied to ground truth + verifies code can be *trusted*. +3. **`forge_record` / `diff_record` are generic probe utilities, retained under + `probe.py` (not test-only) so the evidence leaf's own matrix validator can + reuse them** rather than hand-rolling a second, drifting differ. diff --git a/__reports__/workspace_discovery/03-findings_amendment_review_v0.md b/__reports__/workspace_discovery/03-findings_amendment_review_v0.md new file mode 100644 index 0000000..2020d68 --- /dev/null +++ b/__reports__/workspace_discovery/03-findings_amendment_review_v0.md @@ -0,0 +1,51 @@ +# Amendment Review — Findings (v0) + +Date: 2026-11-13 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-13 +version: v0 +prior-version: none +key-metric: amendment_decision: APPROVE (confidence: high) (prior: N/A, delta: N/A) +decision-required: confirm +--- + +## Headline Result + +metric: amendment_decision +value: APPROVE +unit: reviewer verdict on the `probe_hardening` amendment (confidence: high) +prior: N/A +direction: new + +## Results Tables + +### Review columns (amendment-review-bound, dispatch turn 0, 12s) + +| Column | Reviewer verdict | Independent source check | +|:-------|:-----------------|:-------------------------| +| Validity of gap as stated | Real | Confirmed against `probe.py`, `test_probe.py`, `probe_workspace.py`: three-plus silent-falsification / raise-escape paths on exactly the `tool`, `init_capabilities`, `roots_list` columns the evidence matrix must trust | +| Root-cause vs impact consistency | Consistent | The missing-calibration-witness root cause flows directly into the blind-oracle finding and the unfalsifiable-matrix impact; no overreach identified | +| Proposed solution fit vs never-raise law | Strong fit | Hardening steps make `record` total for arbitrary inputs (closing the confirmed `TypeError` escape past `paths.py:113`) inside the module's own "must never raise" law; consistent with maintainer-policy §one-idiom-per-concern and §hardware-first | +| Recommendations practical vs prior contracts | Consistent | Holding level 2 until adversarial re-signature matches the roadmap Gotcha; retaining `forge_record`/`diff_record` under `probe.py` avoids drift, per gap-analysis recommendation 3 | +| Gap-analysis fidelity to cited findings | Faithful | Each cited lever (1b, 2, 2b, 3, 5, 6) reproduces the findings table; all six independently re-verified line-of-source (stub hardcodes, brittle `_probe_tool_name` frame scan, `capture_pure` outside the `try` block, env-var-only assertion, `snap["ts"]` KeyError on gap records, `roots_static` collapsing error into empty) | + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:-------|:--------------------|:------------------|:----------------| +| Formal review (amendments.md step 4) evidence must live in the reports store | Same rule that forced the findings into 02- files before the amendment dispatch | Reviewer verdict materialized here, not chat-only [source: run rules — chat is not association-visible] | The amendment's A1 source column can now legitimately widen from just the gap analysis to gap analysis + this verdict | +| Branch status updates (evidence dispatch hold) in pipeline | Already-rowed for protocol_survey gotcha | Blocked effect surface this epoch (denied roadmap batch) [source: runtime permission log] | Vicious: cannot hand-place `probe_hardening` node OR mark any leaf status until grant arrives | + +## Steering Questions + +- [now] Grant the roadmap batch authority once: `dirtree-rdm add probe_hardening.md` + one `dirtree-rdm update protocol_survey done` — one clean effect set, no retries bundled with unrelated commands (the bundling caused this epoch's denial). +- [next run] Implement `probe_hardening` at level 1 per the drafted steps, re-verify its calibration oracle failing on the shipped faulty state, then a fresh adversarial signer replaces the UNSOUND verdict before `evidence/` opens. + +## Pointers + +- ../../__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md — the proposal this verdict approves +- ../../__reports__/workspace_discovery/02-findings_probe_verifier_v0.md — the evidence base +- ../../__roadmap__/workspace_discovery/README.md — target of the pending amendment log update diff --git a/__reports__/workspace_discovery/03-findings_live_probe_v0.md b/__reports__/workspace_discovery/03-findings_live_probe_v0.md new file mode 100644 index 0000000..efe89e4 --- /dev/null +++ b/__reports__/workspace_discovery/03-findings_live_probe_v0.md @@ -0,0 +1,89 @@ +# Live workspace-signal probe — Findings (v0) + +Date: 2026-11-13 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-13 +version: v0 +prior-version: none +key-metric: dynamic_resolution_live: YES (measured on the wire; host-dependent) (prior: N/A, delta: N/A) +decision-required: confirm +--- + +## Headline Result + +metric: dynamic_resolution_live +value: YES — both per-call channels measured working; one host measured silent +unit: wire-verified channels of 2; host rows: 1 measured / 2 gated on auth +prior: N/A +direction: new + +## Results Tables + +### Channel measurement (lab wire probe, pinned mcp 2.2.0) + +| Channel | Negotiation | Measured behaviour | Per-call workspace? | +|:--------|:------------|:-------------------|:--------------------| +| request `_meta` vendor keys | both (2026-07-28 offered / 2025-11-25) | stamped keys (`com.example.workspace`, `com.example.note`) arrived verbatim in `request_meta` on the stamped call; `request_meta: null` on the unstamped control | **YES** | +| client roots (per-call `roots/list`) | both | `roots/list` emitted **during each `tools/call`** on the wire; answered `file:` root became `resolved {root: …/fakews, source: "roots"}`; unanswered round-trip fell back `{source: "cwd"}` | **YES** (with first-call race, below) | +| protocol dialect (server side) | both | server negotiated `2025-11-25` in both runs regardless of client offer; MRTR (`ListRootsRequest`) types present in SDK, unwired; `init_capabilities: null` (SDK exposes `client_capabilities`/`protocol_version` instead) | n/a — ceiling known | + +### Host rows + +| Host | Row source | Workspace per call? | Evidence | +|:-----|:-----------|:--------------------|:---------| +| Copilot (VS Code Agent Plugins, this session) | live observation of the shipped plugin server | **NO** — fell through to `cwd` = plugin install tree | `doctor` reported `default_root …/agentPlugins/…/1a1c9036c4d (source: cwd)`; path-less `search` returned only plugin-tree hits | +| Claude Code | attempted `claude -p` + instrumented server (`--mcp-config`) | unknown (gap) | `Failed to authenticate: OAuth session expired` — the documented `stack-traps` `{#oauth}` case; run command ready to replay | +| Codex | attempted `codex exec` with isolated `CODEX_HOME` | unknown (gap) | `401 Unauthorized: Missing bearer` (no credentials used, per policy); run command ready to replay | + +### Measured defects feeding the implementation leaf + +| Defect | Observation | Consequence | +|:-------|:------------|:------------| +| First-call roots race | call 1 recorded twice: first resolve `{items: [], static: "empty"} → source: "cwd"}`, second resolve same call `{items: [fakews]} → source: "roots"}` — identical pattern in **both** negotiation runs | the first tool call can resolve to the wrong root even when the host answers; resolver must await/cache the round-trip before falling back | +| `tool` column fabrication | every ledger row reads `"tool": "record"` | matrix attribution unusable until the thread-inspection fix (verifier lever 1) | +| `init_capabilities` blind spot | `null` on every row though the SDK exposes `client_capabilities`/`protocol_version` | probe schema must key on the 2026-07-28 presence-stable fields (suspected R2' defect, now live-confirmed) | + +## Observations + +| Signal | Baseline / Expected | Observed [source] | Interpretation | +|:-------|:--------------------|:------------------|:----------------| +| `_meta` vendor keys reach the server intact | R02 gap-analysis reservation "needs behavioural proof" | verbatim in `request_meta` on stamped call; `null` on control [source: probe_data/harness/raw/live_lab-a_tool-search.jsonl, live_lab-b] | the projection-route channel is real and parser-ready; per-key lookup is trivially safe to implement | +| roots resolves the workspace per call | R02 verdict "Station 1 static" (superseded) | `roots/list` per call on wire; answer became `resolved.source: "roots"` [source: wire-2026-07-28.log, wire-2025-11-25.log] | R02's station verdict was wrong about dynamics: with a cooperative client the ladder already resolves per call — the fix is consumption-side, not protocol-side | +| Copilot sends neither channel | the original bug report | `source: "cwd"` measurements this session [source: live-session `doctor` + path-less `search` results] | the user's symptom is exactly the host row of this table; server-side robustness + host `_meta`/roots support are the two halves | +| LLM-host census | 3 host rows expected | 2 rows blocked on transport auth, not protocol [source: claude -p / codex exec stderr tails, recorded in the run transcript] | replay cost is one authenticated session per host; commands pinned in the run notes | + +## Charts & Visualizations + +```mermaid +sequenceDiagram + participant H as Host (per tools/call) + participant S as colgrep-mcp resolver + H->>S: tools/call + _meta (vendor keys) + S->>H: roots/list (associated, per call) + H-->>S: file:// workspace root + S->>S: resolved {root, source: "roots"} + Note over S: race on first call: empty answer
must not defeat a late-late arrival +``` + +Caption: the measured happy path — both channels on one call; the noted race is the one defect found. + +## Contradictions & Surprises + +- R02 (01-findings_protocol_survey_v0.md) recorded Station 1 as `static`/no successor; the live wire shows per-call `roots/list` dynamics under the pinned SDK. Superseded by measurement, as intended by the gap-analysis remit. + +## Steering Questions + +- [now] Confirm the server fix scope for the next cycle: consume `_meta` vendor keys + proper per-call roots await/cache (race fix) + fail+guidance on empty; host `_meta`/roots support is the harness-side ask. +- [now] Replay the two host rows from an authenticated session (commands recorded above) before the R03 matrix closes `—` cells. +- [next run] Hardening (referential: `probe_hardening` remedy) lands before any production probe, per 02-gap_analysis; this lab run's ledger parsing is safe precisely because rows were schema-grepped at ingest. + +## Pointers + +- probe_data/harness/raw/live_lab-a_tool-search.jsonl — stamped/control records, negotiation offered 2026-07-28 +- probe_data/harness/raw/live_lab-b_tool-search.jsonl — replication run, negotiation 2025-11-25 (identical 3-record pattern) +- probe_data/harness/raw/wire-2026-07-28.log, wire-2025-11-25.log — per-message JSON-RPC transcripts (roots/list emission per call) +- 01-findings_protocol_survey_v0.md — R02, read with the Contradiction above +- 02-gap_analysis_calibrated_probe_v0.md — the hardening remedy whose gate this run respected diff --git a/__reports__/workspace_discovery/04-findings_dump_only_signature_v0.md b/__reports__/workspace_discovery/04-findings_dump_only_signature_v0.md new file mode 100644 index 0000000..7ef357e --- /dev/null +++ b/__reports__/workspace_discovery/04-findings_dump_only_signature_v0.md @@ -0,0 +1,70 @@ +# Dump-only probe signature — Findings (v0) + +Date: 2026-11-27 + +--- +type: findings +topic: workspace_discovery +date: 2026-11-27 +version: v0 +prior-version: none +key-metric: client_visible_dumps_parity: PASS (4/4 lists byte-identical) (prior: N/A, delta: N/A) +decision-required: none +--- + +## Headline Result + +metric: client_visible_dumps_parity +value: PASS — `Client.list_tools()` / `list_resources()` / `list_resource_templates()` / +`list_prompts()` are byte-identical between base and the hardened probe branch with +`COLGREP_MCP_PROBE` unset; the probe is inert at the client-visible surface. +unit: canonicalized listings compared (4) +prior: N/A (this closes the signature debt recorded in the campaign README Gotchas, +2026-11-13 `ca3cb40`) +direction: n/a (invariant discharge) + +## Results Tables + +### Client-visible listings, base vs task/probe-hardening (probe disabled) + +| Listing | n | sha256[:16] base | sha256[:16] branch | Result | +|:--------|--:|:-----------------|:-------------------|:-------| +| tools | 9 | `88714214c2d7908f` | `88714214c2d7908f` | equal | +| resources | 4 | `3c97ad1b6677e9b2` | `3c97ad1b6677e9b2` | equal | +| resource_templates | 1 | `627bc16ed6218d0f` | `627bc16ed6218d0f` | equal | +| prompts | 4 | `078a59b3f2053426` | `078a59b3f2053426` | equal | + +## Method + +Identical measurement script on both sides: an in-process `mcp.ClientSession` over +stdio against `uv run --quiet --directory server colgrep-mcp`, launched with +`COLGREP_MCP_PROBE` removed from the child environment. Each listing tuple +(name, description, canonical `inputSchema`/URI where applicable) is serialized +with `json.dumps(..., sort_keys=True)` and hashed (`hashlib.sha256`) before +comparison; the digests above are truncated to 16 hex chars for the table. + +- base: this worktree's merge base state — `main` as restored at `5b8b099`, whose + `server/colgrep_mcp/` has no probe facility (withdrawn by `8f9490f`). +- branch: `task/probe-hardening` at `75abe82` (probe re-landed hardened, four + commits `082e707..75abe82`). +- Run window: 2026-11-27 13:36 JST. + +## Interpretation + +The dump-only law of `probe_hardening` step 0 holds where a client can see it: +the probe adds no tool, resource, resource template or prompt, and mutates none, +when its env sentinel is unset. The complementary legs are already pinned +in-tree by `test_probe_inert_without_env` (no filesystem writes), the rewritten +`test_no_probe_side_effects` (ledger truth against `forge_record` ground truth), +and `test_tool_call_survives_probe_rename` (resolution paths unchanged with the +probe rename) — this report is the end-to-end MCP-surface leg the campaign +README lists as the pre-condition for dispatching `collect_harness_evidence`. + +## Caveat + +The two servers self-report versions found outside the leaf's owned files +(base `0.6.1`, branch `0.6.0`, from `pyproject.toml` sits the branch was cut +against); the version literal is not surfaced in any of the four listings +compared here, so parity is unaffected. The manifests/version literals are +written only by `cz bump` (`landing-and-release` §Release) and need no manual +edit. Residual risk: none identified for the probe's client-visible surface. diff --git a/__reports__/workspace_discovery/05-knowledge_transfer_v0.md b/__reports__/workspace_discovery/05-knowledge_transfer_v0.md new file mode 100644 index 0000000..e528161 --- /dev/null +++ b/__reports__/workspace_discovery/05-knowledge_transfer_v0.md @@ -0,0 +1,110 @@ +# workspace_discovery — Knowledge Transfer (v0) + +Date: 2026-11-27 + +## Executive Summary +- What shipped / changed: the sponsor-folded per-call resolution ladder + (`explicit paths → request _meta → client roots → COLGREP_MCP_ROOT pin → + guarded cwd / ROOT_UNRESOLVED guided failure`) landed across three BFS + levels — hardened dump-only probe (truth-sourced records, never-raise + boundary, calibration oracle), harness evidence collection, and the + adjudicating findings report — plus a signed dump-only invariant and four + lead-integrated verifier fixes (F1–F4). +- Primary outcomes: the silent-wrong-project default is gone (the ladder + never resolves a root the client did not name, and a fully silent call + fails with the absolute-`paths` remedy that verifiably works); the fleet + matrix is honestly all-`—` (`dynamic_channels_work = 0`), scoping the next + campaign; campaign branch gates green through `cz check --rev-range + origin/main..HEAD`; landing awaits the maintainer's `gh pr` launch. + +## Wins +- File-disjoint leaf ownership (stated in the roadmap Gotchas) + hand-cut + worktrees from the campaign branch → three level merges, zero conflicts. +- Fail-first discipline held at every landing: `test_first_call_roots_race_regression` + (`30aad59`), the probe/ladder truth pair (`d759d5e`), and the F1–F4 + close-outs each commit their own first red run in the commit body. +- Custom-endpoint dispatch with explicit slugs from `chatLanguageModels.json` + (`customendpoint/RiVault/RiVault/Reasoning-Medium`, no effort field) — + four of four dispatched agents completed; no `400 requested model` fallouts. +- The verifier's margin rule (break-the-guard probes sized to the artefact's + margin, sizes reported) produced four reproducible findings cheaply, and + the triage contract (in-roadmap findings fixed, out-of-scope → notice) kept + the close-out bounded. +- Concurrent evidence + resolution leaves were genuinely file-disjoint at the + file-graph level; the one shared runtime surface (`_probe_record` needing + ladder inputs) was caught by the lead's read-back verification and fixed + before the level closed. + +## Pain Points +- The permission model fail-closed the campaign's mutation spine (gate runs, + merges, host-path tool execution) with epoch-crossing memoization — whole + dispatch rounds died with zero output in earlier sessions, and `dirtree-rdm` + bookkeeping is still blocked (status tables stale at time of writing). +- A `revert(server)` subject (not in the cz vocabulary) survived two rebases + from an earlier round and was caught only by the campaign-range `cz check`. +- The harness rows are all `—`: a `doctor`-only trigger is never invoked by + `claude -p` / `codex exec` (auth-gated per R03b), so the matrix measures + sample absence, not channel absence. +- One brief mislabel ("git-ignored leftovers") sent the evidence implementer + to report committed citation evidence (`wire-*`, `live_lab-*`) as candidate + debris — caught at merge read-back and corrected as a boundary note. +- Cross-leaf call-graph coupling (`resolve_target_paths` → probe hook) between + two simultaneously dispatched leaves produced the `d759d5e` divergence. + +## Root Causes +- No stored allow rules for the DAG's critical commands → unattended roadmap + runs cannot complete their own merge/gate spine. +- Roadmap authoring tooling (`dirtree-rdm`) ships as a host-path plugin script + the workspace cannot execute under a workspace-scoped permission policy. +- File-disjoint ownership does not cover call-graph coupling: the probe hook + and the ladder share one runtime path, so both leaves needed the same helper + (`default_root` with `meta_root`) wired through `_probe_record` — that helper + should have been a pre-dispatch lead commit (campaign-lead rule 3). + +## Next-cycle Changes +1. Stamp allow rules for the recurring gate/merge spine (`git` merge/rebase/ + commit under `.worktrees/`, `uv run pytest|ruff|cz`) so unattended DAG runs + finish; leave destructive effects (worktree remove) prompting. +2. Move `dirtree-rdm` into the repo (`dev/skills/managing-roadmaps/scripts/`) + so bookkeeping never depends on host-path execution; run status writes at + every level close. +3. Dispatch policy: when two leaves share a call-graph path, sequence them or + pre-commit the shared helper — applies to any future `paths.py` + probe + pairing. +4. Evidence leaves must name their auth precondition in Pre-conditions and use + a trigger the target harness reliably invokes; `doctor`-only produced + honest but static evidence. +5. Run `cz check --rev-range campaign-base..HEAD` at level START as well as + close — legacy subjects should burn at rebase time, not at the end. +6. Carry the close-out pairing forward: one commit per verifier finding, + regression test + fail-first quote + fix together (see `3f35c65`, `1e9d845`, + `544d308`). + +## Artifacts to Preserve +- [04-findings_dump_only_signature_v0.md](04-findings_dump_only_signature_v0.md) — + the four listing digests the dump-only invariant is signed against. +- [01-findings_harness_probe_v0.md](01-findings_harness_probe_v0.md) — fleet + adjudication and the terminal `## Decision` scoping the next campaign. +- [probe_data/harness/matrix.md](probe_data/harness/matrix.md) and the raw gap + records — the honest-`—` matrix and its named gaps. +- The F1–F4 reproducers, now pinned as regression tests in + [test_paths_resolution.py](../../server/tests/test_paths_resolution.py): + `test_named_remedy_is_itself_a_working_escape`, + `test_pathless_file_uri_root_never_scopes_the_filesystem`, + `test_classify_needs_usable_items_for_declared`, + `test_concurrent_first_calls_both_reassure_before_settling`. +- The roots reassurance state machine (`paths.py`: `_roots_settled`, + `_FIRST_EMPTY_WAITERS`) — a subtle concurrency contract: the budget belongs + to the unsettled state, and outcomes must never be decided from a stale + provisional empty. + +## Open Questions +- Name the `roots/list` successor (R02 Station 1 opener) — rung 2 stays + at-best-static until then (carried from the findings Steering Questions). +- Re-probe the fleet from authenticated sessions: is any fleet harness + actually stamping `_meta` or answering `roots/list` per call? +- Should the reassurance wait bound (0.1 s) be configurable, and is 0.1 s the + right steady-state cost when a first call and a slow harness coincide? +- The campaign branch's `gh pr` landing is pending; CI's Windows leg is the + first to run this ladder's path-handling (`url2pathname` roots, F2 guard) — + read its verdict before cutting a release. diff --git a/__reports__/workspace_discovery/README.md b/__reports__/workspace_discovery/README.md new file mode 100644 index 0000000..6ecac46 --- /dev/null +++ b/__reports__/workspace_discovery/README.md @@ -0,0 +1,18 @@ +# workspace_discovery — reports + +Reports for the dynamic-workspace-discovery campaign (probe: which per-call +workspace signals each harness delivers, and what the resolution ladder may +trust). Listed by batch round; latest version of each document marked. + +| Round | Documents | Status | +|:------|:----------|:-------| +| 00 | [00-architecture_v0.md](00-architecture_v0.md) — resolution ladder, probe dump schema, harness measurement matrix, fail+guidance error model | **latest** | +| 01 | [01-findings_protocol_survey_v0.md](01-findings_protocol_survey_v0.md) (R02, from the protocol_survey leaf, authored by lead per AMS precedent) | **latest** | +| 01 | `01-findings_harness_probe_v0.md` (R03, from the synthesis leaf) | planned | +| 02 | [02-findings_probe_verifier_v0.md](02-findings_probe_verifier_v0.md) — adversarial verifier signed UNSOUND verdict on probe instrumentation (levers + proofs) | **latest** | +| 02 | [02-gap_analysis_calibrated_probe_v0.md](02-gap_analysis_calibrated_probe_v0.md) — amendment gap analysis: probe truth-source gap and proposed `probe_hardening` remedy | **latest** | +| 03 | [03-findings_amendment_review_v0.md](03-findings_amendment_review_v0.md) — formal amendment review verdict (APPROVE, high confidence), persisted for the A1 source column | **latest** | +| 03 | [03-findings_live_probe_v0.md](03-findings_live_probe_v0.md) — live wire probe: both per-call channels measured working, first-call roots race, host rows (Copilot silent; Claude/Codex auth-gated) | **latest** | +| 03 | probe_data/harness/raw/ — ledgers (live_lab-a/b jsonl) + wire transcripts (2026-07-28 / 2025-11-25) | **latest** | + +Status: batches 00-03 closed. The analysis deliverable is complete: resolution ladder + probe schema (R00), channel verdicts (R02, Station-1 half-superseded by R03), UNSOUND probe verdict + gap analysis (R02'), amendment APPROVE (R03a), and the live wire probe (R03b) answering the campaign question YES — per-call dynamic resolution works on the wire via request `_meta` vendor keys and per-call roots; host rows measure Copilot silent (the original bug), Claude/Codex gated on transport auth (runs ready). Open for the next cycle: probe_hardening (approved remedy) -> host census replay -> the serving-side resolver fix (roots await/cache race, `_meta` consume, fail+guidance). diff --git a/__reports__/workspace_discovery/probe_data/.gitignore b/__reports__/workspace_discovery/probe_data/.gitignore new file mode 100644 index 0000000..e3ff616 --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/.gitignore @@ -0,0 +1,9 @@ +* +!.gitignore +!harness/ +harness/* +!harness/matrix.md +!harness/raw/ +harness/raw/* +!harness/raw/claude_tool-*.jsonl +!harness/raw/codex_tool-*.jsonl diff --git a/__reports__/workspace_discovery/probe_data/harness/matrix.md b/__reports__/workspace_discovery/probe_data/harness/matrix.md new file mode 100644 index 0000000..2474f1a --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/matrix.md @@ -0,0 +1,13 @@ +# Harness × workspace-signal measurement matrix + +Columns are R01's fixed set (§Per-harness measurement matrix): `initialize +capabilities`, `request _meta keys`, `roots/list verdict`, `successor +(2026-07-28)`, `spawn env relevant vars`, plus `Channel Map` (R02 station ids) +and `Notes`. Every cell is measured from a raw JSONL probe record or `—` +(silence). No cell is rounded, inferred, or synthesized. + +| harness | initialize capabilities | request `_meta` keys | `roots/list` verdict | successor (2026-07-28) | spawn env relevant vars | Channel Map | Notes | +|---|---|---|---|---|---|---|---| +| `claude` | — | — | — | — | — | Station 3 (initialize); Station 2 (request `_meta`); Station 1 (`roots/list` + successor); env (launch pin) | gap record `claude_tool-20261127_141546.jsonl`: `{"error": "claude completed but no probe record written"}` — no R01-schema fields emitted, so no measured cells | +| `codex` | — | — | — | — | — | Station 3 (initialize); Station 2 (request `_meta`); Station 1 (`roots/list` + successor); env (launch pin) | gap record `codex_tool-20261127_141606.jsonl`: `{"error": "codex completed but no probe record written"}` — no R01-schema fields emitted, so no measured cells | +| `copilot-agent-plugins` | — | — | — | — | — | Station 3 (initialize); Station 2 (request `_meta`); Station 1 (`roots/list` + successor); env (launch pin) | no `copilot_tool-*.jsonl` present in raw store; reuse-by-filename-match absent, row recorded as `—` | diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/claude_tool-20261127_141546.jsonl b/__reports__/workspace_discovery/probe_data/harness/raw/claude_tool-20261127_141546.jsonl new file mode 100644 index 0000000..67f09ee --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/claude_tool-20261127_141546.jsonl @@ -0,0 +1 @@ +{"error": "claude completed but no probe record written"} diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/codex_tool-20261127_141606.jsonl b/__reports__/workspace_discovery/probe_data/harness/raw/codex_tool-20261127_141606.jsonl new file mode 100644 index 0000000..17db194 --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/codex_tool-20261127_141606.jsonl @@ -0,0 +1 @@ +{"error": "codex completed but no probe record written"} diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-a_tool-search.jsonl b/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-a_tool-search.jsonl new file mode 100644 index 0000000..acbdf7b --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-a_tool-search.jsonl @@ -0,0 +1,3 @@ +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": {"com.example.note": "stamp-v1", "com.example.workspace": "/tmp/probe-live/fakews"}, "resolved": {"root": "/private/tmp/probe-live/server", "source": "cwd"}, "roots_list": {"items": [], "static": "empty"}, "server_pid": 1067, "tool": "record", "ts": "2026-11-13T02:36:15.494808+00:00"} +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": {"com.example.note": "stamp-v1", "com.example.workspace": "/tmp/probe-live/fakews"}, "resolved": {"root": "/private/tmp/probe-live/fakews", "source": "roots"}, "roots_list": {"items": ["/tmp/probe-live/fakews"], "static": "declared"}, "server_pid": 1106, "tool": "record", "ts": "2026-11-13T02:36:23.978111+00:00"} +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": null, "resolved": {"root": "/private/tmp/probe-live/fakews", "source": "roots"}, "roots_list": {"items": ["/tmp/probe-live/fakews"], "static": "declared"}, "server_pid": 1106, "tool": "record", "ts": "2026-11-13T02:36:23.982244+00:00"} diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-b_tool-search.jsonl b/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-b_tool-search.jsonl new file mode 100644 index 0000000..c763877 --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/live_lab-b_tool-search.jsonl @@ -0,0 +1,3 @@ +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": {"com.example.note": "stamp-v1", "com.example.workspace": "/tmp/probe-live/fakews"}, "resolved": {"root": "/private/tmp/probe-live/server", "source": "cwd"}, "roots_list": {"items": [], "static": "empty"}, "server_pid": 1072, "tool": "record", "ts": "2026-11-13T02:36:16.578618+00:00"} +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": {"com.example.note": "stamp-v1", "com.example.workspace": "/tmp/probe-live/fakews"}, "resolved": {"root": "/private/tmp/probe-live/fakews", "source": "roots"}, "roots_list": {"items": ["/tmp/probe-live/fakews"], "static": "declared"}, "server_pid": 1116, "tool": "record", "ts": "2026-11-13T02:36:49.623317+00:00"} +{"cwd": "/private/tmp/probe-live/server", "env": {"COLGREP_MCP_BINARY": null, "COLGREP_MCP_ROOT": null, "spawn_env_digest": null}, "init_capabilities": null, "raw_paths": null, "request_meta": null, "resolved": {"root": "/private/tmp/probe-live/fakews", "source": "roots"}, "roots_list": {"items": ["/tmp/probe-live/fakews"], "static": "declared"}, "server_pid": 1116, "tool": "record", "ts": "2026-11-13T02:36:49.627421+00:00"} diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/wire-2025-11-25.log b/__reports__/workspace_discovery/probe_data/harness/raw/wire-2025-11-25.log new file mode 100644 index 0000000..31563ee --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/wire-2025-11-25.log @@ -0,0 +1,8 @@ +[RECV] {"id": 1, "jsonrpc": "2.0", "result": {"capabilities": {"completions": {}, "experimental": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false}}, "instructions": "colgrep gives ranked semantic + keyword (hybrid) search over code units (functions, classes, docs sections). Use `search` for any question about what, where or how code does something instead of shell grep; add `pattern` (a regex) to narrow hybrid results when you know an identifier. Omit `limit` for an exhaustive listing; use 10-25 while exploring. Results carry `hit_id`s: call `expand` to read the source of the few hits that matter instead of opening whole files. On a large, never-indexed repository call `index_build` first; `index_status` tells you whether that is needed.", "protocolVersion": "2025-11-25", "serverInfo": {"name": "colgrep", "version": "0.6.0"}}} +[RECV] {"id": 1, "jsonrpc": "2.0", "method": "roots/list", "params": {"_meta": {}}} +[SENT] {"for": 1, "kind": "roots-answer"} +[RECV] {"id": 2, "jsonrpc": "2.0", "method": "roots/list", "params": {"_meta": {}}} +[SENT] {"for": 2, "kind": "roots-answer"} +[RECV] {"id": 2, "jsonrpc": "2.0", "result": {"content": [{"text": "Error executing tool search: [COLGREP_FAILED] colgrep output could not be parsed: colgrep search stdout was valid JSON but not a list Next: Read the stderr tail; run `doctor`; retry with simpler arguments.", "type": "text"}], "isError": true}} +[RECV] {"id": 3, "jsonrpc": "2.0", "result": {"content": [{"text": "Error executing tool search: [COLGREP_FAILED] colgrep output could not be parsed: colgrep search stdout was valid JSON but not a list Next: Read the stderr tail; run `doctor`; retry with simpler arguments.", "type": "text"}], "isError": true}} +[WMETA] {"sent_by_server": [1, 2]} \ No newline at end of file diff --git a/__reports__/workspace_discovery/probe_data/harness/raw/wire-2026-07-28.log b/__reports__/workspace_discovery/probe_data/harness/raw/wire-2026-07-28.log new file mode 100644 index 0000000..31563ee --- /dev/null +++ b/__reports__/workspace_discovery/probe_data/harness/raw/wire-2026-07-28.log @@ -0,0 +1,8 @@ +[RECV] {"id": 1, "jsonrpc": "2.0", "result": {"capabilities": {"completions": {}, "experimental": {}, "prompts": {"listChanged": false}, "resources": {"listChanged": false, "subscribe": false}, "tools": {"listChanged": false}}, "instructions": "colgrep gives ranked semantic + keyword (hybrid) search over code units (functions, classes, docs sections). Use `search` for any question about what, where or how code does something instead of shell grep; add `pattern` (a regex) to narrow hybrid results when you know an identifier. Omit `limit` for an exhaustive listing; use 10-25 while exploring. Results carry `hit_id`s: call `expand` to read the source of the few hits that matter instead of opening whole files. On a large, never-indexed repository call `index_build` first; `index_status` tells you whether that is needed.", "protocolVersion": "2025-11-25", "serverInfo": {"name": "colgrep", "version": "0.6.0"}}} +[RECV] {"id": 1, "jsonrpc": "2.0", "method": "roots/list", "params": {"_meta": {}}} +[SENT] {"for": 1, "kind": "roots-answer"} +[RECV] {"id": 2, "jsonrpc": "2.0", "method": "roots/list", "params": {"_meta": {}}} +[SENT] {"for": 2, "kind": "roots-answer"} +[RECV] {"id": 2, "jsonrpc": "2.0", "result": {"content": [{"text": "Error executing tool search: [COLGREP_FAILED] colgrep output could not be parsed: colgrep search stdout was valid JSON but not a list Next: Read the stderr tail; run `doctor`; retry with simpler arguments.", "type": "text"}], "isError": true}} +[RECV] {"id": 3, "jsonrpc": "2.0", "result": {"content": [{"text": "Error executing tool search: [COLGREP_FAILED] colgrep output could not be parsed: colgrep search stdout was valid JSON but not a list Next: Read the stderr tail; run `doctor`; retry with simpler arguments.", "type": "text"}], "isError": true}} +[WMETA] {"sent_by_server": [1, 2]} \ No newline at end of file diff --git a/__roadmap__/workspace_discovery/README.md b/__roadmap__/workspace_discovery/README.md new file mode 100644 index 0000000..72ebb86 --- /dev/null +++ b/__roadmap__/workspace_discovery/README.md @@ -0,0 +1,64 @@ +# workspace_discovery + +## Context +Level-lead campaign rooted at this repository: a tool call with no `paths` resolves its default root to the server process cwd (the plugin install tree) when `COLGREP_MCP_ROOT` is unset and the client sends no roots — silently searching the wrong project. R03b's live wire probe measured both dynamic channels working per call; the sponsor fold of 2026-11-13 fixes the solution shape — the ladder `paths > dynamic (request _meta vendor keys + per-call client roots) > COLGREP_MCP_ROOT > fail+guidance naming an absolute paths entry` — implemented by `probe_hardening` then `resolution/per_call_resolution`. + +## Reference Documents +- [R01 Architecture Analysis (v0)](../../__reports__/workspace_discovery/00-architecture_v0.md) — resolution ladder, probe dump schema, harness measurement matrix, fail+guidance error model +- [R02 Protocol survey (v0)](../../__reports__/workspace_discovery/01-findings_protocol_survey_v0.md) — per-call workspace channels on the MCP wire; written by the protocol_survey leaf + +## Goal +Land the sponsor-folded per-call resolution ladder through two visits: `probe_hardening` (truth-source probe + calibration oracle) then `resolution/per_call_resolution` (meta/roots consumption, `COLGREP_MCP_ROOT` pin rung, fail+guidance). + +## Pre-conditions +- [x] Environment contract measured 2026-11-12: `cd server && uv run pytest -q` resolves imports to this worktree and exits 0; `command -v claude codex` both resolve +- [x] Specs committed before dispatch (KT-B): this README, R01, and all leaf files are committed to the campaign branch before any worktree is cut +- [ ] Probe artifacts for `claude` and `codex` exist under `__reports__/workspace_discovery/probe_data/harness/` before the synthesis level runs (evidence gaps recorded as `—`, never filled) + +## Success Gates +- ✅ `cd server && uv run pytest -q` exits 0 on the campaign branch with probe code in tree; probe inert: `Client.list_tools()`/`list_resources()`/`list_prompts()` dumps equal base and resolved paths bit-identical when `COLGREP_MCP_PROBE` is unset +- ✅ `__reports__/workspace_discovery/probe_data/harness/matrix.md` exists with every dynamic-signal cell a measured value or `—` +- ✅ `__reports__/workspace_discovery/01-findings_protocol_survey_v0.md` and `__reports__/workspace_discovery/01-findings_harness_probe_v0.md` exist, each opening with `type: findings` front matter and a Headline Result block +- ✅ `__reports__/workspace_discovery/02-architecture_v1.md` carries the adjudicated rung order and, for every `—` cell, the per-harness fail+guidance fallback contract (or an explicit Goal-restatement pivot) + +## Gotchas +- Worktrees see only committed files (KT-B): commit this README, R01 and the leaf files before any dispatch. `probe_data/` is runtime-created; git tracks no empty directories, so a check must treat its absence as "not yet collected". +- File-disjoint ownership: `probe_instrumentation` owns `server/colgrep_mcp/probe.py`, `server/colgrep_mcp/paths.py`, `server/tests/test_probe.py`, `server/tests/e2e/probe_workspace.py`; `collect_harness_evidence` owns `__reports__/workspace_discovery/probe_data/**`; `protocol_survey` and `findings_report` own only the report files named in their Deliverables. The driver is owned by `probe_instrumentation` (mechanism) and merely *invoked* by `collect_harness_evidence` (operation) — evidence worktrees get it from the campaign branch after level-1 merges. +- The probe never runs real `colgrep` search against this repository (stack-traps): harness runs trigger `doctor` only — read-only, no index writes. Probe artifacts live under `probe_data/` and are committed as evidence (batch-01 reports cite their paths); the only string sent to any harness API is the canned `TRIGGER_PROMPT` constant. +- Consistency Checks that grep a Deliverable file are deliverable-dependent and exempt at authoring time (they run when the leaf executes); the baseline gates above were measured instead. Nothing may follow `(expected: PASS)` on a check line. +- Hard stop for the dispatch window: 21:30 JST 2026-11-12. Whatever is green at the stop gets merged; whatever is not, reports as unfinished. +- **Outstanding integration debt (2026-11-13, `ca3cb40`)**: the pledged adversarial verification of `probe_instrumentation` never produced a verdict — both dispatch rounds died with zero output to session suspension. That merge integrated on the implementer's branch plus the lead's own post-rebase re-verification only; the dump-only signature is NOT in hand and remains the pre-condition for any `evidence/` dispatch, at an escalated tier (campaign-lead: escalate the leaf, not the round). The `protocol_survey` leaf lost two dispatch rounds the same way and re-opens as a narrowed research question first (2026-07-28 revision / `roots/list` successor / `_meta` stamping), report assembled after. +- Adversarial verification is pledged for `probe_instrumentation` (measurement semantics + silent-failure risk): a verifier signs the dump-only invariant before level-2 leaves run. + +## Status +```mermaid +graph TD + probe_instrumentation[Probe instrumentation for workspace signals]:::done + protocol_survey[Workspace-channel protocol survey]:::done + evidence[Harness evidence collection]:::planned + probe_hardening[Harden probe: truth-source, never-raise, calibration oracle]:::amendment + resolution[Resolution ladder (solution)]:::planned + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `probe_instrumentation.md` | 📄 Leaf Task | ✅ Done | +| `protocol_survey.md` | 📄 Leaf Task | ✅ Done | +| `evidence/` | 📁 Directory | ⬜ Planned | +| `probe_hardening.md` | 📄 Leaf Task | 🔵 Amendment | +| `resolution/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:---|:---|:---|:---| +| A1 | 2026-11-13 | 02-gap_analysis_calibrated_probe_v0.md + 03-findings_live_probe_v0.md | ["probe_hardening", "resolution/per_call_resolution"] | UNSOUND probe remedy + sponsor fold: per-call `_meta`/roots discovery lands as the solution's dynamic rungs | + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/workspace_discovery/evidence/README.md b/__roadmap__/workspace_discovery/evidence/README.md new file mode 100644 index 0000000..8c8d51e --- /dev/null +++ b/__roadmap__/workspace_discovery/evidence/README.md @@ -0,0 +1,42 @@ +# Harness evidence collection + +## Context +Level 2 of `workspace_discovery`: run the probe driver against the reachable harnesses (`claude`, `codex`) and record raw JSONL evidence plus the consolidated signal matrix. Consumes the instrumentation merged from `probe_instrumentation` and R02's channel ids; produces `probe_data/harness/` artifacts for `synthesis/` to adjudicate. + +## Goal +Every harness × signal cell carries a measured value or a recorded gap `—`; no cell is synthesized. + +## Pre-conditions +- [ ] `probe_instrumentation` merged to the campaign branch (`git cat-file -e :server/tests/e2e/probe_workspace.py` exits 0) +- [ ] `__reports__/workspace_discovery/01-findings_protocol_survey_v0.md` exists on the campaign branch +- [ ] Hard stop honoured (campaign README §Gotchas): stop at the window close, commit green work + +## Success Gates +- ✅ `__reports__/workspace_discovery/probe_data/harness/raw/` holds one artifact (raw JSONL or `{"error": ...}` gap record) per harness named in the leaf +- ✅ `matrix.md` exists with exactly one cell per R01 matrix column per harness row; every absent value is `—` with the gap record named in `Notes` + +## Status +```mermaid +graph TD + collect_harness_evidence[Collect harness probe artifacts]:::planned + synthesis[Findings synthesis]:::planned + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `collect_harness_evidence.md` | 📄 Leaf Task | ⬜ Planned | +| `synthesis/` | 📁 Directory | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/workspace_discovery/evidence/collect_harness_evidence.md b/__roadmap__/workspace_discovery/evidence/collect_harness_evidence.md new file mode 100644 index 0000000..ebebd3c --- /dev/null +++ b/__roadmap__/workspace_discovery/evidence/collect_harness_evidence.md @@ -0,0 +1,35 @@ +# Collect harness probe artifacts + +**Goal**: Run the probe driver under each reachable harness and record raw JSONL evidence per harness plus the consolidated signal matrix — measured values or `—`, never synthesized. +**Pre-conditions**: +- [ ] `probe_instrumentation` merged to the campaign branch: `git cat-file -e :server/tests/e2e/probe_workspace.py` exits 0 in this worktree +- [ ] R02 (`01-findings_protocol_survey_v0.md`) exists on the campaign branch so the matrix's `Channel Map` column can cite its station ids +- [ ] Hard stop honoured: campaign README §Gotchas names the dispatch window close; stop there and commit whatever is green +**Success Gates**: +- ✅ `__reports__/workspace_discovery/probe_data/harness/raw/` contains one `claude_tool-*.jsonl` and one `codex_tool-*.jsonl` *or* a gap record naming the harness and the failure mode (`{"error": ...}` — unstubbed result is a named gap, not an invented value) +- ✅ `test -s __reports__/workspace_discovery/probe_data/harness/matrix.md` and every harness row has exactly one cell per matrix column (value or `—`) +**References**: [R01 §Per-harness measurement matrix](../../../__reports__/workspace_discovery/00-architecture_v0.md) — the column set this leaf must not alter; [L1 R01 §Probe dump schema](../../../__reports__/workspace_discovery/00-architecture_v0.md) — what each raw JSONL line must contain + +## Step 1: Claude harness run +**Goal**: Capture `claude -p` probe evidence into the raw store. +**Implementation Logic**: +Invoke the driver from the campaign branch (tool-owned: the leaf only orchestrates) as `COLGREP_MCP_PROBE= uv run python server/tests/e2e/probe_workspace.py --harness claude --out __reports__/workspace_discovery/probe_data/harness/raw/claude_tool-$(date +%Y%m%d_%H%M%S).jsonl`. The driver stubs `colgrep` on `$PATH` and calls `doctor` only — no real search, no index writes (stack-traps). A run that times out, fails to spawn, or leaves no ledger yields a gap record at the same path (`{"error": ": "}`); do not retry more than 2 attempts, do not hand-edit any raw artifact. If the run succeeds, copy the JSONL verbatim (schema keys already validated by the driver). +**Deliverables**: `__reports__/workspace_discovery/probe_data/harness/raw/claude_tool-*.jsonl` (verbatim driver output or `{"error": ...}` gap record) +**Consistency Checks**: `ls __reports__/workspace_discovery/probe_data/harness/raw/claude_tool-*.jsonl` (expected: PASS) +**Commit**: `chore(repo): record claude harness probe artifacts` + +## Step 2: Codex harness run +**Goal**: Capture `codex exec` probe evidence into the raw store. +**Implementation Logic**: +As step 1 with `--harness codex` and raw name `codex_tool-*.jsonl`: `codex exec` non-interactively, same stubbed `PATH`, same `doctor`-only trigger, same 2-attempt limit and gap-record discipline. `codex`'s terminal escaping may flatten output — the raw artifact keeps what it printed; flattening is reported in the matrix `Notes` column in step 3, never guessed behind. +**Deliverables**: `__reports__/workspace_discovery/probe_data/harness/raw/codex_tool-*.jsonl` (verbatim driver output or `{"error": ...}` gap record) +**Consistency Checks**: `ls __reports__/workspace_discovery/probe_data/harness/raw/codex_tool-*.jsonl` (expected: PASS) +**Commit**: `chore(repo): record codex harness probe artifacts` + +## Step 3: Consolidated signal matrix +**Goal**: Publish the harness × signal matrix with every cell measured or `—`. +**Implementation Logic**: +Write `__reports__/workspace_discovery/probe_data/harness/matrix.md`: one row per harness (`claude`, `codex`, `copilot-agent-plugins`), columns exactly R01's: `initialize capabilities | request _meta keys | roots/list verdict | successor (2026-07-28) | spawn env relevant vars`. Cells are filled only from the corresponding raw JSONL fields (probe dump schema keys) crossed with R02's station ids in a final `Channel Map` column; absent evidence writes `—` plus the gap record name in `Notes`. The `copilot-agent-plugins` row may be filled from raw JSONL a previous collection dropped in the same raw dir (reuse by filename match `copilot_tool-*.jsonl`), else `—`. No cell is inferred, rounded, or synthesized (competition rule: silence loses to signal, and `—` is the recorded silence). +**Deliverables**: `__reports__/workspace_discovery/probe_data/harness/matrix.md` (rows per harness; columns `initialize capabilities`, `request _meta keys`, `roots/list verdict`, `successor (2026-07-28)`, `spawn env relevant vars`, `Channel Map`, `Notes`) +**Consistency Checks**: `grep -c '^| ' __reports__/workspace_discovery/probe_data/harness/matrix.md` (expected: PASS) +**Commit**: `docs(reports): consolidate harness probe matrix` diff --git a/__roadmap__/workspace_discovery/evidence/synthesis/README.md b/__roadmap__/workspace_discovery/evidence/synthesis/README.md new file mode 100644 index 0000000..2770faa --- /dev/null +++ b/__roadmap__/workspace_discovery/evidence/synthesis/README.md @@ -0,0 +1,39 @@ +# Findings synthesis + +## Context +Level 3 of `workspace_discovery`, the terminal level: adjudicate the resolution ladder from what the fleet actually delivered. Consumes `probe_data/harness/matrix.md`, the raw JSONL artifacts, R01's rung ids and R02's verdicts; produces the batch-01 findings report whose `Decision` defines the next campaign's scope. + +## Goal +One findings report where each harness gets a `Resolution Picks` rung string-matching R01, dead cells stay `—`, and every `—` carries the fail+guidance fallback (error naming `paths` with an absolute directory). + +## Pre-conditions +- [ ] All level-1 and level-2 leaves `done` per `dirtree-rdm ls` (not memory) +- [ ] Matrix and raw artifacts present under `probe_data/harness/` + +## Success Gates +- ✅ `01-findings_harness_probe_v0.md` exists with valid findings front matter and a `## Headline Result` block +- ✅ `Resolution Picks` per harness matches an R01 rung id; every matrix `—` reappears as `—` in the report + +## Status +```mermaid +graph TD + findings_report[Findings report from the probe fleet]:::planned + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `findings_report.md` | 📄 Leaf Task | ⬜ Planned | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/workspace_discovery/evidence/synthesis/findings_report.md b/__roadmap__/workspace_discovery/evidence/synthesis/findings_report.md new file mode 100644 index 0000000..642fc85 --- /dev/null +++ b/__roadmap__/workspace_discovery/evidence/synthesis/findings_report.md @@ -0,0 +1,18 @@ +# Findings report from the probe fleet + +**Goal**: Publish the harness-probe findings report that turns the measured matrix + R02 into the adjudicated resolution-ladder decision for the next implementation campaign. +**Pre-conditions**: +- [ ] All level-1 and level-2 leaves `done` on the campaign branch (check `dirtree-rdm ls`, not memory): probe instrumentation merged with its verifier sign-off, R02 committed, matrix + raw artifacts present +**Success Gates**: +- ✅ `test -s __reports__/workspace_discovery/01-findings_harness_probe_v0.md`, front matter parses (`type: findings`, `topic: workspace_discovery`, `version: v0`, `prior-version: none`, `key-metric` named, `decision-required` non-empty), and a `## Headline Result` block follows +- ✅ The report's `Resolution Picks` column names one ladder rung per harness, each string-matching a rung id from R01 (dynamic / pin / guarded-cwd / fail+guidance) +- ✅ Every `—` in the matrix is propagated as `—` into the report (no gap is closed in prose) +**References**: [R01 §Proposed State / resolution ladder](../../../../__reports__/workspace_discovery/00-architecture_v0.md) — rung ids the picks must match; [R02](../../../../__reports__/workspace_discovery/01-findings_protocol_survey_v0.md) — channel verdicts the interpretation column cites + +## Step 1: Author the harness-probe findings +**Goal**: Write `01-findings_harness_probe_v0.md`; evidence determines every conclusion, dead cells stay dead. +**Implementation Logic**: +Follow `writing-reports` §findings precisely: front matter block first (`key-metric: dynamic_channels_work:` counts harnesses with a live dynamic rung), Headline Result key/value block (`metric/value/unit/prior/direction`), Results Tables (≤20 rows; `harness|run|init_caps|_meta keys|roots verdict|successor|spawn env|Resolution Picks|Notes` condensed from the matrix), Observations four-column table (`Signal|Baseline/Expected|Observed [source: probe_data/harness/raw/]|Interpretation`) whose Baseline column is the R01-predicted ladder — a cell where reality contradicts R01 belongs in `Contradictions & Surprises`, not smoothed over. Add one Mermaid pie or flowchart visual only if slice counts differ (>0 dynamic vs gaps) and carry captions with units where quantitative. `Decision` statement at the end (matching the front-matter `decision-required`): per-call resolution ship scope — which rungs the next campaign wires into `paths.resolve_target_paths`, and the fail+guidance contract for harnesses where all dynamic rungs are `—` (error names `paths` with an absolute directory as the remedy — the pivot the sponsor specified over bare loud-failure). ≤5 Steering Questions tagged `[now]`/`[next run]`/`[later]`; Pointers = links only (matrix, raw JSONL files, R02, R01) even though their filenames embed timestamps. Restate no raw JSON; the tables are the evidence layer, the bars end every claim. +**Deliverables**: `__reports__/workspace_discovery/01-findings_harness_probe_v0.md` (front matter fields `type/topic/date/version/prior-version/key-metric/decision-required`; `## Headline Result`; Results Tables; Observations; optional `## Contradictions & Surprises`; `## Steering Questions`; `## Pointers`; terminal `## Decision` statement with per-harness `Resolution Picks`) +**Consistency Checks**: `grep -q '^type: findings' __reports__/workspace_discovery/01-findings_harness_probe_v0.md && grep -q '^## Headline Result' __reports__/workspace_discovery/01-findings_harness_probe_v0.md` (expected: PASS) +**Commit**: `docs(reports): adjudicate workspace-resolution rungs from probe fleet` diff --git a/__roadmap__/workspace_discovery/probe_hardening.md b/__roadmap__/workspace_discovery/probe_hardening.md new file mode 100644 index 0000000..36222c5 --- /dev/null +++ b/__roadmap__/workspace_discovery/probe_hardening.md @@ -0,0 +1,43 @@ +# Harden probe: truth-source, never-raise, calibration oracle + +**Goal**: Make the workspace-signal probe trustworthy by construction: truth-sourced record columns, a total never-raise boundary, and a calibration oracle that fails when the probe lies. +**Pre-conditions**: +- [x] Gap analysis + UNSOUND verdict + APPROVE review landed (02-gap_analysis_calibrated_probe_v0.md, 02-findings_probe_verifier_v0.md, 03-findings_amendment_review_v0.md) +- [ ] Branch cut from the campaign branch with the reports visible (worktrees see only committed files) +**Success Gates**: +- ✅ `cd server && uv run pytest -q` green; `test_no_probe_side_effects` fails against the shipped faulty state (commit body names how) and passes here +- ✅ A sabotaged probe (records fabricated `init_capabilities`) fails the calibration oracle test: `diff_record` must whistle on a stub-authored record verbatim +- ✅ `record()` is demonstrably total: no input (`ctx=None`, non-serializable snapshot values, unwritable probe dir) raises past the resolve call site +**References**: [R02' §Evidence](../../__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md) — the four defect lines each step repairs; [R02 §Lever table](../../__reports__/workspace_discovery/02-findings_probe_verifier_v0.md) — exploit chains the fixes must retire + +## Step 1: Truth-source the record columns +**Goal**: Every ledger column reflects what was measured, never what the probe can guess. +**Implementation Logic**: +Re-land `server/colgrep_mcp/probe.py` with the revert-backed facility but two repairs. (1) `tool` attribution: accept the tool name explicitly at the hook site in `paths.resolve_target_paths` (or scan frames skipping module-internal names) — the record must name the actual tool, not `"record"`. (2) `roots_list`: three values `declared` / `empty` / `error` — `error` when the round-trip raised or the back-channel is absent, `empty` only when a client actually answered with zero roots. Both columns verified against the verifier's lever-1/6 chains. +**Deliverables**: `server/colgrep_mcp/probe.py` (exports `capture_pure`, `record`, `PROBE_ENV`, `FORGED_SAMPLE`); `server/colgrep_mcp/paths.py` (hook passes `tool` and the distinct roots outcome); `server/tests/test_probe.py` (`test_tool_column_names_the_actual_tool`, `test_roots_error_distinct_from_empty`) +**Consistency Checks**: `grep -q 'probe_hardening' __reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md` (expected: PASS) +**Commit**: `fix(server): make probe record columns reflect measured truth` + +## Step 2: Make record() total — no raise escapes to the resolve path +**Goal**: The never-raise law becomes a property, not a docstring claim. +**Implementation Logic**: +Wrap the whole body after the env sentinel in one `try/except Exception` (OSError **and** TypeError from `capture_pure` serialization of hostile values), `safe_log` on failure. Regression: a snapshot value that is not JSON-serializable must produce either a coerced record or a swallowed failure — the `tools/call` must succeed either way (this is lever 2b's kill). Prefer coercion in `capture_pure` (`default=str`) over silent loss so the record remains a witness. +**Deliverables**: `server/colgrep_mcp/probe.py` (total `record`, coerced `capture_pure`); `server/tests/test_probe.py` (`test_record_never_raises_on_hostile_snapshot`, `test_tool_call_survives_probe_rename`) +**Consistency Checks**: `cd server && uv run pytest tests/test_probe.py -q` (expected: PASS) +**Commit**: `fix(server): make the probe record path survive hostile snapshots` + +## Step 3: Calibration oracle — forge_record / diff_record +**Goal**: Ship the witness the gap analysis prescribes: the test harness can catch a probe that lies. +**Implementation Logic**: +In `probe.py`: `forge_record(**overrides) -> dict` builds a ground-truth record from an explicit snapshot (no frame reading, no env reading), and `diff_record(expected, actual) -> list[str]` returns the field-level disagreements. `test_probe.py` adds `test_calibration_whistles_on_fabrication`: feed a record with fabricated `init_capabilities` and assert `diff_record` is non-empty; feed the true record and assert empty. The old `test_no_probe_side_effects` is rewritten to read the actual ledger path (`colgrep_probe.jsonl`, not the dead filenames the old test asserted) and compare `capture_pure` round-trip against `forge_record` output. Record in the step-1/2 commit bodies that the OLD test never failed on the faulty state (it was blind) — the new ones must initially fail against the states in `02-findings_probe_verifier_v0.md` lever 3 to earn the name. +**Deliverables**: `server/colgrep_mcp/probe.py` (exports `forge_record`, `diff_record`); `server/tests/test_probe.py` (`test_calibration_whistles_on_fabrication`, `test_no_probe_side_effects` rewritten against the real ledger path) +**Consistency Checks**: `grep -q 'forge_record\|diff_record' __reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md` (expected: PASS) +**Commit**: `test(tests): add the probe calibration oracle and retire the blind ledger test` + +## Step 4: Driver provenance and gap-record tolerance +**Goal**: Stub-written rows are labelled as such, and the driver's own gap signalling stops crashing its validator. +**Implementation Logic**: +`server/tests/e2e/probe_workspace.py`: every stub-written record adds `"provenance": "stub"` (server-written rows carry `"provenance": "server"` or omit); `_validate_record` tolerates `{"error": ...}` gap rows (they parse to `gap_record` verdicts instead of KeyError-ing on `snap["ts"]`); the rotation writer keeps whole raw dirs in `__reports__/workspace_discovery/probe_data/`. A validator call with a gap row must return a named gap, never raise. +**Deliverables**: `server/tests/e2e/probe_workspace.py` (stub records stamped `provenance: "stub"`; gap-tolerant `validate`); `server/tests/test_probe.py` (`test_gap_records_validate_as_gaps`, `test_stub_records_carry_provenance`) +**Consistency Checks**: `cd server && uv run pytest tests/test_probe.py -q` (expected: PASS) +**Commit**: `fix(tests): stamp stub provenance and let gap rows round-trip the validator` diff --git a/__roadmap__/workspace_discovery/probe_instrumentation.md b/__roadmap__/workspace_discovery/probe_instrumentation.md new file mode 100644 index 0000000..4d490ef --- /dev/null +++ b/__roadmap__/workspace_discovery/probe_instrumentation.md @@ -0,0 +1,29 @@ +# Probe instrumentation for workspace signals + +**Goal**: Land an inert, dump-only probe facility and harness driver that record what dynamic workspace signals each harness actually delivers, changing no resolution behaviour. +**Pre-conditions**: +- [x] Campaign README, R01 and this leaf committed to the campaign branch (KT-B: worktrees see only committed files) +- [ ] Baseline green on this worktree: `cd server && uv run pytest -q` exits 0 before the first edit +**Success Gates**: +- ✅ `cd server && uv run pytest -q` exits 0 with `test_probe.py` in tree; `test_no_probe_side_effects` (the dump-only oracle) fails against the base commit this branch was cut from and passes here +- ✅ With `COLGREP_MCP_PROBE` unset, `capture_pure` round-trips byte-identical records and `resolve_target_paths` results equal the base behaviour in `test_capture_matches_runtime` +- ✅ `server/tests/e2e/probe_workspace.py` runs `doctor` against a packaged server and writes one JSONL record per tool call with the R01 §Probe dump schema keys +**References**: [R01 §Probe dump schema](../../__reports__/workspace_discovery/00-architecture_v0.md) — `init_capabilities`, `request_meta`, `roots_list`, `env` digest keys the driver must name + +## Step 1: Probe dump facility +**Goal**: Add the workspace-signal probe as an inert module hooked only behind `COLGREP_MCP_PROBE`. +**Implementation Logic**: +New `server/colgrep_mcp/probe.py`: `capture_pure(snap) -> str` serializes a snapshot dict to one JSONL line (sorted keys, no volatile fields); `record(tool, raw_paths, ctx)` builds `{ts, server_pid, tool, raw_paths, env: {COLGREP_MCP_ROOT, COLGREP_MCP_BINARY, spawn_env_digest}, init_capabilities, request_meta, roots_list, resolved, cwd}` and appends to `$COLGREP_MCP_PROBE/colgrep_probe.jsonl` inside `try/except OSError: pass` with `logging_utils.safe_log` on failure — the probe must never raise into the resolve path. Wire one call at the top of `paths.resolve_target_paths` gated on `os.environ.get("COLGREP_MCP_PROBE")`, reading `init_capabilities`/`request_meta` from `ctx.request_context` via `getattr` (SDK absent or fragment = recorded as `None`, never inferred). `roots_list` records the *outcome* of the existing `client_roots` call (declared/empty/error + items); sharing that call rather than adding a second one keeps resolution cost unchanged (maintainer-policy §hardware-first — no new round-trip per call). The resolve chain itself is not otherwise touched: this step is observable-behaviour inert by construction (maintainer-policy §Client-visible behaviour). +Pseudo-code for the hook point only: `if probe_enabled: record(...) # best effort` precedes the existing `settings = get_settings(ctx)` line. No change to `resolve_paths`/`default_root` precedence. +**Deliverables**: `server/colgrep_mcp/probe.py` (exports `capture_pure`, `record`, `PROBE_ENV`); `server/colgrep_mcp/paths.py` (one gated probe call in `resolve_target_paths`, otherwise unchanged); `server/tests/test_probe.py` (`test_capture_matches_runtime`, `test_probe_inert_without_env`, `test_no_probe_side_effects`) +**Consistency Checks**: `cd server && uv run pytest tests/test_probe.py -q` (expected: PASS) +**Commit**: `refactor(server): record workspace-signal probe behind COLGREP_MCP_PROBE` + +## Step 2: Harness probe driver and dump-only guard +**Goal**: Add the probe-driven harness evidence driver and the regression tests that pin probe inertness. +**Implementation Logic**: +New `server/tests/e2e/probe_workspace.py` (not collected by pytest): a driver that (1) launches the packaged server through a named harness `Claude|Codex` via `subprocess` (`claude -p` / `codex exec` non-interactively with the canned single-line trigger), with a minimal stub `$PATH` shadowing `colgrep` so no real index is touched (stack-traps); (2) the stub's `doctor` subcommand writes one R01-schema JSONL record per invocation to `$COLGREP_MCP_PROBE/colgrep_probe.jsonl` and prints the static `doctor` payload; (3) the driver copies the JSONL to a named raw file and validates records deterministically (schema keys present). Timeout, non-zero exit and missing-ledger cases append an explicit gap record (`{"error": ""}`) — raw evidence or a named gap, never a synthesized value. Newest 3 dated raw directories rotate out at 4 — bounded growth without destroying recent evidence. The trigger string is one constant `TRIGGER_PROMPT` ("Run the colgrep doctor tool now. Reply done.") so its shape is diffable. +`test_no_probe_side_effects` (regression test; failed against base in the first build attempt = the honest record required by maintainer-policy §Regression tests): with `COLGREP_MCP_PROBE` unset, a dump of `Client.list_tools()/list_resources()/list_prompts()` is unstaged-JSON-identical to the base dump produced by the same test, and `capture_pure` output is byte-identical across calls; with `COLGREP_MCP_PROBE` set and a temp dir, a resolved-path call writes exactly one record whose `resolved.source` equals the control run's `root_source`. `test_capture_matches_runtime` asserts the recorded `resolved` equals what `resolve_target_paths` returned on that call. +**Deliverables**: `server/tests/e2e/probe_workspace.py` (exports `main`, `collect_for(harness)`, `TRIGGER_PROMPT`); `server/tests/test_probe.py` (extended with `test_no_probe_side_effects`, `test_capture_matches_runtime`); `__reports__/workspace_discovery/probe_data/.gitignore` ("*\n!.gitignore\n") +**Consistency Checks**: `cd server && uv run pytest tests/test_probe.py -q` (expected: PASS) +**Commit**: `test(tests): pin probe inertness and add probe_workspace harness driver` diff --git a/__roadmap__/workspace_discovery/protocol_survey.md b/__roadmap__/workspace_discovery/protocol_survey.md new file mode 100644 index 0000000..7cb6163 --- /dev/null +++ b/__roadmap__/workspace_discovery/protocol_survey.md @@ -0,0 +1,19 @@ +# Workspace-channel protocol survey + +**Goal**: Publish the per-station workspace-channel verdicts — which dynamic per-call signals the MCP wire, as pinned in this environment, can actually carry — in the R02 findings report. +**Pre-conditions**: +- [ ] Campaign README and R01 committed on the campaign branch (this leaf reads only committed material plus the pinned `mcp` SDK source) +- [x] `cd server && uv run python -c "import mcp; print(mcp.__file__)"` resolves to this worktree's `.venv` (environment contract, 2026-11-12) +**Success Gates**: +- ✅ `test -s __reports__/workspace_discovery/01-findings_protocol_survey_v0.md` and its front matter parses to `type: findings`, `topic: workspace_discovery`, `version: v0`, `prior-version: none`, `decision-required: confirm` +- ✅ The verdict table's `duration` and `invoker_coverage` columns are non-empty for every row; every row's `evidence_for` cites an identifier (`mcp `) or `—` guarded by "dialect has no timestamp" +- ✅ No raw JSON schema dump, SDK source excerpt, or HTML appears in the report body (competition against the steering bullets wins every merge conflict) +**References**: [R01 §Contracts & Invariants](../../__reports__/workspace_discovery/00-architecture_v0.md) — probe dump schema the survey's channels must map onto + +## Step 1: Author the channel verdicts +**Goal**: Fill R02 — every candidate per-call workspace channel adjudicated as `dynamic`/`static`/`none`/`?` with citations and a minimal diagram. +**Implementation Logic**: +Write `__reports__/workspace_discovery/01-findings_protocol_survey_v0.md` following the `writing-reports` §findings contract exactly (front matter block first, then Headline Result key/value block, Results Tables, Observations four-column table, ≤5 Steering Questions, Pointers = links only). Survey stations: (1) client `roots` capability on the 2026-07-28 MCP revision — `roots/list` deprecation and whatever the pinned `mcp` SDK (version recorded from `uv pip show mcp`) exposes as its successor (`notification/roots/list_changed` status included); (2) request `_meta` presence on `tools/call` in the SDK's `Context.request_context` — what key, if any, a host can stamp per call; (3) `initialize` handshake context fields. Evidence policy: claims come from the installed SDK's own source (read-only, cite module + symbol), the MCP specification versions the SDK names, and the repo's own `R05 M1` note (AGENTS.md report-id table); raw corpus runs of other harnesses are expressly out of scope (that is `collect_harness_evidence`'s job — this leaf surveys mechanism, not behaviour). Where the wire cannot carry a channel at the pinned version, verdict is `static` or `none` and the `invoker` column names who must hold the value in that case (host spawn env / user pin / none — fail+guidance). One Mermaid diagram maps signals to the R01 resolution-ladder rungs. Facts (SDK version, spec section ids, symbol names) are cited in `evidence_for`; conclusion prose in its own column; `<` and `|` stripped from cells. +**Deliverables**: `__reports__/workspace_discovery/01-findings_protocol_survey_v0.md` (front matter fields `type/topic/date/version/prior-version/key-metric/decision-required`; `## Headline Result` with `metric: dynamic_channels_found`; one Mermaid signal-to-rung diagram; Results Tables `station|verdict|evidence_for|invoker|duration|invoker_coverage` and `channel|window|trigger|validation|notes`; Observations four-column table) +**Consistency Checks**: `grep -q '^type: findings' __reports__/workspace_discovery/01-findings_protocol_survey_v0.md && grep -q '^## Headline Result' __reports__/workspace_discovery/01-findings_protocol_survey_v0.md` (expected: PASS) +**Commit**: `docs(reports): survey per-call workspace channels on the MCP wire` diff --git a/__roadmap__/workspace_discovery/resolution/README.md b/__roadmap__/workspace_discovery/resolution/README.md new file mode 100644 index 0000000..d9efa3e --- /dev/null +++ b/__roadmap__/workspace_discovery/resolution/README.md @@ -0,0 +1,43 @@ +# Resolution ladder (solution) + +## Context +Depth-ordered after `probe_hardening` (calibration oracle first) and in parallel with the `evidence/` harness census — disjoint files (`paths.py` + resolution tests here, `probe.py` there). Executes the sponsor fold of 2026-11-13: the ladder `paths > dynamic (_meta + per-call roots) > COLGREP_MCP_ROOT > fail+guidance`, grounded in R03b's live wire measurements. + +## Goal +The default root resolves per call from what the harness actually sent, degrades through the `COLGREP_MCP_ROOT` pin, and fails with actionable guidance only when nothing mentions the workspace. + +## Pre-conditions +- [ ] `probe_hardening` reaches `done` (its calibration oracle backs these rungs' tests) +- [ ] R03b (`03-findings_live_probe_v0.md`) is merged and cited by both leaf steps + +## Success Gates +- ✅ Ladder tests pin each rung's precedence; the silence rung's error names the `paths` remedy verbatim +- ✅ Post-rebase `uv run pytest -q` green on the campaign branch after this level integrates + +## Gotchas +- The probe hook line in `paths.py` belongs to `probe_hardening`; this level owns resolution logic and its tests only — landing `probe_hardening` first (level order) keeps the writes from racing. +- The `ROOT_UNRESOLVED` guidance wording is client-visible contract: copy it from the leaf, never improvise. + +## Status +```mermaid +graph TD + per_call_resolution[Per-call workspace resolution ladder (meta, roots, pin, fail+guidance)]:::amendment + classDef done fill:#166534,color:#bbf7d0 + classDef inprogress fill:#854d0e,color:#fef08a + classDef planned fill:#374151,color:#e5e7eb + classDef amendment fill:#1e3a5f,color:#bfdbfe + classDef blocked fill:#7f1d1d,color:#fecaca +``` + +## Nodes +| Node | Type | Status | +|:-----|:-----|:-------| +| `per_call_resolution.md` | 📄 Leaf Task | 🔵 Amendment | + +## Amendment Log +| ID | Date | Source | Nodes Added | Rationale | +|:---|:-----|:-------|:------------|:----------| + +## Progress +| Node | Branch | Commits | Notes | +|:-----|:-------|:--------|:------| diff --git a/__roadmap__/workspace_discovery/resolution/per_call_resolution.md b/__roadmap__/workspace_discovery/resolution/per_call_resolution.md new file mode 100644 index 0000000..1044b71 --- /dev/null +++ b/__roadmap__/workspace_discovery/resolution/per_call_resolution.md @@ -0,0 +1,35 @@ +# Per-call workspace resolution ladder (meta, roots, pin, fail+guidance) + +**Goal**: Land the sponsor-folded resolution ladder in `paths.py`: per-call argument > per-call dynamic discovery (request `_meta` vendor keys and per-call client roots) > `COLGREP_MCP_ROOT` pin > fail with guidance naming an absolute `paths` entry. +**Pre-conditions**: +- [ ] `probe_hardening` is `done` (its truth-source probe and calibration oracle are what these rungs are measured against) +- [ ] R03b decided this ladder: [03-findings_live_probe_v0.md](../../__reports__/workspace_discovery/03-findings_live_probe_v0.md) — both dynamic channels measured working; the pin and fail+guidance are the degradation ladder beneath them +**Success Gates**: +- ✅ `cd server && uv run pytest -q` green with tests that pin every rung: explicit `paths` wins, `_meta` stamp resolves per call, rooted answer resolves per call (AFTER `probe_hardening`'s race fix — a late-arriving roots answer must not lose to a premature `cwd` fallback), `COLGREP_MCP_ROOT` applies only when both dynamic rungs are silent, and a silent-everything call raises the guidance error naming the `paths` remedy +- ✅ The served guide `server/colgrep_mcp/guide.md` states the ladder order and the `paths` remedy; `test_readme.py`/drift tests stay green +- ✅ Resolution outcome is byte-identical with the probe disabled (dump-only law intact from step 0 of `probe_hardening`) +**References**: [R01 §Proposed State](../../__reports__/workspace_discovery/00-architecture_v0.md) — the ladder diagram this implements; [R03b §Results](../../__reports__/workspace_discovery/03-findings_live_probe_v0.md) — the live evidence for each dynamic rung; [02-gap_analysis](../../__reports__/workspace_discovery/02-gap_analysis_calibrated_probe_v0.md) — what the calibration tests must catch while this lands + +## Step 1: Consume per-call request meta in the resolver +**Goal**: `paths.resolve_target_paths` reads workspace location from request `_meta` before anything else dynamic. +**Implementation Logic**: +Rung-2a of the ladder. In `paths.py`, `resolve_target_paths` (or a pure helper called by it for testability) reads `ctx.request_context.meta` — via the same `getattr` spines the probe now records — and extracts a workspace directory from documented keys in priority order: an alias list (e.g. `com.visualstudio.code/workspaceFolder`, `com.visualstudio.code/workspace`, plus the repo-documented colgrep key if any) then a single documented primary key. Absent or non-path values degrade to the next rung (never raise). The key list is a module-level constant `META_WORKSPACE_KEYS` — one idiom, one list. Verification trail: fabricated `_meta` stamps in unit tests use `forge_record` snapshots so the probe's `request_meta` column and the resolver agree on what a stamp looks like. +**Deliverables**: `server/colgrep_mcp/paths.py` (exports `META_WORKSPACE_KEYS`, `default_root_from_meta`); `server/tests/test_paths_resolution.py` (`test_meta_stamp_beats_pin_and_cwd`, `test_meta_absent_falls_back_silently`, `test_meta_alias_priority`) +**Consistency Checks**: `grep -q '_meta' __reports__/workspace_discovery/03-findings_live_probe_v0.md` (expected: PASS) +**Commit**: `feat(server): resolve the default root from per-call request meta` + +## Step 2: Per-call roots without the first-call race +**Goal**: The client-roots rung answers from what the client actually sent, never from a lost race. +**Implementation Logic**: +Rung-2b. `client_roots` (shared with the probe call — one round-trip per call, `maintainer-policy` hardware-first) must await the `roots/list` response to completion before concluding; a timeout or remote method-absence classifies `error`-classed roots per `probe` step 1 (`error` is not `empty`). Registration of `list_changed` remains best-effort on 2025-11-25 dialects and must not defer the first answer. The regression test reproduces the measured race from R03b's ledgers (first `resolve` empty-answer → `cwd`, second → `roots`) and asserts the new behaviour resolves `roots` on the first call; it must fail against the pre-fix code to earn its name. +**Deliverables**: `server/colgrep_mcp/paths.py` (`client_roots` awaits completion distinctly classifies error/empty); `server/tests/test_paths_resolution.py` (`test_first_call_roots_race_regression`, `test_roots_error_falls_to_pin`) +**Consistency Checks**: `grep -q 'race' __reports__/workspace_discovery/03-findings_live_probe_v0.md` (expected: PASS) +**Commit**: `feat(server): resolve per-call roots without the first-call race` + +## Step 3: Wire the ladder, the pin rung, and fail+guidance +**Goal**: The rung order `paths > dynamic > COLGREP_MCP_ROOT > guided failure` is the single resolution idiom, documented in the served guide. +**Implementation Logic**: +Compose `default_root(settings, roots, meta_root) -> (root, source)` with sources `paths` \| `meta` \| `roots` \| `env` \| `cwd`, meta before roots before env-pin per the sponsor fold (explicit argument stays first at the `paths`-level); `resolve_paths` documents that relative entries resolve against this default. When all rungs are silent (no meta, roots error/empty, no pin, and cwd is not a plausible project root — the R01 guarded-cwd condition), raise `Code.ROOT_UNRESOLVED` (advisory id; use the existing error-code registry) whose message names the remedy verbatim: pass an absolute `paths` entry. `guide.md` §Scoping gains the ladder and the remedy sentence (this is the client-visible behaviour change — a pinned test per `maintainer-policy`). Multi-root policy documented: roots[0] when several, surfaced via the existing `root_source` label. +**Deliverables**: `server/colgrep_mcp/paths.py` (`default_root` ladder sources); `server/colgrep_mcp/errors.py` (`ROOT_UNRESOLVED` code with guidance text); `server/colgrep_mcp/guide.md` (§Scoping ladder + remedy); `server/tests/test_paths_resolution.py` (`test_ladder_order_pins_each_rung`, `test_silence_fails_with_paths_guidance`, `test_root_source_labels`) +**Consistency Checks**: `grep -q 'fail+guidance\|fail with guidance' __roadmap__/workspace_discovery/resolution/per_call_resolution.md` (expected: PASS) +**Commit**: `feat(search): land the per-call resolution ladder with guided failure` diff --git a/server/colgrep_mcp/errors.py b/server/colgrep_mcp/errors.py index 02c37e1..a71c443 100644 --- a/server/colgrep_mcp/errors.py +++ b/server/colgrep_mcp/errors.py @@ -40,6 +40,7 @@ class Code(StrEnum): BAD_HIT_ID = "BAD_HIT_ID" INDEX_STORE_UNKNOWN = "INDEX_STORE_UNKNOWN" INDEX_STORE_STALE = "INDEX_STORE_STALE" + ROOT_UNRESOLVED = "ROOT_UNRESOLVED" #: One imperative sentence per code, naming the tool/argument to reach for next. @@ -67,6 +68,7 @@ class Code(StrEnum): Code.BAD_HIT_ID: "Use `hit_id` values exactly as returned by `search`: `:-`.", Code.INDEX_STORE_UNKNOWN: "Run `index_build` on a project that exists on disk so the store can be located; retry.", Code.INDEX_STORE_STALE: "Review them with `index_prune` (a dry run); rerun with `dry_run=false, confirm=true`.", + Code.ROOT_UNRESOLVED: "Pass an absolute `paths` entry naming the project directory to scope the search.", } diff --git a/server/colgrep_mcp/guide.md b/server/colgrep_mcp/guide.md index c767a58..fe3daf9 100644 --- a/server/colgrep_mcp/guide.md +++ b/server/colgrep_mcp/guide.md @@ -69,8 +69,24 @@ Example: `query="where retries are scheduled", pattern="backoff"`. ## Scoping +When you omit `paths`, a search runs against a default project root resolved +per call in this order (the resolution ladder): + +`explicit paths` → a workspace directory the harness sends in the request +`_meta` → the harness's client roots → the `COLGREP_MCP_ROOT` environment +pin → the server's working directory (only when that directory looks like a +project root). + +If nothing above yields a usable root — no `_meta` stamp, no client roots, no +`COLGREP_MCP_ROOT`, and the working directory is not a project — the call +fails with code `ROOT_UNRESOLVED` rather than silently searching the wrong +place. The remedy is to **pass an absolute `paths` entry** naming the project +directory, which scopes the search explicitly and needs no inference. + - `paths` — restrict to specific files or directories instead of the whole - project. + project. Relative entries resolve against the default root above; a single + absolute project directory is the reliable way to scope when the default + root cannot be inferred. - `include` — glob file filters, e.g. `["*.py", "*.rs"]`. - `exclude` — glob file exclusions. - `exclude_dir` — directory names or globs to skip, e.g. diff --git a/server/colgrep_mcp/paths.py b/server/colgrep_mcp/paths.py index abfe944..8bf6ccb 100644 --- a/server/colgrep_mcp/paths.py +++ b/server/colgrep_mcp/paths.py @@ -1,7 +1,9 @@ """The only module that resolves a tool's target paths (R01 §Path resolution invariant, R01 §C2). -Order: explicit argument → COLGREP_MCP_ROOT → first client root → server cwd. +Order (the resolution ladder, R01 §Proposed State; sponsor-fold 2026-11-13): +explicit argument → request `_meta` workspace stamp → per-call client roots → +`COLGREP_MCP_ROOT` pin → guarded server cwd (or `ROOT_UNRESOLVED` guidance). `resolve_target_paths` is the entry point tools call; `resolve_paths` and `default_root` are the pure pieces underneath it, kept separate so they can @@ -10,33 +12,192 @@ from __future__ import annotations +import asyncio import warnings from pathlib import Path +from threading import Lock +from urllib.parse import urlparse from urllib.request import url2pathname from mcp.server.mcpserver import Context from .config import Settings from .errors import Code, tool_error +from .probe import _probe_record # noqa: F401 - PROBE_ENV is exported via probe.PROBE_ENV from .server import get_settings +#: Workspace-location keys read from a request `_meta` stamp, in priority +#: order (R03b measured `_meta` vendor keys arriving verbatim on a stamped +#: call). The leading entries are the documented alias spellings of a host +#: workspace folder; the final entry is the single documented primary key. +#: One list, one idiom (`maintainer-policy`): a resolver reads this list and +#: degrades silently on any absent or non-path value. +META_WORKSPACE_KEYS: tuple[str, ...] = ( + "com.visualstudio.code/workspaceFolder", + "com.visualstudio.code/workspace", + "com.example.workspace", +) -def default_root(settings: Settings, roots: list[Path] | None) -> tuple[Path, str]: - """Return the default project root and the label of where it came from.""" - if settings.root is not None: - return settings.root.expanduser().resolve(), "env" + +def _request_meta(ctx: Context | None) -> dict | None: + """Best-effort extraction of the request `_meta` mapping (R03b). + + Mirrors `probe.record`'s `getattr` spine so the two agree on what a stamp + looks like; never raises, never infers. `meta` is an + `mcp_types.RequestParamsMeta` — a dict of vendor keys — or `None` when + the SDK did not surface one. + """ + try: + request_ctx = getattr(ctx, "request_context", None) if ctx else None + meta = getattr(request_ctx, "meta", None) if request_ctx else None + if meta is None: + return None + dumped = meta.model_dump() if hasattr(meta, "model_dump") else meta + return dict(dumped) if isinstance(dumped, dict) else None + except Exception: + return None + + +def _coerce_workspace_path(raw: str) -> Path | None: + """Coerce a `_meta` workspace value into an existing absolute directory. + + Accepts a `file:` URI or a plain path; percent- and `~`-decodes it, and + returns `None` (silently) when it is relative, unparseable, or names no + existing directory, so a bad stamp degrades to the next ladder rung. + """ + raw = raw.strip() + if not raw: + return None + try: + if raw.startswith("file:"): + raw = url2pathname(urlparse(raw).path) + # A trailing slash is fine; expand `~` homes before evaluating. + p = Path(raw).expanduser() + if not p.is_absolute(): + return None + p = p.resolve() + return p if p.is_dir() else None + except Exception: + return None + + +#: Sub-keys unwrapped when a `_meta` workspace value is itself a dict. +_META_PATH_SUBKEYS: tuple[str, ...] = ("workspaceFolder", "root", "uri", "path") + + +def _meta_to_path(value: object) -> Path | None: + """Coerce a single `_meta` workspace value into an existing directory or `None`.""" + if isinstance(value, str): + return _coerce_workspace_path(value) + if isinstance(value, dict): + for key in _META_PATH_SUBKEYS: + sub = value.get(key) + if isinstance(sub, str): + path = _coerce_workspace_path(sub) + if path is not None: + return path + return None + + +def default_root_from_meta(meta: dict | None) -> Path | None: + """The workspace directory a request `_meta` stamp names (R03b), or `None`. + + Walks `META_WORKSPACE_KEYS` in priority order and returns the first key + whose value coerces to an existing directory. Absent or non-path values + degrade silently (never raise), falling through to the client-roots rung. + A dict-valued stamp is unwrapped under a small set of documented + sub-keys (`workspaceFolder`, `root`, `uri`, `path`) for hosts that nest. + """ + if not meta: + return None + for key in META_WORKSPACE_KEYS: + value = meta.get(key) + path = _meta_to_path(value) + if path is not None: + return path + return None + + +#: Marker files/dirs whose presence makes a directory count as a "plausible +#: project root" — the one place the resolver will quietly accept the server +#: cwd as a default when every higher rung is silent. A cwd with none of +#: these (e.g. a plugin install or harness tree) is not a project, so the +#: ladder refuses it and raises `Code.ROOT_UNRESOLVED` with the `paths` +#: remedy instead of silently scoping to a non-project (R01 guarded-cwd). +_PROJECT_MARKERS: frozenset[str] = frozenset( + { + ".git", + "pyproject.toml", + "package.json", + "Cargo.toml", + "go.mod", + "pom.xml", + "requirements.txt", + "setup.py", + "setup.cfg", + "CMakeLists.txt", + "Makefile", + "README.md", + "workspace.json", + } +) + + +def _is_plausible_project_root(p: Path) -> bool: + """Whether *p* carries a project marker (R01 guarded-cwd condition).""" + try: + return any((p / marker).exists() for marker in _PROJECT_MARKERS) + except OSError: + return False + + +def default_root(settings: Settings, roots: list[Path] | None, meta_root: Path | None = None) -> tuple[Path, str]: + """Return the default project root and the label of where it came from. + + Ladder order (R01 §Proposed State; sponsor fold 2026-11-13): request + `_meta` stamp → per-call client roots → `COLGREP_MCP_ROOT` pin → guarded + server cwd. When several client roots arrive, `roots[0]` is the default + (multi-root policy, surfaced via the `root_source` label). When every + rung is silent *and* the server cwd is not a plausible project root, + raises `Code.ROOT_UNRESOLVED` naming the absolute-`paths`-entry remedy + (fail with guidance, R01 §Error model) — never silence, never a bare loud + fail. + """ + if meta_root is not None: + return meta_root.expanduser().resolve(), "meta" if roots: return roots[0].expanduser().resolve(), "roots" - return Path.cwd().resolve(), "cwd" + if settings.root is not None: + return settings.root.expanduser().resolve(), "env" + cwd = Path.cwd().resolve() + if not _is_plausible_project_root(cwd): + raise tool_error( + Code.ROOT_UNRESOLVED, + "no default workspace resolved from request _meta, client roots, or " + "COLGREP_MCP_ROOT, and the working directory is not a project root — " + "pass an absolute paths entry", + ) + return cwd, "cwd" -def resolve_paths(paths: list[str] | None, settings: Settings, roots: list[Path] | None) -> list[Path]: +def resolve_paths( + paths: list[str] | None, settings: Settings, roots: list[Path] | None, meta_root: Path | None = None +) -> list[Path]: """Resolve user-supplied paths (or the default root) to existing absolute paths. - Relative paths are resolved against the default root. Raises ToolError listing - every path that does not exist, together with the root that was used. + Relative paths are resolved against the default root; a fully absolute + ``paths`` list is honored without consulting the ladder at all, so the + `ROOT_UNRESOLVED` remedy (an absolute `paths` entry) works in exactly the + scenario that names it. Raises ToolError listing every path that does not + exist, together with the root that was used. """ - root, source = default_root(settings, roots) + # The ladder settles only what inference owes: the default root for a + # path-less call, or the base for relative entries. Explicit absolute + # entries stand on their own and never need a default root. + root: Path | None = None + source = "" + if not paths or any(not Path(raw).expanduser().is_absolute() for raw in paths): + root, source = default_root(settings, roots, meta_root) if not paths: if not root.exists(): raise tool_error(Code.PATH_NOT_FOUND, f"Default root {root} (from {source}) does not exist.") @@ -53,48 +214,159 @@ def resolve_paths(paths: list[str] | None, settings: Settings, roots: list[Path] else: missing.append(raw) if missing: + against = f" (relative paths are resolved against {root}, from {source})" if root is not None else "" raise tool_error( Code.PATH_NOT_FOUND, - f"Path(s) not found: {', '.join(missing)} (relative paths are resolved against {root}, from {source}).", + f"Path(s) not found: {', '.join(missing)}{against}.", ) return resolved -async def client_roots(ctx: Context) -> list[Path] | None: - """Best-effort client `roots` (R01 §Path resolution invariant, R05 M1). +#: R03b measured a fresh connection answering the *first* `roots/list` of call +#: 1 with a provisional empty set, then producing the real root a moment later +#: in the same call — and the pre-fix resolver fell to cwd on the first answer, +#: losing the late root. The fix gives the freshly-connected state one bounded +#: reassurance round-trip before concluding "nothing sent", so a late-arriving +#: answer is not beaten by a premature cwd fallback. The budget belongs to the +#: unsettled *state*, not to whichever caller consumes it first: concurrent +#: first calls share one unsettled period and every waiter is released once any +#: re-ask settles it (close-out verifier F4). Once settled (an empty re-ask or +#: any root), steady state snaps back to one round-trip per call. Test +#: harnesses reset this to re-enter the freshly-connected state. +_FIRST_EMPTY_REASSURE = True +_ROOTS_SETTLE_GUARD = Lock() +_FIRST_EMPTY_WAITERS: list[asyncio.Future] = [] - `roots/list` is deprecated as of the 2026-07-28 protocol revision and may - raise `NoBackChannelError` (or just a deprecation warning) on a client - with no back-channel; either way this degrades to `None` rather than - fail the tool call, leaving `resolve_paths` to fall through to cwd. + +def _new_future() -> asyncio.Future: + try: + return asyncio.get_running_loop().create_future() + except RuntimeError: + return asyncio.Future() + + +def _roots_settled() -> None: + """Conclude the reassurance period: release every concurrent waiter.""" + global _FIRST_EMPTY_REASSURE + _FIRST_EMPTY_REASSURE = False + waiters, _FIRST_EMPTY_WAITERS[:] = _FIRST_EMPTY_WAITERS[:], [] + for waiter in waiters: + try: + if not waiter.done(): + waiter.set_result(None) + except Exception: + pass + + +async def _client_roots(ctx: Context) -> tuple[list[Path] | None, bool]: + """`roots`, plus an ``errored`` flag distinguishing a failed round-trip + from a genuine zero-root answer (R05 M1, probe lever 6). + + ``errored`` is True when the back-channel raised or was absent — the + probe's ``roots_list`` classifies that as ``error``, not ``empty``. """ + global _FIRST_EMPTY_REASSURE + result = None try: with warnings.catch_warnings(): warnings.simplefilter("ignore") result = await ctx.session.list_roots() except Exception: - return None + return None, True + + # First empty is provisional (see `_FIRST_EMPTY_REASSURE`): a fresh + # connection reports empty before the harness root lands. The caller that + # catches the unsettled state re-asks (one bounded re-ask per waiter); + # when that re-ask lands a root the period settles and every concurrent + # waiter falls back to its own one-shot re-ask before concluding — a + # first pair of parallel calls must not lose the late root to two + # premature fallbacks (close-out verifier F4). + if result is not None and not result.roots: + settle: asyncio.Future | None = None + with _ROOTS_SETTLE_GUARD: + if _FIRST_EMPTY_REASSURE: + settle = _new_future() + if settle is not None: + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = await ctx.session.list_roots() + except Exception: + result = None + if result is not None and result.roots: + _roots_settled() + else: + with _ROOTS_SETTLE_GUARD: + if _FIRST_EMPTY_REASSURE: + _FIRST_EMPTY_WAITERS.append(settle) + else: + settle = None + if settle is not None: + try: + await asyncio.wait_for(asyncio.shield(settle), timeout=0.1) + except TimeoutError: + # Nobody settled the period in time: conclude empty + # for everyone rather than park (bounded reassurance). + _roots_settled() + return None, False + # The period settled under us (a waiter landed the root): + # decide this call on one more ask, never on the stale empty. + try: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = await ctx.session.list_roots() + except Exception: + result = None + if result is not None and result.roots: + _roots_settled() + + if result is None: + return None, True if not result.roots: - return None + return None, False try: # A root is a `file:` URI: `url2pathname` percent-decodes it (a root # with a space arrives as `%20`) and, on Windows, turns the URI form # `/C:/Users/x` into the drive-rooted path `C:\Users\x` — `Path()` on # the raw `.path` did neither, so such roots resolved to nonsense. - return [Path(url2pathname(root.uri.path)) for root in result.roots if root.uri.path] + # A root that names no directory is unusable and excluded: pydantic + # normalizes a path-less `file:` URI to the truthy path `'/'`, which + # would silently scope a path-less call to the entire filesystem + # (close-out verifier F2). Excluded, it degrades to the zero-root + # class — never to a root the client never named. + return [ + Path(url2pathname(root.uri.path)) + for root in result.roots + if root.uri.path and root.uri.path.rstrip("/") != "" + ], False except Exception: - return None + return None, True + + +async def client_roots(ctx: Context) -> list[Path] | None: + """Best-effort client `roots` (R01 §Path resolution invariant, R05 M1). + + `roots/list` is deprecated as of the 2026-07-28 protocol revision and may + raise `NoBackChannelError` (or just a deprecation warning) on a client + with no back-channel; either way this degrades to `None` rather than + fail the tool call, leaving `resolve_paths` to fall through to cwd. + """ + roots, _errored = await _client_roots(ctx) + return roots -def _roots_can_matter(paths: list[str] | None, settings: Settings) -> bool: +def _roots_can_matter(paths: list[str] | None, settings: Settings, meta_root: Path | None = None) -> bool: """Whether `client_roots` could change what `resolve_paths` returns. - The client root is consulted only when no `COLGREP_MCP_ROOT` is set *and* - something still has to be resolved against a default root: no paths at - all, or at least one relative path. Under the Claude Code plugin the env - root is always set, so every `search` used to pay a `roots/list` - round-trip whose answer could not be used. + The client root is consulted only when no earlier rung has already + settled the default root *and* something still has to be resolved against + a default root: no paths at all, or at least one relative path. Under + the Claude Code plugin the env root is always set, so every `search` used + to pay a `roots/list` round-trip whose answer could not be used. A + request `_meta` stamp outranks roots, so it suppresses the round-trip too. """ + if meta_root is not None: + return False if settings.root is not None: return False if not paths: @@ -103,7 +375,22 @@ def _roots_can_matter(paths: list[str] | None, settings: Settings) -> bool: async def resolve_target_paths(ctx: Context, paths: list[str] | None) -> list[Path]: - """`resolve_paths` for a tool call, fetching client roots only when they can matter.""" + """`resolve_paths` for a tool call, resolving the per-call default root. + + Reads a request `_meta` workspace stamp (rung 2a) before consulting the + per-call client roots (rung 2b, only when the earlier rungs left the + default root unsettled). + """ settings = get_settings(ctx) - roots = await client_roots(ctx) if _roots_can_matter(paths, settings) else None - return resolve_paths(paths, settings, roots) + meta_root = default_root_from_meta(_request_meta(ctx)) + if _roots_can_matter(paths, settings, meta_root): + roots, roots_error = await _client_roots(ctx) + else: + roots, roots_error = None, False + + # Probe hook: best-effort dump of the resolution outcome (maintainer-policy + # section *One idiom per concern*: use ``safe_log`` on failure). Always + # inert when COLGREP_MCP_PROBE is unset; never alters the resolved result. + _probe_record(ctx, paths, settings, roots, meta_root=meta_root, roots_error=roots_error) + + return resolve_paths(paths, settings, roots, meta_root) diff --git a/server/colgrep_mcp/probe.py b/server/colgrep_mcp/probe.py new file mode 100644 index 0000000..355ee52 --- /dev/null +++ b/server/colgrep_mcp/probe.py @@ -0,0 +1,295 @@ +"""Inert, dump-only probe that records workspace-signal snapshots (R01). + +With ``COLGREP_MCP_PROBE`` unset, no file is touched, no tool surface changes, +no resolution path changes. When set, ``record(...)`` appends a single JSONL +line to ``$COLGREP_MCP_PROBE/colgrep_probe.jsonl``. + +The probe must never raise into the resolve chain (maintainer-policy +section *One idiom per concern*: use ``safe_log`` on failure). ``record`` is +total: no input — ``ctx=None``, a non-serializable snapshot value, an +unwritable probe dir — may raise past the resolve call site. Every ledger +column reflects what was measured, never what the probe can guess: the +``tool`` column is attributed from the actual calling tool (never ``"record"``) +and ``roots_list.static`` distinguishes ``declared`` / ``empty`` / ``error``. + +Report references: R01 section Probe dump schema; +02-gap_analysis_calibrated_probe_v0.md (four defect lines each step repairs); +02-findings_probe_verifier_v0.md (lever table). +""" + +from __future__ import annotations + +import inspect +import json +import logging +import os +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +PROBE_ENV = "COLGREP_MCP_PROBE" + +# Canonical stub-authored record (lever 1b): the exact fabricated line the stub +# driver used to write, whose `init_capabilities`/`roots_list` values a running +# harness never sent. The calibration oracle (forge_record/diff_record) must +# whistle on this verbatim fabrication. +FORGED_SAMPLE: dict[str, Any] = { + "ts": "2026-01-01T00:00:00+00:00", + "server_pid": 1, + "tool": "doctor", + "raw_paths": None, + "env": { + "COLGREP_MCP_ROOT": None, + "COLGREP_MCP_BINARY": None, + "spawn_env_digest": None, + }, + "init_capabilities": {"protocolVersion": "NONE"}, + "request_meta": None, + "roots_list": {"static": "empty", "items": []}, + "resolved": {"root": "", "source": "cwd"}, + "cwd": "/stub/cwd", + "provenance": "stub", +} + +_LOG = logging.getLogger("colgrep_mcp") + +# Functions that live inside the probe/resolve machinery and must never be +# mistaken for the tool handler that surfaced a record (lever 1: the frame +# scan used to resolve to ``record`` itself every time). +_PROBE_INTERNAL_NAMES = frozenset( + { + "record", + "_probe_record", + "_probe_tool_name", + "capture_pure", + "forge_record", + "diff_record", + "resolve_target_paths", + "resolve_paths", + "default_root", + "_roots_can_matter", + "client_roots", + "_client_roots", + } +) + + +def capture_pure(snap: dict[str, Any]) -> str: + """Serialise *snap* to one JSONL line with sorted, deterministic keys. + + ``default=str`` coerces a value with no native JSON encoding so the record + stays a witness (lever 2b: an unmappable snapshot value must not turn into + a ``TypeError`` that escapes the never-raise boundary). + """ + return json.dumps(snap, sort_keys=True, ensure_ascii=False, default=str) + + +def _try_dump(obj: Any) -> Any: + """``obj.model_dump()`` when available, else *obj* as-is.""" + if obj is None: + return None + if hasattr(obj, "model_dump"): + return obj.model_dump() + return obj + + +def _probe_tool_name() -> str: + """Best-effort tool name from the call stack (lever 1 repair). + + Walks frames upward from the first caller of ``record``, skipping module + internal names (including ``record`` itself), to find the first function + that stands for a real tool handler — ``search``, ``expand``, ``doctor``, + ``find_files``, etc. Falls back to ``"probe"``. + """ + try: + frame = inspect.currentframe() + frame = frame.f_back if frame is not None else None + while frame is not None: + name = frame.f_code.co_name + if name not in _PROBE_INTERNAL_NAMES: + return name + frame = frame.f_back + except Exception: + pass + return "probe" + + +def _classify_roots(settings_root: Path | None, roots: list[Path] | None, roots_error: bool) -> str: + """Truth-source ``roots_list.static`` (lever 6 / gap defect 6). + + - ``declared``: a ``COLGREP_MCP_ROOT`` pin is present, or ``client_roots`` + actually returned usable items. + - ``error``: the ``roots/list`` round-trip raised or the back-channel was + absent — we could not ask, which is not the same as nothing sent. + - ``empty``: only when a client genuinely answered with zero usable roots. + """ + if settings_root is not None: + return "declared" + if roots: + return "declared" + if roots_error: + return "error" + return "empty" + + +def record( + ctx: Any, + raw_paths: list[str] | None, + settings_root: Path | None, + roots: list[Path] | None, + resolved_root: Path | None, + resolved_source: str, + *, + roots_error: bool = False, + tool: str | None = None, +) -> None: + """Append one JSONL probe record to the ledger file. + + *ctx* is the MCP ``Context`` (or ``None`` in tests). ``init_capabilities`` + and ``request_meta`` are pulled via ``getattr`` from + ``ctx.request_context`` — SDK absent or fragment yields ``None``, never + inferred (R01 section Contracts & Invariants). + + *tool* names the actual calling tool when known (the hook site passes it); + otherwise it is resolved from the stack, never assumed to be ``"record"``. + *roots_error* tells the ``roots_list`` classification that the round-trip + failed rather than that the client sent nothing. + + Best-effort and total: every failure path is swallowed via ``safe_log``/ + a log line and never surfaces past this call (lever 2b). + """ + probe_dir = os.environ.get(PROBE_ENV) + if not probe_dir: + return + + try: + # Build roots_list from the classification, not a second round-trip. + roots_list_data: dict[str, Any] = { + "static": _classify_roots(settings_root, roots, roots_error), + "items": [str(r) for r in roots] if roots else [], + } + + # Extract SDK fields via getattr (may not exist in every SDK version). + init_caps = None + req_meta = None + try: + request_ctx = getattr(ctx, "request_context", None) if ctx else None + init_caps = _try_dump(getattr(request_ctx, "initialize", None)) if request_ctx else None + req_meta = _try_dump(getattr(request_ctx, "meta", None)) if request_ctx else None + except Exception: + init_caps = None + req_meta = None + + env_snapshot: dict[str, str | None] = { + "COLGREP_MCP_ROOT": os.environ.get("COLGREP_MCP_ROOT"), + "COLGREP_MCP_BINARY": os.environ.get("COLGREP_MCP_BINARY"), + "spawn_env_digest": os.environ.get("COLGREP_MCP_SPAWN_ENV_DIGEST"), + } + + record_obj = { + "ts": datetime.now(UTC).isoformat(), + "server_pid": os.getpid(), + "tool": tool if tool is not None else _probe_tool_name(), + "raw_paths": raw_paths, + "env": env_snapshot, + "init_capabilities": init_caps, + "request_meta": req_meta, + "roots_list": roots_list_data, + "resolved": {"root": str(resolved_root) if resolved_root is not None else None, "source": resolved_source}, + "cwd": str(Path.cwd()), + } + + line = capture_pure(record_obj) + log_path = Path(probe_dir) / "colgrep_probe.jsonl" + log_path.parent.mkdir(parents=True, exist_ok=True) + with open(log_path, "a", encoding="utf-8") as fh: + fh.write(line + "\n") + except Exception: + # Total boundary: an unmappable snapshot value, a serialization + # failure, or an unwritable probe dir must never break the caller. + try: + _LOG.debug("probe write failed; continuing without a record") + except Exception: + pass + + +def _probe_record( + ctx: Any, + paths: list[str] | None, + settings: Any, + roots: list[Path] | None, + *, + meta_root: Path | None = None, + roots_error: bool = False, + tool: str | None = None, +) -> None: + """Called from ``paths.resolve_target_paths`` after ``client_roots``. + + Reuses ``default_root`` (the pure function) to build the resolved output + — no second resolution pass, just a label walk. The walk is inside the + total boundary and threads *meta_root*: when the ladder declines a root + (``Code.ROOT_UNRESOLVED``) the record reports ``unresolved`` instead of + raising, and when meta settled the root the record says ``meta`` — the + ledger must agree with the call it measures, and a dump-only probe must + never raise past the resolve call site. + """ + from .paths import default_root + + settings_root = settings.root if hasattr(settings, "root") else getattr(settings, "root", None) + resolved_root: Path | None = None + resolved_source = "unresolved" + try: + resolved_root, resolved_source = default_root(settings, roots, meta_root) + except Exception: + resolved_root, resolved_source = None, "unresolved" + record( + ctx, + paths, + settings_root, + roots, + resolved_root, + resolved_source, + roots_error=roots_error, + tool=tool, + ) + + +def forge_record(**overrides: Any) -> dict[str, Any]: + """Build a ground-truth record from an explicit snapshot (calibration). + + No frame reading, no ``os.environ`` reading — every field is either the + static default or an explicit ``**overrides`` value, so a harness can + construct the record a *truthful* probe *should* have written and differ + it against the ledger to catch a probe that lies. + """ + record_obj: dict[str, Any] = { + "ts": "2026-01-01T00:00:00+00:00", + "server_pid": 1, + "tool": "search", + "raw_paths": None, + "env": { + "COLGREP_MCP_ROOT": None, + "COLGREP_MCP_BINARY": None, + "spawn_env_digest": None, + }, + "init_capabilities": None, + "request_meta": None, + "roots_list": {"static": "empty", "items": []}, + "resolved": {"root": "/truth/root", "source": "cwd"}, + "cwd": "/truth/cwd", + } + record_obj.update(overrides) + return record_obj + + +def diff_record(expected: dict[str, Any], actual: dict[str, Any]) -> list[str]: + """Field-level disagreements between *expected* truth and *actual*. + + Returns a list of disagreement strings, one per field whose value + differs; empty when the two records agree on every key. + """ + disagreements: list[str] = [] + for key in sorted(set(expected) | set(actual)): + if expected.get(key) != actual.get(key): + disagreements.append(f"{key}: expected {expected.get(key)!r}, got {actual.get(key)!r}") + return disagreements diff --git a/server/tests/e2e/probe_workspace.py b/server/tests/e2e/probe_workspace.py new file mode 100644 index 0000000..6b969e2 --- /dev/null +++ b/server/tests/e2e/probe_workspace.py @@ -0,0 +1,244 @@ +"""Probe-driven harness evidence driver. + +Runs the packaged server through a named harness (``claude`` or ``codex``) +with a stub ``colgrep`` on ``$PATH`` so no real index is touched (stack-traps). + +The stub's ``doctor`` subcommand writes one R01-schema JSONL record per +invocation into ``$COLGREP_MCP_PROBE/colgrep_probe.jsonl`` and prints the +static ``doctor`` payload. Stub-written records are stamped +``"provenance": "stub"`` (lever 1b / gap defect 1); the server-written rows +carry no provenance field, so the ledger can tell them apart. + +Never invokes real ``colgrep``, never writes an index against any repository. +The only string sent to any harness API is the canned ``TRIGGER_PROMPT``. + +Raw evidence dirs are rotated whole under +``__reports__/workspace_discovery/probe_data/`` (gitignored), keeping the +newest 3. + +Exports: +- **main**: top-level entry point; runs a single harness probe. +- **collect_for(harness)**: runs the harness probe and returns the raw JSONL. +- **validate(raw_path)**: validates every JSONL line, tolerating gap rows. +- **_validate_record(line)**: per-line verdict, never raises. +- **TRIGGER_PROMPT**: one-line canned trigger whose shape is diffable. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +TRIGGER_PROMPT = "Run the colgrep doctor tool now. Reply done." + +# Stub colgrep script — never touches a real index. Stub-written records are +# stamped ``provenance: stub`` so a ledger reader can separate stub synthesis +# from server-written rows (lever 1b). +_STUB_SCRIPT = ( + "#!/usr/bin/env python3\n" + "# Colgrep stub for probe_workspace.\n" + "import json, os, sys\n" + "from pathlib import Path\n" + "from datetime import datetime, timezone\n" + "\n" + "ENV = os.environ\n" + 'PROBE_DIR = ENV.get("COLGREP_MCP_PROBE", "")\n' + "TOOLS = [\n" + ' {"name": "search", "description": "semantic search"},\n' + ' {"name": "doctor", "description": "doctor"},\n' + "]\n" + 'cmd = sys.argv[1] if len(sys.argv) > 1 else "info"\n' + "env = {\n" + ' "COLGREP_MCP_ROOT": ENV.get("COLGREP_MCP_ROOT", ""),\n' + ' "COLGREP_MCP_BINARY": ENV.get("COLGREP_MCP_BINARY", ""),\n' + ' "spawn_env_digest": ENV.get("COLGREP_MCP_SPAWN_ENV_DIGEST", ""),\n' + "}\n" + "RECORD = {\n" + ' "ts": datetime.now(timezone.utc).isoformat(),\n' + ' "server_pid": os.getpid(),\n' + ' "tool": cmd,\n' + ' "raw_paths": None,\n' + ' "env": env,\n' + ' "init_capabilities": None,\n' + ' "request_meta": None,\n' + ' "roots_list": {"static": "empty", "items": []},\n' + ' "resolved": {\n' + ' "root": ENV.get("COLGREP_MCP_ROOT", ""),\n' + ' "source": "env" if "COLGREP_MCP_ROOT" in ENV else "cwd",\n' + " },\n" + ' "cwd": str(Path.cwd()),\n' + ' "provenance": "stub",\n' + "}\n" + "\n" + "if PROBE_DIR:\n" + " Path(PROBE_DIR).mkdir(parents=True, exist_ok=True)\n" + ' with open(os.path.join(PROBE_DIR, "colgrep_probe.jsonl"), "a") as fh:\n' + ' fh.write(json.dumps(RECORD, sort_keys=True) + "\\n")\n' + "\n" + 'if cmd == "doctor":\n' + " print(json.dumps(RECORD))\n" + "else:\n" + ' print("{}")\n' + "sys.exit(0)\n" +) + +_R01_REQUIRED = ( + "ts", + "server_pid", + "tool", + "raw_paths", + "env", + "init_capabilities", + "request_meta", + "roots_list", + "resolved", + "cwd", +) + +_PROBE_DATA_ROOT = Path(__file__).resolve().parents[3] / "__reports__" / "workspace_discovery" / "probe_data" +_RAW_ROOT = _PROBE_DATA_ROOT / "raw" +_KEEP_RAW_DIRS = 3 + + +def _make_stub() -> Path: + """Create a minimal ``colgrep`` stub on the temp ``$PATH``. + + The stub's ``doctor`` subcommand writes one R01-schema JSONL record + (stamped ``provenance: stub``) into ``$COLGREP_MCP_PROBE/colgrep_probe.jsonl`` + and echoes a static payload. All other subcommands are no-ops that exit 0. + """ + stub_dir = Path(tempfile.mkdtemp(prefix="colgrep_probe_stub_")) + stub = stub_dir / "colgrep" + stub.write_text(_STUB_SCRIPT, encoding="utf-8") + stub.chmod(0o755) + return stub_dir + + +def _collect_one_harness(harness: str, tmp_dir: Path, server_root: Path) -> Path: + """Internal: launch harness + stub and return the probe JSONL path.""" + stub_dir = _make_stub() + env = os.environ.copy() + env["PATH"] = str(stub_dir) + os.pathsep + env.get("PATH", "") + + probe_dir = tmp_dir / "probe_data" + probe_dir.mkdir(parents=True, exist_ok=True) + env["COLGREP_MCP_PROBE"] = str(probe_dir) + + harness_exe = shutil.which(harness) + if harness_exe is None: + gap = {"error": f"harness not found: {harness}"} + (probe_dir / "colgrep_probe.jsonl").write_text(json.dumps(gap, sort_keys=True) + "\n", encoding="utf-8") + return probe_dir / "colgrep_probe.jsonl" + + subprocess.run( + [harness_exe, "-p", TRIGGER_PROMPT], + cwd=str(server_root), + env=env, + timeout=30, + capture_output=True, + text=True, + ) + if not (probe_dir / "colgrep_probe.jsonl").exists(): + gap = {"error": f"{harness} completed but no probe record written"} + (probe_dir / "colgrep_probe.jsonl").write_text(json.dumps(gap, sort_keys=True) + "\n", encoding="utf-8") + return probe_dir / "colgrep_probe.jsonl" + + +def _rotate_raw(raw_jsonl: Path) -> None: + """Persist one fresh raw run into ``probe_data/raw``, keeping whole raw + dirs and retaining the newest ``_KEEP_RAW_DIRS``. The directory is + gitignored by ``probe_data/.gitignore`` so rotation never pollutes git.""" + ts = datetime.now(UTC).strftime("%Y%m%dT%H%M%S") + dump = _RAW_ROOT / f"dump-{ts}" + dump.mkdir(parents=True, exist_ok=True) + for src in raw_jsonl.parent.iterdir(): + if src.is_file(): + shutil.copy2(src, dump / src.name) + shutil.copy2(raw_jsonl, dump / raw_jsonl.name) + + dumps = sorted(_RAW_ROOT.glob("dump-*"), key=lambda p: p.stat().st_mtime, reverse=True) + for old in dumps[_KEEP_RAW_DIRS:]: + shutil.rmtree(old, ignore_errors=True) + + +def collect_for(harness: str, server_root: Path | None = None) -> Path: + """Run *harness* probe and return the raw JSONL path. + + *harness* is one of ``claude`` or ``codex``. The driver injects + a stub ``colgrep`` into ``$PATH`` and launches the harness CLI. + + On timeout, non-zero exit or missing-ledger, appends an explicit + gap record ``{"error": ""}``. Each run's raw dir is rotated + whole under ``probe_data/raw``, keeping the newest 3. + """ + server_root = server_root or Path(__file__).resolve().parents[2] + + with tempfile.TemporaryDirectory(prefix="probe_workspace_") as td: + tmp_dir = Path(td) + raw = _collect_one_harness(harness, tmp_dir, server_root) + _rotate_raw(raw) + return raw + + +def _validate_record(line: str) -> str: + """Per-line verdict for raw JSONL: ``"valid"``, ``"gap"``, or ``"invalid"``. + + Tolerates the driver's own ``{"error": ...}`` gap rows — they parse to a + ``"gap"`` verdict instead of KeyError-ing on ``snap["ts"]`` (lever 5 / + gap defect 5). Never raises. + """ + try: + snap: Any = json.loads(line) + except json.JSONDecodeError: + return "invalid:not-json" + if not isinstance(snap, dict): + return "invalid:not-object" + if "error" in snap: + return "gap" + if set(_R01_REQUIRED).issubset(snap): + return "valid" + return "invalid:missing-keys" + + +def validate(raw_path: Path) -> bool: + """True when every line of *raw_path* is valid R01 or a tolerated gap. + + A gap row never crashes validation — it reports, exactly as the driver's + own gap signalling requires (never KeyError on ``snap["ts"]``). + """ + if not raw_path.exists(): + return False + for line in raw_path.read_text().strip().splitlines(): + line = line.strip() + if not line: + continue + verdict = _validate_record(line) + if verdict.startswith("invalid"): + return False + return True + + +def main() -> None: + """Top-level entry point: collects evidence from one harness.""" + harness = "claude" if len(sys.argv) < 2 else sys.argv[1] + if harness not in ("claude", "codex"): + print(f"Usage: {sys.argv[0]} [claude|codex]", file=sys.stderr) + sys.exit(1) + + server_root = Path(__file__).resolve().parents[2] + raw = collect_for(harness, server_root) + ok = validate(raw) + print(f"{harness} probe: {'OK' if ok else 'FAIL'} ({raw})") + if not ok: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/server/tests/test_errors.py b/server/tests/test_errors.py index 8961d32..e33118c 100644 --- a/server/tests/test_errors.py +++ b/server/tests/test_errors.py @@ -30,6 +30,7 @@ def test_code_enum_has_exactly_the_specified_members(): "INDEX_COLD", "PATH_NOT_FOUND", "PROJECT_ROOT_MISMATCH", + "ROOT_UNRESOLVED", "CONFIRMATION_REQUIRED", "COLGREP_MISSING", "COLGREP_FAILED", diff --git a/server/tests/test_paths.py b/server/tests/test_paths.py index cf832a7..fac2fac 100644 --- a/server/tests/test_paths.py +++ b/server/tests/test_paths.py @@ -9,9 +9,12 @@ from colgrep_mcp.paths import default_root, resolve_paths -def test_default_root_prefers_env(tmp_path): +def test_default_root_orders_meta_first_then_roots(tmp_path): + meta_root = tmp_path / "meta-root" + root, src = default_root(Settings(root=tmp_path), [Path("/elsewhere")], meta_root) + assert root == meta_root.resolve() and src == "meta" root, src = default_root(Settings(root=tmp_path), [Path("/elsewhere")]) - assert root == tmp_path.resolve() and src == "env" + assert root == Path("/elsewhere").resolve() and src == "roots" def test_default_root_falls_back_to_roots_then_cwd(tmp_path): diff --git a/server/tests/test_paths_resolution.py b/server/tests/test_paths_resolution.py new file mode 100644 index 0000000..4a4aff0 --- /dev/null +++ b/server/tests/test_paths_resolution.py @@ -0,0 +1,385 @@ +"""Tests for the per-call workspace resolution ladder (`resolution` leaf). + +Steps land one commit at a time; each rung of the ladder +`paths > _meta > roots > COLGREP_MCP_ROOT > guarded-cwd` is pinned by a test +that fails against the rung's pre-fix state (fail-first): + +- Step 1 (`feat(server): resolve the default root from per-call request meta`): + `test_meta_stamp_beats_pin_and_cwd`, `test_meta_absent_falls_back_silently`, + `test_meta_alias_priority`. +- Step 2 (`feat(server): resolve per-call roots without the first-call race`): + `test_first_call_roots_race_regression`, `test_roots_error_falls_to_pin`. +- Step 3 (`feat(search): land the per-call resolution ladder with guided failure`): + `test_ladder_order_pins_each_rung`, `test_silence_fails_with_paths_guidance`, + `test_root_source_labels`. + +Fabricated `_meta` stamps mirror what `probe.record` records (`request_meta` is +the vendor-key dict from `ctx.request_context.meta`), per the calibration +oracle discipline (02-gap_analysis_calibrated_probe_v0.md). +""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace + +import pytest +from mcp.types import ListRootsResult, Root + +from colgrep_mcp.config import Settings + +pytestmark = pytest.mark.anyio + + +async def _absent_roots(): + """Default fake `session.list_roots`: a genuine zero-root answer.""" + return ListRootsResult(roots=[]) + + +def _meta_ctx(meta, *, env_root: Path | None = None, session=None) -> SimpleNamespace: + """A fake MCP `Context` shaped like the SDK's for `resolve_target_paths`. + + `get_settings` reads `ctx.request_context.lifespan_context.settings`; + the resolver reads the `_meta` stamp from `ctx.request_context.meta`; the + roots round-trip goes over `ctx.session` (the SDK's `Context.session` + property). The same object is reachable through both paths so a fake can + drive the roots response. ``session`` defaults to a genuine zero-root + responder; a test overrides ``ctx.session.list_roots`` to drive a race. + """ + settings = Settings(root=env_root) + session = session if session is not None else SimpleNamespace(list_roots=_absent_roots) + return SimpleNamespace( + session=session, + request_context=SimpleNamespace( + lifespan_context=SimpleNamespace(settings=settings), + meta=meta, + session=session, + ), + ) + + +# --------------------------------------------------------------------------- +# Step 1 — request `_meta` workspace stamp (rung 2a) +# --------------------------------------------------------------------------- + + +def test_meta_stamp_beats_pin_and_cwd(tmp_path): + """A `_meta` workspace stamp resolves to the stamped root even when a + `COLGREP_MCP_ROOT` pin *and* a different server cwd are present — meta is + the higher dynamic rung (R03b; ladder meta > roots > env > guarded-cwd).""" + from colgrep_mcp.paths import default_root, default_root_from_meta + + stamped = tmp_path / "stamped-workspace" + stamped.mkdir() + pinned = tmp_path / "pinned" + pinned.mkdir() + + meta_root = default_root_from_meta({"com.example.workspace": str(stamped)}) + root, source = default_root(Settings(root=pinned), None, meta_root) + assert root == stamped.resolve() + assert source == "meta" + + +def test_meta_absent_falls_back_silently(tmp_path): + """No `_meta` stamp degrades to the next rung without raising.""" + from colgrep_mcp.paths import default_root_from_meta + + assert default_root_from_meta(None) is None + assert default_root_from_meta({}) is None + # A stamp that is present but unusable (relative path, missing dir, or a + # non-path value) also degrades silently — never raises. + assert default_root_from_meta({"com.example.workspace": "relative/path"}) is None + assert default_root_from_meta({"com.example.workspace": str(tmp_path / "nope")}) is None + assert default_root_from_meta({"com.example.workspace": 42}) is None + + +def test_meta_alias_priority(tmp_path): + """`META_WORKSPACE_KEYS` is honoured in priority order: the first key with + a usable value wins, even when later (higher-key) aliases carry other + values.""" + from colgrep_mcp.paths import META_WORKSPACE_KEYS, default_root_from_meta + + winner = tmp_path / "winner" + winner.mkdir() + loser = tmp_path / "loser" + loser.mkdir() + + assert META_WORKSPACE_KEYS[0] == "com.visualstudio.code/workspaceFolder" + # First alias names the winner; the primary key names a different dir. + stamp = { + "com.visualstudio.code/workspaceFolder": str(winner), + "com.example.workspace": str(loser), + } + assert default_root_from_meta(stamp) == winner.resolve() + + # When the leading alias is unusable, the next key is consulted. + stamp2 = {"com.visualstudio.code/workspaceFolder": "relative/x", "com.example.workspace": str(winner)} + assert default_root_from_meta(stamp2) == winner.resolve() + + +async def test_meta_resolves_through_resolve_target_paths(tmp_path): + """End-to-end: `resolve_target_paths` turns a `_meta` stamp into the + scoped root without touching env or roots.""" + from colgrep_mcp.paths import resolve_target_paths + + stamped = tmp_path / "ws" + stamped.mkdir() + ctx = _meta_ctx({"com.example.workspace": str(stamped)}) + result = await resolve_target_paths(ctx, None) + assert result == [stamped.resolve()] + + +# --------------------------------------------------------------------------- +# Step 2 — per-call client roots without the first-call race (rung 2b) +# --------------------------------------------------------------------------- + + +def _flaky_first_empty_root(ctx, root: Path): + """Give `ctx` a `session.list_roots` that answers the *first* call with an + empty set and the second with `root` — the R03b first-call race shape — + and return a counter recording how many `roots/list` round-trips ran.""" + calls = {"n": 0} + + async def list_roots(): + calls["n"] += 1 + if calls["n"] == 1: + return ListRootsResult(roots=[]) + return ListRootsResult(roots=[Root(uri=root.as_uri())]) + + ctx.session.list_roots = list_roots + return calls + + +async def test_first_call_roots_race_regression(tmp_path): + """The first `resolve` on a fresh connection must answer from the roots the + client actually sent, never from a premature cwd fallback (R03b: first + resolve empty -> `cwd`, second -> `roots`; a late root must win).""" + from colgrep_mcp import paths as paths_module + from colgrep_mcp.paths import resolve_target_paths + + # Re-enter the freshly-connected state: once a non-first empty has turned + # the reassurance off, later calls must not keep re-asking (one round-trip + # per call steady state) — so re-arm it for the race the fix targets. + paths_module._FIRST_EMPTY_REASSURE = True + try: + project = tmp_path / "corpus" + project.mkdir() + ctx = _meta_ctx(None) + calls = _flaky_first_empty_root(ctx, project) + + resolved = await resolve_target_paths(ctx, None) + + assert calls["n"] == 2, "the first empty must be re-asked once (bounded reassurance)" + assert resolved == [project.resolve()], ( + f"the late-arriving root must win over a premature cwd fallback; resolved {resolved}" + ) + finally: + paths_module._FIRST_EMPTY_REASSURE = True + + +def test_roots_error_falls_to_pin(tmp_path): + """A failed roots round-trip (`error`, not `empty`) falls to the + `COLGREP_MCP_ROOT` pin; it must never land on cwd when a pin is set.""" + from colgrep_mcp.paths import default_root + + pinned = tmp_path / "pin" + pinned.mkdir() + # roots = None is the `error`-classed form `_client_roots` returns when the + # back-channel raised or was absent (probe lever 6: error != empty). + root, source = default_root(Settings(root=pinned), None) + assert root == pinned.resolve() and source == "env" + + +# --------------------------------------------------------------------------- +# Step 3 — the ladder, the pin rung, and fail-with-guidance (R01 guarded-cwd) +# --------------------------------------------------------------------------- + + +def test_ladder_order_pins_each_rung(tmp_path, monkeypatch): + """The rung order `_meta > roots > COLGREP_MCP_ROOT > guarded-cwd` is the + single resolution idiom: each higher rung wins over every lower one, and + a silent-everything call under a plausible cwd uses the cwd.""" + from colgrep_mcp.paths import default_root + + stamped = tmp_path / "meta-ws" + stamped.mkdir() + rooted = tmp_path / "roots-ws" + rooted.mkdir() + pinned = tmp_path / "pin" + pinned.mkdir() + cwd_proj = tmp_path / "cwd-proj" + cwd_proj.mkdir() + (cwd_proj / "pyproject.toml").touch() + + settings = Settings(root=pinned) + # meta beats roots, pin, and cwd. + assert default_root(settings, [rooted], stamped)[1] == "meta" + # roots beats pin and cwd (no meta). + assert default_root(settings, [rooted], None) == (rooted.resolve(), "roots") + # pin beats cwd (no meta, no roots). + assert default_root(settings, None, None) == (pinned.resolve(), "env") + # all silent under a plausible cwd uses the cwd. + monkeypatch.chdir(cwd_proj) + root, source = default_root(Settings(), None, None) + assert source == "cwd" + assert root == cwd_proj.resolve() + + +def test_silence_fails_with_paths_guidance(tmp_path, monkeypatch): + """When every rung is silent and the working directory is not a plausible + project root, resolution raises `ROOT_UNRESOLVED` whose message names the + remedy verbatim: pass an absolute `paths` entry (R01 fail+guidance).""" + from mcp.server.mcpserver.exceptions import ToolError + + from colgrep_mcp.errors import Code + from colgrep_mcp.paths import default_root + + not_a_project = tmp_path / "not-a-project" + not_a_project.mkdir() + monkeypatch.chdir(not_a_project) + + with pytest.raises(ToolError) as excinfo: + default_root(Settings(), None, None) + + msg = str(excinfo.value) + assert Code.ROOT_UNRESOLVED in msg + assert "paths" in msg and "absolute" in msg + + +def test_root_source_labels(tmp_path): + """Every ladder source is surfaced through the `root_source` label, and a + multi-root answer uses `roots[0]` (R01 multi-root policy).""" + from colgrep_mcp.paths import default_root + + pinned = tmp_path / "pin" + pinned.mkdir() + first = tmp_path / "first" + first.mkdir() + second = tmp_path / "second" + second.mkdir() + stamped = tmp_path / "stamp" + stamped.mkdir() + + assert default_root(Settings(), [first, second], None)[1] == "roots" + assert default_root(Settings(), [first, second], None)[0] == first.resolve() # roots[0] + assert default_root(Settings(root=pinned), None, stamped)[1] == "meta" + + +def test_guide_documents_ladder_and_remedy(): + """The served guide's §Scoping pins the ladder order and the absolute-`paths` + remedy — the client-visible behaviour change of this leaf (maintainer-policy).""" + import importlib.resources + + guide = importlib.resources.files("colgrep_mcp").joinpath("guide.md").read_text() + assert "## Scoping" in guide + assert "explicit paths" in guide and "_meta" in guide and "client roots" in guide + assert "COLGREP_MCP_ROOT" in guide + assert "ROOT_UNRESOLVED" in guide + assert "absolute `paths` entry" in guide + + +# --------------------------------------------------------------------------- +# Close-out — verifier findings (F1–F4), each pinned fail-first +# --------------------------------------------------------------------------- + + +async def test_named_remedy_is_itself_a_working_escape(tmp_path, monkeypatch): + """Following the ROOT_UNRESOLVED remedy literally must work (verifier F1): + with the ladder silent, an explicit absolute `paths` entry naming an + existing directory scopes the call on its own — never re-raises the same + error the entry is the remedy for. The absolute entry is the user + speaking; no inferred default root is needed to honor it.""" + from colgrep_mcp.paths import resolve_target_paths + + not_a_project = tmp_path / "not-a-project" + not_a_project.mkdir() + monkeypatch.chdir(not_a_project) # every ladder rung silent + + ctx = _meta_ctx(None) + resolved = await resolve_target_paths(ctx, [str(not_a_project)]) + assert resolved == [not_a_project.resolve()] + + +async def test_pathless_file_uri_root_never_scopes_the_filesystem(tmp_path, monkeypatch): + """A client root that names no directory must not become the filesystem + root (verifier F2): a path-less `file:` URI normalizes to path `'/'`, and + `'/'` scopes a path-less call to the entire disk — the silent wrong root + this campaign exists to prevent. Such a root is unusable: it degrades to + the zero-root class and the ladder falls through to its guided failure.""" + from mcp.server.mcpserver.exceptions import ToolError + + from colgrep_mcp.errors import Code + from colgrep_mcp.paths import resolve_target_paths + + monkeypatch.chdir(tmp_path) # not a plausible project root + + async def pathless_roots(): + return ListRootsResult(roots=[Root(uri="file:")]) + + ctx = _meta_ctx(None) + ctx.session.list_roots = pathless_roots + + with pytest.raises(ToolError) as excinfo: + await resolve_target_paths(ctx, None) + assert Code.ROOT_UNRESOLVED in str(excinfo.value) + + +def test_classify_needs_usable_items_for_declared(): + """`declared` means the client returned usable root items (verifier F3): + an empty list is never `declared`, or the ledger certifies roots the + client never sent.""" + from colgrep_mcp.probe import _classify_roots + + assert _classify_roots(None, [], False) == "empty" + assert _classify_roots(None, [], True) == "error" + assert _classify_roots(None, [Path("/ws")], False) == "declared" + + +async def test_concurrent_first_calls_both_reassure_before_settling(tmp_path, monkeypatch): + """A pair of concurrent path-less first calls must both settle on the late + arriving root (verifier F4): the reassurance budget belongs to the + freshly-connected *state*, not to one winner of the first lock. With the + budget spent by one caller, the other's premature emptiness conclusion + lands on a wrong project cwd — the silent wrong root this campaign + exists to prevent.""" + import asyncio + + from colgrep_mcp import paths as paths_module + from colgrep_mcp.paths import resolve_target_paths + + project = tmp_path / "corpus" + project.mkdir() + bogus = tmp_path / "looks-like-project" + bogus.mkdir() + (bogus / "pyproject.toml").touch() + monkeypatch.chdir(bogus) # a premature fallback lands on the WRONG project + + class Flaky: + """Answers provisional-empty until the harness root lands (R03b).""" + + def __init__(self, ready_after: int): + self.n = 0 + self.ready_after = ready_after + + async def list_roots(self): + self.n += 1 + resp = [] if self.n <= self.ready_after else [Root(uri=project.as_uri())] + await asyncio.sleep(0) + return ListRootsResult(roots=resp) + + session = Flaky(ready_after=2) + ctx_a, ctx_b = _meta_ctx(None), _meta_ctx(None) + ctx_a.session.list_roots = session.list_roots + ctx_b.session.list_roots = session.list_roots + + paths_module._FIRST_EMPTY_REASSURE = True + try: + ra, rb = await asyncio.gather( + resolve_target_paths(ctx_a, None), + resolve_target_paths(ctx_b, None), + ) + finally: + paths_module._FIRST_EMPTY_REASSURE = True + + assert ra == [project.resolve()], f"caller A resolved {ra} — lost the late root to a premature fallback" + assert rb == [project.resolve()], f"caller B resolved {rb} — lost the late root to a premature fallback" diff --git a/server/tests/test_probe.py b/server/tests/test_probe.py new file mode 100644 index 0000000..9a51aff --- /dev/null +++ b/server/tests/test_probe.py @@ -0,0 +1,478 @@ +"""Unit and regression tests for the dump-only probe facility (R01). + +Tests: +- test_capture_pure_roundtrips: capture_pure serialises with sorted keys. +- test_probe_inert_without_env: nothing changes when COLGREP_MCP_PROBE unset. +- test_record_writes_jsonl: R01 keys present in record output. +- test_capture_matches_runtime: probe record resolved matches runtime call. +- test_tool_column_names_the_actual_tool: the ledger names the calling tool, + never "record" (lever 1 repair). +- test_roots_error_distinct_from_empty: a failed round-trip is "error", a + genuine zero-root answer is "empty" (lever 6 / gap defect 6). +- test_probe_record_survives_unresolvable_ladder: the probe hook records an + unresolved outcome instead of raising when the ladder declines a root. +- test_probe_record_reports_meta_source: a meta-sourced resolution is + recorded as "meta" (lead integration: probe re-derivation must agree with + the runtime ladder). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest + +from colgrep_mcp.config import Settings +from colgrep_mcp.probe import PROBE_ENV, _classify_roots, capture_pure, diff_record, forge_record, record + +pytestmark = pytest.mark.anyio + + +def _none_safe(obj): + """Recursively replace MagicMock with None for JSON serialisation.""" + if obj is None: + return None + if isinstance(obj, MagicMock): + return None + if hasattr(obj, "model_dump"): + try: + dumped = obj.model_dump() + except Exception: + return None + if isinstance(dumped, dict): + return {k: _none_safe(v) for k, v in dumped.items()} + return _none_safe(dumped) + if isinstance(obj, dict): + return {k: _none_safe(v) for k, v in obj.items()} + if isinstance(obj, list): + return [_none_safe(v) for v in obj] + return obj + + +def _simple_ctx() -> SimpleNamespace: + return SimpleNamespace( + request_context=SimpleNamespace( + initialize=None, + meta=None, + session=SimpleNamespace(), + ) + ) + + +# --------------------------------------------------------------------------- +# capture_pure round-trip (sorted keys, deterministic) +# --------------------------------------------------------------------------- + + +def test_capture_pure_roundtrips(_=None): + """capture_pure serialises with sorted keys; round-tripping returns bytes + identical to a second serialization of the same dict.""" + snap = {"z": [1], "a": {"b": 2}} + line1 = capture_pure(snap) + snap2 = json.loads(line1) + line2 = capture_pure(snap2) + assert line1 == line2 + keys_in_order = [k for k in json.loads(line1).keys()] + assert keys_in_order == sorted(keys_in_order) + + +# --------------------------------------------------------------------------- +# Probe is inert when COLGREP_MCP_PROBE is unset +# --------------------------------------------------------------------------- + + +def test_probe_inert_without_env(tmp_path, monkeypatch): + """Without COLGREP_MCP_PROBE the probe never writes or touches the fs.""" + import os + + monkeypatch.delenv("COLGREP_MCP_PROBE", raising=False) + assert os.environ.get("COLGREP_MCP_PROBE") is None + + record( + ctx=_simple_ctx(), + raw_paths=["/some/path"], + settings_root=tmp_path, + roots=None, + resolved_root=tmp_path, + resolved_source="env", + ) + + # With env unset, no probe file should be created anywhere. + assert not tmp_path.joinpath("probe.jsonl").exists() + assert not Path.home().joinpath("colgrep_probe.jsonl").exists() + + +# --------------------------------------------------------------------------- +# Record writes JSONL with R01 keys when env is set +# --------------------------------------------------------------------------- + + +def test_record_writes_jsonl(tmp_path, monkeypatch): + """record() appends one JSONL line when COLGREP_MCP_PROBE is set.""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + + record( + ctx=_simple_ctx(), + raw_paths=["/some/path"], + settings_root=tmp_path, + roots=None, + resolved_root=tmp_path, + resolved_source="env", + ) + + ledger = probe_dir / "colgrep_probe.jsonl" + assert ledger.exists() + line = ledger.read_text().strip() + snap = json.loads(line) + for key in ( + "ts", + "server_pid", + "tool", + "raw_paths", + "env", + "init_capabilities", + "request_meta", + "roots_list", + "resolved", + "cwd", + ): + assert key in snap, f"missing key: {key}" + assert snap["raw_paths"] == ["/some/path"] + assert snap["resolved"]["source"] == "env" + + +# --------------------------------------------------------------------------- +# test_capture_matches_runtime +# --------------------------------------------------------------------------- + + +async def test_capture_matches_runtime(tmp_path, monkeypatch): + """The probe record's resolved output matches what resolve_target_paths + returns on that call.""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + monkeypatch.setenv("COLGREP_MCP_ROOT", str(tmp_path)) + + # Build a mock ctx that satisfies get_settings → ctx.request_context. + # get_settings does ctx.request_context.lifespan_context → app.settings. + mock_settings = Settings(root=tmp_path) + mock_lifespan = SimpleNamespace(settings=mock_settings) + mock_request_ctx = SimpleNamespace( + lifespan_context=mock_lifespan, + session=SimpleNamespace(), + ) + ctx = SimpleNamespace(request_context=mock_request_ctx) + + from colgrep_mcp.paths import resolve_target_paths + + result = await resolve_target_paths(ctx, None) + + ledger = probe_dir / "colgrep_probe.jsonl" + assert ledger.exists() + line = ledger.read_text().strip() + snap = json.loads(line) + + recorded_root = Path(snap["resolved"]["root"]) + assert recorded_root == result[0] + + +# --------------------------------------------------------------------------- +# test_probe_inert_without_env_full +# --------------------------------------------------------------------------- + + +async def test_probe_inert_without_env_full(tmp_path, monkeypatch): + """With COLGREP_MCP_ROOT set and COLGREP_MCP_PROBE unset, the resolution + path produces a correct answer (probe is a no-op gate).""" + monkeypatch.delenv("COLGREP_MCP_PROBE", raising=False) + monkeypatch.setenv("COLGREP_MCP_ROOT", str(tmp_path)) + + settings = Settings(root=tmp_path) + from colgrep_mcp.paths import resolve_paths + + result = resolve_paths(None, settings, None) + + assert result == [tmp_path.resolve()] + + +# --------------------------------------------------------------------------- +# test_tool_column_names_the_actual_tool (lever 1 repair) +# --------------------------------------------------------------------------- + + +async def test_tool_column_names_the_actual_tool(tmp_path, monkeypatch): + """The record's ``tool`` column names the actual calling tool, never + ``"record"``. Regression: the original frame scan resolved to ``record`` + itself every time, silently falsifying the matrix column.""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + monkeypatch.setenv("COLGREP_MCP_ROOT", str(tmp_path)) + + mock_settings = Settings(root=tmp_path) + mock_lifespan = SimpleNamespace(settings=mock_settings) + mock_request_ctx = SimpleNamespace( + lifespan_context=mock_lifespan, + session=SimpleNamespace(), + ) + ctx = SimpleNamespace(request_context=mock_request_ctx) + + from colgrep_mcp.paths import resolve_target_paths + + # Wire the resolution path through a helper whose name stands for the + # "calling tool" the way a real tool handler would. + async def _fake_tool_handler(ctx_: object) -> object: + return await resolve_target_paths(ctx_, None) # type: ignore[arg-type] + + await _fake_tool_handler(ctx) + + ledger = probe_dir / "colgrep_probe.jsonl" + assert ledger.exists() + snap = json.loads(ledger.read_text().strip()) + assert snap["tool"] == "_fake_tool_handler", "tool column should name the calling tool, not 'record'" + assert snap["tool"] != "record" + + +# --------------------------------------------------------------------------- +# test_record_never_raises_on_hostile_snapshot (lever 2b kill) +# --------------------------------------------------------------------------- + + +class _ExplodingStr: + """An object whose ``str()`` raises — the worst case for serialisation.""" + + def __str__(self) -> str: # pragma: no cover - never reached, must raise + raise RuntimeError("cannot stringify") + + +def test_record_never_raises_on_hostile_snapshot(tmp_path, monkeypatch): + """record() is total: a non-JSON-serializable snapshot value must never + raise. A coercible value becomes a coerced record (a witness); a value + whose str() itself fails is swallowed. Both leave the caller untouched.""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + + # 1. Coercible but non-serializable: coerced to a string witness. + class _Coercible: + def model_dump(self): + return {"answer": 42} + + def __str__(self) -> str: + return "coerced-witness" + + ctx = SimpleNamespace( + request_context=SimpleNamespace( + initialize=None, + meta=_Coercible(), + session=SimpleNamespace(), + ) + ) + # Must not raise. + record(ctx=ctx, raw_paths=None, settings_root=None, roots=None, resolved_root=tmp_path, resolved_source="env") + ledger = probe_dir / "colgrep_probe.jsonl" + assert ledger.exists() + snap = json.loads(ledger.read_text().strip().splitlines()[0]) + # request_meta came from model_dump of the _Coercible object. + assert snap["request_meta"] == {"answer": 42} + + # 2. A value whose str() raises must be swallowed, never raised. + hostile_ctx = SimpleNamespace( + request_context=SimpleNamespace( + initialize=_ExplodingStr(), + meta=None, + session=SimpleNamespace(), + ) + ) + record( + ctx=hostile_ctx, raw_paths=None, settings_root=None, roots=None, resolved_root=tmp_path, resolved_source="env" + ) # must not raise + + +# --------------------------------------------------------------------------- +# test_tool_call_survives_probe_rename (lever 2b, end-to-end) +# --------------------------------------------------------------------------- + + +async def test_tool_call_survives_probe_rename(tmp_path, monkeypatch): + """A real tool call through resolve_target_paths survives even when the + probe encounters a hostile snapshot value. Regression: the original + capture_pure sat outside the never-raise boundary, so a TypeError from + serialising a hostile value propagated up through the resolve path and + broke the very tool call the docstring promises never to break.""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + monkeypatch.setenv("COLGREP_MCP_ROOT", str(tmp_path)) + + # A request_ctx whose _meta carries a value with no JSON encoding and a + # str() that raises — the worst non-serializable case. + mock_settings = Settings(root=tmp_path) + mock_lifespan = SimpleNamespace(settings=mock_settings) + mock_request_ctx = SimpleNamespace( + lifespan_context=mock_lifespan, + meta=_ExplodingStr(), + session=SimpleNamespace(), + ) + ctx = SimpleNamespace(request_context=mock_request_ctx) + + from colgrep_mcp.paths import resolve_target_paths + + # The tool call must complete with the correct resolved path, not raise. + result = await resolve_target_paths(ctx, None) + assert result == [tmp_path.resolve()] + + +# --------------------------------------------------------------------------- +# test_roots_error_distinct_from_empty (lever 6 / gap defect 6) +# --------------------------------------------------------------------------- +def test_roots_error_distinct_from_empty(tmp_path): + """A failed round-trip classifies as ``error``; a genuine zero-root answer + classifies as ``empty``; a present pin or returned roots classify as + ``declared`` (never merged into one value).""" + # declared: COLGREP_MCP_ROOT pin present, roots consulted or not. + assert _classify_roots(settings_root=tmp_path, roots=None, roots_error=False) == "declared" + # declared: client_roots returned items. + assert _classify_roots(settings_root=None, roots=[tmp_path], roots_error=False) == "declared" + # error: the round-trip raised / back-channel absent. + assert _classify_roots(settings_root=None, roots=None, roots_error=True) == "error" + # empty: a client genuinely answered with zero roots. + assert _classify_roots(settings_root=None, roots=None, roots_error=False) == "empty" + + +# --------------------------------------------------------------------------- +# test_calibration_whistles_on_fabrication (calibration oracle) +# --------------------------------------------------------------------------- + + +def test_calibration_whistles_on_fabrication(): + """diff_record must be silent on a truthful record and whistle on a + fabricated one — e.g. a stub-authoring a `init_capabilities` the harness + never sent (lever 1b / gap defect 1). The stub's canonical fabrication + (FORGED_SAMPLE) must be caught verbatim.""" + from colgrep_mcp.probe import FORGED_SAMPLE + + var = "init_capabilities" + true_record = forge_record(**{var: {"protocolVersion": "2026-07-28"}}, request_meta={"workspace": "/x"}) + # A truthful record diffs empty. + assert diff_record(true_record, true_record) == [] + + # A fabricated record — the stub's hardcode-lie — must whistle. + fabricated = dict(true_record) + fabricated[var] = {"protocolVersion": "NONE"} # stub wrote this, never the harness + gaps = diff_record(true_record, fabricated) + assert gaps, "diff_record must whistle on a fabricated record" + assert any(var in g for g in gaps), f"fabrication must be named, got {gaps}" + + # The stub's exact fabrication is a fabricated init_capabilities too. + forged_gaps = diff_record(forge_record(**{var: {"protocolVersion": "2026-07-28"}}), FORGED_SAMPLE) + assert forged_gaps, "diff_record must whistle on FORGED_SAMPLE verbatim" + + +# --------------------------------------------------------------------------- +# test_no_probe_side_effects (rewritten: reads the real ledger) +# --------------------------------------------------------------------------- + + +def test_no_probe_side_effects(tmp_path, monkeypatch): + """Regression against the real ledger `colgrep_probe.jsonl` (the old test + asserted dead filenames and re-read only the env, so it could never see a + fabricated record — lever 3). A truthful probe writes a record that + matches forge_record ground truth on every signal column and names the + calling tool, never "record".""" + probe_dir = tmp_path / "probe" + monkeypatch.setenv("COLGREP_MCP_PROBE", str(probe_dir)) + + record( + ctx=_simple_ctx(), + raw_paths=["/some/path"], + settings_root=tmp_path, + roots=None, + resolved_root=tmp_path.resolve(), + resolved_source="env", + ) + + ledger = probe_dir / "colgrep_probe.jsonl" + assert ledger.exists(), "the real ledger colgrep_probe.jsonl must have been written" + actual = json.loads(ledger.read_text().strip()) + + # The tool column must never be the fabricated "record". + assert actual["tool"] != "record", "probe fabricated the tool column as 'record'" + + expected = forge_record( + tool="test_no_probe_side_effects", + raw_paths=["/some/path"], + roots_list={"static": "declared", "items": []}, + resolved={"root": str(tmp_path.resolve()), "source": "env"}, + ) + signal_cols = ("tool", "raw_paths", "init_capabilities", "request_meta", "roots_list", "resolved") + gaps = diff_record({k: expected[k] for k in signal_cols}, {k: actual[k] for k in signal_cols}) + assert not gaps, f"probe record diverges from ground truth: {gaps}" + + +# --------------------------------------------------------------------------- +# Gap-record tolerance and stub provenance (driver hygiene, lever 5 / defect 5) +# --------------------------------------------------------------------------- + + +def test_gap_records_validate_as_gaps(tmp_path): + """A validator call with a gap row ({"error": ...}) must return a named + gap verdict, never raise on snap['ts'] (lever 5 / gap defect 5).""" + from e2e import probe_workspace as driver + + verdict = driver._validate_record('{"error": "harness not found: claude"}') + assert verdict == "gap" + assert driver._validate_record("not json at all") != "valid" + assert driver._validate_record("{}") != "valid" + + # A file whose only row is a gap validates as OK (gaps report, not crash). + gap_file = tmp_path / "ledger.jsonl" + gap_file.write_text('{"error": "completed but no probe record written"}\n', encoding="utf-8") + assert driver.validate(gap_file) is True + + +def test_stub_records_carry_provenance(): + """Every stub-written record is stamped provenance: "stub" so a ledger + reader can separate stub synthesis from server-written rows (lever 1b).""" + from e2e import probe_workspace as driver + + assert '"provenance": "stub"' in driver._STUB_SCRIPT + + +# --------------------------------------------------------------------------- +# Probe hook and the resolution ladder agree (lead tier-2 integration) +# --------------------------------------------------------------------------- + + +def test_probe_record_survives_unresolvable_ladder(tmp_path, monkeypatch): + """When every ladder rung is silent and cwd is not a project root, the + probe hook must record the unresolved outcome — never raise past the + resolve call site (the ladder's ROOT_UNRESOLVED belongs to the caller, + not to the dump-only probe).""" + from colgrep_mcp.probe import _probe_record + + monkeypatch.setenv(PROBE_ENV, str(tmp_path / "probe")) + monkeypatch.chdir(tmp_path) # no project markers => guarded-cwd declines + + _probe_record(None, None, Settings(), None) # must not raise + + ledger = [json.loads(line) for line in (tmp_path / "probe" / "colgrep_probe.jsonl").read_text().splitlines()] + assert len(ledger) == 1 + assert ledger[0]["resolved"] == {"root": None, "source": "unresolved"} + + +def test_probe_record_reports_meta_source(tmp_path, monkeypatch): + """A meta-sourced resolution is recorded as source "meta": the probe's + re-derivation must thread meta_root through the same ladder the runtime + used, or the ledger contradicts the call it measures.""" + from colgrep_mcp.probe import _probe_record + + monkeypatch.setenv(PROBE_ENV, str(tmp_path / "probe")) + meta_root = tmp_path / "ws" / "proj" + meta_root.mkdir(parents=True) + + _probe_record(None, None, Settings(), None, meta_root=meta_root) + + ledger = [json.loads(line) for line in (tmp_path / "probe" / "colgrep_probe.jsonl").read_text().splitlines()] + assert ledger[0]["resolved"] == {"root": str(meta_root.resolve()), "source": "meta"}