even-keel 0.2.2 → 0.2.4

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/CHANGELOG.md CHANGED
@@ -4,6 +4,20 @@ All notable changes to Even Keel are documented in this file.
4
4
 
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.2.4] - 2026-11-11
8
+
9
+ ### Fixed
10
+
11
+ - A project without a counted CI no longer takes main for green when the session merged without running its check. Main counts as green only when the check hook reports it passed on the merged tree (`checkpoint` plugin 0.14.1). A merge without that report, made by a session without the `checkpoint` package for one, is checked in the next task's folder before that task starts.
12
+
13
+ ## [0.2.3] - 2026-11-07
14
+
15
+ ### Fixed
16
+
17
+ - The GitLab plugin's `gitlab:task` skill loads again: its description is quoted, so the skill's frontmatter parses and chain sessions on GitLab projects get the skill (plugin 0.1.3).
18
+ - Right after a service restart a Claude chain no longer pauses on `agents --json --all timed out`. The session listing the chain waits on goes ahead of the account's other short calls and is tried again for up to five minutes.
19
+ - A cleanup after Done whose session stop timed out the same way tries the stop again and then removes the task's worktree folder, instead of warning that the session and the folder were left behind.
20
+
7
21
  ## [0.2.2] - 2026-11-06
8
22
 
9
23
  ### Added
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The reports of the checks before the merge, by project and task, as the `checkpoint` hook sends them. Only a report
3
+ * proves the check ran; in memory, so after a restart a push of main without one is checked in the next task's place.
4
+ */
5
+ export class CheckReports {
6
+ reports = new Map();
7
+ report(project, task, report) {
8
+ this.reports.set(`${project}\n${task}`, report);
9
+ }
10
+ of(project, task) {
11
+ return this.reports.get(`${project}\n${task}`);
12
+ }
13
+ }
14
+ /** The report in a request's body; `null` — not one. */
15
+ export function checkReportOf(body) {
16
+ if (typeof body !== 'object' || body === null)
17
+ return null;
18
+ const { tree, commands } = body;
19
+ if (typeof tree !== 'string' || !/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(tree))
20
+ return null;
21
+ if (!Array.isArray(commands) || !commands.every((command) => typeof command === 'string'))
22
+ return null;
23
+ return { tree, commands };
24
+ }
@@ -57,7 +57,7 @@ export class Cleanups {
57
57
  }
58
58
  /** Cleans up after a done task and, once main is pushed, awaits the CI's verdict on it. */
59
59
  async closeUp(project, task) {
60
- const tree = (await this.main?.taskTree(project, task)) ?? null;
60
+ const tree = this.main?.reportedTree(project, task) ?? null;
61
61
  const outcome = await this.cleanUp(project, task, this.reviews.cleanupOf(project, task));
62
62
  this.reviews.closedUp(project, task);
63
63
  this.syncRetries.delete(project);
@@ -366,6 +366,12 @@ export class Dispatcher {
366
366
  this.deps.save(this.state);
367
367
  return true;
368
368
  }
369
+ /** A warning about a finished task's cleanup that came after the cleanup itself: a stop tried again in vain (EKR-99). */
370
+ leftover(project, task, warning) {
371
+ const leftovers = (this.state.leftovers[project] ??= []);
372
+ leftovers.push({ task, at: this.deps.now().toISOString(), notice: warning });
373
+ this.deps.save(this.state);
374
+ }
369
375
  dismiss(project, task) {
370
376
  const leftovers = this.state.leftovers[project];
371
377
  if (leftovers === undefined || !leftovers.some((each) => each.task === task))
@@ -46,16 +46,16 @@ export class MainCheck {
46
46
  const run = this.afterRuns.get(project);
47
47
  return run === undefined ? undefined : { commit: run.commit, since: run.since };
48
48
  }
49
- /** The tree of the task's branch, read before its cleanup deletes the branch; `null` — unknown. */
50
- async taskTree(project, task) {
49
+ /** The tree the check before the task's merge reported, read before its cleanup; `null` — no report. */
50
+ reportedTree(project, task) {
51
51
  try {
52
- return await this.deps.taskTree(project, task);
52
+ return this.deps.reportedTree(project, task);
53
53
  }
54
54
  catch {
55
55
  return null;
56
56
  }
57
57
  }
58
- /** After the cleanup of a done task synced main: the CI's verdict on the commit is awaited. */
58
+ /** After the cleanup of a done task synced main: the CI's verdict on the commit is awaited; `tree` — `reportedTree`. */
59
59
  async pushed(project, task, tree) {
60
60
  let commit;
61
61
  try {
@@ -81,7 +81,13 @@ export class MainCheck {
81
81
  const checked = tree !== null && (await this.deps.tree(project, commit).catch(() => null)) === tree;
82
82
  const earlier = [...(gate.local?.tasks ?? []), ...(gate.check?.tasks ?? [])];
83
83
  delete gate.local;
84
- const push = { commit, at: this.now().toISOString(), tasks: [...earlier, task], ...(checked ? { checked: true } : {}) };
84
+ const push = {
85
+ commit,
86
+ at: this.now().toISOString(),
87
+ tasks: [...earlier, task],
88
+ ...(checked ? { checked: true } : {}),
89
+ ...(tree === null && this.deps.checking(project).commands.length > 0 ? { unreported: true } : {}),
90
+ };
85
91
  if (this.deps.verdict(project, commit, push.at).state === 'none') {
86
92
  delete gate.check;
87
93
  this.withoutCi(project, gate, push, []);
@@ -338,12 +344,14 @@ export class MainCheck {
338
344
  if (reasons.length > 0)
339
345
  this.log(`ci: ${project}: the CI cannot judge ${commit} (${why}); the project's check takes it`);
340
346
  if (push.checked === true)
341
- this.passed(project, gate, push, 'is the tree the check passed before the merge');
342
- else if (!recheck)
347
+ this.passed(project, gate, push, 'is the tree the check before the merge reported');
348
+ // Without a report nothing shows the check ran, whatever the trees: the check of main is not the user's to skip then.
349
+ else if (!recheck && push.unreported !== true)
343
350
  this.unchecked(project, gate, push, 'main moved past the checked branch, and the check of main is off');
344
351
  else {
345
352
  gate.local = push;
346
- this.log(`ci: ${project}: ${commit} is checked in the next task's place before it starts`);
353
+ const why = push.unreported === true ? ': the check before the merge did not report' : '';
354
+ this.log(`ci: ${project}: ${commit} is checked in the next task's place before it starts${why}`);
347
355
  }
348
356
  }
349
357
  passed(project, gate, push, how) {
@@ -76,11 +76,12 @@ export function mainCheckDeps(deps) {
76
76
  create: (project, task) => deps.create({ project, ...task }),
77
77
  comment: deps.comment,
78
78
  prepare: deps.prepare,
79
- async taskTree(project, task) {
80
- const repo = deps.repo(project);
81
- const refs = await deps.git(repo, ['for-each-ref', '--format=%(objectname)', `refs/heads/${task.toLowerCase()}`]);
82
- const commit = refs.code === 0 ? refs.out.split(/\r?\n/).find((line) => line.trim() !== '') : undefined;
83
- return commit === undefined ? null : revision(repo, `${commit.trim()}^{tree}`);
79
+ // A check of other commands than the project's now proves nothing about them.
80
+ reportedTree(project, task) {
81
+ const report = deps.reported(project, task);
82
+ const commands = deps.commands(project);
83
+ const same = report !== undefined && report.commands.length === commands.length && report.commands.every((command, at) => command === commands[at]);
84
+ return same ? report.tree : null;
84
85
  },
85
86
  tree: (project, commit) => revision(deps.repo(project), `${commit}^{tree}`),
86
87
  checking(project) {
@@ -9,6 +9,44 @@ export class CallTimeout extends Error {
9
9
  this.name = 'CallTimeout';
10
10
  }
11
11
  }
12
+ /** A `CallTimeout`, as it is or under the `cause` of an error that wraps it. */
13
+ export function isCallTimeout(error) {
14
+ for (let each = error; each instanceof Error; each = each.cause)
15
+ if (each instanceof CallTimeout)
16
+ return true;
17
+ return false;
18
+ }
19
+ /**
20
+ * A wait of the chain's own made of folder calls: `claude agents` polled until a launched session shows or a stopped one
21
+ * goes (EKR-102). Right after the service's start the folder's queue is full of `/context` probes, and a call whose
22
+ * timeout passes there never starts: such a call is tried again and does not use up the wait, which grows by the time
23
+ * the call lost, up to `patienceMs` from the start — the longest a running call may hold the folder.
24
+ */
25
+ export class QueueWait {
26
+ deadline;
27
+ patience;
28
+ constructor(waitMs, patienceMs = KILL_AFTER_MS) {
29
+ const now = Date.now();
30
+ this.deadline = now + waitMs;
31
+ this.patience = now + patienceMs;
32
+ }
33
+ get open() {
34
+ return Date.now() < this.deadline;
35
+ }
36
+ async call(call) {
37
+ for (;;) {
38
+ const asked = Date.now();
39
+ try {
40
+ return await call();
41
+ }
42
+ catch (error) {
43
+ if (!(error instanceof CallTimeout) || Date.now() >= this.patience)
44
+ throw error;
45
+ this.deadline = Math.min(this.patience, this.deadline + Date.now() - asked);
46
+ }
47
+ }
48
+ }
49
+ }
12
50
  /**
13
51
  * The short CLI calls of one account folder, one at a time (EKR-15). Any call may renew the folder's sign-in, and a
14
52
  * renewed refresh token is single-use: a call killed after sending the renewal and before writing the answer leaves
@@ -12,7 +12,7 @@ import { fail, notice, NoticeError } from '../notice/notice.js';
12
12
  import { binaryPath, samePath } from '../paths.js';
13
13
  import { blockedAsk, blockedOn, launchedModel, launchedSettings, parseAgents, parseSessionRecord, withLiveRecords } from '../sessions/agents.js';
14
14
  import { newestExtensionBinary } from '../sessions/paths.js';
15
- import { CallTimeout, FolderCalls } from './calls.js';
15
+ import { CallTimeout, FolderCalls, QueueWait } from './calls.js';
16
16
  import { contextArgs } from './context.js';
17
17
  import { daemonVersionOf, noDaemonIn } from './release.js';
18
18
  import { descendantsOf, killLeftovers, sessionProcessAlive } from './tree.js';
@@ -68,10 +68,15 @@ export class ClaudeCli {
68
68
  this.envOf = envOf;
69
69
  this.calls = calls;
70
70
  }
71
- async agents(home) {
72
- const { stdout } = await this.call(home, ['agents', '--json', '--all'], undefined, 16 * 1024 * 1024);
71
+ /** `priority` — a listing the chain waits on (a launch, a resume, a stop) goes ahead of the folder's waiting calls. */
72
+ async agents(home, priority = false) {
73
+ const { stdout } = await this.call(home, ['agents', '--json', '--all'], undefined, 16 * 1024 * 1024, this.timeoutMs, priority);
73
74
  return withJobFiles(home, withLiveRecords(parseAgents(stdout, home.key), await liveRecords(home)));
74
75
  }
76
+ /** The chain's own listing within `wait`: ahead of the waiting calls, and tried again after a timeout in the queue. */
77
+ listIn(home, wait) {
78
+ return wait.call(() => this.agents(home, true));
79
+ }
75
80
  /** `claude --version`: `2.1.303 (Claude Code)`. */
76
81
  async version(env, binary = this.bin()) {
77
82
  return (await run(binary, ['--version'], { env, timeout: this.timeoutMs, windowsHide: true })).stdout;
@@ -143,7 +148,7 @@ export class ClaudeCli {
143
148
  * keeps its `ParentProcessId` there, while `ps` is taken first, before orphans are reparented.
144
149
  */
145
150
  async stop(home, agentId, sessionId) {
146
- const running = (await this.agents(home)).find((entry) => entry.sessionId === sessionId);
151
+ const running = (await this.listIn(home, new QueueWait(0))).find((entry) => entry.sessionId === sessionId);
147
152
  if (running === undefined || isGone(running))
148
153
  return;
149
154
  if (running.pid !== undefined && !(await sessionProcessAlive(running.pid, running.processStartedAt, true)))
@@ -157,13 +162,13 @@ export class ClaudeCli {
157
162
  catch (error) {
158
163
  throw fail('claude.stopFailed', { agent: agentId }, { detail: outputOf(error) }, { cause: error });
159
164
  }
160
- const deadline = Date.now() + APPEAR_TIMEOUT_MS;
161
- while (Date.now() < deadline) {
165
+ const wait = new QueueWait(APPEAR_TIMEOUT_MS);
166
+ while (wait.open) {
162
167
  if (await sessionProcessAlive(running.pid, running.processStartedAt)) {
163
168
  await delay(EXIT_POLL_MS);
164
169
  continue;
165
170
  }
166
- if (isGone((await this.agents(home)).find((entry) => entry.sessionId === sessionId))) {
171
+ if (isGone((await this.listIn(home, wait)).find((entry) => entry.sessionId === sessionId))) {
167
172
  await killLeftovers(await children);
168
173
  return;
169
174
  }
@@ -209,9 +214,9 @@ export class ClaudeCli {
209
214
  }
210
215
  }
211
216
  async appear(home, match, failure) {
212
- const deadline = Date.now() + APPEAR_TIMEOUT_MS;
213
- while (Date.now() < deadline) {
214
- const found = (await this.agents(home)).find(match);
217
+ const wait = new QueueWait(APPEAR_TIMEOUT_MS);
218
+ while (wait.open) {
219
+ const found = (await this.listIn(home, wait)).find(match);
215
220
  if (found !== undefined)
216
221
  return found;
217
222
  await delay(APPEAR_POLL_MS);
@@ -140,6 +140,18 @@ async function deleteLeftFolder(path, gitOut) {
140
140
  return leftBehind(path, `${gitOut}\n${error instanceof Error ? error.message : String(error)}`);
141
141
  }
142
142
  }
143
+ /** A second try at a folder a cleanup left (EKR-99), once the session that held it is stopped; one registered again since is not touched. */
144
+ export async function removeLeftFolder(git, repo, path) {
145
+ try {
146
+ if ((await worktreeAt(git, repo, path)) !== undefined)
147
+ return null;
148
+ await rm(path, { recursive: true, force: true });
149
+ return null;
150
+ }
151
+ catch (error) {
152
+ return leftBehind(path, error instanceof Error ? error.message : String(error));
153
+ }
154
+ }
143
155
  /**
144
156
  * `git worktree remove` on Windows follows junctions: it empties a linked folder outside the worktree
145
157
  * (`npm link`) and stops at a dangling one (an npm workspace link whose package it already deleted),
@@ -10,6 +10,7 @@ import { guardedServer } from './server-guard.js';
10
10
  import { englishOf, fail, noticeOf } from './notice/notice.js';
11
11
  import { isTaskId, parsePeriodQuery, parseStatsFilter, } from './stats/model.js';
12
12
  import { parseChangeIds, parseCompareQuery, parseRulesQuery, } from './stats/rules.js';
13
+ import { checkReportOf } from './chain/checkreports.js';
13
14
  import { statusMovesOf } from './chain/moves.js';
14
15
  import { CLAUDE } from './claude/name.js';
15
16
  import { HOOK_EVENTS } from './sessions/mail.js';
@@ -190,6 +191,24 @@ async function route(deps, request, response) {
190
191
  sendJson(response, 200, check);
191
192
  return;
192
193
  }
194
+ if (request.method === 'POST' && mergeCheck !== null) {
195
+ let known;
196
+ try {
197
+ const report = checkReportOf(await readJsonBody(request, MAX_BODY_BYTES));
198
+ if (report === null)
199
+ throw fail('request.required', { field: 'tree' });
200
+ known = deps.checkReport(decodeURIComponent(mergeCheck[1]), report);
201
+ }
202
+ catch (error) {
203
+ sendFailure(response, error);
204
+ return;
205
+ }
206
+ if (known)
207
+ sendJson(response, 200, { ok: true });
208
+ else
209
+ response.writeHead(404).end();
210
+ return;
211
+ }
193
212
  const standards = /^\/api\/sessions\/([^/]+)\/standards$/.exec(path);
194
213
  if (request.method === 'GET' && standards !== null) {
195
214
  const check = deps.mergeCheck(decodeURIComponent(standards[1]));
@@ -25,7 +25,8 @@ import { DEFAULT_BRANCH, DEFAULT_CI, mergeTargetOf, projectLabel } from '../conf
25
25
  import { runGit } from '../git/run.js';
26
26
  import { finishSlot, heldSlot, prepareSlot, slotPaths } from '../git/slot.js';
27
27
  import { fastForwardMain, syncMain } from '../git/sync.js';
28
- import { ensureIgnored, finishWorktree, prepareWorktree, requireBranch, requireCheckedOut, taskPlace } from '../git/worktree.js';
28
+ import { ensureIgnored, finishWorktree, prepareWorktree, removeLeftFolder, requireBranch, requireCheckedOut, taskPlace } from '../git/worktree.js';
29
+ import { isCallTimeout } from '../claude/calls.js';
29
30
  import { exhaustedReset, limitReopenedAt } from '../limits/model.js';
30
31
  import { overageSession } from '../limits/overage-session.js';
31
32
  import { englishOf, fail, notice, noticeOf } from '../notice/notice.js';
@@ -342,7 +343,7 @@ export async function wireDispatcher(ctx) {
342
343
  let stopped;
343
344
  let finished;
344
345
  try {
345
- stopped = await ctx.stopTaskSessions(repo, task, Math.max(span, 1));
346
+ stopped = await ctx.stopTaskSessions(project, repo, task, Math.max(span, 1));
346
347
  const main = ctx.branchOf(project);
347
348
  const drop = pull === undefined ? {} : { force: pull.force, remote: pull.remote };
348
349
  finished = await (span > 0 ? finishSlot(runGit, repo, task, span, main, drop) : finishWorktree(runGit, repo, task, main, drop));
@@ -352,7 +353,8 @@ export async function wireDispatcher(ctx) {
352
353
  throw error;
353
354
  }
354
355
  ctx.packages.release(project, task);
355
- const outcome = { ...finished, warnings: [...stopped, ...finished.warnings] };
356
+ const left = stopped.retrying ? deferLeftFolder(ctx, project, repo, task, finished.warnings) : finished.warnings;
357
+ const outcome = { ...finished, warnings: [...stopped.warnings, ...left] };
356
358
  for (const warning of outcome.warnings)
357
359
  console.warn(`git: ${task}: ${englishOf(warning)}`);
358
360
  if (outcome.syncError !== null)
@@ -400,6 +402,7 @@ export async function wireDispatcher(ctx) {
400
402
  watches: (project) => (ctx.ciWatches.found ? ctx.ciWatches.shown(project) : null),
401
403
  settings: (project) => ctx.configStore.current.settings[project]?.ci ?? DEFAULT_CI,
402
404
  commands: (project) => ctx.configStore.current.settings[project]?.check ?? [],
405
+ reported: (project, task) => ctx.checkReports.of(project, task),
403
406
  language: () => ctx.configStore.current.language ?? ctx.promptLanguage(),
404
407
  promptLanguage: ctx.promptLanguage,
405
408
  create: async (task) => (await ctx.linkOf(task.project)?.run(async (tracker) => tracker.create?.(task))) ?? null,
@@ -544,14 +547,21 @@ export async function vacateSlot(ctx, slot, task) {
544
547
  console.log(`slot: stopped the session ${agent.sessionId} of ${owner} before ${task} took ${slot}`);
545
548
  }
546
549
  }
547
- /** Stops the task's sessions that are not mid-turn; the rest are kept in `lingering`, to be stopped once their turn ends (BTN-616). */
548
- export async function stopTaskSessions(ctx, repo, task, count) {
550
+ /** How long a cleanup after Done keeps trying a stop that timed out in the folder's queue before it warns (EKR-99). */
551
+ export const STOP_RETRY_MS = 5 * 60_000;
552
+ /**
553
+ * Stops the task's sessions that are not mid-turn; the rest are kept in `lingering`, to be stopped once their turn ends
554
+ * (BTN-616). A stop that timed out waiting for the account folder's queue is kept too, to be tried again (EKR-99):
555
+ * `retrying` says so, and the cleanup then leaves the worktree folder the session holds to `deferLeftFolder`.
556
+ */
557
+ export async function stopTaskSessions(ctx, project, repo, task, count) {
549
558
  const own = new Set(ctx.launches.filter((entry) => entry.task === task).map((entry) => entry.sessionId));
550
559
  const slots = slotPaths(repo, count);
551
560
  const sessions = ctx.agents.filter((agent) => agent.id !== undefined &&
552
561
  isLive(agent) &&
553
562
  (isInside(agent.cwd, taskPlace(repo, task).path) || (slots.some((slot) => isInside(agent.cwd, slot)) && own.has(agent.sessionId))));
554
563
  const warnings = [];
564
+ let retrying = false;
555
565
  for (const agent of sessions) {
556
566
  if (midTurn(agent)) {
557
567
  ctx.lingering.keep(task, agent.sessionId);
@@ -562,24 +572,64 @@ export async function stopTaskSessions(ctx, repo, task, count) {
562
572
  await ctx.stopIn(ctx.homeOf(agent.account ?? 'global'), { agentId: agent.id, sessionId: agent.sessionId });
563
573
  }
564
574
  catch (error) {
565
- warnings.push(notice('cleanup.sessionNotStopped', { session: agent.sessionId }, { cause: noticeOf(error) }));
575
+ if (!isCallTimeout(error)) {
576
+ warnings.push(notice('cleanup.sessionNotStopped', { session: agent.sessionId }, { cause: noticeOf(error) }));
577
+ continue;
578
+ }
579
+ ctx.lingering.keep(task, agent.sessionId, { project, until: Date.now() + STOP_RETRY_MS });
580
+ retrying = true;
581
+ console.log(`cleanup: the stop of the session ${agent.sessionId} of ${task} timed out, it will be tried again: ${englishOf(noticeOf(error))}`);
566
582
  }
567
583
  }
568
- return warnings;
584
+ return { warnings, retrying };
569
585
  }
570
- /** Stops the sessions a cleanup after Done left mid-turn whose turn has ended since (`stopTaskSessions`). */
571
- export async function stopLingering(ctx) {
572
- for (const { task, agent } of ctx.lingering.due(ctx.agents, midTurn)) {
573
- if (agent.id === undefined)
574
- continue;
575
- try {
576
- await ctx.stopIn(ctx.homeOf(agent.account ?? 'global'), { agentId: agent.id, sessionId: agent.sessionId });
577
- console.log(`cleanup: stopped the session ${agent.sessionId} of ${task}, its turn after Done ended`);
586
+ /**
587
+ * The cleanup's warnings without the worktree folder a session whose stop is tried again still holds (EKR-99): the
588
+ * folder is removed once the session is stopped, and warned about only if that fails too.
589
+ */
590
+ export function deferLeftFolder(ctx, project, repo, task, warnings) {
591
+ return warnings.filter((warning) => {
592
+ if (warning.code !== 'cleanup.folderLeft')
593
+ return true;
594
+ ctx.lingering.leave({ project, task, repo, path: warning.params.path, until: Date.now() + STOP_RETRY_MS });
595
+ console.log(`cleanup: the worktree folder ${warning.params.path} of ${task} is held, it will be removed once its session is stopped`);
596
+ return false;
597
+ });
598
+ }
599
+ /**
600
+ * Stops the sessions a cleanup after Done left mid-turn whose turn has ended since, tries again the stops that timed
601
+ * out, and removes the folders they held (`stopTaskSessions`). What still fails once the wait is over is warned about
602
+ * on the task, as the cleanup itself would have.
603
+ */
604
+ export function stopLingering(ctx, git = runGit) {
605
+ return ctx.lingering.alone(async () => {
606
+ for (const { task, agent, retry } of ctx.lingering.due(ctx.agents, midTurn)) {
607
+ if (agent.id === undefined)
608
+ continue;
609
+ try {
610
+ await ctx.stopIn(ctx.homeOf(agent.account ?? 'global'), { agentId: agent.id, sessionId: agent.sessionId });
611
+ console.log(`cleanup: stopped the session ${agent.sessionId} of ${task}, ${retry === undefined ? 'its turn after Done ended' : 'its stop tried again'}`);
612
+ }
613
+ catch (error) {
614
+ if (retry !== undefined && isCallTimeout(error) && Date.now() < retry.until) {
615
+ ctx.lingering.keep(task, agent.sessionId, retry);
616
+ continue;
617
+ }
618
+ console.warn(`cleanup: the session ${agent.sessionId} of ${task} was not stopped: ${englishOf(noticeOf(error))}`);
619
+ if (retry !== undefined)
620
+ ctx.dispatcher.leftover(retry.project, task, notice('cleanup.sessionNotStopped', { session: agent.sessionId }, { cause: noticeOf(error) }));
621
+ }
578
622
  }
579
- catch (error) {
580
- console.warn(`cleanup: the session ${agent.sessionId} of ${task} was not stopped: ${englishOf(noticeOf(error))}`);
623
+ for (const folder of ctx.lingering.dueFolders(Date.now())) {
624
+ const left = await removeLeftFolder(git, folder.repo, folder.path);
625
+ if (left === null) {
626
+ console.log(`cleanup: removed the worktree folder ${folder.path} of ${folder.task} once its session was stopped`);
627
+ continue;
628
+ }
629
+ console.warn(`git: ${folder.task}: ${englishOf(left)}`);
630
+ ctx.dispatcher.leftover(folder.project, folder.task, left);
581
631
  }
582
- }
632
+ });
583
633
  }
584
634
  function midTurn(agent) {
585
635
  return agent.status === 'busy' || agent.status === 'waiting';
@@ -384,6 +384,13 @@ export function wireServer(ctx) {
384
384
  const commands = settings === undefined ? [] : mergeCheck(settings.check, settings.ci, views);
385
385
  return { commands, branch: ctx.branchOf(run.project), standards: settings?.standards ?? [] };
386
386
  },
387
+ checkReport: (sessionId, report) => {
388
+ const run = handoffsOf(ctx.launches, sessionId);
389
+ if (run === undefined)
390
+ return false;
391
+ ctx.checkReports.report(run.project, run.task, report);
392
+ return true;
393
+ },
387
394
  tools: async (project) => {
388
395
  const repo = ctx.configStore.current.projects[project];
389
396
  if (repo === undefined)
@@ -23,6 +23,7 @@ import { englishOf, fail, noticeOf, withLabels } from './notice/notice.js';
23
23
  import { guardToken } from './guard.js';
24
24
  import { ProjectRemotes } from './projects/remotes.js';
25
25
  import { Approvals } from './sessions/approvals.js';
26
+ import { CheckReports } from './chain/checkreports.js';
26
27
  import { createChat } from './sessions/chat.js';
27
28
  import { Mailbox } from './sessions/mailbox.js';
28
29
  import { settleMail } from './sessions/mailRelay.js';
@@ -134,6 +135,7 @@ const context = {
134
135
  get changelogs() { return changelogs; },
135
136
  get chatTitles() { return chatTitles; },
136
137
  get checkMergeTarget() { return checkMergeTarget; },
138
+ get checkReports() { return checkReports; },
137
139
  get choiceFor() { return choiceFor; },
138
140
  get ciOn() { return ciOn; },
139
141
  get ciTokenOf() { return ciTokenOf; },
@@ -410,6 +412,7 @@ const packages = accountsService.wirePackages(context);
410
412
  */
411
413
  function briefOn(project, reader = project) { return accountsService.briefOn(context, project, reader); }
412
414
  const approvals = new Approvals({ language: () => configStore.current.language ?? promptLanguage(), unattended: () => configStore.current.unattended });
415
+ const checkReports = new CheckReports();
413
416
  const runtimes = accountsService.wireRuntimes(context);
414
417
  /** The agent of an account folder: every session of the folder runs on it. */
415
418
  const agentOf = accountsService.wireAgentOf(context);
@@ -621,7 +624,7 @@ const { mailRelay, answerSession } = createChat({
621
624
  function occupantsOf(slot, task) { return chainService.occupantsOf(context, slot, task); }
622
625
  function slotUse(slot, task) { return chainService.slotUse(context, slot, task); }
623
626
  function vacateSlot(slot, task) { return chainService.vacateSlot(context, slot, task); }
624
- function stopTaskSessions(repo, task, count) { return chainService.stopTaskSessions(context, repo, task, count); }
627
+ function stopTaskSessions(project, repo, task, count) { return chainService.stopTaskSessions(context, project, repo, task, count); }
625
628
  function stopLingering() { return chainService.stopLingering(context); }
626
629
  /** What holds a project the page asks to remove: its chain, live sessions of its tasks or in its folders, the places it keeps. */
627
630
  function removalFacts(project, repo) { return chainService.removalFacts(context, project, repo); }
@@ -1,26 +1,52 @@
1
1
  import { isLive } from './agents.js';
2
2
  /**
3
- * The sessions a cleanup after Done found mid-turn and left running (BTN-616): nothing else stops them once their task
4
- * has left the chain, and a Codex session would rest as `waiting` for good. Each is stopped once its turn ends
5
- * (exception 4 of invariant 1). In memory: a restart loses them, as it loses the cleanup that kept them.
3
+ * The sessions a cleanup after Done left running (BTN-616): found mid-turn, or whose stop timed out (EKR-99). Nothing
4
+ * else stops them once their task has left the chain, and a Codex session would rest as `waiting` for good. Each is
5
+ * stopped once its turn ends (exception 4 of invariant 1), and the worktree folder it held is removed after it. In
6
+ * memory: a restart loses them, as it loses the cleanup that kept them.
6
7
  */
7
8
  export class Lingering {
8
- /** By session id, the task each belongs to. */
9
+ /** By session id. */
9
10
  sessions = new Map();
10
- keep(task, sessionId) {
11
- this.sessions.set(sessionId, task);
11
+ folders = new Map();
12
+ running = false;
13
+ keep(task, sessionId, retry) {
14
+ this.sessions.set(sessionId, retry === undefined ? { task } : { task, retry });
15
+ }
16
+ leave(folder) {
17
+ this.folders.set(folder.path, folder);
12
18
  }
13
19
  /** The kept sessions whose turn has ended, to stop now, forgotten as they are given; a session gone meanwhile is forgotten too. */
14
20
  due(agents, busy) {
15
21
  const due = [];
16
- for (const [sessionId, task] of this.sessions) {
22
+ for (const [sessionId, { task, retry }] of this.sessions) {
17
23
  const agent = agents.find((each) => each.sessionId === sessionId);
18
24
  if (agent !== undefined && isLive(agent) && busy(agent))
19
25
  continue;
20
26
  this.sessions.delete(sessionId);
21
27
  if (agent !== undefined && isLive(agent))
22
- due.push({ task, agent });
28
+ due.push(retry === undefined ? { task, agent } : { task, agent, retry });
23
29
  }
24
30
  return due;
25
31
  }
32
+ /** The left folders to remove now, forgotten as they are given: no session of their task is kept any more, or their wait is over. */
33
+ dueFolders(now) {
34
+ const held = new Set([...this.sessions.values()].map((kept) => kept.task));
35
+ const due = [...this.folders.values()].filter((folder) => !held.has(folder.task) || now >= folder.until);
36
+ for (const folder of due)
37
+ this.folders.delete(folder.path);
38
+ return due;
39
+ }
40
+ /** Runs `work` unless the previous run is under way: otherwise a tick would remove a folder while the previous one still stops its session. */
41
+ async alone(work) {
42
+ if (this.running)
43
+ return;
44
+ this.running = true;
45
+ try {
46
+ await work();
47
+ }
48
+ finally {
49
+ this.running = false;
50
+ }
51
+ }
26
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "even-keel",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Runs Claude Code sessions over a tracker's tasks one after another, in the order of their blocks relations",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "checkpoint",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Context checkpoints for Even Keel chain sessions of Claude Code, Codex and OpenCode: once the context passes 200k tokens (and every 50k after, every 25k past 250k), the session is asked to write a handoff note and end its turn with `CHECKPOINT: <path>`, so that Even Keel continues the task in a fresh session instead of re-reading the whole context on every turn. A session that writes the note but forgets the line is sent back to add it. The context and the note come from Even Keel, which reads the transcripts of both agents, so a session it did not start is left alone. The first threshold is the project's calibrated one, and a task that has had three handoffs is asked only from 300k; on a small context window the late and hard thresholds come down to 85 % and 95 % of it. A project that turns handoffs by context off in Even Keel gets no nudge at all and is left to the agent's own compaction. Thresholds: CHECKPOINT_FIRST_TOKENS, CHECKPOINT_STEP_TOKENS, CHECKPOINT_LATE_TOKENS, CHECKPOINT_LATE_STEP_TOKENS, CHECKPOINT_HARD_TOKENS and CHECKPOINT_MAX_HANDOFFS. In a chain session of a project without a CI to judge its main branch, the merge of the task branch waits for the project's check commands from Even Keel and is blocked while they fail. A message the user writes from Even Keel's chat to a working session reaches it mid-turn: before or after its next tool call, at its stop (the turn goes on), or in place of a question it was about to ask. A tool call Claude Code stops on a permission dialog for is asked on Even Keel's page too, and the user's \"Allow\" or \"Deny\" there answers the dialog without stopping the session. An MCP call Claude Code made before loading the tool's schema, whose numbers or lists went as strings and failed the server's validation, gets a hint in the context: load the schema with ToolSearch and repeat the call. A project's standards, set on Even Keel's page (a document of the repository and the files it guards): the first read of a guarded file brings the document into the context, the first edit of one before that is refused with the document, a compaction brings it again, and a standard that asks for it holds the merge (in PR mode, the PULL REQUEST mark) of a branch that changed its files until `.temp/shot/` has shots newer than the change and `.temp/<document>-check.md` answers each question of the document's section \"The check\". OpenCode sessions get the nudges and the chat's messages after each tool call, the standards, the merge check and the CHECKPOINT line from the plugin's OpenCode plugin (opencode/checkpoint.mjs): a turn that wrote the note gets the line added to its last text instead of being sent back.",
5
5
  "author": {
6
6
  "name": "Even Keel"
@@ -30,7 +30,7 @@ Even Keel takes it from there: it stops the session and starts a new one in the
30
30
 
31
31
  ## The check before the merge
32
32
 
33
- A third hook, on `PreToolUse` of Bash, guards the merge of a chain session. When a command runs `git … merge … <branch>` with the branch of the session's own worktree — the session bringing its task into `main` — the hook asks Even Keel for the project's check (`/api/sessions/<id>/check`, the `commands.check` of the project). Even Keel gives the commands only when no CI it counts will judge `main`: the project counts none, or one does not answer. The hook runs them in order in the worktree, through the system shell, 20 minutes each at most; the first that fails blocks the merge, and its command, exit code and the last 60 lines of output go back to the session to fix. A command without `merge`, a merge of another branch, `--abort`, a session Even Keel did not start, or Even Keel not answering within two seconds — the hook lets the command through.
33
+ A third hook, on `PreToolUse` of Bash, guards the merge of a chain session. When a command runs `git … merge … <branch>` with the branch of the session's own worktree — the session bringing its task into `main` — the hook asks Even Keel for the project's check (`/api/sessions/<id>/check`, the `commands.check` of the project). Even Keel gives the commands only when no CI it counts will judge `main`: the project counts none, or one does not answer. The hook runs them in order in the worktree, through the system shell, 20 minutes each at most; the first that fails blocks the merge, and its command, exit code and the last 60 lines of output go back to the session to fix. When every command passes on a worktree without uncommitted changes to tracked files, the hook reports the tree of its `HEAD` and the commands to Even Keel (`POST` to the same address): only that report lets Even Keel count the pushed `main` as checked, and a push without one is checked again before the next task. A command without `merge`, a merge of another branch, `--abort`, a session Even Keel did not start, or Even Keel not answering within two seconds — the hook lets the command through.
34
34
 
35
35
  The refusal is an explicit `permissionDecision: deny`, which also blocks nested shell calls from Codex code mode. Codex 0.164.0 was seen to ignore exit code 2 alone for those calls.
36
36
 
@@ -86,6 +86,16 @@ export async function checkOf(sessionId) {
86
86
  return { commands, standards: standardsIn(body), main: typeof body?.branch === "string" && body.branch !== "" ? body.branch : "main" };
87
87
  }
88
88
 
89
+ /** Tells Even Keel the project's check before the merge passed on `tree` (EKR-103); a failure is the caller's to swallow. */
90
+ export async function reportCheck(sessionId, tree, commands) {
91
+ await fetch(`${base()}/api/sessions/${encodeURIComponent(sessionId)}/check`, {
92
+ method: "POST",
93
+ headers: { "content-type": "application/json" },
94
+ body: JSON.stringify({ tree, commands }),
95
+ signal: AbortSignal.timeout(2000),
96
+ });
97
+ }
98
+
89
99
  function standardsIn(body) {
90
100
  if (!Array.isArray(body?.standards)) return [];
91
101
  return body.standards.filter((standard) => typeof standard?.doc === "string" && standard.doc !== "" && Array.isArray(standard.files));
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // PreToolUse guard on Bash: a chain session's merge of its task branch waits for the project's check,
3
3
  // run in the task's worktree. Even Keel gives the commands only when no CI it counts will judge main;
4
- // a failed command blocks the merge, and its output goes back to the session to fix.
4
+ // a failed command blocks the merge, and its output goes back to the session to fix. A passed check is reported with
5
+ // the tree it ran on: only that report lets Even Keel count main checked after the push (EKR-103).
5
6
  import { readFileSync } from "node:fs";
6
- import { checkOf } from "./evenkeel.mjs";
7
+ import { checkOf, reportCheck } from "./evenkeel.mjs";
7
8
  import { mergeRefusal } from "./merges.mjs";
8
9
 
9
10
  function readInput() {
@@ -18,7 +19,12 @@ async function main() {
18
19
  const input = readInput();
19
20
  if (!input || input.tool_name !== "Bash" || !input.session_id) return;
20
21
  const cwd = process.env.CLAUDE_PROJECT_DIR || input.cwd || input.tool_input?.workdir || ".";
21
- const text = await mergeRefusal(input.tool_input?.command, cwd, () => checkOf(input.session_id));
22
+ const text = await mergeRefusal(
23
+ input.tool_input?.command,
24
+ cwd,
25
+ () => checkOf(input.session_id),
26
+ (tree, commands) => reportCheck(input.session_id, tree, commands),
27
+ );
22
28
  if (text === null) return;
23
29
  // An explicit denial: Codex 0.164.0 ignores exit code 2 alone for the nested shell calls of code mode.
24
30
  process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: text } }));
@@ -85,8 +85,10 @@ export function runCommand(command, cwd, timeoutMs = COMMAND_TIMEOUT_MS) {
85
85
  * What stops `command` when it merges the task branch of the worktree at `cwd` and the project's check fails, or the
86
86
  * check of a standard whose files the branch changed is not done (`standardsRefusal`): the refusal text, or null — no
87
87
  * such merge, no check, or every command passed. `checkOf` asks Even Keel; when it fails, the merge goes on.
88
+ * Once every command passed, `report` tells Even Keel the tree they passed on (EKR-103): only that report counts main
89
+ * as checked after the push. A worktree with changes to tracked files is no tree of a commit, so it is not reported.
88
90
  */
89
- export async function mergeRefusal(command, cwd, checkOf) {
91
+ export async function mergeRefusal(command, cwd, checkOf, report = async () => {}) {
90
92
  if (!String(command ?? "").includes("merge")) return null;
91
93
  const root = await git(cwd, ["rev-parse", "--show-toplevel"]);
92
94
  const branch = root === "" ? "" : await git(root, ["branch", "--show-current"]);
@@ -99,5 +101,16 @@ export async function mergeRefusal(command, cwd, checkOf) {
99
101
  const run = await runCommand(step, root);
100
102
  if (run.code !== 0) return refusal(step, run.code, run.output);
101
103
  }
104
+ if (check.commands.length > 0) await reportTree(root, check.commands, report);
102
105
  return null;
103
106
  }
107
+
108
+ async function reportTree(root, commands, report) {
109
+ const changes = await new Promise((resolve) => {
110
+ execFile("git", ["status", "--porcelain", "--untracked-files=no"], { cwd: root, encoding: "utf8", windowsHide: true }, (error, stdout) => resolve(error ? null : stdout.trim()));
111
+ });
112
+ if (changes !== "") return;
113
+ const tree = await git(root, ["rev-parse", "HEAD^{tree}"]);
114
+ // Even Keel not taking the report leaves main unchecked, never the merge blocked.
115
+ if (tree !== "") await Promise.resolve(report(tree, commands)).catch(() => {});
116
+ }
@@ -3,14 +3,15 @@
3
3
  // what the hook commands of Claude Code and Codex ask (../hooks/evenkeel.mjs) — the checkpoint nudge due and the
4
4
  // chat's waiting messages — and puts them after the tool's output, the only way into the context in the middle of
5
5
  // a turn. A delivered message is also kept in the call's metadata, where Even Keel's feed finds it. Before a shell
6
- // call that merges the task branch it runs the project's check, and an error thrown there keeps the call from running.
6
+ // call that merges the task branch it runs the project's check, and an error thrown there keeps the call from running;
7
+ // a passed check is reported to Even Keel with the tree it ran on, as the hook command does.
7
8
  // The project's standards (../hooks/standards.mjs) work as in the hook commands: a read of a guarded file gets the
8
9
  // document after its output, a first edit before it is refused by an error, and a compaction forgets what was given.
9
10
  // `opencode run` has no Stop to block, so a turn that wrote the handoff note and ends without the CHECKPOINT line gets
10
11
  // the line added to its text as it completes; for the same reason PR mode's mark is not held for the standards. A
11
12
  // subagent runs in a session of its own, which Even Keel does not know, so it is left alone. Only `server` is
12
13
  // exported: OpenCode takes the module's exports for plugins.
13
- import { checkOf, checkpointNote, mailOf, noteAtEnd, STATE_DIR, standardsOf } from "../hooks/evenkeel.mjs";
14
+ import { checkOf, checkpointNote, mailOf, noteAtEnd, reportCheck, STATE_DIR, standardsOf } from "../hooks/evenkeel.mjs";
14
15
  import { hasMark } from "../hooks/handoff.mjs";
15
16
  import { mergeRefusal } from "../hooks/merges.mjs";
16
17
  import { callOf, clearGiven, due, givenStore, standardsAt } from "../hooks/standards.mjs";
@@ -52,7 +53,12 @@ export const server = async ({ directory }) => {
52
53
  return;
53
54
  }
54
55
  // Even Keel not answering, or git failing, must never block a merge.
55
- const text = await mergeRefusal(output?.args?.command, directory, () => checkOf(input.sessionID)).catch(() => null);
56
+ const text = await mergeRefusal(
57
+ output?.args?.command,
58
+ directory,
59
+ () => checkOf(input.sessionID),
60
+ (tree, commands) => reportCheck(input.sessionID, tree, commands),
61
+ ).catch(() => null);
56
62
  if (text !== null) throw new Error(text);
57
63
  },
58
64
  "tool.execute.after": async (input, output) => {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gitlab",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "GitLab Issues for Even Keel sessions: a PAT-capable MCP server for gitlab.com or a self-managed instance, and the task skill.",
5
5
  "author": { "name": "Even Keel" },
6
6
  "keywords": ["gitlab", "issues", "tracker", "even-keel", "mcp"]
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: task
3
- description: Work a GitLab issue through the gitlab MCP server: read the brief, record decisions, file blockers and questions, leave a closing comment and merge into the project's main branch. Use for task ids such as APP-12 in projects tracked in GitLab Issues, or before creating an issue there.
3
+ description: "Work a GitLab issue through the gitlab MCP server: read the brief, record decisions, file blockers and questions, leave a closing comment and merge into the project's main branch. Use for task ids such as APP-12 in projects tracked in GitLab Issues, or before creating an issue there."
4
4
  ---
5
5
 
6
6
  # Working a GitLab issue