For agentic workers: REQUIRED SUB-SKILL: Use
superpowers:executing-plansto implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking. Do not auto-commit, do not push, and leave all implementation changes unstaged for review.
Goal: 收敛 ZCode 现有通用 compaction 流程的 provider-visible content(compact prompt、summary 后处理、post-compact 上下文组装),提升 compact 后继续任务的完整性。
Architecture: 不新增模型专用分支或模型专用配置;直接更新现有 compact prompt、summary 后处理、post-compact message 组装、recent-context 保留、read-state/file reminder 恢复和 compact summary output cap。实现只落本计划冻结的 compact 逻辑/策略,不自行新增策略、抽象或配置开关。UI 投影继续把 compact 展示成一根 context_compaction divider,底层 provider-visible 保留 recent messages 不应改变聊天 UI。
Tech Stack: TypeScript, Vitest, apps/zcode-cli/packages/core, @zcode/contracts, provider-visible request tests, existing compact/session persistence stores.
context_management、compact_20260112、SDK compactionControl、server compaction、cache edit/cache write/cache prefix sharing。if/else if/else 分支才能实现目标行为,先把该处收敛成清晰的现有边界内 helper/数据流,再落目标行为;重构只服务于降低分支复杂度和表达目标策略,不做顺手架构升级。tools: [] 实现。compact config。pnpm typecheck 和 pnpm lint。compact_20260112、context_management、compaction_delta 只作为排除项记录。PreCompact/PostCompact hook 的外部能力不做;只保留 ZCode 已有事件/日志。read the full transcript at: ...。context_hint/server-assisted microcompact:ZCode 当前没有对应接口;local microcompact 不作为本轮 provider-visible 收敛的默认目标。apps/zcode-cli/packages/core/src/compact/prompt.tsapps/zcode-cli/packages/core/src/runtime/helpers/compact.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active-helpers.tsapps/zcode-cli/packages/core/src/compact/policy.tsapps/zcode-cli/packages/core/src/runtime/methods/microcompact.ts and apps/zcode-cli/packages/core/src/compact/microcompact.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsapps/zcode-cli/packages/core/tests/compact-policy.test.ts and apps/zcode-cli/packages/core/tests/microcompact.test.tsapps/zcode-cli/tools/prompt-trajectory/tests/derive.test.tsFiles:
apps/zcode-cli/packages/core/src/compact/prompt.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsapps/zcode-cli/tools/prompt-trajectory/tests/derive.test.tsInterfaces:
buildCompactPrompt(customInstructions, { mode?: "full" | "recent" | "up_to" })formatCompactSummary(text) returns text shaped as Summary:\n... when <summary> exists.Produce: buildCompactSummaryMessage(summary, options) accepts { suppressFollowup?: boolean; transcriptPath?: string; recentMessagesPreserved?: boolean; replStateCleared?: boolean }.
[ ] Add tests asserting full prompt contains these exact semantic anchors:
CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.Tool calls will be REJECTED and will waste your only turnPreserve any security-relevant instructions or constraints verbatimCurrent WorkOptional Next Step[ ] Add tests asserting recent prompt contains:
RECENT portion of the conversationThe earlier messages are being kept intact and do NOT need to be summarizedAll user messages from the recent portion[ ] Add tests asserting formatCompactSummary("<analysis>x</analysis><summary>abc</summary>") === "Summary:\nabc".
[ ] Add tests asserting buildCompactSummaryMessage("Summary:\nabc", { suppressFollowup: true }) includes:
ran out of contextcovers the earlier portionResume directly[ ] Implement prompt text in prompt.ts using existing file, not a new model-specific policy module.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts apps/zcode-cli/tools/prompt-trajectory/tests/derive.test.ts
Files:
apps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active-helpers.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
buildCompactSummaryRequestOptions(...) or equivalent helper that returns normal tools: this.getTools() and compact metadata.CoreErrorType.ModelError with message Compact summary model attempted to call tools.Consume: existing formatCompactSummaryOrThrow(runtime, result) for final validation.
[ ] Add failing test: compact summary request includes the same visible tool contracts as a normal turn when tools are registered.
[ ] Add failing test: compact summary request does not execute a tool if the model returns a tool call; the runtime records compact failure and no tool result part is persisted.
[ ] Add failing test: provider-visible compact prompt still contains the no-tools warning even though tools are present in the request.
[ ] Replace tools: [] in compact-active.ts with the normal compact-visible tool list, usually this.getTools().
[ ] Keep compact execution single-turn summary-only: if runtime.extractToolCallsFromResult(result) returns any tool call, fail/retry through existing compact error path; do not schedule ToolExecutor.
[ ] Ensure ModelRequest event toolCount reflects the actual exposed compact tools, not zero.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts -t "compact"
Files:
apps/zcode-cli/packages/core/src/runtime/helpers/compact.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
selectCompactEntries(input) returning:
entriesForSummary: RuntimeMessageEntry[]preservedEntries: RuntimeMessageEntry[]groupsPreserved: numbertotalGroups: numberConsume: buildPostCompactRuntimeEntries(activeEntries, summaryEntry, { preservedEntries, postCompactReminderEntries }).
[ ] Add failing test: reactive compact after context overflow summarizes older turns but preserves latest assistant/tool/user group verbatim in the retry request.
[ ] Add failing test: auto compact before a user request still excludes the pending user request from the summary request and includes it in the post-compact request.
[ ] Update grouping helper to split conversation rounds by assistant turn boundary where available; if runtime entries lack assistant IDs, use stable role-order grouping that keeps assistant tool calls with their tool results.
[ ] For CompactTrigger.Auto and CompactTrigger.Reactive, preserve at least the newest complete group plus any trailing pending user entries.
[ ] Keep active/reactive compact summary requests on the full compact prompt even when recent groups are preserved; recent messages are preserved in the post-compact context, not by switching the summary prompt to a recent-only prompt.
[ ] Persist keptMessageCount, groupsPreserved, and totalGroups in compact boundary metadata when available.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts -t "compact"
Files:
apps/zcode-cli/packages/core/src/runtime/helpers/compact.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsapps/zcode-cli/packages/core/tests/read-file-state-hydrator.test.tsInterfaces:
buildPostCompactReadStateReminderEntries(input) returning model-only RuntimeMessageEntry[].Input includes readFileState, workspaceRoot, workingDirectory, maxFiles = 5, maxTotalApproxTokens = 50_000, maxFileApproxTokens = 5_000.
[ ] Add failing test: after reading a small file and compacting, the next provider request contains a model-only reminder with the file path and current contents, after the summary message.
[ ] Add failing test: after reading a too-large file and compacting, the next provider request contains Note: <path> was read before the last conversation was summarized, but the contents are too large to include. Use Read tool if you need to access it.
[ ] Add failing test: compact does not expose plan file, memory file, or denied path through recent-file reminders.
[ ] Implement selection from current runtime readFileState before it is cleared/replaced.
[ ] Sort by most recent read time, cap to 5 files, and enforce total/file token budgets.
[ ] Keep read-state stale guard semantics intact; this task only adds model-visible continuity reminders.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts apps/zcode-cli/packages/core/tests/read-file-state-hydrator.test.ts
Files:
apps/zcode-cli/packages/core/src/runtime/helpers/compact.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
Do not append compact-specific todo state after compact. The generic todo reminder cadence still applies, but compact completion does not immediately restore the current todo list into provider-visible context.
[ ] Update existing todo compact test to expect summary body does not contain Current session todo state (authoritative):.
[ ] Add assertion that post-compact provider request does not contain the restored todo state reminder.
[ ] Remove appendTodoStateToCompactSummary use from compact-active.ts.
[ ] Remove compact-only buildPostCompactTodoReminderEntries wiring.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts -t "todo"
Files:
apps/zcode-cli/packages/core/src/compact/policy.tsapps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/src/runtime/methods/compact.tsapps/zcode-cli/packages/core/src/runtime/methods/context-usage.tsapps/zcode-cli/packages/core/tests/compact-policy.test.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
AutoCompactDecision diagnostics must expose enough budget facts to debug failures:
contextWindoweffectiveContextWindowthresholdtokenCounttokenSourceproviderContextUsageTokenCountproviderInputTokensincrementalTokenCountoutputReserveTokenssummaryMaxOutputTokensDEFAULT_AUTOCOMPACT_OUTPUT_RESERVE_TOKENS = 64_000 and DEFAULT_AUTOCOMPACT_THRESHOLD_PERCENT = 0.9.Summary request max output after investigation: Math.min(20_000, capModelRequestMaxOutputTokens(config.maxOutputTokens)).
[ ] Add a regression test that reproduces the reported failure shape: auto compact decides to compact, then the compact summary request fails with context overflow because requestInputTokens + maxOutputTokens > contextWindow.
[ ] In that test, model the user-observed workaround: after dropping/rewinding several older messages, compact summary succeeds. This proves the failure is budget calculation, not summary prompt semantics.
[ ] Add assertions that log/decision diagnostics identify the bad budget terms: active provider token count, local incremental estimate, summary max output, output reserve, threshold, and context window.
[ ] Check whether buildProviderUsageTokenOverride should prefer contextUsageTokenCount over inputTokens, or use Math.max(inputTokens, contextUsageTokenCount) when provider reports both. Add a failing test for the chosen truth-source rule before changing code.
[ ] Check whether local incremental token estimation after the latest provider usage snapshot can undercount large tool results or non-Anthropic tokenization. Add a failing test where provider usage is old, incremental context is large, and current local estimate lets auto compact start too late.
[ ] Check whether compact summary request budget must reserve compact prompt text and exposed normal tools, now that Task 2 intentionally keeps tools in compact requests. Add a failing test where exposed tool schemas push the compact request over context unless threshold leaves enough buffer.
[ ] Check whether providerPostCompactTokenCount = getUsageTotalTokens(result.usage) is being interpreted as post-compact context size even though it is the summary request usage. If so, add a test that truePostCompactTokenCount is the only re-trigger guard until a real provider count for the next request exists.
[ ] Keep default policy tests on the restored ZCode defaults: 64k output reserve and 90 percent threshold.
[ ] Do not change unknown max output reserve to 20k; only compact summary request max output is capped at 20k.
[ ] Keep explicit config compatibility where bufferTokens, summaryReserveTokens, or threshold overrides are provided.
[ ] Update runtime compact test to assert summary generation request uses max output capped at 20k.
[ ] Implement runtime summary-cap changes without adding new env vars.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/compact-policy.test.ts apps/zcode-cli/packages/core/tests/runtime-compact.test.ts -t "auto compact"
Files:
apps/zcode-cli/packages/core/src/runtime/methods/microcompact.tsapps/zcode-cli/packages/core/src/compact/microcompact.tsapps/zcode-cli/packages/core/tests/microcompact.test.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
context_hint/server fallback 能力,ZCode 当前没有对应接口;本轮不改 local microcompact 的 provider-visible 行为。Runtime compact 收敛路径默认不依赖 microcompact;local microcompact 只保留现有显式 opt-in/安全修复,避免在缺少 context_hint 的情况下破坏 cache hit 或污染 provider-visible context。
[ ] Keep this as an explicit skip in review notes; do not add new microcompact requirements here until ZCode has a context_hint/server compact capability.
[ ] Ensure full compact behavior does not depend on microcompact being enabled.
Files:
apps/zcode-cli/packages/core/src/runtime/methods/compact-active.tsapps/zcode-cli/packages/core/tests/runtime-compact.test.tsInterfaces:
If the frozen behavior strips media before compact summary requests, keep the existing stripping direction and only adjust the provider-visible shape accordingly.
[ ] Add an evidence note in this task before implementation: the fixture/contract test that proves whether media is preserved first or stripped before compact.
[ ] If media is preserved first, add failing test: compact summary request preserves latest image/media content on first attempt when provider supports media.
[ ] If media is preserved first, add failing test: on media-too-large error, compact retries once with media stripped and succeeds.
[ ] If media is stripped before compact, add failing test for that exact provider-visible projection and do not add a retry path.
[ ] Implement only the branch confirmed by the evidence.
[ ] Preserve current prompt-too-long retry behavior only if it already exists in the compact flow; do not add a new retry tier.
[ ] Run: pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts -t "media"
Files:
packages/shared/src/zcode-session-visible-content.tspackages/ui/src/lib/zcodeSessionProjection.tspackages/services/src/zcode-agent/zcodeTaskServiceAdapter.tsInterfaces:
isZCodeCompactSummaryMessage must continue filtering model-only compact summary messages.synthesizeCompactionTimeline must continue rendering only lifecycle compaction parts as context_compaction divider.
[ ] Add regression test with summary message + preserved recent messages + compact lifecycle part.
[ ] Assert visible chat contains exactly one context_compaction divider.
[ ] Assert compact summary model-only message is not rendered as user bubble.
[ ] Do not hide real preserved user messages unless product explicitly wants UI to collapse them; current desired behavior is divider replacing historical compacted content.
[ ] Run targeted UI/projection tests available in repo.
Files:
apps/zcode-cli/tools/prompt-trajectory/tests/derive.test.tsapps/zcode-cli/tools/prompt-trajectory/out/...Scenarios:
Compact after reading a too-large file.
[ ] Generate or update deterministic test fixtures rather than relying on stale out/compact-* artifacts.
[ ] Assert compact request exposes normal tool contracts for provider-visible/cache shape, while compact tool calls are denied before execution.
[ ] Assert compact request final user message is the frozen compact prompt.
[ ] Assert post-compact request order is: context prefix, compact summary message, preserved recent entries, post-compact reminders, pending user input.
[ ] Assert UI/session visible projection still hides compact summary body.
pnpm vitest run apps/zcode-cli/packages/core/tests/runtime-compact.test.ts apps/zcode-cli/packages/core/tests/compact-policy.test.ts apps/zcode-cli/packages/core/tests/microcompact.test.ts apps/zcode-cli/packages/core/tests/read-file-state-hydrator.test.ts apps/zcode-cli/tools/prompt-trajectory/tests/derive.test.tspnpm typecheckpnpm lintgit status --short and confirm changes are unstaged.tools: []; it exposes normal tools but rejects any compact-time tool call before execution.context_hint/server compact capability; full compact provider-visible behavior must not depend on microcompact.