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.
@@ -0,0 +1,244 @@
1
+ // `conare sync github <owner/repo>`: every issue and PR thread into "<repo>-github" and every
2
+ // markdown file on the default branch into "<repo>-docs", incrementally.
3
+ //
4
+ // Threads: the issues listing sorted by update, newest first, from the last run's newest
5
+ // updated_at (inclusive, so nothing at the boundary is missed). Newest first because the
6
+ // listing pages by number: a thread updated during the walk moves to the front, which only
7
+ // repeats an item on a later page (dropped here), where oldest first would shift an unread
8
+ // one back past the page boundary and skip it for good. Each changed thread is rebuilt whole
9
+ // from all of its comments. The first run (or one with more than PER_THREAD_LIMIT changed
10
+ // threads) reads the repository-wide comment listings instead of per-thread ones.
11
+ // Docs: the tree of the branch head; a file is fetched again only when its blob changed; its
12
+ // text and the author and date of the last commit touching it come from GraphQL in batches.
13
+ // A doc id that is in the namespace but no longer made by any file is deleted.
14
+ // Nothing advances in the state unless the server accepted everything it covers.
15
+ import { readFileSync } from "node:fs";
16
+ import { ConareError } from "../../index.js";
17
+ import { writePrivate } from "../config.js";
18
+ import { BATCH_BYTES, BATCH_DOCUMENTS, batches, sendBatch } from "../upload.js";
19
+ import { commentNumber, docDocument, docId, threadDocument } from "./documents.js";
20
+ /** More changed threads than this: read the repository-wide comment listings. */
21
+ export const PER_THREAD_LIMIT = 100;
22
+ /** Files per GraphQL request. */
23
+ export const DOCS_PER_QUERY = 25;
24
+ const DELETE_BATCH = 1000;
25
+ export function loadGitHubState(file) {
26
+ try {
27
+ const s = JSON.parse(readFileSync(file, "utf8"));
28
+ if (s && typeof s.repos === "object" && s.repos)
29
+ return s;
30
+ }
31
+ catch {
32
+ // Missing or corrupt: everything is read again, which is safe (same ids).
33
+ }
34
+ return { repos: {} };
35
+ }
36
+ export function saveGitHubState(file, state) {
37
+ writePrivate(file, `${JSON.stringify(state, null, 1)}\n`);
38
+ }
39
+ /** Sync one repository. Returns the report and the state to save. */
40
+ export async function syncRepo(opts) {
41
+ const { gh, repo } = opts;
42
+ const log = opts.log ?? (() => { });
43
+ const report = {
44
+ repo,
45
+ threads: { changed: 0, uploaded: 0, unchanged: 0, failed: 0 },
46
+ docs: { files: 0, changed: 0, uploaded: 0, unchanged: 0, failed: 0, deleted: 0 },
47
+ rejected: [],
48
+ };
49
+ const next = { ...opts.state };
50
+ const info = await gh.json(`/repos/${repo}`);
51
+ // ---- threads ----
52
+ const since = opts.state.updatedAt;
53
+ const issues = latestPerThread(await gh.all(`/repos/${repo}/issues?state=all&sort=updated&direction=desc&per_page=100${since ? `&since=${encodeURIComponent(since)}` : ""}`));
54
+ report.threads.changed = issues.length;
55
+ log(`${repo}: ${issues.length} threads ${since ? `updated since ${since}` : "(first run)"}`);
56
+ const comments = await threadComments(gh, repo, issues, !since || issues.length > PER_THREAD_LIMIT);
57
+ const threads = issues.map((i) => threadDocument(info.full_name, i, comments.get(i.number) ?? []));
58
+ const threadResult = await upload(opts, opts.namespaces?.github, threads);
59
+ report.threads.uploaded = threadResult.accepted.size;
60
+ report.threads.unchanged = threadResult.unchanged;
61
+ report.threads.failed = threadResult.rejected.length;
62
+ report.rejected.push(...threadResult.rejected);
63
+ if (threadResult.rejected.length === 0 && issues.length > 0) {
64
+ next.updatedAt = issues.reduce((max, i) => (i.updated_at > max ? i.updated_at : max), since ?? "");
65
+ }
66
+ // ---- docs ----
67
+ const head = await gh.json(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
68
+ const commit = head.object.sha;
69
+ const tree = await gh.json(`/repos/${repo}/git/trees/${commit}?recursive=1`);
70
+ if (tree.truncated)
71
+ throw new Error(`${repo}: the file tree is too large for one GitHub listing`);
72
+ const files = tree.tree.filter((e) => e.type === "blob" && e.path.endsWith(".md")).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
73
+ report.docs.files = files.length;
74
+ const previous = opts.state.docs ?? {};
75
+ // Fetched again: a new or edited file, and one whose recorded id is not what docId makes now
76
+ // (null: skipped as a duplicate before ids were collision-free), so every file's doc exists.
77
+ const changed = files.filter((f) => {
78
+ const old = previous[f.path];
79
+ return old?.sha !== f.sha || (old.id !== "" && old.id !== docId(f.path));
80
+ });
81
+ report.docs.changed = changed.length;
82
+ log(`${repo}: ${files.length} markdown files on ${info.default_branch}, ${changed.length} new or changed`);
83
+ const fetched = await fetchDocs(gh, repo, commit, changed);
84
+ const docsState = {};
85
+ const owners = new Set(); // ids some file makes: docId() is one-to-one, so one file each
86
+ const toSend = [];
87
+ for (const f of files) {
88
+ const got = fetched.get(f.path);
89
+ let id;
90
+ if (got) {
91
+ const doc = got === "binary" ? undefined : docDocument(info.full_name, info.default_branch, got);
92
+ id = doc?.id ?? "";
93
+ if (doc)
94
+ toSend.push(doc);
95
+ }
96
+ else {
97
+ id = previous[f.path].id; // unchanged: "" or docId(f.path)
98
+ }
99
+ if (id !== "")
100
+ owners.add(id);
101
+ docsState[f.path] = { sha: f.sha, id };
102
+ }
103
+ const docResult = await upload(opts, opts.namespaces?.docs, toSend);
104
+ report.docs.uploaded = docResult.accepted.size;
105
+ report.docs.unchanged = docResult.unchanged;
106
+ report.docs.failed = docResult.rejected.length;
107
+ report.rejected.push(...docResult.rejected);
108
+ // A rejected file keeps its old sha, so the next run sends it again, and its old doc stays.
109
+ const rejectedIds = new Set(docResult.rejected.map((r) => r.slice(0, r.indexOf(": "))));
110
+ for (const [path, entry] of Object.entries(docsState)) {
111
+ if (entry.id && rejectedIds.has(entry.id)) {
112
+ const old = previous[path];
113
+ if (old?.id)
114
+ owners.add(old.id);
115
+ if (old)
116
+ docsState[path] = old;
117
+ else
118
+ delete docsState[path];
119
+ }
120
+ }
121
+ next.docs = docsState;
122
+ // Deleted files: ids in the namespace that no file makes any more.
123
+ if (opts.namespaces) {
124
+ const stale = [];
125
+ try {
126
+ for await (const d of opts.namespaces.docs.list({ limit: 100 }))
127
+ if (!owners.has(d.id))
128
+ stale.push(d.id);
129
+ }
130
+ catch (err) {
131
+ if (!(err instanceof ConareError && err.status === 404))
132
+ throw err;
133
+ }
134
+ report.docs.deleted = stale.length;
135
+ if (stale.length > 0)
136
+ log(`${repo}: ${opts.dryRun ? "would delete" : "deleting"} ${stale.length} docs whose file is gone`);
137
+ if (!opts.dryRun)
138
+ for (let i = 0; i < stale.length; i += DELETE_BATCH)
139
+ await opts.namespaces.docs.deleteMany(stale.slice(i, i + DELETE_BATCH));
140
+ }
141
+ return { report, state: next };
142
+ }
143
+ /** One entry per thread number, its newest version (a thread updated mid-listing can appear twice). */
144
+ export function latestPerThread(issues) {
145
+ const byNumber = new Map();
146
+ for (const i of issues) {
147
+ const seen = byNumber.get(i.number);
148
+ if (!seen || i.updated_at > seen.updated_at)
149
+ byNumber.set(i.number, i);
150
+ }
151
+ return [...byNumber.values()];
152
+ }
153
+ /** Comments of the given threads by number: per thread, or from the repository-wide listings. */
154
+ async function threadComments(gh, repo, issues, repoWide) {
155
+ const out = new Map();
156
+ const add = (n, c) => {
157
+ if (n === undefined)
158
+ return;
159
+ const list = out.get(n);
160
+ if (list)
161
+ list.push(c);
162
+ else
163
+ out.set(n, [c]);
164
+ };
165
+ if (issues.length === 0)
166
+ return out;
167
+ if (repoWide) {
168
+ const wanted = new Set(issues.map((i) => i.number));
169
+ for await (const c of gh.paginate(`/repos/${repo}/issues/comments?per_page=100`)) {
170
+ const n = commentNumber(c);
171
+ if (n !== undefined && wanted.has(n))
172
+ add(n, c);
173
+ }
174
+ for await (const c of gh.paginate(`/repos/${repo}/pulls/comments?per_page=100`)) {
175
+ const n = commentNumber(c);
176
+ if (n !== undefined && wanted.has(n))
177
+ add(n, c);
178
+ }
179
+ return out;
180
+ }
181
+ for (const i of issues) {
182
+ if ((i.comments ?? 1) > 0)
183
+ for (const c of await gh.all(`/repos/${repo}/issues/${i.number}/comments?per_page=100`))
184
+ add(i.number, c);
185
+ if (i.pull_request)
186
+ for (const c of await gh.all(`/repos/${repo}/pulls/${i.number}/comments?per_page=100`))
187
+ add(i.number, c);
188
+ }
189
+ return out;
190
+ }
191
+ /** Text and last-commit author and date of each file at `commit`; "binary" for a binary file. */
192
+ async function fetchDocs(gh, repo, commit, files) {
193
+ const out = new Map();
194
+ const [owner, name] = repo.split("/");
195
+ for (let i = 0; i < files.length; i += DOCS_PER_QUERY) {
196
+ const chunk = files.slice(i, i + DOCS_PER_QUERY);
197
+ const vars = { owner, name, commit };
198
+ const decl = ["$owner: String!", "$name: String!", "$commit: String!"];
199
+ const history = [];
200
+ const blobs = [];
201
+ chunk.forEach((f, j) => {
202
+ vars[`p${j}`] = f.path;
203
+ vars[`e${j}`] = `${commit}:${f.path}`;
204
+ decl.push(`$p${j}: String!`, `$e${j}: String!`);
205
+ history.push(`h${j}: history(first: 1, path: $p${j}) { nodes { author { name date } } }`);
206
+ blobs.push(`b${j}: object(expression: $e${j}) { ... on Blob { text isBinary isTruncated } }`);
207
+ });
208
+ const query = `query(${decl.join(", ")}) { repository(owner: $owner, name: $name) { head: object(expression: $commit) { ... on Commit { ${history.join(" ")} } } ${blobs.join(" ")} } }`;
209
+ const data = await gh.graphql(query, vars);
210
+ for (const [j, f] of chunk.entries()) {
211
+ const blob = data.repository[`b${j}`];
212
+ const node = data.repository.head?.[`h${j}`]?.nodes?.[0];
213
+ if (!blob || blob.isBinary) {
214
+ out.set(f.path, "binary");
215
+ continue;
216
+ }
217
+ let text = blob.text ?? "";
218
+ if (blob.isTruncated) {
219
+ const raw = await gh.json(`/repos/${repo}/git/blobs/${f.sha}`);
220
+ text = Buffer.from(raw.content, raw.encoding === "base64" ? "base64" : "utf8").toString("utf8");
221
+ }
222
+ out.set(f.path, { path: f.path, text, author: node?.author?.name ?? "", date: node?.author?.date ?? "" });
223
+ }
224
+ }
225
+ return out;
226
+ }
227
+ /** Send documents in batches; a dry run sends nothing and counts them all as to upload. */
228
+ async function upload(opts, ns, docs) {
229
+ const result = { accepted: new Set(), unchanged: 0, rejected: [] };
230
+ if (opts.dryRun || !ns) {
231
+ for (const d of docs)
232
+ result.accepted.add(d.id);
233
+ return result;
234
+ }
235
+ for (const batch of batches(docs, BATCH_DOCUMENTS, BATCH_BYTES)) {
236
+ const r = await sendBatch(ns, batch);
237
+ for (const d of r.accepted)
238
+ result.accepted.add(d.id);
239
+ result.unchanged += r.unchanged;
240
+ for (const { doc, error } of r.rejected)
241
+ result.rejected.push(`${doc.id}: ${error.code}: ${error.message}`);
242
+ }
243
+ return result;
244
+ }
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ // The conare command: `conare sync` uploads Claude Code and Codex sessions, `conare sync
3
+ // github` issues, PRs and markdown docs, both through the SDK's own client. Node built-ins
4
+ // only; runs under node (npx conare) and bun (bunx conare). The library entry never imports
5
+ // this directory.
6
+ import { spawnSync } from "node:child_process";
7
+ import { rmSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { fileURLToPath } from "node:url";
10
+ import { Conare, ConareError, VERSION } from "../index.js";
11
+ import { HELP, parseArgs } from "./args.js";
12
+ import { readSavedKey, resolvePaths, saveKey } from "./config.js";
13
+ import { GitHub, GitHubError, githubToken } from "./github/api.js";
14
+ import { loadGitHubState, saveGitHubState, syncRepo } from "./github/sync.js";
15
+ import { PASSED_ENV, installCopy, installSchedule, installedSchedule, pruneVersions, stableRuntime, uninstallSchedule } from "./schedule.js";
16
+ import { accountOf, acquireLock } from "./state.js";
17
+ import { describeStatus, readStamps, readStatus, recordRun, unsyncedTranscripts } from "./status.js";
18
+ import { findTranscripts, formatBytes, runSync } from "./sync.js";
19
+ const MAX_RETRIES = 4;
20
+ /** Exit code for a refused key; --install does not schedule a sync that cannot succeed. */
21
+ const AUTH_FAILED = 3;
22
+ /**
23
+ * Exit code for a sync that ran but did not finish: documents refused, the API unreachable,
24
+ * or another sync holding the lock. --install schedules after this (the next run retries),
25
+ * but not after 1, which is what an unexpected exception exits with.
26
+ */
27
+ const INCOMPLETE = 4;
28
+ async function main(argv) {
29
+ const args = parseArgs(argv);
30
+ if ("error" in args) {
31
+ process.stderr.write(`${args.error}\n\n${HELP}`);
32
+ return 2;
33
+ }
34
+ if (args.help) {
35
+ process.stdout.write(HELP);
36
+ return 0;
37
+ }
38
+ if (args.version) {
39
+ process.stdout.write(`${VERSION}\n`);
40
+ return 0;
41
+ }
42
+ const paths = resolvePaths();
43
+ const say = (line) => {
44
+ if (!args.quiet)
45
+ console.log(line);
46
+ };
47
+ // Errors reach the log when run by the schedule, so they carry a time there.
48
+ const fail = (line) => console.error(args.quiet ? `${new Date().toISOString()} ${line}` : line);
49
+ if (args.command === "status") {
50
+ const status = readStatus(paths.statusFile);
51
+ const lastSuccess = status.lastSuccessAt ? Date.parse(status.lastSuccessAt) : NaN;
52
+ const unsynced = Number.isFinite(lastSuccess)
53
+ ? unsyncedTranscripts(findTranscripts(paths).map((f) => f.path), readStamps(paths.stateFile), lastSuccess)
54
+ : [];
55
+ const { text, ok } = describeStatus(status, Date.now(), installedSchedule({ platform: process.platform }), unsynced);
56
+ process.stdout.write(text);
57
+ return ok ? 0 : 1;
58
+ }
59
+ if (args.key) {
60
+ saveKey(paths.keyFile, args.key);
61
+ say(`Saved the key to ${tilde(paths.keyFile)}.`);
62
+ }
63
+ if (args.uninstall) {
64
+ const removed = uninstallSchedule({ platform: process.platform });
65
+ rmSync(paths.installRoot, { recursive: true, force: true });
66
+ say(removed ? "Removed the background sync." : "No background sync was installed.");
67
+ return 0;
68
+ }
69
+ const envKey = process.env.CONARE_API_KEY || undefined;
70
+ const apiKey = args.key ?? envKey ?? readSavedKey(paths.keyFile);
71
+ if (!apiKey && !args.dryRun) {
72
+ fail("No API key. Create one at https://conare.ai/console/keys, then run:\n npx conare sync --key sk-conare-…");
73
+ return 1;
74
+ }
75
+ if (args.command === "github")
76
+ return syncGitHub(args, paths, apiKey, say, fail);
77
+ if (args.install) {
78
+ if (!args.key && !args.via && envKey && readSavedKey(paths.keyFile) !== envKey) {
79
+ // The schedule does not see this shell's environment; it reads the saved key.
80
+ saveKey(paths.keyFile, envKey);
81
+ say(`Saved the key from CONARE_API_KEY to ${tilde(paths.keyFile)} for the background sync.`);
82
+ }
83
+ return install(args, paths, say, fail);
84
+ }
85
+ if (args.dryRun)
86
+ return (await syncSessions(args, paths, apiKey, say, fail)).code; // writes nothing: no lock, no record
87
+ const release = acquireLock(paths.lockFile);
88
+ if (!release) {
89
+ if (!args.quiet)
90
+ fail("Another sync is running.");
91
+ return args.quiet ? 0 : INCOMPLETE;
92
+ }
93
+ try {
94
+ return (await syncSessions(args, paths, apiKey, say, fail)).code;
95
+ }
96
+ finally {
97
+ release();
98
+ }
99
+ }
100
+ /**
101
+ * Copy the package to ~/.conare/sync/<version>/, check the copy (files and sizes), run it once
102
+ * (`--version`, then a real sync), and only then point the schedule at it. A copy that does
103
+ * not start, or a refused key, leaves the schedule as it was.
104
+ */
105
+ function install(args, paths, say, fail) {
106
+ let via;
107
+ if (args.via) {
108
+ via = args.via.startsWith("/") ? args.via : spawnSync("/bin/sh", ["-c", 'command -v "$0"', args.via], { encoding: "utf8" }).stdout.trim();
109
+ if (!via.startsWith("/")) {
110
+ fail(`--via ${args.via}: no such command on PATH. The schedule is unchanged.`);
111
+ return 1;
112
+ }
113
+ }
114
+ const script = installCopy(fileURLToPath(new URL("..", import.meta.url)), paths.installRoot, VERSION);
115
+ const runtime = stableRuntime(process.execPath);
116
+ const probe = spawnSync(runtime, [script, "--version"], { encoding: "utf8" });
117
+ if (probe.status !== 0 || probe.stdout.trim() !== VERSION) {
118
+ fail(`The installed copy ${script} did not start (${probe.error?.message ?? `exit ${probe.status}: ${probe.stderr.trim()}`}). The schedule is unchanged.`);
119
+ return 1;
120
+ }
121
+ const run = spawnSync(runtime, [script, "sync", ...(args.quiet ? ["--quiet"] : [])], { stdio: "inherit" });
122
+ if (run.status === AUTH_FAILED)
123
+ return AUTH_FAILED;
124
+ if (run.status !== 0 && run.status !== INCOMPLETE) {
125
+ fail(`The installed copy's first sync ended with ${run.signal ?? `exit ${run.status}`}. The schedule is unchanged.`);
126
+ return 1;
127
+ }
128
+ const env = {};
129
+ for (const name of PASSED_ENV)
130
+ if (process.env[name])
131
+ env[name] = process.env[name];
132
+ if (via && process.env.PATH)
133
+ env.PATH = process.env.PATH; // the --via command finds its own tools
134
+ const what = installSchedule({ node: runtime, script, logFile: paths.logFile, env, via }, { platform: process.platform });
135
+ pruneVersions(paths.installRoot, VERSION); // only now: a failed install keeps the old schedule's script
136
+ say(`Installed: sync every 10 minutes (${what}), running ${tilde(script)}.\nLog: ${tilde(paths.logFile)}. Check it with: npx conare sync status. Stop it with: npx conare sync --uninstall`);
137
+ return run.status ?? 1;
138
+ }
139
+ async function syncSessions(args, paths, apiKey, say, fail) {
140
+ const started = Date.now();
141
+ const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES }) : undefined;
142
+ const files = findTranscripts(paths);
143
+ say(`Found ${files.length} transcripts.`);
144
+ let report;
145
+ let error;
146
+ let code;
147
+ try {
148
+ report = await runSync({
149
+ files,
150
+ stateFile: paths.stateFile,
151
+ account: client ? accountOf(client.baseURL, apiKey) : "",
152
+ client: args.dryRun ? undefined : client,
153
+ log: say,
154
+ });
155
+ if (args.dryRun) {
156
+ for (const p of report.planned)
157
+ say(` ${p.id} ${formatBytes(p.bytes)}`);
158
+ say(`Would upload ${report.documents} documents from ${report.sessions} sessions (${formatBytes(report.bytes)}). ${report.unchanged} unchanged.`);
159
+ return { code: 0 };
160
+ }
161
+ for (const r of report.rejected)
162
+ fail(`Not accepted, tried again next run: ${r.id}: ${r.message}`);
163
+ say(report.documents > 0 || report.deleted > 0
164
+ ? `Synced ${report.sessions} sessions: ${report.documents} documents, ${formatBytes(report.bytes)}. ${report.unchanged} unchanged.`
165
+ : `Up to date: ${report.unchanged} sessions.`);
166
+ code = report.rejected.length > 0 ? INCOMPLETE : 0;
167
+ if (code)
168
+ error = `${report.rejected.length} documents not accepted`;
169
+ }
170
+ catch (err) {
171
+ if (err instanceof ConareError && (err.status === 401 || err.status === 403)) {
172
+ error = `The API key was refused (${err.status} ${err.code}).`;
173
+ fail(`${error} Save a valid one: npx conare sync --key sk-conare-…`);
174
+ code = AUTH_FAILED;
175
+ }
176
+ else {
177
+ const detail = err instanceof ConareError ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})` : String(err);
178
+ error = `Sync stopped: ${detail}`;
179
+ fail(`${error}. What was uploaded is saved; the rest is tried next run.`);
180
+ code = err instanceof ConareError ? INCOMPLETE : 1; // anything else is a bug or a broken machine
181
+ }
182
+ }
183
+ recordRun(paths, {
184
+ at: new Date(started).toISOString(),
185
+ durationMs: Date.now() - started,
186
+ ok: code === 0,
187
+ uploaded: report?.documents ?? 0,
188
+ skipped: report?.unchanged ?? 0,
189
+ failed: report?.rejected.length ?? 0,
190
+ deleted: report?.deleted ?? 0,
191
+ ...(error ? { error } : {}),
192
+ }, report?.newest);
193
+ return { code };
194
+ }
195
+ async function syncGitHub(args, paths, apiKey, say, fail) {
196
+ const token = githubToken();
197
+ if (!token) {
198
+ fail("No GitHub token: set GITHUB_TOKEN, or log in with `gh auth login`.");
199
+ return 1;
200
+ }
201
+ const gh = new GitHub(token, { baseURL: process.env.GITHUB_API_URL || undefined, graphqlURL: process.env.GITHUB_GRAPHQL_URL || undefined });
202
+ const client = apiKey ? new Conare({ apiKey, maxRetries: MAX_RETRIES }) : undefined;
203
+ const account = client ? accountOf(client.baseURL, apiKey) : undefined;
204
+ const stateFile = args.state ?? paths.githubStateFile;
205
+ const release = args.dryRun ? () => { } : acquireLock(`${stateFile}.lock`);
206
+ if (!release) {
207
+ fail(`Another github sync is using ${stateFile}.`);
208
+ return 1;
209
+ }
210
+ let code = 0;
211
+ try {
212
+ const state = loadGitHubState(stateFile);
213
+ for (const repo of args.repos) {
214
+ const started = Date.now();
215
+ const name = repo.slice(repo.indexOf("/") + 1);
216
+ // State written for another key or server starts from nothing (a dry run without a key reuses it).
217
+ const saved = state.repos[repo] ?? {};
218
+ const repoState = account === undefined || saved.account === account ? saved : {};
219
+ try {
220
+ const { report, state: next } = await syncRepo({
221
+ gh,
222
+ repo,
223
+ namespaces: client ? { github: client.namespace(`${name}-github`), docs: client.namespace(`${name}-docs`) } : undefined,
224
+ dryRun: args.dryRun,
225
+ state: repoState,
226
+ log: say,
227
+ });
228
+ const t = report.threads;
229
+ const d = report.docs;
230
+ const secs = ((Date.now() - started) / 1000).toFixed(1);
231
+ if (args.dryRun) {
232
+ say(`${repo}: would upload ${t.changed} threads to ${name}-github and ${d.uploaded} docs to ${name}-docs (${d.files} markdown files)${client ? `, delete ${d.deleted} docs` : ""}; ${gh.calls} GitHub requests, ${secs} s.`);
233
+ }
234
+ else {
235
+ state.repos[repo] = { ...next, account };
236
+ saveGitHubState(stateFile, state);
237
+ for (const r of report.rejected)
238
+ fail(`${repo}: not accepted, tried again next run: ${r}`);
239
+ say(`${repo}: threads ${t.changed} changed, ${t.uploaded - t.unchanged} written, ${t.unchanged} unchanged, ${t.failed} failed; docs ${d.files} files, ${d.changed} changed, ${d.uploaded - d.unchanged} written, ${d.unchanged} unchanged, ${d.failed} failed, ${d.deleted} deleted; ${gh.calls} GitHub requests, ${secs} s.`);
240
+ if (report.rejected.length > 0 && code === 0)
241
+ code = INCOMPLETE;
242
+ }
243
+ }
244
+ catch (err) {
245
+ if (err instanceof ConareError && (err.status === 401 || err.status === 403)) {
246
+ fail(`The API key was refused (${err.status} ${err.code}).`);
247
+ return AUTH_FAILED;
248
+ }
249
+ const detail = err instanceof ConareError
250
+ ? `${err.message} (${err.status || err.code}${err.requestId ? `, request ${err.requestId}` : ""})`
251
+ : err instanceof GitHubError || err instanceof Error
252
+ ? err.message
253
+ : String(err);
254
+ fail(`${repo}: sync stopped: ${detail}. The state is unchanged; the next run tries again.`);
255
+ code = err instanceof ConareError || err instanceof GitHubError ? (code === 1 ? 1 : INCOMPLETE) : 1;
256
+ }
257
+ }
258
+ }
259
+ finally {
260
+ release();
261
+ }
262
+ return code;
263
+ }
264
+ function tilde(path) {
265
+ const home = homedir();
266
+ return path.startsWith(home) ? `~${path.slice(home.length)}` : path;
267
+ }
268
+ main(process.argv.slice(2)).then((code) => {
269
+ process.exitCode = code;
270
+ }, (err) => {
271
+ console.error(err instanceof Error ? err.message : String(err));
272
+ process.exitCode = 1;
273
+ });
@@ -0,0 +1,61 @@
1
+ // The project a session worked in: the name of its git repository, else its directory.
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname } from "node:path";
5
+ const cache = new Map();
6
+ /**
7
+ * "conare" for /home/me/conare/sdk, and also for a linked worktree of that repository
8
+ * (/home/me/conare/.claude/worktrees/agent-1, whose .git file points into conare/.git).
9
+ * Falls back to the directory's own name when no repository is found (or it was deleted).
10
+ */
11
+ export function projectName(cwd) {
12
+ if (!cwd)
13
+ return undefined;
14
+ if (!cache.has(cwd))
15
+ cache.set(cwd, resolve(cwd));
16
+ return cache.get(cwd);
17
+ }
18
+ function resolve(cwd) {
19
+ const path = slashes(cwd).replace(/(.)\/+$/, "$1");
20
+ const home = slashes(homedir());
21
+ // The home directory itself is never the project (a dotfiles repo would claim everything).
22
+ for (let dir = path; dir !== home;) {
23
+ const found = repoRoot(dir);
24
+ if (found)
25
+ return name(found);
26
+ const parent = slashes(dirname(dir));
27
+ if (parent === dir)
28
+ break;
29
+ dir = parent;
30
+ }
31
+ // Claude Code puts agent worktrees at <repo>/.claude/worktrees/<name>.
32
+ const at = path.indexOf("/.claude/worktrees/");
33
+ return name(at > 0 ? path.slice(0, at) : path);
34
+ }
35
+ /** dir when it holds a repository; for a linked worktree, the main checkout. */
36
+ function repoRoot(dir) {
37
+ const git = `${dir === "/" ? "" : dir}/.git`;
38
+ try {
39
+ if (statSync(git).isDirectory())
40
+ return dir;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ // A .git file: "gitdir: /repo/.git/worktrees/<name>" for a worktree. A submodule's
46
+ // points into the superproject's .git/modules and is a repository of its own.
47
+ try {
48
+ const gitdir = slashes(/^gitdir:\s*(.+)$/m.exec(readFileSync(git, "utf8"))?.[1]?.trim() ?? "");
49
+ const at = gitdir.indexOf("/.git/worktrees/");
50
+ return at > 0 ? gitdir.slice(0, at) : dir;
51
+ }
52
+ catch {
53
+ return dir;
54
+ }
55
+ }
56
+ function slashes(path) {
57
+ return path.replace(/\\/g, "/");
58
+ }
59
+ function name(dir) {
60
+ return dir.split("/").filter(Boolean).pop();
61
+ }
@@ -0,0 +1,69 @@
1
+ // Transcript → readable text: a short header, then the turns under role lines ("[User · …]",
2
+ // "[Assistant]"), with tool calls as one line each ("→ $ bun test") and kept tool output
3
+ // indented under the call.
4
+ /** "2026-09-30 12:45 UTC" from an RFC 3339 string. */
5
+ export function displayTime(iso) {
6
+ return iso ? `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC` : undefined;
7
+ }
8
+ export function renderHeader(t, project) {
9
+ const lines = [`# ${t.agent}`];
10
+ const add = (label, value) => {
11
+ if (value)
12
+ lines.push(`${label}: ${value}`);
13
+ };
14
+ add("Title", t.title?.replace(/\s+/g, " ").trim());
15
+ add("Project", project);
16
+ add("Directory", t.cwd);
17
+ add("Branch", t.branch);
18
+ add("Session", t.sessionId);
19
+ add("Agent", t.agentId);
20
+ add("Started", displayTime(t.startedAt));
21
+ add("Ended", displayTime(t.endedAt));
22
+ return lines.join("\n");
23
+ }
24
+ /** The whole document text. Consecutive messages of one role share a heading. */
25
+ export function render(t, project) {
26
+ const blocks = [renderHeader(t, project)];
27
+ let role;
28
+ let lastWasLine = false;
29
+ for (const m of t.messages) {
30
+ if (m.role !== role || m.time) {
31
+ blocks.push(heading(m));
32
+ role = m.role;
33
+ lastWasLine = false;
34
+ }
35
+ for (const part of m.parts) {
36
+ const line = part.type !== "text";
37
+ const text = renderPart(part);
38
+ // Tool lines, outputs and events stack without blank lines between them.
39
+ if (line && lastWasLine)
40
+ blocks[blocks.length - 1] += `\n${text}`;
41
+ else
42
+ blocks.push(text);
43
+ lastWasLine = line;
44
+ }
45
+ }
46
+ return `${blocks.join("\n\n")}\n`;
47
+ }
48
+ // "[User · 2026-09-30 12:45 UTC]": agents write markdown headings of their own, so a role
49
+ // line has a shape of its own.
50
+ function heading(m) {
51
+ const time = displayTime(m.time);
52
+ return `[${m.role}${time ? ` · ${time}` : ""}]`;
53
+ }
54
+ function renderPart(part) {
55
+ switch (part.type) {
56
+ case "text":
57
+ return part.text;
58
+ case "tool":
59
+ return `→ ${indent(part.text, " ")}`;
60
+ case "output":
61
+ return ` ${part.error ? "✗" : "←"} ${indent(part.text, " ")}`;
62
+ case "event":
63
+ return `· ${part.text}`;
64
+ }
65
+ }
66
+ /** Continuation lines of a multi-line value, indented under its first line. */
67
+ function indent(text, pad) {
68
+ return text.replace(/\n/g, `\n${pad}`);
69
+ }