@oss-autopilot/core 3.22.3 → 3.24.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/dist/cli-registry.js +43 -1
- package/dist/cli.bundle.cjs +112 -110
- package/dist/commands/daily.d.ts +8 -1
- package/dist/commands/daily.js +33 -3
- package/dist/commands/features.js +5 -11
- package/dist/commands/guidelines.d.ts +15 -0
- package/dist/commands/guidelines.js +22 -0
- package/dist/commands/index.d.ts +2 -0
- package/dist/commands/index.js +2 -0
- package/dist/commands/overnight-push-prep.d.ts +91 -0
- package/dist/commands/overnight-push-prep.js +335 -0
- package/dist/commands/overnight.d.ts +16 -2
- package/dist/commands/overnight.js +33 -14
- package/dist/commands/scout-bridge.js +38 -8
- package/dist/commands/search.js +20 -26
- package/dist/commands/setup.js +9 -0
- package/dist/core/config-registry.js +6 -0
- package/dist/core/issue-grading.d.ts +8 -10
- package/dist/core/issue-grading.js +8 -10
- package/dist/core/state-schema.d.ts +34 -2
- package/dist/core/state-schema.js +29 -2
- package/dist/formatters/json.d.ts +50 -0
- package/dist/formatters/json.js +36 -0
- package/package.json +2 -2
package/dist/commands/daily.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { type AttentionSummary, type DailyDigest, type CommentedIssue, type PRCheckFailure, type RepoGroup } from '../core/index.js';
|
|
10
10
|
import { type StrategyResult } from '../core/strategy.js';
|
|
11
|
-
import { type DailyOutput, type DailyWarning, type CapacityAssessment, type ActionableIssue, type ActionMenu, type MergedPRListUpdate } from '../formatters/json.js';
|
|
11
|
+
import { type DailyOutput, type DailyWarning, type CapacityAssessment, type ActionableIssue, type ActionMenu, type MergedPRListUpdate, type PendingLearnings } from '../formatters/json.js';
|
|
12
12
|
export { applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, printDigest, CRITICAL_STATUSES, } from '../core/index.js';
|
|
13
13
|
import { buildStarFilter } from '../core/daily-logic.js';
|
|
14
14
|
export { buildStarFilter };
|
|
@@ -44,6 +44,13 @@ export interface DailyCheckResult {
|
|
|
44
44
|
* omit it so serialized output (and contract goldens) stay unchanged.
|
|
45
45
|
*/
|
|
46
46
|
listUpdates?: MergedPRListUpdate[];
|
|
47
|
+
/**
|
|
48
|
+
* Recently merged PRs whose learnings the host should extract now, without
|
|
49
|
+
* asking (#1696). Set only when `config.autoExtractLearnings` is on, Gist
|
|
50
|
+
* persistence is available, and at least one such PR exists; otherwise
|
|
51
|
+
* absent, so goldens and merge-free runs are unchanged.
|
|
52
|
+
*/
|
|
53
|
+
pendingLearnings?: PendingLearnings;
|
|
47
54
|
}
|
|
48
55
|
/**
|
|
49
56
|
* Convert a full DailyCheckResult to the compact DailyOutput for JSON serialization (#287).
|
package/dist/commands/daily.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* Domain logic lives in src/core/daily-logic.ts; this file is a thin
|
|
7
7
|
* orchestration layer that wires up the phases and handles I/O.
|
|
8
8
|
*/
|
|
9
|
-
import { getStateManager, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, } from '../core/index.js';
|
|
9
|
+
import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, } from '../core/index.js';
|
|
10
10
|
import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
|
|
11
11
|
import { wrapUntrustedContent } from '../core/untrusted-content.js';
|
|
12
12
|
import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
|
|
@@ -550,6 +550,7 @@ export function toDailyOutput(result) {
|
|
|
550
550
|
// Conditional spread (not a plain assignment) so merge-free runs carry
|
|
551
551
|
// no `listUpdates` key at all — serialized output and goldens unchanged.
|
|
552
552
|
...(result.listUpdates ? { listUpdates: result.listUpdates } : {}),
|
|
553
|
+
...(result.pendingLearnings ? { pendingLearnings: result.pendingLearnings } : {}),
|
|
553
554
|
};
|
|
554
555
|
}
|
|
555
556
|
/**
|
|
@@ -667,10 +668,36 @@ async function executeDailyCheckInternal(token) {
|
|
|
667
668
|
// nudge: it stays up for the whole recently-merged window (7 days) until
|
|
668
669
|
// the user runs the extraction, then self-clears.
|
|
669
670
|
let unextractedMergeCount = 0;
|
|
671
|
+
let pendingLearnings;
|
|
670
672
|
try {
|
|
671
|
-
const
|
|
673
|
+
const sm = getStateManager();
|
|
674
|
+
const ledger = sm.getState().mergedPRs ?? [];
|
|
672
675
|
const recentUrls = new Set(recentlyMergedPRs.map((pr) => pr.url));
|
|
673
|
-
|
|
676
|
+
const unextracted = ledger.filter((pr) => recentUrls.has(pr.url) && !pr.learningsExtractedAt);
|
|
677
|
+
unextractedMergeCount = unextracted.length;
|
|
678
|
+
// Auto mode (#1696): hand the repos to the host for a background
|
|
679
|
+
// extraction instead of a menu item. Guidelines live in the Gist, so
|
|
680
|
+
// local-only persistence gets one warning per run and no menu item —
|
|
681
|
+
// the manual path would only tell the user the same thing.
|
|
682
|
+
if (unextractedMergeCount > 0 && sm.getState().config.autoExtractLearnings) {
|
|
683
|
+
unextractedMergeCount = 0;
|
|
684
|
+
if (sm.isGistMode()) {
|
|
685
|
+
const repos = new Set();
|
|
686
|
+
for (const pr of unextracted) {
|
|
687
|
+
const parsed = parseGitHubUrl(pr.url);
|
|
688
|
+
if (parsed)
|
|
689
|
+
repos.add(`${parsed.owner}/${parsed.repo}`);
|
|
690
|
+
}
|
|
691
|
+
pendingLearnings = { repos: [...repos].sort(), prCount: unextracted.length };
|
|
692
|
+
}
|
|
693
|
+
else {
|
|
694
|
+
warnings.push({
|
|
695
|
+
phase: 'merge-loop',
|
|
696
|
+
operation: 'auto-extract learnings',
|
|
697
|
+
message: `${unextracted.length} recently merged PR(s) have unextracted learnings; per-repo guidelines need Gist persistence (run setup to enable Gist sync, or set autoExtractLearnings=false to hide this)`,
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
}
|
|
674
701
|
}
|
|
675
702
|
catch (error) {
|
|
676
703
|
recordWarning(warnings, 'merge-loop', 'count unextracted merged PRs', error);
|
|
@@ -693,6 +720,9 @@ async function executeDailyCheckInternal(token) {
|
|
|
693
720
|
if (listUpdates) {
|
|
694
721
|
result.listUpdates = listUpdates;
|
|
695
722
|
}
|
|
723
|
+
if (pendingLearnings) {
|
|
724
|
+
result.pendingLearnings = pendingLearnings;
|
|
725
|
+
}
|
|
696
726
|
// Checkpoint: push state to Gist if in Gist mode.
|
|
697
727
|
// If getStateManagerAsync was not called before this command ran,
|
|
698
728
|
// isGistMode() will be false and checkpoint is correctly skipped.
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { buildCandidateLinkedPR, createAutopilotScout } from './scout-bridge.js';
|
|
16
16
|
import { getStateManager } from '../core/index.js';
|
|
17
|
-
import { gradeFromCandidate } from '../core/issue-grading.js';
|
|
17
|
+
import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
|
|
18
18
|
import { warn } from '../core/logger.js';
|
|
19
19
|
const MODULE = 'features';
|
|
20
20
|
/**
|
|
@@ -43,19 +43,13 @@ function sanitizeViabilityScore(raw) {
|
|
|
43
43
|
*/
|
|
44
44
|
function toFeaturesCandidate(scoutCandidate, getState) {
|
|
45
45
|
const repoScoreRecord = getState.getRepoScore(scoutCandidate.issue.repo);
|
|
46
|
-
//
|
|
47
|
-
// pipeline reuses the same vetting code that does emit projectHealth on
|
|
48
|
-
// `vetIssue`, but on this surface scout returns the multi-issue list view
|
|
49
|
-
// which today does not propagate per-candidate health into IssueCandidate.
|
|
50
|
-
// Treating health as unknown grades from the autopilot-tracked repoScore
|
|
51
|
-
// alone, falling to 'F' for unfamiliar repos — an honest "we haven't seen
|
|
52
|
-
// this repo" rather than a fabricated score.
|
|
46
|
+
// Grade from the health scout fetched while vetting (#332); see runSearch.
|
|
53
47
|
const grade = gradeFromCandidate({
|
|
54
48
|
repo: scoutCandidate.issue.repo,
|
|
55
|
-
projectHealth: {
|
|
49
|
+
projectHealth: scoutCandidate.projectHealth ?? {
|
|
56
50
|
repo: scoutCandidate.issue.repo,
|
|
57
51
|
checkFailed: true,
|
|
58
|
-
failureReason: 'health not
|
|
52
|
+
failureReason: 'health not supplied by the caller',
|
|
59
53
|
},
|
|
60
54
|
getRepoScore: (repo) => {
|
|
61
55
|
const score = getState.getRepoScore(repo);
|
|
@@ -78,7 +72,7 @@ function toFeaturesCandidate(scoutCandidate, getState) {
|
|
|
78
72
|
url: scoutCandidate.issue.url,
|
|
79
73
|
labels: scoutCandidate.issue.labels,
|
|
80
74
|
},
|
|
81
|
-
recommendation: scoutCandidate.recommendation,
|
|
75
|
+
recommendation: reconcileRecommendation(scoutCandidate.recommendation, grade),
|
|
82
76
|
reasonsToApprove: scoutCandidate.reasonsToApprove,
|
|
83
77
|
reasonsToSkip: scoutCandidate.reasonsToSkip,
|
|
84
78
|
searchPriority: scoutCandidate.searchPriority,
|
|
@@ -24,6 +24,13 @@ export interface GuidelinesStoreOutput {
|
|
|
24
24
|
/** Set when the post-mutation Gist checkpoint failed; the local mutation succeeded (#1370). */
|
|
25
25
|
gistSyncWarning?: string;
|
|
26
26
|
}
|
|
27
|
+
export interface MarkExtractedOutput {
|
|
28
|
+
repo: string;
|
|
29
|
+
/** PRs stamped `learningsExtractedAt` this call. */
|
|
30
|
+
marked: number;
|
|
31
|
+
/** Set when the post-mutation Gist checkpoint failed; the local mutation succeeded (#1370). */
|
|
32
|
+
gistSyncWarning?: string;
|
|
33
|
+
}
|
|
27
34
|
export interface GuidelinesResetOutput {
|
|
28
35
|
repo: string;
|
|
29
36
|
/** True when an existing file was tombstoned, false when no file existed. */
|
|
@@ -83,6 +90,14 @@ export declare function runGuidelinesList(): Promise<GuidelinesListOutput>;
|
|
|
83
90
|
* outputJson error envelope to surface that to the host cleanly.
|
|
84
91
|
*/
|
|
85
92
|
export declare function runGuidelinesStore(options: StoreOptions): Promise<GuidelinesStoreOutput>;
|
|
93
|
+
/**
|
|
94
|
+
* Stamp `learningsExtractedAt` on every merged/closed PR of `repo` whose
|
|
95
|
+
* comment bundle was fetched (`commentsFetchedAt` set) but not yet marked
|
|
96
|
+
* extracted (#1696). The host calls this after storing guidelines, or after
|
|
97
|
+
* deciding a corpus carried no signal, so `daily` stops reporting those PRs
|
|
98
|
+
* as unextracted. Idempotent: already-stamped PRs are left alone.
|
|
99
|
+
*/
|
|
100
|
+
export declare function runMarkExtracted(options: RepoOption): Promise<MarkExtractedOutput>;
|
|
86
101
|
/** Tombstone the guidelines file for `repo`. */
|
|
87
102
|
export declare function runGuidelinesReset(options: RepoOption): Promise<GuidelinesResetOutput>;
|
|
88
103
|
/**
|
|
@@ -80,6 +80,28 @@ export async function runGuidelinesStore(options) {
|
|
|
80
80
|
...(gistSyncWarning ? { gistSyncWarning } : {}),
|
|
81
81
|
};
|
|
82
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Stamp `learningsExtractedAt` on every merged/closed PR of `repo` whose
|
|
85
|
+
* comment bundle was fetched (`commentsFetchedAt` set) but not yet marked
|
|
86
|
+
* extracted (#1696). The host calls this after storing guidelines, or after
|
|
87
|
+
* deciding a corpus carried no signal, so `daily` stops reporting those PRs
|
|
88
|
+
* as unextracted. Idempotent: already-stamped PRs are left alone.
|
|
89
|
+
*/
|
|
90
|
+
export async function runMarkExtracted(options) {
|
|
91
|
+
validateRepo(options.repo);
|
|
92
|
+
const sm = getStateManager();
|
|
93
|
+
const repoUrlPrefix = `https://github.com/${options.repo}/`;
|
|
94
|
+
const now = new Date().toISOString();
|
|
95
|
+
let marked = 0;
|
|
96
|
+
for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
|
|
97
|
+
if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
|
|
98
|
+
continue;
|
|
99
|
+
sm.markPRLearningsExtracted(pr.url, now);
|
|
100
|
+
marked++;
|
|
101
|
+
}
|
|
102
|
+
const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE) : null;
|
|
103
|
+
return { repo: options.repo, marked, ...(gistSyncWarning ? { gistSyncWarning } : {}) };
|
|
104
|
+
}
|
|
83
105
|
/** Tombstone the guidelines file for `repo`. */
|
|
84
106
|
export async function runGuidelinesReset(options) {
|
|
85
107
|
validateRepo(options.repo);
|
package/dist/commands/index.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export { executeDailyCheck } from './daily.js';
|
|
|
21
21
|
export { runStartup } from './startup.js';
|
|
22
22
|
/** Overnight prepare-and-queue run, branch recording, launchd schedule rendering (#1574). */
|
|
23
23
|
export { runOvernight, runOvernightRecord, runOvernightSchedule } from './overnight.js';
|
|
24
|
+
/** Post-tick step that stages prepared branches under `prep/*` on the user's fork (#1698). */
|
|
25
|
+
export { runOvernightPushPrep } from './overnight-push-prep.js';
|
|
24
26
|
/** Return contribution statistics (merge rate, PR counts, repo breakdown) from local state. */
|
|
25
27
|
export { runStatus } from './status.js';
|
|
26
28
|
/** On-demand strategy snapshot via the typed `computeStrategy` core function (#1243 step 4). */
|
package/dist/commands/index.js
CHANGED
|
@@ -22,6 +22,8 @@ export { executeDailyCheck } from './daily.js';
|
|
|
22
22
|
export { runStartup } from './startup.js';
|
|
23
23
|
/** Overnight prepare-and-queue run, branch recording, launchd schedule rendering (#1574). */
|
|
24
24
|
export { runOvernight, runOvernightRecord, runOvernightSchedule } from './overnight.js';
|
|
25
|
+
/** Post-tick step that stages prepared branches under `prep/*` on the user's fork (#1698). */
|
|
26
|
+
export { runOvernightPushPrep } from './overnight-push-prep.js';
|
|
25
27
|
/** Return contribution statistics (merge rate, PR counts, repo breakdown) from local state. */
|
|
26
28
|
export { runStatus } from './status.js';
|
|
27
29
|
/** On-demand strategy snapshot via the typed `computeStrategy` core function (#1243 step 4). */
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `overnight push-prep` (#1698): the deterministic step that stages prepared
|
|
3
|
+
* branches on the user's fork under `prep/*`, so the machine where `/oss`
|
|
4
|
+
* runs can see what a headless overnight box prepared.
|
|
5
|
+
*
|
|
6
|
+
* The model never runs this. A scheduler runs it after the model tick has
|
|
7
|
+
* ended (systemd `ExecStartPost=`, a second launchd step), and it is the only
|
|
8
|
+
* thing in the overnight pipeline that pushes. Three gates, all enforced in
|
|
9
|
+
* code rather than by convention:
|
|
10
|
+
*
|
|
11
|
+
* 1. The push target is resolved from the worktree's actual remotes: the one
|
|
12
|
+
* whose parsed URL owner equals the authenticated login. Remote names are
|
|
13
|
+
* never trusted.
|
|
14
|
+
* 2. That repo must be a fork (`GET /repos/{owner}/{repo}` says `fork: true`),
|
|
15
|
+
* so the user's own source repos never grow `prep/*` branches.
|
|
16
|
+
* 3. The ref is always `refs/heads/prep/<branch>` and never `--force`; a
|
|
17
|
+
* non-fast-forward is a skip with a reason.
|
|
18
|
+
*/
|
|
19
|
+
/** The only ref namespace this command ever pushes to. */
|
|
20
|
+
export declare const PREP_REF_PREFIX = "refs/heads/prep/";
|
|
21
|
+
export interface RemoteOwnerRepo {
|
|
22
|
+
owner: string;
|
|
23
|
+
repo: string;
|
|
24
|
+
}
|
|
25
|
+
export interface GitRemote {
|
|
26
|
+
name: string;
|
|
27
|
+
url: string;
|
|
28
|
+
}
|
|
29
|
+
export interface PushTarget extends RemoteOwnerRepo {
|
|
30
|
+
remote: string;
|
|
31
|
+
}
|
|
32
|
+
/** `skipped`: a gate said no, nothing to fix tonight. `failed`: the push itself broke; the CLI exits 1. */
|
|
33
|
+
export type PushPrepStatus = 'pushed' | 'planned' | 'skipped' | 'failed';
|
|
34
|
+
export interface PushPrepResult {
|
|
35
|
+
url: string;
|
|
36
|
+
branch: string;
|
|
37
|
+
status: PushPrepStatus;
|
|
38
|
+
/** Remote name, `owner/repo`, full ref and compare URL; set once a target resolved. */
|
|
39
|
+
remote?: string;
|
|
40
|
+
repo?: string;
|
|
41
|
+
ref?: string;
|
|
42
|
+
compareUrl?: string;
|
|
43
|
+
/** Why a `skipped` or `failed` entry was not pushed. */
|
|
44
|
+
reason?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface OvernightPushPrepOutput {
|
|
47
|
+
dryRun: boolean;
|
|
48
|
+
/** Authenticated login every remote owner was compared against. */
|
|
49
|
+
login: string;
|
|
50
|
+
reportPath: string;
|
|
51
|
+
results: PushPrepResult[];
|
|
52
|
+
pushed: number;
|
|
53
|
+
planned: number;
|
|
54
|
+
skipped: number;
|
|
55
|
+
failed: number;
|
|
56
|
+
/** The report file was missing and has been recreated with only the prepared section. */
|
|
57
|
+
reportRecreated?: true;
|
|
58
|
+
/** The pushes and state are recorded, but the report file could not be rewritten. */
|
|
59
|
+
reportWarning?: string;
|
|
60
|
+
gistSyncWarning?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface OvernightPushPrepOptions {
|
|
63
|
+
dryRun: boolean;
|
|
64
|
+
}
|
|
65
|
+
/** A ref outside `prep/` reached the push gate: a programming error, so the run stops instead of skipping. */
|
|
66
|
+
export declare class PrepNamespaceError extends Error {
|
|
67
|
+
constructor(ref: string);
|
|
68
|
+
}
|
|
69
|
+
/** Pure: owner/repo from a GitHub remote URL (https, scp-style ssh, ssh://); null for anything else. */
|
|
70
|
+
export declare function parseRemoteOwner(url: string): RemoteOwnerRepo | null;
|
|
71
|
+
/** Pure: `git remote -v` output to one push URL per remote name. */
|
|
72
|
+
export declare function parseRemotesOutput(stdout: string): GitRemote[];
|
|
73
|
+
/**
|
|
74
|
+
* Pure: the first remote whose parsed URL owner equals `login`. Equality is
|
|
75
|
+
* case-insensitive on the parsed owner, never a substring match, so a remote
|
|
76
|
+
* for `<login>-mirror` or `org/<login>` does not qualify.
|
|
77
|
+
*/
|
|
78
|
+
export declare function resolvePushRemote(remotes: GitRemote[], login: string): PushTarget | null;
|
|
79
|
+
/**
|
|
80
|
+
* Pure: the full ref for a prepared branch. Built by prefixing a constant, so
|
|
81
|
+
* a ref outside `prep/` cannot be produced; anything git would reject or that
|
|
82
|
+
* could escape the namespace (`..`, a leading `/`, refspec separators) throws
|
|
83
|
+
* instead of being pushed.
|
|
84
|
+
*/
|
|
85
|
+
export declare function buildPrepRef(branch: string): string;
|
|
86
|
+
/** Pure: the branch name on the fork (`prep/<branch>`) for a full prep ref. */
|
|
87
|
+
export declare function prepBranchName(ref: string): string;
|
|
88
|
+
/** Pure: `<fork>/compare/<pr-head>...prep/<branch>`. */
|
|
89
|
+
export declare function compareUrlFor(target: RemoteOwnerRepo, prHead: string, prepBranch: string): string;
|
|
90
|
+
/** Push every prepared branch of the latest overnight run to `prep/*` on the user's fork. */
|
|
91
|
+
export declare function runOvernightPushPrep(options: OvernightPushPrepOptions): Promise<OvernightPushPrepOutput>;
|
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `overnight push-prep` (#1698): the deterministic step that stages prepared
|
|
3
|
+
* branches on the user's fork under `prep/*`, so the machine where `/oss`
|
|
4
|
+
* runs can see what a headless overnight box prepared.
|
|
5
|
+
*
|
|
6
|
+
* The model never runs this. A scheduler runs it after the model tick has
|
|
7
|
+
* ended (systemd `ExecStartPost=`, a second launchd step), and it is the only
|
|
8
|
+
* thing in the overnight pipeline that pushes. Three gates, all enforced in
|
|
9
|
+
* code rather than by convention:
|
|
10
|
+
*
|
|
11
|
+
* 1. The push target is resolved from the worktree's actual remotes: the one
|
|
12
|
+
* whose parsed URL owner equals the authenticated login. Remote names are
|
|
13
|
+
* never trusted.
|
|
14
|
+
* 2. That repo must be a fork (`GET /repos/{owner}/{repo}` says `fork: true`),
|
|
15
|
+
* so the user's own source repos never grow `prep/*` branches.
|
|
16
|
+
* 3. The ref is always `refs/heads/prep/<branch>` and never `--force`; a
|
|
17
|
+
* non-fast-forward is a skip with a reason.
|
|
18
|
+
*/
|
|
19
|
+
import { execFileSync } from 'node:child_process';
|
|
20
|
+
import * as fs from 'node:fs';
|
|
21
|
+
import { errorMessage, getOctokit, getStateManager, isRateLimitError, maybeCheckpoint, parseGitHubUrl, requireGitHubToken, } from '../core/index.js';
|
|
22
|
+
import { warn } from '../core/logger.js';
|
|
23
|
+
import { writePreparedSection } from './overnight.js';
|
|
24
|
+
const MODULE = 'overnight-push-prep';
|
|
25
|
+
/** The only ref namespace this command ever pushes to. */
|
|
26
|
+
export const PREP_REF_PREFIX = 'refs/heads/prep/';
|
|
27
|
+
const GIT_TIMEOUT_MS = 60_000;
|
|
28
|
+
/** A ref outside `prep/` reached the push gate: a programming error, so the run stops instead of skipping. */
|
|
29
|
+
export class PrepNamespaceError extends Error {
|
|
30
|
+
constructor(ref) {
|
|
31
|
+
super(`Internal error: refusing to push ref "${ref}" outside ${PREP_REF_PREFIX}`);
|
|
32
|
+
this.name = 'PrepNamespaceError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// https://github.com/o/r(.git), git@github.com:o/r(.git), ssh://git@github.com(:port)/o/r(.git);
|
|
36
|
+
// owner and repo use the same character classes as urls.ts.
|
|
37
|
+
const REMOTE_URL_PATTERN = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com(?::\d+)?\/)([\w-]+)\/([\w.-]+?)(?:\.git)?\/?$/i;
|
|
38
|
+
/** Pure: owner/repo from a GitHub remote URL (https, scp-style ssh, ssh://); null for anything else. */
|
|
39
|
+
export function parseRemoteOwner(url) {
|
|
40
|
+
const m = url.trim().match(REMOTE_URL_PATTERN);
|
|
41
|
+
return m ? { owner: m[1], repo: m[2] } : null;
|
|
42
|
+
}
|
|
43
|
+
/** Pure: `git remote -v` output to one push URL per remote name. */
|
|
44
|
+
export function parseRemotesOutput(stdout) {
|
|
45
|
+
const remotes = [];
|
|
46
|
+
for (const line of stdout.split('\n')) {
|
|
47
|
+
const m = line.match(/^(\S+)\s+(\S+)\s+\(push\)$/);
|
|
48
|
+
if (m)
|
|
49
|
+
remotes.push({ name: m[1], url: m[2] });
|
|
50
|
+
}
|
|
51
|
+
return remotes;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Pure: the first remote whose parsed URL owner equals `login`. Equality is
|
|
55
|
+
* case-insensitive on the parsed owner, never a substring match, so a remote
|
|
56
|
+
* for `<login>-mirror` or `org/<login>` does not qualify.
|
|
57
|
+
*/
|
|
58
|
+
export function resolvePushRemote(remotes, login) {
|
|
59
|
+
// `git push <name>` pushes to EVERY push URL of that remote, so a name with
|
|
60
|
+
// more than one (`git remote set-url --add --push`) can never qualify:
|
|
61
|
+
// validating the first URL would say nothing about the others.
|
|
62
|
+
const pushUrlCount = new Map();
|
|
63
|
+
for (const r of remotes)
|
|
64
|
+
pushUrlCount.set(r.name, (pushUrlCount.get(r.name) ?? 0) + 1);
|
|
65
|
+
for (const r of remotes) {
|
|
66
|
+
// A remote named like an option would reach git's argv; never pick one.
|
|
67
|
+
if (r.name.startsWith('-'))
|
|
68
|
+
continue;
|
|
69
|
+
if (pushUrlCount.get(r.name) !== 1)
|
|
70
|
+
continue;
|
|
71
|
+
const parsed = parseRemoteOwner(r.url);
|
|
72
|
+
if (parsed && parsed.owner.toLowerCase() === login.toLowerCase())
|
|
73
|
+
return { remote: r.name, ...parsed };
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
/** The last gate before `git push`. */
|
|
78
|
+
function assertPrepRef(ref) {
|
|
79
|
+
if (!ref.startsWith(PREP_REF_PREFIX) || ref.length === PREP_REF_PREFIX.length)
|
|
80
|
+
throw new PrepNamespaceError(ref);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Pure: the full ref for a prepared branch. Built by prefixing a constant, so
|
|
84
|
+
* a ref outside `prep/` cannot be produced; anything git would reject or that
|
|
85
|
+
* could escape the namespace (`..`, a leading `/`, refspec separators) throws
|
|
86
|
+
* instead of being pushed.
|
|
87
|
+
*/
|
|
88
|
+
export function buildPrepRef(branch) {
|
|
89
|
+
if (branch.length === 0 ||
|
|
90
|
+
branch.startsWith('/') ||
|
|
91
|
+
branch.endsWith('/') ||
|
|
92
|
+
branch.endsWith('.lock') ||
|
|
93
|
+
branch.includes('//') ||
|
|
94
|
+
branch.includes('..') ||
|
|
95
|
+
branch.includes('@{') ||
|
|
96
|
+
/[\s~^:?*[\\]/.test(branch) ||
|
|
97
|
+
[...branch].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) === 0x7f)) {
|
|
98
|
+
throw new Error(`Refusing to build a prep ref from branch "${branch}": not a valid ref name`);
|
|
99
|
+
}
|
|
100
|
+
const ref = `${PREP_REF_PREFIX}${branch}`;
|
|
101
|
+
assertPrepRef(ref);
|
|
102
|
+
return ref;
|
|
103
|
+
}
|
|
104
|
+
/** Pure: the branch name on the fork (`prep/<branch>`) for a full prep ref. */
|
|
105
|
+
export function prepBranchName(ref) {
|
|
106
|
+
assertPrepRef(ref);
|
|
107
|
+
return ref.slice('refs/heads/'.length);
|
|
108
|
+
}
|
|
109
|
+
/** Pure: `<fork>/compare/<pr-head>...prep/<branch>`. */
|
|
110
|
+
export function compareUrlFor(target, prHead, prepBranch) {
|
|
111
|
+
return `https://github.com/${target.owner}/${target.repo}/compare/${prHead}...${prepBranch}`;
|
|
112
|
+
}
|
|
113
|
+
function git(worktree, args) {
|
|
114
|
+
return execFileSync('git', ['-C', worktree, ...args], {
|
|
115
|
+
encoding: 'utf8',
|
|
116
|
+
timeout: GIT_TIMEOUT_MS,
|
|
117
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
118
|
+
// Unattended: a credential prompt must fail, not hang until the timeout.
|
|
119
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
function gitStderr(err) {
|
|
123
|
+
const stderr = err?.stderr;
|
|
124
|
+
return typeof stderr === 'string' ? stderr.trim() : '';
|
|
125
|
+
}
|
|
126
|
+
// Only git's two non-fast-forward hints. A bare `[rejected]` also covers
|
|
127
|
+
// stale-info and hook rejections, which are failures, not divergence.
|
|
128
|
+
function isNonFastForward(err) {
|
|
129
|
+
return /non-fast-forward|fetch first/.test(gitStderr(err));
|
|
130
|
+
}
|
|
131
|
+
/** errorMessage alone is "Command failed: git ..."; git's own last lines say why (auth, hook, timeout). */
|
|
132
|
+
function pushFailureReason(err) {
|
|
133
|
+
const timedOut = err?.code === 'ETIMEDOUT';
|
|
134
|
+
const tail = gitStderr(err).split('\n').slice(-3).join(' | ');
|
|
135
|
+
const why = timedOut
|
|
136
|
+
? `timed out after ${GIT_TIMEOUT_MS / 1000}s (the ref may still have landed; the next run re-checks)`
|
|
137
|
+
: errorMessage(err);
|
|
138
|
+
return `push failed: ${why}${tail ? ` [git: ${tail}]` : ''}`;
|
|
139
|
+
}
|
|
140
|
+
function notPushed(status, entry, reason, target, ref) {
|
|
141
|
+
warn(MODULE, `${status === 'failed' ? 'Failed' : 'Skipping'} ${entry.branch} for ${entry.url}: ${reason}`);
|
|
142
|
+
return {
|
|
143
|
+
url: entry.url,
|
|
144
|
+
branch: entry.branch,
|
|
145
|
+
status,
|
|
146
|
+
...(target ? { remote: target.remote, repo: `${target.owner}/${target.repo}` } : {}),
|
|
147
|
+
...(ref ? { ref } : {}),
|
|
148
|
+
reason,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function skip(entry, reason, target, ref) {
|
|
152
|
+
return notPushed('skipped', entry, reason, target, ref);
|
|
153
|
+
}
|
|
154
|
+
/** Push every prepared branch of the latest overnight run to `prep/*` on the user's fork. */
|
|
155
|
+
export async function runOvernightPushPrep(options) {
|
|
156
|
+
const sm = getStateManager();
|
|
157
|
+
const last = sm.getLastOvernight();
|
|
158
|
+
if (!last)
|
|
159
|
+
throw new Error('No overnight run recorded yet; run `overnight` first.');
|
|
160
|
+
const lastRun = last; // narrowed binding for the closures below
|
|
161
|
+
const octokit = getOctokit(requireGitHubToken());
|
|
162
|
+
const { data: viewer } = await octokit.users.getAuthenticated();
|
|
163
|
+
const login = viewer.login?.trim();
|
|
164
|
+
if (!login)
|
|
165
|
+
throw new Error('Could not read the authenticated login from the token; refusing to push anywhere.');
|
|
166
|
+
const configured = sm.getState().config.githubUsername;
|
|
167
|
+
if (configured && configured.toLowerCase() !== login.toLowerCase()) {
|
|
168
|
+
throw new Error(`Configured githubUsername "${configured}" does not match the token's login "${login}"; refusing to push anywhere.`);
|
|
169
|
+
}
|
|
170
|
+
// One repo lookup per repo, not per entry.
|
|
171
|
+
const forkVerdicts = new Map();
|
|
172
|
+
/**
|
|
173
|
+
* Skip reason when `target` is not a fork the login owns, or could not be
|
|
174
|
+
* read; null when it is. The live owner is checked as well as the URL's:
|
|
175
|
+
* GitHub redirects a transferred or renamed repo, so a stale
|
|
176
|
+
* `github.com/<login>/<repo>` URL can resolve to someone else's repo.
|
|
177
|
+
*/
|
|
178
|
+
async function forkSkipReason(target) {
|
|
179
|
+
const key = `${target.owner}/${target.repo}`.toLowerCase();
|
|
180
|
+
const cached = forkVerdicts.get(key);
|
|
181
|
+
if (cached !== undefined)
|
|
182
|
+
return cached;
|
|
183
|
+
let reason;
|
|
184
|
+
try {
|
|
185
|
+
const { data } = await octokit.repos.get({ owner: target.owner, repo: target.repo });
|
|
186
|
+
if (!data.fork)
|
|
187
|
+
reason = `${target.owner}/${target.repo} is not a fork`;
|
|
188
|
+
else if (data.owner.login.toLowerCase() !== login.toLowerCase())
|
|
189
|
+
reason = `${target.owner}/${target.repo} resolved to ${data.full_name}, not owned by ${login}`;
|
|
190
|
+
else
|
|
191
|
+
reason = null;
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
// Same convention as the rest of core (errors.ts): a rate limit must
|
|
195
|
+
// propagate, or every entry repeats the doomed call and the run reads
|
|
196
|
+
// as "all skipped".
|
|
197
|
+
if (isRateLimitError(err))
|
|
198
|
+
throw err;
|
|
199
|
+
reason = `could not read ${target.owner}/${target.repo}: ${errorMessage(err)}`;
|
|
200
|
+
}
|
|
201
|
+
forkVerdicts.set(key, reason);
|
|
202
|
+
return reason;
|
|
203
|
+
}
|
|
204
|
+
/** PR head branch for the compare URL; undefined (with a warning) when it cannot be read. */
|
|
205
|
+
async function prHeadFor(url) {
|
|
206
|
+
const parsed = parseGitHubUrl(url);
|
|
207
|
+
if (!parsed || parsed.type !== 'pull')
|
|
208
|
+
return undefined;
|
|
209
|
+
try {
|
|
210
|
+
const { data } = await octokit.pulls.get({ owner: parsed.owner, repo: parsed.repo, pull_number: parsed.number });
|
|
211
|
+
return data.head.ref;
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
if (isRateLimitError(err))
|
|
215
|
+
throw err;
|
|
216
|
+
warn(MODULE, `Could not read the head branch of ${url}; no compare URL: ${errorMessage(err)}`);
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function pushOne(entry) {
|
|
221
|
+
if (!entry.worktree)
|
|
222
|
+
return skip(entry, 'no worktree recorded');
|
|
223
|
+
if (!fs.existsSync(entry.worktree))
|
|
224
|
+
return skip(entry, `worktree ${entry.worktree} does not exist`);
|
|
225
|
+
const target = resolvePushRemote(parseRemotesOutput(git(entry.worktree, ['remote', '-v'])), login);
|
|
226
|
+
if (!target)
|
|
227
|
+
return skip(entry, `no remote in ${entry.worktree} is owned by ${login}`);
|
|
228
|
+
const notFork = await forkSkipReason(target);
|
|
229
|
+
if (notFork)
|
|
230
|
+
return skip(entry, notFork, target);
|
|
231
|
+
// A recorded name git would reject is a gate saying no, not a broken push.
|
|
232
|
+
let ref;
|
|
233
|
+
try {
|
|
234
|
+
ref = buildPrepRef(entry.branch);
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
if (err instanceof PrepNamespaceError)
|
|
238
|
+
throw err;
|
|
239
|
+
return skip(entry, errorMessage(err), target);
|
|
240
|
+
}
|
|
241
|
+
const prepBranch = prepBranchName(ref);
|
|
242
|
+
const head = await prHeadFor(entry.url);
|
|
243
|
+
const base = {
|
|
244
|
+
url: entry.url,
|
|
245
|
+
branch: entry.branch,
|
|
246
|
+
remote: target.remote,
|
|
247
|
+
repo: `${target.owner}/${target.repo}`,
|
|
248
|
+
ref,
|
|
249
|
+
...(head ? { compareUrl: compareUrlFor(target, head, prepBranch) } : {}),
|
|
250
|
+
};
|
|
251
|
+
if (options.dryRun)
|
|
252
|
+
return { ...base, status: 'planned' };
|
|
253
|
+
// The recorded branch, not HEAD: a reused worktree may have something
|
|
254
|
+
// else checked out. `--no-follow-tags` keeps a `push.followTags` config
|
|
255
|
+
// from writing refs/tags/*; `--` keeps the remote name out of option
|
|
256
|
+
// parsing.
|
|
257
|
+
assertPrepRef(ref);
|
|
258
|
+
try {
|
|
259
|
+
git(entry.worktree, ['push', '--no-follow-tags', '--', target.remote, `refs/heads/${entry.branch}:${ref}`]);
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
return isNonFastForward(err)
|
|
263
|
+
? skip(entry, `non-fast-forward: ${prepBranch} on ${target.remote} has commits this worktree lacks; not forced`, target, ref)
|
|
264
|
+
: notPushed('failed', entry, pushFailureReason(err), target, ref);
|
|
265
|
+
}
|
|
266
|
+
return { ...base, status: 'pushed' };
|
|
267
|
+
}
|
|
268
|
+
const results = [];
|
|
269
|
+
// A copy of the whole list, updated in place: if the run stops early, the
|
|
270
|
+
// entries it never reached are kept as they were, not dropped.
|
|
271
|
+
const prepared = [...last.prepared];
|
|
272
|
+
let reportRecreated = false;
|
|
273
|
+
let reportWarning = null;
|
|
274
|
+
let gistSyncWarning = null;
|
|
275
|
+
/** Record what happened so far. Runs even when the loop throws, so a ref that is live on the fork is never missing from state. */
|
|
276
|
+
async function persist() {
|
|
277
|
+
if (options.dryRun)
|
|
278
|
+
return;
|
|
279
|
+
sm.setLastOvernight({ ...lastRun, prepared });
|
|
280
|
+
try {
|
|
281
|
+
reportRecreated = writePreparedSection(lastRun.reportPath, prepared).reportRecreated;
|
|
282
|
+
}
|
|
283
|
+
catch (err) {
|
|
284
|
+
// State already has the pushes; a report that cannot be written must
|
|
285
|
+
// not also cost the Gist checkpoint.
|
|
286
|
+
reportWarning = `could not rewrite ${lastRun.reportPath}: ${errorMessage(err)}`;
|
|
287
|
+
warn(MODULE, reportWarning);
|
|
288
|
+
}
|
|
289
|
+
gistSyncWarning = await maybeCheckpoint(sm, MODULE);
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
for (const [i, entry] of last.prepared.entries()) {
|
|
293
|
+
let result;
|
|
294
|
+
try {
|
|
295
|
+
result = await pushOne(entry);
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
if (err instanceof PrepNamespaceError || isRateLimitError(err))
|
|
299
|
+
throw err;
|
|
300
|
+
result = notPushed('failed', entry, errorMessage(err));
|
|
301
|
+
}
|
|
302
|
+
results.push(result);
|
|
303
|
+
if (result.status === 'pushed' && result.ref) {
|
|
304
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
305
|
+
const { pushProblem: _cleared, ...rest } = entry;
|
|
306
|
+
prepared[i] = {
|
|
307
|
+
...rest,
|
|
308
|
+
pushedRef: prepBranchName(result.ref),
|
|
309
|
+
pushedAt: new Date().toISOString(),
|
|
310
|
+
...(result.compareUrl ? { compareUrl: result.compareUrl } : {}),
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
else if (result.status !== 'planned' && result.reason) {
|
|
314
|
+
prepared[i] = { ...entry, pushProblem: result.reason };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
finally {
|
|
319
|
+
await persist();
|
|
320
|
+
}
|
|
321
|
+
const count = (status) => results.filter((r) => r.status === status).length;
|
|
322
|
+
return {
|
|
323
|
+
dryRun: options.dryRun,
|
|
324
|
+
login,
|
|
325
|
+
reportPath: last.reportPath,
|
|
326
|
+
results,
|
|
327
|
+
pushed: count('pushed'),
|
|
328
|
+
planned: count('planned'),
|
|
329
|
+
skipped: count('skipped'),
|
|
330
|
+
failed: count('failed'),
|
|
331
|
+
...(reportRecreated ? { reportRecreated: true } : {}),
|
|
332
|
+
...(reportWarning ? { reportWarning } : {}),
|
|
333
|
+
...(gistSyncWarning ? { gistSyncWarning } : {}),
|
|
334
|
+
};
|
|
335
|
+
}
|