@teamclaws/teamclaw 2026.11.1 → 2026.11.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.
package/cli.mjs CHANGED
@@ -20,6 +20,7 @@ const PACKAGE_INSTALL_SPEC = `${PACKAGE_NAME}@${PACKAGE_VERSION}`;
20
20
  const PLUGIN_ID = "teamclaw";
21
21
  const DANGEROUS_INSTALL_FLAG = "--dangerously-force-unsafe-install";
22
22
  const CAPABILITY_CONSENT_FLAG = "--accept-capabilities";
23
+ const FORCE_INSTALL_FLAG = "--force";
23
24
 
24
25
  /**
25
26
  * OpenClaw 2026.10+ replaced the legacy break-glass install flag (now a
@@ -32,6 +33,19 @@ const CAPABILITY_CONSENT_FLAG = "--accept-capabilities";
32
33
  function isCapabilityConsentRequired(output) {
33
34
  return /accept-capabilities|capability[\s-]?consent|CapabilityConsentRequired/i.test(String(output || ""));
34
35
  }
36
+
37
+ /**
38
+ * openclaw 2026.10+ retired the legacy break-glass install flag (now a
39
+ * deprecated no-op) and cancels any install from a source outside ClawHub
40
+ * review/trust metadata — local package directories and npm-registry packages
41
+ * alike — asking the operator to rerun with --force after reviewing the
42
+ * source. This source gate cancels before the capability-consent check, so
43
+ * the capability error never surfaces on its own and both consents must be
44
+ * appended on the retry (issue #261).
45
+ */
46
+ function isSourceTrustGateCancel(output) {
47
+ return /rerun with --force|outside ClawHub review/i.test(String(output || ""));
48
+ }
35
49
  const DEFAULT_TEAMCLAW_IMAGE = "ghcr.io/topcheer/teamclaw-openclaw:latest";
36
50
  const DEFAULT_CONTROLLER_PORT = 9527;
37
51
  const DEFAULT_WORKER_PORT = 9528;
@@ -44,6 +58,16 @@ const TEAMCLAW_AGENT_ID = "teamclaw";
44
58
  const TEAMCLAW_RECOMMENDED_EXEC_SECURITY = "full";
45
59
  const TEAMCLAW_RECOMMENDED_EXEC_ASK = "off";
46
60
  const TEAMCLAW_RECOMMENDED_COMMAND_MODE = "auto";
61
+ /**
62
+ * The installer historically wrote commands.ownerDisplay="raw" as a host
63
+ * default. openclaw 2026.11 renders owner ids raw when the key is absent and
64
+ * its doctor now removes the key outright, while openclaw 2026.10.x config
65
+ * validation rejects the key as unrecognized — poisoning every later host CLI
66
+ * invocation after an install (issue #261). This value is what the installer
67
+ * used to write and what it now prunes; explicit non-default user choices are
68
+ * preserved.
69
+ */
70
+ const TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT = "raw";
47
71
  const AGENT_MODE_OPTIONS = [
48
72
  {
49
73
  value: "independent",
@@ -67,8 +91,27 @@ let ROLE_OPTIONS = [];
67
91
  let DEFAULT_WORKER_ROLE = "";
68
92
 
69
93
  async function loadRoleOptions() {
94
+ // #253 layout-adaptive loading via VARIABLE specifiers: bundlers and the
95
+ // image's dist-import checker treat a LITERAL dynamic import whose target
96
+ // does not exist in the current layout (./dist/src/roles.js is a phantom
97
+ // under the image's flat bundle; ./index.js does not exist in the npm
98
+ // tarball) as an unresolved edge and fail the build. A runtime variable
99
+ // defeats static resolution on purpose: whichever layout this file ships
100
+ // in resolves exactly one of the candidates.
101
+ const ROLE_MODULE_CANDIDATES = ["./dist/src/roles.js", "./index.js"];
102
+ let rolesModule = null;
103
+ for (const candidate of ROLE_MODULE_CANDIDATES) {
104
+ try {
105
+ rolesModule = await import(candidate);
106
+ break;
107
+ } catch {
108
+ // try the next layout
109
+ }
110
+ }
70
111
  try {
71
- const rolesModule = await import("./dist/src/roles.js");
112
+ if (!rolesModule) {
113
+ throw new Error("no role registry module found in any known layout");
114
+ }
72
115
  const roles = Array.isArray(rolesModule.ROLES) ? rolesModule.ROLES : [];
73
116
  ROLE_OPTIONS = roles
74
117
  .filter((role) => role && typeof role.id === "string" && role.id.trim())
@@ -81,9 +124,9 @@ async function loadRoleOptions() {
81
124
  ? registryDefault
82
125
  : "";
83
126
  } catch {
84
- // dist not built yet (dev checkout). Keep the registry empty so callers
85
- // fail with the actionable guidance in ensureRoleOptionsLoaded instead
86
- // of presenting a stale role list.
127
+ // Neither layout resolvable (pre-build dev checkout). Keep the registry
128
+ // empty so callers fail with the actionable guidance in
129
+ // ensureRoleOptionsLoaded instead of presenting a stale role list.
87
130
  ROLE_OPTIONS = [];
88
131
  DEFAULT_WORKER_ROLE = "";
89
132
  }
@@ -92,7 +135,7 @@ async function loadRoleOptions() {
92
135
  function ensureRoleOptionsLoaded() {
93
136
  if (ROLE_OPTIONS.length === 0) {
94
137
  throw new Error(
95
- "TeamClaw role registry unavailable (./dist/src/roles.js). Run `npm --prefix src run build` in the repository, or reinstall the @teamclaws/teamclaw package, then retry.",
138
+ "TeamClaw role registry unavailable (tried ./dist/src/roles.js and ./index.js). Run `npm --prefix src run build` in the repository, or reinstall the @teamclaws/teamclaw package, then retry.",
96
139
  );
97
140
  }
98
141
  }
@@ -655,6 +698,36 @@ async function writeConfig(configPath, config) {
655
698
  await fs.writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
656
699
  }
657
700
 
701
+ /**
702
+ * openclaw 2026.10.x config validation rejects the retired commands.ownerDisplay
703
+ * key ("Unrecognized key"), so a config still carrying the value written by an
704
+ * earlier installer deadlocks every host CLI invocation — including the plugin
705
+ * install this run is about to attempt (issue #261). Prune the
706
+ * installer-written "raw" default before any host command runs: the value is
707
+ * openclaw 2026.11's built-in default, and explicit non-default user choices
708
+ * are left untouched.
709
+ */
710
+ async function pruneInstallerWrittenOwnerDisplay(configPath) {
711
+ let config;
712
+ try {
713
+ config = await readOpenClawConfig(configPath);
714
+ } catch {
715
+ // Unparseable config: leave it alone; the host CLI and the existing
716
+ // config-parse error path will surface the problem.
717
+ return false;
718
+ }
719
+ const commands = isRecord(config.commands) ? config.commands : null;
720
+ if (!commands || commands.ownerDisplay !== TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT) {
721
+ return false;
722
+ }
723
+ delete commands.ownerDisplay;
724
+ await writeConfig(configPath, config);
725
+ console.log(
726
+ `Removed commands.ownerDisplay from ${configPath}: the key is retired, openclaw 2026.10.x rejects it as unrecognized (which blocks every OpenClaw command), and openclaw renders owner ids raw by default.`,
727
+ );
728
+ return true;
729
+ }
730
+
658
731
  function getExistingTeamClawConfig(config) {
659
732
  if (!isRecord(config)) {
660
733
  return {};
@@ -1334,7 +1407,7 @@ function attemptPluginInstall({ configPath }) {
1334
1407
  }
1335
1408
  }
1336
1409
  console.log(
1337
- `\nTeamClaw uses host-level orchestration capabilities, so OpenClaw requires an install consent flag during plugin installation (legacy: ${DANGEROUS_INSTALL_FLAG}; OpenClaw 2026.10+: ${CAPABILITY_CONSENT_FLAG}).`,
1410
+ `\nTeamClaw uses host-level orchestration capabilities, so OpenClaw requires install consent flags during plugin installation (legacy: ${DANGEROUS_INSTALL_FLAG}; OpenClaw 2026.10+: ${FORCE_INSTALL_FLAG} ${CAPABILITY_CONSENT_FLAG}).`,
1338
1411
  );
1339
1412
  const candidates = [
1340
1413
  {
@@ -1389,12 +1462,14 @@ function attemptPluginInstall({ configPath }) {
1389
1462
  if (
1390
1463
  result.status !== 0 &&
1391
1464
  !candidate.args.includes(CAPABILITY_CONSENT_FLAG) &&
1392
- isCapabilityConsentRequired(result.output)
1465
+ (isCapabilityConsentRequired(result.output) || isSourceTrustGateCancel(result.output))
1393
1466
  ) {
1394
- console.log("OpenClaw requires capability consent; retrying with --accept-capabilities...");
1467
+ console.log(
1468
+ `OpenClaw requires install consent; retrying with ${FORCE_INSTALL_FLAG} and ${CAPABILITY_CONSENT_FLAG}...`,
1469
+ );
1395
1470
  result = installPluginWithCommand(
1396
1471
  candidate.command,
1397
- [...candidate.args, CAPABILITY_CONSENT_FLAG],
1472
+ [...candidate.args, FORCE_INSTALL_FLAG, CAPABILITY_CONSENT_FLAG],
1398
1473
  env,
1399
1474
  );
1400
1475
  }
@@ -1879,8 +1954,12 @@ function applyTeamClawHostRuntimeDefaults(next) {
1879
1954
  if (typeof commands.restart !== "boolean") {
1880
1955
  commands.restart = true;
1881
1956
  }
1882
- if (typeof commands.ownerDisplay !== "string" || !commands.ownerDisplay.trim()) {
1883
- commands.ownerDisplay = "raw";
1957
+ if (commands.ownerDisplay === TEAMCLAW_RETIRED_OWNER_DISPLAY_DEFAULT) {
1958
+ // openclaw 2026.10.x rejects this retired key ("Unrecognized key"), which
1959
+ // deadlocks every later host CLI invocation; openclaw 2026.11 renders
1960
+ // owner ids raw by default anyway. Prune the installer-written default
1961
+ // and keep explicit non-default user choices (issue #261).
1962
+ delete commands.ownerDisplay;
1884
1963
  }
1885
1964
 
1886
1965
  const tools = ensureRecord(next, "tools");
@@ -2254,6 +2333,12 @@ async function runInstall(options) {
2254
2333
  : `Created ${configPath}`);
2255
2334
  }
2256
2335
 
2336
+ if (!options.dryRun) {
2337
+ // Heal configs poisoned by earlier installers before any host OpenClaw
2338
+ // command runs (issue #261).
2339
+ await pruneInstallerWrittenOwnerDisplay(configPath);
2340
+ }
2341
+
2257
2342
  let pluginInstallStatus = "skipped";
2258
2343
  let pluginInstallMethod = "";
2259
2344
  let pluginInstallError = "";
package/dist/index.js CHANGED
@@ -18,6 +18,13 @@ import { installRecommendedSkills } from "./src/worker/skill-installer.js";
18
18
  // W6 of issue #226: local swallowing pathExists copy replaced by the shared
19
19
  // one (identical semantics; alias keeps the call site byte-identical).
20
20
  import { pathExistsTolerant as pathExists } from "./src/shared/utils.js";
21
+ // #253: the image build compiles this plugin into a flat rolldown bundle
22
+ // (dist/extensions/teamclaw/index.js) with NO nested dist/src tree, while the
23
+ // npm tarball layout ships dist/src/roles.js and no top-level index.js. The
24
+ // installer CLI (cli.mjs) reads the role registry through whichever layout it
25
+ // lands in, so the registry must be reachable from this entry as a named
26
+ // export for the bundled layout to resolve it.
27
+ export { ROLES, DEFAULT_ROLE } from "./src/roles.js";
21
28
  export default definePluginEntry({
22
29
  id: "teamclaw",
23
30
  name: "TeamClaw",
@@ -0,0 +1,138 @@
1
+ // Hot-reloadable worker-provisioning configuration routes (runtime scaling).
2
+ //
3
+ // GET /api/v1/team/config -> read-only snapshot of the hot-reloadable fields
4
+ // PATCH /api/v1/team/config -> whitelist-only update that
5
+ // 1. mutates deps.config IN MEMORY (the provisioner reads these fields on
6
+ // every computeRoleDemand pass, so the change applies on the next
7
+ // reconcile tick — no restart),
8
+ // 2. persists to the host openclaw.json plugins.entries.teamclaw.config
9
+ // (same read-modify-write pattern as updateTeamClawModelConfig), and
10
+ // 3. pokes the provisioner via requestReconcile + broadcasts a
11
+ // team:config_updated WS event so desktop/web UIs refresh.
12
+ //
13
+ // Deployment-shape behavior (issue context: all deployment forms):
14
+ // - process / managed-gateway / desktop-private / tunnel: memory + host-config
15
+ // persistence (resolveDefaultOpenClawConfigPath honors OPENCLAW_HOME /
16
+ // OPENCLAW_CONFIG_PATH, so sandboxed instances persist into their own home).
17
+ // - docker (controller on host): same as process — host config is writable.
18
+ // - docker/k8s (controller itself containerized): container FS is ephemeral,
19
+ // so persistence degrades to memory-only and the response carries
20
+ // persistenceMode: "memory-only" + a restart note (declared behavior, not
21
+ // a silent drop). k8s deployments should source config from ConfigMap and
22
+ // treat this API as runtime-only scaling.
23
+ // Scale-down semantics: lowering maxPerRole never kills active workers; idle
24
+ // workers drain via workerProvisioningIdleTtlMs and the cap stops refills.
25
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
26
+ import { updateTeamClawProvisioningConfig } from "../openclaw-workspace.js";
27
+ /** Fields a PATCH may touch. Everything else in PluginConfig is rejected. */
28
+ const HOT_CONFIG_FIELDS = [
29
+ "workerProvisioningMaxPerRole",
30
+ "workerProvisioningMinPerRole",
31
+ "workerProvisioningIdleTtlMs",
32
+ ];
33
+ const BOUNDS = {
34
+ workerProvisioningMaxPerRole: { min: 1, max: 50 },
35
+ workerProvisioningMinPerRole: { min: 0, max: 50 },
36
+ // 1s floor keeps the idle reaper from churn-looping; 24h ceiling is generous.
37
+ workerProvisioningIdleTtlMs: { min: 1_000, max: 86_400_000 },
38
+ };
39
+ function teamConfigGetRoute(ctx) {
40
+ const { res, deps } = ctx;
41
+ const c = deps.config;
42
+ sendJson(res, 200, {
43
+ workerProvisioningType: c.workerProvisioningType,
44
+ workerProvisioningDisabled: c.workerProvisioningDisabled,
45
+ workerProvisioningMinPerRole: c.workerProvisioningMinPerRole,
46
+ workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
47
+ workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
48
+ // k8s controllers run on ephemeral container FS: declare it up front.
49
+ persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
50
+ });
51
+ }
52
+ async function teamConfigPatchRoute(ctx) {
53
+ const { req, res, deps } = ctx;
54
+ let body = null;
55
+ try {
56
+ body = (await parseJsonBody(req));
57
+ }
58
+ catch {
59
+ sendError(res, 400, "invalid JSON body");
60
+ return;
61
+ }
62
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
63
+ sendError(res, 400, "JSON object body required");
64
+ return;
65
+ }
66
+ const unknown = Object.keys(body).filter((k) => !HOT_CONFIG_FIELDS.includes(k));
67
+ if (unknown.length > 0) {
68
+ sendError(res, 400, `unknown or non-hot-reloadable field(s): ${unknown.join(", ")}`);
69
+ return;
70
+ }
71
+ const update = {};
72
+ for (const field of HOT_CONFIG_FIELDS) {
73
+ if (body[field] === undefined)
74
+ continue;
75
+ const raw = body[field];
76
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
77
+ sendError(res, 400, `${field} must be a finite number`);
78
+ return;
79
+ }
80
+ const { min, max } = BOUNDS[field];
81
+ update[field] = Math.max(min, Math.min(max, Math.floor(raw)));
82
+ }
83
+ if (Object.keys(update).length === 0) {
84
+ sendError(res, 400, `at least one of ${HOT_CONFIG_FIELDS.join(", ")} is required`);
85
+ return;
86
+ }
87
+ // 1) In-memory hot apply (deps.config is a live reference the provisioner
88
+ // reads on every demand computation — no restart needed).
89
+ const applied = {};
90
+ for (const [field, value] of Object.entries(update)) {
91
+ deps.config[field] = value;
92
+ applied[field] = value;
93
+ }
94
+ // Keep the min<=max invariant types.ts enforces at parse time.
95
+ const minR = update.workerProvisioningMinPerRole ?? deps.config.workerProvisioningMinPerRole;
96
+ if (deps.config.workerProvisioningMaxPerRole < minR) {
97
+ deps.config.workerProvisioningMaxPerRole = minR;
98
+ applied.workerProvisioningMaxPerRole = minR;
99
+ }
100
+ // 2) Persist (host config) unless the controller itself runs on an
101
+ // ephemeral container FS.
102
+ const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
103
+ let persisted = false;
104
+ if (!memoryOnly) {
105
+ try {
106
+ await updateTeamClawProvisioningConfig(applied, {
107
+ warn: (message) => deps.logger.info(message),
108
+ });
109
+ persisted = true;
110
+ }
111
+ catch (err) {
112
+ // Memory already applied — report partial success honestly.
113
+ deps.logger.warn(`TeamClaw: hot config applied in memory but host-config persist failed: ${err instanceof Error ? err.message : String(err)}`);
114
+ }
115
+ }
116
+ // 3) Poke the provisioner so the new caps apply immediately instead of
117
+ // waiting for the next periodic reconcile tick, then tell UIs.
118
+ try {
119
+ await deps.workerProvisioningManager?.requestReconcile("team-config-hot-update");
120
+ }
121
+ catch (err) {
122
+ deps.logger.warn(`TeamClaw: config hot-update reconcile poke failed: ${err instanceof Error ? err.message : String(err)}`);
123
+ }
124
+ deps.wsServer.broadcastUpdate({ type: "team:config_updated", data: { ...applied, persisted } });
125
+ deps.logger.info(`TeamClaw: worker provisioning config hot-updated: ${JSON.stringify(applied)} (persisted=${persisted})`);
126
+ sendJson(res, 200, {
127
+ ok: true,
128
+ applied,
129
+ persisted,
130
+ persistenceMode: persisted ? "host-config" : "memory-only",
131
+ ...(persisted
132
+ ? {}
133
+ : {
134
+ restartNote: "Applied in memory only; this deployment shape does not persist to a durable host config — after a gateway restart the config reverts to its persisted source.",
135
+ }),
136
+ });
137
+ }
138
+ export { teamConfigGetRoute, teamConfigPatchRoute };
@@ -3,6 +3,7 @@ import { githubAuthStatusRoute, githubAuthLoginRoute, githubAuthCallbackRoute, g
3
3
  import { workspaceStatusRoute, workspaceChangeDirRoute, modelsConfigGetRoute, modelsConfigPutRoute, workspaceTreeRoute, workspaceSubtreeRoute, workspaceFileRoute, workspaceProjectPathRoute, workspaceRawFileRoute, } from "./workspace-routes.js";
4
4
  import { controllerManifestRoute, controllerRunsListRoute, projectDeleteRoute, controllerRunDeleteRoute, controllerIntakeRoute, } from "./controller-routes.js";
5
5
  import { teamStatsRoute, teamStatusRoute, teamRolesRoute, teamProfilesListRoute, teamProfileGetRoute, teamProfileSwitchRoute, archivedTeamsRoute, } from "./status-routes.js";
6
+ import { teamConfigGetRoute, teamConfigPatchRoute } from "./config-routes.js";
6
7
  import { reportsListRoute, reportsSessionRoute, healthRoute, } from "./report-routes.js";
7
8
  import { handleTeamAutoActivityRequest, handleTeamAutoReposListRequest, handleTeamAutoRepoCandidatesRequest, handleTeamAutoRepoBindRequest, handleTeamAutoRepoItemRequest, } from "./teamauto-routes.js";
8
9
  import { handleRepoStatusRequest, handleRepoBundleRequest, repoImportRoute, } from "./repo-routes.js";
@@ -372,4 +373,9 @@ export const controllerRouteTable = [
372
373
  // { context } (initial business context). The handler enforces the
373
374
  // transition-matrix 503 itself (see workflow-routes.ts).
374
375
  { method: "POST", path: /^\/api\/v1\/workflows\/[^/]+\/start$/, handler: workflowStartRoute },
376
+ // Hot worker-provisioning config (#hot-config): GET snapshot + PATCH
377
+ // hot-apply. Appended at the table tail on the same append-only precedent
378
+ // (no path overlap with any earlier route).
379
+ { method: "GET", path: "/api/v1/team/config", handler: teamConfigGetRoute },
380
+ { method: "PATCH", path: "/api/v1/team/config", handler: teamConfigPatchRoute },
375
381
  ];
@@ -655,6 +655,42 @@ export async function updateTeamClawModelConfig(update, logger, env = process.en
655
655
  logger?.warn?.("TeamClaw: model config updated (hot-reload applies; restart the gateway if a change does not take effect)");
656
656
  return { configPath };
657
657
  }
658
+ /**
659
+ * Persist hot-reloadable worker-provisioning fields into the host
660
+ * openclaw.json plugins.entries.teamclaw.config (read-modify-write, same
661
+ * pattern as updateTeamClawModelConfig). Only whitelisted fields are
662
+ * touched; unknown keys in the existing plugin config are preserved.
663
+ */
664
+ export async function updateTeamClawProvisioningConfig(update, logger, env = process.env, homedir = os.homedir) {
665
+ const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
666
+ let parsed;
667
+ try {
668
+ parsed = JSON5.parse(await fs.readFile(configPath, "utf8"));
669
+ if (!isRecord(parsed)) {
670
+ throw new Error("host config is not an object");
671
+ }
672
+ }
673
+ catch (err) {
674
+ throw new Error(`failed to read host config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
675
+ }
676
+ const plugins = isRecord(parsed.plugins) ? parsed.plugins : {};
677
+ const pluginEntries = isRecord(plugins.entries) ? plugins.entries : {};
678
+ const teamclawPlugin = isRecord(pluginEntries[TEAMCLAW_AGENT_ID]) ? pluginEntries[TEAMCLAW_AGENT_ID] : { enabled: true };
679
+ const pluginConfig = isRecord(teamclawPlugin.config)
680
+ ? { ...teamclawPlugin.config }
681
+ : {};
682
+ for (const [key, value] of Object.entries(update)) {
683
+ if (typeof value === "number" && Number.isFinite(value)) {
684
+ pluginConfig[key] = value;
685
+ }
686
+ }
687
+ pluginEntries[TEAMCLAW_AGENT_ID] = { ...teamclawPlugin, config: pluginConfig };
688
+ plugins.entries = pluginEntries;
689
+ parsed.plugins = plugins;
690
+ await fs.writeFile(configPath, `${JSON.stringify(parsed, null, 2)}\n`, "utf8");
691
+ logger?.warn?.("TeamClaw: worker provisioning config persisted (hot-reload applies to the running controller)");
692
+ return { configPath };
693
+ }
658
694
  /**
659
695
  * Resolve the `projects/` root inside the TeamClaw workspace.
660
696
  * Each orchestration run or ad-hoc task gets its own subdirectory here.
@@ -65,6 +65,19 @@ export async function sweepRepo(repo, client, now = Date.now()) {
65
65
  const pulls = repo.policy.actions.prReview
66
66
  ? await client.listPulls(owner, name, repo.cursors.etags)
67
67
  : [];
68
+ // #265: the commits leg was dead code (listCommits had zero callers,
69
+ // lastCommitSha never advanced) - the designed third signal source never
70
+ // ran. Wire it as an observation-only feed: fetch, filter past the cursor,
71
+ // and surface the delta. Cursor advance happens in advanceCursors (with
72
+ // the other legs, so dry-run semantics stay intact); it produces no task
73
+ // candidates (issue/pull policies stay the sole candidate sources).
74
+ const commits = await client.listCommits(owner, name, repo.cursors.lastCommitSha);
75
+ // Newest-first feed: when the cursor is set, stop the delta at the first
76
+ // entry whose sha equals it (that commit and everything after is already
77
+ // known). An unset cursor means first sweep: observe only, report nothing.
78
+ const newCommits = repo.cursors.lastCommitSha
79
+ ? commits.slice(0, (() => { const i = commits.findIndex((c) => c.sha === repo.cursors.lastCommitSha); return i === -1 ? commits.length : i; })())
80
+ : [];
68
81
  const candidates = [];
69
82
  for (const issue of issues) {
70
83
  // Dedup: seen map survives sweeps; a closed-then-reopened issue updates.
@@ -173,16 +186,22 @@ export async function sweepRepo(repo, client, now = Date.now()) {
173
186
  }
174
187
  }
175
188
  }
176
- return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
189
+ return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls, newCommits, commits };
177
190
  }
178
191
  /** Advance cursors after tasks were enqueued (or observed on first sweep). */
179
- export function advanceCursors(repo, issues, pulls, now = Date.now()) {
192
+ export function advanceCursors(repo, issues, pulls, now = Date.now(), commits = []) {
180
193
  for (const issue of issues) {
181
194
  repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
182
195
  }
183
196
  for (const pull of pulls) {
184
197
  repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
185
198
  }
199
+ // Commit cursor: the feed is newest-first, so when anything came back the
200
+ // HEAD entry IS the new cursor. Empty feed keeps the old cursor (nothing
201
+ // new to advance to).
202
+ if (commits.length > 0) {
203
+ repo.cursors.lastCommitSha = commits[0].sha;
204
+ }
186
205
  // Cap the seen map so it cannot grow unbounded.
187
206
  const entries = Object.entries(repo.cursors.seen);
188
207
  if (entries.length > 2000) {
@@ -337,7 +337,7 @@ export function createTeamAutoScheduler(deps) {
337
337
  }
338
338
  sweeping.add(repo.id);
339
339
  try {
340
- const { candidates, issues, pulls } = await sweepRepo(repo, client);
340
+ const { candidates, issues, pulls, newCommits, commits } = await sweepRepo(repo, client);
341
341
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
342
342
  if (dryRun) {
343
343
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -350,7 +350,7 @@ export function createTeamAutoScheduler(deps) {
350
350
  // Advance only for acting sweeps: a dry-run must leave the cursors
351
351
  // untouched so the reported actions are actually performed next time
352
352
  // instead of being marked as already-seen.
353
- advanceCursors(repo, issues, pulls);
353
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
354
354
  }
355
355
  // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
356
356
  // pull candidates, so a busy repo would otherwise starve them forever
@@ -361,6 +361,11 @@ export function createTeamAutoScheduler(deps) {
361
361
  const capped = [...fullReviews, ...regular];
362
362
  let created = 0;
363
363
  const summary = [`found ${candidates.length} candidate(s)`];
364
+ // #265: surface the commits delta so the third signal source is
365
+ // observable in sweep summaries (was silently dead before).
366
+ if (newCommits.length > 0) {
367
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
368
+ }
364
369
  if (capped.length && dryRun) {
365
370
  summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
366
371
  repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
@@ -401,6 +406,7 @@ export function createTeamAutoScheduler(deps) {
401
406
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
402
407
  }
403
408
  repo.sweepFailures = 0;
409
+ repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
404
410
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
405
411
  await saveTeamAutoStore(s);
406
412
  if (created > 0) {
@@ -419,6 +425,7 @@ export function createTeamAutoScheduler(deps) {
419
425
  // backoff below, and a success clears the state in the block above.
420
426
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
421
427
  repo.lastSweepErrorAt = Date.now();
428
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
422
429
  repo.pausedReason = `sweep failed: ${message}`;
423
430
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
424
431
  await saveTeamAutoStore(s).catch(() => { });