@oss-autopilot/core 3.39.1 → 3.40.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 (43) hide show
  1. package/dist/cli-registry.js +105 -1
  2. package/dist/cli.bundle.cjs +163 -144
  3. package/dist/commands/daily.d.ts +6 -1
  4. package/dist/commands/daily.js +29 -6
  5. package/dist/commands/dashboard-data.js +16 -7
  6. package/dist/commands/index.d.ts +3 -0
  7. package/dist/commands/index.js +2 -0
  8. package/dist/commands/scout-bridge.js +23 -1
  9. package/dist/commands/setup.js +2 -1
  10. package/dist/commands/vet-list.js +18 -1
  11. package/dist/commands/vet.js +7 -1
  12. package/dist/commands/work.d.ts +134 -0
  13. package/dist/commands/work.js +313 -0
  14. package/dist/core/config-registry.js +6 -0
  15. package/dist/core/daily-logic.d.ts +2 -1
  16. package/dist/core/daily-logic.js +12 -1
  17. package/dist/core/engaged-issue-lookup.d.ts +82 -0
  18. package/dist/core/engaged-issue-lookup.js +157 -0
  19. package/dist/core/engaged-issues.d.ts +3 -3
  20. package/dist/core/engaged-issues.js +5 -5
  21. package/dist/core/gist-state-store.js +6 -2
  22. package/dist/core/index.d.ts +2 -0
  23. package/dist/core/index.js +2 -0
  24. package/dist/core/issue-conversation.d.ts +68 -21
  25. package/dist/core/issue-conversation.js +157 -75
  26. package/dist/core/machine-id.d.ts +18 -0
  27. package/dist/core/machine-id.js +131 -0
  28. package/dist/core/paths.d.ts +8 -0
  29. package/dist/core/paths.js +10 -0
  30. package/dist/core/pr-graphql.d.ts +2 -0
  31. package/dist/core/pr-graphql.js +2 -2
  32. package/dist/core/state-persistence.d.ts +8 -0
  33. package/dist/core/state-persistence.js +14 -1
  34. package/dist/core/state-schema.d.ts +54 -1
  35. package/dist/core/state-schema.js +68 -0
  36. package/dist/core/state.d.ts +39 -1
  37. package/dist/core/state.js +86 -2
  38. package/dist/core/types.d.ts +1 -1
  39. package/dist/core/work-claims.d.ts +89 -0
  40. package/dist/core/work-claims.js +196 -0
  41. package/dist/formatters/json.d.ts +130 -1
  42. package/dist/formatters/json.js +26 -0
  43. package/package.json +1 -1
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Stable machine identity (#1856): a random UUID written once to
3
+ * `~/.oss-autopilot/machine-id` and read back on every later need.
4
+ *
5
+ * Work claims record the id next to a `worktree` path so two claims are
6
+ * compared as the same checkout only when they are on the same machine. A
7
+ * hostname cannot do that: it changes with the network (`air.local`) or a
8
+ * rename (`air` to `air-2`), and two machines can share one. The file lives
9
+ * outside `state.json`, so the Gist never carries it and no machine inherits
10
+ * another's id. A read or write failure yields no id (with a debug line);
11
+ * claims then fall back to the hostname rule.
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { getMachineIdPath } from './paths.js';
16
+ import { debug } from './logger.js';
17
+ const MODULE = 'machine-id';
18
+ /**
19
+ * How long to wait for a concurrent creator to fill the file it has just
20
+ * published. Its link lands with the id already inside, so an empty file is
21
+ * almost always a crash leftover; the retries only cover a writer that is
22
+ * still between its own create and its content write.
23
+ */
24
+ const EMPTY_FILE_RETRIES = 5;
25
+ const EMPTY_FILE_RETRY_MS = 20;
26
+ /** Read the stored id, or null when the file is missing or empty. Throws on an unreadable file. */
27
+ function readStoredMachineId(filePath) {
28
+ if (!fs.existsSync(filePath))
29
+ return null;
30
+ const stored = fs.readFileSync(filePath, 'utf8').trim();
31
+ return stored.length > 0 ? stored : null;
32
+ }
33
+ /** Synchronous sleep; the whole id lookup is synchronous and runs once per process. */
34
+ function sleepSync(ms) {
35
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
36
+ }
37
+ /** The stored id, re-reading a few times while the file is present but empty. */
38
+ function readStoredMachineIdWithRetry(filePath) {
39
+ let stored = readStoredMachineId(filePath);
40
+ for (let attempt = 0; stored === null && attempt < EMPTY_FILE_RETRIES; attempt++) {
41
+ sleepSync(EMPTY_FILE_RETRY_MS);
42
+ stored = readStoredMachineId(filePath);
43
+ }
44
+ return stored;
45
+ }
46
+ function isFileExistsError(err) {
47
+ return typeof err === 'object' && err !== null && err.code === 'EEXIST';
48
+ }
49
+ /**
50
+ * Publish a tmp file holding a fresh UUID as `filePath`. Returns true when it
51
+ * created the file, false when another process already had. Throws on any
52
+ * other failure.
53
+ *
54
+ * The create is a hard link of the already-written tmp file: an exclusive
55
+ * `writeFileSync` (`wx`) would create the name before writing the id, and a
56
+ * second session reading in that window would see an empty file and
57
+ * overwrite it with an id of its own. The link lands with the content in
58
+ * place and still fails with EEXIST when the name is taken.
59
+ */
60
+ function didCreateMachineIdFile(tmpPath, filePath) {
61
+ try {
62
+ fs.linkSync(tmpPath, filePath);
63
+ return true;
64
+ }
65
+ catch (err) {
66
+ if (!isFileExistsError(err))
67
+ throw err;
68
+ return false;
69
+ }
70
+ }
71
+ /**
72
+ * Publish the tmp file as `filePath` and return the id the file holds
73
+ * afterwards. The id another process published first wins; an empty file
74
+ * that stays empty is a crash leftover and is replaced in one rename. The
75
+ * id is always re-read from disk, never taken from what this process wrote.
76
+ */
77
+ function publishMachineId(tmpPath, filePath) {
78
+ if (didCreateMachineIdFile(tmpPath, filePath)) {
79
+ debug(MODULE, `Created machine id file ${filePath}`);
80
+ }
81
+ else {
82
+ const concurrent = readStoredMachineIdWithRetry(filePath);
83
+ if (concurrent !== null) {
84
+ debug(MODULE, `Machine id file ${filePath} was created by another process; using its id`);
85
+ return concurrent;
86
+ }
87
+ fs.renameSync(tmpPath, filePath);
88
+ debug(MODULE, `Replaced empty machine id file ${filePath}`);
89
+ }
90
+ const published = readStoredMachineId(filePath);
91
+ if (published === null)
92
+ throw new Error(`Machine id file ${filePath} is empty right after it was written`);
93
+ return published;
94
+ }
95
+ /**
96
+ * The stored id, or a fresh UUID written to `filePath` (private to the user).
97
+ * Throws when the file is unusable.
98
+ *
99
+ * Two sessions starting on a fresh machine at once would otherwise both see
100
+ * no file and each write its own id, and the loser's claims would carry an
101
+ * id that no longer exists on disk. So the id is written to a per-process
102
+ * tmp file first and the file is created atomically with its content; the
103
+ * tmp file is removed whichever way the publish ends.
104
+ */
105
+ function readOrCreateMachineId(filePath) {
106
+ const stored = readStoredMachineId(filePath);
107
+ if (stored !== null)
108
+ return stored;
109
+ const tmpPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
110
+ fs.writeFileSync(tmpPath, `${randomUUID()}\n`, { encoding: 'utf8', mode: 0o600 });
111
+ try {
112
+ return publishMachineId(tmpPath, filePath);
113
+ }
114
+ finally {
115
+ fs.rmSync(tmpPath, { force: true });
116
+ }
117
+ }
118
+ /**
119
+ * This machine's id, creating `~/.oss-autopilot/machine-id` on first need.
120
+ * Returns undefined when the file can neither be read nor written; callers
121
+ * treat that as "unknown machine" rather than failing.
122
+ */
123
+ export function getMachineId() {
124
+ try {
125
+ return readOrCreateMachineId(getMachineIdPath());
126
+ }
127
+ catch (err) {
128
+ debug(MODULE, 'Could not read or create the machine id file; claims will carry no machineId', err);
129
+ return undefined;
130
+ }
131
+ }
@@ -67,6 +67,14 @@ export declare function getReportsDir(): string;
67
67
  * avoiding a search-by-description API call on every session.
68
68
  */
69
69
  export declare function getGistIdPath(): string;
70
+ /**
71
+ * Returns the path to the local machine id file (`~/.oss-autopilot/machine-id`).
72
+ *
73
+ * Holds a random UUID written once per machine (#1856). It is local only:
74
+ * the Gist carries `state.json`, never this file, so two machines never
75
+ * share an id.
76
+ */
77
+ export declare function getMachineIdPath(): string;
70
78
  /**
71
79
  * Returns the path to the local state cache file (`~/.oss-autopilot/state-cache.json`).
72
80
  *
@@ -118,6 +118,16 @@ export function getReportsDir() {
118
118
  export function getGistIdPath() {
119
119
  return path.join(getDataDir(), 'gist-id');
120
120
  }
121
+ /**
122
+ * Returns the path to the local machine id file (`~/.oss-autopilot/machine-id`).
123
+ *
124
+ * Holds a random UUID written once per machine (#1856). It is local only:
125
+ * the Gist carries `state.json`, never this file, so two machines never
126
+ * share an id.
127
+ */
128
+ export function getMachineIdPath() {
129
+ return path.join(getDataDir(), 'machine-id');
130
+ }
121
131
  /**
122
132
  * Returns the path to the local state cache file (`~/.oss-autopilot/state-cache.json`).
123
133
  *
@@ -223,6 +223,8 @@ type NormalizeOutcome = {
223
223
  * hit; `missing` — the node was absent, inaccessible, or lacked a database id).
224
224
  */
225
225
  export declare function normalizePRNode(node: GraphQLPullRequestNode | null | undefined): NormalizeOutcome;
226
+ /** Split an array into fixed-size chunks. Shared with the engaged-issue lookup. */
227
+ export declare function chunk<T>(items: T[], size: number): T[][];
226
228
  /**
227
229
  * Detect GitHub's primary GraphQL rate limit. Unlike a REST 429/403, an
228
230
  * exhausted GraphQL point budget arrives as an HTTP 200 with an
@@ -262,8 +262,8 @@ export function normalizePRNode(node) {
262
262
  },
263
263
  };
264
264
  }
265
- /** Split an array into fixed-size chunks. */
266
- function chunk(items, size) {
265
+ /** Split an array into fixed-size chunks. Shared with the engaged-issue lookup. */
266
+ export function chunk(items, size) {
267
267
  const out = [];
268
268
  for (let i = 0; i < items.length; i += size)
269
269
  out.push(items.slice(i, i + size));
@@ -69,6 +69,14 @@ export interface LoadStateResult {
69
69
  mtimeMs: number;
70
70
  recovery?: LoadRecoveryInfo;
71
71
  }
72
+ /**
73
+ * Report work claims the lenient parse dropped from `raw` (#1856). Every path
74
+ * that turns stored JSON into an `AgentState` (the state file, a Gist copy
75
+ * at bootstrap or refresh, the local cache in degraded mode) calls this, so
76
+ * a claim another machine wrote in a shape this release cannot read is never
77
+ * dropped silently. `source` names the copy in the warning.
78
+ */
79
+ export declare function warnMalformedWorkClaims(raw: unknown, state: AgentState, source: string): void;
72
80
  /**
73
81
  * Load state from file, or create initial state if none exists.
74
82
  * If the main state file is corrupted, attempts to restore from the most recent backup.
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
- import { AgentStateSchema, NEWER_WRITER_HINT, unknownStateKeys } from './state-schema.js';
8
+ import { AgentStateSchema, NEWER_WRITER_HINT, malformedWorkClaimCount, unknownStateKeys } from './state-schema.js';
9
9
  import { serializeState } from './state-prune.js';
10
10
  import { getStatePath, getBackupDir, getDataDir, getLegacyStatePath, getLegacyBackupDir } from './paths.js';
11
11
  import { errorMessage, ConcurrencyError } from './errors.js';
@@ -339,6 +339,18 @@ function preserveRejectedStateFile(statePath) {
339
339
  return null;
340
340
  }
341
341
  }
342
+ /**
343
+ * Report work claims the lenient parse dropped from `raw` (#1856). Every path
344
+ * that turns stored JSON into an `AgentState` (the state file, a Gist copy
345
+ * at bootstrap or refresh, the local cache in degraded mode) calls this, so
346
+ * a claim another machine wrote in a shape this release cannot read is never
347
+ * dropped silently. `source` names the copy in the warning.
348
+ */
349
+ export function warnMalformedWorkClaims(raw, state, source) {
350
+ const malformed = malformedWorkClaimCount(raw, state);
351
+ if (malformed > 0)
352
+ warn(MODULE, `${source} has ${malformed} unreadable work claim(s); they were dropped`);
353
+ }
342
354
  /**
343
355
  * Load state from file, or create initial state if none exists.
344
356
  * If the main state file is corrupted, attempts to restore from the most recent backup.
@@ -411,6 +423,7 @@ export function loadState() {
411
423
  debug(MODULE, 'Migrated and validated state saved');
412
424
  }
413
425
  const state = parsed.data;
426
+ warnMalformedWorkClaims(raw, state, 'State file');
414
427
  // `config.dismissedIssues` keys are issue AND PR URLs: `dismiss` accepts
415
428
  // a merged PR's URL for the merged-PR notes nudge (#1861). The former
416
429
  // "PR dismiss removed" load-time strip of `/pull/N` keys is gone; it
@@ -314,6 +314,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
314
314
  maxActivePRs: z.ZodDefault<z.ZodNumber>;
315
315
  maxOpenPRsPerRepo: z.ZodDefault<z.ZodNumber>;
316
316
  maxOpenPRsColdRepo: z.ZodDefault<z.ZodNumber>;
317
+ maxConcurrentImplementations: z.ZodDefault<z.ZodNumber>;
317
318
  dormantThresholdDays: z.ZodDefault<z.ZodNumber>;
318
319
  approachingDormantDays: z.ZodDefault<z.ZodNumber>;
319
320
  maxIssueAgeDays: z.ZodDefault<z.ZodNumber>;
@@ -383,6 +384,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
383
384
  maxActivePRs: number;
384
385
  maxOpenPRsPerRepo: number;
385
386
  maxOpenPRsColdRepo: number;
387
+ maxConcurrentImplementations: number;
386
388
  dormantThresholdDays: number;
387
389
  approachingDormantDays: number;
388
390
  maxIssueAgeDays: number;
@@ -434,6 +436,7 @@ export declare const AgentConfigSchema: z.ZodPipe<z.ZodObject<{
434
436
  maxActivePRs: number;
435
437
  maxOpenPRsPerRepo: number;
436
438
  maxOpenPRsColdRepo: number;
439
+ maxConcurrentImplementations: number;
437
440
  dormantThresholdDays: number;
438
441
  approachingDormantDays: number;
439
442
  maxIssueAgeDays: number;
@@ -671,6 +674,34 @@ export declare const SearchRotationSchema: z.ZodObject<{
671
674
  strategyOffset: z.ZodDefault<z.ZodNumber>;
672
675
  lastRotatedAt: z.ZodOptional<z.ZodString>;
673
676
  }, z.core.$loose>;
677
+ /**
678
+ * A record that some session is working an item (#1856, #1852 gap 2): an
679
+ * `implementation` claim on an issue URL while a fix is being built (locally
680
+ * in a worktree or on a remote worker run), or a `pr` claim on a PR URL while
681
+ * a session does Tier 2 work on it. One list serves both so a second session,
682
+ * on this machine or another one via the Gist, sees "handled in session X"
683
+ * instead of starting the same work. Claims expire (`expiresAt`); expired
684
+ * ones are ignored on read and pruned on the next claim write. `finished`
685
+ * marks an implementation whose branch is ready to collect and review.
686
+ */
687
+ export declare const WorkClaimSchema: z.ZodObject<{
688
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
689
+ url: z.ZodString;
690
+ session: z.ZodString;
691
+ startedAt: z.ZodString;
692
+ expiresAt: z.ZodString;
693
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
694
+ branch: z.ZodOptional<z.ZodString>;
695
+ worktree: z.ZodOptional<z.ZodString>;
696
+ host: z.ZodOptional<z.ZodString>;
697
+ machineId: z.ZodOptional<z.ZodString>;
698
+ runId: z.ZodOptional<z.ZodString>;
699
+ finishedAt: z.ZodOptional<z.ZodString>;
700
+ }, z.core.$loose>;
701
+ /** How many entries of `raw.workClaims` the lenient parse dropped as malformed (#1856); 0 when none or no list. */
702
+ export declare function malformedWorkClaimCount(raw: unknown, parsed: {
703
+ workClaims: readonly unknown[];
704
+ }): number;
674
705
  /**
675
706
  * Forward compatibility (#1831). The state Gist is shared by clients on
676
707
  * different releases, and a strict parse let an older client drop a newer
@@ -711,6 +742,7 @@ export declare const AgentStateSchema: z.ZodObject<{
711
742
  maxActivePRs: z.ZodDefault<z.ZodNumber>;
712
743
  maxOpenPRsPerRepo: z.ZodDefault<z.ZodNumber>;
713
744
  maxOpenPRsColdRepo: z.ZodDefault<z.ZodNumber>;
745
+ maxConcurrentImplementations: z.ZodDefault<z.ZodNumber>;
714
746
  dormantThresholdDays: z.ZodDefault<z.ZodNumber>;
715
747
  approachingDormantDays: z.ZodDefault<z.ZodNumber>;
716
748
  maxIssueAgeDays: z.ZodDefault<z.ZodNumber>;
@@ -780,6 +812,7 @@ export declare const AgentStateSchema: z.ZodObject<{
780
812
  maxActivePRs: number;
781
813
  maxOpenPRsPerRepo: number;
782
814
  maxOpenPRsColdRepo: number;
815
+ maxConcurrentImplementations: number;
783
816
  dormantThresholdDays: number;
784
817
  approachingDormantDays: number;
785
818
  maxIssueAgeDays: number;
@@ -831,6 +864,7 @@ export declare const AgentStateSchema: z.ZodObject<{
831
864
  maxActivePRs: number;
832
865
  maxOpenPRsPerRepo: number;
833
866
  maxOpenPRsColdRepo: number;
867
+ maxConcurrentImplementations: number;
834
868
  dormantThresholdDays: number;
835
869
  approachingDormantDays: number;
836
870
  maxIssueAgeDays: number;
@@ -1132,6 +1166,21 @@ export declare const AgentStateSchema: z.ZodObject<{
1132
1166
  strategyOffset: z.ZodDefault<z.ZodNumber>;
1133
1167
  lastRotatedAt: z.ZodOptional<z.ZodString>;
1134
1168
  }, z.core.$loose>>;
1169
+ workClaims: z.ZodPipe<z.ZodDefault<z.ZodArray<z.ZodUnknown>>, z.ZodTransform<{
1170
+ [x: string]: unknown;
1171
+ kind: (string & {}) | "implementation" | "pr";
1172
+ url: string;
1173
+ session: string;
1174
+ startedAt: string;
1175
+ expiresAt: string;
1176
+ status: "finished" | "running" | (string & {});
1177
+ branch?: string | undefined;
1178
+ worktree?: string | undefined;
1179
+ host?: string | undefined;
1180
+ machineId?: string | undefined;
1181
+ runId?: string | undefined;
1182
+ finishedAt?: string | undefined;
1183
+ }[], unknown[]>>;
1135
1184
  }, z.core.$loose>;
1136
1185
  export type IssueStatus = z.infer<typeof IssueStatusSchema>;
1137
1186
  export type FetchedPRStatus = z.infer<typeof FetchedPRStatusSchema>;
@@ -1144,6 +1193,9 @@ export type OvernightPrepared = KnownKeys<z.infer<typeof OvernightPreparedSchema
1144
1193
  export type OvernightRecord = KnownKeys<z.infer<typeof OvernightRecordSchema>>;
1145
1194
  export type OvernightImplementAttempt = KnownKeys<z.infer<typeof OvernightImplementAttemptSchema>>;
1146
1195
  export type SearchRotation = KnownKeys<z.infer<typeof SearchRotationSchema>>;
1196
+ export type WorkClaim = KnownKeys<z.infer<typeof WorkClaimSchema>>;
1197
+ export type WorkClaimKind = 'implementation' | 'pr';
1198
+ export type WorkClaimStatus = 'running' | 'finished';
1147
1199
  export type RepoSignals = z.infer<typeof RepoSignalsSchema>;
1148
1200
  export type RepoScore = KnownKeys<z.infer<typeof RepoScoreSchema>>;
1149
1201
  export type StoredMergedPR = KnownKeys<z.infer<typeof StoredMergedPRSchema>>;
@@ -1161,7 +1213,7 @@ export type MergedPR = z.infer<typeof MergedPRSchema>;
1161
1213
  export type DailyDigestSummary = z.infer<typeof DailyDigestSummarySchema>;
1162
1214
  export type DailyDigest = z.infer<typeof DailyDigestSchema>;
1163
1215
  type RawAgentState = z.infer<typeof AgentStateSchema>;
1164
- export type AgentState = Omit<KnownKeys<RawAgentState>, 'config' | 'repoScores' | 'mergedPRs' | 'closedPRs' | 'pickSnapshots' | 'lastOvernight' | 'searchRotation'> & {
1216
+ export type AgentState = Omit<KnownKeys<RawAgentState>, 'config' | 'repoScores' | 'mergedPRs' | 'closedPRs' | 'pickSnapshots' | 'lastOvernight' | 'searchRotation' | 'workClaims'> & {
1165
1217
  config: AgentConfig;
1166
1218
  repoScores: Record<string, RepoScore>;
1167
1219
  mergedPRs?: StoredMergedPR[];
@@ -1169,6 +1221,7 @@ export type AgentState = Omit<KnownKeys<RawAgentState>, 'config' | 'repoScores'
1169
1221
  pickSnapshots: PickSnapshot[];
1170
1222
  lastOvernight?: OvernightRecord;
1171
1223
  searchRotation?: SearchRotation;
1224
+ workClaims: WorkClaim[];
1172
1225
  };
1173
1226
  /** Top-level state keys this release does not know, i.e. written by another (usually newer) release (#1831). */
1174
1227
  export declare function unknownStateKeys(raw: unknown): string[];
@@ -284,6 +284,13 @@ export const AgentConfigSchema = z
284
284
  */
285
285
  maxOpenPRsPerRepo: z.number().int().min(0).default(0),
286
286
  maxOpenPRsColdRepo: z.number().int().min(0).default(1),
287
+ /**
288
+ * Cap on implementations running at once across sessions and machines
289
+ * (#1856): `work claim --kind implementation` refuses once this many
290
+ * running implementation claims are active. 0 disables the cap; the
291
+ * one-implementation-per-worktree rule still applies.
292
+ */
293
+ maxConcurrentImplementations: z.number().int().min(0).default(2),
287
294
  dormantThresholdDays: z.number().default(30),
288
295
  approachingDormantDays: z.number().default(25),
289
296
  maxIssueAgeDays: z.number().default(90),
@@ -579,6 +586,60 @@ export const SearchRotationSchema = z
579
586
  lastRotatedAt: z.string().optional(),
580
587
  })
581
588
  .passthrough();
589
+ /**
590
+ * A record that some session is working an item (#1856, #1852 gap 2): an
591
+ * `implementation` claim on an issue URL while a fix is being built (locally
592
+ * in a worktree or on a remote worker run), or a `pr` claim on a PR URL while
593
+ * a session does Tier 2 work on it. One list serves both so a second session,
594
+ * on this machine or another one via the Gist, sees "handled in session X"
595
+ * instead of starting the same work. Claims expire (`expiresAt`); expired
596
+ * ones are ignored on read and pruned on the next claim write. `finished`
597
+ * marks an implementation whose branch is ready to collect and review.
598
+ */
599
+ export const WorkClaimSchema = z
600
+ .object({
601
+ kind: openEnum(['implementation', 'pr']),
602
+ url: z.string(),
603
+ /** Name of the session that holds the claim, e.g. `air/20261102T1207`. */
604
+ session: z.string(),
605
+ startedAt: z.string(),
606
+ expiresAt: z.string(),
607
+ status: openEnum(['running', 'finished']),
608
+ branch: z.string().optional(),
609
+ /** Absolute path of the checkout the implementation runs in; two live implementations on one machine never share one. */
610
+ worktree: z.string().optional(),
611
+ /** Short hostname (`hostname -s`) the `worktree` path is on; a display field, and the checkout identity for claims without `machineId`. */
612
+ host: z.string().optional(),
613
+ /**
614
+ * Id of the machine the `worktree` path is on (`~/.oss-autopilot/machine-id`,
615
+ * a UUID written once per machine, never synced): the same path on two
616
+ * machines is two checkouts, and a renamed host is still one machine.
617
+ */
618
+ machineId: z.string().optional(),
619
+ /** Remote worker run id, when the implementation runs off-machine. */
620
+ runId: z.string().optional(),
621
+ finishedAt: z.string().optional(),
622
+ })
623
+ .loose();
624
+ /**
625
+ * `state.workClaims`, parsed one claim at a time (#1856): a claim this
626
+ * release cannot read (a newer client's shape, or a corrupted entry) is
627
+ * dropped instead of rejecting the whole state, which would send the loader
628
+ * to a backup and lose every other machine's claims. Loaders compare the
629
+ * stored and parsed counts ({@link malformedWorkClaimCount}) to warn.
630
+ */
631
+ const WorkClaimListSchema = z
632
+ .array(z.unknown())
633
+ .default([])
634
+ .transform((claims) => claims.flatMap((claim) => {
635
+ const parsed = WorkClaimSchema.safeParse(claim);
636
+ return parsed.success ? [parsed.data] : [];
637
+ }));
638
+ /** How many entries of `raw.workClaims` the lenient parse dropped as malformed (#1856); 0 when none or no list. */
639
+ export function malformedWorkClaimCount(raw, parsed) {
640
+ const stored = raw !== null && typeof raw === 'object' ? raw.workClaims : undefined;
641
+ return Array.isArray(stored) ? Math.max(0, stored.length - parsed.workClaims.length) : 0;
642
+ }
582
643
  /**
583
644
  * Forward compatibility (#1831). The state Gist is shared by clients on
584
645
  * different releases, and a strict parse let an older client drop a newer
@@ -656,6 +717,13 @@ export const AgentStateSchema = z
656
717
  * here and fed into the next scout state. Absent until the first search.
657
718
  */
658
719
  searchRotation: SearchRotationSchema.optional(),
720
+ /**
721
+ * Items some session is working on (#1856, #1852): in-flight
722
+ * implementations and PRs under Tier 2 work. Shared across machines via
723
+ * the Gist; `work claim/finish/release` are the only writers. Expired
724
+ * entries are ignored on read and pruned on write.
725
+ */
726
+ workClaims: WorkClaimListSchema,
659
727
  })
660
728
  .passthrough();
661
729
  /** Top-level state keys this release does not know, i.e. written by another (usually newer) release (#1831). */
@@ -3,7 +3,7 @@
3
3
  * Thin coordinator that delegates persistence to state-persistence.ts
4
4
  * and scoring logic to repo-score-manager.ts.
5
5
  */
6
- import { AgentState, TrackedIssue, RepoScore, RepoScoreUpdate, DailyDigest, LocalRepoCache, StatusOverride, FetchedPRStatus, StoredMergedPR, StoredClosedPR, SearchSeenEntry, PickSnapshot, OvernightRecord, SearchRotation } from './types.js';
6
+ import { AgentState, TrackedIssue, RepoScore, RepoScoreUpdate, DailyDigest, LocalRepoCache, StatusOverride, FetchedPRStatus, StoredMergedPR, StoredClosedPR, SearchSeenEntry, PickSnapshot, OvernightRecord, SearchRotation, WorkClaim } from './types.js';
7
7
  import { type LoadRecoveryInfo } from './state-persistence.js';
8
8
  import type { Stats } from './repo-score-manager.js';
9
9
  import { GistStateStore } from './gist-state-store.js';
@@ -521,6 +521,44 @@ export declare class StateManager {
521
521
  getSearchRotation(): SearchRotation | undefined;
522
522
  /** Persist the cursor scout advanced during a search (#1630). */
523
523
  setSearchRotation(rotation: SearchRotation): void;
524
+ /** Every stored claim, expired ones included; `getActiveWorkClaims` is the usual read. */
525
+ getWorkClaims(): WorkClaim[];
526
+ /** The claims still live at `nowMs`, in stored order. */
527
+ getActiveWorkClaims(nowMs?: number): WorkClaim[];
528
+ /**
529
+ * The live claims for a write that is about to replace the list: expired
530
+ * claims drop out here (pruning). One with an `expiresAt` that does not
531
+ * parse is pruned like any expired claim, but it is a data problem rather
532
+ * than the passage of time, so it is reported.
533
+ */
534
+ private pruneWorkClaims;
535
+ /**
536
+ * Record a claim, replacing any claim on the same item (#1856). Expired
537
+ * claims are pruned in the same write. An absolute set: re-running it on a
538
+ * refreshed Gist baseline keeps every other machine's claims.
539
+ * @returns true when a live claim on the item was replaced
540
+ */
541
+ upsertWorkClaim(claim: WorkClaim, nowMs?: number): boolean;
542
+ /**
543
+ * Mark the live claim on `url` finished at `at` (#1856): the branch is ready
544
+ * to collect, and `expiresAt` is extended so it stays collectable (see
545
+ * {@link finishWorkClaim}). Expired claims are pruned in the same write.
546
+ * Without a live claim nothing is written: a prune alone would mark the
547
+ * state un-pushed and raise a sync alarm for a change nobody made.
548
+ * @returns the updated claim, or undefined when no live claim exists
549
+ */
550
+ finishWorkClaim(url: string, at: string, nowMs?: number): WorkClaim | undefined;
551
+ /**
552
+ * Drop claims: the one on `url`, or every claim held by `session` (optionally
553
+ * only of one `kind`). Expired claims are pruned in the same write; when
554
+ * nothing matches, nothing is written (see {@link finishWorkClaim}).
555
+ * @returns the URLs of the live claims released
556
+ */
557
+ releaseWorkClaims(selector: {
558
+ url?: string;
559
+ session?: string;
560
+ kind?: string;
561
+ }, nowMs?: number): string[];
524
562
  setStatusOverride(url: string, status: FetchedPRStatus, lastActivityAt: string): void;
525
563
  /**
526
564
  * Remove a manual status override for a PR.
@@ -5,8 +5,9 @@
5
5
  */
6
6
  import * as fs from 'node:fs';
7
7
  import { AgentStateSchema } from './state-schema.js';
8
+ import { activeWorkClaims, finishWorkClaim, workClaimKey } from './work-claims.js';
8
9
  import { serializeState } from './state-prune.js';
9
- import { loadState, saveState, reloadStateIfChanged, createFreshState, atomicWriteFileSync, } from './state-persistence.js';
10
+ import { loadState, saveState, reloadStateIfChanged, createFreshState, atomicWriteFileSync, warnMalformedWorkClaims, } from './state-persistence.js';
10
11
  import * as repoScoring from './repo-score-manager.js';
11
12
  import { debug, warn } from './logger.js';
12
13
  import { errorMessage, ConfigurationError, ConcurrencyError, GistConcurrencyError, isTransientNetworkError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, } from './errors.js';
@@ -603,8 +604,10 @@ export class StateManager {
603
604
  return false;
604
605
  }
605
606
  const wasUnpushed = this.unpushed;
607
+ let rawState;
606
608
  try {
607
- this.state = AgentStateSchema.parse(JSON.parse(raw));
609
+ rawState = JSON.parse(raw);
610
+ this.state = AgentStateSchema.parse(rawState);
608
611
  }
609
612
  catch (err) {
610
613
  warn(MODULE, `Failed to parse refreshed Gist state: ${errorMessage(err)}`);
@@ -618,6 +621,7 @@ export class StateManager {
618
621
  };
619
622
  return false;
620
623
  }
624
+ warnMalformedWorkClaims(rawState, this.state, 'Gist state');
621
625
  // Derived bookkeeping on the fresh copy, not a user change: it must
622
626
  // not count as un-pushed, so the flag is reset after it runs.
623
627
  this.tryReconcilePRCounts();
@@ -1228,6 +1232,86 @@ export class StateManager {
1228
1232
  this.state.searchRotation = rotation;
1229
1233
  this.autoSave();
1230
1234
  }
1235
+ // === Work claims (#1856, #1852) ===
1236
+ /** Every stored claim, expired ones included; `getActiveWorkClaims` is the usual read. */
1237
+ getWorkClaims() {
1238
+ return this.state.workClaims ?? [];
1239
+ }
1240
+ /** The claims still live at `nowMs`, in stored order. */
1241
+ getActiveWorkClaims(nowMs = Date.now()) {
1242
+ return activeWorkClaims(this.getWorkClaims(), nowMs);
1243
+ }
1244
+ /**
1245
+ * The live claims for a write that is about to replace the list: expired
1246
+ * claims drop out here (pruning). One with an `expiresAt` that does not
1247
+ * parse is pruned like any expired claim, but it is a data problem rather
1248
+ * than the passage of time, so it is reported.
1249
+ */
1250
+ pruneWorkClaims(nowMs) {
1251
+ const stored = this.getWorkClaims();
1252
+ for (const claim of stored) {
1253
+ if (!Number.isFinite(Date.parse(claim.expiresAt))) {
1254
+ warn(MODULE, `Pruning work claim on ${claim.url} (session ${claim.session}): expiresAt "${claim.expiresAt}" is not a date`);
1255
+ }
1256
+ }
1257
+ return activeWorkClaims(stored, nowMs);
1258
+ }
1259
+ /**
1260
+ * Record a claim, replacing any claim on the same item (#1856). Expired
1261
+ * claims are pruned in the same write. An absolute set: re-running it on a
1262
+ * refreshed Gist baseline keeps every other machine's claims.
1263
+ * @returns true when a live claim on the item was replaced
1264
+ */
1265
+ upsertWorkClaim(claim, nowMs = Date.now()) {
1266
+ const key = workClaimKey(claim.url);
1267
+ const live = this.pruneWorkClaims(nowMs);
1268
+ const isReplaced = live.some((c) => workClaimKey(c.url) === key);
1269
+ this.state.workClaims = [...live.filter((c) => workClaimKey(c.url) !== key), claim];
1270
+ this.autoSave();
1271
+ return isReplaced;
1272
+ }
1273
+ /**
1274
+ * Mark the live claim on `url` finished at `at` (#1856): the branch is ready
1275
+ * to collect, and `expiresAt` is extended so it stays collectable (see
1276
+ * {@link finishWorkClaim}). Expired claims are pruned in the same write.
1277
+ * Without a live claim nothing is written: a prune alone would mark the
1278
+ * state un-pushed and raise a sync alarm for a change nobody made.
1279
+ * @returns the updated claim, or undefined when no live claim exists
1280
+ */
1281
+ finishWorkClaim(url, at, nowMs = Date.now()) {
1282
+ const key = workClaimKey(url);
1283
+ const live = this.pruneWorkClaims(nowMs);
1284
+ const existing = live.find((claim) => workClaimKey(claim.url) === key);
1285
+ if (!existing)
1286
+ return undefined;
1287
+ const updated = finishWorkClaim(existing, at);
1288
+ this.state.workClaims = live.map((claim) => (claim === existing ? updated : claim));
1289
+ this.autoSave();
1290
+ return updated;
1291
+ }
1292
+ /**
1293
+ * Drop claims: the one on `url`, or every claim held by `session` (optionally
1294
+ * only of one `kind`). Expired claims are pruned in the same write; when
1295
+ * nothing matches, nothing is written (see {@link finishWorkClaim}).
1296
+ * @returns the URLs of the live claims released
1297
+ */
1298
+ releaseWorkClaims(selector, nowMs = Date.now()) {
1299
+ const key = selector.url === undefined ? undefined : workClaimKey(selector.url);
1300
+ const isMatch = (claim) => {
1301
+ if (key !== undefined && workClaimKey(claim.url) !== key)
1302
+ return false;
1303
+ if (selector.session !== undefined && claim.session !== selector.session)
1304
+ return false;
1305
+ return selector.kind === undefined || claim.kind === selector.kind;
1306
+ };
1307
+ const live = this.pruneWorkClaims(nowMs);
1308
+ const released = live.filter((claim) => isMatch(claim)).map((claim) => claim.url);
1309
+ if (released.length > 0) {
1310
+ this.state.workClaims = live.filter((claim) => !isMatch(claim));
1311
+ this.autoSave();
1312
+ }
1313
+ return released;
1314
+ }
1231
1315
  setStatusOverride(url, status, lastActivityAt) {
1232
1316
  if (!this.state.config.statusOverrides) {
1233
1317
  this.state.config.statusOverrides = {};
@@ -2,7 +2,7 @@
2
2
  * Core types for the Open Source Contribution Agent
3
3
  */
4
4
  import type { FetchedPRStatus, RepoSignals, TrackedIssue, IssueVettingResult, IssueScope, DiffTool, AgentConfig, AgentState } from './state-schema.js';
5
- export type { IssueStatus, FetchedPRStatus, ProjectCategory, IssueScope, DiffTool, RepoSignals, RepoScore, StoredMergedPR, StoredClosedPR, AnalyzedIssueConversation, ContributionGuidelines, IssueVettingResult, TrackedIssue, ShelvedPRRef, StatusOverride, AgentConfig, LocalRepoCache, ClosedPR, MergedPR, DailyDigest, AgentState, SearchSeenEntry, PickSnapshot, OvernightPrepared, OvernightRecord, OvernightImplementAttempt, SearchRotation, } from './state-schema.js';
5
+ export type { IssueStatus, FetchedPRStatus, ProjectCategory, IssueScope, DiffTool, RepoSignals, RepoScore, StoredMergedPR, StoredClosedPR, AnalyzedIssueConversation, ContributionGuidelines, IssueVettingResult, TrackedIssue, ShelvedPRRef, StatusOverride, AgentConfig, LocalRepoCache, ClosedPR, MergedPR, DailyDigest, AgentState, SearchSeenEntry, PickSnapshot, OvernightPrepared, OvernightRecord, OvernightImplementAttempt, SearchRotation, WorkClaim, WorkClaimKind, WorkClaimStatus, } from './state-schema.js';
6
6
  /** CI pipeline status for a PR's latest commit. */
7
7
  export type CIStatus = 'passing' | 'failing' | 'pending' | 'unknown';
8
8
  /**