@hikae/ledger-core 0.3.1 → 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 +1 -1
- package/dist/authored.d.ts +21 -0
- package/dist/authored.js +26 -0
- package/dist/holds.d.ts +1 -1
- package/dist/holds.js +4 -4
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/issueMetrics.d.ts +40 -0
- package/dist/issueMetrics.js +78 -0
- package/dist/issueObservation.d.ts +7 -0
- package/dist/issueObservation.js +79 -0
- package/dist/ports.js +1 -1
- package/dist/pr.js +1 -1
- package/dist/reconcile.d.ts +26 -0
- package/dist/reconcile.js +47 -0
- package/dist/review-action.d.ts +35 -0
- package/dist/review-action.js +33 -0
- package/dist/review-gate.d.ts +56 -0
- package/dist/review-gate.js +85 -0
- package/dist/review-request.d.ts +54 -0
- package/dist/review-request.js +94 -0
- package/dist/review-target.d.ts +52 -0
- package/dist/review-target.js +75 -0
- package/dist/stage.js +1 -1
- package/dist/tiers.d.ts +1 -1
- package/package.json +14 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @hikae/ledger-core
|
|
2
2
|
|
|
3
|
-
Pure core shared by the local ledger agent and a
|
|
3
|
+
Pure core shared by the local ledger agent and a host (the libghostty of ledger). No I/O, no cloud SDKs.
|
|
4
4
|
|
|
5
5
|
- `tiers`: ladder-based self-improving model routing (`seedFor`, `tierFor`, `evolve`).
|
|
6
6
|
- `stage`: Issue factory stage machine (`issueStage`, `ISSUE_STAGES`).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type Reason = "mergeable" | "draft" | "conflicting" | "ci_failed" | "re_request" | "needs_reviewer" | "waiting_ci" | "review_requested" | "blocked";
|
|
2
|
+
export type AuthoredStatus = "mine_ready_to_merge" | "mine_changes_requested" | "mine_review_requested";
|
|
3
|
+
export interface Review {
|
|
4
|
+
login: string;
|
|
5
|
+
state: string;
|
|
6
|
+
canPush: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** pending: currently requested (yellow). responded: latest human review whose author is not re-requested. */
|
|
9
|
+
export interface Reviewers {
|
|
10
|
+
pending: string[];
|
|
11
|
+
responded: Review[];
|
|
12
|
+
}
|
|
13
|
+
/** Lean `ball`: the author acts on draft, conflicts, red CI and reviews to answer; otherwise reviewers do, or it merges. */
|
|
14
|
+
export declare const ball: (r: Reason) => AuthoredStatus;
|
|
15
|
+
/** Lean `classify`. CLEAN/HAS_HOOKS means GitHub already evaluated branch protection (CODEOWNERS included) as satisfied. */
|
|
16
|
+
export declare function classify(n: {
|
|
17
|
+
isDraft: boolean;
|
|
18
|
+
mergeable: string;
|
|
19
|
+
mergeStateStatus: string;
|
|
20
|
+
checks: string | null;
|
|
21
|
+
}, rv: Reviewers): Reason;
|
package/dist/authored.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Where my own PR stands and whose turn it is. Proved in formal/Formal/Authored.lean; check-core.mjs compares the two.
|
|
2
|
+
const AUTHOR_ACTION = new Set(["draft", "conflicting", "ci_failed", "re_request", "needs_reviewer"]);
|
|
3
|
+
/** Lean `ball`: the author acts on draft, conflicts, red CI and reviews to answer; otherwise reviewers do, or it merges. */
|
|
4
|
+
export const ball = (r) => r === "mergeable" ? "mine_ready_to_merge" : AUTHOR_ACTION.has(r) ? "mine_changes_requested" : "mine_review_requested";
|
|
5
|
+
/** Lean `classify`. CLEAN/HAS_HOOKS means GitHub already evaluated branch protection (CODEOWNERS included) as satisfied. */
|
|
6
|
+
export function classify(n, rv) {
|
|
7
|
+
if (n.isDraft)
|
|
8
|
+
return "draft";
|
|
9
|
+
if (n.mergeable === "CONFLICTING" || n.mergeStateStatus === "DIRTY")
|
|
10
|
+
return "conflicting";
|
|
11
|
+
if (n.mergeable === "MERGEABLE" && ["CLEAN", "HAS_HOOKS"].includes(n.mergeStateStatus))
|
|
12
|
+
return "mergeable";
|
|
13
|
+
if (n.checks === "FAILURE" || n.checks === "ERROR")
|
|
14
|
+
return "ci_failed";
|
|
15
|
+
// A counted approval needs no follow-up; any other non-yellow review needs a response and re-request.
|
|
16
|
+
const counted = rv.responded.filter((r) => r.state === "APPROVED" && r.canPush);
|
|
17
|
+
if (rv.responded.some((r) => r.state !== "APPROVED"))
|
|
18
|
+
return "re_request";
|
|
19
|
+
if (!rv.pending.length && !counted.length)
|
|
20
|
+
return "needs_reviewer";
|
|
21
|
+
if (n.checks === "PENDING" || n.checks === "EXPECTED")
|
|
22
|
+
return "waiting_ci";
|
|
23
|
+
if (rv.pending.length)
|
|
24
|
+
return "review_requested";
|
|
25
|
+
return "blocked";
|
|
26
|
+
}
|
package/dist/holds.d.ts
CHANGED
|
@@ -17,5 +17,5 @@ export declare const HUMAN_HOLD_LABEL = "factory:paused";
|
|
|
17
17
|
export declare const BOT_HOLD_LABEL = "factory:held";
|
|
18
18
|
/** Active at `now` for the item's current head. */
|
|
19
19
|
export declare function holdActive(h: Hold, now: number, headSha?: string): boolean;
|
|
20
|
-
/** Holds a label set implies (
|
|
20
|
+
/** Holds a label set implies (a host stores holds as labels). */
|
|
21
21
|
export declare function labelHolds(key: string, labels: Iterable<string>, at: string): Hold[];
|
package/dist/holds.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Holds: why an item (or the whole provider) is not being worked on. The union of ledger's doctor holds, task HOLD
|
|
2
|
-
// answers and escalation refusals with
|
|
2
|
+
// answers and escalation refusals with a host's label holds, provider hold, failure-count holds and leases.
|
|
3
3
|
export const HOLD_REASONS = [
|
|
4
|
-
//
|
|
4
|
+
// queue-side holds (a local queue: drafts, scopes, parked or dispatched items)
|
|
5
5
|
"draft", "scope_excluded", "approved_at_head", "merge_loop", "parked", "dispatched_to_human", "escalation_refused",
|
|
6
|
-
//
|
|
6
|
+
// store-side holds (labels, provider back-off, failure counts, leases)
|
|
7
7
|
"human_label", "bot_label", "provider", "repair_failures", "triage_failures", "lease", "lock",
|
|
8
8
|
// both
|
|
9
9
|
"owner_hold",
|
|
@@ -18,7 +18,7 @@ export function holdActive(h, now, headSha) {
|
|
|
18
18
|
return false;
|
|
19
19
|
return true;
|
|
20
20
|
}
|
|
21
|
-
/** Holds a label set implies (
|
|
21
|
+
/** Holds a label set implies (a host stores holds as labels). */
|
|
22
22
|
export function labelHolds(key, labels, at) {
|
|
23
23
|
const s = new Set([...labels].map((l) => l.toLowerCase()));
|
|
24
24
|
const out = [];
|
package/dist/index.d.ts
CHANGED
|
@@ -5,3 +5,9 @@ export * from "./holds.js";
|
|
|
5
5
|
export * from "./ports.js";
|
|
6
6
|
export * from "./review.js";
|
|
7
7
|
export * from "./issue.js";
|
|
8
|
+
export * from "./review-request.js";
|
|
9
|
+
export * from "./review-target.js";
|
|
10
|
+
export * from "./review-gate.js";
|
|
11
|
+
export * from "./reconcile.js";
|
|
12
|
+
export * from "./authored.js";
|
|
13
|
+
export * from "./review-action.js";
|
package/dist/index.js
CHANGED
|
@@ -5,3 +5,9 @@ export * from "./holds.js";
|
|
|
5
5
|
export * from "./ports.js";
|
|
6
6
|
export * from "./review.js";
|
|
7
7
|
export * from "./issue.js";
|
|
8
|
+
export * from "./review-request.js";
|
|
9
|
+
export * from "./review-target.js";
|
|
10
|
+
export * from "./review-gate.js";
|
|
11
|
+
export * from "./reconcile.js";
|
|
12
|
+
export * from "./authored.js";
|
|
13
|
+
export * from "./review-action.js";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export declare const HOUR = 3600000, DAY: number;
|
|
2
|
+
export declare const dayStart: (at: number) => number;
|
|
3
|
+
export type IssueEvent = {
|
|
4
|
+
id: string;
|
|
5
|
+
at: number;
|
|
6
|
+
state: 'OPEN' | 'CLOSED';
|
|
7
|
+
reason?: string | null;
|
|
8
|
+
};
|
|
9
|
+
type Change = {
|
|
10
|
+
at: number;
|
|
11
|
+
kind: 'created' | 'reopened' | 'closed';
|
|
12
|
+
firstHours?: number;
|
|
13
|
+
reason?: string | null;
|
|
14
|
+
};
|
|
15
|
+
export type Issue = {
|
|
16
|
+
id: string;
|
|
17
|
+
created: number;
|
|
18
|
+
changes: Change[];
|
|
19
|
+
};
|
|
20
|
+
export declare function issueTransitions(id: string, created: number, events: IssueEvent[]): Issue;
|
|
21
|
+
export declare function issueBuckets(issues: Issue[], start: number, until: number, width: number): {
|
|
22
|
+
completed: number | null;
|
|
23
|
+
net: number;
|
|
24
|
+
open: number;
|
|
25
|
+
ageDays: {
|
|
26
|
+
median: number | null;
|
|
27
|
+
p90: number | null;
|
|
28
|
+
};
|
|
29
|
+
first: number;
|
|
30
|
+
firstHours: {
|
|
31
|
+
median: number | null;
|
|
32
|
+
p90: number | null;
|
|
33
|
+
};
|
|
34
|
+
created: number;
|
|
35
|
+
reopened: number;
|
|
36
|
+
closed: number;
|
|
37
|
+
start: number;
|
|
38
|
+
end: number;
|
|
39
|
+
}[];
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Snapshot cutoff and bucket ends are exclusive. GitHub timeline order breaks ties within a second.
|
|
2
|
+
export const HOUR = 3_600_000, DAY = 24 * HOUR;
|
|
3
|
+
const JST = 9 * HOUR;
|
|
4
|
+
export const dayStart = (at) => Math.floor((at + JST) / DAY) * DAY - JST;
|
|
5
|
+
export function issueTransitions(id, created, events) {
|
|
6
|
+
if (!id || !Number.isFinite(created))
|
|
7
|
+
throw new Error('Missing issue identity or creation time');
|
|
8
|
+
let open = true, previouslyClosed = false;
|
|
9
|
+
const changes = [{ at: created, kind: 'created' }];
|
|
10
|
+
const seen = new Set();
|
|
11
|
+
for (const event of [...events].sort((a, b) => a.at - b.at)) {
|
|
12
|
+
if (!event.id || !Number.isFinite(event.at) || event.at < created)
|
|
13
|
+
throw new Error('Invalid issue event');
|
|
14
|
+
if (seen.has(event.id))
|
|
15
|
+
continue;
|
|
16
|
+
seen.add(event.id);
|
|
17
|
+
if (open === (event.state === 'OPEN'))
|
|
18
|
+
continue;
|
|
19
|
+
open = !open;
|
|
20
|
+
if (open)
|
|
21
|
+
changes.push({ at: event.at, kind: 'reopened' });
|
|
22
|
+
else {
|
|
23
|
+
const close = { at: event.at, kind: 'closed', reason: event.reason?.toUpperCase() };
|
|
24
|
+
if (!previouslyClosed)
|
|
25
|
+
close.firstHours = (event.at - created) / HOUR;
|
|
26
|
+
changes.push(close);
|
|
27
|
+
previouslyClosed = true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { id, created, changes };
|
|
31
|
+
}
|
|
32
|
+
function distribution(values) {
|
|
33
|
+
values.sort((a, b) => a - b);
|
|
34
|
+
function quantile(p) {
|
|
35
|
+
if (!values.length)
|
|
36
|
+
return null;
|
|
37
|
+
const i = (values.length - 1) * p, lo = values[Math.floor(i)], hi = values[Math.ceil(i)];
|
|
38
|
+
return Number((lo + (hi - lo) * (i % 1)).toFixed(4));
|
|
39
|
+
}
|
|
40
|
+
return { median: quantile(0.5), p90: quantile(0.9) };
|
|
41
|
+
}
|
|
42
|
+
// Replay each transition once per series. Age always starts at creation, including after a reopen.
|
|
43
|
+
export function issueBuckets(issues, start, until, width) {
|
|
44
|
+
if (![start, until, width].every(Number.isFinite) || width <= 0 || until < start)
|
|
45
|
+
throw new Error('Invalid window');
|
|
46
|
+
const events = issues.flatMap(issue => issue.changes.map(change => ({ ...change, id: issue.id, createdAt: issue.created })))
|
|
47
|
+
.sort((a, b) => a.at - b.at);
|
|
48
|
+
const open = new Map();
|
|
49
|
+
let index = 0;
|
|
50
|
+
const rows = [];
|
|
51
|
+
for (let at = start; at < until; at += width) {
|
|
52
|
+
const end = Math.min(at + width, until), hours = [];
|
|
53
|
+
const counts = { created: 0, reopened: 0, closed: 0 };
|
|
54
|
+
let completed = 0, missingReason = 0;
|
|
55
|
+
while (index < events.length && events[index].at < end) {
|
|
56
|
+
const event = events[index++];
|
|
57
|
+
if (event.kind === 'closed')
|
|
58
|
+
open.delete(event.id);
|
|
59
|
+
else
|
|
60
|
+
open.set(event.id, event.createdAt);
|
|
61
|
+
if (event.at < at)
|
|
62
|
+
continue;
|
|
63
|
+
counts[event.kind]++;
|
|
64
|
+
if (event.kind === 'closed') {
|
|
65
|
+
if (event.reason === 'COMPLETED')
|
|
66
|
+
completed++;
|
|
67
|
+
else if (!event.reason)
|
|
68
|
+
missingReason++;
|
|
69
|
+
}
|
|
70
|
+
if (event.firstHours !== undefined)
|
|
71
|
+
hours.push(event.firstHours);
|
|
72
|
+
}
|
|
73
|
+
rows.push({ start: at, end, ...counts, completed: missingReason ? null : completed, net: counts.created + counts.reopened - counts.closed,
|
|
74
|
+
open: open.size, ageDays: distribution(Array.from(open.values(), created => (end - created) / DAY)),
|
|
75
|
+
first: hours.length, firstHours: distribution(hours) });
|
|
76
|
+
}
|
|
77
|
+
return rows;
|
|
78
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Issue } from './issueMetrics.js';
|
|
2
|
+
type Params = Record<string, string | string[] | null>;
|
|
3
|
+
export declare function collectRepo(fullName: string, token: string, start: number, request: (path: string, token: string, body: {
|
|
4
|
+
query: string;
|
|
5
|
+
variables: Params;
|
|
6
|
+
}) => Promise<any>): Promise<Map<string, Issue>>;
|
|
7
|
+
export {};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { issueTransitions } from './issueMetrics.js';
|
|
2
|
+
const page = 'pageInfo { hasNextPage endCursor }';
|
|
3
|
+
const timeline = (size) => `timelineItems(first:${size}, after:$eventCursor, itemTypes:[CLOSED_EVENT,REOPENED_EVENT]){
|
|
4
|
+
totalCount nodes { __typename ... on ClosedEvent { id createdAt stateReason } ... on ReopenedEvent { id createdAt } } ${page}}`;
|
|
5
|
+
const openQuery = `query($owner:String!,$name:String!,$after:String){repository(owner:$owner,name:$name){
|
|
6
|
+
issues(first:100,after:$after,states:[OPEN],orderBy:{field:CREATED_AT,direction:ASC}){
|
|
7
|
+
nodes {id createdAt updatedAt} ${page}}}}`;
|
|
8
|
+
const changedQuery = `query($owner:String!,$name:String!,$after:String,$since:DateTime!){
|
|
9
|
+
repository(owner:$owner,name:$name){issues(first:50,after:$after,filterBy:{since:$since},orderBy:{field:CREATED_AT,direction:ASC}){
|
|
10
|
+
nodes {id state closedAt} ${page}}}}`;
|
|
11
|
+
// GitHub can truncate filtered timeline connections when identical page arguments are batched across issues,
|
|
12
|
+
// even returning totalCount:0 for a closed Issue. Give each connection its own page size and follow its cursor.
|
|
13
|
+
function historyBatch(ids) {
|
|
14
|
+
const declarations = ids.map((_, i) => `$id${i}:ID!`);
|
|
15
|
+
const fields = ids.map((_, i) => `issue${i}:node(id:$id${i}){... on Issue{id createdAt state ${timeline(50 + i)}}}`);
|
|
16
|
+
return { query: `query(${declarations.join(',')},$eventCursor:String){${fields.join(' ')}}`,
|
|
17
|
+
variables: Object.fromEntries(ids.map((id, i) => ['id' + i, id])) };
|
|
18
|
+
}
|
|
19
|
+
const eventsQuery = `query($id:ID!,$eventCursor:String){node(id:$id){... on Issue{${timeline(100)}}}}`;
|
|
20
|
+
async function* paginate(read) {
|
|
21
|
+
let cursor = null;
|
|
22
|
+
do {
|
|
23
|
+
const { nodes, pageInfo } = await read(cursor);
|
|
24
|
+
if (!Array.isArray(nodes) || typeof pageInfo?.hasNextPage !== 'boolean')
|
|
25
|
+
throw new Error('Incomplete GitHub page');
|
|
26
|
+
yield* nodes;
|
|
27
|
+
if (!pageInfo.hasNextPage)
|
|
28
|
+
break;
|
|
29
|
+
if (!pageInfo.endCursor || pageInfo.endCursor === cursor)
|
|
30
|
+
throw new Error('Missing GitHub cursor');
|
|
31
|
+
cursor = pageInfo.endCursor;
|
|
32
|
+
} while (true);
|
|
33
|
+
}
|
|
34
|
+
export async function collectRepo(fullName, token, start, request) {
|
|
35
|
+
const [owner, name, extra] = fullName.split('/');
|
|
36
|
+
if (!owner || !name || extra !== undefined)
|
|
37
|
+
throw new Error('Invalid repository name');
|
|
38
|
+
const query = async (query, variables) => {
|
|
39
|
+
const result = await request('graphql', token, { query, variables });
|
|
40
|
+
if (result.errors?.length || !result.data)
|
|
41
|
+
throw new Error('Incomplete GitHub issue query');
|
|
42
|
+
return result.data;
|
|
43
|
+
};
|
|
44
|
+
const issues = new Map();
|
|
45
|
+
// Unchanged open issues supply the historical backlog. Changed issues (open AND closed) get full lifetime events.
|
|
46
|
+
for await (const item of paginate(async (after) => (await query(openQuery, { owner, name, after })).repository.issues)) {
|
|
47
|
+
if (Date.parse(item.updatedAt) < start)
|
|
48
|
+
issues.set(item.id, issueTransitions(item.id, Date.parse(item.createdAt), []));
|
|
49
|
+
}
|
|
50
|
+
const changedIds = new Set();
|
|
51
|
+
for await (const item of paginate(async (after) => (await query(changedQuery, { owner, name, after, since: new Date(start).toISOString() })).repository.issues)) {
|
|
52
|
+
if (item.state !== 'CLOSED' || Date.parse(item.closedAt ?? '') >= start || !item.closedAt)
|
|
53
|
+
changedIds.add(item.id);
|
|
54
|
+
}
|
|
55
|
+
const ids = [...changedIds];
|
|
56
|
+
for (let offset = 0; offset < ids.length; offset += 25) {
|
|
57
|
+
const batch = ids.slice(offset, offset + 25);
|
|
58
|
+
const history = historyBatch(batch);
|
|
59
|
+
const nodes = await query(history.query, history.variables);
|
|
60
|
+
for (const [index, id] of batch.entries()) {
|
|
61
|
+
const item = nodes['issue' + index];
|
|
62
|
+
if (item?.id !== id)
|
|
63
|
+
throw new Error('Issue disappeared during observation');
|
|
64
|
+
const events = [];
|
|
65
|
+
for await (const event of paginate(async (cursor) => cursor
|
|
66
|
+
? (await query(eventsQuery, { id: item.id, eventCursor: cursor })).node.timelineItems : item.timelineItems)) {
|
|
67
|
+
if (!['ClosedEvent', 'ReopenedEvent'].includes(event.__typename))
|
|
68
|
+
throw new Error('Unknown issue event');
|
|
69
|
+
events.push({ id: event.id, at: Date.parse(event.createdAt), reason: event.stateReason, state: event.__typename === 'ClosedEvent' ? 'CLOSED' : 'OPEN' });
|
|
70
|
+
}
|
|
71
|
+
const issue = issueTransitions(item.id, Date.parse(item.createdAt), events);
|
|
72
|
+
if (new Set(events.map(e => e.id)).size !== item.timelineItems.totalCount ||
|
|
73
|
+
item.state !== (issue.changes.at(-1)?.kind === 'closed' ? 'CLOSED' : 'OPEN'))
|
|
74
|
+
throw new Error('Incomplete lifetime issue history');
|
|
75
|
+
issues.set(item.id, issue);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return issues;
|
|
79
|
+
}
|
package/dist/ports.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
// Ports: what the core needs from its host. A
|
|
1
|
+
// Ports: what the core needs from its host. A host implements them with DynamoDB/S3/GitHub App; the local ledger with
|
|
2
2
|
// SQLite/files/gh. The core never imports a host SDK.
|
|
3
3
|
export const systemClock = { now: () => Date.now() };
|
package/dist/pr.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// PR ledger row statuses and the invalidation transition, shared by ledger (app/src/ledger.ts) and
|
|
1
|
+
// PR ledger row statuses and the invalidation transition, shared by ledger (app/src/ledger.ts) and a host
|
|
2
2
|
// (src/ledger.mjs). ledger's authored-PR statuses are part of the union.
|
|
3
3
|
export const ACTIVE_STATUSES = ["queued", "reviewing", "waiting_ci", "changes_requested", "ready_to_approve", "approval_pending_verification",
|
|
4
4
|
"approved", "human_required", "merged_waiting_release", "release_in_progress", "post_release_monitoring", "recovering",
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const MAX_ATTEMPTS = 3;
|
|
2
|
+
export declare const BACKOFF_MS: number;
|
|
3
|
+
type Job = Record<string, any> & {
|
|
4
|
+
url: string;
|
|
5
|
+
state: "waiting" | "running" | "done" | "exhausted";
|
|
6
|
+
attempts: number;
|
|
7
|
+
head: string;
|
|
8
|
+
updated: string;
|
|
9
|
+
};
|
|
10
|
+
type Target = Record<string, any> & {
|
|
11
|
+
url: string;
|
|
12
|
+
head: string;
|
|
13
|
+
updated: string;
|
|
14
|
+
};
|
|
15
|
+
/** A target with no job yet: fresh work with a full budget. */
|
|
16
|
+
export declare const freshJob: <T extends Target>(t: T, iso: string) => T & {
|
|
17
|
+
state: "waiting";
|
|
18
|
+
attempts: number;
|
|
19
|
+
enqueued_at: string;
|
|
20
|
+
};
|
|
21
|
+
/** Lean `step`: the entry after one sync. null = drop it (the plan re-adds a fresh job for a live target). */
|
|
22
|
+
export declare function reconcileJob<J extends Job>(job: J, t: Target | undefined, now: number, alive: (pid: number) => boolean, log?: (event: object) => void): {
|
|
23
|
+
job: J | null;
|
|
24
|
+
succeeded: boolean;
|
|
25
|
+
};
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// One queue entry against the latest observation of the world, whatever state a crash or outage left it in.
|
|
2
|
+
// Proved in formal/Formal/Reconcile.lean; check-core.mjs compares the two.
|
|
3
|
+
import { holdSettles } from "./review-request.js";
|
|
4
|
+
export const MAX_ATTEMPTS = 3;
|
|
5
|
+
export const BACKOFF_MS = 10 * 60_000;
|
|
6
|
+
const ciPart = (updated) => updated.slice(updated.indexOf("|") + 1);
|
|
7
|
+
/** A target with no job yet: fresh work with a full budget. */
|
|
8
|
+
export const freshJob = (t, iso) => ({ ...t, state: "waiting", attempts: 0, enqueued_at: iso });
|
|
9
|
+
/** Lean `step`: the entry after one sync. null = drop it (the plan re-adds a fresh job for a live target). */
|
|
10
|
+
export function reconcileJob(job, t, now, alive, log = () => { }) {
|
|
11
|
+
const iso = new Date(now).toISOString();
|
|
12
|
+
// A worker still running keeps its slot; its exit is judged on a later tick.
|
|
13
|
+
if (job.state === "running" && job.pid && alive(job.pid))
|
|
14
|
+
return { job, succeeded: false };
|
|
15
|
+
if (!t)
|
|
16
|
+
return { job: null, succeeded: job.state === "running" && job.exit_code === 0 };
|
|
17
|
+
// A review that exited clean caused the only activity on its own PR (approval, comments) unless head or CI moved.
|
|
18
|
+
const ownWrite = !job.kind && job.state === "running" && job.exit_code === 0 && t.head === job.head && ciPart(t.updated) === ciPart(job.updated);
|
|
19
|
+
// A new head, PR activity or a CI outcome change is new work with a fresh budget.
|
|
20
|
+
if (t.head !== job.head || (t.updated !== job.updated && !ownWrite))
|
|
21
|
+
return { job: null, succeeded: false };
|
|
22
|
+
const base = ownWrite ? { ...job, updated: t.updated } : job;
|
|
23
|
+
if (base.state === "running" && base.exit_code !== 0 && base.rate_limited_until)
|
|
24
|
+
return { job: { ...base, pid: undefined, finished_at: iso, state: "waiting", attempts: Math.max(0, base.attempts - 1), next_at: base.rate_limited_until, rate_limited_until: undefined }, succeeded: false };
|
|
25
|
+
if (base.state === "running" && base.exit_code !== 0 && base.nudge_session)
|
|
26
|
+
return { job: { ...base, pid: undefined, finished_at: iso, state: "waiting", attempts: Math.max(0, base.attempts - 1), next_at: undefined }, succeeded: false };
|
|
27
|
+
if (base.state === "running") {
|
|
28
|
+
const clean = base.exit_code === 0;
|
|
29
|
+
const ok = holdSettles(!base.kind && !!(t.requested || t.editable), clean);
|
|
30
|
+
if (clean && !ok)
|
|
31
|
+
log({ event: "REQUESTED_HOLD", url: base.url, attempt: base.attempts, at: iso });
|
|
32
|
+
return {
|
|
33
|
+
job: { ...base, pid: undefined, finished_at: iso, state: ok ? "done" : base.attempts >= MAX_ATTEMPTS ? "exhausted" : "waiting", next_at: ok ? undefined : new Date(now + BACKOFF_MS).toISOString(), peer_ok: undefined },
|
|
34
|
+
succeeded: ok,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
if (!base.kind && (t.requested || t.editable) && base.state === "done") {
|
|
38
|
+
// A hold settled before the requested rule (or before the request arrived) is still a silent hold on a requested PR.
|
|
39
|
+
return { job: { ...base, requested: t.requested, editable: t.editable, state: base.attempts >= MAX_ATTEMPTS ? "exhausted" : "waiting", next_at: undefined }, succeeded: false };
|
|
40
|
+
}
|
|
41
|
+
if (base.kind === "authored" && base.state === "done") {
|
|
42
|
+
// Still my turn at the same key: the verdict was transient (e.g. mergeable UNKNOWN), so the work is not done.
|
|
43
|
+
const out = base.attempts >= MAX_ATTEMPTS;
|
|
44
|
+
return { job: { ...base, state: out ? "exhausted" : "waiting", next_at: out ? undefined : new Date(now + BACKOFF_MS).toISOString() }, succeeded: false };
|
|
45
|
+
}
|
|
46
|
+
return { job: { ...base, priority: t.priority, scope: t.scope, evidence: t.evidence, requested: t.requested, editable: t.editable, members: t.members, error: t.error }, succeeded: false };
|
|
47
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export type ReviewAction = "review" | "changes_requested" | "human_required" | "wait_ci" | "approve";
|
|
2
|
+
export type Verdict = "approve" | "changes_requested" | "human_required";
|
|
3
|
+
export interface ActionFacts {
|
|
4
|
+
/** Review evidence exists. */
|
|
5
|
+
artifact: boolean;
|
|
6
|
+
/** Evidence is for another base/head, from the future, or stale. */
|
|
7
|
+
integrity: boolean;
|
|
8
|
+
verdict: Verdict;
|
|
9
|
+
draft: boolean;
|
|
10
|
+
/** Mergeability or merge state GitHub has computed and that blocks (not UNKNOWN). */
|
|
11
|
+
mergeHard: boolean;
|
|
12
|
+
/** Mergeability or merge state still UNKNOWN (resolves on a later sync). */
|
|
13
|
+
mergeLazy: boolean;
|
|
14
|
+
/** A required gate failed (review agents are advisory, see review-gate.ts). */
|
|
15
|
+
failed: boolean;
|
|
16
|
+
/** A required gate is pending. */
|
|
17
|
+
pending: boolean;
|
|
18
|
+
/** An active review requests changes on this head. */
|
|
19
|
+
changeActive: boolean;
|
|
20
|
+
/** Review threads are unresolved or their verification is stale. */
|
|
21
|
+
threads: boolean;
|
|
22
|
+
/** The evidence has unresolved blocking findings. */
|
|
23
|
+
blocking: boolean;
|
|
24
|
+
/** human_required for incident coordination. */
|
|
25
|
+
incident: boolean;
|
|
26
|
+
/** human_required evidence left diff/security/tests incomplete without an exempt reason. */
|
|
27
|
+
incomplete: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** Which branch decided, so the host can report the matching reasons. */
|
|
30
|
+
export type ActionPath = "missing" | "integrity" | "verdict_changes" | "incident" | "human_changes" | "human_failed" | "human_pending" | "human_blockers" | "human" | "changes" | "failed" | "blockers" | "approve";
|
|
31
|
+
/** Lean `reviewAction`. CI and UNKNOWN mergeability alone wait (`wait_ci`); anything else the author must change sends it back to review. */
|
|
32
|
+
export declare function reviewAction(f: ActionFacts): {
|
|
33
|
+
action: ReviewAction;
|
|
34
|
+
path: ActionPath;
|
|
35
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The verdict a review row may take now, from facts the evaluator reads off the row, the live PR and the evidence.
|
|
2
|
+
// Proved in formal/Formal/Action.lean; check-core.mjs compares the two. Reason strings stay with the host.
|
|
3
|
+
/** Lean `reviewAction`. CI and UNKNOWN mergeability alone wait (`wait_ci`); anything else the author must change sends it back to review. */
|
|
4
|
+
export function reviewAction(f) {
|
|
5
|
+
if (!f.artifact)
|
|
6
|
+
return { action: "review", path: "missing" };
|
|
7
|
+
if (f.integrity)
|
|
8
|
+
return { action: "review", path: "integrity" };
|
|
9
|
+
if (f.verdict === "changes_requested")
|
|
10
|
+
return { action: "changes_requested", path: "verdict_changes" };
|
|
11
|
+
const nonCi = f.draft || f.mergeHard || f.threads;
|
|
12
|
+
if (f.verdict === "human_required") {
|
|
13
|
+
if (f.incident)
|
|
14
|
+
return { action: "human_required", path: "incident" };
|
|
15
|
+
if (f.changeActive || f.blocking)
|
|
16
|
+
return { action: "changes_requested", path: "human_changes" };
|
|
17
|
+
if (f.failed)
|
|
18
|
+
return { action: nonCi ? "review" : "wait_ci", path: "human_failed" };
|
|
19
|
+
// Pending CI never hides what the author must still change: draft, a computed merge block, threads, gaps.
|
|
20
|
+
if (f.pending)
|
|
21
|
+
return { action: nonCi || f.incomplete ? "review" : "wait_ci", path: "human_pending" };
|
|
22
|
+
if (nonCi || f.mergeLazy || f.incomplete)
|
|
23
|
+
return { action: nonCi || f.incomplete ? "review" : "wait_ci", path: "human_blockers" };
|
|
24
|
+
return { action: "human_required", path: "human" };
|
|
25
|
+
}
|
|
26
|
+
if (f.changeActive || f.blocking)
|
|
27
|
+
return { action: "changes_requested", path: "changes" };
|
|
28
|
+
if (f.failed)
|
|
29
|
+
return { action: nonCi ? "review" : "wait_ci", path: "failed" };
|
|
30
|
+
if (nonCi || f.mergeLazy || f.pending)
|
|
31
|
+
return { action: nonCi ? "review" : "wait_ci", path: "blockers" };
|
|
32
|
+
return { action: "approve", path: "approve" };
|
|
33
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** pass: satisfied. pending: not yet. fail: says no. unavailable: the provider cannot answer (rate limit, outage). */
|
|
2
|
+
export type GateState = "pass" | "pending" | "fail" | "unavailable";
|
|
3
|
+
export interface Gate {
|
|
4
|
+
/** Provider name ("ci:build", "review-agent:CodeRabbit", "draft", "codeowners", ...); never read by the decision. */
|
|
5
|
+
source: string;
|
|
6
|
+
/** required: the verdict waits on it. advisory: helps when it answers, never holds the PR when it cannot. */
|
|
7
|
+
required: boolean;
|
|
8
|
+
state: GateState;
|
|
9
|
+
/** Minutes the gate has been in its state. */
|
|
10
|
+
age: number;
|
|
11
|
+
}
|
|
12
|
+
/** Minutes an advisory gate may stay pending before it counts as unavailable. */
|
|
13
|
+
export declare const ADVISORY_TIMEOUT_MIN = 60;
|
|
14
|
+
export type GateDecision = "go" | "wait" | "blocked";
|
|
15
|
+
/** Lean `effective`: an advisory gate that failed, cannot answer, or timed out drops out (null). */
|
|
16
|
+
export declare function effective(g: Gate, timeout?: number): GateState | null;
|
|
17
|
+
/** Lean `decide`: a required failure or unavailability blocks; anything still pending waits; otherwise go. */
|
|
18
|
+
export declare function decideGates(gates: Gate[], timeout?: number): GateDecision;
|
|
19
|
+
/** Lean `compose`: a stack goes only when every member goes; any blocked member blocks it. */
|
|
20
|
+
export declare function composeDecisions(ds: GateDecision[]): GateDecision;
|
|
21
|
+
/** Check names whose provider is a review agent (advisory), from config `review_agents`. */
|
|
22
|
+
export declare const DEFAULT_REVIEW_AGENTS: string[];
|
|
23
|
+
export interface CheckLike {
|
|
24
|
+
name: string;
|
|
25
|
+
state: "success" | "pending" | "failure";
|
|
26
|
+
since?: string;
|
|
27
|
+
}
|
|
28
|
+
/** A PR's checks as gates: review agents are advisory, everything else required. */
|
|
29
|
+
export declare function checkGates(checks: CheckLike[], now: number, agents?: string[]): Gate[];
|
|
30
|
+
/** Checks that still hold the verdict, named as the evaluator reports them. */
|
|
31
|
+
export declare function blockingChecks(checks: CheckLike[], now: number, agents?: string[], timeout?: number): {
|
|
32
|
+
failed: string[];
|
|
33
|
+
pending: string[];
|
|
34
|
+
};
|
|
35
|
+
/** Facts `stackDecision` reads (Lean `StackFacts`); the chain itself is built by the host from base/head refs. */
|
|
36
|
+
export interface StackFacts {
|
|
37
|
+
baseKnown: boolean;
|
|
38
|
+
/** A lone PR on the default branch. */
|
|
39
|
+
single: boolean;
|
|
40
|
+
/** Another PR also stacks on a member: not a line. */
|
|
41
|
+
branching: boolean;
|
|
42
|
+
rootOnDefault: boolean;
|
|
43
|
+
isTop: boolean;
|
|
44
|
+
/** Each member's own decision ("go" = mergeable). */
|
|
45
|
+
members: GateDecision[];
|
|
46
|
+
}
|
|
47
|
+
/** Lean `stackDecision`: stacked PRs land together, acted on from the top once every member goes. */
|
|
48
|
+
export declare function stackDecision(f: StackFacts): "single" | "stack" | "skip";
|
|
49
|
+
export interface StackNode {
|
|
50
|
+
repository: string;
|
|
51
|
+
base_ref?: string;
|
|
52
|
+
head_ref?: string;
|
|
53
|
+
}
|
|
54
|
+
/** Lean `stackOf`: own PRs chained by base→head in one repo, bottom first; walks down by the first PR whose head is
|
|
55
|
+
* the current base, up while exactly one PR stacks on the current head, never revisiting a member. */
|
|
56
|
+
export declare function stackOf<R extends StackNode>(row: R, all: R[]): R[];
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { asciiLower } from "./review-request.js";
|
|
2
|
+
/** Minutes an advisory gate may stay pending before it counts as unavailable. */
|
|
3
|
+
export const ADVISORY_TIMEOUT_MIN = 60;
|
|
4
|
+
/** Lean `effective`: an advisory gate that failed, cannot answer, or timed out drops out (null). */
|
|
5
|
+
export function effective(g, timeout = ADVISORY_TIMEOUT_MIN) {
|
|
6
|
+
if (g.required)
|
|
7
|
+
return g.state;
|
|
8
|
+
if (g.state === "pass" || g.state === "fail" || g.state === "unavailable")
|
|
9
|
+
return null;
|
|
10
|
+
return g.age > timeout ? null : "pending";
|
|
11
|
+
}
|
|
12
|
+
/** Lean `decide`: a required failure or unavailability blocks; anything still pending waits; otherwise go. */
|
|
13
|
+
export function decideGates(gates, timeout = ADVISORY_TIMEOUT_MIN) {
|
|
14
|
+
const states = gates.map((g) => effective(g, timeout));
|
|
15
|
+
if (states.some((s) => s === "fail" || s === "unavailable"))
|
|
16
|
+
return "blocked";
|
|
17
|
+
if (states.some((s) => s === "pending"))
|
|
18
|
+
return "wait";
|
|
19
|
+
return "go";
|
|
20
|
+
}
|
|
21
|
+
/** Lean `compose`: a stack goes only when every member goes; any blocked member blocks it. */
|
|
22
|
+
export function composeDecisions(ds) {
|
|
23
|
+
if (ds.includes("blocked"))
|
|
24
|
+
return "blocked";
|
|
25
|
+
if (ds.includes("wait"))
|
|
26
|
+
return "wait";
|
|
27
|
+
return "go";
|
|
28
|
+
}
|
|
29
|
+
/** Check names whose provider is a review agent (advisory), from config `review_agents`. */
|
|
30
|
+
export const DEFAULT_REVIEW_AGENTS = ["CodeRabbit"];
|
|
31
|
+
/** A PR's checks as gates: review agents are advisory, everything else required. */
|
|
32
|
+
export function checkGates(checks, now, agents = DEFAULT_REVIEW_AGENTS) {
|
|
33
|
+
const isAgent = new Set(agents.map((a) => asciiLower(a)));
|
|
34
|
+
return checks.map((c) => {
|
|
35
|
+
const since = c.since ? Date.parse(c.since) : NaN;
|
|
36
|
+
return {
|
|
37
|
+
source: c.name,
|
|
38
|
+
required: !isAgent.has(asciiLower(c.name)),
|
|
39
|
+
state: c.state === "success" ? "pass" : c.state === "pending" ? "pending" : "fail",
|
|
40
|
+
age: Number.isFinite(since) ? Math.max(0, Math.floor((now - since) / 60_000)) : 0,
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/** Checks that still hold the verdict, named as the evaluator reports them. */
|
|
45
|
+
export function blockingChecks(checks, now, agents = DEFAULT_REVIEW_AGENTS, timeout = ADVISORY_TIMEOUT_MIN) {
|
|
46
|
+
const gates = checkGates(checks, now, agents);
|
|
47
|
+
const failed = [], pending = [];
|
|
48
|
+
for (const g of gates) {
|
|
49
|
+
const s = effective(g, timeout);
|
|
50
|
+
if (s === "fail" || s === "unavailable")
|
|
51
|
+
failed.push(g.source);
|
|
52
|
+
else if (s === "pending")
|
|
53
|
+
pending.push(g.source);
|
|
54
|
+
}
|
|
55
|
+
return { failed, pending };
|
|
56
|
+
}
|
|
57
|
+
/** Lean `stackDecision`: stacked PRs land together, acted on from the top once every member goes. */
|
|
58
|
+
export function stackDecision(f) {
|
|
59
|
+
if (!f.baseKnown)
|
|
60
|
+
return "skip";
|
|
61
|
+
if (f.single)
|
|
62
|
+
return "single";
|
|
63
|
+
if (f.branching || !f.rootOnDefault || !f.isTop)
|
|
64
|
+
return "skip";
|
|
65
|
+
return composeDecisions(f.members) === "go" ? "stack" : "skip";
|
|
66
|
+
}
|
|
67
|
+
/** Lean `stackOf`: own PRs chained by base→head in one repo, bottom first; walks down by the first PR whose head is
|
|
68
|
+
* the current base, up while exactly one PR stacks on the current head, never revisiting a member. */
|
|
69
|
+
export function stackOf(row, all) {
|
|
70
|
+
const same = all.filter((r) => r.repository === row.repository && r.head_ref);
|
|
71
|
+
const chain = [row];
|
|
72
|
+
for (let cur = row;;) {
|
|
73
|
+
const below = same.find((r) => r.head_ref === cur.base_ref);
|
|
74
|
+
if (!below || chain.includes(below))
|
|
75
|
+
break;
|
|
76
|
+
chain.unshift((cur = below));
|
|
77
|
+
}
|
|
78
|
+
for (let cur = row;;) {
|
|
79
|
+
const above = same.filter((r) => r.base_ref === cur.head_ref);
|
|
80
|
+
if (above.length !== 1 || chain.includes(above[0]))
|
|
81
|
+
break;
|
|
82
|
+
chain.push((cur = above[0]));
|
|
83
|
+
}
|
|
84
|
+
return chain;
|
|
85
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
type Row = Record<string, any>;
|
|
2
|
+
/** required: someone asked me, so the run must leave a verdict. optional: I picked it up myself, so silence is fine and another reviewer may own it. */
|
|
3
|
+
export type ReviewStrength = "required" | "optional";
|
|
4
|
+
export interface ReviewRequest {
|
|
5
|
+
/** Where the request came from: "github", "review-poller", "task", or any other tool's name. */
|
|
6
|
+
source: string;
|
|
7
|
+
/** Who asked (login, task id); null when unknown. */
|
|
8
|
+
from: string | null;
|
|
9
|
+
/** Queue scope the request belongs to; "direct" when it is not a poller scope. */
|
|
10
|
+
scope: string;
|
|
11
|
+
strength: ReviewStrength;
|
|
12
|
+
active: boolean;
|
|
13
|
+
at?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare const DIRECT = "direct";
|
|
16
|
+
export declare const POLLER_SOURCE = "review-poller";
|
|
17
|
+
/** Every review request a ledger row carries: the generic `review_requests` list plus the fields older intake paths write. */
|
|
18
|
+
export declare function reviewRequests(row: Row): ReviewRequest[];
|
|
19
|
+
/** Lean `requested`: some active request requires a verdict. */
|
|
20
|
+
export declare const isRequested: (reqs: ReviewRequest[]) => boolean;
|
|
21
|
+
/** Lean `scopeOf`: the first active scoped request's scope, else direct. */
|
|
22
|
+
export declare const scopeOf: (reqs: ReviewRequest[]) => string;
|
|
23
|
+
/** The queue's reading of a row: its scope and whether any active request requires a verdict. */
|
|
24
|
+
export declare function reviewIntent(row: Row): {
|
|
25
|
+
scope: string;
|
|
26
|
+
requested: boolean;
|
|
27
|
+
};
|
|
28
|
+
/** Add or refresh one tool's request on a row (keyed by source + from); returns whether the row changed. */
|
|
29
|
+
export declare function putReviewRequest(row: Row, req: ReviewRequest): boolean;
|
|
30
|
+
/** What other reviewers did on the PR, abstracted to the facts the ownership rule reads (Lean `Peers`). */
|
|
31
|
+
export interface Peers {
|
|
32
|
+
/** Another human (not the author, me, or a bot) approved, requested changes, or commented. */
|
|
33
|
+
reviewed: boolean;
|
|
34
|
+
/** One of those reviews is an approval. */
|
|
35
|
+
approved: boolean;
|
|
36
|
+
botAuthor: boolean;
|
|
37
|
+
/** GitHub still says REVIEW_REQUIRED (second approval, CODEOWNERS). */
|
|
38
|
+
reviewRequired: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** Lean `Formal.lower`: ASCII-only lower case, so code and model agree on every string (GitHub logins and repo names are ASCII). */
|
|
41
|
+
export declare const asciiLower: (s: string) => string;
|
|
42
|
+
export declare const isBotLogin: (login: string) => boolean;
|
|
43
|
+
/** Lean `Who`: how `peers` classifies a review's login. */
|
|
44
|
+
export type Who = "unknown" | "author" | "self" | "bot" | "human";
|
|
45
|
+
/** Lean `whoOf`: empty → unknown; exact author → author; case-folded `selves` → self; review bots → bot; else human. */
|
|
46
|
+
export declare function whoOf(login: string, author: string, selves: Set<string>): Who;
|
|
47
|
+
export declare function peers(live: Row, selves: Set<string>): Peers;
|
|
48
|
+
/** Lean `takenByOther`: a peer owns the PR, unless it is bot-authored or GitHub still wants one more approval. */
|
|
49
|
+
export declare const takenByOther: (p: Peers) => boolean;
|
|
50
|
+
/** Lean `admitted`: a queued PR stays in my queue when someone asked me, or no peer owns it. */
|
|
51
|
+
export declare const admitted: (reqs: ReviewRequest[], p: Peers) => boolean;
|
|
52
|
+
/** Lean `holdSettles`: a clean exit settles a run as done only when it owes no verdict (requested, or a bot PR it must fix). */
|
|
53
|
+
export declare const holdSettles: (owesVerdict: boolean, clean: boolean) => boolean;
|
|
54
|
+
export {};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
export const DIRECT = "direct";
|
|
2
|
+
export const POLLER_SOURCE = "review-poller";
|
|
3
|
+
const LEGACY_REASON = "team poller";
|
|
4
|
+
const str = (v) => (typeof v === "string" && v ? v : null);
|
|
5
|
+
const at = (v) => (str(v) ? { at: v } : {});
|
|
6
|
+
/** A generic `review_requests` entry written by any tool; malformed entries are dropped. */
|
|
7
|
+
function generic(v) {
|
|
8
|
+
if (!v || typeof v !== "object")
|
|
9
|
+
return null;
|
|
10
|
+
const r = v;
|
|
11
|
+
const source = str(r.source);
|
|
12
|
+
if (!source || (r.strength !== "required" && r.strength !== "optional"))
|
|
13
|
+
return null;
|
|
14
|
+
return { source, from: str(r.from), scope: str(r.scope) ?? DIRECT, strength: r.strength, active: r.active !== false, ...at(r.at) };
|
|
15
|
+
}
|
|
16
|
+
/** Every review request a ledger row carries: the generic `review_requests` list plus the fields older intake paths write. */
|
|
17
|
+
export function reviewRequests(row) {
|
|
18
|
+
const out = [];
|
|
19
|
+
const intake = row.intake ?? {};
|
|
20
|
+
if (intake.source === POLLER_SOURCE) {
|
|
21
|
+
const scope = str(intake.scope);
|
|
22
|
+
if (scope)
|
|
23
|
+
out.push({ source: POLLER_SOURCE, from: null, scope, strength: "optional", active: true, ...at(intake.observed_at) });
|
|
24
|
+
}
|
|
25
|
+
else if (String(intake.reason ?? "").includes(LEGACY_REASON))
|
|
26
|
+
out.push({ source: POLLER_SOURCE, from: null, scope: "ai-driven-dev", strength: "optional", active: true });
|
|
27
|
+
const gh = row.review_request;
|
|
28
|
+
if (gh && typeof gh === "object")
|
|
29
|
+
out.push({ source: "github", from: str(gh.reviewer), scope: DIRECT, strength: "required", active: gh.active === true, ...at(gh.observed_at) });
|
|
30
|
+
if (row.ask)
|
|
31
|
+
out.push({ source: "task", from: str(row.ask.task), scope: DIRECT, strength: "required", active: true, ...at(row.ask.at) });
|
|
32
|
+
for (const r of Array.isArray(row.review_requests) ? row.review_requests : []) {
|
|
33
|
+
const g = generic(r);
|
|
34
|
+
if (g)
|
|
35
|
+
out.push(g);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Lean `requested`: some active request requires a verdict. */
|
|
40
|
+
export const isRequested = (reqs) => reqs.some((r) => r.active && r.strength === "required");
|
|
41
|
+
/** Lean `scopeOf`: the first active scoped request's scope, else direct. */
|
|
42
|
+
export const scopeOf = (reqs) => reqs.find((r) => r.active && r.scope !== DIRECT)?.scope ?? DIRECT;
|
|
43
|
+
/** The queue's reading of a row: its scope and whether any active request requires a verdict. */
|
|
44
|
+
export function reviewIntent(row) {
|
|
45
|
+
const reqs = reviewRequests(row);
|
|
46
|
+
return { scope: scopeOf(reqs), requested: isRequested(reqs) };
|
|
47
|
+
}
|
|
48
|
+
/** Add or refresh one tool's request on a row (keyed by source + from); returns whether the row changed. */
|
|
49
|
+
export function putReviewRequest(row, req) {
|
|
50
|
+
const list = Array.isArray(row.review_requests) ? row.review_requests : [];
|
|
51
|
+
const i = list.findIndex((r) => r?.source === req.source && (r?.from ?? null) === req.from);
|
|
52
|
+
if (i >= 0 && JSON.stringify(list[i]) === JSON.stringify(req))
|
|
53
|
+
return false;
|
|
54
|
+
if (i >= 0)
|
|
55
|
+
list[i] = req;
|
|
56
|
+
else
|
|
57
|
+
list.push(req);
|
|
58
|
+
row.review_requests = list;
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
/** Lean `Formal.lower`: ASCII-only lower case, so code and model agree on every string (GitHub logins and repo names are ASCII). */
|
|
62
|
+
export const asciiLower = (s) => s.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) + 32));
|
|
63
|
+
const REVIEW_BOTS = new Set(["coderabbitai", "claude", "copilot-pull-request-reviewer", "github-actions", "devin-ai-integration"]);
|
|
64
|
+
export const isBotLogin = (login) => {
|
|
65
|
+
const l = asciiLower(login);
|
|
66
|
+
return REVIEW_BOTS.has(l) || l.endsWith("[bot]") || l.startsWith("app/");
|
|
67
|
+
};
|
|
68
|
+
/** Lean `whoOf`: empty → unknown; exact author → author; case-folded `selves` → self; review bots → bot; else human. */
|
|
69
|
+
export function whoOf(login, author, selves) {
|
|
70
|
+
if (!login)
|
|
71
|
+
return "unknown";
|
|
72
|
+
if (login === author)
|
|
73
|
+
return "author";
|
|
74
|
+
if (selves.has(asciiLower(login)))
|
|
75
|
+
return "self";
|
|
76
|
+
return isBotLogin(login) ? "bot" : "human";
|
|
77
|
+
}
|
|
78
|
+
const COUNTED = new Set(["APPROVED", "CHANGES_REQUESTED", "COMMENTED"]);
|
|
79
|
+
export function peers(live, selves) {
|
|
80
|
+
const author = String(live?.author?.login ?? "");
|
|
81
|
+
const others = (live?.latestReviews ?? []).filter((r) => whoOf(String(r?.author?.login ?? ""), author, selves) === "human" && COUNTED.has(r?.state));
|
|
82
|
+
return {
|
|
83
|
+
reviewed: others.length > 0,
|
|
84
|
+
approved: others.some((r) => r.state === "APPROVED"),
|
|
85
|
+
botAuthor: isBotLogin(author),
|
|
86
|
+
reviewRequired: live?.reviewDecision === "REVIEW_REQUIRED",
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** Lean `takenByOther`: a peer owns the PR, unless it is bot-authored or GitHub still wants one more approval. */
|
|
90
|
+
export const takenByOther = (p) => p.reviewed && !p.botAuthor && !(p.reviewRequired && p.approved);
|
|
91
|
+
/** Lean `admitted`: a queued PR stays in my queue when someone asked me, or no peer owns it. */
|
|
92
|
+
export const admitted = (reqs, p) => isRequested(reqs) || !takenByOther(p);
|
|
93
|
+
/** Lean `holdSettles`: a clean exit settles a run as done only when it owes no verdict (requested, or a bot PR it must fix). */
|
|
94
|
+
export const holdSettles = (owesVerdict, clean) => clean && !owesVerdict;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
type Row = Record<string, any>;
|
|
2
|
+
/** Lean `globC`: `*` matches within one path segment; other characters match ASCII case-insensitively. */
|
|
3
|
+
export declare function glob(p: string, s: string): boolean;
|
|
4
|
+
/** The `owner/repo` part of a PR URL, or null for anything else. */
|
|
5
|
+
export declare const repoOf: (url: string) => string | null;
|
|
6
|
+
/** `exclude_repo_patterns`: a PR is excluded when its repo matches any pattern (Lean `glob`). */
|
|
7
|
+
export declare function repoExcluder(patterns?: string[]): (url: string) => boolean;
|
|
8
|
+
export interface ScopeConfig {
|
|
9
|
+
name: string;
|
|
10
|
+
repo?: string;
|
|
11
|
+
repos?: string[];
|
|
12
|
+
exclude_repo_patterns?: string[];
|
|
13
|
+
max_age_days?: number;
|
|
14
|
+
}
|
|
15
|
+
/** Facts `scopeExcluded` decides on (Lean `ScopeFacts`). */
|
|
16
|
+
export interface ScopeFacts {
|
|
17
|
+
/** The row's scope is configured. */
|
|
18
|
+
known: boolean;
|
|
19
|
+
direct: boolean;
|
|
20
|
+
/** Any scope is configured at all. */
|
|
21
|
+
anyScopes: boolean;
|
|
22
|
+
repoExcluded: boolean;
|
|
23
|
+
/** The scope lists repo/repos. */
|
|
24
|
+
restricted: boolean;
|
|
25
|
+
/** The PR's repository is in that list. */
|
|
26
|
+
allowed: boolean;
|
|
27
|
+
tooOld: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** Lean `scopeExcluded`: a removed scope stops its rows; a direct row has no scope entry and is never stopped by one. */
|
|
30
|
+
export declare const scopeExcluded: (f: ScopeFacts) => boolean;
|
|
31
|
+
/** Re-applies scope filters every tick, so narrowing a scope also drops PRs already listed under it. */
|
|
32
|
+
export declare function scopeExcluder(scopes: ScopeConfig[], now: number): (url: string, scope: string, updatedAt?: string) => boolean;
|
|
33
|
+
/** approval.verification values (Lean `Verification`); a rejected or unknown write never landed on GitHub. */
|
|
34
|
+
export type Verification = "none" | "pending" | "rejected" | "unknown" | "landed";
|
|
35
|
+
export declare const verificationOf: (v: unknown) => Verification;
|
|
36
|
+
/** Facts `targetKind` decides on (Lean `TargetFacts`). */
|
|
37
|
+
export interface TargetFacts {
|
|
38
|
+
status: "queued" | "approval_pending_verification" | "other";
|
|
39
|
+
excluded: boolean;
|
|
40
|
+
draft: boolean;
|
|
41
|
+
/** Lean `admitted`: requested, or no peer owns it. */
|
|
42
|
+
admitted: boolean;
|
|
43
|
+
/** An approval exists for the current head. */
|
|
44
|
+
approvedSame: boolean;
|
|
45
|
+
evidence: boolean;
|
|
46
|
+
verification: Verification;
|
|
47
|
+
}
|
|
48
|
+
/** Lean `targetKind`: review a queued PR unless its current head is already approved with evidence; verify a pending approval. */
|
|
49
|
+
export declare function targetKind(f: TargetFacts): "review" | "verify" | null;
|
|
50
|
+
/** The facts of one ledger row. */
|
|
51
|
+
export declare function targetFacts(r: Row, excluded: (url: string, scope: string, updatedAt?: string) => boolean, selves: Set<string>): TargetFacts;
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Whether a ledger row is review work now: scope config, drafts, peer ownership, and an already-approved head.
|
|
2
|
+
// Proved in formal/Formal/Review.lean (§ targets); formal/conformance/check-core.mjs compares the two.
|
|
3
|
+
import { admitted, asciiLower, DIRECT, peers, reviewRequests, scopeOf } from "./review-request.js";
|
|
4
|
+
/** Lean `globC`: `*` matches within one path segment; other characters match ASCII case-insensitively. */
|
|
5
|
+
export function glob(p, s) {
|
|
6
|
+
const go = (i, j) => {
|
|
7
|
+
if (i === p.length)
|
|
8
|
+
return j === s.length;
|
|
9
|
+
if (p[i] === "*")
|
|
10
|
+
return go(i + 1, j) || (j < s.length && s[j] !== "/" && go(i, j + 1));
|
|
11
|
+
return j < s.length && asciiLower(p[i]) === asciiLower(s[j]) && go(i + 1, j + 1);
|
|
12
|
+
};
|
|
13
|
+
return go(0, 0);
|
|
14
|
+
}
|
|
15
|
+
/** The `owner/repo` part of a PR URL, or null for anything else. */
|
|
16
|
+
export const repoOf = (url) => /^https:\/\/github\.com\/(.*?)\/pull\//.exec(url)?.[1] ?? null;
|
|
17
|
+
/** `exclude_repo_patterns`: a PR is excluded when its repo matches any pattern (Lean `glob`). */
|
|
18
|
+
export function repoExcluder(patterns = []) {
|
|
19
|
+
return (url) => {
|
|
20
|
+
const repo = repoOf(url);
|
|
21
|
+
return repo !== null && patterns.some((p) => glob(p, repo));
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Lean `scopeExcluded`: a removed scope stops its rows; a direct row has no scope entry and is never stopped by one. */
|
|
25
|
+
export const scopeExcluded = (f) => !f.known ? !f.direct && f.anyScopes : f.repoExcluded || (f.restricted && !f.allowed) || f.tooOld;
|
|
26
|
+
/** Re-applies scope filters every tick, so narrowing a scope also drops PRs already listed under it. */
|
|
27
|
+
export function scopeExcluder(scopes, now) {
|
|
28
|
+
const by = new Map(scopes.map((s) => {
|
|
29
|
+
const allowed = [s.repo, ...(s.repos ?? [])].filter(Boolean).map((r) => asciiLower(r));
|
|
30
|
+
return [s.name, { repo: repoExcluder(s.exclude_repo_patterns), maxAge: s.max_age_days, allowed }];
|
|
31
|
+
}));
|
|
32
|
+
return (url, scope, updatedAt) => {
|
|
33
|
+
const s = by.get(scope);
|
|
34
|
+
const repo = url.replace(/^https:\/\/github\.com\//, "").replace(/\/pull\/\d+$/, "");
|
|
35
|
+
const repoKey = asciiLower(repo);
|
|
36
|
+
return scopeExcluded({
|
|
37
|
+
known: !!s,
|
|
38
|
+
direct: scope === DIRECT,
|
|
39
|
+
anyScopes: by.size > 0,
|
|
40
|
+
repoExcluded: !!s?.repo(url),
|
|
41
|
+
restricted: !!s?.allowed.length,
|
|
42
|
+
allowed: !!s?.allowed.includes(repoKey),
|
|
43
|
+
tooOld: !!(s?.maxAge && updatedAt && Date.parse(updatedAt) < now - s.maxAge * 86_400_000),
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export const verificationOf = (v) => v === undefined || v === null ? "none" : v === "pending" ? "pending" : v === "write-rejected" ? "rejected" : v === "write-outcome-unknown" ? "unknown" : "landed";
|
|
48
|
+
/** Lean `targetKind`: review a queued PR unless its current head is already approved with evidence; verify a pending approval. */
|
|
49
|
+
export function targetKind(f) {
|
|
50
|
+
if (f.excluded || f.draft)
|
|
51
|
+
return null;
|
|
52
|
+
const verifying = f.verification === "pending";
|
|
53
|
+
const landed = f.verification !== "rejected" && f.verification !== "unknown";
|
|
54
|
+
if (f.status === "queued") {
|
|
55
|
+
if (!f.admitted)
|
|
56
|
+
return null;
|
|
57
|
+
return f.approvedSame && landed && f.evidence && !verifying ? null : "review";
|
|
58
|
+
}
|
|
59
|
+
return f.status === "approval_pending_verification" && verifying ? "verify" : null;
|
|
60
|
+
}
|
|
61
|
+
/** The facts of one ledger row. */
|
|
62
|
+
export function targetFacts(r, excluded, selves) {
|
|
63
|
+
const reqs = reviewRequests(r);
|
|
64
|
+
const head = r.live?.headRefOid ?? r.intake?.head_sha ?? "";
|
|
65
|
+
const approvedHead = r.approval?.head_sha;
|
|
66
|
+
return {
|
|
67
|
+
status: r.status === "queued" || r.status === "approval_pending_verification" ? r.status : "other",
|
|
68
|
+
excluded: excluded(r.url, scopeOf(reqs), r.live?.updatedAt),
|
|
69
|
+
draft: !!r.live?.isDraft,
|
|
70
|
+
admitted: admitted(reqs, peers(r.live ?? {}, selves)),
|
|
71
|
+
approvedSame: !!approvedHead && approvedHead === head,
|
|
72
|
+
evidence: !!(r.evidence_sha256 ?? null),
|
|
73
|
+
verification: verificationOf(r.approval?.verification),
|
|
74
|
+
};
|
|
75
|
+
}
|
package/dist/stage.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Issue stage machine: the factory stage of an Issue derived from its state and labels. Shared by the local ledger and
|
|
2
|
-
//
|
|
2
|
+
// a host so both boards read the same stage for the same Issue.
|
|
3
3
|
export const ISSUE_STAGES = ["triage", "queued", "in_progress", "verifying", "human_required", "backlog", "completed", "closed"];
|
|
4
4
|
export function issueStage(issue) {
|
|
5
5
|
const labels = new Set((issue.labels ?? []).map((l) => String((typeof l === "object" && l !== null ? l.name : l) ?? l).toLowerCase()));
|
package/dist/tiers.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ export interface TierPolicy {
|
|
|
17
17
|
gated?: boolean;
|
|
18
18
|
effort?: string;
|
|
19
19
|
}>;
|
|
20
|
-
/** Default reasoning effort (ledger passes it to the worker;
|
|
20
|
+
/** Default reasoning effort (ledger passes it to the worker; a host omits it). */
|
|
21
21
|
effort?: string;
|
|
22
22
|
}
|
|
23
23
|
export interface Outcome {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hikae/ledger-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Pure core shared by the local ledger agent and
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Pure core shared by the local ledger agent and a host: model tier policy, issue stage machine, port interfaces.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -33,6 +33,18 @@
|
|
|
33
33
|
"./holds": {
|
|
34
34
|
"types": "./dist/holds.d.ts",
|
|
35
35
|
"default": "./dist/holds.js"
|
|
36
|
+
},
|
|
37
|
+
"./review-request": {
|
|
38
|
+
"types": "./dist/review-request.d.ts",
|
|
39
|
+
"default": "./dist/review-request.js"
|
|
40
|
+
},
|
|
41
|
+
"./issueMetrics": {
|
|
42
|
+
"types": "./dist/issueMetrics.d.ts",
|
|
43
|
+
"default": "./dist/issueMetrics.js"
|
|
44
|
+
},
|
|
45
|
+
"./issueObservation": {
|
|
46
|
+
"types": "./dist/issueObservation.d.ts",
|
|
47
|
+
"default": "./dist/issueObservation.js"
|
|
36
48
|
}
|
|
37
49
|
},
|
|
38
50
|
"files": [
|