Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: judge a CoS run's success by whether it committed in its run window, not by a task-id marker nothing emits (#3637)
[._.]/ Adam Eivy63fca0b9e8b3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d1afd87c4c..6218d1834f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -34,3 +34,6 @@- **CoS tasks filed for PortOS's own work now actually run.** Two producers used `metadata.app` as a feature tag when it is workspace routing — it has to name a record in `data/apps.json`. The Series Pipeline autopilot filed every gap it found (unparseable script, stalled verify, failed render, run-ending error) at `app: pipeline`, and the auto-fixer filed its AI-provider investigations at `app: portos`, which matches neither the seeded app id (`portos-default`) nor its name. Both were harmless until the wrong-repo guard (#3180) closed the silent fall-through to the PortOS root: since then each of these tasks was filed and then rejected at every spawn attempt, so the one mechanism that surfaces an autopilot capability gap never reached an agent. Both now file with no app — which resolves to the PortOS workspace they were always meant to run in — and migration 234 un-routes the ones already queued on existing installs (re-stamping them so the fix wins the sync merge against a peer that hasn't upgraded).- A CoS task naming an app that doesn't resolve to a repository directory is now **parked as blocked** instead of retried forever. The spawn guard refused to start the agent (correctly — it would otherwise commit into the PortOS checkout) but left the task `pending`, so the scheduler re-dequeued it every tick and reprinted the same error, while the fix was only visible in that task's own log. It now lands in the Blocked list, and the message covers both ways an app resolves to nothing: no Repository Path set, or nothing in Apps matching that id/name at all (in which case the fix is to clear the app from the task, not to register a path).+++- Autonomous CoS runs are no longer marked as having failed their success criteria by a check nothing could ever pass. `evaluateSuccessCriteria` judged a run by grepping for a commit whose subject carried the task id — a marker no prompt, template, or slashdo command ever asked an agent to write, and one the repo's own commit conventions forbid. So every ordinary code-editing run recorded `validationPassed: false`, and because a declared verdict outranks the exit code in task-learning, those fabricated failures filled the learning buckets that drive the Learning card, routing, and duration estimates. The criterion is now the same run-window commit probe the idle reaper already uses (did this run leave a commit stamped inside its own window?), shared as `server/lib/gitCommitProbe.js` by finalize, run completion, runner completion, and orphan recovery. A run with no usable window records the "no criterion declared" sentinel rather than a false miss, the existing exemptions for non-committing task types are unchanged, and a migration purges the buckets the old criterion poisoned.diff --git a/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.js b/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.jsnew file mode 100644index 0000000000..325e6a5d9d--- /dev/null+++ b/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.js@@ -0,0 +1,121 @@+/**+ * Purge the learning buckets poisoned by the unsatisfiable `[task-<id>]` commit+ * criterion (#3637) — the general case of migrations 197 and 198.+ *+ * Background:+ * `evaluateSuccessCriteria` decided a run's `validationPassed` by grepping the+ * repo for a commit whose subject contained `[task-<id>]`. NOTHING ever emitted+ * that marker — no prompt, template, or slashdo command asked an agent to stamp+ * a task id into a commit subject, and the root CLAUDE.md forbids exactly that+ * shape of subject line. So the criterion was unsatisfiable.+ *+ * That verdict is not inert: in `taskLearning/metrics.js`, a declared boolean+ * OVERRIDES the runner's exit code (`outcomeSuccess = validationPassed ?? success`).+ * Every autonomous, commit-expecting run therefore recorded a FAILURE no matter+ * how well it went, and those fabricated failures feed the CoS Learning card,+ * routing, duration estimates, and the scope-awareness classifier.+ *+ * 197 and 198 purged the two buckets where the artifact was first noticed+ * (layered-intelligence, the gh/git coordinators). #3637 replaces the criterion+ * itself with the run-window commit probe (`server/lib/gitCommitProbe.js`), which+ * is satisfiable — but that fix is PROSPECTIVE. Every other autonomous bucket on+ * an existing install still carries the fabricated failures.+ *+ * `taskLearning/lifecycle.js`'s `withoutStaleCoordinatorVerdict` does NOT cover+ * them: it drops the fossil only for tasks where `declaresNoCommitCriterion` is+ * true, i.e. exactly the exempt types 197/198 already handled. Ordinary+ * code-editing runs were never in its scope, so a migration is required.+ *+ * Approach:+ * DELETE each affected bucket rather than repair it — `validationPassed:false`+ * overwrote the runner's real verdict at record time, so the truth of each+ * historical run is not on disk. Deleting resets each type to an honest "no runs+ * recorded yet". `removeTaskTypeFromLearningData` unwinds the contribution from+ * every aggregate the bucket touched, not just `byTaskType`.+ *+ * KEPT (never poisoned, so purging them would destroy real history):+ * - `user-task` — `evaluateSuccessCriteria` returns the null sentinel for+ * `taskType === 'user'`, so those runs were always exit-code-judged.+ * - the buckets 197/198 already purged (layered-intelligence + the+ * NON_COMMITTING_COORDINATOR_TASK_TYPES set). They have declared no commit+ * criterion since #2696/#2700, so everything recorded after those purges is+ * honest — re-purging would delete legitimately-earned data.+ *+ * Derived from the runtime sources of truth (`NON_COMMITTING_COORDINATOR_TASK_TYPES`)+ * so a coordinator type added there can't drift out of this exemption list.+ *+ * No-op by construction on installs with no learning store or no purgeable bucket.+ *+ * Destructive-rerun guard (#2770): opts into the runner's PURGE class+ * (`purge: true`) so a rerun against a lost/rebuilt applied-list is recorded+ * without executing, rather than dropping post-fix history.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';++import { atomicWrite } from '../../server/lib/fileUtils.js';+import { removeTaskTypeFromLearningData } from '../../server/services/taskLearning/metrics.js';+import { NON_COMMITTING_COORDINATOR_TASK_TYPES } from '../../server/services/taskTypeHooks.js';++const LEARNING_REL = 'data/cos/learning.json';++// Buckets that were NEVER judged by the commit criterion, so their recorded+// outcomes are honest and must survive this purge. `self-improve:` prefixes match+// extractTaskType's first branch (taskLearning/store.js).+export const PRESERVED_BUCKETS = new Set([+ 'user-task',+ 'self-improve:layered-intelligence', // migration 197+ ...[...NON_COMMITTING_COORDINATOR_TASK_TYPES].map((t) => `self-improve:${t}`), // migration 198+]);++/** The buckets this migration would purge from a given `byTaskType` map. Pure. */+export function selectPoisonedBuckets(byTaskType) {+ if (!byTaskType || typeof byTaskType !== 'object' || Array.isArray(byTaskType)) return [];+ return Object.keys(byTaskType).filter((bucket) => !PRESERVED_BUCKETS.has(bucket));+}++export default {+ purge: true,+ async up({ rootDir }) {+ const path = join(rootDir, LEARNING_REL);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log('✅ Commit-criterion learning: no learning store — nothing to purge');+ return { purged: 0, reason: 'no-file' };+ }++ let data;+ try {+ data = JSON.parse(raw);+ } catch {+ // A corrupt learning store is not this migration's problem to fix, and+ // rewriting it would risk destroying recoverable data.+ console.warn('⚠️ Commit-criterion learning: store is not valid JSON — skipping');+ return { purged: 0, reason: 'unparseable' };+ }+ if (!data || typeof data !== 'object' || Array.isArray(data)) {+ console.warn('⚠️ Commit-criterion learning: store is not an object — skipping');+ return { purged: 0, reason: 'unexpected-shape' };+ }++ const present = selectPoisonedBuckets(data.byTaskType);+ if (present.length === 0) {+ console.log('✅ Commit-criterion learning: no poisoned bucket — no changes');+ return { purged: 0 };+ }++ let purged = 0;+ for (const bucket of present) {+ const previous = removeTaskTypeFromLearningData(data, bucket);+ purged += previous?.completed || 0;+ }++ await atomicWrite(path, JSON.stringify(data, null, 2) + '\n');+ console.log(`🧹 Commit-criterion learning: purged ${purged} mis-recorded run(s) across ${present.length} bucket(s) (#3637)`);+ return { purged, buckets: present };+ },+};diff --git a/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.test.js b/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.test.jsnew file mode 100644index 0000000000..b531aa00ef--- /dev/null+++ b/scripts/migrations/234-purge-commit-criterion-poisoned-learning-buckets.test.js@@ -0,0 +1,110 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, rm, readFile, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++import migration, { PRESERVED_BUCKETS, selectPoisonedBuckets } from './234-purge-commit-criterion-poisoned-learning-buckets.js';++let rootDir;++const LEARNING_REL = 'data/cos/learning.json';++async function seed(data) {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(join(rootDir, LEARNING_REL), JSON.stringify(data, null, 2));+}++async function readLearning() {+ return JSON.parse(await readFile(join(rootDir, LEARNING_REL), 'utf-8'));+}++beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'mig234-')); });+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++describe('234-purge-commit-criterion-poisoned-learning-buckets (#3637)', () => {+ it('purges every commit-judged bucket and preserves the ones the criterion never touched', async () => {+ await seed({+ byTaskType: {+ // Judged by the unsatisfiable criterion → fabricated failures.+ 'self-improve:accessibility': { completed: 5, succeeded: 0, failed: 5, successRate: 0, recentOutcomes: [{ t: '2026-07-01T00:00:00Z', s: false }] },+ 'self-improve:code-quality': { completed: 4, succeeded: 0, failed: 4, successRate: 0, recentOutcomes: [] },+ 'app-improve:security': { completed: 2, succeeded: 0, failed: 2, successRate: 0 },+ 'idle-review': { completed: 3, succeeded: 0, failed: 3, successRate: 0 },+ // Never judged by it — must survive.+ 'user-task': { completed: 6, succeeded: 5, failed: 1, successRate: 83 },+ 'self-improve:layered-intelligence': { completed: 2, succeeded: 2, failed: 0, successRate: 100 },+ 'self-improve:branch-reconcile': { completed: 7, succeeded: 6, failed: 1, successRate: 86 },+ }+ });++ const out = await migration.up({ rootDir });++ expect(out.purged).toBe(14);+ expect(out.buckets.sort()).toEqual([+ 'app-improve:security', 'idle-review', 'self-improve:accessibility', 'self-improve:code-quality',+ ]);++ const data = await readLearning();+ expect(Object.keys(data.byTaskType).sort()).toEqual([+ 'self-improve:branch-reconcile', 'self-improve:layered-intelligence', 'user-task',+ ]);+ // Preserved buckets keep their real numbers — the purge must not touch them.+ expect(data.byTaskType['user-task'].successRate).toBe(83);+ expect(data.byTaskType['self-improve:branch-reconcile'].succeeded).toBe(6);+ });++ it('unwinds the purged buckets from the aggregate totals, not just byTaskType', async () => {+ await seed({+ totals: { completed: 10, succeeded: 4, failed: 6, totalDurationMs: 10_000, successDurationMs: 4_000 },+ byTaskType: {+ 'self-improve:accessibility': { completed: 6, succeeded: 0, failed: 6, totalDurationMs: 6_000, successDurationMs: 0, successRate: 0 },+ 'user-task': { completed: 4, succeeded: 4, failed: 0, totalDurationMs: 4_000, successDurationMs: 4_000, successRate: 100 },+ }+ });++ await migration.up({ rootDir });++ const data = await readLearning();+ expect(data.totals.completed).toBe(4);+ expect(data.totals.failed).toBe(0);+ expect(data.totals.succeeded).toBe(4);+ });++ it('is a no-op when only preserved buckets exist', async () => {+ await seed({ byTaskType: { 'user-task': { completed: 3, succeeded: 3, failed: 0, successRate: 100 } } });+ const out = await migration.up({ rootDir });+ expect(out.purged).toBe(0);+ expect((await readLearning()).byTaskType['user-task'].completed).toBe(3);+ });++ it('is a no-op with no learning store at all', async () => {+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'no-file' });+ });++ it('leaves an unparseable or non-object store alone rather than rewriting it', async () => {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(join(rootDir, LEARNING_REL), '{ not json');+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unparseable' });+ expect(await readFile(join(rootDir, LEARNING_REL), 'utf-8')).toBe('{ not json');++ await writeFile(join(rootDir, LEARNING_REL), '[]');+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unexpected-shape' });+ });++ // The runner records a purge migration as applied WITHOUT running it when the+ // applied-list was rebuilt from [] (#2770) — without this flag a lost ledger+ // would delete legitimately-earned post-fix learning data.+ it('opts into the runner purge class', () => {+ expect(migration.purge).toBe(true);+ });++ it('derives its coordinator exemptions from the runtime set rather than a copy', () => {+ // Kept in lockstep with taskTypeHooks.js — a new coordinator type added there+ // must be exempt here too, or this migration would purge its honest history.+ expect(PRESERVED_BUCKETS.has('self-improve:branch-cleanup')).toBe(true);+ expect(PRESERVED_BUCKETS.has('self-improve:jira-status-report')).toBe(true);+ expect(selectPoisonedBuckets({ 'self-improve:branch-cleanup': {}, 'auto-fix': {} })).toEqual(['auto-fix']);+ expect(selectPoisonedBuckets(null)).toEqual([]);+ expect(selectPoisonedBuckets([])).toEqual([]);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex d70df126bf..abc27f6bd3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -181,6 +181,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |+| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` — the run-window commit probe: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. || `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. || `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. |diff --git a/server/lib/gitCommitProbe.js b/server/lib/gitCommitProbe.jsnew file mode 100644index 0000000000..89f66d8acf--- /dev/null+++ b/server/lib/gitCommitProbe.js@@ -0,0 +1,54 @@+/**+ * Run-window commit probe — the single machine-checkable "did this run commit+ * anything?" primitive (#3637).+ *+ * It replaced the `[task-<id>]` commit-marker grep that used to live in+ * `agentRunTracking.js`: nothing in PortOS ever emitted that marker (the root+ * CLAUDE.md requires human-readable commit subjects, so stamping an opaque task+ * id into every permanent commit was never an option), so the criterion was+ * unsatisfiable and scored every ordinary code-editing run a failure.+ *+ * Lives in `server/lib/` rather than under `services/agentTuiSpawning/` because+ * four separate agent paths — finalize's success-criteria evaluation, run+ * completion, runner completion, and orphan recovery — all need the same+ * answer, and none of them should have to reach into the TUI spawner for it.+ */++import { execGit } from './execGit.js';++/**+ * Count commits reachable from HEAD whose COMMITTER date falls inside the run+ * window. `git rev-list --since` filters on committer date, which is what makes+ * this a usable "did this agent commit anything?" probe: commits the agent+ * created (or rewrote via rebase) are stamped now, while commits merely pulled+ * in from the remote keep the committer date they were written with — usually+ * before the run started, so they don't count as this agent's work.+ *+ * Non-throwing: a repo with no commits yet (`rev-list HEAD` fails), a missing,+ * detached, or broken checkout, or a git timeout all return 0.+ *+ * @param {string} workspacePath+ * @param {number} sinceMs - epoch ms marking the start of the run window+ * @returns {Promise<number>}+ */+export async function commitsSince(workspacePath, sinceMs) {+ if (!workspacePath || typeof workspacePath !== 'string') return 0;+ if (!Number.isFinite(sinceMs)) return 0;+ const since = new Date(sinceMs).toISOString();+ // `ignoreExitCode` so a repo with no HEAD resolves to a non-zero exit we can+ // read as "no commits" rather than rejecting — the house convention for+ // probe-shaped git calls (see git.js `isRepo` / `getRemote`).+ const result = await execGit(['rev-list', '--count', `--since=${since}`, 'HEAD'], workspacePath, { ignoreExitCode: true })+ .catch(() => null);+ if (!result || result.exitCode !== 0) return 0;+ const count = parseInt(result.stdout.trim(), 10);+ return Number.isFinite(count) ? count : 0;+}++/**+ * Boolean form of `commitsSince` — "did this run leave a commit behind?".+ * The shape every agent-completion path actually wants.+ */+export async function committedDuringRun(workspacePath, sinceMs) {+ return (await commitsSince(workspacePath, sinceMs)) > 0;+}diff --git a/server/lib/gitCommitProbe.test.js b/server/lib/gitCommitProbe.test.jsnew file mode 100644index 0000000000..5f84f01d0b--- /dev/null+++ b/server/lib/gitCommitProbe.test.js@@ -0,0 +1,64 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./execGit.js', () => ({ execGit: vi.fn() }));++import { execGit } from './execGit.js';+import { commitsSince, committedDuringRun } from './gitCommitProbe.js';++const SINCE = Date.parse('2026-08-08T18:23:30.000Z');++beforeEach(() => vi.clearAllMocks());++describe('commitsSince (#3637)', () => {+ it('counts commits inside the run window, scoped by committer date', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 0, stdout: '2\n', stderr: '' });+ expect(await commitsSince('/tmp/ws', SINCE)).toBe(2);+ expect(execGit).toHaveBeenCalledWith(+ ['rev-list', '--count', '--since=2026-08-08T18:23:30.000Z', 'HEAD'],+ '/tmp/ws',+ { ignoreExitCode: true }+ );+ });++ it('is 0 when nothing was committed during the run', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' });+ expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);+ });++ // A repo with no commits yet makes `rev-list HEAD` exit non-zero with an empty+ // stdout — parsing that as work would launder a no-op run into a success.+ it('is 0 on a non-zero git exit (no HEAD / broken checkout)', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 128, stdout: '', stderr: 'bad revision' });+ expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);+ });++ it('is 0 (never throws) when execGit rejects', async () => {+ vi.mocked(execGit).mockRejectedValue(new Error('timed out'));+ expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);+ });++ it('is 0 for unparseable output', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 0, stdout: 'not-a-number\n', stderr: '' });+ expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);+ });++ it('is 0 for a bad path or a non-finite timestamp without touching git', async () => {+ expect(await commitsSince(null, SINCE)).toBe(0);+ expect(await commitsSince('', SINCE)).toBe(0);+ expect(await commitsSince('/tmp/ws', undefined)).toBe(0);+ expect(await commitsSince('/tmp/ws', NaN)).toBe(0);+ expect(execGit).not.toHaveBeenCalled();+ });+});++describe('committedDuringRun (#3637)', () => {+ it('is true when the run left at least one commit behind', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 0, stdout: '1\n', stderr: '' });+ expect(await committedDuringRun('/tmp/ws', SINCE)).toBe(true);+ });++ it('is false when the run committed nothing', async () => {+ vi.mocked(execGit).mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' });+ expect(await committedDuringRun('/tmp/ws', SINCE)).toBe(false);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 83476d3bd8..6c6140caca 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -173,6 +173,7 @@ export * from './execGit.js';export * from './ffmpeg.js';export * from './ffmpegRenderGuard.js';export * from './gitArgs.js';+export * from './gitCommitProbe.js';export * from './gitForge.js';export * from './gitOutputParsers.js';export * from './gitRemote.js';diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex 0529f6d212..a4b683a3f1 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -227,7 +227,6 @@ describe('every cwd-passing spawn pins PWD', () => {// pins, so they need no call of their own.const DELEGATES = new Map([['services/appBuilder.js', 'bufferedSpawn'],- ['services/agentRunTracking.js', 'bufferedSpawn'],]);// Files that pin by inlining the assignment instead of calling the shareddiff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex ba4fd065a2..0e0831908b 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -773,6 +773,8 @@ export async function spawnDirectly({completionReason: terminatedByUser ? 'user-terminated' : undefined,workspacePath,prExpected: directAgentOwnsPR,+ // The run window the commit criterion is evaluated against (#3637).+ startedAt: agentData?.startedAt ?? null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;} finally {diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 188429b6d3..0abb0edc57 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -32,7 +32,8 @@ import { resolveProviderBench } from '../lib/providerCooldown.js';import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';-import { completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';+import { completeAgentRun } from './agentRunTracking.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';import { canRunTaskOutputHookWithoutPayload, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';import { processAgentCompletion } from './agentCompletion.js';import { extractSimplifySummaries } from './agentSummaryExtraction.js';@@ -62,16 +63,28 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi* Evaluate a completed autonomous run against its DECLARED success criteria* (issue #2344). Distinct from the runner's exit-code `success`: it answers* "did the run actually produce the work it was supposed to?" using the one- * machine-checkable criterion the CoS already relies on — a `[task-<id>]` commit.+ * machine-checkable criterion the CoS can actually observe — did the run leave+ * a commit behind inside its own run window (`committedDuringRun`)?+ *+ * That probe replaced a task-id commit-marker grep in #3637. NOTHING ever+ * emitted that marker — no prompt, template, or slashdo command asked an agent+ * to stamp a task id into a commit subject, and the root CLAUDE.md forbids+ * exactly that shape of subject line — so the criterion was unsatisfiable and+ * stamped `validationPassed: false` on every ordinary code-editing run,+ * poisoning the task-learning buckets it feeds.** Returns a null sentinel when NO criterion is declared (interactive/user tasks,- * user-terminated runs, or a run with no task id / workspace to validate- * against), so downstream telemetry never conflates "not declared" with+ * user-terminated runs, or a run with no task id / workspace / run window to+ * validate against), so downstream telemetry never conflates "not declared" with* "declared and failed". For autonomous tasks it verifies the commit on BOTH* success and failure — a clean exit that committed nothing is an honest miss,- * and that is exactly the signal task-learning wants. `checkForTaskCommit` is- * git-repo-gated, off the event loop, and hard-timeout-bounded, so a non-repo- * workspace or a hung git degrades to "no commit" rather than stalling finalize.+ * and that is exactly the signal task-learning wants. `committedDuringRun` is+ * non-throwing and hard-timeout-bounded, so a non-repo workspace or a hung git+ * degrades to "no commit" rather than stalling finalize.+ *+ * `startedAt` (epoch ms) bounds the window. A non-finite value means we can't+ * tell this run's commits from anything already in the repo, so the criterion is+ * undeclared (null) rather than a manufactured `false`.** `hookResult` is the programmatic-I/O output-hook result (from* `dispatchTaskOutputHook`), which finalizeAgent resolves BEFORE calling this so@@ -79,7 +92,7 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi* runner's exit-code verdict that hook result is weighed against. Both are* absent/null for every other task shape.*/-export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success = false, hookResult = null }) {+export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt = null, success = false, hookResult = null }) {if (terminatedByUser) return null;const taskType = task?.taskType || 'user';// The SCHEDULED type (`metadata.analysisType`) if any, else the queue category —@@ -92,7 +105,7 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac// pre-empted by the `!workspacePath` bail below (a hook that already ran and// threw is a real verdict even if the worktree is gone). Their prompts// explicitly FORBID committing or opening a PR (the worktree is discarded), so- // the `[task-<id>]` commit check would mark every correct run a failure (#2700).+ // the commit criterion would mark every correct run a failure (#2700).// Judging them purely by exit code instead is also wrong: an exit-0 run whose// `.agent-done` sentinel was missing/malformed, or whose hook threw, produced// nothing usable and must be recorded as the failure it is (#2727).@@ -102,7 +115,7 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac// Interactive/user tasks declare no machine-checkable criterion; neither does// a run missing the task id or workspace needed to validate.if (taskType === 'user' || !task?.id || !workspacePath) return null;- // Pipeline/media tasks deliver artifacts, not a `[task-<id>]` commit — the+ // Pipeline/media tasks deliver artifacts, not a commit — the// commit criterion doesn't apply, so don't mislabel a clean artifact run as a// validation miss (which would also pollute the correlation window). null =// no commit criterion declared for this task shape. Unlike programmatic-I/O@@ -112,7 +125,7 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac// gh/git/external COORDINATOR task types (NON_COMMITTING_COORDINATOR_TASK_TYPES in// taskTypeHooks.js — branch-reconcile/issue-reconcile/branch-cleanup/jira-status-report)// deliver their work as a side effect — a merged PR, a resolved conflict, a deleted- // branch, a posted report — and by design NEVER produce a `[task-<id>]` commit. Because+ // branch, a posted report — and by design NEVER produce a commit. Because// their workspacePath IS set (the app's live checkout), the commit check above would// return false on every SUCCESSFUL run and drive their learning bucket to ~0% (#2696) —// the same artifact #2700 fixed for the programmatic-I/O reasoning run. They register no@@ -129,7 +142,10 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac// so the same type still gets its commit criterion on a `plan`-tracker app// where it legitimately commits PLAN.md items (#3273).if (declaresNoCommitCriterion(task)) return null;- return await checkForTaskCommit(task.id, workspacePath);+ // No usable run window means no way to attribute a commit to THIS run — the+ // sentinel, not a false verdict (#3637).+ if (!Number.isFinite(startedAt)) return null;+ return await committedDuringRun(workspacePath, startedAt);}/**@@ -497,7 +513,20 @@ export async function finalizeAgent({completionReason,workspacePath = null,prExpected = false,+ startedAt = null,}) {+ // The run window the commit criterion is evaluated against (#3637). Callers+ // that don't track their own start timestamp still know how long the run took,+ // and `duration` is measured from the same instant, so derive it — a missing+ // window would otherwise leave every such path permanently undeclared.+ //+ // `duration > 0`, not `>= 0`: the spawn-rejected path reports a zero-length+ // run because the agent never started. A window that cannot contain a commit+ // is not evidence of one, so it stays the null sentinel ("no criterion+ // evaluated") rather than recording a run that never happened as a miss.+ const runStartedAt = Number.isFinite(startedAt)+ ? startedAt+ : (Number.isFinite(duration) && duration > 0 ? Date.now() - duration : null);// #3358: a run whose task shape promised a PR is not successful until the// forge confirms one exists. Runs BEFORE the completion verdict is derived so// every downstream write (task status, learning telemetry, the "Completed@@ -568,7 +597,7 @@ export async function finalizeAgent({// exit-code `success`, so task-learning telemetry can distinguish "ran clean// but produced nothing" from a genuine success. Best-effort — a validation// check failure must never block finalize (falls back to the null sentinel).- const validationPassed = await evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success, hookResult })+ const validationPassed = await evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt: runStartedAt, success, hookResult }).catch(err => {emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });return null;diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 9fe245f2f6..25ecd56665 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -62,8 +62,10 @@ vi.mock('./agentErrorAnalysis.js', () => ({}));const completeAgentRunMock = vi.fn(async () => null);+vi.mock('../lib/gitCommitProbe.js', () => ({+ committedDuringRun: vi.fn(async () => true),+}));vi.mock('./agentRunTracking.js', () => ({- checkForTaskCommit: vi.fn(async () => true),createAgentRun: vi.fn(),completeAgentRun: (...args) => completeAgentRunMock(...args),}));diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 53a1c73e58..eb89580be9 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -57,8 +57,10 @@ vi.mock('./agentErrorAnalysis.js', async (importOriginal) => ({resolveFailedTaskUpdate: vi.fn(async () => ({ status: 'pending', metadata: {} })),resolveTypeFailureSignal: vi.fn(() => ({ record: 'skip' })),}));+vi.mock('../lib/gitCommitProbe.js', () => ({+ committedDuringRun: vi.fn(async () => false),+}));vi.mock('./agentRunTracking.js', () => ({- checkForTaskCommit: vi.fn(async () => false),createAgentRun: vi.fn(),completeAgentRun: vi.fn(async () => null),}));diff --git a/server/services/agentFinalization.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.jsindex 9cdcae7bfd..5610410946 100644--- a/server/services/agentFinalization.successCriteria.test.js+++ b/server/services/agentFinalization.successCriteria.test.js@@ -1,7 +1,7 @@/*** Tests for `evaluateSuccessCriteria` (issue #2344) — the success-criteria* validation verdict finalizeAgent stamps onto every completion, distinct from- * the runner's exit-code `success`. The `[task-<id>]` commit check is mocked so+ * the runner's exit-code `success`. The run-window commit probe is mocked so* these run without git; the focus is the null-sentinel gating (no criterion* declared vs declared-and-checked).*/@@ -9,51 +9,58 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';vi.mock('./agentRunTracking.js', () => ({- checkForTaskCommit: vi.fn(),- // finalizeAgent's other imports from this module — stubbed so the graph loads.+ // finalizeAgent's imports from this module — stubbed so the graph loads.createAgentRun: vi.fn(),completeAgentRun: vi.fn(),}));+vi.mock('../lib/gitCommitProbe.js', () => ({+ committedDuringRun: vi.fn(),+}));import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout } from './agentFinalization.js';-import { checkForTaskCommit } from './agentRunTracking.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';++// The run window every commit-criterion assertion below is evaluated against+// (#3637). A criterion-declaring call MUST pass one — without a window there is+// no way to attribute a commit to this run, and the verdict is the null sentinel.+const STARTED_AT = Date.parse('2026-08-09T00:00:00.000Z');describe('evaluateSuccessCriteria (#2344)', () => {beforeEach(() => vi.clearAllMocks());it('returns null (no declared criterion) for interactive/user tasks', async () => {expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'user' }, workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('returns null for a user-terminated run — no criterion was evaluated', async () => {const out = await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' }, terminatedByUser: true, workspacePath: '/w' });expect(out).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('returns null when there is no task id or no workspace to validate against', async () => {expect(await evaluateSuccessCriteria({ task: { taskType: 'internal' }, workspacePath: '/w' })).toBeNull();expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' } })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('returns null for pipeline/media tasks (they deliver artifacts, not a commit)', async () => {expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal', metadata: { pipeline: true } }, workspacePath: '/w' })).toBeNull();expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal', metadata: { mediaJob: true } }, workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('never applies the commit criterion to a programmatic-I/O task (#2700)', async () => {// A layered-intelligence run is explicitly told NOT to commit or open a PR: it// writes `.agent-done` and its output hook does the filing. Checking for a- // `[task-<id>]` commit would stamp validationPassed:false on every correct run —+ // commit would stamp validationPassed:false on every correct run —// and since a declared verdict OVERRIDES the runner's exit code in task-learning,// that recorded successful LI runs as failures and drove the type's success rate// to ~0.const task = { id: 't1', taskType: 'internal', metadata: { analysisType: 'layered-intelligence', selfImprovement: true } };await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true, hookResult: { ran: true, outcome: { action: 'filed' } } });- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});});@@ -75,36 +82,36 @@ describe('evaluateSuccessCriteria — tracker-filing tasks (#3273)', () => {it('declares NO criterion when worktreeChangesExpected is false (forge tracker)', async () => {expect(await evaluateSuccessCriteria({ task: uxTask(false), workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('accepts the string form the TASKS.md round-trip produces', async () => {expect(await evaluateSuccessCriteria({ task: uxTask('false'), workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('still applies the commit criterion when the flag is TRUE (plan tracker)', async () => {- checkForTaskCommit.mockResolvedValue(true);- expect(await evaluateSuccessCriteria({ task: uxTask(true), workspacePath: '/w' })).toBe(true);- expect(checkForTaskCommit).toHaveBeenCalledWith('t1', '/w');+ committedDuringRun.mockResolvedValue(true);+ expect(await evaluateSuccessCriteria({ task: uxTask(true), workspacePath: '/w', startedAt: STARTED_AT })).toBe(true);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);});it('still applies the commit criterion when the flag is ABSENT', async () => {- checkForTaskCommit.mockResolvedValue(false);- expect(await evaluateSuccessCriteria({ task: uxTask(undefined), workspacePath: '/w' })).toBe(false);- expect(checkForTaskCommit).toHaveBeenCalledWith('t1', '/w');+ committedDuringRun.mockResolvedValue(false);+ expect(await evaluateSuccessCriteria({ task: uxTask(undefined), workspacePath: '/w', startedAt: STARTED_AT })).toBe(false);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);});it('retro-fixes reference-watch on a forge tracker (the same latent artifact)', async () => {const task = { id: 't2', taskType: 'internal', metadata: { analysisType: 'reference-watch', worktreeChangesExpected: false } };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('resolves the archived-agent projection the same way as the live task', async () => {const task = { id: 't3', taskType: 'internal', metadata: { taskAnalysisType: 'ux', worktreeChangesExpected: false } };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w' })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('does NOT let the flag exempt a non-tracker-filing type from its commit criterion', async () => {@@ -113,10 +120,10 @@ describe('evaluateSuccessCriteria — tracker-filing tasks (#3273)', () => {// idle-complete clean-tree gate, not to disable success validation. Ungated,// a `security` run that exited 0 having committed nothing would be recorded// as a pass instead of the honest miss it is.- checkForTaskCommit.mockResolvedValue(false);+ committedDuringRun.mockResolvedValue(false);const task = { id: 't4', taskType: 'internal', metadata: { analysisType: 'security', worktreeChangesExpected: false } };- expect(await evaluateSuccessCriteria({ task, workspacePath: '/w' })).toBe(false);- expect(checkForTaskCommit).toHaveBeenCalledWith('t4', '/w');+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', startedAt: STARTED_AT })).toBe(false);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);});});@@ -147,7 +154,7 @@ describe('evaluateSuccessCriteria — programmatic-I/O criterion (#2727)', () =>it('records an exit-0 run whose hook accepted the payload as a SUCCESS — no commit required', async () => {const hookResult = { ran: true, outcome: { app: 'a1', action: 'filed', reason: null } };expect(await evaluateSuccessCriteria({ task: liTask, workspacePath: '/w', success: true, hookResult })).toBe(true);- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('treats benign hook reasons (no-proposal, duplicate, scope-suppressed) as a SUCCESS', async () => {@@ -196,7 +203,7 @@ describe('evaluateSuccessCriteria — programmatic-I/O criterion (#2727)', () =>expect(await evaluateSuccessCriteria({task, workspacePath: '/w', success: true, hookResult: { ran: true, threw: true }})).toBe(false);- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});});@@ -298,33 +305,56 @@ describe('withOutputHookTimeout (#2727)', () => {});});-describe('evaluateSuccessCriteria — commit criterion (#2344)', () => {+/**+ * The commit criterion (#2344), rebuilt on the run-window probe (#3637). The old+ * criterion grepped for a task-id commit subject that NOTHING ever emitted,+ * so it was unsatisfiable: every ordinary code-editing run recorded+ * `validationPassed: false` regardless of what it did, and — because a declared+ * verdict overrides the exit code in task-learning — its bucket filled with+ * fabricated failures. These two cases are the whole fix: a run that committed+ * inside its own window passes, a run that committed nothing fails.+ */+describe('evaluateSuccessCriteria — commit criterion (#2344, #3637)', () => {beforeEach(() => vi.clearAllMocks());+ it('passes an autonomous code run that COMMITTED during its window', async () => {+ committedDuringRun.mockResolvedValueOnce(true);+ expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' }, workspacePath: '/w', startedAt: STARTED_AT })).toBe(true);+ // Probed against the run's own window, NOT the whole repo history — a commit+ // another agent pushed before this run began is not this run's work.+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);+ });++ it('fails an autonomous code run that committed NOTHING (an honest miss, not null)', async () => {+ committedDuringRun.mockResolvedValueOnce(false);+ expect(await evaluateSuccessCriteria({ task: { id: 't2', taskType: 'internal' }, workspacePath: '/w', startedAt: STARTED_AT })).toBe(false);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);+ });+it('still applies the commit criterion to a NON-programmatic self-improvement task', async () => {// The exemption is keyed on the taskTypeHooks registry, not on selfImprovement —// an ordinary self-improve task still commits and must still be checked.- checkForTaskCommit.mockResolvedValueOnce(true);+ committedDuringRun.mockResolvedValueOnce(true);const task = { id: 't1', taskType: 'internal', metadata: { analysisType: 'ui', selfImprovement: true } };- expect(await evaluateSuccessCriteria({ task, workspacePath: '/w' })).toBe(true);- expect(checkForTaskCommit).toHaveBeenCalledWith('t1', '/w');+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', startedAt: STARTED_AT })).toBe(true);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);});- it('returns the commit-check verdict for an autonomous code task (criterion declared)', async () => {- checkForTaskCommit.mockResolvedValueOnce(true);- expect(await evaluateSuccessCriteria({ task: { id: 't1', taskType: 'internal' }, workspacePath: '/w' })).toBe(true);- expect(checkForTaskCommit).toHaveBeenCalledWith('t1', '/w');-- // A clean run that produced NO commit is an honest miss (false, not null).- checkForTaskCommit.mockResolvedValueOnce(false);- expect(await evaluateSuccessCriteria({ task: { id: 't2', taskType: 'internal' }, workspacePath: '/w' })).toBe(false);+ it('declares NO criterion (null) when the run window is missing or unusable', async () => {+ // Without a window there is no way to attribute a commit to THIS run. The+ // sentinel — never a manufactured `false`, which task-learning would treat as+ // a real failure and let override the exit code.+ for (const startedAt of [undefined, null, NaN, 'not-a-date']) {+ expect(await evaluateSuccessCriteria({ task: { id: 't3', taskType: 'internal' }, workspacePath: '/w', startedAt })).toBeNull();+ }+ expect(committedDuringRun).not.toHaveBeenCalled();});});/*** gh/git COORDINATOR task types (#2696): branch-reconcile / issue-reconcile drive* their work through git+gh in the app's LIVE checkout (workspacePath IS set) and never- * produce a `[task-<id>]` commit, so the commit criterion scored every successful run a+ * produce a commit at all, so the commit criterion scored every successful run a* failure and drove their learning bucket to ~0% — the same artifact #2700 fixed for the* programmatic-I/O reasoning run. They must declare NO commit criterion (fall back to the* exit code), exactly like pipeline/media jobs.@@ -334,12 +364,12 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()it('declares NO commit criterion for every non-committing coordinator type', async () => {// The structurally-no-commit coordinators: they run in the live checkout and deliver a- // git/gh/external side effect, never a [task-<id>] commit.+ // git/gh/external side effect, never a commit.for (const analysisType of ['branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report']) {const task = { id: 't1', taskType: 'internal', metadata: { analysisType } };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBeNull();}- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('declares NO commit criterion for a PR follow-up (review-loop or merge-only)', async () => {@@ -354,18 +384,18 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()const task = { id: 'sys-rl-1', taskType: 'internal', metadata };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBeNull();}- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('STILL commit-checks committing self-improve types (jira-sprint-manager, do-replan)', async () => {// jira-sprint-manager commits + opens MRs; do-replan commits PLAN.md edits — their commit// criterion is real, so exempting them would MASK genuine failures. Must stay checked.for (const analysisType of ['jira-sprint-manager', 'do-replan']) {- checkForTaskCommit.mockResolvedValueOnce(true);+ committedDuringRun.mockResolvedValueOnce(true);const task = { id: 't1', taskType: 'internal', metadata: { analysisType, selfImprovement: true } };- expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBe(true);+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', startedAt: STARTED_AT, success: true })).toBe(true);}- expect(checkForTaskCommit).toHaveBeenCalledTimes(2);+ expect(committedDuringRun).toHaveBeenCalledTimes(2);});it('exempts the ARCHIVED coordinator shape (metadata.taskAnalysisType) (#2696 codex)', async () => {@@ -373,7 +403,7 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()// the archived agent shape too (agentLifecycle stamps taskAnalysisType).const task = { id: 't4', taskType: 'internal', metadata: { taskAnalysisType: 'branch-cleanup' } };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('exempts a coordinator typed on taskType alone, not just metadata.analysisType', async () => {@@ -381,16 +411,16 @@ describe('evaluateSuccessCriteria — gh/git coordinator exemption (#2696)', ()// with the scheduled type at the top level is exempted the same way.const task = { id: 't2', taskType: 'branch-reconcile' };expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBeNull();- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();});it('does NOT exempt accessibility — it is a fixing task that DOES commit (#2696 scope)', async () => {// accessibility's prompt ends "Test and commit changes": it makes code changes in a// worktree and commits, so its commit criterion is real and its 0% (if any) is a// genuine agent failure, NOT the coordinator artifact. Must stay commit-checked.- checkForTaskCommit.mockResolvedValueOnce(false);+ committedDuringRun.mockResolvedValueOnce(false);const task = { id: 't3', taskType: 'internal', metadata: { analysisType: 'accessibility', selfImprovement: true } };- expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', success: true })).toBe(false);- expect(checkForTaskCommit).toHaveBeenCalledWith('t3', '/w');+ expect(await evaluateSuccessCriteria({ task, workspacePath: '/w', startedAt: STARTED_AT, success: true })).toBe(false);+ expect(committedDuringRun).toHaveBeenCalledWith('/w', STARTED_AT);});});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 25e374467f..a02e7709d3 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -49,7 +49,8 @@ import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';import { determineLane, acquire, release } from './executionLanes.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';-import { createAgentRun, checkForTaskCommit } from './agentRunTracking.js';+import { createAgentRun } from './agentRunTracking.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';@@ -488,7 +489,7 @@ async function runAgentSpawn(task) {taskQuotaBurnLimitingResetAt: Number(task.metadata?.quotaBurnLimitingResetAt) || null,// Same reason as taskLiProposal — a hand-picked projection, so this must be// listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it- // to decide whether a run declared a `[task-<id>]` commit criterion at all,+ // to decide whether a run declared a commit criterion at all,// and taskLearning's history backfill re-processes the ARCHIVED agent shape// through that same predicate. Without the projection an archived// tracker-filing run (reference-watch/ux on a github/gitlab/jira app) looks@@ -920,7 +921,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// cleanup), so the worktree is still on disk, branch and all — without it// the retry builds a fresh tree off the default branch and redoes work// that is sitting right there.- await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata });+ await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata, agentStartedAt: cosAgent.startedAt });// If orphan recovery settled the task into a terminal `blocked` state (retry budget// exhausted), the local completion already recorded the proposal failure — so stamp// the LI failure verdict here too (#2779, codex P2) or the originating peer would@@ -998,11 +999,14 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationoutputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');}- // Post-execution validation: check for task commit even if exit code is non-zero+ // Post-execution validation: a non-zero exit that still left a commit inside+ // the run's own window DID the work (#3637 — the probe is the window, not a+ // task-id commit marker no agent ever emitted).+ const runStartedAt = Date.parse(agent.startedAt);let effectiveSuccess = success;if (!effectiveSuccess && task?.id) {const workspacePath = agent.workspacePath || ROOT_DIR;- const commitFound = await checkForTaskCommit(task.id, workspacePath);+ const commitFound = await committedDuringRun(workspacePath, runStartedAt);if (commitFound) {emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });effectiveSuccess = true;@@ -1084,6 +1088,8 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationisTruthyMetaFn: isTruthyMeta,workspacePath: agent.workspacePath || null,prExpected: runnerAgentOwnsPR,+ // The run window the commit criterion is evaluated against (#3637).+ startedAt: Number.isFinite(runStartedAt) ? runStartedAt : null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;} catch (err) {diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex 7bd878de3c..e3ccf5ae63 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -42,7 +42,6 @@ vi.mock('./cosAgentLifecycle.js', () => ({vi.mock('./agentRunTracking.js', () => ({createAgentRun: vi.fn().mockResolvedValue(undefined),- checkForTaskCommit: vi.fn().mockResolvedValue(false),completeAgentRun: vi.fn().mockResolvedValue(undefined),}));diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex ef20c4f5c4..bbaa3b13da 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -316,9 +316,13 @@ describe('agentLifecycle — guard wiring', () => {// disk when the task is requeued. Without the dead agent's metadata,// handleOrphanedTask can't tell the retry what to resume, and it builds a fresh// worktree off the default branch and redoes work sitting right there.+ //+ // `startedAt` rides along for the same class of reason (#3637): it is the window+ // the orphan path's commit probe needs, and without it the probe is skipped and a+ // run that DID commit before dying is requeued as if it had produced nothing.it('the post-restart recovery path hands the dead agent’s metadata to the retry handler', () => {const body = recoveryBranchSource();- expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata\s*\}\)/);+ expect(body).toMatch(/handleOrphanedTask\([^)]*\{\s*agentMetadata: cosAgent\.metadata,\s*agentStartedAt: cosAgent\.startedAt\s*\}\)/);});});diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex da61a4a458..562cf7d040 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -28,7 +28,8 @@ import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleimport { isRetryHeld, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';import { syncRunnerAgents } from './agentRunnerSync.js';import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';-import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';+import { completeAgentRun } from './agentRunTracking.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { readHostShutdownMarker, clearHostShutdownMarker, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';@@ -669,7 +670,9 @@ export async function cleanupOrphanedAgents() {// its output.txt tail (capped since #3498, but not free), and the// worktree fields the resume pointer needs are stamped once at// registerAgent and never mutated.- orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata });+ // `startedAt` rides along too — it's the window the commit probe in+ // handleOrphanedTask needs to tell this run's commits from the repo's.+ orphanedTaskIds.push({ taskId: agent.taskId, agentId: agent.id, agentMetadata: agent.metadata, agentStartedAt: agent.startedAt });}}}@@ -697,9 +700,10 @@ export async function cleanupOrphanedAgents() {// (see handleOrphanedTask). Runs AFTER cleanupAgentWorktree above so the resume// pointer reflects what actually survived — a dirty tree aborts removal, leaving// the whole worktree in place.- for (const { taskId, agentId, agentMetadata } of orphanedTaskIds) {+ for (const { taskId, agentId, agentMetadata, agentStartedAt } of orphanedTaskIds) {await handleOrphanedTask(taskId, agentId, getTaskById, {agentMetadata,+ agentStartedAt,// `|| null`, not a bare boolean: a plain `false` would hard-override the// per-agent breadcrumb fallback, leaving this — the path that handles// essentially all boot recovery — with the marker as its ONLY signal. The@@ -748,13 +752,16 @@ export async function cleanupOrphanedAgents() {* @param {object} [options.agentMetadata] - the dead agent's registered metadata* (`isWorktree` / `sourceWorkspace` / `worktreeBranch` / `workspacePath`), used* to work out whether its branch or worktree is worth resuming.+ * @param {string|number|null} [options.agentStartedAt] - when the dead run began. It is+ * the window for the commit probe below; without it the probe is skipped rather than+ * run unbounded, which would credit this task with any commit already in the repo (#3637).* @param {boolean|null} [options.interrupted] - the run died because PortOS itself* was restarted, not because the agent failed. Such a run is requeued immediately* WITHOUT charging orphan-retry budget or arming the orphan cooldown — see the* retry-budget note below (#3202). Pass it when the caller knows (the orphan sweep* reads the host-shutdown marker); leave it null to derive from `agentMetadata`.*/-export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null, interrupted = null } = {}) {+export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentMetadata = null, agentStartedAt = null, interrupted = null } = {}) {// Callers that watched the agent die (the orphan sweep, which reads the// host-shutdown marker) say so explicitly. The ones that didn't —// `resetOrphanedTasks`, post-restart completion recovery — fall back to the@@ -828,8 +835,13 @@ export async function handleOrphanedTask(taskId, agentId, getTaskByIdFn, { agentreturn;}- // Check if the agent actually committed work before treating as orphaned- const commitFound = await checkForTaskCommit(taskId, agentMetadata?.workspacePath || ROOT_DIR);+ // Check if the agent actually committed work before treating as orphaned.+ // Scoped to the dead run's OWN window (#3637): the retired task-id commit marker+ // was never emitted by anything, and an unbounded `git log` would credit this+ // task with any commit in the repo — including another agent's.+ const orphanRunStartedAt = Date.parse(agentStartedAt);+ const commitFound = Number.isFinite(orphanRunStartedAt)+ && await committedDuringRun(agentMetadata?.workspacePath || ROOT_DIR, orphanRunStartedAt);if (commitFound) {emitLog('info', `✅ Orphaned agent ${agentId} actually completed work - commit found for task ${taskId}`, { taskId, agentId });await updateTask(taskId, { status: 'completed' }, task.taskType || 'user');diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 4f1220b250..1de1d1986d 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -53,8 +53,10 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn()}));+vi.mock('../lib/gitCommitProbe.js', () => ({+ committedDuringRun: vi.fn().mockResolvedValue(false),+}));vi.mock('./agentRunTracking.js', () => ({- checkForTaskCommit: vi.fn().mockResolvedValue(false),completeAgentRun: vi.fn().mockResolvedValue(undefined),}));@@ -109,7 +111,8 @@ import { updateTask, addTask, getTaskById } from './cos.js';import { pauseAgentViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';-import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';+import { completeAgentRun } from './agentRunTracking.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {@@ -894,16 +897,31 @@ describe('orphan retries resume what the dead run left behind', () => {});it('checks for completed work in the orphaned agent’s actual workspace', async () => {- checkForTaskCommit.mockResolvedValueOnce(true);+ committedDuringRun.mockResolvedValueOnce(true);getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {agentMetadata: { workspacePath: '/example-app' },+ agentStartedAt: '2026-08-09T00:00:00.000Z',});- expect(checkForTaskCommit).toHaveBeenCalledWith('task-1', '/example-app');+ expect(committedDuringRun).toHaveBeenCalledWith('/example-app', Date.parse('2026-08-09T00:00:00.000Z'));expect(updateTask).toHaveBeenCalledWith('task-1', { status: 'completed' }, 'user');});++ // Without a run window there is nothing to attribute a commit to — probing an+ // unbounded `git log` would credit this task with any commit already in the+ // repo, including another agent's, and complete a task that did nothing (#3637).+ it('skips the commit probe entirely when the dead run has no start time', async () => {+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', status: 'in_progress', metadata: {} });++ await handleOrphanedTask('task-1', 'agent-dead', getTaskById, {+ agentMetadata: { workspacePath: '/example-app' },+ });++ expect(committedDuringRun).not.toHaveBeenCalled();+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');+ });});// The crash-recovery half of the retry hold (#3373). finalizeAgent left the task@@ -922,7 +940,7 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()vi.clearAllMocks();getAgents.mockResolvedValue([]);resolveTaskResumePatch.mockResolvedValue({});- checkForTaskCommit.mockResolvedValue(false);+ committedDuringRun.mockResolvedValue(false);activeAgents.clear();runnerAgents.clear();});@@ -930,7 +948,7 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()// `clearAllMocks` keeps implementations, so hand the commit check back in the// state the suites after this one expect (no queued verdict).afterEach(() => {- checkForTaskCommit.mockReset();+ committedDuringRun.mockReset();});it('flips the held task to pending with the resume pointer and drops the marker', async () => {@@ -969,11 +987,11 @@ describe('the orphan sweep finishes an interrupted retry transition (#3373)', ()// completing the task on that evidence would discard the granted retry.it('does not let the commit check complete a held task', async () => {getTaskById.mockResolvedValue(heldTask());- checkForTaskCommit.mockResolvedValue(true);+ committedDuringRun.mockResolvedValue(true);await handleOrphanedTask('task-1', 'agent-dead', getTaskById, { agentMetadata: null });- expect(checkForTaskCommit).not.toHaveBeenCalled();+ expect(committedDuringRun).not.toHaveBeenCalled();expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'pending' }), 'user');});diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex f47e0dbb87..831545f51a 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -9,8 +9,8 @@ import { writeFile, mkdir } from 'fs/promises';import { v4 as uuidv4 } from '../lib/uuid.js';import { recordSession } from './usage.js';import { recordCompletedRunUsage } from './usageReconciler.js';-import { bufferedSpawn } from '../lib/bufferedSpawn.js';-import { atomicWrite, ensureDir, pathExists, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { committedDuringRun } from '../lib/gitCommitProbe.js';+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';const RUNS_DIR = PATHS.runs;@@ -69,35 +69,6 @@ export async function createAgentRun({ agentId, task, model, provider, workspacereturn { runId, runDir };}-/**- * Check if a commit was made with the task ID.- * Returns true if a recent commit contains [task-{taskId}].- * Returns false if git command fails (not a repo, git not available, etc.)- *- * Async + buffered: `git log` on a large repo can block for 100ms–2s, and this- * runs on the run-completion path of every failed CoS agent run — a `spawnSync`- * here froze all in-flight SSE/socket traffic for that window. `bufferedSpawn`- * runs it off the event loop with a hard timeout (a hung git is treated as- * "no commit found" rather than stalling completion forever).- */-export async function checkForTaskCommit(taskId, workspacePath) {- // Check if it's a git repo first- const gitDir = join(workspacePath, '.git');- if (!(await pathExists(gitDir))) return false;-- const searchPattern = `[task-${taskId}]`;- // --fixed-strings / -F: treat pattern as literal string, not regex. Without- // this, square brackets in `[task-123]` would be parsed as a character class- // and fail to match the literal commit message.- const result = await bufferedSpawn(- 'git',- ['log', '--all', '--oneline', '--fixed-strings', '--grep', searchPattern, '-1'],- { cwd: workspacePath, timeoutMs: 10_000, shell: false },- );- if (!result.success) return false; // non-zero exit, spawn error, or timeout- return result.stdout.trim().length > 0;-}-/*** Complete a run entry with final results.*@@ -120,11 +91,15 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorAmetadata.duration = duration;metadata.exitCode = exitCode;- // Post-execution validation: check for task commit even if exit code is non-zero+ // Post-execution validation: a non-zero exit that nonetheless left a commit+ // behind DID the work (#3637 — the probe is the run window, not a marker in+ // the commit subject, because nothing ever emitted such a marker). The window+ // opens at the run's own startTime, so commits another agent pushed before+ // this run began don't launder it into a success.let success = exitCode === 0;+ const runStartedAt = Date.parse(metadata.startTime);if (!success && metadata.taskId && metadata.workspacePath) {- const commitFound = await checkForTaskCommit(metadata.taskId, metadata.workspacePath);- if (commitFound) {+ if (await committedDuringRun(metadata.workspacePath, runStartedAt)) {console.log(`⚠️ Agent ${metadata.agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${metadata.taskId}`);success = true;}diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex ca734f0bd1..fa6ad4b598 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -644,6 +644,8 @@ export async function spawnTuiAgent({completionReason: reason,workspacePath,prExpected: agentOwnsPR,+ // The run window the commit criterion is evaluated against (#3637).+ startedAt: agentData?.startedAt ?? null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;} finally {diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 5861266f6c..b0e696fe2f 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -91,6 +91,15 @@ vi.mock('./agentState.js', async (importOriginal) => ({unregisterSpawnedAgent: vi.fn(),}));+// ONE execGit double behind BOTH entry points. The commit half of the+// work-evidence probe moved to `lib/gitCommitProbe.js` (#3637), which reaches+// `lib/execGit.js` directly rather than through `git.js`'s re-export — so mocking+// only `git.js` would leave the probe shelling out to real git. Sharing the spy+// keeps every `vi.mocked(gitService.execGit)` override in this file authoritative+// for the probe too.+const { execGitMock } = vi.hoisted(() => ({ execGitMock: vi.fn() }));+vi.mock('../lib/execGit.js', () => ({ execGit: execGitMock }));+vi.mock('./git.js', () => ({// Default: worktree has changes so idle-complete succeeds. Tests that want// to exercise the idle-no-changes failure path override via mockResolvedValueOnce.@@ -99,7 +108,7 @@ vi.mock('./git.js', () => ({// `git rev-list --count --since=…` for the commit half of the work-evidence// probe. Default: zero commits during the run, so a clean tree still fails —// the commit-and-push test overrides this to a non-zero count.- execGit: vi.fn().mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' }),+ execGit: execGitMock,// No owner-matched gh account by default → empty overlay (ambient auth kept).resolveForgeTokenEnv: vi.fn().mockResolvedValue({}),}));diff --git a/server/services/agentTuiSpawning/finalizeHelpers.js b/server/services/agentTuiSpawning/finalizeHelpers.jsindex 55fa27af53..bdd4edc932 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.js@@ -12,6 +12,7 @@ import { join } from 'path';import { writeFile } from 'fs/promises';import * as git from '../git.js';import { readFileTail } from '../../lib/fileUtils.js';+import { commitsSince } from '../../lib/gitCommitProbe.js';import { analyzeAgentFailure } from '../agentErrorAnalysis.js';// Re-exported so this module's existing importers (and its tests) keep their@@ -19,6 +20,12 @@ import { analyzeAgentFailure } from '../agentErrorAnalysis.js';// `getAgent`'s transcript cap needed the same bounded tail read.export { readFileTail };+// Same deal for the run-window commit probe: it moved to lib/gitCommitProbe.js+// (#3637) once finalize's success-criteria evaluation, run completion, and+// orphan recovery all needed the same answer, but this stays its historical+// entry point.+export { commitsSince };+// Tail-read window for raw.txt at failure analysis. analyzeAgentFailure narrows// further (ANSI-stripped, last ~200 lines AND ≤16K chars), so reading the whole// file (which has no upper bound for long-running agents) would reintroduce the@@ -40,32 +47,6 @@ export async function worktreeHasChanges(workspacePath) {return status && !status.clean;}-/**- * Count commits reachable from HEAD whose COMMITTER date falls inside the run- * window. `git rev-list --since` filters on committer date, which is what makes- * this a usable "did this agent commit anything?" probe: commits the agent- * created (or rewrote via rebase) are stamped now, while commits merely pulled- * in from the remote keep the committer date they were written with — usually- * before the run started, so they don't count as this agent's work.- *- * Non-throwing: a repo with no commits yet (`rev-list HEAD` fails), a detached- * or broken checkout, or a git timeout all return 0.- */-export async function commitsSince(workspacePath, sinceMs) {- if (!workspacePath || typeof workspacePath !== 'string') return 0;- if (!Number.isFinite(sinceMs)) return 0;- const since = new Date(sinceMs).toISOString();- // `ignoreExitCode` so a repo with no HEAD resolves to a non-zero exit we can- // read as "no commits" rather than rejecting — the house convention for- // probe-shaped git calls (see git.js `isRepo` / `getRemote`).- const result = await git- .execGit(['rev-list', '--count', `--since=${since}`, 'HEAD'], workspacePath, { ignoreExitCode: true })- .catch(() => null);- if (!result || result.exitCode !== 0) return 0;- const count = parseInt(result.stdout.trim(), 10);- return Number.isFinite(count) ? count : 0;-}-/*** Did this agent leave any evidence of work behind? Dirty tree OR at least one* commit made during the run.diff --git a/server/services/agentTuiSpawning/finalizeHelpers.test.js b/server/services/agentTuiSpawning/finalizeHelpers.test.jsindex 61a28a1b09..39e79b678f 100644--- a/server/services/agentTuiSpawning/finalizeHelpers.test.js+++ b/server/services/agentTuiSpawning/finalizeHelpers.test.js@@ -13,9 +13,15 @@ vi.mock('../git.js', () => ({vi.mock('../agentErrorAnalysis.js', () => ({analyzeAgentFailure: vi.fn(),}));+// The run-window commit probe moved to lib/gitCommitProbe.js (#3637); finalizeHelpers+// re-exports it, so mock it at its new home.+vi.mock('../../lib/gitCommitProbe.js', () => ({+ commitsSince: vi.fn(),+}));import * as git from '../git.js';import { analyzeAgentFailure } from '../agentErrorAnalysis.js';+import { commitsSince as commitsSinceMock } from '../../lib/gitCommitProbe.js';import {readFileTail,worktreeHasChanges,@@ -89,42 +95,13 @@ describe('finalizeHelpers', () => {});});- describe('commitsSince', () => {- const SINCE = Date.parse('2026-08-08T18:23:30.000Z');-- it('counts commits inside the run window, scoped by committer date', async () => {- vi.mocked(git.execGit).mockResolvedValue({ exitCode: 0, stdout: '2\n', stderr: '' });- expect(await commitsSince('/tmp/ws', SINCE)).toBe(2);- expect(git.execGit).toHaveBeenCalledWith(- ['rev-list', '--count', '--since=2026-08-08T18:23:30.000Z', 'HEAD'],- '/tmp/ws',- { ignoreExitCode: true }- );- });-- it('is 0 when nothing was committed during the run', async () => {- vi.mocked(git.execGit).mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' });- expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);- });-- // A repo with no commits yet makes `rev-list HEAD` exit non-zero with an- // empty stdout — parsing that as work would launder a no-op run.- it('is 0 on a non-zero git exit (no HEAD / broken checkout)', async () => {- vi.mocked(git.execGit).mockResolvedValue({ exitCode: 128, stdout: '', stderr: 'bad revision' });- expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);- });-- it('is 0 (never throws) when execGit rejects', async () => {- vi.mocked(git.execGit).mockRejectedValue(new Error('timeout'));- expect(await commitsSince('/tmp/ws', SINCE)).toBe(0);- });-- it('is 0 for a bad path or a non-finite timestamp without touching git', async () => {- expect(await commitsSince(null, SINCE)).toBe(0);- expect(await commitsSince('/tmp/ws', undefined)).toBe(0);- expect(await commitsSince('/tmp/ws', NaN)).toBe(0);- expect(git.execGit).not.toHaveBeenCalled();- });+ // The probe's own behavior (git args, exit-code/timeout handling) is covered by+ // server/lib/gitCommitProbe.test.js — its new home (#3637). What matters HERE is+ // that this module's historical entry point still resolves to it.+ it('re-exports the run-window commit probe from its lib home', async () => {+ vi.mocked(commitsSinceMock).mockResolvedValue(3);+ expect(await commitsSince('/tmp/ws', 1)).toBe(3);+ expect(commitsSince).toBe(commitsSinceMock);});describe('worktreeHasWorkEvidence', () => {@@ -133,27 +110,28 @@ describe('finalizeHelpers', () => {it('is true on a dirty tree without consulting the commit log', async () => {vi.mocked(git.getStatus).mockResolvedValue({ clean: false });expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(true);- expect(git.execGit).not.toHaveBeenCalled();+ expect(commitsSinceMock).not.toHaveBeenCalled();});// The release-run regression: commit + push + open PR leaves a CLEAN tree,// which the uncommitted-changes-only gate scored as "produced no work".it('is true on a clean tree when the run committed something', async () => {vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- vi.mocked(git.execGit).mockResolvedValue({ exitCode: 0, stdout: '1\n', stderr: '' });+ vi.mocked(commitsSinceMock).mockResolvedValue(1);expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(true);+ expect(commitsSinceMock).toHaveBeenCalledWith('/tmp/ws', SINCE);});it('is false on a clean tree with no in-window commits', async () => {vi.mocked(git.getStatus).mockResolvedValue({ clean: true });- vi.mocked(git.execGit).mockResolvedValue({ exitCode: 0, stdout: '0\n', stderr: '' });+ vi.mocked(commitsSinceMock).mockResolvedValue(0);expect(await worktreeHasWorkEvidence('/tmp/ws', SINCE)).toBe(false);});it('falls back to the dirty-tree signal alone when no window is given', async () => {vi.mocked(git.getStatus).mockResolvedValue({ clean: true });+ vi.mocked(commitsSinceMock).mockResolvedValue(0);expect(await worktreeHasWorkEvidence('/tmp/ws')).toBe(false);- expect(git.execGit).not.toHaveBeenCalled();});});diff --git a/server/services/cos.js b/server/services/cos.jsindex 4155c8d1ac..a630e10260 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -687,7 +687,7 @@ async function resetOrphanedTasks({ bootRecovery = false } = {}) {}emitLog('info', `Found orphaned in_progress task ${task.id}, routing through retry handler`, { taskId: task.id });const deadAgent = lastAgentByTask.get(task.id);- await handleOrphanedTask(task.id, deadAgent?.id || 'unknown-reset', getTaskById, { agentMetadata: deadAgent?.metadata });+ await handleOrphanedTask(task.id, deadAgent?.id || 'unknown-reset', getTaskById, { agentMetadata: deadAgent?.metadata, agentStartedAt: deadAgent?.startedAt });}};diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.jsindex 4509ffd21a..b290d76286 100644--- a/server/services/taskLearning/lifecycle.js+++ b/server/services/taskLearning/lifecycle.js@@ -13,7 +13,7 @@ import { declaresNoCommitCriterion } from '../taskTypeHooks.js';// A pre-#2696 gh/git coordinator run (branch-reconcile/issue-reconcile/branch-cleanup/// jira-status-report) carries a FOSSIL `result.validationPassed` — a boolean the old-// `[task-<id>]` commit criterion stamped on a run that never makes such a commit (almost+// commit criterion stamped on a run that never makes such a commit (almost// always `false`). recordTaskCompletion trusts a persisted boolean over the exit code, so// re-recording one verbatim would restore the very bucket migration 198 purged. These types// now declare NO commit criterion, so drop the fossil and let the exit-code success stand —diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex 00e72da643..0c7d45f1d3 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -60,7 +60,7 @@ async function loadHookModule(taskType) {/*** Whether a task type routes through the programmatic-I/O path — i.e. its real* output is the `.agent-done` sentinel an output hook consumes, NOT a- * `[task-<id>]` commit. Synchronous and import-free (a bare registry lookup), so+ * commit. Synchronous and import-free (a bare registry lookup), so* it is safe to consult from hot paths like the agent finalize chain.** This is what tells success-criteria validation that the commit criterion does@@ -101,8 +101,8 @@ export function resolveTaskHookType(task) {/*** Scheduled COORDINATOR task types whose deliverable is a git/gh/external side effect —* a merged PR, a resolved conflict, a deleted branch, healed issue state, a status report- * posted to Jira — NOT a `[task-<id>]` commit. Their agent runs in the app's LIVE checkout- * (no worktree, no PR), so they DO have a workspacePath at finalize, and the `[task-<id>]`+ * posted to Jira — NOT a commit. Their agent runs in the app's LIVE checkout+ * (no worktree, no PR), so they DO have a workspacePath at finalize, and the task-id commit* commit criterion would score every SUCCESSFUL run as a failure and pin their learning* bucket at ~0% (#2696). They declare no commit criterion (fall back to the exit code),* exactly like pipeline/media jobs.@@ -134,7 +134,7 @@ export const NON_COMMITTING_COORDINATOR_TASK_TYPES = new Set([]);/**- * Whether a task declares NO `[task-<id>]` commit criterion because it is a gh/git+ * Whether a task declares NO commit criterion because it is a gh/git* coordinator (see NON_COMMITTING_COORDINATOR_TASK_TYPES).** Resolves the type the SAME way extractTaskType (taskLearning/store.js) computes the@@ -162,7 +162,7 @@ export function isNonCommittingCoordinatorTask(task) {}/**- * Whether a task declares NO `[task-<id>]` commit criterion: the static+ * Whether a task declares NO commit criterion: the static* coordinator set above, OR a TRACKER-FILING task whose dispatch derived* `worktreeChangesExpected: false` (cosTaskGenerator.js#resolveTrackerFilingBlock,* referenceRepos.js#triggerReferenceAnalysis).@@ -192,7 +192,7 @@ export function isNonCommittingCoordinatorTask(task) {*/export function declaresNoCommitCriterion(task) {if (isNonCommittingCoordinatorTask(task)) return true;- // A discarded worktree cannot leave a `[task-<id>]` commit behind by+ // A discarded worktree cannot leave a commit behind by// construction — cleanup removes it without merging, and the prompt forbids// committing at all. Scoring the commit check against it marks every// SUCCESSFUL run a validation miss and drags that provider/model's learningdiff --git a/server/services/taskTypeHooks.noCommit.test.js b/server/services/taskTypeHooks.noCommit.test.jsindex c4bbc723cb..6975f043c3 100644--- a/server/services/taskTypeHooks.noCommit.test.js+++ b/server/services/taskTypeHooks.noCommit.test.js@@ -1,6 +1,6 @@/*** `declaresNoCommitCriterion` — which tasks are exempt from the- * `[task-<id>]` commit success check.+ * commit success check.** The exemption drives provider/model learning buckets: a wrongly-included task* scores every SUCCESSFUL run as a validation miss (#2696/#3273), and a wrongly