@teamclaws/teamclaw 2026.4.3-2 → 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,103 @@
1
+ import type { TeamAutoRepo, TeamAutoRepoNorms } from "./store.js";
2
+ import type { TeamAutoGithubClient } from "./github-client.js";
3
+ import type { TeamAutoRepoSync } from "./repo-sync.js";
4
+
5
+ /**
6
+ * Norms learning: absorb the target repo's collaboration conventions
7
+ * (CONTRIBUTING, issue/PR templates, commit style) so every TeamClaw worker
8
+ * prompt for that repo carries them - "转手目标仓库里面的协作规范".
9
+ */
10
+
11
+ const CONVENTIONAL_RE = /^(\w+)(\([^)]+\))?!?:\s.+/;
12
+
13
+ function detectCommitStyle(messages: string[]): string {
14
+ if (!messages.length) {
15
+ return "unspecified - keep subject lines short and descriptive";
16
+ }
17
+ const matches = messages.filter((m) => CONVENTIONAL_RE.test(m)).length;
18
+ if (matches >= messages.length * 0.6) {
19
+ return "conventional commits (type(scope)!: subject)";
20
+ }
21
+ const chinese = messages.filter((m) => /[\u4e00-\u9fff]/.test(m)).length;
22
+ if (chinese >= messages.length * 0.6) {
23
+ return "plain subject lines, Chinese";
24
+ }
25
+ return "plain subject lines, English";
26
+ }
27
+
28
+ export async function learnNorms(
29
+ repo: TeamAutoRepo,
30
+ client: TeamAutoGithubClient,
31
+ sync: TeamAutoRepoSync,
32
+ cloneUrl: string,
33
+ defaultBranch: string,
34
+ ): Promise<TeamAutoRepoNorms> {
35
+ let dir: string | null = null;
36
+ try {
37
+ dir = await sync.ensureCloned(repo.id, cloneUrl, defaultBranch);
38
+ } catch {
39
+ dir = null;
40
+ }
41
+
42
+ const [owner, name] = repo.id.split("/");
43
+ const fetchRemote = async (apiPath: string): Promise<string | null> => {
44
+ try {
45
+ const { data } = await client.request("GET", apiPath);
46
+ const record = data as { content?: string; encoding?: string };
47
+ if (typeof record.content === "string" && record.encoding === "base64") {
48
+ return Buffer.from(record.content, "base64").toString("utf8");
49
+ }
50
+ } catch {
51
+ // absent file is fine
52
+ }
53
+ return null;
54
+ };
55
+
56
+ const contributing =
57
+ (await fetchRemote(`/repos/${owner}/${name}/contents/CONTRIBUTING.md`)) ??
58
+ (dir ? await sync.readFileIfPresent(dir, "CONTRIBUTING.md") : null);
59
+ const issueTemplate =
60
+ (await fetchRemote(`/repos/${owner}/${name}/contents/.github/ISSUE_TEMPLATE.md`)) ??
61
+ (dir ? await sync.readFileIfPresent(dir, ".github/ISSUE_TEMPLATE.md") : null);
62
+ const prTemplate =
63
+ (await fetchRemote(`/repos/${owner}/${name}/contents/.github/PULL_REQUEST_TEMPLATE.md`)) ??
64
+ (dir ? await sync.readFileIfPresent(dir, ".github/PULL_REQUEST_TEMPLATE.md") : null);
65
+
66
+ let commitStyle = "unspecified";
67
+ if (dir) {
68
+ try {
69
+ commitStyle = detectCommitStyle(await sync.recentCommitMessages(dir, 100));
70
+ } catch {
71
+ commitStyle = "unspecified";
72
+ }
73
+ }
74
+
75
+ return {
76
+ commitStyle,
77
+ issueTemplate: issueTemplate?.slice(0, 2000) ?? null,
78
+ prTemplate: prTemplate?.slice(0, 2000) ?? null,
79
+ contributing: contributing?.slice(0, 4000) ?? null,
80
+ learnedAt: Date.now(),
81
+ };
82
+ }
83
+
84
+ /** Render the learned norms into a compact prompt block for workers. */
85
+ export function renderNormsBlock(norms: TeamAutoRepoNorms | null, repoId: string): string {
86
+ if (!norms) {
87
+ return `Target repo: ${repoId}\nCollaboration norms: not learned yet - follow common sense and read existing issues/PRs for style.\n`;
88
+ }
89
+ const lines = [
90
+ `Target repo: ${repoId}`,
91
+ `Commit style: ${norms.commitStyle}`,
92
+ ];
93
+ if (norms.contributing) {
94
+ lines.push(`CONTRIBUTING.md excerpt:\n${norms.contributing.slice(0, 1500)}`);
95
+ }
96
+ if (norms.issueTemplate) {
97
+ lines.push(`Issue template excerpt:\n${norms.issueTemplate.slice(0, 800)}`);
98
+ }
99
+ if (norms.prTemplate) {
100
+ lines.push(`PR template excerpt:\n${norms.prTemplate.slice(0, 800)}`);
101
+ }
102
+ return lines.join("\n") + "\n";
103
+ }
@@ -0,0 +1,218 @@
1
+ import { execFile } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ import type { GithubAuthManager } from "../controller/github-auth.js";
7
+ import { repoSlugToDirName, resolveTeamAutoPaths } from "./store.js";
8
+
9
+ const exec = promisify(execFile);
10
+
11
+ export const TEAMCLAW_BRANCH_PREFIX = "teamclaw/";
12
+
13
+ /** TaskInfo.projectDir slug for a bound repo (relative to the projects dir). */
14
+ export function teamAutoProjectDir(repoId: string): string {
15
+ return `teamauto/${repoSlugToDirName(repoId)}`;
16
+ }
17
+
18
+ /**
19
+ * Git operations for TeamAuto. Authentication uses the device-flow token
20
+ * inline in the remote URL (x-access-token basic auth) - proven to survive
21
+ * GitHub's smart-HTTP redirects where extraheader injection does not. The
22
+ * token never touches disk: remotes are rewritten per invocation and the
23
+ * on-disk remote stays a clean https URL.
24
+ */
25
+
26
+ function gitEnv(): Record<string, string> {
27
+ return {
28
+ ...process.env,
29
+ GIT_TERMINAL_PROMPT: "0",
30
+ GIT_ASKPASS: "/bin/true",
31
+ GIT_CONFIG_NOSYSTEM: "1",
32
+ };
33
+ }
34
+
35
+ async function run(args: string[], cwd?: string): Promise<string> {
36
+ const { stdout } = await exec("git", args, {
37
+ cwd,
38
+ env: gitEnv(),
39
+ maxBuffer: 16 * 1024 * 1024,
40
+ timeout: 120_000,
41
+ });
42
+ return stdout;
43
+ }
44
+
45
+ export function createRepoSync(auth: GithubAuthManager, logger: { warn: (m: string) => void }) {
46
+ async function tokenizedUrl(cloneUrl: string): Promise<string> {
47
+ const token = await auth.getAccessToken();
48
+ const clean = cloneUrl.replace(/^https:\/\//, "").replace(/\.git$/, "");
49
+ return `https://x-access-token:${token}@${clean}.git`;
50
+ }
51
+
52
+ async function repoDir(repoId: string): Promise<string> {
53
+ const { reposRoot, legacyReposRoot } = resolveTeamAutoPaths();
54
+ await fs.mkdir(reposRoot, { recursive: true });
55
+ const dir = path.join(reposRoot, repoSlugToDirName(repoId));
56
+ const legacy = path.join(legacyReposRoot, repoSlugToDirName(repoId));
57
+ // One-time migration: move pre-workspace clones into the projects tree.
58
+ try {
59
+ await fs.stat(path.join(legacy, ".git"));
60
+ try {
61
+ await fs.stat(path.join(dir, ".git"));
62
+ } catch {
63
+ await fs.mkdir(path.dirname(dir), { recursive: true });
64
+ try {
65
+ await fs.rename(legacy, dir);
66
+ } catch {
67
+ // Cross-device (EXDEV): copy then remove the original.
68
+ await fs.cp(legacy, dir, { recursive: true });
69
+ await fs.rm(legacy, { recursive: true, force: true });
70
+ }
71
+ }
72
+ } catch {
73
+ // No legacy clone - normal path.
74
+ }
75
+ return dir;
76
+ }
77
+
78
+ /** Clone if absent, otherwise fetch + reset to the default branch tip. */
79
+ async function ensureCloned(repoId: string, cloneUrl: string, defaultBranch: string): Promise<string> {
80
+ const dir = await repoDir(repoId);
81
+ const gitDir = path.join(dir, ".git");
82
+ let exists = false;
83
+ try {
84
+ const stat = await fs.stat(gitDir);
85
+ exists = stat.isDirectory() || stat.isFile();
86
+ } catch {
87
+ exists = false;
88
+ }
89
+ if (!exists) {
90
+ const authed = await tokenizedUrl(cloneUrl);
91
+ await run(["clone", "--filter=blob:none", "--no-checkout", authed, dir]);
92
+ await run(["checkout", defaultBranch], dir);
93
+ } else {
94
+ const authed = await tokenizedUrl(cloneUrl);
95
+ // Fetch via a one-shot URL override; the stored remote stays clean.
96
+ await run(["fetch", authed, defaultBranch], dir);
97
+ await run(["reset", "--hard", `FETCH_HEAD`], dir);
98
+ }
99
+ return dir;
100
+ }
101
+
102
+ async function currentSha(dir: string): Promise<string> {
103
+ return (await run(["rev-parse", "HEAD"], dir)).trim();
104
+ }
105
+
106
+ async function recentCommitMessages(dir: string, count: number): Promise<string[]> {
107
+ const out = await run(["log", `--format=%s`, `-n`, String(count)], dir);
108
+ return out.split("\n").filter(Boolean);
109
+ }
110
+
111
+ async function readFileIfPresent(dir: string, relPath: string): Promise<string | null> {
112
+ try {
113
+ return await fs.readFile(path.join(dir, relPath), "utf8");
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ /** Safety-checked worktree path for repo files (blocks traversal). */
120
+ function safeRepoPath(dir: string, relPath: string): string | null {
121
+ const target = path.resolve(dir, relPath);
122
+ if (!target.startsWith(path.resolve(dir) + path.sep)) {
123
+ return null;
124
+ }
125
+ return target;
126
+ }
127
+
128
+ async function createWorkBranch(dir: string, name: string): Promise<void> {
129
+ await run(["checkout", "-B", name], dir);
130
+ }
131
+
132
+ async function commitAll(dir: string, message: string, authorName: string, authorEmail: string): Promise<boolean> {
133
+ const status = await run(["status", "--porcelain"], dir);
134
+ if (!status.trim()) {
135
+ return false;
136
+ }
137
+ await run(["add", "-A"], dir);
138
+ await run(["-c", `user.name=${authorName}`, "-c", `user.email=${authorEmail}`, "commit", "-m", message], dir);
139
+ return true;
140
+ }
141
+
142
+ async function pushBranch(repoId: string, dir: string, cloneUrl: string, branch: string): Promise<void> {
143
+ const authed = await tokenizedUrl(cloneUrl);
144
+ try {
145
+ await run(["push", authed, `HEAD:refs/heads/${branch}`], dir);
146
+ } catch (err) {
147
+ logger.warn(`TeamAuto: push failed for ${repoId}#${branch}: ${err instanceof Error ? err.message : String(err)}`);
148
+ throw err;
149
+ }
150
+ }
151
+
152
+ /** Deterministic worktree dir (relative name) for a TeamAuto write task. */
153
+ function taskWorktreeDirName(repoId: string, taskId: string): string {
154
+ return `${teamAutoProjectDir(repoId)}__task-${taskId.replace(/[^\w-]/g, "")}`;
155
+ }
156
+
157
+ function taskBranchName(taskId: string): string {
158
+ return `teamclaw/task-${taskId.replace(/[^\w-]/g, "")}`;
159
+ }
160
+
161
+ /**
162
+ * Collaboration contract: write tasks execute in a dedicated git worktree
163
+ * branched from HEAD. Reuses an existing worktree (resume-safe) so the
164
+ * checkpoint/retry path lands in the same tree.
165
+ */
166
+ async function ensureTaskWorktree(repoId: string, taskId: string): Promise<string> {
167
+ const base = await repoDir(repoId);
168
+ const wtName = taskWorktreeDirName(repoId, taskId);
169
+ // wtName carries the teamauto/ level for the REL path; the physical dir is
170
+ // a SIBLING of the base checkout (path.join would nest teamauto/ twice).
171
+ const wtPath = path.join(path.dirname(base), path.basename(wtName));
172
+ if (await fs.access(path.join(wtPath, ".git")).then(() => true, () => false)) {
173
+ return wtPath; // resume case
174
+ }
175
+ await run(["worktree", "add", "-b", taskBranchName(taskId), wtPath, "HEAD"], base);
176
+ logger.warn(`TeamAuto: worktree ${wtName} (branch ${taskBranchName(taskId)}) for ${taskId}`);
177
+ return wtPath;
178
+ }
179
+
180
+ /** Remove a task worktree and its local branch (terminal cleanup). */
181
+ async function removeTaskWorktree(repoId: string, taskId: string): Promise<void> {
182
+ const base = await repoDir(repoId);
183
+ const wtName = taskWorktreeDirName(repoId, taskId);
184
+ const wtPath = path.join(path.dirname(base), path.basename(wtName));
185
+ try {
186
+ if (await fs.access(wtPath).then(() => true, () => false)) {
187
+ await run(["worktree", "remove", "--force", wtPath], base);
188
+ }
189
+ await run(["branch", "-D", taskBranchName(taskId)], base).catch(() => undefined);
190
+ } catch (err) {
191
+ logger.warn(`TeamAuto: worktree cleanup failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);
192
+ }
193
+ }
194
+
195
+ function taskWorktreeRelDir(repoId: string, taskId: string): string {
196
+ return taskWorktreeDirName(repoId, taskId);
197
+ }
198
+
199
+ /** True when HEAD has commits beyond the base branch (worktree delivery). */
200
+ async function branchHasCommits(dir: string, baseBranch: string): Promise<boolean> {
201
+ try {
202
+ const out = await run(["rev-list", "--count", "HEAD", "--not", baseBranch], dir);
203
+ return Number(out.trim()) > 0;
204
+ } catch {
205
+ // Base branch name unknown/unfetched - fall back to diff against first parent chain
206
+ try {
207
+ const root = await run(["rev-list", "--max-parents=0", "HEAD"], dir);
208
+ return root.trim().length > 0;
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ }
214
+
215
+ return { ensureCloned, currentSha, recentCommitMessages, readFileIfPresent, safeRepoPath, createWorkBranch, commitAll, pushBranch, ensureTaskWorktree, removeTaskWorktree, taskWorktreeRelDir, taskBranchName, branchHasCommits, repoDir };
216
+ }
217
+
218
+ export type TeamAutoRepoSync = ReturnType<typeof createRepoSync>;
@@ -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
+ }