conare 0.19.0 → 0.20.0
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.
- package/README.md +48 -0
- package/dist/cli/args.js +137 -0
- package/dist/cli/config.js +39 -0
- package/dist/cli/documents.js +82 -0
- package/dist/cli/github/api.js +139 -0
- package/dist/cli/github/documents.js +118 -0
- package/dist/cli/github/sync.js +244 -0
- package/dist/cli/main.js +273 -0
- package/dist/cli/project.js +61 -0
- package/dist/cli/render.js +69 -0
- package/dist/cli/schedule.js +289 -0
- package/dist/cli/scrub.js +115 -0
- package/dist/cli/sources/claude.js +313 -0
- package/dist/cli/sources/codex.js +266 -0
- package/dist/cli/state.js +101 -0
- package/dist/cli/status.js +125 -0
- package/dist/cli/sync.js +219 -0
- package/dist/cli/transcript.js +103 -0
- package/dist/cli/upload.js +139 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -205,6 +205,54 @@ Cursor (`~/.cursor/mcp.json`):
|
|
|
205
205
|
}
|
|
206
206
|
```
|
|
207
207
|
|
|
208
|
+
## The `conare` command: sync sessions and GitHub
|
|
209
|
+
|
|
210
|
+
The package also ships a command (the library never loads it). It runs under Node and Bun:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
npx conare sync --key sk-conare-... # save the key to ~/.conare/sync.json, then sync
|
|
214
|
+
bunx conare sync # sync again: only new or changed sessions are sent
|
|
215
|
+
npx conare sync --dry-run # count what would upload
|
|
216
|
+
npx conare sync --install # sync now, then every 10 minutes in the background
|
|
217
|
+
npx conare sync status # the last background run; exits 1 if no success in 1 h or a transcript was missed
|
|
218
|
+
npx conare sync --uninstall # stop the background sync
|
|
219
|
+
npx conare sync github owner/repo # issues, PRs and markdown docs (GITHUB_TOKEN or gh auth)
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
**Sessions.** Each Claude Code or Codex session becomes one document in the namespace `sessions`:
|
|
223
|
+
a readable transcript with the prompts, the answers, one line per tool call, and the errors. Tool
|
|
224
|
+
output that succeeded, images and thinking are left out, and secrets (API keys, tokens, private
|
|
225
|
+
keys, passwords) are replaced with `[REDACTED:<kind>]` before anything is sent. Ids are
|
|
226
|
+
`claude:<session>`, `claude:<session>:agent:<agent>` for a subagent, and `codex:<rollout file
|
|
227
|
+
name>`; a session over 250 KB is split into `<id>:part:000001`, `:part:000002`, and so on (one
|
|
228
|
+
layout per session, never both). Metadata: `source` (`claude-code` or `codex`), `session_id`,
|
|
229
|
+
`agent_id`, `project`, `cwd`, `git_branch`, `started_at`, `date` (the last activity) and
|
|
230
|
+
`content_hash`.
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const sessions = conare.namespace("sessions");
|
|
234
|
+
await sessions.query("why did we drop the Redis cache?", { filter: { project: "shop" } });
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
It reads `~/.claude/projects` (or `$CLAUDE_CONFIG_DIR`) and `~/.codex/sessions` (or `$CODEX_HOME`).
|
|
238
|
+
The key comes from `--key`, else `CONARE_API_KEY`, else `~/.conare/sync.json`. What the server
|
|
239
|
+
already has is kept in `~/.conare/sync-state.json`, and one run at a time holds `~/.conare/sync.lock`.
|
|
240
|
+
`--install` copies the command to `~/.conare/sync/<version>/`, checks the copy file by file, runs
|
|
241
|
+
it once, and only then adds a launchd agent (`ai.conare.sync`) on macOS or a systemd user timer on
|
|
242
|
+
Linux. Every run adds a line to `~/.conare/sync.log` (uploaded, skipped and failed counts, duration).
|
|
243
|
+
With `--install --via <command>` the schedule runs the sync through that command, which supplies
|
|
244
|
+
`CONARE_API_KEY` (for example a secrets manager's wrapper such as `ops`), and no key is saved to disk.
|
|
245
|
+
Up to four batches upload at once.
|
|
246
|
+
|
|
247
|
+
**GitHub.** `conare sync github owner/repo` writes every issue and PR thread (body, comments and
|
|
248
|
+
review comments; bots other than `greptile-apps[bot]` and `claude[bot]` are left out) into
|
|
249
|
+
`<repo>-github` as `pr-<n>` / `issue-<n>`, with metadata `kind`, `repo`, `number`, `title`,
|
|
250
|
+
`state`, `author`, `date`, `updated_at`, `merged_at`, `labels` and `url`; and every markdown file on
|
|
251
|
+
the default branch into `<repo>-docs` (id: the path with `/` as `:`; metadata `kind: "doc"`,
|
|
252
|
+
`path`, `title`, `author`, `date`, `url`). Later runs read only threads updated since the last one
|
|
253
|
+
and files whose content changed; docs whose file was deleted are deleted. `--state <file>` sets
|
|
254
|
+
where that is kept (default `~/.conare/github-state.json`).
|
|
255
|
+
|
|
208
256
|
## Development
|
|
209
257
|
|
|
210
258
|
```bash
|
package/dist/cli/args.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Command line: `conare sync [sessions]`, `conare sync status`, `conare sync github <owner/repo>...`.
|
|
2
|
+
export const HELP = `Usage:
|
|
3
|
+
conare sync [options] Claude Code and Codex sessions -> namespace "sessions"
|
|
4
|
+
conare sync status the last sessions sync; exits 1 when its last success is over 1 h old or it missed transcripts
|
|
5
|
+
conare sync github <owner/repo>... [opts] issues, PRs and markdown docs -> "<repo>-github", "<repo>-docs"
|
|
6
|
+
|
|
7
|
+
Run it as npx conare … or bunx conare …. Only new or changed sessions, threads and docs are
|
|
8
|
+
sent; secrets in sessions are redacted first.
|
|
9
|
+
|
|
10
|
+
Options:
|
|
11
|
+
--dry-run count what would upload; upload nothing
|
|
12
|
+
--quiet print nothing on success
|
|
13
|
+
--install sessions: sync now, then every 10 minutes in the background
|
|
14
|
+
--uninstall sessions: stop the background sync
|
|
15
|
+
--via <command> with --install: the schedule runs \`<command> node … sync\`, which
|
|
16
|
+
supplies CONARE_API_KEY (e.g. --via ops); no key is saved to disk
|
|
17
|
+
--state <file> github: what was synced (default ~/.conare/github-state.json)
|
|
18
|
+
--key <key> save an API key (sk-conare-…) to ~/.conare/sync.json, then sync
|
|
19
|
+
-v, --version print the version
|
|
20
|
+
-h, --help show this help
|
|
21
|
+
|
|
22
|
+
Exit codes: 0 done; 1 error; 2 bad arguments; 3 API key refused; 4 incomplete (documents
|
|
23
|
+
refused, the API unreachable, or another sync running), tried again next run.
|
|
24
|
+
|
|
25
|
+
The key comes from --key, else CONARE_API_KEY, else ~/.conare/sync.json.
|
|
26
|
+
Create one at https://conare.ai/console/keys. GitHub: GITHUB_TOKEN, else \`gh auth token\`.
|
|
27
|
+
`;
|
|
28
|
+
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
29
|
+
export function parseArgs(argv) {
|
|
30
|
+
const args = { help: false, version: false, command: "sessions", dryRun: false, quiet: false, install: false, uninstall: false, repos: [] };
|
|
31
|
+
const rest = [...argv];
|
|
32
|
+
const words = [];
|
|
33
|
+
while (rest.length > 0) {
|
|
34
|
+
const arg = rest.shift();
|
|
35
|
+
const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, undefined];
|
|
36
|
+
const value = () => {
|
|
37
|
+
const v = inline ?? rest.shift();
|
|
38
|
+
return v && !v.startsWith("-") ? v : undefined;
|
|
39
|
+
};
|
|
40
|
+
switch (flag) {
|
|
41
|
+
case "-h":
|
|
42
|
+
case "--help":
|
|
43
|
+
case "help":
|
|
44
|
+
args.help = true;
|
|
45
|
+
break;
|
|
46
|
+
case "-v":
|
|
47
|
+
case "--version":
|
|
48
|
+
args.version = true;
|
|
49
|
+
break;
|
|
50
|
+
case "--dry-run":
|
|
51
|
+
args.dryRun = true;
|
|
52
|
+
break;
|
|
53
|
+
case "--quiet":
|
|
54
|
+
args.quiet = true;
|
|
55
|
+
break;
|
|
56
|
+
case "--install":
|
|
57
|
+
args.install = true;
|
|
58
|
+
break;
|
|
59
|
+
case "--uninstall":
|
|
60
|
+
args.uninstall = true;
|
|
61
|
+
break;
|
|
62
|
+
case "--key": {
|
|
63
|
+
const key = value();
|
|
64
|
+
if (!key)
|
|
65
|
+
return { error: "--key needs a value: --key sk-conare-…" };
|
|
66
|
+
if (!key.startsWith("sk-conare-"))
|
|
67
|
+
return { error: "The key should start with sk-conare-." };
|
|
68
|
+
args.key = key;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
case "--via": {
|
|
72
|
+
const via = value();
|
|
73
|
+
if (!via)
|
|
74
|
+
return { error: "--via needs a command: --via ops" };
|
|
75
|
+
args.via = via;
|
|
76
|
+
break;
|
|
77
|
+
}
|
|
78
|
+
case "--state": {
|
|
79
|
+
const state = value();
|
|
80
|
+
if (!state)
|
|
81
|
+
return { error: "--state needs a file" };
|
|
82
|
+
args.state = state;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
default:
|
|
86
|
+
if (flag.startsWith("-"))
|
|
87
|
+
return { error: `Unknown argument: ${arg}` };
|
|
88
|
+
words.push(arg);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (args.help || args.version)
|
|
92
|
+
return args;
|
|
93
|
+
const [command, sub, ...more] = words;
|
|
94
|
+
if (command === undefined)
|
|
95
|
+
return { ...args, help: true };
|
|
96
|
+
if (command !== "sync")
|
|
97
|
+
return { error: `Unknown command: ${command}` };
|
|
98
|
+
if (sub === undefined || sub === "sessions" || sub === "status") {
|
|
99
|
+
if (more.length > 0)
|
|
100
|
+
return { error: `Unknown argument: ${more[0]}` };
|
|
101
|
+
args.command = sub === "status" ? "status" : "sessions";
|
|
102
|
+
}
|
|
103
|
+
else if (sub === "github") {
|
|
104
|
+
if (more.length === 0)
|
|
105
|
+
return { error: "sync github needs a repository: conare sync github owner/repo" };
|
|
106
|
+
for (const repo of more)
|
|
107
|
+
if (!REPO.test(repo))
|
|
108
|
+
return { error: `Not a repository (owner/repo): ${repo}` };
|
|
109
|
+
// Namespaces are named after the repository alone (<name>-github, <name>-docs).
|
|
110
|
+
const byName = new Map();
|
|
111
|
+
for (const repo of more) {
|
|
112
|
+
const name = repo.slice(repo.indexOf("/") + 1).toLowerCase();
|
|
113
|
+
const other = byName.get(name);
|
|
114
|
+
if (other && other.toLowerCase() !== repo.toLowerCase())
|
|
115
|
+
return { error: `${other} and ${repo} would both write to ${name}-github and ${name}-docs; sync one of them.` };
|
|
116
|
+
byName.set(name, repo);
|
|
117
|
+
}
|
|
118
|
+
args.command = "github";
|
|
119
|
+
args.repos = more;
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
return { error: `Unknown argument: ${sub}` };
|
|
123
|
+
}
|
|
124
|
+
if (args.install && args.uninstall)
|
|
125
|
+
return { error: "Use --install or --uninstall, not both." };
|
|
126
|
+
if (args.via && !args.install)
|
|
127
|
+
return { error: "--via goes with --install." };
|
|
128
|
+
if ((args.install || args.uninstall) && args.command !== "sessions")
|
|
129
|
+
return { error: "--install and --uninstall schedule the sessions sync only." };
|
|
130
|
+
if (args.dryRun && (args.install || args.uninstall))
|
|
131
|
+
return { error: "--dry-run cannot be combined with --install or --uninstall." };
|
|
132
|
+
if (args.state !== undefined && args.command !== "github")
|
|
133
|
+
return { error: "--state is for sync github." };
|
|
134
|
+
if (args.command === "status" && (args.dryRun || args.key))
|
|
135
|
+
return { error: "sync status takes no options." };
|
|
136
|
+
return args;
|
|
137
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Where sync reads transcripts and keeps its own files, and the saved API key.
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
export function resolvePaths(env = process.env, home = homedir()) {
|
|
6
|
+
const dir = join(home, ".conare");
|
|
7
|
+
return {
|
|
8
|
+
dir,
|
|
9
|
+
keyFile: join(dir, "sync.json"),
|
|
10
|
+
stateFile: join(dir, "sync-state.json"),
|
|
11
|
+
lockFile: join(dir, "sync.lock"),
|
|
12
|
+
logFile: join(dir, "sync.log"),
|
|
13
|
+
statusFile: join(dir, "sync-status.json"),
|
|
14
|
+
githubStateFile: join(dir, "github-state.json"),
|
|
15
|
+
installRoot: join(dir, "sync"),
|
|
16
|
+
claudeDir: env.CLAUDE_CONFIG_DIR || join(home, ".claude"),
|
|
17
|
+
codexDir: env.CODEX_HOME || join(home, ".codex"),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function readSavedKey(keyFile) {
|
|
21
|
+
try {
|
|
22
|
+
const key = JSON.parse(readFileSync(keyFile, "utf8")).api_key;
|
|
23
|
+
return typeof key === "string" && key ? key : undefined;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export function saveKey(keyFile, key) {
|
|
30
|
+
writePrivate(keyFile, `${JSON.stringify({ api_key: key }, null, 2)}\n`);
|
|
31
|
+
}
|
|
32
|
+
/** Atomic write readable only by the user (the directory too). */
|
|
33
|
+
export function writePrivate(path, content) {
|
|
34
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
35
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
36
|
+
writeFileSync(tmp, content, { mode: 0o600 });
|
|
37
|
+
chmodSync(tmp, 0o600); // mode applies only on create; a leftover tmp keeps its old one
|
|
38
|
+
renameSync(tmp, path);
|
|
39
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Transcript → the documents sent to the namespace "sessions". Ids, parts and metadata are
|
|
2
|
+
// the contract with the server (and with the migration of older history, which uses the
|
|
3
|
+
// same ids).
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { render } from "./render.js";
|
|
6
|
+
import { scrub } from "./scrub.js";
|
|
7
|
+
export const NAMESPACE = "sessions";
|
|
8
|
+
/** The API caps text at 256 KB; a part stays under this many UTF-8 bytes. */
|
|
9
|
+
export const PART_BYTES = 250_000;
|
|
10
|
+
const METADATA_VALUE_BYTES = 4096;
|
|
11
|
+
/** claude:<session>, claude:<session>:agent:<agent>, codex:<session>. */
|
|
12
|
+
export function baseId(t) {
|
|
13
|
+
const prefix = t.source === "codex" ? "codex" : "claude";
|
|
14
|
+
return `${prefix}:${idSegment(t.sessionId)}${t.agentId ? `:agent:${idSegment(t.agentId)}` : ""}`;
|
|
15
|
+
}
|
|
16
|
+
/** <base>:part:000001 for n = 1. */
|
|
17
|
+
export function partId(base, n) {
|
|
18
|
+
return `${base}:part:${String(n).padStart(6, "0")}`;
|
|
19
|
+
}
|
|
20
|
+
/** Ids allow [A-Za-z0-9._:-]; anything else in a file name becomes "-". */
|
|
21
|
+
function idSegment(value) {
|
|
22
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 160);
|
|
23
|
+
}
|
|
24
|
+
/** The documents for one transcript: one, or numbered parts when the text is too large. */
|
|
25
|
+
export function toDocuments(t, project) {
|
|
26
|
+
const text = scrub(render(t, project));
|
|
27
|
+
const parts = splitText(text, PART_BYTES);
|
|
28
|
+
const base = baseId(t);
|
|
29
|
+
const shared = {};
|
|
30
|
+
// Metadata is scrubbed like the text: a path or branch name can hold a secret too.
|
|
31
|
+
const set = (key, value) => {
|
|
32
|
+
const clean = value && scrub(value);
|
|
33
|
+
if (clean && Buffer.byteLength(clean) <= METADATA_VALUE_BYTES)
|
|
34
|
+
shared[key] = clean;
|
|
35
|
+
};
|
|
36
|
+
set("source", t.source);
|
|
37
|
+
set("session_id", t.sessionId);
|
|
38
|
+
set("agent_id", t.agentId);
|
|
39
|
+
set("project", project);
|
|
40
|
+
set("cwd", t.cwd);
|
|
41
|
+
set("git_branch", t.branch);
|
|
42
|
+
set("started_at", t.startedAt);
|
|
43
|
+
set("date", t.endedAt ?? t.startedAt); // last activity: MCP shows it as the document's date and orders by it
|
|
44
|
+
return parts.map((part, i) => ({
|
|
45
|
+
id: parts.length > 1 ? partId(base, i + 1) : base,
|
|
46
|
+
text: part,
|
|
47
|
+
metadata: {
|
|
48
|
+
...shared,
|
|
49
|
+
...(parts.length > 1 ? { part: i + 1, parts: parts.length } : {}),
|
|
50
|
+
content_hash: sha256(part),
|
|
51
|
+
},
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
54
|
+
export function sha256(text) {
|
|
55
|
+
return createHash("sha256").update(text).digest("hex");
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Split text into pieces of at most maxBytes UTF-8 bytes whose concatenation is the text.
|
|
59
|
+
* A piece ends after a newline when one falls in the second half of the window; a line
|
|
60
|
+
* longer than that is cut at a character boundary.
|
|
61
|
+
*/
|
|
62
|
+
export function splitText(text, maxBytes) {
|
|
63
|
+
const buf = Buffer.from(text, "utf8");
|
|
64
|
+
if (buf.length <= maxBytes)
|
|
65
|
+
return [text];
|
|
66
|
+
const parts = [];
|
|
67
|
+
let start = 0;
|
|
68
|
+
while (start < buf.length) {
|
|
69
|
+
let end = Math.min(start + maxBytes, buf.length);
|
|
70
|
+
if (end < buf.length) {
|
|
71
|
+
const newline = buf.lastIndexOf(0x0a, end - 1);
|
|
72
|
+
if (newline >= start + maxBytes / 2)
|
|
73
|
+
end = newline + 1;
|
|
74
|
+
else
|
|
75
|
+
while (end > start && (buf[end] & 0xc0) === 0x80)
|
|
76
|
+
end--; // not inside a character
|
|
77
|
+
}
|
|
78
|
+
parts.push(buf.toString("utf8", start, end));
|
|
79
|
+
start = end;
|
|
80
|
+
}
|
|
81
|
+
return parts;
|
|
82
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// A small GitHub client: REST with pagination and GraphQL, on fetch. Retries 5xx, 429 and
|
|
2
|
+
// rate-limit 403s, waiting what GitHub asks (Retry-After, or until X-RateLimit-Reset) up to
|
|
3
|
+
// MAX_WAIT_MS; anything else throws a GitHubError.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
const API = "https://api.github.com";
|
|
6
|
+
const ATTEMPTS = 5;
|
|
7
|
+
const MAX_WAIT_MS = 15 * 60 * 1000;
|
|
8
|
+
/**
|
|
9
|
+
* Bounds one request, body included: a stall before the response is retried, one while reading
|
|
10
|
+
* the body ends the run; either way a hung connection never holds the run (and its lock) forever.
|
|
11
|
+
*/
|
|
12
|
+
export const REQUEST_TIMEOUT_MS = 120_000;
|
|
13
|
+
export class GitHubError extends Error {
|
|
14
|
+
status;
|
|
15
|
+
constructor(status, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.status = status;
|
|
18
|
+
this.name = "GitHubError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class GitHub {
|
|
22
|
+
token;
|
|
23
|
+
/** Requests sent, retries included. */
|
|
24
|
+
calls = 0;
|
|
25
|
+
fetchFn;
|
|
26
|
+
base;
|
|
27
|
+
graphqlURL;
|
|
28
|
+
sleep;
|
|
29
|
+
timeoutMs;
|
|
30
|
+
constructor(token, options = {}) {
|
|
31
|
+
this.token = token;
|
|
32
|
+
this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init));
|
|
33
|
+
this.base = (options.baseURL ?? API).replace(/\/+$/, "");
|
|
34
|
+
this.graphqlURL = options.graphqlURL ?? `${this.base}/graphql`;
|
|
35
|
+
this.sleep = options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
36
|
+
this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
37
|
+
}
|
|
38
|
+
async send(url, init = {}) {
|
|
39
|
+
for (let attempt = 1;; attempt++) {
|
|
40
|
+
this.calls++;
|
|
41
|
+
let res;
|
|
42
|
+
let failure;
|
|
43
|
+
try {
|
|
44
|
+
res = await this.fetchFn(url, {
|
|
45
|
+
...init,
|
|
46
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
47
|
+
headers: {
|
|
48
|
+
Accept: "application/vnd.github+json",
|
|
49
|
+
Authorization: `Bearer ${this.token}`,
|
|
50
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
51
|
+
"User-Agent": "conare-cli",
|
|
52
|
+
...init.headers,
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
if (res.ok)
|
|
56
|
+
return res;
|
|
57
|
+
failure = `${res.status} ${(await res.text()).slice(0, 300)}`;
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
failure = String(err);
|
|
61
|
+
}
|
|
62
|
+
const wait = res ? retryWait(res, attempt) : 2 ** attempt * 1000;
|
|
63
|
+
if (wait === undefined || attempt >= ATTEMPTS)
|
|
64
|
+
throw new GitHubError(res?.status ?? 0, `GitHub ${init.method ?? "GET"} ${url.replace(this.base, "")}: ${failure}`);
|
|
65
|
+
await this.sleep(wait);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** GET a REST path (or a full URL) as JSON. */
|
|
69
|
+
async json(path) {
|
|
70
|
+
const res = await this.send(path.startsWith("http") ? path : this.base + path);
|
|
71
|
+
return (await res.json());
|
|
72
|
+
}
|
|
73
|
+
/** Every item of a paginated REST list, following the Link header. */
|
|
74
|
+
async *paginate(path) {
|
|
75
|
+
let url = this.base + path;
|
|
76
|
+
while (url) {
|
|
77
|
+
const res = await this.send(url);
|
|
78
|
+
for (const item of (await res.json()))
|
|
79
|
+
yield item;
|
|
80
|
+
url = nextLink(res.headers.get("link"));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async all(path) {
|
|
84
|
+
const out = [];
|
|
85
|
+
for await (const item of this.paginate(path))
|
|
86
|
+
out.push(item);
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
async graphql(query, variables) {
|
|
90
|
+
const res = await this.send(this.graphqlURL, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
body: JSON.stringify({ query, variables }),
|
|
93
|
+
headers: { "Content-Type": "application/json" },
|
|
94
|
+
});
|
|
95
|
+
const body = (await res.json());
|
|
96
|
+
if (body.errors?.length || !body.data) {
|
|
97
|
+
throw new GitHubError(res.status, `GitHub GraphQL: ${(body.errors ?? []).map((e) => e.message).join("; ") || "no data"}`);
|
|
98
|
+
}
|
|
99
|
+
return body.data;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** How long to wait before retrying this response, or undefined when retrying cannot help. */
|
|
103
|
+
export function retryWait(res, attempt, now = Date.now()) {
|
|
104
|
+
const after = Number(res.headers.get("retry-after"));
|
|
105
|
+
const limited = res.status === 429 || (res.status === 403 && (res.headers.get("x-ratelimit-remaining") === "0" || res.headers.has("retry-after")));
|
|
106
|
+
if (limited) {
|
|
107
|
+
let wait = Number.isFinite(after) && after > 0 ? after * 1000 : undefined;
|
|
108
|
+
const reset = Number(res.headers.get("x-ratelimit-reset"));
|
|
109
|
+
if (wait === undefined && Number.isFinite(reset) && reset > 0)
|
|
110
|
+
wait = reset * 1000 - now + 1000;
|
|
111
|
+
wait ??= 60_000;
|
|
112
|
+
return wait <= MAX_WAIT_MS ? Math.max(wait, 1000) : undefined;
|
|
113
|
+
}
|
|
114
|
+
if (res.status >= 500)
|
|
115
|
+
return 2 ** attempt * 1000;
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
export function nextLink(link) {
|
|
119
|
+
if (!link)
|
|
120
|
+
return undefined;
|
|
121
|
+
for (const part of link.split(",")) {
|
|
122
|
+
const m = /<([^>]+)>\s*;\s*rel="next"/.exec(part);
|
|
123
|
+
if (m)
|
|
124
|
+
return m[1];
|
|
125
|
+
}
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
/** GITHUB_TOKEN, else GH_TOKEN, else what the gh CLI is logged in with. */
|
|
129
|
+
export function githubToken(env = process.env) {
|
|
130
|
+
const fromEnv = env.GITHUB_TOKEN || env.GH_TOKEN;
|
|
131
|
+
if (fromEnv)
|
|
132
|
+
return fromEnv;
|
|
133
|
+
try {
|
|
134
|
+
return execFileSync("gh", ["auth", "token"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || undefined;
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// GitHub → documents. The format is the 2026-10-02 build that filled conare-github and
|
|
2
|
+
// conare-docs (build_corpus.py, gs://conare-results/pointer/corpus-2026-10-02/): a thread is
|
|
3
|
+
// one document "pr-<n>" / "issue-<n>" in "<repo>-github" (head line, state line, body, then
|
|
4
|
+
// every kept comment in time order); a markdown file is one document in "<repo>-docs" whose id
|
|
5
|
+
// is its path with / as : and whose text starts with the path. Pure: no network.
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
/** Bots whose comments are review findings agents answered; other bots are CI noise. */
|
|
8
|
+
export const KEEP_BOTS = new Set(["greptile-apps[bot]", "claude[bot]"]);
|
|
9
|
+
/** Bytes; the API takes 256 KiB per text. */
|
|
10
|
+
export const MAX_TEXT_BYTES = 250_000;
|
|
11
|
+
/** Greptile's appended summary, HTML comments and badge images removed; blank runs collapsed. */
|
|
12
|
+
export function clean(s) {
|
|
13
|
+
let t = (s ?? "").split("<!-- greptile_comment -->")[0];
|
|
14
|
+
t = t.replace(/<!--[\s\S]*?-->/g, "");
|
|
15
|
+
t = t.replace(/<(picture|img|source)[^>]*>|<\/picture>/g, "");
|
|
16
|
+
return t.replace(/\n{3,}/g, "\n\n").trim();
|
|
17
|
+
}
|
|
18
|
+
/** Comments by people, and by the bots in KEEP_BOTS. A deleted account counts as a person. */
|
|
19
|
+
export function kept(c) {
|
|
20
|
+
return c.user?.type !== "Bot" || KEEP_BOTS.has(c.user.login);
|
|
21
|
+
}
|
|
22
|
+
/** At most MAX_TEXT_BYTES of UTF-8, cut at a character boundary, marked "[truncated]". */
|
|
23
|
+
export function fit(text, max = MAX_TEXT_BYTES) {
|
|
24
|
+
const buf = Buffer.from(text, "utf8");
|
|
25
|
+
if (buf.length <= max)
|
|
26
|
+
return text;
|
|
27
|
+
let end = max;
|
|
28
|
+
while (end > 0 && (buf[end] & 0xc0) === 0x80)
|
|
29
|
+
end--;
|
|
30
|
+
return `${buf.toString("utf8", 0, end)}\n[truncated]`;
|
|
31
|
+
}
|
|
32
|
+
/** The thread a comment belongs to. */
|
|
33
|
+
export function commentNumber(c) {
|
|
34
|
+
const url = c.issue_url ?? c.pull_request_url;
|
|
35
|
+
const n = url ? Number(url.slice(url.lastIndexOf("/") + 1)) : NaN;
|
|
36
|
+
return Number.isInteger(n) ? n : undefined;
|
|
37
|
+
}
|
|
38
|
+
export function threadId(issue) {
|
|
39
|
+
return `${issue.pull_request ? "pr" : "issue"}-${issue.number}`;
|
|
40
|
+
}
|
|
41
|
+
/** One issue or PR with its kept comments (issue comments and review comments, any order). */
|
|
42
|
+
export function threadDocument(repo, issue, comments) {
|
|
43
|
+
const pr = Boolean(issue.pull_request);
|
|
44
|
+
const merged = issue.pull_request?.merged_at ?? undefined;
|
|
45
|
+
const state = merged ? "merged" : issue.state;
|
|
46
|
+
const kind = pr ? "PR" : "Issue";
|
|
47
|
+
const author = issue.user?.login ?? "ghost";
|
|
48
|
+
let head = `${kind} ${repo}#${issue.number}: ${issue.title}\n${state} · opened by ${author} on ${issue.created_at.slice(0, 10)}`;
|
|
49
|
+
head += merged ? ` · merged ${merged.slice(0, 10)}` : issue.closed_at ? ` · closed ${issue.closed_at.slice(0, 10)}` : "";
|
|
50
|
+
const entries = comments
|
|
51
|
+
.filter(kept)
|
|
52
|
+
.map((c) => [c.created_at, c.user?.login ?? "ghost", c.pull_request_url ? ` on ${c.path}` : "", c.body ?? ""])
|
|
53
|
+
.sort(compareTuples);
|
|
54
|
+
const parts = [head, clean(issue.body), ...entries.map(([at, who, where, body]) => `--- ${who} on ${at.slice(0, 10)}${where}:\n${clean(body)}`)];
|
|
55
|
+
const metadata = {
|
|
56
|
+
title: issue.title,
|
|
57
|
+
author,
|
|
58
|
+
date: issue.created_at,
|
|
59
|
+
updated_at: issue.updated_at,
|
|
60
|
+
url: issue.html_url,
|
|
61
|
+
repo,
|
|
62
|
+
number: issue.number,
|
|
63
|
+
kind: kind.toLowerCase(),
|
|
64
|
+
state,
|
|
65
|
+
labels: (issue.labels ?? []).map((l) => (typeof l === "string" ? l : (l.name ?? ""))).slice(0, 20),
|
|
66
|
+
};
|
|
67
|
+
if (merged)
|
|
68
|
+
metadata.merged_at = merged;
|
|
69
|
+
return { id: threadId(issue), text: fit(parts.filter(Boolean).join("\n\n")), metadata };
|
|
70
|
+
}
|
|
71
|
+
// Python's tuple order: created_at, then login, then where, then body.
|
|
72
|
+
function compareTuples(a, b) {
|
|
73
|
+
for (let i = 0; i < a.length; i++) {
|
|
74
|
+
if (a[i] < b[i])
|
|
75
|
+
return -1;
|
|
76
|
+
if (a[i] > b[i])
|
|
77
|
+
return 1;
|
|
78
|
+
}
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* "docs/a.md" → "docs:a.md": [A-Za-z0-9._:-], no leading . _ : -, at most 256. A path that
|
|
83
|
+
* needs more than "/" → ":" (other characters, a ":", a leading dot, over 256) also gets
|
|
84
|
+
* "::" and 16 hex of its sha256, so "a b.md" and "a_b.md" never share an id. A git path has
|
|
85
|
+
* no empty segment, so "::" never appears in an id that needed no sanitizing.
|
|
86
|
+
*/
|
|
87
|
+
export function docId(path) {
|
|
88
|
+
const plain = path.replace(/\//g, ":");
|
|
89
|
+
const id = plain.replace(/[^A-Za-z0-9._:-]/g, "_").replace(/^[._:-]+/, "");
|
|
90
|
+
if (id === plain && !path.includes(":") && id.length <= 256)
|
|
91
|
+
return id;
|
|
92
|
+
const suffix = `::${createHash("sha256").update(path).digest("hex").slice(0, 16)}`;
|
|
93
|
+
return `${id.slice(0, 256 - suffix.length)}${suffix}`;
|
|
94
|
+
}
|
|
95
|
+
/** The first markdown heading, else the path; at most 200 characters. */
|
|
96
|
+
export function docTitle(path, text) {
|
|
97
|
+
const heading = text.split(/\r?\n|\r/).find((l) => l.startsWith("#"));
|
|
98
|
+
const title = heading ? heading.replace(/^[# ]+/, "").trim() : path;
|
|
99
|
+
return [...title].slice(0, 200).join("");
|
|
100
|
+
}
|
|
101
|
+
/** A markdown file, or undefined when it holds only whitespace. */
|
|
102
|
+
export function docDocument(repo, branch, f) {
|
|
103
|
+
if (!f.text.trim())
|
|
104
|
+
return undefined;
|
|
105
|
+
return {
|
|
106
|
+
id: docId(f.path),
|
|
107
|
+
text: fit(`${f.path}\n\n${f.text}`),
|
|
108
|
+
metadata: {
|
|
109
|
+
title: docTitle(f.path, f.text),
|
|
110
|
+
author: f.author,
|
|
111
|
+
date: f.date,
|
|
112
|
+
path: f.path,
|
|
113
|
+
repo,
|
|
114
|
+
url: `https://github.com/${repo}/blob/${branch}/${f.path}`,
|
|
115
|
+
kind: "doc",
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|