@oss-autopilot/core 3.28.0 → 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.
Files changed (50) hide show
  1. package/dist/cli-pre-action.d.ts +9 -0
  2. package/dist/cli-pre-action.js +95 -0
  3. package/dist/cli-registry.js +5 -1
  4. package/dist/cli.bundle.cjs +116 -116
  5. package/dist/cli.js +4 -87
  6. package/dist/commands/comments.js +3 -1
  7. package/dist/commands/daily.js +32 -6
  8. package/dist/commands/dashboard-server.js +1 -1
  9. package/dist/commands/dashboard.d.ts +2 -2
  10. package/dist/commands/dashboard.js +13 -5
  11. package/dist/commands/guidelines.d.ts +8 -0
  12. package/dist/commands/guidelines.js +2 -1
  13. package/dist/commands/overnight-handoff.d.ts +59 -0
  14. package/dist/commands/overnight-handoff.js +212 -0
  15. package/dist/commands/overnight-push-prep.d.ts +7 -0
  16. package/dist/commands/overnight-push-prep.js +97 -25
  17. package/dist/commands/overnight.d.ts +22 -1
  18. package/dist/commands/overnight.js +68 -7
  19. package/dist/core/ci-analysis.js +11 -4
  20. package/dist/core/errors.d.ts +17 -0
  21. package/dist/core/errors.js +25 -0
  22. package/dist/core/pr-monitor.d.ts +2 -2
  23. package/dist/core/pr-monitor.js +9 -6
  24. package/dist/core/repo-score-manager.js +23 -2
  25. package/dist/core/review-analysis.d.ts +6 -2
  26. package/dist/core/review-analysis.js +13 -4
  27. package/dist/core/state-persistence.js +25 -11
  28. package/dist/core/status-determination.js +10 -1
  29. package/dist/core/types.d.ts +1 -1
  30. package/dist/dashboard/assets/chart-panel-0drzwc3-.js +3 -0
  31. package/dist/dashboard/assets/confetti.module-BYDB1iN2.js +2 -0
  32. package/dist/dashboard/assets/index-C0LCGMVi.js +50 -0
  33. package/dist/dashboard/assets/index-CTiG-vjC.css +1 -0
  34. package/dist/dashboard/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  35. package/dist/dashboard/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  36. package/dist/dashboard/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  37. package/dist/dashboard/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  38. package/dist/dashboard/assets/plus-jakarta-sans-latin-400-normal-BDKaGhyp.woff +0 -0
  39. package/dist/dashboard/assets/plus-jakarta-sans-latin-400-normal-Dhut76fR.woff2 +0 -0
  40. package/dist/dashboard/assets/plus-jakarta-sans-latin-500-normal-Bf-nb4oT.woff2 +0 -0
  41. package/dist/dashboard/assets/plus-jakarta-sans-latin-500-normal-DYtqi0QS.woff +0 -0
  42. package/dist/dashboard/assets/plus-jakarta-sans-latin-600-normal-BR_Ojra4.woff +0 -0
  43. package/dist/dashboard/assets/plus-jakarta-sans-latin-600-normal-DLTa1BUW.woff2 +0 -0
  44. package/dist/dashboard/assets/plus-jakarta-sans-latin-700-normal-CfpNZvy6.woff2 +0 -0
  45. package/dist/dashboard/assets/plus-jakarta-sans-latin-700-normal-DqEcQeE5.woff +0 -0
  46. package/dist/dashboard/assets/plus-jakarta-sans-latin-800-normal-BRNHt2w0.woff +0 -0
  47. package/dist/dashboard/assets/plus-jakarta-sans-latin-800-normal-CusIZhrK.woff2 +0 -0
  48. package/dist/dashboard/favicon.svg +83 -0
  49. package/dist/dashboard/index.html +54 -0
  50. package/package.json +3 -2
package/dist/cli.js CHANGED
@@ -9,8 +9,9 @@
9
9
  * handlers so only the invoked command's dependencies are evaluated.
10
10
  */
11
11
  import { Command } from 'commander';
12
- import { getGitHubTokenAsync, enableDebug, debug, getCLIVersion, stateFileExists } from './core/index.js';
12
+ import { getCLIVersion, stateFileExists } from './core/index.js';
13
13
  import { commands, handleCommandError } from './cli-registry.js';
14
+ import { installPreAction } from './cli-pre-action.js';
14
15
  const VERSION = getCLIVersion();
15
16
  const program = new Command();
16
17
  program
@@ -24,92 +25,8 @@ const localOnlySet = new Set(commands.filter((c) => c.localOnly).map((c) => c.na
24
25
  for (const cmd of commands) {
25
26
  cmd.register(program);
26
27
  }
27
- // Validate GitHub token before running commands that need it
28
- program.hook('preAction', async (thisCommand, actionCommand) => {
29
- // Enable debug logging if --debug flag is set
30
- const globalOpts = thisCommand.opts();
31
- if (globalOpts.debug) {
32
- enableDebug();
33
- debug('cli', `Running command: ${actionCommand.name()}`);
34
- }
35
- // actionCommand is the command being executed (e.g., 'status', 'daily').
36
- // For subcommand groups (e.g. `guidelines view`), Commander returns the
37
- // leaf name `view` — but the registry sets `localOnly` on the parent
38
- // entry `guidelines`. Walk the parent chain so a `localOnly` ancestor
39
- // covers all its leaves (#1208 M2). Without this, `guidelines view` —
40
- // which works fine in local mode (returns storageMode: 'local-unavailable')
41
- // — would still hit the auth gate and fail.
42
- let cmd = actionCommand;
43
- let isLocalOnly = false;
44
- while (cmd) {
45
- if (localOnlySet.has(cmd.name())) {
46
- isLocalOnly = true;
47
- break;
48
- }
49
- cmd = cmd.parent;
50
- }
51
- if (!isLocalOnly) {
52
- const token = await getGitHubTokenAsync();
53
- if (!token) {
54
- // Honor --json at the CLI boundary so machine consumers (plugins, MCP
55
- // stdio harnesses, scripts) get a parseable envelope instead of a
56
- // stderr blob followed by a non-zero exit. Commander has already parsed
57
- // the action's own options, so we check both the action command and the
58
- // raw argv as a fallback (#1056 M20).
59
- const wantsJson = Boolean(actionCommand.opts().json) || process.argv.includes('--json');
60
- if (wantsJson) {
61
- const { outputJsonError } = await import('./formatters/json.js');
62
- outputJsonError('GitHub authentication required. Install gh CLI and run `gh auth login`, or set GITHUB_TOKEN.', 'AUTH_REQUIRED');
63
- }
64
- else {
65
- console.error('Error: GitHub authentication required.');
66
- console.error('');
67
- console.error('Option 1 (Recommended): Install and authenticate GitHub CLI');
68
- console.error(' Install: https://cli.github.com/');
69
- console.error(' Then run: gh auth login');
70
- console.error('');
71
- console.error('Option 2: Set GITHUB_TOKEN environment variable');
72
- console.error(' export GITHUB_TOKEN="your-github-token-here"');
73
- console.error('');
74
- console.error('Then run your command again.');
75
- }
76
- process.exit(1);
77
- }
78
- // Activate Gist persistence if configured, before any command runs.
79
- // Shared helper peeks at the state file and only pre-sets the singleton
80
- // when Gist mode is the configured persistence (#1000). Hard errors
81
- // still throw (#1202); the resolving degraded modes are surfaced in the
82
- // JSON envelope so --json consumers see them too (#1433).
83
- const { ensureGistPersistence, renderGistWarning } = await import('./core/index.js');
84
- const status = await ensureGistPersistence(token);
85
- if (status === 'degraded' || status === 'state-unreadable') {
86
- const { setEnvelopeGistWarning } = await import('./formatters/json.js');
87
- // Shared renderer (#1444). 'degraded' is ensureGistPersistence's
88
- // deliberate conflation of the transient init fallback and a #1443
89
- // degraded bootstrap — rendered as the init-fallback cause, as before.
90
- setEnvelopeGistWarning(renderGistWarning(status === 'degraded' ? 'init-fallback' : 'state-unreadable'));
91
- }
92
- }
93
- else {
94
- // #1431: localOnly skips the AUTH GATE, not gist persistence. Mutating
95
- // localOnly commands (shelve/move/dismiss/override/...) already call
96
- // maybeCheckpoint, which silently no-ops when the singleton never
97
- // bootstrapped — so a gist-configured user's CLI mutations were written
98
- // local-only with no warning and never reached the Gist. Best-effort
99
- // bootstrap; the warning semantics live (and are unit-tested) in
100
- // bootstrapGistBestEffort.
101
- const { bootstrapGistBestEffort } = await import('./core/index.js');
102
- const localOnlyWarning = await bootstrapGistBestEffort(getGitHubTokenAsync);
103
- if (localOnlyWarning) {
104
- console.error(`Warning: ${localOnlyWarning}`);
105
- // Also thread it into the JSON envelope: shelve/move/dismiss --json
106
- // consumers (the agent harness) must see the mutation will not sync —
107
- // stderr alone is invisible to them (#1433).
108
- const { setEnvelopeGistWarning } = await import('./formatters/json.js');
109
- setEnvelopeGistWarning(localOnlyWarning);
110
- }
111
- }
112
- });
28
+ // Debug flag, auth gate and Gist bootstrap (see cli-pre-action.ts).
29
+ installPreAction(program, localOnlySet);
113
30
  // First-run detection: if no subcommand was provided and no state file exists,
114
31
  // show a quick-start guide and exit before Commander displays generic help.
115
32
  const userArgs = process.argv.slice(2);
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { getStateManager, getOctokit, parseGitHubUrl, requireGitHubToken, maybeCheckpoint } from '../core/index.js';
6
6
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
7
- import { ValidationError, isRateLimitOrAuthError } from '../core/errors.js';
7
+ import { ValidationError, assertAttended, isRateLimitOrAuthError } from '../core/errors.js';
8
8
  import { warn } from '../core/logger.js';
9
9
  const MODULE = 'comments';
10
10
  import { paginateAllDetailed } from '../core/pagination.js';
@@ -157,6 +157,7 @@ export async function runComments(options) {
157
157
  * @throws {ValidationError} If the URL or message is invalid
158
158
  */
159
159
  export async function runPost(options) {
160
+ assertAttended('post a comment');
160
161
  validateUrl(options.url);
161
162
  validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
162
163
  if (!options.message.trim()) {
@@ -192,6 +193,7 @@ export async function runPost(options) {
192
193
  * @throws {ValidationError} If the URL or message is invalid
193
194
  */
194
195
  export async function runClaim(options) {
196
+ assertAttended('claim an issue');
195
197
  validateUrl(options.issueUrl);
196
198
  validateGitHubUrl(options.issueUrl, ISSUE_URL_PATTERN, 'issue');
197
199
  const token = requireGitHubToken();
@@ -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
@@ -212,7 +212,7 @@ export async function startDashboardServer(options) {
212
212
  // cache after the port is bound, so the startup poller sees us in time.
213
213
  const initialDigest = gistSync.stateManager.getState().lastDigest;
214
214
  if (!initialDigest) {
215
- throw new Error('No dashboard data available. Run the daily check first: GITHUB_TOKEN=$(gh auth token) npm start -- daily');
215
+ throw new Error('No dashboard data available. Run the daily check first: oss-autopilot daily (or /oss in Claude Code)');
216
216
  }
217
217
  const cache = new DashboardCache(initialDigest, (failures) => gistSync.withPendingGistWarnings(failures));
218
218
  // ── Build cached JSON response ───────────────────────────────────────────
@@ -6,8 +6,8 @@ interface ServeOptions {
6
6
  open: boolean;
7
7
  }
8
8
  /**
9
- * Resolve the SPA assets directory from packages/dashboard/dist/.
10
- * Tries multiple strategies to locate it across dev (tsx) and bundled (cjs) modes.
9
+ * Resolve the SPA assets directory. Tries packages/dashboard/dist/ in a
10
+ * checkout (dev via tsx, or the bundle), then the copy shipped in the npm package.
11
11
  */
12
12
  export declare function resolveAssetsDir(): string | null;
13
13
  export declare function serveDashboard(options: ServeOptions): Promise<void>;
@@ -5,8 +5,8 @@ import * as fs from 'node:fs';
5
5
  import * as path from 'node:path';
6
6
  import { getGitHubToken } from '../core/index.js';
7
7
  /**
8
- * Resolve the SPA assets directory from packages/dashboard/dist/.
9
- * Tries multiple strategies to locate it across dev (tsx) and bundled (cjs) modes.
8
+ * Resolve the SPA assets directory. Tries packages/dashboard/dist/ in a
9
+ * checkout (dev via tsx, or the bundle), then the copy shipped in the npm package.
10
10
  */
11
11
  export function resolveAssetsDir() {
12
12
  // Strategy 1: relative to this source file (works in dev with tsx)
@@ -19,7 +19,15 @@ export function resolveAssetsDir() {
19
19
  if (fs.existsSync(path.join(bundlePath, 'index.html'))) {
20
20
  return bundlePath;
21
21
  }
22
- // Strategy 3: resolve the dashboard package via require.resolve
22
+ // Strategy 3: assets shipped inside the published package. `prepublishOnly`
23
+ // copies packages/dashboard/dist to dist/dashboard, next to the CLI bundle,
24
+ // because @oss-autopilot/dashboard itself is private and never on npm. Kept
25
+ // after the checkout paths so a working tree serves its own fresh build.
26
+ const packagedPath = path.resolve(__dirname, 'dashboard');
27
+ if (fs.existsSync(path.join(packagedPath, 'index.html'))) {
28
+ return packagedPath;
29
+ }
30
+ // Strategy 4: resolve the dashboard package via require.resolve
23
31
  try {
24
32
  const dashboardPkgPath = require.resolve('@oss-autopilot/dashboard/package.json');
25
33
  const dashboardDist = path.join(path.dirname(dashboardPkgPath), 'dist');
@@ -39,8 +47,8 @@ export async function serveDashboard(options) {
39
47
  const assetsDir = resolveAssetsDir();
40
48
  if (!assetsDir) {
41
49
  console.error('Could not find dashboard SPA assets.');
42
- console.error('Make sure packages/dashboard has been built:');
43
- console.error(' cd packages/dashboard && pnpm run build');
50
+ console.error('From a git checkout, build them: cd packages/dashboard && pnpm run build');
51
+ console.error('From npm, update to the latest @oss-autopilot/core; older releases did not include them.');
44
52
  process.exit(1);
45
53
  }
46
54
  const token = getGitHubToken();
@@ -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. */