Skip to content

fix(antigravity-local): align process liveness tracking and empty-stdout failure handling - #771

Merged
insightflo merged 1 commit into
mainfrom
fix/antigravity-liveness-and-failure-detection
Nov 18, 2026
Merged

insightflo merged 1 commit into
mainfrom
fix/antigravity-liveness-and-failure-detection

Conversation

@insightflo

Copy link
Copy Markdown
Owner

Summary

Fixes intermittent process_lost misclassifications and false successes when running agents with antigravity_local (agy --print):

  1. Match raw runId key in runningProcesses (packages/adapters/antigravity-local/src/server/execute.ts):
    • Pass runId instead of `antigravity-${runId}` to runChildProcess(...) so runningProcesses.get(run.id) in heartbeat-orphan-reaper.ts, cancelRun, and shutdown cleanup finds active agy child processes.
  2. Track antigravity_local as a sessioned local adapter (server/src/services/heartbeat-process-liveness.ts):
    • Add "antigravity_local" to SESSIONED_LOCAL_ADAPTERS so live detached processes keep running rather than prematurely tripping process_lost across handle loss.
  3. Emit progress heartbeats from diagnostic log growth (packages/adapters/antigravity-local/src/server/runtime.ts, execute.ts):
    • Extract helper functions into runtime.ts (keeping execute.ts at 268 lines, under the 300-line policy limit) and add startDiagnosticLogActivityMonitor(...) to emit periodic [paperclip] Antigravity active (diagnostic log ... bytes) updates only when --log-file grows, preventing silent --print output buffering from triggering stale execution timeouts while genuine freezes still time out.
  4. Treat empty stdout + non-empty stderr on exit 0 as failure (packages/adapters/antigravity-local/src/server/runtime.ts):
    • Remove the !input.stderr.trim() guard in resolveAntigravityFailure(...) so silent exit-0 rejections (e.g., jetski: no output produced... on stderr) surface an error instead of succeeded.

Verification

  • pnpm --filter @paperclipai/adapter-antigravity-local build -> passed
  • npx vitest run packages/adapters/antigravity-local server/src/__tests__/antigravity-local-adapter-environment.test.ts server/src/__tests__/antigravity-models.test.ts server/src/__tests__/heartbeat-process-recovery.test.ts -> 8 test files passed, 84 tests passed
  • node scripts/check-run-status-write-chokepoint.mjs -> OK (2119 source files scanned, 31 allowlisted)
  • bash scripts/check-dockerfile-deps-stage.sh -> passed
  • pnpm -r typecheck -> passed

@insightflo
insightflo merged commit 3c897c9 into main Nov 18, 2026
6 checks passed
@insightflo
insightflo deleted the fix/antigravity-liveness-and-failure-detection branch November 18, 2026 07:24
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 9 issue(s) in this PR.

  • ✅ Successfully posted inline: 9 comment(s)

.split(/\n\s*\n/g)
.map((block) => block.trim())
.filter(Boolean);
const latestBlock = blocks.length > 0 ? blocks[blocks.length - 1] : normalized;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style · low
normalized가 빈 문자열이 아님이 이미 보장된 시점이므로 split 결과는 항상 최소 1개 요소를 가지고, trim + filter(Boolean) 이후에도 최소 하나의 비어 있지 않은 블록이 남습니다. 따라서 blocks.length > 0은 항상 참이고 else 분기(: normalized)는 도달 불가능한 죽은 코드입니다. 삼항식을 제거하면 가독성이 좋아집니다.

Suggestion:

Suggested change
const latestBlock = blocks.length > 0 ? blocks[blocks.length - 1] : normalized;
const latestBlock = blocks[blocks.length - 1];

Comment on lines +12 to +14
if (blocks.length <= 1 && lines.length > 1) {
return lines[lines.length - 1]?.trim() ?? "";
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
빈 줄로 구분되지 않은 단일 블록의 멀티라인 응답이 마지막 한 줄로 잘립니다. 이 휴리스틱은 execute.ts에서 이동된 기존 로직이고, execute.test.ts의 'resumed plain stdout' 케이스(resume 시 이전 응답이 줄 단위로 재출력되는 상황)를 위한 의도된 동작임을 테스트가 보여줍니다. 하지만 resume이 아닌 정상 실행에서도 빈 줄 없이 개행만으로 구성된 응답(리스트, 코드 블록, 줄바꿈된 문단)이 곧바로 마지막 한 줄만 남습니다. 이 summary는 execute.ts:227에서 최종 결과로 반환되고 heartbeat.ts의 handoff/summaryText로 흐르므로, 응답 내용 유실이 사용자에게 그대로 노출됩니다. resume 재출력 판별(예: 중복 라인 존재)을 조건으로 추가해 정상 멀티라인 응답은 보존하는 것을 권장합니다.

Suggestion:

Suggested change
if (blocks.length <= 1 && lines.length > 1) {
return lines[lines.length - 1]?.trim() ?? "";
}
if (blocks.length <= 1 && lines.length > 1) {
// resume 재출력(이전 응답 반복)으로 판단되는 경우에만 마지막 줄을 취한다.
// 중복 없는 정상 멀티라인 응답(리스트/코드 블록)은 전체를 보존한다.
const hasReplayedLines = new Set(lines).size < lines.length;
if (hasReplayedLines) {
return lines[lines.length - 1]?.trim() ?? "";
}
}

Comment on lines +27 to +28
function extractAntigravityQuotaMessage(diagnosticLog: string): string | null {
const match = diagnosticLog.match(/RESOURCE_EXHAUSTED \(code 429\):\s*([^\n]+)/i);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · low
\s*는 \n도 매칭하므로 마커가 줄 끝에 있는 경우 캡처가 다음 줄로 넘어갑니다. 예를 들어 진단 로그가 "RESOURCE_EXHAUSTED (code 429):\nRetrying in 25.3s (attempt 3)" 형태면 \s*가 개행을 소비하고 [^ ]+가 다음 줄 전체를 캡처해 "RESOURCE_EXHAUSTED (code 429): Retrying in 25.3s (attempt 3)"처럼 429과 무관한 텍스트가 에러 메시지에 붙습니다. 캡처를 같은 줄로 제한하려면 [ \t]* 또는 [^ ]* 계열(예: [^ ]*)로 바꾸는 것이 안전합니다. 분류 자체는 마커 존재 여부로 결정되어 영향이 메시지 정확성에 머무르지만, 사용자에게 노출되는 에러 문구이므로 수정이 권장됩니다.

Suggestion:

Suggested change
function extractAntigravityQuotaMessage(diagnosticLog: string): string | null {
const match = diagnosticLog.match(/RESOURCE_EXHAUSTED \(code 429\):\s*([^\n]+)/i);
const match = diagnosticLog.match(/RESOURCE_EXHAUSTED \(code 429\):[ \t]*([^\n]+)/i);

Comment on lines +29 to +30
if (!match) return null;
return `RESOURCE_EXHAUSTED (code 429): ${match[1]?.trim() ?? "quota exhausted"}`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
[^ ]+ 캡처 그룹은 매칭 성공 시 항상 non-nullish 문자열을 반환하므로 match[1]?.trim() ?? "quota exhausted"의 ?? 폴백은 도달 불가능한 죽은 코드입니다. 게다가 캡처 내용이 공백뿐인 경우 trim 결과는 빈 문자열(nullish가 아님)이라 폴백이 발동하지 않고 "RESOURCE_EXHAUSTED (code 429): "처럼 빈 값이 붙은 메시지가 만들어집니다. 빈 문자열까지 폴백으로 처리하려면 의도대로라면 ??가 아니라 ||를 사용해야 합니다.

Suggestion:

Suggested change
if (!match) return null;
return `RESOURCE_EXHAUSTED (code 429): ${match[1]?.trim() ?? "quota exhausted"}`;
return `RESOURCE_EXHAUSTED (code 429): ${match[1]?.trim() || "quota exhausted"}`;

if (input.timedOut) {
return { errorMessage: input.latestResponse || "Antigravity CLI timed out", errorCode: "adapter_failed" };
}
if ((input.exitCode ?? 0) !== 0) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
runChildProcess는 child가 시그널로 종료되면 close 핸들러에서 exitCode를 null로 resolve합니다(adapter-utils/src/server-utils.ts:1019-1033). 이 경우 (input.exitCode ?? 0) !== 0이 0과 동일하게 취급되어 실패로 분류되지 않고, 부분적인 stdout이 남아 있으면 resolveAntigravityFailure가 null을 반환해 잘린 응답이 정상 결과로 처리됩니다. heartbeat.ts:4437도 동일한 exitCode ?? 0 기준이므로 errorMessage가 없으면 해당 run은 succeeded로 종결됩니다. execute.ts 호출부에 child.signal이 이미 존재하므로 입력에 signal을 추가해 시그널 종료를 실패로 판정하는 것을 권장합니다.

Suggestion:

Suggested change
if ((input.exitCode ?? 0) !== 0) {
// ResolveAntigravityFailureInput에 signal?: NodeJS.Signals | null 추가 후
if (input.signal != null || (input.exitCode ?? 0) !== 0) {

errorCode: "adapter_failed",
};
}
if (/^Error:\s*timed out waiting for response\s*$/i.test(input.latestResponse.trim())) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
errorCode 문자열("adapter_failed", "provider_quota_exhausted")과 CLI 응답 텍스트 정규식이 함수 내부에 리터럴로 박혀 있습니다. 특히 "adapter_failed"는 서버 전역의 트랜지언트 재시도(heartbeat.ts:4705), provider-403 ladder, 휴먼카드 억제(AUTO_RECOVERABLE_RUN_ERROR_CODES)가 키로 사용하는 계약 값이라 오타 하나로 여러 복구 기능이 조용히 깨집니다. 모듈 레벨 상수로 추출해 export하고, 이 정규식이 agy CLI의 메시지 문구에 의존하므로 CLI 업데이트 시 매칭이 깨질 수 있음을 주석으로 관리하는 것을 권장합니다.

Comment on lines +67 to +68
errorMessage: `Antigravity provider quota exhausted: ${quotaMessage}`,
errorCode: "provider_quota_exhausted",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
provider_quota_exhausted는 저장소 전체에서 이 파일과 테스트 외에 소비자가 없습니다. 서버의 자동 복구 계약은 quota(429) 실패를 adapter_failed에 매핑합니다 — adapter_failed 트랜지언트 재시도(heartbeat.ts:4705의 failedErrorCode === "adapter_failed"), provider-403 ladder(heartbeat-provider403-ladder.ts:75), AUTO_RECOVERABLE_RUN_ERROR_CODES(human-card-admission.ts:11, 주석에 '429/할당량' 명시)가 모두 adapter_failed를 키로 사용합니다. 따라서 exit 0 + 빈 응답 경로에서 분류된 quota 실패는 자동 재시도와 휴먼카드 억제를 모두 놓칩니다. 또한 동일한 RESOURCE_EXHAUSTED라도 비정상 종료 시에는 아래 분기에서 adapter_failed로 분류되어, 종료 코드에 따라 같은 원인이 다른 errorCode로 갈라지는 불일치도 있습니다. errorCode를 복구 계약에 맞추거나(예: adapter_failed 유지 + errorMessage에 quota 상세), 신규 코드를 서버 측 복구 목록에 등록해야 합니다.

const pollOnce = async () => {
if (stopped) return;
const stat = await fs.stat(opts.logFilePath).catch(() => null);
if (stopped || !stat || stat.size <= lastBytes) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
stat.size가 줄어드는 경우(로그 truncate/rewrite) lastBytes 워터마크가 리셋되지 않습니다. 파일이 truncate된 뒤 이전 최대 크기를 다시 넘지 못하는 동안 활동 이벤트가 전혀 발생하지 않아, stdout이 버퍼링되어 조용한 장기 실행에서 하트비트 활동 갱신이 멈출 수 있습니다. 이 모니터의 존재 이유가 조용한 구간의 라이브니스 갱신인 만큼, 크기 감소를 감지하면 워터마크를 리셋해 이후 성장을 다시 감지하도록 하는 것이 안전합니다.

Suggestion:

Suggested change
if (stopped || !stat || stat.size <= lastBytes) return;
if (stopped || !stat) return;
if (stat.size < lastBytes) {
// truncate/rotate 감지 — 워터마크를 리셋해 이후 성장을 다시 감지한다.
lastBytes = stat.size;
return;
}
if (stat.size === lastBytes) return;

Comment on lines +111 to +112
lastBytes = stat.size;
await opts.onActivity(stat.size).catch(() => undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · low
onActivity와 fs.stat의 모든 오류가 조용히 삼켜집니다. 로그 파일이 아직 생성되지 않은 초기 구간의 stat 실패(ENOENT)는 정상 시나리오지만, onActivity(하트비트 활동 기록)가 반복적으로 실패하면 모니터가 사실상 동작하지 않는 상황을 디버깅할 방법이 없습니다. ENOENT는 무시하되 그 외 stat 오류와 onActivity 실패는 debug 수준 로그를 남기는 것을 권장합니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant