Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions cdk/src/handlers/fanout-task-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import {
type LinearPostResult,
} from './shared/linear-feedback';
import { logger } from './shared/logger';
import { coerceNumericOrNull } from './shared/numeric';
import { coerceNumericOrNull, completedTurnsOrNull } from './shared/numeric';
import { loadRepoConfig } from './shared/repo-config';
import { encodeMarkdownUrl } from './shared/screenshot-url';
import { prNumberFromTask } from './shared/task-pr-number';
Expand Down Expand Up @@ -1689,11 +1689,11 @@ function linearFinalStatusArgs(
{ field: 'cost_usd', task_id: task.task_id, event_id: event.event_id },
logger,
),
turns: coerceNumericOrNull(
task.turns_attempted,
{ field: 'turns_attempted', task_id: task.task_id, event_id: event.event_id },
turns: completedTurnsOrNull(coerceNumericOrNull(
task.turns_completed,
Comment thread
abhiramshaji-cyber marked this conversation as resolved.
Resolved
{ field: 'turns_completed', task_id: task.task_id, event_id: event.event_id },
logger,
),
)),
maxTurns: coerceNumericOrNull(
task.max_turns,
{ field: 'max_turns', task_id: task.task_id, event_id: event.event_id },
Expand Down Expand Up @@ -2027,11 +2027,11 @@ async function dispatchToJira(event: FanOutEvent): Promise<void> {
{ field: 'cost_usd', task_id: task.task_id, event_id: event.event_id },
logger,
),
turns: coerceNumericOrNull(
task.turns_attempted,
{ field: 'turns_attempted', task_id: task.task_id, event_id: event.event_id },
turns: completedTurnsOrNull(coerceNumericOrNull(
task.turns_completed,
{ field: 'turns_completed', task_id: task.task_id, event_id: event.event_id },
logger,
),
)),
maxTurns: coerceNumericOrNull(
task.max_turns,
{ field: 'max_turns', task_id: task.task_id, event_id: event.event_id },
Expand Down
9 changes: 5 additions & 4 deletions cdk/src/handlers/orchestration-reconciler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ import {
} from './shared/jira-status-comment';
import { logger } from './shared/logger';
import { type LookupResult, LOOKUP_ABSENT, isLookupFailure, lookupFailed, lookupFound, lookupValueOr } from './shared/lookup-result';
import { completedTurnsOrNull } from './shared/numeric';
import type { Channel, CommentRef, IssueRef } from './shared/orchestration-channel';
import { channelForSource, type ChannelRegistryTables } from './shared/orchestration-channel-factory';
import { computeLeaves, isIntegrationNode } from './shared/orchestration-integration-node';
Expand Down Expand Up @@ -252,7 +253,7 @@ interface TerminalTaskEvent {
* null for records we don't act on (inserts, non-terminal MODIFYs,
* non-orchestration tasks, malformed images).
*/
// eslint-disable-next-line complexity -- predates the ceiling (71 when it landed); must not grow
// eslint-disable-next-line complexity -- predates the ceiling (70, down from 71 when it landed); must not grow
export function parseTerminalTaskRecord(record: DynamoDBRecord): TerminalTaskEvent | null {
if (record.eventName !== 'MODIFY' && record.eventName !== 'INSERT') return null;
const img = record.dynamodb?.NewImage;
Expand Down Expand Up @@ -288,8 +289,8 @@ export function parseTerminalTaskRecord(record: DynamoDBRecord): TerminalTaskEve
: (img.cost_usd?.S !== undefined ? Number(img.cost_usd.S) : undefined);
const durationS = img.duration_s?.N !== undefined ? Number(img.duration_s.N)
: (img.duration_s?.S !== undefined ? Number(img.duration_s.S) : undefined);
const turns = img.turns_attempted?.N !== undefined ? Number(img.turns_attempted.N)
: (img.turns_attempted?.S !== undefined ? Number(img.turns_attempted.S) : undefined);
const turns = completedTurnsOrNull(img.turns_completed?.N !== undefined ? Number(img.turns_completed.N)
: (img.turns_completed?.S !== undefined ? Number(img.turns_completed.S) : undefined));
const maxTurns = img.max_turns?.N !== undefined ? Number(img.max_turns.N)
: (img.max_turns?.S !== undefined ? Number(img.max_turns.S) : undefined);

Expand Down Expand Up @@ -327,7 +328,7 @@ export function parseTerminalTaskRecord(record: DynamoDBRecord): TerminalTaskEve
...(iterationReplyId !== undefined && { iterationReplyId }),
...(costUsd !== undefined && Number.isFinite(costUsd) && { costUsd }),
...(durationS !== undefined && Number.isFinite(durationS) && { durationS }),
...(turns !== undefined && Number.isFinite(turns) && { turns }),
...(turns !== null && { turns }),
...(maxTurns !== undefined && Number.isFinite(maxTurns) && { maxTurns }),
};
}
Expand Down
6 changes: 3 additions & 3 deletions cdk/src/handlers/shared/jira-iteration-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
import type { JiraPreviewBudget } from './jira-preview-budget';
import { jiraIterationFrame, renderJiraFinalStatusComment } from './jira-status-comment';
import { logger } from './logger';
import { coerceNumericOrNull } from './numeric';
import { coerceNumericOrNull, completedTurnsOrNull } from './numeric';
import { isAllowedScreenshotUrl } from './screenshot-url';
import type { TaskRecord } from './types';

Expand All @@ -50,14 +50,14 @@ function renderIterationComment(task: TaskRecord): Record<string, unknown> {
const saved = task.jira_iteration_status;
// Only build a fallback when no usable status was persisted. Runtime result
// metrics may be numeric strings, just as in the fan-out notification path.
const metric = (field: 'cost_usd' | 'turns_attempted' | 'max_turns' | 'duration_s') =>
const metric = (field: 'cost_usd' | 'turns_completed' | 'max_turns' | 'duration_s') =>
coerceNumericOrNull(task[field], { field, task_id: task.task_id }, logger);
const body = saved && (!terminal || saved.terminal) ? saved.body : terminal
? buildAdfDocument(renderJiraFinalStatusComment({
...jiraIterationFrame(`task_${String(task.status).toLowerCase()}`, task.build_passed, null),
prUrl: task.pr_url ?? null,
costUsd: metric('cost_usd'),
turns: metric('turns_attempted'),
turns: completedTurnsOrNull(metric('turns_completed')),
maxTurns: metric('max_turns'),
durationS: metric('duration_s'),
taskId: task.task_id,
Expand Down
4 changes: 4 additions & 0 deletions cdk/src/handlers/shared/numeric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,7 @@ export function coerceNumericOrNull(
}
return n;
}

export function completedTurnsOrNull(turns: number | null | undefined): number | null {
return typeof turns === 'number' && Number.isFinite(turns) && turns > 0 ? turns : null;
}
7 changes: 7 additions & 0 deletions cdk/test/handlers/fanout-linear-agent-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ const SESSION_TASK = {
},
cost_usd: 0.5,
turns_attempted: 12,
turns_completed: '9',
max_turns: 100,
duration_s: 300,
};
Expand Down Expand Up @@ -199,6 +200,12 @@ test.each([
expect(mockPostIssueComment).not.toHaveBeenCalled();
});

test('the final activity counts turns_completed, not turns_attempted', async () => {
mockTask({ ...SESSION_TASK, status: 'COMPLETED', pr_url: 'https://github.com/acme/web/pull/7' });
await routeEvent(ev('task_completed'), LINEAR_ONLY);
expect(mockEmitAgentActivity.mock.calls[0][2].body).toContain('9 / 100');
});

test('a final activity already emitted is not repeated', async () => {
mockTask({ ...SESSION_TASK, status: 'COMPLETED', linear_final_comment_event_id: 'e-old' });
await routeEvent(ev('task_completed'), LINEAR_ONLY);
Expand Down
32 changes: 28 additions & 4 deletions cdk/test/handlers/fanout-task-events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1604,7 +1604,8 @@ describe('fanout-task-events: Linear dispatcher', () => {
created_at: '2026-04-30T11:50:00Z',
updated_at: '2026-04-30T12:00:00Z',
cost_usd: 0.55,
turns_attempted: 27,
turns_attempted: 41,
turns_completed: '27',
max_turns: 100,
duration_s: 221,
pr_url: 'https://github.com/owner/repo/pull/13',
Expand Down Expand Up @@ -1656,6 +1657,7 @@ describe('fanout-task-events: Linear dispatcher', () => {
expect(body).toContain('Task completed');
expect(body).toContain('$0.55');
expect(body).toContain('27 / 100');
expect(body).not.toContain('41 / 100');
expect(body).toContain('3m 41s');
// The PR URL IS rendered on the ✅ success path. The old
// behavior omitted it, assuming the agent's own step-2 "PR opened" comment
Expand All @@ -1668,6 +1670,15 @@ describe('fanout-task-events: Linear dispatcher', () => {
expect(body).toContain('t-lin');
});

test.each([undefined, 0, '0'])('turns_completed %p is no count, so turns_attempted is not shown', async (turnsCompleted) => {
mockGet({ ...TASK_RECORD_LINEAR, turns_completed: turnsCompleted });

await handler({ Records: [mkEvent('task_completed', 't-lin')] });

const [, , body] = mockPostIssueComment.mock.calls[0];
expect(body).toContain('turns: —');
});

test('task_failed without PR renders ❌ frame', async () => {
mockGet({
...TASK_RECORD_LINEAR,
Expand Down Expand Up @@ -1696,6 +1707,7 @@ describe('fanout-task-events: Linear dispatcher', () => {
// classifier reads the error_message text to derive the title.
error_message: 'Task did not succeed: agent_status="error_max_turns"',
turns_attempted: 101,
turns_completed: 100,
cost_usd: 3.44,
duration_s: 1272,
});
Expand All @@ -1708,7 +1720,7 @@ describe('fanout-task-events: Linear dispatcher', () => {
expect(body).toContain('Shipped a PR but stopped early');
expect(body).toContain('https://github.com/owner/repo/pull/13');
expect(body).toContain('$3.44');
expect(body).toContain('101 / 100');
expect(body).toContain('100 / 100');
expect(body).toContain('21m 12s');
});

Expand Down Expand Up @@ -2492,7 +2504,8 @@ describe('fanout-task-events: Jira dispatcher', () => {
created_at: '2026-06-30T11:50:00Z',
updated_at: '2026-06-30T12:00:00Z',
cost_usd: 0.55,
turns_attempted: 27,
turns_attempted: 41,
turns_completed: '27',
max_turns: 100,
duration_s: 221,
pr_url: 'https://github.com/owner/repo/pull/13',
Expand Down Expand Up @@ -2534,6 +2547,7 @@ describe('fanout-task-events: Jira dispatcher', () => {
expect(text).toContain('Task completed');
expect(text).toContain('$0.55');
expect(text).toContain('27 / 100');
expect(text).not.toContain('41 / 100');
expect(text).toContain('3m 41s');
// Unlike Linear, the PR URL IS rendered on the ✅ success path — the
// agent-side terminal comment (which carried it) was demoted to this
Expand All @@ -2542,6 +2556,15 @@ describe('fanout-task-events: Jira dispatcher', () => {
expect(text).toContain('t-jira');
});

test.each([undefined, 0, '0'])('turns_completed %p is no count, so turns_attempted is not shown', async (turnsCompleted) => {
mockGet({ ...TASK_RECORD_JIRA, turns_completed: turnsCompleted });

await handler({ Records: [mkEvent('task_completed', 't-jira')] });

const [, , body] = mockPostIssueCommentAdf.mock.calls[0];
expect(adfText(body)).toContain('turns: —');
});

test('task_failed without PR renders ❌ frame', async () => {
mockGet({ ...TASK_RECORD_JIRA, pr_url: undefined, error_message: 'Generic crash' });

Expand All @@ -2559,6 +2582,7 @@ describe('fanout-task-events: Jira dispatcher', () => {
...TASK_RECORD_JIRA,
error_message: 'Task did not succeed: agent_status="error_max_turns"',
turns_attempted: 101,
turns_completed: 100,
cost_usd: 3.44,
duration_s: 1272,
});
Expand All @@ -2572,7 +2596,7 @@ describe('fanout-task-events: Jira dispatcher', () => {
expect(text).toContain('Shipped a PR but stopped early');
expect(text).toContain('https://github.com/owner/repo/pull/13');
expect(text).toContain('$3.44');
expect(text).toContain('101 / 100');
expect(text).toContain('100 / 100');
expect(text).toContain('21m 12s');
});

Expand Down
28 changes: 27 additions & 1 deletion cdk/test/handlers/orchestration-reconciler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ function taskRecord(fields: {
cost_usd?: number;
duration_s?: number;
turns_attempted?: number;
turns_completed?: string;
max_turns?: number;
// Stream sequence number (itemIdentifier for partial-batch reporting).
sequenceNumber?: string;
Expand All @@ -179,6 +180,7 @@ function taskRecord(fields: {
if (fields.cost_usd !== undefined) img.cost_usd = { N: String(fields.cost_usd) };
if (fields.duration_s !== undefined) img.duration_s = { N: String(fields.duration_s) };
if (fields.turns_attempted !== undefined) img.turns_attempted = { N: String(fields.turns_attempted) };
if (fields.turns_completed !== undefined) img.turns_completed = { S: fields.turns_completed };
if (fields.max_turns !== undefined) img.max_turns = { N: String(fields.max_turns) };
if (fields.error_message) img.error_message = { S: fields.error_message };
// PRODUCTION SHAPE: createTaskCore persists orchestration_id INSIDE the
Expand Down Expand Up @@ -218,6 +220,29 @@ describe('parseTerminalTaskRecord', () => {
expect(evt).toEqual({ taskId: 'T1', status: 'COMPLETED', buildPassed: true, orchestrationId: 'orch_1' });
});

test('reads turns_completed, the count max_turns limits, not turns_attempted', () => {
const evt = parseTerminalTaskRecord(taskRecord({
task_id: 'T1',
status: 'COMPLETED',
orchestration_id: 'orch_1',
turns_attempted: 90,
turns_completed: '62',
max_turns: 80,
}));
expect(evt).toMatchObject({ turns: 62, maxTurns: 80 });
});

test.each([undefined, '0', 'NaN'])('turns_completed %p is no count, so turns is left out', (turnsCompleted) => {
const evt = parseTerminalTaskRecord(taskRecord({
task_id: 'T1',
status: 'COMPLETED',
orchestration_id: 'orch_1',
turns_attempted: 90,
turns_completed: turnsCompleted,
}));
expect(evt).not.toHaveProperty('turns');
});

test('skips non-terminal status', () => {
expect(parseTerminalTaskRecord(taskRecord({ task_id: 'T1', status: 'RUNNING', orchestration_id: 'orch_1' }))).toBeNull();
});
Expand Down Expand Up @@ -1547,7 +1572,8 @@ describe('orchestration-reconciler handler — the iteration ack reply', () => {
iteration_reply_comment_id: 'jira-status-1',
cost_usd: 1.25,
duration_s: 125,
turns_attempted: 12,
turns_attempted: 19,
turns_completed: '12',
max_turns: 100,
})],
} as never);
Expand Down
13 changes: 11 additions & 2 deletions cdk/test/handlers/shared/jira-iteration-comment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ test('a preview on an older task that completed with a red build renders a failu

test('completed runtime metrics stored as strings do not block the saved terminal status or preview', async () => {
const f = fixture();
f.finish({ cost_usd: '0.20663065', turns_attempted: '12', duration_s: '69.3' });
f.finish({ cost_usd: '0.20663065', turns_completed: '12', duration_s: '69.3' });
f.screenshot();
await expect(f.update(status('✅ Finished — result posted below.', true))).resolves.toEqual({ ok: true });
const body = JSON.stringify(put.mock.calls.at(-1)![3]);
Expand All @@ -188,7 +188,7 @@ test('completed runtime metrics stored as strings do not block the saved termina
test('fallback status normalizes runtime metrics stored as strings', async () => {
const f = fixture();
await f.update(status('Working', false));
f.finish({ cost_usd: '0.20663065', turns_attempted: '12', max_turns: '30', duration_s: '69.3' });
f.finish({ cost_usd: '0.20663065', turns_attempted: '41', turns_completed: '12', max_turns: '30', duration_s: '69.3' });
f.screenshot();
await expect(f.update()).resolves.toEqual({ ok: true });
const body = JSON.stringify(put.mock.calls.at(-1)![3]);
Expand All @@ -200,6 +200,15 @@ test('fallback status normalizes runtime metrics stored as strings', async () =>
expect(body).not.toContain('Working');
});

test.each([undefined, '0'])('fallback status shows no turns when turns_completed is %p', async (turnsCompleted) => {
const f = fixture();
f.finish({ turns_attempted: '41', turns_completed: turnsCompleted, max_turns: '30' });
await f.update();
const body = JSON.stringify(put.mock.calls.at(-1)![3]);
expect(body).toContain('turns: —');
expect(body).not.toContain('41 / 30');
});

test('malformed optional metrics do not prevent terminal feedback', async () => {
const f = fixture();
f.finish({ cost_usd: 'invalid', duration_s: 'NaN' });
Expand Down
12 changes: 11 additions & 1 deletion cdk/test/handlers/shared/numeric.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* SOFTWARE.
*/

import { coerceNumericOrNull, type CoerceLogger } from '../../../src/handlers/shared/numeric';
import { coerceNumericOrNull, completedTurnsOrNull, type CoerceLogger } from '../../../src/handlers/shared/numeric';

function mkLogger(): { logger: CoerceLogger; warnCalls: Array<{ message: string; meta?: Record<string, unknown> }> } {
const warnCalls: Array<{ message: string; meta?: Record<string, unknown> }> = [];
Expand Down Expand Up @@ -96,3 +96,13 @@ describe('coerceNumericOrNull', () => {
expect(warnCalls[0].meta?.raw).toBe('x'.repeat(length));
});
});

describe('completedTurnsOrNull', () => {
test.each([1, 27, 100])('keeps a count of %p', (turns) => {
expect(completedTurnsOrNull(turns)).toBe(turns);
});

test.each([undefined, null, 0, -0, -3, NaN, Infinity, -Infinity])('treats %p as no count', (turns) => {
expect(completedTurnsOrNull(turns)).toBeNull();
});
});
Loading