@mrclrchtr/supi-review 3.1.0 → 4.0.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 (47) hide show
  1. package/README.md +41 -20
  2. package/node_modules/@mrclrchtr/supi-core/package.json +2 -4
  3. package/node_modules/@mrclrchtr/supi-core/src/api.ts +0 -4
  4. package/node_modules/@mrclrchtr/supi-core/src/evidence-badge.ts +3 -2
  5. package/node_modules/@mrclrchtr/supi-core/src/index.ts +0 -4
  6. package/node_modules/@mrclrchtr/supi-core/src/llm.ts +0 -10
  7. package/node_modules/@mrclrchtr/supi-core/src/path-utils.ts +19 -15
  8. package/package.json +2 -2
  9. package/src/git-choices.ts +42 -0
  10. package/src/git-command.ts +172 -2
  11. package/src/git.ts +126 -294
  12. package/src/history/collect.ts +15 -6
  13. package/src/review-input.ts +36 -0
  14. package/src/review-limits.ts +12 -0
  15. package/src/review-path.ts +18 -12
  16. package/src/review-result.ts +26 -5
  17. package/src/review.ts +150 -62
  18. package/src/session/review-artifact-store.ts +97 -0
  19. package/src/session/review-plan-store.ts +93 -12
  20. package/src/target/change-metadata.ts +125 -0
  21. package/src/target/diff.ts +43 -0
  22. package/src/target/file-manifest.ts +40 -0
  23. package/src/target/packet.ts +17 -6
  24. package/src/target/resolve.ts +209 -0
  25. package/src/tool/agent-review-schemas.ts +9 -4
  26. package/src/tool/agent-review-tools.ts +46 -14
  27. package/src/tool/child-failure-diagnostics.ts +26 -49
  28. package/src/tool/child-lifecycle-trace.ts +3 -16
  29. package/src/tool/child-session-runner.ts +28 -11
  30. package/src/tool/child-usage.ts +73 -0
  31. package/src/tool/diagnostic-sanitizer.ts +35 -0
  32. package/src/tool/output-page.ts +26 -0
  33. package/src/tool/planner-runner.ts +28 -10
  34. package/src/tool/review-output-tool.ts +93 -0
  35. package/src/tool/review-runner.ts +9 -7
  36. package/src/tool/review-tools.ts +90 -12
  37. package/src/tool/review-workflow.ts +146 -82
  38. package/src/tool/schemas.ts +24 -5
  39. package/src/tool/session-lifecycle.ts +44 -54
  40. package/src/tool/usage-format.ts +15 -0
  41. package/src/tui/common.ts +8 -13
  42. package/src/tui/prepare.ts +57 -31
  43. package/src/tui/run.ts +13 -3
  44. package/src/types.ts +60 -21
  45. package/node_modules/@mrclrchtr/supi-core/src/abort-utils.ts +0 -31
  46. package/node_modules/@mrclrchtr/supi-core/src/substrate-types.ts +0 -11
  47. package/node_modules/@mrclrchtr/supi-core/src/types.ts +0 -2
@@ -1,9 +1,15 @@
1
+ import { REVIEW_LIMITS } from "./review-limits.ts";
1
2
  import { normalizeRepositoryRelativePath } from "./review-path.ts";
2
3
  import type { NormalizedReviewSubmission, ReviewSubmission } from "./types.ts";
3
4
 
4
- function requireText(value: string, label: string): string {
5
+ function requireText(value: string, label: string, maxCharacters: number): string {
5
6
  const normalized = value.trim();
6
7
  if (!normalized) throw new Error(`${label} must not be blank.`);
8
+ if (normalized.length > maxCharacters) {
9
+ throw new Error(
10
+ `${label} must not exceed ${maxCharacters.toLocaleString("en-US")} characters.`,
11
+ );
12
+ }
7
13
  return normalized;
8
14
  }
9
15
 
@@ -11,8 +17,11 @@ function requireText(value: string, label: string): string {
11
17
  export function normalizeReviewSubmission(
12
18
  submission: ReviewSubmission,
13
19
  ): NormalizedReviewSubmission {
20
+ if (submission.findings.length > REVIEW_LIMITS.findingsPerTask) {
21
+ throw new Error(`A review task may submit at most ${REVIEW_LIMITS.findingsPerTask} findings.`);
22
+ }
14
23
  return {
15
- summary: requireText(submission.summary, "Review summary"),
24
+ summary: requireText(submission.summary, "Review summary", REVIEW_LIMITS.summaryCharacters),
16
25
  findings: submission.findings.map((finding, index) => {
17
26
  if (
18
27
  !Number.isFinite(finding.confidence) ||
@@ -32,13 +41,25 @@ export function normalizeReviewSubmission(
32
41
  }
33
42
  return {
34
43
  ...finding,
35
- title: requireText(finding.title, `Finding ${index + 1} title`),
36
- description: requireText(finding.description, `Finding ${index + 1} description`),
44
+ title: requireText(
45
+ finding.title,
46
+ `Finding ${index + 1} title`,
47
+ REVIEW_LIMITS.findingTitleCharacters,
48
+ ),
49
+ description: requireText(
50
+ finding.description,
51
+ `Finding ${index + 1} description`,
52
+ REVIEW_LIMITS.findingDescriptionCharacters,
53
+ ),
37
54
  location: finding.location
38
55
  ? {
39
56
  ...finding.location,
40
57
  path: normalizeRepositoryRelativePath(
41
- requireText(finding.location.path, `Finding ${index + 1} location path`),
58
+ requireText(
59
+ finding.location.path,
60
+ `Finding ${index + 1} location path`,
61
+ REVIEW_LIMITS.locationPathCharacters,
62
+ ),
42
63
  ),
43
64
  }
44
65
  : undefined,
package/src/review.ts CHANGED
@@ -1,12 +1,17 @@
1
- import { buildSessionContext, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
1
+ import {
2
+ BorderedLoader,
3
+ buildSessionContext,
4
+ type ExtensionAPI,
5
+ } from "@earendil-works/pi-coding-agent";
2
6
  import { Box } from "@earendil-works/pi-tui";
3
7
  import { loadReviewConfig, registerReviewSettings } from "./config.ts";
4
- import { listLocalBranches, listRecentCommits } from "./git.ts";
8
+ import { listLocalBranches, listRecentCommits } from "./git-choices.ts";
5
9
  import { collectPlannerContext } from "./history/collect.ts";
6
10
  import { getSelectableReviewModels, resolveAgentReviewModel } from "./model.ts";
11
+ import { ReviewArtifactStore } from "./session/review-artifact-store.ts";
7
12
  import { ReviewPlanStore } from "./session/review-plan-store.ts";
8
13
  import { formatReviewBatch, registerAgentReviewTools } from "./tool/agent-review-tools.ts";
9
- import { pageText } from "./tool/output-page.ts";
14
+ import { createReviewOutput, registerReviewOutputTool } from "./tool/review-output-tool.ts";
10
15
  import { prepareReview, runReview } from "./tool/review-workflow.ts";
11
16
  import { renderRunResult } from "./tui/run.ts";
12
17
  import type { ReviewInput, ReviewModelSelection, ReviewTargetSpec } from "./types.ts";
@@ -24,12 +29,13 @@ const DEFAULT_REVIEW: ReviewInput = {
24
29
 
25
30
  async function selectTarget(ctx: CommandContext): Promise<ReviewTargetSpec | undefined> {
26
31
  const kind = await ctx.ui.select("Review target", [
27
- "Working tree",
28
- "Comparison against a base commit",
32
+ "Uncommitted changes against HEAD",
33
+ "Current work against a base branch",
34
+ "Committed changes against a base branch",
29
35
  "Single commit",
30
36
  ]);
31
37
  if (!kind) return undefined;
32
- if (kind === "Working tree") return { kind: "working-tree" };
38
+ if (kind === "Uncommitted changes against HEAD") return { kind: "working-tree" };
33
39
  const choices =
34
40
  kind === "Single commit" ? await listRecentCommits(ctx.cwd) : await listLocalBranches(ctx.cwd);
35
41
  const label = await ctx.ui.select(
@@ -38,9 +44,11 @@ async function selectTarget(ctx: CommandContext): Promise<ReviewTargetSpec | und
38
44
  );
39
45
  const choice = choices.find((candidate) => candidate.label === label);
40
46
  if (!choice) return undefined;
41
- return kind === "Single commit"
42
- ? { kind: "commit", commit: choice.commit }
43
- : { kind: "comparison", baseCommit: choice.commit };
47
+ if (kind === "Single commit") return { kind: "commit", commit: choice.commit };
48
+ if (kind === "Current work against a base branch") {
49
+ return { kind: "working-tree", baseCommit: choice.commit };
50
+ }
51
+ return { kind: "comparison", baseCommit: choice.commit };
44
52
  }
45
53
 
46
54
  async function selectReviewerModel(ctx: CommandContext): Promise<ReviewModelSelection | undefined> {
@@ -103,18 +111,124 @@ async function editReviewInteractive(
103
111
  }
104
112
 
105
113
  const result: ReviewInput = { tasks };
106
- if (review.sharedContext) {
107
- const sharedContext = await ctx.ui.editor("Shared context (optional)", review.sharedContext);
108
- if (sharedContext === undefined) return undefined;
109
- if (sharedContext.trim()) result.sharedContext = sharedContext.trim();
110
- }
114
+ const sharedContext = await ctx.ui.editor(
115
+ "Shared context (optional)",
116
+ review.sharedContext ?? "",
117
+ );
118
+ if (sharedContext === undefined) return undefined;
119
+ if (sharedContext.trim()) result.sharedContext = sharedContext.trim();
111
120
  return result;
112
121
  }
113
122
 
123
+ /** Run command-owned child work behind an Escape-cancellable Pi loader. */
124
+ async function withCancellableLoader<T>(
125
+ ctx: CommandContext,
126
+ message: string,
127
+ operation: (signal: AbortSignal) => Promise<T>,
128
+ ): Promise<T | undefined> {
129
+ return ctx.ui.custom<T | undefined>((tui, theme, _keybindings, done) => {
130
+ const loader = new BorderedLoader(tui, theme, message);
131
+ let settled = false;
132
+ const finish = (value: T | undefined) => {
133
+ if (settled) return;
134
+ settled = true;
135
+ done(value);
136
+ };
137
+ loader.onAbort = () => {
138
+ // CancellableLoader aborts loader.signal; lifecycle cleanup determines the final outcome.
139
+ };
140
+ void operation(loader.signal).then(
141
+ (value) => finish(value),
142
+ (error) => {
143
+ ctx.ui.notify(
144
+ error instanceof Error ? error.message : "Review failed unexpectedly.",
145
+ "error",
146
+ );
147
+ finish(undefined);
148
+ },
149
+ );
150
+ return loader;
151
+ });
152
+ }
153
+
154
+ async function prepareInteractiveReview(
155
+ ctx: CommandContext,
156
+ target: ReviewTargetSpec,
157
+ reviewerModel: ReviewModelSelection,
158
+ planStore: ReviewPlanStore,
159
+ ): Promise<{ review: ReviewInput; planId: string } | undefined> {
160
+ const config = loadReviewConfig(ctx.cwd);
161
+ const plannerModel = resolveAgentReviewModel(ctx, config.plannerModel);
162
+ const session = buildSessionContext(
163
+ ctx.sessionManager.getEntries(),
164
+ ctx.sessionManager.getLeafId(),
165
+ );
166
+ const outcome = await withCancellableLoader(ctx, "Planning review…", (signal) =>
167
+ prepareReview({
168
+ cwd: ctx.cwd,
169
+ target,
170
+ planning: "suggest",
171
+ plannerContext: collectPlannerContext(session.messages),
172
+ reviewerModel,
173
+ plannerModel,
174
+ planStore,
175
+ signal,
176
+ }),
177
+ );
178
+ if (!outcome) return undefined;
179
+ if (outcome.kind === "canceled") {
180
+ ctx.ui.notify("Review planning canceled.", "info");
181
+ return undefined;
182
+ }
183
+ if (outcome.kind !== "prepared") {
184
+ ctx.ui.notify(outcome.reason, "error");
185
+ return undefined;
186
+ }
187
+ if (outcome.plan.plannerFailure) {
188
+ ctx.ui.notify("Planner unavailable; edit replacement tasks to continue.", "warning");
189
+ }
190
+ return {
191
+ review: outcome.plan.plannerDraft ?? DEFAULT_REVIEW,
192
+ planId: outcome.plan.id,
193
+ };
194
+ }
195
+
196
+ async function executeInteractiveReview(
197
+ ctx: CommandContext,
198
+ input: {
199
+ target: ReviewTargetSpec;
200
+ review: ReviewInput;
201
+ reviewerModel: ReviewModelSelection;
202
+ planId?: string;
203
+ planStore: ReviewPlanStore;
204
+ },
205
+ ) {
206
+ return withCancellableLoader(ctx, "Reviewing…", (signal) =>
207
+ input.planId
208
+ ? runReview({
209
+ mode: "prepared",
210
+ cwd: ctx.cwd,
211
+ planId: input.planId,
212
+ decision: { kind: "use-review", review: input.review },
213
+ planStore: input.planStore,
214
+ signal,
215
+ })
216
+ : runReview({
217
+ mode: "direct",
218
+ cwd: ctx.cwd,
219
+ target: input.target,
220
+ review: input.review,
221
+ reviewerModel: input.reviewerModel,
222
+ signal,
223
+ }),
224
+ );
225
+ }
226
+
114
227
  async function runCommand(
115
228
  ctx: CommandContext,
116
229
  pi: ExtensionAPI,
117
230
  planStore: ReviewPlanStore,
231
+ artifactStore: ReviewArtifactStore,
118
232
  ): Promise<void> {
119
233
  if (!ctx.hasUI) return;
120
234
  const target = await selectTarget(ctx);
@@ -127,35 +241,13 @@ async function runCommand(
127
241
  ]);
128
242
  if (!planning) return;
129
243
 
130
- let review = DEFAULT_REVIEW;
131
- let planId: string | undefined;
132
- if (planning === "AI suggests tasks") {
133
- const config = loadReviewConfig(ctx.cwd);
134
- const plannerModel = resolveAgentReviewModel(ctx, config.plannerModel);
135
- if (!plannerModel) {
136
- ctx.ui.notify(`Configured Planner model "${config.plannerModel}" is unavailable.`, "error");
137
- return;
138
- }
139
- const session = buildSessionContext(
140
- ctx.sessionManager.getEntries(),
141
- ctx.sessionManager.getLeafId(),
142
- );
143
- const outcome = await prepareReview({
144
- cwd: ctx.cwd,
145
- target,
146
- planning: "suggest",
147
- plannerContext: collectPlannerContext(session.messages),
148
- reviewerModel,
149
- plannerModel,
150
- planStore,
151
- });
152
- if (outcome.kind !== "prepared" || !outcome.plan.plannerDraft) {
153
- ctx.ui.notify("Planner did not produce a draft.", "error");
154
- return;
155
- }
156
- review = outcome.plan.plannerDraft;
157
- planId = outcome.plan.id;
158
- }
244
+ const prepared =
245
+ planning === "AI suggests tasks"
246
+ ? await prepareInteractiveReview(ctx, target, reviewerModel, planStore)
247
+ : undefined;
248
+ if (planning === "AI suggests tasks" && !prepared) return;
249
+ const review = prepared?.review ?? DEFAULT_REVIEW;
250
+ const planId = prepared?.planId;
159
251
 
160
252
  const edited = await editReviewInteractive(ctx, review, {
161
253
  allowResize: planning === "Write my own tasks",
@@ -167,37 +259,33 @@ async function runCommand(
167
259
  );
168
260
  if (!approved) return;
169
261
 
170
- const outcome = planId
171
- ? await runReview({
172
- mode: "prepared",
173
- cwd: ctx.cwd,
174
- planId,
175
- decision: { kind: "use-review", review: edited },
176
- planStore,
177
- })
178
- : await runReview({
179
- mode: "direct",
180
- cwd: ctx.cwd,
181
- target,
182
- review: edited,
183
- reviewerModel,
184
- });
262
+ const outcome = await executeInteractiveReview(ctx, {
263
+ target,
264
+ review: edited,
265
+ reviewerModel,
266
+ ...(planId ? { planId } : {}),
267
+ planStore,
268
+ });
269
+ if (!outcome) return;
185
270
  if (outcome.kind !== "completed") {
186
271
  ctx.ui.notify(outcome.reason, "error");
187
272
  return;
188
273
  }
274
+ const output = createReviewOutput(artifactStore, formatReviewBatch(outcome.details));
189
275
  pi.sendMessage({
190
276
  customType: "supi-review",
191
- content: pageText(formatReviewBatch(outcome.details)).text,
277
+ content: output.text,
192
278
  display: true,
193
- details: outcome.details,
279
+ details: { ...outcome.details, output: output.reference, usage: outcome.usage },
194
280
  });
195
281
  }
196
282
 
197
283
  export default function reviewExtension(pi: ExtensionAPI): void {
198
284
  const planStore = new ReviewPlanStore();
285
+ const artifactStore = new ReviewArtifactStore();
199
286
  registerReviewSettings(pi);
200
- registerAgentReviewTools(pi, planStore);
287
+ registerAgentReviewTools(pi, planStore, artifactStore);
288
+ registerReviewOutputTool(pi, artifactStore);
201
289
 
202
290
  // Message renderer for the /supi-review slash command output.
203
291
  // Adapts the sendMessage shape into the shape renderRunResult expects.
@@ -215,6 +303,6 @@ export default function reviewExtension(pi: ExtensionAPI): void {
215
303
 
216
304
  pi.registerCommand("supi-review", {
217
305
  description: "Run one or more caller-defined read-only review tasks",
218
- handler: async (_args, ctx) => runCommand(ctx, pi, planStore),
306
+ handler: async (_args, ctx) => runCommand(ctx, pi, planStore, artifactStore),
219
307
  });
220
308
  }
@@ -0,0 +1,97 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { pageText, type TextPage } from "../tool/output-page.ts";
3
+
4
+ const DEFAULT_MAX_ARTIFACTS = 8;
5
+ const DEFAULT_MAX_TOTAL_CHARACTERS = 2_000_000;
6
+ const DEFAULT_MAX_AGE_MS = 30 * 60 * 1_000;
7
+
8
+ interface ArtifactEntry {
9
+ id: string;
10
+ text: string;
11
+ createdAt: number;
12
+ }
13
+
14
+ export interface ReviewArtifactStoreOptions {
15
+ maxArtifacts?: number;
16
+ maxTotalCharacters?: number;
17
+ maxAgeMs?: number;
18
+ now?: () => number;
19
+ }
20
+
21
+ export interface ReviewArtifact {
22
+ id: string;
23
+ totalCharacters: number;
24
+ }
25
+
26
+ /** Bounded session-local store for resumable parent-facing review output. */
27
+ export class ReviewArtifactStore {
28
+ readonly #entries = new Map<string, ArtifactEntry>();
29
+ readonly #maxArtifacts: number;
30
+ readonly #maxTotalCharacters: number;
31
+ readonly #maxAgeMs: number;
32
+ readonly #now: () => number;
33
+ #totalCharacters = 0;
34
+
35
+ constructor(options: ReviewArtifactStoreOptions = {}) {
36
+ this.#maxArtifacts = options.maxArtifacts ?? DEFAULT_MAX_ARTIFACTS;
37
+ this.#maxTotalCharacters = options.maxTotalCharacters ?? DEFAULT_MAX_TOTAL_CHARACTERS;
38
+ this.#maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS;
39
+ this.#now = options.now ?? Date.now;
40
+ }
41
+
42
+ /** Store complete formatted output and return its opaque retrieval identity. */
43
+ create(text: string): ReviewArtifact {
44
+ if (text.length > this.#maxTotalCharacters) {
45
+ throw new Error(
46
+ `Review output exceeds the session artifact limit of ${this.#maxTotalCharacters} characters.`,
47
+ );
48
+ }
49
+ this.#pruneExpired();
50
+ while (
51
+ this.#entries.size >= this.#maxArtifacts ||
52
+ this.#totalCharacters + text.length > this.#maxTotalCharacters
53
+ ) {
54
+ if (!this.#evictOldest()) break;
55
+ }
56
+ const entry = {
57
+ id: `review-output-${randomUUID()}`,
58
+ text,
59
+ createdAt: this.#now(),
60
+ };
61
+ this.#entries.set(entry.id, entry);
62
+ this.#totalCharacters += text.length;
63
+ return { id: entry.id, totalCharacters: text.length };
64
+ }
65
+
66
+ /** Read one page without consuming the artifact so callers may retry pages. */
67
+ read(id: string, offset?: number, limit?: number): TextPage | undefined {
68
+ this.#pruneExpired();
69
+ const entry = this.#entries.get(id);
70
+ return entry ? pageText(entry.text, offset, limit) : undefined;
71
+ }
72
+
73
+ clear(): void {
74
+ this.#entries.clear();
75
+ this.#totalCharacters = 0;
76
+ }
77
+
78
+ #pruneExpired(): void {
79
+ const cutoff = this.#now() - this.#maxAgeMs;
80
+ for (const entry of this.#entries.values()) {
81
+ if (entry.createdAt > cutoff) continue;
82
+ this.#delete(entry);
83
+ }
84
+ }
85
+
86
+ #evictOldest(): boolean {
87
+ const oldest = this.#entries.values().next().value as ArtifactEntry | undefined;
88
+ if (!oldest) return false;
89
+ this.#delete(oldest);
90
+ return true;
91
+ }
92
+
93
+ #delete(entry: ArtifactEntry): void {
94
+ if (!this.#entries.delete(entry.id)) return;
95
+ this.#totalCharacters -= entry.text.length;
96
+ }
97
+ }
@@ -1,7 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import type { PlannerDraft, ReviewModelSelection, ReviewSnapshot } from "../types.ts";
2
+ import type { Usage } from "@earendil-works/pi-ai";
3
+ import type {
4
+ PlannerDraft,
5
+ PlannerRunResult,
6
+ ReviewModelSelection,
7
+ ReviewSnapshot,
8
+ } from "../types.ts";
3
9
 
4
- /** Session-local resolved target and model choices awaiting one execution decision. */
10
+ /** Session-local resolved target and model choices awaiting an execution decision. */
5
11
  export interface StoredReviewPlan {
6
12
  id: string;
7
13
  snapshot: ReviewSnapshot;
@@ -9,30 +15,105 @@ export interface StoredReviewPlan {
9
15
  plannerDraft?: PlannerDraft;
10
16
  plannerModelId?: string;
11
17
  plannerPromptVersion?: string;
18
+ plannerUsage?: Usage;
19
+ /** Bounded advisory Planner outcome retained when no draft was produced. */
20
+ plannerFailure?: Exclude<PlannerRunResult, { kind: "success" }>;
12
21
  }
13
22
 
14
- /** In-memory one-shot store; `take` atomically removes a plan before validation/execution. */
23
+ interface PlanEntry {
24
+ plan: StoredReviewPlan;
25
+ createdAt: number;
26
+ leaseToken?: string;
27
+ }
28
+
29
+ export interface ReviewPlanStoreOptions {
30
+ maxPlans?: number;
31
+ maxAgeMs?: number;
32
+ now?: () => number;
33
+ }
34
+
35
+ /** Opaque lease that prevents concurrent execution of one Prepared Review Plan. */
36
+ export interface ReviewPlanLease {
37
+ plan: StoredReviewPlan;
38
+ token: string;
39
+ }
40
+
41
+ /** Session-local plan store with explicit available, running, and consumed transitions. */
15
42
  export class ReviewPlanStore {
16
- readonly #plans = new Map<string, StoredReviewPlan>();
43
+ readonly #plans = new Map<string, PlanEntry>();
44
+ readonly #maxPlans: number;
45
+ readonly #maxAgeMs: number;
46
+ readonly #now: () => number;
47
+
48
+ constructor(options: ReviewPlanStoreOptions = {}) {
49
+ this.#maxPlans = options.maxPlans ?? 32;
50
+ this.#maxAgeMs = options.maxAgeMs ?? 30 * 60 * 1_000;
51
+ this.#now = options.now ?? Date.now;
52
+ }
17
53
 
18
54
  create(input: Omit<StoredReviewPlan, "id">): StoredReviewPlan {
55
+ this.#pruneExpired();
56
+ while (this.#plans.size >= this.#maxPlans) {
57
+ if (!this.#evictOldestAvailable()) {
58
+ throw new Error("Too many Review Plans are currently running in this session.");
59
+ }
60
+ }
19
61
  const plan = { id: `review-plan-${randomUUID()}`, ...input };
20
- this.#plans.set(plan.id, plan);
62
+ this.#plans.set(plan.id, { plan, createdAt: this.#now() });
21
63
  return plan;
22
64
  }
23
65
 
24
- take(id: string): StoredReviewPlan | undefined {
25
- const plan = this.#plans.get(id);
26
- if (plan) this.#plans.delete(id);
27
- return plan;
66
+ /** Read an available plan without leasing or consuming it. */
67
+ peek(id: string): StoredReviewPlan | undefined {
68
+ this.#pruneExpired();
69
+ const entry = this.#plans.get(id);
70
+ return entry && !entry.leaseToken ? entry.plan : undefined;
28
71
  }
29
72
 
30
- /** Read a plan without consuming it, for pre-execution task count display. */
31
- peek(id: string): StoredReviewPlan | undefined {
32
- return this.#plans.get(id);
73
+ /** Atomically mark an available plan as running. */
74
+ acquire(id: string): ReviewPlanLease | undefined {
75
+ this.#pruneExpired();
76
+ const entry = this.#plans.get(id);
77
+ if (!entry || entry.leaseToken) return undefined;
78
+ const token = randomUUID();
79
+ entry.leaseToken = token;
80
+ return { plan: entry.plan, token };
81
+ }
82
+
83
+ /** Make a running plan available again when no task produced a structured review. */
84
+ release(lease: ReviewPlanLease): boolean {
85
+ const entry = this.#plans.get(lease.plan.id);
86
+ if (!entry || entry.leaseToken !== lease.token) return false;
87
+ entry.leaseToken = undefined;
88
+ entry.createdAt = this.#now();
89
+ return true;
90
+ }
91
+
92
+ /** Permanently consume a running plan after at least one task completes. */
93
+ consume(lease: ReviewPlanLease): boolean {
94
+ const entry = this.#plans.get(lease.plan.id);
95
+ if (!entry || entry.leaseToken !== lease.token) return false;
96
+ this.#plans.delete(lease.plan.id);
97
+ return true;
33
98
  }
34
99
 
35
100
  clear(): void {
36
101
  this.#plans.clear();
37
102
  }
103
+
104
+ #pruneExpired(): void {
105
+ const cutoff = this.#now() - this.#maxAgeMs;
106
+ for (const [id, entry] of this.#plans) {
107
+ if (!entry.leaseToken && entry.createdAt <= cutoff) this.#plans.delete(id);
108
+ }
109
+ }
110
+
111
+ #evictOldestAvailable(): boolean {
112
+ for (const [id, entry] of this.#plans) {
113
+ if (entry.leaseToken) continue;
114
+ this.#plans.delete(id);
115
+ return true;
116
+ }
117
+ return false;
118
+ }
38
119
  }