Reduce src/engine/loop.ts:1-6567 (6567 lines, single HeadlessSession class at src/engine/loop.ts:1363) toward docs/typescript-standards.md (250 file / 200 class / 20 function lines) with no behavior change. Land a coherent partial split with tests + green gates if the full split does not fit; do not leave a sprawling WIP.
- Owns ONLY
src/engine/loop.ts. Do NOT touchsrc/orchestrator/cli.ts,resume.ts, or anything a sibling worker owns per the issue brief. - No behavior change: pure moves + thin delegation. Keep all 27 existing importers compiling (importers include
src/cli.ts,src/index.ts,src/orchestrator/pipeline.ts); keepsrc/engine/loop.tsas a re-export facade during the split. - Tests-first is mandatory: test must exist and pass BEFORE the unit it covers is reshaped.
- Monolith:
src/engine/loop.ts:1363HeadlessSession+ config interfacessrc/engine/loop.ts:744(HeadlessSessionConfig),src/engine/loop.ts:1218(ResolvedSessionConfig),src/engine/loop.ts:1208(SessionRunState). - Largest method:
runIterations()spans ~3416–5487 (~2000 lines) — the endgame; do it last, and accept a partial win. - Condensation cluster (extract as a group):
maybeCondenseHistory(),fireBackgroundCondense(),applyBackgroundCondense(),recordCondensationUsage(),recordHandoffCondensationUsage(),writeIterationCapHandoff(),recordAuxLlmUsage(),condensationClient(). Prior art already extracted:src/engine/condense.ts:1-60,src/engine/handoff.ts:42-52. - Handler cluster:
handleNewTask(),handleSwitchMode(),handleExtensionManage(),handleExtensionCall(),handleActivateSkill(),handleReadSkillReference(),handleRequestTool(),handleListTools(). - Pure free functions (lowest-risk first extraction):
combineAbortSignals(),isReadOnlyDirectCall(),isReadOnlyTurnCall(),artifactRejectionNudgeMessage(),stripSupersededReasoning(),countVerifiedCitations(),matchingArtifactFileStatus(),hasUncommittedTrackedChanges(),estimateTokenSize(),summarizeToolArg(),truncateHistory(),sameToolNames(),messagesPrefixEquals(),env*helperssrc/engine/loop.ts:6493-6560. - Existing test style: plain
node:assert/strictscripts viatsx, auto-discovered (scripts/run-tests.mjs:41-55). Main suitesrc/engine/__tests__/loop.test.ts:1-80(4402 lines, FakeLlmClient DI pattern atsrc/engine/__tests__/loop.test.ts:44-65). Focused suites exist for condense/pause/inject/switch-mode — mirror them. - Check tooling:
scripts/check-code-standards.mjs:18limits,scripts/check-architecture.mjs:19limits; baselinesscripts/code-standards-baseline.json,scripts/architecture-baseline.json(content-anchored; regenerate with--write-baselinein the SAME change, never by hand).
- Measure (record numbers for the closing report). Run:
npm run check-standards -- src/engine/loop.ts,npm run check-architecture -- src/engine/loop.ts(or full runs),npm run coverage -- --filter engine. Save outputs; alsowc -l src/engine/loop.ts. - Tests FIRST — pure helpers. Add
src/engine/__tests__/loop-helpers.test.tscovering every pure function to be moved first (combineAbortSignals,isReadOnlyDirectCall/TurnCall,artifactRejectionNudgeMessage,stripSupersededReasoning,countVerifiedCitations+matchingArtifactFileStatuswith temp dirs,estimateTokenSize,summarizeToolArg,truncateHistory,sameToolNames,messagesPrefixEquals, env helpers). Keep each test file <250 lines — split intoloop-helpers-*.test.tsif needed. Runnpx tsx <file>thennpm test -- loop-helpersuntil green. Do not move code until these pass. - Extract pure helpers. Create
src/engine/loop-helpers.ts(or two files if >250 lines:loop-pure.ts+loop-history.tsfor truncate/messages fns). Move the step-2 functions verbatim, fix imports, re-export fromloop.tsso existingimport { … } from "../loop.js"in tests (src/engine/__tests__/loop.test.ts:17-30) keeps working. Verifynpx tsc --noEmit. - Tests FIRST — condensation. Add
src/engine/__tests__/loop-condense.test.tsusing the FakeLlmClient pattern formaybeCondenseHistory/fireBackgroundCondense/applyBackgroundCondense/ usage recorders. Reuse fixtures fromsrc/engine/__tests__/condense.test.ts, not new harness machinery. - Extract condensation. Create
src/engine/loop-condense.tstaking explicit params (messages, budgetTracker, contextWindowTokens) rather than reaching into private session fields;HeadlessSessionmethods atsrc/engine/loop.ts:2584-3415become thin delegates. Follow thesrc/engine/condense.ts/src/engine/handoff.tsmodule idiom (one layout/concern per file). Verify typecheck. - Tests FIRST + extract handlers. Add
src/engine/__tests__/loop-handlers.test.tsforhandleSwitchMode/handleNewTask/ extension + skill handlers with fake executor/registry (see existingswitch-mode.test.ts,new-task.test.ts). Then createsrc/engine/loop-handlers.ts; pass a minimal session-context interface (not the wholeHeadlessSession) to avoid an import cycle (cyclerule allows zero cycles). - runIterations — partial, coherent only. Do NOT attempt to split the whole
src/engine/loop.ts:3416-5487in one go. If time permits, extract ONE seam (e.g. pause/inject pollingsrc/engine/loop.ts:2439-2583→loop-poll.ts, or checkpoint helperssrc/engine/loop.ts:5488-5575→loop-checkpoints.ts). Prefer landing steps 2–6 green over a half-split runIterations. - Baselines + gates (all green, same change).
npx tsc --noEmit;npm test(full);npm run check-standards;npm run check-architecture; regenerate both baselines in the same commit(s);npm run coverage -- --min 24must not regress vs step 1. - Commit / PR. One logical commit per extraction (
git add+git commitwith#127in message). Push branch, open PR (ready, not draft) againstmasterlinking#127. Close with the ORCHESTRATOR_TASK.md template (Files changed / Baseline before+after / Boot check / Residual risk / PR link).
npx tsc --noEmitclean.npm testfull passes (runner:scripts/run-tests.mjs:105-177, fail-fast, sorted).npm run check-standardsandnpm run check-architecturepass with regenerated baselines in the same change.npm run coverage -- --min 24passes;npm run coverage -- --filter enginerecorded before/after (must not regress).- Boot check: N/A (library refactor, no CLI behavior change) — state that explicitly in the closing report unless a touched path warrants
npx tsx src/cli.ts --help.
- Content-anchored baselines: editing a flagged line creates a NEW violation key — expect to fix (not baseline) touched lines; keep lines ≤80 chars and functions ≤20 lines in all new files.
- Cycle risk: new
loop-*.tsmodules must not importloop.tsback (zerocycletolerance). Inject a narrow context interface instead. runIterationsstatefulness (locals atsrc/engine/loop.ts:3419-3456likecompletionNudged,lastExecuteCommandFailed) makes extraction error-prone — default to leaving it intact and claiming the helpers+condensation+handlers win.- Scratch only under
.headlesscode/scratch/; never/tmp(outside-workspace writes fail).