@oss-autopilot/core 3.22.3 → 3.23.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.
@@ -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). */
@@ -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
+ }
@@ -13,7 +13,10 @@
13
13
  * the launchd plist that runs the plugin command headlessly.
14
14
  *
15
15
  * Hard gate: nothing in this module pushes, posts, or merges. That gate is the
16
- * feature, not a limitation.
16
+ * feature, not a limitation. The one deliberate exception, `overnight
17
+ * push-prep` (#1698), lives in `overnight-push-prep.ts` and is never run by
18
+ * the model: a scheduler runs it after the tick, and it only pushes to
19
+ * `prep/*` on the user's own fork.
17
20
  */
18
21
  import type { PRCheckFailure } from '../core/pr-monitor.js';
19
22
  import type { ActionableIssueType, OvernightPrepared } from '../core/types.js';
@@ -62,6 +65,15 @@ export declare function bucketize(daily: Pick<DailyOutput, 'actionableIssues' |
62
65
  };
63
66
  /** Pure: the "Prepared branches" section; `record` rewrites just this part. */
64
67
  export declare function renderPreparedSection(prepared: OvernightPrepared[]): string;
68
+ /**
69
+ * Rewrite the "Prepared branches" section of `reportPath` from `prepared`
70
+ * (state is the source of truth for the list, so the heading count stays
71
+ * right). A report someone deleted is recreated with just this section
72
+ * rather than failing the caller; `reportRecreated` says so.
73
+ */
74
+ export declare function writePreparedSection(reportPath: string, prepared: OvernightPrepared[]): {
75
+ reportRecreated: boolean;
76
+ };
65
77
  /** Pure: the morning report. Prepared branches are appended by `record`. */
66
78
  export declare function renderReport(out: ReportBody, prepared?: OvernightPrepared[]): string;
67
79
  /** Local calendar date: the job fires at a local hour, so the report is filed under the local day. */
@@ -13,7 +13,10 @@
13
13
  * the launchd plist that runs the plugin command headlessly.
14
14
  *
15
15
  * Hard gate: nothing in this module pushes, posts, or merges. That gate is the
16
- * feature, not a limitation.
16
+ * feature, not a limitation. The one deliberate exception, `overnight
17
+ * push-prep` (#1698), lives in `overnight-push-prep.ts` and is never run by
18
+ * the model: a scheduler runs it after the tick, and it only pushes to
19
+ * `prep/*` on the user's own fork.
17
20
  */
18
21
  import * as fs from 'node:fs';
19
22
  import * as os from 'node:os';
@@ -64,11 +67,30 @@ export function renderPreparedSection(prepared) {
64
67
  if (prepared.length === 0)
65
68
  lines.push('_None recorded yet._');
66
69
  for (const p of prepared) {
67
- lines.push(`- ${p.url} — branch \`${p.branch}\`${p.worktree ? ` at ${p.worktree}` : ''}${p.note ? `: ${p.note}` : ''}`);
70
+ const pushed = p.pushedRef
71
+ ? ` (pushed to \`${p.pushedRef}\`${p.compareUrl ? `, compare ${p.compareUrl}` : ''})`
72
+ : p.pushProblem
73
+ ? ` (NOT pushed: ${p.pushProblem})`
74
+ : '';
75
+ lines.push(`- ${p.url} — branch \`${p.branch}\`${p.worktree ? ` at ${p.worktree}` : ''}${pushed}${p.note ? `: ${p.note}` : ''}`);
68
76
  }
69
77
  lines.push('');
70
78
  return lines.join('\n');
71
79
  }
80
+ /**
81
+ * Rewrite the "Prepared branches" section of `reportPath` from `prepared`
82
+ * (state is the source of truth for the list, so the heading count stays
83
+ * right). A report someone deleted is recreated with just this section
84
+ * rather than failing the caller; `reportRecreated` says so.
85
+ */
86
+ export function writePreparedSection(reportPath, prepared) {
87
+ const reportExists = fs.existsSync(reportPath);
88
+ if (!reportExists)
89
+ warn(MODULE, `Report ${reportPath} is missing; recreating it with only the prepared section`);
90
+ const reportBody = reportExists ? fs.readFileSync(reportPath, 'utf8') : '';
91
+ fs.writeFileSync(reportPath, replacePreparedSection(reportBody, renderPreparedSection(prepared)), { mode: 0o600 });
92
+ return { reportRecreated: !reportExists };
93
+ }
72
94
  /** Pure: the morning report. Prepared branches are appended by `record`. */
73
95
  export function renderReport(out, prepared = []) {
74
96
  const lines = [];
@@ -153,21 +175,12 @@ export async function runOvernightRecord(options) {
153
175
  };
154
176
  const prepared = [...last.prepared, entry];
155
177
  sm.setLastOvernight({ ...last, prepared });
156
- // Rewrite the section in place (state is the source of truth for the
157
- // list) so its heading count stays right; a report someone deleted is
158
- // recreated with just this section rather than failing the record.
159
- const reportExists = fs.existsSync(last.reportPath);
160
- if (!reportExists)
161
- warn(MODULE, `Report ${last.reportPath} is missing; recreating it with only the prepared section`);
162
- const reportBody = reportExists ? fs.readFileSync(last.reportPath, 'utf8') : '';
163
- fs.writeFileSync(last.reportPath, replacePreparedSection(reportBody, renderPreparedSection(prepared)), {
164
- mode: 0o600,
165
- });
178
+ const { reportRecreated } = writePreparedSection(last.reportPath, prepared);
166
179
  const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
167
180
  return {
168
181
  reportPath: last.reportPath,
169
182
  preparedCount: prepared.length,
170
- ...(reportExists ? {} : { reportRecreated: true }),
183
+ ...(reportRecreated ? { reportRecreated: true } : {}),
171
184
  ...(gistSyncWarning ? { gistSyncWarning } : {}),
172
185
  };
173
186
  }
@@ -3,7 +3,8 @@
3
3
  * Maps state fields and creates scout instances for search/vet commands.
4
4
  */
5
5
  import { createScout } from '@oss-scout/core';
6
- import { getStateManager, isLinkedPRStalled, requireGitHubToken } from '../core/index.js';
6
+ import { getStateManager, isLinkedPRStalled, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
7
+ import { SearchRotationSchema } from '../core/state-schema.js';
7
8
  import { computeStrategy } from '../core/strategy.js';
8
9
  import { loadSkippedIssuesDetailed } from './skip-file-parser.js';
9
10
  /**
@@ -87,6 +88,27 @@ export function buildScoutState(diagnostics) {
87
88
  if ((skippedIssuesLoad.readError !== undefined || skippedIssuesLoad.notFound) && diagnostics) {
88
89
  diagnostics.skipListUnavailable = true;
89
90
  }
91
+ // Dismissed issues (`/oss dismiss`, dashboard) count as skipped for scout too.
92
+ // Without this, scout's own recently-surfaced window (7 days) was the only
93
+ // thing keeping a dismissed issue out of `search`, so it came back once the
94
+ // window lapsed. `undismiss` deletes the map entry, so only current
95
+ // dismissals are merged. Scout filters by URL alone; repo/number are
96
+ // best-effort from the URL and title is unknown, same as the skip file.
97
+ const skippedIssues = [...skippedIssuesLoad.issues];
98
+ const skippedUrls = new Set(skippedIssues.map((s) => s.url));
99
+ for (const [url, dismissedAt] of Object.entries(config.dismissedIssues ?? {})) {
100
+ if (skippedUrls.has(url))
101
+ continue;
102
+ const parsed = parseGitHubUrl(url);
103
+ skippedIssues.push({
104
+ url,
105
+ repo: parsed ? `${parsed.owner}/${parsed.repo}` : '',
106
+ number: parsed?.number ?? 0,
107
+ title: '',
108
+ skippedAt: dismissedAt,
109
+ reason: 'dismissed',
110
+ });
111
+ }
90
112
  // Strategy-derived personalization (#1464). `computeStrategy` returns null
91
113
  // below the merged-PR floor — empty lists then read as "no bias" on scout's
92
114
  // side. Baking the bias into the preferences (rather than only per-call
@@ -112,8 +134,15 @@ export function buildScoutState(diagnostics) {
112
134
  maxIssueAgeDays: config.maxIssueAgeDays,
113
135
  includeDocIssues: config.includeDocIssues,
114
136
  minRepoScoreThreshold: config.minRepoScoreThreshold,
115
- interPhaseDelayMs: 30_000,
116
- broadPhaseDelayMs: 90_000,
137
+ // No inter-phase or broad-phase cooldown. Scout's broad phase runs on
138
+ // GraphQL now (its schema default for broadPhaseDelayMs is 0), and the
139
+ // 30s/90s pins formerly here cost ~2 minutes per search. Both must be
140
+ // passed explicitly: scout does not schema-parse a provided initialState,
141
+ // so an omitted field falls through to its hard-coded 30s/90s fallbacks.
142
+ // OSS_AUTOPILOT_SCOUT_{INTER,BROAD}_PHASE_DELAY_MS (search.ts) override
143
+ // per call for hosts that need spacing.
144
+ interPhaseDelayMs: 0,
145
+ broadPhaseDelayMs: 0,
117
146
  skipBroadWhenSufficientResults: config.skipBroadWhenSufficientResults,
118
147
  persistence: config.persistence,
119
148
  slmTriageModel: config.slmTriageModel,
@@ -196,14 +225,15 @@ export function buildScoutState(diagnostics) {
196
225
  lastSeenAt: s.lastSeenAt,
197
226
  lastScore: 0,
198
227
  })),
199
- skippedIssues: skippedIssuesLoad.issues,
228
+ skippedIssues,
200
229
  lastRunAt: state.lastRunAt,
201
- // Broad-phase language rotation cursor (#1630). Scout advances it in its
202
- // own state after a search whose broad phase ran; under
230
+ // Scout's rotation cursors (#1630): the broad-phase language cursor, the
231
+ // capped phases' repo windows, and the round-robin strategy cursor. Scout
232
+ // advances them in its own state after a search; under
203
233
  // persistence:'provided' that write is discarded with the process, so
204
234
  // search.ts copies it back into AgentState and it is fed in from there.
205
- // Scout's documented default (offset 0) applies until the first search.
206
- searchRotation: state.searchRotation ?? { languageOffset: 0 },
235
+ // The schema defaults (all offsets 0) apply until the first search.
236
+ searchRotation: state.searchRotation ?? SearchRotationSchema.parse({}),
207
237
  };
208
238
  }
209
239
  /**
@@ -92,17 +92,16 @@ function sanitizeViabilityScore(raw) {
92
92
  /**
93
93
  * Read a non-negative integer scout-delay override from an env var.
94
94
  *
95
- * Scout spaces its multi-phase `/search/issues` calls with an inter-phase
96
- * delay (default 30s) and a broad-phase delay (default 90s) to stay under
97
- * GitHub's secondary rate limit (see `buildScoutState`). Those delays make a
98
- * single `search` invocation take ~100s, which is fine in normal use but makes
99
- * the live-API e2e suite (`search.e2e.test.ts`, run only in the nightly
100
- * workflow — see #1452) impractically slow. These env vars let that suite
101
- * collapse the delays so the test completes in a realistic CI window.
95
+ * Scout can space its multi-phase `/search/issues` calls with an inter-phase
96
+ * delay and a broad-phase delay to stay under GitHub's secondary rate limit.
97
+ * `buildScoutState` sets both to 0 (the broad phase runs on GraphQL now), so
98
+ * these env vars are the knob for hosts that still need spacing, including
99
+ * the live-API e2e suite (`search.e2e.test.ts`, nightly only, see #1452),
100
+ * which restores a modest gap on shared CI runner IPs.
102
101
  *
103
102
  * Returns `undefined` when the var is unset/empty or not a parseable
104
103
  * non-negative integer, so scout falls back to its preference value and
105
- * production behavior is unchanged. Only the live test/nightly run sets them.
104
+ * production behavior is unchanged.
106
105
  */
107
106
  function readScoutDelayOverride(envVar) {
108
107
  const raw = process.env[envVar];
@@ -170,9 +169,8 @@ export async function runSearch(options) {
170
169
  if (preferLanguages?.length || preferRepos?.length) {
171
170
  debug(MODULE, `Applying strategy bias to search: preferLanguages=${JSON.stringify(preferLanguages ?? [])}, preferRepos=${JSON.stringify(preferRepos ?? [])}`);
172
171
  }
173
- // Live-API test/nightly affordance (#1452): collapse scout's inter-phase
174
- // delays so the e2e suite finishes in a realistic window. Unset in normal
175
- // use → undefined → scout falls back to the 30s/90s preference defaults.
172
+ // Per-call delay override (#1452). Unset in normal use → undefined → scout
173
+ // uses the bridge preferences (0/0, see buildScoutState).
176
174
  const interPhaseDelayMs = readScoutDelayOverride('OSS_AUTOPILOT_SCOUT_INTER_PHASE_DELAY_MS');
177
175
  const broadPhaseDelayMs = readScoutDelayOverride('OSS_AUTOPILOT_SCOUT_BROAD_PHASE_DELAY_MS');
178
176
  const result = await scout.search({