diff --git a/.claude/skills/porch/SKILL.md b/.claude/skills/porch/SKILL.md index 4538caf60..1ef0836a9 100644 --- a/.claude/skills/porch/SKILL.md +++ b/.claude/skills/porch/SKILL.md @@ -107,6 +107,8 @@ Override a protocol check per name in `.codev/config.json` under `porch.checks` A phase check is killed after 5 minutes unless it sets `timeout_ms` — in `protocol.json` or in its `porch.checks` override. On timeout porch kills the check's whole process tree. +A failed check prints the last 30 lines of its output and the path of a log holding all of it: `codev/projects/-/checks/--.log`, one per failed run, the newest 20 kept, ignored by git. Read the log to name the failure, even after a retry passes. + ## State storage Project state lives in `codev/projects/-/status.yaml`, managed automatically by porch. The status file tracks current phase, gate states, consultation results, and timestamps. diff --git a/.codex/skills/porch/SKILL.md b/.codex/skills/porch/SKILL.md index 4538caf60..1ef0836a9 100644 --- a/.codex/skills/porch/SKILL.md +++ b/.codex/skills/porch/SKILL.md @@ -107,6 +107,8 @@ Override a protocol check per name in `.codev/config.json` under `porch.checks` A phase check is killed after 5 minutes unless it sets `timeout_ms` — in `protocol.json` or in its `porch.checks` override. On timeout porch kills the check's whole process tree. +A failed check prints the last 30 lines of its output and the path of a log holding all of it: `codev/projects/-/checks/--.log`, one per failed run, the newest 20 kept, ignored by git. Read the log to name the failure, even after a retry passes. + ## State storage Project state lives in `codev/projects/-/status.yaml`, managed automatically by porch. The status file tracks current phase, gate states, consultation results, and timestamps. diff --git a/codev-skeleton/.claude/skills/porch/SKILL.md b/codev-skeleton/.claude/skills/porch/SKILL.md index 4538caf60..1ef0836a9 100644 --- a/codev-skeleton/.claude/skills/porch/SKILL.md +++ b/codev-skeleton/.claude/skills/porch/SKILL.md @@ -107,6 +107,8 @@ Override a protocol check per name in `.codev/config.json` under `porch.checks` A phase check is killed after 5 minutes unless it sets `timeout_ms` — in `protocol.json` or in its `porch.checks` override. On timeout porch kills the check's whole process tree. +A failed check prints the last 30 lines of its output and the path of a log holding all of it: `codev/projects/-/checks/--.log`, one per failed run, the newest 20 kept, ignored by git. Read the log to name the failure, even after a retry passes. + ## State storage Project state lives in `codev/projects/-/status.yaml`, managed automatically by porch. The status file tracks current phase, gate states, consultation results, and timestamps. diff --git a/codev-skeleton/.codex/skills/porch/SKILL.md b/codev-skeleton/.codex/skills/porch/SKILL.md index 4538caf60..1ef0836a9 100644 --- a/codev-skeleton/.codex/skills/porch/SKILL.md +++ b/codev-skeleton/.codex/skills/porch/SKILL.md @@ -107,6 +107,8 @@ Override a protocol check per name in `.codev/config.json` under `porch.checks` A phase check is killed after 5 minutes unless it sets `timeout_ms` — in `protocol.json` or in its `porch.checks` override. On timeout porch kills the check's whole process tree. +A failed check prints the last 30 lines of its output and the path of a log holding all of it: `codev/projects/-/checks/--.log`, one per failed run, the newest 20 kept, ignored by git. Read the log to name the failure, even after a retry passes. + ## State storage Project state lives in `codev/projects/-/status.yaml`, managed automatically by porch. The status file tracks current phase, gate states, consultation results, and timestamps. diff --git a/codev/projects/bugfix-1853-porch-done-truncates-failing-c/status.yaml b/codev/projects/bugfix-1853-porch-done-truncates-failing-c/status.yaml new file mode 100644 index 000000000..bb65ba828 --- /dev/null +++ b/codev/projects/bugfix-1853-porch-done-truncates-failing-c/status.yaml @@ -0,0 +1,21 @@ +id: bugfix-1853 +title: porch-done-truncates-failing-c +protocol: bugfix +phase: pr +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending + requested_at: '2026-11-24T01:56:22.535Z' +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-24T01:06:35.062Z' +updated_at: '2026-11-24T01:56:22.536Z' +pr_history: + - phase: pr + pr_number: 1964 + branch: builder/bugfix-1853 + created_at: '2026-11-24T01:32:51.412Z' +pr_ready_for_human: true diff --git a/codev/state/bugfix-1853_thread.md b/codev/state/bugfix-1853_thread.md new file mode 100644 index 000000000..7b0e63e1a --- /dev/null +++ b/codev/state/bugfix-1853_thread.md @@ -0,0 +1,86 @@ +# bugfix-1853 thread + +Issue #1853: porch done truncates failing check output; the failing test is never named. +Scope is the architect's last issue comment (2026-11-23): persist the full output of every failed +check, print the last lines instead of the first, and leave the commit-adjacent timing alone +(explained by #1956). + +## 2026-11-23 — investigate + +Operating rules from architect:main: no local full unit suite (#1956 load), targeted tests + build + +type-check only; open a draft PR so CI runs the suite and tell the architect before `porch done`; +present the pr gate in PRFT form. + +Reproduced through porch's own `runCheck` + `formatCheckResults`, running one failing vitest test +under the real `npm test -- --exclude='**/e2e/**' ` command in `packages/codev`. Porch printed +five `npm warn Unknown env config ...` lines and `...`, nothing else. The failing test's name was +in two places porch never shows: stderr's `FAIL > > ` block (the last ~18 +lines of stderr) and stdout's `× ` line. + +Root cause, `packages/codev/src/commands/porch/checks.ts`: +- `runCheck` keeps stdout in `output` and stderr in `error`; `formatCheckResults` prints only the + first five lines of `error` and never `output`. npm writes its config warnings to stderr first, so + the five lines are always warnings. +- The timeout result carries neither stream, so a timed-out check loses its output entirely. +- Nothing is written to disk, so a retry that passes leaves no record. + +Fix plan (~250 LOC with tests, fits BUGFIX): +- `runCheck` also keeps one transcript of stdout and stderr in the order porch reads them, on every + failure path (exit code, timeout, spawn error). +- `runPhaseChecks` takes an optional log destination and writes each failed shell check's full + output to `codev/projects//checks/--.log`; it keeps the newest 20 + and drops `.gitignore` (`*`) in the directory, since adopters' `.gitignore` does not ignore + `codev/projects/*/*.txt`, let alone a new directory. +- `formatCheckResults` prints the last lines of the transcript plus the log path. +- `porch check`, `porch done` and `porch approve` pass the destination. + +`overriddenChecks` on `runPhaseChecks` is never passed by any caller. Noted, left alone: it is about +artifact checks, not output. + +## 2026-11-23 — fix built, draft PR #1964 + +Fix and test commits pushed (c0cc478cb, c49ccc5f9). Seven new tests; six fail against the old +`checks.ts`. Targeted runs: 8 files, 90/90; `tsc --noEmit` clean; `pnpm build` clean. End-to-end with +the built CLI in a scratch workspace and with a real failing vitest test under `npm test`: the tail +names the test and ends with the log path, and `git status` stays clean. + +Surprise worth knowing: the POSIX launcher collapses runs of whitespace in a check's command +(`posixCollapseWhitespace`), so an `echo "FAIL x"` in a check prints `FAIL x`. The test strings use +single spaces for that reason. + +Draft PR #1964 opened so CI runs the full suite; Windows on-demand run 45303921745 dispatched. +Holding before `porch done` (fix phase's `tests` check is the full local suite) per architect rule 2. + +## 2026-11-23 — porch done (fix phase), run once on the architect's go + +`VITEST_MAX_WORKERS=3 porch done bugfix-1853`: build passed (26.0s), tests failed (147.8s), 174s +wall. Not rerun, per the architect. The failing test is unknown because the `porch` on PATH is the +installed v3.3.7 (main's build), not this branch's build. So the run printed the old five npm-warning +lines and saved no log: the bug this fix addresses hid its own evidence. Reported to the architect +with options; holding. + +Named from vitest's results cache (`packages/codev/node_modules/.vite/vitest//results.json`): +the one real failure was `src/__tests__/skill-refresh.test.ts`, "lists the current version of every +shipped skill". It was caused by this PR: I edited the porch SKILL.md without running +`generate-skill-hashes`. It failed alone too, deterministically. Regenerating the registry added one +hash each for `.claude/skills/porch` and `.codex/skills/porch`, and the file then passed 23/23. The +cache's other failed entry, `zz-repro-1853`, was my deleted repro file, a stale record. + +The worker cap reaches vitest through porch → shell → npm → vitest. I probed with 6 throwaway files +under porch's own `runCheck`: with `VITEST_MAX_WORKERS=3`, pool ids were 1–3 and at most 3 ran at +once; without it, ids 1–6 and 6 at once. vitest 4.1.4 applies the variable in config resolution, +overriding the config. I did not sample load during the porch done run (1-min load was 6.4 just after). + +## 2026-11-23 — fix phase passed, pr phase + +On the architect's go: `VITEST_MAX_WORKERS=3 node packages/codev/bin/porch.js done bugfix-1853` with +this branch's porch, run once. Build passed (19.5s), tests passed (142.6s), 165s wall, peak 1-min load +14.96. Advanced to pr. + +CMAP: claude APPROVE with five non-blocking notes. I fixed three: stream splicing (now whole lines), +the dead `stderr` accumulator, and a prune that could delete the log just written (5a67e5800, with +tests in 32fd78350). codex REQUEST_CHANGES, only on the `chore(porch)` commit prefixes. Rebutted: +those are porch's own state commits, standard on main (87 of the last 200). + +Windows run 45303921745 (first commit) failed only the same skill-hash test; the #1853 tests passed +there. Re-dispatched as 45306427073 on head 32fd783. PR #1964 is out of draft. diff --git a/packages/codev/src/commands/porch/__tests__/bugfix-1853-check-output.test.ts b/packages/codev/src/commands/porch/__tests__/bugfix-1853-check-output.test.ts new file mode 100644 index 000000000..466ae0082 --- /dev/null +++ b/packages/codev/src/commands/porch/__tests__/bugfix-1853-check-output.test.ts @@ -0,0 +1,177 @@ +/** + * Regression tests for issue #1853: a failed check printed the FIRST five lines + * of its stderr — npm's config warnings, for the tests check — and kept nothing, + * so the failing test was never named and a passing retry erased the evidence. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { tmpdir } from 'node:os'; +import { + runPhaseChecks, + formatCheckResults, + MAX_CHECK_LOGS, + type CheckEnv, + type CheckLogTarget, +} from '../checks.js'; +import { loadProtocol, getPhaseChecks } from '../protocol.js'; + +const env: CheckEnv = { PROJECT_ID: '1853', PROJECT_TITLE: 'check-output' }; + +// Single spaces only: the POSIX launcher collapses runs of whitespace in a check's command. +const FAILURE = 'FAIL src/thing.test.ts > thing > the named failing test'; +const SUMMARY = 'Tests 1 failed | 41 passed (42)'; + +/** + * Shaped like `npm test` under vitest: a stdout banner, 50 warnings on stderr, + * then the failure block (stderr) and the summary (stdout). + */ +const NOISY_FAILING_CHECK = [ + 'echo "> vitest run"', + 'for i in $(seq 1 50); do echo "npm warn Unknown env config $i" >&2; done', + `echo "${FAILURE}" >&2`, + `echo "${SUMMARY}"`, + 'exit 1', +].join('; '); + +function logFiles(dir: string): string[] { + return fs.existsSync(dir) ? fs.readdirSync(dir).filter(f => f.endsWith('.log')).sort() : []; +} + +describe('bugfix #1853: a failed check names its failure and keeps its full output', () => { + let root: string; + let target: CheckLogTarget; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(tmpdir(), 'porch-1853-')); + target = { dir: path.join(root, 'codev/projects/1853-check-output/checks'), phase: 'implement-phase_2' }; + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('prints the end of the output, where the failure is, and the path to the full log', async () => { + const results = await runPhaseChecks({ tests: NOISY_FAILING_CHECK }, root, env, undefined, undefined, undefined, target); + const printed = formatCheckResults(results); + + expect(results[0].passed).toBe(false); + expect(printed).toContain(FAILURE); + expect(printed).toContain(SUMMARY); + expect(printed).not.toContain('npm warn Unknown env config 1\n'); + expect(printed).toContain('earlier lines'); + expect(printed).toContain(`Full output: ${results[0].log_path}`); + }); + + it('the log holds the complete stdout and stderr', async () => { + const [result] = await runPhaseChecks({ tests: NOISY_FAILING_CHECK }, root, env, undefined, undefined, undefined, target); + + expect(path.dirname(result.log_path!)).toBe(target.dir); + expect(path.basename(result.log_path!)).toMatch(/^\d{4}-\d\d-\d\dT[\d-]+Z-implement-phase_2-tests\.log$/); + const log = fs.readFileSync(result.log_path!, 'utf-8'); + for (let i = 1; i <= 50; i++) expect(log).toContain(`npm warn Unknown env config ${i}\n`); + expect(log).toContain('> vitest run'); + expect(log).toContain(FAILURE); + expect(log).toContain(SUMMARY); + expect(log).toContain(`command: ${NOISY_FAILING_CHECK}\n`); + expect(log).toContain('result: Exit code 1'); + }); + + it('a passing check writes nothing', async () => { + const results = await runPhaseChecks({ build: 'echo ok' }, root, env, undefined, undefined, undefined, target); + + expect(results[0].passed).toBe(true); + expect(results[0].log_path).toBeUndefined(); + expect(fs.existsSync(target.dir)).toBe(false); + }); + + it('a check killed at its timeout still saves what it printed', async () => { + const [result] = await runPhaseChecks( + { tests: { command: 'echo "printed before the hang"; sleep 30', timeout_ms: 300 } }, + root, env, undefined, undefined, undefined, target, + ); + const printed = formatCheckResults([result]); + + expect(result.error).toContain('Timed out after 0.3s'); + expect(printed).toContain('Timed out after 0.3s'); + expect(printed).toContain('printed before the hang'); + expect(printed).toContain(`Full output: ${result.log_path}`); + const log = fs.readFileSync(result.log_path!, 'utf-8'); + expect(log).toContain('printed before the hang'); + expect(log).toContain('result: Timed out after 0.3s'); + }, 45_000); + + it('a porch.checks override that fails is saved like the protocol command', async () => { + const dir = path.join(root, 'codev/protocols/p1853'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'protocol.json'), JSON.stringify({ + name: 'p1853', phases: [{ id: 'implement', checks: { tests: { command: 'true' } } }], + })); + const checks = getPhaseChecks(loadProtocol(root, 'p1853'), 'implement', { + tests: { command: 'echo "override output"; exit 3' }, + }); + + const [result] = await runPhaseChecks(checks, root, env, undefined, undefined, undefined, target); + + expect(result.passed).toBe(false); + expect(fs.readFileSync(result.log_path!, 'utf-8')).toContain('override output'); + }); + + it('keeps only the newest logs, and git never sees them', async () => { + fs.mkdirSync(target.dir, { recursive: true }); + const old = Array.from({ length: MAX_CHECK_LOGS + 5 }, (_, i) => + `2020-01-01T00-00-${String(i).padStart(2, '0')}-000Z-implement-tests.log`); + for (const name of old) fs.writeFileSync(path.join(target.dir, name), 'old run'); + + const [result] = await runPhaseChecks({ tests: 'exit 1' }, root, env, undefined, undefined, undefined, target); + + const kept = logFiles(target.dir); + expect(kept).toHaveLength(MAX_CHECK_LOGS); + expect(kept).toContain(path.basename(result.log_path!)); + expect(kept).not.toContain(old[5]); + expect(kept).toContain(old[6]); + + execFileSync('git', ['init', '-q'], { cwd: root }); + const status = execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: root, encoding: 'utf-8' }); + expect(status).not.toContain('checks/'); + }); + + it('never deletes the log it just wrote, even when older logs sort after it', async () => { + fs.mkdirSync(target.dir, { recursive: true }); + const later = Array.from({ length: MAX_CHECK_LOGS }, (_, i) => + `2099-01-01T00-00-${String(i).padStart(2, '0')}-000Z-implement-tests.log`); + for (const name of later) fs.writeFileSync(path.join(target.dir, name), 'clock-skewed run'); + + const [result] = await runPhaseChecks({ tests: 'exit 1' }, root, env, undefined, undefined, undefined, target); + + expect(fs.existsSync(result.log_path!)).toBe(true); + expect(logFiles(target.dir)).toHaveLength(MAX_CHECK_LOGS); + expect(logFiles(target.dir)).not.toContain(later[0]); + }); + + it('lines from the two streams never splice into each other', async () => { + // stderr's line is split across two writes, with a whole stdout line between them. + const [result] = await runPhaseChecks( + { tests: "printf 'first half ' >&2; sleep 0.2; echo 'stdout line'; sleep 0.2; echo 'second half' >&2; exit 1" }, + root, env, undefined, undefined, undefined, target, + ); + + const lines = result.transcript!.split('\n'); + expect(lines).toContain('first half second half'); + expect(lines).toContain('stdout line'); + }); + + it('a log that cannot be written is reported, and the failure is still printed', async () => { + fs.mkdirSync(path.dirname(target.dir), { recursive: true }); + fs.writeFileSync(target.dir, 'a file where the checks directory should be'); + + const [result] = await runPhaseChecks({ tests: NOISY_FAILING_CHECK }, root, env, undefined, undefined, undefined, target); + const printed = formatCheckResults([result]); + + expect(result.log_path).toBeUndefined(); + expect(printed).toContain(FAILURE); + expect(printed).toMatch(/Full output could not be saved: .+/); + }); +}); diff --git a/packages/codev/src/commands/porch/__tests__/checks.test.ts b/packages/codev/src/commands/porch/__tests__/checks.test.ts index 0f59d7a58..5af0ad234 100644 --- a/packages/codev/src/commands/porch/__tests__/checks.test.ts +++ b/packages/codev/src/commands/porch/__tests__/checks.test.ts @@ -10,6 +10,7 @@ import { runArtifactCheck, formatCheckResults, allChecksPassed, + OUTPUT_TAIL_LINES, REQUIRED_SPEC_SECTIONS, type CheckEnv, } from '../checks.js'; @@ -54,7 +55,8 @@ describe('porch check runner', () => { const result = await runCheck('ls', 'ls /nonexistent/path/12345', cwd, defaultEnv); expect(result.passed).toBe(false); - expect(result.error).toBeDefined(); + expect(result.error).toMatch(/^Exit code \d+$/); + expect(result.transcript).toContain('/nonexistent/path/12345'); }); it('should pass project env variables to command', async () => { @@ -129,15 +131,18 @@ describe('porch check runner', () => { expect(output).toContain('3 tests failed'); }); - it('should truncate long error messages', () => { - const longError = Array(10).fill('Error line').join('\n'); + it('should truncate long output to its last lines', () => { + const transcript = Array.from({ length: OUTPUT_TAIL_LINES + 10 }, (_, i) => `line ${i + 1}`).join('\n'); const results = [ - { name: 'test', command: 'npm test', passed: false, error: longError, duration_ms: 1000 }, + { name: 'test', command: 'npm test', passed: false, error: 'Exit code 1', transcript, duration_ms: 1000 }, ]; const output = formatCheckResults(results); - expect(output).toContain('...'); + expect(output).toContain('... (10 earlier lines)'); + expect(output).not.toContain('line 10\n'); + expect(output).toContain('line 11\n'); + expect(output).toContain(`line ${OUTPUT_TAIL_LINES + 10}`); }); }); diff --git a/packages/codev/src/commands/porch/checks.ts b/packages/codev/src/commands/porch/checks.ts index a9a441f4d..406c4655b 100644 --- a/packages/codev/src/commands/porch/checks.ts +++ b/packages/codev/src/commands/porch/checks.ts @@ -8,6 +8,7 @@ import { execFile, type ChildProcessByStdio } from 'node:child_process'; import type { Readable } from 'node:stream'; import { promisify } from 'node:util'; +import * as fs from 'node:fs'; import * as path from 'node:path'; import type { CheckResult, CheckDef } from './types.js'; import type { ArtifactResolver } from './artifacts.js'; @@ -27,6 +28,15 @@ const KILL_GRACE_MS = 5000; /** Signals porch forwards to a running check's process group */ const RELAYED_SIGNALS: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP']; +/** + * Lines of a failed check's output printed at the terminal; the rest is in its log (#1853). + * Enough for a test runner's failure block and summary, which come last. + */ +export const OUTPUT_TAIL_LINES = 30; + +/** Failed-check logs kept per project; the oldest are deleted first (#1853) */ +export const MAX_CHECK_LOGS = 20; + // ============================================================================ // Check Execution // ============================================================================ @@ -37,6 +47,14 @@ export interface CheckEnv { PROJECT_TITLE: string; } +/** Where porch saves the full output of a failed shell check (#1853) */ +export interface CheckLogTarget { + /** The project's `checks/` directory, beside its status.yaml */ + dir: string; + /** The phase the check ran for, as it appears in the file name (e.g. `implement-phase_2`) */ + phase: string; +} + /** * Run a single check command. * @@ -56,7 +74,21 @@ export async function runCheck( return new Promise((resolve) => { let stdout = ''; - let stderr = ''; + // Both streams as one, as a terminal would have shown them: a test runner + // writes its warnings first and its failures last, across both (#1853). + // Each stream enters it a whole line at a time, so chunks from the two + // pipes never splice into each other mid-line. + let transcript = ''; + const partialLine = { stdout: '', stderr: '' }; + const record = (stream: keyof typeof partialLine, text: string) => { + const buffered = partialLine[stream] + text; + const end = buffered.lastIndexOf('\n') + 1; + transcript += buffered.slice(0, end); + partialLine[stream] = buffered.slice(end); + }; + /** The transcript, with each stream's unterminated last line */ + const fullTranscript = () => + transcript + [partialLine.stdout, partialLine.stderr].filter(Boolean).map(line => `${line}\n`).join(''); let killed = false; // detached: the check leads its own process group, so a timeout can kill @@ -118,14 +150,16 @@ export async function runCheck( }, timeoutMs); proc.stdout.on('data', (data) => { - stdout += data.toString(); + const text = data.toString(); + stdout += text; + record('stdout', text); }); proc.stderr.on('data', (data) => { - stderr += data.toString(); + record('stderr', data.toString()); }); - proc.on('close', async (code) => { + proc.on('close', async (code, signal) => { clearTimeout(timeout); if (killed) { @@ -143,7 +177,9 @@ export async function runCheck( name, command, passed: false, + output: stdout.trim(), error: `Timed out after ${timeoutMs / 1000}s (raise this check's timeout_ms if it needs longer)`, + transcript: fullTranscript(), duration_ms: Date.now() - startTime, }); return; @@ -160,12 +196,14 @@ export async function runCheck( duration_ms: duration, }); } else { + // stderr is in the transcript; `error` says only why the check failed. resolve({ name, command, passed: false, output: stdout.trim(), - error: stderr.trim() || `Exit code ${code}`, + error: code !== null ? `Exit code ${code}` : `Killed by ${signal}`, + transcript: fullTranscript(), duration_ms: duration, }); } @@ -179,6 +217,7 @@ export async function runCheck( command, passed: false, error: err.message, + transcript: fullTranscript(), duration_ms: Date.now() - startTime, }); }); @@ -353,6 +392,9 @@ export function runArtifactCheck( * Special handling: `pr_exists` checks are routed through the forge concept * command dispatcher instead of running the protocol.json command directly. * This allows per-project forge configuration while keeping protocol JSON unchanged. + * + * With a `log` target, each failed shell check's full output is saved there and + * its path recorded on the result (#1853). */ export async function runPhaseChecks( checks: Record, @@ -361,6 +403,7 @@ export async function runPhaseChecks( timeoutMs: number = DEFAULT_TIMEOUT_MS, resolver?: ArtifactResolver, overriddenChecks?: Set, + log?: CheckLogTarget, ): Promise { const results: CheckResult[] = []; @@ -399,6 +442,7 @@ export async function runPhaseChecks( // Stop on first failure if (!result.passed) { + if (log) saveCheckLog(log, result, checkCwd); break; } } @@ -406,6 +450,47 @@ export async function runPhaseChecks( return results; } +/** + * Save a failed check's full output, so the failure can still be read after a + * retry passes (#1853). A file that cannot be written is reported on the result + * rather than thrown, so the check's own failure is still printed. + */ +function saveCheckLog(target: CheckLogTarget, result: CheckResult, cwd: string): void { + const savedAt = new Date().toISOString(); + // Timestamp first, so file names sort oldest to newest. + const fileName = [savedAt.replace(/[:.]/g, '-'), target.phase, result.name] + .map(part => part.replace(/[^A-Za-z0-9_-]/g, '_')) + .join('-') + '.log'; + const logPath = path.join(target.dir, fileName); + const header = [ + `check: ${result.name}`, + `phase: ${target.phase}`, + `command: ${result.command}`, + `cwd: ${cwd}`, + `result: ${result.error}`, + `duration: ${((result.duration_ms ?? 0) / 1000).toFixed(1)}s`, + `saved at: ${savedAt}`, + ]; + + try { + fs.mkdirSync(target.dir, { recursive: true }); + // Per-run output, never project state. Ignored from inside the directory + // because adopters' .gitignore carries no rule for codev/projects/. + const gitignore = path.join(target.dir, '.gitignore'); + if (!fs.existsSync(gitignore)) fs.writeFileSync(gitignore, '*\n'); + fs.writeFileSync( + logPath, + `${header.join('\n')}\n\n--- stdout and stderr, in the order porch read them ---\n${result.transcript ?? ''}`, + ); + result.log_path = logPath; + // Never the file just written, whatever names sort after it. + const older = fs.readdirSync(target.dir).filter(f => f.endsWith('.log') && f !== fileName).sort(); + for (const old of older.slice(0, -(MAX_CHECK_LOGS - 1))) fs.rmSync(path.join(target.dir, old)); + } catch (err) { + result.log_error = err instanceof Error ? err.message : String(err); + } +} + /** * Run pr_exists check via the forge concept command dispatcher. * Gets the current branch name from git, then uses the pr-exists concept. @@ -451,6 +536,16 @@ async function runPrExistsViaConcept( // Result Formatting // ============================================================================ +/** + * The last `max` lines of `text`. A failing command's useful lines come last: + * the first ones are tool and config warnings (#1853). + */ +function lastLines(text: string, max: number): string[] { + const lines = text.trimEnd().split('\n'); + if (lines.length <= max) return lines; + return [`... (${lines.length - max} earlier lines)`, ...lines.slice(-max)]; +} + /** * Format check results for terminal output */ @@ -465,15 +560,15 @@ export function formatCheckResults(results: CheckResult[]): string { lines.push(` ${status} ${result.name}${duration}`); - if (!result.passed && result.error) { - // Indent error message - const errorLines = result.error.split('\n').slice(0, 5); - for (const line of errorLines) { - lines.push(` ${line}`); - } - if (result.error.split('\n').length > 5) { - lines.push(' ...'); - } + if (result.passed) continue; + const details = [ + ...(result.error ? lastLines(result.error, OUTPUT_TAIL_LINES) : []), + ...(result.transcript?.trim() ? lastLines(result.transcript, OUTPUT_TAIL_LINES) : []), + ]; + if (result.log_path) details.push(`Full output: ${result.log_path}`); + if (result.log_error) details.push(`Full output could not be saved: ${result.log_error}`); + for (const line of details) { + lines.push(` ${line}`); } } diff --git a/packages/codev/src/commands/porch/index.ts b/packages/codev/src/commands/porch/index.ts index a19bc3e92..c5a33dc9c 100644 --- a/packages/codev/src/commands/porch/index.ts +++ b/packages/codev/src/commands/porch/index.ts @@ -57,6 +57,7 @@ import { formatCheckResults, allChecksPassed, type CheckEnv, + type CheckLogTarget, } from './checks.js'; import { loadCheckOverrides, resolveConsultationModels } from './config.js'; import { notifyTerminal, gateApprovedMessage } from './notify.js'; @@ -76,6 +77,17 @@ function section(title: string, content: string): string { return `\n${chalk.bold(title)}:\n${content}`; } +/** + * Where a failed check's full output is saved (#1853): `checks/` beside the + * project's status.yaml, one file per failed run. + */ +function checkLogTarget(statusPath: string, state: ProjectState): CheckLogTarget { + return { + dir: path.join(path.dirname(statusPath), 'checks'), + phase: state.current_plan_phase ? `${state.phase}-${state.current_plan_phase}` : state.phase, + }; +} + /** * Return a resolver scoped to `artifactRoot` when it differs from the caller's * cwd-rooted resolver. The incoming `resolver` is typically built from @@ -382,7 +394,8 @@ export async function check(workspaceRoot: string, projectId: string, resolver?: return; } - const results = await runPhaseChecks(checks, artifactRoot, checkEnv, undefined, scopedResolver); + const results = await runPhaseChecks( + checks, artifactRoot, checkEnv, undefined, scopedResolver, undefined, checkLogTarget(statusPath, state)); console.log(formatCheckResults(results)); console.log(''); @@ -470,7 +483,8 @@ export async function done(workspaceRoot: string, projectId: string, resolver?: logCheckOverrides(phaseCheckNames, checks, overrides); if (Object.keys(checks).length > 0) { - const results = await runPhaseChecks(checks, artifactRoot, checkEnv, undefined, scopedResolver); + const results = await runPhaseChecks( + checks, artifactRoot, checkEnv, undefined, scopedResolver, undefined, checkLogTarget(statusPath, state)); console.log(formatCheckResults(results)); if (!allChecksPassed(results)) { @@ -801,7 +815,8 @@ export async function approve( logCheckOverrides(phaseCheckNames, checks, overrides); if (Object.keys(checks).length > 0) { - const results = await runPhaseChecks(checks, artifactRoot, checkEnv, undefined, scopedResolver); + const results = await runPhaseChecks( + checks, artifactRoot, checkEnv, undefined, scopedResolver, undefined, checkLogTarget(statusPath, state)); console.log(formatCheckResults(results)); if (!allChecksPassed(results)) { diff --git a/packages/codev/src/commands/porch/types.ts b/packages/codev/src/commands/porch/types.ts index ebe2e7e04..933f639b7 100644 --- a/packages/codev/src/commands/porch/types.ts +++ b/packages/codev/src/commands/porch/types.ts @@ -318,4 +318,10 @@ export interface CheckResult { output?: string; error?: string; duration_ms?: number; + /** A failed shell check's stdout and stderr, interleaved in the order porch read them (#1853) */ + transcript?: string; + /** Where porch saved a failed shell check's full output (#1853) */ + log_path?: string; + /** Why that output could not be saved, when it could not */ + log_error?: string; } diff --git a/packages/codev/src/lib/shipped-skill-hashes.ts b/packages/codev/src/lib/shipped-skill-hashes.ts index fbaceffe8..a8286aa1c 100644 --- a/packages/codev/src/lib/shipped-skill-hashes.ts +++ b/packages/codev/src/lib/shipped-skill-hashes.ts @@ -120,6 +120,7 @@ export const SHIPPED_SKILL_HASHES: Record = { 'b1f49ca7947d0216a150c9160c0e1ca3720904b5a727c4d438520462dde9aa0d', 'b811a74a097a7b9ddf00b7f30a907186026220d09625a675dfa805e6bdf2128f', 'cbea3254263c98713076ebf666e0805e029cfc809229e7fbf1f71c87dd5a0767', + 'dbb6d5225a68e48b783df7d1ca874a3c936b11f46a244b7b63988535f74dfd89', ], '.claude/skills/runnable-worktrees': [ '371d5dc88ddbcce63649aa325fbf55945283f61cb91c44e157b280c293c4f264', @@ -219,6 +220,7 @@ export const SHIPPED_SKILL_HASHES: Record = { '97fba15b2e5f7e4aa42cd7d172c11aa915a8562da4e06d46fb1ab2c062c3b3cf', 'b1f49ca7947d0216a150c9160c0e1ca3720904b5a727c4d438520462dde9aa0d', 'b811a74a097a7b9ddf00b7f30a907186026220d09625a675dfa805e6bdf2128f', + 'dbb6d5225a68e48b783df7d1ca874a3c936b11f46a244b7b63988535f74dfd89', ], '.codex/skills/runnable-worktrees': [ '371d5dc88ddbcce63649aa325fbf55945283f61cb91c44e157b280c293c4f264',