@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.
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { type ClosedPRStatusUpdate, type MergedPRNotes, type ReviewedPRFollowUp, type AttentionSummary, type DailyDigest, type CommentedIssue, type PRCheckFailure, type RepoGroup } from '../core/index.js';
9
+ import { type WorkClaim, type ClosedPRStatusUpdate, type MergedPRNotes, type ReviewedPRFollowUp, type AttentionSummary, type DailyDigest, type CommentedIssue, type PRCheckFailure, type RepoGroup } from '../core/index.js';
10
10
  import { type StrategyResult } from '../core/strategy.js';
11
11
  import { type DailyOutput, type DailyWarning, type CapacityAssessment, type ActionableIssue, type ActionMenu, type MergedPRListUpdate, type PendingLearnings } from '../formatters/json.js';
12
12
  export { applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, printDigest, CRITICAL_STATUSES, } from '../core/index.js';
@@ -68,6 +68,11 @@ export interface DailyCheckResult {
68
68
  * Raw excerpts here; `toDailyOutput` fences them.
69
69
  */
70
70
  reviewedPRs?: ReviewedPRFollowUp[];
71
+ /**
72
+ * Live work claims (#1856, #1852). Set only when at least one exists; see
73
+ * {@link DailyOutput.workClaims}.
74
+ */
75
+ workClaims?: WorkClaim[];
71
76
  }
72
77
  /**
73
78
  * Convert a full DailyCheckResult to the compact DailyOutput for JSON serialization (#287).
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { getStateManager, parseGitHubUrl, issueRefKey, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, GistConcurrencyError, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, collectEngagedIssues, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, selectClosedPRStatusCandidates, toClosedPRStatusUpdate, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, issueRefKey, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, GistConcurrencyError, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, collectEngagedIssues, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, selectClosedPRStatusCandidates, toClosedPRStatusUpdate, activeWorkClaims, finishedImplementations, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
11
  import { DEFAULT_CONCURRENCY, runWorkerPool } from '../core/concurrency.js';
12
12
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
@@ -520,12 +520,15 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
520
520
  // Close candidates are usually dormant and auto-shelved, so count them over
521
521
  // all open PRs (digest.openPRs includes shelved), not activePRs.
522
522
  const closeSuggested = digest.openPRs.filter(shouldSuggestClose).length;
523
+ // Live claims (#1856): read, never written, so an expired claim stays in
524
+ // state until the next `work` write prunes it.
525
+ const workClaims = activeWorkClaims(stateManager.getState().workClaims ?? []);
523
526
  const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues, { ...attention, closeSuggested }, unextractedMergeCount, closedPRStatusUpdates.length,
524
527
  // One action per entry the workflow handles on its own; covered
525
528
  // thanks-only entries ride along with their carrier.
526
529
  mergedPRNotes.filter((entry) => entry.ackCoveredBy === undefined).length,
527
530
  // Other people's PRs: a menu item, never a capacity or attention count.
528
- reviewedPRs.length);
531
+ reviewedPRs.length, finishedImplementations(workClaims).length);
529
532
  const repoGroups = groupPRsByRepo(activePRs);
530
533
  // Periodic strategy snapshot (#1270 Step 2). Cadence-gated to fire every
531
534
  // 30 days OR after 5+ PRs merge since the last snapshot, whichever comes
@@ -558,6 +561,7 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
558
561
  failures,
559
562
  warnings,
560
563
  strategySummary,
564
+ ...(workClaims.length > 0 && { workClaims }),
561
565
  };
562
566
  }
563
567
  const CLOSED_PR_STATUS_OPERATION = 'closed-PR status updates';
@@ -786,6 +790,7 @@ export function toDailyOutput(result) {
786
790
  ...(result.closedPRStatusUpdates && { closedPRStatusUpdates: result.closedPRStatusUpdates }),
787
791
  ...(result.mergedPRNotes && { mergedPRNotes: result.mergedPRNotes.map((entry) => fenceMergedPRNotes(entry)) }),
788
792
  ...(result.reviewedPRs && { reviewedPRs: result.reviewedPRs.map((entry) => fenceReviewedPR(entry)) }),
793
+ ...(result.workClaims && { workClaims: result.workClaims }),
789
794
  };
790
795
  }
791
796
  /**
@@ -50,6 +50,8 @@ export { runMove } from './move.js';
50
50
  export { runDismiss } from './dismiss.js';
51
51
  /** Restore a dismissed issue to notifications. */
52
52
  export { runUndismiss } from './dismiss.js';
53
+ /** Work claims (#1856, #1852): record, finish, release and list in-flight implementations and PR work. */
54
+ export { runWorkClaim, runWorkFinish, runWorkRelease, runWorkList } from './work.js';
53
55
  /** Fetch comments for tracked issues/PRs. */
54
56
  export { runComments } from './comments.js';
55
57
  /** Post a comment to a GitHub issue or PR. */
@@ -104,6 +106,7 @@ export type { ConfigOutput, DetectFormattersOutput, ParseIssueListOutput, Parsed
104
106
  export type { MoveOutput, MoveTarget } from './move.js';
105
107
  export type { GuidelinesListOutput, GuidelinesViewOutput, GuidelinesStoreOutput, GuidelinesResetOutput, FetchCorpusOutput, } from './guidelines.js';
106
108
  export type { DismissOutput, UndismissOutput } from './dismiss.js';
109
+ export type { WorkClaimOptions, WorkClaimOutcome, WorkClaimOutput, WorkFinishOptions, WorkFinishOutput, WorkReleaseOptions, WorkReleaseOutput, WorkListOutput, } from './work.js';
107
110
  export type { InitOutput } from './init.js';
108
111
  export type { ConfigSetOutput, ConfigCommandOutput } from './config.js';
109
112
  export type { SetupSetOutput, SetupCompleteOutput, SetupRequiredOutput, SetupOutput, CheckSetupOutput, } from './setup.js';
@@ -52,6 +52,8 @@ export { runMove } from './move.js';
52
52
  export { runDismiss } from './dismiss.js';
53
53
  /** Restore a dismissed issue to notifications. */
54
54
  export { runUndismiss } from './dismiss.js';
55
+ /** Work claims (#1856, #1852): record, finish, release and list in-flight implementations and PR work. */
56
+ export { runWorkClaim, runWorkFinish, runWorkRelease, runWorkList } from './work.js';
55
57
  // ── Issue & Comment Management ──────────────────────────────────────────────
56
58
  /** Fetch comments for tracked issues/PRs. */
57
59
  export { runComments } from './comments.js';
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { reposAtCap } from '../core/repo-cap.js';
6
6
  import { createScout } from '@oss-scout/core';
7
- import { getStateManager, isLinkedPRStalled, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
7
+ import { activeWorkClaims, getStateManager, isLinkedPRStalled, parseGitHubUrl, requireGitHubToken, } from '../core/index.js';
8
8
  import { SearchRotationSchema } from '../core/state-schema.js';
9
9
  import { computeStrategy } from '../core/strategy.js';
10
10
  import { loadSkippedIssuesDetailed } from './skip-file-parser.js';
@@ -104,6 +104,7 @@ export function buildScoutState(diagnostics) {
104
104
  if (skippedUrls.has(url) || !ISSUE_URL_PATTERN.test(url))
105
105
  continue;
106
106
  const parsed = parseGitHubUrl(url);
107
+ skippedUrls.add(url);
107
108
  skippedIssues.push({
108
109
  url,
109
110
  repo: parsed ? `${parsed.owner}/${parsed.repo}` : '',
@@ -115,6 +116,27 @@ export function buildScoutState(diagnostics) {
115
116
  permanent: true,
116
117
  });
117
118
  }
119
+ // Issues under a live implementation claim (#1856) are skipped the way
120
+ // issues with a linked PR are: a session is already building the fix, here
121
+ // or on another machine. Only live claims are forwarded, so the issue comes
122
+ // back once the claim is released or expires. `pr` claims sit on PR URLs,
123
+ // which scout cannot surface.
124
+ const liveClaims = activeWorkClaims(state.workClaims ?? []);
125
+ for (const claim of liveClaims) {
126
+ if (claim.kind !== 'implementation' || skippedUrls.has(claim.url) || !ISSUE_URL_PATTERN.test(claim.url))
127
+ continue;
128
+ const parsed = parseGitHubUrl(claim.url);
129
+ skippedUrls.add(claim.url);
130
+ skippedIssues.push({
131
+ url: claim.url,
132
+ repo: parsed ? `${parsed.owner}/${parsed.repo}` : '',
133
+ number: parsed?.number ?? 0,
134
+ title: '',
135
+ skippedAt: claim.startedAt,
136
+ reason: `implementation in progress (session ${claim.session})`,
137
+ permanent: true,
138
+ });
139
+ }
118
140
  // Strategy-derived personalization (#1464). `computeStrategy` returns null
119
141
  // below the merged-PR floor — empty lists then read as "no bias" on scout's
120
142
  // side. Baking the bias into the preferences (rather than only per-call
@@ -70,7 +70,8 @@ export async function runSetup(options) {
70
70
  }
71
71
  case 'maxActivePRs':
72
72
  case 'maxOpenPRsPerRepo':
73
- case 'maxOpenPRsColdRepo': {
73
+ case 'maxOpenPRsColdRepo':
74
+ case 'maxConcurrentImplementations': {
74
75
  const limit = parseNonNegativeInt(value, key);
75
76
  stateManager.updateConfig({ [key]: limit });
76
77
  results[key] = String(limit);
@@ -9,7 +9,7 @@ import { detectIssueList } from './startup.js';
9
9
  import { computeSuccessGrade, gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
10
10
  import { repoCapField } from '../core/repo-cap.js';
11
11
  import { ValidationError } from '../core/errors.js';
12
- import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, traitsFromVerification, isFirstInRepo, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, RULED_OUT_VERDICTS, } from '../core/index.js';
12
+ import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, traitsFromVerification, isFirstInRepo, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, RULED_OUT_VERDICTS, workClaimVetFields, } from '../core/index.js';
13
13
  const UNKNOWN_GRADE = computeSuccessGrade({ avgResponseDays: null, mergeRate: null, daysSinceLastCommit: null });
14
14
  const KNOWN_SKIP_REASONS = new Set([
15
15
  'issue_closed',
@@ -261,6 +261,23 @@ export async function runVetList(options = {}) {
261
261
  };
262
262
  }
263
263
  async function processItem(item, verification) {
264
+ // A fix for this issue is already being built in some session (#1856):
265
+ // file it as claimed without grading it, the way a linked PR rules an
266
+ // issue out. The row comes back once the claim is released or expires.
267
+ const claimed = workClaimVetFields(getStateManager().getState().workClaims ?? [], item.url);
268
+ if (claimed) {
269
+ return {
270
+ issue: { repo: item.repo, number: item.number, title: item.title, url: item.url, labels: [] },
271
+ recommendation: 'skip',
272
+ reasonsToApprove: [],
273
+ reasonsToSkip: claimed.reasonsToSkip,
274
+ projectHealth: {},
275
+ vettingResult: {},
276
+ grade: UNKNOWN_GRADE,
277
+ listStatus: 'claimed',
278
+ workClaim: claimed.workClaim,
279
+ };
280
+ }
264
281
  // No authoritative verdict for this row: either verify errored, or the URL
265
282
  // was never enrolled (parse-list also accepts PR URLs, which `verify-issue`
266
283
  // can't classify). Either way `listStatus` falls back to scout's heuristic,
@@ -6,7 +6,7 @@ import { adaptScoutLinkedPR, buildCandidateLinkedPR, createAutopilotScout } from
6
6
  import { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
7
7
  import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
8
8
  import { repoCapField } from '../core/repo-cap.js';
9
- import { getStateManager, getOctokit, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, fetchIssueVerification, RULED_OUT_VERDICTS, traitsFromVerification, isFirstInRepo, requireGitHubToken, errorMessage, warn, } from '../core/index.js';
9
+ import { getStateManager, getOctokit, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, fetchIssueVerification, RULED_OUT_VERDICTS, traitsFromVerification, isFirstInRepo, requireGitHubToken, errorMessage, warn, workClaimVetFields, } from '../core/index.js';
10
10
  /**
11
11
  * Vet a specific GitHub issue for claimability and project health.
12
12
  *
@@ -51,6 +51,12 @@ export async function runVet(options) {
51
51
  grade,
52
52
  ...repoCapField(getStateManager().getState(), candidate.issue.repo),
53
53
  };
54
+ // A fix already being built somewhere (#1856) overrides the grade: the
55
+ // issue is skipped like one with a linked PR, and no pick is recorded.
56
+ const claimed = workClaimVetFields(getStateManager().getState().workClaims ?? [], options.issueUrl);
57
+ if (claimed) {
58
+ return { ...output, ...claimed, reasonsToSkip: [...output.reasonsToSkip, ...claimed.reasonsToSkip] };
59
+ }
54
60
  const pick = await pickFor(output);
55
61
  return { ...output, ...(await persistPickSnapshots(getStateManager(), pick ? [pick] : [])) };
56
62
  }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Work claim commands (#1856, #1852 gap 2): `work claim`, `work finish`,
3
+ * `work release`, `work list`.
4
+ *
5
+ * A claim records that some session is working an item, so other sessions
6
+ * (same machine or another one via the Gist) see it instead of starting the
7
+ * same work. `implementation` claims sit on issue URLs while a fix is built
8
+ * in the background; `pr` claims sit on PR URLs while a session does Tier 2
9
+ * work there. Rules live in `core/work-claims.ts`; this file validates input,
10
+ * applies the state mutation and pushes it to the Gist.
11
+ *
12
+ * Each `run*` has a `*Work(stateManager, options)` twin that takes the
13
+ * manager explicitly, so the Gist concurrency tests can drive two machines
14
+ * through the real command path.
15
+ */
16
+ import { type StateManager, type WorkClaim, type WorkClaimKind } from '../core/index.js';
17
+ import { type DailyWarning } from '../formatters/json.js';
18
+ export interface WorkClaimOptions {
19
+ url: string;
20
+ kind: WorkClaimKind;
21
+ /** Name of the session taking the claim, e.g. `air/20261102T120733-3f9a`. */
22
+ session: string;
23
+ branch?: string;
24
+ /** Checkout the implementation runs in; required for a local implementation (one implementation per checkout). */
25
+ worktree?: string;
26
+ /** Remote worker run id; required for an implementation with no local worktree. */
27
+ runId?: string;
28
+ /** Claim lifetime in hours; defaults per kind (implementation 24, pr 12). */
29
+ ttlHours?: number;
30
+ /** Replace a live claim another session holds on the item. Without it such a claim is refused. */
31
+ takeover?: boolean;
32
+ }
33
+ /** What `work claim` did to the item: nothing was there, this session renewed its own claim, or another session's claim was replaced. */
34
+ export type WorkClaimOutcome = 'claimed' | 'renewed' | 'took-over';
35
+ export interface WorkClaimOutput {
36
+ claim: WorkClaim;
37
+ outcome: WorkClaimOutcome;
38
+ /**
39
+ * False when the claim exists on this machine only: the Gist push failed
40
+ * (`gistSyncWarning`) or Gist persistence is degraded. Other machines
41
+ * cannot see it, so a workflow should not treat the item as reserved.
42
+ */
43
+ synced: boolean;
44
+ /** Set when the post-mutation Gist checkpoint failed; the local mutation succeeded (#1370). */
45
+ gistSyncWarning?: string;
46
+ }
47
+ export interface WorkFinishOptions {
48
+ url: string;
49
+ /** When given, the live claim must belong to this session; a mismatch is refused instead of finishing someone else's run. */
50
+ session?: string;
51
+ }
52
+ export interface WorkFinishOutput {
53
+ url: string;
54
+ /** The claim as marked finished, or null when no live claim exists on the item. */
55
+ claim: WorkClaim | null;
56
+ gistSyncWarning?: string;
57
+ }
58
+ export interface WorkReleaseOptions {
59
+ url?: string;
60
+ /** Release every claim this session holds (optionally only `kind`). */
61
+ session?: string;
62
+ kind?: WorkClaimKind;
63
+ }
64
+ export interface WorkReleaseOutput {
65
+ /** URLs of the live claims released, in stored order. */
66
+ released: string[];
67
+ gistSyncWarning?: string;
68
+ }
69
+ export interface WorkListOutput {
70
+ /** Live claims, in stored order. */
71
+ claims: WorkClaim[];
72
+ /** Stored claims past `expiresAt`; pruned by the next claim write. */
73
+ expiredCount: number;
74
+ /** When the list was computed; `expiresAt` values compare against this. */
75
+ now: string;
76
+ /** Set when the list comes from a stale copy: the Gist refresh failed, so another machine's claims may be missing (#1193). */
77
+ warnings?: DailyWarning[];
78
+ }
79
+ /**
80
+ * Take (or renew) a claim on an item (#1856, #1852).
81
+ *
82
+ * An implementation claim needs a `worktree` or a `runId` so the
83
+ * one-implementation-per-checkout rule has something to compare, and it is
84
+ * refused when `maxConcurrentImplementations` running implementations
85
+ * already exist or another live implementation uses the same checkout on
86
+ * this machine. A live claim another session holds is refused unless `takeover`
87
+ * is set (the workflow asks first); this session's own claim is renewed.
88
+ *
89
+ * In Gist mode the checks run again on the Gist's copy when the push
90
+ * conflicts with another machine: if that copy refuses the claim, nothing is
91
+ * recorded and the refusal is thrown. The claim is `synced: false` when it
92
+ * exists locally only.
93
+ *
94
+ * @throws {ValidationError} On a malformed URL or kind mismatch, a missing
95
+ * location for an implementation, an out-of-range TTL, or when another
96
+ * session's claim, the cap or the checkout rule blocks the claim.
97
+ */
98
+ export declare function runWorkClaim(options: WorkClaimOptions): Promise<WorkClaimOutput>;
99
+ /** {@link runWorkClaim} against an explicit manager. */
100
+ export declare function claimWork(stateManager: StateManager, options: WorkClaimOptions): Promise<WorkClaimOutput>;
101
+ /**
102
+ * Mark the live claim on `url` finished (#1856): the implementation's branch
103
+ * is ready to collect. The claim stays (with its expiry extended to at least
104
+ * a week) until it is released or expires, so the action menu can offer
105
+ * "Collect finished implementations" and search keeps skipping the issue.
106
+ * With `session`, a claim another session holds is refused rather than
107
+ * finished on its behalf.
108
+ *
109
+ * @throws {ValidationError} When `session` is given and the live claim belongs to another session.
110
+ */
111
+ export declare function runWorkFinish(options: WorkFinishOptions): Promise<WorkFinishOutput>;
112
+ /** {@link runWorkFinish} against an explicit manager. */
113
+ export declare function finishWork(stateManager: StateManager, options: WorkFinishOptions): Promise<WorkFinishOutput>;
114
+ /**
115
+ * Drop claims (#1856, #1852): the claim on `url`, or every claim `session`
116
+ * holds (Session End releases that session's `pr` claims with
117
+ * `{ session, kind: 'pr' }`). Releasing an item nobody holds is not an
118
+ * error: `released` is simply empty.
119
+ *
120
+ * @throws {ValidationError} When neither `url` nor `session` is given.
121
+ */
122
+ export declare function runWorkRelease(options: WorkReleaseOptions): Promise<WorkReleaseOutput>;
123
+ /** {@link runWorkRelease} against an explicit manager. */
124
+ export declare function releaseWork(stateManager: StateManager, options: WorkReleaseOptions): Promise<WorkReleaseOutput>;
125
+ /**
126
+ * The live claims (#1856). Read-only: expired claims are counted, not
127
+ * pruned. In Gist mode the state is refreshed first (throttled to once per
128
+ * 30 s by the store; a failed fetch serves the cached copy and sets a
129
+ * `warnings` entry) so a claim another machine pushed since this process
130
+ * loaded state is visible.
131
+ */
132
+ export declare function runWorkList(): Promise<WorkListOutput>;
133
+ /** {@link runWorkList} against an explicit manager. */
134
+ export declare function listWork(stateManager: StateManager): Promise<WorkListOutput>;
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Work claim commands (#1856, #1852 gap 2): `work claim`, `work finish`,
3
+ * `work release`, `work list`.
4
+ *
5
+ * A claim records that some session is working an item, so other sessions
6
+ * (same machine or another one via the Gist) see it instead of starting the
7
+ * same work. `implementation` claims sit on issue URLs while a fix is built
8
+ * in the background; `pr` claims sit on PR URLs while a session does Tier 2
9
+ * work there. Rules live in `core/work-claims.ts`; this file validates input,
10
+ * applies the state mutation and pushes it to the Gist.
11
+ *
12
+ * Each `run*` has a `*Work(stateManager, options)` twin that takes the
13
+ * manager explicitly, so the Gist concurrency tests can drive two machines
14
+ * through the real command path.
15
+ */
16
+ import os from 'node:os';
17
+ import { WORK_CLAIM_DEFAULT_TTL_HOURS, WORK_CLAIM_FINISHED_TTL_HOURS, WORK_CLAIM_MAX_TTL_HOURS, checkImplementationClaim, describeWorkClaim, findWorkClaim, getMachineId, getStateManager, heldByOtherSession, maybeCheckpoint, normalizeWorktreePath, } from '../core/index.js';
18
+ import { ValidationError } from '../core/errors.js';
19
+ import { buildStalenessWarning } from '../formatters/json.js';
20
+ import { ISSUE_URL_PATTERN, PR_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
21
+ const MODULE = 'work';
22
+ /** Longest free-text field (`session`, `branch`, `worktree`, `runId`) accepted, in characters. */
23
+ const MAX_FIELD_LENGTH = 500;
24
+ /** Control characters (Unicode category Cc), which would break the one-line menu rendering of a claim. */
25
+ const CONTROL_CHARACTERS = /\p{Cc}/u;
26
+ function isoAt(ms) {
27
+ const at = new Date(ms);
28
+ return at.toISOString();
29
+ }
30
+ function validateField(name, value) {
31
+ if (value === undefined)
32
+ return undefined;
33
+ const trimmed = value.trim();
34
+ if (trimmed.length === 0)
35
+ throw new ValidationError(`--${name} must not be empty`);
36
+ if (trimmed.length > MAX_FIELD_LENGTH)
37
+ throw new ValidationError(`--${name} is longer than ${MAX_FIELD_LENGTH} characters`);
38
+ if (CONTROL_CHARACTERS.test(trimmed))
39
+ throw new ValidationError(`--${name} must not contain control characters`);
40
+ return trimmed;
41
+ }
42
+ function validateKind(kind) {
43
+ if (kind === 'implementation' || kind === 'pr')
44
+ return kind;
45
+ throw new ValidationError(`--kind must be "implementation" or "pr", got "${kind}"`);
46
+ }
47
+ function validateTtl(ttlHours) {
48
+ if (ttlHours === undefined)
49
+ return undefined;
50
+ if (!Number.isFinite(ttlHours) || ttlHours <= 0 || ttlHours > WORK_CLAIM_MAX_TTL_HOURS) {
51
+ throw new ValidationError(`--ttl must be a number of hours between 0 and ${WORK_CLAIM_MAX_TTL_HOURS}`);
52
+ }
53
+ return ttlHours;
54
+ }
55
+ /** Validate a claim's URL against its kind: implementations sit on issues, pr claims on PRs. */
56
+ function validateClaimUrl(url, kind) {
57
+ validateUrl(url);
58
+ if (kind === 'pr') {
59
+ validateGitHubUrl(url, PR_URL_PATTERN, 'PR');
60
+ }
61
+ else {
62
+ validateGitHubUrl(url, ISSUE_URL_PATTERN, 'issue');
63
+ }
64
+ }
65
+ /**
66
+ * This machine's short hostname, as `hostname -s` prints it: `os.hostname()`
67
+ * may carry a domain (`air.local`, `air.example.com`) that differs between
68
+ * networks, and the workflow docs compare a claim's `host` to `hostname -s`.
69
+ */
70
+ function shortHostname() {
71
+ return os.hostname().split('.', 1)[0];
72
+ }
73
+ /**
74
+ * The validated `--worktree` with the identity of the machine it is on:
75
+ * the short hostname (display, and the legacy comparison key) and the
76
+ * machine id (the comparison key; absent when the id file is unusable).
77
+ * Empty when no worktree was given.
78
+ */
79
+ function checkoutIdentity(rawWorktree) {
80
+ const worktree = validateField('worktree', rawWorktree);
81
+ if (worktree === undefined)
82
+ return {};
83
+ return { worktree: normalizeWorktreePath(worktree), host: shortHostname(), machineId: getMachineId() };
84
+ }
85
+ function validateClaimInput(options) {
86
+ const kind = validateKind(options.kind);
87
+ validateClaimUrl(options.url, kind);
88
+ const session = validateField('session', options.session);
89
+ if (session === undefined)
90
+ throw new ValidationError('--session is required');
91
+ const branch = validateField('branch', options.branch);
92
+ const runId = validateField('run-id', options.runId);
93
+ const checkout = checkoutIdentity(options.worktree);
94
+ if (kind === 'implementation' && runId === undefined && checkout.worktree === undefined) {
95
+ throw new ValidationError('An implementation claim needs --worktree (local checkout) or --run-id (remote worker run)');
96
+ }
97
+ const ttlHours = validateTtl(options.ttlHours);
98
+ const isTakeover = options.takeover === true;
99
+ return { kind, session, branch, ...checkout, runId, ttlHours, url: options.url, takeover: isTakeover };
100
+ }
101
+ /**
102
+ * Why the claim may not be recorded against the manager's current claims:
103
+ * another session holds the item (and `takeover` was not passed), the
104
+ * implementation cap is reached, or the checkout hosts another
105
+ * implementation. Null when it may proceed. Evaluated on the local state
106
+ * first and again on the Gist's copy after a conflict, so a claim another
107
+ * machine recorded first is never overwritten.
108
+ */
109
+ function claimRefusal(stateManager, input, nowMs) {
110
+ const claims = stateManager.getWorkClaims();
111
+ const holder = heldByOtherSession(claims, input.url, input.session, nowMs);
112
+ if (holder && !input.takeover) {
113
+ return (`${input.url} is already claimed: ${describeWorkClaim(holder, nowMs)}. ` +
114
+ `Pass --takeover (takeover: true) to replace that claim.`);
115
+ }
116
+ if (input.kind === 'implementation') {
117
+ const cap = stateManager.getState().config.maxConcurrentImplementations;
118
+ const conflict = checkImplementationClaim(claims, input, cap, nowMs);
119
+ if (conflict)
120
+ return conflict.message;
121
+ }
122
+ return null;
123
+ }
124
+ /**
125
+ * Build the claim to store. Renewing this session's own `finished`
126
+ * implementation keeps it finished (and collectable for the finished TTL):
127
+ * a renewal must not quietly turn a branch that is ready to collect back
128
+ * into a run in progress. To start over, release the claim first.
129
+ */
130
+ function buildClaim(input, existing, nowMs) {
131
+ const finishedOwn = isOwnFinishedClaim(input, existing) ? existing : undefined;
132
+ const ttlHours = input.ttlHours ?? (finishedOwn ? WORK_CLAIM_FINISHED_TTL_HOURS : WORK_CLAIM_DEFAULT_TTL_HOURS[input.kind]);
133
+ return {
134
+ kind: input.kind,
135
+ url: input.url,
136
+ session: input.session,
137
+ startedAt: isoAt(nowMs),
138
+ expiresAt: isoAt(nowMs + ttlHours * 3_600_000),
139
+ status: finishedOwn ? 'finished' : 'running',
140
+ ...locationFields(input),
141
+ ...(finishedOwn?.finishedAt !== undefined && { finishedAt: finishedOwn.finishedAt }),
142
+ };
143
+ }
144
+ /** The optional location fields of `input` that are set, so an absent one is left off the stored claim. */
145
+ function locationFields(input) {
146
+ const { branch, worktree, host, machineId, runId } = input;
147
+ return {
148
+ ...(branch !== undefined && { branch }),
149
+ ...(worktree !== undefined && { worktree }),
150
+ ...(host !== undefined && { host }),
151
+ ...(machineId !== undefined && { machineId }),
152
+ ...(runId !== undefined && { runId }),
153
+ };
154
+ }
155
+ /** Whether `existing` is this session's own finished claim of the same kind (a renewal keeps it finished). */
156
+ function isOwnFinishedClaim(input, existing) {
157
+ return (existing !== undefined &&
158
+ existing.session === input.session &&
159
+ existing.kind === input.kind &&
160
+ existing.status === 'finished');
161
+ }
162
+ /** What recording `claim` over `existing` amounts to. */
163
+ function outcomeFor(existing, session) {
164
+ if (existing === undefined)
165
+ return 'claimed';
166
+ return existing.session === session ? 'renewed' : 'took-over';
167
+ }
168
+ /**
169
+ * Take (or renew) a claim on an item (#1856, #1852).
170
+ *
171
+ * An implementation claim needs a `worktree` or a `runId` so the
172
+ * one-implementation-per-checkout rule has something to compare, and it is
173
+ * refused when `maxConcurrentImplementations` running implementations
174
+ * already exist or another live implementation uses the same checkout on
175
+ * this machine. A live claim another session holds is refused unless `takeover`
176
+ * is set (the workflow asks first); this session's own claim is renewed.
177
+ *
178
+ * In Gist mode the checks run again on the Gist's copy when the push
179
+ * conflicts with another machine: if that copy refuses the claim, nothing is
180
+ * recorded and the refusal is thrown. The claim is `synced: false` when it
181
+ * exists locally only.
182
+ *
183
+ * @throws {ValidationError} On a malformed URL or kind mismatch, a missing
184
+ * location for an implementation, an out-of-range TTL, or when another
185
+ * session's claim, the cap or the checkout rule blocks the claim.
186
+ */
187
+ export async function runWorkClaim(options) {
188
+ return claimWork(getStateManager(), options);
189
+ }
190
+ /** {@link runWorkClaim} against an explicit manager. */
191
+ export async function claimWork(stateManager, options) {
192
+ const input = validateClaimInput(options);
193
+ const now = Date.now();
194
+ const refusedLocally = claimRefusal(stateManager, input, now);
195
+ if (refusedLocally)
196
+ throw new ValidationError(refusedLocally);
197
+ const existing = findWorkClaim(stateManager.getWorkClaims(), input.url, now);
198
+ const claim = buildClaim(input, existing, now);
199
+ const outcome = outcomeFor(existing, input.session);
200
+ // The reapply (pre-push and after a Gist conflict) re-checks on whatever
201
+ // state is current. On the local state it sees this claim and passes; on
202
+ // a refreshed Gist copy it may find another machine got there first, and
203
+ // then it records the refusal instead of writing over that claim.
204
+ const remote = { message: null };
205
+ const apply = () => {
206
+ remote.message = claimRefusal(stateManager, input, now);
207
+ if (remote.message === null)
208
+ stateManager.upsertWorkClaim(claim, now);
209
+ };
210
+ apply();
211
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
212
+ if (remote.message !== null) {
213
+ throw new ValidationError(`${remote.message} (recorded on another machine first; this claim was not saved)`);
214
+ }
215
+ const isSynced = gistSyncWarning === null && stateManager.getGistHealth().degraded === null;
216
+ return { claim, outcome, synced: isSynced, ...(gistSyncWarning && { gistSyncWarning }) };
217
+ }
218
+ /**
219
+ * Mark the live claim on `url` finished (#1856): the implementation's branch
220
+ * is ready to collect. The claim stays (with its expiry extended to at least
221
+ * a week) until it is released or expires, so the action menu can offer
222
+ * "Collect finished implementations" and search keeps skipping the issue.
223
+ * With `session`, a claim another session holds is refused rather than
224
+ * finished on its behalf.
225
+ *
226
+ * @throws {ValidationError} When `session` is given and the live claim belongs to another session.
227
+ */
228
+ export async function runWorkFinish(options) {
229
+ return finishWork(getStateManager(), options);
230
+ }
231
+ /** {@link runWorkFinish} against an explicit manager. */
232
+ export async function finishWork(stateManager, options) {
233
+ validateUrl(options.url);
234
+ const session = validateField('session', options.session);
235
+ const now = Date.now();
236
+ const at = isoAt(now);
237
+ const mismatch = () => {
238
+ const existing = findWorkClaim(stateManager.getWorkClaims(), options.url, now);
239
+ if (existing === undefined || session === undefined || existing.session === session)
240
+ return null;
241
+ return `The claim on ${options.url} belongs to session ${existing.session}, not ${session}; it was not marked finished.`;
242
+ };
243
+ const refusal = { message: mismatch() };
244
+ if (refusal.message !== null)
245
+ throw new ValidationError(refusal.message);
246
+ const result = { claim: null };
247
+ const apply = () => {
248
+ refusal.message = mismatch();
249
+ if (refusal.message === null)
250
+ result.claim = stateManager.finishWorkClaim(options.url, at, now) ?? null;
251
+ };
252
+ apply();
253
+ const gistSyncWarning = result.claim ? await maybeCheckpoint(stateManager, MODULE, apply) : null;
254
+ if (refusal.message !== null)
255
+ throw new ValidationError(refusal.message);
256
+ return { url: options.url, claim: result.claim, ...(gistSyncWarning && { gistSyncWarning }) };
257
+ }
258
+ /**
259
+ * Drop claims (#1856, #1852): the claim on `url`, or every claim `session`
260
+ * holds (Session End releases that session's `pr` claims with
261
+ * `{ session, kind: 'pr' }`). Releasing an item nobody holds is not an
262
+ * error: `released` is simply empty.
263
+ *
264
+ * @throws {ValidationError} When neither `url` nor `session` is given.
265
+ */
266
+ export async function runWorkRelease(options) {
267
+ return releaseWork(getStateManager(), options);
268
+ }
269
+ /** {@link runWorkRelease} against an explicit manager. */
270
+ export async function releaseWork(stateManager, options) {
271
+ const session = validateField('session', options.session);
272
+ const kind = options.kind === undefined ? undefined : validateKind(options.kind);
273
+ if (options.url !== undefined)
274
+ validateUrl(options.url);
275
+ if (session === undefined && options.url === undefined) {
276
+ throw new ValidationError('work release needs a URL or --session <name>');
277
+ }
278
+ const selector = { url: options.url, session, kind };
279
+ const released = stateManager.releaseWorkClaims(selector);
280
+ const gistSyncWarning = released.length > 0
281
+ ? await maybeCheckpoint(stateManager, MODULE, () => stateManager.releaseWorkClaims(selector))
282
+ : null;
283
+ return { released, ...(gistSyncWarning && { gistSyncWarning }) };
284
+ }
285
+ /**
286
+ * The live claims (#1856). Read-only: expired claims are counted, not
287
+ * pruned. In Gist mode the state is refreshed first (throttled to once per
288
+ * 30 s by the store; a failed fetch serves the cached copy and sets a
289
+ * `warnings` entry) so a claim another machine pushed since this process
290
+ * loaded state is visible.
291
+ */
292
+ export async function runWorkList() {
293
+ return listWork(getStateManager());
294
+ }
295
+ /** {@link runWorkList} against an explicit manager. */
296
+ export async function listWork(stateManager) {
297
+ if (stateManager.isGistMode()) {
298
+ await stateManager.refreshFromGist();
299
+ }
300
+ else {
301
+ stateManager.reloadIfChanged();
302
+ }
303
+ const now = Date.now();
304
+ const all = stateManager.getWorkClaims();
305
+ const claims = stateManager.getActiveWorkClaims(now);
306
+ const staleness = stateManager.getStateStaleness();
307
+ return {
308
+ claims,
309
+ expiredCount: all.length - claims.length,
310
+ now: isoAt(now),
311
+ ...(staleness && { warnings: [buildStalenessWarning(staleness)] }),
312
+ };
313
+ }