diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ef5f01..6c2dc50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. +## [1.0.4] - 2026-09-11 + +### Added + +- **`/ctx-pause` & `/ctx-resume` — per-session context-control suspension** — typing `/ctx-pause` suspends the measured-context regime for the current session only: read gates (watermark tiers and the self-read budget) and force-tier auto-handover stop intervening, while measurement keeps recording so pace estimates stay intact after `/ctx-resume` restores enforcement. The commands work without model cooperation — the injected marker line is captured by the plugin at the event layer (idempotent; per-session in-memory state, so an opencode restart auto-resumes control and session deletion cleans it). While paused the `[WATERMARK:SESSION]` banner keeps reporting measured numbers with a PAUSED notice, and the only override is a pure warning at ≥95% of the model's real context window (overflow still hard-errors the session regardless of pause). Shell subagent caps are never suspended. + ## [1.0.3] - 2026-09-10 ### Added diff --git a/package.json b/package.json index 26e8c51..b0c3c6c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-switchman", - "version": "1.0.3", + "version": "1.0.4", "description": "OpenCode orchestration plugin: six-lane shell matrix dispatch (hard ROUTE_META validation / breaker self-healing / probes / three-pool quota awareness / cost-aware tiebreaker)", "license": "MIT", "repository": { diff --git a/src/commands-md.ts b/src/commands-md.ts index 983801a..7039ccb 100644 --- a/src/commands-md.ts +++ b/src/commands-md.ts @@ -9,6 +9,7 @@ // (review head preferred; hard head's -ro face as fallback), dispatch goes through the standard six gates + auto-redirect] import { paths } from "./state" import { LANG_SETTINGS_FILE } from "./lang-config" +import { CTX_PAUSE_MARKER, CTX_RESUME_MARKER } from "./context-watch" const q = (p: string): string => JSON.stringify(p) @@ -114,3 +115,34 @@ export function expertCommandMd(): string { "", ].join("\n") } + +// [2026-09-11]-[/ctx-pause //ctx-resume: per-session context-control suspension. The marker line below is the whole +// mechanism: the plugin captures it from the user message at the event layer (context-watch.ctxControlMarkerOf) and +// flips an in-memory set — session-scoped, restart = auto-resume, session.deleted = cleaned. Measurement keeps +// running while paused (resume must not lose pace history); shell subagent caps are NOT suspended. The model is told +// to just confirm briefly — enforcement never depends on its goodwill] +export function ctxPauseCommandMd(): string { + return [ + "---", + "description: pause this session's context watermark control (read gates + self-read budget + auto-handover) until /ctx-resume or an opencode restart; this session only, measurement continues", + "---", + "", + `${CTX_PAUSE_MARKER} The user paused opencode-switchman's context control for THIS session — the plugin captures this marker itself; no tool call is needed.`, + "", + "Confirm in one short sentence: context read gates, self-read budget and auto-handover are suspended for this session (the [WATERMARK:SESSION] line keeps reporting measured numbers); control resumes via /ctx-resume or an opencode restart. Note that overflowing the model's context window still hard-errors the session regardless of pause. Then continue the task at hand without further ceremony.", + "", + ].join("\n") +} + +export function ctxResumeCommandMd(): string { + return [ + "---", + "description: resume this session's context watermark control (undo /ctx-pause); read gates, self-read budget and auto-handover go live again from the next turn", + "---", + "", + `${CTX_RESUME_MARKER} The user resumed opencode-switchman's context control for THIS session — the plugin captures this marker itself; no tool call is needed.`, + "", + "Confirm resumption in one short sentence and read the next [WATERMARK:SESSION] banner line: if it reports a soft/hard/force tier, follow its directive immediately (delegate reads, wrap up, or stand by for auto-handover). Then continue the task at hand.", + "", + ].join("\n") +} diff --git a/src/context-watch.ts b/src/context-watch.ts index 4f0b18d..85da39d 100644 --- a/src/context-watch.ts +++ b/src/context-watch.ts @@ -51,6 +51,37 @@ export function watermarkLevel(tokens: number, t: ContextThresholds): WatermarkL return "ok" } +// [2026-09-11]-[/ctx-pause //ctx-resume: per-session suspension of context control — the commands inject a fixed +// marker line into the user message and the plugin captures it at the event layer (mechanism, not model goodwill); +// markers live here as the single source shared by the command templates and the capture hook] +export const CTX_PAUSE_MARKER = "[CTX-CONTROL-PAUSE]" +export const CTX_RESUME_MARKER = "[CTX-CONTROL-RESUME]" + +export type CtxControlAction = "pause" | "resume" + +/** Scan a user message's text parts for the pause/resume marker; first match wins (null = unrelated message) */ +export function ctxControlMarkerOf(info: unknown): CtxControlAction | null { + const parts = (info as { parts?: Array<{ type?: unknown; text?: unknown }> } | null | undefined)?.parts + if (!Array.isArray(parts)) return null + for (const p of parts) { + if (p?.type === "text" && typeof p.text === "string") { + if (p.text.includes(CTX_PAUSE_MARKER)) return "pause" + if (p.text.includes(CTX_RESUME_MARKER)) return "resume" + } + } + return null +} + +/** [2026-09-11]-[while paused, the ONLY override of a session's ctx-control pause: a pure warning when the measured + * context reaches ≥95% of the model's real context window (overflow hard-errors the session regardless of pause; + * text only — the pause promise of no denies is kept). Unknown window → empty (fail-open, numbers only) */ +export function pausedWindowWarning(wmTokens: number, windowTokens?: number): string { + if (typeof windowTokens !== "number" || !Number.isFinite(windowTokens) || windowTokens <= 0) return "" + return wmTokens >= windowTokens * 0.95 + ? `—[WARNING] context window ≥95% full (~${fmtK(wmTokens)}/${fmtK(windowTokens)}): overflow hard-errors this session regardless of pause; compact or run /handover now` + : "" +} + /** Verification/delivery commands pass through (tiny output, no context injection): delivery git (state-changing + * bounded-output reads, including add/commit/push wrap-up), test/lint/typecheck, build/pack — wrap-up verification * and delivery still work at every watermark. Archaeology git is excluded here and handled as scanning below. */ diff --git a/src/index.ts b/src/index.ts index b9c65c5..e7b4843 100644 --- a/src/index.ts +++ b/src/index.ts @@ -32,9 +32,9 @@ import { READ_CLASS_TOOLS, estimateContextTokens, thresholdsOf, watermarkLevel, budgetGateDecision, estimateReadRange, estimateOutputTokens, readBudgetOf, turnBudgetOf, capThresholdsByWindow, subagentCapOf, capByWindow, - subagentCapDenyMessage, subagentResumeDenyMessage, + subagentCapDenyMessage, subagentResumeDenyMessage, ctxControlMarkerOf, pausedWindowWarning, } from "./context-watch" -import type { ReadEstimate, FileSample, ContextThresholds } from "./context-watch" +import type { CtxControlAction, ReadEstimate, FileSample, ContextThresholds } from "./context-watch" import { backupSession, compactSession, v1HandoverPort, type HandoverResult } from "./handover-core" import { logDecision, BILLING_API_BOOST } from "./scoring" import type { WaterFactor, DecisionRecord } from "./scoring" @@ -46,7 +46,7 @@ import { injectShells, injectShellDefs, selectInjectableDefs } from "./shells" import { buildBanner, shortName, providerStatusEntries } from "./banner" import { refreshSelfUpdate, updateBannerText, ensureUpdateCommands, detectLoadMode, pluginCliPath } from "./selfupdate" import { loadPoolConfig, overrideSummary } from "./user-overrides" -import { poolConfigCommandMd, modelRankCommandMd, expertCommandMd, langCommandMd } from "./commands-md" +import { poolConfigCommandMd, modelRankCommandMd, expertCommandMd, langCommandMd, ctxPauseCommandMd, ctxResumeCommandMd } from "./commands-md" import { billingOfProvider, loadUserConfig, resolveEffectiveOptions, routingPeakActive, routePolicy, DEFAULT_DELEGATION_FLOOR } from "./config" import { poolForProviderId } from "./provider-config" import { runDoctor } from "./doctor" @@ -168,6 +168,16 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const turnReadUsage = new Map() const wmHistory = new Map() const lastUserMsg = new Map() + // [2026-09-11]-[/ctx-pause //ctx-resume: per-session context-control suspension — the commands inject a fixed marker + // and the capture happens at the event layer (never model goodwill). While paused: read gates + self-read budget + // charging + auto-handover are suspended for that session; measurement keeps recording (resume keeps pace history); + // shell subagent caps are NOT suspended; restart = auto-resume (fail-safe direction); session.deleted cleans] + // [2026-09-11 fix]-[live verification showed message.updated's info carries no parts in the real host (marker in + // the user turn, zero capture lines) — the reliable capture lives in experimental.chat.messages.transform where + // every round-trip exposes full {info, parts} pairs (shape production-verified by the image relay); the event + // handler stays as an opportunistic first-try] + const ctxPaused = new Set() + const ctxMarkerSeen = new Map() // per-session last-processed user message id (transform-path dedup) // [2026-09-05]-[window cap: current session model key (providerID/modelID from message.updated assistant messages; // registry-keyed, unlike chat.params' sessionModelKey which can be stale/absent when a turn never fires chat.params)] const sessionMsgModel = new Map() @@ -224,6 +234,18 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { return /-mx-/.test(sessionAgent.get(sessionID) ?? "") } + /** [2026-09-11 fix]-[shared flip for both capture paths (message.updated event + chat.messages.transform); + * idempotent — a re-fire of the same marker never double-logs]-[see ctxPaused declaration for why the transform + * path exists: the real host's event info carries no parts] */ + function applyCtxControlAction(sid: string, act: CtxControlAction | null): void { + if (act === "pause" && !ctxPaused.has(sid)) { + ctxPaused.add(sid) + appendStatusLog(`ctx control paused for session ${sid} (/ctx-pause): read gates + self-read budget + auto-handover suspended; measurement continues`) + } else if (act === "resume" && ctxPaused.delete(sid)) { + appendStatusLog(`ctx control resumed for session ${sid} (/ctx-resume): read gates + auto-handover live again`) + } + } + function kk(n: number): string { return `${Math.round(n / 1000)}k` } // [2026-09-05]-[v1 read budget helpers: file head sampling for read-cost estimation, per-turn spend bookkeeping, @@ -350,6 +372,17 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const growth = pace ? ` | growth ~${kk(pace.delta)}/turn, ~${pace.turnsToHard} turns to hard` : " | growth unknown yet" + // [2026-09-11]-[/ctx-pause: control suspended for this session — keep reporting the measured numbers (observation + // never pauses) + the resume hint; the only override is the ≥95%-window pure warning (context-watch.pausedWindowWarning — + // text only, no denies; unknown window fails open to numbers)] + if (ctxPaused.has(sessionID)) { + let win: number | undefined + try { + const key = sessionMsgModel.get(sessionID) ?? sessionModelKey.get(sessionID) + win = key ? contextWindowOf(metaIndexRuntime ?? bundledModelIndex(), key) : undefined + } catch { /* fail-open: numbers only */ } + return `[WATERMARK:SESSION] measured session context ~${kk(wm.tokens)} (soft ${kk(t.soft)}/hard ${kk(t.hard)}/force ${kk(t.force)})${growth} | ctx control PAUSED by /ctx-pause (read gates + auto-handover suspended for this session; resume with /ctx-resume)${pausedWindowWarning(wm.tokens, win)}` + } const base = `[WATERMARK:SESSION] measured session context ~${kk(wm.tokens)} (soft ${kk(t.soft)}/hard ${kk(t.hard)}/force ${kk(t.force)})${growth} | self-read this turn ${used}/${cap}` if (level === "ok") return base if (level === "soft") return `${base}—past soft: prefer delegating new reads/scans to an economy shell (scouter/clerk) (self-read budget still open — bounded reads under the cap pass)` @@ -1116,6 +1149,9 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (options.context?.gates !== true) return const sid = input.sessionID if (!sid || isShellOrInternalSession(sid)) return + // [2026-09-11]-[/ctx-pause: whole gate suspended for this session — both the self-read budget and the watermark + // tiers fall through ("release context control" in full); the no-vision image guard above stays (not ctx control)] + if (ctxPaused.has(sid)) return const wm = sessionWatermark.get(sid) if (!wm) return const t = sessionThresholds(sid) @@ -1257,6 +1293,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-05]-[/switchman-lang: show/reconfigure the project language preference (marker-question re-ask // flows through the same plugin-side capture; see commands-md.langCommandMd)] "switchman-lang": { template: langCommandMd(options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME), description: "Show or reconfigure this project's language preference (conversation / code comments & commit messages / documents)" }, + // [2026-09-11]-[/ctx-pause //ctx-resume: per-session context-control suspension — the marker inside the + // template is captured at the event layer (context-watch.ctxControlMarkerOf); session-scoped, restart auto-resumes] + "ctx-pause": { template: ctxPauseCommandMd(), description: "Pause this session's context watermark control (read gates + self-read budget + auto-handover) until /ctx-resume or an opencode restart; this session only, measurement continues" }, + "ctx-resume": { template: ctxResumeCommandMd(), description: "Resume this session's context watermark control (undo /ctx-pause); gates and auto-handover go live again from the next turn" }, // [2026-09-04]-[removed the /handover conversational registration: moved to direct TUI palette execution (fork backup + compaction of the // current session, no AI in the loop); opencode's built-in session.fork (message-selection fork dialog) also occupies /fork, // so the plugin no longer registers a same-name command, avoiding dual entries]- @@ -1467,6 +1507,24 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // persistCache deduplicates disk writes across round-trips] "experimental.chat.messages.transform": async (_input, output) => { try { + // [2026-09-11 fix]-[ctx-pause//ctx-resume capture runs here, before the relay early-returns: every round-trip + // exposes full {info, parts} pairs (production-verified by the image relay), unlike message.updated whose info + // carries no parts in the real host. Per-session last-seen id keeps it O(1) per turn; only the LAST user + // message is scanned, so a marker missed on its turn is not backfilled (user re-sends the command)] + try { + const tm = (output as any)?.messages + if (Array.isArray(tm) && tm.length > 0) { + let lastU: { info: any; parts: unknown[] } | null = null + for (let i = tm.length - 1; i >= 0; i--) { + if (tm[i]?.info?.role === "user") { lastU = tm[i]; break } + } + const msid = typeof lastU?.info?.sessionID === "string" ? lastU.info.sessionID : undefined + if (lastU && msid && !isShellOrInternalSession(msid) && ctxMarkerSeen.get(msid) !== lastU.info.id) { + ctxMarkerSeen.set(msid, lastU.info.id) + applyCtxControlAction(msid, ctxControlMarkerOf(lastU)) + } + } + } catch { /* fail-open */ } if (options.relay?.image === false) return const msgs = (output as any)?.messages if (!Array.isArray(msgs) || msgs.length === 0) return @@ -1753,7 +1811,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // to the per-turn budget from the result payload size (main sessions only, mirroring the before-hook's shell-session // exemption; ≥100-token charges are logged as the v2 data substrate; fail-open)] try { - if ((hookInput.tool === "bash" || READ_CLASS_TOOLS.has(hookInput.tool)) && hookInput.tool !== "task" && sid && !isShellOrInternalSession(sid)) { + if ((hookInput.tool === "bash" || READ_CLASS_TOOLS.has(hookInput.tool)) && hookInput.tool !== "task" && sid && !isShellOrInternalSession(sid) && !ctxPaused.has(sid)) { const len = JSON.stringify((hookOutput as any)?.output ?? "").length const charge = estimateOutputTokens(len) chargeTurnRead(sid, charge) @@ -1763,6 +1821,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { try { if (options.context?.autoHandover === false) return if (!sid || isShellOrInternalSession(sid)) return + // [2026-09-11]-[/ctx-pause: auto-handover suspended for this session; the watermark line keeps a ≥95%-window warning] + if (ctxPaused.has(sid)) return const wm = sessionWatermark.get(sid) if (!wm) return if (watermarkLevel(wm.tokens, sessionThresholds(sid)) !== "force") return @@ -1859,10 +1919,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const sid = props?.sessionID const info = props?.info if (typeof sid === "string" && !isShellOrInternalSession(sid)) { - if (info?.role === "user") { - lastUserMsg.set(sid, info.id) - turnReadUsage.delete(sid) - // [2026-09-07]-[lang ask was one-shot per session and the model routinely skipped the turn-1 directive + if (info?.role === "user") { + lastUserMsg.set(sid, info.id) + turnReadUsage.delete(sid) + // [2026-09-11]-[opportunistic first-try: if the host ever ships parts on the event's info this fires + // before the transform pass; in the real host info carries no parts so this no-ops and the reliable + // capture lives in experimental.chat.messages.transform (see applyCtxControlAction)] + applyCtxControlAction(sid, ctxControlMarkerOf(info)) + // [2026-09-07]-[lang ask was one-shot per session and the model routinely skipped the turn-1 directive // (buried under the injected protocol) — reset the latch on every new user message so the ask directive // re-surfaces each user turn until the config is persisted; impact: unconfigured projects get asked // every turn instead of silently never (decline still re-asks; escape hatch = lang.ask:false)] @@ -1924,6 +1988,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { lastUserMsg.delete(sid) sessionMsgModel.delete(sid) sessionTodos.delete(sid) + ctxPaused.delete(sid) // [2026-09-11]-[/ctx-pause: per-session suspension follows the session out] + ctxMarkerSeen.delete(sid) // [2026-09-11 fix]-[transform-path dedup map follows the session out too] workspace.forget(sid) langAsked.delete(sid) langGateWaived.delete(sid) diff --git a/src/version.ts b/src/version.ts index dbfea85..e050823 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ // Generated at build time: run bun scripts/gen-version.ts -export const PLUGIN_VERSION = "1.0.3" +export const PLUGIN_VERSION = "1.0.4" diff --git a/test/ctx-pause.test.ts b/test/ctx-pause.test.ts new file mode 100644 index 0000000..da586ba --- /dev/null +++ b/test/ctx-pause.test.ts @@ -0,0 +1,195 @@ +// [2026-09-11]-[/ctx-pause //ctx-resume behavioral contract: the command marker injected into a user message is +// captured at the event layer and suspends context control for THAT session only — read gates (self-read budget + +// watermark tiers) and auto-handover fall through while paused; measurement keeps recording; the watermark line keeps +// reporting numbers with a PAUSED notice and a ≥95%-window warning (pure text, no denies); resume restores +// enforcement; re-fired captures never double-log (idempotent); session.deleted cleans the suspension] +import { expect, test } from "bun:test" +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const configDir = mkdtempSync(join(tmpdir(), "switchman-ctxpa-config-")) +const stateDir = mkdtempSync(join(tmpdir(), "switchman-ctxpa-state-")) +const projectDir = mkdtempSync(join(tmpdir(), "switchman-ctxpa-project-")) +process.env.OPENCODE_CONFIG_DIR = configDir +process.env.SWITCHMAN_STATE = stateDir +// catalog entry present from module load (the model-catalog index is cached at first read; a mid-file rewrite would +// never be seen) — harmless for the other tests: their sessions carry no model face, so no threshold clamping occurs +writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: { "copilot/glm-5.3": { contextWindow: 128_000 } } })) + +import { SwitchmanPlugin } from "../src/index" +import { CTX_PAUSE_MARKER, CTX_RESUME_MARKER, ctxControlMarkerOf, pausedWindowWarning } from "../src/context-watch" + +function readStatusLog(): string { + const p = join(stateDir, "status-log.json") + return existsSync(p) ? readFileSync(p, "utf8") : "" +} + +const fakeClient = { + provider: { list: async () => [] }, + session: { + async fork(opts: any) { return { data: { id: `${opts?.path?.id}_fork`, title: "T (fork)" } } }, + async update() { return { data: {} } }, + async list() { return { data: [] } }, + async get(opts: any) { return { data: { id: opts?.path?.id, title: "T", directory: projectDir } } }, + async summarize() { return { data: true } }, + }, +} + +async function boot(client: unknown = fakeClient) { + // legacy mode (same recipe as todo-nudge.test.ts): deterministic session classification without the dynamic manager + const hooks = await SwitchmanPlugin({ client, directory: projectDir } as any, { matrix: { mode: "legacy" } } as any) + const emit = (event: any) => hooks.event!({ event } as any) + const user = (sid: string, text: string) => + emit({ type: "message.updated", properties: { sessionID: sid, info: { id: `msg_${sid}_${text.length}`, role: "user", parts: [{ type: "text", text }] } } }) + const watermark = (sid: string, tokens: number) => + emit({ type: "message.updated", properties: { sessionID: sid, info: { role: "assistant", tokens: { input: tokens, output: 1_000, reasoning: 0, cache: { read: 0 } } } } }) + const glob = (sid: string) => + hooks["tool.execute.before"]!({ sessionID: sid, tool: "glob", callID: `call_${sid}_${Math.random()}` } as any, { args: { pattern: "*.ts" } } as any) + const system = async (sessionID: string) => { + const output = { system: [] as string[] } + await hooks["experimental.chat.system.transform"]!({ sessionID } as any, output as any) + return output.system + } + return { hooks, emit, user, watermark, glob, system } +} + +test("ctx-pause: marker suspends the hard-tier read gate for this session only; resume restores; captures idempotent", async () => { + const { user, watermark, glob } = await boot() + const sid = "ses_ctxpa_main" + const other = "ses_ctxpa_other" + + await watermark(sid, 85_000) // defaults 60k/80k/120k → hard tier + await expect(glob(sid)).rejects.toThrow(/hard watermark/) + + // pause marker → gate open (no throw, args untouched) + await user(sid, `${CTX_PAUSE_MARKER} pause this session`) + await glob(sid) + + // a re-fired message.updated of the same marker never double-logs (idempotent flip) + await user(sid, `${CTX_PAUSE_MARKER} pause this session`) + expect(readStatusLog().split(`ctx control paused for session ${sid}`).length - 1).toBe(1) + + // session scoping: another session at the same tier stays gated + await watermark(other, 85_000) + await expect(glob(other)).rejects.toThrow(/hard watermark/) + + // resume restores enforcement; idempotent on re-fire + await user(sid, `${CTX_RESUME_MARKER} resume this session`) + await expect(glob(sid)).rejects.toThrow(/hard watermark/) + await user(sid, `${CTX_RESUME_MARKER} resume this session`) + expect(readStatusLog().split(`ctx control resumed for session ${sid}`).length - 1).toBe(1) +}) + +test("ctx-pause: transform-path capture (real host shape — parts live on the message, not on info)", async () => { + const { hooks, watermark, glob, system } = await boot() + const sid = "ses_ctxpa_transform" + // [2026-09-11 fix]-[live verification: the real host's message.updated info carries no parts, so capture had to + // move to experimental.chat.messages.transform where {info, parts} pairs arrive per round-trip] + const turn = (msgId: string, text: string) => + hooks["experimental.chat.messages.transform"]!({ sessionID: sid } as any, { + messages: [{ info: { id: msgId, role: "user", sessionID: sid }, parts: [{ type: "text", text }] }], + } as any) + + await watermark(sid, 85_000) // hard tier armed + await expect(glob(sid)).rejects.toThrow(/hard watermark/) + + await turn("msg_t1", `${CTX_PAUSE_MARKER} pause this session`) // info has NO parts field — the real shape + await glob(sid) // gate suspended + + // seen-map: the same message id re-arriving in later round-trips never double-logs + await turn("msg_t1", `${CTX_PAUSE_MARKER} pause this session`) + expect(readStatusLog().split(`ctx control paused for session ${sid}`).length - 1).toBe(1) + + // watermark line keeps reporting with the PAUSED notice + expect((await system(sid)).some((l) => l.includes("ctx control PAUSED"))).toBe(true) + + // resume via the transform path restores enforcement + await turn("msg_t2", `${CTX_RESUME_MARKER} resume this session`) + await expect(glob(sid)).rejects.toThrow(/hard watermark/) +}) + +test("ctx-pause: auto-handover suspended while paused (fresh session — no cooldown interference)", async () => { + const forks: string[] = [] + const recordingClient = { + ...fakeClient, + session: { + ...fakeClient.session, + async fork(opts: any) { forks.push(opts?.path?.id); return { data: { id: `${opts?.path?.id}_fork`, title: "T (fork)" } } }, + }, + } + const { hooks, user, watermark } = await boot(recordingClient) + const output = { message: async () => {} } as any + + // control (unpaused): force tier → backup fork fires (the standard auto-handover contract) + const a = "ses_ctxpa_ho_a" + await watermark(a, 130_000) + await hooks["tool.execute.after"]!({ sessionID: a, tool: "read" } as any, output) + expect(forks).toContain(a) + + // paused session: same force tier → no backup, hook returns fast + const b = "ses_ctxpa_ho_b" + await user(b, `${CTX_PAUSE_MARKER} pause`) + await watermark(b, 130_000) + const t0 = Date.now() + await hooks["tool.execute.after"]!({ sessionID: b, tool: "read" } as any, output) + expect(Date.now() - t0).toBeLessThan(5_000) + expect(forks).not.toContain(b) +}) + +test("ctx-pause: watermark line keeps numbers + PAUSED notice; resume returns tiered directives", async () => { + const { user, emit, system } = await boot() + const sid = "ses_ctxpa_line" + const assistant = (tokens: number) => + emit({ type: "message.updated", properties: { sessionID: sid, info: { role: "assistant", modelID: "glm-5.3", providerID: "copilot", tokens: { input: tokens, output: 0, reasoning: 0, cache: { read: 0 } } } } }) + + await assistant(70_000) // soft tier under the defaults + await user(sid, `${CTX_PAUSE_MARKER} pause`) + let sys = await system(sid) + let line = sys.find((l) => l.startsWith("[WATERMARK:SESSION]")) + expect(line).toContain("ctx control PAUSED by /ctx-pause") + expect(line).toContain("~70k") + expect(line).toContain("resume with /ctx-resume") + expect(line).not.toContain("[WARNING]") + + // resume → tiered directives return (85k ≥ hard 80k) + await assistant(85_000) + await user(sid, `${CTX_RESUME_MARKER} resume`) + sys = await system(sid) + line = sys.find((l) => l.startsWith("[WATERMARK:SESSION]")) + expect(line).not.toContain("PAUSED") + expect(line).toContain("hard watermark exceeded") +}) + +test("ctx-pause: session.deleted cleans the suspension (fresh watermark is unpaused again)", async () => { + const { user, watermark, emit, system } = await boot() + const sid = "ses_ctxpa_del" + await watermark(sid, 85_000) + await user(sid, `${CTX_PAUSE_MARKER} pause`) + expect((await system(sid)).some((l) => l.includes("ctx control PAUSED"))).toBe(true) + + await emit({ type: "session.deleted", properties: { info: { id: sid } } }) + await watermark(sid, 85_000) // re-seed: the session's watermark map was cleaned with it + expect((await system(sid)).some((l) => l.includes("ctx control PAUSED"))).toBe(false) +}) + +test("ctx-pause: marker detection is pure and shape-defensive", () => { + expect(ctxControlMarkerOf({ parts: [{ type: "text", text: `prefix ${CTX_PAUSE_MARKER} suffix` }] })).toBe("pause") + expect(ctxControlMarkerOf({ parts: [{ type: "text", text: `prefix ${CTX_RESUME_MARKER} suffix` }] })).toBe("resume") + expect(ctxControlMarkerOf({ parts: [{ type: "file", path: "/x" }] })).toBe(null) + expect(ctxControlMarkerOf({ parts: [{ type: "text", text: "unrelated" }] })).toBe(null) + expect(ctxControlMarkerOf(null)).toBe(null) + expect(ctxControlMarkerOf({})).toBe(null) +}) + +test("ctx-pause: pausedWindowWarning fires only at ≥95% of a known window (pure, fail-open on unknown)", () => { + // the ≥95%-window override is the ONLY warning a pause cannot suppress (overflow hard-errors regardless) + expect(pausedWindowWarning(125_000, 128_000)).toContain("[WARNING] context window ≥95% full (~125k/128k)") + expect(pausedWindowWarning(121_600, 128_000)).toContain("[WARNING]") // exactly 95% + expect(pausedWindowWarning(121_599, 128_000)).toBe("") // just under + expect(pausedWindowWarning(70_000, 128_000)).toBe("") + // unknown/invalid window → fail-open, numbers only (the paused line keeps its no-warning form) + expect(pausedWindowWarning(500_000, undefined)).toBe("") + expect(pausedWindowWarning(500_000, 0)).toBe("") + expect(pausedWindowWarning(500_000, Number.NaN)).toBe("") +})