@oss-autopilot/core 3.28.1 → 3.29.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.
@@ -16,6 +16,26 @@ import { updateMonthlyAnalytics } from './dashboard-data.js';
16
16
  import { deduplicateDigest, compactActionableIssues, compactRepoGroups, buildStalenessWarning, } from '../formatters/json.js';
17
17
  import { reconcileMergedPRsWithList } from './merge-loop.js';
18
18
  const MODULE = 'daily';
19
+ /**
20
+ * Run a batch against a baseline that is fresh as of right now.
21
+ *
22
+ * A daily run spends tens of seconds on the network between loading state and
23
+ * each of its saves. If the dashboard, `move`, or another CLI call writes
24
+ * state.json in that time, the compare-and-swap in `saveState` rejects the
25
+ * save, and because the baseline never moved, every later batch in the run is
26
+ * rejected too: repo scores, analytics, the merged/closed ledger and lastDigest
27
+ * were all dropped, surfacing only as warnings. Reloading first picks up the
28
+ * other writer's change and shrinks the window to the batch itself.
29
+ *
30
+ * Only safe where the callback reads state live through the manager, as the
31
+ * batches in this file do. A callback that writes from a snapshot taken
32
+ * earlier would overwrite the other writer's fields, which is why this is not
33
+ * done inside `StateManager.batch` for every caller.
34
+ */
35
+ function batchOnFreshBaseline(stateManager, fn) {
36
+ stateManager.reloadIfChanged();
37
+ stateManager.batch(fn);
38
+ }
19
39
  /**
20
40
  * Record a non-fatal failure: push a structured entry into the run's warnings
21
41
  * collector AND emit the existing log line. Consumers (dashboard, MCP, tests)
@@ -166,7 +186,7 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, closedCounts, warn
166
186
  // Per-repo try-catch: a single corrupted repo should not prevent updates to others.
167
187
  // Outer try-catch: save failure should not crash the daily check (in-memory mutations still apply).
168
188
  try {
169
- stateManager.batch(() => {
189
+ batchOnFreshBaseline(stateManager, () => {
170
190
  // Reset stale repos first (so excluded/removed repos get zeroed).
171
191
  // Guard: if the API returned zero results but we have existing repos with merged PRs,
172
192
  // skip the reset to avoid wiping scores due to transient API failures.
@@ -267,7 +287,7 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, closedCounts, warn
267
287
  }
268
288
  // Batch metadata + trust sync mutations for a single disk write
269
289
  try {
270
- stateManager.batch(() => {
290
+ batchOnFreshBaseline(stateManager, () => {
271
291
  let metadataUpdateFailures = 0;
272
292
  for (const [repo, { stars, language }] of repoMetadata) {
273
293
  try {
@@ -323,6 +343,10 @@ function partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs, warn
323
343
  // are respected by the CLI pipeline.
324
344
  // Override-application failures (#1448) mean a PR silently shows its
325
345
  // un-overridden status — record each into the run's warnings[].
346
+ // Reload first: the overrides read here decide what the batch below writes
347
+ // (unshelve, lastDigest). Reading them from the state loaded before the
348
+ // network phases would persist decisions the dashboard already superseded.
349
+ stateManager.reloadIfChanged();
326
350
  const overrideFailures = [];
327
351
  const overriddenPRs = applyStatusOverrides(prs, stateManager.getState(), overrideFailures);
328
352
  for (const failure of overrideFailures) {
@@ -336,7 +360,7 @@ function partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs, warn
336
360
  // Outer try-catch: save failure should not crash the daily check (in-memory mutations still apply).
337
361
  let digest;
338
362
  try {
339
- stateManager.batch(() => {
363
+ batchOnFreshBaseline(stateManager, () => {
340
364
  for (const pr of overriddenPRs) {
341
365
  if (stateManager.isPRShelved(pr.url)) {
342
366
  if (CRITICAL_STATUSES.has(pr.status)) {
@@ -409,13 +433,15 @@ function partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs, warn
409
433
  */
410
434
  function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, warnings, previousLastDigestAt, unextractedMergeCount) {
411
435
  const stateManager = getStateManager();
412
- // Assess capacity from active PRs only (shelved PRs excluded)
436
+ // Assess capacity from active PRs only (shelved PRs excluded). Reload first
437
+ // so maxActivePRs reflects a config change made while the run was fetching.
438
+ stateManager.reloadIfChanged();
413
439
  const capacity = assessCapacity(activePRs, stateManager.getState().config.maxActivePRs, shelvedPRs.length);
414
440
  // Filter dismissed issues: suppress if dismissed after last response, resurface + auto-undismiss if new activity.
415
441
  // Batch: undismissIssue calls trigger autoSave — batch produces a single disk write for all auto-undismisses.
416
442
  let filteredCommentedIssues = [];
417
443
  try {
418
- stateManager.batch(() => {
444
+ batchOnFreshBaseline(stateManager, () => {
419
445
  filteredCommentedIssues = commentedIssues.filter((issue) => {
420
446
  const dismissedAt = stateManager.getIssueDismissedAt(issue.url);
421
447
  if (!dismissedAt)
@@ -618,7 +644,7 @@ async function executeDailyCheckInternal(token) {
618
644
  // just-merged/closed PR was open during a prior enriched run, its
619
645
  // openPRs entry carries firstMaintainerResponseAt for the ledger (#1461).
620
646
  const previousDigest = getStateManager().getState().lastDigest;
621
- getStateManager().batch(() => {
647
+ batchOnFreshBaseline(getStateManager(), () => {
622
648
  const analyticsFailures = updateMonthlyAnalytics(prs, monthlyCounts, monthlyClosedCounts, openedFromMerged, openedFromClosed);
623
649
  // Per-metric setter failures are caught inside updateMonthlyAnalytics
624
650
  // (one bad metric must not sink the others); surface each in the run's
@@ -3,6 +3,14 @@ export interface GuidelinesViewOutput {
3
3
  repo: string;
4
4
  /** Markdown content, or null when the repo has no guidelines stored. */
5
5
  content: string | null;
6
+ /**
7
+ * `content` prefixed with the provenance note, or null. This is the field to
8
+ * hand to an agent: stored guidelines were distilled from other people's PR
9
+ * comments, and re-injected unlabeled they read as project instructions
10
+ * (#1455). `content` itself stays raw, because the edit flow reads it and
11
+ * writes it back, and a label in there would be stored as guideline text.
12
+ */
13
+ agentContent: string | null;
6
14
  /** UTF-8 byte size of `content`, or 0 when content is null. */
7
15
  byteSize: number;
8
16
  /** Whether a guidelines file exists for this repo. */
@@ -12,7 +12,7 @@
12
12
  * Standalone-mode users see "not available" on store/reset/fetch-corpus
13
13
  * because per-repo guidelines require Gist persistence to be useful.
14
14
  */
15
- import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, maybeCheckpoint, } from '../core/index.js';
15
+ import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, labelGuidelinesContent, maybeCheckpoint, } from '../core/index.js';
16
16
  import { fetchPRCommentBundlesBatch } from '../core/pr-comments-fetcher.js';
17
17
  import { warn } from '../core/logger.js';
18
18
  const MODULE = 'guidelines';
@@ -37,6 +37,7 @@ export async function runGuidelinesView(options) {
37
37
  return {
38
38
  repo: options.repo,
39
39
  content,
40
+ agentContent: content === null ? null : labelGuidelinesContent(content),
40
41
  byteSize: content === null ? 0 : Buffer.byteLength(content, 'utf8'),
41
42
  exists: content !== null,
42
43
  storageMode: sm.isGuidelinesAvailable() ? 'gist' : 'local-unavailable',
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The overnight handoff: how a tick that holds no write-capable GitHub
3
+ * credential gets its prepared branches to `overnight push-prep`, which does.
4
+ *
5
+ * On a box where the model tick runs as its own unix user, that user must not
6
+ * share a git directory with the user holding the token: `push-prep` running
7
+ * git in a repo the tick can write would run the tick's hooks, `core.fsmonitor`,
8
+ * `core.sshCommand`, credential helpers and `insteadOf` rewrites as the
9
+ * token holder. So the handoff is data only. With `OSS_AUTOPILOT_HANDOFF_DIR`
10
+ * set, `overnight` / `record` / `implement-blocked` (the tick) write into that
11
+ * directory:
12
+ *
13
+ * - `<branch>.bundle`: `git bundle` of each prepared branch;
14
+ * - `last-overnight.json`: the run's state record, without local paths;
15
+ * - `report.md`: the morning report.
16
+ *
17
+ * `push-prep` (the token holder, same env var) reads those files as untrusted
18
+ * input: never through a symlink, a FIFO or a hard link, size-capped, schema-
19
+ * checked, and each bundle is fetched into a fresh private repo it pushes from.
20
+ * Unset (the single-user default), nothing here runs.
21
+ */
22
+ import type { OvernightRecord } from '../core/types.js';
23
+ export declare const HANDOFF_ENV = "OSS_AUTOPILOT_HANDOFF_DIR";
24
+ export declare const HANDOFF_STATE = "last-overnight.json";
25
+ export declare const HANDOFF_REPORT = "report.md";
26
+ /** The drop dir, or null when this box does not split the tick from the pusher. */
27
+ export declare function handoffDir(): string | null;
28
+ /** Pure: a flat file name for a branch's bundle; never a path. */
29
+ export declare function bundleFileFor(branch: string): string;
30
+ /**
31
+ * Bundle `branch` from `worktree` into the drop dir.
32
+ * ponytail: full-history bundle, so the pusher needs no clone of its own; it
33
+ * costs the repo's size per prepared branch. Thin bundles against a pusher-
34
+ * side mirror if a big repo ever makes that hurt.
35
+ */
36
+ export declare function writeHandoffBundle(dir: string, worktree: string, branch: string): void;
37
+ /** Write the run's state record (local paths dropped) and its report into the drop dir. */
38
+ export declare function exportHandoff(dir: string, record: OvernightRecord): void;
39
+ /** Drop bundles of branches the current run no longer lists. */
40
+ export declare function pruneHandoffBundles(dir: string, keepBranches: string[]): void;
41
+ /**
42
+ * The tick's state record, validated. Only fields the pusher needs survive;
43
+ * local paths and push results from the tick side are dropped, and
44
+ * `reportPath` is left for the caller to set to its own.
45
+ */
46
+ export declare function loadHandoff(dir: string): {
47
+ record: OvernightRecord;
48
+ report: string | null;
49
+ };
50
+ /**
51
+ * Fetch `branch` from its bundle into a fresh bare repo under a private temp
52
+ * dir. The bundle is copied through a checked descriptor first, so the tick
53
+ * cannot swap the file between the check and git reading it. The caller
54
+ * pushes from `repo` and must call `cleanup`.
55
+ */
56
+ export declare function importHandoffBundle(dir: string, branch: string): {
57
+ repo: string;
58
+ cleanup: () => void;
59
+ };
@@ -0,0 +1,212 @@
1
+ /**
2
+ * The overnight handoff: how a tick that holds no write-capable GitHub
3
+ * credential gets its prepared branches to `overnight push-prep`, which does.
4
+ *
5
+ * On a box where the model tick runs as its own unix user, that user must not
6
+ * share a git directory with the user holding the token: `push-prep` running
7
+ * git in a repo the tick can write would run the tick's hooks, `core.fsmonitor`,
8
+ * `core.sshCommand`, credential helpers and `insteadOf` rewrites as the
9
+ * token holder. So the handoff is data only. With `OSS_AUTOPILOT_HANDOFF_DIR`
10
+ * set, `overnight` / `record` / `implement-blocked` (the tick) write into that
11
+ * directory:
12
+ *
13
+ * - `<branch>.bundle`: `git bundle` of each prepared branch;
14
+ * - `last-overnight.json`: the run's state record, without local paths;
15
+ * - `report.md`: the morning report.
16
+ *
17
+ * `push-prep` (the token holder, same env var) reads those files as untrusted
18
+ * input: never through a symlink, a FIFO or a hard link, size-capped, schema-
19
+ * checked, and each bundle is fetched into a fresh private repo it pushes from.
20
+ * Unset (the single-user default), nothing here runs.
21
+ */
22
+ import { execFileSync } from 'node:child_process';
23
+ import * as fs from 'node:fs';
24
+ import * as os from 'node:os';
25
+ import * as path from 'node:path';
26
+ import { OvernightRecordSchema } from '../core/state-schema.js';
27
+ export const HANDOFF_ENV = 'OSS_AUTOPILOT_HANDOFF_DIR';
28
+ export const HANDOFF_STATE = 'last-overnight.json';
29
+ export const HANDOFF_REPORT = 'report.md';
30
+ const MAX_STATE_BYTES = 1 << 20;
31
+ const MAX_REPORT_BYTES = 1 << 20;
32
+ // GitHub rejects pushes over 2 GiB anyway.
33
+ const MAX_BUNDLE_BYTES = 2 * 1024 ** 3;
34
+ const MAX_PREPARED = 50;
35
+ const MAX_NOTE_CHARS = 500;
36
+ const GIT_TIMEOUT_MS = 10 * 60_000;
37
+ /** The drop dir, or null when this box does not split the tick from the pusher. */
38
+ export function handoffDir() {
39
+ return process.env[HANDOFF_ENV] || null;
40
+ }
41
+ /** Pure: a flat file name for a branch's bundle; never a path. */
42
+ export function bundleFileFor(branch) {
43
+ return `${branch.replaceAll(/[^\w.-]/g, '_').replace(/^\.+/, '_')}.bundle`;
44
+ }
45
+ function gitRun(args) {
46
+ execFileSync('git', args, {
47
+ stdio: ['ignore', 'ignore', 'pipe'],
48
+ timeout: GIT_TIMEOUT_MS,
49
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
50
+ });
51
+ }
52
+ /** Group-readable (the pusher reads it through the drop dir's group), whatever the umask. */
53
+ function publishFile(dir, name, write) {
54
+ const tmp = path.join(dir, `.${name}.tmp`);
55
+ fs.rmSync(tmp, { force: true });
56
+ write(tmp);
57
+ fs.chmodSync(tmp, 0o640);
58
+ fs.renameSync(tmp, path.join(dir, name));
59
+ }
60
+ // ── Tick side ─────────────────────────────────────────────────────────
61
+ /**
62
+ * Bundle `branch` from `worktree` into the drop dir.
63
+ * ponytail: full-history bundle, so the pusher needs no clone of its own; it
64
+ * costs the repo's size per prepared branch. Thin bundles against a pusher-
65
+ * side mirror if a big repo ever makes that hurt.
66
+ */
67
+ export function writeHandoffBundle(dir, worktree, branch) {
68
+ publishFile(dir, bundleFileFor(branch), (tmp) => gitRun(['-C', worktree, 'bundle', 'create', '-q', tmp, `refs/heads/${branch}`]));
69
+ }
70
+ /** Write the run's state record (local paths dropped) and its report into the drop dir. */
71
+ export function exportHandoff(dir, record) {
72
+ const prepared = record.prepared.map(({ worktree: _local, ...rest }) => rest);
73
+ publishFile(dir, HANDOFF_STATE, (tmp) => fs.writeFileSync(tmp, JSON.stringify({ ...record, prepared })));
74
+ if (fs.existsSync(record.reportPath)) {
75
+ publishFile(dir, HANDOFF_REPORT, (tmp) => fs.copyFileSync(record.reportPath, tmp));
76
+ }
77
+ }
78
+ /** Drop bundles of branches the current run no longer lists. */
79
+ export function pruneHandoffBundles(dir, keepBranches) {
80
+ const keep = new Set(keepBranches.map((b) => bundleFileFor(b)));
81
+ for (const name of fs.readdirSync(dir)) {
82
+ if (name.endsWith('.bundle') && !keep.has(name))
83
+ fs.rmSync(path.join(dir, name), { force: true });
84
+ }
85
+ }
86
+ // ── Pusher side: everything below reads files the tick wrote ─────────
87
+ /**
88
+ * Stream a drop-dir file the tick wrote to `onChunk`. No symlinks
89
+ * (O_NOFOLLOW), no FIFO that would block the open (O_NONBLOCK), regular files
90
+ * only, no hard link to a file the tick could not read itself, a size cap, and
91
+ * exactly the size checked is read: the tick owns the file and could keep
92
+ * appending to it while it is read.
93
+ */
94
+ function streamUntrusted(file, maxBytes, onChunk) {
95
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
96
+ try {
97
+ const st = fs.fstatSync(fd);
98
+ if (!st.isFile())
99
+ throw new Error(`${file} is not a regular file`);
100
+ if (st.nlink !== 1)
101
+ throw new Error(`${file} has ${st.nlink} links; refusing a hard-linked file`);
102
+ if (st.size > maxBytes)
103
+ throw new Error(`${file} is ${st.size} bytes, over the ${maxBytes} byte cap`);
104
+ const buf = Buffer.alloc(Math.max(1, Math.min(st.size, 1 << 20)));
105
+ let left = st.size;
106
+ while (left > 0) {
107
+ const n = fs.readSync(fd, buf, 0, Math.min(buf.length, left), null);
108
+ if (n === 0)
109
+ throw new Error(`${file} shrank while being read`);
110
+ onChunk(buf.subarray(0, n));
111
+ left -= n;
112
+ }
113
+ if (fs.readSync(fd, buf, 0, 1, null) > 0)
114
+ throw new Error(`${file} grew while being read`);
115
+ }
116
+ finally {
117
+ fs.closeSync(fd);
118
+ }
119
+ }
120
+ function readUntrusted(file, maxBytes) {
121
+ const chunks = [];
122
+ streamUntrusted(file, maxBytes, (c) => chunks.push(Buffer.from(c)));
123
+ return Buffer.concat(chunks).toString('utf8');
124
+ }
125
+ /**
126
+ * The tick's state record, validated. Only fields the pusher needs survive;
127
+ * local paths and push results from the tick side are dropped, and
128
+ * `reportPath` is left for the caller to set to its own.
129
+ */
130
+ export function loadHandoff(dir) {
131
+ const file = path.join(dir, HANDOFF_STATE);
132
+ let raw;
133
+ try {
134
+ raw = JSON.parse(readUntrusted(file, MAX_STATE_BYTES));
135
+ }
136
+ catch (err) {
137
+ if (err.code === 'ENOENT')
138
+ throw new Error(`No overnight handoff at ${file} yet.`, { cause: err });
139
+ throw err;
140
+ }
141
+ const parsed = OvernightRecordSchema.safeParse(raw);
142
+ if (!parsed.success)
143
+ throw new Error(`${file} is not an overnight record: ${parsed.error.message}`);
144
+ const r = parsed.data;
145
+ if (Number.isNaN(Date.parse(r.runAt)))
146
+ throw new Error(`${file} has an unreadable runAt: ${r.runAt}`);
147
+ if (r.prepared.length > MAX_PREPARED)
148
+ throw new Error(`${file} lists ${r.prepared.length} branches`);
149
+ let report = null;
150
+ try {
151
+ report = readUntrusted(path.join(dir, HANDOFF_REPORT), MAX_REPORT_BYTES);
152
+ }
153
+ catch (err) {
154
+ if (err.code !== 'ENOENT')
155
+ throw err;
156
+ }
157
+ return {
158
+ record: {
159
+ runAt: r.runAt,
160
+ reportPath: '',
161
+ prepareCount: r.prepareCount,
162
+ judgmentCount: r.judgmentCount,
163
+ prepared: r.prepared.map((p) => ({
164
+ url: p.url,
165
+ branch: p.branch,
166
+ recordedAt: p.recordedAt,
167
+ ...(p.note && { note: p.note.slice(0, MAX_NOTE_CHARS) }),
168
+ })),
169
+ ...(r.implementUrl && { implementUrl: r.implementUrl }),
170
+ ...(r.implementAttempts && { implementAttempts: r.implementAttempts }),
171
+ },
172
+ report,
173
+ };
174
+ }
175
+ /**
176
+ * Fetch `branch` from its bundle into a fresh bare repo under a private temp
177
+ * dir. The bundle is copied through a checked descriptor first, so the tick
178
+ * cannot swap the file between the check and git reading it. The caller
179
+ * pushes from `repo` and must call `cleanup`.
180
+ */
181
+ export function importHandoffBundle(dir, branch) {
182
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'oss-push-prep-'));
183
+ const cleanup = () => fs.rmSync(tmp, { recursive: true, force: true });
184
+ try {
185
+ const copy = path.join(tmp, 'in.bundle');
186
+ const out = fs.openSync(copy, 'wx', 0o600);
187
+ try {
188
+ streamUntrusted(path.join(dir, bundleFileFor(branch)), MAX_BUNDLE_BYTES, (c) => fs.writeSync(out, c));
189
+ }
190
+ finally {
191
+ fs.closeSync(out);
192
+ }
193
+ const repo = path.join(tmp, 'repo.git');
194
+ gitRun(['init', '-q', '--bare', repo]);
195
+ gitRun([
196
+ '-C',
197
+ repo,
198
+ '-c',
199
+ 'fetch.fsckObjects=true',
200
+ 'fetch',
201
+ '-q',
202
+ '--no-tags',
203
+ copy,
204
+ `+refs/heads/${branch}:refs/heads/${branch}`,
205
+ ]);
206
+ return { repo, cleanup };
207
+ }
208
+ catch (err) {
209
+ cleanup();
210
+ throw err;
211
+ }
212
+ }
@@ -15,6 +15,12 @@
15
15
  * so the user's own source repos never grow `prep/*` branches.
16
16
  * 3. The ref is always `refs/heads/prep/<branch>` and never `--force`; a
17
17
  * non-fast-forward is a skip with a reason.
18
+ *
19
+ * With `OSS_AUTOPILOT_HANDOFF_DIR` set the tick ran as another user, and the
20
+ * branches arrive as bundles (overnight-handoff.ts). Then there is no
21
+ * worktree to read remotes from: the target is the PR's head repo (or
22
+ * `<login>/<repo>` for an issue), which must also be a fork of the PR's repo,
23
+ * and the push goes out of a private repo filled from the bundle.
18
24
  */
19
25
  /** The only ref namespace this command ever pushes to. */
20
26
  export declare const PREP_REF_PREFIX = "refs/heads/prep/";
@@ -27,6 +33,7 @@ export interface GitRemote {
27
33
  url: string;
28
34
  }
29
35
  export interface PushTarget extends RemoteOwnerRepo {
36
+ /** Remote name in the worktree, or the fork's URL in handoff mode. */
30
37
  remote: string;
31
38
  }
32
39
  /** `skipped`: a gate said no, nothing to fix tonight. `failed`: the push itself broke; the CLI exits 1. */
@@ -15,13 +15,22 @@
15
15
  * so the user's own source repos never grow `prep/*` branches.
16
16
  * 3. The ref is always `refs/heads/prep/<branch>` and never `--force`; a
17
17
  * non-fast-forward is a skip with a reason.
18
+ *
19
+ * With `OSS_AUTOPILOT_HANDOFF_DIR` set the tick ran as another user, and the
20
+ * branches arrive as bundles (overnight-handoff.ts). Then there is no
21
+ * worktree to read remotes from: the target is the PR's head repo (or
22
+ * `<login>/<repo>` for an issue), which must also be a fork of the PR's repo,
23
+ * and the push goes out of a private repo filled from the bundle.
18
24
  */
19
25
  import { execFileSync } from 'node:child_process';
20
26
  import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
21
28
  import { errorMessage, getOctokit, getStateManager, isRateLimitError, maybeCheckpoint, parseGitHubUrl, requireGitHubToken, } from '../core/index.js';
22
29
  import { assertAttended } from '../core/errors.js';
23
30
  import { warn } from '../core/logger.js';
24
- import { publishReport, writePreparedSection } from './overnight.js';
31
+ import { getReportsDir } from '../core/paths.js';
32
+ import { handoffDir, importHandoffBundle, loadHandoff } from './overnight-handoff.js';
33
+ import { publishReport, reportDateFor, writePreparedSection } from './overnight.js';
25
34
  const MODULE = 'overnight-push-prep';
26
35
  /** The only ref namespace this command ever pushes to. */
27
36
  export const PREP_REF_PREFIX = 'refs/heads/prep/';
@@ -158,10 +167,19 @@ export async function runOvernightPushPrep(options) {
158
167
  // environment. Inside the tick it must not run at all.
159
168
  assertAttended('push prepared branches');
160
169
  const sm = getStateManager();
161
- const last = sm.getLastOvernight();
170
+ const dropDir = handoffDir();
171
+ const handoff = dropDir ? loadHandoff(dropDir) : null;
172
+ const last = handoff
173
+ ? {
174
+ ...handoff.record,
175
+ reportPath: path.join(getReportsDir(), `overnight-${reportDateFor(new Date(handoff.record.runAt))}.md`),
176
+ }
177
+ : sm.getLastOvernight();
162
178
  if (!last)
163
179
  throw new Error('No overnight run recorded yet; run `overnight` first.');
164
180
  const lastRun = last; // narrowed binding for the closures below
181
+ if (handoff?.report != null && !options.dryRun)
182
+ fs.writeFileSync(lastRun.reportPath, handoff.report, { mode: 0o600 });
165
183
  const octokit = getOctokit(requireGitHubToken());
166
184
  const { data: viewer } = await octokit.users.getAuthenticated();
167
185
  const login = viewer.login?.trim();
@@ -179,8 +197,8 @@ export async function runOvernightPushPrep(options) {
179
197
  * GitHub redirects a transferred or renamed repo, so a stale
180
198
  * `github.com/<login>/<repo>` URL can resolve to someone else's repo.
181
199
  */
182
- async function forkSkipReason(target) {
183
- const key = `${target.owner}/${target.repo}`.toLowerCase();
200
+ async function forkSkipReason(target, upstream) {
201
+ const key = `${target.owner}/${target.repo}|${upstream ?? ''}`.toLowerCase();
184
202
  const cached = forkVerdicts.get(key);
185
203
  if (cached !== undefined)
186
204
  return cached;
@@ -191,6 +209,8 @@ export async function runOvernightPushPrep(options) {
191
209
  reason = `${target.owner}/${target.repo} is not a fork`;
192
210
  else if (data.owner.login.toLowerCase() !== login.toLowerCase())
193
211
  reason = `${target.owner}/${target.repo} resolved to ${data.full_name}, not owned by ${login}`;
212
+ else if (upstream && data.parent?.full_name?.toLowerCase() !== upstream.toLowerCase())
213
+ reason = `${data.full_name} is not a fork of ${upstream}`;
194
214
  else
195
215
  reason = null;
196
216
  }
@@ -205,31 +225,66 @@ export async function runOvernightPushPrep(options) {
205
225
  forkVerdicts.set(key, reason);
206
226
  return reason;
207
227
  }
208
- /** PR head branch for the compare URL; undefined (with a warning) when it cannot be read. */
209
- async function prHeadFor(url) {
228
+ const pulls = new Map();
229
+ /** The PR's head (branch and repo), read once per URL; undefined (with a warning) when it cannot be read. */
230
+ function pullFor(url) {
210
231
  const parsed = parseGitHubUrl(url);
211
232
  if (!parsed || parsed.type !== 'pull')
212
- return undefined;
213
- try {
214
- const { data } = await octokit.pulls.get({ owner: parsed.owner, repo: parsed.repo, pull_number: parsed.number });
215
- return data.head.ref;
233
+ return Promise.resolve(undefined);
234
+ let pending = pulls.get(url);
235
+ if (!pending) {
236
+ pending = octokit.pulls
237
+ .get({ owner: parsed.owner, repo: parsed.repo, pull_number: parsed.number })
238
+ .then(({ data }) => data.head)
239
+ .catch((err) => {
240
+ if (isRateLimitError(err))
241
+ throw err;
242
+ warn(MODULE, `Could not read the head of ${url}: ${errorMessage(err)}`);
243
+ return undefined;
244
+ });
245
+ pulls.set(url, pending);
216
246
  }
217
- catch (err) {
218
- if (isRateLimitError(err))
219
- throw err;
220
- warn(MODULE, `Could not read the head branch of ${url}; no compare URL: ${errorMessage(err)}`);
221
- return undefined;
247
+ return pending;
248
+ }
249
+ /** Handoff mode: push to the PR's head repo, or `<login>/<repo>` for an issue; a string is a skip reason. */
250
+ async function handoffTarget(url) {
251
+ const parsed = parseGitHubUrl(url);
252
+ if (!parsed)
253
+ return `${url} is not a GitHub PR or issue URL`;
254
+ const upstream = `${parsed.owner}/${parsed.repo}`;
255
+ let owner = login;
256
+ let repo = parsed.repo;
257
+ if (parsed.type === 'pull') {
258
+ const head = (await pullFor(url))?.repo;
259
+ if (!head)
260
+ return `could not read the head repository of ${url}`;
261
+ if (head.owner.login.toLowerCase() !== login.toLowerCase())
262
+ return `the head of ${url} is ${head.full_name}, not a repo owned by ${login}`;
263
+ owner = head.owner.login;
264
+ repo = head.name;
222
265
  }
266
+ return { target: { owner, repo, remote: `https://github.com/${owner}/${repo}.git` }, upstream };
223
267
  }
224
268
  async function pushOne(entry) {
225
- if (!entry.worktree)
226
- return skip(entry, 'no worktree recorded');
227
- if (!fs.existsSync(entry.worktree))
228
- return skip(entry, `worktree ${entry.worktree} does not exist`);
229
- const target = resolvePushRemote(parseRemotesOutput(git(entry.worktree, ['remote', '-v'])), login);
230
- if (!target)
231
- return skip(entry, `no remote in ${entry.worktree} is owned by ${login}`);
232
- const notFork = await forkSkipReason(target);
269
+ let target;
270
+ let upstream;
271
+ if (dropDir) {
272
+ const resolved = await handoffTarget(entry.url);
273
+ if (typeof resolved === 'string')
274
+ return skip(entry, resolved);
275
+ ({ target, upstream } = resolved);
276
+ }
277
+ else {
278
+ if (!entry.worktree)
279
+ return skip(entry, 'no worktree recorded');
280
+ if (!fs.existsSync(entry.worktree))
281
+ return skip(entry, `worktree ${entry.worktree} does not exist`);
282
+ const found = resolvePushRemote(parseRemotesOutput(git(entry.worktree, ['remote', '-v'])), login);
283
+ if (!found)
284
+ return skip(entry, `no remote in ${entry.worktree} is owned by ${login}`);
285
+ target = found;
286
+ }
287
+ const notFork = await forkSkipReason(target, upstream);
233
288
  if (notFork)
234
289
  return skip(entry, notFork, target);
235
290
  // A recorded name git would reject is a gate saying no, not a broken push.
@@ -243,7 +298,7 @@ export async function runOvernightPushPrep(options) {
243
298
  return skip(entry, errorMessage(err), target);
244
299
  }
245
300
  const prepBranch = prepBranchName(ref);
246
- const head = await prHeadFor(entry.url);
301
+ const head = (await pullFor(entry.url))?.ref;
247
302
  const base = {
248
303
  url: entry.url,
249
304
  branch: entry.branch,
@@ -259,14 +314,27 @@ export async function runOvernightPushPrep(options) {
259
314
  // from writing refs/tags/*; `--` keeps the remote name out of option
260
315
  // parsing.
261
316
  assertPrepRef(ref);
317
+ // Handoff: push out of a private repo filled from the bundle, never out
318
+ // of anything the tick can write. A bundle that cannot be imported is a
319
+ // failure (the tick recorded a branch it did not deliver), not a gate.
320
+ let source;
321
+ try {
322
+ source = dropDir ? importHandoffBundle(dropDir, entry.branch) : { repo: entry.worktree, cleanup: () => { } };
323
+ }
324
+ catch (err) {
325
+ return notPushed('failed', entry, `bundle import failed: ${errorMessage(err)}`, target, ref);
326
+ }
262
327
  try {
263
- git(entry.worktree, ['push', '--no-follow-tags', '--', target.remote, `refs/heads/${entry.branch}:${ref}`]);
328
+ git(source.repo, ['push', '--no-follow-tags', '--', target.remote, `refs/heads/${entry.branch}:${ref}`]);
264
329
  }
265
330
  catch (err) {
266
331
  return isNonFastForward(err)
267
332
  ? skip(entry, `non-fast-forward: ${prepBranch} on ${target.remote} has commits this worktree lacks; not forced`, target, ref)
268
333
  : notPushed('failed', entry, pushFailureReason(err), target, ref);
269
334
  }
335
+ finally {
336
+ source.cleanup();
337
+ }
270
338
  return { ...base, status: 'pushed' };
271
339
  }
272
340
  const results = [];
@@ -128,9 +128,27 @@ export declare function renderReport(out: ReportBody, prepared?: OvernightPrepar
128
128
  /** Local calendar date: the job fires at a local hour, so the report is filed under the local day. */
129
129
  export declare function reportDateFor(d: Date): string;
130
130
  export declare function runOvernight(): Promise<OvernightOutput>;
131
+ /** The fields of the preparer agent's four-line report (agents/overnight-preparer.md). */
132
+ export interface PreparerReport {
133
+ branch?: string;
134
+ worktree?: string;
135
+ status?: string;
136
+ note?: string;
137
+ }
138
+ /**
139
+ * Parse the preparer's `KEY: value` report. The agent that writes it has read
140
+ * CI logs and review comments from other people's repos, so its text is
141
+ * untrusted. The orchestrating command saves the report with the Write tool and
142
+ * passes the path (`--from-report`); nothing from it is ever spliced into a
143
+ * shell command line, where `$(...)` or backticks inside double quotes would run.
144
+ * Unknown lines are ignored and the first occurrence of a key wins.
145
+ */
146
+ export declare function parsePreparerReport(text: string): PreparerReport;
131
147
  export interface OvernightImplementBlockedOptions {
132
148
  url: string;
133
149
  note?: string;
150
+ /** Path to the saved preparer report; supplies `note` when it is not given. */
151
+ fromReport?: string;
134
152
  }
135
153
  export interface OvernightImplementBlockedOutput {
136
154
  url: string;
@@ -146,9 +164,12 @@ export interface OvernightImplementBlockedOutput {
146
164
  export declare function runOvernightImplementBlocked(options: OvernightImplementBlockedOptions): Promise<OvernightImplementBlockedOutput>;
147
165
  export interface OvernightRecordOptions {
148
166
  url: string;
149
- branch: string;
167
+ /** Required unless `fromReport` supplies it. */
168
+ branch?: string;
150
169
  worktree?: string;
151
170
  note?: string;
171
+ /** Path to the saved preparer report; supplies branch, worktree and note when they are not given. */
172
+ fromReport?: string;
152
173
  }
153
174
  export interface OvernightRecordOutput {
154
175
  reportPath: string;