@oss-autopilot/core 3.42.5 → 3.44.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 (192) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +428 -27
  3. package/dist/cli.bundle.cjs +212 -156
  4. package/dist/commands/check-integration.js +5 -1
  5. package/dist/commands/cleanup.d.ts +80 -0
  6. package/dist/commands/cleanup.js +334 -0
  7. package/dist/commands/comments.d.ts +14 -1
  8. package/dist/commands/comments.js +17 -5
  9. package/dist/commands/config.d.ts +2 -0
  10. package/dist/commands/config.js +63 -6
  11. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  12. package/dist/commands/daily-dismiss-filter.js +17 -1
  13. package/dist/commands/daily-ledger.d.ts +150 -0
  14. package/dist/commands/daily-ledger.js +248 -0
  15. package/dist/commands/daily-recent-prs.d.ts +26 -0
  16. package/dist/commands/daily-recent-prs.js +55 -0
  17. package/dist/commands/daily-render.d.ts +2 -1
  18. package/dist/commands/daily-render.js +4 -1
  19. package/dist/commands/daily.d.ts +5 -1
  20. package/dist/commands/daily.js +83 -93
  21. package/dist/commands/dashboard-cache.d.ts +2 -0
  22. package/dist/commands/dashboard-cache.js +33 -8
  23. package/dist/commands/dashboard-data.js +113 -69
  24. package/dist/commands/dashboard-gist-sync.js +3 -1
  25. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  26. package/dist/commands/dashboard-lifecycle.js +132 -39
  27. package/dist/commands/dashboard-process.d.ts +49 -1
  28. package/dist/commands/dashboard-process.js +111 -12
  29. package/dist/commands/dashboard-server.js +89 -23
  30. package/dist/commands/detect-formatters.js +1 -0
  31. package/dist/commands/dismiss.js +11 -7
  32. package/dist/commands/doctor.d.ts +15 -1
  33. package/dist/commands/doctor.js +66 -5
  34. package/dist/commands/draft.d.ts +77 -0
  35. package/dist/commands/draft.js +218 -0
  36. package/dist/commands/eval.js +1 -0
  37. package/dist/commands/fork-prune.d.ts +58 -0
  38. package/dist/commands/fork-prune.js +247 -0
  39. package/dist/commands/guidelines.d.ts +69 -2
  40. package/dist/commands/guidelines.js +158 -14
  41. package/dist/commands/index.d.ts +29 -4
  42. package/dist/commands/index.js +20 -3
  43. package/dist/commands/issue-thread.d.ts +46 -0
  44. package/dist/commands/issue-thread.js +123 -0
  45. package/dist/commands/ledger-backfill.d.ts +9 -0
  46. package/dist/commands/ledger-backfill.js +44 -1
  47. package/dist/commands/list-mark-done.d.ts +2 -1
  48. package/dist/commands/list-mark-done.js +3 -1
  49. package/dist/commands/list-move-tier.d.ts +2 -1
  50. package/dist/commands/list-move-tier.js +3 -1
  51. package/dist/commands/local-repos.js +10 -5
  52. package/dist/commands/locate-issue-list.d.ts +40 -17
  53. package/dist/commands/locate-issue-list.js +148 -88
  54. package/dist/commands/move.js +7 -1
  55. package/dist/commands/overnight-handoff.d.ts +17 -7
  56. package/dist/commands/overnight-handoff.js +36 -14
  57. package/dist/commands/overnight-push-prep.d.ts +14 -8
  58. package/dist/commands/overnight-push-prep.js +107 -35
  59. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  60. package/dist/commands/overnight-tool-rules.js +217 -0
  61. package/dist/commands/overnight.d.ts +5 -6
  62. package/dist/commands/overnight.js +61 -140
  63. package/dist/commands/parse-list.js +7 -1
  64. package/dist/commands/policy.d.ts +90 -0
  65. package/dist/commands/policy.js +276 -0
  66. package/dist/commands/pr-create.d.ts +48 -0
  67. package/dist/commands/pr-create.js +200 -0
  68. package/dist/commands/pr-preflight.d.ts +69 -0
  69. package/dist/commands/pr-preflight.js +348 -0
  70. package/dist/commands/repo-vet.d.ts +9 -0
  71. package/dist/commands/repo-vet.js +36 -11
  72. package/dist/commands/scout-bridge.js +18 -8
  73. package/dist/commands/search.js +7 -0
  74. package/dist/commands/setup.d.ts +3 -3
  75. package/dist/commands/setup.js +160 -48
  76. package/dist/commands/skip-add.js +10 -1
  77. package/dist/commands/startup.d.ts +12 -3
  78. package/dist/commands/startup.js +82 -49
  79. package/dist/commands/state-cmd.d.ts +2 -0
  80. package/dist/commands/state-cmd.js +5 -1
  81. package/dist/commands/stats.js +1 -0
  82. package/dist/commands/status.js +6 -0
  83. package/dist/commands/strategy.js +1 -0
  84. package/dist/commands/validation.d.ts +5 -0
  85. package/dist/commands/validation.js +5 -0
  86. package/dist/commands/vet-list.d.ts +6 -0
  87. package/dist/commands/vet-list.js +26 -1
  88. package/dist/commands/vet.d.ts +20 -0
  89. package/dist/commands/vet.js +133 -2
  90. package/dist/commands/work.d.ts +4 -0
  91. package/dist/commands/work.js +34 -11
  92. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  93. package/dist/core/anti-llm-policy.d.ts +3 -0
  94. package/dist/core/anti-llm-policy.js +3 -0
  95. package/dist/core/auth.js +2 -0
  96. package/dist/core/ci-analysis.d.ts +7 -2
  97. package/dist/core/ci-analysis.js +76 -21
  98. package/dist/core/commit-date.d.ts +45 -0
  99. package/dist/core/commit-date.js +45 -0
  100. package/dist/core/compliance-score.d.ts +3 -0
  101. package/dist/core/compliance-score.js +13 -9
  102. package/dist/core/config-registry.d.ts +27 -2
  103. package/dist/core/config-registry.js +94 -7
  104. package/dist/core/contributing.d.ts +2 -3
  105. package/dist/core/contributing.js +2 -3
  106. package/dist/core/daily-logic.d.ts +30 -5
  107. package/dist/core/daily-logic.js +68 -19
  108. package/dist/core/errors.d.ts +37 -3
  109. package/dist/core/errors.js +54 -5
  110. package/dist/core/fork-prune.d.ts +149 -0
  111. package/dist/core/fork-prune.js +333 -0
  112. package/dist/core/gist-health.d.ts +15 -3
  113. package/dist/core/gist-health.js +8 -0
  114. package/dist/core/gist-state-store.d.ts +24 -4
  115. package/dist/core/gist-state-store.js +98 -51
  116. package/dist/core/github-stats.d.ts +110 -16
  117. package/dist/core/github-stats.js +295 -110
  118. package/dist/core/http-cache.d.ts +0 -10
  119. package/dist/core/http-cache.js +0 -19
  120. package/dist/core/index.d.ts +13 -6
  121. package/dist/core/index.js +16 -6
  122. package/dist/core/issue-conversation.d.ts +8 -2
  123. package/dist/core/issue-conversation.js +31 -12
  124. package/dist/core/local-config.d.ts +95 -0
  125. package/dist/core/local-config.js +270 -0
  126. package/dist/core/merged-pr-notes.d.ts +2 -2
  127. package/dist/core/pacing.d.ts +41 -0
  128. package/dist/core/pacing.js +115 -0
  129. package/dist/core/pagination.d.ts +55 -0
  130. package/dist/core/pagination.js +59 -0
  131. package/dist/core/paths.d.ts +7 -0
  132. package/dist/core/paths.js +9 -0
  133. package/dist/core/pr-assembly.d.ts +2 -0
  134. package/dist/core/pr-assembly.js +6 -2
  135. package/dist/core/pr-graphql.d.ts +53 -4
  136. package/dist/core/pr-graphql.js +87 -14
  137. package/dist/core/pr-monitor.d.ts +35 -12
  138. package/dist/core/pr-monitor.js +110 -26
  139. package/dist/core/pr-preflight.d.ts +154 -0
  140. package/dist/core/pr-preflight.js +753 -0
  141. package/dist/core/pr-quality-rubric.d.ts +0 -6
  142. package/dist/core/pr-quality-rubric.js +0 -8
  143. package/dist/core/pr-template.d.ts +2 -0
  144. package/dist/core/pr-template.js +5 -1
  145. package/dist/core/prose-script.d.ts +72 -0
  146. package/dist/core/prose-script.js +223 -0
  147. package/dist/core/repo-policy.d.ts +111 -0
  148. package/dist/core/repo-policy.js +428 -0
  149. package/dist/core/repo-score-manager.d.ts +66 -0
  150. package/dist/core/repo-score-manager.js +140 -1
  151. package/dist/core/review-analysis.d.ts +49 -21
  152. package/dist/core/review-analysis.js +89 -15
  153. package/dist/core/reviewed-prs-fetch.js +11 -29
  154. package/dist/core/reviewed-prs.js +8 -15
  155. package/dist/core/stale-data.d.ts +78 -0
  156. package/dist/core/stale-data.js +153 -0
  157. package/dist/core/state-persistence.d.ts +62 -27
  158. package/dist/core/state-persistence.js +338 -119
  159. package/dist/core/state-schema.d.ts +152 -210
  160. package/dist/core/state-schema.js +232 -80
  161. package/dist/core/state.d.ts +81 -8
  162. package/dist/core/state.js +239 -46
  163. package/dist/core/status-determination.js +32 -12
  164. package/dist/core/strategy.js +3 -1
  165. package/dist/core/types.d.ts +22 -1
  166. package/dist/core/types.js +1 -0
  167. package/dist/core/untrusted-content.d.ts +30 -11
  168. package/dist/core/untrusted-content.js +95 -42
  169. package/dist/core/urls.d.ts +33 -0
  170. package/dist/core/urls.js +94 -0
  171. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  172. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  173. package/dist/dashboard/index.html +1 -1
  174. package/dist/formatters/json.d.ts +432 -10
  175. package/dist/formatters/json.js +156 -1
  176. package/package.json +6 -6
  177. package/dist/core/ci-enforced-tools.d.ts +0 -35
  178. package/dist/core/ci-enforced-tools.js +0 -109
  179. package/dist/core/comment-decision.d.ts +0 -79
  180. package/dist/core/comment-decision.js +0 -82
  181. package/dist/core/extraction-categories.d.ts +0 -55
  182. package/dist/core/extraction-categories.js +0 -108
  183. package/dist/core/follow-up-history.d.ts +0 -40
  184. package/dist/core/follow-up-history.js +0 -71
  185. package/dist/core/issue-effort.d.ts +0 -29
  186. package/dist/core/issue-effort.js +0 -47
  187. package/dist/core/maintainer-hints.d.ts +0 -23
  188. package/dist/core/maintainer-hints.js +0 -36
  189. package/dist/core/workflow-state.d.ts +0 -56
  190. package/dist/core/workflow-state.js +0 -101
  191. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +0 -3
  192. package/dist/dashboard/assets/index-B25bZOYX.js +0 -55
@@ -20,8 +20,56 @@ export declare function readDashboardServerInfo(): DashboardServerInfo | null;
20
20
  */
21
21
  export declare function recordBrowserOpened(port: number): void;
22
22
  export declare function removeDashboardServerInfo(): void;
23
- export declare function isDashboardServerRunning(port: number): Promise<boolean>;
23
+ /**
24
+ * Remove the PID file only when it records this process. A server that lost
25
+ * the file to a newer server (it was probed as dead, then replaced) must not
26
+ * delete the replacement's PID file on its own shutdown (#1927).
27
+ */
28
+ export declare function removeOwnDashboardServerInfo(): void;
29
+ /**
30
+ * Probe GET /api/health, which sits outside the rate limiters and reloads no
31
+ * state: the old probe of /api/data read a busy or throttled server as dead
32
+ * (#1927). The server counts as ours only when the reply names the PID the
33
+ * PID file records, so another program listening on the port (or a recycled
34
+ * PID) never passes as the dashboard.
35
+ */
36
+ export declare function isDashboardServerRunning(port: number, pid: number): Promise<boolean>;
37
+ /**
38
+ * What the PID file points at. `unverified` means the recorded PID is alive
39
+ * but did not answer `/api/health` as ours: a recycled PID, a server too busy
40
+ * to answer within the timeout, or a server from before 3.43.0, which has no
41
+ * health route (#1882). The PID file is left in place for the caller to decide.
42
+ */
43
+ export type DashboardServerProbe = {
44
+ status: 'none';
45
+ } | {
46
+ info: DashboardServerInfo;
47
+ status: 'running';
48
+ port: number;
49
+ url: string;
50
+ } | {
51
+ status: 'unverified';
52
+ info: DashboardServerInfo;
53
+ };
54
+ export declare function probeDashboardServer(): Promise<DashboardServerProbe>;
24
55
  export declare function findRunningDashboardServer(): Promise<{
25
56
  port: number;
26
57
  url: string;
27
58
  } | null>;
59
+ /**
60
+ * True only for the command line the launchers spawn: `node [--flags] <cli
61
+ * entry> dashboard serve ...`. Matching "dashboard serve" anywhere in argv
62
+ * would accept a recycled PID now running e.g. `grep -rn "dashboard serve"`
63
+ * or a shell wrapper. Anything else, including paths with spaces and a tsx
64
+ * dev server, reads as false, which only ever means "never signal".
65
+ */
66
+ export declare function isDashboardServeCommand(command: string): boolean;
67
+ /**
68
+ * True only when the process at `pid` is a `dashboard serve` process, read
69
+ * from its command line (see isDashboardServeCommand). This is what lets a
70
+ * caller signal a server that does not answer `/api/health` (#1882) without
71
+ * ever signalling a PID that was recycled to an unrelated program (#1927).
72
+ * Anything that cannot be checked (no `ps`, as on Windows, or an exited PID)
73
+ * reads as false.
74
+ */
75
+ export declare function isDashboardServeProcess(pid: number): boolean;
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import * as http from 'node:http';
6
6
  import * as fs from 'node:fs';
7
+ import { execFileSync } from 'node:child_process';
7
8
  import * as path from 'node:path';
8
9
  import { getDataDir } from '../core/index.js';
9
10
  import { warn } from '../core/logger.js';
@@ -70,13 +71,50 @@ export function removeDashboardServerInfo() {
70
71
  }
71
72
  }
72
73
  }
74
+ /**
75
+ * Remove the PID file only when it records this process. A server that lost
76
+ * the file to a newer server (it was probed as dead, then replaced) must not
77
+ * delete the replacement's PID file on its own shutdown (#1927).
78
+ */
79
+ export function removeOwnDashboardServerInfo() {
80
+ if (readDashboardServerInfo()?.pid === process.pid)
81
+ removeDashboardServerInfo();
82
+ }
73
83
  // ── Health Probe ───────────────────────────────────────────────────────────────
74
- export function isDashboardServerRunning(port) {
84
+ /** Our health reply is a few dozen bytes; anything larger is another program. */
85
+ const MAX_HEALTH_BODY_LENGTH = 1024;
86
+ /** The `pid` field of a health reply, or undefined when the body is not ours. */
87
+ function parseHealthPid(body) {
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(body);
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ return parsed?.pid;
96
+ }
97
+ /**
98
+ * Probe GET /api/health, which sits outside the rate limiters and reloads no
99
+ * state: the old probe of /api/data read a busy or throttled server as dead
100
+ * (#1927). The server counts as ours only when the reply names the PID the
101
+ * PID file records, so another program listening on the port (or a recycled
102
+ * PID) never passes as the dashboard.
103
+ */
104
+ export function isDashboardServerRunning(port, pid) {
75
105
  return new Promise((resolve) => {
76
- const req = http.get(`http://127.0.0.1:${port}/api/data`, { timeout: 2000 }, (res) => {
77
- // Consume response data to free up memory
78
- res.resume();
79
- resolve(res.statusCode === 200);
106
+ const req = http.get(`http://127.0.0.1:${port}/api/health`, { timeout: 2000 }, (res) => {
107
+ let body = '';
108
+ res.setEncoding('utf8');
109
+ res.on('data', (chunk) => {
110
+ body += chunk;
111
+ if (body.length > MAX_HEALTH_BODY_LENGTH) {
112
+ resolve(false);
113
+ req.destroy();
114
+ }
115
+ });
116
+ res.on('end', () => resolve(parseHealthPid(body) === pid));
117
+ res.on('error', () => resolve(false));
80
118
  });
81
119
  req.on('error', () => resolve(false));
82
120
  req.on('timeout', () => {
@@ -85,10 +123,10 @@ export function isDashboardServerRunning(port) {
85
123
  });
86
124
  });
87
125
  }
88
- export async function findRunningDashboardServer() {
126
+ export async function probeDashboardServer() {
89
127
  const info = readDashboardServerInfo();
90
128
  if (!info)
91
- return null;
129
+ return { status: 'none' };
92
130
  // Check if process is alive (signal 0 = existence check only)
93
131
  try {
94
132
  process.kill(info.pid, 0);
@@ -101,13 +139,74 @@ export async function findRunningDashboardServer() {
101
139
  // ESRCH = no process at that PID; EPERM = PID recycled to another user's process
102
140
  // Either way, our dashboard server is no longer running — clean up stale PID file
103
141
  removeDashboardServerInfo();
104
- return null;
142
+ return { status: 'none' };
105
143
  }
106
144
  // Process exists — verify it's actually our server via HTTP probe
107
- if (await isDashboardServerRunning(info.port)) {
108
- return { port: info.port, url: `http://oss.localhost:${info.port}` };
145
+ if (await isDashboardServerRunning(info.port, info.pid)) {
146
+ return { info, status: 'running', port: info.port, url: `http://oss.localhost:${info.port}` };
109
147
  }
110
- // Process exists but not responding on expected port — stale
111
- removeDashboardServerInfo();
148
+ return { status: 'unverified', info };
149
+ }
150
+ export async function findRunningDashboardServer() {
151
+ const probe = await probeDashboardServer();
152
+ if (probe.status === 'running')
153
+ return { port: probe.port, url: probe.url };
154
+ // Process exists but is not answering as our server on the expected port:
155
+ // stale. Never signal it. The PID file outlives crashes and reboots, so the
156
+ // PID may have been recycled to an unrelated process (#1927).
157
+ if (probe.status === 'unverified')
158
+ removeDashboardServerInfo();
112
159
  return null;
113
160
  }
161
+ const PS_PATHS = ['/bin/ps', '/usr/bin/ps'];
162
+ /** The CLI entries a server is started from: the bundle, a source entry, or the npm bin. */
163
+ const EVAL_FLAGS = new Set(['-e', '--eval', '-p', '--print']);
164
+ const CLI_ENTRY = /^(?:cli\.(?:bundle\.cjs|ts|js)|oss-autopilot)$/;
165
+ /**
166
+ * True only for the command line the launchers spawn: `node [--flags] <cli
167
+ * entry> dashboard serve ...`. Matching "dashboard serve" anywhere in argv
168
+ * would accept a recycled PID now running e.g. `grep -rn "dashboard serve"`
169
+ * or a shell wrapper. Anything else, including paths with spaces and a tsx
170
+ * dev server, reads as false, which only ever means "never signal".
171
+ */
172
+ export function isDashboardServeCommand(command) {
173
+ const tokens = command.trim().split(/\s+/);
174
+ if (!/^node(?:js)?$/.test(path.basename(tokens[0])))
175
+ return false;
176
+ let i = 1;
177
+ while (tokens[i]?.startsWith('-')) {
178
+ // With -e / -p the next token is code, not the script.
179
+ if (EVAL_FLAGS.has(tokens[i].split('=', 1)[0]))
180
+ return false;
181
+ i++;
182
+ }
183
+ return (i + 2 < tokens.length &&
184
+ CLI_ENTRY.test(path.basename(tokens[i])) &&
185
+ tokens[i + 1] === 'dashboard' &&
186
+ tokens[i + 2] === 'serve');
187
+ }
188
+ /**
189
+ * True only when the process at `pid` is a `dashboard serve` process, read
190
+ * from its command line (see isDashboardServeCommand). This is what lets a
191
+ * caller signal a server that does not answer `/api/health` (#1882) without
192
+ * ever signalling a PID that was recycled to an unrelated program (#1927).
193
+ * Anything that cannot be checked (no `ps`, as on Windows, or an exited PID)
194
+ * reads as false.
195
+ */
196
+ export function isDashboardServeProcess(pid) {
197
+ // An absolute path, so a `ps` earlier on PATH cannot answer for it.
198
+ const ps = PS_PATHS.find((candidate) => fs.existsSync(candidate));
199
+ if (!ps)
200
+ return false;
201
+ try {
202
+ const command = execFileSync(ps, ['-o', 'command=', '-p', String(pid)], {
203
+ encoding: 'utf8',
204
+ timeout: 2000,
205
+ stdio: ['ignore', 'pipe', 'ignore'],
206
+ });
207
+ return isDashboardServeCommand(command);
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
@@ -15,15 +15,15 @@ import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
16
  import * as crypto from 'node:crypto';
17
17
  import { getGitHubToken, getCLIVersion } from '../core/index.js';
18
- import { errorMessage, ValidationError, ConcurrencyError, GistConcurrencyError } from '../core/errors.js';
18
+ import { errorMessage, ValidationError, ConcurrencyError, GistConcurrencyError, StateLockTimeoutError, ConfigurationError, } from '../core/errors.js';
19
19
  import { warn } from '../core/logger.js';
20
20
  import { validateUrl, validateGitHubUrl, PR_URL_PATTERN, ISSUE_URL_PATTERN } from './validation.js';
21
21
  import { fetchDashboardData } from './dashboard-data.js';
22
22
  import { openInBrowser } from './startup.js';
23
- import { writeDashboardServerInfo, removeDashboardServerInfo } from './dashboard-process.js';
23
+ import { writeDashboardServerInfo, removeOwnDashboardServerInfo } from './dashboard-process.js';
24
24
  import { RateLimiter } from './rate-limiter.js';
25
25
  import { GistSyncCoordinator } from './dashboard-gist-sync.js';
26
- import { DashboardCache, getIssueListMtimeMs } from './dashboard-cache.js';
26
+ import { DashboardCache, clearForeignVerdicts, getIssueListMtimeMs } from './dashboard-cache.js';
27
27
  // Re-export the payload builder for backward compatibility — it moved to
28
28
  // dashboard-cache.ts with the cache extraction (#1457) but is unit-tested
29
29
  // (and consumed) under this module's name.
@@ -174,8 +174,33 @@ function sanitizeHeaderValue(value) {
174
174
  * save. See state-concurrency.test.ts (#1378) and errors.ts.
175
175
  */
176
176
  function isConcurrencyConflict(error) {
177
+ if (error instanceof StateLockTimeoutError)
178
+ return false; // a reload cannot help: see didSendStateError
177
179
  return error instanceof ConcurrencyError || error instanceof GistConcurrencyError;
178
180
  }
181
+ /**
182
+ * Answer a state error whose message the user has to see (#1951), and report
183
+ * whether it did. Neither is retried by the page (it retries 409 only), and
184
+ * each message says what to do:
185
+ * - a state-lock timeout (423): the lock is held by another process, so a
186
+ * reload-and-retry cannot help and only blocks the event loop again;
187
+ * - a ConfigurationError (500), e.g. state written by a newer release: a
188
+ * generic "Internal server error" would leave the real message in the
189
+ * detached server's log.
190
+ */
191
+ function didSendStateError(res, error) {
192
+ if (res.headersSent)
193
+ return false;
194
+ if (error instanceof StateLockTimeoutError) {
195
+ sendJson(res, 423, { error: error.message, code: 'STATE_LOCKED', retryable: false });
196
+ return true;
197
+ }
198
+ if (error instanceof ConfigurationError) {
199
+ sendJson(res, 500, { error: error.message, code: error.code, retryable: false });
200
+ return true;
201
+ }
202
+ return false;
203
+ }
179
204
  /**
180
205
  * Send the machine-readable 409 for a concurrency conflict (#1397).
181
206
  * `retryable: true` tells the SPA it can re-prime via GET /api/data and
@@ -239,6 +264,14 @@ export async function startDashboardServer(options) {
239
264
  return;
240
265
  }
241
266
  // ── API routes ─────────────────────────────────────────────────────
267
+ // Liveness probe for isDashboardServerRunning (#1927). Deliberately
268
+ // outside the rate limiters and free of state reloads so a busy or
269
+ // throttled server still answers. The pid lets the prober tell this
270
+ // server from another program listening on the same port.
271
+ if (url === '/api/health' && method === 'GET') {
272
+ sendJson(res, 200, { ok: true, pid: process.pid });
273
+ return;
274
+ }
242
275
  if (url === '/api/data' && method === 'GET') {
243
276
  const check = dataLimiter.check();
244
277
  if (!check.allowed) {
@@ -262,6 +295,8 @@ export async function startDashboardServer(options) {
262
295
  const currentIssueListMtimeMs = getIssueListMtimeMs();
263
296
  const issueListChanged = currentIssueListMtimeMs !== cache.issueListMtimeMs;
264
297
  if (stateChanged || issueListChanged) {
298
+ // Re-check the list's checkout on the same events that rebuild (#2012).
299
+ clearForeignVerdicts();
265
300
  try {
266
301
  cache.rebuild(gistSync.stateManager.getState(), undefined, undefined, currentIssueListMtimeMs);
267
302
  }
@@ -327,6 +362,8 @@ export async function startDashboardServer(options) {
327
362
  }
328
363
  catch (error) {
329
364
  warn(MODULE, `Unhandled request error: ${method} ${url} ${errorMessage(error)}`);
365
+ if (didSendStateError(res, error))
366
+ return;
330
367
  if (!res.headersSent) {
331
368
  sendError(res, 500, 'Internal server error');
332
369
  }
@@ -486,6 +523,8 @@ export async function startDashboardServer(options) {
486
523
  await sm.runMutation(async () => applyMutation());
487
524
  }
488
525
  catch (error) {
526
+ if (didSendStateError(res, error))
527
+ return;
489
528
  if (!isConcurrencyConflict(error)) {
490
529
  warn(MODULE, `Action failed: ${body.action} ${body.url} ${errorMessage(error)}`);
491
530
  sendError(res, 500, 'Action failed');
@@ -507,6 +546,8 @@ export async function startDashboardServer(options) {
507
546
  await sm.runMutation(async () => applyMutation());
508
547
  }
509
548
  catch (retryError) {
549
+ if (didSendStateError(res, retryError))
550
+ return;
510
551
  if (isConcurrencyConflict(retryError)) {
511
552
  warn(MODULE, `Action conflicted twice: ${body.action} ${body.url} ${errorMessage(retryError)}`);
512
553
  sendConflict(res);
@@ -538,31 +579,54 @@ export async function startDashboardServer(options) {
538
579
  sendJson(res, 200, cache.jsonData);
539
580
  }
540
581
  // ── POST /api/refresh handler ────────────────────────────────────────────
541
- async function handleRefresh(_req, res) {
582
+ async function refreshFromGitHub(currentToken) {
583
+ // Clear PRE-EXISTING loss notices before the reload: by now they have
584
+ // been visible across the degraded window. Order matters — this
585
+ // refresh's own reloadState may RECOVER and produce a fresh notice,
586
+ // which must survive into the rebuild below, not be wiped 10 lines
587
+ // after its creation (#1433 pass-2).
588
+ gistSync.clearRecoveryLossNotices();
589
+ await reloadState();
590
+ warn(MODULE, 'Refreshing dashboard data from GitHub...');
591
+ const result = await fetchDashboardData(currentToken);
592
+ cache.adoptFetchResult(result);
593
+ cache.rebuild(gistSync.stateManager.getState(), result.allMergedPRs, result.allClosedPRs);
594
+ // This refresh just fetched GitHub successfully, so a prior
595
+ // background-refresh failure is no longer current (#1487) — clear it as
596
+ // the background success path does.
597
+ cache.lastBackgroundRefreshError = null;
598
+ }
599
+ /** Run a refresh nobody awaits; a failure surfaces as staleness on /api/data (#1205). */
600
+ async function refreshInBackground(currentToken) {
601
+ try {
602
+ await refreshFromGitHub(currentToken);
603
+ }
604
+ catch (error) {
605
+ cache.lastBackgroundRefreshError = errorMessage(error);
606
+ warn(MODULE, `Background data refresh failed (serving cached data): ${cache.lastBackgroundRefreshError}`);
607
+ }
608
+ }
609
+ async function handleRefresh(req, res) {
542
610
  const currentToken = token || getGitHubToken();
543
611
  if (!currentToken) {
544
612
  sendError(res, 401, 'No GitHub token available. Cannot refresh data.');
545
613
  return;
546
614
  }
615
+ // A caller that does not consume the payload (startup's refresh trigger)
616
+ // asks for `Prefer: respond-async` and gets a 202 at once: the refresh is
617
+ // a full GitHub fetch that outlives any sensible client timeout (#1927).
618
+ // The SPA omits the header because it renders the response body.
619
+ if (req.headers['prefer'] === 'respond-async') {
620
+ void refreshInBackground(currentToken);
621
+ sendJson(res, 202, { refreshing: true });
622
+ return;
623
+ }
547
624
  try {
548
- // Clear PRE-EXISTING loss notices before the reload: by now they have
549
- // been visible across the degraded window. Order matters — this
550
- // refresh's own reloadState may RECOVER and produce a fresh notice,
551
- // which must survive into the rebuild below, not be wiped 10 lines
552
- // after its creation (#1433 pass-2).
553
- gistSync.clearRecoveryLossNotices();
554
- await reloadState();
555
- warn(MODULE, 'Refreshing dashboard data from GitHub...');
556
- const result = await fetchDashboardData(currentToken);
557
- cache.adoptFetchResult(result);
558
- cache.rebuild(gistSync.stateManager.getState(), result.allMergedPRs, result.allClosedPRs);
559
- // This manual refresh just fetched GitHub successfully, so a prior
560
- // background-refresh failure is no longer current (#1487) — clear it as
561
- // the background success path does, then emit the staleness headers. A
562
- // gist-divergence marker that survived a failed pull inside reloadState
563
- // still surfaces via getStateStaleness, so the SPA stays honest even
564
- // when the GitHub fetch succeeds but the gist remains unreachable.
565
- cache.lastBackgroundRefreshError = null;
625
+ await refreshFromGitHub(currentToken);
626
+ // Emit the staleness headers: a gist-divergence marker that survived a
627
+ // failed pull inside reloadState still surfaces via getStateStaleness,
628
+ // so the SPA stays honest even when the GitHub fetch succeeds but the
629
+ // gist remains unreachable.
566
630
  applyStalenessHeaders(res);
567
631
  sendJson(res, 200, cache.jsonData);
568
632
  }
@@ -570,6 +634,8 @@ export async function startDashboardServer(options) {
570
634
  // No server-side retry here (unlike handleAction): a refresh re-run is a
571
635
  // full GitHub fetch — expensive and rate-limited. The 409 is retryable
572
636
  // by the client, which re-POSTs /api/refresh on its own schedule (#1397).
637
+ if (didSendStateError(res, error))
638
+ return;
573
639
  if (isConcurrencyConflict(error)) {
574
640
  warn(MODULE, `Dashboard refresh hit a concurrent state write: ${errorMessage(error)}`);
575
641
  sendConflict(res);
@@ -733,7 +799,7 @@ export async function startDashboardServer(options) {
733
799
  // ── Clean shutdown ───────────────────────────────────────────────────────
734
800
  const shutdown = () => {
735
801
  warn(MODULE, 'Shutting down dashboard server...');
736
- removeDashboardServerInfo();
802
+ removeOwnDashboardServerInfo();
737
803
  server.close(() => {
738
804
  process.exit(0);
739
805
  });
@@ -7,6 +7,7 @@ import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
8
  import { detectFormatters, diagnoseCIFormatterFailure } from '../core/formatter-detection.js';
9
9
  import { errorMessage } from '../core/errors.js';
10
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
10
11
  export async function runDetectFormatters(options) {
11
12
  const repoPath = path.resolve(options.repoPath ?? process.cwd());
12
13
  const output = { ...detectFormatters(repoPath) };
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { getStateManager, maybeCheckpoint } from '../core/index.js';
22
22
  import { ValidationError } from '../core/errors.js';
23
+ import { findRefKey, issueRefKey } from '../core/urls.js';
23
24
  import { ISSUE_OR_PR_URL_PATTERN, PR_URL_PATTERN, validateCommitSha, validateGitHubUrl, validateUrl, } from './validation.js';
24
25
  const MODULE = 'dismiss';
25
26
  /**
@@ -29,14 +30,15 @@ const MODULE = 'dismiss';
29
30
  * when the PR is shelved: `daily` keeps shelved PRs in `openPRs` but out of
30
31
  * Needs Attention, and `move <pr-url> waiting` would unshelve one.
31
32
  *
32
- * URL validation accepts any owner/repo casing while `openPRs` holds GitHub's,
33
- * so the match is case-insensitive and the suggested `move` command uses the
34
- * stored URL, which is the one `daily` checks against the shelf.
33
+ * URL validation accepts any owner/repo casing, and the `/issues/N` form of a
34
+ * PR already dismissed as `/pull/N`, while `openPRs` holds GitHub's URL, so
35
+ * the match is by {@link issueRefKey} and the suggested `move` command uses
36
+ * the stored URL, which is the one `daily` checks against the shelf.
35
37
  */
36
38
  function openPRDismissWarning(stateManager, url) {
37
39
  const openPRs = stateManager.getState().lastDigest?.openPRs ?? [];
38
- const wanted = url.toLowerCase();
39
- const openPR = openPRs.find((pr) => pr.url.toLowerCase() === wanted);
40
+ const wanted = issueRefKey(url);
41
+ const openPR = wanted === null ? undefined : openPRs.find((pr) => issueRefKey(pr.url) === wanted);
40
42
  if (!openPR || stateManager.isPRShelved(openPR.url))
41
43
  return undefined;
42
44
  return (`${openPR.url} is one of your open PRs. dismiss records it but does not clear the PR from Needs Attention; ` +
@@ -66,11 +68,13 @@ function openPRDismissWarning(stateManager, url) {
66
68
  export async function runDismiss(options) {
67
69
  validateUrl(options.url);
68
70
  validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
69
- const isPR = PR_URL_PATTERN.test(options.url);
71
+ const stateManager = getStateManager();
72
+ // The /issues/N form of a PR already dismissed as /pull/N is that PR (#2001).
73
+ const existingKey = findRefKey(stateManager.getState().config?.dismissedIssues, options.url);
74
+ const isPR = PR_URL_PATTERN.test(options.url) || (existingKey !== undefined && PR_URL_PATTERN.test(existingKey));
70
75
  if (!isPR && options.head !== undefined) {
71
76
  throw new ValidationError('--head applies to PR URLs only: a dismissed issue has no head commit');
72
77
  }
73
- const stateManager = getStateManager();
74
78
  const dismissedAt = new Date().toISOString();
75
79
  const dismissOptions = {
76
80
  refresh: isPR,
@@ -44,6 +44,20 @@ export declare function checkStateFile(options?: {
44
44
  * stub without mocking the module registry.
45
45
  */
46
46
  export type ScoutImporter = () => Promise<unknown>;
47
- export declare function checkScoutResolvable(importer?: ScoutImporter): Promise<DoctorCheck>;
47
+ export declare function checkScoutResolvable(importer?: ScoutImporter, options?: {
48
+ sourceCheckout?: boolean;
49
+ }): Promise<DoctorCheck>;
48
50
  export declare function checkGitHubRateLimit(preloadedToken?: string | null): Promise<DoctorCheck>;
51
+ /**
52
+ * Stale data under the data directory (#1956): counts only, from the file
53
+ * system; no Git runs here. Which worktrees are safe to remove, and why the
54
+ * others are kept, is what `cleanup` reports.
55
+ */
56
+ export declare function checkStaleData(dataDir?: string): DoctorCheck;
57
+ /**
58
+ * The overnight launchd job carries the tool rules and environment of the
59
+ * version that installed it (#1937): an upgrade that tightens them changes
60
+ * nothing for a schedule already on disk until it is installed again.
61
+ */
62
+ export declare function checkOvernightSchedule(plistPath?: string): DoctorCheck;
49
63
  export declare function runDoctor(): Promise<DoctorOutput>;
@@ -10,12 +10,16 @@
10
10
  * external dependencies in isolation.
11
11
  */
12
12
  import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
13
14
  import * as path from 'node:path';
14
15
  import { execFile } from 'node:child_process';
15
16
  import { promisify } from 'node:util';
16
17
  import { getGitHubTokenAsync, getOctokit, getStatePath } from '../core/index.js';
17
18
  import { AgentStateSchema } from '../core/state-schema.js';
18
19
  import { errorMessage } from '../core/errors.js';
20
+ import { resolveDataDir } from '../core/paths.js';
21
+ import { countStaleData } from '../core/stale-data.js';
22
+ import { LAUNCHD_LABEL, isScheduleCurrent } from './overnight.js';
19
23
  const execFileAsync = promisify(execFile);
20
24
  const GH_CMD_TIMEOUT_MS = 3000;
21
25
  // ── Individual checks ───────────────────────────────────────────────────
@@ -122,6 +126,13 @@ function resolveBundlePaths() {
122
126
  const sourcePath = fs.existsSync(devSource) ? devSource : fs.existsSync(coDirSource) ? coDirSource : devSource;
123
127
  return { bundlePath, sourcePath };
124
128
  }
129
+ /**
130
+ * Remediation text depends on the install layout. A source checkout (cli.ts
131
+ * present) rebuilds from pnpm-lock.yaml only (#1935). A prebuilt install (the
132
+ * plugin's marketplace tree, or the npm package) has nothing to build from.
133
+ */
134
+ const SOURCE_CHECKOUT_REBUILD = 'From the repo root run `pnpm install --frozen-lockfile --ignore-scripts && pnpm --filter @oss-autopilot/core run bundle`';
135
+ const PREBUILT_REINSTALL = 'Update or reinstall the oss-autopilot plugin (or the @oss-autopilot/core package)';
125
136
  /**
126
137
  * Try `fs.statSync`; if the file is merely missing (ENOENT), return null.
127
138
  * For other fs errors (EACCES, ELOOP, ENOTDIR, …) surface the error so the
@@ -164,7 +175,7 @@ export function checkBundleUpToDate(options) {
164
175
  name: 'CLI bundle',
165
176
  status: 'warning',
166
177
  message: 'Neither cli.ts nor cli.bundle.cjs could be located',
167
- remediation: 'Reinstall the package or check your install location',
178
+ remediation: `${PREBUILT_REINSTALL}, or check your install location`,
168
179
  };
169
180
  }
170
181
  if (!bundleStat) {
@@ -172,7 +183,7 @@ export function checkBundleUpToDate(options) {
172
183
  name: 'CLI bundle',
173
184
  status: 'warning',
174
185
  message: 'dist/cli.bundle.cjs not built yet',
175
- remediation: 'Run `pnpm run bundle` to build the CLI bundle',
186
+ remediation: SOURCE_CHECKOUT_REBUILD,
176
187
  };
177
188
  }
178
189
  if (sourceStat && sourceStat.mtimeMs > bundleStat.mtimeMs) {
@@ -180,7 +191,7 @@ export function checkBundleUpToDate(options) {
180
191
  name: 'CLI bundle',
181
192
  status: 'warning',
182
193
  message: 'Source files are newer than dist/cli.bundle.cjs',
183
- remediation: 'Run `pnpm run bundle` to rebuild',
194
+ remediation: SOURCE_CHECKOUT_REBUILD,
184
195
  };
185
196
  }
186
197
  return { name: 'CLI bundle', status: 'ok', message: 'Bundle present and up-to-date' };
@@ -223,7 +234,7 @@ export function checkStateFile(options) {
223
234
  }
224
235
  }
225
236
  const defaultScoutImporter = () => import('@oss-scout/core');
226
- export async function checkScoutResolvable(importer = defaultScoutImporter) {
237
+ export async function checkScoutResolvable(importer = defaultScoutImporter, options) {
227
238
  // The scout package is ESM-exports-only, so `require.resolve` fails even
228
239
  // when it's installed. `import()` goes through the ESM resolver, which
229
240
  // honors `exports` maps correctly. Dynamic import only loads the package
@@ -245,6 +256,10 @@ export async function checkScoutResolvable(importer = defaultScoutImporter) {
245
256
  code === 'ERR_INVALID_PACKAGE_CONFIG' ||
246
257
  err instanceof SyntaxError;
247
258
  const reinstallRequired = isNotFound || isCorruptInstall;
259
+ const isSourceCheckout = options?.sourceCheckout ?? fs.existsSync(resolveBundlePaths().sourcePath);
260
+ const reinstallHint = isSourceCheckout
261
+ ? 'Reinstall dependencies from the lockfile: `pnpm install --frozen-lockfile`'
262
+ : PREBUILT_REINSTALL;
248
263
  return {
249
264
  name: '@oss-scout/core resolvable',
250
265
  status: 'error',
@@ -252,7 +267,7 @@ export async function checkScoutResolvable(importer = defaultScoutImporter) {
252
267
  ? `@oss-scout/core cannot be loaded (install issue): ${errorMessage(err)}`
253
268
  : `@oss-scout/core failed to load: ${errorMessage(err)}`,
254
269
  remediation: reinstallRequired
255
- ? 'Reinstall dependencies (`pnpm install` or `npm install`)'
270
+ ? reinstallHint
256
271
  : 'Scout loaded but threw during initialization — report this as a bug in oss-scout with the error above',
257
272
  };
258
273
  }
@@ -294,6 +309,50 @@ export async function checkGitHubRateLimit(preloadedToken) {
294
309
  };
295
310
  }
296
311
  }
312
+ /**
313
+ * Stale data under the data directory (#1956): counts only, from the file
314
+ * system; no Git runs here. Which worktrees are safe to remove, and why the
315
+ * others are kept, is what `cleanup` reports.
316
+ */
317
+ export function checkStaleData(dataDir = resolveDataDir()) {
318
+ const name = 'Stale data';
319
+ let counts;
320
+ try {
321
+ counts = countStaleData(dataDir);
322
+ }
323
+ catch (err) {
324
+ return { name, status: 'warning', message: `Could not read ${dataDir}: ${errorMessage(err)}` };
325
+ }
326
+ const message = `${counts.worktrees} overnight worktree(s); ${counts.rejected} rejected state copy(ies) past retention`;
327
+ if (counts.rejected === 0)
328
+ return { name, message, status: 'ok' };
329
+ return {
330
+ name,
331
+ message,
332
+ status: 'warning',
333
+ remediation: 'They are pruned at the next overnight run; `oss-autopilot cleanup` (a dry run) lists them and the worktrees',
334
+ };
335
+ }
336
+ /**
337
+ * The overnight launchd job carries the tool rules and environment of the
338
+ * version that installed it (#1937): an upgrade that tightens them changes
339
+ * nothing for a schedule already on disk until it is installed again.
340
+ */
341
+ export function checkOvernightSchedule(plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)) {
342
+ const name = 'Overnight schedule';
343
+ if (!fs.existsSync(plistPath)) {
344
+ return { name, status: 'ok', message: 'No launchd schedule found (systemd and cron jobs are not checked)' };
345
+ }
346
+ if (isScheduleCurrent(fs.readFileSync(plistPath, 'utf8'))) {
347
+ return { name, status: 'ok', message: 'Installed schedule matches this version' };
348
+ }
349
+ return {
350
+ name,
351
+ status: 'warning',
352
+ message: `${plistPath} was written by another version: its permission flags, tool rules or environment differ from the current ones`,
353
+ remediation: 'Run `overnight schedule --install --hour <hour> --claude-path "$(command -v claude)"` again, then the launchctl command it prints',
354
+ };
355
+ }
297
356
  // ── Orchestrator ────────────────────────────────────────────────────────
298
357
  /**
299
358
  * Run all diagnostic checks and return a structured report.
@@ -348,6 +407,8 @@ export async function runDoctor() {
348
407
  runCheckSafely('@oss-scout/core resolvable', () => checkScoutResolvable()),
349
408
  runCheckSafely('CLI bundle', () => checkBundleUpToDate()),
350
409
  runCheckSafely('state.json valid', () => checkStateFile()),
410
+ runCheckSafely('Stale data', () => checkStaleData()),
411
+ runCheckSafely('Overnight schedule', () => checkOvernightSchedule()),
351
412
  ]);
352
413
  const summary = {
353
414
  ok: checks.filter((c) => c.status === 'ok').length,