@oss-autopilot/core 3.39.2 → 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.
@@ -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
  /**
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Work claims (#1856, #1852 gap 2): the pure rules over `state.workClaims`.
3
+ *
4
+ * A claim says "this item is being worked on somewhere": an `implementation`
5
+ * claim on an issue while a fix is being built, or a `pr` claim on a PR while
6
+ * a session does Tier 2 work on it. The rules here decide which claims are
7
+ * live, whether a new implementation may start (concurrency cap, one
8
+ * implementation per checkout), and how a live claim shows up in vetting.
9
+ * Persistence lives in `StateManager` (state.ts); the CLI surface is
10
+ * `commands/work.ts`.
11
+ *
12
+ * Expiry is compared against the reading machine's clock. Clock skew between
13
+ * machines is minutes at most, against TTLs of hours, so a claim never looks
14
+ * expired on one machine while another still relies on it in any way that
15
+ * matters; a claim that is re-issued (`work claim` again) gets a fresh
16
+ * `expiresAt`.
17
+ */
18
+ import type { WorkClaim, WorkClaimKind } from './state-schema.js';
19
+ /** Default claim lifetime per kind, in hours. */
20
+ export declare const WORK_CLAIM_DEFAULT_TTL_HOURS: Readonly<Record<WorkClaimKind, number>>;
21
+ /** Longest TTL `work claim --ttl` accepts, in hours (one week). */
22
+ export declare const WORK_CLAIM_MAX_TTL_HOURS = 168;
23
+ /**
24
+ * How long a finished implementation stays collectable, in hours (one week).
25
+ * `work finish` extends `expiresAt` to at least `finishedAt` plus this, so a
26
+ * branch finished late on a 24-hour claim is still offered the next morning.
27
+ */
28
+ export declare const WORK_CLAIM_FINISHED_TTL_HOURS = 168;
29
+ /** Identity of the item a claim is on: `owner/repo#number`, or the raw URL when it does not parse. */
30
+ export declare function workClaimKey(url: string): string;
31
+ /** Whether a claim is still live at `nowMs`. An unparseable `expiresAt` counts as expired. */
32
+ export declare function isWorkClaimActive(claim: Pick<WorkClaim, 'expiresAt'>, nowMs?: number): boolean;
33
+ /** The live claims, in stored order. */
34
+ export declare function activeWorkClaims(claims: readonly WorkClaim[], nowMs?: number): WorkClaim[];
35
+ /** The live claim on `url`, if any. */
36
+ export declare function findWorkClaim(claims: readonly WorkClaim[], url: string, nowMs?: number): WorkClaim | undefined;
37
+ /**
38
+ * The live claim on `url` that a session other than `session` holds. Such a
39
+ * claim blocks `work claim` unless the caller passes `--takeover`: a second
40
+ * session must decide to take an item over, never do it by accident.
41
+ */
42
+ export declare function heldByOtherSession(claims: readonly WorkClaim[], url: string, session: string, nowMs?: number): WorkClaim | undefined;
43
+ /**
44
+ * The claim as `work finish` records it: `finished`, stamped `finishedAt`,
45
+ * and kept at least {@link WORK_CLAIM_FINISHED_TTL_HOURS} past `at` so the
46
+ * branch stays collectable (a longer `expiresAt` already on the claim is kept).
47
+ */
48
+ export declare function finishWorkClaim(claim: WorkClaim, at: string): WorkClaim;
49
+ /** Live implementation claims whose branch is ready to collect. */
50
+ export declare function finishedImplementations(claims: readonly WorkClaim[], nowMs?: number): WorkClaim[];
51
+ /** Live implementation claims still running. */
52
+ export declare function runningImplementations(claims: readonly WorkClaim[], nowMs?: number): WorkClaim[];
53
+ /** One checkout path for comparison: absolute and normalized (`path.resolve` also drops trailing separators). */
54
+ export declare function normalizeWorktreePath(worktree: string): string;
55
+ /** Why a new implementation claim may not start. */
56
+ export interface ImplementationClaimConflict {
57
+ reason: 'cap' | 'worktree';
58
+ message: string;
59
+ /** The claims that block the new one. */
60
+ blocking: WorkClaim[];
61
+ }
62
+ /** The location fields of a claim that identify its checkout. */
63
+ export type CheckoutLocation = Pick<WorkClaim, 'worktree' | 'host' | 'machineId'>;
64
+ /**
65
+ * Check whether an implementation claim may start (#1856): at most
66
+ * `maxConcurrentImplementations` implementations run at once (0 = no cap),
67
+ * and no two live implementations share a checkout (the same directory on
68
+ * the same machine; see {@link isSameCheckout}). A claim already held on the
69
+ * same item is being renewed or taken over, so it never blocks itself.
70
+ * Returns null when the claim may proceed.
71
+ */
72
+ export declare function checkImplementationClaim(claims: readonly WorkClaim[], next: {
73
+ url: string;
74
+ } & CheckoutLocation, maxConcurrentImplementations: number, nowMs?: number): ImplementationClaimConflict | null;
75
+ /** Age of a claim as "12 min" / "3 h" / "2 d"; "0 min" for a future or unparseable start. */
76
+ export declare function workClaimAge(claim: Pick<WorkClaim, 'startedAt'>, nowMs?: number): string;
77
+ /** One-line description of a claim for menus and vet reasons, e.g. "implementation claimed in session air/1207 (12 min, running)". */
78
+ export declare function describeWorkClaim(claim: WorkClaim, nowMs?: number): string;
79
+ /**
80
+ * Vet-side dedup (#1856): an issue under a live implementation claim is
81
+ * skipped the way an issue with a linked PR is. Returns the vet fields to
82
+ * merge, or null when the issue is unclaimed. The skip reason contains the
83
+ * word "claimed" so `vet-list`'s status classifier files it as claimed.
84
+ */
85
+ export declare function workClaimVetFields(claims: readonly WorkClaim[], issueUrl: string, nowMs?: number): {
86
+ recommendation: 'skip';
87
+ reasonsToSkip: string[];
88
+ workClaim: WorkClaim;
89
+ } | null;
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Work claims (#1856, #1852 gap 2): the pure rules over `state.workClaims`.
3
+ *
4
+ * A claim says "this item is being worked on somewhere": an `implementation`
5
+ * claim on an issue while a fix is being built, or a `pr` claim on a PR while
6
+ * a session does Tier 2 work on it. The rules here decide which claims are
7
+ * live, whether a new implementation may start (concurrency cap, one
8
+ * implementation per checkout), and how a live claim shows up in vetting.
9
+ * Persistence lives in `StateManager` (state.ts); the CLI surface is
10
+ * `commands/work.ts`.
11
+ *
12
+ * Expiry is compared against the reading machine's clock. Clock skew between
13
+ * machines is minutes at most, against TTLs of hours, so a claim never looks
14
+ * expired on one machine while another still relies on it in any way that
15
+ * matters; a claim that is re-issued (`work claim` again) gets a fresh
16
+ * `expiresAt`.
17
+ */
18
+ import * as fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { issueRefKey } from './urls.js';
21
+ /** Default claim lifetime per kind, in hours. */
22
+ export const WORK_CLAIM_DEFAULT_TTL_HOURS = {
23
+ implementation: 24,
24
+ pr: 12,
25
+ };
26
+ /** Longest TTL `work claim --ttl` accepts, in hours (one week). */
27
+ export const WORK_CLAIM_MAX_TTL_HOURS = 168;
28
+ /**
29
+ * How long a finished implementation stays collectable, in hours (one week).
30
+ * `work finish` extends `expiresAt` to at least `finishedAt` plus this, so a
31
+ * branch finished late on a 24-hour claim is still offered the next morning.
32
+ */
33
+ export const WORK_CLAIM_FINISHED_TTL_HOURS = 168;
34
+ /** Identity of the item a claim is on: `owner/repo#number`, or the raw URL when it does not parse. */
35
+ export function workClaimKey(url) {
36
+ return issueRefKey(url) ?? url.trim().toLowerCase();
37
+ }
38
+ /** Whether a claim is still live at `nowMs`. An unparseable `expiresAt` counts as expired. */
39
+ export function isWorkClaimActive(claim, nowMs = Date.now()) {
40
+ const expires = Date.parse(claim.expiresAt);
41
+ return Number.isFinite(expires) && expires > nowMs;
42
+ }
43
+ /** The live claims, in stored order. */
44
+ export function activeWorkClaims(claims, nowMs = Date.now()) {
45
+ return claims.filter((claim) => isWorkClaimActive(claim, nowMs));
46
+ }
47
+ /** The live claim on `url`, if any. */
48
+ export function findWorkClaim(claims, url, nowMs = Date.now()) {
49
+ const key = workClaimKey(url);
50
+ return activeWorkClaims(claims, nowMs).find((claim) => workClaimKey(claim.url) === key);
51
+ }
52
+ /**
53
+ * The live claim on `url` that a session other than `session` holds. Such a
54
+ * claim blocks `work claim` unless the caller passes `--takeover`: a second
55
+ * session must decide to take an item over, never do it by accident.
56
+ */
57
+ export function heldByOtherSession(claims, url, session, nowMs = Date.now()) {
58
+ const existing = findWorkClaim(claims, url, nowMs);
59
+ if (existing === undefined || existing.session === session)
60
+ return undefined;
61
+ return existing;
62
+ }
63
+ /**
64
+ * The claim as `work finish` records it: `finished`, stamped `finishedAt`,
65
+ * and kept at least {@link WORK_CLAIM_FINISHED_TTL_HOURS} past `at` so the
66
+ * branch stays collectable (a longer `expiresAt` already on the claim is kept).
67
+ */
68
+ export function finishWorkClaim(claim, at) {
69
+ const extended = new Date(Date.parse(at) + WORK_CLAIM_FINISHED_TTL_HOURS * 3_600_000);
70
+ const current = Date.parse(claim.expiresAt);
71
+ const expiresAt = Number.isFinite(current) && current > extended.getTime() ? claim.expiresAt : extended.toISOString();
72
+ return { ...claim, status: 'finished', finishedAt: at, expiresAt };
73
+ }
74
+ /** Live implementation claims whose branch is ready to collect. */
75
+ export function finishedImplementations(claims, nowMs = Date.now()) {
76
+ return activeWorkClaims(claims, nowMs).filter((c) => c.kind === 'implementation' && c.status === 'finished');
77
+ }
78
+ /** Live implementation claims still running. */
79
+ export function runningImplementations(claims, nowMs = Date.now()) {
80
+ return activeWorkClaims(claims, nowMs).filter((c) => c.kind === 'implementation' && c.status === 'running');
81
+ }
82
+ /** One checkout path for comparison: absolute and normalized (`path.resolve` also drops trailing separators). */
83
+ export function normalizeWorktreePath(worktree) {
84
+ return path.resolve(worktree.trim());
85
+ }
86
+ /**
87
+ * Legacy rule for claims written before `machineId` existed: a path only
88
+ * identifies a checkout on one host, so claims from different hosts never
89
+ * share one. A claim without `host` is compared on the path alone.
90
+ */
91
+ function isSameHost(a, b) {
92
+ return a === undefined || b === undefined || a === b;
93
+ }
94
+ /**
95
+ * The canonical form of a normalized path on this machine: its real path
96
+ * (symlinks resolved) when it exists here, else the normalized path itself.
97
+ */
98
+ function canonicalLocalPath(normalized) {
99
+ try {
100
+ return fs.realpathSync(normalized);
101
+ }
102
+ catch {
103
+ return normalized;
104
+ }
105
+ }
106
+ /**
107
+ * Whether `claim`'s checkout is the directory `wanted` (already normalized).
108
+ *
109
+ * When both claims carry a `machineId`, that decides which machine the path
110
+ * is on: different ids never conflict, whatever the path or host, and on the
111
+ * same id the paths are compared canonically ({@link canonicalLocalPath}),
112
+ * so a renamed host (`air` to `air-2`) or a symlinked path still refuses a
113
+ * second implementation in a checkout in use. A claim without an id on
114
+ * either side (written before the field existed, or by a machine whose id
115
+ * file is unreadable) falls back to the hostname rule: the same normalized
116
+ * path on the same `host`, with no real-path resolution, since the stored
117
+ * path may be another machine's.
118
+ */
119
+ function isSameCheckout(claim, wanted, next) {
120
+ if (!claim.worktree)
121
+ return false;
122
+ const theirs = normalizeWorktreePath(claim.worktree);
123
+ if (claim.machineId !== undefined && next.machineId !== undefined) {
124
+ if (claim.machineId !== next.machineId)
125
+ return false;
126
+ return canonicalLocalPath(theirs) === canonicalLocalPath(wanted);
127
+ }
128
+ return isSameHost(claim.host, next.host) && theirs === wanted;
129
+ }
130
+ /**
131
+ * Check whether an implementation claim may start (#1856): at most
132
+ * `maxConcurrentImplementations` implementations run at once (0 = no cap),
133
+ * and no two live implementations share a checkout (the same directory on
134
+ * the same machine; see {@link isSameCheckout}). A claim already held on the
135
+ * same item is being renewed or taken over, so it never blocks itself.
136
+ * Returns null when the claim may proceed.
137
+ */
138
+ export function checkImplementationClaim(claims, next, maxConcurrentImplementations, nowMs = Date.now()) {
139
+ const key = workClaimKey(next.url);
140
+ const others = activeWorkClaims(claims, nowMs).filter((claim) => claim.kind === 'implementation' && workClaimKey(claim.url) !== key);
141
+ if (next.worktree !== undefined) {
142
+ const wanted = normalizeWorktreePath(next.worktree);
143
+ const sharing = others.filter((claim) => isSameCheckout(claim, wanted, next));
144
+ if (sharing.length > 0) {
145
+ const holder = sharing[0];
146
+ return {
147
+ reason: 'worktree',
148
+ blocking: sharing,
149
+ message: `Checkout ${wanted} already hosts an implementation of ${holder.url} ` +
150
+ `(session ${holder.session}, ${holder.status}). Use a separate worktree, ` +
151
+ `or finish or release that claim first.`,
152
+ };
153
+ }
154
+ }
155
+ const running = others.filter((claim) => claim.status === 'running');
156
+ if (maxConcurrentImplementations > 0 && running.length >= maxConcurrentImplementations) {
157
+ const list = running.map((claim) => `${claim.url} (session ${claim.session})`).join(', ');
158
+ return {
159
+ reason: 'cap',
160
+ blocking: running,
161
+ message: `Implementation cap reached: ${running.length} of ${maxConcurrentImplementations} running (${list}). ` +
162
+ `Collect or release one, or raise it with \`setup --set maxConcurrentImplementations=N\`.`,
163
+ };
164
+ }
165
+ return null;
166
+ }
167
+ /** Age of a claim as "12 min" / "3 h" / "2 d"; "0 min" for a future or unparseable start. */
168
+ export function workClaimAge(claim, nowMs = Date.now()) {
169
+ const started = Date.parse(claim.startedAt);
170
+ const minutes = Number.isFinite(started) ? Math.max(0, Math.floor((nowMs - started) / 60_000)) : 0;
171
+ if (minutes < 60)
172
+ return `${minutes} min`;
173
+ if (minutes < 24 * 60)
174
+ return `${Math.floor(minutes / 60)} h`;
175
+ return `${Math.floor(minutes / (24 * 60))} d`;
176
+ }
177
+ /** One-line description of a claim for menus and vet reasons, e.g. "implementation claimed in session air/1207 (12 min, running)". */
178
+ export function describeWorkClaim(claim, nowMs = Date.now()) {
179
+ return `${claim.kind} claimed in session ${claim.session} (${workClaimAge(claim, nowMs)}, ${claim.status})`;
180
+ }
181
+ /**
182
+ * Vet-side dedup (#1856): an issue under a live implementation claim is
183
+ * skipped the way an issue with a linked PR is. Returns the vet fields to
184
+ * merge, or null when the issue is unclaimed. The skip reason contains the
185
+ * word "claimed" so `vet-list`'s status classifier files it as claimed.
186
+ */
187
+ export function workClaimVetFields(claims, issueUrl, nowMs = Date.now()) {
188
+ const claim = findWorkClaim(claims, issueUrl, nowMs);
189
+ if (!claim || claim.kind !== 'implementation')
190
+ return null;
191
+ return {
192
+ recommendation: 'skip',
193
+ reasonsToSkip: [`Already being implemented: ${describeWorkClaim(claim, nowMs)}`],
194
+ workClaim: claim,
195
+ };
196
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { z, type ZodType } from 'zod';
6
6
  import type { AttentionSummary } from '../core/pr-attention.js';
7
- import type { FetchedPR, DailyDigest, AgentState, RepoGroup, CommentedIssue, ShelvedPRRef, SearchPriority, CapacityAssessment, ActionableIssue, CompactActionableIssue, ActionMenu } from '../core/types.js';
7
+ import type { FetchedPR, DailyDigest, AgentState, RepoGroup, CommentedIssue, ShelvedPRRef, SearchPriority, CapacityAssessment, ActionableIssue, CompactActionableIssue, ActionMenu, WorkClaim } from '../core/types.js';
8
8
  import type { ContributionStats } from '../core/stats.js';
9
9
  import type { RepoCapStatus } from '../core/repo-cap.js';
10
10
  import type { PRCheckFailure } from '../core/pr-monitor.js';
@@ -185,6 +185,15 @@ export interface DailyOutput {
185
185
  * goldens are unchanged. See {@link ReviewedPRFollowUp}.
186
186
  */
187
187
  reviewedPRs?: ReviewedPRFollowUp[];
188
+ /**
189
+ * Live work claims (#1856, #1852): implementations running or finished in
190
+ * the background and PRs another session holds. The action menu shows them
191
+ * in its header, offers `collect_implementations` when one is `finished`,
192
+ * and treats a `pr` claim from another session as "handled in session X".
193
+ * Present only when at least one live claim exists, so goldens are
194
+ * unchanged. See {@link WorkClaim}.
195
+ */
196
+ workClaims?: WorkClaim[];
188
197
  }
189
198
  /** Work order for the host's background learnings extraction (#1696). */
190
199
  export interface PendingLearnings {
@@ -231,6 +240,8 @@ export interface CompactDailyOutput {
231
240
  mergedPRNotes?: MergedPRNotes[];
232
241
  /** Reviewed PRs with author activity since the review (#1857). See {@link DailyOutput.reviewedPRs}. */
233
242
  reviewedPRs?: ReviewedPRFollowUp[];
243
+ /** Live work claims (#1856, #1852). See {@link DailyOutput.workClaims}. */
244
+ workClaims?: WorkClaim[];
234
245
  }
235
246
  /**
236
247
  * Strip a full DailyOutput down to the compact subset (#763).
@@ -629,6 +640,20 @@ export declare const DailyOutputSchema: z.ZodObject<{
629
640
  latestActivityAt: z.ZodString;
630
641
  latestCommentAt: z.ZodOptional<z.ZodString>;
631
642
  }, z.core.$strip>>>;
643
+ workClaims: z.ZodOptional<z.ZodArray<z.ZodObject<{
644
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
645
+ url: z.ZodString;
646
+ session: z.ZodString;
647
+ startedAt: z.ZodString;
648
+ expiresAt: z.ZodString;
649
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
650
+ branch: z.ZodOptional<z.ZodString>;
651
+ worktree: z.ZodOptional<z.ZodString>;
652
+ host: z.ZodOptional<z.ZodString>;
653
+ machineId: z.ZodOptional<z.ZodString>;
654
+ runId: z.ZodOptional<z.ZodString>;
655
+ finishedAt: z.ZodOptional<z.ZodString>;
656
+ }, z.core.$loose>>>;
632
657
  }, z.core.$strip>;
633
658
  export declare const CompactDailyOutputSchema: z.ZodObject<{
634
659
  digest: z.ZodObject<{
@@ -859,6 +884,20 @@ export declare const CompactDailyOutputSchema: z.ZodObject<{
859
884
  latestActivityAt: z.ZodString;
860
885
  latestCommentAt: z.ZodOptional<z.ZodString>;
861
886
  }, z.core.$strip>>>;
887
+ workClaims: z.ZodOptional<z.ZodArray<z.ZodObject<{
888
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
889
+ url: z.ZodString;
890
+ session: z.ZodString;
891
+ startedAt: z.ZodString;
892
+ expiresAt: z.ZodString;
893
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
894
+ branch: z.ZodOptional<z.ZodString>;
895
+ worktree: z.ZodOptional<z.ZodString>;
896
+ host: z.ZodOptional<z.ZodString>;
897
+ machineId: z.ZodOptional<z.ZodString>;
898
+ runId: z.ZodOptional<z.ZodString>;
899
+ finishedAt: z.ZodOptional<z.ZodString>;
900
+ }, z.core.$loose>>>;
862
901
  }, z.core.$strip>;
863
902
  /** Per-repo open-PR cap status (core/repo-cap.ts). */
864
903
  export declare const RepoCapStatusSchema: z.ZodObject<{
@@ -1153,6 +1192,90 @@ export declare const InitOutputSchema: z.ZodObject<{
1153
1192
  message: z.ZodString;
1154
1193
  gistSyncWarning: z.ZodOptional<z.ZodString>;
1155
1194
  }, z.core.$strip>;
1195
+ export declare const WorkClaimOutputSchema: z.ZodObject<{
1196
+ claim: z.ZodObject<{
1197
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
1198
+ url: z.ZodString;
1199
+ session: z.ZodString;
1200
+ startedAt: z.ZodString;
1201
+ expiresAt: z.ZodString;
1202
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
1203
+ branch: z.ZodOptional<z.ZodString>;
1204
+ worktree: z.ZodOptional<z.ZodString>;
1205
+ host: z.ZodOptional<z.ZodString>;
1206
+ machineId: z.ZodOptional<z.ZodString>;
1207
+ runId: z.ZodOptional<z.ZodString>;
1208
+ finishedAt: z.ZodOptional<z.ZodString>;
1209
+ }, z.core.$loose>;
1210
+ outcome: z.ZodEnum<{
1211
+ claimed: "claimed";
1212
+ renewed: "renewed";
1213
+ "took-over": "took-over";
1214
+ }>;
1215
+ synced: z.ZodBoolean;
1216
+ gistSyncWarning: z.ZodOptional<z.ZodString>;
1217
+ }, z.core.$strip>;
1218
+ export declare const WorkFinishOutputSchema: z.ZodObject<{
1219
+ url: z.ZodString;
1220
+ claim: z.ZodNullable<z.ZodObject<{
1221
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
1222
+ url: z.ZodString;
1223
+ session: z.ZodString;
1224
+ startedAt: z.ZodString;
1225
+ expiresAt: z.ZodString;
1226
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
1227
+ branch: z.ZodOptional<z.ZodString>;
1228
+ worktree: z.ZodOptional<z.ZodString>;
1229
+ host: z.ZodOptional<z.ZodString>;
1230
+ machineId: z.ZodOptional<z.ZodString>;
1231
+ runId: z.ZodOptional<z.ZodString>;
1232
+ finishedAt: z.ZodOptional<z.ZodString>;
1233
+ }, z.core.$loose>>;
1234
+ gistSyncWarning: z.ZodOptional<z.ZodString>;
1235
+ }, z.core.$strip>;
1236
+ export declare const WorkReleaseOutputSchema: z.ZodObject<{
1237
+ released: z.ZodArray<z.ZodString>;
1238
+ gistSyncWarning: z.ZodOptional<z.ZodString>;
1239
+ }, z.core.$strip>;
1240
+ export declare const WorkListOutputSchema: z.ZodObject<{
1241
+ claims: z.ZodArray<z.ZodObject<{
1242
+ kind: z.ZodCustom<(string & {}) | "implementation" | "pr", (string & {}) | "implementation" | "pr">;
1243
+ url: z.ZodString;
1244
+ session: z.ZodString;
1245
+ startedAt: z.ZodString;
1246
+ expiresAt: z.ZodString;
1247
+ status: z.ZodCustom<"finished" | "running" | (string & {}), "finished" | "running" | (string & {})>;
1248
+ branch: z.ZodOptional<z.ZodString>;
1249
+ worktree: z.ZodOptional<z.ZodString>;
1250
+ host: z.ZodOptional<z.ZodString>;
1251
+ machineId: z.ZodOptional<z.ZodString>;
1252
+ runId: z.ZodOptional<z.ZodString>;
1253
+ finishedAt: z.ZodOptional<z.ZodString>;
1254
+ }, z.core.$loose>>;
1255
+ expiredCount: z.ZodNumber;
1256
+ now: z.ZodString;
1257
+ warnings: z.ZodOptional<z.ZodArray<z.ZodObject<{
1258
+ phase: z.ZodEnum<{
1259
+ fetch: "fetch";
1260
+ "merged-pr-notes": "merged-pr-notes";
1261
+ "reviewed-prs": "reviewed-prs";
1262
+ "closed-pr-status": "closed-pr-status";
1263
+ "merge-loop": "merge-loop";
1264
+ "repo-scores": "repo-scores";
1265
+ analytics: "analytics";
1266
+ partition: "partition";
1267
+ "dismiss-filter": "dismiss-filter";
1268
+ "gist-init": "gist-init";
1269
+ "gist-checkpoint": "gist-checkpoint";
1270
+ "gist-staleness": "gist-staleness";
1271
+ "state-load": "state-load";
1272
+ }>;
1273
+ operation: z.ZodString;
1274
+ message: z.ZodString;
1275
+ timestamp: z.ZodOptional<z.ZodString>;
1276
+ details: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1277
+ }, z.core.$strip>>>;
1278
+ }, z.core.$strip>;
1156
1279
  export declare const ManifestOutputSchema: z.ZodObject<{
1157
1280
  schemaVersion: z.ZodLiteral<1>;
1158
1281
  cliVersion: z.ZodString;
@@ -1826,6 +1949,12 @@ export interface VetOutput {
1826
1949
  * haven't been touched in 30+ days as revive opportunities.
1827
1950
  */
1828
1951
  linkedPR?: CandidateLinkedPR;
1952
+ /**
1953
+ * The live implementation claim on this issue (#1856), when a session is
1954
+ * already building a fix for it. The recommendation is then `skip` and
1955
+ * `reasonsToSkip` names the session; `vet-list` files the item as claimed.
1956
+ */
1957
+ workClaim?: WorkClaim;
1829
1958
  /**
1830
1959
  * Optional SLM pre-triage classification (#1122). Populated when the
1831
1960
  * user has set `slmTriageModel` and a local Ollama instance answered
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { z } from 'zod';
6
6
  import { fenceFetchedPR } from '../core/untrusted-content.js';
7
+ import { WorkClaimSchema } from '../core/state-schema.js';
7
8
  // Process-level gist degradation warning threaded into every JSON envelope
8
9
  // (#1433). The CLI preAction bootstrap sets it; one-shot processes never
9
10
  // clear it (the whole invocation runs degraded or it doesn't).
@@ -47,6 +48,7 @@ export function toCompactDailyOutput(output) {
47
48
  closedPRStatusUpdates: output.closedPRStatusUpdates,
48
49
  mergedPRNotes: output.mergedPRNotes,
49
50
  reviewedPRs: output.reviewedPRs,
51
+ workClaims: output.workClaims,
50
52
  };
51
53
  }
52
54
  /**
@@ -395,6 +397,7 @@ export const DailyOutputSchema = z.object({
395
397
  closedPRStatusUpdates: z.array(ClosedPRStatusUpdateSchema).optional(),
396
398
  mergedPRNotes: z.array(MergedPRNotesSchema).optional(),
397
399
  reviewedPRs: z.array(ReviewedPRFollowUpSchema).optional(),
400
+ workClaims: z.array(WorkClaimSchema).optional(),
398
401
  });
399
402
  export const CompactDailyOutputSchema = z.object({
400
403
  digest: DailyDigestCompactSchema,
@@ -412,6 +415,7 @@ export const CompactDailyOutputSchema = z.object({
412
415
  closedPRStatusUpdates: z.array(ClosedPRStatusUpdateSchema).optional(),
413
416
  mergedPRNotes: z.array(MergedPRNotesSchema).optional(),
414
417
  reviewedPRs: z.array(ReviewedPRFollowUpSchema).optional(),
418
+ workClaims: z.array(WorkClaimSchema).optional(),
415
419
  });
416
420
  // ── Search output schema (#1147) ─────────────────────────────────────
417
421
  const SearchPrioritySchema = z.enum(['merged_pr', 'preferred_org', 'starred', 'normal']);
@@ -607,6 +611,28 @@ export const InitOutputSchema = z.object({
607
611
  // Post-mutation Gist checkpoint failure (#1440). Optional: absent on clean runs.
608
612
  gistSyncWarning: z.string().optional(),
609
613
  });
614
+ // ── #1856 / #1852: work claims ───────────────────────────────────────
615
+ export const WorkClaimOutputSchema = z.object({
616
+ claim: WorkClaimSchema,
617
+ outcome: z.enum(['claimed', 'renewed', 'took-over']),
618
+ synced: z.boolean(),
619
+ gistSyncWarning: z.string().optional(),
620
+ });
621
+ export const WorkFinishOutputSchema = z.object({
622
+ url: z.string(),
623
+ claim: WorkClaimSchema.nullable(),
624
+ gistSyncWarning: z.string().optional(),
625
+ });
626
+ export const WorkReleaseOutputSchema = z.object({
627
+ released: z.array(z.string()),
628
+ gistSyncWarning: z.string().optional(),
629
+ });
630
+ export const WorkListOutputSchema = z.object({
631
+ claims: z.array(WorkClaimSchema),
632
+ expiredCount: z.number().int().nonnegative(),
633
+ now: z.string(),
634
+ warnings: z.array(DailyWarningSchema).optional(),
635
+ });
610
636
  // ── #1190: plugin → CLI contract ─────────────────────────────────────
611
637
  //
612
638
  // Pinned shape, checked by cli-registry.docs.test.ts at CI time, so the bundled
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.39.2",
3
+ "version": "3.40.0",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {