@aidenhq/sdk 0.2.0 → 0.4.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 +5 -4
- package/dist/src/agent-paused.d.ts +7 -0
- package/dist/src/agent-paused.js +4 -0
- package/dist/src/attribution.d.ts +16 -0
- package/dist/src/attribution.js +21 -0
- package/dist/src/box-bundle.d.ts +9 -0
- package/dist/src/box-bundle.js +59 -0
- package/dist/src/caller.js +2 -1
- package/dist/src/checks.d.ts +101 -0
- package/dist/src/checks.js +151 -0
- package/dist/src/churn.d.ts +46 -0
- package/dist/src/churn.js +177 -0
- package/dist/src/closed-event.d.ts +36 -0
- package/dist/src/closed-event.js +17 -0
- package/dist/src/engine-io.d.ts +2 -0
- package/dist/src/engine-io.js +13 -8
- package/dist/src/executor.d.ts +46 -3
- package/dist/src/executor.js +23 -13
- package/dist/src/fence.d.ts +12 -0
- package/dist/src/fence.js +24 -1
- package/dist/src/for-others.d.ts +3 -0
- package/dist/src/for-others.js +7 -0
- package/dist/src/instance-details.d.ts +10 -0
- package/dist/src/instance-details.js +63 -0
- package/dist/src/instance-paths.d.ts +3 -0
- package/dist/src/instance-paths.js +7 -0
- package/dist/src/judge.d.ts +65 -0
- package/dist/src/judge.js +71 -0
- package/dist/src/kernel-client.d.ts +45 -0
- package/dist/src/kernel-client.js +103 -0
- package/dist/src/kit.js +19 -4
- package/dist/src/maintained-repos.d.ts +58 -0
- package/dist/src/maintained-repos.js +136 -0
- package/dist/src/model-text.d.ts +29 -0
- package/dist/src/model-text.js +361 -0
- package/dist/src/owner-day.d.ts +12 -0
- package/dist/src/owner-day.js +39 -0
- package/dist/src/paperclip.d.ts +34 -0
- package/dist/src/paperclip.js +64 -0
- package/dist/src/pass-rule.d.ts +10 -0
- package/dist/src/pass-rule.js +24 -0
- package/dist/src/pin-owner.d.ts +2 -0
- package/dist/src/pin-owner.js +1 -0
- package/dist/src/progress.js +7 -2
- package/dist/src/provider.d.ts +83 -0
- package/dist/src/provider.js +31 -0
- package/dist/src/quality.d.ts +74 -0
- package/dist/src/quality.js +131 -0
- package/dist/src/repeat.d.ts +19 -0
- package/dist/src/repeat.js +38 -0
- package/dist/src/responses.d.ts +64 -0
- package/dist/src/responses.js +198 -0
- package/dist/src/reviewer.d.ts +79 -34
- package/dist/src/reviewer.js +198 -22
- package/dist/src/source-store.d.ts +13 -3
- package/dist/src/source-store.js +12 -7
- package/dist/src/task-state-types.d.ts +77 -0
- package/dist/src/task-state-types.js +4 -0
- package/dist/src/tiers.d.ts +88 -0
- package/dist/src/tiers.js +156 -0
- package/dist/src/tools-client.d.ts +60 -0
- package/dist/src/tools-client.js +192 -0
- package/dist/src/types.d.ts +28 -2
- package/dist/src/vendor/needs.d.ts +35 -0
- package/dist/src/vendor/needs.js +43 -0
- package/dist/src/vendor/oauth.d.ts +82 -2
- package/dist/src/vendor/oauth.js +282 -32
- package/dist/src/vendor/proxy.d.ts +33 -4
- package/dist/src/vendor/proxy.js +377 -49
- package/package.json +13 -11
package/README.md
CHANGED
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
The code AidenHQ modules share, one copy on npm. MIT. Entry points: `types`, `engine-io`, `kit`, `progress` (engines),
|
|
4
4
|
`caller` and `fence` (every module server: the kernel's caller assertion and the untrusted-text fence), `executor` (write
|
|
5
|
-
kinds), `reviewer` (reviewer@1), `source-store` (source writers; `pg` is a peer
|
|
6
|
-
`vendor/oauth` (vendor connections; the MCP SDK, zod and pino are peer dependencies).
|
|
5
|
+
kinds), `reviewer` (reviewer@1), `judge` (the judges' model call), `responses` and `provider` (the one streaming Responses reader, the roles a caller names and the error kinds), `paperclip` (the Paperclip HTTP client), `source-store` (source writers; `pg` is a peer
|
|
6
|
+
dependency) and `vendor/proxy`, `vendor/oauth`, `vendor/needs` (vendor connections; the MCP SDK, zod and pino are peer dependencies).
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
The official modules in this repo hold synced copies of these files instead (`scripts/sync-shared.ts`), so what they run
|
|
9
|
+
is gated source. A third-party module depends on an exact version (`"@aidenhq/sdk": "X.Y.Z"`). Our own scope is exempt from the 7-day rule, so a module
|
|
9
10
|
may pin a version the day it is published.
|
|
10
11
|
|
|
11
12
|
## Releasing
|
|
12
13
|
|
|
13
14
|
Push a tag `sdk-vX.Y.Z` on a commit of `main`. `.github/workflows/sdk-publish.yml` takes the version from the tag and publishes
|
|
14
15
|
with npm trusted publishing (provenance, no token). Pull requests that touch this folder dry-run the same publish. The pack
|
|
15
|
-
step (`scripts/sdk-pack.
|
|
16
|
+
step (`scripts/sdk-pack.ts`) compiles with this folder's own TypeScript: `bun install --frozen-lockfile --ignore-scripts` here first.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Whether the owner holds the agent paused (or it is gone): Paperclip's lifecycle holds (manual, setup, budget, company
|
|
2
|
+
* archived), never its runtime `status`, which stays "paused" while a pause or resume waits on Paperclip's stop proof. The one
|
|
3
|
+
* rule: the kernel, the board, the Telegram channel and the Fleet Steward all ask this copy. */
|
|
4
|
+
export declare const agentPaused: (a: {
|
|
5
|
+
status: string;
|
|
6
|
+
lifecycleHolds?: string[];
|
|
7
|
+
}) => boolean;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Whether the owner holds the agent paused (or it is gone): Paperclip's lifecycle holds (manual, setup, budget, company
|
|
2
|
+
* archived), never its runtime `status`, which stays "paused" while a pause or resume waits on Paperclip's stop proof. The one
|
|
3
|
+
* rule: the kernel, the board, the Telegram channel and the Fleet Steward all ask this copy. */
|
|
4
|
+
export const agentPaused = (a) => a.status === "terminated" || (a.lifecycleHolds?.length ?? 0) > 0;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The fixed address in every trailer. */
|
|
2
|
+
export declare const TRAILER_EMAIL = "noreply@aidenhq.ai";
|
|
3
|
+
/** The fixed link in every footer. */
|
|
4
|
+
export declare const FOOTER_LINK = "https://aidenhq.ai";
|
|
5
|
+
/** `Co-authored-by: AidenHQ <agent> <noreply@aidenhq.ai>` */
|
|
6
|
+
export declare const trailer: (agent: string) => string;
|
|
7
|
+
/** `🤖 Generated by <agent> with [AidenHQ](https://aidenhq.ai)` */
|
|
8
|
+
export declare const footer: (agent: string) => string;
|
|
9
|
+
/** A commit message ending with the agent's trailer (once: a message already carrying an AidenHQ trailer keeps it). */
|
|
10
|
+
export declare const withTrailer: (message: string, agent: string) => string;
|
|
11
|
+
/** A posted text ending with the agent's footer (once). */
|
|
12
|
+
export declare const withFooter: (text: string, agent: string) => string;
|
|
13
|
+
/** Whether a commit message carries an AidenHQ trailer (any agent). */
|
|
14
|
+
export declare const hasTrailer: (message: string) => boolean;
|
|
15
|
+
/** Whether a text ends with the exact footer line `footer()` writes, for any agent (a link to AidenHQ in anyone's words is not one). */
|
|
16
|
+
export declare const hasFooter: (text: string) => boolean;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// How AidenHQ signs what it writes on GitHub as the owner (spec 2026-11-20-github-owner-identity §4; owner, 2026-11-20): every
|
|
2
|
+
// commit carries a trailer naming the agent, every posted text ends with a footer naming it and linking AidenHQ. Readers
|
|
3
|
+
// (flow.ts author_kind) match only the fixed parts, never the names: the noreply address and the link.
|
|
4
|
+
//
|
|
5
|
+
// First-party modules hold byte-identical copies (scripts/sync-shared.ts: edit this one and run it).
|
|
6
|
+
/** The fixed address in every trailer. */
|
|
7
|
+
export const TRAILER_EMAIL = "noreply@aidenhq.ai";
|
|
8
|
+
/** The fixed link in every footer. */
|
|
9
|
+
export const FOOTER_LINK = "https://aidenhq.ai";
|
|
10
|
+
/** `Co-authored-by: AidenHQ <agent> <noreply@aidenhq.ai>` */
|
|
11
|
+
export const trailer = (agent) => `Co-authored-by: AidenHQ ${agent} <${TRAILER_EMAIL}>`;
|
|
12
|
+
/** `🤖 Generated by <agent> with [AidenHQ](https://aidenhq.ai)` */
|
|
13
|
+
export const footer = (agent) => `🤖 Generated by ${agent} with [AidenHQ](${FOOTER_LINK})`;
|
|
14
|
+
/** A commit message ending with the agent's trailer (once: a message already carrying an AidenHQ trailer keeps it). */
|
|
15
|
+
export const withTrailer = (message, agent) => (hasTrailer(message) ? message : [message.trimEnd(), trailer(agent)].filter(Boolean).join("\n\n"));
|
|
16
|
+
/** A posted text ending with the agent's footer (once). */
|
|
17
|
+
export const withFooter = (text, agent) => (hasFooter(text) ? text : [text.trimEnd(), footer(agent)].filter(Boolean).join("\n\n"));
|
|
18
|
+
/** Whether a commit message carries an AidenHQ trailer (any agent). */
|
|
19
|
+
export const hasTrailer = (message) => new RegExp(`^Co-authored-by: AidenHQ .*<${TRAILER_EMAIL.replace(/\./g, "\\.")}>\\s*$`, "im").test(message);
|
|
20
|
+
/** Whether a text ends with the exact footer line `footer()` writes, for any agent (a link to AidenHQ in anyone's words is not one). */
|
|
21
|
+
export const hasFooter = (text) => new RegExp(`(^|\\n)🤖 Generated by [^\\n]+ with \\[AidenHQ\\]\\(${FOOTER_LINK.replace(/[.]/g, "\\.")}\\)\\s*$`).test(text);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Where the in-box `aidenhq` leaves a branch's bundle, relative to the task's workspace. */
|
|
2
|
+
export declare const bundlePath: (sha: string) => string;
|
|
3
|
+
/** The one ref a bundle carries, named by the sha alone so no branch decides it; hosts fetch it into the branch they push. The in-box `aidenhq` (plain node) writes the same literal. */
|
|
4
|
+
export declare const publishRef: (sha: string) => string;
|
|
5
|
+
/**
|
|
6
|
+
* Copies task `ident`'s bundle of `sha` to `<scratch>/branch.bundle` (made exclusively) and returns that path. `what` names it in
|
|
7
|
+
* refusals (e.g. "acme/x `fix`"). 404: no bundle; 400: a symlink, not a regular file, or outside the task; 413: too large.
|
|
8
|
+
*/
|
|
9
|
+
export declare function copyBoxBundle(tasksDir: string, scratch: string, ident: string, sha: string, what: string): string;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// A job's branch as its box handed it over: a git bundle the in-box `aidenhq publish|review|apply` wrote at
|
|
2
|
+
// <workspace>/.aidenhq/bundles/<sha>.bundle. Both code hosts read it the one way: that one file, opened without following a
|
|
3
|
+
// symlink, resolved after opening to a regular file inside that task's folder, copied whole into the reader's own scratch.
|
|
4
|
+
// Host git and host fs writes never run in a workspace a box can write; git then reads only the copy.
|
|
5
|
+
import { closeSync, constants, existsSync, fstatSync, openSync, readSync, readlinkSync, realpathSync, writeSync } from "node:fs";
|
|
6
|
+
import { join, sep } from "node:path";
|
|
7
|
+
/** Where the in-box `aidenhq` leaves a branch's bundle, relative to the task's workspace. */
|
|
8
|
+
export const bundlePath = (sha) => `.aidenhq/bundles/${sha}.bundle`;
|
|
9
|
+
/** The one ref a bundle carries, named by the sha alone so no branch decides it; hosts fetch it into the branch they push. The in-box `aidenhq` (plain node) writes the same literal. */
|
|
10
|
+
export const publishRef = (sha) => `refs/aidenhq/publish/${sha}`;
|
|
11
|
+
const MAX_BUNDLE = 1 << 30;
|
|
12
|
+
const IDENT = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
|
|
13
|
+
const SHA = /^[0-9a-f]{40}$/;
|
|
14
|
+
const fail = (status, message) => Object.assign(new Error(message), { status });
|
|
15
|
+
/**
|
|
16
|
+
* Copies task `ident`'s bundle of `sha` to `<scratch>/branch.bundle` (made exclusively) and returns that path. `what` names it in
|
|
17
|
+
* refusals (e.g. "acme/x `fix`"). 404: no bundle; 400: a symlink, not a regular file, or outside the task; 413: too large.
|
|
18
|
+
*/
|
|
19
|
+
export function copyBoxBundle(tasksDir, scratch, ident, sha, what) {
|
|
20
|
+
if (!IDENT.test(String(ident)))
|
|
21
|
+
throw fail(400, `${ident} is not a task's workspace`);
|
|
22
|
+
if (!SHA.test(String(sha)))
|
|
23
|
+
throw fail(400, "sha is a full commit sha");
|
|
24
|
+
const task = join(realpathSync(tasksDir), ident);
|
|
25
|
+
const inside = (p) => p.startsWith(task + sep);
|
|
26
|
+
const at = join(task, bundlePath(sha));
|
|
27
|
+
let fd;
|
|
28
|
+
try {
|
|
29
|
+
fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
if (e.code === "ELOOP")
|
|
33
|
+
throw fail(400, `the bundle of ${what} is a symlink; refusing it`);
|
|
34
|
+
throw fail(404, `task ${ident} has no bundle of ${what} at ${sha.slice(0, 12)} (publish it with aidenhq)`);
|
|
35
|
+
}
|
|
36
|
+
const copy = join(scratch, "branch.bundle");
|
|
37
|
+
try {
|
|
38
|
+
// What was opened, not what the path says now: /proc's link where there is one.
|
|
39
|
+
const opened = existsSync(`/proc/self/fd/${fd}`) ? readlinkSync(`/proc/self/fd/${fd}`) : realpathSync(at);
|
|
40
|
+
const st = fstatSync(fd);
|
|
41
|
+
if (!inside(opened) || !inside(realpathSync(at)) || !st.isFile() || st.size > MAX_BUNDLE)
|
|
42
|
+
throw fail(400, `the bundle of ${what} isn't a regular file inside task ${ident}`);
|
|
43
|
+
const out = openSync(copy, "wx", 0o600), buf = Buffer.alloc(1 << 20);
|
|
44
|
+
try {
|
|
45
|
+
for (let n, total = 0; (n = readSync(fd, buf)) > 0;) {
|
|
46
|
+
if ((total += n) > MAX_BUNDLE)
|
|
47
|
+
throw fail(413, "the bundle is too large");
|
|
48
|
+
writeSync(out, buf, 0, n);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
closeSync(out);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
closeSync(fd);
|
|
57
|
+
}
|
|
58
|
+
return copy;
|
|
59
|
+
}
|
package/dist/src/caller.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Who a proxied tool call is for: the kernel's signed caller assertion (X-AidenHQ-Caller, an EdDSA JWT, 60 s), checked
|
|
2
2
|
// against the kernel's keys (GET /v1/jwks). A module trusts nothing else about the caller: not a header, not an argument.
|
|
3
3
|
//
|
|
4
|
-
//
|
|
4
|
+
// First-party modules hold byte-identical copies (scripts/sync-shared.ts: edit this one and run it); third-party modules import
|
|
5
|
+
// @aidenhq/sdk/caller.
|
|
5
6
|
import { createPublicKey, verify } from "node:crypto";
|
|
6
7
|
export const CALLER_HEADER = "x-aidenhq-caller";
|
|
7
8
|
const b64 = (s) => Buffer.from(s, "base64url");
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
type Json = any;
|
|
2
|
+
/** Code review's commit status: a mirror of its merge verdict for people and `gh pr checks`. The merge queue asks code review's
|
|
3
|
+
* verdict itself, so the status never becomes a second gate here. */
|
|
4
|
+
export declare const CODE_REVIEW_STATUS = "aidenhq/review";
|
|
5
|
+
/** The aggregate check a repository's CI may end with (the product's ci.yml `ci-required`). */
|
|
6
|
+
export declare const GATE_CHECK = "ci-required";
|
|
7
|
+
/** The product's PR-metadata job: its title check (and the supply-chain checks), the one job an `edited` run still runs. */
|
|
8
|
+
export declare const POLICY_CHECK = "policy";
|
|
9
|
+
/** One context's result: a check run's conclusion once completed, else PENDING; a status's state. */
|
|
10
|
+
export declare const contextStatus: (n: Json) => string | null | undefined;
|
|
11
|
+
/** Which judgement a context is: a check run and a status context that share a name are different judgements, both counted. */
|
|
12
|
+
export declare const contextKind: (n: Json) => "run" | "status";
|
|
13
|
+
/**
|
|
14
|
+
* Where a context sits in its name's history, higher is later: a check run's `databaseId` (GitHub creates every run, a re-run
|
|
15
|
+
* included, with a higher one), else its `id` where that is a number (REST), else its start or completion time; a status's
|
|
16
|
+
* `id` (REST), else its `createdAt`. Undefined when GitHub gave none, so a caller never trusts a rollup's node order as a contract.
|
|
17
|
+
*/
|
|
18
|
+
export declare function contextRank(n: Json): number | undefined;
|
|
19
|
+
/**
|
|
20
|
+
* One judgement per name and kind: the newest check run of a name, and the newest status of a name (a check run and a status
|
|
21
|
+
* sharing a name judge the same name twice, so both survive and the gate takes the worst). `rank` (contextRank) decides the
|
|
22
|
+
* newest. An entry with no rank proves no order, so it stays its own judgement and the worst of the name still counts: only
|
|
23
|
+
* entries carrying a rank are resolved against each other, and entries of one name whose ranks tie (two statuses in the same
|
|
24
|
+
* second) all stay judgements, so the worst of them counts rather than whichever the rollup listed first. An entry with no
|
|
25
|
+
* `kind` is left as it is for the same reason.
|
|
26
|
+
*/
|
|
27
|
+
export declare function latestChecks<T extends {
|
|
28
|
+
name?: string;
|
|
29
|
+
kind?: "run" | "status";
|
|
30
|
+
rank?: number;
|
|
31
|
+
}>(checks: T[]): T[];
|
|
32
|
+
/** A named check as this module reads it: its status, which judgement it is (`kind`) and where it sits in its name's history (`rank`). */
|
|
33
|
+
export type Check = {
|
|
34
|
+
name: string;
|
|
35
|
+
status: string | null | undefined;
|
|
36
|
+
kind: "run" | "status";
|
|
37
|
+
rank?: number;
|
|
38
|
+
ok: boolean;
|
|
39
|
+
success: boolean;
|
|
40
|
+
pending: boolean;
|
|
41
|
+
skipped?: true; /** When it last reported: a run's completion, a status's creation. */
|
|
42
|
+
at?: string;
|
|
43
|
+
};
|
|
44
|
+
/** Every context in a rollup as a named check, advisory ones (code review's status) included: { name, status, kind, rank?, ok, success, pending, skipped? } (`ok` counts neutral and skipped as passed, `success` only success). A name's newest run is picked where it is judged (latestChecks). */
|
|
45
|
+
export declare function contextChecks(rollup: Json): Check[];
|
|
46
|
+
/** The named checks in a rollup, code review's status left out (contextChecks): every context is returned, and a name's newest run is picked where it is judged (latestChecks). */
|
|
47
|
+
export declare function namedChecks(rollup: Json): Check[];
|
|
48
|
+
/**
|
|
49
|
+
* Whether a check is the aggregate gate reporting that it judged nothing: `ci-required` `skipped` (a job skipped by an `if`, as
|
|
50
|
+
* an `edited` run's is) or `cancelled` (a run superseded before the job started). GitHub counts a skip as a pass for branch
|
|
51
|
+
* protection; nothing here does. Scoped to the gate name: a suite's own skip is a real result (the change didn't touch it).
|
|
52
|
+
*/
|
|
53
|
+
export declare const gateJudgedNothing: (c: {
|
|
54
|
+
name?: string;
|
|
55
|
+
status?: string | null;
|
|
56
|
+
}) => boolean;
|
|
57
|
+
/** Whether a report actually judged something: a job skipped by `if` or a run cancelled before it started judged nothing. */
|
|
58
|
+
export declare const judgedSomething: (c: {
|
|
59
|
+
status?: string | null;
|
|
60
|
+
}) => boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Whether the head's newest aggregate report judged nothing: the `ci-required` an `edited` run posts, skipped because that run
|
|
63
|
+
* planned no suite. Every check that run posted is a skip too, and those skips are newer than the run that tested the head — so
|
|
64
|
+
* they are no verdict, and reading them as passes is exactly the bug this rule exists to stop.
|
|
65
|
+
*/
|
|
66
|
+
export declare function newestGateSkipped<T extends {
|
|
67
|
+
name?: string;
|
|
68
|
+
kind?: "run" | "status";
|
|
69
|
+
rank?: number;
|
|
70
|
+
status?: string | null;
|
|
71
|
+
}>(checks: T[]): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* The reports that judge a head, for a reader that decides on its checks. A run that plans no suite (`edited`) posts a
|
|
74
|
+
* `skipped` check for every job it did not run — and a job `if` skips is still a check GitHub counts as a pass. Those reports
|
|
75
|
+
* are newer than the run that tested the head, so judging them would let a body edit read as green over a real failure and
|
|
76
|
+
* hide it.
|
|
77
|
+
*
|
|
78
|
+
* Per name and kind: when the newest report is `skipped` and an older report of that same name judged something, the skip is
|
|
79
|
+
* dropped and the older result stands — it is the run that tested the code, and an edit's skip says nothing about it. Two runs
|
|
80
|
+
* on one head differ only in the event (an edit against a push or a re-run); within one run a path-filtered suite is skipped
|
|
81
|
+
* the same way both times, so an older judgement of the same name is the same tree's. A name whose only report is a skip keeps
|
|
82
|
+
* it: a suite skipped by the run that judged the head is a real result (the change didn't touch it). An unranked report proves
|
|
83
|
+
* no order, so it is never dropped. `cancelled` is left alone: latestChecks still reads it as a superseded run's red.
|
|
84
|
+
*/
|
|
85
|
+
export declare function judgedOnHead<T extends {
|
|
86
|
+
name?: string;
|
|
87
|
+
kind?: "run" | "status";
|
|
88
|
+
rank?: number;
|
|
89
|
+
status?: string | null;
|
|
90
|
+
}>(checks: T[]): T[];
|
|
91
|
+
/**
|
|
92
|
+
* `image-scan` skipped on a PR that changes an image definition (or whose files weren't read at all): nothing was scanned.
|
|
93
|
+
* The scan's newest report that judged the head is the judgement (judgedOnHead): a run that scanned the head after an edit
|
|
94
|
+
* superseded a skip cleared the question, so the obsolete skip is not one, and a skip that is the newest judgement is.
|
|
95
|
+
* The file list answers on its own: a truncated list is answered on the pages that were read; paging happens at the caller.
|
|
96
|
+
* Deleting an image definition is not one: the workflow selects Dockerfiles from the head's tree, so a PR that only removes
|
|
97
|
+
* a service's Dockerfile skips the scan for a real reason, and no commit could unskip it. A file whose `changeType` is
|
|
98
|
+
* missing counts as a change (fail closed).
|
|
99
|
+
*/
|
|
100
|
+
export declare function skippedImageScan(pr: Json): boolean;
|
|
101
|
+
export {};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/** Code review's commit status: a mirror of its merge verdict for people and `gh pr checks`. The merge queue asks code review's
|
|
2
|
+
* verdict itself, so the status never becomes a second gate here. */
|
|
3
|
+
export const CODE_REVIEW_STATUS = "aidenhq/review";
|
|
4
|
+
/** The aggregate check a repository's CI may end with (the product's ci.yml `ci-required`). */
|
|
5
|
+
export const GATE_CHECK = "ci-required";
|
|
6
|
+
/** The product's PR-metadata job: its title check (and the supply-chain checks), the one job an `edited` run still runs. */
|
|
7
|
+
export const POLICY_CHECK = "policy";
|
|
8
|
+
/** One context's result: a check run's conclusion once completed, else PENDING; a status's state. */
|
|
9
|
+
export const contextStatus = (n) => (n.__typename === "CheckRun" ? (n.status === "COMPLETED" ? n.conclusion : "PENDING") : n.state);
|
|
10
|
+
/** Which judgement a context is: a check run and a status context that share a name are different judgements, both counted. */
|
|
11
|
+
export const contextKind = (n) => (n.__typename === "CheckRun" ? "run" : n.__typename === "StatusContext" || n.state !== undefined ? "status" : "run");
|
|
12
|
+
const numOf = (v) => {
|
|
13
|
+
if (v === null || v === undefined || v === "")
|
|
14
|
+
return undefined;
|
|
15
|
+
const n = Number(v);
|
|
16
|
+
return Number.isFinite(n) ? n : undefined;
|
|
17
|
+
};
|
|
18
|
+
const timeOf = (v) => {
|
|
19
|
+
const t = Date.parse(String(v ?? ""));
|
|
20
|
+
return Number.isNaN(t) ? undefined : t;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Where a context sits in its name's history, higher is later: a check run's `databaseId` (GitHub creates every run, a re-run
|
|
24
|
+
* included, with a higher one), else its `id` where that is a number (REST), else its start or completion time; a status's
|
|
25
|
+
* `id` (REST), else its `createdAt`. Undefined when GitHub gave none, so a caller never trusts a rollup's node order as a contract.
|
|
26
|
+
*/
|
|
27
|
+
export function contextRank(n) {
|
|
28
|
+
if (contextKind(n) === "status")
|
|
29
|
+
return numOf(n.id) ?? timeOf(n.createdAt ?? n.created_at);
|
|
30
|
+
// A run's id is the authority; without one, its start is the point every run of a name shares, so the fallback never compares
|
|
31
|
+
// one run's completion with another's start (a cancelled run finishes after its replacement has started, and would outrank it).
|
|
32
|
+
return numOf(n.databaseId ?? n.id) ?? timeOf(n.startedAt ?? n.started_at) ?? timeOf(n.completedAt ?? n.completed_at);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* One judgement per name and kind: the newest check run of a name, and the newest status of a name (a check run and a status
|
|
36
|
+
* sharing a name judge the same name twice, so both survive and the gate takes the worst). `rank` (contextRank) decides the
|
|
37
|
+
* newest. An entry with no rank proves no order, so it stays its own judgement and the worst of the name still counts: only
|
|
38
|
+
* entries carrying a rank are resolved against each other, and entries of one name whose ranks tie (two statuses in the same
|
|
39
|
+
* second) all stay judgements, so the worst of them counts rather than whichever the rollup listed first. An entry with no
|
|
40
|
+
* `kind` is left as it is for the same reason.
|
|
41
|
+
*/
|
|
42
|
+
export function latestChecks(checks) {
|
|
43
|
+
const out = [];
|
|
44
|
+
const groups = new Map();
|
|
45
|
+
for (const c of checks) {
|
|
46
|
+
if (!c.kind || c.rank === undefined) {
|
|
47
|
+
out.push(c);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const key = `${c.kind}\u0000${c.name ?? ""}`;
|
|
51
|
+
const g = groups.get(key);
|
|
52
|
+
if (!g) {
|
|
53
|
+
groups.set(key, { top: c.rank, items: [c] });
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (c.rank > g.top) {
|
|
57
|
+
g.top = c.rank;
|
|
58
|
+
g.items = [c];
|
|
59
|
+
}
|
|
60
|
+
else if (c.rank === g.top)
|
|
61
|
+
g.items.push(c);
|
|
62
|
+
}
|
|
63
|
+
for (const g of groups.values())
|
|
64
|
+
out.push(...g.items);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
/** Every context in a rollup as a named check, advisory ones (code review's status) included: { name, status, kind, rank?, ok, success, pending, skipped? } (`ok` counts neutral and skipped as passed, `success` only success). A name's newest run is picked where it is judged (latestChecks). */
|
|
68
|
+
export function contextChecks(rollup) {
|
|
69
|
+
const pass = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
|
|
70
|
+
return (rollup?.contexts?.nodes ?? [])
|
|
71
|
+
.map((n) => ({ name: n.name ?? n.context, status: contextStatus(n), kind: contextKind(n), ...(contextRank(n) !== undefined ? { rank: contextRank(n) } : {}), ...(n.completedAt ?? n.createdAt ? { at: String(n.completedAt ?? n.createdAt) } : {}) }))
|
|
72
|
+
.filter((c) => c.name)
|
|
73
|
+
.map((c) => ({ ...c, ok: pass.has(c.status), success: c.status === "SUCCESS", pending: ["PENDING", "EXPECTED", "QUEUED", null, undefined].includes(c.status), ...(c.status === "SKIPPED" ? { skipped: true } : {}) }));
|
|
74
|
+
}
|
|
75
|
+
/** The named checks in a rollup, code review's status left out (contextChecks): every context is returned, and a name's newest run is picked where it is judged (latestChecks). */
|
|
76
|
+
export function namedChecks(rollup) {
|
|
77
|
+
return contextChecks(rollup).filter((c) => c.name !== CODE_REVIEW_STATUS);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Whether a check is the aggregate gate reporting that it judged nothing: `ci-required` `skipped` (a job skipped by an `if`, as
|
|
81
|
+
* an `edited` run's is) or `cancelled` (a run superseded before the job started). GitHub counts a skip as a pass for branch
|
|
82
|
+
* protection; nothing here does. Scoped to the gate name: a suite's own skip is a real result (the change didn't touch it).
|
|
83
|
+
*/
|
|
84
|
+
export const gateJudgedNothing = (c) => c.name === GATE_CHECK && ["SKIPPED", "CANCELLED"].includes(String(c.status ?? "").toUpperCase());
|
|
85
|
+
/** Whether a report actually judged something: a job skipped by `if` or a run cancelled before it started judged nothing. */
|
|
86
|
+
export const judgedSomething = (c) => !["SKIPPED", "CANCELLED"].includes(String(c.status ?? "").toUpperCase());
|
|
87
|
+
/**
|
|
88
|
+
* Whether the head's newest aggregate report judged nothing: the `ci-required` an `edited` run posts, skipped because that run
|
|
89
|
+
* planned no suite. Every check that run posted is a skip too, and those skips are newer than the run that tested the head — so
|
|
90
|
+
* they are no verdict, and reading them as passes is exactly the bug this rule exists to stop.
|
|
91
|
+
*/
|
|
92
|
+
export function newestGateSkipped(checks) {
|
|
93
|
+
const runs = checks.filter((c) => c.name === GATE_CHECK && (c.kind ?? "run") === "run" && typeof c.rank === "number");
|
|
94
|
+
const newest = runs.reduce((a, b) => (a === undefined || b.rank > a.rank ? b : a), undefined);
|
|
95
|
+
return newest !== undefined && gateJudgedNothing(newest);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The reports that judge a head, for a reader that decides on its checks. A run that plans no suite (`edited`) posts a
|
|
99
|
+
* `skipped` check for every job it did not run — and a job `if` skips is still a check GitHub counts as a pass. Those reports
|
|
100
|
+
* are newer than the run that tested the head, so judging them would let a body edit read as green over a real failure and
|
|
101
|
+
* hide it.
|
|
102
|
+
*
|
|
103
|
+
* Per name and kind: when the newest report is `skipped` and an older report of that same name judged something, the skip is
|
|
104
|
+
* dropped and the older result stands — it is the run that tested the code, and an edit's skip says nothing about it. Two runs
|
|
105
|
+
* on one head differ only in the event (an edit against a push or a re-run); within one run a path-filtered suite is skipped
|
|
106
|
+
* the same way both times, so an older judgement of the same name is the same tree's. A name whose only report is a skip keeps
|
|
107
|
+
* it: a suite skipped by the run that judged the head is a real result (the change didn't touch it). An unranked report proves
|
|
108
|
+
* no order, so it is never dropped. `cancelled` is left alone: latestChecks still reads it as a superseded run's red.
|
|
109
|
+
*/
|
|
110
|
+
export function judgedOnHead(checks) {
|
|
111
|
+
const groups = new Map();
|
|
112
|
+
for (const c of checks) {
|
|
113
|
+
if (typeof c.rank !== "number")
|
|
114
|
+
continue;
|
|
115
|
+
const key = `${c.name ?? ""}\u0000${c.kind ?? "run"}`;
|
|
116
|
+
groups.set(key, [...(groups.get(key) ?? []), c]);
|
|
117
|
+
}
|
|
118
|
+
const drop = new Set();
|
|
119
|
+
for (const group of groups.values()) {
|
|
120
|
+
const ranked = [...group].sort((a, b) => b.rank - a.rank);
|
|
121
|
+
if (String(ranked[0]?.status ?? "").toUpperCase() !== "SKIPPED")
|
|
122
|
+
continue;
|
|
123
|
+
// Drop the newest run of skips only when something older judged the name: then they are a later run's skips, not its result.
|
|
124
|
+
const firstJudged = ranked.findIndex((c) => judgedSomething(c));
|
|
125
|
+
if (firstJudged <= 0)
|
|
126
|
+
continue;
|
|
127
|
+
for (const c of ranked.slice(0, firstJudged))
|
|
128
|
+
drop.add(c);
|
|
129
|
+
}
|
|
130
|
+
return drop.size ? checks.filter((c) => !drop.has(c)) : checks;
|
|
131
|
+
}
|
|
132
|
+
const IMAGE_FILE = /(^|\/)(Dockerfile|Containerfile)[^/]*$|\.dockerfile$/i;
|
|
133
|
+
/**
|
|
134
|
+
* `image-scan` skipped on a PR that changes an image definition (or whose files weren't read at all): nothing was scanned.
|
|
135
|
+
* The scan's newest report that judged the head is the judgement (judgedOnHead): a run that scanned the head after an edit
|
|
136
|
+
* superseded a skip cleared the question, so the obsolete skip is not one, and a skip that is the newest judgement is.
|
|
137
|
+
* The file list answers on its own: a truncated list is answered on the pages that were read; paging happens at the caller.
|
|
138
|
+
* Deleting an image definition is not one: the workflow selects Dockerfiles from the head's tree, so a PR that only removes
|
|
139
|
+
* a service's Dockerfile skips the scan for a real reason, and no commit could unskip it. A file whose `changeType` is
|
|
140
|
+
* missing counts as a change (fail closed).
|
|
141
|
+
*/
|
|
142
|
+
export function skippedImageScan(pr) {
|
|
143
|
+
const nodes = pr.commits?.nodes?.[0]?.commit?.statusCheckRollup?.contexts?.nodes ?? [];
|
|
144
|
+
const scans = latestChecks(judgedOnHead(contextChecks({ contexts: { nodes } })).filter((c) => c.name === "image-scan"));
|
|
145
|
+
if (!scans.some((c) => c.status === "SKIPPED"))
|
|
146
|
+
return false;
|
|
147
|
+
// No file list at all (ship's list read carries none) is no evidence: the full PR read answers instead.
|
|
148
|
+
if (!Array.isArray(pr.files?.nodes))
|
|
149
|
+
return true;
|
|
150
|
+
return pr.files.nodes.some((f) => IMAGE_FILE.test(f.path ?? "") && f.changeType !== "DELETED");
|
|
151
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The paths churn ignores. */
|
|
2
|
+
export declare const DEFAULT_CHURN_EXCLUDE: string[];
|
|
3
|
+
export type ChurnPr = {
|
|
4
|
+
pr: string;
|
|
5
|
+
mergedAt: string;
|
|
6
|
+
diff: string;
|
|
7
|
+
};
|
|
8
|
+
export type Rewrite = {
|
|
9
|
+
pr: string;
|
|
10
|
+
by_pr: string;
|
|
11
|
+
lines: number;
|
|
12
|
+
days: number;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Per-PR survival from `prs` in merge order. `opts.windowDays`: a removed line counts as rewritten when it was added at most
|
|
16
|
+
* that many days earlier. `opts.exclude`: globs of paths ignored. `added[pr]`: lines the PR added that were not moves.
|
|
17
|
+
* `rewritten`: per (pr, by_pr) the lines of `pr` that `by_pr` removed, and their mean age in whole days.
|
|
18
|
+
*/
|
|
19
|
+
export declare function churn(prs: ChurnPr[], opts: {
|
|
20
|
+
windowDays: number;
|
|
21
|
+
exclude: string[];
|
|
22
|
+
}): {
|
|
23
|
+
added: Record<string, number>;
|
|
24
|
+
rewritten: Rewrite[];
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Churn over a repo's first-parent history through `git` (args → stdout, run in the repo): each commit whose subject
|
|
28
|
+
* names a PR (`prOf`) is one PR. With a `cursor` only the window before it is read again, so lines added just before it keep
|
|
29
|
+
* their owner; `fresh` says which of the results are new since it. `last`: the newest commit's time, the next cursor.
|
|
30
|
+
* `first`: without a cursor, only the newest that many commits (a first pass on the caller's own thread).
|
|
31
|
+
*/
|
|
32
|
+
export declare function churnFromGit(git: (args: string[]) => Promise<string>, o: {
|
|
33
|
+
rev: string;
|
|
34
|
+
cursor?: string;
|
|
35
|
+
first?: number;
|
|
36
|
+
windowDays: number;
|
|
37
|
+
exclude: string[];
|
|
38
|
+
prOf: (subject: string) => string | undefined;
|
|
39
|
+
onError?: (commit: string, e: unknown) => void;
|
|
40
|
+
}): Promise<{
|
|
41
|
+
added: Record<string, number>;
|
|
42
|
+
rewritten: Rewrite[];
|
|
43
|
+
mergedAt: Map<string, string>;
|
|
44
|
+
fresh: (iso: string) => boolean;
|
|
45
|
+
last: string | undefined;
|
|
46
|
+
}>;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Code churn (docs/design/flow.md): how much of each merged PR's code is rewritten soon after it landed. A pure function over
|
|
2
|
+
// PRs' unified diffs in merge order: every line is tracked by identity (the PR that added it, and when) through later hunks and
|
|
3
|
+
// renames, so a line counts once: as added by its PR, and, when a later PR removes it inside the window, as rewritten. A hunk
|
|
4
|
+
// a PR removes in one place and adds in another unchanged is a move: the lines keep their owner and count as neither.
|
|
5
|
+
// Copied into the code host's service (scripts/sync-shared.ts); codehost-local calls it from the kernel.
|
|
6
|
+
/** The paths churn ignores. */
|
|
7
|
+
export const DEFAULT_CHURN_EXCLUDE = ["**/package-lock.json", "**/bun.lock", "**/dist/**", "**/vendor/**", "**/*.min.*"];
|
|
8
|
+
const DAY = 86_400_000;
|
|
9
|
+
/** Shortest trimmed line a move may match on: `}` and `return;` appear everywhere and prove nothing. */
|
|
10
|
+
const MIN_MOVE = 8;
|
|
11
|
+
const globRe = (g) => new RegExp(`^${g.replace(/[.+^${}()|[\]\\?]/g, "\\$&").replace(/\*\*\//g, "\u0000").replace(/\*\*/g, "\u0001").replace(/\*/g, "[^/]*").replace(/\u0000/g, "(?:.*/)?").replace(/\u0001/g, ".*")}$`);
|
|
12
|
+
/** A unified diff (git's, with renames) as per-file hunks; binary files and mode-only changes have none. */
|
|
13
|
+
function parse(diff) {
|
|
14
|
+
const out = [];
|
|
15
|
+
const lines = diff.split("\n");
|
|
16
|
+
let f;
|
|
17
|
+
const strip = (p) => (p === "/dev/null" ? null : p.replace(/^[ab]\//, "").replace(/\t.*$/, ""));
|
|
18
|
+
for (let i = 0; i < lines.length; i++) {
|
|
19
|
+
const l = lines[i];
|
|
20
|
+
if (l.startsWith("diff --git ")) {
|
|
21
|
+
const m = /^diff --git a\/(.*) b\/(.*)$/.exec(l);
|
|
22
|
+
out.push(f = { from: m?.[1] ?? null, to: m?.[2] ?? null, hunks: [] });
|
|
23
|
+
}
|
|
24
|
+
else if (f && l.startsWith("rename from "))
|
|
25
|
+
f.from = l.slice(12);
|
|
26
|
+
else if (f && l.startsWith("rename to "))
|
|
27
|
+
f.to = l.slice(10);
|
|
28
|
+
else if (f && l.startsWith("new file mode "))
|
|
29
|
+
f.from = null;
|
|
30
|
+
else if (f && l.startsWith("deleted file mode "))
|
|
31
|
+
f.to = null;
|
|
32
|
+
else if (f && l.startsWith("--- ") && !f.hunks.length) {
|
|
33
|
+
if (l.slice(4) === "/dev/null")
|
|
34
|
+
f.from = null;
|
|
35
|
+
else
|
|
36
|
+
f.from = strip(l.slice(4));
|
|
37
|
+
}
|
|
38
|
+
else if (f && l.startsWith("+++ ") && !f.hunks.length) {
|
|
39
|
+
if (l.slice(4) === "/dev/null")
|
|
40
|
+
f.to = null;
|
|
41
|
+
else
|
|
42
|
+
f.to = strip(l.slice(4));
|
|
43
|
+
}
|
|
44
|
+
else if (f && l.startsWith("@@ ")) {
|
|
45
|
+
const m = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l);
|
|
46
|
+
if (!m)
|
|
47
|
+
continue;
|
|
48
|
+
let old = m[2] === undefined ? 1 : Number(m[2]), neu = m[3] === undefined ? 1 : Number(m[3]);
|
|
49
|
+
const h = { start: Number(m[1]), count: old, lines: [] };
|
|
50
|
+
// The counts say where the hunk ends, so a removed line that starts with `--` isn't a header.
|
|
51
|
+
while ((old > 0 || neu > 0) && i + 1 < lines.length) {
|
|
52
|
+
const t = lines[++i];
|
|
53
|
+
const op = t[0] ?? " ";
|
|
54
|
+
if (op === "\\")
|
|
55
|
+
continue;
|
|
56
|
+
if (op === "-")
|
|
57
|
+
old--;
|
|
58
|
+
else if (op === "+")
|
|
59
|
+
neu--;
|
|
60
|
+
else {
|
|
61
|
+
old--;
|
|
62
|
+
neu--;
|
|
63
|
+
}
|
|
64
|
+
h.lines.push({ op: op === "-" || op === "+" ? op : " ", text: t.slice(1) });
|
|
65
|
+
}
|
|
66
|
+
f.hunks.push(h);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Per-PR survival from `prs` in merge order. `opts.windowDays`: a removed line counts as rewritten when it was added at most
|
|
73
|
+
* that many days earlier. `opts.exclude`: globs of paths ignored. `added[pr]`: lines the PR added that were not moves.
|
|
74
|
+
* `rewritten`: per (pr, by_pr) the lines of `pr` that `by_pr` removed, and their mean age in whole days.
|
|
75
|
+
*/
|
|
76
|
+
export function churn(prs, opts) {
|
|
77
|
+
const skip = opts.exclude.map(globRe);
|
|
78
|
+
const excluded = (p) => skip.some((r) => r.test(p));
|
|
79
|
+
const files = new Map();
|
|
80
|
+
const added = {};
|
|
81
|
+
const rewritten = new Map();
|
|
82
|
+
for (const p of prs) {
|
|
83
|
+
const at = Date.parse(p.mergedAt);
|
|
84
|
+
const removed = [], fresh = [];
|
|
85
|
+
for (const d of parse(p.diff)) {
|
|
86
|
+
const path = d.to ?? d.from;
|
|
87
|
+
if (!path)
|
|
88
|
+
continue;
|
|
89
|
+
if (excluded(path) || (d.from && excluded(d.from))) {
|
|
90
|
+
if (d.from)
|
|
91
|
+
files.delete(d.from);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
let cells = (d.from ? files.get(d.from) : undefined) ?? [];
|
|
95
|
+
if (d.from)
|
|
96
|
+
files.delete(d.from);
|
|
97
|
+
let shift = 0;
|
|
98
|
+
for (const h of d.hunks) {
|
|
99
|
+
let i = (h.count === 0 ? h.start : h.start - 1) + shift;
|
|
100
|
+
for (const l of h.lines) {
|
|
101
|
+
if (l.op === " ")
|
|
102
|
+
i++;
|
|
103
|
+
else if (l.op === "-") {
|
|
104
|
+
while (cells.length <= i)
|
|
105
|
+
cells.push({ text: "", owner: null });
|
|
106
|
+
removed.push(...cells.splice(i, 1));
|
|
107
|
+
removed[removed.length - 1].text = l.text;
|
|
108
|
+
shift--;
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
const c = { text: l.text, owner: { pr: p.pr, at } };
|
|
112
|
+
while (cells.length < i)
|
|
113
|
+
cells.push({ text: "", owner: null }); // untracked history before the insertion: pad so it lands where it is, as a removal does
|
|
114
|
+
cells.splice(i, 0, c);
|
|
115
|
+
fresh.push(c);
|
|
116
|
+
i++;
|
|
117
|
+
shift++;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (d.to)
|
|
122
|
+
files.set(d.to, cells);
|
|
123
|
+
}
|
|
124
|
+
// Moves: an identical line removed and added by this one PR stays its first owner's.
|
|
125
|
+
const gone = new Map();
|
|
126
|
+
for (const r of removed) {
|
|
127
|
+
const k = r.text.trim();
|
|
128
|
+
if (k.length >= MIN_MOVE)
|
|
129
|
+
(gone.get(k) ?? gone.set(k, []).get(k)).push(r);
|
|
130
|
+
}
|
|
131
|
+
const moved = new Set();
|
|
132
|
+
for (const c of fresh) {
|
|
133
|
+
const r = gone.get(c.text.trim())?.pop();
|
|
134
|
+
if (!r)
|
|
135
|
+
continue;
|
|
136
|
+
c.owner = r.owner;
|
|
137
|
+
moved.add(r);
|
|
138
|
+
moved.add(c);
|
|
139
|
+
}
|
|
140
|
+
added[p.pr] = (added[p.pr] ?? 0) + fresh.filter((c) => !moved.has(c)).length;
|
|
141
|
+
for (const r of removed) {
|
|
142
|
+
if (moved.has(r) || !r.owner || r.owner.pr === p.pr)
|
|
143
|
+
continue;
|
|
144
|
+
const age = (at - r.owner.at) / DAY;
|
|
145
|
+
if (age > opts.windowDays)
|
|
146
|
+
continue;
|
|
147
|
+
const k = `${r.owner.pr}|${p.pr}`;
|
|
148
|
+
const e = rewritten.get(k) ?? rewritten.set(k, { pr: r.owner.pr, by_pr: p.pr, lines: 0, days: 0, sum: 0 }).get(k);
|
|
149
|
+
e.lines++;
|
|
150
|
+
e.sum += age;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return { added, rewritten: [...rewritten.values()].map(({ sum, ...e }) => ({ ...e, days: Math.round(sum / e.lines) })) };
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Churn over a repo's first-parent history through `git` (args → stdout, run in the repo): each commit whose subject
|
|
157
|
+
* names a PR (`prOf`) is one PR. With a `cursor` only the window before it is read again, so lines added just before it keep
|
|
158
|
+
* their owner; `fresh` says which of the results are new since it. `last`: the newest commit's time, the next cursor.
|
|
159
|
+
* `first`: without a cursor, only the newest that many commits (a first pass on the caller's own thread).
|
|
160
|
+
*/
|
|
161
|
+
export async function churnFromGit(git, o) {
|
|
162
|
+
const since = o.cursor ? [`--since=${new Date(Date.parse(o.cursor) - o.windowDays * DAY).toISOString()}`] : o.first ? [`--max-count=${o.first}`] : [];
|
|
163
|
+
const log = await git(["log", "--first-parent", "--reverse", "--format=%H%x09%cI%x09%s", ...since, o.rev]);
|
|
164
|
+
const prs = [];
|
|
165
|
+
for (const line of log.split("\n").filter(Boolean)) {
|
|
166
|
+
const [commit, mergedAt, ...rest] = line.split("\t");
|
|
167
|
+
const pr = o.prOf(rest.join("\t"));
|
|
168
|
+
if (!pr)
|
|
169
|
+
continue;
|
|
170
|
+
const args = ["diff", "-M", "-U0", "--no-ext-diff", "--no-textconv"];
|
|
171
|
+
const diff = await git([...args, `${commit}^1`, commit]).catch(() => git([...args, "4b825dc642cb6eb9a060e54bf8d69288fbee4904", commit])).catch((e) => { o.onError?.(commit, e); return ""; });
|
|
172
|
+
prs.push({ pr, mergedAt: mergedAt, diff, commit: commit });
|
|
173
|
+
}
|
|
174
|
+
const out = churn(prs, { windowDays: o.windowDays, exclude: o.exclude });
|
|
175
|
+
const fresh = (iso) => !o.cursor || Date.parse(iso) > Date.parse(o.cursor);
|
|
176
|
+
return { ...out, mergedAt: new Map(prs.map((p) => [p.pr, p.mergedAt])), fresh, last: prs.at(-1)?.mergedAt };
|
|
177
|
+
}
|