supipowers 2.2.0 → 2.2.2

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 (45) hide show
  1. package/README.md +71 -12
  2. package/package.json +11 -15
  3. package/skills/ui-design/SKILL.md +2 -2
  4. package/src/ai/final-message.ts +15 -1
  5. package/src/ai/schema-text.ts +60 -40
  6. package/src/ai/schema-validation.ts +88 -0
  7. package/src/ai/structured-output.ts +19 -19
  8. package/src/bootstrap.ts +2 -1
  9. package/src/commands/doctor.ts +3 -2
  10. package/src/commands/fix-pr.ts +166 -26
  11. package/src/commands/plan.ts +2 -1
  12. package/src/commands/update.ts +7 -5
  13. package/src/config/schema.ts +102 -139
  14. package/src/docs/contracts.ts +13 -23
  15. package/src/fix-pr/assessment.ts +63 -24
  16. package/src/fix-pr/contracts.ts +15 -23
  17. package/src/fix-pr/fetch-comments.ts +119 -0
  18. package/src/fix-pr/prompt-builder.ts +19 -8
  19. package/src/git/commit-contract.ts +13 -19
  20. package/src/git/commit.ts +168 -6
  21. package/src/harness/anti_slop/fallow-adapter.ts +4 -3
  22. package/src/harness/command.ts +12 -7
  23. package/src/harness/pipeline.ts +2 -8
  24. package/src/harness/stage-runner.ts +3 -0
  25. package/src/harness/stages/docs.ts +82 -0
  26. package/src/lsp/capabilities.ts +9 -12
  27. package/src/lsp/contracts.ts +15 -23
  28. package/src/mempalace/uv.ts +15 -7
  29. package/src/planning/approval-flow.ts +15 -17
  30. package/src/planning/planning-ask-tool.ts +13 -2
  31. package/src/planning/spec.ts +21 -27
  32. package/src/planning/system-prompt.ts +1 -1
  33. package/src/planning/validate.ts +4 -7
  34. package/src/platform/progress.ts +11 -0
  35. package/src/quality/contracts.ts +15 -23
  36. package/src/quality/schemas.ts +40 -67
  37. package/src/release/contracts.ts +19 -28
  38. package/src/review/types.ts +142 -186
  39. package/src/types.ts +15 -2
  40. package/src/ui-design/session.ts +13 -2
  41. package/src/ui-design/system-prompt.ts +2 -2
  42. package/src/ultraplan/contracts.ts +458 -524
  43. package/src/utils/exec-cli.ts +106 -0
  44. package/src/visual/scripts/npm-shrinkwrap.json +878 -0
  45. package/src/visual/scripts/package-lock.json +878 -0
@@ -1,176 +1,142 @@
1
- import type { TSchema } from "@sinclair/typebox";
2
- import { Type } from "@sinclair/typebox";
3
- import { Value } from "@sinclair/typebox/value";
1
+ import { z } from "zod/v4";
2
+ import type { ZodType } from "zod/v4";
4
3
  import type { SupipowersConfig } from "../types.js";
5
4
  import { QualityGatesSchema } from "../quality/schemas.js";
6
5
  import { UltraPlanConfigSchema } from "../ultraplan/contracts.js";
6
+ import { collectSchemaValidationErrors } from "../ai/schema-validation.js";
7
7
 
8
8
  const TAG_FORMAT_PATTERN = "^(?:(?!\\$\\{version\\}).)*\\$\\{version\\}(?:(?!\\$\\{version\\}).)*$";
9
9
 
10
10
 
11
- export const ConfigSchema = Type.Object(
11
+ export const ConfigSchema = z.object(
12
12
  {
13
- version: Type.String(),
14
- quality: Type.Object(
13
+ version: z.string(),
14
+ quality: z.object(
15
15
  {
16
16
  gates: QualityGatesSchema,
17
17
  },
18
- { additionalProperties: false },
19
- ),
20
- lsp: Type.Object(
18
+ ).strict(),
19
+ lsp: z.object(
21
20
  {
22
- setupGuide: Type.Boolean(),
21
+ setupGuide: z.boolean(),
23
22
  },
24
- { additionalProperties: false },
25
- ),
26
- qa: Type.Object(
23
+ ).strict(),
24
+ qa: z.object(
27
25
  {
28
- framework: Type.Union([Type.String(), Type.Null()]),
29
- e2e: Type.Boolean(),
26
+ framework: z.string().nullable(),
27
+ e2e: z.boolean(),
30
28
  },
31
- { additionalProperties: false },
32
- ),
33
- release: Type.Object(
29
+ ).strict(),
30
+ release: z.object(
34
31
  {
35
- channels: Type.Array(Type.String()),
36
- tagFormat: Type.String({ pattern: TAG_FORMAT_PATTERN }),
37
- customChannels: Type.Optional(
38
- Type.Record(
39
- Type.String(),
40
- Type.Object({
41
- label: Type.String(),
42
- publishCommand: Type.String(),
43
- detectCommand: Type.Optional(Type.String()),
44
- }),
45
- ),
46
- ),
32
+ channels: z.array(z.string()),
33
+ tagFormat: z.string().regex(new RegExp(TAG_FORMAT_PATTERN)),
34
+ customChannels: z.record(
35
+ z.string(),
36
+ z.object({
37
+ label: z.string(),
38
+ publishCommand: z.string(),
39
+ detectCommand: z.string().optional(),
40
+ }),
41
+ ).optional(),
47
42
  },
48
- { additionalProperties: false },
49
- ),
43
+ ).strict(),
50
44
  ultraplan: UltraPlanConfigSchema,
51
- contextMode: Type.Object(
45
+ contextMode: z.object(
52
46
  {
53
- enabled: Type.Boolean(),
54
- compressionThreshold: Type.Number({ minimum: 1024 }),
55
- blockHttpCommands: Type.Boolean(),
56
- routingInstructions: Type.Boolean(),
57
- eventTracking: Type.Boolean(),
58
- compaction: Type.Boolean(),
59
- llmSummarization: Type.Boolean(),
60
- llmThreshold: Type.Number({ minimum: 4096 }),
61
- enforceRouting: Type.Boolean(),
62
- lazyTools: Type.Object(
47
+ enabled: z.boolean(),
48
+ compressionThreshold: z.number().min(1024),
49
+ blockHttpCommands: z.boolean(),
50
+ routingInstructions: z.boolean(),
51
+ eventTracking: z.boolean(),
52
+ compaction: z.boolean(),
53
+ llmSummarization: z.boolean(),
54
+ llmThreshold: z.number().min(4096),
55
+ enforceRouting: z.boolean(),
56
+ lazyTools: z.object(
63
57
  {
64
- enabled: Type.Boolean(),
65
- mode: Type.Union([
66
- Type.Literal("conservative"),
67
- Type.Literal("balanced"),
68
- Type.Literal("aggressive"),
69
- ]),
70
- alwaysKeep: Type.Array(Type.String()),
71
- commandAllowlist: Type.Record(Type.String(), Type.Array(Type.String())),
72
- keywordTools: Type.Record(Type.String(), Type.Array(Type.String())),
58
+ enabled: z.boolean(),
59
+ mode: z.enum(["conservative", "balanced", "aggressive"]),
60
+ alwaysKeep: z.array(z.string()),
61
+ commandAllowlist: z.record(z.string(), z.array(z.string())),
62
+ keywordTools: z.record(z.string(), z.array(z.string())),
73
63
  },
74
- { additionalProperties: false },
75
- ),
76
- processors: Type.Object(
64
+ ).strict(),
65
+ processors: z.object(
77
66
  {
78
- enabled: Type.Boolean(),
79
- disable: Type.Array(
80
- Type.Union([
81
- Type.Literal("git"),
82
- Type.Literal("test"),
83
- Type.Literal("lint"),
84
- Type.Literal("build"),
85
- Type.Literal("k8s"),
86
- Type.Literal("docker"),
87
- Type.Literal("log"),
88
- Type.Literal("json"),
89
- ]),
67
+ enabled: z.boolean(),
68
+ disable: z.array(
69
+ z.enum(["git", "test", "lint", "build", "k8s", "docker", "log", "json"]),
90
70
  ),
91
71
  },
92
- { additionalProperties: false },
93
- ),
94
- cacheHandles: Type.Object(
72
+ ).strict(),
73
+ cacheHandles: z.object(
95
74
  {
96
- enabled: Type.Boolean(),
97
- spillThresholdBytes: Type.Number({ minimum: 1024 }),
98
- previewBytes: Type.Number({ minimum: 256 }),
75
+ enabled: z.boolean(),
76
+ spillThresholdBytes: z.number().min(1024),
77
+ previewBytes: z.number().min(256),
99
78
  },
100
- { additionalProperties: false },
101
- ),
102
- repomap: Type.Object(
79
+ ).strict(),
80
+ repomap: z.object(
103
81
  {
104
- enabled: Type.Boolean(),
105
- tokenBudget: Type.Number({ minimum: 100 }),
106
- maxFiles: Type.Number({ minimum: 1 }),
82
+ enabled: z.boolean(),
83
+ tokenBudget: z.number().min(100),
84
+ maxFiles: z.number().min(1),
107
85
  },
108
- { additionalProperties: false },
109
- ),
110
- memory: Type.Object(
86
+ ).strict(),
87
+ memory: z.object(
111
88
  {
112
- enabled: Type.Boolean(),
113
- byteBudget: Type.Number({ minimum: 256 }),
114
- maxRows: Type.Number({ minimum: 1 }),
115
- retentionDays: Type.Number({ minimum: 1 }),
116
- focusChainCadence: Type.Integer({ minimum: 1 }),
89
+ enabled: z.boolean(),
90
+ byteBudget: z.number().min(256),
91
+ maxRows: z.number().min(1),
92
+ retentionDays: z.number().min(1),
93
+ focusChainCadence: z.number().int().min(1),
117
94
  },
118
- { additionalProperties: false },
119
- ),
95
+ ).strict(),
120
96
  },
121
- { additionalProperties: false },
122
- ),
123
- mempalace: Type.Object(
97
+ ).strict(),
98
+ mempalace: z.object(
124
99
  {
125
- enabled: Type.Boolean(),
126
- packageVersion: Type.String({ minLength: 1 }),
127
- managedVenvPath: Type.String({ minLength: 1 }),
128
- palacePath: Type.String({ minLength: 1 }),
129
- defaultWingStrategy: Type.Union([
130
- Type.Literal("repo-name"),
131
- Type.Literal("project-slug"),
132
- Type.Literal("explicit"),
133
- ]),
134
- explicitWing: Type.Union([Type.String(), Type.Null()]),
135
- defaultAgentName: Type.String({ minLength: 1 }),
136
- autoSetup: Type.Boolean(),
137
- hooks: Type.Object(
100
+ enabled: z.boolean(),
101
+ packageVersion: z.string().min(1),
102
+ managedVenvPath: z.string().min(1),
103
+ palacePath: z.string().min(1),
104
+ defaultWingStrategy: z.enum(["repo-name", "project-slug", "explicit"]),
105
+ explicitWing: z.string().nullable(),
106
+ defaultAgentName: z.string().min(1),
107
+ autoSetup: z.boolean(),
108
+ hooks: z.object(
138
109
  {
139
- wakeUp: Type.Boolean(),
140
- searchGuidance: Type.Boolean(),
141
- autoSearchOnPrompt: Type.Boolean(),
142
- compactionCheckpoint: Type.Boolean(),
143
- shutdownDiary: Type.Boolean(),
110
+ wakeUp: z.boolean(),
111
+ searchGuidance: z.boolean(),
112
+ autoSearchOnPrompt: z.boolean(),
113
+ compactionCheckpoint: z.boolean(),
114
+ shutdownDiary: z.boolean(),
144
115
  },
145
- { additionalProperties: false },
146
- ),
147
- budgets: Type.Object(
116
+ ).strict(),
117
+ budgets: z.object(
148
118
  {
149
- wakeUpTokens: Type.Integer({ minimum: 1 }),
150
- searchResultChars: Type.Integer({ minimum: 1 }),
151
- listResultChars: Type.Integer({ minimum: 1 }),
152
- diaryChars: Type.Integer({ minimum: 1 }),
153
- autoSearchTokens: Type.Integer({ minimum: 1 }),
154
- wakeUpInjectionEvery: Type.Integer({ minimum: 1 }),
155
- autoSearchSimilarityFloor: Type.Number({ minimum: 0, maximum: 1 }),
156
- autoSearchBm25Floor: Type.Number({ minimum: 0 }),
119
+ wakeUpTokens: z.number().int().min(1),
120
+ searchResultChars: z.number().int().min(1),
121
+ listResultChars: z.number().int().min(1),
122
+ diaryChars: z.number().int().min(1),
123
+ autoSearchTokens: z.number().int().min(1),
124
+ wakeUpInjectionEvery: z.number().int().min(1),
125
+ autoSearchSimilarityFloor: z.number().min(0).max(1),
126
+ autoSearchBm25Floor: z.number().min(0),
157
127
  },
158
- { additionalProperties: false },
159
- ),
160
- timeouts: Type.Object(
128
+ ).strict(),
129
+ timeouts: z.object(
161
130
  {
162
- setupMs: Type.Integer({ minimum: 1 }),
163
- bridgeMs: Type.Integer({ minimum: 1 }),
164
- hookMs: Type.Integer({ minimum: 1 }),
131
+ setupMs: z.number().int().min(1),
132
+ bridgeMs: z.number().int().min(1),
133
+ hookMs: z.number().int().min(1),
165
134
  },
166
- { additionalProperties: false },
167
- ),
135
+ ).strict(),
168
136
  },
169
- { additionalProperties: false },
170
- ),
137
+ ).strict(),
171
138
  },
172
- { additionalProperties: false },
173
- );
139
+ ).strict();
174
140
 
175
141
  export interface ConfigParseError {
176
142
  source: "global" | "root";
@@ -190,13 +156,10 @@ export interface InspectionLoadResult {
190
156
  validationErrors: ConfigValidationError[];
191
157
  }
192
158
 
193
- function normalizeErrorPath(path: string): string {
194
- return path.replace(/^\//, "").replace(/\//g, ".") || "(root)";
195
- }
196
159
 
197
- function collectValidationErrors(schema: TSchema, data: unknown): ConfigValidationError[] {
198
- return [...Value.Errors(schema, data)].map((error) => ({
199
- path: normalizeErrorPath(error.path),
160
+ function collectValidationErrors(schema: ZodType, data: unknown): ConfigValidationError[] {
161
+ return collectSchemaValidationErrors(schema, data).map((error) => ({
162
+ path: error.path,
200
163
  message: error.message,
201
164
  }));
202
165
  }
@@ -5,7 +5,7 @@
5
5
  // retry loop (runWithOutputValidation) will hand validation errors back to
6
6
  // the model rather than letting a silent regex heuristic invent findings.
7
7
 
8
- import { Type, type Static } from "@sinclair/typebox";
8
+ import { z } from "zod/v4"
9
9
 
10
10
  export const DOC_DRIFT_SEVERITIES = ["info", "warning", "error"] as const;
11
11
  export const DOC_DRIFT_STATUSES = ["ok", "drifted"] as const;
@@ -13,27 +13,17 @@ export const DOC_DRIFT_STATUSES = ["ok", "drifted"] as const;
13
13
  export type DocDriftSeverity = (typeof DOC_DRIFT_SEVERITIES)[number];
14
14
  export type DocDriftStatus = (typeof DOC_DRIFT_STATUSES)[number];
15
15
 
16
- export const DocDriftFindingSchema = Type.Object(
17
- {
18
- file: Type.String({ minLength: 1 }),
19
- description: Type.String({ minLength: 1 }),
20
- severity: Type.Union(
21
- DOC_DRIFT_SEVERITIES.map((value) => Type.Literal(value)),
22
- ),
23
- relatedFiles: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
24
- },
25
- { additionalProperties: false },
26
- );
16
+ export const DocDriftFindingSchema = z.object({
17
+ file: z.string().min(1),
18
+ description: z.string().min(1),
19
+ severity: z.enum(DOC_DRIFT_SEVERITIES),
20
+ relatedFiles: z.array(z.string().min(1)).optional(),
21
+ }).strict();
27
22
 
28
- export const DocDriftOutputSchema = Type.Object(
29
- {
30
- findings: Type.Array(DocDriftFindingSchema),
31
- status: Type.Union(
32
- DOC_DRIFT_STATUSES.map((value) => Type.Literal(value)),
33
- ),
34
- },
35
- { additionalProperties: false },
36
- );
23
+ export const DocDriftOutputSchema = z.object({
24
+ findings: z.array(DocDriftFindingSchema),
25
+ status: z.enum(DOC_DRIFT_STATUSES),
26
+ }).strict();
37
27
 
38
- export type DocDriftFinding = Static<typeof DocDriftFindingSchema>;
39
- export type DocDriftOutput = Static<typeof DocDriftOutputSchema>;
28
+ export type DocDriftFinding = z.infer<typeof DocDriftFindingSchema>;
29
+ export type DocDriftOutput = z.infer<typeof DocDriftOutputSchema>;
@@ -29,6 +29,8 @@ export interface RunFixPrAssessmentInput {
29
29
  model?: string;
30
30
  thinkingLevel?: string | null;
31
31
  maxAttempts?: number;
32
+ timeoutMs?: number;
33
+ maxCommentsPerBatch?: number;
32
34
  }
33
35
 
34
36
  interface BuildAssessmentPromptArgs {
@@ -74,6 +76,19 @@ function buildAssessmentPrompt(args: BuildAssessmentPromptArgs): string {
74
76
  ].join("\n");
75
77
  }
76
78
 
79
+ function chunkComments(comments: readonly PrComment[], maxCommentsPerBatch: number): PrComment[][] {
80
+ if (maxCommentsPerBatch <= 0 || comments.length <= maxCommentsPerBatch) {
81
+ return [[...comments]];
82
+ }
83
+
84
+ const chunks: PrComment[][] = [];
85
+ for (let index = 0; index < comments.length; index += maxCommentsPerBatch) {
86
+ chunks.push(comments.slice(index, index + maxCommentsPerBatch));
87
+ }
88
+ return chunks;
89
+ }
90
+
91
+
77
92
  /**
78
93
  * Run a schema-backed assessment over a cluster of PR comments.
79
94
  *
@@ -93,30 +108,54 @@ export async function runFixPrAssessment(
93
108
  }
94
109
 
95
110
  const schemaText = renderSchemaText(FixPrAssessmentBatchSchema);
96
- const prompt = buildAssessmentPrompt({
97
- schemaText,
98
- comments: input.comments,
99
- repo: input.repo,
100
- prNumber: input.prNumber,
101
- selectedTargetLabel: input.selectedTargetLabel,
102
- });
103
-
104
- return runWithOutputValidation<FixPrAssessmentBatch>(
105
- input.createAgentSession as any,
106
- {
107
- cwd: input.cwd,
108
- prompt,
109
- schema: schemaText,
110
- parse: (raw) =>
111
- parseStructuredOutput<FixPrAssessmentBatch>(raw, FixPrAssessmentBatchSchema),
112
- model: input.model,
113
- thinkingLevel: input.thinkingLevel ?? null,
114
- maxAttempts: input.maxAttempts,
115
- reliability: input.paths
116
- ? { paths: input.paths, cwd: input.cwd, command: "fix-pr", operation: "assessment" }
117
- : undefined,
118
- },
119
- );
111
+ const maxCommentsPerBatch = input.maxCommentsPerBatch ?? input.comments.length;
112
+ const commentChunks = chunkComments(input.comments, maxCommentsPerBatch);
113
+ const assessments: FixPrAssessmentBatch["assessments"] = [];
114
+ const rawOutputs: string[] = [];
115
+ let attempts = 0;
116
+
117
+ for (const comments of commentChunks) {
118
+ const prompt = buildAssessmentPrompt({
119
+ schemaText,
120
+ comments,
121
+ repo: input.repo,
122
+ prNumber: input.prNumber,
123
+ selectedTargetLabel: input.selectedTargetLabel,
124
+ });
125
+
126
+ const result = await runWithOutputValidation<FixPrAssessmentBatch>(
127
+ input.createAgentSession as any,
128
+ {
129
+ cwd: input.cwd,
130
+ prompt,
131
+ schema: schemaText,
132
+ parse: (raw) =>
133
+ parseStructuredOutput<FixPrAssessmentBatch>(raw, FixPrAssessmentBatchSchema),
134
+ model: input.model,
135
+ thinkingLevel: input.thinkingLevel ?? null,
136
+ maxAttempts: input.maxAttempts,
137
+ timeoutMs: input.timeoutMs,
138
+ reliability: input.paths
139
+ ? { paths: input.paths, cwd: input.cwd, command: "fix-pr", operation: "assessment" }
140
+ : undefined,
141
+ },
142
+ );
143
+
144
+ attempts += result.attempts;
145
+ if (result.status === "blocked") {
146
+ return { ...result, attempts };
147
+ }
148
+
149
+ rawOutputs.push(result.rawOutput);
150
+ assessments.push(...result.output.assessments);
151
+ }
152
+
153
+ return {
154
+ status: "ok",
155
+ output: { assessments },
156
+ rawOutput: rawOutputs.join("\n"),
157
+ attempts,
158
+ };
120
159
  }
121
160
 
122
161
  /**
@@ -5,35 +5,27 @@
5
5
  // against FixPrAssessmentBatchSchema; downstream work batches are derived
6
6
  // from this validated artifact, not from ad-hoc orchestration prose.
7
7
 
8
- import { Type, type Static } from "@sinclair/typebox";
8
+ import { z } from "zod/v4"
9
9
 
10
10
  export const FIX_PR_ASSESSMENT_VERDICTS = ["apply", "reject", "investigate"] as const;
11
11
  export type FixPrAssessmentVerdict = (typeof FIX_PR_ASSESSMENT_VERDICTS)[number];
12
12
 
13
- export const FixPrCommentAssessmentSchema = Type.Object(
14
- {
15
- commentId: Type.Integer(),
16
- verdict: Type.Union(
17
- FIX_PR_ASSESSMENT_VERDICTS.map((value) => Type.Literal(value)),
18
- ),
19
- rationale: Type.String({ minLength: 1 }),
20
- affectedFiles: Type.Array(Type.String({ minLength: 1 })),
21
- rippleEffects: Type.Array(Type.String({ minLength: 1 })),
22
- verificationPlan: Type.String({ minLength: 1 }),
23
- },
24
- { additionalProperties: false },
25
- );
13
+ export const FixPrCommentAssessmentSchema = z.object({
14
+ commentId: z.number().int(),
15
+ verdict: z.enum(FIX_PR_ASSESSMENT_VERDICTS),
16
+ rationale: z.string().min(1),
17
+ affectedFiles: z.array(z.string().min(1)),
18
+ rippleEffects: z.array(z.string().min(1)),
19
+ verificationPlan: z.string().min(1),
20
+ }).strict();
26
21
 
27
- export const FixPrAssessmentBatchSchema = Type.Object(
28
- {
29
- assessments: Type.Array(FixPrCommentAssessmentSchema),
30
- summary: Type.Optional(Type.String()),
31
- },
32
- { additionalProperties: false },
33
- );
22
+ export const FixPrAssessmentBatchSchema = z.object({
23
+ assessments: z.array(FixPrCommentAssessmentSchema),
24
+ summary: z.string().optional(),
25
+ }).strict();
34
26
 
35
- export type FixPrCommentAssessment = Static<typeof FixPrCommentAssessmentSchema>;
36
- export type FixPrAssessmentBatch = Static<typeof FixPrAssessmentBatchSchema>;
27
+ export type FixPrCommentAssessment = z.infer<typeof FixPrCommentAssessmentSchema>;
28
+ export type FixPrAssessmentBatch = z.infer<typeof FixPrAssessmentBatchSchema>;
37
29
 
38
30
  /**
39
31
  * A deterministic execution unit derived from a validated FixPrAssessmentBatch.
@@ -11,6 +11,30 @@ const INLINE_COMMENTS_JQ =
11
11
  const REVIEW_COMMENTS_JQ =
12
12
  '.[] | select(.body != null and .body != "") | {id, path: null, line: null, body, user: .user.login, userType: .user.type, createdAt: .submitted_at, updatedAt: .submitted_at, inReplyToId: null, diffHunk: null, state}';
13
13
 
14
+
15
+ const RESOLVED_REVIEW_THREAD_COMMENT_IDS_QUERY = `
16
+ query($owner: String!, $name: String!, $number: Int!, $endCursor: String) {
17
+ repository(owner: $owner, name: $name) {
18
+ pullRequest(number: $number) {
19
+ reviewThreads(first: 100, after: $endCursor) {
20
+ nodes {
21
+ isResolved
22
+ comments(first: 100) {
23
+ nodes {
24
+ databaseId
25
+ }
26
+ }
27
+ }
28
+ pageInfo {
29
+ hasNextPage
30
+ endCursor
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
36
+ `;
37
+
14
38
  export interface ClusteredPrComments<TTarget extends WorkspaceTarget = WorkspaceTarget> {
15
39
  allComments: PrComment[];
16
40
  commentsByTargetId: Map<string, PrComment[]>;
@@ -27,6 +51,30 @@ function appendComment(commentsByTargetId: Map<string, PrComment[]>, targetId: s
27
51
  commentsByTargetId.set(targetId, [comment]);
28
52
  }
29
53
 
54
+
55
+ function parseRepoOwnerAndName(repo: string): { owner: string; name: string } | null {
56
+ const separator = repo.indexOf("/");
57
+ if (separator <= 0 || separator === repo.length - 1) {
58
+ return null;
59
+ }
60
+
61
+ return {
62
+ owner: repo.slice(0, separator),
63
+ name: repo.slice(separator + 1),
64
+ };
65
+ }
66
+
67
+ function parseResolvedCommentIds(output: string): Set<number> {
68
+ const ids = new Set<number>();
69
+ for (const line of output.split(/\r?\n/)) {
70
+ const id = Number.parseInt(line.trim(), 10);
71
+ if (Number.isInteger(id)) {
72
+ ids.add(id);
73
+ }
74
+ }
75
+ return ids;
76
+ }
77
+
30
78
  export function parsePrCommentsJsonl(content: string): PrComment[] {
31
79
  return content
32
80
  .split(/\r?\n/)
@@ -49,6 +97,68 @@ export function stringifyPrCommentsJsonl(comments: readonly PrComment[]): string
49
97
  return `${comments.map((comment) => JSON.stringify(comment)).join("\n")}\n`;
50
98
  }
51
99
 
100
+ async function fetchResolvedReviewThreadCommentIds(
101
+ platform: Platform,
102
+ repo: string,
103
+ prNumber: number,
104
+ cwd: string,
105
+ ): Promise<Set<number> | string> {
106
+ const repoParts = parseRepoOwnerAndName(repo);
107
+ if (!repoParts) {
108
+ return `Invalid repository name: ${repo}`;
109
+ }
110
+
111
+ const result = await platform.exec(
112
+ "gh",
113
+ [
114
+ "api",
115
+ "graphql",
116
+ "--paginate",
117
+ "-f",
118
+ `query=${RESOLVED_REVIEW_THREAD_COMMENT_IDS_QUERY}`,
119
+ "-F",
120
+ `owner=${repoParts.owner}`,
121
+ "-F",
122
+ `name=${repoParts.name}`,
123
+ "-F",
124
+ `number=${prNumber}`,
125
+ "--jq",
126
+ ".data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == true) | .comments.nodes[].databaseId",
127
+ ],
128
+ { cwd },
129
+ );
130
+
131
+ if (result.code !== 0) {
132
+ return result.stderr || "gh api graphql failed while fetching resolved review threads";
133
+ }
134
+
135
+ return parseResolvedCommentIds(result.stdout);
136
+ }
137
+
138
+ function filterResolvedComments(content: string, resolvedCommentIds: ReadonlySet<number>): string {
139
+ if (!content.trim() || resolvedCommentIds.size === 0) {
140
+ return content;
141
+ }
142
+
143
+ const unresolvedLines = content
144
+ .split(/\r?\n/)
145
+ .filter((line) => {
146
+ const trimmed = line.trim();
147
+ if (!trimmed) {
148
+ return false;
149
+ }
150
+ try {
151
+ const comment = JSON.parse(trimmed) as Pick<PrComment, "id">;
152
+ return !resolvedCommentIds.has(comment.id);
153
+ } catch {
154
+ return true;
155
+ }
156
+ });
157
+
158
+ return unresolvedLines.length > 0 ? `${unresolvedLines.join("\n")}\n` : "";
159
+ }
160
+
161
+
52
162
  export function clusterPrCommentsByTarget<TTarget extends WorkspaceTarget>(
53
163
  targets: readonly TTarget[],
54
164
  comments: readonly PrComment[],
@@ -143,4 +253,13 @@ export async function fetchPrComments(
143
253
  if (inlineResult.code !== 0 && reviewResult.code !== 0) {
144
254
  return inlineResult.stderr || reviewResult.stderr || "gh api calls failed";
145
255
  }
256
+
257
+ const resolvedCommentIds = await fetchResolvedReviewThreadCommentIds(platform, repo, prNumber, cwd);
258
+ if (typeof resolvedCommentIds === "string") {
259
+ return resolvedCommentIds;
260
+ }
261
+
262
+ if (resolvedCommentIds.size > 0) {
263
+ fs.writeFileSync(outputPath, filterResolvedComments(fs.readFileSync(outputPath, "utf-8"), resolvedCommentIds));
264
+ }
146
265
  }