@teamclaws/teamclaw 2026.4.4 → 2026.5.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.
@@ -0,0 +1,221 @@
1
+ import type { SweepableIssue, SweepablePull, TeamAutoGithubClient } from "./github-client.js";
2
+ import type { TeamAutoRepo } from "./store.js";
3
+
4
+ /**
5
+ * Incremental sweep: turn a repo's changed issues/PRs into candidate work
6
+ * items, applying the per-repo policy (assignment rules, keyword/label
7
+ * filters, idempotency via the `seen` cursor map).
8
+ */
9
+
10
+ export type CandidateKind = "issueReview" | "takeOwnership" | "prReview" | "fullReview";
11
+
12
+ /** Roles that jointly author a scheduled full review (one section each). */
13
+ export const JOINT_REVIEW_ROLES = ["architect", "qa", "security-engineer"] as const;
14
+
15
+ const JOINT_REVIEW_FOCUS: Record<(typeof JOINT_REVIEW_ROLES)[number], string> = {
16
+ architect: "architecture and structure: module boundaries, layering, README/docs accuracy, maintainability hotspots, dead or duplicated code paths",
17
+ qa: "quality and tests: test coverage gaps, flaky-test hotspots, error-handling weaknesses, missing failure-path tests, CI blind spots",
18
+ "security-engineer": "security surface: dependency risks, secret handling, injection/validation gaps, auth-sensitive paths, unsafe defaults",
19
+ };
20
+
21
+ export type Candidate = {
22
+ kind: CandidateKind;
23
+ repoId: string;
24
+ key: string; // idempotency key, e.g. "owner/repo#issue-42"
25
+ number: number;
26
+ title: string;
27
+ role: "qa" | "developer" | "architect" | "security-engineer";
28
+ /** Collaboration contract: reviews are read-only, ownership work writes. */
29
+ writeMode: "read-only" | "write";
30
+ /** Shared full-review cycle id: write-backs group on it (umbrella issue). */
31
+ cycle?: number;
32
+ reason: string;
33
+ context: string;
34
+ };
35
+
36
+ function matchesAny(text: string, keywords: string[]): boolean {
37
+ const lower = text.toLowerCase();
38
+ return keywords.some((k) => k.trim() && lower.includes(k.trim().toLowerCase()));
39
+ }
40
+
41
+ function labelAllowed(issue: SweepableIssue, repo: TeamAutoRepo): boolean {
42
+ const { include, exclude } = repo.policy.labelFilter;
43
+ if (exclude.some((l) => issue.labels.includes(l))) {
44
+ return false;
45
+ }
46
+ if (include.length && !include.some((l) => issue.labels.includes(l))) {
47
+ return false;
48
+ }
49
+ return true;
50
+ }
51
+
52
+ function keywordAllowed(title: string, repo: TeamAutoRepo): boolean {
53
+ const { include, exclude } = repo.policy.keywordFilter;
54
+ if (exclude.length && matchesAny(title, exclude)) {
55
+ return false;
56
+ }
57
+ if (include.length && !matchesAny(title, include)) {
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+
63
+ const TEAMCLAW_MARKER_RE = /\[teamclaw(?::\w+)?\]/i;
64
+
65
+ function truncate(text: string, max: number): string {
66
+ return text.length > max ? text.slice(0, max) + "..." : text;
67
+ }
68
+
69
+ export async function sweepRepo(
70
+ repo: TeamAutoRepo,
71
+ client: TeamAutoGithubClient,
72
+ now = Date.now(),
73
+ ): Promise<{ candidates: Candidate[]; issues: SweepableIssue[]; pulls: SweepablePull[] }> {
74
+ const [owner, name] = repo.id.split("/");
75
+ const issues = await client.listIssues(owner, name, repo.cursors.lastIssueSince, repo.cursors.etags);
76
+ const pulls = repo.policy.actions.prReview
77
+ ? await client.listPulls(owner, name, repo.cursors.etags)
78
+ : [];
79
+ const candidates: Candidate[] = [];
80
+
81
+ for (const issue of issues) {
82
+ // Dedup: seen map survives sweeps; a closed-then-reopened issue updates.
83
+ const key = `${repo.id}#issue-${issue.number}`;
84
+ const updatedAtMs = Date.parse(issue.updatedAt) || 0;
85
+ if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
86
+ continue;
87
+ }
88
+ // NOTE: no first-sweep gate here. Gating candidates on "first sweep"
89
+ // combined with the dry-run not advancing cursors deadlocked repos in
90
+ // observe-only mode forever (zero candidates -> dryRunDone never set).
91
+ // Backlog protection comes from the per-sweep cap + one dry-run pass.
92
+ if (!labelAllowed(issue, repo) || !keywordAllowed(issue.title, repo)) {
93
+ continue;
94
+ }
95
+ if (repo.policy.skipAssignedToHumans && issue.assignees.length > 0) {
96
+ continue;
97
+ }
98
+ // Never self-assign or review our own threads.
99
+ if (TEAMCLAW_MARKER_RE.test(issue.title) || TEAMCLAW_MARKER_RE.test(issue.body)) {
100
+ continue;
101
+ }
102
+ const base = {
103
+ repoId: repo.id,
104
+ key,
105
+ number: issue.number,
106
+ role: "qa" as const,
107
+ writeMode: "read-only" as const,
108
+ };
109
+ if (repo.policy.actions.issueReview) {
110
+ candidates.push({
111
+ ...base,
112
+ kind: "issueReview",
113
+ title: truncate(`Review issue #${issue.number}: ${issue.title}`, 120),
114
+ reason: "new/updated issue needs triage",
115
+ context: `Issue #${issue.number} by @${issue.user}\nTitle: ${issue.title}\nLabels: ${issue.labels.join(", ") || "none"}\nLink: ${issue.htmlUrl}\n\nBody:\n${truncate(issue.body, 4000)}`,
116
+ });
117
+ }
118
+ if (repo.policy.actions.takeOwnership && issue.state === "open") {
119
+ candidates.push({
120
+ ...base,
121
+ kind: "takeOwnership",
122
+ role: "developer",
123
+ writeMode: "write",
124
+ title: truncate(`Take ownership of issue #${issue.number}: ${issue.title}`, 120),
125
+ reason: "unassigned issue eligible for autonomous ownership",
126
+ context: `Own and implement issue #${issue.number}: ${issue.title}\nLink: ${issue.htmlUrl}\n\nBody:\n${truncate(issue.body, 6000)}`,
127
+ });
128
+ }
129
+ }
130
+
131
+ for (const pull of pulls) {
132
+ const key = `${repo.id}#pr-${pull.number}`;
133
+ const updatedAtMs = Date.parse(pull.updated_at) || 0;
134
+ if ((repo.cursors.seen[key] ?? 0) >= updatedAtMs) {
135
+ continue;
136
+ }
137
+ // See the issue-loop note: no first-sweep gate (deadlock source).
138
+ // Skip our own PRs and drafts.
139
+ if (pull.head.startsWith("teamclaw/") || pull.draft || TEAMCLAW_MARKER_RE.test(pull.title)) {
140
+ continue;
141
+ }
142
+ if (repo.policy.actions.prReview) {
143
+ candidates.push({
144
+ repoId: repo.id,
145
+ key,
146
+ kind: "prReview",
147
+ number: pull.number,
148
+ role: "qa" as const,
149
+ writeMode: "read-only" as const,
150
+ title: truncate(`Review PR #${pull.number}: ${pull.title}`, 120),
151
+ reason: "new/updated pull request needs review",
152
+ context: `PR #${pull.number} by @${pull.user} (head: ${pull.head})\nLink: ${pull.htmlUrl}\n\nDescription:\n${truncate(pull.body, 4000)}`,
153
+ });
154
+ }
155
+ }
156
+
157
+ // Periodic full review (weekly/daily), independent of per-object cursors.
158
+ if (repo.policy.actions.fullReview !== "off") {
159
+ const intervalMs = repo.policy.actions.fullReview === "daily" ? 24 * 3600_000 : 7 * 24 * 3600_000;
160
+ // Interval-gated only (the old !firstSweep gate could never open for a
161
+ // repo whose first sweep observed nothing - see the deadlock note above).
162
+ if (now - repo.cursors.lastFullReviewAt >= intervalMs) {
163
+ const cycle = Math.floor(now / intervalMs);
164
+ // Joint review: one candidate per role, one shared cycle. Each role's
165
+ // reply becomes a labeled section of a single umbrella review issue
166
+ // (the write-back reconciler groups by the cycle key).
167
+ for (const role of JOINT_REVIEW_ROLES) {
168
+ candidates.push({
169
+ repoId: repo.id,
170
+ key: `${repo.id}#fullreview-${cycle}-${role}`,
171
+ kind: "fullReview",
172
+ number: 0,
173
+ role,
174
+ writeMode: "read-only" as const,
175
+ cycle,
176
+ title: `Full repository review (${role}): ${repo.id}`,
177
+ reason: `scheduled ${repo.policy.actions.fullReview} full review (joint, ${role} section)`,
178
+ context: [
179
+ `Perform the ${role} section of a joint full-repository review of ${repo.id}.`,
180
+ `Your focus: ${JOINT_REVIEW_FOCUS[role]}.`,
181
+ "Other roles cover complementary areas in parallel - do NOT duplicate their scope; go deep on yours.",
182
+ "Your reply becomes the " + role + " section of the joint review issue on GitHub. Do not change code.",
183
+ ].join("\n"),
184
+ });
185
+ }
186
+ }
187
+ }
188
+
189
+ return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
190
+ }
191
+
192
+ /** Advance cursors after tasks were enqueued (or observed on first sweep). */
193
+ export function advanceCursors(repo: TeamAutoRepo, issues: SweepableIssue[], pulls: SweepablePull[], now = Date.now()): void {
194
+ for (const issue of issues) {
195
+ repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
196
+ }
197
+ for (const pull of pulls) {
198
+ repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
199
+ }
200
+ // Cap the seen map so it cannot grow unbounded.
201
+ const entries = Object.entries(repo.cursors.seen);
202
+ if (entries.length > 2000) {
203
+ entries.sort((a, b) => a[1] - b[1]);
204
+ for (const [key] of entries.slice(0, entries.length - 2000)) {
205
+ delete repo.cursors.seen[key];
206
+ }
207
+ }
208
+ // `since` cursors track the newest observed object time, never the sweep's
209
+ // wall clock - objects updated between fetch and save must not fall behind
210
+ // the cursor forever.
211
+ let maxIssueUpdated = 0;
212
+ let maxPullUpdated = 0;
213
+ for (const issue of issues) {
214
+ maxIssueUpdated = Math.max(maxIssueUpdated, Date.parse(issue.updatedAt) || now);
215
+ }
216
+ for (const pull of pulls) {
217
+ maxPullUpdated = Math.max(maxPullUpdated, Date.parse(pull.updated_at) || now);
218
+ }
219
+ repo.cursors.lastIssueSince = Math.max(repo.cursors.lastIssueSince, maxIssueUpdated);
220
+ repo.cursors.lastPrSince = Math.max(repo.cursors.lastPrSince, maxPullUpdated);
221
+ }