pi-roundtable-coding 0.43.0 → 0.44.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/src/git-run.ts ADDED
@@ -0,0 +1,120 @@
1
+ import {
2
+ AgentError,
3
+ checkRepoName,
4
+ childEnv,
5
+ scrubDiagnostic,
6
+ } from "pi-roundtable/kit";
7
+ import type { CloneCommand } from "./repo-types.ts";
8
+
9
+ const GIT_TIMEOUT_MS = 60_000;
10
+
11
+ /**
12
+ * Host variables git and gh need besides the shell's: their config files and homes, the identity a
13
+ * rebase commits as, ssh agent and ssh command, and gh's host; never a token, which comes from
14
+ * `githubToken`.
15
+ */
16
+ const GIT_ENV_NAMES = [
17
+ "XDG_CONFIG_HOME",
18
+ "GIT_CONFIG_GLOBAL",
19
+ "GIT_CONFIG_SYSTEM",
20
+ "GIT_CONFIG_NOSYSTEM",
21
+ "GIT_AUTHOR_NAME",
22
+ "GIT_AUTHOR_EMAIL",
23
+ "GIT_COMMITTER_NAME",
24
+ "GIT_COMMITTER_EMAIL",
25
+ "GH_CONFIG_DIR",
26
+ "GH_HOST",
27
+ "SSH_AUTH_SOCK",
28
+ "GIT_SSH",
29
+ "GIT_SSH_COMMAND",
30
+ ];
31
+
32
+ /** The environment of a git or gh call: the shell's whitelist, git's own names, and the token as GH_TOKEN. */
33
+ function gitEnv(token: string | undefined): Record<string, string> {
34
+ return childEnv(process.env, {
35
+ pass: GIT_ENV_NAMES,
36
+ ...(token ? { set: { GH_TOKEN: token } } : {}),
37
+ });
38
+ }
39
+
40
+ async function run(
41
+ command: string[],
42
+ cwd: string | undefined,
43
+ env: Record<string, string>,
44
+ ): Promise<{ out: string; err: string; code: number }> {
45
+ const safeCommand =
46
+ command[0] === "git"
47
+ ? [
48
+ "git",
49
+ "-c",
50
+ "core.fsmonitor=false",
51
+ "-c",
52
+ "core.hooksPath=/dev/null",
53
+ ...command.slice(1),
54
+ ]
55
+ : command;
56
+ const child = Bun.spawn(safeCommand, {
57
+ ...(cwd ? { cwd } : {}),
58
+ env,
59
+ stdout: "pipe",
60
+ stderr: "pipe",
61
+ timeout: GIT_TIMEOUT_MS,
62
+ });
63
+ const [out, err, code] = await Promise.all([
64
+ new Response(child.stdout).text(),
65
+ new Response(child.stderr).text(),
66
+ child.exited,
67
+ ]);
68
+ return { out: out.trimEnd(), err: err.trim(), code };
69
+ }
70
+
71
+ /**
72
+ * Clones with gh, which authenticates with `token` as GH_TOKEN (default the host's GH_TOKEN, read
73
+ * at each clone) or its own login; a failure's stderr is cut at `diagnosticChars`.
74
+ */
75
+ export const ghCloneWith =
76
+ (diagnosticChars?: number, token?: () => string | undefined): CloneCommand =>
77
+ async (repo, dir) => {
78
+ checkRepoName(repo);
79
+ if (repo.startsWith("-"))
80
+ throw new AgentError("Repository owner cannot start with a dash.");
81
+ const { err, code } = await run(
82
+ ["gh", "repo", "clone", repo, dir, "--", "--quiet"],
83
+ undefined,
84
+ gitEnv(token ? token() : process.env.GH_TOKEN),
85
+ );
86
+ if (code !== 0)
87
+ throw new AgentError(
88
+ `Cloning ${repo} failed: ${scrubDiagnostic(err, diagnosticChars) || `exit ${code}`}`,
89
+ );
90
+ };
91
+ export const ghClone: CloneCommand = ghCloneWith();
92
+
93
+ /** Git and gh calls that carry the shelf's token and no other host secret. */
94
+ export class GitRunner {
95
+ readonly #token: () => string | undefined;
96
+ readonly diagnosticChars: number | undefined;
97
+
98
+ constructor(token: () => string | undefined, diagnosticChars?: number) {
99
+ this.#token = token;
100
+ this.diagnosticChars = diagnosticChars;
101
+ }
102
+
103
+ /** A git or gh call with the shelf's token and no other host secret. */
104
+ run(
105
+ command: string[],
106
+ cwd?: string,
107
+ ): Promise<{ out: string; err: string; code: number }> {
108
+ return run(command, cwd, gitEnv(this.#token()));
109
+ }
110
+
111
+ /** `git -C dir <args>`, its stdout; a failure throws with the scrubbed stderr. */
112
+ async git(dir: string, ...args: string[]): Promise<string> {
113
+ const { out, err, code } = await this.run(["git", "-C", dir, ...args]);
114
+ if (code !== 0)
115
+ throw new AgentError(
116
+ `git ${args[0]} failed in ${dir}: ${scrubDiagnostic(err, this.diagnosticChars) || `exit ${code}`}`,
117
+ );
118
+ return out;
119
+ }
120
+ }
@@ -0,0 +1,72 @@
1
+ import {
2
+ closeSync,
3
+ constants,
4
+ fstatSync,
5
+ lstatSync,
6
+ openSync,
7
+ readdirSync,
8
+ readSync,
9
+ } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ const MAX_SUMMARY_CHARS = 120;
13
+ const MAX_METADATA_BYTES = 65_536;
14
+
15
+ /** Metadata discovery never follows links or opens devices/FIFOs; each file is bounded. */
16
+ function metadataText(path: string): string | undefined {
17
+ let fd: number | undefined;
18
+ try {
19
+ if (!lstatSync(path).isFile()) return undefined;
20
+ fd = openSync(
21
+ path,
22
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
23
+ );
24
+ if (!fstatSync(fd).isFile()) return undefined;
25
+ const bytes = Buffer.alloc(MAX_METADATA_BYTES);
26
+ const count = readSync(fd, bytes, 0, bytes.length, 0);
27
+ return bytes.subarray(0, count).toString("utf8");
28
+ } catch {
29
+ return undefined;
30
+ } finally {
31
+ if (fd !== undefined) closeSync(fd);
32
+ }
33
+ }
34
+
35
+ /** The first prose line of a README or AGENTS.md: no frontmatter, heading, badge, or markup. */
36
+ export function summaryOf(dir: string): string | undefined {
37
+ for (const name of ["README.md", "AGENTS.md"]) {
38
+ const file = join(dir, name);
39
+ const content = metadataText(file);
40
+ if (!content) continue;
41
+ const text = content.replace(/^---\n[\s\S]*?\n---\n/, "");
42
+ const line = text
43
+ .split("\n")
44
+ .map((l) => l.trim())
45
+ .find((l) => /\p{L}/u.test(l) && !/^([#!<>|`[\-*=]|\d+\.)/.test(l));
46
+ if (line)
47
+ return line.length > MAX_SUMMARY_CHARS
48
+ ? `${line.slice(0, MAX_SUMMARY_CHARS - 1)}…`
49
+ : line;
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ export function ciOnPush(dir: string): boolean {
55
+ const workflows = join(dir, ".github", "workflows");
56
+ try {
57
+ if (
58
+ !lstatSync(join(dir, ".github")).isDirectory() ||
59
+ !lstatSync(workflows).isDirectory()
60
+ )
61
+ return false;
62
+ return readdirSync(workflows)
63
+ .filter((name) => /\.ya?ml$/.test(name))
64
+ .some((name) =>
65
+ /^\s*(on:\s*\[?[^\n]*\bpush\b|push\s*:)/m.test(
66
+ metadataText(join(workflows, name)) ?? "",
67
+ ),
68
+ );
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
@@ -0,0 +1,16 @@
1
+ import type { ChangeReport } from "./repo-types.ts";
2
+
3
+ /** The report as posted for the owner. */
4
+ export function reportPost(report: ChangeReport, direct = false): string {
5
+ return [
6
+ `**Change report**: \`${report.repo}\`, commit \`${report.sha}\`, default branch \`${report.branch}\`.`,
7
+ `**Push destination**: \`${report.target}\``,
8
+ `**Commits (${report.commits.length})**`,
9
+ ...report.commits.map((c) => `- \`${c.slice(0, 12)}\`${c.slice(12)}`),
10
+ "**Changed files**",
11
+ `\`\`\`\n${report.diffstat}\n\`\`\``,
12
+ direct
13
+ ? "This repository is explicitly owner-owned; repo_push does not need an approval card."
14
+ : `After approval: repo_push ${report.repo} ${report.sha}`,
15
+ ].join("\n");
16
+ }