@hamzaahmadaslam/commit-changelog 0.0.0-stage → 1.0.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.mjs ADDED
@@ -0,0 +1,184 @@
1
+ // Reads commits from a local git repository with read-only git commands (rev-parse, describe, log). git runs as a
2
+ // child process with its arguments passed as an array, never through a shell. Every ref the user gives is checked,
3
+ // then resolved to a commit hash, and only hashes reach `git log`.
4
+ import { spawn } from "node:child_process";
5
+ import { statSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { UserError } from "./errors.mjs";
8
+
9
+ /** A git failure the user can act on: git's own first line of explanation. */
10
+ function gitFailure(stderr) {
11
+ const line = stderr.split(/\r?\n/).find((text) => text.trim()) ?? "no message";
12
+ return new UserError(`git failed: ${line.trim()}`);
13
+ }
14
+
15
+ /**
16
+ * Runs `git <args>` in `cwd` and resolves { code, stdout, stderr }. It rejects only when git cannot be started.
17
+ * GIT_OPTIONAL_LOCKS=0 keeps git from refreshing the index or taking any lock it does not need.
18
+ */
19
+ export function runGit(args, { cwd }) {
20
+ return new Promise((resolve, reject) => {
21
+ let settled = false;
22
+ const fail = (error) => {
23
+ if (settled) return;
24
+ settled = true;
25
+ reject(
26
+ error?.code === "ENOENT"
27
+ ? new UserError("git was not found. Install git and make sure it is on your PATH.")
28
+ : new UserError(`Could not run git: ${error?.message ?? error}`),
29
+ );
30
+ };
31
+ let child;
32
+ try {
33
+ child = spawn("git", args, {
34
+ cwd,
35
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ windowsHide: true,
38
+ });
39
+ } catch (error) {
40
+ fail(error);
41
+ return;
42
+ }
43
+ const out = [];
44
+ const err = [];
45
+ child.stdout.on("data", (chunk) => out.push(chunk));
46
+ child.stderr.on("data", (chunk) => err.push(chunk));
47
+ child.on("error", fail);
48
+ child.on("close", (code) => {
49
+ if (settled) return;
50
+ settled = true;
51
+ resolve({ code, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") });
52
+ });
53
+ });
54
+ }
55
+
56
+ /** Checks that `input` is a folder inside a git repository. Returns { dir } with the absolute path. */
57
+ export async function openRepository(input = ".", { cwd = process.cwd() } = {}) {
58
+ const dir = path.resolve(cwd, input);
59
+ let stats;
60
+ try {
61
+ stats = statSync(dir);
62
+ } catch {
63
+ throw new UserError(`Cannot read ${input}: there is no such folder.`);
64
+ }
65
+ if (!stats.isDirectory()) throw new UserError(`${input} is not a folder. Give the folder of a git repository.`);
66
+ const { code, stderr } = await runGit(["rev-parse", "--git-dir"], { cwd: dir });
67
+ if (code !== 0) {
68
+ if (/not a git repository/i.test(stderr)) throw new UserError(`${input} is not inside a git repository.`);
69
+ throw gitFailure(stderr);
70
+ }
71
+ return { dir };
72
+ }
73
+
74
+ /**
75
+ * Rejects a ref that git could read as an option (it starts with "-") or that holds control characters. Anything
76
+ * else is left to `git rev-parse --verify`, which accepts only names of existing objects.
77
+ */
78
+ export function checkRef(ref, option) {
79
+ if (typeof ref !== "string" || !ref.trim()) throw new UserError(`${option} needs a ref, such as v1.2.0 or HEAD.`);
80
+ if (ref.startsWith("-") || /[\u0000-\u001f\u007f]/.test(ref)) {
81
+ throw new UserError(`${option} must be a tag, branch or commit such as v1.2.0 or HEAD, not "${ref}".`);
82
+ }
83
+ }
84
+
85
+ /** The commit hash `ref` names, or null when there is no such commit. */
86
+ async function commitOf(repo, ref) {
87
+ const { code, stdout, stderr } = await runGit(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { cwd: repo.dir });
88
+ if (code === 0) return stdout.trim();
89
+ if (code === 1) return null;
90
+ throw gitFailure(stderr);
91
+ }
92
+
93
+ async function resolveCommit(repo, ref, option) {
94
+ checkRef(ref, option);
95
+ const commit = await commitOf(repo, ref);
96
+ if (!commit) throw new UserError(`Cannot find "${ref}" (${option}) in this repository.`);
97
+ return commit;
98
+ }
99
+
100
+ /** The nearest tag reachable from `commit`, as { name, commit }, or null when there is none. */
101
+ async function nearestTag(repo, commit) {
102
+ const { code, stdout } = await runGit(["describe", "--tags", "--abbrev=0", commit], { cwd: repo.dir });
103
+ const name = code === 0 ? stdout.trim() : "";
104
+ if (!name) return null;
105
+ const tagged = await commitOf(repo, `refs/tags/${name}`);
106
+ return tagged ? { name, commit: tagged } : null;
107
+ }
108
+
109
+ /**
110
+ * The last tag before `toCommit`: the nearest tag reachable from it. When that tag is on `toCommit` itself (the
111
+ * release is already tagged), the nearest tag reachable from its first parent instead, so the range covers the
112
+ * release that tag marks.
113
+ */
114
+ export async function lastTag(repo, toCommit) {
115
+ const tag = await nearestTag(repo, toCommit);
116
+ if (!tag || tag.commit !== toCommit) return tag;
117
+ const parent = await commitOf(repo, `${toCommit}^`);
118
+ return parent ? nearestTag(repo, parent) : null;
119
+ }
120
+
121
+ /**
122
+ * Resolves the range to read. `to` defaults to HEAD; `from` defaults to the last tag before `to`, and when there is
123
+ * no tag the range is every commit reachable from `to`.
124
+ */
125
+ export async function resolveRange(repo, { from, to = "HEAD" } = {}) {
126
+ const toCommit = await resolveCommit(repo, to, "--to");
127
+ if (from !== undefined) {
128
+ return { from, to, fromCommit: await resolveCommit(repo, from, "--from"), toCommit, fromSource: "option" };
129
+ }
130
+ const tag = await lastTag(repo, toCommit);
131
+ if (!tag) return { from: null, to, fromCommit: null, toCommit, fromSource: "none" };
132
+ return { from: tag.name, to, fromCommit: tag.commit, toCommit, fromSource: "last_tag" };
133
+ }
134
+
135
+ // One record per commit: a header item (hash, raw message) and then its changed files, each item ended by NUL.
136
+ const FORMAT = "%x1e%H%x1f%B%x1f";
137
+ const HEADER = /^\x1e([0-9a-f]{40}|[0-9a-f]{64})\x1f([\s\S]*)\x1f$/;
138
+
139
+ /** Splits a raw commit message into its first line and the rest. Leading blank lines are skipped. */
140
+ export function splitMessage(message) {
141
+ const lines = message.replace(/\r\n?/g, "\n").split("\n");
142
+ while (lines.length && !lines[0].trim()) lines.shift();
143
+ return { firstLine: (lines[0] ?? "").trim(), body: lines.slice(1).join("\n").trim() };
144
+ }
145
+
146
+ /** Parses the output of `git log -z --name-only --format=FORMAT` into commits, newest first as git prints them. */
147
+ export function parseLog(output) {
148
+ const commits = [];
149
+ let current = null;
150
+ for (const item of output.split("\0")) {
151
+ const header = HEADER.exec(item);
152
+ if (header) {
153
+ current = { hash: header[1], short: header[1].slice(0, 7), ...splitMessage(header[2]), files: [] };
154
+ commits.push(current);
155
+ } else if (current && item) {
156
+ // git puts a newline between a commit's header and its first file name.
157
+ current.files.push(current.files.length === 0 && item.startsWith("\n") ? item.slice(1) : item);
158
+ }
159
+ }
160
+ return commits;
161
+ }
162
+
163
+ /**
164
+ * Reads the commits in the range, oldest first: hash, first line, the rest of the message, and the names of the
165
+ * files each one changed. Merge commits are skipped.
166
+ */
167
+ export async function readCommits(repo, range) {
168
+ const revisions = range.fromCommit ? [`${range.fromCommit}..${range.toCommit}`] : [range.toCommit];
169
+ const args = [
170
+ "log",
171
+ "-z",
172
+ "--no-merges",
173
+ "--no-color",
174
+ "--no-show-signature",
175
+ "--encoding=UTF-8",
176
+ "--name-only",
177
+ `--format=${FORMAT}`,
178
+ ...revisions,
179
+ "--",
180
+ ];
181
+ const { code, stdout, stderr } = await runGit(args, { cwd: repo.dir });
182
+ if (code !== 0) throw gitFailure(stderr);
183
+ return parseLog(stdout).reverse();
184
+ }
package/src/jev.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // A small client for TypeSafe's System One API (Jev). Copy this file into a tool as src/jev.mjs.
2
+ // API: POST https://api.typesafe.ai/v1/systemone { model, state, questions } -> { model, answers, usage }
3
+ // The key comes from TYPESAFE_API_KEY and is only ever sent in the Authorization header.
4
+
5
+ export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
6
+ export const DEFAULT_MODEL = "jev-latest";
7
+
8
+ export class JevError extends Error {
9
+ constructor(message, status) {
10
+ super(message);
11
+ this.name = "JevError";
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
17
+
18
+ /**
19
+ * Asks Jev the `questions` about `state`. Retries 429 and 529 up to `retries` times with exponential backoff
20
+ * (honouring retry-after), times out each attempt after `timeoutMs`, and throws a JevError with a plain message
21
+ * otherwise. `fetchImpl` is injectable so tests never touch the network.
22
+ */
23
+ export async function askJev(state, questions, options = {}) {
24
+ const {
25
+ apiKey = process.env.TYPESAFE_API_KEY,
26
+ model = process.env.TYPESAFE_MODEL || DEFAULT_MODEL,
27
+ timeoutMs = 10_000,
28
+ retries = 3,
29
+ fetchImpl = globalThis.fetch,
30
+ } = options;
31
+ if (!apiKey || !apiKey.trim()) {
32
+ throw new JevError("TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first.", 0);
33
+ }
34
+ const body = JSON.stringify({ model, state, questions });
35
+ for (let attempt = 0; ; attempt++) {
36
+ let res;
37
+ try {
38
+ res = await fetchImpl(JEV_ENDPOINT, {
39
+ method: "POST",
40
+ headers: { authorization: `Bearer ${apiKey.trim()}`, "content-type": "application/json" },
41
+ body,
42
+ signal: AbortSignal.timeout(timeoutMs),
43
+ });
44
+ } catch (error) {
45
+ if (attempt < retries) {
46
+ await sleep(500 * 2 ** attempt);
47
+ continue;
48
+ }
49
+ throw new JevError(`Could not reach TypeSafe: ${error?.name === "TimeoutError" ? "timed out" : error?.message}`, 0);
50
+ }
51
+ if (res.ok) {
52
+ const data = await res.json();
53
+ if (!data || typeof data.answers !== "object") throw new JevError("TypeSafe answered without answers.", res.status);
54
+ return data;
55
+ }
56
+ if ((res.status === 429 || res.status === 529) && attempt < retries) {
57
+ const after = Number(res.headers.get("retry-after"));
58
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : 500 * 2 ** attempt);
59
+ continue;
60
+ }
61
+ const detail = await res.text().catch(() => "");
62
+ const reason =
63
+ res.status === 401
64
+ ? "the API key was refused"
65
+ : res.status === 422
66
+ ? `the request was invalid: ${detail.slice(0, 300)}`
67
+ : res.status === 429
68
+ ? "rate limited; try again later"
69
+ : res.status === 529
70
+ ? "TypeSafe is overloaded; try again later"
71
+ : `HTTP ${res.status}`;
72
+ throw new JevError(`TypeSafe error: ${reason}`, res.status);
73
+ }
74
+ }
75
+
76
+ /** Question helpers (the shapes in reference/typesafe/api.md). */
77
+ export const noul = (instructions, criteria) => ({ type: "noul", instructions, ...(criteria ? { criteria } : {}) });
78
+ export const choice = (instructions, options) => ({ type: "choice", instructions, criteria: options });
79
+ export const score = (instructions, levels) => ({ type: "score", instructions, criteria: levels });
80
+
81
+ /** A fetch stand-in for tests: answers each request with `respond(body)` (a plain object) or an error status. */
82
+ export function fixtureFetch(respond) {
83
+ const calls = [];
84
+ const fetchImpl = async (url, init) => {
85
+ const body = JSON.parse(init.body);
86
+ calls.push({ url, body, headers: init.headers });
87
+ const out = await respond(body, calls.length);
88
+ if (typeof out === "number") return new Response(JSON.stringify({ error: "fixture" }), { status: out });
89
+ return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json" } });
90
+ };
91
+ return { fetchImpl, calls };
92
+ }
package/src/report.mjs ADDED
@@ -0,0 +1,220 @@
1
+ // Formats results for people (the report, the dry run) and for programs (JSON). Every word printed comes from the
2
+ // commits or from the fixed text in this file; Jev returns only probabilities.
3
+ import { estimatePlan, SECTIONS } from "./classify.mjs";
4
+ import { SECTION_TITLES } from "./changelog.mjs";
5
+
6
+ const REASONS = {
7
+ unsure_section: "unclear which section",
8
+ unsure_users: "unclear if users notice it",
9
+ answers_disagree: "the section and the users answer disagree",
10
+ empty_message: "the commit has no message",
11
+ no_answer: "no answer from TypeSafe",
12
+ };
13
+
14
+ const LIST_LIMIT = 20;
15
+
16
+ const count = (n) => n.toLocaleString("en-US");
17
+ const plural = (n, word) => `${count(n)} ${word}${n === 1 ? "" : "s"}`;
18
+ const p2 = (value) => value.toFixed(2);
19
+
20
+ /** "in v1.2.0..HEAD", or "up to HEAD (no tag before it)" when the range starts at the first commit. */
21
+ export function describeRange(range) {
22
+ return range.fromSource === "none" ? `up to ${range.to} (no tag before it)` : `in ${range.from}..${range.to}`;
23
+ }
24
+
25
+ /** The sections Jev leaned to, highest first: the top one, and the others at 0.05 or more, at most three. */
26
+ function sectionAnswer(section) {
27
+ const ranked = Object.entries(section.probabilities)
28
+ .filter(([, value]) => typeof value === "number")
29
+ .sort((a, b) => b[1] - a[1] || SECTIONS.indexOf(a[0]) - SECTIONS.indexOf(b[0]));
30
+ const shown = ranked.filter(([, value], i) => i === 0 || value >= 0.05).slice(0, 3);
31
+ return `${shown.map(([name, value]) => `${name} ${p2(value)}`).join(", ")} (confidence ${p2(section.confidence)})`;
32
+ }
33
+
34
+ function reviewLines(entry) {
35
+ const lines = [` ${entry.commit.short} ${entry.commit.firstLine || "(no message)"}`];
36
+ if (entry.answer) lines.push(` ${sectionAnswer(entry.answer.section)} | affects users ${p2(entry.answer.users)}`);
37
+ lines.push(` ${entry.reasons.map((reason) => REASONS[reason] ?? reason).join(", ")}`);
38
+ return lines;
39
+ }
40
+
41
+ function header(result, meta) {
42
+ const { summary, usage } = result;
43
+ const lines = [`commit-changelog: ${plural(summary.commits, "commit")} ${describeRange(meta.range)} (merge commits skipped)`];
44
+ if (!summary.commits) return lines;
45
+ if (usage.requests) {
46
+ lines.push(
47
+ `Model ${result.model}, ${plural(usage.requests, "request")}, ${count(usage.input_tokens)} input tokens, ` +
48
+ `threshold ${result.threshold}`,
49
+ );
50
+ } else if (summary.asked === 0) {
51
+ lines.push("No request was sent to TypeSafe: no commit needed Jev.");
52
+ }
53
+ lines.push(
54
+ "",
55
+ `listed ${summary.listed} internal ${summary.internal} review ${summary.review}` +
56
+ ` (${summary.by_prefix} placed by their conventional-commit prefix, ${summary.asked} asked)`,
57
+ );
58
+ return lines;
59
+ }
60
+
61
+ /**
62
+ * The human-readable report: counts, the changelog section (or where it was written), the commits to review with
63
+ * their probabilities, and a note on internal commits.
64
+ */
65
+ export function formatReport(result, meta) {
66
+ const { summary } = result;
67
+ const lines = header(result, meta);
68
+ if (!summary.commits) {
69
+ if (meta.writeFile) lines.push(`Nothing was written to ${meta.writeFile}.`);
70
+ return `${lines.join("\n")}\n`;
71
+ }
72
+
73
+ lines.push("");
74
+ if (!meta.section.text) {
75
+ lines.push(`No commit was listed, so there is no changelog section${meta.writeFile ? ` and nothing was written to ${meta.writeFile}` : ""}.`);
76
+ } else if (meta.written) {
77
+ lines.push(
78
+ `${meta.written.created ? "Created" : "Updated"} ${meta.writeFile}: added the ${meta.heading} section with ` +
79
+ `${count(meta.section.entries)} ${meta.section.entries === 1 ? "entry" : "entries"}.`,
80
+ );
81
+ } else {
82
+ lines.push(meta.section.text.trimEnd());
83
+ }
84
+
85
+ const review = result.entries.filter((entry) => entry.outcome === "review");
86
+ if (review.length) {
87
+ lines.push("", "Review: these commits were not placed. Add them to the section by hand if they belong.");
88
+ for (const entry of review) lines.push(...reviewLines(entry));
89
+ }
90
+ if (summary.internal && !meta.includeInternal) {
91
+ lines.push("", `${plural(summary.internal, "internal commit")} not listed. --include-internal lists them under Internal.`);
92
+ }
93
+ return `${lines.join("\n")}\n`;
94
+ }
95
+
96
+ function commitJson(entry) {
97
+ return {
98
+ hash: entry.commit.hash,
99
+ short: entry.commit.short,
100
+ first_line: entry.commit.firstLine,
101
+ files_changed: entry.commit.files.length,
102
+ decided_by: entry.decidedBy,
103
+ prefix: entry.prefix ? { type: entry.prefix.type, scope: entry.prefix.scope, breaking: entry.prefix.breaking } : null,
104
+ outcome: entry.outcome,
105
+ section: entry.section,
106
+ reasons: entry.reasons,
107
+ section_probabilities: entry.answer?.section.probabilities ?? null,
108
+ section_confidence: entry.answer?.section.confidence ?? null,
109
+ affects_users: entry.answer?.users ?? null,
110
+ };
111
+ }
112
+
113
+ function rangeJson(range) {
114
+ return {
115
+ from: range.from,
116
+ to: range.to,
117
+ from_commit: range.fromCommit,
118
+ to_commit: range.toCommit,
119
+ from_source: range.fromSource,
120
+ };
121
+ }
122
+
123
+ /** The report as JSON: the range, the section, every commit with its outcome and the raw probabilities. */
124
+ export function toJson(result, meta) {
125
+ return {
126
+ tool: "commit-changelog",
127
+ version: meta.version,
128
+ range: rangeJson(meta.range),
129
+ label: meta.label,
130
+ date: meta.date,
131
+ threshold: result.threshold,
132
+ batch: meta.batch,
133
+ include_internal: meta.includeInternal,
134
+ model: result.model,
135
+ summary: result.summary,
136
+ usage: result.usage,
137
+ section: meta.section.text,
138
+ written: meta.written ? meta.writeFile : null,
139
+ commits: result.entries.map(commitJson),
140
+ };
141
+ }
142
+
143
+ /** What --dry-run prints: how each commit would be placed, the requests, the token estimate and one commit's questions. */
144
+ export function formatDryRun(plan, meta) {
145
+ const estimate = estimatePlan(plan);
146
+ const byPrefix = plan.entries.filter((entry) => entry.decidedBy === "prefix");
147
+ const toAsk = plan.entries.filter((entry) => entry.decidedBy === "jev");
148
+ const empty = plan.entries.filter((entry) => entry.decidedBy === "none");
149
+ const lines = [
150
+ "Dry run: nothing was sent to TypeSafe and nothing was written.",
151
+ "",
152
+ `${plural(plan.entries.length, "commit")} ${describeRange(meta.range)} (merge commits skipped)`,
153
+ ];
154
+ const width = Math.max(0, ...byPrefix.map((entry) => SECTION_TITLES[entry.section].length));
155
+ const list = (entries, show) => {
156
+ for (const entry of entries.slice(0, LIST_LIMIT)) lines.push(` ${entry.commit.short} ${show(entry)}`);
157
+ if (entries.length > LIST_LIMIT) lines.push(` and ${plural(entries.length - LIST_LIMIT, "more commit")}`);
158
+ };
159
+ if (byPrefix.length) {
160
+ lines.push(` ${count(byPrefix.length)} placed by their conventional-commit prefix:`);
161
+ list(byPrefix, (entry) => `${SECTION_TITLES[entry.section].padEnd(width)} ${entry.commit.firstLine}`);
162
+ }
163
+ if (empty.length) {
164
+ lines.push(` ${count(empty.length)} without a message, listed for review:`);
165
+ list(empty, () => "(no message)");
166
+ }
167
+ if (toAsk.length) {
168
+ lines.push(` ${count(toAsk.length)} to ask Jev:`);
169
+ list(toAsk, (entry) => entry.commit.firstLine);
170
+ }
171
+ lines.push("");
172
+ if (!plan.requests.length) {
173
+ lines.push("No request would be sent: no commit needs Jev.");
174
+ return `${lines.join("\n")}\n`;
175
+ }
176
+ lines.push(`${plural(plan.requests.length, "request")} to ${meta.model}, about ${count(estimate.tokens)} input tokens`, "");
177
+ const [request] = plan.requests;
178
+ const [target] = request.targets;
179
+ lines.push(`Each commit sent gets two questions. For ${target.entry.commit.short}, which is \`commits[${target.at}]\` in its request:`);
180
+ for (const suffix of ["section", "users"]) {
181
+ const id = `${target.key}_${suffix}`;
182
+ const question = request.body.questions[id];
183
+ const options = question.type === "choice" ? `: ${Object.keys(question.criteria).join(", ")}` : "";
184
+ lines.push(` ${id} (${question.type}${options})`, ` ${question.instructions}`);
185
+ }
186
+ lines.push("", "Run with --dry-run --json to see every request body.");
187
+ return `${lines.join("\n")}\n`;
188
+ }
189
+
190
+ /** What --dry-run --json prints: how each commit would be placed, the estimate, and every request body as it would be sent. */
191
+ export function dryRunJson(plan, meta) {
192
+ const estimate = estimatePlan(plan);
193
+ return {
194
+ tool: "commit-changelog",
195
+ version: meta.version,
196
+ dry_run: true,
197
+ range: rangeJson(meta.range),
198
+ batch: meta.batch,
199
+ model: meta.model,
200
+ summary: {
201
+ commits: plan.entries.length,
202
+ by_prefix: plan.entries.filter((entry) => entry.decidedBy === "prefix").length,
203
+ to_ask: plan.asked,
204
+ requests: plan.requests.length,
205
+ },
206
+ estimated_input_tokens: estimate.tokens,
207
+ commits: plan.entries.map((entry) => ({
208
+ hash: entry.commit.hash,
209
+ short: entry.commit.short,
210
+ first_line: entry.commit.firstLine,
211
+ decided_by: entry.decidedBy,
212
+ section: entry.section,
213
+ })),
214
+ requests: plan.requests.map((request, i) => ({
215
+ commits: request.targets.map((target) => target.entry.commit.short),
216
+ estimated_tokens: estimate.perRequest[i],
217
+ body: request.body,
218
+ })),
219
+ };
220
+ }