@oss-autopilot/core 3.22.2 → 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). */
@@ -3,7 +3,7 @@
3
3
  * Scans configurable directories for local git clones and caches results
4
4
  */
5
5
  import * as fs from 'node:fs';
6
- import * as path from 'node:path';
6
+ import path from 'node:path';
7
7
  import * as os from 'node:os';
8
8
  import { execFileSync } from 'node:child_process';
9
9
  import { getStateManager, debug } from '../core/index.js';
@@ -17,6 +17,49 @@ const DEFAULT_SCAN_PATHS = [
17
17
  path.join(os.homedir(), 'code'),
18
18
  path.join(os.homedir(), 'repos'),
19
19
  ];
20
+ // Maximum depth for `.git` directories, matching the previous `find -maxdepth 4` behavior.
21
+ const MAX_GIT_DIR_DEPTH = 4;
22
+ // Wall-clock bound per scan root, matching the previous `execFileSync` timeout. A scan root like
23
+ // `~` can hold millions of entries within four levels; a partial result beats a hung process.
24
+ const SCAN_TIMEOUT_MS = 30_000;
25
+ function collectGitDirectoryEntries(entries, directory, depth, pending, gitDirectories) {
26
+ for (const entry of entries) {
27
+ if (!entry.isDirectory())
28
+ continue;
29
+ const childPath = path.join(directory, entry.name);
30
+ const childDepth = depth + 1;
31
+ if (entry.name === '.git') {
32
+ gitDirectories.push(childPath);
33
+ }
34
+ else if (childDepth < MAX_GIT_DIR_DEPTH) {
35
+ pending.push({ directory: childPath, depth: childDepth });
36
+ }
37
+ }
38
+ }
39
+ // Find `.git` directories without platform-specific shell tools. Directory symlinks are not
40
+ // followed, matching GNU find's default behavior.
41
+ function findGitDirectories(scanPath) {
42
+ const gitDirectories = [];
43
+ const pending = [{ directory: scanPath, depth: 0 }];
44
+ const deadline = Date.now() + SCAN_TIMEOUT_MS;
45
+ while (pending.length > 0) {
46
+ if (Date.now() > deadline) {
47
+ debug('local-repos', `Scan of ${scanPath} exceeded ${SCAN_TIMEOUT_MS}ms; returning partial results`);
48
+ break;
49
+ }
50
+ const { directory, depth } = pending.pop();
51
+ let entries;
52
+ try {
53
+ entries = fs.readdirSync(directory, { withFileTypes: true });
54
+ }
55
+ catch (error) {
56
+ debug('local-repos', `Failed to read directory ${directory}`, error);
57
+ continue;
58
+ }
59
+ collectGitDirectoryEntries(entries, directory, depth, pending, gitDirectories);
60
+ }
61
+ return gitDirectories;
62
+ }
20
63
  /** Extract the GitHub "owner/repo" remote from a git directory */
21
64
  function getGitHubRemote(repoPath) {
22
65
  try {
@@ -62,23 +105,10 @@ export function scanForRepos(scanPaths) {
62
105
  for (const scanPath of scanPaths) {
63
106
  if (!fs.existsSync(scanPath))
64
107
  continue;
65
- // Find git repos up to 3 levels deep
66
- let gitDirs;
67
- try {
68
- const output = execFileSync('find', [scanPath, '-maxdepth', '4', '-name', '.git', '-type', 'd'], {
69
- encoding: 'utf8',
70
- timeout: 30_000,
71
- stdio: ['pipe', 'pipe', 'pipe'],
72
- }).trim();
73
- gitDirs = output ? output.split('\n').filter(Boolean) : [];
74
- }
75
- catch (err) {
76
- // find command failed for this scan path (permission denied, path gone, etc.) — skip it
77
- debug('local-repos', `find failed for scan path ${scanPath}`, err);
78
- continue;
79
- }
80
- for (const gitDir of gitDirs) {
81
- const repoPath = path.dirname(gitDir);
108
+ // Find `.git` directories up to 4 levels beneath the scan root (repos up to 3 levels deep).
109
+ const gitDirectories = findGitDirectories(scanPath);
110
+ for (const gitDirectory of gitDirectories) {
111
+ const repoPath = path.dirname(gitDirectory);
82
112
  const remote = getGitHubRemote(repoPath);
83
113
  if (!remote)
84
114
  continue;
@@ -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
  }
@@ -258,6 +271,15 @@ export const OVERNIGHT_DISALLOWED_TOOLS = [
258
271
  'Bash(gh issue close *)',
259
272
  'Bash(gh run rerun *)',
260
273
  'Bash(gh api *)',
274
+ // `npm`/`pnpm` are allowed for builds and tests, but a token in ~/.npmrc
275
+ // would let their registry writes ship a release unattended — exactly the
276
+ // credential-bearing writes the gate exists to keep out.
277
+ 'Bash(npm publish)',
278
+ 'Bash(npm publish *)',
279
+ 'Bash(npm unpublish *)',
280
+ 'Bash(npm deprecate *)',
281
+ 'Bash(pnpm publish)',
282
+ 'Bash(pnpm publish *)',
261
283
  'AskUserQuestion',
262
284
  ].join(',');
263
285
  export const OVERNIGHT_ALLOWED_TOOLS = [