Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "sourcegraph",
"description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.",
"version": "0.6.0",
"version": "0.7.0",
"author": {
"name": "context4ai"
},
Expand Down
2 changes: 2 additions & 0 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ A token acts as its owner: it reads what you can read, manages repositories you

`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours).

`sourcegraph read <repo> <path>` prints lines 1–200 by default; `--start N` alone reads 200 lines from line N, and `--start/--end` reads a range of up to 2000 lines per call. `--all` reads the whole file page by page at the commit of the first page, with continuous line numbers. It stops after 20000 lines and still exits 0: the command that continues is printed on stderr, and `--json` output keeps `HasMore: true` and `NextStartLine`.

Run `sourcegraph <command> --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations.

Repository settings use `key=value` (`sourcegraph repo set org/repo sync_interval_minutes=60 public_read=false`). Intervals under 30 minutes are for site administrators; others are raised to 30 minutes with a warning. `manual_updates=true` turns off automatic updates (scheduled checks); `tags=a,b` replaces the tags and `tags=` clears them.
Expand Down
2 changes: 1 addition & 1 deletion cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@c4a/sourcegraph",
"version": "0.6.0",
"version": "0.7.0",
"description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.",
"license": "MIT",
"type": "module",
Expand Down
46 changes: 43 additions & 3 deletions cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,52 @@ async function logout(ctx: Ctx) {

// ---------- read ----------
async function readFile(ctx: Ctx, repo: string, path: string, o: Opts) {
const r = await ctx.client.call('/v1/repo/read', { query: repoQ(repo), body: { Revision: o.rev || '', Path: path, StartLine: Number(o.start || 1), EndLine: Number(o.end || 200) } });
if (o.all) return readAll(ctx, repo, path, o);
const start = Number(o.start || 1);
const r = await ctx.client.call('/v1/repo/read', { query: repoQ(repo), body: { Revision: o.rev || '', Path: path, StartLine: start, EndLine: o.end !== undefined ? Number(o.end) : start + 199 } });
servedNote(r);
if (jsonOutput) return r;
return jsonOutput ? r : fileText(repo, r);
}
function fileText(repo: string, r: any): string {
const lines = String(r.Content || '').replace(/\n$/, '').split('\n');
return `# ${repo}@${String(r.Commit).slice(0, 12)} ${r.Path} lines ${r.ReturnedStartLine}-${r.ReturnedEndLine}${r.HasMore ? ` (more from ${r.NextStartLine})` : ''}\n` + lines.map((l, i) => `${String(r.ReturnedStartLine + i).padStart(5)} ${l}`).join('\n');
}
// shellWord quotes a value for a POSIX shell command line when needed.
function shellWord(v: string): string {
return /^[\w@%+=:,./-]+$/.test(v) ? v : `'${v.replace(/'/g, `'\\''`)}'`;
}
// readAll follows NextStartLine page by page, at most 2000 lines per request
// (older servers answer 500), pinned to the first page's commit, and stops
// after READ_ALL_LINES lines with the command that continues. Stopping there
// is not an error: the exit code stays 0 and HasMore remains true.
const READ_ALL_LINES = 20000;
async function readAll(ctx: Ctx, repo: string, path: string, o: Opts) {
if (o.end !== undefined) throw new Error('--all reads to the end of the file; use --start/--end without --all for a range');
const first = Number(o.start || 1);
let start = first, rev = o.rev || '', file: any;
for (;;) {
const end = Math.min(start + 1999, first + READ_ALL_LINES - 1);
const r = await ctx.client.call('/v1/repo/read', { query: repoQ(repo), body: { Revision: rev, Path: path, StartLine: start, EndLine: end } });
if (r.ReturnedStartLine == null ? r.HasMore : r.ReturnedStartLine !== start) throw new Error(`the server answered from line ${r.ReturnedStartLine ?? '(none)'} when asked for line ${start}`);
if (!file) { servedNote(r); file = r; rev = r.Commit; } else {
file.Content += r.Content || '';
if (r.ReturnedEndLine != null) file.ReturnedEndLine = r.ReturnedEndLine;
file.Truncated = r.Truncated;
}
file.HasMore = r.HasMore;
file.NextStartLine = r.NextStartLine;
if (!r.HasMore) break;
if (r.NextStartLine == null) throw new Error(`the server reported more content after line ${r.ReturnedEndLine ?? start} without NextStartLine`);
if (!(r.NextStartLine > start)) throw new Error(`the server did not advance: NextStartLine ${r.NextStartLine} for a page starting at line ${start}`);
if (r.ReturnedEndLine != null && r.NextStartLine !== r.ReturnedEndLine + 1) throw new Error(`the server skipped lines: NextStartLine ${r.NextStartLine} after a page ending at line ${r.ReturnedEndLine}`);
if (r.NextStartLine > first + READ_ALL_LINES - 1) {
if (!jsonOutput) console.error(`note: stopped after ${READ_ALL_LINES} lines; continue with: sourcegraph read --rev ${shellWord(rev)} --start ${r.NextStartLine} --all -- ${shellWord(repo)} ${shellWord(path)}`);
break;
}
start = r.NextStartLine;
}
return jsonOutput ? file : fileText(repo, file);
}

// ---------- repository registration ----------
async function repoAdd(ctx: Ctx, a: string[], o: Opts) {
Expand Down Expand Up @@ -338,7 +378,7 @@ const C: Record<string, Command> = {
for (const f of files) for (const m of f.LineMatches || []) out.push(`${f.FileName}:${m.LineNumber}: ${Buffer.from(m.Line || '', 'base64').toString('utf8').replace(/\n$/, '')}`);
return out.join('\n');
} },
read: { usage: 'read <repo> <path> [--rev REV] [--start N] [--end N]', summary: 'Read lines of a file', options: { rev: { type: 'string' }, start: { type: 'string' }, end: { type: 'string' } }, run: (ctx, a, o) => readFile(ctx, need(a[0], 'repo'), need(a[1], 'path'), o) },
read: { usage: 'read <repo> <path> [--rev REV] [--start N] [--end N]\n read <repo> <path> --all [--rev REV] [--start N]\n\n Without --end, reads 200 lines from --start (default 1); up to 2000 lines per call.\n --all reads to the end of the file at the first page\'s commit and stops after\n 20000 lines with exit code 0: stderr notes the command that continues, and\n --json output keeps HasMore/NextStartLine.', summary: 'Read lines of a file, or the whole file with --all', options: { rev: { type: 'string' }, start: { type: 'string' }, end: { type: 'string' }, all: { type: 'boolean' } }, run: (ctx, a, o) => readFile(ctx, need(a[0], 'repo'), need(a[1], 'path'), o) },
'read-many': { usage: 'read-many <repo> --rev REV <path[:start-end]>...', summary: 'Read several files or ranges at one commit', options: { rev: { type: 'string' } }, run: async (ctx, a, o) => {
const repo = need(a[0], 'repo'), out: unknown[] = [];
for (const spec of a.slice(1)) { const [path, range] = spec.split(':'); const [s, e] = (range || '1-200').split('-'); out.push(await readFile(ctx, repo, path, { ...o, start: s, end: e })); }
Expand Down
172 changes: 172 additions & 0 deletions cli/src/read-all.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

const SHA = 'a'.repeat(40);

// A read API over a file of `total` lines that pages at `page` lines, like
// older (500) and current (2000) servers; it records each request body.
async function fakeServer(total: number, page: number, tweak: (q: any, r: any, n: number) => void = () => {}) {
const requests: any[] = [];
const server = createServer((req, res) => {
let body = '';
req.on('data', c => { body += c; });
req.on('end', () => {
const q = JSON.parse(body);
requests.push(q);
const start = q.StartLine, last = Math.min(q.EndLine, start + page - 1, total);
const lines = [];
for (let n = start; n <= last; n++) lines.push(`line ${n}\n`);
const more = last < total;
const r = { Path: q.Path, Commit: SHA, Content: lines.join(''), ReturnedStartLine: start, ReturnedEndLine: last, HasMore: more, NextStartLine: more ? last + 1 : null, Truncated: more && last < q.EndLine };
tweak(q, r, requests.length);
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(r));
});
});
await new Promise<void>(r => server.listen(0, '127.0.0.1', r));
const port = (server.address() as any).port;
return { url: `http://127.0.0.1:${port}`, requests, close: () => server.close() };
}

function cli(url: string, ...args: string[]) {
const env = { ...process.env, XDG_CONFIG_HOME: mkdtempSync(join(tmpdir(), 'sg-cli-')) };
delete env.SOURCEGRAPH_API_TOKEN;
delete env.SOURCEGRAPH_URL;
// The server runs in this process, so the CLI must not block it.
return new Promise<{ status: number | null; stdout: string; stderr: string }>(resolve => {
const child = spawn(process.execPath, [fileURLToPath(new URL('main.ts', import.meta.url)), '--url', url, ...args], { env });
let stdout = '', stderr = '';
child.stdout.on('data', (d: Buffer) => { stdout += d; });
child.stderr.on('data', (d: Buffer) => { stderr += d; });
child.on('close', (status: number | null) => resolve({ status, stdout, stderr }));
});
}

for (const page of [500, 2000]) {
test(`read --all reads every line at one commit (${page}-line pages)`, async () => {
const s = await fakeServer(4321, page);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--all', '--rev', 'main');
assert.equal(r.status, 0, r.stderr);
const rows = r.stdout.trim().split('\n');
assert.match(rows[0], /lines 1-4321$/);
assert.equal(rows.length, 4322);
rows.slice(1).forEach((row, i) => assert.equal(row, `${String(i + 1).padStart(5)} line ${i + 1}`));
assert.equal(s.requests[0].Revision, 'main');
for (const q of s.requests.slice(1)) assert.equal(q.Revision, SHA);
for (const q of s.requests) assert.equal(q.EndLine, q.StartLine + 1999);
assert.equal(s.requests.length, Math.ceil(4321 / page));
} finally { s.close(); }
});
}

test('read --all stops at 20000 lines and says where to continue', async () => {
const s = await fakeServer(25000, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--all', '--start', '11');
assert.equal(r.status, 0, r.stderr);
assert.match(r.stdout.split('\n')[0], /lines 11-20010 \(more from 20011\)$/);
assert.ok(r.stderr.includes(`continue with: sourcegraph read --rev ${SHA} --start 20011 --all -- org/repo a.txt`), r.stderr);
assert.equal(s.requests.at(-1).EndLine, 20010);
} finally { s.close(); }
});

test('read --all with an exactly 20000-line file prints no stop note', async () => {
const s = await fakeServer(20000, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--all');
assert.equal(r.status, 0, r.stderr);
assert.match(r.stdout.split('\n')[0], /lines 1-20000$/);
assert.equal(r.stderr, '');
} finally { s.close(); }
});

test('read --all quotes the repository and path in the continue command', async () => {
const s = await fakeServer(25000, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', "dir/it's a.txt", '--all');
assert.equal(r.status, 0, r.stderr);
assert.ok(r.stderr.includes(`sourcegraph read --rev ${SHA} --start 20001 --all -- org/repo 'dir/it'\\''s a.txt'`), r.stderr);
// The printed command runs as is, also for a path starting with '-'.
const dash = await cli(s.url, 'read', '--all', '--', 'org/repo', '-x.txt');
assert.equal(dash.status, 0, dash.stderr);
const command = dash.stderr.split('continue with: sourcegraph ')[1].trim();
assert.equal(command, `read --rev ${SHA} --start 20001 --all -- org/repo -x.txt`);
const again = await cli(s.url, ...command.split(' '));
assert.equal(again.status, 0, again.stderr);
assert.equal(s.requests.at(-1).Path, '-x.txt');
assert.equal(s.requests.at(-1).Revision, SHA);
assert.match(again.stdout.split('\n')[0], /lines 20001-25000$/);
} finally { s.close(); }
});

test('read --all --json returns one merged file and no stop note', async () => {
for (const [total, more] of [[4321, false], [25000, true]] as const) {
const s = await fakeServer(total, 500);
try {
const r = await cli(s.url, '--json', 'read', 'org/repo', 'a.txt', '--all');
assert.equal(r.status, 0, r.stderr);
assert.equal(r.stderr, '');
const f = JSON.parse(r.stdout);
const last = Math.min(total, 20000);
assert.equal(f.Commit, SHA);
assert.equal(f.ReturnedStartLine, 1);
assert.equal(f.ReturnedEndLine, last);
assert.equal(f.HasMore, more);
assert.equal(f.NextStartLine, more ? 20001 : null);
assert.equal(f.Content.split('\n').length - 1, last);
assert.ok(f.Content.endsWith(`line ${last}\n`));
} finally { s.close(); }
}
});

test('read --all rejects --end', async () => {
const s = await fakeServer(10, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--all', '--end', '5');
assert.equal(r.status, 1);
assert.match(r.stderr, /--all reads to the end of the file/);
assert.equal(s.requests.length, 0);
} finally { s.close(); }
});

test('read --all stops with a clear error when the server misbehaves', async () => {
for (const [tweak, message] of [
[(q: any, r: any) => { r.NextStartLine = q.StartLine; }, /did not advance: NextStartLine 1 for a page starting at line 1/],
[(_q: any, r: any) => { r.NextStartLine = null; }, /more content after line 500 without NextStartLine/],
[(_q: any, r: any, n: number) => { if (n === 2) r.ReturnedStartLine += 1; }, /answered from line 502 when asked for line 501/],
[(_q: any, r: any) => { if (r.NextStartLine) r.NextStartLine += 3; }, /skipped lines: NextStartLine 504 after a page ending at line 500/],
] as const) {
const s = await fakeServer(4321, 500, tweak);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--all');
assert.equal(r.status, 1);
assert.match(r.stderr, message);
} finally { s.close(); }
}
});

test('read --start alone reads 200 lines from that line', async () => {
const s = await fakeServer(4321, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt', '--start', '300');
assert.equal(r.status, 0, r.stderr);
assert.deepEqual([s.requests[0].StartLine, s.requests[0].EndLine], [300, 499]);
} finally { s.close(); }
});

test('read without --all keeps the 200-line default', async () => {
const s = await fakeServer(4321, 2000);
try {
const r = await cli(s.url, 'read', 'org/repo', 'a.txt');
assert.equal(r.status, 0, r.stderr);
assert.equal(s.requests.length, 1);
assert.equal(s.requests[0].EndLine, 200);
} finally { s.close(); }
});
2 changes: 1 addition & 1 deletion cli/src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const VERSION = '0.6.0';
export const VERSION = '0.7.0';
6 changes: 4 additions & 2 deletions docs/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ For an MCP client supporting Streamable HTTP:
{"mcpServers":{"sourcegraph":{"url":"https://context4ai.org/sourcegraph/mcp"}}}
```

`read_many` reads several files or line ranges in one call. Repository read plugins enrich `read` and `read_many`; see [repository plugins](ref/repository-plugins.md).
`read` returns at most 2000 lines and 256 KiB per call, whichever comes first; an omitted `end_line` reads 500 lines (MCP), and a larger range returns its first 2000 lines with `HasMore` and `NextStartLine` (HTTP `POST /v1/repo/read` takes an explicit `EndLine`). When more of the requested range remains, the MCP text gives the exact next call — `read` with the same `repo`, the full commit as `revision`, the canonical `path`, `start_line` = NextStartLine and `end_line` within the requested end, plus an explicitly passed `plugins` value; when the range is complete but the file continues, it only says from which line.

`read_many` reads several files or line ranges in one call: at most 500 lines per file and 1000 lines, 256 KiB and 30 seconds per batch. Repository read plugins enrich `read` and `read_many`; see [repository plugins](ref/repository-plugins.md).

Other tools accept a monitored branch or a full SHA. To work with any other branch or a tag, find it with `refs` if needed, `resolve` it to a full SHA, and use that SHA. When `indexed` is false, a repository manager prepares that SHA first.

Expand Down Expand Up @@ -163,7 +165,7 @@ A temporary token is a personal token of the same owner with these properties:

### Command-line client `sourcegraph`

`npm i -g @c4a/sourcegraph` installs `sourcegraph`, a fuller client that also registers and manages repositories, personal tokens and site settings. `sourcegraph login` signs in through the website and stores a 90-day personal token; `sourcegraph --help` lists every command. See [cli/README.md](../cli/README.md). The agent skill in [skills/sourcegraph](../skills/sourcegraph/SKILL.md) teaches agents to use MCP or this CLI: `npx skills add context4ai/sourcegraph --skill sourcegraph`.
`npm i -g @c4a/sourcegraph` installs `sourcegraph`, a fuller client that also registers and manages repositories, personal tokens and site settings. `sourcegraph login` signs in through the website and stores a 90-day personal token; `sourcegraph --help` lists every command. `sourcegraph read <repo> <path> --all` reads a whole file page by page at one commit (stopping after 20000 lines with exit code 0 and the command that continues). See [cli/README.md](../cli/README.md). The agent skill in [skills/sourcegraph](../skills/sourcegraph/SKILL.md) teaches agents to use MCP or this CLI: `npx skills add context4ai/sourcegraph --skill sourcegraph`.

## Remote reads

Expand Down
9 changes: 9 additions & 0 deletions internal/gitstore/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ import (
const MaxReadBytes = 256 << 10
const MaxScanBytes = 8 << 20

// DefaultReadLines applies when a caller omits the end line; an explicit range
// returns at most MaxReadLines (MaxBatchItemLines per batch item), then
// continues at NextStartLine.
const (
DefaultReadLines = 500
MaxReadLines = 2000
MaxBatchItemLines = 500
)

func sortEntries(entries []Entry) {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
}
Expand Down
8 changes: 6 additions & 2 deletions internal/gitstore/read_content.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ import (
// line, and stops immediately at the requested end. bufio may read ahead 4 KiB;
// the caller kills the Git producer instead of draining the rest of the blob.
func readContent(src io.Reader, result File, size int64, start, end, maxBytes int, batch bool) (File, error, int64) {
limited := end-start >= 500
maxLines := MaxReadLines
if batch {
maxLines = MaxBatchItemLines
}
limited := end-start >= maxLines
if limited {
end = start + 499
end = start + maxLines - 1
}
reader := bufio.NewReaderSize(io.LimitReader(src, MaxScanBytes), 4096)
var consumed int64
Expand Down
Loading