@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
@@ -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 { preserveRejected } 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
@@ -329,8 +475,7 @@ function tryRestoreFromBackup() {
329
475
  */
330
476
  function preserveRejectedStateFile(statePath) {
331
477
  try {
332
- const rejectedPath = statePath + '.rejected-' + Date.now();
333
- fs.copyFileSync(statePath, rejectedPath);
478
+ const rejectedPath = preserveRejected(statePath, 'copy');
334
479
  warn(MODULE, `Previous state preserved at: ${rejectedPath}`);
335
480
  return rejectedPath;
336
481
  }
@@ -351,31 +496,91 @@ export function warnMalformedWorkClaims(raw, state, source) {
351
496
  if (malformed > 0)
352
497
  warn(MODULE, `${source} has ${malformed} unreadable work claim(s); they were dropped`);
353
498
  }
499
+ /**
500
+ * Refuse stored state whose schema version is above this release's. Treating
501
+ * it as invalid would restore an older backup (or fresh state) over newer
502
+ * data. `source` names the copy in the message.
503
+ */
504
+ export function assertNotNewerVersion(raw, source) {
505
+ const version = raw?.version;
506
+ const supported = AgentStateSchema.shape.version.value;
507
+ if (typeof version === 'number' && version > supported) {
508
+ throw new NewerStateVersionError(source, version, supported);
509
+ }
510
+ }
511
+ /**
512
+ * Refuse to save over a state file a newer release wrote. Runs on every save,
513
+ * whatever the caller's mtime baseline: a process that started before the
514
+ * file existed has no baseline and would otherwise write old state over it.
515
+ * A missing or unparseable file is not this check's concern.
516
+ */
517
+ function assertDiskStateNotNewer(statePath) {
518
+ let raw;
519
+ try {
520
+ raw = JSON.parse(fs.readFileSync(statePath, 'utf8'));
521
+ }
522
+ catch (err) {
523
+ // No file yet, or one that does not parse: nothing to protect. Any other
524
+ // failure is worth a warning, but the save still goes ahead.
525
+ const isExpected = errnoCode(err) === 'ENOENT' || err instanceof SyntaxError;
526
+ if (isExpected)
527
+ debug(MODULE, 'No parseable state file to version-check before save', err);
528
+ else
529
+ warn(MODULE, `Could not version-check the state file before save: ${errorMessage(err)}`);
530
+ return;
531
+ }
532
+ assertNotNewerVersion(raw, 'state file');
533
+ }
534
+ /**
535
+ * Rethrow a load failure that is not corruption, before any file is touched:
536
+ * a newer-version state file, or anything carrying an errno `code`, i.e. a
537
+ * file system error (EACCES, EMFILE, EIO, EISDIR, ENOSPC, ...).
538
+ * Restoring a backup or starting fresh there would mask the real problem and
539
+ * can overwrite a valid state file (#1371, #1951). Only unparseable or
540
+ * structurally broken content returns, to be recovered.
541
+ */
542
+ function rethrowUnlessCorrupt(error) {
543
+ if (error instanceof NewerStateVersionError)
544
+ throw error;
545
+ const code = errnoCode(error);
546
+ if (code === 'EACCES' || code === 'EPERM') {
547
+ throw new Error(`Permission denied reading state file (${code}): ${errorMessage(error)}. ` +
548
+ 'This is an environment problem, not state corruption. Check the ownership and ' +
549
+ 'permissions of ~/.oss-autopilot/state.json (e.g. run `ls -l ~/.oss-autopilot/state.json` ' +
550
+ 'and fix with chown/chmod), then retry.', { cause: error });
551
+ }
552
+ if (typeof code === 'string')
553
+ throw error;
554
+ }
354
555
  /**
355
556
  * Load state from file, or create initial state if none exists.
356
557
  * If the main state file is corrupted, attempts to restore from the most recent backup.
357
558
  * Performs migration from legacy ./data/ location if needed.
358
- * @returns Object with the loaded state, the file's mtime (for change detection),
559
+ * @returns Object with the loaded state, the file's identity (for change detection),
359
560
  * 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.
561
+ * @throws Error when the state file exists but cannot be read due to a file
562
+ * system error (EACCES/EPERM get guidance, others are rethrown as they are)
563
+ * or was written by a newer release. Neither is corruption, so
564
+ * restore-or-fresh would mask it and risk clobbering data. No file is touched.
363
565
  */
364
566
  export function loadState() {
365
567
  // Try to migrate from legacy location first
366
568
  migrateFromLegacyLocation();
367
569
  const statePath = getStatePath();
570
+ // Outside the try so the fresh-state recovery in the catch keeps it (#2006).
571
+ let fileId = null;
368
572
  try {
369
573
  if (fs.existsSync(statePath)) {
370
- // Baseline mtime for saveState's compare-and-swap. Taken BEFORE the read:
574
+ // Baseline identity for saveState's compare-and-swap. Taken BEFORE the read:
371
575
  // if another process writes in between, we end up with a baseline older
372
576
  // than our content, and the next save fails with a ConcurrencyError the
373
577
  // 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
578
+ // race pairs stale content with the new identity and the save silently
375
579
  // overwrites the other writer.
376
- let mtimeMs = safeGetMtimeMs(statePath);
580
+ fileId = statFileIdentity(statePath);
377
581
  const data = fs.readFileSync(statePath, 'utf8');
378
582
  let raw = JSON.parse(data);
583
+ assertNotNewerVersion(raw, 'state file');
379
584
  // Chain migrations: v1 → v2 → v3 → v4
380
585
  let wasMigrated = false;
381
586
  if (typeof raw === 'object' && raw !== null) {
@@ -409,17 +614,16 @@ export function loadState() {
409
614
  const reason = `Invalid state file structure: ${summary}`;
410
615
  const restoredState = tryRestoreFromBackup();
411
616
  if (restoredState) {
412
- const mtimeMs = safeGetMtimeMs(statePath);
413
617
  const recovery = { source: 'backup', rejectedPath, reason };
414
- return { state: restoredState, mtimeMs, recovery };
618
+ return { state: restoredState, fileId: statFileIdentity(statePath), recovery };
415
619
  }
416
620
  warn(MODULE, 'No valid backup found, starting fresh');
417
- return { state: createFreshState(), mtimeMs: 0, recovery: { source: 'fresh', rejectedPath, reason } };
621
+ return { fileId, state: createFreshState(), recovery: { source: 'fresh', rejectedPath, reason } };
418
622
  }
419
623
  // Save migrated state only after validation succeeds
420
624
  if (wasMigrated) {
421
625
  atomicWriteFileSync(statePath, serializeState(parsed.data), 0o600);
422
- mtimeMs = safeGetMtimeMs(statePath); // our own write: what we hold is what is on disk
626
+ fileId = statFileIdentity(statePath); // our own write: what we hold is what is on disk
423
627
  debug(MODULE, 'Migrated and validated state saved');
424
628
  }
425
629
  const state = parsed.data;
@@ -431,20 +635,11 @@ export function loadState() {
431
635
  // Log appropriate message based on version
432
636
  const repoCount = Object.keys(state.repoScores).length;
433
637
  debug(MODULE, `Loaded state v${state.version}: ${repoCount} repo scores tracked`);
434
- return { state, mtimeMs };
638
+ return { state, fileId };
435
639
  }
436
640
  }
437
641
  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
- }
642
+ rethrowUnlessCorrupt(error);
448
643
  warn(MODULE, 'Error loading state:', error);
449
644
  warn(MODULE, 'Attempting to restore from backup...');
450
645
  // Preserve the unparseable file before tryRestoreFromBackup() overwrites
@@ -454,26 +649,27 @@ export function loadState() {
454
649
  const reason = `Error loading state: ${errorMessage(error)}`;
455
650
  const restoredState = tryRestoreFromBackup();
456
651
  if (restoredState) {
457
- const mtimeMs = safeGetMtimeMs(statePath);
458
652
  const recovery = { source: 'backup', rejectedPath, reason };
459
- return { state: restoredState, mtimeMs, recovery };
653
+ return { state: restoredState, fileId: statFileIdentity(statePath), recovery };
460
654
  }
461
655
  warn(MODULE, 'No valid backup found, starting fresh');
462
- return { state: createFreshState(), mtimeMs: 0, recovery: { source: 'fresh', rejectedPath, reason } };
656
+ return { fileId, state: createFreshState(), recovery: { source: 'fresh', rejectedPath, reason } };
463
657
  }
464
658
  debug(MODULE, 'No existing state found, initializing...');
465
- return { state: createFreshState(), mtimeMs: 0 };
659
+ return { state: createFreshState(), fileId: null };
466
660
  }
467
661
  /**
468
- * Safely read a file's mtime. Returns 0 if the stat call fails.
662
+ * Read a file's identity. A failed stat returns an identity that matches
663
+ * nothing, so the next save reports a conflict and the next reload re-reads,
664
+ * rather than a 0 that would switch the compare-and-swap off (#2006).
469
665
  */
470
- function safeGetMtimeMs(filePath) {
666
+ function statFileIdentity(filePath) {
471
667
  try {
472
- return fs.statSync(filePath).mtimeMs;
668
+ return statIdentitySync(filePath);
473
669
  }
474
670
  catch (error) {
475
- debug(MODULE, `Could not read state file mtime (reload detection will always trigger): ${errorMessage(error)}`);
476
- return 0;
671
+ debug(MODULE, `Could not stat state file (treating it as changed): ${errorMessage(error)}`);
672
+ return UNKNOWN_FILE_IDENTITY;
477
673
  }
478
674
  }
479
675
  /**
@@ -505,34 +701,35 @@ function cleanupBackups() {
505
701
  * Persist state to disk, creating a timestamped backup of the previous
506
702
  * state file first. Retains at most 10 backup files.
507
703
  *
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).
704
+ * When `expected` is provided (non-null), implements optimistic
705
+ * compare-and-swap: if the on-disk file's identity (mtime, inode, size)
706
+ * differs from the one the caller last loaded or saved, throws
707
+ * `ConcurrencyError` instead of overwriting. This prevents the classic
708
+ * read-modify-write lost-update race across processes (see issues #1030,
709
+ * #2006). Pass `null` to disable the check (no file at load).
514
710
  *
515
711
  * The check runs *inside* the advisory lock so the compare-and-swap is
516
712
  * atomic with respect to the write.
517
713
  *
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.
714
+ * @returns The file's identity after writing (for change detection).
715
+ * @throws ConcurrencyError when `expected` is provided and the on-disk
716
+ * identity no longer matches, or the file cannot be stat'ed.
521
717
  */
522
- export function saveState(state, expectedMtimeMs = null) {
718
+ export function saveState(state, expected = null) {
523
719
  const statePath = getStatePath();
524
720
  const lockPath = statePath + '.lock';
525
721
  const backupDir = getBackupDir();
526
722
  // Acquire advisory lock to prevent concurrent writes
527
- acquireLock(lockPath);
723
+ const held = acquireLock(lockPath);
528
724
  try {
725
+ assertDiskStateNotNewer(statePath);
529
726
  // 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);
727
+ // between the caller's last load and now. Null bypasses the check:
728
+ // there was no file to take a baseline from.
729
+ if (expected !== null && fs.existsSync(statePath)) {
730
+ const current = statFileIdentity(statePath);
731
+ if (!isSameIdentity(current, expected)) {
732
+ throw new ConcurrencyError(expected.mtimeMs, current.mtimeMs, undefined, expected, current);
536
733
  }
537
734
  }
538
735
  // Create backup of existing state (best-effort, non-fatal)
@@ -551,50 +748,72 @@ export function saveState(state, expectedMtimeMs = null) {
551
748
  warn(MODULE, `Could not create backup before save: ${errorMessage(backupErr)}`);
552
749
  // Continue with save — losing a backup is acceptable, losing the save is not
553
750
  }
554
- // Atomic write: write to temp file then rename to prevent corruption on crash
751
+ // Atomic write: write to temp file then rename to prevent corruption on crash.
752
+ // Ownership is re-checked first: a takeover since acquiring must not end in two writers.
753
+ assertLockHeld(lockPath, held);
555
754
  atomicWriteFileSync(statePath, serializeState(state), 0o600);
556
- const mtimeMs = safeGetMtimeMs(statePath);
755
+ const fileId = statFileIdentity(statePath);
557
756
  debug(MODULE, 'State saved successfully');
558
- return mtimeMs;
757
+ return fileId;
559
758
  }
560
759
  finally {
561
- releaseLock(lockPath);
760
+ releaseLock(lockPath, held);
562
761
  }
563
762
  }
763
+ // Read failures that usually clear on their own: worth one retry before a reload fails its caller.
764
+ const TRANSIENT_READ_CODES = new Set(['EMFILE', 'ENFILE', 'EBUSY', 'EAGAIN']);
564
765
  /**
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.
766
+ * loadState for a reload. A file that vanished since the stat is "no change"
767
+ * (null); a transient resource error is retried once after a short pause.
768
+ * Everything else loadState throws (newer-version state, EACCES, a second
769
+ * failure) propagates: swallowing it would leave a long-lived process on old
770
+ * state that its next save writes over the file (#1951).
568
771
  */
569
- export function reloadStateIfChanged(lastLoadedMtimeMs) {
772
+ function loadStateForReload() {
570
773
  try {
571
- const statePath = getStatePath();
572
- const currentMtimeMs = fs.statSync(statePath).mtimeMs;
573
- if (currentMtimeMs === lastLoadedMtimeMs)
774
+ return loadState();
775
+ }
776
+ catch (error) {
777
+ const code = errnoCode(error) ?? '';
778
+ if (code === 'ENOENT')
574
779
  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;
780
+ if (!TRANSIENT_READ_CODES.has(code))
781
+ throw error;
782
+ warn(MODULE, `State reload hit ${code}, retrying once: ${errorMessage(error)}`);
783
+ }
784
+ sleepSync(LOCK_RETRY_INTERVAL_MS);
785
+ return loadState();
786
+ }
787
+ /**
788
+ * Re-read state from disk if the file has been modified since the last load/save.
789
+ * Compares file identity (single statSync call) to avoid unnecessary JSON parsing;
790
+ * a null baseline always reloads.
791
+ * @returns The new state and identity if reloaded, or null if no change detected
792
+ * (or the file is gone).
793
+ * @throws What {@link loadState} throws, after one retry for transient
794
+ * resource errors: a newer-version state file or a persistent file system
795
+ * error must reach the caller, not be served as stale state.
796
+ */
797
+ export function reloadStateIfChanged(lastLoaded) {
798
+ const statePath = getStatePath();
799
+ let current;
800
+ try {
801
+ current = statIdentitySync(statePath);
594
802
  }
595
803
  catch (error) {
596
- // statSync failure (file deleted) is benign — keep current in-memory state.
804
+ if (errnoCode(error) !== 'ENOENT')
805
+ throw error;
806
+ // File deleted: benign, keep the current in-memory state.
597
807
  warn(MODULE, `Failed to reload state from disk: ${errorMessage(error)}`);
598
808
  return null;
599
809
  }
810
+ if (lastLoaded !== null && isSameIdentity(current, lastLoaded))
811
+ return null;
812
+ // No re-stat here: loadState's baseline was taken BEFORE its read (or
813
+ // after its own backup restore), and replacing it with a later stat would
814
+ // pair the content we hold with a newer writer's identity, so the next
815
+ // save would overwrite that writer without a ConcurrencyError. That holds
816
+ // for the fresh-state recovery too (#2006). A baseline that is merely old
817
+ // costs one more reload, which converges.
818
+ return loadStateForReload();
600
819
  }