@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.
package/src/roles.ts CHANGED
@@ -1,6 +1,20 @@
1
1
  import type { RoleDefinition, RoleId } from "./types.js";
2
2
  import { buildRoleOperatingRules, buildWorkerMemoryContractRules, composePrompt } from "./prompt-policy.js";
3
3
 
4
+ const TEAMCLAW_ROLE_IDS_TEXT = [
5
+ "pm",
6
+ "architect",
7
+ "developer",
8
+ "qa",
9
+ "release-engineer",
10
+ "infra-engineer",
11
+ "devops",
12
+ "security-engineer",
13
+ "designer",
14
+ "marketing",
15
+ "data-engineer",
16
+ ];
17
+
4
18
  const ROLES: RoleDefinition[] = [
5
19
  {
6
20
  id: "pm",
@@ -257,6 +271,44 @@ const ROLES: RoleDefinition[] = [
257
271
  ].join("\n"),
258
272
  suggestedNextRoles: ["pm", "designer"],
259
273
  },
274
+ {
275
+ id: "data-engineer",
276
+ label: "Data Engineer",
277
+ icon: "\uD83D\uDCCA",
278
+ description: "Data pipeline design, ETL, data modeling",
279
+ capabilities: [
280
+ "data-modeling", "etl-pipeline", "data-quality", "sql-optimization",
281
+ ],
282
+ recommendedSkills: ["find-skills"],
283
+ systemPrompt: [
284
+ "You are a Data Engineer in a virtual software team.",
285
+ "Your core responsibilities include designing, building, and maintaining data pipelines,",
286
+ "ETL processes, data models, and ensuring data quality across systems.",
287
+ "",
288
+ "Scope of expertise:",
289
+ "- Data Pipeline Design: batch and streaming pipelines (Apache Spark, Airflow, dbt, Flink, Kafka)",
290
+ "- ETL/ELT Processes: extraction, transformation, loading patterns; incremental vs. full refresh strategies",
291
+ "- Data Modeling: dimensional modeling (star/snowflake schemas), Data Vault, event-sourced modeling, normalization vs. denormalization trade-offs",
292
+ "- Data Quality: validation frameworks, anomaly detection, data profiling, SLA monitoring, lineage tracking",
293
+ "- SQL Optimization: query performance tuning, indexing strategies, execution plan analysis, partitioning",
294
+ "- Data Storage: relational databases (PostgreSQL, MySQL), data warehouses (Snowflake, BigQuery, Redshift), data lakes (Delta Lake, Iceberg, Hudi)",
295
+ "- Orchestration: workflow scheduling, dependency management, idempotent pipeline design, backfill strategies",
296
+ "- Data Integration: API ingestion, CDC (Change Data Capture), schema evolution, data contracts",
297
+ "",
298
+ "When receiving tasks:",
299
+ "1. Always produce concrete, actionable data specifications (not vague guidance).",
300
+ "2. Include schema definitions (DDL), pipeline DAGs or flow diagrams (in ASCII/mermaid if helpful), and configuration snippets.",
301
+ "3. Consider data freshness, latency, and throughput requirements when choosing pipeline architectures.",
302
+ "4. Design for data quality from the start: include validation checks, monitoring, and alerting in every pipeline.",
303
+ "5. Prefer idempotent and reversible transformations to simplify recovery and debugging.",
304
+ "6. Document data lineage and ownership so downstream consumers can trace data origins.",
305
+ "7. Collaborate closely with Developers on data API contracts and with Architects on storage infrastructure.",
306
+ "8. If the required data sources, credentials, or infrastructure are unavailable in the current environment, explicitly report the blocker and request clarification instead of inventing a nonexistent system.",
307
+ "",
308
+ "Output format: Provide structured specifications with clear sections for pipeline architecture, data models (schema DDL), quality rules, and operational runbooks.",
309
+ ].join("\n"),
310
+ suggestedNextRoles: ["developer", "infra-engineer"],
311
+ },
260
312
  ];
261
313
 
262
314
  for (const role of ROLES) {
package/src/state.ts CHANGED
@@ -2,12 +2,74 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  import type {
5
+ RoleId,
5
6
  StartupProvisioningReadiness,
6
7
  TeamProvisioningState,
7
8
  TeamState,
8
9
  WorkerIdentity,
9
10
  } from "./types.js";
10
11
 
12
+ const STATE_VERSION = 2;
13
+
14
+ function migrateState(raw: unknown): TeamState | null {
15
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
16
+ return null;
17
+ }
18
+ const state = raw as Record<string, unknown>;
19
+
20
+ // Basic structural guard — same checks as the old loadTeamState
21
+ if (
22
+ typeof state.teamName !== "string" ||
23
+ typeof state.createdAt !== "number" ||
24
+ typeof state.updatedAt !== "number" ||
25
+ !state.workers ||
26
+ !state.tasks
27
+ ) {
28
+ return null;
29
+ }
30
+
31
+ // Ensure required nested objects exist (defensive, same as before)
32
+ if (!state.controllerRuns || typeof state.controllerRuns !== "object") {
33
+ state.controllerRuns = {};
34
+ }
35
+ if (!state.projects || typeof state.projects !== "object") {
36
+ state.projects = {};
37
+ }
38
+ if (!Array.isArray(state.messages)) {
39
+ state.messages = [];
40
+ }
41
+ if (!state.clarifications || typeof state.clarifications !== "object") {
42
+ state.clarifications = {};
43
+ }
44
+ if (state.repo && typeof state.repo !== "object") {
45
+ delete state.repo;
46
+ }
47
+ if (!state.provisioning || typeof state.provisioning !== "object") {
48
+ state.provisioning = createEmptyProvisioningState();
49
+ } else {
50
+ const prov = state.provisioning as Record<string, unknown>;
51
+ if (!prov.workers || typeof prov.workers !== "object") {
52
+ prov.workers = {};
53
+ }
54
+ prov.startupReadiness = normalizeStartupReadiness(prov.startupReadiness);
55
+ }
56
+
57
+ const version = typeof state.version === "number" ? state.version : 1;
58
+
59
+ if (version > STATE_VERSION) {
60
+ throw new Error(
61
+ `Saved team state is version ${version}, but this software only supports up to version ${STATE_VERSION}. ` +
62
+ "Please update TeamClaw to a newer version that supports this state format.",
63
+ );
64
+ }
65
+
66
+ // Version 1 → 2: no new required fields beyond `version` itself.
67
+ // startupReadiness was already optional and handled by normalizeStartupReadiness above.
68
+ state.version = STATE_VERSION;
69
+
70
+ return state as unknown as TeamState;
71
+ }
72
+
11
73
  function resolvePluginStateDir(): string {
12
74
  const explicitStateDir = process.env.OPENCLAW_STATE_DIR?.trim();
13
75
  if (explicitStateDir) {
@@ -54,7 +116,7 @@ function normalizeStartupReadiness(value: unknown): StartupProvisioningReadiness
54
116
  startedAt,
55
117
  checkedAt,
56
118
  attempts,
57
- requiredRoles,
119
+ requiredRoles: requiredRoles as RoleId[],
58
120
  readyWorkerIds,
59
121
  message,
60
122
  };
@@ -87,39 +149,8 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
87
149
  const filePath = path.join(STATE_DIR, `${teamName}-team-state.json`);
88
150
  try {
89
151
  const raw = await fs.readFile(filePath, "utf8");
90
- const parsed = JSON.parse(raw) as TeamState;
91
- if (
92
- typeof parsed.teamName !== "string" ||
93
- typeof parsed.createdAt !== "number" ||
94
- typeof parsed.updatedAt !== "number" ||
95
- !parsed.workers ||
96
- !parsed.tasks
97
- ) {
98
- return null;
99
- }
100
- if (!parsed.controllerRuns || typeof parsed.controllerRuns !== "object") {
101
- parsed.controllerRuns = {};
102
- }
103
- if (!parsed.projects || typeof parsed.projects !== "object") {
104
- parsed.projects = {};
105
- }
106
- if (!Array.isArray(parsed.messages)) {
107
- parsed.messages = [];
108
- }
109
- if (!parsed.clarifications || typeof parsed.clarifications !== "object") {
110
- parsed.clarifications = {};
111
- }
112
- if (parsed.repo && typeof parsed.repo !== "object") {
113
- delete parsed.repo;
114
- }
115
- if (!parsed.provisioning || typeof parsed.provisioning !== "object") {
116
- parsed.provisioning = createEmptyProvisioningState();
117
- }
118
- if (!parsed.provisioning.workers || typeof parsed.provisioning.workers !== "object") {
119
- parsed.provisioning.workers = {};
120
- }
121
- parsed.provisioning.startupReadiness = normalizeStartupReadiness(parsed.provisioning.startupReadiness);
122
- return parsed;
152
+ const parsed = JSON.parse(raw);
153
+ return migrateState(parsed);
123
154
  } catch {
124
155
  return null;
125
156
  }
@@ -128,6 +159,7 @@ async function loadTeamState(teamName: string): Promise<TeamState | null> {
128
159
  async function saveTeamState(state: TeamState): Promise<void> {
129
160
  await ensureDir(STATE_DIR);
130
161
  const filePath = path.join(STATE_DIR, `${state.teamName}-team-state.json`);
162
+ state.version = STATE_VERSION;
131
163
  state.updatedAt = Date.now();
132
164
  state.provisioning = state.provisioning && typeof state.provisioning === "object"
133
165
  ? state.provisioning
@@ -14,7 +14,15 @@ import {
14
14
  import { getRole } from "./roles.js";
15
15
  import type { RoleId, TaskAssignmentPayload, TaskExecutionEventInput, WorkerTaskResultContract } from "./types.js";
16
16
 
17
+ const TEAMCLAW_ROLE_IDS_TEXT = [
18
+ "pm", "architect", "developer", "qa",
19
+ "release-engineer", "infra-engineer", "devops", "security-engineer",
20
+ "designer", "marketing", "data-engineer",
21
+ ];
22
+
17
23
  const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
24
+ /** Checkpoint heartbeat cadence (resume support). */
25
+ const CHECKPOINT_EMIT_INTERVAL_MS = 15_000;
18
26
  const SESSION_PROGRESS_MESSAGE_LIMIT = 200;
19
27
  const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
20
28
  const RUN_WAIT_SLICE_MS = 30_000;
@@ -58,18 +66,24 @@ export type TaskExecutorResult = {
58
66
  contract?: Record<string, unknown>;
59
67
  };
60
68
 
69
+ import type { PluginConfig } from "./types.js";
70
+
61
71
  export type RoleTaskExecutorDeps = {
62
72
  runtime: OpenClawPluginApi["runtime"];
63
73
  logger: PluginLogger;
64
74
  role: RoleId;
65
75
  taskTimeoutMs: number;
76
+ /** Full plugin config; used for per-role model overrides. */
77
+ config?: Pick<PluginConfig, "roleModelOverrides">;
66
78
  getSessionKey: (assignment: TaskAssignmentPayload) => string;
67
79
  getIdempotencyKey?: (assignment: TaskAssignmentPayload) => string;
68
80
  reportExecutionEvent?: (taskId: string, event: TaskExecutionEventInput) => Promise<void> | void;
81
+ /** Persist a resumable progress snapshot (throttled by the executor). */
82
+ reportCheckpoint?: (taskId: string, checkpoint: { lastAssistantMessage: string; progressNote?: string; sessionKey: string }) => Promise<void> | void;
69
83
  };
70
84
 
71
85
  export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
72
- const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent } = deps;
86
+ const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
73
87
  const roleDef = getRole(role);
74
88
  const roleSystemPrompt = roleDef
75
89
  ? roleDef.systemPrompt
@@ -82,6 +96,7 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
82
96
  const taskMessage = buildTaskMessage(taskDescription, taskId, roleDef?.label ?? role, {
83
97
  inlineContract: true,
84
98
  projectDir: assignment.projectDir,
99
+ teamContext: assignment.teamContext,
85
100
  });
86
101
  const workspaceDir = resolveTeamClawWorkspaceDir();
87
102
  logger.info(`TeamClaw: executing task ${taskId} as ${role} via subagent`);
@@ -89,10 +104,30 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
89
104
  function buildSubagentRunOptions(
90
105
  options: Parameters<typeof runtime.subagent.run>[0],
91
106
  ): Parameters<typeof runtime.subagent.run>[0] {
92
- const enrichedOptions: Parameters<typeof runtime.subagent.run>[0] & { workspaceDir?: string } = {
107
+ // OpenClaw 2026.10+ renamed the subagent working-directory override from
108
+ // `workspaceDir` to `cwd`. Pass both so the run lands in the project
109
+ // workspace on legacy and current hosts (each host ignores the key it
110
+ // does not know).
111
+ const enrichedOptions: Parameters<typeof runtime.subagent.run>[0] & {
112
+ workspaceDir?: string;
113
+ cwd?: string;
114
+ } = {
93
115
  ...options,
94
116
  workspaceDir,
117
+ cwd: options.cwd ?? workspaceDir,
95
118
  };
119
+ // Per-role model override ("provider/model"): takes precedence over the
120
+ // teamclaw agent entry model for this role's subagent runs.
121
+ const roleModel = deps.config?.roleModelOverrides?.[role];
122
+ if (roleModel) {
123
+ const slashIndex = roleModel.indexOf("/");
124
+ if (slashIndex > 0) {
125
+ enrichedOptions.provider = roleModel.slice(0, slashIndex);
126
+ enrichedOptions.model = roleModel.slice(slashIndex + 1);
127
+ } else {
128
+ enrichedOptions.model = roleModel;
129
+ }
130
+ }
96
131
  return enrichedOptions;
97
132
  }
98
133
 
@@ -112,6 +147,8 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
112
147
  }
113
148
 
114
149
  try {
150
+ // Checkpoint heartbeat state for resume support.
151
+ let lastCheckpointAt = 0;
115
152
  const runResult = await runtime.subagent.run(buildSubagentRunOptions({
116
153
  sessionKey,
117
154
  message: taskMessage,
@@ -260,6 +297,16 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
260
297
  }
261
298
  if (entry.stream === "assistant") {
262
299
  progressSnapshot.lastAssistantMessage = entry.message;
300
+ // Checkpoint heartbeat: persist the latest assistant turn so an
301
+ // interrupted execution resumes with fresh context (max once per
302
+ // CHECKPOINT_EMIT_INTERVAL_MS to bound controller write load).
303
+ if (reportCheckpoint && Date.now() - lastCheckpointAt >= CHECKPOINT_EMIT_INTERVAL_MS) {
304
+ lastCheckpointAt = Date.now();
305
+ void Promise.resolve(reportCheckpoint(taskId, {
306
+ lastAssistantMessage: entry.message.slice(0, 8000),
307
+ sessionKey,
308
+ })).catch(() => { /* checkpointing is best-effort */ });
309
+ }
263
310
  }
264
311
  await emitExecutionEvent({
265
312
  type: "progress",
@@ -891,10 +938,11 @@ function buildTaskMessage(
891
938
  taskDescription: string,
892
939
  taskId: string,
893
940
  roleLabel: string,
894
- options?: { inlineContract?: boolean; projectDir?: string },
941
+ options?: { inlineContract?: boolean; projectDir?: string; teamContext?: TaskAssignmentPayload["teamContext"] },
895
942
  ): string {
896
943
  const rules = [
897
944
  ...buildTaskExecutionRules(RATE_LIMIT_WAITING_SENTINEL),
945
+ "Before your final reply, you MUST call teamclaw_submit_result_contract to deliver the structured result for this task. Do not end your turn without it.",
898
946
  ...buildWorkerMemoryContractRules(),
899
947
  ...buildVerificationPolicy(),
900
948
  ...buildDeliverableMetadataPolicy(),
@@ -925,6 +973,65 @@ function buildTaskMessage(
925
973
  );
926
974
  }
927
975
 
976
+ if (options?.teamContext) {
977
+ const contextLines: string[] = [];
978
+ if (options.teamContext.requirementSummary) {
979
+ contextLines.push(`Requirement summary: ${options.teamContext.requirementSummary}`);
980
+ }
981
+ if (options.teamContext.projectName) {
982
+ contextLines.push(`Project name: ${options.teamContext.projectName}`);
983
+ }
984
+ if (options.teamContext.requiredRoles && options.teamContext.requiredRoles.length > 0) {
985
+ contextLines.push(`Required TeamClaw roles: ${options.teamContext.requiredRoles.join(", ")}`);
986
+ }
987
+ const appendTaskBucket = (
988
+ label: string,
989
+ entries: Array<{ id: string; title: string; assignedRole?: string; status: string; summary?: string }> | undefined,
990
+ ) => {
991
+ if (!entries || entries.length === 0) {
992
+ return;
993
+ }
994
+ contextLines.push("", label);
995
+ for (const entry of entries) {
996
+ const roleText = entry.assignedRole ? ` (${entry.assignedRole})` : "";
997
+ const summaryText = entry.summary ? `: ${entry.summary}` : "";
998
+ contextLines.push(`- [${entry.id}] ${entry.title}${roleText} [${entry.status}]${summaryText}`);
999
+ }
1000
+ };
1001
+ appendTaskBucket("Active same-requirement tasks:", options.teamContext.activeTasks);
1002
+ appendTaskBucket("Blocked same-requirement tasks:", options.teamContext.blockedTasks);
1003
+ appendTaskBucket("Recent completed upstream tasks:", options.teamContext.recentCompletedTasks);
1004
+ if (options.teamContext.pendingClarifications && options.teamContext.pendingClarifications.length > 0) {
1005
+ contextLines.push("", "Pending clarifications:");
1006
+ for (const clarification of options.teamContext.pendingClarifications) {
1007
+ contextLines.push(`- ${clarification.question}${clarification.blockingReason ? ` — ${clarification.blockingReason}` : ""}`);
1008
+ }
1009
+ }
1010
+ if (options.teamContext.answeredClarifications && options.teamContext.answeredClarifications.length > 0) {
1011
+ contextLines.push("", "Recently answered clarifications (treat these as authoritative and do not ask the same question again unless the answer is still objectively missing or invalid):");
1012
+ for (const clarification of options.teamContext.answeredClarifications) {
1013
+ const meta = [
1014
+ clarification.answeredBy ? `answered by ${clarification.answeredBy}` : "",
1015
+ clarification.blockingReason ? `was blocked by ${clarification.blockingReason}` : "",
1016
+ ].filter(Boolean).join("; ");
1017
+ contextLines.push(`- Q: ${clarification.question}`);
1018
+ contextLines.push(` A: ${clarification.answer}${meta ? ` (${meta})` : ""}`);
1019
+ }
1020
+ }
1021
+ if (options.teamContext.kickoffSummary) {
1022
+ contextLines.push("", "Team kickoff consensus:", options.teamContext.kickoffSummary);
1023
+ }
1024
+ if (options.teamContext.handoffPlan) {
1025
+ contextLines.push("", `Current handoff plan: ${options.teamContext.handoffPlan}`);
1026
+ }
1027
+ if (options.teamContext.notes) {
1028
+ contextLines.push("", `Controller notes: ${options.teamContext.notes}`);
1029
+ }
1030
+ if (contextLines.length > 0) {
1031
+ sections.push("", "## TeamClaw Requirement Context", ...contextLines);
1032
+ }
1033
+ }
1034
+
928
1035
  sections.push("", "## Execution Rules", ...rules);
929
1036
  return sections.join("\n");
930
1037
  }
@@ -0,0 +1,254 @@
1
+ import type { GithubAuthManager } from "../controller/github-auth.js";
2
+
3
+ /**
4
+ * Minimal GitHub REST client for TeamAuto: ETag-conditional GETs, light
5
+ * pagination, and the write endpoints we need. All requests ride the stored
6
+ * device-flow token via the auth manager (transparent refresh).
7
+ */
8
+
9
+ const API = "https://api.github.com";
10
+ const VERSION = "2026-03-10";
11
+ const USER_AGENT = "teamclaw-teamauto";
12
+
13
+ export class GithubClientError extends Error {
14
+ readonly status: number;
15
+ constructor(message: string, status: number) {
16
+ super(message);
17
+ this.name = "GithubClientError";
18
+ this.status = status;
19
+ }
20
+ }
21
+
22
+ export type EtagCache = Record<string, string>;
23
+
24
+ export type SweepableIssue = {
25
+ number: number;
26
+ title: string;
27
+ body: string;
28
+ state: "open" | "closed";
29
+ assignees: string[];
30
+ labels: string[];
31
+ updatedAt: string;
32
+ user: string;
33
+ htmlUrl: string;
34
+ };
35
+
36
+ export type SweepablePull = {
37
+ number: number;
38
+ title: string;
39
+ body: string;
40
+ state: "open" | "closed";
41
+ draft: boolean;
42
+ updated_at: string;
43
+ user: string;
44
+ head: string;
45
+ htmlUrl: string;
46
+ };
47
+
48
+ export type GithubRepoInfo = {
49
+ fullName: string;
50
+ defaultBranch: string;
51
+ cloneUrl: string;
52
+ permissions: { push: boolean; pull: boolean };
53
+ };
54
+
55
+ export function createGithubClient(auth: GithubAuthManager) {
56
+ async function request(
57
+ method: string,
58
+ urlPath: string,
59
+ options: { body?: unknown; etagKey?: string; etags?: EtagCache } = {},
60
+ ): Promise<{ status: number; data: unknown; notModified: boolean }> {
61
+ const headers: Record<string, string> = {
62
+ ...(await auth.getAuthHeaders()),
63
+ "User-Agent": USER_AGENT,
64
+ "X-GitHub-Api-Version": VERSION,
65
+ };
66
+ if (options.body !== undefined) {
67
+ headers["Content-Type"] = "application/json";
68
+ }
69
+ const etagKey = options.etagKey ? `${method} ${urlPath}` : undefined;
70
+ if (etagKey && options.etags?.[etagKey]) {
71
+ headers["If-None-Match"] = options.etags[etagKey];
72
+ }
73
+ const response = await fetch(`${API}${urlPath}`, {
74
+ method,
75
+ headers,
76
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
77
+ signal: AbortSignal.timeout(20_000),
78
+ });
79
+ if (etagKey) {
80
+ const etag = response.headers.get("etag");
81
+ if (etag && options.etags) {
82
+ options.etags[etagKey] = etag;
83
+ }
84
+ }
85
+ if (response.status === 304) {
86
+ return { status: 304, data: null, notModified: true };
87
+ }
88
+ const text = await response.text();
89
+ let data: unknown = null;
90
+ if (text) {
91
+ try {
92
+ data = JSON.parse(text);
93
+ } catch {
94
+ data = { raw: text.slice(0, 500) };
95
+ }
96
+ }
97
+ if (!response.ok) {
98
+ const message = (data as { message?: string } | null)?.message ?? `HTTP ${response.status}`;
99
+ throw new GithubClientError(message, response.status);
100
+ }
101
+ return { status: response.status, data, notModified: false };
102
+ }
103
+
104
+ async function getJson<T>(urlPath: string, etags?: EtagCache): Promise<T | null> {
105
+ const { data, notModified } = await request("GET", urlPath, { etagKey: etags ? urlPath : undefined, etags });
106
+ return notModified ? null : data as T;
107
+ }
108
+
109
+ return {
110
+ request,
111
+
112
+ async getRepoInfo(owner: string, repo: string): Promise<GithubRepoInfo> {
113
+ const data = await getJson<Record<string, unknown>>(`/repos/${owner}/${repo}`);
114
+ if (!data) {
115
+ throw new GithubClientError("unexpected 304 without etag", 500);
116
+ }
117
+ const perms = (data.permissions ?? {}) as Record<string, boolean>;
118
+ return {
119
+ fullName: String(data.full_name ?? `${owner}/${repo}`),
120
+ defaultBranch: String(data.default_branch ?? "main"),
121
+ cloneUrl: String(data.clone_url ?? `https://github.com/${owner}/${repo}.git`),
122
+ permissions: { push: Boolean(perms.push), pull: Boolean(perms.pull ?? true) },
123
+ };
124
+ },
125
+
126
+ /** Issues updated since the cursor; pass 0 for a first (bounded) backfill. */
127
+ async listIssues(owner: string, repo: string, sinceMs: number, etags?: EtagCache): Promise<SweepableIssue[]> {
128
+ const since = sinceMs > 0 ? new Date(sinceMs).toISOString() : new Date(Date.now() - 7 * 24 * 3600_000).toISOString();
129
+ const data = await getJson<unknown[]>(
130
+ `/repos/${owner}/${repo}/issues?state=open&sort=updated&direction=desc&per_page=50&since=${encodeURIComponent(since)}`,
131
+ etags,
132
+ );
133
+ if (!data) {
134
+ return [];
135
+ }
136
+ return data
137
+ .filter((raw) => {
138
+ const item = raw as Record<string, unknown>;
139
+ // The issues API also returns PRs; drop them (pull_request field).
140
+ return !item.pull_request;
141
+ })
142
+ .map((raw) => {
143
+ const item = raw as Record<string, unknown>;
144
+ return {
145
+ number: Number(item.number ?? 0),
146
+ title: String(item.title ?? ""),
147
+ body: String(item.body ?? ""),
148
+ state: item.state === "closed" ? "closed" : "open",
149
+ assignees: Array.isArray(item.assignees) ? item.assignees.map((a) => String((a as { login?: string }).login ?? "")) : [],
150
+ labels: Array.isArray(item.labels) ? item.labels.map((l) => String((l as { name?: string }).name ?? "")) : [],
151
+ updatedAt: String(item.updated_at ?? ""),
152
+ user: String((item.user as { login?: string } | undefined)?.login ?? ""),
153
+ htmlUrl: String(item.html_url ?? ""),
154
+ } satisfies SweepableIssue;
155
+ });
156
+ },
157
+
158
+ async listPulls(owner: string, repo: string, etags?: EtagCache): Promise<SweepablePull[]> {
159
+ const data = await getJson<unknown[]>(
160
+ `/repos/${owner}/${repo}/pulls?state=open&sort=updated&direction=desc&per_page=30`,
161
+ etags,
162
+ );
163
+ if (!data) {
164
+ return [];
165
+ }
166
+ return data.map((raw) => {
167
+ const item = raw as Record<string, unknown>;
168
+ return {
169
+ number: Number(item.number ?? 0),
170
+ title: String(item.title ?? ""),
171
+ body: String(item.body ?? ""),
172
+ state: item.state === "closed" ? "closed" : "open",
173
+ draft: Boolean(item.draft),
174
+ updated_at: String(item.updated_at ?? ""),
175
+ user: String((item.user as { login?: string } | undefined)?.login ?? ""),
176
+ head: String((item.head as { ref?: string } | undefined)?.ref ?? ""),
177
+ htmlUrl: String(item.html_url ?? ""),
178
+ } satisfies SweepablePull;
179
+ });
180
+ },
181
+
182
+ async listCommits(owner: string, repo: string, sinceSha: string): Promise<{ sha: string; message: string }[]> {
183
+ const suffix = sinceSha ? `?sha=${encodeURIComponent(sinceSha)}` : "?per_page=20";
184
+ void suffix;
185
+ // Compare-style walk is heavy; use the commits feed and filter client-side.
186
+ const data = await getJson<unknown[]>(`/repos/${owner}/${repo}/commits?per_page=30`);
187
+ if (!data) {
188
+ return [];
189
+ }
190
+ const commits = data.map((raw) => {
191
+ const item = raw as Record<string, unknown>;
192
+ return {
193
+ sha: String(item.sha ?? ""),
194
+ message: String((item.commit as { message?: string } | undefined)?.message ?? "").split("\n")[0],
195
+ };
196
+ });
197
+ if (!sinceSha) {
198
+ return commits.slice(0, 10);
199
+ }
200
+ const index = commits.findIndex((c) => c.sha.startsWith(sinceSha.slice(0, 10)));
201
+ return index === -1 ? commits.slice(0, 5) : commits.slice(0, index);
202
+ },
203
+
204
+ // ---- write side (require Contents/Issues/PR write on the App) ----
205
+
206
+ async postIssueComment(owner: string, repo: string, issueNumber: number, body: string): Promise<number> {
207
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body: { body } });
208
+ return Number((data as { id?: number }).id ?? 0);
209
+ },
210
+
211
+ async postPullReviewComment(owner: string, repo: string, pullNumber: number, body: string): Promise<void> {
212
+ await request("POST", `/repos/${owner}/${repo}/pulls/${pullNumber}/reviews`, { body: { event: "COMMENT", body } });
213
+ },
214
+
215
+ async createIssue(owner: string, repo: string, title: string, body: string, labels?: string[]): Promise<number> {
216
+ const { data } = await request("POST", `/repos/${owner}/${repo}/issues`, {
217
+ body: { title, body, ...(labels?.length ? { labels } : {}) },
218
+ });
219
+ return Number((data as { number?: number }).number ?? 0);
220
+ },
221
+
222
+ async assignIssue(owner: string, repo: string, issueNumber: number, assignee: string): Promise<void> {
223
+ await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
224
+ },
225
+
226
+ /** Open a PR from a task worktree branch (collaboration contract delivery). */
227
+ async createPullRequest(owner: string, repo: string, head: string, base: string, title: string, body: string): Promise<{ number: number; url: string }> {
228
+ const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
229
+ body: { title, head, base, body },
230
+ });
231
+ const item = data as { number?: number; html_url?: string };
232
+ return { number: Number(item.number ?? 0), url: String(item.html_url ?? "") };
233
+ },
234
+
235
+ /** Repos the logged-in user can select in the TeamAuto bind picker. */
236
+ async listUserRepos(): Promise<{ id: string; fullName: string; private: boolean; pushedAt: string | null }[]> {
237
+ const data = await getJson<unknown[]>("/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100");
238
+ if (!data) {
239
+ return [];
240
+ }
241
+ return data.map((raw) => {
242
+ const item = raw as Record<string, unknown>;
243
+ return {
244
+ id: String(item.full_name ?? ""),
245
+ fullName: String(item.full_name ?? ""),
246
+ private: Boolean(item.private),
247
+ pushedAt: typeof item.pushed_at === "string" ? item.pushed_at : null,
248
+ };
249
+ }).filter((r) => r.id);
250
+ },
251
+ };
252
+ }
253
+
254
+ export type TeamAutoGithubClient = ReturnType<typeof createGithubClient>;