From 0437abbe30a095ceb1a28da8e03dd28efdd0e3f7 Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 10 Oct 2026 03:37:05 +0800 Subject: [PATCH] factory 0.1.22: Claude Code's restored-context turn after /compact reaches Factory adapted (#68, Vigilans) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After /compact, Claude Code 2.1.280 sends the files it restores and the session's runtime context as one system text block with no reminder wrappers and no opening token marker: restored-file notes ("Note: was read before the last conversation was summarized…"), "Called the Read tool with the following input: {…}" and its result, "# Environment\nYou have been invoked in the following environment:", the model line, token and date. The reporter's bisect shows Factory 403s on each of those fixed fragments, and 0.1.21 matched none of them: SYSTEM_ENV_CONTEXT is anchored at the block's start, COMPACT_READ / COMPACT_FILE need a standalone wrapped reminder, and the token-prefixed bundle path needs a leading token marker. restoredContext recognizes the complete turn: its first paragraph is a generated restored-file note or Read call (as COMPACT_FILE / COMPACT_READ would match it wrapped), and a later paragraph, before any hook output, is the generated environment paragraph or a token marker. Then announcedContext adapts every paragraph from the first on, with the existing compat spellings (Previously read file…, # Runtime context / The session environment is:, Current model name / Model ID / Model knowledge cutoff) and the lossless JSON encoding of Read results; everything else stays byte-for-byte. It runs for system-role strings and text blocks and for the same block folded into user text. An adapted turn no longer opens with the generated note, so a second pass is byte-for-byte. Quoted, incomplete (no environment or token), hook-owned and assistant forms are left untouched. Run: bun test (packages/factory: 116 pass; repo: 1010 pass, 0 fail), bun scripts/check.mjs (all pass). The two new tests use the issue's literal fragments (several notes, Read call + result, environment, model line with claude-opus-5-5[1m], token, date); the adapting one fails on 0.1.21's index.mjs, and removing the env/token requirement, the hook guard, the user-text path or starting at paragraph 1 each turns a test red. PR #66 applied on top passes too (119 factory tests). Stubbed fetch only; no request was sent to Factory (no Factory account here). --- packages/factory/README.md | 7 ++ packages/factory/index.mjs | 30 +++++++- packages/factory/package.json | 2 +- packages/factory/request.test.mjs | 113 ++++++++++++++++++++++++++++++ 4 files changed, 149 insertions(+), 3 deletions(-) diff --git a/packages/factory/README.md b/packages/factory/README.md index c7d4c27..138b307 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -143,6 +143,13 @@ When runtime notifications precede the skill update, the adapter recognizes the complete skill-header and bullet-list paragraphs inside a token-terminated bundle. It preserves MCP connection errors, other notifications, mode updates and custom skill descriptions while adapting the known built-in description. +After `/compact`, Claude Code also sends the files it restores and the +runtime context as one turn that opens with an unwrapped restored-file note +or Read call, with no token marker first. When that turn also carries the +generated environment paragraph or a token marker before any hook output, +each fixed paragraph (file notes, Read calls and results, environment, model +line) is adapted as in a token-prefixed bundle; everything else stays +byte-for-byte. Quoted, incomplete and hook-owned forms are left alone. Factory can also refuse fixed client phrases quoted in tool results, such as the identity/environment definitions printed when inspecting this plugin's diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index 987668f..6eb4da0 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -685,6 +685,8 @@ const SYSTEM_SKILL_CONTEXT = /^The following skills are available for use with t function systemContext(text) { text = changedFileContext(text) text = announcedSkills(text) + const restored = restoredContext(text) + if (restored !== null) return restored if (SYSTEM_TOKEN_OPENING.test(text) || SYSTEM_SKILL_CONTEXT.test(text)) return announcedContext(text) if (HOOK_OUTPUT.test(text) || text.startsWith(DEFERRED_TOOLS_OPENING)) { const at = text.indexOf(HOOK_CONTEXT) @@ -714,11 +716,11 @@ function announcedSkills(text) { // Claude Code also announces several reminders as one system turn, with // token context and no system-reminder wrappers. Only known metadata // paragraphs change; numbered file contents and the hook's own output stay. -function announcedContext(text) { +function announcedContext(text, start = 1) { const parts = changedFileContext(text).split(/\n\n(?!\.\.\. \[)/) const open = "\n", close = "\n" let quoteChangedFiles = true - for (let i = 1; i < parts.length; i++) { + for (let i = start; i < parts.length; i++) { const part = parts[i] const hook = part.replace(/^\n/, "") if (HOOK_OUTPUT.test(hook)) break @@ -747,6 +749,28 @@ function announcedContext(text) { return parts.join("\n\n") } +// After /compact, Claude Code (2.1.280) sends the files it restores and the +// session's runtime context as one turn without reminder wrappers or an +// opening token marker: restored-file notes, Read calls and their results, +// the environment, the model line, token and date. Each fixed fragment is +// refused on its own (plugins#68). Require the generated restored-file +// opening and the generated environment paragraph or a token marker before +// the first hook; then each paragraph is adapted as in a token-prefixed +// bundle, the rest kept byte-for-byte. An adapted block no longer opens +// with the generated note, so a second pass leaves it as it is. +function restoredContext(text) { + const parts = text.split(/\n\n(?!\.\.\. \[)/) + const result = parts[0].indexOf("\n" + READ_RESULT_HEADER) + const opening = "\n" + (result < 0 ? parts[0] : parts[0].slice(0, result)) + "\n" + if (!COMPACT_FILE.test(opening) && !COMPACT_READ.test(opening)) return null + if (compactContext(opening) === opening) return null + for (const part of parts.slice(1)) { + if (HOOK_NOTIFICATION.test(part.replace(/^\n/, ""))) return null + if (SYSTEM_ENV_CONTEXT.test(part + "\n") || /^\d+ tokens left<\/total_tokens>$/.test(part)) return announcedContext(text, 0) + } + return null +} + function generatedContext(text) { const environment = SYSTEM_ENV_CONTEXT.test(text) if (!environment && !((SYSTEM_MODEL_UPDATE.test(text) || SYSTEM_ENV_UPDATE.test(text)) && SYSTEM_TOKEN_CONTEXT.test(text))) return text @@ -801,6 +825,8 @@ function compactContext(text, quoteChangedFiles = true) { // A translating gateway can fold an announced system turn into user text. if (SYSTEM_TOKEN_OPENING.test(text) || SYSTEM_SKILL_CONTEXT.test(text)) return announcedContext(text) if (HOOK_OUTPUT.test(text) || text.startsWith(DEFERRED_TOOLS_OPENING)) return systemContext(text) + const restored = restoredContext(text) + if (restored !== null) return restored const result = readResultText(text) if (result !== null) return result const changedFile = quoteChangedFiles && text.startsWith("\n") ? changedFileText(text) : null diff --git a/packages/factory/package.json b/packages/factory/package.json index b432867..2a721ba 100644 --- a/packages/factory/package.json +++ b/packages/factory/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-factory-auth", - "version": "0.1.21", + "version": "0.1.22", "description": "Sign in to a Factory (Droid) subscription from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/factory/request.test.mjs b/packages/factory/request.test.mjs index e8f9331..5cce05c 100644 --- a/packages/factory/request.test.mjs +++ b/packages/factory/request.test.mjs @@ -1145,3 +1145,116 @@ test("preserves quoted or incomplete unwrapped bundles and assistant content", a } } }) + +// Claude Code 2.1.280's restored-context turn after /compact (plugins#68): +// restored-file notes, Read calls and results, the environment, the model +// line, token and date, folded into one text block with no wrappers. Each +// fixed fragment is the reporter's literal text. +const restoredNote = (path) => "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." +const restoredRead = 'Called the Read tool with the following input: {"file_path":"/tmp/example.py"}' +const restoredResult = 'Result of calling the Read tool:\n1\timport os\n2\tprint("You are Claude Code, Anthropic\'s official CLI for Claude.")\n3\t# 中文 \\u0054' +const restoredEnvironment = "# Environment\nYou have been invoked in the following environment: \n - Primary working directory: /tmp\n - Is a git repository: true\n - Platform: darwin" +const restoredModel = "You are powered by the model named Opus 5.5. The exact model ID is claude-opus-5-5[1m]. Assistant knowledge cutoff is June 2026." +const restoredToken = "14831568 tokens left" +const restoredDate = "Today's date is 2026-10-10." +const restoredFixed = [ + "was read before the last conversation was summarized", + "Called the Read tool with the following input:", + "You have been invoked in the following environment:", + "You are powered by the model named", + "The exact model ID is", + "Assistant knowledge cutoff is", + "You are Claude Code", +] + +test("adapts Claude Code's complete restored-context turn after /compact (plugins#68)", async () => { + const { l, seen } = await loaded() + const notes = [restoredNote("/tmp/large.log"), restoredNote("/tmp/示例 data.json"), restoredNote("/tmp/third.txt")] + const adaptedNotes = [ + "Previously read file: /tmp/large.log. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it.", + "Previously read file: /tmp/示例 data.json. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it.", + "Previously read file: /tmp/third.txt. Its contents were omitted from the conversation summary because of length. Use Read tool if you need to access it.", + ] + const adaptedRead = 'Previously read file with these arguments: {"file_path":"/tmp/example.py"}' + const adaptedEnvironment = "# Runtime context\nThe session environment is: \n - Primary working directory: /tmp\n - Is a git repository: true\n - Platform: darwin" + const adaptedModel = "Current model name: Opus 5.5. Model ID: claude-opus-5-5[1m]. Model knowledge cutoff: June 2026." + const source = restoredResult.slice("Result of calling the Read tool:\n".length) + const cases = [ + // the reporter's shape: several notes, Read call and result, environment, model line, token, date + [[...notes, restoredRead, restoredResult, restoredEnvironment, restoredModel, restoredToken, restoredDate], + [...adaptedNotes, adaptedRead, "RESULT", adaptedEnvironment, adaptedModel, restoredToken, restoredDate]], + // a Read call first, its result in the same paragraph; no token marker + [[restoredRead + "\n" + restoredResult, notes[0], restoredEnvironment, restoredModel, restoredDate], + [adaptedRead + "\nRESULT", adaptedNotes[0], adaptedEnvironment, adaptedModel, restoredDate]], + // token marker without the environment + [[notes[0], restoredModel, restoredToken], [adaptedNotes[0], adaptedModel, restoredToken]], + ] + for (const [input, output] of cases) { + const text = input.join("\n\n") + for (const endpoint of [url, url + "/count_tokens"]) { + for (const role of ["system", "user"]) { + for (const content of [text, [{ type: "text", text, cache_control: { type: "ephemeral" } }, { type: "text", text: "Keep this block." }]]) { + const request = { system: droid, messages: [{ role, content }, { role: "user", content: "OK" }] } + await l.fetch(endpoint, { method: "POST", body: JSON.stringify(request) }) + const got = JSON.parse(seen.at(-1).body) + const out = typeof got.messages[0].content === "string" ? got.messages[0].content : got.messages[0].content[0].text + for (const phrase of restoredFixed) expect(out).not.toContain(phrase) + const parts = out.split("\n\n") + expect(parts.length).toBe(output.length) + for (const [i, want] of output.entries()) { + if (!want.includes("RESULT")) { + expect(parts[i]).toBe(want) + continue + } + const head = want.slice(0, want.indexOf("RESULT")) + "Result of calling the Read tool:\n" + expect(parts[i]).toStartWith(head) + const encoded = parts[i].slice(head.length) + expect(encoded).toStartWith("Tool output encoded as a JSON string.") + expect(JSON.parse(encoded.slice(encoded.indexOf("\n") + 1))).toBe(source) + } + const adapted = typeof content === "string" ? out : [{ ...content[0], text: out }, content[1]] + expect(got).toEqual({ ...request, messages: [{ role, content: adapted }, request.messages[1]] }) + const once = seen.at(-1).body + await l.fetch(endpoint, { method: "POST", body: once }) + expect(seen.at(-1).body).toBe(once) + } + } + } + } +}) + +test("preserves quoted, incomplete and hook-owned restored-context turns", async () => { + const { l, seen } = await loaded() + const note = restoredNote("/tmp/large.log") + const block = [note, restoredRead, restoredEnvironment, restoredModel, restoredToken].join("\n\n") + const values = [ + "Explain:\n" + block, + "> " + block, + block.replace("was read before the last conversation", "was read long before the last conversation"), + block.replace('{"file_path":"/tmp/example.py"}', "not JSON").replace(note + "\n\n", ""), + // no environment and no token marker: not the complete generated turn + [note, restoredRead, restoredModel, restoredDate].join("\n\n"), + [note, restoredEnvironment.replace("\n - Primary", "\nPrimary"), restoredModel].join("\n\n"), + // a hook owns what follows it, even a quoted environment + [note, "SessionStart:compact hook success: Keep my hook output.", restoredEnvironment, restoredToken].join("\n\n"), + [note, "SubagentStart hook additional context: Keep hook output.", restoredEnvironment].join("\n\n"), + ] + for (const text of values) { + for (const endpoint of [url, url + "/count_tokens"]) { + for (const role of ["system", "user"]) { + for (const content of [text, [{ type: "text", text }]]) { + const body = JSON.stringify({ system: droid, messages: [{ role, content }] }) + await l.fetch(endpoint, { method: "POST", body }) + expect(seen.at(-1).body).toBe(body) + } + } + } + } + const messages = [ + { role: "assistant", content: block }, + { role: "assistant", content: [{ type: "text", text: block }] }, + ] + const body = JSON.stringify({ system: droid, messages }) + await l.fetch(url, { method: "POST", body }) + expect(seen.at(-1).body).toBe(body) +})