@oss-autopilot/core 3.42.5 → 3.43.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 (168) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/ci-analysis.d.ts +7 -2
  85. package/dist/core/ci-analysis.js +76 -21
  86. package/dist/core/commit-date.d.ts +19 -0
  87. package/dist/core/commit-date.js +17 -0
  88. package/dist/core/config-registry.js +11 -5
  89. package/dist/core/contributing.d.ts +2 -3
  90. package/dist/core/contributing.js +2 -3
  91. package/dist/core/daily-logic.d.ts +27 -5
  92. package/dist/core/daily-logic.js +57 -19
  93. package/dist/core/errors.d.ts +37 -3
  94. package/dist/core/errors.js +54 -5
  95. package/dist/core/gist-health.d.ts +15 -3
  96. package/dist/core/gist-health.js +8 -0
  97. package/dist/core/gist-state-store.d.ts +24 -4
  98. package/dist/core/gist-state-store.js +97 -46
  99. package/dist/core/github-stats.d.ts +104 -16
  100. package/dist/core/github-stats.js +282 -97
  101. package/dist/core/http-cache.d.ts +0 -10
  102. package/dist/core/http-cache.js +0 -19
  103. package/dist/core/index.d.ts +12 -5
  104. package/dist/core/index.js +15 -5
  105. package/dist/core/issue-conversation.d.ts +8 -2
  106. package/dist/core/issue-conversation.js +31 -12
  107. package/dist/core/local-config.d.ts +95 -0
  108. package/dist/core/local-config.js +271 -0
  109. package/dist/core/merged-pr-notes.d.ts +2 -2
  110. package/dist/core/pagination.d.ts +55 -0
  111. package/dist/core/pagination.js +59 -0
  112. package/dist/core/paths.d.ts +7 -0
  113. package/dist/core/paths.js +9 -0
  114. package/dist/core/pr-assembly.js +6 -2
  115. package/dist/core/pr-graphql.d.ts +37 -3
  116. package/dist/core/pr-graphql.js +73 -12
  117. package/dist/core/pr-monitor.d.ts +29 -12
  118. package/dist/core/pr-monitor.js +71 -23
  119. package/dist/core/pr-preflight.d.ts +113 -0
  120. package/dist/core/pr-preflight.js +364 -0
  121. package/dist/core/pr-quality-rubric.d.ts +0 -6
  122. package/dist/core/pr-quality-rubric.js +0 -8
  123. package/dist/core/pr-template.d.ts +2 -0
  124. package/dist/core/pr-template.js +5 -1
  125. package/dist/core/repo-policy.d.ts +105 -0
  126. package/dist/core/repo-policy.js +400 -0
  127. package/dist/core/repo-score-manager.d.ts +48 -0
  128. package/dist/core/repo-score-manager.js +111 -1
  129. package/dist/core/review-analysis.d.ts +34 -19
  130. package/dist/core/review-analysis.js +67 -10
  131. package/dist/core/reviewed-prs-fetch.js +11 -29
  132. package/dist/core/reviewed-prs.js +8 -15
  133. package/dist/core/stale-data.d.ts +41 -0
  134. package/dist/core/stale-data.js +115 -0
  135. package/dist/core/state-persistence.d.ts +62 -27
  136. package/dist/core/state-persistence.js +338 -117
  137. package/dist/core/state-schema.d.ts +113 -210
  138. package/dist/core/state-schema.js +165 -80
  139. package/dist/core/state.d.ts +60 -8
  140. package/dist/core/state.js +192 -46
  141. package/dist/core/status-determination.js +26 -8
  142. package/dist/core/strategy.js +3 -1
  143. package/dist/core/types.d.ts +22 -1
  144. package/dist/core/types.js +1 -0
  145. package/dist/core/untrusted-content.d.ts +30 -11
  146. package/dist/core/untrusted-content.js +77 -42
  147. package/dist/core/urls.d.ts +9 -0
  148. package/dist/core/urls.js +18 -0
  149. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  150. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  151. package/dist/dashboard/index.html +1 -1
  152. package/dist/formatters/json.d.ts +262 -6
  153. package/dist/formatters/json.js +77 -1
  154. package/package.json +1 -1
  155. package/dist/core/ci-enforced-tools.d.ts +0 -35
  156. package/dist/core/ci-enforced-tools.js +0 -109
  157. package/dist/core/comment-decision.d.ts +0 -79
  158. package/dist/core/comment-decision.js +0 -82
  159. package/dist/core/extraction-categories.d.ts +0 -55
  160. package/dist/core/extraction-categories.js +0 -108
  161. package/dist/core/follow-up-history.d.ts +0 -40
  162. package/dist/core/follow-up-history.js +0 -71
  163. package/dist/core/issue-effort.d.ts +0 -29
  164. package/dist/core/issue-effort.js +0 -47
  165. package/dist/core/maintainer-hints.d.ts +0 -23
  166. package/dist/core/maintainer-hints.js +0 -36
  167. package/dist/core/workflow-state.d.ts +0 -56
  168. package/dist/core/workflow-state.js +0 -101
@@ -4,82 +4,219 @@
4
4
  * No module-level mutable state — functions accept/return AgentState objects.
5
5
  */
6
6
  import * as fs from 'node:fs';
7
+ import { randomUUID } from 'node:crypto';
7
8
  import * as path from 'node:path';
8
9
  import { AgentStateSchema, NEWER_WRITER_HINT, malformedWorkClaimCount, unknownStateKeys } from './state-schema.js';
9
10
  import { serializeState } from './state-prune.js';
10
11
  import { getStatePath, getBackupDir, getDataDir, getLegacyStatePath, getLegacyBackupDir } from './paths.js';
11
- import { errorMessage, ConcurrencyError } from './errors.js';
12
+ import { pruneRejectedCopies } from './stale-data.js';
13
+ import { errorMessage, ConcurrencyError, NewerStateVersionError, StateLockTimeoutError } from './errors.js';
12
14
  import { debug, warn } from './logger.js';
13
15
  const MODULE = 'state';
14
- // Lock file timeout: if a lock is older than this, it is considered stale
15
- const LOCK_TIMEOUT_MS = 30_000; // 30 seconds
16
+ // A lock whose owner is gone is stale once it is older than this. The locked
17
+ // section is a synchronous copy + write + rename (milliseconds), so 30 seconds
18
+ // is far past any real write.
19
+ const LOCK_TIMEOUT_MS = 30_000;
20
+ // A lock whose PID is still alive on this host is only taken after this long:
21
+ // the owner is most likely an unrelated process that reused the PID of a
22
+ // crashed writer, and a live writer that is merely slow must keep its lock.
23
+ const LIVE_LOCK_TIMEOUT_MS = 10 * 60_000;
24
+ // Contention: poll every 25 ms for about one second, then fail (#1951).
25
+ const LOCK_RETRY_INTERVAL_MS = 25;
26
+ const LOCK_RETRY_ATTEMPTS = 40;
27
+ /** Block this thread for `ms`. saveState is synchronous, so the wait has to be too. */
28
+ function sleepSync(ms) {
29
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
30
+ }
31
+ function errnoCode(err) {
32
+ return err?.code;
33
+ }
16
34
  /**
17
- * Check whether an existing lock file is stale (expired or corrupt).
18
- * Returns true if the lock should be considered stale and can be removed.
35
+ * The lock file's content, or null when there is no lock file. Any other read
36
+ * failure is rethrown: an fd or permission problem is not "locked".
19
37
  */
20
- function isLockStale(lockPath) {
38
+ function readLockFile(lockPath) {
21
39
  try {
22
- const existing = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
23
- return Date.now() - existing.timestamp > LOCK_TIMEOUT_MS;
40
+ return fs.readFileSync(lockPath, 'utf8');
24
41
  }
25
42
  catch (err) {
26
- // Lock file is unreadable or contains invalid JSON — treat as stale
27
- debug(MODULE, 'Lock file unreadable or invalid JSON, treating as stale', err);
43
+ if (errnoCode(err) !== 'ENOENT')
44
+ throw err;
45
+ return null;
46
+ }
47
+ }
48
+ function isPidAlive(pid) {
49
+ if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0)
50
+ return false;
51
+ try {
52
+ process.kill(pid, 0);
28
53
  return true;
29
54
  }
55
+ catch (err) {
56
+ // EPERM: the process exists but belongs to another user.
57
+ return errnoCode(err) === 'EPERM';
58
+ }
59
+ }
60
+ function parseLock(content) {
61
+ let parsed = null;
62
+ try {
63
+ parsed = JSON.parse(content);
64
+ }
65
+ catch (err) {
66
+ debug(MODULE, 'Lock file is not valid JSON', err);
67
+ }
68
+ return parsed ?? {};
69
+ }
70
+ /** The lock file's mtime, or a time that can never look stale when it cannot be read. */
71
+ function lockMtimeMs(lockPath) {
72
+ try {
73
+ return fs.statSync(lockPath).mtimeMs;
74
+ }
75
+ catch (err) {
76
+ debug(MODULE, 'Lock file disappeared while checking staleness', err);
77
+ return Infinity;
78
+ }
30
79
  }
31
80
  /**
32
- * Acquire an advisory file lock using exclusive-create (`wx` flag).
33
- * If the lock file already exists but is stale (older than LOCK_TIMEOUT_MS or corrupt),
34
- * it is removed and re-acquired.
35
- * @throws Error if the lock is held by another active process.
81
+ * Return the lock's content when it is stale, or null when it must be
82
+ * respected (or is already gone). Age is counted from the earlier of the
83
+ * lock's timestamp and the file mtime, so a lock without a usable timestamp
84
+ * (empty while its owner is still writing it, or corrupt) is aged by mtime
85
+ * instead of being stale on sight, and a timestamp in the future cannot make
86
+ * a lock immortal.
36
87
  */
37
- export function acquireLock(lockPath) {
38
- const lockData = JSON.stringify({ pid: process.pid, timestamp: Date.now() });
88
+ function readStaleLock(lockPath) {
89
+ const content = readLockFile(lockPath);
90
+ if (content === null)
91
+ return null;
92
+ const lock = parseLock(content);
93
+ // Saving is synchronous, so a process that is acquiring is not inside the
94
+ // locked section: a lock with its own PID is a leftover, stale now.
95
+ // ponytail: assumes one PID namespace and one writer thread per process.
96
+ // Containers sharing the data directory with colliding PIDs rely on the
97
+ // commit-point check in saveState; add a host/boot id to the lock if that
98
+ // setup becomes real.
99
+ if (lock.pid === process.pid)
100
+ return content;
101
+ const stamped = typeof lock.timestamp === 'number' ? lock.timestamp : Infinity;
102
+ const since = Math.min(stamped, lockMtimeMs(lockPath));
103
+ const limit = isPidAlive(lock.pid) ? LIVE_LOCK_TIMEOUT_MS : LOCK_TIMEOUT_MS;
104
+ return Date.now() - since > limit ? content : null;
105
+ }
106
+ /** Link a wrongly claimed lock back into place; `linkSync` fails rather than overwrite a newer lock. */
107
+ function putBackLock(claimed, lockPath) {
39
108
  try {
40
- fs.writeFileSync(lockPath, lockData, { flag: 'wx' }); // Fails if file exists
41
- return;
109
+ fs.linkSync(claimed, lockPath);
42
110
  }
43
111
  catch (err) {
44
- // Lock file exists (EEXIST from 'wx' flag) — check if it is stale
45
- debug(MODULE, 'Lock file already exists, checking staleness', err);
112
+ warn(MODULE, `Could not put back a live state lock: ${errorMessage(err)}`);
46
113
  }
47
- if (!isLockStale(lockPath)) {
48
- throw new Error('State file is locked by another process');
114
+ }
115
+ /** True when the claimed file is the lock that was judged stale. Unreadable counts as not: it is put back. */
116
+ function isJudgedLock(claimed, staleContent) {
117
+ try {
118
+ return fs.readFileSync(claimed, 'utf8') === staleContent;
49
119
  }
50
- // Stale lock detected — remove it and try to re-acquire
120
+ catch (err) {
121
+ warn(MODULE, `Could not read a claimed state lock: ${errorMessage(err)}`);
122
+ return false;
123
+ }
124
+ }
125
+ /**
126
+ * Remove a lock judged stale without ever removing a fresh one. The rename
127
+ * is the atomic claim: of several processes that judged the same lock stale,
128
+ * one gets the file and the rest fail with ENOENT. If the claimed file is not
129
+ * the lock that was judged (another process finished its own takeover in
130
+ * between), it is put back.
131
+ */
132
+ function removeStaleLock(lockPath, staleContent) {
133
+ const claimed = `${lockPath}.stale-${process.pid}-${randomUUID()}`;
51
134
  try {
52
- fs.unlinkSync(lockPath);
135
+ fs.renameSync(lockPath, claimed);
53
136
  }
54
137
  catch (err) {
55
- // Another process may have removed the stale lock first — proceed to re-acquire regardless
56
- debug(MODULE, 'Stale lock already removed by another process', err);
138
+ debug(MODULE, 'Stale lock already claimed or released by another process', err);
139
+ return;
57
140
  }
141
+ if (!isJudgedLock(claimed, staleContent))
142
+ putBackLock(claimed, lockPath);
143
+ fs.rmSync(claimed, { force: true });
144
+ }
145
+ /** Exclusive-create the lock file. False when one already exists; any other failure is rethrown. */
146
+ function didCreateLock(lockPath, lockData) {
58
147
  try {
59
- fs.writeFileSync(lockPath, lockData, { flag: 'wx' });
148
+ fs.writeFileSync(lockPath, lockData, { flag: 'wx' }); // Fails if file exists
149
+ return true;
60
150
  }
61
151
  catch (err) {
62
- // Another process grabbed the lock between unlink and write
63
- debug(MODULE, 'Lock re-acquire failed (race condition)', err);
64
- throw new Error('State file is locked by another process', { cause: err });
152
+ if (errnoCode(err) !== 'EEXIST')
153
+ throw err;
154
+ return false;
65
155
  }
66
156
  }
67
157
  /**
68
- * Release an advisory file lock, but only if this process owns it.
69
- * Silently ignores missing lock files or locks owned by other processes.
158
+ * Exclusive-create the lock, then re-read it: this process holds the lock
159
+ * only if the file on disk is the one it wrote. If the re-read fails, a lock
160
+ * this call created is removed again so it is not left orphaned.
70
161
  */
71
- export function releaseLock(lockPath) {
162
+ function didTakeLock(lockPath, lockData) {
163
+ const didCreate = didCreateLock(lockPath, lockData);
72
164
  try {
73
- const data = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
74
- if (data.pid === process.pid) {
75
- fs.unlinkSync(lockPath);
165
+ return readLockFile(lockPath) === lockData;
166
+ }
167
+ catch (err) {
168
+ if (didCreate)
169
+ fs.rmSync(lockPath, { force: true });
170
+ throw err;
171
+ }
172
+ }
173
+ /**
174
+ * Acquire an advisory file lock using exclusive-create (`wx` flag).
175
+ * A held lock is retried for about a second; a stale one (see
176
+ * {@link readStaleLock}) is taken over through an atomic rename.
177
+ * @returns The lock content written, for {@link releaseLock} and for
178
+ * re-checking ownership before the write the lock protects.
179
+ * @throws StateLockTimeoutError (a ConcurrencyError) if the lock is still
180
+ * held after the wait. Nothing has been written at that point.
181
+ */
182
+ export function acquireLock(lockPath) {
183
+ const startedAt = Date.now();
184
+ const lockData = JSON.stringify({ pid: process.pid, timestamp: startedAt, token: randomUUID() });
185
+ for (let attempt = 0; attempt <= LOCK_RETRY_ATTEMPTS; attempt++) {
186
+ if (attempt > 0)
187
+ sleepSync(LOCK_RETRY_INTERVAL_MS);
188
+ if (didTakeLock(lockPath, lockData))
189
+ return lockData;
190
+ const staleContent = readStaleLock(lockPath);
191
+ if (staleContent !== null) {
192
+ removeStaleLock(lockPath, staleContent);
193
+ if (didTakeLock(lockPath, lockData))
194
+ return lockData;
76
195
  }
77
196
  }
197
+ throw new StateLockTimeoutError(lockPath, Date.now() - startedAt);
198
+ }
199
+ /**
200
+ * Release an advisory file lock, but only if it still holds `held`, the
201
+ * content {@link acquireLock} returned. A missing lock is ignored; any other
202
+ * failure is warned about, never thrown (this runs in a `finally`).
203
+ */
204
+ export function releaseLock(lockPath, held) {
205
+ try {
206
+ if (readLockFile(lockPath) === held)
207
+ fs.unlinkSync(lockPath);
208
+ }
78
209
  catch (err) {
79
- // Lock already removed or unreadable — nothing to do
80
- debug(MODULE, 'Lock file already removed or unreadable during release', err);
210
+ if (errnoCode(err) !== 'ENOENT')
211
+ warn(MODULE, `Could not release the state lock ${lockPath}: ${errorMessage(err)}`);
81
212
  }
82
213
  }
214
+ /** Throw unless the lock file still holds what {@link acquireLock} wrote (it was taken over meanwhile). */
215
+ function assertLockHeld(lockPath, held) {
216
+ if (readLockFile(lockPath) === held)
217
+ return;
218
+ throw new ConcurrencyError(0, 0, 'The state lock was taken over by another process before the write. Nothing was written; re-run the command.');
219
+ }
83
220
  /**
84
221
  * Write data to `filePath` atomically by first writing to a temporary file
85
222
  * in the same directory and then renaming. Rename is atomic on POSIX filesystems,
@@ -321,6 +458,15 @@ function tryRestoreFromBackup() {
321
458
  }
322
459
  return null;
323
460
  }
461
+ /** A stat that failed. NaN never compares equal, so it always reads as "changed". */
462
+ const UNKNOWN_FILE_IDENTITY = { mtimeMs: NaN, ino: '', size: NaN };
463
+ function statIdentitySync(filePath) {
464
+ const stats = fs.statSync(filePath, { bigint: true });
465
+ return { mtimeMs: Number(stats.mtimeNs) / 1e6, ino: stats.ino.toString(), size: Number(stats.size) };
466
+ }
467
+ function isSameIdentity(a, b) {
468
+ return a.mtimeMs === b.mtimeMs && a.ino === b.ino && a.size === b.size;
469
+ }
324
470
  /**
325
471
  * Copy a rejected state file to `<statePath>.rejected-<timestamp>` so the
326
472
  * user can recover data manually before the file is overwritten by a backup
@@ -332,6 +478,7 @@ function preserveRejectedStateFile(statePath) {
332
478
  const rejectedPath = statePath + '.rejected-' + Date.now();
333
479
  fs.copyFileSync(statePath, rejectedPath);
334
480
  warn(MODULE, `Previous state preserved at: ${rejectedPath}`);
481
+ pruneRejectedCopies(path.dirname(rejectedPath));
335
482
  return rejectedPath;
336
483
  }
337
484
  catch (preserveErr) {
@@ -351,31 +498,91 @@ export function warnMalformedWorkClaims(raw, state, source) {
351
498
  if (malformed > 0)
352
499
  warn(MODULE, `${source} has ${malformed} unreadable work claim(s); they were dropped`);
353
500
  }
501
+ /**
502
+ * Refuse stored state whose schema version is above this release's. Treating
503
+ * it as invalid would restore an older backup (or fresh state) over newer
504
+ * data. `source` names the copy in the message.
505
+ */
506
+ export function assertNotNewerVersion(raw, source) {
507
+ const version = raw?.version;
508
+ const supported = AgentStateSchema.shape.version.value;
509
+ if (typeof version === 'number' && version > supported) {
510
+ throw new NewerStateVersionError(source, version, supported);
511
+ }
512
+ }
513
+ /**
514
+ * Refuse to save over a state file a newer release wrote. Runs on every save,
515
+ * whatever the caller's mtime baseline: a process that started before the
516
+ * file existed has no baseline and would otherwise write old state over it.
517
+ * A missing or unparseable file is not this check's concern.
518
+ */
519
+ function assertDiskStateNotNewer(statePath) {
520
+ let raw;
521
+ try {
522
+ raw = JSON.parse(fs.readFileSync(statePath, 'utf8'));
523
+ }
524
+ catch (err) {
525
+ // No file yet, or one that does not parse: nothing to protect. Any other
526
+ // failure is worth a warning, but the save still goes ahead.
527
+ const isExpected = errnoCode(err) === 'ENOENT' || err instanceof SyntaxError;
528
+ if (isExpected)
529
+ debug(MODULE, 'No parseable state file to version-check before save', err);
530
+ else
531
+ warn(MODULE, `Could not version-check the state file before save: ${errorMessage(err)}`);
532
+ return;
533
+ }
534
+ assertNotNewerVersion(raw, 'state file');
535
+ }
536
+ /**
537
+ * Rethrow a load failure that is not corruption, before any file is touched:
538
+ * a newer-version state file, or anything carrying an errno `code`, i.e. a
539
+ * file system error (EACCES, EMFILE, EIO, EISDIR, ENOSPC, ...).
540
+ * Restoring a backup or starting fresh there would mask the real problem and
541
+ * can overwrite a valid state file (#1371, #1951). Only unparseable or
542
+ * structurally broken content returns, to be recovered.
543
+ */
544
+ function rethrowUnlessCorrupt(error) {
545
+ if (error instanceof NewerStateVersionError)
546
+ throw error;
547
+ const code = errnoCode(error);
548
+ if (code === 'EACCES' || code === 'EPERM') {
549
+ throw new Error(`Permission denied reading state file (${code}): ${errorMessage(error)}. ` +
550
+ 'This is an environment problem, not state corruption. Check the ownership and ' +
551
+ 'permissions of ~/.oss-autopilot/state.json (e.g. run `ls -l ~/.oss-autopilot/state.json` ' +
552
+ 'and fix with chown/chmod), then retry.', { cause: error });
553
+ }
554
+ if (typeof code === 'string')
555
+ throw error;
556
+ }
354
557
  /**
355
558
  * Load state from file, or create initial state if none exists.
356
559
  * If the main state file is corrupted, attempts to restore from the most recent backup.
357
560
  * Performs migration from legacy ./data/ location if needed.
358
- * @returns Object with the loaded state, the file's mtime (for change detection),
561
+ * @returns Object with the loaded state, the file's identity (for change detection),
359
562
  * and recovery details when the main file was rejected.
360
- * @throws Error when the state file exists but cannot be read due to a
361
- * permission error (EACCES/EPERM) — that is an environment problem, not
362
- * corruption, so restore-or-fresh would mask it and risk clobbering data.
563
+ * @throws Error when the state file exists but cannot be read due to a file
564
+ * system error (EACCES/EPERM get guidance, others are rethrown as they are)
565
+ * or was written by a newer release. Neither is corruption, so
566
+ * restore-or-fresh would mask it and risk clobbering data. No file is touched.
363
567
  */
364
568
  export function loadState() {
365
569
  // Try to migrate from legacy location first
366
570
  migrateFromLegacyLocation();
367
571
  const statePath = getStatePath();
572
+ // Outside the try so the fresh-state recovery in the catch keeps it (#2006).
573
+ let fileId = null;
368
574
  try {
369
575
  if (fs.existsSync(statePath)) {
370
- // Baseline mtime for saveState's compare-and-swap. Taken BEFORE the read:
576
+ // Baseline identity for saveState's compare-and-swap. Taken BEFORE the read:
371
577
  // if another process writes in between, we end up with a baseline older
372
578
  // than our content, and the next save fails with a ConcurrencyError the
373
579
  // caller can recover from by reloading. Taken after the read, the same
374
- // race pairs stale content with the new mtime and the save silently
580
+ // race pairs stale content with the new identity and the save silently
375
581
  // overwrites the other writer.
376
- let mtimeMs = safeGetMtimeMs(statePath);
582
+ fileId = statFileIdentity(statePath);
377
583
  const data = fs.readFileSync(statePath, 'utf8');
378
584
  let raw = JSON.parse(data);
585
+ assertNotNewerVersion(raw, 'state file');
379
586
  // Chain migrations: v1 → v2 → v3 → v4
380
587
  let wasMigrated = false;
381
588
  if (typeof raw === 'object' && raw !== null) {
@@ -409,17 +616,16 @@ export function loadState() {
409
616
  const reason = `Invalid state file structure: ${summary}`;
410
617
  const restoredState = tryRestoreFromBackup();
411
618
  if (restoredState) {
412
- const mtimeMs = safeGetMtimeMs(statePath);
413
619
  const recovery = { source: 'backup', rejectedPath, reason };
414
- return { state: restoredState, mtimeMs, recovery };
620
+ return { state: restoredState, fileId: statFileIdentity(statePath), recovery };
415
621
  }
416
622
  warn(MODULE, 'No valid backup found, starting fresh');
417
- return { state: createFreshState(), mtimeMs: 0, recovery: { source: 'fresh', rejectedPath, reason } };
623
+ return { fileId, state: createFreshState(), recovery: { source: 'fresh', rejectedPath, reason } };
418
624
  }
419
625
  // Save migrated state only after validation succeeds
420
626
  if (wasMigrated) {
421
627
  atomicWriteFileSync(statePath, serializeState(parsed.data), 0o600);
422
- mtimeMs = safeGetMtimeMs(statePath); // our own write: what we hold is what is on disk
628
+ fileId = statFileIdentity(statePath); // our own write: what we hold is what is on disk
423
629
  debug(MODULE, 'Migrated and validated state saved');
424
630
  }
425
631
  const state = parsed.data;
@@ -431,20 +637,11 @@ export function loadState() {
431
637
  // Log appropriate message based on version
432
638
  const repoCount = Object.keys(state.repoScores).length;
433
639
  debug(MODULE, `Loaded state v${state.version}: ${repoCount} repo scores tracked`);
434
- return { state, mtimeMs };
640
+ return { state, fileId };
435
641
  }
436
642
  }
437
643
  catch (error) {
438
- // Permission errors are environmental, not corruption — restoring a
439
- // backup or starting fresh here would mask the real problem and risk
440
- // clobbering a perfectly valid state file. Rethrow with guidance (#1371).
441
- const code = error?.code;
442
- if (code === 'EACCES' || code === 'EPERM') {
443
- throw new Error(`Permission denied reading state file (${code}): ${errorMessage(error)}. ` +
444
- 'This is an environment problem, not state corruption. Check the ownership and ' +
445
- 'permissions of ~/.oss-autopilot/state.json (e.g. run `ls -l ~/.oss-autopilot/state.json` ' +
446
- 'and fix with chown/chmod), then retry.', { cause: error });
447
- }
644
+ rethrowUnlessCorrupt(error);
448
645
  warn(MODULE, 'Error loading state:', error);
449
646
  warn(MODULE, 'Attempting to restore from backup...');
450
647
  // Preserve the unparseable file before tryRestoreFromBackup() overwrites
@@ -454,26 +651,27 @@ export function loadState() {
454
651
  const reason = `Error loading state: ${errorMessage(error)}`;
455
652
  const restoredState = tryRestoreFromBackup();
456
653
  if (restoredState) {
457
- const mtimeMs = safeGetMtimeMs(statePath);
458
654
  const recovery = { source: 'backup', rejectedPath, reason };
459
- return { state: restoredState, mtimeMs, recovery };
655
+ return { state: restoredState, fileId: statFileIdentity(statePath), recovery };
460
656
  }
461
657
  warn(MODULE, 'No valid backup found, starting fresh');
462
- return { state: createFreshState(), mtimeMs: 0, recovery: { source: 'fresh', rejectedPath, reason } };
658
+ return { fileId, state: createFreshState(), recovery: { source: 'fresh', rejectedPath, reason } };
463
659
  }
464
660
  debug(MODULE, 'No existing state found, initializing...');
465
- return { state: createFreshState(), mtimeMs: 0 };
661
+ return { state: createFreshState(), fileId: null };
466
662
  }
467
663
  /**
468
- * Safely read a file's mtime. Returns 0 if the stat call fails.
664
+ * Read a file's identity. A failed stat returns an identity that matches
665
+ * nothing, so the next save reports a conflict and the next reload re-reads,
666
+ * rather than a 0 that would switch the compare-and-swap off (#2006).
469
667
  */
470
- function safeGetMtimeMs(filePath) {
668
+ function statFileIdentity(filePath) {
471
669
  try {
472
- return fs.statSync(filePath).mtimeMs;
670
+ return statIdentitySync(filePath);
473
671
  }
474
672
  catch (error) {
475
- debug(MODULE, `Could not read state file mtime (reload detection will always trigger): ${errorMessage(error)}`);
476
- return 0;
673
+ debug(MODULE, `Could not stat state file (treating it as changed): ${errorMessage(error)}`);
674
+ return UNKNOWN_FILE_IDENTITY;
477
675
  }
478
676
  }
479
677
  /**
@@ -505,34 +703,35 @@ function cleanupBackups() {
505
703
  * Persist state to disk, creating a timestamped backup of the previous
506
704
  * state file first. Retains at most 10 backup files.
507
705
  *
508
- * When `expectedMtimeMs` is provided (non-null, non-zero), implements
509
- * optimistic compare-and-swap: if the on-disk file has been modified since
510
- * the caller last loaded it, throws `ConcurrencyError` instead of
511
- * overwriting. This prevents the classic read-modify-write lost-update
512
- * race across processes (see issue #1030). Pass `null` / `0` to disable
513
- * the check (first write, or when the caller has already reloaded).
706
+ * When `expected` is provided (non-null), implements optimistic
707
+ * compare-and-swap: if the on-disk file's identity (mtime, inode, size)
708
+ * differs from the one the caller last loaded or saved, throws
709
+ * `ConcurrencyError` instead of overwriting. This prevents the classic
710
+ * read-modify-write lost-update race across processes (see issues #1030,
711
+ * #2006). Pass `null` to disable the check (no file at load).
514
712
  *
515
713
  * The check runs *inside* the advisory lock so the compare-and-swap is
516
714
  * atomic with respect to the write.
517
715
  *
518
- * @returns The file's mtime after writing (for change detection).
519
- * @throws ConcurrencyError when `expectedMtimeMs` is provided and the
520
- * on-disk mtime no longer matches.
716
+ * @returns The file's identity after writing (for change detection).
717
+ * @throws ConcurrencyError when `expected` is provided and the on-disk
718
+ * identity no longer matches, or the file cannot be stat'ed.
521
719
  */
522
- export function saveState(state, expectedMtimeMs = null) {
720
+ export function saveState(state, expected = null) {
523
721
  const statePath = getStatePath();
524
722
  const lockPath = statePath + '.lock';
525
723
  const backupDir = getBackupDir();
526
724
  // Acquire advisory lock to prevent concurrent writes
527
- acquireLock(lockPath);
725
+ const held = acquireLock(lockPath);
528
726
  try {
727
+ assertDiskStateNotNewer(statePath);
529
728
  // Compare-and-swap: reject the write if the file changed externally
530
- // between the caller's last load and now. Zero/null bypasses the
531
- // check for first writes and Gist-mode local-cache paths.
532
- if (expectedMtimeMs !== null && expectedMtimeMs > 0 && fs.existsSync(statePath)) {
533
- const currentMtimeMs = safeGetMtimeMs(statePath);
534
- if (currentMtimeMs !== expectedMtimeMs) {
535
- throw new ConcurrencyError(expectedMtimeMs, currentMtimeMs);
729
+ // between the caller's last load and now. Null bypasses the check:
730
+ // there was no file to take a baseline from.
731
+ if (expected !== null && fs.existsSync(statePath)) {
732
+ const current = statFileIdentity(statePath);
733
+ if (!isSameIdentity(current, expected)) {
734
+ throw new ConcurrencyError(expected.mtimeMs, current.mtimeMs, undefined, expected, current);
536
735
  }
537
736
  }
538
737
  // Create backup of existing state (best-effort, non-fatal)
@@ -551,50 +750,72 @@ export function saveState(state, expectedMtimeMs = null) {
551
750
  warn(MODULE, `Could not create backup before save: ${errorMessage(backupErr)}`);
552
751
  // Continue with save — losing a backup is acceptable, losing the save is not
553
752
  }
554
- // Atomic write: write to temp file then rename to prevent corruption on crash
753
+ // Atomic write: write to temp file then rename to prevent corruption on crash.
754
+ // Ownership is re-checked first: a takeover since acquiring must not end in two writers.
755
+ assertLockHeld(lockPath, held);
555
756
  atomicWriteFileSync(statePath, serializeState(state), 0o600);
556
- const mtimeMs = safeGetMtimeMs(statePath);
757
+ const fileId = statFileIdentity(statePath);
557
758
  debug(MODULE, 'State saved successfully');
558
- return mtimeMs;
759
+ return fileId;
559
760
  }
560
761
  finally {
561
- releaseLock(lockPath);
762
+ releaseLock(lockPath, held);
562
763
  }
563
764
  }
765
+ // Read failures that usually clear on their own: worth one retry before a reload fails its caller.
766
+ const TRANSIENT_READ_CODES = new Set(['EMFILE', 'ENFILE', 'EBUSY', 'EAGAIN']);
564
767
  /**
565
- * Re-read state from disk if the file has been modified since the last load/save.
566
- * Uses mtime comparison (single statSync call) to avoid unnecessary JSON parsing.
567
- * @returns The new state and mtime if reloaded, or null if no change detected.
768
+ * loadState for a reload. A file that vanished since the stat is "no change"
769
+ * (null); a transient resource error is retried once after a short pause.
770
+ * Everything else loadState throws (newer-version state, EACCES, a second
771
+ * failure) propagates: swallowing it would leave a long-lived process on old
772
+ * state that its next save writes over the file (#1951).
568
773
  */
569
- export function reloadStateIfChanged(lastLoadedMtimeMs) {
774
+ function loadStateForReload() {
570
775
  try {
571
- const statePath = getStatePath();
572
- const currentMtimeMs = fs.statSync(statePath).mtimeMs;
573
- if (currentMtimeMs === lastLoadedMtimeMs)
776
+ return loadState();
777
+ }
778
+ catch (error) {
779
+ const code = errnoCode(error) ?? '';
780
+ if (code === 'ENOENT')
574
781
  return null;
575
- const result = loadState();
576
- // Re-stat only on the recovery paths. There loadState rewrote the file
577
- // itself (backup restore) or returned 0 (fresh state), and a current mtime
578
- // stops a reload on every request. On the clean path the baseline was
579
- // taken BEFORE the read on purpose: replacing it with a later stat would
580
- // pair the content we hold with a newer writer's mtime, and the next save
581
- // would overwrite that writer without a ConcurrencyError. A baseline that
582
- // is merely old costs one more reload, which converges.
583
- if (result.recovery) {
584
- try {
585
- result.mtimeMs = fs.statSync(statePath).mtimeMs;
586
- }
587
- catch (err) {
588
- // If file was just loaded, stat should not fail. If it does,
589
- // next reloadIfChanged() will simply trigger another reload.
590
- debug(MODULE, 'Could not re-read mtime after reload (will retry next cycle)', err);
591
- }
592
- }
593
- return result;
782
+ if (!TRANSIENT_READ_CODES.has(code))
783
+ throw error;
784
+ warn(MODULE, `State reload hit ${code}, retrying once: ${errorMessage(error)}`);
785
+ }
786
+ sleepSync(LOCK_RETRY_INTERVAL_MS);
787
+ return loadState();
788
+ }
789
+ /**
790
+ * Re-read state from disk if the file has been modified since the last load/save.
791
+ * Compares file identity (single statSync call) to avoid unnecessary JSON parsing;
792
+ * a null baseline always reloads.
793
+ * @returns The new state and identity if reloaded, or null if no change detected
794
+ * (or the file is gone).
795
+ * @throws What {@link loadState} throws, after one retry for transient
796
+ * resource errors: a newer-version state file or a persistent file system
797
+ * error must reach the caller, not be served as stale state.
798
+ */
799
+ export function reloadStateIfChanged(lastLoaded) {
800
+ const statePath = getStatePath();
801
+ let current;
802
+ try {
803
+ current = statIdentitySync(statePath);
594
804
  }
595
805
  catch (error) {
596
- // statSync failure (file deleted) is benign — keep current in-memory state.
806
+ if (errnoCode(error) !== 'ENOENT')
807
+ throw error;
808
+ // File deleted: benign, keep the current in-memory state.
597
809
  warn(MODULE, `Failed to reload state from disk: ${errorMessage(error)}`);
598
810
  return null;
599
811
  }
812
+ if (lastLoaded !== null && isSameIdentity(current, lastLoaded))
813
+ return null;
814
+ // No re-stat here: loadState's baseline was taken BEFORE its read (or
815
+ // after its own backup restore), and replacing it with a later stat would
816
+ // pair the content we hold with a newer writer's identity, so the next
817
+ // save would overwrite that writer without a ConcurrencyError. That holds
818
+ // for the fresh-state recovery too (#2006). A baseline that is merely old
819
+ // costs one more reload, which converges.
820
+ return loadStateForReload();
600
821
  }