@flyingrobots/graft 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +218 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +4 -0
  4. package/README.md +119 -0
  5. package/bin/graft.js +11 -0
  6. package/docs/GUIDE.md +374 -0
  7. package/package.json +76 -0
  8. package/src/adapters/canonical-json.ts +56 -0
  9. package/src/adapters/node-fs.ts +39 -0
  10. package/src/git/diff.ts +96 -0
  11. package/src/guards/stream-boundary.ts +110 -0
  12. package/src/hooks/posttooluse-read.ts +107 -0
  13. package/src/hooks/pretooluse-read.ts +88 -0
  14. package/src/hooks/shared.ts +168 -0
  15. package/src/mcp/cache.ts +94 -0
  16. package/src/mcp/cached-file.ts +38 -0
  17. package/src/mcp/context.ts +52 -0
  18. package/src/mcp/metrics.ts +53 -0
  19. package/src/mcp/receipt.ts +83 -0
  20. package/src/mcp/server.ts +166 -0
  21. package/src/mcp/stdio.ts +6 -0
  22. package/src/mcp/tools/budget.ts +20 -0
  23. package/src/mcp/tools/changed-since.ts +68 -0
  24. package/src/mcp/tools/doctor.ts +20 -0
  25. package/src/mcp/tools/explain.ts +80 -0
  26. package/src/mcp/tools/file-outline.ts +57 -0
  27. package/src/mcp/tools/graft-diff.ts +24 -0
  28. package/src/mcp/tools/read-range.ts +21 -0
  29. package/src/mcp/tools/run-capture.ts +67 -0
  30. package/src/mcp/tools/safe-read.ts +135 -0
  31. package/src/mcp/tools/state.ts +30 -0
  32. package/src/mcp/tools/stats.ts +20 -0
  33. package/src/metrics/logger.ts +69 -0
  34. package/src/metrics/types.ts +12 -0
  35. package/src/operations/file-outline.ts +38 -0
  36. package/src/operations/graft-diff.ts +117 -0
  37. package/src/operations/read-range.ts +65 -0
  38. package/src/operations/safe-read.ts +96 -0
  39. package/src/operations/state.ts +33 -0
  40. package/src/parser/diff.ts +142 -0
  41. package/src/parser/lang.ts +12 -0
  42. package/src/parser/outline.ts +327 -0
  43. package/src/parser/types.ts +67 -0
  44. package/src/policy/evaluate.ts +178 -0
  45. package/src/policy/graftignore.ts +6 -0
  46. package/src/policy/types.ts +86 -0
  47. package/src/ports/codec.ts +13 -0
  48. package/src/ports/filesystem.ts +17 -0
  49. package/src/session/tracker.ts +114 -0
  50. package/src/session/types.ts +20 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,218 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/).
7
+
8
+ ## [0.3.1] - 2026-04-05
9
+
10
+ ### Changed
11
+
12
+ - **CI**: release workflow now publishes to npm via OIDC provenance.
13
+ - **Docs**: regenerated README, GUIDE, BEARING, and VISION signposts
14
+ to reflect v0.3.0 features (12 tools, budget governor, reason codes).
15
+
16
+ ## [0.3.0] - 2026-04-05
17
+
18
+ ### Added
19
+
20
+ - **Budget-aware governor**: `set_budget(bytes)` declares a session
21
+ byte budget. Thresholds tighten as budget drains — no single read
22
+ may consume more than 5% of remaining budget. New `BUDGET_CAP`
23
+ reason code. Budget info in receipts.
24
+ - **Explain tool**: `explain(code)` returns human-readable meaning and
25
+ recommended action for any reason code.
26
+ - **Policy check middleware**: tools with `policyCheck: true` get
27
+ automatic `evaluatePolicy` before the handler runs. Applied to
28
+ `read_range`.
29
+ - **CachedFile value object**: immutable file snapshot bundles content,
30
+ hash, outline, jump table, and actual metrics from a single read.
31
+ Eliminates TOCTOU snapshot races by construction.
32
+ - **guardedPort() factory**: Proxy-based stream boundary guard wraps
33
+ all methods on a port interface. One line to guard a whole port.
34
+ - **Receipt compression ratio**: `compressionRatio` field in receipts
35
+ (returnedBytes / fileBytes). Instant context efficiency signal.
36
+ - **Diff summary lines**: each file in `graft_diff` output includes a
37
+ one-line structural stat for quick triage.
38
+
39
+ ### Fixed
40
+
41
+ - **Strict MCP argument validation**: Zod schemas now reject unknown
42
+ keys at the MCP edge instead of silently stripping them.
43
+ - **run_capture log-write isolation**: filesystem failures when
44
+ persisting capture logs no longer mask successful command output.
45
+ - **Cache-hit policy re-check**: `safe_read` now re-evaluates policy
46
+ on cache hits, preventing stale cached data from bypassing refusals.
47
+
48
+ ## [0.2.2] - 2026-04-04
49
+
50
+ ### Added
51
+
52
+ - **Docker support**: run graft as an MCP server without installing
53
+ Node. `docker run -i --rm -v "$PWD:/workspace" flyingrobots/graft`.
54
+ Node 22 Alpine, non-root user.
55
+ - **Canonical JSON codec**: all JSON serialization uses deterministic
56
+ sorted keys and compact output via `CanonicalJsonCodec`. Enables
57
+ stable hashes and diffable logs. `JsonCodec` port for hexagonal
58
+ compliance.
59
+
60
+ ### Fixed
61
+
62
+ - **JSON serialization safety**: codec preserves `Date` and custom
63
+ `toJSON` semantics, detects circular references, handles shared
64
+ object references without false cycle detection.
65
+
66
+ ## [0.2.1] - 2026-04-04
67
+
68
+ ### Added
69
+
70
+ - **Value objects** (cycle 0016): OutlineEntry, JumpEntry, DiffEntry,
71
+ OutlineDiff, and Tripwire converted from plain interfaces to frozen
72
+ SSJS classes with constructor validation and private `_brand` fields.
73
+ Completes SSJS P1 migration for all domain types.
74
+ - **PostToolUse hook for Read**: educates agents on context cost after
75
+ large file reads, showing what safe_read would have returned and the
76
+ savings in KB.
77
+ - **Shared hook utilities** (`src/hooks/shared.ts`): validated input
78
+ parsing, stdin reader with 1 MB size guard, safe relative path
79
+ resolution, and `runHook` harness with full stack trace logging.
80
+ - **18 project invariants** documented in `docs/invariants/`.
81
+
82
+ ### Fixed
83
+
84
+ - **Trim-and-validate**: value object constructors trim names before
85
+ validation, preventing whitespace-only strings from passing as valid.
86
+ - **Input validation**: hooks now validate JSON structure at runtime
87
+ instead of using unsafe `as` type assertions.
88
+ - **Path traversal guard**: hooks reject file paths outside the project
89
+ `cwd` (passes through to native Read instead of evaluating policy on
90
+ arbitrary paths).
91
+ - **UTF-8 safety**: stdin reader accumulates raw buffers before decoding
92
+ to prevent multi-byte character corruption at chunk boundaries.
93
+ - **Stack traces**: hook error handler logs `err.stack` instead of
94
+ `err.message` for debuggability.
95
+ - **Node engine**: bump minimum to `>=20.11.0` for `import.meta.dirname`
96
+ support (used across test suite and eslint config).
97
+
98
+ ## [0.2.0] - 2026-04-03
99
+
100
+ ### Changed
101
+
102
+ - **Server decomposition** (cycle 0010): split 541-line MCP server
103
+ god file into focused modules. `server.ts` is now 110 lines of pure
104
+ registration and plumbing. New modules:
105
+ - `metrics.ts` — `Metrics` class replaces 6 loose counters
106
+ - `cache.ts` — `Observation` class + `ObservationCache` with
107
+ `isStale()`, `touch()`, `record()`, `check()`, `get()`
108
+ - `receipt.ts` — `buildReceiptResult()` with stabilization loop
109
+ - `context.ts` — `ToolContext` interface + `ToolHandler` type
110
+ - `tools/*.ts` — 9 files, one per tool handler (state.ts has both
111
+ save + load)
112
+ - **FileSystem port** (cycle 0011): hexagonal compliance — core logic
113
+ no longer imports `node:fs` directly. New `FileSystem` interface in
114
+ `src/ports/filesystem.ts` with Node adapter in `src/adapters/node-fs.ts`.
115
+ All operations and metrics use the port; testable with mock filesystems.
116
+ - **Outline quality audit** (cycle 0012): 7 real-world fixture files,
117
+ 40 test assertions proving outline extraction works on React
118
+ components, Express routers, barrel files, god classes, dense
119
+ generics, and decorated classes.
120
+
121
+ ### Added
122
+
123
+ - **Arrow function export extraction**: `export const fn = () => {}`
124
+ now gets `kind: "function"` with parameter/return type signature
125
+ instead of generic `kind: "export"`.
126
+ - **Enum extraction**: `enum` declarations appear in outlines with
127
+ `kind: "enum"`.
128
+ - **Re-export extraction**: named, type, and wildcard re-exports
129
+ now appear in outlines. Barrel files are no longer invisible.
130
+ - **Claude Code hooks** (cycle 0015): PreToolUse hook blocks banned
131
+ files (secrets, binaries, lockfiles, `.graftignore` matches).
132
+ PostToolUse hook educates agents on context cost after large file
133
+ reads, suggesting `safe_read` as an alternative.
134
+
135
+ ### Fixed
136
+
137
+ - **Byte metrics**: receipt builder now uses `Buffer.byteLength()`
138
+ instead of `text.length` for returnedBytes and cumulative byte
139
+ accounting. Was counting UTF-16 code units as bytes.
140
+ - **Path traversal guard**: all path-accepting tools now use
141
+ `ctx.resolvePath()` which rejects relative paths that escape the
142
+ project root via `..` segments.
143
+ - **Doctor thresholds drift**: doctor tool now imports
144
+ `STATIC_THRESHOLDS` from policy instead of hardcoding values.
145
+ - **run_capture tail validation**: clamp tail to minimum 1 to prevent
146
+ zero/negative values from producing undefined behavior.
147
+ - **safe_read result.actual guard**: check `result.actual !== undefined`
148
+ before using it for cache recording (actual is optional on error
149
+ projections).
150
+
151
+ ## [0.1.0] - 2026-04-03
152
+
153
+ ### Added
154
+
155
+ - **Policy engine**: dual thresholds (150 lines + 12 KB), 5 ban
156
+ categories (binary, lockfile, minified, build output, secret),
157
+ `.graftignore` support, session-depth dynamic caps (20/10/4 KB).
158
+ - **Parser**: tree-sitter WASM outline extraction for JS/TS with
159
+ jump tables, signature bounding, and broken-file recovery.
160
+ - **Session tracker**: 4 tripwires (SESSION_LONG, EDIT_BASH_LOOP,
161
+ RUNAWAY_TOOLS, LATE_LARGE_READ) with session depth reporting.
162
+ - **Metrics logger**: NDJSON decision logging with retention/rotation.
163
+ - **Operations**: safe_read, file_outline, read_range, state_save/load.
164
+ - **MCP server**: all 8 Phase 1 commands as MCP tools over stdio,
165
+ session tracking (tripwires + dynamic caps automatic), doctor and
166
+ stats tools. Entry point at `src/mcp/stdio.ts`.
167
+ - **Re-read suppression**: session-level observation cache — second
168
+ read of an unchanged file returns cached outline instead of
169
+ re-reading. Tracks readCount, estimatedBytesAvoided, lastReadAt.
170
+ Works for both safe_read and file_outline. Stats includes
171
+ totalCacheHits and totalBytesAvoidedByCache.
172
+ - **Receipt mode**: every MCP response includes a `_receipt` block
173
+ with sessionId, monotonic seq, projection, reason, fileBytes,
174
+ returnedBytes, and cumulative counters (reads, outlines, refusals,
175
+ cacheHits, bytesReturned, bytesAvoided). Blacklight can grep API
176
+ transcripts to prove graft works.
177
+ - **Changed-since-last-read**: when a file changes between reads,
178
+ graft returns a structural diff (added/removed/changed symbols)
179
+ alongside the new outline. New `changed_since` MCP tool for
180
+ explicit delta queries without triggering a full safe_read.
181
+ - Now 16 machine-stable reason codes — added `REREAD_UNCHANGED`
182
+ (cycle 0003) and `CHANGED_SINCE_LAST_READ` (cycle 0005).
183
+ - **Structural git diff** (`graft_diff`): symbol-level diff between
184
+ any two git refs. Uses `git rev-parse --verify` + `git cat-file -e`
185
+ for stable ref/object detection.
186
+ - **run_capture implemented**: tee shell output to log file, return
187
+ last N lines. Full output at `.graft/logs/capture.log`.
188
+ - **MCP tool descriptions**: all 10 tools have agent-facing
189
+ descriptions in their schema for discovery via `listTools`.
190
+ - **bin/graft.js**: CLI entry point for `npx @flyingrobots/graft`.
191
+ - 16 machine-stable reason codes.
192
+ - 227 tests across 20 test files.
193
+ - 7 cycles completed, 3 legends (CORE, WARP, CLEAN_CODE).
194
+
195
+ ### Fixed
196
+
197
+ - **Diff path policy check**: both `safe_read` and `changed_since`
198
+ now run `evaluatePolicy` before returning structural data,
199
+ preventing leaks if policy rules change after initial observation.
200
+ Note: `safe_read` always evaluates policy; `changed_since` was
201
+ added in this release and now also evaluates policy.
202
+ - **Nested symbol diff**: classes/interfaces now recursively diff
203
+ children. A method added inside a class shows as a changed class
204
+ with a childDiff detailing the nested change.
205
+ - **Snapshot race**: diff and changed_since paths now use
206
+ extractOutline with the already-read content instead of
207
+ re-reading the file via fileOutline.
208
+ - **Pre-push hook**: parses stdin for the remote ref being pushed to
209
+ instead of checking the local branch name.
210
+ - **oldSignature consistency**: DiffEntry.oldSignature now uses the
211
+ same entrySignature fallback (name when no signature) as the
212
+ comparison logic.
213
+ - **Stale lastReadAt**: diff responses now return the updated
214
+ timestamp from the observation cache instead of the old one.
215
+ - **Dead DiffEntry fields**: removed unused start/end from DiffEntry.
216
+ - Add `@types/node` and `@types/picomatch` (required by TypeScript 6).
217
+ - Fix session-depth table in design doc ("Messages Remaining" →
218
+ "Messages Elapsed").
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 James Ross
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Graft
2
+ Copyright 2026 James Ross
3
+
4
+ Licensed under the Apache License, Version 2.0.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ <div align="center">
2
+ <img src="./docs/assets/graft.svg" />
3
+ <h3>Context governor for coding agents</h3>
4
+ </div>
5
+
6
+ Graft enforces read policy so coding agents consume the smallest
7
+ structurally correct view of a codebase instead of dumping entire
8
+ files into their context window. Agent-first, but the structural
9
+ tools (outlines, diffs, symbol history) are useful to anyone.
10
+
11
+ ## Why
12
+
13
+ Empirical analysis of 1,091 real coding sessions (Blacklight) found
14
+ that **Read accounts for 96.2 GB of context burden** — 6.6x all
15
+ other tools combined. 58% of reads are full-file. The fattest 2.4%
16
+ of reads produce 24% of raw bytes. Dynamic read caps + session
17
+ management reduce this by **75.1%**.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install -g @flyingrobots/graft
23
+ ```
24
+
25
+ Or use directly:
26
+
27
+ ```bash
28
+ npx @flyingrobots/graft
29
+ ```
30
+
31
+ Or run in Docker (no Node required):
32
+
33
+ ```bash
34
+ docker run -i --rm -v "$PWD:/workspace" flyingrobots/graft
35
+ ```
36
+
37
+ ## Quick start
38
+
39
+ ```json
40
+ {
41
+ "mcpServers": {
42
+ "graft": {
43
+ "command": "npx",
44
+ "args": ["-y", "@flyingrobots/graft"]
45
+ }
46
+ }
47
+ }
48
+ ```
49
+
50
+ Add this to your MCP config — works with Claude Code, Cursor,
51
+ Windsurf, Continue, Cline, and any MCP-compatible client.
52
+
53
+ See **[Setup Guide](docs/GUIDE.md)** for per-editor instructions,
54
+ Claude Code hooks, `.graftignore` configuration, troubleshooting,
55
+ and details on what the agent experiences.
56
+
57
+ ## What it does
58
+
59
+ When an agent asks to read a file, Graft applies policy:
60
+
61
+ - **Small files** are returned as-is.
62
+ - **Large files** are returned as a structural outline with a jump
63
+ table so the agent can request specific ranges.
64
+ - **Banned files** (binaries, lockfiles, minified bundles, secrets)
65
+ are refused with a machine-readable reason code and suggested next
66
+ steps.
67
+ - **Re-reads** of unchanged files return a cached outline (no wasted
68
+ context). Changed files return a structural diff (added/removed/
69
+ changed symbols).
70
+ - **Ranges** are bounded — no stealth `cat` of a 10,000-line file.
71
+ - **Session depth** tightens caps as the context window fills.
72
+ - **Budget governor** — agent declares a byte budget, thresholds
73
+ tighten as it drains. No single read may consume more than 5% of
74
+ remaining budget.
75
+ - **Tripwires** signal when the session is going off the rails.
76
+ - **Receipts** on every response with compression ratio for usage
77
+ analysis.
78
+
79
+ Every decision is logged. Every refusal is explainable. All output
80
+ is structured JSON.
81
+
82
+ ## Tools
83
+
84
+ | Tool | Purpose |
85
+ |---|---|
86
+ | `safe_read` | Policy-enforced file read (content, outline, refusal, or diff) |
87
+ | `file_outline` | Structural skeleton with jump table |
88
+ | `read_range` | Bounded range read (max 250 lines), policy-gated |
89
+ | `graft_diff` | Structural diff between git refs with per-file summary lines |
90
+ | `changed_since` | Check if a file changed since last read (peek or consume) |
91
+ | `run_capture` | Shell output capture — tee to log, tail to agent |
92
+ | `state_save` | Save session working state (max 8 KB) |
93
+ | `state_load` | Restore session working state |
94
+ | `set_budget` | Declare session byte budget — governor tightens as it drains |
95
+ | `explain` | Human-readable help for any reason code |
96
+ | `doctor` | Runtime health check |
97
+ | `stats` | Decision metrics summary |
98
+
99
+ ## Reason codes
100
+
101
+ Every refusal or policy decision includes a machine-readable reason
102
+ code. Use `explain(code)` to get meaning and recommended action.
103
+
104
+ | Code | Meaning |
105
+ |------|---------|
106
+ | `CONTENT` | File within thresholds — full content returned |
107
+ | `OUTLINE` | File exceeds thresholds — structural outline returned |
108
+ | `SESSION_CAP` | Session-depth byte cap triggered |
109
+ | `BUDGET_CAP` | Budget-proportional cap triggered |
110
+ | `BINARY` | Binary file refused |
111
+ | `LOCKFILE` | Machine-generated lockfile refused |
112
+ | `MINIFIED` | Minified file refused |
113
+ | `BUILD_OUTPUT` | Build output directory refused |
114
+ | `SECRET` | Potential secrets file refused |
115
+ | `GRAFTIGNORE` | Matches .graftignore pattern |
116
+
117
+ ## License
118
+
119
+ Apache 2.0 — see [LICENSE](LICENSE).
package/bin/graft.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env -S node --import tsx
2
+
3
+ // Graft MCP server — stdio transport
4
+ // Usage: npx @flyingrobots/graft
5
+
6
+ import { createGraftServer } from "../src/mcp/server.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+
9
+ const graft = createGraftServer();
10
+ const transport = new StdioServerTransport();
11
+ await graft.getMcpServer().connect(transport);