convergedev 0.0.0-stage → 0.1.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.
Files changed (46) hide show
  1. package/LICENSE.md +34 -0
  2. package/THIRD_PARTY_NOTICES.md +149 -0
  3. package/dist/agent-execution.js +103 -0
  4. package/dist/agent-process.js +70 -0
  5. package/dist/agent.js +2 -0
  6. package/dist/anchors.js +101 -0
  7. package/dist/applications.js +69 -0
  8. package/dist/apply-proposal.js +236 -0
  9. package/dist/bridge-health.js +57 -0
  10. package/dist/bridge.js +203 -0
  11. package/dist/change-proposals.js +51 -0
  12. package/dist/claude.js +277 -0
  13. package/dist/cli.js +278 -0
  14. package/dist/commands.js +80 -0
  15. package/dist/comment-file.js +41 -0
  16. package/dist/comment-host.js +96 -0
  17. package/dist/config.js +43 -0
  18. package/dist/converge.js +36 -0
  19. package/dist/exec.js +52 -0
  20. package/dist/follow-branch.js +70 -0
  21. package/dist/git.js +169 -0
  22. package/dist/hunks.js +558 -0
  23. package/dist/implementation-results.js +98 -0
  24. package/dist/implementation-runner.js +262 -0
  25. package/dist/queries/ecmascript.scm +35 -0
  26. package/dist/queries/javascript.scm +6 -0
  27. package/dist/queries/python.scm +10 -0
  28. package/dist/queries/typescript.scm +16 -0
  29. package/dist/relay.js +32 -0
  30. package/dist/runner.js +104 -0
  31. package/dist/sandbox.js +53 -0
  32. package/dist/session-state.js +36 -0
  33. package/dist/setup.js +328 -0
  34. package/dist/share-review.js +34 -0
  35. package/dist/shared.js +193 -0
  36. package/dist/skill/converge/SKILL.md +25 -0
  37. package/dist/skill/converge/converge.mjs +35 -0
  38. package/dist/skill-link.js +100 -0
  39. package/dist/worktree.js +231 -0
  40. package/grammars/SOURCES.json +22 -0
  41. package/grammars/tree-sitter-javascript.wasm +0 -0
  42. package/grammars/tree-sitter-python.wasm +0 -0
  43. package/grammars/tree-sitter-tsx.wasm +0 -0
  44. package/grammars/tree-sitter-typescript.wasm +0 -0
  45. package/package.json +45 -4
  46. package/README.md +0 -3
@@ -0,0 +1,41 @@
1
+ // The room's comments, kept on the owner's machine (docs/review-room.md decision 15). One small file per repository
2
+ // and branch, next to config.json, so a room opened on the same branch later starts with the discussion so far.
3
+ // Leaving a room keeps the file; nothing else on the machine reads it.
4
+ import { createHash } from 'node:crypto';
5
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
6
+ import { basename, dirname, join } from 'node:path';
7
+ import { configPath } from './config.js';
8
+ export const commentsDir = () => join(dirname(configPath()), 'comments');
9
+ const slug = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 60);
10
+ /**
11
+ * The file for a repository (its remote's address, or its folder when it has none) and branch. The name is readable
12
+ * for someone looking in the folder; the hash keeps two repositories with the same folder name apart.
13
+ */
14
+ export function commentFilePath(repoKey, branch) {
15
+ const hash = createHash('sha256').update(`${repoKey}\n${branch}`).digest('hex').slice(0, 12);
16
+ return join(commentsDir(), `${slug(basename(repoKey.replace(/\.git$/, '')))}--${slug(branch)}--${hash}.json`);
17
+ }
18
+ /** The file's contents, or null when there is none yet (or it cannot be read, which starts the room afresh). */
19
+ export async function loadCommentFile(path) {
20
+ try {
21
+ return JSON.parse(await readFile(path, 'utf8'));
22
+ }
23
+ catch (err) {
24
+ if (err?.code !== 'ENOENT')
25
+ console.warn(`Ignoring unreadable ${path}:`, err.message);
26
+ return null;
27
+ }
28
+ }
29
+ // Saves to one path run one after another: two at once would write the same temporary file and could leave a torn one.
30
+ const pending = new Map();
31
+ /** Writes the file whole (a temporary file, then a rename), readable only by this user. */
32
+ export function saveCommentFile(path, file) {
33
+ const save = async () => {
34
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
35
+ await writeFile(`${path}.tmp`, JSON.stringify(file), { mode: 0o600 });
36
+ await rename(`${path}.tmp`, path);
37
+ };
38
+ const next = (pending.get(path) ?? Promise.resolve()).then(save, save);
39
+ pending.set(path, next);
40
+ return next;
41
+ }
@@ -0,0 +1,96 @@
1
+ // The owner's agent as the keeper of the room's comments (docs/review-room.md, "Comments that survive change"). It
2
+ // opens the comment file for the room's repository and branch before the bridge connects, so the first state the room
3
+ // gets already has them; on becoming host and after every new snapshot it matches them to the code the room shows
4
+ // (anchors.ts); and it saves the file after every change. A reviewer's agent keeps no comments: it gets an empty
5
+ // store that the relay never asks it for.
6
+ import { rematch } from './anchors.js';
7
+ import { commentFilePath, loadCommentFile, saveCommentFile } from './comment-file.js';
8
+ import { loadConfig, saveRoom } from './config.js';
9
+ import { collectRepository } from './git.js';
10
+ import { api, OWNER_ROLE, RelayError } from './relay.js';
11
+ import { roomBranch } from './share-review.js';
12
+ import { SharedStore } from './shared.js';
13
+ const EMPTY = { rev: 0, next_num: 1, reserved: [], comments: [] };
14
+ /** The branch of a room whose snapshot was taken on a detached HEAD: its comments are filed under this name. */
15
+ const DETACHED = 'HEAD';
16
+ /** Asks the relay until it answers (it may be restarting), backing off to 30 s; a refusal (4xx) is final. */
17
+ async function selfStatus(room) {
18
+ for (let waitMs = 1000;; waitMs = Math.min(waitMs * 2, 30_000)) {
19
+ try {
20
+ return await api('/agent-grants/self', { token: room.agentToken, base: room.apiUrl });
21
+ }
22
+ catch (err) {
23
+ if (err instanceof RelayError && err.status < 500)
24
+ return null;
25
+ console.error(`Could not reach the relay to load the room's comments (trying again in ${waitMs / 1000}s): ${err.message}`);
26
+ await new Promise((r) => setTimeout(r, waitMs));
27
+ }
28
+ }
29
+ }
30
+ /** The repository's identity for the comment file: its remote's address, or its folder when it has none. */
31
+ async function repositoryOf(projectDir) {
32
+ try {
33
+ const { repository } = await collectRepository(projectDir);
34
+ return { repo: repository.repo, remote: repository.remote, key: repository.remote ?? projectDir };
35
+ }
36
+ catch {
37
+ return { repo: projectDir, remote: null, key: projectDir };
38
+ }
39
+ }
40
+ export async function openCommentHost(room) {
41
+ const shared = new SharedStore();
42
+ const session = await selfStatus(room);
43
+ if (session?.role !== OWNER_ROLE)
44
+ return { shared, refresh: async () => false, save: async () => { } };
45
+ const repository = await repositoryOf(room.projectDir);
46
+ let branch = '', path = '';
47
+ const contents = () => ({ repo: repository.repo, remote: repository.remote, branch, state: shared.get() });
48
+ const save = () => saveCommentFile(path, contents()).catch((err) => console.error(`Could not save the room's comments to ${path}: ${err.message}`));
49
+ /** Files the room under `to`: saves what it holds, starts from that branch's file, and tells `leave` where it is. */
50
+ const open = async (to) => {
51
+ if (path)
52
+ await save();
53
+ branch = to;
54
+ path = commentFilePath(repository.key, branch);
55
+ const file = await loadCommentFile(path);
56
+ shared.restore(file?.state ?? EMPTY);
57
+ const stored = (await loadConfig()).rooms[room.roomId];
58
+ if (stored && stored.commentsFile !== path)
59
+ await saveRoom({ ...stored, commentsFile: path });
60
+ if (file?.state.comments.length)
61
+ console.log(`Loaded ${file.state.comments.length} comments for ${branch} from ${path}`);
62
+ };
63
+ await open(roomBranch(session) ?? DETACHED);
64
+ // The head the relay last announced: two shares close together can answer out of order, and an older snapshot
65
+ // fetched after a newer one was announced is not matched against.
66
+ let announced;
67
+ let running = Promise.resolve(false);
68
+ const match = async () => {
69
+ let review;
70
+ try {
71
+ review = await api('/agent-grants/self/review', { token: room.agentToken, base: room.apiUrl });
72
+ }
73
+ catch (err) {
74
+ if (!(err instanceof RelayError && err.status === 404))
75
+ console.error(`Could not fetch the room's changes to match comments: ${err.message}`);
76
+ return false;
77
+ }
78
+ if (announced && review.head_sha !== announced)
79
+ return false;
80
+ const to = review.branch && review.branch !== DETACHED ? review.branch : DETACHED;
81
+ const switched = to !== branch;
82
+ if (switched)
83
+ await open(to);
84
+ const moved = shared.relocate(rematch(shared.get().comments, review));
85
+ if (switched || moved)
86
+ await save();
87
+ return switched || moved;
88
+ };
89
+ // Without a head (on becoming host again, after a drop), whatever the room shows now is what to match.
90
+ const refresh = (announcedHead) => {
91
+ announced = announcedHead;
92
+ running = running.then(match, match);
93
+ return running;
94
+ };
95
+ return { shared, refresh, save };
96
+ }
package/dist/config.js ADDED
@@ -0,0 +1,43 @@
1
+ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ export const configPath = () => resolve(process.env.AGENT_REVIEW_CONFIG ?? join(homedir(), '.agent-review', 'config.json'));
5
+ // Kept next to the config: each room's Claude session ID, and the log of the agent a /converge command left running.
6
+ export const sessionStatePath = () => resolve(process.env.SESSION_STATE_FILE ?? join(dirname(configPath()), 'sessions.json'));
7
+ export const logPath = (roomId) => join(dirname(configPath()), 'logs', `${roomId}.log`);
8
+ export async function loadConfig() {
9
+ try {
10
+ const parsed = JSON.parse(await readFile(configPath(), 'utf8'));
11
+ return { rooms: parsed?.rooms && typeof parsed.rooms === 'object' ? parsed.rooms : {} };
12
+ }
13
+ catch (err) {
14
+ if (err?.code !== 'ENOENT')
15
+ console.warn(`Ignoring unreadable ${configPath()}:`, err.message);
16
+ return { rooms: {} };
17
+ }
18
+ }
19
+ export async function saveConfig(config) {
20
+ const path = configPath();
21
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
22
+ await writeFile(`${path}.tmp`, JSON.stringify(config, null, 2), { mode: 0o600 });
23
+ await rename(`${path}.tmp`, path);
24
+ }
25
+ /** Stores one room, replacing what was stored for it and keeping the others. */
26
+ export async function saveRoom(room) {
27
+ const config = await loadConfig();
28
+ config.rooms[room.roomId] = room;
29
+ await saveConfig(config);
30
+ }
31
+ /** Accepts a bare room ID or any URL whose path contains /rooms/<id>. */
32
+ export function parseRoomRef(ref) {
33
+ const value = ref.trim();
34
+ if (/^https?:\/\//i.test(value)) {
35
+ const match = new URL(value).pathname.match(/\/rooms\/([^/]+)/);
36
+ if (!match)
37
+ throw new Error(`No room ID found in URL: ${value}`);
38
+ return decodeURIComponent(match[1]);
39
+ }
40
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(value))
41
+ throw new Error(`Not a room ID or room URL: ${value}`);
42
+ return value;
43
+ }
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // The `converge` command the package installs (npm install -g convergedev; docs/review-room.md, decision 40). It sets
3
+ // Converge up and checks it, nothing more: rooms are created, joined and left only through /converge in Claude Code
4
+ // (commands.ts), so a room command typed here is pointed there instead of run.
5
+ import { readFileSync } from 'node:fs';
6
+ import { BRIDGE_VERSION } from './bridge-health.js';
7
+ import { diagnose, initialize, thisMachine } from './setup.js';
8
+ export const CONVERGE_USAGE = `Usage: converge [--yes] set up Converge, or check it is still set up (asks before installing the skill)
9
+ converge doctor check Converge, the relay and your saved rooms, changing nothing
10
+ converge --version
11
+
12
+ Rooms are opened and joined from Claude Code: /converge review, /converge build "<task>", /converge join ...`;
13
+ /** The package's version, from its package.json (one level up from dist/ or src/). */
14
+ const version = () => JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
15
+ async function main(args) {
16
+ const [first, ...rest] = args;
17
+ if (first === '--version' || first === '-v') {
18
+ console.log(`convergedev ${version()} (bridge protocol ${BRIDGE_VERSION})`);
19
+ return 0;
20
+ }
21
+ if (first === 'help' || first === '--help' || first === '-h') {
22
+ console.log(CONVERGE_USAGE);
23
+ return 0;
24
+ }
25
+ if (first === 'doctor' && !rest.length) {
26
+ console.log(`Converge ${version()}: checking this machine, the relay and your rooms`);
27
+ return diagnose(thisMachine());
28
+ }
29
+ if (first === undefined || (first === '--yes' && !rest.length)) {
30
+ console.log(`Converge ${version()}: setting up`);
31
+ return initialize(thisMachine(), { yes: first === '--yes' });
32
+ }
33
+ console.error(`converge does not take "${args.join(' ')}". In Claude Code, room commands are /converge <command>.\n\n${CONVERGE_USAGE}`);
34
+ return 1;
35
+ }
36
+ process.exitCode = await main(process.argv.slice(2));
package/dist/exec.js ADDED
@@ -0,0 +1,52 @@
1
+ import { accessSync, constants } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { delimiter, dirname, extname, join } from 'node:path';
4
+ export const describeCommand = (c) => [c.command, ...c.prefix].join(' ');
5
+ export const runnable = (file) => { try {
6
+ accessSync(file, constants.X_OK);
7
+ return true;
8
+ }
9
+ catch {
10
+ return false;
11
+ } };
12
+ /** Finds an agent CLI the way a shell would, resolving to what the shell would ultimately run. */
13
+ export function findExecutable(lookup) {
14
+ const win = (lookup.platform ?? process.platform) === 'win32';
15
+ const home = lookup.home ?? homedir();
16
+ const expand = (p) => p.replace(/^~(?=$|[\\/])/, home);
17
+ const fromFile = (file) => {
18
+ if (!runnable(file))
19
+ return undefined;
20
+ const ext = extname(file).toLowerCase();
21
+ if (['.js', '.cjs', '.mjs'].includes(ext))
22
+ return { command: process.execPath, prefix: [file] };
23
+ if (win && ['.cmd', '.bat'].includes(ext))
24
+ return unwrapShim(dirname(file));
25
+ return { command: file, prefix: [] };
26
+ };
27
+ // A shim whose package is gone (half-finished upgrade) resolves to nothing rather than to a broken command.
28
+ const unwrapShim = (dir) => {
29
+ if (!lookup.npmPackage)
30
+ return undefined;
31
+ for (const target of lookup.shimTargets ?? []) {
32
+ const found = fromFile(join(dir, 'node_modules', lookup.npmPackage, target));
33
+ if (found)
34
+ return found;
35
+ }
36
+ return undefined;
37
+ };
38
+ if (lookup.override)
39
+ return fromFile(expand(lookup.override));
40
+ const dirs = [...(lookup.path ?? process.env.PATH ?? '').split(delimiter), ...(lookup.extraDirs ?? []).map(expand)];
41
+ const names = win ? ['.exe', '.cmd', '.bat'].map((ext) => lookup.name + ext) : [lookup.name];
42
+ for (const dir of dirs) {
43
+ if (!dir)
44
+ continue;
45
+ for (const name of names) {
46
+ const found = fromFile(join(dir, name));
47
+ if (found)
48
+ return found;
49
+ }
50
+ }
51
+ return undefined;
52
+ }
@@ -0,0 +1,70 @@
1
+ // The owner's bridge following the room's branch on the owner's machine (docs/review-room.md decision 15, "New
2
+ // commits"). Each interval it reads where the branch points and, when that has moved since it last shared, shares it:
3
+ // a commit reaches the room within seconds, without a command. It never fetches. Ticks never overlap, and an error
4
+ // waits for the next one.
5
+ import { loadConfig } from './config.js';
6
+ import { commitOf, GitReviewError, localRef } from './git.js';
7
+ import { api, OWNER_ROLE, RelayError } from './relay.js';
8
+ import { roomBranch, shareReview } from './share-review.js';
9
+ /** Reading a ref is a cheap local `rev-parse`, so a short interval keeps "within seconds" true. */
10
+ export const FOLLOW_INTERVAL_MS = 5_000;
11
+ /**
12
+ * A share that will fail the same way however often it is retried: the relay refused this snapshot (too large, not
13
+ * allowed), or git cannot make one (no base). The next commit is tried; this one is not sent again.
14
+ */
15
+ const refusedForGood = (err) => err instanceof GitReviewError || (err instanceof RelayError && err.status >= 400 && err.status < 500);
16
+ /**
17
+ * Follows the room's branch for `room` if this is the owner's agent, starting at once. The first tick asks the relay
18
+ * whose agent this is, which branch the room shows and at which commit, and is retried until it answers, so a relay
19
+ * that is briefly down never stops the agent from starting. After that the stored room is read on each tick: the
20
+ * branch and base the last `/converge update` shared are the ones followed. Returns a function that stops it.
21
+ */
22
+ export function followBranch(opts) {
23
+ const { room, intervalMs = FOLLOW_INTERVAL_MS } = opts;
24
+ let known;
25
+ let stopped = false;
26
+ let timer;
27
+ const tick = async () => {
28
+ let branch;
29
+ try {
30
+ if (!known) {
31
+ const session = await api('/agent-grants/self', { token: room.agentToken, base: room.apiUrl });
32
+ if (session.role !== OWNER_ROLE) {
33
+ stopped = true;
34
+ return;
35
+ }
36
+ known = { branch: roomBranch(session), shared: session.review?.head_sha };
37
+ console.log(`Following ${known.branch ? `branch ${known.branch}` : "the room's branch once /converge update shares one"}: new commits reach the room by themselves`);
38
+ }
39
+ const stored = (await loadConfig()).rooms[room.roomId] ?? room;
40
+ branch = stored.branch !== undefined ? stored.branch : known.branch;
41
+ const ref = branch ? await localRef(stored.projectDir, branch) : null;
42
+ const head = ref ? await commitOf(stored.projectDir, ref) : null;
43
+ if (!ref || !head || head === known.shared)
44
+ return;
45
+ try {
46
+ const { snapshot } = await shareReview(stored, { ref });
47
+ const newest = snapshot.commits[0];
48
+ console.log(`Shared ${branch} at ${head.slice(0, 7)}${newest ? `: "${newest.subject}" by ${newest.author}` : ''}`);
49
+ }
50
+ catch (err) {
51
+ // A task room whose branch has nothing past its starting commit yet is quiet until the branch moves.
52
+ if (!(err instanceof GitReviewError && err.kind === 'no-changes')) {
53
+ if (!refusedForGood(err))
54
+ throw err;
55
+ console.error(`Could not share ${branch} at ${head.slice(0, 7)}; trying again at its next commit: ${err.message}`);
56
+ }
57
+ }
58
+ known.shared = head;
59
+ }
60
+ catch (err) {
61
+ console.error(`Could not share ${branch ?? "the room's branch"} (trying again in ${intervalMs / 1000}s): ${err.message}`);
62
+ }
63
+ finally {
64
+ if (!stopped)
65
+ timer = setTimeout(tick, intervalMs);
66
+ }
67
+ };
68
+ void tick();
69
+ return () => { stopped = true; clearTimeout(timer); };
70
+ }
package/dist/git.js ADDED
@@ -0,0 +1,169 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { basename } from 'node:path';
3
+ import { promisify } from 'node:util';
4
+ import { collectHunks } from './hunks.js';
5
+ const run = promisify(execFile);
6
+ const MAX_DIFF_CHARS = 900_000; // the API accepts up to 1,000,000
7
+ const MAX_COMMITS = 500;
8
+ export class GitReviewError extends Error {
9
+ kind;
10
+ constructor(kind, message) {
11
+ super(message);
12
+ this.kind = kind;
13
+ }
14
+ }
15
+ /**
16
+ * Runs git without a shell: every argument reaches git as it is, whatever it contains. Hidden because the detached
17
+ * bridge has no console, so Windows would open a new window for every call (runner.ts hides the agent the same way).
18
+ */
19
+ export async function git(cwd, args) {
20
+ const { stdout } = await run('git', ['-c', 'core.quotepath=off', ...args], { cwd, maxBuffer: 64 * 1024 * 1024, windowsHide: true });
21
+ return stdout;
22
+ }
23
+ const exists = (cwd, ref) => git(cwd, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).then(() => true, () => false);
24
+ /** The branch a pull request would target: origin's default branch, else a conventional local one. */
25
+ async function detectBase(cwd) {
26
+ const originHead = (await git(cwd, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']).catch(() => '')).trim();
27
+ for (const ref of [originHead, 'origin/main', 'origin/master', 'main', 'master']) {
28
+ if (ref && await exists(cwd, ref))
29
+ return ref;
30
+ }
31
+ throw new GitReviewError('no-base', 'Could not find a base branch (main/master). Pass --base <ref>.');
32
+ }
33
+ /**
34
+ * Snapshot of the committed changes on `headRef` since it diverged from `baseRef`. Uncommitted changes are excluded,
35
+ * and `dirty` says whether there are any (only meaningful for HEAD, the checkout).
36
+ */
37
+ export async function collectReview(cwd, baseRef, headRef = 'HEAD') {
38
+ let top;
39
+ try {
40
+ top = (await git(cwd, ['rev-parse', '--show-toplevel'])).trim();
41
+ }
42
+ catch {
43
+ throw new GitReviewError('not-a-repo', `${cwd} is not a git repository.`);
44
+ }
45
+ const head = (await git(top, ['rev-parse', '--verify', `${headRef}^{commit}`])).trim();
46
+ const branch = headRef === 'HEAD' ? (await git(top, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim() : branchName(headRef);
47
+ const base = baseRef ?? await detectBase(top);
48
+ if (!await exists(top, base))
49
+ throw new GitReviewError('no-base', `Base ref not found: ${base}`);
50
+ const baseSha = (await git(top, ['merge-base', base, head])).trim();
51
+ const commits = (await git(top, ['log', `--max-count=${MAX_COMMITS}`, '--format=%H%x1f%an%x1f%s', `${baseSha}..${head}`]))
52
+ .split('\n').filter(Boolean).map((line) => {
53
+ const [sha, author, subject] = line.split('\x1f');
54
+ return { sha, author, subject: subject.slice(0, 500) };
55
+ });
56
+ if (!commits.length) {
57
+ throw new GitReviewError('no-changes', `No commits on ${branch} since ${base}. Commit your changes on a branch, ` +
58
+ 'or pass --base <ref> (for example --base HEAD~1).');
59
+ }
60
+ const added = new Set(), deleted = new Set();
61
+ for (const line of (await git(top, ['diff', '--name-status', '--no-renames', baseSha, head])).split('\n')) {
62
+ const [code, ...path] = line.split('\t');
63
+ if (code === 'A')
64
+ added.add(path.join('\t'));
65
+ if (code === 'D')
66
+ deleted.add(path.join('\t'));
67
+ }
68
+ const files = (await git(top, ['diff', '--numstat', '--no-renames', baseSha, head])).split('\n').filter(Boolean).map((line) => {
69
+ const [add, del, ...parts] = line.split('\t');
70
+ const path = parts.join('\t');
71
+ // numstat gives no line counts ("-") for a binary file, whether it was added, changed or deleted.
72
+ const status = add === '-' ? 'binary' : added.has(path) ? 'added' : deleted.has(path) ? 'deleted' : 'modified';
73
+ return { path, additions: add === '-' ? null : Number(add), deletions: del === '-' ? null : Number(del), status };
74
+ });
75
+ const fullDiff = await git(top, ['diff', '--no-color', '--no-ext-diff', '--no-renames', baseSha, head]);
76
+ const dirty = headRef === 'HEAD' && (await git(top, ['status', '--porcelain', '--untracked-files=no'])).trim().length > 0;
77
+ const diff = fullDiff.slice(0, MAX_DIFF_CHARS), diff_truncated = fullDiff.length > MAX_DIFF_CHARS;
78
+ const hunks = await collectHunks({ cwd: top, baseSha, headSha: head, diff, diffTruncated: diff_truncated }).catch(() => []);
79
+ return {
80
+ dirty,
81
+ snapshot: {
82
+ repo: basename(top), branch, base_ref: base, base_sha: baseSha, head_sha: head, commits, files,
83
+ diff, diff_truncated, hunks,
84
+ },
85
+ };
86
+ }
87
+ const LOCAL_PREFIX = 'refs/heads/';
88
+ const branchName = (ref) => ref.replace(LOCAL_PREFIX, '');
89
+ /**
90
+ * A branch name as git accepts one, checked before it becomes a ref path. The room's branch comes from the relay, so
91
+ * a name such as `-x` or `a..b` must never reach git as an option or a range.
92
+ */
93
+ export async function validBranch(cwd, branch) {
94
+ if (!branch || branch === 'HEAD' || branch.startsWith('-'))
95
+ return false;
96
+ return git(cwd, ['check-ref-format', '--branch', branch]).then(() => true, () => false);
97
+ }
98
+ /** The local branch's full ref (`refs/heads/<branch>`), or null when the name is not valid or the branch is gone. */
99
+ export async function localRef(cwd, branch) {
100
+ if (!await validBranch(cwd, branch))
101
+ return null;
102
+ const ref = `${LOCAL_PREFIX}${branch}`;
103
+ return await exists(cwd, ref) ? ref : null;
104
+ }
105
+ /** The commit `ref` points at, or null when it does not exist. */
106
+ export async function commitOf(cwd, ref) {
107
+ return (await git(cwd, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]).catch(() => '')).trim() || null;
108
+ }
109
+ export function describeReview(s) {
110
+ const add = s.files.reduce((n, f) => n + (f.additions ?? 0), 0);
111
+ const del = s.files.reduce((n, f) => n + (f.deletions ?? 0), 0);
112
+ return `${s.branch} vs ${s.base_ref} (${s.base_sha.slice(0, 7)}..${s.head_sha.slice(0, 7)}): ` +
113
+ `${s.commits.length} commit${s.commits.length === 1 ? '' : 's'}, ${s.files.length} file${s.files.length === 1 ? '' : 's'}, +${add} −${del}`;
114
+ }
115
+ /** SSH authenticates with keys, so its user name is part of the address (git@…), never a secret. */
116
+ const SSH_SCHEMES = new Set(['ssh:', 'git+ssh:', 'ssh+git:']);
117
+ /**
118
+ * A remote as an address only, safe to show the room: no password or token, query or fragment, ever.
119
+ * - URL form: parsed, then stripped of the query, the fragment and all user info, except an SSH user name.
120
+ * https://ghp_x@github.com/acme/shop.git?access_token=y#z → https://github.com/acme/shop.git
121
+ * - scp form ([user[:password]@]host:path): the user is kept, the password, query and fragment dropped.
122
+ * - A plain local path is kept unless it contains @, ? or #.
123
+ * Anything that does not parse cleanly gives null: better no remote than a leaked secret. The API refuses the same
124
+ * things (apps/api/rooms.py RepositoryContext), in case another client sends them.
125
+ */
126
+ export function safeRemote(remote) {
127
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(remote)) {
128
+ let url;
129
+ try {
130
+ url = new URL(remote);
131
+ }
132
+ catch {
133
+ return null;
134
+ }
135
+ const keepsUser = SSH_SCHEMES.has(url.protocol.toLowerCase()) && url.username !== '';
136
+ if (!keepsUser)
137
+ url.username = '';
138
+ url.password = '';
139
+ url.search = '';
140
+ url.hash = '';
141
+ const safe = url.toString();
142
+ // An @ anywhere but an SSH user name (e.g. in the path) is ambiguous; the API refuses it, so send nothing.
143
+ return (safe.match(/@/g) ?? []).length > (keepsUser ? 1 : 0) ? null : safe;
144
+ }
145
+ const scp = remote.match(/^(?:([^@:/\s]+)(?::[^@\s]*)?@)?([^@:/\s]+):([^?#@\s]+)(?:[?#].*)?$/);
146
+ if (scp)
147
+ return `${scp[1] ? `${scp[1]}@` : ''}${scp[2]}:${scp[3]}`;
148
+ return /[@?#\s]/.test(remote) ? null : remote;
149
+ }
150
+ /**
151
+ * The repository a development session starts from: the commit checked out now, pinned, and where it lives. Only
152
+ * reads git (no checkout, branch, worktree or fetch), so the working tree is left exactly as it is.
153
+ */
154
+ export async function collectRepository(cwd) {
155
+ let top;
156
+ try {
157
+ top = (await git(cwd, ['rev-parse', '--show-toplevel'])).trim();
158
+ }
159
+ catch {
160
+ throw new GitReviewError('not-a-repo', `${cwd} is not a git repository.`);
161
+ }
162
+ const base_sha = (await git(top, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']).catch(() => '')).trim();
163
+ if (!base_sha)
164
+ throw new GitReviewError('no-commits', `${top} has no commits yet. Commit once so the session has a starting point.`);
165
+ const branch = (await git(top, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
166
+ const remote = (await git(top, ['remote', 'get-url', 'origin']).catch(() => '')).trim();
167
+ const dirty = (await git(top, ['status', '--porcelain', '--untracked-files=no'])).trim().length > 0;
168
+ return { dirty, repository: { repo: basename(top), remote: remote ? safeRemote(remote) : null, branch, base_sha } };
169
+ }